diff --git a/.github/workflows/web-runtime-parity.yml b/.github/workflows/web-runtime-parity.yml index 799672c..4e58e84 100644 --- a/.github/workflows/web-runtime-parity.yml +++ b/.github/workflows/web-runtime-parity.yml @@ -9,6 +9,8 @@ name: Web runtime platform checks - 'nilstd/**' - 'common/webview_*' - 'common/content_digest.hpp' + - 'common/private_directory.hpp' + - 'common/windows_private_storage.hpp' - 'tests/net_*' - 'tests/file_time_support_tests.cpp' - 'tests/rooted_file_snapshot_tests.cpp' @@ -29,7 +31,10 @@ name: Web runtime platform checks - 'tests/console_input_state_tests.cpp' - 'tests/durable_file_io_tests.cpp' - 'tests/durable_vm_lifecycle_tests.cpp' + - 'tests/windows_durable_file_io_tests.cpp' + - 'tests/windows_durable_publication_tests.cpp' - 'tests/tools/durable_file_io_contract.py' + - 'tests/tools/windows_durable_oracle.py' - 'tests/tools/ordinary_io_parity_contract.py' - 'tests/native_output_staging.py' - 'validation/ny-3d/scripts/debugger_process.py' @@ -107,12 +112,16 @@ jobs: timeout-minutes: 40 run: | set -o pipefail + nil_windows_targets=() + if [[ "$RUNNER_OS" == Windows ]]; then + nil_windows_targets=(nil_windows_durable_file_io_tests nil_windows_durable_publication_tests) + fi cmake --build build/web-parity --config Release --parallel 2 \ --target nilcompiler nilinterpreter nilassembler nillinker ny_class_vm_tests nil_net_support_tests \ nil_net_lifecycle_tests nil_file_time_support_tests \ nil_rooted_file_snapshot_tests nil_webview_runtime_tests \ nil_console_input_state_tests nil_durable_file_io_tests \ - nil_durable_vm_lifecycle_tests nilruntime \ + nil_durable_vm_lifecycle_tests nilruntime "${nil_windows_targets[@]}" \ 2>&1 | tee build/web-parity-evidence/build.log - name: Run real peer and language contracts timeout-minutes: 8 @@ -154,19 +163,69 @@ jobs: assert by_name['ny.global-contract'].findtext('system-out', '').strip() == ( 'global contracts passed: 9 negative and 3 control cases in text/binary NIL\n' 'nominal global contracts passed: 8 VM executions, 2 initialization rejections, 0 native rejections') - # The Windows helper exercises checked unsupported errors and nonmutation. - # Do not count its zero-check VM lifecycle or skipped POSIX route as support. (root/'durable-platform-boundary.json').write_text(json.dumps({ - 'platform': os.name, 'durable_api': 'unsupported' if os.name == 'nt' else 'POSIX', + 'platform': os.name, 'durable_api': 'local-NTFS' if os.name == 'nt' else 'POSIX', 'helper_contract': 'nil.durable-file-io', 'helper_status': 'PASS', - 'release_qualification': False}, indent=2)+'\n') + 'release_qualification': False, 'power_cut_qualification': False}, indent=2)+'\n') PY - - name: Verify POSIX durable publication and lock lifetime - if: runner.os != 'Windows' + - name: Verify Win32 private files, locks and publication barriers + if: runner.os == 'Windows' + timeout-minutes: 4 + run: | + "$NIL_CI_PYTHON" - <<'PYTHON' + import json, subprocess, xml.etree.ElementTree as ET + from pathlib import Path + root = Path('build/web-parity-evidence').resolve() + expected = { + 'nil.windows-private-files-locks': ( + 'windows-durable-file-io-ok: 20 contracts; 18 invalid paths', { + 'exclusive-owner-only-create', 'inherited-owner-only-profile', + 'public-parent-private-creation-access-check', 'public-acl-false-and-lock-refusal', + 'wrong-owner-descriptor-false', 'cross-kind-false', 'junction-no-follow-and-no-adoption', + 'single-link-required', 'missing-and-uninspectable-are-errors', + 'utf8-without-code-page-conversion', 'invalid-paths-no-normalization-or-mutation', + 'registry-ownership-stale-and-monotonic-tokens', 'no-clobber-create-and-payload-preservation', + 'live-handle-pins-final-namespace-entry', 'clear-retires-all-tokens-and-closes-handles', + 'registry-destruction-releases-os-lock', 'cross-process-registry-contention', + 'external-lockfileex-contends-with-registry', 'registry-contends-with-external-lockfileex', + 'child-normal-release-and-process-death-release'}), + 'nil.windows-durable-publication': ( + 'windows-durable-publication-ok: 15 contracts; 16 invalid paths', { + 'real-local-ntfs-and-directory-flush', 'binary-create-private-and-ordered-barriers', + 'no-clobber-preserves-existing-bytes-and-links', 'replacement-uses-fresh-private-single-link-file', + 'replace-absent-and-empty-payload', 'staging-flush-failure-preserves-prior-state', + 'post-publication-flush-failure-reports-uncertainty', 'explicit-directory-flush-failure', + 'post-publication-close-failure-still-flushes-directory', + 'unsupported-filesystem-fails-before-mutation', 'wrong-kind-and-final-reparse-rejected', + 'reparse-parent-is-not-followed', 'missing-parent-and-invalid-operands', + 'occupied-destination-preserved-on-rename-failure', 'directory-handle-pins-publication-namespace'})} + base = ['ctest', '--test-dir', 'build/web-parity', '-C', 'Release', '-R', + r'^nil[.]windows-(private-files-locks|durable-publication)$'] + inventory = subprocess.check_output(base+['--show-only=json-v1'], timeout=30) + (root/'windows-durable-inventory.json').write_bytes(inventory) + tests = json.loads(inventory)['tests'] + assert len(tests) == 2 and {test['name'] for test in tests} == set(expected) + with (root/'windows-durable.log').open('wb') as output: + result = subprocess.run(base+['--no-tests=error', '--output-on-failure', + '--test-output-size-passed', '65536', '--output-junit', str(root/'windows-durable-results.xml')], + stdout=output, stderr=subprocess.STDOUT, timeout=200) + print((root/'windows-durable.log').read_text(errors='replace')) + result.check_returncode() + cases = list(ET.parse(root/'windows-durable-results.xml').getroot().iter('testcase')) + assert len(cases) == 2 and {case.get('name') for case in cases} == set(expected) + for case in cases: + assert case.get('status') == 'run' and all(case.find(kind) is None + for kind in ['failure', 'error', 'skipped']) + summary, groups = expected[case.get('name')] + lines = case.findtext('system-out', '').splitlines() + assert len(lines) == len(groups)+1 and lines[-1] == summary + assert set(lines[:-1]) == {'PASS '+group for group in groups} + PYTHON + - name: Verify durable publication and lock lifetime on the host timeout-minutes: 6 run: | "$NIL_CI_PYTHON" - <<'PYTHON' - import hashlib, json, re, subprocess, xml.etree.ElementTree as ET + import hashlib, json, os, re, subprocess, xml.etree.ElementTree as ET from pathlib import Path BUILD, LLVM = 'build/web-parity', False root = Path('build/web-parity-evidence').resolve() @@ -193,7 +252,8 @@ jobs: assert len(reports) == 1, reports proof = json.loads(reports[0].read_text()) assert proof['schema'] == 'nil.durable-file-io.v1' and proof['status'] == 'PASS' - assert proof['scope'] == 'POSIX_SOURCE_RUNTIME_NOT_RELEASE_OR_POWER_CUT_QUALIFICATION' + assert proof['scope'] == ('WINDOWS_NTFS_SOURCE_RUNTIME_NOT_RELEASE_OR_POWER_CUT_QUALIFICATION' + if os.name == 'nt' else 'POSIX_SOURCE_RUNTIME_NOT_RELEASE_OR_POWER_CUT_QUALIFICATION') assert proof['llvm_enabled'] is LLVM and proof['cleanup_verified'] is True routes = ['text-vm', 'binary-vm'] + (['aot', 'jit'] if LLVM else []) expected_routes = {(language, language+'-'+route) for language in ['ny', 'matrix'] for route in routes} @@ -202,7 +262,21 @@ jobs: oracle = {'bytes': 'exact', 'modes': '0600', 'remaining_staging_files': 0, 'lock_after_process_completion': 'released', 'private_directories': ['private'], 'directory_modes': '0700'} - assert all(row['status'] == 'PASS' and row['oracle'] == oracle for row in proof['executions']) + if os.name == 'nt': + fixed = {'bytes': 'exact', 'filesystem': 'local-NTFS', 'remaining_staging_files': 0, + 'lock_after_process_completion': 'released', 'lock_primitive': 'LockFileEx-byte-0-length-1', + 'private_directories': ['private'], 'windows_owner': 'effective-user', + 'windows_dacl': 'one-FILE_ALL_ACCESS-owner-allow-ACE'} + entries = {'.', 'private', 'checkpoint.bin', 'empty.bin', 'writer.lock'} + for row in proof['executions']: + observed = row['oracle'] + assert row['status'] == 'PASS' and set(observed) == set(fixed) | {'windows_acl_profiles', 'windows_acl_sha256'} + assert all(observed[key] == value for key, value in fixed.items()) + assert set(observed['windows_acl_profiles']) == set(observed['windows_acl_sha256']) == entries + assert all(value in ['protected-owner', 'inherited-owner'] for value in observed['windows_acl_profiles'].values()) + assert all(re.fullmatch(r'[0-9a-f]{64}', value) for value in observed['windows_acl_sha256'].values()) + else: + assert all(row['status'] == 'PASS' and row['oracle'] == oracle for row in proof['executions']) invalid = ['width', 'owner', 'query-width', 'query-owner'] negative_routes = ['text-vm', 'binary-vm'] + (['llvm-aot'] if LLVM else []) expected_negative = {(case, route) for case in invalid for route in negative_routes} @@ -217,6 +291,10 @@ jobs: assert len(proof['negative_library']) == len(expected_library) == 36 assert {(row['operation'], row['route'], row['schema']) for row in proof['negative_library']} == expected_library assert all(row['status'] == 'PASS' and row['filesystem'] == 'unchanged' for row in proof['negative_library']) + if os.name == 'nt': + for row in proof['negative_library']: + assert set(row['windows_acl_sha256']) == {'file', 'directory'} + assert all(re.fullmatch(r'[0-9a-f]{64}', value) for value in row['windows_acl_sha256'].values()) expected_commands = {'runtime-selection': False} for language in ['ny', 'matrix']: for encoding in ['text', 'binary']: @@ -235,7 +313,7 @@ jobs: for encoding in ['text', 'binary']: for schema in ['schema', 'no-schema']: expected_commands['foreign-'+operation+'-'+encoding+'-'+schema] = True - assert len(proof['commands']) == len(expected_commands) + assert len(proof['commands']) == len(expected_commands) == (71 if LLVM else 61) assert {row['name'] for row in proof['commands']} == set(expected_commands) for row in proof['commands']: assert row['cleanup_verified'] is True and not row.get('timed_out') and not row.get('error') @@ -252,6 +330,8 @@ jobs: for case in invalid: filename = ('query-invalid-'+case[len('query-'):]) if case.startswith('query-') else 'invalid-'+case inputs[case] = Path('tests/language/durable-file-io-'+filename+'.ny').resolve() + if os.name == 'nt': + inputs['windows_oracle'] = Path('tests/tools/windows_durable_oracle.py').resolve() def record(path): hasher = hashlib.sha256() with path.open('rb') as stream: @@ -348,6 +428,20 @@ jobs: inputs[name] = dict(bytes=len(data), sha256=hashlib.sha256(data).hexdigest()) (root/'nominal-global-inputs.json').write_text(json.dumps(dict( revision=revision, files=inputs), indent=2)+'\n') + durable_inputs = [ + 'nilcompiler/src/secure_file_io.cpp', 'nilcompiler/src/secure_file_io.hpp', + 'nilcompiler/src/native_runtime.cpp', + 'nilcompiler/src/windows_private_entries.hpp', 'nilcompiler/src/windows_durable_publication.hpp', + 'common/private_directory.hpp', 'common/windows_private_storage.hpp', + 'tests/windows_durable_file_io_tests.cpp', 'tests/windows_durable_publication_tests.cpp', + 'tests/durable_file_io_tests.cpp', 'tests/durable_vm_lifecycle_tests.cpp', + 'tests/tools/durable_file_io_contract.py', 'tests/tools/windows_durable_oracle.py'] + durable_files = {} + for name in durable_inputs: + data = Path(name).read_bytes() + durable_files[name] = dict(bytes=len(data), sha256=hashlib.sha256(data).hexdigest()) + (root/'windows-durable-inputs.json').write_text(json.dumps(dict( + revision=revision, files=durable_files), indent=2)+'\n') files = {} for path in sorted(root.rglob('*')): if path.is_file() and not path.is_symlink(): diff --git a/CMakeLists.txt b/CMakeLists.txt index 2264eb6..5f14ea5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -116,6 +116,21 @@ if(BUILD_TESTING) target_compile_definitions(nil_durable_file_io_tests PRIVATE NIL_TEST_WRAP_FSYNC=1) target_link_options(nil_durable_file_io_tests PRIVATE "-Wl,--wrap=fsync") endif() + if(WIN32) + target_link_libraries(nil_durable_file_io_tests PRIVATE advapi32) + add_executable(nil_windows_durable_file_io_tests + tests/windows_durable_file_io_tests.cpp + nilcompiler/src/secure_file_io.cpp) + target_compile_features(nil_windows_durable_file_io_tests PRIVATE cxx_std_17) + target_link_libraries(nil_windows_durable_file_io_tests PRIVATE advapi32) + add_test(NAME nil.windows-private-files-locks COMMAND $) + set_tests_properties(nil.windows-private-files-locks PROPERTIES LABELS "stdlib;io;security;windows;rc" TIMEOUT 90) + add_executable(nil_windows_durable_publication_tests tests/windows_durable_publication_tests.cpp) + target_compile_features(nil_windows_durable_publication_tests PRIVATE cxx_std_17) + target_link_libraries(nil_windows_durable_publication_tests PRIVATE advapi32) + add_test(NAME nil.windows-durable-publication COMMAND $) + set_tests_properties(nil.windows-durable-publication PROPERTIES LABELS "stdlib;io;security;windows;rc" TIMEOUT 90) + endif() add_test(NAME nil.durable-file-io COMMAND $) set_tests_properties(nil.durable-file-io PROPERTIES LABELS "stdlib;io;security;rc" TIMEOUT 30) add_executable(nil_durable_vm_lifecycle_tests tests/durable_vm_lifecycle_tests.cpp) diff --git a/README.md b/README.md index 414ad6b..4798669 100644 --- a/README.md +++ b/README.md @@ -283,17 +283,22 @@ The [Goetic/Enigma integration](https://github.com/exec-software/exec-nil-framew additionally combines those compiler and editor fixes with [durable files and context-owned locks](docs/standard-library/durable-files.md), private-entry checks, SHA-256, optional console input and native hexadecimal -random draws. Durable filesystem operations currently support POSIX hosts; -Windows returns explicit unsupported errors. The +random draws. The source also implements Windows private entries and context-owned +locks; Windows durable writes and directory synchronization require local NTFS. +The `b564ef6` Windows development SDK passes 609 source tests, with two headless +display skips, all 1,248 installed ordinary routes, and the installed durable, +console and global-state checks. The [Windows qualification record](notebook/2026-11-21-windows-durable-parity.md) +pins the SDK and later qualification helper separately. Desktop acceptance and +stable-release qualification remain separate. The [integration notebook](notebook/2026-11-21-goetic-enigma-sdk.md) separates source checks, installed SDK evidence and remaining limitations. The interpreter also preserves imported class values through typed module globals, record wrappers and explicit `Option` factories. Native aggregate globals remain unsupported. The real Goetic/Enigma snapshot and optional-value consumers pass against the relocated Linux development SDK. -The current Linux development SDK passes 609 source tests and 1,248 installed -artifact routes; all four hosts pass 18 interpreter contracts and 32 fixture -routes each. Admission indexing reduces the measured Goetic parse/load time +The earlier `167ae3a` Linux development SDK campaign passed 609 source tests and +1,248 installed artifact routes; its four-host campaign passed 18 interpreter +contracts and 32 fixture routes per host. Admission indexing reduces the measured Goetic parse/load time from 45.58 seconds to 0.45 seconds. With the updated SDK, an isolated Goetic instance reached HTTP readiness in 0.56 seconds within its unchanged ten-second deadline. Its complete application suite passes all 26 Matrix fixtures and 101 diff --git a/docs/design/NIL-0028-durable-files-and-locks.md b/docs/design/NIL-0028-durable-files-and-locks.md index fa6f877..f23e2bc 100644 --- a/docs/design/NIL-0028-durable-files-and-locks.md +++ b/docs/design/NIL-0028-durable-files-and-locks.md @@ -1,7 +1,9 @@ # NIL-0028: Durable publication and context-owned file locks -- **Status:** Implemented additive POSIX source-runtime profile; release SDK - qualification remains separate. +- **Status:** Implemented POSIX and Windows providers. Windows source and + [installed development SDK qualification](../../notebook/2026-11-21-windows-durable-parity.md) + pass; stable-release qualification remains separate. Windows durable + publication requires local NTFS. ## Motivation @@ -17,12 +19,28 @@ semantics, permission policy, and recovery decisions stay in the application. Add `write_bytes_durable`, `sync_directory`, `acquire_file_lock`, `release_file_lock`, and `file_lock_is_held`. Preserve the existing `write_bytes_atomic` and `File.flush` -contracts. Durable writes reuse the atomic publication helper and synchronize -the exact publication directory descriptor. A post-publication sync failure -returns an explicitly uncertain outcome. +contracts. POSIX durable writes reuse the atomic publication helper and +synchronize the exact publication directory descriptor. Windows uses a private +staging file created relative to a held directory, flushes file data, renames +relative to the same handle, closes the writing handle and synchronizes that +directory. A post-publication synchronization or Windows close failure returns +an explicitly uncertain outcome; the final directory flush is attempted even +after a reported close failure. + +Before mutation, Windows must positively identify the held directory as local, +writable NTFS with persistent ACLs. This follows +[MS-FSA directory-flush semantics](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fsa/0de7dc40-9627-437e-a4df-c4696cdc3d02) +and [Appendix A note 80](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fsa/4e3695bd-7574-4f24-a223-b4679c065b63): +success on another filesystem does not establish directory persistence. No +volume-wide flush or enabled privilege substitutes for that check. Cleanup of +unpublished staging uses its held handle, never a potentially replaced name. File locks are nonblocking exclusive advisory locks on private regular backing -files. Runtime-owned registries hold the descriptors. Tokens are never recycled, +files. POSIX uses `flock`; Windows uses nonblocking exclusive +[`LockFileEx`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfileex) +over byte zero, length one. Windows handles are not inheritable and pin the +backing entry against deletion/rename. Runtime-owned registries hold the +descriptors or handles. Tokens are never recycled, are checked against their owning execution context, and are closed at invocation termination and context teardown. An execution checkpoint cannot clone one. Unsupported platforms fail closed before mutation. @@ -46,18 +64,25 @@ The Enigma consumer also requires the existing `text.byte_at` and `from_byte` operations on native routes. Their native providers use the ordinary-I/O bridge and preserve byte/range behavior within the native NUL-free text boundary. -This is a Linux-tested POSIX mechanism, not a production database protocol, +These are filesystem mechanisms, not a production database protocol, power-loss certification, pathname containment service, credential, or general rollback defense. Lock participants must cooperate and control the directory ancestry. Fork-inherited descriptors retain ordinary POSIX lifetime semantics. An uncertain publication requires caller recovery rather than transparent retry. +The POSIX mode/ownership rules are unchanged. Windows uses the exact effective +user's owner-only ACL profile and strict ordinary DOS pathname grammar specified +in [NIL-0029](NIL-0029-private-entries-and-digests.md); the six private-entry/lock +APIs are distinct from the two publication APIs' local-NTFS restriction. Tests cover shared OS helpers, embedded VM invocation/reset/destructor cleanup, static/shared native context lifetimes, ownership queries before and after retirement, Ny/Matrix VM text/binary and AOT/JIT routes, malformed ABI declarations, private file modes, contention, and Linux -file/directory-sync fault injection. Existing secure-byte and ordinary-I/O -regressions remain part of focused validation. +file/directory-sync fault injection. Windows adds independent ACL/file-byte +oracles, actual byte-range lock contention and teardown, and test-only +file/directory-flush and close-error injection. Production has no fault switches. +These coverage requirements do not declare all campaigns completed. Existing +secure-byte and ordinary-I/O regressions remain part of focused validation. The [public API reference](../standard-library/durable-files.md) defines exact limits. Existing SDKs do not gain the new provider from source declarations diff --git a/docs/design/NIL-0029-private-entries-and-digests.md b/docs/design/NIL-0029-private-entries-and-digests.md index cce85d8..79b2967 100644 --- a/docs/design/NIL-0029-private-entries-and-digests.md +++ b/docs/design/NIL-0029-private-entries-and-digests.md @@ -1,7 +1,8 @@ # NIL-0029: Private directory creation, metadata verdicts, and content digests -- **Status:** Implemented additive POSIX source-runtime profile, with a - portable digest; release SDK qualification remains separate. +- **Status:** Implemented POSIX and Windows profiles, with a portable digest. + Windows source and [installed development SDK qualification](../../notebook/2026-11-21-windows-durable-parity.md) + pass; stable-release qualification remains separate. ## Motivation @@ -23,16 +24,40 @@ Add `create_private_directory`, `is_private_regular_file`, `crc32`, which already draws the line between corruption detection and authentication. -Directory creation applies its mode at creation rather than through a later -chmod, which would expose a writable directory in between. An existing entry is +Directory creation applies POSIX mode `0700` or a protected Windows owner-only +security descriptor at creation, without a later permission-repair window. An existing entry is reported, never adopted, so success means the caller created the directory. -Parents are neither created nor trusted beyond existing ancestry rules. +Parents are not created and must remain trusted. The created entry is verified; +failure can leave it in place rather than repairing or removing a potentially +replaced pathname. A restrictive POSIX umask is not changed. The predicates return `Result` so three outcomes stay distinct: the entry was inspected and matches, it was inspected and does not, or it could not be inspected. Collapsing absence into a false verdict would let a caller read "missing" as "unsafe" or the reverse. Inspection does not follow a final -symlink, so a link is judged as itself and never inherits its target's verdict. +symlink or Windows reparse point, so a link is judged as itself and never +inherits its target's verdict. + +Windows inspection uses the effective thread user, or the process user only +when there is no thread token. The entry owner must equal that user SID, not a +default owner group. Its DACL must contain exactly one ordinary allow ACE +granting `FILE_ALL_ACCESS` to the same SID: explicit in a protected DACL, or +inherited from an owner-only parent. Directory ACEs propagate to files and +directories; file ACEs have no propagation flags. Additional, deny, callback, +inherit-only, null and empty ACL profiles fail the predicate. This is a +conservative accepted profile rather than a general access-check engine. +[Handle-based owner/DACL queries](https://learn.microsoft.com/en-us/windows/win32/api/aclapi/nf-aclapi-getsecurityinfo) +never repair permissions. Files must also be disk objects, regular and singly +linked; both kinds reject reparses and delete-pending entries. + +Windows takes strict UTF-8 ordinary relative or drive-absolute DOS paths. UNC, +device and extended namespaces, alternate data streams, drive-relative or +current-drive-rooted paths, empty/dot/parent components, reserved device names, +leading spaces and trailing dots/spaces are rejected. Directory inspection may +accept an explicit drive root; other trailing separators are rejected. See the +[Win32 naming rules](https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file) +and the [public API's pathname profile](../standard-library/durable-files.md#windows-owner-and-pathname-profile). +An inspected final component does not establish safe ancestry or containment. `sha256_hex` returns 64 lowercase hexadecimal characters over every supplied byte, including embedded NULs. It reuses the existing portable implementation, @@ -42,7 +67,7 @@ depend on which route computed it. ## Boundaries and validation A path predicate describes an entry at inspection time. It is not a safe -substitute for opening the entry under `O_NOFOLLOW`, because it cannot close the +substitute for a no-follow open, because it cannot close the window between inspection and use. Publication and lock acquisition keep their own checked opens; these surfaces are for preflight and diagnosis. A caller that needs a guarantee must act on an open descriptor, not on a prior verdict. @@ -52,19 +77,23 @@ signature, a message authentication code, encryption, or rollback protection: whoever can replace the bytes can replace the digest beside them. Authenticating a digest requires a secret these functions do not take. -Mode and owner verdicts describe POSIX ownership and permission bits only. They +On POSIX, mode and owner verdicts describe ownership and permission bits only. They say nothing about ACLs, extended attributes, capabilities, or mandatory access -control, and they are not a security boundary against the owner or root. +control. Windows verdicts describe the explicit ACL profile above. Neither +profile is a security boundary against the owner or a privileged administrator. Tests cover creation mode and exclusivity, cross-kind verdicts, loosened file and directory modes, symlinks to otherwise-private targets, multiply-linked files, FIFOs, uninspectable entries, unsupported-platform behavior before any -mutation, and RFC 6234 digest vectors including embedded NUL bytes. The paired +mutation, and RFC 6234 digest vectors including embedded NUL bytes. Windows +adds protected and inherited owner ACLs, wrong-owner descriptors, extra/denied +rights, junctions, sharing behavior and ambiguous-path rejection. The paired Ny and Matrix fixtures exercise every surface across textual and binary VM, AOT, -and JIT, with an independent host oracle checking directory modes. +and JIT, with independent host oracles checking POSIX modes or Windows owner/ACL +metadata. This describes validation coverage, not completed platform evidence. -Windows returns an explicit unsupported-platform error before filesystem -mutation; the digest is platform-independent. Other POSIX platforms need their -own execution evidence. As with NIL-0028, source declarations alone do not give -an installed SDK the new provider, and release qualification is independent -work. See the [public API reference](../standard-library/durable-files.md). +Windows source and installed development SDK checks pass with independently +verified owner/ACL and byte oracles; the digest is platform-independent. The +qualification record pins the SDK and helper revisions, and does not update an +older installation. Stable-release qualification remains independent work. +See the [public API reference](../standard-library/durable-files.md). diff --git a/docs/design/README.md b/docs/design/README.md index dc9a4ca..cd957f8 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -54,8 +54,8 @@ not assigned architecture identifiers. | NIL-0025 | [Matrix desktop UI](NIL-0025-matrix-desktop-ui.md) | Implemented GTK4 on Linux, Win32 on Windows and AppKit on Intel/Apple Silicon macOS; release qualification remains separate | | NIL-0026 | [Evolving the language without breaking what is written](NIL-0026-language-evolution.md) | Editions implemented in the project manifest | | NIL-0027 | [Multiline formatted text and structured markup literals](NIL-0027-structured-markup.md) | Implemented initial multiline text and structural markup profile for Ny and Matrix; installed SDK evidence is recorded separately | -| NIL-0028 | [Durable publication and context-owned file locks](NIL-0028-durable-files-and-locks.md) | Implemented additive POSIX source-runtime profile; installed/release SDK qualification separate | -| NIL-0029 | [Private directory creation, metadata verdicts, and content digests](NIL-0029-private-entries-and-digests.md) | Implemented additive POSIX source-runtime profile with a portable digest; installed/release SDK qualification separate | +| NIL-0028 | [Durable publication and context-owned file locks](NIL-0028-durable-files-and-locks.md) | Implemented POSIX and Windows providers; local-NTFS Windows source and installed development checks pass; stable-release qualification separate | +| NIL-0029 | [Private directory creation, metadata verdicts, and content digests](NIL-0029-private-entries-and-digests.md) | Implemented POSIX ownership/mode and Windows owner-ACL profiles, with a portable digest; Windows source and installed development checks pass | | NIL-0030 | [Reading a line without faulting at end of input](NIL-0030-end-of-input.md) | Implemented additive surface on every execution route; installed/release SDK qualification separate | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | diff --git a/docs/getting-started/index.md b/docs/getting-started/index.md index 33ebb59..5fc0aa3 100644 --- a/docs/getting-started/index.md +++ b/docs/getting-started/index.md @@ -190,6 +190,14 @@ the SDK, and runs installed source/binary-library consumers outside the checkout Logs and evidence stay beside `sdk`, outside its sealed payload. A failed candidate is retained with `FAILED.txt`; it is not reported ready. +The durable/console/global consumer checks use a fresh private execution directory +under the process's system-temp location, so deeply nested candidate paths do not +consume native tools' temporary-path budget. That execution root must fit within +96 UTF-16 units; if preflight rejects it, select a shorter process `TMP`/`TEMP` +directory. The original execution evidence is retained and an exact hash-verified +copy is stored beside the candidate. Copy or cleanup failures fail qualification. +This layout does not qualify general Windows long-path support. + There is no SDK activation, replacement, release publication, or Lich upload in this workflow. Successful candidates contain eleven `.exe` tools at their root, `nilstd` sources, `nillib` binaries with `native/nil.lib` and `native/nil.dll`, and diff --git a/docs/platform-support.md b/docs/platform-support.md index 79cd32a..6cb26aa 100644 --- a/docs/platform-support.md +++ b/docs/platform-support.md @@ -31,9 +31,19 @@ SDK's manifest. The [Goetic/Enigma integration](../notebook/2026-11-21-goetic-enigma-sdk.md) adds durable publication, context-owned advisory locks and private-entry -inspection. These filesystem APIs have a POSIX implementation; Windows returns -explicit unsupported errors before mutation. A passing Windows rejection test -does not establish support. Native `random_hex`, SHA-256 and optional console +inspection. These filesystem APIs have POSIX and Windows implementations; +Windows durable publication and directory synchronization require local NTFS. +The [Windows development campaign](../notebook/2026-11-21-windows-durable-parity.md) +records 609 passing source tests, two headless display skips and all 1,248 +installed ordinary routes for the `b564ef6` SDK. The later `6bd3b18` helper +qualifies additional installed checks against unchanged SDK bytes. Across both +libraries, these total sixteen durable executions, 24 ABI rejections and 72 +foreign-library rejections, with 184 console checks per library and the nominal +global-state checks. The original failed deep-path qualifier remains recorded; +its shallow-workspace correction preserves the tests and SDK bytes. These results +do not establish current desktop acceptance, bare-host installation or release +qualification, and do not replace the earlier baseline SDKs above. +Native `random_hex`, SHA-256 and optional console input are separate portable additions. New source or installed results are recorded with their exact revision and do not replace the pinned baselines above or establish release qualification. diff --git a/docs/standard-library/durable-files.md b/docs/standard-library/durable-files.md index 314df18..c86c9bc 100644 --- a/docs/standard-library/durable-files.md +++ b/docs/standard-library/durable-files.md @@ -1,8 +1,13 @@ # Durable files and advisory locks -`nil.std.io` provides additive POSIX primitives for applications that need a +`nil.std.io` provides filesystem primitives for applications that need a durable checkpoint and a cooperative single-writer protocol. Ny and Matrix use -the same runtime provider and checked results. +the same runtime provider and checked results. POSIX and Windows providers are +implemented and pass source-runtime checks. The [Windows development SDK +campaign](../../notebook/2026-11-21-windows-durable-parity.md) also passes installed +checks against both source and binary libraries. This is not stable-release or +power-cut qualification. +Windows durable publication and directory synchronization require local NTFS. | Function | Result | | --- | --- | @@ -22,32 +27,52 @@ descriptors or authentication credentials. ## Publication and durability -`write_bytes_durable` keeps the existing atomic byte-write rules: bounded byte -arrays, strict UTF-8 nonempty NUL-free filenames, a fresh private `0600` staging -inode, and no-clobber publication when `replace` is false. Replacement preflight -requires a regular destination, and publication replaces the entry without +`write_bytes_durable` takes bounded byte arrays and strict UTF-8, nonempty, +NUL-free filenames. It creates a fresh private staging file and uses no-clobber +publication when `replace` is false. Replacement preflight requires a regular +destination, and publication replaces the entry without following it. Existing ownership, mode, ACLs, and extended attributes are not -copied. It adds synchronization of the **same directory descriptor** used for -publication, after synchronizing the candidate file and publishing its entry. +copied. On POSIX, the existing atomic helper creates mode `0600` and synchronizes +the **same directory descriptor** used for publication, after synchronizing the +candidate file and publishing its entry. The POSIX contract is unchanged. + +Windows first opens the parent directory without following its final reparse +point and verifies that the held handle identifies writable local NTFS with +persistent ACLs. An unknown, remote or other filesystem is rejected before +staging. The fresh file receives the effective user's protected owner-only +security descriptor at creation. Creation, replacement inspection and rename +are relative to the retained directory handle. The runtime flushes file data, +publishes the name, closes the writing handle, and flushes that same directory. +Failed staging is deleted through its held handle rather than a pathname. Success means those synchronization calls succeeded. It assumes a filesystem -and device stack honoring `fsync` and atomic rename/link. It does not prove -hardware power-cut behavior, protect against privileged namespace replacement, +and device stack honoring the platform's flush and publication operations. It +does not prove hardware power-cut behavior, protect against privileged namespace replacement, or authenticate data. Parent-directory ancestry must be trusted. Cleanup can leave an orphaned `.ny-write-*` entry after a host failure. -If directory synchronization fails after publication, the operation returns +If directory synchronization fails after publication, or the Windows writing +handle reports a close failure after rename, the operation returns `Error("file.write_bytes_durable: publication durability uncertain")`. The candidate may already be visible. A caller must stop or poison its session and recover rather than assume the previous file remains or retry blindly. +Windows still attempts the final directory flush after a reported close failure. + +The Windows restriction follows [MS-FSA directory-flush semantics](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fsa/0de7dc40-9627-437e-a4df-c4696cdc3d02) +and [Appendix A, note 80](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fsa/4e3695bd-7574-4f24-a223-b4679c065b63), +which identify NTFS as implementing directory persistence. A successful flush +on another filesystem is insufficient. The implementation uses +[file/directory flushes](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-flushfilebuffers) +and [native handle-relative rename](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_rename_information), +without a volume-wide flush or enabling privileges. `sync_directory` synchronizes an existing directory selected without following its final component. It is useful after separately controlled namespace changes, including initial directory/lock creation. Its ancestors remain trusted. -Directory synchronization and inspection reject trailing `/` separators except +On POSIX, directory synchronization and inspection reject trailing `/` separators except for filesystem-root paths such as `/`. Pass a named directory without trailing separators: POSIX otherwise resolves a slash-terminated symlink before applying -the final-component no-follow rule. +the final-component no-follow rule. Windows path restrictions are described below. `write_bytes_atomic` retains its visibility-only contract. `File.flush` retains its stream-flush contract; neither acquires the new durability guarantee. @@ -57,10 +82,16 @@ its stream-flush contract; neither acquires the new durability guarantee. `acquire_file_lock(path, true)` exclusively creates a new private backing file; it fails if an entry already exists. Pass `false` to open an existing lock file. The file must be regular, owned by the effective user, have one hard link, and -have exactly mode `0600`. Symlinks, special files, and unsafe permissions fail. -The runtime acquires a nonblocking exclusive advisory `flock`, with close-on-exec -and no-follow/nonblocking open flags, and checks the acquired inode still names -the inspected entry. Paths never appear in returned diagnostics. +have exactly mode `0600` on POSIX, or match the Windows owner-only ACL profile +below. Symlinks/reparse points, special files and nonmatching permissions fail. +On POSIX the runtime acquires a nonblocking exclusive advisory `flock`, with +close-on-exec and no-follow/nonblocking open flags, and checks the acquired inode still names +the inspected entry. On Windows it requests an exclusive, nonblocking +[`LockFileEx`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfileex) +lock at byte zero with length one, including on an empty backing file. The +handle is not inheritable and denies delete sharing, pinning the final entry +against rename/deletion while held. The runtime checks the held and visible +file identities and private metadata. Paths never appear in returned diagnostics. All writers must use the same persistent lock entry. Do not unlink or replace that file while participants may still hold it. Creating the file does not @@ -96,39 +127,79 @@ outside the string; out-of-range byte construction returns empty text. Native for arbitrary binary content. Joining nonzero byte fragments preserves their bytes, including UTF-8 sequences. -The source-runtime tests exercise Ny and Matrix through textual and binary VM, +The source-runtime contracts cover Ny and Matrix through textual and binary VM, AOT, and JIT, with exact host byte/mode oracles, checked ABI failures, runtime context teardown, and process death. Linux helper tests inject file and directory -sync failures, including uncertain publication. Windows returns an explicit -unsupported-platform error before filesystem mutation. Other POSIX platforms -need their own execution evidence; this addition does not qualify an installed -or release SDK. +sync failures, including uncertain publication. Windows contracts cover owner +ACLs, reparse and hard-link rejection, context-owned byte-range locks, local-NTFS +publication, and failures before and after publication. Test-only Win32 wrappers +inject flush/close failures; the production provider has no fault switches. +An independent Windows oracle checks held file bytes, owner/DACL, file identity, +namespace and externally reacquired locks. Implemented tests are not a claim +that every platform campaign has completed. Current-source, installed-SDK and +release evidence remain separate, including for macOS and Windows. ## Private entries and digests `create_private_directory` exclusively creates one owner-only directory: POSIX -mode `0700`, applied by creation rather than a later chmod, which would leave a -writable window. An existing entry is reported, never adopted, so success means -this call created an owned directory with exactly mode `0700`. If the process +mode `0700` or a protected Windows owner-only descriptor, applied at creation. +An existing entry is reported, never adopted. On POSIX success requires an +owned directory with exactly mode `0700`. If the process umask removes owner permissions, creation returns an error and can leave the new directory in place; it does not change the umask or repair permissions. +Windows likewise verifies the created entry through a no-follow handle and can +leave the new entry on a verification failure; it does not repair its ACL or +delete through a potentially replaced pathname. Parents are not created and remain trusted. Creation does not durably publish the new name; call `sync_directory` when that matters. `is_private_regular_file` asks whether an entry is regular, owned by the -effective user, singly linked, and exactly mode `0600`. `is_private_directory` -asks whether it is a directory owned by the effective user with exactly mode -`0700`. Neither follows a final symlink, so a link is judged as itself and does -not inherit its target's verdict. Directory inspection uses the same -trailing-separator operand rule as `sync_directory`. +effective user and singly linked. On POSIX it additionally requires exactly +mode `0600`; `is_private_directory` requires effective-user ownership and mode +`0700`. On Windows both require the owner-only ACL profile below. Neither follows +a final symlink/reparse point, so a link is judged as itself and does not inherit +its target's verdict. Directory inspection rejects trailing separators except +filesystem roots. An `Error` means the entry could not be inspected, which is distinct from a verdict of `false`. Both are distinct from being safe to use: these inspect a path, so the entry can change between inspection and use. Treat them as preflight and diagnosis. A caller needing a guarantee must act on an open descriptor; durable publication and lock acquisition keep their own checked -no-follow opens. The verdicts describe POSIX owner and permission bits only, -not ACLs, extended attributes, capabilities, or mandatory access control. +no-follow opens. POSIX verdicts describe owner and permission bits only, not ACLs, +extended attributes, capabilities or mandatory access control. + +### Windows owner and pathname profile + +The three private-entry APIs and three lock APIs use the effective thread user, +falling back to the process user only when no thread token exists. The entry +owner must equal that user's SID, not a default owner group. The DACL must +contain exactly one ordinary allow ACE granting `FILE_ALL_ACCESS` to that SID. +It must be explicit in a protected DACL or inherited from an owner-only parent. +Directory ACEs propagate to both files and directories; file ACEs have no +propagation flags. Null, empty, extra, deny, callback and inherit-only ACE +profiles are rejected. This conservative profile can reject other restrictive +ACL arrangements; it is not a general effective-permissions calculator. +[Win32 owner/DACL inspection](https://learn.microsoft.com/en-us/windows/win32/api/aclapi/nf-aclapi-getsecurityinfo) +does not modify the entry. Reparse points, wrong kinds, delete-pending entries +and multiply-linked regular files return a false verdict when inspectable; +missing entries and inspection failures return `Error`. + +These Windows APIs accept ordinary relative names and drive-absolute DOS paths +with either separator. They reject UNC/device/extended namespaces, alternate +data streams, drive-relative or current-drive-rooted paths, empty/dot/parent +components, reserved DOS basenames, leading spaces, and trailing dots/spaces. +A trailing separator is accepted only for an explicit drive root where a +directory operand is allowed. `sync_directory(".")` additionally selects the +current directory; a bare durable-write filename uses that same parent +internally. Suffixes such as `dir/.` are rejected. These restrictions avoid +[Win32 name normalization and device aliases](https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file). +They do not validate ancestor ownership or create a pathname sandbox. The +local-NTFS restriction applies specifically to durable writes and directory +synchronization; all six private-entry/lock APIs still require their checked +Windows metadata and handle operations to succeed. + +### Content digests `sha256_hex` returns 64 lowercase hexadecimal characters over every supplied byte, embedded NULs included, bounded like the other byte-array operations. It diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index e44ff3c..aba65d0 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -161,8 +161,14 @@ The additive [durable-files reference](durable-files.md) covers `write_bytes_durable`, `sync_directory`, context-owned advisory file locks and the `file_lock_is_held` ownership query, owner-only directory creation, private-entry metadata verdicts, and portable -`sha256_hex`. The filesystem primitives are POSIX-only; Windows reports an -explicit unsupported error. They supply filesystem barriers and nonblocking +`sha256_hex`. The filesystem primitives have POSIX and Windows implementations; +Windows durable publication and directory synchronization require local NTFS. +The [Windows development campaign](../../notebook/2026-11-21-windows-durable-parity.md) +passes the private-entry, locking and publication contracts, including installed +Ny/Matrix VM, AOT and JIT routes against both `nilstd` and `nillib` in the +unchanged `b564ef6` SDK. The qualification helper is pinned separately to +`6bd3b18`; stable-release qualification remains separate. These APIs supply +filesystem barriers and nonblocking single-writer coordination. They preserve existing atomic-write/stream-flush semantics and do not expand an older installed SDK's guarantees. diff --git a/nilbuild/windows_toolchain_inputs.hpp b/nilbuild/windows_toolchain_inputs.hpp index e1a270c..69acd0e 100644 --- a/nilbuild/windows_toolchain_inputs.hpp +++ b/nilbuild/windows_toolchain_inputs.hpp @@ -189,7 +189,7 @@ class collector { } } if (error || !library(runtime, 0)) return {}; - for (const auto *name : {"kernel32.lib", "ws2_32.lib", "user32.lib", "gdi32.lib", + for (const auto *name : {"kernel32.lib", "ws2_32.lib", "user32.lib", "gdi32.lib", "advapi32.lib", "msvcrt.lib", "ucrt.lib", "vcruntime.lib", "legacy_stdio_definitions.lib"}) { const auto selected = resolve(name); diff --git a/nilcompiler/CMakeLists.txt b/nilcompiler/CMakeLists.txt index dec1beb..4abda23 100644 --- a/nilcompiler/CMakeLists.txt +++ b/nilcompiler/CMakeLists.txt @@ -92,7 +92,7 @@ foreach(nil_runtime_target IN ITEMS nilruntime nilruntime_shared) # Winsock; propagate it to static build-tree consumers as well as DLLs. # The Win32 desktop provider calls USER32 and GDI32 directly, unlike # the dynamically loaded GTK provider, so those travel the same way. - target_link_libraries(${nil_runtime_target} PUBLIC ws2_32 user32 gdi32) + target_link_libraries(${nil_runtime_target} PUBLIC ws2_32 user32 gdi32 advapi32) endif() if(APPLE) # The AppKit desktop provider calls Cocoa and CoreGraphics directly, diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index 0fa1ff5..44bc3b1 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -2225,7 +2225,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) // otherwise only ever inline - without it a generated call to printf // is an unresolved external. const std::vector windows_crt_libraries = { - "kernel32.lib", "ws2_32.lib", "user32.lib", "gdi32.lib", "msvcrt.lib", + "kernel32.lib", "ws2_32.lib", "user32.lib", "gdi32.lib", "advapi32.lib", "msvcrt.lib", "ucrt.lib", "vcruntime.lib", "legacy_stdio_definitions.lib"}; const auto manifest_path = *private_output_workspace / "utf8.manifest"; const auto manifest_publish = ny::detail::write_file_atomic( @@ -2296,7 +2296,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) std::vector arguments = { driver->u8string(), "-o", link_output_path.u8string(), obj_path.u8string(), native_runtime->u8string(), "ws2_32.lib", - "user32.lib", "gdi32.lib", + "user32.lib", "gdi32.lib", "advapi32.lib", "-Xlinker", "/MANIFEST:EMBED", "-Xlinker", manifest_argument}; arguments.insert(arguments.end(), link_libraries.begin(), link_libraries.end()); diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index 5833b1e..d1463b2 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -1949,8 +1949,7 @@ std::int32_t nyrt_io_v1(const char *operation, std::uint64_t first, #ifdef _WIN32 wchar_t buffer[1024] = {}; DWORD size = static_cast(sizeof(buffer) / sizeof(*buffer)); - // The SDK runtime does not otherwise require an advapi32 import - // library. Resolve only the OS copy, never a working-directory DLL. + // Resolve only the OS copy, never a working-directory DLL. const HMODULE library = LoadLibraryExW(L"advapi32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); if (!library) return fail("user name is unavailable"); const auto get_user_name = reinterpret_cast( diff --git a/nilcompiler/src/secure_file_io.cpp b/nilcompiler/src/secure_file_io.cpp index 0220075..509d52e 100644 --- a/nilcompiler/src/secure_file_io.cpp +++ b/nilcompiler/src/secure_file_io.cpp @@ -43,6 +43,8 @@ #endif #include #include +#include "windows_private_entries.hpp" +#include "windows_durable_publication.hpp" #endif namespace ny::detail { @@ -906,8 +908,10 @@ AtomicFileWrite write_file_atomic(const char *path, AtomicFileWrite sync_directory_utf8(const std::string &path) { #ifdef _WIN32 - (void)path; - return {false, "file.sync_directory: unsupported platform"}; + const auto native_path = path_from_utf8_string(path); + if (!native_path) + return {false, "file.sync_directory: invalid directory path"}; + return windows_durable_publication::sync_directory(*native_path); #else const auto native_path = path_from_utf8_string(path); if (!native_path || !valid_directory_entry_operand(*native_path)) @@ -930,10 +934,10 @@ AtomicFileWrite write_file_durable_utf8(const std::string &path, const std::vector &bytes, bool replace) { #ifdef _WIN32 - (void)path; - (void)bytes; - (void)replace; - return {false, "file.write_bytes_durable: unsupported platform"}; + const auto native_path = path_from_utf8_string(path); + if (!native_path) + return {false, "file.write_bytes_durable: invalid destination path"}; + return windows_durable_publication::write_file(*native_path, bytes, replace); #else const auto native_path = path_from_utf8_string(path); if (!native_path) @@ -942,23 +946,25 @@ AtomicFileWrite write_file_durable_utf8(const std::string &path, #endif } -#ifndef _WIN32 namespace { std::atomic next_lock_token{1}; +#ifndef _WIN32 bool private_lock_file(const struct stat &status) { return S_ISREG(status.st_mode) && status.st_uid == ::geteuid() && status.st_nlink == 1 && (status.st_mode & 07777) == 0600; } +#endif } // namespace -#endif AtomicFileWrite create_private_directory_utf8(const std::string &path) { #ifdef _WIN32 - (void)path; - return {false, "file.create_private_directory: unsupported platform"}; + const auto native_path = path_from_utf8_string(path); + if (!native_path) + return {false, "file.create_private_directory: invalid directory path"}; + return windows_private_entries::create_directory(*native_path); #else const auto native_path = path_from_utf8_string(path); if (!native_path) @@ -988,9 +994,10 @@ AtomicFileWrite create_private_directory_utf8(const std::string &path) { FileCheck private_regular_file_utf8(const std::string &path) { #ifdef _WIN32 - (void)path; - return {false, false, - "file.is_private_regular_file: unsupported platform"}; + const auto native_path = path_from_utf8_string(path); + if (!native_path) + return {false, false, "file.is_private_regular_file: invalid file path"}; + return windows_private_entries::inspect_regular_file(*native_path); #else const auto native_path = path_from_utf8_string(path); if (!native_path) @@ -1007,8 +1014,10 @@ FileCheck private_regular_file_utf8(const std::string &path) { FileCheck private_directory_utf8(const std::string &path) { #ifdef _WIN32 - (void)path; - return {false, false, "file.is_private_directory: unsupported platform"}; + const auto native_path = path_from_utf8_string(path); + if (!native_path) + return {false, false, "file.is_private_directory: invalid directory path"}; + return windows_private_entries::inspect_directory(*native_path); #else const auto native_path = path_from_utf8_string(path); if (!native_path || !valid_directory_entry_operand(*native_path)) @@ -1027,9 +1036,69 @@ FileLockRegistry::~FileLockRegistry() noexcept { clear(); } FileLockResult FileLockRegistry::acquire(const std::string &path, bool create) { #ifdef _WIN32 - (void)path; - (void)create; - return {false, 0, "file.acquire_file_lock: unsupported platform"}; + const auto failure = [](const char *reason) { + return FileLockResult{false, 0, std::string("file.acquire_file_lock: ") + reason}; + }; + const auto native_path = path_from_utf8_string(path); + if (!native_path || !windows_private_entries::valid_path(*native_path)) + return failure("invalid lock path"); + if (descriptors_.size() >= 4096) + return failure("lock limit exceeded"); + nil::detail::owner_security security; + std::error_code error; + if (!security.initialize(false, error)) + return failure("cannot inspect effective identity"); + auto attributes = security.attributes(); + // Permit another cooperating opener to reach LockFileEx, but pin this + // backing entry against rename/delete while the context holds its lock. + UniqueWindowsHandle lock(CreateFileW(native_path->c_str(), + GENERIC_READ | GENERIC_WRITE | READ_CONTROL | FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE, create ? &attributes : nullptr, + create ? CREATE_NEW : OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, nullptr)); + if (lock.get() == INVALID_HANDLE_VALUE) + return failure("cannot open lock file"); + const auto private_entry = windows_private_entries::inspect_handle( + lock.get(), false, "file.acquire_file_lock", security); + if (!private_entry.ok || !private_entry.value) + return failure("lock file is not private and regular"); + // Windows participants coordinate over byte zero (including empty files). + // The immediate flag also applies to synchronous handles: never wait on a + // foreign context's lock, and never issue an asynchronous request. + OVERLAPPED range{}; + if (!LockFileEx(lock.get(), LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, + 0, 1, 0, &range)) + return failure(GetLastError() == ERROR_LOCK_VIOLATION ? "lock is busy" + : "cannot acquire lock"); + UniqueWindowsHandle visible(CreateFileW(native_path->c_str(), + READ_CONTROL | FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, + nullptr, OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, nullptr)); + BY_HANDLE_FILE_INFORMATION held_info{}, visible_info{}; + const auto visible_private = windows_private_entries::inspect_handle( + visible.get(), false, "file.acquire_file_lock", security); + const auto still_private = windows_private_entries::inspect_handle( + lock.get(), false, "file.acquire_file_lock", security); + if (!visible_private.ok || !visible_private.value || !still_private.ok || + !still_private.value || !GetFileInformationByHandle(lock.get(), &held_info) || + !GetFileInformationByHandle(visible.get(), &visible_info) || + held_info.dwVolumeSerialNumber != visible_info.dwVolumeSerialNumber || + held_info.nFileIndexHigh != visible_info.nFileIndexHigh || + held_info.nFileIndexLow != visible_info.nFileIndexLow) + return failure("lock file changed while acquiring"); + auto token = next_lock_token.load(std::memory_order_relaxed); + do { + if (token > static_cast((std::numeric_limits::max)())) + return failure("lock token space exhausted"); + } while (!next_lock_token.compare_exchange_weak(token, token + 1, + std::memory_order_relaxed)); + try { + descriptors_.emplace(static_cast(token), lock.get()); + } catch (const std::bad_alloc &) { + return failure("cannot track lock"); + } + lock.release(); + return {true, static_cast(token), {}}; #else const auto failure = [](const char *reason) { return FileLockResult{false, 0, std::string("file.acquire_file_lock: ") + reason}; @@ -1099,18 +1168,22 @@ FileLockResult FileLockRegistry::acquire(const std::string &path, bool create) { } FileCheck FileLockRegistry::is_held(std::int64_t token) const { -#ifdef _WIN32 - (void)token; - return {false, false, "file.file_lock_is_held: unsupported platform"}; -#else return {true, token > 0 && descriptors_.find(token) != descriptors_.end(), {}}; -#endif } AtomicFileWrite FileLockRegistry::release(std::int64_t token) { #ifdef _WIN32 - (void)token; - return {false, "file.release_file_lock: unsupported platform"}; + const auto found = descriptors_.find(token); + if (found == descriptors_.end()) + return {false, "file.release_file_lock: invalid lock token"}; + const HANDLE handle = found->second; + descriptors_.erase(found); + OVERLAPPED range{}; + const BOOL unlocked = UnlockFileEx(handle, 0, 1, 0, &range); + const BOOL closed = CloseHandle(handle); + if (!unlocked || !closed) + return {false, "file.release_file_lock: release failed"}; + return {true, {}}; #else const auto found = descriptors_.find(token); if (found == descriptors_.end()) @@ -1131,7 +1204,13 @@ AtomicFileWrite FileLockRegistry::release(std::int64_t token) { } void FileLockRegistry::clear() noexcept { -#ifndef _WIN32 +#ifdef _WIN32 + for (const auto &entry : descriptors_) { + OVERLAPPED range{}; + UnlockFileEx(entry.second, 0, 1, 0, &range); + CloseHandle(entry.second); + } +#else for (const auto &entry : descriptors_) ::close(entry.second); #endif diff --git a/nilcompiler/src/secure_file_io.hpp b/nilcompiler/src/secure_file_io.hpp index be77d76..8aafa12 100644 --- a/nilcompiler/src/secure_file_io.hpp +++ b/nilcompiler/src/secure_file_io.hpp @@ -58,7 +58,8 @@ struct FileCheck { // Registry ownership is the execution-context boundary. Tokens are process- // monotonic and never recycled, and never expose the host descriptor. Locks -// are advisory; callers must control the directory ancestry and cooperate. +// coordinate cooperating callers; Windows also enforces the locked byte range. +// Callers must control the directory ancestry. class FileLockRegistry { public: FileLockRegistry() = default; @@ -77,7 +78,12 @@ class FileLockRegistry { bool empty() const noexcept { return descriptors_.empty(); } private: +#ifdef _WIN32 + // HANDLE is pointer-sized. Keep windows.h out of this shared header. + std::map descriptors_; +#else std::map descriptors_; +#endif }; bool valid_file_path(const std::string &path); @@ -90,7 +96,7 @@ BoundedFileRead read_regular_file_bounded_utf8(const std::string &path, AtomicFileWrite write_file_atomic_utf8(const std::string &path, const std::vector &bytes, bool replace); -// POSIX only. Directory synchronization is explicit; durable publication +// POSIX and local NTFS. Directory synchronization is explicit; publication // synchronizes the same anchored directory used to publish the destination. // An error after publication does not imply that the old destination remains. // Directory synchronization and directory metadata inspection reject trailing @@ -99,13 +105,12 @@ AtomicFileWrite sync_directory_utf8(const std::string &path); AtomicFileWrite write_file_durable_utf8(const std::string &path, const std::vector &bytes, bool replace); -// POSIX only. Exclusive owner-only directory creation: an existing entry is -// never adopted, and the final mode is set by creation rather than a later -// chmod, which would leave a writable window. +// Exclusive owner-only directory creation: an existing entry is never adopted. +// POSIX permissions or the Windows owner-only DACL are applied at creation. AtomicFileWrite create_private_directory_utf8(const std::string &path); -// POSIX only. No-follow metadata predicates. These inspect a path, so the +// No-follow metadata predicates. These inspect a path, so the // answer describes the entry at inspection time and is not a safe substitute -// for opening the entry under O_NOFOLLOW: a preflight check cannot close the +// for a checked no-follow open: a preflight check cannot close the // window between inspection and use. Publication and lock acquisition keep // their own checked opens. FileCheck private_regular_file_utf8(const std::string &path); diff --git a/nilcompiler/src/windows_durable_publication.hpp b/nilcompiler/src/windows_durable_publication.hpp new file mode 100644 index 0000000..31edd21 --- /dev/null +++ b/nilcompiler/src/windows_durable_publication.hpp @@ -0,0 +1,307 @@ +#ifndef NIL_WINDOWS_DURABLE_PUBLICATION_HPP +#define NIL_WINDOWS_DURABLE_PUBLICATION_HPP + +#include "secure_file_io.hpp" + +#ifdef _WIN32 +#include "windows_private_entries.hpp" +#include + +#include +#include +#include +#include +#include + +namespace ny::detail::windows_durable_publication { + +using create_file_function = NTSTATUS (NTAPI *)( + PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, PIO_STATUS_BLOCK, PLARGE_INTEGER, + ULONG, ULONG, ULONG, ULONG, PVOID, ULONG); +using query_file_function = NTSTATUS (NTAPI *)( + HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, FILE_INFORMATION_CLASS); +using set_file_function = NTSTATUS (NTAPI *)( + HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, FILE_INFORMATION_CLASS); + +template +inline Function native_function(const char *name) { + const HMODULE module = GetModuleHandleW(L"ntdll.dll"); + const FARPROC symbol = module ? GetProcAddress(module, name) : nullptr; + Function function = nullptr; + static_assert(sizeof(function) == sizeof(symbol), "Windows function pointer size"); + std::memcpy(&function, &symbol, sizeof(function)); + return function; +} + +inline create_file_function create_file_api() { + static const auto function = native_function("NtCreateFile"); + return function; +} + +inline set_file_function set_file_api() { + static const auto function = native_function("NtSetInformationFile"); + return function; +} + +// MS-FSA directory-flush semantics and Appendix A note 80 specify directory persistence for +// NTFS; other filesystem success responses do not establish that guarantee. +// Both facts below come from the held directory, never from a path/drive +// lookup. Unknown locality or filesystem is unsupported, before mutation. +// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fsa/0de7dc40-9627-437e-a4df-c4696cdc3d02 +// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fsa/4e3695bd-7574-4f24-a223-b4679c065b63 +inline bool local_ntfs(HANDLE directory) { + static const auto query = native_function("NtQueryInformationFile"); + if (!query) return false; + // FILE_IS_REMOTE_DEVICE_INFORMATION has one BOOLEAN member. Initialize it + // to remote and require an actual completed response, not a zeroed fallback. + BOOLEAN remote = TRUE; + IO_STATUS_BLOCK io{}; + constexpr auto information_class = static_cast(51); + if (query(directory, &io, &remote, sizeof(remote), information_class) != 0 || + io.Status != 0 || io.Information != sizeof(remote) || remote != FALSE) + return false; + wchar_t filesystem[MAX_PATH + 1]{}; + DWORD flags = 0; + if (!GetVolumeInformationByHandleW(directory, nullptr, 0, nullptr, nullptr, + &flags, filesystem, MAX_PATH + 1)) + return false; + return std::wstring_view(filesystem) == L"NTFS" && + (flags & FILE_PERSISTENT_ACLS) != 0 && (flags & FILE_READ_ONLY_VOLUME) == 0; +} + +inline bool directory_operand(const std::filesystem::path &path) { + // A standalone '.' selects the already-established cwd. It is not accepted + // as a component or trailing suffix of a supplied pathname. Bare output + // filenames use this same selector for their parent. + return path.native() == L"." || windows_private_entries::valid_path(path, true); +} + +inline HANDLE open_directory(const std::filesystem::path &path) { + if (!directory_operand(path)) return INVALID_HANDLE_VALUE; + HANDLE handle = CreateFileW(path.c_str(), GENERIC_WRITE | FILE_READ_ATTRIBUTES | FILE_TRAVERSE, + FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); + if (handle == INVALID_HANDLE_VALUE) return handle; + FILE_ATTRIBUTE_TAG_INFO attributes{}; + FILE_STANDARD_INFO standard{}; + if (GetFileType(handle) != FILE_TYPE_DISK || + !GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &attributes, + sizeof(attributes)) || + (attributes.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 || + (attributes.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 || + !GetFileInformationByHandleEx(handle, FileStandardInfo, &standard, + sizeof(standard)) || + !standard.Directory || standard.DeletePending) { + CloseHandle(handle); + return INVALID_HANDLE_VALUE; + } + return handle; +} + +inline AtomicFileWrite sync_directory(const std::filesystem::path &path) { + if (!directory_operand(path)) + return {false, "file.sync_directory: invalid directory path"}; + nil::detail::storage_handle directory(open_directory(path)); + if (directory.get() == INVALID_HANDLE_VALUE) + return {false, "file.sync_directory: cannot open directory"}; + if (!local_ntfs(directory.get())) + return {false, "file.sync_directory: requires a local NTFS directory"}; + if (!FlushFileBuffers(directory.get())) + return {false, "file.sync_directory: synchronization failed"}; + return {true, {}}; +} + +// Every child name here is one validated component, relative to the already +// opened directory. No process cwd lookup or parent pathname reopen occurs. +inline HANDLE open_child(HANDLE directory, const std::wstring &name, + ACCESS_MASK access, ULONG sharing, bool create, + PSECURITY_DESCRIPTOR security, NTSTATUS &status) { + const auto api = create_file_api(); + status = static_cast(0xc000000dL); // STATUS_INVALID_PARAMETER + if (!api || name.empty() || name.size() > 32767 || + name.find_first_of(L"\\/:") != std::wstring::npos || + !windows_private_entries::valid_path(std::filesystem::path(name))) + return INVALID_HANDLE_VALUE; + UNICODE_STRING string{}; + string.Buffer = const_cast(name.data()); + string.Length = static_cast(name.size() * sizeof(wchar_t)); + string.MaximumLength = string.Length; + OBJECT_ATTRIBUTES attributes{}; + attributes.Length = sizeof(attributes); + attributes.RootDirectory = directory; + attributes.ObjectName = &string; + attributes.Attributes = 0x40; // OBJ_CASE_INSENSITIVE, no handle inheritance. + attributes.SecurityDescriptor = security; + IO_STATUS_BLOCK io{}; + HANDLE handle = INVALID_HANDLE_VALUE; + constexpr ULONG file_open = 1, file_create = 2; + constexpr ULONG no_follow = 0x00200000, synchronous = 0x20, non_directory = 0x40; + status = api(&handle, access | SYNCHRONIZE, &attributes, &io, nullptr, + FILE_ATTRIBUTE_NORMAL, sharing, create ? file_create : file_open, + no_follow | synchronous | non_directory, nullptr, 0); + const ULONG_PTR expected = create ? 2 : 1; // FILE_CREATED / FILE_OPENED. + if (status != 0 || io.Status != 0 || io.Information != expected || + handle == nullptr || handle == INVALID_HANDLE_VALUE) { + if (handle != nullptr && handle != INVALID_HANDLE_VALUE) CloseHandle(handle); + if (status == 0) status = static_cast(0xc0000001L); // STATUS_UNSUCCESSFUL + return INVALID_HANDLE_VALUE; + } + return handle; +} + +inline bool regular_destination(HANDLE handle) { + FILE_ATTRIBUTE_TAG_INFO attributes{}; + FILE_STANDARD_INFO standard{}; + return GetFileType(handle) == FILE_TYPE_DISK && + GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &attributes, + sizeof(attributes)) && + (attributes.FileAttributes & + (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) == 0 && + GetFileInformationByHandleEx(handle, FileStandardInfo, &standard, + sizeof(standard)) && + !standard.Directory && !standard.DeletePending; +} + +class staging_file { +public: + explicit staging_file(HANDLE handle) : handle_(handle) {} + staging_file(const staging_file &) = delete; + staging_file &operator=(const staging_file &) = delete; + ~staging_file() { + if (handle_ != INVALID_HANDLE_VALUE) { + if (!published_) { + // Delete only this held object, never a potentially replaced pathname. + // Cleanup failure may leave an orphan; it cannot change the old target. + FILE_DISPOSITION_INFO disposition{TRUE}; + SetFileInformationByHandle(handle_, FileDispositionInfo, &disposition, + sizeof(disposition)); + } + CloseHandle(handle_); + } + } + HANDLE get() const { return handle_; } + void published() { published_ = true; } + bool close() { + const HANDLE handle = handle_; + handle_ = INVALID_HANDLE_VALUE; + return CloseHandle(handle) != FALSE; + } +private: + HANDLE handle_; + bool published_ = false; +}; + +inline AtomicFileWrite write_file(const std::filesystem::path &path, + const std::vector &bytes, bool replace) { + constexpr const char *operation = "file.write_bytes_durable"; + const auto failure = [](const char *reason) -> AtomicFileWrite { + return {false, std::string("file.write_bytes_durable: ") + reason}; + }; + if (!windows_private_entries::valid_path(path)) + return failure("invalid destination path"); + const auto name = path.filename().native(); + auto parent = path.parent_path(); + if (parent.empty()) parent = L"."; + nil::detail::storage_handle directory(open_directory(parent)); + if (directory.get() == INVALID_HANDLE_VALUE) return failure("cannot open directory"); + if (!local_ntfs(directory.get())) return failure("requires a local NTFS directory"); + if (!create_file_api() || !set_file_api()) + return failure("relative file operations unavailable"); + + if (replace) { + NTSTATUS status = 0; + nil::detail::storage_handle previous(open_child(directory.get(), name, + FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + false, nullptr, status)); + if (previous.get() != INVALID_HANDLE_VALUE) { + if (!regular_destination(previous.get())) return failure("destination is not a regular file"); + } else if (status != static_cast(0xc0000034L)) { // STATUS_OBJECT_NAME_NOT_FOUND + return failure("cannot inspect destination"); + } + } + + nil::detail::owner_security identity; + std::error_code error; + if (!identity.initialize(false, error)) return failure("cannot establish owner identity"); + auto security = identity.attributes(); + HANDLE raw = INVALID_HANDLE_VALUE; + static std::atomic sequence{0}; + for (int attempt = 0; attempt < 128; ++attempt) { + std::wstring candidate; + try { + std::random_device entropy; + const auto random = (static_cast(entropy()) << 32U) ^ entropy(); + candidate = L".ny-write-" + std::to_wstring(GetCurrentProcessId()) + L"-" + + std::to_wstring(random) + L"-" + + std::to_wstring(sequence.fetch_add(1, std::memory_order_relaxed)); + } catch (...) { + return failure("cannot create staging file"); + } + NTSTATUS status = 0; + raw = open_child(directory.get(), candidate, + GENERIC_WRITE | DELETE | READ_CONTROL | FILE_READ_ATTRIBUTES, + 0, true, security.lpSecurityDescriptor, status); + if (raw != INVALID_HANDLE_VALUE) break; + if (status != static_cast(0xc0000035L)) // STATUS_OBJECT_NAME_COLLISION + return failure("cannot create staging file"); + } + if (raw == INVALID_HANDLE_VALUE) return failure("cannot create staging file"); + staging_file temporary(raw); + const auto private_file = windows_private_entries::inspect_handle( + temporary.get(), false, operation, identity); + if (!private_file.ok || !private_file.value) return failure("staging file is not private and regular"); + std::size_t offset = 0; + while (offset < bytes.size()) { + const DWORD count = static_cast(std::min( + bytes.size() - offset, (std::numeric_limits::max)())); + DWORD written = 0; + if (!WriteFile(temporary.get(), bytes.data() + offset, count, &written, nullptr) || + written == 0 || written > count) + return failure("staging write failed"); + offset += written; + } + if (!FlushFileBuffers(temporary.get())) return failure("staging flush failed"); + + const std::size_t name_bytes = name.size() * sizeof(wchar_t); + // Include the full fixed structure and space beyond the counted name for a + // zero terminator. Short leaves must not produce a buffer smaller than the + // native FILE_RENAME_INFORMATION structure. Its layout is FILE_RENAME_INFO. + const std::size_t rename_bytes = sizeof(FILE_RENAME_INFO) + name_bytes; + // max_align_t storage keeps the variable-sized native structure aligned. + std::vector storage( + (rename_bytes + sizeof(std::max_align_t) - 1) / sizeof(std::max_align_t)); + std::memset(storage.data(), 0, storage.size() * sizeof(std::max_align_t)); + auto *rename = reinterpret_cast(storage.data()); + rename->ReplaceIfExists = replace ? TRUE : FALSE; + rename->RootDirectory = directory.get(); + rename->FileNameLength = static_cast(name_bytes); + std::memcpy(rename->FileName, name.data(), name_bytes); + // The Win32 wrapper can reject a supplied RootDirectory. Use the native + // handle-relative operation directly, retaining the same write-capable + // directory for publication and the final persistence barrier. + // https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_rename_information + IO_STATUS_BLOCK renamed{}; + renamed.Status = static_cast(0xc0000001L); // STATUS_UNSUCCESSFUL + const auto status = set_file_api()(temporary.get(), &renamed, rename, + static_cast(rename_bytes), static_cast(10)); + if (status != 0 || renamed.Status != 0) { + const auto error_status = status != 0 ? status : renamed.Status; + return failure(!replace && error_status == static_cast(0xc0000035L) + ? "destination already exists" : "cannot publish staging file"); + } + temporary.published(); + // Publication has happened. Never remove the candidate or imply the prior + // destination survived if close or directory synchronization fails. Close + // the writing handle before the final directory flush, so close-time file + // metadata updates precede that last persistence request too. + const bool closed = temporary.close(); + // Even an uncertain close must not suppress the final directory barrier. + const bool synchronized = FlushFileBuffers(directory.get()) != FALSE; + if (!closed || !synchronized) + return failure("publication durability uncertain"); + return {true, {}}; +} + +} // namespace ny::detail::windows_durable_publication +#endif // _WIN32 +#endif // NIL_WINDOWS_DURABLE_PUBLICATION_HPP diff --git a/nilcompiler/src/windows_private_entries.hpp b/nilcompiler/src/windows_private_entries.hpp new file mode 100644 index 0000000..a000f72 --- /dev/null +++ b/nilcompiler/src/windows_private_entries.hpp @@ -0,0 +1,233 @@ +#ifndef NIL_WINDOWS_PRIVATE_ENTRIES_HPP +#define NIL_WINDOWS_PRIVATE_ENTRIES_HPP + +#include "secure_file_io.hpp" + +#ifdef _WIN32 +#include "../../common/windows_private_storage.hpp" + +#include +#include + +namespace ny::detail::windows_private_entries { + +inline bool separator(wchar_t value) { return value == L'\\' || value == L'/'; } + +inline wchar_t ascii_upper(wchar_t value) { + return value >= L'a' && value <= L'z' ? value - L'a' + L'A' : value; +} + +inline bool reserved_component(std::wstring_view component) { + // Win32 recognizes device basenames even before an extension. Trim spaces + // immediately before that extension too; never let normalization choose a + // device after our checks. Superscript 1, 2 and 3 also name COM/LPT devices. + auto base = component.substr(0, component.find(L'.')); + while (!base.empty() && base.back() == L' ') base.remove_suffix(1); + std::wstring upper; + upper.reserve(base.size()); + for (const auto value : base) upper.push_back(ascii_upper(value)); + if (upper == L"CON" || upper == L"PRN" || upper == L"AUX" || + upper == L"NUL" || upper == L"CONIN$" || upper == L"CONOUT$" || + upper == L"CLOCK$") + return true; + if (upper.size() != 4 || + (upper.compare(0, 3, L"COM") != 0 && upper.compare(0, 3, L"LPT") != 0)) + return false; + return (upper[3] >= L'0' && upper[3] <= L'9') || upper[3] == L'\u00b9' || + upper[3] == L'\u00b2' || upper[3] == L'\u00b3'; +} + +// Restricted ordinary DOS paths: relative names or drive-absolute names, +// either separator, and no normalization of components. UNC/device/extended +// namespaces, drive-relative/current-drive-rooted paths, ADS, dot/parent/empty +// components, reserved devices, leading spaces and trailing dots/spaces are +// rejected. Only an explicit drive root may end in a separator, and only when +// requested. This is a naming policy, not an ancestry sandbox: parents remain +// trusted. The UTF-8 runtime entry points validate before constructing a path; +// direct host callers must also supply well-formed UTF-16. +inline bool valid_path(const std::filesystem::path &path, bool allow_root = false) { + const auto &name = path.native(); + if (name.empty() || name.size() > 32767 || separator(name.front())) return false; + std::size_t begin = 0; + if (name.size() >= 2 && name[1] == L':') { + const auto drive = ascii_upper(name[0]); + if (drive < L'A' || drive > L'Z' || name.size() < 3 || !separator(name[2])) + return false; + begin = 3; + if (begin == name.size()) return allow_root; + } + for (std::size_t index = begin; index < name.size(); ++index) { + const auto value = static_cast(name[index]); + if (value < 32 || value == L'<' || value == L'>' || value == L':' || + value == L'"' || value == L'|' || value == L'?' || value == L'*') + return false; + if (value >= 0xd800 && value <= 0xdbff) { + if (++index == name.size() || name[index] < 0xdc00 || name[index] > 0xdfff) + return false; + } else if (value >= 0xdc00 && value <= 0xdfff) { + return false; + } + } + while (begin < name.size()) { + const auto end = name.find_first_of(L"\\/", begin); + const auto count = (end == std::wstring::npos ? name.size() : end) - begin; + const std::wstring_view component(name.data() + begin, count); + if (component.empty() || component.front() == L' ' || + component.back() == L' ' || component.back() == L'.' || + reserved_component(component)) + return false; + if (end == std::wstring::npos) return true; + begin = end + 1; + } + return false; +} + +inline FileCheck inspection_error(const char *operation) { + return {false, false, std::string(operation) + ": cannot inspect entry"}; +} + +// Accept only the effective user's ownership and one full-access +// allow ACE for that same SID. The ACE is either explicit in a protected DACL, +// or inherited from an owner-only parent; directories must propagate it to +// files and directories. Additional/deny/object/callback/inherit-only ACEs, +// null/empty DACLs and default group ownership are not this private profile. +// Inheritance is an inspected current state, not a promise about future ACL +// changes. This read-only descriptor predicate is shared by the held-handle +// check and deterministic malformed/wrong-owner controls in the Windows tests. +inline FileCheck inspect_descriptor(PSECURITY_DESCRIPTOR descriptor, + PSID expected_user, bool directory, + const char *operation) { + PSID owner = nullptr; + PACL acl = nullptr; + SECURITY_DESCRIPTOR_CONTROL control = 0; + DWORD revision = 0; + BOOL present = FALSE, defaulted = FALSE; + if (!descriptor || !IsValidSecurityDescriptor(descriptor) || + !GetSecurityDescriptorControl(descriptor, &control, &revision) || + !GetSecurityDescriptorOwner(descriptor, &owner, &defaulted) || + !GetSecurityDescriptorDacl(descriptor, &present, &acl, &defaulted)) + return inspection_error(operation); + if (!expected_user || !IsValidSid(expected_user)) + return inspection_error(operation); + if (!owner || !IsValidSid(owner) || !EqualSid(owner, expected_user) || + !present || !acl || !IsValidAcl(acl) || acl->AceCount != 1) + return {true, false, {}}; + void *raw = nullptr; + if (!GetAce(acl, 0, &raw)) return inspection_error(operation); + const auto *header = static_cast(raw); + constexpr std::size_t sid_offset = offsetof(ACCESS_ALLOWED_ACE, SidStart); + if (header->AceType != ACCESS_ALLOWED_ACE_TYPE || header->AceSize < sid_offset + 8) + return {true, false, {}}; + const auto *ace = static_cast(raw); + const BYTE propagation = directory ? OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE : 0; + const bool explicit_private = (control & SE_DACL_PROTECTED) != 0 && + header->AceFlags == propagation; + const bool inherited_private = header->AceFlags == (propagation | INHERITED_ACE); + if ((!explicit_private && !inherited_private) || ace->Mask != FILE_ALL_ACCESS) + return {true, false, {}}; + const auto *sid_bytes = reinterpret_cast(raw) + sid_offset; + // Bound the variable-length SID inside its ACE before invoking SID helpers. + const std::size_t sid_size = 8 + 4 * static_cast(sid_bytes[1]); + if (sid_size != header->AceSize - sid_offset) + return {true, false, {}}; + const PSID trustee = const_cast(sid_bytes); + return {true, IsValidSid(trustee) && EqualSid(trustee, expected_user), {}}; +} + +// Inspect an already-held, no-follow handle without opening or changing a +// pathname. Retain that handle for any subsequent action; a path preflight +// cannot establish the identity of a later open. +inline FileCheck inspect_handle(HANDLE handle, bool directory, + const char *operation, + const nil::detail::owner_security &identity) { + if (handle == nullptr || handle == INVALID_HANDLE_VALUE) + return inspection_error(operation); + SetLastError(ERROR_SUCCESS); + const DWORD kind = GetFileType(handle); + if (kind == FILE_TYPE_UNKNOWN && GetLastError() != ERROR_SUCCESS) + return inspection_error(operation); + if (kind != FILE_TYPE_DISK) return {true, false, {}}; + FILE_ATTRIBUTE_TAG_INFO attributes{}; + if (!GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &attributes, + sizeof(attributes))) + return inspection_error(operation); + if ((attributes.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 || + bool(attributes.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) != directory) + return {true, false, {}}; + FILE_STANDARD_INFO standard{}; + if (!GetFileInformationByHandleEx(handle, FileStandardInfo, &standard, + sizeof(standard))) + return inspection_error(operation); + if (bool(standard.Directory) != directory || standard.DeletePending || + (!directory && standard.NumberOfLinks != 1)) + return {true, false, {}}; + + PSECURITY_DESCRIPTOR descriptor = nullptr; + const DWORD status = GetSecurityInfo(handle, SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, + nullptr, nullptr, nullptr, nullptr, &descriptor); + if (status != ERROR_SUCCESS) return inspection_error(operation); + struct descriptor_owner { + PSECURITY_DESCRIPTOR value; + ~descriptor_owner() { if (value) LocalFree(value); } + } owned{descriptor}; + return inspect_descriptor(descriptor, identity.sid(), directory, operation); +} + +inline FileCheck inspect_handle(HANDLE handle, bool directory, const char *operation) { + nil::detail::owner_security identity; + std::error_code error; + if (!identity.initialize(directory, error)) return inspection_error(operation); + return inspect_handle(handle, directory, operation, identity); +} + +inline FileCheck inspect_path(const std::filesystem::path &path, bool directory, + const char *operation) { + if (!valid_path(path, directory)) + return {false, false, std::string(operation) + ": invalid " + + (directory ? "directory" : "file") + " path"}; + nil::detail::storage_handle handle(CreateFileW(path.c_str(), + READ_CONTROL | FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr)); + return inspect_handle(handle.get(), directory, operation); +} + +inline FileCheck inspect_regular_file(const std::filesystem::path &path) { + return inspect_path(path, false, "file.is_private_regular_file"); +} + +inline FileCheck inspect_directory(const std::filesystem::path &path) { + return inspect_path(path, true, "file.is_private_directory"); +} + +inline AtomicFileWrite create_directory(const std::filesystem::path &path) { + constexpr const char *operation = "file.create_private_directory"; + if (!valid_path(path)) return {false, std::string(operation) + ": invalid directory path"}; + nil::detail::owner_security identity; + std::error_code error; + if (!identity.initialize(true, error)) + return {false, std::string(operation) + ": cannot establish owner identity"}; + auto attributes = identity.attributes(); + if (!CreateDirectoryW(path.c_str(), &attributes)) { + const DWORD status = GetLastError(); + return {false, std::string(operation) + + ((status == ERROR_ALREADY_EXISTS || status == ERROR_FILE_EXISTS) + ? ": entry already exists" : ": cannot create directory")}; + } + nil::detail::storage_handle handle(CreateFileW(path.c_str(), + READ_CONTROL | FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, + nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, + nullptr)); + const auto verified = inspect_handle(handle.get(), true, operation, identity); + // Fail closed without path-based repair/removal. A post-creation failure can + // leave the new entry; reopening permissively or deleting a replaced name + // would be a different and weaker operation. Parents remain trusted. + if (!verified.ok || !verified.value) + return {false, std::string(operation) + ": created directory is not owner-only"}; + return {true, {}}; +} + +} // namespace ny::detail::windows_private_entries +#endif // _WIN32 +#endif // NIL_WINDOWS_PRIVATE_ENTRIES_HPP diff --git a/nillinker/main.cpp b/nillinker/main.cpp index 5ef5a06..340e136 100644 --- a/nillinker/main.cpp +++ b/nillinker/main.cpp @@ -1493,6 +1493,7 @@ bool Linker::link(const fs::path &requested_output) { // The runtime's Win32 desktop provider creates windows and measures text. arguments.push_back("user32.lib"); arguments.push_back("gdi32.lib"); + arguments.push_back("advapi32.lib"); // A linked program gets exactly one C runtime, and nil.lib decides which: // it is built /MD, so every reference it makes is an import (__imp_*) that // only the dynamic CRT satisfies. `cl /c` defaults to the *static* CRT, @@ -1535,6 +1536,7 @@ bool Linker::link(const fs::path &requested_output) { arguments.push_back("ws2_32.lib"); arguments.push_back("user32.lib"); arguments.push_back("gdi32.lib"); + arguments.push_back("advapi32.lib"); arguments.push_back("-Xlinker"); arguments.push_back("/MANIFEST:EMBED"); arguments.push_back("-Xlinker"); diff --git a/nilstd/src/io/file.ny b/nilstd/src/io/file.ny index 3eac110..3be86c4 100644 --- a/nilstd/src/io/file.ny +++ b/nilstd/src/io/file.ny @@ -86,27 +86,35 @@ pub fn write_bytes(path: text, content: array) -> Result @intrinsic("file.write_bytes_atomic") pub fn write_bytes_atomic(path: text, content: array, replace: bool) -> Result -# POSIX durability: atomic byte publication plus synchronization of the same -# parent-directory handle used for publication. Existing atomic-write semantics +# Durable publication on POSIX or positively identified Windows local NTFS: +# synchronize the same parent-directory handle used for publication. +# Windows stages with an effective-user owner-only ACL, flushes bytes, renames, +# closes the writer and flushes the held directory. Existing atomic-write semantics # remain unchanged. A failure after publication is an uncertain outcome: the # destination may already contain the new bytes. Stop and recover before retry. -# Unsupported platforms return Error before filesystem mutation. Parent ancestry +# Unsupported filesystems/platforms return Error before staging. Parent ancestry # must be trusted; this is not encryption or a filesystem/device guarantee. @intrinsic("file.write_bytes_durable") pub fn write_bytes_durable(path: text, content: array, replace: bool) -> Result -# Synchronize an existing directory. POSIX-only, no-follow final component; -# ancestors are trusted. Errors do not include the supplied path. +# Synchronize an existing directory on POSIX or Windows local NTFS, without +# following its final symlink/reparse point. Ancestors are trusted. Windows +# accepts a standalone '.' for cwd; otherwise its strict DOS path rules apply. +# Errors do not include the supplied path. @intrinsic("file.sync_directory") pub fn sync_directory(path: text) -> Result # Acquire a nonblocking exclusive advisory lock. create=true exclusively creates -# a new 0600 backing file; false opens an existing private, singly-linked regular -# file owned by the effective user. The runtime returns a context-owned token, +# a new private backing file: POSIX 0600 or Windows owner-only ACL. false opens +# an existing private, singly-linked regular file owned by the effective user. +# Windows locks byte zero, length one, with nonblocking LockFileEx; its handle +# is not inherited and pins the final entry against rename/deletion. +# The runtime returns a context-owned token, # never a descriptor. Invocation completion closes remaining locks. The backing # file remains present after release; do not unlink or replace it while used. # Lock creation does not synchronize its parent; call sync_directory as needed. -# POSIX-only, fails closed elsewhere. All writers must follow the same protocol. +# All writers must follow the same protocol. See durable-files.md for the exact +# Windows owner-ACL and ordinary DOS pathname profiles. @intrinsic("file.acquire_file_lock") pub fn acquire_file_lock(path: text, create: bool) -> Result @@ -117,26 +125,30 @@ pub fn release_file_lock(token: i64) -> Result # Ask whether this execution context still owns a live lock token. This does # not release/reacquire the lock or inspect its pathname. Stale, foreign, -# unknown, zero and negative tokens return Ok(false); POSIX-only. +# unknown, zero and negative tokens return Ok(false) on POSIX and Windows. # Invocation termination can retire a token while application objects remain. @intrinsic("file.file_lock_is_held") pub fn file_lock_is_held(token: i64) -> Result -# Create a new owner-only directory: POSIX mode 0700, applied by creation -# rather than a later chmod, which would leave a writable window. An existing -# entry is an error and is never adopted, so success means this call created -# an owned directory with exactly mode 0700. A umask that removes owner -# permissions causes an error and can leave the new directory in place; -# the runtime does not change the umask or repair permissions. +# Create a new owner-only directory: POSIX mode 0700 or a protected Windows +# effective-user ACL, applied at creation without a permission-repair window. +# An existing entry is an error and is never adopted. Success means this call +# created an owned directory matching that platform's private profile. +# A POSIX umask that removes owner permissions causes an error and can leave +# the new directory in place; +# the runtime does not change the umask or repair permissions. Windows also +# leaves the new entry if its held-handle privacy verification fails. # Parents are not created and are trusted; creation does not # durably publish the new name, so call sync_directory when that is needed. -# POSIX-only, fails closed elsewhere. +# Windows rejects ambiguous DOS names, UNC/device namespaces and ADS paths. @intrinsic("file.create_private_directory") pub fn create_private_directory(path: text) -> Result # Is this entry a private regular file: regular, owned by the effective user, -# exactly one hard link, and exactly mode 0600? A symlink is judged as itself -# and answers false rather than describing its target. +# exactly one hard link, and POSIX mode 0600 or the Windows owner-only ACL +# profile? Windows requires the exact user SID and one full-access allow ACE, +# protected explicit or inherited; extra permissions and default owner groups +# do not match. A symlink/reparse is judged as itself and answers false. # # Error means the entry could not be inspected, which is distinct from an # answer of false. Both are distinct from being safe to use: this inspects a @@ -146,8 +158,9 @@ pub fn create_private_directory(path: text) -> Result @intrinsic("file.is_private_regular_file") pub fn is_private_regular_file(path: text) -> Result -# Is this entry a directory owned by the effective user with exactly mode -# 0700? The same inspection limits as is_private_regular_file apply. Trailing +# Is this entry an effective-user-owned directory with POSIX mode 0700 or the +# Windows owner-only ACL profile (inheritable by files and directories)? +# The same inspection limits as is_private_regular_file apply. Trailing # separators are rejected except for filesystem-root paths, preserving the # final-component no-follow rule. @intrinsic("file.is_private_directory") diff --git a/nilstd/src/io/package.ny b/nilstd/src/io/package.ny index a328379..1db6f71 100644 --- a/nilstd/src/io/package.ny +++ b/nilstd/src/io/package.ny @@ -8,8 +8,9 @@ # - Console I/O: write, writeln, read_line, write_error, flush (console.ny) # - File: checked whole-file operations, bounded regular-file input, atomic # byte publication, and opaque-handle streams (file.ny) -# - POSIX durable publication, directory synchronization, context-owned locks -# - Owner-only directory creation and private-entry metadata verdicts +# - Durable publication and directory synchronization: POSIX or Windows local NTFS +# - Context-owned locks, owner-only directories and private-entry verdicts: +# POSIX modes or the Windows effective-user ACL profile # - Checksum: CRC-32 windows and SHA-256 content digests (checksum.ny) # - Stream: Read/Write/Seek/Close traits and checked stream_copy (stream.ny) # - Path: lexical path inspection and transformation (path.ny) diff --git a/notebook/2026-11-21-windows-durable-parity.md b/notebook/2026-11-21-windows-durable-parity.md new file mode 100644 index 0000000..dda4b11 --- /dev/null +++ b/notebook/2026-11-21-windows-durable-parity.md @@ -0,0 +1,188 @@ +# Windows durable files and lock parity + +Source runtime and installed Windows development SDK qualification pass. The +SDK is built from `b564ef6`, with the later `6bd3b18` qualification helper recorded +separately below. This work does not replace +the accepted SDK, activate a new shared SDK, or declare a stable release. + +## Implementation + +The eight durable/private/lock operations now have Windows implementations. +Directory synchronization and durable publication require positively identified +local NTFS. The directory handle anchors staging, relative rename and the final +flush. Published output is never removed after a failed final barrier; close or +flush failure reports `publication durability uncertain`. Owner-only ACLs apply +at creation, with no later permission-repair window. + +Private-entry inspection accepts only the documented effective-user owner and +single owner-allow ACE profiles. File locks use noninherited handles and an +immediate exclusive `LockFileEx` range at byte zero, length one. Registry tokens +remain context-owned and process-monotonic. Held lock handles deny deletion; +namespace identity and privacy are checked again before returning the token. +The checked ordinary-DOS path grammar rejects device/UNC paths, alternate streams, +reserved aliases and ambiguous components. POSIX implementations are unchanged. + +The Windows security import library is included in runtime/native linking and +in the native toolchain cache input closure. Cache tests cover content changes +with preserved timestamps and missing security import libraries. + +## Evidence and failed attempts + +Evidence is retained in an isolated Windows qualification campaign. Source +snapshots have per-file byte sizes and SHA-256 hashes. Test output and failed +attempts are retained; no accepted installation or existing worktree is changed. + +- MinGW compilation checks passed for both new headers and both Win32 test + executables. These are compilation evidence, not Windows runtime acceptance. +- A real Windows local-NTFS probe confirmed directory `FlushFileBuffers` works + under the build account. This is not a power-cut test. +- The first private/lock standalone build had an incomplete source snapshot; + its transitive header closure was corrected. The next build succeeded but + exposed an ACL-negative fixture bypass through the elevated account's backup + privilege. The fixture now uses its own restricted impersonation token; + production policy was not relaxed. +- Initial CMake configuration attempts failed the strict owned-process cleanup + check after successful configuration. Instrumentation identified the owned + descendant as MSVC's `mspdbsrv.exe`, not the telemetry uploader. The isolated + build now selects CMake CMP0141 NEW and embedded MSVC debug information. + Configuration then passed with clean process teardown. The owner and cleanup + deadlines were not changed. + +## Acceptance contract + +Real Windows acceptance must cover the private/lock executable (20 contracts, +18 invalid path operands), the publication executable (15 contracts, 16 invalid +path operands), common helper and VM lifecycle tests, and all eight Ny/Matrix +text/binary/AOT/JIT routes with an independent Win32 ACL/bytes/lock oracle. +Installed qualification must repeat the routes with both source and compiled +standard libraries. Current-source hosted Linux, Windows and both macOS checks +remain necessary before broad parity or SDK adoption claims. + +The earlier Goetic handoff remains pinned to source +`167ae3a6b0abb69c26e943a008ee6eb1eac8f13d`, with documentation closeout +`fd4417dbb5e7b614ee3fd7962409395a95793521`; it is not switched by this Windows +qualification. Its 609-source/1248-installed-route and hosted results belong to +that revision. The new Windows evidence below has its own exact identities. + +## Source qualification checkpoint + +The fifth isolated MSVC/LLVM build passes all seven selected CTests, with strict +owned-process cleanup and unchanged source hashes. The suites include 20 private/ +lock contracts (18 invalid operands), 15 publication contracts (16 invalid +operands), the common helper, 251 VM lifecycle checks, the private-directory +contract, native runtime ABI and all eight Ny/Matrix text-VM, binary-VM, AOT and +JIT routes. The route report includes 71 owned commands, 12 ABI rejection cases +and 36 foreign-library rejection cases, with an independent Win32 host oracle. +Report SHA-256: `e648cef32ff0ae653686952255617b1f1358e1562473db569db6ed3049621418`. + +Real execution caught two additional issues before this checkpoint. Replacing a +locked target correctly failed with access-denied rather than sharing-violation; +the test now accepts either refusal code and still requires unchanged bytes and +namespace. The Win32 rename wrapper rejected a non-null root directory with +invalid-parameter, even with a padded buffer. A direct native rename probe +succeeded using the same held directory. Publication now uses +`NtSetInformationFile` with a counted, padded name and checked completion status. +One-character output names are covered. No directory/path anchoring was relaxed. + +The Linux suite reports 609 tests, zero failures, 606 passes and three optional +skips (PostgreSQL client/provider and desktop display). The final native ABI test +was rebuilt and rerun after adding exception-safe Windows fixture cleanup. +The updated installed qualifier also passes against the existing immutable +Linux SDK/source `167ae3a`: both libraries cover 16 durable executions, 24 ABI and +72 library rejections, 202 console checks per library, 16 nominal-global VM +executions and eight expected initialization/native rejections. SDK/helper seals +remain unchanged. That tests qualifier compatibility, not a new SDK build. +Installed regression report SHA-256: +`8c640a05bc7a7c3785359cbcd26bbc4a9484007fde5ed874b08edbb790a2fbb6`. + +The source scan found no credentials or new private paths/addresses. The sole +remaining path-policy report is the unchanged public README contact address; +its original line is present in the parent commit. Public specification section +numbers were reworded to avoid being misread by the address scanner; the direct +Microsoft reference links remain. + +## Clean development SDK checkpoint + +The clean `b564ef60092d552884e6416dcdede2145ce55291` Windows build records +611 registered source tests: 609 pass, none fail, and the two interactive display +tests skip in the headless session. SQLite and isolated PostgreSQL provider tests +run successfully. Its installed SDK passes all 1,248 ordinary consumer routes: +78 Ny/Matrix fixtures, both source and binary libraries, and eight routes each. +The manifest seals 279 payload files, eleven root executables, nineteen library +modules and 76 HTML documentation pages. Manifest SHA-256: +`cb4d35926174bfcc7c62e54b8acb7106f108c9919fc5f3f5a60caa2d4add56d5`. +These counts do not substitute for the new installed durable-I/O qualification. + +The first complete SDK attempt retained failures caused by missing SQLite +headers in the isolated configuration; the provider configuration was corrected. +A subsequent external tool-runner shutdown stopped QEMU while the first campaign +was running. Its partial evidence and disk were preserved. The existing VM was +restarted under a user service, and the clean campaign above ran to completion. +No interrupted run is counted as a pass. + +The added installed durable qualifier then caught a separate harness path-budget +bug. It nested its temporary directory inside the already deep candidate evidence +path. Native `niltest` reached its manifest staging step, where the generated +atomic filename exceeded the ordinary Windows path budget. A native probe with +a 224-character parent created a 245-character final filename successfully but +failed at 263 and 266 characters with Win32 error 3. Python created those longer +paths, illustrating why its own successful directory creation did not establish +that native child tools could use the same depth. The failed candidate and logs +remain intact; ordinary-route success does not erase this failure. + +The qualifier correction uses a fresh, shallow Windows execution workspace and +retains a verified evidence copy under the requested output directory. It does +not change production pathname semantics, machine settings, child cleanup or +test deadlines. The successful installed rerun below records the unchanged +SDK, separate helper revision and both workspace paths. + +## Hosted source evidence + +The `b564ef6` [runtime campaign](https://github.com/exec-software/exec-nil-framework/actions/runs/44910080429) +passes on Linux, Windows, Intel macOS and Apple Silicon macOS with no skips: +82 CTests and 128 fixture executions in total. The durable subsets cover sixteen +executions, 32 ABI rejections and 144 foreign-library rejections across the four +hosts. Hosted non-LLVM fixtures and the full local LLVM campaign are distinct. + +The same revision's [macOS application campaign](https://github.com/exec-software/exec-nil-framework/actions/runs/44910080427) +passes on both architectures. Each runs 51 application CTests, 204 extension unit +checks and all 88 real-editor checks across nine modules. Each also covers eight +durable executions, twelve ABI and 36 library rejections, and 202 console checks. +These are source/application results; they neither replace installed SDK records +nor establish a stable Windows or macOS release. + + +## Installed Windows qualification closeout + +The clean helper revision `6bd3b180ba84c1664ea359d5d73d5877acf96d3e` passes all +21 qualifier unit tests on both Linux and Windows. Against the unchanged +`b564ef60092d552884e6416dcdede2145ce55291` SDK, its real Windows installed run +passes in 116.7 seconds with strict owned-process cleanup. Both `nilstd` and +`nillib` pass: + +- Sixteen total Ny/Matrix text-VM, binary-VM, AOT and JIT durable executions. +- Twenty-four ABI rejections and 72 foreign-library rejections, with unchanged + filesystem/ACL evidence and independent byte, owner and lock-release oracles. +- 184 console executions/checks per library (the Windows inventory). +- Sixteen nominal-global VM executions, four initialization rejections and four + native rejections, plus the existing nine-negative/three-control global checks + per library. + +The 53-unit execution root stays within the documented 96-unit budget. Its +523 evidence files and empty directories are retained in the original workspace +and in a separately verified copy. The outer owner confirms all 280 SDK entries +(including the manifest) and nine external provider/tool inputs are unchanged; +those dependency hashes also match the original SDK campaign. The original +candidate's `FAILED.txt` is preserved: this is a separate successful installed +qualification, not a rewrite of that failed build-script attempt. + +Installed qualifier report SHA-256: +`997f0cc2fcd6ec7646adfedad0db16b4383479a698c883061c2642c2933fd96d`. +Outer ownership/source/SDK verification report SHA-256: +`e6b04bab355e0b77fb5b1c26b04c388638892948f7f5ce6fe31021d9c69fbec3`. +The unchanged SDK archive SHA-256 is +`5d60bbab2397c2f13e9839107cda4cb4567bfdf18f55d8f1dc04290a178780ba`. +Later documentation commits close out this evidence; they are not the compiled +SDK revision. The package is a qualified development artifact, not a stable +release, a new desktop acceptance result or a power-cut guarantee. No shared SDK, +Goetic installation or release deployment was activated. diff --git a/scripts/build-sdk.ps1 b/scripts/build-sdk.ps1 index 65ed888..0d10b7d 100644 --- a/scripts/build-sdk.ps1 +++ b/scripts/build-sdk.ps1 @@ -127,6 +127,7 @@ $sdk = Join-Path $candidate 'sdk' $evidence = Join-Path $candidate 'build-evidence.json' $ctestReport = Join-Path $candidate 'ctest.xml' $consumerReport = Join-Path $candidate 'consumer-routes.json' +$durableEvidence = Join-Path $candidate 'durable-consumer-evidence' $transcriptStarted = $false Write-Host "Windows development candidate: $candidate" @@ -165,6 +166,10 @@ try { (Join-Path $PSScriptRoot 'check-sdk-routes.py'), '--sdk', $sdk, '--expected-revision', $revision, '--output', $consumerReport ) + Invoke-Checked $Python @( + (Join-Path $PSScriptRoot 'check-sdk-durable-io.py'), '--sdk', $sdk, + '--expected-revision', $revision, '--output', $durableEvidence + ) } catch { Set-Content -LiteralPath (Join-Path $candidate 'FAILED.txt') -Encoding UTF8 -Value ( 'This candidate did not complete Windows development SDK validation.' + @@ -179,4 +184,5 @@ try { } Write-Host "Validated Windows development SDK: $sdk" Write-Host "Consumer evidence: $consumerReport" +Write-Host "Durable I/O, console and nominal-global evidence: $durableEvidence" Write-Host 'Not activated; not RC/release-qualified; no publication performed.' diff --git a/scripts/check-sdk-durable-io.py b/scripts/check-sdk-durable-io.py index 753a01a..1b83424 100644 --- a/scripts/check-sdk-durable-io.py +++ b/scripts/check-sdk-durable-io.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Qualify installed durable I/O, console and nominal globals on POSIX hosts. +"""Qualify installed durable I/O, console and nominal globals on supported hosts. Uses the existing source contracts and SDK validator. Evidence is retained in a fresh directory outside the SDK; success is not a language release declaration. @@ -12,6 +12,8 @@ import os from pathlib import Path import re +import secrets +import stat import sys import tempfile import time @@ -21,6 +23,9 @@ sys.path.insert(0, str(ROOT / "tests/tools")) import ordinary_io_parity_contract as support +WINDOWS = os.name == "nt" +WINDOWS_WORKSPACE_UNITS = 96 + OPERATIONS = ( "file.write_bytes_durable", "file.sync_directory", "file.acquire_file_lock", "file.release_file_lock", "file.file_lock_is_held", "file.create_private_directory", @@ -49,6 +54,148 @@ def record(path: Path) -> dict: return support.file_record(path) +def windows_workspace_fits(path: Path) -> bool: + # Reserve 160 UTF-16 units for the current helper/tool descendants, including + # niltest's directory, compiler private staging and atomic temporary names. + # This is a qualification layout bound, not general long-path support. + return len(str(path).encode("utf-16-le")) // 2 <= WINDOWS_WORKSPACE_UNITS + + +def windows_execution_workspace() -> Path: + import windows_durable_oracle as oracle + parent = Path(tempfile.gettempdir()).resolve(strict=True) + for _ in range(128): + candidate = parent / ("nilq-" + secrets.token_hex(8)) + require(windows_workspace_fits(candidate), + "Windows qualification requires a system-temp workspace of at most " + "96 UTF-16 units; select a shorter process TMP/TEMP directory") + try: + # Apply the effective user's protected ACL at exclusive creation; + # verify local NTFS and retain this directory on success or failure. + oracle.create_private_directory(candidate) + return candidate + except OSError as error: + if error.errno not in (80, 183): # Existing names are never adopted. + raise ValueError("cannot reserve Windows qualification workspace at " + + str(candidate) + "; any created entry is retained") from error + except Exception as error: + raise ValueError("cannot verify Windows qualification workspace at " + + str(candidate) + "; any created entry is retained") from error + raise ValueError("cannot reserve a fresh Windows qualification workspace") + + +def retention_inventory(root: Path, deadline: float) -> dict: + result, pending, total = {}, [root], 0 + while pending: + require(time.monotonic() < deadline, "evidence retention exceeded its time budget") + directory = pending.pop() + mode = directory.lstat() + require(stat.S_ISDIR(mode.st_mode) and not + getattr(mode, "st_file_attributes", 0) & 0x400, + "evidence retention requires ordinary non-reparse directories") + for path in sorted(directory.iterdir()): + require(len(result) < 8192, "evidence retention exceeds its entry budget") + mode = path.lstat() + require(not stat.S_ISLNK(mode.st_mode) and not + getattr(mode, "st_file_attributes", 0) & 0x400, + "evidence retention refuses links and reparse points") + name = path.relative_to(root).as_posix() + if stat.S_ISDIR(mode.st_mode): + result[name] = {"kind": "directory"} + pending.append(path) + else: + require(stat.S_ISREG(mode.st_mode), "evidence retention refuses special files") + item = record(path) + total += item["bytes"] + require(total <= 1024**3, "evidence retention exceeds its byte budget") + result[name] = {"kind": "file", **item} + return dict(sorted(result.items())) + + +def copy_retained_file(source: Path, destination: Path, expected: dict, + deadline: float) -> None: + copied = 0 + with source.open("rb") as incoming, destination.open("xb") as outgoing: + while True: + require(time.monotonic() < deadline, "evidence retention exceeded its time budget") + data = incoming.read(128 * 1024) + if not data: + break + copied += len(data) + require(copied <= expected["bytes"], "source evidence grew during retention") + outgoing.write(data) + require(copied == expected["bytes"], "source evidence shrank during retention") + + +def retain_windows_evidence(source: Path, destination: Path) -> dict: + mode = source.lstat() + require(stat.S_ISDIR(mode.st_mode) and not + getattr(mode, "st_file_attributes", 0) & 0x400, + "execution workspace must be an ordinary non-reparse directory") + source = source.resolve(strict=True) + destination = destination.parent.resolve(strict=True) / destination.name + require(source != destination and source not in destination.parents and + destination not in source.parents, "execution and retained evidence must be separate") + deadline = time.monotonic() + 120 + identity = source.stat() + before = retention_inventory(source, deadline) + destination.mkdir() # A prior evidence tree is never adopted or replaced. + for name, item in before.items(): + target = destination / name + if item["kind"] == "directory": + target.mkdir() + else: + copy_retained_file(source / name, target, item, deadline) + require(retention_inventory(destination, deadline) == before, + "retained evidence bytes or namespace differ from execution evidence") + require(retention_inventory(source, deadline) == before, + "execution evidence changed during retention") + after = source.stat() + require((identity.st_dev, identity.st_ino) == (after.st_dev, after.st_ino), + "execution workspace changed during retention") + return {"status": "PASS", "execution_workspace": str(source), + "retained_copy": str(destination), "original_workspace_retained": True, + "files_and_directories": before, + "file_count": sum(item["kind"] == "file" for item in before.values()), + "byte_count": sum(item.get("bytes", 0) for item in before.values())} + + +def summary_bytes(output: bytes) -> bytes: + # Only human-readable helper summaries pass through this function. Binary + # fixture bytes, child output contracts, hashes and retained logs do not. + return output.replace(b"\r\n", b"\n") if WINDOWS else output + + +def sdk_tools(sdk: Path, manifest: dict) -> dict[str, Path]: + result = {} + for item in manifest["tools"]: + name = item["name"] + expected = name + (".exe" if WINDOWS else "") + require(item["path"] == expected and name not in result, + "manifest tools must be unique canonical root executables") + result[name] = sdk / item["path"] + return result + + +def check_windows_oracle(oracle: dict) -> None: + fixed = {"bytes": "exact", "filesystem": "local-NTFS", "remaining_staging_files": 0, + "lock_after_process_completion": "released", "lock_primitive": "LockFileEx-byte-0-length-1", + "private_directories": ["private"], "windows_owner": "effective-user", + "windows_dacl": "one-FILE_ALL_ACCESS-owner-allow-ACE"} + require(isinstance(oracle, dict) and + set(oracle) == set(fixed) | {"windows_acl_profiles", "windows_acl_sha256"} and + all(oracle[key] == value for key, value in fixed.items()), + "Windows durable host filesystem oracle differs") + entries = {".", "private", "checkpoint.bin", "empty.bin", "writer.lock"} + profiles, seals = oracle["windows_acl_profiles"], oracle["windows_acl_sha256"] + require(isinstance(profiles, dict) and set(profiles) == entries and + all(profile in ("protected-owner", "inherited-owner") for profile in profiles.values()), + "Windows oracle omitted an owner-only ACL profile") + require(isinstance(seals, dict) and set(seals) == entries and + all(isinstance(value, str) and re.fullmatch(r"[0-9a-f]{64}", value) for value in seals.values()), + "Windows oracle omitted an entry security seal") + + def check_rows(rows: list, expected: set, keys: tuple[str, ...], label: str) -> None: require(isinstance(rows, list) and len(rows) == len(expected), label + " count differs") require(all(isinstance(row, dict) and row.get("status") == "PASS" for row in rows), @@ -62,6 +209,9 @@ def check_durable(report: dict, sdk: Path, library: Path, runtime: Path, require(report.get("schema") == "nil.durable-file-io.v1" and report.get("status") == "PASS" and report.get("llvm_enabled") is True and report.get("cleanup_verified") is True, "durable contract did not qualify") + require(report.get("scope") == ("WINDOWS_NTFS_SOURCE_RUNTIME_NOT_RELEASE_OR_POWER_CUT_QUALIFICATION" + if WINDOWS else "POSIX_SOURCE_RUNTIME_NOT_RELEASE_OR_POWER_CUT_QUALIFICATION"), + "durable contract has the wrong platform qualification scope") check_rows(report.get("executions"), EXECUTIONS, ("route", "language"), "durable executions") check_rows(report.get("negative_abi"), NEGATIVE_ABI, ("case", "route"), "ABI rejections") check_rows(report.get("negative_library"), NEGATIVE_LIBRARY, @@ -71,9 +221,20 @@ def check_durable(report: dict, sdk: Path, library: Path, runtime: Path, oracle = {"bytes": "exact", "modes": "0600", "remaining_staging_files": 0, "lock_after_process_completion": "released", "private_directories": ["private"], "directory_modes": "0700"} - require(all(row.get("oracle") == oracle for row in report["executions"]), - "durable host filesystem oracle differs") - require(report.get("selected_native_runtime") == str(runtime), + if WINDOWS: + for row in report["executions"]: + check_windows_oracle(row.get("oracle")) + for row in report["negative_library"]: + seals = row.get("windows_acl_sha256") + require(isinstance(seals, dict) and set(seals) == {"file", "directory"} and + all(isinstance(value, str) and re.fullmatch(r"[0-9a-f]{64}", value) for value in seals.values()), + "Windows library rejection omitted unchanged ACL evidence") + else: + require(all(row.get("oracle") == oracle for row in report["executions"]), + "durable host filesystem oracle differs") + selected = report.get("selected_native_runtime") + require(isinstance(selected, str) and + (Path(selected).resolve() == runtime.resolve() if WINDOWS else selected == str(runtime)), "durable compiler selected a runtime outside this SDK") before = report.get("inputs_before") require(isinstance(before, dict) and before == report.get("inputs_after"), @@ -84,6 +245,8 @@ def check_durable(report: dict, sdk: Path, library: Path, runtime: Path, for case in ("width", "owner", "query-width", "query-owner"): suffix = "query-invalid-" + case[6:] if case.startswith("query-") else "invalid-" + case sources[case] = ROOT / "tests/language" / ("durable-file-io-" + suffix + ".ny") + if WINDOWS: + sources["windows_oracle"] = ROOT / "tests/tools/windows_durable_oracle.py" expected_inputs = {key: record(path) for key, path in sources.items()} tool_records = {item["name"]: item for item in manifest["tools"]} for key, item in (("compiler", tool_records["nilcompiler"]), @@ -91,14 +254,16 @@ def check_durable(report: dict, sdk: Path, library: Path, runtime: Path, ("runtime", manifest["native_runtime"])): expected_inputs[key] = {field: item[field] for field in ("bytes", "sha256")} require(before == expected_inputs, "durable inputs do not match the installed SDK and current helpers") - compiler, interpreter = str(sdk / "nilcompiler"), str(sdk / "nilinterpreter") + tools = sdk_tools(sdk, manifest) + compiler, interpreter = str(tools["nilcompiler"]), str(tools["nilinterpreter"]) expected_commands = {"runtime-selection": (False, compiler)} for language in ("ny", "matrix"): for encoding in ("text", "binary"): expected_commands[language + "-compile-" + encoding] = (False, compiler) expected_commands[language + "-" + encoding + "-vm"] = (False, interpreter) expected_commands[language + "-compile-aot"] = (False, compiler) - expected_commands[language + "-aot"] = (False, str(work / (language + "-build") / "native")) + expected_commands[language + "-aot"] = (False, str(work / (language + "-build") / + ("native.exe" if WINDOWS else "native"))) expected_commands[language + "-jit"] = (False, compiler) for case in ("width", "owner", "query-width", "query-owner"): for encoding in ("text", "binary"): @@ -144,6 +309,8 @@ def helper_inputs() -> list[Path]: ROOT / "tests/language/module-global-contract.stdout"] paths.extend(sorted((ROOT / "tests/language").glob("durable-file-io*.ny"))) paths.extend(sorted((ROOT / "tests/tools/fixtures").glob("console-input*.*"))) + if WINDOWS: + paths.append(ROOT / "tests/tools/windows_durable_oracle.py") return paths @@ -163,11 +330,15 @@ def qualify(args: argparse.Namespace, sdk: Path, work: Path) -> dict: temporary = work / "temporary" temporary.mkdir() environment["TMPDIR"] = str(temporary) + if WINDOWS: + environment.update(TMP=str(temporary), TEMP=str(temporary)) deadline = time.monotonic() + 1800 report = {"schema": "nil.sdk.durable-io.v1", "status": "FAIL", "release_declaration": False, "source_revision": args.expected_revision, "sdk": str(sdk), "require_rc_checks": args.require_rc_checks, - "scope": "INSTALLED_POSIX_PROVIDER_REGRESSION_NOT_RELEASE_OR_POWER_CUT_QUALIFICATION", + "scope": ("INSTALLED_WINDOWS_NTFS_PROVIDER_REGRESSION_NOT_RELEASE_OR_POWER_CUT_QUALIFICATION" + if WINDOWS else + "INSTALLED_POSIX_PROVIDER_REGRESSION_NOT_RELEASE_OR_POWER_CUT_QUALIFICATION"), "commands": [], "libraries": [], "errors": []} manifest_record = None identity = sdk.stat() @@ -201,16 +372,17 @@ def run(name: str, command: list, limit: int, *, final: bool = False) -> bytes: report.update(sdk_manifest=manifest_record, payload_file_count=manifest["payload"]["file_count"], installed_tools=manifest["tools"], native_runtime=manifest["native_runtime"]) runtime = sdk / manifest["native_runtime"]["path"] + tools = sdk_tools(sdk, manifest) for library_name in ("nilstd", "nillib"): library = sdk / library_name durable_output = work / (library_name + "-durable") durable_output.mkdir() stdout = run(library_name + "-durable", [sys.executable, - ROOT / "tests/tools/durable_file_io_contract.py", "--compiler", sdk / "nilcompiler", - "--interpreter", sdk / "nilinterpreter", "--nilstd", library, + ROOT / "tests/tools/durable_file_io_contract.py", "--compiler", tools["nilcompiler"], + "--interpreter", tools["nilinterpreter"], "--nilstd", library, "--runtime", runtime, "--llvm", "ON", "--output", durable_output], 300) reports = list(durable_output.glob("run-*/report.json")) - require(len(reports) == 1 and stdout == ("PASS: " + str(reports[0]) + "\n").encode(), + require(len(reports) == 1 and summary_bytes(stdout) == ("PASS: " + str(reports[0]) + "\n").encode(), "durable helper did not report exactly one retained PASS result") durable = json.loads(reports[0].read_text(encoding="utf-8")) check_durable(durable, sdk, library, runtime, manifest, reports[0].parent) @@ -220,21 +392,21 @@ def run(name: str, command: list, limit: int, *, final: bool = False) -> bytes: "routes": sorted(route for route, _ in EXECUTIONS)} report["libraries"].append(result) stdout = run(library_name + "-console", [sys.executable, - ROOT / "tests/tools/native_console_contract.py", "--compiler", sdk / "nilcompiler", - "--interpreter", sdk / "nilinterpreter", "--assembler", sdk / "nilassembler", - "--linker", sdk / "nillinker", "--runtime", runtime, "--stdlib", library], 240) + ROOT / "tests/tools/native_console_contract.py", "--compiler", tools["nilcompiler"], + "--interpreter", tools["nilinterpreter"], "--assembler", tools["nilassembler"], + "--linker", tools["nillinker"], "--runtime", runtime, "--stdlib", library], 240) # The unchanged harness owns its precise count (including compile # and rejection checks); record that count, not an invented number # of program executions. Extra output, SKIP and an empty run fail. - matched = re.fullmatch(rb"native console contract: ([1-9][0-9]*) executions/checks passed\n", stdout) + matched = re.fullmatch(rb"native console contract: ([1-9][0-9]*) executions/checks passed\n", summary_bytes(stdout)) require(matched is not None, "console helper did not report a complete PASS") result["console_executions_and_checks"] = int(matched.group(1)) stdout = run(library_name + "-globals", [sys.executable, - ROOT / "tests/tools/global_contract.py", "--compiler", sdk / "nilcompiler", - "--interpreter", sdk / "nilinterpreter", "--assembler", sdk / "nilassembler", - "--linker", sdk / "nillinker", "--runtime", runtime, + ROOT / "tests/tools/global_contract.py", "--compiler", tools["nilcompiler"], + "--interpreter", tools["nilinterpreter"], "--assembler", tools["nilassembler"], + "--linker", tools["nillinker"], "--runtime", runtime, "--nilstd", library, "--llvm", "ON"], 180) - require(stdout == GLOBAL_SUMMARY, "global helper did not report every required PASS case") + require(summary_bytes(stdout) == GLOBAL_SUMMARY, "global helper did not report every required PASS case") result.update(nominal_global_vm_executions=8, nominal_global_initialization_rejections=2, nominal_global_native_rejections=2, status="PASS") @@ -277,10 +449,11 @@ def main() -> int: parser.add_argument("--output", type=Path, required=True, help="evidence parent outside the SDK; always creates a fresh retained child") args = parser.parse_args() - work = None + work, execution, report = None, None, None try: - require(os.name == "posix" and sys.platform in ("linux", "darwin"), - "installed durable qualification supports native Linux/macOS only; Windows is unsupported") + require((os.name == "posix" and sys.platform in ("linux", "darwin")) or + (os.name == "nt" and sys.platform == "win32"), + "installed durable qualification requires native Linux, macOS or Windows") require(not args.require_rc_checks or sys.platform == "linux", "RC checks require Linux") require(re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", args.expected_revision) is not None, "expected revision must be a full lowercase Git revision") @@ -289,16 +462,28 @@ def main() -> int: require(sdk != output and sdk not in output.parents, "evidence must be outside the SDK") output.mkdir(parents=True, exist_ok=True) work = Path(tempfile.mkdtemp(prefix="run-", dir=output)) - report = qualify(args, sdk, work) + execution = windows_execution_workspace() if WINDOWS else work + report = qualify(args, sdk, execution) + if WINDOWS: + report["workspace_provenance"] = { + "execution_workspace": str(execution), "requested_evidence": str(work), + "execution_path_utf16_units": len(str(execution).encode("utf-16-le")) // 2, + "execution_path_limit_utf16_units": WINDOWS_WORKSPACE_UNITS, + "general_long_path_support_qualified": False, + "original_workspace_retained": True} + support.save_new(execution / "report.json", report) + report["evidence_retention"] = retain_windows_evidence(execution, work / "execution") support.save_new(work / "report.json", report) print(report["status"] + ": " + str(work / "report.json")) return 0 if report["status"] == "PASS" else 1 except Exception as error: if work is not None and not (work / "report.json").exists(): - support.save_new(work / "report.json", { - "schema": "nil.sdk.durable-io.v1", "status": "FAIL", - "release_declaration": False, "source_revision": args.expected_revision, - "error": str(error), "cleanup_verified": False}) + failed = report if report is not None else { + "schema": "nil.sdk.durable-io.v1", "release_declaration": False, + "source_revision": args.expected_revision, "cleanup_verified": False} + failed.update(status="FAIL", error=str(error), + execution_workspace=str(execution) if execution is not None else None) + support.save_new(work / "report.json", failed) print("installed durable qualification failed: " + str(error), file=sys.stderr) return 1 diff --git a/tests/durable_file_io_tests.cpp b/tests/durable_file_io_tests.cpp index 207b5e4..6b8c486 100644 --- a/tests/durable_file_io_tests.cpp +++ b/tests/durable_file_io_tests.cpp @@ -586,20 +586,25 @@ void check_private_directory_umask(const fs::path &root) { } #else -void check_unsupported_host(const fs::path &root) { - const auto target = root / "private-unsupported-marker"; - require_error(ny::detail::sync_directory_utf8(root.u8string()), "private-unsupported-marker"); - require_error(ny::detail::write_file_durable_utf8(target.u8string(), {'x'}, false), "private-unsupported-marker"); +void check_windows_host(const fs::path &root) { + const auto target = root / "private-windows-marker"; + require(ny::detail::sync_directory_utf8(root.u8string()).ok, "cannot sync local NTFS directory"); + require(ny::detail::write_file_durable_utf8(target.u8string(), {'x'}, false).ok, + "cannot publish durable Windows file"); + require(read_bytes(target) == "x", "Windows durable file bytes differ"); + const auto metadata = ny::detail::private_regular_file_utf8(target.u8string()); + require(metadata.ok && metadata.value, "Windows publication is not private"); FileLockRegistry registry; - require_error(registry.acquire(target.u8string(), true), "private-unsupported-marker"); - require_error(registry.is_held(0), "private-unsupported-marker"); - require_error(ny::detail::create_private_directory_utf8(target.u8string()), - "private-unsupported-marker"); - require_error(ny::detail::private_regular_file_utf8(target.u8string()), - "private-unsupported-marker"); - require_error(ny::detail::private_directory_utf8(target.u8string()), - "private-unsupported-marker"); - require(registry.empty() && !fs::exists(target), "unsupported host mutated its namespace"); + const auto locked = registry.acquire(target.u8string(), false); + require(locked.ok && registry.is_held(locked.token).value, "cannot hold private Windows file lock"); + require(registry.release(locked.token).ok && registry.empty(), "cannot release Windows lock"); + const auto absent = registry.is_held(0); + require(absent.ok && !absent.value, "unknown Windows token must have a false verdict"); + const auto directory = root / "private-windows-directory"; + require(ny::detail::create_private_directory_utf8(directory.u8string()).ok, + "cannot create private Windows directory"); + const auto private_directory = ny::detail::private_directory_utf8(directory.u8string()); + require(private_directory.ok && private_directory.value, "created Windows directory is not private"); } #endif @@ -639,7 +644,7 @@ int main() { check_private_metadata(owned.root); check_private_directory_umask(owned.root); #else - check_unsupported_host(owned.root); + check_windows_host(owned.root); #endif check_content_digest(); std::cout << "durable-file-io-ok\n"; diff --git a/tests/durable_vm_lifecycle_tests.cpp b/tests/durable_vm_lifecycle_tests.cpp index 3964235..2664409 100644 --- a/tests/durable_vm_lifecycle_tests.cpp +++ b/tests/durable_vm_lifecycle_tests.cpp @@ -16,6 +16,10 @@ #include #include #include +#ifdef _WIN32 +#define NOMINMAX +#include +#endif #if defined(__unix__) || defined(__APPLE__) #include @@ -47,6 +51,16 @@ class fixture_directory { output.close(); require(static_cast(output) && ::chmod(lock.c_str(), 0600) == 0, "cannot create private VM lock file"); +#elif defined(_WIN32) + root = fs::temp_directory_path() / ("nil-durable-vm-" + + std::to_string(GetCurrentProcessId()) + "-" + std::to_string(GetTickCount64())); + require(ny::detail::create_private_directory_utf8(root.u8string()).ok, + "cannot create private VM lock fixture"); + lock = root / "invocation.lock"; + ny::detail::FileLockRegistry creator; + const auto created = creator.acquire(lock.u8string(), true); + require(created.ok, "cannot create private VM lock file"); + require(creator.release(created.token).ok, "cannot release VM fixture lock"); #endif } ~fixture_directory() { @@ -236,7 +250,7 @@ void lifecycle(const fs::path &path, bool binary) { int main() { try { -#if defined(__unix__) || defined(__APPLE__) +#if defined(__unix__) || defined(__APPLE__) || defined(_WIN32) fixture_directory owned; lifecycle(owned.lock, false); lifecycle(owned.lock, true); diff --git a/tests/native_runtime_tests.cpp b/tests/native_runtime_tests.cpp index c00a090..2c62dc5 100644 --- a/tests/native_runtime_tests.cpp +++ b/tests/native_runtime_tests.cpp @@ -870,9 +870,14 @@ void check_ordinary_io_contract(bool &ok) { } void check_durable_io_contract(bool &ok) { - nyrt_context_begin(0, nullptr); try { temporary_directory temporary; + // Release every context-owned handle before the directory is removed, + // including when a fixture operation throws. Windows locks deny deletion. + struct context_scope { + context_scope() { nyrt_context_begin(0, nullptr); } + ~context_scope() { nyrt_context_end(); } + } context; const auto directory = temporary.path().u8string(); const auto destination = (temporary.path() / "checkpoint.bin").u8string(); const auto lock_path = (temporary.path() / "writer.lock").u8string(); @@ -884,16 +889,6 @@ void check_durable_io_contract(bool &ok) { const auto call = [&](const char *name, std::uint64_t a = 0, std::uint64_t b = 0, std::uint64_t c = 0) { return nyrt_io_v1(name, a, b, c, &value, &error); }; -#ifdef _WIN32 - ok &= expect(call("file.sync_directory", word(directory.c_str())) == 0 && error, - "unsupported durable I/O reported success"); - ok &= expect(call("file.acquire_file_lock", word(lock_path.c_str()), 1) == 0 && error && - !std::filesystem::exists(std::filesystem::u8path(lock_path)), - "unsupported locking mutated the namespace"); - ok &= expect(call("file.file_lock_is_held", 0) == 0 && error && - std::string(error) == "file.file_lock_is_held: unsupported platform", - "unsupported lock ownership query reported a verdict"); -#else ok &= expect(call("file.file_lock_is_held", 1) == 1 && value == 0 && !error, "new native context reported an unknown token as held"); ok &= expect(call("file.sync_directory", word(directory.c_str())) == 1 && value == 1 && !error, @@ -952,12 +947,12 @@ void check_durable_io_contract(bool &ok) { "native lock survived context teardown"); ok &= expect(call("file.acquire_file_lock", word(lock_path.c_str()), 0) == 1 && value > abandoned, "native teardown failed to close the backing descriptor"); -#endif + ok &= expect(call("file.release_file_lock", value) == 1 && value == 1 && !error, + "native final lock release failed"); } catch (const std::exception &exception) { std::cerr << "durable I/O native test setup failed: " << exception.what() << '\n'; ok = false; } - nyrt_context_end(); } } // namespace diff --git a/tests/sdk_consumer_routes_tests.py b/tests/sdk_consumer_routes_tests.py index cef2f2d..7caf42c 100644 --- a/tests/sdk_consumer_routes_tests.py +++ b/tests/sdk_consumer_routes_tests.py @@ -4,10 +4,15 @@ from __future__ import annotations import copy +import contextlib import importlib.util +import io import json from pathlib import Path +import stat import tempfile +import time +from types import SimpleNamespace import unittest from unittest import mock @@ -16,6 +21,10 @@ SPEC = importlib.util.spec_from_file_location("sdk_consumer", ROOT / "scripts/check-sdk-routes.py") consumer = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(consumer) +DURABLE_SPEC = importlib.util.spec_from_file_location( + "sdk_durable_consumer", ROOT / "scripts/check-sdk-durable-io.py") +durable = importlib.util.module_from_spec(DURABLE_SPEC) +DURABLE_SPEC.loader.exec_module(durable) # check_report requires an absolute run directory, and on Windows a path with @@ -250,5 +259,131 @@ def test_dummy_commands_or_unnamed_checks_do_not_prove_execution(self): self.check(report) +class DurableEvidenceTests(unittest.TestCase): + def fixtures(self, parent): + source = parent / "execution" + source.mkdir() + (source / "logs").mkdir() + (source / "empty").mkdir() + (source / "logs" / "raw.bin").write_bytes(b"before\x00\xff\r\nafter") + (source / "report.json").write_text(json.dumps({"status": "PASS", "work": str(source)})) + return source, parent / "retained" + + def test_retention_preserves_all_bytes_empty_directories_and_original_paths(self): + with tempfile.TemporaryDirectory() as directory: + source, target = self.fixtures(Path(directory)) + proof = durable.retain_windows_evidence(source, target) + self.assertEqual(proof["status"], "PASS") + self.assertEqual(proof["execution_workspace"], str(source.resolve())) + self.assertEqual(proof["retained_copy"], str(target.resolve())) + self.assertTrue(proof["original_workspace_retained"]) + self.assertEqual(proof["file_count"], 2) + self.assertEqual(durable.retention_inventory(source, time.monotonic()+30), + durable.retention_inventory(target, time.monotonic()+30)) + self.assertEqual(json.loads((target / "report.json").read_text())["work"], str(source)) + self.assertTrue((source / "empty").is_dir()) + + def test_copy_corruption_and_source_mutation_fail_closed(self): + for change in ("copy", "source", "namespace"): + with self.subTest(change=change), tempfile.TemporaryDirectory() as directory: + source, target = self.fixtures(Path(directory)) + original = durable.copy_retained_file + + def corrupt(incoming, outgoing, expected, deadline): + original(incoming, outgoing, expected, deadline) + if incoming.name == "raw.bin": + if change == "namespace": + (source / "unexpected").write_bytes(b"new") + else: + (outgoing if change == "copy" else incoming).write_bytes(b"changed") + + with mock.patch.object(durable, "copy_retained_file", side_effect=corrupt): + with self.assertRaises(ValueError): + durable.retain_windows_evidence(source, target) + self.assertTrue(source.is_dir()) + + def test_existing_destination_is_never_replaced(self): + with tempfile.TemporaryDirectory() as directory: + source, target = self.fixtures(Path(directory)) + target.mkdir() + marker = target / "marker" + marker.write_bytes(b"retained") + with self.assertRaises(FileExistsError): + durable.retain_windows_evidence(source, target) + self.assertEqual(marker.read_bytes(), b"retained") + + def test_symlink_and_windows_reparse_entries_are_not_followed(self): + for kind in ("symlink", "reparse"): + with self.subTest(kind=kind), tempfile.TemporaryDirectory() as directory: + source, target = self.fixtures(Path(directory)) + blocked = source / "logs" + original = Path.lstat + + def attributes(path, *args, **kwargs): + actual = original(path, *args, **kwargs) + if path == blocked: + return SimpleNamespace( + st_mode=stat.S_IFLNK if kind == "symlink" else actual.st_mode, + st_file_attributes=0x400 if kind == "reparse" else 0) + return actual + + # Exercise both actual lstat verdicts on every host without + # requiring Windows symlink privileges or creating a junction. + with mock.patch.object(Path, "lstat", attributes): + with self.assertRaisesRegex(ValueError, "links and reparse"): + durable.retain_windows_evidence(source, target) + self.assertFalse(target.exists()) + self.assertEqual((blocked / "raw.bin").read_bytes(), b"before\x00\xff\r\nafter") + + def test_utf16_path_budget_accounts_for_surrogate_pairs(self): + self.assertTrue(durable.windows_workspace_fits(Path("a" * 96))) + self.assertFalse(durable.windows_workspace_fits(Path("a" * 97))) + self.assertTrue(durable.windows_workspace_fits(Path("a" * 94 + "\U0001f512"))) + self.assertFalse(durable.windows_workspace_fits(Path("a" * 95 + "\U0001f512"))) + + def test_main_retention_failure_cannot_report_qualification_success(self): + with tempfile.TemporaryDirectory() as directory: + parent = Path(directory) + sdk, source, output = parent / "sdk", parent / "execution", parent / "evidence" + sdk.mkdir(); source.mkdir() + argv = ["qualify", "--sdk", str(sdk), "--expected-revision", "a" * 40, + "--output", str(output)] + report = {"status": "PASS", "cleanup_verified": True, "errors": []} + stdout, stderr = io.StringIO(), io.StringIO() + with mock.patch.object(durable, "WINDOWS", True), \ + mock.patch.object(durable.sys, "argv", argv), \ + mock.patch.object(durable, "windows_execution_workspace", return_value=source), \ + mock.patch.object(durable, "qualify", return_value=report), \ + mock.patch.object(durable, "retain_windows_evidence", side_effect=ValueError("copy failed")), \ + contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + self.assertEqual(durable.main(), 1) + retained = list(output.glob("run-*/report.json")) + self.assertEqual(len(retained), 1) + failed = json.loads(retained[0].read_text()) + self.assertEqual(failed["status"], "FAIL") + self.assertEqual(failed["execution_workspace"], str(source)) + self.assertEqual(json.loads((source / "report.json").read_text())["status"], "PASS") + self.assertNotIn("PASS:", stdout.getvalue()) + self.assertIn("copy failed", stderr.getvalue()) + + def test_posix_keeps_requested_execution_directory(self): + with tempfile.TemporaryDirectory() as directory: + parent = Path(directory) + sdk, output = parent / "sdk", parent / "evidence" + sdk.mkdir() + argv = ["qualify", "--sdk", str(sdk), "--expected-revision", "a" * 40, + "--output", str(output)] + with mock.patch.object(durable, "WINDOWS", False), \ + mock.patch.object(durable.sys, "argv", argv), \ + mock.patch.object(durable, "windows_execution_workspace") as reserve, \ + mock.patch.object(durable, "qualify", return_value={"status": "PASS"}) as qualify, \ + contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(durable.main(), 0) + reserve.assert_not_called() + self.assertEqual(qualify.call_args.args[2].parent, output) + saved = json.loads(next(output.glob("run-*/report.json")).read_text()) + self.assertNotIn("workspace_provenance", saved) + + if __name__ == "__main__": unittest.main() diff --git a/tests/tools/durable_file_io_contract.py b/tests/tools/durable_file_io_contract.py index 1fa28a0..b2491dd 100644 --- a/tests/tools/durable_file_io_contract.py +++ b/tests/tools/durable_file_io_contract.py @@ -1,8 +1,9 @@ #!/usr/bin/env python3 """Public Ny/Matrix durable-file and lock routes with a host filesystem oracle. -This qualifies local POSIX source-runtime behavior, not storage hardware power -loss or an installed/release SDK. Each execution has its own private directory. +This qualifies local POSIX or Windows NTFS source-runtime behavior, not storage +hardware power loss or an installed/release SDK. Each execution has its own +private directory and an independent host filesystem oracle. """ from __future__ import annotations @@ -18,6 +19,9 @@ import ordinary_io_parity_contract as support +if os.name == "nt": + import windows_durable_oracle as windows_oracle + ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "tests")) from native_output_staging import native_output_path @@ -82,6 +86,9 @@ def string(value: str) -> bytes: def host_oracle(directory: Path) -> dict: + if os.name == "nt": + return windows_oracle.host_oracle(directory, { + "checkpoint.bin": EXPECTED_BYTES, "empty.bin": b"", "writer.lock": b""}) import fcntl expected = {"checkpoint.bin": EXPECTED_BYTES, "empty.bin": b"", "writer.lock": b""} @@ -135,12 +142,14 @@ def main() -> int: report = {"schema": "nil.durable-file-io.v1", "status": "FAIL", "commands": [], "executions": [], "negative_abi": [], "negative_library": [], "llvm_enabled": args.llvm == "ON", - "scope": "POSIX_SOURCE_RUNTIME_NOT_RELEASE_OR_POWER_CUT_QUALIFICATION"} - if os.name != "posix": - report.update(status="SKIP", reason="POSIX implementation only; unsupported-host checks are separate") + "scope": ("WINDOWS_NTFS_SOURCE_RUNTIME_NOT_RELEASE_OR_POWER_CUT_QUALIFICATION" + if os.name == "nt" else + "POSIX_SOURCE_RUNTIME_NOT_RELEASE_OR_POWER_CUT_QUALIFICATION")} + if os.name not in ("posix", "nt"): + report.update(status="FAIL", error="unsupported host platform: " + os.name) support.save_new(output / "report.json", report) - print("SKIP: " + str(output / "report.json")) - return 0 + print("FAIL: " + str(output / "report.json")) + return 1 ownership = support.load_ownership(ROOT) compiler = args.compiler.resolve(strict=True) @@ -161,6 +170,8 @@ def main() -> int: **sources, **{name: row[0] for name, row in invalid.items()}} if runtime: inputs["runtime"] = runtime + if os.name == "nt": + inputs["windows_oracle"] = Path(windows_oracle.__file__).resolve() report["inputs_before"] = {name: support.file_record(path) for name, path in inputs.items()} environment = {key: value for key, value in os.environ.items() if not key.startswith(("NIL_", "NY_"))} @@ -195,7 +206,10 @@ def execute(name: str, language: str, command: list) -> None: working = output / name working.mkdir() data = working / "data-café 日本語 🦊" - data.mkdir(mode=0o700) + if os.name == "nt": + windows_oracle.create_private_directory(data) + else: + data.mkdir(mode=0o700) run(name, [*command, data], working, EXPECTED_STDOUT) report["executions"].append({"route": name, "language": language, "status": "PASS", "oracle": host_oracle(data)}) @@ -257,22 +271,35 @@ def execute(name: str, language: str, command: list) -> None: for schema in (True, False): name = "foreign-" + operation + "-" + encoding + ("-schema" if schema else "-no-schema") working = output / name - working.mkdir(mode=0o700) + if os.name == "nt": + windows_oracle.create_private_directory(working) + else: + working.mkdir(mode=0o700) existing = working / "existing.bin" existing.write_bytes(EXPECTED_BYTES) existing.chmod(0o600) before = (existing.read_bytes(), existing.lstat().st_ino, stat.S_IMODE(existing.lstat().st_mode), stat.S_IMODE(working.stat().st_mode)) + before_acl = ({"file": windows_oracle.security_hash(existing), + "directory": windows_oracle.security_hash(working)} + if os.name == "nt" else None) artifact = output / (name + ".nil") artifact.write_bytes(foreign_library_nil(operation, encoding == "binary", schema)) run(name, [interpreter, "--no-ai", artifact], working, rejection=(operation + ": requires the intrinsic library").encode()) after = (existing.read_bytes(), existing.lstat().st_ino, stat.S_IMODE(existing.lstat().st_mode), stat.S_IMODE(working.stat().st_mode)) - if {p.name for p in working.iterdir()} != {"existing.bin"} or after != before: + after_acl = ({"file": windows_oracle.security_hash(existing), + "directory": windows_oracle.security_hash(working)} + if os.name == "nt" else None) + if ({p.name for p in working.iterdir()} != {"existing.bin"} or after != before + or after_acl != before_acl): raise AssertionError(name + ": rejected library operand changed the filesystem") - report["negative_library"].append({"operation": operation, "route": encoding + "-vm", - "schema": "present" if schema else "absent", "status": "PASS", "filesystem": "unchanged"}) + row = {"operation": operation, "route": encoding + "-vm", + "schema": "present" if schema else "absent", "status": "PASS", "filesystem": "unchanged"} + if os.name == "nt": + row["windows_acl_sha256"] = before_acl + report["negative_library"].append(row) if len(report["negative_library"]) != 36: raise AssertionError("library rejection matrix incomplete") expected_count = 8 if args.llvm == "ON" else 4 diff --git a/tests/tools/windows_durable_oracle.py b/tests/tools/windows_durable_oracle.py new file mode 100644 index 0000000..c5f9eb5 --- /dev/null +++ b/tests/tools/windows_durable_oracle.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Independent Win32 ctypes oracle for the durable-file route fixtures. + +No framework executable, privacy predicate, or production helper is used here. +This is a local-NTFS runtime observation, not a power-loss/storage qualification. +""" +from __future__ import annotations + +from contextlib import contextmanager +import ctypes as C +from ctypes import wintypes as W +import hashlib +import os +from pathlib import Path +import struct + +if os.name != "nt": + raise RuntimeError("the Windows durable oracle requires Win32") + +K = C.WinDLL("kernel32", use_last_error=True) +A = C.WinDLL("advapi32", use_last_error=True) +N = C.WinDLL("ntdll", use_last_error=True) +VOID = C.c_void_p +PTR = C.POINTER +INVALID_HANDLE = VOID(-1).value +READ_CONTROL = 0x00020000 +FILE_ALL_ACCESS = 0x001F01FF +FILE_ATTRIBUTE_DIRECTORY = 0x10 +FILE_ATTRIBUTE_REPARSE_POINT = 0x400 + + +class SecurityAttributes(C.Structure): + _fields_ = [("length", W.DWORD), ("descriptor", VOID), ("inherit", W.BOOL)] + + +class SidAndAttributes(C.Structure): + _fields_ = [("sid", VOID), ("attributes", W.DWORD)] + + +class FileInformation(C.Structure): + _fields_ = [("attributes", W.DWORD), ("created", W.FILETIME), + ("accessed", W.FILETIME), ("written", W.FILETIME), + ("volume", W.DWORD), ("size_high", W.DWORD), + ("size_low", W.DWORD), ("links", W.DWORD), + ("index_high", W.DWORD), ("index_low", W.DWORD)] + + +class Acl(C.Structure): + _fields_ = [("revision", W.BYTE), ("reserved", W.BYTE), ("size", W.WORD), + ("count", W.WORD), ("reserved2", W.WORD)] + + +class AceHeader(C.Structure): + _fields_ = [("kind", W.BYTE), ("flags", W.BYTE), ("size", W.WORD)] + + +class Overlapped(C.Structure): + _fields_ = [("internal", C.c_size_t), ("internal_high", C.c_size_t), + ("offset", W.DWORD), ("offset_high", W.DWORD), ("event", W.HANDLE)] + + +class IoStatus(C.Union): + _fields_ = [("status", W.LONG), ("pointer", VOID)] + + +class IoStatusBlock(C.Structure): + _fields_ = [("result", IoStatus), ("information", C.c_size_t)] + + +def api(library, name, arguments, result): + function = getattr(library, name) + function.argtypes, function.restype = arguments, result + return function + + +close = api(K, "CloseHandle", [W.HANDLE], W.BOOL) +free = api(K, "LocalFree", [VOID], VOID) +current_process = api(K, "GetCurrentProcess", [], W.HANDLE) +current_thread = api(K, "GetCurrentThread", [], W.HANDLE) +open_process_token = api(A, "OpenProcessToken", [W.HANDLE, W.DWORD, PTR(W.HANDLE)], W.BOOL) +open_thread_token = api(A, "OpenThreadToken", [W.HANDLE, W.DWORD, W.BOOL, PTR(W.HANDLE)], W.BOOL) +token_information = api(A, "GetTokenInformation", [W.HANDLE, C.c_int, VOID, W.DWORD, PTR(W.DWORD)], W.BOOL) +sid_string = api(A, "ConvertSidToStringSidW", [VOID, PTR(VOID)], W.BOOL) +valid_sid = api(A, "IsValidSid", [VOID], W.BOOL) +equal_sid = api(A, "EqualSid", [VOID, VOID], W.BOOL) +sid_length = api(A, "GetLengthSid", [VOID], W.DWORD) +convert_descriptor = api(A, "ConvertStringSecurityDescriptorToSecurityDescriptorW", + [W.LPCWSTR, W.DWORD, PTR(VOID), PTR(W.DWORD)], W.BOOL) +create_directory = api(K, "CreateDirectoryW", [W.LPCWSTR, PTR(SecurityAttributes)], W.BOOL) +create_file = api(K, "CreateFileW", [W.LPCWSTR, W.DWORD, W.DWORD, VOID, W.DWORD, W.DWORD, W.HANDLE], W.HANDLE) +file_type = api(K, "GetFileType", [W.HANDLE], W.DWORD) +file_information = api(K, "GetFileInformationByHandle", [W.HANDLE, PTR(FileInformation)], W.BOOL) +security_information = api(A, "GetSecurityInfo", [W.HANDLE, C.c_int, W.DWORD, PTR(VOID), + PTR(VOID), PTR(VOID), PTR(VOID), PTR(VOID)], W.DWORD) +descriptor_control = api(A, "GetSecurityDescriptorControl", [VOID, PTR(W.WORD), PTR(W.DWORD)], W.BOOL) +valid_acl = api(A, "IsValidAcl", [VOID], W.BOOL) +get_ace = api(A, "GetAce", [VOID, W.DWORD, PTR(VOID)], W.BOOL) +read_file = api(K, "ReadFile", [W.HANDLE, VOID, W.DWORD, PTR(W.DWORD), VOID], W.BOOL) +lock_file = api(K, "LockFileEx", [W.HANDLE, W.DWORD, W.DWORD, W.DWORD, W.DWORD, PTR(Overlapped)], W.BOOL) +unlock_file = api(K, "UnlockFileEx", [W.HANDLE, W.DWORD, W.DWORD, W.DWORD, PTR(Overlapped)], W.BOOL) +volume_information = api(K, "GetVolumeInformationByHandleW", [W.HANDLE, W.LPWSTR, W.DWORD, + PTR(W.DWORD), PTR(W.DWORD), PTR(W.DWORD), W.LPWSTR, W.DWORD], W.BOOL) +query_information = api(N, "NtQueryInformationFile", [W.HANDLE, PTR(IoStatusBlock), VOID, + W.DWORD, C.c_int], W.LONG) + + +def require(condition, message): + if not condition: + raise AssertionError(message) + + +def succeeded(result, operation): + if not result: + raise OSError(C.get_last_error(), "Windows durable oracle: " + operation) + + +@contextmanager +def handle(path: Path, *, write=False, data=False): + access = READ_CONTROL | 0x80 # FILE_READ_ATTRIBUTES + if data: + access |= 0x80000000 # GENERIC_READ + if write: + access |= 0xC0000000 # GENERIC_READ | GENERIC_WRITE + value = create_file(str(path), access, 7, None, 3, + 0x02000000 | 0x00200000, None) # BACKUP_SEMANTICS | OPEN_REPARSE_POINT + require(value not in (None, INVALID_HANDLE), "cannot open an oracle entry without following reparses") + try: + yield value + finally: + succeeded(close(value), "close owned inspection handle") + + +@contextmanager +def effective_user(): + token = W.HANDLE() + if not open_thread_token(current_thread(), 0x0008, True, C.byref(token)): + require(C.get_last_error() == 1008, "cannot inspect effective thread identity") # ERROR_NO_TOKEN + succeeded(open_process_token(current_process(), 0x0008, C.byref(token)), "open process token") + try: + size = W.DWORD() + require(not token_information(token, 1, None, 0, C.byref(size)) and + C.get_last_error() == 122 and 0 < size.value <= 65536, "bound TokenUser buffer") + storage = C.create_string_buffer(size.value) + succeeded(token_information(token, 1, storage, size, C.byref(size)), "read TokenUser") + sid = C.cast(storage, PTR(SidAndAttributes)).contents.sid + require(valid_sid(sid), "effective user SID is invalid") + yield sid # Keep both the token and backing buffer alive through inspection. + finally: + succeeded(close(token), "close owned token handle") + + +def metadata(value): + require(file_type(value) == 1, "oracle entry is not a disk object") + info = FileInformation() + succeeded(file_information(value, C.byref(info)), "read held file metadata") + require(not info.attributes & FILE_ATTRIBUTE_REPARSE_POINT, "oracle entry is a reparse point") + return info + + +def identity(info): + return (info.volume, info.index_high, info.index_low, info.size_high, info.size_low, + info.links, info.attributes, info.written.dwHighDateTime, info.written.dwLowDateTime) + + +def security(value, expected_user=None, directory=False): + owner, acl, descriptor = VOID(), VOID(), VOID() + status = security_information(value, 1, 0x00000001 | 0x00000004, + C.byref(owner), None, C.byref(acl), None, C.byref(descriptor)) + require(status == 0 and descriptor.value, "cannot read held owner/DACL") + try: + control, revision = W.WORD(), W.DWORD() + succeeded(descriptor_control(descriptor, C.byref(control), C.byref(revision)), "read descriptor control") + require(owner.value and valid_sid(owner) and acl.value and valid_acl(acl), "missing/invalid owner or DACL") + header = C.cast(acl, PTR(Acl)).contents + require(8 <= header.size <= 65535, "DACL size is invalid") + owner_bytes = C.string_at(owner, sid_length(owner)) + acl_bytes = C.string_at(acl, header.size) + digest = hashlib.sha256(struct.pack(" str: + """Read-only owner/DACL seal for a before/after nonmutation oracle.""" + with handle(path) as held: + metadata(held) + return security(held)["sha256"] + + +def host_oracle(directory: Path, expected: dict[str, bytes]) -> dict: + expected_directories = {"private"} + observed = {entry.name for entry in directory.iterdir()} + require(observed == set(expected) | expected_directories, "durable namespace differs from exact fixture inventory") + profiles, seals = {}, {} + with effective_user() as user: + with handle(directory) as held: + _, result = inspect(held, user, True) + require_local_ntfs(held) + profiles["."] = result["profile"] + seals["."] = result["sha256"] + for name in sorted(expected_directories): + with handle(directory / name) as held: + _, result = inspect(held, user, True) + profiles[name], seals[name] = result["profile"], result["sha256"] + require(not any((directory / name).iterdir()), "private fixture directory must remain empty") + for name, content in expected.items(): + with handle(directory / name, data=True) as held: + before, result = inspect(held, user, False) + require(before.size_high == 0 and before.size_low == len(content) <= 4096, + "held durable file has the wrong size") + data, count = C.create_string_buffer(len(content) + 1), W.DWORD() + succeeded(read_file(held, data, len(content) + 1, C.byref(count), None), "read held durable bytes") + require(count.value == len(content) and data.raw[:count.value] == content, "durable bytes differ") + after, after_security = inspect(held, user, False) + require(identity(after) == identity(before) and result == after_security, + "held durable entry changed during its independent inspection") + profiles[name], seals[name] = result["profile"], result["sha256"] + with handle(directory / "writer.lock", write=True) as held: + inspect(held, user, False) + overlap = Overlapped() + succeeded(lock_file(held, 0x3, 0, 1, 0, C.byref(overlap)), "acquire external nonblocking byte-zero lock") + try: + inspect(held, user, False) + finally: + succeeded(unlock_file(held, 0, 1, 0, C.byref(overlap)), "release external byte-zero lock") + require({entry.name for entry in directory.iterdir()} == observed, "oracle namespace changed during inspection") + return {"bytes": "exact", "filesystem": "local-NTFS", "remaining_staging_files": 0, + "lock_after_process_completion": "released", "lock_primitive": "LockFileEx-byte-0-length-1", + "private_directories": sorted(expected_directories), "windows_owner": "effective-user", + "windows_dacl": "one-FILE_ALL_ACCESS-owner-allow-ACE", + "windows_acl_profiles": profiles, "windows_acl_sha256": seals} diff --git a/tests/windows_durable_file_io_tests.cpp b/tests/windows_durable_file_io_tests.cpp new file mode 100644 index 0000000..171f7fc --- /dev/null +++ b/tests/windows_durable_file_io_tests.cpp @@ -0,0 +1,698 @@ +#include "../nilcompiler/src/secure_file_io.hpp" +#include "../nilcompiler/src/windows_private_entries.hpp" +#include "../common/private_directory.hpp" + +#ifndef _WIN32 +#error This contract requires the real Win32 filesystem and locking APIs. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace fs = std::filesystem; +namespace entries = ny::detail::windows_private_entries; +using ny::detail::FileLockRegistry; +using nil::detail::storage_handle; + +void require(bool condition, const char *message) { + if (!condition) throw std::runtime_error(message); +} + +template +void refused(const Result &result, const char *message = "rejection must have an error") { + require(!result.ok && !result.error.empty(), message); + require(result.error.find("nil-win-durable-") == std::string::npos && + result.error.find("private-marker") == std::string::npos, + "rejection disclosed a private pathname"); +} + +void verdict(const ny::detail::FileCheck &result, bool expected) { + require(result.ok && result.error.empty() && result.value == expected, + "metadata/query verdict differs from its three-state contract"); +} + +unsigned completed = 0; +template +void contract(const char *name, Function body) { + body(); + ++completed; + std::cout << "PASS " << name << '\n'; +} + +struct fixture { + fs::path root = nil::detail::create_private_directory(fs::temp_directory_path(), + "nil-win-durable-"); + std::vector junctions; + ~fixture() { + // Remove the exact owned reparse entries before ordinary recursive cleanup. + // In particular, cleanup must not traverse a junction's target. + for (const auto &path : junctions) RemoveDirectoryW(path.c_str()); + std::error_code ignored; + fs::remove_all(root, ignored); + } +}; + +void write_file(const fs::path &path, const std::string &bytes, bool inherited = false) { + nil::detail::owner_security identity; + std::error_code error; + require(identity.initialize(false, error), "initialize fixture identity"); + SECURITY_DESCRIPTOR descriptor{}; + require(InitializeSecurityDescriptor(&descriptor, SECURITY_DESCRIPTOR_REVISION), + "initialize inherited fixture descriptor"); + require(SetSecurityDescriptorOwner(&descriptor, identity.sid(), FALSE), + "set inherited fixture owner"); + // Omit the DACL only for the inherited-profile control; explicit ownership + // avoids TokenOwner group defaults on an elevated CI worker. + auto attributes = identity.attributes(); + if (inherited) attributes.lpSecurityDescriptor = &descriptor; + storage_handle file(CreateFileW(path.c_str(), GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &attributes, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL, nullptr)); + require(file.get() != INVALID_HANDLE_VALUE, "create fixture file exclusively"); + DWORD count = 0; + require(WriteFile(file.get(), bytes.data(), static_cast(bytes.size()), &count, nullptr) && + count == bytes.size(), "write fixture bytes"); +} + +std::string read_file(const fs::path &path) { + require(fs::file_size(path) <= 4096, "fixture unexpectedly grew"); + std::ifstream input(path, std::ios::binary); + require(static_cast(input), "read fixture file"); + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +void make_public(const fs::path &path) { + PSECURITY_DESCRIPTOR descriptor = nullptr; + require(ConvertStringSecurityDescriptorToSecurityDescriptorW( + L"D:P(A;OICI;FA;;;WD)", SDDL_REVISION_1, &descriptor, nullptr), + "create public fixture descriptor"); + PACL acl = nullptr; + BOOL present = FALSE, defaulted = FALSE; + const bool extracted = GetSecurityDescriptorDacl(descriptor, &present, &acl, &defaulted) && present; + const auto result = extracted ? SetNamedSecurityInfoW(const_cast(path.c_str()), + SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, + nullptr, nullptr, acl, nullptr) : ERROR_INVALID_SECURITY_DESCR; + LocalFree(descriptor); + require(result == ERROR_SUCCESS, "apply public fixture ACL"); +} + +class restricted_identity { +public: + restricted_identity() { + HANDLE process = nullptr; + require(OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &process), + "open fixture process token"); + storage_handle source(process); + BYTE world[SECURITY_MAX_SID_SIZE]{}; + DWORD size = sizeof(world); + require(CreateWellKnownSid(WinWorldSid, nullptr, world, &size), "create restricting SID"); + SID_AND_ATTRIBUTES restricting{world, 0}; + require(CreateRestrictedToken(source.get(), DISABLE_MAX_PRIVILEGE, 0, nullptr, + 0, nullptr, 1, &restricting, &token_), "create restricted fixture identity"); + } + ~restricted_identity() { if (token_) CloseHandle(token_); } + template + auto run(Function body) { + require(ImpersonateLoggedOnUser(token_), "impersonate restricted fixture identity"); + struct revert { + ~revert() { if (!RevertToSelf()) std::terminate(); } + } scope; + return body(); + } + DWORD open(const fs::path &path, DWORD access, DWORD creation = OPEN_EXISTING) { + require(ImpersonateLoggedOnUser(token_), "impersonate restricted fixture identity"); + const HANDLE file = CreateFileW(path.c_str(), access, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, creation, + FILE_ATTRIBUTE_NORMAL, nullptr); + const auto error = file == INVALID_HANDLE_VALUE ? GetLastError() : ERROR_SUCCESS; + if (file != INVALID_HANDLE_VALUE) CloseHandle(file); + if (!RevertToSelf()) std::terminate(); + return error; + } +private: + HANDLE token_ = nullptr; +}; + +void junction(fixture &owned, const fs::path &path, const fs::path &target) { + require(fs::create_directory(path), "create junction entry"); + owned.junctions.push_back(path); + const std::wstring shown = fs::absolute(target).wstring(); + const std::wstring substitute = L"\\??\\" + shown; + struct data { + DWORD tag; + USHORT length, reserved, substitute_offset, substitute_length, print_offset, print_length; + WCHAR names[1]; + }; + std::vector storage(offsetof(data, names) + + (substitute.size() + shown.size() + 2) * sizeof(WCHAR), 0); + auto *value = reinterpret_cast(storage.data()); + value->tag = IO_REPARSE_TAG_MOUNT_POINT; + value->length = static_cast(storage.size() - 8); + value->substitute_length = static_cast(substitute.size() * sizeof(WCHAR)); + value->print_offset = static_cast((substitute.size() + 1) * sizeof(WCHAR)); + value->print_length = static_cast(shown.size() * sizeof(WCHAR)); + std::memcpy(value->names, substitute.data(), value->substitute_length); + std::memcpy(reinterpret_cast(value->names) + value->print_offset, + shown.data(), value->print_length); + storage_handle handle(CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr)); + require(handle.get() != INVALID_HANDLE_VALUE, "open owned junction entry"); + DWORD returned = 0; + require(DeviceIoControl(handle.get(), FSCTL_SET_REPARSE_POINT, value, + static_cast(storage.size()), nullptr, 0, &returned, nullptr), + "set junction without symlink privileges"); +} + +std::set names(const fs::path &root) { + std::set result; + for (const auto &entry : fs::directory_iterator(root)) result.insert(entry.path().filename().wstring()); + return result; +} + +// Win32 command-line quoting, including backslashes immediately before quotes +// and the closing quote. No shell or command interpreter participates. +std::wstring quote(const std::wstring &argument) { + std::wstring result = L"\""; + std::size_t slashes = 0; + for (const auto ch : argument) { + if (ch == L'\\') { ++slashes; continue; } + result.append(ch == L'"' ? slashes * 2 + 1 : slashes, L'\\'); + slashes = 0; + result += ch; + } + result.append(slashes * 2, L'\\'); + return result + L'"'; +} + +class child { +public: + child(const wchar_t *mode, const fs::path &path) { + SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE}; + ready_ = CreateEventW(&attributes, TRUE, FALSE, nullptr); + stop_ = CreateEventW(&attributes, TRUE, FALSE, nullptr); + try { + require(ready_ && stop_, "create child coordination events"); + std::vector executable(32768); + const auto count = GetModuleFileNameW(nullptr, executable.data(), static_cast(executable.size())); + require(count && count < executable.size(), "locate current test executable"); + std::wstring command = quote(std::wstring(executable.data(), count)) + L" --child " + + quote(mode) + L" " + quote(path.wstring()) + L" " + + std::to_wstring(reinterpret_cast(ready_)) + L" " + + std::to_wstring(reinterpret_cast(stop_)); + SIZE_T size = 0; + InitializeProcThreadAttributeList(nullptr, 1, 0, &size); + require(size != 0, "size child handle whitelist"); + std::vector buffer(size); + auto *list = reinterpret_cast(buffer.data()); + require(InitializeProcThreadAttributeList(list, 1, 0, &size), "initialize child handle whitelist"); + HANDLE handles[]{ready_, stop_}; + const bool updated = UpdateProcThreadAttribute(list, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, + handles, sizeof(handles), nullptr, nullptr) != 0; + STARTUPINFOEXW startup{}; + startup.StartupInfo.cb = sizeof(startup); + startup.lpAttributeList = list; + PROCESS_INFORMATION process{}; + const bool started = updated && CreateProcessW(executable.data(), command.data(), nullptr, + nullptr, TRUE, EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, nullptr, nullptr, + &startup.StartupInfo, &process); + DeleteProcThreadAttributeList(list); + require(started, "launch bounded owned child"); + process_ = process.hProcess; + CloseHandle(process.hThread); + } catch (...) { + if (ready_) CloseHandle(ready_); + if (stop_) CloseHandle(stop_); + throw; + } + } + ~child() { + if (process_) { + if (WaitForSingleObject(process_, 0) == WAIT_TIMEOUT) { + // This is only the handle returned for this exact child, never a name, + // PID search, job shared with another process, or machine-wide kill. + TerminateProcess(process_, 99); + WaitForSingleObject(process_, 5000); + } + CloseHandle(process_); + } + CloseHandle(ready_); + CloseHandle(stop_); + } + child(const child &) = delete; + child &operator=(const child &) = delete; + void ready() { + HANDLE handles[]{ready_, process_}; + require(WaitForMultipleObjects(2, handles, FALSE, 5000) == WAIT_OBJECT_0, + "child failed before lock-ready signal or exceeded deadline"); + } + void finish() { + require(SetEvent(stop_), "signal owned child completion"); + wait(0); + } + void wait(DWORD expected) { + require(WaitForSingleObject(process_, 5000) == WAIT_OBJECT_0, "owned child exceeded deadline"); + DWORD code = 0; + require(GetExitCodeProcess(process_, &code) && code == expected, "owned child contract failed"); + } + void crash() { + require(TerminateProcess(process_, 77), "terminate exact owned lock holder"); + wait(77); + } +private: + HANDLE ready_ = nullptr, stop_ = nullptr, process_ = nullptr; +}; + +int child_main(const std::wstring &mode, const fs::path &path, HANDLE ready, HANDLE stop) { + if (mode == L"registry-blocked") { + FileLockRegistry registry; + refused(registry.acquire(path.u8string(), false)); + require(registry.empty(), "failed child acquisition retained a token"); + return 0; + } + if (mode == L"registry-hold") { + FileLockRegistry registry; + const auto lock = registry.acquire(path.u8string(), false); + require(lock.ok, "child cannot acquire registry lock"); + require(SetEvent(ready), "signal registry lock readiness"); + require(WaitForSingleObject(stop, 15000) == WAIT_OBJECT_0, "child stop deadline"); + require(registry.release(lock.token).ok, "release child registry lock"); + return 0; + } + require(mode == L"raw-blocked" || mode == L"raw-hold", "unknown child operation"); + storage_handle handle(CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT, nullptr)); + require(handle.get() != INVALID_HANDLE_VALUE, "external lock must open backing file"); + OVERLAPPED overlap{}; + const bool acquired = LockFileEx(handle.get(), LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, + 0, 1, 0, &overlap) != 0; + const auto error = GetLastError(); + if (mode == L"raw-blocked") { + if (acquired) UnlockFileEx(handle.get(), 0, 1, 0, &overlap); + require(!acquired && error == ERROR_LOCK_VIOLATION, + "external byte-zero contender must fail specifically on lock contention"); + return 0; + } + require(acquired, "external child cannot lock byte zero"); + require(SetEvent(ready), "signal external lock readiness"); + require(WaitForSingleObject(stop, 15000) == WAIT_OBJECT_0, "external child stop deadline"); + require(UnlockFileEx(handle.get(), 0, 1, 0, &overlap), "release external child lock"); + return 0; +} + +void private_contracts(fixture &owned) { + const auto &root = owned.root; + const auto directory = root / "private-marker-directory"; + const auto file = root / "private-marker-file"; + contract("exclusive-owner-only-create", [&] { + require(ny::detail::create_private_directory_utf8(directory.u8string()).ok, + "create private directory"); + verdict(ny::detail::private_directory_utf8(directory.u8string()), true); + write_file(file, "retained\n"); + verdict(ny::detail::private_regular_file_utf8(file.u8string()), true); + refused(ny::detail::create_private_directory_utf8(directory.u8string())); + refused(ny::detail::create_private_directory_utf8(file.u8string())); + require(read_file(file) == "retained\n", "exclusive creation clobbered bytes"); + }); + contract("inherited-owner-only-profile", [&] { + const auto inherited = directory / "inherited-file"; + write_file(inherited, "inherited", true); + verdict(ny::detail::private_regular_file_utf8(inherited.u8string()), true); + nil::detail::owner_security identity; + std::error_code error; + require(identity.initialize(true, error), "initialize inherited directory identity"); + SECURITY_DESCRIPTOR descriptor{}; + require(InitializeSecurityDescriptor(&descriptor, SECURITY_DESCRIPTOR_REVISION) && + SetSecurityDescriptorOwner(&descriptor, identity.sid(), FALSE), "inherited directory owner"); + SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), &descriptor, FALSE}; + const auto nested = directory / "inherited-directory"; + require(CreateDirectoryW(nested.c_str(), &attributes), "create inherited directory"); + verdict(ny::detail::private_directory_utf8(nested.u8string()), true); + FileLockRegistry registry; + const auto lock = registry.acquire(inherited.u8string(), false); + require(lock.ok && registry.release(lock.token).ok, "lock inherited owner-only file"); + }); + contract("public-parent-private-creation-access-check", [&] { + const auto shared = root / "public-parent"; + require(fs::create_directory(shared), "create public parent"); + make_public(shared); + const auto public_file = shared / "control"; + write_file(public_file, "public"); + make_public(public_file); + restricted_identity reader; + require(reader.open(public_file, FILE_READ_DATA) == ERROR_SUCCESS && + reader.open(public_file, FILE_WRITE_DATA) == ERROR_SUCCESS, + "restricted reader/writer negative control must have access"); + const auto secret = shared / "private-child"; + require(ny::detail::create_private_directory_utf8(secret.u8string()).ok, + "create private child under public parent"); + const auto payload = secret / "payload"; + write_file(payload, "private", true); + require(reader.open(payload, FILE_READ_DATA) == ERROR_ACCESS_DENIED && + reader.open(payload, FILE_WRITE_DATA) == ERROR_ACCESS_DENIED && + reader.open(secret / "injection", FILE_WRITE_DATA, CREATE_NEW) == ERROR_ACCESS_DENIED, + "private creation must exclude restricted reads, writes, and child injection"); + }); + contract("public-acl-false-and-lock-refusal", [&] { + const auto loose_file = root / "private-marker-public-file"; + const auto loose_dir = root / "private-marker-public-directory"; + write_file(loose_file, "unchanged"); + require(ny::detail::create_private_directory_utf8(loose_dir.u8string()).ok, "public directory fixture"); + make_public(loose_file); + make_public(loose_dir); + verdict(ny::detail::private_regular_file_utf8(loose_file.u8string()), false); + verdict(ny::detail::private_directory_utf8(loose_dir.u8string()), false); + FileLockRegistry registry; + refused(registry.acquire(loose_file.u8string(), false)); + require(registry.empty() && read_file(loose_file) == "unchanged", "public refusal changed fixture"); + }); + contract("wrong-owner-descriptor-false", [&] { + // A normal account cannot assign an arbitrary foreign owner to an NTFS + // file. Exercise the same production predicate with this real file's ACL + // and a well-known foreign owner; no privilege or account setup is needed. + nil::detail::owner_security identity; + std::error_code error; + require(identity.initialize(false, error), "initialize descriptor identity"); + PSECURITY_DESCRIPTOR raw = nullptr; + PACL acl = nullptr; + PSID owner = nullptr; + require(GetNamedSecurityInfoW(file.c_str(), SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, &owner, nullptr, + &acl, nullptr, &raw) == ERROR_SUCCESS, "read real fixture security descriptor"); + struct descriptor_owner { PSECURITY_DESCRIPTOR value; ~descriptor_owner() { LocalFree(value); } } held{raw}; + verdict(entries::inspect_descriptor(raw, identity.sid(), false, "test.descriptor"), true); + BYTE world[SECURITY_MAX_SID_SIZE]{}; + DWORD size = sizeof(world); + require(CreateWellKnownSid(WinWorldSid, nullptr, world, &size), "create foreign owner SID"); + SECURITY_DESCRIPTOR altered{}; + require(InitializeSecurityDescriptor(&altered, SECURITY_DESCRIPTOR_REVISION) && + SetSecurityDescriptorOwner(&altered, world, FALSE) && + SetSecurityDescriptorDacl(&altered, TRUE, acl, FALSE) && + SetSecurityDescriptorControl(&altered, SE_DACL_PROTECTED, SE_DACL_PROTECTED), + "construct wrong-owner descriptor control"); + verdict(entries::inspect_descriptor(&altered, identity.sid(), false, "test.descriptor"), false); + require(SetSecurityDescriptorOwner(&altered, owner, FALSE), "restore matching owner control"); + verdict(entries::inspect_descriptor(&altered, identity.sid(), false, "test.descriptor"), true); + refused(entries::inspect_descriptor(nullptr, identity.sid(), false, "test.descriptor")); + refused(entries::inspect_descriptor(raw, nullptr, false, "test.descriptor")); + verdict(ny::detail::private_regular_file_utf8(file.u8string()), true); + }); + contract("cross-kind-false", [&] { + verdict(ny::detail::private_regular_file_utf8(directory.u8string()), false); + verdict(ny::detail::private_directory_utf8(file.u8string()), false); + FileLockRegistry registry; + refused(registry.acquire(directory.u8string(), false)); + refused(registry.acquire(directory.u8string(), true)); + }); + contract("junction-no-follow-and-no-adoption", [&] { + const auto link = root / "private-marker-junction"; + junction(owned, link, directory); + verdict(ny::detail::private_directory_utf8(link.u8string()), false); + verdict(ny::detail::private_regular_file_utf8(link.u8string()), false); + refused(ny::detail::create_private_directory_utf8(link.u8string())); + FileLockRegistry registry; + refused(registry.acquire(link.u8string(), false)); + refused(registry.acquire(link.u8string(), true)); + verdict(ny::detail::private_directory_utf8(directory.u8string()), true); + }); + contract("single-link-required", [&] { + const auto alias = root / "private-marker-hardlink"; + require(CreateHardLinkW(alias.c_str(), file.c_str(), nullptr), "create hard-link fixture"); + verdict(ny::detail::private_regular_file_utf8(file.u8string()), false); + verdict(ny::detail::private_regular_file_utf8(alias.u8string()), false); + FileLockRegistry registry; + refused(registry.acquire(file.u8string(), false)); + refused(registry.acquire(alias.u8string(), false)); + require(DeleteFileW(alias.c_str()), "remove owned hard link"); + verdict(ny::detail::private_regular_file_utf8(file.u8string()), true); + require(read_file(file) == "retained\n", "hard-link rejection modified payload"); + }); + contract("missing-and-uninspectable-are-errors", [&] { + const auto missing = root / "private-marker-missing"; + refused(ny::detail::private_regular_file_utf8(missing.u8string()), "missing regular metadata must be Error"); + refused(ny::detail::private_directory_utf8(missing.u8string()), "missing directory metadata must be Error"); + FileLockRegistry registry; + refused(registry.acquire(missing.u8string(), false), "missing existing lock must be Error"); + require(!fs::exists(missing), "open-existing created a missing lock"); + const auto unreadable = root / "private-marker-uninspectable"; + write_file(unreadable, "uninspectable"); + nil::detail::owner_security identity; + std::error_code error; + require(identity.initialize(false, error), "initialize uninspectable fixture identity"); + LPWSTR sid = nullptr; + require(ConvertSidToStringSidW(identity.sid(), &sid), "format fixture owner SID"); + const std::wstring sddl = L"D:P(D;;RC;;;OW)(A;;FA;;;" + std::wstring(sid) + L")"; + LocalFree(sid); + PSECURITY_DESCRIPTOR descriptor = nullptr; + require(ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(), + SDDL_REVISION_1, &descriptor, nullptr), "construct uninspectable fixture ACL"); + PACL acl = nullptr; + BOOL present = FALSE, defaulted = FALSE; + const bool extracted = GetSecurityDescriptorDacl(descriptor, &present, &acl, &defaulted) && present; + const DWORD applied = extracted ? SetNamedSecurityInfoW(const_cast(unreadable.c_str()), + SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, + nullptr, nullptr, acl, nullptr) : ERROR_INVALID_SECURITY_DESCR; + LocalFree(descriptor); + require(applied == ERROR_SUCCESS, "deny READ_CONTROL on only the owned fixture"); + // OWNER RIGHTS removes the owner's implicit READ_CONTROL grant. This is + // a real inspection failure, unlike metadata opens which bypass data + // sharing restrictions. DELETE/WRITE_DAC remain available for cleanup. + // An elevated runner may have backup privileges enabled. Disable them in + // this owned impersonation token rather than assuming machine policy. + restricted_identity restricted; + refused(restricted.run([&] { return ny::detail::private_regular_file_utf8(unreadable.u8string()); }), + "uninspectable regular metadata must be Error"); + refused(restricted.run([&] { return ny::detail::private_directory_utf8(unreadable.u8string()); }), + "uninspectable directory metadata must be Error"); + refused(restricted.run([&] { return registry.acquire(unreadable.u8string(), false); }), + "uninspectable existing lock must be Error"); + require(registry.empty(), "inspection error retained registry state"); + }); + contract("utf8-without-code-page-conversion", [&] { + const auto unicode = root / fs::u8path(u8"caf\u00e9-\u65e5\U0001f512"); + require(ny::detail::create_private_directory_utf8(unicode.u8string()).ok, "UTF-8 directory creation"); + verdict(ny::detail::private_directory_utf8(unicode.u8string()), true); + const auto name = unicode / fs::u8path(u8"\u00e9.lock"); + FileLockRegistry registry; + const auto lock = registry.acquire(name.u8string(), true); + require(lock.ok, "UTF-8 lock creation"); + verdict(ny::detail::private_regular_file_utf8(name.u8string()), true); + require(registry.release(lock.token).ok && fs::exists(name), "UTF-8 lock release"); + }); + contract("invalid-paths-no-normalization-or-mutation", [&] { + const auto prefix = (root / "private-marker-invalid").u8string(); + const auto before = names(root); + const std::vector paths{ + "", prefix + std::string("\0suffix", 7), prefix + static_cast(0xff), + prefix + ":stream", prefix + ".", prefix + " ", prefix + "/", prefix + "\\", + (root / "CON").u8string(), (root / "nul.txt").u8string(), + (root / "COM1.log").u8string(), (root / fs::u8path(u8"LPT\u00b9.txt")).u8string(), + (root / "CONIN$").u8string(), root.u8string() + "/./private-marker-invalid", + root.u8string() + "/../private-marker-invalid", "\\\\?\\" + prefix, + "\\\\.\\NUL", "C:private-marker-invalid"}; + require(paths.size() == 18, "invalid-path inventory changed"); + FileLockRegistry registry; + for (const auto &path : paths) { + refused(ny::detail::create_private_directory_utf8(path)); + refused(ny::detail::private_regular_file_utf8(path)); + refused(ny::detail::private_directory_utf8(path)); + refused(registry.acquire(path, false)); + refused(registry.acquire(path, true)); + } + require(names(root) == before && registry.empty(), "invalid paths mutated the owned namespace"); + require(!fs::exists(root / "private-marker-invalid"), "invalid path was truncated or normalized"); + }); +} + +void lock_contracts(const fs::path &root) { + contract("registry-ownership-stale-and-monotonic-tokens", [&] { + FileLockRegistry first, second; + const auto path = root / "tokens.lock"; + for (const auto token : {std::int64_t(0), std::int64_t(-1), std::numeric_limits::max()}) { + verdict(first.is_held(token), false); + refused(first.release(token)); + } + const auto lock = first.acquire(path.u8string(), true); + require(lock.ok && lock.token > 0 && !first.empty(), "acquire initial token"); + verdict(first.is_held(lock.token), true); + verdict(second.is_held(lock.token), false); + refused(second.release(lock.token)); + verdict(first.is_held(lock.token), true); + refused(second.acquire(path.u8string(), false)); + refused(first.acquire(path.u8string(), false)); + require(first.release(lock.token).ok, "release initial token"); + verdict(first.is_held(lock.token), false); + refused(first.release(lock.token)); + const auto next = second.acquire(path.u8string(), false); + require(next.ok && next.token > lock.token, "tokens must be process-monotonic across registries"); + verdict(first.is_held(next.token), false); + require(second.release(next.token).ok && first.empty() && second.empty(), "release monotonic token"); + }); + contract("no-clobber-create-and-payload-preservation", [&] { + const auto path = root / "private-marker-existing.lock"; + write_file(path, "preserve this payload"); + FileLockRegistry registry; + refused(registry.acquire(path.u8string(), true)); + require(read_file(path) == "preserve this payload", "lock creation truncated an existing file"); + const auto lock = registry.acquire(path.u8string(), false); + require(lock.ok && registry.release(lock.token).ok, "acquire/release existing file"); + require(read_file(path) == "preserve this payload", "locking modified an existing payload"); + const auto fresh = root / "fresh.lock"; + const auto created = registry.acquire(fresh.u8string(), true); + require(created.ok, "exclusively create fresh lock"); + verdict(ny::detail::private_regular_file_utf8(fresh.u8string()), true); + refused(registry.acquire(fresh.u8string(), true)); + require(registry.release(created.token).ok && fs::file_size(fresh) == 0, + "fresh lock must remain an empty private file after release"); + }); + contract("live-handle-pins-final-namespace-entry", [&] { + const auto path = root / "pinned.lock"; + const auto replacement = root / "replacement.lock"; + const auto moved = root / "moved.lock"; + write_file(path, "pinned"); + write_file(replacement, "replacement"); + FileLockRegistry registry; + const auto lock = registry.acquire(path.u8string(), false); + require(lock.ok, "acquire namespace pin"); + require(!DeleteFileW(path.c_str()) && GetLastError() == ERROR_SHARING_VIOLATION, + "live lock must deny deletion of its backing entry"); + require(!MoveFileExW(path.c_str(), moved.c_str(), 0) && GetLastError() == ERROR_SHARING_VIOLATION, + "live lock must deny renaming of its backing entry"); + const BOOL replaced = MoveFileExW(replacement.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING); + const DWORD replacement_error = GetLastError(); + require(!replaced && (replacement_error == ERROR_SHARING_VIOLATION || + replacement_error == ERROR_ACCESS_DENIED), + "live lock must deny replacement of its backing entry"); + verdict(registry.is_held(lock.token), true); + require(registry.release(lock.token).ok, "release namespace pin"); + require(read_file(path) == "pinned" && read_file(replacement) == "replacement" && + !fs::exists(moved), "namespace contention changed existing entries"); + require(MoveFileExW(path.c_str(), moved.c_str(), 0), "released handle must stop pinning the name"); + }); + contract("clear-retires-all-tokens-and-closes-handles", [&] { + FileLockRegistry first, second; + const auto a = root / "clear-a.lock", b = root / "clear-b.lock"; + const auto one = first.acquire(a.u8string(), true), two = first.acquire(b.u8string(), true); + require(one.ok && two.ok, "acquire two clear fixtures"); + first.clear(); + first.clear(); + verdict(first.is_held(one.token), false); + verdict(first.is_held(two.token), false); + refused(first.release(one.token)); + require(first.empty(), "clear must empty registry"); + const auto after_a = second.acquire(a.u8string(), false), after_b = second.acquire(b.u8string(), false); + require(after_a.ok && after_b.ok && after_a.token > two.token && after_b.token > after_a.token, + "clear must release every OS lock without recycling tokens"); + second.clear(); + require(DeleteFileW(a.c_str()) && DeleteFileW(b.c_str()), "clear must close namespace-pinning handles"); + }); + contract("registry-destruction-releases-os-lock", [&] { + const auto path = root / "destructor.lock"; + std::int64_t old = 0; + { + FileLockRegistry transient; + const auto lock = transient.acquire(path.u8string(), true); + require(lock.ok, "acquire destruction fixture"); + old = lock.token; + } + FileLockRegistry next; + const auto lock = next.acquire(path.u8string(), false); + require(lock.ok && lock.token > old, "registry destruction must release its OS lock"); + verdict(next.is_held(old), false); + require(next.release(lock.token).ok && DeleteFileW(path.c_str()), "destruction must leave no open handles"); + }); + contract("cross-process-registry-contention", [&] { + const auto path = root / "process-registry.lock"; + FileLockRegistry registry; + const auto lock = registry.acquire(path.u8string(), true); + require(lock.ok, "acquire parent process lock"); + child contender(L"registry-blocked", path); + contender.wait(0); + verdict(registry.is_held(lock.token), true); + require(registry.release(lock.token).ok, "release parent process lock"); + }); + contract("external-lockfileex-contends-with-registry", [&] { + const auto path = root / "process-external-contender.lock"; + FileLockRegistry registry; + const auto lock = registry.acquire(path.u8string(), true); + require(lock.ok, "acquire external contention fixture"); + child contender(L"raw-blocked", path); + contender.wait(0); + verdict(registry.is_held(lock.token), true); + require(registry.release(lock.token).ok, "release external contention fixture"); + }); + contract("registry-contends-with-external-lockfileex", [&] { + const auto path = root / "process-external-owner.lock"; + write_file(path, "external payload"); + child external(L"raw-hold", path); + external.ready(); + FileLockRegistry registry; + refused(registry.acquire(path.u8string(), false)); + require(registry.empty(), "external contention retained registry state"); + external.finish(); + const auto lock = registry.acquire(path.u8string(), false); + require(lock.ok && registry.release(lock.token).ok, "acquire after external unlock"); + require(read_file(path) == "external payload", "external cooperation changed payload"); + }); + contract("child-normal-release-and-process-death-release", [&] { + const auto path = root / "process-death.lock"; + write_file(path, "death control"); + FileLockRegistry registry; + { + child normal(L"registry-hold", path); + normal.ready(); + refused(registry.acquire(path.u8string(), false)); + normal.finish(); + } + const auto after_normal = registry.acquire(path.u8string(), false); + require(after_normal.ok && registry.release(after_normal.token).ok, "acquire after normal child exit"); + { + child crashed(L"registry-hold", path); + crashed.ready(); + refused(registry.acquire(path.u8string(), false)); + crashed.crash(); + } + // Windows may finish releasing outstanding process file locks shortly + // after its process handle becomes signalled; retry only within 2 seconds. + ny::detail::FileLockResult recovered; + const auto deadline = GetTickCount64() + 2000; + do { + recovered = registry.acquire(path.u8string(), false); + if (recovered.ok) break; + Sleep(10); + } while (GetTickCount64() < deadline); + require(recovered.ok && registry.release(recovered.token).ok, "process death must release its lock"); + require(read_file(path) == "death control", "process cleanup changed backing bytes"); + }); +} +} // namespace + +int wmain(int argc, wchar_t **argv) { + try { + if (argc == 6 && std::wstring(argv[1]) == L"--child") { + return child_main(argv[2], fs::path(argv[3]), + reinterpret_cast(static_cast(std::stoull(argv[4]))), + reinterpret_cast(static_cast(std::stoull(argv[5])))); + } + require(argc == 1, "unexpected contract arguments"); + fixture owned; + private_contracts(owned); + lock_contracts(owned.root); + require(completed == 20, "Windows durable contract inventory changed"); + std::cout << "windows-durable-file-io-ok: 20 contracts; 18 invalid paths\n"; + return 0; + } catch (const std::exception &error) { + std::cerr << "windows-durable-file-io: " << error.what() << '\n'; + return 1; + } +} diff --git a/tests/windows_durable_publication_tests.cpp b/tests/windows_durable_publication_tests.cpp new file mode 100644 index 0000000..72d7672 --- /dev/null +++ b/tests/windows_durable_publication_tests.cpp @@ -0,0 +1,420 @@ +#include "../common/private_directory.hpp" + +#ifndef _WIN32 +#error This contract requires the real Win32 filesystem APIs. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// This executable is deliberately a single translation unit. Only its private +// copy of the inline implementation sees these redirects; production has no +// fault switches and this target must not also link secure_file_io.cpp. +BOOL WINAPI contract_flush(HANDLE handle); +BOOL WINAPI contract_close(HANDLE handle); +BOOL WINAPI contract_volume(HANDLE handle, LPWSTR volume, DWORD volume_size, + LPDWORD serial, LPDWORD component_size, LPDWORD flags, LPWSTR filesystem, + DWORD filesystem_size); +#define FlushFileBuffers contract_flush +#define CloseHandle contract_close +#define GetVolumeInformationByHandleW contract_volume +#include "../nilcompiler/src/windows_durable_publication.hpp" +#undef GetVolumeInformationByHandleW +#undef CloseHandle +#undef FlushFileBuffers + +namespace { +namespace fs = std::filesystem; +namespace publication = ny::detail::windows_durable_publication; +namespace entries = ny::detail::windows_private_entries; +using nil::detail::storage_handle; + +enum class flush_fault { none, regular, directory }; +flush_fault pending = flush_fault::none; +bool fault_consumed = false; +bool fail_published_close = false, close_fault_consumed = false; +bool force_non_ntfs = false; +std::vector flushes; +fs::path pin_from, pin_to; +bool pin_attempted = false, pin_refused = false; + +void require(bool condition, const char *message) { + if (!condition) throw std::runtime_error(message); +} + +void reset_observation() { + pending = flush_fault::none; + fault_consumed = false; + fail_published_close = close_fault_consumed = false; + force_non_ntfs = false; + flushes.clear(); + pin_from.clear(); + pin_to.clear(); + pin_attempted = pin_refused = false; +} + +void refused(const ny::detail::AtomicFileWrite &result) { + require(!result.ok && !result.error.empty(), "rejection must include a diagnostic"); + require(result.error.find("nil-win-publication-") == std::string::npos && + result.error.find("private-marker") == std::string::npos, + "rejection disclosed a private pathname"); +} + +unsigned completed = 0; +template +void contract(const char *name, Function body) { + reset_observation(); + body(); + reset_observation(); + ++completed; + std::cout << "PASS " << name << '\n'; +} + +struct fixture { + fs::path root = nil::detail::create_private_directory(fs::temp_directory_path(), + "nil-win-publication-"); + std::vector junctions; + ~fixture() { + for (const auto &path : junctions) RemoveDirectoryW(path.c_str()); + std::error_code ignored; + fs::remove_all(root, ignored); + } +}; + +std::set names(const fs::path &root) { + std::set result; + for (const auto &entry : fs::directory_iterator(root)) result.insert(entry.path().filename().wstring()); + return result; +} + +void write_fixture(const fs::path &path, const std::string &bytes) { + std::ofstream output(path, std::ios::binary | std::ios::trunc); + require(static_cast(output), "open owned publication fixture"); + output.write(bytes.data(), static_cast(bytes.size())); + output.close(); + require(static_cast(output), "finish owned publication fixture"); +} + +std::string read_fixture(const fs::path &path) { + require(fs::file_size(path) <= 4096, "fixture unexpectedly grew"); + std::ifstream input(path, std::ios::binary); + require(static_cast(input), "read owned publication fixture"); + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +void private_file(const fs::path &path) { + const auto result = entries::inspect_regular_file(path); + require(result.ok && result.value && result.error.empty(), "publication must be a private single-link regular file"); +} + +void make_public(const fs::path &path) { + PSECURITY_DESCRIPTOR descriptor = nullptr; + require(ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;;FA;;;WD)", + SDDL_REVISION_1, &descriptor, nullptr), "create public source descriptor"); + PACL acl = nullptr; + BOOL present = FALSE, defaulted = FALSE; + const bool extracted = GetSecurityDescriptorDacl(descriptor, &present, &acl, &defaulted) && present; + const DWORD status = extracted ? SetNamedSecurityInfoW(const_cast(path.c_str()), + SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, + nullptr, nullptr, acl, nullptr) : ERROR_INVALID_SECURITY_DESCR; + LocalFree(descriptor); + require(status == ERROR_SUCCESS, "apply public source ACL"); +} + +void junction(fixture &owned, const fs::path &path, const fs::path &target) { + require(fs::create_directory(path), "create owned junction entry"); + owned.junctions.push_back(path); + const auto shown = fs::absolute(target).wstring(); + const auto substitute = L"\\??\\" + shown; + struct data { + DWORD tag; + USHORT length, reserved, substitute_offset, substitute_length, print_offset, print_length; + WCHAR names[1]; + }; + std::vector storage(offsetof(data, names) + + (substitute.size() + shown.size() + 2) * sizeof(WCHAR), 0); + auto *value = reinterpret_cast(storage.data()); + value->tag = IO_REPARSE_TAG_MOUNT_POINT; + value->length = static_cast(storage.size() - 8); + value->substitute_length = static_cast(substitute.size() * sizeof(WCHAR)); + value->print_offset = static_cast((substitute.size() + 1) * sizeof(WCHAR)); + value->print_length = static_cast(shown.size() * sizeof(WCHAR)); + std::memcpy(value->names, substitute.data(), value->substitute_length); + std::memcpy(reinterpret_cast(value->names) + value->print_offset, shown.data(), value->print_length); + storage_handle held(CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr)); + require(held.get() != INVALID_HANDLE_VALUE, "open owned junction entry"); + DWORD returned = 0; + require(DeviceIoControl(held.get(), FSCTL_SET_REPARSE_POINT, value, + static_cast(storage.size()), nullptr, 0, &returned, nullptr), "set owned junction reparse data"); +} + +void run_contracts(fixture &owned) { + const auto &root = owned.root; + const std::vector binary{0, '\n', '\r', static_cast(0x80), static_cast(0xff)}; + const std::string exact(binary.begin(), binary.end()); + const std::vector next{'n', 'e', 'x', 't'}; + contract("real-local-ntfs-and-directory-flush", [&] { + storage_handle handle(CreateFileW(root.c_str(), GENERIC_WRITE | FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr)); + require(handle.get() != INVALID_HANDLE_VALUE, "open local filesystem control"); + wchar_t filesystem[32]{}; + require(GetVolumeInformationByHandleW(handle.get(), nullptr, 0, nullptr, nullptr, nullptr, + filesystem, 32) && std::wcscmp(filesystem, L"NTFS") == 0, + "contract requires a real NTFS fixture volume"); + const auto result = publication::sync_directory(root); + require(result.ok && result.error.empty(), "real directory flush failed"); + require(flushes == std::vector{true}, "directory sync must flush the actual directory handle"); + }); + contract("binary-create-private-and-ordered-barriers", [&] { + const auto path = root / fs::u8path(u8"caf\u00e9-\u65e5\U0001f512.bin"); + auto expected = names(root); + expected.insert(path.filename().wstring()); + const auto result = publication::write_file(path, binary, false); + require(result.ok && result.error.empty() && read_fixture(path) == exact, "binary no-clobber publication"); + require(flushes == std::vector({false, true}), "flush staging bytes before directory metadata"); + private_file(path); + require(names(root) == expected, "successful publication left a staging entry"); + }); + contract("no-clobber-preserves-existing-bytes-and-links", [&] { + const auto target = root / "private-marker-existing", alias = root / "existing-alias"; + write_fixture(target, "retained"); + require(CreateHardLinkW(alias.c_str(), target.c_str(), nullptr), "create old inode alias"); + const auto before = names(root); + refused(publication::write_file(target, next, false)); + require(read_fixture(target) == "retained" && read_fixture(alias) == "retained" && names(root) == before, + "no-clobber refusal changed existing data or namespace"); + }); + contract("replacement-uses-fresh-private-single-link-file", [&] { + const auto target = root / "replace-public", alias = root / "replace-public-alias"; + write_fixture(target, "old public bytes"); + make_public(target); + require(CreateHardLinkW(alias.c_str(), target.c_str(), nullptr), "create replacement alias"); + const auto before = names(root); + require(publication::write_file(target, next, true).ok, "replace existing regular file"); + require(read_fixture(target) == "next" && read_fixture(alias) == "old public bytes", + "replacement must not mutate the old file through its other name"); + private_file(target); + require(names(root) == before && flushes == std::vector({false, true}), + "replacement barriers or staging cleanup changed"); + }); + contract("replace-absent-and-empty-payload", [&] { + // A single UTF-16 code unit exercises the native rename buffer minimum. + const auto target = root / "r"; + require(publication::write_file(target, next, true).ok && read_fixture(target) == "next", + "replace=true must also publish an absent target"); + require(publication::write_file(target, {}, true).ok && read_fixture(target).empty(), + "empty replacement must remove prior bytes"); + private_file(target); + require(flushes == std::vector({false, true, false, true}), "each replacement must use both barriers"); + }); + contract("staging-flush-failure-preserves-prior-state", [&] { + const auto existing = root / "private-marker-staging-old", absent = root / "private-marker-staging-absent"; + write_fixture(existing, "prior bytes"); + const auto before = names(root); + for (const auto &target : {existing, absent}) { + reset_observation(); + pending = flush_fault::regular; + const auto result = publication::write_file(target, next, true); + refused(result); + require(fault_consumed && result.error == "file.write_bytes_durable: staging flush failed", + "staging fault must reach the real publication path"); + require(flushes == std::vector{false}, "staging failure must precede any directory flush"); + require(read_fixture(existing) == "prior bytes" && !fs::exists(absent) && names(root) == before, + "staging failure changed prior destination or leaked its temporary file"); + } + }); + contract("post-publication-flush-failure-reports-uncertainty", [&] { + const auto existing = root / "private-marker-uncertain-old", absent = root / "private-marker-uncertain-absent"; + write_fixture(existing, "prior bytes"); + for (const auto &target : {existing, absent}) { + reset_observation(); + auto expected = names(root); + expected.insert(target.filename().wstring()); + pending = flush_fault::directory; + const auto result = publication::write_file(target, next, true); + refused(result); + require(fault_consumed && result.error == "file.write_bytes_durable: publication durability uncertain", + "post-publication failure must not claim rollback or successful durability"); + require(flushes == std::vector({false, true}) && read_fixture(target) == "next", + "directory flush failure occurs after new bytes are published"); + private_file(target); + require(names(root) == expected, "uncertain publication left staging garbage or removed destination"); + } + }); + contract("explicit-directory-flush-failure", [&] { + const auto before = names(root); + pending = flush_fault::directory; + const auto result = publication::sync_directory(root); + refused(result); + require(fault_consumed && result.error == "file.sync_directory: synchronization failed" && + flushes == std::vector{true} && names(root) == before, + "explicit failed flush must report the barrier failure without namespace changes"); + }); + contract("post-publication-close-failure-still-flushes-directory", [&] { + const auto target = root / "private-marker-close-uncertain"; + auto expected = names(root); + expected.insert(target.filename().wstring()); + fail_published_close = true; + const auto result = publication::write_file(target, next, false); + refused(result); + require(close_fault_consumed && result.error == "file.write_bytes_durable: publication durability uncertain", + "published close failure must report durability uncertainty"); + require(flushes == std::vector({false, true}) && read_fixture(target) == "next", + "published close failure must still attempt the final directory barrier"); + private_file(target); + require(names(root) == expected, "close uncertainty changed the published namespace"); + }); + contract("unsupported-filesystem-fails-before-mutation", [&] { + const auto before = names(root); + const auto target = root / "private-marker-non-ntfs"; + force_non_ntfs = true; + refused(publication::write_file(target, next, false)); + refused(publication::sync_directory(root)); + require(flushes.empty() && names(root) == before, "unsupported filesystem reached writes or flushes"); + }); + contract("wrong-kind-and-final-reparse-rejected", [&] { + const auto directory = root / "private-marker-directory"; + require(entries::create_directory(directory).ok, "create directory-kind fixture"); + write_fixture(directory / "sentinel", "target retained"); + const auto link = root / "private-marker-junction"; + junction(owned, link, directory); + const auto before = names(root); + for (const auto &target : {directory, link}) { + refused(publication::write_file(target, next, false)); + refused(publication::write_file(target, next, true)); + } + refused(publication::sync_directory(link)); + const auto regular = directory / "sentinel"; + refused(publication::sync_directory(regular)); + require(read_fixture(regular) == "target retained" && names(root) == before, + "wrong-kind/reparse refusal altered its target or namespace"); + }); + contract("reparse-parent-is-not-followed", [&] { + const auto target = root / "private-marker-parent-target"; + require(entries::create_directory(target).ok, "create parent target fixture"); + const auto alias = root / "private-marker-parent-junction"; + junction(owned, alias, target); + refused(publication::write_file(alias / "injected", next, false)); + require(fs::is_empty(target), "publication followed a reparse final parent"); + }); + contract("missing-parent-and-invalid-operands", [&] { + const auto before = names(root); + const auto base = root / "private-marker-invalid"; + const std::vector invalid{ + fs::path(), fs::path(base.wstring() + L":stream"), fs::path(base.wstring() + L"."), + fs::path(base.wstring() + L" "), fs::path(base.wstring() + L"/"), + fs::path(base.wstring() + L"\\"), root / "CON", root / "NUL.txt", root / "COM1.log", + fs::path(root.wstring() + L"/./private-marker-invalid"), + fs::path(root.wstring() + L"/../private-marker-invalid"), + fs::path(L"\\\\?\\" + base.wstring()), fs::path(L"\\\\.\\NUL"), + fs::path(L"C:private-marker-invalid"), + fs::path(base.wstring() + std::wstring(1, wchar_t(0xd800))), + fs::path(base.wstring() + std::wstring(L"\0tail", 5))}; + require(invalid.size() == 16, "publication invalid-path inventory changed"); + for (const auto &path : invalid) { + refused(publication::write_file(path, next, false)); + refused(publication::write_file(path, next, true)); + refused(publication::sync_directory(path)); + } + refused(publication::write_file(root / "missing-parent" / "target", next, false)); + refused(publication::sync_directory(root / "missing-directory")); + require(flushes.empty() && names(root) == before, "invalid operand reached publication or mutated namespace"); + }); + contract("occupied-destination-preserved-on-rename-failure", [&] { + const auto target = root / "private-marker-open-destination"; + write_fixture(target, "held prior bytes"); + const auto before = names(root); + { + storage_handle held(CreateFileW(target.c_str(), GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT, nullptr)); + require(held.get() != INVALID_HANDLE_VALUE, "hold destination without delete sharing"); + refused(publication::write_file(target, next, true)); + } + require(read_fixture(target) == "held prior bytes" && names(root) == before, + "rename refusal changed destination or leaked staging entry"); + }); + contract("directory-handle-pins-publication-namespace", [&] { + const auto directory = root / "pinned-parent", moved = root / "pinned-parent-moved"; + require(entries::create_directory(directory).ok, "create namespace pin fixture"); + pin_from = directory; + pin_to = moved; + const auto target = directory / "payload"; + require(publication::write_file(target, next, false).ok, "publish through retained parent handle"); + require(pin_attempted && pin_refused && !fs::exists(moved) && read_fixture(target) == "next", + "publication parent was replaceable while its stage was being flushed"); + require(MoveFileExW(directory.c_str(), moved.c_str(), 0), "completed publication leaked parent handle"); + require(read_fixture(moved / "payload") == "next", "released parent namespace no longer points at published bytes"); + }); +} +} // namespace + +BOOL WINAPI contract_flush(HANDLE handle) { + FILE_ATTRIBUTE_TAG_INFO attributes{}; + if (!GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &attributes, sizeof(attributes))) + return FALSE; + const bool directory = (attributes.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; + flushes.push_back(directory); + if (!directory && !pin_from.empty() && !pin_attempted) { + pin_attempted = true; + pin_refused = !MoveFileExW(pin_from.c_str(), pin_to.c_str(), 0) && GetLastError() == ERROR_SHARING_VIOLATION; + } + if (pending == (directory ? flush_fault::directory : flush_fault::regular)) { + pending = flush_fault::none; + fault_consumed = true; + SetLastError(ERROR_WRITE_FAULT); + return FALSE; + } + return FlushFileBuffers(handle); +} + +BOOL WINAPI contract_volume(HANDLE handle, LPWSTR volume, DWORD volume_size, + LPDWORD serial, LPDWORD component_size, LPDWORD flags, LPWSTR filesystem, + DWORD filesystem_size) { + const BOOL result = GetVolumeInformationByHandleW(handle, volume, volume_size, serial, + component_size, flags, filesystem, filesystem_size); + if (result && force_non_ntfs && filesystem && filesystem_size >= 6) + std::wmemcpy(filesystem, L"FAT32", 6); + return result; +} + +BOOL WINAPI contract_close(HANDLE handle) { + FILE_ATTRIBUTE_TAG_INFO attributes{}; + const bool regular = GetFileType(handle) == FILE_TYPE_DISK && + GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &attributes, sizeof(attributes)) && + !(attributes.FileAttributes & FILE_ATTRIBUTE_DIRECTORY); + const BOOL closed = CloseHandle(handle); + if (closed && regular && fail_published_close) { + // Actually close our handle so a synthetic error cannot leak it. Only + // publication-header close calls are redirected, not RAII fixture cleanup. + fail_published_close = false; + close_fault_consumed = true; + SetLastError(ERROR_WRITE_FAULT); + return FALSE; + } + return closed; +} + +int main() { + try { + fixture owned; + run_contracts(owned); + require(completed == 15, "Windows publication contract inventory changed"); + std::cout << "windows-durable-publication-ok: 15 contracts; 16 invalid paths\n"; + return 0; + } catch (const std::exception &error) { + std::cerr << "windows-durable-publication: " << error.what() << '\n'; + return 1; + } +} diff --git a/tests/windows_toolchain_inputs_tests.cpp b/tests/windows_toolchain_inputs_tests.cpp index 056aa0a..f12a005 100644 --- a/tests/windows_toolchain_inputs_tests.cpp +++ b/tests/windows_toolchain_inputs_tests.cpp @@ -70,7 +70,7 @@ void closure(const fs::path &root) { write(runtime, "NIL runtime archive"); for (const auto *name : {"msvcrt.lib", "vcruntime.lib", "legacy_stdio_definitions.lib", "msvcprt.lib", "oldnames.lib"}) write(vc / name, name); - for (const auto *name : {"kernel32.lib", "ws2_32.lib", "user32.lib", "gdi32.lib", + for (const auto *name : {"kernel32.lib", "ws2_32.lib", "user32.lib", "gdi32.lib", "advapi32.lib", "ucrt.lib", "uuid.lib"}) write(sdk / name, name); write(ambient / "ambient.lib", "ambient library"); std::map directives; @@ -91,10 +91,20 @@ void closure(const fs::path &root) { auto before = identities(*files); for (const auto &file : {runtime, driver, bin / "cvtres.exe", bin / "c2.dll", bin / "1033" / "linkui.dll", vc / "msvcprt.lib", vc / "oldnames.lib", - sdk / "uuid.lib", sdk / "ws2_32.lib", ambient / "ambient.lib"}) + sdk / "uuid.lib", sdk / "ws2_32.lib", sdk / "advapi32.lib", ambient / "ambient.lib"}) check(before.count(file.string()) == 1, "closure includes runtime, transitive libs and helper tools"); check(probes[vc / "msvcprt.lib"] == 1, "default library cycles do not repeat subprocesses"); + const auto security_time = fs::last_write_time(sdk / "advapi32.lib"); + write(sdk / "advapi32.lib", "Windows security import library changed"); + fs::last_write_time(sdk / "advapi32.lib", security_time); + files = collect(); + check(files && identities(*files) != before, "security archive changes invalidate despite preserved timestamp"); + before = identities(*files); + fs::remove(sdk / "advapi32.lib"); + check(!collect(), "missing Windows security import library disables reuse"); + write(sdk / "advapi32.lib", "Windows security import library changed"); + const auto winsock_time = fs::last_write_time(sdk / "ws2_32.lib"); write(sdk / "ws2_32.lib", "Winsock import library changed"); fs::last_write_time(sdk / "ws2_32.lib", winsock_time);