Repository navigation
fix(kanban): parent-granted self-scope carve-out for delegated child self-report #119108
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,6 +17,12 @@ | |
| # so delegate_task-specific behaviour (subprocess env scrubbing, its error strings) is unchanged. | ||
| _NON_DISPATCHER_OWNED_CONTEXT: ContextVar[bool] = ContextVar("hermes_non_dispatcher_owned_context", default=False) | ||
|
|
||
| # ``(task_id, claim_lock)`` a child may self-report against — captured FROM THE PARENT at the | ||
| # moment of delegation, never read out of the child's own environment. See | ||
| # :func:`delegated_self_scope_grant`. | ||
| _SELF_SCOPE_GRANT: ContextVar["tuple[str, str | None] | None"] = ContextVar( | ||
| "hermes_delegated_self_scope_grant", default=None) | ||
|
|
||
| DELEGATED_CHILD_ENV_MARKER = "HERMES_DELEGATED_CHILD_CONTEXT" | ||
|
|
||
| KANBAN_ENV_KEYS: tuple[str, ...] = ( | ||
|
|
@@ -142,6 +148,69 @@ def kanban_path_is_fenced(path: "os.PathLike[str] | str") -> bool: | |
| return True | ||
|
|
||
|
|
||
| def is_delegated_child_in_process_context() -> bool: | ||
| """True when THIS context is an in-process ``delegate_task`` child. | ||
|
|
||
| ContextVar-only: never true for a spawned descendant that merely carries the | ||
| ``HERMES_DELEGATED_CHILD_CONTEXT`` env marker. The mutation gate uses this to | ||
| separate the blanket in-process deny (parent's own board) from the path-scoped | ||
| fence that governs exec'd descendants. | ||
| """ | ||
| return bool(_DELEGATED_CHILD_CONTEXT.get()) | ||
|
|
||
|
|
||
| @contextmanager | ||
| def delegated_self_scope_grant(task_id: str | None, claim_lock: str | None = None) -> Iterator[None]: | ||
| """Hand a child the ONE task id it may self-report against (comment/attach). | ||
|
|
||
| The identity is captured by the PARENT — the dispatcher-owned worker that | ||
| still holds ``HERMES_KANBAN_TASK`` and its claim lock — and handed down as | ||
| context, never re-read from the child's own environment. ``scrub_kanban_env`` | ||
| strips ``HERMES_KANBAN_TASK`` from every child env by construction, so an | ||
| env-keyed carve-out could only ever fire on an id the child supplied itself, | ||
| which is precisely the prompt-injection vector the ownership gate exists to | ||
| stop. A grant is in-process only: it does not cross ``scrub_kanban_env``, so | ||
| a subprocess descendant of the child stays fully fenced. | ||
| """ | ||
| tid = (task_id or "").strip() | ||
| token = _SELF_SCOPE_GRANT.set((tid, (claim_lock or "").strip() or None) if tid else None) | ||
| try: | ||
| yield | ||
| finally: | ||
| _SELF_SCOPE_GRANT.reset(token) | ||
|
|
||
|
|
||
| def self_scope_grant() -> tuple[str, str | None] | None: | ||
| """``(task_id, claim_lock)`` this context may self-report against, else None. | ||
|
|
||
| Fails closed in a subprocess: the grant is a ContextVar, so it is absent in | ||
| any spawned descendant even though the env marker survives. | ||
| """ | ||
| return _SELF_SCOPE_GRANT.get() | ||
|
|
||
|
|
||
| def capture_self_scope_identity() -> tuple[str, str | None] | None: | ||
| """Read the dispatcher-issued identity of the CURRENT process, in the parent's frame. | ||
|
|
||
| Call this BEFORE entering ``delegated_child_context`` — it is only truthful | ||
| while the caller is still the dispatcher-owned worker. Returns ``None`` for a | ||
| delegated child, an in-process cron run, or a plain session, so a child that | ||
| delegates further hands its grandchild nothing. | ||
| """ | ||
| if not is_dispatcher_owned_worker_context(): | ||
| return None | ||
| task_id = (os.environ.get("HERMES_KANBAN_TASK") or "").strip() | ||
| if not task_id: | ||
| return None | ||
| return task_id, (os.environ.get("HERMES_KANBAN_CLAIM_LOCK") or "").strip() or None | ||
|
|
||
|
|
||
| def is_self_scoped_write(task_id: str | None) -> bool: | ||
| """True when ``task_id`` is exactly the dispatcher-provided grant for this context.""" | ||
| grant = _SELF_SCOPE_GRANT.get() | ||
| return bool(grant and task_id and str(task_id).strip() == grant[0]) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1 — the captured claim generation is never validated. The grant stores |
||
|
|
||
|
|
||
| @overload | ||
| def delegated_child_subprocess_env(env: Mapping[str, str]) -> dict[str, str]: ... | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -673,11 +673,21 @@ def connect(db_path: Optional[Path] = None, *, board: Optional[str] = None) -> s | |
| :func:`kanban_db_path` (``HERMES_KANBAN_DB`` -> ``HERMES_KANBAN_BOARD`` -> | ||
| ``<root>/kanban/current`` -> ``default``).""" | ||
| path = db_path if db_path is not None else _kb.kanban_db_path(board=board) | ||
| from agent.delegation_context import kanban_path_is_fenced | ||
| if kanban_path_is_fenced(path): | ||
| # Reads must not enter schema/backfill write transactions. Never create a | ||
| # missing board or migrate on a descendant's behalf; the owner initializes it. | ||
| conn = sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True) | ||
| from agent.delegation_context import ( | ||
| is_delegated_child_in_process_context, kanban_path_is_fenced, self_scope_grant, | ||
| ) | ||
| if not kanban_path_is_fenced(path): | ||
| pass # unfenced (owner, or descendant scratch board outside the fenced root) | ||
| else: | ||
| # Fenced: reads only, except the ONE writable case — an in-process child | ||
| # holding a dispatcher-issued grant (its own card's comment/attach rows). | ||
| # ``_sqlite_connect`` keeps busy_timeout so a concurrent parent write waits | ||
| # instead of instant-locking. Never init_db / migrations here; missing | ||
| # schema fails closed. | ||
| if is_delegated_child_in_process_context() and self_scope_grant() is not None: | ||
| conn = _sqlite_connect(path) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1 — this widens two sanctioned writes into a generic writable database capability. |
||
| else: | ||
| conn = sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True) | ||
| conn.row_factory = sqlite3.Row | ||
| conn.text_factory = _kb._lossy_text | ||
| if not _schema_is_present(conn): | ||
|
|
@@ -1188,7 +1198,8 @@ def _main_db_file(conn: sqlite3.Connection) -> Optional[str]: | |
|
|
||
|
|
||
| @contextlib.contextmanager | ||
| def write_txn(conn: sqlite3.Connection, *, allow_nested: bool = False): | ||
| def write_txn(conn: sqlite3.Connection, *, allow_nested: bool = False, | ||
| self_scoped_task: str | None = None): | ||
| """IMMEDIATE write transaction; a claim CAS inside is atomic — at most one | ||
| concurrent writer succeeds. | ||
|
|
||
|
|
@@ -1197,8 +1208,13 @@ def write_txn(conn: sqlite3.Connection, *, allow_nested: bool = False): | |
| ``add_comment``) opt in — helpers with post-commit side effects | ||
| (``complete_task`` & co.) must never run under an open outer transaction, | ||
| since those side effects would fire while the outer txn can still roll back. | ||
|
|
||
| ``self_scoped_task`` forwards the self-report carve-out to | ||
| ``_assert_not_delegated_child_mutation``: only the two write paths a | ||
| delegated child may use on ITS OWN dispatcher-granted task (``add_comment``, | ||
| ``add_attachment``) pass it. Every other writer keeps failing closed. | ||
| """ | ||
| _kb._assert_not_delegated_child_mutation(_main_db_file(conn)) | ||
| _kb._assert_not_delegated_child_mutation(path=_main_db_file(conn), self_scoped_task=self_scoped_task) | ||
| if getattr(conn, "in_transaction", False): | ||
| if not allow_nested: | ||
| raise RuntimeError( | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P1 — this is not parent-only authority. A delegated child can import this same context manager and call
delegated_self_scope_grant(foreign_id, ...); there is no issuer/context check before_SELF_SCOPE_GRANT.set. The newtest_h_nested_grant_cannot_widen_scopeeven proves the dangerous intermediate state by assertingis_self_scoped_write(foreign) is Trueinside a nested foreign grant. From thereadd_comment/add_attachmentaccept the forged id. Install the grant only from the dispatcher-owned parent frame (before entering child context), refuse replacement from a child/already-granted scope, and add the foreign-write regression.