ONRAMP-6068 — D2 (token & addressing scheme) + D4 (security decisions)
Written 2026-08-10 against main
24864a73a5for ONRAMP-6068. Code line numbers are stale; current facts live in the ONRAMP-7078 stories.
Scope: D2 and D4 only. D1 + D5 (inbound transport, vendor, ingestion architecture) and D3 (parse benchmark) are owned by other agents — referenced here as see D1 / see D3 and never re-decided.
Verified at: main @ 24864a73a5 (2026-08-10 20:26 UTC). Every path/line below was read at that commit. Research only — no repo file was modified.
Labels used throughout:
- [V] verified in repo at HEAD (path + line read)
- [I] inferred / domain knowledge, not provable from this repo
- [H] needs a human decision — I state a recommendation but do not have the authority
0. Verification ledger — what held, what drifted
Every claim I was handed, re-checked. Line numbers in the planning docs were mostly exact; four paths were wrong.
| Claim handed to me | Verdict | Actual at HEAD |
|---|---|---|
SECRET_KEY hardcoded literal at config.py:12 | [V] exact | config.py:12 — SECRET_KEY = "{redacted}" (a literal string in source) |
duplicated at docker/files/app-config/configtemplate.py:10 | [V] exact | confirmed |
| no env or SSM override anywhere | [V] confirmed | repo-wide grep: the only non-test consumer is app/api/utils/preview_token.py:23. No environ.get("SECRET_KEY"), no SSM read, no per-env branch. |
ORWidgetFastPassToken at app/api/widget/or_models.py:30-48 | [V] exact | confirmed, secrets.token_urlsafe(32) at app/api/widget/fast_pass_helper.py:34, TTL 60 min at :13 |
fast-pass "delete+commit BEFORE acting" at fast_pass_controller.py:163-165 | [V] exact lines, WRONG PATH | real path is app/api/portal/controllers/fast_pass_controller.py (not app/api/widget/). Referrer-Policy: no-referrer at :172. |
ORApiIdempotencyKey at app/api/idempotency/or_models.py:12-39 | [V] exact | confirmed |
preview_token.py re-checks every bound field, returns None on deviation | [V] exact | verify_preview_token at :31-72 |
transaction_id is the existing email→action correlator, unique | [V] confirmed | OREmailTracking.transaction_id at app/api/email_tracking/models/or_email_tracking.py:36, UniqueConstraint(...) at :24. Threaded through url_helper.py:167,187,195,205,215,223,237,246. |
From hardcoded to notifications@onramp.us in exactly 3 places | [V] exact, all three | app/api/utils/email/Email.py:554, :593, app/api/custom_email_templates/services/custom_email_template_service.py:1235 |
| per-org custom from-domains do not exist | [V] confirmed | no sending-identity, no configuration-set, no MAIL FROM anywhere in app/api. Sending identity lives entirely in the SES Lambda, outside this repo. |
OREmail.reply_to / OREmailJob.reply_to exist | [V] exact | app/api/email/models.py:51, app/api/email_jobs/models.py:18 — both Mapped[Internal[Optional[str]]], Text, nullable |
User.email_address has no unique constraint, ~:50 | [V] exact line 50 | email_address: Mapped[Confidential[str]] = mapped_column(Text, nullable=False, index=True) — index only |
app-level dup guard on (email, vendor_id, is_customer_user) ~:297-300 | [V] line 297 | app/api/user/services.py:297 — one line, .filter_by(email_address=email_address.lower(), vendor=vendor_id, is_customer_user=...) |
get_organization_user compares raw address ~:532 | [V] :529-536, comparison on :532 | User.email_address == email_address — no .lower(). Correct as described. |
nudge sets both cc_email and reply_to_email to the CSM :3136-3137 | [V] exact | app/api/task/services_old.py:3136-3137 |
no rate limiting anywhere in app/api | [V] confirmed | no Flask-Limiter, no SlowAPI, in app/api or pyproject.toml. Only hit is a comment at app/api/user/controllers/org_users_controller.py:183 explicitly delegating throttling to customer-api's SlowAPI. |
| inbound / SPF / DKIM / DMARC / receipt-rule machinery = none | [V] confirmed greenfield | exhaustive negative grep over app/ + infra/: single hit is the string _dmarc.example.com in a text-editor unit test. |
portal upload path has no allowlist / size cap / scanning, task_files_helper.py:11-44 | [V] confirmed, WRONG PATH | real path app/api/utils/task_files_helper.py (not app/api/task/helpers/). save_task_file at :11-44. And it is pinned by a committed test — see D4.5. |
daily_jobs/services.py:242 timedelta-zero bug | [V] exact line, WRONG PATH | app/api/project/daily_jobs/services.py:242 |
SPA router auto-consumes ?token= | [V] confirmed | app/ui-customer/router.js:244 (if (to.query.token && !authStore.isAuthenticated)) |
ORComment has no attachment column | [V] confirmed | app/api/comments/models/or_comment.py — 22 columns, none file-related |
| EasyCron registration list carries the real nudge/digest cadence | [V] FALSE — see D2.5 | the list at .agents/skills/backend-development/SKILL.md:98-118 carries URLs only, no schedules. Cadence is not derivable from this repo. |
D2 — Token & addressing scheme
D2.1 Decision: DB-backed opaque token, hashed at rest. Does NOT block on E3.
Verdict: DB-backed opaque random token. Ratifies the brief's going-in recommendation, with one deviation (store a hash, not the plaintext) and one substitution (token_hex, not token_urlsafe — see D2.4).
E3 is NOT a hard prerequisite. Stated plainly, as requested: nothing in this scheme reads current_app.config["SECRET_KEY"], signs with it, or verifies against it. The forgeability of SECRET_KEY [V] config.py:12 is therefore irrelevant to token integrity here, and W3 can proceed while E3 is still open.
That is the whole reason to reject signed-stateless. The counterfactual is worth stating so nobody re-litigates it: an itsdangerous token minted today is forgeable by anyone who has read the source tree — which includes every current and former engineer and anyone who has ever cloned the repo. A forged task_answer_option token is an unauthenticated write of an arbitrary answer to an arbitrary task in an arbitrary tenant. Signed-stateless is not "cheaper pending E3"; it is unshippable until E3 lands, and it would still need a DB row afterwards to enforce single-use. There is no version of this design where signing saves work.
E3 remains worth doing on its own merits — preview_token.py (/gateway preview + impersonation logins) is forgeable today, which is a live privilege-escalation path independent of this epic — but it should not be sequenced as a 6068 dependency. [H] Confirm E3 stays a standalone security ticket, not a W3 blocker.
Deviation from precedent: store token_hash, not token
Both in-repo precedents store the plaintext (ORWidgetFastPassToken.token [V] or_models.py:47; UserSession.session_token). I recommend not copying that here, and storing sha256(token).hexdigest() under a unique index instead.
The reason is a TTL difference, not a taste difference. Fast-pass tokens live 60 minutes [V] fast_pass_helper.py:13; these live days (D2.5). A live plaintext token in a table readable by anyone with prod-replica access is a working "answer this task as this customer" credential. That population is not small — the prod-db-investigation skill exists precisely because read-replica queries are routine.
Hashing costs nothing operationally: lookup is where token_hash = sha256(incoming), a single index probe. No secrets.compare_digest is needed and a reviewer will ask why — the answer is that the lookup is by full-preimage hash of a 192-bit secret, so there is no secret-dependent branch or partial-prefix comparison for a timing oracle to attack. compare_digest guards a comparison against a stored secret; an index probe on a hash is not that shape.
One constraint this creates, and it is easy to miss: hashing the token is pointless if the raw inbound message is persisted with its To:/Delivered-To: headers intact, because those headers contain the plaintext token. So either the inbound raw store redacts the recipient token, or hashing buys nothing for reply tokens. It still fully protects task_answer_option tokens, which never appear in any inbound message (nobody replies to a button) — and those are the numerous ones. Spec: redact the token from persisted inbound headers (replace with the token_hash), and treat the raw store as Internal[] regardless (D2.3).
What to copy from each precedent — and what not to
ORWidgetFastPassToken — copy the consumption discipline, reject three of its habits.
Copy: delete/mark-consumed and commit() BEFORE performing the action [V] app/api/portal/controllers/fast_pass_controller.py:163-165. This is the single most important line in the precedent. It means a crash between consume and act loses the action, never the single-use guarantee — the fail-safe direction. And Referrer-Policy: no-referrer on the response [V] :172, so the token cannot leak via Referer on the next navigation from the confirmation page.
Do not copy:
- Its mint-time
deleteof prior tokens [V]fast_pass_helper.py:24-29. Fast-pass can hold "at most one live token per user" because it is minted at widget render, seconds before use. Email cannot: nudge N+1 must not break the buttons in nudge N, which the customer may open first. Prior tokens must survive to their own expiry. - Its plaintext storage (above).
- Its email-in-the-URL habit —
build_fast_pass_urlputs&email=<addr>in the query string [V]fast_pass_helper.py:54, and the controller uses it as a second factor [V]fast_pass_controller.py:143. Do not import this. The token is already bound touser_idin the row; the address in the URL adds no security (an attacker holding the token holds the URL) and does add a PII leak into mail-client logs, proxy logs, andReferer. See D2.4.
ORApiIdempotencyKey — copy the replay shape, not the columns. [V] app/api/idempotency/or_models.py:12-39: reserve-before-execute, then complete-with-stored-response, so a retry replays rather than re-executes. Applied here: a second POST on a consumed token must render "you answered X on <date>" from the row, not 404 and not re-submit. Its request_hash column [V] :35 has no analogue — there is no caller-supplied body to fingerprint on a one-click confirm — so do not carry it over.
preview_token.py — copy the verification shape. [V] :31-72: re-check every bound field against the caller's independently-derived expectations, and return None (never a partial success, never an exception the caller might swallow) on any single deviation. Concretely for a token resolve: purpose matches the endpoint, vendor matches the host-derived vendor, task/step/element still exist and still belong to that vendor, expires_dts > now, consumed_dts IS NULL. Any one fails → one generic negative outcome. This shape is what makes the resolver auditable; the alternative (trusting the row's own scoping) silently loses the cross-tenant check.
D2.2 Table spec — or_email_action_token
Domain: new app/api/email_actions/ [V] confirmed greenfield (app/api/ holds email, email_jobs, email_notifications, email_opt_out, email_templates, email_tracking, custom_email_templates — no email_actions; and or_email_action* / or_inbound_email* appear nowhere in app/ or migrations/).
The CI gate governs this table even though it is never exposed
This is the fact that catches implementers out. The skill's own docstring says the gate fires for columns "on a table that is already exposed" — that description is stale. The live test test_every_column_on_orm_model_is_classified [V] app/api/agent/tests/test_sql_tool_classification_gate.py:114-200 walks ORBaseModel.__subclasses__() / ORStandardModel.__subclasses__() and asserts on every model, exposed or not: "Un-classified columns on any ORM model will fail CI regardless of whether the table is currently exposed" (:126-128). So every column below carries a marker.
Two further mechanics that decide the markers:
*_dtsis NOT auto-exposed.AUTO_EXPOSED_COLUMN_NAMES[V]app/api/agent/sql_tool_conventions.py:22-36containscreated_at/modified_at/archived_at/deleted_at— notcreated_dts,expires_dts,consumed_dts. This is exactly whyORWidgetFastPassTokenmarksexpires_dts: Mapped[Internal[datetime]]explicitly [V]or_models.py:48. Mirror it..*token.*matchesAUTO_DENIED_COLUMN_PATTERNS[V]sql_tool_conventions.py:44.Internal[]ontoken_hashis both correct and the only marker that passes without a signoff file.
No __sql_tool_policy__ and no PortalAccessible on either table. Rationale: a table of live authorization credentials has no business being agent-queryable at any scope, and adding PortalAccessible would force a CustomerOwner resolution it does not need. This matches both precedents exactly — neither ORWidgetFastPassToken nor ORApiIdempotencyKey declares a policy [V]. Consequence to state in the PR so nobody adds it later: no rls_policies/ file and no GRANT SELECT ... TO or_readonly in the migration (per the new-exposure checklist in the sql-tool-exposure skill, grants are a static list — omitting the grant is what keeps the table invisible to the read-only role).
Also do not add a mapper or DTO for this model. ORBaseModel.serialize() [V] app/api/base/or_models.py:41-44 returns every column unconditionally — a single careless .serialize() on this row emits the token hash and the full scoping. There is no legitimate API response containing an or_email_action_token row.
or_email_action_token
Inherits ORBaseModel directly (required: the CI gate walks direct subclasses only [V] :136-144).
| Column | Type | Null | Marker | Notes |
|---|---|---|---|---|
id | Integer PK, FetchedValue(), autoincrement | no | (auto-exposed) | precedent shape |
token_hash | Text | no | Internal[str] | sha256(token).hexdigest(), 64 chars. Unique index. Never store plaintext. |
purpose | Text | no | Internal[str] | task_answer_option | task_reply | comment_reply. String, not IntEnum — see D4.3. |
vendor_id | Integer FK or_vendors.id ondelete=CASCADE | no | VendorOwner[int] | single FK to or_vendors so auto-detection would suffice, but the marker documents tenancy on a security table. 0 is a real tenant — D4.3. |
user_id | Integer FK user.id ondelete=CASCADE | no | Internal[int] | the bound recipient. This is the authorization subject and the identity the answer is attributed to. NOT NULL — deliberately unlike UserMagicLinkMapping.user_id, which is nullable and is the reason that table can authenticate nothing. |
project_id | Integer FK or_projects.id ondelete=CASCADE | no | Internal[int] | denormalized from the task, so the resolver can cross-check tenancy without a join and so a project delete reaps tokens |
task_id | Integer FK or_tasks.id ondelete=CASCADE | yes | Internal[Optional[int]] | set for both task purposes; NULL for comment_reply |
step_id | Integer FK or_task_steps.id ondelete=CASCADE | yes | Internal[Optional[int]] | set for both task purposes |
element_id | Text | yes | Internal[Optional[str]] | FORM element uuid; NULL for legacy step types |
option_value | Text | yes | Internal[Optional[str]] | the flat-dict key (legacy) or option id (FORM), per PLAN §5.1. Set only for task_answer_option. May legitimately be "0" or "" — D4.3. |
comment_group_id | Integer FK or_comment_group.id ondelete=CASCADE | yes | Internal[Optional[int]] | comment_reply only. Binds to the group, not a comment — replies post into the thread, and the specific comment may be archived by the time the reply lands. |
mint_group_uuid | UUID | no | Internal[str] | one value per (email × step) mint batch. See "sibling invalidation" below — this is the column the brief's spec is missing. Indexed. |
email_transaction_id | UUID(as_uuid=False) | yes | Internal[Optional[str]] | the existing correlator, reused. No DB FK — see below. Indexed. |
expires_dts | DateTime(timezone=True) | no | Internal[datetime] | writable-until. Indexed (reaper + resolver). |
consumed_dts | DateTime(timezone=True) | yes | Internal[Optional[datetime]] | NULL = unconsumed. Set before acting. |
consumed_source | Text | yes | Internal[Optional[str]] | email_one_click | email_reply — feeds PLAN §5.4's answered_via / posted_via |
confirm_attempts | Integer, server_default="0" | no | Internal[int] | per-token attempt ceiling — D4.4 |
auto_replied_dts | DateTime(timezone=True) | yes | Internal[Optional[datetime]] | one-auto-reply-per-token ledger — D4.1 |
created_dts | DateTime(timezone=True), server_default=text("now()") | no | Internal[datetime] |
__table_args__:
Index("ix_or_email_action_token_hash", "token_hash", unique=True)
Index("ix_or_email_action_token_mint_group", "mint_group_uuid")
Index("ix_or_email_action_token_vendor_user_task", "vendor_id", "user_id", "task_id")
Index("ix_or_email_action_token_expires", "expires_dts")
Index("ix_or_email_action_token_transaction", "email_transaction_id")No standalone vendor_id index — the composite leads with it, matching the reasoning already written into ORApiIdempotencyKey [V] or_models.py:26-27.
Why email_transaction_id carries no DB FK — a deliberate deviation from OREmail.
OREmail.transaction_id does have a real FK to or_email_tracking.transaction_id with ondelete="SET NULL" [V] app/api/email/models.py:39-48. Do not copy it here, for a sequencing reason:
The tracking row is created inside __build_email [V] app/api/utils/email/Email.py:527 (EmailTrackingCreateService().create_or_ignore(...)) — i.e. at render time. But a token must exist before render, because the token is what gets rendered into the body and the Reply-To. So at token-insert time the tracking row does not yet exist, and a hard FK would fail the insert.
Worse, the tracking row is best-effort in two ways: it is skipped entirely when vendor_id is None [V] Email.py:514-521, and any failure is caught and logged rather than raised [V] Email.py:534-540. A hard FK converts an observability failure into a token-mint failure — the customer receives an email whose buttons do not work. Plain indexed column, nullable, populated best-effort.
The sequencing that does work — and it is available today with no change to Email.py: __resolve_transaction_id memoizes onto the instance and reuses an existing value (allow_existing=True) [V] Email.py:254-263. So a sender can set email_util.transaction_id = str(uuid4()) before build, mint tokens against that value, and the build path will reuse the same id rather than generating a fresh one. [V] This is the only correlation-safe ordering; deriving the transaction id after render is impossible.
Sibling invalidation — the gap in the going-in spec
PLAN §5.2 says "one row per option button". It does not say what happens when a recipient clicks Yes and then clicks No. With per-row single-use and nothing else, both succeed: the second click either overwrites an answer on an already-completed task or 500s inside the completion gate.
mint_group_uuid closes it. Consumption is group-scoped: consuming any row in a mint_group_uuid stamps consumed_dts on every row in the group in the same transaction, before acting. A subsequent click on a sibling then finds a consumed row, and — via the ORApiIdempotencyKey shape — renders "you already answered Yes on 12 Aug" instead of a dead end. This is also what makes the idempotency precedent actually applicable: without a group key you cannot find the sibling that recorded the answer.
A 6-option dropdown for 5 recipients mints 30 rows in 5 groups. That is the intended volume; do not try to collapse it.
or_inbound_email — the security-relevant half
Transport and drain semantics are see D1/D5. D4 owns the verdict and audit columns, so the shape is specified here to keep them from being invented twice.
| Column | Type | Null | Marker | Notes |
|---|---|---|---|---|
id | Integer PK | no | (auto) | |
provider_message_id | Text | yes | Internal[Optional[str]] | unique — the idempotency key for redelivery (see D1) |
token_hash | Text | yes | Internal[Optional[str]] | resolved token; NULL when the address matched nothing |
vendor_id | Integer FK or_vendors.id | yes | VendorOwner[Optional[int]] | NULL until a token resolves — an unresolvable inbound has no tenant |
from_address | Text | no | Confidential[str] | the claimed sender. Confirmation signal only — D4.2. |
spf_verdict / dkim_verdict / dmarc_verdict / dmarc_policy / spam_verdict / virus_verdict | Text | yes | Internal[Optional[str]] | verbatim provider verdicts; NULL means absent, which is not a pass — D4.1 |
disposition | Text | no | Internal[str] | accepted | dropped_verdict | dropped_virus | dropped_spam | held_verdict | held_sender_mismatch | dropped_no_token | dropped_expired | autoresponder |
raw_object_key | Text | yes | Internal[Optional[str]] | S3 key for the raw MIME. Token redacted from headers before persisting (D2.1). |
parsed_text | Text | yes | Confidential[Optional[str]] | stripped reply body. Confidential, not Public — an inbound body is unvalidated third-party content; it must not be agent-queryable before it has been accepted and posted through the normal path. |
received_dts | DateTime(timezone=True) | no | Internal[datetime] | indexed — backs the per-sender ceiling in D4.4 |
One exposure asymmetry worth stating explicitly, because it is easy to get backwards: ORComment.message_plain is Mapped[Public[str]] [V] app/api/comments/models/or_comment.py:76. So once an inbound reply is accepted and posted as a comment, its text is legitimately agent-queryable — identical to a portal-posted comment, no new exposure, fine. What must not happen is the raw inbound message (full headers, other recipients, quoted history, the token) landing in that column. Post the stripped body only; the raw stays in or_inbound_email / S3 under Internal[].
D2.3 Address format
Recommendation
r-<token>@<inbound_email_domain> e.g. r-4f3a...c9@reply.onramp.uswith token = secrets.token_hex(24) — 48 lowercase hex chars, 192 bits.
Two deviations from the brief's reply+<token>@<subdomain>, both for concrete failure modes:
1. - prefix, not +. +-subaddressing is stripped or rewritten by some corporate mail systems and gateways [I], and a stripped tag yields an address that resolves to nothing — the epic's must-not-happen outcome (a silently dropped customer answer). A hyphen is an ordinary local-part character with no special handling anywhere. Keeping a short fixed prefix (rather than making the whole local part the token) is still worth it: it makes the address greppable in logs, and it gives a cheap scheme-version escape hatch (r2-) if the token format ever changes. Validate with a strict anchored regex — ^r-([0-9a-f]{48})$ — and drop anything else before any DB access.
2. token_hex, not token_urlsafe. This one is not cosmetic. token_urlsafe(32) yields base64url — a mixed-case alphabet. RFC 5321 §2.4 requires local-parts to be treated as case-sensitive but explicitly discourages relying on that ("impedes interoperability and is discouraged") [I], and real-world hops do normalize case. A token that loses its case in transit is unresolvable, and the failure is silent. token_hex is single-case, contains no + or / (either of which would break local-part parsing), and 24 bytes still gives 192 bits — vastly beyond brute force at any conceivable request rate.
This is a stated deviation from the token_urlsafe(32) precedent [V] fast_pass_helper.py:34. [H] A reviewer either accepts the deviation or explicitly accepts the case-fragility risk; do not let it pass unremarked.
Length check: r- (2) + 48 + @ + reply.onramp.us (15) = 66 octets total, local part 50 octets. Under the RFC 5321 64-octet local-part limit and the 254-octet address limit, with headroom for the longest env prefix (gdpr-reply.onramp.us → 71). [V] arithmetic; [I] the limits.
Subdomain: dedicated, receive-only, per-env, single-domain-for-all-orgs
Single inbound domain for all orgs — recommended explicitly, as asked. There is no foundation for anything else: From is hardcoded to notifications@onramp.us in all three send paths [V] Email.py:554, :593, custom_email_template_service.py:1235, and no per-org sending domain exists anywhere in the repo [V]. Per-org inbound addressing would require per-org DNS, per-org verified identities, and per-org DKIM — a project an order of magnitude larger than this epic. Tenancy comes from the token row's vendor_id, which is strictly stronger than domain-based tenancy anyway (a domain can be spoofed; a 192-bit row key cannot).
Per-env domains follow an existing repo convention. {env-prefix}-{service}.onramp.us, established by SCIM [V] app/api/platform_integrations/routes.py:445-452: dev-scim / demo-scim / gdpr-scim / bare scim for prod. So:
ENVIRONMENT_NAME | inbound_email_domain |
|---|---|
prod | reply.onramp.us |
gdpr-prod | gdpr-reply.onramp.us |
stage | stage-reply.onramp.us |
demo | demo-reply.onramp.us |
dev | dev-reply.onramp.us |
localdev | null — feature off, no minting |
This goes in the config map as one key per env block, not an if-ladder. app/config/environments.yaml already has exactly the seven blocks needed [V] defaults(21) / localdev(96) / dev(97) / stage(108) / demo(109) / prod(110) / gdpr-prod(115), read via get_env_config(). Add inbound_email_domain to defaults as null and override per env. Do not copy get_sso_config's pattern [V] platform_integrations/routes.py:445-452 — it is a hardcoded if "dev" in env ladder, which is both the if env == shape CLAUDE.md's "derive, don't configure" section bans and substring-fragile ("dev" in "localdev" is True, so localdev silently resolves to the dev SCIM URL). null in defaults also gives the fail-closed default the same section asks for: an unconfigured env cannot mint a reply address at all.
The webhook secret goes to SSM, not the map: /onramp/{env}/inbound_email/webhook_hmac_secret, matching the verified prefix convention /onramp/{env}/docusign [V] app/api/integrations/docusign/constants.py:54. Copy secrets.py wholesale — accessor [V] :36-46, 60s memo with the "never cache an empty read" rule [V] :64-93, and the _NO_AWS_RUNTIME_ERRORS local escape [V] :33 that is the fix for the dev-config-env-name-overload trap.
Two existing credential env vars (ONRAMP_EDGE_SHARED_SECRET [V] middleware/edge_gateway.py:67, EASYCRON_SHARED_SECRET [V] utils/cron_auth.py:45) are not a precedent to copy — both are injected by infra at the container boundary and documented as such (edge_gateway.py:63-66: "A credential for the running container… not configuration"). An app-layer integration secret goes to SSM.
Sending reputation: the question dissolves if the domain is receive-only
[H] Ratify this, then it is settled: auto-replies continue to send From notifications@onramp.us, with Reply-To pointing at the tokenized address. The inbound subdomain is never a sending identity.
With that constraint, the reputation question has a clean answer:
- Adding MX records to a subdomain has no effect on the parent domain's SPF, DKIM, or the
notifications@onramp.ussending identity — receiving and sending are independent [I]. - SES reputation (bounce/complaint) that drives account-level sending pauses is tracked at the account level, not per domain identity [I] — so a new domain could not isolate reputation even if we wanted it to, and cannot damage it by existing.
- We never verify a new sending identity, never publish a second DKIM selector, and never create a subdomain that inherits
_dmarc.onramp.uspolicy as a sender [I].
The risk this avoids is real and specific: putting MX on the apex onramp.us would mean editing apex DNS that currently serves Webflow with DNS at GoDaddy (per the onramp-hosting-dns-topology memory) — a change with blast radius on the marketing site and any existing apex mail routing, for zero benefit. Use a subdomain.
I cannot verify the SES sending identity or configuration-set setup from this repo — there is none [V]: no configuration_set, no MAIL FROM, no verified-identity call anywhere in app/api; the only SES calls are account-level get_send_quota / get_send_statistics [V] app/api/admin/services/email_monitoring_service.py:364-374. The identity lives in the SES-sending Lambda's AWS account, outside this repo. [H] Someone with AWS console access must confirm the above against the real account before DNS work starts — this is part of the brief's "what changes are needed outside this repo" deliverable.
EU data residency splits the inbound path — not previously flagged
gdpr-prod is an eu-west-1 data-residency tenant [V] app/config/environments.yaml:113 ("us. inference profiles can't be invoked from eu-west-1") and [V] app/api/utils/crm_broker.py:15-16 ("gdpr-prod (EU) maps to its OWN in-region broker — a dedicated eu-west-1 stack"). PRODUCTION_ENV_NAMES = frozenset({"prod", "gdpr-prod"}) [V] app/api/utils/env_config.py:78.
An inbound customer email body is customer personal data. Receiving EU orgs' replies in a US region would route that data through us-east-1 — a residency violation, and the repo's established answer to exactly this problem is a dedicated in-region stack (the CRM broker precedent). So gdpr-prod needs its own inbound domain and its own in-region receiving path. That is already satisfied by the per-env config-map key above, which is a further reason the domain must not be a module constant. [H] Confirm with whoever owns the GDPR commitments; it is a scope input to D1's vendor choice (an inbound vendor must offer EU-region receiving, and SES inbound receipt rules are region-limited [I]).
What is never in the address — spec obeys this
- No email address. The recipient is
user_idon the row. (Contrastbuild_fast_pass_url[V]fast_pass_helper.py:54, which does put&email=in the URL — deliberately not copied.) - No entity id, raw or hashid. Not
task_id, notstep_id, notproject_id. And specifically not a hashid:hashids = Hashids(min_length=16)[V]app/api/utils/api_helpers.py:11is constructed with no salt, soencode_idis reversible and forgeable by anyone with the library and zero secret. Hashids are obfuscation, not authorization, and must never carry scoping in an unauthenticated address. - No vendor identifier, no org name, no project name.
Everything scoping-related lives in the row; the address carries exactly one thing, a 192-bit random. [V] the spec above contains no other field.
D2.4 Expiry, rotation, lifecycle
The cadence question cannot be answered from this repo — correcting the brief
The brief instructs: "get the real nudge/digest cadence from the EasyCron registration list in the backend-development skill rather than guessing." That list does not contain schedules. [V] .agents/skills/backend-development/SKILL.md:98-118 is a list of 19 URLs with a coordination procedure; no cron expressions, no frequencies. The schedules live in the EasyCron console, outside the repo.
What the repo does support [V]:
- Manual nudge is ad-hoc and human-triggered —
POST /tasks/nudge_email→send_task_nudge_emails[V]app/api/task/services_old.py:3092, rendered and sent inline. No schedule at all. - Automated re-engagement is a daily batch —
/api/agent/re_engagement/cron/run_daily_batch(name + endpoint), with thresholdsOVERDUE_DAYS_THRESHOLD = 2,ACTIVE_MEMBER_DAYS_THRESHOLD = 5,UNREPLIED_COMMENTS_LOOKBACK_DAYS = 30[V]app/api/agent/dtos/re_engagement_dtos.py:8-10. - Digests are enqueued rendered and drained on a UTC-hour match —
OREmailJob.programmed_timedefaults to09:00:00[V]app/api/email_jobs/models.py:15; the drain selectsfunc.extract("hour", OREmailJob.programmed_time) == datetime.now(timezone.utc).hour[V]app/api/email_jobs/services.py:20-22. So mint→delivery latency is hours up to ~24h, confirming PLAN §5.6 and §6.
So the upper bound on repeat cadence is daily. [H] Someone with EasyCron console access should confirm the actual cron expressions before these TTLs are final — but the numbers below are safe for any cadence ≥ daily.
TTLs
| Purpose | Writable TTL | Rationale |
|---|---|---|
task_answer_option | 7 days | Not a new number in the system — project invitations already use 7 days (project/services.py:1268, per discovery/tokens-auth.md). Comfortably exceeds a daily cadence, so a Friday email opened Monday still works. Emphatically not fast-pass's 60 minutes [V] fast_pass_helper.py:13 — that TTL is sized for an interactive widget hand-off, not for a human reading email. |
task_reply | 30 days | Anchored on an existing in-repo judgement that 30 days is the window in which a thread is still live: UNREPLIED_COMMENTS_LOOKBACK_DAYS = 30 [V] re_engagement_dtos.py:10. |
comment_reply | 30 days | same |
| Digest-minted tokens | +1 day on top | mint ≠ send; the enqueue→drain gap is up to ~24h [V] email_jobs/services.py:20-22. Compute expires_dts from mint and add the digest grace, or the token dies in the queue. |
[H] The 30-day writable window on an unauthenticated write path is the single number most worth a human's attention. The mitigations are real — the write is single-use, bound to one user and one step, and requires an inbound message that DKIM-aligns to the recipient's own domain — but the residual exposure is a forwarded email thread. 14 days is the conservative alternative; I recommend 30 and flag it rather than quietly picking the safer number, because a reply token that expires before the customer replies produces exactly the silent-drop the epic forbids.
Does a reply token die when the task completes? No — ratifying the going-in recommendation, with the state machine made explicit
The brief's recommendation ("stays resolvable so a late reply gets an informative auto-reply, but stops being writable") is right, and it survives contact with the schema. The important consequence is that "resolvable" and "writable" must be two separate checks, not one consumed_dts IS NULL test — otherwise an implementer will collapse them and the late reply gets a silent drop.
| Row state | Resolvable? | Writable? | Behaviour |
|---|---|---|---|
consumed_dts IS NULL, expires_dts > now, entity open | yes | yes | perform the action |
consumed_dts IS NOT NULL | yes | no | render/auto-reply the recorded answer (idempotency shape), incl. via a mint_group_uuid sibling |
expires_dts <= now | yes | no | auto-reply "this link expired", portal magic link |
| entity completed/archived/deleted since mint | yes | no | auto-reply "already completed", portal link |
token_hash matches nothing | no | no | disposition = dropped_no_token, no auto-reply (D4.1) |
Reaping, not expiry, is what makes "stays resolvable" bounded. Recommend retaining rows for 180 days past expires_dts, then hard-deleting. Note two things: (a) there is no reaper precedent in the repo — fast-pass replaces at mint, magic links delete at consume — so this is net-new; (b) a new reaper endpoint means a new EasyCron registration, which carries the EASYCRON_URL label + per-environment job-creation procedure [V] .agents/skills/backend-development/SKILL.md:120-130. Recommendation: fold the reap into an existing daily job rather than registering a new endpoint, to avoid paying that coordination cost for a housekeeping sweep. [H] Which existing job is a call for whoever owns the cron inventory.
No rotation mechanism, and that is the right answer. Tokens are not rotated; they are single-use and short-lived, and a fresh mint per email supersedes nothing (prior tokens must stay live — D2.1). The only "rotation" event is the reap. There is no shared key to rotate, which is precisely the property that decouples this from E3.
D4 — Security decisions
D4.1 SPF / DKIM / DMARC verdict handling
Frame this correctly or the policy comes out wrong: the token is the authorization; the verdicts are defense-in-depth. An attacker who does not hold a token cannot do anything regardless of verdicts. An attacker who does hold a token does not need to forge the sender, because the recommended matching policy (D4.2) treats the sender as confirmation, not credential. So verdicts exist to catch a narrow case — a leaked token replayed from a forged sender — and to keep us from processing malware and spam. They must never be the reason a legitimate reply is dropped.
| Verdict combination | Action | Auto-reply? |
|---|---|---|
virus_verdict = FAIL | hard drop, dropped_virus | no |
spam_verdict = FAIL | hard drop, dropped_spam | no — replying confirms a live address |
dmarc_verdict = FAIL and dmarc_policy in (REJECT, QUARANTINE) | hard drop, dropped_verdict | no — the sender's own domain told us to reject; replying is backscatter to a probably-forged address |
dmarc_verdict = FAIL and dmarc_policy = NONE | hold, held_verdict | no to sender; notify the org actor |
dkim_verdict = PASS, spf_verdict = FAIL | ACCEPT | normal |
dkim_verdict = FAIL, spf_verdict = PASS, DMARC pass | ACCEPT | normal |
| both SPF and DKIM fail (DMARC cannot pass) | hold, held_verdict | no to sender; notify org actor |
any verdict GRAY / PROCESSING_FAILED | hold | no |
| any verdict field absent/NULL | hold — absent is not a pass | no |
The dkim=PASS, spf=FAIL → ACCEPT row is the most important line in this table. SPF fails routinely on legitimate forwarding (the forwarder's IP is not in the original domain's SPF record) while DKIM signatures survive forwarding intact [I]. A naive "require SPF pass" implementation silently drops every forwarded customer reply — which is precisely the epic's stated must-not-happen. Anyone reviewing the ingestion code should look for this specific mistake first.
"Hold" needs a real home, and the CSM-review surface does not exist. So v1 hold = persist the or_inbound_email row with disposition = held_*, do not write the answer, and notify the task's org-side actor internally — never auto-reply to the sender, because on a DMARC failure the From may be forged and a reply is backscatter at a victim. This reuses the machinery PLAN Q1 already commits to building ("post as comment + notify the acting user"), so it is reuse, not new surface. [H] Confirm that's an acceptable v1 (versus building a review queue).
Auto-reply suppression — a required ledger, not a nicety
RFC 3834 shape [I]; none of this exists today [V] (no inbound anything).
Never auto-reply when:
- any verdict failed (above);
Auto-Submitted:is present and notno;Precedence: bulk | list | junk, orList-Id/List-Unsubscribepresent;X-Auto-Response-Suppresspresent;- envelope Return-Path is null (
<>); auto_replied_dts IS NOT NULLon the token — one auto-reply per token, ever. This is the loop-breaker: two autoresponders facing each other is the classic mail-loop, and with no rate limiting anywhere [V] the DB column is the only brake available.- the contact is unsubscribed —
unsubscribed_users[V]app/api/email_opt_out/models.py:16.
[H] The unsubscribe interaction needs a product call. The opt-out copy promises "You will still receive authentication-related emails" [V] app/api/email_opt_out/services.py:~76; an answer confirmation is not authentication. Recommendation: suppress the confirmation but still record the answer — never punish the customer's action because of a mail preference. That asymmetry (write succeeds, confirmation silent) needs to be a deliberate, documented choice, not an accident.
Auto-replies send From notifications@onramp.us with Reply-To = the same token address, so a follow-up still lands (D2.3).
D4.2 Sender-address-to-contact matching
The verified problem
User.email_addressisMapped[Confidential[str]] = mapped_column(Text, nullable=False, index=True)— index, no unique constraint [V]app/api/user/models.py:50.- The only uniqueness guard is app-level, on
(email.lower(), vendor, is_customer_user)[V]app/api/user/services.py:297. So one address legitimately exists as a vendor user and a customer user within one org, and across every org. - Normalization is genuinely inconsistent:
services.py:297lowercases;get_organization_user[V]app/api/user/services.py:532compares raw (User.email_address == email_address, no.lower()); the neighbouring:517-521lowercases. Two functions in the same class disagree — the "asymmetric sibling functions" class from themocked-helper-hides-a-broken-fixmemory.
Consequence: a global email→user lookup on the inbound path is not just ambiguous, it is unsafe. It can return a row in the wrong tenant, or the vendor-user twin of a customer contact, and the ambiguity is invisible in local testing (one seeded org).
Recommendation ratified, with the ordering made explicit
Match the token's bound user_id. Treat the sender address as a confirmation signal, never a lookup key. The evaluation is unambiguous — this is correct, and it is correct for a stronger reason than the brief gives: the token row's user_id is NOT NULL and vendor-scoped by construction (D2.2), so there is nothing to look up. The identity is already decided at mint time by an authenticated org user's action. Introducing an address lookup would replace a strong binding with a weak one.
The ordering matters and should be written into the resolver:
- Resolve
token_hash→ row. No row →dropped_no_token, no auto-reply, log only. Never fall back to an address lookup. - Load
Userby the row'suser_id; re-verifyvendor == row.vendor_id,is_active,is_customer_user— thepreview_token.pyre-check-every-bound-field shape [V]:31-72. - Then compare the inbound
Fromto that user's address, both.strip().lower(). This is a confirmation check on an already-decided identity, and it is the one place a canonical normalizer must be used.
[H] Introduce one canonical normalize_email_address() and route this path through it. Given services.py:297 and :532 already disagree [V], a fourth ad-hoc .lower() inline is how this class of bug propagates. Fixing the existing two call sites is out of scope for 6068 (it would change login behaviour), but the new path must not add a fifth variant.
Alternate-address policy
The realistic case is mundane: the contact was invited at jane@example.com and replies from jane.doe@example.com or her phone's alias.
Recommendation: hold for review, scoped by domain — do not allowlist, do not silently reject.
| Sender vs token's user | Action |
|---|---|
| exact match (normalized) | accept, write the answer |
| different local part, same domain, verdicts pass | hold → held_sender_mismatch; notify the org actor with both addresses; do not write |
| different domain | hold → held_sender_mismatch; notify org actor; do not write |
| verdicts failed | already dropped/held by D4.1 — verdicts are evaluated first |
Rejected alternatives, with reasons:
- Accept any sender if the token is valid. Tempting (the token is the authorization) and defensible in isolation, but it makes a forwarded email thread a full write primitive with no second signal, and it destroys attribution: the answer would be recorded as Jane's when it came from her colleague. Attribution correctness is a product requirement here, not just a security one.
- A per-user alternate-address allowlist. New table, new UI, new admin surface — and no evidence yet that the volume justifies it. Hold-for-review generates that evidence for free. Revisit if the held-mismatch rate is material.
- Silent reject. The epic's whole premise is that a customer reply must never vanish.
[H] "Notify the org actor" is the load-bearing dependency — it reuses PLAN Q1's path, so 6073 must build it, and it should be built once for D4.1 holds, D4.2 holds, and Q1's not-an-answer replies.
D4.3 vendor_id = 0, and the same truthiness class elsewhere in this spec
Binding, stated here so implementers inherit it: vendor_id = 0 is a legitimate tenant — the OnRamp self-tenant in prod/stage/demo/eu and the local golden seed [V] .claude/rules/python.md. Any if not vendor_id: on the inbound path is a bug. Use is None. Resolve the platform tenant via get_platform_tenant_vendor_id() (backed by platform_tenant_vendor_id in the config map — and note dev overrides it to 1 [V] app/config/environments.yaml:107), never a literal. The CI sentinel app/api/agent/tests/test_no_vendor_zero_regression.py fails the build on either anti-pattern [V] rule text.
Local testing does not catch this — local flows run as the seeded customer org, so a boundary test must pin the fixture to 0 explicitly; None does not catch it.
I was asked to check whether the same truthiness class bites any other field in my spec. It does, in three places, and one of them is not an id:
option_value— the real one. ASINGLE_SELECTION/DROP_DOWNoption key, or aYES_NOvalue, can legitimately be the string"0"or"", both falsy.if not option_value: raiserejects a valid customer answer, and the failure is data-dependent — it appears only for orgs that happen to have authored an option keyed"0". Useis None. This is the same shape as the vendor-0 rule on a non-id field, and it is why the column is nullable-with-explicit-None rather than defaulted to"".purposemust be a string enum, not anIntEnum. AnIntEnumwhose first member is0is falsy, soif not token.purposewould treat a valid purpose as missing. StoringText(D2.2) makes the bug unrepresentable — the "make the interface say it" preference over writing a rule about it.Any
timedeltaTTL offset.timedelta(0)is falsy. This is not hypothetical in this codebase: it is the exact live bug at [V]app/api/project/daily_jobs/services.py:242—(date_time - time_offset).time() if time_offset else date_time, which assigns a fulldatetimeinto aTimecolumn for every zero-offset timezone (PLAN §5.3(a)). If any TTL or grace period is expressed as atimedeltain config, guard withis None.
Datetime columns (expires_dts, consumed_dts, auto_replied_dts) are safe under truthiness in Python 3.12, but the is None / is not None form is what the codebase reads as intentional — use it.
D4.4 Abuse surface and rate limiting
Confirmed: there is no rate limiting anywhere in app/api. [V] No Flask-Limiter, no SlowAPI, no in-app throttle, in the source or pyproject.toml. The only mention is a comment explicitly delegating throttling to customer-api's own SlowAPI [V] app/api/user/controllers/org_users_controller.py:183.
And there is no shared store to build one on. [V] Flask-Caching==2.4.1 is a dependency (pyproject.toml:34) but CACHE_TYPE is set to "null" [V] app/api/__init__.py:375 with a second Cache(...) on FileSystemCache [V] :379-382 — per-pod, not shared. No Redis, no memcached, no ElastiCache. So a correct distributed limiter is not a small change; it is new infrastructure.
Verdict: ingestion does not need a general-purpose rate limiter, and adding one here would be the wrong project. The threat model does not call for it:
- The inbound webhook is signature-authenticated (HMAC we define for SES→Lambda, or the vendor's — see D1/D5). Unauthenticated callers never reach any logic, following the DocuSign discipline [V]
app/api/integrations/docusign/routes.py:83-107: raw body captured pre-parse, reject without a signature header, and read the HMAC keys only after a signature is present so strangers cannot drive SSM traffic. That last point is the load-bearing one and is easy to lose in a refactor. - The one-click endpoints are token-bearing. 192 bits is not brute-forceable at any request rate; a limiter buys nothing against guessing.
What is needed are three bounded counters, all DB-backed, all cheap, none requiring new infrastructure:
confirm_attemptsper token (column in D2.2) — hard-stop after 10. Bounds a loop hammering one confirmation URL.auto_replied_dtsper token (D4.1) — the mail-loop breaker. Not optional.- Per-sender-address daily ceiling — count
or_inbound_emailrows for afrom_addressin the last 24h (thereceived_dtsindex backs it); above 50, persist withdisposition = autoresponderand process nothing. Catches a misconfigured autoresponder or a compromised mailbox.
Where a real limiter belongs, if one is ever wanted: the edge, not the app. [H] Prod fronting is a Duplo ELB → Caddy, and the prod Caddy vhosts are not in this repo (per the onramp-hosting-dns-topology memory) — so an edge limiter is a change owned outside this repo, and that ownership question belongs in the brief's "outside this repo" deliverable alongside MX/DNS.
New finding: the edge gateway blocks inbound webhooks on PR previews
Not mentioned in the brief or PLAN, and it will surface as a mysterious 403 during 6073 development.
enforce_edge_secret is registered as the first before_request handler, and when a secret is configured, "No path is exempt" [V] app/api/middleware/edge_gateway.py:22-24, 98-120, 144. On PR previews (EDGE_FRONTED_CONFIG_MODE = "Preview" [V] :71) the app refuses to boot without the secret [V] :130-140. An external provider POSTing to /api/inbound-email cannot inject X-Onramp-Edge-Secret, so every inbound webhook to a PR preview is 403'd before reaching a route.
Consequence: inbound email cannot be exercised on PR previews. The path is dev.onramp.us, which is explicitly not edge-fronted ("Local, dev, stage and prod are not fronted by this edge" [V] :28-30). This aligns with the third-party-integration-lessons memory (exercise the real vendor sandbox on a deployed env early) and with the docusign-dev-env-setup-runbook — DocuSign's webhook lives under the same constraint today, which is evidence it is survivable rather than a blocker. Plan the vendor sandbox against dev.onramp.us from day one; do not budget for preview-based webhook testing.
D4.5 Attachment policy
Verified state of the portal upload path — worse than "no policy"
[V] save_task_file at app/api/utils/task_files_helper.py:11-44 (note the path correction). No content-type allowlist, no per-file size cap, no per-request file count cap, no scanning. MAX_CONTENT_LENGTH is not set anywhere [V] — Flask has no global request-body cap; the only mentions are docstrings discussing its absence.
And the absence is pinned by a committed test, which makes it a documented decision rather than an oversight: test_save_task_file_does_not_enforce_accepted_file_types [V] app/api/utils/tests/test_task_files_helper_accepted_types.py:19-31 asserts that malware.exe is accepted and stored. So PLAN Q13's "attachment limits are NET-NEW policy" is correct, and stronger than stated — any limit added will break that test, and the test's name is the review conversation.
A pre-existing cross-tenant overwrite on the S3 path — must be fixed before inbound accepts attachments
While verifying the above I found an asymmetry between the two branches of save_task_file [V]:
- Local-disk branch (
:38) saves underunique_filename=make_unique(filename)— 8 hex chars of uuid4 prefixed [V]app/api/utils/fileSave.py:12-14. - S3 branch (
:27, :30, :33) uses the rawfilename—upload_file_to_s3(filename, ...)andget_file_url(filename).make_uniqueis computed at:22and then never used on this branch.
upload_file_to_s3 keys objects as f"{sub_folder}/{filename}" [V] app/api/integrations/image_upload/amazons3.py:21 — a flat, global, non-tenant-scoped namespace, written with put_object (overwrite, no conditional). So on the S3 path (offload_task_files_to_s3 — the deployed configuration), two uploads with the same filename from different tenants collide, and the second silently overwrites the first. The stored answer is a URL to that shared key [V] task_files_helper.py:30.
Today the attacker must be an authenticated portal user who can guess a filename. Accepting attachments from unauthenticated inbound email hands filename choice to anyone holding a reply token — invoice.pdf, contract.pdf, signed.pdf are not hard to guess. This turns a latent collision bug into a cross-tenant file-overwrite and disclosure primitive.
[H] This is my top escalation. It is a pre-existing bug, it is not 6068's to fix, and 6073 must not ship attachments until it is fixed — file it now as a standalone security bug ("S3 task-file uploads use the caller-supplied filename as a global key"; fix = use unique_filename on the S3 branch and prefix the key with the vendor id). This is exactly the "fix the class, not the instance" case from CLAUDE.md: the class fix is tenant-prefixed, uniquified keys for all uploads, not a special case for the email path.
Proposed limits — a starting position for ratification
[H] Every number below is a proposal for a human to ratify. They are deliberately tighter than the portal's (which is no policy at all), because an unauthenticated inbound sender is a materially larger exposure than a logged-in upload — and because a limit is easy to loosen and hard to tighten once customers rely on it.
Handling branches on token purpose — per PLAN Q2 (resolved 2026-08-10), comment attachments are a no-go (no model exists [V] or_comment.py has no file column), while FILE_UPLOAD task answers do accept them (save_task_file writes an S3 URL string into action_response). PLAN Q2's own warning applies: this must not become a global rule.
| Token purpose | Attachments |
|---|---|
task_reply where the target step is FILE_UPLOAD | accepted, under the limits below |
task_reply, any other step type | stripped; text answer recorded; auto-reply notes the attachment was not kept, with a portal link |
comment_reply | stripped; comment posted with text only; same auto-reply (PLAN Q2's "attachment over limit" row, generalized) |
task_answer_option | N/A — no inbound path |
| Limit | Proposed | Reasoning |
|---|---|---|
| Max files per inbound message | 5 | mirrors _MAX_FORM_FILE_FIELDS = 10 [V] app/api/agent/helpers/portal_step_family.py:83 at half, since one step is being answered |
| Max size per file | 10 MB | comfortably covers scans and photos; small enough to bound a single message |
| Max total per message | 25 MB | below the ~30–40 MB most providers accept anyway [I], so we reject rather than truncate |
| Content-type allowlist | pdf, png, jpeg, gif, webp, csv, txt, docx, xlsx, pptx | the onboarding-document reality. Allowlist, never denylist — fail-closed per CLAUDE.md |
| Type determination | sniff magic bytes; require agreement with both the declared MIME type and the extension. Disagreement → reject | the declared type and the extension are both attacker-controlled on this path |
| Executables/archives | reject unconditionally — exe, dll, js, vbs, scr, jar, zip, rar, 7z, tar, gz, iso, dmg, lnk, msi, bat, cmd, ps1, sh, svg | svg is on this list deliberately: it is an XML document that executes script, and it is served from a domain we control |
| Macro-enabled Office | reject — docm, xlsm, pptm, xlsb | the allowlist above is macro-free by construction |
| Encrypted / password-protected | reject — unscannable by definition | |
| Malware scanning | required before the object is retrievable. Either provider-side (see D1) or a scan step on our side; quarantine prefix until clean | the portal has none [V]; unauthenticated inbound is where that stops being tolerable |
| Filename | discard the sender's entirely. Generate the key as <vendor_id>/<uuid4>.<ext-from-sniffed-type>; keep the original as display metadata only | the direct mitigation for the S3 finding above, applied at the new call site regardless of when the class fix lands |
| Request body cap on the webhook | @max_json_body_size(...), sized to the total above | already exists — app/api/utils/decorators.py:149-183, with DEFAULT_API_BODY_MAX_BYTES = 256 * 1024 at :190. Use it rather than inventing a cap. Note its documented gap [V] :172-176: a chunked request omitting Content-Length is buffered before the 413, so it is not a defence against a header-omitting flood. |
Reply-body caps: inherit, do not invent. The repo already has per-type caps — RICH_TEXT_MAX_BYTES = 64 KiB [V] app/api/utils/html_sanitization.py:176, LONG_TEXT_MAX_BYTES = 16 KiB, SHORT_TEXT_MAX_BYTES = 2 KiB, OPTION_VALUE_MAX_BYTES = 256 B [V] app/api/task/services/answer_sanitization.py:194-196. Route the parsed reply body through sanitize_answer_payload / WRITABLE_STEP_TYPES [V] answer_sanitization.py:107, 226 so the email path and the customer-API path cap identically. A parsed body that exceeds the step's cap should be truncated with an auto-reply telling the customer, never silently truncated and never dropped.
D4.6 Prefetch safety
Confirmed: nothing in the repo detects scanners, and nothing should be added that tries. No HEAD-vs-GET discrimination, no UA screening, no bot detection anywhere. The only two prefetch mitigations that exist are architectural: the portal magic-link endpoint deliberately does not consume the token [V] app/api/portal/controllers/magic_link_controller.py:58-62 (comment: "prevents email link scanners from consuming the token"), and the email landing pages put mutation behind a human click.
Correct — the design must be safe against any client that fetches links, including ones that follow POST-less redirects and ones that do not exist yet. Detection is a losing game; inertness is a property.
Spec:
GET /email-action/<token>is inert. No writes, no consumption, no side effects — not evenlast_seen_dts. Safe to fetch any number of times by any number of scanners. It renders the question and the recorded state, and idempotency (D2.1) means a GET after consumption renders the recorded answer rather than an error.POST /email-action/<token>/confirmis the only mutating verb. Consume + commit before acting, per fast-pass [V]fast_pass_controller.py:163-165.- The POST must originate from a human click on the page the GET rendered — a form submit or an explicit button, exactly as
Pin.vueandUnsubscribe.vuealready do (perdiscovery/tokens-auth.md§5). SafeLinks and mail-client prefetchers issue GETs and HEADs; they do not submit forms. That is the entire mitigation, and it needs no detection. - Do not rely on CSRF.
WTF_CSRF_ENABLED = Falseglobally [V]config.py:41. The available precedent isverify_pin's host+referrer check that permits an empty referrer (the email-link case) — weak, and not worth importing. The token is the authorization; the human click is the intent signal. Referrer-Policy: no-referreron both responses [V]fast_pass_controller.py:172, so the token never leaks viaRefereron the next navigation.Cache-Control: no-storeon both. A corporate proxy caching the confirmation page caches the token in the URL.- HEAD must behave as an inert GET (Flask serves HEAD from GET by default), and must not 500 — a 500 on a scanner's HEAD is a monitoring false positive that will train people to ignore real ones.
- Do not use
?token=as the query key — use a path segment. [V]app/ui-customer/router.js:244: the portal SPA's global router guard auto-consumes any?token=query param viaauth.magicLinkLoginand then strips it withreplace: true. If the one-click link lands on an SPA route carrying?token=, the guard races the confirmation flow and eats the token. A path segment (/email-action/<token>) sidesteps it entirely. [H] PLAN UX Q11 (thin Flasksite_templatepage vs public SPA route) is still open — the thin Flask page avoids this trap by construction and is the safer default if design has no strong preference.
Open items requiring a human decision
Ranked. The first three are the ones I would put in front of an eng lead.
- The S3 filename/global-key bug must be fixed before 6073 ships attachments (D4.5). Pre-existing, cross-tenant, and inbound email hands filename choice to an unauthenticated sender. File as a standalone security bug now.
- Reply-token writable TTL: 30 days (recommended) vs 14 days (D2.5). The one number where the security/UX trade is genuinely contested, on an unauthenticated write path.
- Sender-mismatch policy: hold-for-review (D4.2) — and its dependency, the "notify the org actor" surface that D4.1 holds, D4.2 holds, and PLAN Q1 all need. One build, three consumers.
- Auto-replies stay From
notifications@onramp.us; the inbound subdomain is receive-only (D2.4). Ratifying this is what makes the sending-reputation question disappear. token_hexover thetoken_urlsafe(32)precedent, for email-local-part case-safety (D2.4). Accept the deviation or explicitly accept the case-fragility risk.- EU residency:
gdpr-prodneeds its own inbound domain and in-region receiving (D2.4). A scope input to D1's vendor choice, not an afterthought. - Confirm E3 is not sequenced as a W3 blocker (D2.1) — it is still worth doing for
preview_token.py's sake. - Attachment limit numbers (D4.5) — and who owns the policy, which is PLAN Q13's actual question.
- Unsubscribed contacts: suppress the confirmation, still record the answer (D4.1).
- Where the token reaper rides — an existing daily job, to avoid a new EasyCron registration (D2.5).
- AWS-side verification of the SES sending identity / configuration-set assumptions, which this repo cannot answer (D2.4).
- PLAN UX Q11 — thin Flask page vs SPA route; the thin page dodges the
?token=guard by construction (D4.6).
Where this contradicts the brief, PLAN, or the discovery docs
- The EasyCron list does not carry schedules. The brief instructs getting the real nudge/digest cadence from it; it is a URL list with a coordination procedure [V]
SKILL.md:98-118. Cadence is not derivable from this repo — the TTLs are anchored on in-repo constants instead, and the console remains the source of truth. reply+<token>@→r-<token>@, andtoken_urlsafe→token_hex(D2.4). Two concrete silent-drop failure modes:+-tag stripping, and case normalization of a mixed-case local part.- Store
token_hash, not the plaintext token (D2.1) — a deliberate deviation fromORWidgetFastPassToken, justified by a days-vs-60-minutes TTL difference. email_transaction_idcarries no DB FK, unlikeOREmail.transaction_idwhich does [V]app/api/email/models.py:39-48. A hard FK would fail at mint time (the tracking row does not exist yet) and would convert a best-effort observability failure into a broken-buttons customer email.- PLAN §5.2's token spec is missing sibling invalidation. "One row per option button" with per-row single-use lets a recipient click Yes and then No.
mint_group_uuid+ group-scoped consumption closes it, and is also what makes the idempotency "show the recorded answer" behaviour implementable. - The SQL-tool CI gate applies to unexposed tables too. The skill's docstring describes it as firing on already-exposed tables; the live test asserts on every ORM model [V]
test_sql_tool_classification_gate.py:114-128. Consequential — an implementer trusting the docstring ships a red build. - Four path corrections (§0):
fast_pass_controller.pyis underapp/api/portal/controllers/,task_files_helper.pyunderapp/api/utils/, the digest writer underapp/api/project/daily_jobs/. Line numbers within those files were accurate. - New: the edge gateway 403s inbound webhooks on PR previews (D4.4). Not in the brief or PLAN. Changes where the vendor sandbox gets exercised — dev.onramp.us, not previews.
- New: the "no attachment policy" is pinned by a committed test (D4.5) —
test_save_task_file_does_not_enforce_accepted_file_types[V]. Any limit added breaks it, so the change is a visible decision rather than a quiet addition. - New: the S3 flat-namespace overwrite (D4.5), and the
make_unique-computed-then-unused asymmetry between the two branches ofsave_task_file[V]task_files_helper.py:22, 27, 38. - Minor, but I would copy it if unremarked:
OREmail.transaction_idis annotatedMapped[Internal[Optional[int]]]while the column isUUID(as_uuid=False)[V]app/api/email/models.py:39-40— the annotation saysint, the column storesstr. UseOptional[str]on the new column.