فهرست منبع

docs(mail): record the transport facts that were measured, not assumed

The mail section exists so the next person does not re-derive any of this.
Every claim in it was measured against a running server or a fake one and
is pinned by a test, and the three that cost the most to find are the
CUSTOMREQUEST requirement (curl's ";UID=" form always sets \Seen, and the
STORE workaround corrupts already-read mail), where SELECT's untagged
chatter does and does not arrive, and that curl dot-stuffs what it is
given.

Also records the scope cut and its reason, because "why is there no
WebDAV" is the obvious question: curl's HTTP is compiled out so there is
only one HTTP client with one set of outbound defaults, and re-enabling it
brings redirects back on credentialed requests.
fszontagh 1 ماه پیش
والد
کامیت
f4b7353ff2
1فایلهای تغییر یافته به همراه18 افزوده شده و 1 حذف شده
  1. 18 1
      CLAUDE.md

+ 18 - 1
CLAUDE.md

@@ -38,7 +38,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
   - `db_gateway` (`qualify(project,coll)` + `DbGateway` over `smartbotic::database::Client`), `settings_store` (global settings **and per-project embedding overrides**, hot-reload, one subscribe stream for both), `project_settings` (`ProjectEmbeddingSettings` + the pure `resolveEmbedding()`), `outbound_http` (User-Agent + TLS defaults for every external call), `key_store` (API keys, hot-reload, bootstrap admin key), `collection_registry` (per-project metadata), `embeddings` (OpenAI), `auth` (sessions, bearer/cookie), `server` (ApiServer + auth helpers), `handlers/*` (one file per route group).
   - Auth model: pre-routing **authenticates** `/api/*` (401); each handler **authorizes** via `requireKey` → `requireAdmin` / `requireProjectAccess` (403). Keys are referenced by a stable **`id`** (not the secret).
 - `webui/` - React 19 + Vite + TS (strict, `erasableSyntaxOnly`) + Tailwind + Monaco. `pages/Functions.tsx` holds `fn`/`tab` in the URL (a draft is `?new=1` and carries no source, so it is deliberately not shareable); `components/ScopeRules.tsx` is the `rules`/`ops` editor shared by key scopes and function policies, with `allowEmpty` for the latter because an empty function policy is legal. `require_human_token` is hidden for function policies: it is a captcha header check in `requireCapability`, and a function is authorized through `requireCapabilityCore`, which never sees an HTTP request - offering it would store a field that silently does nothing. Cookie-session auth (`credentials:'include'`). Pages read `currentProject`/`admin` from `useAuthStore`; all calls go through `src/api/client.ts`. **Documents keeps `collection`, the filter triple (`field`/`op`/`value`) and `open` in the URL**, so relation links are ordinary links and any filtered view is shareable; changing collection closes an open editor (it belongs to the collection being left). `pages/Settings.tsx` is a tab shell over `pages/settings/*` (Embeddings, Cache & performance, Access & security, Web UI are admin-only; the per-project embeddings tab is not, so `/settings` is **not** admin-gated in `App.tsx`). Shared controls live in `components/form.tsx`.
-- `runner/` - the **function runner service**, a second binary (`smartbotic-vectorapi-runner`). Three layers split by what they must link, which is also what decides where each can be tested: `runner_core` (QuickJS engine + pool, no database), `runner_protocol` (`/run`, `/validate`, `/health` as JSON in / JSON out, no transport and no database - which is why its 30 tests run on the dev host), `runner_host` (the `ctx.*` surface; links `vectorapi_core`). `src/main.cpp` is the only part that links the world and the only part the dev host cannot build. The QuickJS execution core (`runner_core`). **Builds as its own top-level project** (`cmake -S runner -B build-runner`), which is the one part of this repo that compiles on the Void dev host, since it links neither `vectorapi_core` nor the database client. `BUILD_RUNNER=ON` wires it into the root build; it is **OFF by default** because it vendors QuickJS from GitHub at configure time and an ordinary build must not start depending on a network fetch.
+- `runner/` - the **function runner service**, a second binary (`smartbotic-vectorapi-runner`). **Four** layers split by what they must link, which is also what decides where each can be tested: `runner_core` (QuickJS engine + pool, no database), `runner_protocol` (`/run`, `/validate`, `/health` as JSON in / JSON out, no transport and no database - which is why its 30 tests run on the dev host), `runner_net` (libcurl + the IMAP/MIME parsers + the mail budget + the error map; links neither `vectorapi_core` nor the database client, so its ~200 tests run on the dev host too), `runner_host` (the `ctx.*` surface; links `vectorapi_core` AND `runner_net`). `src/main.cpp` is the only part that links the world and the only part the dev host cannot build. The QuickJS execution core (`runner_core`). **Builds as its own top-level project** (`cmake -S runner -B build-runner`), which is the one part of this repo that compiles on the Void dev host, since it links neither `vectorapi_core` nor the database client. `BUILD_RUNNER=ON` wires it into the root build; it is **OFF by default** because it vendors QuickJS from GitHub at configure time and an ordinary build must not start depending on a network fetch.
 - `api/` - `openapi.json` (3.1), `llms.txt` (llmstxt.org), `docs/` (Redoc page). Served at `/openapi.json`, `/llms.txt`, `/docs`. Shipped in the server `.deb`. **Keep these in sync when changing routes.**
 - `packaging/` - `build.sh` (`--local` + Docker trixie), `deb/create-debs.sh`, control templates, systemd unit, maintainer scripts. `docs/superpowers/` - design spec (esp. **Addendum A**) + the 3 implementation plans.
 
