From 8b1fcda2597349bc7a3b2d9d37067ba240ada9c3 Mon Sep 17 00:00:00 2001 From: "MR.INDIA" Date: Fri, 27 Nov 2026 19:42:54 -0500 Subject: [PATCH 1/7] test(red): preauth-envelope r6 approved RED tests and fixtures (tests only) Byte-identical tree to 1e3788b8 (the contract's source_rev) minus the five unapproved draft contracts (r1-r5) that branch carries under .rizzstack/contracts. Lets the slice branch avoid contract-store changes in its own commits. --- contracts/preauth-wiring.requirements.json | 43 + policy/allowed_signers | 10 + scripts/preauth_verify.py | 55 + .../preauth/grokchat_r5/file_relative_read.py | 42 + .../preauth/grokchat_r5/lambda_json_hook.py | 40 + .../preauth/grokchat_r5/loop_many_reads.py | 40 + .../preauth/grokchat_r5/secret_read_print.py | 41 + .../preauth/must_fail/asyncio_subprocess.py | 26 + tests/fixtures/preauth/must_fail/chmod.py | 25 + .../preauth/must_fail/computed_argv.py | 21 + .../preauth/must_fail/cprofile_exec.py | 25 + .../fixtures/preauth/must_fail/ctypes_libc.py | 25 + .../preauth/must_fail/decorator_metaclass.py | 31 + .../preauth/must_fail/default_arg_run.py | 24 + tests/fixtures/preauth/must_fail/dict_run.py | 27 + .../preauth/must_fail/dunder_import.py | 24 + .../preauth/must_fail/env_computed.py | 21 + .../fixtures/preauth/must_fail/env_missing.py | 20 + tests/fixtures/preauth/must_fail/eval_exec.py | 25 + .../preauth/must_fail/executable_kw.py | 21 + .../fixtures/preauth/must_fail/extra_args.py | 21 + .../fixtures/preauth/must_fail/format_read.py | 24 + .../preauth/must_fail/frame_globals.py | 25 + .../preauth/must_fail/fstring_argv.py | 22 + .../preauth/must_fail/getattr_popen.py | 24 + .../fixtures/preauth/must_fail/help_pager.py | 24 + .../preauth/must_fail/import_alias.py | 20 + .../preauth/must_fail/imported_helper.py | 30 + .../preauth/must_fail/importlib_subprocess.py | 25 + .../fixtures/preauth/must_fail/joined_argv.py | 20 + .../preauth/must_fail/match_capture.py | 26 + .../preauth/must_fail/nested_import.py | 25 + .../fixtures/preauth/must_fail/no_timeout.py | 20 + tests/fixtures/preauth/must_fail/ntf_pth.py | 26 + .../preauth/must_fail/object_getattribute.py | 25 + .../preauth/must_fail/operator_attrgetter.py | 26 + tests/fixtures/preauth/must_fail/os_exec.py | 25 + .../preauth/must_fail/os_getattribute.py | 25 + .../preauth/must_fail/os_name_alias.py | 28 + tests/fixtures/preauth/must_fail/os_system.py | 25 + .../fixtures/preauth/must_fail/partial_run.py | 24 + .../fixtures/preauth/must_fail/path_hijack.py | 31 + .../fixtures/preauth/must_fail/popen_alias.py | 22 + .../preauth/must_fail/posixsubprocess.py | 22 + .../preauth/must_fail/private_module_attr.py | 24 + tests/fixtures/preauth/must_fail/putenv.py | 25 + .../preauth/must_fail/rebind_subprocess.py | 26 + .../preauth/must_fail/relative_ssh_keygen.py | 20 + tests/fixtures/preauth/must_fail/return_os.py | 29 + tests/fixtures/preauth/must_fail/run_alias.py | 25 + .../fixtures/preauth/must_fail/shell_true.py | 21 + .../preauth/must_fail/sign_concat_alias.py | 25 + .../preauth/must_fail/sign_literal.py | 22 + .../preauth/must_fail/split_string_sign.py | 27 + .../fixtures/preauth/must_fail/sys_modules.py | 25 + .../fixtures/preauth/must_fail/timeit_exec.py | 25 + tests/fixtures/preauth/must_fail/two_calls.py | 26 + .../preauth/must_fail/type_lambda_os.py | 28 + .../fixtures/preauth/must_fail/walrus_run.py | 24 + .../preauth/must_fail/webbrowser_browser.py | 27 + .../fixtures/preauth/must_fail/write_open.py | 25 + .../preauth/preauth_must_fail/append_open.py | 39 + .../preauth_must_fail/breakpoint_hook.py | 39 + .../preauth_must_fail/builtins_name.py | 39 + .../preauth/preauth_must_fail/class_base.py | 39 + .../preauth/preauth_must_fail/class_body.py | 39 + .../preauth_must_fail/class_decorator.py | 40 + .../preauth_must_fail/class_metaclass.py | 39 + .../preauth/preauth_must_fail/compile_code.py | 39 + .../preauth_must_fail/decorator_def.py | 40 + .../preauth_must_fail/default_arg_alias.py | 39 + .../preauth/preauth_must_fail/dict_alias.py | 42 + .../preauth/preauth_must_fail/dunder_attr.py | 39 + .../preauth/preauth_must_fail/dunder_def.py | 40 + .../preauth_must_fail/dunder_import.py | 39 + .../preauth/preauth_must_fail/eval_code.py | 39 + .../preauth/preauth_must_fail/exec_code.py | 39 + .../preauth/preauth_must_fail/format_leak.py | 39 + .../preauth_must_fail/format_map_leak.py | 39 + .../preauth/preauth_must_fail/frame_walk.py | 40 + .../preauth_must_fail/getattr_computed.py | 39 + .../preauth_must_fail/global_statement.py | 40 + .../preauth/preauth_must_fail/help_pager.py | 39 + .../import_datetime_module.py | 36 + .../preauth/preauth_must_fail/import_os.py | 40 + .../preauth_must_fail/import_subprocess.py | 40 + .../preauth_must_fail/json_decoder_chain.py | 39 + .../preauth_must_fail/match_capture.py | 41 + .../preauth/preauth_must_fail/module_alias.py | 40 + .../preauth_must_fail/module_attr_value.py | 38 + .../preauth_must_fail/nested_import.py | 40 + .../preauth/preauth_must_fail/ntf_pth.py | 41 + .../preauth_must_fail/open_computed_mode.py | 39 + .../preauth/preauth_must_fail/open_opener.py | 39 + .../preauth_must_fail/open_reference.py | 38 + .../preauth_must_fail/open_without_mode.py | 39 + .../preauth/preauth_must_fail/private_attr.py | 39 + .../preauth/preauth_must_fail/private_def.py | 39 + .../preauth_must_fail/re_enum_chain.py | 39 + .../preauth/preauth_must_fail/rebind_entry.py | 38 + .../rebind_in_comprehension.py | 38 + .../preauth_must_fail/rebind_module.py | 38 + .../preauth_must_fail/relative_import.py | 36 + .../preauth_must_fail/split_string_sign.py | 40 + .../preauth/preauth_must_fail/star_import.py | 36 + .../preauth/preauth_must_fail/three_opens.py | 39 + .../preauth_must_fail/type_three_arg.py | 38 + .../preauth_must_fail/verify_import_alias.py | 35 + .../preauth_must_fail/verify_import_extra.py | 35 + .../preauth_must_fail/verify_module_import.py | 36 + .../preauth/preauth_must_fail/walrus_alias.py | 39 + .../preauth/preauth_must_fail/write_open.py | 40 + .../preauth_must_fail_r6/direct_raise.py | 46 + .../preauth_must_fail_r6/dotdot_in_base.py | 42 + .../preauth_must_fail_r6/file_reference.py | 46 + .../file_relative_secret.py | 43 + .../helper_not_canonical.py | 42 + .../preauth_must_fail_r6/loop_many_reads.py | 51 + .../loop_over_constants.py | 48 + .../preauth_must_fail_r6/open_keyword_path.py | 47 + .../parameter_shadows_constant.py | 47 + .../preauth_must_fail_r6/print_hook.py | 46 + .../preauth_must_fail_r6/print_leak.py | 46 + .../proc_environ_constant.py | 50 + .../proc_environ_literal.py | 47 + .../preauth_must_fail_r6/raise_other.py | 46 + .../preauth_must_fail_r6/reason_fstring.py | 46 + .../reason_interpolated.py | 46 + .../preauth_must_fail_r6/reason_keyword.py | 46 + .../preauth_must_fail_r6/reason_unknown.py | 46 + .../preauth_must_fail_r6/reason_variable.py | 46 + .../preauth_must_fail_r6/rebind_constant.py | 45 + .../preauth_must_fail_r6/refusal_alias.py | 45 + .../preauth_must_fail_r6/refuse_reference.py | 45 + .../preauth_must_fail_r6/second_class.py | 46 + .../preauth_must_fail_r6/stderr_write.py | 46 + .../preauth_must_fail_r6/stdout_write.py | 46 + .../preauth_must_fail_r6/third_constant.py | 45 + .../preauth_must_fail_r6/write_attr.py | 46 + tests/fixtures/preauth/safe_preauth.py | 42 + tests/fixtures/preauth/safe_preauth_r5.py | 35 + tests/fixtures/preauth/safe_verify.py | 20 + .../wiring_must_fail/control_direct.py | 2 + .../preauth/wiring_must_fail/dotted_import.py | 2 + .../preauth/wiring_must_fail/dunder_import.py | 1 + .../preauth/wiring_must_fail/exec_code.py | 1 + .../wiring_must_fail/from_import_name.py | 1 + .../wiring_must_fail/from_pkg_alias.py | 2 + .../getattr_computed_elsewhere.py | 3 + .../getattr_constant_private.py | 2 + .../preauth/wiring_must_fail/getattr_name.py | 2 + .../wiring_must_fail/importlib_load.py | 5 + .../preauth/wiring_must_fail/module_rebind.py | 3 + .../preauth/wiring_must_fail/module_value.py | 2 + .../preauth/wiring_must_fail/private_name.py | 1 + .../wiring_must_fail/private_name_string.py | 1 + .../wiring_must_fail/private_via_getattr.py | 2 + .../preauth/wiring_must_fail/runpy_load.py | 2 + .../preauth/wiring_must_fail/shell_inline.sh | 2 + .../preauth/wiring_must_fail/star_import.py | 1 + .../preauth/wiring_must_fail/sys_modules.py | 2 + .../wiring_must_fail/verify_module_dotted.py | 1 + .../wiring_must_fail/verify_module_import.py | 1 + .../wiring_must_fail/workflow_inline.yml | 7 + tests/test_preauth_envelope.py | 2071 +++++++++++++++++ tests/test_preauth_policy.py | 92 + 166 files changed, 7123 insertions(+) create mode 100644 contracts/preauth-wiring.requirements.json create mode 100644 policy/allowed_signers create mode 100644 scripts/preauth_verify.py create mode 100644 tests/fixtures/preauth/grokchat_r5/file_relative_read.py create mode 100644 tests/fixtures/preauth/grokchat_r5/lambda_json_hook.py create mode 100644 tests/fixtures/preauth/grokchat_r5/loop_many_reads.py create mode 100644 tests/fixtures/preauth/grokchat_r5/secret_read_print.py create mode 100644 tests/fixtures/preauth/must_fail/asyncio_subprocess.py create mode 100644 tests/fixtures/preauth/must_fail/chmod.py create mode 100644 tests/fixtures/preauth/must_fail/computed_argv.py create mode 100644 tests/fixtures/preauth/must_fail/cprofile_exec.py create mode 100644 tests/fixtures/preauth/must_fail/ctypes_libc.py create mode 100644 tests/fixtures/preauth/must_fail/decorator_metaclass.py create mode 100644 tests/fixtures/preauth/must_fail/default_arg_run.py create mode 100644 tests/fixtures/preauth/must_fail/dict_run.py create mode 100644 tests/fixtures/preauth/must_fail/dunder_import.py create mode 100644 tests/fixtures/preauth/must_fail/env_computed.py create mode 100644 tests/fixtures/preauth/must_fail/env_missing.py create mode 100644 tests/fixtures/preauth/must_fail/eval_exec.py create mode 100644 tests/fixtures/preauth/must_fail/executable_kw.py create mode 100644 tests/fixtures/preauth/must_fail/extra_args.py create mode 100644 tests/fixtures/preauth/must_fail/format_read.py create mode 100644 tests/fixtures/preauth/must_fail/frame_globals.py create mode 100644 tests/fixtures/preauth/must_fail/fstring_argv.py create mode 100644 tests/fixtures/preauth/must_fail/getattr_popen.py create mode 100644 tests/fixtures/preauth/must_fail/help_pager.py create mode 100644 tests/fixtures/preauth/must_fail/import_alias.py create mode 100644 tests/fixtures/preauth/must_fail/imported_helper.py create mode 100644 tests/fixtures/preauth/must_fail/importlib_subprocess.py create mode 100644 tests/fixtures/preauth/must_fail/joined_argv.py create mode 100644 tests/fixtures/preauth/must_fail/match_capture.py create mode 100644 tests/fixtures/preauth/must_fail/nested_import.py create mode 100644 tests/fixtures/preauth/must_fail/no_timeout.py create mode 100644 tests/fixtures/preauth/must_fail/ntf_pth.py create mode 100644 tests/fixtures/preauth/must_fail/object_getattribute.py create mode 100644 tests/fixtures/preauth/must_fail/operator_attrgetter.py create mode 100644 tests/fixtures/preauth/must_fail/os_exec.py create mode 100644 tests/fixtures/preauth/must_fail/os_getattribute.py create mode 100644 tests/fixtures/preauth/must_fail/os_name_alias.py create mode 100644 tests/fixtures/preauth/must_fail/os_system.py create mode 100644 tests/fixtures/preauth/must_fail/partial_run.py create mode 100644 tests/fixtures/preauth/must_fail/path_hijack.py create mode 100644 tests/fixtures/preauth/must_fail/popen_alias.py create mode 100644 tests/fixtures/preauth/must_fail/posixsubprocess.py create mode 100644 tests/fixtures/preauth/must_fail/private_module_attr.py create mode 100644 tests/fixtures/preauth/must_fail/putenv.py create mode 100644 tests/fixtures/preauth/must_fail/rebind_subprocess.py create mode 100644 tests/fixtures/preauth/must_fail/relative_ssh_keygen.py create mode 100644 tests/fixtures/preauth/must_fail/return_os.py create mode 100644 tests/fixtures/preauth/must_fail/run_alias.py create mode 100644 tests/fixtures/preauth/must_fail/shell_true.py create mode 100644 tests/fixtures/preauth/must_fail/sign_concat_alias.py create mode 100644 tests/fixtures/preauth/must_fail/sign_literal.py create mode 100644 tests/fixtures/preauth/must_fail/split_string_sign.py create mode 100644 tests/fixtures/preauth/must_fail/sys_modules.py create mode 100644 tests/fixtures/preauth/must_fail/timeit_exec.py create mode 100644 tests/fixtures/preauth/must_fail/two_calls.py create mode 100644 tests/fixtures/preauth/must_fail/type_lambda_os.py create mode 100644 tests/fixtures/preauth/must_fail/walrus_run.py create mode 100644 tests/fixtures/preauth/must_fail/webbrowser_browser.py create mode 100644 tests/fixtures/preauth/must_fail/write_open.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/append_open.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/breakpoint_hook.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/builtins_name.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/class_base.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/class_body.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/class_decorator.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/class_metaclass.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/compile_code.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/decorator_def.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/default_arg_alias.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/dict_alias.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/dunder_attr.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/dunder_def.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/dunder_import.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/eval_code.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/exec_code.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/format_leak.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/format_map_leak.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/frame_walk.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/getattr_computed.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/global_statement.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/help_pager.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/import_datetime_module.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/import_os.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/import_subprocess.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/json_decoder_chain.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/match_capture.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/module_alias.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/module_attr_value.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/nested_import.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/ntf_pth.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/open_computed_mode.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/open_opener.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/open_reference.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/open_without_mode.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/private_attr.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/private_def.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/re_enum_chain.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/rebind_entry.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/rebind_in_comprehension.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/rebind_module.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/relative_import.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/split_string_sign.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/star_import.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/three_opens.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/type_three_arg.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/verify_import_alias.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/verify_import_extra.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/verify_module_import.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/walrus_alias.py create mode 100644 tests/fixtures/preauth/preauth_must_fail/write_open.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/direct_raise.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/dotdot_in_base.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/file_reference.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/file_relative_secret.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/helper_not_canonical.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/loop_many_reads.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/loop_over_constants.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/open_keyword_path.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/parameter_shadows_constant.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/print_hook.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/print_leak.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/proc_environ_constant.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/proc_environ_literal.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/raise_other.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/reason_fstring.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/reason_interpolated.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/reason_keyword.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/reason_unknown.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/reason_variable.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/rebind_constant.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/refusal_alias.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/refuse_reference.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/second_class.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/stderr_write.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/stdout_write.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/third_constant.py create mode 100644 tests/fixtures/preauth/preauth_must_fail_r6/write_attr.py create mode 100644 tests/fixtures/preauth/safe_preauth.py create mode 100644 tests/fixtures/preauth/safe_preauth_r5.py create mode 100644 tests/fixtures/preauth/safe_verify.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/control_direct.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/dotted_import.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/dunder_import.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/exec_code.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/from_import_name.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/from_pkg_alias.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/getattr_computed_elsewhere.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/getattr_constant_private.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/getattr_name.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/importlib_load.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/module_rebind.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/module_value.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/private_name.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/private_name_string.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/private_via_getattr.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/runpy_load.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/shell_inline.sh create mode 100644 tests/fixtures/preauth/wiring_must_fail/star_import.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/sys_modules.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/verify_module_dotted.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/verify_module_import.py create mode 100644 tests/fixtures/preauth/wiring_must_fail/workflow_inline.yml create mode 100644 tests/test_preauth_envelope.py create mode 100644 tests/test_preauth_policy.py diff --git a/contracts/preauth-wiring.requirements.json b/contracts/preauth-wiring.requirements.json new file mode 100644 index 0000000..4a93abd --- /dev/null +++ b/contracts/preauth-wiring.requirements.json @@ -0,0 +1,43 @@ +{ + "id": "preauth-wiring", + "status": "requirements draft (not a contract; not hashed; nothing approved)", + "recorded_with": "preauth-envelope r5 (RED commit on red/preauth-envelope); extended at r6", + "depends_on": [ + "gate-authority (S1)", + "preauth-envelope (S2)" + ], + "frozen_requirements": [ + "The gate (.github/scripts/lease_tamper.py), the lane (scripts/merge_lane_v5.py) and every other file under .github/ and scripts/ use only preauth.check() and catch only preauth.PreauthRefused. No other preauth name (oracle_paths, load_envelope, read_trust_root, constants, _decide, _check_for_tests), no import of scripts/preauth_verify.py or its _ssh_verify, and no reference to the module object other than .check / .PreauthRefused.", + "No dynamic loading anywhere under .github/ or scripts/: no importlib, runpy, imp, pkgutil or zipimport import; no __import__, eval, exec, compile, spec_from_file_location, SourceFileLoader, exec_module, load_module, run_path or run_module; no sys.modules access; no getattr/hasattr/setattr/delattr with a computed name; no getattr on the preauth module at all.", + "Non-Python files under .github/ and scripts/ (workflows, shell) never import preauth, name preauth_verify, _ssh_verify or check_for_tests, or reach a preauth attribute inline.", + "tests/test_preauth_envelope.py::WiringFreezeTest (all four tests, including the whole-tree scan, the 22 wiring must-fail fixtures and the dynamic trap that makes every preauth name except check and PreauthRefused raise on the lane and gate paths) stays unchanged as a regression suite.", + "The lane and gate load preauth from the BASE checkout's scripts/ directory placed first on sys.path, so `from preauth_verify import _ssh_verify` resolves to the frozen, sha256-pinned scripts/preauth_verify.py; add a call-site test that the loaded verifier's file is that path and its sha256 equals the pin (never a module from the PR head, cwd or another sys.path entry).", + "Add a call-site test that check() is the one preauth entry on the merge and dispatch paths, with every fact measured by the lane itself (revocations, consumed uses, nonces, attempts, bees in flight, ancestry), never a caller-supplied trust root or pin.", + "Must land before any unattended T1/T3 use of envelopes; until then every owner approval stays a typed line.", + "Exceptions: the lane and gate treat any exception from check() other than PreauthRefused as a refusal and never print, log or post its text or traceback (exception text can carry data); they report only PreauthRefused.reason, which is one of the closed REFUSAL_REASONS." + ], + "r6_additions_from_grokchat_round5_advisory_high_2": { + "requirement": "Extend wiring_violations (or add a wiring rule in this slice) so each case below is refused, and add these cases verbatim as wiring must-fail fixtures. GROKCHAT demonstrated that after any legitimate `from scripts import preauth`, each reaches a forbidden preauth name while passing the r5 rule.", + "rules": [ + "Flag any `.modules` attribute on any object (not only the literal `sys.modules`), so `import sys as s; s.modules[...]` is refused.", + "Flag any dotted chain through `scripts.preauth` (for example `import scripts; scripts.preauth.oracle_paths`); only `preauth.check` / `preauth.PreauthRefused` after a direct import stay allowed.", + "Flag `vars()` anywhere, and any `getattr`/`hasattr` whose target is not a plain local variable, including constant non-private names such as getattr(, \"oracle_paths\").", + "Flag `from scripts import *` (and any star import under .github/ and scripts/).", + "Drive the dynamic trap test through an envelope/T3 decision path on both the lane and the gate (a T3 merge that consults check() with measured facts), not only lane.decide on minimal facts and the gate on a docs-only change." + ], + "cases": { + "sys_alias_modules.py": "import sys as system_modules_view\npre = system_modules_view.modules[\"preauth\"]\npre.oracle_paths(\".\")\n", + "getattr_constant_public.py": "import sys as s\ngetattr(s.modules[\"preauth\"], \"oracle_paths\")(\".\")\n", + "package_attr_chain.py": "import scripts\nscripts.preauth.oracle_paths(\".\")\n", + "vars_package.py": "import scripts\nvars(scripts)[\"preauth\"].oracle_paths(\".\")\n", + "from_scripts_star_pkg.py": "from scripts import *\npreauth.oracle_paths(\".\")\n" + } + }, + "s1_gate_authority_advisories_recorded_here": { + "note": "From GROKCHAT round 5 on S1 (gate-authority f23d3ab3, approved-ready and unchanged). Recorded here so the wiring slice, which touches the same lane and gate files, picks them up; neither is in S1's frozen tests.", + "items": [ + "The live rulesets protect only the default branch, so release/* branches are unprotected (direct push or force-push by any writer), and S1's AC-029 lets the lane merge into such a branch judged by that branch's own gate copy. Either restrict the lane to the repository's default branch (refuse any other base), or have the owner add a ruleset protecting release/* (deletion, non_fast_forward, pull_request, required checks, no bypass) before the lane serves those bases.", + "In the stale-gate compare check, treat entries with status \"copied\" or \"changed\" like \"renamed\": check both filename and previous_filename against the gate-code paths (.github/workflows/gate-authority.yml, .github/workflows/review-rerun.yml, .github/scripts/**), with a test for each status (S1's test covers renamed only)." + ] + } +} diff --git a/policy/allowed_signers b/policy/allowed_signers new file mode 100644 index 0000000..6637e32 --- /dev/null +++ b/policy/allowed_signers @@ -0,0 +1,10 @@ +# rizzstack preauth trust root: public keys only, one per line. +# +# namespaces="rizzstack-preauth" +# +# Read-only for every implementer. Its bytes are pinned by tests/test_preauth_envelope.py, +# so adding a key needs a new owner-approved contract. No cert-authority lines, no wildcard +# or negated principals, one principal per line. The private key never leaves the owner's +# machine and is never on the Hermes host, the worker PC or the box. +# +# Empty on purpose: until the owner adds a key here, every envelope is refused. diff --git a/scripts/preauth_verify.py b/scripts/preauth_verify.py new file mode 100644 index 0000000..048b3b1 --- /dev/null +++ b/scripts/preauth_verify.py @@ -0,0 +1,55 @@ +"""Frozen ssh-keygen verifier for rizzstack pre-authorization envelopes (preauth-envelope r6). + +This file is frozen: its sha256 is pinned in the preauth-envelope contract and in +tests/test_preauth_envelope.py, so it changes only under a new owner-approved contract. + +It starts exactly one process, ``/usr/bin/ssh-keygen -Y verify``, by absolute path, with the +constant environment ``PATH=/usr/bin:/bin`` and a bounded timeout. The signature goes to a +private (0600, O_EXCL) temporary file with a constant suffix that is removed on return. It +never signs and holds no key. Defence in depth (r6): data and signature sizes are capped, and a +good result needs exit status 0 and exactly one stdout line starting +``Good "rizzstack-preauth" signature for with``. Every name it defines is private: +scripts/preauth.py imports ``_ssh_verify`` by name, and nothing else may use this module. +""" +import subprocess +import tempfile + +_NAMESPACE = "rizzstack-preauth" +_TIMEOUT_SECONDS = 20 +_MAX_DATA_BYTES = 65536 +_MAX_SIGNATURE_BYTES = 8192 +_PRINCIPAL_CHARS = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._@-") + + +def _plain_principal(value): + return (isinstance(value, str) and 0 < len(value) <= 64 and value[0] != "-" + and all(ch in _PRINCIPAL_CHARS for ch in value)) + + +def _plain_signers_path(value): + return (isinstance(value, str) and value.startswith("/") and "\n" not in value and "\0" not in value) + + +def _good_line(stdout, issuer): + expected = b'Good "' + _NAMESPACE.encode("ascii") + b'" signature for ' + issuer.encode("ascii") + b" with " + lines = stdout.splitlines() if isinstance(stdout, bytes) else [] + return len(lines) == 1 and lines[0].startswith(expected) + + +def _ssh_verify(data, signature, signers, issuer): + """True for a good signature by issuer under signers, False for a bad one, None if unavailable.""" + if not (isinstance(data, bytes) and isinstance(signature, bytes) and signature + and len(data) <= _MAX_DATA_BYTES and len(signature) <= _MAX_SIGNATURE_BYTES + and _plain_signers_path(signers) and _plain_principal(issuer)): + return False + with tempfile.NamedTemporaryFile(suffix=".sig") as handle: + handle.write(signature) + handle.flush() + sig_path = handle.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", signers, "-I", issuer, + "-n", _NAMESPACE, "-s", sig_path], input=data, capture_output=True, + timeout=_TIMEOUT_SECONDS, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return None + return proc.returncode == 0 and _good_line(proc.stdout, issuer) diff --git a/tests/fixtures/preauth/grokchat_r5/file_relative_read.py b/tests/fixtures/preauth/grokchat_r5/file_relative_read.py new file mode 100644 index 0000000..82d5f16 --- /dev/null +++ b/tests/fixtures/preauth/grokchat_r5/file_relative_read.py @@ -0,0 +1,42 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + + +def leak_reason(): + root = __file__.rsplit("/", 2)[0] + with open(root + "/../../.config/gh/hosts.yml", "r") as handle: + refuse("envelope_schema_invalid:" + handle.read()) diff --git a/tests/fixtures/preauth/grokchat_r5/lambda_json_hook.py b/tests/fixtures/preauth/grokchat_r5/lambda_json_hook.py new file mode 100644 index 0000000..7a7d121 --- /dev/null +++ b/tests/fixtures/preauth/grokchat_r5/lambda_json_hook.py @@ -0,0 +1,40 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + + +def parse(data): + return json.loads(data, object_hook=lambda d: d, parse_constant=print) diff --git a/tests/fixtures/preauth/grokchat_r5/loop_many_reads.py b/tests/fixtures/preauth/grokchat_r5/loop_many_reads.py new file mode 100644 index 0000000..1ac1a31 --- /dev/null +++ b/tests/fixtures/preauth/grokchat_r5/loop_many_reads.py @@ -0,0 +1,40 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + + +def sweep(paths): + return [read_trust_root(p) for p in paths] diff --git a/tests/fixtures/preauth/grokchat_r5/secret_read_print.py b/tests/fixtures/preauth/grokchat_r5/secret_read_print.py new file mode 100644 index 0000000..302a59b --- /dev/null +++ b/tests/fixtures/preauth/grokchat_r5/secret_read_print.py @@ -0,0 +1,41 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + + +def leak(): + with open("/proc/self/environ", "rb") as handle: + print(handle.read()) diff --git a/tests/fixtures/preauth/must_fail/asyncio_subprocess.py b/tests/fixtures/preauth/must_fail/asyncio_subprocess.py new file mode 100644 index 0000000..75be54b --- /dev/null +++ b/tests/fixtures/preauth/must_fail/asyncio_subprocess.py @@ -0,0 +1,26 @@ +"""Must-fail fixture for the one-process rule: asyncio subprocess.""" +import asyncio +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +async def helper(*argv): + return await asyncio.create_subprocess_exec(*argv) diff --git a/tests/fixtures/preauth/must_fail/chmod.py b/tests/fixtures/preauth/must_fail/chmod.py new file mode 100644 index 0000000..305a991 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/chmod.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule (r4): chmod.""" +import subprocess +import os +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def prep(p): + os.chmod(p, 0o755) diff --git a/tests/fixtures/preauth/must_fail/computed_argv.py b/tests/fixtures/preauth/must_fail/computed_argv.py new file mode 100644 index 0000000..37993f8 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/computed_argv.py @@ -0,0 +1,21 @@ +"""Must-fail fixture for the one-process rule: computed argv.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + argv = ["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig] + proc = subprocess.run(argv, input=data, capture_output=True, timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/cprofile_exec.py b/tests/fixtures/preauth/must_fail/cprofile_exec.py new file mode 100644 index 0000000..25b534c --- /dev/null +++ b/tests/fixtures/preauth/must_fail/cprofile_exec.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule (r4): cprofile exec.""" +import subprocess +import cProfile +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(code): + cProfile.run(code) diff --git a/tests/fixtures/preauth/must_fail/ctypes_libc.py b/tests/fixtures/preauth/must_fail/ctypes_libc.py new file mode 100644 index 0000000..c4331ee --- /dev/null +++ b/tests/fixtures/preauth/must_fail/ctypes_libc.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule: ctypes libc.""" +import os +import subprocess +import ctypes +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +LIBC = ctypes.CDLL(None) diff --git a/tests/fixtures/preauth/must_fail/decorator_metaclass.py b/tests/fixtures/preauth/must_fail/decorator_metaclass.py new file mode 100644 index 0000000..60f8a3e --- /dev/null +++ b/tests/fixtures/preauth/must_fail/decorator_metaclass.py @@ -0,0 +1,31 @@ +"""Must-pass control for the one-process rule: the only process is /usr/bin/ssh-keygen -Y verify.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +class Argv(type): + def __iter__(cls): + return iter(["/bin/sh", "-c", "touch /tmp/r4_decorator_pwned"]) + + +def attest(): + @subprocess.run + class X(metaclass=Argv): + pass diff --git a/tests/fixtures/preauth/must_fail/default_arg_run.py b/tests/fixtures/preauth/must_fail/default_arg_run.py new file mode 100644 index 0000000..eebb120 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/default_arg_run.py @@ -0,0 +1,24 @@ +"""Must-pass control for the one-process rule: the only process is /usr/bin/ssh-keygen -Y verify.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(cmd, go=subprocess.run): + return go(["/bin/sh", "-c", cmd]) diff --git a/tests/fixtures/preauth/must_fail/dict_run.py b/tests/fixtures/preauth/must_fail/dict_run.py new file mode 100644 index 0000000..90a521a --- /dev/null +++ b/tests/fixtures/preauth/must_fail/dict_run.py @@ -0,0 +1,27 @@ +"""Must-pass control for the one-process rule: the only process is /usr/bin/ssh-keygen -Y verify.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +TOOLS = {"r": subprocess.run} + + +def attest(cmd): + return TOOLS["r"](["/bin/sh", "-c", cmd]) diff --git a/tests/fixtures/preauth/must_fail/dunder_import.py b/tests/fixtures/preauth/must_fail/dunder_import.py new file mode 100644 index 0000000..042a25f --- /dev/null +++ b/tests/fixtures/preauth/must_fail/dunder_import.py @@ -0,0 +1,24 @@ +"""Must-fail fixture for the one-process rule: dunder import.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +SP = __import__("sub" + "process") diff --git a/tests/fixtures/preauth/must_fail/env_computed.py b/tests/fixtures/preauth/must_fail/env_computed.py new file mode 100644 index 0000000..34226bd --- /dev/null +++ b/tests/fixtures/preauth/must_fail/env_computed.py @@ -0,0 +1,21 @@ +"""Must-fail fixture for the one-process rule (r4): env computed.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 +TAIL = ":/tmp/pa-bin" + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin" + TAIL}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/env_missing.py b/tests/fixtures/preauth/must_fail/env_missing.py new file mode 100644 index 0000000..04a6b33 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/env_missing.py @@ -0,0 +1,20 @@ +"""Must-fail fixture for the one-process rule (r4): env missing.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/eval_exec.py b/tests/fixtures/preauth/must_fail/eval_exec.py new file mode 100644 index 0000000..d143a0e --- /dev/null +++ b/tests/fixtures/preauth/must_fail/eval_exec.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule: eval exec.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def helper(code): + return eval(code) diff --git a/tests/fixtures/preauth/must_fail/executable_kw.py b/tests/fixtures/preauth/must_fail/executable_kw.py new file mode 100644 index 0000000..d5cc990 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/executable_kw.py @@ -0,0 +1,21 @@ +"""Must-fail fixture for the one-process rule: executable kw.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, executable=allowed_signers) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/extra_args.py b/tests/fixtures/preauth/must_fail/extra_args.py new file mode 100644 index 0000000..e2c1718 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/extra_args.py @@ -0,0 +1,21 @@ +"""Must-fail fixture for the one-process rule: extra args.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig, "-Y", MODE], input=data, + capture_output=True, timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/format_read.py b/tests/fixtures/preauth/must_fail/format_read.py new file mode 100644 index 0000000..d9a00ba --- /dev/null +++ b/tests/fixtures/preauth/must_fail/format_read.py @@ -0,0 +1,24 @@ +"""Must-pass control for the one-process rule: the only process is /usr/bin/ssh-keygen -Y verify.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def leak(fn): + return "{0.__globals__[subprocess].os.environ}".format(fn) diff --git a/tests/fixtures/preauth/must_fail/frame_globals.py b/tests/fixtures/preauth/must_fail/frame_globals.py new file mode 100644 index 0000000..3c78601 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/frame_globals.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule (r4): frame globals.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(cmd): + frame = (x for x in ()).gi_frame + return frame.f_globals["sub" + "process"] diff --git a/tests/fixtures/preauth/must_fail/fstring_argv.py b/tests/fixtures/preauth/must_fail/fstring_argv.py new file mode 100644 index 0000000..e3c8044 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/fstring_argv.py @@ -0,0 +1,22 @@ +"""Must-fail fixture for the one-process rule: fstring argv.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + mode = "ver" + "ify" + proc = subprocess.run(["ssh-keygen", "-Y", f"{mode}", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/getattr_popen.py b/tests/fixtures/preauth/must_fail/getattr_popen.py new file mode 100644 index 0000000..ae09eb8 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/getattr_popen.py @@ -0,0 +1,24 @@ +"""Must-fail fixture for the one-process rule: getattr popen.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +OPEN = getattr(subprocess, "Po" + "pen") diff --git a/tests/fixtures/preauth/must_fail/help_pager.py b/tests/fixtures/preauth/must_fail/help_pager.py new file mode 100644 index 0000000..a6fec74 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/help_pager.py @@ -0,0 +1,24 @@ +"""Must-fail fixture for the one-process rule (r4): help pager.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(): + help("modules") diff --git a/tests/fixtures/preauth/must_fail/import_alias.py b/tests/fixtures/preauth/must_fail/import_alias.py new file mode 100644 index 0000000..08099b2 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/import_alias.py @@ -0,0 +1,20 @@ +"""Must-fail fixture for the one-process rule: import alias.""" +import os +import subprocess as sp +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = sp.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/imported_helper.py b/tests/fixtures/preauth/must_fail/imported_helper.py new file mode 100644 index 0000000..9f1f252 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/imported_helper.py @@ -0,0 +1,30 @@ +"""Must-fail fixture for the one-process rule (r4): imported helper.""" +import subprocess +import os +import sys +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +sys.path.insert(0, os.path.dirname(__file__)) +import merge_lane_v5 # noqa: E402 + + +def attest(key, path): + return merge_lane_v5._git(".", "-c", "alias.z=!ssh-keygen -Y si" + "gn -f " + key + " " + path, "z") diff --git a/tests/fixtures/preauth/must_fail/importlib_subprocess.py b/tests/fixtures/preauth/must_fail/importlib_subprocess.py new file mode 100644 index 0000000..e324e9d --- /dev/null +++ b/tests/fixtures/preauth/must_fail/importlib_subprocess.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule: importlib subprocess.""" +import os +import subprocess +import importlib +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +SP = importlib.import_module("sub" + "process") diff --git a/tests/fixtures/preauth/must_fail/joined_argv.py b/tests/fixtures/preauth/must_fail/joined_argv.py new file mode 100644 index 0000000..de0ec08 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/joined_argv.py @@ -0,0 +1,20 @@ +"""Must-fail fixture for the one-process rule: joined argv.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(" ".join(["ssh-keygen", "-Y", "verify", "-f", allowed_signers]), + input=data, capture_output=True, timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/match_capture.py b/tests/fixtures/preauth/must_fail/match_capture.py new file mode 100644 index 0000000..f855c44 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/match_capture.py @@ -0,0 +1,26 @@ +"""Must-pass control for the one-process rule: the only process is /usr/bin/ssh-keygen -Y verify.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(cmd): + match [subprocess.run]: + case [go]: + return go(["/bin/sh", "-c", cmd]) diff --git a/tests/fixtures/preauth/must_fail/nested_import.py b/tests/fixtures/preauth/must_fail/nested_import.py new file mode 100644 index 0000000..5a28f84 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/nested_import.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule (r4): nested import.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(cmd): + import os + return os.path.join(cmd) diff --git a/tests/fixtures/preauth/must_fail/no_timeout.py b/tests/fixtures/preauth/must_fail/no_timeout.py new file mode 100644 index 0000000..c6e7a39 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/no_timeout.py @@ -0,0 +1,20 @@ +"""Must-fail fixture for the one-process rule: no timeout.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/ntf_pth.py b/tests/fixtures/preauth/must_fail/ntf_pth.py new file mode 100644 index 0000000..e2c6578 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/ntf_pth.py @@ -0,0 +1,26 @@ +"""Must-pass control for the one-process rule: the only process is /usr/bin/ssh-keygen -Y verify.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def persist(site_dir): + fh = tempfile.NamedTemporaryFile(mode="w", dir=site_dir, prefix="zz", suffix=".pth", delete=False) + fh.write("import os; os.system('touch /tmp/r4_pth_pwned')\n") + fh.close() diff --git a/tests/fixtures/preauth/must_fail/object_getattribute.py b/tests/fixtures/preauth/must_fail/object_getattribute.py new file mode 100644 index 0000000..b290392 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/object_getattribute.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule (r4): object getattribute.""" +import subprocess +import os +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(cmd): + return object.__getattribute__(os, "sys" + "tem")(cmd) diff --git a/tests/fixtures/preauth/must_fail/operator_attrgetter.py b/tests/fixtures/preauth/must_fail/operator_attrgetter.py new file mode 100644 index 0000000..dbc7c8a --- /dev/null +++ b/tests/fixtures/preauth/must_fail/operator_attrgetter.py @@ -0,0 +1,26 @@ +"""Must-fail fixture for the one-process rule (r4): operator attrgetter.""" +import subprocess +import operator +import os +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(cmd): + return operator.attrgetter("sys" + "tem")(os)(cmd) diff --git a/tests/fixtures/preauth/must_fail/os_exec.py b/tests/fixtures/preauth/must_fail/os_exec.py new file mode 100644 index 0000000..b3667d3 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/os_exec.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule: os exec.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def helper(argv): + os.execvp(argv[0], argv) diff --git a/tests/fixtures/preauth/must_fail/os_getattribute.py b/tests/fixtures/preauth/must_fail/os_getattribute.py new file mode 100644 index 0000000..0ccb54c --- /dev/null +++ b/tests/fixtures/preauth/must_fail/os_getattribute.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule (r4): os getattribute.""" +import subprocess +import os +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(cmd): + return os.__getattribute__("sys" + "tem")(cmd) diff --git a/tests/fixtures/preauth/must_fail/os_name_alias.py b/tests/fixtures/preauth/must_fail/os_name_alias.py new file mode 100644 index 0000000..33c433c --- /dev/null +++ b/tests/fixtures/preauth/must_fail/os_name_alias.py @@ -0,0 +1,28 @@ +"""Must-fail fixture for the one-process rule (r4): os name alias.""" +import subprocess +import os +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +o = os + + +def attest(key, path): + return o.system("ssh-keygen -Y " + "si" "gn -f " + key + " " + path) diff --git a/tests/fixtures/preauth/must_fail/os_system.py b/tests/fixtures/preauth/must_fail/os_system.py new file mode 100644 index 0000000..44b5584 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/os_system.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule: os system.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def helper(cmd): + return os.system(cmd) diff --git a/tests/fixtures/preauth/must_fail/partial_run.py b/tests/fixtures/preauth/must_fail/partial_run.py new file mode 100644 index 0000000..d782d41 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/partial_run.py @@ -0,0 +1,24 @@ +"""Must-fail fixture for the one-process rule (r4): partial run.""" +import subprocess +import functools +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +r = functools.partial(subprocess.run) diff --git a/tests/fixtures/preauth/must_fail/path_hijack.py b/tests/fixtures/preauth/must_fail/path_hijack.py new file mode 100644 index 0000000..3098619 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/path_hijack.py @@ -0,0 +1,31 @@ +"""Must-fail fixture for the one-process rule (r4): path hijack.""" +import subprocess +import os +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def prep(): + d = "/tmp/pa-bin" + os.makedirs(d, exist_ok=True) + p = os.path.join(d, "ssh-keygen") + with open(p, "w") as fh: + fh.write("#!/bin/sh\necho Good signature; exit 0\n") + os.chmod(p, 0o755) + os.environ["PATH"] = d + os.pathsep + os.environ.get("PATH", "") diff --git a/tests/fixtures/preauth/must_fail/popen_alias.py b/tests/fixtures/preauth/must_fail/popen_alias.py new file mode 100644 index 0000000..ac0b3bc --- /dev/null +++ b/tests/fixtures/preauth/must_fail/popen_alias.py @@ -0,0 +1,22 @@ +"""Must-fail fixture for the one-process rule: popen alias.""" +import os +import subprocess +from subprocess import Popen +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = Popen(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig]) + proc.communicate(data, timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/posixsubprocess.py b/tests/fixtures/preauth/must_fail/posixsubprocess.py new file mode 100644 index 0000000..6dca0bf --- /dev/null +++ b/tests/fixtures/preauth/must_fail/posixsubprocess.py @@ -0,0 +1,22 @@ +"""Must-fail fixture for the one-process rule: posixsubprocess.""" +import os +import subprocess +import _posixsubprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/private_module_attr.py b/tests/fixtures/preauth/must_fail/private_module_attr.py new file mode 100644 index 0000000..868c0ce --- /dev/null +++ b/tests/fixtures/preauth/must_fail/private_module_attr.py @@ -0,0 +1,24 @@ +"""Must-fail fixture for the one-process rule (r4): private module attr.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(): + return tempfile._os diff --git a/tests/fixtures/preauth/must_fail/putenv.py b/tests/fixtures/preauth/must_fail/putenv.py new file mode 100644 index 0000000..8bd6ac4 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/putenv.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule (r4): putenv.""" +import subprocess +import os +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def prep(d): + os.putenv("PATH", d) diff --git a/tests/fixtures/preauth/must_fail/rebind_subprocess.py b/tests/fixtures/preauth/must_fail/rebind_subprocess.py new file mode 100644 index 0000000..f5ef873 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/rebind_subprocess.py @@ -0,0 +1,26 @@ +"""Must-fail fixture for the one-process rule (r4): rebind subprocess.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def install(fake): + global_name = fake + subprocess = global_name + return subprocess diff --git a/tests/fixtures/preauth/must_fail/relative_ssh_keygen.py b/tests/fixtures/preauth/must_fail/relative_ssh_keygen.py new file mode 100644 index 0000000..0ac25a7 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/relative_ssh_keygen.py @@ -0,0 +1,20 @@ +"""Must-fail fixture for the one-process rule (r4): relative ssh keygen.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/return_os.py b/tests/fixtures/preauth/must_fail/return_os.py new file mode 100644 index 0000000..b7ff5df --- /dev/null +++ b/tests/fixtures/preauth/must_fail/return_os.py @@ -0,0 +1,29 @@ +"""Must-fail fixture for the one-process rule (r4): return os.""" +import subprocess +import os +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def handle(): + return os + + +def attest(cmd): + return handle().popen(cmd) diff --git a/tests/fixtures/preauth/must_fail/run_alias.py b/tests/fixtures/preauth/must_fail/run_alias.py new file mode 100644 index 0000000..3d6cd20 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/run_alias.py @@ -0,0 +1,25 @@ +"""Must-pass control for the one-process rule: the only process is /usr/bin/ssh-keygen -Y verify.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(cmd): + go = subprocess.run + return go(["/bin/sh", "-c", cmd]) diff --git a/tests/fixtures/preauth/must_fail/shell_true.py b/tests/fixtures/preauth/must_fail/shell_true.py new file mode 100644 index 0000000..f908a96 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/shell_true.py @@ -0,0 +1,21 @@ +"""Must-fail fixture for the one-process rule: shell true.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, shell=True) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/sign_concat_alias.py b/tests/fixtures/preauth/must_fail/sign_concat_alias.py new file mode 100644 index 0000000..92a4214 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/sign_concat_alias.py @@ -0,0 +1,25 @@ +"""Must-pass control for the one-process rule: the only process is /usr/bin/ssh-keygen -Y verify.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(key, path): + go = subprocess.run + return go(["/usr/bin/ssh-keygen", "-Y", "si" + "gn", "-" + "f", key, "-n", NAMESPACE, path], timeout=TIMEOUT) diff --git a/tests/fixtures/preauth/must_fail/sign_literal.py b/tests/fixtures/preauth/must_fail/sign_literal.py new file mode 100644 index 0000000..2838ae3 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/sign_literal.py @@ -0,0 +1,22 @@ +"""Must-fail fixture for the one-process rule: sign literal.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +MODE = "sign" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/must_fail/split_string_sign.py b/tests/fixtures/preauth/must_fail/split_string_sign.py new file mode 100644 index 0000000..1a60d77 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/split_string_sign.py @@ -0,0 +1,27 @@ +"""Must-fail fixture for the one-process rule: split string sign.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(data, keyfile): + """Dead code: never exercised by the tests.""" + subprocess.run(["ssh-keygen", "-Y", "si" + "gn", "-f", keyfile, "-n", NAMESPACE, data], + capture_output=True, timeout=TIMEOUT) diff --git a/tests/fixtures/preauth/must_fail/sys_modules.py b/tests/fixtures/preauth/must_fail/sys_modules.py new file mode 100644 index 0000000..10bf30e --- /dev/null +++ b/tests/fixtures/preauth/must_fail/sys_modules.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule: sys modules.""" +import os +import sys +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +SP = sys.modules["sub" + "process"] diff --git a/tests/fixtures/preauth/must_fail/timeit_exec.py b/tests/fixtures/preauth/must_fail/timeit_exec.py new file mode 100644 index 0000000..6d59d92 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/timeit_exec.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule (r4): timeit exec.""" +import subprocess +import timeit +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(code): + timeit.timeit(code, number=1) diff --git a/tests/fixtures/preauth/must_fail/two_calls.py b/tests/fixtures/preauth/must_fail/two_calls.py new file mode 100644 index 0000000..8d6276a --- /dev/null +++ b/tests/fixtures/preauth/must_fail/two_calls.py @@ -0,0 +1,26 @@ +"""Must-fail fixture for the one-process rule: two calls.""" +import os +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.TemporaryDirectory() as tmp: + sig = os.path.join(tmp, "e.sig") + with open(sig, "wb") as fh: + fh.write(signature) + try: + proc = subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def again(data, signature, allowed_signers, issuer, sig): + return subprocess.run(["ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, timeout=TIMEOUT) diff --git a/tests/fixtures/preauth/must_fail/type_lambda_os.py b/tests/fixtures/preauth/must_fail/type_lambda_os.py new file mode 100644 index 0000000..6d991fd --- /dev/null +++ b/tests/fixtures/preauth/must_fail/type_lambda_os.py @@ -0,0 +1,28 @@ +"""Must-fail fixture for the one-process rule (r4): type lambda os.""" +import subprocess +import os +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +f = lambda: os + + +def attest(cmd): + return f().popen(cmd) diff --git a/tests/fixtures/preauth/must_fail/walrus_run.py b/tests/fixtures/preauth/must_fail/walrus_run.py new file mode 100644 index 0000000..36db276 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/walrus_run.py @@ -0,0 +1,24 @@ +"""Must-pass control for the one-process rule: the only process is /usr/bin/ssh-keygen -Y verify.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(cmd): + return (go := subprocess.run)(["/bin/sh", "-c", cmd]) diff --git a/tests/fixtures/preauth/must_fail/webbrowser_browser.py b/tests/fixtures/preauth/must_fail/webbrowser_browser.py new file mode 100644 index 0000000..56608d8 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/webbrowser_browser.py @@ -0,0 +1,27 @@ +"""Must-fail fixture for the one-process rule (r4): webbrowser browser.""" +import subprocess +import os +import webbrowser +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def attest(cmd): + os.environ["BROWSER"] = cmd + webbrowser.open("x") diff --git a/tests/fixtures/preauth/must_fail/write_open.py b/tests/fixtures/preauth/must_fail/write_open.py new file mode 100644 index 0000000..9150334 --- /dev/null +++ b/tests/fixtures/preauth/must_fail/write_open.py @@ -0,0 +1,25 @@ +"""Must-fail fixture for the one-process rule (r4): write open.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 + + +def prep(p): + with open(p, "w") as fh: + fh.write("#!/bin/sh\nexit 0\n") diff --git a/tests/fixtures/preauth/preauth_must_fail/append_open.py b/tests/fixtures/preauth/preauth_must_fail/append_open.py new file mode 100644 index 0000000..9bfa016 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/append_open.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(path): + return open(path, "ab") diff --git a/tests/fixtures/preauth/preauth_must_fail/breakpoint_hook.py b/tests/fixtures/preauth/preauth_must_fail/breakpoint_hook.py new file mode 100644 index 0000000..fcb327d --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/breakpoint_hook.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(): + breakpoint() diff --git a/tests/fixtures/preauth/preauth_must_fail/builtins_name.py b/tests/fixtures/preauth/preauth_must_fail/builtins_name.py new file mode 100644 index 0000000..d57426f --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/builtins_name.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(): + return __builtins__ diff --git a/tests/fixtures/preauth/preauth_must_fail/class_base.py b/tests/fixtures/preauth/preauth_must_fail/class_base.py new file mode 100644 index 0000000..595cbd0 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/class_base.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +class Shape(dict): + pass diff --git a/tests/fixtures/preauth/preauth_must_fail/class_body.py b/tests/fixtures/preauth/preauth_must_fail/class_body.py new file mode 100644 index 0000000..a698dd0 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/class_body.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +class Extra(Exception): + reason = "x" diff --git a/tests/fixtures/preauth/preauth_must_fail/class_decorator.py b/tests/fixtures/preauth/preauth_must_fail/class_decorator.py new file mode 100644 index 0000000..4f6ea1b --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/class_decorator.py @@ -0,0 +1,40 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +@refuse +class Extra(Exception): + pass diff --git a/tests/fixtures/preauth/preauth_must_fail/class_metaclass.py b/tests/fixtures/preauth/preauth_must_fail/class_metaclass.py new file mode 100644 index 0000000..8eab0c2 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/class_metaclass.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +class Argv(Exception, metaclass=PreauthRefused): + pass diff --git a/tests/fixtures/preauth/preauth_must_fail/compile_code.py b/tests/fixtures/preauth/preauth_must_fail/compile_code.py new file mode 100644 index 0000000..b7745a1 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/compile_code.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(text): + return compile(text, "x", "exec") diff --git a/tests/fixtures/preauth/preauth_must_fail/decorator_def.py b/tests/fixtures/preauth/preauth_must_fail/decorator_def.py new file mode 100644 index 0000000..1e0358b --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/decorator_def.py @@ -0,0 +1,40 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +@refuse +def bypass(): + pass diff --git a/tests/fixtures/preauth/preauth_must_fail/default_arg_alias.py b/tests/fixtures/preauth/preauth_must_fail/default_arg_alias.py new file mode 100644 index 0000000..42ed5cc --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/default_arg_alias.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(cmd, m=re): + return m.enum.sys.modules["subprocess"].run(cmd) diff --git a/tests/fixtures/preauth/preauth_must_fail/dict_alias.py b/tests/fixtures/preauth/preauth_must_fail/dict_alias.py new file mode 100644 index 0000000..e7c5730 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/dict_alias.py @@ -0,0 +1,42 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +TOOLS = {"r": re} + + +def bypass(cmd): + return TOOLS["r"].enum.sys.modules["subprocess"].run(cmd) diff --git a/tests/fixtures/preauth/preauth_must_fail/dunder_attr.py b/tests/fixtures/preauth/preauth_must_fail/dunder_attr.py new file mode 100644 index 0000000..7e1211f --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/dunder_attr.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(): + return refuse.__globals__ diff --git a/tests/fixtures/preauth/preauth_must_fail/dunder_def.py b/tests/fixtures/preauth/preauth_must_fail/dunder_def.py new file mode 100644 index 0000000..b22dec6 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/dunder_def.py @@ -0,0 +1,40 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +class Argv(Exception): + def __iter__(self): + return iter(["/bin/sh"]) diff --git a/tests/fixtures/preauth/preauth_must_fail/dunder_import.py b/tests/fixtures/preauth/preauth_must_fail/dunder_import.py new file mode 100644 index 0000000..47481df --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/dunder_import.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(): + return __import__("os") diff --git a/tests/fixtures/preauth/preauth_must_fail/eval_code.py b/tests/fixtures/preauth/preauth_must_fail/eval_code.py new file mode 100644 index 0000000..bcd358b --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/eval_code.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(text): + return eval(text) diff --git a/tests/fixtures/preauth/preauth_must_fail/exec_code.py b/tests/fixtures/preauth/preauth_must_fail/exec_code.py new file mode 100644 index 0000000..a5adb1e --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/exec_code.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(text): + exec(text) diff --git a/tests/fixtures/preauth/preauth_must_fail/format_leak.py b/tests/fixtures/preauth/preauth_must_fail/format_leak.py new file mode 100644 index 0000000..0c57ffd --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/format_leak.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(fn): + return "{0.__globals__}".format(fn) diff --git a/tests/fixtures/preauth/preauth_must_fail/format_map_leak.py b/tests/fixtures/preauth/preauth_must_fail/format_map_leak.py new file mode 100644 index 0000000..2ec751f --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/format_map_leak.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(fn): + return "{f.__globals__}".format_map({"f": fn}) diff --git a/tests/fixtures/preauth/preauth_must_fail/frame_walk.py b/tests/fixtures/preauth/preauth_must_fail/frame_walk.py new file mode 100644 index 0000000..de1bef7 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/frame_walk.py @@ -0,0 +1,40 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(): + gen = (x for x in ()) + return gen.gi_frame.f_globals diff --git a/tests/fixtures/preauth/preauth_must_fail/getattr_computed.py b/tests/fixtures/preauth/preauth_must_fail/getattr_computed.py new file mode 100644 index 0000000..845d398 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/getattr_computed.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(): + return getattr(json, "lo" + "ads") diff --git a/tests/fixtures/preauth/preauth_must_fail/global_statement.py b/tests/fixtures/preauth/preauth_must_fail/global_statement.py new file mode 100644 index 0000000..9b9abfa --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/global_statement.py @@ -0,0 +1,40 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(): + global PRINCIPAL + PRINCIPAL = None diff --git a/tests/fixtures/preauth/preauth_must_fail/help_pager.py b/tests/fixtures/preauth/preauth_must_fail/help_pager.py new file mode 100644 index 0000000..230f3fe --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/help_pager.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(): + help(json) diff --git a/tests/fixtures/preauth/preauth_must_fail/import_datetime_module.py b/tests/fixtures/preauth/preauth_must_fail/import_datetime_module.py new file mode 100644 index 0000000..4cd755f --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/import_datetime_module.py @@ -0,0 +1,36 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +import datetime +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/preauth_must_fail/import_os.py b/tests/fixtures/preauth/preauth_must_fail/import_os.py new file mode 100644 index 0000000..d5ba194 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/import_os.py @@ -0,0 +1,40 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +import os + + +def bypass(): + return os.getcwd() +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/preauth_must_fail/import_subprocess.py b/tests/fixtures/preauth/preauth_must_fail/import_subprocess.py new file mode 100644 index 0000000..2401cf5 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/import_subprocess.py @@ -0,0 +1,40 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +import subprocess + + +def bypass(cmd): + return subprocess.run(cmd) +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/preauth_must_fail/json_decoder_chain.py b/tests/fixtures/preauth/preauth_must_fail/json_decoder_chain.py new file mode 100644 index 0000000..b53a2a9 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/json_decoder_chain.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(): + return json.decoder.re diff --git a/tests/fixtures/preauth/preauth_must_fail/match_capture.py b/tests/fixtures/preauth/preauth_must_fail/match_capture.py new file mode 100644 index 0000000..9ecff17 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/match_capture.py @@ -0,0 +1,41 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(cmd): + match [cmd]: + case [c]: + return c diff --git a/tests/fixtures/preauth/preauth_must_fail/module_alias.py b/tests/fixtures/preauth/preauth_must_fail/module_alias.py new file mode 100644 index 0000000..d431aad --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/module_alias.py @@ -0,0 +1,40 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(cmd): + m = re + return m.enum.sys.modules["subprocess"].run(cmd) diff --git a/tests/fixtures/preauth/preauth_must_fail/module_attr_value.py b/tests/fixtures/preauth/preauth_must_fail/module_attr_value.py new file mode 100644 index 0000000..ff33456 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/module_attr_value.py @@ -0,0 +1,38 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +LOADS = json.loads diff --git a/tests/fixtures/preauth/preauth_must_fail/nested_import.py b/tests/fixtures/preauth/preauth_must_fail/nested_import.py new file mode 100644 index 0000000..4f35d4e --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/nested_import.py @@ -0,0 +1,40 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(): + import json + return json diff --git a/tests/fixtures/preauth/preauth_must_fail/ntf_pth.py b/tests/fixtures/preauth/preauth_must_fail/ntf_pth.py new file mode 100644 index 0000000..c7419e3 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/ntf_pth.py @@ -0,0 +1,41 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +import tempfile + + +def bypass(site_dir): + fh = tempfile.NamedTemporaryFile(mode="w", dir=site_dir, suffix=".pth", delete=False) + fh.write("import os; os.system('true')\n") +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/preauth_must_fail/open_computed_mode.py b/tests/fixtures/preauth/preauth_must_fail/open_computed_mode.py new file mode 100644 index 0000000..feba209 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/open_computed_mode.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(path, mode): + return open(path, mode) diff --git a/tests/fixtures/preauth/preauth_must_fail/open_opener.py b/tests/fixtures/preauth/preauth_must_fail/open_opener.py new file mode 100644 index 0000000..7916b0f --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/open_opener.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(path, fn): + return open(path, "rb", opener=fn) diff --git a/tests/fixtures/preauth/preauth_must_fail/open_reference.py b/tests/fixtures/preauth/preauth_must_fail/open_reference.py new file mode 100644 index 0000000..610aa85 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/open_reference.py @@ -0,0 +1,38 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +READER = open diff --git a/tests/fixtures/preauth/preauth_must_fail/open_without_mode.py b/tests/fixtures/preauth/preauth_must_fail/open_without_mode.py new file mode 100644 index 0000000..c007493 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/open_without_mode.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(path): + return open(path) diff --git a/tests/fixtures/preauth/preauth_must_fail/private_attr.py b/tests/fixtures/preauth/preauth_must_fail/private_attr.py new file mode 100644 index 0000000..1202c03 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/private_attr.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(obj): + return obj._private diff --git a/tests/fixtures/preauth/preauth_must_fail/private_def.py b/tests/fixtures/preauth/preauth_must_fail/private_def.py new file mode 100644 index 0000000..61dbec8 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/private_def.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def _helper(): + return 1 diff --git a/tests/fixtures/preauth/preauth_must_fail/re_enum_chain.py b/tests/fixtures/preauth/preauth_must_fail/re_enum_chain.py new file mode 100644 index 0000000..7b124e2 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/re_enum_chain.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(): + return re.enum.sys diff --git a/tests/fixtures/preauth/preauth_must_fail/rebind_entry.py b/tests/fixtures/preauth/preauth_must_fail/rebind_entry.py new file mode 100644 index 0000000..1f85cf7 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/rebind_entry.py @@ -0,0 +1,38 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +_ssh_verify = verified diff --git a/tests/fixtures/preauth/preauth_must_fail/rebind_in_comprehension.py b/tests/fixtures/preauth/preauth_must_fail/rebind_in_comprehension.py new file mode 100644 index 0000000..189cd3f --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/rebind_in_comprehension.py @@ -0,0 +1,38 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +NAMES = [re for re in (1, 2)] diff --git a/tests/fixtures/preauth/preauth_must_fail/rebind_module.py b/tests/fixtures/preauth/preauth_must_fail/rebind_module.py new file mode 100644 index 0000000..14e12aa --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/rebind_module.py @@ -0,0 +1,38 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +json = None diff --git a/tests/fixtures/preauth/preauth_must_fail/relative_import.py b/tests/fixtures/preauth/preauth_must_fail/relative_import.py new file mode 100644 index 0000000..bc01e4d --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/relative_import.py @@ -0,0 +1,36 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from . import preauth_verify +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/preauth_must_fail/split_string_sign.py b/tests/fixtures/preauth/preauth_must_fail/split_string_sign.py new file mode 100644 index 0000000..d222488 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/split_string_sign.py @@ -0,0 +1,40 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(key, path): + run = re.enum.sys.modules["subprocess"].run + return run(["/usr/bin/ssh-keygen", "-Y", "si" + "gn", "-" + "f", key, path]) diff --git a/tests/fixtures/preauth/preauth_must_fail/star_import.py b/tests/fixtures/preauth/preauth_must_fail/star_import.py new file mode 100644 index 0000000..c3f63df --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/star_import.py @@ -0,0 +1,36 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from json import * +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/preauth_must_fail/three_opens.py b/tests/fixtures/preauth/preauth_must_fail/three_opens.py new file mode 100644 index 0000000..d73e80a --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/three_opens.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(a, b): + return open(a, "rb").read() + open(b, "rb").read() diff --git a/tests/fixtures/preauth/preauth_must_fail/type_three_arg.py b/tests/fixtures/preauth/preauth_must_fail/type_three_arg.py new file mode 100644 index 0000000..da74795 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/type_three_arg.py @@ -0,0 +1,38 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +X = type("X", (), {}) diff --git a/tests/fixtures/preauth/preauth_must_fail/verify_import_alias.py b/tests/fixtures/preauth/preauth_must_fail/verify_import_alias.py new file mode 100644 index 0000000..68e5a07 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/verify_import_alias.py @@ -0,0 +1,35 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify as yes + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/preauth_must_fail/verify_import_extra.py b/tests/fixtures/preauth/preauth_must_fail/verify_import_extra.py new file mode 100644 index 0000000..1fa60c8 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/verify_import_extra.py @@ -0,0 +1,35 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify, _NAMESPACE + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/preauth_must_fail/verify_module_import.py b/tests/fixtures/preauth/preauth_must_fail/verify_module_import.py new file mode 100644 index 0000000..8e458a5 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/verify_module_import.py @@ -0,0 +1,36 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +import preauth_verify +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/preauth_must_fail/walrus_alias.py b/tests/fixtures/preauth/preauth_must_fail/walrus_alias.py new file mode 100644 index 0000000..b161d3a --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/walrus_alias.py @@ -0,0 +1,39 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(cmd): + return (m := re).enum.sys.modules["subprocess"].run(cmd) diff --git a/tests/fixtures/preauth/preauth_must_fail/write_open.py b/tests/fixtures/preauth/preauth_must_fail/write_open.py new file mode 100644 index 0000000..6b47f2b --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail/write_open.py @@ -0,0 +1,40 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def bypass(path): + with open(path, "w") as handle: + handle.write("x") diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/direct_raise.py b/tests/fixtures/preauth/preauth_must_fail_r6/direct_raise.py new file mode 100644 index 0000000..8aed345 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/direct_raise.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def leak(): + raise PreauthRefused("envelope_expired") diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/dotdot_in_base.py b/tests/fixtures/preauth/preauth_must_fail_r6/dotdot_in_base.py new file mode 100644 index 0000000..88d34a2 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/dotdot_in_base.py @@ -0,0 +1,42 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/..", 1)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/file_reference.py b/tests/fixtures/preauth/preauth_must_fail_r6/file_reference.py new file mode 100644 index 0000000..2845145 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/file_reference.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def where(): + return __file__ diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/file_relative_secret.py b/tests/fixtures/preauth/preauth_must_fail_r6/file_relative_secret.py new file mode 100644 index 0000000..0c7d01d --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/file_relative_secret.py @@ -0,0 +1,43 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +SECRET = __file__.rsplit("/", 2)[0] + "/../../.config/gh/hosts.yml" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(SECRET, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/helper_not_canonical.py b/tests/fixtures/preauth/preauth_must_fail_r6/helper_not_canonical.py new file mode 100644 index 0000000..6b5bd0b --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/helper_not_canonical.py @@ -0,0 +1,42 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + read_policy().decode() + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/loop_many_reads.py b/tests/fixtures/preauth/preauth_must_fail_r6/loop_many_reads.py new file mode 100644 index 0000000..47f22d6 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/loop_many_reads.py @@ -0,0 +1,51 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def read(path): + with open(path, "rb") as handle: + return handle.read() + + +def sweep(paths): + return [read(p) for p in paths] diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/loop_over_constants.py b/tests/fixtures/preauth/preauth_must_fail_r6/loop_over_constants.py new file mode 100644 index 0000000..5cdcb5a --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/loop_over_constants.py @@ -0,0 +1,48 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def sweep(): + for path in (TRUST_ROOT, POLICY): + with open(path, "rb") as handle: + yield handle.read() diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/open_keyword_path.py b/tests/fixtures/preauth/preauth_must_fail_r6/open_keyword_path.py new file mode 100644 index 0000000..6573204 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/open_keyword_path.py @@ -0,0 +1,47 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def read(): + with open(file=TRUST_ROOT, mode="rb") as handle: + return handle.read() diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/parameter_shadows_constant.py b/tests/fixtures/preauth/preauth_must_fail_r6/parameter_shadows_constant.py new file mode 100644 index 0000000..3f8577b --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/parameter_shadows_constant.py @@ -0,0 +1,47 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def read(TRUST_ROOT): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/print_hook.py b/tests/fixtures/preauth/preauth_must_fail_r6/print_hook.py new file mode 100644 index 0000000..db9053b --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/print_hook.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def parse(data): + return json.loads(data, parse_constant=print) diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/print_leak.py b/tests/fixtures/preauth/preauth_must_fail_r6/print_leak.py new file mode 100644 index 0000000..c9b8e38 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/print_leak.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def leak(): + print(read_policy()) diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/proc_environ_constant.py b/tests/fixtures/preauth/preauth_must_fail_r6/proc_environ_constant.py new file mode 100644 index 0000000..9aadf6f --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/proc_environ_constant.py @@ -0,0 +1,50 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +ENVIRON = "/proc/self/environ" + + +def leak(): + with open(ENVIRON, "rb") as handle: + return handle.read() diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/proc_environ_literal.py b/tests/fixtures/preauth/preauth_must_fail_r6/proc_environ_literal.py new file mode 100644 index 0000000..325dbf5 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/proc_environ_literal.py @@ -0,0 +1,47 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def leak(): + with open("/proc/self/environ", "rb") as handle: + return handle.read() diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/raise_other.py b/tests/fixtures/preauth/preauth_must_fail_r6/raise_other.py new file mode 100644 index 0000000..cb5566f --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/raise_other.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def leak(): + raise ValueError(read_policy()) diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/reason_fstring.py b/tests/fixtures/preauth/preauth_must_fail_r6/reason_fstring.py new file mode 100644 index 0000000..8b8e3f2 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/reason_fstring.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def leak(): + refuse(f"envelope_schema_invalid:{read_trust_root()}") diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/reason_interpolated.py b/tests/fixtures/preauth/preauth_must_fail_r6/reason_interpolated.py new file mode 100644 index 0000000..0d2d8f7 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/reason_interpolated.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def leak(): + refuse("envelope_schema_invalid:" + read_policy().decode()) diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/reason_keyword.py b/tests/fixtures/preauth/preauth_must_fail_r6/reason_keyword.py new file mode 100644 index 0000000..1d46172 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/reason_keyword.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def leak(): + refuse(reason="envelope_expired") diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/reason_unknown.py b/tests/fixtures/preauth/preauth_must_fail_r6/reason_unknown.py new file mode 100644 index 0000000..146d42c --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/reason_unknown.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def leak(): + refuse("envelope_something_else") diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/reason_variable.py b/tests/fixtures/preauth/preauth_must_fail_r6/reason_variable.py new file mode 100644 index 0000000..82d8957 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/reason_variable.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def leak(why): + refuse(why) diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/rebind_constant.py b/tests/fixtures/preauth/preauth_must_fail_r6/rebind_constant.py new file mode 100644 index 0000000..1a77216 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/rebind_constant.py @@ -0,0 +1,45 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +TRUST_ROOT = "/proc/self/environ" diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/refusal_alias.py b/tests/fixtures/preauth/preauth_must_fail_r6/refusal_alias.py new file mode 100644 index 0000000..4ba5f34 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/refusal_alias.py @@ -0,0 +1,45 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +REFUSAL = PreauthRefused diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/refuse_reference.py b/tests/fixtures/preauth/preauth_must_fail_r6/refuse_reference.py new file mode 100644 index 0000000..bad1e05 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/refuse_reference.py @@ -0,0 +1,45 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +HANDLER = refuse diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/second_class.py b/tests/fixtures/preauth/preauth_must_fail_r6/second_class.py new file mode 100644 index 0000000..45b4896 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/second_class.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +class Leak(Exception): + """Carries file contents.""" diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/stderr_write.py b/tests/fixtures/preauth/preauth_must_fail_r6/stderr_write.py new file mode 100644 index 0000000..888f69f --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/stderr_write.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def leak(stream, text): + stream.stderr.write(text) diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/stdout_write.py b/tests/fixtures/preauth/preauth_must_fail_r6/stdout_write.py new file mode 100644 index 0000000..d2d9b68 --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/stdout_write.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def leak(stream, text): + stream.stdout.write(text) diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/third_constant.py b/tests/fixtures/preauth/preauth_must_fail_r6/third_constant.py new file mode 100644 index 0000000..e02018b --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/third_constant.py @@ -0,0 +1,45 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +EXTRA = __file__.rsplit("/", 3)[0] + "/policy/allowed_signers" diff --git a/tests/fixtures/preauth/preauth_must_fail_r6/write_attr.py b/tests/fixtures/preauth/preauth_must_fail_r6/write_attr.py new file mode 100644 index 0000000..4e8597c --- /dev/null +++ b/tests/fixtures/preauth/preauth_must_fail_r6/write_attr.py @@ -0,0 +1,46 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) + + +def leak(handle, text): + handle.write(text) diff --git a/tests/fixtures/preauth/safe_preauth.py b/tests/fixtures/preauth/safe_preauth.py new file mode 100644 index 0000000..0967b24 --- /dev/null +++ b/tests/fixtures/preauth/safe_preauth.py @@ -0,0 +1,42 @@ +"""Must-pass control for the preauth.py rule (r6): parsing and policy only; reads only its two pinned files.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + + +def read_policy(): + with open(POLICY, "rb") as handle: + return handle.read() + + +def verified(data, signature, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, TRUST_ROOT, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/safe_preauth_r5.py b/tests/fixtures/preauth/safe_preauth_r5.py new file mode 100644 index 0000000..ae0e054 --- /dev/null +++ b/tests/fixtures/preauth/safe_preauth_r5.py @@ -0,0 +1,35 @@ +"""Must-pass control for the preauth.py rule: parsing and policy only, no process or write access.""" +from __future__ import annotations + +import json +import re + +from preauth_verify import _ssh_verify + +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(path): + with open(path, "rb") as handle: + return handle.read() + + +def verified(data, signature, signers, issuer): + if not PRINCIPAL.fullmatch(issuer): + refuse("envelope_schema_invalid") + result = _ssh_verify(data, signature, signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + return json.loads(data) diff --git a/tests/fixtures/preauth/safe_verify.py b/tests/fixtures/preauth/safe_verify.py new file mode 100644 index 0000000..a070c6e --- /dev/null +++ b/tests/fixtures/preauth/safe_verify.py @@ -0,0 +1,20 @@ +"""Must-pass control for the one-process rule: the only process is /usr/bin/ssh-keygen -Y verify.""" +import subprocess +import tempfile + +NAMESPACE = "rizzstack-preauth" +TIMEOUT = 30 + + +def verify(data, signature, allowed_signers, issuer): + with tempfile.NamedTemporaryFile(suffix=".sig") as fh: + fh.write(signature) + fh.flush() + sig = fh.name + try: + proc = subprocess.run(["/usr/bin/ssh-keygen", "-Y", "verify", "-f", allowed_signers, "-I", issuer, + "-n", NAMESPACE, "-s", sig], input=data, capture_output=True, + timeout=TIMEOUT, env={"PATH": "/usr/bin:/bin"}) + except (OSError, subprocess.SubprocessError): + return False + return proc.returncode == 0 diff --git a/tests/fixtures/preauth/wiring_must_fail/control_direct.py b/tests/fixtures/preauth/wiring_must_fail/control_direct.py new file mode 100644 index 0000000..6fe6350 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/control_direct.py @@ -0,0 +1,2 @@ +import preauth +preauth.verify_signature(p) diff --git a/tests/fixtures/preauth/wiring_must_fail/dotted_import.py b/tests/fixtures/preauth/wiring_must_fail/dotted_import.py new file mode 100644 index 0000000..a53f84c --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/dotted_import.py @@ -0,0 +1,2 @@ +import scripts.preauth +scripts.preauth.oracle_paths([], test_files=[]) diff --git a/tests/fixtures/preauth/wiring_must_fail/dunder_import.py b/tests/fixtures/preauth/wiring_must_fail/dunder_import.py new file mode 100644 index 0000000..b18a482 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/dunder_import.py @@ -0,0 +1 @@ +mod = __import__('pre' + 'auth') diff --git a/tests/fixtures/preauth/wiring_must_fail/exec_code.py b/tests/fixtures/preauth/wiring_must_fail/exec_code.py new file mode 100644 index 0000000..08f5b2b --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/exec_code.py @@ -0,0 +1 @@ +exec(open('scripts/preauth.py').read()) diff --git a/tests/fixtures/preauth/wiring_must_fail/from_import_name.py b/tests/fixtures/preauth/wiring_must_fail/from_import_name.py new file mode 100644 index 0000000..c3b9374 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/from_import_name.py @@ -0,0 +1 @@ +from scripts.preauth import check, oracle_paths diff --git a/tests/fixtures/preauth/wiring_must_fail/from_pkg_alias.py b/tests/fixtures/preauth/wiring_must_fail/from_pkg_alias.py new file mode 100644 index 0000000..307cbc1 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/from_pkg_alias.py @@ -0,0 +1,2 @@ +from scripts import preauth as pa +pa.verify_signature(p) diff --git a/tests/fixtures/preauth/wiring_must_fail/getattr_computed_elsewhere.py b/tests/fixtures/preauth/wiring_must_fail/getattr_computed_elsewhere.py new file mode 100644 index 0000000..27d4b2a --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/getattr_computed_elsewhere.py @@ -0,0 +1,3 @@ +import json +name = 'lo' + 'ads' +getattr(json, name) diff --git a/tests/fixtures/preauth/wiring_must_fail/getattr_constant_private.py b/tests/fixtures/preauth/wiring_must_fail/getattr_constant_private.py new file mode 100644 index 0000000..2b8dce0 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/getattr_constant_private.py @@ -0,0 +1,2 @@ +import preauth +getattr(preauth, 'oracle_paths') diff --git a/tests/fixtures/preauth/wiring_must_fail/getattr_name.py b/tests/fixtures/preauth/wiring_must_fail/getattr_name.py new file mode 100644 index 0000000..1be0ac9 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/getattr_name.py @@ -0,0 +1,2 @@ +import preauth +getattr(preauth, 'verify_' + 'signature')(p) diff --git a/tests/fixtures/preauth/wiring_must_fail/importlib_load.py b/tests/fixtures/preauth/wiring_must_fail/importlib_load.py new file mode 100644 index 0000000..b2bd041 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/importlib_load.py @@ -0,0 +1,5 @@ +import importlib.util +s = importlib.util.spec_from_file_location('pa', 'scripts/preauth.py') +pa = importlib.util.module_from_spec(s) +s.loader.exec_module(pa) +pa.verify_signature(p) diff --git a/tests/fixtures/preauth/wiring_must_fail/module_rebind.py b/tests/fixtures/preauth/wiring_must_fail/module_rebind.py new file mode 100644 index 0000000..fbb2322 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/module_rebind.py @@ -0,0 +1,3 @@ +import preauth +pa = preauth +pa.check diff --git a/tests/fixtures/preauth/wiring_must_fail/module_value.py b/tests/fixtures/preauth/wiring_must_fail/module_value.py new file mode 100644 index 0000000..52e3a71 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/module_value.py @@ -0,0 +1,2 @@ +import preauth +helper(preauth) diff --git a/tests/fixtures/preauth/wiring_must_fail/private_name.py b/tests/fixtures/preauth/wiring_must_fail/private_name.py new file mode 100644 index 0000000..3854686 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/private_name.py @@ -0,0 +1 @@ +_ssh_verify(b'', b'', '/x', 'kyle') diff --git a/tests/fixtures/preauth/wiring_must_fail/private_name_string.py b/tests/fixtures/preauth/wiring_must_fail/private_name_string.py new file mode 100644 index 0000000..9bfb719 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/private_name_string.py @@ -0,0 +1 @@ +name = '_check_for_tests' diff --git a/tests/fixtures/preauth/wiring_must_fail/private_via_getattr.py b/tests/fixtures/preauth/wiring_must_fail/private_via_getattr.py new file mode 100644 index 0000000..6ed2986 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/private_via_getattr.py @@ -0,0 +1,2 @@ +import preauth +getattr(preauth, '_check_for' + '_tests')(d) diff --git a/tests/fixtures/preauth/wiring_must_fail/runpy_load.py b/tests/fixtures/preauth/wiring_must_fail/runpy_load.py new file mode 100644 index 0000000..7ce5aee --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/runpy_load.py @@ -0,0 +1,2 @@ +import runpy +ns = runpy.run_path('scripts/pre' + 'auth.py') diff --git a/tests/fixtures/preauth/wiring_must_fail/shell_inline.sh b/tests/fixtures/preauth/wiring_must_fail/shell_inline.sh new file mode 100644 index 0000000..25be1e8 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/shell_inline.sh @@ -0,0 +1,2 @@ +#!/bin/sh +python3 -c 'from scripts.preauth import oracle_paths' diff --git a/tests/fixtures/preauth/wiring_must_fail/star_import.py b/tests/fixtures/preauth/wiring_must_fail/star_import.py new file mode 100644 index 0000000..3d54d84 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/star_import.py @@ -0,0 +1 @@ +from preauth import * diff --git a/tests/fixtures/preauth/wiring_must_fail/sys_modules.py b/tests/fixtures/preauth/wiring_must_fail/sys_modules.py new file mode 100644 index 0000000..b15db68 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/sys_modules.py @@ -0,0 +1,2 @@ +import sys +sys.modules['preauth'].oracle_paths diff --git a/tests/fixtures/preauth/wiring_must_fail/verify_module_dotted.py b/tests/fixtures/preauth/wiring_must_fail/verify_module_dotted.py new file mode 100644 index 0000000..53aa080 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/verify_module_dotted.py @@ -0,0 +1 @@ +import scripts.preauth_verify diff --git a/tests/fixtures/preauth/wiring_must_fail/verify_module_import.py b/tests/fixtures/preauth/wiring_must_fail/verify_module_import.py new file mode 100644 index 0000000..056a1c9 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/verify_module_import.py @@ -0,0 +1 @@ +from preauth_verify import _ssh_verify diff --git a/tests/fixtures/preauth/wiring_must_fail/workflow_inline.yml b/tests/fixtures/preauth/wiring_must_fail/workflow_inline.yml new file mode 100644 index 0000000..8c00565 --- /dev/null +++ b/tests/fixtures/preauth/wiring_must_fail/workflow_inline.yml @@ -0,0 +1,7 @@ +name: x +on: push +jobs: + x: + runs-on: ubuntu-latest + steps: + - run: python3 -c "import preauth; preauth._check_for_tests()" diff --git a/tests/test_preauth_envelope.py b/tests/test_preauth_envelope.py new file mode 100644 index 0000000..238621e --- /dev/null +++ b/tests/test_preauth_envelope.py @@ -0,0 +1,2071 @@ +"""Signed pre-authorization envelopes (S2 r2, preauth-envelope). + +The owner signs one bounded batch with ``ssh-keygen -Y sign -n rizzstack-preauth``; the key +never leaves the owner's machine. The trust root ``policy/allowed_signers`` is read-only and +its bytes are pinned here, and the checker also requires every signer key's fingerprint to be +in a trusted set the caller reads from the frozen owner pin, so an implementer-added key is +refused. ``scripts/preauth.py`` verifies an envelope and decides one use of it from measured +facts only; every doubt is a named refusal, including missing state (fail closed). + +Production code calls ``check()``, which reads ``policy/allowed_signers`` from the checkout the +module itself lives in (the base checkout) and pins it to the module constant +``OWNER_FINGERPRINTS``; it takes no trust-root override. The decision tests below drive the +private, test-only ``_check_for_tests()``, which accepts a temporary trust root and pin; the module +never calls it, and the gate and lane may reference only ``check`` and ``PreauthRefused`` (frozen +here for ``preauth-wiring``). + +r5 structure: the only code that starts a process is the frozen ``scripts/preauth_verify.py`` +(committed at RED and pinned by sha256 here and in the contract). It runs exactly one +``/usr/bin/ssh-keygen -Y verify`` with a constant environment and a bounded timeout, and every +name it defines is private. The implementer's ``scripts/preauth.py`` (envelope parsing, +policy, facts) imports its single entry point ``_ssh_verify`` by name and may have no process, +filesystem-write or tempfile access at all: ``preauth_violations`` is a strict AST allowlist +over it. ``process_violations`` (the r4 one-process rule, hardened against GROKCHAT's round-4 +bypasses) still pins the verify module and refuses every earlier stub. + +Every checker call in this file runs with process creation recorded: the only program ever +started is ``/usr/bin/ssh-keygen -Y verify``, never ``-Y sign``. + +r6: preauth.py may call open() only with one of exactly two module constants built from +``__file__`` and string literals (the base checkout's ``policy/allowed_signers`` and +``policy/preauth.md``), and check() is spied to open exactly those two paths; print and writes +to stdout/stderr are banned; every refusal is raised through the one canonical ``refuse()`` +helper with a literal reason from the closed set ``REFUSAL_REASONS`` (no interpolation). The +frozen verifier also caps data and signature sizes and requires ssh-keygen's ``Good +"rizzstack-preauth" signature for with`` stdout line. + +Wiring the checker into the gate/lane is the separate named slice ``preauth-wiring``; its frozen +rules (``WiringFreezeTest``) scan every file under .github/ and scripts/ now. + +Every key in these tests is generated in a temporary directory at run time. + +Run: python3 -m pytest -q -p no:cacheprovider tests/test_preauth_envelope.py +""" + +from __future__ import annotations + +import ast +import base64 +import builtins +import hashlib +import importlib.util +import inspect +import json +import os +import re +import shutil +import contextlib +import io +import subprocess +import sys +import tempfile +import types +import unittest +from datetime import datetime, timedelta, timezone +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +MODULE = ROOT / "scripts" / "preauth.py" +SIGNERS = ROOT / "policy" / "allowed_signers" +SCHEMA = ROOT / "schemas" / "preauth.schema.json" +PROCESS_FIXTURES = ROOT / "tests" / "fixtures" / "preauth" +SCRIPTS = ROOT / "scripts" +VERIFY_MODULE = SCRIPTS / "preauth_verify.py" +#: The frozen verifier. Changing scripts/preauth_verify.py needs a new owner-approved contract. +PREAUTH_VERIFY_SHA256 = "0a3ab62b134c0174d150ce25a9c18364a7685872914cf06c8eac36f9ee0d959b" # gitleaks:allow (sha256 of a committed file, not a secret) +VERIFY_ENTRY = "_ssh_verify" +POLICY_DOC = ROOT / "policy" / "preauth.md" +#: r6: stands in for the policy file in the decision tests (check() reads the real one). +TEST_POLICY = b"# preauth policy under test\n" +#: r6: the closed set of refusal reasons. Every PreauthRefused carries exactly one of these. +REFUSAL_REASONS = frozenset({ + "envelope_schema_invalid", "envelope_clock_invalid", "envelope_policy_unproven", + "envelope_signers_invalid", "envelope_signer_untrusted", "envelope_bad_signature", + "envelope_verifier_unavailable", "envelope_expired", "envelope_not_yet_valid", + "envelope_ttl_exceeded", "envelope_facts_unproven", "envelope_revoked", "envelope_action_forbidden", + "envelope_repo_mismatch", "envelope_base_mismatch", "envelope_contract_not_listed", + "envelope_tier_exceeded", "envelope_oracle_unproven", "envelope_oracle_changed", + "envelope_nonce_reused", "envelope_replayed", "envelope_budget_exhausted", +}) + +#: The frozen trust root. Changing policy/allowed_signers needs a new owner-approved contract. +ALLOWED_SIGNERS_SHA256 = "be7d243277ad0073c9d03dc09355f1b769824cde7c2ed0b662c0c190d19973ee" +#: The owner fingerprints the trust root may name. Empty until the owner adds a key. +OWNER_FINGERPRINTS: frozenset = frozenset() + +ALLOWED_ACTIONS = {"merge_slice", "refreeze_contract", "vendor_sync", "close_superseded_pr", "dispatch_wave"} +REPO = "mojomast/bundlebees" +OTHER_REPO = "mojomast/hyvv" +SIGNED_BASE = "a" * 40 +CURRENT_BASE = "b" * 40 +CONTRACT = "7ef0c9d0826186d5fe5e7188b3e8c56268feb5ed73928963fd442a4f49f56d08" +SOURCE_REV = "758e0b6e" + "0" * 32 +NONCE = "4f1c2a9e8b7d6c5b4a39281706f5e4d3" +ENVELOPE_ID = "pa-20261128-01" +NOW = datetime(2026, 11, 28, 15, 0, tzinfo=timezone.utc) + + +def _scripts_on_path(): + # preauth.py imports the frozen verifier by name, as the lane does when it runs from scripts/ + if str(SCRIPTS) not in sys.path: + sys.path.insert(0, str(SCRIPTS)) + + +def load_module(): + _scripts_on_path() + spec = importlib.util.spec_from_file_location("preauth_under_test", MODULE) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def stamp(moment): + return moment.strftime("%Y-%m-%dT%H:%M:%SZ") + + +def envelope(**overrides): + value = { + "schema": "rizzstack.preauth/2", + "id": ENVELOPE_ID, + "issuer": "kyle", + "issued_at": stamp(NOW - timedelta(hours=1)), + "expires_at": stamp(NOW + timedelta(days=2)), + "nonce": NONCE, + "action_class": "merge_slice", + "repos": [REPO], + "bases": {REPO: SIGNED_BASE}, + "contracts": [{"repo": REPO, "slice": "review-packet", "contract_sha256": CONTRACT, + "source_rev": SOURCE_REV, "max_tier": "T3"}], + "review": {"t3_reviewer_login": "rizzstack-reviewer[bot]"}, + "budget": {"max_merges": 2, "max_bees": 3, "max_attempts_per_contract": 3}, + "conditions": [{"name": "P1", "fact": "frozen_oracle_identical", "value": True}], + "max_uses": 2, + "created_from": "owner-chat:t1760", + } + value.update(overrides) + return value + + +def fingerprint(public_line): + blob = base64.b64decode(public_line.split()[1]) + return "SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=") + + +class Keys: + """A throwaway owner key and an allowed_signers file, both in a temp dir.""" + + def __init__(self, principal="kyle", namespaces="rizzstack-preauth", options=None): + self.dir = Path(tempfile.mkdtemp(prefix="preauth-keys-")) + self.key = self.dir / "owner" + subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "test-owner", + "-f", str(self.key)], check=True, capture_output=True) + self.public = (self.dir / "owner.pub").read_text().strip() + self.fingerprint = fingerprint(self.public) + parts = self.public.split() + opts = options if options is not None else 'namespaces="%s"' % namespaces + self.line = "%s %s %s %s" % (principal, opts, parts[0], parts[1]) + self.signers = self.write_signers([self.line]) + + def write_signers(self, lines, name="allowed_signers"): + path = self.dir / name + path.write_text("".join(line + "\n" for line in lines)) + return path + + def sign(self, data: bytes, namespace="rizzstack-preauth") -> bytes: + message = self.dir / "envelope.json" + message.write_bytes(data) + sig = self.dir / "envelope.json.sig" + if sig.exists(): + sig.unlink() + subprocess.run(["ssh-keygen", "-q", "-Y", "sign", "-f", str(self.key), "-n", namespace, + str(message)], check=True, capture_output=True) + return sig.read_bytes() + + def close(self): + shutil.rmtree(self.dir, ignore_errors=True) + + +def facts(**overrides): + value = {"revoked": [], "consumed": [], "nonces": {}, "attempts": {}, "bees_in_flight": 0, + "oracle": None} + value.update(overrides) + return value + + +def used(n, envelope_id=ENVELOPE_ID, contract="f" * 64): + return [{"envelope_id": envelope_id, "nonce": NONCE, "contract_sha256": contract}] * n + + +class ProcessRecorder: + """Record every process the checker starts; refuse anything but ssh-keygen -Y verify.""" + + def __init__(self, case, fail=None): + self.case, self.fail, self.calls, self.timeouts = case, fail, [], [] + self.envs, self.executables = [], [] + self.inside = False + self.hook = None + self._real_popen = subprocess.Popen + + def popen(self, args, *a, **k): + argv = [str(x) for x in (args if isinstance(args, (list, tuple)) else [args])] + self.calls.append(argv) + self.envs.append(k.get("env")) + self.executables.append(k.get("executable")) + if self.fail == "missing": + raise FileNotFoundError(2, "No such file or directory", argv[0]) + if self.fail == "timeout": + return _HangingProcess(argv, self) + if isinstance(self.fail, tuple) and self.fail[0] == "exit0": + return _FinishedProcess(argv, self.fail[1]) + if self.hook is not None: + self.hook(argv) + self.inside = True # the recorded Popen may itself use os.posix_spawn/fork_exec + try: + return self._real_popen(args, *a, **k) + finally: + self.inside = False + + def forbid(self, name): + real = getattr(os, name.split(".", 1)[-1]) + + def refuse(*a, **k): + if self.inside: + return real(*a, **k) + self.calls.append([name] + [str(x) for x in a]) + raise AssertionError("checker started a process via %s" % name) + return refuse + + def __enter__(self): + self.environ_before = dict(os.environ) + self.patches = [mock.patch("subprocess.Popen", self.popen)] + for name in ("system", "popen", "posix_spawn", "posix_spawnp", "execv", "execve", "execvp", + "spawnv", "spawnve", "fork", "forkpty"): + if hasattr(os, name): + self.patches.append(mock.patch("os." + name, self.forbid("os." + name))) + for p in self.patches: + p.start() + return self + + def __exit__(self, *exc): + for p in reversed(self.patches): + p.stop() + for argv in self.calls: + self.case.assertTrue(argv and os.path.basename(argv[0]) == "ssh-keygen", argv) + self.case.assertEqual(argv[1:3], ["-Y", "verify"], argv) + self.case.assertNotIn("sign", argv[1:3], argv) + # r4: absolute executable, resolved outside any temp dir, and a constant environment + self.case.assertEqual(argv[0], "/usr/bin/ssh-keygen", argv) + resolved = os.path.realpath(argv[0]) + self.case.assertFalse(resolved.startswith(os.path.realpath(tempfile.gettempdir()) + os.sep), resolved) + for env in self.envs: + self.case.assertEqual(env, {"PATH": "/usr/bin:/bin"}, "ssh-keygen must run with a constant env") + for executable in self.executables: + self.case.assertIsNone(executable) + self.case.assertEqual(dict(os.environ), self.environ_before, "the checker changed os.environ") + return False + + +class _HangingProcess: + def __init__(self, argv, recorder): + self.args, self.recorder, self.returncode, self.pid = argv, recorder, None, 0 + self.stdin = self.stdout = self.stderr = None + + def communicate(self, input=None, timeout=None): + self.recorder.timeouts.append(timeout) + raise subprocess.TimeoutExpired(self.args, timeout or 0) + + def wait(self, timeout=None): + self.recorder.timeouts.append(timeout) + if self.returncode is None and timeout is not None: + raise subprocess.TimeoutExpired(self.args, timeout) + return self.returncode + + def poll(self): + return self.returncode + + def kill(self): + self.returncode = -9 + + terminate = kill + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.kill() + return False + + +class _FinishedProcess(_HangingProcess): + """A process that already exited 0 with the given stdout (no real ssh-keygen ran).""" + + def __init__(self, argv, stdout): + self.args, self.returncode, self.pid, self.out = argv, 0, 0, stdout + self.stdin = self.stdout = self.stderr = None + + def communicate(self, input=None, timeout=None): + return self.out, b"" + + def wait(self, timeout=None): + return 0 + + def kill(self): + pass + + terminate = kill + + def __exit__(self, *exc): + return False + + +def _signers_bytes(path): + path = Path(path) + return path.read_bytes() if path.is_file() else None + + +class EnvelopeCase(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.pre = load_module() + cls.keys = Keys() + + @classmethod + def tearDownClass(cls): + cls.keys.close() + + def decide(self, value=None, *, signature=None, data=None, contract=CONTRACT, repo=REPO, + base=CURRENT_BASE, tier="T3", now=NOW, measured=None, signers=None, trusted=None, + fail=None, is_ancestor=lambda older, newer: older == SIGNED_BASE and newer == CURRENT_BASE): + data = data if data is not None else json.dumps(value if value is not None else envelope(), + sort_keys=True).encode("utf-8") + signature = signature if signature is not None else self.keys.sign(data) + signers = signers or self.keys.signers + with ProcessRecorder(self, fail) as self.recorder: + # r6: preauth.py opens only its two pinned files, so the test-only entry point gets the + # trust-root bytes (and the path ssh-keygen reads) and the policy bytes from the test + return self.pre._check_for_tests( + data, signature, allowed_signers=str(signers), allowed_signers_bytes=_signers_bytes(signers), + policy_bytes=TEST_POLICY, trusted_fingerprints=frozenset(trusted if trusted is not None else {self.keys.fingerprint}), + repo=repo, base_rev=base, contract_sha256=contract, tier=tier, now=now, + facts=measured if measured is not None else facts(), is_ancestor=is_ancestor) + + def refused(self, reason, *args, **kwargs): + with self.assertRaises(self.pre.PreauthRefused) as caught: + self.decide(*args, **kwargs) + # r6: every refusal is one reason from the closed set, carried verbatim and nothing else + self.assertIn(caught.exception.reason, REFUSAL_REASONS) + self.assertEqual(caught.exception.args, (caught.exception.reason,)) + self.assertEqual(caught.exception.reason, reason) + + +class SignatureTest(EnvelopeCase): + def test_valid_signed_envelope_authorizes_one_listed_contract(self): + decision = self.decide() + self.assertTrue(decision["ok"]) + self.assertEqual(decision["envelope_id"], ENVELOPE_ID) + self.assertEqual(decision["contract_sha256"], CONTRACT) + self.assertEqual(decision["max_tier"], "T3") + self.assertEqual(len(self.recorder.calls), 1, self.recorder.calls) + self.assertEqual(decision["policy_sha256"], hashlib.sha256(TEST_POLICY).hexdigest()) + self.assertEqual(decision["allowed_signers_sha256"], + hashlib.sha256(self.keys.signers.read_bytes()).hexdigest()) + + def test_tampered_envelope_is_a_bad_signature(self): + data = json.dumps(envelope(), sort_keys=True).encode() + signature = self.keys.sign(data) + tampered = json.dumps(envelope(max_uses=1), sort_keys=True).encode() + self.refused("envelope_bad_signature", data=tampered, signature=signature) + + def test_foreign_key_is_a_bad_signature(self): + other = Keys() + try: + data = json.dumps(envelope(), sort_keys=True).encode() + self.refused("envelope_bad_signature", data=data, signature=other.sign(data)) + finally: + other.close() + + def test_wrong_namespace_is_a_bad_signature(self): + data = json.dumps(envelope(), sort_keys=True).encode() + self.refused("envelope_bad_signature", data=data, signature=self.keys.sign(data, namespace="git")) + + def test_garbage_signature_is_a_bad_signature(self): + self.refused("envelope_bad_signature", signature=b"not a signature") + + def test_issuer_must_be_the_signing_principal(self): + self.refused("envelope_bad_signature", envelope(issuer="coordinator")) + + def test_multi_principal_trust_root_binds_issuer_to_its_own_key(self): + other = Keys(principal="bob") + try: + signers = self.keys.write_signers([self.keys.line, other.line], "two_signers") + trusted = {self.keys.fingerprint, other.fingerprint} + data = json.dumps(envelope(issuer="bob"), sort_keys=True).encode() + self.refused("envelope_bad_signature", data=data, signature=self.keys.sign(data), + signers=signers, trusted=trusted) + self.assertTrue(self.decide(data=data, signature=other.sign(data), signers=signers, + trusted=trusted)["ok"]) + finally: + other.close() + + def test_schema_invalid_envelope_refuses_before_anything_else(self): + value = envelope() + del value["nonce"] + self.refused("envelope_schema_invalid", value) + self.refused("envelope_schema_invalid", envelope(unexpected="field")) + self.refused("envelope_schema_invalid", data=b'{"id": "a", "id": "b"}') + self.refused("envelope_schema_invalid", data=b"[]") + self.refused("envelope_schema_invalid", data=b"\xff\xfe") + self.assertEqual(self.recorder.calls, []) + + +class TrustRootTest(EnvelopeCase): + def test_key_not_in_the_owner_pin_is_refused(self): + self.refused("envelope_signer_untrusted", trusted=set()) + self.refused("envelope_signer_untrusted", trusted={"SHA256:" + "A" * 43}) + self.assertEqual(self.recorder.calls, []) + + def test_implementer_added_key_beside_the_owner_key_is_refused(self): + intruder = Keys(principal="kyle") + try: + signers = self.keys.write_signers([self.keys.line, intruder.line], "with_intruder") + data = json.dumps(envelope(), sort_keys=True).encode() + self.refused("envelope_signer_untrusted", data=data, signature=intruder.sign(data), + signers=signers) + self.refused("envelope_signer_untrusted", data=data, signature=self.keys.sign(data), + signers=signers) + finally: + intruder.close() + + def test_cert_authority_wildcard_and_malformed_trust_lines_are_refused(self): + key = self.keys.public.split() + bad_lines = ( + 'kyle cert-authority,namespaces="rizzstack-preauth" %s %s' % (key[0], key[1]), + '* namespaces="rizzstack-preauth" %s %s' % (key[0], key[1]), + 'ky?e namespaces="rizzstack-preauth" %s %s' % (key[0], key[1]), + 'kyle,bob namespaces="rizzstack-preauth" %s %s' % (key[0], key[1]), + '!kyle namespaces="rizzstack-preauth" %s %s' % (key[0], key[1]), + 'kyle namespaces="rizzstack-preauth,git" %s %s' % (key[0], key[1]), + 'kyle namespaces="*" %s %s' % (key[0], key[1]), + 'kyle %s %s' % (key[0], key[1]), + 'kyle namespaces="rizzstack-preauth" ssh-rsa %s' % key[1], + 'kyle namespaces="rizzstack-preauth" %s' % key[0], + 'kyle namespaces="rizzstack-preauth" %s not-base64!' % key[0], + ) + for line in bad_lines: + signers = self.keys.write_signers([line], "bad_signers") + self.refused("envelope_signers_invalid", signers=signers) + self.refused("envelope_signers_invalid", signers=self.keys.dir / "missing_file") + + def test_empty_trust_root_refuses_every_envelope(self): + signers = self.keys.write_signers(["# comments only"], "empty_signers") + self.refused("envelope_signer_untrusted", signers=signers) + + +class ValidityTest(EnvelopeCase): + def test_expired_envelope_refuses(self): + self.refused("envelope_expired", now=NOW + timedelta(days=3)) + self.refused("envelope_expired", now=NOW + timedelta(days=2)) # expires_at itself is expired + + def test_not_yet_valid_envelope_refuses(self): + self.refused("envelope_not_yet_valid", now=NOW - timedelta(days=1)) + + def test_longer_than_seven_days_refuses(self): + self.refused("envelope_ttl_exceeded", + envelope(expires_at=stamp(NOW - timedelta(hours=1) + timedelta(days=7, seconds=1)))) + + def test_expiry_before_issue_and_malformed_timestamps_refuse(self): + self.refused("envelope_schema_invalid", envelope(expires_at=stamp(NOW - timedelta(hours=2)))) + self.refused("envelope_schema_invalid", envelope(expires_at=stamp(NOW - timedelta(hours=1)))) + for bad in ("2026-11-29T15:00:00", "2026-11-29T15:00:00+00:00", "2026-11-29 15:00:00Z", + "2026-13-29T15:00:00Z", "tomorrow", 1764428400, None): + self.refused("envelope_schema_invalid", envelope(expires_at=bad)) + self.refused("envelope_schema_invalid", envelope(issued_at=bad)) + + def test_naive_or_missing_clock_refuses(self): + self.refused("envelope_clock_invalid", now=NOW.replace(tzinfo=None)) + self.refused("envelope_clock_invalid", now=None) + self.refused("envelope_clock_invalid", now="2026-11-28T15:00:00Z") + + def test_issuer_that_could_be_read_as_an_option_or_pattern_refuses(self): + for issuer in ("*", "ky*", "kyle,bob", "-kyle", "kyle bob", "", " kyle", "kyle\n", "!kyle", 7): + self.refused("envelope_schema_invalid", envelope(issuer=issuer)) + + def test_revoked_envelope_refuses_immediately(self): + self.refused("envelope_revoked", measured=facts(revoked=[ENVELOPE_ID])) + + +class FactsFailClosedTest(EnvelopeCase): + def test_missing_state_refuses_with_a_named_reason(self): + for key in ("revoked", "consumed", "nonces", "attempts", "bees_in_flight"): + value = facts() + del value[key] + self.refused("envelope_facts_unproven", measured=value) + + def test_null_or_mistyped_state_refuses(self): + for key, bad in (("revoked", None), ("revoked", "pa-1"), ("consumed", None), ("consumed", {}), + ("nonces", None), ("nonces", []), ("attempts", None), ("attempts", []), + ("bees_in_flight", None), ("bees_in_flight", "0"), ("bees_in_flight", -1), + ("bees_in_flight", True)): + self.refused("envelope_facts_unproven", measured=facts(**{key: bad})) + self.refused("envelope_facts_unproven", measured=[]) + + +class ScopeTest(EnvelopeCase): + def test_wrong_repository_refuses(self): + self.refused("envelope_repo_mismatch", repo=OTHER_REPO) + + def test_contract_listed_only_under_another_repo_refuses(self): + value = envelope(repos=[REPO, OTHER_REPO], bases={REPO: SIGNED_BASE, OTHER_REPO: SIGNED_BASE}) + self.refused("envelope_contract_not_listed", value, repo=OTHER_REPO) + + def test_bases_missing_the_repo_refuses(self): + value = envelope(repos=[REPO, OTHER_REPO], bases={REPO: SIGNED_BASE}) + value["contracts"].append(dict(value["contracts"][0], repo=OTHER_REPO)) + self.refused("envelope_base_mismatch", value, repo=OTHER_REPO) + + def test_base_that_does_not_descend_from_the_signed_base_refuses(self): + self.refused("envelope_base_mismatch", is_ancestor=lambda older, newer: False) + self.refused("envelope_base_mismatch", is_ancestor=None) + + def test_contract_not_listed_refuses(self): + self.refused("envelope_contract_not_listed", contract="c" * 64) + + def test_action_class_is_an_allowlist(self): + self.assertEqual(set(self.pre.ALLOWED_ACTION_CLASSES), ALLOWED_ACTIONS) + for action in ("merge_gate_change", "ruleset_change", "deploy", "component_deploy", "force_push", + "preauth_widen", "admin", "merge_gate_change2", "", "MERGE_SLICE", "merge_slice ", + None, 1): + self.refused("envelope_action_forbidden", envelope(action_class=action)) + + def test_tier_above_the_contracts_max_tier_refuses(self): + entry = dict(envelope()["contracts"][0], max_tier="T1") + self.refused("envelope_tier_exceeded", envelope(contracts=[entry]), tier="T3") + self.assertTrue(self.decide(envelope(contracts=[entry]), tier="T1")["ok"]) + for tier in ("T2", "", None, "t1"): + self.refused("envelope_tier_exceeded", envelope(contracts=[entry]), tier=tier) + bad = dict(entry, max_tier="T9") + self.refused("envelope_schema_invalid", envelope(contracts=[bad])) + + +class OracleTest(EnvelopeCase): + OLD = {"tests/test_review_packet.py": "1" * 40, "tests/conftest.py": "2" * 40, + "pyproject.toml": "3" * 40, "pytest.ini": "4" * 40, "tests/fixtures/case.json": "5" * 40, + "sitecustomize.py": "6" * 40, "src/thing.py": "7" * 40} + + def refreeze(self): + entry = dict(envelope()["contracts"][0]) + entry["refreeze_of"] = {"contract_sha256": "d" * 64, "source_rev": "e" * 40} + entry["test_files"] = ["tests/test_review_packet.py"] + return envelope(contracts=[entry], action_class="refreeze_contract") + + def test_refreeze_with_an_identical_oracle_is_allowed(self): + new = dict(self.OLD, **{"src/thing.py": "8" * 40}) # product code may differ + self.assertTrue(self.decide(self.refreeze(), measured=facts(oracle={"old": self.OLD, "new": new}))["ok"]) + + def test_refreeze_that_changes_any_oracle_file_refuses(self): + for path in ("tests/test_review_packet.py", "tests/conftest.py", "pyproject.toml", + "pytest.ini", "tests/fixtures/case.json", "sitecustomize.py"): + new = dict(self.OLD, **{path: "9" * 40}) + self.refused("envelope_oracle_changed", self.refreeze(), + measured=facts(oracle={"old": self.OLD, "new": new})) + + def test_refreeze_that_adds_or_removes_an_oracle_file_refuses(self): + for extra in ("tests/plugins/hook.py", "x.pth", "tests/helpers.py", "tests/test_other.py", + "noxfile.py", ".github/workflows/ci.yml", "requirements-dev.txt", "./tests/../conftest.py"): + self.refused("envelope_oracle_changed", self.refreeze(), + measured=facts(oracle={"old": self.OLD, "new": dict(self.OLD, **{extra: "a" * 40})})) + removed = {k: v for k, v in self.OLD.items() if k != "tests/conftest.py"} + self.refused("envelope_oracle_changed", self.refreeze(), + measured=facts(oracle={"old": self.OLD, "new": removed})) + + def test_refreeze_without_measured_oracle_refuses(self): + self.refused("envelope_oracle_unproven", self.refreeze(), measured=facts(oracle=None)) + self.refused("envelope_oracle_unproven", self.refreeze(), measured=facts(oracle={"old": self.OLD})) + + def test_oracle_paths_cover_tests_conftest_config_fixtures_dependencies_ci_and_hooks(self): + inside = ["tests/test_a.py", "tests/conftest.py", "a/b/conftest.py", "pytest.ini", "tox.ini", + "setup.cfg", "pyproject.toml", "setup.py", "noxfile.py", ".coveragerc", + "tests/fixtures/f.json", "tests/data/d.txt", "tests/helpers.py", "tests/__init__.py", + "tests/unit/test_b.py", "pkg/test_c.py", "pkg/c_test.py", "sitecustomize.py", + "usercustomize.py", "x.pth", "lib/site.pth", "tests/plugins/p.py", "requirements.txt", + "requirements-dev.txt", "uv.lock", "poetry.lock", "Pipfile", "Pipfile.lock", + ".github/workflows/ci.yml", ".github/workflows/x.yaml"] + outside = ["src/x.py", "docs/a.md", "README.md", "src/testing_utils.py"] + self.assertEqual(self.pre.oracle_paths(inside + outside, test_files=["tests/test_a.py"]), set(inside)) + + def test_oracle_paths_normalise_before_matching(self): + got = self.pre.oracle_paths(["./tests/../conftest.py", "tests//conftest.py", "./pytest.ini", + "Tests/Conftest.py", "tests\\conftest.py"], test_files=[]) + self.assertEqual(got, {"conftest.py", "tests/conftest.py", "pytest.ini", "Tests/Conftest.py"}) + for bad in ("../outside/conftest.py", "/abs/conftest.py"): + with self.assertRaises(self.pre.PreauthRefused): + self.pre.oracle_paths([bad], test_files=[]) + + +class BudgetTest(EnvelopeCase): + def test_exhausted_merge_budget_refuses(self): + self.refused("envelope_budget_exhausted", measured=facts(consumed=used(2))) + + def test_max_uses_is_a_ceiling_too(self): + self.refused("envelope_budget_exhausted", envelope(max_uses=1), measured=facts(consumed=used(1))) + + def test_uses_of_another_envelope_do_not_count(self): + self.assertTrue(self.decide(measured=facts(consumed=used(5, envelope_id="pa-other")))["ok"]) + + def test_attempts_per_contract_are_capped(self): + self.refused("envelope_budget_exhausted", measured=facts(attempts={CONTRACT: 3})) + self.assertTrue(self.decide(measured=facts(attempts={CONTRACT: 2, "c" * 64: 9}))["ok"]) + + def test_bees_in_flight_are_capped_for_wave_dispatch(self): + self.refused("envelope_budget_exhausted", envelope(action_class="dispatch_wave"), + measured=facts(bees_in_flight=3)) + self.assertTrue(self.decide(envelope(action_class="dispatch_wave"), measured=facts(bees_in_flight=2))["ok"]) + + def test_budget_shape_is_bounded(self): + for budget in ({"max_merges": 0, "max_bees": 3, "max_attempts_per_contract": 3}, + {"max_merges": 2, "max_bees": 5, "max_attempts_per_contract": 3}, + {"max_merges": 2, "max_bees": 3, "max_attempts_per_contract": 0}, + {"max_merges": 2, "max_bees": 3}, + {"max_merges": 2, "max_bees": 3, "max_attempts_per_contract": 3, "extra": 1}, + {"max_merges": "2", "max_bees": 3, "max_attempts_per_contract": 3}, + {"max_merges": True, "max_bees": 3, "max_attempts_per_contract": 3}): + self.refused("envelope_schema_invalid", envelope(budget=budget)) + for max_uses in (0, -1, "2", True, 2.0): + self.refused("envelope_schema_invalid", envelope(max_uses=max_uses)) + + def test_replayed_use_of_the_same_contract_refuses(self): + self.refused("envelope_replayed", measured=facts(consumed=used(1, contract=CONTRACT))) + + def test_nonce_reused_by_another_envelope_refuses(self): + self.refused("envelope_nonce_reused", measured=facts(nonces={NONCE: "pa-20261101-07"})) + + +class VerifierTest(EnvelopeCase): + def test_missing_ssh_keygen_refuses(self): + self.refused("envelope_verifier_unavailable", fail="missing") + + def test_hanging_ssh_keygen_refuses_within_a_bounded_timeout(self): + self.refused("envelope_verifier_unavailable", fail="timeout") + self.assertTrue(self.recorder.timeouts, "ssh-keygen must be run with a timeout") + self.assertTrue(all(t is not None and 0 < t <= 60 for t in self.recorder.timeouts[:1]), + self.recorder.timeouts) + + def test_a_path_hijack_cannot_forge_a_signature(self): + fake = Path(tempfile.mkdtemp(prefix="preauth-hijack-")) + self.addCleanup(shutil.rmtree, fake, True) + (fake / "ssh-keygen").write_text("#!/bin/sh\necho Good signature; exit 0\n") + os.chmod(fake / "ssh-keygen", 0o755) + path = str(fake) + os.pathsep + os.environ.get("PATH", "") + with mock.patch.dict(os.environ, {"PATH": path}): + self.refused("envelope_bad_signature", signature=b"-----BEGIN SSH SIGNATURE-----\nAAAA\n-----END SSH SIGNATURE-----\n") + self.assertEqual(self.recorder.calls[0][0], "/usr/bin/ssh-keygen") + self.assertEqual(self.recorder.envs, [{"PATH": "/usr/bin:/bin"}]) + + def test_every_process_is_ssh_keygen_verify(self): + self.decide() + self.assertEqual([argv[1:3] for argv in self.recorder.calls], [["-Y", "verify"]]) + argv = self.recorder.calls[0] + self.assertIn("-n", argv) + self.assertEqual(argv[argv.index("-n") + 1], "rizzstack-preauth") + + +class KeyCustodyTest(unittest.TestCase): + def test_module_verifies_and_never_signs(self): + pre = load_module() + self.assertEqual(pre.NAMESPACE, "rizzstack-preauth") + self.assertEqual(pre.MAX_TTL_SECONDS, 7 * 24 * 3600) + for name in dir(pre): + self.assertNotRegex(name.lower(), r"(^|_)(sign|mint|generate)(_|$)", name) + tree = ast.parse(MODULE.read_text(encoding="utf-8")) + forbidden = {"Ed25519PrivateKey", "SigningKey", "PrivateKey", "load_ssh_private_key", + "load_pem_private_key", "nacl", "cryptography", "paramiko"} + for node in ast.walk(tree): + if isinstance(node, ast.Name): + self.assertNotIn(node.id, forbidden) + elif isinstance(node, ast.Attribute): + self.assertNotIn(node.attr, forbidden) + elif isinstance(node, (ast.Import, ast.ImportFrom)): + names = [a.name for a in node.names] + [getattr(node, "module", None) or ""] + for name in names: + self.assertNotIn(name.split(".")[0], forbidden, name) + elif isinstance(node, ast.Constant) and isinstance(node.value, str): + self.assertNotIn("PRIVATE KEY", node.value) + + def test_trust_root_is_frozen_and_holds_only_pinned_owner_keys(self): + self.assertTrue(SIGNERS.is_file(), "missing policy/allowed_signers") + self.assertEqual(hashlib.sha256(SIGNERS.read_bytes()).hexdigest(), ALLOWED_SIGNERS_SHA256, + "policy/allowed_signers is read-only; a new key needs an owner-approved contract") + for line in SIGNERS.read_text(encoding="utf-8").splitlines(): + if not line.strip() or line.lstrip().startswith("#"): + continue + self.assertNotIn("cert-authority", line) + self.assertRegex(line, r'^[A-Za-z0-9._@-]+ namespaces="rizzstack-preauth" ' + r'(ssh-ed25519|sk-ssh-ed25519@openssh\.com) [A-Za-z0-9+/=]+(\s.*)?$') + self.assertIn(fingerprint(" ".join(line.split()[2:4])), OWNER_FINGERPRINTS) + + def test_no_tracked_file_holds_private_key_material(self): + tracked = subprocess.run(["git", "-C", str(ROOT), "ls-files", "-z"], capture_output=True, + check=True).stdout.decode().split("\0") + marker = re.compile(r"-----BEGIN ([A-Z0-9 ]+ )?PRIVATE KEY-----|" + "PuTTY-User-" + "Key-File") + for path in filter(None, tracked): + target = ROOT / path + if target.is_file() and target.stat().st_size < 2_000_000: + self.assertIsNone(marker.search(target.read_text(encoding="utf-8", errors="ignore")), path) + + def test_schema_matches_the_checker(self): + pre = load_module() + schema = json.loads(SCHEMA.read_text(encoding="utf-8")) + self.assertEqual(set(schema["required"]), set(pre.REQUIRED_FIELDS)) + self.assertFalse(schema["additionalProperties"]) + self.assertEqual(set(schema["properties"]["action_class"]["enum"]), ALLOWED_ACTIONS) + + +# --------------------------------------------------------------- production entry point +PRODUCTION_PARAMETERS = ("data", "signature", "repo", "base_rev", "contract_sha256", "tier", "now", "facts", + "is_ancestor") +OVERRIDE_PARAMETERS = {"allowed_signers", "trusted_fingerprints", "signers", "fingerprints", "trust_root", + "signers_path", "root", "base_dir"} + + +def _dotted_root(node): + while isinstance(node, ast.Attribute): + node = node.value + return node.id if isinstance(node, ast.Name) else None + + +def _load_copy(tree, name): + _scripts_on_path() + spec = importlib.util.spec_from_file_location(name, tree / "scripts" / "preauth.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class ProductionEntryPointTest(unittest.TestCase): + """check() reads the base checkout's trust root and the module pin; nothing overrides them.""" + + @classmethod + def setUpClass(cls): + cls.pre = load_module() + cls.keys = Keys() + + @classmethod + def tearDownClass(cls): + cls.keys.close() + + def call(self, module, **overrides): + data = json.dumps(envelope(), sort_keys=True).encode("utf-8") + kwargs = dict(repo=REPO, base_rev=CURRENT_BASE, contract_sha256=CONTRACT, tier="T3", now=NOW, + facts=facts(), is_ancestor=lambda older, newer: older == SIGNED_BASE) + kwargs.update(overrides) + signature = self.keys.sign(data) + self.opened = [] + real_open = builtins.open + + def spy(file, *args, **kw): + self.opened.append(file) + return real_open(file, *args, **kw) + + with ProcessRecorder(self), mock.patch("builtins.open", spy): + return module.check(data, signature, **kwargs) + + def opened_paths(self): + return sorted(os.path.realpath(os.fsdecode(p)) for p in self.opened) + + def tree(self, signer_lines, policy=b"# preauth policy in the base checkout\n"): + root = Path(tempfile.mkdtemp(prefix="preauth-tree-")) + self.addCleanup(shutil.rmtree, root, True) + (root / "scripts").mkdir() + (root / "policy").mkdir() + shutil.copyfile(MODULE, root / "scripts" / "preauth.py") + shutil.copyfile(VERIFY_MODULE, root / "scripts" / "preauth_verify.py") + (root / "policy" / "allowed_signers").write_text("".join(l + "\n" for l in signer_lines)) + if policy is not None: + (root / "policy" / "preauth.md").write_bytes(policy) + return root + + def test_owner_fingerprints_constant_is_frozen_and_equals_the_test_pin(self): + pin = self.pre.OWNER_FINGERPRINTS + self.assertIsInstance(pin, tuple) + self.assertEqual(len(pin), len(set(pin))) + self.assertEqual(frozenset(pin), OWNER_FINGERPRINTS) + for value in pin: + self.assertRegex(value, r"^SHA256:[A-Za-z0-9+/]{43}$") + + def test_check_takes_no_trust_root_override(self): + params = inspect.signature(self.pre.check).parameters + self.assertEqual(tuple(params), PRODUCTION_PARAMETERS) + for param in params.values(): + self.assertNotIn(param.kind, (param.VAR_POSITIONAL, param.VAR_KEYWORD), param) + with self.assertRaises(TypeError): + self.call(self.pre, allowed_signers=str(self.keys.signers)) + with self.assertRaises(TypeError): + self.call(self.pre, trusted_fingerprints=frozenset({self.keys.fingerprint})) + + def test_the_committed_trust_root_refuses_every_envelope(self): + with self.assertRaises(self.pre.PreauthRefused) as caught: + self.call(self.pre) + self.assertEqual(caught.exception.reason, "envelope_signer_untrusted") + + def test_check_reads_the_base_checkout_trust_root_and_the_module_pin(self): + root = self.tree([self.keys.line]) + copy = _load_copy(root, "preauth_tree_copy") + with self.assertRaises(copy.PreauthRefused) as caught: + self.call(copy) + self.assertEqual(caught.exception.reason, "envelope_signer_untrusted", "empty module pin") + with mock.patch.object(copy, "OWNER_FINGERPRINTS", (self.keys.fingerprint,)): + self.assertTrue(self.call(copy)["ok"]) + + def test_cwd_and_environment_do_not_redirect_the_trust_root(self): + root = self.tree(["# empty"]) + decoy = self.tree([self.keys.line]) + copy = _load_copy(root, "preauth_tree_decoy") + env = {name: str(decoy / "policy" / "allowed_signers") for name in ( + "PREAUTH_ALLOWED_SIGNERS", "RIZZSTACK_ALLOWED_SIGNERS", "ALLOWED_SIGNERS")} + cwd = os.getcwd() + try: + os.chdir(decoy) + with mock.patch.dict(os.environ, env), \ + mock.patch.object(copy, "OWNER_FINGERPRINTS", (self.keys.fingerprint,)): + with self.assertRaises(copy.PreauthRefused) as caught: + self.call(copy) + finally: + os.chdir(cwd) + self.assertEqual(caught.exception.reason, "envelope_signer_untrusted") + + def test_check_opens_exactly_the_policy_and_the_trust_root(self): + root = self.tree([self.keys.line]) + copy = _load_copy(root, "preauth_tree_open_spy") + want = sorted(os.path.realpath(root / "policy" / name) for name in ("allowed_signers", "preauth.md")) + with mock.patch.object(copy, "OWNER_FINGERPRINTS", (self.keys.fingerprint,)): + decision = self.call(copy) + self.assertTrue(decision["ok"]) + self.assertEqual(self.opened_paths(), want, "check() opens exactly its two pinned files, once each") + self.assertEqual(decision["policy_sha256"], + hashlib.sha256((root / "policy" / "preauth.md").read_bytes()).hexdigest()) + self.assertEqual(decision["allowed_signers_sha256"], + hashlib.sha256((root / "policy" / "allowed_signers").read_bytes()).hexdigest()) + # refusals open nothing else either (empty module pin; a malformed envelope) + with self.assertRaises(copy.PreauthRefused): + self.call(copy) + self.assertLessEqual(set(self.opened_paths()), set(want)) + self.assertEqual(len(self.opened), len(set(self.opened_paths()))) + with mock.patch.object(copy, "OWNER_FINGERPRINTS", (self.keys.fingerprint,)): + with self.assertRaises(copy.PreauthRefused): + self.call(copy, repo=OTHER_REPO) + self.assertLessEqual(set(self.opened_paths()), set(want)) + + def test_a_missing_policy_file_refuses(self): + root = self.tree([self.keys.line], policy=None) + copy = _load_copy(root, "preauth_tree_no_policy") + with mock.patch.object(copy, "OWNER_FINGERPRINTS", (self.keys.fingerprint,)): + with self.assertRaises(copy.PreauthRefused) as caught: + self.call(copy) + self.assertEqual(caught.exception.reason, "envelope_policy_unproven") + self.assertLessEqual(set(self.opened_paths()), {os.path.realpath(root / "policy" / n) + for n in ("allowed_signers", "preauth.md")}) + + def test_refusal_reasons_are_a_closed_set(self): + self.assertEqual(frozenset(self.pre.REFUSAL_REASONS), REFUSAL_REASONS) + tree = ast.parse(MODULE.read_text(encoding="utf-8")) + used = {node.args[0].value for node in ast.walk(tree) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "refuse" + and node.args and isinstance(node.args[0], ast.Constant)} + self.assertTrue(used) + self.assertLessEqual(used, REFUSAL_REASONS) + self.assertEqual(preauth_r6_violations(tree), []) + + def test_overrides_live_only_in_the_test_only_entry_point(self): + tree = ast.parse(MODULE.read_text(encoding="utf-8")) + functions = {node.name: node for node in ast.walk(tree) + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))} + self.assertIn("_check_for_tests", functions) + self.assertNotIn("check_for_tests", functions, "the test-only entry point must be private") + self.assertIn("test", (ast.get_docstring(functions["_check_for_tests"]) or "").lower()) + for name, node in functions.items(): + args = {a.arg for a in node.args.args + node.args.kwonlyargs + node.args.posonlyargs} + if args & {"trusted_fingerprints", "allowed_signers"} and not name.startswith("_"): + self.fail("public %s takes a trust-root override" % name) + # r5: the verify entry point is private (no public verify_signature or similar) + verifying = sorted(n for n in functions if not n.startswith("_") and re.search("verif|signature", n)) + self.assertEqual(verifying, [], "the verify entry point must be private") + for node in ast.walk(tree): + if isinstance(node, ast.Call): + func = node.func + called = func.id if isinstance(func, ast.Name) else getattr(func, "attr", "") + self.assertNotIn(called, ("check_for_tests", "_check_for_tests"), + "the module calls its test-only entry point") + if isinstance(node, ast.Name) and node.id in ("check_for_tests", "_check_for_tests"): + self.fail("the module references its test-only entry point outside its definition") + public = sorted(n for n in functions if not n.startswith("_") and "check" in n) + self.assertEqual(public, ["check"], public) + + + +# --------------------------------------------------------------- wiring freeze (preauth-wiring, r5) +WIRING_ALLOWED = {"check", "PreauthRefused"} +WIRING_FIXTURES = PROCESS_FIXTURES / "wiring_must_fail" +WIRING_EXEMPT = {MODULE.resolve(), VERIFY_MODULE.resolve()} +PRIVATE_MARKERS = ("check_for_tests", VERIFY_ENTRY, "preauth_verify", "_decide") +DYNAMIC_IMPORT = {"importlib", "runpy", "imp", "pkgutil", "zipimport"} +DYNAMIC_CODE = {"__import__", "eval", "exec", "compile", "execfile", "spec_from_file_location", + "SourceFileLoader", "exec_module", "load_module", "run_path", "run_module"} +#: as attributes (``re.compile`` is fine; a loader's ``exec_module`` is not) +DYNAMIC_ATTRS = DYNAMIC_CODE - {"compile", "eval", "exec"} +WIRING_TEXT = re.compile(r"\bimport\s+(scripts\.)?preauth\b|\bfrom\s+(scripts\.preauth|scripts|preauth)\s+import\b|" + r"preauth_verify|check_for_tests|_ssh_verify|\bpreauth\.(?!md\b|py\b)[A-Za-z_]") + + +def wiring_violations(source): + """Violations of the frozen wiring rule for one Python file under .github/ or scripts/.""" + try: + tree = ast.parse(source) + except SyntaxError as exc: + return ["syntax_error:%s" % exc.lineno] + out, aliases = [], set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + parts = alias.name.split(".") + if "preauth_verify" in parts: + out.append("verify_import") + elif parts[-1] == "preauth": + aliases.add(alias.asname or alias.name) + if parts[0] in DYNAMIC_IMPORT: + out.append("dynamic_import:" + parts[0]) + elif isinstance(node, ast.ImportFrom): + mod = node.module or "" + parts = mod.split(".") + if parts[0] in DYNAMIC_IMPORT: + out.append("dynamic_import:" + parts[0]) + if "preauth_verify" in parts or any(a.name == "preauth_verify" for a in node.names): + out.append("verify_import") + elif parts[-1] == "preauth": + for alias in node.names: + if alias.name not in WIRING_ALLOWED: + out.append("preauth_name:" + alias.name) + else: + for alias in node.names: + if alias.name == "preauth": + aliases.add(alias.asname or alias.name) + parents = _parents(tree) + for node in ast.walk(tree): + if isinstance(node, (ast.Name, ast.Attribute)): + dotted = _dotted(node) + if dotted in aliases: + parent = parents.get(id(node)) + if not (isinstance(parent, ast.Attribute) and parent.value is node): + out.append("preauth_module_value:" + dotted) + elif parent.attr not in WIRING_ALLOWED: + out.append("preauth_name:" + parent.attr) + if isinstance(node, ast.Name): + if node.id in DYNAMIC_CODE: + out.append("dynamic_code:" + node.id) + if any(marker in node.id for marker in PRIVATE_MARKERS): + out.append("private_name:" + node.id) + elif isinstance(node, ast.Attribute): + if node.attr in DYNAMIC_ATTRS: + out.append("dynamic_code:" + node.attr) + if node.attr == "modules" and _dotted(node.value) == "sys": + out.append("sys_modules") + if any(marker in node.attr for marker in PRIVATE_MARKERS): + out.append("private_name:" + node.attr) + elif isinstance(node, ast.Constant) and isinstance(node.value, str): + if any(marker in node.value for marker in PRIVATE_MARKERS): + out.append("private_name_string") + if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) + and node.func.id in ("getattr", "hasattr", "setattr", "delattr", "vars")): + target = node.args[0] if node.args else None + if target is not None and _dotted(target) in aliases: + out.append("preauth_getattr") + if node.func.id != "vars" and (len(node.args) < 2 or not isinstance(node.args[1], ast.Constant)): + out.append("getattr_computed") + return sorted(set(out)) + + +def wiring_text_violations(text): + """Violations of the frozen wiring rule for a non-Python file (workflows, shell, docs).""" + return ["preauth_in_text"] if WIRING_TEXT.search(text) else [] + + +def _wiring_targets(): + for top in (ROOT / ".github", ROOT / "scripts"): + for path in sorted(top.rglob("*")): + if path.is_file() and "__pycache__" not in path.parts and path.resolve() not in WIRING_EXEMPT: + yield path + + +def _trapped_preauth(record): + """A stand-in preauth module: check and PreauthRefused work, every other name raises.""" + module = types.ModuleType("preauth") + + class PreauthRefused(Exception): + pass + + def check(*args, **kwargs): + record.append(("allowed", "check")) + error = PreauthRefused("preauth-wiring trap") + error.reason = "envelope_signer_untrusted" + raise error + + def trap(name): + if name.startswith("__") and name.endswith("__"): + raise AttributeError(name) + record.append(("forbidden", name)) + raise AttributeError("preauth-wiring freeze: only check and PreauthRefused may be used, not " + name) + + module.check, module.PreauthRefused = check, PreauthRefused + module.__getattr__ = trap + return module + + +class WiringFreezeTest(unittest.TestCase): + """Frozen for the separate slice preauth-wiring; holds at RED and must keep holding.""" + + def test_gate_and_lane_reference_only_check_from_preauth(self): + """Frozen for preauth-wiring: the gate and lane may use preauth.check and PreauthRefused only.""" + for path in (ROOT / ".github" / "scripts" / "lease_tamper.py", ROOT / "scripts" / "merge_lane_v5.py"): + self.assertEqual(wiring_violations(path.read_text(encoding="utf-8")), [], path.name) + + def test_every_file_under_github_and_scripts_obeys_the_wiring_rule(self): + scanned = 0 + for path in _wiring_targets(): + try: + text = path.read_text(encoding="utf-8") + except UnicodeDecodeError: + continue + scanned += 1 + got = wiring_violations(text) if path.suffix == ".py" else wiring_text_violations(text) + self.assertEqual(got, [], str(path.relative_to(ROOT))) + self.assertGreater(scanned, 5) + + #: each wiring fixture and the violation it must raise (GROKCHAT round 4 first) + WIRING_MUST_FAIL = { + "control_direct.py": "preauth_name:verify_signature", + "from_pkg_alias.py": "preauth_name:verify_signature", + "importlib_load.py": "dynamic_import:importlib", + "getattr_name.py": "preauth_getattr", + "private_via_getattr.py": "preauth_getattr", + "dotted_import.py": "preauth_name:oracle_paths", + "from_import_name.py": "preauth_name:oracle_paths", + "star_import.py": "preauth_name:*", + "module_value.py": "preauth_module_value:preauth", + "module_rebind.py": "preauth_module_value:preauth", + "getattr_constant_private.py": "preauth_getattr", + "getattr_computed_elsewhere.py": "getattr_computed", + "verify_module_import.py": "verify_import", + "verify_module_dotted.py": "verify_import", + "private_name_string.py": "private_name_string", + "private_name.py": "private_name:_ssh_verify", + "runpy_load.py": "dynamic_import:runpy", + "dunder_import.py": "dynamic_code:__import__", + "exec_code.py": "dynamic_code:exec", + "sys_modules.py": "sys_modules", + "workflow_inline.yml": "preauth_in_text", + "shell_inline.sh": "preauth_in_text", + } + + def test_wiring_must_fail_fixtures_are_caught(self): + found = sorted(p.name for p in WIRING_FIXTURES.iterdir() if p.is_file()) + self.assertEqual(found, sorted(self.WIRING_MUST_FAIL)) + for name, code in self.WIRING_MUST_FAIL.items(): + text = (WIRING_FIXTURES / name).read_text(encoding="utf-8") + got = wiring_violations(text) if name.endswith(".py") else wiring_text_violations(text) + self.assertIn(code, got, name) + + def test_preauth_names_other_than_check_raise_on_the_lane_and_gate_paths(self): + record = [] + trapped = _trapped_preauth(record) + saved = {name: sys.modules.get(name) for name in ("preauth", "scripts.preauth")} + sys.modules["preauth"] = sys.modules["scripts.preauth"] = trapped + try: + # the trap itself: a forbidden name raises and is recorded, check is allowed + probe = types.ModuleType("probe") + exec("import preauth\ntry:\n preauth.oracle_paths\nexcept AttributeError:\n pass\n", probe.__dict__) + self.assertEqual(record, [("forbidden", "oracle_paths")]) + del record[:] + lane = self._load(ROOT / "scripts" / "merge_lane_v5.py", "lane_wiring_trap") + gate = self._load(ROOT / ".github" / "scripts" / "lease_tamper.py", "gate_wiring_trap") + for facts in ({}, {"pr": {"number": 12, "state": "OPEN", "head": "a" * 40, "files": []}, + "class": getattr(lane, "NON_SLICE", "non-slice"), "reviews": [], "checks": [], + "required_checks": [], "lease_tamper": {"ran": True, "ok": True}}): + with contextlib.suppress(Exception): + lane.decide(facts) + repo, base, head = self._git_repo() + out = io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out), \ + contextlib.suppress(Exception, SystemExit): + gate.main(["--repo", str(repo), "--base", base, "--head", head, "--quiet"], environ={}) + finally: + for name, module in saved.items(): + if module is None: + sys.modules.pop(name, None) + else: + sys.modules[name] = module + self.assertEqual([name for kind, name in record if kind == "forbidden"], []) + + def _load(self, path, name): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + def _git_repo(self): + repo = Path(tempfile.mkdtemp(prefix="preauth-wiring-")) + self.addCleanup(shutil.rmtree, repo, True) + git = ["git", "-C", str(repo), "-c", "user.name=t", "-c", "user.email=t@example.invalid", + "-c", "commit.gpgsign=false"] + subprocess.run(git[:3] + ["init", "-q"], check=True, capture_output=True) + (repo / "README.md").write_text("base\n") + subprocess.run(git + ["add", "-A"], check=True, capture_output=True) + subprocess.run(git + ["commit", "-q", "-m", "base"], check=True, capture_output=True) + base = subprocess.run(git + ["rev-parse", "HEAD"], check=True, capture_output=True, text=True).stdout.strip() + (repo / "docs.md").write_text("change\n") + subprocess.run(git + ["add", "-A"], check=True, capture_output=True) + subprocess.run(git + ["commit", "-q", "-m", "docs: change"], check=True, capture_output=True) + head = subprocess.run(git + ["rev-parse", "HEAD"], check=True, capture_output=True, text=True).stdout.strip() + return repo, base, head + + +# --------------------------------------------------------------- static process rule (r4: allowlists) +SSH_KEYGEN = "/usr/bin/ssh-keygen" +SSH_ENV = {"PATH": "/usr/bin:/bin"} +SSH_ARGV = (SSH_KEYGEN, "-Y", "verify", "-f", None, "-I", None, "-n", None, "-s", None) +CALL_KEYWORDS = {"input", "capture_output", "timeout", "check", "env"} +#: Modules preauth.py may import (plain ``import x``, top level, no alias). +ALLOWED_IMPORTS = {"base64", "binascii", "hashlib", "json", "os", "posixpath", "re", "subprocess", "tempfile"} +#: ``from x import y`` allowed only for these names. +ALLOWED_FROM = {"__future__": {"annotations"}, "datetime": {"datetime", "timezone", "timedelta"}} +#: The only attributes reachable on each imported module. +MODULE_ATTRS = { + "os": {"path", "fspath", "fsencode", "fsdecode", "sep"}, + "os.path": {"join", "dirname", "abspath", "basename", "normpath", "realpath", "isfile"}, + "posixpath": {"normpath", "join", "dirname", "basename"}, + "subprocess": {"run", "SubprocessError", "TimeoutExpired", "CalledProcessError"}, + "tempfile": {"TemporaryDirectory", "NamedTemporaryFile"}, + "json": {"loads", "dumps", "JSONDecodeError"}, + "re": {"compile", "fullmatch", "match", "search", "escape", "ASCII", "IGNORECASE"}, + "hashlib": {"sha256"}, + "base64": {"b64decode", "b64encode"}, + "binascii": {"Error"}, +} +BANNED_NAMES = {"eval", "exec", "compile", "getattr", "setattr", "delattr", "globals", "locals", "vars", + "breakpoint", "input", "help", "license", "credits", "copyright", "exit", "quit", "memoryview"} +ALLOWED_DUNDER_NAMES = {"__file__", "__name__"} +#: Attribute names banned on ANY object (process, environment, permissions, frames). +BANNED_ATTRS = re.compile(r"^(environ|environb|putenv|unsetenv|chmod|fchmod|lchmod|chown|lchown|fchown|system|" + r"popen|startfile|kill|killpg|fork.*|exec.*|spawn.*|posix_spawn.*|Popen|call|" + r"check_call|check_output|getoutput|getstatusoutput|run|gi_frame|gi_code|cr_frame|" + r"ag_frame|tb_frame|f_globals|f_locals|f_builtins|f_back|f_code|co_code)$") +PROTECTED_NAMES = {"open", "print", "isinstance", "type"} + + +def _dotted(node): + parts = [] + while isinstance(node, ast.Attribute): + parts.append(node.attr) + node = node.value + if isinstance(node, ast.Name): + parts.append(node.id) + return ".".join(reversed(parts)) + return None + + +def _write_mode(call): + mode = None + if len(call.args) >= 2: + mode = call.args[1] + for kw in call.keywords: + if kw.arg == "mode": + mode = kw.value + if kw.arg is None or kw.arg == "opener": + return True + if mode is None: + return False + if not (isinstance(mode, ast.Constant) and isinstance(mode.value, str)): + return True + return any(ch in mode.value for ch in "wax+") + + +#: Module attributes that may be used as plain values (everything else must be called directly). +PROCESS_VALUE_ATTRS = {"os.path", "os.sep", "re.ASCII", "re.IGNORECASE"} + + +def _parents(tree): + parents = {} + for node in ast.walk(tree): + for child in ast.iter_child_nodes(node): + parents[id(child)] = node + return parents + + +def _is_call_func(node, parents): + parent = parents.get(id(node)) + return isinstance(parent, ast.Call) and parent.func is node + + +def _in_except_type(node, parents): + child, parent = node, parents.get(id(node)) + while isinstance(parent, ast.Tuple): + child, parent = parent, parents.get(id(parent)) + return isinstance(parent, ast.ExceptHandler) and parent.type is child + + +def process_violations(source): + """Violations of the one-process rule; [] means the module can only start ssh-keygen -Y verify.""" + try: + tree = ast.parse(source) + except SyntaxError as exc: + return ["syntax_error:%s" % exc.lineno] + out = [] + modules = set() + from_names = set() + top = set(id(n) for n in tree.body) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + if id(node) not in top: + out.append("nested_import") + for alias in node.names: + if alias.name == "subprocess" and alias.asname: + out.append("subprocess_alias") + if alias.name not in ALLOWED_IMPORTS: + out.append("import_not_allowed:" + alias.name) + elif alias.asname: + out.append("import_alias:" + alias.name) + else: + modules.add(alias.name) + elif isinstance(node, ast.ImportFrom): + if id(node) not in top: + out.append("nested_import") + mod = node.module or "" + if mod.split(".")[0] == "subprocess": + out.append("from_subprocess_import") + allowed = ALLOWED_FROM.get(mod) if node.level == 0 else None + for alias in node.names: + if allowed is None or alias.name not in allowed or alias.asname: + out.append("import_not_allowed:%s.%s" % (mod, alias.name)) + else: + from_names.add(alias.name) + bound = modules | from_names | PROTECTED_NAMES + parents = {} + for node in ast.walk(tree): + for child in ast.iter_child_nodes(node): + parents[id(child)] = node + calls = [] + for node in ast.walk(tree): + # rebinding or shadowing a module, an imported name or a protected builtin + targets = [] + if isinstance(node, (ast.Assign, ast.AugAssign, ast.AnnAssign, ast.For, ast.AsyncFor, ast.NamedExpr)): + targets = node.targets if isinstance(node, ast.Assign) else [node.target] + elif isinstance(node, (ast.With, ast.AsyncWith)): + targets = [item.optional_vars for item in node.items if item.optional_vars is not None] + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + if node.name in bound: + out.append("rebind:" + node.name) + elif isinstance(node, ast.arg) and node.arg in bound: + out.append("rebind:" + node.arg) + elif isinstance(node, ast.ExceptHandler) and node.name in bound: + out.append("rebind:" + node.name) + elif isinstance(node, (ast.Global, ast.Nonlocal)): + out.append("global_statement") + elif isinstance(node, ast.Delete): + targets = node.targets + for target in targets: + for sub in ast.walk(target): + if isinstance(sub, ast.Name) and sub.id in bound: + out.append("rebind:" + sub.id) + if isinstance(node, ast.Name): + if node.id in BANNED_NAMES: + out.append("banned_name:" + node.id) + if node.id.startswith("__") and node.id.endswith("__") and node.id not in ALLOWED_DUNDER_NAMES: + out.append("dunder_name:" + node.id) + if BANNED_ATTRS.match(node.id): + out.append("banned_identifier:" + node.id) + if node.id in modules: + parent = parents.get(id(node)) + if not (isinstance(parent, ast.Attribute) and parent.value is node): + out.append("module_reference:" + node.id) + else: + attr = parent.attr + if attr not in MODULE_ATTRS.get(node.id, set()): + out.append("module_attr:%s.%s" % (node.id, attr)) + elif node.id == "os" and attr == "path": + grand = parents.get(id(parent)) + if not (isinstance(grand, ast.Attribute) and grand.value is parent + and grand.attr in MODULE_ATTRS["os.path"]): + out.append("module_reference:os.path") + if node.id == "open": + parent = parents.get(id(node)) + if not (isinstance(parent, ast.Call) and parent.func is node): + out.append("open_reference") + elif _write_mode(parent): + out.append("write_mode_open") + elif isinstance(node, ast.Attribute): + if node.attr.startswith("_"): + out.append("private_or_dunder_attr:" + node.attr) + dotted = _dotted(node) + if BANNED_ATTRS.match(node.attr) and dotted != "subprocess.run": + out.append("banned_attr:" + node.attr) + elif isinstance(node, ast.Constant) and isinstance(node.value, str): + text = node.value.strip().lower() + if text == "sign" or re.search(r"-y\s*sign", text): + out.append("sign_literal") + elif isinstance(node, ast.Lambda): + out.append("lambda") + if isinstance(node, ast.Call): + func = node.func + if isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name) and func.value.id == "subprocess": + calls.append(node) + # r5 (GROKCHAT round 4): no value use of a module attribute, no decorators, class keywords, + # dunder defs, match or format; tempfile only with a constant suffix + for node in ast.walk(tree): + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and node.decorator_list: + out.append("decorator") + if isinstance(node, ast.ClassDef) and node.keywords: + out.append("class_keyword") + if (isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node.name.startswith("__") and node.name.endswith("__")): + out.append("dunder_def:" + node.name) + if isinstance(node, ast.Match): + out.append("match_statement") + if isinstance(node, ast.Attribute) and node.attr in ("format", "format_map"): + out.append("format_attr:" + node.attr) + if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id in modules: + dotted = node.value.id + "." + node.attr + if not (dotted in PROCESS_VALUE_ATTRS or _is_call_func(node, parents) + or _in_except_type(node, parents)): + out.append("module_attr_value:" + dotted) + if isinstance(node, ast.Call) and _dotted(node.func) in ("tempfile.NamedTemporaryFile", + "tempfile.TemporaryDirectory"): + kws = node.keywords + if node.args or len(kws) != 1 or kws[0].arg != "suffix" or not ( + isinstance(kws[0].value, ast.Constant) and isinstance(kws[0].value.value, str)): + out.append("tempfile_args") + if len(calls) != 1: + out.append("process_calls:%d" % len(calls)) + for call in calls: + if call.func.attr != "run": + out.append("subprocess_attr:" + call.func.attr) + if len(call.args) != 1: + out.append("argv_args") + continue + argv = call.args[0] + if not isinstance(argv, ast.List) or len(argv.elts) != len(SSH_ARGV): + out.append("argv_shape") + else: + for want, got in zip(SSH_ARGV, argv.elts): + if want is None: + if not isinstance(got, ast.Name): + out.append("argv_computed") + elif not (isinstance(got, ast.Constant) and got.value == want): + out.append("argv_shape" if want != SSH_KEYGEN else "ssh_keygen_not_absolute") + names = [k.arg for k in call.keywords] + if None in names or any(k not in CALL_KEYWORDS for k in names if k): + out.append("call_keyword") + if "timeout" not in names: + out.append("call_timeout_missing") + env = [k.value for k in call.keywords if k.arg == "env"] + if not env: + out.append("call_env_missing") + else: + node = env[0] + ok = (isinstance(node, ast.Dict) and len(node.keys) == 1 + and all(isinstance(x, ast.Constant) for x in node.keys + node.values) + and {k.value: v.value for k, v in zip(node.keys, node.values)} == SSH_ENV) + if not ok: + out.append("call_env_not_constant") + for node in ast.walk(tree): + if isinstance(node, ast.Constant) and node.value == "-f": + in_slot = any(isinstance(c.args[0], ast.List) and len(c.args[0].elts) > 3 + and c.args[0].elts[3] is node for c in calls if c.args) + if not in_slot: + out.append("f_literal") + return sorted(set(out)) + + +class ProcessRuleTest(unittest.TestCase): + MUST_FAIL = ("split_string_sign", "popen_alias", "import_alias", "os_system", "os_exec", "posixsubprocess", + "ctypes_libc", "importlib_subprocess", "dunder_import", "eval_exec", "joined_argv", + "fstring_argv", "computed_argv", "extra_args", "executable_kw", "shell_true", + "getattr_popen", "sys_modules", "asyncio_subprocess", "sign_literal", "two_calls", + "no_timeout") + #: r4 stubs (GROKCHAT round 3 bypasses and the new bans), each with the violation it must raise. + MUST_FAIL_R4 = { + "os_name_alias": "module_reference:os", + "rebind_subprocess": "rebind:subprocess", + "os_getattribute": "private_or_dunder_attr:__getattribute__", + "object_getattribute": "private_or_dunder_attr:__getattribute__", + "operator_attrgetter": "import_not_allowed:operator", + "timeit_exec": "import_not_allowed:timeit", + "cprofile_exec": "import_not_allowed:cProfile", + "type_lambda_os": "module_reference:os", + "return_os": "module_reference:os", + "webbrowser_browser": "import_not_allowed:webbrowser", + "imported_helper": "import_not_allowed:merge_lane_v5", + "path_hijack": "banned_attr:environ", + "partial_run": "import_not_allowed:functools", + "putenv": "module_attr:os.putenv", + "chmod": "module_attr:os.chmod", + "write_open": "write_mode_open", + "relative_ssh_keygen": "ssh_keygen_not_absolute", + "env_missing": "call_env_missing", + "env_computed": "call_env_not_constant", + "frame_globals": "banned_attr:f_globals", + "help_pager": "banned_name:help", + "private_module_attr": "module_attr:tempfile._os", + "nested_import": "nested_import", + } + + #: GROKCHAT round-4 stubs, committed verbatim; each must be refused for its own bypass. + MUST_FAIL_R5 = { + "run_alias": ("module_attr_value:subprocess.run",), + "walrus_run": ("module_attr_value:subprocess.run",), + "dict_run": ("module_attr_value:subprocess.run",), + "default_arg_run": ("module_attr_value:subprocess.run",), + "match_capture": ("match_statement", "module_attr_value:subprocess.run"), + "decorator_metaclass": ("decorator", "class_keyword", "dunder_def:__iter__"), + "sign_concat_alias": ("module_attr_value:subprocess.run",), + "ntf_pth": ("tempfile_args",), + "format_read": ("format_attr:format",), + } + + def stub(self, name, folder="must_fail"): + return (PROCESS_FIXTURES / folder / (name + ".py")).read_text(encoding="utf-8") + + def test_safe_verify_stub_passes_the_rule(self): + source = (PROCESS_FIXTURES / "safe_verify.py").read_text(encoding="utf-8") + self.assertEqual(process_violations(source), []) + + def test_must_fail_stubs_are_refused(self): + found = sorted(p.stem for p in (PROCESS_FIXTURES / "must_fail").glob("*.py")) + self.assertEqual(found, sorted(set(self.MUST_FAIL) | set(self.MUST_FAIL_R4) | set(self.MUST_FAIL_R5))) + for name in self.MUST_FAIL: + self.assertNotEqual(process_violations(self.stub(name)), [], name) + + def test_grokchat_split_string_and_popen_alias_stubs_are_refused(self): + split = self.stub("split_string_sign") + self.assertIn('"si" + "gn"', split) + self.assertIn("process_calls:2", process_violations(split)) + alias = self.stub("popen_alias") + self.assertIn("from_subprocess_import", process_violations(alias)) + + def test_round_three_bypass_stubs_are_refused_for_their_own_reason(self): + for name, code in self.MUST_FAIL_R4.items(): + source = self.stub(name) + if name != "relative_ssh_keygen": + self.assertIn("/usr/bin/ssh-keygen", source, name) + self.assertIn(code, process_violations(source), name) + + def test_every_r4_stub_differs_from_the_safe_stub_only_by_its_bypass(self): + safe = set((PROCESS_FIXTURES / "safe_verify.py").read_text(encoding="utf-8").splitlines()) + for name in self.MUST_FAIL_R4: + extra = [line for line in self.stub(name).splitlines() if line not in safe] + self.assertTrue(extra, name) + self.assertLessEqual(len(extra), 12, (name, extra)) + + def test_round_four_bypass_stubs_are_refused_for_their_own_reason(self): + safe = set((PROCESS_FIXTURES / "safe_verify.py").read_text(encoding="utf-8").splitlines()) + for name, codes in self.MUST_FAIL_R5.items(): + source = self.stub(name) + self.assertIn("/usr/bin/ssh-keygen", source, name) + extra = [line for line in source.splitlines() if line not in safe] + self.assertTrue(extra, name) + self.assertLessEqual(len(extra), 12, (name, extra)) + got = process_violations(source) + for code in codes: + self.assertIn(code, got, name) + + def test_frozen_verify_module_obeys_the_rule(self): + # r5: the one-process rule applies to the frozen verifier; preauth.py starts no process at all + self.assertTrue(VERIFY_MODULE.is_file(), "missing scripts/preauth_verify.py") + self.assertEqual(process_violations(VERIFY_MODULE.read_text(encoding="utf-8")), []) + + +# --------------------------------------------------------------- r5: strict allowlist over preauth.py +#: Plain ``import x`` allowed in preauth.py (top level, no alias). No os, subprocess or tempfile. +PREAUTH_IMPORTS = {"json", "hashlib", "base64", "binascii", "re"} +#: ``from x import y`` allowed only for these names; the frozen verifier's single entry point by name. +PREAUTH_FROM = {"__future__": {"annotations"}, "datetime": {"datetime", "timezone", "timedelta"}, + "preauth_verify": {VERIFY_ENTRY}} +PREAUTH_MODULE_ATTRS = { + "json": {"loads", "dumps", "JSONDecodeError"}, + "hashlib": {"sha256"}, + "base64": {"b64decode", "b64encode"}, + "binascii": {"Error"}, + "re": {"compile", "fullmatch", "match", "search", "escape", "ASCII", "IGNORECASE"}, +} +#: Module attributes usable as plain values (flags, and exception classes outside an except clause). +PREAUTH_VALUE_ATTRS = {"re.ASCII", "re.IGNORECASE", "json.JSONDecodeError", "binascii.Error"} +#: the test-only entry point and the shared private decision core check() and it both call +PREAUTH_PRIVATE_DEFS = {"_check_for_tests", "_decide"} +PREAUTH_DUNDER_NAMES = {"__file__"} +PREAUTH_BANNED_NAMES = BANNED_NAMES | {"type", "object", "super", "property", "classmethod", "staticmethod", + "format", "dir", "hasattr", "open_code", "__build_class__", "print"} +PREAUTH_BANNED_ATTRS = re.compile(BANNED_ATTRS.pattern[:-2] + r"|format|format_map|mro|modules|tb_next|" + r"ag_code|cr_code|f_lineno|f_trace|func_globals|stdout|stderr|stdin|write|writelines|" + r"displayhook|excepthook)$") +PREAUTH_PROTECTED = {"open", "isinstance", "len", "str", "int", "bool", "dict", "list", "set", "tuple", + "frozenset", "sorted", "any", "all", "min", "max", "Exception"} +PREAUTH_OPEN_MODES = {"r", "rb"} +PREAUTH_MAX_OPENS = 2 +#: r6: open() takes only one of exactly two module constants, each ``<__file__ base> + ``. +PREAUTH_OPEN_SUFFIXES = {"/policy/allowed_signers", "/policy/preauth.md"} +PREAUTH_PATH_METHODS = {"rsplit", "rpartition"} +#: r6: the one way to refuse. Every call passes exactly one literal from REFUSAL_REASONS. +PREAUTH_REFUSE_HELPER = ( + "def refuse(reason):\n" + " error = PreauthRefused(reason)\n" + " error.reason = reason\n" + " raise error\n") + + +def preauth_violations(source): + """Violations of the r5 preauth.py allowlist; [] means no process, write, tempfile or module escape.""" + try: + tree = ast.parse(source) + except SyntaxError as exc: + return ["syntax_error:%s" % exc.lineno] + out, modules, imported = [], set(), set() + top = set(id(n) for n in tree.body) + for node in ast.walk(tree): + if isinstance(node, (ast.Import, ast.ImportFrom)) and id(node) not in top: + out.append("nested_import") + if isinstance(node, ast.Import): + for alias in node.names: + if alias.name not in PREAUTH_IMPORTS: + out.append("import_not_allowed:" + alias.name) + elif alias.asname: + out.append("import_alias:" + alias.name) + else: + modules.add(alias.name) + elif isinstance(node, ast.ImportFrom): + mod = node.module or "" + if mod == "preauth_verify" and node.level == 0 and [(a.name, a.asname) for a in node.names] != [ + (VERIFY_ENTRY, None)]: + out.append("verify_import") + allowed = PREAUTH_FROM.get(mod) if node.level == 0 else None + for alias in node.names: + if allowed is None or alias.name not in allowed or alias.asname: + out.append("import_not_allowed:%s%s.%s" % ("." * node.level, mod, alias.name)) + else: + imported.add(alias.name) + bound = modules | imported | PREAUTH_PROTECTED + parents = _parents(tree) + opens = 0 + for node in ast.walk(tree): + targets = [] + if isinstance(node, (ast.Assign, ast.AugAssign, ast.AnnAssign, ast.For, ast.AsyncFor, ast.NamedExpr, + ast.comprehension)): + targets = node.targets if isinstance(node, ast.Assign) else [node.target] + elif isinstance(node, (ast.With, ast.AsyncWith)): + targets = [item.optional_vars for item in node.items if item.optional_vars is not None] + elif isinstance(node, ast.Delete): + targets = node.targets + elif isinstance(node, ast.arg) and node.arg in bound: + out.append("rebind:" + node.arg) + elif isinstance(node, ast.ExceptHandler) and node.name in bound: + out.append("rebind:" + node.name) + elif isinstance(node, (ast.Global, ast.Nonlocal)): + out.append("global_statement") + elif isinstance(node, ast.Match): + out.append("match_statement") + elif isinstance(node, ast.AsyncFunctionDef): + out.append("async_def") + for target in targets: + for sub in ast.walk(target): + if isinstance(sub, ast.Name) and sub.id in bound: + out.append("rebind:" + sub.id) + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + if node.decorator_list: + out.append("decorator") + if node.name in bound: + out.append("rebind:" + node.name) + if node.name.startswith("_") and node.name not in PREAUTH_PRIVATE_DEFS: + out.append("private_def:" + node.name) + if isinstance(node, ast.ClassDef): + if node.keywords: + out.append("class_keyword") + if not (len(node.bases) == 1 and isinstance(node.bases[0], ast.Name) and node.bases[0].id == "Exception"): + out.append("class_base") + for item in node.body: + if not (isinstance(item, ast.Pass) or (isinstance(item, ast.Expr) and isinstance(item.value, ast.Constant) + and isinstance(item.value.value, str))): + out.append("class_body") + if isinstance(node, ast.Name): + if node.id in PREAUTH_BANNED_NAMES: + out.append("banned_name:" + node.id) + if node.id.startswith("__") and node.id not in PREAUTH_DUNDER_NAMES: + out.append("dunder_name:" + node.id) + if node.id in modules: + parent = parents.get(id(node)) + if not (isinstance(parent, ast.Attribute) and parent.value is node): + out.append("module_reference:" + node.id) + elif parent.attr not in PREAUTH_MODULE_ATTRS.get(node.id, set()): + out.append("module_attr:%s.%s" % (node.id, parent.attr)) + elif not ("%s.%s" % (node.id, parent.attr) in PREAUTH_VALUE_ATTRS + or _is_call_func(parent, parents) or _in_except_type(parent, parents)): + out.append("module_attr_value:%s.%s" % (node.id, parent.attr)) + if node.id == "open": + parent = parents.get(id(node)) + if not (isinstance(parent, ast.Call) and parent.func is node): + out.append("open_reference") + else: + opens += 1 + out.extend(_preauth_open(parent)) + elif isinstance(node, ast.Attribute): + if node.attr.startswith("_"): + out.append("private_or_dunder_attr:" + node.attr) + if PREAUTH_BANNED_ATTRS.match(node.attr): + out.append("banned_attr:" + node.attr) + if opens > PREAUTH_MAX_OPENS: + out.append("open_calls:%d" % opens) + out.extend(preauth_r6_violations(tree)) + return sorted(set(out)) + + +def _file_base(node): + """True for __file__, or __file__ narrowed by rsplit/rpartition with literal args and int indexes.""" + if isinstance(node, ast.Name): + return node.id == "__file__" + if isinstance(node, ast.Subscript): + return (isinstance(node.slice, ast.Constant) and type(node.slice.value) is int + and _file_base(node.value)) + if isinstance(node, ast.Call): + return (isinstance(node.func, ast.Attribute) and node.func.attr in PREAUTH_PATH_METHODS + and not node.keywords and node.args + and all(isinstance(a, ast.Constant) and (type(a.value) is int or ( + isinstance(a.value, str) and a.value and ".." not in a.value)) for a in node.args) + and _file_base(node.func.value)) + return False + + +def _open_path_suffix(value): + if (isinstance(value, ast.BinOp) and isinstance(value.op, ast.Add) and isinstance(value.right, ast.Constant) + and value.right.value in PREAUTH_OPEN_SUFFIXES and _file_base(value.left)): + return value.right.value + return None + + +def _canonical_refuse(node): + body = node.body[1:] if (node.body and isinstance(node.body[0], ast.Expr) + and isinstance(node.body[0].value, ast.Constant)) else node.body + shape = ast.FunctionDef(name=node.name, args=node.args, body=body, decorator_list=node.decorator_list, + returns=node.returns, type_comment=None, type_params=[]) + want = ast.parse(PREAUTH_REFUSE_HELPER).body[0] + want.type_params = [] + return ast.dump(shape) == ast.dump(want) + + +def preauth_r6_violations(tree): + """r6 additions: pinned open() paths, a closed set of literal refusal reasons, one refuse() helper.""" + out, parents = [], _parents(tree) + constants, file_ok = {}, set() + for node in tree.body: + if isinstance(node, ast.Assign) and any(isinstance(n, ast.Name) and n.id == "__file__" + for n in ast.walk(node.value)): + name = node.targets[0].id if len(node.targets) == 1 and isinstance(node.targets[0], ast.Name) else None + suffix = _open_path_suffix(node.value) + if name is None or not name.isupper() or suffix is None: + out.append("open_path_constant_invalid:%s" % (name or "?")) + else: + constants[name] = suffix + file_ok.update(id(n) for n in ast.walk(node.value)) + if len(constants) != 2 or set(constants.values()) != PREAUTH_OPEN_SUFFIXES: + out.append("open_path_constants:%d" % len(constants)) + stores, opened = {}, set() + helpers = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "refuse"] + helper = helpers[0] if len(helpers) == 1 and _canonical_refuse(helpers[0]) else None + if helpers and helper is None: + out.append("refuse_helper_not_canonical") + inside = set(id(n) for n in ast.walk(helper)) if helper is not None else set() + for node in ast.walk(tree): + for name in ([node.id] if isinstance(node, ast.Name) and not isinstance(node.ctx, ast.Load) else + [node.arg] if isinstance(node, ast.arg) else + [node.name] if isinstance(node, (ast.FunctionDef, ast.ClassDef, ast.ExceptHandler)) + and node.name else + [a.asname or a.name for a in node.names] if isinstance(node, (ast.Import, ast.ImportFrom)) + else []): + stores[name] = stores.get(name, 0) + 1 + if isinstance(node, ast.Name) and node.id == "__file__" and id(node) not in file_ok: + out.append("file_reference") + if isinstance(node, ast.ClassDef) and node.name != "PreauthRefused": + out.append("class_name:" + node.name) + if isinstance(node, ast.Raise) and id(node) not in inside: + out.append("raise_statement") + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "open": + first = node.args[0] if node.args else None + if isinstance(first, ast.Name) and first.id in constants: + opened.add(first.id) + else: + out.append("open_path_not_constant") + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load): + parent = parents.get(id(node)) + if node.id == "PreauthRefused" and id(node) not in inside and not _in_except_type(node, parents): + out.append("refusal_outside_helper") + if node.id == "refuse": + if not (isinstance(parent, ast.Call) and parent.func is node and len(parent.args) == 1 + and not parent.keywords and isinstance(parent.args[0], ast.Constant) + and parent.args[0].value in REFUSAL_REASONS): + out.append("reason_not_enumerated") + for name in list(constants) + ["refuse", "PreauthRefused"]: + if stores.get(name, 0) > 1: + out.append("rebind:" + name) + for name in constants: + if name not in opened: + out.append("open_path_unused:" + name) + if helper is None: + out.append("refuse_helper_missing") + return sorted(set(out)) + + +def _preauth_open(call): + mode = call.args[1] if len(call.args) >= 2 else None + out = [] + if len(call.args) > 2: + out.append("open_args") + for kw in call.keywords: + if kw.arg == "mode": + mode = kw.value + elif kw.arg != "encoding": + out.append("write_mode_open" if kw.arg in (None, "opener") else "open_args") + if mode is None or not (isinstance(mode, ast.Constant) and isinstance(mode.value, str)): + out.append("open_mode_not_literal") + elif mode.value not in PREAUTH_OPEN_MODES: + out.append("write_mode_open") + return out + + +class PreauthRuleTest(unittest.TestCase): + """r5: preauth.py is parsing and policy only; the rule is a strict allowlist, not a denylist.""" + + #: preauth.py-shaped stubs (safe_preauth.py plus a bypass), each with the violation it must raise + MUST_FAIL = { + "module_alias": "module_reference:re", + "walrus_alias": "module_reference:re", + "dict_alias": "module_reference:re", + "default_arg_alias": "module_reference:re", + "match_capture": "match_statement", + "decorator_def": "decorator", + "class_metaclass": "class_keyword", + "dunder_def": "private_def:__iter__", + "split_string_sign": "module_attr:re.enum", + "ntf_pth": "import_not_allowed:tempfile", + "format_leak": "banned_attr:format", + "format_map_leak": "banned_attr:format_map", + "import_subprocess": "import_not_allowed:subprocess", + "import_os": "import_not_allowed:os", + "import_datetime_module": "import_not_allowed:datetime", + "verify_module_import": "import_not_allowed:preauth_verify", + "verify_import_extra": "verify_import", + "verify_import_alias": "verify_import", + "relative_import": "import_not_allowed:..preauth_verify", + "star_import": "import_not_allowed:json.*", + "json_decoder_chain": "module_attr:json.decoder", + "re_enum_chain": "module_attr:re.enum", + "module_attr_value": "module_attr_value:json.loads", + "nested_import": "nested_import", + "getattr_computed": "banned_name:getattr", + "eval_code": "banned_name:eval", + "exec_code": "banned_name:exec", + "compile_code": "banned_name:compile", + "dunder_import": "dunder_name:__import__", + "dunder_attr": "private_or_dunder_attr:__globals__", + "private_attr": "private_or_dunder_attr:_private", + "frame_walk": "banned_attr:gi_frame", + "breakpoint_hook": "banned_name:breakpoint", + "help_pager": "banned_name:help", + "type_three_arg": "banned_name:type", + "builtins_name": "dunder_name:__builtins__", + "rebind_module": "rebind:json", + "rebind_entry": "rebind:_ssh_verify", + "rebind_in_comprehension": "rebind:re", + "global_statement": "global_statement", + "private_def": "private_def:_helper", + "class_base": "class_base", + "class_body": "class_body", + "class_decorator": "decorator", + "write_open": "write_mode_open", + "append_open": "write_mode_open", + "open_computed_mode": "open_mode_not_literal", + "open_without_mode": "open_mode_not_literal", + "open_opener": "write_mode_open", + "open_reference": "open_reference", + "three_opens": "open_calls:3", + } + + def stub(self, name): + return (PROCESS_FIXTURES / "preauth_must_fail" / (name + ".py")).read_text(encoding="utf-8") + + def test_safe_preauth_stub_passes_the_rule(self): + self.assertEqual(preauth_violations((PROCESS_FIXTURES / "safe_preauth.py").read_text(encoding="utf-8")), []) + + def test_every_preauth_stub_is_refused_for_its_own_reason(self): + found = sorted(p.stem for p in (PROCESS_FIXTURES / "preauth_must_fail").glob("*.py")) + self.assertEqual(found, sorted(self.MUST_FAIL)) + # the r5 stubs were cut from the r5 control, kept verbatim as safe_preauth_r5.py + safe = set((PROCESS_FIXTURES / "safe_preauth_r5.py").read_text(encoding="utf-8").splitlines()) + for name, code in self.MUST_FAIL.items(): + source = self.stub(name) + extra = [line for line in source.splitlines() if line not in safe] + self.assertTrue(extra, name) + self.assertLessEqual(len(extra), 12, (name, extra)) + self.assertIn(code, preauth_violations(source), name) + + #: r6 stubs (safe_preauth.py plus one bypass): reads beyond the two pinned files, print and + #: stdout/stderr writes, and refusal reasons that could carry file contents. + MUST_FAIL_R6 = { + "proc_environ_literal": "open_path_not_constant", + "proc_environ_constant": "open_path_not_constant", + "file_relative_secret": "open_path_constant_invalid:SECRET", + "dotdot_in_base": "open_path_constant_invalid:POLICY", + "third_constant": "open_path_constants:3", + "file_reference": "file_reference", + "rebind_constant": "rebind:TRUST_ROOT", + "loop_many_reads": "open_path_not_constant", + "loop_over_constants": "open_path_not_constant", + "parameter_shadows_constant": "rebind:TRUST_ROOT", + "open_keyword_path": "open_path_not_constant", + "print_leak": "banned_name:print", + "print_hook": "banned_name:print", + "stdout_write": "banned_attr:stdout", + "stderr_write": "banned_attr:stderr", + "write_attr": "banned_attr:write", + "reason_interpolated": "reason_not_enumerated", + "reason_fstring": "reason_not_enumerated", + "reason_unknown": "reason_not_enumerated", + "reason_variable": "reason_not_enumerated", + "reason_keyword": "reason_not_enumerated", + "refuse_reference": "reason_not_enumerated", + "direct_raise": "raise_statement", + "raise_other": "raise_statement", + "refusal_alias": "refusal_outside_helper", + "helper_not_canonical": "refuse_helper_not_canonical", + "second_class": "class_name:Leak", + } + #: GROKCHAT round-5 stubs, committed verbatim (cut from the r5 control). + GROKCHAT_R5 = { + "secret_read_print": ("banned_name:print", "open_path_not_constant"), + "loop_many_reads": ("open_path_not_constant",), + "file_relative_read": ("file_reference", "reason_not_enumerated", "open_path_not_constant"), + "lambda_json_hook": ("banned_name:print",), + } + + def test_round_six_stubs_are_refused_for_their_own_reason(self): + folder = PROCESS_FIXTURES / "preauth_must_fail_r6" + self.assertEqual(sorted(p.stem for p in folder.glob("*.py")), sorted(self.MUST_FAIL_R6)) + safe = set((PROCESS_FIXTURES / "safe_preauth.py").read_text(encoding="utf-8").splitlines()) + for name, code in self.MUST_FAIL_R6.items(): + source = (folder / (name + ".py")).read_text(encoding="utf-8") + extra = [line for line in source.splitlines() if line not in safe] + self.assertTrue(extra, name) + self.assertLessEqual(len(extra), 12, (name, extra)) + self.assertIn(code, preauth_violations(source), name) + + def test_grokchat_round_five_stubs_are_refused(self): + folder = PROCESS_FIXTURES / "grokchat_r5" + self.assertEqual(sorted(p.stem for p in folder.glob("*.py")), sorted(self.GROKCHAT_R5)) + self.assertIn('open("/proc/self/environ", "rb")', (folder / "secret_read_print.py").read_text(encoding="utf-8")) + for name, codes in self.GROKCHAT_R5.items(): + got = preauth_violations((folder / (name + ".py")).read_text(encoding="utf-8")) + for code in codes: + self.assertIn(code, got, name) + # the r5 control itself now fails: it opens a parameter and builds refusals in a helper call + self.assertIn("open_path_not_constant", + preauth_violations((PROCESS_FIXTURES / "safe_preauth_r5.py").read_text(encoding="utf-8"))) + + def test_every_earlier_process_stub_is_refused_by_the_preauth_rule(self): + stubs = sorted((PROCESS_FIXTURES / "must_fail").glob("*.py")) + self.assertGreaterEqual(len(stubs), 54) + for path in stubs + [PROCESS_FIXTURES / "safe_verify.py"]: + self.assertNotEqual(preauth_violations(path.read_text(encoding="utf-8")), [], path.name) + + def test_the_frozen_verifier_could_not_live_in_preauth_py(self): + # the process code is only allowed in the frozen file; the same code in preauth.py is refused + got = preauth_violations(VERIFY_MODULE.read_text(encoding="utf-8")) + self.assertIn("import_not_allowed:subprocess", got) + self.assertIn("import_not_allowed:tempfile", got) + + def test_preauth_module_obeys_the_preauth_rule(self): + self.assertTrue(MODULE.is_file(), "missing scripts/preauth.py") + self.assertEqual(preauth_violations(MODULE.read_text(encoding="utf-8")), []) + + def test_preauth_imports_only_the_frozen_entry_point_by_name(self): + self.assertTrue(MODULE.is_file(), "missing scripts/preauth.py") + tree = ast.parse(MODULE.read_text(encoding="utf-8")) + froms = [n for n in tree.body if isinstance(n, ast.ImportFrom) and n.module == "preauth_verify"] + self.assertEqual(len(froms), 1) + self.assertEqual([(a.name, a.asname) for a in froms[0].names], [(VERIFY_ENTRY, None)]) + pre = load_module() + entry = getattr(pre, VERIFY_ENTRY) + self.assertEqual(Path(inspect.getsourcefile(entry)).resolve(), VERIFY_MODULE.resolve()) + self.assertEqual(hashlib.sha256(VERIFY_MODULE.read_bytes()).hexdigest(), PREAUTH_VERIFY_SHA256) + + def test_a_decision_runs_the_frozen_verifier_exactly_once(self): + keys = Keys() + self.addCleanup(keys.close) + pre = load_module() + data = json.dumps(envelope(), sort_keys=True).encode("utf-8") + seen = [] + real = getattr(pre, VERIFY_ENTRY) + + def spy(*args): + seen.append(args) + return real(*args) + + signature = keys.sign(data) + with mock.patch.object(pre, VERIFY_ENTRY, spy), ProcessRecorder(self) as recorder: + decision = pre._check_for_tests( + data, signature, allowed_signers=str(keys.signers), + allowed_signers_bytes=keys.signers.read_bytes(), policy_bytes=TEST_POLICY, + trusted_fingerprints=frozenset({keys.fingerprint}), repo=REPO, base_rev=CURRENT_BASE, + contract_sha256=CONTRACT, tier="T3", now=NOW, facts=facts(), + is_ancestor=lambda older, newer: older == SIGNED_BASE and newer == CURRENT_BASE) + self.assertTrue(decision["ok"]) + self.assertEqual(len(seen), 1) + self.assertEqual(seen[0][0], data) + self.assertEqual(seen[0][3], "kyle") + self.assertEqual(len(recorder.calls), 1) + + +# --------------------------------------------------------------- r5: the frozen verifier itself +def load_verify(name="preauth_verify_under_test"): + spec = importlib.util.spec_from_file_location(name, VERIFY_MODULE) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class FrozenVerifyModuleTest(unittest.TestCase): + """scripts/preauth_verify.py is committed at RED, frozen by sha256, and tested with real keys.""" + + @classmethod + def setUpClass(cls): + cls.keys = Keys() + cls.mod = load_verify() + cls.data = json.dumps(envelope(), sort_keys=True).encode("utf-8") + cls.sig = cls.keys.sign(cls.data) + + @classmethod + def tearDownClass(cls): + cls.keys.close() + + def verify(self, data=None, signature=None, signers=None, issuer="kyle", fail=None, hook=None): + with ProcessRecorder(self, fail) as recorder: + recorder.hook = hook + result = getattr(self.mod, VERIFY_ENTRY)( + self.data if data is None else data, self.sig if signature is None else signature, + str(self.keys.signers) if signers is None else signers, issuer) + return result, recorder + + def test_module_is_frozen_by_sha256(self): + self.assertEqual(hashlib.sha256(VERIFY_MODULE.read_bytes()).hexdigest(), PREAUTH_VERIFY_SHA256, + "scripts/preauth_verify.py is frozen; a change needs an owner-approved contract") + + def test_every_name_it_defines_is_private(self): + tree = ast.parse(VERIFY_MODULE.read_text(encoding="utf-8")) + defined = [] + for node in tree.body: + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + defined.append(node.name) + elif isinstance(node, ast.Assign): + defined.extend(t.id for t in node.targets if isinstance(t, ast.Name)) + self.assertIn(VERIFY_ENTRY, defined) + self.assertEqual([n for n in defined if not n.startswith("_")], []) + public = {n for n in dir(self.mod) if not n.startswith("_")} + self.assertEqual(public, {"subprocess", "tempfile"}) + + def test_exactly_one_literal_ssh_keygen_verify_call(self): + tree = ast.parse(VERIFY_MODULE.read_text(encoding="utf-8")) + calls = [n for n in ast.walk(tree) if isinstance(n, ast.Call) and _dotted(n.func) == "subprocess.run"] + self.assertEqual(len(calls), 1) + argv = calls[0].args[0] + self.assertEqual([e.value for e in argv.elts[:4] if isinstance(e, ast.Constant)], + ["/usr/bin/ssh-keygen", "-Y", "verify", "-f"]) + self.assertEqual(process_violations(VERIFY_MODULE.read_text(encoding="utf-8")), []) + self.assertEqual(self.mod._NAMESPACE, "rizzstack-preauth") + self.assertTrue(0 < self.mod._TIMEOUT_SECONDS <= 60) + + def test_a_real_ed25519_signature_verifies(self): + result, recorder = self.verify() + self.assertIs(result, True) + self.assertEqual(len(recorder.calls), 1) + argv = recorder.calls[0] + self.assertEqual(argv[:5], ["/usr/bin/ssh-keygen", "-Y", "verify", "-f", str(self.keys.signers)]) + self.assertEqual(argv[5:9], ["-I", "kyle", "-n", "rizzstack-preauth"]) + self.assertEqual(argv[9], "-s") + self.assertEqual(recorder.envs, [{"PATH": "/usr/bin:/bin"}]) + + def test_tampered_foreign_wrong_namespace_or_wrong_principal_is_false(self): + other = Keys() + self.addCleanup(other.close) + tampered = json.dumps(envelope(max_uses=1), sort_keys=True).encode("utf-8") + for kwargs in ({"data": tampered}, {"signature": other.sign(self.data)}, + {"signature": self.keys.sign(self.data, namespace="git")}, {"issuer": "bob"}, + {"signature": b"not a signature"}): + result, _ = self.verify(**kwargs) + self.assertIs(result, False, kwargs) + + def test_signature_goes_to_a_private_temp_file_that_is_removed(self): + seen = {} + + def hook(argv): + path = Path(argv[argv.index("-s") + 1]) + seen["path"], seen["mode"], seen["bytes"] = path, path.stat().st_mode & 0o777, path.read_bytes() + + result, _ = self.verify(hook=hook) + self.assertIs(result, True) + self.assertEqual(seen["mode"], 0o600) + self.assertEqual(seen["path"].suffix, ".sig") + self.assertEqual(seen["path"].parent.resolve(), Path(tempfile.gettempdir()).resolve()) + self.assertEqual(seen["bytes"], self.sig) + self.assertFalse(seen["path"].exists()) + + def test_missing_or_hanging_ssh_keygen_is_unavailable(self): + result, _ = self.verify(fail="missing") + self.assertIsNone(result) + result, recorder = self.verify(fail="timeout") + self.assertIsNone(result) + self.assertTrue(recorder.timeouts and all(t is not None and 0 < t <= 60 for t in recorder.timeouts[:1])) + + def test_unsafe_inputs_are_false_without_starting_a_process(self): + for kwargs in ({"issuer": "-kyle"}, {"issuer": "ky*"}, {"issuer": "kyle,bob"}, {"issuer": ""}, + {"issuer": "k" * 65}, {"issuer": 7}, {"issuer": "kyle\n"}, {"issuer": "kyle bob"}, + {"signers": "policy/allowed_signers"}, {"signers": "-f"}, {"signers": "/x\n"}, + {"signers": 7}, {"data": "text"}, {"signature": b""}, {"signature": "sig"}): + result, recorder = self.verify(**kwargs) + self.assertIs(result, False, kwargs) + self.assertEqual(recorder.calls, [], kwargs) + + def test_oversized_data_or_signature_is_false_without_a_process(self): + self.assertEqual(self.mod._MAX_DATA_BYTES, 65536) + self.assertEqual(self.mod._MAX_SIGNATURE_BYTES, 8192) + for kwargs in ({"data": b"x" * 65537}, {"signature": b"s" * 8193}): + result, recorder = self.verify(**kwargs) + self.assertIs(result, False, list(kwargs)) + self.assertEqual(recorder.calls, [], list(kwargs)) + + def test_exit_zero_needs_the_good_signature_line_for_the_issuer(self): + good = b'Good "rizzstack-preauth" signature for kyle with ED25519 key SHA256:' + b"A" * 43 + b"\n" + for stdout in (b"", b"Good signature\n", good.replace(b"rizzstack-preauth", b"git"), + good.replace(b"for kyle", b"for bob"), good.replace(b"for kyle", b"for kyle2"), + good + good, b"x" + good, good.replace(b" with ", b" by ")): + result, recorder = self.verify(fail=("exit0", stdout)) + self.assertIs(result, False, stdout) + self.assertEqual(len(recorder.calls), 1) + result, _ = self.verify(fail=("exit0", good)) + self.assertIs(result, True) + + def test_a_path_hijack_does_not_reach_the_frozen_verifier(self): + fake = Path(tempfile.mkdtemp(prefix="preauth-hijack-")) + self.addCleanup(shutil.rmtree, fake, True) + (fake / "ssh-keygen").write_text("#!/bin/sh\necho Good signature; exit 0\n") + os.chmod(fake / "ssh-keygen", 0o755) + with mock.patch.dict(os.environ, {"PATH": str(fake) + os.pathsep + os.environ.get("PATH", "")}): + result, recorder = self.verify(signature=b"-----BEGIN SSH SIGNATURE-----\nAAAA\n-----END SSH SIGNATURE-----\n") + self.assertIs(result, False) + self.assertEqual(recorder.calls[0][0], "/usr/bin/ssh-keygen") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_preauth_policy.py b/tests/test_preauth_policy.py new file mode 100644 index 0000000..3578185 --- /dev/null +++ b/tests/test_preauth_policy.py @@ -0,0 +1,92 @@ +"""Pre-authorization policy and envelope schema (preauth-envelope re-cut of preauth-policy r3). + +This test freezes the *content* of the policy before the checker exists, so the doc cannot +drift from the rules the checker enforces: the envelope fields, the seven-day ceiling, the +never-pre-authorizable classes, owner-signed approval (ssh-keygen -Y, namespace +rizzstack-preauth, key held only by the owner), immediate revocation, and the five initial +envelopes the owner is asked to consider. + +Run: python3 -m unittest discover -s tests -p 'test_preauth_policy.py' -v +""" + +from __future__ import annotations + +import json +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +POLICY = ROOT / "policy" / "preauth.md" +SCHEMA = ROOT / "schemas" / "preauth.schema.json" + +FIELDS = {"id", "action_class", "conditions", "max_uses", "expires_at", "created_from", + "schema", "issuer", "issued_at", "nonce", "repos", "bases", "contracts", "budget", "review"} + + +class PreauthPolicyTest(unittest.TestCase): + def setUp(self) -> None: + self.text = POLICY.read_text(encoding="utf-8") + self.schema = json.loads(SCHEMA.read_text(encoding="utf-8")) + + def test_schema_requires_the_envelope_fields(self): + self.assertLessEqual(FIELDS, set(self.schema["required"])) + properties = self.schema["properties"] + self.assertEqual(properties["max_uses"]["type"], "integer") + self.assertEqual(properties["max_uses"]["minimum"], 1) + self.assertEqual(properties["conditions"]["type"], "array") + self.assertEqual(properties["expires_at"]["format"], "date-time") + + def test_policy_states_the_seven_day_ceiling(self): + self.assertIn("7 days", self.text) + self.assertIn("expires_at", self.text) + + def test_policy_names_every_never_preauthorizable_class(self): + for phrase in ( + "gate", "merge lane", "policy/**", "rulesets", "preauth", "secrets", + "force-push", "deleting data", "automatic rollback", + ): + self.assertIn(phrase, self.text.lower()) + + def test_policy_requires_signed_approval_and_immediate_revocation(self): + """A typed hash proves content, not who approved it: the owner signs the envelope.""" + self.assertIn("ssh-keygen -Y sign", self.text) + self.assertIn("rizzstack-preauth", self.text) + self.assertIn("policy/allowed_signers", self.text) + self.assertIn("never on the hermes host", self.text.lower()) + self.assertIn("revoke preauth ", self.text) + self.assertIn("effective immediately", self.text) + self.assertIn("never create, widen or extend", self.text) + + def test_policy_proposes_the_five_initial_envelopes(self): + for marker in ("P1", "P2", "P3", "P4", "P5"): + self.assertIn(marker, self.text) + for condition in ( + "source_rev", "RED evidence", "byte-identical", "superseding PR", + "health check", "automatic rollback", "dependency order", "4 bees in flight", + ): + self.assertIn(condition, self.text) + + def test_policy_requires_mechanical_conditions_and_a_daily_digest(self): + self.assertIn("prove every condition from data", self.text.lower()) + self.assertIn("daily digest", self.text.lower()) + self.assertIn("ledger", self.text.lower()) + + def test_p1_rejects_a_refreeze_that_changes_frozen_test_blobs(self): + """A re-freeze is not a spec change: P1 must require the frozen test blobs to be + identical at the old and the new source_rev.""" + text = self.text.lower() + self.assertIn("frozen test blobs", text) + self.assertIn("identical at the old and new source_rev", text) + + def test_p1_is_a_numbered_condition_covering_conftest_and_fixtures(self): + """P1 must be the first numbered envelope condition and must cover conftest, pytest + configuration and fixtures, not just the phrase 'test blobs'.""" + self.assertRegex(self.text, r"(?m)^1\.\s+\*\*P1") + section = self.text.lower().split("**p1", 1)[1].split("**p2", 1)[0] + for token in ("frozen test blobs", "identical at the old and new source_rev", + "conftest", "pytest config", "fixtures"): + self.assertIn(token, section) + + +if __name__ == "__main__": + unittest.main() From 672702ab93712f10ea95a20fe06ecda373f32522 Mon Sep 17 00:00:00 2001 From: "bee (deepseek-v4.1-flash)" Date: Fri, 27 Nov 2026 20:59:47 -0500 Subject: [PATCH 2/7] feat(preauth): envelope checker scripts/preauth.py and policy [bee att_acba65aca9441b6b] Slice preauth-envelope (contract c413827e). Verified by the coordinator: the 98 approved tests pass, the full suite passes (459), the frozen verifier scripts/preauth_verify.py is untouched (sha 0a3ab62b...), gitleaks clean, only assigned files changed. Coordinator-authored: needs an independent review. --- policy/README.md | 2 +- policy/preauth.md | 57 +++++ schemas/preauth.schema.json | 126 ++++++++++ scripts/preauth.py | 455 ++++++++++++++++++++++++++++++++++++ 4 files changed, 639 insertions(+), 1 deletion(-) create mode 100644 policy/preauth.md create mode 100644 schemas/preauth.schema.json create mode 100644 scripts/preauth.py diff --git a/policy/README.md b/policy/README.md index 4147680..25ff21a 100644 --- a/policy/README.md +++ b/policy/README.md @@ -18,4 +18,4 @@ Known gaps: no required reviewer (one maintainer); rizzstack's path-filtered `co - `merge-lane-v5.md`: what merges, and on what evidence (slice/non-slice, risk tier T1/T3, the review format, carry-forward, the dry run and go-live). - `outside-review.md`: who may review a pull request, reviewer model routing, what a review bee receives, and how its verdict is validated and posted. - `identities.md`: the owner, coordinator and reviewer identities on GitHub, key custody, and the migration off the owner's token. -- Planned: `preauth.md`, bounded pre-authorization envelopes the owner approves ahead of time (coordinator program, Phase 2). +- `preauth.md`: bounded pre-authorization envelopes the owner signs ahead of time (coordinator program, Phase 2), the never-pre-authorizable classes, and revocation. diff --git a/policy/preauth.md b/policy/preauth.md new file mode 100644 index 0000000..56092bf --- /dev/null +++ b/policy/preauth.md @@ -0,0 +1,57 @@ +# Signed pre-authorization envelopes + +A pre-authorization envelope is one bounded, owner-signed batch: the owner signs the exact +envelope bytes with `ssh-keygen -Y sign` using namespace `rizzstack-preauth`, and the key is +held only by the owner and never on the Hermes host. The signature is checked against +`policy/allowed_signers`, the read-only trust root, and every key line there must also match +the frozen fingerprint pin in the checker. An envelope the owner did not sign is refused. +Typed hashes prove content, not who approved it: only the owner's signature is approval. + +An envelope is capped at **7 days**: `expires_at` minus `issued_at` must not exceed seven +days, and `expires_at` must be after `issued_at`. The checker decides one use from measured +facts only and must prove every condition from data; a missing, null, malformed or unprovable +fact is a named refusal, not a pass. The checker is bound to this policy by its sha256. + +Agents never create, widen or extend envelopes. Only the owner signs one. Agents may ask for +a specific envelope and may execute exactly the action a valid envelope names, nothing more. + +## Revocation + +The owner revokes with `revoke preauth `, effective immediately: the envelope id goes on +the measured revocation list before the next decision, and every later use refuses. A nonce +and a consumed-use record make replay visible, and budget counters are read from measured +state, never from the envelope's own claims. + +## Never pre-authorizable + +Some classes are never pre-authorizable, at any tier, for any budget: changes to the gate, +the merge lane, `policy/**` (including this file and `policy/allowed_signers`), rulesets, +the preauth checker or verifier, secrets handling, force-push, deleting data, and automatic +rollback. An envelope that names one of these, or a case variant of it, is refused. A +pre-authorization can never widen preauth itself. + +## The five initial envelopes the owner is asked to consider + +Each candidate is proposed with mechanical conditions, and the ledger records every use. + +1. **P1 — Re-freeze behind an identical oracle.** A re-freeze of a frozen contract is allowed + only when the frozen test blobs are identical at the old and new source_rev: the same + conftest files, the same pytest config, and the same fixtures, byte-identical. Any added, + removed or changed oracle file refuses; product code may differ. This is not a spec + change. +2. **P2 — Merge one reviewed slice.** Merge a named slice whose RED evidence is present, whose + review packet is byte-identical to the reviewed head, and whose contract, source_rev and + tier match the envelope; at most the signed merge budget. +3. **P3 — Vendor a pinned dependency sync.** Land a dependency order that only updates a + vendored, pinned copy, with the upstream revision named and no other path touched. +4. **P4 — Close a superseding PR.** Close a superseded pull request whose superseding PR is + identified in the envelope; no merges, no branch deletion. +5. **P5 — Dispatch a bounded wave.** Dispatch a wave in dependency order with at most + 4 bees in flight, each on a listed contract; a failing health check stops the wave, and an + automatic rollback is a separate action that is never pre-authorizable. + +## Ledger and digest + +Every decision appends to a ledger: envelope id, nonce, contract_sha256, source_rev, tier, +action, the measured facts it used, and the policy and trust-root sha256 it decided under. +The owner receives a daily digest of the ledger: uses, refusals and remaining budgets. diff --git a/schemas/preauth.schema.json b/schemas/preauth.schema.json new file mode 100644 index 0000000..7fa4150 --- /dev/null +++ b/schemas/preauth.schema.json @@ -0,0 +1,126 @@ +{ + "title": "rizzstack signed pre-authorization envelope", + "description": "One bounded, owner-signed batch: rizzstack.preauth/2. Additional fields are refused.", + "type": "object", + "additionalProperties": false, + "required": [ + "schema", + "id", + "issuer", + "issued_at", + "expires_at", + "nonce", + "action_class", + "repos", + "bases", + "contracts", + "review", + "budget", + "conditions", + "max_uses", + "created_from" + ], + "properties": { + "schema": { + "type": "string", + "const": "rizzstack.preauth/2" + }, + "id": { + "type": "string", + "minLength": 1, + "description": "Envelope id; the unit of revocation and replay accounting." + }, + "issuer": { + "type": "string", + "pattern": "^[A-Za-z0-9._@-]{1,64}$", + "description": "The owner principal that signs; ssh-keygen -Y verify identity." + }, + "issued_at": { + "type": "string", + "format": "date-time", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$" + }, + "expires_at": { + "type": "string", + "format": "date-time", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$" + }, + "nonce": { + "type": "string", + "minLength": 1 + }, + "action_class": { + "type": "string", + "enum": [ + "merge_slice", + "refreeze_contract", + "vendor_sync", + "close_superseded_pr", + "dispatch_wave" + ] + }, + "repos": { + "type": "array", + "minItems": 1, + "items": { + "type": "string", + "minLength": 1 + } + }, + "bases": { + "type": "object", + "additionalProperties": { + "type": "string", + "minLength": 1 + } + }, + "contracts": { + "type": "array", + "minItems": 1, + "items": { + "type": "object" + } + }, + "review": { + "type": "object" + }, + "budget": { + "type": "object", + "additionalProperties": false, + "required": [ + "max_merges", + "max_bees", + "max_attempts_per_contract" + ], + "properties": { + "max_merges": { + "type": "integer", + "minimum": 1 + }, + "max_bees": { + "type": "integer", + "minimum": 1, + "maximum": 4 + }, + "max_attempts_per_contract": { + "type": "integer", + "minimum": 1 + } + } + }, + "conditions": { + "type": "array", + "items": { + "type": "object" + } + }, + "max_uses": { + "type": "integer", + "minimum": 1 + }, + "created_from": { + "type": "string", + "minLength": 1 + } + } +} diff --git a/scripts/preauth.py b/scripts/preauth.py new file mode 100644 index 0000000..ce2ce57 --- /dev/null +++ b/scripts/preauth.py @@ -0,0 +1,455 @@ +"""Signed pre-authorization envelopes: parsing, policy and one-use decisions. + +This module is parsing and policy only. It starts no process, writes no file and uses no +temporary file. The one way it checks a signature is the frozen verifier's private entry +point, ``_ssh_verify``, called with the exact envelope bytes. It opens exactly two files, +both through the constants below and both in the checkout this module lives in: +``policy/allowed_signers`` (the trust root) and ``policy/preauth.md`` (the policy the decision +is bound to by sha256). Every doubt, including missing measured state, refuses with one +literal reason from the closed set ``REFUSAL_REASONS`` through the single ``refuse`` helper. +""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import json +import re + +from datetime import datetime, timedelta, timezone + +from preauth_verify import _ssh_verify + +NAMESPACE = "rizzstack-preauth" +MAX_TTL_SECONDS = 7 * 24 * 3600 +VERIFY_TIMEOUT_SECONDS = 20 +SCHEMA_ID = "rizzstack.preauth/2" +NAMESPACE_OPTION = 'namespaces="rizzstack-preauth"' + +TRUST_ROOT = __file__.rsplit("/", 2)[0] + "/policy/allowed_signers" +POLICY = __file__.rsplit("/", 2)[0] + "/policy/preauth.md" + +OWNER_FINGERPRINTS = () + +REQUIRED_FIELDS = frozenset({ + "schema", "id", "issuer", "issued_at", "expires_at", "nonce", "action_class", "repos", + "bases", "contracts", "review", "budget", "conditions", "max_uses", "created_from", +}) + +ALLOWED_ACTION_CLASSES = frozenset({ + "merge_slice", "refreeze_contract", "vendor_sync", "close_superseded_pr", "dispatch_wave", +}) + +REFUSAL_REASONS = frozenset({ + "envelope_schema_invalid", "envelope_clock_invalid", "envelope_policy_unproven", + "envelope_signers_invalid", "envelope_signer_untrusted", "envelope_bad_signature", + "envelope_verifier_unavailable", "envelope_expired", "envelope_not_yet_valid", + "envelope_ttl_exceeded", "envelope_facts_unproven", "envelope_revoked", + "envelope_action_forbidden", "envelope_repo_mismatch", "envelope_base_mismatch", + "envelope_contract_not_listed", "envelope_tier_exceeded", "envelope_oracle_unproven", + "envelope_oracle_changed", "envelope_nonce_reused", "envelope_replayed", + "envelope_budget_exhausted", +}) + +BUDGET_FIELDS = frozenset({"max_merges", "max_bees", "max_attempts_per_contract"}) +CONTRACT_FIELDS = frozenset({"repo", "slice", "contract_sha256", "source_rev", "max_tier"}) +KEY_TYPES = frozenset({"ssh-ed25519", "sk-ssh-ed25519@openssh.com"}) +TIERS = {"T1": 1, "T2": 2, "T3": 3} +CONFIG_NAMES = frozenset({ + "pytest.ini", "tox.ini", "setup.cfg", "pyproject.toml", "setup.py", "noxfile.py", ".coveragerc", +}) +HOOK_NAMES = frozenset({"sitecustomize.py", "usercustomize.py"}) +STAMP = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z") +PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") + + +class PreauthRefused(Exception): + """A named refusal.""" + + +def refuse(reason): + error = PreauthRefused(reason) + error.reason = reason + raise error + + +def read_trust_root(): + try: + with open(TRUST_ROOT, "rb") as handle: + return handle.read() + except OSError: + refuse("envelope_signer_untrusted") + + +def read_policy(): + try: + with open(POLICY, "rb") as handle: + return handle.read() + except OSError: + refuse("envelope_policy_unproven") + + +def unique_object(pairs): + seen = set() + for key, item in pairs: + if key in seen: + refuse("envelope_schema_invalid") + seen.add(key) + return dict(pairs) + + +def parse_json(data): + try: + value = json.loads(data, object_pairs_hook=unique_object) + except (ValueError, TypeError): + refuse("envelope_schema_invalid") + if not isinstance(value, dict): + refuse("envelope_schema_invalid") + return value + + +def parse_stamp(text): + if not isinstance(text, str) or not STAMP.fullmatch(text): + refuse("envelope_schema_invalid") + try: + moment = datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ") + except ValueError: + refuse("envelope_schema_invalid") + return moment.replace(tzinfo=timezone.utc) + + +def positive_int(value): + return isinstance(value, int) and not isinstance(value, bool) and value >= 1 + + +def budget_ok(budget): + if not isinstance(budget, dict): + refuse("envelope_schema_invalid") + if set(budget.keys()) != BUDGET_FIELDS: + refuse("envelope_schema_invalid") + merges = budget.get("max_merges") + bees = budget.get("max_bees") + attempts = budget.get("max_attempts_per_contract") + if not positive_int(merges): + refuse("envelope_schema_invalid") + if not isinstance(bees, int) or isinstance(bees, bool) or bees < 1 or bees > 4: + refuse("envelope_schema_invalid") + if not positive_int(attempts): + refuse("envelope_schema_invalid") + + +def contract_fields(entry): + if not isinstance(entry, dict): + refuse("envelope_schema_invalid") + for name in CONTRACT_FIELDS: + if name not in entry or not isinstance(entry.get(name), str): + refuse("envelope_schema_invalid") + if entry.get("max_tier") not in TIERS: + refuse("envelope_schema_invalid") + + +def validate_envelope(value): + if set(value.keys()) != REQUIRED_FIELDS: + refuse("envelope_schema_invalid") + if value.get("schema") != SCHEMA_ID: + refuse("envelope_schema_invalid") + if not isinstance(value.get("id"), str) or not value.get("id"): + refuse("envelope_schema_invalid") + issuer = value.get("issuer") + if not principal_ok(issuer): + refuse("envelope_schema_invalid") + issued = parse_stamp(value.get("issued_at")) + expires = parse_stamp(value.get("expires_at")) + if expires <= issued: + refuse("envelope_schema_invalid") + if not isinstance(value.get("nonce"), str) or not value.get("nonce"): + refuse("envelope_schema_invalid") + repos = value.get("repos") + if not isinstance(repos, list): + refuse("envelope_schema_invalid") + for item in repos: + if not isinstance(item, str) or not item: + refuse("envelope_schema_invalid") + bases = value.get("bases") + if not isinstance(bases, dict): + refuse("envelope_schema_invalid") + for key in bases.keys(): + if not isinstance(key, str) or not isinstance(bases.get(key), str): + refuse("envelope_schema_invalid") + contracts = value.get("contracts") + if not isinstance(contracts, list): + refuse("envelope_schema_invalid") + for entry in contracts: + contract_fields(entry) + if not isinstance(value.get("review"), dict): + refuse("envelope_schema_invalid") + budget_ok(value.get("budget")) + if not isinstance(value.get("conditions"), list): + refuse("envelope_schema_invalid") + if not positive_int(value.get("max_uses")): + refuse("envelope_schema_invalid") + if not isinstance(value.get("created_from"), str): + refuse("envelope_schema_invalid") + + +def principal_ok(value): + return isinstance(value, str) and bool(PRINCIPAL.fullmatch(value)) and value[0] != "-" + + +def load_envelope(data): + value = parse_json(data) + validate_envelope(value) + return value + + +def fingerprint_of(blob): + try: + raw = base64.b64decode(blob, validate=True) + except binascii.Error: + refuse("envelope_signers_invalid") + digest = hashlib.sha256(raw).digest() + return "SHA256:" + base64.b64encode(digest).decode("ascii").rstrip("=") + + +def trust_fingerprints(raw, trusted): + if not isinstance(raw, bytes): + refuse("envelope_signers_invalid") + try: + text = raw.decode("utf-8") + except UnicodeDecodeError: + refuse("envelope_signers_invalid") + found = [] + for line in text.splitlines(): + stripped = line.strip() + if not stripped or stripped.startswith("#"): + continue + parts = stripped.split() + if len(parts) < 4: + refuse("envelope_signers_invalid") + if not principal_ok(parts[0]): + refuse("envelope_signers_invalid") + if parts[1] != NAMESPACE_OPTION: + refuse("envelope_signers_invalid") + if parts[2] not in KEY_TYPES: + refuse("envelope_signers_invalid") + found.append(fingerprint_of(parts[3])) + if not found: + refuse("envelope_signer_untrusted") + for item in found: + if item not in trusted: + refuse("envelope_signer_untrusted") + + +def validate_facts(facts): + if not isinstance(facts, dict): + refuse("envelope_facts_unproven") + for name in ("revoked", "consumed", "nonces", "attempts", "bees_in_flight"): + if name not in facts: + refuse("envelope_facts_unproven") + revoked = facts.get("revoked") + consumed = facts.get("consumed") + nonces = facts.get("nonces") + attempts = facts.get("attempts") + bees = facts.get("bees_in_flight") + if not isinstance(revoked, list) or not isinstance(consumed, list): + refuse("envelope_facts_unproven") + if not isinstance(nonces, dict) or not isinstance(attempts, dict): + refuse("envelope_facts_unproven") + if isinstance(bees, bool) or not isinstance(bees, int) or bees < 0: + refuse("envelope_facts_unproven") + for item in revoked: + if not isinstance(item, str): + refuse("envelope_facts_unproven") + for item in consumed: + if not isinstance(item, dict): + refuse("envelope_facts_unproven") + if not isinstance(item.get("envelope_id"), str): + refuse("envelope_facts_unproven") + if not isinstance(item.get("contract_sha256"), str): + refuse("envelope_facts_unproven") + for key in nonces.keys(): + if not isinstance(key, str) or not isinstance(nonces.get(key), str): + refuse("envelope_facts_unproven") + for key in attempts.keys(): + value = attempts.get(key) + if not isinstance(key, str) or isinstance(value, bool) or not isinstance(value, int) or value < 0: + refuse("envelope_facts_unproven") + return (revoked, consumed, nonces, attempts, bees) + + +def normalize_path(value): + if not isinstance(value, str): + refuse("envelope_oracle_unproven") + text = value.replace("\\", "/") + if text.startswith("/"): + refuse("envelope_oracle_unproven") + result = [] + for part in text.split("/"): + if not part or part == ".": + continue + if part == "..": + if not result: + refuse("envelope_oracle_unproven") + result.pop() + else: + result.append(part) + if not result: + refuse("envelope_oracle_unproven") + return "/".join(result) + + +def is_oracle(path, test_files): + lower = path.lower() + parts = lower.split("/") + base = parts[-1] + if lower in test_files: + return True + if parts[0] == "tests": + return True + if base == "conftest.py": + return True + if base in CONFIG_NAMES or base in HOOK_NAMES: + return True + if base.endswith(".pth"): + return True + if re.fullmatch(r"test_[^/]*\.py", base) or re.fullmatch(r"[^/]*_test\.py", base): + return True + for part in parts[:-1]: + if part in {"fixtures", "data", "helpers"}: + return True + if base == "__init__.py": + return True + if base.startswith("requirements") or base in {"uv.lock", "poetry.lock"} or base.startswith("pipfile"): + return True + if lower.startswith(".github/workflows/"): + return True + return False + + +def oracle_paths(paths, test_files=None): + wanted = set() + if test_files is not None: + for item in test_files: + wanted.add(normalize_path(item).lower()) + result = set() + for item in paths: + normalized = normalize_path(item) + if is_oracle(normalized, wanted): + result.add(normalized) + return result + + +def _decide(data, signature, allowed_signers, allowed_signers_bytes, policy_bytes, trusted_fingerprints, + repo, base_rev, contract_sha256, tier, now, facts, is_ancestor): + value = load_envelope(data) + if not isinstance(now, datetime) or now.tzinfo is None: + refuse("envelope_clock_invalid") + trust_fingerprints(allowed_signers_bytes, trusted_fingerprints) + issuer = value.get("issuer") + result = _ssh_verify(data, signature, allowed_signers, issuer) + if result is None: + refuse("envelope_verifier_unavailable") + if result is not True: + refuse("envelope_bad_signature") + action = value.get("action_class") + if not isinstance(action, str) or action not in ALLOWED_ACTION_CLASSES: + refuse("envelope_action_forbidden") + issued = parse_stamp(value.get("issued_at")) + expires = parse_stamp(value.get("expires_at")) + if now >= expires: + refuse("envelope_expired") + if now < issued: + refuse("envelope_not_yet_valid") + if (expires - issued).total_seconds() > MAX_TTL_SECONDS: + refuse("envelope_ttl_exceeded") + revoked, consumed, nonces, attempts, bees = validate_facts(facts) + envelope_id = value.get("id") + nonce = value.get("nonce") + if envelope_id in revoked: + refuse("envelope_revoked") + recorded = nonces.get(nonce) + if recorded is not None and recorded != envelope_id: + refuse("envelope_nonce_reused") + for entry in consumed: + if entry.get("contract_sha256") == contract_sha256: + refuse("envelope_replayed") + budget = value.get("budget") + uses = 0 + for entry in consumed: + if entry.get("envelope_id") == envelope_id: + uses += 1 + limit = min(value.get("max_uses"), budget.get("max_merges")) + if uses >= limit: + refuse("envelope_budget_exhausted") + if attempts.get(contract_sha256, 0) >= budget.get("max_attempts_per_contract"): + refuse("envelope_budget_exhausted") + if action == "dispatch_wave" and bees >= budget.get("max_bees"): + refuse("envelope_budget_exhausted") + repos = value.get("repos") + if repo not in repos: + refuse("envelope_repo_mismatch") + bases = value.get("bases") + if repo not in bases: + refuse("envelope_base_mismatch") + if is_ancestor is None: + refuse("envelope_base_mismatch") + try: + descended = is_ancestor(bases.get(repo), base_rev) + except Exception: + descended = False + if not descended: + refuse("envelope_base_mismatch") + entry = None + for item in value.get("contracts"): + if item.get("repo") == repo and item.get("contract_sha256") == contract_sha256: + entry = item + if entry is None: + refuse("envelope_contract_not_listed") + max_tier = entry.get("max_tier") + if not isinstance(tier, str) or tier not in TIERS: + refuse("envelope_tier_exceeded") + rank = TIERS.get(tier) + if rank > TIERS.get(max_tier, 0): + refuse("envelope_tier_exceeded") + if action == "refreeze_contract": + oracle = facts.get("oracle") + if not isinstance(oracle, dict): + refuse("envelope_oracle_unproven") + old = oracle.get("old") + new = oracle.get("new") + if not isinstance(old, dict) or not isinstance(new, dict): + refuse("envelope_oracle_unproven") + test_files = entry.get("test_files", []) + if not isinstance(test_files, list): + test_files = [] + old_paths = oracle_paths(old.keys(), test_files) + new_paths = oracle_paths(new.keys(), test_files) + if old_paths != new_paths: + refuse("envelope_oracle_changed") + for path in old_paths: + if old.get(path) != new.get(path): + refuse("envelope_oracle_changed") + return { + "ok": True, + "envelope_id": envelope_id, + "contract_sha256": contract_sha256, + "max_tier": max_tier, + "policy_sha256": hashlib.sha256(policy_bytes).hexdigest(), + "allowed_signers_sha256": hashlib.sha256(allowed_signers_bytes).hexdigest(), + } + + +def check(data, signature, repo, base_rev, contract_sha256, tier, now, facts, is_ancestor): + trust_bytes = read_trust_root() + policy_bytes = read_policy() + return _decide(data, signature, TRUST_ROOT, trust_bytes, policy_bytes, OWNER_FINGERPRINTS, + repo, base_rev, contract_sha256, tier, now, facts, is_ancestor) + + +def _check_for_tests(data, signature, *, allowed_signers, allowed_signers_bytes, policy_bytes, + trusted_fingerprints, repo, base_rev, contract_sha256, tier, now, facts, + is_ancestor): + """Test-only entry point: the decision tests pass a temporary trust root and pin.""" + return _decide(data, signature, allowed_signers, allowed_signers_bytes, policy_bytes, + trusted_fingerprints, repo, base_rev, contract_sha256, tier, now, facts, is_ancestor) From 7fa2eaf373f40d505b5c94e116afdfb68516bb58 Mon Sep 17 00:00:00 2001 From: "MR.INDIA" Date: Sat, 28 Nov 2026 02:41:46 -0500 Subject: [PATCH 3/7] test(preauth): RED regression tests for the trust-root parsing and re-freeze oracle blockers (r7, draft) --- tests/test_preauth_r7_blockers.py | 124 ++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 tests/test_preauth_r7_blockers.py diff --git a/tests/test_preauth_r7_blockers.py b/tests/test_preauth_r7_blockers.py new file mode 100644 index 0000000..d824a65 --- /dev/null +++ b/tests/test_preauth_r7_blockers.py @@ -0,0 +1,124 @@ +"""Regression tests for the two blocking findings on the preauth-envelope slice (r7). + +BLOCKER 1 (AC-005, trust-root pin bypass): ``trust_fingerprints`` must read the trust root the way +ssh-keygen does: lines end at b"\\n" only, fields split on space or tab only, and any byte that is +not printable ASCII (or a tab) makes the file invalid. Otherwise a line led by a Unicode or +control "whitespace" character is a comment to preauth.py but a real entry to ssh-keygen. + +BLOCKER 2 (AC-015/016, re-freeze oracle fail-open): measured oracle maps are normalised first, a +collision between two raw keys refuses, and the normalised maps are compared. + +Run: python3 -m pytest -q -p no:cacheprovider tests/test_preauth_r7_blockers.py +""" + +from __future__ import annotations + +import json +import unittest + +import test_preauth_envelope as base + +LEADS = (b"\x0c", b"\x0b", b"\x1c", b"\x1d", b"\x1e", b"\x1f", "\u0085".encode(), "\u00a0".encode(), + "\u2028".encode(), "\u2029".encode(), "\u3000".encode(), b"\x00", b"\x7f") + + +class TrustRootParsingTest(base.EnvelopeCase): + def trust_file(self, *chunks, name="r7_signers"): + path = self.keys.dir / name + path.write_bytes(b"".join(chunks)) + return path + + def intruder_line(self, intruder, lead): + parts = intruder.public.split() + return lead + b'#,* namespaces="rizzstack-preauth" ' + parts[0].encode() + b" " + parts[1].encode() + + def test_a_comment_hidden_from_preauth_but_not_from_ssh_keygen_is_refused(self): + intruder = base.Keys(principal="kyle") + try: + data = json.dumps(base.envelope(), sort_keys=True).encode() + for lead in LEADS: + signers = self.trust_file(self.keys.line.encode() + b"\n", self.intruder_line(intruder, lead) + b"\n") + for key in (intruder, self.keys): + self.refused("envelope_signers_invalid", data=data, signature=key.sign(data), signers=signers) + self.assertEqual(self.recorder.calls, [], repr(lead)) + finally: + intruder.close() + + def test_any_control_or_non_ascii_byte_anywhere_in_the_trust_root_is_refused(self): + key = self.keys.line.encode() + for byte in (b"\x0c", b"\x0b", b"\x1c", b"\x00", b"\x7f", b"\x1b", "\u0085".encode(), "\u00e9".encode(), + "\u2028".encode(), b"\xff"): + for blob in (key + b"\n# note " + byte + b"\n", + key + b" " + byte + b"\n", + byte + key + b"\n", + key + b"\n" + byte + b"\n"): + self.refused("envelope_signers_invalid", signers=self.trust_file(blob)) + # a bare carriage return inside a line is not a line ending for ssh-keygen: refuse it too + self.refused("envelope_signers_invalid", signers=self.trust_file(key + b"\r# x\n")) + + def test_ordinary_ascii_trust_roots_still_work(self): + key = self.keys.line.encode() + parts = key.split() + tabbed = b"\t".join(parts) + for blob in (b"# comment\n" + key + b"\n", + key + b"\n", + b" # indented comment\n\t# tab comment\n\n" + key + b"\n", + b" " + key + b" \n", + tabbed + b"\n", + key + b"\r\n"): + data = json.dumps(base.envelope(), sort_keys=True).encode() + result = self.decide(data=data, signature=self.keys.sign(data), signers=self.trust_file(blob)) + self.assertTrue(result["ok"], repr(blob)) + + def test_comment_detection_uses_space_and_tab_only(self): + key = self.keys.line.encode() + # first non-space/tab byte is not '#': this is an entry, and a malformed one + self.refused("envelope_signers_invalid", signers=self.trust_file(key + b"\n", b"x#,* junk\n")) + + +class OracleNormalisationTest(base.EnvelopeCase): + def refreeze(self): + entry = dict(base.envelope()["contracts"][0]) + entry["refreeze_of"] = {"contract_sha256": "d" * 64, "source_rev": "e" * 40} + entry["test_files"] = ["tests/test_review_packet.py"] + return base.envelope(contracts=[entry], action_class="refreeze_contract") + + def run_old_new(self, old, new): + return self.decide(self.refreeze(), measured=base.facts(oracle={"old": old, "new": new})) + + def test_changed_oracle_file_with_non_canonical_keys_refuses(self): + for old_key, new_key in (("./tests/test_review_packet.py", "./tests/test_review_packet.py"), + ("tests//test_review_packet.py", "tests//test_review_packet.py"), + ("./tests/test_review_packet.py", "tests/test_review_packet.py"), + ("tests/test_review_packet.py", "./tests/test_review_packet.py"), + ("tests/./conftest.py", "tests//conftest.py"), + ("tests/x/../conftest.py", "tests/x/../conftest.py")): + old = {old_key: "1" * 40} + new = {new_key: "9" * 40} + self.refused("envelope_oracle_changed", self.refreeze(), + measured=base.facts(oracle={"old": old, "new": new})) + + def test_unchanged_oracle_with_equivalent_spellings_is_allowed(self): + old = {"./tests/test_review_packet.py": "1" * 40, "tests//conftest.py": "2" * 40, "src/thing.py": "7" * 40} + new = {"tests/test_review_packet.py": "1" * 40, "./tests/conftest.py": "2" * 40, "src/thing.py": "8" * 40} + self.assertTrue(self.run_old_new(old, new)["ok"]) + + def test_two_raw_keys_that_normalise_to_one_path_refuse(self): + for pair in (("tests/test_review_packet.py", "./tests/test_review_packet.py"), + ("tests/conftest.py", "tests//conftest.py"), + ("tests/a/../conftest.py", "tests/conftest.py")): + colliding = {pair[0]: "1" * 40, pair[1]: "1" * 40} + clean = {"tests/test_review_packet.py": "1" * 40, "tests/conftest.py": "1" * 40} + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": colliding, "new": clean})) + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": clean, "new": colliding})) + + def test_a_path_present_in_only_one_map_still_refuses_after_normalising(self): + old = {"./tests/test_review_packet.py": "1" * 40} + new = {} + self.refused("envelope_oracle_changed", self.refreeze(), measured=base.facts(oracle={"old": old, "new": new})) + + +if __name__ == "__main__": + unittest.main() From b664aa4994df7106f90b5b5bb83b3612f6702e25 Mon Sep 17 00:00:00 2001 From: "MR.INDIA" Date: Sat, 28 Nov 2026 03:20:23 -0500 Subject: [PATCH 4/7] test(preauth): R9 RED cases for backslash/trailing-slash keys, non-hex oracle values, ssh-keygen vacuity, and check() hidden entry GROKCHAT r9 on the r7 draft: pin path spellings that a no-backslash normaliser missed, require 40/64-hex oracle values, and keep the hidden-entry test from going vacuous. --- tests/test_preauth_r7_blockers.py | 123 +++++++++++++++++++++++++++++- 1 file changed, 121 insertions(+), 2 deletions(-) diff --git a/tests/test_preauth_r7_blockers.py b/tests/test_preauth_r7_blockers.py index d824a65..58f5c0d 100644 --- a/tests/test_preauth_r7_blockers.py +++ b/tests/test_preauth_r7_blockers.py @@ -14,12 +14,38 @@ from __future__ import annotations import json +import os +import shutil +import subprocess +import tempfile import unittest +from pathlib import Path +from unittest import mock import test_preauth_envelope as base LEADS = (b"\x0c", b"\x0b", b"\x1c", b"\x1d", b"\x1e", b"\x1f", "\u0085".encode(), "\u00a0".encode(), "\u2028".encode(), "\u2029".encode(), "\u3000".encode(), b"\x00", b"\x7f") +# Leads that real ssh-keygen treats as a live allowed-signers entry (R9 fuzz). NUL and DEL are +# still refused by the byte rule, but ssh-keygen does not accept them, so they are not in this set. +BYPASS_LEADS = (b"\x0c", b"\x0b", b"\x1c", b"\x1d", b"\x1e", b"\x1f", "\u0085".encode(), "\u00a0".encode(), + "\u2028".encode(), "\u2029".encode(), "\u3000".encode()) + + +def ssh_keygen_accepts(data, signature, signers, issuer="kyle"): + """True if /usr/bin/ssh-keygen -Y verify accepts signature as issuer under signers.""" + signers = os.path.abspath(os.fsdecode(signers)) + with tempfile.NamedTemporaryFile(suffix=".sig") as handle: + handle.write(signature) + handle.flush() + proc = subprocess.run( + ["/usr/bin/ssh-keygen", "-Y", "verify", "-f", signers, "-I", issuer, + "-n", "rizzstack-preauth", "-s", handle.name], + input=data, capture_output=True, timeout=20, env={"PATH": "/usr/bin:/bin"}, + ) + expected = b'Good "rizzstack-preauth" signature for ' + issuer.encode("ascii") + b" with " + lines = proc.stdout.splitlines() + return proc.returncode == 0 and len(lines) == 1 and lines[0].startswith(expected) class TrustRootParsingTest(base.EnvelopeCase): @@ -36,11 +62,18 @@ def test_a_comment_hidden_from_preauth_but_not_from_ssh_keygen_is_refused(self): intruder = base.Keys(principal="kyle") try: data = json.dumps(base.envelope(), sort_keys=True).encode() + accepted_by_ssh = 0 for lead in LEADS: signers = self.trust_file(self.keys.line.encode() + b"\n", self.intruder_line(intruder, lead) + b"\n") - for key in (intruder, self.keys): - self.refused("envelope_signers_invalid", data=data, signature=key.sign(data), signers=signers) + intruder_sig = intruder.sign(data) + if lead in BYPASS_LEADS: + self.assertTrue(ssh_keygen_accepts(data, intruder_sig, signers), + "ssh-keygen must accept the hidden entry, else the test is vacuous: %r" % lead) + accepted_by_ssh += 1 + for key, sig in ((intruder, intruder_sig), (self.keys, self.keys.sign(data))): + self.refused("envelope_signers_invalid", data=data, signature=sig, signers=signers) self.assertEqual(self.recorder.calls, [], repr(lead)) + self.assertEqual(accepted_by_ssh, len(BYPASS_LEADS), "vacuity: every bypass lead must be accepted by ssh-keygen") finally: intruder.close() @@ -119,6 +152,92 @@ def test_a_path_present_in_only_one_map_still_refuses_after_normalising(self): new = {} self.refused("envelope_oracle_changed", self.refreeze(), measured=base.facts(oracle={"old": old, "new": new})) + def test_backslash_and_trailing_slash_spellings_are_normalised(self): + # normalize_path folds "\\" to "/" and drops empty trailing segments; it does not refuse these + # spellings. A changed file under either spelling is envelope_oracle_changed; two raw keys + # that fold to the same path are envelope_oracle_unproven; equivalent spellings of an + # unchanged file are allowed. + digest, changed = "1" * 40, "9" * 40 + canonical = "tests/test_review_packet.py" + for spelling in (r"tests\test_review_packet.py", "tests/test_review_packet.py/", + r"tests\test_review_packet.py/", "tests/test_review_packet.py//"): + self.refused("envelope_oracle_changed", self.refreeze(), + measured=base.facts(oracle={"old": {spelling: digest}, "new": {spelling: changed}})) + self.refused("envelope_oracle_changed", self.refreeze(), + measured=base.facts(oracle={"old": {canonical: digest}, "new": {spelling: changed}})) + self.refused("envelope_oracle_changed", self.refreeze(), + measured=base.facts(oracle={"old": {spelling: digest}, "new": {canonical: changed}})) + for left, right in ((r"tests\test_review_packet.py", canonical), + (canonical, "tests/test_review_packet.py/"), + (r"tests\test_review_packet.py", "tests/test_review_packet.py/"), + ("tests/conftest.py", "tests/conftest.py/")): + colliding = {left: digest, right: digest} + clean = {canonical: digest, "tests/conftest.py": digest} + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": colliding, "new": clean})) + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": clean, "new": colliding})) + old = {r"tests\test_review_packet.py": digest, "tests/conftest.py/": "2" * 40, "src/thing.py": "7" * 40} + new = {canonical: digest, "tests/conftest.py": "2" * 40, "src/thing.py": "8" * 40} + self.assertTrue(self.run_old_new(old, new)["ok"]) + + def test_a_non_hex_oracle_value_refuses(self): + good = { "tests/test_review_packet.py": "1" * 40, "tests/conftest.py": "2" * 40 } + bad_values = (None, "?", "", "1" * 39, "1" * 41, "1" * 63, "1" * 65, "g" * 40, "1" * 39 + "g", 40, True, []) + for value in bad_values: + for side in ("old", "new"): + old, new = dict(good), dict(good) + (old if side == "old" else new)["tests/test_review_packet.py"] = value + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": old, "new": new})) + # same bad value on both sides is still unproven, not a successful "unchanged" + both = dict(good, **{"tests/test_review_packet.py": value}) + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": both, "new": dict(both)})) + # mixed-case hex of length 40 or 64 is accepted (unchanged) + for digest in ("A" * 40, "aB" * 20, "0" * 64, "Ff" * 32): + maps = {"tests/test_review_packet.py": digest, "src/thing.py": "7" * 40} + self.assertTrue(self.run_old_new(maps, dict(maps, **{"src/thing.py": "8" * 40}))["ok"], digest) + + +class ProductionCheckTest(unittest.TestCase): + """The hidden-entry pin bypass is also refused at check(), via an AC-027-style module copy.""" + + def test_check_refuses_a_hidden_trust_root_entry(self): + keys = base.Keys() + intruder = base.Keys(principal="kyle") + root = Path(tempfile.mkdtemp(prefix="preauth-r7-check-")) + try: + (root / "scripts").mkdir() + (root / "policy").mkdir() + shutil.copyfile(base.MODULE, root / "scripts" / "preauth.py") + shutil.copyfile(base.VERIFY_MODULE, root / "scripts" / "preauth_verify.py") + lead = b"\x0c" + parts = intruder.public.split() + hidden = lead + b'#,* namespaces="rizzstack-preauth" ' + parts[0].encode() + b" " + parts[1].encode() + signers = root / "policy" / "allowed_signers" + signers.write_bytes(keys.line.encode() + b"\n" + hidden + b"\n") + (root / "policy" / "preauth.md").write_bytes(base.TEST_POLICY) + copy = base._load_copy(root, "preauth_r7_check_copy") + data = json.dumps(base.envelope(), sort_keys=True).encode() + signature = intruder.sign(data) + self.assertTrue(ssh_keygen_accepts(data, signature, signers), + "ssh-keygen must accept the hidden entry, else the test is vacuous") + with mock.patch.object(copy, "OWNER_FINGERPRINTS", (keys.fingerprint,)): + with self.assertRaises(copy.PreauthRefused) as caught: + copy.check( + data, signature, repo=base.REPO, base_rev=base.CURRENT_BASE, + contract_sha256=base.CONTRACT, tier="T3", now=base.NOW, + facts=base.facts(), + is_ancestor=lambda older, newer: older == base.SIGNED_BASE and newer == base.CURRENT_BASE, + ) + self.assertEqual(caught.exception.reason, "envelope_signers_invalid") + self.assertEqual(caught.exception.args, (caught.exception.reason,)) + finally: + keys.close() + intruder.close() + shutil.rmtree(root, ignore_errors=True) + if __name__ == "__main__": unittest.main() From 049b521a051ec4fcb3e52fb89a837806de089a33 Mon Sep 17 00:00:00 2001 From: "MR.INDIA" Date: Sat, 28 Nov 2026 03:31:52 -0500 Subject: [PATCH 5/7] test(preauth): R10 RED cases refuse backslash oracle keys; pad values; version-adaptive ssh-keygen vacuity GROKCHAT r10: normalising a backslash aliases two distinct git paths (a git mv keeps the blob and pytest stops collecting it). Backslash keys must be unproven; trailing-slash, // and ./ stay normalised. --- tests/test_preauth_r7_blockers.py | 106 +++++++++++++++++++++--------- 1 file changed, 76 insertions(+), 30 deletions(-) diff --git a/tests/test_preauth_r7_blockers.py b/tests/test_preauth_r7_blockers.py index 58f5c0d..aeecec4 100644 --- a/tests/test_preauth_r7_blockers.py +++ b/tests/test_preauth_r7_blockers.py @@ -62,18 +62,20 @@ def test_a_comment_hidden_from_preauth_but_not_from_ssh_keygen_is_refused(self): intruder = base.Keys(principal="kyle") try: data = json.dumps(base.envelope(), sort_keys=True).encode() - accepted_by_ssh = 0 + accepted_by_ssh = [] for lead in LEADS: signers = self.trust_file(self.keys.line.encode() + b"\n", self.intruder_line(intruder, lead) + b"\n") intruder_sig = intruder.sign(data) - if lead in BYPASS_LEADS: - self.assertTrue(ssh_keygen_accepts(data, intruder_sig, signers), - "ssh-keygen must accept the hidden entry, else the test is vacuous: %r" % lead) - accepted_by_ssh += 1 + if ssh_keygen_accepts(data, intruder_sig, signers): + accepted_by_ssh.append(lead) for key, sig in ((intruder, intruder_sig), (self.keys, self.keys.sign(data))): self.refused("envelope_signers_invalid", data=data, signature=sig, signers=signers) self.assertEqual(self.recorder.calls, [], repr(lead)) - self.assertEqual(accepted_by_ssh, len(BYPASS_LEADS), "vacuity: every bypass lead must be accepted by ssh-keygen") + # Probe every lead against this OpenSSH; only leads it really accepts count for + # vacuity, and at least one must be accepted, so a different OpenSSH cannot turn + # the test red while the checker is still correct. + self.assertGreaterEqual(len(accepted_by_ssh), 1, + "vacuity: local ssh-keygen accepted none of the hidden-entry leads") finally: intruder.close() @@ -152,24 +154,26 @@ def test_a_path_present_in_only_one_map_still_refuses_after_normalising(self): new = {} self.refused("envelope_oracle_changed", self.refreeze(), measured=base.facts(oracle={"old": old, "new": new})) - def test_backslash_and_trailing_slash_spellings_are_normalised(self): - # normalize_path folds "\\" to "/" and drops empty trailing segments; it does not refuse these - # spellings. A changed file under either spelling is envelope_oracle_changed; two raw keys - # that fold to the same path are envelope_oracle_unproven; equivalent spellings of an - # unchanged file are allowed. + def test_trailing_slash_and_dot_slash_spellings_are_normalised(self): + # Trailing slash, "//" and "./" cannot appear in a git tree path, so normalising them + # cannot alias two real files. A changed file under those spellings is + # envelope_oracle_changed; two raw keys that fold to the same path are + # envelope_oracle_unproven; equivalent spellings of an unchanged file are allowed. + # Backslash is not normalised: it is a legal git path character (see the backslash tests). digest, changed = "1" * 40, "9" * 40 canonical = "tests/test_review_packet.py" - for spelling in (r"tests\test_review_packet.py", "tests/test_review_packet.py/", - r"tests\test_review_packet.py/", "tests/test_review_packet.py//"): + for spelling in ("./tests/test_review_packet.py", "tests//test_review_packet.py", + "tests/test_review_packet.py/", "tests/test_review_packet.py//", + "tests/./test_review_packet.py"): self.refused("envelope_oracle_changed", self.refreeze(), measured=base.facts(oracle={"old": {spelling: digest}, "new": {spelling: changed}})) self.refused("envelope_oracle_changed", self.refreeze(), measured=base.facts(oracle={"old": {canonical: digest}, "new": {spelling: changed}})) self.refused("envelope_oracle_changed", self.refreeze(), measured=base.facts(oracle={"old": {spelling: digest}, "new": {canonical: changed}})) - for left, right in ((r"tests\test_review_packet.py", canonical), - (canonical, "tests/test_review_packet.py/"), - (r"tests\test_review_packet.py", "tests/test_review_packet.py/"), + for left, right in ((canonical, "tests/test_review_packet.py/"), + (canonical, "tests/test_review_packet.py//"), + ("./tests/test_review_packet.py", canonical), ("tests/conftest.py", "tests/conftest.py/")): colliding = {left: digest, right: digest} clean = {canonical: digest, "tests/conftest.py": digest} @@ -177,13 +181,53 @@ def test_backslash_and_trailing_slash_spellings_are_normalised(self): measured=base.facts(oracle={"old": colliding, "new": clean})) self.refused("envelope_oracle_unproven", self.refreeze(), measured=base.facts(oracle={"old": clean, "new": colliding})) - old = {r"tests\test_review_packet.py": digest, "tests/conftest.py/": "2" * 40, "src/thing.py": "7" * 40} + old = {"./tests/test_review_packet.py": digest, "tests/conftest.py/": "2" * 40, "src/thing.py": "7" * 40} new = {canonical: digest, "tests/conftest.py": "2" * 40, "src/thing.py": "8" * 40} self.assertTrue(self.run_old_new(old, new)["ok"]) + def test_a_backslash_in_an_oracle_key_is_unproven(self): + # A backslash is a legal filename character on Linux and in git, so folding it to slash + # would merge two distinct tree paths. Any raw key containing "\" refuses + # envelope_oracle_unproven, whether the hash changed, stayed the same, or collides + # with a slash spelling in the same map. + digest, changed = "1" * 40, "9" * 40 + canonical = "tests/test_review_packet.py" + for spelling in (r"tests\test_review_packet.py", r"tests\test_review_packet.py/", + r"foo\bar.py", r"tests/foo\bar.py"): + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": {spelling: digest}, "new": {spelling: changed}})) + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": {canonical: digest}, "new": {spelling: changed}})) + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": {spelling: digest}, "new": {canonical: changed}})) + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": {spelling: digest}, "new": {spelling: digest}})) + colliding = {canonical: digest, r"tests\test_review_packet.py": digest} + clean = {canonical: digest, "tests/conftest.py": digest} + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": colliding, "new": clean})) + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": clean, "new": colliding})) + + def test_a_slash_to_backslash_swap_is_unproven(self): + # Real-git case: git mv tests/test_review_packet.py to a literal backslash filename + # keeps the blob and pytest stops collecting the file. Both directions must refuse + # (envelope_oracle_unproven), not compare as unchanged after normalisation. + digest = "03348f5f0f815389d5261ab8ed4aff3e237e68bc" + slash = "tests/test_review_packet.py" + backslash = r"tests\test_review_packet.py" + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": {slash: digest}, "new": {backslash: digest}})) + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": {backslash: digest}, "new": {slash: digest}})) + def test_a_non_hex_oracle_value_refuses(self): - good = { "tests/test_review_packet.py": "1" * 40, "tests/conftest.py": "2" * 40 } - bad_values = (None, "?", "", "1" * 39, "1" * 41, "1" * 63, "1" * 65, "g" * 40, "1" * 39 + "g", 40, True, []) + good = {"tests/test_review_packet.py": "1" * 40, "tests/conftest.py": "2" * 40} + bad_values = ( + None, "?", "", "1" * 39, "1" * 41, "1" * 63, "1" * 65, "g" * 40, "1" * 39 + "g", + 40, True, [], + "1" * 40 + "\n", " " + "1" * 40, "1" * 40 + " ", "\t" + "1" * 40, "1" * 40 + "\t", + ) for value in bad_values: for side in ("old", "new"): old, new = dict(good), dict(good) @@ -194,10 +238,9 @@ def test_a_non_hex_oracle_value_refuses(self): both = dict(good, **{"tests/test_review_packet.py": value}) self.refused("envelope_oracle_unproven", self.refreeze(), measured=base.facts(oracle={"old": both, "new": dict(both)})) - # mixed-case hex of length 40 or 64 is accepted (unchanged) - for digest in ("A" * 40, "aB" * 20, "0" * 64, "Ff" * 32): - maps = {"tests/test_review_packet.py": digest, "src/thing.py": "7" * 40} - self.assertTrue(self.run_old_new(maps, dict(maps, **{"src/thing.py": "8" * 40}))["ok"], digest) + # Lowercase 40- and 64-character hex values remain accepted. The tests do not require + # uppercase or mixed-case hex to be accepted (an implementer may treat lowercase as + # canonical). Comparison is exact, so a case mismatch of the same digest is not "unchanged". class ProductionCheckTest(unittest.TestCase): @@ -212,17 +255,20 @@ def test_check_refuses_a_hidden_trust_root_entry(self): (root / "policy").mkdir() shutil.copyfile(base.MODULE, root / "scripts" / "preauth.py") shutil.copyfile(base.VERIFY_MODULE, root / "scripts" / "preauth_verify.py") - lead = b"\x0c" - parts = intruder.public.split() - hidden = lead + b'#,* namespaces="rizzstack-preauth" ' + parts[0].encode() + b" " + parts[1].encode() - signers = root / "policy" / "allowed_signers" - signers.write_bytes(keys.line.encode() + b"\n" + hidden + b"\n") (root / "policy" / "preauth.md").write_bytes(base.TEST_POLICY) + signers = root / "policy" / "allowed_signers" copy = base._load_copy(root, "preauth_r7_check_copy") data = json.dumps(base.envelope(), sort_keys=True).encode() signature = intruder.sign(data) - self.assertTrue(ssh_keygen_accepts(data, signature, signers), - "ssh-keygen must accept the hidden entry, else the test is vacuous") + chosen = None + for lead in BYPASS_LEADS: + parts = intruder.public.split() + hidden = lead + b'#,* namespaces="rizzstack-preauth" ' + parts[0].encode() + b" " + parts[1].encode() + signers.write_bytes(keys.line.encode() + b"\n" + hidden + b"\n") + if ssh_keygen_accepts(data, signature, signers): + chosen = lead + break + self.assertIsNotNone(chosen, "vacuity: local ssh-keygen accepted none of the hidden-entry leads") with mock.patch.object(copy, "OWNER_FINGERPRINTS", (keys.fingerprint,)): with self.assertRaises(copy.PreauthRefused) as caught: copy.check( From 052afa3ec095527653cfdb0c92a59c3bc15b20a4 Mon Sep 17 00:00:00 2001 From: "MR.INDIA" Date: Sat, 28 Nov 2026 03:51:28 -0500 Subject: [PATCH 6/7] test(preauth): R11 RED cases for edge backslash keys; unittest-discover clean failures GROKCHAT r11: a check of only embedded backslashes (key.strip('\\\\')) still accepted a trailing-backslash git mv. Add trailing, leading, doubled and slash-backslash spellings to the unproven and swap tests. Report a refusal as a failure under unittest discover, not an error. --- tests/test_preauth_r7_blockers.py | 85 ++++++++++++++++++++++--------- 1 file changed, 60 insertions(+), 25 deletions(-) diff --git a/tests/test_preauth_r7_blockers.py b/tests/test_preauth_r7_blockers.py index aeecec4..7ac87aa 100644 --- a/tests/test_preauth_r7_blockers.py +++ b/tests/test_preauth_r7_blockers.py @@ -8,7 +8,8 @@ BLOCKER 2 (AC-015/016, re-freeze oracle fail-open): measured oracle maps are normalised first, a collision between two raw keys refuses, and the normalised maps are compared. -Run: python3 -m pytest -q -p no:cacheprovider tests/test_preauth_r7_blockers.py +Run (pytest): python3 -m pytest -q -p no:cacheprovider tests/test_preauth_r7_blockers.py +Run (as CI): python3 -m unittest discover -s tests -v """ from __future__ import annotations @@ -26,8 +27,10 @@ LEADS = (b"\x0c", b"\x0b", b"\x1c", b"\x1d", b"\x1e", b"\x1f", "\u0085".encode(), "\u00a0".encode(), "\u2028".encode(), "\u2029".encode(), "\u3000".encode(), b"\x00", b"\x7f") -# Leads that real ssh-keygen treats as a live allowed-signers entry (R9 fuzz). NUL and DEL are -# still refused by the byte rule, but ssh-keygen does not accept them, so they are not in this set. +# Historical set from the R9 fuzz: leads that ssh-keygen treated as a live entry. +# Local ssh-keygen also accepts DEL (0x7f) and rejects NUL. DEL stays in LEADS so the +# byte rule still refuses it; it is not in this historical set. Vacuity probes every +# lead against the local binary and requires at least one acceptance. BYPASS_LEADS = (b"\x0c", b"\x0b", b"\x1c", b"\x1d", b"\x1e", b"\x1f", "\u0085".encode(), "\u00a0".encode(), "\u2028".encode(), "\u2029".encode(), "\u3000".encode()) @@ -121,6 +124,14 @@ def refreeze(self): def run_old_new(self, old, new): return self.decide(self.refreeze(), measured=base.facts(oracle={"old": old, "new": new})) + def assert_ok(self, old, new): + # unittest reports an uncaught PreauthRefused as an error, not a failure. + try: + result = self.run_old_new(old, new) + except self.pre.PreauthRefused as exc: + self.fail("expected ok, refused %s" % exc.reason) + self.assertTrue(result["ok"]) + def test_changed_oracle_file_with_non_canonical_keys_refuses(self): for old_key, new_key in (("./tests/test_review_packet.py", "./tests/test_review_packet.py"), ("tests//test_review_packet.py", "tests//test_review_packet.py"), @@ -136,7 +147,7 @@ def test_changed_oracle_file_with_non_canonical_keys_refuses(self): def test_unchanged_oracle_with_equivalent_spellings_is_allowed(self): old = {"./tests/test_review_packet.py": "1" * 40, "tests//conftest.py": "2" * 40, "src/thing.py": "7" * 40} new = {"tests/test_review_packet.py": "1" * 40, "./tests/conftest.py": "2" * 40, "src/thing.py": "8" * 40} - self.assertTrue(self.run_old_new(old, new)["ok"]) + self.assert_ok(old, new) def test_two_raw_keys_that_normalise_to_one_path_refuse(self): for pair in (("tests/test_review_packet.py", "./tests/test_review_packet.py"), @@ -183,17 +194,29 @@ def test_trailing_slash_and_dot_slash_spellings_are_normalised(self): measured=base.facts(oracle={"old": clean, "new": colliding})) old = {"./tests/test_review_packet.py": digest, "tests/conftest.py/": "2" * 40, "src/thing.py": "7" * 40} new = {canonical: digest, "tests/conftest.py": "2" * 40, "src/thing.py": "8" * 40} - self.assertTrue(self.run_old_new(old, new)["ok"]) + self.assert_ok(old, new) def test_a_backslash_in_an_oracle_key_is_unproven(self): # A backslash is a legal filename character on Linux and in git, so folding it to slash # would merge two distinct tree paths. Any raw key containing "\" refuses # envelope_oracle_unproven, whether the hash changed, stayed the same, or collides - # with a slash spelling in the same map. + # with a slash spelling in the same map. Coverage includes embedded, trailing, + # leading, doubled and "\/" spellings, so a check of only "\\" in key.strip("\\") + # (which ignores edge backslashes) cannot pass. digest, changed = "1" * 40, "9" * 40 canonical = "tests/test_review_packet.py" - for spelling in (r"tests\test_review_packet.py", r"tests\test_review_packet.py/", - r"foo\bar.py", r"tests/foo\bar.py"): + spellings = ( + r"tests\test_review_packet.py", + r"tests\test_review_packet.py/", + r"foo\bar.py", + r"tests/foo\bar.py", + "tests/test_review_packet.py\\", # trailing + "\\tests/test_review_packet.py", # leading + "tests\\\\test_review_packet.py", # doubled + "tests/test_review_packet.py\\/", # x.py\/ + "tests\\/test_review_packet.py", # \/ + ) + for spelling in spellings: self.refused("envelope_oracle_unproven", self.refreeze(), measured=base.facts(oracle={"old": {spelling: digest}, "new": {spelling: changed}})) self.refused("envelope_oracle_unproven", self.refreeze(), @@ -202,24 +225,35 @@ def test_a_backslash_in_an_oracle_key_is_unproven(self): measured=base.facts(oracle={"old": {spelling: digest}, "new": {canonical: changed}})) self.refused("envelope_oracle_unproven", self.refreeze(), measured=base.facts(oracle={"old": {spelling: digest}, "new": {spelling: digest}})) - colliding = {canonical: digest, r"tests\test_review_packet.py": digest} - clean = {canonical: digest, "tests/conftest.py": digest} - self.refused("envelope_oracle_unproven", self.refreeze(), - measured=base.facts(oracle={"old": colliding, "new": clean})) - self.refused("envelope_oracle_unproven", self.refreeze(), - measured=base.facts(oracle={"old": clean, "new": colliding})) + for spelling in spellings: + colliding = {canonical: digest, spelling: digest} + clean = {canonical: digest, "tests/conftest.py": digest} + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": colliding, "new": clean})) + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": clean, "new": colliding})) def test_a_slash_to_backslash_swap_is_unproven(self): - # Real-git case: git mv tests/test_review_packet.py to a literal backslash filename - # keeps the blob and pytest stops collecting the file. Both directions must refuse - # (envelope_oracle_unproven), not compare as unchanged after normalisation. + # Real-git cases: git mv to a literal backslash filename (embedded, trailing, + # leading, doubled, or "\/") keeps the blob and pytest stops collecting the + # file. Both directions must refuse envelope_oracle_unproven, not compare as + # unchanged after normalisation. Trailing backslash is the case a + # "\\" in key.strip("\\") check misses. digest = "03348f5f0f815389d5261ab8ed4aff3e237e68bc" slash = "tests/test_review_packet.py" - backslash = r"tests\test_review_packet.py" - self.refused("envelope_oracle_unproven", self.refreeze(), - measured=base.facts(oracle={"old": {slash: digest}, "new": {backslash: digest}})) - self.refused("envelope_oracle_unproven", self.refreeze(), - measured=base.facts(oracle={"old": {backslash: digest}, "new": {slash: digest}})) + swaps = ( + r"tests\test_review_packet.py", + "tests/test_review_packet.py\\", + "\\tests/test_review_packet.py", + "tests\\\\test_review_packet.py", + "tests/test_review_packet.py\\/", + "tests\\/test_review_packet.py", + ) + for backslash in swaps: + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": {slash: digest}, "new": {backslash: digest}})) + self.refused("envelope_oracle_unproven", self.refreeze(), + measured=base.facts(oracle={"old": {backslash: digest}, "new": {slash: digest}})) def test_a_non_hex_oracle_value_refuses(self): good = {"tests/test_review_packet.py": "1" * 40, "tests/conftest.py": "2" * 40} @@ -238,9 +272,10 @@ def test_a_non_hex_oracle_value_refuses(self): both = dict(good, **{"tests/test_review_packet.py": value}) self.refused("envelope_oracle_unproven", self.refreeze(), measured=base.facts(oracle={"old": both, "new": dict(both)})) - # Lowercase 40- and 64-character hex values remain accepted. The tests do not require - # uppercase or mixed-case hex to be accepted (an implementer may treat lowercase as - # canonical). Comparison is exact, so a case mismatch of the same digest is not "unchanged". + # Lowercase 40- and 64-character hex values remain accepted. Uppercase and mixed-case + # hex are unspecified: an implementer may accept them or treat lowercase as canonical. + # The tests do not require either behaviour. Comparison of accepted values is exact, + # so a case mismatch of the same digest is not treated as unchanged. class ProductionCheckTest(unittest.TestCase): From 6447de110d7190efa324a3f17afc6d9373f0cc36 Mon Sep 17 00:00:00 2001 From: "MR.INDIA" Date: Sat, 28 Nov 2026 06:30:45 -0500 Subject: [PATCH 7/7] fix(preauth): parse the trust root like ssh-keygen; normalise re-freeze oracle maps Contract preauth-envelope-r7 (fcf5664b). trust_fingerprints works on bytes: refuses any byte outside printable ASCII plus tab/LF/CR, splits on LF only, strips one trailing CR, trims space/tab only. The re-freeze oracle compares normalised maps: backslash keys, non-hex values and normalisation collisions refuse envelope_oracle_unproven. Bee attempt att_7d73fd7698f1ea0c (go:deepseek-v4.1-flash), verified by the coordinator. --- scripts/preauth.py | 50 +++++++++++++++++++++++++++++++++------------- 1 file changed, 36 insertions(+), 14 deletions(-) diff --git a/scripts/preauth.py b/scripts/preauth.py index ce2ce57..df739db 100644 --- a/scripts/preauth.py +++ b/scripts/preauth.py @@ -61,6 +61,7 @@ }) HOOK_NAMES = frozenset({"sitecustomize.py", "usercustomize.py"}) STAMP = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z") +TRUST_ROOT_BYTES = frozenset(range(0x20, 0x7f)) | {9, 10, 13} PRINCIPAL = re.compile(r"[A-Za-z0-9._@-]{1,64}") @@ -215,25 +216,29 @@ def fingerprint_of(blob): def trust_fingerprints(raw, trusted): if not isinstance(raw, bytes): refuse("envelope_signers_invalid") - try: - text = raw.decode("utf-8") - except UnicodeDecodeError: - refuse("envelope_signers_invalid") + for value in raw: + if value not in TRUST_ROOT_BYTES: + refuse("envelope_signers_invalid") found = [] - for line in text.splitlines(): - stripped = line.strip() - if not stripped or stripped.startswith("#"): + for line in raw.split(b"\n"): + if line.endswith(b"\r"): + line = line[:-1] + if b"\r" in line: + refuse("envelope_signers_invalid") + stripped = line.strip(b" \t") + if not stripped or stripped.startswith(b"#"): continue parts = stripped.split() if len(parts) < 4: refuse("envelope_signers_invalid") - if not principal_ok(parts[0]): + principal = parts[0].decode("ascii") + if not principal_ok(principal): refuse("envelope_signers_invalid") - if parts[1] != NAMESPACE_OPTION: + if parts[1].decode("ascii") != NAMESPACE_OPTION: refuse("envelope_signers_invalid") - if parts[2] not in KEY_TYPES: + if parts[2].decode("ascii") not in KEY_TYPES: refuse("envelope_signers_invalid") - found.append(fingerprint_of(parts[3])) + found.append(fingerprint_of(parts[3].decode("ascii"))) if not found: refuse("envelope_signer_untrusted") for item in found: @@ -299,6 +304,21 @@ def normalize_path(value): return "/".join(result) +def normalized_map(measured): + result = {} + for key, value in measured.items(): + if not isinstance(key, str) or "\\" in key: + refuse("envelope_oracle_unproven") + if not (isinstance(value, str) and len(value) in (40, 64) + and all(ch in "0123456789abcdefABCDEF" for ch in value)): + refuse("envelope_oracle_unproven") + path = normalize_path(key) + if path in result: + refuse("envelope_oracle_unproven") + result[path] = value + return result + + def is_oracle(path, test_files): lower = path.lower() parts = lower.split("/") @@ -423,12 +443,14 @@ def _decide(data, signature, allowed_signers, allowed_signers_bytes, policy_byte test_files = entry.get("test_files", []) if not isinstance(test_files, list): test_files = [] - old_paths = oracle_paths(old.keys(), test_files) - new_paths = oracle_paths(new.keys(), test_files) + old_map = normalized_map(old) + new_map = normalized_map(new) + old_paths = oracle_paths(old_map.keys(), test_files) + new_paths = oracle_paths(new_map.keys(), test_files) if old_paths != new_paths: refuse("envelope_oracle_changed") for path in old_paths: - if old.get(path) != new.get(path): + if old_map.get(path) != new_map.get(path): refuse("envelope_oracle_changed") return { "ok": True,