Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions src/ucode/agents/claude.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,11 @@ def _otel_trace_env(workspace: str) -> dict[str, str]:
# settings `env` value beats the shell's, so ug blanks them for the Claude process only.
CLAUDE_BLANKED_CREDENTIAL_ENV_KEYS = ("ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY")
CLAUDE_BLANKED_CREDENTIAL_PATHS = [["env", key] for key in CLAUDE_BLANKED_CREDENTIAL_ENV_KEYS]
# Provider switches Claude Code also honors from the shell or user settings; a stale one left over
# from using the provider directly routes around the gateway. ug blanks them like the credentials.
CLAUDE_BLANKED_PROVIDER_ENV_KEYS = ("CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX")
CLAUDE_BLANKED_ENV_KEYS = CLAUDE_BLANKED_CREDENTIAL_ENV_KEYS + CLAUDE_BLANKED_PROVIDER_ENV_KEYS
CLAUDE_BLANKED_ENV_PATHS = [["env", key] for key in CLAUDE_BLANKED_ENV_KEYS]
CLAUDE_MANAGED_PICKER_KEYS = ("availableModels", "enforceAvailableModels", "modelPicker")
CLAUDE_PERMISSIONS_DENY_PATH = ["permissions", "deny"]
CLAUDE_ALLOWED_MCP_SERVERS_KEY = "allowedMcpServers"
Expand Down Expand Up @@ -755,6 +760,7 @@ def render_overlay(
"CLAUDE_CODE_USE_GATEWAY": "1",
# Also outrank the subscription login, so relayed launches blank them too.
**dict.fromkeys(CLAUDE_BLANKED_CREDENTIAL_ENV_KEYS, ""),
**dict.fromkeys(CLAUDE_BLANKED_PROVIDER_ENV_KEYS, ""),
}
# Intentionally NOT setting ANTHROPIC_MODEL by default. Setting it produces a
# duplicate catalog row in Claude Code's /model picker (e.g. "Opus 4.8 (1M
Expand Down Expand Up @@ -2256,7 +2262,7 @@ def _managed_settings_conflicts(
owned_paths = [
path
for path in owned_paths
if path not in CLAUDE_HEADER_MOD_PATHS and path not in CLAUDE_BLANKED_CREDENTIAL_PATHS
if path not in CLAUDE_HEADER_MOD_PATHS and path not in CLAUDE_BLANKED_ENV_PATHS
]
conflicts = managed_file_conflicts(existing, desired, owned_paths)
header_path = f"env.{ANTHROPIC_CUSTOM_HEADERS_ENV_KEY}"
Expand Down Expand Up @@ -2462,8 +2468,8 @@ def header_mod_active(*, require_current: bool = False) -> bool:
return True


def _settle_credential_blanks(desired: dict, existing: dict, *, add: bool) -> None:
"""Add ug's credential blanks to the managed file only when asked; otherwise keep it as found.
def _settle_blank_env_keys(desired: dict, existing: dict, *, add: bool) -> None:
"""Add ug's blank env keys to the managed file only when asked; otherwise keep it as found.

Like the header mod, they are written by ``ug configure`` and never by a plain launch: another
writer of the file drops keys it doesn't template, and re-adding them would rewrite the
Expand All @@ -2474,15 +2480,21 @@ def _settle_credential_blanks(desired: dict, existing: dict, *, add: bool) -> No
return
existing_env = existing.get("env")
existing_env = existing_env if isinstance(existing_env, dict) else {}
for key in CLAUDE_BLANKED_CREDENTIAL_ENV_KEYS:
for key in CLAUDE_BLANKED_ENV_KEYS:
held = existing_env.get(key)
if add and isinstance(held, str) and held.strip():
# Someone else's explicit value (e.g. IT's): never replace it silently.
env[key] = held
if key in CLAUDE_BLANKED_CREDENTIAL_ENV_KEYS:
detail = (
"so Claude may use it instead of the gateway credential and fail with a 401"
)
else:
detail = "so Claude may route around the gateway and fail with a 400"
print_warning(
f"Claude Code managed settings at {_managed_settings_path()} set env.{key}; "
f"ug left it as is, so Claude may use it instead of the gateway credential and "
f"fail with a 401. Ask your administrator to remove it, or blank it yourself."
f"ug left it as is, {detail}. Ask your administrator to remove it, or blank it "
f"yourself."
)
elif add:
env[key] = ""
Expand Down Expand Up @@ -2647,7 +2659,7 @@ def _reconcile_managed_settings(
],
]
# Only the explicit `ug configure` path adds the blanks.
_settle_credential_blanks(desired_settings, managed_before, add=_explicit_configure)
_settle_blank_env_keys(desired_settings, managed_before, add=_explicit_configure)
if _explicit_configure:
desired_settings.setdefault(
CLAUDE_PARENT_SETTINGS_BEHAVIOR_PATH[0], CLAUDE_PARENT_SETTINGS_BEHAVIOR
Expand Down
3 changes: 0 additions & 3 deletions src/ucode/published_agent_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,6 @@ def claude_ug_values(
env.pop(entry.path[1], None)
# Set per launch (smart routing), never in the managed file.
env.pop("ANTHROPIC_MODEL", None)
# Blank provider switches keep developers from routing around the gateway.
env["CLAUDE_CODE_USE_BEDROCK"] = ""
env["CLAUDE_CODE_USE_VERTEX"] = ""
if mcp_entries:
overlay[claude_agent.MANAGED_MCP_SETTINGS_KEY] = dict(mcp_entries)
return overlay
Expand Down
54 changes: 35 additions & 19 deletions tests/test_claude_credential_blanks.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

WS = "https://example.cloud.databricks.com"
BLANKS = {"ANTHROPIC_AUTH_TOKEN": "", "ANTHROPIC_API_KEY": ""}
PROVIDER_BLANKS = {"CLAUDE_CODE_USE_BEDROCK": "", "CLAUDE_CODE_USE_VERTEX": ""}
ALL_BLANKS = {**BLANKS, **PROVIDER_BLANKS}
MODEL = "databricks-claude-sonnet-4"


Expand All @@ -27,12 +29,12 @@ def _env(path):


def _blanks(path):
return {k: v for k, v in _env(path).items() if k in BLANKS}
return {k: v for k, v in _env(path).items() if k in ALL_BLANKS}


def _drop_blanks_like_a_second_writer(path):
doc = json.loads(path.read_text())
for key in BLANKS:
for key in ALL_BLANKS:
doc["env"].pop(key)
path.write_text(json.dumps(doc), encoding="utf-8")

Expand All @@ -49,14 +51,14 @@ def test_overlay_blanks_both_for_helper_and_relayed_launches():
relayed=relayed,
relayed_base_url="http://127.0.0.1:9" if relayed else None,
)
assert {k: overlay["env"][k] for k in BLANKS} == BLANKS
assert all(["env", k] in keys for k in BLANKS)
assert {k: overlay["env"][k] for k in ALL_BLANKS} == ALL_BLANKS
assert all(["env", k] in keys for k in ALL_BLANKS)


def test_configure_writes_blanks_to_both_files(env):
claude.write_tool_config(dict(STATE), MODEL)
assert _blanks(env.user) == BLANKS
assert _blanks(env.managed) == BLANKS
assert _blanks(env.user) == ALL_BLANKS
assert _blanks(env.managed) == ALL_BLANKS
assert env.writes.count(str(env.managed)) == 1 # same privileged write as the rest of the file


Expand All @@ -73,14 +75,14 @@ def test_plain_launch_after_second_writer_dropped_them_makes_no_write(env):
assert len(env.writes) == count
assert env.managed.read_bytes() == before
assert _blanks(env.managed) == {}
assert _blanks(env.user) == BLANKS
assert _blanks(env.user) == ALL_BLANKS


def test_plain_launch_does_not_add_blanks_to_a_fresh_managed_file(env):
claude.request_explicit_configure(False)
claude.write_tool_config(dict(STATE), MODEL)
assert _blanks(env.managed) == {}
assert _blanks(env.user) == BLANKS
assert _blanks(env.user) == ALL_BLANKS


def test_plain_launch_leaves_present_blanks_and_values_alone(env):
Expand All @@ -89,7 +91,7 @@ def test_plain_launch_leaves_present_blanks_and_values_alone(env):
claude.request_explicit_configure(False)
claude.write_tool_config(dict(STATE), MODEL)
assert len(env.writes) == count
assert _blanks(env.managed) == BLANKS
assert _blanks(env.managed) == ALL_BLANKS

# A value another party set is neither a conflict nor rewritten by a plain launch.
doc = json.loads(env.managed.read_text())
Expand All @@ -98,13 +100,13 @@ def test_plain_launch_leaves_present_blanks_and_values_alone(env):
claude.write_tool_config(dict(STATE), MODEL)
assert len(env.writes) == count
assert _env(env.managed)["ANTHROPIC_API_KEY"] == "admin-set"
assert _blanks(env.user) == BLANKS
assert _blanks(env.user) == ALL_BLANKS


def test_conflicts_ignore_the_blanks():
existing = {"env": {"ANTHROPIC_API_KEY": "x", "ANTHROPIC_BASE_URL": "a"}}
desired = {"env": {"ANTHROPIC_BASE_URL": "b"}}
paths = [*claude.CLAUDE_BLANKED_CREDENTIAL_PATHS, ["env", "ANTHROPIC_BASE_URL"]]
paths = [*claude.CLAUDE_BLANKED_ENV_PATHS, ["env", "ANTHROPIC_BASE_URL"]]
assert claude._managed_settings_conflicts(existing, desired, paths) == [
"env.ANTHROPIC_BASE_URL"
]
Expand All @@ -115,23 +117,23 @@ def test_relayed_launch_blanks_user_file_and_leaves_managed_file_alone(env):
claude.write_tool_config(dict(STATE), MODEL, relayed=True)
doc = json.loads(env.user.read_text())
assert "apiKeyHelper" not in doc
assert _blanks(env.user) == BLANKS
assert _blanks(env.user) == ALL_BLANKS
assert not env.managed.exists()
assert env.writes == []


def test_skip_mode_writes_only_the_user_file(env):
env.mp.setenv("UG_SKIP_OS_SETTINGS", "1")
claude.write_tool_config(dict(STATE), MODEL)
assert _blanks(env.user) == BLANKS
assert _blanks(env.user) == ALL_BLANKS
assert not env.managed.exists()
assert env.writes == []


def test_revert_removes_blanks_from_the_managed_file(env):
env.managed.write_text(json.dumps({"env": {"KEEP": "1"}}), encoding="utf-8")
claude.write_tool_config(dict(STATE), MODEL)
assert _blanks(env.managed) == BLANKS
assert _blanks(env.managed) == ALL_BLANKS

claude.revert_managed_settings()
assert json.loads(env.managed.read_text()) == {"env": {"KEEP": "1"}}
Expand All @@ -141,7 +143,7 @@ def test_revert_removes_blanks_added_by_configure_after_a_launch_rewrite(env):
claude.write_tool_config(dict(STATE), MODEL)
claude.request_explicit_configure(False)
claude.write_tool_config({**STATE, "claude_http_headers": {"x-team": "a"}}, MODEL)
assert _blanks(env.managed) == BLANKS # kept by the launch's rewrite
assert _blanks(env.managed) == ALL_BLANKS # kept by the launch's rewrite

claude.revert_managed_settings()
assert not env.managed.exists()
Expand All @@ -155,12 +157,12 @@ def test_admin_passthrough_cannot_override_the_blanks(env):
},
}
claude.write_tool_config(state, MODEL)
assert _blanks(env.user) == BLANKS
assert _blanks(env.managed) == BLANKS
assert _blanks(env.user) == ALL_BLANKS
assert _blanks(env.managed) == ALL_BLANKS
assert _env(env.managed)["OTHER"] == "ok"
claude.request_explicit_configure(False)
claude.write_tool_config(state, MODEL)
assert _blanks(env.managed) == BLANKS
assert _blanks(env.managed) == ALL_BLANKS


