diff --git a/.crumb b/.crumb index d19f4dc90..87e7ae083 100644 --- a/.crumb +++ b/.crumb @@ -46,7 +46,7 @@ "children": [ { "digest": "fb7cc6e608fdbe68a9735a1313285782b9717ff12bde17343f8ce635de3644f6", - "last_commit": "80ca5d4", + "last_commit": "190ff89", "name": "calibration", "purpose": "Directory calibration. Purpose not yet described by a human." }, @@ -58,25 +58,25 @@ }, { "digest": "536f7b8db9a92a1f586bad4379d47544a30d1b8e83c2d799c18e66cf8660c9ae", - "last_commit": "80ca5d4", + "last_commit": "30bb116", "name": "doctrine", "purpose": "Directory doctrine. Purpose not yet described by a human." }, { - "digest": "378566048adb168d897e24a62f089c1f95b1d9d11aef3ecfd1f64bbdc58a2089", - "last_commit": "3b53f25", + "digest": "513b9be9b23211265e46271a7c806d63889faaad0b5571746dcdf3bcabf441a5", + "last_commit": "96527a6", "name": "mk", "purpose": "Directory mk. Purpose not yet described by a human." }, { "digest": "69cbb8ef13ccce47ccc21f159e95f1eac58679319e2cc25937065f95c4eb9207", - "last_commit": "80ca5d4", + "last_commit": "ae8c7c5", "name": "polyglot", "purpose": "Directory polyglot. Purpose not yet described by a human." }, { "digest": "8178197a3e956890d6194e5b4fcc0e0b5c4ec67b0749f0d257f2ed17c8ca7465", - "last_commit": "80ca5d4", + "last_commit": "559f6e5", "name": "research", "purpose": "Directory research. Purpose not yet described by a human." }, @@ -87,33 +87,33 @@ "purpose": "Directory spec. Purpose not yet described by a human." }, { - "digest": "db9d74f63064d34f9e3c9c0195b3c6a2e9d599a4b0c4304dfeb8c662d7bc7191", - "last_commit": "d7d05ac", + "digest": "c06c116644765d66e2c7346e99179861cbb7bba7e8e932ff40b6c51983d90d01", + "last_commit": "7adf33e", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "3afb8a86231a7f5421eda8f4b1fa501b283145fa0f46b25c98fc74b298b9cf8c", - "last_commit": "703e09c", + "digest": "4010554a7244d3f0837e6b31a4fc8d17ca0db18038afaa5de90bbec8a08e8496", + "last_commit": "7adf33e", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, { "digest": "8d09b39d6d457128ffa8b3a3e3a8bc16cb619d952dd8db04dc3fc3cda7d38890", - "last_commit": "97d1b9a", + "last_commit": "2ae8677", "name": "tools", "purpose": "Directory tools. Purpose not yet described by a human." } ], - "children_root": "sha256:8cf37dbda3b1c5aa496d1da2f1d3d172691dd9fc95ea8c1932b77e8df4be8902", - "compiled_at": "2026-10-08T13:06:11Z", + "children_root": "sha256:3a827c9c7acb2f9ae983c449a7d7b54c11a5c0d9c90be41ae1626e87b00eb2c1", + "compiled_at": "2026-10-09T04:11:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:6afdffeffc9588037d004a285e0319d44a0cf07eabe0acee7f89d982e6490dbf", + "digest": "sha256:9e4ad68b0c4f21dbceb81d1e820ef8806cff4bc565a827a5141b14ca4203a3bc", "evidence_files": 4818, "evidence_root": "sha256:07642731585ad396c5d9b566a4b8df7807018f494d322dffce41bd04fb51e553", - "files": 6814, - "generated_at_commit": "703e09c0cc8c973c93bc262912eef015ee4fc127", - "source_tree": "sha256:50a9676659b281a33686aacdc19a35e9ad04b981105b35fe726f670c42c4f660" + "files": 6817, + "generated_at_commit": "7adf33efee7b590d919662b54df824f0c2cf2cbf", + "source_tree": "sha256:c7b7ae9064ca15470a710d19a6332eece324b9baa3fd3ebee276bed92ca153e9" }, "owner_lane": "", "provenance": { diff --git a/mk/.crumb b/mk/.crumb index babbc908e..99daa7a6a 100644 --- a/mk/.crumb +++ b/mk/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-08T12:58:13Z", + "compiled_at": "2026-10-09T03:14:06Z", "compiler": "crumb-compile/1", - "digest": "sha256:378566048adb168d897e24a62f089c1f95b1d9d11aef3ecfd1f64bbdc58a2089", + "digest": "sha256:513b9be9b23211265e46271a7c806d63889faaad0b5571746dcdf3bcabf441a5", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 62, - "generated_at_commit": "4cc3bdda4ace926eb2a9a976551dc525279c53b8", - "source_tree": "sha256:c94b1ac157aa5608d1ea10a60cc6ff3526e712bab21797fd86513d341d531a70" + "generated_at_commit": "080fd49f8f7a75ed0a3e5c817737f65ce4631b48", + "source_tree": "sha256:f56c19dc78096e1807daefe7026297de8b532868e2c9e046c6b2dc66c08579cf" }, "owner_lane": "", "provenance": { diff --git a/mk/osh-host.mk b/mk/osh-host.mk index 8618c8943..1c8f88b48 100644 --- a/mk/osh-host.mk +++ b/mk/osh-host.mk @@ -6,9 +6,9 @@ OSH_HOST_MK := 1 .PHONY: test-osh-host OSH_HOST_DIR = $(OUT_DIR)/osh-host OSH_HOST_SRCS = tests/osh/host/test_osh_host.c src/osh/host/osh_req.c src/osh/host/osh_vars.c \ - src/osh/host/osh_builtin.c src/osh/host/osh_exec.c -OSH_HOST_HDRS = src/osh/host/osh_host.h src/osh/host/osh_priv.h -OSH_HOST_FLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -Isrc/osh/host + src/osh/host/osh_builtin.c src/osh/host/osh_exec.c src/osh/host/osh_journal.c src/sha256.c +OSH_HOST_HDRS = src/osh/host/osh_host.h src/osh/host/osh_priv.h src/osh/host/osh_journal.h src/sha256.h +OSH_HOST_FLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -Isrc/osh/host -Isrc OSH_HOST_ASAN = -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all $(OSH_HOST_DIR)/test_osh_host: $(OSH_HOST_SRCS) $(OSH_HOST_HDRS) @@ -29,7 +29,7 @@ test-osh-host: $(OSH_HOST_DIR)/test_osh_host $(OSH_HOST_DIR)/test_osh_host_asan # make test-osh-caps plain and under ASan/UBSan .PHONY: test-osh-caps OSH_CAPS_SRCS = tests/osh/host/test_osh_caps.c src/osh/host/osh_caps.c src/runtime/rx_caproot.c src/osh/host/osh_req.c \ - src/osh/host/osh_vars.c src/osh/host/osh_builtin.c src/osh/host/osh_exec.c + src/osh/host/osh_vars.c src/osh/host/osh_builtin.c src/osh/host/osh_exec.c src/osh/host/osh_journal.c src/sha256.c OSH_CAPS_HDRS = $(OSH_HOST_HDRS) src/osh/host/osh_caps.h src/runtime/rx_caproot.h OSH_CAPS_FLAGS = $(OSH_HOST_FLAGS) -Isrc/runtime -Wno-format-truncation @@ -42,7 +42,29 @@ $(OSH_HOST_DIR)/test_osh_caps_asan: $(OSH_CAPS_SRCS) $(OSH_CAPS_HDRS) $(CC) $(OSH_CAPS_FLAGS) $(OSH_HOST_ASAN) -o $@ $(OSH_CAPS_SRCS) test-osh-caps: $(OSH_HOST_DIR)/test_osh_caps $(OSH_HOST_DIR)/test_osh_caps_asan $(OUT_DIR)/osh/osh - $(abspath $(OSH_HOST_DIR)/test_osh_caps) $(abspath $(OUT_DIR)/osh/osh) > $(OSH_HOST_DIR)/caps.out; rc=$$?; tail -5 $(OSH_HOST_DIR)/caps.out; test $$rc -eq 0 && tail -1 $(OSH_HOST_DIR)/caps.out | grep -q '^OSH_CAPS_PASS$$' - $(abspath $(OSH_HOST_DIR)/test_osh_caps_asan) $(abspath $(OUT_DIR)/osh/osh) > $(OSH_HOST_DIR)/caps_asan.out; rc=$$?; tail -3 $(OSH_HOST_DIR)/caps_asan.out; test $$rc -eq 0 && tail -1 $(OSH_HOST_DIR)/caps_asan.out | grep -q '^OSH_CAPS_PASS$$' + rm -rf $(abspath $(OSH_HOST_DIR))/state; XDG_STATE_HOME=$(abspath $(OSH_HOST_DIR))/state $(abspath $(OSH_HOST_DIR)/test_osh_caps) $(abspath $(OUT_DIR)/osh/osh) > $(OSH_HOST_DIR)/caps.out; rc=$$?; tail -5 $(OSH_HOST_DIR)/caps.out; test $$rc -eq 0 && tail -1 $(OSH_HOST_DIR)/caps.out | grep -q '^OSH_CAPS_PASS$$' + rm -rf $(abspath $(OSH_HOST_DIR))/state; XDG_STATE_HOME=$(abspath $(OSH_HOST_DIR))/state $(abspath $(OSH_HOST_DIR)/test_osh_caps_asan) $(abspath $(OUT_DIR)/osh/osh) > $(OSH_HOST_DIR)/caps_asan.out; rc=$$?; tail -3 $(OSH_HOST_DIR)/caps_asan.out; test $$rc -eq 0 && tail -1 $(OSH_HOST_DIR)/caps_asan.out | grep -q '^OSH_CAPS_PASS$$' @echo "test-osh-caps: PASS (capability enforcement; plain and ASan/UBSan)" +# durable intent/outcome journal (ABI section 10): intent before each effect, outcome after, recovery never replays. +# make test-osh-journal plain and under ASan/UBSan +.PHONY: test-osh-journal +OSH_JOURNAL_SRCS = tests/osh/host/test_osh_journal.c src/osh/host/osh_req.c src/osh/host/osh_vars.c src/osh/host/osh_builtin.c \ + src/osh/host/osh_exec.c src/osh/host/osh_journal.c src/sha256.c + +$(OSH_HOST_DIR)/test_osh_journal: $(OSH_JOURNAL_SRCS) $(OSH_HOST_HDRS) + @mkdir -p $(OSH_HOST_DIR) + $(CC) $(OSH_HOST_FLAGS) -DOSH_JOURNAL_TEST_HOOKS -O2 -o $@ $(OSH_JOURNAL_SRCS) + +$(OSH_HOST_DIR)/test_osh_journal_asan: $(OSH_JOURNAL_SRCS) $(OSH_HOST_HDRS) + @mkdir -p $(OSH_HOST_DIR) + $(CC) $(OSH_HOST_FLAGS) -DOSH_JOURNAL_TEST_HOOKS $(OSH_HOST_ASAN) -o $@ $(OSH_JOURNAL_SRCS) + +test-osh-journal: $(OSH_HOST_DIR)/test_osh_journal $(OSH_HOST_DIR)/test_osh_journal_asan $(OUT_DIR)/osh/osh + @nm $(OUT_DIR)/osh/osh | grep -q osh_journal_intent || { echo "FAIL: shipped osh is stripped, cannot check"; exit 1; } + @if nm $(OUT_DIR)/osh/osh | grep -q osh_journal_test_hooks_compiled; then echo "FAIL: shipped osh contains the journal test hooks"; exit 1; fi + @nm $(abspath $(OSH_HOST_DIR)/test_osh_journal) | grep -q osh_journal_test_hooks_compiled || { echo "FAIL: test build lacks the hooks"; exit 1; } + @echo "test hooks: absent from the shipped osh, present in the test build" + $(abspath $(OSH_HOST_DIR)/test_osh_journal) $(abspath $(OUT_DIR)/osh/osh) > $(OSH_HOST_DIR)/journal.out; rc=$$?; tail -5 $(OSH_HOST_DIR)/journal.out; test $$rc -eq 0 && tail -1 $(OSH_HOST_DIR)/journal.out | grep -q '^OSH_JOURNAL_PASS$$' + $(abspath $(OSH_HOST_DIR)/test_osh_journal_asan) $(abspath $(OUT_DIR)/osh/osh) > $(OSH_HOST_DIR)/journal_asan.out; rc=$$?; tail -3 $(OSH_HOST_DIR)/journal_asan.out; test $$rc -eq 0 && tail -1 $(OSH_HOST_DIR)/journal_asan.out | grep -q '^OSH_JOURNAL_PASS$$' + @echo "test-osh-journal: PASS (durable intent/outcome journal; plain and ASan/UBSan)" endif diff --git a/mk/osh.mk b/mk/osh.mk index 6a6a2fb59..ab6f6697e 100644 --- a/mk/osh.mk +++ b/mk/osh.mk @@ -112,7 +112,7 @@ $(OSH_DIR)/test_osh_e2e: tests/osh/e2e/test_osh_e2e.c $(CC) -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 -o $@ $< test-osh-e2e: osh-gen-check $(OSH_DIR)/osh $(OSH_DIR)/argprint $(OSH_DIR)/test_osh_e2e - $(abspath $(OSH_DIR)/test_osh_e2e) $(abspath $(OSH_DIR)/osh) $(abspath $(OSH_DIR)/argprint) > $(OSH_DIR)/e2e.out + rm -rf $(abspath $(OSH_DIR))/state; XDG_STATE_HOME=$(abspath $(OSH_DIR))/state $(abspath $(OSH_DIR)/test_osh_e2e) $(abspath $(OSH_DIR)/osh) $(abspath $(OSH_DIR)/argprint) > $(OSH_DIR)/e2e.out @tail -3 $(OSH_DIR)/e2e.out; tail -1 $(OSH_DIR)/e2e.out | grep -q '^OSH_E2E_PASS$$' @echo "test-osh-e2e: PASS" diff --git a/src/.crumb b/src/.crumb index 6c814a058..2ed87b64d 100644 --- a/src/.crumb +++ b/src/.crumb @@ -80,7 +80,7 @@ }, { "digest": "18e933f213d7958215bb0ecf09116e5c21d3b335cfdabc1ffbf7a2a4e98b5250", - "last_commit": "eb8dedf", + "last_commit": "f7b4389", "name": "compiler", "purpose": "Directory src/compiler. Purpose not yet described by a human." }, @@ -115,8 +115,8 @@ "purpose": "Directory src/language. Purpose not yet described by a human." }, { - "digest": "e8f706b54de6ee42d3f96b1fc7ab5e94fe8cc132928e213604fe8b247db9fcad", - "last_commit": "6211ebf", + "digest": "bac52a0d2c450354c2862c720e19363d5eb7bed4b5b47615c7ca734a729e1ab7", + "last_commit": "7adf33e", "name": "osh", "purpose": "osh (Omega-native shell, arch#158) lexer unit: layout list, generator, osh_lex.osc, C reference " }, @@ -175,15 +175,15 @@ "purpose": "Directory src/visor. Purpose not yet described by a human." } ], - "children_root": "sha256:412f19f9f99b190238677ac44ed7112cb7028d8aae98bc10d2f03e4243cb1903", - "compiled_at": "2026-10-08T12:46:55Z", + "children_root": "sha256:1fe047c4933784ac25ab5bd834b9677180143f30a22f91432c009878d5a00b97", + "compiled_at": "2026-10-09T04:11:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:db9d74f63064d34f9e3c9c0195b3c6a2e9d599a4b0c4304dfeb8c662d7bc7191", + "digest": "sha256:c06c116644765d66e2c7346e99179861cbb7bba7e8e932ff40b6c51983d90d01", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 443, - "generated_at_commit": "6211ebf08d0d51eafe24d6962fdd22d643612347", - "source_tree": "sha256:419e9b3f62ed45c271d89920b6e1eb934efa1bf58ddeeaa6133e20d20cab3bfc" + "files": 445, + "generated_at_commit": "7adf33efee7b590d919662b54df824f0c2cf2cbf", + "source_tree": "sha256:53cb7c5b9b55f98a01b5efadbc049231a9fbd485731c0d91b84516b3d594e23f" }, "owner_lane": "", "provenance": { diff --git a/src/osh/.crumb b/src/osh/.crumb index 3d88f0a7b..19415bcbd 100644 --- a/src/osh/.crumb +++ b/src/osh/.crumb @@ -3,21 +3,21 @@ "generated": { "children": [ { - "digest": "adf85d2d49ef3b7df08d58db4585a9c16e2c185fb04b3b7615349eb8a31f4a91", - "last_commit": "6211ebf", + "digest": "6e571ea9d38be544ba34197741022963e7d58b3f264b2992d4a3f266de6a22b6", + "last_commit": "7adf33e", "name": "host", "purpose": "osh Linux host: execution service (request decoder, resolution, builtins, redirections, pipeline" } ], - "children_root": "sha256:07aa040bee75e295849806e68f6fa3dac2bbd9c57272d07c0e85f6a4058e852b", - "compiled_at": "2026-10-08T12:46:55Z", + "children_root": "sha256:f78fa9adb0402a9c251fe3b206c56b23fd698011a51a72cc408479bf20225b66", + "compiled_at": "2026-10-09T04:11:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:e8f706b54de6ee42d3f96b1fc7ab5e94fe8cc132928e213604fe8b247db9fcad", + "digest": "sha256:bac52a0d2c450354c2862c720e19363d5eb7bed4b5b47615c7ca734a729e1ab7", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 29, - "generated_at_commit": "6211ebf08d0d51eafe24d6962fdd22d643612347", - "source_tree": "sha256:39cde33d4f7e01045875486e4fb02a244b0876859f148eaa3846a3b6c12f4ca9" + "files": 31, + "generated_at_commit": "7adf33efee7b590d919662b54df824f0c2cf2cbf", + "source_tree": "sha256:ad3d00f50624469724e62cc25e76cea9ad20f6eb4027caeace07aa21fcf5fcaf" } }, "name": "osh", diff --git a/src/osh/host/.crumb b/src/osh/host/.crumb index 689ce51ee..82984707b 100644 --- a/src/osh/host/.crumb +++ b/src/osh/host/.crumb @@ -3,14 +3,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-08T12:46:55Z", + "compiled_at": "2026-10-09T04:11:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:adf85d2d49ef3b7df08d58db4585a9c16e2c185fb04b3b7615349eb8a31f4a91", + "digest": "sha256:6e571ea9d38be544ba34197741022963e7d58b3f264b2992d4a3f266de6a22b6", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 14, - "generated_at_commit": "6211ebf08d0d51eafe24d6962fdd22d643612347", - "source_tree": "sha256:5938f4d9d775ab4c4778996b20eea6a05d99bf4e4baf349d0a6ba175732b44dd" + "files": 16, + "generated_at_commit": "7adf33efee7b590d919662b54df824f0c2cf2cbf", + "source_tree": "sha256:ece8557c3e1d5ea71058159fc79f7148e4862e2cd710c12f952f60a3e10d84ca" } }, "name": "host", diff --git a/src/osh/host/osh_exec.c b/src/osh/host/osh_exec.c index 3b60564b3..c89690196 100644 --- a/src/osh/host/osh_exec.c +++ b/src/osh/host/osh_exec.c @@ -43,13 +43,28 @@ * when interactive, else to each pid) and are reaped (outcome CANCELLED); not-yet-started commands are NOT_STARTED; status 1. * - waitpid ECHILD for a started child (someone else reaped it): that command is OUTCOME_UNKNOWN, status 1, err * OUTCOME_UNKNOWN. A pipeline whose last command died of SIGINT/SIGQUIT sets killed_by_int and osh_run_list stops there. - * - No durable intent/outcome record (ABI section 10) is written: outcomes live in the result only. NOT DONE. + * - DURABLE INTENT/OUTCOME (ABI section 10), when s->journal is set (osh_journal.h; the osh program always sets it). + * An effect is one external spawn or one write-class open (output/append redirection), so a command is an effect + * iff it is external or has such a redirection; builtins, standalone assignments and read-only/dup redirections + * are not (section 10 defines the term that way). Just before each effect an INTENT record is appended and fsynced + * (file; directory on creation); if that fails the command is NOT launched (FAILED_NO_EFFECT, err IO, status 1: + * mandatory records fail closed). After the pipeline is reaped one OUTCOME record per effect is appended and fsynced: + * a refusal or denial before the intent is an outcome with no intent (ref 0, FAILED_NO_EFFECT, nothing launched), a + * command never reached is NOT_STARTED. ONE ACCOUNT: the record and the result give the same outcome + * for every command. A command that died of a signal it was sent (^C, kill) is COMPLETED with status 128+sig + * (ABI 8.4 exit status convention); CANCELLED is the adapter's own act (stopped member, partial-launch cleanup). If an + * outcome cannot be made durable the intent stays open (recovery reports it UNKNOWN) and res->journal_failed is set. + * Recovery never launches anything. The journal holds no argument values (osh_journal.h, redaction rule). Without + * s->journal and without s->journal_required nothing is written and behaviour is unchanged (library embedders). With + * journal_required set and no journal open (the osh program when the journal cannot be opened) every effect is refused with + * a named diagnostic (status 1, FAILED_NO_EFFECT, err IO); commands that are not effects still run. */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include "osh_host.h" #include "osh_priv.h" +#include "osh_journal.h" #include #include @@ -336,13 +351,89 @@ static void fail_all(OshResult *res, int n, int status, int err) res->err = err; } +/* ---------------- durable intent/outcome (ABI section 10) ---------------- */ + +typedef struct { + OshJournal *j; + int required; /* mandatory journal: no journal means every effect is refused */ + const char *why; + uint8_t dig[32]; + uint64_t ref[OSH_MAX_CMDS]; /* intent rec per command, 0 = none */ +} JCtx; + +/* an effect per ABI section 10: one external spawn or one write-class open */ +static int cmd_effect(const OshCmd *c) +{ + if (c->nargv > 0 && c->builtin_id == OSH_B_NONE) return 1; + for (int k = 0; k < c->nredir; k++) + if (c->redir[k].kind == OSH_R_OUT || c->redir[k].kind == OSH_R_APPEND) return 1; + return 0; +} + +static void jc_init(JCtx *jc, OshSession *s, const OshRequest *r) +{ + memset(jc, 0, sizeof *jc); + jc->j = s->journal; + jc->required = s->journal_required && !s->journal; + jc->why = s->journal_error ? s->journal_error : "not opened"; + if (jc->j) osh_req_digest(jc->j, r, jc->dig); +} + +/* 0: durable (or no journal / not an effect); -1: the intent could not be made durable and the effect must not run */ +static int jc_intent(JCtx *jc, const OshRequest *r, int idx) +{ + if (jc->required && cmd_effect(&r->cmd[idx])) return -2; + if (!jc->j || !cmd_effect(&r->cmd[idx])) return 0; + jc->ref[idx] = osh_journal_intent(jc->j, jc->dig, r, idx); + return jc->ref[idx] ? 0 : -1; +} + +/* the named refusal: -2 = the journal is not open at all, -1 = the intent record was not durable */ +static void jc_refuse(OshSession *s, const JCtx *jc, int rc) +{ + if (rc == -2) osh_diag(s->fd[2], "effect journal unavailable (%s); effect refused, nothing was run", jc->why); + else if (jc->j && jc->j->poisoned) osh_diag(s->fd[2], "effect journal failed (a write or fsync did not succeed) and is closed for this session; effect refused, nothing was run"); + else osh_diag(s->fd[2], "effect journal: intent could not be made durable; effect refused, nothing was run"); +} + +static int jc_outcome(const OshCmdResult *c) { return c->outcome; } /* one account: the record says exactly what the result says */ + +/* one outcome per effect, one write, one fsync */ +static void jc_finish(JCtx *jc, const OshRequest *r, OshResult *res) +{ + if (!jc->j) return; + OshJournalOutcome o[OSH_MAX_CMDS]; + int n = 0; + for (int i = 0; i < r->ncmds; i++) { + if (!cmd_effect(&r->cmd[i])) continue; + o[n].idx = i; + o[n].ref = jc->ref[i]; + o[n].outcome = jc_outcome(&res->cmd[i]); + o[n].status = res->cmd[i].status; + o[n].err = res->cmd[i].err; + n++; + } + if (osh_journal_outcomes(jc->j, jc->dig, r->ncmds, o, n) != 0) { + res->journal_failed = 1; + osh_diag(2, "journal: an outcome could not be made durable; recovery will report it UNKNOWN"); + } +} + /* single parent-side command: builtin, or standalone assignment / redirection-only */ -static void run_in_parent(OshSession *s, const OshCmd *c, OshResult *res) +static void run_in_parent(OshSession *s, const OshRequest *rq, JCtx *jc, OshResult *res) { + const OshCmd *c = &rq->cmd[0]; FdTab t; tab_init(&t, s); int st; int rerr = OSH_E_IO; + int jrc = jc_intent(jc, rq, 0); + if (jrc != 0) { + jc_refuse(s, jc, jrc); + set_cmd(&res->cmd[0], 1, OSH_OUT_FAILED_NO_EFFECT, OSH_E_IO); + res->status = 1; + return; + } if (apply_redirs(s, &t, c, s->fd[2], &rerr) != 0) { st = 1; set_cmd(&res->cmd[0], st, OSH_OUT_FAILED_NO_EFFECT, rerr); @@ -456,7 +547,7 @@ static int wait_all(OshSession *s, OshResult *res, Child *ch, int n, pid_t pgid, return first_stop; } -static void run_pipeline(OshSession *s, const OshRequest *r, OshResult *res) +static void run_pipeline(OshSession *s, const OshRequest *r, JCtx *jc, OshResult *res) { int n = r->ncmds; Pipes p; @@ -524,6 +615,17 @@ static void run_pipeline(OshSession *s, const OshRequest *r, OshResult *res) if (!envp) { launch_failed = 1; set_cmd(&res->cmd[i], 1, OSH_OUT_NOT_STARTED, OSH_E_LIMIT); break; } } + int jrc = jc_intent(jc, r, i); + if (jrc != 0) { /* mandatory record not durable: fail closed, launch nothing */ + jc_refuse(s, jc, jrc); + osh_envp_free(envp); + set_cmd(&res->cmd[i], 1, OSH_OUT_FAILED_NO_EFFECT, OSH_E_IO); + if (rd >= 0) { close(rd); p.pp[i - 1][0] = -1; } + if (wr >= 0) { close(wr); p.pp[i][1] = -1; } + if (started > 0) { launch_failed = 1; break; } /* earlier members already run: cancel and reap them (PARTIAL_LAUNCH, ABI s10) */ + continue; + } + pid_t pid; /* SIGINT/SIGQUIT stay blocked across fork: a signal that lands before the child has reset its handlers would * otherwise run the shell's handler inside the child. They are delivered once the child's signals are default. */ @@ -542,6 +644,8 @@ static void run_pipeline(OshSession *s, const OshRequest *r, OshResult *res) } if (pid == 0) { /* ---- child ---- */ + /* a forked builtin never execs, so the O_CLOEXEC journal descriptor (and its flock) would outlive the shell: close it now */ + if (s->journal && s->journal->fd >= 0) close(s->journal->fd); if (own_pg) setpgid(0, pgid); /* pgid 0 on the first one: become a leader */ if (tty && pgid == 0) tcsetpgrp(s->tty_fd, getpid()); /* SIGTTOU is still ignored here */ child_signals(); @@ -617,10 +721,13 @@ int osh_exec(OshSession *s, const OshRequest *r, OshResult *res) { memset(res, 0, sizeof *res); res->ncmds = r->ncmds; + JCtx jc; + jc_init(&jc, s, r); int a = authorize(s, r); if (a != OSH_E_OK) { osh_diag(s->fd[2], "%s: not permitted (platform error %d); nothing was run", r->cmd[0].nargv ? r->cmd[0].argv[0] : "request", a); fail_all(res, r->ncmds, 126, a); + jc_finish(&jc, r, res); s->last_status = res->status; return res->status; } @@ -631,14 +738,16 @@ int osh_exec(OshSession *s, const OshRequest *r, OshResult *res) if (cls != OSH_CLASS_LINUX) { osh_diag(s->fd[2], "%s: destination class %d is not a Linux executable and is unavailable on this host; refused", c->argv[0], cls); fail_all(res, r->ncmds, 126, OSH_E_UNAVAILABLE); + jc_finish(&jc, r, res); s->last_status = res->status; return res->status; } } SigGuard g; guard_enter(&g, s->interactive); - if (r->ncmds == 1 && (r->cmd[0].builtin_id != OSH_B_NONE || r->cmd[0].nargv == 0)) run_in_parent(s, &r->cmd[0], res); - else run_pipeline(s, r, res); + if (r->ncmds == 1 && (r->cmd[0].builtin_id != OSH_B_NONE || r->cmd[0].nargv == 0)) run_in_parent(s, r, &jc, res); + else run_pipeline(s, r, &jc, res); + jc_finish(&jc, r, res); res->sigint_seen = g_sig_seen == SIGINT; const OshCmdResult *last = &res->cmd[r->ncmds - 1]; res->killed_by_int = last->termsig == SIGINT || last->termsig == SIGQUIT; diff --git a/src/osh/host/osh_host.h b/src/osh/host/osh_host.h index 5b541b4c8..4dcffc2eb 100644 --- a/src/osh/host/osh_host.h +++ b/src/osh/host/osh_host.h @@ -142,6 +142,9 @@ typedef struct OshSession { void *effect_ctx; int exit_requested, exit_status; /* set by the parent `exit` builtin */ int abort_list; /* set by the parent `exit` with too many arguments: bash drops the rest of the list */ + struct OshJournal *journal; /* durable intent/outcome journal (osh_journal.h, ABI section 10); NULL = none */ + int journal_required; /* the effect journal is mandatory (ABI section 10): with journal NULL every effect is refused */ + const char *journal_error; /* why the mandatory journal is unavailable (named in the refusal) */ /* test-only fault injection; all zero in production */ int fail_fork_at; /* 1-based index of the command whose fork() is made to fail */ void (*after_launch_hook)(void *); /* called after the last command is started, before waiting */ @@ -178,6 +181,7 @@ typedef struct { int killed_by_int; /* the last command died of SIGINT or SIGQUIT: list execution must stop */ int exit_requested; /* mirrors session: parent `exit` ran */ int refusal; /* decoder refusal code if the request was refused before any effect, else 0 */ + int journal_failed; /* an outcome record could not be made durable (the intent stays; recovery reports UNKNOWN) */ } OshResult; /* Execute one decoded request (one pipeline). Returns the pipeline status. */ diff --git a/src/osh/host/osh_journal.c b/src/osh/host/osh_journal.c new file mode 100644 index 000000000..bb9fdedef --- /dev/null +++ b/src/osh/host/osh_journal.c @@ -0,0 +1,626 @@ +/* + * osh_journal.c -- durable effect journal (OSH_PLATFORM_ABI.md section 10). Format and rules: osh_journal.h. + * Plain POSIX: open(O_APPEND), one write() per batch, fsync(file), fsync(directory) when the file is created. + */ +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#include "osh_journal.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "sha256.h" + +static const char *const k_outcome[] = {"NOT_STARTED", "COMPLETED", "FAILED_NO_EFFECT", "CANCELLED", "OUTCOME_UNKNOWN"}; + +/* ---- redaction ---- */ + +/* The ABI draft names "a secret list" (section 13) but does not define it. ASSUMPTION: a variable NAME is secret when, + * compared case-insensitively, it contains any of these fragments. False positives only blank a value inside a digest. */ +int osh_secret_name(const char *name) +{ + static const char *const frag[] = {"PASSWORD", "PASSWD", "PASSPHRASE", "SECRET", "TOKEN", "CREDENTIAL", "APIKEY", + "API_KEY", "PRIVATE", "AUTH", "COOKIE", "KEY", "SESSION", "SIGNATURE"}; + size_t n = strlen(name); + for (size_t f = 0; f < sizeof frag / sizeof frag[0]; f++) { + size_t fl = strlen(frag[f]); + for (size_t i = 0; i + fl <= n; i++) { + size_t k = 0; + while (k < fl && toupper((unsigned char)name[i + k]) == frag[f][k]) k++; + if (k == fl) return 1; + } + } + return 0; +} + +/* ---- request digest ---- */ + +static void h_u64(sha256_ctx *h, uint64_t v) +{ + uint8_t b[8]; + for (int i = 0; i < 8; i++) b[i] = (uint8_t)(v >> (8 * i)); + sha256_update(h, b, 8); +} + +static void h_str(sha256_ctx *h, const char *s) +{ + size_t n = s ? strlen(s) : 0; + h_u64(h, n); + if (n) sha256_update(h, (const uint8_t *)s, n); +} + +/* Canonical encoding: domain tag, ncmds, connector, flags, then per command the builtin id, argv, assignments + * (name, value; a secret name's value is replaced by the marker "\x01REDACTED"), redirections. Lengths are prefixed. */ +static void canon(sha256_ctx *hp, const OshRequest *r) +{ + sha256_ctx h = *hp; + h_str(&h, "OSHREQ1"); + h_u64(&h, (uint64_t)r->ncmds); + h_u64(&h, (uint64_t)r->connector_after); + h_u64(&h, r->flags); + for (int i = 0; i < r->ncmds; i++) { + const OshCmd *c = &r->cmd[i]; + h_u64(&h, (uint64_t)c->builtin_id); + h_u64(&h, (uint64_t)c->nargv); + for (int k = 0; k < c->nargv; k++) h_str(&h, c->argv[k]); + h_u64(&h, (uint64_t)c->nassign); + for (int k = 0; k < c->nassign; k++) { + h_str(&h, c->assign[k].name); + h_str(&h, osh_secret_name(c->assign[k].name) ? "\x01REDACTED" : c->assign[k].value); + } + h_u64(&h, (uint64_t)c->nredir); + for (int k = 0; k < c->nredir; k++) { + h_u64(&h, (uint64_t)c->redir[k].kind); + h_u64(&h, (uint64_t)c->redir[k].fd); + h_u64(&h, (uint64_t)c->redir[k].src_fd); + h_str(&h, c->redir[k].path); + } + } + *hp = h; +} + +void osh_req_digest_unkeyed(const OshRequest *r, uint8_t out[32]) +{ + sha256_ctx h; + sha256_init(&h); + canon(&h, r); + sha256_final(&h, out); +} + +/* HMAC-SHA256 (RFC 2104) over omega's src/sha256.c, key 32 bytes. (src/fabric/fab_hmac.c is a test-only stand-in that refuses to + * build in a production program, so it is not used.) */ +static void hmac_begin(sha256_ctx *h, const uint8_t key[32]) +{ + uint8_t pad[64]; + memset(pad, 0x36, sizeof pad); + for (int i = 0; i < 32; i++) pad[i] ^= key[i]; + sha256_init(h); + sha256_update(h, pad, sizeof pad); +} + +static void hmac_end(sha256_ctx *h, const uint8_t key[32], uint8_t out[32]) +{ + uint8_t pad[64], inner[32]; + sha256_final(h, inner); + memset(pad, 0x5c, sizeof pad); + for (int i = 0; i < 32; i++) pad[i] ^= key[i]; + sha256_init(h); + sha256_update(h, pad, sizeof pad); + sha256_update(h, inner, sizeof inner); + sha256_final(h, out); +} + +void osh_req_digest(const OshJournal *j, const OshRequest *r, uint8_t out[32]) +{ + sha256_ctx h; + hmac_begin(&h, j->key); + canon(&h, r); + hmac_end(&h, j->key, out); +} + +#ifdef OSH_JOURNAL_TEST_HOOKS +/* the same HMAC, over a byte string, so the test can check RFC 4231 vectors (key given zero-extended to 32 bytes, which HMAC treats as the shorter key) */ +void osh_hmac_for_test(const uint8_t key[32], const uint8_t *msg, size_t n, uint8_t out[32]) +{ + sha256_ctx h; + hmac_begin(&h, key); + sha256_update(&h, msg, n); + hmac_end(&h, key, out); +} +#endif + +static void hex(const uint8_t d[32], char out[65]) +{ + static const char x[] = "0123456789abcdef"; + for (int i = 0; i < 32; i++) { + out[2 * i] = x[d[i] >> 4]; + out[2 * i + 1] = x[d[i] & 15]; + } + out[64] = 0; +} + +/* ---- low-level io ---- */ + +static int write_all(int fd, const char *p, size_t n) +{ + while (n) { + ssize_t w = write(fd, p, n); + if (w < 0) { + if (errno == EINTR) continue; + return -1; + } + p += w; + n -= (size_t)w; + } + return 0; +} + +static int sync_fd(int fd) +{ + for (;;) { + if (fsync(fd) == 0) return 0; + if (errno != EINTR) return -1; + } +} + +static int fsync_parent(const char *path) +{ + char d[4096]; + if (strlen(path) >= sizeof d) return -ENAMETOOLONG; + strcpy(d, path); + char *sl = strrchr(d, '/'); + if (!sl) strcpy(d, "."); + else if (sl == d) d[1] = 0; + else *sl = 0; + int fd = open(d, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (fd < 0) return -errno; + int rc = sync_fd(fd) == 0 ? 0 : -errno; + close(fd); + return rc; +} + +/* the journal's own fsync; the test build can make one fail (the tests also count real fsync(2) calls) */ +static int jsync(OshJournal *j) +{ +#ifdef OSH_JOURNAL_TEST_HOOKS + if (j->fail_fsync_at && j->n_commit == j->fail_fsync_at) { errno = EIO; return -1; } +#endif + return sync_fd(j->fd); +} + +/* Append one batch and make it durable. STICKY: the first failed write or fsync poisons the journal for the rest of the + * session, and after that no new intent is written (every later effect is refused instead). Reason: a short write can + * leave a fragment with no newline, and a record appended after it would be glued onto it and be unreadable, so an effect + * could run with no readable intent. On a failed write the fragment is cut back to the previous end (tail_clean); only + * then may an OUTCOME for an effect that already started still be appended (is_outcome), because it cannot be glued. After + * a failed fsync the tail is unknown and nothing more is written. Reopening also closes a torn tail with a newline. */ +static int commit(OshJournal *j, const char *buf, size_t n, int is_outcome) +{ + if (j->fd < 0) return -1; + if (j->poisoned && !(is_outcome && j->tail_clean)) { errno = EIO; return -1; } + off_t pre = lseek(j->fd, 0, SEEK_END); + int rc = 0, e = 0, wrote_failed = 0; +#ifdef OSH_JOURNAL_TEST_HOOKS + j->n_commit++; + if (j->fail_write_at && j->n_commit == j->fail_write_at) { + if (n > 1) (void)write_all(j->fd, buf, n / 2); + rc = -1; + e = ENOSPC; + wrote_failed = 1; + } +#endif + if (!rc && write_all(j->fd, buf, n) != 0) { rc = -1; e = errno; wrote_failed = 1; } + if (wrote_failed) { + j->tail_clean = pre >= 0 && ftruncate(j->fd, pre) == 0; + } else if (!rc && jsync(j) != 0) { + rc = -1; + e = errno; + j->tail_clean = 0; + } + if (rc) { + j->poisoned = 1; + errno = e ? e : EIO; + return -1; + } + return 0; +} + +/* ---- parsing (shared by open and recover) ---- */ + +typedef struct { + int kind; /* 'I', 'O', 0 = unparsable */ + uint64_t rec, ref; + char digest[65]; + int idx, ncmds; + char a0[200]; +} Line; + +static void parse_line(char *s, Line *o) +{ + memset(o, 0, sizeof *o); + char *sv = NULL, *tok = strtok_r(s, " ", &sv); + if (!tok || strcmp(tok, "OSHJ1")) return; + if (!(tok = strtok_r(NULL, " ", &sv))) return; + o->rec = strtoull(tok, NULL, 10); + if (!(tok = strtok_r(NULL, " ", &sv)) || (tok[0] != 'I' && tok[0] != 'O') || tok[1]) return; + char kind = tok[0]; + if (kind == 'O') { + if (!(tok = strtok_r(NULL, " ", &sv))) return; + o->ref = strtoull(tok, NULL, 10); + } + if (!(tok = strtok_r(NULL, " ", &sv)) || strlen(tok) != 64) return; + memcpy(o->digest, tok, 65); + if (!(tok = strtok_r(NULL, " ", &sv)) || sscanf(tok, "%d/%d", &o->idx, &o->ncmds) != 2) return; + if (kind == 'I') { + for (int k = 0; k < 3; k++) /* b= argc= wr= */ + if (!strtok_r(NULL, " ", &sv)) return; + if (!(tok = strtok_r(NULL, " ", &sv)) || strncmp(tok, "a0=", 3)) return; + snprintf(o->a0, sizeof o->a0, "%s", tok + 3); + } + o->kind = kind; +} + +/* Visit every line of the file. cb returns nothing; torn/garbled lines are counted in *bad. */ +static int scan(const char *path, void (*cb)(void *, const Line *), void *ctx, int *bad, int *ends_nl) +{ + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return -errno; + size_t cap = 1 << 16, len = 0; + char *buf = malloc(cap); + if (!buf) { close(fd); return -ENOMEM; } + for (;;) { + if (len == cap) { + char *nb = realloc(buf, cap * 2); + if (!nb) { free(buf); close(fd); return -ENOMEM; } + buf = nb; + cap *= 2; + } + ssize_t n = read(fd, buf + len, cap - len); + if (n < 0 && errno == EINTR) continue; + if (n < 0) { int e = errno; free(buf); close(fd); return -e; } + if (n == 0) break; + len += (size_t)n; + } + close(fd); + if (ends_nl) *ends_nl = len == 0 || buf[len - 1] == '\n'; + size_t i = 0; + while (i < len) { + size_t e = i; + while (e < len && buf[e] != '\n') e++; + int terminated = e < len; + char *line = malloc(e - i + 1); + if (!line) { free(buf); return -ENOMEM; } + memcpy(line, buf + i, e - i); + line[e - i] = 0; + Line l; + parse_line(line, &l); + if (!terminated || !l.kind || l.rec == 0) { if (bad && (e > i)) (*bad)++; } + else cb(ctx, &l); + free(line); + i = e + 1; + } + free(buf); + return 0; +} + +static void max_cb(void *ctx, const Line *l) { uint64_t *m = ctx; if (l->rec > *m) *m = l->rec; } + +static int jfail(OshJournal *j, int e, const char *fmt, const char *a, unsigned m) +{ + snprintf(j->why, sizeof j->why, fmt, a, m); + return -e; +} + +static int random_bytes(uint8_t *b, size_t n) +{ + size_t got = 0; + while (got < n) { + ssize_t r = getrandom(b + got, n - got, 0); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) break; + got += (size_t)r; + } + if (got == n) return 0; + int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC); + if (fd < 0) return -1; + while (got < n) { + ssize_t r = read(fd, b + got, n - got); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) { close(fd); return -1; } + got += (size_t)r; + } + close(fd); + return 0; +} + +/* The per-journal HMAC key lives beside the journal as .key (32 random bytes, 0600, owned by the caller). + * Created atomically (temporary file with O_EXCL, fsync, link(2) which never overwrites, fsync of the directory) and + * reused when present. FAIL CLOSED: an existing key with another owner, a mode other than 0600, a size other than 32 or + * that cannot be read refuses the journal; so does a missing key beside a journal that already holds records (a new + * key would silently make every earlier digest meaningless). */ +static int load_key(OshJournal *j, const char *path, int have_records) +{ + char kp[4200]; + if (snprintf(kp, sizeof kp, "%s.key", path) >= (int)sizeof kp) return jfail(j, ENAMETOOLONG, "journal path too long%s", "", 0); + int fd = open(kp, O_RDONLY | O_NOFOLLOW | O_CLOEXEC); + if (fd < 0 && errno == ENOENT) { + if (have_records) return jfail(j, ENOENT, "key file %s is missing but the journal already has records; refusing to start a new key", kp, 0); + char tmp[4300]; + snprintf(tmp, sizeof tmp, "%s.tmp.%ld", kp, (long)getpid()); + int tfd = open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600); + if (tfd < 0) return jfail(j, errno, "cannot create key file %s", kp, 0); + uint8_t k[32]; + int ok = random_bytes(k, sizeof k) == 0 && write_all(tfd, (const char *)k, sizeof k) == 0 && sync_fd(tfd) == 0; + int e = ok ? 0 : (errno ? errno : EIO); + close(tfd); + memset(k, 0, sizeof k); + if (ok && link(tmp, kp) != 0 && errno != EEXIST) { ok = 0; e = errno; } + unlink(tmp); + if (!ok) return jfail(j, e, "cannot create key file %s", kp, 0); + int dr = fsync_parent(kp); + if (dr) return jfail(j, -dr, "cannot sync the directory of key file %s", kp, 0); + fd = open(kp, O_RDONLY | O_NOFOLLOW | O_CLOEXEC); + } + if (fd < 0) return jfail(j, errno, "cannot open key file %s", kp, 0); + struct stat st; + if (fstat(fd, &st) != 0) { int e = errno; close(fd); return jfail(j, e, "cannot stat key file %s", kp, 0); } + if (!S_ISREG(st.st_mode) || st.st_uid != geteuid() || (st.st_mode & 0777) != 0600 || st.st_size != 32) { + close(fd); + return jfail(j, EACCES, "key file %s must be a regular file of 32 bytes, owned by you, mode 0600 (found mode %04o); refusing it", kp, (unsigned)(st.st_mode & 07777)); + } + size_t got = 0; + while (got < 32) { + ssize_t r = read(fd, j->key + got, 32 - got); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) { close(fd); return jfail(j, EIO, "cannot read key file %s", kp, 0); } + got += (size_t)r; + } + close(fd); + return 0; +} + +int osh_journal_open(OshJournal *j, const char *path) +{ + memset(j, 0, sizeof *j); + j->fd = -1; + struct stat st; + int existed = lstat(path, &st) == 0; + long size = 0; + if (existed) { + if (!S_ISREG(st.st_mode) || st.st_uid != geteuid() || (st.st_mode & 07777) != 0600) + return jfail(j, EACCES, "journal %s must be a regular file owned by you with mode 0600 (found mode %04o); refusing it, fix or remove it", path, (unsigned)(st.st_mode & 07777)); + size = (long)st.st_size; + } + int fd = open(path, O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0600); + if (fd < 0) return jfail(j, errno, "cannot open journal %s", path, 0); + /* ONE SESSION PER JOURNAL: take the lock first, before the key is read or created and before recovery runs, so a live + * session's open intents are never reported UNKNOWN by another. The kernel drops the lock when this process exits or dies. */ + if (flock(fd, LOCK_EX | LOCK_NB) != 0) { + int e = errno; + close(fd); + if (e == EWOULDBLOCK) return jfail(j, EBUSY, "journal %s is in use by another osh session (one session per journal); start this one with --journal FILE to use a separate journal", path, 0); + return jfail(j, e, "cannot lock journal %s", path, 0); + } + /* everything below is decided from the locked descriptor, not from the earlier lstat (another session may have created or filled the file meanwhile) */ + if (fstat(fd, &st) != 0) { int e = errno; close(fd); return jfail(j, e, "cannot stat journal %s", path, 0); } + if (!S_ISREG(st.st_mode) || st.st_uid != geteuid() || (st.st_mode & 07777) != 0600) { + close(fd); + return jfail(j, EACCES, "journal %s must be a regular file owned by you with mode 0600 (found mode %04o); refusing it, fix or remove it", path, (unsigned)(st.st_mode & 07777)); + } + size = (long)st.st_size; + int krc = load_key(j, path, size > 0); + if (krc) { close(fd); return krc; } + if (size == 0) { /* empty: new, so make it and its directory entry durable */ + int rc = sync_fd(fd) == 0 ? fsync_parent(path) : -errno; + if (rc) { close(fd); return jfail(j, rc < 0 ? -rc : EIO, "cannot sync new journal %s", path, 0); } + } + uint64_t mx = 0; + int nl = 1; + if (size > 0) { + int bad = 0; + int rc = scan(path, max_cb, &mx, &bad, &nl); + if (rc && rc != -ENOENT) { close(fd); return jfail(j, -rc, "cannot read journal %s", path, 0); } + } + j->fd = fd; + j->next_rec = mx + 1; + if (!nl && commit(j, "\n", 1, 0) != 0) { int e = errno; close(fd); j->fd = -1; return jfail(j, e ? e : EIO, "cannot repair journal tail %s", path, 0); } + return 0; +} + +/* a state directory made by an earlier run must be ours and private; otherwise refuse (0 ok, -EACCES with why) */ +int osh_journal_check_dir(OshJournal *j, const char *dir) +{ + struct stat st; + if (stat(dir, &st) != 0) return jfail(j, errno, "cannot stat state directory %s", dir, 0); + if (!S_ISDIR(st.st_mode) || st.st_uid != geteuid() || (st.st_mode & 077) != 0) + return jfail(j, EACCES, "state directory %s must be owned by you with mode 0700 (found mode %04o); refusing it, fix it with chmod 700", dir, (unsigned)(st.st_mode & 07777)); + return 0; +} + +void osh_journal_close(OshJournal *j) +{ + if (j->fd >= 0) close(j->fd); + j->fd = -1; + memset(j->key, 0, sizeof j->key); +} + +/* ---- records ---- */ + +static void esc(const char *s, char *out, size_t cap) +{ + size_t o = 0, n = strlen(s); + if (!n) { snprintf(out, cap, "%%"); return; } /* an empty argv[0] */ + size_t from = n > 64 ? n - 64 : 0; /* keep the LAST 64 bytes: the program name matters, not its directory */ + if (from && o + 1 < cap) out[o++] = '~'; + for (size_t i = from; i < n && o + 4 < cap; i++) { + unsigned char c = (unsigned char)s[i]; + if (isalnum(c) || c == '.' || c == '_' || c == '/' || c == '-' || c == '+') out[o++] = (char)c; + else o += (size_t)snprintf(out + o, cap - o, "%%%02X", c); + } + out[o] = 0; +} + +uint64_t osh_journal_intent(OshJournal *j, const uint8_t dig[32], const OshRequest *r, int idx) +{ + const OshCmd *c = &r->cmd[idx]; + char dh[65], a0[200], lens[OSH_MAX_ARGV * 6 + 4], line[1024]; + hex(dig, dh); + esc(c->nargv > 0 ? c->argv[0] : "", a0, sizeof a0); + size_t lo = 0; + for (int k = 0; k < c->nargv; k++) lo += (size_t)snprintf(lens + lo, sizeof lens - lo, "%s%zu", k ? "," : "", strlen(c->argv[k])); + if (!lo) strcpy(lens, "-"); + int wr = 0; + for (int k = 0; k < c->nredir; k++) wr += c->redir[k].kind == OSH_R_OUT || c->redir[k].kind == OSH_R_APPEND; + uint64_t rec = j->next_rec; + int n = snprintf(line, sizeof line, "OSHJ1 %llu I %s %d/%d b=%d argc=%d wr=%d a0=%s lens=%s\n", (unsigned long long)rec, dh, idx, + r->ncmds, c->builtin_id, c->nargv, wr, a0, lens); + if (n <= 0 || (size_t)n >= sizeof line) return 0; + if (commit(j, line, (size_t)n, 0) != 0) return 0; + j->next_rec++; +#ifdef OSH_JOURNAL_TEST_HOOKS + if (j->die_after_intent && ++j->n_intent == j->die_after_intent) _exit(77); +#endif + return rec; +} + +int osh_journal_outcomes(OshJournal *j, const uint8_t dig[32], int ncmds, const OshJournalOutcome *o, int n) +{ + if (n <= 0) return 0; + char dh[65]; + hex(dig, dh); + char *buf = malloc((size_t)n * 160 + 1); + if (!buf) return -1; + size_t len = 0; + uint64_t rec = j->next_rec; + for (int i = 0; i < n; i++) { + int oc = o[i].outcome; + if (oc < 0 || oc > 4) oc = 4; + len += (size_t)snprintf(buf + len, 160, "OSHJ1 %llu O %llu %s %d/%d %s st=%d err=%d\n", (unsigned long long)rec++, + (unsigned long long)o[i].ref, dh, o[i].idx, ncmds, k_outcome[oc], o[i].status, o[i].err); + } + int rc = commit(j, buf, len, 1); + free(buf); + if (rc != 0) return -1; + j->next_rec = rec; + return 0; +} + +/* ---- recovery ---- */ + +typedef struct { + Line *open; + int n, cap; + uint64_t *closed; + int nclosed, capclosed; +} Rec; + +static void rec_cb(void *ctx, const Line *l) +{ + Rec *r = ctx; + if (l->kind == 'I') { + if (r->n == r->cap) { + int nc = r->cap ? r->cap * 2 : 64; + Line *p = realloc(r->open, (size_t)nc * sizeof *p); + if (!p) return; + r->open = p; + r->cap = nc; + } + r->open[r->n++] = *l; + } else if (l->ref) { + if (r->nclosed == r->capclosed) { + int nc = r->capclosed ? r->capclosed * 2 : 64; + uint64_t *p = realloc(r->closed, (size_t)nc * sizeof *p); + if (!p) return; + r->closed = p; + r->capclosed = nc; + } + r->closed[r->nclosed++] = l->ref; + } +} + +int osh_journal_recover(OshJournal *j, const char *path, OshJournalUnknown *out, int cap, int *bad) +{ + Rec r; + memset(&r, 0, sizeof r); + int nb = 0; + int rc = scan(path, rec_cb, &r, &nb, NULL); + if (bad) *bad = nb; + if (rc) { free(r.open); free(r.closed); return rc; } + int found = 0; + for (int i = 0; i < r.n; i++) { + int closed = 0; + for (int k = 0; k < r.nclosed && !closed; k++) closed = r.closed[k] == r.open[i].rec; + if (closed) continue; + if (out && found < cap) { + OshJournalUnknown *u = &out[found]; + u->intent_rec = r.open[i].rec; + memcpy(u->digest, r.open[i].digest, 65); + u->idx = r.open[i].idx; + u->ncmds = r.open[i].ncmds; + snprintf(u->argv0, sizeof u->argv0, "%s", r.open[i].a0); + } + found++; + char line[256]; + int n = snprintf(line, sizeof line, "OSHJ1 %llu O %llu %s %d/%d OUTCOME_UNKNOWN st=-1 err=%d recovered=1\n", + (unsigned long long)j->next_rec, (unsigned long long)r.open[i].rec, r.open[i].digest, r.open[i].idx, + r.open[i].ncmds, OSH_E_OUTCOME_UNKNOWN); + if (commit(j, line, (size_t)n, 1) != 0) { found = -EIO; break; } + j->next_rec++; + } + free(r.open); + free(r.closed); + return found; +} + +/* ---- default location ---- */ + +int osh_journal_default_path(const char *xdg, const char *home, char *out, size_t cap) +{ + int n; + if (xdg && xdg[0] == '/') n = snprintf(out, cap, "%s/osh/effects.journal", xdg); + else if (home && home[0] == '/') n = snprintf(out, cap, "%s/.local/state/osh/effects.journal", home); + else return -1; + return n > 0 && (size_t)n < cap ? 0 : -1; +} + +int osh_journal_mkparents(const char *path) +{ + char d[4096]; + if (strlen(path) >= sizeof d) return -ENAMETOOLONG; + strcpy(d, path); + char *last = strrchr(d, '/'); + if (!last) return 0; + *last = 0; + for (char *p = d + 1; ; p++) { + if (*p == '/' || *p == 0) { + char c = *p; + *p = 0; + if (mkdir(d, 0700) == 0) { /* newly created: make it and its place in the parent durable */ + int dfd = open(d, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dfd < 0) return -errno; + int sr = sync_fd(dfd) == 0 ? 0 : -errno; + close(dfd); + if (sr) return sr; + int pr = fsync_parent(d); + if (pr) return pr; + } else if (errno != EEXIST) return -errno; + *p = c; + if (!c) break; + } + } + return 0; +} + +#ifdef OSH_JOURNAL_TEST_HOOKS +/* marker symbol: the build checks the shipped osh does NOT contain it (so no test hook is compiled into production) */ +int osh_journal_test_hooks_compiled(void) { return 1; } +#endif diff --git a/src/osh/host/osh_journal.h b/src/osh/host/osh_journal.h new file mode 100644 index 000000000..0509ac92a --- /dev/null +++ b/src/osh/host/osh_journal.h @@ -0,0 +1,93 @@ +/* + * osh_journal.h -- durable effect journal of the osh Linux host adapter (OSH_PLATFORM_ABI.md section 10). + * + * An EFFECT is one external TASK_SPAWN or one write-class open (redirection kinds output/append). Before each effect the + * adapter appends an INTENT record and fsyncs the journal; after the pipeline is reaped it appends one OUTCOME record per + * effect and fsyncs again. After a crash, an intent with no outcome is OUTCOME_UNKNOWN and is NEVER replayed. + * + * This is the MANDATORY effect record (section 10). It is a separate file from any optional history or recording + * (section 13): it is written whatever the recording mode is, and it holds no argument values. + * + * File format (text, one record per line, '\n' terminated, append-only, mode 0600): + * OSHJ1 I / b= argc= wr= a0= lens= + * OSHJ1 O / st= err= [recovered=1] + * is a journal-wide counter (1, 2, ...), never a pid or any transient id. is the of the intent this + * outcome closes, or 0 for an outcome with no intent (the effect was refused or never reached: nothing was launched). + * is the lowercase hex request digest, HMAC-SHA256 under a random per-journal key kept in .key (osh_req_digest). OUTCOME is one of NOT_STARTED, COMPLETED, + * FAILED_NO_EFFECT, CANCELLED, OUTCOME_UNKNOWN. + * + * Redaction rule: argument values, assignment values, redirection targets and environment values are never written. + * Only argv[0], the argument count, argument lengths, the builtin id, the write-redirection count, the status and the + * request digest are. The digest is keyed (HMAC-SHA256, random per-journal key in .key, 0600), so a low-entropy secret + * given as a plain argument cannot be confirmed by hashing guesses against a leaked journal alone; it also replaces the VALUE + * of any assignment whose NAME is secret (osh_secret_name) by a fixed marker. Whoever holds journal AND key can test guesses. + */ +#ifndef OSH_JOURNAL_H +#define OSH_JOURNAL_H +#include +#include + +#include "osh_host.h" + +typedef struct OshJournal { + int fd; + uint64_t next_rec; + uint8_t key[32]; /* per-journal HMAC key (loaded from .key) */ + char why[4700]; /* why osh_journal_open or osh_journal_check_dir refused */ + int poisoned; /* sticky: the first failed write or fsync ends all journaling for this session; every later effect is refused */ + int tail_clean; /* after a failed write the fragment was cut back, so an outcome may still be appended */ +#ifdef OSH_JOURNAL_TEST_HOOKS + /* test-only fault injection; compiled out of the shipped binary */ + int die_after_intent; /* _exit(77) right after the Nth intent became durable (simulates a crash before launch) */ + int n_intent; + int fail_write_at; /* the Nth commit writes only half its bytes, then fails with ENOSPC */ + int fail_fsync_at; /* the Nth commit fails its fsync with EIO */ + int n_commit; +#endif +} OshJournal; + +typedef struct { + uint64_t intent_rec; + char digest[65]; + int idx, ncmds; + char argv0[200]; +} OshJournalUnknown; + +/* Open (create if needed, 0600) and fsync the directory when created; load or atomically create .key (32 random bytes, 0600). + * FAIL CLOSED: a journal or key with another owner or a mode other than 0600, a key of the wrong size, an unreadable key, or a + * missing key beside a journal that has records is refused (-errno, j->why names the reason). 0 ok, -errno. A torn last line (crash during a + * write) is closed with '\n' so the next record starts on its own line. */ +int osh_journal_open(OshJournal *j, const char *path); +void osh_journal_close(OshJournal *j); + +/* Default location of the mandatory journal: $XDG_STATE_HOME/osh/effects.journal, else $HOME/.local/state/osh/effects.journal + * (XDG Base Directory spec; the ABI draft and the osh docs name no location). 0 ok, -1 when neither variable is usable. */ +int osh_journal_default_path(const char *xdg_state_home, const char *home, char *out, size_t cap); +/* mkdir -p the parent directories of path with mode 0700. 0 ok, -errno. */ +int osh_journal_mkparents(const char *path); + +/* Recovery: report every intent with no outcome as UNKNOWN (never replayed; nothing is launched here) and append an + * OUTCOME_UNKNOWN record (recovered=1) for each so it is reported once. Returns the number found (all counted, at most + * cap stored in out), or -errno. *bad (optional) gets the number of unparsable (torn) lines. */ +int osh_journal_recover(OshJournal *j, const char *path, OshJournalUnknown *out, int cap, int *bad); + +/* ---- used by osh_exec.c ---- */ +int osh_secret_name(const char *name); /* 1 when the variable name is in the secret class (see osh_journal.c) */ +/* Request digest: HMAC-SHA256 under the journal's random per-journal key over a canonical encoding of the request. */ +void osh_req_digest(const OshJournal *j, const OshRequest *r, uint8_t out[32]); +/* The same encoding under plain SHA-256. NOT used by the host; it exists so the tests can show that the recorded (keyed) + * digest cannot be matched by guessing arguments and hashing them. */ +void osh_req_digest_unkeyed(const OshRequest *r, uint8_t out[32]); +/* A state directory that already exists must be ours with mode 0700, else refuse (-EACCES, j->why says why). */ +int osh_journal_check_dir(OshJournal *j, const char *dir); +/* Append and fsync an intent for command idx. Returns its rec (> 0) or 0 when it is not durable (the effect must not run). */ +uint64_t osh_journal_intent(OshJournal *j, const uint8_t dig[32], const OshRequest *r, int idx); + +typedef struct { + int idx; + uint64_t ref; /* intent rec or 0 */ + int outcome, status, err; +} OshJournalOutcome; +/* Append all outcomes in one write and fsync. 0 ok, -1 not durable. */ +int osh_journal_outcomes(OshJournal *j, const uint8_t dig[32], int ncmds, const OshJournalOutcome *o, int n); +#endif diff --git a/src/osh/host/osh_main.c b/src/osh/host/osh_main.c index 7c151dbd1..8d4597e38 100644 --- a/src/osh/host/osh_main.c +++ b/src/osh/host/osh_main.c @@ -7,6 +7,12 @@ * the grants, seals the admin handle, and every spawn / redirection open / cd is checked at the moment of the effect. * Without it the policy is a principal with no grants: every such effect is denied (fail closed). Builtins that make * no effect (printf, pwd, export, unset, exit) still run. + * The effect journal (osh_journal.h, ABI section 10) is MANDATORY and always on: before each external spawn or write-class + * redirection an intent is fsynced, after it an outcome. Default file: $XDG_STATE_HOME/osh/effects.journal, else + * $HOME/.local/state/osh/effects.journal (directories 0700, file 0600); `--journal FILE` (before or after --caps) names another. + * At startup every intent left without an outcome by an earlier run is reported on stderr as UNKNOWN (never re-run) and + * closed. There is no opt-out. If the journal cannot be opened or recovered the shell says so on stderr and refuses every + * effect (status 1, nothing launched); builtins without a write redirection still run. * OSH_INTERP=1 in the environment runs the shell core in the reference interpreter instead of native code. * Never runs a command through another shell: programs are started by the host adapter with execve(). */ @@ -17,10 +23,65 @@ #include #include "osh_caps.h" +#include "osh_journal.h" #include "osh_shell.h" extern char **environ; +static const char *g_journal_file; +static OshJournal g_journal = {.fd = -1}; + +static char g_journal_err[4700]; + +/* The effect journal is MANDATORY (ABI section 10 has no off switch). Open it (default location when no --journal was + * given), report what a previous run left unfinished, attach it. If it cannot be opened, recovered or written, the shell + * still starts but says so loudly and refuses every effect (spawn, write-class open) until it is run with a working one. */ +static void journal_unavailable(OshShell *sh, const char *what) +{ + snprintf(g_journal_err, sizeof g_journal_err, "%s", what); + sh->s.journal_error = g_journal_err; + osh_journal_close(&g_journal); + sh->s.journal = NULL; + fprintf(stderr, "osh: effect journal unavailable (%s): every command that starts a program or writes a file will be refused\n", what); +} + +static int journal_attach(OshShell *sh) +{ + char def[4096], why[4300]; + const char *path = g_journal_file; + sh->s.journal_required = 1; + if (!path) { + if (osh_journal_default_path(getenv("XDG_STATE_HOME"), getenv("HOME"), def, sizeof def) != 0) { + journal_unavailable(sh, "neither XDG_STATE_HOME nor HOME names an absolute directory; use --journal FILE"); + return 0; + } + int mk = osh_journal_mkparents(def); + if (mk) { snprintf(why, sizeof why, "%s: %s", def, strerror(-mk)); journal_unavailable(sh, why); return 0; } + path = def; + } + /* default or explicit: the directory holding the journal must be ours and private */ + { + char dir[4200]; + snprintf(dir, sizeof dir, "%s", path); + char *sl = strrchr(dir, '/'); + if (!sl) strcpy(dir, "."); + else if (sl == dir) dir[1] = 0; + else *sl = 0; + if (osh_journal_check_dir(&g_journal, dir)) { journal_unavailable(sh, g_journal.why); return 0; } + } + int rc = osh_journal_open(&g_journal, path); + if (rc) { journal_unavailable(sh, g_journal.why); return 0; } + OshJournalUnknown u[16]; + int bad = 0, n = osh_journal_recover(&g_journal, path, u, 16, &bad); + if (n < 0) { snprintf(why, sizeof why, "%s: recovery failed: %s", path, strerror(-n)); journal_unavailable(sh, why); return 0; } + for (int i = 0; i < n && i < 16; i++) + fprintf(stderr, "osh: journal: effect %d/%d of request %.16s... (record %llu, argv0 %s) has outcome UNKNOWN; it is not re-run\n", u[i].idx + 1, u[i].ncmds, u[i].digest, (unsigned long long)u[i].intent_rec, u[i].argv0); + if (n > 16) fprintf(stderr, "osh: journal: and %d more UNKNOWN\n", n - 16); + if (bad) fprintf(stderr, "osh: journal: %d unreadable line(s) ignored\n", bad); + sh->s.journal = &g_journal; + return 0; +} + static char *slurp_fd(int fd, size_t *n) { size_t cap = 4096, len = 0; @@ -46,6 +107,7 @@ static const char DEFAULT_POLICY[] = "principal 1\n"; static int arm(OshShell *sh, OshCaps *caps, const char *file) { char *z = NULL; + if (journal_attach(sh) != 0) return -1; if (file) { int fd = open(file, O_RDONLY | O_CLOEXEC); if (fd < 0) { fprintf(stderr, "osh: --caps %s: cannot open\n", file); return -1; } @@ -78,8 +140,9 @@ int main(int argc, char **argv) const char *ei = getenv("OSH_INTERP"); if (ei && strcmp(ei, "1") == 0) native = 0; const char *caps_file = NULL; - if (argc >= 3 && strcmp(argv[1], "--caps") == 0) { - caps_file = argv[2]; + while (argc >= 3 && (strcmp(argv[1], "--caps") == 0 || strcmp(argv[1], "--journal") == 0)) { + if (argv[1][2] == 'c') caps_file = argv[2]; + else g_journal_file = argv[2]; argv[2] = argv[0]; argv += 2; argc -= 2; @@ -112,5 +175,6 @@ int main(int argc, char **argv) } osh_shell_free(&sh); osh_caps_stop(&caps); + osh_journal_close(&g_journal); return rc & 255; } diff --git a/tests/.crumb b/tests/.crumb index b5dec00c2..7f8842e97 100644 --- a/tests/.crumb +++ b/tests/.crumb @@ -110,25 +110,25 @@ "children": [ { "digest": "e7498eca87fe5ca8dc27d92f2d99be0de3e4c804711f9d8cba5bb1e47ca95f74", - "last_commit": "80ca5d4", + "last_commit": "28911be", "name": "algebra", "purpose": "Directory tests/algebra. Purpose not yet described by a human." }, { "digest": "d484ca176e9932b098df5664d01bdd679c78f5b89f4d15a77eb30f43d235f570", - "last_commit": "80ca5d4", + "last_commit": "834ee93", "name": "ans", "purpose": "Tests 1-10 for ANS (docs/ans/INERTIAL_ALIGNMENT_SPEC_V1.md): freeze/digest, hostile reference mu" }, { "digest": "bd7114b42f99c7e51741abdf24329d20713c73a332bd5f349e04384fd0241e91", - "last_commit": "80ca5d4", + "last_commit": "e722877", "name": "brownian", "purpose": "Directory tests/brownian. Purpose not yet described by a human." }, { "digest": "1cbe9561b87b394e200f67996ce1407c377025d07ad033b27cdd542625e277d4", - "last_commit": "80ca5d4", + "last_commit": "30bb116", "name": "canonicalization", "purpose": "Directory tests/canonicalization. Purpose not yet described by a human." }, @@ -140,97 +140,97 @@ }, { "digest": "47683e6a56ca8e14ee526004b2a90dd08498507e8d4b0b42c3d85d22afb07d28", - "last_commit": "80ca5d4", + "last_commit": "28b8793", "name": "constraints", "purpose": "Directory tests/constraints. Purpose not yet described by a human." }, { "digest": "95b2041562face1ba7baa6c57456bf07d77a0f44e093b989ec18f559064e22d9", - "last_commit": "80ca5d4", + "last_commit": "49abb02", "name": "crumbline", "purpose": "Directory tests/crumbline. Purpose not yet described by a human." }, { "digest": "d57833fb3f63ef6475cf25e2e16319d818a0a407b825d5b4c5cbdd3cc0e06492", - "last_commit": "80ca5d4", + "last_commit": "00f54b6", "name": "dual_experiment", "purpose": "Tests for the DUAL applicability experiment: determinism (same seed, byte-identical results dige" }, { "digest": "fb0a9296a93d065d5e016ad0a950fc6b9691f8ddca12ad0111cee2e35791cdb4", - "last_commit": "80ca5d4", + "last_commit": "c819b37", "name": "effect", "purpose": "Directory tests/effect. Purpose not yet described by a human." }, { "digest": "bc2473da101ba5a74c32021a9d27ecb2007897f07a9689ba50ccc99b9030bf0c", - "last_commit": "80ca5d4", + "last_commit": "1a147e4", "name": "estimation", "purpose": "Directory tests/estimation. Purpose not yet described by a human." }, { "digest": "de2bc4e310a257dbd21cc5c9624641b137b1b4487d8876cb52469aea2af5b904", - "last_commit": "80ca5d4", + "last_commit": "3108fc2", "name": "fabric", "purpose": "Directory tests/fabric. Purpose not yet described by a human." }, { "digest": "90418926706f827aafd72938aee1dea89222cb5e465fba06a8df5a83253e0412", - "last_commit": "80ca5d4", + "last_commit": "28b8793", "name": "identity", "purpose": "Directory tests/identity. Purpose not yet described by a human." }, { "digest": "c653c851c8934ce9ac4eabaa32a9df65d858c9ac7a556e76b265b1ee81494443", - "last_commit": "80ca5d4", + "last_commit": "4f55f45", "name": "language", "purpose": "Directory tests/language. Purpose not yet described by a human." }, { "digest": "e485aa0a00f0a588e22d55caa704db8581a5da1b53080b311086e6edd38f6044", - "last_commit": "80ca5d4", + "last_commit": "30bb116", "name": "malformed", "purpose": "Directory tests/malformed. Purpose not yet described by a human." }, { "digest": "adba9b5ea1c000db36078fca7d1bfef0b2769b73c8fb474024d9409bd48bdbc1", - "last_commit": "80ca5d4", + "last_commit": "40d1ea3", "name": "numeric_native", "purpose": "Simulated M16 driver for numeric resource-lifecycle tests. No device execution or numeric parity" }, { - "digest": "cbeed5ed9e19195b442f1bde9cac95f066d4b7037b48f73859573d469240c664", - "last_commit": "3b53f25", + "digest": "73b1c903b94cd9f94314eb99e32a0245756c4ad241c49c92339ee9978cacd532", + "last_commit": "7adf33e", "name": "osh", "purpose": "osh lexer host driver, vendored aien-protocols PR#16 draft vectors (5ae5292)" }, { "digest": "a4d320b3203650a28c43ea954957d8902d1cc25cbdc8aecd15628c01a92f68f8", - "last_commit": "80ca5d4", + "last_commit": "d550b70", "name": "path", "purpose": "Directory tests/path. Purpose not yet described by a human." }, { "digest": "1fd5f914f326a1a51fc343ab633ac411e86bea22beee718b1460db066807f292", - "last_commit": "80ca5d4", + "last_commit": "8a2e268", "name": "physics0", "purpose": "PD-0 gates: world self-test, oracle calibration, learner L0/L1/NULL, mutations, OSC differential" }, { "digest": "4619a90a957e77cd3d5680132ab4d1a5ef65f43419ddcc089743ca5b7a7719ee", - "last_commit": "80ca5d4", + "last_commit": "8f8babe", "name": "polyglot", "purpose": "Directory tests/polyglot. Purpose not yet described by a human." }, { "digest": "16bea65aa50f0b3ab8b90cb286de048639fa8e635ff84e517e138c6f9f26a059", - "last_commit": "80ca5d4", + "last_commit": "3c82389", "name": "program", "purpose": "Directory tests/program. Purpose not yet described by a human." }, { "digest": "ba0c09f67d12b5d7de906129bdbe2f6e0a228e1a34236ecc4b779c523cb2061e", - "last_commit": "80ca5d4", + "last_commit": "6fdc4c3", "name": "r16_inventory", "purpose": "Directory tests/r16_inventory. Purpose not yet described by a human." }, @@ -242,19 +242,19 @@ }, { "digest": "25cabf47d18353539db28146434d246a2f81bf9c323471566451aca56806f279", - "last_commit": "80ca5d4", + "last_commit": "44d8c06", "name": "r16_surface", "purpose": "Directory tests/r16_surface. Purpose not yet described by a human." }, { "digest": "9106f2ea57e8f453322f0a988b61cfcbd06631573c9ff32a777903d27d7741e1", - "last_commit": "80ca5d4", + "last_commit": "40d1ea3", "name": "realize", "purpose": "Directory tests/realize. Purpose not yet described by a human." }, { "digest": "381184e79b26920b256dd4a774fb11f17a92afa8ceda4813eada241bac4163a9", - "last_commit": "80ca5d4", + "last_commit": "30bb116", "name": "relations", "purpose": "Directory tests/relations. Purpose not yet described by a human." }, @@ -266,38 +266,38 @@ }, { "digest": "b1311025a3bfd8dd7b5e07b1adf1d7ece502a15200f7207f515334f7083b8315", - "last_commit": "80ca5d4", + "last_commit": "5ae192a", "name": "searchtrace", "purpose": "Directory tests/searchtrace. Purpose not yet described by a human." }, { "digest": "3ecf636e2923038708cafa062895b8d8f2664dc1865cdff38575911eaa9f1b2d", - "last_commit": "80ca5d4", + "last_commit": "54826a3", "name": "train", "purpose": "Directory tests/train. Purpose not yet described by a human." }, { "digest": "75d5e576c38a0497a55e9f5ee79550cb94f9b75008f3e4e126312802704b3f86", - "last_commit": "80ca5d4", + "last_commit": "2564f57", "name": "turing", "purpose": "Directory tests/turing. Purpose not yet described by a human." }, { "digest": "3f19e3034ff999211cb13ab8995ca6c38d0d8e1f5bfbbbd621caaa08412d3f1f", - "last_commit": "80ca5d4", + "last_commit": "fed4f07", "name": "visor", "purpose": "Directory tests/visor. Purpose not yet described by a human." } ], - "children_root": "sha256:25307df070b72d8ae2c65989d733e08286e87634d467b89541273dcfa16e6817", - "compiled_at": "2026-10-08T13:06:11Z", + "children_root": "sha256:04c0254e511c24620f8aae767387f111847991d21249677fe2025e051f983604", + "compiled_at": "2026-10-09T04:11:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:3afb8a86231a7f5421eda8f4b1fa501b283145fa0f46b25c98fc74b298b9cf8c", + "digest": "sha256:4010554a7244d3f0837e6b31a4fc8d17ca0db18038afaa5de90bbec8a08e8496", "evidence_files": 11, "evidence_root": "sha256:d5c1bceb4d57ef0eb42797c58801b5926509711614c3e38bb7105b6efa3942f2", - "files": 941, - "generated_at_commit": "703e09c0cc8c973c93bc262912eef015ee4fc127", - "source_tree": "sha256:1394a8e2227a2bf9a719ed41b6dba5e19d5296f61d7ee4aea65b02d2646b7887" + "files": 942, + "generated_at_commit": "7adf33efee7b590d919662b54df824f0c2cf2cbf", + "source_tree": "sha256:757423745ccfad30d07024dfe038709ff04c9ae73a4e337f40f906d86025e094" }, "owner_lane": "", "provenance": { diff --git a/tests/osh/.crumb b/tests/osh/.crumb index 3cd05f878..7014fd36f 100644 --- a/tests/osh/.crumb +++ b/tests/osh/.crumb @@ -9,8 +9,8 @@ "purpose": "end-to-end tests of the osh program: argprint helper plus a runner comparing native and OSH_INTE" }, { - "digest": "1c28545ce48f728e1070ab03fc69b7cbb6f515ea6423b0f3198b7ea51157f646", - "last_commit": "d7d05ac", + "digest": "4f87a019164c79daa5e2386ba644d9366411bc39e27c2da3e4a597b153408c54", + "last_commit": "7adf33e", "name": "host", "purpose": "tests for the osh Linux host adapter execution service (hand-built request records, helper-mode " }, @@ -21,15 +21,15 @@ "purpose": "Core-only step traces of the osh shell units over fixture scripts (OSH-AIENOS-0 differential fix" } ], - "children_root": "sha256:bffabbbede587d83286e7d9f0e2c1e197cd822f77d105a7fe02f448b24d67f9c", - "compiled_at": "2026-10-08T12:58:13Z", + "children_root": "sha256:5324124d08361b8556db9e2b66e78a7937f8475e80390c0434a887394790edf0", + "compiled_at": "2026-10-09T04:11:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:cbeed5ed9e19195b442f1bde9cac95f066d4b7037b48f73859573d469240c664", + "digest": "sha256:73b1c903b94cd9f94314eb99e32a0245756c4ad241c49c92339ee9978cacd532", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 92, - "generated_at_commit": "4cc3bdda4ace926eb2a9a976551dc525279c53b8", - "source_tree": "sha256:8f5bcc8408f791b3a0fefb4124df3db6f1adfaf602c278d3913776c22cc23714" + "files": 93, + "generated_at_commit": "7adf33efee7b590d919662b54df824f0c2cf2cbf", + "source_tree": "sha256:7e2cbb72d84bce8192cbc6313ea05885284c314552c2e545c60c86257e8f5e50" } }, "name": "osh-tests", diff --git a/tests/osh/host/.crumb b/tests/osh/host/.crumb index 96d6f07b4..a5ead384f 100644 --- a/tests/osh/host/.crumb +++ b/tests/osh/host/.crumb @@ -3,14 +3,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-08T12:46:55Z", + "compiled_at": "2026-10-09T04:11:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:1c28545ce48f728e1070ab03fc69b7cbb6f515ea6423b0f3198b7ea51157f646", + "digest": "sha256:4f87a019164c79daa5e2386ba644d9366411bc39e27c2da3e4a597b153408c54", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 2, - "generated_at_commit": "6211ebf08d0d51eafe24d6962fdd22d643612347", - "source_tree": "sha256:a97a5406dfe8e00ede0dd0888e8af7e5e682bc0e1c952fc2acff0acebd4c8925" + "files": 3, + "generated_at_commit": "7adf33efee7b590d919662b54df824f0c2cf2cbf", + "source_tree": "sha256:7ae4369503619dbff0373f9e64045dc71e42514e41e8e6059560e551864eefa6" } }, "name": "host-tests", diff --git a/tests/osh/host/test_osh_journal.c b/tests/osh/host/test_osh_journal.c new file mode 100644 index 000000000..60f4fd359 --- /dev/null +++ b/tests/osh/host/test_osh_journal.c @@ -0,0 +1,1192 @@ +/* + * test_osh_journal.c -- durable intent/outcome journal of the osh Linux host adapter (OSH_PLATFORM_ABI.md section 10, + * aien-architecture#158). Records are hand-built; everything happens in a disposable temp dir under $TMPDIR. + * The binary is its own helper program: `test_osh_journal --helper append FILE` (create + append one byte) and + * `--helper sleep MS`. Scenarios that kill, interrupt or crash the shell run it in a forked child. + */ +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#include "osh_host.h" +#include "osh_journal.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int g_fail, g_checks; +#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_fail++; printf("FAIL line %d: %s -- ", __LINE__, #c); printf(__VA_ARGS__); printf("\n"); } } while (0) + +static char g_self[1024], g_dir[512]; +static int g_null; + +static void msleep(int ms) { struct timespec ts = {ms / 1000, (ms % 1000) * 1000000L}; nanosleep(&ts, NULL); } + +static int helper_main(int argc, char **argv) +{ + if (argc >= 4 && !strcmp(argv[2], "append")) { + int fd = open(argv[3], O_WRONLY | O_CREAT | O_APPEND, 0666); + if (fd < 0 || write(fd, "x", 1) != 1) return 1; + return 0; + } + if (argc >= 4 && !strcmp(argv[2], "sleep")) { msleep(atoi(argv[3])); return 0; } + if (argc >= 3 && !strcmp(argv[2], "quiet")) return 0; + return 2; +} + +/* ---------------- plumbing ---------------- */ + +static int count_fds(void) +{ + int n = 0; + DIR *d = opendir("/proc/self/fd"); + int dfd = dirfd(d); + struct dirent *e; + while ((e = readdir(d))) if (e->d_name[0] != '.' && atoi(e->d_name) != dfd) n++; + closedir(d); + return n; +} + +static char *slurp(const char *path, size_t *n) +{ + FILE *f = fopen(path, "rb"); + char *b = calloc(1, 1 << 16); + size_t len = f ? fread(b, 1, (1 << 16) - 1, f) : 0; + if (f) fclose(f); + if (n) *n = len; + return b; +} + +static int count_sub(const char *hay, const char *needle) +{ + int n = 0; + for (const char *p = hay; (p = strstr(p, needle)); p += strlen(needle)) n++; + return n; +} + +static long fsize(const char *path) { struct stat st; return stat(path, &st) == 0 ? (long)st.st_size : -1; } + +typedef struct { + OshSession s; + OshJournal j; + char jpath[4400]; + char dir[4200]; +} T; + +static int g_tn; + +static void t_begin(T *t, int with_journal) +{ + memset(t, 0, sizeof *t); + snprintf(t->dir, sizeof t->dir, "%s/t%d", g_dir, ++g_tn); + mkdir(t->dir, 0700); + snprintf(t->jpath, sizeof t->jpath, "%s/journal.log", t->dir); + char *envp[] = {"PATH=/usr/bin:/bin", "HOME=/tmp", NULL}; + osh_session_init(&t->s, envp); + for (int i = 0; i < 3; i++) t->s.fd[i] = g_null; + t->s.binding.valid = 1; + t->s.binding.domain = 2; + t->s.binding.cap_generation = 1; + if (with_journal) { + int rc = osh_journal_open(&t->j, t->jpath); + CHECK(rc == 0, "journal open: %d", rc); + t->s.journal = &t->j; + } +} + +static void t_end(T *t) +{ + if (t->s.journal) osh_journal_close(&t->j); + osh_session_free(&t->s); +} + +static void mpath(const T *t, const char *name, char *out, size_t cap) { snprintf(out, cap, "%s/%s", t->dir, name); } + +static OshBuilder *nb(void) +{ + OshBuilder *b = malloc(sizeof *b); + osh_rb_init(b, 0, 0); + return b; +} + +static void helper(OshBuilder *b, const char *op, const char *arg) +{ + osh_rb_cmd(b, 0); + osh_rb_arg(b, g_self); + osh_rb_arg(b, "--helper"); + osh_rb_arg(b, op); + if (arg) osh_rb_arg(b, arg); +} + +static int run(T *t, OshBuilder *b, OshResult *r) +{ + osh_rb_seal(b); + return osh_exec_record(&t->s, b->rec, osh_rb_cells(b), b->out, b->out_used, r); +} + +static char *jtext(const T *t) { return slurp(t->jpath, NULL); } + +/* the Nth line (0-based) of a text blob, copied */ +static int line_has(const char *text, int n, const char *needle) +{ + const char *p = text; + for (int i = 0; i < n && p; i++) { p = strchr(p, '\n'); if (p) p++; } + if (!p) return 0; + const char *e = strchr(p, '\n'); + size_t len = e ? (size_t)(e - p) : strlen(p); + char *ln = strndup(p, len); + int ok = strstr(ln, needle) != NULL; + free(ln); + return ok; +} + +/* ONE ACCOUNT: for every command of the request the LAST outcome record in the journal names the same outcome and status as + * the in-memory result. Returns the number of commands that disagree (or have no outcome record). */ +static int same_account(const T *t, int ncmds, const OshResult *r) +{ + static const char *const nm[] = {"NOT_STARTED", "COMPLETED", "FAILED_NO_EFFECT", "CANCELLED", "OUTCOME_UNKNOWN"}; + char *j = jtext(t); + int bad = 0; + for (int i = 0; i < ncmds; i++) { + char key[32], want[96], *hit = NULL; + snprintf(key, sizeof key, " %d/%d ", i, ncmds); + snprintf(want, sizeof want, "%s st=%d err=%d", nm[r->cmd[i].outcome], r->cmd[i].status, r->cmd[i].err); + for (char *p = j; p && *p;) { + char *e = strchr(p, '\n'); + if (strstr(p, " O ") && strstr(p, key) && (!e || strstr(p, key) < e)) hit = p; + p = e ? e + 1 : NULL; + } + char *e = hit ? strchr(hit, '\n') : NULL; + if (!hit || !(e ? (size_t)(e - hit) : strlen(hit)) || !memmem(hit, e ? (size_t)(e - hit) : strlen(hit), want, strlen(want))) { + bad++; + printf(" account mismatch cmd %d: want '%s' in: %.*s\n", i, want, hit ? (int)(e ? e - hit : (long)strlen(hit)) : 4, hit ? hit : "none"); + } + } + free(j); + return bad; +} + +static int wait_file(const char *path, long size, int ms) +{ + for (int i = 0; i < ms / 20; i++) { if (fsize(path) >= size) return 1; msleep(20); } + return fsize(path) >= size; +} + +/* run fn in a forked child (own process group when grp); returns the child's wait status */ +static int in_child(void (*fn)(T *, void *), T *t, void *arg, int grp) +{ + fflush(stdout); + pid_t pid = fork(); + if (pid == 0) { + if (grp) setpgid(0, 0); + fn(t, arg); + _exit(0); + } + int st = 0; + waitpid(pid, &st, 0); + if (grp) kill(-pid, SIGKILL); + return st; +} + +/* ---------------- tests ---------------- */ + +static void test_secret_names(void) +{ + CHECK(osh_secret_name("DB_PASSWORD") && osh_secret_name("api_token") && osh_secret_name("AWS_SECRET_ACCESS_KEY") && + osh_secret_name("Authorization"), "secret-class names are caught"); + CHECK(!osh_secret_name("PATH") && !osh_secret_name("HOME") && !osh_secret_name("LANG") && !osh_secret_name("PLAINVAR"), + "ordinary names are not (negative control)"); +} + +static void test_normal_and_redaction(void) +{ + T t; + t_begin(&t, 1); + char marker[4400]; + mpath(&t, "m1", marker, sizeof marker); + int fds0 = count_fds(); + OshBuilder *b = nb(); + helper(b, "append", marker); + osh_rb_arg(b, "--password=hunter2XYZ"); + osh_rb_assign(b, "API_TOKEN", "hunter2XYZ"); + osh_rb_assign(b, "PLAINVAR", "visibleval"); + char outf[4400]; + mpath(&t, "out-hunter2XYZ.txt", outf, sizeof outf); + osh_rb_redir(b, OSH_R_OUT, 1, outf, 0); + OshResult r; + int st = run(&t, b, &r); + free(b); + CHECK(st == 0 && r.cmd[0].outcome == OSH_OUT_COMPLETED && fsize(marker) == 1, "ran once (st %d)", st); + CHECK(same_account(&t, 1, &r) == 0, "normal: record == result"); + char *j = jtext(&t); + CHECK(count_sub(j, " I ") == 1 && count_sub(j, " O ") == 1, "one intent and one outcome:\n%s", j); + CHECK(line_has(j, 0, " I ") && line_has(j, 1, " O 1 ") && line_has(j, 1, "COMPLETED st=0 err=0"), "order and ref:\n%s", j); + CHECK(line_has(j, 0, "argc=") && line_has(j, 0, "wr=1"), "write-class open counted:\n%s", j); + CHECK(!strstr(j, "hunter2XYZ"), "secret value absent from record bytes"); + CHECK(!strstr(j, "visibleval") && !strstr(j, "PLAINVAR") && !strstr(j, "API_TOKEN") && !strstr(j, "password"), + "no assignment, argument or target text at all"); + CHECK(strstr(j, "a0=") != NULL, "argv[0] is recorded"); + free(j); + struct stat sb; + CHECK(stat(t.jpath, &sb) == 0 && (sb.st_mode & 0777) == 0600, "journal mode 0600"); + CHECK(count_fds() == fds0, "no descriptor leaked by a run (%d vs %d)", count_fds(), fds0); + t_end(&t); + + /* digest: a secret-named assignment's VALUE does not change it; an ordinary value and an argument do (control) */ + char kpa[700]; + snprintf(kpa, sizeof kpa, "%s/digest-a.log", g_dir); + OshJournal ja; + CHECK(osh_journal_open(&ja, kpa) == 0, "open journal A: %s", ja.why); + static OshRequest ra, rb, rc, rd; + OshBuilder *x[4]; + OshRequest *rq[4] = {&ra, &rb, &rc, &rd}; + const char *tok[4] = {"aaa", "bbb", "aaa", "aaa"}, *pv[4] = {"v", "v", "w", "v"}, *arg[4] = {"p", "p", "p", "q"}; + uint8_t dg[4][32]; + for (int i = 0; i < 4; i++) { + x[i] = nb(); + osh_rb_cmd(x[i], 0); + osh_rb_arg(x[i], "prog"); + osh_rb_arg(x[i], arg[i]); + osh_rb_assign(x[i], "MY_TOKEN", tok[i]); + osh_rb_assign(x[i], "PLAINVAR", pv[i]); + osh_rb_seal(x[i]); + CHECK(osh_req_decode(x[i]->rec, osh_rb_cells(x[i]), x[i]->out, x[i]->out_used, rq[i]) == 0, "decode"); + osh_req_digest(&ja, rq[i], dg[i]); + free(x[i]); + } + CHECK(!memcmp(dg[0], dg[1], 32), "secret value masked in the digest"); + CHECK(memcmp(dg[0], dg[2], 32) && memcmp(dg[0], dg[3], 32), "ordinary value and argument change the digest"); + osh_journal_close(&ja); +} + +static void hexs(const uint8_t d[32], char o[65]) +{ + for (int i = 0; i < 32; i++) snprintf(o + 2 * i, 3, "%02x", d[i]); +} + +/* The digest is keyed: two journals give two digests for one request, and a low-entropy secret passed as a plain argument + * cannot be confirmed by hashing guesses (the plain SHA-256 of every PIN does not match the recorded digest). */ +static void test_keyed_digest(void) +{ + char pa[700], pb[700]; + snprintf(pa, sizeof pa, "%s/keyed-a.log", g_dir); + snprintf(pb, sizeof pb, "%s/keyed-b.log", g_dir); + OshJournal a, b2, a2; + CHECK(osh_journal_open(&a, pa) == 0 && osh_journal_open(&b2, pb) == 0, "two journals, two keys"); + CHECK(memcmp(a.key, b2.key, 32) != 0, "keys differ between journals"); + OshBuilder *x = nb(); + osh_rb_cmd(x, 0); + osh_rb_arg(x, "login"); + osh_rb_arg(x, "--pin"); + osh_rb_arg(x, "1234"); + osh_rb_seal(x); + static OshRequest rq; + CHECK(osh_req_decode(x->rec, osh_rb_cells(x), x->out, x->out_used, &rq) == 0, "decode"); + free(x); + uint8_t da[32], db[32], da2[32], pl[32]; + osh_req_digest(&a, &rq, da); + osh_req_digest(&b2, &rq, db); + CHECK(memcmp(da, db, 32) != 0, "same request under two journal keys: different digests"); + osh_journal_close(&a); + CHECK(osh_journal_open(&a2, pa) == 0, "reopen: %s", a2.why); + osh_req_digest(&a2, &rq, da2); + CHECK(!memcmp(da, da2, 32), "the key is reused on reopen: same digest"); + struct stat sb; + char kp[720]; + snprintf(kp, sizeof kp, "%s.key", pa); + CHECK(stat(kp, &sb) == 0 && sb.st_size == 32 && (sb.st_mode & 0777) == 0600, "key file: 32 bytes, mode 0600"); + /* an attacker who knows the encoding and the argument shape but not the key */ + osh_req_digest_unkeyed(&rq, pl); + CHECK(memcmp(da, pl, 32) != 0, "recorded digest is not the plain SHA-256 of the request"); + char want[65], plain[65], got[65]; + hexs(da, want); + hexs(pl, plain); + int hit = 0, ctl = 0; + for (int pin = 0; pin < 10000; pin++) { + char s[16]; + snprintf(s, sizeof s, "%04d", pin); + OshBuilder *y = nb(); + osh_rb_cmd(y, 0); + osh_rb_arg(y, "login"); + osh_rb_arg(y, "--pin"); + osh_rb_arg(y, s); + osh_rb_seal(y); + static OshRequest rg; + osh_req_decode(y->rec, osh_rb_cells(y), y->out, y->out_used, &rg); + free(y); + uint8_t g[32]; + osh_req_digest_unkeyed(&rg, g); + hexs(g, got); + hit += !strcmp(got, want); + ctl += !strcmp(got, plain); + } + CHECK(hit == 0, "none of the 10000 PIN guesses hashed with plain SHA-256 matches the recorded digest (control: see next check)"); + CHECK(ctl == 1, "control: the same loop does find the PIN against the PLAIN digest of the request (%d)", ctl); + osh_journal_close(&a2); + osh_journal_close(&b2); +} + +static int deny_all(void *c, const OshBinding *bd, int op, const char *p) { (void)c; (void)bd; (void)op; (void)p; return OSH_E_DENIED; } + +static void test_denial(void) +{ + T t; + t_begin(&t, 1); + char marker[4400]; + mpath(&t, "m3", marker, sizeof marker); + t.s.binding.valid = 0; /* no authority */ + OshBuilder *b = nb(); + helper(b, "append", marker); + OshResult r; + int st = run(&t, b, &r); + free(b); + msleep(150); + CHECK(st == 126 && r.err == OSH_E_DENIED && r.cmd[0].pid == 0, "denied (st %d err %d)", st, r.err); + CHECK(fsize(marker) < 0, "negative control: no child ran, marker absent"); + char *j = jtext(&t); + CHECK(count_sub(j, " I ") == 0 && count_sub(j, " O 0 ") == 1 && strstr(j, "FAILED_NO_EFFECT st=126 err=1"), "denial record, no intent:\n%s", j); + free(j); + + /* control: the same request with authority runs */ + t.s.binding.valid = 1; + b = nb(); + helper(b, "append", marker); + st = run(&t, b, &r); + free(b); + CHECK(st == 0 && fsize(marker) == 1, "with authority the marker appears"); + t_end(&t); + + /* per-effect denial (ABI 9.2) at the moment of the spawn */ + T u; + t_begin(&u, 1); + mpath(&u, "m3b", marker, sizeof marker); + u.s.effect_hook = deny_all; + b = nb(); + helper(b, "append", marker); + st = run(&u, b, &r); + free(b); + msleep(150); + char *j2 = jtext(&u); + CHECK(st == 126 && fsize(marker) < 0 && count_sub(j2, " I ") == 0 && strstr(j2, "FAILED_NO_EFFECT"), "effect-hook denial:\n%s", j2); + free(j2); + t_end(&u); +} + +static void raise_int_group(void *ctx) { (void)ctx; kill(0, SIGINT); } + +static void child_sigint(T *t, void *arg) +{ + (void)arg; + OshBuilder *b = nb(); + helper(b, "sleep", "20000"); + helper(b, "sleep", "20000"); + t->s.after_launch_hook = raise_int_group; + OshResult r; + run(t, b, &r); + _exit(same_account(t, 2, &r) == 0 && r.cmd[0].outcome == OSH_OUT_COMPLETED && r.cmd[1].outcome == OSH_OUT_COMPLETED ? 0 : 3); +} + +static void test_interrupt(void) +{ + T t; + t_begin(&t, 1); + int st = in_child(child_sigint, &t, NULL, 1); + CHECK(WIFEXITED(st) && WEXITSTATUS(st) == 0, "SIGINT: record == result for both commands, both COMPLETED (child status %d)", st); + char *j = jtext(&t); + CHECK(count_sub(j, " I ") == 2 && count_sub(j, " O ") == 2 && count_sub(j, "COMPLETED st=130") == 2, "both ended by the signal: COMPLETED st=130 (ABI 8.4 convention):\n%s", j); + CHECK(line_has(j, 2, " O 1 ") && line_has(j, 3, " O 2 "), "outcomes close their intents:\n%s", j); + free(j); + osh_journal_close(&t.j); + OshJournal j2; + CHECK(osh_journal_open(&j2, t.jpath) == 0, "reopen"); + int bad = 0, n = osh_journal_recover(&j2, t.jpath, NULL, 0, &bad); + CHECK(n == 0 && bad == 0, "nothing unresolved after an interrupt (%d)", n); + osh_journal_close(&j2); + t.s.journal = NULL; + t_end(&t); +} + +static void test_partial_launch(void) +{ + T t; + t_begin(&t, 1); + OshBuilder *b = nb(); + helper(b, "sleep", "30000"); + helper(b, "sleep", "30000"); + helper(b, "sleep", "30000"); + t.s.fail_fork_at = 2; + OshResult r; + int st = run(&t, b, &r); + free(b); + CHECK(st == 1 && r.err == OSH_E_PARTIAL_LAUNCH, "partial launch (st %d err %d)", st, r.err); + CHECK(same_account(&t, 3, &r) == 0, "partial launch: record == result"); + char *j = jtext(&t); + CHECK(count_sub(j, " I ") == 2, "first and second have intents, third never reached:\n%s", j); + CHECK(count_sub(j, " O ") == 3, "three outcomes"); + CHECK(strstr(j, " 0/3 CANCELLED") && strstr(j, " 1/3 NOT_STARTED") && strstr(j, " 2/3 NOT_STARTED"), "first CANCELLED, rest NOT_STARTED:\n%s", j); + CHECK(strstr(j, " O 0 ") != NULL, "the never-reached command has an outcome with no intent"); + free(j); + t_end(&t); +} + +static void steal_child(void *ctx) { (void)ctx; msleep(300); waitpid(-1, NULL, 0); } + +static void test_echild_unknown(void) +{ + T t; + t_begin(&t, 1); + OshBuilder *b = nb(); + helper(b, "quiet", NULL); + t.s.after_launch_hook = steal_child; /* somebody else reaps our child: its fate is unknowable */ + OshResult r; + run(&t, b, &r); + free(b); + CHECK(r.cmd[0].outcome == OSH_OUT_UNKNOWN && r.err == OSH_E_OUTCOME_UNKNOWN, "result says unknown"); + CHECK(same_account(&t, 1, &r) == 0, "ECHILD: record == result"); + char *j = jtext(&t); + CHECK(strstr(j, " O 1 ") && strstr(j, "OUTCOME_UNKNOWN st=1 err=11"), "durably mirrored:\n%s", j); + free(j); + t_end(&t); +} + +static void child_kill_after_launch_hook(void *ctx) { (void)ctx; kill(getpid(), SIGKILL); } +static void child_kill_between(T *t, void *arg) +{ + OshBuilder *b = nb(); + helper(b, "append", (const char *)arg); + t->s.after_launch_hook = child_kill_after_launch_hook; /* the shell dies after the spawn, before any outcome */ + OshResult r; + run(t, b, &r); +} + +static void test_kill_between_and_recovery(void) +{ + T t; + t_begin(&t, 1); + char marker[4400]; + mpath(&t, "m7", marker, sizeof marker); + int st = in_child(child_kill_between, &t, marker, 0); + CHECK(WIFSIGNALED(st) && WTERMSIG(st) == SIGKILL, "shell died by SIGKILL between intent and outcome"); + CHECK(wait_file(marker, 1, 3000), "the already launched child still ran once"); + char *j = jtext(&t); + CHECK(count_sub(j, " I ") == 1 && count_sub(j, " O ") == 0, "intent only:\n%s", j); + free(j); + osh_journal_close(&t.j); + + OshJournal j2; + CHECK(osh_journal_open(&j2, t.jpath) == 0, "reopen after the crash"); + OshJournalUnknown u[4]; + int bad = -1, n = osh_journal_recover(&j2, t.jpath, u, 4, &bad); + CHECK(n == 1 && bad == 0 && u[0].idx == 0 && u[0].ncmds == 1 && strlen(u[0].digest) == 64, "one UNKNOWN reported (n %d)", n); + CHECK(strstr(u[0].argv0, "test_osh_journal") != NULL, "with argv0 (%s)", u[0].argv0); + { + OshBuilder *kb = nb(); + helper(kb, "append", marker); + osh_rb_seal(kb); + static OshRequest kr; + uint8_t kd[32]; + char kh[65]; + CHECK(osh_req_decode(kb->rec, osh_rb_cells(kb), kb->out, kb->out_used, &kr) == 0, "decode"); + free(kb); + osh_req_digest(&j2, &kr, kd); + hexs(kd, kh); + CHECK(!strcmp(kh, u[0].digest), "recovery reports the KEYED digest of the request (recomputed with the journal key)"); + osh_req_digest_unkeyed(&kr, kd); + hexs(kd, kh); + CHECK(strcmp(kh, u[0].digest) != 0, "and it is not the plain SHA-256"); + } + msleep(700); + CHECK(fsize(marker) == 1, "recovery did not replay: marker still 1 byte (%ld)", fsize(marker)); + j = jtext(&t); + CHECK(strstr(j, "OUTCOME_UNKNOWN") && strstr(j, "recovered=1"), "recovery closes it durably as UNKNOWN:\n%s", j); + free(j); + n = osh_journal_recover(&j2, t.jpath, u, 4, &bad); + CHECK(n == 0, "second recovery reports nothing new (%d)", n); + osh_journal_close(&j2); + t.s.journal = NULL; + t_end(&t); +} + +static void child_die_after_intent(T *t, void *arg) +{ + t->j.die_after_intent = 1; /* crash right after the intent is durable, before fork */ + OshBuilder *b = nb(); + helper(b, "append", (const char *)arg); + OshResult r; + run(t, b, &r); +} + +static void test_crash_before_launch(void) +{ + T t; + t_begin(&t, 1); + char marker[4400]; + mpath(&t, "m8", marker, sizeof marker); + int st = in_child(child_die_after_intent, &t, marker, 0); + CHECK(WIFEXITED(st) && WEXITSTATUS(st) == 77, "crashed after the intent (status %d)", st); + msleep(300); + CHECK(fsize(marker) < 0, "nothing was launched"); + osh_journal_close(&t.j); + OshJournal j2; + CHECK(osh_journal_open(&j2, t.jpath) == 0, "reopen"); + OshJournalUnknown u[2]; + int bad = 0, n = osh_journal_recover(&j2, t.jpath, u, 2, &bad); + CHECK(n == 1, "intent without outcome is UNKNOWN (%d)", n); + msleep(300); + CHECK(fsize(marker) < 0, "recovery launched nothing"); + osh_journal_close(&j2); + t.s.journal = NULL; + t_end(&t); +} + +static void test_fail_closed(void) +{ + T t; + t_begin(&t, 1); + char marker[4400]; + mpath(&t, "m9", marker, sizeof marker); + int full = open("/dev/full", O_WRONLY); + dup2(full, t.j.fd); /* the journal's descriptor now fails every write with ENOSPC */ + close(full); + OshBuilder *b = nb(); + helper(b, "append", marker); + OshResult r; + int st = run(&t, b, &r); + free(b); + msleep(150); + CHECK(st == 1 && r.err == OSH_E_IO && r.cmd[0].outcome == OSH_OUT_FAILED_NO_EFFECT && fsize(marker) < 0, + "no durable intent -> command not launched (st %d err %d)", st, r.err); + t_end(&t); +} + +static void test_non_effects_and_direct(void) +{ + T t; + t_begin(&t, 1); + long before = fsize(t.jpath); + OshBuilder *b = nb(); + osh_rb_cmd(b, OSH_B_PWD); + osh_rb_arg(b, "pwd"); /* builtin, no write-class open: not an effect */ + OshResult r; + run(&t, b, &r); + free(b); + CHECK(fsize(t.jpath) == before, "a builtin with no write open writes no record"); + char outf[4400]; + mpath(&t, "o10", outf, sizeof outf); + b = nb(); + osh_rb_cmd(b, OSH_B_PWD); + osh_rb_arg(b, "pwd"); + osh_rb_redir(b, OSH_R_OUT, 1, outf, 0); /* write-class open IS an effect, even for a builtin */ + run(&t, b, &r); + free(b); + char *j = jtext(&t); + CHECK(count_sub(j, " I ") == 1 && count_sub(j, "COMPLETED") == 1 && line_has(j, 0, "b=2"), "builtin with output redirection recorded:\n%s", j); + free(j); + + char marker[4400]; + mpath(&t, "m10", marker, sizeof marker); + const char *argv[] = {g_self, "--helper", "append", marker}; + int st = osh_submit_argv(&t.s, argv, 4, NULL, 0, NULL, 0, &r); /* ABI section 11: same path, same records */ + j = jtext(&t); + CHECK(st == 0 && count_sub(j, " I ") == 2 && count_sub(j, " O ") == 2, "direct-argv submission is journaled:\n%s", j); + free(j); + t_end(&t); + + /* control: a session without a journal behaves as before and writes nothing */ + T u; + t_begin(&u, 0); + b = nb(); + helper(b, "append", marker); + st = run(&u, b, &r); + free(b); + CHECK(st == 0 && fsize(u.jpath) < 0, "no journal -> no file"); + t_end(&u); +} + +static void test_torn_tail_and_cleanup(void) +{ + T t; + t_begin(&t, 1); + OshBuilder *b = nb(); + helper(b, "quiet", NULL); + OshResult r; + run(&t, b, &r); + free(b); + osh_journal_close(&t.j); + t.s.journal = NULL; + FILE *f = fopen(t.jpath, "ab"); + fputs("OSHJ1 99 I 00ff", f); /* a write cut short by a crash: no newline */ + fclose(f); + int fds0 = count_fds(); + OshJournal j2; + CHECK(osh_journal_open(&j2, t.jpath) == 0, "reopen over a torn tail"); + CHECK(j2.next_rec == 3, "record counter continues (%llu)", (unsigned long long)j2.next_rec); + int bad = 0, n = osh_journal_recover(&j2, t.jpath, NULL, 0, &bad); + CHECK(n == 0 && bad == 1, "torn line is ignored, not an intent (n %d bad %d)", n, bad); + osh_journal_close(&j2); + CHECK(count_fds() == fds0, "open/recover/close leaks no descriptor"); + int files = 0; + DIR *d = opendir(t.dir); + struct dirent *e; + while ((e = readdir(d))) if (e->d_name[0] != '.' && strcmp(e->d_name, "journal.log") && strcmp(e->d_name, "journal.log.key")) files++; + closedir(d); + CHECK(files == 0, "only the journal and its key exist, no temp files (%d stray)", files); + t_end(&t); +} + +/* the real program. jpath NULL = no --journal (default location from xdg/home); xdg/home NULL = variable unset */ +static int run_osh(const char *osh, const char *caps, const char *jpath, const char *script, const char *errf, const char *xdg, + const char *home) +{ + pid_t pid = fork(); + if (pid == 0) { + int fd = open(errf, O_WRONLY | O_CREAT | O_TRUNC, 0600); + dup2(fd, 2); + dup2(g_null, 1); + if (xdg) setenv("XDG_STATE_HOME", xdg, 1); else unsetenv("XDG_STATE_HOME"); + if (home) setenv("HOME", home, 1); else unsetenv("HOME"); + const char *av[12]; + int n = 0; + av[n++] = osh; + if (caps) { av[n++] = "--caps"; av[n++] = caps; } + if (jpath) { av[n++] = "--journal"; av[n++] = jpath; } + av[n++] = "-c"; + av[n++] = script; + av[n] = NULL; + execv(osh, (char *const *)av); + _exit(127); + } + int st = 0; + waitpid(pid, &st, 0); + return WIFEXITED(st) ? WEXITSTATUS(st) : -1; +} + +static void test_cli(const char *osh) +{ + char jp[700], ef[700], pol[700], xdg[700], home[700], jd[1400], mk[700], sc[1500]; + snprintf(jp, sizeof jp, "%s/cli.log", g_dir); + snprintf(ef, sizeof ef, "%s/cli.err", g_dir); + snprintf(pol, sizeof pol, "%s/cli.policy", g_dir); + snprintf(xdg, sizeof xdg, "%s/xdg", g_dir); + snprintf(home, sizeof home, "%s/home", g_dir); + snprintf(mk, sizeof mk, "%s/cli.marker", g_dir); + FILE *pf = fopen(pol, "w"); + fputs("principal 77\nallow spawn /bin\nallow spawn /usr/bin\nallow spawn /home\nallow write /home\n", pf); + fclose(pf); + /* default policy (no grants): the spawns are denied; denials are recorded, no intents, nothing ran */ + CHECK(run_osh(osh, NULL, jp, "/bin/true", ef, xdg, home) == 126, "denied by the default policy"); + char *d0 = slurp(jp, NULL); + CHECK(count_sub(d0, " I ") == 0 && count_sub(d0, "FAILED_NO_EFFECT st=126 err=1") == 1, "program records the denial:\n%s", d0); + free(d0); + unlink(jp); + CHECK(run_osh(osh, pol, jp, "/bin/true; /bin/false", ef, xdg, home) == 1, "osh --journal runs the script"); + char *j = slurp(jp, NULL); + CHECK(count_sub(j, " I ") == 2 && count_sub(j, " O ") == 2 && strstr(j, "COMPLETED st=0") && strstr(j, "COMPLETED st=1"), "program writes intents and outcomes:\n%s", j); + free(j); + FILE *f = fopen(jp, "ab"); /* a previous run died after its intent */ + fprintf(f, "OSHJ1 50 I %064d 0/1 b=0 argc=2 wr=0 a0=/bin/touch lens=10,3\n", 7); + fclose(f); + CHECK(run_osh(osh, pol, jp, "/bin/echo second-run", ef, xdg, home) == 0, "second start"); + char *e = slurp(ef, NULL); + CHECK(strstr(e, "has outcome UNKNOWN; it is not re-run") && strstr(e, "/bin/touch"), "UNKNOWN reported at start:\n%s", e); + free(e); + CHECK(run_osh(osh, pol, jp, "/bin/true", ef, xdg, home) == 0, "third start"); + e = slurp(ef, NULL); + CHECK(!strstr(e, "UNKNOWN"), "reported once only"); + free(e); + + /* MANDATORY: no --journal -> the default location is used ($XDG_STATE_HOME/osh/effects.journal), 0700 dirs, 0600 file */ + snprintf(jd, sizeof jd, "%s/osh/effects.journal", xdg); + CHECK(run_osh(osh, pol, NULL, "/bin/true", ef, xdg, home) == 0, "no --journal still runs"); + struct stat sb; + char xo[1000]; + snprintf(xo, sizeof xo, "%s/osh", xdg); + CHECK(stat(jd, &sb) == 0 && (sb.st_mode & 0777) == 0600, "default journal exists with mode 0600"); + CHECK(stat(xo, &sb) == 0 && (sb.st_mode & 0777) == 0700, "its directory is 0700"); + j = slurp(jd, NULL); + CHECK(count_sub(j, " I ") == 1 && count_sub(j, " O ") == 1, "the effect was recorded there:\n%s", j); + free(j); + /* fallback: no XDG_STATE_HOME -> $HOME/.local/state/osh/effects.journal */ + snprintf(jd, sizeof jd, "%s/.local/state/osh/effects.journal", home); + mkdir(home, 0700); + CHECK(run_osh(osh, pol, NULL, "/bin/true", ef, NULL, home) == 0 && stat(jd, &sb) == 0 && (sb.st_mode & 0777) == 0600, + "HOME fallback location used"); + char dd[1200]; + snprintf(dd, sizeof dd, "%s/.local/state/osh", home); + CHECK(stat(dd, &sb) == 0 && (sb.st_mode & 0777) == 0700, "fallback directory is 0700"); + + /* unwritable journal: effects refused by name, nothing launched, non-effect builtins still run */ + snprintf(jd, sizeof jd, "%s/not-a-dir", g_dir); + FILE *nf = fopen(jd, "w"); /* a regular file where the state directory must be */ + fclose(nf); + unlink(mk); + snprintf(sc, sizeof sc, "/bin/touch %s", mk); + CHECK(run_osh(osh, pol, NULL, sc, ef, jd, home) == 1, "effect refused when the journal cannot be opened"); + e = slurp(ef, NULL); + CHECK(strstr(e, "effect journal unavailable") && strstr(e, "effect refused, nothing was run"), "named error:\n%s", e); + free(e); + msleep(150); + CHECK(fsize(mk) < 0, "no child was launched (marker absent)"); + CHECK(run_osh(osh, pol, NULL, "printf x", ef, jd, home) == 0, "a builtin without a write redirection is unaffected"); + snprintf(sc, sizeof sc, "printf x > %s", mk); + CHECK(run_osh(osh, pol, NULL, sc, ef, jd, home) == 1 && fsize(mk) < 0, "a write-class redirection is an effect: refused, no file"); + /* an explicit --journal that cannot be opened is the same refusal (no silent fallback) */ + snprintf(sc, sizeof sc, "/bin/touch %s", mk); + CHECK(run_osh(osh, pol, "/nonexistent-dir/j.log", sc, ef, xdg, home) == 1 && fsize(mk) < 0, "explicit unopenable --journal: effect refused"); + /* the key file sits beside the default journal: 32 bytes, 0600 */ + snprintf(jd, sizeof jd, "%s/.local/state/osh/effects.journal.key", home); + CHECK(stat(jd, &sb) == 0 && sb.st_size == 32 && (sb.st_mode & 0777) == 0600, "default key file: 32 bytes, 0600"); + /* wrong-mode key, wrong-mode journal, wrong-mode state dir: refused by name, nothing launched; fixing them restores service */ + char kd[3000], jf[2900], sd[1500]; + snprintf(sd, sizeof sd, "%s/.local/state/osh", home); + snprintf(jf, sizeof jf, "%s/effects.journal", sd); + snprintf(kd, sizeof kd, "%s.key", jf); + snprintf(sc, sizeof sc, "/bin/touch %s", mk); + unlink(mk); + chmod(kd, 0644); + CHECK(run_osh(osh, pol, NULL, sc, ef, NULL, home) == 1 && fsize(mk) < 0, "key with mode 0644: effect refused, nothing launched"); + e = slurp(ef, NULL); + CHECK(strstr(e, "effect journal unavailable") && strstr(e, "key file"), "named: %s", e); + free(e); + chmod(kd, 0600); + chmod(jf, 0644); + CHECK(run_osh(osh, pol, NULL, sc, ef, NULL, home) == 1 && fsize(mk) < 0, "journal with mode 0644: effect refused"); + chmod(jf, 0600); + chmod(sd, 0755); + CHECK(run_osh(osh, pol, NULL, sc, ef, NULL, home) == 1 && fsize(mk) < 0, "state directory with mode 0755: effect refused"); + e = slurp(ef, NULL); + CHECK(strstr(e, "state directory") && strstr(e, "0700"), "named: %s", e); + free(e); + chmod(sd, 0700); + unlink(kd); + CHECK(run_osh(osh, pol, NULL, sc, ef, NULL, home) == 1 && fsize(mk) < 0, "key deleted beside a journal with records: effect refused"); + snprintf(sc, sizeof sc, "/bin/touch %s", mk); + /* control: the same command with a working journal does run */ + CHECK(run_osh(osh, pol, jp, sc, ef, xdg, home) == 0 && fsize(mk) == 0, "control: with a working journal the marker is created"); +} + +static void test_key_and_modes(void) +{ + char p[1400], k[1500], dir[700]; + snprintf(dir, sizeof dir, "%s/km", g_dir); + mkdir(dir, 0700); + snprintf(p, sizeof p, "%s/j.log", dir); + snprintf(k, sizeof k, "%s.key", p); + OshJournal j; + CHECK(osh_journal_open(&j, p) == 0, "fresh journal and key: %s", j.why); + osh_journal_close(&j); + chmod(k, 0644); + CHECK(osh_journal_open(&j, p) != 0 && strstr(j.why, "mode 0600"), "key with mode 0644 refused: %s", j.why); + chmod(k, 0600); + CHECK(truncate(k, 16) == 0 && osh_journal_open(&j, p) != 0, "key of the wrong size refused"); + unlink(k); + mkdir(k, 0700); + CHECK(osh_journal_open(&j, p) != 0, "unreadable key (a directory) refused"); + rmdir(k); + /* a missing key beside a journal with records: refused, no silent new key */ + FILE *f = fopen(p, "ab"); + fputs("OSHJ1 1 O 0 00 0/1 NOT_STARTED st=0 err=0\n", f); + fclose(f); + CHECK(osh_journal_open(&j, p) != 0 && strstr(j.why, "missing") && access(k, F_OK) != 0, "missing key beside a journal with records refused, no key invented: %s", j.why); + /* a pre-existing journal with a wrong mode is REFUSED (not silently fixed), and nothing is changed */ + unlink(p); + f = fopen(p, "w"); + fclose(f); + chmod(p, 0644); + CHECK(osh_journal_open(&j, p) != 0 && strstr(j.why, "mode 0600"), "journal with mode 0644 refused: %s", j.why); + struct stat sb; + CHECK(stat(p, &sb) == 0 && (sb.st_mode & 0777) == 0644, "and its mode was left alone"); + CHECK(osh_journal_check_dir(&j, dir) == 0, "private directory accepted"); + chmod(dir, 0755); + CHECK(osh_journal_check_dir(&j, dir) != 0 && strstr(j.why, "0700"), "directory with mode 0755 refused: %s", j.why); + chmod(dir, 0700); +} + +/* library level: journal_required with no journal open refuses every effect and launches nothing */ +static void test_required_without_journal(void) +{ + T t; + t_begin(&t, 0); + t.s.journal_required = 1; + t.s.journal_error = "test: unwritable"; + char marker[4400]; + mpath(&t, "mreq", marker, sizeof marker); + OshBuilder *b = nb(); + helper(b, "append", marker); + OshResult r; + int st = run(&t, b, &r); + free(b); + msleep(150); + CHECK(st == 1 && r.err == OSH_E_IO && r.cmd[0].outcome == OSH_OUT_FAILED_NO_EFFECT && r.cmd[0].pid == 0 && fsize(marker) < 0, + "required journal missing -> effect refused (st %d)", st); + b = nb(); + osh_rb_cmd(b, OSH_B_PWD); + osh_rb_arg(b, "pwd"); + st = run(&t, b, &r); + free(b); + CHECK(st == 0 && r.cmd[0].outcome == OSH_OUT_COMPLETED, "non-effect builtin unaffected"); + t_end(&t); +} + +/* ---------------- review round: partial launch on a failed later intent, sticky failure, fsync, modes, hooks ---------------- */ + +void osh_hmac_for_test(const uint8_t key[32], const uint8_t *msg, size_t n, uint8_t out[32]); + +static void test_hmac_vectors(void) +{ + /* RFC 4231 test cases 1 and 2 (keys shorter than 32 bytes are zero-extended, which HMAC treats as the same key) */ + uint8_t key[32] = {0}, out[32]; + char h[65]; + memset(key, 0x0b, 20); + osh_hmac_for_test(key, (const uint8_t *)"Hi There", 8, out); + hexs(out, h); + CHECK(!strcmp(h, "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"), "RFC 4231 case 1: %s", h); + memset(key, 0, sizeof key); + memcpy(key, "Jefe", 4); + osh_hmac_for_test(key, (const uint8_t *)"what do ya want for nothing?", 28, out); + hexs(out, h); + CHECK(!strcmp(h, "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"), "RFC 4231 case 2: %s", h); +} + +/* The test program supplies its own fsync(2); calls on the journal's descriptor are counted, then really performed. If the + * journal stopped calling fsync, the count below would fall short and this test fails. */ +static int g_fsync_fd = -1, g_fsync_n; +int fsync(int fd) +{ + if (fd == g_fsync_fd) g_fsync_n++; + return (int)syscall(SYS_fsync, fd); +} + +static void test_fsync_counted(void) +{ + T t; + t_begin(&t, 1); + g_fsync_fd = t.j.fd; + g_fsync_n = 0; + OshBuilder *b = nb(); + helper(b, "quiet", NULL); + OshResult r; + run(&t, b, &r); + free(b); + CHECK(t.j.n_commit == 2 && g_fsync_n == 2, "one intent + one outcome = 2 commits, each followed by a real fsync on the journal (commits %d, fsyncs %d)", t.j.n_commit, g_fsync_n); + g_fsync_fd = -1; + t_end(&t); +} + +static int zombies(void) +{ + int n = 0; + while (waitpid(-1, NULL, WNOHANG) > 0) n++; + return n; +} + +static void test_pipeline_later_intent_fails(void) +{ + T t; + t_begin(&t, 1); + char m1[4400], m2[4400], m3[4400]; + mpath(&t, "pl1", m1, sizeof m1); + mpath(&t, "pl2", m2, sizeof m2); + mpath(&t, "pl3", m3, sizeof m3); + OshBuilder *b = nb(); + helper(b, "sleep", "30000"); /* a: starts */ + helper(b, "append", m2); /* b: its intent write fails */ + helper(b, "append", m3); /* c: never reached */ + t.j.fail_write_at = 2; /* commit 1 = a's intent, commit 2 = b's intent */ + OshResult r; + int st = run(&t, b, &r); + free(b); + msleep(200); + CHECK(st == 1 && r.err == OSH_E_PARTIAL_LAUNCH, "journal failure on member 2 of 3: PARTIAL_LAUNCH (st %d err %d)", st, r.err); + CHECK(r.cmd[0].outcome == OSH_OUT_CANCELLED && r.cmd[0].pid > 0, "member 1 was started and is CANCELLED (%d)", r.cmd[0].outcome); + CHECK(kill(r.cmd[0].pid, 0) != 0 && errno == ESRCH, "member 1 is gone, not running"); + CHECK(zombies() == 0, "and reaped: no zombie left"); + CHECK(r.cmd[1].outcome == OSH_OUT_FAILED_NO_EFFECT && r.cmd[1].pid == 0 && r.cmd[2].outcome == OSH_OUT_NOT_STARTED && r.cmd[2].pid == 0, + "members 2 and 3 never launched (%d, %d)", r.cmd[1].outcome, r.cmd[2].outcome); + CHECK(fsize(m2) < 0 && fsize(m3) < 0, "their marker files do not exist"); + CHECK(same_account(&t, 3, &r) == 0, "records match the result"); + char *j = jtext(&t); + CHECK(count_sub(j, " I ") == 1 && strstr(j, " 0/3 CANCELLED") && strstr(j, " 1/3 FAILED_NO_EFFECT"), "journal: one intent, member 1 cancelled:\n%s", j); + free(j); + t_end(&t); +} + +static int rec_numbers_unique(const char *text) +{ + unsigned long long seen[512]; + int n = 0, bad = 0; + for (const char *p = text; p && *p;) { + unsigned long long v; + if (!strncmp(p, "OSHJ1 ", 6) && sscanf(p + 6, "%llu", &v) == 1) { + for (int i = 0; i < n; i++) bad += seen[i] == v; + if (n < 512) seen[n++] = v; + } + p = strchr(p, '\n'); + if (p) p++; + } + return bad; +} + +static void sticky_case(int write_fail) +{ + T t; + t_begin(&t, 1); + char m1[4400], m2[4400]; + mpath(&t, write_fail ? "sk1" : "sk3", m1, sizeof m1); + mpath(&t, write_fail ? "sk2" : "sk4", m2, sizeof m2); + if (write_fail) t.j.fail_write_at = 1; else t.j.fail_fsync_at = 1; + OshBuilder *b = nb(); + helper(b, "append", m1); + OshResult r; + int st = run(&t, b, &r); + free(b); + msleep(150); + CHECK(st == 1 && fsize(m1) < 0, "%s: first command refused (st %d), nothing launched", write_fail ? "short write" : "fsync failure", st); + CHECK(t.j.poisoned, "journal is poisoned"); + long size1 = fsize(t.jpath); + char *before = slurp(t.jpath, NULL); + int intents_before = count_sub(before, " I "); + free(before); + int commits = t.j.n_commit; + /* the injected fault is one-shot; a second command must STILL be refused, by name, and write nothing */ + int err = dup(2), ef = open("/dev/null", O_WRONLY); + char errf[4400]; + mpath(&t, "sk.err", errf, sizeof errf); + int efd = open(errf, O_WRONLY | O_CREAT | O_TRUNC, 0600); + t.s.fd[2] = efd; + b = nb(); + helper(b, "append", m2); + st = run(&t, b, &r); + free(b); + close(efd); close(ef); close(err); + msleep(150); + char *e = slurp(errf, NULL); + CHECK(st == 1 && r.err == OSH_E_IO && r.cmd[0].outcome == OSH_OUT_FAILED_NO_EFFECT && fsize(m2) < 0, "second command refused, nothing launched (st %d)", st); + CHECK(e && strstr(e, "effect journal failed") && strstr(e, "nothing was run"), "refusal is named:\n%s", e ? e : "(none)"); + free(e); + char *after = slurp(t.jpath, NULL); + CHECK(count_sub(after, " I ") == intents_before, "no new intent was written after the poison"); + CHECK(write_fail || fsize(t.jpath) == size1, "after a failed fsync nothing at all is written (%ld vs %ld)", fsize(t.jpath), size1); + CHECK(t.j.n_commit <= commits + 1, "at most an intent-less outcome line was attempted (%d vs %d)", t.j.n_commit, commits); + free(after); + /* recovery reads the file sanely: reopen, then run a command; record numbers never repeat and every line parses */ + osh_journal_close(&t.j); + OshJournal j2; + CHECK(osh_journal_open(&j2, t.jpath) == 0, "reopen after the failure: %s", j2.why); + OshJournalUnknown u[8]; + int bad = 0; + int nu = osh_journal_recover(&j2, t.jpath, u, 8, &bad); + CHECK(nu >= 0 && bad == 0, "recovery reads the file sanely (unknown %d, unreadable lines %d)", nu, bad); + t.s.journal = &j2; + t.s.fd[2] = g_null; + b = nb(); + helper(b, "quiet", NULL); + st = run(&t, b, &r); + free(b); + char *txt = slurp(t.jpath, NULL); + CHECK(st == 0 && rec_numbers_unique(txt) == 0, "after reopening, a new command runs and no record number repeats:\n%s", txt); + free(txt); + osh_journal_close(&j2); + t.s.journal = NULL; + osh_session_free(&t.s); +} + +static void test_sticky_failure(void) +{ + sticky_case(1); + sticky_case(0); +} + +static void test_explicit_journal_modes(void) +{ + char dir[700], p[1400], k[1500]; + snprintf(dir, sizeof dir, "%s/em", g_dir); + mkdir(dir, 0700); + snprintf(p, sizeof p, "%s/j.log", dir); + snprintf(k, sizeof k, "%s.key", p); + OshJournal j; + CHECK(osh_journal_open(&j, p) == 0, "fresh"); + osh_journal_close(&j); + chmod(p, 0400); + CHECK(osh_journal_open(&j, p) != 0 && strstr(j.why, "0600"), "journal mode 0400 refused: %s", j.why); + chmod(p, 0700); + CHECK(osh_journal_open(&j, p) != 0 && strstr(j.why, "0600"), "journal mode 0700 refused: %s", j.why); + chmod(p, 0600); + CHECK(osh_journal_open(&j, p) == 0, "exactly 0600 accepted"); + osh_journal_close(&j); + /* mkparents creates every missing level at 0700 */ + char deep[1800]; + snprintf(deep, sizeof deep, "%s/mp/a/b/effects.journal", g_dir); + CHECK(osh_journal_mkparents(deep) == 0, "mkparents"); + struct stat sb; + char d1[1800]; + snprintf(d1, sizeof d1, "%s/mp/a/b", g_dir); + CHECK(stat(d1, &sb) == 0 && (sb.st_mode & 0777) == 0700, "created directory is 0700"); + CHECK(osh_journal_mkparents(deep) == 0, "and is idempotent"); +} + +static void test_cli_explicit_dir(const char *osh) +{ + char pol[700], ef[700], sd[700], jp[900], mk[700], sc[1500]; + snprintf(pol, sizeof pol, "%s/cli.policy", g_dir); + snprintf(ef, sizeof ef, "%s/cli2.err", g_dir); + snprintf(sd, sizeof sd, "%s/ed", g_dir); + snprintf(jp, sizeof jp, "%s/j.log", sd); + snprintf(mk, sizeof mk, "%s/cli2.marker", g_dir); + snprintf(sc, sizeof sc, "/bin/touch %s", mk); + mkdir(sd, 0755); + CHECK(run_osh(osh, pol, jp, sc, ef, NULL, "/tmp") == 1 && fsize(mk) < 0, "explicit --journal in a 0755 directory: effect refused, nothing launched"); + char *e = slurp(ef, NULL); + CHECK(strstr(e, "state directory") && strstr(e, "0700"), "named: %s", e); + free(e); + chmod(sd, 0700); + CHECK(run_osh(osh, pol, jp, sc, ef, NULL, "/tmp") == 0 && fsize(mk) == 0, "control: with a private directory it runs"); +} + +/* ONE SESSION PER JOURNAL (flock). Start osh in its own process group without waiting. */ +static pid_t start_osh(const char *osh, const char *caps, const char *jpath, const char *script, const char *errf) +{ + pid_t pid = fork(); + if (pid == 0) { + setpgid(0, 0); + int fd = open(errf, O_WRONLY | O_CREAT | O_TRUNC, 0600); + dup2(fd, 2); + dup2(g_null, 1); + const char *av[8] = {osh, "--caps", caps, "--journal", jpath, "-c", script, NULL}; + execv(osh, (char *const *)av); + _exit(127); + } + setpgid(pid, pid); + return pid; +} + +static void test_cli_one_session(const char *osh) +{ + char pol[700], jp[900], ef1[700], ef2[700], ef3[700], mk[700], sc[1500], key[1000]; + snprintf(pol, sizeof pol, "%s/cli.policy", g_dir); + snprintf(jp, sizeof jp, "%s/lock.log", g_dir); + snprintf(key, sizeof key, "%s.key", jp); + snprintf(ef1, sizeof ef1, "%s/lk1.err", g_dir); + snprintf(ef2, sizeof ef2, "%s/lk2.err", g_dir); + snprintf(ef3, sizeof ef3, "%s/lk3.err", g_dir); + snprintf(mk, sizeof mk, "%s/lk.marker", g_dir); + pid_t a = start_osh(osh, pol, jp, "/bin/sleep 2; /bin/true", ef1); + for (int i = 0; i < 200 && !(fsize(jp) > 0); i++) msleep(25); + CHECK(fsize(jp) > 0, "first session holds the journal and has written its intent"); + /* second session on the SAME journal: effects refused by name, nothing launched, builtins still work */ + snprintf(sc, sizeof sc, "/bin/touch %s", mk); + CHECK(run_osh(osh, pol, jp, sc, ef2, NULL, "/tmp") == 1 && fsize(mk) < 0, "second session: effect refused, nothing launched"); + char *e = slurp(ef2, NULL); + CHECK(strstr(e, "in use by another osh session") && strstr(e, "--journal") && strstr(e, "use a separate journal);") && !strstr(e, "journal0"), "named, says to use --journal, exact ending (no stray digit):\n%s", e); + free(e); + CHECK(run_osh(osh, pol, jp, "printf x", ef2, NULL, "/tmp") == 0, "second session: a builtin without a write still runs"); + int st = 0; + waitpid(a, &st, 0); + CHECK(WIFEXITED(st) && WEXITSTATUS(st) == 0, "first session unaffected (exit %d)", WIFEXITED(st) ? WEXITSTATUS(st) : -1); + char *j = slurp(jp, NULL); + CHECK(count_sub(j, " I ") == 2 && count_sub(j, " O ") == 2 && rec_numbers_unique(j) == 0, "no duplicate record numbers, nothing from the refused session:\n%s", j); + free(j); + /* the lock dies with the process: SIGKILL a session mid-command, a new session takes the lock and recovery reports the open intent once */ + unlink(jp); + unlink(key); + pid_t b = start_osh(osh, pol, jp, "/bin/sleep 30", ef1); + for (int i = 0; i < 200 && !(fsize(jp) > 0); i++) msleep(25); + CHECK(fsize(jp) > 0, "second run: intent written"); + kill(-b, SIGKILL); + waitpid(b, NULL, 0); + msleep(100); + snprintf(sc, sizeof sc, "/bin/touch %s", mk); + CHECK(run_osh(osh, pol, jp, sc, ef3, NULL, "/tmp") == 0 && fsize(mk) == 0, "after the holder was killed, a new session gets the lock and runs"); + e = slurp(ef3, NULL); + CHECK(count_sub(e, "has outcome UNKNOWN") == 1, "recovery marks the killed session's open intent UNKNOWN exactly once:\n%s", e); + free(e); + CHECK(run_osh(osh, pol, jp, "/bin/true", ef3, NULL, "/tmp") == 0, "next start"); + e = slurp(ef3, NULL); + CHECK(count_sub(e, "UNKNOWN") == 0, "and not again"); + free(e); + j = slurp(jp, NULL); + CHECK(rec_numbers_unique(j) == 0, "record numbers unique across sessions:\n%s", j); + free(j); +} + +/* a forked builtin never execs: it must not keep the journal descriptor (and so the flock) after the shell is SIGKILLed */ +static void test_cli_orphan_builtin(const char *osh) +{ + char pol[700], jp[900], ef[700], mk[700], fifo[700], sc[1500]; + snprintf(pol, sizeof pol, "%s/orphan.policy", g_dir); + snprintf(jp, sizeof jp, "%s/orphan.log", g_dir); + snprintf(ef, sizeof ef, "%s/orphan.err", g_dir); + snprintf(mk, sizeof mk, "%s/orphan.marker", g_dir); + snprintf(fifo, sizeof fifo, "%s/orphan.fifo", g_dir); + FILE *pf = fopen(pol, "w"); + fprintf(pf, "principal 77\nallow spawn /bin\nallow spawn /usr/bin\nallow write %s\n", g_dir); + fclose(pf); + CHECK(mkfifo(fifo, 0600) == 0, "fifo"); + snprintf(sc, sizeof sc, "pwd > %s | /bin/true", fifo); + pid_t a = start_osh(osh, pol, jp, sc, ef); + for (int i = 0; i < 200 && !(fsize(jp) > 0); i++) msleep(25); + msleep(400); /* the forked builtin is now blocked opening the fifo */ + kill(a, SIGKILL); /* only the shell: the blocked builtin child is orphaned and still alive */ + waitpid(a, NULL, 0); + msleep(100); + snprintf(sc, sizeof sc, "/bin/touch %s", mk); + CHECK(run_osh(osh, pol, jp, sc, ef, NULL, "/tmp") == 0 && fsize(mk) == 0, "new session gets the lock at once while the orphan still holds the fifo"); + char *e = slurp(ef, NULL); + CHECK(!strstr(e, "in use by another"), "no 'in use' refusal:\n%s", e); + free(e); + int rd = open(fifo, O_RDONLY | O_NONBLOCK); /* let the orphan go */ + char buf[4400]; + for (int i = 0; i < 40; i++) { if (read(rd, buf, sizeof buf) > 0) break; msleep(25); } + close(rd); + msleep(100); + unlink(fifo); +} + +int main(int argc, char **argv) +{ + if (argc >= 2 && !strcmp(argv[1], "--helper")) return helper_main(argc, argv); + const char *osh_bin = argc >= 2 ? argv[1] : NULL; + ssize_t n = readlink("/proc/self/exe", g_self, sizeof g_self - 1); + if (n <= 0) return 1; + g_self[n] = 0; + const char *tmp = getenv("TMPDIR"); + snprintf(g_dir, sizeof g_dir, "%s/osh-journal-XXXXXX", tmp && *tmp ? tmp : "/tmp"); + if (!mkdtemp(g_dir)) return 1; + g_null = open("/dev/null", O_RDWR); + test_secret_names(); + test_keyed_digest(); + test_normal_and_redaction(); + test_denial(); + test_interrupt(); + test_partial_launch(); + test_echild_unknown(); + test_kill_between_and_recovery(); + test_crash_before_launch(); + test_fail_closed(); + test_non_effects_and_direct(); + test_torn_tail_and_cleanup(); + test_required_without_journal(); + test_key_and_modes(); + test_hmac_vectors(); + test_fsync_counted(); + test_pipeline_later_intent_fails(); + test_sticky_failure(); + test_explicit_journal_modes(); + if (osh_bin) { test_cli(osh_bin); test_cli_explicit_dir(osh_bin); test_cli_one_session(osh_bin); test_cli_orphan_builtin(osh_bin); } + close(g_null); + char cmd[4400]; + snprintf(cmd, sizeof cmd, "rm -rf '%s'", g_dir); + if (system(cmd)) {} + printf("%d checks, %d failed\n", g_checks, g_fail); + printf(g_fail ? "OSH_JOURNAL_FAIL\n" : "OSH_JOURNAL_PASS\n"); + return g_fail ? 1 : 0; +}