HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
Environments: each one is readable by its own sessions only, and its installs run as its own identity (#329)
github-actions[bot]23f3e3fefc6c
diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex 85d78aad..fab37198 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -40,12 +40,14 @@ mkdir -p "$HARNESS_WORKSPACE"# by their session's uid (0700); the runner sets that as it allocates them.chown "$PRODUCT:$PRODUCT" "$DATA_DIR" "$HARNESS_WORKSPACE"chmod 751 "$DATA_DIR" "$HARNESS_WORKSPACE" # traversable by sessions, neither listable nor writable-# Environments (runner/environments.py): project layers built once and read by every session that-# names one. Root's, readable by every session uid, writable by none: that ownership is the-# read-only guarantee, so nothing here is handed to $PRODUCT. /env holds the links sessions are told.+# Environments (runner/environments.py): project layers built once and read by the sessions that+# name one. Root's, each environment readable by its own group and writable by none: that ownership+# is the read-only guarantee, so nothing here is handed to $PRODUCT. Both directories are+# traversable, not listable: a session reaches the environment it was told and enumerates none.+# /env holds the links sessions are told.export HR_ENV_ROOT="${HR_ENV_ROOT:-$DATA_DIR/environments}"mkdir -p "$HR_ENV_ROOT" /env-chmod 755 "$HR_ENV_ROOT" /env+chmod 751 "$HR_ENV_ROOT" /env# A login shell (`bash -lc`, which codex uses for its commands) runs /etc/profile, and Debian's# sets PATH from scratch, which dropped the environment's venv and node_modules/.bin that the runner# had put first (measured on 0.26.0-rc.1: `python3` was /usr/local's, not the venv's). The runnerdiff --git a/docs/environments.md b/docs/environments.mdindex 64cc0f89..d64a8d94 100644--- a/docs/environments.md+++ b/docs/environments.md@@ -56,14 +56,26 @@ harness object and on `POST /v1/responses`; `environment` on the session object.with org, workspace, name, slug, description, entry, status, active/latest version, theversions list and the active build's packages, refreshed from the runner on reads.- **Bytes**: the runner (`runner/environments.py`) owns `/data/environments/<id>/`:- `source/` (editable), `versions/<n>/` (a build, root-owned, `a+rX`, with `.hr-build.json`:+ `source/` (editable, `0700`), `versions/<n>/` (a build, `root:<env group>` `0750/0640`, with `.hr-build.json`:status, log, packages, size), `active` → `versions/<n>`. The mount `/env/<slug>` is a link to`active`, on the container's rootfs, remade lazily after a restart. Builds run in a thread ofthe runner with the image's own `python3` and `npm`, caches in a scratch directory, a wall clockof `HR_ENV_BUILD_TIMEOUT` (1800 s). Dependency directories in the source are never copied.-- **Read-only**: the write-wall (`HR_SESSION_UIDS`): an agent runs as its session's uid, the layer- is root's, `chmod 755/644`, so a write fails with EACCES. Without the wall (a development box)- the permissions still hold for any non-root agent; root is the operator's own choice.+- **Read-only, and read by its own sessions only**: the write-wall (`HR_SESSION_UIDS`): an agent+ runs as its session's uid, the layer is root's, so a write fails with EACCES. Each environment+ has a group of its own (`GID_BASE` 60000 + a hash of the id; the environment directory's group+ IS the record, as the workspace's owner is the session uid's). The source is `0700`, the+ runner's alone; a built version is `0750/0640`, the group's to read; the agent process joins+ that group (`extra_groups`) only for a turn whose harness names the environment, so a session+ reads the one environment it was given and no other. `/data/environments` and `/env` are `0751`:+ traversable, not listable, so a session cannot enumerate the rest. pip, npm and `setup.sh`+ run the packages' own code, so a build runs them as the environment's identity+ (`uid = gid = the environment's number`) that owns the layer under construction and nothing+ else; apt-get and `dpkg -x` run no package code and stay the runner's. A store from before+ groups is migrated once at start (`secure_store`). Without the wall (a development box) the+ modes still hold for any non-root agent; root is the operator's own choice. Measured on+ hr-test 2026-09-28: before the groups, any session could list and read every environment's+ source and layers; after, a session reads its own and gets EACCES on the others.- **The turn**: the gateway resolves the environment (request field, else the harness's) beforeanything is allocated, passes `{id, slug, entry}` to the runner, stamps the session vertex with`environment` and the turn record with the version. The runner resolves the mount before writing@@ -112,8 +124,10 @@ contract is built like this:sharing a layer across sessions is ever needed, the ACA-native shape is a session pool whoseimage bakes the layer, a different product decision; a bind mount is not promised.6. **Isolation.** The container is the boundary: one session cannot see another's container at- all; the layer is root's and the agent is not; the source and the layers are written only by- the API and the build's write SAS.+ all, and a container holds only the environment its turn named (the hydrate downloads that+ layer and no other), which is the group model's outcome without the groups; the layer is+ root's and the agent is not; the source and the layers are written only by the API and the+ build's write SAS. The build runs in its own job container, never in a session's.7. **Versions, rollback, retention.** `active_version` on the vertex is the pointer; the gatewaypasses `version` in the turn body so a hydrate is deterministic, and stamps the session withthe version it started on, which later turns of that session keep. The active version plus thediff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.mdindex f819cf74..081e9b0e 100644--- a/docs/self-hosting-guide.md+++ b/docs/self-hosting-guide.md@@ -691,7 +691,7 @@ shared, with the environment's Python virtualenv and `node_modules` first on `PAwritable, private to the session, checkpointed, and the only place its outputs come from. Two taskson one environment share every byte of it and cannot read each other's workspace or write theenvironment; behind the write-wall an agent runs as its session's user and the environment is-root's, so a write fails rather than being merely discouraged. The agent's instruction file says all+root's, so a write fails rather than being merely discouraged; it is readable by the sessions of the harnesses that name it and by no other session, which cannot list the environments the box holds either. The agent's instruction file says allof this, and repeats the "how it is run" line you gave.On the console, **Environments** (under Build): create one, then put the project in, one file at adiff --git a/protocol/versions/2026-09-28/environments.md b/protocol/versions/2026-09-28/environments.mdindex cdcb66ed..ff84a2ed 100644--- a/protocol/versions/2026-09-28/environments.md+++ b/protocol/versions/2026-09-28/environments.md@@ -231,9 +231,11 @@ For a task that runs with an environment, a server MUST:version.Two sessions on one environment MUST NOT be able to read each other's working directory or write-the environment. How a server enforces that is its own business: a per-session container with a-read-only mount, a per-session user without write permission on a shared directory, or a copy-made read-only. What a client may rely on is the outcome.+the environment. A session MUST NOT be able to read an environment its task did not name, nor to+enumerate the environments a server holds. How a server enforces that is its own business: a+per-session container with a read-only mount, a per-session user and a per-environment group+without write permission on a shared directory, or a copy made read-only. What a client may rely+on is the outcome.## 7. Discoverydiff --git a/runner/environments.py b/runner/environments.pyindex ea586b45..874c82ae 100644--- a/runner/environments.py+++ b/runner/environments.py@@ -29,9 +29,12 @@ with EACCES; that is the enforcement, not an instruction."""from __future__ import annotations+import grp+import hashlibimport jsonimport mimetypesimport platform+import pwdimport reimport osimport pathlib@@ -61,6 +64,20 @@ _ID_SAFE = set("abcdefghijklmnopqrstuvwxyz0123456789_-")_SPEC_RE = re.compile(r"^@?[A-Za-z0-9][A-Za-z0-9._/+-]{0,99}(?:(?:==|>=|<=|~=|!=|@|=)[A-Za-z0-9._*+^~<>-]{0,60})?$") # one declared package_ARCH_DIRS = {"amd64": "x86_64-linux-gnu", "arm64": "aarch64-linux-gnu"}+# ── who may read an environment ─────────────────────────────────────────────────────────────────+# One group per environment, and the environment directory's group IS the record (as a session's+# uid is its workspace's owner: nothing to keep in sync, and it survives a restart because it lives+# on the volume). The runner alone reads the source (0700). A built version is the group's to read+# (0750 / 0640), and an agent process joins that group only for a turn whose harness names the+# environment, so a session reads the one environment it was given and no other. The store root+# and the mount directory are traversable, not listable: a session cannot enumerate the rest.+# Package installs run the packages' own code, so they run as the environment's build identity+# (uid = gid = the environment's number), never as root. Ownership needs root: a runner that is not+# root (a dev box, the per-session sandbox, the tests) applies the modes and nothing else.+GID_BASE = int(os.environ.get("HR_ENV_GID_BASE", "60000") or 60000)+GID_SPAN = 40000+_gid_lock = threading.Lock()+router = APIRouter()_builds_lock = threading.Lock()_builds: dict[str, threading.Thread] = {} # "<id>:<n>" -> the thread building it@@ -99,6 +116,135 @@ def mount_path(slug: str) -> str:return os.path.join(ENV_MOUNT, slug)+def _root() -> bool:+ return os.geteuid() == 0+++def _in_range(gid: int) -> int | None:+ return gid if GID_BASE <= gid < GID_BASE + GID_SPAN else None+++def env_gid(env_id: str) -> int | None:+ """The group that reads this environment's builds, from its directory; None when the+ directory is not there or predates groups (secure_store gives it one)."""+ try:+ return _in_range(os.stat(env_dir(env_id)).st_gid)+ except OSError:+ return None+++def reader_gid(mount: str | None) -> int | None:+ """The group a turn's process joins for the environment at `mount` (the link the agent is+ told), read from the active version the link points at; None when there is none."""+ if not mount:+ return None+ try:+ return _in_range(os.stat(mount).st_gid)+ except OSError:+ return None+++def _account(n: int) -> None:+ """A group and passwd entry for an environment's number, so a tool that looks itself up (npm+ does) finds one. Best effort: nothing here needs the entry to exist."""+ try:+ grp.getgrgid(n)+ except KeyError:+ subprocess.run(["groupadd", "-g", str(n), f"henv{n}"], capture_output=True)+ try:+ pwd.getpwuid(n)+ except KeyError:+ subprocess.run(["useradd", "-M", "-u", str(n), "-g", str(n), "-s", "/usr/sbin/nologin", "-d", "/nonexistent", f"henv{n}"],+ capture_output=True)+++def _claim(env_id: str) -> pathlib.Path:+ """The environment's directory with a group of its own: made on first use, its group derived+ from the id and bumped past any sibling that already holds it, traversable by that group only."""+ d = env_dir(env_id)+ if env_gid(env_id) is not None:+ return d+ d.mkdir(parents=True, exist_ok=True)+ if not _root():+ return d+ with _gid_lock:+ taken = set()+ for sib in pathlib.Path(ENV_ROOT).iterdir():+ try:+ taken.add(os.stat(sib).st_gid)+ except OSError:+ pass+ gid = GID_BASE + int(hashlib.sha256(env_id.encode()).hexdigest()[:8], 16) % GID_SPAN+ while gid in taken:+ gid = GID_BASE + (gid - GID_BASE + 1) % GID_SPAN+ os.chown(d, 0, gid)+ os.chmod(d, 0o750)+ _account(gid)+ return d+++def _source(env_id: str) -> pathlib.Path:+ """The source directory, the runner's alone."""+ _claim(env_id)+ src = source_dir(env_id)+ src.mkdir(exist_ok=True)+ os.chmod(src, 0o700)+ return src+++def _build_as(env_id: str) -> dict:+ """Popen/run arguments that make a build step run as the environment's own identity; empty+ off root, so every step reads the same with or without it."""+ gid = env_gid(env_id)+ return {"user": gid, "group": gid, "extra_groups": []} if gid is not None and _root() else {}+++def _own(path: pathlib.Path, uid: int, gid: int) -> None:+ """chown -R, a link as itself rather than what it points at."""+ try:+ os.lchown(path, uid, gid)+ except OSError:+ pass+ for dirpath, dirnames, filenames in os.walk(path):+ for name in dirnames + filenames:+ try:+ os.lchown(os.path.join(dirpath, name), uid, gid)+ except OSError:+ pass+++def secure_store() -> int:+ """Every environment made before groups existed (its directory has no group of its own) gets+ one, its source the runner's alone, its versions the group's: the migration a restart on a box+ with older environments runs once. Returns how many it changed."""+ if not _root():+ return 0+ root = pathlib.Path(ENV_ROOT)+ root.mkdir(parents=True, exist_ok=True)+ os.chmod(root, 0o751)+ n = 0+ for d in root.iterdir():+ try:+ if not d.is_dir() or env_gid(d.name) is not None:+ continue+ _claim(d.name)+ gid = env_gid(d.name)+ if gid is None:+ continue+ if source_dir(d.name).is_dir():+ os.chmod(source_dir(d.name), 0o700)+ vers = d / "versions"+ if vers.is_dir():+ os.chown(vers, 0, gid)+ os.chmod(vers, 0o750)+ for v in vers.iterdir():+ _read_only(v, gid)+ n += 1+ except Exception: # noqa: BLE001 — one odd directory must not stop the rest+ continue+ return n++def _safe_rel(root: pathlib.Path, rel: str) -> pathlib.Path:"""A path under root, or 400. Symlinks inside the source are followed for the containment checkso a link that points out of the tree cannot be read or written through."""@@ -161,8 +307,7 @@ def read_file(env_id: str, rel: str) -> tuple[bytes, str]:def write_file(env_id: str, rel: str, data: bytes) -> dict:- src = source_dir(env_id)- src.mkdir(parents=True, exist_ok=True)+ src = _source(env_id)p = _safe_rel(src, rel)if p.is_dir():raise HTTPException(409, "a directory is at that path")@@ -174,8 +319,7 @@ def write_file(env_id: str, rel: str, data: bytes) -> dict:def make_dir(env_id: str, rel: str) -> dict:- src = source_dir(env_id)- src.mkdir(parents=True, exist_ok=True)+ src = _source(env_id)p = _safe_rel(src, rel)p.mkdir(parents=True, exist_ok=True)return {"path": rel.strip("/"), "dir": True}@@ -223,7 +367,7 @@ def import_archive(env_id: str, data_path: str, *, replace: bool = False) -> dicsrc = source_dir(env_id)if replace and src.exists():shutil.rmtree(src)- src.mkdir(parents=True, exist_ok=True)+ src = _source(env_id)written = skipped = 0if zipfile.is_zipfile(data_path):with zipfile.ZipFile(data_path) as zf:@@ -388,11 +532,11 @@ def _tool_env() -> dict:return env-def _run(log: list[str], cmd: list[str], cwd: str, env: dict, deadline: float) -> None:+def _run(log: list[str], cmd: list[str], cwd: str, env: dict, deadline: float, run_as: dict | None = None) -> None:left = max(1, int(deadline - time.time()))log.append(f"$ {' '.join(cmd)}")try:- r = subprocess.run(cmd, cwd=cwd, env=env, capture_output=True, text=True, timeout=left)+ r = subprocess.run(cmd, cwd=cwd, env=env, capture_output=True, text=True, timeout=left, **(run_as or {}))except subprocess.TimeoutExpired:raise RuntimeError(f"{cmd[0]} did not finish within the build's {BUILD_TIMEOUT}s")if r.stdout.strip():@@ -403,12 +547,13 @@ def _run(log: list[str], cmd: list[str], cwd: str, env: dict, deadline: float) -raise RuntimeError(f"{cmd[0]} exited {r.returncode}")-def _packages(dst: pathlib.Path, env: dict) -> list[dict]:+def _packages(dst: pathlib.Path, env: dict, run_as: dict | None = None) -> list[dict]:out: list[dict] = []+ run_as = run_as or {}pip = dst / ".venv" / "bin" / "pip"if pip.is_file():try:- r = subprocess.run([str(pip), "list", "--format=json"], capture_output=True, text=True, timeout=120, env=env)+ r = subprocess.run([str(pip), "list", "--format=json"], capture_output=True, text=True, timeout=120, env=env, **run_as)for row in json.loads(r.stdout or "[]"):out.append({"manager": "pip", "name": str(row.get("name")), "version": str(row.get("version"))})except (OSError, ValueError, subprocess.TimeoutExpired):@@ -416,7 +561,7 @@ def _packages(dst: pathlib.Path, env: dict) -> list[dict]:if (dst / "node_modules").is_dir():try:r = subprocess.run(["npm", "ls", "--json", "--depth=0"], cwd=str(dst), capture_output=True, text=True,- timeout=120, env=env)+ timeout=120, env=env, **run_as)deps = (json.loads(r.stdout or "{}") or {}).get("dependencies") or {}for name, info in sorted(deps.items()):out.append({"manager": "npm", "name": name, "version": str((info or {}).get("version") or "")})@@ -460,23 +605,27 @@ def _apt_packages(dst: pathlib.Path) -> list[dict]:return out-def _read_only(dst: pathlib.Path) -> None:- """Root's, readable by everyone, writable by nobody else: directories 755, files keep their- execute bits and lose group/other write."""- for dirpath, dirnames, filenames in os.walk(dst):+def _read_only(dst: pathlib.Path, gid: int | None = None) -> None:+ """Root's, the environment's group's to read, writable by nobody: directories 750, files 640+ keeping their execute bit (750). Nobody outside the group sees a byte of it."""+ own = gid is not None and _root()++ def one(p: str, is_dir: bool) -> None:try:- os.chmod(dirpath, 0o755)+ st = os.lstat(p)+ if own:+ os.lchown(p, 0, gid)+ if not stat.S_ISLNK(st.st_mode):+ os.chmod(p, 0o750 if is_dir or st.st_mode & 0o111 else 0o640)except OSError:pass++ one(str(dst), True)+ for dirpath, dirnames, filenames in os.walk(dst):+ for d in dirnames:+ one(os.path.join(dirpath, d), True)for f in filenames:- p = os.path.join(dirpath, f)- try:- st = os.lstat(p)- if stat.S_ISLNK(st.st_mode):- continue- os.chmod(p, 0o755 if st.st_mode & 0o111 else 0o644)- except OSError:- continue+ one(os.path.join(dirpath, f), False)def _size(dst: pathlib.Path) -> tuple[int, int]:@@ -515,55 +664,68 @@ def _build(env_id: str, n: int, slug: str, activate: bool, spec: dict | None = N"packages": [], "files": 0, "bytes": 0, "log": log, "runtime": {},"declared": {"pip": pip_specs, "npm": npm_specs, "apt": apt_specs}}try:+ _claim(env_id)+ gid = env_gid(env_id)if dst.exists():shutil.rmtree(dst)_write_record(dst, rec)+ if gid is not None:+ os.chown(dst.parent, 0, gid)+ os.chmod(dst.parent, 0o750)deadline = time.time() + BUILD_TIMEOUTenv = _tool_env()log.append(f"copying the project ({source_stat(env_id)['count']} files)")shutil.copytree(src, dst, symlinks=False, dirs_exist_ok=True,ignore=lambda d, names: [x for x in names if x in NOT_COPIED])+ as_build = _build_as(env_id)with tempfile.TemporaryDirectory(prefix="hr-env-build-") as scratch:env["HOME"] = env["TMPDIR"] = scratchenv["npm_config_cache"] = os.path.join(scratch, "npm-cache")+ if as_build:+ # pip, npm and setup.sh run the project's and its packages' own code: as the+ # environment's identity, which owns this layer and the scratch and nothing else.+ _own(dst, gid, gid)+ os.chown(scratch, gid, gid)if pip_specs or (dst / "requirements.txt").is_file() or (dst / "pyproject.toml").is_file():# The interpreter the owner chose, when the box has it; the image's python3 otherwise.python = (shutil.which(f"python{want_py}", path=env.get("PATH")) if want_py else None) \or shutil.which("python3", path=env.get("PATH")) or "python3"- _run(log, [python, "-m", "venv", ".venv"], str(dst), env, deadline)+ _run(log, [python, "-m", "venv", ".venv"], str(dst), env, deadline, as_build)pip = str(dst / ".venv" / "bin" / "pip")if (dst / "requirements.txt").is_file():- _run(log, [pip, "install", "-r", "requirements.txt"], str(dst), env, deadline)+ _run(log, [pip, "install", "-r", "requirements.txt"], str(dst), env, deadline, as_build)if (dst / "pyproject.toml").is_file():- _run(log, [pip, "install", "."], str(dst), env, deadline)+ _run(log, [pip, "install", "."], str(dst), env, deadline, as_build)if pip_specs:- _run(log, [pip, "install", *pip_specs], str(dst), env, deadline)+ _run(log, [pip, "install", *pip_specs], str(dst), env, deadline, as_build)try:rec["runtime"]["python"] = subprocess.run([str(dst / ".venv" / "bin" / "python"), "-c", "import platform; print(platform.python_version())"],- capture_output=True, text=True, timeout=30, env=env).stdout.strip()+ capture_output=True, text=True, timeout=30, env=env, **as_build).stdout.strip()except (OSError, subprocess.TimeoutExpired):passif npm_specs or (dst / "package.json").is_file():npm = shutil.which("npm", path=env.get("PATH")) or "npm"if (dst / "package.json").is_file():_run(log, [npm, "ci" if (dst / "package-lock.json").is_file() else "install", "--no-audit", "--no-fund"],- str(dst), env, deadline)+ str(dst), env, deadline, as_build)if npm_specs:if not (dst / "package.json").is_file():(dst / "package.json").write_text(json.dumps({"name": slug or "environment", "version": "0.0.0", "private": True}, indent=2) + "\n")- _run(log, [npm, "install", "--no-audit", "--no-fund", "--save", *npm_specs], str(dst), env, deadline)+ if as_build:+ os.chown(dst / "package.json", gid, gid)+ _run(log, [npm, "install", "--no-audit", "--no-fund", "--save", *npm_specs], str(dst), env, deadline, as_build)try:rec["runtime"]["node"] = subprocess.run(["node", "--version"], capture_output=True, text=True, timeout=10, env=env).stdout.strip().lstrip("v")except (OSError, subprocess.TimeoutExpired):pass- if apt_specs:+ if apt_specs: # apt-get and dpkg -x run none of the packages' code; apt's lists need root_apt_into_layer(log, dst, apt_specs, env, scratch, deadline)if (dst / "setup.sh").is_file():- _run(log, ["bash", "setup.sh"], str(dst), {**env, "ENV_ROOT": str(dst)}, deadline)- rec["packages"] = _packages(dst, env)+ _run(log, ["bash", "setup.sh"], str(dst), {**env, "ENV_ROOT": str(dst)}, deadline, as_build)+ rec["packages"] = _packages(dst, env, as_build)if (dst / "apt").is_dir():rec["packages"] += _apt_packages(dst)- _read_only(dst)+ _read_only(dst, gid)rec["files"], rec["bytes"] = _size(dst)rec["status"], rec["finished_at"] = "ready", int(time.time())log.append(f"ready: {rec['files']} files, {len(rec['packages'])} packages, {int(time.time()) - started}s")@@ -620,9 +782,9 @@ def ensure_mount(env_id: str, slug: str) -> str:raise HTTPException(400, "environment slug is not a path segment")if active_version(env_id) is None:raise HTTPException(409, "the environment has no built version")- os.makedirs(ENV_MOUNT, mode=0o755, exist_ok=True)+ os.makedirs(ENV_MOUNT, mode=0o751, exist_ok=True)try:- os.chmod(ENV_MOUNT, 0o755)+ os.chmod(ENV_MOUNT, 0o751)except OSError:passtarget = str(active_link(env_id))diff --git a/runner/server.py b/runner/server.pyindex 13089d7a..58ec178c 100644--- a/runner/server.py+++ b/runner/server.py@@ -116,6 +116,10 @@ if _SESSION_UIDS and _SANDBOX_PER_SESSION:if _SESSION_UIDS and os.geteuid() != 0:raise RuntimeError("HR_SESSION_UIDS=1 requires the runner to run as root (it switches to a ""per-session uid for every agent process); refusing to start on a shared uid")+if _SESSION_UIDS:+ _secured = environments.secure_store() # environments from before per-environment groups+ if _secured:+ print(f"[runner] environments: {_secured} older environment(s) now readable by their own group only", flush=True)# Names an agent process must never inherit from the runner's environment. The turn sets the# credential it needs explicitly (see turn()); everything else secret-shaped is the product's._SECRET_ENV = re.compile(r"^(HARNESS_INTERNAL_KEY|HR_AUTH_.*|HR_SECRET_KEY|HR_SESSION_KEY|HR_POOL_.*)$"@@ -203,11 +207,16 @@ def _session_uid(ws: str) -> int | None:return uid if _SESSION_UID_BASE <= uid < _SESSION_UID_BASE + _SESSION_UID_SPAN else None-def _as_session(ws: str) -> dict:+def _as_session(ws: str, env: dict | None = None) -> dict:"""Popen/run keyword arguments that make a child act as this session. Empty when the wall is- off, so every spawn site reads the same with or without it."""+ off, so every spawn site reads the same with or without it. A turn's agent process (the sites+ that pass the turn's env) also joins the group of the one environment the turn names, which is+ what lets it read that environment and no other (runner/environments.py)."""uid = _session_uid(ws)- return {"user": uid, "group": uid, "extra_groups": []} if uid is not None else {}+ if uid is None:+ return {}+ gid = environments.reader_gid((env or {}).get("HR_ENVIRONMENT"))+ return {"user": uid, "group": uid, "extra_groups": [gid] if gid is not None else []}def _ensure_passwd(uid: int, home: str) -> None:@@ -6630,7 +6639,7 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, m# shell children (see _kill_proc_tree) instead of orphaning a pipe-holding child.proc = subprocess.Popen(cmd, cwd=cwd, env=env, text=True, bufsize=1,stdout=subprocess.PIPE, stderr=subprocess.STDOUT,- start_new_session=True, **_as_session(cwd))+ start_new_session=True, **_as_session(cwd, env))except Exception as e: # noqa: BLE001rec.update(status="failed", error=f"spawn: {e}"[:500], done=True)return@@ -6818,7 +6827,7 @@ def _run_codex_appserver_bg(turn_id: str, cwd: str, env: dict, model: str, promptry:proc = subprocess.Popen(["codex", "app-server"], cwd=cwd, env=env, text=True, bufsize=1,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,- start_new_session=True, **_as_session(cwd))+ start_new_session=True, **_as_session(cwd, env))except Exception as e: # noqa: BLE001rec.update(status="failed", error=f"spawn app-server: {e}"[:500], done=True)return@@ -7105,7 +7114,7 @@ def _run_hermes_bg(turn_id: str, cwd: str, env: dict, model: str, provider: str,try:proc = subprocess.Popen(cmd, cwd=cwd, env=env, text=True, bufsize=1,stdout=subprocess.PIPE, stderr=subprocess.PIPE,- start_new_session=True, **_as_session(cwd))+ start_new_session=True, **_as_session(cwd, env))except Exception as e: # noqa: BLE001rec.update(status="failed", error=f"spawn: {e}"[:500], done=True)returndiff --git a/runner/tests/test_environments.py b/runner/tests/test_environments.pyindex bb19f1b5..cdd237e7 100644--- a/runner/tests/test_environments.py+++ b/runner/tests/test_environments.py@@ -103,9 +103,11 @@ def test_a_build_snapshots_the_source_installs_and_becomes_the_active_read_only_assert (v1 / ".venv" / "bin" / "python3").exists() or (v1 / ".venv" / "bin" / "python").exists()assert any(p["manager"] == "pip" and p["name"] == "pip" for p in rec["packages"])assert rec["files"] > 3 and rec["bytes"] > 0- assert oct(os.stat(v1 / "scripts" / "render.py").st_mode & 0o777) == "0o644"- assert oct(os.stat(v1 / "run.sh").st_mode & 0o777) == "0o755"- assert oct(os.stat(v1).st_mode & 0o777) == "0o755"+ # the layer is its group's to read and nobody else's; the source is the runner's alone+ assert oct(os.stat(v1 / "scripts" / "render.py").st_mode & 0o777) == "0o640"+ assert oct(os.stat(v1 / "run.sh").st_mode & 0o777) == "0o750"+ assert oct(os.stat(v1).st_mode & 0o777) == "0o750"+ assert oct(os.stat(E.source_dir("henv_b")).st_mode & 0o777) == "0o700"assert E.active_version("henv_b") == 1link = E.mount_path("content-studio")assert os.path.islink(link) and pathlib.Path(link).resolve() == v1.resolve()@@ -160,6 +162,42 @@ def test_the_turn_gets_the_path_the_variables_and_the_instructions(store):assert E.resolve({"id": "henv_t", "slug": "studio"})["path"] == link and os.path.islink(link)+def test_each_environment_gets_its_own_group_and_its_builds_run_as_it(store, monkeypatch):+ """The group model needs root; what a test process can pin is the allocation, the identity a+ build step gets, the group a turn joins, and that none of it applies off root."""+ E.write_file("henv_g1", "a.txt", b"a")+ assert E.env_gid("henv_g1") is None and E._build_as("henv_g1") == {} and E.secure_store() == 0 # not root: modes only+ owned, made = {}, []+ monkeypatch.setattr(E.os, "geteuid", lambda: 0)+ monkeypatch.setattr(E.os, "chown", lambda p, u, g: owned.__setitem__(str(p), (u, g)))+ monkeypatch.setattr(E.os, "lchown", lambda p, u, g: owned.__setitem__(str(p), (u, g)))+ monkeypatch.setattr(E, "_account", lambda n: made.append(n))+ real_stat = os.stat++ def fake_stat(p, *a, **k): # the directory's group is the record: replay what chown set+ st = real_stat(p, *a, **k)+ if str(p) in owned:+ class St:+ st_uid, st_gid, st_mode = owned[str(p)][0], owned[str(p)][1], st.st_mode+ return St()+ return st+ monkeypatch.setattr(E.os, "stat", fake_stat)+ E._claim("henv_g1"); E._claim("henv_g2")+ g1, g2 = E.env_gid("henv_g1"), E.env_gid("henv_g2")+ assert g1 and g2 and g1 != g2 and E.GID_BASE <= g1 < E.GID_BASE + E.GID_SPAN and made == [g1, g2]+ assert owned[str(E.env_dir("henv_g1"))] == (0, g1) and oct(real_stat(E.env_dir("henv_g1")).st_mode & 0o777) == "0o750"+ assert E._claim("henv_g1") == E.env_dir("henv_g1") and E.env_gid("henv_g1") == g1 # stable: read back, not reallocated+ assert E._build_as("henv_g1") == {"user": g1, "group": g1, "extra_groups": []}+ # a layer made read-only for the group is chowned root:group, links included+ v = E.version_dir("henv_g1", 1); (v / "bin").mkdir(parents=True); (v / "bin" / "tool").write_bytes(b"#!/bin/sh\n")+ os.chmod(v / "bin" / "tool", 0o755); os.symlink("tool", v / "bin" / "alias")+ E._read_only(v, g1)+ assert owned[str(v)] == (0, g1) and owned[str(v / "bin" / "tool")] == (0, g1) and owned[str(v / "bin" / "alias")] == (0, g1)+ assert oct(real_stat(v / "bin" / "tool").st_mode & 0o777) == "0o750"+ # the turn joins the group of the environment at its mount, and no group for a path outside the range+ assert E.reader_gid(str(v)) == g1 and E.reader_gid(str(store)) is None and E.reader_gid("") is None++def test_the_slug_is_a_path_segment(store):assert E.slug_ok("content-studio") and E.slug_ok("a.b_c") and not E.slug_ok("../x") and not E.slug_ok("a/b") and not E.slug_ok("")diff --git a/runner/tests/test_session_uids.py b/runner/tests/test_session_uids.pyindex b604259e..07f09ed7 100644--- a/runner/tests/test_session_uids.py+++ b/runner/tests/test_session_uids.py@@ -38,6 +38,11 @@ def test_session_uid_reads_the_directory_owner(tmp_path, monkeypatch):monkeypatch.setattr(server.os, "stat", lambda p, *a, **k: St() if str(p) == str(ws) else real_stat(p, *a, **k))assert server._session_uid(str(ws)) == fakeassert server._as_session(str(ws)) == {"user": fake, "group": fake, "extra_groups": []}+ # a turn that names an environment joins that environment's group, and only then+ gid = server.environments.GID_BASE + 3+ monkeypatch.setattr(server.environments, "reader_gid", lambda m: gid if m == "/env/studio" else None)+ assert server._as_session(str(ws), {"HR_ENVIRONMENT": "/env/studio"}) == {"user": fake, "group": fake, "extra_groups": [gid]}+ assert server._as_session(str(ws), {"PATH": "/usr/bin"}) == {"user": fake, "group": fake, "extra_groups": []}@pytest.mark.parametrize("name,stripped", [