def test_configure_keeps_a_value_someone_else_set_and_warns(env, capsys):
Expand All @@ -174,4 +176,18 @@ def test_configure_keeps_a_value_someone_else_set_and_warns(env, capsys):
out = capsys.readouterr().out
assert "env.ANTHROPIC_API_KEY" in out and "401" in out
assert "env.ANTHROPIC_AUTH_TOKEN" not in out
assert _blanks(env.user) == BLANKS # ug's own file is still blanked
assert _blanks(env.user) == ALL_BLANKS # ug's own file is still blanked


def test_configure_keeps_a_provider_switch_someone_else_set_and_warns(env, capsys):
env.managed.write_text(
json.dumps({"env": {"CLAUDE_CODE_USE_BEDROCK": "1", "CLAUDE_CODE_USE_VERTEX": ""}}),
encoding="utf-8",
)
claude.write_tool_config(dict(STATE), MODEL)
assert _env(env.managed)["CLAUDE_CODE_USE_BEDROCK"] == "1"
assert _env(env.managed)["CLAUDE_CODE_USE_VERTEX"] == ""
out = capsys.readouterr().out
assert "env.CLAUDE_CODE_USE_BEDROCK" in out and "400" in out
assert "env.CLAUDE_CODE_USE_VERTEX" not in out
assert _blanks(env.user) == ALL_BLANKS # ug's own file is still blanked
2 changes: 1 addition & 1 deletion tests/test_ownership.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def test_launch_and_removed_keys_never_reach_the_managed_file(self):

def test_credential_blanks_and_mcp_keys_are_reserved(self):
entries = _claude_entries()
for path in claude.CLAUDE_BLANKED_CREDENTIAL_PATHS:
for path in claude.CLAUDE_BLANKED_ENV_PATHS:
assert entries[".".join(path)].cls == ownership.RESERVED
assert entries[claude.MANAGED_MCP_SETTINGS_KEY].cls == ownership.RESERVED
assert entries[claude.CLAUDE_ALLOWED_MCP_SERVERS_KEY].cls == ownership.SHARED_LIST
Expand Down
Loading