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
2 changes: 1 addition & 1 deletion docs/system-specs/modules/learn-cron-dashboard.md
Original file line number Diff line number Diff line change
Expand Up @@ -1005,7 +1005,7 @@ command or script runners may access member memory.

- **Module layout**: `kiro_crew.cron_script` is the import path for all of it, and a `_facade_mirror` facade: `cron_script.py` keeps the two runners (`run_script_sandboxed`, `run_command_sandboxed`) and the command-shell probe, and a patch through it reaches the owners beside it. `cron_script_child_env.py` builds what a child starts with (the scrubbed env, the scratch and temp dirs, the internal secret, the dial port, the session token, the persistence preflight); `cron_script_redaction.py` bounds the redaction of captured output; `cron_script_paths.py` resolves a script spec; `cron_script_grants.py` validates, pins and applies vault-secret grants; `cron_script_procs.py` registers running children and kills one on cancel; `cron_script_mcp.py` is the MCP tool client; `cron_script_context.py` is `ScriptContext` and `Skip`/`Done`/`Report`. New script-cron code goes to the owner of its job, or to a new `cron_script_<role>.py`.
- **Script mode**: `script` field specifies a Python callable path (`~/.kiro/crew/crons/file.py:function`). The function receives a `ScriptContext` with `ctx.call_tool()` (MCP tool access), `ctx.notify()` (deliver message), `ctx.list_session_folders()` / `ctx.create_session_folder()` / `ctx.open_session()` / `ctx.send_to_session()` / `ctx.set_session_mode()` (dashboard sessions, see **Script-mode dashboard sessions** below), `ctx.crew_log_append()` (one record into the bound Bot's crew log, see **Script-mode Bot records** below), `ctx.message` (arguments from the `message` field). Control flow via exceptions: `raise Skip()` to silently retry next tick, `raise Done()` to complete and remove the job, `raise Report("msg")` to deliver a message and keep running.
- **Script path resolution and its two roots**: `resolve_script_path` (`cron_script_paths.py`) is the single resolver for every script spec, and its DEFAULT is the operator contract: a relative path resolves against the process CWD and the resolved file must sit under `~/.kiro/crew/crons/`. `cron_add`, the CLI's `cron add` and `cron preview` paths and both vault-grant sites take that default, so an authoring caller can never name a file outside `crons/`. An app cron's script legitimately ships inside the app's own bundle instead, and two opt-in keywords cover that, each opening exactly one root. `app_root` is passed where a MANIFEST's own spec is vetted (`apps.bridges`, `apps.cron_sdk`): it is the base a relative spec resolves against, because `"job.py:run"` means "next to my manifest" and is the only spelling an app can write without knowing its install location -- resolving it against the gateway process's CWD instead produced a path that changed with every launch and named a file that was never there (#11819) -- and containment narrows to that ONE bundle, so app A cannot name a script in app B's tree. `allow_bundle_roots` is passed only by the three consumers that re-resolve a spec ALREADY vetted and persisted while holding no app context (the fire-time governance gate, the launcher, the dashboard script-source endpoint); containment is then the shared bundle roots (`cron_script._trusted_script_bundle_roots`) -- the builtin manifest sources (the package's `apps/builtins` plus the active edition's manifest sources, the same walk `shipped_builtin_app_root` uses to choose a builtin's root) and `<config_dir>/apps`, with the package directory admitted only when that walk fails -- because a stored absolute bundle path is all those callers have to go on. The app bridge and the cron SDK therefore PERSIST the resolved absolute spec rather than the manifest's relative one: a relative value on the job record would be re-resolved against each consumer's own CWD. A bundle root accepts `.py` files only, which is containment and not style -- a bundle also holds `.app_secret` (the app's gateway credential) and `data/`, and a resolved script's bytes are readable through the script-source endpoint, so the suffix keeps every non-module bundle file off that surface; `crons/` keeps no such rule because it holds nothing else. A `..`-bearing relative spec is refused lexically before any join so the verdict never depends on the host's path grammar, and `resolve()` runs before containment so a link pointing out of a trusted root is rejected on its target. The vault-grant reader (`_read_script_body`) stays pinned to `crons/` alone and the grant paths pass neither keyword, so a bundle script can register and run but can never be handed a secret.
- **Script path resolution and its two roots**: `resolve_script_path` (`cron_script_paths.py`) is the single resolver for every script spec, and its DEFAULT is the operator contract: a relative path resolves against the process CWD and the resolved file must sit under `~/.kiro/crew/crons/`. On every path a `~/.kiro/crew/crons/...` spec (the spelling the cron help, tool schema and docs give) is rebased onto `<config_dir>/crons/` by `_data_home_spec` before resolution, so it follows `KIROCREW_HOME` and a persisted spec re-resolves to the same file at fire time; every other spec keeps the plain expansion, and the resolve, sensitive-path and containment checks judge the result. `cron_add`, the CLI's `cron add` and `cron preview` paths and both vault-grant sites take that default, so an authoring caller can never name a file outside `crons/`. An app cron's script legitimately ships inside the app's own bundle instead, and two opt-in keywords cover that, each opening exactly one root. `app_root` is passed where a MANIFEST's own spec is vetted (`apps.bridges`, `apps.cron_sdk`): it is the base a relative spec resolves against, because `"job.py:run"` means "next to my manifest" and is the only spelling an app can write without knowing its install location -- resolving it against the gateway process's CWD instead produced a path that changed with every launch and named a file that was never there (#11819) -- and containment narrows to that ONE bundle, so app A cannot name a script in app B's tree. `allow_bundle_roots` is passed only by the three consumers that re-resolve a spec ALREADY vetted and persisted while holding no app context (the fire-time governance gate, the launcher, the dashboard script-source endpoint); containment is then the shared bundle roots (`cron_script._trusted_script_bundle_roots`) -- the builtin manifest sources (the package's `apps/builtins` plus the active edition's manifest sources, the same walk `shipped_builtin_app_root` uses to choose a builtin's root) and `<config_dir>/apps`, with the package directory admitted only when that walk fails -- because a stored absolute bundle path is all those callers have to go on. The app bridge and the cron SDK therefore PERSIST the resolved absolute spec rather than the manifest's relative one: a relative value on the job record would be re-resolved against each consumer's own CWD. A bundle root accepts `.py` files only, which is containment and not style -- a bundle also holds `.app_secret` (the app's gateway credential) and `data/`, and a resolved script's bytes are readable through the script-source endpoint, so the suffix keeps every non-module bundle file off that surface; `crons/` keeps no such rule because it holds nothing else. A `..`-bearing relative spec is refused lexically before any join so the verdict never depends on the host's path grammar, and `resolve()` runs before containment so a link pointing out of a trusted root is rejected on its target. The vault-grant reader (`_read_script_body`) stays pinned to `crons/` alone and the grant paths pass neither keyword, so a bundle script can register and run but can never be handed a secret.
- **Residual: a script or command cron child can read every installed app's `.app_secret`**: making a bundle script resolvable means a cron child now legitimately runs with an app bundle on `sys.path`, and nothing masks `<config_dir>/apps` from it. `.app_secret` is a bearer credential rather than a marker -- `dashboard.token_auth.validate_app_secret` exchanges it for that app's scoped token -- and the `cc` profile both cron exec paths run under leaves it readable: `run_script_sandboxed` and `run_command_sandboxed` both call `wrap_argv(..., mode="cc")` with no apps mask. So an app-authored cron script, an operator script under `crons/`, and a command cron can each read any installed app's credential. This is not introduced by the path fix: the same read is available on a tree without it. It is recorded here because the path fix is what makes app-shipped cron scripts actually run, so the read goes from unreachable-in-practice to ordinary. Closing it is tracked separately (#16061), with the three conditions a fix has to satisfy at once.
- **Persisted bundle paths go stale if a bundle moves**: because the app bridge and the cron SDK store the RESOLVED absolute spec, and the manifest re-sync above refreshes a job only when its DEFINITION changed (the digest covers the manifest's relative `script`, not the resolved path), a bundle root that changes location under an unchanged manifest leaves the stored `job.script` naming the old path and the job fails `FileNotFoundError` at every fire. Recovery is to disable and re-enable the app, which re-registers the cron against the current root. Reachable only where a bundle root can move between runs, which today means the builtin/edition leg.
- **Script-mode MCP identity**: a script cron runs as the principal `cron:<job id>` — the same key `ScriptContext` presents to the gateway over HTTP (`X-Session-Key` / `caller_session`) and the key an agent cron's session runs under, so ownership and audit see one principal per job whichever surface the job uses. It is delivered on two hops: `run_script_sandboxed` exports `KIROCREW_SESSION_KEY=cron:<job id>` into the script child, and `McpToolClient` hard-assigns the same key on the env of every MCP server `ctx.call_tool()` spawns — after both the inherited-env and per-server `env` overlays, so a script that rewrites its own `os.environ` cannot present a different principal (best-effort friction on the same footing as the rest of the env-based identity contract, not a containment boundary). This is load-bearing rather than cosmetic: a direct MCP spawn is not routed through gatewayd, so it gets no caller block, and nobody publishes a signed `session_pid_*` sidecar for the launcher pid — leaving a script cron with **none** of the three sources `_resolve_session_key_strict()` accepts, which fails closed for writes only. Every state-mutating tool then returns its refusal as an ordinary result string while read-only calls keep working, so the job reports `ok` and writes nothing. Two consequences to keep in mind: `cloud.aws.assert_human_action` keys on the same env var, so destructive cloud verbs from a script cron are refused exactly as they are from an agent session; and job ownership is unchanged, so a script cron reaches only the jobs recorded under its own key (`cron_trigger` against another job stays refused, as it is for agent crons). The general rule this is one instance of: **a spawn path that hands a child MCP access must hand it an identity too**, because the strict resolver fails closed for writes alone and the omission is therefore silent.
Expand Down
3 changes: 2 additions & 1 deletion src/kiro_crew/cron_script.py
Original file line number Diff line number Diff line change
Expand Up @@ -1090,7 +1090,7 @@ def run_command_sandboxed(
from kiro_crew import agent_scratch # noqa: F401
from kiro_crew.agent_discovery import _read_agent_spec # noqa: F401
from kiro_crew.atomic_write import replace_with_retry # noqa: F401
from kiro_crew.config.loader import read_local_secret # noqa: F401
from kiro_crew.config.loader import CONFIG_DIR_NAME, read_local_secret # noqa: F401
from kiro_crew.config.paths import data_home, kiro_agents_dir # noqa: F401
from kiro_crew.cron_script_child_env import ( # noqa: F401
_CRON_ENV_DENY,
Expand Down Expand Up @@ -1151,6 +1151,7 @@ def run_command_sandboxed(
)
from kiro_crew.cron_script_paths import ( # noqa: F401
_bundle_relative_spec,
_data_home_spec,
_split_script_spec,
_trusted_script_bundle_roots,
)
Expand Down
24 changes: 22 additions & 2 deletions src/kiro_crew/cron_script_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import os
from pathlib import Path

from kiro_crew.config.loader import config_dir
from kiro_crew.config.loader import CONFIG_DIR_NAME, config_dir
from kiro_crew.platform_compat import strip_extended_length_prefix
from kiro_crew.security import canonical_path_refusal, is_unverifiable_path_refusal

Expand Down Expand Up @@ -132,6 +132,24 @@ def _bundle_relative_spec(module_part: str, app_root: Path) -> str:
return str(app_root / expanded)


def _data_home_spec(module_part: str) -> str:
"""Rebase the documented ``~/.kiro/crew/crons/...`` spelling onto ``config_dir()``.

``expanduser`` alone maps it onto the real home, which under a
``KIROCREW_HOME`` override holds no ``crons/`` this resolver admits. Every
other spec, ``~/.kiro/crew/dev/crons/...`` for an override nested in the
default home included, keeps the plain expansion. Path arithmetic on the
spec only: resolution, the sensitive-path check and containment stay in
:func:`resolve_script_path`.
"""
spelling = Path("~", CONFIG_DIR_NAME, "crons")
try:
tail = Path(module_part).relative_to(spelling)
except ValueError:
return module_part
return str(config_dir() / "crons" / tail)


def resolve_script_path(
script_path: str,
*,
Expand All @@ -144,7 +162,8 @@ def resolve_script_path(
contract, byte for byte: a relative path resolves against the process CWD,
and the resolved file must sit under ``<config_dir>/crons/``. ``cron_add``,
the CLI and the vault-grant paths pass neither keyword, so nothing below
reaches them.
reaches them. On every path a ``~/.kiro/crew/crons/...`` spec names the
configured data home's ``crons/`` (:func:`_data_home_spec`).

An app cron's script legitimately lives in the app's own bundle rather than
in ``crons/``, and the two keywords are how a caller says so. They are
Expand Down Expand Up @@ -197,6 +216,7 @@ def resolve_script_path(

if app_root is not None:
module_part = _bundle_relative_spec(module_part, app_root)
module_part = _data_home_spec(module_part)
file_path = Path(os.path.expanduser(module_part)).resolve()
if not file_path.exists():
raise FileNotFoundError(f"Script file not found: {file_path}")
Expand Down
62 changes: 62 additions & 0 deletions test/test_cron_script_more_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import json
import os
import re
import subprocess
import sys
import tempfile
Expand Down Expand Up @@ -967,6 +968,67 @@ def test_allowed_script_resolves(self, tmp_path, monkeypatch):
assert os.path.realpath(resolved) == os.path.realpath(str(script))
assert func == "run"

@staticmethod
def _homes(tmp_path, monkeypatch, data_home: Path) -> None:
"""Point ``~`` at a scratch user home and ``KIROCREW_HOME`` at *data_home*."""
for var in ("HOME", "USERPROFILE"):
monkeypatch.setenv(var, str(tmp_path / "user"))
monkeypatch.setenv("KIROCREW_HOME", str(data_home))
(data_home / "crons").mkdir(parents=True)

def test_the_documented_tilde_spelling_names_the_configured_data_home(
self, tmp_path, monkeypatch
):
"""``~/.kiro/crew/`` in a spec follows ``KIROCREW_HOME``, still held to ``crons/``."""
data_home = tmp_path / "data-home"
self._homes(tmp_path, monkeypatch, data_home)
script = data_home / "crons" / "job.py"
script.write_text("def run(ctx): pass\n", newline="\n")
(data_home / "loose.py").write_text("def run(ctx): pass\n", newline="\n")
missing = re.escape(str((data_home / "crons" / "missing.py").resolve()))

with pytest.raises(FileNotFoundError, match=missing):
resolve_script_path("~/.kiro/crew/crons/missing.py:run")
resolved = resolve_script_path("~/.kiro/crew/crons/job.py:run")
assert resolved == (str(script.resolve()), "run")
assert resolve_script_path("~/.kiro/crew/crons/job.py:run", allow_bundle_roots=True) == (
resolved
)
with pytest.raises(PermissionError, match="Script must be under"):
resolve_script_path("~/.kiro/crew/crons/../loose.py:run")

@pytest.mark.skipif(
sys.platform == "win32", reason="a directory symlink needs a privilege on Windows"
)
def test_a_nested_data_home_that_links_out_of_the_default_keeps_its_spelling(
self, tmp_path, monkeypatch
):
"""``~/.kiro/crew/dev`` linked to a disk elsewhere still reads ``.../dev/crons/``."""
data_home = tmp_path / "user" / ".kiro" / "crew" / "dev"
data_home.parent.mkdir(parents=True)
(tmp_path / "data").mkdir()
data_home.symlink_to(tmp_path / "data", target_is_directory=True)
self._homes(tmp_path, monkeypatch, data_home)
script = data_home / "crons" / "job.py"
script.write_text("def run(ctx): pass\n", newline="\n")

resolved, _func = resolve_script_path("~/.kiro/crew/dev/crons/job.py:run")

assert Path(resolved) == script.resolve()

def test_a_data_home_above_the_default_still_takes_the_documented_spelling(
self, tmp_path, monkeypatch
):
"""``KIROCREW_HOME=~/.kiro`` reads ``~/.kiro/crew/crons/`` as its own ``crons/``."""
data_home = tmp_path / "user" / ".kiro"
self._homes(tmp_path, monkeypatch, data_home)
script = data_home / "crons" / "job.py"
script.write_text("def run(ctx): pass\n", newline="\n")

resolved, _func = resolve_script_path("~/.kiro/crew/crons/job.py:run")

assert Path(resolved) == script.resolve()

def test_internal_secret_prefers_the_environment(self, monkeypatch):
monkeypatch.setenv("KIROCREW_INTERNAL_SECRET", "env-secret")
monkeypatch.setattr(cron_script, "read_local_secret", lambda port, **_kw: "file-secret")
Expand Down
Loading