Repository navigation
fix(platform): enforce host policy and allowlists in provider resolution - #3221
Merged
Merged
Conversation
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
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 onsafeFetchalone, 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: theconfigCachereader chain no 0.5 shim reaches, the unread brokerpoolSize/ test-onlymapTokens, and the unreachablejson-base64transcription lane.Findings fixed
checkProviderHostPolicyon the broker endpoint before the token-pool fetch; codedCREDENTIAL_BROKER_ENDPOINT_BLOCKED; a policy-admitted private host is named tosafeFetch's allowlist (8cd966f27).core/lib/config_cache/and every reader stacked on it deleted; pureevaluate*/filter*/buildPeriodKey*/budget maths kept; stale comments fixed (d7d0cc915).CATALOG_FAILURE_BACKOFF_MS(5 min), concurrent fetches coalesced (c6450a1de).getServableCatalog, entries gated bymodelAllowlistPermits(4a636b799).transcriptionMode/json-base64branch /formatargument removed (dead-code disposition; the schema half left in feat(platform): rewrite the AI backend on a minimal YAML-config core #2857) (c7ceaf077).brokerCredentialDataSchema+ host policy on create and rotation →CREDENTIAL_BROKER_CONFIG_INVALID400;tokensPathrefined to start with$; itest probe posts a schema-valid document (58c6b9c56).endpointUrlheld toproviderBaseUrlSchema+ host policy →CREDENTIAL_ENDPOINT_INVALID(58c6b9c56).POST /providers/catalogs/refreshreports the error line the docs already promise (c6450a1de).providerKeyEnvNameSchema(one definition, the documented 40-char cap) instead of a restated regex; unusedSubscriptionBrokerConstraintsalias and the Convex-era rationale dropped. Disposition differs from the proposal: the exported schema is now the save-time checker rather than deleted (58c6b9c56).poolSizeandmapTokensremoved; mapping tests re-pointed atdiagnoseTokenMapping(...).usableTokens(6eafd806e).secreton anenvcredential refused withCREDENTIAL_SECRET_INVALID(58c6b9c56).Polish pass (reviewer's non-blocking notes)
walkChatCatalog(composer picker + voice flags + Auto pick) now appliesmodelAllowlistPermitslike the voice resolvers and the serving checks — an allowlist namingopenai/gpt-4o-mini-ttsadmits the catalog'sgpt-4o-mini-ttson both surfaces; the same privateincludescopy is retired in the vision auto-selection (keeps its empty-list-means-unrestricted rule; the REST boundary admits[]) and the thread-title picker. Newchat_catalog.test.tsandgenerate_title.test.ts, dialect case added to the vision suite (58521332f).7424921ae).providerBaseUrlSchema's refusal is field-neutral —formatZodErrorprefixes the path (baseUrl: …,endpoint: …) andassertCredentialEndpointUrlits "Endpoint URL is invalid —" label; test pins the credential-side wording (bb81b67cc).tokensPathwithout the$root before the round-trip (buildBrokerDocumentrunsbrokerCredentialDataSchema, wrapped inproviders.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
Tests & gates observed
Re-verified 2026-09-05 on the branch head
4000a30c5(polish pass; base = currentorigin/mainfe27bd32b), worktree with hard-linkednode_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 threeapp/routes/**files that failed at load in the earlier symlinked worktree — ViteDenied 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).run-itest.sh(fresh tale-db + MinIO, Docker), branch head4000a30c5+ the TEMPORARY, uncommittedgit cherry-pick -n aa3d1d7a9(fix(platform): pass the corpus scope rows as one jsonb parameter #3222's unblock of main'scheckCorpusScopeReconcilejsonb defect,git reset --hardafterwards, 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) andwebdav re-home(red on main before this campaign).Notes for the reviewer
providerKeyEnvNameSchema). Existing rows with a longerenvName(41–82 chars were admitted before) keep resolving — read-time (SECRETS_ENV_REGEX) has no cap; only a futureenvNamepatch on such a row is refused until it is shortened.providerKeyEnvNameSchemain favour ofSECRETS_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.transcriptiontag, and the mock provider's contract test only exercises the multipart wire.CREDENTIAL_*codes are backend literals like the existing ones (none appear inmessages/*.ymlorapp/), so no locale work.chatShimHandlers → knowledgeShimHandlers → credentialShimHandlersservesgetDefaultCredentialInternalto every caller (tts/service, tts/routes, files/transcription, transcribe_audio).CATALOG_FAILURE_BACKOFF_MSbefore its second read — the remembered failure is the intended new behaviour.checkCorpusScopeReconcilejsonb defect is fixed by fix(platform): pass the corpus scope rows as one jsonb parameter #3222 (knowledge theme); nothing from it is committed here.