diff --git a/.github/workflows/catalog.yml b/.github/workflows/catalog.yml index 082ef57..f1f3d8b 100644 --- a/.github/workflows/catalog.yml +++ b/.github/workflows/catalog.yml @@ -2,9 +2,9 @@ name: Public catalog source verification 'on': push: branches: ['main'] - paths: ['registry.json', '.github/workflows/catalog.yml'] + paths: ['registry.json', '.github/workflows/catalog.yml', 'catalog_tests/**'] pull_request: - paths: ['registry.json', '.github/workflows/catalog.yml'] + paths: ['registry.json', '.github/workflows/catalog.yml', 'catalog_tests/**'] workflow_dispatch: permissions: contents: read @@ -53,6 +53,32 @@ jobs: (out/'VERIFIED.json').write_text(json.dumps({'commit':os.environ['GITHUB_SHA'],'run':os.environ['GITHUB_RUN_ID'],'python':sys.version,'catalog_sha256':hashlib.sha256(raw).hexdigest(),'artifact_count':len(data['artifacts']),'verified':checked['verified'],'distinct_tests':20,'modes':['normal','optimized'],'private_sources_fetched':False,'scope':'declared public payload identity and query behavior, not scientific acceptance'},indent=2)+'\n') print('ALL_DECLARED_PUBLIC_ARTIFACTS_VERIFIED',len(data['artifacts'])) PY + - name: W8d V control on the authenticated query- pin (normal and -O, separate receipt) + env: + PYTHONDONTWRITEBYTECODE: '1' + W8D_REQUIRE_SOURCE: '1' + W8D_QUERY_SOURCE: ${{ runner.temp }}/catalog-evidence/workspace/query-/research_query.py + shell: bash + run: | + set -euo pipefail + src="$W8D_QUERY_SOURCE" + test -f "$src" || { echo "::error::authenticated query- source missing: $src"; exit 1; } + test "$(stat -c %s "$src")" = 5577 || { echo "::error::query- source is not 5577 bytes"; exit 1; } + echo "54105dcd723e71b19263afc8f449a7d77b78cec27148f13603f33be7727e6b6b $src" | sha256sum -c - || { echo "::error::query- source sha256 mismatch"; exit 1; } + ev="$RUNNER_TEMP/catalog-evidence/w8d-v-control"; mkdir -p "$ev" + cd catalog_tests + for mode in normal optimized; do + if [ "$mode" = optimized ]; then flags='-B -O -S'; want=1; else flags='-B -S'; want=0; fi + rc=0 + env -u PYTHONOPTIMIZE W8D_MODE_RECEIPT="$ev/$mode.receipt.json" python $flags -m unittest -v test_w8d_verify_refusal_control >"$ev/$mode.stdout" 2>"$ev/$mode.stderr" || rc=$? + echo "$rc" >"$ev/$mode.rc"; cat "$ev/$mode.stdout" "$ev/$mode.stderr" + if [ "$rc" -ne 0 ]; then echo "::error::V control failed ($mode, rc=$rc)"; exit 1; fi + grep -q '^Ran 13 tests in ' "$ev/$mode.stderr" || { echo "::error::V control did not run exactly 13 tests ($mode)"; exit 1; } + grep -qx 'OK' "$ev/$mode.stderr" || { echo "::error::V control did not end in a bare OK ($mode)"; exit 1; } + if grep -q 'skipped' "$ev/$mode.stderr"; then echo "::error::V control skipped ($mode)"; exit 1; fi + python -B -S -c "import json,sys; r=json.load(open(sys.argv[1])); sys.exit(0 if r['parent_optimize']==r['child_optimize']==int(sys.argv[2]) else 1)" "$ev/$mode.receipt.json" "$want" || { echo "::error::V control mode receipt is not optimize=$want ($mode)"; exit 1; } + echo "W8D_V_CONTROL $mode rc=0 ran=13 optimize=$want" + done - name: Preserve actual evidence including failures if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 diff --git a/.github/workflows/contracts.yml b/.github/workflows/contracts.yml index 7cd1b0d..c533ba3 100644 --- a/.github/workflows/contracts.yml +++ b/.github/workflows/contracts.yml @@ -7,8 +7,8 @@ name: Source contracts and architecture conformance - 'examples/**' - 'tools/contract_validation.py' - 'tools/architecture_conformance.py' - - 'tests/test_source_contracts.py' - - 'tests/test_architecture_conformance.py' + - 'tests/**' + - '.github/workflows/catalog.yml' - '.github/workflows/contracts.yml' workflow_dispatch: permissions: diff --git a/catalog_tests/test_w8d_verify_refusal_control.py b/catalog_tests/test_w8d_verify_refusal_control.py new file mode 100644 index 0000000..da0d0d8 --- /dev/null +++ b/catalog_tests/test_w8d_verify_refusal_control.py @@ -0,0 +1,245 @@ +"""Proposed control (W8d, group V): the catalog `--verify` refusal contract of the +query- lookup tool that meta-framework's catalog.yml pins and executes +(query- 8e201316d17cf4ff3c679e1e9906d4b016ac6730 research_query.py, blob c2dd46a2, +sha256 54105dcd...; catalog.yml L38/L40/L42/L46). + +Positive: exact bytes for two rows in two repositories -> exit 0, empty stderr, +stdout is exactly the verified JSON report. +Negatives (one predicate per test, always on the SECOND row 'b' in +'google-drive', so first-row-only or one-repository exemptions cannot pass): +exit 2, stderr exactly 'REFUSED: \n', EMPTY stdout, and the API raises +CatalogError with the exact message. Offline: no network. + +Source location (first that exists): $W8D_QUERY_SOURCE, then +$FEDERATION_WORKSPACE/query-/research_query.py, then ../query-/research_query.py +beside this repository. If $W8D_QUERY_SOURCE is set but missing the module fails +closed; if nothing is found the module is SKIPPED (a skip is not protection). + +W8-F (meta-framework catalog_tests/, run by catalog.yml): with W8D_REQUIRE_SOURCE=1 the +ONLY accepted source is $W8D_QUERY_SOURCE (no FEDERATION_WORKSPACE or sibling fallback, +never a skip); unset or missing -> the module fails closed. test_mode_receipt spawns a +child through the same child_flags() helper that cli() uses and checks that the child's +actual sys.flags.optimize equals the parent's; with W8D_MODE_RECEIPT= it also writes +that observation as JSON (the optimized-coverage receipt). +""" +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + + +def _locate(): + env = os.environ.get('W8D_QUERY_SOURCE') + if os.environ.get('W8D_REQUIRE_SOURCE') == '1' and not env: + raise RuntimeError('W8D_REQUIRE_SOURCE=1 requires W8D_QUERY_SOURCE (no fallback)') + if env: + p = Path(env) + if not p.is_file(): + raise RuntimeError('W8D_QUERY_SOURCE does not name a file: ' + env) + return p.resolve() + cands = [] + if os.environ.get('FEDERATION_WORKSPACE'): + cands.append(Path(os.environ['FEDERATION_WORKSPACE']) / 'query-' / 'research_query.py') + cands.append(Path(__file__).resolve().parents[2] / 'query-' / 'research_query.py') + for p in cands: + if p.is_file(): + return p.resolve() + raise unittest.SkipTest('query- research_query.py not found; set W8D_QUERY_SOURCE') + + +QUERY = _locate() +_SPEC = importlib.util.spec_from_file_location('w8d_checked_query', QUERY) +q = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(q) + +A_BYTES = b'alpha\n' +B_BYTES = b'beta\n' +MEANING = 'exact bytes only; not currentness or theorem acceptance' + + +def child_flags(): + # forward the parent's optimization to every child (M292-OPT-01) + return ['-B', '-S'] + (['-O'] if sys.flags.optimize else []) + + +def child_env(): + # C164-OPT-01: drop ambient PYTHONOPTIMIZE. One -O cannot express a + # parent level above 1, so pin that observed level after the pop. + env = dict(os.environ) + env.pop('PYTHONOPTIMIZE', None) + if sys.flags.optimize > 1: + env['PYTHONOPTIMIZE'] = str(sys.flags.optimize) + return env + + +def row(key, repo, path, payload, **over): + r = {'key': key, 'repository': repo, 'path': path, 'commit': '1' * 40, + 'visibility': 'public', 'bytes': len(payload), + 'sha256': hashlib.sha256(payload).hexdigest(), + 'scope': 'synthetic W8d control row, not acceptance'} + r.update(over) + return r + + +class VerifyRefusalControl(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.base = Path(tmp.name).resolve() + self.ws = self.base / 'ws' + (self.ws / 'Math-').mkdir(parents=True) + (self.ws / 'google-drive' / 'r').mkdir(parents=True) + (self.ws / 'Math-' / 'a.txt').write_bytes(A_BYTES) + (self.ws / 'google-drive' / 'r' / 'b.txt').write_bytes(B_BYTES) + self.catalog = { + 'schema_version': 1, 'scientific_status_authority': False, + 'repositories': { + 'Math-': {'full_name': 'd6g8k5htny-coder/Math-', 'visibility': 'public'}, + 'google-drive': {'full_name': 'd6g8k5htny-coder/google-drive', 'visibility': 'public'}, + 'sandbox': {'full_name': 'd6g8k5htny-coder/sandbox', 'visibility': 'private'}}, + 'artifacts': [row('a', 'Math-', 'a.txt', A_BYTES), + row('b', 'google-drive', 'r/b.txt', B_BYTES)]} + self.catpath = self.base / 'catalog.json' + + # helpers ------------------------------------------------------------- + def write_catalog(self): + self.catpath.write_text(json.dumps(self.catalog), encoding='utf-8') + + def cli(self, *extra, cwd=None, workspace=True): + self.write_catalog() + args = [sys.executable, *child_flags(), str(QUERY), '--registry', str(self.catpath), '--verify'] + if workspace: + args += ['--workspace', str(self.ws)] + p = subprocess.run(args + list(extra), cwd=cwd or self.base, + capture_output=True, text=True, timeout=20, env=child_env()) + return p.returncode, p.stdout, p.stderr + + def assert_refused(self, message): + code, out, err = self.cli() + self.assertEqual(err, 'REFUSED: ' + message + '\n') + self.assertEqual(code, 2) + self.assertEqual(out, '', 'a refused run must not print a report') + + def assert_api_refused(self, message): + self.write_catalog() + data = q.load_catalog(self.catpath) + with self.assertRaises(q.CatalogError) as cm: + q.verify(data, self.ws) + self.assertEqual(str(cm.exception), message) + + def assert_load_refused(self, message): + self.write_catalog() + with self.assertRaises(q.CatalogError) as cm: + q.load_catalog(self.catpath) + self.assertEqual(str(cm.exception), message) + self.assert_refused(message) + + def set_b(self, **over): + self.catalog['artifacts'][1].update(over) + + # mode receipt ---------------------------------------------------------- + def test_mode_receipt(self): + p = subprocess.run([sys.executable, *child_flags(), '-c', 'import sys; print(sys.flags.optimize)'], + capture_output=True, text=True, timeout=20, env=child_env()) + self.assertEqual((p.returncode, p.stderr), (0, '')) + receipt = {'parent_optimize': sys.flags.optimize, 'child_optimize': int(p.stdout.strip()), + 'child_flags': child_flags(), 'query_source': str(QUERY), + 'query_sha256': hashlib.sha256(QUERY.read_bytes()).hexdigest()} + if os.environ.get('W8D_MODE_RECEIPT'): + Path(os.environ['W8D_MODE_RECEIPT']).write_text(json.dumps(receipt, sort_keys=True) + '\n') + self.assertEqual(receipt['child_optimize'], receipt['parent_optimize']) + + # positive ------------------------------------------------------------ + def test_exact_bytes_are_verified_with_exact_report(self): + code, out, err = self.cli() + self.assertEqual((code, err), (0, '')) + self.assertEqual(out, json.dumps({'meaning': MEANING, 'verified': ['a', 'b']}, + indent=2, sort_keys=True) + '\n') + self.write_catalog() + self.assertEqual(q.verify(q.load_catalog(self.catpath), self.ws)['verified'], ['a', 'b']) + + # V-BYTES (L101-102) -------------------------------------------------- + def test_longer_payload_is_byte_count_refusal(self): + (self.ws / 'google-drive/r/b.txt').write_bytes(B_BYTES + b'\n') + self.assert_api_refused('byte count mismatch: b') + self.assert_refused('byte count mismatch: b') + + def test_shorter_payload_is_byte_count_refusal(self): + (self.ws / 'google-drive/r/b.txt').write_bytes(B_BYTES[:-1]) + self.assert_api_refused('byte count mismatch: b') + self.assert_refused('byte count mismatch: b') + + # V-HASH (L103-105) --------------------------------------------------- + def test_same_length_substitution_is_hash_refusal(self): + (self.ws / 'google-drive/r/b.txt').write_bytes(b'BETA\n') + self.assert_api_refused('hash mismatch: b') + self.assert_refused('hash mismatch: b') + + # V-PAYLOAD (L95-100) ------------------------------------------------- + def test_symlinked_final_component_is_refused(self): + target = self.base / 'elsewhere.txt' + target.write_bytes(B_BYTES) + p = self.ws / 'google-drive/r/b.txt' + p.unlink() + p.symlink_to(target) + self.assert_api_refused('symlink payload refused: b') + self.assert_refused('symlink payload refused: b') + + def test_symlinked_intermediate_directory_is_refused(self): + real = self.ws / 'real-gd' + (self.ws / 'google-drive').rename(real) + (self.ws / 'google-drive').symlink_to(real, target_is_directory=True) + self.assert_api_refused('symlink payload refused: b') + self.assert_refused('symlink payload refused: b') + + def test_missing_payload_names_the_key(self): + (self.ws / 'google-drive/r/b.txt').unlink() + self.assert_api_refused('missing/outside payload: b') + self.assert_refused('missing/outside payload: b') + + # V-COMMIT (L71-72) --------------------------------------------------- + def test_non_exact_commit_is_refused(self): + for bad in ('abcdef1', 'A' * 40, '0' * 40 + 'x', 'refs/' + '0' * 40, 'main'): + with self.subTest(commit=bad): + self.set_b(commit=bad) + self.assert_load_refused('exact commit required') + + # V-SHAFMT (L73-74) --------------------------------------------------- + def test_non_exact_sha256_is_refused(self): + for bad in ('a' * 40, 'a' * 63, 'a' * 64 + '0', 'A' * 64): + with self.subTest(sha256=bad): + self.set_b(sha256=bad) + self.assert_load_refused('exact SHA256 required') + + # V-BYTESFMT (L75-76) ------------------------------------------------- + def test_invalid_byte_count_is_refused(self): + for bad in (True, -1, 10000001, 5.0, '5'): + with self.subTest(bytes=bad): + self.set_b(bytes=bad) + self.assert_load_refused('invalid byte count') + + # V-PATH (valid_path L29-35) ------------------------------------------ + def test_unsafe_paths_are_refused(self): + for bad in ('r\\b.txt', 'r:b.txt', './r/b.txt', 'r//b.txt', '/r/b.txt', + '../r/b.txt', 'r/../b.txt', ''): + with self.subTest(path=bad): + self.set_b(path=bad) + self.assert_load_refused('unsafe path') + + # V-CLI (L118-133) ---------------------------------------------------- + def test_verify_without_workspace_is_refused_even_in_a_valid_cwd(self): + code, out, err = self.cli(cwd=self.ws, workspace=False) + self.assertEqual(err, 'REFUSED: --verify requires --workspace\n') + self.assertEqual(code, 2) + self.assertEqual(out, '') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_w8d_catalog_fetch_control.py b/tests/test_w8d_catalog_fetch_control.py new file mode 100644 index 0000000..880e879 --- /dev/null +++ b/tests/test_w8d_catalog_fetch_control.py @@ -0,0 +1,167 @@ +"""Proposed control (W8d, group C): the inline fetch() identity gate in +meta-framework .github/workflows/catalog.yml (L28-36 at 75685db7). + +The job's only exercise of fetch() is the real registry, where every row is +legitimate, so no refusal branch is ever executed by CI. This control extracts +fetch() verbatim from the workflow text (no copy of the logic lives here), +binds it to a fake urllib and a temporary root, and checks each predicate in +isolation. Offline: no network. + +Positive: each of the six approved repositories at a 40-hex commit, safe path, +exact size+sha256 -> returns root//, writes exactly the served +bytes, requests exactly the pinned raw URL once. +Negatives: ValueError with the exact message ('unapproved source', +'unsafe path', 'invalid identity', 'source mismatch: /'), and +nothing written under root; the first three also make NO request. +""" +from __future__ import annotations + +import hashlib +import os +import pathlib +import re +import tempfile +import textwrap +import types +import unittest +from pathlib import Path + +WORKFLOW = Path(os.environ.get('W8D_CATALOG_YML') or + Path(__file__).resolve().parents[1] / '.github' / 'workflows' / 'catalog.yml') +APPROVED = ('Math-', 'meta-framework', 'query-', 'google-drive', 'trial', 'governance-') +COMMIT = '1' * 40 +PAYLOAD = b'alpha\n' +DIGEST = hashlib.sha256(PAYLOAD).hexdigest() + + +def extract_fetch_source(text): + lines = text.splitlines() + starts = [i for i, l in enumerate(lines) if l.rstrip().endswith("<<'PY'")] + if len(starts) != 1: + raise AssertionError('expected exactly one <<\'PY\' heredoc, found %d' % len(starts)) + body = [] + for l in lines[starts[0] + 1:]: + if l.strip() == 'PY': + break + body.append(l) + else: + raise AssertionError('unterminated heredoc') + script = textwrap.dedent('\n'.join(body)) + out, inside = [], False + for l in script.splitlines(): + if l.startswith('def fetch('): + if inside or out: + raise AssertionError('more than one def fetch') + inside = True + elif inside and l and not l[0].isspace(): + break + if inside: + out.append(l) + if not out: + raise AssertionError('def fetch not found') + return '\n'.join(out) + '\n' + + +FETCH_SOURCE = extract_fetch_source(WORKFLOW.read_text(encoding='utf-8')) + + +class _Response: + def __init__(self, data): + self._data = data + + def read(self, n=-1): + return self._data if n is None or n < 0 else self._data[:n] + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +class CatalogFetchControl(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name).resolve() / 'workspace' + self.root.mkdir() + self.requests = [] + self.served = {} + + def urlopen(url, timeout=None): + self.requests.append(url) + return _Response(self.served.get(url, PAYLOAD)) + + fake = types.SimpleNamespace(request=types.SimpleNamespace(urlopen=urlopen)) + ns = {'hashlib': hashlib, 'pathlib': pathlib, 're': re, 'urllib': fake, 'root': self.root} + exec(compile(FETCH_SOURCE, str(WORKFLOW) + ':fetch', 'exec'), ns) + self.fetch = ns['fetch'] + + def url(self, repo, commit, path): + return f'https://raw.githubusercontent.com/d6g8k5htny-coder/{repo}/{commit}/{path}' + + def written(self): + return sorted(str(p.relative_to(self.root)) for p in self.root.rglob('*') if p.is_file()) + + def assert_refused(self, message, args, fetched): + with self.assertRaises(ValueError) as cm: + self.fetch(*args) + self.assertEqual(str(cm.exception), message) + self.assertEqual(self.written(), [], 'a refused fetch must not write a payload') + if not fetched: + self.assertEqual(self.requests, [], 'a pre-fetch refusal must not open a URL') + + # positive ------------------------------------------------------------ + def test_approved_exact_source_is_fetched_and_written(self): + for repo in APPROVED: + with self.subTest(repo=repo): + self.requests.clear() + dest = self.fetch(repo, COMMIT, 'dir/a.txt', len(PAYLOAD), DIGEST) + self.assertEqual(dest, self.root / repo / 'dir/a.txt') + self.assertEqual(dest.read_bytes(), PAYLOAD) + self.assertEqual(self.requests, [self.url(repo, COMMIT, 'dir/a.txt')]) + + # C-ALLOW (L29) -------------------------------------------------------- + def test_unapproved_repository_is_refused(self): + for repo in ('sandbox', 'Sandbox', 'main', 'evil', 'Math-/../sandbox'): + with self.subTest(repo=repo): + self.assert_refused('unapproved source', + (repo, COMMIT, 'dir/a.txt', len(PAYLOAD), DIGEST), False) + + def test_non_exact_commit_is_refused(self): + for commit in ('main', 'abcdef1', '1' * 41, 'A' * 40, 'refs/' + '1' * 40, '1' * 40 + '\n'): + with self.subTest(commit=commit): + self.assert_refused('unapproved source', + ('Math-', commit, 'dir/a.txt', len(PAYLOAD), DIGEST), False) + + # C-PATH (L30-31) ------------------------------------------------------ + def test_unsafe_path_is_refused(self): + for path in ('/abs.txt', '../a.txt', 'dir/../a.txt', './a.txt', 'dir//a.txt', + 'dir\\a.txt', 'dir:a.txt', ''): + with self.subTest(path=path): + self.assert_refused('unsafe path', + ('Math-', COMMIT, path, len(PAYLOAD), DIGEST), False) + + # C-IDENT (L32) -------------------------------------------------------- + def test_invalid_declared_identity_is_refused(self): + for size, digest in ((True, DIGEST), (-1, DIGEST), (1000001, DIGEST), (6.0, DIGEST), + ('6', DIGEST), (6, DIGEST[:63]), (6, DIGEST + '0'), + (6, DIGEST.upper()), (6, 'x' + DIGEST[1:])): + with self.subTest(size=size, digest=digest): + self.assert_refused('invalid identity', + ('Math-', COMMIT, 'dir/a.txt', size, digest), False) + + # C-MATCH (L33-34) ----------------------------------------------------- + def test_served_bytes_must_match_declared_size_and_digest(self): + url = self.url('Math-', COMMIT, 'dir/a.txt') + for served in (b'ALPHA\n', PAYLOAD + b'EXTRA', PAYLOAD[:-1], b''): + with self.subTest(served=served): + self.requests.clear() + self.served[url] = served + self.assert_refused('source mismatch: Math-/dir/a.txt', + ('Math-', COMMIT, 'dir/a.txt', len(PAYLOAD), DIGEST), True) + self.assertEqual(self.requests, [url]) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_w8d_registry_row_identity_control.py b/tests/test_w8d_registry_row_identity_control.py new file mode 100644 index 0000000..1ce9073 --- /dev/null +++ b/tests/test_w8d_registry_row_identity_control.py @@ -0,0 +1,126 @@ +"""Proposed control (W8d, group A): registry artifact-row identity predicates in +meta-framework tools/architecture_conformance.py (L70-73, helper +_safe_registry_path L13-16, at 75685db7). + +The existing suite has one artifact fixture whose sha256 and bytes are valid, +whose path is not a sandbox/unsafe path, and whose commit is 'main'; it only +checks that some violation text contains a term. Here each predicate is +isolated: one field of one otherwise-valid row is changed, and the report must +contain EXACTLY that one violation. + +Positive: a valid public row -> ok True, no violations; CLI exit 0, empty +stderr, exact JSON stdout. +Negatives: violations == [': k']; CLI exit 2, empty stderr, +stdout exactly the JSON report. Offline: no network. Duplicate-member JSON +parsing, non-object roots, manifests, snapshots and the authority map are +out of scope (other owners). +""" +from __future__ import annotations + +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from tools.architecture_conformance import check_workspace + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / 'tools' / 'architecture_conformance.py' +REPOS = ['Math-', 'google-drive', 'governance-', 'main', 'meta-framework', 'query-', 'sandbox', 'trial'] + + +def valid_authority(): + return {'required_authority_ids': ['claims_firewall', 'scientific_state_architecture'], + 'authorities': {'claims_firewall': {'id': 'claims_firewall', 'owns': ['grade']}}, + 'this_package': {'id': 'scientific_state_architecture', 'owns': ['schema_contract'], + 'never_writes': ['status', 'grade', 'classification', 'controlling', + 'lemma_closed', 'prizes_solved', 'independence_credit']}} + + +def valid_row(**over): + row = {'key': 'k', 'repository': 'Math-', 'visibility': 'public', 'commit': '1' * 40, + 'path': 'frontiers/a.txt', 'sha256': 'a' * 64, 'bytes': 6, + 'scope': 'synthetic W8d control row, not acceptance'} + row.update(over) + return row + + +class RegistryRowIdentityControl(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + for name in REPOS: + (self.root / name).mkdir(parents=True) + a = self.root / 'main/architecture/scientific_state/v1' + a.mkdir(parents=True) + (a / 'AUTHORITY_MAP.json').write_text(json.dumps(valid_authority())) + + def write_registry(self, row): + registry = {'schema_version': 1, 'scientific_status_authority': False, + 'repositories': {n: {'full_name': 'd6g8k5htny-coder/' + n, 'role': n, + 'visibility': 'private' if n == 'sandbox' else 'public'} + for n in REPOS}, + 'artifacts': [row]} + (self.root / 'meta-framework/registry.json').write_text(json.dumps(registry)) + + def cli(self): + flags = ['-B', '-S'] + (['-O'] if sys.flags.optimize else []) + # C164-OPT-01: drop ambient PYTHONOPTIMIZE. One -O cannot express a + # parent level above 1, so pin that observed level after the pop. + env = dict(os.environ) + env.pop('PYTHONOPTIMIZE', None) + if sys.flags.optimize > 1: + env['PYTHONOPTIMIZE'] = str(sys.flags.optimize) + p = subprocess.run([sys.executable, *flags, str(SCRIPT), '--workspace', str(self.root)], + capture_output=True, text=True, timeout=20, env=env) + return p.returncode, p.stdout, p.stderr + + def expected(self, violations): + return {'ok': not violations, 'repositories_checked': sorted(REPOS), + 'violations': violations, 'scientific_effect': 'NONE'} + + def assert_report(self, row, violations): + self.write_registry(row) + exp = self.expected(violations) + self.assertEqual(check_workspace(self.root), exp) + code, out, err = self.cli() + self.assertEqual(err, '') + self.assertEqual(code, 0 if not violations else 2) + self.assertEqual(out, json.dumps(exp, indent=2, sort_keys=True) + '\n') + + # positive ------------------------------------------------------------ + def test_valid_public_row_is_accepted(self): + self.assert_report(valid_row(), []) + + # A-COMMIT (L70) ------------------------------------------------------ + def test_non_exact_commit_is_refused(self): + for bad in ('A' * 40, '1' * 40 + 'x', 'abc1234', 'main', ''): + with self.subTest(commit=bad): + self.assert_report(valid_row(commit=bad), ['artifact exact commit required: k']) + + # A-PATH (L71, L13-16) ------------------------------------------------ + def test_unsafe_or_sandbox_path_is_refused(self): + for bad in ('sandbox/x.txt', 'Sandbox/x.txt', 'a/SANDBOX/x.txt', '../x.txt', 'a/../x.txt', + 'a\\b.txt', 'a:b.txt', '/abs.txt', './a.txt', ''): + with self.subTest(path=bad): + self.assert_report(valid_row(path=bad), ['artifact unsafe/sandbox path: k']) + + # A-SHA (L72) --------------------------------------------------------- + def test_non_exact_sha256_is_refused(self): + for bad in ('A' * 64, 'a' * 63, 'a' * 64 + '0', 'not-a-hash', ''): + with self.subTest(sha256=bad): + self.assert_report(valid_row(sha256=bad), ['artifact exact sha256 required: k']) + + # A-BYTES (L73) ------------------------------------------------------- + def test_invalid_bytes_is_refused(self): + for bad in (True, -1, 6.0, '6', None): + with self.subTest(bytes=bad): + self.assert_report(valid_row(bytes=bad), ['artifact bytes invalid: k']) + + +if __name__ == '__main__': + unittest.main()