Referenční konfigurace a nasazení.
Settings
Popis
Složka examples/settings obsahuje ukázkové managed settings pro organizace – soubory settings-lax.json, settings-strict.json, settings-bash-sandbox.json a rozsáhlejší pár pro HIPAA (settings-hipaa.json + managed-mcp-hipaa.json s návodem README-hipaa.md). Jde o výchozí body; podle README je lze slučovat a před nasazením je třeba je lokálně vyzkoušet.
Tři úrovně přísnosti. lax vypne --dangerously-skip-permissions (permissions.disableBypassPermissionsMode: disable) a zakáže plugin marketplaces (strictKnownMarketplaces: []). strict navíc blokuje uživatelská a projektová permission pravidla (allowManagedPermissionRulesOnly) i hooks (allowManagedHooksOnly), zakazuje WebSearch a WebFetch a vyžaduje potvrzování nástroje Bash (ask). bash-sandbox zapne sandbox.enabled a zakáže příkazy mimo sandbox (allowUnsandboxedCommands: false); sandbox ovlivňuje jen nástroj Bash, ne Read/Write/WebFetch, MCP ani hooks.
HIPAA varianta. Přidává přihlášení jen přes claude.ai a konkrétní organizaci (forceLoginMethod, forceLoginOrgUUID), povolené providery ["anthropic"], prázdný MCP allowlist, blokaci čtení i editace souborů se secrets (~/.ssh, ~/.aws, ~/.npmrc, ~/.git-credentials…), sandbox se síťovým allowlistem, skrytí proměnných s tokeny (GITHUB_TOKEN, AWS_*, ANTHROPIC_API_KEY…), cleanupPeriodDays: 30 a telemetrii přes OTLP s vypnutým logováním promptů, odpovědí a obsahu nástrojů. managed-mcp-hipaa.json je prázdný mcpServers: {}, tj. MCP vypnuto úplně.
Proč je to nejlepší způsob. Managed settings stojí na vrcholu pořadí priorit a uživatel je nemůže přebít; dává se jimi zámek právě tam, kde jsou rizika (bypass oprávnění, cizí hooks a marketplaces, únik přes síť). Seznamy allow jsou ve výchozí podobě prázdné, tedy blokují vše – bezpečný základ, který správce záměrně rozšiřuje.
Aktuálnost a auditOvěřeno proti Claude Code 2.1.314 (aktuální verze v CHANGELOG.md i v kontejneru claude-t373). Ukázky lax a strict jsou záměrně minimální a nepokrývají novější klíče. Stojí za zvážení: permissions.blockWritesOutsideWorkingDirectories (2.1.314), sandbox.failIfUnavailable (viz HIPAA ukázka), onFailure: "block" u hooks (hook, který nelze spustit, vyprší nebo skončí neočekávaným kódem, akci zablokuje) a drop-in složku managed-settings.d/ pro nezávislé fragmenty politik. Neparsovatelný managed soubor dnes Claude Code odmítne spustit (nepoběží bez politiky) – před deploy proto JSON vždy validuj.
Zdrojový kód
examples/settings/settings-lax.json (6 řádků)
Nejmírnější varianta.
{
"permissions": {
"disableBypassPermissionsMode": "disable"
},
"strictKnownMarketplaces": []
}examples/settings/settings-strict.json (28 řádků)
Přísná varianta.
{
"permissions": {
"disableBypassPermissionsMode": "disable",
"ask": [
"Bash"
],
"deny": [
"WebSearch",
"WebFetch"
]
},
"allowManagedPermissionRulesOnly": true,
"allowManagedHooksOnly": true,
"strictKnownMarketplaces": [],
"sandbox": {
"autoAllowBashIfSandboxed": false,
"excludedCommands": [],
"network": {
"allowUnixSockets": [],
"allowAllUnixSockets": false,
"allowLocalBinding": false,
"allowedDomains": [],
"httpProxyPort": null,
"socksProxyPort": null
},
"enableWeakerNestedSandbox": false
}
}examples/settings/settings-bash-sandbox.json (18 řádků)
Bash jen v sandboxu.
{
"allowManagedPermissionRulesOnly": true,
"sandbox": {
"enabled": true,
"autoAllowBashIfSandboxed": false,
"allowUnsandboxedCommands": false,
"excludedCommands": [],
"network": {
"allowUnixSockets": [],
"allowAllUnixSockets": false,
"allowLocalBinding": false,
"allowedDomains": [],
"httpProxyPort": null,
"socksProxyPort": null
},
"enableWeakerNestedSandbox": false
}
}examples/settings/managed-mcp-hipaa.json (3 řádků)
Vypnutí MCP (mcpServers prázdné).
{
"mcpServers": {}
}examples/settings/settings-hipaa.json (152 řádků)
Rozsáhlá varianta pro HIPAA.
{
"forceLoginMethod": "claudeai",
"forceLoginOrgUUID": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"allowedProviders": ["anthropic"],
"allowManagedHooksOnly": true,
"allowedHttpHookUrls": [],
"allowManagedMcpServersOnly": true,
"allowedMcpServers": [],
"deniedMcpServers": [
{ "serverName": "claude-in-chrome" },
{ "serverName": "computer-use" },
{ "serverName": "ide" }
],
"allowManagedPermissionRulesOnly": true,
"forceRemoteSettingsRefresh": true,
"disableRemoteControl": true,
"permissions": {
"deny": [
"WebFetch",
"Projects",
"SendUserFile",
"ShareOnboardingGuide",
"Artifact",
"Read(~/.ssh/**)",
"Read(~/.aws/**)",
"Read(~/.config/gh/**)",
"Read(~/.npmrc)",
"Read(~/.claude/.credentials.json)",
"Read(~/.claude.json)",
"Read(~/.claude.json.backup*)",
"Read(~/.claude/backups/**)",
"Read(~/.git-credentials)",
"Read(~/.config/git/credentials)",
"Read(~/.netrc)",
"Read(~/_netrc)",
"Edit(~/.ssh/**)",
"Edit(~/.aws/**)",
"Edit(~/.config/gh/**)",
"Edit(~/.npmrc)",
"Edit(~/.claude/.credentials.json)",
"Edit(~/.claude.json)",
"Edit(~/.claude.json.backup*)",
"Edit(~/.claude/backups/**)",
"Edit(~/.git-credentials)",
"Edit(~/.config/git/credentials)",
"Edit(~/.netrc)",
"Edit(~/_netrc)"
],
"disableBypassPermissionsMode": "disable"
},
"strictKnownMarketplaces": [],
"strictPluginOnlyCustomization": true,
"disableSideloadFlags": true,
"crossSessionInbound": "refuse",
"enableArtifact": false,
"syncClaudeAiSkills": false,
"syncClaudeAiPlugins": false,
"skillOverrides": { "auto-mode-setup": "off" },
"autoMode": {
"environment": ["$defaults"],
"soft_deny": ["$defaults"],
"hard_deny": ["$defaults"],
"classifyAllShell": true
},
"sandbox": {
"enabled": true,
"failIfUnavailable": true,
"allowUnsandboxedCommands": false,
"enableWeakerNestedSandbox": false,
"enableWeakerNetworkIsolation": false,
"filesystem": {
"allowManagedReadPathsOnly": true,
"denyWrite": [
"~/.ssh",
"~/.aws/credentials",
"~/.aws/config",
"~/.npmrc",
"~/.git-credentials",
"~/.config/git/credentials",
"~/.netrc",
"~/_netrc",
"~/.claude/.credentials.json",
"~/.claude.json",
"~/.claude.json.backup*",
"~/.claude/backups"
]
},
"credentials": {
"files": [
{ "path": "~/.aws/credentials", "mode": "deny" },
{ "path": "~/.ssh", "mode": "deny" },
{ "path": "~/.npmrc", "mode": "deny" },
{ "path": "~/.git-credentials", "mode": "deny" },
{ "path": "~/.config/git/credentials", "mode": "deny" },
{ "path": "~/.netrc", "mode": "deny" },
{ "path": "~/_netrc", "mode": "deny" },
{ "path": "~/.claude/.credentials.json", "mode": "deny" },
{ "path": "~/.claude.json", "mode": "deny" },
{ "path": "~/.claude.json.backup*", "mode": "deny" },
{ "path": "~/.claude/backups", "mode": "deny" }
],
"envVars": [
{ "name": "AWS_ACCESS_KEY_ID", "mode": "deny" },
{ "name": "AWS_SECRET_ACCESS_KEY", "mode": "deny" },
{ "name": "AWS_SESSION_TOKEN", "mode": "deny" },
{ "name": "GITHUB_TOKEN", "mode": "deny" },
{ "name": "GH_TOKEN", "mode": "deny" },
{ "name": "GH_ENTERPRISE_TOKEN", "mode": "deny" },
{ "name": "GITHUB_ENTERPRISE_TOKEN", "mode": "deny" },
{ "name": "NPM_TOKEN", "mode": "deny" },
{ "name": "NODE_AUTH_TOKEN", "mode": "deny" },
{ "name": "YARN_NPM_AUTH_TOKEN", "mode": "deny" },
{ "name": "YARN_NPM_AUTH_IDENT", "mode": "deny" },
{ "name": "COREPACK_NPM_TOKEN", "mode": "deny" },
{ "name": "COREPACK_NPM_PASSWORD", "mode": "deny" },
{ "name": "COREPACK_NPM_USERNAME", "mode": "deny" },
{ "name": "BUN_CONFIG_TOKEN", "mode": "deny" },
{ "name": "ANTHROPIC_API_KEY", "mode": "deny" },
{ "name": "ANTHROPIC_AUTH_TOKEN", "mode": "deny" }
]
},
"network": {
"allowManagedDomainsOnly": true,
"allowAllUnixSockets": false,
"allowLocalBinding": false,
"allowedDomains": ["github.example.com", "registry.example.com"]
}
},
"cleanupPeriodDays": 30,
"env": {
"CLAUDE_CODE_ENABLE_TELEMETRY": "1",
"CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY": "1",
"DISABLE_ERROR_REPORTING": "1",
"DISABLE_FEEDBACK_COMMAND": "1",
"DISABLE_INSTALL_GITHUB_APP_COMMAND": "1",
"HTTPS_PROXY": "http://proxy.example.internal:8080",
"https_proxy": "http://proxy.example.internal:8080",
"HTTP_PROXY": "http://proxy.example.internal:8080",
"http_proxy": "http://proxy.example.internal:8080",
"NO_PROXY": "localhost,127.0.0.1,otel-collector.example.internal",
"no_proxy": "localhost,127.0.0.1,otel-collector.example.internal",
"OTEL_METRICS_EXPORTER": "otlp",
"OTEL_LOGS_EXPORTER": "otlp",
"OTEL_EXPORTER_OTLP_PROTOCOL": "http/protobuf",
"OTEL_EXPORTER_OTLP_ENDPOINT": "https://otel-collector.example.internal:4318",
"OTEL_LOG_USER_PROMPTS": "0",
"OTEL_LOG_ASSISTANT_RESPONSES": "0",
"OTEL_LOG_TOOL_DETAILS": "0",
"OTEL_LOG_TOOL_CONTENT": "0",
"OTEL_LOG_RAW_API_BODIES": "0"
}
}examples/settings/README.md (39 řádků)
Srovnávací tabulka a tipy.
# Settings Examples
Example Claude Code settings files, primarily intended for organization-wide deployments. Use these as starting points — adjust them to fit your needs.
These may be applied at any level of the [settings hierarchy](https://code.claude.com/docs/en/settings#settings-files), though certain properties only take effect if specified in enterprise settings (e.g. `strictKnownMarketplaces`, `allowManagedHooksOnly`, `allowManagedPermissionRulesOnly`).
## Configuration Examples
> [!WARNING]
> These examples are community-maintained snippets which may be unsupported or incorrect. You are responsible for the correctness of your own settings configuration.
| Setting | [`settings-lax.json`](./settings-lax.json) | [`settings-strict.json`](./settings-strict.json) | [`settings-bash-sandbox.json`](./settings-bash-sandbox.json) |
|---------|:---:|:---:|:---:|
| Disable `--dangerously-skip-permissions` | ✅ | ✅ | |
| Block plugin marketplaces | ✅ | ✅ | |
| Block user and project-defined permission `allow` / `ask` / `deny` | | ✅ | ✅ |
| Block user and project-defined hooks | | ✅ | |
| Deny web fetch and search tools | | ✅ | |
| Bash tool requires approval | | ✅ | |
| Bash tool must run inside of sandbox | | | ✅ |
## Tips
- Consider merging snippets of the above examples to reach your desired configuration
- Settings files must be valid JSON
- Before deploying configuration files to your organization, test them locally by applying to `managed-settings.json`, `settings.json` or `settings.local.json`
- The `sandbox` property only applies to the `Bash` tool; it does not apply to other tools (like Read, Write, WebSearch, WebFetch, MCPs), hooks, or internal commands
## Deploying via MDM
To distribute these settings as enterprise-managed policy through Jamf, Iru (Kandji), Intune, or Group Policy, see the deployment templates in [`../mdm`](../mdm).
## HIPAA deployments
For an organization that has the HIPAA configuration applied, [`settings-hipaa.json`](./settings-hipaa.json) and [`managed-mcp-hipaa.json`](./managed-mcp-hipaa.json) are a fuller `managed-settings.json` and `managed-mcp.json` pair with sandboxing, a network allowlist, credential protections, and local data retention. [`README-hipaa.md`](./README-hipaa.md) explains each choice and what to edit before deploying.
## Full Documentation
See https://code.claude.com/docs/en/settings for complete documentation on all available managed settings.
examples/settings/README-hipaa.md (155 řádků – zobrazeno 70 z 155 řádků)
Vysvětlení voleb a co upravit před deploy.
# HIPAA settings example
Example `managed-settings.json` and `managed-mcp.json` files for an organization that has the HIPAA configuration applied and wants to limit how session content can leave a developer's computer.
They apply whether or not the HIPAA configuration is in effect.
> [!WARNING]
> They are a sample that we recommend as a starting point.
> Your organization is responsible for deciding what its own environment needs and for confirming that its configuration meets those needs.
Requires Claude Code v2.1.285 or later, and Claude Desktop v2.19675.0 or later for the Code tab and Cowork.
Start with [Set up Claude Code (local mode) for a HIPAA-ready organization](https://code.claude.com/docs/en/hipaa-setup), which covers versions, network access, and a four-key starting sample.
For the Claude Desktop policy and Cowork, see [Set up Cowork (local mode) for a HIPAA-ready organization](https://claude.com/docs/cowork/hipaa-setup).
## Files
| File | Purpose |
|---|---|
| [`settings-hipaa.json`](./settings-hipaa.json) | Deploy as `managed-settings.json`. Sandboxed commands reach only the hosts you list, and the retention period for local session data is 30 days. [Tighten further](#tighten-further) lists optional changes. |
| [`managed-mcp-hipaa.json`](./managed-mcp-hipaa.json) | Deploy as `managed-mcp.json` beside the settings file to [turn MCP off](https://code.claude.com/docs/en/managed-mcp#disable-mcp-entirely). Keep the `mcpServers` key. |
The settings file also governs local sessions in the Code tab of Claude Desktop and, [by default](https://code.claude.com/docs/en/managed-settings#where-and-when-a-policy-applies), Cowork.
[Check which Claude Code managed settings apply in Cowork](https://claude.com/docs/cowork/hipaa-setup#check-which-claude-code-managed-settings-apply-in-cowork) lists what these keys change in Cowork.
## Edit before you deploy
On Windows, decide where each copy goes before you edit.
The sandbox can't run on native Windows or WSL1, so `sandbox.failIfUnavailable` makes Claude Code exit at startup there.
Run the terminal in WSL2 with the full file inside the distribution.
For the Code tab and Cowork, deploy a copy without the `sandbox` block to `C:\Program Files\ClaudeCode\managed-settings.json`.
1. Replace the `forceLoginOrgUUID` placeholder with your [organization ID](https://code.claude.com/docs/en/hipaa-setup#what-each-key-does).
Until it matches, Claude Code exits at startup for every claude.ai sign-in.
2. Replace `proxy.example.internal:8080` in the four proxy variables with your proxy.
If you have none, delete those four lines and the two `NO_PROXY` lines.
An unedited placeholder stops Claude Code from starting.
3. Point `OTEL_EXPORTER_OTLP_ENDPOINT` at your own collector, and put the collector's host in `NO_PROXY` and `no_proxy` beside `localhost` and `127.0.0.1`.
Those entries send exports straight to the collector, because a corporate proxy often can't reach an internal host, and keep local HTTP MCP servers and other loopback endpoints off the proxy.
If your proxy is the only route to the collector, leave only the two loopback entries.
4. Replace the placeholder hosts in `sandbox.network.allowedDomains` with your Git host and package registry.
If either host is internal, add it to `NO_PROXY` and `no_proxy` as in step 3, or the sandbox forwards those requests to your corporate proxy.
5. Set `cleanupPeriodDays` to your retention period.
6. Add the MCP servers, plugin marketplaces, and HTTP hook URLs you have reviewed to `allowedMcpServers`, `strictKnownMarketplaces`, and `allowedHttpHookUrls`.
As shipped, all three are empty.
Empty `allowedMcpServers` and `strictKnownMarketplaces` lists block everything, and `allowedHttpHookUrls` is one of the [lists that merge across scopes](#what-these-files-dont-cover).
7. Extend the `Read` and `Edit` rules in `permissions.deny`, `sandbox.filesystem.denyWrite`, and `sandbox.credentials` with your computers' other shells, `PATH` directories, and secrets.
Add an `Edit` rule for each credential path you add: `denyWrite` binds sandboxed commands, not Claude's own file edits.
Yarn and Bun configuration files (`~/.yarnrc`, `~/.yarnrc.yml`, `~/.bunfig.toml`) aren't hidden as shipped, because those tools can't start when they are; keep registry tokens in the hidden variables instead, and check that no token sits in those files on your computers.
On Linux and WSL2, a `denyWrite` entry with a wildcard is skipped, so spell paths out there; see [Sandbox path prefixes](https://code.claude.com/docs/en/settings-reference#sandbox-path-prefixes).
The denies match exact names, so cover the spellings your developers use: a relocated `XDG_CONFIG_HOME`, npm's `npm_config_` variables, and pointer variables such as `NPM_CONFIG_USERCONFIG` or `NETRC` aren't covered as shipped.
8. On Linux and WSL2, [install bubblewrap and socat](https://code.claude.com/docs/en/sandboxing#set-up-linux-and-wsl2).
9. In a container that lacks the privileges the sandbox needs, such as a dev container, every sandboxed command fails with a `bwrap` error about [mounting `/proc`](https://code.claude.com/docs/en/sandboxing#bubblewrap-fails-to-start-inside-a-container) while [`sandbox.enableWeakerNestedSandbox`](https://code.claude.com/docs/en/settings-reference#sandbox-enableweakernestedsandbox) is `false`, and `allowUnsandboxedCommands: false` leaves no fallback.
Claude Code usually still starts there, so check a command rather than the startup.
Deploy a copy with that key set to `true` in those containers, after you read what the weaker mode gives up.
## Tighten further
The file favors a working developer setup over the tightest possible one.
These optional changes tighten it:
- Set `cleanupPeriodDays` lower, for example `7`.
- Empty `sandbox.network.allowedDomains` so sandboxed commands reach no host at all.
`git` against your Git host and package installs then fail inside the sandbox.
- Add the home-directory files that later run or configure tools outside the sandbox, such as `~/.bashrc`, `~/.profile`, `~/.zshrc`, `~/.gitconfig`, `~/.config/autostart`, `~/Library/LaunchAgents`, and the package-manager files `~/.yarnrc`, `~/.yarnrc.yml` and `~/.bunfig.toml`, to `sandbox.filesystem.denyWrite`, with a matching `Edit` rule for each in `permissions.deny`.
On Linux and WSL2, create each listed path before you deploy: the sandbox stands in for a listed path that doesn't exist with [an unreadable placeholder](https://code.claude.com/docs/en/sandboxing#troubleshooting), so an absent `~/.yarnrc.yml` on that list stops every `yarn` command, and an empty `~/.bash_profile` or `~/.xinitrc` can break a login, so give the shell files real content.
## What the keys do
The [settings reference](https://code.claude.com/docs/en/settings-reference) describes each key in full.
Kvíz (14)
Co jsou managed settings a proč mají vyšší prioritu než uživatelská nastavení?
Jsou to nastavení vynucená organizací (soubor v systémové složce, MDM, politika). Stojí na vrcholu pořadí priorit a uživatel je nemůže přebít. Některé klíče (např. strictKnownMarketplaces, allowManagedHooksOnly) mají efekt jen tady.
Co přesně dělá permissions.disableBypassPermissionsMode: disable?
Zakáže režim obcházení oprávnění (--dangerously-skip-permissions). Bez toho by uživatel mohl všechna potvrzování vypnout.
Proč má strictKnownMarketplaces hodnotu prázdného pole a co to znamená?
Prázdný seznam povolených marketplace zdrojů znamená, že se nesmí přidat žádný marketplace. Správce pak případně doplní jen prověřené zdroje.
Čím se strict liší od lax?
Navíc: allowManagedPermissionRulesOnly (uživatelská a projektová allow/ask/deny se ignorují), allowManagedHooksOnly (cizí hooks se ignorují), deny pro WebSearch a WebFetch a ask pro Bash (každý příkaz potvrzuje člověk). Je tam i prázdný sandbox blok, ale sandbox sám zapnutý není.
Co dělá settings-bash-sandbox.json a jaký má limit?
Zapne sandbox.enabled, vypne allowUnsandboxedCommands (příkaz musí běžet v sandboxu) a nechá autoAllowBashIfSandboxed: false. Sandbox se týká jen nástroje Bash, ne Read, Write, WebSearch, WebFetch, MCP, hooks ani interních příkazů.
Proč se v sandbox.network používají prázdné allowedDomains?
Prázdný allowlist znamená, že sandboxovaný příkaz nedosáhne na žádnou doménu. Správce přidá jen to, co je nutné (v HIPAA ukázce Git host a registr balíčků).
Co je cílem HIPAA ukázky a co jí nelze „předat“ organizaci bez kontroly?
Omezit, jak může obsah session opustit počítač vývojáře. README upozorňuje, že jde o sample a organizace sama odpovídá za to, že konfigurace splňuje její potřeby. Nutno upravit zástupné hodnoty (UUID organizace, proxy, OTLP endpoint, domény).
Proč HIPAA ukázka zamítá Read a Edit u souborů typu ~/.ssh, ~/.aws, ~/.npmrc?
Obsahují přihlašovací údaje a secrets. Deny pravidla brání Claudovi tyto soubory číst i měnit; sandbox.filesystem.denyWrite a sandbox.credentials je chrání i pro sandboxované příkazy. Edit pravidla se přidávají zvlášť, protože denyWrite váže jen sandboxované příkazy, ne vlastní editace Claudea.
K čemu je sandbox.credentials.envVars s mode: deny?
Proměnné s tokeny (GITHUB_TOKEN, AWS_SECRET_ACCESS_KEY, ANTHROPIC_API_KEY …) jsou pro sandboxované příkazy skryté, takže je příkaz nemůže přečíst ani odeslat ven.
Proč má HIPAA ukázka sandbox.failIfUnavailable: true?
Kdyby sandbox nešel spustit (např. na nativním Windows nebo WSL1), Claude Code se ukončí při startu místo toho, aby tiše běžel bez ochrany. Na Windows se proto spouští v WSL2.
Co dělá forceLoginOrgUUID a co se stane, když ho nenahradím?
Vynutí přihlášení jen do dané organizace. Dokud je v něm zástupná hodnota, Claude Code se při startu ukončí pro každé přihlášení přes claude.ai.
Proč jsou OTEL_LOG_USER_PROMPTS a podobné nastaveny na 0?
Telemetrie přes OTLP posílá metriky a logy na vlastní collector organizace, ale nemá v nich být obsah promptů, odpovědí, detaily ani obsah nástrojů a surová těla API. Zapnout je lze jen vědomě.
Proč má managed-mcp-hipaa.json jen prázdný objekt mcpServers?
Prázdný managed-mcp.json vypne MCP úplně. Klíč mcpServers musí zůstat, aby soubor platil.
Jak před nasazením bezpečně vyzkoušet jinak hotový soubor?
README radí lokálně ho nasadit jako managed-settings.json, settings.json nebo settings.local.json a ověřit; soubory musí být platný JSON. Snippety lze slučovat.
Slovník pojmů (18)
managed-settings.json
Soubor se settings vynucenými organizací v systémové složce (nebo přes MDM). V příkladech je to formát, který se nasazuje.
permissions.disableBypassPermissionsMode
Volba, která zakáže režim --dangerously-skip-permissions; všechny tři úrovně příkladů ji obsahují.
strictKnownMarketplaces
Seznam povolených zdrojů plugin marketplaces. Prázdný = žádný marketplace nesmí být přidán; efekt má jen v enterprise settings.
allowManagedPermissionRulesOnly
Počítají se jen permission pravidla (allow/ask/deny) z managed settings; uživatelská a projektová se ignorují.
allowManagedHooksOnly
Spouštějí se jen hooks z managed settings. Chrání před hooks vloženými do repozitáře nebo uživatelského nastavení.
permissions.ask / deny
ask: nástroj vždy žádá potvrzení; deny: nástroj je zakázán. Ve strict jsou Bash v ask a WebSearch/WebFetch v deny.
sandbox
Izolace příkazů nástroje Bash (souborový systém, síť). Neplatí pro ostatní nástroje, MCP ani hooks.
autoAllowBashIfSandboxed
Zda se Bash příkazy v sandboxu schvalují automaticky. V příkladech je false.
allowUnsandboxedCommands
Zda smí příkaz opustit sandbox. V sandbox variantě false.
network.allowedDomains / allowManagedDomainsOnly
Seznam domén dostupných ze sandboxu; allowManagedDomainsOnly znamená, že se počítají jen domény z managed settings.
denyWrite / credentials
sandbox.filesystem.denyWrite zakáže zápis do cest; sandbox.credentials skryje soubory a proměnné s přihlašovacími údaji.
failIfUnavailable
Když sandbox nelze spustit, Claude Code skončí při startu.
forceLoginMethod / forceLoginOrgUUID
Vynucení způsobu přihlášení (claudeai) a konkrétní organizace.
allowedProviders
Povolení poskytovatelé modelů; v HIPAA ukázce jen anthropic.
managed-mcp.json / allowedMcpServers
managed-mcp.json vypíná nebo předepisuje MCP servery; allowedMcpServers je allowlist (prázdný = nic).
cleanupPeriodDays
Počet dní, po které se uchovávají lokální data session (HIPAA ukázka: 30).
OTEL / OTLP
OpenTelemetry a jeho protokol. Metriky a logy se exportují na collector organizace; proměnné OTEL_LOG_* určují, zda se do nich dostane obsah.
NO_PROXY / HTTPS_PROXY
Proměnné prostředí pro korporátní proxy a výjimky; zástupnou hodnotu proxy je nutné před deploy nahradit.
MDM
Popis
Složka examples/mdm obsahuje šablony pro plošné rozdistribuování managed settings přes MDM (Jamf, Iru/Kandji, Intune) nebo Group Policy. Všechny šablony kódují stejný minimální příklad: permissions.disableBypassPermissionsMode: disable. Liší se jen způsobem doručení na zařízení.
Šablony. managed-settings.json – obecný JSON pro systémovou konfigurační složku. macos/com.anthropic.claudecode.plist – payload Custom Settings pro Jamf nebo Iru (preference domain com.anthropic.claudecode). macos/com.anthropic.claudecode.mobileconfig – celý konfigurační profil (PayloadType Configuration, scope System) pro lokální test či MDM, které berou kompletní profil. windows/Set-ClaudeCodePolicy.ps1 – Intune Platform script, který zapíše managed-settings.json do C:\Program Files\ClaudeCode\. windows/ClaudeCode.admx (+ en-US/ClaudeCode.adml) – šablona Group Policy, která zapíše JSON jako jednořádkový REG_SZ do HKLM\SOFTWARE\Policies\ClaudeCode\Settings.
Proč právě takto. Nastavení doručená tímto způsobem leží na vrcholu pořadí priorit a uživatel je nemůže přebít. Každý operační systém má vlastní nativní mechanismus (plist/profil na macOS, soubor/registr na Windows), takže správce nemusí zasahovat do zařízení ručně a platforma sama hlídá, že se politika neztratí. Před plošným deploy se doporučuje otestovat na jednom stroji a v /status ověřit zdroj v Setting sources (např. Enterprise managed settings (plist) či (HKLM)). V .mobileconfig je nutné nahradit zástupné PayloadUUID a PayloadOrganization (uuidgen).
Aktuálnost a auditOvěřeno proti Claude Code 2.1.314 (aktuální verze v CHANGELOG.md i v kontejneru claude-t373). Nově: managed-settings.d/ (drop-in fragmenty slučované abecedně, každý tým svůj), odmítnutí startu při neparsovatelném zdroji (soubor, drop-in, plist i HKLM) a diagnostika selhání obnovy politiky v /status. Pozor na forceRemoteSettingsRefresh: 2.1.314 opravila případ, kdy po vypršení uložené kopie sezení startovalo bez politiky při nedostupném serveru.
Zdrojový kód
examples/mdm/managed-settings.json (5 řádků)
Obecný JSON pro systémovou složku.
{
"permissions": {
"disableBypassPermissionsMode": "disable"
}
}examples/mdm/macos/com.anthropic.claudecode.plist (11 řádků)
Payload pro Jamf / Iru Custom Settings.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>permissions</key>
<dict>
<key>disableBypassPermissionsMode</key>
<string>disable</string>
</dict>
</dict>
</plist>
examples/mdm/macos/com.anthropic.claudecode.mobileconfig (56 řádků)
Kompletní konfigurační profil.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PayloadDisplayName</key>
<string>Claude Code Managed Settings</string>
<key>PayloadDescription</key>
<string>Configures managed settings for Claude Code.</string>
<key>PayloadIdentifier</key>
<string>com.anthropic.claudecode.profile</string>
<key>PayloadOrganization</key>
<string>Example Organization</string>
<key>PayloadScope</key>
<string>System</string>
<key>PayloadType</key>
<string>Configuration</string>
<key>PayloadUUID</key>
<string>DC3CBC17-3330-4CDE-94AC-D2342E9C88A3</string>
<key>PayloadVersion</key>
<integer>1</integer>
<key>PayloadContent</key>
<array>
<dict>
<key>PayloadDisplayName</key>
<string>Claude Code</string>
<key>PayloadIdentifier</key>
<string>com.anthropic.claudecode.profile.BEFD5F54-71FC-4012-82B2-94399A1E220B</string>
<key>PayloadType</key>
<string>com.apple.ManagedClient.preferences</string>
<key>PayloadUUID</key>
<string>BEFD5F54-71FC-4012-82B2-94399A1E220B</string>
<key>PayloadVersion</key>
<integer>1</integer>
<key>PayloadContent</key>
<dict>
<key>com.anthropic.claudecode</key>
<dict>
<key>Forced</key>
<array>
<dict>
<key>mcx_preference_settings</key>
<dict>
<key>permissions</key>
<dict>
<key>disableBypassPermissionsMode</key>
<string>disable</string>
</dict>
</dict>
</dict>
</array>
</dict>
</dict>
</dict>
</array>
</dict>
</plist>
examples/mdm/windows/Set-ClaudeCodePolicy.ps1 (28 řádků)
Intune Platform script.
<#
Deploys Claude Code managed settings as a JSON file.
Intune: Devices > Scripts and remediations > Platform scripts > Add (Windows 10 and later).
Run this script using the logged on credentials: No
Run script in 64 bit PowerShell Host: Yes
Claude Code reads C:\Program Files\ClaudeCode\managed-settings.json at startup
and treats it as a managed policy source. Edit the JSON below to change the
deployed settings; see https://code.claude.com/docs/en/settings for available keys.
#>
$ErrorActionPreference = 'Stop'
$dir = Join-Path $env:ProgramFiles 'ClaudeCode'
New-Item -ItemType Directory -Path $dir -Force | Out-Null
$json = @'
{
"permissions": {
"disableBypassPermissionsMode": "disable"
}
}
'@
$path = Join-Path $dir 'managed-settings.json'
[System.IO.File]::WriteAllText($path, $json, (New-Object System.Text.UTF8Encoding($false)))
Write-Output "Wrote $path"examples/mdm/windows/ClaudeCode.admx (28 řádků)
Šablona Group Policy (ADMX).
<?xml version="1.0" encoding="utf-8"?>
<policyDefinitions xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/GroupPolicy/2006/07/PolicyDefinitions"
revision="1.0" schemaVersion="1.0">
<policyNamespaces>
<target prefix="claudecode" namespace="Anthropic.Policies.ClaudeCode" />
<using prefix="windows" namespace="Microsoft.Policies.Windows" />
</policyNamespaces>
<resources minRequiredRevision="1.0" />
<categories>
<category name="Cat_ClaudeCode" displayName="$(string.Cat_ClaudeCode)" />
</categories>
<policies>
<policy name="ManagedSettings"
class="Machine"
displayName="$(string.ManagedSettings)"
explainText="$(string.ManagedSettings_Explain)"
presentation="$(presentation.ManagedSettings)"
key="SOFTWARE\Policies\ClaudeCode">
<parentCategory ref="Cat_ClaudeCode" />
<supportedOn ref="windows:SUPPORTED_Windows_10_0" />
<elements>
<text id="SettingsJson" valueName="Settings" maxLength="1000000" required="true" />
</elements>
</policy>
</policies>
</policyDefinitions>examples/mdm/README.md (28 řádků)
Tabulka šablon a tipy.
# MDM Deployment Examples
Example templates for deploying Claude Code [managed settings](https://code.claude.com/docs/en/settings#settings-files) through Jamf, Iru (Kandji), Intune, or Group Policy. Use these as starting points — adjust them to fit your needs.
All templates encode the same minimal example (`permissions.disableBypassPermissionsMode`). See the [settings reference](https://code.claude.com/docs/en/settings#available-settings) for the full list of keys, and [`../settings`](../settings) for more complete example configurations.
## Templates
> [!WARNING]
> These examples are community-maintained templates which may be unsupported or incorrect. You are responsible for the correctness of your own deployment configuration.
| File | Use with |
| :--- | :--- |
| [`managed-settings.json`](./managed-settings.json) | Any platform. Deploy to the [system config directory](https://code.claude.com/docs/en/settings#settings-files). |
| [`macos/com.anthropic.claudecode.plist`](./macos/com.anthropic.claudecode.plist) | Jamf or Iru (Kandji) **Custom Settings** payload. Preference domain: `com.anthropic.claudecode`. |
| [`macos/com.anthropic.claudecode.mobileconfig`](./macos/com.anthropic.claudecode.mobileconfig) | Full configuration profile for local testing or MDMs that take a complete profile. |
| [`windows/Set-ClaudeCodePolicy.ps1`](./windows/Set-ClaudeCodePolicy.ps1) | Intune **Platform scripts**. Writes `managed-settings.json` to `C:\Program Files\ClaudeCode\`. |
| [`windows/ClaudeCode.admx`](./windows/ClaudeCode.admx) + [`en-US/ClaudeCode.adml`](./windows/en-US/ClaudeCode.adml) | Group Policy or Intune **Import ADMX**. Writes `HKLM\SOFTWARE\Policies\ClaudeCode\Settings` (REG_SZ, single-line JSON). |
## Tips
- Replace the placeholder `PayloadUUID` and `PayloadOrganization` values in the `.mobileconfig` with your own (`uuidgen`)
- Before deploying to your fleet, test on a single machine and confirm `/status` lists the source under **Setting sources** — e.g. `Enterprise managed settings (plist)` on macOS or `Enterprise managed settings (HKLM)` on Windows
- Settings deployed this way sit at the top of the precedence order and cannot be overridden by users
## Full Documentation
See https://code.claude.com/docs/en/settings#settings-files for complete documentation on managed settings and settings precedence.
Kvíz (12)
Co je MDM a proč se pro Claude Code používá?
Mobile Device Management je systém pro centrální správu zařízení (Jamf, Iru/Kandji, Intune). Slouží k plošnému doručení managed settings všem počítačům organizace, aby je uživatel nemohl přebít.
Jaké nastavení všechny šablony obsahují a proč zrovna to?
permissions.disableBypassPermissionsMode: disable – zakáže režim obcházení oprávnění. Je to minimální, srozumitelný příklad, který je snadné ověřit; ostatní klíče jsou v ../settings.
Který soubor použít pro Jamf nebo Iru a jaká je preference domain?
macos/com.anthropic.claudecode.plist jako Custom Settings payload; preference domain je com.anthropic.claudecode.
Kdy je lepší .mobileconfig než .plist?
Když je potřeba celý konfigurační profil – pro lokální testování nebo MDM, které přijímají kompletní profil. Má metadata (PayloadIdentifier, PayloadScope: System, PayloadUUID).
Co musím před nasazením .mobileconfig změnit?
Zástupné hodnoty PayloadUUID a PayloadOrganization; UUID se generuje uuidgen. Jedinečné UUID identifikuje profil v MDM.
Kam Set-ClaudeCodePolicy.ps1 zapisuje a jak ho spustit v Intune?
Do C:\Program Files\ClaudeCode\managed-settings.json (adresář vytvoří přes New-Item). V Intune: Devices → Scripts and remediations → Platform scripts, Run this script using the logged on credentials: No, Run in 64 bit PowerShell: Yes.
Proč skript zapisuje soubor jako UTF-8 bez BOM?
New-Object System.Text.UTF8Encoding($false) vypne BOM. JSON parser by na začátku souboru s BOM mohl selhat, takže je bezpečnější psát čisté UTF-8.
Jak funguje Group Policy varianta a kam zapisuje?
ADMX definuje politiku ManagedSettings s textovým prvkem SettingsJson (max. 1 000 000 znaků). Hodnota se uloží jako REG_SZ s jednořádkovým JSON pod HKLM\SOFTWARE\Policies\ClaudeCode\Settings. Texty rozhraní jsou v en-US/ClaudeCode.adml.
Jak ověřit, že politika opravdu platí?
Na jednom testovacím stroji spustit /status a zkontrolovat v Setting sources, že je uvedena např. Enterprise managed settings (plist) na macOS nebo (HKLM) na Windows.
Proč README varuje, že šablony mohou být nepodporované nebo nesprávné?
Jsou to komunitně udržované ukázky. Správce odpovídá za správnost nasazené konfigurace a musí ji ověřit v prostředí organizace.
Proč jsou nastavení nasazená přes MDM „nepřebitelná“?
Zdroj je na vrcholu pořadí priorit (enterprise managed). Uživatelské, projektové ani lokální settings je nepřepíšou; uživatel bez práv správce nemůže plist/registr změnit.
Co je nepřenosné mezi platformami v této ukázce?
Mechanismus doručení: plist/profil (macOS), soubor v Program Files nebo registr HKLM (Windows). Obsah – JSON se settings – je shodný, proto ukázky kódují totéž.
Slovník pojmů (15)
MDM
Centrální správa zařízení; v ukázce Jamf, Iru (Kandji) a Intune.
Group Policy
Windows mechanismus pro plošnou konfiguraci počítačů v doméně; zde přes šablonu ADMX.
ADMX / ADML
ADMX definuje strukturu politiky (kategorie, klíč registru, prvky); ADML nese lokalizované texty (zde en-US).
Custom Settings payload
Typ payloadu v Jamf/Iru pro libovolnou preferenci; zde plist s doménou com.anthropic.claudecode.
preference domain
Jmenný prostor preferencí na macOS; Claude Code čte doménu com.anthropic.claudecode.
plist
Property list – XML formát nastavení na macOS. Zde zapisuje klíče permissions a disableBypassPermissionsMode.
mobileconfig (konfigurační profil)
Soubor profilu Apple pro MDM; obsahuje identifikátory, scope a pole PayloadContent.
PayloadUUID / PayloadOrganization
Povinné údaje profilu; zástupné hodnoty se musí před použitím nahradit vlastními.
Intune Platform script
Skript doručený přes Intune a spuštěný na zařízení; zde zapíše managed-settings.json.
REG_SZ / HKLM
REG_SZ je textová hodnota registru; HKLM (HKEY_LOCAL_MACHINE) je větev platná pro celý počítač a vyžaduje práva správce.
managed policy source
Zdroj nastavení, který Claude Code při startu čte a považuje za politiku organizace (soubor, plist nebo registr).
Setting sources (/status)
Seznam zdrojů nastavení v /status; slouží k ověření, že MDM politika dorazila.
pořadí priorit settings
Managed (enterprise) > příkazový řádek > lokální > projektové > uživatelské. MDM leží nahoře.
UTF-8 bez BOM
Kódování souboru bez znaku pořadí bajtů; skript ho nastavuje, aby JSON parser nenarazil na nečekané znaky.
systémová konfigurační složka
Místo, kde Claude Code hledá managed-settings.json (na Windows C:\Program Files\ClaudeCode).
Gateway – AWS
Popis
Příklad Claude apps gateway na AWS ukazuje referenční deploy brány claude gateway (podkomando binárky Claude Code), která stojí mezi vývojáři a modely. Upstream je Amazon Bedrock, identitu zajišťuje IdP (v šabloně Okta přes OIDC). Soubory slouží jako funkční příklad, ne jako podporovaný produkční deploy – je třeba je přizpůsobit prostředí.
Architektura. ECS Fargate (nebo EKS) kontejner za interním Application Load Balancerem, RDS pro PostgreSQL v privátních subnetech bez veřejné adresy (store brány), secrets v AWS Secrets Manager, IAM role úlohy pro přístup k Bedrocku bez statických klíčů. Tři security groups oddělují ALB, bránu a databázi. Sestavení umí dvě cesty: skript setup.sh (příkazy aws CLI, idempotentní, celý průvodce §1–7) a terraform/ (dvouprůchodový apply, protože Terraform vytvoří ECR repozitář, ale nesestaví image).
Dockerfile. Neprovádí build binárky – očekává hotový nativní claude executable. Základem je distroless/cc-debian12:nonroot pinovaný digestem (build nikdy neodebere tiše nové bajty), běží jako uživatel nonroot (uid 65532), gateway.yaml se zapéká do image a image obsahuje CA bundle RDS (NODE_EXTRA_CA_CERTS), aby spojení sslmode=verify-full ověřilo certifikát i hostname. Konfigurace neobsahuje žádné secrets; ty se doplňují za běhu přes ${ENV_VAR} (ECS task definition je vkládá z Secrets Manager).
gateway.yaml.example. Sekce listen (povinný public_url, který fixuje redirect_uri a issuer tokenů a nikdy se neodvozuje z hlavičky Host; trusted_proxies pro X-Forwarded-For za ALB), oidc (issuer, client_id, allowed_email_domains), session (jwt_secret ≥ 32 bajtů, ttl_hours: 8), store (povinný Postgres, bez něj se brána nespustí) a upstreams (provider bedrock, region, auth: {} = výchozí AWS řetězec přihlášení, tj. role úlohy).
Aktuálnost a auditOvěřeno proti Claude Code 2.1.314 (aktuální verze v CHANGELOG.md i v kontejneru claude-t373). Gateway v 2.1.314 přibyly: volitelný seznam groups u upstreamů (jen vývojáři z uvedených skupin IdP se pošlou na daný upstream, i při failoveru) a guardrail_trace u Bedrock upstreamů (loguje, který filtr Bedrock guardrail zabral, bez dotčeného textu). Šablona gateway.yaml.example je neobsahuje – dopiš je podle potřeby. Image základ je pinovaný digestem; digest je třeba po revizi občas obnovit.
Zdrojový kód
examples/gateway/aws/Dockerfile (67 řádků)
Runtime image brány (distroless, nonroot, zapečená konfigurace).
# Runtime image for `claude gateway`.
#
# This image does NOT build the binary. It expects a prebuilt native
# linux-x64 `claude` executable in the build context — the Claude Code release
# binary, which includes the `gateway` subcommand. setup.sh places it at
# ./claude (downloading and checksum-verifying it via DIST_URL/DIST_SHA256 if
# missing). Override CLAUDE_BINARY to point at a different path.
#
# Unlike the GCP example (which mounts the config from Secret Manager at
# runtime), this image BAKES gateway.yaml in at /etc/claude/gateway.yaml — on
# ECS the task definition injects only the secrets the YAML references, as env
# vars. gateway.yaml therefore must be fully filled in (no REPLACE_ME) before
# building; setup.sh enforces this. A config edit means a rebuild under a new
# tag. The file contains no secret values — every credential resolves at boot
# via ${ENV_VAR} expansion.
#
# The image also bakes in the AWS RDS CA bundle (rds-global-bundle.pem —
# setup.sh downloads it from https://truststore.pki.rds.amazonaws.com before
# the build) and trusts it via NODE_EXTRA_CA_CERTS, so the store connection
# string's `?sslmode=verify-full` verifies the RDS server certificate chain
# and hostname. NOTE the gateway's driver reads `sslmode` from the URL but NOT
# a libpq-style `sslrootcert=` param — the CA must come from this env var.
#
# Build:
# docker build --platform=linux/amd64 --provenance=false \
# --build-arg CLAUDE_BINARY=./claude -t claude-gateway .
#
# (For Fargate on ARM64/Graviton: build --platform=linux/arm64 with the
# linux-arm64 binary and set the task definition's cpuArchitecture to ARM64.)
#
# Run:
# docker run --rm -p 8080:8080 \
# -e OIDC_CLIENT_SECRET -e GATEWAY_JWT_SECRET -e GATEWAY_POSTGRES_URL \
# claude-gateway
ARG CLAUDE_BINARY=./claude
ARG GATEWAY_CONFIG=./gateway.yaml
ARG RDS_CA_BUNDLE=./rds-global-bundle.pem
# distroless/cc provides glibc + libstdc++ (required by the Bun-compiled
# native binary). The :nonroot tag runs as uid/gid 65532. Pinned by digest so
# the build never silently takes new upstream bytes (the digest is the
# multi-arch OCI index, so --platform still selects amd64/arm64). To refresh
# the pin after reviewing upstream changes:
# docker manifest inspect -v gcr.io/distroless/cc-debian12:nonroot # prints the index digest
FROM gcr.io/distroless/cc-debian12:nonroot@sha256:ce0d66bc0f64aae46e6a03add867b07f42cc7b8799c949c2e898057b7f75a151
ARG CLAUDE_BINARY
ARG GATEWAY_CONFIG
ARG RDS_CA_BUNDLE
COPY --chmod=0755 ${CLAUDE_BINARY} /usr/local/bin/claude
# WORKDIR pre-creates /etc/claude with 0755 — without it, COPY --chmod would
# also stamp the auto-created parent directory 0644 (no execute bit), making
# the config unreadable for the nonroot user.
WORKDIR /etc/claude
COPY --chmod=0644 ${GATEWAY_CONFIG} /etc/claude/gateway.yaml
COPY --chmod=0644 ${RDS_CA_BUNDLE} /etc/claude/rds-global-bundle.pem
WORKDIR /
ENV CLAUDE_CONFIG_DIR=/tmp/.claude
# Trust anchor for the store's sslmode=verify-full (see header comment).
ENV NODE_EXTRA_CA_CERTS=/etc/claude/rds-global-bundle.pem
EXPOSE 8080
USER nonroot
ENTRYPOINT ["/usr/local/bin/claude", "gateway", "--config", "/etc/claude/gateway.yaml"]examples/gateway/aws/gateway.yaml.example (174 řádků – zobrazeno 120 z 174 řádků)
Šablona konfigurace; REPLACE_ME se musí nahradit před buildem.
# gateway.yaml.example — Claude apps gateway config template, AWS-shaped (walkthrough §4).
#
# Okta IdP + Bedrock upstream, following the walkthrough at
# https://code.claude.com/docs/en/claude-apps-gateway-on-aws. The active sections
# below are a strict subset of the full configuration reference at
# https://code.claude.com/docs/en/claude-apps-gateway-config; optional keys are
# included commented-out.
#
# USAGE — this is the shippable TEMPLATE. Copy it to gateway.yaml and fill it in:
# cp gateway.yaml.example gateway.yaml
# setup.sh and terraform/ read gateway.yaml (your filled-in copy, which is
# gitignored). Unlike the GCP example it is NOT published to a secret store:
# the Dockerfile bakes it into the image at /etc/claude/gateway.yaml — the
# container ENTRYPOINT runs `claude gateway --config /etc/claude/gateway.yaml`.
# It holds no secret values; a config edit means an image rebuild (setup.sh
# tags images with a hash of this file, so a re-run rebuilds automatically).
#
# Secret expansion: ${ENV_VAR} reads an env var; ${file:/path} reads a mounted file.
# On ECS, the task definition injects the JWT / OIDC / Postgres secrets as ENV
# VARS via its `secrets` field (valueFrom -> Secrets Manager ARN). On EKS you
# may mount them as files instead and use ${file:/secrets/...}.
#
# BEFORE BUILD — replace every REPLACE_ME placeholder below (setup.sh refuses to
# build the image while any remain — the config is baked in, so a half-filled
# config would ship), and create the referenced secrets:
# gateway-jwt-secret (setup.sh generates this)
# gateway-oidc-client-secret (from the Okta admin console OIDC web app)
# gateway-postgres-url (setup.sh generates this)
# ── Listener ─────────────────────────────────────────────────────────────────
listen:
host: 0.0.0.0
port: 8080 # the target group forwards ALB :443 -> :8080
# Required. Fixes the IdP redirect_uri, the OIDC discovery doc, and the
# gateway-token issuer so none are derived from the client-controlled Host
# header (X-Forwarded-Host/-Proto are likewise never trusted). Set it to the
# internal hostname you picked in the prerequisites — the Route 53 private
# zone name your ACM certificate covers (e.g.
# https://claude-gateway.internal.example.com). Unlike Cloud Run there is no
# first-deploy placeholder dance: you choose the hostname up front, alias it
# to the internal ALB after the deploy, and register the same host's
# /oauth/callback on the Okta app.
public_url: REPLACE_ME
# Register this exact redirect URI on the Okta OIDC web application:
# https://<public_url host>/oauth/callback
#
# Behind the internal ALB every request arrives via the load balancer, so the
# gateway sees ALB-node peer IPs for all developers — set trusted_proxies so
# X-Forwarded-For from those proxies is trusted and per-IP rate limiting /
# audit IPs record the real client. ALB nodes take addresses from the subnets
# the ALB is attached to, so list those subnets' CIDRs (the private subnets
# from the prerequisites).
#
# NOTE: listing the ALB subnets' CIDRs trusts every host in those subnets as a
# proxy — any co-located workload that can reach the ALB can then spoof the
# client IP via X-Forwarded-For (audit logs, per-IP rate limits, IP
# allowlists). Keep the ALB :443 ingress source (CORP_CIDR / corporate_cidr)
# from overlapping these subnets, and don't share the subnets with untrusted
# workloads.
trusted_proxies: [REPLACE_ME] # e.g. [10.0.1.0/24, 10.0.2.0/24]
#
# Alternative — terminate TLS in the gateway itself instead of at the ALB:
# tls:
# cert: /certs/gateway.crt
# key: /certs/gateway.key
# ── Identity provider — Okta ─────────────────────────────────────────────────
oidc:
issuer: REPLACE_ME # e.g. https://example.okta.com (or your custom auth server URL)
client_id: REPLACE_ME # Okta OIDC web app client ID (not secret)
client_secret: ${OIDC_CLIENT_SECRET} # EKS file mounts: ${file:/secrets/oidc-client-secret}
allowed_email_domains: [REPLACE_ME] # e.g. [example.com] — reject id_tokens outside your org
# The Okta org authorization server returns a thin id_token that omits email
# and groups; the gateway fills them from /userinfo.
userinfo_fallback: true
# offline_access yields refresh tokens (silent renewal + the deprovision
# leash); Okta emits groups only when the `groups` scope is requested AND the
# app's groups claim filter allows them (Okta admin console -> the app's
# Sign On tab -> OpenID Connect ID Token -> Groups claim filter).
scopes: [openid, profile, email, offline_access, groups]
# groups_claim: groups # Okta default. Entra app roles=roles; see the config reference
# ca_cert_pem: ${file:/secrets/idp-ca.pem} # only for an IdP behind a private CA
# ── Sessions ─────────────────────────────────────────────────────────────────
session:
jwt_secret: ${GATEWAY_JWT_SECRET} # >= 32 bytes; openssl rand -base64 32
# Okta issues refresh tokens (offline_access above), so sessions renew
# silently and this mainly bounds deprovision latency. 8 is a sane default;
# lower toward 1 for tighter revocation. Array form rotates keys:
# [new, old] (index 0 signs, all verify).
ttl_hours: 8
# ── Store (REQUIRED — the gateway refuses to boot without it) ─────────────────
store:
postgres_url: ${GATEWAY_POSTGRES_URL} # private-subnet RDS; built with ?sslmode=verify-full by setup.sh
# (the image trusts the RDS CA bundle via NODE_EXTRA_CA_CERTS — see Dockerfile)
# ── Upstreams — Amazon Bedrock ───────────────────────────────────────────────
upstreams:
- provider: bedrock
# Must equal the region you provision in (setup.sh's AWS_REGION /
# terraform's region): the IAM policy's inference-profile ARNs are scoped
# to that region, and Bedrock model access is enabled there (cross-region
# us.anthropic.* profiles need access in every spanned region). NOTE: the
# walkthrough is scoped to US regions — the built-in model catalog maps to
# us.anthropic.* (US-geo) profiles; a non-US region also needs a models:
# list below (see the model catalog section).
region: REPLACE_ME # e.g. us-east-1
auth: {} # AWS default credential chain: ECS task role / IRSA on EKS (preferred — no static keys)
# base_url: https://bedrock-runtime.us-east-1.amazonaws.com # bedrock-runtime interface VPC endpoint, to keep model traffic off the public path
# Add more upstreams for failover (tried top→bottom on 5xx/timeout/501): a
# second region, or an anthropic/vertex fallback. See
# https://code.claude.com/docs/en/claude-apps-gateway.
# ── Telemetry fan-out (OPTIONAL) ─────────────────────────────────────────────
# The CLI sends OTLP/HTTP to the gateway; the gateway fans out, stamping
# user.id/user.email/user.groups server-side. On AWS, point at an OpenTelemetry
# Collector (e.g. the AWS Distro for OpenTelemetry -> CloudWatch / Managed
# Prometheus). When forward_to and public_url are both configured the gateway
# pushes CLAUDE_CODE_ENABLE_TELEMETRY and the OTEL exporter selectors to everyexamples/gateway/aws/terraform/main.tf (510 řádků – zobrazeno 130 z 510 řádků)
Security groups, IAM role a další zdroje (celkem přes 480 řádků).
# Claude apps gateway on ECS Fargate — Terraform equivalent of setup.sh.
# Section markers (§N) map to setup.sh and the walkthrough:
# https://code.claude.com/docs/en/claude-apps-gateway-on-aws
#
# Unlike the GCP example this module does NOT create the network — the VPC and
# private subnets are walkthrough prerequisites, passed in as variables.
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
# Read (not created) so a typo'd VPC or subnet ID fails the plan up front
# instead of half-applying.
data "aws_vpc" "this" {
id = var.vpc_id
}
data "aws_subnet" "private" {
for_each = toset(var.private_subnet_ids)
id = each.value
}
locals {
config_path = var.gateway_config_path != "" ? var.gateway_config_path : "${path.module}/../gateway.yaml"
gateway_config = file(local.config_path)
image = "${aws_ecr_repository.repo.repository_url}:${var.image_tag}"
}
# ── 1 Security groups ───────────────────────────────────────────────────────
# Three groups chain the traffic path: corp network -> ALB :443, ALB ->
# gateway :8080, gateway -> Postgres :5432. Nothing else is reachable.
# Rules are separate resources (not inline) so they never fight other tooling.
resource "aws_security_group" "alb" {
name = "claude-gateway-alb"
description = "Claude gateway ALB"
vpc_id = var.vpc_id
}
resource "aws_security_group" "gateway" {
name = "claude-gateway-svc"
description = "Claude gateway service"
vpc_id = var.vpc_id
}
resource "aws_security_group" "db" {
name = "claude-gateway-db"
description = "Claude gateway Postgres"
vpc_id = var.vpc_id
}
resource "aws_vpc_security_group_ingress_rule" "alb_https" {
security_group_id = aws_security_group.alb.id
description = "HTTPS from the corporate network"
ip_protocol = "tcp"
from_port = 443
to_port = 443
cidr_ipv4 = var.corporate_cidr
}
resource "aws_vpc_security_group_ingress_rule" "gateway_from_alb" {
security_group_id = aws_security_group.gateway.id
description = "Gateway port from the ALB"
ip_protocol = "tcp"
from_port = 8080
to_port = 8080
referenced_security_group_id = aws_security_group.alb.id
}
resource "aws_vpc_security_group_ingress_rule" "db_from_gateway" {
security_group_id = aws_security_group.db.id
description = "Postgres from the gateway"
ip_protocol = "tcp"
from_port = 5432
to_port = 5432
referenced_security_group_id = aws_security_group.gateway.id
}
# Egress: the ALB only needs to reach its targets; the gateway needs the NAT
# path out (Bedrock, the IdP, Secrets Manager, ECR, CloudWatch Logs) plus
# Postgres. The DB group needs no egress (security groups are stateful).
resource "aws_vpc_security_group_egress_rule" "alb_to_gateway" {
security_group_id = aws_security_group.alb.id
description = "Health checks + forwarding to gateway tasks"
ip_protocol = "tcp"
from_port = 8080
to_port = 8080
referenced_security_group_id = aws_security_group.gateway.id
}
resource "aws_vpc_security_group_egress_rule" "gateway_all" {
security_group_id = aws_security_group.gateway.id
description = "Egress to Bedrock, the IdP, Secrets Manager, ECR, CloudWatch Logs, Postgres"
ip_protocol = "-1"
cidr_ipv4 = "0.0.0.0/0"
}
# ── 2 IAM roles (least-privilege) ───────────────────────────────────────────
# Task role: the gateway's runtime identity. Its ONLY permission is invoking
# Claude models on Bedrock — the upstream's `auth: {}` resolves to this role
# via the AWS default credential chain. The policy must cover both the
# cross-region inference-profile ARNs and the underlying foundation-model ARNs.
data "aws_iam_policy_document" "ecs_trust" {
statement {
effect = "Allow"
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ecs-tasks.amazonaws.com"]
}
}
}
resource "aws_iam_role" "task" {
name = var.task_role_name
assume_role_policy = data.aws_iam_policy_document.ecs_trust.json
}
resource "aws_iam_role_policy" "bedrock_invoke" {
name = "bedrock-invoke"
role = aws_iam_role.task.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"]
Resource = [
"arn:aws:bedrock:${data.aws_region.current.region}:${data.aws_caller_identity.current.account_id}:inference-profile/us.anthropic.*",
"arn:aws:bedrock:*::foundation-model/anthropic.*",
]
}]
})examples/gateway/aws/setup.sh (964 řádků – zobrazeno 110 z 964 řádků)
Skript, který provede celý průvodce přes aws CLI.
#!/usr/bin/env bash
#
# setup.sh — AWS setup for Claude apps gateway (walkthrough §1–7, ECS track).
#
# Provisions, in this order: the three security groups (§1), the task +
# execution IAM roles (§2), the gateway container image in Amazon ECR (§6),
# an RDS for PostgreSQL instance in the private subnets with no public
# address (§3), the JWT + postgres-url secrets (§5), and an ECS Fargate
# service behind an internal Application Load Balancer (§7).
#
# gateway.yaml (§4 of the walkthrough) is BAKED INTO THE IMAGE on this track —
# the task definition injects only the secrets it references, as env vars — so
# the config step here lives inside the image build (§6): the build is gated on
# a fully filled-in gateway.yaml and the image tag carries a hash of it, so a
# config edit triggers a rebuild on the next run.
#
# Section markers (§N) below map to the walkthrough:
# https://code.claude.com/docs/en/claude-apps-gateway-on-aws
#
# Covers here: security groups (§1) -> IAM roles + Bedrock model-access note (§2)
# -> build & push image, config baked in (§6 + §4) -> DB subnet group
# + RDS instance (§3) -> jwt + postgres-url secrets (§5) -> ECS
# cluster/task definition/service + internal ALB (§7, ECS Fargate tab).
# Not covered: EKS track (§7's EKS tab) — ECS Fargate is the lower-friction path here.
# Bedrock model access (§2) — console-only; the script reminds you.
# Route 53 alias — see the next steps it prints. Client MDM
# push (§8) is covered by the walkthrough, not this script.
#
# Idempotent: existing resources are detected and skipped, so it is safe to re-run.
# Reuse is by NAME, so a pre-existing resource may not match what this script
# would have created: reuse that would change the exposure model is fatal (an
# ALB that is not internal/in ${VPC_ID}); upsert-able settings are converged on
# every run; other posture drift (extra security group ingress, a public or
# unencrypted RDS instance, wrong-VPC target group) is checked and warned
# about, never silently adopted.
# Override any default below via environment variable, e.g. `AWS_REGION=us-west-2 ./setup.sh`.
set -euo pipefail
# ---- configuration (env-overridable) ----------------------------------------
AWS_REGION="${AWS_REGION:-$(aws configure get region 2>/dev/null || true)}" # guide uses us-east-1 (a region where Bedrock serves the Claude models you need)
ACCOUNT_ID="${ACCOUNT_ID:-$(aws sts get-caller-identity --query Account --output text 2>/dev/null || true)}"
VPC_ID="${VPC_ID:-}" # REQUIRED — the VPC from the prerequisites
PRIVATE_SUBNETS="${PRIVATE_SUBNETS:-}" # REQUIRED — two+ private subnet IDs in different AZs, space-separated
CORP_CIDR="${CORP_CIDR:-}" # REQUIRED — your corporate network CIDR (ALB :443 ingress source)
# Must not overlap PRIVATE_SUBNETS: hosts there are trusted_proxies (gateway.yaml) and could spoof client IPs via X-Forwarded-For.
# §1 security groups
ALB_SG_NAME="${ALB_SG_NAME:-claude-gateway-alb}"
GW_SG_NAME="${GW_SG_NAME:-claude-gateway-svc}"
DB_SG_NAME="${DB_SG_NAME:-claude-gateway-db}"
# §2 IAM roles (task role = the gateway's runtime AWS identity; execution role
# = the ECS agent's identity for pulling the image and injecting secrets)
TASK_ROLE="${TASK_ROLE:-claude-gateway-task}"
EXEC_ROLE="${EXEC_ROLE:-claude-gateway-execution}"
# §6 image
ECR_REPO="${ECR_REPO:-claude-gateway}" # ECR repository name
VERSION="${VERSION:-}" # REQUIRED — the gateway release tag you build and push (e.g. the linux-x64 binary's version)
DOCKERFILE="${DOCKERFILE:-./Dockerfile}"
CLAUDE_BINARY="${CLAUDE_BINARY:-./claude}" # prebuilt linux-x64 Claude Code release binary (includes the gateway subcommand)
DIST_URL="${DIST_URL:-}" # optional: download URL, used only if $CLAUDE_BINARY is missing
DIST_SHA256="${DIST_SHA256:-}" # REQUIRED with DIST_URL: expected sha256 of the binary (verified fail-closed)
DIST_SHA256="${DIST_SHA256,,}" # normalize to lowercase — openssl emits lowercase hex; some tools (PowerShell Get-FileHash) publish uppercase
# Obtain DIST_SHA256 out-of-band — never from the server that serves DIST_URL.
# For binaries from the standard Claude Code release channel, verify the
# release's GPG-signed manifest.json and copy the platform checksum from it:
# https://code.claude.com/docs/en/setup#binary-integrity-and-code-signing
# For any other distribution channel, use the checksum published alongside the
# download link on that channel.
GATEWAY_YAML="${GATEWAY_YAML:-./gateway.yaml}" # §4 config file — BAKED into the image
RDS_CA_BUNDLE="${RDS_CA_BUNDLE:-./rds-global-bundle.pem}" # RDS CA trust anchor — BAKED into the image (downloaded below if missing)
# Official AWS RDS truststore. AWS rotates this bundle (new regional CAs get
# appended), so no checksum is pinned — a pinned hash would break on every
# rotation. The script downloads it only when absent (an existing file is never
# re-downloaded); to pick up a rotation, delete the file — and since the image
# tag hashes only gateway.yaml, also bump VERSION or set IMAGE_TAG so the
# next run rebuilds rather than reusing the existing tag. Operators who want
# to pin may pre-place a reviewed copy at ${RDS_CA_BUNDLE}.
RDS_CA_BUNDLE_URL="${RDS_CA_BUNDLE_URL:-https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem}"
REGISTRY="${ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"
# §3 RDS
DB_SUBNET_GROUP="${DB_SUBNET_GROUP:-claude-gateway-db}"
DB_PARAM_GROUP="${DB_PARAM_GROUP:-claude-gateway-db}" # carries rds.force_ssl=1 (server-side TLS enforcement)
DB_INSTANCE="${DB_INSTANCE:-claude-gateway-db}"
DB_CLASS="${DB_CLASS:-db.t4g.micro}"
DB_STORAGE_GB="${DB_STORAGE_GB:-20}"
DB_NAME="${DB_NAME:-claude_gateway}"
DB_USER="${DB_USER:-gateway}"
# PG14+ supported; 16 is the recommended default (matches terraform/'s).
# Always pinned: the instance's engine version and the parameter group's
# family must name the same major, so both derive from this one value.
DB_ENGINE_VERSION="${DB_ENGINE_VERSION:-16}"
SECRET_NAME="${SECRET_NAME:-gateway-postgres-url}" # §5 store.postgres_url
JWT_SECRET_NAME="${JWT_SECRET_NAME:-gateway-jwt-secret}" # §5 session.jwt_secret
OIDC_SECRET_NAME="${OIDC_SECRET_NAME:-gateway-oidc-client-secret}" # operator-created (Okta OIDC web app)
# NOTE: the execution role's secrets-read policy (§2) is built from these
# three names, one per-secret ARN prefix each — a rename is picked up on the
# next run (put-role-policy is an upsert).
# §7 ECS + internal ALB deploy
CLUSTER="${CLUSTER:-claude-gateway}"
SERVICE="${SERVICE:-claude-gateway}"
TASK_FAMILY="${TASK_FAMILY:-claude-gateway}"
LOG_GROUP="${LOG_GROUP:-/ecs/claude-gateway}"
LOG_RETENTION_DAYS="${LOG_RETENTION_DAYS:-90}" # CloudWatch retention — the group carries the gateway's audit events, so align with your audit retention policyexamples/gateway/aws/README.md (19 řádků)
Přehled souborů.
# Claude apps gateway on AWS
Reference deployment artifacts for running Claude apps gateway on AWS with
Amazon Bedrock as the upstream: ECS on Fargate or EKS, Amazon RDS for
PostgreSQL, AWS Secrets Manager, and IAM-role auth to Bedrock.
These files are provided as a working example rather than a supported production
deployment. Adapt them to your own environment.
- **Walkthrough**: https://code.claude.com/docs/en/claude-apps-gateway-on-aws
- **Related**: AWS-maintained samples for various customer environments at
https://github.com/aws-samples/anthropic-on-aws/tree/main/claude-apps-gateway
| File | Purpose |
|---|---|
| `setup.sh` | Scripts the walkthrough end to end via the `aws` CLI |
| `Dockerfile` | Runtime image for the `claude gateway` binary (bakes in `gateway.yaml`) |
| `gateway.yaml.example` | Gateway config template, AWS-shaped (Bedrock upstream, Okta IdP) |
| `terraform/` | Provisions the full architecture (two-pass apply — see `terraform/README.md`) |
examples/gateway/aws/terraform/README.md (182 řádků – zobrazeno 60 z 182 řádků)
Předpoklady a dvouprůchodový apply.
# Claude apps gateway — Terraform (ECS Fargate)
Terraform equivalent of `../setup.sh`. Lets end-users provision and manage
the gateway with `terraform apply`. Covers the same scope ([walkthrough](https://code.claude.com/docs/en/claude-apps-gateway-on-aws) §1–7,
ECS track): security groups → task + execution IAM roles → ECR repository →
private-subnet RDS for PostgreSQL → Secrets Manager secrets → ECS Fargate
service behind an internal ALB. The VPC and private subnets are walkthrough
prerequisites, passed in as variables — unlike the GCP example, no network is
created here.
## Files
| File | Purpose |
|------|---------|
| `versions.tf` | Provider pins (aws, random) |
| `variables.tf` | All inputs (defaults match `setup.sh`'s) |
| `main.tf` | Resources |
| `outputs.tf` | ALB DNS name + zone ID, image, roles, DB endpoint |
| `terraform.tfvars.example` | Copy to `terraform.tfvars` and edit |
## Prerequisites
1. **`../gateway.yaml` created and FULLY filled in** — copy the template first:
`cp ../gateway.yaml.example ../gateway.yaml`, then replace every `REPLACE_ME`
(Terraform reads this file and enforces no `REPLACE_ME` via a precondition).
Unlike the GCP example there is no placeholder-first-pass: the config is
**baked into the image**, and `public_url` is your own internal hostname,
which you choose up front (you already hold its ACM certificate).
`gateway.yaml` is gitignored; the committed template is `gateway.yaml.example`.
2. The **prebuilt linux-x64 `claude` binary at `../claude`** — the Claude Code
release binary, which includes the `gateway` subcommand (see the
[walkthrough](https://code.claude.com/docs/en/claude-apps-gateway-on-aws)).
See `../setup.sh`'s `DIST_URL`/`DIST_SHA256` download path for a
checksum-verified fetch.
3. A **VPC with two+ private subnets** in different AZs and NAT egress, an **ACM
certificate** for your internal gateway hostname, and **Bedrock model access**
enabled in the console (cross-region `us.anthropic.*` profiles need it in each
region the profile spans), with the one-time use case form submitted.
4. A **remote backend** for shared use (see below). State holds secrets — never commit it.
## Deploy
Terraform creates the ECR repository but does **not** build/push the image, so
the apply is two passes: a targeted apply to create the repo, then build/push,
then the full apply.
```bash
cp terraform.tfvars.example terraform.tfvars # edit it
terraform init
# Pin providers in your copy (once, then commit .terraform.lock.hcl and drop
# its .gitignore line): versions.tf pins by range only, so without a committed
# lock the registry serves the newest in-range build — a platform-complete
# lock gives hash continuity across machines/CI and makes provider upgrades
# reviewable diffs.
terraform providers lock -platform=linux_amd64 -platform=linux_arm64 \
-platform=darwin_amd64 -platform=darwin_arm64 -platform=windows_amd64
# 1. Create just the ECR repository (the -target warning is expected):
terraform apply -target=aws_ecr_repository.repo
Kvíz (15)
Co je Claude apps gateway a jakou roli hraje Bedrock?
Brána claude gateway je server mezi klienty Claude Code a modely: ověřuje uživatele přes OIDC, drží sessions a směruje požadavky na upstream. V AWS příkladu je upstream Amazon Bedrock (provider: bedrock).
Proč je ALB interní a RDS v privátních subnetech bez veřejné adresy?
Brána má sloužit jen interním vývojářům. Interní ALB není dostupný z internetu a databáze nesmí být vystavena vůbec. Skript reuse zdrojů hlídá: změna modelu expozice (ALB není internal / ve VPC) je fatální chyba.
K čemu jsou tři security groups?
Oddělují vrstvy: ALB (příchozí HTTPS z korporátní sítě), brána (příchozí jen z ALB) a databáze (příchozí jen z brány). Každá vrstva smí komunikovat jen s další.
Proč se gateway.yaml zapéká do image a co z toho plyne?
Na ECS task definition vkládá jen secrets jako env proměnné; konfigurace je součástí image na /etc/claude/gateway.yaml. Úprava konfigurace znamená nový build s novým tagem (setup.sh tagy odvozuje od hashe souboru, takže se rebuild děje automaticky). Soubor neobsahuje secrets.
Jak se do konfigurace dostávají secrets, když jsou v ní jen odkazy?
Přes expanzi ${ENV_VAR} (nebo ${file:/path}) při startu. Secrets OIDC_CLIENT_SECRET, GATEWAY_JWT_SECRET a GATEWAY_POSTGRES_URL vkládá ECS z AWS Secrets Manageru (valueFrom ARN).
Proč Dockerfile používá distroless a pinuje ho digestem?
distroless/cc obsahuje jen glibc a libstdc++ potřebné pro binárku – žádný shell ani balíčkovač, tedy menší plocha útoku. Digest zaručuje, že build nikdy tiše nepřevezme nové bajty ze změněného tagu; obnova pinu se dělá vědomě po revizi.
Proč kontejner běží jako uživatel nonroot a co dělá WORKDIR před COPY?
Tag :nonroot běží jako uid/gid 65532 – kompromitovaný proces nemá práva roota. WORKDIR /etc/claude vytvoří adresář s právy 0755; jinak by COPY --chmod zapsal i automaticky vytvořenému rodiči 0644 a uživatel by nemohl číst konfiguraci.
K čemu je CA bundle RDS a proměnná NODE_EXTRA_CA_CERTS?
Připojení k Postgresu používá ?sslmode=verify-full, které ověřuje řetěz certifikátů i hostname. Ovladač čte sslmode z URL, ale ne libpq parametr sslrootcert=, proto se CA musí dodat přes NODE_EXTRA_CA_CERTS.
Co je listen.public_url a proč je povinné?
Pevně určuje redirect_uri pro IdP, OIDC discovery dokument a issuer tokenů brány. Nikdy se neodvozuje z hlavičky Host ani z X-Forwarded-*, které klient může podvrhnout. Stejný host s /oauth/callback se registruje v Oktě.
Proč nastavit trusted_proxies a jaké je riziko?
Za ALB vidí brána jako peer IP uzly balanceru. Se trusted_proxies se X-Forwarded-For od nich věří, takže per-IP rate limiting a audit zaznamenají skutečného klienta. Riziko: CIDR subnetů důvěřuje každému hostu v nich, tedy workload ve stejných subnetech by mohl IP podvrhnout. Proto ALB ingress nesmí překrývat tyto subnety a subnety se nesdílí s nedůvěryhodnými workloady.
Co znamená auth: {} u upstreamu Bedrock a proč je to preferované?
Použije se výchozí AWS řetěz přihlášení: role úlohy ECS (nebo IRSA na EKS). Nejsou potřeba statické klíče, které se mohou ztratit či uniknout.
Proč musí region v konfiguraci odpovídat regionu infrastruktury?
IAM politika má ARN inference profilů omezené na ten region a Bedrock přístup k modelům je povolen tam. Cross-region profily us.anthropic.* vyžadují přístup v každém regionu, který zahrnují.
Proč je Terraform apply dvouprůchodový?
Terraform vytvoří ECR repozitář, ale nesestaví a nenahraje image. Nejdřív se cílený apply vytvoří repozitář, pak se image sestaví a pushne a až poté proběhne plný apply.
Jak se brána chová při selhání upstreamu a jak lze nastavit failover?
Další upstreamy (druhý region nebo anthropic/vertex) se zkouší shora dolů při 5xx, timeoutu nebo 501. Přidají se do seznamu upstreams.
Jaká je role session.ttl_hours a offline_access?
ttl_hours: 8 omezuje dobu platnosti session; s refresh tokeny (offline_access) se session obnovují tiše, takže ttl hlavně omezuje latenci zrušení účtu. Nižší hodnota (blízko 1) = rychlejší odebrání přístupu.
Slovník pojmů (18)
claude gateway
Podpříkaz binárky Claude Code, který spustí bránu (listener, OIDC, sessions, store, upstreams). Spouští ho ENTRYPOINT v Dockerfile.
upstream
Cíl, kam brána směruje požadavky na model. Zde bedrock v daném regionu; lze přidat záložní.
Amazon Bedrock
Služba AWS pro přístup k modelům. Zde zdroj modelů; přístup se povoluje v konzoli a v IAM.
ECS Fargate
Provoz kontejnerů bez správy serverů. Úloha je definovaná task definition.
ALB (internal)
Application Load Balancer dostupný jen z privátní sítě; terminuje TLS (certifikát z ACM) a přeposílá na port 8080 brány.
RDS for PostgreSQL
Spravovaná databáze v privátním subnetu; store brány, bez kterého se brána nespustí.
Secrets Manager
Služba AWS pro ukládání secrets. ECS z ní vkládá OIDC_CLIENT_SECRET, JWT secret a Postgres URL jako env proměnné.
task role / execution role
Dvě IAM role: task role dává kontejneru přístup k Bedrocku; execution role umožňuje ECS stáhnout image a přečíst secrets.
OIDC / IdP / Okta
OpenID Connect je protokol přihlášení; IdP je poskytovatel identity (Okta). Brána ověřuje id_token a plní e-mail a skupiny z /userinfo.
allowed_email_domains
Seznam e-mailových domén, jejichž id_tokeny se přijmou; ostatní se odmítnou.
jwt_secret
Klíč pro podpis tokenů brány (≥ 32 bajtů, generuje openssl rand -base64 32). Pole [new, old] umožňuje rotaci.
trusted_proxies
CIDR proxy, jejichž X-Forwarded-For brána věří. Bez něj by všichni klienti měli IP ALB.
sslmode=verify-full
Režim TLS k Postgresu, který ověří řetěz certifikátů i hostname serveru.
distroless / nonroot
Minimální image bez shellu; uživatel s uid 65532 bez práv roota.
digest pinning
Odkaz na image přes neměnný hash obsahu (@sha256:…), nikoli pohyblivý tag.
Terraform two-pass apply
První cílený apply vytvoří ECR; po push image proběhne plný apply.
idempotentní skript
Opakované spuštění existující zdroje detekuje a přeskočí; setup.sh je takový.
IRSA
IAM Roles for Service Accounts – způsob, jak pod EKS dát podu IAM roli bez statických klíčů.
Gateway – GCP
Popis
Příklad Claude Gateway na Google Cloud je protějšek AWS varianty. Upstream je Agent Platform (dříve Vertex AI; v konfiguraci provider: vertex), IdP je Google Workspace, kontejner běží na Cloud Run (nebo GKE), databází je Cloud SQL pro PostgreSQL pouze s privátní IP a secrets leží v Secret Manageru. Soubory jsou funkční příklad, nikoli podporovaný produkční deploy.
Rozdíly proti AWS. (1) gateway.yaml se nezapéká do image, ale publikuje se jako secret gateway-config a mountuje do /etc/claude/gateway.yaml (Cloud Run nemůže připojit více secrets do jednoho adresáře, takže JWT, OIDC a Postgres URL jdou jako proměnné prostředí a jako soubor jen konfigurace). (2) public_url je zpočátku zástupný https://set-after-first-deploy.invalid, protože URL run.app se přidělí až prvním deployem; přihlášení nefunguje, dokud se nenastaví skutečné URL a skript znovu nepublikuje konfiguraci. (3) Privátní IP Cloud SQL je nutné kvůli organizační politice constraints/sql.restrictPublicIp, takže skript navíc vytvoří VPC a Private Services Access. (4) Cloud Run používá Direct VPC egress k dosažení databáze. (5) Auth upstreamu je auth: {} = Application Default Credentials přes servisní účet Cloud Run (nebo Workload Identity na GKE), tedy bez statických klíčů.
Dockerfile. Stejně jako u AWS očekává předem sestavenou binárku claude (distroless/cc-debian12:nonroot, uživatel nonroot, port 8080, CLAUDE_CONFIG_DIR=/tmp/.claude) a konfigurace se připojí za běhu. Terraform (terraform/) vytváří stejnou architekturu: API, servisní účet, Artifact Registry, VPC, Cloud SQL, secrets a Cloud Run službu s IAM vazbami.
Aktuálnost a auditOvěřeno proti Claude Code 2.1.314 (aktuální verze v CHANGELOG.md i v kontejneru claude-t373). Platí stejné novinky jako u AWS (groups u upstreamů). 2.1.314 navíc opravila situaci, kdy Vertex upstream brány minuty visel, protože Google token endpoint přijal spojení a nikdy neodpověděl. Základní image distroless/cc-debian12:nonroot není u GCP varianty pinovaný digestem (AWS varianta ano) – pro reprodukovatelný build ho pinuj.
Zdrojový kód
examples/gateway/gcp/Dockerfile (35 řádků)
Runtime image bez zapečené konfigurace.
# syntax=docker/dockerfile:1
# Runtime image for `claude gateway`.
#
# This image does NOT build the binary. It expects a prebuilt native
# linux-x64 `claude` executable in the build context — the public Claude Code
# release binary, which includes the `gateway` subcommand. setup.sh places it
# at ./claude (downloading it from the public release endpoint and verifying
# it against the release manifest if missing). Override CLAUDE_BINARY to
# point at a different path.
#
# Build (with the binary at ./claude; otherwise add --build-arg CLAUDE_BINARY=<path>):
# docker build --platform=linux/amd64 --provenance=false -t claude-gateway .
#
# Run:
# docker run --rm -p 8080:8080 \
# -v "$PWD/gateway.yaml:/etc/claude/gateway.yaml:ro" \
# -e OIDC_CLIENT_SECRET -e GATEWAY_JWT_SECRET -e GATEWAY_POSTGRES_URL \
# claude-gateway
ARG CLAUDE_BINARY=./claude
# distroless/cc provides glibc + libstdc++ (required by the Bun-compiled
# native binary). The :nonroot tag runs as uid/gid 65532.
FROM gcr.io/distroless/cc-debian12:nonroot
ARG CLAUDE_BINARY
COPY --chmod=0755 ${CLAUDE_BINARY} /usr/local/bin/claude
ENV CLAUDE_CONFIG_DIR=/tmp/.claude
EXPOSE 8080
USER nonroot
ENTRYPOINT ["/usr/local/bin/claude", "gateway", "--config", "/etc/claude/gateway.yaml"]examples/gateway/gcp/gateway.yaml.example (156 řádků – zobrazeno 110 z 156 řádků)
Šablona konfigurace pro Google Workspace a Agent Platform.
# gateway.yaml.example — Claude Gateway config template, GCP-shaped (walkthrough §6).
#
# Google Workspace IdP + Agent Platform (formerly Vertex AI) upstream, following
# the walkthrough at https://code.claude.com/docs/en/claude-apps-gateway-on-gcp.
# The active sections
# below are a strict subset of the full configuration reference at
# https://code.claude.com/docs/en/claude-apps-gateway; optional keys are included
# commented-out.
#
# USAGE — this is the shippable TEMPLATE. Copy it to gateway.yaml and fill it in:
# cp gateway.yaml.example gateway.yaml
# setup.sh and terraform/ read gateway.yaml (your filled-in copy, which is
# gitignored). It is published as the Secret Manager secret `gateway-config`
# (§6) and mounted at /etc/claude/gateway.yaml — the container ENTRYPOINT runs
# `claude gateway --config /etc/claude/gateway.yaml`.
#
# Secret expansion: ${ENV_VAR} reads an env var; ${file:/path} reads a mounted file.
# On Cloud Run, setup.sh injects the JWT / OIDC / Postgres secrets as ENV VARS
# (Cloud Run can't mount multiple secrets into a single directory), and mounts
# only gateway.yaml itself as a file at /etc/claude. On GKE you may use file mounts.
#
# BEFORE DEPLOY — replace every REPLACE_ME placeholder below (setup.sh refuses to
# publish the config secret while any remain), and create the referenced secrets:
# gateway-jwt-secret (setup.sh generates this)
# gateway-oidc-client-secret (from the Google Cloud Console OAuth client)
# gateway-postgres-url (setup.sh generates this)
# ── Listener ─────────────────────────────────────────────────────────────────
listen:
host: 0.0.0.0
port: 8080 # Cloud Run sets PORT=8080; leave as-is
# Required. Fixes the IdP redirect_uri, the OIDC discovery doc, and the
# gateway-token issuer so none are derived from the client-controlled Host
# header (X-Forwarded-Host/-Proto are likewise never trusted). On Cloud Run
# the run.app URL is only assigned on the first deploy, so this starts as a
# placeholder for the provisioning-only first pass (login does NOT work until
# the real URL is set). After the first deploy, setup.sh prints the run.app
# URL: set it here (or your LB hostname) and re-run; setup.sh republishes the
# config and redeploys. Register the same host's /oauth/callback on the
# Google OAuth client.
public_url: https://set-after-first-deploy.invalid
# Register this exact redirect URI on the Google OAuth client:
# https://<public_url host>/oauth/callback
#
# On Cloud Run (or behind any L7 LB) every request arrives via Google's front
# end, so the gateway sees one peer IP for all developers — set trusted_proxies
# so X-Forwarded-For from those proxies is trusted and per-IP rate limiting /
# audit IPs record the real client. 169.254.0.0/16 is Cloud Run's fixed
# link-local serving range; the proxy-only subnet is the one your internal ALB
# uses in this VPC.
# trusted_proxies:
# - 169.254.0.0/16 # Cloud Run serving proxy (link-local peer)
# - <proxy-only-subnet-cidr> # add if fronted by your internal ALB (its proxy-only subnet)
#
# Alternative — terminate TLS in the gateway itself instead of at a proxy:
# tls:
# cert: /certs/gateway.crt
# key: /certs/gateway.key
# ── Identity provider — Google Workspace ─────────────────────────────────────
oidc:
issuer: https://accounts.google.com
client_id: REPLACE_ME # Google OAuth client ID (not secret; from Cloud Console)
client_secret: ${OIDC_CLIENT_SECRET}
allowed_email_domains: [REPLACE_ME] # e.g. [example.com] — reject id_tokens outside your org
# Google ignores the default offline_access scope; these two are what actually
# yield refresh tokens (silent renewal + the deprovision leash) from Google.
scopes: [openid, profile, email]
extra_auth_params: { access_type: offline, prompt: consent }
# NOTE: Google id_tokens carry NO groups claim. For group-based RBAC with
# Google as IdP, set `google_groups` (below) and the gateway fetches each
# user's Workspace groups at login via the Admin SDK Directory API.
# Otherwise, use email_domain matching (see managed.policies below).
# google_groups:
# service_account_json_path: /secrets/google-sa.json # SA with domain-wide delegation on admin.directory.group.readonly
# admin_email: admin@example.com # a Workspace admin the SA impersonates
# groups_claim: groups # Okta=groups, Entra app roles=roles — NOT Google
# ca_cert_pem: ${file:/secrets/idp-ca.pem} # only for an IdP behind a private CA
# ── Sessions ─────────────────────────────────────────────────────────────────
session:
jwt_secret: ${GATEWAY_JWT_SECRET} # >= 32 bytes; openssl rand -base64 32
# Google issues refresh tokens (above), so sessions renew silently and this
# mainly bounds deprovision latency. 8 is a sane default; lower toward 1 for
# tighter revocation. Array form rotates keys: [new, old] (index 0 signs, all verify).
ttl_hours: 8
# ── Store (REQUIRED — the gateway refuses to boot without it) ─────────────────
store:
postgres_url: ${GATEWAY_POSTGRES_URL} # private-IP Cloud SQL; built with ?sslmode=require by setup.sh
# ── Upstreams — Agent Platform ───────────────────────────────────────────────
upstreams:
- provider: vertex
region: us-east5 # a region where the Claude models you need are published in Model Garden
project_id: REPLACE_ME # your GCP project ID for Agent Platform access
auth: {} # ADC via Cloud Run SA / GKE Workload Identity (preferred — no static keys)
# base_url: https://us-east5-aiplatform.p.googleapis.com # Private Service Connect endpoint
# Add more upstreams for failover (tried top→bottom on 5xx/timeout/501): a
# second region, or an anthropic/bedrock fallback. See
# https://code.claude.com/docs/en/claude-apps-gateway.
# ── Telemetry fan-out (OPTIONAL) ─────────────────────────────────────────────
# The CLI sends OTLP/HTTP to the gateway; the gateway fans out, stamping
# user.id/user.email/user.groups server-side. On GCP, point at an OpenTelemetry
# Collector with the googlecloud exporter (-> Cloud Trace / Managed Prometheus).
# Takes effect after the second pass (once public_url is the real URL, not the
# placeholder): when forward_to and public_url are both configured the gateway pushes
# CLAUDE_CODE_ENABLE_TELEMETRY and the OTEL exporter selectors to every client
# automatically — no per-developer config needed.examples/gateway/gcp/terraform/main.tf (399 řádků – zobrazeno 140 z 399 řádků)
API, servisní účet, Artifact Registry, VPC a Cloud SQL (celkem přes 400 řádků).
# Claude Gateway on Cloud Run — Terraform equivalent of setup.sh.
# Section markers (§N) map to setup.sh and the walkthrough:
# https://code.claude.com/docs/en/claude-apps-gateway-on-gcp
locals {
config_path = var.gateway_config_path != "" ? var.gateway_config_path : "${path.module}/../gateway.yaml"
gateway_config = file(local.config_path)
image = "${var.region}-docker.pkg.dev/${var.project_id}/${var.ar_repo}/${var.image_name}:${var.image_tag}"
apis = [
"aiplatform.googleapis.com",
"artifactregistry.googleapis.com",
"cloudresourcemanager.googleapis.com",
"sqladmin.googleapis.com",
"secretmanager.googleapis.com",
"iamcredentials.googleapis.com",
"iam.googleapis.com",
"compute.googleapis.com",
"servicenetworking.googleapis.com",
"run.googleapis.com",
]
}
# ── 1 Project & API setup ───────────────────────────────────────────────────
resource "google_project_service" "apis" {
for_each = toset(local.apis)
project = var.project_id
service = each.value
# Don't disable APIs (or delete anything) when this config is torn down.
disable_on_destroy = false
disable_dependent_services = false
}
# ── 2 Service account & IAM (least-privilege) ───────────────────────────────
resource "google_service_account" "gateway" {
project = var.project_id
account_id = var.sa_name
display_name = "Claude Gateway"
depends_on = [google_project_service.apis]
}
# Non-authoritative (_member) so we never clobber other project bindings.
#
# Only aiplatform.user is granted: the gateway reaches Cloud SQL over the VPC at
# its private IP with a password user (direct TCP via Direct VPC egress — see §7
# below), not via the Cloud SQL Auth Proxy / connector, so it never calls
# cloudsql.instances.connect and no roles/cloudsql.client grant is needed.
# Direct private-IP keeps the gateway's store a plain postgres_url with no proxy
# sidecar/socket plumbing, and the connection string is portable across Cloud
# Run and GKE.
resource "google_project_iam_member" "vertex" {
project = var.project_id
role = "roles/aiplatform.user" # Agent Platform inference
member = "serviceAccount:${google_service_account.gateway.email}"
}
# ── 3 Artifact Registry repo ────────────────────────────────────────────────
# NOTE: image build/push is a separate step (see README) — Terraform only makes the repo.
resource "google_artifact_registry_repository" "repo" {
project = var.project_id
location = var.region
repository_id = var.ar_repo
format = "DOCKER"
description = "Claude Gateway container images"
depends_on = [google_project_service.apis]
}
# ── 4 VPC + Private Services Access ──────────────────────────────────────────
resource "google_compute_network" "vpc" {
project = var.project_id
name = var.vpc_network
auto_create_subnetworks = false
depends_on = [google_project_service.apis]
}
resource "google_compute_subnetwork" "subnet" {
project = var.project_id
name = var.subnet
region = var.region
network = google_compute_network.vpc.id
ip_cidr_range = var.subnet_range
}
resource "google_compute_global_address" "psa_range" {
project = var.project_id
name = "google-managed-services-${var.vpc_network}"
purpose = "VPC_PEERING"
address_type = "INTERNAL"
prefix_length = var.psa_prefix_length
network = google_compute_network.vpc.id
}
resource "google_service_networking_connection" "psa" {
network = google_compute_network.vpc.id
service = "servicenetworking.googleapis.com"
reserved_peering_ranges = [google_compute_global_address.psa_range.name]
# ABANDON: on destroy, leave the producer peering in place (deleting it can hang
# and would affect any other private-IP service on this VPC).
deletion_policy = "ABANDON"
# If the peering already exists (e.g. a previous apply failed partway), patch it
# instead of failing the create.
update_on_creation_fail = true
depends_on = [google_project_service.apis]
}
# ── 4 Cloud SQL (private IP only) ───────────────────────────────────────────
resource "google_sql_database_instance" "db" {
project = var.project_id
name = var.db_instance
region = var.region
database_version = var.db_version
deletion_protection = var.deletion_protection
depends_on = [google_service_networking_connection.psa]
settings {
tier = var.db_tier
ip_configuration {
ipv4_enabled = false # private IP only (org policy: sql.restrictPublicIp)
private_network = google_compute_network.vpc.id
ssl_mode = "ENCRYPTED_ONLY"
}
}
}
resource "google_sql_database" "db" {
project = var.project_id
name = var.db_name
instance = google_sql_database_instance.db.name
}
# URL-safe (alphanumeric) so it drops cleanly into the connection string.
# nosemgrep: terraform-generic-secrets-in-state -- secrets in tfstate are inherent to TF; mitigated by the documented remote GCS backend (see README "Remote state")
resource "random_password" "db" {
length = 32
special = false
}
# nosemgrep: terraform-gcp-secrets-in-state -- secrets in tfstate are inherent to TF; mitigated by the documented remote GCS backend (see README "Remote state")
resource "google_sql_user" "gateway" {
project = var.project_idexamples/gateway/gcp/setup.sh (558 řádků – zobrazeno 100 z 558 řádků)
Skript, který provede průvodce přes gcloud.
#!/usr/bin/env bash
#
# setup.sh — GCP setup for Claude Gateway (walkthrough §1–7b).
#
# Provisions, in doc order: APIs (§1), service account + IAM (§2), the gateway
# container image in Artifact Registry (§3), a Cloud SQL (PostgreSQL) backend
# with PRIVATE IP only (§4), the JWT + postgres-url secrets (§5), the
# gateway.yaml config secret (§6), and a Cloud Run deploy with Direct VPC
# egress (§7b).
#
# Private IP is required because public IP is disallowed by the org-policy constraint
# `constraints/sql.restrictPublicIp`. A Cloud SQL private IP is an address inside a VPC,
# so §4 here also provisions the prerequisite VPC + Private Services Access — the
# one-time, irreducible networking required for private IP.
#
# Section markers (§N) below map to the walkthrough:
# https://code.claude.com/docs/en/claude-apps-gateway-on-gcp
#
# Covers here: APIs (§1) -> service account + IAM (§2) -> build & push image (§3)
# -> VPC + Private Services Access -> Cloud SQL (private IP only) -> database
# + user (§4) -> jwt + postgres-url secrets (§5) -> gateway-config
# secret from gateway.yaml (§6) -> Cloud Run deploy (§7b).
# Not covered: GKE track (§7a) — Cloud Run is the lower-friction path here.
#
# Idempotent: existing resources are detected and skipped, so it is safe to re-run.
# Override any default below via environment variable, e.g. `REGION=us-east5 ./setup.sh`.
set -euo pipefail
# ---- configuration (env-overridable) ----------------------------------------
PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project 2>/dev/null)}"
REGION="${REGION:-${CLOUDSDK_COMPUTE_REGION:-us-east5}}" # guide §1 uses us-east5 (Agent Platform model region)
SA_NAME="${SA_NAME:-claude-gateway}" # §2 service account
SA_EMAIL="${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"
# §3 image
AR_REPO="${AR_REPO:-claude-gateway}" # Artifact Registry repository
IMAGE_NAME="${IMAGE_NAME:-gateway}"
RELEASES_URL="${RELEASES_URL:-https://downloads.claude.ai/claude-code-releases}" # public Claude Code release endpoint
VERSION="${VERSION:-}" # Claude Code release to deploy; empty = latest release (resolved below)
VERSION_FILE="${VERSION_FILE:-./.claude-version}" # pins the resolved release across re-runs; delete it (or set VERSION) to upgrade
DOCKERFILE="${DOCKERFILE:-./Dockerfile}"
CLAUDE_BINARY="${CLAUDE_BINARY:-./claude}" # linux-x64 Claude Code binary; downloaded from RELEASES_URL if missing
CLAUDE_SHA256="${CLAUDE_SHA256:-}" # optional: out-of-band sha256 pin for the downloaded binary, checked in addition to the release manifest
VPC_NETWORK="${VPC_NETWORK:-cc-gateway-vpc}"
SUBNET="${SUBNET:-cc-gateway-subnet}"
SUBNET_RANGE="${SUBNET_RANGE:-10.0.0.0/24}"
PSA_RANGE_NAME="${PSA_RANGE_NAME:-google-managed-services-${VPC_NETWORK}}"
PSA_PREFIX_LENGTH="${PSA_PREFIX_LENGTH:-16}" # /16 is GCP's recommendation; reserved, not consumed
DB_INSTANCE="${DB_INSTANCE:-claude-gateway-db}"
DB_VERSION="${DB_VERSION:-POSTGRES_16}" # PG14+ supported; 16 is the recommended default (§4)
DB_TIER="${DB_TIER:-db-g1-small}"
DB_NAME="${DB_NAME:-claude_gateway}"
DB_USER="${DB_USER:-gateway}"
SECRET_NAME="${SECRET_NAME:-gateway-postgres-url}" # §5 store.postgres_url
JWT_SECRET_NAME="${JWT_SECRET_NAME:-gateway-jwt-secret}" # §5 session.jwt_secret
GATEWAY_YAML="${GATEWAY_YAML:-./gateway.yaml}" # §6 config file
CONFIG_SECRET="${CONFIG_SECRET:-gateway-config}" # §6 mounted at /etc/claude/gateway.yaml
# §7 Cloud Run deploy
SERVICE_NAME="${SERVICE_NAME:-claude-gateway}"
OIDC_SECRET_NAME="${OIDC_SECRET_NAME:-gateway-oidc-client-secret}" # operator-created (Google OAuth client)
DEPLOY="${DEPLOY:-1}" # set DEPLOY=0 to provision only, no Cloud Run deploy
INGRESS="${INGRESS:-internal}" # internal (default; no public URL) | internal-and-cloud-load-balancing (only if you front it with your own internal ALB)
MAX_INSTANCES="${MAX_INSTANCES:-8}" # keep MAX_INSTANCES × store.max_connections (default 5) below the DB tier's max_connections (~50 on db-g1-small); raise the tier before raising this
# ---- helpers ----------------------------------------------------------------
log() { printf '\n==> %s\n' "$*"; }
skip() { printf ' (exists) %s\n' "$*"; }
curl_https() { curl --proto '=https' --proto-redir '=https' --tlsv1.2 "$@"; } # refuse plaintext/protocol-downgrade
sha_of() { openssl dgst -sha256 "$1" | awk '{print $NF}'; } # openssl avoids shasum/sha256sum portability gaps
if [[ -z "${PROJECT_ID}" ]]; then
echo "ERROR: PROJECT_ID is not set and no gcloud default project is configured." >&2
echo " Set it with: export PROJECT_ID=<your-project> (or 'gcloud config set project ...')" >&2
exit 1
fi
# VERSION tags the image and selects the public Claude Code release to download.
# The first resolved value is pinned to ${VERSION_FILE} so the documented
# re-runs (fill gateway.yaml -> re-run; set public_url -> re-run) don't silently
# build and deploy a newer release mid-bootstrap.
if [[ -z "${VERSION}" && -f "${VERSION_FILE}" ]]; then
VERSION="$(< "${VERSION_FILE}")"
log "Using release pinned in ${VERSION_FILE}: ${VERSION} (delete the file or set VERSION to change it)"
elif [[ -z "${VERSION}" ]]; then
# /latest is the channel the official installer (claude.ai/install.sh) uses.
VERSION="$(curl_https -fsSL "${RELEASES_URL}/latest" | tr -d '[:space:]' || true)"
if [[ -z "${VERSION}" ]]; then
echo "ERROR: could not resolve the latest release from ${RELEASES_URL}/latest." >&2
echo " Set VERSION to a Claude Code release version, e.g. export VERSION=2.1.195" >&2
exit 1
fi
log "VERSION not set — using latest Claude Code release: ${VERSION}"
fiexamples/gateway/gcp/README.md (17 řádků)
Přehled souborů.
# Claude Gateway on Google Cloud
Reference deployment artifacts for running Claude Gateway on GCP with Agent
Platform (formerly Vertex AI) as the upstream: Cloud Run or GKE, Cloud SQL for
PostgreSQL, Secret Manager, and service-account auth to Agent Platform.
These files are provided as a working example rather than a supported production
deployment. Adapt them to your own environment.
- **Walkthrough**: https://code.claude.com/docs/en/claude-apps-gateway-on-gcp
| File | Purpose |
|---|---|
| `setup.sh` | Scripts the walkthrough end to end via `gcloud` |
| `Dockerfile` | Runtime image for the `claude gateway` binary |
| `gateway.yaml.example` | Gateway config template, GCP-shaped (Agent Platform upstream, Google Workspace IdP) |
| `terraform/` | Provisions the full architecture (two-pass apply — see `terraform/README.md`) |
Kvíz (13)
Z jakých částí se GCP architektura skládá?
Cloud Run (kontejner brány), Cloud SQL PostgreSQL s privátní IP (store), Secret Manager (JWT, OIDC secret, Postgres URL a konfigurace), Artifact Registry (image), VPC s Private Services Access, servisní účet s přístupem k Agent Platform (provider vertex) a Google Workspace jako IdP.
Proč Cloud SQL používá jen privátní IP a co to znamená pro skript?
Organizační politika constraints/sql.restrictPublicIp veřejnou IP zakazuje. Privátní IP je adresa uvnitř VPC, takže skript musí vytvořit VPC a Private Services Access – jednorázové nutné síťování.
Jak se liší ukládání konfigurace od AWS varianty?
V GCP se gateway.yaml publikuje do Secret Manageru jako gateway-config a mountuje do /etc/claude/gateway.yaml za běhu. V AWS je zapečená do image. Změna konfigurace v GCP tedy nevyžaduje nový build, jen nové publikování a deploy.
Proč jsou secrets jako env proměnné a konfigurace jako soubor?
Cloud Run nemůže připojit více secrets do jednoho adresáře. Proto se JWT, OIDC a Postgres URL vkládají jako proměnné a jako soubor se mountuje jen gateway.yaml do /etc/claude. Na GKE lze použít file mounty.
Co je zástupné public_url a proč login nefunguje při prvním průchodu?
Hodnota https://set-after-first-deploy.invalid je placeholder, protože URL run.app existuje až po prvním deployi. Dokud se nenahradí skutečným URL (nebo hostname LB) a skript neprovede nové publikování a deploy, přihlášení nefunguje. Tentýž host s /oauth/callback se registruje na Google OAuth klientovi.
Proč nelze veřejnému URL věřit z hlavičky Host?
Klient ji může podvrhnout. Proto je public_url povinné a pevně určuje redirect_uri, OIDC discovery dokument a issuer tokenů; X-Forwarded-Host/-Proto se také nikdy nevěří.
Co je Direct VPC egress na Cloud Run?
Způsob, jak Cloud Run služba posílá odchozí provoz přímo do VPC bez konektoru, takže dosáhne na privátní IP Cloud SQL.
Jak se brána autentizuje k Agent Platform a proč je to bezpečnější než klíče?
auth: {} znamená Application Default Credentials: servisní účet Cloud Run (nebo Workload Identity na GKE). Neexistuje statický klíč, který by mohl uniknout; práva se řídí IAM rolí servisního účtu.
Proč má google OIDC extra_auth_params access_type: offline a prompt: consent?
Aby Google vydal refresh token. Brána pak může session obnovovat tiše; bez něj by session po vypršení vyžadovala nové přihlášení.
Co dělá Dockerfile jinak než AWS verze?
Nezapéká konfiguraci ani CA bundle databáze. Pouze zkopíruje předem stažený binární claude do distroless image (nonroot), nastaví CLAUDE_CONFIG_DIR=/tmp/.claude, exponuje 8080 a spustí claude gateway --config /etc/claude/gateway.yaml.
Proč je setup.sh idempotentní a jak to pomáhá?
Existující zdroje detekuje a přeskočí; lze ho bezpečně spustit znovu – například po nastavení skutečného public_url, kdy skript znovu publikuje konfiguraci a redeployuje.
Proč skript odmítne publikovat konfiguraci s REPLACE_ME?
Poloplná konfigurace by se nasadila a brána by neběžela správně. Kontrola chrání před nasazením zástupných hodnot (client_id, domény, project_id).
Jak vypadá Terraform apply ve dvou průchodech i tady?
Terraform README popisuje: nejdřív cílený apply vytvoří Artifact Registry repozitář, pak se image sestaví a nahraje a následuje plný apply. Navíc je potřeba „two-pass OAuth bootstrap“: dokud public_url není skutečné URL, přihlášení nefunguje; po prvním deployi se URL doplní a konfigurace se znovu publikuje. Při privátním přístupu se bootstrap dělá zevnitř VPC.
Slovník pojmů (16)
Cloud Run
Spravovaná služba pro běh kontejnerů; nastavuje PORT=8080 a přiděluje URL run.app.
Agent Platform (Vertex)
Google Cloud služba pro přístup k modelům (dříve Vertex AI). V konfiguraci provider: vertex s region a project_id.
Cloud SQL (private IP)
Spravovaná PostgreSQL databáze dostupná jen uvnitř VPC.
Private Services Access
Síťová konstrukce umožňující VPC dosáhnout spravovaných služeb Google po privátní IP; skript ji vytváří.
Secret Manager
Služba pro uložení secrets (gateway-jwt-secret, gateway-oidc-client-secret, gateway-postgres-url, gateway-config).
Artifact Registry
Registr kontejnerových image, kam se nahraje image brány.
Direct VPC egress
Přímé napojení odchozího provozu Cloud Run do VPC.
ADC (Application Default Credentials)
Standardní řetěz přihlášení Google klientů; na Cloud Run se odvodí ze servisního účtu.
Workload Identity (GKE)
Způsob, jak podu na GKE přiřadit identitu servisního účtu bez klíčů.
servisní účet
Identita aplikace v IAM; zde s rolí pro Agent Platform a čtení secrets.
restrictPublicIp
Organizační politika zakazující veřejnou IP u Cloud SQL.
run.app URL
Adresa přidělená Cloud Run službě při prvním deployi; poté se vkládá do public_url.
OAuth client (Google)
Registrace aplikace v Google Cloud Console; client_id není secret, client secret je v Secret Manageru.
extra_auth_params
Dodatečné parametry autorizace OIDC; zde access_type: offline, prompt: consent.
gateway-config secret
Secret s celou konfigurací brány, mountovaný jako soubor do /etc/claude/gateway.yaml.
IAM binding
Vazba role na identitu u zdroje (např. servisní účet smí číst konkrétní secret); Terraform ji vytváří pro každý secret.