Skip to content

fix(platform): enforce host policy and allowlists in provider resolution - #3221

Merged
larryro merged 12 commits into
mainfrom
fix/provider-resolution-hardening
Sep 5, 2026
Merged

larryro merged 12 commits into
mainfrom
fix/provider-resolution-hardening

Conversation

@larryro

@larryro larryro commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Provider/model resolution hardening (fix campaign, theme core-lib-providers). The admin write boundary and the turn-time consumers now agree on what a provider credential may be: the deployment's host policy is enforced on every operator-supplied URL at save time and before the subscription-broker token-pool fetch (which previously relied on safeFetch alone, whose own-host allowlist made its private-IP gate inert for the initial URL); a broker document is parsed at save; the voice resolvers honour the default credential's model allowlist exactly as the composer's voice flags do; a failed live-catalog fetch is remembered for a short back-off and coalesced across callers, and a forced refresh surfaces its failure to the settings page. Three dead 0.4 remnants are removed: the configCache reader chain no 0.5 shim reaches, the unread broker poolSize / test-only mapTokens, and the unreachable json-base64 transcription lane.

Findings fixed

  • core-lib-providers-1 — checkProviderHostPolicy on the broker endpoint before the token-pool fetch; coded CREDENTIAL_BROKER_ENDPOINT_BLOCKED; a policy-admitted private host is named to safeFetch's allowlist (8cd966f27).
  • core-lib-providers-2 — core/lib/config_cache/ and every reader stacked on it deleted; pure evaluate*/filter*/buildPeriodKey*/budget maths kept; stale comments fixed (d7d0cc915).
  • core-lib-providers-3 — failed catalog fetch remembered for CATALOG_FAILURE_BACKOFF_MS (5 min), concurrent fetches coalesced (c6450a1de).
  • core-lib-providers-4 — TTS/transcription resolvers read the default credential first (no catalog fetch for credential-less providers), catalog via getServableCatalog, entries gated by modelAllowlistPermits (4a636b799).
  • core-lib-providers-5 — transcriptionMode / json-base64 branch / format argument removed (dead-code disposition; the schema half left in feat(platform): rewrite the AI backend on a minimal YAML-config core #2857) (c7ceaf077).
  • core-lib-providers-6 — broker document parsed with brokerCredentialDataSchema + host policy on create and rotation → CREDENTIAL_BROKER_CONFIG_INVALID 400; tokensPath refined to start with $; itest probe posts a schema-valid document (58c6b9c56).
  • core-lib-providers-7 — endpointUrl held to providerBaseUrlSchema + host policy → CREDENTIAL_ENDPOINT_INVALID (58c6b9c56).
  • core-lib-providers-8 — a forced refresh rethrows its failure after logging, so POST /providers/catalogs/refresh reports the error line the docs already promise (c6450a1de).
  • core-lib-providers-9 — the service uses providerKeyEnvNameSchema (one definition, the documented 40-char cap) instead of a restated regex; unused SubscriptionBrokerConstraints alias and the Convex-era rationale dropped. Disposition differs from the proposal: the exported schema is now the save-time checker rather than deleted (58c6b9c56).
  • core-lib-providers-10 — poolSize and mapTokens removed; mapping tests re-pointed at diagnoseTokenMapping(...).usableTokens (6eafd806e).
  • core-lib-providers-11 — secret on an env credential refused with CREDENTIAL_SECRET_INVALID (58c6b9c56).

Polish pass (reviewer's non-blocking notes)

  • One allowlist predicate: walkChatCatalog (composer picker + voice flags + Auto pick) now applies modelAllowlistPermits like the voice resolvers and the serving checks — an allowlist naming openai/gpt-4o-mini-tts admits the catalog's gpt-4o-mini-tts on both surfaces; the same private includes copy is retired in the vision auto-selection (keeps its empty-list-means-unrestricted rule; the REST boundary admits []) and the thread-title picker. New chat_catalog.test.ts and generate_title.test.ts, dialect case added to the vision suite (58521332f).
  • A remembered catalog failure is logged once, when it is remembered (naming what serves and for how long); reads inside the 5-minute back-off are silent. Test pins two silent reads (7424921ae).
  • providerBaseUrlSchema's refusal is field-neutral — formatZodError prefixes the path (baseUrl: …, endpoint: …) and assertCredentialEndpointUrl its "Endpoint URL is invalid —" label; test pins the credential-side wording (bb81b67cc).
  • Broker form: the client already refuses a tokensPath without the $ root before the round-trip (buildBrokerDocument runs brokerCredentialDataSchema, wrapped in providers.broker.invalid); a test now pins it. The coarse submit-button gate stays coarse on purpose — a greyed-out button would hide the reason the on-submit refusal shows (4000a30c5).

Skipped

  • none

Tests & gates observed

Re-verified 2026-09-05 on the branch head 4000a30c5 (polish pass; base = current origin/main fe27bd32b), worktree with hard-linked node_modules:

  • bunx tsc --noEmit (services/platform): exit 0.
  • bunx oxlint --type-aware (services/platform): exit 0.
  • bunx vitest --run --project server (services/platform): Test Files 498 passed (498) / Tests 6006 passed (6006). (The three app/routes/** files that failed at load in the earlier symlinked worktree — Vite Denied ID …@fontsource/inter…woff2?url — load and pass here; that was a worktree artefact, not this branch.)
  • bun run check (worktree root): Tasks: 40 successful, 40 total, exit 0 — format:check, lint, typecheck, test (@tale/platform#test: Test Files 504 passed (504) / Tests 73220 passed (73220)), test:ui (@tale/platform#test:ui: Test Files 455 passed (455) / Tests 3504 passed (3504)) all green.
  • bun run knip:check: exit 0 (one pre-existing configuration hint: cron-parser … Remove from ignoreDependencies).
  • Integration proof run-itest.sh (fresh tale-db + MinIO, Docker), branch head 4000a30c5 + the TEMPORARY, uncommitted git cherry-pick -n aa3d1d7a9 (fix(platform): pass the corpus scope rows as one jsonb parameter #3222's unblock of main's checkCorpusScopeReconcile jsonb defect, git reset --hard afterwards, tree clean): [itest] 464/466 checks passed across 133/133 lanes (no truncation). Every provider-credential, catalog, picker, title, TTS, transcription and dictation lane PASSes (provider credentials (0.4 resolver over PG), provider credential edits reach the row, catalog-less provider serves its credential allowlist, picker offers only what the active default credential can serve, composer picker: governance-filtered models + harness roster, thread-title model call is booked to the usage ledger, AI title lane: auto-enqueued, fallback lands, never clobbers a name, tts on pg, transcription pipeline/dedup/failure→retry/skip + one-shot dictation, providers/connectors/sandbox settings surfaces). The 2 failed checks are main's, outside this theme: knowledge: corpus scope drift is corrected and reported (drifted=null — knowledge theme, fix(platform): pass the corpus scope rows as one jsonb parameter #3222) and webdav re-home (red on main before this campaign).

Notes for the reviewer

  • Finding 9's save-time rule is now the documented 40-char cap (providerKeyEnvNameSchema). Existing rows with a longer envName (41–82 chars were admitted before) keep resolving — read-time (SECRETS_ENV_REGEX) has no cap; only a future envName patch on such a row is refused until it is shortened.
  • Finding 9's disposition: the review proposed deleting providerKeyEnvNameSchema in favour of SECRETS_ENV_REGEX; the branch instead makes the exported schema the save-time checker (it carries the documented 40-char cap — docs/en/self-hosted/configuration/environment-reference.md:108, docs/en/platform/admin/providers.md:83) and removes the restated regex. Read-time (SECRETS_ENV_REGEX, no cap) stays laxer than save-time, so no stored row is stranded.
  • Finding 5's disposition: deletion, not completion — no shipped catalog declares a json-base64 model, the live normalizer never emits the transcription tag, and the mock provider's contract test only exercises the multipart wire.
  • New CREDENTIAL_* codes are backend literals like the existing ones (none appear in messages/*.yml or app/), so no locale work.
  • F4 changes the voice resolvers' read order: the default credential row is read before the catalog, so a provider without an active direct default credential is skipped with no catalog fetch. chatShimHandlers → knowledgeShimHandlers → credentialShimHandlers serves getDefaultCredentialInternal to every caller (tts/service, tts/routes, files/transcription, transcribe_audio).
  • The pre-existing test "treats a listing with no usable models as a failure and caches nothing" now advances past CATALOG_FAILURE_BACKOFF_MS before its second read — the remembered failure is the intended new behaviour.
  • Main's checkCorpusScopeReconcile jsonb defect is fixed by fix(platform): pass the corpus scope rows as one jsonb parameter #3222 (knowledge theme); nothing from it is committed here.

The subscription-broker resolution fetched the admin-supplied broker
endpoint through safeFetch alone. safeFetch's auto-derived own-host
allowlist admits the initial URL's host, so its private-IP refusal never
fired for the URL it was handed: an org admin could aim the backend at
169.254.169.254 or metadata.google.internal and read the status, the
kind, and — via tokensPath — the JSON body into a sandbox env var.

Apply checkProviderHostPolicy to the broker endpoint on every resolution
(metadata hosts refused unconditionally, private hosts unless
TALE_ALLOW_PRIVATE_PROVIDER_HOSTS=1), surface the refusal as the coded
CREDENTIAL_BROKER_ENDPOINT_BLOCKED, and name a policy-admitted private
host to safeFetch's allowlist — the same shape catalog_fetch already
uses. Regression tests pin the three cases.

Finding: core-lib-providers-1.
createCredential/updateCredential accepted what every consumer later
refused: a subscription-broker document was encrypted verbatim and failed
only at turn time with "delete and recreate it"; a per-credential endpoint
was checked with startsWith('https://') while turns ran the full URL parse
plus host policy (so `https://` alone or a metadata host saved with 200
and an audit row); a secret rotation on an env credential wrote ciphertext
the resolver never reads and audited a no-op as an update; and the env-name
rule was a restated regex beside the exported providerKeyEnvNameSchema
that nothing imported.

- Parse a broker document with brokerCredentialDataSchema on create and
  rotation and run checkProviderHostPolicy on its endpoint —
  CREDENTIAL_BROKER_CONFIG_INVALID (400) names the offending field.
- Hold endpointUrl to providerBaseUrlSchema plus the host policy —
  CREDENTIAL_ENDPOINT_INVALID names the reason.
- Refuse `secret` on an env row with CREDENTIAL_SECRET_INVALID.
- Use providerKeyEnvNameSchema for the env name (one definition, the
  documented 40-char cap); drop the unused SubscriptionBrokerConstraints
  alias and the schema's Convex-era rationale.
- Refine tokensPath to start with `$`, as json_path.ts requires, so a
  root-less path is a coded 400 instead of an uncoded JsonPathError.
- The itest broker probe posts a schema-valid document.

Findings: core-lib-providers-6, -7, -9, -11.
…Tokens

`poolSize` on the resolved subscription-broker credential was produced by
resolveBroker and read by no consumer (the turn hosts and the gateway
provisioner destructure token/targetEnvVar/endpointUrl only); `mapTokens`
in broker_pool.ts was referenced only by its own doc comment and its
tests while the runtime calls diagnoseTokenMapping directly. Remove both
and point the two mapping tests at `diagnoseTokenMapping(...).usableTokens`.

Finding: core-lib-providers-10.
…eaches

core/lib/config_cache/read.ts read the retired Convex `configCache` table
through `ctx.db`, which no 0.5 ctx shim provides (createCtxShim builds
runQuery/runMutation/runAction only) and no migration ever created. Every
function stacked on it was an uncalled 0.4 body — a divergent second copy
of the policy-reading concept the live domain does over the org's policy
FILES (backend/lib/org-config.ts, governance-policies.ts) — that a future
caller could wire and hit a runtime TypeError.

Delete the module and its dead readers: governance/helpers
(PolicyRow, readPolicyRow, readPolicyConfig, getPasswordPolicyRow,
getPasswordPolicy, getTwoFactorPolicy, getStrictestPasswordPolicyForUser),
dsar_policy.getDsarPolicy, sandbox/quota_policy.readSandboxQuotaPolicy,
budget_enforcement.{checkBudget, computeRollingRemainingCostCents} and the
four ctx.db usage getters only they called, resolve_default_model
.resolveDefaultModel, model_access_enforcement.{checkModelAccess,
getAccessibleModels}, feature_enforcement.resolveFeatureFlags. Every pure
evaluate*/filter*/findApplicableModelRule/buildPeriodKey*/merge* helper
and the budget maths stay; the two mock-based tests now exercise the pure
halves directly. Stale comments naming the removed functions are fixed.

Finding: core-lib-providers-2.
…efresh

cachedLiveCatalog stamped the cache only on success: a failed fetch
served the stale catalog or the shipped defaults correctly but remembered
nothing, so while a listing host was unreachable every settings-page
load, composer listing, Auto pick and voice resolution re-ran the full
retry ladder (up to 66 s per URL, two URLs for OpenRouter), and
concurrent callers each started their own. A forced refresh that failed
was swallowed the same way, so POST /providers/catalogs/refresh reported
"N models" as success for an outage the operator pressed the button to
see — the docs already promise "the error it hit".

- Remember the last failure per cache key for a 5-minute back-off
  (CATALOG_FAILURE_BACKOFF_MS): inside it the stale catalog, the shipped
  defaults, or the remembered error answer without a fetch.
- Coalesce concurrent fetches of one catalog into a single in-flight
  promise.
- A forced refresh bypasses the back-off and rethrows its own failure
  after logging; the previous catalog keeps serving every other caller,
  so the refresh route's error branch now fires.

Regression tests pin the back-off, its lapse, the forceRefresh bypass,
the coalescing and the surfaced forced-refresh failure.

Findings: core-lib-providers-3, -8.
resolveTtsModel and resolveTranscriptionModel took the first
text-to-speech / transcription entry of the provider's whole catalog and
only then resolved the credential — the default credential's model
allowlist was never read, while the composer derives ttsAvailable /
transcriptionAvailable from walkChatCatalog, which drops every entry the
allowlist excludes. An OpenAI default credential allowlisted to
['gpt-4o'] hid voice in the UI while POST /tts/synthesize, the dictation
door and the audio-upload pipeline still resolved (and metered) the
voice model on it — the documented restriction bypassed exactly where
the resolver header promises agreement. The catalog was also fetched for
providers with no credential at all, on every voice call.

Both resolvers now read the provider's default credential first through
the existing directActiveCredential narrowing (no active api-key/env
default → the provider is skipped before any catalog fetch), read the
catalog through getServableCatalog with the allowlist, and take the
first tagged entry modelAllowlistPermits admits — the shared predicate
the agent lane applies. The secret is still resolved through
resolveProviderCredential afterwards.

Regression tests pin the allowlist refusal (NO_PROVIDER /
NO_TRANSCRIPTION_MODEL), the allowlisted pass, and that a credential-less
or subscription-only provider costs no catalog fetch; the transcription
resolver gets its first test file.

Finding: core-lib-providers-4.
`ResolvedTranscriptionModel.transcriptionMode` was declared but never
set: the resolver's only return carries modelId/providerName/baseUrl/
apiKey, so the `json-base64` branch in requestTranscription could not
execute, its `format` argument was plumbed by both callers for nothing,
and the header pointed at a `transcriptionMode` field
lib/shared/schemas/providers.ts has not carried since the catalog schema
rewrite (#2857). The catalog normalizer emits no `transcription` tag for
live listings either, so no OpenRouter entry ever reaches the resolver.

Remove the field from the resolved model and the request model, the
json-base64 request branch and its tests, the `format` argument at both
call sites, and the stale comments; the mock provider spec no longer
advertises an `input_audio` envelope. Only the multipart Whisper wire
remains — the one every shipped transcription model speaks.

Finding: core-lib-providers-5.
…vice

format:check flagged import order in three files touched by this branch.
The composer's catalog walk (`walkChatCatalog`) filtered a credential's
model allowlist with a strict `allowlist.includes(entry.id)` while the
voice resolvers, the turn-time serving checks and the pinned-credential
path apply `modelAllowlistPermits`, which also admits a dialect-equivalent
id (`openai/gpt-4o-mini-tts` ↔ `gpt-4o-mini-tts`). The header's promise
that the picker's voice flags and the resolvers "can never disagree" did
not hold for such an allowlist: the resolver served the model, the
composer's `ttsAvailable` flag stayed off.

The walk now reads the shared predicate, and the same private copy is
retired in the two other walks of the theme — the vision auto-selection
(which keeps its own empty-list-means-unrestricted rule; the REST boundary
admits an empty allowlist) and the thread-title picker. Tests pin the
dialect case on all three and the walk's existing skip rules.

Polish over the PR #3221 review (theme core-lib-providers, F4 note).
`serveDegraded` warned on every read the failure back-off answered from
memory, so a provider whose listing was down produced one warning per
picker open, per turn, per title call for five minutes. The warning now
fires once, when the failed fetch is remembered (it names what serves
meanwhile and for how long); the back-off path itself is silent. The
forced-refresh line is unchanged.

Polish over the PR #3221 review (theme core-lib-providers, F3 note).
`providerBaseUrlSchema`'s refine message read "baseUrl must be an
https:// URL …", but the schema is shared: `formatZodError` already
prefixes the field path where it sits in a document (`baseUrl: …`,
`endpoint: …` for the broker document), and `assertCredentialEndpointUrl`
prefixes its own "Endpoint URL is invalid —" label — so the per-credential
Endpoint URL and the broker endpoint were refused with a message naming a
field the operator never filled in. The message is now field-neutral; a
test pins that the credential-side refusal names the endpoint only.

Polish over the PR #3221 review (theme core-lib-providers, F7 note).
The broker form validates its document with the same
`brokerCredentialDataSchema` the server enforces, so a `tokensPath`
without the `$` root the resolver requires is already refused before the
round-trip with a message naming the field; nothing pinned that. The
coarse submit-button gate deliberately stays coarse — greying the button
out would hide the reason the on-submit refusal shows.

Polish over the PR #3221 review (theme core-lib-providers, F6 note).
@larryro
larryro merged commit 68b26a4 into main Sep 5, 2026
48 checks passed
@larryro
larryro deleted the fix/provider-resolution-hardening branch September 5, 2026 10:18
larryro added a commit that referenced this pull request Sep 5, 2026
runModerationProvider fetched the org-admin-supplied endpoint.url through
safeFetch alone. safeFetch auto-allowlists the initial URL's own host, so
its private-IP / metadata gate never fired for the URL it was handed: an
org admin (not the deployment operator) could aim the moderation endpoint
at http://169.254.169.254/... or a private host and, with responseShape
custom_jsonpath, read the response back — the same class #3221 fixed for
the credential broker.

policeModerationEndpoint runs checkProviderHostPolicy once before the
retry loop: cloud-metadata hosts are refused always, private hosts unless
the operator set TALE_ALLOW_PRIVATE_PROVIDER_HOSTS=1 — a refusal is a
ModerationHttpError('config') (step_error, the fail behaviour applies,
off the breaker). A policy-admitted private host is named to safeFetch's
allowedHosts so its own gate does not refuse what the policy just
allowed. The endpoint schema comment now describes that gate. The
moderation itest lane already opts in (mock on 127.0.0.1).

governance-3 (SSRF), review of PR #3230.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant