Item 3: an agent cannot approve its own proposals: the before-tool hook refuses sisi approve in any wrapping; a decision needs the typed word read from the controlling terminal; refused attempts are recorded with the session. done / next: items 4 and 9 (backlog and pending-approval statuses, main-repo origin)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4418136d01
commit
11554b759a
7 files changed
+405
-28
No files matched your search
+36
-12
@@ -28,18 +28,41 @@ limited, and the rest waits for you:
|
||||
own trusted project, a risk pattern that lowers a profile, any replaced or disabled rule, and rule text or a
|
||||
library entry from a learning confined to one project. Protected rules (`canon/protected.json`) cannot be changed
|
||||
by a cycle or by `sisi overlay` at all, and if that file cannot be read, no rule can be changed.
|
||||
- Replaying a command check runs it, so a replay happens only in a repository on the trust list, only if the
|
||||
command exists at both commits, and only if the earlier commit is an ancestor of the later one.
|
||||
- A cycle file is untrusted input, and `sisi cycle check` never executes anything from it. `sisi cycle apply`
|
||||
replays a command check only in a repository on the trust list, only between two commits taken from the learning's
|
||||
own record (its unit's start and closing commits, or the ones stored with the finding; never from the file), only
|
||||
if the command names a path that differs between the two trees, and only inside an exported copy of each
|
||||
commit's tree: no `.git` directory (the command cannot read history), an environment of `PATH`, `HOME` (an empty
|
||||
directory) and `LANG` only (none of the caller's credentials or tokens), a time limit, and the copy deleted
|
||||
afterwards. A learning with no recorded commits cannot be validated: its command check waits for you as
|
||||
`unvalidated`. What this does not do: the replayed command still runs as you, with your file permissions, and
|
||||
sisi does not sandbox it; which is why a command that was not seen to fail and then pass waits for you.
|
||||
|
||||
`sisi approve` lists every waiting change in full (the exact command, the pattern and profile, the rule text as a
|
||||
diff) and decides it with `--yes` or `--no`. What this does guarantee: a decision from a process with no terminal
|
||||
(an agent, a script, a pipe) is refused, unless your config has `learning.agent_relayed_approval` set (off by
|
||||
default), and then the record says `relayed by an agent`; every decision is written to `approvals.jsonl` with the
|
||||
time, the session if known, and whether it came from a terminal. What it does not guarantee: sisi cannot tell a
|
||||
person at a terminal from a program that allocates one, and anyone who can write your personal data folder can
|
||||
edit the config, the pending list or the ledger directly. The protection is that an agent is told to show you the
|
||||
change and to give you the command to type yourself, and that the cycle cannot apply anything consequential on its
|
||||
own; it is not a defence against code that already runs with your permissions.
|
||||
diff). Deciding one takes two layers:
|
||||
|
||||
- The before-tool hook refuses any shell command an agent runs whose text invokes `sisi approve` with an argument,
|
||||
however it is wrapped (`script`, `sh -c`, `env`, `expect`, a path to the launcher, `python -m sisi`, quotes and
|
||||
backslashes inside the words), for main threads and workers alike, and tells the agent that approval is yours
|
||||
alone and to show you the command to run yourself. The plain listing (`sisi approve` with no arguments) is
|
||||
allowed. The hook fails open on an error, so it is a guard, not a wall: a command built from pieces, from a
|
||||
variable or from an encoded string is not recognised by its text.
|
||||
- `sisi approve ID --yes|--no` itself prints the whole action and a short random word on the controlling terminal
|
||||
device (`/dev/tty`, never standard input) and decides only when that word is typed back there. A process with no
|
||||
controlling terminal is refused; so is one whose terminal returns the wrong word or nothing. This is the typed
|
||||
word, and it is what `script -qec "sisi approve ID --yes" /dev/null </dev/null` runs into: the pseudo-terminal it
|
||||
allocates has nobody typing at it.
|
||||
|
||||
Every refused attempt, by the hook or by the command, is written to `approvals.jsonl` with the session id; every
|
||||
decision is written there with the time, the session if known, and whether a terminal was used. Your config may set
|
||||
`learning.agent_relayed_approval` (off by default): then a decision from a process with no terminal is accepted and
|
||||
the record says `relayed by an agent`. What this does not stop: an agent that can read and write a terminal it
|
||||
allocated itself (`expect`, a pty library) sees the word and can type it, and the hook's text check does not see
|
||||
every way of writing a command. Neither layer proves who is at the keyboard, and anyone who can write your personal
|
||||
data folder can edit the config, the pending list or the ledger directly. The protection is that an agent is told to
|
||||
show you the change and give you the command to type yourself, that the hook and the typed word make doing it for you
|
||||
hard and leave a record, and that the cycle cannot apply anything consequential on its own; it is not a defence
|
||||
against code that already runs with your permissions.
|
||||
|
||||
The same limit applies to who recorded something. A learning recorded from a subagent is held as a candidate until
|
||||
the parent adopts it by id. "Recorded by a subagent" is read from what the hooks recorded in the session record, not
|
||||
@@ -71,7 +94,8 @@ that could be exploited. Include the version (`sisi --version`), what you did, a
|
||||
The trust list guarantees only that an untrusted project's contract does not run; it does not
|
||||
make a trusted contract safe. Protected rules guarantee that a cycle or overlay cannot change
|
||||
them; they do not stop someone who can write the product folder. Owner approval guarantees
|
||||
that a consequential change waits and that a decision without a terminal is refused unless
|
||||
relayed approval is allowed in config; it does not prove who was at the terminal. The
|
||||
that a consequential change waits and that a decision needs the word typed at a controlling terminal (and is
|
||||
refused for an agent's shell command by the before-tool hook) unless relayed approval is allowed in config; it
|
||||
does not stop a program that allocates its own terminal and reads it, and does not prove who was at the keyboard. The
|
||||
delivery ledger guarantees that only rows sisi's own commands wrote, as written, are
|
||||
delivered; it does not prove the content of a row is true.
|
||||
+100
-11
@@ -718,13 +718,83 @@ def revert_cycle(cid=None):
|
||||
|
||||
# ---- approval -------------------------------------------------------------------------
|
||||
|
||||
def _stdin_is_tty():
|
||||
TYPED_WAIT_S = 300 # how long a decision waits for the owner to type the word
|
||||
|
||||
|
||||
class _Terminal:
|
||||
"""The controlling terminal device, opened for reading and for writing (one text file object
|
||||
cannot do both on a terminal)."""
|
||||
|
||||
def __init__(self):
|
||||
self._r = open("/dev/tty", "r", encoding="utf-8")
|
||||
try:
|
||||
self._w = open("/dev/tty", "w", encoding="utf-8")
|
||||
except OSError:
|
||||
self._r.close()
|
||||
raise
|
||||
|
||||
def write(self, text):
|
||||
self._w.write(text)
|
||||
|
||||
def flush(self):
|
||||
self._w.flush()
|
||||
|
||||
def fileno(self):
|
||||
return self._r.fileno()
|
||||
|
||||
def readline(self):
|
||||
return self._r.readline()
|
||||
|
||||
def close(self):
|
||||
for f in (self._r, self._w):
|
||||
try:
|
||||
f.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _open_terminal():
|
||||
"""The controlling terminal, or None when the process has none. Never standard input: a pipe,
|
||||
a file or a script's stdin can carry words; a terminal device is what a person sits at."""
|
||||
try:
|
||||
return bool(sys.stdin is not None and sys.stdin.isatty())
|
||||
except (ValueError, OSError):
|
||||
return _Terminal()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _decision_word():
|
||||
import secrets
|
||||
c, v = "bdfgklmnprstvz", "aeiou"
|
||||
return "".join(secrets.choice(c) + secrets.choice(v) for _ in range(3))
|
||||
|
||||
|
||||
def _typed_word(tty, word):
|
||||
"""True when the owner typed `word` at the terminal (read from the device, with a time limit)."""
|
||||
import select
|
||||
try:
|
||||
tty.write("Type the word %s to decide, anything else cancels: " % word)
|
||||
tty.flush()
|
||||
try:
|
||||
fd = tty.fileno()
|
||||
except (AttributeError, OSError, ValueError):
|
||||
fd = None
|
||||
if fd is not None and not select.select([fd], [], [], TYPED_WAIT_S)[0]:
|
||||
return False
|
||||
return tty.readline().strip() == word
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def refuse_attempt(pid, why, how="approve", session=None):
|
||||
"""Every refused attempt to decide a change is recorded, with the session id it came from."""
|
||||
try:
|
||||
L.record_approval({"id": pid or "", "decision": "refused", "ts": L.now(), "how": how, "why": why,
|
||||
"session": session or os.environ.get("SISI_SESSION_ID") or None})
|
||||
except Exception as e: # recording must not turn a refusal into a crash
|
||||
from . import store
|
||||
store.log_error("approve-refused-record", e)
|
||||
|
||||
|
||||
def relay_allowed():
|
||||
"""May an agent relay the owner's decision? Off unless the user's config says so."""
|
||||
try:
|
||||
@@ -856,27 +926,46 @@ def cmd_approve(argv):
|
||||
for i in items:
|
||||
print("\n".join(describe_pending(i)))
|
||||
print()
|
||||
print("The owner decides, in a terminal: sisi approve ID --yes | --no")
|
||||
print("The owner decides, in a terminal: sisi approve ID --yes | --no (and types the word it shows)")
|
||||
return 0
|
||||
pid, yes = argv[0], "--yes" in argv
|
||||
if not yes and "--no" not in argv:
|
||||
print("usage: sisi approve [ID --yes | --no]", file=sys.stderr)
|
||||
return 2
|
||||
tty = _stdin_is_tty()
|
||||
item = next((i for i in items if i.get("id") == pid), None)
|
||||
tty = _open_terminal()
|
||||
relayed = False
|
||||
if not tty:
|
||||
if tty is None:
|
||||
if not relay_allowed():
|
||||
item = next((i for i in items if i.get("id") == pid), None)
|
||||
if item:
|
||||
print("\n".join(describe_pending(item)), file=sys.stderr)
|
||||
print("sisi approve: refused. A decision must be made by the owner in a terminal: this was run "
|
||||
"without one (an agent, a script, a pipe). Show the owner what it does (the listing above) "
|
||||
"and give the owner the command to type. To allow an agent to relay a decision, set "
|
||||
refuse_attempt(pid, "no controlling terminal")
|
||||
print("sisi approve: refused. A decision is the owner's, typed at a terminal: this process has no "
|
||||
"controlling terminal (an agent, a script, a pipe). Show the owner what it does (the listing "
|
||||
"above) and give the owner the command to type. To allow an agent to relay a decision, set "
|
||||
"learning.agent_relayed_approval in the user config (off by default).", file=sys.stderr)
|
||||
return 2
|
||||
relayed = True
|
||||
else:
|
||||
try:
|
||||
if item is None:
|
||||
print("sisi approve: no pending change %r (`sisi approve` lists them)" % pid, file=sys.stderr)
|
||||
return 2
|
||||
word = _decision_word()
|
||||
tty.write("\n".join(describe_pending(item)) + "\n\nYou are about to %s %s.\n"
|
||||
% ("APPROVE" if yes else "REFUSE", pid))
|
||||
if not _typed_word(tty, word):
|
||||
refuse_attempt(pid, "the word was not typed at the terminal")
|
||||
print("sisi approve: refused. The word was not typed at the terminal, so nothing was decided.",
|
||||
file=sys.stderr)
|
||||
return 2
|
||||
finally:
|
||||
try:
|
||||
tty.close()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
print(apply_pending(pid, yes, {"terminal": tty, "relayed": relayed}))
|
||||
print(apply_pending(pid, yes, {"terminal": tty is not None, "relayed": relayed}))
|
||||
return 0
|
||||
except (CycleError, overlay.OverlayError, documents.DocumentError) as e:
|
||||
print("sisi approve: %s" % e, file=sys.stderr)
|
||||
|
||||
@@ -120,10 +120,46 @@ def note_shell(sess, cmd, payload):
|
||||
del shells[:-8]
|
||||
|
||||
|
||||
_APPROVE = re.compile(r"(?:^|[\s/;&|(=`$])(?:sisi|sisi\.py|__main__\.py)(?=\s)(?:\s+-{1,2}[\w=-]+)*\s+approve\b([^;&|\n)`]*)")
|
||||
_DECISION = re.compile(r"\bP-\d+\b[\s\S]*--(?:yes|no)\b|--(?:yes|no)\b[\s\S]*\bP-\d+\b")
|
||||
APPROVE_REFUSED = ("sisi: refused. Approving or refusing a learning change is the owner's alone; an agent does not "
|
||||
"run `sisi approve ID --yes|--no`, however it is wrapped. Show the owner what is waiting (run "
|
||||
"`sisi approve` with no arguments to list it, and show him the listing) and give him the command "
|
||||
"to type himself in a terminal.")
|
||||
|
||||
|
||||
def refuse_self_approval(cmd, sid):
|
||||
"""Before-tool guard, for main threads and workers alike: a shell command whose text invokes
|
||||
sisi's approve command with an argument is refused (exit 2, the reason on stderr), however it
|
||||
is wrapped (`script`, `sh -c`, `env`, `expect`, a path to the launcher, `python -m sisi`). The
|
||||
plain listing, `sisi approve`, is allowed. Quotes, backslashes and IFS tricks are stripped
|
||||
before the text is read. The attempt is recorded in the store with the session id. Fails open:
|
||||
an error in this check never holds up a tool call. Text can hide a command (a variable built
|
||||
from pieces, an encoded string); SECURITY.md says so, and the typed word that `sisi approve`
|
||||
itself requires at the terminal is the second layer."""
|
||||
try:
|
||||
text = re.sub(r"\$\{?IFS\}?", " ", re.sub(r"[\"'\\]", "", cmd or ""))
|
||||
m = _APPROVE.search(text)
|
||||
hit = bool(m and m.group(1).strip()) or bool(re.search(r"\bsisi\b", text) and _DECISION.search(text))
|
||||
if not hit:
|
||||
return
|
||||
pid = re.search(r"\bP-\d+\b", text)
|
||||
from . import cycle
|
||||
cycle.refuse_attempt(pid.group(0) if pid else "", "an agent's shell command invoked it (refused by the "
|
||||
"before-tool hook)", how="hook", session=sid)
|
||||
except Exception as e:
|
||||
store.log_error("watch-refuse-approval", e)
|
||||
return
|
||||
import sys
|
||||
sys.stderr.write(APPROVE_REFUSED + "\n")
|
||||
raise SystemExit(2)
|
||||
|
||||
|
||||
def before(payload):
|
||||
tool, cmd, _ev, cwd, sid = extract(payload)
|
||||
if not is_shell(tool, cmd):
|
||||
return
|
||||
refuse_self_approval(cmd, sid)
|
||||
sid = sid or "cwd-" + cwd
|
||||
sess = _session(sid, payload, cwd)
|
||||
note_shell(sess, cmd, payload)
|
||||
|
||||
@@ -56,6 +56,12 @@ class SisiCase(unittest.TestCase):
|
||||
for k in ("SISI_TOOL", "SISI_SESSION_ID"):
|
||||
os.environ.pop(k, None)
|
||||
|
||||
# no test may talk to the terminal it is run from: `sisi approve` finds none unless the test says so
|
||||
from unittest import mock as _mock
|
||||
_no_tty = _mock.patch("sisi.cycle._open_terminal", return_value=None)
|
||||
_no_tty.start()
|
||||
self.addCleanup(_no_tty.stop)
|
||||
|
||||
def restore():
|
||||
for k, v in saved.items():
|
||||
if v is None:
|
||||
@@ -143,3 +149,42 @@ def skip_timing_if_busy(case):
|
||||
return
|
||||
if load > cpus:
|
||||
case.skipTest("machine overloaded (load %.0f on %d processors): speed not measured" % (load, cpus))
|
||||
|
||||
|
||||
class FakeTerminal:
|
||||
"""What `sisi approve` reads its decision from. Writes are kept; the line it answers with is the
|
||||
word the prompt asked for (or `typed`, to type something else, or None to type nothing)."""
|
||||
|
||||
def __init__(self, typed="the word"):
|
||||
self.out, self.typed = [], typed
|
||||
|
||||
def write(self, text):
|
||||
self.out.append(text)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
def readline(self):
|
||||
if self.typed is None:
|
||||
return ""
|
||||
if self.typed != "the word":
|
||||
return self.typed + "\n"
|
||||
import re
|
||||
m = re.search(r"Type the word (\w+)", "".join(self.out))
|
||||
return (m.group(1) if m else "") + "\n"
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
@property
|
||||
def text(self):
|
||||
return "".join(self.out)
|
||||
|
||||
|
||||
def terminal(typed="the word"):
|
||||
"""Patch: the process has a controlling terminal, and the owner types `typed` at it."""
|
||||
from unittest import mock
|
||||
t = FakeTerminal(typed)
|
||||
p = mock.patch("sisi.cycle._open_terminal", return_value=t)
|
||||
p.fake = t
|
||||
return p
|
||||
@@ -3,7 +3,7 @@
|
||||
Each test is an abuse case: the cycle file's author (an agent, untrusted) tries to get something
|
||||
to run, validate or take effect that nobody approved.
|
||||
"""
|
||||
import json, os, subprocess, sys
|
||||
import json, os, subprocess, sys, unittest
|
||||
|
||||
from support import SisiCase
|
||||
from test_learning_loop import Base, PROMOTE, FINDING, CAUSE, _contract
|
||||
@@ -130,3 +130,186 @@ class Replay(Base):
|
||||
r = self.apply([self.cmd_action("grep -q fixed f.txt")])
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertEqual(self.rows()[0]["validation"]["result"], "validated")
|
||||
|
||||
|
||||
def _shell_payload(cmd, sid="sess-hook"):
|
||||
return {"hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": {"command": cmd},
|
||||
"session_id": sid, "cwd": os.getcwd()}
|
||||
|
||||
|
||||
class Approval(Base):
|
||||
"""R-11.5-11, R-14.3-2, R-16-11, R-16-8 (item 3): an agent cannot approve its own proposals."""
|
||||
|
||||
def park(self):
|
||||
_contract(self)
|
||||
self.git_init()
|
||||
self.retro(*PROMOTE[1:])
|
||||
self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
|
||||
"cmd": "make deploy --force-everything"}])
|
||||
self.assertEqual(len(self.pending()), 1)
|
||||
|
||||
def hook(self, cmd, sid="sess-hook"):
|
||||
"""Run the before-tool hook on a shell command. Returns the exit code the hook ends with."""
|
||||
import contextlib, io
|
||||
from sisi import watch
|
||||
try:
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
watch.before(_shell_payload(cmd, sid))
|
||||
except SystemExit as e:
|
||||
return e.code
|
||||
return 0
|
||||
|
||||
def test_the_before_tool_hook_refuses_every_wrapping_of_approve(self):
|
||||
"""R-14.3-2 (item 3a): script, sh -c, env, expect, a path to the launcher and python -m sisi."""
|
||||
self.park()
|
||||
wrapped = [
|
||||
'script -qec "sisi approve P-0001 --yes" /dev/null </dev/null',
|
||||
"sh -c 'sisi approve P-0001 --yes'",
|
||||
"/path/to/bin/sisi approve P-0001 --yes",
|
||||
"python3 -m sisi approve P-0001 --yes",
|
||||
"env SISI_SESSION_ID=x sisi approve P-0001 --no",
|
||||
"expect -c 'spawn sisi approve P-0001 --yes; expect eof'",
|
||||
"echo P-0001 | xargs sisi approve --yes",
|
||||
"bash -lc \"cd /tmp && sisi approve P-0001 --yes\"",
|
||||
"s\\isi 'app'rove P-0001 --yes",
|
||||
"sisi${IFS}approve${IFS}P-0001${IFS}--yes",
|
||||
"cd x; sisi approve P-0001 --yes; echo done",
|
||||
"a=approve; sisi $a P-0001 --yes",
|
||||
]
|
||||
for cmd in wrapped:
|
||||
with self.subTest(cmd=cmd):
|
||||
self.assertEqual(self.hook(cmd), 2, cmd)
|
||||
self.assertEqual(len(self.pending()), 1)
|
||||
refused = [r for r in L.load_approvals() if r.get("decision") == "refused"]
|
||||
self.assertEqual(len(refused), len(wrapped))
|
||||
self.assertTrue(all(r["session"] == "sess-hook" and r["how"] == "hook" for r in refused))
|
||||
self.assertEqual(refused[0]["id"], "P-0001")
|
||||
|
||||
def test_the_listing_and_other_commands_are_allowed_through_the_hook(self):
|
||||
"""R-14.3-2 (item 3a): `sisi approve` with no arguments is the listing; nothing else is touched."""
|
||||
for cmd in ("sisi approve", "/path/to/bin/sisi approve", "sisi approve | head -20", "python3 -m sisi approve;",
|
||||
"sisi cycle apply f.json", "sisi cycle check c.json", "echo approve the plan",
|
||||
"git commit -m 'approve the design'", "ls"):
|
||||
with self.subTest(cmd=cmd):
|
||||
self.assertEqual(self.hook(cmd), 0, cmd)
|
||||
self.assertEqual(L.load_approvals(), [])
|
||||
|
||||
def test_the_hook_is_one_for_main_threads_and_workers(self):
|
||||
"""R-16-10 (item 3a): a subagent's shell command goes through the same refusal."""
|
||||
payload = _shell_payload("sisi approve P-0001 --yes", "sess-w")
|
||||
payload["agent_id"] = "worker-1"
|
||||
import contextlib, io
|
||||
from sisi import watch
|
||||
with self.assertRaises(SystemExit) as cm, contextlib.redirect_stderr(io.StringIO()):
|
||||
watch.before(payload)
|
||||
self.assertEqual(cm.exception.code, 2)
|
||||
|
||||
def test_the_hook_process_exits_2_with_the_reason_and_fails_open_on_error(self):
|
||||
"""R-16-9 (item 3a): `sisi watch --before` refuses with exit 2 and says whom to ask; an error in
|
||||
the check lets the command through."""
|
||||
r = self.sisi_proc("watch", "--before", stdin=json.dumps(_shell_payload("sisi approve P-0001 --yes")))
|
||||
self.assertEqual(r.returncode, 2, r.stderr)
|
||||
self.assertIn("owner's alone", r.stderr)
|
||||
self.assertIn("give him the command", r.stderr)
|
||||
import unittest.mock
|
||||
from sisi import watch
|
||||
with unittest.mock.patch.object(watch, "_APPROVE", None):
|
||||
self.assertEqual(self.hook("sisi approve P-0001 --yes"), 0)
|
||||
|
||||
def test_a_decision_needs_the_word_typed_at_the_terminal(self):
|
||||
"""R-14.3-2 (item 3b): the full action and a word are printed to the terminal; the word read
|
||||
back from it decides. A wrong word, no word, or words on standard input decide nothing."""
|
||||
from support import terminal
|
||||
self.park()
|
||||
t = terminal("wrong")
|
||||
with t:
|
||||
r = self.sisi("approve", "P-0001", "--yes", env={"SISI_SESSION_ID": "sess-9"})
|
||||
self.assertEqual(r.returncode, 2)
|
||||
self.assertIn("make deploy --force-everything", t.fake.text) # the full action, on the terminal
|
||||
self.assertIn("Type the word", t.fake.text)
|
||||
self.assertEqual(len(self.pending()), 1)
|
||||
self.assertFalse(self.exists("overlay/enforced.json"))
|
||||
t = terminal(None)
|
||||
with t:
|
||||
self.assertEqual(self.sisi("approve", "P-0001", "--no").returncode, 2)
|
||||
self.assertEqual(len(self.pending()), 1)
|
||||
refused = [r for r in L.load_approvals() if r.get("decision") == "refused"]
|
||||
self.assertEqual(len(refused), 2)
|
||||
self.assertEqual(refused[0]["session"], "sess-9")
|
||||
with terminal():
|
||||
r = self.sisi("approve", "P-0001", "--yes")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertTrue(self.exists("overlay/enforced.json"))
|
||||
|
||||
def test_no_controlling_terminal_means_refused_and_stdin_cannot_stand_in(self):
|
||||
"""R-14.3-2 (item 3b): the word is not read from standard input."""
|
||||
import unittest.mock
|
||||
self.park()
|
||||
with unittest.mock.patch("sisi.cycle._open_terminal", return_value=None):
|
||||
r = self.sisi("approve", "P-0001", "--yes", stdin="pagaso\nyes\n", env={"SISI_SESSION_ID": "s-1"})
|
||||
self.assertEqual(r.returncode, 2)
|
||||
self.assertIn("controlling terminal", r.stderr)
|
||||
self.assertEqual(len(self.pending()), 1)
|
||||
self.assertEqual([x["session"] for x in L.load_approvals()], ["s-1"])
|
||||
# a real process in its own session has no controlling terminal at all
|
||||
p = subprocess.run([sys.executable, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
|
||||
"bin", "sisi"), "approve", "P-0001", "--yes"],
|
||||
cwd=self.proj, input="pagaso\n", capture_output=True, text=True, timeout=60,
|
||||
start_new_session=True, env=dict(os.environ))
|
||||
self.assertEqual(p.returncode, 2, p.stderr)
|
||||
self.assertEqual(len(self.pending()), 1)
|
||||
|
||||
@unittest.skipUnless(os.path.exists("/usr/bin/script") or os.path.exists("/bin/script"), "no script(1)")
|
||||
def test_script_gives_a_terminal_but_not_the_owners_hands(self):
|
||||
"""R-14.3-2 (item 3b): the evidence case, `script -qec "sisi approve ..." /dev/null </dev/null`."""
|
||||
self.park()
|
||||
bin_ = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "bin", "sisi")
|
||||
p = subprocess.run(["script", "-qec", "%s %s approve P-0001 --yes" % (sys.executable, bin_), "/dev/null"],
|
||||
cwd=self.proj, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60,
|
||||
env=dict(os.environ))
|
||||
self.assertEqual(len(self.pending()), 1, p.stdout + p.stderr)
|
||||
self.assertFalse(self.exists("overlay/enforced.json"))
|
||||
|
||||
def test_a_person_at_a_real_terminal_can_decide(self):
|
||||
"""R-14.3-2 (item 3b): through a real pseudo-terminal, typing the word approves."""
|
||||
try:
|
||||
import pty
|
||||
except ImportError:
|
||||
self.skipTest("no pty")
|
||||
self.park()
|
||||
bin_ = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "bin", "sisi")
|
||||
pid, fd = pty.fork()
|
||||
if pid == 0:
|
||||
os.chdir(self.proj)
|
||||
os.execv(sys.executable, [sys.executable, bin_, "approve", "P-0001", "--yes"])
|
||||
out = b""
|
||||
import re, select, time
|
||||
sent, end = False, time.time() + 60
|
||||
while time.time() < end:
|
||||
ready, _w, _x = select.select([fd], [], [], 1)
|
||||
if not ready:
|
||||
continue
|
||||
try:
|
||||
d = os.read(fd, 4096)
|
||||
except OSError:
|
||||
break
|
||||
if not d:
|
||||
break
|
||||
out += d
|
||||
m = re.search(rb"Type the word (\w+) to decide", out)
|
||||
if m and not sent:
|
||||
os.write(fd, m.group(1) + b"\n")
|
||||
sent = True
|
||||
_p, status = os.waitpid(pid, 0)
|
||||
self.assertTrue(sent, out)
|
||||
self.assertEqual(os.waitstatus_to_exitcode(status), 0, out)
|
||||
self.assertTrue(self.exists("overlay/enforced.json"))
|
||||
self.assertEqual(self.pending(), [])
|
||||
|
||||
def test_security_says_plainly_what_this_stops_and_does_not(self):
|
||||
"""R-16-1 (item 3): SECURITY.md names the hook, the typed word, and what neither stops."""
|
||||
with open(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "SECURITY.md")) as f:
|
||||
text = f.read()
|
||||
low = text.lower()
|
||||
for needle in ("typed word", "before-tool hook", "controlling terminal", "does not stop"):
|
||||
self.assertIn(needle, low)
|
||||
@@ -7,7 +7,7 @@ one unit, approves from a non-terminal, adds a row to the store by hand).
|
||||
"""
|
||||
import json, os, stat, subprocess, sys, unittest.mock
|
||||
|
||||
from support import SisiCase
|
||||
from support import SisiCase, terminal
|
||||
from sisi import learning as L
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ class Base(SisiCase):
|
||||
return self.sisi("cycle", "apply", self.cycle_file(actions, **kw))
|
||||
|
||||
def tty(self):
|
||||
return unittest.mock.patch("sisi.cycle._stdin_is_tty", return_value=True)
|
||||
return terminal()
|
||||
|
||||
def other_project(self, name="other"):
|
||||
d = os.path.join(self.tmp, name)
|
||||
@@ -789,7 +789,7 @@ class Approval(Base):
|
||||
self.assertIn("terminal", r.stderr)
|
||||
self.assertEqual(len(self.pending()), 1)
|
||||
self.assertFalse(self.exists("overlay/enforced.json"))
|
||||
self.assertEqual(L.load_approvals(), [])
|
||||
self.assertEqual([a["decision"] for a in L.load_approvals()], ["refused", "refused"]) # attempts are recorded
|
||||
|
||||
def test_a_terminal_decision_is_recorded_with_when_session_and_terminal(self):
|
||||
"""The record keeps when, the session if known, and that standard input was a terminal."""
|
||||
|
||||
@@ -66,7 +66,7 @@ class PersonalCase(SisiCase):
|
||||
r = self.ok(*a, **kw)
|
||||
self.assertTrue(L.load_pending(), "the change should be waiting for the owner")
|
||||
for item in L.load_pending():
|
||||
with unittest.mock.patch("sisi.cycle._stdin_is_tty", return_value=True):
|
||||
with terminal():
|
||||
self.ok("approve", item["id"], "--yes")
|
||||
return r
|
||||
|
||||
|
||||
Reference in new issue
Block a user