diff --git a/CHANGELOG.md b/CHANGELOG.md index c13c29d..d6190e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] +### Added +- `TRENTINA_MCP_TOKEN_FILE`: the entrypoint reads the gateway token from that + file, stripping one trailing newline, and it wins over `TRENTINA_MCP_TOKEN`. + A file that is missing, unreadable, empty, over 4096 bytes, holds a NUL or + is more than one line stops the start with a message naming the variable, + never the value (#77). + ## [1.15.0] - 2026-11-18 ### Added diff --git a/README.md b/README.md index 030b229..20143bf 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,16 @@ allowlist, git through `TRENTINA_GIT_URL`. No forge host is on the allowlist; the gateway holds the GitHub token and limits which repositories and branches a push may move. The nested engine pulls through that same allowlist. +The seat's gateway token is `TRENTINA_MCP_TOKEN`, or the file named by +`TRENTINA_MCP_TOKEN_FILE` (one line; a trailing newline is stripped), which +wins. A `TRENTINA_MCP_TOKEN_FILE` that is missing, unreadable, empty, over 4096 +bytes, holds a NUL or is more than one line stops the container rather than +starting it without a gateway. +The token is written to Claude Code's state file, git's include file and +`gatehouse.env`, all 0600, and removed from the environment before Claude Code +starts. It is the only secret the entrypoint reads; the Matrix token is already +a file (`JOSUI_MATRIX_TOKEN_FILE`) that claude-agent reads itself. + ## Attaching ```bash diff --git a/gourmand-exceptions.toml b/gourmand-exceptions.toml index dcb9712..ab742d9 100644 --- a/gourmand-exceptions.toml +++ b/gourmand-exceptions.toml @@ -21,11 +21,19 @@ classification = "by_design" # The one test of a read-only checkout (Dolza's shared one, mounted read-only # into every seat but Josui Prime) makes .git mode 0555. Root writes through # mode bits, so as root the condition cannot be built without a privileged -# read-only mount, which a unit test cannot make. +# read-only mount, which a unit test cannot make. Gourmand matches exceptions +# by path alone and ignores `pattern`, so the test has a file to itself. [[exceptions]] check = "EV003-test_skip_evasion" -path = "tests/test_skills_sync.py" -pattern = "skipIf" +path = "tests/test_skills_sync_readonly.py" justification = "Root ignores the 0555 mode the test uses to make a checkout unwritable, and a real read-only mount needs privileges a unit test does not have; the test runs for every non-root user." classification = "by_design" +# Same reason, for the gateway token file (#77): a 0000 file is unreadable to +# everyone but root, and nothing short of a privileged mount makes a regular +# file unreadable to root. Its own file, for the same reason. +[[exceptions]] +check = "EV003-test_skip_evasion" +path = "tests/test_entrypoint_unreadable.py" +justification = "Root reads through the 0000 mode the test uses to make the token file unreadable, and nothing short of a privileged mount changes that; the test runs for every non-root user." +classification = "by_design" diff --git a/rootfs/usr/local/bin/developer-entrypoint b/rootfs/usr/local/bin/developer-entrypoint index deca1a2..f09329f 100755 --- a/rootfs/usr/local/bin/developer-entrypoint +++ b/rootfs/usr/local/bin/developer-entrypoint @@ -11,6 +11,37 @@ workdir=${JOSUI_WORKDIR:-$HOME/work} log() { echo "josui: $*" >&2; } +# The gateway token may come as a file instead (#77): Exedore delivers a seat's +# secrets as files under /run/srv-secrets. The file wins over the variable. It +# is read into TRENTINA_MCP_TOKEN, so it reaches exactly what the variable +# always reached and is unset with it below. One trailing newline is stripped. +# A file that is missing, unreadable, empty or more than one line stops the +# start, naming the variable and never the value: a seat that came up without +# its gateway would look healthy and do nothing. +if [ -n "${TRENTINA_MCP_TOKEN_FILE:-}" ]; then + if ! [ -f "$TRENTINA_MCP_TOKEN_FILE" ] || ! [ -r "$TRENTINA_MCP_TOKEN_FILE" ]; then + log "TRENTINA_MCP_TOKEN_FILE is set but is not a readable file; not starting" + exit 1 + fi + # read is a builtin, so the token is never in a process's arguments. It + # stops at a NUL or after 4097 bytes and succeeds only then; reaching the end + # of the file is the one way through. So a NUL cannot cut the token short + # unnoticed, and a huge file is not read into memory. LC_ALL=C because -n + # counts characters in the locale, and the limit is in bytes. + token_from_file= + if LC_ALL=C IFS= read -r -d '' -n 4097 token_from_file < "$TRENTINA_MCP_TOKEN_FILE"; then + log "TRENTINA_MCP_TOKEN_FILE holds a NUL or is over 4096 bytes; not starting" + exit 1 + fi + token_from_file=${token_from_file%$'\n'} + if [ -z "$token_from_file" ] || [[ "$token_from_file" == *[$'\n\r']* ]]; then + log "TRENTINA_MCP_TOKEN_FILE is empty or not a single line; not starting" + exit 1 + fi + export TRENTINA_MCP_TOKEN=$token_from_file + unset token_from_file TRENTINA_MCP_TOKEN_FILE +fi + # josui.env keeps the names it has always had; claude-agent reads its own. for name in ANSWER_PERMISSIONS MAX_TOOL_CALLS MAX_REPEAT; do value="JOSUI_$name" diff --git a/tests/test_entrypoint.py b/tests/test_entrypoint.py index 82fb2c8..ac0a896 100644 --- a/tests/test_entrypoint.py +++ b/tests/test_entrypoint.py @@ -73,7 +73,9 @@ """ -class EntrypointTest(unittest.TestCase): +class EntrypointCase(unittest.TestCase): + """A temporary home, a stand-in claude, and the helpers every test here uses.""" + def setUp(self) -> None: tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) @@ -121,6 +123,28 @@ def run_entrypoint( timeout=60, ) + def git(self, *args: str) -> str: + env = {"HOME": str(self.home), "PATH": os.environ["PATH"]} + return subprocess.run( + ["git", "config", *args], env=env, capture_output=True, text=True, check=True + ).stdout.strip() + + def token_file(self, body: str) -> dict[str, str]: + path = self.root / "trentina-token" + path.write_text(body) + return {**self.env, "TRENTINA_MCP_TOKEN_FILE": str(path)} + + def assert_refused(self, env: dict[str, str]) -> None: + result = self.run_entrypoint(env=env) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("TRENTINA_MCP_TOKEN_FILE", result.stderr) + self.assertNotIn("s3cret-token", result.stderr) + self.assertNotIn("file-token", result.stderr) + self.assertFalse((self.home / "claude-args").exists()) + self.assertFalse((self.home / ".claude.json").exists()) + + +class EntrypointTest(EntrypointCase): def test_assembles_the_home_and_serves_remote_control(self) -> None: result = self.run_entrypoint() self.assertEqual(result.returncode, 0, result.stderr) @@ -158,12 +182,6 @@ def test_token_is_not_handed_to_the_agent_process(self) -> None: self.run_entrypoint() self.assertNotIn("s3cret-token", (self.home / "claude-env").read_text()) - def git(self, *args: str) -> str: - env = {"HOME": str(self.home), "PATH": os.environ["PATH"]} - return subprocess.run( - ["git", "config", *args], env=env, capture_output=True, text=True, check=True - ).stdout.strip() - def test_git_goes_to_the_gateway_route_with_the_gateway_token(self) -> None: self.run_entrypoint() self.run_entrypoint() # a restart does not add a second include @@ -178,6 +196,58 @@ def test_git_goes_to_the_gateway_route_with_the_gateway_token(self) -> None: "Authorization: Bearer s3cret-token", ) + def test_a_token_file_wins_over_the_variable(self) -> None: + result = self.run_entrypoint(env=self.token_file("file-token\n")) + self.assertEqual(result.returncode, 0, result.stderr) + state = json.loads((self.home / ".claude.json").read_text()) + self.assertEqual(state["mcpServers"]["trentina"]["headers"]["Authorization"], "Bearer file-token") + self.assertEqual( + self.git("--get", "http.http://192.0.2.2:8019/git/.extraHeader"), + "Authorization: Bearer file-token", + ) + self.assertIn( + "OPENROUTER_API_KEY=file-token\n", (self.home / ".config/mcp-env/gatehouse.env").read_text() + ) + claude_env = (self.home / "claude-env").read_text() + self.assertNotIn("file-token", claude_env) + self.assertNotIn("TRENTINA_MCP_TOKEN", claude_env) + + def test_a_token_file_works_without_the_variable(self) -> None: + env = {k: v for k, v in self.token_file("file-token").items() if k != "TRENTINA_MCP_TOKEN"} + result = self.run_entrypoint(env=env) + self.assertEqual(result.returncode, 0, result.stderr) + state = json.loads((self.home / ".claude.json").read_text()) + self.assertEqual(state["mcpServers"]["trentina"]["headers"]["Authorization"], "Bearer file-token") + + def test_a_missing_token_file_stops_the_start(self) -> None: + self.assert_refused({**self.env, "TRENTINA_MCP_TOKEN_FILE": str(self.root / "nope")}) + + def test_a_token_file_that_is_a_directory_stops_the_start(self) -> None: + self.assert_refused({**self.env, "TRENTINA_MCP_TOKEN_FILE": str(self.root)}) + + def test_a_token_file_with_a_nul_stops_the_start(self) -> None: + self.assert_refused(self.token_file("file-token\0extra\n")) + + def test_an_oversized_token_file_stops_the_start(self) -> None: + self.assert_refused(self.token_file("x" * 4097)) + + def test_the_size_limit_is_in_bytes_in_a_multibyte_locale(self) -> None: + env = {**self.token_file("\u00e9" * 2049), "LC_ALL": "C.UTF-8"} + self.assert_refused(env) + + def test_a_token_file_at_the_size_limit_is_accepted(self) -> None: + result = self.run_entrypoint(env=self.token_file("x" * 4095 + "\n")) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_an_empty_token_file_stops_the_start(self) -> None: + self.assert_refused(self.token_file("")) + self.assert_refused(self.token_file("\n")) + + def test_a_token_file_of_more_than_one_line_stops_the_start(self) -> None: + self.assert_refused(self.token_file("file-token\n\n")) + self.assert_refused(self.token_file("file-token\r\n")) + self.assert_refused(self.token_file("file-token\nsecond")) + def test_git_url_that_is_not_a_plain_url_is_ignored(self) -> None: env = {**self.env, "TRENTINA_GIT_URL": 'http://x"]\n[credential]\n\thelper = !touch /tmp/pwned'} result = self.run_entrypoint(env=env) diff --git a/tests/test_entrypoint_unreadable.py b/tests/test_entrypoint_unreadable.py new file mode 100644 index 0000000..31fb539 --- /dev/null +++ b/tests/test_entrypoint_unreadable.py @@ -0,0 +1,22 @@ +"""The entrypoint refusing a token file it cannot read. + +Its own file because it is skipped as root, which reads a file whatever its +mode. Gourmand matches an exception by path alone, so the exception for this +skip names this file and covers nothing else. +""" + +from __future__ import annotations + +import os +import unittest +from pathlib import Path + +from test_entrypoint import EntrypointCase + + +class UnreadableTokenFileTest(EntrypointCase): + @unittest.skipIf(os.geteuid() == 0, "root reads a file whatever its mode") + def test_an_unreadable_token_file_stops_the_start(self) -> None: + env = self.token_file("file-token\n") + Path(env["TRENTINA_MCP_TOKEN_FILE"]).chmod(0) + self.assert_refused(env) diff --git a/tests/test_skills_sync.py b/tests/test_skills_sync.py index 65946ad..c959025 100644 --- a/tests/test_skills_sync.py +++ b/tests/test_skills_sync.py @@ -19,7 +19,7 @@ def status_of(repo: Path) -> dict[str, str]: return dict(field.split("=", 1) for field in line.split()[1:]) -class SkillsSyncTest(unittest.TestCase): +class SkillsSyncCase(unittest.TestCase): def setUp(self) -> None: tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) @@ -61,6 +61,8 @@ def sync(self, *extra: str, env: dict[str, str] | None = None) -> subprocess.Com def linked(self) -> list[str]: return sorted(p.name for p in (self.claude / "skills").iterdir()) + +class SkillsSyncTest(SkillsSyncCase): def test_a_merge_upstream_is_fast_forwarded_and_linked(self) -> None: self.assertEqual(self.sync().returncode, 0) self.assertEqual(self.linked(), ["alpha"]) @@ -129,23 +131,6 @@ def test_a_failed_fetch_keeps_the_last_good_fetch_time(self) -> None: self.assertEqual(status_of(self.repo)["fetched"], fetched) self.assertEqual(status_of(self.repo)["state"], "current") - @unittest.skipIf(os.geteuid() == 0, "root writes through a read-only mode") - def test_a_checkout_it_cannot_write_is_only_read_and_relinked(self) -> None: - self.add_skill(self.upstream, "beta") - before = self.git(self.repo, "rev-parse", "HEAD") - self.add_skill(self.repo, "gamma") # as if the owner had already pulled it - gamma = self.git(self.repo, "rev-parse", "HEAD") - self.assertNotEqual(before, gamma) - (self.repo / ".git").chmod(0o555) - self.addCleanup((self.repo / ".git").chmod, 0o755) - - result = self.sync() - - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(self.git(self.repo, "rev-parse", "HEAD"), gamma) - self.assertEqual(self.linked(), ["alpha", "gamma"]) - self.assertFalse((self.repo / ".git/skills-sync.status").exists()) - def test_an_empty_directory_is_cloned(self) -> None: shutil.rmtree(self.repo) self.repo.mkdir() diff --git a/tests/test_skills_sync_readonly.py b/tests/test_skills_sync_readonly.py new file mode 100644 index 0000000..f0252e0 --- /dev/null +++ b/tests/test_skills_sync_readonly.py @@ -0,0 +1,32 @@ +"""developer-skills-sync on a checkout it cannot write (#42). + +Its own file because it is skipped as root, which writes through a read-only +mode. Gourmand matches an exception by path alone, so the exception for this +skip names this file and covers nothing else. +""" + +from __future__ import annotations + +import os +import unittest + +from test_skills_sync import SkillsSyncCase + + +class ReadOnlyCheckoutTest(SkillsSyncCase): + @unittest.skipIf(os.geteuid() == 0, "root writes through a read-only mode") + def test_a_checkout_it_cannot_write_is_only_read_and_relinked(self) -> None: + self.add_skill(self.upstream, "beta") + before = self.git(self.repo, "rev-parse", "HEAD") + self.add_skill(self.repo, "gamma") # as if the owner had already pulled it + gamma = self.git(self.repo, "rev-parse", "HEAD") + self.assertNotEqual(before, gamma) + (self.repo / ".git").chmod(0o555) + self.addCleanup((self.repo / ".git").chmod, 0o755) + + result = self.sync() + + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.git(self.repo, "rev-parse", "HEAD"), gamma) + self.assertEqual(self.linked(), ["alpha", "gamma"]) + self.assertFalse((self.repo / ".git/skills-sync.status").exists())