From 95df7b1884457f46e863e4d2895ed5bfd24a7ba4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:59:50 +0000 Subject: [PATCH 01/10] Add a C ABI status ledger and bind OCaml only to exported symbols proven.h declares 162 functions; the qualified RefC library defines 9 of them with matching signatures, exports 2 more under conflicting signatures (proven_init, proven_is_initialized) and 7 symbols the header omits, including proven_header_codegen_main leaking through -Dmain. The eager OCaml binding declared 146 and could not load (undefined proven_deinit). bindings/c/include/proven-abi.tsv records each symbol as exported, conflict, owed or undeclared, with an idris-refc or zig-legacy backend. scripts/check-abi-ledger.sh checks it against the preprocessed header and nm of the real library, in both directions, and test-header-bridge.sh runs it with planted controls (1 accept, 6 reject, 1 not-run). The OCaml binding now binds the 7 ledger-exported symbols it declared; full-api-audit.sh enforces binding <= ledger-exported <= nm and owed disjoint from nm. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDi2XA8N9NEXSvCspMr --- .github/workflows/ocaml-ci.yml | 4 +- bindings/c/include/proven-abi.tsv | 194 +++ bindings/ocaml/lib/proven.ml | 1351 +----------------- bindings/ocaml/lib/proven_ffi.ml | 954 +------------ bindings/ocaml/scripts/full-api-audit.sh | 37 +- bindings/ocaml/test/test_proven.ml | 235 +-- docs/adr/2026-11-17-c-abi-status-ledger.adoc | 133 ++ scripts/check-abi-ledger.sh | 85 ++ scripts/test-abi-ledger.sh | 62 + scripts/test-header-bridge.sh | 13 +- 10 files changed, 580 insertions(+), 2488 deletions(-) create mode 100644 bindings/c/include/proven-abi.tsv create mode 100644 docs/adr/2026-11-17-c-abi-status-ledger.adoc create mode 100755 scripts/check-abi-ledger.sh create mode 100755 scripts/test-abi-ledger.sh diff --git a/.github/workflows/ocaml-ci.yml b/.github/workflows/ocaml-ci.yml index 0e35f052..5baaa6f9 100644 --- a/.github/workflows/ocaml-ci.yml +++ b/.github/workflows/ocaml-ci.yml @@ -22,6 +22,7 @@ on: - 'src/Proven/SafeHeader/ByteKernel.idr' - 'src/Proven/FFI/HeaderKernelMain.idr' - 'bindings/c/include/proven.h' + - 'bindings/c/include/proven-abi.tsv' - '.github/workflows/ocaml-ci.yml' pull_request: branches: [main] @@ -32,6 +33,7 @@ on: - 'src/Proven/SafeHeader/ByteKernel.idr' - 'src/Proven/FFI/HeaderKernelMain.idr' - 'bindings/c/include/proven.h' + - 'bindings/c/include/proven-abi.tsv' - '.github/workflows/ocaml-ci.yml' workflow_dispatch: concurrency: @@ -59,7 +61,7 @@ jobs: while IFS= read -r raw; do p="${raw%[.,;:)]}" case "$p" in - bindings/ocaml/*|ffi/zig/*|bindings/c/include|bindings/c/include/proven.h|.github/workflows/ocaml-ci.yml|./scripts/symbol-audit.sh|scripts/build-header-refc.sh|src/Proven/SafeHeader/ByteKernel.idr|src/Proven/FFI/HeaderKernelMain.idr) + bindings/ocaml/*|ffi/zig/*|bindings/c/include|bindings/c/include/proven.h|bindings/c/include/proven-abi.tsv|.github/workflows/ocaml-ci.yml|./scripts/symbol-audit.sh|scripts/build-header-refc.sh|src/Proven/SafeHeader/ByteKernel.idr|src/Proven/FFI/HeaderKernelMain.idr) ;; bindings/*/*) echo "::error file=.github/workflows/ocaml-ci.yml::detachability violation: $p" diff --git a/bindings/c/include/proven-abi.tsv b/bindings/c/include/proven-abi.tsv new file mode 100644 index 00000000..058a04fe --- /dev/null +++ b/bindings/c/include/proven-abi.tsv @@ -0,0 +1,194 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell +# +# libproven C ABI status ledger. One row per symbol declared in proven.h or +# exported by libproven. proven.h is the target ABI; this file says which part +# of it actually exists. Columns are tab-separated: +# +# symbol status backend note +# +# status exported in proven.h, exported, signature matches the header +# conflict exported under the header name with an incompatible signature +# owed in proven.h, not exported; an outstanding ABI obligation +# undeclared exported, absent from proven.h +# backend idris-refc computed by the compiled Idris core through RefC +# zig-legacy computed in Zig; not an Idris-verified implementation +# - no implementation +# +# Bindings may bind only `exported` rows. Checkers fail if an exported row is +# missing from the library, an owed row appears in it, or a header symbol or +# library export has no row. Move a row only together with the code change. +# +# Rows describe the qualified profile: build_standalone.zig -Dheader-refc on +# native Linux x86_64 GNU. Without -Dheader-refc, proven_header_has_crlf is +# still exported but refuses with status -99 (no Idris backend). +# Producer check: scripts/check-abi-ledger.sh (run by test-header-bridge.sh). +proven_angle_deg_to_rad owed - - +proven_angle_normalize_degrees owed - - +proven_angle_normalize_radians owed - - +proven_angle_rad_to_deg owed - - +proven_bloom_add owed - - +proven_bloom_contains owed - - +proven_bloom_create owed - - +proven_bloom_free owed - - +proven_buffer_append owed - - +proven_buffer_create owed - - +proven_buffer_free owed - - +proven_buffer_get owed - - +proven_build_info exported zig-legacy - +proven_calculator_eval owed - - +proven_callback_clear_all owed - - +proven_callback_count owed - - +proven_callback_fire owed - - +proven_callback_register owed - - +proven_callback_unregister owed - - +proven_checksum_crc32 owed - - +proven_checksum_verify_crc32 owed - - +proven_circuit_breaker_allow owed - - +proven_circuit_breaker_create owed - - +proven_circuit_breaker_failure owed - - +proven_circuit_breaker_free owed - - +proven_circuit_breaker_state owed - - +proven_circuit_breaker_success owed - - +proven_color_parse_hex owed - - +proven_color_rgb_to_hsl owed - - +proven_color_to_hex owed - - +proven_content_type_can_sniff_dangerous owed - - +proven_content_type_free owed - - +proven_content_type_is_json owed - - +proven_content_type_is_xml owed - - +proven_content_type_parse owed - - +proven_content_type_render owed - - +proven_cookie_build_delete owed - - +proven_cookie_build_set_cookie owed - - +proven_cookie_get_prefix owed - - +proven_cookie_has_injection owed - - +proven_cookie_validate_name owed - - +proven_cookie_validate_value owed - - +proven_crypto_constant_time_eq owed - - +proven_crypto_random_bytes owed - - +proven_currency_format owed - - +proven_currency_parse owed - - +proven_datetime_days_in_month owed - - +proven_datetime_format_iso8601 owed - - +proven_datetime_is_leap_year owed - - +proven_datetime_parse owed - - +proven_deinit owed - - +proven_digest_parse owed - - +proven_digest_to_string owed - - +proven_digest_verify owed - - +proven_email_is_valid owed - - +proven_ffi_abi_version exported zig-legacy - +proven_float_div owed - - +proven_float_is_finite owed - - +proven_float_is_nan owed - - +proven_float_ln owed - - +proven_float_sqrt owed - - +proven_free undeclared zig-legacy - +proven_free_string exported zig-legacy - +proven_geo_distance owed - - +proven_geo_in_bounds owed - - +proven_geo_validate owed - - +proven_get_string undeclared zig-legacy - +proven_graph_add_edge owed - - +proven_graph_create owed - - +proven_graph_free owed - - +proven_graph_has_edge owed - - +proven_header_build_csp owed - - +proven_header_build_hsts owed - - +proven_header_codegen_main undeclared idris-refc RefC program main renamed by -Dmain; not an API; should not be exported +proven_header_has_crlf exported idris-refc - +proven_header_is_dangerous owed - - +proven_header_is_valid_name owed - - +proven_header_render owed - - +proven_hex_decode owed - - +proven_hex_encode owed - - +proven_hex_free owed - - +proven_http_parse_www_authenticate owed - - +proven_http_url_decode owed - - +proven_http_url_encode owed - - +proven_init conflict zig-legacy header int32_t(void); export ?*Handle(void) +proven_is_initialized conflict zig-legacy header bool(void); export u32(?*Handle) +proven_json_get_type owed - - +proven_json_is_valid owed - - +proven_last_error undeclared zig-legacy - +proven_lru_create owed - - +proven_lru_free owed - - +proven_lru_get owed - - +proven_lru_put owed - - +proven_math_abs_safe owed - - +proven_math_add_checked owed - - +proven_math_clamp owed - - +proven_math_div owed - - +proven_math_mod owed - - +proven_math_mul_checked owed - - +proven_math_pow_checked owed - - +proven_math_sub_checked owed - - +proven_ml_clamp owed - - +proven_ml_leaky_relu owed - - +proven_ml_relu owed - - +proven_ml_sigmoid owed - - +proven_ml_softmax owed - - +proven_module_count owed - - +proven_monotonic_create owed - - +proven_monotonic_free owed - - +proven_monotonic_next owed - - +proven_network_ipv4_is_loopback owed - - +proven_network_ipv4_is_private owed - - +proven_network_parse_ipv4 owed - - +proven_password_is_common owed - - +proven_password_validate owed - - +proven_path_has_traversal exported zig-legacy - +proven_path_sanitize_filename owed - - +proven_phone_format_e164 owed - - +proven_phone_parse owed - - +proven_probability_and owed - - +proven_probability_create owed - - +proven_probability_not owed - - +proven_probability_or_exclusive owed - - +proven_process undeclared zig-legacy - +proven_process_array undeclared zig-legacy - +proven_queue_create owed - - +proven_queue_free owed - - +proven_queue_pop owed - - +proven_queue_push owed - - +proven_queue_size owed - - +proven_rate_limiter_create owed - - +proven_rate_limiter_free owed - - +proven_rate_limiter_try_acquire owed - - +proven_register_callback undeclared zig-legacy - +proven_registry_has_registry owed - - +proven_registry_parse owed - - +proven_registry_to_string owed - - +proven_retry_delay owed - - +proven_retry_should_retry owed - - +proven_state_machine_allow owed - - +proven_state_machine_create owed - - +proven_state_machine_free owed - - +proven_state_machine_state owed - - +proven_state_machine_transition owed - - +proven_string_escape_html owed - - +proven_string_escape_js owed - - +proven_string_escape_sql owed - - +proven_string_is_valid_utf8 owed - - +proven_tensor_create owed - - +proven_tensor_free owed - - +proven_tensor_get owed - - +proven_tensor_matmul owed - - +proven_tensor_set owed - - +proven_unit_convert_length owed - - +proven_unit_convert_temp owed - - +proven_url_free owed - - +proven_url_parse owed - - +proven_uuid_is_nil owed - - +proven_uuid_parse owed - - +proven_uuid_to_string owed - - +proven_uuid_v4 owed - - +proven_uuid_version owed - - +proven_version exported zig-legacy - +proven_version_compare owed - - +proven_version_free owed - - +proven_version_major exported zig-legacy - +proven_version_minor exported zig-legacy - +proven_version_parse owed - - +proven_version_patch exported zig-legacy - diff --git a/bindings/ocaml/lib/proven.ml b/bindings/ocaml/lib/proven.ml index 09cad8b3..f2142ff7 100644 --- a/bindings/ocaml/lib/proven.ml +++ b/bindings/ocaml/lib/proven.ml @@ -1,15 +1,19 @@ (* SPDX-License-Identifier: MPL-2.0 *) (* Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) *) -(** Proven: Formally verified safety primitives for OCaml. +(** Proven: safety primitives for OCaml, bound to libproven. - This library is a thin FFI wrapper around [libproven], which provides - formally verified (Idris 2) safety primitives. All computation is - performed inside the verified Idris 2 core -- this OCaml package does - data marshaling only. + This library marshals data only. It exposes exactly the libproven + functions whose C ABI status ledger row ([proven-abi.tsv] beside + [proven.h]) is [exported]. Each wrapper names its backend: - Every public function returns [option] or [result] instead of raising - exceptions. *) + - [SafeHeader.has_crlf] is computed by the compiled Idris core (RefC). + - [SafePath.has_traversal] and [Version] are computed in Zig and are not + Idris-verified implementations. + + The other [proven.h] functions are owed ABI obligations, not available + functions. Every public function returns a plain value or [option]; none + raises. *) open Ctypes module F = Proven_ffi @@ -18,7 +22,8 @@ module F = Proven_ffi (* Internal helpers *) (* ========================================================================== *) -(** Allocate a ctypes char pointer from an OCaml string. *) +(** Copy an OCaml string into a NUL-terminated buffer the caller owns. + Embedded NUL bytes are data: the length passed to C is [String.length]. *) let cstring_of_string (s : string) : char ptr = let len = String.length s in let buf = allocate_n char ~count:(len + 1) in @@ -28,74 +33,19 @@ let cstring_of_string (s : string) : char ptr = (buf +@ len) <-@ '\000'; buf -(** Read a C string (pointer + length) into an OCaml string, then free it - via [proven_free_string]. *) -let read_and_free_string (p : char ptr) (len : Unsigned.size_t) : string = - let n = Unsigned.Size_t.to_int len in - let s = Bytes.create n in - for i = 0 to n - 1 do - Bytes.set s i !@(p +@ i) - done; - F.proven_free_string p; - Bytes.to_string s - -(** Check if a status value is ok (== 0). *) -let status_ok (s : int32) : bool = - Int32.equal s F.proven_status_ok - -(** Unwrap an IntResult into [Some int64] if ok, [None] otherwise. *) -let unwrap_int_result (r : F.int_result structure) : int64 option = - if status_ok (getf r F.ir_status) then - Some (getf r F.ir_value) - else - None - (** Unwrap a BoolResult into [Some bool] if ok, [None] otherwise. *) let unwrap_bool_result (r : F.bool_result structure) : bool option = - if status_ok (getf r F.br_status) then + if Int32.equal (getf r F.br_status) F.proven_status_ok then Some (getf r F.br_value) else None -(** Unwrap a StringResult into [Some string] if ok, [None] otherwise. - The C string is freed after copying. *) -let unwrap_string_result (r : F.string_result structure) : string option = - if status_ok (getf r F.sr_status) then - let p = getf r F.sr_value in - let len = getf r F.sr_length in - if is_null p then None - else Some (read_and_free_string p len) - else - None - -(** Unwrap a FloatResult into [Some float] if ok, [None] otherwise. *) -let unwrap_float_result (r : F.float_result structure) : float option = - if status_ok (getf r F.fr_status) then - Some (getf r F.fr_value) - else - None - -(* ========================================================================== *) -(* Lifecycle *) -(* ========================================================================== *) - -module Lifecycle = struct - (** Initialize libproven. Returns [true] if initialization succeeded. *) - let init () : bool = - let rc = F.proven_init () in - Int32.equal rc 0l - - (** Deinitialize libproven. *) - let deinit () : unit = - F.proven_deinit () - - (** Check whether libproven has been initialized. *) - let is_initialized () : bool = - F.proven_is_initialized () -end +let check_span call (s : string) : bool option = + let p = cstring_of_string s in + unwrap_bool_result (call p (Unsigned.Size_t.of_int (String.length s))) (* ========================================================================== *) -(* Version *) +(* Version (zig-legacy) *) (* ========================================================================== *) module Version = struct @@ -114,1267 +64,34 @@ module Version = struct (** FFI ABI version. *) let abi_version () : int = Unsigned.UInt32.to_int (F.proven_ffi_abi_version ()) - - (** Number of modules in libproven. *) - let module_count () : int = - Unsigned.UInt32.to_int (F.proven_module_count ()) -end - -(* ========================================================================== *) -(* SafeMath *) -(* ========================================================================== *) - -module SafeMath = struct - (** Safe division. Returns [None] on division by zero. *) - let div (a : int) (b : int) : int option = - unwrap_int_result (F.proven_math_div (Int64.of_int a) (Int64.of_int b)) - |> Option.map Int64.to_int - - (** Safe modulo. Returns [None] on division by zero. *) - let modulo (a : int) (b : int) : int option = - unwrap_int_result (F.proven_math_mod (Int64.of_int a) (Int64.of_int b)) - |> Option.map Int64.to_int - - (** Checked addition. Returns [None] on overflow. *) - let add (a : int) (b : int) : int option = - unwrap_int_result (F.proven_math_add_checked (Int64.of_int a) (Int64.of_int b)) - |> Option.map Int64.to_int - - (** Checked subtraction. Returns [None] on underflow. *) - let sub (a : int) (b : int) : int option = - unwrap_int_result (F.proven_math_sub_checked (Int64.of_int a) (Int64.of_int b)) - |> Option.map Int64.to_int - - (** Checked multiplication. Returns [None] on overflow. *) - let mul (a : int) (b : int) : int option = - unwrap_int_result (F.proven_math_mul_checked (Int64.of_int a) (Int64.of_int b)) - |> Option.map Int64.to_int - - (** Safe absolute value. Handles MIN_INT correctly. *) - let abs (n : int) : int option = - unwrap_int_result (F.proven_math_abs_safe (Int64.of_int n)) - |> Option.map Int64.to_int - - (** Clamp value to range [lo, hi]. *) - let clamp ~lo ~hi (value : int) : int = - Int64.to_int (F.proven_math_clamp (Int64.of_int lo) (Int64.of_int hi) (Int64.of_int value)) - - (** Integer power with overflow checking. *) - let pow (base : int) (exp : int) : int option = - unwrap_int_result (F.proven_math_pow_checked (Int64.of_int base) (Unsigned.UInt32.of_int exp)) - |> Option.map Int64.to_int - - (** 64-bit variants for when OCaml [int] is too narrow. *) - - let div64 (a : int64) (b : int64) : int64 option = - unwrap_int_result (F.proven_math_div a b) - - let add64 (a : int64) (b : int64) : int64 option = - unwrap_int_result (F.proven_math_add_checked a b) - - let sub64 (a : int64) (b : int64) : int64 option = - unwrap_int_result (F.proven_math_sub_checked a b) - - let mul64 (a : int64) (b : int64) : int64 option = - unwrap_int_result (F.proven_math_mul_checked a b) end (* ========================================================================== *) -(* SafeString *) -(* ========================================================================== *) - -module SafeString = struct - (** Check whether a byte sequence is valid UTF-8. *) - let is_valid_utf8 (s : string) : bool = - let p = cstring_of_string s in - let r = F.proven_string_is_valid_utf8 p (Unsigned.Size_t.of_int (String.length s)) in - match unwrap_bool_result r with Some v -> v | None -> false - - (** Escape a string for SQL (single-quote doubling). *) - let escape_sql (s : string) : string option = - let p = cstring_of_string s in - unwrap_string_result (F.proven_string_escape_sql p (Unsigned.Size_t.of_int (String.length s))) - - (** Escape HTML angle brackets, ampersands and quotation marks. *) - let escape_html (s : string) : string option = - let p = cstring_of_string s in - unwrap_string_result (F.proven_string_escape_html p (Unsigned.Size_t.of_int (String.length s))) - - (** Escape a string for JavaScript (within quotes). *) - let escape_js (s : string) : string option = - let p = cstring_of_string s in - unwrap_string_result (F.proven_string_escape_js p (Unsigned.Size_t.of_int (String.length s))) -end - -(* ========================================================================== *) -(* SafePath *) +(* SafePath (zig-legacy) *) (* ========================================================================== *) module SafePath = struct - (** Check whether a path attempts directory traversal. *) - let has_traversal (s : string) : bool = - let p = cstring_of_string s in - let r = F.proven_path_has_traversal p (Unsigned.Size_t.of_int (String.length s)) in - match unwrap_bool_result r with Some v -> v | None -> true - - (** Sanitize a filename by removing dangerous characters. *) - let sanitize_filename (s : string) : string option = - let p = cstring_of_string s in - unwrap_string_result (F.proven_path_sanitize_filename p (Unsigned.Size_t.of_int (String.length s))) -end - -(* ========================================================================== *) -(* SafeCrypto *) -(* ========================================================================== *) - -module SafeCrypto = struct - (** Constant-time byte comparison (timing-safe). *) - let constant_time_eq (a : string) (b : string) : bool = - let pa = cstring_of_string a in - let pb = cstring_of_string b in - let r = F.proven_crypto_constant_time_eq - pa (Unsigned.Size_t.of_int (String.length a)) - pb (Unsigned.Size_t.of_int (String.length b)) in - match unwrap_bool_result r with Some v -> v | None -> false - - (** Fill a buffer with cryptographically secure random bytes. - Returns [None] on failure. *) - let random_bytes (n : int) : string option = - if n <= 0 then Some "" - else - let buf = allocate_n char ~count:n in - let rc = F.proven_crypto_random_bytes buf (Unsigned.Size_t.of_int n) in - if Int32.equal rc 0l then begin - let s = Bytes.create n in - for i = 0 to n - 1 do - Bytes.set s i !@(buf +@ i) - done; - Some (Bytes.to_string s) - end else - None -end - -(* ========================================================================== *) -(* SafeEmail *) -(* ========================================================================== *) - -module SafeEmail = struct - (** Check whether an email address is valid (RFC 5321 simplified). *) - let is_valid (s : string) : bool = - let p = cstring_of_string s in - let r = F.proven_email_is_valid p (Unsigned.Size_t.of_int (String.length s)) in - match unwrap_bool_result r with Some v -> v | None -> false -end - -(* ========================================================================== *) -(* SafeNetwork *) -(* ========================================================================== *) - -module SafeNetwork = struct - (** Parse an IPv4 address string. Returns the four octets on success. *) - let parse_ipv4 (s : string) : (int * int * int * int) option = - let p = cstring_of_string s in - let r = F.proven_network_parse_ipv4 p (Unsigned.Size_t.of_int (String.length s)) in - if status_ok (getf r F.ipv4r_status) then - let addr = getf r F.ipv4r_address in - let octets = getf addr F.ipv4_octets in - Some ( - Unsigned.UInt8.to_int (CArray.get octets 0), - Unsigned.UInt8.to_int (CArray.get octets 1), - Unsigned.UInt8.to_int (CArray.get octets 2), - Unsigned.UInt8.to_int (CArray.get octets 3) - ) - else - None + (** Check whether a path attempts directory traversal. Fails closed: a + library error is reported as [true]. Use {!has_traversal_result} to + distinguish errors. *) + let has_traversal_result (s : string) : bool option = + check_span F.proven_path_has_traversal s - (** Check whether an IPv4 address is in a private range (RFC 1918). *) - let ipv4_is_private (a : int) (b : int) (c : int) (d : int) : bool = - let addr = make F.ipv4_address in - let octets = getf addr F.ipv4_octets in - CArray.set octets 0 (Unsigned.UInt8.of_int a); - CArray.set octets 1 (Unsigned.UInt8.of_int b); - CArray.set octets 2 (Unsigned.UInt8.of_int c); - CArray.set octets 3 (Unsigned.UInt8.of_int d); - F.proven_network_ipv4_is_private addr - - (** Check whether an IPv4 address is loopback (127.0.0.0/8). *) - let ipv4_is_loopback (a : int) (b : int) (c : int) (d : int) : bool = - let addr = make F.ipv4_address in - let octets = getf addr F.ipv4_octets in - CArray.set octets 0 (Unsigned.UInt8.of_int a); - CArray.set octets 1 (Unsigned.UInt8.of_int b); - CArray.set octets 2 (Unsigned.UInt8.of_int c); - CArray.set octets 3 (Unsigned.UInt8.of_int d); - F.proven_network_ipv4_is_loopback addr + let has_traversal (s : string) : bool = + match has_traversal_result s with Some v -> v | None -> true end (* ========================================================================== *) -(* SafeHeader *) +(* SafeHeader (idris-refc) *) (* ========================================================================== *) module SafeHeader = struct - (** Check for CRLF injection characters in a header value. *) - let has_crlf (s : string) : bool = - let p = cstring_of_string s in - let r = F.proven_header_has_crlf p (Unsigned.Size_t.of_int (String.length s)) in - match unwrap_bool_result r with Some v -> v | None -> true - - (** Check whether a header name is valid per RFC 7230. *) - let is_valid_name (s : string) : bool = - let p = cstring_of_string s in - let r = F.proven_header_is_valid_name p (Unsigned.Size_t.of_int (String.length s)) in - match unwrap_bool_result r with Some v -> v | None -> false - - (** Check whether a header name is in the dangerous-headers list. *) - let is_dangerous (s : string) : bool = - let p = cstring_of_string s in - let r = F.proven_header_is_dangerous p (Unsigned.Size_t.of_int (String.length s)) in - match unwrap_bool_result r with Some v -> v | None -> true - - (** Render a validated header string "Name: Value". *) - let render ~name ~value : string option = - let pn = cstring_of_string name in - let pv = cstring_of_string value in - unwrap_string_result (F.proven_header_render - pn (Unsigned.Size_t.of_int (String.length name)) - pv (Unsigned.Size_t.of_int (String.length value))) - - (** Build a Content-Security-Policy header value from JSON directives. *) - let build_csp (directives_json : string) : string option = - let p = cstring_of_string directives_json in - unwrap_string_result (F.proven_header_build_csp p (Unsigned.Size_t.of_int (String.length directives_json))) - - (** Build an HSTS header value. *) - let build_hsts ~max_age ~include_subdomains ~preload : string option = - unwrap_string_result (F.proven_header_build_hsts (Int64.of_int max_age) include_subdomains preload) -end - -(* ========================================================================== *) -(* SafeCookie *) -(* ========================================================================== *) - -module SafeCookie = struct - (** Check for cookie injection characters. *) - let has_injection (s : string) : bool = - let p = cstring_of_string s in - let r = F.proven_cookie_has_injection p (Unsigned.Size_t.of_int (String.length s)) in - match unwrap_bool_result r with Some v -> v | None -> true - - (** Validate a cookie name. *) - let validate_name (s : string) : bool = - let p = cstring_of_string s in - let r = F.proven_cookie_validate_name p (Unsigned.Size_t.of_int (String.length s)) in - match unwrap_bool_result r with Some v -> v | None -> false - - (** Validate a cookie value. *) - let validate_value (s : string) : bool = - let p = cstring_of_string s in - let r = F.proven_cookie_validate_value p (Unsigned.Size_t.of_int (String.length s)) in - match unwrap_bool_result r with Some v -> v | None -> false - - (** Get cookie prefix type: 0=none, 1=__Secure-, 2=__Host-. *) - let get_prefix (s : string) : int option = - let p = cstring_of_string s in - unwrap_int_result (F.proven_cookie_get_prefix p (Unsigned.Size_t.of_int (String.length s))) - |> Option.map Int64.to_int - - (** Build a delete-cookie header value. *) - let build_delete (name : string) : string option = - let p = cstring_of_string name in - unwrap_string_result (F.proven_cookie_build_delete p (Unsigned.Size_t.of_int (String.length name))) - - (* Note: build_set_cookie requires CookieAttributes struct marshaling. - Add if needed by extending Proven_ffi with the struct definition. *) -end - -(* ========================================================================== *) -(* SafeContentType *) -(* ========================================================================== *) - -module SafeContentType = struct - (** Check whether a content type could be sniffed to something dangerous. *) - let can_sniff_dangerous (s : string) : bool = - let p = cstring_of_string s in - let r = F.proven_content_type_can_sniff_dangerous p (Unsigned.Size_t.of_int (String.length s)) in - match unwrap_bool_result r with Some v -> v | None -> true - - (** Check whether a content type is JSON. *) - let is_json ~subtype ~suffix : bool = - let ps = cstring_of_string subtype in - let pf = cstring_of_string suffix in - let r = F.proven_content_type_is_json - ps (Unsigned.Size_t.of_int (String.length subtype)) - pf (Unsigned.Size_t.of_int (String.length suffix)) in - match unwrap_bool_result r with Some v -> v | None -> false - - (** Check whether a content type is XML. *) - let is_xml ~subtype ~suffix : bool = - let ps = cstring_of_string subtype in - let pf = cstring_of_string suffix in - let r = F.proven_content_type_is_xml - ps (Unsigned.Size_t.of_int (String.length subtype)) - pf (Unsigned.Size_t.of_int (String.length suffix)) in - match unwrap_bool_result r with Some v -> v | None -> false -end - -(* ========================================================================== *) -(* SafeUUID *) -(* ========================================================================== *) - -module SafeUUID = struct - (** Generate a random UUID v4. Returns the 36-character string. *) - let v4 () : string option = - let r = F.proven_uuid_v4 () in - if status_ok (getf r F.ur_status) then - let u = getf r F.ur_uuid in - let sr = F.proven_uuid_to_string u in - unwrap_string_result sr - else - None - - (** Parse a UUID from its string representation. Returns the 36-char string - if valid, [None] otherwise. *) - let parse (s : string) : string option = - let p = cstring_of_string s in - let r = F.proven_uuid_parse p (Unsigned.Size_t.of_int (String.length s)) in - if status_ok (getf r F.ur_status) then - let u = getf r F.ur_uuid in - unwrap_string_result (F.proven_uuid_to_string u) - else - None - - (** Check whether a UUID is nil (all zeros). *) - let is_nil (s : string) : bool = - let p = cstring_of_string s in - let r = F.proven_uuid_parse p (Unsigned.Size_t.of_int (String.length s)) in - if status_ok (getf r F.ur_status) then - F.proven_uuid_is_nil (getf r F.ur_uuid) - else - false - - (** Get the UUID version number (1-8). *) - let version (s : string) : int option = - let p = cstring_of_string s in - let r = F.proven_uuid_parse p (Unsigned.Size_t.of_int (String.length s)) in - if status_ok (getf r F.ur_status) then - Some (Unsigned.UInt8.to_int (F.proven_uuid_version (getf r F.ur_uuid))) - else - None - - (** Check whether a string is a valid UUID. *) - let is_valid (s : string) : bool = - let p = cstring_of_string s in - let r = F.proven_uuid_parse p (Unsigned.Size_t.of_int (String.length s)) in - status_ok (getf r F.ur_status) -end - -(* ========================================================================== *) -(* SafeJson *) -(* ========================================================================== *) - -module SafeJson = struct - (** Check whether a string is valid JSON. *) - let is_valid (s : string) : bool = - let p = cstring_of_string s in - let r = F.proven_json_is_valid p (Unsigned.Size_t.of_int (String.length s)) in - match unwrap_bool_result r with Some v -> v | None -> false - - (** JSON value types. *) - type json_type = - | Null - | Bool - | Number - | String - | Array - | Object - | Invalid - - (** Get the root-level JSON value type. *) - let get_type (s : string) : json_type = - let p = cstring_of_string s in - let t = F.proven_json_get_type p (Unsigned.Size_t.of_int (String.length s)) in - match Int32.to_int t with - | 0 -> Null - | 1 -> Bool - | 2 -> Number - | 3 -> String - | 4 -> Array - | 5 -> Object - | _ -> Invalid -end - -(* ========================================================================== *) -(* SafeDateTime *) -(* ========================================================================== *) - -module SafeDateTime = struct - (** Parsed date-time components. *) - type t = { - year : int; - month : int; - day : int; - hour : int; - minute : int; - second : int; - nanosecond : int; - tz_offset_minutes : int; - } - - (** Parse an ISO 8601 date/time string. *) - let parse (s : string) : t option = - let p = cstring_of_string s in - let r = F.proven_datetime_parse p (Unsigned.Size_t.of_int (String.length s)) in - if status_ok (getf r F.dtr_status) then - let dt = getf r F.dtr_datetime in - Some { - year = Int32.to_int (getf dt F.dt_year); - month = Unsigned.UInt8.to_int (getf dt F.dt_month); - day = Unsigned.UInt8.to_int (getf dt F.dt_day); - hour = Unsigned.UInt8.to_int (getf dt F.dt_hour); - minute = Unsigned.UInt8.to_int (getf dt F.dt_minute); - second = Unsigned.UInt8.to_int (getf dt F.dt_second); - nanosecond = Unsigned.UInt32.to_int (getf dt F.dt_nanosecond); - tz_offset_minutes = getf dt F.dt_tz_offset_minutes; - } - else - None - - (** Format a date-time as ISO 8601. *) - let format_iso8601 (t : t) : string option = - let dt = make F.datetime in - setf dt F.dt_year (Int32.of_int t.year); - setf dt F.dt_month (Unsigned.UInt8.of_int t.month); - setf dt F.dt_day (Unsigned.UInt8.of_int t.day); - setf dt F.dt_hour (Unsigned.UInt8.of_int t.hour); - setf dt F.dt_minute (Unsigned.UInt8.of_int t.minute); - setf dt F.dt_second (Unsigned.UInt8.of_int t.second); - setf dt F.dt_nanosecond (Unsigned.UInt32.of_int t.nanosecond); - setf dt F.dt_tz_offset_minutes t.tz_offset_minutes; - unwrap_string_result (F.proven_datetime_format_iso8601 dt) - - (** Check whether a year is a leap year. *) - let is_leap_year (year : int) : bool = - F.proven_datetime_is_leap_year (Int32.of_int year) - - (** Get the number of days in a month. *) - let days_in_month ~year ~month : int = - Unsigned.UInt8.to_int (F.proven_datetime_days_in_month (Int32.of_int year) (Unsigned.UInt8.of_int month)) -end - -(* ========================================================================== *) -(* SafeFloat *) -(* ========================================================================== *) - -module SafeFloat = struct - (** Safe floating-point division. *) - let div (a : float) (b : float) : float option = - unwrap_float_result (F.proven_float_div a b) - - (** Check whether a float is finite (not NaN or Inf). *) - let is_finite (x : float) : bool = - F.proven_float_is_finite x - - (** Check whether a float is NaN. *) - let is_nan (x : float) : bool = - F.proven_float_is_nan x - - (** Safe square root (returns [None] for negative input). *) - let sqrt (x : float) : float option = - unwrap_float_result (F.proven_float_sqrt x) - - (** Safe natural logarithm (returns [None] for non-positive input). *) - let ln (x : float) : float option = - unwrap_float_result (F.proven_float_ln x) -end - -(* ========================================================================== *) -(* SafePassword *) -(* ========================================================================== *) - -module SafePassword = struct - (** Password strength levels. *) - type strength = - | Very_weak - | Weak - | Fair - | Strong - | Very_strong - - (** Password validation result. *) - type validation = { - strength : strength; - has_lowercase : bool; - has_uppercase : bool; - has_digit : bool; - has_special : bool; - length : int; - } - - (** Validate password strength. *) - let validate (s : string) : validation = - let p = cstring_of_string s in - let r = F.proven_password_validate p (Unsigned.Size_t.of_int (String.length s)) in - let str = match Int32.to_int (getf r F.pw_strength) with - | 0 -> Very_weak - | 1 -> Weak - | 2 -> Fair - | 3 -> Strong - | 4 -> Very_strong - | _ -> Very_weak - in - { - strength = str; - has_lowercase = getf r F.pw_has_lowercase; - has_uppercase = getf r F.pw_has_uppercase; - has_digit = getf r F.pw_has_digit; - has_special = getf r F.pw_has_special; - length = Unsigned.Size_t.to_int (getf r F.pw_length); - } - - (** Check whether a password is in the common-passwords list. *) - let is_common (s : string) : bool = - let p = cstring_of_string s in - F.proven_password_is_common p (Unsigned.Size_t.of_int (String.length s)) -end - -(* ========================================================================== *) -(* SafeVersion (semver) *) -(* ========================================================================== *) - -module SafeVersion = struct - (** Parse a semantic version string. Returns (major, minor, patch) on - success, or [None] on parse failure. *) - let parse (s : string) : (int * int * int) option = - let p = cstring_of_string s in - let r = F.proven_version_parse_semver p (Unsigned.Size_t.of_int (String.length s)) in - if status_ok (getf r F.vr_status) then begin - let v = getf r F.vr_version in - let major = Unsigned.UInt32.to_int (getf v F.sv_major) in - let minor = Unsigned.UInt32.to_int (getf v F.sv_minor) in - let patch = Unsigned.UInt32.to_int (getf v F.sv_patch) in - (* Free the version result (may contain prerelease string) *) - let vp = allocate F.semantic_version v in - F.proven_version_free vp; - Some (major, minor, patch) - end else - None - - (** Compare two version strings. Returns [Some n] where [n < 0] means - [a < b], [n = 0] means equal, [n > 0] means [a > b]. - Returns [None] if either string fails to parse. *) - let compare (a_str : string) (b_str : string) : int option = - let pa = cstring_of_string a_str in - let ra = F.proven_version_parse_semver pa (Unsigned.Size_t.of_int (String.length a_str)) in - if not (status_ok (getf ra F.vr_status)) then None - else begin - let pb = cstring_of_string b_str in - let rb = F.proven_version_parse_semver pb (Unsigned.Size_t.of_int (String.length b_str)) in - if not (status_ok (getf rb F.vr_status)) then begin - let vpa = allocate F.semantic_version (getf ra F.vr_version) in - F.proven_version_free vpa; - None - end else begin - let va = getf ra F.vr_version in - let vb = getf rb F.vr_version in - let result = Int32.to_int (F.proven_version_compare va vb) in - let vpa = allocate F.semantic_version va in - let vpb = allocate F.semantic_version vb in - F.proven_version_free vpa; - F.proven_version_free vpb; - Some result - end - end -end - -(* ========================================================================== *) -(* SafeGeo *) -(* ========================================================================== *) - -module SafeGeo = struct - (** Validate and normalize a geographic coordinate. - Returns [(latitude, longitude)] on success. *) - let validate ~lat ~lon : (float * float) option = - let r = F.proven_geo_validate lat lon in - if status_ok (getf r F.geor_status) then - let coord = getf r F.geor_coordinate in - Some (getf coord F.geo_latitude, getf coord F.geo_longitude) - else - None - - (** Calculate distance between two points in meters (Haversine). *) - let distance ~lat1 ~lon1 ~lat2 ~lon2 : float option = - let a = make F.geo_coordinate in - setf a F.geo_latitude lat1; - setf a F.geo_longitude lon1; - let b = make F.geo_coordinate in - setf b F.geo_latitude lat2; - setf b F.geo_longitude lon2; - unwrap_float_result (F.proven_geo_distance a b) - - (** Check whether a coordinate is within a bounding box. *) - let in_bounds ~lat ~lon ~min_lat ~max_lat ~min_lon ~max_lon : bool = - let coord = make F.geo_coordinate in - setf coord F.geo_latitude lat; - setf coord F.geo_longitude lon; - F.proven_geo_in_bounds coord min_lat max_lat min_lon max_lon -end - -(* ========================================================================== *) -(* SafeChecksum *) -(* ========================================================================== *) - -module SafeChecksum = struct - (** Calculate CRC32 of a byte string. *) - let crc32 (s : string) : int option = - let p = cstring_of_string s in - unwrap_int_result (F.proven_checksum_crc32 p (Unsigned.Size_t.of_int (String.length s))) - |> Option.map Int64.to_int - - (** Verify that CRC32 of data matches an expected value. *) - let verify_crc32 (s : string) (expected : int) : bool = - let p = cstring_of_string s in - let r = F.proven_checksum_verify_crc32 p - (Unsigned.Size_t.of_int (String.length s)) - (Unsigned.UInt32.of_int expected) in - match unwrap_bool_result r with Some v -> v | None -> false -end - -(* ========================================================================== *) -(* SafeProbability *) -(* ========================================================================== *) - -module SafeProbability = struct - (** Create a probability value, clamped to [0, 1]. *) - let create (v : float) : float = - F.proven_probability_create v - - (** Probability of independent events both occurring (a * b). *) - let both (a : float) (b : float) : float = - F.proven_probability_and a b - - (** Probability of mutually exclusive events (a + b). *) - let either_exclusive (a : float) (b : float) : float = - F.proven_probability_or_exclusive a b - - (** Complement probability (1 - p). *) - let complement (p : float) : float = - F.proven_probability_not p -end - -(* ========================================================================== *) -(* SafeCalculator *) -(* ========================================================================== *) - -module SafeCalculator = struct - (** Evaluate a mathematical expression string. *) - let eval (expr : string) : float option = - let p = cstring_of_string expr in - unwrap_float_result (F.proven_calculator_eval p (Unsigned.Size_t.of_int (String.length expr))) -end - -(* ========================================================================== *) -(* SafeHex *) -(* ========================================================================== *) + (** Check every byte of a header value for CR or LF. Fails closed: a + library error (including an unavailable Idris backend) is reported as + [true]. Use {!has_crlf_result} to distinguish errors. *) + let has_crlf_result (s : string) : bool option = + check_span F.proven_header_has_crlf s -module SafeHex = struct - (** Hex-encode bytes. [uppercase] selects A-F vs a-f. *) - let encode ?(uppercase = false) (s : string) : string option = - let p = cstring_of_string s in - unwrap_string_result (F.proven_hex_encode p (Unsigned.Size_t.of_int (String.length s)) uppercase) - - (** Hex-decode a string to bytes. *) - let decode (hex : string) : string option = - let p = cstring_of_string hex in - let r = F.proven_hex_decode p (Unsigned.Size_t.of_int (String.length hex)) in - if status_ok (getf r F.hdr_status) then begin - let data = getf r F.hdr_data in - let len = Unsigned.Size_t.to_int (getf r F.hdr_length) in - if is_null data then None - else begin - let s = Bytes.create len in - for i = 0 to len - 1 do - Bytes.set s i (Char.chr (Unsigned.UInt8.to_int !@(data +@ i))) - done; - let rp = allocate F.hex_decode_result r in - F.proven_hex_free rp; - Some (Bytes.to_string s) - end - end else - None -end - -(* ========================================================================== *) -(* SafeCurrency *) -(* ========================================================================== *) - -module SafeCurrency = struct - (** Parsed currency amount. *) - type t = { - amount_minor : int64; - currency_code : string; - decimal_places : int; - } - - (** Parse a currency string (e.g., "USD 123.45"). *) - let parse (s : string) : t option = - let p = cstring_of_string s in - let r = F.proven_currency_parse p (Unsigned.Size_t.of_int (String.length s)) in - if status_ok (getf r F.cur_status) then begin - let code_arr = getf r F.cur_currency_code in - let code = Printf.sprintf "%c%c%c" - (Char.chr (Unsigned.UInt8.to_int (CArray.get code_arr 0))) - (Char.chr (Unsigned.UInt8.to_int (CArray.get code_arr 1))) - (Char.chr (Unsigned.UInt8.to_int (CArray.get code_arr 2))) in - Some { - amount_minor = getf r F.cur_amount_minor; - currency_code = code; - decimal_places = Unsigned.UInt8.to_int (getf r F.cur_decimal_places); - } - end else - None - - (** Format a currency amount to string. *) - let format ~amount_minor ~currency_code ~decimal_places : string option = - if String.length currency_code <> 3 then None - else begin - let code = CArray.make uint8_t 3 in - CArray.set code 0 (Unsigned.UInt8.of_int (Char.code currency_code.[0])); - CArray.set code 1 (Unsigned.UInt8.of_int (Char.code currency_code.[1])); - CArray.set code 2 (Unsigned.UInt8.of_int (Char.code currency_code.[2])); - unwrap_string_result (F.proven_currency_format amount_minor code (Unsigned.UInt8.of_int decimal_places)) - end -end - -(* ========================================================================== *) -(* SafePhone *) -(* ========================================================================== *) - -module SafePhone = struct - (** Parsed phone number. *) - type t = { - country_code : int; - national_number : int64; - is_valid : bool; - } - - (** Parse a phone number to E.164 components. *) - let parse (s : string) : t option = - let p = cstring_of_string s in - let r = F.proven_phone_parse p (Unsigned.Size_t.of_int (String.length s)) in - if status_ok (getf r F.phr_status) then - Some { - country_code = Unsigned.UInt16.to_int (getf r F.phr_country_code); - national_number = Unsigned.UInt64.to_int64 (getf r F.phr_national_number); - is_valid = getf r F.phr_is_valid; - } - else - None - - (** Format a phone number as E.164 string. *) - let format_e164 ~country_code ~national_number : string option = - unwrap_string_result (F.proven_phone_format_e164 - (Unsigned.UInt16.of_int country_code) - (Unsigned.UInt64.of_int64 national_number)) -end - -(* ========================================================================== *) -(* SafeColor *) -(* ========================================================================== *) - -module SafeColor = struct - (** RGB color. *) - type rgb = { r : int; g : int; b : int } - - (** HSL color. *) - type hsl = { h : float; s : float; l : float } - - (** Parse a hex color string (#RRGGBB or #RGB). *) - let parse_hex (s : string) : rgb option = - let p = cstring_of_string s in - let r = F.proven_color_parse_hex p (Unsigned.Size_t.of_int (String.length s)) in - if status_ok (getf r F.cpr_status) then begin - let c = getf r F.cpr_color in - Some { - r = Unsigned.UInt8.to_int (getf c F.rgb_r); - g = Unsigned.UInt8.to_int (getf c F.rgb_g); - b = Unsigned.UInt8.to_int (getf c F.rgb_b); - } - end else - None - - (** Convert RGB to HSL. *) - let rgb_to_hsl (color : rgb) : hsl = - let c = make F.rgb_color in - setf c F.rgb_r (Unsigned.UInt8.of_int color.r); - setf c F.rgb_g (Unsigned.UInt8.of_int color.g); - setf c F.rgb_b (Unsigned.UInt8.of_int color.b); - let h = F.proven_color_rgb_to_hsl c in - { h = getf h F.hsl_h; s = getf h F.hsl_s; l = getf h F.hsl_l } - - (** Format RGB as hex string. *) - let to_hex (color : rgb) : string option = - let c = make F.rgb_color in - setf c F.rgb_r (Unsigned.UInt8.of_int color.r); - setf c F.rgb_g (Unsigned.UInt8.of_int color.g); - setf c F.rgb_b (Unsigned.UInt8.of_int color.b); - unwrap_string_result (F.proven_color_to_hex c) -end - -(* ========================================================================== *) -(* SafeAngle *) -(* ========================================================================== *) - -module SafeAngle = struct - (** Convert degrees to radians. *) - let deg_to_rad (degrees : float) : float = - F.proven_angle_deg_to_rad degrees - - (** Convert radians to degrees. *) - let rad_to_deg (radians : float) : float = - F.proven_angle_rad_to_deg radians - - (** Normalize angle to [0, 360) degrees. *) - let normalize_degrees (degrees : float) : float = - F.proven_angle_normalize_degrees degrees - - (** Normalize angle to [0, 2*pi) radians. *) - let normalize_radians (radians : float) : float = - F.proven_angle_normalize_radians radians -end - -(* ========================================================================== *) -(* SafeUnit *) -(* ========================================================================== *) - -module SafeUnit = struct - (** Length unit identifiers (matching libproven LengthUnit enum). *) - type length_unit = - | Meters | Kilometers | Centimeters | Millimeters - | Feet | Inches | Miles | Yards - - let length_unit_to_int = function - | Meters -> 0 | Kilometers -> 1 | Centimeters -> 2 | Millimeters -> 3 - | Feet -> 4 | Inches -> 5 | Miles -> 6 | Yards -> 7 - - (** Temperature unit identifiers (matching libproven TempUnit enum). *) - type temp_unit = Celsius | Fahrenheit | Kelvin - - let temp_unit_to_int = function - | Celsius -> 0 | Fahrenheit -> 1 | Kelvin -> 2 - - (** Convert a length value between units. *) - let convert_length ~from ~to_ (value : float) : float option = - unwrap_float_result (F.proven_unit_convert_length value - (Int32.of_int (length_unit_to_int from)) - (Int32.of_int (length_unit_to_int to_))) - - (** Convert a temperature value between units. *) - let convert_temp ~from ~to_ (value : float) : float option = - unwrap_float_result (F.proven_unit_convert_temp value - (Int32.of_int (temp_unit_to_int from)) - (Int32.of_int (temp_unit_to_int to_))) -end - -(* ========================================================================== *) -(* SafeHttp *) -(* ========================================================================== *) - -module SafeHttp = struct - (** URL-encode a string (RFC 3986 percent encoding). *) - let url_encode (s : string) : string option = - let p = cstring_of_string s in - unwrap_string_result (F.proven_http_url_encode p (Unsigned.Size_t.of_int (String.length s))) - - (** URL-decode a percent-encoded string. *) - let url_decode (s : string) : string option = - let p = cstring_of_string s in - unwrap_string_result (F.proven_http_url_decode p (Unsigned.Size_t.of_int (String.length s))) -end - -(* ========================================================================== *) -(* SafeBuffer *) -(* ========================================================================== *) - -module SafeBuffer = struct - (** Opaque buffer handle. *) - type t = F.bounded_buffer structure ptr - - (** Create a bounded buffer with the given capacity. *) - let create (capacity : int) : t option = - let r = F.proven_buffer_create (Unsigned.Size_t.of_int capacity) in - if status_ok (getf r F.bufr_status) then - let buf = getf r F.bufr_buffer in - if is_null buf then None - else Some buf - else - None - - (** Append data to the buffer. Returns [true] on success. *) - let append (buf : t) (data : string) : bool = - let p = cstring_of_string data in - let rc = F.proven_buffer_append buf p (Unsigned.Size_t.of_int (String.length data)) in - Int32.equal rc 0l - - (** Free the buffer. *) - let free (buf : t) : unit = - F.proven_buffer_free buf -end - -(* ========================================================================== *) -(* SafeRateLimiter *) -(* ========================================================================== *) - -module SafeRateLimiter = struct - (** Opaque rate limiter handle. *) - type t = F.rate_limiter structure ptr - - (** Create a token-bucket rate limiter. *) - let create ~capacity ~refill_rate : t option = - F.proven_rate_limiter_create capacity refill_rate - - (** Try to acquire [tokens] from the limiter. Returns [true] if allowed. *) - let try_acquire (rl : t) (tokens : float) : bool = - F.proven_rate_limiter_try_acquire rl tokens - - (** Free the rate limiter. *) - let free (rl : t) : unit = - F.proven_rate_limiter_free rl -end - -(* ========================================================================== *) -(* SafeCircuitBreaker *) -(* ========================================================================== *) - -module SafeCircuitBreaker = struct - (** Circuit breaker states. *) - type state = Closed | Open | Half_open - - (** Opaque circuit breaker handle. *) - type t = F.circuit_breaker structure ptr - - (** Create a circuit breaker. *) - let create ~failure_threshold ~success_threshold ~timeout_ms : t option = - F.proven_circuit_breaker_create - (Unsigned.UInt32.of_int failure_threshold) - (Unsigned.UInt32.of_int success_threshold) - (Int64.of_int timeout_ms) - - (** Check whether a request should be allowed. *) - let allow (cb : t) : bool = - F.proven_circuit_breaker_allow cb - - (** Record a successful request. *) - let success (cb : t) : unit = - F.proven_circuit_breaker_success cb - - (** Record a failed request. *) - let failure (cb : t) : unit = - F.proven_circuit_breaker_failure cb - - (** Get the current circuit breaker state. *) - let state (cb : t) : state = - match Int32.to_int (F.proven_circuit_breaker_state cb) with - | 0 -> Closed - | 1 -> Open - | 2 -> Half_open - | _ -> Open - - (** Free the circuit breaker. *) - let free (cb : t) : unit = - F.proven_circuit_breaker_free cb -end - -(* ========================================================================== *) -(* SafeRetry *) -(* ========================================================================== *) - -module SafeRetry = struct - (** Retry configuration. *) - type config = { - max_attempts : int; - base_delay_ms : int; - max_delay_ms : int; - multiplier : float; - } - - let make_config (c : config) : F.retry_config structure = - let rc = make F.retry_config in - setf rc F.rc_max_attempts (Unsigned.UInt32.of_int c.max_attempts); - setf rc F.rc_base_delay_ms (Unsigned.UInt64.of_int c.base_delay_ms); - setf rc F.rc_max_delay_ms (Unsigned.UInt64.of_int c.max_delay_ms); - setf rc F.rc_multiplier c.multiplier; - rc - - (** Calculate the delay for a given attempt number. *) - let delay (config : config) (attempt : int) : int = - Unsigned.UInt64.to_int (F.proven_retry_delay (make_config config) (Unsigned.UInt32.of_int attempt)) - - (** Check whether a retry should be attempted. *) - let should_retry (config : config) (attempt : int) : bool = - F.proven_retry_should_retry (make_config config) (Unsigned.UInt32.of_int attempt) -end - -(* ========================================================================== *) -(* SafeMonotonic *) -(* ========================================================================== *) - -module SafeMonotonic = struct - (** Opaque monotonic counter handle. *) - type t = F.monotonic_counter structure ptr - - (** Create a monotonic counter with initial value and maximum. *) - let create ~initial ~max_value : t option = - F.proven_monotonic_create - (Unsigned.UInt64.of_int initial) - (Unsigned.UInt64.of_int max_value) - - (** Get the next value from the counter. Returns [None] at overflow. *) - let next (c : t) : int64 option = - unwrap_int_result (F.proven_monotonic_next c) - - (** Free the counter. *) - let free (c : t) : unit = - F.proven_monotonic_free c -end - -(* ========================================================================== *) -(* SafeStateMachine *) -(* ========================================================================== *) - -module SafeStateMachine = struct - (** Opaque state machine handle. *) - type t = F.state_machine structure ptr - - (** Create a state machine with [state_count] states and an initial state. *) - let create ~state_count ~initial_state : t option = - F.proven_state_machine_create - (Unsigned.UInt32.of_int state_count) - (Unsigned.UInt32.of_int initial_state) - - (** Allow a transition from one state to another. Returns success. *) - let allow_transition (sm : t) ~from ~to_ : bool = - F.proven_state_machine_allow sm - (Unsigned.UInt32.of_int from) (Unsigned.UInt32.of_int to_) - - (** Try to transition to a new state. Returns [true] if the transition - was allowed and completed. *) - let transition (sm : t) ~to_ : bool = - F.proven_state_machine_transition sm (Unsigned.UInt32.of_int to_) - - (** Get the current state. *) - let current_state (sm : t) : int = - Unsigned.UInt32.to_int (F.proven_state_machine_state sm) - - (** Free the state machine. *) - let free (sm : t) : unit = - F.proven_state_machine_free sm -end - -(* ========================================================================== *) -(* SafeTensor *) -(* ========================================================================== *) - -module SafeTensor = struct - (** Opaque 2D tensor handle. *) - type t = F.tensor_2d structure ptr - - (** Create a [rows x cols] tensor (initialized to zero). *) - let create ~rows ~cols : t option = - F.proven_tensor_create - (Unsigned.Size_t.of_int rows) - (Unsigned.Size_t.of_int cols) - - (** Set a value at (row, col). Returns [true] on success. *) - let set (t : t) ~row ~col (value : float) : bool = - let rc = F.proven_tensor_set t - (Unsigned.Size_t.of_int row) - (Unsigned.Size_t.of_int col) value in - Int32.equal rc 0l - - (** Get a value at (row, col). *) - let get (t : t) ~row ~col : float option = - unwrap_float_result (F.proven_tensor_get t - (Unsigned.Size_t.of_int row) - (Unsigned.Size_t.of_int col)) - - (** Matrix multiplication. Returns [None] if dimensions are incompatible. *) - let matmul (a : t) (b : t) : t option = - F.proven_tensor_matmul a b - - (** Free the tensor. *) - let free (t : t) : unit = - F.proven_tensor_free t -end - -(* ========================================================================== *) -(* SafeMl *) -(* ========================================================================== *) - -module SafeMl = struct - (** Sigmoid activation function. *) - let sigmoid (x : float) : float = - F.proven_ml_sigmoid x - - (** ReLU activation function. *) - let relu (x : float) : float = - F.proven_ml_relu x - - (** Leaky ReLU activation function. *) - let leaky_relu ?(alpha = 0.01) (x : float) : float = - F.proven_ml_leaky_relu x alpha - - (** Clamp value to [min_val, max_val]. *) - let clamp ~min_val ~max_val (x : float) : float = - F.proven_ml_clamp x min_val max_val -end - -(* ========================================================================== *) -(* SafeLru *) -(* ========================================================================== *) - -module SafeLru = struct - (** Opaque LRU cache handle. *) - type t = F.lru_cache structure ptr - - (** Create an LRU cache with the given capacity. *) - let create (capacity : int) : t option = - F.proven_lru_create (Unsigned.Size_t.of_int capacity) - - (** Get a value by key. Returns [None] on miss. *) - let get (cache : t) (key : int) : int64 option = - unwrap_int_result (F.proven_lru_get cache (Unsigned.UInt64.of_int key)) - - (** Put a key-value pair. Returns [true] on success. *) - let put (cache : t) (key : int) (value : int64) : bool = - let rc = F.proven_lru_put cache (Unsigned.UInt64.of_int key) value in - Int32.equal rc 0l - - (** Free the cache. *) - let free (cache : t) : unit = - F.proven_lru_free cache -end - -(* ========================================================================== *) -(* SafeGraph *) -(* ========================================================================== *) - -module SafeGraph = struct - (** Opaque graph handle. *) - type t = F.graph structure ptr - - (** Create a graph with the given number of nodes. *) - let create (node_count : int) : t option = - F.proven_graph_create (Unsigned.Size_t.of_int node_count) - - (** Add a directed edge. Returns [true] on success. *) - let add_edge (g : t) ~from ~to_ : bool = - let rc = F.proven_graph_add_edge g - (Unsigned.Size_t.of_int from) - (Unsigned.Size_t.of_int to_) in - Int32.equal rc 0l - - (** Check whether a directed edge exists. *) - let has_edge (g : t) ~from ~to_ : bool = - F.proven_graph_has_edge g - (Unsigned.Size_t.of_int from) - (Unsigned.Size_t.of_int to_) - - (** Free the graph. *) - let free (g : t) : unit = - F.proven_graph_free g -end - -(* ========================================================================== *) -(* SafeQueue *) -(* ========================================================================== *) - -module SafeQueue = struct - (** Opaque bounded queue handle. *) - type t = F.bounded_queue structure ptr - - (** Create a bounded FIFO queue with the given capacity. *) - let create (capacity : int) : t option = - F.proven_queue_create (Unsigned.Size_t.of_int capacity) - - (** Push a value. Returns [true] on success, [false] if full. *) - let push (q : t) (value : int64) : bool = - F.proven_queue_push q value - - (** Pop a value. Returns [None] if empty. *) - let pop (q : t) : int64 option = - unwrap_int_result (F.proven_queue_pop q) - - (** Get current queue size. *) - let size (q : t) : int = - Unsigned.Size_t.to_int (F.proven_queue_size q) - - (** Free the queue. *) - let free (q : t) : unit = - F.proven_queue_free q -end - -(* ========================================================================== *) -(* SafeBloom *) -(* ========================================================================== *) - -module SafeBloom = struct - (** Opaque bloom filter handle. *) - type t = F.bloom_filter structure ptr - - (** Create a bloom filter. *) - let create ~expected_elements ~false_positive_rate : t option = - F.proven_bloom_create - (Unsigned.Size_t.of_int expected_elements) - false_positive_rate - - (** Add an element to the filter. *) - let add (bf : t) (s : string) : unit = - let p = cstring_of_string s in - F.proven_bloom_add bf p (Unsigned.Size_t.of_int (String.length s)) - - (** Check whether an element might be in the filter. *) - let contains (bf : t) (s : string) : bool = - let p = cstring_of_string s in - F.proven_bloom_contains bf p (Unsigned.Size_t.of_int (String.length s)) - - (** Free the bloom filter. *) - let free (bf : t) : unit = - F.proven_bloom_free bf -end - -(* ========================================================================== *) -(* Callbacks *) -(* ========================================================================== *) - -module Callbacks = struct - (** Event types that can trigger callbacks. *) - type event_type = - | Validation_failed - | Resource_acquired - | Resource_released - | Rate_limit_hit - | Circuit_state_change - | Signal_received - | Retry_attempt - | Crypto_operation - | Custom - - let event_type_to_int = function - | Validation_failed -> 1l - | Resource_acquired -> 2l - | Resource_released -> 3l - | Rate_limit_hit -> 4l - | Circuit_state_change -> 5l - | Signal_received -> 6l - | Retry_attempt -> 7l - | Crypto_operation -> 8l - | Custom -> 100l - - (** Query how many callbacks are registered for an event type. *) - let count (et : event_type) : int = - Unsigned.UInt32.to_int (F.proven_callback_count (event_type_to_int et)) - - (** Unregister all callbacks. Returns the number removed. *) - let clear_all () : int = - Unsigned.UInt32.to_int (F.proven_callback_clear_all ()) + let has_crlf (s : string) : bool = + match has_crlf_result s with Some v -> v | None -> true end diff --git a/bindings/ocaml/lib/proven_ffi.ml b/bindings/ocaml/lib/proven_ffi.ml index 1d859520..1f7df219 100644 --- a/bindings/ocaml/lib/proven_ffi.ml +++ b/bindings/ocaml/lib/proven_ffi.ml @@ -3,9 +3,12 @@ (** Low-level ctypes FFI bindings to libproven. - This module declares all C-ABI types and function bindings using - [Ctypes] and [Ctypes.Foreign]. Every function here is a direct - 1-to-1 mapping of a [proven_*] export from the shared library. + Binds only symbols whose row in the C ABI status ledger + ([bindings/c/include/proven-abi.tsv]) is [exported]: present in + libproven with the signature declared in [proven.h]. Every other + [proven.h] function is an [owed] or [conflict] row and is deliberately + not bound here; binding it eagerly would make this library fail to load. + [scripts/full-api-audit.sh] enforces this against the real library. Users should prefer the safe wrappers in {!Proven} instead. *) @@ -22,7 +25,7 @@ let lib = Dl.dlopen ~filename:"libproven.so" ~flags:[Dl.RTLD_NOW; Dl.RTLD_GLOBAL (* Enum: ProvenStatus *) (* -------------------------------------------------------------------------- *) -(** Status codes returned by most libproven functions. *) +(** Status codes returned by libproven functions. *) let proven_status_ok = 0l let proven_status_err_null_pointer = -1l let proven_status_err_invalid_arg = -2l @@ -35,16 +38,6 @@ let proven_status_err_out_of_bounds = -8l let proven_status_err_encoding = -9l let proven_status_err_alloc_failed = -10l -(* -------------------------------------------------------------------------- *) -(* Struct: IntResult { status: i32, value: i64 } *) -(* -------------------------------------------------------------------------- *) - -type int_result -let int_result : int_result structure typ = structure "IntResult" -let ir_status = field int_result "status" int32_t -let ir_value = field int_result "value" int64_t -let () = seal int_result - (* -------------------------------------------------------------------------- *) (* Struct: BoolResult { status: i32, value: bool } *) (* -------------------------------------------------------------------------- *) @@ -55,302 +48,10 @@ let br_status = field bool_result "status" int32_t let br_value = field bool_result "value" bool let () = seal bool_result -(* -------------------------------------------------------------------------- *) -(* Struct: StringResult { status: i32, value: *char, length: size_t } *) -(* -------------------------------------------------------------------------- *) - -type string_result -let string_result : string_result structure typ = structure "StringResult" -let sr_status = field string_result "status" int32_t -let sr_value = field string_result "value" (ptr char) -let sr_length = field string_result "length" size_t -let () = seal string_result - -(* -------------------------------------------------------------------------- *) -(* Struct: FloatResult { status: i32, value: f64 } *) -(* -------------------------------------------------------------------------- *) - -type float_result -let float_result : float_result structure typ = structure "FloatResult" -let fr_status = field float_result "status" int32_t -let fr_value = field float_result "value" double -let () = seal float_result - -(* -------------------------------------------------------------------------- *) -(* Struct: UUID { bytes: u8[16] } *) -(* -------------------------------------------------------------------------- *) - -type uuid -let uuid : uuid structure typ = structure "UUID" -let uuid_bytes = field uuid "bytes" (array 16 uint8_t) -let () = seal uuid - -(* -------------------------------------------------------------------------- *) -(* Struct: UUIDResult { status: i32, uuid: UUID } *) -(* -------------------------------------------------------------------------- *) - -type uuid_result -let uuid_result : uuid_result structure typ = structure "UUIDResult" -let ur_status = field uuid_result "status" int32_t -let ur_uuid = field uuid_result "uuid" uuid -let () = seal uuid_result - -(* -------------------------------------------------------------------------- *) -(* Struct: IPv4Address { octets: u8[4] } *) -(* -------------------------------------------------------------------------- *) - -type ipv4_address -let ipv4_address : ipv4_address structure typ = structure "IPv4Address" -let ipv4_octets = field ipv4_address "octets" (array 4 uint8_t) -let () = seal ipv4_address - -(* -------------------------------------------------------------------------- *) -(* Struct: IPv4Result { status: i32, address: IPv4Address } *) -(* -------------------------------------------------------------------------- *) - -type ipv4_result -let ipv4_result : ipv4_result structure typ = structure "IPv4Result" -let ipv4r_status = field ipv4_result "status" int32_t -let ipv4r_address = field ipv4_result "address" ipv4_address -let () = seal ipv4_result - -(* -------------------------------------------------------------------------- *) -(* Struct: CurrencyResult *) -(* -------------------------------------------------------------------------- *) - -type currency_result -let currency_result : currency_result structure typ = structure "CurrencyResult" -let cur_status = field currency_result "status" int32_t -let cur_amount_minor = field currency_result "amount_minor" int64_t -let cur_currency_code = field currency_result "currency_code" (array 3 uint8_t) -let cur_decimal_places = field currency_result "decimal_places" uint8_t -let () = seal currency_result - -(* -------------------------------------------------------------------------- *) -(* Struct: PhoneResult *) -(* -------------------------------------------------------------------------- *) - -type phone_result -let phone_result : phone_result structure typ = structure "PhoneResult" -let phr_status = field phone_result "status" int32_t -let phr_country_code = field phone_result "country_code" uint16_t -let phr_national_number = field phone_result "national_number" uint64_t -let phr_is_valid = field phone_result "is_valid" bool -let () = seal phone_result - -(* -------------------------------------------------------------------------- *) -(* Struct: DateTime *) -(* -------------------------------------------------------------------------- *) - -type datetime -let datetime : datetime structure typ = structure "DateTime" -let dt_year = field datetime "year" int32_t -let dt_month = field datetime "month" uint8_t -let dt_day = field datetime "day" uint8_t -let dt_hour = field datetime "hour" uint8_t -let dt_minute = field datetime "minute" uint8_t -let dt_second = field datetime "second" uint8_t -let dt_nanosecond = field datetime "nanosecond" uint32_t -let dt_tz_offset_minutes = field datetime "tz_offset_minutes" int16_t -let () = seal datetime - -(* -------------------------------------------------------------------------- *) -(* Struct: DateTimeResult *) -(* -------------------------------------------------------------------------- *) - -type datetime_result -let datetime_result : datetime_result structure typ = structure "DateTimeResult" -let dtr_status = field datetime_result "status" int32_t -let dtr_datetime = field datetime_result "datetime" datetime -let () = seal datetime_result - -(* -------------------------------------------------------------------------- *) -(* Struct: SemanticVersion *) -(* -------------------------------------------------------------------------- *) - -type semantic_version -let semantic_version : semantic_version structure typ = structure "SemanticVersion" -let sv_major = field semantic_version "major" uint32_t -let sv_minor = field semantic_version "minor" uint32_t -let sv_patch = field semantic_version "patch" uint32_t -let sv_prerelease_len = field semantic_version "prerelease_len" size_t -let sv_prerelease = field semantic_version "prerelease" (ptr char) -let () = seal semantic_version - -(* -------------------------------------------------------------------------- *) -(* Struct: VersionResult *) -(* -------------------------------------------------------------------------- *) - -type version_result -let version_result : version_result structure typ = structure "VersionResult" -let vr_status = field version_result "status" int32_t -let vr_version = field version_result "version" semantic_version -let () = seal version_result - -(* -------------------------------------------------------------------------- *) -(* Struct: GeoCoordinate *) -(* -------------------------------------------------------------------------- *) - -type geo_coordinate -let geo_coordinate : geo_coordinate structure typ = structure "GeoCoordinate" -let geo_latitude = field geo_coordinate "latitude" double -let geo_longitude = field geo_coordinate "longitude" double -let () = seal geo_coordinate - -(* -------------------------------------------------------------------------- *) -(* Struct: GeoResult *) -(* -------------------------------------------------------------------------- *) - -type geo_result -let geo_result : geo_result structure typ = structure "GeoResult" -let geor_status = field geo_result "status" int32_t -let geor_coordinate = field geo_result "coordinate" geo_coordinate -let () = seal geo_result - -(* -------------------------------------------------------------------------- *) -(* Struct: PasswordResult *) -(* -------------------------------------------------------------------------- *) - -type password_result -let password_result : password_result structure typ = structure "PasswordResult" -let pw_strength = field password_result "strength" int32_t -let pw_has_lowercase = field password_result "has_lowercase" bool -let pw_has_uppercase = field password_result "has_uppercase" bool -let pw_has_digit = field password_result "has_digit" bool -let pw_has_special = field password_result "has_special" bool -let pw_length = field password_result "length" size_t -let () = seal password_result - -(* -------------------------------------------------------------------------- *) -(* Struct: RGBColor *) -(* -------------------------------------------------------------------------- *) - -type rgb_color -let rgb_color : rgb_color structure typ = structure "RGBColor" -let rgb_r = field rgb_color "r" uint8_t -let rgb_g = field rgb_color "g" uint8_t -let rgb_b = field rgb_color "b" uint8_t -let () = seal rgb_color - -(* -------------------------------------------------------------------------- *) -(* Struct: HSLColor *) -(* -------------------------------------------------------------------------- *) - -type hsl_color -let hsl_color : hsl_color structure typ = structure "HSLColor" -let hsl_h = field hsl_color "h" double -let hsl_s = field hsl_color "s" double -let hsl_l = field hsl_color "l" double -let () = seal hsl_color - -(* -------------------------------------------------------------------------- *) -(* Struct: ColorParseResult *) -(* -------------------------------------------------------------------------- *) - -type color_parse_result -let color_parse_result : color_parse_result structure typ = structure "ColorParseResult" -let cpr_status = field color_parse_result "status" int32_t -let cpr_color = field color_parse_result "color" rgb_color -let () = seal color_parse_result - -(* -------------------------------------------------------------------------- *) -(* Struct: HexDecodeResult *) -(* -------------------------------------------------------------------------- *) - -type hex_decode_result -let hex_decode_result : hex_decode_result structure typ = structure "HexDecodeResult" -let hdr_status = field hex_decode_result "status" int32_t -let hdr_data = field hex_decode_result "data" (ptr uint8_t) -let hdr_length = field hex_decode_result "length" size_t -let () = seal hex_decode_result - -(* -------------------------------------------------------------------------- *) -(* Struct: RetryConfig *) -(* -------------------------------------------------------------------------- *) - -type retry_config -let retry_config : retry_config structure typ = structure "RetryConfig" -let rc_max_attempts = field retry_config "max_attempts" uint32_t -let rc_base_delay_ms = field retry_config "base_delay_ms" uint64_t -let rc_max_delay_ms = field retry_config "max_delay_ms" uint64_t -let rc_multiplier = field retry_config "multiplier" double -let () = seal retry_config - -(* -------------------------------------------------------------------------- *) -(* Opaque pointer types for stateful objects *) -(* -------------------------------------------------------------------------- *) - -(* Keep pointee types incomplete. Sealing an empty C struct is unsupported; - these declarations are used only behind pointers, never allocated here. *) - -(** Opaque handle for BoundedBuffer. *) -type bounded_buffer -let bounded_buffer : bounded_buffer structure typ = structure "BoundedBuffer" - -(** Opaque handle for RateLimiter. *) -type rate_limiter -let rate_limiter : rate_limiter structure typ = structure "RateLimiter" - -(** Opaque handle for CircuitBreaker. *) -type circuit_breaker -let circuit_breaker : circuit_breaker structure typ = structure "CircuitBreaker" - -(** Opaque handle for MonotonicCounter. *) -type monotonic_counter -let monotonic_counter : monotonic_counter structure typ = structure "MonotonicCounter" - -(** Opaque handle for StateMachine. *) -type state_machine -let state_machine : state_machine structure typ = structure "StateMachine" - -(** Opaque handle for Tensor2D. *) -type tensor_2d -let tensor_2d : tensor_2d structure typ = structure "Tensor2D" - -(** Opaque handle for LRUCache. *) -type lru_cache -let lru_cache : lru_cache structure typ = structure "LRUCache" - -(** Opaque handle for Graph. *) -type graph -let graph : graph structure typ = structure "Graph" - -(** Opaque handle for BoundedQueue. *) -type bounded_queue -let bounded_queue : bounded_queue structure typ = structure "BoundedQueue" - -(** Opaque handle for BloomFilter. *) -type bloom_filter -let bloom_filter : bloom_filter structure typ = structure "BloomFilter" - -(* -------------------------------------------------------------------------- *) -(* Struct: BufferResult { status: i32, buffer: *BoundedBuffer } *) -(* -------------------------------------------------------------------------- *) - -type buffer_result -let buffer_result : buffer_result structure typ = structure "BufferResult" -let bufr_status = field buffer_result "status" int32_t -let bufr_buffer = field buffer_result "buffer" (ptr bounded_buffer) -let () = seal buffer_result - (* ========================================================================== *) -(* Function bindings *) +(* Function bindings: ledger status `exported` *) (* ========================================================================== *) -(* -- Lifecycle ------------------------------------------------------------- *) - -let proven_init = - foreign ~from:lib "proven_init" - (void @-> returning int32_t) - -let proven_deinit = - foreign ~from:lib "proven_deinit" - (void @-> returning void) - -let proven_is_initialized = - foreign ~from:lib "proven_is_initialized" - (void @-> returning bool) - (* -- Memory management ----------------------------------------------------- *) let proven_free_string = @@ -375,649 +76,14 @@ let proven_ffi_abi_version = foreign ~from:lib "proven_ffi_abi_version" (void @-> returning uint32_t) -let proven_module_count = - foreign ~from:lib "proven_module_count" - (void @-> returning uint32_t) - -(* -- SafeMath -------------------------------------------------------------- *) - -let proven_math_div = - foreign ~from:lib "proven_math_div" - (int64_t @-> int64_t @-> returning int_result) - -let proven_math_mod = - foreign ~from:lib "proven_math_mod" - (int64_t @-> int64_t @-> returning int_result) - -let proven_math_add_checked = - foreign ~from:lib "proven_math_add_checked" - (int64_t @-> int64_t @-> returning int_result) - -let proven_math_sub_checked = - foreign ~from:lib "proven_math_sub_checked" - (int64_t @-> int64_t @-> returning int_result) - -let proven_math_mul_checked = - foreign ~from:lib "proven_math_mul_checked" - (int64_t @-> int64_t @-> returning int_result) - -let proven_math_abs_safe = - foreign ~from:lib "proven_math_abs_safe" - (int64_t @-> returning int_result) - -let proven_math_clamp = - foreign ~from:lib "proven_math_clamp" - (int64_t @-> int64_t @-> int64_t @-> returning int64_t) - -let proven_math_pow_checked = - foreign ~from:lib "proven_math_pow_checked" - (int64_t @-> uint32_t @-> returning int_result) - -(* -- SafeString ------------------------------------------------------------ *) - -let proven_string_is_valid_utf8 = - foreign ~from:lib "proven_string_is_valid_utf8" - (ptr char @-> size_t @-> returning bool_result) - -let proven_string_escape_sql = - foreign ~from:lib "proven_string_escape_sql" - (ptr char @-> size_t @-> returning string_result) - -let proven_string_escape_html = - foreign ~from:lib "proven_string_escape_html" - (ptr char @-> size_t @-> returning string_result) - -let proven_string_escape_js = - foreign ~from:lib "proven_string_escape_js" - (ptr char @-> size_t @-> returning string_result) - -(* -- SafePath -------------------------------------------------------------- *) +(* -- SafePath (zig-legacy backend) ----------------------------------------- *) let proven_path_has_traversal = foreign ~from:lib "proven_path_has_traversal" (ptr char @-> size_t @-> returning bool_result) -let proven_path_sanitize_filename = - foreign ~from:lib "proven_path_sanitize_filename" - (ptr char @-> size_t @-> returning string_result) - -(* -- SafeCrypto ------------------------------------------------------------ *) - -let proven_crypto_constant_time_eq = - foreign ~from:lib "proven_crypto_constant_time_eq" - (ptr char @-> size_t @-> ptr char @-> size_t @-> returning bool_result) - -let proven_crypto_random_bytes = - foreign ~from:lib "proven_crypto_random_bytes" - (ptr char @-> size_t @-> returning int32_t) - -(* -- SafeUrl --------------------------------------------------------------- *) - -(* Note: URL parsing uses a complex struct; we wrap only the simpler - helpers at this level. Full URL parsing is available through the - proven_url_parse / proven_url_free pair if needed. *) - -(* -- SafeEmail ------------------------------------------------------------- *) - -let proven_email_is_valid = - foreign ~from:lib "proven_email_is_valid" - (ptr char @-> size_t @-> returning bool_result) - -(* -- SafeNetwork ----------------------------------------------------------- *) - -let proven_network_parse_ipv4 = - foreign ~from:lib "proven_network_parse_ipv4" - (ptr char @-> size_t @-> returning ipv4_result) - -let proven_network_ipv4_is_private = - foreign ~from:lib "proven_network_ipv4_is_private" - (ipv4_address @-> returning bool) - -let proven_network_ipv4_is_loopback = - foreign ~from:lib "proven_network_ipv4_is_loopback" - (ipv4_address @-> returning bool) - -(* -- SafeHeader ------------------------------------------------------------ *) +(* -- SafeHeader (idris-refc backend) --------------------------------------- *) let proven_header_has_crlf = foreign ~from:lib "proven_header_has_crlf" (ptr char @-> size_t @-> returning bool_result) - -let proven_header_is_valid_name = - foreign ~from:lib "proven_header_is_valid_name" - (ptr char @-> size_t @-> returning bool_result) - -let proven_header_is_dangerous = - foreign ~from:lib "proven_header_is_dangerous" - (ptr char @-> size_t @-> returning bool_result) - -let proven_header_render = - foreign ~from:lib "proven_header_render" - (ptr char @-> size_t @-> ptr char @-> size_t @-> returning string_result) - -let proven_header_build_csp = - foreign ~from:lib "proven_header_build_csp" - (ptr char @-> size_t @-> returning string_result) - -let proven_header_build_hsts = - foreign ~from:lib "proven_header_build_hsts" - (int64_t @-> bool @-> bool @-> returning string_result) - -(* -- SafeCookie ------------------------------------------------------------ *) - -let proven_cookie_has_injection = - foreign ~from:lib "proven_cookie_has_injection" - (ptr char @-> size_t @-> returning bool_result) - -let proven_cookie_validate_name = - foreign ~from:lib "proven_cookie_validate_name" - (ptr char @-> size_t @-> returning bool_result) - -let proven_cookie_validate_value = - foreign ~from:lib "proven_cookie_validate_value" - (ptr char @-> size_t @-> returning bool_result) - -let proven_cookie_get_prefix = - foreign ~from:lib "proven_cookie_get_prefix" - (ptr char @-> size_t @-> returning int_result) - -let proven_cookie_build_delete = - foreign ~from:lib "proven_cookie_build_delete" - (ptr char @-> size_t @-> returning string_result) - -(* -- SafeContentType ------------------------------------------------------- *) - -let proven_content_type_can_sniff_dangerous = - foreign ~from:lib "proven_content_type_can_sniff_dangerous" - (ptr char @-> size_t @-> returning bool_result) - -let proven_content_type_is_json = - foreign ~from:lib "proven_content_type_is_json" - (ptr char @-> size_t @-> ptr char @-> size_t @-> returning bool_result) - -let proven_content_type_is_xml = - foreign ~from:lib "proven_content_type_is_xml" - (ptr char @-> size_t @-> ptr char @-> size_t @-> returning bool_result) - -(* -- SafeUUID -------------------------------------------------------------- *) - -let proven_uuid_v4 = - foreign ~from:lib "proven_uuid_v4" - (void @-> returning uuid_result) - -let proven_uuid_to_string = - foreign ~from:lib "proven_uuid_to_string" - (uuid @-> returning string_result) - -let proven_uuid_parse = - foreign ~from:lib "proven_uuid_parse" - (ptr char @-> size_t @-> returning uuid_result) - -let proven_uuid_is_nil = - foreign ~from:lib "proven_uuid_is_nil" - (uuid @-> returning bool) - -let proven_uuid_version = - foreign ~from:lib "proven_uuid_version" - (uuid @-> returning uint8_t) - -(* -- SafeJson -------------------------------------------------------------- *) - -let proven_json_is_valid = - foreign ~from:lib "proven_json_is_valid" - (ptr char @-> size_t @-> returning bool_result) - -let proven_json_get_type = - foreign ~from:lib "proven_json_get_type" - (ptr char @-> size_t @-> returning int32_t) - -(* -- SafeDateTime ---------------------------------------------------------- *) - -let proven_datetime_parse = - foreign ~from:lib "proven_datetime_parse" - (ptr char @-> size_t @-> returning datetime_result) - -let proven_datetime_format_iso8601 = - foreign ~from:lib "proven_datetime_format_iso8601" - (datetime @-> returning string_result) - -let proven_datetime_is_leap_year = - foreign ~from:lib "proven_datetime_is_leap_year" - (int32_t @-> returning bool) - -let proven_datetime_days_in_month = - foreign ~from:lib "proven_datetime_days_in_month" - (int32_t @-> uint8_t @-> returning uint8_t) - -(* -- SafeFloat ------------------------------------------------------------- *) - -let proven_float_div = - foreign ~from:lib "proven_float_div" - (double @-> double @-> returning float_result) - -let proven_float_is_finite = - foreign ~from:lib "proven_float_is_finite" - (double @-> returning bool) - -let proven_float_is_nan = - foreign ~from:lib "proven_float_is_nan" - (double @-> returning bool) - -let proven_float_sqrt = - foreign ~from:lib "proven_float_sqrt" - (double @-> returning float_result) - -let proven_float_ln = - foreign ~from:lib "proven_float_ln" - (double @-> returning float_result) - -(* -- SafePassword ---------------------------------------------------------- *) - -let proven_password_validate = - foreign ~from:lib "proven_password_validate" - (ptr char @-> size_t @-> returning password_result) - -let proven_password_is_common = - foreign ~from:lib "proven_password_is_common" - (ptr char @-> size_t @-> returning bool) - -(* -- SafeVersion ----------------------------------------------------------- *) - -let proven_version_parse_semver = - foreign ~from:lib "proven_version_parse" - (ptr char @-> size_t @-> returning version_result) - -let proven_version_compare = - foreign ~from:lib "proven_version_compare" - (semantic_version @-> semantic_version @-> returning int32_t) - -let proven_version_free = - foreign ~from:lib "proven_version_free" - (ptr semantic_version @-> returning void) - -(* -- SafeGeo --------------------------------------------------------------- *) - -let proven_geo_validate = - foreign ~from:lib "proven_geo_validate" - (double @-> double @-> returning geo_result) - -let proven_geo_distance = - foreign ~from:lib "proven_geo_distance" - (geo_coordinate @-> geo_coordinate @-> returning float_result) - -let proven_geo_in_bounds = - foreign ~from:lib "proven_geo_in_bounds" - (geo_coordinate @-> double @-> double @-> double @-> double @-> returning bool) - -(* -- SafeChecksum ---------------------------------------------------------- *) - -let proven_checksum_crc32 = - foreign ~from:lib "proven_checksum_crc32" - (ptr char @-> size_t @-> returning int_result) - -let proven_checksum_verify_crc32 = - foreign ~from:lib "proven_checksum_verify_crc32" - (ptr char @-> size_t @-> uint32_t @-> returning bool_result) - -(* -- SafeProbability ------------------------------------------------------- *) - -let proven_probability_create = - foreign ~from:lib "proven_probability_create" - (double @-> returning double) - -let proven_probability_and = - foreign ~from:lib "proven_probability_and" - (double @-> double @-> returning double) - -let proven_probability_or_exclusive = - foreign ~from:lib "proven_probability_or_exclusive" - (double @-> double @-> returning double) - -let proven_probability_not = - foreign ~from:lib "proven_probability_not" - (double @-> returning double) - -(* -- SafeCalculator -------------------------------------------------------- *) - -let proven_calculator_eval = - foreign ~from:lib "proven_calculator_eval" - (ptr char @-> size_t @-> returning float_result) - -(* -- SafeHex --------------------------------------------------------------- *) - -let proven_hex_encode = - foreign ~from:lib "proven_hex_encode" - (ptr char @-> size_t @-> bool @-> returning string_result) - -let proven_hex_decode = - foreign ~from:lib "proven_hex_decode" - (ptr char @-> size_t @-> returning hex_decode_result) - -let proven_hex_free = - foreign ~from:lib "proven_hex_free" - (ptr hex_decode_result @-> returning void) - -(* -- SafeCurrency ---------------------------------------------------------- *) - -let proven_currency_parse = - foreign ~from:lib "proven_currency_parse" - (ptr char @-> size_t @-> returning currency_result) - -let proven_currency_format = - foreign ~from:lib "proven_currency_format" - (int64_t @-> array 3 uint8_t @-> uint8_t @-> returning string_result) - -(* -- SafePhone ------------------------------------------------------------- *) - -let proven_phone_parse = - foreign ~from:lib "proven_phone_parse" - (ptr char @-> size_t @-> returning phone_result) - -let proven_phone_format_e164 = - foreign ~from:lib "proven_phone_format_e164" - (uint16_t @-> uint64_t @-> returning string_result) - -(* -- SafeColor ------------------------------------------------------------- *) - -let proven_color_parse_hex = - foreign ~from:lib "proven_color_parse_hex" - (ptr char @-> size_t @-> returning color_parse_result) - -let proven_color_rgb_to_hsl = - foreign ~from:lib "proven_color_rgb_to_hsl" - (rgb_color @-> returning hsl_color) - -let proven_color_to_hex = - foreign ~from:lib "proven_color_to_hex" - (rgb_color @-> returning string_result) - -(* -- SafeAngle ------------------------------------------------------------- *) - -let proven_angle_deg_to_rad = - foreign ~from:lib "proven_angle_deg_to_rad" - (double @-> returning double) - -let proven_angle_rad_to_deg = - foreign ~from:lib "proven_angle_rad_to_deg" - (double @-> returning double) - -let proven_angle_normalize_degrees = - foreign ~from:lib "proven_angle_normalize_degrees" - (double @-> returning double) - -let proven_angle_normalize_radians = - foreign ~from:lib "proven_angle_normalize_radians" - (double @-> returning double) - -(* -- SafeUnit -------------------------------------------------------------- *) - -let proven_unit_convert_length = - foreign ~from:lib "proven_unit_convert_length" - (double @-> int32_t @-> int32_t @-> returning float_result) - -let proven_unit_convert_temp = - foreign ~from:lib "proven_unit_convert_temp" - (double @-> int32_t @-> int32_t @-> returning float_result) - -(* -- SafeHttp -------------------------------------------------------------- *) - -let proven_http_url_encode = - foreign ~from:lib "proven_http_url_encode" - (ptr char @-> size_t @-> returning string_result) - -let proven_http_url_decode = - foreign ~from:lib "proven_http_url_decode" - (ptr char @-> size_t @-> returning string_result) - -(* -- SafeBuffer ------------------------------------------------------------ *) - -let proven_buffer_create = - foreign ~from:lib "proven_buffer_create" - (size_t @-> returning buffer_result) - -let proven_buffer_append = - foreign ~from:lib "proven_buffer_append" - (ptr bounded_buffer @-> ptr char @-> size_t @-> returning int32_t) - -let proven_buffer_get = - foreign ~from:lib "proven_buffer_get" - (ptr bounded_buffer @-> ptr (ptr char) @-> ptr size_t @-> returning int32_t) - -let proven_buffer_free = - foreign ~from:lib "proven_buffer_free" - (ptr bounded_buffer @-> returning void) - -(* -- SafeRateLimiter ------------------------------------------------------- *) - -let proven_rate_limiter_create = - foreign ~from:lib "proven_rate_limiter_create" - (double @-> double @-> returning (ptr_opt rate_limiter)) - -let proven_rate_limiter_try_acquire = - foreign ~from:lib "proven_rate_limiter_try_acquire" - (ptr rate_limiter @-> double @-> returning bool) - -let proven_rate_limiter_free = - foreign ~from:lib "proven_rate_limiter_free" - (ptr rate_limiter @-> returning void) - -(* -- SafeCircuitBreaker ---------------------------------------------------- *) - -let proven_circuit_breaker_create = - foreign ~from:lib "proven_circuit_breaker_create" - (uint32_t @-> uint32_t @-> int64_t @-> returning (ptr_opt circuit_breaker)) - -let proven_circuit_breaker_allow = - foreign ~from:lib "proven_circuit_breaker_allow" - (ptr circuit_breaker @-> returning bool) - -let proven_circuit_breaker_success = - foreign ~from:lib "proven_circuit_breaker_success" - (ptr circuit_breaker @-> returning void) - -let proven_circuit_breaker_failure = - foreign ~from:lib "proven_circuit_breaker_failure" - (ptr circuit_breaker @-> returning void) - -let proven_circuit_breaker_state = - foreign ~from:lib "proven_circuit_breaker_state" - (ptr circuit_breaker @-> returning int32_t) - -let proven_circuit_breaker_free = - foreign ~from:lib "proven_circuit_breaker_free" - (ptr circuit_breaker @-> returning void) - -(* -- SafeRetry ------------------------------------------------------------- *) - -let proven_retry_delay = - foreign ~from:lib "proven_retry_delay" - (retry_config @-> uint32_t @-> returning uint64_t) - -let proven_retry_should_retry = - foreign ~from:lib "proven_retry_should_retry" - (retry_config @-> uint32_t @-> returning bool) - -(* -- SafeMonotonic --------------------------------------------------------- *) - -let proven_monotonic_create = - foreign ~from:lib "proven_monotonic_create" - (uint64_t @-> uint64_t @-> returning (ptr_opt monotonic_counter)) - -let proven_monotonic_next = - foreign ~from:lib "proven_monotonic_next" - (ptr monotonic_counter @-> returning int_result) - -let proven_monotonic_free = - foreign ~from:lib "proven_monotonic_free" - (ptr monotonic_counter @-> returning void) - -(* -- SafeStateMachine ------------------------------------------------------ *) - -let proven_state_machine_create = - foreign ~from:lib "proven_state_machine_create" - (uint32_t @-> uint32_t @-> returning (ptr_opt state_machine)) - -let proven_state_machine_allow = - foreign ~from:lib "proven_state_machine_allow" - (ptr state_machine @-> uint32_t @-> uint32_t @-> returning bool) - -let proven_state_machine_transition = - foreign ~from:lib "proven_state_machine_transition" - (ptr state_machine @-> uint32_t @-> returning bool) - -let proven_state_machine_state = - foreign ~from:lib "proven_state_machine_state" - (ptr state_machine @-> returning uint32_t) - -let proven_state_machine_free = - foreign ~from:lib "proven_state_machine_free" - (ptr state_machine @-> returning void) - -(* -- SafeTensor ------------------------------------------------------------ *) - -let proven_tensor_create = - foreign ~from:lib "proven_tensor_create" - (size_t @-> size_t @-> returning (ptr_opt tensor_2d)) - -let proven_tensor_set = - foreign ~from:lib "proven_tensor_set" - (ptr tensor_2d @-> size_t @-> size_t @-> double @-> returning int32_t) - -let proven_tensor_get = - foreign ~from:lib "proven_tensor_get" - (ptr tensor_2d @-> size_t @-> size_t @-> returning float_result) - -let proven_tensor_matmul = - foreign ~from:lib "proven_tensor_matmul" - (ptr tensor_2d @-> ptr tensor_2d @-> returning (ptr_opt tensor_2d)) - -let proven_tensor_free = - foreign ~from:lib "proven_tensor_free" - (ptr tensor_2d @-> returning void) - -(* -- SafeML ---------------------------------------------------------------- *) - -let proven_ml_sigmoid = - foreign ~from:lib "proven_ml_sigmoid" - (double @-> returning double) - -let proven_ml_relu = - foreign ~from:lib "proven_ml_relu" - (double @-> returning double) - -let proven_ml_leaky_relu = - foreign ~from:lib "proven_ml_leaky_relu" - (double @-> double @-> returning double) - -let proven_ml_clamp = - foreign ~from:lib "proven_ml_clamp" - (double @-> double @-> double @-> returning double) - -(* -- SafeLRU --------------------------------------------------------------- *) - -let proven_lru_create = - foreign ~from:lib "proven_lru_create" - (size_t @-> returning (ptr_opt lru_cache)) - -let proven_lru_get = - foreign ~from:lib "proven_lru_get" - (ptr lru_cache @-> uint64_t @-> returning int_result) - -let proven_lru_put = - foreign ~from:lib "proven_lru_put" - (ptr lru_cache @-> uint64_t @-> int64_t @-> returning int32_t) - -let proven_lru_free = - foreign ~from:lib "proven_lru_free" - (ptr lru_cache @-> returning void) - -(* -- SafeGraph ------------------------------------------------------------- *) - -let proven_graph_create = - foreign ~from:lib "proven_graph_create" - (size_t @-> returning (ptr_opt graph)) - -let proven_graph_add_edge = - foreign ~from:lib "proven_graph_add_edge" - (ptr graph @-> size_t @-> size_t @-> returning int32_t) - -let proven_graph_has_edge = - foreign ~from:lib "proven_graph_has_edge" - (ptr graph @-> size_t @-> size_t @-> returning bool) - -let proven_graph_free = - foreign ~from:lib "proven_graph_free" - (ptr graph @-> returning void) - -(* -- SafeQueue ------------------------------------------------------------- *) - -let proven_queue_create = - foreign ~from:lib "proven_queue_create" - (size_t @-> returning (ptr_opt bounded_queue)) - -let proven_queue_push = - foreign ~from:lib "proven_queue_push" - (ptr bounded_queue @-> int64_t @-> returning bool) - -let proven_queue_pop = - foreign ~from:lib "proven_queue_pop" - (ptr bounded_queue @-> returning int_result) - -let proven_queue_size = - foreign ~from:lib "proven_queue_size" - (ptr bounded_queue @-> returning size_t) - -let proven_queue_free = - foreign ~from:lib "proven_queue_free" - (ptr bounded_queue @-> returning void) - -(* -- SafeBloom ------------------------------------------------------------- *) - -let proven_bloom_create = - foreign ~from:lib "proven_bloom_create" - (size_t @-> double @-> returning (ptr_opt bloom_filter)) - -let proven_bloom_add = - foreign ~from:lib "proven_bloom_add" - (ptr bloom_filter @-> ptr char @-> size_t @-> returning void) - -let proven_bloom_contains = - foreign ~from:lib "proven_bloom_contains" - (ptr bloom_filter @-> ptr char @-> size_t @-> returning bool) - -let proven_bloom_free = - foreign ~from:lib "proven_bloom_free" - (ptr bloom_filter @-> returning void) - -(* -- Callbacks ------------------------------------------------------------- *) - -let proven_callback_register = - foreign ~from:lib "proven_callback_register" - (int32_t @-> ptr void @-> ptr_opt void @-> returning uint32_t) - -let proven_callback_unregister = - foreign ~from:lib "proven_callback_unregister" - (uint32_t @-> returning int32_t) - -let proven_callback_fire = - foreign ~from:lib "proven_callback_fire" - (int32_t @-> ptr_opt char @-> size_t @-> int32_t @-> returning int32_t) - -let proven_callback_count = - foreign ~from:lib "proven_callback_count" - (int32_t @-> returning uint32_t) - -let proven_callback_clear_all = - foreign ~from:lib "proven_callback_clear_all" - (void @-> returning uint32_t) - -(* -- SafeRegistry ---------------------------------------------------------- *) - -(* Note: Registry and Digest use complex structs with internal pointers. - We provide the simpler interfaces here; full parsing can be added - by extending the struct definitions above. *) - -(* -- SafeDigest ------------------------------------------------------------ *) - -(* Digest structs with internal pointers require careful lifetime management. - Basic operations are exposed via the string-based API through SafeHex. *) diff --git a/bindings/ocaml/scripts/full-api-audit.sh b/bindings/ocaml/scripts/full-api-audit.sh index 6efc7dc1..11241759 100644 --- a/bindings/ocaml/scripts/full-api-audit.sh +++ b/bindings/ocaml/scripts/full-api-audit.sh @@ -1,28 +1,47 @@ #!/usr/bin/env bash # SPDX-License-Identifier: MPL-2.0 # Copyright (c) 2026 Jonathan D.A. Jewell +# +# Full-API audit for the eager OCaml binding against the C ABI status ledger +# (proven-abi.tsv beside proven.h) and a real libproven.so. +# +# Fails when the binding binds a symbol that is not a ledger `exported` row, +# a bound symbol is absent from the library, a ledger `exported` row is +# absent from the library, or a ledger `owed` row is present in it (the +# ledger is stale and must be reclassified together with the code). +# Presence alone does not prove a C signature, ownership contract or Idris +# implementation; full_api_probe stays as the load test. set -euo pipefail unset CDPATH root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) : "${PROVEN_LIB_PATH:?directory containing the actual libproven.so required}" +include=${PROVEN_INCLUDE_PATH:-"$root/../c/include"} library="$PROVEN_LIB_PATH/libproven.so" +ledger="$include/proven-abi.tsv" test -s "$library" +test -s "$ledger" out="$root/_build/full-api-audit" mkdir -p "$out" echo INCOMPLETE > "$out/result.txt" trap 'status=$?; if ((status)); then echo FAIL > "$out/result.txt"; fi' EXIT -# This inventory is distinct from the five-symbol qualified wired manifest. -# Every eagerly bound symbol must exist. Presence alone does not prove a C -# signature, ownership contract, or Idris implementation; full_api_probe stays. sed -nE 's/.*foreign ~from:lib "([^"]+)".*/\1/p' "$root/lib/proven_ffi.ml" | sort -u > "$out/required.txt" test -s "$out/required.txt" +grep -vE '^(#|[[:space:]]*$)' "$ledger" | awk -F'\t' '$2 == "exported" { print $1 }' | sort -u > "$out/ledger-exported.txt" +grep -vE '^(#|[[:space:]]*$)' "$ledger" | awk -F'\t' '$2 == "owed" { print $1 }' | sort -u > "$out/ledger-owed.txt" +test -s "$out/ledger-exported.txt" nm -D --defined-only "$library" | awk '$2 ~ /^[TW]$/ {print $3}' | sort -u > "$out/exported.txt" +comm -23 "$out/required.txt" "$out/ledger-exported.txt" > "$out/bound-not-ledger-exported.txt" comm -23 "$out/required.txt" "$out/exported.txt" > "$out/missing.txt" +comm -23 "$out/ledger-exported.txt" "$out/exported.txt" > "$out/ledger-exported-missing.txt" +comm -12 "$out/ledger-owed.txt" "$out/exported.txt" > "$out/owed-present.txt" comm -12 "$out/required.txt" "$out/exported.txt" > "$out/present.txt" -sha256sum "$root/lib/proven_ffi.ml" "$library" > "$out/identity.sha256" -printf 'Required=%s Present=%s Missing=%s\n' "$(wc -l < "$out/required.txt")" \ - "$(wc -l < "$out/present.txt")" "$(wc -l < "$out/missing.txt")" | tee "$out/summary.txt" -if [[ -s "$out/missing.txt" ]]; then - cat "$out/missing.txt"; exit 1 -fi +sha256sum "$root/lib/proven_ffi.ml" "$ledger" "$library" > "$out/identity.sha256" +printf 'Required=%s Present=%s Missing=%s LedgerExported=%s LedgerOwed=%s\n' \ + "$(wc -l < "$out/required.txt")" "$(wc -l < "$out/present.txt")" "$(wc -l < "$out/missing.txt")" \ + "$(wc -l < "$out/ledger-exported.txt")" "$(wc -l < "$out/ledger-owed.txt")" | tee "$out/summary.txt" +fail=0 +for f in bound-not-ledger-exported missing ledger-exported-missing owed-present; do + if [[ -s "$out/$f.txt" ]]; then echo "FAIL: $f"; sed 's/^/ /' "$out/$f.txt"; fail=1; fi +done +((fail == 0)) echo PASS > "$out/result.txt" diff --git a/bindings/ocaml/test/test_proven.ml b/bindings/ocaml/test/test_proven.ml index 9c5c6984..36cff516 100644 --- a/bindings/ocaml/test/test_proven.ml +++ b/bindings/ocaml/test/test_proven.ml @@ -4,75 +4,9 @@ (** Tests for the Proven OCaml FFI bindings. These tests call through to libproven via ctypes. They require - [libproven.so] to be loadable at runtime (e.g., via LD_LIBRARY_PATH). *) - -(* -------------------------------------------------------------------------- *) -(* Test helpers *) -(* -------------------------------------------------------------------------- *) - -let option_int = Alcotest.(option int) -let option_string = Alcotest.(option string) -let option_float = Alcotest.(option (float 1e-6)) - -(* -------------------------------------------------------------------------- *) -(* Lifecycle *) -(* -------------------------------------------------------------------------- *) - -let test_init () = - let ok = Proven.Lifecycle.init () in - Alcotest.(check bool) "init succeeds" true ok; - Alcotest.(check bool) "is_initialized" true (Proven.Lifecycle.is_initialized ()) - -(* -------------------------------------------------------------------------- *) -(* SafeMath *) -(* -------------------------------------------------------------------------- *) - -let test_math_div () = - Alcotest.(check option_int) "10/2=5" (Some 5) (Proven.SafeMath.div 10 2); - Alcotest.(check option_int) "10/0=None" None (Proven.SafeMath.div 10 0) - -let test_math_mod () = - Alcotest.(check option_int) "10%3=1" (Some 1) (Proven.SafeMath.modulo 10 3); - Alcotest.(check option_int) "10%0=None" None (Proven.SafeMath.modulo 10 0) - -let test_math_add () = - Alcotest.(check option_int) "1+2=3" (Some 3) (Proven.SafeMath.add 1 2) - -let test_math_sub () = - Alcotest.(check option_int) "5-3=2" (Some 2) (Proven.SafeMath.sub 5 3) - -let test_math_mul () = - Alcotest.(check option_int) "3*4=12" (Some 12) (Proven.SafeMath.mul 3 4) - -let test_math_abs () = - Alcotest.(check option_int) "abs(-7)=7" (Some 7) (Proven.SafeMath.abs (-7)); - Alcotest.(check option_int) "abs(0)=0" (Some 0) (Proven.SafeMath.abs 0) - -let test_math_clamp () = - Alcotest.(check int) "clamp 5 [0,10]" 5 (Proven.SafeMath.clamp ~lo:0 ~hi:10 5); - Alcotest.(check int) "clamp -1 [0,10]" 0 (Proven.SafeMath.clamp ~lo:0 ~hi:10 (-1)); - Alcotest.(check int) "clamp 20 [0,10]" 10 (Proven.SafeMath.clamp ~lo:0 ~hi:10 20) - -let test_math_pow () = - Alcotest.(check option_int) "2^10=1024" (Some 1024) (Proven.SafeMath.pow 2 10) - -(* -------------------------------------------------------------------------- *) -(* SafeString *) -(* -------------------------------------------------------------------------- *) - -let test_string_escape_html () = - Alcotest.(check option_string) "escape <" - (Some "<script>") - (Proven.SafeString.escape_html "") = False - -||| OWED: Event handlers are removed -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_eventHandlersRemoved_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_eventHandlersRemoved : containsEventHandler (sanitizeHtml "
text
") = False - -||| OWED: Escaped output doesn't contain raw HTML -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_escapeNoRawHtml_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_escapeNoRawHtml : (s : String) -> containsRawHtml (escapeHtml s) = False - -||| OWED: Escape is idempotent -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_escapeIdempotent_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_escapeIdempotent : (s : String) -> escapeHtml (escapeHtml s) = escapeHtml s - -||| Property: Less-than is escaped -prop_ltEscaped : escapeHtml "<" = "<" +-- Real API: `escapeHtmlContent : String -> String`, the total sanitisers +-- `sanitizeStandard`/`sanitizeStrict : String -> String` (documented as a +-- simplified implementation: strip every tag, then escape), `sanitizeUrl`, +-- `sanitizeAttrValue`, and the policy predicates `isTagAllowed`, +-- `isAttrAllowed`, `isDangerousAttr`, `isBlacklistedTag`. There is no +-- `sanitizeHtml` returning a Result. `Proven.SafeString.Escape` is imported +-- so that `escapeHtmlContent = escapeHTML` unfolds at the type level. +-- +-- The original `prop_escapeIdempotent` (escape (escape s) = escape s) is +-- false for any HTML escaper: escape "&" = "&" but escape "&" = +-- "&amp;". It is replaced by an execution check of that counterexample. + +-------------------------------------------------------------------------------- +-- Type-level proofs +-------------------------------------------------------------------------------- + +||| Less-than is escaped. +prop_ltEscaped : escapeHtmlContent "<" = "<" prop_ltEscaped = Refl -||| Property: Greater-than is escaped -prop_gtEscaped : escapeHtml ">" = ">" +||| Greater-than is escaped. +prop_gtEscaped : escapeHtmlContent ">" = ">" prop_gtEscaped = Refl -||| Property: Ampersand is escaped -prop_ampEscaped : escapeHtml "&" = "&" +||| Ampersand is escaped. +prop_ampEscaped : escapeHtmlContent "&" = "&" prop_ampEscaped = Refl -||| Property: Quote is escaped -prop_quoteEscaped : escapeHtml "\"" = """ +||| Double quote is escaped. +prop_quoteEscaped : escapeHtmlContent "\"" = """ prop_quoteEscaped = Refl -||| Property: Safe tags are preserved -prop_safeTagsPreserved : isOk (sanitizeHtml "

paragraph

") = True -prop_safeTagsPreserved = Refl +||| A whole script tag is neutralised by escaping. +prop_scriptEscaped : escapeHtmlContent "" + , "
text
" + , "link" + , "" + , "<" == "alert('xss')") + check "event-handler attribute removed with its tag" + (sanitizeStandard "
text
" == "text") + check "javascript: link removed, link text kept" + (sanitizeStandard "link" == "link") + check "sanitised attack corpus has no raw < > \" and no dangerous tag" + (all (\s => noRaw (sanitizeStandard s) && + not (isInfixOf " \" (corpus)" + (all (noRaw . escapeHtmlContent) attackCorpus) + check "escaping is not idempotent (double escape of < is &lt;)" + (escapeHtmlContent (escapeHtmlContent "<") == "&lt;") + check "safe paragraph text preserved" (sanitizeStandard "

paragraph

" == "paragraph") + check "safe href attribute value preserved, event handler refused" + (sanitizeAttrValue "a" "href" "https://example.com" == Just "https://example.com" && + sanitizeAttrValue "div" "onclick" "evil()" == Nothing && + sanitizeAttrValue "a" "href" "javascript:alert(1)" == Nothing) putStrLn "" diff --git a/tests/properties/SafeJWTProps.idr b/tests/properties/SafeJWTProps.idr index 0ea0d6cc..244e6ff7 100644 --- a/tests/properties/SafeJWTProps.idr +++ b/tests/properties/SafeJWTProps.idr @@ -4,76 +4,85 @@ module SafeJWTProps import Proven.Core import Proven.SafeJWT +import System %default total -||| OWED: Valid JWT structure parses -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_validJWTParses_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_validJWTParses : isOk (parseJWT "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.sig") = True +-- The real API: token splitting (`splitToken`, total), creation +-- (`createToken`/`createHS256Token`, total; signing is a stub), and the +-- validation pipeline (`validateAlgorithm`, `validateExp`, `validateNbf`, +-- `validateDecoded`, `validate`, all total over a `DecodedJWT`). The +-- string-level entry points `decode`, `decodeClaims`, `verifyJWT`, +-- `validateToken` are `covering`, so this total module cannot call them; the +-- properties are therefore stated on the total layers they delegate to. +-- There is no `parseJWT`, `createJWT`, `validateJWT` or `getClaims`. -||| OWED: Invalid JWT structure fails -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_invalidJWTFails_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_invalidJWTFails : isErr (parseJWT "not.a.jwt.token") = True +||| Property: the 'none' algorithm is rejected by the default validation +||| pipeline, for every current time, header fields, claims and signature, +||| and hence by `validate` for every key. +prop_noneAlgRejected : (t : Integer) -> (key : SigningKey) -> + (raw : String) -> (typ, cty, kid, x5u, x5t, x5tS : Maybe String) -> + (claims : JWTClaims) -> (sig : List Bits8) -> (hs, ps : String) -> + validate Types.defaultValidation key t + (MkDecodedJWT raw (MkJWTHeader None typ cty kid x5u x5t x5tS) + claims sig hs ps) + = Err AlgorithmNoneNotAllowed +prop_noneAlgRejected t key raw typ cty kid x5u x5t x5tS claims sig hs ps = Refl -||| Property: JWT with missing parts fails -prop_missingPartsFails : isErr (parseJWT "header.payload") = True -prop_missingPartsFails = Refl +||| Property: whenever `isExpired` holds, `validateExp` fails, for every time, +||| clock skew and claim set. +prop_expiredRejected : (t : Integer) -> (skew : ClockSkew) -> (c : JWTClaims) -> + isExpired t skew c = True -> isOk (validateExp t skew c) = False +prop_expiredRejected t skew (MkJWTClaims _ _ _ Nothing _ _ _ _) prf = absurd prf +prop_expiredRejected t skew (MkJWTClaims _ _ _ (Just e) _ _ _ _) prf = rewrite prf in Refl -||| Property: None algorithm rejected -prop_noneAlgRejected : isErr (verifyJWT "eyJhbGciOiJub25lIn0.eyJzdWIiOiIxIn0." "secret") = True -prop_noneAlgRejected = Refl +||| Property: whenever `isNotYetValid` holds, `validateNbf` fails, for every +||| time, clock skew and claim set. +prop_nbfFutureRejected : (t : Integer) -> (skew : ClockSkew) -> (c : JWTClaims) -> + isNotYetValid t skew c = True -> isOk (validateNbf t skew c) = False +prop_nbfFutureRejected t skew (MkJWTClaims _ _ _ _ Nothing _ _ _) prf = absurd prf +prop_nbfFutureRejected t skew (MkJWTClaims _ _ _ _ (Just n) _ _ _) prf = rewrite prf in Refl -||| OWED: Expired JWT rejected -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_expiredRejected_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_expiredRejected : (jwt : JWT) -> isExpired jwt = True -> - isErr (validateJWT jwt) = True +||| Property: HS256 token creation succeeds for every secret and claim set +prop_hs256Supported : (secret : List Bits8) -> (claims : JWTClaims) -> + isOk (createToken (minimalHeader HS256) claims (SecretKey secret)) = True +prop_hs256Supported secret claims = Refl -||| OWED: Not-before future JWT rejected -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_nbfFutureRejected_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_nbfFutureRejected : (jwt : JWT) -> nbfInFuture jwt = True -> - isErr (validateJWT jwt) = True +||| Property: HS384 token creation succeeds for every secret and claim set +prop_hs384Supported : (secret : List Bits8) -> (claims : JWTClaims) -> + isOk (createToken (minimalHeader HS384) claims (SecretKey secret)) = True +prop_hs384Supported secret claims = Refl -||| Property: Signature verification deterministic -prop_verifyDeterministic : (token, secret : String) -> - verifyJWT token secret = verifyJWT token secret -prop_verifyDeterministic token secret = Refl +||| Property: HS512 token creation succeeds for every secret and claim set +prop_hs512Supported : (secret : List Bits8) -> (claims : JWTClaims) -> + isOk (createToken (minimalHeader HS512) claims (SecretKey secret)) = True +prop_hs512Supported secret claims = Refl -||| Property: HS256 algorithm supported -prop_hs256Supported : isOk (createJWT HS256 "secret" [("sub", "user")]) = True -prop_hs256Supported = Refl +-- The orphan's `prop_verifyDeterministic` (`verifyJWT t s = verifyJWT t s`) +-- holds by Refl for any function and says nothing; it is replaced by +-- `prop_noneAlgRejected` above, a real statement about the pipeline. -||| Property: HS384 algorithm supported -prop_hs384Supported : isOk (createJWT HS384 "secret" [("sub", "user")]) = True -prop_hs384Supported = Refl +||| OWED: claims survive a create/decode round trip, for `decode = +||| decodeClaims`. Blocked by: `decodeClaims` (and the JSON claim parser it +||| uses) is `covering`, so this total module can neither run nor mention it, +||| hence the family over the decoder; encoding and base64 also run over +||| `unpack`. This names the proposition; it is not a witness. +public export +ClaimsRoundTripObligation : (String -> Result JWTError JWTClaims) -> Type +ClaimsRoundTripObligation decode = + (secret : String) -> (claims : JWTClaims) -> (tok : String) -> + createHS256Token secret claims = Ok tok -> decode tok = Ok claims -||| Property: HS512 algorithm supported -prop_hs512Supported : isOk (createJWT HS512 "secret" [("sub", "user")]) = True -prop_hs512Supported = Refl +private +check : String -> Bool -> IO () +check label True = putStrLn ("PASS (execution): " ++ label) +check label False = do + putStrLn ("FAIL: " ++ label) + exitFailure -||| OWED: Claims are preserved in roundtrip -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_claimsPreserved_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_claimsPreserved : (claims : List (String, String)) -> (secret : String) -> - getClaims (createJWT HS256 secret claims) = claims +private +subUser : JWTClaims +subUser = { sub := Just "user" } emptyClaims ||| Test runner for JWT properties export @@ -81,10 +90,37 @@ runJWTProperties : IO () runJWTProperties = do putStrLn "SafeJWT Property Tests" putStrLn "======================" - putStrLn "prop_missingPartsFails: PASS (proven by type)" - putStrLn "prop_noneAlgRejected: PASS (proven by type)" - putStrLn "prop_verifyDeterministic: PASS (proven by type)" - putStrLn "prop_hs256Supported: PASS (proven by type)" - putStrLn "prop_hs384Supported: PASS (proven by type)" - putStrLn "prop_hs512Supported: PASS (proven by type)" + putStrLn "prop_noneAlgRejected: PASS (proven by type, all tokens/keys/times)" + putStrLn "prop_expiredRejected: PASS (proven by type, all claims/times)" + putStrLn "prop_nbfFutureRejected: PASS (proven by type, all claims/times)" + putStrLn "prop_hs256Supported: PASS (proven by type, all secrets/claims)" + putStrLn "prop_hs384Supported: PASS (proven by type, all secrets/claims)" + putStrLn "prop_hs512Supported: PASS (proven by type, all secrets/claims)" + check "valid three-part JWT structure splits" + (case splitToken "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.sig" of + Ok segs => segs.header == "eyJhbGciOiJIUzI1NiJ9" && + segs.payload == "eyJzdWIiOiIxIn0" && segs.signature == "sig" + Err _ => False) + check "four-part string rejected" + (isErr (splitToken "not.a.jwt.token")) + check "unsecured JWT (empty signature segment) splits" + (isOk (splitToken "eyJhbGciOiJub25lIn0.eyJzdWIiOiIxIn0.")) + check "created HS256 token has three segments and the encoded claims" + (case createHS256Token "secret" subUser of + Ok tok => case splitToken tok of + Ok segs => case base64UrlDecodeString segs.payload of + Ok json => json == "{\"sub\":\"user\"}" + Err _ => False + Err _ => False + Err _ => False) + check "concrete expiry: no exp accepted, exp 1000 rejected at t=2000 (default skew)" + (isOk (validateExp 2000 defaultClockSkew subUser) && + isErr (validateExp 2000 defaultClockSkew ({ exp := Just 1000 } subUser))) + check "concrete nbf: nbf 5000 rejected at t=1000, accepted at t=5000" + (isErr (validateNbf 1000 defaultClockSkew ({ nbf := Just 5000 } subUser)) && + isOk (validateNbf 5000 defaultClockSkew ({ nbf := Just 5000 } subUser))) + -- Kept last: compact serialisation (RFC 7515 s7.1 / RFC 7519 s6.1) always + -- has three segments; a FAIL here is a suspected library defect. + check "two-part string (missing signature segment) rejected" + (isErr (splitToken "header.payload")) putStrLn "" diff --git a/tests/properties/SafeJsonProps.idr b/tests/properties/SafeJsonProps.idr index b2b51034..29ecdec0 100644 --- a/tests/properties/SafeJsonProps.idr +++ b/tests/properties/SafeJsonProps.idr @@ -4,44 +4,113 @@ module SafeJsonProps import Proven.Core import Proven.SafeJson +import System %default total -||| Property: Parsing valid JSON returns Ok -prop_validJsonParses : parseJson "{}" = Ok (JsonObject []) +-- The real API: `parseJson : String -> Maybe JsonValue` (literal fast paths +-- for null/true/false/""/[]/{}, otherwise the full `parse` state machine), +-- `parse : String -> Either ParseError JsonValue`, `get` for object lookup, +-- `at` for array indexing. There is no `stringify`; `show` renders JSON. + +||| Property: parsing "{}" yields the empty object (holds via parseJson's +||| literal dispatch; the full parser is exercised at runtime below). +prop_validJsonParses : parseJson "{}" = Just (JsonObject []) prop_validJsonParses = Refl -||| Property: Parsing empty string fails -prop_emptyStringFails : isErr (parseJson "") = True +||| Property: parsing the empty string fails +prop_emptyStringFails : parseJson "" = Nothing prop_emptyStringFails = Refl -||| Property: JSON null is a valid value -prop_nullIsValid : parseJson "null" = Ok JsonNull +||| Property: JSON null parses +prop_nullIsValid : parseJson "null" = Just JsonNull prop_nullIsValid = Refl -||| Property: JSON boolean true parses correctly -prop_trueParses : parseJson "true" = Ok (JsonBool True) +||| Property: JSON true parses +prop_trueParses : parseJson "true" = Just (JsonBool True) prop_trueParses = Refl -||| Property: JSON boolean false parses correctly -prop_falseParses : parseJson "false" = Ok (JsonBool False) +||| Property: JSON false parses +prop_falseParses : parseJson "false" = Just (JsonBool False) prop_falseParses = Refl -||| Property: Getting from empty object returns Nothing -prop_emptyObjectGet : get "key" (JsonObject []) = Nothing -prop_emptyObjectGet = Refl +||| Property: getting any key from the empty object returns Nothing +prop_emptyObjectGet : (k : String) -> get k (JsonObject []) = Nothing +prop_emptyObjectGet k = Refl + +||| Property: any index into the empty array returns Nothing +prop_arrayOutOfBounds : (n : Nat) -> at n (JsonArray []) = Nothing +prop_arrayOutOfBounds n = Refl + +||| OWED: render/parse round trip for JsonNull, stated against the full +||| parser (`parse`, not `parseJson`'s literal fast path) on "null", the +||| rendering both `Show JsonValue` instances produce for JsonNull. +||| Blocked by: `parse` runs the module-private, fuel-indexed `parseValue` +||| over `unpack s`, which does not reduce at the type level. A general +||| `parse (render v) = Right v` cannot even be stated against the library: +||| there is no `stringify`, and `show` is ambiguous (two `Show JsonValue` +||| instances, in Proven.SafeJson.Parser and Proven.SafeJson). This names the +||| proposition; it is not a witness. +public export +NullRoundTripObligation : Type +NullRoundTripObligation = parse "null" = Right JsonNull + +||| OWED: the `parseJson` literal fast paths agree with the full parser. +||| Blocked by: same non-reduction of `parse` as above. This names the +||| proposition; it is not a witness. +public export +FastPathAgreesObligation : Type +FastPathAgreesObligation = + (s : String) -> (v : JsonValue) -> parseJson s = Just v -> parse s = Right v + +-- Total structural equality (the library's `Eq JsonValue` is only `covering`). +mutual + private + jsonEq : JsonValue -> JsonValue -> Bool + jsonEq JsonNull JsonNull = True + jsonEq (JsonBool a) (JsonBool b) = a == b + jsonEq (JsonNumber a) (JsonNumber b) = a == b + jsonEq (JsonString a) (JsonString b) = a == b + jsonEq (JsonArray a) (JsonArray b) = listEq a b + jsonEq (JsonObject a) (JsonObject b) = pairsEq a b + jsonEq _ _ = False + + private + listEq : List JsonValue -> List JsonValue -> Bool + listEq [] [] = True + listEq (x :: xs) (y :: ys) = jsonEq x y && listEq xs ys + listEq _ _ = False + + private + pairsEq : List (String, JsonValue) -> List (String, JsonValue) -> Bool + pairsEq [] [] = True + pairsEq ((k, x) :: xs) ((l, y) :: ys) = k == l && jsonEq x y && pairsEq xs ys + pairsEq _ _ = False + +private +maybeEq : Maybe JsonValue -> Maybe JsonValue -> Bool +maybeEq Nothing Nothing = True +maybeEq (Just a) (Just b) = jsonEq a b +maybeEq _ _ = False + +private +check : String -> Bool -> IO () +check label True = putStrLn ("PASS (execution): " ++ label) +check label False = do + putStrLn ("FAIL: " ++ label) + exitFailure -||| Property: Array index out of bounds returns Nothing -prop_arrayOutOfBounds : getIndex 10 (JsonArray []) = Nothing -prop_arrayOutOfBounds = Refl +private +parsesTo : String -> JsonValue -> Bool +parsesTo s v = case parse s of + Right v' => jsonEq v' v + Left _ => False -||| OWED: Stringify then parse roundtrip for simple values -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_roundTripNull_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_roundTripNull : parseJson (stringify JsonNull) = Ok JsonNull +private +rejects : String -> Bool +rejects s = case parse s of + Right _ => False + Left _ => True ||| Test runner for JSON properties export @@ -54,6 +123,35 @@ runJsonProperties = do putStrLn "prop_nullIsValid: PASS (proven by type)" putStrLn "prop_trueParses: PASS (proven by type)" putStrLn "prop_falseParses: PASS (proven by type)" - putStrLn "prop_emptyObjectGet: PASS (proven by type)" - putStrLn "prop_arrayOutOfBounds: PASS (proven by type)" + putStrLn "prop_emptyObjectGet: PASS (proven by type, all keys)" + putStrLn "prop_arrayOutOfBounds: PASS (proven by type, all indices)" + -- The literal fast paths above bypass the real parser; check it directly. + check "full parser: {} / [] / null / true / false" + (parsesTo "{}" (JsonObject []) && parsesTo "[]" (JsonArray []) && + parsesTo "null" JsonNull && parsesTo "true" (JsonBool True) && + parsesTo "false" (JsonBool False)) + check "full parser: empty and whitespace-only input rejected" + (rejects "" && rejects " ") + check "full parser: whitespace-padded and nested values" + (parsesTo " { \"a\" : [1, true, null] } " + (JsonObject [("a", JsonArray [JsonNumber 1.0, JsonBool True, JsonNull])])) + check "full parser: trailing content and malformed input rejected" + (rejects "{} x" && rejects "{\"a\" 1}" && rejects "tru" && rejects "[1 2]") + check "get finds a present key and misses an absent one" + (maybeEq (get "k" (JsonObject [("k", JsonNull)])) (Just JsonNull) && + maybeEq (get "z" (JsonObject [("k", JsonNull)])) Nothing) + check "at: in-bounds index hits, out-of-bounds misses" + (maybeEq (at 0 (JsonArray [JsonBool True])) (Just (JsonBool True)) && + maybeEq (at 10 (JsonArray [JsonBool True])) Nothing) + check "full parser on \"null\" (instance of NullRoundTripObligation)" + (parsesTo "null" JsonNull) + check "fast paths agree with full parser (instances of FastPathAgreesObligation)" + (all (\t => case parseJson t of + Just v => parsesTo t v + Nothing => rejects t) + ["null", "true", "false", "", "[]", "{}"]) + -- RFC 8259 grammar has no trailing commas. Kept last so the other checks + -- above still report; a FAIL here is a suspected parser defect. + check "full parser: trailing commas rejected (RFC 8259)" + (rejects "[1,]" && rejects "{\"a\":1,}") putStrLn "" diff --git a/tests/properties/SafeNetworkProps.idr b/tests/properties/SafeNetworkProps.idr index 500f8d07..7cbcf77e 100644 --- a/tests/properties/SafeNetworkProps.idr +++ b/tests/properties/SafeNetworkProps.idr @@ -4,73 +4,100 @@ module SafeNetworkProps import Proven.Core import Proven.SafeNetwork +import Data.Maybe +import System %default total -||| Property: Valid IPv4 parses -prop_validIPv4 : isOk (parseIPv4 "192.168.1.1") = True -prop_validIPv4 = Refl +-- The real API is Maybe-returning: `parseIPv4`, `parseIPv6`, `parseCIDR` +-- (prefix validated by `mkPrefix`) and `mkPort : Nat -> Maybe Port`. +-- `isPrivateIP` takes the `IPAddress` union, so IPv4 values are wrapped +-- with `IPv4Addr`. The parsers go through `split`/`unpack`/`parsePositive` +-- on String, which do not reduce at the type level, so the parse +-- properties are execution checks in `runNetworkProperties`. -||| Property: Invalid IPv4 fails -prop_invalidIPv4 : isErr (parseIPv4 "256.1.1.1") = True -prop_invalidIPv4 = Refl - -||| Property: Localhost IPv4 parses -prop_localhost : isOk (parseIPv4 "127.0.0.1") = True -prop_localhost = Refl - -||| Property: Valid IPv6 parses -prop_validIPv6 : isOk (parseIPv6 "::1") = True -prop_validIPv6 = Refl - -||| Property: Valid CIDR parses -prop_validCIDR : isOk (parseCIDR "192.168.0.0/24") = True -prop_validCIDR = Refl - -||| Property: Invalid CIDR prefix fails -prop_invalidCIDRPrefix : isErr (parseCIDR "192.168.0.0/33") = True -prop_invalidCIDRPrefix = Refl - -||| Property: Valid port in range -prop_validPort : isOk (validatePort 8080) = True +||| Property: a port in range is accepted +prop_validPort : map (\p => portValue p) (mkPort 8080) = Just 8080 prop_validPort = Refl -||| Property: Port zero is valid -prop_portZero : isOk (validatePort 0) = True +||| Property: port zero is accepted +prop_portZero : map (\p => portValue p) (mkPort 0) = Just 0 prop_portZero = Refl -||| Property: Port max is valid (65535) -prop_portMax : isOk (validatePort 65535) = True +||| Property: the maximum port 65535 is accepted +prop_portMax : map (\p => portValue p) (mkPort 65535) = Just 65535 prop_portMax = Refl -||| Property: Port over max fails -prop_portOverMax : isErr (validatePort 65536) = True +||| Property: 65536 is rejected +prop_portOverMax : isJust (mkPort 65536) = False prop_portOverMax = Refl -||| Property: Private IP detection -prop_privateIP : isPrivateIP (MkIPv4 192 168 1 1) = True +||| Property: private IP detection (RFC 1918, 192.168.0.0/16) +prop_privateIP : isPrivateIP (IPv4Addr (MkIPv4 192 168 1 1)) = True prop_privateIP = Refl -||| Property: Public IP detection -prop_publicIP : isPrivateIP (MkIPv4 8 8 8 8) = False +||| Property: 8.8.8.8 is not private +prop_publicIP : isPrivateIP (IPv4Addr (MkIPv4 8 8 8 8)) = False prop_publicIP = Refl +||| Property: every address in 10.0.0.0/8 is private +prop_tenSlashEightPrivate : (b, c, d : Bits8) -> + isPrivateIP (IPv4Addr (MkIPv4 10 b c d)) = True +prop_tenSlashEightPrivate b c d = Refl + +||| Property: every address in 192.168.0.0/16 is private +prop_192168Private : (c, d : Bits8) -> + isPrivateIP (IPv4Addr (MkIPv4 192 168 c d)) = True +prop_192168Private c d = Refl + +||| Property: mkPrefix rejects 33 (CIDR prefix bound) +prop_prefix33Rejected : isJust (mkPrefix 33) = False +prop_prefix33Rejected = Refl + +||| Property: mkPrefix accepts 24 +prop_prefix24Accepted : map (\p => prefixValue p) (mkPrefix 24) = Just 24 +prop_prefix24Accepted = Refl + +private +check : String -> Bool -> IO () +check label True = putStrLn ("PASS (execution): " ++ label) +check label False = do + putStrLn ("FAIL: " ++ label) + exitFailure + ||| Test runner for network properties export runNetworkProperties : IO () runNetworkProperties = do putStrLn "SafeNetwork Property Tests" putStrLn "==========================" - putStrLn "prop_validIPv4: PASS (proven by type)" - putStrLn "prop_invalidIPv4: PASS (proven by type)" - putStrLn "prop_localhost: PASS (proven by type)" - putStrLn "prop_validIPv6: PASS (proven by type)" - putStrLn "prop_validCIDR: PASS (proven by type)" - putStrLn "prop_invalidCIDRPrefix: PASS (proven by type)" putStrLn "prop_validPort: PASS (proven by type)" putStrLn "prop_portZero: PASS (proven by type)" putStrLn "prop_portMax: PASS (proven by type)" putStrLn "prop_portOverMax: PASS (proven by type)" putStrLn "prop_privateIP: PASS (proven by type)" putStrLn "prop_publicIP: PASS (proven by type)" + putStrLn "prop_tenSlashEightPrivate: PASS (proven by type, all addresses)" + putStrLn "prop_192168Private: PASS (proven by type, all addresses)" + putStrLn "prop_prefix33Rejected: PASS (proven by type)" + putStrLn "prop_prefix24Accepted: PASS (proven by type)" + check "valid IPv4 192.168.1.1 parses to its octets" + (parseIPv4 "192.168.1.1" == Just (MkIPv4 192 168 1 1)) + check "invalid IPv4 256.1.1.1 rejected" + (isNothing (parseIPv4 "256.1.1.1")) + check "malformed IPv4 rejected (too few/many octets, empty, letters)" + (isNothing (parseIPv4 "1.2.3") && isNothing (parseIPv4 "1.2.3.4.5") && + isNothing (parseIPv4 "") && isNothing (parseIPv4 "a.b.c.d")) + check "localhost 127.0.0.1 parses to localhost" + (parseIPv4 "127.0.0.1" == Just localhost) + check "IPv6 ::1 parses to the loopback address" + (map isLoopbackIPv6 (parseIPv6 "::1") == Just True) + check "valid CIDR 192.168.0.0/24 parses with prefix 24" + (map (prefixValue . pfxLen) (parseCIDR "192.168.0.0/24") == Just 24) + check "CIDR prefix /33 rejected" + (isNothing (parseCIDR "192.168.0.0/33")) + check "parsePort agrees with mkPort at the boundaries" + (map portValue (parsePort "8080") == Just 8080 && + map portValue (parsePort "65535") == Just 65535 && + isNothing (parsePort "65536")) putStrLn "" diff --git a/tests/properties/SafePasswordProps.idr b/tests/properties/SafePasswordProps.idr index a686a162..96ad2668 100644 --- a/tests/properties/SafePasswordProps.idr +++ b/tests/properties/SafePasswordProps.idr @@ -4,69 +4,77 @@ module SafePasswordProps import Proven.Core import Proven.SafePassword +import Data.List +import System %default total -||| Property: Strong password validates -prop_strongPasswordValid : isOk (validatePassword "Str0ng!Pass#2024") = True -prop_strongPasswordValid = Refl +-- The real API: `validatePassword : (policy : PasswordPolicy) -> RawPassword +-- -> Either (List PolicyViolation) (ValidPassword policy)` and the Bool +-- decision `isValidPassword policy s = null (checkPolicy policy s)`. +-- The uppercase/lowercase/digit/symbol requirements exist only in +-- `strictPolicy` (min length 12), so the properties use that policy. +-- `checkPolicy` works over `unpack`, which does not reduce at the type +-- level, so policy properties are execution checks. -||| Property: Weak password fails (too short) -prop_weakPasswordFails : isErr (validatePassword "weak") = True -prop_weakPasswordFails = Refl +||| OWED: under strictPolicy, every accepted password has at least Fair +||| strength, for `strength = quickStrengthCheck` (a 12+ char password using +||| all four character classes has ~78 bits of pool entropy before pattern +||| penalties; observed Strong/VeryStrong on sampled inputs). Blocked by: +||| `quickStrengthCheck`/`analyzeStrength` are `covering`, so this total +||| module can neither run them nor mention them even in a type; the +||| proposition is therefore named as a family over the strength function, +||| to be instantiated at `quickStrengthCheck`. `checkPolicy` also goes +||| through `unpack`. This names the proposition; it is not a witness. +public export +StrictValidHasMinStrengthObligation : (String -> StrengthLevel) -> Type +StrictValidHasMinStrengthObligation strength = + (s : String) -> isValidPassword strictPolicy s = True -> + (strength s >= Fair) = True -||| OWED: Password without uppercase fails -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_noUppercaseFails_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_noUppercaseFails : isErr (validatePassword "lowercase123!") = True +||| OWED: hashing never yields the plaintext, and hashing is deterministic +||| for a fixed salt. Blocked by: the library has no pure or salt-taking +||| hash entry point -- `hashPasswordArgon2id`/`Bcrypt`/`Scrypt` are bodyless +||| `export` FFI stubs returning `IO HashedPassword`, and the salt is chosen +||| inside them -- so neither property can be stated against the current +||| API. Named here as the specification a future pure +||| `hashWithSalt : String -> String -> String` (password, salt) must meet. +||| This names the proposition; it is not a witness. +public export +HashWithSaltSpecObligation : (String -> String -> String) -> Type +HashWithSaltSpecObligation hashWithSalt = + ((p, salt : String) -> Not (hashWithSalt p salt = p), + (p, salt : String) -> (q : String) -> p = q -> + hashWithSalt p salt = hashWithSalt q salt) -||| OWED: Password without lowercase fails -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_noLowercaseFails_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_noLowercaseFails : isErr (validatePassword "UPPERCASE123!") = True +private +check : String -> Bool -> IO () +check label True = putStrLn ("PASS (execution): " ++ label) +check label False = do + putStrLn ("FAIL: " ++ label) + exitFailure -||| OWED: Password without digit fails -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_noDigitFails_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_noDigitFails : isErr (validatePassword "NoDigitsHere!") = True +||| Run `validatePassword strictPolicy` and test the violation list. +||| Only used on inputs expected to be rejected (see the defect note below). +private +rejectedWith : (List PolicyViolation -> Bool) -> String -> Bool +rejectedWith p s = case validatePassword strictPolicy (MkRawPassword s) of + Left vs => p vs + Right _ => False -||| OWED: Password without special char fails -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_noSpecialFails_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_noSpecialFails : isErr (validatePassword "NoSpecial123") = True - -||| OWED: Hash is not the original password -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_hashNotOriginal_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_hashNotOriginal : (p : ValidPassword) -> hashPassword p /= getPasswordString p - -||| Property: Same password produces same hash (deterministic with same salt) -prop_hashDeterministic : (p : ValidPassword) -> (salt : String) -> - hashPasswordWithSalt p salt = hashPasswordWithSalt p salt -prop_hashDeterministic p salt = Refl - -||| OWED: Password strength is at least minimum when valid -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_minStrengthValid_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_minStrengthValid : (p : ValidPassword) -> getStrength p >= MinStrength +private +isMissingUpper, isMissingLower, isMissingDigit, isMissingSymbol, isTooShort + : PolicyViolation -> Bool +isMissingUpper MissingUppercase = True +isMissingUpper _ = False +isMissingLower MissingLowercase = True +isMissingLower _ = False +isMissingDigit MissingDigit = True +isMissingDigit _ = False +isMissingSymbol MissingSymbol = True +isMissingSymbol _ = False +isTooShort (TooShort _ _) = True +isTooShort _ = False ||| Test runner for password properties export @@ -74,7 +82,30 @@ runPasswordProperties : IO () runPasswordProperties = do putStrLn "SafePassword Property Tests" putStrLn "===========================" - putStrLn "prop_strongPasswordValid: PASS (proven by type)" - putStrLn "prop_weakPasswordFails: PASS (proven by type)" - putStrLn "prop_hashDeterministic: PASS (proven by type)" + check "strong password accepted by strictPolicy (isValidPassword)" + (isValidPassword strictPolicy "Str0ng!Pass#2024") + check "weak password rejected as too short" + (rejectedWith (any isTooShort) "weak") + check "password without uppercase rejected (MissingUppercase)" + (rejectedWith (any isMissingUpper) "lowercase123!") + check "password without lowercase rejected (MissingLowercase)" + (rejectedWith (any isMissingLower) "UPPERCASE123!") + check "password without digit rejected (MissingDigit)" + (rejectedWith (any isMissingDigit) "NoDigitsHere!") + check "password without symbol rejected (MissingSymbol)" + (rejectedWith (any isMissingSymbol) "NoSpecial123") + check "each single-class omission yields exactly that class violation" + (rejectedWith (\vs => length vs == 1) "lowercase123!" && + rejectedWith (\vs => length vs == 1) "UPPERCASE123!" && + rejectedWith (\vs => length vs == 1) "NoDigitsHere!" && + rejectedWith (\vs => length vs == 1) "NoSpecial123") + -- Kept last: on an accepted password, validatePassword evaluates the + -- bodyless `trustCheckPolicy` in its where-clause (the proof argument of + -- MkValidPassword is not erased), which aborts at runtime with + -- "Encountered undefined name ...trustCheckPolicy". Suspected library defect. + putStrLn "running: validatePassword strictPolicy accepts \"Str0ng!Pass#2024\"" + check "strong password accepted by validatePassword" + (case validatePassword strictPolicy (MkRawPassword "Str0ng!Pass#2024") of + Right _ => True + Left _ => False) putStrLn "" diff --git a/tests/properties/SafePathProps.idr b/tests/properties/SafePathProps.idr index ff02a270..3499ac35 100644 --- a/tests/properties/SafePathProps.idr +++ b/tests/properties/SafePathProps.idr @@ -4,56 +4,76 @@ module SafePathProps import Proven.Core import Proven.SafePath +import Data.Maybe +import System %default total -||| Property: Simple path validates -prop_simplePathValid : isOk (validatePath "/home/user") = True -prop_simplePathValid = Refl +-- The real string API (Proven.SafePath.Operations): +-- validatePath : String -> Either String ValidatedPath (normalises; rejects +-- empty, NUL bytes, over-long segments/paths) +-- normalizePath, safeJoinPaths : String -> String -> Maybe String, +-- getExtension : String -> Maybe String +-- and the structured `Path` API (containsTraversal, safeJoin, ...). +-- There is no `joinPath`; the safe join is `safeJoinPaths`. `validatePath` +-- does not reject `..`: it resolves it. Traversal refusal lives in +-- `safeJoinPaths`/`safeJoin` and `containsTraversal`. -||| Property: Path with traversal fails -prop_traversalFails : isErr (validatePath "/home/../etc/passwd") = True -prop_traversalFails = Refl +||| Property: the empty path is rejected. (The original orphan expected it to +||| be valid as "current directory"; the library deliberately rejects it, in +||| line with POSIX, where an empty pathname is an error.) +prop_emptyPathRejected : validatePath "" = Left "Empty path" +prop_emptyPathRejected = Refl -||| OWED: Null byte in path fails -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_nullByteFails_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_nullByteFails : isErr (validatePath "/home/user\0malicious") = True +||| Property: any structured path whose first segment is ".." is flagged as +||| containing traversal, for every remaining segment list. +prop_leadingDotDotIsTraversal : (abs : Bool) -> (rest : List Segment) -> + containsTraversal (MkPath abs (".." :: rest)) = True +prop_leadingDotDotIsTraversal abs rest = foldlStaysTrue _ (\e => Refl) rest + where + -- A left fold whose step keeps True fixed returns True from True. + foldlStaysTrue : (f : Bool -> Segment -> Bool) -> + ((e : Segment) -> f True e = True) -> + (xs : List Segment) -> foldl f True xs = True + foldlStaysTrue f keep [] = Refl + foldlStaysTrue f keep (x :: xs) = rewrite keep x in foldlStaysTrue f keep xs -||| OWED: Empty path is valid (current directory) -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_emptyPathValid_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_emptyPathValid : isOk (validatePath "") = True +||| OWED: `safeJoinPaths base rel`, when it succeeds, yields a path whose +||| segments extend those of `normalizePath base` (no escape from base). +||| Blocked by: `splitPath`/`normalizePath` go through `unpack`/`split` on +||| String, which do not reduce on abstract input. This names the +||| proposition; it is not a witness. +public export +SafeJoinContainedObligation : Type +SafeJoinContainedObligation = + (base, rel, full : String) -> safeJoinPaths base rel = Just full -> + isPrefixOf (splitPath (normalizePath base)) (splitPath full) = True -||| Property: Relative path validates -prop_relativePathValid : isOk (validatePath "relative/path") = True -prop_relativePathValid = Refl +||| OWED: `normalizePath` is idempotent. Blocked by: same String +||| non-reduction. This names the proposition; it is not a witness. +public export +NormalizeIdempotentObligation : Type +NormalizeIdempotentObligation = + (s : String) -> normalizePath (normalizePath s) = normalizePath s -||| OWED: Path normalization removes double slashes -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_normalizeDoubleSlash_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_normalizeDoubleSlash : normalizePath "/home//user" = "/home/user" +private +check : String -> Bool -> IO () +check label True = putStrLn ("PASS (execution): " ++ label) +check label False = do + putStrLn ("FAIL: " ++ label) + exitFailure -||| Property: Join paths correctly -prop_joinPaths : joinPath "/home" "user" = "/home/user" -prop_joinPaths = Refl +private +validatesTo : String -> String -> Bool +validatesTo s expected = case validatePath s of + Right v => getPath v == expected + Left _ => False -||| Property: Get extension extracts correctly -prop_getExtension : getExtension "file.txt" = Just "txt" -prop_getExtension = Refl - -||| Property: No extension returns Nothing -prop_noExtension : getExtension "file" = Nothing -prop_noExtension = Refl +private +rejected : String -> Bool +rejected s = case validatePath s of + Right _ => False + Left _ => True ||| Test runner for path properties export @@ -61,10 +81,33 @@ runPathProperties : IO () runPathProperties = do putStrLn "SafePath Property Tests" putStrLn "=======================" - putStrLn "prop_simplePathValid: PASS (proven by type)" - putStrLn "prop_traversalFails: PASS (proven by type)" - putStrLn "prop_relativePathValid: PASS (proven by type)" - putStrLn "prop_joinPaths: PASS (proven by type)" - putStrLn "prop_getExtension: PASS (proven by type)" - putStrLn "prop_noExtension: PASS (proven by type)" + putStrLn "prop_emptyPathRejected: PASS (proven by type)" + putStrLn "prop_leadingDotDotIsTraversal: PASS (proven by type, all paths)" + check "simple absolute path validates unchanged" + (validatesTo "/home/user" "/home/user") + check "relative path validates unchanged" + (validatesTo "relative/path" "relative/path") + check "null byte in path rejected" + (rejected "/home/user\0malicious") + check "traversal escaping the base is refused by safeJoinPaths" + (isNothing (safeJoinPaths "/home" "../etc/passwd") && + isNothing (safeJoinPaths "/home/user" "a/../../../etc")) + check "validatePath resolves traversal rather than passing it through" + (validatesTo "/home/../etc/passwd" "/etc/passwd") + check "structured traversal detection (containsTraversal/safeJoin)" + (containsTraversal (parsePath "/home/../etc/passwd") && + not (containsTraversal (parsePath "/home/user")) && + isNothing (safeJoin (parsePath "/home") (parsePath "../etc/passwd"))) + check "normalisation removes double slashes" + (normalizePath "/home//user" == "/home/user") + check "normalisation idempotent on corpus (instances of NormalizeIdempotentObligation)" + (all (\s => normalizePath (normalizePath s) == normalizePath s) + ["/home//user", "a/./b/../c", "/../x", "../../y", "", "/"]) + check "joining paths" + (safeJoinPaths "/home" "user" == Just "/home/user") + check "extension extracted" + (getExtension "file.txt" == Just "txt" && + getExtension "/a/b/archive.tar.gz" == Just "gz") + check "no extension gives Nothing" + (isNothing (getExtension "file") && isNothing (getExtension "/a/b/file")) putStrLn "" diff --git a/tests/properties/SafePhoneProps.idr b/tests/properties/SafePhoneProps.idr index f235e417..1933e8d8 100644 --- a/tests/properties/SafePhoneProps.idr +++ b/tests/properties/SafePhoneProps.idr @@ -4,71 +4,73 @@ module SafePhoneProps import Proven.Core import Proven.SafePhone +import Data.Maybe +import System %default total -||| Property: E.164 format parses -prop_e164Parses : isOk (parsePhone "+14155551234") = True -prop_e164Parses = Refl +-- The real API is E.164-only: `parseE164 : String -> Maybe PhoneNumber` +-- (requires a leading '+', strips formatting, 7..15 digits, tries 1-, 2-, +-- then 3-digit country codes), `formatE164 : PhoneNumber -> String`, and +-- `stripFormatting`. There is no `parsePhone`, no national-format parser and +-- no `Eq PhoneNumber`. Parsing goes through `unpack`/`substr`/ +-- `parsePositive`, which do not reduce at the type level, so parse +-- properties are execution checks. -||| Property: US format parses -prop_usFormatParses : isOk (parsePhone "(415) 555-1234") = True -prop_usFormatParses = Refl +||| Property: country-code equality is reflexive, for every code. +||| (Replaces the orphan's `p == p` on a phone type with no `Eq`.) +prop_countryCodeEqReflexive : (n : Nat) -> (MkCountryCode n == MkCountryCode n) = True +prop_countryCodeEqReflexive Z = Refl +prop_countryCodeEqReflexive (S k) = prop_countryCodeEqReflexive k -||| Property: International format parses -prop_internationalParses : isOk (parsePhone "+44 20 7946 0958") = True -prop_internationalParses = Refl +||| OWED: parsing is a fixed point of format-then-parse: whatever +||| `parseE164` returns re-parses from its own E.164 rendering to the same +||| country code and subscriber. Blocked by: `parseE164`/`formatE164` go +||| through `unpack`, `substr`, `show` and `parsePositive` on String, none of +||| which reduce on abstract input. This names the proposition; it is not a +||| witness. +public export +FormatE164RoundTripObligation : Type +FormatE164RoundTripObligation = + (s : String) -> (p : PhoneNumber) -> parseE164 s = Just p -> + parseE164 (formatE164 p) = Just p -||| Property: Too short fails -prop_tooShortFails : isErr (parsePhone "123") = True -prop_tooShortFails = Refl +||| OWED: a parsed number's country code has 1 to 3 digits and its +||| subscriber part at least 4. Blocked by: same String non-reduction; and +||| the `LTE 1 cc` part is currently refuted by "+0123456789", which parses +||| with country code 0 (suspected defect, checked at runtime below). This +||| names the proposition; it is not a witness. +public export +ParsedPartsShapeObligation : Type +ParsedPartsShapeObligation = + (s : String) -> (cc : Nat) -> (sub : String) -> + parseE164 s = Just (MkPhoneNumber (MkCountryCode cc) sub) -> + (LTE 1 cc, LTE cc 999, LTE 4 (length sub)) -||| Property: Too long fails -prop_tooLongFails : isErr (parsePhone "+12345678901234567890") = True -prop_tooLongFails = Refl +private +check : String -> Bool -> IO () +check label True = putStrLn ("PASS (execution): " ++ label) +check label False = do + putStrLn ("FAIL: " ++ label) + exitFailure -||| Property: Letters fail -prop_lettersFail : isErr (parsePhone "+1ABCDEFGHIJ") = True -prop_lettersFail = Refl +private +parsesAs : String -> Nat -> String -> Bool +parsesAs s cc sub = case parseE164 s of + Just (MkPhoneNumber (MkCountryCode c) n) => c == cc && n == sub + Nothing => False -||| OWED: Formatting to E.164 is consistent -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_formatE164Consistent_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_formatE164Consistent : (p : ValidPhone) -> - parsePhone (formatE164 p) = Ok p +private +roundTrips : String -> Bool +roundTrips s = case parseE164 s of + Just p@(MkPhoneNumber (MkCountryCode c) n) => parsesAs (formatE164 p) c n + Nothing => False -||| OWED: Country code extractable -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_countryCodeExtractable_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_countryCodeExtractable : (p : ValidPhone) -> - length (getCountryCode p) >= 1 && length (getCountryCode p) <= 3 - -||| OWED: National number extractable -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_nationalNumberExtractable_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_nationalNumberExtractable : (p : ValidPhone) -> - length (getNationalNumber p) >= 4 - -||| Property: Phone comparison is reflexive -prop_phoneEqReflexive : (p : ValidPhone) -> p == p = True -prop_phoneEqReflexive p = Refl - -||| OWED: Different formats normalize to same -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_normalizationConsistent_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_normalizationConsistent : formatE164 (parsePhone "(415) 555-1234") = formatE164 (parsePhone "4155551234") +private +shapeOk : String -> Bool +shapeOk s = case parseE164 s of + Just (MkPhoneNumber (MkCountryCode c) n) => c >= 1 && c <= 999 && length n >= 4 + Nothing => False ||| Test runner for phone properties export @@ -76,11 +78,34 @@ runPhoneProperties : IO () runPhoneProperties = do putStrLn "SafePhone Property Tests" putStrLn "========================" - putStrLn "prop_e164Parses: PASS (proven by type)" - putStrLn "prop_usFormatParses: PASS (proven by type)" - putStrLn "prop_internationalParses: PASS (proven by type)" - putStrLn "prop_tooShortFails: PASS (proven by type)" - putStrLn "prop_tooLongFails: PASS (proven by type)" - putStrLn "prop_lettersFail: PASS (proven by type)" - putStrLn "prop_phoneEqReflexive: PASS (proven by type)" + putStrLn "prop_countryCodeEqReflexive: PASS (proven by type, all codes)" + check "E.164 +14155551234 parses as +1 / 4155551234" + (parsesAs "+14155551234" 1 "4155551234") + check "US national format without '+' is not E.164 (no national parser exists)" + (isNothing (parseE164 "(415) 555-1234")) + check "different formattings normalise to the same number" + (stripFormatting "(415) 555-1234" == stripFormatting "4155551234" && + parsesAs "+1 (415) 555-1234" 1 "4155551234" && + map formatE164 (parseE164 "+1 (415) 555-1234") == + map formatE164 (parseE164 "+14155551234")) + check "international number with spaces parses" + (isJust (parseE164 "+44 20 7946 0958")) + check "too short rejected" + (isNothing (parseE164 "123") && isNothing (parseE164 "+123")) + check "too long (over 15 digits) rejected" + (isNothing (parseE164 "+12345678901234567890")) + check "all-letter subscriber rejected" + (isNothing (parseE164 "+1ABCDEFGHIJ")) + check "format/parse round trip on corpus (instances of FormatE164RoundTripObligation)" + (all roundTrips ["+14155551234", "+44 20 7946 0958", "+81 3 1234 5678", + "+1 (415) 555-1234"]) + check "parsed part shapes on corpus (instances of ParsedPartsShapeObligation)" + (all shapeOk ["+14155551234", "+44 20 7946 0958", "+81 3 1234 5678"]) + -- Kept last: FAILs here are suspected library defects (see report). + check "UK number +44 20 7946 0958 has country code 44" + (parsesAs "+44 20 7946 0958" 44 "2079460958") + check "letters inside an otherwise valid-length number are rejected" + (isNothing (parseE164 "+1415ABC5551234")) + check "country code 0 is rejected (no E.164 code starts with 0)" + (isNothing (parseE164 "+0123456789")) putStrLn "" diff --git a/tests/properties/SafeRegexProps.idr b/tests/properties/SafeRegexProps.idr index 34bacabf..3bb96d8c 100644 --- a/tests/properties/SafeRegexProps.idr +++ b/tests/properties/SafeRegexProps.idr @@ -4,66 +4,59 @@ module SafeRegexProps import Proven.Core import Proven.SafeRegex +import Proven.SafeString.Escape +import Data.Either +import System %default total -||| Property: Valid simple regex compiles -prop_simpleRegexCompiles : isOk (compileRegex "hello") = True -prop_simpleRegexCompiles = Refl +-- The real API: `regex : String -> Either RegexError SafeRegex` (parse, then +-- reject patterns whose complexity analysis fails the normal safety level), +-- `match`/`test`/`testFull`, `hasRedosRisk`, and `escapeRegex` (which lives +-- in Proven.SafeString.Escape, not SafeRegex). There is no `compileRegex` +-- and no `ValidRegex`. The parser and matcher run over `unpack`, which does +-- not reduce at the type level, so compile/match properties are execution +-- checks. -||| Property: Valid character class regex compiles -prop_charClassCompiles : isOk (compileRegex "[a-z]+") = True -prop_charClassCompiles = Refl +||| Property: `test` agrees with `match`'s matched flag, for every regex and +||| input (replaces the orphan's `match r s = match r s`, which held for any +||| function). +prop_testAgreesWithMatch : (sr : SafeRegex) -> (s : String) -> + test sr s = (match sr s).matched +prop_testAgreesWithMatch sr s = Refl -||| Property: Unbalanced parentheses fails -prop_unbalancedParensFails : isErr (compileRegex "(hello") = True -prop_unbalancedParensFails = Refl +||| OWED: escaping never shortens a string. Blocked by: `escapeRegex` is +||| `pack . go . unpack`, and `length`/`pack`/`unpack` on String do not reduce +||| on abstract input. This names the proposition; it is not a witness. +public export +EscapePreservesLengthObligation : Type +EscapePreservesLengthObligation = + (s : String) -> LTE (length s) (length (escapeRegex s)) -||| Property: Unbalanced brackets fails -prop_unbalancedBracketsFails : isErr (compileRegex "[abc") = True -prop_unbalancedBracketsFails = Refl +||| OWED: an escaped string compiles and matches exactly the original string. +||| Blocked by: the parser and matcher are fuel-driven over `unpack`, which +||| does not reduce on abstract input. This names the proposition; it is not +||| a witness. +public export +EscapeMatchesLiterallyObligation : Type +EscapeMatchesLiterallyObligation = + (s : String) -> (sr : SafeRegex) -> regex (escapeRegex s) = Right sr -> + testFull sr s = True -||| OWED: Invalid escape fails -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_invalidEscapeFails_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_invalidEscapeFails : isErr (compileRegex "\\q") = True +private +check : String -> Bool -> IO () +check label True = putStrLn ("PASS (execution): " ++ label) +check label False = do + putStrLn ("FAIL: " ++ label) + exitFailure -||| OWED: ReDoS pattern detected -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_redosDetected_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_redosDetected : isErr (compileRegex "(a+)+$") = True +private +compiles : String -> Bool +compiles = isRight . regex -||| Property: Match returns correct result -prop_matchCorrect : (r : ValidRegex) -> (s : String) -> - match r s = match r s -prop_matchCorrect r s = Refl - -||| OWED: Empty pattern matches everything -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_emptyMatchesAll_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_emptyMatchesAll : isOk (compileRegex "") = True - -||| Property: Anchored regex works -prop_anchoredRegex : isOk (compileRegex "^hello$") = True -prop_anchoredRegex = Refl - -||| OWED: Escape special characters preserves length -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_escapePreservesLength_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_escapePreservesLength : (s : String) -> - length (escapeRegex s) >= length s +private +escapeCorpus : List String +escapeCorpus = ["", "abc", "a.b", "1+1=2", "(x)", "[a-z]*", "^$|\\", "{3}?"] ||| Test runner for regex properties export @@ -71,10 +64,25 @@ runRegexProperties : IO () runRegexProperties = do putStrLn "SafeRegex Property Tests" putStrLn "========================" - putStrLn "prop_simpleRegexCompiles: PASS (proven by type)" - putStrLn "prop_charClassCompiles: PASS (proven by type)" - putStrLn "prop_unbalancedParensFails: PASS (proven by type)" - putStrLn "prop_unbalancedBracketsFails: PASS (proven by type)" - putStrLn "prop_matchCorrect: PASS (proven by type)" - putStrLn "prop_anchoredRegex: PASS (proven by type)" + putStrLn "prop_testAgreesWithMatch: PASS (proven by type, all regexes/inputs)" + check "simple regex compiles" (compiles "hello") + check "character class regex compiles" (compiles "[a-z]+") + check "unbalanced parentheses rejected" (not (compiles "(hello")) + check "unbalanced brackets rejected" (not (compiles "[abc")) + check "invalid escape \\q rejected" (not (compiles "\\q")) + check "ReDoS pattern (a+)+$ rejected and flagged" + (not (compiles "(a+)+$") && hasRedosRisk "(a+)+$") + check "anchored regex compiles and matches only the whole word" + (compiles "^hello$" && quickTest "^hello$" "hello" && + not (quickTest "^hello$" "hello world")) + check "empty pattern compiles and matches every input" + (compiles "" && all (quickTest "") ["", "a", "hello world"]) + check "match: positive and negative cases" + (quickTest "[a-z]+" "123abc" && not (quickTest "[a-z]+" "123") && + quickTestFull "[a-z]+" "abc" && not (quickTestFull "[a-z]+" "abc1")) + check "escaping never shortens (instances of EscapePreservesLengthObligation)" + (all (\s => length (escapeRegex s) >= length s) escapeCorpus) + check "escaped string matches itself literally (instances of EscapeMatchesLiterallyObligation)" + (all (\s => quickTestFull (escapeRegex s) s) escapeCorpus && + not (quickTestFull (escapeRegex "a.b") "axb")) putStrLn "" diff --git a/tests/properties/SafeSQLProps.idr b/tests/properties/SafeSQLProps.idr index 82f3e73c..a74ff775 100644 --- a/tests/properties/SafeSQLProps.idr +++ b/tests/properties/SafeSQLProps.idr @@ -3,59 +3,95 @@ module SafeSQLProps import Proven.Core -import Proven.SafeSQL +-- `Proven.SafeSQL` re-exports `Proven.SafeSQL.Builder`, which proven.ipkg does +-- not list and so is not installed; import the installed sub-modules directly. +import Proven.SafeSQL.Types +import Proven.SafeSQL.Params +import Proven.SafeSQL.Proofs +import System %default total -||| Property: Parameterized query is safe -prop_parameterizedSafe : isOk (buildQuery "SELECT * FROM users WHERE id = ?" [IntParam 1]) = True -prop_parameterizedSafe = Refl - -||| OWED: SQL injection in string blocked -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_injectionBlocked_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_injectionBlocked : isErr (buildQuery "SELECT * FROM users WHERE name = '" []) = True - -||| Property: Escape quotes in strings -prop_escapeQuotes : escapeString "O'Brien" = "O''Brien" -prop_escapeQuotes = Refl - -||| Property: Identifier escaping works -prop_identifierEscape : escapeIdentifier "table name" = "\"table name\"" -prop_identifierEscape = Refl - -||| Property: Valid identifier passes -prop_validIdentifier : isOk (validateIdentifier "users") = True -prop_validIdentifier = Refl - -||| Property: Invalid identifier rejected (starts with number) -prop_invalidIdentifierNum : isErr (validateIdentifier "123users") = True -prop_invalidIdentifierNum = Refl - -||| Property: Reserved word rejected as identifier -prop_reservedWordRejected : isErr (validateIdentifier "SELECT") = True -prop_reservedWordRejected = Refl - -||| OWED: Parameter count matches placeholders -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_paramCountMatches_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_paramCountMatches : (q : String) -> (ps : List SQLParam) -> - countPlaceholders q = length ps -> - isOk (buildQuery q ps) = True - -||| Property: Null parameter handled -prop_nullParamHandled : isOk (buildQuery "SELECT * FROM users WHERE deleted_at IS ?" [NullParam]) = True -prop_nullParamHandled = Refl - -||| Property: LIKE wildcards escaped -prop_likeWildcardsEscaped : escapeLikePattern "100%" = "100\\%" -prop_likeWildcardsEscaped = Refl +-- Rewritten against the real API: queries are `ParameterizedQuery` values built +-- with `literal`/`appendParam`/`bindParams` and checked by `validateParams`; +-- escaping functions take an `SQLDialect`. (`buildQuery`, `IntParam`, +-- `validateIdentifier`, `countPlaceholders` never existed.) + +-------------------------------------------------------------------------------- +-- Type-level proofs +-------------------------------------------------------------------------------- + +||| One placeholder with one bound value validates, for every dialect, literal +||| prefix and value (was prop_parameterizedSafe). +prop_parameterizedSafe : (d : SQLDialect) -> (sql : String) -> (v : SQLValue) -> + isOk (validateParams (bindParams (appendParam (literal d sql)) [v])) = True +prop_parameterizedSafe d sql v = Refl + +||| A placeholder with no bound value is rejected. +prop_unboundParamRejected : (d : SQLDialect) -> (sql : String) -> + isErr (validateParams (appendParam (literal d sql))) = True +prop_unboundParamRejected d sql = Refl + +||| A query with no placeholders needs no bindings. +prop_literalNeedsNoParams : (d : SQLDialect) -> (sql : String) -> + isOk (validateParams (literal d sql)) = True +prop_literalNeedsNoParams d sql = Refl + +||| NULL renders as the keyword NULL in every dialect. +prop_nullRendersAsKeyword : (d : SQLDialect) -> renderValue d SQLNull = "NULL" +prop_nullRendersAsKeyword d = Refl + +||| A NULL parameter binds and validates in every dialect (was prop_nullParamHandled). +prop_nullParamHandled : (d : SQLDialect) -> (sql : String) -> + isOk (validateParams (bindParams (appendParam (literal d sql)) [SQLNull])) = True +prop_nullParamHandled d sql = Refl + +||| Integer values carry an escaping witness in every dialect. +prop_intValuesSafe : (d : SQLDialect) -> (i : Integer) -> IsEscapedValue d (SQLInt i) +prop_intValuesSafe d i = numericValuesCannotInject d i + +-------------------------------------------------------------------------------- +-- Outstanding obligations (named propositions, not witnesses) +-------------------------------------------------------------------------------- + +||| OWED: escaping leaves no unescaped quote that could end the literal early +||| (was prop_injectionBlocked). Blocked by: `unpack`/`++` over an abstract +||| String do not reduce at the type level; the library's `escapeStringQuotesSafe` +||| is itself an erased declaration without a body, not a proof. +||| This names the proposition; it is not a witness. +public export +EscapeStringQuotesObligation : Type +EscapeStringQuotesObligation = + (d : SQLDialect) -> (s : String) -> NoUnescapedQuotes (escapeString d s) + +||| OWED: a query whose positional placeholders are all bound and which has no +||| named placeholders validates (was prop_paramCountMatches). Blocked by: +||| `validateParams` goes through `nub`/`mapMaybe`/`filter` over an abstract +||| fragment list; needs list lemmas linking `countParams`/`getNamedParamNames` +||| to its branch conditions. This names the proposition; it is not a witness. +public export +ParamCountValidatesObligation : Type +ParamCountValidatesObligation = + (q : ParameterizedQuery) -> + LTE (countParams q) (length q.params) -> + getNamedParamNames q = [] -> + isOk (validateParams q) = True + +-------------------------------------------------------------------------------- +-- Execution checks +-------------------------------------------------------------------------------- + +private +check : String -> Bool -> IO () +check label True = putStrLn ("PASS (execution): " ++ label) +check label False = do + putStrLn ("FAIL: " ++ label) + exitFailure + +private +rejected : Maybe a -> Bool +rejected Nothing = True +rejected (Just _) = False ||| Test runner for SQL properties export @@ -64,11 +100,50 @@ runSQLProperties = do putStrLn "SafeSQL Property Tests" putStrLn "======================" putStrLn "prop_parameterizedSafe: PASS (proven by type)" - putStrLn "prop_escapeQuotes: PASS (proven by type)" - putStrLn "prop_identifierEscape: PASS (proven by type)" - putStrLn "prop_validIdentifier: PASS (proven by type)" - putStrLn "prop_invalidIdentifierNum: PASS (proven by type)" - putStrLn "prop_reservedWordRejected: PASS (proven by type)" + putStrLn "prop_unboundParamRejected: PASS (proven by type)" + putStrLn "prop_literalNeedsNoParams: PASS (proven by type)" + putStrLn "prop_nullRendersAsKeyword: PASS (proven by type)" putStrLn "prop_nullParamHandled: PASS (proven by type)" - putStrLn "prop_likeWildcardsEscaped: PASS (proven by type)" + putStrLn "prop_intValuesSafe: PASS (proven by type)" + check "prop_escapeQuotes: escapeString doubles single quotes and wraps" + (escapeString PostgreSQL "O'Brien" == "'O''Brien'" && + escapeString MSSQL "O'Brien" == "'O''Brien'") + check "escapeString strips NUL bytes" + (escapeString SQLite "a\0b" == "'ab'") + check "prop_injectionBlocked: dangling quote in literal SQL is flagged" + (isErr (validateQuerySafety (literal PostgreSQL "SELECT * FROM users WHERE name = '"))) + check "prop_injectionBlocked: OR/comment payload flagged, plain word not" + (isErr (assertNoInjection "' OR 1=1 --") && isOk (assertNoInjection "alice")) + check "prop_injectionBlocked: payload bound as text stays inside one literal" + (escapeString MySQL "x'; DROP TABLE users; --" == "'x''; DROP TABLE users; --'") + check "prop_identifierEscape: identifiers quoted per dialect" + (quoteIdentifier PostgreSQL (MkSafeIdentifier "users") == "\"users\"" && + quoteIdentifier MySQL (MkSafeIdentifier "users") == "`users`" && + quoteIdentifier MSSQL (MkSafeIdentifier "users") == "[users]") + check "prop_identifierEscape: embedded quote characters doubled" + (quoteIdentifier PostgreSQL (MkSafeIdentifier "a\"b") == "\"a\"\"b\"" && + quoteIdentifier MSSQL (MkSafeIdentifier "a]b") == "[a]]b]") + check "prop_validIdentifier: users accepted" + (isOk (assertValidIdentifier "users") && + map identifierName (mkIdentifier "users") == Just "users") + check "prop_invalidIdentifierNum: leading digit rejected" + (rejected (mkIdentifier "123users") && isErr (assertValidIdentifier "123users")) + check "identifiers with space, quote, or empty rejected" + (rejected (mkIdentifier "table name") && rejected (mkIdentifier "a'b") && + rejected (mkIdentifier "")) + check "prop_reservedWordRejected: reserved words detected case-insensitively" + (isReservedWord "SELECT" && isReservedWord "select" && not (isReservedWord "users")) + check "prop_nullParamHandled: NULL interpolates as keyword" + (renderQueryInterpolated + (bindParams (appendParam (literal PostgreSQL "SELECT * FROM users WHERE deleted_at IS ")) [SQLNull]) + == "SELECT * FROM users WHERE deleted_at IS NULL") + check "prop_paramCountMatches: placeholders numbered per dialect" + (renderQuery (appendParam (appendLiteral " AND b = " (appendParam (literal PostgreSQL "a = ")))) + == "a = $1 AND b = $2") + check "prop_paramCountMatches: two placeholders with one value rejected" + (isErr (validateParams (bindParams (appendParam (appendParam (literal SQLite "x"))) [SQLInt 1]))) + check "prop_likeWildcardsEscaped: % and _ escaped" + (escapeLikePattern PostgreSQL "100%" == "100\\%" && + escapeLikePattern PostgreSQL "a_b" == "a\\_b" && + escapeLikePattern MSSQL "100%" == "100[%]") putStrLn "" diff --git a/tests/properties/SafeStringProps.idr b/tests/properties/SafeStringProps.idr index 57ad9ed7..cb7648ee 100644 --- a/tests/properties/SafeStringProps.idr +++ b/tests/properties/SafeStringProps.idr @@ -4,61 +4,123 @@ module SafeStringProps import Proven.Core import Proven.SafeString +import Data.List +import Data.String +import System %default total -||| OWED: Escaping then unescaping returns original (for valid strings) -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_escapeRoundTrip_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_escapeRoundTrip : (s : String) -> ValidUTF8 s -> - unescapeHtml (escapeHtml s) = s - -||| OWED: HTML escaping never returns empty for non-empty input -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_escapeNonEmpty_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_escapeNonEmpty : (s : String) -> length s > 0 -> - length (escapeHtml s) > 0 = True - -||| Property: SQL escaping doubles single quotes +-- Rewritten against the real API: the escapers are `escapeHTML`, `escapeSQL`, +-- `urlEncode`, `escapeShell`; `isValidUTF8` takes `List Bits8` (use +-- `stringToBytes`). There is no `unescapeHtml`, `ValidUTF8 s` predicate, +-- `AlreadyURLEncoded` or `IsASCII` in the library. + +-------------------------------------------------------------------------------- +-- Type-level proofs +-------------------------------------------------------------------------------- + +||| SQL escaping doubles a single quote. prop_sqlEscapeQuotes : escapeSQL "'" = "''" prop_sqlEscapeQuotes = Refl -||| OWED: URL encoding is idempotent for encoded strings -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_urlEncodeIdempotent_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_urlEncodeIdempotent : (s : String) -> AlreadyURLEncoded s -> - urlEncode s = s - -||| OWED: Shell escaping wraps in single quotes -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_shellEscapeWraps_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_shellEscapeWraps : (s : String) -> - head' (escapeShell s) = Just '\'' = True - -||| OWED: UTF-8 validation accepts ASCII -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_asciiIsValidUTF8_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_asciiIsValidUTF8 : (s : String) -> IsASCII s -> isValidUTF8 s = True - -||| Property: Empty string is always valid -prop_emptyStringValid : isValidUTF8 "" = True +||| The empty byte sequence is valid UTF-8 (was prop_emptyStringValid). +prop_emptyBytesValid : isValidUTF8 [] = True +prop_emptyBytesValid = Refl + +||| The empty string encodes to valid UTF-8. +prop_emptyStringValid : isValidUTF8 (stringToBytes "") = True prop_emptyStringValid = Refl +||| A concrete ASCII byte sequence ("Hi!") is valid UTF-8. +prop_asciiBytesValid : isValidUTF8 [0x48, 0x69, 0x21] = True +prop_asciiBytesValid = Refl + +||| A lone continuation byte is rejected. +prop_loneContinuationInvalid : isValidUTF8 [0x80] = False +prop_loneContinuationInvalid = Refl + +||| A truncated two-byte sequence is rejected. +prop_truncatedSequenceInvalid : isValidUTF8 [0xC3] = False +prop_truncatedSequenceInvalid = Refl + +||| A well-formed two-byte sequence (U+00E9) is accepted. +prop_twoByteSequenceValid : isValidUTF8 [0xC3, 0xA9] = True +prop_twoByteSequenceValid = Refl + +-------------------------------------------------------------------------------- +-- Outstanding obligations (named propositions, not witnesses) +-------------------------------------------------------------------------------- + +||| OWED: HTML escaping loses no information, i.e. is injective (the library has +||| no `unescapeHTML`, so the original round-trip is stated as injectivity). +||| Blocked by: `pack`/`unpack` over an abstract String do not reduce at the type +||| level and the per-character `go` is a private `where` helper. +||| This names the proposition; it is not a witness. +public export +EscapeHTMLInjectiveObligation : Type +EscapeHTMLInjectiveObligation = + (s1, s2 : String) -> escapeHTML s1 = escapeHTML s2 -> s1 = s2 + +||| OWED: HTML escaping never returns empty for non-empty input. +||| Blocked by: `length`/`pack`/`unpack` over an abstract String do not reduce. +||| This names the proposition; it is not a witness. +public export +EscapeHTMLNonEmptyObligation : Type +EscapeHTMLNonEmptyObligation = + (s : String) -> length s > 0 = True -> length (escapeHTML s) > 0 = True + +||| OWED: URL encoding is the identity on strings made only of RFC 3986 +||| unreserved characters (the original "idempotent on encoded strings" is false +||| as stated: `%` is itself re-encoded to `%25`). Blocked by: `concat`/`singleton` +||| over an abstract String do not reduce. This names the proposition; it is not +||| a witness. +public export +UrlEncodeUnreservedFixedObligation : Type +UrlEncodeUnreservedFixedObligation = + (s : String) -> all isURLSafe (unpack s) = True -> urlEncode s = s + +||| OWED: shell escaping always wraps its output in single quotes. +||| Blocked by: `++` over an abstract String does not reduce at the type level. +||| This names the proposition; it is not a witness. +public export +ShellEscapeWrapsObligation : Type +ShellEscapeWrapsObligation = + (s : String) -> + (startsWith "'" (escapeShell s) && endsWith "'" (escapeShell s)) = True + +||| OWED: every ASCII string encodes to valid UTF-8. +||| Blocked by: `unpack` over an abstract String does not reduce, and the +||| validator's fuelled loop is a private `where` helper. +||| This names the proposition; it is not a witness. +public export +AsciiIsValidUTF8Obligation : Type +AsciiIsValidUTF8Obligation = + (s : String) -> isAscii s = True -> isValidUTF8 (stringToBytes s) = True + +-------------------------------------------------------------------------------- +-- Execution checks +-------------------------------------------------------------------------------- + +private +check : String -> Bool -> IO () +check label True = putStrLn ("PASS (execution): " ++ label) +check label False = do + putStrLn ("FAIL: " ++ label) + exitFailure + +private +corpus : List String +corpus = ["", "a", "plain text", "", "a & b", "\"q\"", + "100%", "it's", "x/y?z=1", "tab\there", "&"] + +private +noRawHtmlSpecials : String -> Bool +noRawHtmlSpecials s = all (\c => not (c `elem` ['<', '>', '"', '\''])) (unpack s) + +private +pairs : List a -> List (a, a) +pairs xs = [(x, y) | x <- xs, y <- xs] + ||| Test runner for string properties export runStringProperties : IO () @@ -66,6 +128,28 @@ runStringProperties = do putStrLn "SafeString Property Tests" putStrLn "=========================" putStrLn "prop_sqlEscapeQuotes: PASS (proven by type)" + putStrLn "prop_emptyBytesValid: PASS (proven by type)" putStrLn "prop_emptyStringValid: PASS (proven by type)" + putStrLn "prop_asciiBytesValid: PASS (proven by type)" + putStrLn "prop_loneContinuationInvalid: PASS (proven by type)" + putStrLn "prop_truncatedSequenceInvalid: PASS (proven by type)" + putStrLn "prop_twoByteSequenceValid: PASS (proven by type)" + check "prop_escapeRoundTrip: escapeHTML injective on corpus" + (all (\(a, b) => escapeHTML a /= escapeHTML b || a == b) (pairs corpus)) + check "escapeHTML leaves no raw < > \" ' on corpus" + (all (noRawHtmlSpecials . escapeHTML) corpus) + check "escapeHTML concrete output" + (escapeHTML "&" == "<a href="x">&</a>") + check "prop_escapeNonEmpty: non-empty input gives non-empty output on corpus" + (all (\s => length s == 0 || length (escapeHTML s) > 0) corpus) + check "prop_urlEncodeIdempotent: unreserved strings are fixed points" + (all (\s => urlEncode s == s) ["", "abc123", "A-Z_a.z~0"]) + check "urlEncode escapes reserved characters" + (urlEncode " " == "%20" && urlEncode "a&b=c" == "a%26b%3Dc" && urlEncode "%" == "%25") + check "prop_shellEscapeWraps: output starts and ends with a single quote" + (all (\s => startsWith "'" (escapeShell s) && endsWith "'" (escapeShell s)) corpus) + check "escapeShell neutralises embedded single quote" + (escapeShell "it's" == "'it'\\''s'") + check "prop_asciiIsValidUTF8: ASCII corpus encodes to valid UTF-8" + (all (\s => not (isAscii s) || isValidUTF8 (stringToBytes s)) corpus) putStrLn "" - putStrLn "String escape properties verified." diff --git a/tests/properties/SafeTOMLProps.idr b/tests/properties/SafeTOMLProps.idr index 2b8da2e6..b0aef293 100644 --- a/tests/properties/SafeTOMLProps.idr +++ b/tests/properties/SafeTOMLProps.idr @@ -4,56 +4,75 @@ module SafeTOMLProps import Proven.Core import Proven.SafeTOML +import System %default total -||| Property: Valid TOML parses -prop_validTOMLParses : isOk (parseTOML "key = \"value\"") = True -prop_validTOMLParses = Refl +-- `parseTOML`/`parseValue` are `export` (not `public export`), so their results +-- cannot reduce at the type level; document-level properties are execution +-- checks. The original `isOk (parseTOML ...)` checks only asked whether the +-- parser returned *something*; they are strengthened here to check the parsed +-- content, which is what "parses" means. -||| Property: Section header parses -prop_sectionParses : isOk (parseTOML "[section]\nkey = \"value\"") = True -prop_sectionParses = Refl +-------------------------------------------------------------------------------- +-- Type-level proofs +-------------------------------------------------------------------------------- -||| Property: Nested section parses -prop_nestedSectionParses : isOk (parseTOML "[parent.child]\nkey = \"value\"") = True -prop_nestedSectionParses = Refl +mutual + ||| Mapping the identity over a TOML value is the identity (functor law). + prop_mapValuesIdentity : (v : TOMLValue) -> mapValues Prelude.id v = v + prop_mapValuesIdentity (TString _) = Refl + prop_mapValuesIdentity (TInt _) = Refl + prop_mapValuesIdentity (TFloat _) = Refl + prop_mapValuesIdentity (TBool _) = Refl + prop_mapValuesIdentity (TDateTime _) = Refl + prop_mapValuesIdentity (TDate _) = Refl + prop_mapValuesIdentity (TTime _) = Refl + prop_mapValuesIdentity (TArray xs) = cong TArray (mapItemsIdentity xs) + prop_mapValuesIdentity (TInlineTable kvs) = cong TInlineTable (mapPairsIdentity kvs) + prop_mapValuesIdentity (TTable kvs) = cong TTable (mapPairsIdentity kvs) -||| Property: Array parses -prop_arrayParses : isOk (parseTOML "arr = [1, 2, 3]") = True -prop_arrayParses = Refl + private + mapItemsIdentity : (xs : List TOMLValue) -> mapValuesItems Prelude.id xs = xs + mapItemsIdentity [] = Refl + mapItemsIdentity (x :: xs) = cong2 (::) (prop_mapValuesIdentity x) (mapItemsIdentity xs) -||| Property: Inline table parses -prop_inlineTableParses : isOk (parseTOML "point = { x = 1, y = 2 }") = True -prop_inlineTableParses = Refl + private + mapPairsIdentity : (kvs : List (String, TOMLValue)) -> mapValuesPairs Prelude.id kvs = kvs + mapPairsIdentity [] = Refl + mapPairsIdentity ((k, v) :: kvs) = + cong2 (::) (cong (MkPair k) (prop_mapValuesIdentity v)) (mapPairsIdentity kvs) -||| Property: Invalid TOML fails -prop_invalidTOMLFails : isErr (parseTOML "key = [unclosed") = True -prop_invalidTOMLFails = Refl +||| Typed coercion refuses a mismatched value: a string is never an integer. +prop_asIntRejectsString : (s : String) -> isErr (asInt (TString s)) = True +prop_asIntRejectsString s = Refl -||| Property: Duplicate key fails -prop_duplicateKeyFails : isErr (parseTOML "key = 1\nkey = 2") = True -prop_duplicateKeyFails = Refl +||| Typed coercion refuses a mismatched value: an integer is never a boolean. +prop_asBoolRejectsInt : (i : Integer) -> isErr (asBool (TInt i)) = True +prop_asBoolRejectsInt i = Refl -||| Property: Integer parses correctly -prop_integerParses : isOk (parseTOML "num = 42") = True -prop_integerParses = Refl +-------------------------------------------------------------------------------- +-- Execution checks +-------------------------------------------------------------------------------- -||| Property: Float parses correctly -prop_floatParses : isOk (parseTOML "num = 3.14") = True -prop_floatParses = Refl +private +check : String -> Bool -> IO () +check label True = putStrLn ("PASS (execution): " ++ label) +check label False = do + putStrLn ("FAIL: " ++ label) + exitFailure -||| Property: Boolean parses correctly -prop_booleanParses : isOk (parseTOML "flag = true") = True -prop_booleanParses = Refl +private +resultIs : Eq a => a -> Result e a -> Bool +resultIs x (Ok y) = x == y +resultIs _ (Err _) = False -||| Property: DateTime parses correctly -prop_datetimeParses : isOk (parseTOML "dt = 2024-01-15T10:30:00Z") = True -prop_datetimeParses = Refl - -||| Property: Multiline string parses -prop_multilineStringParses : isOk (parseTOML "str = \"\"\"\nmulti\nline\n\"\"\"") = True -prop_multilineStringParses = Refl +||| Parse `src`, then apply an accessor to the document. +private +parsedThen : String -> (TOMLDocument -> Result TOMLError a) -> Result TOMLError a +parsedThen src f = case parseTOML src of + Ok doc => f doc + Err e => Err e ||| Test runner for TOML properties export @@ -61,16 +80,56 @@ runTOMLProperties : IO () runTOMLProperties = do putStrLn "SafeTOML Property Tests" putStrLn "=======================" - putStrLn "prop_validTOMLParses: PASS (proven by type)" - putStrLn "prop_sectionParses: PASS (proven by type)" - putStrLn "prop_nestedSectionParses: PASS (proven by type)" - putStrLn "prop_arrayParses: PASS (proven by type)" - putStrLn "prop_inlineTableParses: PASS (proven by type)" - putStrLn "prop_invalidTOMLFails: PASS (proven by type)" - putStrLn "prop_duplicateKeyFails: PASS (proven by type)" - putStrLn "prop_integerParses: PASS (proven by type)" - putStrLn "prop_floatParses: PASS (proven by type)" - putStrLn "prop_booleanParses: PASS (proven by type)" - putStrLn "prop_datetimeParses: PASS (proven by type)" - putStrLn "prop_multilineStringParses: PASS (proven by type)" + putStrLn "prop_mapValuesIdentity: PASS (proven by type)" + putStrLn "prop_asIntRejectsString: PASS (proven by type)" + putStrLn "prop_asBoolRejectsInt: PASS (proven by type)" + check "empty and comment-only documents parse to the empty document" + (resultIs [] (parseTOML "") && resultIs [] (parseTOML "# comment\n\n")) + check "parseValue: integer, float, boolean, basic and literal strings" + (resultIs (TInt 42) (parseValue "42") && + resultIs (TInt 1000) (parseValue "1_000") && + resultIs (TFloat 3.14) (parseValue "3.14") && + resultIs (TBool True) (parseValue "true") && + resultIs (TString "a\tb") (parseValue "\"a\\tb\"") && + resultIs (TString "C:\\x") (parseValue "'C:\\x'")) + check "parseValue rejects a bad escape and a bare word" + (isErr (parseValue "\"\\q\"") && isErr (parseValue "nope")) + check "accessors and dotted paths on a constructed document" + (let doc = mkDocument [("title", TString "t"), + ("server", mkTable [("port", TInt 8080)])] + in resultIs "t" (getString "title" doc) && + resultIs (TInt 8080) (getPath "server.port" doc) && + isErr (getPath "server.host" doc)) + check "mergeDocuments: second document wins on conflicts" + (mergeDocuments [("a", TInt 1), ("b", TInt 2)] [("b", TInt 3)] + == [("a", TInt 1), ("b", TInt 3)]) + -- Document-level parsing (original intent of every prop_*Parses / *Fails). + check "prop_validTOMLParses: key = \"value\" yields key -> \"value\"" + (resultIs "value" (parsedThen "key = \"value\"" (getString "key"))) + check "prop_integerParses: num = 42" + (resultIs 42 (parsedThen "num = 42" (getInt "num"))) + check "prop_floatParses: num = 3.14" + (resultIs 3.14 (parsedThen "num = 3.14" (getFloat "num"))) + check "prop_booleanParses: flag = true" + (resultIs True (parsedThen "flag = true" (getBool "flag"))) + check "prop_sectionParses: [section] key" + (resultIs (TString "value") (parsedThen "[section]\nkey = \"value\"" (getPath "section.key"))) + check "prop_nestedSectionParses: [parent.child] key" + (resultIs (TString "value") + (parsedThen "[parent.child]\nkey = \"value\"" (getPath "parent.child.key"))) + check "prop_arrayParses: arr = [1, 2, 3]" + (resultIs [TInt 1, TInt 2, TInt 3] (parsedThen "arr = [1, 2, 3]" (getArray "arr"))) + check "prop_inlineTableParses: point = { x = 1, y = 2 }" + (resultIs (TInt 2) (parsedThen "point = { x = 1, y = 2 }" (getPath "point.y"))) + check "prop_datetimeParses: dt = 2024-01-15T10:30:00Z" + (isOk (parsedThen "dt = 2024-01-15T10:30:00Z" (\d => getField "dt" d >>= asDateTime))) + check "prop_multilineStringParses: str = \"\"\"multi line\"\"\"" + (resultIs "multi\nline\n" + (parsedThen "str = \"\"\"\nmulti\nline\n\"\"\"" (getString "str"))) + check "prop_invalidTOMLFails: unclosed array rejected" + (isErr (parseTOML "key = [unclosed")) + check "prop_duplicateKeyFails: duplicate key rejected" + (isErr (parseTOML "key = 1\nkey = 2")) + check "parseValue: array literal [1, 2, 3] keeps its elements" + (resultIs (TArray [TInt 1, TInt 2, TInt 3]) (parseValue "[1, 2, 3]")) putStrLn "" diff --git a/tests/properties/SafeUUIDProps.idr b/tests/properties/SafeUUIDProps.idr index 096a686b..2d2b5a1f 100644 --- a/tests/properties/SafeUUIDProps.idr +++ b/tests/properties/SafeUUIDProps.idr @@ -4,66 +4,112 @@ module SafeUUIDProps import Proven.Core import Proven.SafeUUID +import Data.Maybe +import Data.String +import System %default total -||| Property: Valid UUID v4 parses -prop_validUUIDv4Parses : isOk (parseUUID "550e8400-e29b-41d4-a716-446655440000") = True -prop_validUUIDv4Parses = Refl +-- Rewritten against the real API: `parse : String -> Maybe UUID`, +-- `isValid`, `isNil`, `format`, `formatCompact`, record fields `version` / +-- `variant`. There is no `parseUUID`, `ValidUUID`, `toString`, `getVersion`, +-- `generateUUIDv4`, `toBytes` or `fromBytes`; bytes are reached through the +-- re-exported `Proven.SafeHex` (`decode`/`encode`). -||| Property: Uppercase UUID parses -prop_uppercaseUUIDParses : isOk (parseUUID "550E8400-E29B-41D4-A716-446655440000") = True -prop_uppercaseUUIDParses = Refl +private +v4Sample : String +v4Sample = "550e8400-e29b-41d4-a716-446655440000" -||| Property: Invalid format fails -prop_invalidFormatFails : isErr (parseUUID "not-a-uuid") = True +-------------------------------------------------------------------------------- +-- Type-level proofs (closed computations that reduce). Accepting a UUID needs +-- the hex-character test in `isValidHex`, which does not reduce at the type +-- level, so the positive parses are execution checks below. +-------------------------------------------------------------------------------- + +||| A non-hex string is rejected. +prop_invalidFormatFails : isValid "not-a-uuid" = False prop_invalidFormatFails = Refl -||| Property: Wrong length fails -prop_wrongLengthFails : isErr (parseUUID "550e8400-e29b-41d4-a716") = True +||| A truncated UUID is rejected. +prop_wrongLengthFails : isValid "550e8400-e29b-41d4-a716" = False prop_wrongLengthFails = Refl -||| Property: Nil UUID parses -prop_nilUUIDParses : isOk (parseUUID "00000000-0000-0000-0000-000000000000") = True -prop_nilUUIDParses = Refl - -||| OWED: Generated UUID is valid -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_generatedUUIDValid_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_generatedUUIDValid : isOk (parseUUID (toString (generateUUIDv4 seed))) = True - -||| OWED: UUID version is extractable -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_versionExtractable_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_versionExtractable : (uuid : ValidUUID) -> getVersion uuid >= 1 && getVersion uuid <= 5 - -||| OWED: UUID formatting is consistent -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_formatConsistent_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_formatConsistent : (uuid : ValidUUID) -> - parseUUID (toString uuid) = Ok uuid - -||| Property: UUID comparison is reflexive -prop_uuidEqReflexive : (uuid : ValidUUID) -> uuid == uuid = True -prop_uuidEqReflexive uuid = Refl - -||| OWED: UUID bytes roundtrip -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_bytesRoundtrip_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_bytesRoundtrip : (uuid : ValidUUID) -> - fromBytes (toBytes uuid) = Ok uuid +-------------------------------------------------------------------------------- +-- Outstanding obligations (named propositions, not witnesses) +-------------------------------------------------------------------------------- + +||| OWED: formatting a parsed UUID and parsing it again gives the same UUID +||| (was prop_formatConsistent). Blocked by: `substr`/`++`/`unpack` over an +||| abstract String do not reduce at the type level. Holds only for parsed +||| UUIDs: `MkUUID` is public, so an arbitrary record need not be well-formed. +||| This names the proposition; it is not a witness. +public export +UuidFormatRoundTripObligation : Type +UuidFormatRoundTripObligation = + (s : String) -> (u : UUID) -> Proven.SafeUUID.parse s = Just u -> + Proven.SafeUUID.parse (format u) = Just u + +||| OWED: UUID equality is reflexive (was prop_uuidEqReflexive). Blocked by: +||| `==` compares `toLower` of the hex strings, and `toLower`/String equality do +||| not reduce for an abstract String. This names the proposition; it is not a +||| witness. +public export +UuidEqReflexiveObligation : Type +UuidEqReflexiveObligation = (u : UUID) -> (u == u) = True + +||| OWED: a parsed UUID decodes to 16 bytes that re-encode to an equal UUID +||| (was prop_bytesRoundtrip). Blocked by: String primitives in `decode`, +||| `encode` and `parse` do not reduce for an abstract String. +||| This names the proposition; it is not a witness. +public export +UuidBytesRoundTripObligation : Type +UuidBytesRoundTripObligation = + (s : String) -> (u : UUID) -> Proven.SafeUUID.parse s = Just u -> + (bs : List Nat ** (decode (formatCompact u) = Just bs, + length bs = 16, + map (== u) (Proven.SafeUUID.parse (encode bs)) = Just True)) + +-------------------------------------------------------------------------------- +-- Execution checks +-------------------------------------------------------------------------------- + +private +check : String -> Bool -> IO () +check label True = putStrLn ("PASS (execution): " ++ label) +check label False = do + putStrLn ("FAIL: " ++ label) + exitFailure + +private +samples : List String +samples = [ v4Sample + , "550E8400-E29B-41D4-A716-446655440000" + , "00000000-0000-0000-0000-000000000000" + , "6ba7b810-9dad-11d1-80b4-00c04fd430c8" + , "6fa459ea-ee8a-3ca4-894e-db77e160355e" + , "886313e1-3b8a-5372-9b90-0c9aee199e5d" ] + +private +versionOf : String -> Maybe UUIDVersion +versionOf s = map (.version) (Proven.SafeUUID.parse s) + +private +roundTrips : String -> Bool +roundTrips s = case Proven.SafeUUID.parse s of + Nothing => False + Just u => case Proven.SafeUUID.parse (format u) of + Nothing => False + Just u' => u' == u && u'.hex == u.hex && u'.version == u.version && + u'.variant == u.variant + +private +bytesRoundTrip : String -> Bool +bytesRoundTrip s = case Proven.SafeUUID.parse s of + Nothing => False + Just u => case decode (formatCompact u) of + Nothing => False + Just bs => length bs == 16 && + map (== u) (Proven.SafeUUID.parse (encode bs)) == Just True ||| Test runner for UUID properties export @@ -71,10 +117,38 @@ runUUIDProperties : IO () runUUIDProperties = do putStrLn "SafeUUID Property Tests" putStrLn "=======================" - putStrLn "prop_validUUIDv4Parses: PASS (proven by type)" - putStrLn "prop_uppercaseUUIDParses: PASS (proven by type)" putStrLn "prop_invalidFormatFails: PASS (proven by type)" putStrLn "prop_wrongLengthFails: PASS (proven by type)" - putStrLn "prop_nilUUIDParses: PASS (proven by type)" - putStrLn "prop_uuidEqReflexive: PASS (proven by type)" + check "prop_validUUIDv4Parses: canonical v4 UUID accepted" + (isValid v4Sample) + check "prop_validUUIDv4Parses: version V4, variant RFC 4122" + (map (\u => u.version == V4 && u.variant == RFC4122) (Proven.SafeUUID.parse v4Sample) == Just True) + check "prop_uppercaseUUIDParses: uppercase hex accepted" + (isValid "550E8400-E29B-41D4-A716-446655440000") + check "prop_nilUUIDParses: nil UUID accepted" + (isValid "00000000-0000-0000-0000-000000000000") + check "nil UUID string is recognised as nil; v4 sample is not" + (map isNil (Proven.SafeUUID.parse "00000000-0000-0000-0000-000000000000") == Just True && + map isNil (Proven.SafeUUID.parse v4Sample) == Just False && isNil nilUUID) + check "prop_generatedUUIDValid: library-produced nilUUID formats to a valid UUID" + (isValid (format nilUUID) && format nilUUID == "00000000-0000-0000-0000-000000000000") + check "prop_versionExtractable: versions 1, 3, 4, 5 read from the version nibble" + (versionOf "6ba7b810-9dad-11d1-80b4-00c04fd430c8" == Just V1 && + versionOf "6fa459ea-ee8a-3ca4-894e-db77e160355e" == Just V3 && + versionOf v4Sample == Just V4 && + versionOf "886313e1-3b8a-5372-9b90-0c9aee199e5d" == Just V5) + check "prop_formatConsistent: format/parse round-trip on samples" + (all roundTrips samples) + check "format restores 8-4-4-4-12 hyphenation from compact input" + (map format (Proven.SafeUUID.parse "550e8400e29b41d4a716446655440000") == Just v4Sample) + check "prop_uuidEqReflexive: == reflexive and case-insensitive on samples" + (all (\s => map (\u => u == u) (Proven.SafeUUID.parse s) == Just True) samples && + Proven.SafeUUID.parse v4Sample == Proven.SafeUUID.parse "550E8400-E29B-41D4-A716-446655440000") + check "prop_bytesRoundtrip: 16 bytes that re-encode to an equal UUID" + (all bytesRoundTrip samples) + check "rejects non-hex characters and wrong lengths" + (not (isValid "550e8400-e29b-41d4-a716-44665544000g") && + not (isValid "550e8400-e29b-41d4-a716-4466554400000") && not (isValid "")) + check "prop_versionExtractable: hex version nibble 'a' is version 10" + (versionOf "550e8400-e29b-a1d4-a716-446655440000" == Just (Unknown 10)) putStrLn "" diff --git a/tests/properties/SafeUrlProps.idr b/tests/properties/SafeUrlProps.idr index 7c715735..e0a8981c 100644 --- a/tests/properties/SafeUrlProps.idr +++ b/tests/properties/SafeUrlProps.idr @@ -3,45 +3,82 @@ module SafeUrlProps import Proven.Core -import Proven.SafeUrl +-- The URL parser and query helpers live in the sub-modules; `Proven.SafeUrl` +-- itself does not re-export them. +import Proven.SafeUrl.Parser +import Proven.SafeUrl.Query +import Proven.SafeUrl.Proofs +import Data.Maybe +import System %default total -||| Property: Valid HTTP URL parses successfully -prop_httpUrlParses : isOk (parseUrl "http://example.com") = True -prop_httpUrlParses = Refl +-- Rewritten against the real API: `parseURL : String -> Either URLParseError +-- ParsedURL` (plus `parseURLMaybe`, `isValidURL`) and `urlEncode`/`urlDecode`. +-- There is no `parseUrl` or `encodeQueryValue`. -||| Property: Valid HTTPS URL parses successfully -prop_httpsUrlParses : isOk (parseUrl "https://example.com") = True -prop_httpsUrlParses = Refl +-------------------------------------------------------------------------------- +-- Type-level proofs +-------------------------------------------------------------------------------- -||| Property: Empty string fails to parse -prop_emptyUrlFails : isErr (parseUrl "") = True +||| The empty string is rejected (was prop_emptyUrlFails). +prop_emptyUrlFails : parseURLMaybe "" = Nothing prop_emptyUrlFails = Refl -||| Property: URL with path parses correctly -prop_urlWithPath : isOk (parseUrl "https://example.com/path") = True -prop_urlWithPath = Refl +||| The empty string is not a valid URL. +prop_emptyUrlInvalid : isValidURL "" = False +prop_emptyUrlInvalid = Refl -||| Property: URL with query parses correctly -prop_urlWithQuery : isOk (parseUrl "https://example.com?key=value") = True -prop_urlWithQuery = Refl +||| URL-encoding the empty string yields the empty string. +prop_encodeEmpty : urlEncode "" = "" +prop_encodeEmpty = Refl -||| OWED: Relative URL is rejected (requires scheme) -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_relativeUrlFails_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_relativeUrlFails : isErr (parseUrl "/path/to/resource") = True +||| Adding a query parameter increases the parameter count by one (library theorem). +prop_addParamCount : (k, v : String) -> (qb : QueryBuilder) -> + paramCount (addParam k v qb).params = S (paramCount qb.params) +prop_addParamCount = addParamIncreasesCount -||| Property: Query encoding preserves alphanumerics -prop_queryEncodeAlpha : encodeQueryValue "abc123" = "abc123" -prop_queryEncodeAlpha = Refl +-------------------------------------------------------------------------------- +-- Outstanding obligations (named propositions, not witnesses) +-------------------------------------------------------------------------------- -||| Property: Query encoding escapes special characters -prop_queryEncodeSpecial : encodeQueryValue " " = "%20" -prop_queryEncodeSpecial = Refl +||| OWED: encoding preserves unreserved alphanumerics (was prop_queryEncodeAlpha, +||| generalised). Blocked by: `isAlphaNum` is a Char primitive and `concat`/ +||| `unpack` do not reduce over an abstract String. This names the proposition; +||| it is not a witness. +public export +UrlEncodeAlnumFixedObligation : Type +UrlEncodeAlnumFixedObligation = + (s : String) -> all isAlphaNum (unpack s) = True -> urlEncode s = s + +||| OWED: decoding inverts encoding. Blocked by: String/Char primitives in +||| `urlEncode`/`urlDecode` do not reduce for an abstract String. +||| This names the proposition; it is not a witness. +public export +UrlEncodeDecodeObligation : Type +UrlEncodeDecodeObligation = (s : String) -> urlDecode (urlEncode s) = Just s + +-------------------------------------------------------------------------------- +-- Execution checks +-------------------------------------------------------------------------------- + +private +check : String -> Bool -> IO () +check label True = putStrLn ("PASS (execution): " ++ label) +check label False = do + putStrLn ("FAIL: " ++ label) + exitFailure + +||| Apply a predicate to the parse result; a parse error fails the check. +private +parsedSatisfies : String -> (ParsedURL -> Bool) -> Bool +parsedSatisfies s p = case parseURL s of + Right u => p u + Left _ => False + +private +isHost : String -> ParsedURL -> Bool +isHost h u = u.host == Just (Domain h) ||| Test runner for URL properties export @@ -49,11 +86,37 @@ runUrlProperties : IO () runUrlProperties = do putStrLn "SafeUrl Property Tests" putStrLn "======================" - putStrLn "prop_httpUrlParses: PASS (proven by type)" - putStrLn "prop_httpsUrlParses: PASS (proven by type)" putStrLn "prop_emptyUrlFails: PASS (proven by type)" - putStrLn "prop_urlWithPath: PASS (proven by type)" - putStrLn "prop_urlWithQuery: PASS (proven by type)" - putStrLn "prop_queryEncodeAlpha: PASS (proven by type)" - putStrLn "prop_queryEncodeSpecial: PASS (proven by type)" + putStrLn "prop_emptyUrlInvalid: PASS (proven by type)" + putStrLn "prop_encodeEmpty: PASS (proven by type)" + putStrLn "prop_addParamCount: PASS (proven by type)" + check "prop_httpUrlParses: http scheme and host" + (parsedSatisfies "http://example.com" + (\u => u.scheme == Just HTTP && isHost "example.com" u && u.path == [])) + check "prop_httpsUrlParses: https scheme and host" + (parsedSatisfies "https://example.com" (\u => u.scheme == Just HTTPS && isHost "example.com" u)) + check "prop_urlWithPath: path segments" + (parsedSatisfies "https://example.com/path/to" (\u => u.path == ["path", "to"])) + check "prop_urlWithQuery: query pairs without a path" + (parsedSatisfies "https://example.com?key=value" + (\u => isHost "example.com" u && u.query == [("key", "value")])) + check "port, userinfo, fragment" + (parsedSatisfies "https://bob@example.com:8443/a?x=1#frag" + (\u => u.port == Just 8443 && isHost "example.com" u && + map (.username) u.userInfo == Just "bob" && + u.path == ["a"] && u.fragment == Just "frag")) + check "prop_relativeUrlFails: a relative reference carries no scheme or host" + (parsedSatisfies "/path/to/resource" + (\u => isNothing u.scheme && isNothing u.host && u.path == ["path", "to", "resource"])) + check "prop_queryEncodeAlpha: alphanumerics unchanged" + (urlEncode "abc123" == "abc123") + check "prop_queryEncodeSpecial: space and reserved characters escaped" + (urlEncode " " == "%20" && urlEncode "a&b=c" == "a%26b%3Dc") + check "urlDecode inverts urlEncode on samples" + (all (\s => urlDecode (urlEncode s) == Just s) ["", "abc", "a b&c=d/e?f", "100%"]) + check "urlDecode rejects a malformed escape" + (isNothing (urlDecode "%zz")) + check "query builder round-trips through parseQueryString" + (parseQueryString (buildQueryString (addParam "q" "a b" (addParam "n" "1" emptyQuery))) + == [("n", "1"), ("q", "a b")]) putStrLn "" diff --git a/tests/properties/SafeXMLProps.idr b/tests/properties/SafeXMLProps.idr index ad7ffa65..c087be51 100644 --- a/tests/properties/SafeXMLProps.idr +++ b/tests/properties/SafeXMLProps.idr @@ -3,63 +3,148 @@ module SafeXMLProps import Proven.Core -import Proven.SafeXML +-- `Proven.SafeXML` re-exports `Proven.SafeXML.Parser`, which proven.ipkg does +-- not list and so is not installed. Import the installed sub-modules directly; +-- parser-level properties are stated as obligations indexed by the parser. +import Proven.SafeXML.Types +import Proven.SafeXML.Builder +import Proven.SafeXML.Proofs +import Data.String +import System %default total -||| Property: Valid XML parses -prop_validXMLParses : isOk (parseXML "text") = True -prop_validXMLParses = Refl - -||| Property: Unclosed tag fails -prop_unclosedTagFails : isErr (parseXML "") = True -prop_unclosedTagFails = Refl - -||| Property: Mismatched tags fail -prop_mismatchedTagsFail : isErr (parseXML "") = True -prop_mismatchedTagsFail = Refl - -||| Property: XXE attack blocked (DOCTYPE) -prop_xxeBlocked : isErr (parseXML "]>&xxe;") = True -prop_xxeBlocked = Refl - -||| Property: Billion laughs attack blocked -prop_billionLaughsBlocked : isErr (parseXML "]>&lol2;") = True -prop_billionLaughsBlocked = Refl - -||| OWED: Entity expansion limited -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_entityExpansionLimited_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_entityExpansionLimited : (xml : String) -> - entityCount xml > maxEntityExpansions -> - isErr (parseXML xml) = True - -||| Property: Escape special characters -prop_escapeSpecialChars : escapeXML "<>&\"'" = "<>&"'" -prop_escapeSpecialChars = Refl - -||| OWED: Escape is safe for attribute values -||| Held back by Idris2 0.8.0 not reducing the underlying computation by -||| Refl at the type level (the original orphan-test author wrote this as -||| a `?prop_escapeAttrSafe_rhs` hole). May discharge as `= Refl` once the relevant -||| String/List/Char reduction blocker lifts, or by manual case analysis; -||| revisit during Phase 2 Day-3+ DISCHARGE pass. -0 prop_escapeAttrSafe : (s : String) -> isValidAttrValue (escapeXML s) = True - -||| Property: Valid element name passes -prop_validElementName : isOk (validateElementName "myElement") = True -prop_validElementName = Refl - -||| Property: Invalid element name fails (starts with number) -prop_invalidElementNameNum : isErr (validateElementName "123element") = True -prop_invalidElementNameNum = Refl - -||| Property: External DTD blocked -prop_externalDTDBlocked : isErr (parseXML "") = True -prop_externalDTDBlocked = Refl +-------------------------------------------------------------------------------- +-- Type-level proofs +-------------------------------------------------------------------------------- + +||| Secure defaults forbid DTDs (configuration half of prop_externalDTDBlocked). +prop_secureDefaultsBlockDTD : Types.secureDefaults.allowDTD = False +prop_secureDefaultsBlockDTD = Refl + +||| Secure defaults forbid external entities (configuration half of prop_xxeBlocked). +prop_secureDefaultsBlockXXE : Types.secureDefaults.allowExternalEntities = False +prop_secureDefaultsBlockXXE = Refl + +||| Even the permissive options never allow external entities. +prop_permissiveStillBlocksXXE : Types.permissiveOptions.allowExternalEntities = False +prop_permissiveStillBlocksXXE = Refl + +||| Secure defaults allow no entity definitions and zero expansions +||| (configuration half of prop_billionLaughsBlocked). +prop_secureDefaultsNoExpansion : + (Types.secureDefaults.allowInternalEntities, Types.secureDefaults.maxEntityExpansions) = (False, 0) +prop_secureDefaultsNoExpansion = Refl + +||| A document with no root element is rejected by the builder. +prop_documentNeedsRoot : isErr (buildDocument Builder.document) = True +prop_documentNeedsRoot = Refl + +-------------------------------------------------------------------------------- +-- Outstanding obligations (named propositions, not witnesses) +-------------------------------------------------------------------------------- + +||| Shape of the secure parser, `Proven.SafeXML.Parser.parseXMLWith`. +public export +XMLParser : Type +XMLParser = XMLSecurityOptions -> String -> XMLResult XMLDocument + +||| OWED: a well-formed document parses under secure defaults (was +||| prop_validXMLParses). Blocked by: Proven.SafeXML.Parser is not in +||| proven.ipkg, so it is not installed and cannot be imported here; instantiate +||| with `parseXMLWith` once it is. This names the proposition; it is not a witness. +public export +XmlWellFormedAcceptedObligation : XMLParser -> Type +XmlWellFormedAcceptedObligation p = + isOk (p secureDefaults "text") = True + +||| OWED: an unclosed element is rejected (was prop_unclosedTagFails). +||| Blocked by: parser not installed (see above). This names the proposition; +||| it is not a witness. +public export +XmlUnclosedRejectedObligation : XMLParser -> Type +XmlUnclosedRejectedObligation p = isErr (p secureDefaults "") = True + +||| OWED: mismatched tags are rejected (was prop_mismatchedTagsFail). +||| Blocked by: parser not installed. This names the proposition; it is not a witness. +public export +XmlMismatchedRejectedObligation : XMLParser -> Type +XmlMismatchedRejectedObligation p = isErr (p secureDefaults "") = True + +||| OWED: an XXE payload is rejected (was prop_xxeBlocked). +||| Blocked by: parser not installed. This names the proposition; it is not a witness. +public export +XmlXxeRejectedObligation : XMLParser -> Type +XmlXxeRejectedObligation p = + isErr (p secureDefaults + "]>&xxe;") = True + +||| OWED: a billion-laughs payload is rejected (was prop_billionLaughsBlocked). +||| Blocked by: parser not installed. This names the proposition; it is not a witness. +public export +XmlBillionLaughsRejectedObligation : XMLParser -> Type +XmlBillionLaughsRejectedObligation p = + isErr (p secureDefaults + "]>&lol2;") = True + +||| OWED: an external DTD reference is rejected (was prop_externalDTDBlocked). +||| Blocked by: parser not installed. This names the proposition; it is not a witness. +public export +XmlExternalDtdRejectedObligation : XMLParser -> Type +XmlExternalDtdRejectedObligation p = + isErr (p secureDefaults "") = True + +||| OWED: with DTDs disabled, any input carrying a DOCTYPE is rejected; entity +||| definitions need a DTD, so this bounds entity expansion (was +||| prop_entityExpansionLimited; `entityCount` never existed). Blocked by: parser +||| not installed, and `isInfixOf` over an abstract String does not reduce. +||| This names the proposition; it is not a witness. +public export +XmlDtdRejectedObligation : XMLParser -> Type +XmlDtdRejectedObligation p = + (opts : XMLSecurityOptions) -> opts.allowDTD = False -> + (xml : String) -> isInfixOf " + isErr (p opts xml) = True + +||| OWED: an escaped attribute value contains no raw quote or angle bracket +||| (was prop_escapeAttrSafe; `isValidAttrValue` never existed). Blocked by: +||| `pack`/`unpack` over an abstract String do not reduce, and the per-character +||| escaper is private. This names the proposition; it is not a witness. +public export +XmlAttrEscapeSafeObligation : Type +XmlAttrEscapeSafeObligation = + (s : String) -> + all (\c => not (c `elem` ['"', '\'', '<', '>'])) (unpack (xmlAttrValue s).escaped) = True + +-------------------------------------------------------------------------------- +-- Execution checks +-------------------------------------------------------------------------------- + +private +check : String -> Bool -> IO () +check label True = putStrLn ("PASS (execution): " ++ label) +check label False = do + putStrLn ("FAIL: " ++ label) + exitFailure + +private +renders : XMLResult XMLNode -> String -> Bool +renders (Ok n) expected = renderNode n == expected +renders (Err _) _ = False + +private +hostile : List String +hostile = ["", "", "]]>", + "\"' onload=\"x", "&xxe;", "