@@ -82,6 +82,23 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **The runner authenticates a shared bearer token and fails closed.** No token plus a non-loopback bind address means it **refuses to start**. `isLoopbackBind()` answers "not loopback" for anything it cannot parse, so an unrecognised address produces the refusal. The comparison is constant-time, `/health` is authenticated too, and both sides prefer `SVAPI_RUNNER_TOKEN` in the `.env` over the conffile.
 - **`ctx.fetch` egress goes through the SSRF guard** (`functions/net_guard.hpp`): fail closed on anything unparseable, and classify **every** address a name resolves to, not the first. A settings blocklist is **UNIONED** with the built-in defaults by `SsrfPolicy::fromSettings()`, never substituted for them - an operator adding one CIDR must not silently reopen loopback, RFC1918 and the metadata endpoint. `function_egress_allow_private` is the explicit opt-out and relaxes **only** `privateBlockedCidrs()`; 169.254.0.0/16, link-local, multicast, reserved space and the IPv6 spellings of an IPv4 destination (NAT64, 6to4, `::/96`) stay blocked whatever it is set to. Note the opt-out does expose loopback, where our own API listens.
 
+## Mail surface (`ctx.mail`, IMAP + SMTP)
+
+- **Scope is IMAP read + SMTP send, deliberately.** No FTP, FTPS, POP3 or WebDAV/CalDAV. SFTP was dropped by the owner, which is what keeps vendoring to ONE upstream - SFTP needs libssh2, which is far less watched than curl while having had remotely reachable issues. **WebDAV is out because it is HTTP**, and curl's HTTP is compiled OUT: `ctx.fetch` is cpp-httplib with its own guard, its own pinning and its own outbound defaults, and two HTTP clients with two sets of defaults is exactly how the two drift. Re-enabling it also brings redirects back, which then need `CURLOPT_REDIR_PROTOCOLS_STR` set separately and `FOLLOWLOCATION` off.
+- **`runner_net` is a separate target for testability, not tidiness.** `runner_host` links `vectorapi_core` and the database client, so putting the IMAP and MIME code there would make the largest and most defect-prone part of the feature the one part only the Docker path can compile. The division at the boundary is strict: `runner_host` converts JS values to a plain request struct and back, and does nothing else - no curl call, no IMAP knowledge, no timeout arithmetic above that line.
+- **libcurl is VENDORED at `curl-8_22_0`** (`SVAPI_CURL_TAG`, `SVAPI_VENDOR_CURL=ON`; `OFF` links the system one and is what the dev loop uses, because vendoring costs minutes). The pin comment carries the obligations, and they are real: **CVE tracking is ours now**, a statically linked curl is invisible to `apt`, and a fix means a rebuild and a republish of both binaries rather than an unattended upgrade. Judge an advisory against **what this service reaches** - exactly `imaps`/`imap`/`smtps`/`smtp` - the same discipline the httplib pin uses. `PROXY` is compiled out rather than disabled per handle, because curl reads `*_proxy` from the environment where httplib does not and `runner.env` is a file an operator edits; a stray proxy variable would silently reroute a destination the SSRF guard had already approved. `NETRC` is out so credentials can only come from project secrets. Cookies/ALTSVC/HSTS are out because each is persistent cross-request state, which a multi-tenant pool must not accumulate. A build from a git tag reports its version as `8.22.0-DEV`.
+- **A fetch goes through `CURLOPT_CUSTOMREQUEST` with `BODY.PEEK[]`, NEVER curl's `;UID=` URL form.** Measured against a live server elsewhere: the URL form **always** sets `\Seen`. Undoing it afterwards with a `UID STORE -FLAGS` is worse than the disease - it removes a flag it may not have set, so a message the user had **already read comes back unread**, and a timeout between the fetch and the undo leaves the message read anyway, which is the exact outcome peek exists to prevent. A test asserts no `STORE`, `+FLAGS` or `-FLAGS` ever reaches the wire.
+- **`SELECT`'s untagged responses do NOT reach a custom request's write callback, but the tagged final line does.** Measured, and pinned by a test against the fake server, because a parser written for the other answer silently mis-reads every fetch. Also: a `BODY.PEEK[...]` fetch comes back labelled **`BODY[...]`** without the `.PEEK`, so a parser looking for the string it sent finds nothing.
+- **curl dot-stuffs the payload it is given, so the renderer must not.** Both doing it corrupts any line beginning with a period; neither doing it truncates the message at a lone `.`. The renderer additionally emits a leading period as `=2E` in quoted-printable, so the protection holds either way.
+- **Non-ASCII IMAP SEARCH is REFUSED by field name, not sent.** Doing it properly needs `SEARCH CHARSET UTF-8` with the term as an octet-counted literal, which is a multi-step exchange the one-shot transport does not drive. Sending the raw bytes is **worse than failing**: the server matches nothing and zero results is indistinguishable from "there is no such mail". That shipped elsewhere and produced silently wrong answers against Hungarian mail. The refusal names the field and says to filter on an ASCII-safe criterion and match the accented text after fetching. Mailbox NAMES are unaffected and still go out as modified UTF-7.
+- **An SMTP refusal after DATA arrives as `CURLcode` 8 (`WEIRD_SERVER_REPLY`) with `CURLINFO_RESPONSE_CODE` 550.** So a reply code the server actually sent **wins over curl's generic transport complaint** for the generic codes; otherwise a bad recipient was reported as a protocol fault. Codes that already carry more meaning than a reply code, such as a denied login, keep their own answer. A 4xx reply is transient (`mail_server_busy`, 503), a 5xx is the caller's problem (`mail_rejected`, **422** - a 550 is overwhelmingly a bad recipient or a rejected sender, and blaming the server sends them looking in the wrong place).
+- **Retryability is a PARAMETER, never inferred.** `sideEffecting` is the caller saying whether the operation changes anything at the far end, for the same reason the run kind is a parameter to `RunService::run`. A failure is retryable only when nothing can have happened: DNS and connect failures are, a mailbox read that times out is, and a **send is never retryable** past the point delivery was possible, because a duplicate cannot be recalled. **A rejected login is not retryable either** - repeating it is how an account gets locked or an IP blocked, which is far more expensive than the failure being retried. A timeout is **504**, not 503, because 503's whole meaning is "retry as-is".
+- **The mail budget has a THIRD number the embedding budget does not: `totalMs`.** An embedding call is one request/response, so bounding connect and read bounds it. A mailbox read is several round trips on one connection, and a read timeout bounds each quiet period and **not their sum** - a server answering every command just inside the read timeout holds a pooled runtime far past the run's budget without ever tripping it. `resolveMailBudget()` (`net/mail_budget.hpp`, pure) otherwise mirrors `resolveEmbedBudget()`, connect capped at half.
+- **`mailGlobalInit()` is called once from the runner's `main` before any worker starts, and FAILS CLOSED.** `curl_global_init` is not thread-safe and a lazy first-use from two pool threads is a real race. It also checks `CURL_VERSION_THREADSAFE` and refuses to start without it, in the same spirit as the runner refusing to start with no token on a non-loopback bind. **`CURLOPT_NOSIGNAL` on every handle**, or curl uses `SIGALRM` for resolution timeouts, which is unsafe off the main thread and can longjmp out of a worker - and a single-threaded test never shows it.
+- **One handle per (run, account), destroyed with the session. No `CURLSH`, no cross-tenant reuse.** A handle carries connection state and credentials. A fresh handle per command would mean a TCP connect, a TLS handshake and a LOGIN for every command, which is both slow and what gets an account throttled; a test asserts one LOGIN serves three commands.
+- **The fake IMAP/SMTP servers are committed** (`runner/tests/fake_mail_server.hpp`): in-process TCP listeners on **ephemeral** ports. Ephemeral because a fixed port collides - twice during development a test reached a stale server from an earlier run and "passed" against the wrong process. They **mask credentials** before recording a transcript, and the SMTP one answers a bare `AUTH PLAIN` with a **334 challenge, not 235**: answering 235 made an earlier harness report a working login for a client that had sent no credentials. It also **un-stuffs** the leading period during DATA, as a real receiver does, or a correct client looks like it double-stuffed.
+- `src/functions/mime_words.*` is **adapted from an existing internal implementation**, is owned elsewhere, and changes flow one way INTO this repo. If a decoding bug turns up here, report it rather than fixing only this copy.
+
 ## Data model & runtime config
 
 - Bootstrap `config.json` is minimal: `log_level`, `http.{bind_address,port}`, `database.address`. Everything else lives in the DB and **hot-reloads** (subscribe + atomic snapshot swap).