diff --git a/.devflow/features/index.md b/.devflow/features/index.md index 18fe520b..34f623ce 100644 --- a/.devflow/features/index.md +++ b/.devflow/features/index.md @@ -2,7 +2,7 @@ - **bundler-plugins** — packages/bundler-utils/, packages/vite-plugin/, packages/rollup-plugin/, packages/webpack-loader/, packages/rspack-loader/ — Use when adding a new bundler integration, modifying the emitted-module contract, debugging HMR behavior, working on the CJS compatibility shim, updating the transformer/loader factory, registering a new package in the release pipeline, or investigating why a .mds file emits unexpected output. Keywords: createMdsTransformer, createMdsLoader, bundler-utils, vite-plugin, rollup-plugin, webpack-loader, rspack-loader, addWatchFile, addDependency, handleHotUpdate, emitted module contract, export default string, export default Message[], safeJsonForJs, escapeForJs, metadata, kind, markdown, messages, discriminated union, mds.d.ts, MdsMessage, string | MdsMessage[]. - **mds-cli** — crates/mds-cli/ — Use when adding new subcommands, changing output-path resolution logic, modifying the watch architecture, adding new compile paths, updating mds.json config handling, debugging stdout/stderr stream separation, investigating exit codes, adding directory-mode build/check support, working on stale-output cleanup, or on the CLI's input refusals (forbidden path characters, directory-argument validation, or the entry-overwrite refusal). Keywords: mds build, mds check, mds watch, mds init, OutputKind, run_build, run_watch, build.rs, build/admit.rs, build/config.rs, build/directory.rs, build/entry.rs, build/flags.rs, build/out_paths.rs, build/single.rs, build/source_map.rs, build/stdio.rs, build/vars.rs, output.rs, watch.rs, input.rs, mds.json, output_dir, resolve_output_base, OutputBase, output_path_for, compile_and_write, compile_to_content, intrinsic extension, run_build_directory, run_check_directory, is_partial, collect_mds_files, probe_and_remove_stale, canonicalize_out_dir, output_base_no_ext, continue-on-error, subtree mirror, symlink guard, 10 MiB cap, load_config, reject_forbidden_output_path, reject_forbidden_resolved_output_path, resolve_directory_argument, ensure_existing_mds_file, forbidden path characters, #265, #413, #417, #425, #428, read_canonical_source, read_stdin, read_at_most, safe_path, safe_file_display, escape_path_for_message, display_native_path, #409, mds init filename, admit_output, refuse_output_over_entry, file_identity, EntryPaths, WatchedPath, Watched, WorkingDir, CompileWriteOutcome, has_sidecar_head, verify_then_delete_map. -- **mds-compiler** — crates/mds-core/ — Use when changing the MDS compile pipeline: directives, scope, frontmatter, reserved keys, imports, @extends, local data sources, path security, output caps. Keywords: resolver, read_data, MAX_DATA_FILES. +- **mds-compiler** — crates/mds-core/, crates/mds-fetch/, crates/mds-cli/src/build/ — Use when changing the MDS compile pipeline: directives, scope, frontmatter, imports, @extends, data and URL entries, step compiles, network policy, mds-fetch, path security. Keywords: resolver, read_data, StepCtx. - **mds-fmt** — crates/mds-core/src, crates/mds-cli/src — Use when modifying the mds fmt formatter engine (crates/mds-core/src/formatter.rs), the mds fmt CLI subcommand (crates/mds-cli/src/fmt.rs), any change to mds-core's output model (clean_output, evaluate_nodes, @message/@define body evaluation, the lexer's fence recognition) that could silently break the formatter's compile-equivalence guarantee, or changes to the shared directory walker (output.rs). Keywords: mds fmt, format_str, format_str_with, format_str_named, FormatterInvariant, clean_output, compile-equivalence, idempotent, assert_equivalent, structural_equivalent, strip_trailing_insignificant_text, in_raw_content, raw_content_spans, protected_spans, R1 R2 R3 R4, safety gate, token lossiness, @message body, @define body, @block body, FmtConfig, FmtFlags, interior-verbatim contract, try_scan_fence_at, FenceMatch, deep_merge_yaml, RESERVED_MERGE_KEYS, is_default_excluded_dir, is_within_default_excluded_dir, walker exclusions, node_modules, hidden dirs, effective_parent, bare filename, atomic_write_file. - **mds-js** — packages/mds/src, packages/mds/__test__ — Use when changing the @mdscript/mds JS API, option or result types, the backend contract, or the WASM backend's file and local data pre-scanner. Keywords: compileFile, buildModulesMap, walkData, preflightData. - **mds-lint** — crates/mds-core/src/lint, crates/mds-cli/src, crates/mds-wasm/src, crates/mds-napi/src, crates/mds-python/src, packages/mds/src — Use when adding or modifying lint rules, extending the --fix pipeline, changing the JSON wire format, wiring lint into a binding layer, debugging unexpected exit codes and reverify gate refusals, or working on the ESC/bidi/newline injection defences. Keywords: mds lint, LintDiagnostic, fix_removals, fix_edits, TextEdit, FixLineSpan, diag_to_edits, LintResult, LintConfig, to_canonical_json, fix tier, reverify gate, FixOutcome, PartiallyFixed, apply_fixes_incremental, preview_fixes, PreviewOutcome, set_diag_display_path, AnalysisContext, ElseifBranch, end_offset, DefineFact, assertKnownKeys, CheckOptions, unreachable-branch, unused-variable, duplicate-import, empty-block, legacy-interpolation, is_output_neutral, all_output_neutral, Tier A Tier B Tier C, structural-standalone, compile-clean, is_standalone, sanitize_control_chars, sanitize_control_chars_wire, named_source_for_render, neutralize_source_for_render, SanitizedReport, SanitizedNode, MAX_AUX_DEPTH, EscapeMode, HUMAN WIRE, eprint_warning, safe_path, safe_inline, safe_file_display, escape_path_for_message, preview_text_for, print_discipline, reverify_failure_reason, precheck, RegressionGate, Verdict, splice_edit, apply_per_edit, summarize_rejections, fallback_cap_rejected, FALLBACK_MAX_EDITS, check_if_block, check_primary, check_elseifs, LintDirCtx, config_cache, dedup_contained_or_identical, EXIT 0 1 2 3, render_error_sanitized, eprint_error, display_sanitized, MdsError::display_sanitized, ESC-injection, CWE-150, CWE-117, bidi, Trojan-Source, CVE-2021-42574, U+061C, U+202E, U+FEFF, U+2028, U+2029, PF-014, PF-005, construction-time sanitization, per-field rule, Cow, #176, ADR-008, ResultSink, from_rules_checked, relative_display, write_bytes, PF-020, #309, emit-ordering, Severity FromStr, ParseSeverityError, SeveritySpellings, parse_rule_severities, deserialize_lint_rules, sanitizeControlCharsWire, assertKnownKeys, format_unknown_keys_error, TOCTOU, read_module_file, resolve_path_intrinsic_keyed, #175, #418, #428, #414, #417, #413, literal-directive. diff --git a/.devflow/features/mds-compiler/KNOWLEDGE.md b/.devflow/features/mds-compiler/KNOWLEDGE.md index 738d4ca0..b07b2ec6 100644 --- a/.devflow/features/mds-compiler/KNOWLEDGE.md +++ b/.devflow/features/mds-compiler/KNOWLEDGE.md @@ -1,9 +1,9 @@ --- feature: mds-compiler -name: MDS Compiler Core (mds-core) -description: "Use when changing the MDS compile pipeline: directives, scope, frontmatter, reserved keys, imports, @extends, local data sources, path security, output caps. Keywords: resolver, read_data, MAX_DATA_FILES." +name: MDS Compiler Core (mds-core), with URL Data Entries +description: "Use when changing the MDS compile pipeline: directives, scope, frontmatter, imports, @extends, data and URL entries, step compiles, network policy, mds-fetch, path security. Keywords: resolver, read_data, StepCtx." category: domain-knowledge -directories: ["crates/mds-core/"] +directories: ["crates/mds-core/", "crates/mds-fetch/", "crates/mds-cli/src/build/"] referencedFiles: - crates/mds-core/src/lib.rs - crates/mds-core/src/evaluator.rs @@ -42,8 +42,18 @@ referencedFiles: - crates/mds-core/tests/data_paths.rs - crates/mds-core/tests/fixtures/data-path-vectors.json - crates/mds-core/tests/yaml_funnel.rs + - crates/mds-core/src/data/step.rs + - crates/mds-core/src/data/policy.rs + - crates/mds-core/src/data/request.rs + - crates/mds-core/src/data/envelope.rs + - crates/mds-core/tests/supply_chain.rs + - crates/mds-core/tests/net_sinks.rs + - crates/mds-fetch/src/lib.rs + - crates/mds-cli/src/build/net.rs + - crates/mds-cli/tests/panic_hook.rs + - crates/mds-cli/tests/cli_net.rs created: 2026-06-26 -updated: 2026-11-24 +updated: 2026-11-25 --- # MDS Compiler Core (mds-core) @@ -64,8 +74,13 @@ updated: 2026-11-24 - **KB-AP-9** Check a data path only as written, or add a path rule as a unit test only: the segment and containment rules run again on the exact resolved key, and a new rule is a row in the shared vector table `tests/fixtures/data-path-vectors.json`. Details: Local Data Sources. - **KB-AP-10** Parse data JSON or YAML outside `resolver/frontmatter.rs`: `tests/yaml_funnel.rs` permits the parse entry points only there (and `serde_json` also in `vars_json.rs`), so the node and memory caps apply to every data parse. Details: Local Data Sources. - **KB-INV-4** Only `ModuleCache::compiling` (the compile entry points) reads data files. `ModuleCache::tooling` (check, lint, fmt) reads none and marks unreplayed entries pending; a plain `ModuleCache` reports one as `mds::undefined_var`. Details: Local Data Sources. -- **KB-INV-5** No data file is read before the whole-graph preflight passes over every module. An unreplayed URL entry gives `mds::network_denied` before any local read; a kept graph refusal blocks every read, but the first fault that the compile meets itself wins. Details: Local Data Sources. +- **KB-INV-5** No data file is read before the whole-graph preflight passes over every module. In a compile with no step context, an unreplayed URL entry gives `mds::network_denied` before any local read; a kept graph refusal blocks every read, but the first fault that the compile meets itself wins. Details: Local Data Sources. - **KB-INV-6** A `@message` role never depends on data: `expr_reads_data` must see each expression form that can carry a data value. Details: Local Data Sources. +- **KB-AP-11** Call a step engine function (anything that `bind_with_engine` reaches) directly from resolver code: resolver code reaches the engine only through `step::bind_url_entry` and the `StepCtx.bind` pointer, so the WASM build, which starts no step compile, keeps no engine code. A direct call links the engine into WASM and can break the CI WASM size limit; the source scan `engine_reach_findings` (`data/step_tests.rs`) pins the shape. Details: URL Data Entries. +- **KB-INV-7** The core makes every network decision: the allow list, the import opt-in, the method, the strict URL parse, each redirect hop, the secret binding and the response secret scan. A sender follows no redirect and only checks addresses with `NetworkPolicy::check_address`. A policy can only narrow (`NetworkPolicy::narrow`), and the secret header rule (entry module only) runs on every URL entry, replayed too. Details: URL Data Entries. +- **KB-INV-8** The raw response bodies of one compile, of every status (3xx and errors too), share one total that `FetchState::with_response` counts (`MAX_RESPONSE_BODY_BYTES_PER_COMPILE`). A host that sends in parallel caps each send at its share of `FetchState::body_bytes_left`, or a group in flight passes the total. Details: URL Data Entries. +- **KB-AP-12** Format a value that can hold a planted secret (the secret, stderr, stdout, an error message) into a test assertion message: the code scan of the repository flags it. Use a fixed message, and check that the value is absent before a later assertion prints the stream (`assert_no_secret` in `crates/mds-cli/tests/cli_net.rs`). Details: Anti-Patterns. +- **KB-AP-13** Write expected CLI path text with `/` in a CLI test: the CLI prints `.\mds.json` on Windows, and the test fails only in the Windows CI job. Build the text with `MAIN_SEPARATOR_STR` and keep the full sentence (`cli_net.rs`). Details: Anti-Patterns. ## Overview @@ -316,7 +331,7 @@ Normative text: `spec.md` §4.12 "Data sources", the "Local data limits" of §4. - Reach: a data path can name any `.json`, `.yaml` or `.yml` file that these rules permit below the project root (the nearest directory with `.git` or `.mdsroot`), not only files near the template, and a template can put that content in its output. `SECURITY.md` states this reach; change the two together. ### Entry-point roles -- The compile entry points (`compile*`, `compile_native_fs`, `compile_virtual_fs` and their wrappers) use `ModuleCache::compiling` (`data.compile` and `analyze_data` on). They read and bind local files. An unreplayed URL entry fails the compile with `mds::network_denied`: this release sends no network request. +- The compile entry points (`compile*`, `compile_native_fs`, `compile_virtual_fs` and their wrappers) use `ModuleCache::compiling` (`data.compile` and `analyze_data` on). They read and bind local files. An unreplayed URL entry fails the compile with `mds::network_denied`: a plain compile has no step context and sends no request. Only the step entry points (`ModuleCache::stepping`) bind URL entries; see URL Data Entries. - `check*`, `lint*`, `fmt` and the lint fix verify use `ModuleCache::tooling` (`analyze_data` only). They read no data file (WASM `check_and_lint_read_no_data_file`, napi `D-6`, `tooling_checks_pending_variables_without_opening_data` in `tests/data_tooling.rs`). Unreplayed entries become pending names, the warning `data pending; output was not evaluated: ` is added, and module evaluation is skipped while `data.pending` is set. `tooling_output_in_dir` returns `None` then, so `fmt` and the fix verify do not compare output. - A plain `ModuleCache` (`new`, `native`, `virtual_fs`, `with_fs`) has neither flag: an unreplayed entry is `mds::undefined_var`, and `dependencies()` lists modules only. - A runtime variable with the entry's name replays it in every role: the graph marks it replayed, and no file or URL is used. @@ -324,7 +339,7 @@ Normative text: `spec.md` §4.12 "Data sources", the "Local data limits" of §4. ### Preflight, graph and first-fault order - `prepare_data` runs once, at the root, when `analyze_data` is on. `collect_data_preflight` reads every module source into a snapshot before any module evaluates, and `check_scope` builds the graph of each scope (`FrontmatterNames::Preflight`). - `graph::analyze`: the root of each `Source::Url` reference must name a winning entry, a frontmatter key or a runtime variable (`unknown data reference name`). `check_levels` removes one level for each pass; a pass with nothing ready is a cycle (`blocked by a data dependency cycle`); more than `MAX_DATA_LEVELS` levels is `mds::resource_limit`. A file entry has no dependencies. -- In the compile role, the frontier (unreplayed URL entries, in module first-resolution order, then declaration order) gives `MdsError::network_denied` before any local read (`url_frontier_precedes_local_reads_and_follows_module_then_declaration_order`). +- In the compile role with no step context (`data.net` is `None`), the frontier (unreplayed URL entries, in module first-resolution order, then declaration order) gives `MdsError::network_denied` before any local read (`url_frontier_precedes_local_reads_and_follows_module_then_declaration_order`). - A preflight refusal does not return at once. `graph_refusal` keeps it; the compile continues from the snapshot and reports its own first fault, `bind_data` returns the refusal and reads nothing, and `pop_resolving` returns it at root close when no other fault came first (`a_later_missing_import_does_not_replace_the_first_fault_of_the_compile`, `a_refused_graph_check_still_blocks_every_data_read` in `tests/data_graph.rs`). - `bind_data` reads each distinct canonical key once for each compile (the `data.files` memo; `one_canonical_file_is_read_once_across_three_modules`). @@ -352,6 +367,70 @@ The compile memory budget also counts data: `read_file` reserves one `MAX_DATA_F - A bad data file is `mds::yaml`, `data file "", entry "": invalid data`. JSON and YAML data parse through `parse_data_json_with` and `parse_data_yaml_with` in `resolver/frontmatter.rs`; `yaml_parse_sites_are_funnelled` and `json_parse_sites_are_funnelled` (`tests/yaml_funnel.rs`) refuse a parse entry point in another file (`vars_json.rs` is the one other JSON owner). - Lint (`lint/facts.rs`): each entry is a `FmVarKind::DataEntry` fact that `unused-variable` reports with "data entry" text; each URL reference root counts as a use; `shadow-variable` reports a `@for` variable or `@define` parameter over an entry (`ShadowKind::DataEntry`). +## URL Data Entries (step compiles, `mds-fetch`, `mds build --allow-net`, #405) + +Normative text: `spec.md` §4.12 ("Replay and network access", "Network access") and the `SECURITY.md` bullet "URL data entries"; change the two with the code. Core code: `src/data/step.rs` (the step engine), `policy.rs`, `request.rs`, `url.rs` (the one strict URL parser), `encode.rs` (reference expansion into a URL or a header), `envelope.rs`, `digest.rs` (SHA-256 and HMAC). The resolver calls the engine from `bind_data` (`resolver/module_scope.rs`); `prepare_data` (`resolver/process.rs`) refuses the frontier only when there is no step context. + +### Roles and the host loop +- `ModuleCache::stepping(fs, StepCtx)` is `compiling` plus `data.net = Some(ctx)`. It is the only role with a step context; the tooling roles and a plain compile have none. +- Public step entry points: `compile_step_native_fs`, `compile_step_str` and `compile_step_virtual_fs`. Each takes the normal compile arguments plus `&FetchContext` and `&FetchState`, and gives `Step::Done(Box)` or `Step::Need(Vec)`. Each round is a fresh compile with a fresh budget: it derives every request again and runs every check again, so the core keeps no state between rounds (`every_resume_runs_every_check_again` in `tests/data_step.rs`). +- `FetchState` holds responses only, keyed by `RequestId`. `with_response` refuses a second response for one ID (`mds::invalid_options`) and a response past `MAX_REQUESTS_PER_COMPILE` (`mds::resource_limit`). It also adds each raw body to one total (KB-INV-8); a body past it is `MdsError::response_bodies_exceeded` (`mds::resource_limit`), and `body_bytes_left` gives the rest. `StepCtx::finish` refuses a response that the compile did not consume (`mds::invalid_options`), so a host cannot give a value for a request that the core did not derive. Pending data with no request, or a request with no pending entry, is `mds::internal`. +- `bind_data` walks the graph in level order. For a URL entry, `bind_url_entry` gives `Bound::Value` (bound like a file value) or `Bound::Pending` (the name goes into `pending` and `data.pending` is set). An entry whose reference root is pending is pending too, with no request of its own. +- `CompileResult::remote_inputs` lists each bound entry as `RemoteInput { module, entry, template, origin }`, in template form. `dependencies` holds files only, never a URL. + +### The `StepCtx.bind` pointer keeps the engine out of the WASM build +`StepCtx` has a field `bind: BindFn`. Only `StepCtx::new` sets it (to `bind_with_engine`), and only `FetchContext::start` calls `StepCtx::new`, from the step entry points. `bind_url_entry` calls the engine through this pointer. `mds-wasm` calls no step entry point, so the linker drops every function that only `bind_with_engine` reaches. `check_secret_module` is the one engine function that `bind_data` calls directly: it is small, and it must also run in a plain compile. The measure of this rule is the WASM size limit of `.github/workflows/ci.yml` (`WASM_SIZE_LIMIT`); use the CI-measured size, because a local build with another `wasm-opt` or compiler gives another number. `code_outside_the_engine_reaches_it_through_the_bind_pointer_only` in `data/step_tests.rs` pins the shape (KB-AP-11). Its `engine_reach_findings` walks all of `src/`, asserts that each needed file is in the walk, and finds an engine name outside `ENGINE_FILES` or a direct call at the pointer site; `the_engine_scan_reports_each_planted_reach` plants each reach, one in a child module too. To keep the scan narrow, `scan_secrets` and `request_label` are private and `StepCtx::new` is `pub(super)`. + +### Engine order for one entry (`derive`, then `follow`) +1. `check_secret_module`: a secret header outside the entry module is `mds::data` ("a secret header is allowed in the entry module only"). +2. A header in `SENDER_HEADERS` (`host`, `content-length`, `transfer-encoding`, `connection` and the other framing names, and the method override names `x-http-method-override`, `x-http-method`, `x-method-override`; any ASCII case) is `mds::data` ("a request cannot set this header"): a `host` header would name a host that the allow list never checked, and an override header would change the method that the core set. +3. The literal origin of the URL as declared; `check_method` (GET and HEAD only; another method is refused at `Layer::Method`). +4. A reference to a pending root gives `Bound::Pending`. +5. The URL is expanded (`encode::expand`, `Target::Url`; the budget charges twice `MAX_URL_BYTES` before), parsed by `url::parse_absolute`, and its origin must equal the literal origin: a reference cannot change the host. Then `check_origin`: the allow list first, then the import opt-in for an entry of an imported module. +6. `request_headers`: a text header is expanded through `Target::Header`; a secret header is bound with `policy.bind_secret(name, declared origin)`, its prefix plus value must fit `MAX_HEADER_VALUE_BYTES`, and the request keeps only the descriptor `HeaderValue::Secret { name, prefix }`, never the value. +7. `Request::new` builds the identity; then `follow` reads the response chain: + - each hop is a new request with its own ID, at most `MAX_REDIRECTS` hops; the memo is keyed by `(RequestId, envelope flag)`; + - `TransportFailure::AddressRefused` is a refusal at `transport-address` (`mds::network_denied`); another failure is `mds::network` with the fixed text of its kind; the response header bytes and the body cap (`MAX_RESPONSE_BYTES`) are checked again, for every status and before the redirect match; + - a 301, 302, 303, 307 or 308 answer goes to `redirect`: exactly one `location`, UTF-8, no host secret value in it, `url::parse_location`, then `check_hop` (the hop count first, as `mds::resource_limit`; then https to http is refused; then the allow list). `Hop::keeps_header` drops each secret header and each `CREDENTIAL_HEADERS` header on a hop to another origin; + - a 2xx answer binds; another answer from 300 to 599 that is not a redirect (300 and 304 too) binds only with the envelope; another status is `mds::network`. A table test in `data/step_tests.rs` pins each redirect status with and without the envelope, and 300 and 304. A HEAD answer binds `Value::Null` as its body. A body goes through `convert`, the parse funnel of data files, and `admit_bytes` counts it against the data byte total; + - `scan_secrets` refuses a value that holds the exact bytes of a host secret value in a string or an object key (`response-check`). A changed form (base64, percent encoding) is not found. + +### Policy (`policy.rs`) +- The network is off until a host builds `NetworkPolicy::new(items)` (one to `MAX_ALLOW_ITEMS` items). `AllowItem::parse` accepts `host`, `host:port`, `https://host[:port]` and `http://host:port`: an exact origin, with no path, wildcard, upper-case letter or trailing dot. It reads the host through `url::parse_absolute`, so one parser reads every host. +- `narrow(items, imports)` is the one narrowing rule of every host surface. Each item must be `within` an item of the wider policy (the same origin; an IP item with a written port only when the wider item also has a written port, because such a port can open a refused address). `imports` can be true only when the wider policy allows imports. The secrets stay the same. +- `check_address` refuses each address in `REFUSED_V4` and `REFUSED_V6` (loopback, private, link-local, shared, multicast, the IPv4-compatible `::/96` (which holds the unspecified and loopback addresses), IPv4-mapped, IPv4-translated, 6to4, both NAT64, Teredo and site-local ranges, and others). A range that embeds an IPv4 address is refused whole; `address_table_refuses_both_edges_of_each_range` (`policy_tests.rs`) pins both edges of each range and the next address outside it, and `spec.md` §4.12 lists the same ranges. Such an address passes only when an allow item is that exact IP address with that exact written port; an IPv4-mapped IPv6 address never equals an IPv4 item. A `const` block asserts that each range is a valid prefix. The core does no name lookup: the sender calls this check. +- `Secret::new(name, SecretValue, origin)`: an identifier name, an `https` origin only; at most `MAX_SECRETS`, each name once. `SecretValue` has no `Display` and no `Serialize`, its `Debug` shows no value, and `expose_for_send` is its one accessor. The core calls `bind_secret` for each secret header, and the sender calls it again before it writes the header. +- `Refusal` is a `Layer` plus a fixed `&'static str`; code outside the core cannot build one. A message shows the layer name (`Layer::name`, for example `response-check: ...`) and never input text. + +### Header declarations and the secret form (`decl.rs`) +- A request map has the keys `url`, `method`, `accept`, `headers`, `body`, `cache` and `envelope` (a bool). +- A `CREDENTIAL_HEADERS` name (`authorization`, `proxy-authorization`, `cookie`, `x-api-key`, any case) with a string value is refused: "use the secret form for this header". +- The secret form is the exact map `{secret, prefix}`: two keys, an identifier secret name and a literal prefix with no `{{` that passes the header byte check. A secret header is allowed in the entry module only. `bind_data` runs `check_secret_module` on every URL entry, replayed or not, in a plain compile and in a step compile, so a runtime value cannot lift the rule in an imported module or an `@extends` base (`a_replayed_secret_header_is_allowed_in_the_entry_module_only` in `tests/data_resolve.rs`). + +### Request identity (`request.rs`) +- `RequestId` is the SHA-256 of a canonical text of length-prefixed fields: the version tag `IDENTITY_VERSION`, the method, the URL, the format, the header count, the header keys in lower-case name order, and the body (empty in this release). Change the tag with any change of the text. +- A secret header enters the text as its name, the secret name, the prefix and the hex HMAC-SHA-256 of the value under the per-run `RunKey`. So two requests that differ in one header value have two IDs, and an ID permits no offline guess of a short secret. The template is not part of the identity. +- `RunKey::from_bytes` takes 32 random bytes once per run (`mds_fetch::run_key`). `RequestId::as_hex` and `parse_hex` (exactly 64 lower-case hex digits, else `RequestIdError`). `identity_bytes` is the budget charge before `Request::new`. + +### The status envelope (`envelope.rs`) +With `envelope: true`, the entry binds `{status, headers, body}` for each status from 200 to 599. A header name becomes lower case with `-` changed to `_`; a name that is then not an identifier is dropped, and `set-cookie` and `set-cookie2` are dropped. Two names that give the same key fail; a repeated header joins its values with `, `. A message names the entry and the field `headers` only, never a header name or value. The envelope puts the body one level deeper, so a body that reaches `MAX_VALUE_DEPTH` is `mds::data` on the field `body`, never `mds::internal`; the same body with no envelope binds. + +### Sinks of request text +The module doc of `step.rs` lists each sink. `request_label` builds every message about a request from the module, the entry, the URL as declared and the origin, never the expanded URL, a header value or response text. `Debug` of `Request`, `Response` and `FetchState` shows the template, the origin and sizes only. `tests/net_sinks.rs` pins this. + +### Public API +`lib.rs` re-exports `policy` (`AllowItem`, `Layer`, `NarrowError`, `NetworkPolicy`, `PolicyError`, `Refusal`, `Secret`, `SecretValue`), `request` (`HeaderValue`, `Method`, `Request`, `RequestHeader`, `RequestId`, `RequestIdError`, `RunKey`), `step` (`FetchContext`, `FetchState`, `RemoteInput`, `Response`, `Step`, `TransportFailure`) and `url` (`CheckedUrl`, `Host`, `Origin`, `Scheme`), plus `COMPILE_DEADLINE`, `MAX_PARALLEL_SENDS`, `MAX_REQUESTS_PER_COMPILE` and `MAX_REQUESTS_PER_RUN` for a driver. Each type that can grow is `#[non_exhaustive]` and has a named constructor in the same change (`Response::http`, `Response::failed`, `FetchContext::new`, `FetchState::new`, `with_response`). `network_policy_api_exists`, `request_identity_api_exists`, `step_api_exists` and `secret_binding_api_exists` in `tests/api_surface.rs` pin them from outside the crate. + +### `mds-fetch`, the one network crate +- `crates/mds-fetch` is the only crate with the HTTP, TLS and root list crates (`ureq`, `rustls`, `webpki-root-certs`). `Fetcher::new(Arc, &roots)` and `Fetcher::send(&Request, deadline) -> Response`. The sender follows no redirect (`max_redirects(0)`), uses no proxy, looks up a name once, checks every address with `check_address` and connects only to a checked address, uses TLS 1.2 or 1.3 with ring and the Mozilla roots plus the host roots, reads at most the body cap plus one byte, and keeps no connection. `clippy.toml` refuses `disable_verification`. It installs no logger: `ureq` logs request text at the debug and trace levels. The sender does not check the allow list again (it uses its policy for the address check and the secret headers only), so a host must give it the same `NetworkPolicy` as the step context. A lookup past its timeout keeps its thread until the system lookup returns; a long-running host can give its own lookup (`Fetcher::with_lookup`). +- `tests/supply_chain.rs` (in mds-core) is the gate: no `NETWORK_CRATES` name in the normal-dependency tree of `mds-core` or `mds-wasm` for any target (it reads `cargo metadata --offline --locked` and `Cargo.lock`), and no `LOGGER_CRATES` name in any workspace crate, tests included. `the_gate_finds_planted_crates` and `the_gate_fails_closed_on_an_unknown_edge` are its controls. `deny.toml` holds the license and duplicate-version exceptions of the TLS tree. + +### The CLI driver (`crates/mds-cli/src/build/net.rs`) +- Only `mds build` has network flags: `--allow-net` (a comma list), and `--allow-net-imports`, `--secret NAME=env:VAR@ORIGIN` and `--tls-root`, which need `--allow-net`. With no `--allow-net` the network stays off, whatever `mds.json` holds. The `mds.json` `network` section (`allow`, `allow_imports`) only narrows the flags through `NetworkPolicy::narrow`. `mds watch`, `check`, `lint` and `fmt` never send. +- `NetRun::from_flags` builds the policy, the `Fetcher` and the run key. `drive` runs at most `MAX_REQUESTS_PER_COMPILE` plus one rounds; one deadline starts at the first send, and each later round gets only the time left (its length is the `NetRun` field `deadline`, set to `COMPILE_DEADLINE`, with the test setter `with_deadline`; `round_two_gets_only_the_time_left_of_the_compile_deadline` pins it); `reserve` counts each round against `MAX_REQUESTS_PER_RUN` for the whole run; `send_round` sends `MAX_PARALLEL_SENDS` at a time on scoped threads, with no retry, and a failed join is `MdsError::Internal`. Each send of a group reads with `Fetcher::with_body_cap` at `body_share` (an equal share of `body_bytes_left`, at most `MAX_RESPONSE_BYTES`), and `add_group` adds the group to the state before the next group starts; a `BodyTooLarge` under a share below the one-response cap is `MdsError::response_bodies_exceeded` (KB-INV-8). `compile_native` and `compile_source_text` select the plain or the step compile; a directory build compiles each file through `compile_pinned_to_content` in `build.rs`. +- The driver prints nothing: the core builds each message about a request, and a `--secret` message names the index, the name and the variable, never the value or the flag text. +- The panic gate (`tests/panic_hook.rs`): `each_catch_wraps_one_compile_call_and_nothing_else` and `compile_reach_findings` start from `COMPILE_CALLS` and follow each call BY NAME into every mds-cli function with that name; a reached call that ends with a `WRITES` name fails. A call whose path starts with an `OTHER_CRATES` prefix is not followed. So a driver helper with the same name as a mds-cli function that writes (`start`, `compile_source`, the `failed` methods of the lint sinks) makes the gate fail: rename it, or write a core call with its `mds::` path (`mds::Response::failed`). A new compile call inside a catch must be added to `COMPILE_CALLS`. + ## Severity has one parser, shared by every surface (#175, #418) - `Severity` (`lint/diagnostic.rs`) hand-implements `serde::Deserialize` by deserializing to `String` first and parsing it with `FromStr` — so `mds.json`'s `lint.rules` values and every binding's `rules` map accept exactly the same four spellings, with NO case folding, trimming or escape decoding (`"Warn"` and `" warn"` are both rejected; napi/WASM used to decode escapes before comparing, so spelling the leading letter as a JSON unicode escape (U+0077, followed by "arn") configured `warn`). `Severity::ALL = [Off, Info, Warn, Error]` is what both `FromStr` and the spelling-list `Display` helper (`SeveritySpellings`) iterate; `as_str()`/`Display` print the one canonical spelling. `ParseSeverityError` (`#[non_exhaustive]`, carries no copy of the rejected input, so its own message is always safe to print raw) is the sole error `str::parse::()` returns: `unknown severity; expected "off", "info", "warn", or "error"`. @@ -452,6 +531,9 @@ Mixed-content errors surface as `mds::mixed_content` from both `compile*` and `c - **Treating `VirtualFs::with_aliases` as applying to entry resolution** — it only affects `normalize_in_dir` (imports); an entry key is always taken as given, unaliased - **KB-AP-2 — Reserving a frontmatter key at fewer than all the reserved-key sites**: the sites are listed in Fence Opt-In and Indented Directives. A missing site leaks the key into scope (`build_scope_from_frontmatter`), the merge (`RESERVED_MERGE_KEYS`), standalone output (the `RESERVED_OUTPUT_KEYS` entry, which also feeds the proof and the form messages) or `unused-variable` (`RESERVED`); a missing data site lets a data entry take the key as its name (`RESERVED_NAMES`) or treats the key as a scope name (`is_scope_key`). Add the key to the output table with its form message, then audit the other lists at their SYNC POINT comments. - **KB-AP-3 — A lexer step that does not move `pos`**: `Lexer::run` stops with `mds::internal` instead of looping. Every new `step` branch must consume at least one character or return an error. +- **KB-AP-11 — A direct call into the step engine from resolver code**: the WASM build compiles the resolver but starts no step compile, so the linker can drop the engine only while the sole path into it is the `StepCtx.bind` pointer that `StepCtx::new` sets. A new direct call (for example to `derive`, `follow` or a policy check that only the engine needs) from `bind_data`, `prepare_data` or other resolver code keeps the engine in `mds-wasm`. The source scan `engine_reach_findings` fails on it; the CI WASM size check stays the measure of the linked code. A new engine file goes into `ENGINE_FILES` and a new engine function name into `ENGINE_NAMES`. Add a new engine behavior inside `bind_with_engine`'s reach. A check that must also run in a plain compile (as `check_secret_module`) stays small and is called directly. +- **KB-AP-12 — A planted secret in an assertion message**: `assert!(!stderr.contains(SECRET), "{}", stderr)` prints the stream when the check fails, and the stream can hold the planted value. Use a fixed message (`"stderr must not show the secret value"`), and run the absence check (`assert_no_secret`) before an assertion that prints stderr. This applies to each test that plants a secret value, in the core and in the CLI. +- **KB-AP-13 — `/` in expected CLI path text**: the CLI joins its own paths with the platform separator, so the `mds.json` prefix of a `network.allow[i]` refusal is `.\mds.json` on Windows. Build the expected text as `format!(".{MAIN_SEPARATOR_STR}mds.json network.allow[2]: ...")`, keep the full sentence, and never normalize the output side, so a real change of the text still fails. ## Gotchas @@ -468,6 +550,9 @@ Mixed-content errors surface as `mds::mixed_content` from both `compile*` and `c - **KB-AP-5 — Merged `@extends` frontmatter is not stripped**: `frontmatter_prefix` takes `MarkdownFrontmatter::Standalone` raw text through the stripper, but `MarkdownFrontmatter::Merged` text (from `serialize_merged_frontmatter`) is emitted as is. The merge already drops reserved keys at depth 0, so a reserved key in the merged mapping is a compiler bug and gives a real `mds::internal` check, not a silent strip. Each base is proved at its own parse, so a bad spelling in a base fails before the merge. `fmt` returns the form error itself: `formatter.rs` lets `is_frontmatter_form_message` errors pass before the structural fallback, so a refused form is never "verified" by token comparison. - **KB-AP-6 — Two scanners read `type: mds`**: `is_type_mds_line` (`resolver/module.rs`, decides whether a `.md` file is MDS) trims the value and accepts only `mds`, `"mds"` or `'mds'`. `ReservedOutputKey::matches_line` (the stripper) also accepts a trailing ` #` comment. Both match only unindented lines and neither parses YAML, so a spelling change in one leaves the two disagreeing. The parse proof catches only the stripper side. - The `+mds` marker is the last blank-separated word of the info string. A longer word that holds it (`x+mds`) is not the marker and is refused as a reserved word. +- **KB-INV-7 — Where each network check runs**: a sender gives a redirect answer back as it is, so the core checks each hop with `check_hop` and drops the secret and credential headers on a hop to another origin. A check that only the sender runs is a check that another host surface can skip. The address check is the one exception: only the sender sees the lookup answer, so it calls `NetworkPolicy::check_address` and reports `TransportFailure::AddressRefused`, which the core turns into a `transport-address` refusal. Before the replay fix, only the request step checked the secret header rule, so a replayed entry with a secret header passed in an imported module; the check now lives in `bind_data` too, for every URL entry. +- The panic gate of `mds-cli` follows calls by name, not by type. A new helper in `build/net.rs` with a common name (`start`, `failed`, `compile_source`) can lead the walk to an unrelated mds-cli function that writes, and the gate fails with "`` reaches ``, which calls ``". Rename the helper or write the core call with its `mds::` path. The walk does not follow a function pointer, a trait object or another crate. +- A step compile reads its local data files again in each round (`a_data_file_changed_between_two_steps_is_read_again` in `tests/data_step.rs`): the rounds share no file memo. ## Key Files @@ -504,12 +589,24 @@ Mixed-content errors surface as `mds::mixed_content` from both `compile*` and `c - `crates/mds-core/tests/data_*.rs` — data behavior by stage: `data_paths.rs` (both `read_data` backends), `data_limits.rs` (each cap and its order), `data_graph.rs` (first-fault order), `data_role.rs` (role gate and lint facts), `data_tooling.rs` (roles and frontier order), `data_extends.rs`, `data_output.rs`, `data_convert.rs`, `data_resolve.rs` - `crates/mds-core/tests/fixtures/data-path-vectors.json` — the shared data path vector table (`portable`, `windows`) - `crates/mds-core/tests/yaml_funnel.rs` — source-scan gate: YAML parse entry points only in `resolver/frontmatter.rs`, JSON ones only there and in `vars_json.rs` +- `crates/mds-core/src/data/step.rs` — the step engine: `StepCtx` and its `bind` pointer, `bind_url_entry`, `check_secret_module`, `derive`, `follow`, `redirect`, `scan_secrets`, `request_label`; `FetchContext`, `FetchState` (and its body total), `Step`, `Response`, `TransportFailure`, `RemoteInput`; `step_tests.rs` holds the engine reach scan (`engine_reach_findings`, `ENGINE_FILES`) +- `crates/mds-core/src/data/policy.rs` — `NetworkPolicy` (`new`, `narrow`, `check_address`, `check_origin`, `check_hop`, `bind_secret`, `check_method`), `AllowItem`, `Secret`, `SecretValue`, `Refusal`, `Layer`, the refused address tables +- `crates/mds-core/src/data/request.rs` — `Request`, `RequestId`, `RunKey`, `HeaderValue`, the canonical identity text and `identity_bytes` +- `crates/mds-core/src/data/decl.rs` — also `CREDENTIAL_HEADERS`, `SENDER_HEADERS` and the `{secret, prefix}` form (`secret_parts`) +- `crates/mds-core/src/data/url.rs`, `envelope.rs`, `encode.rs` — the strict URL parser, the status envelope, reference expansion into a URL or a header +- `crates/mds-core/tests/data_step.rs`, `tests/net_sinks.rs`, `tests/supply_chain.rs` — the host loop, the sinks of request text, the network crate and logger gate +- `crates/mds-fetch/src/` — `Fetcher` (`send.rs`), the checked name lookup (`resolve.rs`), the roots (`tls.rs`), `run_key` (`lib.rs`) +- `crates/mds-cli/src/build/net.rs` — `NetFlags`, `NetRun` (`from_flags`, `drive`, `reserve`, `send_round`, `with_deadline`), `body_share`, `add_group`, `compile_native`, `compile_source_text`, `effective_policy`, `parse_secret` +- `crates/mds-cli/tests/cli_net.rs` — end-to-end `mds build --allow-net` tests with local listeners (`assert_no_secret`, the proxy variables, the narrowing messages) +- `crates/mds-cli/tests/panic_hook.rs` — the panic gate: `COMPILE_CALLS`, `WRITES`, `OTHER_CRATES`, `compile_reach_findings` ## Related - Feature: mds-cli — consumes `CompileResult` and `CompiledOutput`; derives output extension from `OutputKind::from(&compiled.output)`; its own directory-argument and output-path refusals now call `NativeFs::check_directory`/`reject_forbidden_path` (#413) and its `lint.rules` reader calls `parse_rule_severities` (#175/#418); `mds build` and `mds watch` never write an output over a data file that the run reads (`build_never_writes_over_a_data_file_it_reads` in `crates/mds-cli/tests/cli_data.rs`) -- Feature: mds-napi — builds the canonical discriminated-union wire object from `CompileResult` via `build_canonical_result`; its `rules` option now reads through `parse_rule_severities`; `lintVirtual` counts data keys apart from modules- Feature: mds-js — TypeScript `CompileResult = MarkdownResult | MessagesResult` union mirrors this Rust type; its WASM-backend file pre-scanner mirrors `check_module_bytes`/`check_module_type`/`scan_import_records`/`VirtualFs::with_aliases` via `preflightModule`/`scanImportRecords`/`moduleAliases` (#414) -- Feature: mds-lint — the `literal-directive` rule reports the conditional lines that these opt-ins leave literal; `unused-variable` and `shadow-variable` read the data entry facts; `Severity`, `parse_rule_severities` and `apply_fixes_incremental` live here; consult it for the fix-tier and reverify-gate model +- Feature: mds-napi — builds the canonical discriminated-union wire object from `CompileResult` via `build_canonical_result`; its `rules` option now reads through `parse_rule_severities`; `lintVirtual` counts data keys apart from modules +- Feature: mds-cli — also owns `mds build --allow-net` (`crates/mds-cli/src/build/net.rs`), the only host surface in this release that runs step compiles; its `mds.json` `network` section narrows the flags through `NetworkPolicy::narrow` +- Feature: mds-js — TypeScript `CompileResult = MarkdownResult | MessagesResult` union mirrors this Rust type; its WASM-backend file pre-scanner mirrors `check_module_bytes`/`check_module_type`/`scan_import_records`/`VirtualFs::with_aliases` via `preflightModule`/`scanImportRecords`/`moduleAliases` (#414) +- Feature: mds-lint — the `literal-directive` rule reports the conditional lines that these opt-ins leave literal; `unused-variable` and `shadow-variable` read the data entry facts; `insecure-data-origin` and `literal-credential-header` (`lint/rules/`) read the URL entry declarations, never a response; `Severity`, `parse_rule_severities` and `apply_fixes_incremental` live here; consult it for the fix-tier and reverify-gate model - Feature: source-map-security — `relativize_source`/`source_root` path-relativization choke point; this KB's `SourceTable`/`MapBuilder`/`FragmentMap` section (#416) covers the source-SHARING model that choke point's callers rely on - Lesson: an alternate code path silently bypassing a resource/security check — cited above for the pre-#155 `let _ =` anchor-failure swallow and for why `EvalBudget` is one-per-chain, not one-per-region - Lesson: a host-path leak fixed on one surface stays live on its siblings — cited above for `NotMdsFile`'s pre-#417 shape and the design-time census that found #413/#414/#417's remaining sinks before they shipped diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fc136e49..17933816 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1446,28 +1446,75 @@ jobs: echo "$OUTPUT" exit 1 fi - - name: Wait for crates.io index to update + - name: Wait for crates.io index to update (mds-core) + env: + CRATE: mds-core run: | # Bounded poll — max 20 attempts × 15 s = 300 s (5 min), then fail with # a clear message. Avoids the former unbounded sleep 30 that silently - # masked races on slow registry propagation. + # masked races on slow registry propagation. Both poll steps run this + # block, each with its own CRATE. VERSION=$(cargo metadata --no-deps --format-version 1 \ - | grep -o '"name":"mds-core","version":"[^"]*"' \ + | grep -o "\"name\":\"$CRATE\",\"version\":\"[^\"]*\"" \ + | grep -o '[0-9][^"]*' | head -1) + test -n "$VERSION" || { echo "::error::no workspace version for $CRATE"; exit 1; } + echo "Polling crates.io for ${CRATE}@${VERSION} (max 20 × 15 s)" + MAX=20 + for i in $(seq 1 "$MAX"); do + if curl -sf --max-time 20 --connect-timeout 10 \ + "https://crates.io/api/v1/crates/${CRATE}/${VERSION}" \ + -H "User-Agent: mds-release-ci/1.0" \ + | grep -qF "\"num\":\"${VERSION}\""; then + echo "${CRATE}@${VERSION} is visible in crates.io (attempt $i/$MAX)" + exit 0 + fi + echo " Attempt $i/$MAX: not yet visible — sleeping 15 s..." + sleep 15 + done + echo "::error::${CRATE}@${VERSION} not visible in crates.io after $((MAX * 15)) s" + exit 1 + - name: Publish mds-fetch + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + run: | + # Same idempotency guard as mds-core above. mds-fetch needs mds-core in + # the index, and mds-cli needs mds-fetch. + if OUTPUT=$(cargo publish -p mds-fetch 2>&1); then + echo "$OUTPUT" + elif echo "$OUTPUT" | grep -qE "already (uploaded|exists|published)"; then + echo "::notice::mds-fetch already published — idempotent re-run, skipping" + echo "$OUTPUT" + else + echo "::error::mds-fetch publish failed" + echo "$OUTPUT" + exit 1 + fi + - name: Wait for crates.io index to update (mds-fetch) + env: + CRATE: mds-fetch + run: | + # Bounded poll — max 20 attempts × 15 s = 300 s (5 min), then fail with + # a clear message. Avoids the former unbounded sleep 30 that silently + # masked races on slow registry propagation. Both poll steps run this + # block, each with its own CRATE. + VERSION=$(cargo metadata --no-deps --format-version 1 \ + | grep -o "\"name\":\"$CRATE\",\"version\":\"[^\"]*\"" \ | grep -o '[0-9][^"]*' | head -1) - echo "Polling crates.io for mds-core@${VERSION} (max 20 × 15 s)" + test -n "$VERSION" || { echo "::error::no workspace version for $CRATE"; exit 1; } + echo "Polling crates.io for ${CRATE}@${VERSION} (max 20 × 15 s)" MAX=20 for i in $(seq 1 "$MAX"); do if curl -sf --max-time 20 --connect-timeout 10 \ - "https://crates.io/api/v1/crates/mds-core/${VERSION}" \ + "https://crates.io/api/v1/crates/${CRATE}/${VERSION}" \ -H "User-Agent: mds-release-ci/1.0" \ | grep -qF "\"num\":\"${VERSION}\""; then - echo "mds-core@${VERSION} is visible in crates.io (attempt $i/$MAX)" + echo "${CRATE}@${VERSION} is visible in crates.io (attempt $i/$MAX)" exit 0 fi echo " Attempt $i/$MAX: not yet visible — sleeping 15 s..." sleep 15 done - echo "::error::mds-core@${VERSION} not visible in crates.io after $((MAX * 15)) s" + echo "::error::${CRATE}@${VERSION} not visible in crates.io after $((MAX * 15)) s" exit 1 - name: Publish mds-cli env: diff --git a/CHANGELOG.md b/CHANGELOG.md index 11c0e059..04a3d98e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,8 +37,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 YAML document, and control characters in keys and strings. It changes CRLF in strings to LF. Each canonical data file is read once per compile. See spec §4.12. - A runtime variable with the name of an entry replaces that entry, and MDS reads no file for it. -- URL entries (`https://…` strings and request maps) are checked, but this release does not - fetch them. A URL entry with no runtime value fails with the new code `mds::network_denied` +- URL entries (`https://…` strings and request maps) are checked. Without a network grant, a URL + entry with no runtime value fails with the new code `mds::network_denied` (exit 2). - The new code `mds::data` (exit 1) reports an invalid declaration or data value. A data file that does not parse gives `mds::yaml`, which names the file and the entry and shows no source text. @@ -78,10 +78,55 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 counts toward the 256-file and 32 MiB data limits. On POSIX, two data paths with one key can name two files, for example `./a.json` and `./sub/../a.json` through a linked `sub`. Then the WASM backend refuses the second path, as it refuses two such module imports. +- HTTP `GET` and `HEAD` URL entries in `mds build` (#405). `mds build --allow-net ` + sends the requests of URL entries to the listed origins only. Without the flag the network + stays off. Each allow item names one exact origin: `host`, `host:port`, + `https://host[:port]` or `http://host:port`. `--allow-net-imports` lets the URL entries of + imported modules and `@extends` bases send. `--secret NAME=env:VAR@ORIGIN` gives a header + value for one `https` origin, and `--tls-root ` adds trust roots. The `network` section + of `mds.json` (`allow`, `allow_imports`) can only narrow the flags. A refused flag or + `network` key fails with `mds::invalid_options` (exit 2). See spec §4.12 and §7.2. +- `mds build --allow-net` follows redirects through the allow list, up to 5 per entry. It + ignores the proxy environment variables and uses TLS 1.2 or 1.3 with the Mozilla roots and the + `--tls-root` files. Stdin and directory builds send too. `mds watch`, `mds check`, `mds lint` + and `mds fmt` have no network flags and send nothing. The napi, WASM and Python bindings and + `@mdscript/mds` do not send in this release: a URL entry with no runtime value fails with + `mds::network_denied`, as before. +- A request map can set `envelope: true` to bind `{status, headers, body}` for a final status + from 200 to 599. Without it, a status that is not 2xx fails. +- The new code `mds::network` (exit 2) reports a failed send or a status that is not 2xx. A + refused request fails with `mds::network_denied` (exit 2) and names the check. A data value in + a request URL or header that is not a string, a boolean or an exact integer fails with + `mds::type_error`. Messages show the URL as declared and the origin only. +- New network limits: 64 requests per compile, 512 per `mds build` run and 200 MiB of response + bodies per compile, of every status (`mds::resource_limit`, exit 3); 16 KiB of response + headers, 10 MiB of response body, also for a redirect answer, 10 s per request and 30 s of + network work per compile (`mds::network`, exit 2). See spec §4.1 "Network limits". +- Lint: `insecure-data-origin` reports a request map with an `http://` URL. + `literal-credential-header` reports a header with literal text when its name contains + `token`, `secret`, `api-key`, `apikey` or `password`. Both warn by default and are never fixed. +- Rust API: the step compiles `compile_step_native_fs`, `compile_step_virtual_fs` and + `compile_step_str`, with `FetchContext`, `FetchState`, `Step`, `Request`, `RequestId`, + `Response`, `TransportFailure`, `NetworkPolicy`, `AllowItem`, `Secret`, `SecretValue` and the + network limit constants. `FetchState::body_bytes_left` gives the body bytes that a compile can + still take, and `MdsError::response_bodies_exceeded` gives the error of that total. + `CompileResult.remote_inputs` lists the bound URL entries in template form. The canonical + JSON writes `remoteInputs` only when the list is not empty. +- The new crate `mds-fetch` holds the native sender of URL entries. `mds-cli` depends on it, + and `mds-core` and the WASM build depend on no network crate. ### Changed - Emitted standalone frontmatter keeps the author's blank lines and trailing spaces exactly as written outside removed blocks. +- A request map with an `http://` URL passes the declaration check and reaches the network + policy. It sends only when an `http://host:port` allow item names its origin (#405). +- A `GET` or `HEAD` request map with a `body` fails with `mds::data`. A `HEAD` request needs + `envelope: true` (#405). +- A request map cannot set the headers `Host`, `Content-Length`, `Transfer-Encoding`, + `Connection`, `Keep-Alive`, `Proxy-Connection`, `TE`, `Trailer` or `Upgrade`. A step compile + fails with `mds::data` before it sends (#405). +- The core sets the request method; headers that change it are refused. A request map cannot + set `X-HTTP-Method-Override`, `X-HTTP-Method` or `X-Method-Override`, with the same error (#405). ### Fixed diff --git a/Cargo.lock b/Cargo.lock index ec7ce085..6cb77805 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -73,6 +73,45 @@ version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "async-trait" version = "0.1.89" @@ -114,6 +153,21 @@ dependencies = [ "backtrace", ] +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] + [[package]] name = "bitflags" version = "2.11.1" @@ -145,6 +199,12 @@ version = "3.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + [[package]] name = "cast" version = "0.3.0" @@ -245,6 +305,32 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "dispatch2" version = "0.3.1" @@ -257,6 +343,17 @@ dependencies = [ "objc2", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -388,6 +485,17 @@ dependencies = [ "slab", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.4.2" @@ -428,6 +536,22 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "id-arena" version = "2.3.0" @@ -515,6 +639,12 @@ dependencies = [ "libc", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "leb128fmt" version = "0.1.0" @@ -563,9 +693,12 @@ dependencies = [ "ctrlc", "libc", "mds-core", + "mds-fetch", "miette", "notify", + "rcgen", "rustix", + "rustls", "serde", "serde_json", "similar", @@ -588,6 +721,17 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "mds-fetch" +version = "0.7.0" +dependencies = [ + "mds-core", + "rcgen", + "rustls", + "ureq", + "webpki-root-certs", +] + [[package]] name = "mds-napi" version = "0.7.0" @@ -668,6 +812,12 @@ dependencies = [ "walkdir", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -767,6 +917,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "notify" version = "8.2.0" @@ -803,6 +963,31 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -837,6 +1022,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -861,6 +1055,22 @@ version = "4.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d211803b9b6b570f68772237e415a029d5a50c65d382910b879fb19d3271f94d" +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64", + "serde_core", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -873,6 +1083,12 @@ version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "prettyplease" version = "0.2.37" @@ -974,6 +1190,34 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rustc-demangle" version = "0.1.27" @@ -986,6 +1230,15 @@ version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + [[package]] name = "rustix" version = "1.1.6" @@ -999,6 +1252,41 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.22" @@ -1120,6 +1408,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "supports-color" version = "3.0.2" @@ -1163,6 +1457,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "target-lexicon" version = "0.13.5" @@ -1176,7 +1481,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom", + "getrandom 0.4.2", "once_cell", "rustix", "windows-sys 0.61.2", @@ -1222,6 +1527,36 @@ dependencies = [ "syn 3.0.5", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tokio" version = "1.54.1" @@ -1273,6 +1608,45 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" +dependencies = [ + "base64", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8parse" version = "0.2.2" @@ -1442,6 +1816,15 @@ dependencies = [ "semver", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "winapi-util" version = "0.1.11" @@ -1457,13 +1840,22 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" dependencies = [ - "windows-targets", + "windows-targets 0.53.5", ] [[package]] @@ -1475,6 +1867,22 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + [[package]] name = "windows-targets" version = "0.53.5" @@ -1482,58 +1890,106 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" dependencies = [ "windows-link", - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + [[package]] name = "windows_aarch64_gnullvm" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + [[package]] name = "windows_aarch64_msvc" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + [[package]] name = "windows_i686_gnu" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + [[package]] name = "windows_i686_gnullvm" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + [[package]] name = "windows_i686_msvc" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + [[package]] name = "windows_x86_64_gnu" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + [[package]] name = "windows_x86_64_gnullvm" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "windows_x86_64_msvc" version = "0.53.1" @@ -1634,6 +2090,40 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zmij" version = "1.0.21" diff --git a/Cargo.toml b/Cargo.toml index b93ea993..4f6821cc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/mds-core", "crates/mds-cli", "crates/mds-wasm", "crates/mds-napi", "crates/mds-python"] +members = ["crates/mds-core", "crates/mds-cli", "crates/mds-wasm", "crates/mds-napi", "crates/mds-python", "crates/mds-fetch"] resolver = "2" [workspace.package] @@ -72,6 +72,28 @@ similar = "3.1" # dependency edge and no package. Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT; # rust-version 1.63, within the workspace MSRV. rustix = { version = "1.1.4", default-features = false, features = ["fs", "std"] } +# The sender of URL data entries (crates/mds-fetch). Pins are exact and soak-checked on +# the crates.io API (2026-11-25; cut-off 2026-10-26). mds-core and mds-wasm never depend +# on these crates (crates/mds-core/tests/supply_chain.rs). +# ureq 3.5.0: blocking HTTP/1.1 client, MIT OR Apache-2.0, published 2026-10-21 (35 d). +# No default features: `rustls-no-provider` gives the rustls connector with no gzip, no +# root list and no crypto provider; mds-fetch sets each one itself. Its `unversioned` +# resolver and connector API can change in a minor release, so the pin is exact: review +# the adapter in crates/mds-fetch/src/send.rs on each bump. +ureq = { version = "=3.5.0", default-features = false, features = ["rustls-no-provider"] } +# rustls 0.23.46: TLS 1.2 and 1.3 with the ring provider (C compiler only, no cmake or +# nasm). Apache-2.0 OR ISC OR MIT, published 2026-10-14 (42 d). It is the first version +# with the fixes of four 2026 rustls advisories: do not take a lower version. +rustls = { version = "=0.23.46", default-features = false, features = ["ring", "std", "tls12"] } +# webpki-root-certs 1.0.11: the Mozilla root list as DER certificates, so host roots can +# join it. CDLA-Permissive-2.0, a permissive data license with no copyleft (one-crate +# exception in deny.toml). Published 2026-10-23 (33 d). +webpki-root-certs = "=1.0.11" +# rcgen 0.14.10: test-only. The TLS tests of mds-fetch make their CA, certificate and key +# at test time, so the repository holds no key. MIT OR Apache-2.0, published 2026-08-28 +# (89 d), rust-version 1.88. The ring provider only (no aws-lc-rs); `pem` writes the PEM +# form of a host root. +rcgen = { version = "=0.14.10", default-features = false, features = ["ring", "pem"] } # panic = "unwind" is required workspace-wide because mds-napi and mds-python catch # panics with catch_unwind at the host boundary and return `mds::internal` errors, and diff --git a/README.md b/README.md index 7d62fe29..7872d5d8 100644 --- a/README.md +++ b/README.md @@ -81,9 +81,10 @@ data: Each path starts with `./` or `../` and stays inside the [project root](#project-root). A runtime variable with the same name (`--set team=...`, `--vars`) replaces the entry, and then MDS reads -no file. `mds check`, `mds lint` and `mds fmt` read no data file. In this release, MDS does not -fetch a URL entry: give it a runtime value. See [spec §4.12](spec.md#412-data-sources-data) for the forms, the -conversion rules and the limits. +no file. `mds check`, `mds lint` and `mds fmt` read no data file. A URL entry sends a `GET` or +`HEAD` request only with `mds build --allow-net `, to the listed origins only. Elsewhere, +give it a runtime value. See [spec §4.12](spec.md#412-data-sources-data) for the forms, the +conversion rules, the network rules and the limits. ## Features @@ -399,6 +400,8 @@ Rules (configure via `mds.json` `lint.rules`; severities differ per rule): | `empty-block` | warn | `@if`/`@elseif`/`@else`/`@for`/`@define`/`@message` body is empty or whitespace-only (auto-fixable) | | `legacy-interpolation` | warn | Single-brace `{x}` syntax from MDS v0.x; migrates to `{{x}}` automatically (auto-fixable) | | `literal-directive` | warn | Conditional lines that stay literal: indented lines without the file opt-in, or lines in an unmarked fence with `@if …:` before `@end` (report-only). The `mds` label suppresses the fence warning. | +| `insecure-data-origin` | warn | A request map of a URL data entry names an `http://` URL (report-only) | +| `literal-credential-header` | warn | A URL data entry sets a credential header such as `X-Auth-Token` to literal text; use the secret form (report-only) | | `redundant-else` | warn | `@else` body is structurally identical to the `@if`/`@elseif` then-body | | `unreachable-branch` | **error** | Branch condition is always-true or always-false (auto-fixable) | | `duplicate-import` | **error** | Same file imported more than once (auto-fixable) | diff --git a/RELEASING.md b/RELEASING.md index 7d1cfae0..19c3f5c9 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,7 +1,7 @@ # Releasing MDS -MDS ships as a **single coordinated release**: both crates and all npm packages go -out together at the same version. This document is the ordered runbook. +MDS ships as a **single coordinated release**: the three published crates and all +npm packages go out together at the same version. This document is the ordered runbook. > The release is **deliberately a manual, triggered step.** Pushing a `v*` tag is > what starts it. Until then, nothing publishes. @@ -12,7 +12,7 @@ The [version-consistency gate](scripts/verify-versions.mjs) (run in CI and local asserts these are all equal before anything publishes: - Workspace crate version — `Cargo.toml` `[workspace.package] version` (covers - `mds-core`, `mds-cli`, `mds-wasm`, `mds-napi`, and `mds-python`) + `mds-core`, `mds-fetch`, `mds-cli`, `mds-wasm`, `mds-napi`, and `mds-python`) - Workspace member versions in `Cargo.lock` and `package-lock.json`. The gate checks the members in `scripts/release-manifest.mjs`, not transitive versions. - Every publishable `package.json`: `@mdscript/mds-napi`, `@mdscript/mds`, @@ -36,10 +36,13 @@ These are **not** automated and must be done before the first release: Provenance requires the `id-token: write` permission (already set on the publish job) plus publishing from GitHub Actions. 3. **Add the `CARGO_REGISTRY_TOKEN` repo secret** with publish rights to - `mds-core` and `mds-cli` on crates.io. The workflow cannot probe this token + `mds-core`, `mds-fetch` and `mds-cli` on crates.io. The workflow cannot probe this token (crates.io has no read-only endpoint that accepts a scoped token — see the credential probe under Pre-flight); verify it in the crates.io UI before tagging (PF-023). + - The first release with `mds-fetch` publishes a new crate name. Before that tag, + give the token the scope to publish a new crate, or publish `mds-fetch` once by + hand. After the first publish, limit the token to the three crates again. 4. **Enable GitHub private vulnerability reporting** (Settings → Code security → Private vulnerability reporting) so the SECURITY.md flow works. 5. **Configure PyPI trusted publisher** for `markdown-script` at @@ -232,10 +235,11 @@ cargo clippy --workspace --all-targets -- -D warnings # all miss broken private intra-doc links; only this command catches them. RUSTDOCFLAGS="-D warnings" cargo doc -p mds-core --no-deps cargo publish -p mds-core --dry-run -# NOTE: `cargo publish -p mds-cli --dry-run` fails locally with -# "no matching package named `mds-core` found" until mds-core is on crates.io — -# mds-cli has a path+version dep on it. This is expected; the release workflow -# publishes mds-core first (and waits for the index), then mds-cli. +# NOTE: `cargo publish -p mds-fetch --dry-run` and `cargo publish -p mds-cli --dry-run` +# fail locally with "no matching package named `mds-core` found" until mds-core is +# on crates.io — each has a path+version dep on it. This is expected; the release +# workflow publishes mds-core first (and waits for the index), then mds-fetch (and +# waits for the index), then mds-cli. # JS node scripts/check-wasm-tools.mjs --strict # Match the WASM tool pins in CI @@ -525,7 +529,9 @@ The `credential-probe` job checks the registry inputs first. After it passes, 7. **publish-crates** — blocked until `stage-and-verify-napi`, `load-test-musl-arm64`, `build-python`, AND `rehearse-publish-python` succeed. `cargo publish` `mds-core`, polls the crates.io index for up to - 5 min (bounded, max 20 × 15 s), then `mds-cli`. + 5 min (bounded, max 20 × 15 s), then publishes `mds-fetch` with the same + bounded poll, then `mds-cli`. Spec S34 in + `scripts/__test__/release-auth-probe.spec.mjs` pins this order. 8. **publish-npm**, then **publish-python** (`publish-python` `needs` `publish-npm`). The npm job checks the restored platform NOTICE files before the A3 re-run (#136). It checks the workspace pack lists before the first npm publish. @@ -552,8 +558,9 @@ the failed job tells you what has already happened: nothing publishes before | `Version gate` — cargo-about install or version check fails (#136) | Nothing | If the archive host failed temporarily, run `gh run rerun --failed`. If the pin or archive is wrong, fix it in a pull request. Verify the local install and the release dry run. If no registry has the version, move the tag to the corrected commit after CI passes. | | `build-napi`, `build-python`, `Stage + verify platform packages`, `Alpine load test (linux-arm64-musl)`, `Rehearse PyPI publish (no upload)` | Nothing | Transient (runner, Docker Hub pull, registry outage): `gh run rerun --failed` — re-runs the failed jobs and their dependents; upstream artifacts are reused. Genuine defect: land the fix, bump to the next patch version, tag that. Do not move a tag that a defect was found on. | | `Publish to crates.io` at `Publish mds-core` — the v0.4.0 case: HTTP 403 from a revoked token, run 33569514359 | Nothing | Fix the secret or cause, then `gh run rerun --failed`. | -| `Publish to crates.io` after `mds-core` is live — index poll timeout, `Publish mds-cli` failure | `mds-core@X.Y.Z` on crates.io (cannot be deleted; `cargo yank` only hides it from new resolutions) | Transient: `gh run rerun --failed` — the `mds-core` step treats "already uploaded" as success and proceeds to `mds-cli`. Defect in `mds-cli`: the version is consumed for the whole workspace (one coordinated version); land the fix, bump to the next patch, optionally `cargo yank --version X.Y.Z mds-core`, and say so in the GitHub Release body. | -| `Publish to npm` — any point | Both crates on crates.io. Zero or more `@mdscript/*` packages at X.Y.Z can be on npm. If a NOTICE or pack-list check fails, the run makes no new npm writes. | `gh run rerun --failed`: `napi prepublish` tolerates E403 for platform packages already published and `publish_if_absent` skips versions `npm view` already sees. **Do not publish from a workstation** — a laptop `npm publish` carries no OIDC provenance attestation, and that gap is permanent for the version. If a code or workflow change is required for the re-run to succeed: bump to the next patch; npm unpublish is restricted by registry policy and leaves the version number consumed either way, so retire a partial set with `npm deprecate` rather than trying to remove it. | +| `Publish to crates.io` after `mds-core` is live — index poll timeout, `Publish mds-fetch` failure | `mds-core@X.Y.Z` on crates.io (cannot be deleted; `cargo yank` only hides it from new resolutions) | Transient: `gh run rerun --failed` — the `mds-core` step treats "already uploaded" as success and proceeds to `mds-fetch`. A new-crate scope error on the first `mds-fetch` release: fix the token scope (prerequisite 3), then rerun. Defect in `mds-fetch`: the version is consumed for the whole workspace (one coordinated version); land the fix, bump to the next patch, optionally `cargo yank --version X.Y.Z mds-core`, and say so in the GitHub Release body. | +| `Publish to crates.io` after `mds-fetch` is live — index poll timeout, `Publish mds-cli` failure | `mds-core@X.Y.Z` and `mds-fetch@X.Y.Z` on crates.io | Transient: `gh run rerun --failed` — the `mds-core` and `mds-fetch` steps treat "already uploaded" as success and proceed to `mds-cli`. Defect in `mds-cli`: land the fix, bump to the next patch, optionally yank both crates at X.Y.Z, and say so in the GitHub Release body. | +| `Publish to npm` — any point | All three crates on crates.io. Zero or more `@mdscript/*` packages at X.Y.Z can be on npm. If a NOTICE or pack-list check fails, the run makes no new npm writes. | `gh run rerun --failed`: `napi prepublish` tolerates E403 for platform packages already published and `publish_if_absent` skips versions `npm view` already sees. **Do not publish from a workstation** — a laptop `npm publish` carries no OIDC provenance attestation, and that gap is permanent for the version. If a code or workflow change is required for the re-run to succeed: bump to the next patch; npm unpublish is restricted by registry policy and leaves the version number consumed either way, so retire a partial set with `npm deprecate` rather than trying to remove it. | | `Publish to PyPI` — the v0.4.1 case: `manifest unknown` on an annotated-tag-object pin (#350) | crates.io and the npm packages at X.Y.Z; `GitHub Release` was skipped | Transient: `gh run rerun --failed` (`skip-existing: true` makes the upload re-run safe). Workflow or pin defect: per the tag-immutability rule above, the fix goes to a new commit rather than the tagged one, so land it and bump to the next patch (v0.4.2 was that release), then create the partial version's GitHub Release by hand so the tag is not left bare — `gh release create vX.Y.Z --title vX.Y.Z --generate-notes --latest=false` — with a body line naming which registries the version reached (v0.4.1 was backfilled this way on 2026-09-04). | | `GitHub Release` | Everything is published | `gh run rerun --failed`, or by hand: `gh release create vX.Y.Z --title vX.Y.Z --generate-notes` (the job itself falls back to `gh release edit`). | @@ -664,8 +671,10 @@ The local pre-flight command runs all four checks. and on pushes to `main`. The verifier requires the GitHub Actions check run with this exact name. The license check accepts only the allowed licenses and crate exceptions. The bans check rejects wildcard requirements and duplicate or unused workspace dependency declarations. - Duplicate crate versions give a warning only. The checked graph has four duplicate - pairs with skips: `syn`, `unicode-width`, `windows-sys`, and `wit-bindgen`. + Duplicate crate versions give a warning only. The checked graph has six skips for + older versions: `syn`, `unicode-width`, `windows-sys` 0.52 and 0.60, `wit-bindgen`, + and `getrandom`. One tree skip covers `windows-targets` 0.52 and its eight + `windows_*` target crates. The sources check rejects dependencies from Git or registries other than crates.io. - `Rust — cargo-deny advisories` runs in `.github/workflows/deny-advisories.yml`. It runs daily at 04:23 UTC, on manual dispatch, and on pull requests that change diff --git a/SECURITY.md b/SECURITY.md index e0d36de8..b6a62f18 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -78,9 +78,39 @@ input. The compiler enforces several defense-in-depth controls: `mds check`, `mds lint`, `mds fmt` and the check and lint calls of the Rust API, the Python binding, the napi binding and the WASM binding read no data file (tests: `D-6` in `crates/mds-napi/__test__/index.spec.mjs`, `check_and_lint_read_no_data_file` in - `crates/mds-wasm/tests/web.rs`). This release sends no network request: a URL entry fails - with `mds::network_denied` unless a runtime value replaces it. `mds build` and `mds watch` + `crates/mds-wasm/tests/web.rs`). `mds build` and `mds watch` never write an output over a data file that the run reads (`mds::io`, exit 2). +- **URL data entries** (spec §4.12 "Network access", `crates/mds-core/src/data/policy.rs`, + `crates/mds-fetch`): the network is off by default. Only `mds build --allow-net ` + and the Rust step API send requests, and only `GET` and `HEAD`. Without a grant, a URL entry + with no runtime value fails with `mds::network_denied`. The napi, WASM and Python bindings, + `@mdscript/mds`, `mds watch`, `mds check`, `mds lint` and `mds fmt` send no request in this + release. The `network` section of `mds.json` can only narrow the flags, and it can never open + the network (`crates/mds-cli/tests/cli_net.rs`). + - Each allow item names one exact origin: scheme, host and port, with no wildcard. An `http` + origin needs an `http://host:port` item. A URL entry of an imported module or an + `@extends` base needs `--allow-net-imports`. A request cannot set the `Host` header or a + header that frames the message, so it reaches only the origin of its URL. + - The sender looks up a name once per request and checks every address before it connects. + It refuses the special ranges that spec §4.12 lists, such as loopback, private, + link-local and multicast addresses, unless an allow item is that exact IP address with + its port. + - The sender follows no redirect. The core checks each hop against the allow list, refuses + a hop from `https` to `http`, stops after 5 hops, and drops secret and credential headers + on a hop to another origin. + - The sender ignores the proxy environment variables. It uses TLS 1.2 or 1.3 with the + certificate check always on. The trust roots are the Mozilla list and the `--tls-root` + files, never the system or environment roots. + - A host secret (`--secret NAME=env:VAR@ORIGIN`) binds to one `https` origin and fills a + header value only. In a directory build, each `.mds` file of the tree that is not a + partial is its own entry module with the same network flags, so each such file can use + the host secret. A message, a request ID and a `Debug` view never show its value. A + response that holds the exact value fails the request. **Residual:** this check finds + exact bytes only, so a server that returns the value in a changed form (for example + base64 or percent encoding) is not detected. + - Messages show the URL as declared and the origin, never the expanded URL, a header + value or response text. The request, redirect, size and time limits are in spec §4.1 + "Network limits". - **Directory and watch entries**: a directory build, check, lint or fmt compares each entry with its walked canonical path, plus the walk's device and inode on Unix. `mds watch` compares the directory argument with its watched canonical directory before each rebuild. @@ -305,13 +335,17 @@ place each check runs, and the tests that pin them — in `spec.md` §4.6 | Max data references | 256 per data entry, in its URL, headers and body together, before the data graph check | `limits.rs` (`MAX_DATA_REFS_PER_ENTRY`) | | Max data graph depth | 16 levels of references between data entries | `limits.rs` (`MAX_DATA_LEVELS`) | | Max data text | 32 MiB (33,554,432 bytes) of data file text per compile, and of data text in a binding's virtual module map | `limits.rs` (`MAX_DATA_BYTES_PER_COMPILE`) | +| Max requests | 64 per compile, 512 per `mds build` run, 5 redirects per entry, 8 in flight at one time | `limits.rs` (`MAX_REQUESTS_PER_COMPILE`, `MAX_REQUESTS_PER_RUN`, `MAX_REDIRECTS`, `MAX_PARALLEL_SENDS`) | +| Max response size | 16 KiB of status line and headers, 10 MiB of body | `limits.rs` (`MAX_RESPONSE_HEADER_BYTES`, `MAX_RESPONSE_BYTES`) | +| Network time | 10 s per request, 30 s of network work per compile | `limits.rs` (`REQUEST_TIMEOUT`, `COMPILE_DEADLINE`) | The data limits and their messages are in [spec §4.1](spec.md#41-variables-yaml-frontmatter) -"Local data limits". A data file also counts toward the compile memory budget: the budget -keeps the converted value of each distinct data file once per compile. +"Local data limits", and the network limits in "Network limits". A data file also counts +toward the compile memory budget: the budget keeps the converted value of each distinct data +file once per compile. A response body counts as a data file does. -These limits apply to the quantities and scopes in the table. They do not bound -elapsed time. +These limits apply to the quantities and scopes in the table. Apart from the two network +times, they do not bound elapsed time. In a compile or a check, the compile memory budget counts an estimate of the syntax tree of each module: a cached import, an `@extends` base, the file entry and the string diff --git a/about.toml b/about.toml index 291b0879..eb26dc61 100644 --- a/about.toml +++ b/about.toml @@ -1,4 +1,5 @@ # List the policy allow list first, then exception licenses in deny.toml order (#136). +# The crate tables below accept their exception license for that one crate only. accepted = ["MIT", "Apache-2.0", "ISC", "CC0-1.0", "Unicode-3.0", "Zlib", "Apache-2.0 WITH LLVM-exception"] # Include the native addon targets and the WASM target (#136). targets = [ @@ -21,3 +22,11 @@ ignore = false [miniz_oxide.clarify] license = "MIT" files = [{ path = "LICENSE-MIT.md", checksum = "799e9ca9d179295ef372f25d3769cdda7d25bb2668add6a6a1e22d1e4c678b8d" }] + +# Accept the permissive data license for the Mozilla root list of the sender only. +[webpki-root-certs] +accepted = ["CDLA-Permissive-2.0"] + +# Accept BSD-3-Clause terms for the constant-time crate of the TLS library only. +[subtle] +accepted = ["BSD-3-Clause"] diff --git a/crates/mds-cli/Cargo.toml b/crates/mds-cli/Cargo.toml index 48cedb01..58bb5119 100644 --- a/crates/mds-cli/Cargo.toml +++ b/crates/mds-cli/Cargo.toml @@ -30,6 +30,8 @@ debug-panics = [] [dependencies] mds = { package = "mds-core", path = "../mds-core", version = "0.7.0" } +# The sender of URL data entries for `mds build --allow-net`. +mds-fetch = { path = "../mds-fetch", version = "0.7.0" } clap = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } @@ -49,6 +51,10 @@ tempfile = { workspace = true } [dev-dependencies] tempfile = { workspace = true } thiserror = { workspace = true } +# The TLS tests of `tests/cli_net.rs` make their CA, certificate and key at test time +# and serve them with rustls, so the repository holds no key. +rcgen = { workspace = true } +rustls = { workspace = true } [target.'cfg(unix)'.dev-dependencies] libc = "0.2" diff --git a/crates/mds-cli/src/build.rs b/crates/mds-cli/src/build.rs index f52e88d4..b1e24a5f 100644 --- a/crates/mds-cli/src/build.rs +++ b/crates/mds-cli/src/build.rs @@ -7,6 +7,7 @@ mod config; mod directory; mod entry; mod flags; +mod net; mod out_paths; mod single; mod source_map; @@ -26,6 +27,8 @@ pub(crate) use config::{compile_inputs, load_config, run_reads, source_inputs, P #[cfg(test)] pub(crate) use config::{BuildConfig, MdsConfig}; pub(crate) use entry::{auto_detect_mds_file, resolve_input}; +pub(crate) use net::NetFlags; +use net::NetRun; pub(crate) use out_paths::{ reject_forbidden_output_flags, resolve_output_path_for_kind, OutputKind, }; @@ -43,7 +46,7 @@ pub(crate) use vars::{ /// Exit codes: /// - 0: success (never returned here — handled by happy path) /// - 1: logical or syntax error (invalid data, undefined variable, arity mismatch, recursion) -/// - 2: I/O error, file-system error, or denied network access +/// - 2: I/O error, file-system error, denied network access or a network failure /// - 3: resource limit exceeded (output too large, too many iterations) /// - 101: internal compiler error /// @@ -64,7 +67,9 @@ pub(crate) fn exit_code(err: &miette::Error) -> i32 { MdsError::Io { .. } | MdsError::FileNotFound { .. } | MdsError::NotMdsFile { .. } - | MdsError::NetworkDenied { .. } => 2, + | MdsError::NetworkDenied { .. } + | MdsError::Network { .. } + | MdsError::InvalidOptions { .. } => 2, MdsError::ResourceLimit { .. } => 3, MdsError::Internal => crate::output::PANIC_EXIT, // R4: --set/--set-string collision is a usage error over runtime @@ -171,41 +176,64 @@ pub(crate) fn messages_json(messages: &[impl serde::Serialize]) -> serde_json::R /// result — the caller does not specify it. This is the pure "compile" step used by the /// watch loop for content-based dedup. /// -/// `build` calls this directly; `mds watch` calls it for its entry and every source -/// once it has checked that the path it compiles still leads to the file it watches. -/// -/// Pass `opts = mds::CompileOptions::default()` from watch callers that do not want -/// source maps; the watch paths never emit maps so they always use the default. +/// `mds build` calls this for a file argument. With `net`, step compiles send the +/// requests of the URL entries; with `None`, the network stays off. /// /// # PF-004 compliance -/// All file reads go through `mds::compile_with_deps_opts` or -/// `mds::compile_str_with_deps_opts` (which use the resolver that enforces -/// MAX_FILE_SIZE). Stdin input is read through `read_stdin` which enforces the same cap. +/// All file reads go through the resolver of `mds::compile_native_fs`, +/// `mds::compile_step_native_fs` or the string compiles, which enforces MAX_FILE_SIZE. +/// Stdin input is read through `read_stdin` which enforces the same cap. /// There is no bare `std::fs::read_to_string`. pub(crate) fn compile_to_content( input: &Path, runtime_vars: Option>, quiet: bool, opts: mds::CompileOptions, + net: Option<&NetRun>, ) -> Result { - let result = if input == Path::new("-") { + if input == Path::new("-") { // Stdin: compile from source string with the working directory as base_dir // (`None` — see `read_stdin`). read_stdin enforces MAX_FILE_SIZE (PF-004). let source = read_stdin()?; // AD-211-1 / AD-211-5: a string-source compile labels its errors `` // (resolver's SOURCE_LABEL). Relabel to the uniform CLI sentinel here, at the // boundary that knows the input was stdin. - mds::compile_str_with_deps_opts(&source, None, runtime_vars, opts) - .map_err(|e| crate::output::relabel_stdin_error(&e, &source))? - } else { - // File path: compile_with_deps_opts routes through the resolver which enforces - // MAX_FILE_SIZE and check_symlink (PF-004 compliance). - mds::compile_with_deps_opts(input, runtime_vars, opts).map_err(miette::Error::from)? - }; + let result = net::compile_source_text(&source, runtime_vars, opts, net) + .map_err(|e| crate::output::relabel_stdin_error(&e, &source))?; + return compiled_content(result, quiet); + } + // File path: the resolver enforces MAX_FILE_SIZE and check_symlink (PF-004). + compile_pinned_to_content( + || Ok(mds::NativeFs::new()), + input, + runtime_vars, + quiet, + opts, + net, + ) +} + +/// Compile a native entry with the filesystem and entry pin that `fs` gives each +/// compile. With `net`, step compiles send the requests of the URL entries. +fn compile_pinned_to_content( + fs: impl Fn() -> Result, + input: &Path, + runtime_vars: Option>, + quiet: bool, + opts: mds::CompileOptions, + net: Option<&NetRun>, +) -> Result { + let result = + net::compile_native(fs, input, runtime_vars, opts, net).map_err(miette::Error::from)?; compiled_content(result, quiet) } -/// Compile a native entry through the caller's filesystem and entry pin. +/// Compile a native entry through the caller's filesystem and entry pin, with the +/// network off: `mds watch` compiles its entry and every source through it once it has +/// checked that the path it compiles still leads to the file it watches. A URL entry +/// with no runtime value fails with `mds::network_denied`. +/// +/// The watch paths never emit maps, so they pass `mds::CompileOptions::default()`. pub(crate) fn compile_native_to_content( fs: mds::NativeFs, input: &Path, @@ -258,6 +286,8 @@ pub(crate) struct BuildArgs { pub(crate) inline: bool, /// `--embed-sources` CLI flag: include source text in sourcesContent[]. pub(crate) embed_sources: bool, + /// `--allow-net`, `--allow-net-imports`, `--secret` and `--tls-root`. + pub(crate) net: NetFlags, } pub(crate) fn run_build(args: BuildArgs) -> Result<()> { @@ -273,6 +303,7 @@ pub(crate) fn run_build(args: BuildArgs) -> Result<()> { no_source_map, inline, embed_sources: flag_embed_sources, + net, } = args; // #265, #390: refuse a hostile output location before anything is read or compiled. let output = reject_forbidden_output_flags(output.as_deref(), out_dir.as_deref())?; @@ -298,6 +329,7 @@ pub(crate) fn run_build(args: BuildArgs) -> Result<()> { no_source_map, inline, flag_embed_sources, + net, }; // Directory mode: compile every non-partial .mds file in the tree. @@ -345,21 +377,18 @@ fn run_build_directory( dir: &Path, out_dir: Option, vars: RuntimeVars, - quiet: bool, - source_map: bool, + flags: directory::WriteFlags, embed_sources: bool, - inline: bool, + net: Option<&NetRun>, ) -> Result<()> { use crate::output::{is_partial, output_base_no_ext}; - use directory::{setup_walk, write_file, WriteFlags, WriteOutcome}; + use directory::{setup_walk, write_file, WriteOutcome}; let setup = setup_walk(dir, out_dir.as_ref(), vars.vars_file.as_deref())?; let runtime_vars = vars.vars; - let flags = WriteFlags { - quiet, - source_map, - inline, - }; + let directory::WriteFlags { + quiet, source_map, .. + } = flags; let mut ok_count: usize = 0; let mut fail_count: usize = 0; @@ -375,19 +404,16 @@ fn run_build_directory( .with_source_map(source_map) .with_include_sources_content(embed_sources) .with_source_map_base(base_no_ext.parent().map(Path::to_path_buf)); - let pin = match crate::output::walked_pin(&setup.walk, file, dir, &setup.canonical_dir) { - Ok(pin) => pin, - Err(e) => { - crate::output::eprint_file_failure(e.into()); - fail_count += 1; - continue; - } + // Each compile of the file, one per network round, is pinned to the walk. A walk + // entry with no pin fails this file alone. + let fs = || { + crate::output::walked_pin(&setup.walk, file, dir, &setup.canonical_dir) + .map(|pin| mds::NativeFs::new().with_entry_pin(pin)) }; - let fs = mds::NativeFs::new().with_entry_pin(pin); let compiled = crate::output::catch_compile( file, AssertUnwindSafe(|| { - compile_native_to_content(fs, file, runtime_vars.clone(), quiet, opts) + compile_pinned_to_content(fs, file, runtime_vars.clone(), quiet, opts, net) }), ); match compiled { @@ -434,6 +460,17 @@ mod tests { 1, ), (MdsError::network_denied(&[("main.mds", "entries")]), 2), + ( + MdsError::network( + "main.mds", + "entries", + "https://a.example/", + "https://a.example", + "request timed out", + ), + 2, + ), + (MdsError::invalid_options("x"), 2), (mds::module_count_exceeded(), 3), ]; for (error, expected) in errors { diff --git a/crates/mds-cli/src/build/config.rs b/crates/mds-cli/src/build/config.rs index ad5854e0..bab55777 100644 --- a/crates/mds-cli/src/build/config.rs +++ b/crates/mds-cli/src/build/config.rs @@ -32,6 +32,48 @@ pub(crate) struct MdsConfig { /// warning — an accepted asymmetry, not an oversight (see CHANGELOG). #[serde(default)] pub(crate) lint: LintCliConfig, + /// The `network` section: it can only narrow the grant of `mds build --allow-net`, + /// and with no flag it opens nothing. An unknown key and an item that is not in the + /// allow-item grammar fail config loading, for every command that loads `mds.json`. + #[serde(default)] + pub(crate) network: Option, +} + +/// mds.json `network` section. Each key can only narrow the flags of `mds build`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct NetworkConfig { + /// The allow list. Each item must permit no request that the `--allow-net` list + /// refuses. + #[serde(default, deserialize_with = "deserialize_allow_items")] + pub(crate) allow: Option>, + /// The import opt-in. `true` needs `--allow-net-imports`. + #[serde(default)] + pub(crate) allow_imports: Option, +} + +/// `network.allow` read by [`mds::AllowItem::parse`], the one item parser of every host +/// surface. An item that it refuses fails with its fixed reason and the item index, never +/// the item text. +fn deserialize_allow_items<'de, D>( + deserializer: D, +) -> std::result::Result>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let texts = Vec::::deserialize(deserializer)?; + let mut items = Vec::with_capacity(texts.len()); + for (index, text) in texts.iter().enumerate() { + match mds::AllowItem::parse(text) { + Ok(item) => items.push(item), + Err(refused) => { + return Err(serde::de::Error::custom(format!( + "network.allow[{index}]: {refused}" + ))) + } + } + } + Ok(Some(items)) } /// mds.json `lint` section: per-rule severity overrides. diff --git a/crates/mds-cli/src/build/directory.rs b/crates/mds-cli/src/build/directory.rs index ead231d2..9e586fe8 100644 --- a/crates/mds-cli/src/build/directory.rs +++ b/crates/mds-cli/src/build/directory.rs @@ -8,6 +8,7 @@ use miette::Result; use super::config::compile_inputs; use super::config::{load_config, run_reads, source_inputs}; use super::flags::{effective_build_flags, warn_build_flags}; +use super::net::NetRun; use super::single::BuildRun; use super::source_map::{apply_source_map_file_label, embed_map_in_content, write_sidecar_map}; use super::vars::RuntimeVars; @@ -31,6 +32,7 @@ pub(super) fn build_directory_mode( no_source_map, inline, flag_embed_sources, + net, } = run; // Reject -o/--output in directory mode: output goes to files, not a single destination. if output.is_some() { @@ -51,15 +53,21 @@ pub(super) fn build_directory_mode( flag_embed_sources, ); warn_build_flags(&flags, false, quiet); + // One network grant for the whole run: its request count covers every file. + let net = NetRun::from_flags(&net, dir_config.as_ref())?; + let write = WriteFlags { + quiet, + source_map: flags.use_source_map, + inline, + }; run_build_directory( &input, out_dir, resolved, - quiet, - flags.use_source_map, + write, flags.use_embed_sources, - inline, + net.as_ref(), ) } diff --git a/crates/mds-cli/src/build/net.rs b/crates/mds-cli/src/build/net.rs new file mode 100644 index 00000000..1bb42ee4 --- /dev/null +++ b/crates/mds-cli/src/build/net.rs @@ -0,0 +1,821 @@ +//! The network of `mds build`: the `--allow-net` flags, the `mds.json` `network` section +//! that can only narrow them, and the driver loop of step compiles over the native sender. +//! +//! With no `--allow-net` the network stays off: each compile is a plain compile, and a +//! URL entry with no runtime value fails with `mds::network_denied`, whatever `mds.json` +//! holds. `mds watch`, `mds check`, `mds lint` and `mds fmt` have no network flags and +//! never send. +//! +//! The driver prints nothing. Each refusal is an `MdsError` that names a flag, a field +//! or a file, never a secret value; the core builds every message about a request. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::thread; +use std::time::{Duration, Instant}; + +use mds::{ + AllowItem, CompileOptions, CompileResult, FetchContext, FetchState, MdsError, NarrowError, + NativeFs, NetworkPolicy, Request, Response, Secret, SecretValue, Step, TransportFailure, Value, + COMPILE_DEADLINE, MAX_PARALLEL_SENDS, MAX_REQUESTS_PER_COMPILE, MAX_REQUESTS_PER_RUN, + MAX_RESPONSE_BYTES, +}; +use mds_fetch::{CertificateDer, Fetcher, SetupError}; + +use super::config::ProjectConfig; +use crate::output::{io_cause, safe_inline, safe_path}; + +/// The largest `--tls-root` file: 1 MiB, the cap of `mds.json`. +const MAX_ROOT_FILE_BYTES: u64 = 1024 * 1024; + +/// The network flags of `mds build`, as typed. +#[derive(Debug, Default)] +pub(crate) struct NetFlags { + /// `--allow-net`: the allow items. Empty keeps the network off. + pub(crate) allow: Vec, + /// `--allow-net-imports`: URL entries of imported modules can send. + pub(crate) allow_imports: bool, + /// `--secret NAME=env:VAR@ORIGIN`, each as typed. + pub(crate) secrets: Vec, + /// `--tls-root`: PEM files of extra trust roots. + pub(crate) tls_roots: Vec, +} + +/// The network grant of one `mds build` run: the policy and the per-run key of every +/// step compile, the sender, the count of the requests that the run sent, and the time +/// that the network work of one compile can take. +pub(crate) struct NetRun { + ctx: FetchContext, + fetcher: Fetcher, + sent: AtomicUsize, + /// The time of the network work of one compile, from its first send: + /// [`COMPILE_DEADLINE`] in a run. + deadline: Duration, +} + +impl NetRun { + /// The network of a run: `None` with no `--allow-net`. Otherwise the flag grant, + /// narrowed by the `network` section of the `mds.json` in force, with the host roots + /// of `--tls-root` and a new run key. + /// + /// # Errors + /// + /// `mds::invalid_options` for a flag or a `network` key that the narrowing rule + /// refuses, and `mds::io` or `mds::resource_limit` for a root file that can not be + /// read. + pub(crate) fn from_flags( + flags: &NetFlags, + config: Option<&ProjectConfig>, + ) -> Result, MdsError> { + let Some(policy) = effective_policy(flags, config)? else { + return Ok(None); + }; + let (roots, owners) = read_roots(&flags.tls_roots)?; + let fetcher = Fetcher::new(Arc::new(policy.clone()), &roots) + .map_err(|reason| root_error(&flags.tls_roots, &owners, reason))?; + let key = mds_fetch::run_key().map_err(|reason| MdsError::Io { + message: format!("cannot start the network sender: {reason}"), + })?; + Ok(Some(Self { + ctx: FetchContext::new(policy, key), + fetcher, + sent: AtomicUsize::new(0), + deadline: COMPILE_DEADLINE, + })) + } + + /// The run with a compile deadline of `deadline`, so that a test can make it short. + #[cfg(test)] + #[must_use] + fn with_deadline(self, deadline: Duration) -> Self { + Self { deadline, ..self } + } + + /// Run step compiles to the end: each round sends the requests that the compile + /// needs and runs the compile again with every response. At most one round per + /// request of a compile and one more. One deadline binds the network work of the + /// compile from its first send; each request is sent once, with no retry. The state + /// counts the raw bodies of the compile against one total, and each send reads at + /// most its share of the bytes left. + fn drive( + &self, + mut step: impl FnMut(&FetchContext, &FetchState) -> Result, + ) -> Result { + let mut deadline = None; + let mut state = FetchState::new(); + for _ in 0..=MAX_REQUESTS_PER_COMPILE { + let requests = match step(&self.ctx, &state)? { + Step::Done(result) => return Ok(*result), + Step::Need(requests) if !requests.is_empty() => requests, + // A round that needs nothing and is not done can not end. + _ => return Err(MdsError::Internal), + }; + let deadline = match deadline { + Some(deadline) => deadline, + None => *deadline.insert( + Instant::now() + .checked_add(self.deadline) + .ok_or(MdsError::Internal)?, + ), + }; + self.reserve(requests.len())?; + state = self.send_round(&requests, deadline, state)?; + } + // The core needs at most one round per request of a compile and one more. + Err(MdsError::Internal) + } + + /// Count `count` more requests of the run. Past the run cap, the round sends + /// nothing and fails. + fn reserve(&self, count: usize) -> Result<(), MdsError> { + let before = self.sent.fetch_add(count, Ordering::SeqCst); + if before.saturating_add(count) > MAX_REQUESTS_PER_RUN { + return Err(MdsError::ResourceLimit { + message: format!("one run sends at most {MAX_REQUESTS_PER_RUN} requests"), + }); + } + Ok(()) + } + + /// Send the requests of one round, at most [`MAX_PARALLEL_SENDS`] at a time, and add + /// their responses to `state` in request order. Each group enters the state before + /// the next group starts, and each send of a group reads at most its share of the + /// body bytes that the state can still take, so a group in flight can not take the + /// compile past its body total. + /// + /// # Errors + /// + /// The refusals of [`FetchState::with_response`] and of [`add_group`], and + /// `MdsError::Internal` when a send thread panics. In `mds` the panic hook ends the + /// process with the internal code first, as on any thread that catches nothing, so + /// the error is the way out only where no hook is set. + fn send_round( + &self, + requests: &[Request], + deadline: Instant, + mut state: FetchState, + ) -> Result { + for group in requests.chunks(MAX_PARALLEL_SENDS) { + let share = body_share(state.body_bytes_left(), group.len()); + let fetcher = self.fetcher.clone().with_body_cap(share); + let fetcher = &fetcher; + let mut responses = Vec::with_capacity(group.len()); + thread::scope(|scope| { + let sends: Vec<_> = group + .iter() + .map(|request| { + thread::Builder::new() + .spawn_scoped(scope, move || send(fetcher, request, deadline)) + .map_err(|_| request) + }) + .collect(); + for send_thread in sends { + responses.push(match send_thread { + // Each thread is joined, so the scope itself never panics. + Ok(handle) => handle.join().map_err(|_| MdsError::Internal), + // With no thread for it, the request is sent on this thread. + Err(request) => Ok(send(fetcher, request, deadline)), + }); + } + }); + state = add_group(state, group, responses, share)?; + } + Ok(state) + } +} + +/// Send one request before `deadline`. With no time left, it is not sent. +fn send(fetcher: &Fetcher, request: &Request, deadline: Instant) -> Response { + if Instant::now() >= deadline { + // The `mds::` path keeps this call apart from the `failed` methods of + // mds-cli's lint sinks, which tests/panic_hook.rs follows by name. + return mds::Response::failed(TransportFailure::Timeout); + } + fetcher.send(request, deadline) +} + +/// The body cap of each of `sends` sends of one group: an equal share of the `left` body +/// bytes of the compile, at most the cap of one response. The shares of a group add up +/// to at most `left`. +fn body_share(left: usize, sends: usize) -> u64 { + let share = left.checked_div(sends).unwrap_or(0); + u64::try_from(share).map_or(MAX_RESPONSE_BYTES, |share| share.min(MAX_RESPONSE_BYTES)) +} + +/// Add the responses of one group, sent with a body cap of `share`, to `state` in +/// request order. A body past a share below the cap of one response would take the +/// compile past its body total, so it fails with the error of that total. +fn add_group( + mut state: FetchState, + group: &[Request], + responses: Vec>, + share: u64, +) -> Result { + for (request, response) in group.iter().zip(responses) { + let response = response?; + // A `#[non_exhaustive]` tuple variant of another crate matches in brace form. + if share < MAX_RESPONSE_BYTES + && matches!( + response, + Response::Failed { + 0: TransportFailure::BodyTooLarge, + .. + } + ) + { + return Err(MdsError::response_bodies_exceeded()); + } + state = state.with_response(request.id(), response)?; + } + Ok(state) +} + +/// Compile the native entry `input` with the filesystem that `fs` gives each compile. +/// With `net`, step compiles send the requests of the URL entries; without it, the +/// network stays off. +pub(crate) fn compile_native( + fs: impl Fn() -> Result, + input: &Path, + runtime_vars: Option>, + opts: CompileOptions, + net: Option<&NetRun>, +) -> Result { + match net { + None => mds::compile_native_fs(fs()?, input, runtime_vars, opts), + Some(net) => net.drive(|ctx, state| { + mds::compile_step_native_fs( + fs()?, + input, + runtime_vars.clone(), + opts.clone(), + ctx, + state, + ) + }), + } +} + +/// Compile `source` (stdin) with the working directory as its base, as +/// [`compile_native`] compiles a file. +pub(crate) fn compile_source_text( + source: &str, + runtime_vars: Option>, + opts: CompileOptions, + net: Option<&NetRun>, +) -> Result { + match net { + None => mds::compile_str_with_deps_opts(source, None, runtime_vars, opts), + Some(net) => net.drive(|ctx, state| { + mds::compile_step_str(source, None, runtime_vars.clone(), opts.clone(), ctx, state) + }), + } +} + +/// The policy of a run: `None` with no `--allow-net`, so `mds.json` never opens the +/// network. Otherwise the flag grant, narrowed by the `network` section of `config`. +fn effective_policy( + flags: &NetFlags, + config: Option<&ProjectConfig>, +) -> Result, MdsError> { + if flags.allow.is_empty() { + return Ok(None); + } + let mut items = Vec::with_capacity(flags.allow.len()); + for text in &flags.allow { + match AllowItem::parse(text) { + Ok(item) => items.push(item), + Err(reason) => { + return Err(refused(format!( + "--allow-net item \"{}\": {reason}", + safe_inline(text) + ))) + } + } + } + let mut policy = NetworkPolicy::new(items.clone()) + .map_err(|reason| refused(format!("--allow-net: {reason}")))? + .with_imports(flags.allow_imports); + for (index, text) in flags.secrets.iter().enumerate() { + let (name, secret) = parse_secret(index, text)?; + policy = policy.with_secret(secret).map_err(|reason| { + refused(format!( + "--secret[{index}] \"{}\": {reason}", + safe_inline(name) + )) + })?; + } + let Some((section, shown)) = config.and_then(|config| { + let section = config.config.network.as_ref()?; + Some((section, safe_path(&config.shown_file()))) + }) else { + return Ok(Some(policy)); + }; + let narrower = section.allow.clone().unwrap_or(items); + let imports = section.allow_imports.unwrap_or(flags.allow_imports); + policy + .narrow(narrower, imports) + .map(Some) + .map_err(|reason| { + refused(match reason { + NarrowError::ItemNotAllowed { index } => format!( + "{shown} network.allow[{index}]: the item permits a request that the \ + --allow-net list refuses" + ), + NarrowError::ImportsNotAllowed => { + format!("{shown} network.allow_imports: true needs --allow-net-imports") + } + other => format!("{shown} network.allow: {other}"), + }) + }) +} + +/// One `--secret NAME=env:VAR@ORIGIN` at `index`: the host secret `NAME`, with the +/// value of the environment variable `VAR`, for requests to `ORIGIN` only. A message +/// names the index, `NAME` and `VAR`, never the value, and never the flag text, which +/// can hold a value typed by mistake. +fn parse_secret(index: usize, text: &str) -> Result<(&str, Secret), MdsError> { + let malformed = || refused(format!("--secret[{index}]: expected NAME=env:VAR@ORIGIN")); + let (name, rest) = text.split_once('=').ok_or_else(malformed)?; + let (var, origin) = rest + .strip_prefix("env:") + .and_then(|rest| rest.split_once('@')) + .ok_or_else(malformed)?; + let at = |what: String| { + refused(format!( + "--secret[{index}] \"{}\": {what}", + safe_inline(name) + )) + }; + // A text that is not a variable name can be a value typed in place of VAR, so the + // message does not show it. + if !is_env_name(var) { + return Err(at( + "the text after env: is not an environment variable name".to_owned(), + )); + } + let origin = AllowItem::parse(origin) + .map_err(|reason| at(format!("the origin: {reason}")))? + .origin(); + let value = std::env::var_os(var) + .ok_or_else(|| at(format!("the environment variable {var} is not set")))?; + let value = value + .into_string() + .ok() + .and_then(|value| SecretValue::new(value).ok()) + .ok_or_else(|| { + at(format!( + "the environment variable {var} must hold one or more visible ASCII characters" + )) + })?; + let secret = Secret::new(name, value, origin).map_err(|reason| at(format!("{reason}")))?; + Ok((name, secret)) +} + +/// `var` is a portable environment variable name: an ASCII letter or `_`, then ASCII +/// letters, digits or `_`. +fn is_env_name(var: &str) -> bool { + let mut bytes = var.bytes(); + bytes + .next() + .is_some_and(|first| first.is_ascii_alphabetic() || first == b'_') + && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') +} + +/// The roots of the `--tls-root` files, and for each root the index of its file. +fn read_roots(paths: &[PathBuf]) -> Result<(Vec>, Vec), MdsError> { + let mut roots = Vec::new(); + let mut owners = Vec::new(); + for (index, path) in paths.iter().enumerate() { + let bytes = read_root_file(path)?; + let parsed = mds_fetch::parse_pem_roots(&bytes) + .map_err(|reason| refused(format!("--tls-root file {}: {reason}", safe_path(path))))?; + owners.extend(std::iter::repeat_n(index, parsed.len())); + roots.extend(parsed); + } + Ok((roots, owners)) +} + +/// The refusal of the sender setup: a root that is not a valid trust anchor names its +/// file. +fn root_error(paths: &[PathBuf], owners: &[usize], reason: SetupError) -> MdsError { + let file = match reason { + SetupError::Root { index } => owners.get(index).and_then(|owner| paths.get(*owner)), + _ => None, + }; + match file { + Some(path) => refused(format!( + "--tls-root file {}: a root is not a valid trust anchor", + safe_path(path) + )), + None => refused(format!("--tls-root: {reason}")), + } +} + +/// The bytes of one `--tls-root` file, read as the `--vars` file is: a forbidden path +/// character and a symlink are refused, the file must be a regular file, and the read +/// stops one byte past the cap. +fn read_root_file(path: &Path) -> Result, MdsError> { + let shown = safe_path(path); + let canonical = NativeFs::check_symlink(path).map_err(|e| match e { + MdsError::ImportError { .. } => MdsError::Io { + message: format!("--tls-root file must not be a symlink: \"{shown}\""), + }, + other => other, + })?; + let cannot_read = |e: std::io::Error| MdsError::Io { + message: format!( + "cannot read --tls-root file {shown}: {}", + safe_inline(io_cause(&e)) + ), + }; + let not_regular = || MdsError::Io { + message: format!("--tls-root file {shown} is not a regular file"), + }; + // A named pipe would block the open, so the type is checked first, and again on + // the opened file. + if !std::fs::symlink_metadata(&canonical) + .map_err(cannot_read)? + .is_file() + { + return Err(not_regular()); + } + let mut file = std::fs::File::open(&canonical).map_err(cannot_read)?; + let metadata = file.metadata().map_err(cannot_read)?; + if !metadata.is_file() { + return Err(not_regular()); + } + let too_large = || MdsError::ResourceLimit { + message: format!( + "--tls-root file {shown} exceeds maximum size of {MAX_ROOT_FILE_BYTES} bytes" + ), + }; + if metadata.len() > MAX_ROOT_FILE_BYTES { + return Err(too_large()); + } + let bytes = mds::read_at_most(&mut file, MAX_ROOT_FILE_BYTES + 1, metadata.len()) + .map_err(cannot_read)?; + if bytes.len() as u64 > MAX_ROOT_FILE_BYTES { + return Err(too_large()); + } + Ok(bytes) +} + +/// A refused network option: `mds::invalid_options`, exit 2. The message is fixed text, +/// a flag or field name, and flag text escaped through `safe_inline`. +fn refused(message: String) -> MdsError { + MdsError::invalid_options(&message) +} + +#[cfg(test)] +mod tests { + use std::io::{Read, Write}; + use std::net::{TcpListener, TcpStream}; + use std::sync::atomic::AtomicBool; + + use super::*; + + fn flags(allow: &[&str]) -> NetFlags { + NetFlags { + allow: allow.iter().map(|item| (*item).to_owned()).collect(), + ..NetFlags::default() + } + } + + fn code(error: &MdsError) -> String { + error.serialize().code + } + + /// The network stays off with no `--allow-net`, also when `mds.json` names an + /// origin and the import opt-in. Control: with the flag the run has a sender. + #[test] + fn no_flag_keeps_the_network_off() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("mds.json"), + r#"{"network": {"allow": ["api.example"], "allow_imports": true}}"#, + ) + .unwrap(); + let config = super::super::load_config(dir.path()).unwrap(); + assert!(NetRun::from_flags(&flags(&[]), config.as_ref()) + .unwrap() + .is_none()); + let control = NetRun::from_flags( + &NetFlags { + allow_imports: true, + ..flags(&["api.example"]) + }, + config.as_ref(), + ); + assert!( + control.unwrap().is_some(), + "control: the flag opens the network" + ); + } + + /// A run sends at most 512 requests: request 513 fails with `mds::resource_limit` + /// before it is sent. Control: 512 pass. + #[test] + fn the_run_cap_refuses_request_513() { + let run = NetRun::from_flags(&flags(&["api.example"]), None) + .unwrap() + .unwrap(); + assert!( + run.reserve(MAX_REQUESTS_PER_RUN).is_ok(), + "control: 512 pass" + ); + let error = run.reserve(1).unwrap_err(); + assert_eq!(code(&error), "mds::resource_limit"); + assert!( + error.to_string().contains("at most 512 requests"), + "{error}" + ); + } + + /// Each send of a group reads at most its share of the body bytes that the compile + /// can still take, so the shares of a group add up to at most the bytes left. + /// Control: with room, each send keeps the cap of one response. + #[test] + fn each_send_reads_at_most_its_share_of_the_bytes_left() { + let total = FetchState::new().body_bytes_left(); + assert_eq!( + body_share(total, MAX_PARALLEL_SENDS), + MAX_RESPONSE_BYTES, + "control: with room, a send keeps the cap of one response" + ); + assert_eq!( + body_share(40 * 1024 * 1024, MAX_PARALLEL_SENDS), + 5 * 1024 * 1024 + ); + for left in [0, 7, 8 * 1024, 79 * 1024 * 1024, total] { + for sends in 1..=MAX_PARALLEL_SENDS { + let share = body_share(left, sends); + assert!(share <= MAX_RESPONSE_BYTES, "{left} bytes, {sends} sends"); + let shares = share * u64::try_from(sends).unwrap(); + assert!( + shares <= u64::try_from(left).unwrap(), + "{left} bytes, {sends} sends" + ); + } + } + } + + /// A body past a share below the cap of one response fails with the body total error + /// of the core, not the 10 MiB network text. Control: at the full cap the failure + /// enters the state, and the core reports it for its entry. + #[test] + fn a_body_past_its_share_fails_with_the_body_total_error() { + let policy = NetworkPolicy::new(vec![AllowItem::parse("api.example").unwrap()]).unwrap(); + let ctx = FetchContext::new(policy, mds::RunKey::from_bytes([7; 32])); + let source = "---\ndata:\n a: https://api.example/x\n---\n{{a}}\n"; + let step = mds::compile_step_str( + source, + None, + None, + CompileOptions::default(), + &ctx, + &FetchState::new(), + ) + .unwrap(); + let Step::Need(requests) = step else { + panic!("expected the request of the entry"); + }; + assert_eq!(requests.len(), 1); + let too_large = || vec![Ok(mds::Response::failed(TransportFailure::BodyTooLarge))]; + let error = add_group( + FetchState::new(), + &requests, + too_large(), + MAX_RESPONSE_BYTES - 1, + ) + .unwrap_err(); + assert_eq!(code(&error), "mds::resource_limit"); + assert_eq!( + error.to_string(), + "resource limit exceeded: response bodies exceed 209715200 bytes per compile" + ); + let state = add_group( + FetchState::new(), + &requests, + too_large(), + MAX_RESPONSE_BYTES, + ); + assert_eq!( + state.unwrap().len(), + 1, + "control: at the full cap the failure enters the state" + ); + } + + /// The wait of [`SlowServer`] before each answer. + const ANSWER_WAIT: Duration = Duration::from_millis(600); + /// The poll interval of [`SlowServer`] and of the wait for its end. + const POLL: Duration = Duration::from_millis(5); + + /// A listener thread on `127.0.0.1:0` that answers each request [`ANSWER_WAIT`] + /// after its head: `{"x": "next"}` for `/a` and `{"n": 1}` for another path. The + /// thread ends at a stop, and at the latest after 10 s. + struct SlowServer { + port: u16, + stop: Arc, + thread: thread::JoinHandle>, + } + + impl SlowServer { + fn start() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let port = listener.local_addr().unwrap().port(); + let stop = Arc::new(AtomicBool::new(false)); + let flag = Arc::clone(&stop); + let thread = thread::spawn(move || { + let end = Instant::now() + Duration::from_secs(10); + let mut lines = Vec::new(); + while Instant::now() < end && !flag.load(Ordering::SeqCst) { + match listener.accept() { + Ok((stream, _)) => lines.extend(answer_late(stream)), + Err(_) => thread::sleep(POLL), + } + } + lines + }); + Self { port, stop, thread } + } + + /// Stop the listener and give the request line of each request that it read. The + /// wait for the thread has a bound: its read and its write each have a limit. + fn stop(self) -> Vec { + self.stop.store(true, Ordering::SeqCst); + for _ in 0..1_000 { + if self.thread.is_finished() { + break; + } + thread::sleep(POLL); + } + assert!( + self.thread.is_finished(), + "the listener thread must end within 5 s" + ); + self.thread.join().unwrap() + } + } + + /// Read the head of one request, wait [`ANSWER_WAIT`], answer, and give the request + /// line. + fn answer_late(mut stream: TcpStream) -> Option { + stream.set_nonblocking(false).ok()?; + stream.set_read_timeout(Some(Duration::from_secs(2))).ok()?; + stream + .set_write_timeout(Some(Duration::from_secs(2))) + .ok()?; + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + while head.len() < 16 * 1024 && !head.ends_with(b"\r\n\r\n") { + if stream.read(&mut byte).ok()? == 0 { + break; + } + head.push(byte[0]); + } + let line = String::from_utf8_lossy(&head).lines().next()?.to_owned(); + let body = if line.starts_with("GET /a ") { + r#"{"x": "next"}"# + } else { + r#"{"n": 1}"# + }; + thread::sleep(ANSWER_WAIT); + // The client can have stopped its wait, and then the answer is lost. + let _ = stream.write_all( + format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + .as_bytes(), + ); + Some(line) + } + + /// One deadline binds the network work of a compile from its first send, so round 2 + /// gets only the time that is left. `b` reads `a`, so it is sent in round 2, and the + /// listener answers each request 600 ms after it. With a 900 ms deadline, `a` passes + /// (300 ms of slack for a slow runner) and `b` fails with the timeout, because at most + /// 300 ms are left for it. Control: with a 5 s deadline the chain renders. + #[test] + fn round_two_gets_only_the_time_left_of_the_compile_deadline() { + let chain = |deadline: Duration| { + let server = SlowServer::start(); + let item = format!("http://127.0.0.1:{}", server.port); + let run = NetRun::from_flags(&flags(&[&item]), None) + .unwrap() + .unwrap() + .with_deadline(deadline); + let source = format!( + "---\ndata:\n a:\n url: \"{item}/a\"\n b:\n url: \"{item}/{{{{a.x}}}}\"\n---\n{{{{b.n}}}}\n" + ); + let result = compile_source_text(&source, None, CompileOptions::default(), Some(&run)); + (item, result, server.stop()) + }; + + let (_, result, lines) = chain(Duration::from_secs(5)); + assert_eq!( + result.unwrap().output, + mds::CompiledOutput::Markdown("1\n".into()), + "control: with time left the chain renders" + ); + assert_eq!(lines.len(), 2, "control: the listener gets a and b"); + + let (item, result, lines) = chain(Duration::from_millis(900)); + let error = result.unwrap_err(); + assert_eq!(code(&error), "mds::network"); + let text = error.to_string(); + assert!( + text.contains(&format!("URL \"{item}/{{{{a.x}}}}\"")), + "round 2, the entry b, must fail: {text}" + ); + assert!(text.ends_with("the request timed out"), "{text}"); + assert!( + lines.len() == 2 && lines[1].starts_with("GET /next "), + "round 2 must be sent with the time that is left: {lines:?}" + ); + } + + /// A refused `--allow-net` item fails with `mds::invalid_options` and its fixed + /// reason. Control: a valid item passes. + #[test] + fn a_refused_allow_item_names_the_flag() { + let error = effective_policy(&flags(&["api.example", "HTTP://x"]), None).unwrap_err(); + assert_eq!(code(&error), "mds::invalid_options"); + assert!( + error.to_string().contains("--allow-net item \"HTTP://x\""), + "{error}" + ); + assert!(effective_policy(&flags(&["api.example"]), None).is_ok()); + } + + /// A `--secret` with no variable set names the secret and the variable; a value typed + /// in place of `env:VAR` is never shown. Each assertion message is fixed text, and the + /// check for the value comes first, so a failure can not show the value. + #[test] + fn a_secret_flag_names_the_secret_and_the_variable_never_a_value() { + let unset = NetFlags { + secrets: vec!["TOKEN=env:MDS_TEST_UNSET_VARIABLE_405@https://api.example".into()], + ..flags(&["api.example"]) + }; + let error = effective_policy(&unset, None).unwrap_err(); + assert_eq!( + code(&error), + "mds::invalid_options", + "an unset variable is a refused option" + ); + let text = error.to_string(); + assert!( + text.contains("--secret[0] \"TOKEN\""), + "the message must name the secret" + ); + assert!( + text.contains("MDS_TEST_UNSET_VARIABLE_405 is not set"), + "the message must name the variable" + ); + + let typed_value = NetFlags { + secrets: vec!["TOKEN=planted-secret-value".into()], + ..flags(&["api.example"]) + }; + let Err(error) = effective_policy(&typed_value, None) else { + panic!("a value typed in place of env:VAR must be refused"); + }; + let text = error.to_string(); + assert!( + !text.contains("planted-secret-value"), + "the message must not show the value" + ); + assert!( + text.contains("--secret[0]: expected NAME=env:VAR@ORIGIN"), + "the message must name the flag form" + ); + + let value_as_var = NetFlags { + secrets: vec!["TOKEN=env:planted-secret-value@https://api.example".into()], + ..flags(&["api.example"]) + }; + let Err(error) = effective_policy(&value_as_var, None) else { + panic!("a value typed in place of VAR must be refused"); + }; + let text = error.to_string(); + assert!( + !text.contains("planted-secret-value"), + "the message must not show the value" + ); + assert_eq!( + code(&error), + "mds::invalid_options", + "a value in place of VAR is a refused option" + ); + assert!( + text.contains( + "--secret[0] \"TOKEN\": the text after env: is not an environment variable name" + ), + "the message must name the secret and the reason" + ); + } +} diff --git a/crates/mds-cli/src/build/single.rs b/crates/mds-cli/src/build/single.rs index 4f94e8ef..c3a90542 100644 --- a/crates/mds-cli/src/build/single.rs +++ b/crates/mds-cli/src/build/single.rs @@ -7,6 +7,7 @@ use miette::Result; use super::admit::{admit_output, EntryPaths}; use super::config::{compile_inputs, load_config, run_reads, ProjectConfig}; use super::flags::{effective_build_flags, warn_build_flags}; +use super::net::{compile_source_text, NetFlags, NetRun}; use super::out_paths::{resolve_output_path_for_kind, warn_output_extension_mismatch, OutputKind}; use super::source_map::{ apply_source_map_file_label, compute_source_map_base, embed_map_in_content, file_name_of, @@ -26,6 +27,7 @@ pub(super) struct BuildRun { pub(super) no_source_map: bool, pub(super) inline: bool, pub(super) flag_embed_sources: bool, + pub(super) net: NetFlags, } // ── Stdin path ─────────────────────────────────────────────────────────────── @@ -39,6 +41,7 @@ pub(super) fn run_build_stdin(input: PathBuf, vars: RuntimeVars, run: &BuildRun) no_source_map, inline, flag_embed_sources, + ref net, } = *run; let flags = effective_build_flags(None, flag_source_map, no_source_map, flag_embed_sources); warn_build_flags(&flags, inline, quiet); @@ -52,10 +55,12 @@ pub(super) fn run_build_stdin(input: PathBuf, vars: RuntimeVars, run: &BuildRun) .with_include_sources_content(flags.use_embed_sources) .with_source_map_base(source_map_base); + // Stdin has no project config, so only the flags grant the network. + let net = NetRun::from_flags(net, None)?; let source = read_stdin()?; // AD-211-1 / AD-211-5: same stdin relabel as `compile_to_content`; `None` is the // working directory, shown as "." (see `read_stdin`). - let result = mds::compile_str_with_deps_opts(&source, None, vars.vars, opts) + let result = compile_source_text(&source, vars.vars, opts, net.as_ref()) .map_err(|e| crate::output::relabel_stdin_error(&e, &source))?; if !quiet { for w in &result.warnings { @@ -137,6 +142,7 @@ pub(super) fn run_build_file(input: PathBuf, vars: RuntimeVars, run: &BuildRun) no_source_map, inline, flag_embed_sources, + ref net, } = *run; let config = load_config(&input)?; let flags = effective_build_flags( @@ -156,7 +162,8 @@ pub(super) fn run_build_file(input: PathBuf, vars: RuntimeVars, run: &BuildRun) .with_include_sources_content(flags.use_embed_sources) .with_source_map_base(source_map_base); - let compiled = compile_to_content(&input, vars.vars, quiet, opts)?; + let net = NetRun::from_flags(net, config.as_ref())?; + let compiled = compile_to_content(&input, vars.vars, quiet, opts, net.as_ref())?; let inputs = compile_inputs( Some(&input), &compiled.dependencies, diff --git a/crates/mds-cli/src/main.rs b/crates/mds-cli/src/main.rs index 4090af1a..d49bd9f4 100644 --- a/crates/mds-cli/src/main.rs +++ b/crates/mds-cli/src/main.rs @@ -16,7 +16,7 @@ mod write; use build::{ build_runtime_vars, emit_duplicate_var_warnings, exit_code, parse_key_value, resolve_input, - run_build, BuildArgs, RuntimeVarArgs, + run_build, BuildArgs, NetFlags, RuntimeVarArgs, }; // ── CLI entry point ─────────────────────────────────────────────────────────── @@ -44,7 +44,7 @@ enum Commands { /// All other templates compile to Markdown (.md). /// The output extension is derived automatically from the compiled kind. #[command( - after_help = "Examples:\n mds build Auto-detect the .mds file in current dir\n mds build template.mds Compile to template.md (next to source)\n mds build chat.mds Compile @message template to chat.json\n mds build template.mds -o - Compile to stdout\n mds build template.mds -o output.md Compile to specific file\n mds build template.mds --out-dir dist Compile to dist/template.md or dist/template.json\n mds build template.mds --vars vars.json With variable overrides\n mds build template.mds --set name=Alice Set a single variable\n echo \"Hello {{name}}!\" | mds build - Compile from stdin (writes to stdout)" + after_help = "Examples:\n mds build Auto-detect the .mds file in current dir\n mds build template.mds Compile to template.md (next to source)\n mds build chat.mds Compile @message template to chat.json\n mds build template.mds -o - Compile to stdout\n mds build template.mds -o output.md Compile to specific file\n mds build template.mds --out-dir dist Compile to dist/template.md or dist/template.json\n mds build template.mds --vars vars.json With variable overrides\n mds build template.mds --set name=Alice Set a single variable\n mds build template.mds --allow-net api.example Fetch URL data entries from api.example\n echo \"Hello {{name}}!\" | mds build - Compile from stdin (writes to stdout)" )] Build { /// Input .mds file (use "-" for stdin; omit to auto-detect in current directory) @@ -87,6 +87,26 @@ enum Commands { /// Requires --source-map. #[arg(long = "embed-sources", requires = "source_map")] embed_sources: bool, + /// Let URL data entries send GET and HEAD requests to these origins (comma-separated + /// or repeatable): `host`, `host:port`, `https://host[:port]` or `http://host:port`, + /// matched exactly. Without it the network is off. mds.json `network` can only narrow it + #[arg(long = "allow-net", value_name = "ORIGINS", value_delimiter = ',')] + allow_net: Vec, + /// Let URL data entries of imported modules and @extends bases send too. + /// Requires --allow-net + #[arg(long = "allow-net-imports", requires = "allow_net")] + allow_net_imports: bool, + /// A host secret for a header of the entry module (repeatable): the value of the + /// environment variable VAR, sent to ORIGIN only. Requires --allow-net + #[arg( + long = "secret", + value_name = "NAME=env:VAR@ORIGIN", + requires = "allow_net" + )] + secret: Vec, + /// A PEM file of extra trust roots for HTTPS (repeatable). Requires --allow-net + #[arg(long = "tls-root", value_name = "FILE", requires = "allow_net")] + tls_root: Vec, }, /// Validate an MDS file without rendering #[command( @@ -558,6 +578,10 @@ fn run(cli: Cli) -> Result<()> { no_source_map, inline, embed_sources, + allow_net, + allow_net_imports, + secret, + tls_root, } => run_build(BuildArgs { input, output, @@ -570,6 +594,12 @@ fn run(cli: Cli) -> Result<()> { no_source_map, inline, embed_sources, + net: NetFlags { + allow: allow_net, + allow_imports: allow_net_imports, + secrets: secret, + tls_roots: tls_root, + }, }), Commands::Check { input, diff --git a/crates/mds-cli/src/output.rs b/crates/mds-cli/src/output.rs index b2d54b7d..10753dec 100644 --- a/crates/mds-cli/src/output.rs +++ b/crates/mds-cli/src/output.rs @@ -3026,9 +3026,14 @@ mod tests { fn compiled_messages(dir: &Path, source: &str) -> String { let path = dir.join("chat.mds"); std::fs::write(&path, source).unwrap(); - let compiled = - crate::build::compile_to_content(&path, None, true, mds::CompileOptions::default()) - .unwrap(); + let compiled = crate::build::compile_to_content( + &path, + None, + true, + mds::CompileOptions::default(), + None, + ) + .unwrap(); assert_eq!(compiled.kind, OutputKind::Messages, "{source:?}"); compiled.content } diff --git a/crates/mds-cli/tests/cli_lint.rs b/crates/mds-cli/tests/cli_lint.rs index be2f48f2..c6c3e402 100644 --- a/crates/mds-cli/tests/cli_lint.rs +++ b/crates/mds-cli/tests/cli_lint.rs @@ -4389,13 +4389,14 @@ fn unknown_rule_plural_sorted_warning() { #[test] fn unknown_rule_cli_exact_golden() { // We cannot import mds:: directly from an integration test; hard-code the - // current eleven names in alphabetical order (the same value KNOWN_LINT_RULES + // current thirteen names in alphabetical order (the same value KNOWN_LINT_RULES // holds, verified by AC-224-7). If the registry grows this golden must be // updated alongside the registry — the test will fail loudly. #[rustfmt::skip] let recognised = concat!( - "duplicate-export, duplicate-import, empty-block, legacy-interpolation, ", - "literal-directive, redundant-else, shadow-variable, unreachable-branch, ", + "duplicate-export, duplicate-import, empty-block, insecure-data-origin, ", + "legacy-interpolation, literal-credential-header, literal-directive, ", + "redundant-else, shadow-variable, unreachable-branch, ", "unused-function, unused-import, unused-variable" ); @@ -4486,8 +4487,9 @@ fn unknown_rule_cli_exact_golden() { fn unknown_rule_cli_exact_golden_single_file() { #[rustfmt::skip] let recognised = concat!( - "duplicate-export, duplicate-import, empty-block, legacy-interpolation, ", - "literal-directive, redundant-else, shadow-variable, unreachable-branch, ", + "duplicate-export, duplicate-import, empty-block, insecure-data-origin, ", + "legacy-interpolation, literal-credential-header, literal-directive, ", + "redundant-else, shadow-variable, unreachable-branch, ", "unused-function, unused-import, unused-variable" ); @@ -9254,3 +9256,68 @@ fn stdin_where_the_working_directory_is_gone_fails_in_the_words_build_uses() { "control: where the working directory exists" ); } + +/// TP-100: the data rules report a literal credential header and an http request map +/// URL through the CLI, with no header value in the JSON output. Lint sends no request. +/// Control: the secret form and an https URL give no data rule finding. +#[test] +fn data_rules_report_a_literal_credential_header_and_an_http_url() { + let tmp = tempfile::tempdir().unwrap(); + let file = tmp.path().join("main.mds"); + let source = "---\ndata:\n feed:\n url: http://127.0.0.1:9/x\n headers:\n X-Auth-Token: planted-value\n---\n{{feed}}\n"; + fs::write(&file, source).unwrap(); + // The checks for the value come first, with fixed messages: `lint_json` and + // `json_diagnostics` print the output when they fail. The second check covers a value + // that the JSON text escapes. + let out = lint_path(&file, &["--format", "json"]); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + !stdout.contains("planted-value"), + "the lint output must not show the header value" + ); + let json: serde_json::Value = + serde_json::from_str(&stdout).expect("lint --format json must emit valid JSON"); + assert!( + !json.to_string().contains("planted-value"), + "the decoded lint output must not show the header value" + ); + assert_eq!(json["version"], 1, "the JSON version must be 1"); + let mut found: Vec<(String, String)> = json_diagnostics(&json, "data rules") + .iter() + .map(|d| { + ( + d["rule"].as_str().unwrap().to_owned(), + d["message"].as_str().unwrap().to_owned(), + ) + }) + .collect(); + found.sort(); + assert_eq!( + found, + [ + ( + "insecure-data-origin".to_owned(), + "Data entry 'feed' requests an http URL.".to_owned() + ), + ( + "literal-credential-header".to_owned(), + "Data entry 'feed' sets the credential header 'X-Auth-Token' to literal text." + .to_owned() + ), + ], + "lint must report the two data rules" + ); + + let safe = source + .replace("http://127.0.0.1:9/x", "https://a.example/x") + .replace("planted-value", "{secret: TOKEN, prefix: ''}"); + fs::write(&file, safe).unwrap(); + let (json, _) = lint_json(&file, "control"); + let files = json["files"].as_array().unwrap(); + let rules: Vec<&str> = files + .iter() + .flat_map(|f| f["diagnostics"].as_array().into_iter().flatten()) + .filter_map(|d| d["rule"].as_str()) + .collect(); + assert!(rules.is_empty(), "control: {rules:?}"); +} diff --git a/crates/mds-cli/tests/cli_net.rs b/crates/mds-cli/tests/cli_net.rs new file mode 100644 index 00000000..afb5000e --- /dev/null +++ b/crates/mds-cli/tests/cli_net.rs @@ -0,0 +1,826 @@ +//! End-to-end tests of the network of `mds build` (#405): `--allow-net`, the `mds.json` +//! `network` section that can only narrow it, the import opt-in, host secrets, host +//! roots, the proxy variables, and the commands that never send. +//! +//! Every listener is a thread on `127.0.0.1:0` in this process. Each check that a +//! listener got no connection has a control in the same test that shows the listener +//! taking a connection first. + +mod common; +use common::{mds_bin, ChildGuard}; + +use std::fs; +use std::io::{self, ErrorKind, Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::{Path, MAIN_SEPARATOR_STR}; +use std::process::{Command, Output, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +use rcgen::{BasicConstraints, CertificateParams, CertifiedIssuer, IsCa, KeyPair, KeyUsagePurpose}; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}; +use rustls::{ServerConfig, ServerConnection, StreamOwned}; + +/// The poll interval of a listener thread. +const POLL: Duration = Duration::from_millis(5); +/// The longest life of a listener thread. +const LIFE: Duration = Duration::from_secs(60); +/// The longest wait for a command that must stop at its argument parse. +const PARSE_WAIT: Duration = Duration::from_secs(10); +/// The longest request head that a listener reads. +const MAX_HEAD: usize = 64 * 1024; +/// The body of a plain answer, and the output of `{{u.n}}` over it. +const BODY: &str = r#"{"n": 1}"#; +const RENDERED: &str = "1\n"; +/// The secret value of the secret tests. It must never reach stderr. +const SECRET: &str = "planted-secret-405"; +/// The environment variable that holds [`SECRET`] for the child. +const SECRET_VAR: &str = "MDS_TEST_NET_TOKEN"; + +// ── Listeners ──────────────────────────────────────────────────────────────── + +/// What a listener saw. +#[derive(Debug, Default)] +struct Seen { + connections: usize, + heads: Vec, +} + +/// A listener thread on `127.0.0.1:0`. `serve` handles each connection and gives the +/// request head that it read. +struct Server { + port: u16, + stop: Arc, + seen: Arc>, + thread: JoinHandle<()>, +} + +impl Server { + fn start(serve: impl Fn(TcpStream) -> Option + Send + 'static) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let port = listener.local_addr().unwrap().port(); + let stop = Arc::new(AtomicBool::new(false)); + let seen = Arc::new(Mutex::new(Seen::default())); + let (flag, record) = (Arc::clone(&stop), Arc::clone(&seen)); + let thread = thread::spawn(move || { + let end = Instant::now() + LIFE; + // Accept until a stop, then take every connection still in the backlog. + while Instant::now() < end { + match listener.accept() { + Ok((stream, _)) => { + record.lock().unwrap().connections += 1; + stream.set_nonblocking(false).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + if let Some(head) = serve(stream) { + record.lock().unwrap().heads.push(head); + } + } + Err(e) if e.kind() == ErrorKind::WouldBlock => { + if flag.load(Ordering::SeqCst) { + break; + } + thread::sleep(POLL); + } + Err(e) => panic!("accept failed: {e}"), + } + } + }); + Self { + port, + stop, + seen, + thread, + } + } + + /// A plain HTTP listener: `reply` gives the answer to a request head, or `None` to + /// close with no answer. + fn plain(reply: impl Fn(&str) -> Option> + Send + 'static) -> Self { + Self::start(move |mut stream| { + let head = read_head(&mut stream).ok()?; + if let Some(bytes) = reply(&head) { + let _ = stream.write_all(&bytes); + let _ = stream.flush(); + } + Some(head) + }) + } + + /// A plain listener that answers every request with 200 and [`BODY`]. + fn ok() -> Self { + Self::plain(|_| Some(answer("200 OK", "", BODY))) + } + + /// A TLS listener that presents the server certificate of `pki`. + fn tls(pki: &Pki, reply: impl Fn(&str) -> Option> + Send + 'static) -> Self { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let config = ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![pki.server.clone()], pki.key.clone_key()) + .unwrap(); + let config = Arc::new(config); + Self::start(move |stream| { + let connection = ServerConnection::new(Arc::clone(&config)).ok()?; + let mut tls = StreamOwned::new(connection, stream); + // A failed handshake ends the read: the client refused the certificate. + let head = read_head(&mut tls).ok().filter(|head| !head.is_empty())?; + if let Some(bytes) = reply(&head) { + let _ = tls.write_all(&bytes); + } + tls.conn.send_close_notify(); + let _ = tls.flush(); + Some(head) + }) + } + + /// The connections until now. + fn connections(&self) -> usize { + self.seen.lock().unwrap().connections + } + + /// Stop the listener and give what it saw. It takes every connection that completed + /// before the stop, so a count with no new connection means that none came. + fn stop(self) -> Seen { + self.stop.store(true, Ordering::SeqCst); + self.thread.join().unwrap(); + Arc::try_unwrap(self.seen).unwrap().into_inner().unwrap() + } +} + +/// Read a request head: the bytes up to the first blank line, at most [`MAX_HEAD`]. +fn read_head(stream: &mut impl Read) -> io::Result { + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + while head.len() < MAX_HEAD && !head.ends_with(b"\r\n\r\n") { + if stream.read(&mut byte)? == 0 { + break; + } + head.push(byte[0]); + } + Ok(String::from_utf8_lossy(&head).into_owned()) +} + +/// An HTTP/1.1 answer with `status`, the extra header lines `headers` and `body`. +fn answer(status: &str, headers: &str, body: &str) -> Vec { + format!( + "HTTP/1.1 {status}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + .into_bytes() +} + +/// The value of the header `name` in a request head, any letter case. +fn header_value<'h>(head: &'h str, name: &str) -> Option<&'h str> { + head.lines().find_map(|line| { + let (key, value) = line.split_once(':')?; + key.eq_ignore_ascii_case(name).then(|| value.trim()) + }) +} + +/// A test CA, its PEM text, and a server certificate and key that the CA signed. +struct Pki { + ca_pem: String, + server: CertificateDer<'static>, + key: PrivateKeyDer<'static>, +} + +/// A CA and a certificate for `127.0.0.1`, made now: the repository holds no key. +fn pki() -> Pki { + let mut ca_params = CertificateParams::new(Vec::::new()).unwrap(); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + ca_params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; + let ca = CertifiedIssuer::self_signed(ca_params, KeyPair::generate().unwrap()).unwrap(); + let key = KeyPair::generate().unwrap(); + let server = CertificateParams::new(vec!["127.0.0.1".to_owned()]) + .unwrap() + .signed_by(&key, &ca) + .unwrap(); + Pki { + ca_pem: ca.pem(), + server: server.der().clone(), + key: PrivatePkcs8KeyDer::from(key.serialize_der()).into(), + } +} + +// ── Projects and runs ──────────────────────────────────────────────────────── + +/// A project directory (a `.mdsroot` marker) that holds `files`. +fn project(files: &[(&str, &str)]) -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join(".mdsroot"), "").unwrap(); + for (name, text) in files { + fs::write(dir.path().join(name), text).unwrap(); + } + dir +} + +/// A module with one request-map entry `u` for `url`, that renders `{{u.n}}`. +fn entry_module(url: &str) -> String { + format!("---\ndata:\n u:\n url: \"{url}\"\n---\n{{{{u.n}}}}\n") +} + +/// The allow item of a plain listener. +fn http_item(server: &Server) -> String { + format!("http://127.0.0.1:{}", server.port) +} + +/// A plain URL at a listener. +fn http_url(server: &Server, path: &str) -> String { + format!("http://127.0.0.1:{}{path}", server.port) +} + +/// `mds ` in `dir`, with no stdin and no proxy variable. +fn command(dir: &Path, args: &[&str]) -> Command { + let mut cmd = mds_bin(); + cmd.current_dir(dir).args(args).stdin(Stdio::null()); + for var in PROXY_VARS { + cmd.env_remove(var); + } + cmd +} + +fn run(dir: &Path, args: &[&str]) -> Output { + command(dir, args).output().unwrap() +} + +/// `mds build main.mds -o - --allow-net ` in `dir`, with `extra` args. +fn build(dir: &Path, items: &[&str], extra: &[&str]) -> Output { + let allow = items.join(","); + let mut args = vec!["build", "main.mds", "-o", "-", "--allow-net", &allow]; + args.extend_from_slice(extra); + run(dir, &args) +} + +fn stderr_of(out: &Output) -> String { + String::from_utf8_lossy(&out.stderr).into_owned() +} + +/// The exit code and the stdout of `out`. +fn code_and_stdout(out: &Output) -> (Option, String) { + ( + out.status.code(), + String::from_utf8_lossy(&out.stdout).into_owned(), + ) +} + +/// `text` without whitespace or miette's frame marker, so that a message miette wrapped +/// compares equal to the unwrapped one. +fn squash(text: &str) -> String { + text.chars() + .filter(|c| !c.is_whitespace() && *c != '\u{2502}') + .collect() +} + +/// Assert that `out` is a success that printed [`RENDERED`]. +fn assert_rendered(out: &Output, what: &str) { + assert_eq!( + code_and_stdout(out), + (Some(0), RENDERED.to_owned()), + "{what}; stderr: {}", + stderr_of(out) + ); +} + +/// Assert that `out` failed with exit 2, `code` and a message that holds `text`. +fn assert_fails(out: &Output, code: &str, text: &str) { + let stderr = stderr_of(out); + assert_eq!(code_and_stdout(out), (Some(2), String::new()), "{stderr}"); + assert!(stderr.contains(code), "expected {code}: {stderr}"); + assert!( + squash(&stderr).contains(&squash(text)), + "expected {text:?}: {stderr}" + ); +} + +/// Assert that neither stream of `out` holds the planted secret value. The messages +/// are fixed text, so a failure does not show the value. +fn assert_no_secret(out: &Output) { + assert!( + !String::from_utf8_lossy(&out.stdout).contains(SECRET), + "stdout must not show the secret value" + ); + assert!( + !stderr_of(out).contains(SECRET), + "stderr must not show the secret value" + ); +} + +/// The proxy variables of common HTTP clients, in both letter cases. +const PROXY_VARS: [&str; 8] = [ + "HTTP_PROXY", + "HTTPS_PROXY", + "ALL_PROXY", + "NO_PROXY", + "http_proxy", + "https_proxy", + "all_proxy", + "no_proxy", +]; + +// ── TP-84, TP-85, TP-99: the flag and mds.json ────────────────────────────── + +/// TP-84: with no `--allow-net`, an `mds.json` that allows the listener opens nothing: +/// the build fails with `mds::network_denied`, exit 2, and the listener gets no +/// connection. Control: `--allow-net` with the same origin sends once. +#[test] +fn no_flag_opens_no_connection_whatever_mds_json_allows() { + let server = Server::ok(); + let config = format!( + "{{\"network\": {{\"allow\": [\"{}\"]}}}}", + http_item(&server) + ); + let dir = project(&[ + ("main.mds", &entry_module(&http_url(&server, "/u"))), + ("mds.json", &config), + ]); + + assert_rendered(&build(dir.path(), &[&http_item(&server)], &[]), "control"); + assert_eq!(server.connections(), 1, "control: the flag sends once"); + + let out = run(dir.path(), &["build", "main.mds", "-o", "-"]); + assert_fails( + &out, + "mds::network_denied", + "network access denied for data entries: \"main.mds\", entry \"u\"", + ); + assert_eq!(server.stop().connections, 1, "no flag: no connection"); +} + +/// TP-85: an `mds.json` allow list wider than `--allow-net` fails with +/// `mds::invalid_options` and names the item, and `allow_imports: true` without +/// `--allow-net-imports` fails and names the key; a narrower list refuses the origin +/// that it drops. Each sends nothing. Control: equal lists send once. +#[test] +fn mds_json_can_only_narrow_the_flag() { + let target = Server::ok(); + let other = Server::ok(); + let items = [http_item(&other), http_item(&target)]; + let flags = [items[0].as_str(), items[1].as_str()]; + let dir = project(&[("main.mds", &entry_module(&http_url(&target, "/u")))]); + let with_config = |config: &str| { + fs::write(dir.path().join("mds.json"), config).unwrap(); + build(dir.path(), &flags, &[]) + }; + + let equal = format!( + "{{\"network\": {{\"allow\": [\"{}\", \"{}\"]}}}}", + items[0], items[1] + ); + assert_rendered(&with_config(&equal), "control: equal lists"); + assert_eq!(target.connections(), 1, "control: equal lists send once"); + + let wider = format!( + "{{\"network\": {{\"allow\": [\"{}\", \"{}\", \"http://127.0.0.1:9\"]}}}}", + items[0], items[1] + ); + assert_fails( + &with_config(&wider), + "mds::invalid_options", + &format!( + ".{MAIN_SEPARATOR_STR}mds.json network.allow[2]: the item permits a request \ + that the --allow-net list refuses" + ), + ); + let imports = format!( + "{{\"network\": {{\"allow\": [\"{}\"], \"allow_imports\": true}}}}", + items[1] + ); + assert_fails( + &with_config(&imports), + "mds::invalid_options", + &format!( + ".{MAIN_SEPARATOR_STR}mds.json network.allow_imports: true needs --allow-net-imports" + ), + ); + let narrower = format!("{{\"network\": {{\"allow\": [\"{}\"]}}}}", items[0]); + assert_fails( + &with_config(&narrower), + "mds::network_denied", + &format!( + "\"main.mds\", entry \"u\", URL \"{}\", origin \"{}\": allow-list: the origin is not in the allow list", + http_url(&target, "/u"), + items[1] + ), + ); + assert_eq!(target.stop().connections, 1, "no refused run sends"); + assert_eq!(other.stop().connections, 0); +} + +/// TP-99: an unknown key in the `network` section fails config loading and sends +/// nothing. Control: without the section, the request is sent. +#[test] +fn an_unknown_network_key_fails_and_sends_nothing() { + let server = Server::ok(); + let dir = project(&[("main.mds", &entry_module(&http_url(&server, "/u")))]); + let item = http_item(&server); + + assert_rendered(&build(dir.path(), &[&item], &[]), "control: no section"); + assert_eq!(server.connections(), 1); + + let config = format!("{{\"network\": {{\"allow\": [\"{item}\"], \"allow_all\": true}}}}"); + fs::write(dir.path().join("mds.json"), config).unwrap(); + let out = build(dir.path(), &[&item], &[]); + let stderr = stderr_of(&out); + assert_eq!(code_and_stdout(&out), (Some(1), String::new()), "{stderr}"); + assert!( + stderr.contains("invalid mds.json") && stderr.contains("unknown field `allow_all`"), + "{stderr}" + ); + assert_eq!( + server.stop().connections, + 1, + "the refused config sends nothing" + ); +} + +// ── TP-87, TP-88, TP-95..TP-98: requests ──────────────────────────────────── + +/// TP-87: a redirect to an origin that is not in the allow list fails with +/// `mds::network_denied` (`redirect-check`), and its target gets no connection. +/// Control: with the target in the list, the redirect is followed once. +#[test] +fn a_redirect_to_an_unlisted_origin_fails_with_no_connection() { + let target = Server::ok(); + let location = http_url(&target, "/to"); + let start = Server::plain(move |_| { + Some(answer( + "302 Found", + &format!("Location: {location}\r\n"), + "", + )) + }); + let dir = project(&[("main.mds", &entry_module(&http_url(&start, "/from")))]); + + assert_rendered( + &build(dir.path(), &[&http_item(&start), &http_item(&target)], &[]), + "control: a listed target", + ); + assert_eq!( + target.connections(), + 1, + "control: the redirect is followed once" + ); + + assert_fails( + &build(dir.path(), &[&http_item(&start)], &[]), + "mds::network_denied", + "redirect-check: the redirect target is not in the allow list", + ); + assert_eq!( + target.stop().connections, + 1, + "the unlisted target gets nothing" + ); + assert_eq!(start.stop().connections, 2); +} + +/// The source of the secret tests: `a` sends the host secret `TOKEN` to the TLS +/// listener, and `b` puts a value of its response in the URL of the second listener. +fn secret_chain(tls_port: u16, path: &str, next: &Server) -> String { + format!( + "---\ndata:\n a:\n url: \"https://127.0.0.1:{tls_port}{path}\"\n headers:\n Authorization: {{secret: TOKEN, prefix: \"Bearer \"}}\n b:\n url: \"{}/{{{{a.x}}}}\"\n---\n{{{{b.n}}}}\n", + http_url(next, "/b") + ) +} + +/// TP-88, TP-98: a listener that echoes the secret header fails the response check +/// (`mds::network_denied`), the second listener of the chain gets no connection, and +/// stderr holds no secret value. A TLS listener with a CA that the sender does not know +/// fails with `mds::network`. Controls: with `--tls-root`, a fixed answer reaches the +/// second listener once, and the bound listener got the secret. +#[test] +fn an_echoed_secret_stops_the_chain_and_tls_needs_the_host_root() { + let pki = pki(); + let tls = Server::tls(&pki, |head| { + let x = if head.starts_with("GET /echo ") { + header_value(head, "authorization").unwrap_or("").to_owned() + } else { + "fixed".to_owned() + }; + Some(answer("200 OK", "", &format!("{{\"x\": \"{x}\"}}"))) + }); + let next = Server::ok(); + let tls_origin = format!("https://127.0.0.1:{}", tls.port); + let dir = project(&[ + ("echo.mds", &secret_chain(tls.port, "/echo", &next)), + ("fixed.mds", &secret_chain(tls.port, "/fixed", &next)), + ("ca.pem", &pki.ca_pem), + ]); + let allow = format!("{tls_origin},{}", http_item(&next)); + let secret = format!("TOKEN=env:{SECRET_VAR}@{tls_origin}"); + let send = |source: &str, roots: bool| { + let mut args = vec!["build", source, "-o", "-", "--allow-net", &allow]; + args.extend_from_slice(&["--secret", &secret]); + if roots { + args.extend_from_slice(&["--tls-root", "ca.pem"]); + } + command(dir.path(), &args) + .env(SECRET_VAR, SECRET) + .output() + .unwrap() + }; + + // Check for the value first in each run, with a fixed message, so that no failure + // message below can show it. + let out = send("fixed.mds", true); + assert_no_secret(&out); + assert_rendered(&out, "control: a fixed answer"); + assert_eq!( + next.connections(), + 1, + "control: the chain reaches the second listener" + ); + + let out = send("echo.mds", true); + assert_no_secret(&out); + assert_fails( + &out, + "mds::network_denied", + "response-check: the response holds the value of a host secret", + ); + + let out = send("fixed.mds", false); + assert_no_secret(&out); + assert_fails(&out, "mds::network", "the TLS handshake failed"); + + assert_eq!( + next.stop().connections, + 1, + "no refused run reaches the second listener" + ); + // Each head holds the secret header, so these messages are fixed text. + let seen = tls.stop(); + let bound = format!("Bearer {SECRET}"); + assert_eq!( + seen.heads.len(), + 2, + "the bound listener must get two requests" + ); + assert!( + seen.heads + .iter() + .all(|head| header_value(head, "authorization") == Some(bound.as_str())), + "the bound listener must get the secret header" + ); +} + +/// TP-95: an origin that is not in the allow list fails with `mds::network_denied` +/// (`allow-list`), exit 2, and sends nothing; a listed listener that closes with no +/// answer fails with `mds::network`, exit 2. Control: the listed origin sends once. +#[test] +fn an_unlisted_origin_is_denied_and_no_answer_is_a_network_failure() { + let server = Server::ok(); + let silent = Server::plain(|_| None); + let dir = project(&[("main.mds", &entry_module(&http_url(&server, "/u")))]); + + assert_rendered(&build(dir.path(), &[&http_item(&server)], &[]), "control"); + assert_eq!(server.connections(), 1); + assert_fails( + &build(dir.path(), &[&http_item(&silent)], &[]), + "mds::network_denied", + "allow-list: the origin is not in the allow list", + ); + assert_eq!( + server.stop().connections, + 1, + "the unlisted origin gets nothing" + ); + + fs::write( + dir.path().join("main.mds"), + entry_module(&http_url(&silent, "/u")), + ) + .unwrap(); + let out = build(dir.path(), &[&http_item(&silent)], &[]); + let stderr = stderr_of(&out); + assert_eq!(code_and_stdout(&out), (Some(2), String::new()), "{stderr}"); + assert!(stderr.contains("mds::network"), "{stderr}"); + assert!(!stderr.contains("mds::network_denied"), "{stderr}"); + assert_eq!(silent.stop().connections, 1); +} + +/// TP-96: a response value in the URL of the next request, which gets 404, is absent +/// from stderr. Control: stderr names the URL template, and the listener got the value. +#[test] +fn a_response_value_in_a_failed_url_never_reaches_stderr() { + const MARKER: &str = "marker-from-response-405"; + let first = Server::plain(|_| Some(answer("200 OK", "", &format!("{{\"x\": \"{MARKER}\"}}")))); + let second = Server::plain(|_| Some(answer("404 Not Found", "", ""))); + let template = format!("{}/{{{{a.x}}}}", http_url(&second, "/b")); + let source = format!( + "---\ndata:\n a:\n url: \"{}\"\n b:\n url: \"{template}\"\n---\n{{{{b.n}}}}\n", + http_url(&first, "/a") + ); + let dir = project(&[("main.mds", &source)]); + + let out = build(dir.path(), &[&http_item(&first), &http_item(&second)], &[]); + // Check for the value first, with fixed messages, so that no failure message below + // can show it. The request head holds the value, so its messages are fixed too. + assert!( + !stderr_of(&out).contains(MARKER), + "stderr must not show the response value" + ); + assert!( + !String::from_utf8_lossy(&out.stdout).contains(MARKER), + "stdout must not show the response value" + ); + assert_fails(&out, "mds::network", &format!("URL \"{template}\"")); + assert!( + squash(&stderr_of(&out)).contains("theserveransweredwithHTTPstatus404"), + "stderr must name the status of the answer" + ); + let seen = second.stop(); + assert_eq!( + seen.heads.len(), + 1, + "the second listener must get one request" + ); + assert!( + seen.heads[0].starts_with(&format!("GET /b/{MARKER} ")), + "control: the second listener must get the response value" + ); + first.stop(); +} + +/// TP-97: a URL entry of an imported module fails without `--allow-net-imports` +/// (`import-opt-in`) and sends nothing. Control: with the opt-in it sends once. +#[test] +fn an_imported_url_entry_needs_the_import_opt_in() { + let server = Server::ok(); + let dir = project(&[ + ("main.mds", "@import \"./lib.mds\" as lib\n@include lib\n"), + ("lib.mds", &entry_module(&http_url(&server, "/lib"))), + ]); + let item = http_item(&server); + + assert_rendered( + &build(dir.path(), &[&item], &["--allow-net-imports"]), + "control: the opt-in", + ); + assert_eq!(server.connections(), 1); + assert_fails( + &build(dir.path(), &[&item], &[]), + "mds::network_denied", + "import-opt-in: a network entry of an imported module needs the import opt-in", + ); + assert_eq!(server.stop().connections, 1, "no opt-in: no connection"); +} + +/// The proxy variables of the child change no target: the request goes to the listed +/// listener, and the proxy listener gets no connection. Test-side control: a connection +/// to the proxy listener is seen. +#[test] +fn proxy_variables_change_no_target() { + let target = Server::ok(); + let proxy = Server::plain(|_| Some(answer("200 OK", "", r#"{"n": 2}"#))); + drop(TcpStream::connect(("127.0.0.1", proxy.port)).unwrap()); + let deadline = Instant::now() + Duration::from_secs(5); + while proxy.connections() == 0 && Instant::now() < deadline { + thread::sleep(POLL); + } + assert_eq!( + proxy.connections(), + 1, + "control: the proxy listener sees a connection" + ); + + let dir = project(&[("main.mds", &entry_module(&http_url(&target, "/u")))]); + let allow = http_item(&target); + let mut cmd = command( + dir.path(), + &["build", "main.mds", "-o", "-", "--allow-net", &allow], + ); + let proxy_url = http_url(&proxy, ""); + for var in PROXY_VARS { + if !var.eq_ignore_ascii_case("NO_PROXY") { + cmd.env(var, &proxy_url); + } + } + assert_rendered(&cmd.output().unwrap(), "the target answers"); + assert_eq!(target.stop().connections, 1); + assert_eq!(proxy.stop().connections, 1, "the proxy gets no request"); +} + +/// A stdin build and a directory build send too: stdin through the string step +/// compile, a directory build once per file, each file pinned to its walk entry. +#[test] +fn stdin_and_directory_builds_send() { + let server = Server::ok(); + let module = entry_module(&http_url(&server, "/u")); + let dir = project(&[("a.mds", &module), ("b.mds", &module)]); + let item = http_item(&server); + + let mut child = command(dir.path(), &["build", "-", "--allow-net", &item]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(module.as_bytes()) + .unwrap(); + assert_rendered(&child.wait_with_output().unwrap(), "stdin"); + assert_eq!(server.connections(), 1); + + let out = run(dir.path(), &["build", ".", "--allow-net", &item]); + assert_eq!(out.status.code(), Some(0), "{}", stderr_of(&out)); + for name in ["a.md", "b.md"] { + assert_eq!(fs::read_to_string(dir.path().join(name)).unwrap(), RENDERED); + } + assert_eq!(server.stop().connections, 3); +} + +// ── Commands that never send ───────────────────────────────────────────────── + +/// `mds check`, `mds lint` and `mds fmt --check` open no connection, and the parser +/// refuses `--allow-net` on them and on `mds watch`. The other network flags need +/// `--allow-net`. Control: `mds build --allow-net` sends once. +#[test] +fn tooling_never_sends_and_refuses_the_network_flags() { + let server = Server::ok(); + let dir = project(&[("main.mds", &entry_module(&http_url(&server, "/u")))]); + let item = http_item(&server); + + assert_rendered(&build(dir.path(), &[&item], &[]), "control"); + assert_eq!(server.connections(), 1); + + for args in [ + &["check", "main.mds"][..], + &["lint", "main.mds"], + &["fmt", "--check", "main.mds"], + ] { + let out = run(dir.path(), args); + assert!( + matches!(out.status.code(), Some(0 | 1)), + "{args:?}: {}", + stderr_of(&out) + ); + let mut flagged = args.to_vec(); + flagged.extend_from_slice(&["--allow-net", &item]); + let out = run(dir.path(), &flagged); + assert_eq!(out.status.code(), Some(2), "{flagged:?}"); + assert!( + stderr_of(&out).contains("unexpected argument '--allow-net'"), + "{flagged:?}: {}", + stderr_of(&out) + ); + } + // A watch that takes the flag runs until it is stopped, so the wait has a bound. + let mut watch = ChildGuard( + command(dir.path(), &["watch", "main.mds", "--allow-net", &item]) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(), + ); + let end = Instant::now() + PARSE_WAIT; + let mut status = None; + for _ in 0..PARSE_WAIT.as_millis().div_ceil(POLL.as_millis()) { + status = watch.0.try_wait().unwrap(); + if status.is_some() || Instant::now() >= end { + break; + } + thread::sleep(POLL); + } + let Some(status) = status else { + watch.kill_and_wait(); + panic!("mds watch must refuse --allow-net at parse time"); + }; + let mut stderr = String::new(); + watch + .0 + .stderr + .take() + .unwrap() + .read_to_string(&mut stderr) + .unwrap(); + assert_eq!(status.code(), Some(2)); + assert!(stderr.contains("unexpected argument '--allow-net'")); + + for flag in [ + &["--allow-net-imports"][..], + &["--secret", "TOKEN=env:VAR@api.example"], + &["--tls-root", "ca.pem"], + ] { + let mut args = vec!["build", "main.mds", "-o", "-"]; + args.extend_from_slice(flag); + let out = run(dir.path(), &args); + assert_eq!(out.status.code(), Some(2), "{flag:?}"); + assert!( + stderr_of(&out).contains("--allow-net"), + "{flag:?}: {}", + stderr_of(&out) + ); + } + assert_eq!(server.stop().connections, 1, "no tooling command sends"); +} diff --git a/crates/mds-cli/tests/panic_hook.rs b/crates/mds-cli/tests/panic_hook.rs index 7667a78f..a1afa4a4 100644 --- a/crates/mds-cli/tests/panic_hook.rs +++ b/crates/mds-cli/tests/panic_hook.rs @@ -2052,9 +2052,9 @@ fn each_catch_wraps_one_compile_call_and_nothing_else() { ( replaced( "build.rs", - "compile_native_to_content(fs, file, runtime_vars.clone(), quiet, opts)", - "{ fail_count += 1; compile_native_to_content(fs, file, \ - runtime_vars.clone(), quiet, opts) }", + "compile_pinned_to_content(fs, file, runtime_vars.clone(), quiet, opts, net)", + "{ fail_count += 1; compile_pinned_to_content(fs, file, \ + runtime_vars.clone(), quiet, opts, net) }", ), "more than one call", "a state change beside the compile", @@ -2080,8 +2080,8 @@ fn each_catch_wraps_one_compile_call_and_nothing_else() { ( replaced( "build.rs", - "compile_native_to_content(fs, file, runtime_vars.clone(), quiet, opts)", - "compile_native_to_content(fs, file, runtime_vars.clone(), quiet, &mut opts)", + "compile_pinned_to_content(fs, file, runtime_vars.clone(), quiet, opts, net)", + "compile_pinned_to_content(fs, file, runtime_vars.clone(), quiet, &mut opts, net)", ), "changes state", "a mutable borrow", @@ -2698,6 +2698,9 @@ const COMPILE_CATCHES: &[(&str, &str)] = &[ const COMPILE_CALLS: &[(&str, Option<&str>)] = &[ ("compile_to_content", Some("build.rs")), ("compile_native_to_content", Some("build.rs")), + // The compile of one file of an `mds build` directory run: each network round compiles + // the file again through the walk's pin, and the sends of a round run inside it. + ("compile_pinned_to_content", Some("build.rs")), ("mds::check_native_fs", None), ("format_source_named", Some("fmt.rs")), ("mds::lint_native_fs", None), diff --git a/crates/mds-cli/tests/print_discipline.rs b/crates/mds-cli/tests/print_discipline.rs index aa856e1e..71c4e17f 100644 --- a/crates/mds-cli/tests/print_discipline.rs +++ b/crates/mds-cli/tests/print_discipline.rs @@ -933,6 +933,21 @@ const PATH_FREE_ERRORS: &[(&str, &str, usize, &str)] = &[ count and an offset), a `serde_json` error parsing it (a message, a line and a \ column), and one serializing `messages` output (fixed text).", ), + ( + "config.rs", + "refused", + 1, + "The reason of `mds::AllowItem::parse` (a `PolicyError`) for a `network.allow` item \ + of `mds.json`: fixed text of mds-core that holds no input and names no path (#405).", + ), + ( + "net.rs", + "reason", + 8, + "A `PolicyError`, a `NarrowError` or an `mds_fetch::SetupError`: fixed text of \ + mds-core and mds-fetch that holds no input and names no path, for a network flag, \ + a `network` key of `mds.json` or a `--tls-root` file (#405).", + ), ( "lint.rs", "e", diff --git a/crates/mds-core/src/data/convert.rs b/crates/mds-core/src/data/convert.rs index 5c51bf75..ac3fa906 100644 --- a/crates/mds-core/src/data/convert.rs +++ b/crates/mds-core/src/data/convert.rs @@ -4,11 +4,10 @@ use crate::limits::MAX_DATA_FILE_BYTES; use crate::resolver::{parse_data_json_with, parse_data_yaml_with, Allowance, NODE_YAML}; use crate::value::Value; -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Accept { Json, Yaml, - #[cfg_attr(not(test), expect(dead_code, reason = "text is a response format"))] Text, } @@ -17,19 +16,46 @@ pub(crate) struct DataLabel<'a> { /// Project-relative label of the declaring module. pub(crate) module: &'a str, pub(crate) entry: &'a str, - pub(crate) file: Option<&'a str>, + pub(crate) input: DataInput<'a>, +} + +/// The input that a data value comes from, for messages. +#[derive(Clone, Copy)] +pub(crate) enum DataInput<'a> { + /// The declaration itself. + Declaration, + /// A data file, by its project-relative label. + File(&'a str), + /// The response of a network request. A message names the entry, never the URL. + Response, } impl DataLabel<'_> { pub(crate) fn syntax(self, format: &str) -> MdsError { - MdsError::yaml_error(format!( - "data file \"{}\", entry \"{}\": invalid {format} data", - crate::escape_path_for_message(self.file.unwrap_or(self.module)), - crate::sanitize_control_chars_wire(self.entry), - )) + let entry = crate::sanitize_control_chars_wire(self.entry); + let module = crate::escape_path_for_message(self.module); + MdsError::yaml_error(match self.input { + DataInput::Response => { + format!("\"{module}\", response for entry \"{entry}\": invalid {format} data") + } + DataInput::File(file) => format!( + "data file \"{}\", entry \"{entry}\": invalid {format} data", + crate::escape_path_for_message(file), + ), + DataInput::Declaration => { + format!("data file \"{module}\", entry \"{entry}\": invalid {format} data") + } + }) } + /// A data error of this input. For a file or a declaration, `field` is the key path + /// of the value. A key path of a response is body text, so a response error names + /// the entry only. pub(crate) fn error(self, field: Option<&str>, reason: &str) -> MdsError { + let field = match self.input { + DataInput::Response => None, + DataInput::Declaration | DataInput::File(_) => field, + }; MdsError::data(self.module, Some(self.entry), field, reason, None) } } diff --git a/crates/mds-core/src/data/convert_tests.rs b/crates/mds-core/src/data/convert_tests.rs index a143d6cd..7bf5166b 100644 --- a/crates/mds-core/src/data/convert_tests.rs +++ b/crates/mds-core/src/data/convert_tests.rs @@ -7,7 +7,7 @@ use crate::value::{Value, MAX_VALUE_DEPTH}; const LABEL: DataLabel<'static> = DataLabel { module: "entry.mds", entry: "settings", - file: None, + input: crate::data::DataInput::Declaration, }; fn read(raw: &str, accept: Accept) -> Result { @@ -233,7 +233,7 @@ fn conversion_failure_keeps_no_data_charge() { #[test] fn syntax_diagnostic_wire_escapes_the_file_and_entry_labels() { let label = DataLabel { - file: Some("sub/settings\t.yml"), + input: crate::data::DataInput::File("sub/settings\t.yml"), entry: "my\nentry", ..LABEL }; diff --git a/crates/mds-core/src/data/corpus_tests.rs b/crates/mds-core/src/data/corpus_tests.rs index 2456426e..5bbd4f66 100644 --- a/crates/mds-core/src/data/corpus_tests.rs +++ b/crates/mds-core/src/data/corpus_tests.rs @@ -12,7 +12,7 @@ use crate::value::MAX_VALUE_DEPTH; const LABEL: DataLabel<'static> = DataLabel { module: "entry.mds", entry: "sample", - file: None, + input: crate::data::DataInput::Declaration, }; fn parsed_json(raw: &str) -> Result { diff --git a/crates/mds-core/src/data/decl.rs b/crates/mds-core/src/data/decl.rs index fb84fd04..53c5fc97 100644 --- a/crates/mds-core/src/data/decl.rs +++ b/crates/mds-core/src/data/decl.rs @@ -4,10 +4,15 @@ use std::mem::size_of; use serde_yaml_ng::{Mapping, Value}; -use super::{refs::references, DataLabel}; +use super::encode::{check_header_value, EncodeRefusal}; +use super::refs::{pieces, references, Piece}; +use super::url::{self, UrlRefusal}; +use super::{Accept, DataLabel}; use crate::error::data_location; use crate::evaluator::budget::{MemBudget, Part}; -use crate::limits::{MAX_DATA_ENTRIES_PER_MODULE, MAX_DATA_REFS_PER_ENTRY}; +use crate::limits::{ + MAX_DATA_ENTRIES_PER_MODULE, MAX_DATA_REFS_PER_ENTRY, MAX_REQUEST_HEADERS, MAX_URL_BYTES, +}; use crate::parser::is_valid_identifier; use crate::value::MAX_VALUE_DEPTH; use crate::{escape_path_for_message, MdsError}; @@ -23,13 +28,145 @@ const RESERVED_NAMES: [&str; 6] = [ "indented-directives", ]; const RENAME_HELP: &str = "`data` is reserved for data sources; rename the variable"; +const METHOD_GRAMMAR: &str = "expected GET, HEAD, POST, PUT, PATCH, DELETE or OPTIONS"; +const ACCEPT_GRAMMAR: &str = "expected json, yaml or text"; +const HEADER_GRAMMAR: &str = "expected a string or a secret name with a literal prefix"; #[derive(Debug, PartialEq, Eq)] pub(crate) enum Source { File(String), + Url(Box), +} + +/// A network request as declared: literal text and `{{…}}` templates, never values. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct RequestTemplate { + /// The URL as declared, with its `{{…}}` text. + pub(crate) url: String, + pub(crate) method: DeclaredMethod, + /// `json` when the declaration does not name a format. + pub(crate) accept: Accept, + /// Bind the status, the headers and the body of the response, not the body only. + pub(crate) envelope: bool, + /// In declaration order. + pub(crate) headers: Vec, + /// The body is parsed for its references only. The body encoder comes later. + pub(crate) has_body: bool, /// The paths that the declaration references, in URL, header, then body order: /// at most `MAX_DATA_REFS_PER_ENTRY`. - Url(Vec), + pub(crate) refs: Vec, +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct HeaderTemplate { + /// The header name as declared. + pub(crate) name: String, + pub(crate) value: HeaderSource, +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum HeaderSource { + /// Header text with `{{…}}` references. + Text(String), + /// A host secret: the request sends the literal prefix, then the secret value. + Secret { name: String, prefix: String }, +} + +impl HeaderSource { + /// Text with no `{{…}}` reference, which the request sends as written. + pub(crate) fn is_literal_text(&self) -> bool { + match self { + Self::Text(text) => references(text).next().is_none(), + Self::Secret { .. } => false, + } + } +} + +/// The method of a request map. GET when the map does not name one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum DeclaredMethod { + Get, + Head, + Post, + Put, + Patch, + Delete, + Options, +} + +impl DeclaredMethod { + fn parse(text: &str) -> Option { + Some(match text { + "GET" => Self::Get, + "HEAD" => Self::Head, + "POST" => Self::Post, + "PUT" => Self::Put, + "PATCH" => Self::Patch, + "DELETE" => Self::Delete, + "OPTIONS" => Self::Options, + _ => return None, + }) + } +} + +/// The header names that carry a credential, in lower case. A declaration can set them +/// through the secret form only, and a redirect to another origin drops them. +pub(crate) const CREDENTIAL_HEADERS: [&str; 4] = [ + "authorization", + "proxy-authorization", + "cookie", + "x-api-key", +]; + +/// `name` is one of [`CREDENTIAL_HEADERS`] in any ASCII letter case. +pub(crate) fn is_credential_header(name: &str) -> bool { + CREDENTIAL_HEADERS + .iter() + .any(|known| same_name(name, known)) +} + +/// The header names that the sender writes from the URL, that frame the message or that +/// change the method, in lower case. A request can not set them: a `host` header would +/// name a host that the allow list and the secret origins never checked, and the core +/// sets the request method. The step engine refuses them before a request exists. +const SENDER_HEADERS: [&str; 12] = [ + "host", + "content-length", + "transfer-encoding", + "connection", + "keep-alive", + "proxy-connection", + "te", + "trailer", + "upgrade", + "x-http-method-override", + "x-http-method", + "x-method-override", +]; + +/// `name` is one of [`SENDER_HEADERS`] in any ASCII letter case. +pub(crate) fn is_sender_header(name: &str) -> bool { + SENDER_HEADERS.iter().any(|known| same_name(name, known)) +} + +/// `a` and `b` are equal in any ASCII letter case. It is not inlined, so the WASM build +/// carries one copy of the compare loop for all the names of the list. +#[inline(never)] +fn same_name(a: &str, b: &str) -> bool { + a.eq_ignore_ascii_case(b) +} + +/// The declaration form of a URL. Only a request map can name `http://`. +#[derive(Clone, Copy)] +enum UrlForm { + Text, + Map, +} + +/// The text of `text` as an owned string, charged before the copy. +fn owned(text: &str, mem: &mut MemBudget) -> Result { + mem.charge(Part::Temp, Some(text.len()))?; + Ok(text.to_owned()) } #[derive(Debug, PartialEq, Eq)] @@ -106,7 +243,7 @@ fn parse_mapping( let label = DataLabel { module, entry: name, - file: None, + input: crate::data::DataInput::Declaration, }; if RESERVED_NAMES.contains(&name.as_str()) { return Err(label.error(None, "data entry name is reserved")); @@ -153,36 +290,45 @@ impl DataLabel<'_> { fn parse_source(self, value: &Value, mem: &mut MemBudget) -> Result { self.check_quote(value, None)?; - let mut refs = Vec::new(); - match value { + let template = match value { Value::String(path) if path.starts_with("./") || path.starts_with("../") => { if path.contains("{{") { return Err(self.error(Some("path"), "file paths cannot contain `{{`")); } - mem.charge(Part::Temp, Some(path.len()))?; - return Ok(Source::File(path.clone())); + return Ok(Source::File(owned(path, mem)?)); } Value::String(url) if has_scheme(url) || url.contains("://") => { - self.parse_url(url, &mut refs, mem)?; + let mut refs = Vec::new(); + self.parse_url(url, UrlForm::Text, &mut refs, mem)?; + RequestTemplate { + url: owned(url, mem)?, + method: DeclaredMethod::Get, + accept: Accept::Json, + envelope: false, + headers: Vec::new(), + has_body: false, + refs, + } } - Value::Mapping(fields) => self.parse_request(fields, &mut refs, mem)?, + Value::Mapping(fields) => self.parse_request(fields, mem)?, _ => return Err(self.unknown_form()), - } - Ok(Source::Url(refs)) + }; + mem.charge(Part::Temp, Some(size_of::()))?; + Ok(Source::Url(Box::new(template))) } fn parse_request( self, fields: &Mapping, - refs: &mut Vec, mem: &mut MemBudget, - ) -> Result<(), MdsError> { + ) -> Result { let Some(url) = fields.get("url") else { return if fields.contains_key("method") || fields.contains_key("accept") || fields.contains_key("headers") || fields.contains_key("body") || fields.contains_key("cache") + || fields.contains_key("envelope") { Err(self.error(Some("url"), "request map requires a URL")) } else { @@ -193,58 +339,107 @@ impl DataLabel<'_> { let Value::String(url) = url else { return Err(self.error(Some("url"), "expected a URL string")); }; - self.parse_url(url, refs, mem)?; + let mut refs = Vec::new(); + self.parse_url(url, UrlForm::Map, &mut refs, mem)?; + let mut method = DeclaredMethod::Get; + let mut accept = Accept::Json; + let mut envelope = false; for (key, value) in fields { let Value::String(field) = key else { return Err(self.error(None, "request field name must be a string")); }; let reason = match (field.as_str(), value) { ("url" | "headers" | "body", _) => continue, - ("method", Value::String(s)) - if matches!( - s.as_str(), - "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS" - ) => - { - continue - } - ("accept", Value::String(s)) if matches!(s.as_str(), "json" | "yaml" | "text") => { - continue - } + ("method", Value::String(text)) => match DeclaredMethod::parse(text) { + Some(parsed) => { + method = parsed; + continue; + } + None => METHOD_GRAMMAR, + }, + ("accept", Value::String(text)) => match parse_accept(text) { + Some(parsed) => { + accept = parsed; + continue; + } + None => ACCEPT_GRAMMAR, + }, ("cache", Value::String(s)) if valid_cache(s) => continue, - ("method", _) => "expected GET, HEAD, POST, PUT, PATCH, DELETE or OPTIONS", - ("accept", _) => "expected json, yaml or text", + ("envelope", Value::Bool(flag)) => { + envelope = *flag; + continue; + } + ("method", _) => METHOD_GRAMMAR, + ("accept", _) => ACCEPT_GRAMMAR, ("cache", _) => "expected a duration in s, m, h or d, forever or off", + ("envelope", _) => "expected true or false", _ => "unknown request field", }; return Err(self.error(Some(field), reason)); } - if let Some(headers) = fields.get("headers") { - self.parse_headers(headers, refs, mem)?; - } - if let Some(body) = fields.get("body") { - self.check_quote(body, Some("body"))?; - match body { - Value::Mapping(_) => self.parse_body_tree(body, 0, refs, mem)?, - Value::String(s) if references(s).next().is_none() => (), - Value::String(_) => { - return Err(self.error(Some("body"), "a string body cannot contain references")) + let headers = match fields.get("headers") { + Some(headers) => self.parse_headers(headers, &mut refs, mem)?, + None => Vec::new(), + }; + let has_body = match fields.get("body") { + Some(body) => { + self.check_quote(body, Some("body"))?; + match body { + Value::Mapping(_) => self.parse_body_tree(body, 0, &mut refs, mem)?, + Value::String(s) if references(s).next().is_none() => (), + Value::String(_) => { + return Err( + self.error(Some("body"), "a string body cannot contain references") + ) + } + _ => { + return Err( + self.error(Some("body"), "expected a mapping or a literal string") + ) + } } - _ => return Err(self.error(Some("body"), "expected a mapping or a literal string")), + true } + None => false, + }; + if has_body && matches!(method, DeclaredMethod::Get | DeclaredMethod::Head) { + return Err(self.error(Some("body"), "a GET or HEAD request cannot have a body")); } - Ok(()) + if method == DeclaredMethod::Head && !envelope { + // A HEAD response has no body, so its data is in the envelope only. + return Err(self.error(Some("envelope"), "a HEAD request requires `envelope: true`")); + } + Ok(RequestTemplate { + url: owned(url, mem)?, + method, + accept, + envelope, + headers, + has_body, + refs, + }) } fn parse_url( self, url: &str, + form: UrlForm, refs: &mut Vec, mem: &mut MemBudget, ) -> Result<(), MdsError> { let field = Some("url"); - let Some(rest) = url.strip_prefix("https://") else { - return Err(self.error(field, "expected the literal https scheme")); + let rest = match ( + url.strip_prefix("https://"), + url.strip_prefix("http://"), + form, + ) { + (Some(rest), _, _) | (None, Some(rest), UrlForm::Map) => rest, + (_, _, UrlForm::Text) => { + return Err(self.error(field, "expected the literal https scheme")) + } + (_, _, UrlForm::Map) => { + return Err(self.error(field, "expected the literal https or http scheme")) + } }; if rest.contains(['\\', '#']) { return Err(self.error(field, "URL cannot contain a backslash or fragment")); @@ -272,7 +467,44 @@ impl DataLabel<'_> { if suffix.starts_with('?') { return Err(self.error(field, "URL with a query requires a path")); } - self.add_refs(suffix, "url", refs, mem) + self.add_refs(suffix, "url", refs, mem)?; + self.check_url_shape(url, mem) + } + + /// Parse the literal URL with the strict URL parser, each reference as the shortest + /// text that it can expand to: one byte in a path segment and none in the query. A + /// host or port form that the parser refuses, or a URL that is already past the + /// length cap, then fails here, on every declaration, before any request exists. + fn check_url_shape(self, url: &str, mem: &mut MemBudget) -> Result<(), MdsError> { + let mark = mem.mark(); + // A reference is at least five bytes and its stand-in at most one. + mem.charge(Part::Temp, Some(url.len()))?; + let mut probe = String::with_capacity(url.len()); + let mut in_query = false; + for piece in pieces(url) { + match piece { + Ok(Piece::Literal(text)) => { + in_query |= text.contains('?'); + probe.push_str(text); + } + Ok(Piece::Reference(_)) if in_query => {} + Ok(Piece::Reference(_)) => probe.push('x'), + Err(reason) => { + mem.release_to(mark); + return Err(self.error(Some("url"), reason)); + } + } + } + let parsed = url::parse_absolute(&probe); + mem.release_to(mark); + match parsed { + Ok(_) => Ok(()), + Err(UrlRefusal::TooLong) => Err(MdsError::resource_limit(format!( + "{}: URL exceeds the maximum length of {MAX_URL_BYTES} bytes", + data_location(self.module, Some(self.entry), Some("url")) + ))), + Err(refusal) => Err(self.error(Some("url"), refusal.reason())), + } } fn parse_headers( @@ -280,11 +512,22 @@ impl DataLabel<'_> { headers: &Value, refs: &mut Vec, mem: &mut MemBudget, - ) -> Result<(), MdsError> { + ) -> Result, MdsError> { self.check_quote(headers, Some("headers"))?; let Value::Mapping(headers) = headers else { return Err(self.error(Some("headers"), "expected a header mapping")); }; + if headers.len() > MAX_REQUEST_HEADERS { + return Err(MdsError::resource_limit(format!( + "{}: too many headers (max {MAX_REQUEST_HEADERS} per request)", + data_location(self.module, Some(self.entry), Some("headers")) + ))); + } + mem.charge( + Part::Temp, + headers.len().checked_mul(size_of::()), + )?; + let mut kept = Vec::with_capacity(headers.len()); for (key, value) in headers { let Value::String(name) = key else { return Err(self.error(Some("headers"), "header name must be a literal token")); @@ -293,18 +536,32 @@ impl DataLabel<'_> { return Err(self.error(Some(name), "header name must be a literal token")); } self.check_quote(value, Some(name))?; - match value { - Value::String(s) => self.add_refs(s, name, refs, mem)?, - Value::Mapping(map) if valid_secret(map) => (), - _ => { - return Err(self.error( - Some(name), - "expected a string or a secret name with a literal prefix", - )) + let source = match value { + Value::String(_) if is_credential_header(name) => { + return Err(self.error(Some(name), "use the secret form for this header")) } - } + Value::String(text) => { + self.add_refs(text, name, refs, mem)?; + HeaderSource::Text(owned(text, mem)?) + } + Value::Mapping(map) => match secret_parts(map) { + Some((_, prefix)) if check_header_value(prefix).is_err() => { + return Err(self.error(Some(name), EncodeRefusal::HeaderByte.reason())) + } + Some((secret, prefix)) => HeaderSource::Secret { + name: owned(secret, mem)?, + prefix: owned(prefix, mem)?, + }, + None => return Err(self.error(Some(name), HEADER_GRAMMAR)), + }, + _ => return Err(self.error(Some(name), HEADER_GRAMMAR)), + }; + kept.push(HeaderTemplate { + name: owned(name, mem)?, + value: source, + }); } - Ok(()) + Ok(kept) } fn parse_body_tree( @@ -368,7 +625,7 @@ impl DataLabel<'_> { } } -fn has_scheme(text: &str) -> bool { +pub(super) fn has_scheme(text: &str) -> bool { text.split_once(':').is_some_and(|(scheme, _)| { let mut chars = scheme.bytes(); chars.next().is_some_and(|b| b.is_ascii_alphabetic()) @@ -405,12 +662,25 @@ fn header_token(name: &str) -> bool { .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) } -fn valid_secret(map: &Mapping) -> bool { - matches!( - (map.len(), map.get("secret"), map.get("prefix")), +/// The secret name and the literal prefix of the exact `{secret, prefix}` shape. +fn secret_parts(map: &Mapping) -> Option<(&str, &str)> { + match (map.len(), map.get("secret"), map.get("prefix")) { (2, Some(Value::String(name)), Some(Value::String(prefix))) - if is_valid_identifier(name) && !prefix.contains("{{") - ) + if is_valid_identifier(name) && !prefix.contains("{{") => + { + Some((name, prefix)) + } + _ => None, + } +} + +fn parse_accept(text: &str) -> Option { + match text { + "json" => Some(Accept::Json), + "yaml" => Some(Accept::Yaml), + "text" => Some(Accept::Text), + _ => None, + } } #[cfg(test)] diff --git a/crates/mds-core/src/data/decl_tests.rs b/crates/mds-core/src/data/decl_tests.rs index c61d56fe..0f60448c 100644 --- a/crates/mds-core/src/data/decl_tests.rs +++ b/crates/mds-core/src/data/decl_tests.rs @@ -26,14 +26,18 @@ fn refusal(raw: &str, field: Option<&str>) -> crate::SerializedError { error } -fn refs(raw: &str) -> Vec { +fn template(raw: &str) -> RequestTemplate { let mut entries = parse(raw).unwrap(); match entries.remove(0).source { - Source::Url(references) => references, + Source::Url(template) => *template, other => panic!("expected a URL, got {other:?}"), } } +fn refs(raw: &str) -> Vec { + template(raw).refs +} + #[test] fn unknown_forms_have_rename_help() { assert_eq!( @@ -155,7 +159,10 @@ fn entry_limit_applies_before_entry_analysis() { #[test] fn exact_method_accept_and_cache_grammars() { for method in ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] { - assert!(parse(&format!("{{item: {{url: '{URL}', method: {method}}}}}")).is_ok()); + assert!(parse(&format!( + "{{item: {{url: '{URL}', method: {method}, envelope: true}}}}" + )) + .is_ok()); } for accept in ["json", "yaml", "text"] { assert!(parse(&format!("{{item: {{url: '{URL}', accept: {accept}}}}}")).is_ok()); @@ -193,7 +200,7 @@ fn exact_method_accept_and_cache_grammars() { fn only_string_leaves_in_url_headers_and_body_produce_references() { assert_eq!( refs( - r"{item: {url: 'https://example.test/{{obj.path}}?q={{query}}', headers: {X-List: '{{header}} \{{literal}} {{ next }}', X-Auth: {secret: token, prefix: 'Scheme '}}, body: {'{{literalKey}}': ['é{{body.field}}', '\{{literal}}', 3, null]}}}" + r"{item: {url: 'https://example.test/{{obj.path}}?q={{query}}', method: POST, headers: {X-List: '{{header}} \{{literal}} {{ next }}', X-Auth: {secret: token, prefix: 'Scheme '}}, body: {'{{literalKey}}': ['é{{body.field}}', '\{{literal}}', 3, null]}}}" ), ["obj.path", "query", "header", "next", "body.field"] ); @@ -201,9 +208,12 @@ fn only_string_leaves_in_url_headers_and_body_produce_references() { refs("{item: 'https://example.test/{{first}}/{{first}}'}"), ["first", "first"] ); - assert!(refs(r"{item: {url: 'https://example.test/', body: '\{{literal}}'}}").is_empty()); + assert!( + refs(r"{item: {url: 'https://example.test/', method: POST, body: '\{{literal}}'}}") + .is_empty() + ); refusal( - "{item: {url: 'https://example.test/', body: '{{name}}'}}", + "{item: {url: 'https://example.test/', method: POST, body: '{{name}}'}}", Some("body"), ); } @@ -247,7 +257,7 @@ fn bare_flow_reference_shape_gets_quote_help() { "X-Value", ), ( - "{item: {url: 'https://example.test/', body: {value: {{name}}}}}", + "{item: {url: 'https://example.test/', method: POST, body: {value: {{name}}}}}", "body", ), ] { @@ -279,7 +289,6 @@ fn header_grammar_keeps_names_and_secret_parts_literal() { #[test] fn both_url_forms_require_a_literal_https_origin() { for value in [ - "http://example.test/path", "file:///example.json", "data:text/plain,test", "custom:test", @@ -349,3 +358,235 @@ fn declaration_memory_is_admitted_before_it_is_retained() { ); assert_eq!(limited, original); } + +/// The string form keeps its https rule. A request map may name `http://`, and the +/// network policy decides on it. Control: the same text as a request map parses. +#[test] +fn http_is_accepted_in_the_request_map_form_only() { + let error = refusal("{item: 'http://example.test/path'}", Some("url")); + assert!( + error + .message + .ends_with(": expected the literal https scheme"), + "{error:?}" + ); + assert_eq!( + template("{item: {url: 'http://127.0.0.1:8080/{{name}}'}}").url, + "http://127.0.0.1:8080/{{name}}" + ); + for value in ["ftp://example.test/path", "HTTP://example.test/path"] { + refusal(&format!("{{item: {{url: '{value}'}}}}"), Some("url")); + } +} + +/// `envelope` is a boolean that defaults to false, and `accept` defaults to `json`. +#[test] +fn envelope_is_a_boolean_and_accept_defaults_to_json() { + for raw in [ + format!("{{item: '{URL}'}}"), + format!("{{item: {{url: '{URL}'}}}}"), + ] { + let parsed = template(&raw); + assert_eq!((parsed.accept, parsed.envelope), (Accept::Json, false)); + } + let parsed = template(&format!( + "{{item: {{url: '{URL}', accept: text, envelope: true}}}}" + )); + assert_eq!((parsed.accept, parsed.envelope), (Accept::Text, true)); + for value in ["'true'", "1", "null", "yes"] { + refusal( + &format!("{{item: {{url: '{URL}', envelope: {value}}}}}"), + Some("envelope"), + ); + } + refusal("{item: {envelope: true}}", Some("url")); +} + +/// Control: POST keeps its body. +#[test] +fn get_and_head_requests_cannot_have_a_body() { + for method in ["", "method: GET, ", "method: HEAD, envelope: true, "] { + let error = refusal( + &format!("{{item: {{url: '{URL}', {method}body: {{text: abc}}}}}}"), + Some("body"), + ); + assert!(error.message.ends_with("cannot have a body"), "{error:?}"); + } + let parsed = template(&format!( + "{{item: {{url: '{URL}', method: POST, body: {{text: abc}}}}}}" + )); + assert_eq!( + (parsed.method, parsed.has_body), + (DeclaredMethod::Post, true) + ); +} + +/// A HEAD response has data only in the envelope. Control: HEAD with the envelope. +#[test] +fn head_requires_the_envelope() { + for raw in [ + format!("{{item: {{url: '{URL}', method: HEAD}}}}"), + format!("{{item: {{url: '{URL}', method: HEAD, envelope: false}}}}"), + ] { + refusal(&raw, Some("envelope")); + } + let parsed = template(&format!( + "{{item: {{url: '{URL}', method: HEAD, envelope: true}}}}" + )); + assert_eq!( + (parsed.method, parsed.envelope), + (DeclaredMethod::Head, true) + ); +} + +/// Credential headers take the secret form only, in any letter case and also when the +/// text holds a reference. The message does not show the value. Controls: the secret +/// form of each name, and a literal value for another header name. +#[test] +fn credential_headers_take_the_secret_form_only() { + for name in [ + "Authorization", + "authorization", + "PROXY-AUTHORIZATION", + "Cookie", + "X-Api-Key", + "x-API-key", + ] { + for value in ["'Bearer value_marker'", "'Bearer {{value_marker}}'"] { + let raw = format!("{{item: {{url: '{URL}', headers: {{{name}: {value}}}}}}}"); + let error = refusal(&raw, Some(name)); + assert!( + error + .message + .ends_with(": use the secret form for this header"), + "{error:?}" + ); + assert!(!error.message.contains("value_marker"), "{error:?}"); + } + let secret = format!( + "{{item: {{url: '{URL}', headers: {{{name}: {{secret: token, prefix: 'Bearer '}}}}}}}}" + ); + assert_eq!( + template(&secret).headers[0].value, + HeaderSource::Secret { + name: "token".into(), + prefix: "Bearer ".into() + } + ); + } + let parsed = template(&format!( + "{{item: {{url: '{URL}', headers: {{X-Trace: 'Bearer {{{{id}}}}'}}}}}}" + )); + assert_eq!( + parsed.headers, + [HeaderTemplate { + name: "X-Trace".into(), + value: HeaderSource::Text("Bearer {{id}}".into()) + }] + ); +} + +/// The core sets the request method, so the headers that change it are in the list of +/// headers that a request cannot set, in any letter case. Control: a longer name. +#[test] +fn method_override_headers_are_headers_a_request_cannot_set() { + for name in [ + "X-HTTP-Method-Override", + "x-http-method-override", + "X-Http-Method-OVERRIDE", + "X-HTTP-Method", + "x-http-METHOD", + "X-Method-Override", + "X-METHOD-OVERRIDE", + ] { + assert!(is_sender_header(name), "{name}"); + } + assert!(!is_sender_header("X-HTTP-Method-Overrides")); +} + +/// The prefix of a secret header is header text. Control: a visible ASCII prefix. +#[test] +fn secret_prefix_is_header_text() { + let header = |prefix: &str| { + format!("{{item: {{url: '{URL}', headers: {{X-Auth: {{secret: token, prefix: '{prefix}'}}}}}}}}") + }; + refusal(&header("Beärer "), Some("X-Auth")); + assert!(parse(&header("Bearer ")).is_ok()); +} + +/// The literal URL goes through the strict URL parser, each reference as the shortest +/// text that it can expand to, in both forms. An IPv4 short form, an upper-case host or +/// a bad port fails before any request exists. Controls: canonical forms with a port. +#[test] +fn literal_url_goes_through_the_strict_parser() { + for url in [ + "https://127.1/{{name}}", + "https://2130706433/path", + "https://0x7f000001/path", + "https://127.0.0.01/path", + "https://Example.test/path", + "https://example.test:99999/path", + "https://example.test:0/path", + "https://[::1/path", + "https://[fe80::1%25en0]/path", + "https://example.test/pa%th", + "https://example.test/é", + ] { + refusal(&format!("{{item: '{url}'}}"), Some("url")); + refusal(&format!("{{item: {{url: '{url}'}}}}"), Some("url")); + } + refusal("{item: {url: 'http://127.1:8080/'}}", Some("url")); + for url in [ + "https://127.0.0.1:8080/{{name}}?q={{query}}", + "https://[::1]:8080/path", + "https://example.test", + ] { + assert!(parse(&format!("{{item: '{url}'}}")).is_ok(), "{url}"); + } + assert!(parse("{item: {url: 'http://127.0.0.1:8080/'}}").is_ok()); +} + +/// A query reference can expand to empty text, so it counts no byte toward the URL cap +/// at declaration; a path reference counts one. Past the cap is a resource limit. +#[test] +fn literal_url_at_the_length_cap_passes_and_one_byte_over_fails() { + let base = "https://example.test/"; + let url = |extra: usize| { + let fill = crate::limits::MAX_URL_BYTES - base.len() - "x?q=".len() + extra; + format!("{base}{{{{a}}}}{}?q={{{{b}}}}", "p".repeat(fill)) + }; + assert!(parse(&format!("{{item: '{}'}}", url(0))).is_ok()); + let error = parse(&format!("{{item: '{}'}}", url(1))) + .unwrap_err() + .serialize(); + assert_eq!(error.code, "mds::resource_limit", "{error:?}"); + assert!( + error.message.contains("entry \"item\", field \"url\"") + && error.message.contains("8192 bytes"), + "{error:?}" + ); +} + +/// Declaration analysis counts the header map before it keeps a header: 32 headers pass, +/// and one more is a resource limit that names the entry. +#[test] +fn header_count_cap_admits_exactly_the_cap() { + let entry = |count: usize| { + let headers: Vec = (0..count).map(|i| format!("x-h{i}: v")).collect(); + format!( + "{{item: {{url: '{URL}', headers: {{{}}}}}}}", + headers.join(", ") + ) + }; + let cap = crate::limits::MAX_REQUEST_HEADERS; + assert_eq!(template(&entry(cap)).headers.len(), cap); + let error = parse(&entry(cap + 1)).unwrap_err().serialize(); + assert_eq!(error.code, "mds::resource_limit", "{error:?}"); + assert_eq!( + error.message, + format!( + "resource limit exceeded: \"sub/main.mds\", entry \"item\", field \"headers\": \ + too many headers (max {cap} per request)" + ) + ); +} diff --git a/crates/mds-core/src/data/digest.rs b/crates/mds-core/src/data/digest.rs new file mode 100644 index 00000000..a48d22c6 --- /dev/null +++ b/crates/mds-core/src/data/digest.rs @@ -0,0 +1,244 @@ +//! SHA-256 (FIPS 180-4) and HMAC-SHA-256 (RFC 2104). +//! +//! Own code, so the core and the WASM build need no hash crate. The vectors of FIPS 180-4 +//! and RFC 4231 in `digest_tests.rs` prove it. The block loop is bounded by the input +//! length and does not allocate. + +/// The bytes of one SHA-256 block. +const BLOCK: usize = 64; +/// The block offset where the 64-bit message length starts in the last block. +const LENGTH_AT: usize = BLOCK - 8; + +const INITIAL: [u32; 8] = [ + 0x6a09_e667, + 0xbb67_ae85, + 0x3c6e_f372, + 0xa54f_f53a, + 0x510e_527f, + 0x9b05_688c, + 0x1f83_d9ab, + 0x5be0_cd19, +]; + +const ROUND: [u32; 64] = [ + 0x428a_2f98, + 0x7137_4491, + 0xb5c0_fbcf, + 0xe9b5_dba5, + 0x3956_c25b, + 0x59f1_11f1, + 0x923f_82a4, + 0xab1c_5ed5, + 0xd807_aa98, + 0x1283_5b01, + 0x2431_85be, + 0x550c_7dc3, + 0x72be_5d74, + 0x80de_b1fe, + 0x9bdc_06a7, + 0xc19b_f174, + 0xe49b_69c1, + 0xefbe_4786, + 0x0fc1_9dc6, + 0x240c_a1cc, + 0x2de9_2c6f, + 0x4a74_84aa, + 0x5cb0_a9dc, + 0x76f9_88da, + 0x983e_5152, + 0xa831_c66d, + 0xb003_27c8, + 0xbf59_7fc7, + 0xc6e0_0bf3, + 0xd5a7_9147, + 0x06ca_6351, + 0x1429_2967, + 0x27b7_0a85, + 0x2e1b_2138, + 0x4d2c_6dfc, + 0x5338_0d13, + 0x650a_7354, + 0x766a_0abb, + 0x81c2_c92e, + 0x9272_2c85, + 0xa2bf_e8a1, + 0xa81a_664b, + 0xc24b_8b70, + 0xc76c_51a3, + 0xd192_e819, + 0xd699_0624, + 0xf40e_3585, + 0x106a_a070, + 0x19a4_c116, + 0x1e37_6c08, + 0x2748_774c, + 0x34b0_bcb5, + 0x391c_0cb3, + 0x4ed8_aa4a, + 0x5b9c_ca4f, + 0x682e_6ff3, + 0x748f_82ee, + 0x78a5_636f, + 0x84c8_7814, + 0x8cc7_0208, + 0x90be_fffa, + 0xa450_6ceb, + 0xbef9_a3f7, + 0xc671_78f2, +]; + +/// The SHA-256 digest of the concatenation of `parts`. +#[must_use] +pub(crate) fn sha256(parts: &[&[u8]]) -> [u8; 32] { + let mut state = Sha256::new(); + for part in parts { + state.update(part); + } + state.finish() +} + +/// The HMAC-SHA-256 of the concatenation of `parts` under `key`. A key longer than one +/// block is hashed first, as RFC 2104 says. +#[must_use] +pub(crate) fn hmac_sha256(key: &[u8], parts: &[&[u8]]) -> [u8; 32] { + let mut block = [0u8; BLOCK]; + let hashed; + let key = if key.len() > BLOCK { + hashed = sha256(&[key]); + &hashed[..] + } else { + key + }; + for (slot, byte) in block.iter_mut().zip(key) { + *slot = *byte; + } + let mut inner = Sha256::new(); + inner.update(&block.map(|byte| byte ^ 0x36)); + for part in parts { + inner.update(part); + } + let inner = inner.finish(); + let mut outer = Sha256::new(); + outer.update(&block.map(|byte| byte ^ 0x5c)); + outer.update(&inner); + outer.finish() +} + +/// The lower-case hex text of a digest. +#[must_use] +pub(crate) fn hex(digest: &[u8; 32]) -> String { + digest.iter().map(|byte| format!("{byte:02x}")).collect() +} + +struct Sha256 { + state: [u32; 8], + /// The bytes of the block that is not full yet. + pending: [u8; BLOCK], + /// How many bytes of `pending` are in use, always below `BLOCK`. + filled: usize, + /// The message length in bytes, modulo 2^64. + length: u64, +} + +impl Sha256 { + fn new() -> Self { + Self { + state: INITIAL, + pending: [0; BLOCK], + filled: 0, + length: 0, + } + } + + fn update(&mut self, data: &[u8]) { + self.length = self.length.wrapping_add(data.len() as u64); + let mut data = data; + if self.filled > 0 { + let mut copied = 0; + for (slot, byte) in self.pending.iter_mut().skip(self.filled).zip(data) { + *slot = *byte; + copied += 1; + } + self.filled += copied; + data = data.get(copied..).unwrap_or_default(); + if self.filled < BLOCK { + return; + } + compress(&mut self.state, &self.pending); + self.filled = 0; + } + let (blocks, tail) = data.as_chunks::(); + for block in blocks { + compress(&mut self.state, block); + } + for (slot, byte) in self.pending.iter_mut().zip(tail) { + *slot = *byte; + } + self.filled = tail.len(); + } + + fn finish(mut self) -> [u8; 32] { + let bits = self.length.wrapping_mul(8).to_be_bytes(); + let mut last = self.pending; + for (index, slot) in last.iter_mut().enumerate().skip(self.filled) { + *slot = if index == self.filled { 0x80 } else { 0 }; + } + // The end mark and the 8 length bytes do not fit after `LENGTH_AT`: pad this + // block and put the length in one more. + if self.filled >= LENGTH_AT { + compress(&mut self.state, &last); + last = [0; BLOCK]; + } + for (slot, byte) in last.iter_mut().skip(LENGTH_AT).zip(bits) { + *slot = byte; + } + compress(&mut self.state, &last); + let mut digest = [0u8; 32]; + for (bytes, word) in digest.as_chunks_mut::<4>().0.iter_mut().zip(self.state) { + *bytes = word.to_be_bytes(); + } + digest + } +} + +fn compress(state: &mut [u32; 8], block: &[u8; BLOCK]) { + let mut schedule = [0u32; 64]; + for (word, bytes) in schedule.iter_mut().zip(block.as_chunks::<4>().0) { + *word = u32::from_be_bytes(*bytes); + } + // Each index stays inside the 64 words by the range of the loop. + for t in 16..64 { + let w15 = schedule[t - 15]; + let w2 = schedule[t - 2]; + let s0 = w15.rotate_right(7) ^ w15.rotate_right(18) ^ (w15 >> 3); + let s1 = w2.rotate_right(17) ^ w2.rotate_right(19) ^ (w2 >> 10); + schedule[t] = schedule[t - 16] + .wrapping_add(s0) + .wrapping_add(schedule[t - 7]) + .wrapping_add(s1); + } + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *state; + for (round, word) in ROUND.iter().zip(schedule) { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let choice = (e & f) ^ (!e & g); + let t1 = h + .wrapping_add(s1) + .wrapping_add(choice) + .wrapping_add(*round) + .wrapping_add(word); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let majority = (a & b) ^ (a & c) ^ (b & c); + let t2 = s0.wrapping_add(majority); + h = g; + g = f; + f = e; + e = d.wrapping_add(t1); + d = c; + c = b; + b = a; + a = t1.wrapping_add(t2); + } + for (word, add) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) { + *word = word.wrapping_add(add); + } +} diff --git a/crates/mds-core/src/data/digest_tests.rs b/crates/mds-core/src/data/digest_tests.rs new file mode 100644 index 00000000..ddddcb7e --- /dev/null +++ b/crates/mds-core/src/data/digest_tests.rs @@ -0,0 +1,105 @@ +use super::digest::{hex, hmac_sha256, sha256}; + +fn sha_hex(parts: &[&[u8]]) -> String { + hex(&sha256(parts)) +} + +fn hmac_hex(key: &[u8], message: &[u8]) -> String { + hex(&hmac_sha256(key, &[message])) +} + +// FIPS 180-4 examples (NIST CSRC example values for SHA-256). +#[test] +fn sha256_matches_the_fips_180_4_examples() { + assert_eq!( + sha_hex(&[b"abc"]), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!( + sha_hex(&[b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"]), + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" + ); + let million = vec![b'a'; 1_000_000]; + assert_eq!( + sha_hex(&[&million]), + "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0" + ); +} + +#[test] +fn sha256_of_the_empty_message() { + let empty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + assert_eq!(sha_hex(&[]), empty); + assert_eq!(sha_hex(&[b""]), empty); + assert_eq!(sha_hex(&[b"", b""]), empty); +} + +/// The digest of the parts is the digest of their concatenation, for each split point of +/// a two-block message and for parts that cross a block end. +#[test] +fn sha256_of_parts_is_the_digest_of_their_concatenation() { + let message = b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; + let whole = sha256(&[message]); + for split in 0..=message.len() { + let (head, tail) = message.split_at(split); + assert_eq!(sha256(&[head, tail]), whole, "split at {split}"); + } + let long = vec![b'a'; 1_000_000]; + let pieces: Vec<&[u8]> = long.chunks(63).collect(); + assert_eq!( + hex(&sha256(&pieces)), + "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0" + ); +} + +// RFC 4231 test cases 1, 2, 3, 4, 6 and 7 (case 5 tests output truncation). +#[test] +fn hmac_sha256_matches_rfc_4231() { + assert_eq!( + hmac_hex(&[0x0b; 20], b"Hi There"), + "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" + ); + assert_eq!( + hmac_hex(b"Jefe", b"what do ya want for nothing?"), + "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" + ); + assert_eq!( + hmac_hex(&[0xaa; 20], &[0xdd; 50]), + "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe" + ); + let key: Vec = (0x01..=0x19).collect(); + assert_eq!( + hmac_hex(&key, &[0xcd; 50]), + "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b" + ); + let long_key = [0xaa; 131]; + assert_eq!( + hmac_hex( + &long_key, + b"Test Using Larger Than Block-Size Key - Hash Key First" + ), + "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54" + ); + assert_eq!( + hmac_hex( + &long_key, + b"This is a test using a larger than block-size key and a larger than \ + block-size data. The key needs to be hashed before being used by the \ + HMAC algorithm." + ), + "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2" + ); +} + +#[test] +fn hmac_of_parts_is_the_hmac_of_their_concatenation() { + let key = [7u8; 32]; + assert_eq!( + hmac_sha256(&key, &[b"Hi ", b"", b"There"]), + hmac_sha256(&key, &[b"Hi There"]) + ); + assert_ne!( + hmac_sha256(&key, &[b"Hi There"]), + hmac_sha256(&[8u8; 32], &[b"Hi There"]) + ); +} diff --git a/crates/mds-core/src/data/encode.rs b/crates/mds-core/src/data/encode.rs new file mode 100644 index 00000000..e41cfe48 --- /dev/null +++ b/crates/mds-core/src/data/encode.rs @@ -0,0 +1,307 @@ +//! Placement encoders and value-to-text of network data requests. +//! +//! [`expand`] is the one path from a template and its reference values to request text, +//! for every value source. The place of each reference comes from the literal template +//! text, never from the expanded text, and each value is inserted once and never scanned +//! again. + +use std::borrow::Cow; + +use super::refs::{pieces, Piece}; +use crate::error::{data_location, MdsError}; +use crate::limits::{MAX_HEADER_VALUE_BYTES, MAX_URL_BYTES}; +use crate::value::Value; + +/// The largest integer up to which an `f64` holds every integer exactly: 2^53. +const MAX_EXACT_INTEGER: f64 = 9_007_199_254_740_992.0; + +/// Where a reference value goes in a request. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Placement { + /// One URL path segment, before the first literal `?`. + PathSegment, + /// A query key or value, after the first literal `?`. + Query, + HeaderValue, +} + +impl Placement { + fn noun(self) -> &'static str { + match self { + Placement::PathSegment => "a URL path segment", + Placement::Query => "a URL query", + Placement::HeaderValue => "a header value", + } + } +} + +/// The request text that a template fills. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Target { + Url, + Header, +} + +/// The declaration site of a template, for messages. +#[derive(Clone, Copy)] +pub(crate) struct FieldLabel<'a> { + /// Project-relative label of the declaring module. + pub(crate) module: &'a str, + pub(crate) entry: &'a str, + /// The request field: `url` or a header name. + pub(crate) field: &'a str, +} + +/// Why an encoder refused a value. The reason is fixed text and never holds the value. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum EncodeRefusal { + EmptySegment, + DotSegment, + HeaderByte, +} + +impl EncodeRefusal { + pub(crate) fn reason(self) -> &'static str { + match self { + EncodeRefusal::EmptySegment => { + "a reference cannot fill a URL path segment with empty text" + } + EncodeRefusal::DotSegment => { + "a reference cannot fill a URL path segment with `.` or `..`" + } + EncodeRefusal::HeaderByte => { + "a header value can contain only visible ASCII characters and spaces" + } + } + } +} + +/// The text of a reference value: a string as it is, `true` or `false`, or an integer +/// with no fraction and an absolute value of at most 2^53. Every other value fails with +/// `mds::type_error`. +#[must_use = "a value can have a type that the request does not take"] +pub(crate) fn scalar_text<'v>( + value: &'v Value, + placement: Placement, + label: FieldLabel<'_>, +) -> Result, MdsError> { + let got = match value { + Value::String(text) => return Ok(Cow::Borrowed(text)), + Value::Boolean(true) => return Ok(Cow::Borrowed("true")), + Value::Boolean(false) => return Ok(Cow::Borrowed("false")), + Value::Number(number) if is_exact_integer(*number) => { + // An exact integer of at most 2^53 converts to `i64` with no loss. + return Ok(Cow::Owned((*number as i64).to_string())); + } + Value::Number(_) => "a number that is not such an integer", + Value::Null => "null", + Value::Array(_) => "an array", + Value::Object(_) => "an object", + }; + Err(MdsError::data_type_error( + label.module, + label.entry, + label.field, + &format!( + "{} takes a string, a boolean or an exact integer up to 2^53, not {got}", + placement.noun() + ), + )) +} + +fn is_exact_integer(number: f64) -> bool { + number.is_finite() && number.fract() == 0.0 && number.abs() <= MAX_EXACT_INTEGER +} + +/// Encode a value for one URL path segment. Every byte outside the RFC 3986 unreserved +/// set is percent-encoded, so a value can not add a segment. Empty text, `.` and `..` +/// are refused. +#[must_use = "a path segment value can be refused"] +pub(crate) fn encode_path_segment(text: &str) -> Result { + match text { + "" => Err(EncodeRefusal::EmptySegment), + "." | ".." => Err(EncodeRefusal::DotSegment), + _ => Ok(percent_encode(text)), + } +} + +/// Encode a value for a query key or value: the byte rule of [`encode_path_segment`], so +/// `&`, `=`, `+` and `#` can not add or cut parameters. +#[must_use] +pub(crate) fn encode_query(text: &str) -> String { + percent_encode(text) +} + +/// Check header text: bytes 0x20 to 0x7E only. Other text is refused, never encoded. +#[must_use = "header text can be refused"] +pub(crate) fn check_header_value(text: &str) -> Result<(), EncodeRefusal> { + if text.bytes().all(|byte| matches!(byte, 0x20..=0x7e)) { + Ok(()) + } else { + Err(EncodeRefusal::HeaderByte) + } +} + +fn percent_encode(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for byte in text.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + out.push(char::from(byte)); + } else { + out.push('%'); + out.push(hex_digit(byte >> 4)); + out.push(hex_digit(byte & 0x0f)); + } + } + out +} + +/// The upper-case hex digit of a value from 0 to 15. +fn hex_digit(nibble: u8) -> char { + char::from(if nibble < 10 { + b'0' + nibble + } else { + b'A' + (nibble - 10) + }) +} + +/// Expand `template` for `target` in one pass over its original text. `lookup` gives the +/// value of each reference path, whatever its source. A URL that would grow past +/// `MAX_URL_BYTES`, or a header value past `MAX_HEADER_VALUE_BYTES`, fails with +/// `mds::resource_limit` before the append. +#[must_use = "expansion can fail"] +pub(crate) fn expand<'v>( + template: &str, + target: Target, + label: FieldLabel<'_>, + mut lookup: impl FnMut(&str) -> Result<&'v Value, MdsError>, +) -> Result { + let mut writer = Writer::new(target); + for piece in pieces(template) { + let piece = piece.map_err(|reason| label.data_error(reason))?; + let written = match piece { + Piece::Literal(text) => writer.literal(text), + Piece::Reference(path) => { + let text = scalar_text(lookup(path)?, writer.placement, label)?; + writer.value(&text) + } + }; + written.map_err(|fault| label.fault(fault))?; + } + Ok(writer.finish()) +} + +impl FieldLabel<'_> { + fn data_error(self, reason: &str) -> MdsError { + MdsError::data( + self.module, + Some(self.entry), + Some(self.field), + reason, + None, + ) + } + + fn fault(self, fault: Fault) -> MdsError { + match fault { + Fault::Refused(refusal) => self.data_error(refusal.reason()), + Fault::UrlTooLong => self.limit("URL", MAX_URL_BYTES), + Fault::HeaderTooLong => self.limit("header value", MAX_HEADER_VALUE_BYTES), + } + } + + pub(crate) fn limit(self, what: &str, max: usize) -> MdsError { + MdsError::resource_limit(format!( + "{}: {what} exceeds the maximum length of {max} bytes", + data_location(self.module, Some(self.entry), Some(self.field)) + )) + } +} + +enum Fault { + Refused(EncodeRefusal), + UrlTooLong, + HeaderTooLong, +} + +impl From for Fault { + fn from(refusal: EncodeRefusal) -> Self { + Fault::Refused(refusal) + } +} + +struct Writer { + out: String, + /// The placement of the next reference. + placement: Placement, +} + +impl Writer { + fn new(target: Target) -> Self { + Self { + out: String::new(), + placement: match target { + Target::Url => Placement::PathSegment, + Target::Header => Placement::HeaderValue, + }, + } + } + + /// Write literal template text. `\{{` writes `{{`. In a URL, the first literal `?` + /// starts the query. + fn literal(&mut self, text: &str) -> Result<(), Fault> { + let text = if text.contains("\\{{") { + Cow::Owned(text.replace("\\{{", "{{")) + } else { + Cow::Borrowed(text) + }; + match self.placement { + Placement::HeaderValue => check_header_value(&text)?, + Placement::PathSegment if text.contains('?') => self.placement = Placement::Query, + Placement::PathSegment | Placement::Query => {} + } + self.push(&text) + } + + /// Write the text of one reference value with the encoder of its placement. + fn value(&mut self, text: &str) -> Result<(), Fault> { + match self.placement { + Placement::PathSegment => { + // Encoding never makes text shorter: check the raw length before the work. + self.room_for(text.len())?; + self.push(&encode_path_segment(text)?) + } + Placement::Query => { + self.room_for(text.len())?; + self.push(&encode_query(text)) + } + Placement::HeaderValue => { + check_header_value(text)?; + self.push(text) + } + } + } + + fn finish(self) -> String { + self.out + } + + fn push(&mut self, text: &str) -> Result<(), Fault> { + self.room_for(text.len())?; + self.out.push_str(text); + Ok(()) + } + + /// A URL holds at most `MAX_URL_BYTES`, and a header value `MAX_HEADER_VALUE_BYTES`. + fn room_for(&self, bytes: usize) -> Result<(), Fault> { + let (max, fault) = match self.placement { + Placement::HeaderValue => (MAX_HEADER_VALUE_BYTES, Fault::HeaderTooLong), + Placement::PathSegment | Placement::Query => (MAX_URL_BYTES, Fault::UrlTooLong), + }; + if self.out.len().saturating_add(bytes) > max { + Err(fault) + } else { + Ok(()) + } + } +} diff --git a/crates/mds-core/src/data/encode_tests.rs b/crates/mds-core/src/data/encode_tests.rs new file mode 100644 index 00000000..04aee9d2 --- /dev/null +++ b/crates/mds-core/src/data/encode_tests.rs @@ -0,0 +1,350 @@ +use std::cell::Cell; +use std::collections::HashMap; + +use super::encode::{ + check_header_value, encode_path_segment, encode_query, expand, scalar_text, EncodeRefusal, + FieldLabel, Placement, Target, +}; +use crate::error::MdsError; +use crate::limits::{MAX_HEADER_VALUE_BYTES, MAX_URL_BYTES}; +use crate::value::Value; + +const LABEL: FieldLabel<'static> = FieldLabel { + module: "entry.mds", + entry: "users", + field: "url", +}; + +const EXACT: f64 = 9_007_199_254_740_992.0; + +/// A value, then the exact bytes it gives in a path segment, a query part and a header +/// value, or the refusal. `None` for a header means the header refusal. +pub(super) type Vector = ( + String, + Result<&'static str, EncodeRefusal>, + &'static str, + Option<&'static str>, +); + +/// One value from each row of the shared vector table. `abc` is the control. +pub(super) fn vectors() -> Vec { + let refuse_header = None; + vec![ + ("abc".into(), Ok("abc"), "abc", Some("abc")), + ("a/b".into(), Ok("a%2Fb"), "a%2Fb", Some("a/b")), + ( + "..".into(), + Err(EncodeRefusal::DotSegment), + "..", + Some(".."), + ), + (".".into(), Err(EncodeRefusal::DotSegment), ".", Some(".")), + ( + String::new(), + Err(EncodeRefusal::EmptySegment), + "", + Some(""), + ), + ("x?y".into(), Ok("x%3Fy"), "x%3Fy", Some("x?y")), + ("x#y".into(), Ok("x%23y"), "x%23y", Some("x#y")), + ("a&b=c".into(), Ok("a%26b%3Dc"), "a%26b%3Dc", Some("a&b=c")), + ("%2F".into(), Ok("%252F"), "%252F", Some("%2F")), + (char::from(92).to_string(), Ok("%5C"), "%5C", Some("\\")), + ("\r\n".into(), Ok("%0D%0A"), "%0D%0A", refuse_header), + ( + ['\u{10d}', '\u{10a}'].iter().collect(), + Ok("%C4%8D%C4%8A"), + "%C4%8D%C4%8A", + refuse_header, + ), + ] +} + +fn one(name: &str, value: &str) -> HashMap { + HashMap::from([(name.to_owned(), Value::String(value.to_owned()))]) +} + +fn expand_with( + template: &str, + target: Target, + values: &HashMap, +) -> Result { + expand(template, target, LABEL, |path| { + values + .get(path) + .ok_or_else(|| MdsError::undefined_var(path)) + }) +} + +fn data_reason(result: Result) -> String { + match result { + Err(err @ MdsError::Data { .. }) => err.to_string(), + other => panic!("expected mds::data, got {other:?}"), + } +} + +#[test] +fn each_placement_encoder_gives_the_exact_bytes_or_its_refusal() { + for (value, path, query, header) in vectors() { + assert_eq!( + encode_path_segment(&value).as_deref(), + path.as_deref(), + "{value:?}" + ); + assert_eq!(encode_query(&value), query, "{value:?}"); + match header { + Some(_) => assert_eq!(check_header_value(&value), Ok(()), "{value:?}"), + None => assert_eq!( + check_header_value(&value), + Err(EncodeRefusal::HeaderByte), + "{value:?}" + ), + } + } +} + +#[test] +fn every_vector_goes_through_expansion_into_path_query_and_header() { + for (value, path, query, header) in vectors() { + let values = one("v", &value); + let url = expand_with("https://a.example/items/{{v}}", Target::Url, &values); + match path { + Ok(bytes) => assert_eq!(url.unwrap(), format!("https://a.example/items/{bytes}")), + Err(refusal) => assert!(data_reason(url).ends_with(refusal.reason()), "{value:?}"), + } + let url = expand_with("https://a.example/items?q={{v}}&n=1", Target::Url, &values); + assert_eq!( + url.unwrap(), + format!("https://a.example/items?q={query}&n=1"), + "{value:?}" + ); + let header_text = expand_with("Bearer {{v}}", Target::Header, &values); + match header { + Some(bytes) => assert_eq!(header_text.unwrap(), format!("Bearer {bytes}")), + None => assert!( + data_reason(header_text).ends_with(EncodeRefusal::HeaderByte.reason()), + "{value:?}" + ), + } + } +} + +#[test] +fn an_encoder_refusal_names_the_module_entry_and_field() { + let message = data_reason(expand_with( + "https://a.example/{{v}}", + Target::Url, + &one("v", ".."), + )); + assert!( + message.starts_with(r#"data error in "entry.mds", entry "users", field "url": "#), + "{message}" + ); +} + +/// The placement comes from the template text: a `?` in a value does not move the next +/// reference into the query. +#[test] +fn placement_comes_from_the_literal_template_never_from_a_value() { + let mut values = one("a", "x?y"); + values.insert("b".into(), Value::String("..".into())); + let refused = data_reason(expand_with( + "https://a.example/{{a}}/{{b}}", + Target::Url, + &values, + )); + assert!( + refused.ends_with(EncodeRefusal::DotSegment.reason()), + "{refused}" + ); + + values.insert("b".into(), Value::String("abc".into())); + assert_eq!( + expand_with("https://a.example/{{a}}/{{b}}", Target::Url, &values).unwrap(), + "https://a.example/x%3Fy/abc" + ); + // After the first literal `?`, a dot value is query text. + values.insert("b".into(), Value::String("..".into())); + assert_eq!( + expand_with("https://a.example/{{a}}?k={{b}}", Target::Url, &values).unwrap(), + "https://a.example/x%3Fy?k=.." + ); +} + +/// Inserted text is never scanned for references: one lookup per reference in the template. +#[test] +fn each_value_is_inserted_once_and_never_scanned_again() { + let values = HashMap::from([ + ("a".to_owned(), Value::String("{{b}}".into())), + ("b".to_owned(), Value::String("other".into())), + ]); + for (template, target, expected) in [ + ( + "https://a.example/{{a}}", + Target::Url, + "https://a.example/%7B%7Bb%7D%7D", + ), + ("x {{a}}", Target::Header, "x {{b}}"), + ] { + let lookups = Cell::new(0); + let result = expand(template, target, LABEL, |path| { + lookups.set(lookups.get() + 1); + Ok(&values[path]) + }); + assert_eq!(result.unwrap(), expected); + assert_eq!(lookups.get(), 1, "{template}"); + } +} + +#[test] +fn an_escaped_reference_writes_literal_braces_and_needs_no_lookup() { + let lookups = Cell::new(0); + let result = expand("x \\{{a}} y", Target::Header, LABEL, |_| { + lookups.set(lookups.get() + 1); + Err(MdsError::internal()) + }); + assert_eq!(result.unwrap(), "x {{a}} y"); + assert_eq!(lookups.get(), 0); +} + +#[test] +fn literal_header_text_follows_the_header_byte_rule() { + let refused = data_reason(expand_with("a\r\n{{v}}", Target::Header, &one("v", "b"))); + assert!( + refused.ends_with(EncodeRefusal::HeaderByte.reason()), + "{refused}" + ); + assert_eq!( + expand_with("a {{v}}", Target::Header, &one("v", "b")).unwrap(), + "a b" + ); +} + +#[test] +fn the_url_cap_counts_encoded_bytes_and_admits_exactly_the_cap() { + let prefix = "https://a.example/"; + let fits = "a".repeat(MAX_URL_BYTES - prefix.len()); + let template = format!("{prefix}{{{{v}}}}"); + let url = expand_with(&template, Target::Url, &one("v", &fits)).unwrap(); + assert_eq!(url.len(), MAX_URL_BYTES); + + let over = format!("{fits}a"); + for value in [over, "/".repeat((MAX_URL_BYTES - prefix.len()) / 3 + 1)] { + match expand_with(&template, Target::Url, &one("v", &value)) { + Err(err @ MdsError::ResourceLimit { .. }) => { + let message = err.to_string(); + assert!(message.contains(r#""entry.mds", entry "users", field "url""#)); + assert!(message.contains(&MAX_URL_BYTES.to_string()), "{message}"); + } + other => panic!("expected mds::resource_limit, got {other:?}"), + } + } + let slashes = "/".repeat((MAX_URL_BYTES - prefix.len()) / 3); + assert!(expand_with(&template, Target::Url, &one("v", &slashes)).is_ok()); +} + +#[test] +fn reference_and_lookup_errors_stop_expansion() { + let unclosed = data_reason(expand_with( + "https://a.example/{{v", + Target::Url, + &one("v", "a"), + )); + assert!(unclosed.ends_with("unclosed `{{` reference"), "{unclosed}"); + let missing = expand_with("https://a.example/{{w}}", Target::Url, &one("v", "a")); + assert!( + matches!(missing, Err(MdsError::UndefinedVariable { .. })), + "{missing:?}" + ); +} + +#[test] +fn scalars_become_text_only_as_strings_booleans_and_exact_integers() { + for (value, text) in [ + (Value::String("a b".into()), "a b"), + (Value::Boolean(true), "true"), + (Value::Boolean(false), "false"), + (Value::Number(EXACT), "9007199254740992"), + (Value::Number(-EXACT), "-9007199254740992"), + (Value::Number(3.0), "3"), + (Value::Number(0.0), "0"), + ] { + for placement in [ + Placement::PathSegment, + Placement::Query, + Placement::HeaderValue, + ] { + assert_eq!(scalar_text(&value, placement, LABEL).unwrap(), text); + } + } +} + +#[test] +fn other_numbers_null_arrays_and_objects_fail_with_the_type_error_code() { + for value in [ + Value::Number(EXACT + 2.0), + Value::Number(-(EXACT + 2.0)), + Value::Number(1.5), + Value::Number(f64::INFINITY), + Value::Number(f64::NAN), + Value::Null, + Value::Array(vec![Value::String("a".into())]), + Value::Object(HashMap::new()), + ] { + for placement in [ + Placement::PathSegment, + Placement::Query, + Placement::HeaderValue, + ] { + let err = scalar_text(&value, placement, LABEL).unwrap_err(); + assert_eq!(err.serialize().code, "mds::type_error", "{value:?}"); + let message = err.to_string(); + assert!( + message.starts_with(r#"type error in "entry.mds", entry "users", field "url": "#), + "{message}" + ); + } + } + let through_expand = expand("https://a.example/{{v}}", Target::Url, LABEL, |_| { + Ok(&Value::Null) + }); + assert_eq!( + through_expand.unwrap_err().serialize().code, + "mds::type_error" + ); +} + +/// A header value holds at most 8 KiB: the cap counts literal and inserted text, admits +/// exactly the cap and refuses one more byte before the append. +#[test] +fn the_header_value_cap_admits_exactly_the_cap() { + let label = FieldLabel { + field: "x-trace", + ..LABEL + }; + let header = |value: &str| { + let values = one("v", value); + expand("Bearer {{v}}", Target::Header, label, |path| { + Ok(&values[path]) + }) + }; + let fits = "a".repeat(MAX_HEADER_VALUE_BYTES - "Bearer ".len()); + assert_eq!(header(&fits).unwrap().len(), MAX_HEADER_VALUE_BYTES); + match header(&format!("{fits}a")) { + Err(err @ MdsError::ResourceLimit { .. }) => assert_eq!( + err.to_string(), + format!( + "resource limit exceeded: \"entry.mds\", entry \"users\", field \"x-trace\": \ + header value exceeds the maximum length of {MAX_HEADER_VALUE_BYTES} bytes" + ) + ), + other => panic!("expected mds::resource_limit, got {other:?}"), + } + let literal = format!("{}{{{{v}}}}", "a".repeat(MAX_HEADER_VALUE_BYTES + 1)); + let values = one("v", ""); + let refused = expand(&literal, Target::Header, label, |path| Ok(&values[path])); + assert!( + matches!(refused, Err(MdsError::ResourceLimit { .. })), + "{refused:?}" + ); +} diff --git a/crates/mds-core/src/data/envelope.rs b/crates/mds-core/src/data/envelope.rs new file mode 100644 index 00000000..016c3c2b --- /dev/null +++ b/crates/mds-core/src/data/envelope.rs @@ -0,0 +1,143 @@ +//! The status envelope of a URL entry: the status, the headers and the body of one +//! response as one value, `{status, headers, body}`. +//! +//! A header name becomes lower case, with each `-` changed to `_`, so that a reference +//! can read it with dot access. A name that is then not an identifier is dropped, and so +//! are `set-cookie` and `set-cookie2`. Two names that differ but give the same key fail. +//! A repeated header joins its values with `, `. Each value passes the character rule of +//! data strings. A message names the entry and the field `headers`, never a header name +//! or value, because both are server text. + +use std::collections::HashMap; +use std::mem::size_of; + +use super::DataLabel; +use crate::escape_class::is_control_char; +use crate::evaluator::budget::{value_bytes, MemBudget, Part}; +use crate::parser::is_valid_identifier; +use crate::value::{Value, MAX_VALUE_DEPTH}; +use crate::MdsError; + +/// The response headers that the envelope never holds: they set client state. +const DROPPED: [&str; 2] = ["set-cookie", "set-cookie2"]; + +/// The envelope of a response with `status`, `headers` in received order and the +/// converted `body` (`Value::Null` for a HEAD request). The caller has checked the +/// header byte cap. The header values are charged as `Buffers` once the value exists. +/// +/// The envelope puts the body one level deeper. Thus a body with a value at +/// `MAX_VALUE_DEPTH` fails with a data error of the field `body`, so that the envelope +/// stays in the value depth cap. +pub(crate) fn envelope( + status: u16, + headers: &[(String, Vec)], + body: Value, + label: DataLabel<'_>, + mem: &mut MemBudget, +) -> Result { + if reaches_depth(&body, MAX_VALUE_DEPTH) { + return Err(MdsError::data( + label.module, + Some(label.entry), + Some("body"), + &format!("value nesting exceeds maximum depth of {MAX_VALUE_DEPTH}"), + None, + )); + } + let text_bytes = headers.iter().try_fold(0usize, |sum, (name, value)| { + sum.checked_add(name.len())?.checked_add(value.len()) + }); + // The lower-case name, the key and the joined value of each header, each at twice + // its length for buffer growth, and the table slots. + let slots = headers + .len() + .checked_mul(2 * size_of::<(String, (String, String))>()); + mem.charge( + Part::Temp, + text_bytes + .and_then(|bytes| bytes.checked_mul(6)) + .and_then(|bytes| bytes.checked_add(slots?)), + )?; + let mut fields: HashMap = HashMap::with_capacity(headers.len()); + for (name, value) in headers { + let lower = name.to_ascii_lowercase(); + if DROPPED.contains(&lower.as_str()) { + continue; + } + let key = lower.replace('-', "_"); + if !is_valid_identifier(&key) { + continue; + } + let text = header_text(value, label)?; + match fields.get_mut(&key) { + Some((first, joined)) if *first == lower => { + joined.push_str(", "); + joined.push_str(text); + } + Some(_) => { + return Err(header_error( + label, + "two response header names give the same envelope key", + )) + } + None => { + fields.insert(key, (lower, text.to_owned())); + } + } + } + let headers = Value::Object( + fields + .into_iter() + .map(|(key, (_, value))| (key, Value::String(value))) + .collect(), + ); + // The body charged its own bytes when it was converted. The outer table has three + // fields, counted at twice their size. + mem.charge( + Part::Buffers, + value_bytes(&headers).and_then(|bytes| bytes.checked_add(6 * size_of::<(String, Value)>())), + )?; + Ok(Value::Object(HashMap::from([ + ("status".to_owned(), Value::Number(f64::from(status))), + ("headers".to_owned(), headers), + ("body".to_owned(), body), + ]))) +} + +/// Whether `value` holds a value `levels` or more levels below its root. The walk goes +/// at most `levels` levels down, so its depth has a bound for any value. +fn reaches_depth(value: &Value, levels: usize) -> bool { + let Some(next) = levels.checked_sub(1) else { + return true; + }; + match value { + Value::Array(items) => items.iter().any(|item| reaches_depth(item, next)), + Value::Object(fields) => fields.values().any(|item| reaches_depth(item, next)), + _ => false, + } +} + +/// The text of one header value: UTF-8 with no character of the escape class of data +/// strings. +fn header_text<'v>(value: &'v [u8], label: DataLabel<'_>) -> Result<&'v str, MdsError> { + let text = std::str::from_utf8(value) + .map_err(|_| header_error(label, "invalid UTF-8 in a response header value"))?; + if text.chars().any(is_control_char) { + return Err(header_error( + label, + "forbidden character in a response header value", + )); + } + Ok(text) +} + +/// A data error of the field `headers`, a fixed name. +fn header_error(label: DataLabel<'_>, reason: &str) -> MdsError { + MdsError::data( + label.module, + Some(label.entry), + Some("headers"), + reason, + None, + ) +} diff --git a/crates/mds-core/src/data/envelope_tests.rs b/crates/mds-core/src/data/envelope_tests.rs new file mode 100644 index 00000000..0eaef68e --- /dev/null +++ b/crates/mds-core/src/data/envelope_tests.rs @@ -0,0 +1,180 @@ +//! The header rules of the status envelope. + +use std::collections::HashMap; + +use super::envelope::envelope; +use super::{DataInput, DataLabel}; +use crate::evaluator::budget::MemBudget; +use crate::value::MAX_VALUE_DEPTH; +use crate::{MdsError, Value}; + +const LABEL: DataLabel<'static> = DataLabel { + module: "main.mds", + entry: "a", + input: DataInput::Response, +}; + +fn build(status: u16, headers: &[(&str, &[u8])], body: Value) -> Result { + let headers: Vec<(String, Vec)> = headers + .iter() + .map(|&(name, value)| (name.to_owned(), value.to_vec())) + .collect(); + envelope(status, &headers, body, LABEL, &mut MemBudget::default()) +} + +fn headers(raw: &[(&str, &[u8])]) -> Result, MdsError> { + let value = build(200, raw, Value::Null)?; + let Value::Object(mut fields) = value else { + panic!("expected an object"); + }; + match fields.remove("headers") { + Some(Value::Object(headers)) => Ok(headers), + other => panic!("expected a header object, got {other:?}"), + } +} + +fn text(value: &str) -> Value { + Value::String(value.to_owned()) +} + +/// The envelope holds the status as a number, the headers and the body as given. +#[test] +fn the_envelope_holds_the_status_the_headers_and_the_body() { + let value = build(404, &[("ETag", b"\"v1\"")], text("gone")).unwrap(); + let expected = Value::Object(HashMap::from([ + ("status".to_owned(), Value::Number(404.0)), + ( + "headers".to_owned(), + Value::Object(HashMap::from([("etag".to_owned(), text("\"v1\""))])), + ), + ("body".to_owned(), text("gone")), + ])); + assert_eq!(value, expected); +} + +/// The envelope puts the body one level deeper. Thus a body with a value at the depth +/// cap fails with a data error of the field `body`. Control: a body one level less deep +/// builds. +#[test] +fn a_body_at_the_depth_cap_fails_with_a_data_error() { + let nested = + |depth: usize| (0..depth).fold(Value::Number(0.0), |inner, _| Value::Array(vec![inner])); + let err = build(200, &[], nested(MAX_VALUE_DEPTH)).unwrap_err(); + assert_eq!(err.serialize().code, "mds::data"); + assert_eq!( + err.to_string(), + r#"data error in "main.mds", entry "a", field "body": value nesting exceeds maximum depth of 64"# + ); + assert!(build(200, &[], nested(MAX_VALUE_DEPTH - 1)).is_ok()); +} + +/// A header name becomes lower case with `-` changed to `_`. Control: a name that is +/// already a lower-case identifier stays the same. +#[test] +fn header_names_become_lower_case_with_underscores() { + let fields = headers(&[ + ("X-Rate-Limit", b"10"), + ("Content-Type", b"application/json"), + ("etag", b"x"), + ]) + .unwrap(); + assert_eq!( + fields, + HashMap::from([ + ("x_rate_limit".to_owned(), text("10")), + ("content_type".to_owned(), text("application/json")), + ("etag".to_owned(), text("x")), + ]) + ); +} + +/// A name that is not an identifier after the change is dropped. Control: an +/// identifier name in the same response stays. +#[test] +fn a_name_that_is_not_an_identifier_is_dropped() { + let fields = headers(&[ + ("x.dotted", b"1"), + ("1st", b"1"), + ("caf\u{e9}", b"1"), + ("x-kept", b"1"), + ]) + .unwrap(); + assert_eq!(fields, HashMap::from([("x_kept".to_owned(), text("1"))])); +} + +/// `set-cookie` and `set-cookie2` are dropped in any letter case. Control: a longer name +/// that starts with `set-cookie` stays. +#[test] +fn cookie_headers_are_dropped() { + let fields = headers(&[ + ("Set-Cookie", b"id=1"), + ("SET-COOKIE2", b"id=2"), + ("set-cookie-policy", b"strict"), + ]) + .unwrap(); + assert_eq!( + fields, + HashMap::from([("set_cookie_policy".to_owned(), text("strict"))]) + ); +} + +/// A repeated header joins its values with `, `, in received order, in any letter case. +#[test] +fn a_repeated_header_joins_its_values_in_received_order() { + let fields = headers(&[("Vary", b"accept"), ("vary", b"origin"), ("VARY", b"x")]).unwrap(); + assert_eq!( + fields, + HashMap::from([("vary".to_owned(), text("accept, origin, x"))]) + ); +} + +/// Two different names that give one key fail, and the message names neither name nor +/// value. Control: the same name twice joins. +#[test] +fn two_names_with_one_key_fail() { + let err = headers(&[("x-a", b"one"), ("x_a", b"two")]).unwrap_err(); + assert_eq!(err.serialize().code, "mds::data"); + assert_eq!( + err.to_string(), + r#"data error in "main.mds", entry "a", field "headers": two response header names give the same envelope key"# + ); + let fields = headers(&[("x-a", b"one"), ("X-A", b"two")]).unwrap(); + assert_eq!( + fields, + HashMap::from([("x_a".to_owned(), text("one, two"))]) + ); +} + +/// A header value passes the character rule of data strings: an escape-class character +/// or a byte that is not UTF-8 fails, and the message does not show the value. Control: +/// a tab passes. +#[test] +fn a_header_value_passes_the_character_rule() { + for (value, reason) in [ + ( + &b"a\x1bb"[..], + "forbidden character in a response header value", + ), + ( + "a\u{202e}b".as_bytes(), + "forbidden character in a response header value", + ), + ( + &b"a\rb"[..], + "forbidden character in a response header value", + ), + (&b"a\xffb"[..], "invalid UTF-8 in a response header value"), + ] { + let err = headers(&[("x-value", value)]).unwrap_err(); + assert_eq!(err.serialize().code, "mds::data"); + assert_eq!( + err.to_string(), + format!(r#"data error in "main.mds", entry "a", field "headers": {reason}"#) + ); + } + let fields = headers(&[("x-value", b"a\tb")]).unwrap(); + assert_eq!( + fields, + HashMap::from([("x_value".to_owned(), text("a\tb"))]) + ); +} diff --git a/crates/mds-core/src/data/graph.rs b/crates/mds-core/src/data/graph.rs index ca95e3fc..ed231f5a 100644 --- a/crates/mds-core/src/data/graph.rs +++ b/crates/mds-core/src/data/graph.rs @@ -20,7 +20,7 @@ impl Node<'_> { DataLabel { module: self.module, entry: &self.entry.name, - file: None, + input: crate::data::DataInput::Declaration, } } } @@ -29,6 +29,11 @@ impl Node<'_> { pub(crate) struct Graph<'a> { nodes: &'a [Node<'a>], replayed: NodeSet, + /// The level of each node: 1 for a node with no dependency, else one more than + /// the highest level of its dependencies. + levels: [u8; MAX_DATA_ENTRIES_PER_COMPILE], + /// The highest level, at most `MAX_DATA_LEVELS`. + depth: usize, } impl<'a> Graph<'a> { @@ -46,6 +51,22 @@ impl<'a> Graph<'a> { .filter_map(|(index, node)| (!self.replayed.contains(index)).then_some(node)) } + /// The entries that a bind must satisfy, level by level and in declaration order + /// inside a level, so each entry comes after every entry it references. Replayed + /// entries are left out. + pub(crate) fn in_level_order(&self) -> impl Iterator> + '_ { + (1..=self.depth).flat_map(move |level| { + self.nodes + .iter() + .copied() + .enumerate() + .filter(move |&(index, _)| { + usize::from(self.levels[index]) == level && !self.replayed.contains(index) + }) + .map(|(_, node)| node) + }) + } + /// Append these pairs in module first-resolution order in the collect pass. pub(crate) fn frontier(&self) -> impl Iterator + '_ { self.unreplayed() @@ -81,8 +102,8 @@ pub(crate) fn analyze<'a>( // Replay satisfies the node without use of its outgoing references. // The declaration parser already checked the source form. replayed.insert(index); - } else if let Source::Url(refs) = &node.entry.source { - for path in refs { + } else if let Source::Url(template) = &node.entry.source { + for path in &template.refs { let root = path.split_once('.').map_or(path.as_str(), |(root, _)| root); if let Ok(slot) = indices.binary_search_by_key(&root, |&i| name_at(i)) { deps.insert(indices[slot]); @@ -99,8 +120,14 @@ pub(crate) fn analyze<'a>( } waiting[index] = Some(deps); } - check_levels(nodes, waiting)?; - Ok(Graph { nodes, replayed }) + let mut levels = [0; MAX_DATA_ENTRIES_PER_COMPILE]; + let depth = check_levels(nodes, waiting, &mut levels[..nodes.len()])?; + Ok(Graph { + nodes, + replayed, + levels, + depth, + }) } pub(crate) fn entry_limit() -> MdsError { @@ -133,7 +160,12 @@ pub(crate) fn sort_entries_by_key( Ok(()) } -fn check_levels(nodes: &[Node<'_>], waiting: &mut [Option]) -> Result<(), MdsError> { +/// Give each node its level and return the highest level. An empty graph has none. +fn check_levels( + nodes: &[Node<'_>], + waiting: &mut [Option], + levels: &mut [u8], +) -> Result { // Each pass removes one whole level. At most one pass per node is necessary. for level in 1..=nodes.len() { let mut ready = NodeSet::default(); @@ -141,6 +173,8 @@ fn check_levels(nodes: &[Node<'_>], waiting: &mut [Option]) -> Result<( if deps.as_ref().is_some_and(NodeSet::is_empty) { ready.insert(index); *deps = None; + // A level past the cap fails below, before any caller reads it. + levels[index] = u8::try_from(level).unwrap_or(u8::MAX); } } let Some(blocked) = waiting.iter().position(Option::is_some) else { @@ -149,7 +183,7 @@ fn check_levels(nodes: &[Node<'_>], waiting: &mut [Option]) -> Result<( "data dependency graph exceeds {MAX_DATA_LEVELS} levels" ))); } - break; + return Ok(level); }; if ready.is_empty() { return Err(nodes[blocked] @@ -160,7 +194,12 @@ fn check_levels(nodes: &[Node<'_>], waiting: &mut [Option]) -> Result<( deps.remove_all(&ready); } } - Ok(()) + // Only an empty graph gets here: each pass returns or removes at least one node. + if nodes.is_empty() { + Ok(0) + } else { + Err(MdsError::internal()) + } } // The graph uses fixed-size sets. Repeated references cost only one edge each. diff --git a/crates/mds-core/src/data/graph_tests.rs b/crates/mds-core/src/data/graph_tests.rs index 8721dcd4..0607eb4c 100644 --- a/crates/mds-core/src/data/graph_tests.rs +++ b/crates/mds-core/src/data/graph_tests.rs @@ -10,6 +10,19 @@ fn parse(raw: &str, module: &str) -> Result, MdsError> { parse_declarations(&tree["data"], module, &mut MemBudget::default()) } +/// A GET entry whose declaration references `refs`. +fn url_source(refs: Vec) -> Source { + Source::Url(Box::new(crate::data::decl::RequestTemplate { + url: "https://example.test/".into(), + method: crate::data::decl::DeclaredMethod::Get, + accept: crate::data::Accept::Json, + envelope: false, + headers: Vec::new(), + has_body: false, + refs, + })) +} + fn nodes<'a>(entries: &'a [Entry], module: &'a str) -> Vec> { entries .iter() @@ -209,7 +222,7 @@ fn merged_graph_accepts_the_compile_entry_cap_but_not_more() { source: Source::File("./leaf.json".into()), }) .collect::>(); - entries[0].source = Source::Url(vec![format!("{last}.id"), format!("{last}.name")]); + entries[0].source = url_source(vec![format!("{last}.id"), format!("{last}.name")]); let at_cap = nodes(&entries, MODULE); let graph = check(&at_cap[..cap], &[], &[]).unwrap(); assert_eq!(graph.unreplayed().count(), cap); @@ -218,9 +231,34 @@ fn merged_graph_accepts_the_compile_entry_cap_but_not_more() { "mds::resource_limit" ); - entries[cap - 1].source = Source::Url(vec!["entry0.id".into()]); + entries[cap - 1].source = url_source(vec!["entry0.id".into()]); let cycle = nodes(&entries[..cap], MODULE); let error = check(&cycle, &[], &[]).unwrap_err().serialize(); assert_eq!(error.code, "mds::data"); assert!(error.message.contains("data dependency cycle")); } + +/// The bind order is level by level, declaration order inside a level, and it skips a +/// replayed entry: a dependent entry always comes after each entry it references. +#[test] +fn level_order_puts_each_entry_after_its_dependencies() { + let entries = parse( + "{c: 'https://example.test/{{b.x}}', b: 'https://example.test/{{a.x}}', \ + d: ./d.json, a: 'https://example.test/a', e: 'https://example.test/{{a.x}}', \ + r: 'https://example.test/{{c.x}}'}", + MODULE, + ) + .unwrap(); + let nodes = nodes(&entries, MODULE); + let order = |runtime: &[&str]| { + check(&nodes, &[], runtime) + .unwrap() + .in_level_order() + .map(|node| node.entry.name.as_str()) + .collect::>() + }; + assert_eq!(order(&[]), ["d", "a", "b", "e", "c", "r"]); + assert_eq!(order(&["r"]), ["d", "a", "b", "e", "c"]); + // A replayed entry is skipped, and its dependents keep their level. + assert_eq!(order(&["b"]), ["d", "a", "c", "e", "r"]); +} diff --git a/crates/mds-core/src/data/mod.rs b/crates/mds-core/src/data/mod.rs index 259c6690..29b7f60d 100644 --- a/crates/mds-core/src/data/mod.rs +++ b/crates/mds-core/src/data/mod.rs @@ -2,14 +2,35 @@ mod convert; pub(crate) mod decl; +pub(crate) mod digest; +pub(crate) mod encode; +pub(crate) mod envelope; pub(crate) mod graph; pub(crate) mod path; +pub(crate) mod policy; mod refs; +pub(crate) mod request; pub(crate) mod resolve; +pub(crate) mod step; +pub(crate) mod url; -pub(crate) use convert::{convert, Accept, DataLabel}; +pub(crate) use convert::{convert, Accept, DataInput, DataLabel}; #[cfg(test)] mod convert_tests; #[cfg(test)] mod corpus_tests; +#[cfg(test)] +mod digest_tests; +#[cfg(test)] +mod encode_tests; +#[cfg(test)] +mod envelope_tests; +#[cfg(test)] +mod policy_tests; +#[cfg(test)] +mod request_tests; +#[cfg(test)] +mod step_tests; +#[cfg(test)] +mod url_tests; diff --git a/crates/mds-core/src/data/policy.rs b/crates/mds-core/src/data/policy.rs new file mode 100644 index 00000000..eb9c79d6 --- /dev/null +++ b/crates/mds-core/src/data/policy.rs @@ -0,0 +1,620 @@ +//! The network policy of data requests: the host allow list and its narrowing, the import +//! opt-in, the host secrets, the address table and the redirect rules. +//! +//! The network is off until a host builds a [`NetworkPolicy`]. The core checks every +//! request against it, and a policy can only narrow. A refusal is a fixed [`Refusal`] +//! that names its check and never holds input text. + +use std::error::Error; +use std::fmt; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + +use super::decl::{is_credential_header, DeclaredMethod}; +use super::request::Method; +use super::url::{self, CheckedUrl, Host, Origin, Scheme}; +use crate::limits::{MAX_ALLOW_ITEMS, MAX_REDIRECTS, MAX_SECRETS}; +use crate::parser::is_valid_identifier; + +/// The check that refused a request. +/// +/// This enum is `#[non_exhaustive]`: new checks may be added in minor releases. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Layer { + /// The origin is not in the allow list. + AllowList, + /// A network entry of an imported module needs the import opt-in. + ImportOptIn, + /// The strict URL parser refused an expanded URL or a redirect location. + UrlParser, + /// A redirect hop breaks a hop rule. + RedirectCheck, + /// A secret header does not match a host secret. + SecretBinding, + /// A name lookup gave an address in a refused range. + TransportAddress, + /// A response holds a secret value. + ResponseCheck, + /// The request method is not one that this release sends. + Method, +} + +impl Layer { + /// The check's name: `allow-list`, `import-opt-in`, `url-parser`, `redirect-check`, + /// `secret-binding`, `transport-address`, `response-check` or `method`. + #[must_use] + pub fn name(self) -> &'static str { + match self { + Layer::AllowList => "allow-list", + Layer::ImportOptIn => "import-opt-in", + Layer::UrlParser => "url-parser", + Layer::RedirectCheck => "redirect-check", + Layer::SecretBinding => "secret-binding", + Layer::TransportAddress => "transport-address", + Layer::ResponseCheck => "response-check", + Layer::Method => "method", + } + } +} + +/// A policy refusal: the check and a fixed reason that never holds input text. +/// +/// Obtain refusals from the checks of [`NetworkPolicy`]. This type is +/// `#[non_exhaustive]` and cannot be built outside the core. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Refusal { + layer: Layer, + reason: &'static str, +} + +/// The refusal of an address in a refused range, for the address check and for a sender +/// that reports it. +pub(crate) const ADDRESS_REFUSED: Refusal = + Refusal::new(Layer::TransportAddress, "the address is in a refused range"); + +impl Refusal { + pub(crate) const fn new(layer: Layer, reason: &'static str) -> Self { + Self { layer, reason } + } + + #[must_use] + pub fn layer(&self) -> Layer { + self.layer + } + + #[must_use] + pub fn reason(&self) -> &'static str { + self.reason + } +} + +/// Why the host input of a policy is refused. The message is fixed text and never holds +/// the input. +/// +/// This enum is `#[non_exhaustive]`: new errors may be added in minor releases. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PolicyError { + /// An allow item is not in the item grammar. The value is the fixed reason. + AllowItem(&'static str), + /// An allow list has no item. + NoItems, + /// An allow list has more than 64 items. + TooManyItems, + /// A secret name is not an identifier. + SecretName, + /// A secret value is empty or holds a character that is not visible ASCII. + SecretValue, + /// A secret origin does not use `https`. + SecretScheme, + /// A policy has more than 16 secrets. + TooManySecrets, + /// Two secrets have the same name. + DuplicateSecret, +} + +impl fmt::Display for PolicyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + PolicyError::AllowItem(reason) => f.write_str(reason), + PolicyError::NoItems => f.write_str("an allow list needs at least one item"), + PolicyError::TooManyItems => { + write!(f, "an allow list has at most {MAX_ALLOW_ITEMS} items") + } + PolicyError::SecretName => f.write_str("a secret name must be an identifier"), + PolicyError::SecretValue => { + f.write_str("a secret value must be one or more visible ASCII characters") + } + PolicyError::SecretScheme => f.write_str("a secret origin must use https"), + PolicyError::TooManySecrets => write!(f, "a policy has at most {MAX_SECRETS} secrets"), + PolicyError::DuplicateSecret => f.write_str("two secrets have the same name"), + } + } +} + +impl Error for PolicyError {} + +/// Why [`NetworkPolicy::narrow`] refused a narrower policy. +/// +/// This enum is `#[non_exhaustive]`: new errors may be added in minor releases. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NarrowError { + /// The item at `index` of the narrower list permits a request that the wider + /// policy refuses. + ItemNotAllowed { index: usize }, + /// The narrower policy allows imports, and the wider policy does not. + ImportsNotAllowed, + /// The narrower list breaks a list rule. + Policy(PolicyError), +} + +impl fmt::Display for NarrowError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + NarrowError::ItemNotAllowed { index } => write!( + f, + "allow item {index} permits a request that the wider allow list refuses" + ), + NarrowError::ImportsNotAllowed => { + f.write_str("the import opt-in is not in the wider policy") + } + NarrowError::Policy(error) => error.fmt(f), + } + } +} + +impl Error for NarrowError {} + +/// One item of a host allow list: an exact scheme, host and port. +/// +/// The grammar is `host`, `host:port`, `https://host[:port]` or `http://host:port`. The +/// host rules are those of a request URL: a lower-case name or a canonical IP address. +/// An item has no path, no wildcard, no trailing dot and no upper-case letter. `http` +/// needs its scheme and a port. +/// +/// This type is `#[non_exhaustive]`: obtain items from [`AllowItem::parse`]. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AllowItem { + scheme: Scheme, + host: Host, + /// The port as written. `None` is the default port of the scheme. + port: Option, +} + +impl AllowItem { + /// Parse one allow item. + #[must_use = "an allow item can be refused"] + pub fn parse(text: &str) -> Result { + let (scheme, authority) = if let Some(rest) = text.strip_prefix("https://") { + (Scheme::Https, rest) + } else if let Some(rest) = text.strip_prefix("http://") { + (Scheme::Http, rest) + } else if text.contains("://") { + return Err(PolicyError::AllowItem( + "expected the scheme https:// or http://, or no scheme", + )); + } else { + (Scheme::Https, text) + }; + if authority.contains(['/', '?', '#']) { + return Err(PolicyError::AllowItem( + "an allow item cannot have a path, a query or a fragment", + )); + } + // One strict parser reads every host, so the item goes through the URL parser. + let parsed = url::parse_absolute(&format!("{}://{authority}/", scheme.as_str())) + .map_err(|refusal| PolicyError::AllowItem(refusal.reason()))?; + if scheme == Scheme::Http && parsed.port.is_none() { + return Err(PolicyError::AllowItem( + "an http allow item needs the http:// scheme and a port", + )); + } + Ok(Self { + scheme, + host: parsed.host, + port: parsed.port, + }) + } + + /// The origin that the item allows. An item with no port has the default port. + #[must_use] + pub fn origin(&self) -> Origin { + Origin { + scheme: self.scheme, + host: self.host.clone(), + port: self.effective_port(), + } + } + + /// The item allows requests to `origin`: the same scheme and host, and the same port, + /// where the default port and no port are equal. + pub(crate) fn matches(&self, origin: &Origin) -> bool { + self.scheme == origin.scheme + && self.host == origin.host + && self.effective_port() == origin.port + } + + fn effective_port(&self) -> u16 { + self.port.unwrap_or(self.scheme.default_port()) + } + + /// The item is the IP address of `address` with its port, written in the item. + fn opens_address(&self, address: SocketAddr) -> bool { + let same_ip = match (&self.host, address.ip()) { + (Host::V4(item), IpAddr::V4(ip)) => *item == ip, + (Host::V6(item), IpAddr::V6(ip)) => *item == ip, + _ => false, + }; + same_ip && self.port == Some(address.port()) + } + + /// The item permits no request that `wider` refuses: the same origin, and for an IP + /// address a written port only when `wider` has one, because such a port can open the + /// address. + fn within(&self, wider: &AllowItem) -> bool { + let opens = self.port.is_some() && !matches!(self.host, Host::Name(_)); + wider.matches(&self.origin()) && (!opens || wider.port.is_some()) + } +} + +/// The value of a host secret. Its `Debug` shows no value. It has no `Display` and no +/// `Serialize`, and [`SecretValue::expose_for_send`] is its one accessor. +/// +/// This type is `#[non_exhaustive]`: obtain values from [`SecretValue::new`]. +#[non_exhaustive] +#[derive(Clone)] +pub struct SecretValue(String); + +impl SecretValue { + /// A secret value: one or more visible ASCII characters. + #[must_use = "a secret value can be refused"] + pub fn new(value: String) -> Result { + if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_graphic()) { + return Err(PolicyError::SecretValue); + } + Ok(Self(value)) + } + + /// The value, for the request header of a send only. Never write it to a message, a + /// log or an output. + #[must_use] + pub fn expose_for_send(&self) -> &str { + &self.0 + } +} + +impl fmt::Debug for SecretValue { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SecretValue(..)") + } +} + +/// A host secret: a name in its own name space, a value and the one origin that can +/// receive it. +/// +/// This type is `#[non_exhaustive]`: obtain secrets from [`Secret::new`]. +#[non_exhaustive] +#[derive(Clone, Debug)] +pub struct Secret { + name: String, + value: SecretValue, + origin: Origin, +} + +impl Secret { + /// A secret named `name` (an identifier) that only requests to `origin` (an `https` + /// origin) can carry. + #[must_use = "a secret can be refused"] + pub fn new(name: &str, value: SecretValue, origin: Origin) -> Result { + if !is_valid_identifier(name) { + return Err(PolicyError::SecretName); + } + if origin.scheme != Scheme::Https { + return Err(PolicyError::SecretScheme); + } + Ok(Self { + name: name.to_owned(), + value, + origin, + }) + } +} + +/// The network grant of a host: the allow list, the import opt-in and the host secrets. +/// +/// This type is `#[non_exhaustive]`: obtain policies from [`NetworkPolicy::new`]. +#[non_exhaustive] +#[derive(Clone, Debug)] +pub struct NetworkPolicy { + items: Vec, + imports: bool, + secrets: Vec, +} + +impl NetworkPolicy { + /// A policy that allows the origins of `items` (1 to 64 items), with no import opt-in + /// and no secret. + #[must_use = "a policy can be refused"] + pub fn new(items: Vec) -> Result { + check_item_count(items.len())?; + Ok(Self { + items, + imports: false, + secrets: Vec::new(), + }) + } + + /// Set the import opt-in: a network entry of an imported module can then send. + #[must_use] + pub fn with_imports(self, allow: bool) -> Self { + Self { + imports: allow, + ..self + } + } + + /// Add a host secret. A policy has at most 16 secrets, each with its own name. + #[must_use = "a secret can be refused"] + pub fn with_secret(mut self, secret: Secret) -> Result { + if self.secrets.iter().any(|known| known.name == secret.name) { + return Err(PolicyError::DuplicateSecret); + } + if self.secrets.len() >= MAX_SECRETS { + return Err(PolicyError::TooManySecrets); + } + self.secrets.push(secret); + Ok(self) + } + + /// A policy with only the grants of `items` and `imports`. Each item must permit no + /// request that this policy refuses, and `imports` can be true only when this policy + /// allows imports. The secrets stay the same. This is the one narrowing rule of every + /// host surface. + #[must_use = "a narrower policy can be refused"] + pub fn narrow(&self, items: Vec, imports: bool) -> Result { + check_item_count(items.len()).map_err(NarrowError::Policy)?; + let wider = |item: &AllowItem| !self.items.iter().any(|known| item.within(known)); + if let Some(index) = items.iter().position(wider) { + return Err(NarrowError::ItemNotAllowed { index }); + } + if imports && !self.imports { + return Err(NarrowError::ImportsNotAllowed); + } + Ok(Self { + items, + imports, + secrets: self.secrets.clone(), + }) + } + + /// Check one address that a name lookup gave, before a connection to it. An address + /// in a refused range passes only when an allow item is that exact IP address with + /// that exact port, written in the item. So a name can not open such an address that + /// the host did not list. An IPv4-mapped IPv6 address never equals an IPv4 item. + #[must_use = "an address can be refused"] + pub fn check_address(&self, address: SocketAddr) -> Result<(), Refusal> { + if !is_refused_address(address.ip()) + || self.items.iter().any(|item| item.opens_address(address)) + { + Ok(()) + } else { + Err(ADDRESS_REFUSED) + } + } +} + +impl NetworkPolicy { + /// Check the origin of a request: the allow list first, then the import opt-in for an + /// entry that an imported module declares. + pub(crate) fn check_origin( + &self, + origin: &Origin, + from_entry_module: bool, + ) -> Result<(), Refusal> { + if !self.allows(origin) { + return Err(Refusal::new( + Layer::AllowList, + "the origin is not in the allow list", + )); + } + if !from_entry_module && !self.imports { + return Err(Refusal::new( + Layer::ImportOptIn, + "a network entry of an imported module needs the import opt-in", + )); + } + Ok(()) + } + + /// Check redirect hop number `hop` (the first redirect is hop 1) from `from` to `to`. + /// The hop count binds first, then the scheme, then the allow list. + pub(crate) fn check_hop( + &self, + from: &CheckedUrl, + to: &CheckedUrl, + hop: usize, + ) -> Result { + if hop > MAX_REDIRECTS { + return Err(HopError::TooMany); + } + if from.scheme == Scheme::Https && to.scheme == Scheme::Http { + return Err(HopError::Refused(Refusal::new( + Layer::RedirectCheck, + "a redirect from https to http is refused", + ))); + } + let target = to.origin(); + if !self.allows(&target) { + return Err(HopError::Refused(Refusal::new( + Layer::RedirectCheck, + "the redirect target is not in the allow list", + ))); + } + Ok(Hop { + same_origin: from.origin() == target, + }) + } + + /// The value of the host secret `name` for a request to `origin`. The secret must + /// exist and name that exact origin, which is always an `https` origin. The core + /// binds each secret header with it, and a sender binds it again before it writes + /// the header. + #[must_use = "a secret binding can be refused"] + pub fn bind_secret(&self, name: &str, origin: &Origin) -> Result<&SecretValue, Refusal> { + let Some(secret) = self.secrets.iter().find(|secret| secret.name == name) else { + return Err(Refusal::new( + Layer::SecretBinding, + "the host gives no secret of this name", + )); + }; + if secret.origin != *origin { + return Err(Refusal::new( + Layer::SecretBinding, + "the request origin is not the origin of the secret", + )); + } + Ok(&secret.value) + } + + /// The method that a request sends. This release sends GET and HEAD only. + pub(crate) fn check_method(&self, method: DeclaredMethod) -> Result { + match method { + DeclaredMethod::Get => Ok(Method::Get), + DeclaredMethod::Head => Ok(Method::Head), + DeclaredMethod::Post + | DeclaredMethod::Put + | DeclaredMethod::Patch + | DeclaredMethod::Delete + | DeclaredMethod::Options => Err(Refusal::new( + Layer::Method, + "this release sends GET and HEAD requests only", + )), + } + } + + /// The name and the value of each host secret, for the response check only. + pub(crate) fn secrets(&self) -> impl Iterator { + self.secrets + .iter() + .map(|secret| (secret.name.as_str(), &secret.value)) + } + + fn allows(&self, origin: &Origin) -> bool { + self.items.iter().any(|item| item.matches(origin)) + } +} + +fn check_item_count(count: usize) -> Result<(), PolicyError> { + match count { + 0 => Err(PolicyError::NoItems), + 1..=MAX_ALLOW_ITEMS => Ok(()), + _ => Err(PolicyError::TooManyItems), + } +} + +/// A redirect hop that the policy allows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Hop { + same_origin: bool, +} + +impl Hop { + /// A hop to another origin drops every secret header and each credential header. + pub(crate) fn keeps_header(self, name: &str, secret: bool) -> bool { + self.same_origin || !(secret || is_credential_header(name)) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum HopError { + Refused(Refusal), + /// The chain has more than `MAX_REDIRECTS` hops: a resource limit. + TooMany, +} + +/// The refused IPv4 ranges: the first address and the prefix length. +const REFUSED_V4: [(Ipv4Addr, u32); 12] = [ + (Ipv4Addr::new(0, 0, 0, 0), 8), + (Ipv4Addr::new(10, 0, 0, 0), 8), + (Ipv4Addr::new(100, 64, 0, 0), 10), + (Ipv4Addr::new(127, 0, 0, 0), 8), + (Ipv4Addr::new(169, 254, 0, 0), 16), + (Ipv4Addr::new(172, 16, 0, 0), 12), + (Ipv4Addr::new(192, 0, 0, 0), 24), + (Ipv4Addr::new(192, 168, 0, 0), 16), + (Ipv4Addr::new(198, 18, 0, 0), 15), + (Ipv4Addr::new(224, 0, 0, 0), 4), + (Ipv4Addr::new(240, 0, 0, 0), 4), + (Ipv4Addr::new(255, 255, 255, 255), 32), +]; + +/// The refused IPv6 ranges: the first address and the prefix length. `::/96` holds the +/// unspecified and the loopback address. Each range that embeds an IPv4 address +/// (IPv4-compatible, IPv4-mapped, IPv4-translated, the two NAT64 prefixes, Teredo and 6to4) +/// is refused whole, so each IPv4 address that it embeds is too. +const REFUSED_V6: [(Ipv6Addr, u32); 11] = [ + (Ipv6Addr::UNSPECIFIED, 96), + (Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0, 0), 96), + (Ipv6Addr::new(0, 0, 0, 0, 0xffff, 0, 0, 0), 96), + (Ipv6Addr::new(0x64, 0xff9b, 0, 0, 0, 0, 0, 0), 96), + (Ipv6Addr::new(0x64, 0xff9b, 1, 0, 0, 0, 0, 0), 48), + (Ipv6Addr::new(0x2001, 0, 0, 0, 0, 0, 0, 0), 32), + (Ipv6Addr::new(0x2002, 0, 0, 0, 0, 0, 0, 0), 16), + (Ipv6Addr::new(0xfc00, 0, 0, 0, 0, 0, 0, 0), 7), + (Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0), 10), + (Ipv6Addr::new(0xfec0, 0, 0, 0, 0, 0, 0, 0), 10), + (Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0), 8), +]; + +// Each range is a valid prefix: its length fits the address, and its first address has +// no bit set past the prefix. +const _: () = { + let mut at = 0; + while at < REFUSED_V4.len() { + let (first, length) = REFUSED_V4[at]; + assert!(length <= u32::BITS); + assert!(u32::from_be_bytes(first.octets()) & !v4_mask(length) == 0); + at += 1; + } + let mut at = 0; + while at < REFUSED_V6.len() { + let (first, length) = REFUSED_V6[at]; + assert!(length <= u128::BITS); + assert!(u128::from_be_bytes(first.octets()) & !v6_mask(length) == 0); + at += 1; + } +}; + +const fn v4_mask(length: u32) -> u32 { + match u32::MAX.checked_shl(u32::BITS - length) { + Some(mask) => mask, + None => 0, + } +} + +const fn v6_mask(length: u32) -> u128 { + match u128::MAX.checked_shl(u128::BITS - length) { + Some(mask) => mask, + None => 0, + } +} + +fn is_refused_address(address: IpAddr) -> bool { + match address { + IpAddr::V4(ip) => { + let bits = u32::from(ip); + REFUSED_V4 + .iter() + .any(|&(first, length)| bits & v4_mask(length) == u32::from(first)) + } + IpAddr::V6(ip) => { + let bits = u128::from(ip); + REFUSED_V6 + .iter() + .any(|&(first, length)| bits & v6_mask(length) == u128::from(first)) + } + } +} diff --git a/crates/mds-core/src/data/policy_tests.rs b/crates/mds-core/src/data/policy_tests.rs new file mode 100644 index 00000000..3dc08129 --- /dev/null +++ b/crates/mds-core/src/data/policy_tests.rs @@ -0,0 +1,572 @@ +use std::net::SocketAddr; + +use super::policy::*; +use super::url::{parse_absolute, CheckedUrl, Origin}; +use crate::limits::{MAX_ALLOW_ITEMS, MAX_REDIRECTS, MAX_SECRETS}; + +fn item(text: &str) -> AllowItem { + AllowItem::parse(text).unwrap_or_else(|error| panic!("{text}: {error}")) +} + +fn url(text: &str) -> CheckedUrl { + parse_absolute(text).unwrap() +} + +fn origin(text: &str) -> Origin { + url(text).origin() +} + +fn policy(items: &[&str]) -> NetworkPolicy { + NetworkPolicy::new(items.iter().map(|text| item(text)).collect()).unwrap() +} + +fn value(text: &str) -> SecretValue { + SecretValue::new(text.into()).unwrap() +} + +fn secret(name: &str, at: &str) -> Secret { + Secret::new(name, value("planted-secret-value"), origin(at)).unwrap() +} + +fn address(text: &str) -> SocketAddr { + text.parse().unwrap() +} + +fn layer(result: Result) -> Layer { + result.unwrap_err().layer() +} + +/// Each accepted form names one exact origin; the default port and no port are equal. +#[test] +fn allow_items_name_one_exact_origin() { + for (text, expected) in [ + ("api.example", "https://api.example"), + ("api.example:8443", "https://api.example:8443"), + ("https://api.example", "https://api.example"), + ("https://api.example:443", "https://api.example"), + ("http://127.0.0.1:8080", "http://127.0.0.1:8080"), + ("http://api.example:80", "http://api.example"), + ("127.0.0.1:8080", "https://127.0.0.1:8080"), + ("[::1]:8080", "https://[::1]:8080"), + ("https://[::1]", "https://[::1]"), + ] { + assert_eq!(item(text).origin().to_string(), expected, "{text}"); + } +} + +/// The item grammar refuses each form outside it, with fixed text. Short IPv4 forms are +/// refused as items, as in declarations. Control: the canonical address with a port. +#[test] +fn allow_items_refuse_every_other_form() { + for text in [ + "", + "https://", + "http://api.example", + "http://127.0.0.1", + "ftp://api.example", + "HTTPS://api.example", + "Api.example", + "api.example.", + "*.example", + "api.example/path", + "api.example/", + "api.example?q", + "api.example#part", + "user@api.example", + " api.example", + "api.example:", + "api.example:0", + "api.example:65536", + "api.example:+80", + "127.1", + "2130706433", + "0x7f000001", + "127.1:8080", + "[::1", + "[fe80::1%25en0]:8080", + ] { + let error = AllowItem::parse(text).unwrap_err(); + assert!( + matches!(error, PolicyError::AllowItem(_)), + "{text}: {error:?}" + ); + if !text.is_empty() { + assert!(!error.to_string().contains(text), "{text}: {error}"); + } + } + assert!(AllowItem::parse("127.0.0.1:8080").is_ok()); +} + +/// A match needs the same scheme, the exact host and the same port. +#[test] +fn allow_items_match_the_exact_host_scheme_and_port() { + let plain = item("api.example"); + let explicit = item("api.example:443"); + for at in ["https://api.example/", "https://api.example:443/x"] { + assert!(plain.matches(&origin(at)), "{at}"); + assert!(explicit.matches(&origin(at)), "{at}"); + } + for at in [ + "http://api.example:443/", + "https://api.example:8443/", + "https://sub.api.example/", + "https://example/", + "https://api.example.org/", + ] { + assert!(!plain.matches(&origin(at)), "{at}"); + } + assert!(item("http://127.0.0.1:8080").matches(&origin("http://127.0.0.1:8080/"))); + assert!(!item("127.0.0.1:8080").matches(&origin("http://127.0.0.1:8080/"))); +} + +#[test] +fn allow_list_takes_one_to_the_item_cap() { + let items = |count: usize| (0..count).map(|i| item(&format!("h{i}.example"))).collect(); + assert_eq!( + NetworkPolicy::new(Vec::new()).unwrap_err(), + PolicyError::NoItems + ); + assert!(NetworkPolicy::new(items(MAX_ALLOW_ITEMS)).is_ok()); + let error = NetworkPolicy::new(items(MAX_ALLOW_ITEMS + 1)).unwrap_err(); + assert_eq!(error, PolicyError::TooManyItems); + assert!(error.to_string().contains(&MAX_ALLOW_ITEMS.to_string())); +} + +/// Names are identifiers in their own name space, values are visible ASCII, and a +/// secret goes to one `https` origin. Controls: the valid form of each. +#[test] +fn secrets_have_identifier_names_visible_values_and_an_https_origin() { + for name in ["", "9token", "two.parts", "a-b", "café"] { + let result = Secret::new(name, value("v"), origin("https://api.example/")); + assert_eq!(result.unwrap_err(), PolicyError::SecretName, "{name}"); + } + for text in ["", "a b", "tab\there", "line\n", "café"] { + assert_eq!( + SecretValue::new(text.into()).unwrap_err(), + PolicyError::SecretValue + ); + } + let error = Secret::new("token", value("v"), origin("http://127.0.0.1:8080/")).unwrap_err(); + assert_eq!(error, PolicyError::SecretScheme); + assert_eq!(value("!a~Z9").expose_for_send(), "!a~Z9"); + assert!(Secret::new("_token9", value("v"), origin("https://api.example/")).is_ok()); +} + +#[test] +fn policy_takes_unique_secrets_up_to_the_cap() { + let mut full = policy(&["api.example"]); + for i in 0..MAX_SECRETS { + full = full + .with_secret(secret(&format!("s{i}"), "https://api.example/")) + .unwrap(); + } + let error = full + .clone() + .with_secret(secret("extra", "https://api.example/")) + .unwrap_err(); + assert_eq!(error, PolicyError::TooManySecrets); + assert!(error.to_string().contains(&MAX_SECRETS.to_string())); + let error = policy(&["api.example"]) + .with_secret(secret("token", "https://api.example/")) + .and_then(|policy| policy.with_secret(secret("token", "https://other.example/"))) + .unwrap_err(); + assert_eq!(error, PolicyError::DuplicateSecret); +} + +/// The value is absent from `Debug` of the value, the secret and the policy, while the +/// send accessor holds it. +#[test] +fn debug_output_does_not_show_a_secret_value() { + let policy = policy(&["api.example"]) + .with_secret(secret("token", "https://api.example/")) + .unwrap(); + let bound = policy + .bind_secret("token", &origin("https://api.example/")) + .unwrap(); + assert_eq!(bound.expose_for_send(), "planted-secret-value"); + let debug = format!("{policy:?} {bound:?}"); + // Fixed messages: a failure must not show the text that holds the value. + assert!( + !debug.contains("planted-secret-value"), + "Debug must not show the secret value" + ); + assert!(debug.contains("token"), "Debug must show the secret name"); +} + +/// A secret binds only to its declared name and its exact origin. +#[test] +fn secrets_bind_to_their_name_and_origin_only() { + let policy = policy(&["api.example", "other.example"]) + .with_secret(secret("token", "https://api.example/")) + .unwrap(); + for (name, at) in [ + ("missing", "https://api.example/"), + ("token", "https://other.example/"), + ("token", "https://api.example:8443/"), + ] { + assert_eq!( + layer(policy.bind_secret(name, &origin(at))), + Layer::SecretBinding, + "{name} {at}" + ); + } + assert!(policy + .bind_secret("token", &origin("https://api.example:443/path")) + .is_ok()); +} + +/// The allow list comes first, then the import opt-in. Controls: the entry module, and +/// an imported module with the opt-in. +#[test] +fn origins_need_the_allow_list_then_the_import_opt_in() { + let closed = policy(&["api.example"]); + let open = policy(&["api.example"]).with_imports(true); + let listed = origin("https://api.example/"); + let unlisted = origin("https://other.example/"); + for from_entry in [true, false] { + assert_eq!( + layer(closed.check_origin(&unlisted, from_entry)), + Layer::AllowList + ); + assert_eq!( + layer(open.check_origin(&unlisted, from_entry)), + Layer::AllowList + ); + assert!(open.check_origin(&listed, from_entry).is_ok()); + } + assert_eq!( + layer(closed.check_origin(&listed, false)), + Layer::ImportOptIn + ); + assert!(closed.check_origin(&listed, true).is_ok()); +} + +/// TP-85 unit rows: a wider list or a wider import grant fails, a narrower list narrows, +/// and an equal list keeps the same grant. +#[test] +fn narrowing_never_widens_a_policy() { + let wide = policy(&["api.example", "http://127.0.0.1:8080"]) + .with_secret(secret("token", "https://api.example/")) + .unwrap(); + let narrowed = |items: &[&str], imports| { + wide.narrow(items.iter().map(|text| item(text)).collect(), imports) + }; + assert_eq!( + narrowed(&["api.example", "other.example"], false).unwrap_err(), + NarrowError::ItemNotAllowed { index: 1 } + ); + assert_eq!( + narrowed(&["api.example"], true).unwrap_err(), + NarrowError::ImportsNotAllowed + ); + assert_eq!( + narrowed(&[], false).unwrap_err(), + NarrowError::Policy(PolicyError::NoItems) + ); + + let narrower = narrowed(&["api.example"], false).unwrap(); + let local = origin("http://127.0.0.1:8080/"); + assert_eq!(layer(narrower.check_origin(&local, true)), Layer::AllowList); + assert!(narrower + .bind_secret("token", &origin("https://api.example/")) + .is_ok()); + + let equal = narrowed(&["http://127.0.0.1:8080", "api.example:443"], false).unwrap(); + assert!(equal.check_origin(&local, true).is_ok()); + assert!(equal + .check_origin(&origin("https://api.example/"), true) + .is_ok()); + + let open = wide.clone().with_imports(true); + let kept = open.narrow(vec![item("api.example")], true).unwrap(); + assert!(kept + .check_origin(&origin("https://api.example/"), false) + .is_ok()); + let closed = open.narrow(vec![item("api.example")], false).unwrap(); + assert_eq!( + layer(closed.check_origin(&origin("https://api.example/"), false)), + Layer::ImportOptIn + ); +} + +/// A narrower item can not gain a port that opens a refused address. Control: an item +/// can drop that port. +#[test] +fn narrowing_cannot_add_the_port_that_opens_an_address() { + let plain = policy(&["127.0.0.1"]); + assert_eq!( + plain + .narrow(vec![item("127.0.0.1:443")], false) + .unwrap_err(), + NarrowError::ItemNotAllowed { index: 0 } + ); + let explicit = policy(&["127.0.0.1:443"]); + assert!(explicit.narrow(vec![item("127.0.0.1")], false).is_ok()); + assert!(explicit.narrow(vec![item("127.0.0.1:443")], false).is_ok()); +} + +/// Both edges of each refused range are refused, and each next address outside the +/// table passes. +#[test] +fn address_table_refuses_both_edges_of_each_range() { + let open = policy(&["api.example"]); + let refused = [ + "0.0.0.0", + "0.255.255.255", + "10.0.0.0", + "10.255.255.255", + "100.64.0.0", + "100.127.255.255", + "127.0.0.0", + "127.255.255.255", + "169.254.0.0", + "169.254.255.255", + "172.16.0.0", + "172.31.255.255", + "192.0.0.0", + "192.0.0.255", + "192.168.0.0", + "192.168.255.255", + "198.18.0.0", + "198.19.255.255", + "224.0.0.0", + "239.255.255.255", + "240.0.0.0", + "255.255.255.254", + "255.255.255.255", + "[::]", + "[::1]", + "[::2]", + "[::ffff:ffff]", + "[::ffff:0.0.0.0]", + "[::ffff:255.255.255.255]", + "[::ffff:8.8.8.8]", + "[::ffff:0:0:0]", + "[::ffff:0:ffff:ffff]", + "[2001::]", + "[2001:0:ffff:ffff:ffff:ffff:ffff:ffff]", + "[2002::]", + "[2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff]", + "[64:ff9b::]", + "[64:ff9b::ffff:ffff]", + "[64:ff9b:1::]", + "[64:ff9b:1:ffff:ffff:ffff:ffff:ffff]", + "[fc00::]", + "[fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]", + "[fe80::]", + "[febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff]", + "[fec0::]", + "[feff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]", + "[ff00::]", + "[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]", + ]; + for text in refused { + assert_eq!( + layer(open.check_address(address(&format!("{text}:443")))), + Layer::TransportAddress, + "{text}" + ); + } + let passed = [ + "1.0.0.0", + "9.255.255.255", + "11.0.0.0", + "100.63.255.255", + "100.128.0.0", + "126.255.255.255", + "128.0.0.0", + "169.253.255.255", + "169.255.0.0", + "172.15.255.255", + "172.32.0.0", + "191.255.255.255", + "192.0.1.0", + "192.167.255.255", + "192.169.0.0", + "198.17.255.255", + "198.20.0.0", + "223.255.255.255", + "[::1:0:0]", + "[::fffe:ffff:ffff]", + "[::fffe:ffff:ffff:ffff]", + "[::ffff:1:0:0]", + "[::1:0:0:0]", + "[2000:ffff:ffff:ffff:ffff:ffff:ffff:ffff]", + "[2001:1::]", + "[2001:ffff:ffff:ffff:ffff:ffff:ffff:ffff]", + "[2003::]", + "[64:ff9a:ffff:ffff:ffff:ffff:ffff:ffff]", + "[64:ff9b::1:0:0]", + "[64:ff9b:0:ffff:ffff:ffff:ffff:ffff]", + "[64:ff9b:2::]", + "[fbff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]", + "[fe00::]", + "[fe7f:ffff:ffff:ffff:ffff:ffff:ffff:ffff]", + ]; + for text in passed { + assert!( + open.check_address(address(&format!("{text}:443"))).is_ok(), + "{text}" + ); + } +} + +/// A refused address passes only for an item of that exact IP literal with that exact +/// port. A mapped form never equals an IPv4 item. Controls: the exact address and port. +#[test] +fn only_an_exact_ip_item_with_its_port_opens_a_refused_address() { + let listed = policy(&["127.0.0.1:8080", "http://[::1]:9090", "api.example"]); + assert!(listed.check_address(address("127.0.0.1:8080")).is_ok()); + assert!(listed.check_address(address("[::1]:9090")).is_ok()); + for text in [ + "127.0.0.1:8081", + "127.0.0.2:8080", + "127.0.0.1:443", + "[::ffff:127.0.0.1]:8080", + "[::1]:8080", + "10.0.0.1:443", + ] { + assert_eq!( + layer(listed.check_address(address(text))), + Layer::TransportAddress, + "{text}" + ); + } + let no_port = policy(&["127.0.0.1"]); + assert_eq!( + layer(no_port.check_address(address("127.0.0.1:443"))), + Layer::TransportAddress + ); + let mapped = policy(&["[::ffff:127.0.0.1]:8080"]); + assert!(mapped + .check_address(address("[::ffff:127.0.0.1]:8080")) + .is_ok()); + assert_eq!( + layer(mapped.check_address(address("127.0.0.1:8080"))), + Layer::TransportAddress + ); +} + +/// TP-87 unit rows: a hop to `http://169.254.169.254/` and a hop to an unlisted host fail +/// the redirect check, and so does https to http. Control: a hop to a listed origin. +#[test] +fn redirect_hops_stay_on_the_allow_list_and_never_drop_to_http() { + let listed = policy(&[ + "http://127.0.0.1:8080", + "api.example", + "http://api.example:80", + ]); + let refused = |from: &str, to: &str| match listed.check_hop(&url(from), &url(to), 1) { + Err(HopError::Refused(refusal)) => refusal.layer(), + other => panic!("{from} -> {to}: {other:?}"), + }; + assert_eq!( + refused("http://127.0.0.1:8080/", "http://169.254.169.254/"), + Layer::RedirectCheck + ); + assert_eq!( + refused("https://api.example/", "https://other.example/"), + Layer::RedirectCheck + ); + assert_eq!( + refused("https://api.example/", "http://api.example/"), + Layer::RedirectCheck + ); + for (from, to) in [ + ("http://127.0.0.1:8080/", "http://127.0.0.1:8080/next"), + ("http://api.example/", "https://api.example/"), + ("https://api.example/", "https://api.example:443/next"), + ] { + assert!(listed.check_hop(&url(from), &url(to), 1).is_ok(), "{to}"); + } +} + +#[test] +fn redirect_chains_take_the_hop_cap() { + let listed = policy(&["api.example"]); + let (from, to) = (url("https://api.example/a"), url("https://api.example/b")); + assert!(listed.check_hop(&from, &to, MAX_REDIRECTS).is_ok()); + assert_eq!( + listed.check_hop(&from, &to, MAX_REDIRECTS + 1).unwrap_err(), + HopError::TooMany + ); +} + +/// A hop to another origin drops each secret header and each credential header in any +/// letter case. Controls: a same-origin hop keeps them, and a plain header goes on. +#[test] +fn cross_origin_hops_drop_secret_and_credential_headers() { + let listed = policy(&["api.example", "other.example"]); + let start = url("https://api.example/a"); + let same = listed + .check_hop(&start, &url("https://api.example:443/b"), 1) + .unwrap(); + let cross = listed + .check_hop(&start, &url("https://other.example/b"), 1) + .unwrap(); + for name in [ + "Authorization", + "cookie", + "PROXY-AUTHORIZATION", + "X-Api-Key", + ] { + assert!(same.keeps_header(name, false), "{name}"); + assert!(!cross.keeps_header(name, false), "{name}"); + } + assert!(same.keeps_header("X-Token", true)); + assert!(!cross.keeps_header("X-Token", true)); + assert!(cross.keeps_header("X-Trace", false)); +} + +#[test] +fn layer_names_are_distinct_kebab_case_words() { + let names = [ + Layer::AllowList, + Layer::ImportOptIn, + Layer::UrlParser, + Layer::RedirectCheck, + Layer::SecretBinding, + Layer::TransportAddress, + Layer::ResponseCheck, + Layer::Method, + ] + .map(Layer::name); + assert_eq!( + names, + [ + "allow-list", + "import-opt-in", + "url-parser", + "redirect-check", + "secret-binding", + "transport-address", + "response-check", + "method", + ] + ); +} + +/// This release sends GET and HEAD only. Every other declared method is refused with +/// the method layer. +#[test] +fn only_get_and_head_pass_the_method_check() { + use super::decl::DeclaredMethod; + use super::request::Method; + let policy = NetworkPolicy::new(vec![AllowItem::parse("a.example").unwrap()]).unwrap(); + assert_eq!(policy.check_method(DeclaredMethod::Get), Ok(Method::Get)); + assert_eq!(policy.check_method(DeclaredMethod::Head), Ok(Method::Head)); + for method in [ + DeclaredMethod::Post, + DeclaredMethod::Put, + DeclaredMethod::Patch, + DeclaredMethod::Delete, + DeclaredMethod::Options, + ] { + let refusal = policy.check_method(method).unwrap_err(); + assert_eq!(refusal.layer(), Layer::Method); + assert_eq!( + refusal.reason(), + "this release sends GET and HEAD requests only" + ); + } +} diff --git a/crates/mds-core/src/data/refs.rs b/crates/mds-core/src/data/refs.rs index 4f2ae288..de2cc197 100644 --- a/crates/mds-core/src/data/refs.rs +++ b/crates/mds-core/src/data/refs.rs @@ -2,20 +2,60 @@ use crate::lexer::find_interpolation_close; use crate::limits::MAX_DOT_SEGMENTS; use crate::parser::is_valid_identifier; -/// Visit each unescaped reference in the original text. Do not scan inserted text. -pub(super) fn references(text: &str) -> impl Iterator> { +/// One piece of the original text of a URL, header or body template. +#[derive(Debug, PartialEq, Eq)] +pub(super) enum Piece<'a> { + /// Text as written. An escaped `\{{` keeps its backslash here. + Literal(&'a str), + /// The trimmed path of an unescaped `{{…}}` reference. + Reference(&'a str), +} + +/// Split the original text into literal text and unescaped references, in order. An +/// unclosed reference ends the pieces with an error. Do not scan inserted text. +pub(super) fn pieces(text: &str) -> impl Iterator, &'static str>> { let mut rest = text; + let mut next = None; std::iter::from_fn(move || { - let (start, _) = rest + if let Some(reference) = next.take() { + return Some(reference); + } + if rest.is_empty() { + return None; + } + let Some((start, _)) = rest .match_indices("{{") - .find(|&(index, _)| index == 0 || rest.as_bytes()[index - 1] != b'\\')?; + .find(|&(index, _)| index == 0 || rest.as_bytes()[index - 1] != b'\\') + else { + return Some(Ok(Piece::Literal(std::mem::take(&mut rest)))); + }; + let literal = &rest[..start]; let after_open = &rest[start + 2..]; - let Some(close) = find_interpolation_close(after_open.char_indices()) else { - rest = ""; - return Some(Err("unclosed `{{` reference")); + let reference = match find_interpolation_close(after_open.char_indices()) { + Some(close) => { + rest = &after_open[close + 2..]; + parse_reference(after_open[..close].trim()).map(Piece::Reference) + } + None => { + rest = ""; + Err("unclosed `{{` reference") + } }; - rest = &after_open[close + 2..]; - Some(parse_reference(after_open[..close].trim())) + if literal.is_empty() { + Some(reference) + } else { + next = Some(reference); + Some(Ok(Piece::Literal(literal))) + } + }) +} + +/// Visit each unescaped reference in the original text. Do not scan inserted text. +pub(super) fn references(text: &str) -> impl Iterator> { + pieces(text).filter_map(|piece| match piece { + Ok(Piece::Literal(_)) => None, + Ok(Piece::Reference(path)) => Some(Ok(path)), + Err(reason) => Some(Err(reason)), }) } diff --git a/crates/mds-core/src/data/request.rs b/crates/mds-core/src/data/request.rs new file mode 100644 index 00000000..0d70670f --- /dev/null +++ b/crates/mds-core/src/data/request.rs @@ -0,0 +1,421 @@ +//! The requests of network data entries and their identity. +//! +//! A request carries a descriptor of each secret header, never the secret value. The +//! request ID is the SHA-256 digest of the exact request. A secret header enters the +//! digest as its name, its prefix and the HMAC-SHA-256 of its value under the per-run +//! key, so two requests that differ in one header value have two IDs, and an ID permits +//! no offline guess of a short secret. + +use std::error::Error; +use std::fmt; + +use super::digest::{hex, hmac_sha256, sha256}; +use super::policy::{NetworkPolicy, Refusal, SecretValue}; +use super::url::{CheckedUrl, Host}; +use super::Accept; + +/// The per-run key of the keyed hash of secret header values. The host makes it from a +/// random source once per run. Its `Debug` shows no key. +/// +/// This type is `#[non_exhaustive]`: obtain keys from [`RunKey::from_bytes`]. +#[non_exhaustive] +pub struct RunKey([u8; 32]); + +impl RunKey { + /// A key of 32 bytes from a random source. + #[must_use] + pub fn from_bytes(bytes: [u8; 32]) -> Self { + Self(bytes) + } +} + +impl fmt::Debug for RunKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("RunKey(..)") + } +} + +/// The method of a request. This release sends GET and HEAD only. +/// +/// This enum is `#[non_exhaustive]`: new methods may be added in minor releases. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Method { + Get, + Head, +} + +impl Method { + /// The method name: `GET` or `HEAD`. + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Method::Get => "GET", + Method::Head => "HEAD", + } + } +} + +/// The identity of a request: a SHA-256 digest of the exact request. +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct RequestId([u8; 32]); + +impl RequestId { + /// The ID as 64 lower-case hex digits. + #[must_use] + pub fn as_hex(&self) -> String { + hex(&self.0) + } + + /// Parse an ID from exactly 64 lower-case hex digits. + #[must_use = "an ID can be refused"] + pub fn parse_hex(text: &str) -> Result { + let (pairs, []) = text.as_bytes().as_chunks::<2>() else { + return Err(RequestIdError); + }; + let mut id = [0u8; 32]; + if pairs.len() != id.len() { + return Err(RequestIdError); + } + for (byte, &[high, low]) in id.iter_mut().zip(pairs) { + *byte = (lower_hex_digit(high).ok_or(RequestIdError)? << 4) + | lower_hex_digit(low).ok_or(RequestIdError)?; + } + Ok(Self(id)) + } +} + +impl fmt::Debug for RequestId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "RequestId({})", self.as_hex()) + } +} + +/// Text that is not 64 lower-case hex digits. +/// +/// This type is `#[non_exhaustive]` and cannot be built outside the core. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RequestIdError; + +impl fmt::Display for RequestIdError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a request ID is 64 lower-case hex digits") + } +} + +impl Error for RequestIdError {} + +/// The value of a request header. Its `Debug` shows the secret name and the prefix of a +/// secret value, and never the text of a text value. +/// +/// This enum is `#[non_exhaustive]`: new value kinds may be added in minor releases. +#[non_exhaustive] +#[derive(Clone, PartialEq, Eq)] +pub enum HeaderValue { + /// The final header text. + Text(String), + /// A host secret: the secret name and the literal prefix, never the value. The + /// sender writes the prefix and then the value of the bound secret. + Secret { name: String, prefix: String }, +} + +impl fmt::Debug for HeaderValue { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + HeaderValue::Text(_) => f.write_str("Text(..)"), + HeaderValue::Secret { name, prefix } => f + .debug_struct("Secret") + .field("name", name) + .field("prefix", prefix) + .finish(), + } + } +} + +/// One header of a request. +/// +/// This type is `#[non_exhaustive]`: obtain headers from [`Request::headers`]. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RequestHeader { + name: String, + value: HeaderValue, +} + +impl RequestHeader { + /// The header name as declared. + #[must_use] + pub fn name(&self) -> &str { + &self.name + } + + #[must_use] + pub fn value(&self) -> &HeaderValue { + &self.value + } +} + +impl RequestHeader { + pub(crate) fn new(name: String, value: HeaderValue) -> Self { + Self { name, value } + } +} + +/// A request that the core needs and that passed every policy check. +/// +/// Its `Debug` shows the ID, the method, the URL as declared, the origin and the header +/// names, never the expanded path or query or a header value. +/// +/// This type is `#[non_exhaustive]`: obtain requests from the core. +#[non_exhaustive] +#[derive(Clone, PartialEq, Eq)] +pub struct Request { + id: RequestId, + method: Method, + /// The URL as declared, with its `{{…}}` text. + template: String, + url: CheckedUrl, + accept: Accept, + headers: Vec, +} + +impl fmt::Debug for Request { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Request") + .field("id", &self.id) + .field("method", &self.method) + .field("template", &self.template) + .field("origin", &format_args!("{}", self.url.origin())) + .field("headers", &self.headers) + .finish_non_exhaustive() + } +} + +impl Request { + #[must_use] + pub fn id(&self) -> RequestId { + self.id + } + + #[must_use] + pub fn method(&self) -> Method { + self.method + } + + /// The URL as declared, with its `{{…}}` text. A message about the request shows + /// this text and the origin, never the URL of [`Request::url`]. + #[must_use] + pub fn template(&self) -> &str { + &self.template + } + + #[must_use] + pub fn url(&self) -> &CheckedUrl { + &self.url + } + + /// The headers in declaration order. + #[must_use] + pub fn headers(&self) -> &[RequestHeader] { + &self.headers + } +} + +impl Request { + /// A request with its ID. `template` is the URL as declared, for messages only: it is + /// not part of the identity. Each secret header must name a host secret that is + /// bound to the origin of `url`; else the request fails the secret binding. + pub(crate) fn new( + method: Method, + template: &str, + url: CheckedUrl, + accept: Accept, + headers: Vec, + key: &RunKey, + policy: &NetworkPolicy, + ) -> Result { + let origin = url.origin(); + let mut keys = Vec::with_capacity(headers.len()); + for header in &headers { + let value = match &header.value { + HeaderValue::Text(text) => Part::Text(text), + HeaderValue::Secret { name, prefix } => Part::Secret { + name, + prefix, + value: policy.bind_secret(name, &origin)?, + }, + }; + keys.push(header_key(&header.name, value, key)); + } + Ok(Self { + id: identity(method, &url, accept, keys), + method, + template: template.to_owned(), + url, + accept, + headers, + }) + } +} + +/// The version tag of the canonical text. Change it with any change of the text. +const IDENTITY_VERSION: &str = "mds-request-1"; + +/// The fields of the canonical text apart from the header keys: the version tag, the +/// method, the URL, the format, the header count and the body. +const FIXED_FIELDS: usize = 6; + +/// The longest decimal length of a `usize`, for a netstring prefix. +const MAX_LENGTH_DIGITS: usize = 20; + +/// The longest text of a host IP address: an IPv6 address with its brackets. +const MAX_IP_HOST_BYTES: usize = 47; + +/// An upper bound of the bytes that the identity of a request with `url` and `headers` +/// allocates while [`Request::new`] builds it: the URL text, each header key and the +/// canonical text, each counted at twice its length for buffer growth. A secret header +/// counts the hex HMAC of its value, never the value. The caller charges this bound +/// before it builds the request. `None` is a count past the address space. +pub(crate) fn identity_bytes(url: &CheckedUrl, headers: &[RequestHeader]) -> Option { + let host = match &url.host { + Host::Name(name) => name.len(), + Host::V4(_) | Host::V6(_) => MAX_IP_HOST_BYTES, + }; + // `https://`, the host, `:` and five port digits, the path, `?` and the query. + let url_text = host + .checked_add("https://:65535?".len())? + .checked_add(url.path.len())? + .checked_add(url.query.as_ref().map_or(0, String::len))?; + let mut keys = 0usize; + for header in headers { + let parts = match &header.value { + HeaderValue::Text(text) => netstring_len(text)?, + HeaderValue::Secret { name, prefix } => netstring_len(name)? + .checked_add(netstring_len(prefix)?)? + .checked_add(MAX_LENGTH_DIGITS + 1 + HMAC_HEX_BYTES)?, + }; + // The lower-case name, NUL and the kind byte, the name netstring and the parts, + // and the lower-case copy and the hex HMAC that the key is built from. + let key = header + .name + .len() + .checked_mul(2)? + .checked_add(2)? + .checked_add(netstring_len(&header.name)?)? + .checked_add(parts)? + .checked_add(HMAC_HEX_BYTES)?; + keys = keys.checked_add(key)?.checked_add(size_of::())?; + } + let fields = FIXED_FIELDS.checked_add(headers.len())?.checked_mul(8)?; + let text = fields + .checked_add(IDENTITY_VERSION.len() + "HEAD".len() + "json".len() + 8)? + .checked_add(url_text)? + .checked_add(keys)?; + url_text + .checked_add(keys)? + .checked_add(text)? + .checked_mul(2) +} + +/// The hex digits of one HMAC-SHA-256 value. +const HMAC_HEX_BYTES: usize = 64; + +/// An upper bound of the netstring of `text`: its length digits, `:` and its bytes. +fn netstring_len(text: &str) -> Option { + text.len().checked_add(MAX_LENGTH_DIGITS + 1) +} + +/// The SHA-256 digest of the canonical text of a request. The text is a sequence of +/// fields, each its byte length as a u64 big-endian number and then its bytes: the +/// version tag, the method, the URL text, the format (`json`, `yaml` or `text`), the +/// header count as a u64 big-endian number, each header key in byte order, and the body +/// (empty in this release). +fn identity(method: Method, url: &CheckedUrl, accept: Accept, mut keys: Vec) -> RequestId { + // The keys are strings, so this sort is the one string sort that the crate has, and + // the WASM build carries no other sort code for it. + keys.sort_unstable(); + let mut text = Vec::new(); + let count = u64::try_from(keys.len()).unwrap_or(u64::MAX).to_be_bytes(); + for part in [ + IDENTITY_VERSION.as_bytes(), + method.as_str().as_bytes(), + url.to_text().as_bytes(), + accept_name(accept).as_bytes(), + &count, + ] { + push_field(&mut text, part); + } + for header in &keys { + push_field(&mut text, header.as_bytes()); + } + push_field(&mut text, b""); + RequestId(sha256(&[&text])) +} + +/// The value of one header as the identity reads it. +enum Part<'a> { + Text(&'a str), + Secret { + name: &'a str, + prefix: &'a str, + value: &'a SecretValue, + }, +} + +/// The key of one header: the lower-case name and NUL, so that the keys sort in +/// lower-case name order, and then the parts as netstrings (byte length, `:`, bytes). +/// A text header gives `t`, the name and the text. A secret header gives `s`, the name, +/// the secret name, the prefix and the hex HMAC-SHA-256 of the value under the run key. +fn header_key(name: &str, value: Part<'_>, key: &RunKey) -> String { + let name = name.to_ascii_lowercase(); + let mut text = format!("{name}\0"); + match value { + Part::Secret { + name: secret, + prefix, + value, + } => { + let hmac = hex(&hmac_sha256(&key.0, &[value.expose_for_send().as_bytes()])); + text.push('s'); + for part in [name.as_str(), secret, prefix, &hmac] { + push_netstring(&mut text, part); + } + } + Part::Text(value) => { + text.push('t'); + for part in [name.as_str(), value] { + push_netstring(&mut text, part); + } + } + } + text +} + +fn push_field(out: &mut Vec, bytes: &[u8]) { + let length = u64::try_from(bytes.len()).unwrap_or(u64::MAX); + out.extend_from_slice(&length.to_be_bytes()); + out.extend_from_slice(bytes); +} + +fn push_netstring(out: &mut String, text: &str) { + out.push_str(&text.len().to_string()); + out.push(':'); + out.push_str(text); +} + +fn accept_name(accept: Accept) -> &'static str { + match accept { + Accept::Json => "json", + Accept::Yaml => "yaml", + Accept::Text => "text", + } +} + +fn lower_hex_digit(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + _ => None, + } +} diff --git a/crates/mds-core/src/data/request_tests.rs b/crates/mds-core/src/data/request_tests.rs new file mode 100644 index 00000000..d075683c --- /dev/null +++ b/crates/mds-core/src/data/request_tests.rs @@ -0,0 +1,295 @@ +use super::digest::{hex, hmac_sha256, sha256}; +use super::policy::{AllowItem, Layer, NetworkPolicy, Secret, SecretValue}; +use super::request::*; +use super::url::parse_absolute; +use super::Accept; + +const PLANTED: &str = "planted-secret-value"; +const URL: &str = "https://api.example/items?q=1"; +const TEMPLATE: &str = "https://api.example/{{kind}}?q={{query}}"; + +fn key(byte: u8) -> RunKey { + RunKey::from_bytes([byte; 32]) +} + +fn policy() -> NetworkPolicy { + let items = vec![AllowItem::parse("api.example").unwrap()]; + let origin = AllowItem::parse("api.example").unwrap().origin(); + let value = SecretValue::new(PLANTED.into()).unwrap(); + NetworkPolicy::new(items) + .unwrap() + .with_secret(Secret::new("token", value, origin).unwrap()) + .unwrap() +} + +fn text(name: &str, value: &str) -> RequestHeader { + RequestHeader::new(name.into(), HeaderValue::Text(value.into())) +} + +fn secret(name: &str, secret: &str) -> RequestHeader { + let value = HeaderValue::Secret { + name: secret.into(), + prefix: "Bearer ".into(), + }; + RequestHeader::new(name.into(), value) +} + +fn request(url: &str, headers: Vec, key: &RunKey) -> Request { + let url = parse_absolute(url).unwrap(); + Request::new( + Method::Get, + TEMPLATE, + url, + Accept::Json, + headers, + key, + &policy(), + ) + .unwrap() +} + +fn id(url: &str, headers: Vec) -> RequestId { + request(url, headers, &key(1)).id() +} + +/// TP-79 unit: equal requests have one ID. The header order and the letter case of a +/// header name do not change it. +#[test] +fn equal_requests_have_one_id() { + let headers = || vec![text("X-B", "2"), text("x-a", "1")]; + assert_eq!(id(URL, headers()), id(URL, headers())); + assert_eq!( + id(URL, headers()), + id(URL, vec![text("X-A", "1"), text("x-b", "2")]) + ); +} + +/// A change to any one part of a request gives another ID. +#[test] +fn each_request_part_changes_the_id() { + let base = id(URL, vec![text("X-A", "1")]); + let url = parse_absolute(URL).unwrap(); + let headers = vec![text("X-A", "1")]; + let other = |method, accept| { + Request::new( + method, + TEMPLATE, + url.clone(), + accept, + headers.clone(), + &key(1), + &policy(), + ) + .unwrap() + .id() + }; + for changed in [ + id("https://api.example/items?q=2", vec![text("X-A", "1")]), + id("https://api.example/items", vec![text("X-A", "1")]), + id(URL, vec![text("X-A", "2")]), + id(URL, vec![text("X-B", "1")]), + id(URL, vec![text("X-A", "1"), text("X-A", "1")]), + id(URL, Vec::new()), + other(Method::Head, Accept::Json), + other(Method::Get, Accept::Yaml), + other(Method::Get, Accept::Text), + ] { + assert_ne!(changed, base); + } + assert_eq!(other(Method::Get, Accept::Json), base); +} + +/// The same URL with and without a secret header gives two IDs, and a secret header +/// differs from text that names the same parts. +#[test] +fn a_secret_header_changes_the_id() { + let with_secret = id(URL, vec![secret("Authorization", "token")]); + assert_ne!(with_secret, id(URL, Vec::new())); + assert_ne!(with_secret, id(URL, vec![text("Authorization", "Bearer ")])); + assert_ne!( + with_secret, + id( + URL, + vec![text("Authorization", &format!("Bearer {PLANTED}"))] + ) + ); +} + +/// Two run keys change only the ID of a request with a secret header. +#[test] +fn the_run_key_changes_only_secret_request_ids() { + let plain = || vec![text("X-A", "1")]; + assert_eq!( + request(URL, plain(), &key(1)).id(), + request(URL, plain(), &key(2)).id() + ); + let bound = || vec![secret("Authorization", "token")]; + assert_ne!( + request(URL, bound(), &key(1)).id(), + request(URL, bound(), &key(2)).id() + ); +} + +/// A secret header needs a host secret of that name that is bound to the request origin. +/// Control: the bound origin with its default port written. +#[test] +fn secret_headers_bind_to_the_secret_origin() { + for (url, name) in [ + ("https://api.example/x", "missing"), + ("https://api.example:8443/x", "token"), + ] { + let url = parse_absolute(url).unwrap(); + let refused = Request::new( + Method::Get, + TEMPLATE, + url, + Accept::Json, + vec![secret("Authorization", name)], + &key(1), + &policy(), + ) + .unwrap_err(); + assert_eq!(refused.layer(), Layer::SecretBinding, "{name}"); + } + let bound = request( + "https://api.example:443/x", + vec![secret("Authorization", "token")], + &key(1), + ); + assert_eq!(bound.headers().len(), 1); +} + +/// `Debug` of a request with a secret header shows the descriptor, never the value. +/// Control: the descriptor parts are in `Debug`. +#[test] +fn debug_output_of_a_secret_request_has_no_secret_value() { + let bound = request(URL, vec![secret("Authorization", "token")], &key(1)); + let debug = format!("{bound:?} {:?}", key(7)); + // Fixed messages: a failure must not show the text that holds the value. + assert!( + !debug.contains(PLANTED), + "Debug must not show the secret value" + ); + assert!( + debug.contains("token") && debug.contains("Bearer "), + "Debug must show the secret name and prefix" + ); + assert!( + !debug.contains("[7, 7"), + "Debug must not show the key bytes" + ); +} + +/// `Debug` of a request and of its URL shows the URL as declared, the origin and the +/// header names, never the expanded path or query or a header value. Control: the +/// template, the origin and the header name are in `Debug`. +#[test] +fn debug_output_of_a_request_has_no_expanded_url_or_header_value() { + let markers = ["marker-path", "marker-query", "marker-header"]; + let planted = request( + "https://api.example/marker-path?q=marker-query", + vec![text("X-Echo", "marker-header")], + &key(1), + ); + assert_eq!(planted.url().path(), "/marker-path"); + let request = format!("{planted:?}"); + let url = format!("{:?}", planted.url()); + let headers = format!("{:?}", planted.headers()); + for debug in [&request, &url, &headers] { + for marker in markers { + assert!(!debug.contains(marker), "{marker} in {debug}"); + } + } + for debug in [&request, &url] { + assert!(debug.contains(r#"origin: https://api.example"#), "{debug}"); + } + assert!(request.contains(TEMPLATE), "{request}"); + assert!(headers.contains("X-Echo"), "{headers}"); + assert_eq!(planted.template(), TEMPLATE); +} + +/// The ID is the SHA-256 digest of the documented canonical text, with the HMAC of the +/// secret value under the run key. +#[test] +fn the_id_is_the_digest_of_the_canonical_text() { + fn field(out: &mut Vec, bytes: &[u8]) { + out.extend_from_slice(&u64::try_from(bytes.len()).unwrap().to_be_bytes()); + out.extend_from_slice(bytes); + } + let hmac = hex(&hmac_sha256(&[1; 32], &[PLANTED.as_bytes()])); + let mut canonical = Vec::new(); + for part in ["mds-request-1", "GET", URL, "json"] { + field(&mut canonical, part.as_bytes()); + } + field(&mut canonical, &2u64.to_be_bytes()); + let secret_key = format!("authorization\0s13:authorization5:token7:Bearer 64:{hmac}"); + field(&mut canonical, secret_key.as_bytes()); + field(&mut canonical, b"x-a\0t3:x-a1:1"); + field(&mut canonical, b""); + let expected = sha256(&[&canonical]); + let actual = id( + URL, + vec![text("X-A", "1"), secret("Authorization", "token")], + ); + assert_eq!(actual.as_hex(), hex(&expected)); +} + +/// The charge bound of the identity covers twice the canonical text, for a request with +/// no header and for one with a long text header and a secret header. +#[test] +fn the_identity_bound_covers_the_canonical_text() { + fn netstring(text: &str) -> String { + format!("{}:{text}", text.len()) + } + let long = "v".repeat(8 * 1024); + let hmac = hex(&hmac_sha256(&[1; 32], &[PLANTED.as_bytes()])); + let cases = [ + (Vec::new(), Vec::new()), + ( + vec![text("X-Long", &long), secret("Authorization", "token")], + vec![ + format!("x-long\0t{}{}", netstring("x-long"), netstring(&long)), + format!( + "authorization\0s{}{}{}{}", + netstring("authorization"), + netstring("token"), + netstring("Bearer "), + netstring(&hmac) + ), + ], + ), + ]; + for (headers, keys) in cases { + let fields = ["mds-request-1", "GET", URL, "json"] + .iter() + .map(|part| part.len()) + .chain([8]) + .chain(keys.iter().map(String::len)) + .chain([0]); + let canonical: usize = fields.map(|len| len + 8).sum(); + let url = parse_absolute(URL).unwrap(); + let bound = identity_bytes(&url, &headers).unwrap(); + assert!(bound >= 2 * canonical, "{bound} < 2 * {canonical}"); + } +} + +/// The hex form is exactly 64 lower-case hex digits. Control: the form of a real ID. +#[test] +fn request_ids_round_trip_through_lower_case_hex() { + let original = id(URL, Vec::new()); + let text = original.as_hex(); + assert_eq!(text.len(), 64); + assert_eq!(RequestId::parse_hex(&text), Ok(original)); + for bad in [ + String::new(), + "remote".into(), + text.to_uppercase(), + text[1..].to_owned(), + format!("{text}0"), + format!("g{}", &text[1..]), + format!("+{}", &text[1..]), + format!(" {}", &text[1..]), + ] { + assert_eq!(RequestId::parse_hex(&bad), Err(RequestIdError), "{bad}"); + } +} diff --git a/crates/mds-core/src/data/resolve.rs b/crates/mds-core/src/data/resolve.rs index e5f05216..f53079d1 100644 --- a/crates/mds-core/src/data/resolve.rs +++ b/crates/mds-core/src/data/resolve.rs @@ -20,6 +20,9 @@ pub(crate) struct State { pub(crate) files: IndexMap>, pub(crate) entries: usize, pub(crate) bytes: usize, + /// The step context of a step compile. Only `ModuleCache::stepping` sets it, so a + /// compile without it sends nothing and a frontier stays a refusal. + pub(crate) net: Option, } /// Per-file declarations and names, in a shared chain from child to base. @@ -307,7 +310,7 @@ pub(crate) fn read_file( text.as_bytes(), accept, DataLabel { - file: Some(&display), + input: crate::data::DataInput::File(&display), ..label }, mem, @@ -349,7 +352,7 @@ mod tests { let label = DataLabel { module: "entry.mds", entry: "item", - file: None, + input: crate::data::DataInput::Declaration, }; std::fs::write(&path, "[").unwrap(); let (key, accept) = canonical_file(&fs, &dir, "./item.yml", label).unwrap(); diff --git a/crates/mds-core/src/data/step.rs b/crates/mds-core/src/data/step.rs new file mode 100644 index 00000000..1295989f --- /dev/null +++ b/crates/mds-core/src/data/step.rs @@ -0,0 +1,1039 @@ +//! The step engine: the requests of URL data entries and the binding of their responses. +//! +//! A step compile runs the whole resolver once per round. For each URL entry, in level +//! order, it derives the request, checks it against the network policy and looks it up +//! in the responses of the host. An entry with a response binds its value; an entry +//! with no response yet adds its request to the needed list and stays pending, and so +//! does each entry that references a pending entry. The host sends the needed requests +//! and runs the next round with every response it has, so the core keeps no state +//! between rounds. +//! +//! # Sinks of request text +//! +//! The expanded URL, a header value, a secret value and response text reach no sink but +//! the needed [`Request`] list, which is for the sender only. Each other sink has one +//! builder: +//! +//! - Error messages: [`request_label`] builds every message about a request +//! (`mds::network`, `mds::network_denied`, the redirect limit) from the module, the +//! entry, the URL as declared and the origin, through `request_location`. The help of +//! a refusal is the fixed help of its check. A value error of a response names the +//! entry and never a key path (`DataLabel::error`), and an envelope error names the +//! field `headers` only. +//! - Warnings: a step compile adds none. The pending warning of the tooling roles names +//! the module and the entry only. +//! - `Debug`: `Request` and `CheckedUrl` show the URL as declared and the origin, a text +//! header value shows no text, [`Response`] and [`FetchState`] show sizes only, and a +//! secret value and the run key show no value. +//! - Result fields: [`RemoteInput`] holds the template form, and `dependencies` holds +//! files only. +//! - Lint JSON: the data rules read the declarations, never a response, and name the +//! entry and the header name, never a value. +//! - CLI stderr: the CLI prints the messages above. + +use std::collections::hash_map::Entry; +use std::collections::{HashMap, HashSet}; +use std::fmt; +use std::sync::Arc; + +use indexmap::IndexMap; + +use super::decl::{is_sender_header, HeaderSource, RequestTemplate}; +use super::encode::{self, FieldLabel, Target}; +use super::graph::Node; +use super::policy::{HopError, Layer, NetworkPolicy, Refusal, ADDRESS_REFUSED}; +use super::request::RunKey; +use super::request::{identity_bytes, HeaderValue, Method, Request, RequestHeader, RequestId}; +use super::url::{self, CheckedUrl, Host, Origin}; +use super::{convert, envelope, Accept, DataInput, DataLabel}; +use crate::error::request_location; +use crate::evaluator::budget::{MemBudget, Part}; +use crate::limits::{ + MAX_HEADER_VALUE_BYTES, MAX_REDIRECTS, MAX_REQUESTS_PER_COMPILE, + MAX_RESPONSE_BODY_BYTES_PER_COMPILE, MAX_RESPONSE_BYTES, MAX_RESPONSE_HEADER_BYTES, + MAX_URL_BYTES, +}; +use crate::scope::VarLayer; +use crate::value::{Value, MAX_VALUE_DEPTH}; +use crate::{CompileResult, MdsError}; + +/// The answer of the host to one request. The core checks every cap of the answer +/// again when a step compile reads it. Its `Debug` shows the status and the sizes only. +/// +/// This enum is `#[non_exhaustive]`: obtain answers from [`Response::http`] and +/// [`Response::failed`]. +#[non_exhaustive] +#[derive(Clone)] +pub enum Response { + /// An HTTP answer: the status, the headers in received order and the body. + #[non_exhaustive] + Http { + status: u16, + headers: Vec<(String, Vec)>, + body: Vec, + }, + /// The request got no HTTP answer. + #[non_exhaustive] + Failed(TransportFailure), +} + +impl Response { + /// An HTTP answer: the status, the headers in received order and the body. The + /// sender follows no redirect: a redirect answer is given as it is. + #[must_use] + pub fn http(status: u16, headers: Vec<(String, Vec)>, body: Vec) -> Self { + Self::Http { + status, + headers, + body, + } + } + + /// A request that got no HTTP answer. + #[must_use] + pub fn failed(failure: TransportFailure) -> Self { + Self::Failed(failure) + } +} + +impl fmt::Debug for Response { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Response::Http { + status, + headers, + body, + } => f + .debug_struct("Http") + .field("status", status) + .field("headers", &headers.len()) + .field("body_bytes", &body.len()) + .finish(), + Response::Failed(failure) => f.debug_tuple("Failed").field(failure).finish(), + } + } +} + +/// Why a request got no HTTP answer. The core gives each kind its own fixed message. +/// +/// This enum is `#[non_exhaustive]`: new kinds may be added in minor releases. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TransportFailure { + Timeout, + Connect, + Tls, + /// An address that the name lookup gave is in a refused range: see + /// [`NetworkPolicy::check_address`]. One such address fails the request. + AddressRefused, + /// The body is longer than 10 MiB. + BodyTooLarge, + /// The status line and the headers are longer than 16 KiB. + HeadersTooLarge, + /// The answer is not valid HTTP. + Protocol, +} + +impl TransportFailure { + /// The fixed text of the failure. It never holds response text. + fn kind(self) -> String { + match self { + TransportFailure::Timeout => "the request timed out".into(), + TransportFailure::Connect => "the connection failed".into(), + TransportFailure::Tls => "the TLS handshake failed".into(), + TransportFailure::Protocol => "the response is not valid HTTP".into(), + TransportFailure::BodyTooLarge => { + format!("the response body exceeds {MAX_RESPONSE_BYTES} bytes") + } + TransportFailure::HeadersTooLarge => { + format!("the response headers exceed {MAX_RESPONSE_HEADER_BYTES} bytes") + } + TransportFailure::AddressRefused => ADDRESS_REFUSED.reason().into(), + } + } +} + +/// One URL entry that a step compile bound, in template form: the module, the entry, the +/// URL as declared and its origin. It never holds the expanded URL. +/// +/// This type is `#[non_exhaustive]`: obtain values from [`CompileResult::remote_inputs`]. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +pub struct RemoteInput { + /// The project-relative label of the declaring module. + pub module: String, + pub entry: String, + /// The URL as declared, with its `{{…}}` text. + pub template: String, + /// The origin of the URL as declared. + pub origin: String, +} + +/// The network grant of one run of step compiles: the policy and the per-run key. +/// +/// This type is `#[non_exhaustive]`: obtain values from [`FetchContext::new`]. +#[non_exhaustive] +#[derive(Clone, Debug)] +pub struct FetchContext { + policy: Arc, + key: Arc, +} + +impl FetchContext { + #[must_use] + pub fn new(policy: NetworkPolicy, key: RunKey) -> Self { + Self { + policy: Arc::new(policy), + key: Arc::new(key), + } + } + + /// The policy, for the address check of a sender. + #[must_use] + pub fn policy(&self) -> &NetworkPolicy { + &self.policy + } + + /// The network state of one step compile with the responses of `state`. + pub(crate) fn start(&self, state: &FetchState) -> StepCtx { + StepCtx::new( + Arc::clone(&self.policy), + Arc::clone(&self.key), + Arc::clone(&state.responses), + ) + } +} + +/// The responses that a host has for the requests of a step compile, keyed by request +/// ID. It holds responses only: each step compile derives every request again and runs +/// every check again. The raw bodies of its responses, of every status, are at most +/// 200 MiB in total. Its `Debug` shows the response count and the body bytes only. +/// +/// This type is `#[non_exhaustive]`: obtain values from [`FetchState::new`]. +#[non_exhaustive] +#[derive(Clone, Default)] +pub struct FetchState { + responses: Arc>, + /// The raw body bytes of the responses, every status counted. At most + /// `MAX_RESPONSE_BODY_BYTES_PER_COMPILE`. + body_bytes: usize, +} + +impl FetchState { + /// The start state, with no response. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// The state with the response to the request `id` added. A second response for one + /// ID fails with `mds::invalid_options`. A response past the request cap of a compile + /// (64) fails with `mds::resource_limit`, and so does a body that takes the raw body + /// bytes of the state past 200 MiB ([`MdsError::response_bodies_exceeded`]). Every + /// body counts, of every status: a redirect body and an error body too. + #[must_use = "a response can be refused"] + pub fn with_response(mut self, id: RequestId, response: Response) -> Result { + if self.responses.contains_key(&id) { + return Err(MdsError::invalid_options( + "the fetch state already holds a response for this request", + )); + } + if self.responses.len() >= MAX_REQUESTS_PER_COMPILE { + return Err(MdsError::resource_limit(format!( + "too many responses in the fetch state (max {MAX_REQUESTS_PER_COMPILE})" + ))); + } + let body = match &response { + Response::Http { body, .. } => body.len(), + Response::Failed(_) => 0, + }; + let Some(total @ ..=MAX_RESPONSE_BODY_BYTES_PER_COMPILE) = + self.body_bytes.checked_add(body) + else { + return Err(MdsError::response_bodies_exceeded()); + }; + Arc::make_mut(&mut self.responses).insert(id, response); + self.body_bytes = total; + Ok(self) + } + + /// The raw body bytes that the state can still take, of the 200 MiB total. A host + /// caps its body reads with it: a host that sends in parallel gives each send a share, + /// so the bodies in flight can not pass the total. + #[must_use] + pub fn body_bytes_left(&self) -> usize { + MAX_RESPONSE_BODY_BYTES_PER_COMPILE.saturating_sub(self.body_bytes) + } + + /// The number of responses. + #[must_use] + pub fn len(&self) -> usize { + self.responses.len() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.responses.is_empty() + } +} + +impl fmt::Debug for FetchState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("FetchState") + .field("responses", &self.responses.len()) + .field("body_bytes", &self.body_bytes) + .finish() + } +} + +/// The result of one step compile. +/// +/// This enum is `#[non_exhaustive]`: new variants may be added in minor releases. +#[non_exhaustive] +#[derive(Debug)] +pub enum Step { + /// Every URL entry is bound and the compile is complete. + Done(Box), + /// The host sends these requests, adds each response to the [`FetchState`] and runs + /// the next step. + Need(Vec), +} + +/// The network state of one step compile. +pub(crate) struct StepCtx { + /// The engine that binds a URL entry. A compile reaches the engine through this + /// pointer only, and only [`StepCtx::new`] sets it. So a build that never starts a + /// step compile, such as the WASM build, keeps none of the engine code. + bind: BindFn, + policy: Arc, + key: Arc, + responses: Arc>, + /// The requests with no response yet, in derive order, each one once. + needed: IndexMap, + /// The IDs of the responses that this compile used. + consumed: HashSet, + /// The value of each request of a bound chain, for the other entries of the compile, + /// with the envelope flag of the entry: the request ID does not hold the flag, and + /// one response gives a body value and an envelope value of two shapes. + memo: HashMap<(RequestId, bool), Arc>, + remote: Vec, +} + +/// The result of a step compile. +#[derive(Debug)] +pub(crate) enum Outcome { + /// Every URL entry is bound. + Done(Vec), + /// The host must send these requests and run the next round. + Need(Vec), +} + +impl StepCtx { + /// The only place that sets the engine pointer. Code outside `data` reaches it + /// through [`FetchContext::start`]. + pub(super) fn new( + policy: Arc, + key: Arc, + responses: Arc>, + ) -> Self { + Self { + bind: bind_with_engine, + policy, + key, + responses, + needed: IndexMap::new(), + consumed: HashSet::new(), + memo: HashMap::new(), + remote: Vec::new(), + } + } + + /// The outcome of a compile that ended with `pending` data. A response that the + /// compile did not use fails, so a host cannot give a value for a request that the + /// core did not derive. + pub(crate) fn finish(self, pending: bool) -> Result { + if self.responses.keys().any(|id| !self.consumed.contains(id)) { + return Err(MdsError::invalid_options( + "the fetch state holds a response that this compile did not request", + )); + } + match (pending, self.needed.is_empty()) { + (false, true) => Ok(Outcome::Done(self.remote)), + (true, false) => Ok(Outcome::Need(self.needed.into_values().collect())), + // Pending data with no request, or a request with no pending entry. + _ => Err(MdsError::internal()), + } + } + + /// The requests that the compile needs so far, in derive order. + #[cfg(test)] + pub(crate) fn needed(&self) -> impl Iterator { + self.needed.values() + } +} + +impl StepCtx { + /// Count one new request ID against `MAX_REQUESTS_PER_COMPILE`, before it is added. + fn count_new(&self) -> Result<(), MdsError> { + if self.consumed.len() + self.needed.len() >= MAX_REQUESTS_PER_COMPILE { + return Err(MdsError::resource_limit(format!( + "too many requests (max {MAX_REQUESTS_PER_COMPILE} per compile)" + ))); + } + Ok(()) + } +} + +/// The scope that the references of one entry read, and the facts of its module. +pub(crate) struct EntryScope<'s> { + pub(crate) runtime: &'s VarLayer, + /// The frontmatter variables and the entries that are already bound. + pub(crate) vars: &'s VarLayer, + /// The entries of this scope that are pending. + pub(crate) pending: &'s HashSet, + /// The entry belongs to the module that the compile starts from. + pub(crate) entry_module: bool, +} + +impl<'s> EntryScope<'s> { + /// The value of a reference path: the root from the runtime layer, else from the + /// module variables, then each field. + fn value(&self, path: &str) -> Option<&'s Value> { + let mut segments = path.split('.'); + let root = segments.next()?; + let mut value = self.runtime.value(root).or_else(|| self.vars.value(root))?; + for segment in segments { + let Value::Object(fields) = value else { + return None; + }; + value = fields.get(segment)?; + } + Some(value) + } +} + +/// What one URL entry binds. +#[derive(Debug)] +pub(crate) enum Bound { + Value(Arc), + /// The entry waits for a response, of its own request or of an entry it references. + Pending, +} + +/// The message site of one request of a URL entry: the module, the entry, the URL as +/// declared and the origin of the request. +pub(crate) struct RequestLabel<'a> { + module: &'a str, + entry: &'a str, + template: &'a str, + /// The origin of the request that the message is about. + origin: String, + /// The origin of the URL as declared. + declared: &'a Origin, +} + +/// The message site of a request to `origin` for the URL entry of `node`. Every message +/// about a URL entry request is built from it. +fn request_label<'a>( + node: Node<'a>, + template: &'a RequestTemplate, + origin: &'a Origin, +) -> RequestLabel<'a> { + RequestLabel { + module: node.module, + entry: &node.entry.name, + template: &template.url, + origin: origin.to_string(), + declared: origin, + } +} + +impl RequestLabel<'_> { + fn refused(&self, refusal: Refusal, secret: Option<&str>) -> MdsError { + MdsError::refused_request( + self.module, + self.entry, + self.template, + &self.origin, + refusal, + secret, + ) + } + + fn network(&self, kind: &str) -> MdsError { + MdsError::network(self.module, self.entry, self.template, &self.origin, kind) + } + + fn limit(&self, what: &str) -> MdsError { + MdsError::resource_limit(format!( + "{}: {what}", + request_location(self.module, self.entry, self.template, &self.origin) + )) + } +} + +/// Bind the URL entry of `node` from the responses of `ctx`, or add its request to the +/// needed list. `admit_bytes` counts the body bytes of a response against the data byte +/// cap of the compile. A request that fails a check never enters the needed list. +pub(crate) fn bind_url_entry( + node: Node<'_>, + template: &RequestTemplate, + scope: &EntryScope<'_>, + ctx: &mut StepCtx, + mem: &mut MemBudget, + mut admit_bytes: impl FnMut(usize) -> Result<(), MdsError>, +) -> Result { + let bind = ctx.bind; + bind(node, template, scope, ctx, mem, &mut admit_bytes) +} + +/// The type of [`StepCtx::bind`]. +type BindFn = fn( + Node<'_>, + &RequestTemplate, + &EntryScope<'_>, + &mut StepCtx, + &mut MemBudget, + &mut dyn FnMut(usize) -> Result<(), MdsError>, +) -> Result; + +/// The body of [`bind_url_entry`], through [`StepCtx::bind`]. +fn bind_with_engine( + node: Node<'_>, + template: &RequestTemplate, + scope: &EntryScope<'_>, + ctx: &mut StepCtx, + mem: &mut MemBudget, + admit_bytes: &mut dyn FnMut(usize) -> Result<(), MdsError>, +) -> Result { + let mark = mem.mark(); + let bound = derive(node, template, scope, ctx, mem, admit_bytes); + mem.release_to(mark); + bound +} + +/// Refuse a URL entry of `node` that has a secret header when the entry is not in the +/// module that the compile starts from. Every compile runs this on every URL entry, +/// replayed or not, so replay cannot lift the rule. +pub(crate) fn check_secret_module( + node: Node<'_>, + template: &RequestTemplate, + entry_module: bool, +) -> Result<(), MdsError> { + let has_secret = template + .headers + .iter() + .any(|header| matches!(header.value, HeaderSource::Secret { .. })); + if has_secret && !entry_module { + return Err(MdsError::data( + node.module, + Some(&node.entry.name), + Some("headers"), + "a secret header is allowed in the entry module only", + None, + )); + } + Ok(()) +} + +fn derive( + node: Node<'_>, + template: &RequestTemplate, + scope: &EntryScope<'_>, + ctx: &mut StepCtx, + mem: &mut MemBudget, + admit_bytes: impl FnMut(usize) -> Result<(), MdsError>, +) -> Result { + let module = node.module; + let entry = node.entry.name.as_str(); + check_secret_module(node, template, scope.entry_module)?; + if let Some(header) = template + .headers + .iter() + .find(|header| is_sender_header(&header.name)) + { + return Err(MdsError::data( + module, + Some(entry), + Some(&header.name), + "a request cannot set this header", + None, + )); + } + let literal = literal_origin(&template.url, mem)?; + mem.charge(Part::Temp, Some(origin_text_bytes(&literal)))?; + let label = request_label(node, template, &literal); + let method = ctx + .policy + .check_method(template.method) + .map_err(|refusal| label.refused(refusal, None))?; + let blocked = template.refs.iter().any(|path| { + let root = path.split_once('.').map_or(path.as_str(), |(root, _)| root); + scope.pending.contains(root) + }); + if blocked { + return Ok(Bound::Pending); + } + + let url_field = FieldLabel { + module, + entry, + field: "url", + }; + // The writer can grow its buffer to twice the cap before the cap check refuses. + mem.charge(Part::Temp, Some(2 * MAX_URL_BYTES))?; + let text = encode::expand(&template.url, Target::Url, url_field, |path| { + reference(scope, url_field, path) + })?; + mem.charge(Part::Temp, Some(text.len()))?; + let url = url::parse_absolute(&text) + .map_err(|refusal| label.refused(Refusal::new(Layer::UrlParser, refusal.reason()), None))?; + if url.origin() != literal { + return Err(label.refused( + Refusal::new(Layer::UrlParser, "the expanded URL has another origin"), + None, + )); + } + ctx.policy + .check_origin(&literal, scope.entry_module) + .map_err(|refusal| label.refused(refusal, None))?; + let headers = request_headers(template, scope, &label, &ctx.policy, mem)?; + let first = new_request(method, url, template.accept, headers, ctx, mem, &label)?; + let shape = Shape { + accept: template.accept, + envelope: template.envelope, + }; + follow(first, shape, node, label, ctx, mem, admit_bytes) +} + +/// The headers of the first request of a URL entry, in declaration order: each text +/// header expanded through the header encoder, and each secret header bound to the +/// declared origin and bounded by `MAX_HEADER_VALUE_BYTES`, as a descriptor only. +fn request_headers( + template: &RequestTemplate, + scope: &EntryScope<'_>, + label: &RequestLabel<'_>, + policy: &NetworkPolicy, + mem: &mut MemBudget, +) -> Result, MdsError> { + mem.charge( + Part::Temp, + template + .headers + .len() + .checked_mul(size_of::()), + )?; + let mut headers = Vec::with_capacity(template.headers.len()); + for header in &template.headers { + let field = FieldLabel { + module: label.module, + entry: label.entry, + field: &header.name, + }; + let value = match &header.value { + HeaderSource::Text(text) => { + mem.charge(Part::Temp, Some(2 * MAX_HEADER_VALUE_BYTES))?; + HeaderValue::Text(encode::expand(text, Target::Header, field, |path| { + reference(scope, field, path) + })?) + } + HeaderSource::Secret { name, prefix } => { + let secret = policy + .bind_secret(name, label.declared) + .map_err(|refusal| label.refused(refusal, Some(name)))?; + if prefix.len() + secret.expose_for_send().len() > MAX_HEADER_VALUE_BYTES { + return Err(field.limit("header value", MAX_HEADER_VALUE_BYTES)); + } + mem.charge(Part::Temp, name.len().checked_add(prefix.len()))?; + HeaderValue::Secret { + name: name.clone(), + prefix: prefix.clone(), + } + } + }; + mem.charge(Part::Temp, Some(header.name.len()))?; + headers.push(RequestHeader::new(header.name.clone(), value)); + } + Ok(headers) +} + +/// The value form of a URL entry: the body format and the envelope flag. +#[derive(Clone, Copy)] +struct Shape { + accept: Accept, + envelope: bool, +} + +/// The value of the reference `path` of a template field. A path that names no value +/// fails: a request never sends a guessed text. +fn reference<'s>( + scope: &EntryScope<'s>, + field: FieldLabel<'_>, + path: &str, +) -> Result<&'s Value, MdsError> { + scope.value(path).ok_or_else(|| { + MdsError::data( + field.module, + Some(field.entry), + Some(field.field), + &format!( + "the reference \"{}\" names no value", + crate::sanitize_control_chars_wire(path) + ), + None, + ) + }) +} + +/// Follow the redirect chain of `request` through the responses of `ctx`, at most +/// `MAX_REDIRECTS` hops. Each hop is a new request with its own ID and checks. With the +/// envelope, the final answer binds as `{status, headers, body}` for any status from +/// 200 to 599; without it, a status that is not 2xx fails. +fn follow( + mut request: Request, + shape: Shape, + node: Node<'_>, + mut label: RequestLabel<'_>, + ctx: &mut StepCtx, + mem: &mut MemBudget, + mut admit_bytes: impl FnMut(usize) -> Result<(), MdsError>, +) -> Result { + let responses = Arc::clone(&ctx.responses); + let mut chain = [None; MAX_REDIRECTS + 1]; + for hop in 0..=MAX_REDIRECTS { + let id = request.id(); + chain[hop] = Some(id); + if let Some(value) = ctx.memo.get(&(id, shape.envelope)) { + let value = Arc::clone(value); + return bind_value(value, &chain[..=hop], shape, node, &label, ctx, mem); + } + if ctx.needed.contains_key(&id) { + return Ok(Bound::Pending); + } + let Some(response) = responses.get(&id) else { + ctx.count_new()?; + mem.charge(Part::Buffers, retained_bytes(&request))?; + ctx.needed.insert(id, request); + return Ok(Bound::Pending); + }; + if !ctx.consumed.contains(&id) { + ctx.count_new()?; + mem.charge(Part::Buffers, Some(2 * size_of::()))?; + ctx.consumed.insert(id); + } + let (status, headers, body) = match response { + Response::Failed(TransportFailure::AddressRefused) => { + return Err(label.refused(ADDRESS_REFUSED, None)); + } + Response::Failed(failure) => return Err(label.network(&failure.kind())), + Response::Http { + status, + headers, + body, + } => (*status, headers, body), + }; + let header_bytes = headers.iter().try_fold(0usize, |sum, (name, value)| { + sum.checked_add(name.len())?.checked_add(value.len() + 4) + }); + if header_bytes.is_none_or(|bytes| bytes > MAX_RESPONSE_HEADER_BYTES) { + return Err(label.network(&TransportFailure::HeadersTooLarge.kind())); + } + // The body cap applies to every status, a redirect answer too. + if u64::try_from(body.len()).map_or(true, |len| len > MAX_RESPONSE_BYTES) { + return Err(label.network(&TransportFailure::BodyTooLarge.kind())); + } + let bound = match status { + 301 | 302 | 303 | 307 | 308 => { + let next = redirect(&request, shape.accept, headers, hop, &label, ctx, mem)?; + let origin = next.url().origin(); + mem.charge(Part::Temp, Some(origin_text_bytes(&origin)))?; + label.origin = origin.to_string(); + request = next; + continue; + } + 200..=299 => true, + 300..=599 => shape.envelope, + _ => false, + }; + if !bound { + return Err(label.network(&format!("the server answered with HTTP status {status}"))); + } + let data = DataLabel { + module: node.module, + entry: &node.entry.name, + input: DataInput::Response, + }; + // A HEAD answer has no body, so its envelope holds `body: null`. + let value = if request.method() == Method::Head { + Value::Null + } else { + admit_bytes(body.len())?; + convert(body, shape.accept, data, mem)? + }; + let value = if shape.envelope { + envelope::envelope(status, headers, value, data, mem)? + } else { + value + }; + if let Some(secret) = scan_secrets(&value, &ctx.policy)? { + return Err(label.refused(response_check(), Some(secret))); + } + mem.charge( + Part::Buffers, + Some(size_of::() + 2 * size_of::()), + )?; + return bind_value( + Arc::new(value), + &chain[..=hop], + shape, + node, + &label, + ctx, + mem, + ); + } + // The hop check refuses the hop past `MAX_REDIRECTS`, so the loop always returns. + Err(MdsError::internal()) +} + +/// The next request of a redirect response to `request`, after the location, the hop +/// and the header checks. +fn redirect( + request: &Request, + accept: Accept, + headers: &[(String, Vec)], + hop: usize, + label: &RequestLabel<'_>, + ctx: &StepCtx, + mem: &mut MemBudget, +) -> Result { + let mut locations = headers + .iter() + .filter(|(name, _)| name.eq_ignore_ascii_case("location")); + let (Some((_, location)), None) = (locations.next(), locations.next()) else { + return Err(label.refused( + Refusal::new( + Layer::RedirectCheck, + "a redirect needs exactly one location header", + ), + None, + )); + }; + let Ok(location) = std::str::from_utf8(location) else { + return Err(label.refused( + Refusal::new( + Layer::UrlParser, + "URL can contain only visible ASCII characters", + ), + None, + )); + }; + if let Some(secret) = find_secret(location, &ctx.policy) { + return Err(label.refused(response_check(), Some(secret))); + } + mem.charge( + Part::Temp, + location + .len() + .checked_add(origin_text_bytes(&request.url().origin())) + .and_then(|bytes| bytes.checked_mul(2)), + )?; + let next = url::parse_location(request.url(), location) + .map_err(|refusal| label.refused(Refusal::new(Layer::UrlParser, refusal.reason()), None))?; + let rule = ctx + .policy + .check_hop(request.url(), &next, hop + 1) + .map_err(|error| match error { + HopError::TooMany => label.limit(&format!( + "too many redirects (max {MAX_REDIRECTS} per entry)" + )), + HopError::Refused(refusal) => label.refused(refusal, None), + })?; + let mut kept = Vec::with_capacity(request.headers().len()); + for header in request.headers() { + let secret = matches!(header.value(), HeaderValue::Secret { .. }); + if rule.keeps_header(header.name(), secret) { + mem.charge(Part::Temp, header_bytes(header))?; + kept.push(header.clone()); + } + } + new_request(request.method(), next, accept, kept, ctx, mem, label) +} + +/// Build a request after a charge of the bound of its identity text. +fn new_request( + method: Method, + url: CheckedUrl, + accept: Accept, + headers: Vec, + ctx: &StepCtx, + mem: &mut MemBudget, + label: &RequestLabel<'_>, +) -> Result { + mem.charge(Part::Temp, identity_bytes(&url, &headers))?; + mem.charge(Part::Temp, Some(label.template.len()))?; + Request::new( + method, + label.template, + url, + accept, + headers, + &ctx.key, + &ctx.policy, + ) + .map_err(|refusal| label.refused(refusal, None)) +} + +/// Bind `value` for the entry of `node`: keep it for each request ID of the chain and +/// add the remote input of the entry. +fn bind_value( + value: Arc, + chain: &[Option], + shape: Shape, + node: Node<'_>, + label: &RequestLabel<'_>, + ctx: &mut StepCtx, + mem: &mut MemBudget, +) -> Result { + for id in chain.iter().flatten() { + if let Entry::Vacant(slot) = ctx.memo.entry((*id, shape.envelope)) { + mem.charge( + Part::Buffers, + Some(2 * size_of::<((RequestId, bool), Arc, usize)>()), + )?; + slot.insert(Arc::clone(&value)); + } + } + let template = label.template; + mem.charge(Part::Temp, Some(origin_text_bytes(label.declared)))?; + let origin = label.declared.to_string(); + let bytes = node + .module + .len() + .checked_add(node.entry.name.len()) + .and_then(|sum| sum.checked_add(template.len())) + .and_then(|sum| sum.checked_add(origin.len())) + .and_then(|sum| sum.checked_add(2 * size_of::())); + mem.charge(Part::Buffers, bytes)?; + ctx.remote.push(RemoteInput { + module: node.module.to_owned(), + entry: node.entry.name.clone(), + template: template.to_owned(), + origin, + }); + Ok(Bound::Value(value)) +} + +/// The name of the first host secret whose value is in `value`, in a string or in an +/// object key, as an exact byte match. A changed form of the value (base64, percent +/// encoding, a split over two strings) is not found. The walk is bounded by +/// `MAX_VALUE_DEPTH`; a deeper value fails closed. +fn scan_secrets<'p>(value: &Value, policy: &'p NetworkPolicy) -> Result, MdsError> { + fn walk<'p>( + value: &Value, + policy: &'p NetworkPolicy, + depth: usize, + ) -> Result, MdsError> { + if depth > MAX_VALUE_DEPTH { + return Err(MdsError::internal()); + } + match value { + Value::String(text) => Ok(find_secret(text, policy)), + Value::Array(items) => { + for item in items { + if let Some(name) = walk(item, policy, depth + 1)? { + return Ok(Some(name)); + } + } + Ok(None) + } + Value::Object(fields) => { + for (key, item) in fields { + if let Some(name) = find_secret(key, policy) { + return Ok(Some(name)); + } + if let Some(name) = walk(item, policy, depth + 1)? { + return Ok(Some(name)); + } + } + Ok(None) + } + Value::Number(_) | Value::Boolean(_) | Value::Null => Ok(None), + } + } + walk(value, policy, 0) +} + +/// The name of the first host secret whose value is in `text`, as an exact byte match. +fn find_secret<'p>(text: &str, policy: &'p NetworkPolicy) -> Option<&'p str> { + policy + .secrets() + .find(|(_, secret)| text.contains(secret.expose_for_send())) + .map(|(name, _)| name) +} + +fn response_check() -> Refusal { + Refusal::new( + Layer::ResponseCheck, + "the response holds the value of a host secret", + ) +} + +/// The origin of the literal URL of a template: the declaration parser keeps the +/// authority literal, so a failure here is an internal error. +fn literal_origin(template: &str, mem: &mut MemBudget) -> Result { + let scheme = if template.starts_with("https://") { + "https://".len() + } else if template.starts_with("http://") { + "http://".len() + } else { + return Err(MdsError::internal()); + }; + let end = template[scheme..] + .find(['/', '?']) + .map_or(template.len(), |index| scheme + index); + mem.charge(Part::Temp, Some(end + 1))?; + url::parse_absolute(&template[..end]) + .map(|url| url.origin()) + .map_err(|_| MdsError::internal()) +} + +/// An upper bound of the text of `origin`: the scheme, the host and a port. +fn origin_text_bytes(origin: &Origin) -> usize { + let host = match &origin.host { + Host::Name(name) => name.len(), + Host::V4(_) | Host::V6(_) => 47, + }; + host + "https://:65535".len() +} + +/// An upper bound of the bytes of one header. +fn header_bytes(header: &RequestHeader) -> Option { + let value = match header.value() { + HeaderValue::Text(text) => text.len(), + HeaderValue::Secret { name, prefix } => name.len().checked_add(prefix.len())?, + }; + header + .name() + .len() + .checked_add(value)? + .checked_add(size_of::()) +} + +/// An upper bound of the bytes that a request in the needed list holds. +fn retained_bytes(request: &Request) -> Option { + let url = request.url(); + let host = match &url.host { + Host::Name(name) => name.len(), + Host::V4(_) | Host::V6(_) => 0, + }; + let mut bytes = host + .checked_add(url.path().len())? + .checked_add(request.template().len())? + .checked_add(url.query().map_or(0, str::len))? + .checked_add(2 * size_of::<(RequestId, Request, usize)>())?; + for header in request.headers() { + bytes = bytes.checked_add(header_bytes(header)?)?; + } + Some(bytes) +} diff --git a/crates/mds-core/src/data/step_tests.rs b/crates/mds-core/src/data/step_tests.rs new file mode 100644 index 00000000..3d9be486 --- /dev/null +++ b/crates/mds-core/src/data/step_tests.rs @@ -0,0 +1,1730 @@ +//! The step engine through real compiles: each `run_step` call is one round. + +use std::collections::HashMap; +use std::ops::Range; +use std::path::Path; +use std::sync::Arc; + +use indexmap::IndexMap; + +use super::encode::{check_header_value, encode_path_segment, encode_query, EncodeRefusal}; +use super::encode_tests::{vectors, Vector}; +use super::policy::{AllowItem, NetworkPolicy, Secret, SecretValue}; +use super::request::{HeaderValue, Request, RequestId, RunKey}; +use super::step::{FetchState, Outcome, RemoteInput, Response, StepCtx, TransportFailure}; +use super::{convert, Accept, DataInput, DataLabel}; +use crate::evaluator::budget::MemBudget; +use crate::limits::{ + MAX_DATA_BYTES_PER_COMPILE, MAX_HEADER_VALUE_BYTES, MAX_REDIRECTS, MAX_REQUESTS_PER_COMPILE, + MAX_RESPONSE_BODY_BYTES_PER_COMPILE, MAX_RESPONSE_BYTES, +}; +use crate::resolver::ModuleCache; +use crate::{CompiledOutput, MdsError, Value, VirtualFs}; + +const PLANTED: &str = "planted-secret-value"; + +type Responses = IndexMap; +type Runtime = HashMap; + +fn policy(items: &[&str]) -> NetworkPolicy { + let items = items + .iter() + .map(|item| AllowItem::parse(item).unwrap()) + .collect(); + NetworkPolicy::new(items).unwrap() +} + +fn with_secret(policy: NetworkPolicy, name: &str, value: &str, origin: &str) -> NetworkPolicy { + let origin = AllowItem::parse(origin).unwrap().origin(); + let value = SecretValue::new(value.into()).unwrap(); + policy + .with_secret(Secret::new(name, value, origin).unwrap()) + .unwrap() +} + +/// One round of a step compile of `main.mds`: the text and the outcome, or the first +/// error, and the requests that the compile needed when it stopped. +fn run_round( + files: &[(&str, &str)], + runtime: &Runtime, + policy: &NetworkPolicy, + responses: &Responses, +) -> (Result<(String, Outcome), MdsError>, Vec) { + let files = files + .iter() + .map(|&(key, text)| (key.to_owned(), text.to_owned())) + .collect(); + let ctx = StepCtx::new( + Arc::new(policy.clone()), + Arc::new(RunKey::from_bytes([7; 32])), + Arc::new(responses.clone()), + ); + let mut cache = ModuleCache::stepping(Box::new(VirtualFs::new(files)), ctx); + let compiled = cache.resolve_virtual_intrinsic("main.mds", runtime, &mut Vec::new()); + let pending = cache.has_pending_data(); + let ctx = cache.take_step().unwrap(); + let needed = ctx.needed().cloned().collect(); + let result = compiled.and_then(|output| { + let CompiledOutput::Markdown(text) = output else { + panic!("expected Markdown output"); + }; + Ok((text, ctx.finish(pending)?)) + }); + (result, needed) +} + +fn run_step( + files: &[(&str, &str)], + runtime: &Runtime, + policy: &NetworkPolicy, + responses: &Responses, +) -> Result<(String, Outcome), MdsError> { + run_round(files, runtime, policy, responses).0 +} + +/// The requests of a round that needs more responses. +fn need(result: Result<(String, Outcome), MdsError>) -> Vec { + match result { + Ok((_, Outcome::Need(requests))) => requests, + other => panic!("expected requests, got {other:?}"), + } +} + +fn done(result: Result<(String, Outcome), MdsError>) -> String { + match result { + Ok((text, Outcome::Done(_))) => text, + other => panic!("expected a finished compile, got {other:?}"), + } +} + +fn urls(requests: &[Request]) -> Vec { + requests + .iter() + .map(|request| request.url().to_text()) + .collect() +} + +/// Run rounds until the compile is done, with `serve` as the host. Return the text, +/// the round count and every request in send order. +fn drive( + files: &[(&str, &str)], + policy: &NetworkPolicy, + serve: impl Fn(&Request) -> Response, +) -> Result<(String, usize, Vec), MdsError> { + let mut responses = Responses::new(); + let mut sent = Vec::new(); + for round in 1..=MAX_REQUESTS_PER_COMPILE + 1 { + match run_step(files, &Runtime::new(), policy, &responses)? { + (text, Outcome::Done(_)) => return Ok((text, round, sent)), + (_, Outcome::Need(requests)) => { + for request in requests { + responses.insert(request.id(), serve(&request)); + sent.push(request); + } + } + } + } + panic!("the compile did not end within the round bound"); +} + +fn ok(body: &str) -> Response { + Response::Http { + status: 200, + headers: Vec::new(), + body: body.as_bytes().to_vec(), + } +} + +fn moved(location: &str) -> Response { + Response::Http { + status: 302, + headers: vec![("Location".into(), location.as_bytes().to_vec())], + body: Vec::new(), + } +} + +/// Answer each request with the response of its URL, after the round that needs it. +fn answer(requests: &[Request], responses: &mut Responses, by_url: &[(&str, Response)]) { + for request in requests { + let url = request.url().to_text(); + let (_, response) = by_url + .iter() + .find(|(known, _)| *known == url) + .unwrap_or_else(|| panic!("no response for {url}")); + responses.insert(request.id(), response.clone()); + } +} + +fn code(error: &MdsError) -> String { + error.serialize().code +} + +/// A JSON string, which is also a YAML double-quoted scalar. A control character is +/// written as a six-character escape. +fn quoted(text: &str) -> String { + let mut out = String::from('"'); + for ch in text.chars() { + match ch { + '"' | '\\' => { + out.push('\\'); + out.push(ch); + } + ch if u32::from(ch) < 0x20 => out.push_str(&format!("{}u{:04x}", '\\', u32::from(ch))), + ch => out.push(ch), + } + } + out.push('"'); + out +} + +/// What one placement of a value gives: the request text or the error message. +fn observed(result: Result<(String, Outcome), MdsError>, header: bool) -> Result { + match result { + Ok((_, Outcome::Need(requests))) => { + let [request] = requests.as_slice() else { + panic!("expected one request, got {}", requests.len()); + }; + if !header { + return Ok(request.url().to_text()); + } + match request.headers()[0].value() { + HeaderValue::Text(text) => Ok(text.clone()), + other => panic!("expected a text header, got {other:?}"), + } + } + Ok((_, Outcome::Done(_))) => panic!("expected the request of the target entry"), + Err(error) => Err(error.to_string()), + } +} + +/// The expected text of each placement of `value`, from the encoders. +fn expected(value: &str) -> [Result; 3] { + let refused = |refusal: EncodeRefusal| { + Err(format!( + r#"data error in "main.mds", entry "t", field "{}": {}"#, + if refusal == EncodeRefusal::HeaderByte { + "X-V" + } else { + "url" + }, + refusal.reason() + )) + }; + [ + match encode_path_segment(value) { + Ok(bytes) => Ok(format!("https://a.example/items/{bytes}")), + Err(refusal) => refused(refusal), + }, + Ok(format!("https://a.example/items?q={}", encode_query(value))), + match check_header_value(value) { + Ok(()) => Ok(format!("Bearer {value}")), + Err(refusal) => refused(refusal), + }, + ] +} + +/// The shared vector table and the encoders agree on each placement of a value, so an +/// expectation from the encoders is the expectation of the table. +fn assert_table_row(row: &Vector, expected: &[Result; 3]) { + let (value, path, query, header) = row; + match path { + Ok(bytes) => assert_eq!(expected[0], Ok(format!("https://a.example/items/{bytes}"))), + Err(refusal) => assert!( + expected[0] + .as_ref() + .unwrap_err() + .ends_with(refusal.reason()), + "{value:?}" + ), + } + assert_eq!( + expected[1], + Ok(format!("https://a.example/items?q={query}")) + ); + match header { + Some(bytes) => assert_eq!(expected[2], Ok(format!("Bearer {bytes}"))), + None => assert!( + expected[2] + .as_ref() + .unwrap_err() + .ends_with(EncodeRefusal::HeaderByte.reason()), + "{value:?}" + ), + } +} + +/// TP-75: each vector of the encoder table gives the same request bytes, or the same +/// refusal, from a frontmatter variable, a runtime variable, a replayed entry, a data +/// file and a response. A data file and a response change CR LF to LF, so their +/// expectation is the one of the changed value. +#[test] +fn each_value_source_gives_the_same_request_bytes_or_refusal() { + let targets = [ + "'https://a.example/items/{{v}}'", + "'https://a.example/items?q={{v}}'", + "{url: 'https://a.example/h', headers: {X-V: 'Bearer {{v}}'}}", + ]; + let net = policy(&["a.example"]); + for (value, path, query, header) in vectors() { + let raw_expected = expected(&value); + assert_table_row(&(value.clone(), path, query, header), &raw_expected); + let data_expected = expected(&value.replace("\r\n", "\n")); + let json = quoted(&value); + for (index, target) in targets.iter().enumerate() { + let header = index == 2; + let with = |data: &str| format!("---\ndata:\n{data} t: {target}\n---\n{{{{t}}}}\n"); + let runtime = Runtime::from([("v".to_owned(), Value::String(value.clone()))]); + let frontmatter = format!("---\nv: {json}\ndata:\n t: {target}\n---\n{{{{t}}}}\n"); + let replayed = with(" v: https://a.example/v\n"); + let file = with(" v: ./v.json\n"); + let remote = with(" v: https://a.example/v\n"); + let sources = [ + run_step( + &[("main.mds", &frontmatter)], + &Runtime::new(), + &net, + &Responses::new(), + ), + run_step( + &[("main.mds", &with(""))], + &runtime, + &net, + &Responses::new(), + ), + run_step( + &[("main.mds", &replayed)], + &runtime, + &net, + &Responses::new(), + ), + run_step( + &[("main.mds", &file), ("v.json", &json)], + &Runtime::new(), + &net, + &Responses::new(), + ), + ]; + for (source, result) in sources.into_iter().enumerate() { + let want = if source == 3 { + &data_expected + } else { + &raw_expected + }; + assert_eq!( + observed(result, header), + want[index], + "{value:?} source {source}" + ); + } + let first = need(run_step( + &[("main.mds", &remote)], + &Runtime::new(), + &net, + &Responses::new(), + )); + assert_eq!(urls(&first), ["https://a.example/v"]); + let mut responses = Responses::new(); + answer( + &first, + &mut responses, + &[("https://a.example/v", ok(&json))], + ); + let result = run_step(&[("main.mds", &remote)], &Runtime::new(), &net, &responses); + assert_eq!( + observed(result, header), + data_expected[index], + "{value:?} response" + ); + } + } +} + +/// TP-77: a two-level chain needs one request per round, and the compile ends in the +/// round after the last level: depth plus one rounds. +#[test] +fn a_two_level_chain_needs_one_round_per_level_and_one_more() { + let main = "---\ndata:\n user: https://a.example/user\n repos: https://a.example/users/{{user.id}}/repos\n---\n{{repos.count}}\n"; + let files = [("main.mds", main)]; + let net = policy(&["a.example"]); + let first = need(run_step(&files, &Runtime::new(), &net, &Responses::new())); + assert_eq!(urls(&first), ["https://a.example/user"]); + let serve = |request: &Request| match request.url().path() { + "/user" => ok(r#"{"id": "u1"}"#), + "/users/u1/repos" => ok(r#"{"count": 3}"#), + other => panic!("unexpected path {other}"), + }; + let (text, rounds, sent) = drive(&files, &net, serve).unwrap(); + assert!(text.ends_with("3\n"), "{text:?}"); + assert_eq!(rounds, 3); + assert_eq!( + urls(&sent), + ["https://a.example/user", "https://a.example/users/u1/repos"] + ); +} + +/// TP-78: a response for a request that the compile did not derive fails with fixed +/// text. Control: the exact responses complete the compile. +#[test] +fn a_response_that_the_compile_did_not_request_fails() { + let net = policy(&["a.example"]); + let main = "---\ndata:\n a: https://a.example/a\n---\n{{a.n}}\n"; + let other = "---\ndata:\n a: https://a.example/other\n---\n{{a.n}}\n"; + let requests = need(run_step( + &[("main.mds", main)], + &Runtime::new(), + &net, + &Responses::new(), + )); + let foreign = need(run_step( + &[("main.mds", other)], + &Runtime::new(), + &net, + &Responses::new(), + )); + let mut responses = Responses::new(); + answer( + &requests, + &mut responses, + &[("https://a.example/a", ok(r#"{"n": 1}"#))], + ); + let exact = responses.clone(); + responses.insert(foreign[0].id(), ok(r#"{"n": 2}"#)); + let err = run_step(&[("main.mds", main)], &Runtime::new(), &net, &responses).unwrap_err(); + assert_eq!(code(&err), "mds::invalid_options"); + assert_eq!( + err.to_string(), + "invalid options: the fetch state holds a response that this compile did not request" + ); + let text = done(run_step( + &[("main.mds", main)], + &Runtime::new(), + &net, + &exact, + )); + assert!(text.ends_with("1\n"), "{text:?}"); +} + +/// TP-79: one request that two modules derive is needed once, and its response binds +/// both entries. +#[test] +fn one_request_of_two_modules_is_needed_once() { + let main = "---\ndata:\n a: https://a.example/shared\n---\n@import \"./lib.mds\" as lib\n{{a.n}}\n@include lib\n"; + let lib = "---\ndata:\n b: https://a.example/shared\n---\nlib {{b.n}}\n"; + let files = [("main.mds", main), ("lib.mds", lib)]; + let net = policy(&["a.example"]).with_imports(true); + let requests = need(run_step(&files, &Runtime::new(), &net, &Responses::new())); + assert_eq!(urls(&requests), ["https://a.example/shared"]); + let mut responses = Responses::new(); + answer( + &requests, + &mut responses, + &[("https://a.example/shared", ok(r#"{"n": 5}"#))], + ); + let Ok((text, Outcome::Done(remote))) = run_step(&files, &Runtime::new(), &net, &responses) + else { + panic!("expected a finished compile"); + }; + assert!(text.ends_with("5\nlib 5\n"), "{text:?}"); + let input = |module: &str, entry: &str| RemoteInput { + module: module.into(), + entry: entry.into(), + template: "https://a.example/shared".into(), + origin: "https://a.example".into(), + }; + assert_eq!(remote, [input("main.mds", "a"), input("lib.mds", "b")]); +} + +/// TP-80: a request that fails a policy check never enters the needed list. +#[test] +fn a_request_that_fails_a_check_never_enters_the_needed_list() { + let net = policy(&["a.example"]); + for (bad, layer) in [ + ("{url: 'https://a.example/x', method: POST}", "method"), + ("'https://b.example/x'", "allow-list"), + ( + "{url: 'https://a.example/x', headers: {Authorization: {secret: NONE, prefix: 'Bearer '}}}", + "secret-binding", + ), + ] { + let main = format!("---\ndata:\n ok: https://a.example/ok\n bad: {bad}\n---\n{{{{ok}}}}{{{{bad}}}}\n"); + let (result, needed) = run_round(&[("main.mds", &main)], &Runtime::new(), &net, &Responses::new()); + let err = result.unwrap_err(); + assert_eq!(code(&err), "mds::network_denied", "{err}"); + assert!(err.to_string().contains(&format!(": {layer}: ")), "{err}"); + assert_eq!(urls(&needed), ["https://a.example/ok"], "{bad}"); + } +} + +/// TP-81: a base URL entry reads the merged scope, so a child frontmatter variable fills +/// its path. The base is another module than the entry, so it needs the import opt-in. +#[test] +fn a_base_url_entry_reads_a_child_frontmatter_variable() { + let base = "---\ndata:\n remote: 'https://a.example/users/{{name}}'\n---\nBase.\n"; + let child = "---\nname: child\n---\n@extends \"./base.mds\"\n"; + let files = [("main.mds", child), ("base.mds", base)]; + let net = policy(&["a.example"]); + let requests = need(run_step( + &files, + &Runtime::new(), + &net.clone().with_imports(true), + &Responses::new(), + )); + assert_eq!(urls(&requests), ["https://a.example/users/child"]); + let err = run_step(&files, &Runtime::new(), &net, &Responses::new()).unwrap_err(); + assert!(err.to_string().contains(": import-opt-in: "), "{err}"); +} + +/// TP-82: a response value that holds reference text goes into the next URL as text and +/// is never expanded again. Control: plain text. +#[test] +fn a_response_value_is_not_expanded_again() { + let main = "---\nx: zzz\ndata:\n a: https://a.example/a\n b: https://a.example/b/{{a.id}}\n---\n{{b}}\n"; + let net = policy(&["a.example"]); + for (id, url) in [ + ("{{x}}", "https://a.example/b/%7B%7Bx%7D%7D"), + ("abc", "https://a.example/b/abc"), + ] { + let first = need(run_step( + &[("main.mds", main)], + &Runtime::new(), + &net, + &Responses::new(), + )); + let mut responses = Responses::new(); + let body = format!("{{\"id\": {}}}", quoted(id)); + answer( + &first, + &mut responses, + &[("https://a.example/a", ok(&body))], + ); + let next = need(run_step( + &[("main.mds", main)], + &Runtime::new(), + &net, + &responses, + )); + assert_eq!(urls(&next), [url]); + } +} + +/// TP-83: a response body goes through the data file converter, so each refused form +/// fails with the code of a data file. A message names the entry, never the URL. +#[test] +fn a_response_body_fails_as_a_data_file_fails() { + let backslash = '\\'; + let cases: [(&str, Vec); 6] = [ + ("json", br#"{"a": 1, "a": 2}"#.to_vec()), + ("json", format!("\"a{backslash}u0001b\"").into_bytes()), + ("json", b"9007199254740993".to_vec()), + ("json", vec![b'"', 0xff, b'"']), + ("yaml", b"a: 1\n---\nb: 2\n".to_vec()), + ("json", b"{".to_vec()), + ]; + let net = policy(&["a.example"]); + let mut syntax = 0; + for (accept, body) in cases { + let main = format!("---\nhidden: secret-path\ndata:\n a: {{url: 'https://a.example/{{{{hidden}}}}', accept: {accept}}}\n---\n{{{{a}}}}\n"); + let first = need(run_step( + &[("main.mds", &main)], + &Runtime::new(), + &net, + &Responses::new(), + )); + let mut responses = Responses::new(); + responses.insert( + first[0].id(), + Response::Http { + status: 200, + headers: Vec::new(), + body: body.clone(), + }, + ); + let err = run_step(&[("main.mds", &main)], &Runtime::new(), &net, &responses).unwrap_err(); + let format = if accept == "json" { + Accept::Json + } else { + Accept::Yaml + }; + let label = DataLabel { + module: "main.mds", + entry: "a", + input: DataInput::File("a.json"), + }; + let file = convert(&body, format, label, &mut MemBudget::default()).unwrap_err(); + assert_eq!(code(&err), code(&file), "{err}"); + let message = err.to_string(); + assert!( + !message.contains("a.example") && !message.contains("secret-path"), + "{message}" + ); + if code(&err) == "mds::yaml" { + syntax += 1; + assert!( + message.contains(r#""main.mds", response for entry "a""#), + "{message}" + ); + } + } + assert!(syntax > 0, "no case gave a syntax error"); +} + +/// TP-87: each redirect hop goes through the hop checks, and a chain has at most +/// `MAX_REDIRECTS` hops. Controls: a hop to a listed host gives one next request, and +/// five hops pass. +#[test] +fn each_redirect_hop_passes_the_hop_checks() { + let main = "---\ndata:\n a: https://a.example/0\n---\n{{a.n}}\n"; + let net = policy(&["a.example", "b.example"]); + let first = need(run_step( + &[("main.mds", main)], + &Runtime::new(), + &net, + &Responses::new(), + )); + for (location, refused) in [ + ( + "http://169.254.169.254/", + Some("redirect-check: a redirect from https to http is refused"), + ), + ( + "https://c.example/", + Some("redirect-check: the redirect target is not in the allow list"), + ), + ("https://b.example/x", None), + ] { + let mut responses = Responses::new(); + answer( + &first, + &mut responses, + &[("https://a.example/0", moved(location))], + ); + let result = run_step(&[("main.mds", main)], &Runtime::new(), &net, &responses); + match refused { + Some(reason) => { + let err = result.unwrap_err(); + assert_eq!(code(&err), "mds::network_denied"); + assert!(err.to_string().ends_with(reason), "{err}"); + } + None => assert_eq!(urls(&need(result)), [location]), + } + } + let chain = |hops: usize| { + let serve = move |request: &Request| { + let step: usize = request.url().path()[1..].parse().unwrap(); + if step < hops { + moved(&format!("/{}", step + 1)) + } else { + ok(r#"{"n": 9}"#) + } + }; + drive(&[("main.mds", main)], &net, serve) + }; + let (text, rounds, _) = chain(MAX_REDIRECTS).unwrap(); + assert!(text.ends_with("9\n"), "{text:?}"); + assert_eq!(rounds, MAX_REDIRECTS + 2); + let err = chain(MAX_REDIRECTS + 1).unwrap_err(); + assert_eq!(code(&err), "mds::resource_limit"); + assert!( + err.to_string() + .ends_with("too many redirects (max 5 per entry)"), + "{err}" + ); +} + +/// A hop to another origin drops the secret header. Control: a hop on the same origin +/// keeps it. +#[test] +fn a_hop_to_another_origin_drops_the_secret_header() { + let main = "---\ndata:\n a:\n url: https://a.example/0\n headers:\n Authorization: {secret: TOKEN, prefix: 'Bearer '}\n X-Plain: kept\n---\n{{a.n}}\n"; + let net = with_secret( + policy(&["a.example", "b.example"]), + "TOKEN", + PLANTED, + "a.example", + ); + let first = need(run_step( + &[("main.mds", main)], + &Runtime::new(), + &net, + &Responses::new(), + )); + for (location, names) in [ + ("https://b.example/1", vec!["X-Plain"]), + ("/1", vec!["Authorization", "X-Plain"]), + ] { + let mut responses = Responses::new(); + answer( + &first, + &mut responses, + &[("https://a.example/0", moved(location))], + ); + let next = need(run_step( + &[("main.mds", main)], + &Runtime::new(), + &net, + &responses, + )); + let kept: Vec<_> = next[0] + .headers() + .iter() + .map(|header| header.name()) + .collect(); + assert_eq!(kept, names, "{location}"); + } +} + +/// TP-88: a host secret is not a scope name, a runtime variable never fills a secret +/// header, and a response that holds the secret value fails. Control: a fixed body. +#[test] +fn a_host_secret_is_only_a_header_value() { + let net = with_secret(policy(&["a.example"]), "GITHUB", PLANTED, "a.example"); + let reference = "---\ndata:\n a: https://a.example/{{GITHUB}}\n---\n{{a}}\n"; + let err = run_step( + &[("main.mds", reference)], + &Runtime::new(), + &net, + &Responses::new(), + ) + .unwrap_err(); + assert_eq!(code(&err), "mds::data"); + assert!( + err.to_string() + .contains("unknown data reference name \"GITHUB\""), + "{err}" + ); + + let main = "---\ndata:\n a:\n url: https://a.example/x\n headers:\n Authorization: {secret: GITHUB, prefix: 'Bearer '}\n---\n{{a.n}}\n"; + let files = [("main.mds", main)]; + let runtime = Runtime::from([("GITHUB".to_owned(), Value::String("runtime-value".into()))]); + let first = need(run_step(&files, &runtime, &net, &Responses::new())); + let plain = need(run_step(&files, &Runtime::new(), &net, &Responses::new())); + assert_eq!(first[0].id(), plain[0].id()); + assert_eq!( + first[0].headers()[0].value(), + &HeaderValue::Secret { + name: "GITHUB".into(), + prefix: "Bearer ".into() + } + ); + let err = run_step(&files, &runtime, &policy(&["a.example"]), &Responses::new()).unwrap_err(); + assert!(err.to_string().contains(": secret-binding: "), "{err}"); + + let echo_value = format!("{{\"echo\": \"{PLANTED}\"}}"); + let echo_key = format!("{{\"x-{PLANTED}\": 1}}"); + let in_array = format!("{{\"a\": [\"x\", \"{PLANTED}\"]}}"); + let in_top_array = format!("[{{\"b\": \"{PLANTED}\"}}]"); + for (response, refused) in [ + (ok(&echo_value), true), + (ok(&echo_key), true), + (moved(&format!("/next?k={PLANTED}")), true), + (ok(&in_array), true), + (ok(&in_top_array), true), + (ok(r#"{"n": 4}"#), false), + // Control: the same array shapes without the value bind. + ( + ok(r#"{"n": 4, "a": ["x", "plain"], "c": [{"b": "plain"}]}"#), + false, + ), + ] { + let mut responses = Responses::new(); + answer(&first, &mut responses, &[("https://a.example/x", response)]); + let result = run_step(&files, &Runtime::new(), &net, &responses); + if refused { + let err = result.unwrap_err(); + assert_eq!(code(&err), "mds::network_denied"); + let message = err.to_string(); + // The value check comes first with a fixed message, so `{message}` below + // cannot show the value. + assert!( + !message.contains(PLANTED), + "the message must not show the secret value" + ); + assert!(message.ends_with("response-check: the response holds the value of a host secret (secret \"GITHUB\")"), "{message}"); + } else { + assert!(done(result).ends_with("4\n")); + } + } +} + +/// The prefix and the value of a secret header count against `MAX_HEADER_VALUE_BYTES` +/// before the request exists. Control: a header of exactly the cap. +#[test] +fn a_secret_header_value_is_bounded_before_the_request_exists() { + let main = "---\ndata:\n a:\n url: https://a.example/x\n headers:\n Authorization: {secret: TOKEN, prefix: 'Bearer '}\n---\n{{a.n}}\n"; + let room = MAX_HEADER_VALUE_BYTES - "Bearer ".len(); + for (length, fits) in [(room, true), (room + 1, false)] { + let net = with_secret( + policy(&["a.example"]), + "TOKEN", + &"k".repeat(length), + "a.example", + ); + let (result, needed) = run_round( + &[("main.mds", main)], + &Runtime::new(), + &net, + &Responses::new(), + ); + if fits { + assert_eq!(need(result).len(), 1); + } else { + let err = result.unwrap_err(); + assert_eq!(code(&err), "mds::resource_limit"); + assert_eq!( + err.to_string(), + "resource limit exceeded: \"main.mds\", entry \"a\", field \"Authorization\": header value exceeds the maximum length of 8192 bytes" + ); + assert!(needed.is_empty()); + } + } +} + +/// TP-89: a secret header in an imported module fails, with the import opt-in too. +/// Control: the same header in the entry module. +#[test] +fn a_secret_header_is_allowed_in_the_entry_module_only() { + let entry = "a:\n url: https://a.example/x\n headers:\n Authorization: {secret: TOKEN, prefix: 'Bearer '}\n"; + let lib = format!("---\ndata:\n {entry}---\n{{{{a.n}}}}\n"); + let main = "@import \"./lib.mds\" as lib\n@include lib\n"; + let net = with_secret(policy(&["a.example"]), "TOKEN", PLANTED, "a.example").with_imports(true); + let files = [("main.mds", main), ("lib.mds", lib.as_str())]; + let err = run_step(&files, &Runtime::new(), &net, &Responses::new()).unwrap_err(); + assert_eq!(code(&err), "mds::data"); + assert!( + err.to_string() + .ends_with("a secret header is allowed in the entry module only"), + "{err}" + ); + let requests = need(run_step( + &[("main.mds", &lib)], + &Runtime::new(), + &net, + &Responses::new(), + )); + assert_eq!(urls(&requests), ["https://a.example/x"]); +} + +/// A request cannot set a header that the sender writes from the URL, that frames the +/// message or that changes the method, in any letter case and in any value form, so a +/// `Host` header can not name a host that the allow list did not check. The compile fails +/// before any request exists. Controls: a name that only holds one of these names, and the +/// plain request. +#[test] +fn a_request_cannot_set_a_sender_header() { + let net = with_secret(policy(&["a.example"]), "TOKEN", PLANTED, "a.example"); + let main = |header: &str| { + format!("---\ndata:\n a:\n url: https://a.example/x\n headers:\n {header}\n---\n{{{{a.n}}}}\n") + }; + let runtime = Runtime::from([("v".to_owned(), Value::String("other.example".into()))]); + for name in [ + "Host", + "HOST", + "host", + "Content-Length", + "transfer-encoding", + "Connection", + "Keep-Alive", + "Proxy-Connection", + "TE", + "Trailer", + "Upgrade", + "X-HTTP-Method-Override", + "x-http-method", + "X-Method-OVERRIDE", + ] { + for value in ["other.example", "'{{v}}'", "{secret: TOKEN, prefix: ''}"] { + let text = main(&format!("{name}: {value}")); + let (result, needed) = run_round( + &[("main.mds", text.as_str())], + &runtime, + &net, + &Responses::new(), + ); + let err = result.unwrap_err(); + assert_eq!(code(&err), "mds::data", "{name}: {value}"); + let message = err.to_string(); + assert!( + message.ends_with(&format!( + "field \"{name}\": a request cannot set this header" + )), + "{message}" + ); + assert!(!message.contains("other.example"), "{message}"); + assert!(needed.is_empty(), "{name}: {value}"); + } + } + for control in [ + "X-Host: other.example", + "Hosts: other.example", + "X-Method-Overrides: other.example", + "X-Plain: kept", + ] { + let text = main(control); + let requests = need(run_step( + &[("main.mds", text.as_str())], + &runtime, + &net, + &Responses::new(), + )); + assert_eq!(urls(&requests), ["https://a.example/x"], "{control}"); + assert_eq!(requests[0].headers().len(), 1, "{control}"); + } +} + +/// An `@extends` base is a module other than the entry module, so its URL entry cannot +/// use a secret header, also with the import opt-in. Control: the same base text as the +/// entry module derives its request. +#[test] +fn an_extends_base_cannot_use_a_secret_header() { + let entry = "a:\n url: https://a.example/x\n headers:\n Authorization: {secret: TOKEN, prefix: 'Bearer '}\n"; + let base = format!("---\ndata:\n {entry}---\n{{{{a.n}}}}\n"); + let child = "@extends \"./base.mds\"\n"; + let net = with_secret(policy(&["a.example"]), "TOKEN", PLANTED, "a.example").with_imports(true); + let files = [("main.mds", child), ("base.mds", base.as_str())]; + let (result, needed) = run_round(&files, &Runtime::new(), &net, &Responses::new()); + let err = result.unwrap_err(); + assert_eq!(code(&err), "mds::data"); + assert!( + err.to_string() + .ends_with("a secret header is allowed in the entry module only"), + "{err}" + ); + assert!(needed.is_empty()); + let requests = need(run_step( + &[("main.mds", &base)], + &Runtime::new(), + &net, + &Responses::new(), + )); + assert_eq!(urls(&requests), ["https://a.example/x"]); +} + +/// Replay does not lift the secret header rule: a replayed URL entry with a secret +/// header fails in an imported module and in an `@extends` base, and no request exists. +/// Control: the same replayed entry in the entry module renders the runtime value. +#[test] +fn a_replayed_secret_header_is_allowed_in_the_entry_module_only() { + let entry = "a:\n url: https://a.example/x\n headers:\n Authorization: {secret: TOKEN, prefix: 'Bearer '}\n"; + let module = format!("---\ndata:\n {entry}---\n{{{{a}}}}\n"); + let runtime = Runtime::from([("a".to_owned(), Value::String("replayed".into()))]); + let net = with_secret(policy(&["a.example"]), "TOKEN", PLANTED, "a.example").with_imports(true); + for main in [ + "@import \"./lib.mds\" as lib\n@include lib\n", + "@extends \"./lib.mds\"\n", + ] { + let files = [("main.mds", main), ("lib.mds", module.as_str())]; + let (result, needed) = run_round(&files, &runtime, &net, &Responses::new()); + let err = result.unwrap_err(); + assert_eq!(code(&err), "mds::data", "{main}"); + let message = err.to_string(); + assert!(message.contains("lib.mds"), "{message}"); + assert!( + message.ends_with("a secret header is allowed in the entry module only"), + "{message}" + ); + assert!(needed.is_empty(), "{main}"); + } + let text = done(run_step( + &[("main.mds", &module)], + &runtime, + &net, + &Responses::new(), + )); + assert!(text.ends_with("replayed\n"), "{text}"); +} + +/// TP-97: a URL entry of an imported module needs the import opt-in. Control: with it. +#[test] +fn a_url_entry_of_an_imported_module_needs_the_import_opt_in() { + let lib = "---\ndata:\n b: https://a.example/lib\n---\n{{b.n}}\n"; + let main = "@import \"./lib.mds\" as lib\n@include lib\n"; + let files = [("main.mds", main), ("lib.mds", lib)]; + let net = policy(&["a.example"]); + let err = run_step(&files, &Runtime::new(), &net, &Responses::new()).unwrap_err(); + assert_eq!(code(&err), "mds::network_denied"); + assert!(err.to_string().contains(": import-opt-in: "), "{err}"); + let requests = need(run_step( + &files, + &Runtime::new(), + &net.with_imports(true), + &Responses::new(), + )); + assert_eq!(urls(&requests), ["https://a.example/lib"]); +} + +/// TP-90: each round checks the policy again, so a narrower allow list on resume fails. +/// Control: the same list. +#[test] +fn a_narrower_allow_list_on_resume_fails() { + let main = + "---\ndata:\n a: https://a.example/a\n b: https://b.example/b\n---\n{{a.n}}{{b.n}}\n"; + let files = [("main.mds", main)]; + let wide = policy(&["a.example", "b.example"]); + let requests = need(run_step(&files, &Runtime::new(), &wide, &Responses::new())); + let mut responses = Responses::new(); + let body = || ok(r#"{"n": 1}"#); + answer( + &requests, + &mut responses, + &[ + ("https://a.example/a", body()), + ("https://b.example/b", body()), + ], + ); + let err = run_step(&files, &Runtime::new(), &policy(&["a.example"]), &responses).unwrap_err(); + assert!(err.to_string().contains(": allow-list: "), "{err}"); + assert!(done(run_step(&files, &Runtime::new(), &wide, &responses)).ends_with("11\n")); +} + +/// A compile derives at most `MAX_REQUESTS_PER_COMPILE` distinct requests, redirect hops +/// included; the next one fails before it is added. Control: exactly the cap. +#[test] +fn the_request_cap_binds_before_a_new_request_is_added() { + let mut main = String::from("---\ndata:\n"); + for index in 0..MAX_REQUESTS_PER_COMPILE { + main.push_str(&format!(" e{index}: https://a.example/e{index}\n")); + } + main.push_str("---\n"); + let files = [("main.mds", main.as_str())]; + let net = policy(&["a.example"]); + let requests = need(run_step(&files, &Runtime::new(), &net, &Responses::new())); + assert_eq!(requests.len(), MAX_REQUESTS_PER_COMPILE); + let mut responses = Responses::new(); + for (index, request) in requests.iter().enumerate() { + let response = if index == 0 { moved("/hop") } else { ok("1") }; + responses.insert(request.id(), response); + } + let (result, needed) = run_round(&files, &Runtime::new(), &net, &responses); + let err = result.unwrap_err(); + assert_eq!( + err.to_string(), + "resource limit exceeded: too many requests (max 64 per compile)" + ); + assert_eq!(needed.len(), 1); +} + +/// A transport failure, a status that is not 2xx or 3xx and a refused address fail the +/// entry. A message names the URL as declared and the origin, never the expanded URL. +#[test] +fn a_failed_answer_fails_the_entry() { + let main = "---\nhidden: secret-path\ndata:\n a: https://a.example/{{hidden}}\n---\n{{a}}\n"; + let net = policy(&["a.example"]); + let first = need(run_step( + &[("main.mds", main)], + &Runtime::new(), + &net, + &Responses::new(), + )); + let large = Response::Http { + status: 200, + headers: vec![("x-big".into(), vec![b'a'; 16 * 1024])], + body: b"1".to_vec(), + }; + let unlocated = Response::Http { + status: 302, + headers: Vec::new(), + body: Vec::new(), + }; + for (response, code_text, tail) in [ + ( + Response::Failed(TransportFailure::Timeout), + "mds::network", + "the request timed out", + ), + ( + Response::Failed(TransportFailure::Connect), + "mds::network", + "the connection failed", + ), + ( + Response::Failed(TransportFailure::Tls), + "mds::network", + "the TLS handshake failed", + ), + ( + Response::Failed(TransportFailure::Protocol), + "mds::network", + "the response is not valid HTTP", + ), + ( + Response::Failed(TransportFailure::BodyTooLarge), + "mds::network", + "the response body exceeds 10485760 bytes", + ), + ( + Response::Http { + status: 404, + headers: Vec::new(), + body: Vec::new(), + }, + "mds::network", + "the server answered with HTTP status 404", + ), + ( + Response::Failed(TransportFailure::AddressRefused), + "mds::network_denied", + "transport-address: the address is in a refused range", + ), + ( + large, + "mds::network", + "the response headers exceed 16384 bytes", + ), + ( + unlocated, + "mds::network_denied", + "redirect-check: a redirect needs exactly one location header", + ), + ] { + let mut responses = Responses::new(); + responses.insert(first[0].id(), response); + let err = run_step(&[("main.mds", main)], &Runtime::new(), &net, &responses).unwrap_err(); + assert_eq!(code(&err), code_text, "{err}"); + let message = err.to_string(); + assert!( + message.contains( + r#"entry "a", URL "https://a.example/{{hidden}}", origin "https://a.example": "# + ), + "{message}" + ); + assert!(message.ends_with(tail), "{message}"); + assert!(!message.contains("secret-path"), "{message}"); + } +} + +fn answered(status: u16, headers: &[(&str, &str)], body: &str) -> Response { + Response::Http { + status, + headers: headers + .iter() + .map(|&(name, value)| (name.to_owned(), value.as_bytes().to_vec())) + .collect(), + body: body.as_bytes().to_vec(), + } +} + +/// Run one entry `a` of `main` to its end, with `response` as the answer to its request. +fn run_answered(main: &str, net: &NetworkPolicy, response: Response) -> Result { + let files = [("main.mds", main)]; + let requests = need(run_step(&files, &Runtime::new(), net, &Responses::new())); + let mut responses = Responses::new(); + for request in &requests { + responses.insert(request.id(), response.clone()); + } + run_step(&files, &Runtime::new(), net, &responses).map(|(text, outcome)| { + assert!(matches!(outcome, Outcome::Done(_)), "{outcome:?}"); + text + }) +} + +/// TP-95 and TP-100: with the envelope, a status that is not 2xx binds as +/// `{status, headers, body}`, and a reference reads a header with dot access. Control: +/// the same answer without the envelope fails with the status number. +#[test] +fn a_status_that_is_not_2xx_binds_only_with_the_envelope() { + let net = policy(&["a.example"]); + let response = answered(404, &[("X-Rate-Limit", "7")], r#"{"n": 1}"#); + let main = "---\ndata:\n a: {url: 'https://a.example/x', envelope: true}\n---\n{{a.status}} {{a.headers.x_rate_limit}} {{a.body.n}}\n"; + let text = run_answered(main, &net, response.clone()).unwrap(); + assert!(text.ends_with("404 7 1\n"), "{text:?}"); + let plain = "---\ndata:\n a: https://a.example/x\n---\n{{a.n}}\n"; + let err = run_answered(plain, &net, response).unwrap_err(); + assert_eq!(code(&err), "mds::network"); + assert!( + err.to_string() + .ends_with("the server answered with HTTP status 404"), + "{err}" + ); +} + +/// The envelope binds a status from 200 to 599 only. Control: 599 binds. +#[test] +fn the_envelope_binds_a_status_from_200_to_599_only() { + let net = policy(&["a.example"]); + let main = "---\ndata:\n a: {url: 'https://a.example/x', envelope: true}\n---\n{{a.status}}\n"; + for status in [100, 199, 600] { + let err = run_answered(main, &net, answered(status, &[], "1")).unwrap_err(); + assert_eq!(code(&err), "mds::network", "{err}"); + assert!( + err.to_string() + .ends_with(&format!("the server answered with HTTP status {status}")), + "{err}" + ); + } + let text = run_answered(main, &net, answered(599, &[], "1")).unwrap(); + assert!(text.ends_with("599\n"), "{text:?}"); +} + +/// A HEAD envelope has `body: null`: the core never converts the body of a HEAD answer, +/// so a body that is not JSON does not fail. Control: the same body for GET fails. +#[test] +fn a_head_envelope_has_a_null_body() { + let net = policy(&["a.example"]); + let response = answered(200, &[("Content-Length", "12")], "not json ["); + let entry = |method: &str| { + format!("---\ndata:\n a: {{url: 'https://a.example/x', method: {method}, envelope: true}}\n---\n{{{{a.headers.content_length}}}}\n@if a.body:\nbody\n@else:\nno body\n@end\n") + }; + let text = run_answered(&entry("HEAD"), &net, response.clone()).unwrap(); + assert!(text.ends_with("12\nno body\n"), "{text:?}"); + let err = run_answered(&entry("GET"), &net, response).unwrap_err(); + assert_eq!(code(&err), "mds::yaml", "{err}"); +} + +/// One response binds a body entry and an envelope entry of the same request, each in +/// its own shape: the memo keeps the envelope flag next to the request ID. +#[test] +fn one_response_binds_a_body_entry_and_an_envelope_entry() { + let main = "---\ndata:\n a: https://a.example/x\n b: {url: 'https://a.example/x', envelope: true}\n---\n{{a.n}} {{b.status}} {{b.body.n}}\n"; + let net = policy(&["a.example"]); + let requests = need(run_step( + &[("main.mds", main)], + &Runtime::new(), + &net, + &Responses::new(), + )); + assert_eq!(urls(&requests), ["https://a.example/x"]); + let text = run_answered(main, &net, answered(200, &[], r#"{"n": 3}"#)).unwrap(); + assert!(text.ends_with("3 200 3\n"), "{text:?}"); +} + +/// A host secret value in a header of the envelope fails the response check, and the +/// message names the secret, never its value. Control: another header value binds. +#[test] +fn a_secret_value_in_an_envelope_header_fails_the_response_check() { + let net = with_secret(policy(&["a.example"]), "TOKEN", PLANTED, "a.example"); + let main = "---\ndata:\n a: {url: 'https://a.example/x', envelope: true}\n---\n{{a.status}}\n"; + let err = run_answered(main, &net, answered(200, &[("X-Echo", PLANTED)], "1")).unwrap_err(); + assert_eq!(code(&err), "mds::network_denied"); + let message = err.to_string(); + // The value check comes first with a fixed message, so `{message}` below cannot + // show the value. + assert!( + !message.contains(PLANTED), + "the message must not show the secret value" + ); + assert!( + message.ends_with( + r#"response-check: the response holds the value of a host secret (secret "TOKEN")"# + ), + "{message}" + ); + let text = run_answered(main, &net, answered(200, &[("X-Echo", "plain")], "1")).unwrap(); + assert!(text.ends_with("200\n"), "{text:?}"); +} + +/// The raw bodies of one fetch state count against one total, the compile memory budget, +/// whatever the status: a redirect body and an error body count too. Exactly the total +/// passes, an answer with no body and a failed send still pass at the total, and one +/// more byte fails with `mds::resource_limit`. +#[test] +fn the_fetch_state_counts_every_body_against_one_total() { + let cap = usize::try_from(MAX_RESPONSE_BYTES).unwrap(); + let total = MAX_RESPONSE_BODY_BYTES_PER_COMPILE; + assert_eq!(total % cap, 0, "the total is a whole number of full bodies"); + let id = |n: usize| RequestId::parse_hex(&format!("{n:064x}")).unwrap(); + let mut state = FetchState::new(); + assert_eq!(state.body_bytes_left(), total); + // The bodies come zeroed from the allocator, so the test writes no 200 MiB. + let statuses = [200, 301, 302, 404, 500].into_iter().cycle(); + for (n, status) in statuses.take(total / cap).enumerate() { + let response = Response::http(status, Vec::new(), vec![0; cap]); + state = state.with_response(id(n), response).unwrap(); + assert_eq!(state.body_bytes_left(), total - (n + 1) * cap); + } + state = state + .with_response(id(100), Response::http(302, Vec::new(), Vec::new())) + .unwrap(); + state = state + .with_response(id(101), Response::failed(TransportFailure::Timeout)) + .unwrap(); + let err = state + .with_response(id(102), Response::http(302, Vec::new(), vec![0; 1])) + .unwrap_err(); + assert_eq!(code(&err), "mds::resource_limit"); + assert_eq!( + err.to_string(), + "resource limit exceeded: response bodies exceed 209715200 bytes per compile" + ); + assert_eq!( + err.to_string(), + MdsError::response_bodies_exceeded().to_string() + ); +} + +/// The core checks the body of an answer that the host gives again: a body of exactly +/// 10 MiB binds, and one byte more fails with `mds::network`. A redirect answer is +/// checked too: at the cap its hop goes on, and one byte more fails. +#[test] +fn the_core_body_cap_binds_at_the_cap_and_fails_one_byte_over() { + let cap = usize::try_from(MAX_RESPONSE_BYTES).unwrap(); + let net = policy(&["a.example"]); + let text = + "---\ndata:\n a: {url: 'https://a.example/x', accept: text}\n---\n@if a:\nbound\n@end\n"; + let main = "---\ndata:\n a: https://a.example/x\n---\n{{a.n}}\n"; + let body = |len| Response::http(200, Vec::new(), vec![b'a'; len]); + let hop = |len| { + Response::http( + 302, + vec![("Location".into(), b"/next".to_vec())], + vec![b'a'; len], + ) + }; + let bound = run_answered(text, &net, body(cap)).unwrap(); + assert!(bound.ends_with("bound\n"), "control: a full body binds"); + let files = [("main.mds", main)]; + let first = need(run_step(&files, &Runtime::new(), &net, &Responses::new())); + let mut responses = Responses::new(); + answer(&first, &mut responses, &[("https://a.example/x", hop(cap))]); + let next = need(run_step(&files, &Runtime::new(), &net, &responses)); + assert_eq!( + urls(&next), + ["https://a.example/next"], + "control: a full hop" + ); + for (source, response) in [(text, body(cap + 1)), (main, hop(cap + 1))] { + let err = run_answered(source, &net, response).unwrap_err(); + assert_eq!(code(&err), "mds::network", "{err}"); + assert!( + err.to_string() + .ends_with("the response body exceeds 10485760 bytes"), + "{err}" + ); + } +} + +/// A response body counts against the data byte total of a compile, as a data file +/// does: four bodies of 8 MiB give exactly 32 MiB and bind, and one byte more fails with +/// `mds::resource_limit`. +#[test] +fn response_bodies_count_against_the_data_total_of_a_compile() { + let mut main = String::from("---\ndata:\n"); + for name in ["a", "b", "c", "d"] { + main.push_str(&format!( + " {name}: {{url: 'https://a.example/{name}', accept: text}}\n" + )); + } + main.push_str("---\nbound\n"); + let files = [("main.mds", main.as_str())]; + let net = policy(&["a.example"]); + let requests = need(run_step(&files, &Runtime::new(), &net, &Responses::new())); + assert_eq!(requests.len(), 4); + let quarter = MAX_DATA_BYTES_PER_COMPILE / 4; + for (extra, fits) in [(0, true), (1, false)] { + let mut responses = Responses::new(); + for (index, request) in requests.iter().enumerate() { + let len = quarter + if index == 3 { extra } else { 0 }; + responses.insert( + request.id(), + Response::http(200, Vec::new(), vec![b'a'; len]), + ); + } + let result = run_step(&files, &Runtime::new(), &net, &responses); + if fits { + assert!( + done(result).ends_with("bound\n"), + "control: the total binds" + ); + } else { + let err = result.unwrap_err(); + assert_eq!(code(&err), "mds::resource_limit", "{err}"); + assert_eq!( + err.to_string(), + "resource limit exceeded: data files exceed 33554432 bytes per compile" + ); + } + } +} + +/// Each redirect status runs the hop checks, with and without the envelope: a +/// `location` outside the allow list fails. Controls: a listed `location` gives the next +/// request, and 300 and 304, which are not redirects, bind with the envelope and fail +/// without it. +#[test] +fn each_redirect_status_runs_the_hop_checks() { + let net = policy(&["a.example"]); + let to = |status, location: &str| { + Response::http( + status, + vec![("Location".into(), location.as_bytes().to_vec())], + b"1".to_vec(), + ) + }; + let plain = "---\ndata:\n a: https://a.example/x\n---\n{{a}}\n"; + let envelope = + "---\ndata:\n a: {url: 'https://a.example/x', envelope: true}\n---\n{{a.status}}\n"; + for status in [301, 302, 303, 307, 308] { + for main in [plain, envelope] { + let files = [("main.mds", main)]; + let first = need(run_step(&files, &Runtime::new(), &net, &Responses::new())); + for (location, refused) in [ + ("https://c.example/", true), + ("https://a.example/next", false), + ] { + let mut responses = Responses::new(); + answer( + &first, + &mut responses, + &[("https://a.example/x", to(status, location))], + ); + let result = run_step(&files, &Runtime::new(), &net, &responses); + if refused { + let err = result.unwrap_err(); + assert_eq!(code(&err), "mds::network_denied", "{status}: {err}"); + assert!( + err.to_string().ends_with( + "redirect-check: the redirect target is not in the allow list" + ), + "{status}: {err}" + ); + } else { + assert_eq!(urls(&need(result)), [location], "{status}"); + } + } + } + } + for status in [300, 304] { + let text = run_answered(envelope, &net, to(status, "https://c.example/")).unwrap(); + assert!(text.ends_with(&format!("{status}\n")), "{text:?}"); + let err = run_answered(plain, &net, to(status, "https://c.example/")).unwrap_err(); + assert!( + err.to_string() + .ends_with(&format!("the server answered with HTTP status {status}")), + "{err}" + ); + } +} + +/// The names that only the step engine may use. A use outside the engine files links +/// engine code into a build that never starts a step compile, such as the WASM build. +const ENGINE_NAMES: [&str; 12] = [ + "StepCtx::new", + "bind_with_engine", + "scan_secrets", + "request_label", + "encode::expand", + "envelope::envelope", + "Request::new", + "parse_location", + ".check_hop(", + ".check_method(", + ".check_origin(", + ".keeps_header(", +]; + +/// The files of the step engine, relative to `src/`. +const ENGINE_FILES: [&str; 6] = [ + "data/step.rs", + "data/policy.rs", + "data/url.rs", + "data/encode.rs", + "data/envelope.rs", + "data/request.rs", +]; + +/// The findings of one source file at `path` (relative to `src/`, with `/` between parts): +/// each place where code outside the engine reaches the engine other than through the +/// `StepCtx.bind` pointer. Comments and literals are not code. +fn engine_reach_findings(path: &str, text: &str) -> Vec { + let code = code_only(text); + let mut findings = Vec::new(); + if path == "data/step.rs" { + let mut pointer_site = 0..0; + match fn_body(&code, "pub(crate) fn bind_url_entry(") { + Some((lines, body)) => { + if !body.contains("ctx.bind") || has_name(&body, "bind_with_engine") { + findings.push(format!( + "{path}: bind_url_entry must reach the engine through ctx.bind only" + )); + } + pointer_site = lines; + } + None => findings.push(format!("{path}: bind_url_entry is missing")), + } + for (index, line) in code.lines().enumerate() { + let allowed = line.trim_start().starts_with("fn bind_with_engine(") + || line.trim() == "bind: bind_with_engine,"; + if !pointer_site.contains(&index) && !allowed && has_name(line, "bind_with_engine") { + findings.push(format!("{path}:{}: bind_with_engine", index + 1)); + } + } + } + if !ENGINE_FILES.contains(&path) { + for (index, line) in code.lines().enumerate() { + let names = ENGINE_NAMES + .iter() + .chain((path != "lib.rs").then_some(&"ctx.start(")); + for name in names { + if has_name(line, name) { + findings.push(format!("{path}:{}: {name}", index + 1)); + } + } + } + } + findings +} + +/// The line range and the text of the function whose line starts with `head`, to the +/// next line that starts with `}`. +fn fn_body(code: &str, head: &str) -> Option<(Range, String)> { + let lines: Vec<&str> = code.lines().collect(); + let start = lines.iter().position(|line| line.starts_with(head))?; + let end = start + + lines[start..] + .iter() + .position(|line| line.starts_with('}'))?; + Some((start..end + 1, lines[start..=end].join("\n"))) +} + +/// `line` names `name`: an identifier character is not next to an identifier edge of +/// the name. +fn has_name(line: &str, name: &str) -> bool { + let ident = |ch: char| ch.is_alphanumeric() || ch == '_'; + line.match_indices(name).any(|(at, _)| { + let before = line[..at].chars().next_back().is_some_and(ident); + let after = line[at + name.len()..].chars().next().is_some_and(ident); + let joined_before = before && name.starts_with(ident); + let joined_after = after && name.ends_with(ident); + !joined_before && !joined_after + }) +} + +/// `text` with each comment and each string or char literal made blank. Each char gives +/// one char and each line break stays, so the line numbers stay. +fn code_only(text: &str) -> String { + let chars: Vec = text.chars().collect(); + let mut out = String::with_capacity(text.len()); + let blank = |out: &mut String, chars: &[char]| { + for &ch in chars { + out.push(if ch == '\n' { '\n' } else { ' ' }); + } + }; + let at = |i: usize, pattern: &str| { + pattern + .chars() + .enumerate() + .all(|(k, ch)| chars.get(i + k) == Some(&ch)) + }; + let ident = |i: usize| { + chars + .get(i) + .is_some_and(|&ch| ch.is_alphanumeric() || ch == '_') + }; + // A raw string starts with `r`, or `br`, that ends no identifier. + let raw_start = |i: usize| { + let start = if i > 0 && chars[i - 1] == 'b' { + i - 1 + } else { + i + }; + chars[i] == 'r' && !(start > 0 && ident(start - 1)) && (at(i, "r\"") || at(i, "r#")) + }; + let mut i = 0; + // Each turn moves `i` on by one char or more, so the bound is never reached first. + for _ in 0..=chars.len() { + let Some(&ch) = chars.get(i) else { break }; + let end = if at(i, "//") { + chars[i..] + .iter() + .position(|&c| c == '\n') + .map_or(chars.len(), |n| i + n) + } else if at(i, "/*") { + let mut depth = 0usize; + let mut j = i; + for _ in 0..chars.len() { + if j >= chars.len() { + break; + } + if at(j, "/*") { + depth += 1; + j += 2; + } else if at(j, "*/") { + depth -= 1; + j += 2; + if depth == 0 { + break; + } + } else { + j += 1; + } + } + j.min(chars.len()) + } else if ch == '"' || raw_start(i) { + let hashes = if ch == 'r' { + chars[i + 1..].iter().take_while(|&&c| c == '#').count() + } else { + 0 + }; + let open = if ch == 'r' { i + 1 + hashes } else { i }; + if chars.get(open) != Some(&'"') { + // A raw identifier such as `r#type`. + out.push(ch); + i += 1; + continue; + } + let close: String = std::iter::once('"') + .chain("#".repeat(hashes).chars()) + .collect(); + let mut j = open + 1; + for _ in 0..chars.len() { + if j >= chars.len() || at(j, &close) { + break; + } + j += if ch == '"' && chars[j] == '\\' { 2 } else { 1 }; + } + (j + close.chars().count()).min(chars.len()) + } else if ch == '\'' && chars.get(i + 1) == Some(&'\\') { + // An escape char literal: the closing quote comes after the escaped char. + chars + .get(i + 3..) + .and_then(|rest| rest.iter().position(|&c| c == '\'')) + .map_or(chars.len(), |n| i + 4 + n) + } else if ch == '\'' && chars.get(i + 2) == Some(&'\'') { + i + 3 + } else { + out.push(ch); + i += 1; + continue; + }; + blank(&mut out, &chars[i..end]); + i = end; + } + out +} + +/// The `.rs` files below `root` that are not `*_tests.rs` files, as paths relative to +/// `root` with `/` between parts, with their text, and the directories that the walk read. +/// Every loop is bounded, and the walk must read every directory. +fn source_files(root: &Path) -> (Vec, Vec<(String, String)>) { + let relative = |path: &Path| { + let parts: Vec = path + .strip_prefix(root) + .unwrap() + .components() + .map(|part| part.as_os_str().to_string_lossy().into_owned()) + .collect(); + parts.join("/") + }; + let mut dirs = vec![root.to_path_buf()]; + let mut visited = Vec::new(); + let mut files = Vec::new(); + for _ in 0..1024 { + let Some(dir) = dirs.pop() else { break }; + let entries: Vec<_> = std::fs::read_dir(&dir).unwrap().take(4096).collect(); + assert!( + entries.len() < 4096, + "a source directory has too many entries" + ); + for entry in entries { + let entry = entry.unwrap(); + let path = entry.path(); + let kind = entry.file_type().unwrap(); + let name = entry.file_name().to_string_lossy().into_owned(); + if kind.is_dir() { + dirs.push(path); + } else if kind.is_file() && name.ends_with(".rs") && !name.ends_with("_tests.rs") { + files.push((relative(&path), std::fs::read_to_string(&path).unwrap())); + } + } + visited.push(relative(&dir)); + } + assert!(dirs.is_empty(), "the walk must read every source directory"); + (visited, files) +} + +/// Resolver code reaches the step engine only through the `StepCtx.bind` pointer, so a +/// build that never starts a step compile keeps no engine code. The scan pins the code +/// shape; the WASM size limit of CI stays the measure of the linked code. +#[test] +fn code_outside_the_engine_reaches_it_through_the_bind_pointer_only() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let (dirs, files) = source_files(&root); + for dir in ["data", "resolver", "evaluator", "lint"] { + assert!( + dirs.iter().any(|read| read == dir), + "the walk must read {dir}" + ); + } + let read = |path: &str| { + files + .iter() + .find(|(known, _)| known == path) + .map(|(_, text)| text.as_str()) + .unwrap_or_else(|| panic!("the walk must read {path}")) + }; + for path in ["data/step.rs", "resolver/process.rs", "lib.rs"] { + assert!(!read(path).is_empty(), "{path} must hold code"); + } + let module_scope = code_only(read("resolver/module_scope.rs")); + for call in ["step::bind_url_entry", "step::check_secret_module"] { + assert!( + module_scope.contains(call), + "resolver/module_scope.rs must call {call}" + ); + } + let findings: Vec = files + .iter() + .flat_map(|(path, text)| engine_reach_findings(path, text)) + .collect(); + assert_eq!( + findings, + Vec::::new(), + "code outside the engine must reach it through StepCtx.bind only" + ); +} + +/// Each planted reach of the engine gives exactly its own finding: a direct call at the +/// pointer site, a call in a planted child module and a hop check in resolver code. The +/// walk reads a planted child directory and skips a test file. Control: comments and +/// literals that name the engine give no finding. +#[test] +fn the_engine_scan_reports_each_planted_reach() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let step = std::fs::read_to_string(root.join("data/step.rs")).unwrap(); + let process = std::fs::read_to_string(root.join("resolver/process.rs")).unwrap(); + let quiet = "// scan_secrets(v, p)\n/* a /* nested */ policy.check_hop(a, b, 1) */\nconst A: &str = \"StepCtx::new\";\nconst B: &str = r#\"envelope::envelope\"#;\nconst C: char = '\\'';\nfn f<'a>(x: &'a str) -> &'a str { x }\n"; + assert_eq!( + engine_reach_findings("resolver/quiet.rs", quiet), + Vec::::new() + ); + assert_eq!( + engine_reach_findings("data/step.rs", &step), + Vec::::new() + ); + + let pointer = step.replacen(" bind(node,", " bind_with_engine(node,", 1); + assert_ne!(pointer, step, "the plant must change the pointer site"); + assert_eq!( + engine_reach_findings("data/step.rs", &pointer), + ["data/step.rs: bind_url_entry must reach the engine through ctx.bind only"] + ); + + let planted = "pub(super) fn leak(v: &Value, p: &NetworkPolicy) {\n let _ = crate::data::step::scan_secrets(v, p);\n}\n"; + assert_eq!( + engine_reach_findings("resolver/nested/planted.rs", planted), + ["resolver/nested/planted.rs:2: scan_secrets"] + ); + + let hop = format!("{process}\nfn planted(policy: &NetworkPolicy) {{\n let _ = policy.check_hop(a, b, 1);\n}}\n"); + let line = hop + .lines() + .position(|text| text.contains(".check_hop(")) + .unwrap() + + 1; + assert_eq!( + engine_reach_findings("resolver/process.rs", &hop), + [format!("resolver/process.rs:{line}: .check_hop(")] + ); + + let dir = tempfile::tempdir().unwrap(); + let nested = dir.path().join("resolver").join("nested"); + std::fs::create_dir_all(&nested).unwrap(); + std::fs::write(nested.join("planted.rs"), planted).unwrap(); + std::fs::write(nested.join("planted_tests.rs"), planted).unwrap(); + let (dirs, files) = source_files(dir.path()); + assert!(dirs.iter().any(|read| read == "resolver/nested")); + let findings: Vec = files + .iter() + .flat_map(|(path, text)| engine_reach_findings(path, text)) + .collect(); + assert_eq!(findings, ["resolver/nested/planted.rs:2: scan_secrets"]); +} diff --git a/crates/mds-core/src/data/url.rs b/crates/mds-core/src/data/url.rs new file mode 100644 index 00000000..91eee462 --- /dev/null +++ b/crates/mds-core/src/data/url.rs @@ -0,0 +1,380 @@ +//! The strict URL parser of network data entries. +//! +//! One parser reads every URL that a request can go to: the expanded URL of an entry and +//! each redirect `location`. It accepts a narrow form and refuses all else, so no two +//! readers can disagree about the host of a URL. A refusal is a fixed reason that never +//! holds the input text. + +use std::fmt; +use std::net::{Ipv4Addr, Ipv6Addr}; + +use super::decl::has_scheme; +use crate::limits::MAX_URL_BYTES; + +/// The maximum bytes of a host name. +const MAX_HOST_BYTES: usize = 253; +/// The maximum bytes of one host name label. +const MAX_LABEL_BYTES: usize = 63; +/// The maximum digits of a port. +const MAX_PORT_DIGITS: usize = 5; + +/// The scheme of a request URL. +/// +/// This enum is `#[non_exhaustive]`: new schemes may be added in minor releases. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Scheme { + Https, + Http, +} + +impl Scheme { + /// The scheme name: `https` or `http`. + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Scheme::Https => "https", + Scheme::Http => "http", + } + } + + pub(crate) fn default_port(self) -> u16 { + match self { + Scheme::Https => 443, + Scheme::Http => 80, + } + } +} + +/// The host of a request URL. A URL holds a host only after the strict URL parser +/// checked it. +/// +/// This enum is `#[non_exhaustive]`: new host forms may be added in minor releases. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum Host { + /// A lower-case name of letter, digit and hyphen labels. + Name(String), + V4(Ipv4Addr), + V6(Ipv6Addr), +} + +impl fmt::Display for Host { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Host::Name(name) => f.write_str(name), + Host::V4(address) => write!(f, "{address}"), + Host::V6(address) => write!(f, "[{address}]"), + } + } +} + +/// A URL that passed the strict parser. It has no `Display`, and its `Debug` shows the +/// [`Origin`] only, so a message can not show its path or query by accident. +/// +/// Obtain a URL from [`Request::url`](crate::Request::url). This type is +/// `#[non_exhaustive]` and cannot be built with a struct literal. +#[non_exhaustive] +#[derive(Clone, PartialEq, Eq)] +pub struct CheckedUrl { + pub(crate) scheme: Scheme, + pub(crate) host: Host, + /// The port as written. `None` means the default port of the scheme. + pub(crate) port: Option, + /// The path. It starts with `/`. + pub(crate) path: String, + /// The text after the first `?`, if the URL has one. + pub(crate) query: Option, +} + +impl fmt::Debug for CheckedUrl { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("CheckedUrl") + .field("origin", &format_args!("{}", self.origin())) + .finish_non_exhaustive() + } +} + +impl CheckedUrl { + /// The scheme, host and port. A URL with no port has the default port. + #[must_use] + pub fn origin(&self) -> Origin { + Origin { + scheme: self.scheme, + host: self.host.clone(), + port: self.port.unwrap_or(self.scheme.default_port()), + } + } + + /// The path. It starts with `/`. + #[must_use] + pub fn path(&self) -> &str { + &self.path + } + + /// The text after the first `?`, if the URL has one. + #[must_use] + pub fn query(&self) -> Option<&str> { + self.query.as_deref() + } + + /// The URL text that a request sends: the origin (with no default port), the path + /// and the query. Never put it in a message: a message shows the origin only. + #[must_use] + pub fn to_text(&self) -> String { + let mut text = format!("{}{}", self.origin(), self.path); + if let Some(query) = &self.query { + text.push('?'); + text.push_str(query); + } + text + } +} + +/// The scheme, host and port of a URL. The default port and no port are the same origin. +/// +/// Obtain an origin from [`AllowItem::origin`](crate::AllowItem::origin). This type is +/// `#[non_exhaustive]` and cannot be built with a struct literal. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Origin { + pub(crate) scheme: Scheme, + pub(crate) host: Host, + pub(crate) port: u16, +} + +impl Origin { + #[must_use] + pub fn scheme(&self) -> Scheme { + self.scheme + } + + #[must_use] + pub fn host(&self) -> &Host { + &self.host + } + + /// The port. The default port of the scheme when the URL names none. + #[must_use] + pub fn port(&self) -> u16 { + self.port + } +} + +impl fmt::Display for Origin { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}://{}", self.scheme.as_str(), self.host)?; + if self.port != self.scheme.default_port() { + write!(f, ":{}", self.port)?; + } + Ok(()) + } +} + +/// Why the strict parser refused a URL. The reason is fixed text and never holds input. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum UrlRefusal { + TooLong, + NotVisibleAscii, + ForbiddenChar, + Percent, + Scheme, + EmptyHost, + HostName, + TrailingDot, + HostTooLong, + Ipv4, + Ipv6, + Zone, + Port, + Path, + NotAbsolute, +} + +impl UrlRefusal { + pub(crate) fn reason(self) -> &'static str { + match self { + UrlRefusal::TooLong => "URL exceeds the maximum length of 8192 bytes", + UrlRefusal::NotVisibleAscii => "URL can contain only visible ASCII characters", + UrlRefusal::ForbiddenChar => "URL cannot contain `@`, a backslash or `#`", + UrlRefusal::Percent => "each `%` in a URL needs two hex digits", + UrlRefusal::Scheme => "expected the scheme https or http", + UrlRefusal::EmptyHost => "URL has no host", + UrlRefusal::HostName => { + "expected a host name of lower-case letter, digit and inner hyphen labels" + } + UrlRefusal::TrailingDot => "host name cannot end with a dot", + UrlRefusal::HostTooLong => "host name exceeds 253 bytes", + UrlRefusal::Ipv4 => "expected an IPv4 address of four decimal parts from 0 to 255", + UrlRefusal::Ipv6 => "expected an IPv6 address in brackets", + UrlRefusal::Zone => "IPv6 address cannot have a zone", + UrlRefusal::Port => "expected a port from 1 to 65535", + UrlRefusal::Path => "expected a path that starts with `/`", + UrlRefusal::NotAbsolute => "expected an absolute URL or an absolute path", + } + } +} + +/// Parse an absolute `https` or `http` URL. +#[must_use = "a URL can be refused"] +pub(crate) fn parse_absolute(text: &str) -> Result { + if text.len() > MAX_URL_BYTES { + return Err(UrlRefusal::TooLong); + } + // After this check every byte is ASCII, so each split below is on a char boundary. + if !text.bytes().all(|byte| byte.is_ascii_graphic()) { + return Err(UrlRefusal::NotVisibleAscii); + } + if text.contains(['@', '\\', '#']) { + return Err(UrlRefusal::ForbiddenChar); + } + let percent_ok = text.split('%').skip(1).all(|rest| { + rest.as_bytes() + .first_chunk::<2>() + .is_some_and(|pair| pair.iter().all(u8::is_ascii_hexdigit)) + }); + if !percent_ok { + return Err(UrlRefusal::Percent); + } + let (scheme, rest) = if let Some(rest) = text.strip_prefix("https://") { + (Scheme::Https, rest) + } else if let Some(rest) = text.strip_prefix("http://") { + (Scheme::Http, rest) + } else { + return Err(UrlRefusal::Scheme); + }; + let (authority, target) = split_before(rest, &['/', '?']); + let (host, port) = parse_authority(authority)?; + let (path, query) = match target.split_once('?') { + Some((path, query)) => (path, Some(query)), + None if target.is_empty() => ("/", None), + None => (target, None), + }; + if !path.starts_with('/') { + return Err(UrlRefusal::Path); + } + Ok(CheckedUrl { + scheme, + host, + port, + path: path.to_owned(), + query: query.map(str::to_owned), + }) +} + +/// Parse a redirect `location`: an absolute URL, or an absolute path on the origin of +/// `base`. Every other form is refused, and both forms go through [`parse_absolute`]. +#[must_use = "a location can be refused"] +pub(crate) fn parse_location(base: &CheckedUrl, text: &str) -> Result { + if text.len() > MAX_URL_BYTES { + return Err(UrlRefusal::TooLong); + } + match text.strip_prefix('/') { + Some(rest) if !rest.starts_with('/') => parse_absolute(&format!("{}{text}", base.origin())), + None if has_scheme(text) => parse_absolute(text), + _ => Err(UrlRefusal::NotAbsolute), + } +} + +/// Split `text` before the first of `marks`, or at its end. +fn split_before<'a>(text: &'a str, marks: &[char]) -> (&'a str, &'a str) { + let at = text.find(marks).unwrap_or(text.len()); + text.split_at_checked(at).unwrap_or((text, "")) +} + +fn parse_authority(authority: &str) -> Result<(Host, Option), UrlRefusal> { + if let Some(bracketed) = authority.strip_prefix('[') { + let (inside, after) = bracketed.split_once(']').ok_or(UrlRefusal::Ipv6)?; + if inside.contains('%') { + return Err(UrlRefusal::Zone); + } + let address = inside.parse::().map_err(|_| UrlRefusal::Ipv6)?; + let port = match after { + "" => None, + _ => Some(parse_port( + after.strip_prefix(':').ok_or(UrlRefusal::Ipv6)?, + )?), + }; + return Ok((Host::V6(address), port)); + } + let (host, port) = match authority.split_once(':') { + Some((host, port)) => (host, Some(port)), + None => (authority, None), + }; + let host = parse_host(host)?; + let port = port.map(parse_port).transpose()?; + Ok((host, port)) +} + +fn parse_port(text: &str) -> Result { + if text.is_empty() + || text.len() > MAX_PORT_DIGITS + || !text.bytes().all(|byte| byte.is_ascii_digit()) + { + return Err(UrlRefusal::Port); + } + match text.parse::() { + Ok(port) if port != 0 => Ok(port), + _ => Err(UrlRefusal::Port), + } +} + +fn parse_host(text: &str) -> Result { + if text.is_empty() { + return Err(UrlRefusal::EmptyHost); + } + if text.ends_with('.') { + return Err(UrlRefusal::TrailingDot); + } + if text.len() > MAX_HOST_BYTES { + return Err(UrlRefusal::HostTooLong); + } + // A name whose last label reads as a number is an IPv4 form, never a name: other + // readers take `127.1` or `0x7f000001` as an address. + if text.rsplit('.').next().is_some_and(is_numeric_label) { + return parse_ipv4(text).map(Host::V4).ok_or(UrlRefusal::Ipv4); + } + if text.split('.').all(is_name_label) { + Ok(Host::Name(text.to_owned())) + } else { + Err(UrlRefusal::HostName) + } +} + +fn is_numeric_label(label: &str) -> bool { + let digits = !label.is_empty() && label.bytes().all(|byte| byte.is_ascii_digit()); + let hex = label + .strip_prefix("0x") + .is_some_and(|rest| rest.bytes().all(|byte| byte.is_ascii_hexdigit())); + digits || hex +} + +fn is_name_label(label: &str) -> bool { + !label.is_empty() + && label.len() <= MAX_LABEL_BYTES + && !label.starts_with('-') + && !label.ends_with('-') + && label + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') +} + +/// Four decimal parts from 0 to 255, with no leading zero. +fn parse_ipv4(text: &str) -> Option { + let mut parts = text.split('.'); + let mut octets = [0u8; 4]; + for octet in &mut octets { + let part = parts.next()?; + let canonical = matches!(part.len(), 1..=3) + && part.bytes().all(|byte| byte.is_ascii_digit()) + && (part == "0" || !part.starts_with('0')); + if !canonical { + return None; + } + *octet = part.parse().ok()?; + } + if parts.next().is_some() { + return None; + } + Some(Ipv4Addr::from(octets)) +} diff --git a/crates/mds-core/src/data/url_tests.rs b/crates/mds-core/src/data/url_tests.rs new file mode 100644 index 00000000..457fd64a --- /dev/null +++ b/crates/mds-core/src/data/url_tests.rs @@ -0,0 +1,311 @@ +use std::net::{Ipv4Addr, Ipv6Addr}; + +use super::url::{parse_absolute, parse_location, CheckedUrl, Host, Scheme, UrlRefusal}; +use crate::limits::MAX_URL_BYTES; + +fn refused(text: &str) -> UrlRefusal { + match parse_absolute(text) { + Ok(url) => panic!("{text:?} was accepted as {url:?}"), + Err(refusal) => refusal, + } +} + +fn accepted(text: &str) -> CheckedUrl { + parse_absolute(text).unwrap_or_else(|refusal| panic!("{text:?}: {}", refusal.reason())) +} + +#[test] +fn accepts_a_name_an_ipv4_literal_and_a_bracketed_ipv6_literal() { + let name = accepted("https://a.example/x?q=1"); + assert_eq!(name.scheme, Scheme::Https); + assert_eq!(name.host, Host::Name("a.example".to_owned())); + assert_eq!(name.port, None); + assert_eq!(name.path, "/x"); + assert_eq!(name.query.as_deref(), Some("q=1")); + assert_eq!(name.origin().to_string(), "https://a.example"); + + let v4 = accepted("http://127.0.0.1:8080/"); + assert_eq!(v4.scheme, Scheme::Http); + assert_eq!(v4.host, Host::V4(Ipv4Addr::LOCALHOST)); + assert_eq!(v4.port, Some(8080)); + assert_eq!((v4.path.as_str(), v4.query.as_deref()), ("/", None)); + assert_eq!(v4.origin().to_string(), "http://127.0.0.1:8080"); + + let v6 = accepted("https://[2001:db8::1]:8443/p"); + let address: Ipv6Addr = "2001:db8::1".parse().unwrap(); + assert_eq!(v6.host, Host::V6(address)); + assert_eq!(v6.port, Some(8443)); + assert_eq!(v6.origin().to_string(), "https://[2001:db8::1]:8443"); +} + +#[test] +fn an_explicit_default_port_names_the_same_origin_as_no_port() { + let explicit = accepted("https://a.example:443/"); + assert_eq!(explicit.port, Some(443)); + assert_eq!(explicit.origin(), accepted("https://a.example/").origin()); + assert_eq!(explicit.origin().to_string(), "https://a.example"); + assert_ne!( + accepted("http://a.example/").origin(), + accepted("https://a.example/").origin() + ); +} + +#[test] +fn a_url_with_no_path_has_the_root_path_and_a_query_needs_a_path() { + let bare = accepted("https://a.example"); + assert_eq!((bare.path.as_str(), bare.query.as_deref()), ("/", None)); + assert_eq!(refused("https://a.example?q=1"), UrlRefusal::Path); + assert_eq!(accepted("https://a.example/?").query.as_deref(), Some("")); +} + +#[test] +fn only_the_lower_case_https_and_http_schemes_are_accepted() { + for text in [ + "ftp://a.example/", + "HTTPS://a.example/", + "Http://a.example/", + "https:/a.example/", + "https:a.example/", + "//a.example/", + "a.example/", + ] { + assert_eq!(refused(text), UrlRefusal::Scheme, "{text}"); + } +} + +#[test] +fn user_information_backslashes_and_fragments_are_refused_anywhere() { + for text in [ + "https://user@a.example/", + "https://a.example/@me", + "https://a.example\\b.example/", + "https://a.example/x\\y", + "https://a.example/#top", + "https://a.example/x?q=1#top", + ] { + assert_eq!(refused(text), UrlRefusal::ForbiddenChar, "{text}"); + } +} + +#[test] +fn only_visible_ascii_is_accepted() { + for text in [ + "https://a.example/a b", + "https://a.example/\t", + "https://a.example/\r\n", + "https://a.example/\u{7f}", + "https://a.example/\u{e9}", + "https://\u{430}.example/", + ] { + assert_eq!(refused(text), UrlRefusal::NotVisibleAscii, "{text:?}"); + } +} + +#[test] +fn the_length_cap_admits_a_url_of_exactly_the_cap() { + let prefix = "https://a.example/"; + let at_cap = format!("{prefix}{}", "a".repeat(MAX_URL_BYTES - prefix.len())); + assert_eq!(at_cap.len(), MAX_URL_BYTES); + assert!(parse_absolute(&at_cap).is_ok()); + let over = format!("{at_cap}a"); + assert_eq!(refused(&over), UrlRefusal::TooLong); + // The cap is checked first: an over-cap URL with another fault gets the length reason. + assert_eq!(refused(&format!("{over} ")), UrlRefusal::TooLong); + assert!(UrlRefusal::TooLong + .reason() + .contains(&MAX_URL_BYTES.to_string())); +} + +#[test] +fn host_names_are_lower_case_letter_digit_hyphen_labels() { + for (text, refusal) in [ + ("https:///x", UrlRefusal::EmptyHost), + ("https://:443/", UrlRefusal::EmptyHost), + ("https://a..example/", UrlRefusal::HostName), + ("https://.a.example/", UrlRefusal::HostName), + ("https://A.example/", UrlRefusal::HostName), + ("https://-a.example/", UrlRefusal::HostName), + ("https://a-.example/", UrlRefusal::HostName), + ("https://a_b.example/", UrlRefusal::HostName), + ("https://a.example./", UrlRefusal::TrailingDot), + ("https://a.example.:443/", UrlRefusal::TrailingDot), + ] { + assert_eq!(refused(text), refusal, "{text}"); + } + let label = "a".repeat(63); + assert!(parse_absolute(&format!("https://{label}.example/")).is_ok()); + assert_eq!( + refused(&format!("https://{label}a.example/")), + UrlRefusal::HostName + ); + assert!(parse_absolute("https://xn--d1acufc.xn--p1ai/").is_ok()); + assert!(parse_absolute("https://a-b.example/").is_ok()); +} + +#[test] +fn a_host_name_has_at_most_253_bytes() { + let label = "a".repeat(61); + // Four labels of 61 bytes, four dots and a final label of 5 bytes: 253 bytes. + let at_cap = format!("{label}.{label}.{label}.{label}.abcde"); + assert_eq!(at_cap.len(), 253); + assert!(parse_absolute(&format!("https://{at_cap}/")).is_ok()); + assert_eq!( + refused(&format!("https://{at_cap}g/")), + UrlRefusal::HostTooLong + ); +} + +#[test] +fn ipv4_literals_need_four_canonical_decimal_parts() { + for text in [ + "https://127.1/", + "https://2130706433/", + "https://0x7f000001/", + "https://0x7f.0.0.1/", + "https://0177.0.0.1/", + "https://127.0.0.01/", + "https://1.2.3.256/", + "https://1.2.3.4.5/", + "https://1.2.3./", + "https://a.example.123/", + "https://a.0x1/", + "https://a.0x/", + ] { + let expected = if text.ends_with("./") { + UrlRefusal::TrailingDot + } else { + UrlRefusal::Ipv4 + }; + assert_eq!(refused(text), expected, "{text}"); + } + assert_eq!( + accepted("https://10.0.0.255/").host, + Host::V4(Ipv4Addr::new(10, 0, 0, 255)) + ); + assert_eq!( + accepted("https://0.0.0.0/").host, + Host::V4(Ipv4Addr::UNSPECIFIED) + ); + // A label that is hex letters only is a name: only a `0x` label reads as a number. + assert!(matches!(accepted("https://cafe.beef/").host, Host::Name(_))); +} + +#[test] +fn ipv6_literals_need_brackets_and_no_zone() { + for (text, refusal) in [ + ("https://[::1%25eth0]/", UrlRefusal::Zone), + ("https://[fe80::1%251]/", UrlRefusal::Zone), + ("https://[::1/", UrlRefusal::Ipv6), + ("https://[not-v6]/", UrlRefusal::Ipv6), + ("https://[::1]x/", UrlRefusal::Ipv6), + ("https://[127.0.0.1]/", UrlRefusal::Ipv6), + ("https://::1/", UrlRefusal::EmptyHost), + ] { + assert_eq!(refused(text), refusal, "{text}"); + } + let mapped = accepted("https://[::ffff:127.0.0.1]/"); + assert_eq!(mapped.host, Host::V6(Ipv4Addr::LOCALHOST.to_ipv6_mapped())); + assert_eq!(accepted("https://[::1]/").port, None); +} + +#[test] +fn ports_are_decimal_from_1_to_65535() { + for text in [ + "https://a.example:0/", + "https://a.example:65536/", + "https://a.example:/", + "https://a.example:+80/", + "https://a.example:80a/", + "https://a.example:123456/", + "https://a.example:1:2/", + "https://[::1]:/", + "https://[::1]:0/", + ] { + assert_eq!(refused(text), UrlRefusal::Port, "{text}"); + } + assert_eq!(accepted("https://a.example:65535/").port, Some(65535)); + assert_eq!(accepted("https://a.example:1/").port, Some(1)); +} + +#[test] +fn each_percent_sign_needs_two_hex_digits() { + for text in [ + "https://a.example/%zz", + "https://a.example/%2", + "https://a.example/%", + "https://a.example/x?y=%", + "https://a.example/x?y=%g0", + ] { + assert_eq!(refused(text), UrlRefusal::Percent, "{text}"); + } + assert_eq!(accepted("https://a.example/%2F%2e").path, "/%2F%2e"); +} + +#[test] +fn a_location_is_an_absolute_url_or_an_absolute_path_on_the_base_origin() { + let base = accepted("https://a.example:8443/x?y=1"); + let path = parse_location(&base, "/next?page=2").unwrap(); + assert_eq!(path.origin(), base.origin()); + assert_eq!(path.path, "/next"); + assert_eq!(path.query.as_deref(), Some("page=2")); + + let absolute = parse_location(&base, "http://b.example/z").unwrap(); + assert_eq!(absolute.origin().to_string(), "http://b.example"); + + for text in ["//b.example/z", "next", "../x", "./x", "?q=1", ""] { + assert_eq!( + parse_location(&base, text).unwrap_err(), + UrlRefusal::NotAbsolute, + "{text}" + ); + } + // Each form goes through the one strict parser. + for (text, refusal) in [ + ("/\\b.example/", UrlRefusal::ForbiddenChar), + ("/x#top", UrlRefusal::ForbiddenChar), + ("/a b", UrlRefusal::NotVisibleAscii), + ("javascript:alert", UrlRefusal::Scheme), + ("https://127.1/", UrlRefusal::Ipv4), + ] { + assert_eq!(parse_location(&base, text).unwrap_err(), refusal, "{text}"); + } +} + +#[test] +fn an_absolute_path_location_counts_the_base_origin_in_the_length_cap() { + let base = accepted("https://a.example/"); + let origin_len = "https://a.example".len(); + let fits = format!("/{}", "a".repeat(MAX_URL_BYTES - origin_len - 1)); + assert!(parse_location(&base, &fits).is_ok()); + let over = format!("{fits}a"); + assert_eq!( + parse_location(&base, &over).unwrap_err(), + UrlRefusal::TooLong + ); +} + +#[test] +fn each_refusal_has_its_own_fixed_reason() { + let all = [ + UrlRefusal::TooLong, + UrlRefusal::NotVisibleAscii, + UrlRefusal::ForbiddenChar, + UrlRefusal::Percent, + UrlRefusal::Scheme, + UrlRefusal::EmptyHost, + UrlRefusal::HostName, + UrlRefusal::TrailingDot, + UrlRefusal::HostTooLong, + UrlRefusal::Ipv4, + UrlRefusal::Ipv6, + UrlRefusal::Zone, + UrlRefusal::Port, + UrlRefusal::Path, + UrlRefusal::NotAbsolute, + ]; + let mut reasons: Vec<&str> = all.iter().map(|refusal| refusal.reason()).collect(); + assert!(reasons.iter().all(|reason| !reason.is_empty())); + reasons.sort_unstable(); + reasons.dedup(); + assert_eq!(reasons.len(), all.len()); +} diff --git a/crates/mds-core/src/error.rs b/crates/mds-core/src/error.rs index b981d2d4..10ba9daa 100644 --- a/crates/mds-core/src/error.rs +++ b/crates/mds-core/src/error.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use miette::{Diagnostic, SourceSpan}; use thiserror::Error; -use crate::limits::{MAX_COMPILE_MEMORY, MAX_OUTPUT_SIZE}; +use crate::limits::{MAX_COMPILE_MEMORY, MAX_OUTPUT_SIZE, MAX_RESPONSE_BODY_BYTES_PER_COMPILE}; use crate::lint::{ escape_path_for_message, named_source_for_render, sanitize_control_chars, sanitize_control_chars_wire, @@ -24,6 +24,40 @@ pub(crate) fn data_location(module: &str, entry: Option<&str>, field: Option<&st location } +/// The location of one request of a URL entry: the module, the entry, the URL as +/// declared and the origin, each escaped. Never pass the expanded URL. +pub(crate) fn request_location(module: &str, entry: &str, template: &str, origin: &str) -> String { + format!( + "{}, URL \"{}\", origin \"{}\"", + data_location(module, Some(entry), None), + escape_path_for_message(template), + escape_path_for_message(origin), + ) +} + +/// The fixed help of each check that can refuse a request. It never holds input text. +fn refusal_help(layer: crate::Layer) -> &'static str { + use crate::Layer; + match layer { + Layer::AllowList => "add the origin to the network allow list of the host", + Layer::ImportOptIn => { + "allow the network entries of imported modules with the import opt-in of the host" + } + Layer::UrlParser => "check the URL template and the values that its references give", + Layer::RedirectCheck => { + "the redirect breaks a redirect rule; request the final URL directly" + } + Layer::SecretBinding => { + "give the host a secret of this name for the origin of the request" + } + Layer::TransportAddress => { + "to reach an address in a refused range, add its exact IP address and port to the allow list" + } + Layer::ResponseCheck => "the server sent back the value of a host secret; the response is not used", + Layer::Method => "use a GET or HEAD request", + } +} + // ── Serializable error types ────────────────────────────────────────────────── /// A serializable representation of a source span. @@ -470,14 +504,38 @@ pub enum MdsError { help: Option, }, - /// Data entries need network access but have no replay value. + /// Data entries need network access but have no replay value, or a step compile + /// refused a request of a URL entry. #[error("network access denied for data entries: {entries}")] - #[diagnostic( - code(mds::network_denied), - help("provide a runtime value for each entry to replay it without network access") - )] + #[diagnostic(code(mds::network_denied))] #[non_exhaustive] - NetworkDenied { entries: String }, + NetworkDenied { + entries: String, + /// The replay help for entries with no replay value, else the fixed help of the + /// check that refused the request. + #[help] + detail: String, + }, + + /// A request of a network data entry failed in transport. The message names the + /// entry, the URL as declared and the origin, never the expanded URL. + #[error("network error in {message}")] + #[diagnostic(code(mds::network))] + #[non_exhaustive] + Network { message: String }, + + /// A step compile refused the input of its host: a fetch state that holds a response + /// that the compile did not request. The message is fixed text. + #[error("invalid options: {message}")] + #[diagnostic(code(mds::invalid_options))] + #[non_exhaustive] + InvalidOptions { message: String }, + + /// A data value has a type that its place in a request does not take. + #[error("type error in {message}")] + #[diagnostic(code(mds::type_error))] + #[non_exhaustive] + DataTypeError { message: String }, #[error("YAML parse error: {message}")] #[diagnostic(code(mds::yaml))] @@ -1038,6 +1096,83 @@ impl MdsError { .map(|&(module, entry)| data_location(module, Some(entry), None)) .collect::>() .join("; "), + detail: "provide a runtime value for each entry to replay it without network access" + .to_owned(), + } + } + + /// Construct a spanless transport failure of one URL entry. + /// Pass the project-relative module label, the entry name, the URL as declared (with + /// its `{{…}}` text) and the origin of the request. Never pass the expanded URL, a + /// header value or a body. Pass fixed prose as `kind`, for example + /// `request timed out`, never text that a host error or a server supplies. + pub fn network(module: &str, entry: &str, template: &str, origin: &str, kind: &str) -> Self { + Self::Network { + message: format!( + "{}: {kind}", + request_location(module, entry, template, origin) + ), + } + } + + /// Construct a spanless policy refusal of one URL entry: the location of the + /// request, the name of the check and its fixed reason, with the fixed help of the + /// check. Pass the other arguments as for [`MdsError::network`]. A sender that + /// refuses an address passes the refusal of [`crate::NetworkPolicy::check_address`]. + pub fn network_refused( + module: &str, + entry: &str, + template: &str, + origin: &str, + refusal: crate::Refusal, + ) -> Self { + Self::refused_request(module, entry, template, origin, refusal, None) + } + + /// [`MdsError::network_refused`] about the host secret `secret`: the message names + /// the secret, never its value. + pub(crate) fn refused_request( + module: &str, + entry: &str, + template: &str, + origin: &str, + refusal: crate::Refusal, + secret: Option<&str>, + ) -> Self { + let mut entries = format!( + "{}: {}: {}", + request_location(module, entry, template, origin), + refusal.layer().name(), + refusal.reason() + ); + if let Some(secret) = secret { + entries.push_str(" (secret \""); + entries.push_str(&sanitize_control_chars_wire(secret)); + entries.push_str("\")"); + } + Self::NetworkDenied { + entries, + detail: refusal_help(refusal.layer()).to_owned(), + } + } + + /// Construct a spanless refusal of the host input to a step compile. Pass fixed prose + /// as `reason`, never text that a host or a server supplies. + pub fn invalid_options(reason: &str) -> Self { + Self::InvalidOptions { + message: reason.to_owned(), + } + } + + /// Construct a spanless type error of a data value in a request field. + /// Pass the project-relative module label, the entry and the field. Pass diagnostic + /// prose as `reason`, never the value. + pub fn data_type_error(module: &str, entry: &str, field: &str, reason: &str) -> Self { + Self::DataTypeError { + message: format!( + "{}: {reason}", + data_location(module, Some(entry), Some(field)) + ), } } @@ -1059,6 +1194,18 @@ impl MdsError { )) } + /// The error of the response body total of one compile, 200 MiB of raw body bytes of + /// every status. [`crate::FetchState::with_response`] returns it for a body that takes + /// the state past the total. A host sender returns it for a body past the share of + /// [`crate::FetchState::body_bytes_left`] that the sender read it with. + #[cold] + #[inline(never)] + pub fn response_bodies_exceeded() -> Self { + Self::resource_limit(format!( + "response bodies exceed {MAX_RESPONSE_BODY_BYTES_PER_COMPILE} bytes per compile" + )) + } + /// A frontmatter parse expanded past its `MAX_OUTPUT_SIZE` byte allowance. #[cold] #[inline(never)] @@ -1246,6 +1393,9 @@ impl MdsError { | MdsError::ResourceLimit { .. } | MdsError::Data { .. } | MdsError::NetworkDenied { .. } + | MdsError::Network { .. } + | MdsError::InvalidOptions { .. } + | MdsError::DataTypeError { .. } | MdsError::YamlError { .. } | MdsError::JsonError { .. } | MdsError::InvalidVars { .. } @@ -1343,6 +1493,9 @@ impl MdsError { | MdsError::ResourceLimit { .. } | MdsError::Data { .. } | MdsError::NetworkDenied { .. } + | MdsError::Network { .. } + | MdsError::InvalidOptions { .. } + | MdsError::DataTypeError { .. } | MdsError::YamlError { .. } | MdsError::JsonError { .. } | MdsError::InvalidVars { .. } diff --git a/crates/mds-core/src/lib.rs b/crates/mds-core/src/lib.rs index 6b5aa79b..fa3dc778 100644 --- a/crates/mds-core/src/lib.rs +++ b/crates/mds-core/src/lib.rs @@ -65,6 +65,14 @@ pub(crate) mod vars_json; #[cfg(any(windows, test))] pub(crate) mod verbatim; +pub use data::policy::{ + AllowItem, Layer, NarrowError, NetworkPolicy, PolicyError, Refusal, Secret, SecretValue, +}; +pub use data::request::{ + HeaderValue, Method, Request, RequestHeader, RequestId, RequestIdError, RunKey, +}; +pub use data::step::{FetchContext, FetchState, RemoteInput, Response, Step, TransportFailure}; +pub use data::url::{CheckedUrl, Host, Origin, Scheme}; pub use formatter::{format_str, format_str_named, format_str_with}; pub use fs::{ check_module_bytes, effective_parent, read_at_most, reject_forbidden_path, EntryPin, @@ -181,6 +189,12 @@ pub struct CompileResult { /// `CompileOptions::source_map` is `true` (AC-API-02: absent, not null, when off). #[serde(skip_serializing_if = "Option::is_none")] pub source_map: Option, + /// The URL entries that a step compile bound, in bind order, in template form: the + /// module, the entry, the URL as declared and its origin, never an expanded URL. An + /// entry of two modules occurs once per module. Empty for a compile that is not a + /// step compile and for an entry that a runtime variable replays. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub remote_inputs: Vec, } impl CompileResult { @@ -225,17 +239,20 @@ impl CompileResult { /// carve-out — emitted verbatim, so their paths reach the consumer with whatever /// bytes the filesystem allowed. See [`CompileResult::dependencies`] and /// [`crate::SourceMap`]; consumers that display those paths must escape them. + /// `remoteInputs` (present only when not empty) is display text: each field of each + /// `{module, entry, template, origin}` item is WIRE-escaped. pub fn to_canonical_json(self) -> serde_json::Value { // Sanitize warnings at the serialization boundary (issue #176 / CWE-150): // warning strings may embed a hostile filename. WIRE mode — this value is // consumed as JSON by the bindings, so an embedded newline could forge an // extra warning line downstream. + let wire = |text: &str| { + serde_json::Value::String(crate::lint::sanitize_control_chars_wire(text).into_owned()) + }; let warnings: serde_json::Value = self .warnings - .into_iter() - .map(|w| { - serde_json::Value::String(crate::lint::sanitize_control_chars_wire(&w).into_owned()) - }) + .iter() + .map(|w| wire(w)) .collect::>() .into(); let dependencies: serde_json::Value = self @@ -248,20 +265,31 @@ impl CompileResult { let source_map_val: Option = self .source_map .map(|sm| serde_json::to_value(sm).unwrap_or(serde_json::Value::Null)); - - match self.output { - CompiledOutput::Markdown(text) => { - let mut obj = serde_json::json!({ - "kind": "markdown", - "output": text, - "warnings": warnings, - "dependencies": dependencies, - }); - if let Some(sm) = source_map_val { - obj["sourceMap"] = sm; - } - obj - } + // Remote inputs: absent when empty, so a compile that is not a step compile keeps + // its exact shape. + let remote_inputs: Option = + (!self.remote_inputs.is_empty()).then(|| { + self.remote_inputs + .iter() + .map(|input| { + serde_json::json!({ + "module": wire(&input.module), + "entry": wire(&input.entry), + "template": wire(&input.template), + "origin": wire(&input.origin), + }) + }) + .collect::>() + .into() + }); + + let mut obj = match self.output { + CompiledOutput::Markdown(text) => serde_json::json!({ + "kind": "markdown", + "output": text, + "warnings": warnings, + "dependencies": dependencies, + }), CompiledOutput::Messages(msgs) => { let messages: serde_json::Value = msgs .into_iter() @@ -273,18 +301,21 @@ impl CompileResult { }) .collect::>() .into(); - let mut obj = serde_json::json!({ + serde_json::json!({ "kind": "messages", "messages": messages, "warnings": warnings, "dependencies": dependencies, - }); - if let Some(sm) = source_map_val { - obj["sourceMap"] = sm; - } - obj + }) } + }; + if let Some(sm) = source_map_val { + obj["sourceMap"] = sm; + } + if let Some(inputs) = remote_inputs { + obj["remoteInputs"] = inputs; } + obj } } @@ -420,6 +451,33 @@ pub const MAX_DATA_BYTES: usize = limits::MAX_DATA_BYTES_PER_COMPILE; /// data graph check. pub const MAX_DATA_REFS_PER_ENTRY: usize = limits::MAX_DATA_REFS_PER_ENTRY; +/// Maximum distinct requests of one compile, redirect hops included: 64. +/// +/// The core counts them on each derive, so a host driver loop that sends what the core +/// asks for ends after at most this many rounds plus one. +pub const MAX_REQUESTS_PER_COMPILE: usize = limits::MAX_REQUESTS_PER_COMPILE; + +/// Maximum requests that one CLI run sends, over all of its compiles: 512. +pub const MAX_REQUESTS_PER_RUN: usize = limits::MAX_REQUESTS_PER_RUN; + +/// Maximum body bytes of one response that a fetcher reads: 10 MiB. +pub const MAX_RESPONSE_BYTES: u64 = limits::MAX_RESPONSE_BYTES; + +/// Maximum bytes of the status line and the headers of one response: 16 KiB. +pub const MAX_RESPONSE_HEADER_BYTES: usize = limits::MAX_RESPONSE_HEADER_BYTES; + +/// Maximum time of one request, from the name lookup to the end of the response read: 10 s. +pub const REQUEST_TIMEOUT: std::time::Duration = limits::REQUEST_TIMEOUT; + +/// Maximum time of the network work of one compile, over all of its rounds: 30 s. +pub const COMPILE_DEADLINE: std::time::Duration = limits::COMPILE_DEADLINE; + +/// Maximum requests in flight at one time in one compile: 8. +pub const MAX_PARALLEL_SENDS: usize = limits::MAX_PARALLEL_SENDS; + +/// Maximum addresses that a fetcher takes from one name lookup: 64. +pub const MAX_RESOLVED_ADDRS: usize = limits::MAX_RESOLVED_ADDRS; + /// Whether `path` names a local data file: it ends with `.json`, `.yaml` or `.yml`, /// compared byte for byte, so `a.JSON` is not a data path. /// @@ -808,6 +866,7 @@ pub fn compile_collecting_warnings( warnings, dependencies, source_map: None, + remote_inputs: Vec::new(), }) } @@ -843,6 +902,7 @@ fn compile_source_in_dir( warnings, dependencies, source_map: None, + remote_inputs: Vec::new(), }) } @@ -1465,6 +1525,7 @@ pub fn compile_virtual_collecting_warnings( warnings, dependencies, source_map: None, + remote_inputs: Vec::new(), }) } @@ -1594,10 +1655,54 @@ pub fn compile_native_fs( runtime_vars: Option>, opts: CompileOptions, ) -> Result { - let path = entry.as_ref(); + let mut cache = ModuleCache::compiling(Box::new(fs)); + compile_native_in(&mut cache, entry.as_ref(), runtime_vars, opts) +} + +/// One step compile of a native entry: a fresh compile with a fresh budget that derives +/// every request of its URL entries again, runs every check again and binds the +/// responses of `state`. See [`compile_step_virtual_fs`] for the host loop. +/// +/// # Errors +/// Returns the errors of [`compile_native_fs`], a refused request +/// (`mds::network_denied`), a failed or refused response (`mds::network`, +/// `mds::network_denied`, `mds::data`), and a state that holds a response that this +/// compile did not request (`mds::invalid_options`). +#[must_use = "a step either completes the compile or needs requests"] +pub fn compile_step_native_fs( + fs: NativeFs, + entry: impl AsRef, + runtime_vars: Option>, + opts: CompileOptions, + ctx: &FetchContext, + state: &FetchState, +) -> Result { + let mut cache = ModuleCache::stepping(Box::new(fs), ctx.start(state)); + let result = compile_native_in(&mut cache, entry.as_ref(), runtime_vars, opts)?; + finish_step(&mut cache, result) +} + +/// The step result of a compile in `cache` that gave `result`. +fn finish_step(cache: &mut ModuleCache, result: CompileResult) -> Result { + let pending = cache.has_pending_data(); + let step = cache.take_step().ok_or_else(MdsError::internal)?; + Ok(match step.finish(pending)? { + data::step::Outcome::Need(requests) => Step::Need(requests), + data::step::Outcome::Done(remote_inputs) => Step::Done(Box::new(CompileResult { + remote_inputs, + ..result + })), + }) +} + +fn compile_native_in( + cache: &mut ModuleCache, + path: &Path, + runtime_vars: Option>, + opts: CompileOptions, +) -> Result { let path_str = path_to_str(path)?; let vars = runtime_vars.unwrap_or_default(); - let mut cache = ModuleCache::compiling(Box::new(fs)); let mut warnings = vec![]; let (output, source_map) = cache.resolve_path_intrinsic_opts(path_str, &vars, &opts, &mut warnings)?; @@ -1615,6 +1720,7 @@ pub fn compile_native_fs( warnings, dependencies, source_map, + remote_inputs: Vec::new(), }) } @@ -1641,18 +1747,50 @@ pub fn compile_str_with_deps_opts( runtime_vars: Option>, opts: CompileOptions, ) -> Result { - let vars = runtime_vars.unwrap_or_default(); let dir = resolve_base_dir(base_dir)?; let mut cache = ModuleCache::compiling(Box::new(NativeFs::new())); + compile_str_in(&mut cache, source, &dir, runtime_vars, opts) +} + +/// One step compile of MDS source from a string, as [`compile_step_native_fs`] for a +/// file. `base_dir` is as for [`compile_str_with_deps_opts`]. +/// +/// # Errors +/// Returns the errors of [`compile_str_with_deps_opts`] and the step errors of +/// [`compile_step_native_fs`]. +#[must_use = "a step either completes the compile or needs requests"] +pub fn compile_step_str( + source: &str, + base_dir: Option<&Path>, + runtime_vars: Option>, + opts: CompileOptions, + ctx: &FetchContext, + state: &FetchState, +) -> Result { + let dir = resolve_base_dir(base_dir)?; + let mut cache = ModuleCache::stepping(Box::new(NativeFs::new()), ctx.start(state)); + let result = compile_str_in(&mut cache, source, &dir, runtime_vars, opts)?; + finish_step(&mut cache, result) +} + +fn compile_str_in( + cache: &mut ModuleCache, + source: &str, + dir: &str, + runtime_vars: Option>, + opts: CompileOptions, +) -> Result { + let vars = runtime_vars.unwrap_or_default(); let mut warnings = vec![]; let (output, source_map) = - cache.resolve_source_intrinsic_opts(source, &dir, &vars, &opts, &mut warnings)?; + cache.resolve_source_intrinsic_opts(source, dir, &vars, &opts, &mut warnings)?; let dependencies = native_dependencies(cache.dependencies()); Ok(CompileResult { output, warnings, dependencies, source_map, + remote_inputs: Vec::new(), }) } @@ -1711,8 +1849,73 @@ pub fn compile_virtual_fs( runtime_vars: Option>, opts: CompileOptions, ) -> Result { - let vars = runtime_vars.unwrap_or_default(); let mut cache = ModuleCache::compiling(Box::new(fs)); + compile_virtual_in(&mut cache, entry, runtime_vars, opts) +} + +/// One step compile of a module from a [`VirtualFs`], as [`compile_step_native_fs`] for +/// a native entry. +/// +/// Each call is a fresh compile. It derives every request of the URL entries again, +/// runs every check again, and binds the responses of `state`. A host loop sends each +/// request of [`Step::Need`], adds each response under its [`Request::id`], and calls +/// again until [`Step::Done`]. The loop needs at most one call per request and one more. +/// +/// # Examples +/// +/// ```rust +/// use std::collections::HashMap; +/// let modules = HashMap::from([( +/// "main.mds".to_string(), +/// "---\ndata:\n user: https://api.example/user\n---\nHi {{user.name}}!\n".to_string(), +/// )]); +/// let policy = mds::NetworkPolicy::new(vec![mds::AllowItem::parse("api.example")?])?; +/// let ctx = mds::FetchContext::new(policy, mds::RunKey::from_bytes([7; 32])); +/// let mut state = mds::FetchState::new(); +/// for _ in 0..=64 { +/// let fs = mds::VirtualFs::new(modules.clone()); +/// match mds::compile_step_virtual_fs(fs, "main.mds", None, Default::default(), &ctx, &state)? { +/// mds::Step::Need(requests) => { +/// for request in requests { +/// // A real host sends the request here. +/// let answer = mds::Response::http(200, Vec::new(), br#"{"name": "Ada"}"#.to_vec()); +/// state = state.with_response(request.id(), answer)?; +/// } +/// } +/// mds::Step::Done(result) => { +/// assert_eq!(result.into_markdown()?, "Hi Ada!\n"); +/// break; +/// } +/// _ => return Err("an unknown step".into()), +/// } +/// } +/// # Ok::<(), Box>(()) +/// ``` +/// +/// # Errors +/// Returns the errors of [`compile_virtual_fs`] and the step errors of +/// [`compile_step_native_fs`]. +#[must_use = "a step either completes the compile or needs requests"] +pub fn compile_step_virtual_fs( + fs: VirtualFs, + entry: &str, + runtime_vars: Option>, + opts: CompileOptions, + ctx: &FetchContext, + state: &FetchState, +) -> Result { + let mut cache = ModuleCache::stepping(Box::new(fs), ctx.start(state)); + let result = compile_virtual_in(&mut cache, entry, runtime_vars, opts)?; + finish_step(&mut cache, result) +} + +fn compile_virtual_in( + cache: &mut ModuleCache, + entry: &str, + runtime_vars: Option>, + opts: CompileOptions, +) -> Result { + let vars = runtime_vars.unwrap_or_default(); let mut warnings = vec![]; let (output, source_map) = cache.resolve_virtual_intrinsic_opts(entry, &vars, &opts, &mut warnings)?; @@ -1726,6 +1929,7 @@ pub fn compile_virtual_fs( warnings, dependencies, source_map, + remote_inputs: Vec::new(), }) } diff --git a/crates/mds-core/src/limits.rs b/crates/mds-core/src/limits.rs index 7d12ece2..c15e362a 100644 --- a/crates/mds-core/src/limits.rs +++ b/crates/mds-core/src/limits.rs @@ -1,3 +1,5 @@ +use std::time::Duration; + // ── Structural limits ───────────────────────────────────────────────────────── /// Maximum number of segments in a dot-separated path (e.g. `a.b.c` = 3 segments). @@ -310,3 +312,105 @@ pub(crate) const MAX_DATA_LEVELS: usize = 16; /// Large sparse files can reach this cap without reaching the node cap. /// Dense data can reach the compile memory budget before the byte aggregate. pub(crate) const MAX_DATA_BYTES_PER_COMPILE: usize = 32 * 1024 * 1024; + +// ── Network limits ──────────────────────────────────────────────────────────── + +/// Maximum distinct requests of one compile, redirect hops included: 64. +/// The unit is one request identity. The step engine counts the identities on each +/// derive, before it returns a request to the host, so a request past the cap is never +/// sent. In one compile this cap binds before `MAX_REQUESTS_PER_RUN`. It also bounds the +/// rounds of a compile to this cap plus one. +pub(crate) const MAX_REQUESTS_PER_COMPILE: usize = 64; + +/// Maximum requests that one CLI run sends, over all of its compiles: 512. +/// The unit is one sent request. The CLI driver counts each request before it sends it. +/// One compile reaches `MAX_REQUESTS_PER_COMPILE` first. A directory build of many +/// files can reach this cap. +pub(crate) const MAX_REQUESTS_PER_RUN: usize = 512; + +/// Maximum body bytes of one response: the data file cap, 10 MiB. +/// The unit is one body byte as received. The fetcher stops its read at one byte past +/// the cap, and the core checks the length again for every status, before it follows a +/// redirect or converts a body. A dense body can +/// reach the node cap or the compile memory budget first, as a data file can. +pub(crate) const MAX_RESPONSE_BYTES: u64 = MAX_DATA_FILE_BYTES; + +/// Maximum raw body bytes of all the responses of one compile: the compile memory budget, +/// 200 MiB. +/// The unit is one body byte as the host gives it, for every status: the body of a +/// redirect answer and of an error answer count too, though no entry converts them. +/// `FetchState::with_response` counts each body as the response enters the state, before +/// any step compile reads it. For the bodies that entries convert, +/// `MAX_DATA_BYTES_PER_COMPILE` binds first, in the next step compile. A host that sends +/// in parallel caps each read at its share of the bytes left (`FetchState::body_bytes_left`), +/// so a group of sends in flight can not pass this bound. +pub(crate) const MAX_RESPONSE_BODY_BYTES_PER_COMPILE: usize = MAX_COMPILE_MEMORY; + +/// Maximum bytes of the status line and the headers of one response: 16 KiB. +/// The fetcher counts them as it reads them, before the body. It binds before the body +/// cap, because the headers come first. +pub(crate) const MAX_RESPONSE_HEADER_BYTES: usize = 16 * 1024; + +/// Maximum redirect hops of one entry chain: 5. +/// The unit is one redirect response that the core follows. The core counts the hops of +/// the chain on each derive, before it returns the next hop request. Each hop is also a +/// request identity, so `MAX_REQUESTS_PER_COMPILE` can bind first when many entries +/// redirect. +pub(crate) const MAX_REDIRECTS: usize = 5; + +/// Maximum time of one request, from the name lookup to the end of the response read: 10 s. +/// The fetcher applies it to each request. `COMPILE_DEADLINE` binds first when less +/// time is left in the compile. +pub(crate) const REQUEST_TIMEOUT: Duration = Duration::from_secs(10); + +/// Maximum time of the network work of one compile, over all of its rounds: 30 s. +/// The host driver starts one deadline at the first send of the compile. It checks the +/// deadline before each send: with no time left, the request is not sent and fails with +/// the timeout. Each send waits at most the time that is left, so the deadline binds +/// before `REQUEST_TIMEOUT` when less time is left. +pub(crate) const COMPILE_DEADLINE: Duration = Duration::from_secs(30); + +/// Maximum requests in flight at one time in one compile: 8. +/// The host driver sends the requests of one round in groups of at most this many. It +/// bounds concurrency, not the request count. +pub(crate) const MAX_PARALLEL_SENDS: usize = 8; + +/// Maximum distinct secret names of one compile: 16. +/// The unit is one secret name. The core counts the names that the request headers +/// declare and the secret values that the host supplies, before it derives a request. +/// The reference cap of an entry does not count secrets. +pub(crate) const MAX_SECRETS: usize = 16; + +/// Maximum items of one network allow list: 64. +/// The unit is one origin item. The core counts the items as it parses the list, +/// before it matches a request against it, so the match work of each request is bounded. +pub(crate) const MAX_ALLOW_ITEMS: usize = 64; + +/// Maximum bytes of one URL: 8 KiB. +/// The unit is one URL byte. It applies to the expanded URL of an entry and to each +/// redirect `location`. Expansion checks it before each append, and the strict URL +/// parser checks it before any other rule. For a `location` value it binds before the +/// response header cap. +pub(crate) const MAX_URL_BYTES: usize = 8 * 1024; + +/// Maximum headers that one data entry declares for its request: 32. +/// The unit is one declared header. Declaration analysis counts the header map before it +/// keeps any header, so this cap binds before the value cap and before the reference +/// cap of the entry. The value is a choice of this release: it is above the header count +/// of usual API requests, and with `MAX_HEADER_VALUE_BYTES` it bounds the header text of +/// one request to 256 KiB. +pub(crate) const MAX_REQUEST_HEADERS: usize = 32; + +/// Maximum bytes of one request header value: 8 KiB. +/// The unit is one byte that the request sends as the value: the expanded text, or the +/// literal prefix and the secret value. Expansion checks it before each append, and the +/// step engine checks a secret header before it builds the request. The value is a +/// choice of this release: it is the header field limit of usual HTTP servers, so a +/// longer value fails at the server, and it equals `MAX_URL_BYTES`. +pub(crate) const MAX_HEADER_VALUE_BYTES: usize = 8 * 1024; + +/// Maximum addresses that the fetcher takes from one name lookup: 64. +/// The unit is one resolved address. The fetcher checks each address against the +/// address table before it connects. A lookup with more addresses fails the request, so +/// the check work of each request is bounded. +pub(crate) const MAX_RESOLVED_ADDRS: usize = 64; diff --git a/crates/mds-core/src/lint/facts.rs b/crates/mds-core/src/lint/facts.rs index f4745f0e..ffb4ad5c 100644 --- a/crates/mds-core/src/lint/facts.rs +++ b/crates/mds-core/src/lint/facts.rs @@ -109,6 +109,20 @@ pub enum FmVarKind { DataEntry, } +/// A URL data entry, as declared: the facts of the data rules. It holds no header +/// value. +#[derive(Debug, Clone)] +pub struct DataRequestFact { + /// The entry name. + pub name: String, + /// The URL as declared starts with `http://`. + pub plain_http: bool, + /// The names of the headers whose value is literal text, in declaration order. + pub literal_headers: Vec, + /// Approximate byte offset of the entry name in the source, as for [`FmVarFact`]. + pub approx_offset: Option, +} + /// A shadow variable pair: a name in an inner scope that shadows an outer-scope binding. #[derive(Debug, Clone)] pub struct ShadowPair { @@ -168,6 +182,9 @@ pub struct AnalysisContext { /// prompt, data), then the entry names of the `data` mapping. pub frontmatter_vars: Vec, + /// The URL entries of the `data` mapping, in declaration order. + pub data_requests: Vec, + // ── Usage tracking ──────────────────────────────────────────────────────── /// Variable names referenced in body expressions /// (`Expr::Var`, `Expr::MemberAccess::object`, `Arg::Var`, `Arg::MemberAccess::object`). @@ -359,16 +376,27 @@ fn collect_data_entries( return; }; for entry in entries { - if let crate::data::decl::Source::Url(paths) = &entry.source { - ctx.used_vars.extend(paths.iter().map(|path| { + let approx_offset = region.and_then(|(start, text)| { + find_data_entry_in_source(text, &entry.name).map(|offset| start + offset) + }); + if let crate::data::decl::Source::Url(template) = &entry.source { + ctx.used_vars.extend(template.refs.iter().map(|path| { path.split_once('.') .map_or(path.as_str(), |(root, _)| root) .to_owned() })); + ctx.data_requests.push(DataRequestFact { + name: entry.name.clone(), + plain_http: template.url.starts_with("http://"), + literal_headers: template + .headers + .iter() + .filter(|header| header.value.is_literal_text()) + .map(|header| header.name.clone()) + .collect(), + approx_offset, + }); } - let approx_offset = region.and_then(|(start, text)| { - find_data_entry_in_source(text, &entry.name).map(|offset| start + offset) - }); ctx.frontmatter_vars.push(FmVarFact { name: entry.name, kind: FmVarKind::DataEntry, diff --git a/crates/mds-core/src/lint/fix.rs b/crates/mds-core/src/lint/fix.rs index a70b1fb0..50744ede 100644 --- a/crates/mds-core/src/lint/fix.rs +++ b/crates/mds-core/src/lint/fix.rs @@ -8,7 +8,8 @@ //! | | empty-block, legacy-interpolation | | //! | B | unused-import, unused-function | Fixable only when structural-standalone (no imports/extends/partial; reverify applies) | //! | C | literal-directive, unused-variable, redundant-else, | Report-only; never fixed | -//! | | shadow-variable | | +//! | | shadow-variable, insecure-data-origin, | | +//! | | literal-credential-header | | //! //! **Tier B nuance:** //! - `unused-function` sets `fix_removals` to a whole-block [`FixLineSpan`] and is diff --git a/crates/mds-core/src/lint/mod.rs b/crates/mds-core/src/lint/mod.rs index 6f74e165..daff1d6b 100644 --- a/crates/mds-core/src/lint/mod.rs +++ b/crates/mds-core/src/lint/mod.rs @@ -2,7 +2,7 @@ //! //! The engine runs AFTER the check gate (resolve+validate) passes, confirming the //! template compiles correctly. It then independently tokenizes and parses the entry -//! source for a single-pass facts walk, applies the 11 lint rules as plain +//! source for a single-pass facts walk, applies the 13 lint rules as plain //! functions, and returns a `LintResult`. //! //! ## Pipeline (per file) @@ -69,7 +69,7 @@ pub(crate) fn is_partial_by_name(path: &str) -> bool { /// /// `source` is the raw entry source string (already used for the check gate). /// `filename` is the display name used in diagnostics and JSON grouping. -/// Returns `Ok(LintResult)` with diagnostics from all 11 rules. +/// Returns `Ok(LintResult)` with diagnostics from all 13 rules. pub(crate) fn lint_source( source: &str, filename: &str, @@ -104,7 +104,7 @@ pub(crate) fn lint_source( Ok(builder.build(is_standalone)) } -/// Apply all 11 lint rules over the module and facts context. +/// Apply all 13 lint rules over the module and facts context. /// /// Non-generic dispatch: each rule is a plain function call with no monomorphization. /// Rules are listed in the same order as the implementation steps (local-AST first, @@ -130,6 +130,8 @@ fn run_rules( rules::unused_import::check(module, ctx, filename, config, builder); rules::unused_function::check(module, ctx, filename, config, builder); rules::shadow_variable::check(module, ctx, filename, config, builder); + rules::insecure_data_origin::check(module, ctx, filename, config, builder); + rules::literal_credential_header::check(module, ctx, filename, config, builder); // Step 6 — token-based rules (require raw token stream) rules::legacy_interpolation::check(tokens, source, filename, config, builder); diff --git a/crates/mds-core/src/lint/rules/insecure_data_origin.rs b/crates/mds-core/src/lint/rules/insecure_data_origin.rs new file mode 100644 index 00000000..7eb19cf7 --- /dev/null +++ b/crates/mds-core/src/lint/rules/insecure_data_origin.rs @@ -0,0 +1,145 @@ +//! Rule: `insecure-data-origin` +//! +//! **Severity**: Warn (default) | **Tier**: C (never auto-fixed) +//! +//! A URL data entry (spec §4.12) requests an `http://` URL. Only a request map can name +//! the http scheme. The http scheme does not encrypt the request or the response, so +//! each network between the host and the server can read and change them. +//! +//! The rule reads the declarations only and never sends a request. It applies to +//! partials and `@extends` templates too, because their declarations are sent as +//! written. + +use crate::ast::Module; +use crate::error::SerializedSpan; +use crate::lint::config::LintConfig; +use crate::lint::diagnostic::{LintDiagnostic, LintResultBuilder, Severity}; +use crate::lint::facts::AnalysisContext; + +pub(crate) const RULE: &str = "insecure-data-origin"; + +/// Check the URL data entries for an `http://` URL. +pub(crate) fn check( + _module: &Module, + ctx: &AnalysisContext, + filename: &str, + config: &LintConfig, + builder: &mut LintResultBuilder, +) { + let severity = config.severity_for(RULE).copied().unwrap_or(Severity::Warn); + if severity == Severity::Off { + return; + } + for request in ctx + .data_requests + .iter() + .filter(|request| request.plain_http) + { + let pushed = builder.push(LintDiagnostic { + rule: RULE.to_string(), + severity, + message: format!("Data entry '{}' requests an http URL.", request.name), + help: Some( + "Use an https URL. The http scheme does not encrypt the request or the response." + .to_string(), + ), + span: request.approx_offset.map(|offset| SerializedSpan { + offset, + length: request.name.len(), + line: None, + column: None, + }), + file: Some(filename.to_string()), + fix_removals: None, + fix_edits: None, + }); + if !pushed { + return; + } + } +} + +// ── Unit tests ──────────────────────────────────────────────────────────────── + +#[cfg(test)] +mod tests { + use super::*; + use crate::lexer::tokenize; + use crate::lint::facts::collect_facts; + use crate::parser::parse_with_ctx; + + fn lint_src(src: &str) -> Vec { + let tokens = tokenize(src, "test.mds").unwrap(); + let module = parse_with_ctx(&tokens, "test.mds", src).unwrap(); + let ctx = collect_facts(&module, false, src).unwrap(); + let mut builder = LintResultBuilder::new(); + check( + &module, + &ctx, + "test.mds", + &LintConfig::default(), + &mut builder, + ); + builder.build(false).diagnostics + } + + fn with_data(data: &str) -> String { + format!("---\ndata:\n {data}\n---\n{{{{feed}}}}\n") + } + + /// TP-100: a request map with an http URL warns, in the flow form and in the block + /// form, with its span on the entry name. + #[test] + fn a_request_map_with_an_http_url_warns() { + for data in [ + "feed: {url: 'http://a.example/x'}", + "feed:\n url: http://a.example/x\n method: HEAD\n envelope: true", + ] { + let src = with_data(data); + let diagnostics = lint_src(&src); + let [diagnostic] = diagnostics.as_slice() else { + panic!("{data}: expected one diagnostic, got {diagnostics:?}"); + }; + assert_eq!(diagnostic.rule, RULE); + assert_eq!(diagnostic.severity, Severity::Warn); + assert_eq!( + diagnostic.message, + "Data entry 'feed' requests an http URL." + ); + let span = diagnostic.span.as_ref().expect("a span on the entry"); + assert_eq!(&src[span.offset..span.offset + span.length], "feed"); + } + } + + /// Control: an https URL in each form and a data file give no diagnostic. + #[test] + fn an_https_url_gives_no_diagnostic() { + for (data, requests) in [ + ("feed: https://a.example/x", 1), + ("feed: {url: 'https://a.example/x'}", 1), + ("feed: ./http.json", 0), + ] { + let src = with_data(data); + assert!(lint_src(&src).is_empty(), "{data}"); + // The declaration parses, so the empty result is not from a refused entry. + let tokens = tokenize(&src, "test.mds").unwrap(); + let module = parse_with_ctx(&tokens, "test.mds", &src).unwrap(); + let ctx = collect_facts(&module, false, &src).unwrap(); + assert_eq!(ctx.data_requests.len(), requests, "{data}"); + assert_eq!(ctx.frontmatter_vars.len(), 1, "{data}"); + } + } + + /// The rule can be turned off. + #[test] + fn the_rule_can_be_turned_off() { + let src = with_data("feed: {url: 'http://a.example/x'}"); + let tokens = tokenize(&src, "test.mds").unwrap(); + let module = parse_with_ctx(&tokens, "test.mds", &src).unwrap(); + let ctx = collect_facts(&module, false, &src).unwrap(); + let config = LintConfig::from_rules_checked([(RULE.to_string(), Severity::Off)].into()).0; + let mut builder = LintResultBuilder::new(); + check(&module, &ctx, "test.mds", &config, &mut builder); + assert!(builder.build(false).diagnostics.is_empty()); + } +} diff --git a/crates/mds-core/src/lint/rules/literal_credential_header.rs b/crates/mds-core/src/lint/rules/literal_credential_header.rs new file mode 100644 index 00000000..d756f14b --- /dev/null +++ b/crates/mds-core/src/lint/rules/literal_credential_header.rs @@ -0,0 +1,191 @@ +//! Rule: `literal-credential-header` +//! +//! **Severity**: Warn (default) | **Tier**: C (never auto-fixed) +//! +//! A URL data entry (spec §4.12) sets a header to literal text, and the lower-case +//! header name contains `token`, `secret`, `api-key`, `apikey` or `password`. The value +//! is then part of the template source. The secret form `{secret: NAME, prefix: ''}` lets the host +//! give the value for the origin of the request. +//! +//! A value with a `{{…}}` reference takes its text from a variable, so the rule does not +//! report it. The check gate refuses literal text for `Authorization`, +//! `Proxy-Authorization`, `Cookie` and `X-Api-Key`, which accept the secret form only. +//! +//! The rule reads the declarations only and never sends a request. Its message names +//! the entry and the header, never the value. It applies to partials and `@extends` +//! templates too, because their declarations are sent as written. + +use crate::ast::Module; +use crate::error::SerializedSpan; +use crate::lint::config::LintConfig; +use crate::lint::diagnostic::{LintDiagnostic, LintResultBuilder, Severity}; +use crate::lint::facts::AnalysisContext; + +pub(crate) const RULE: &str = "literal-credential-header"; + +/// The parts of a lower-case header name that mark a credential. +const CREDENTIAL_WORDS: [&str; 5] = ["token", "secret", "api-key", "apikey", "password"]; + +/// The header name `name` marks a credential, in any ASCII letter case. +fn names_a_credential(name: &str) -> bool { + let lower = name.to_ascii_lowercase(); + CREDENTIAL_WORDS.iter().any(|word| lower.contains(word)) +} + +/// Check the URL data entries for a credential header with a literal value. +pub(crate) fn check( + _module: &Module, + ctx: &AnalysisContext, + filename: &str, + config: &LintConfig, + builder: &mut LintResultBuilder, +) { + let severity = config.severity_for(RULE).copied().unwrap_or(Severity::Warn); + if severity == Severity::Off { + return; + } + for request in &ctx.data_requests { + for header in request + .literal_headers + .iter() + .filter(|header| names_a_credential(header)) + { + let pushed = builder.push(LintDiagnostic { + rule: RULE.to_string(), + severity, + message: format!( + "Data entry '{}' sets the credential header '{header}' to literal text.", + request.name + ), + help: Some( + "Use the secret form `{secret: NAME, prefix: ''}`, so that the host gives the value." + .to_string(), + ), + span: request.approx_offset.map(|offset| SerializedSpan { + offset, + length: request.name.len(), + line: None, + column: None, + }), + file: Some(filename.to_string()), + fix_removals: None, + fix_edits: None, + }); + if !pushed { + return; + } + } + } +} + +// ── Unit tests ──────────────────────────────────────────────────────────────── + +#[cfg(test)] +mod tests { + use super::*; + use crate::lexer::tokenize; + use crate::lint::facts::collect_facts; + use crate::parser::parse_with_ctx; + + fn lint_src(src: &str) -> Vec { + let tokens = tokenize(src, "test.mds").unwrap(); + let module = parse_with_ctx(&tokens, "test.mds", src).unwrap(); + let ctx = collect_facts(&module, false, src).unwrap(); + let mut builder = LintResultBuilder::new(); + check( + &module, + &ctx, + "test.mds", + &LintConfig::default(), + &mut builder, + ); + builder.build(false).diagnostics + } + + fn with_header(header: &str) -> String { + format!("---\ndata:\n api:\n url: https://a.example/x\n headers:\n {header}\n---\n{{{{api}}}}\n") + } + + /// TP-100: each credential word in a literal header name gives a warning that names + /// the entry and the header, never the value, with its span on the entry name. The + /// check for the value over every diagnostic comes first, and the messages are fixed + /// text or the header name, so a failure can not show the value. + #[test] + fn a_literal_credential_header_warns() { + for name in [ + "X-Auth-Token", + "Client-Secret", + "Api-Key", + "ApiKey", + "X-PASSWORD", + ] { + let src = with_header(&format!("{name}: planted-value")); + let diagnostics = lint_src(&src); + assert!( + !format!("{diagnostics:?}").contains("planted-value"), + "{name}: no diagnostic may show the header value" + ); + let [diagnostic] = diagnostics.as_slice() else { + panic!("{name}: expected one diagnostic, got {}", diagnostics.len()); + }; + assert_eq!(diagnostic.rule, RULE, "{name}: the rule"); + assert_eq!(diagnostic.severity, Severity::Warn, "{name}: the severity"); + assert_eq!( + diagnostic.message, + format!("Data entry 'api' sets the credential header '{name}' to literal text."), + "{name}: the message must name the entry and the header" + ); + let span = diagnostic.span.as_ref().expect("a span on the entry"); + // The source holds the value, so the span text is compared, not printed. + assert!( + src.get(span.offset..span.offset + span.length) == Some("api"), + "{name}: the span must cover the entry name" + ); + } + } + + /// Control: the secret form, a value with a reference and a header name with no + /// credential word give no diagnostic. A header line can hold the value, so the + /// messages name its index. + #[test] + fn the_secret_form_and_other_headers_give_no_diagnostic() { + for (index, header) in [ + "X-Auth-Token: {secret: TOKEN, prefix: ''}", + "X-Auth-Token: {secret: TOKEN, prefix: 'Bearer '}", + "X-Auth-Token: 'Bearer {{key}}'", + "X-Trace: planted-value", + ] + .into_iter() + .enumerate() + { + let src = with_header(header).replace("---\n{{api}}", "key: k\n---\n{{api}}"); + // The declaration parses, so the empty result is not from a refused entry. + let tokens = tokenize(&src, "test.mds").unwrap(); + let module = parse_with_ctx(&tokens, "test.mds", &src).unwrap(); + let ctx = collect_facts(&module, false, &src).unwrap(); + assert_eq!( + ctx.data_requests.len(), + 1, + "header {index}: the entry must parse" + ); + assert!(lint_src(&src).is_empty(), "header {index}: no diagnostic"); + } + } + + /// The severity can be raised or turned off. + #[test] + fn the_severity_follows_the_config() { + let src = with_header("X-Auth-Token: planted-value"); + let tokens = tokenize(&src, "test.mds").unwrap(); + let module = parse_with_ctx(&tokens, "test.mds", &src).unwrap(); + let ctx = collect_facts(&module, false, &src).unwrap(); + for (severity, count) in [(Severity::Error, 1), (Severity::Off, 0)] { + let config = LintConfig::from_rules_checked([(RULE.to_string(), severity)].into()).0; + let mut builder = LintResultBuilder::new(); + check(&module, &ctx, "test.mds", &config, &mut builder); + let diagnostics = builder.build(false).diagnostics; + assert_eq!(diagnostics.len(), count, "{severity:?}"); + assert!(diagnostics.iter().all(|d| d.severity == severity)); + } + } +} diff --git a/crates/mds-core/src/lint/rules/mod.rs b/crates/mds-core/src/lint/rules/mod.rs index 2d1b94e8..5eb6bae9 100644 --- a/crates/mds-core/src/lint/rules/mod.rs +++ b/crates/mds-core/src/lint/rules/mod.rs @@ -18,11 +18,15 @@ //! | `shadow-variable` | Info | C | Inner scope name hides outer binding | //! | `legacy-interpolation` | Warn | A | Single-brace `{x}` syntax (migrates to `{{x}}`) | //! | `literal-directive` | Warn | C | Conditional line stays literal text | +//! | `insecure-data-origin` | Warn | C | Request map URL with the http scheme | +//! | `literal-credential-header` | Warn | C | Credential header set to literal text | pub(crate) mod duplicate_export; pub(crate) mod duplicate_import; pub(crate) mod empty_block; +pub(crate) mod insecure_data_origin; pub(crate) mod legacy_interpolation; +pub(crate) mod literal_credential_header; pub(crate) mod literal_directive; pub(crate) mod redundant_else; pub(crate) mod shadow_variable; @@ -39,12 +43,14 @@ pub(crate) mod structural_eq; /// is the single source of truth. This does NOT close the *omission* risk — a /// new module whose `RULE` is never listed here compiles fine. The mechanical /// closure is the bidirectional tier table in `tier.rs` plus an explicit -/// `ALL_RULE_NAMES.len() == 11` pin in that table's test. +/// `ALL_RULE_NAMES.len() == 13` pin in that table's test. pub(crate) const ALL_RULE_NAMES: &[&str] = &[ duplicate_export::RULE, duplicate_import::RULE, empty_block::RULE, + insecure_data_origin::RULE, legacy_interpolation::RULE, + literal_credential_header::RULE, literal_directive::RULE, redundant_else::RULE, shadow_variable::RULE, diff --git a/crates/mds-core/src/lint/tier.rs b/crates/mds-core/src/lint/tier.rs index 1a69f7a1..3284d539 100644 --- a/crates/mds-core/src/lint/tier.rs +++ b/crates/mds-core/src/lint/tier.rs @@ -11,7 +11,8 @@ //! | | empty-block, legacy-interpolation | | //! | B | unused-import, unused-function | Fixable only when structural-standalone | //! | C | literal-directive, unused-variable, redundant-else, | Never fixed | -//! | | shadow-variable | | +//! | | shadow-variable, insecure-data-origin, | | +//! | | literal-credential-header | | //! //! This table restates `rule_tier`, which is the authoritative source; `legacy-interpolation` //! is the one Tier A rule whose fix is not output-neutral (see `is_output_neutral`). @@ -47,7 +48,7 @@ pub fn rule_tier(rule: &str) -> FixTier { | "empty-block" | "legacy-interpolation" => FixTier::A, "unused-import" | "unused-function" => FixTier::B, - _ => FixTier::C, // literal-directive, unused-variable, redundant-else, shadow-variable, unknown + _ => FixTier::C, // the report-only rules and unknown names } } @@ -120,7 +121,7 @@ mod tests { /// Canonical expected-tier table: (rule_name, expected_FixTier). /// Must be updated whenever a rule is added, removed, or re-tiered. - /// Pin: len must equal ALL_RULE_NAMES.len() (11 as of this release). + /// Pin: len must equal ALL_RULE_NAMES.len() (13 as of this release). const EXPECTED: &[(&str, FixTier)] = &[ // Tier A — auto-fixable with reverify gate ("duplicate-export", FixTier::A), @@ -132,6 +133,8 @@ mod tests { ("unused-function", FixTier::B), ("unused-import", FixTier::B), // Tier C — report-only, never fixed + ("insecure-data-origin", FixTier::C), + ("literal-credential-header", FixTier::C), ("literal-directive", FixTier::C), ("redundant-else", FixTier::C), ("shadow-variable", FixTier::C), @@ -141,18 +144,18 @@ mod tests { // Length pin: update this when a new rule ships. assert_eq!( EXPECTED.len(), - 11, - "EXPECTED table length must equal the number of registered rules (11)" + 13, + "EXPECTED table length must equal the number of registered rules (13)" ); assert_eq!( ALL_RULE_NAMES.len(), - 11, - "ALL_RULE_NAMES length must equal the number of registered rules (11)" + 13, + "ALL_RULE_NAMES length must equal the number of registered rules (13)" ); assert_eq!( KNOWN_LINT_RULES.len(), - 11, - "KNOWN_LINT_RULES length must equal the number of registered rules (11)" + 13, + "KNOWN_LINT_RULES length must equal the number of registered rules (13)" ); // Direction 1: every registry entry has a correct entry in EXPECTED. @@ -204,6 +207,8 @@ mod tests { "unused-variable", "redundant-else", "shadow-variable", + "insecure-data-origin", + "literal-credential-header", ] { assert!(is_output_neutral(rule), "{rule} should be output-neutral"); } @@ -235,7 +240,7 @@ mod tests { /// token that names a registered rule together with the tier of its row /// (a continuation row with a blank tier column inherits the tier of the row /// above), and asserts the extracted map agrees with `rule_tier` in both - /// directions for all 11 rules. + /// directions for all 13 rules. #[test] fn module_doc_tier_table_matches_rule_tier() { use super::super::rules::ALL_RULE_NAMES; diff --git a/crates/mds-core/src/resolver.rs b/crates/mds-core/src/resolver.rs index e94e7edc..cd886e31 100644 --- a/crates/mds-core/src/resolver.rs +++ b/crates/mds-core/src/resolver.rs @@ -268,6 +268,19 @@ impl ModuleCache { cache } + /// A compile that derives the requests of its URL entries and binds the responses of + /// `ctx`. It is the only role with a step context: the tooling roles take none. + pub(crate) fn stepping(fs: Box, ctx: crate::data::step::StepCtx) -> Self { + let mut cache = Self::compiling(fs); + cache.data.net = Some(ctx); + cache + } + + /// Take the step context back after a step compile. + pub(crate) fn take_step(&mut self) -> Option { + self.data.net.take() + } + /// The check gate can validate without returning a rendered artifact. pub(crate) fn tooling(fs: Box) -> Self { let mut cache = Self::with_fs(fs); diff --git a/crates/mds-core/src/resolver/frontmatter_tests.rs b/crates/mds-core/src/resolver/frontmatter_tests.rs index bb71b161..2a9d969c 100644 --- a/crates/mds-core/src/resolver/frontmatter_tests.rs +++ b/crates/mds-core/src/resolver/frontmatter_tests.rs @@ -12,7 +12,7 @@ const DATA_LABEL: crate::data::DataLabel<'static> = crate::data::DataLabel { module: "test.mds", entry: "item", - file: Some("item.yml"), + input: crate::data::DataInput::File("item.yml"), }; use super::{ diff --git a/crates/mds-core/src/resolver/module_scope.rs b/crates/mds-core/src/resolver/module_scope.rs index 1853d122..d30d929e 100644 --- a/crates/mds-core/src/resolver/module_scope.rs +++ b/crates/mds-core/src/resolver/module_scope.rs @@ -7,7 +7,7 @@ use super::{ MemBudget, Module, ModuleCache, ModuleCtx, Node, Part, Scope, Value, VarLayer, INDENTED_DIRECTIVES, MAX_BLOCKS_PER_MODULE, MAX_DEFINES_PER_MODULE, }; -use crate::data::{decl::Source, resolve, DataLabel}; +use crate::data::{decl::Source, resolve, step, DataLabel}; /// Return `true` when the AST body contains at least one `@message` block /// (possibly nested inside `@if` or `@for` — a shallow scan is enough for the @@ -311,6 +311,8 @@ impl ModuleCache { let fs = &*self.fs; let data = &mut self.data; let analyze_data = self.analyze_data; + // The module that the compile starts from: only its entries can send a secret. + let entry_key = self.resolving.first().map(String::as_str); let result = resolve::Declarations::with_graph( chain, resolve::FrontmatterNames::Parsed { mapping, is_md }, @@ -319,8 +321,16 @@ impl ModuleCache { |count, graph, mem| { count_data_entries(&mut data.entries, count)?; // The role check reads these names, so a replayed entry keeps its source. + // Replay does not lift the secret header rule, so check every URL entry. let mut names = HashSet::new(); for node in graph.nodes() { + if let Source::Url(template) = &node.entry.source { + step::check_secret_module( + node, + template, + Some(node.position.0) == entry_key, + )?; + } let name = &node.entry.name; mem.charge( Part::Buffers, @@ -346,17 +356,46 @@ impl ModuleCache { } return Ok((names, pending)); } - if graph.frontier().next().is_some() { + // Only a step compile has a context for its URL entries. + if graph.frontier().next().is_some() && data.net.is_none() { return Err(MdsError::internal()); } - for node in graph.unreplayed() { - let Source::File(written) = &node.entry.source else { - return Err(MdsError::internal()); + for node in graph.in_level_order() { + let written = match &node.entry.source { + Source::File(written) => written, + Source::Url(template) => { + let ctx = data.net.as_mut().ok_or_else(MdsError::internal)?; + let scope = step::EntryScope { + runtime, + vars, + pending: &pending, + entry_module: Some(node.position.0) == entry_key, + }; + let bound = + step::bind_url_entry(node, template, &scope, ctx, mem, |len| { + count_data_bytes(&mut data.bytes, len) + })?; + let name = &node.entry.name; + match bound { + step::Bound::Value(value) => { + bind_entry(name, value, vars, mem)?; + } + step::Bound::Pending => { + mem.charge( + Part::Buffers, + name.len().checked_add(2 * size_of::()), + )?; + pending.insert(name.clone()); + data.pending = true; + } + } + continue; + } }; let label = DataLabel { module: node.module, entry: &node.entry.name, - file: None, + input: crate::data::DataInput::Declaration, }; let (key, accept) = resolve::canonical_file(fs, node.dir, written, label)?; let value = if let Some(value) = data.files.get(&key) { @@ -372,13 +411,7 @@ impl ModuleCache { data.files.insert(key, Arc::clone(&value)); value }; - let binding_bytes = node - .entry - .name - .len() - .checked_add(2 * size_of::<(String, crate::scope::Slot)>()); - mem.charge(Part::Buffers, binding_bytes)?; - vars.insert(node.entry.name.clone(), value); + bind_entry(&node.entry.name, value, vars, mem)?; } Ok((names, pending)) }, @@ -388,6 +421,21 @@ impl ModuleCache { } } +/// Bind the value of the entry `name` into the module variables. +fn bind_entry( + name: &str, + value: Arc, + vars: &mut VarLayer, + mem: &mut MemBudget, +) -> Result<(), MdsError> { + let binding_bytes = name + .len() + .checked_add(2 * size_of::<(String, crate::scope::Slot)>()); + mem.charge(Part::Buffers, binding_bytes)?; + vars.insert(name.to_owned(), value); + Ok(()) +} + fn data_memo_bytes(key: usize) -> Option { key.checked_add(2 * size_of::<(String, Arc, usize)>())? .checked_add(2 * size_of::()) diff --git a/crates/mds-core/src/resolver/process.rs b/crates/mds-core/src/resolver/process.rs index 32488c46..c7d8a942 100644 --- a/crates/mds-core/src/resolver/process.rs +++ b/crates/mds-core/src/resolver/process.rs @@ -450,8 +450,10 @@ impl ModuleCache { } }; if self.data.compile { + // A step compile binds its URL entries from the step context, so only a + // compile without one refuses a frontier. let frontier: Vec<_> = preflight.frontier().collect(); - if !frontier.is_empty() { + if !frontier.is_empty() && self.data.net.is_none() { self.budget.mem.release_buffers(preflight.snapshot.charge); return Err(MdsError::network_denied(&frontier)); } diff --git a/crates/mds-core/src/scope.rs b/crates/mds-core/src/scope.rs index 377a302c..2b6d59d3 100644 --- a/crates/mds-core/src/scope.rs +++ b/crates/mds-core/src/scope.rs @@ -249,6 +249,11 @@ impl VarLayer { self.0.get(name) } + /// The value of the variable `name`, if the layer holds one. + pub(crate) fn value(&self, name: &str) -> Option<&Value> { + self.get(name).and_then(Slot::get) + } + fn len(&self) -> usize { self.0.len() } diff --git a/crates/mds-core/tests/api_surface.rs b/crates/mds-core/tests/api_surface.rs index 8e213a12..bacef42e 100644 --- a/crates/mds-core/tests/api_surface.rs +++ b/crates/mds-core/tests/api_surface.rs @@ -455,6 +455,9 @@ fn mds_error_variants_exist() { | MdsError::ResourceLimit { .. } | MdsError::Data { .. } | MdsError::NetworkDenied { .. } + | MdsError::Network { .. } + | MdsError::InvalidOptions { .. } + | MdsError::DataTypeError { .. } | MdsError::DataFileNotFound { .. } | MdsError::YamlError { .. } | MdsError::JsonError { .. } @@ -489,6 +492,21 @@ fn data_error_variants_have_named_constructors() { type DataFn = fn(&str, Option<&str>, Option<&str>, &str, Option) -> MdsError; let _: DataFn = MdsError::data; let _: fn(&[(&str, &str)]) -> MdsError = MdsError::network_denied; + let _: fn(&str, &str, &str, &str, mds::Refusal) -> MdsError = MdsError::network_refused; + let network: fn(&str, &str, &str, &str, &str) -> MdsError = MdsError::network; + let err = network( + "main.mds", + "users", + "https://a.example/", + "https://a.example", + "x", + ); + assert!(matches!(err, MdsError::Network { .. }), "{err:?}"); + let invalid: fn(&str) -> MdsError = MdsError::invalid_options; + assert!(matches!(invalid("x"), MdsError::InvalidOptions { .. })); + let type_error: fn(&str, &str, &str, &str) -> MdsError = MdsError::data_type_error; + let err = type_error("main.mds", "users", "url", "x"); + assert!(matches!(err, MdsError::DataTypeError { .. }), "{err:?}"); } #[test] @@ -641,6 +659,14 @@ fn constants_have_expected_values() { assert_eq!(mds::MAX_DATA_FILES, 256); assert_eq!(mds::MAX_DATA_BYTES, 32 * 1024 * 1024); assert_eq!(mds::MAX_DATA_REFS_PER_ENTRY, 256); + assert_eq!(mds::MAX_REQUESTS_PER_COMPILE, 64); + assert_eq!(mds::MAX_REQUESTS_PER_RUN, 512); + assert_eq!(mds::MAX_RESPONSE_BYTES, MAX_FILE_SIZE); + assert_eq!(mds::MAX_RESPONSE_HEADER_BYTES, 16 * 1024); + assert_eq!(mds::REQUEST_TIMEOUT, std::time::Duration::from_secs(10)); + assert_eq!(mds::COMPILE_DEADLINE, std::time::Duration::from_secs(30)); + assert_eq!(mds::MAX_PARALLEL_SENDS, 8); + assert_eq!(mds::MAX_RESOLVED_ADDRS, 64); const _: () = assert!(MAX_TRAVERSAL_DEPTH > 0); const _: () = assert!(MAX_TRAVERSAL_DEPTH <= 1000); } @@ -2314,7 +2340,7 @@ fn lint_types_exist() { /// AC-224-7 / AC-224-8: KNOWN_LINT_RULES and UnknownRuleNames honour ADR-010. /// /// - `KNOWN_LINT_RULES` is publicly reachable from an external crate. -/// - It contains exactly the eleven registered rule names. +/// - It contains exactly the thirteen registered rule names. /// - Every entry in the registry is accepted by `LintConfig::from_rules_checked` without /// unknowns. /// - `find_unknown_rule_names` returns `None` for all-known maps and `Some` for @@ -2325,11 +2351,11 @@ fn lint_types_exist() { fn known_lint_rules_and_unknown_detection() { use mds::{find_unknown_rule_names, KNOWN_LINT_RULES}; - // AC-224-7: exactly 11 rules. + // AC-224-7: exactly 13 rules. assert_eq!( KNOWN_LINT_RULES.len(), - 11, - "KNOWN_LINT_RULES must have exactly 11 entries" + 13, + "KNOWN_LINT_RULES must have exactly 13 entries" ); // AC-224-7: exact sorted contents. @@ -2337,7 +2363,9 @@ fn known_lint_rules_and_unknown_detection() { "duplicate-export", "duplicate-import", "empty-block", + "insecure-data-origin", "legacy-interpolation", + "literal-credential-header", "literal-directive", "redundant-else", "shadow-variable", @@ -2945,3 +2973,187 @@ fn text_edit_and_fix_edits_public_api() { assert_eq!(arr[0]["end"], 12); assert_eq!(arr[0]["new_text"], "{{name}}"); } + +/// #405: the network policy is reachable from the crate root and built through its +/// named constructors. A secret value is absent from `Debug`, the refusals are fixed +/// text, and a match on `Layer` or `Scheme` needs a wildcard arm, as a new kind may be +/// added. +#[test] +fn network_policy_api_exists() { + let local = mds::AllowItem::parse("http://127.0.0.1:8080").unwrap(); + let origin: mds::Origin = mds::AllowItem::parse("api.example").unwrap().origin(); + assert_eq!( + (origin.scheme().as_str(), origin.port(), origin.to_string()), + ("https", 443, "https://api.example".to_owned()) + ); + assert!(matches!(origin.host(), mds::Host::Name(name) if name == "api.example")); + let value = mds::SecretValue::new("planted-value".into()).unwrap(); + assert_eq!(value.expose_for_send(), "planted-value"); + let secret = mds::Secret::new("token", value, origin).unwrap(); + let policy = mds::NetworkPolicy::new(vec![local.clone()]) + .unwrap() + .with_imports(true) + .with_secret(secret) + .unwrap(); + assert!(!format!("{policy:?}").contains("planted-value")); + + let narrowed = policy.narrow(vec![local.clone()], false).unwrap(); + assert!(narrowed + .check_address("127.0.0.1:8080".parse().unwrap()) + .is_ok()); + let refusal: mds::Refusal = narrowed + .check_address("10.0.0.1:443".parse().unwrap()) + .unwrap_err(); + assert_eq!(refusal.reason(), "the address is in a refused range"); + match refusal.layer() { + mds::Layer::TransportAddress => {} + other => panic!("unexpected layer {}", other.name()), + } + let error: mds::NarrowError = narrowed.narrow(vec![local], true).unwrap_err(); + assert_eq!(error, mds::NarrowError::ImportsNotAllowed); + let error: mds::PolicyError = mds::NetworkPolicy::new(Vec::new()).unwrap_err(); + let error: &dyn std::error::Error = &error; + assert_eq!(error.to_string(), "an allow list needs at least one item"); +} + +/// #405: the request types are reachable from the crate root. The core builds each +/// `Request`, so its accessors are pinned by type here; `RequestId` has a strict hex +/// form, and `RunKey` hides its bytes from `Debug`. +#[test] +fn request_identity_api_exists() { + fn accessors(request: &mds::Request) -> (mds::RequestId, mds::Method, String) { + let url: &mds::CheckedUrl = request.url(); + let _: &str = request.template(); + let _: (mds::Origin, &str, Option<&str>) = (url.origin(), url.path(), url.query()); + for header in request.headers() { + let _: &str = header.name(); + match header.value() { + mds::HeaderValue::Text(_) | mds::HeaderValue::Secret { .. } => {} + _ => {} + } + } + (request.id(), request.method(), url.to_text()) + } + let _ = accessors; + + assert!(!format!("{:?}", mds::RunKey::from_bytes([7; 32])).contains('7')); + match mds::Method::Head { + mds::Method::Get => panic!("unexpected method"), + other => assert_eq!(other.as_str(), "HEAD"), + } + let text = "0123456789abcdef".repeat(4); + let id = mds::RequestId::parse_hex(&text).unwrap(); + assert_eq!(id.as_hex(), text); + let error: mds::RequestIdError = mds::RequestId::parse_hex("remote").unwrap_err(); + let error: &dyn std::error::Error = &error; + assert_eq!( + error.to_string(), + "a request ID is 64 lower-case hex digits" + ); +} + +/// #405: the step API is reachable from the crate root. Each step function takes the +/// options of its compile function plus the context and the state; a match on `Step`, +/// `Response` or `TransportFailure` needs a wildcard arm, as a new kind may be added. +#[test] +fn step_api_exists() { + type Vars = Option>; + type Ctx<'a> = &'a mds::FetchContext; + type State<'a> = &'a mds::FetchState; + type Stepped = Result; + type VirtualStep = fn(mds::VirtualFs, &str, Vars, mds::CompileOptions, Ctx, State) -> Stepped; + type StrStep = + fn(&str, Option<&std::path::Path>, Vars, mds::CompileOptions, Ctx, State) -> Stepped; + let native = |fs: mds::NativeFs, + entry: &std::path::Path, + vars: Vars, + opts, + ctx: Ctx, + state: State| + -> Stepped { mds::compile_step_native_fs(fs, entry, vars, opts, ctx, state) }; + let _ = native; + let _: VirtualStep = mds::compile_step_virtual_fs; + let _: StrStep = mds::compile_step_str; + + let policy = + mds::NetworkPolicy::new(vec![mds::AllowItem::parse("a.example").unwrap()]).unwrap(); + let ctx = mds::FetchContext::new(policy, mds::RunKey::from_bytes([7; 32])); + let _: &mds::NetworkPolicy = ctx.policy(); + let state = mds::FetchState::new(); + assert!(state.is_empty()); + let id = mds::RequestId::parse_hex(&"ab".repeat(32)).unwrap(); + let answer = mds::Response::http( + 200, + vec![("x-a".into(), b"marker".to_vec())], + b"marker".to_vec(), + ); + let state = state.with_response(id, answer).unwrap(); + assert_eq!(state.len(), 1); + assert!(!format!("{state:?}").contains("marker")); + // The raw bodies of one compile share one 200 MiB total; a host caps its reads with + // the bytes left, and a read past its share gives the error of the total. + let left: fn(&mds::FetchState) -> usize = mds::FetchState::body_bytes_left; + assert_eq!(left(&state), 200 * 1024 * 1024 - "marker".len()); + let over: fn() -> MdsError = MdsError::response_bodies_exceeded; + let err = over(); + assert!(matches!(err, MdsError::ResourceLimit { .. }), "{err:?}"); + assert_eq!( + err.to_string(), + "resource limit exceeded: response bodies exceed 209715200 bytes per compile" + ); + assert_eq!( + format!( + "{:?}", + mds::Response::failed(mds::TransportFailure::Timeout) + ), + "Failed(Timeout)" + ); + assert_ne!( + mds::TransportFailure::AddressRefused, + mds::TransportFailure::Timeout + ); + + let fs = mds::VirtualFs::new(HashMap::from([( + "main.mds".to_string(), + "Hi!\n".to_string(), + )])); + let step = mds::compile_step_virtual_fs( + fs, + "main.mds", + None, + mds::CompileOptions::default(), + &ctx, + &mds::FetchState::new(), + ) + .unwrap(); + let result: mds::CompileResult = match step { + mds::Step::Done(result) => *result, + mds::Step::Need(_) => panic!("expected a finished compile"), + _ => panic!("unexpected step"), + }; + let _: &[mds::RemoteInput] = &result.remote_inputs; + for input in &result.remote_inputs { + let _: (&str, &str, &str, &str) = + (&input.module, &input.entry, &input.template, &input.origin); + } +} + +/// #405: a host sender binds a secret header through the policy again before it writes +/// the header. A secret binds only for its own name and the one origin of the secret. +#[test] +fn secret_binding_api_exists() { + let item = mds::AllowItem::parse("api.example").unwrap(); + let origin = item.origin(); + let other = mds::AllowItem::parse("other.example").unwrap().origin(); + let value = mds::SecretValue::new("planted-value".into()).unwrap(); + let policy = mds::NetworkPolicy::new(vec![item]) + .unwrap() + .with_secret(mds::Secret::new("token", value, origin.clone()).unwrap()) + .unwrap(); + let bound: &mds::SecretValue = policy.bind_secret("token", &origin).unwrap(); + assert_eq!(bound.expose_for_send(), "planted-value"); + for (name, at) in [("token", &other), ("missing", &origin)] { + let refusal: mds::Refusal = policy.bind_secret(name, at).unwrap_err(); + assert_eq!(refusal.layer(), mds::Layer::SecretBinding, "{name}"); + } +} diff --git a/crates/mds-core/tests/data_limits.rs b/crates/mds-core/tests/data_limits.rs index 9a6561b0..bc64b754 100644 --- a/crates/mds-core/tests/data_limits.rs +++ b/crates/mds-core/tests/data_limits.rs @@ -197,7 +197,7 @@ fn reference_cap_counts_the_fields_of_one_entry_and_binds_before_the_graph_check let entry = |name: &str, extra: &str| { let body = "{{k}}".repeat(REFS_PER_ENTRY - 2) + extra; format!( - " {name}:\n url: 'https://example.com/{{{{k}}}}'\n headers:\n X-Key: '{{{{k}}}}'\n body:\n text: '{body}'\n" + " {name}:\n url: 'https://example.com/{{{{k}}}}'\n method: POST\n headers:\n X-Key: '{{{{k}}}}'\n body:\n text: '{body}'\n" ) }; let files = |extra: &str| { diff --git a/crates/mds-core/tests/data_resolve.rs b/crates/mds-core/tests/data_resolve.rs index 366a4300..b3ce817c 100644 --- a/crates/mds-core/tests/data_resolve.rs +++ b/crates/mds-core/tests/data_resolve.rs @@ -167,6 +167,65 @@ fn static_url_checks_run_before_replay_and_unreplayed_urls_are_denied() { } } +/// The request rules of a declaration hold when replay satisfies the entry. Control: +/// the same map with only the fault removed renders the replayed value. +#[test] +fn request_map_rules_run_before_replay() { + let compile_map = |fields: &str| { + let source = format!("---\ndata:\n remote: {{{fields}}}\n---\n{{{{remote}}}}\n"); + compile(&[("main.mds", &source)], replay("remote")) + }; + for (fault, control) in [ + ( + "url: 'https://127.1/path'", + "url: 'https://127.0.0.1:8080/path'", + ), + ( + "url: 'https://example.com/', method: HEAD", + "url: 'https://example.com/', method: HEAD, envelope: true", + ), + ( + "url: 'https://example.com/', body: {a: b}", + "url: 'https://example.com/', method: POST, body: {a: b}", + ), + ( + "url: 'https://example.com/', headers: {Cookie: 'a=b'}", + "url: 'https://example.com/', headers: {Cookie: {secret: session, prefix: 'a='}}", + ), + ] { + let err = compile_map(fault).unwrap_err(); + assert!(matches!(err, MdsError::Data { .. }), "{fault}: {err}"); + assert!( + rendered(compile_map(control)).ends_with("replayed\n"), + "{control}" + ); + } + assert!(rendered(compile_map("url: 'http://example.com/path'")).ends_with("replayed\n")); +} + +/// Replay does not lift the secret header rule in a plain compile: a replayed URL entry +/// with a secret header fails in an imported module and in an `@extends` base. Control: +/// the same replayed entry in the entry module renders the replayed value. +#[test] +fn a_replayed_secret_header_is_allowed_in_the_entry_module_only() { + let module = "---\ndata:\n remote: {url: 'https://example.com/', headers: {Authorization: {secret: token, prefix: 'Bearer '}}}\n---\n{{remote}}\n"; + for main in [ + "@import \"./part.mds\" as part\n@include part\n", + "@extends \"./part.mds\"\n", + ] { + let files = [("main.mds", main), ("part.mds", module)]; + let err = compile(&files, replay("remote")).unwrap_err(); + assert_eq!(err.serialize().code, "mds::data", "{main}: {err}"); + let message = err.to_string(); + assert!(message.contains("part.mds"), "{message}"); + assert!( + message.ends_with("a secret header is allowed in the entry module only"), + "{message}" + ); + } + assert!(rendered(compile(&[("main.mds", module)], replay("remote"))).ends_with("replayed\n")); +} + #[test] fn data_values_are_text_and_do_not_add_module_edges() { let main = "---\ndata:\n settings: ./value.json\n---\n@import \"./part.mds\" as part\n{{settings}}\n@include part\n"; diff --git a/crates/mds-core/tests/data_step.rs b/crates/mds-core/tests/data_step.rs new file mode 100644 index 00000000..8983eb46 --- /dev/null +++ b/crates/mds-core/tests/data_step.rs @@ -0,0 +1,278 @@ +//! The public step API: start and resume with stateless re-derive. + +use std::collections::HashMap; + +use mds::{ + AllowItem, CompileOptions, CompileResult, FetchContext, FetchState, MdsError, NativeFs, + NetworkPolicy, Request, RequestId, Response, RunKey, Step, TransportFailure, VirtualFs, +}; + +fn context(items: &[&str]) -> FetchContext { + let items = items + .iter() + .map(|item| AllowItem::parse(item).unwrap()) + .collect(); + FetchContext::new( + NetworkPolicy::new(items).unwrap(), + RunKey::from_bytes([7; 32]), + ) +} + +fn step(main: &str, ctx: &FetchContext, state: &FetchState) -> Result { + let fs = VirtualFs::new(HashMap::from([("main.mds".to_owned(), main.to_owned())])); + mds::compile_step_virtual_fs(fs, "main.mds", None, CompileOptions::default(), ctx, state) +} + +fn need(step: Result) -> Vec { + match step { + Ok(Step::Need(requests)) => requests, + other => panic!("expected requests, got {other:?}"), + } +} + +fn done(step: Result) -> CompileResult { + match step { + Ok(Step::Done(result)) => *result, + other => panic!("expected a finished compile, got {other:?}"), + } +} + +fn ok(body: &str) -> Response { + Response::http(200, Vec::new(), body.as_bytes().to_vec()) +} + +/// The state after an answer of `body` to each request. +fn answered(requests: &[Request], body: &str) -> FetchState { + requests.iter().fold(FetchState::new(), |state, request| { + state.with_response(request.id(), ok(body)).unwrap() + }) +} + +fn code(error: &MdsError) -> String { + error.serialize().code +} + +const TWO: &str = + "---\ndata:\n a: https://a.example/a\n b: https://b.example/b\n---\n{{a.n}}{{b.n}}\n"; + +/// TP-78: a second response for one ID fails with fixed text, and an entry name is not a +/// request ID. Control: two IDs are accepted. +#[test] +fn a_duplicate_response_id_fails_and_an_entry_name_is_no_id() { + let id = RequestId::parse_hex(&"ab".repeat(32)).unwrap(); + let other = RequestId::parse_hex(&"cd".repeat(32)).unwrap(); + let state = FetchState::new().with_response(id, ok("1")).unwrap(); + let err = state.clone().with_response(id, ok("2")).unwrap_err(); + assert_eq!(code(&err), "mds::invalid_options"); + assert_eq!( + err.to_string(), + "invalid options: the fetch state already holds a response for this request" + ); + assert_eq!(state.with_response(other, ok("2")).unwrap().len(), 2); + for name in ["a", "user", &"A".repeat(64)] { + assert!(RequestId::parse_hex(name).is_err(), "{name}"); + } +} + +/// The state holds at most one response per request of a compile (64). Control: 64. +#[test] +fn the_state_holds_at_most_the_request_cap() { + let ids: Vec = (0..=64) + .map(|index| RequestId::parse_hex(&format!("{index:064x}")).unwrap()) + .collect(); + let full = ids[..64].iter().fold(FetchState::new(), |state, id| { + state.with_response(*id, ok("1")).unwrap() + }); + assert_eq!(full.len(), 64); + let err = full.with_response(ids[64], ok("1")).unwrap_err(); + assert_eq!(code(&err), "mds::resource_limit"); + assert_eq!( + err.to_string(), + "resource limit exceeded: too many responses in the fetch state (max 64)" + ); +} + +/// TP-90: each resume is a fresh compile that runs every check again. A response with +/// an extra ID fails, and so does a narrower allow list. Control: an identical resume +/// completes. +#[test] +fn every_resume_runs_every_check_again() { + let wide = context(&["a.example", "b.example"]); + let requests = need(step(TWO, &wide, &FetchState::new())); + assert_eq!(requests.len(), 2); + let state = answered(&requests, r#"{"n": 1}"#); + + let extra = RequestId::parse_hex(&"ef".repeat(32)).unwrap(); + let err = step( + TWO, + &wide, + &state.clone().with_response(extra, ok("1")).unwrap(), + ) + .unwrap_err(); + assert_eq!(code(&err), "mds::invalid_options"); + assert_eq!( + err.to_string(), + "invalid options: the fetch state holds a response that this compile did not request" + ); + + let err = step(TWO, &context(&["a.example"]), &state).unwrap_err(); + assert_eq!(code(&err), "mds::network_denied"); + assert!(err.to_string().contains(": allow-list: "), "{err}"); + + let first = done(step(TWO, &wide, &state)); + let second = done(step(TWO, &wide, &state)); + assert_eq!(first, second); + assert_eq!(first.into_markdown().unwrap(), "11\n"); +} + +/// The result lists each bound URL entry in template form, and `dependencies` holds no +/// URL. Canonical JSON writes `remoteInputs` only when the list is not empty. Control: a +/// compile with no URL entry has no `remoteInputs` key. +#[test] +fn remote_inputs_are_in_template_form_and_dependencies_hold_no_url() { + let main = "---\nid: 7\ndata:\n a: https://a.example/items/{{id}}\n---\n{{a.n}}\n"; + let ctx = context(&["a.example"]); + let requests = need(step(main, &ctx, &FetchState::new())); + assert_eq!(requests[0].url().path(), "/items/7"); + let result = done(step(main, &ctx, &answered(&requests, r#"{"n": 1}"#))); + assert!(result.dependencies.is_empty(), "{:?}", result.dependencies); + let [input] = result.remote_inputs.as_slice() else { + panic!("expected one remote input, got {:?}", result.remote_inputs); + }; + assert_eq!( + ( + input.module.as_str(), + input.entry.as_str(), + input.template.as_str(), + input.origin.as_str() + ), + ( + "main.mds", + "a", + "https://a.example/items/{{id}}", + "https://a.example" + ) + ); + let json = result.to_canonical_json(); + assert_eq!( + json["remoteInputs"], + serde_json::json!([{ + "module": "main.mds", + "entry": "a", + "template": "https://a.example/items/{{id}}", + "origin": "https://a.example", + }]) + ); + assert!(!json.to_string().contains("/items/7"), "{json}"); + + let plain = done(step("Hello!\n", &ctx, &FetchState::new())); + assert!(plain.remote_inputs.is_empty()); + assert!(plain.to_canonical_json().get("remoteInputs").is_none()); +} + +/// A transport failure enters as a fixed kind: a refused address gives the policy code +/// and any other failure gives `mds::network`. +#[test] +fn a_transport_failure_enters_as_a_fixed_kind() { + let main = "---\ndata:\n a: https://a.example/a\n---\n{{a.n}}\n"; + let ctx = context(&["a.example"]); + let requests = need(step(main, &ctx, &FetchState::new())); + for (failure, expected, tail) in [ + ( + TransportFailure::AddressRefused, + "mds::network_denied", + "transport-address: the address is in a refused range", + ), + ( + TransportFailure::Timeout, + "mds::network", + "the request timed out", + ), + ] { + let state = FetchState::new() + .with_response(requests[0].id(), Response::failed(failure)) + .unwrap(); + let err = step(main, &ctx, &state).unwrap_err(); + assert_eq!(code(&err), expected, "{err}"); + assert!(err.to_string().ends_with(tail), "{err}"); + } +} + +/// The value depth cap of the data values. +const DEPTH_CAP: usize = 64; + +/// An envelope puts the body one level deeper. Thus a body with a value at the depth cap +/// fails with a data error, not with an internal error. Control: the same body with no +/// envelope binds. +#[test] +fn an_envelope_over_a_body_at_the_depth_cap_fails_with_a_data_error() { + let ctx = context(&["a.example"]); + let body = format!("{}1{}", r#"{"n":"#.repeat(DEPTH_CAP), "}".repeat(DEPTH_CAP)); + let wrapped = + "---\ndata:\n a: {url: 'https://a.example/a', envelope: true}\n---\n{{a.status}}\n"; + let requests = need(step(wrapped, &ctx, &FetchState::new())); + let err = step(wrapped, &ctx, &answered(&requests, &body)).unwrap_err(); + assert!(!matches!(err, MdsError::Internal), "{err}"); + assert_eq!(code(&err), "mds::data", "{err}"); + assert_eq!( + err.to_string(), + r#"data error in "main.mds", entry "a", field "body": value nesting exceeds maximum depth of 64"# + ); + + let plain = "---\ndata:\n a: https://a.example/a\n---\n@if a.n:\nbound\n@end\n"; + let requests = need(step(plain, &ctx, &FetchState::new())); + let result = done(step(plain, &ctx, &answered(&requests, &body))); + assert_eq!(result.into_markdown().unwrap(), "bound\n"); +} + +/// A data file that changes between two steps is read again: each step is a fresh +/// compile that keeps no value of the step before it. +#[test] +fn a_data_file_changed_between_two_steps_is_read_again() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + std::fs::write(root.join(".mdsroot"), "").unwrap(); + std::fs::write(root.join("cfg.json"), r#"{"name": "old"}"#).unwrap(); + let main = root.join("main.mds"); + std::fs::write( + &main, + "---\ndata:\n cfg: ./cfg.json\n remote: https://a.example/x\n---\n{{cfg.name}} {{remote.n}}\n", + ) + .unwrap(); + let ctx = context(&["a.example"]); + let run = |state: &FetchState| { + mds::compile_step_native_fs( + NativeFs::new(), + &main, + None, + CompileOptions::default(), + &ctx, + state, + ) + }; + let requests = need(run(&FetchState::new())); + std::fs::write(root.join("cfg.json"), r#"{"name": "new"}"#).unwrap(); + let result = done(run(&answered(&requests, r#"{"n": 1}"#))); + assert!( + result + .dependencies + .iter() + .all(|path| path.ends_with("cfg.json")), + "{:?}", + result.dependencies + ); + assert_eq!(result.into_markdown().unwrap(), "new 1\n"); +} + +/// A string source steps as a module does. +#[test] +fn a_string_source_steps_as_a_module_does() { + let ctx = context(&["a.example"]); + let source = "---\ndata:\n a: https://a.example/a\n---\n{{a.n}}\n"; + let run = |state: &FetchState| { + mds::compile_step_str(source, None, None, CompileOptions::default(), &ctx, state) + }; + let requests = need(run(&FetchState::new())); + let result = done(run(&answered(&requests, r#"{"n": 4}"#))); + assert_eq!(result.into_markdown().unwrap(), "4\n"); +} diff --git a/crates/mds-core/tests/net_sinks.rs b/crates/mds-core/tests/net_sinks.rs new file mode 100644 index 00000000..49fccce6 --- /dev/null +++ b/crates/mds-core/tests/net_sinks.rs @@ -0,0 +1,200 @@ +//! The sinks of request text: a message, a warning, `Debug` and a result field show the +//! URL as declared and the origin, never the expanded URL or response text. + +use std::collections::HashMap; + +use mds::{ + AllowItem, CompileOptions, CompileResult, FetchContext, FetchState, MdsError, NetworkPolicy, + Request, Response, RunKey, Step, VirtualFs, +}; + +const MARKER: &str = "marker-from-response"; + +/// `b` reads a value of the response of `a` into its URL. +const CHAIN: &str = + "---\ndata:\n a: https://a.example/a\n b: https://a.example/b/{{a.x}}\n---\n{{b.n}}\n"; +const TEMPLATE: &str = "https://a.example/b/{{a.x}}"; + +fn context(items: &[&str]) -> FetchContext { + let items = items + .iter() + .map(|item| AllowItem::parse(item).unwrap()) + .collect(); + FetchContext::new( + NetworkPolicy::new(items).unwrap(), + RunKey::from_bytes([7; 32]), + ) +} + +fn step(files: &[(&str, &str)], ctx: &FetchContext, state: &FetchState) -> Result { + let files = files + .iter() + .map(|&(key, text)| (key.to_owned(), text.to_owned())) + .collect::>(); + let fs = VirtualFs::new(files); + mds::compile_step_virtual_fs(fs, "main.mds", None, CompileOptions::default(), ctx, state) +} + +/// Run `main` to its end. `serve` answers each request by its URL path. +fn drive( + main: &str, + ctx: &FetchContext, + serve: impl Fn(&Request) -> Response, +) -> (Result, Vec) { + let mut state = FetchState::new(); + let mut sent = Vec::new(); + for _ in 0..=64 { + match step(&[("main.mds", main)], ctx, &state) { + Ok(Step::Need(requests)) => { + for request in requests { + state = state.with_response(request.id(), serve(&request)).unwrap(); + sent.push(request); + } + } + Ok(Step::Done(result)) => return (Ok(*result), sent), + Ok(other) => panic!("unexpected step {other:?}"), + Err(error) => return (Err(error), sent), + } + } + panic!("the compile did not end within the round bound"); +} + +fn serve_chain(status: u16) -> impl Fn(&Request) -> Response { + move |request| { + if request.url().path() == "/a" { + let body = format!(r#"{{"x": "{MARKER}"}}"#); + Response::http(200, Vec::new(), body.into_bytes()) + } else { + Response::http(status, Vec::new(), br#"{"n": 1}"#.to_vec()) + } + } +} + +fn record(error: &MdsError) -> String { + serde_json::to_string(&error.serialize()).unwrap() +} + +/// TP-96: a response value in the next URL, which gets 404, is absent from `Display`, +/// `Debug` and the serialized error. Control: the URL template and the origin are in +/// the message, and the marker is in the URL that the sender got. +#[test] +fn a_response_value_in_a_failed_next_url_is_in_no_message() { + let (result, sent) = drive(CHAIN, &context(&["a.example"]), serve_chain(404)); + let err = result.unwrap_err(); + assert_eq!(err.serialize().code, "mds::network"); + assert_eq!(sent[1].url().path(), format!("/b/{MARKER}")); + let sinks = [err.to_string(), format!("{err:?}"), record(&err)]; + for sink in &sinks { + assert!(!sink.contains(MARKER), "{sink}"); + } + assert!( + sinks[0].contains(&format!( + r#"entry "b", URL "{TEMPLATE}", origin "https://a.example": "# + )), + "{}", + sinks[0] + ); +} + +/// The `Debug` of a needed request shows the template and the origin, never the +/// expanded URL. Control: the template is there. +#[test] +fn a_needed_request_shows_the_template_in_debug() { + let ctx = context(&["a.example"]); + let (_, sent) = drive(CHAIN, &ctx, serve_chain(404)); + let debug = format!("{:?}", sent[1]); + assert!(!debug.contains(MARKER), "{debug}"); + assert!(debug.contains(TEMPLATE), "{debug}"); + assert_eq!(sent[1].template(), TEMPLATE); +} + +/// A finished compile shows the marker in no warning, no remote input and no dependency, +/// in Rust and in canonical JSON. Control: the remote input holds the template. +#[test] +fn a_finished_compile_shows_no_response_value_in_its_metadata() { + let main = "---\ndata:\n a: https://a.example/a\n b: {url: 'https://a.example/b/{{a.x}}', envelope: true}\n---\n{{b.status}}\n"; + let (result, _) = drive(main, &context(&["a.example"]), serve_chain(404)); + let result = result.unwrap(); + let inputs = format!("{:?}", result.remote_inputs); + for sink in [ + format!("{:?}", result.warnings), + inputs.clone(), + format!("{:?}", result.dependencies), + ] { + assert!(!sink.contains(MARKER), "{sink}"); + } + assert!(inputs.contains(TEMPLATE), "{inputs}"); + let mut json = result.to_canonical_json(); + json["output"] = serde_json::Value::Null; + assert!(!json.to_string().contains(MARKER), "{json}"); + assert!(json.to_string().contains(TEMPLATE), "{json}"); +} + +/// A policy refusal has the fixed help of its check, in the message record too. +/// Control: the replay help of entries with no replay value stays the same. +#[test] +fn a_refusal_has_the_fixed_help_of_its_check() { + let main = "---\ndata:\n a: https://b.example/x\n---\n{{a.n}}\n"; + let err = step( + &[("main.mds", main)], + &context(&["a.example"]), + &FetchState::new(), + ) + .unwrap_err(); + let serialized = err.serialize(); + assert_eq!(serialized.code, "mds::network_denied"); + assert_eq!( + serialized.help.as_deref(), + Some("add the origin to the network allow list of the host") + ); + let built = MdsError::network_refused( + "main.mds", + "a", + "https://b.example/x", + "https://b.example", + context(&["a.example"]) + .policy() + .check_address("10.0.0.2:443".parse().unwrap()) + .unwrap_err(), + ); + assert_eq!( + built.to_string(), + r#"network access denied for data entries: "main.mds", entry "a", URL "https://b.example/x", origin "https://b.example": transport-address: the address is in a refused range"# + ); + assert_eq!( + built.serialize().help.as_deref(), + Some("to reach an address in a refused range, add its exact IP address and port to the allow list") + ); + let frontier = MdsError::network_denied(&[("main.mds", "a")]); + assert_eq!( + frontier.serialize().help.as_deref(), + Some("provide a runtime value for each entry to replay it without network access") + ); +} + +/// A value error of a response names the entry, never a key path, because the key is +/// response text. Control: the same value in a data file names its key path. +#[test] +fn a_value_error_of_a_response_names_no_key_path() { + let body = format!(r#"{{"{MARKER}\u001b": 1}}"#); + let ctx = context(&["a.example"]); + let main = "---\ndata:\n a: https://a.example/a\n---\n{{a}}\n"; + let (result, _) = drive(main, &ctx, |_| { + Response::http(200, Vec::new(), body.clone().into_bytes()) + }); + let err = result.unwrap_err(); + assert_eq!(err.serialize().code, "mds::data"); + assert_eq!( + err.to_string(), + r#"data error in "main.mds", entry "a": forbidden character in a data string or key"# + ); + let file = "---\ndata:\n a: ./a.json\n---\n{{a}}\n"; + let err = step( + &[("main.mds", file), ("a.json", body.as_str())], + &ctx, + &FetchState::new(), + ) + .unwrap_err(); + assert_eq!(err.serialize().code, "mds::data"); + assert!(err.to_string().contains(MARKER), "{err}"); +} diff --git a/crates/mds-core/tests/spec_error_codes.rs b/crates/mds-core/tests/spec_error_codes.rs index 26674de2..27a66ddb 100644 --- a/crates/mds-core/tests/spec_error_codes.rs +++ b/crates/mds-core/tests/spec_error_codes.rs @@ -70,12 +70,72 @@ fn network_denied_names_each_frontier_entry_without_a_source_span() { assert_eq!(err.source_name(), None); } +#[test] +fn data_type_error_names_its_location_without_a_source_span() { + let err = MdsError::data_type_error( + "sub/mo\tdule.mds", + "en\x1btry", + "fi\neld", + "a header value takes a string, a boolean or an exact integer up to 2^53, not null", + ); + let serialized = err.serialize(); + let message = concat!( + r#"type error in "sub/mo\u"#, + r#"0009dule.mds", entry "en\u"#, + r#"001Btry", field "fi\u"#, + r#"000Aeld": a header value takes a string, a boolean or an exact integer up to 2^53, not null"#, + ); + assert_eq!(serialized.code, "mds::type_error"); + assert_eq!(err.to_string(), message); + assert_eq!(serialized.message, message); + assert_eq!(serialized.span, None); + assert_eq!(err.source_name(), None); +} + +/// A transport failure names the entry, the URL as declared and the origin. Each name is +/// escaped as a path is, so a control character in it can not start a new line. +#[test] +fn network_error_names_the_entry_template_and_origin_without_a_source_span() { + let err = MdsError::network( + "sub/mod\nule.mds", + "us\x1bers", + "https://api.example/users/{{id}}\t", + "https://api.example\n", + "request timed out", + ); + let serialized = err.serialize(); + let message = concat!( + r#"network error in "sub/mod\u"#, + r#"000Aule.mds", entry "us\u"#, + r#"001Bers", URL "https://api.example/users/{{id}}\u"#, + r#"0009", origin "https://api.example\u"#, + r#"000A": request timed out"#, + ); + assert_eq!(serialized.code, "mds::network"); + assert_eq!(err.to_string(), message); + assert_eq!(serialized.message, message); + assert_eq!(serialized.help, None); + assert_eq!(serialized.span, None); + assert_eq!(err.source_name(), None); +} + +/// A step compile refuses host input with `mds::invalid_options`: fixed text, no span and +/// no help. The bindings use the same code for their option checks. +#[test] +fn invalid_options_is_fixed_text_without_a_source_span() { + let reason = "the fetch state holds a response that this compile did not request"; + let err = MdsError::invalid_options(reason); + let serialized = err.serialize(); + assert_eq!(serialized.code, "mds::invalid_options"); + assert_eq!(err.to_string(), format!("invalid options: {reason}")); + assert_eq!(serialized.message, err.to_string()); + assert_eq!(serialized.help, None); + assert_eq!(serialized.span, None); + assert_eq!(err.source_name(), None); +} + /// Codes the napi, WASM, or Python bindings return but `mds-core` does not declare. -const BINDING_ONLY_CODES: &[&str] = &[ - "mds::invalid_options", - "mds::filename_collision", - "mds::invalid_backend_result", -]; +const BINDING_ONLY_CODES: &[&str] = &["mds::filename_collision", "mds::invalid_backend_result"]; fn read_error_rs() -> String { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/error.rs"); @@ -211,7 +271,12 @@ fn core_codes_are_documented_in_spec() { fn data_codes_have_core_declarations_and_spec_exit_classes() { let codes = extract_codes(&read_error_rs()); let section = error_codes_section(&read_spec_md()).expect("spec error registry"); - for (code, exits) in [("mds::data", "1 / 2"), ("mds::network_denied", "2 / 2")] { + for (code, exits) in [ + ("mds::data", "1 / 2"), + ("mds::network_denied", "2 / 2"), + ("mds::network", "2 / 2"), + ("mds::invalid_options", "2 / n/a"), + ] { assert!(codes.iter().any(|declared| declared == code), "{code}"); let row = section .lines() diff --git a/crates/mds-core/tests/supply_chain.rs b/crates/mds-core/tests/supply_chain.rs new file mode 100644 index 00000000..4f7ae756 --- /dev/null +++ b/crates/mds-core/tests/supply_chain.rs @@ -0,0 +1,392 @@ +//! The dependency gate of the core and the WASM build (#405, TP-98): no HTTP, TLS, URL, +//! async runtime or sender crate is in the normal-dependency tree of `mds-core` or +//! `mds-wasm` for any target, and no workspace crate depends on a logger crate. +//! +//! The gate reads two sources, and neither needs network access: +//! - `cargo metadata --no-deps --offline --locked` for the dependency kinds of each +//! workspace crate, so a dev-dependency of a workspace crate is not in its tree; +//! - `Cargo.lock` for every other edge. The lock holds the packages of every target and +//! every feature, and the optional edges that it keeps, so the gate checks a tree that +//! is at least as wide as the tree of any build. + +use std::collections::{BTreeSet, HashMap, VecDeque}; +use std::process::Command; + +/// The crates that the core and the WASM build must never depend on: HTTP, TLS, URL, +/// async runtimes, root lists and the native sender. +const NETWORK_CRATES: [&str; 21] = [ + "ureq", + "ureq-proto", + "http", + "httparse", + "rustls", + "rustls-webpki", + "rustls-pki-types", + "ring", + "webpki-roots", + "webpki-root-certs", + "url", + "hyper", + "hyper-util", + "h2", + "reqwest", + "tokio", + "async-std", + "smol", + "native-tls", + "openssl", + "mds-fetch", +]; + +/// Logger crates. A logger would write the request text that ureq logs at the debug and +/// trace levels, so no workspace crate may depend on one, also for its tests. +const LOGGER_CRATES: [&str; 6] = [ + "env_logger", + "tracing-subscriber", + "simplelog", + "pretty_env_logger", + "fern", + "log4rs", +]; + +/// The normal-dependency names of each workspace crate. +type NormalDeps = HashMap>; + +/// One `[[package]]` of a lock file. +#[derive(Debug, Default)] +struct Package { + name: String, + version: String, + /// The package has a `source`: it is not a workspace package. + registry: bool, + /// Each dependency: the name and, when the lock gives it, the version. + dependencies: Vec<(String, Option)>, +} + +/// The packages of a lock file. The value of `name`, `version` and each item of a +/// `dependencies` list is a basic string; other keys are skipped. +fn parse_lock(text: &str) -> Vec { + let mut packages: Vec = Vec::new(); + let mut in_dependencies = false; + for line in text.lines() { + let line = line.trim(); + if line == "[[package]]" { + packages.push(Package::default()); + in_dependencies = false; + continue; + } + let Some(package) = packages.last_mut() else { + continue; + }; + if in_dependencies { + if line == "]" { + in_dependencies = false; + } else if let Some(entry) = quoted(line.trim_end_matches(',')) { + let mut parts = entry.split(' '); + let name = parts.next().unwrap_or_default().to_owned(); + let version = parts.next().map(str::to_owned); + package.dependencies.push((name, version)); + } + } else if let Some(value) = line.strip_prefix("name = ").and_then(quoted) { + package.name = value.to_owned(); + } else if let Some(value) = line.strip_prefix("version = ").and_then(quoted) { + package.version = value.to_owned(); + } else if line.starts_with("source = ") { + package.registry = true; + } else if line == "dependencies = [" { + in_dependencies = true; + } + } + packages +} + +fn quoted(text: &str) -> Option<&str> { + text.strip_prefix('"')?.strip_suffix('"') +} + +/// The names of the packages that `roots` (workspace crate names) reach, the roots +/// included. With `normal`, a workspace crate follows only its normal dependencies of +/// every target; without it, every edge of the lock. A dependency that names no +/// package, a name with two packages and no version, or a workspace crate that +/// `normal` does not list fails the gate. +fn closure( + packages: &[Package], + normal: Option<&NormalDeps>, + roots: &[&str], +) -> Result, String> { + let mut queue = VecDeque::new(); + for root in roots { + let index = packages + .iter() + .position(|package| package.name == *root && !package.registry) + .ok_or_else(|| format!("the lock has no workspace crate {root}"))?; + queue.push_back(index); + } + let mut seen = vec![false; packages.len()]; + let mut names = BTreeSet::new(); + // Each package is expanded once, so the loop ends after the package count. + while let Some(index) = queue.pop_front() { + if std::mem::replace(&mut seen[index], true) { + continue; + } + let package = &packages[index]; + names.insert(package.name.clone()); + let kept = match (normal, package.registry) { + (Some(normal), false) => Some( + normal + .get(&package.name) + .ok_or_else(|| format!("no dependency kinds for {}", package.name))?, + ), + _ => None, + }; + for (name, version) in &package.dependencies { + if kept.is_some_and(|kept| !kept.contains(name)) { + continue; + } + let matches: Vec = (0..packages.len()) + .filter(|&other| { + packages[other].name == *name + && version + .as_ref() + .is_none_or(|v| packages[other].version == *v) + }) + .collect(); + match matches.as_slice() { + [one] => queue.push_back(*one), + [] => return Err(format!("{} names a missing package {name}", package.name)), + _ => return Err(format!("{} names {name} with no version", package.name)), + } + } + } + Ok(names) +} + +/// The names of `banned` that the tree of `roots` holds. +fn banned_in( + lock: &str, + normal: Option<&NormalDeps>, + roots: &[&str], + banned: &[&str], +) -> Result, String> { + let names = closure(&parse_lock(lock), normal, roots)?; + Ok(banned + .iter() + .filter(|name| names.contains(**name)) + .map(|name| (*name).to_owned()) + .collect()) +} + +const WORKSPACE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../.."); + +fn workspace_lock() -> String { + std::fs::read_to_string(format!("{WORKSPACE}/Cargo.lock")) + .expect("the workspace Cargo.lock is readable") +} + +/// The normal-dependency names of each workspace crate, of every target and with every +/// optional dependency, from `cargo metadata`. `--no-deps` and `--offline` read the +/// workspace manifests only. +fn workspace_normal_deps() -> NormalDeps { + let output = Command::new(env!("CARGO")) + .args([ + "metadata", + "--no-deps", + "--offline", + "--locked", + "--format-version", + "1", + ]) + .current_dir(WORKSPACE) + .output() + .expect("cargo metadata runs"); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let metadata: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + let packages = metadata["packages"].as_array().expect("a package list"); + packages + .iter() + .map(|package| { + let names = package["dependencies"] + .as_array() + .expect("a dependency list") + .iter() + .filter(|dependency| dependency["kind"].is_null()) + .map(|dependency| dependency["name"].as_str().unwrap().to_owned()) + .collect(); + (package["name"].as_str().unwrap().to_owned(), names) + }) + .collect() +} + +/// TP-98: the core and the WASM build depend on no HTTP, TLS, URL, async or sender +/// crate. Controls: the tree holds crates that the core and the WASM build use, and the +/// lock lists a dev-dependency of the WASM crate that the tree leaves out. The same gate +/// finds the network crates of the sender. +#[test] +fn the_core_and_wasm_trees_hold_no_network_crate() { + let lock = workspace_lock(); + let normal = workspace_normal_deps(); + let roots = ["mds-core", "mds-wasm"]; + assert_eq!( + banned_in(&lock, Some(&normal), &roots, &NETWORK_CRATES), + Ok(Vec::new()) + ); + let packages = parse_lock(&lock); + let names = closure(&packages, Some(&normal), &roots).unwrap(); + for used in ["mds-core", "mds-wasm", "serde_json", "wasm-bindgen"] { + assert!(names.contains(used), "{used}"); + } + let wasm = packages + .iter() + .find(|package| package.name == "mds-wasm") + .unwrap(); + assert!(wasm + .dependencies + .iter() + .any(|(name, _)| name == "wasm-bindgen-test")); + assert!(!names.contains("wasm-bindgen-test")); + let sender = banned_in(&lock, Some(&normal), &["mds-fetch"], &NETWORK_CRATES).unwrap(); + for found in ["ureq", "rustls", "ring", "webpki-root-certs", "mds-fetch"] { + assert!( + sender.iter().any(|name| name == found), + "{found}: {sender:?}" + ); + } +} + +/// No workspace crate depends on a logger crate, for any kind of dependency. Control: +/// the workspace tree holds the sender and the `log` facade that ureq uses. +#[test] +fn no_workspace_tree_holds_a_logger() { + let lock = workspace_lock(); + let members: Vec = parse_lock(&lock) + .into_iter() + .filter(|package| !package.registry) + .map(|package| package.name) + .collect(); + let roots: Vec<&str> = members.iter().map(String::as_str).collect(); + assert!(roots.contains(&"mds-fetch"), "{roots:?}"); + assert_eq!( + banned_in(&lock, None, &roots, &LOGGER_CRATES), + Ok(Vec::new()) + ); + let names = closure(&parse_lock(&lock), None, &roots).unwrap(); + assert!(names.contains("ureq") && names.contains("log")); +} + +/// A planted lock where the core reaches `ureq` and, through it, `rustls`. +const PLANTED: &str = r#" +[[package]] +name = "mds-core" +version = "0.7.0" +dependencies = [ + "serde", + "ureq", +] + +[[package]] +name = "mds-wasm" +version = "0.7.0" +dependencies = [ + "mds-core", +] + +[[package]] +name = "mds-cli" +version = "0.7.0" +dependencies = [ + "env_logger", + "mds-core", +] + +[[package]] +name = "serde" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "ureq" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rustls 0.23.46", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rustls" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "env_logger" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +"#; + +/// The dependency kinds of [`PLANTED`] with `core` as the normal dependencies of +/// `mds-core`. +fn planted_kinds(core: &[&str]) -> NormalDeps { + let set = |names: &[&str]| names.iter().map(|name| (*name).to_owned()).collect(); + HashMap::from([ + ("mds-core".to_owned(), set(core)), + ("mds-wasm".to_owned(), set(&["mds-core"])), + ("mds-cli".to_owned(), set(&["env_logger", "mds-core"])), + ]) +} + +/// TP-98 control: the gate finds a planted HTTP crate and the TLS crate below it, from +/// the core and from the WASM build, and a planted logger in another workspace crate. +/// The same crate as a dev-dependency of the core is not in its tree. +#[test] +fn the_gate_finds_planted_crates() { + let normal = planted_kinds(&["serde", "ureq"]); + let expected = Ok(vec!["ureq".to_owned(), "rustls".to_owned()]); + for root in ["mds-core", "mds-wasm"] { + let found = banned_in(PLANTED, Some(&normal), &[root], &NETWORK_CRATES); + assert_eq!(found, expected, "{root}"); + } + assert_eq!( + banned_in(PLANTED, None, &["mds-cli"], &LOGGER_CRATES), + Ok(vec!["env_logger".to_owned()]) + ); + let dev_only = planted_kinds(&["serde"]); + assert_eq!( + banned_in(PLANTED, Some(&dev_only), &["mds-wasm"], &NETWORK_CRATES), + Ok(Vec::new()) + ); +} + +/// The gate fails closed on a lock that it can not follow: a missing root, a missing +/// dependency, an ambiguous name or a workspace crate with no dependency kinds. +#[test] +fn the_gate_fails_closed_on_an_unknown_edge() { + let normal = planted_kinds(&["serde", "ureq"]); + let check = |lock: &str, normal: &NormalDeps| { + banned_in(lock, Some(normal), &["mds-core"], &NETWORK_CRATES) + }; + assert!(check(PLANTED, &normal).is_ok()); + assert!(banned_in(PLANTED, Some(&normal), &["mds-napi"], &NETWORK_CRATES).is_err()); + let renamed = PLANTED.replace(" \"serde\",\n", " \"serde_json\",\n"); + assert!(check(&renamed, &planted_kinds(&["serde_json", "ureq"])).is_err()); + assert!(check( + &PLANTED.replace("\"rustls 0.23.46\"", "\"rustls 9.9.9\""), + &normal + ) + .is_err()); + assert!(check( + &PLANTED.replace("\"rustls 0.23.46\"", "\"rustls\""), + &normal + ) + .is_err()); + let mut unknown = normal.clone(); + unknown.remove("mds-core"); + assert!(check(PLANTED, &unknown).is_err()); +} diff --git a/crates/mds-fetch/Cargo.toml b/crates/mds-fetch/Cargo.toml new file mode 100644 index 00000000..87bd68d6 --- /dev/null +++ b/crates/mds-fetch/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "mds-fetch" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +description = "MDS (Markdown Script) compiler — the native sender of URL data entries" +license.workspace = true +readme.workspace = true +repository.workspace = true +keywords.workspace = true +categories = ["network-programming", "template-engine"] + +# The HTTP, TLS and root list crates live here only. mds-core and mds-wasm never depend +# on this crate: `crates/mds-core/tests/supply_chain.rs` fails if they do. +[dependencies] +mds = { package = "mds-core", path = "../mds-core", version = "0.7.0" } +ureq = { workspace = true } +rustls = { workspace = true } +webpki-root-certs = { workspace = true } + +[dev-dependencies] +rcgen = { workspace = true } diff --git a/crates/mds-fetch/LICENSE b/crates/mds-fetch/LICENSE new file mode 100644 index 00000000..37193c4b --- /dev/null +++ b/crates/mds-fetch/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Dean Sharon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/mds-fetch/clippy.toml b/crates/mds-fetch/clippy.toml new file mode 100644 index 00000000..a528a6ca --- /dev/null +++ b/crates/mds-fetch/clippy.toml @@ -0,0 +1,5 @@ +# TLS certificate checks stay on in every build of the sender. A call to one of these +# methods fails `cargo clippy -- -D warnings`. +disallowed-methods = [ + { path = "ureq::tls::TlsConfigBuilder::disable_verification", reason = "the sender always checks the certificate of the server" }, +] diff --git a/crates/mds-fetch/src/lib.rs b/crates/mds-fetch/src/lib.rs new file mode 100644 index 00000000..ce9d4b39 --- /dev/null +++ b/crates/mds-fetch/src/lib.rs @@ -0,0 +1,85 @@ +//! The native sender of URL data entries. +//! +//! [`Fetcher`] sends each [`mds::Request`] of a step compile and gives the +//! [`mds::Response`] that the host adds to the [`mds::FetchState`] of the next step. +//! This crate holds the HTTP, TLS and root list crates, so `mds-core` and `mds-wasm` +//! depend on none of them. +//! +//! The sender keeps these rules: +//! - It follows no redirect. A redirect answer goes back to the core, which checks +//! each hop. +//! - It uses no proxy. The agent has no proxy setting, and its connector chain has no +//! proxy connector, so a proxy environment variable has no effect. +//! - It looks up a host name once per request, checks every address of the answer with +//! [`mds::NetworkPolicy::check_address`] and connects only to a checked address. One +//! refused address refuses the request. +//! - It uses TLS 1.2 or 1.3 with the ring provider, and the certificate check is always +//! on. The roots are the Mozilla list and the roots that the host gives, never roots +//! of the environment or of the system. +//! - It reads at most the body cap plus one byte, and one deadline binds the request +//! from the name lookup to the end of the body. +//! - It keeps no connection after a request. +//! +//! The sender installs no logger. ureq writes the request at the `debug` level and the +//! bytes on the wire at the `trace` level of the `log` crate, so a host that installs a +//! logger must keep those levels off for ureq. + +use std::error::Error; +use std::fmt; + +use mds::RunKey; + +mod resolve; +mod send; +mod tls; + +pub use resolve::{Lookup, SystemLookup}; +pub use rustls::pki_types::CertificateDer; +pub use send::Fetcher; +pub use tls::parse_pem_roots; + +/// Why the sender can not start. The message is fixed text and holds no input. +/// +/// This enum is `#[non_exhaustive]`: new errors may be added in minor releases. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SetupError { + /// The random source of the system failed. + Random, + /// A root file is not valid PEM. + RootFile, + /// A root file holds no certificate. + NoRoots, + /// The host root at this index of the list is not a valid trust anchor. + Root { index: usize }, +} + +impl fmt::Display for SetupError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + SetupError::Random => f.write_str("the random source of the system failed"), + SetupError::RootFile => f.write_str("the root file is not valid PEM"), + SetupError::NoRoots => f.write_str("the root file holds no certificate"), + SetupError::Root { index } => { + write!(f, "root {index} of the host is not a valid trust anchor") + } + } + } +} + +impl Error for SetupError {} + +/// A new per-run key for the request identities of one run, from the random source of +/// the system (through the ring provider of the sender). +/// +/// # Errors +/// +/// [`SetupError::Random`] when the random source fails. +pub fn run_key() -> Result { + let mut bytes = [0u8; 32]; + rustls::crypto::ring::default_provider() + .secure_random + .fill(&mut bytes) + .map_err(|_| SetupError::Random)?; + Ok(RunKey::from_bytes(bytes)) +} diff --git a/crates/mds-fetch/src/resolve.rs b/crates/mds-fetch/src/resolve.rs new file mode 100644 index 00000000..d77b809b --- /dev/null +++ b/crates/mds-fetch/src/resolve.rs @@ -0,0 +1,205 @@ +//! Name lookup and the address check: the sender connects only to an address that the +//! policy passed. + +use std::error::Error; +use std::fmt; +use std::io; +use std::net::{IpAddr, SocketAddr, ToSocketAddrs}; +use std::sync::mpsc::{self, RecvTimeoutError}; +use std::sync::Arc; +use std::thread; +use std::time::Duration; + +use mds::{NetworkPolicy, MAX_RESOLVED_ADDRS}; +use ureq::config::Config; +use ureq::http::Uri; +use ureq::unversioned::resolver::{ArrayVec, ResolvedSocketAddrs, Resolver}; +use ureq::unversioned::transport::NextTimeout; + +/// A name lookup. The sender calls it once per request, for a host name only: an IP +/// address host needs no lookup. +pub trait Lookup: Send + Sync { + /// The addresses of `host` for `port`, in less than `timeout`. An answer of more + /// than [`MAX_RESOLVED_ADDRS`] addresses fails the request. + /// + /// # Errors + /// + /// An I/O error of kind [`io::ErrorKind::TimedOut`] for a lookup past `timeout`, + /// and any other error when the name has no address. + fn lookup(&self, host: &str, port: u16, timeout: Duration) -> io::Result>; +} + +/// The lookup of the operating system. It runs each lookup on its own thread and waits +/// at most the timeout. +/// +/// A lookup past its timeout fails the request at once. But its thread stays until the +/// system lookup returns, and only then ends. The sender does at most one lookup for +/// each request. The CLI counts each request against [`mds::MAX_REQUESTS_PER_RUN`], so +/// this cap also bounds the count of these threads in one CLI run. A host that sends +/// requests for a long time can give its own [`Lookup`] with +/// [`Fetcher::with_lookup`](crate::Fetcher::with_lookup), for example a lookup with a +/// limit on its live threads. +/// +/// This type is `#[non_exhaustive]`: obtain values from [`SystemLookup::new`]. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, Default)] +pub struct SystemLookup; + +impl SystemLookup { + #[must_use] + pub fn new() -> Self { + Self + } +} + +impl Lookup for SystemLookup { + fn lookup(&self, host: &str, port: u16, timeout: Duration) -> io::Result> { + let (sender, receiver) = mpsc::sync_channel(1); + let target = (host.to_owned(), port); + thread::Builder::new() + .name("mds-fetch-lookup".to_owned()) + .spawn(move || { + // One more address than the cap shows that the answer is too long. + let found = target + .to_socket_addrs() + .map(|addrs| addrs.take(MAX_RESOLVED_ADDRS + 1).collect()); + // The receiver is gone after a timeout; then the answer is not used. + let _ = sender.send(found); + })?; + match receiver.recv_timeout(timeout) { + Ok(found) => found, + Err(RecvTimeoutError::Timeout) => Err(io::ErrorKind::TimedOut.into()), + Err(RecvTimeoutError::Disconnected) => Err(io::Error::other("the lookup stopped")), + } + } +} + +/// The resolver failure of a request that an address check refused. +#[derive(Debug)] +pub(crate) struct AddressRefused; + +impl fmt::Display for AddressRefused { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("an address is in a refused range") + } +} + +impl Error for AddressRefused {} + +/// The resolver failure of a lookup with more than [`MAX_RESOLVED_ADDRS`] addresses. +#[derive(Debug)] +pub(crate) struct TooManyAddresses; + +impl fmt::Display for TooManyAddresses { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("the lookup gave too many addresses") + } +} + +impl Error for TooManyAddresses {} + +/// The host and the port of the one request that a resolver serves. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Target { + /// The host with no IPv6 brackets. + pub(crate) host: String, + pub(crate) port: u16, +} + +impl Target { + /// The target of `uri`. An `https` or `http` URI with no port has the default port. + pub(crate) fn of(uri: &Uri) -> Option { + let default_port = match uri.scheme_str()? { + "https" => 443, + "http" => 80, + _ => return None, + }; + let host = uri.host()?; + let host = host + .strip_prefix('[') + .and_then(|inner| inner.strip_suffix(']')) + .unwrap_or(host); + Some(Self { + host: host.to_owned(), + port: uri.port_u16().unwrap_or(default_port), + }) + } +} + +/// The resolver of one request: one lookup for a host name, none for an IP address, and +/// an address check for every address of the answer before ureq connects. One refused +/// address refuses the request. +pub(crate) struct CheckedResolver { + pub(crate) policy: Arc, + pub(crate) lookup: Arc, + pub(crate) target: Target, +} + +impl fmt::Debug for CheckedResolver { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("CheckedResolver").finish_non_exhaustive() + } +} + +impl Resolver for CheckedResolver { + fn resolve( + &self, + uri: &Uri, + _config: &Config, + timeout: NextTimeout, + ) -> Result { + // The resolver serves one request: any other host or port is refused. + if Target::of(uri).as_ref() != Some(&self.target) { + return Err(ureq::Error::ConnectionFailed); + } + let Target { host, port } = &self.target; + let found = match host.parse::() { + Ok(ip) => vec![SocketAddr::new(ip, *port)], + Err(_) => match self.lookup.lookup(host, *port, *timeout.after) { + Ok(found) => found, + Err(error) if error.kind() == io::ErrorKind::TimedOut => { + return Err(ureq::Error::Timeout(timeout.reason)); + } + Err(_) => return Err(ureq::Error::HostNotFound), + }, + }; + let checked = check_answer(&self.policy, &found, *port)?; + let mut addrs = self.empty(); + let room = capacity(&addrs); + for address in checked.into_iter().take(room) { + addrs.push(address); + } + Ok(addrs) + } +} + +/// The capacity of a ureq address list. A push past it panics, so the copy takes at +/// most this many addresses. +fn capacity(_: &ArrayVec) -> usize { + N +} + +/// The addresses of a lookup answer, each with the request port, after the address +/// check of each one. An empty answer, an answer past the cap or one refused address +/// fails the request. +fn check_answer( + policy: &NetworkPolicy, + found: &[SocketAddr], + port: u16, +) -> Result, ureq::Error> { + if found.is_empty() { + return Err(ureq::Error::HostNotFound); + } + if found.len() > MAX_RESOLVED_ADDRS { + return Err(ureq::Error::Other(Box::new(TooManyAddresses))); + } + let mut checked = Vec::with_capacity(found.len()); + for address in found { + let address = SocketAddr::new(address.ip(), port); + if policy.check_address(address).is_err() { + return Err(ureq::Error::Other(Box::new(AddressRefused))); + } + checked.push(address); + } + Ok(checked) +} diff --git a/crates/mds-fetch/src/send.rs b/crates/mds-fetch/src/send.rs new file mode 100644 index 00000000..f1ee43d6 --- /dev/null +++ b/crates/mds-fetch/src/send.rs @@ -0,0 +1,269 @@ +//! The sender: one ureq agent per request with a fixed configuration. +//! +//! Each request gets its own agent, resolver and connection pool, so no connection or +//! address stays from an earlier request. The agent has no proxy, and its connector +//! chain is TCP then rustls only: no proxy connector is in the chain. + +use std::fmt; +use std::io::{self, Read}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use mds::{ + HeaderValue, Method, NetworkPolicy, Origin, Request, Response, TransportFailure, + MAX_RESPONSE_BYTES, MAX_RESPONSE_HEADER_BYTES, REQUEST_TIMEOUT, +}; +use rustls::pki_types::CertificateDer; +use ureq::config::Config; +use ureq::http::Uri; +use ureq::tls::TlsConfig; +use ureq::unversioned::transport::{Connector, RustlsConnector, TcpConnector}; +use ureq::{Agent, Body}; + +use crate::resolve::{AddressRefused, CheckedResolver, Lookup, SystemLookup, Target}; +use crate::tls::client_config; +use crate::SetupError; + +/// The `User-Agent` of every request. +const USER_AGENT: &str = concat!("mds-fetch/", env!("CARGO_PKG_VERSION")); +/// The `Accept` of every request: the data formats that the core reads. +const ACCEPT: &str = "application/json, application/yaml, text/plain"; +/// The `Accept-Encoding` of every request. The sender decodes no content coding, so the +/// body cap counts the bytes that the core reads. +const ACCEPT_ENCODING: &str = "identity"; + +/// The sender of the requests of step compiles. +/// +/// It follows no redirect, uses no proxy, checks every address of a lookup with +/// [`NetworkPolicy::check_address`] before it connects, keeps the certificate check on, +/// reads at most the body cap plus one byte and binds each request with a deadline. +/// +/// This type is `#[non_exhaustive]`: obtain values from [`Fetcher::new`]. +#[non_exhaustive] +#[derive(Clone)] +pub struct Fetcher { + policy: Arc, + tls: TlsConfig, + lookup: Arc, + deadline: Duration, + body_cap: u64, +} + +impl fmt::Debug for Fetcher { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Fetcher") + .field("deadline", &self.deadline) + .field("body_cap", &self.body_cap) + .finish_non_exhaustive() + } +} + +impl Fetcher { + /// A sender for the requests of step compiles. `host_roots` join the Mozilla roots; + /// no root comes from the environment or the system. + /// + /// The sender does not examine the allow list again: it sends each request that the + /// core gives it. It uses `policy` only for the address check and to bind the secret + /// headers. Thus give the sender the same `NetworkPolicy` as the + /// [`mds::FetchContext`] of the step compiles. + /// + /// # Errors + /// + /// [`SetupError::Root`] when a host root is not a valid trust anchor. + pub fn new( + policy: Arc, + host_roots: &[CertificateDer<'_>], + ) -> Result { + Ok(Self { + policy, + tls: client_config(host_roots)?, + lookup: Arc::new(SystemLookup::new()), + deadline: REQUEST_TIMEOUT, + body_cap: MAX_RESPONSE_BYTES, + }) + } + + /// The sender with `lookup` for host names. + #[must_use] + pub fn with_lookup(self, lookup: impl Lookup + 'static) -> Self { + Self { + lookup: Arc::new(lookup), + ..self + } + } + + /// The sender with a request deadline of at most `deadline`. It can only narrow the + /// core deadline of 10 s. + #[must_use] + pub fn with_deadline(self, deadline: Duration) -> Self { + Self { + deadline: deadline.min(REQUEST_TIMEOUT), + ..self + } + } + + /// The sender with a body cap of at most `cap` bytes. It can only narrow the core + /// cap of 10 MiB. + #[must_use] + pub fn with_body_cap(self, cap: u64) -> Self { + Self { + body_cap: cap.min(MAX_RESPONSE_BYTES), + ..self + } + } + + /// Send `request` and give its response for the next step. The request ends before + /// `deadline` and before the request deadline of the sender. A redirect answer comes + /// back as it is: the core checks each hop. + /// + /// The sender binds each secret header again for the request origin before it + /// writes the header; a header that does not bind sends nothing. Every failure is a + /// fixed [`TransportFailure`]: no error text of a lower layer is in the response. + #[must_use] + pub fn send(&self, request: &Request, deadline: Instant) -> Response { + match self.try_send(request, deadline) { + Ok(response) => response, + Err(failure) => Response::failed(failure), + } + } + + fn try_send(&self, request: &Request, deadline: Instant) -> Result { + let left = deadline + .checked_duration_since(Instant::now()) + .filter(|left| !left.is_zero()) + .ok_or(TransportFailure::Timeout)?; + let url = request.url(); + let origin = url.origin(); + let uri: Uri = url + .to_text() + .parse() + .map_err(|_| TransportFailure::Connect)?; + // The URI that ureq reads must name the origin that the core checked. + let target = Target::of(&uri) + .filter(|target| names_origin(target, &origin)) + .ok_or(TransportFailure::Connect)?; + let agent = self.agent(left.min(self.deadline), target); + let mut builder = match request.method() { + Method::Get => agent.get(uri), + Method::Head => agent.head(uri), + _ => return Err(TransportFailure::Connect), + }; + for header in request.headers() { + let value = header_text(&self.policy, header.value(), &origin)?; + builder = builder.header(header.name(), value); + } + let response = builder.call().map_err(failure_of)?; + let status = response.status().as_u16(); + let headers = response + .headers() + .iter() + .map(|(name, value)| (name.as_str().to_owned(), value.as_bytes().to_vec())) + .collect(); + let body = read_body(response.into_body(), self.body_cap)?; + Ok(Response::http(status, headers, body)) + } + + /// The agent of one request: no proxy, no redirect, no idle connection, the header + /// cap, the deadline, fixed request headers and a resolver for `target` only. + fn agent(&self, timeout: Duration, target: Target) -> Agent { + let config = Config::builder() + .proxy(None) + .max_redirects(0) + .http_status_as_error(false) + .max_idle_connections(0) + .max_idle_connections_per_host(0) + .max_response_header_size(MAX_RESPONSE_HEADER_BYTES) + .timeout_global(Some(timeout)) + .user_agent(USER_AGENT) + .accept(ACCEPT) + .accept_encoding(ACCEPT_ENCODING) + .tls_config(self.tls.clone()) + .build(); + let connector = ().chain(TcpConnector::default()).chain(RustlsConnector::default()); + let resolver = CheckedResolver { + policy: Arc::clone(&self.policy), + lookup: Arc::clone(&self.lookup), + target, + }; + Agent::with_parts(config, connector, resolver) + } +} + +/// The target is the host and the port of `origin`. +fn names_origin(target: &Target, origin: &Origin) -> bool { + let host = origin.host().to_string(); + let host = host + .strip_prefix('[') + .and_then(|inner| inner.strip_suffix(']')) + .unwrap_or(&host); + target.host == host && target.port == origin.port() +} + +/// The text that a header sends: a text value as it is, or the prefix and then the +/// value of the host secret that binds to `origin`. +fn header_text( + policy: &NetworkPolicy, + value: &HeaderValue, + origin: &Origin, +) -> Result { + match value { + HeaderValue::Text(text) => Ok(text.clone()), + HeaderValue::Secret { name, prefix } => { + let secret = policy + .bind_secret(name, origin) + .map_err(|_| TransportFailure::Connect)?; + Ok(format!("{prefix}{}", secret.expose_for_send())) + } + _ => Err(TransportFailure::Connect), + } +} + +/// The body, read to at most `cap` plus one byte. A longer body fails the request. +fn read_body(body: Body, cap: u64) -> Result, TransportFailure> { + let mut bytes = Vec::new(); + body.into_reader() + .take(cap.saturating_add(1)) + .read_to_end(&mut bytes) + .map_err(|error| failure_of(ureq::Error::from(error)))?; + if u64::try_from(bytes.len()).map_or(true, |len| len > cap) { + return Err(TransportFailure::BodyTooLarge); + } + Ok(bytes) +} + +/// The fixed failure of a ureq error. No error text crosses. +fn failure_of(error: ureq::Error) -> TransportFailure { + match error { + ureq::Error::Timeout(_) | ureq::Error::BodyStalled => TransportFailure::Timeout, + ureq::Error::Other(inner) if inner.is::() => { + TransportFailure::AddressRefused + } + ureq::Error::HostNotFound | ureq::Error::ConnectionFailed | ureq::Error::Other(_) => { + TransportFailure::Connect + } + ureq::Error::Tls(_) + | ureq::Error::Pem(_) + | ureq::Error::Rustls(_) + | ureq::Error::TlsRequired => TransportFailure::Tls, + ureq::Error::LargeResponseHeader(..) => TransportFailure::HeadersTooLarge, + ureq::Error::BodyExceedsLimit(_) => TransportFailure::BodyTooLarge, + ureq::Error::Io(error) => io_failure(&error), + _ => TransportFailure::Protocol, + } +} + +/// The failure of an I/O error. A TLS error of the handshake comes as an I/O error that +/// holds the rustls error. +fn io_failure(error: &io::Error) -> TransportFailure { + if error + .get_ref() + .is_some_and(|inner| inner.is::()) + { + return TransportFailure::Tls; + } + match error.kind() { + io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock => TransportFailure::Timeout, + io::ErrorKind::InvalidData => TransportFailure::Protocol, + _ => TransportFailure::Connect, + } +} diff --git a/crates/mds-fetch/src/tls.rs b/crates/mds-fetch/src/tls.rs new file mode 100644 index 00000000..682d261a --- /dev/null +++ b/crates/mds-fetch/src/tls.rs @@ -0,0 +1,53 @@ +//! The TLS settings of the sender: the ring provider, the Mozilla roots and the roots of +//! the host. The certificate check is always on. + +use std::sync::Arc; + +use rustls::pki_types::pem::PemObject; +use rustls::pki_types::CertificateDer; +use rustls::RootCertStore; +use ureq::tls::{Certificate, RootCerts, TlsConfig, TlsProvider}; + +use crate::SetupError; + +/// The roots of a PEM file that the host gives: one or more `CERTIFICATE` sections. +/// Other sections are skipped. +/// +/// # Errors +/// +/// [`SetupError::RootFile`] when the text is not valid PEM, and [`SetupError::NoRoots`] +/// when it has no certificate. +pub fn parse_pem_roots(pem: &[u8]) -> Result>, SetupError> { + let roots = CertificateDer::pem_slice_iter(pem) + .collect::, _>>() + .map_err(|_| SetupError::RootFile)?; + if roots.is_empty() { + return Err(SetupError::NoRoots); + } + Ok(roots) +} + +/// The TLS settings of each request: the ring provider, set here so that no default of +/// the process applies, and the Mozilla roots plus `host_roots`. Each host root must be +/// a valid trust anchor: ureq skips a bad root with no error, so a bad root fails here. +pub(crate) fn client_config(host_roots: &[CertificateDer<'_>]) -> Result { + let mozilla = webpki_root_certs::TLS_SERVER_ROOT_CERTS; + let mut certs = Vec::with_capacity(mozilla.len() + host_roots.len()); + certs.extend( + mozilla + .iter() + .map(|root| Certificate::from_der(root.as_ref())), + ); + let mut store = RootCertStore::empty(); + for (index, root) in host_roots.iter().enumerate() { + store + .add(root.clone()) + .map_err(|_| SetupError::Root { index })?; + certs.push(Certificate::from_der(root.as_ref()).to_owned()); + } + Ok(TlsConfig::builder() + .provider(TlsProvider::Rustls) + .root_certs(RootCerts::Specific(Arc::new(certs))) + .unversioned_rustls_crypto_provider(Arc::new(rustls::crypto::ring::default_provider())) + .build()) +} diff --git a/crates/mds-fetch/tests/common/mod.rs b/crates/mds-fetch/tests/common/mod.rs new file mode 100644 index 00000000..a63636fa --- /dev/null +++ b/crates/mds-fetch/tests/common/mod.rs @@ -0,0 +1,272 @@ +//! Helpers of the sender tests: requests from the core step API, a listener thread on +//! `127.0.0.1:0` inside the test process, and lookups with fixed answers. +#![allow(dead_code)] + +use std::collections::HashMap; +use std::io::{self, ErrorKind, Read, Write}; +use std::net::{IpAddr, SocketAddr, TcpListener, TcpStream}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::Arc; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +use mds::{ + AllowItem, CompileOptions, FetchContext, FetchState, NetworkPolicy, Request, Response, RunKey, + Step, TransportFailure, VirtualFs, +}; +use mds_fetch::Lookup; + +/// The poll interval of a listener thread. +const POLL: Duration = Duration::from_millis(5); +/// The longest life of a listener thread: its poll loops stop after this time. +const LIFE: Duration = Duration::from_secs(60); +/// The longest request head that a listener reads. +const MAX_HEAD: usize = 64 * 1024; + +/// A policy that allows `items`. +pub fn policy(items: &[&str]) -> Arc { + let items = items + .iter() + .map(|item| AllowItem::parse(item).unwrap()) + .collect(); + Arc::new(NetworkPolicy::new(items).unwrap()) +} + +/// The source of one entry `item` with the request map `fields`. +pub fn entry(fields: &str) -> String { + format!("---\ndata:\n item: {{{fields}}}\n---\n{{{{item.n}}}}\n") +} + +/// The context of a step compile under `policy` with a fixed run key. +pub fn context(policy: &NetworkPolicy) -> FetchContext { + FetchContext::new(policy.clone(), RunKey::from_bytes([7; 32])) +} + +/// The result of a step compile of `main` under `ctx` with `state`. +pub fn step(main: &str, ctx: &FetchContext, state: &FetchState) -> Step { + let fs = VirtualFs::new(HashMap::from([("main.mds".to_owned(), main.to_owned())])); + mds::compile_step_virtual_fs(fs, "main.mds", None, CompileOptions::default(), ctx, state) + .unwrap() +} + +/// The one request that the first step compile of `main` needs. +pub fn request(main: &str, policy: &NetworkPolicy) -> Request { + match step(main, &context(policy), &FetchState::new()) { + Step::Need(mut requests) if requests.len() == 1 => requests.remove(0), + other => panic!("expected one request, got {other:?}"), + } +} + +/// A deadline far enough for every test request. +pub fn soon() -> Instant { + Instant::now() + Duration::from_secs(20) +} + +/// The failure of a failed response. +pub fn failure(response: &Response) -> Option { + match response { + Response::Failed { 0: failure, .. } => Some(*failure), + _ => None, + } +} + +/// The status and the body of an HTTP response. +pub fn http(response: &Response) -> Option<(u16, &[u8])> { + match response { + Response::Http { status, body, .. } => Some((*status, body.as_slice())), + _ => None, + } +} + +/// The value of the response header `name` (lower case). +pub fn header<'a>(response: &'a Response, name: &str) -> Option<&'a [u8]> { + match response { + Response::Http { headers, .. } => headers + .iter() + .find(|(key, _)| key == name) + .map(|(_, value)| value.as_slice()), + _ => None, + } +} + +/// An HTTP/1.1 answer with `status`, the extra header lines `headers` and `body`. +pub fn answer(status: &str, headers: &str, body: &[u8]) -> Vec { + let mut bytes = format!( + "HTTP/1.1 {status}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ) + .into_bytes(); + bytes.extend_from_slice(body); + bytes +} + +/// What a listener does after it reads a request head. +#[derive(Clone)] +pub enum Reply { + /// Write these bytes and close. + Bytes(Arc>), + /// Write these bytes, then write nothing more and keep the connection open until the + /// listener stops. + Stall(Arc>), + /// Write nothing until the listener stops. + Silent, +} + +impl Reply { + pub fn bytes(bytes: Vec) -> Self { + Reply::Bytes(Arc::new(bytes)) + } +} + +/// What a listener saw. +#[derive(Debug, Default)] +pub struct Seen { + /// The accepted connections. + pub connections: usize, + /// The request heads, as text. + pub heads: Vec, +} + +/// A listener thread on `127.0.0.1:0` that gives each connection the same reply. +pub struct Server { + addr: SocketAddr, + stop: Arc, + thread: JoinHandle, +} + +impl Server { + /// A plain HTTP listener. + pub fn start(reply: Reply) -> Self { + Self::start_with(move |stream, stop| serve_plain(stream, &reply, stop)) + } + + /// A listener that runs `serve` on each connection and keeps the head it gives. + pub fn start_with(serve: F) -> Self + where + F: Fn(TcpStream, &AtomicBool) -> Option + Send + 'static, + { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let addr = listener.local_addr().unwrap(); + let stop = Arc::new(AtomicBool::new(false)); + let flag = Arc::clone(&stop); + let thread = thread::spawn(move || { + let mut seen = Seen::default(); + let end = Instant::now() + LIFE; + // Accept until a stop, then take every connection still in the backlog. + while Instant::now() < end { + match listener.accept() { + Ok((stream, _)) => { + seen.connections += 1; + stream.set_nonblocking(false).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + if let Some(head) = serve(stream, &flag) { + seen.heads.push(head); + } + } + Err(error) if error.kind() == ErrorKind::WouldBlock => { + if flag.load(Ordering::SeqCst) { + break; + } + thread::sleep(POLL); + } + Err(error) => panic!("accept failed: {error}"), + } + } + seen + }); + Self { addr, stop, thread } + } + + pub fn port(&self) -> u16 { + self.addr.port() + } + + pub fn addr(&self) -> SocketAddr { + self.addr + } + + /// Stop the listener and give what it saw. The listener takes every connection that + /// completed before the stop, so a count of zero means that no connection came. + pub fn stop(self) -> Seen { + self.stop.store(true, Ordering::SeqCst); + self.thread.join().unwrap() + } +} + +/// Read a request head: the bytes up to the first blank line, at most [`MAX_HEAD`]. +pub fn read_head(stream: &mut impl Read) -> io::Result { + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + while head.len() < MAX_HEAD && !head.ends_with(b"\r\n\r\n") { + if stream.read(&mut byte)? == 0 { + break; + } + head.push(byte[0]); + } + Ok(String::from_utf8_lossy(&head).into_owned()) +} + +/// Give `reply` on `stream` after its head. A stalled or silent reply holds the +/// connection open until the stop. +pub fn reply_on(stream: &mut impl Write, reply: &Reply, stop: &AtomicBool) { + // A client that stops at its body cap closes first: a write error is expected. + match reply { + Reply::Bytes(bytes) => { + let _ = stream.write_all(bytes); + let _ = stream.flush(); + } + Reply::Stall(bytes) => { + let _ = stream.write_all(bytes); + let _ = stream.flush(); + wait_for(stop); + } + Reply::Silent => wait_for(stop), + } +} + +fn wait_for(stop: &AtomicBool) { + let end = Instant::now() + LIFE; + while !stop.load(Ordering::SeqCst) && Instant::now() < end { + thread::sleep(POLL); + } +} + +fn serve_plain(mut stream: TcpStream, reply: &Reply, stop: &AtomicBool) -> Option { + let head = read_head(&mut stream).ok()?; + reply_on(&mut stream, reply, stop); + Some(head) +} + +/// A lookup that gives the IP addresses of answer `n` to call `n`, and the last answer +/// to each later call, each with the asked port. It counts its calls. +pub struct Scripted { + answers: Vec>, + calls: Arc, +} + +impl Scripted { + pub fn new(answers: &[&[&str]]) -> (Self, Arc) { + let calls = Arc::new(AtomicUsize::new(0)); + let answers = answers + .iter() + .map(|answer| answer.iter().map(|ip| ip.parse().unwrap()).collect()) + .collect(); + let lookup = Self { + answers, + calls: Arc::clone(&calls), + }; + (lookup, calls) + } +} + +impl Lookup for Scripted { + fn lookup(&self, host: &str, port: u16, _: Duration) -> io::Result> { + assert_eq!(host, "api.test", "the lookup is for the request host"); + let call = self.calls.fetch_add(1, Ordering::SeqCst); + let answer = &self.answers[call.min(self.answers.len() - 1)]; + Ok(answer.iter().map(|ip| SocketAddr::new(*ip, port)).collect()) + } +} diff --git a/crates/mds-fetch/tests/plain.rs b/crates/mds-fetch/tests/plain.rs new file mode 100644 index 00000000..5c2e6362 --- /dev/null +++ b/crates/mds-fetch/tests/plain.rs @@ -0,0 +1,413 @@ +//! The plain HTTP sender: the address check of each lookup answer, one lookup per +//! request, no redirect, the deadline, the body and header caps and the fixed request +//! headers. Every listener is a thread on `127.0.0.1:0` in this process. + +mod common; + +use std::sync::atomic::Ordering; +use std::time::{Duration, Instant}; + +use common::{ + answer, entry, failure, header, http, policy, read_head, reply_on, request, soon, step, Reply, + Scripted, Server, +}; +use mds::{FetchState, Step, TransportFailure, MAX_RESPONSE_BYTES}; +use mds_fetch::Fetcher; + +const OK: &[u8] = b"{\"n\": 1}"; + +/// A listener that answers each request with 200 and [`OK`]. +fn ok_server() -> Server { + Server::start(Reply::bytes(answer("200 OK", "", OK))) +} + +/// A request for `api.test` on the port of `server`, with the allow items of that name +/// and of `127.0.0.1` with the port, so a lookup answer of `127.0.0.1` can pass. +fn named(server: &Server) -> (std::sync::Arc, mds::Request) { + let port = server.port(); + let policy = policy(&[ + &format!("http://api.test:{port}"), + &format!("127.0.0.1:{port}"), + ]); + let request = request(&entry(&format!("url: 'http://api.test:{port}/x'")), &policy); + (policy, request) +} + +/// TP-86: a lookup answer in a refused range fails with the address failure and opens no +/// connection: a mapped IPv6 loopback, the IPv6 loopback, an IPv6 link-local and a +/// private IPv4 address. One refused address in an answer refuses the request. Control: +/// the answer `127.0.0.1`, with that exact address and port listed, connects once. +#[test] +fn a_refused_lookup_answer_fails_and_opens_no_connection() { + for answer in [ + &["::ffff:127.0.0.1"][..], + &["::1"], + &["fe80::1"], + &["10.0.0.1"], + &["127.0.0.1", "10.0.0.1"], + ] { + let server = ok_server(); + let (policy, request) = named(&server); + let (lookup, calls) = Scripted::new(&[answer]); + let fetcher = Fetcher::new(policy, &[]).unwrap().with_lookup(lookup); + let response = fetcher.send(&request, soon()); + assert_eq!( + failure(&response), + Some(TransportFailure::AddressRefused), + "{answer:?}" + ); + assert_eq!(calls.load(Ordering::SeqCst), 1, "{answer:?}"); + assert_eq!(server.stop().connections, 0, "{answer:?}"); + } + + let server = ok_server(); + let (policy, request) = named(&server); + let (lookup, calls) = Scripted::new(&[&["127.0.0.1"]]); + let fetcher = Fetcher::new(policy, &[]).unwrap().with_lookup(lookup); + let response = fetcher.send(&request, soon()); + assert_eq!(http(&response), Some((200, OK))); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(server.stop().connections, 1); +} + +/// An IP address host needs no lookup: the lookup is not called, and the request +/// connects once to that address. +#[test] +fn an_ip_address_host_needs_no_lookup() { + let server = ok_server(); + let port = server.port(); + let policy = policy(&[&format!("http://127.0.0.1:{port}")]); + let request = request( + &entry(&format!("url: 'http://127.0.0.1:{port}/x'")), + &policy, + ); + let (lookup, calls) = Scripted::new(&[&["10.0.0.1"]]); + let fetcher = Fetcher::new(policy, &[]).unwrap().with_lookup(lookup); + assert_eq!(http(&fetcher.send(&request, soon())), Some((200, OK))); + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert_eq!(server.stop().connections, 1); +} + +/// TP-87: a lookup that changes its answer is called once per request, and the +/// connection goes to the address that passed the check. The next request looks up +/// again, so the new answer is checked and refused. +#[test] +fn a_changing_lookup_is_called_once_and_the_checked_address_connects() { + let server = ok_server(); + let (policy, request) = named(&server); + let (lookup, calls) = Scripted::new(&[&["127.0.0.1"], &["10.0.0.1"]]); + let fetcher = Fetcher::new(policy, &[]).unwrap().with_lookup(lookup); + assert_eq!(http(&fetcher.send(&request, soon())), Some((200, OK))); + assert_eq!(calls.load(Ordering::SeqCst), 1); + let again = fetcher.send(&request, soon()); + assert_eq!(failure(&again), Some(TransportFailure::AddressRefused)); + assert_eq!(calls.load(Ordering::SeqCst), 2); + assert_eq!(server.stop().connections, 1); +} + +/// TP-87: a 302 comes back as it is, with its `Location`. The sender sends one request +/// and follows nothing: the core checks each hop. +#[test] +fn a_redirect_comes_back_unfollowed() { + let location = "Location: http://169.254.169.254/latest\r\n"; + let server = Server::start(Reply::bytes(answer("302 Found", location, b""))); + let port = server.port(); + let policy = policy(&[&format!("http://127.0.0.1:{port}")]); + let request = request( + &entry(&format!("url: 'http://127.0.0.1:{port}/x'")), + &policy, + ); + let response = Fetcher::new(policy, &[]).unwrap().send(&request, soon()); + assert_eq!(http(&response), Some((302, &b""[..]))); + assert_eq!( + header(&response, "location"), + Some(&b"http://169.254.169.254/latest"[..]) + ); + let seen = server.stop(); + assert_eq!(seen.connections, 1); + assert!( + seen.heads[0].starts_with("GET /x HTTP/1.1\r\n"), + "{:?}", + seen.heads + ); +} + +/// A lookup answer with more addresses than the cap fails the request and opens no +/// connection. Control: an answer at the cap connects. +#[test] +fn a_lookup_answer_past_the_cap_fails() { + for (count, connections) in [ + (mds::MAX_RESOLVED_ADDRS + 1, 0), + (mds::MAX_RESOLVED_ADDRS, 1), + ] { + let server = ok_server(); + let (policy, request) = named(&server); + let answer = vec!["127.0.0.1"; count]; + let (lookup, _) = Scripted::new(&[&answer]); + let fetcher = Fetcher::new(policy, &[]).unwrap().with_lookup(lookup); + let response = fetcher.send(&request, soon()); + if connections == 0 { + assert_eq!( + failure(&response), + Some(TransportFailure::Connect), + "{count}" + ); + } else { + assert_eq!(http(&response), Some((200, OK)), "{count}"); + } + assert_eq!(server.stop().connections, connections, "{count}"); + } +} + +/// TP-95: a listener that never answers gives the timeout at the narrowed deadline, and +/// a deadline that passed sends nothing. Control: the same request with time left +/// connects. +#[test] +fn a_silent_server_times_out_at_the_narrowed_deadline() { + let server = Server::start(Reply::Silent); + let port = server.port(); + let policy = policy(&[&format!("http://127.0.0.1:{port}")]); + let request = request( + &entry(&format!("url: 'http://127.0.0.1:{port}/x'")), + &policy, + ); + let fetcher = Fetcher::new(policy, &[]) + .unwrap() + .with_deadline(Duration::from_millis(300)); + let start = Instant::now(); + let response = fetcher.send(&request, soon()); + let took = start.elapsed(); + assert_eq!(failure(&response), Some(TransportFailure::Timeout)); + assert!(took >= Duration::from_millis(250), "{took:?}"); + assert!(took < Duration::from_secs(5), "{took:?}"); + let past = fetcher.send(&request, Instant::now()); + assert_eq!(failure(&past), Some(TransportFailure::Timeout)); + assert_eq!(server.stop().connections, 1); +} + +/// TP-95: a listener that waits inside the narrowed deadline and then answers gives its +/// 200 and body. The wait is 100 ms of a 1 s deadline, so a loaded runner keeps a wide +/// margin. The silent listener above is the case past the deadline. +#[test] +fn a_late_answer_inside_the_narrowed_deadline_passes() { + const WAIT: Duration = Duration::from_millis(100); + let reply = Reply::bytes(answer("200 OK", "", OK)); + let server = Server::start_with(move |mut stream, stop| { + let head = read_head(&mut stream).ok()?; + std::thread::sleep(WAIT); + reply_on(&mut stream, &reply, stop); + Some(head) + }); + let port = server.port(); + let policy = policy(&[&format!("http://127.0.0.1:{port}")]); + let request = request( + &entry(&format!("url: 'http://127.0.0.1:{port}/x'")), + &policy, + ); + let fetcher = Fetcher::new(policy, &[]) + .unwrap() + .with_deadline(Duration::from_secs(1)); + let start = Instant::now(); + let response = fetcher.send(&request, soon()); + let took = start.elapsed(); + assert_eq!(http(&response), Some((200, OK))); + assert!(took >= WAIT, "{took:?}"); + assert_eq!(server.stop().connections, 1); +} + +/// TP-95: a body of exactly the cap passes and a body one byte over fails. +#[test] +fn the_body_cap_passes_at_the_cap_and_fails_one_byte_over() { + for (size, passes) in [(16, true), (17, false)] { + let body = vec![b'a'; size]; + let server = Server::start(Reply::bytes(answer("200 OK", "", &body))); + let port = server.port(); + let policy = policy(&[&format!("http://127.0.0.1:{port}")]); + let request = request( + &entry(&format!("url: 'http://127.0.0.1:{port}/x'")), + &policy, + ); + let response = Fetcher::new(policy, &[]) + .unwrap() + .with_body_cap(16) + .send(&request, soon()); + if passes { + assert_eq!(http(&response), Some((200, body.as_slice()))); + } else { + assert_eq!(failure(&response), Some(TransportFailure::BodyTooLarge)); + } + server.stop(); + } +} + +/// The sender stops its body read one byte past the cap: a server that sends the cap +/// plus one byte of a longer body and then stalls gives the body failure at once, not +/// the timeout. Control: the same stall at the cap gives the timeout. +#[test] +fn the_body_read_stops_one_byte_past_the_cap() { + let head = "HTTP/1.1 200 OK\r\nContent-Length: 1000\r\n\r\n"; + for (size, expected) in [ + (17, TransportFailure::BodyTooLarge), + (16, TransportFailure::Timeout), + ] { + let mut bytes = head.as_bytes().to_vec(); + bytes.extend(vec![b'a'; size]); + let server = Server::start(Reply::Stall(std::sync::Arc::new(bytes))); + let port = server.port(); + let policy = policy(&[&format!("http://127.0.0.1:{port}")]); + let request = request( + &entry(&format!("url: 'http://127.0.0.1:{port}/x'")), + &policy, + ); + let response = Fetcher::new(policy, &[]) + .unwrap() + .with_body_cap(16) + .with_deadline(Duration::from_secs(2)) + .send(&request, soon()); + assert_eq!(failure(&response), Some(expected), "{size}"); + server.stop(); + } +} + +/// TP-95: the core body cap binds by default, and a wider cap can not open it: a body +/// of exactly 10 MiB passes, and one byte more fails. +#[test] +fn the_core_body_cap_binds_and_can_not_widen() { + let cap = usize::try_from(MAX_RESPONSE_BYTES).unwrap(); + for (size, passes) in [(cap, true), (cap + 1, false)] { + let server = Server::start(Reply::bytes(answer("200 OK", "", &vec![b'a'; size]))); + let port = server.port(); + let policy = policy(&[&format!("http://127.0.0.1:{port}")]); + let request = request( + &entry(&format!("url: 'http://127.0.0.1:{port}/x'")), + &policy, + ); + let response = Fetcher::new(policy, &[]) + .unwrap() + .with_body_cap(u64::MAX) + .send(&request, soon()); + if passes { + assert_eq!(http(&response).map(|(_, body)| body.len()), Some(size)); + } else { + assert_eq!(failure(&response), Some(TransportFailure::BodyTooLarge)); + } + server.stop(); + } +} + +/// Response headers past the header cap fail the request. Control: short headers pass. +#[test] +fn response_headers_past_the_cap_fail() { + let long = format!("X-Pad: {}\r\n", "a".repeat(mds::MAX_RESPONSE_HEADER_BYTES)); + for (headers, passes) in [(long.as_str(), false), ("X-Pad: a\r\n", true)] { + let server = Server::start(Reply::bytes(answer("200 OK", headers, OK))); + let port = server.port(); + let policy = policy(&[&format!("http://127.0.0.1:{port}")]); + let request = request( + &entry(&format!("url: 'http://127.0.0.1:{port}/x'")), + &policy, + ); + let response = Fetcher::new(policy, &[]).unwrap().send(&request, soon()); + if passes { + assert_eq!(http(&response), Some((200, OK))); + } else { + assert_eq!(failure(&response), Some(TransportFailure::HeadersTooLarge)); + } + server.stop(); + } +} + +/// Each request sends the fixed `User-Agent`, `Accept` and `Accept-Encoding` and the +/// declared headers, and no proxy header. +#[test] +fn a_request_sends_the_fixed_and_the_declared_headers() { + let server = ok_server(); + let port = server.port(); + let policy = policy(&[&format!("http://127.0.0.1:{port}")]); + let fields = format!("url: 'http://127.0.0.1:{port}/x?q=1', headers: {{X-Trace: abc}}"); + let request = request(&entry(&fields), &policy); + assert_eq!( + http(&Fetcher::new(policy, &[]).unwrap().send(&request, soon())), + Some((200, OK)) + ); + let head = server.stop().heads.remove(0).to_ascii_lowercase(); + assert!(head.starts_with("get /x?q=1 http/1.1\r\n"), "{head}"); + for line in [ + concat!("user-agent: mds-fetch/", env!("CARGO_PKG_VERSION")), + "accept: application/json, application/yaml, text/plain", + "accept-encoding: identity", + "x-trace: abc", + ] { + assert!(head.contains(&format!("\r\n{line}\r\n")), "{line}: {head}"); + } + assert!(!head.contains("proxy"), "{head}"); +} + +/// A HEAD request sends HEAD and gives an empty body. +#[test] +fn a_head_request_gives_an_empty_body() { + let server = Server::start(Reply::bytes( + b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: close\r\n\r\n".to_vec(), + )); + let port = server.port(); + let policy = policy(&[&format!("http://127.0.0.1:{port}")]); + let fields = format!("url: 'http://127.0.0.1:{port}/x', method: HEAD, envelope: true"); + let request = request(&entry(&fields), &policy); + let response = Fetcher::new(policy, &[]).unwrap().send(&request, soon()); + assert_eq!(http(&response), Some((200, &b""[..]))); + assert!(server.stop().heads[0].starts_with("HEAD /x HTTP/1.1\r\n")); +} + +/// The response of the sender completes the step compile that asked for it. +#[test] +fn a_sent_response_completes_the_step_compile() { + let server = ok_server(); + let port = server.port(); + let policy = policy(&[&format!("http://127.0.0.1:{port}")]); + let main = entry(&format!("url: 'http://127.0.0.1:{port}/x'")); + let ctx = common::context(&policy); + let Step::Need(requests) = step(&main, &ctx, &FetchState::new()) else { + panic!("expected requests"); + }; + let fetcher = Fetcher::new(policy, &[]).unwrap(); + let state = requests.iter().fold(FetchState::new(), |state, request| { + state + .with_response(request.id(), fetcher.send(request, soon())) + .unwrap() + }); + let Step::Done(result) = step(&main, &ctx, &state) else { + panic!("expected a finished compile"); + }; + assert!(result.into_markdown().unwrap().ends_with("1\n")); + assert_eq!(server.stop().connections, 1); +} + +/// Each run key is new: the identity of a request with a secret header differs between +/// two keys. Control: the same key bytes give the same identity. +#[test] +fn each_run_key_is_new() { + let origin = mds::AllowItem::parse("api.test").unwrap().origin(); + let value = mds::SecretValue::new("planted-value".into()).unwrap(); + let policy = mds::NetworkPolicy::new(vec![mds::AllowItem::parse("api.test").unwrap()]) + .unwrap() + .with_secret(mds::Secret::new("token", value, origin).unwrap()) + .unwrap(); + let main = entry( + "url: 'https://api.test/x', headers: {Authorization: {secret: token, prefix: 'Bearer '}}", + ); + let id = |key: mds::RunKey| match step( + &main, + &mds::FetchContext::new(policy.clone(), key), + &FetchState::new(), + ) { + Step::Need(requests) => requests[0].id(), + other => panic!("expected requests, got {other:?}"), + }; + let first = id(mds_fetch::run_key().unwrap()); + let second = id(mds_fetch::run_key().unwrap()); + assert_ne!(first, second); + assert_eq!( + id(mds::RunKey::from_bytes([3; 32])), + id(mds::RunKey::from_bytes([3; 32])) + ); +} diff --git a/crates/mds-fetch/tests/proxy.rs b/crates/mds-fetch/tests/proxy.rs new file mode 100644 index 00000000..15110d50 --- /dev/null +++ b/crates/mds-fetch/tests/proxy.rs @@ -0,0 +1,124 @@ +//! The sender uses no proxy. The test runs itself again as a child process with every +//! proxy variable set to a second listener; that listener must see no connection from +//! the sender. Controls: a direct connection to the second listener is seen, and a +//! default ureq agent in the same environment does reach it. + +mod common; + +use std::env; +use std::io::ErrorKind; +use std::net::{TcpListener, TcpStream}; +use std::process::Command; +use std::thread; +use std::time::{Duration, Instant}; + +use common::{answer, entry, http, policy, request, soon, Reply, Server}; +use mds_fetch::Fetcher; + +/// The variable that tells the child process its part. +const CHILD: &str = "MDS_FETCH_PROXY_CHILD"; +/// The name of this test, for the child process. +const NAME: &str = "proxy_variables_do_not_reach_the_sender"; +/// Every proxy variable that ureq reads, in both cases. +const PROXY_VARS: [&str; 6] = [ + "HTTPS_PROXY", + "https_proxy", + "HTTP_PROXY", + "http_proxy", + "ALL_PROXY", + "all_proxy", +]; +const OK: &[u8] = b"{\"n\": 1}"; + +#[test] +fn proxy_variables_do_not_reach_the_sender() { + if let Ok(part) = env::var(CHILD) { + return child(&part); + } + let proxy = TcpListener::bind("127.0.0.1:0").unwrap(); + proxy.set_nonblocking(true).unwrap(); + let url = format!("http://{}", proxy.local_addr().unwrap()); + + // Control: the second listener sees a direct connection. + drop(TcpStream::connect(proxy.local_addr().unwrap()).unwrap()); + assert_eq!(accepted(&proxy), 1); + + run_child("sender", &url); + assert_eq!(accepted(&proxy), 0, "the sender connected to the proxy"); + + // Control: the proxy variables reach a default ureq agent in the child. + run_child("default", &url); + assert_eq!(accepted(&proxy), 1, "the control did not reach the proxy"); +} + +/// Run this test as a child for `part`, with each proxy variable set to `url` and no +/// proxy exception, and check that the child ran its part. +fn run_child(part: &str, url: &str) { + let mut command = Command::new(env::current_exe().unwrap()); + command + .args(["--exact", NAME, "--nocapture"]) + .env(CHILD, part) + .env_remove("NO_PROXY") + .env_remove("no_proxy"); + for var in PROXY_VARS { + command.env(var, url); + } + let output = command.output().unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success(), + "{part}: {stdout}{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!( + stdout.contains(&format!("child part done: {part}")), + "{stdout}" + ); +} + +/// The connections in the backlog of `listener`, after a short wait for late ones. +fn accepted(listener: &TcpListener) -> usize { + let mut count = 0; + let end = Instant::now() + Duration::from_millis(200); + while Instant::now() < end { + match listener.accept() { + Ok(_) => count += 1, + Err(error) if error.kind() == ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(5)); + } + Err(error) => panic!("accept failed: {error}"), + } + } + count +} + +/// The part of a child process: the sender sends one request to a direct listener, or +/// a default ureq agent tries one request, which goes to the proxy. +fn child(part: &str) { + for var in PROXY_VARS { + assert!(env::var(var).is_ok(), "{var} is not set"); + } + let server = Server::start(Reply::bytes(answer("200 OK", "", OK))); + let port = server.port(); + let target = format!("http://127.0.0.1:{port}/x"); + match part { + "sender" => { + let policy = policy(&[&format!("http://127.0.0.1:{port}")]); + let request = request(&entry(&format!("url: '{target}'")), &policy); + let response = Fetcher::new(policy, &[]).unwrap().send(&request, soon()); + assert_eq!(http(&response), Some((200, OK))); + assert_eq!(server.stop().connections, 1); + } + "default" => { + let agent: ureq::Agent = ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_millis(500))) + .build() + .into(); + // The proxy never answers, so the request fails after it connects there. + assert!(agent.get(&target).call().is_err()); + assert_eq!(server.stop().connections, 0); + } + other => panic!("unknown child part {other}"), + } + println!("child part done: {part}"); +} diff --git a/crates/mds-fetch/tests/tls.rs b/crates/mds-fetch/tests/tls.rs new file mode 100644 index 00000000..e4ecf3f2 --- /dev/null +++ b/crates/mds-fetch/tests/tls.rs @@ -0,0 +1,216 @@ +//! The TLS sender: the certificate check, the host roots and the secret header. Each +//! test makes its CA, certificate and key at test time, so the repository holds no key. +//! The server is a rustls thread on `127.0.0.1:0` in this process. + +mod common; + +use std::net::TcpStream; +use std::sync::atomic::AtomicBool; +use std::sync::Arc; + +use common::{ + answer, entry, failure, http, read_head, reply_on, request, soon, Reply, Seen, Server, +}; +use mds::{AllowItem, NetworkPolicy, Secret, SecretValue, TransportFailure}; +use mds_fetch::{parse_pem_roots, CertificateDer, Fetcher, SetupError}; +use rcgen::{BasicConstraints, CertificateParams, CertifiedIssuer, IsCa, KeyPair, KeyUsagePurpose}; +use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer}; +use rustls::{ServerConfig, ServerConnection, StreamOwned}; + +const OK: &[u8] = b"{\"n\": 1}"; + +/// A test CA, and a server certificate and key that the CA signed. +struct Pki { + ca: CertificateDer<'static>, + ca_pem: String, + server: CertificateDer<'static>, + key: PrivateKeyDer<'static>, +} + +/// A CA and a server certificate for the IP address `server_ip`, made now. +fn pki(server_ip: &str) -> Pki { + let mut ca_params = CertificateParams::new(Vec::::new()).unwrap(); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + ca_params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; + let ca = CertifiedIssuer::self_signed(ca_params, KeyPair::generate().unwrap()).unwrap(); + let key = KeyPair::generate().unwrap(); + let server = CertificateParams::new(vec![server_ip.to_owned()]) + .unwrap() + .signed_by(&key, &ca) + .unwrap(); + Pki { + ca: ca.der().clone(), + ca_pem: ca.pem(), + server: server.der().clone(), + key: PrivatePkcs8KeyDer::from(key.serialize_der()).into(), + } +} + +/// A TLS listener on `127.0.0.1:0` that presents the server certificate of `pki` and +/// answers each request with 200 and [`OK`]. +fn tls_server(pki: &Pki) -> Server { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let config = ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![pki.server.clone()], pki.key.clone_key()) + .unwrap(); + let config = Arc::new(config); + let reply = Reply::bytes(answer("200 OK", "", OK)); + Server::start_with(move |stream: TcpStream, stop: &AtomicBool| { + let connection = ServerConnection::new(Arc::clone(&config)).ok()?; + let mut tls = StreamOwned::new(connection, stream); + // A failed handshake ends the read: the client refused the certificate. + let head = read_head(&mut tls).ok().filter(|head| !head.is_empty())?; + reply_on(&mut tls, &reply, stop); + Some(head) + }) +} + +/// A policy for `https://127.0.0.1:`, with the secret `token` for that origin. +fn tls_policy(port: u16) -> Arc { + let item = AllowItem::parse(&format!("https://127.0.0.1:{port}")).unwrap(); + let value = SecretValue::new("planted-value".into()).unwrap(); + let secret = Secret::new("token", value, item.origin()).unwrap(); + Arc::new( + NetworkPolicy::new(vec![item]) + .unwrap() + .with_secret(secret) + .unwrap(), + ) +} + +/// Send one GET to `server` with `roots` as the host roots. +fn send_with_roots(server: &Server, roots: &[CertificateDer<'_>]) -> mds::Response { + let port = server.port(); + let policy = tls_policy(port); + let request = request( + &entry(&format!("url: 'https://127.0.0.1:{port}/x'")), + &policy, + ); + Fetcher::new(policy, roots).unwrap().send(&request, soon()) +} + +/// TP-98: a server whose certificate chains to a CA that the sender does not know fails +/// with the TLS failure, and no request reaches it. Control: with the CA as a host +/// root, the body arrives. +#[test] +fn an_unknown_root_fails_and_a_host_root_passes() { + let pki = pki("127.0.0.1"); + let server = tls_server(&pki); + let response = send_with_roots(&server, &[]); + assert_eq!(failure(&response), Some(TransportFailure::Tls)); + let seen: Seen = server.stop(); + assert_eq!((seen.connections, seen.heads.len()), (1, 0)); + + let server = tls_server(&pki); + let response = send_with_roots(&server, std::slice::from_ref(&pki.ca)); + assert_eq!(http(&response), Some((200, OK))); + assert_eq!(server.stop().heads.len(), 1); +} + +/// A certificate for another address fails the host check, also with its CA as a host +/// root. Control: the certificate for the request address passes. +#[test] +fn a_certificate_for_another_address_fails() { + for (server_ip, passes) in [("127.0.0.2", false), ("127.0.0.1", true)] { + let pki = pki(server_ip); + let server = tls_server(&pki); + let response = send_with_roots(&server, std::slice::from_ref(&pki.ca)); + if passes { + assert_eq!(http(&response), Some((200, OK))); + } else { + assert_eq!(failure(&response), Some(TransportFailure::Tls)); + } + server.stop(); + } +} + +/// A secret header sends its prefix and then the value of the host secret for the +/// request origin, over TLS only. The request head holds the value, so each assertion +/// message is fixed text. +#[test] +fn a_secret_header_sends_the_prefix_and_the_value() { + let pki = pki("127.0.0.1"); + let server = tls_server(&pki); + let port = server.port(); + let policy = tls_policy(port); + let fields = format!( + "url: 'https://127.0.0.1:{port}/x', \ + headers: {{Authorization: {{secret: token, prefix: 'Bearer '}}}}" + ); + let request = request(&entry(&fields), &policy); + assert!( + !format!("{request:?}").contains("planted-value"), + "Debug of the request must not show the secret value" + ); + let response = Fetcher::new(policy, std::slice::from_ref(&pki.ca)) + .unwrap() + .send(&request, soon()); + assert_eq!( + http(&response), + Some((200, OK)), + "the server must answer the request" + ); + let head = server.stop().heads.remove(0).to_ascii_lowercase(); + assert!( + head.contains("\r\nauthorization: bearer planted-value\r\n"), + "the request must carry the prefix and the value" + ); +} + +/// A sender with a policy that has no secret for the request origin sends nothing for +/// a secret header. Control: the policy of the step compile sends it. +#[test] +fn a_secret_header_that_does_not_bind_sends_nothing() { + let pki = pki("127.0.0.1"); + let server = tls_server(&pki); + let port = server.port(); + let policy = tls_policy(port); + let fields = format!( + "url: 'https://127.0.0.1:{port}/x', \ + headers: {{Authorization: {{secret: token, prefix: 'Bearer '}}}}" + ); + let request = request(&entry(&fields), &policy); + let other = Arc::new( + NetworkPolicy::new(vec![ + AllowItem::parse(&format!("https://127.0.0.1:{port}")).unwrap() + ]) + .unwrap(), + ); + let response = Fetcher::new(other, std::slice::from_ref(&pki.ca)) + .unwrap() + .send(&request, soon()); + assert_eq!(failure(&response), Some(TransportFailure::Connect)); + let response = Fetcher::new(policy, std::slice::from_ref(&pki.ca)) + .unwrap() + .send(&request, soon()); + assert_eq!(http(&response), Some((200, OK))); + assert_eq!(server.stop().connections, 1); +} + +/// A host root must be a valid trust anchor, and a root file must be PEM with at least +/// one certificate. Control: the PEM of the test CA gives that one root. +#[test] +fn host_roots_are_checked() { + let policy = tls_policy(443); + let bad = CertificateDer::from(vec![1, 2, 3]); + let error = Fetcher::new(Arc::clone(&policy), &[bad]).unwrap_err(); + assert_eq!(error, SetupError::Root { index: 0 }); + assert_eq!( + error.to_string(), + "root 0 of the host is not a valid trust anchor" + ); + assert_eq!( + parse_pem_roots(b"no roots here\n"), + Err(SetupError::NoRoots) + ); + let broken = b"-----BEGIN CERTIFICATE-----\n!!!!\n-----END CERTIFICATE-----\n"; + assert_eq!(parse_pem_roots(broken), Err(SetupError::RootFile)); + + let pki = pki("127.0.0.1"); + let roots = parse_pem_roots(pki.ca_pem.as_bytes()).unwrap(); + assert_eq!(roots, vec![pki.ca.clone()]); + assert!(Fetcher::new(policy, &roots).is_ok()); +} diff --git a/crates/mds-napi/src/lib.rs b/crates/mds-napi/src/lib.rs index 77bbfb44..178ae2bb 100644 --- a/crates/mds-napi/src/lib.rs +++ b/crates/mds-napi/src/lib.rs @@ -20,9 +20,10 @@ //! Errors thrown at the napi boundary carry a `code` property (set via //! N-API `napi_create_error` with an explicit code string). Codes that //! originate inside `mds-core` (e.g. `"mds::syntax"`) are defined by -//! [`mds::MdsError`]. The following codes are synthesised here. Only -//! `mds::invalid_options` is **binding-only**: the core crate also returns -//! `mds::internal` and `mds::resource_limit`. +//! [`mds::MdsError`]. The following codes are synthesised here. None of them is +//! binding-only: the core crate also returns `mds::internal` and +//! `mds::resource_limit`, and `mds::invalid_options` for the fetch state of a step +//! compile. //! //! | Code | Meaning | //! |------------------------|--------------------------------------------------------------------------------| diff --git a/crates/mds-python/src/lib.rs b/crates/mds-python/src/lib.rs index c7e71385..27fb9f40 100644 --- a/crates/mds-python/src/lib.rs +++ b/crates/mds-python/src/lib.rs @@ -31,9 +31,9 @@ //! //! Every failure raises [`MdsError`] (a native, catchable `markdown_script.MdsError`) with a //! `.code`. Codes originating in `mds-core` (e.g. `"mds::syntax"`) are defined by -//! [`mds::MdsError`]. Three codes are synthesised here. Only `mds::invalid_options` -//! is **binding-only**: the core crate also returns `mds::internal` and -//! `mds::resource_limit`. +//! [`mds::MdsError`]. Three codes are synthesised here. None of them is binding-only: +//! the core crate also returns `mds::internal` and `mds::resource_limit`, and +//! `mds::invalid_options` for the fetch state of a step compile. //! //! | Code | Meaning | //! |------------------------|----------------------------------------------------------------------------------| diff --git a/crates/mds-wasm/src/lib.rs b/crates/mds-wasm/src/lib.rs index 75521cd4..86ab8c30 100644 --- a/crates/mds-wasm/src/lib.rs +++ b/crates/mds-wasm/src/lib.rs @@ -9,8 +9,9 @@ //! Errors thrown at the WASM boundary carry a `code` property. Codes that //! originate inside `mds-core` (e.g. `"mds::syntax"`) are defined by //! [`mds::MdsError`]. The following codes are synthesised here. Only -//! `mds::invalid_options` and `mds::filename_collision` are **binding-only**: -//! the core crate also returns `mds::internal` and `mds::resource_limit`. +//! `mds::filename_collision` is **binding-only**: the core crate also returns +//! `mds::internal` and `mds::resource_limit`, and `mds::invalid_options` for the +//! fetch state of a step compile. //! //! | Code | Meaning | //! |---------------------------|--------------------------------------------------------------------------------| diff --git a/deny.toml b/deny.toml index 4d789051..a3ef86d6 100644 --- a/deny.toml +++ b/deny.toml @@ -41,6 +41,10 @@ exceptions = [ { crate = "foldhash", allow = ["Zlib"] }, # Accept the LLVM exception for the target triple crate. { crate = "target-lexicon", allow = ["Apache-2.0 WITH LLVM-exception"] }, + # Accept the permissive data license for the Mozilla root list of the sender. + { crate = "webpki-root-certs", allow = ["CDLA-Permissive-2.0"] }, + # Accept BSD-3-Clause terms for the constant-time crate of the TLS library. + { crate = "subtle", allow = ["BSD-3-Clause"] }, ] [licenses.private] @@ -66,8 +70,14 @@ skip = [ { crate = "unicode-width@0.1.14", reason = "miette uses 0.1 and textwrap uses 0.2" }, { crate = "windows-sys@0.60.2", reason = "notify uses 0.60 and ctrlc uses 0.61" }, { crate = "wit-bindgen@0.51.0", reason = "wasip3 uses 0.51 and wasip2 uses 0.57" }, + { crate = "getrandom@0.2.17", reason = "ring uses 0.2 and the workspace uses 0.4" }, + { crate = "windows-sys@0.52.0", reason = "ring uses 0.52, notify uses 0.60 and ctrlc uses 0.61" }, +] +# The windows-targets 0.52 tree holds only windows-targets and its eight windows_* target +# crates, all at 0.52.6 and with no other dependency. +skip-tree = [ + { crate = "windows-targets@0.52.6", reason = "ring uses 0.52 through windows-sys and notify uses 0.53" }, ] -skip-tree = [] [bans.workspace-dependencies] duplicates = "deny" diff --git a/examples/linting/README.md b/examples/linting/README.md index 8b8873ea..49578b17 100644 --- a/examples/linting/README.md +++ b/examples/linting/README.md @@ -1,6 +1,6 @@ # Linting demo -`mds lint` checks a template against eleven static-analysis rules. This directory +`mds lint` checks a template against thirteen static-analysis rules. This directory shows lint reports, automatic fixes and rule severity overrides in `mds.json`. `demo.mds` compiles cleanly (`mds build examples/linting/demo.mds`) but deliberately @@ -25,7 +25,7 @@ The file key does not suppress warnings in unmarked fences. Run the commands below from the repository root. -## The eleven rules +## The thirteen rules | Rule | Default severity | Tier | `--fix` behavior | |------|------------------|------|------------------| @@ -39,6 +39,8 @@ Run the commands below from the repository root. | `unused-variable` | warn | C | Never auto-fixed (report-only). | | `redundant-else` | warn | C | Never auto-fixed (report-only). | | `literal-directive` | warn | C | Never auto-fixed (report-only). | +| `insecure-data-origin` | warn | C | Never auto-fixed (report-only). | +| `literal-credential-header` | warn | C | Never auto-fixed (report-only). | | `shadow-variable` | off | C | Never auto-fixed; off by default (see config demo). | **Tiers.** Tier **A** fixes apply always (gated by a re-verify recompile); Tier **B** diff --git a/packages/mds/__test__/data-scanner.spec.mjs b/packages/mds/__test__/data-scanner.spec.mjs index 564d3791..277764cd 100644 --- a/packages/mds/__test__/data-scanner.spec.mjs +++ b/packages/mds/__test__/data-scanner.spec.mjs @@ -564,7 +564,7 @@ describe('WASM backend data pre-scanner (#405)', () => { await put(sub, 'big.json', `"${'a'.repeat(MAX_DATA_FILE_BYTES - 2)}"`); // An entry with 254 references in its body, one in its URL and one in a header. const refs = (extra) => - `---\nk: v\ndata:\n a: ./a.json\n b:\n url: 'https://example.com/{{k}}'\n headers:\n X-Key: '{{k}}'\n` + + `---\nk: v\ndata:\n a: ./a.json\n b:\n url: 'https://example.com/{{k}}'\n method: POST\n headers:\n X-Key: '{{k}}'\n` + ` body:\n text: '${'{{k}}'.repeat(254)}${extra}'\n---\n{{a}}\n`; const rules = [ ['root', dataModule({ d: '../outside.json' }, '{{d}}\n'), dataModule({ d: '../outside.json' }, '{{d}}\n')], diff --git a/packages/mds/__test__/lint.spec.mjs b/packages/mds/__test__/lint.spec.mjs index df40c403..c5d21375 100644 --- a/packages/mds/__test__/lint.spec.mjs +++ b/packages/mds/__test__/lint.spec.mjs @@ -789,8 +789,10 @@ describe('unknown lint rule names (AC-224-1 / D8)', () => { // field can appear. Without this, an implementation that always populated // lint_warnings would pass every assertion above. test('U-L-WARN-4: every recognised rule name is accepted with no lint_warnings', () => { - assert.equal(LINT_RULE_NAMES.length, 11, 'LINT_RULE_NAMES must have exactly 11 entries'); + assert.equal(LINT_RULE_NAMES.length, 13, 'LINT_RULE_NAMES must have exactly 13 entries'); assert.ok(LINT_RULE_NAMES.includes('literal-directive')); + assert.ok(LINT_RULE_NAMES.includes('insecure-data-origin')); + assert.ok(LINT_RULE_NAMES.includes('literal-credential-header')); for (const name of LINT_RULE_NAMES) { const result = lint(CLEAN_SOURCE, { rules: { [name]: 'off' } }); assert.equal( diff --git a/packages/mds/src/types.ts b/packages/mds/src/types.ts index 5fa34215..bc06cb69 100644 --- a/packages/mds/src/types.ts +++ b/packages/mds/src/types.ts @@ -271,7 +271,9 @@ export type LintRuleName = | 'duplicate-export' | 'duplicate-import' | 'empty-block' + | 'insecure-data-origin' | 'legacy-interpolation' + | 'literal-credential-header' | 'literal-directive' | 'redundant-else' | 'shadow-variable' @@ -295,7 +297,9 @@ export const LINT_RULE_NAMES: readonly LintRuleName[] = [ 'duplicate-export', 'duplicate-import', 'empty-block', + 'insecure-data-origin', 'legacy-interpolation', + 'literal-credential-header', 'literal-directive', 'redundant-else', 'shadow-variable', diff --git a/scripts/__test__/cargo-deny-policy.spec.mjs b/scripts/__test__/cargo-deny-policy.spec.mjs index f2c761e1..ade265d5 100644 --- a/scripts/__test__/cargo-deny-policy.spec.mjs +++ b/scripts/__test__/cargo-deny-policy.spec.mjs @@ -22,8 +22,15 @@ const EXCEPTIONS = { 'unicode-ident': 'Unicode-3.0', foldhash: 'Zlib', 'target-lexicon': 'Apache-2.0 WITH LLVM-exception', + 'webpki-root-certs': 'CDLA-Permissive-2.0', + subtle: 'BSD-3-Clause', }; -const SKIPS = ['syn@2.0.117', 'unicode-width@0.1.14', 'windows-sys@0.60.2', 'wit-bindgen@0.51.0']; +const SKIPS = [ + 'syn@2.0.117', 'unicode-width@0.1.14', 'windows-sys@0.60.2', 'wit-bindgen@0.51.0', + 'getrandom@0.2.17', 'windows-sys@0.52.0', +]; +// A skipped tree must hold only one crate family at one version. +const SKIP_TREES = ['windows-targets@0.52.6']; const SHAPE = Symbol('shape'); const POLICY = { graph: { 'all-features': true, 'no-default-features': false, features: [], 'exclude-dev': false }, @@ -43,7 +50,7 @@ const POLICY = { 'multiple-versions': 'warn', 'multiple-versions-include-dev': true, wildcards: 'deny', 'allow-wildcard-paths': false, highlight: 'all', 'workspace-default-features': 'allow', 'external-default-features': 'allow', allow: [], 'allow-workspace': false, deny: [], features: [], - skip: SHAPE, 'skip-tree': [], + skip: SHAPE, 'skip-tree': SHAPE, }, 'bans.workspace-dependencies': { duplicates: 'deny', 'include-path-dependencies': false, unused: 'deny' }, sources: { @@ -74,7 +81,11 @@ const ABOUT = { license: 'MIT', files: [{ path: 'LICENSE-MIT.md', checksum: '799e9ca9d179295ef372f25d3769cdda7d25bb2668add6a6a1e22d1e4c678b8d' }], }, + 'webpki-root-certs': { accepted: SHAPE }, + subtle: { accepted: SHAPE }, }; +// The notice config accepts the exception license of these crates in a crate table only. +const ABOUT_SCOPED = ['webpki-root-certs', 'subtle']; const BARE = /^[A-Za-z0-9_-]+$/; const BASIC = /^"[^"\\\x00-\x1f]*"$/; @@ -199,13 +210,14 @@ function checkShape(table, key, rows, today) { assert.deepEqual(value.allow, [EXCEPTIONS[value.crate]], 'crate license exception'); assert.ok(comment, 'license exception needs a reason comment on the previous line'); } - if (key === 'skip') { + if (key === 'skip' || key === 'skip-tree') { exactSet(Object.keys(value), ['crate', 'reason'], 'duplicate skip fields'); assert.match(value.reason, /\S/, 'duplicate skip needs a reason'); } } if (key === 'exceptions') exactSet(rows.map(row => row.value.crate), Object.keys(EXCEPTIONS), 'exception crates'); if (key === 'skip') exactSet(rows.map(row => row.value.crate), SKIPS, 'versioned duplicate skips'); + if (key === 'skip-tree') exactSet(rows.map(row => row.value.crate), SKIP_TREES, 'versioned duplicate tree skips'); } function checkPolicy(text, today) { @@ -227,9 +239,10 @@ function checkAbout(text, denyText) { const tables = readPolicy(text, ABOUT); exactSet(tables.keys(), Object.keys(ABOUT), 'about.toml tables'); const licenses = readPolicy(denyText).get('licenses'); - const accepted = new Set([ + const exceptions = licenses.get('exceptions').map(({ value }) => value); + const global = new Set([ ...licenses.get('allow').map(({ value }) => value), - ...licenses.get('exceptions').flatMap(({ value }) => value.allow), + ...exceptions.filter(({ crate }) => !ABOUT_SCOPED.includes(crate)).flatMap(({ allow }) => allow), ]); for (const [name, table] of tables) { exactSet(table.keys(), Object.keys(ABOUT[name]), `about.toml ${name || 'root'} keys`); @@ -237,7 +250,13 @@ function checkAbout(text, denyText) { const actual = Array.isArray(value) ? value.map(row => row.value) : value; if (key === 'accepted') { assert.ok(Array.isArray(actual), 'about.toml accepted must be an array'); - exactSet(actual, accepted, 'about.toml accepted licenses'); + if (name === '') { + exactSet(actual, global, 'about.toml accepted licenses'); + } else { + const scoped = exceptions.find(({ crate }) => crate === name); + assert.ok(scoped, `about.toml ${name} needs a deny.toml exception`); + exactSet(actual, scoped.allow, `about.toml ${name} accepted licenses`); + } } else { assert.deepEqual(actual, ABOUT[name][key], `about.toml ${key}`); } @@ -497,6 +516,21 @@ test('the license policy requires a reason immediately above an exception', () = assert.throws(() => checkShape('licenses', 'exceptions', [{ value: { crate: 'notify', allow: ['CC0-1.0'] } }]), /reason comment/); }); +test('the duplicate policy skips only the approved tree, with no depth field', () => { + const baseline = read('deny.toml'); + checkPolicy(baseline, TODAY); + const entry = '{ crate = "windows-targets@0.52.6", reason'; + const empty = baseline.replace(/^skip-tree = \[\n[^\]]*\]$/m, 'skip-tree = []'); + for (const [modified, diagnostic] of [ + [baseline.replace(entry, '{ crate = "windows-sys@0.52.0", reason'), /versioned duplicate tree skips/], + [baseline.replace(entry, '{ crate = "windows-targets@0.52.6", depth = 1, reason'), /duplicate skip fields/], + [empty, /versioned duplicate tree skips/], + ]) { + assert.notEqual(modified, baseline, 'the control must change the policy'); + assert.throws(() => checkPolicy(modified, TODAY), diagnostic); + } +}); + test('the global license list excludes extra licenses', () => { const allow = [...LICENSES, 'Zlib'].map(value => ({ value })); assert.throws(() => checkShape('licenses', 'allow', allow), /global license list/); @@ -508,8 +542,11 @@ test('the notice config matches the dependency license policy (#136)', () => { }); for (const [name, from, to, message] of [ - ['an extra accepted license', 'accepted = [', 'accepted = ["BSD-3-Clause", ', /^about\.toml accepted licenses/], + ['an extra accepted license', 'accepted = [', 'accepted = ["MPL-2.0", ', /^about\.toml accepted licenses/], ['a missing accepted license', '"CC0-1.0", ', '', /^about\.toml accepted licenses/], + ['a crate license in the global list', 'accepted = ["MIT", ', 'accepted = ["MIT", "BSD-3-Clause", ', /^about\.toml accepted licenses/], + ['a crate license for another crate', 'accepted = ["BSD-3-Clause"]', 'accepted = ["CDLA-Permissive-2.0"]', /^about\.toml subtle accepted licenses/], + ['a missing crate table', '[subtle]\naccepted = ["BSD-3-Clause"]\n', '', /^about\.toml tables/], ['a quoted key', 'accepted =', '"accepted" =', /^expected a bare key$/], ['a missing target', ' "wasm32-unknown-unknown",\n', '', /^about\.toml targets/], ['the alternate miniz license file', 'path = "LICENSE-MIT.md"', 'path = "LICENSE"', /^about\.toml files/], diff --git a/scripts/__test__/release-auth-probe.spec.mjs b/scripts/__test__/release-auth-probe.spec.mjs index 14d783ff..e4db04bd 100644 --- a/scripts/__test__/release-auth-probe.spec.mjs +++ b/scripts/__test__/release-auth-probe.spec.mjs @@ -1996,7 +1996,7 @@ function assertPublishEnv(section, names, binding) { } function assertCargoPublishEnv(section) { - assertPublishEnv(section, ['Publish mds-core', 'Publish mds-cli'], + assertPublishEnv(section, ['Publish mds-core', 'Publish mds-fetch', 'Publish mds-cli'], 'CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}'); assert.doesNotMatch(stripCommentLines(section), /\bcargo publish[^\n]*\s--token\b/, 'cargo publish must not use a token flag'); @@ -2030,7 +2030,78 @@ function assertNpmRegistryOrder(section) { assert.equal(platform.index + 1, npm.index, 'no step may separate the two npm publishes'); } -test('S24: only the two Cargo publish steps bind registry values', () => { +// The crates publish in dependency order. Each crate publishes directly after a bounded +// index poll shows the crate before it, and each publish passes on a re-run where its +// version is already on crates.io (PF-023). +const CRATE_PUBLISH_STEPS = [ + ['Publish mds-core', 'mds-core'], + ['Wait for crates.io index to update (mds-core)', 'mds-core'], + ['Publish mds-fetch', 'mds-fetch'], + ['Wait for crates.io index to update (mds-fetch)', 'mds-fetch'], + ['Publish mds-cli', 'mds-cli'], +]; + +function assertCratePublishOrder(section) { + const steps = jobSteps(section); + const found = CRATE_PUBLISH_STEPS.map(([name]) => namedStep(steps, name)); + for (const [n, [name]] of CRATE_PUBLISH_STEPS.entries()) { + assert.ok(found[n], `${name} must exist`); + } + assert.deepEqual(found.map(step => step.index), found.map((_, n) => found[0].index + n), + 'the crate publish and index poll steps must run in dependency order, with no step between'); + const polls = []; + for (const [n, [name, crate]] of CRATE_PUBLISH_STEPS.entries()) { + const run = stepRun(found[n].body); + if (name.startsWith('Publish ')) { + assert.ok(run.includes(`if OUTPUT=$(cargo publish -p ${crate} 2>&1); then\n`), + `${name} must publish ${crate}`); + assert.ok(run.includes('grep -qE "already (uploaded|exists|published)"'), + `${name} must pass on a re-run`); + } else { + assert.ok(stepEnv(found[n].body).split('\n').includes(` CRATE: ${crate}`), + `${name} must poll ${crate}`); + polls.push(run); + } + } + assert.ok(/^ {10}MAX=20$/m.test(polls[0]) && /for i in \$\(seq 1 "\$MAX"\); do/.test(polls[0]), + 'the index poll must be bounded'); + assert.equal(polls[1], polls[0], 'both index polls must run the same block'); +} + +test('S34: the crates publish in dependency order after each index poll', () => { + const section = extractJobSection(yml, 'publish-crates'); + assertCratePublishOrder(section); + const name = step => ` - name: ${step}\n`; + const fetchPublish = name('Publish mds-fetch'); + const fetchPoll = name('Wait for crates.io index to update (mds-fetch)'); + const cliPublish = name('Publish mds-cli'); + const start = section.indexOf(fetchPublish); + const end = section.indexOf(cliPublish); + assert.ok(start > 0 && end > start, 'non-vacuity: the mds-fetch steps precede Publish mds-cli'); + const coreStart = section.indexOf(name('Publish mds-core')); + assert.ok(coreStart > 0 && coreStart < start, 'non-vacuity: Publish mds-core comes first'); + const moved = section.slice(0, coreStart) + section.slice(start, end) + + section.slice(coreStart, start) + section.slice(end); + assert.throws(() => assertCratePublishOrder(moved), /dependency order/); + const noPoll = section.replace(fetchPoll, name('Wait for the mds-fetch index')); + assert.throws(() => assertCratePublishOrder(noPoll), /\(mds-fetch\) must exist/); + const wrongCrate = section.replace('cargo publish -p mds-fetch 2>&1', 'cargo publish -p mds-cli 2>&1'); + assert.throws(() => assertCratePublishOrder(wrongCrate), /Publish mds-fetch must publish mds-fetch/); + const notIdempotent = section.replace( + /(Publish mds-fetch\n(?:.*\n)*?.*)grep -qE "already \(uploaded\|exists\|published\)"/, + '$1grep -qE "already uploaded"'); + assert.notEqual(notIdempotent, section, 'non-vacuity: the re-run guard plant changes the section'); + assert.throws(() => assertCratePublishOrder(notIdempotent), /Publish mds-fetch must pass on a re-run/); + const otherCrate = section.replace(' CRATE: mds-fetch\n', ' CRATE: mds-core\n'); + assert.throws(() => assertCratePublishOrder(otherCrate), /must poll mds-fetch/); + const unbounded = section.replaceAll(' MAX=20\n', ' MAX=\n'); + assert.throws(() => assertCratePublishOrder(unbounded), /must be bounded/); + const drifted = section.replace(/(CRATE: mds-fetch\n(?:.*\n)*?.*)--max-time 20/, '$1--max-time 99'); + assert.notEqual(drifted, section, 'non-vacuity: the drift plant changes the section'); + assert.throws(() => assertCratePublishOrder(drifted), /same block/); +}); + +test('S24: only the three Cargo publish steps bind registry values', () => { const section = extractJobSection(yml, 'publish-crates'); assertCargoPublishEnv(section); const withFlag = section.replace('cargo publish -p mds-core ', diff --git a/scripts/__test__/verify-versions.spec.mjs b/scripts/__test__/verify-versions.spec.mjs index 842516ec..e24fc950 100644 --- a/scripts/__test__/verify-versions.spec.mjs +++ b/scripts/__test__/verify-versions.spec.mjs @@ -94,6 +94,12 @@ for (const [name, path, edit, problem] of [ ['mds-core dependency version drift', 'crates/mds-cli/Cargo.toml', (text) => text.replace(/^(.*package = "mds-core".*version = ")[^"]+/m, (_, prefix) => `${prefix}${NEXT}`), /crates\/mds-cli\/Cargo\.toml: mds-core dep version "101\.102\.103" != workspace version/], + ['mds-fetch dependency version drift', 'crates/mds-cli/Cargo.toml', (text) => + text.replace(/^(mds-fetch = \{.*version = ")[^"]+/m, (_, prefix) => `${prefix}${NEXT}`), + /crates\/mds-cli\/Cargo\.toml: mds-fetch dep version "101\.102\.103" != workspace version/], + ['an mds-fetch dependency without a version', 'crates/mds-cli/Cargo.toml', (text) => + text.replace(/^(mds-fetch = \{ path = "[^"]+"), version = "[^"]+"/m, '$1'), + /crates\/mds-cli\/Cargo\.toml: no path\+version dep on mds-fetch found/], ['a different Python project name', PYPROJECT, (text) => text.replace('name = "markdown-script"', 'name = "mdscript"'), /crates\/mds-python\/pyproject\.toml: project name is not "markdown-script"/], ['a Python dynamic list without version', PYPROJECT, (text) => text.replace('dynamic = ["version"]', 'dynamic = []'), @@ -136,7 +142,7 @@ test('verification accepts locks with CRLF line ends', (t) => { const result = repo.run('scripts/verify-versions.mjs'); assert.equal(result.status, 0, result.stderr); const version = canonical(); - assert.equal(result.stdout, `✓ version gate: 8 packages + 4 crates all at ${version}; no file: refs; internal deps pinned to ^${version}; Python pyproject.toml name=markdown-script version=dynamic\n`); + assert.equal(result.stdout, `✓ version gate: 8 packages + 5 crates all at ${version}; no file: refs; internal deps pinned to ^${version}; Python pyproject.toml name=markdown-script version=dynamic\n`); }); test('bump updates only workspace lock fields and keeps CRLF', (t) => { @@ -144,7 +150,7 @@ test('bump updates only workspace lock fields and keeps CRLF', (t) => { const version = canonical(); const pattern = new RegExp(`^version = "${version.replaceAll('.', '\\.')}"$`, 'gm'); const cargo = repo.read('Cargo.lock'); - assert.equal([...cargo.matchAll(pattern)].length, 5); + assert.equal([...cargo.matchAll(pattern)].length, 6); const crlf = (text) => text.replace(/\r?\n/g, '\r\n'); repo.write('Cargo.lock', crlf(cargo)); const lock = JSON.parse(repo.read('package-lock.json')); @@ -155,6 +161,11 @@ test('bump updates only workspace lock fields and keeps CRLF', (t) => { const result = repo.run('scripts/bump-version.mjs', NEXT); assert.equal(result.status, 0, result.stderr); assert.equal(repo.read('Cargo.lock'), crlf(cargo.replace(pattern, `version = "${NEXT}"`))); + const cli = repo.read('crates/mds-cli/Cargo.toml'); + for (const crate of ['package = "mds-core"', 'mds-fetch = {']) { + const line = cli.split('\n').find((text) => text.includes(crate)); + assert.match(line ?? '', new RegExp(`version = "${NEXT.replaceAll('.', '\\.')}"`), crate); + } for (const [dir, pkg] of Object.entries(lock.packages)) { if (!/^(?:packages|crates)\/[^/]+$/.test(dir)) continue; pkg.version = NEXT; @@ -234,9 +245,10 @@ import { readFileSync } from 'node:fs'; import * as verify from './scripts/verify-versions.mjs'; import * as bump from './scripts/bump-version.mjs'; import * as manifest from './scripts/release-manifest.mjs'; -const { LOCK_MEMBERS, PKG_DIRS, PKG_PATHS, CRATE_CARGO_PATHS } = manifest; +const { LOCK_MEMBERS, PKG_DIRS, PKG_PATHS, CRATE_CARGO_PATHS, FETCH_DEP_PATHS } = manifest; assert.equal(PKG_PATHS.length, 8); -assert.equal(CRATE_CARGO_PATHS.length, 4); +assert.equal(CRATE_CARGO_PATHS.length, 5); +assert.deepEqual(FETCH_DEP_PATHS, ['crates/mds-cli/Cargo.toml']); assert.equal(PKG_DIRS.length, 8); const cargo = readFileSync('Cargo.lock', 'utf8'); const npm = readFileSync('package-lock.json', 'utf8'); diff --git a/scripts/bump-version.mjs b/scripts/bump-version.mjs index 5f32f211..115d3225 100644 --- a/scripts/bump-version.mjs +++ b/scripts/bump-version.mjs @@ -1,6 +1,6 @@ #!/usr/bin/env node // Set a new version in the workspace Cargo.toml and its path+version -// dependencies on mds-core. Update publishable npm versions and internal +// dependencies on mds-core and mds-fetch. Update publishable npm versions and internal // dependency ranges. Update only the workspace entries in both lockfiles. // Stamp CHANGELOG.md. Run locally before you tag a release. // @@ -11,9 +11,9 @@ import { writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { CRATE_CARGO_PATHS, DEP_SETS, LOCK_MEMBERS, PKG_DIRS, PKG_PATHS } from './release-manifest.mjs'; +import { DEP_SETS, LOCK_MEMBERS, PKG_DIRS, PKG_PATHS } from './release-manifest.mjs'; import { - CARGO_LOCK_VERSION, CORE_DEP_VERSION, WORKSPACE_VERSION, checkVersions, isInternal, + CARGO_LOCK_VERSION, VERSIONED_DEPS, WORKSPACE_VERSION, checkVersions, isInternal, isMainModule, isRecord, parsePackageLock, parseRecord, readVersionFiles, reportVersionProblems, scanCargoLock, } from './verify-versions.mjs'; @@ -85,8 +85,8 @@ function prepareBump(files, version, date) { const updated = new Map(files); const replacement = setVersion(version); updated.set('Cargo.toml', files.get('Cargo.toml').replace(WORKSPACE_VERSION, replacement)); - for (const path of CRATE_CARGO_PATHS) { - updated.set(path, files.get(path).replace(CORE_DEP_VERSION, replacement)); + for (const { paths, pattern } of VERSIONED_DEPS) { + for (const path of paths) updated.set(path, updated.get(path).replace(pattern, replacement)); } const problems = []; diff --git a/scripts/release-manifest.mjs b/scripts/release-manifest.mjs index e55db871..b483d451 100644 --- a/scripts/release-manifest.mjs +++ b/scripts/release-manifest.mjs @@ -18,8 +18,12 @@ export const CRATE_CARGO_PATHS = Object.freeze([ 'crates/mds-napi/Cargo.toml', 'crates/mds-wasm/Cargo.toml', 'crates/mds-python/Cargo.toml', + 'crates/mds-fetch/Cargo.toml', ]); +// Workspace crates with a path and version dependency on mds-fetch. +export const FETCH_DEP_PATHS = Object.freeze(['crates/mds-cli/Cargo.toml']); + export const DEP_SETS = Object.freeze(['dependencies', 'optionalDependencies', 'peerDependencies']); export const PKG_DIRS = Object.freeze(PKG_PATHS.map(dirname)); export const LOCK_MEMBERS = Object.freeze([...CRATE_CARGO_PATHS.map((path) => basename(dirname(path))), 'mds-core']); diff --git a/scripts/verify-versions.mjs b/scripts/verify-versions.mjs index 493567e4..61a033f8 100644 --- a/scripts/verify-versions.mjs +++ b/scripts/verify-versions.mjs @@ -5,8 +5,8 @@ // 2. Published dependency sets use no `file:` specifiers. // 3. Each internal `@mdscript/*` dependency uses a caret range on that // version (for example, ^0.1.0). -// 4. Each crate's path+version dependency on mds-core uses the workspace -// version. +// 4. Each crate's path+version dependency on mds-core, and each one on +// mds-fetch, uses the workspace version. // 5. The Python distribution name is `markdown-script`, not `mdscript`. // pyproject.toml declares the version as dynamic so maturin reads it from // the Cargo workspace. @@ -20,11 +20,22 @@ import { readFileSync, realpathSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import { CRATE_CARGO_PATHS, DEP_SETS, LOCK_MEMBERS, PKG_DIRS, PKG_PATHS } from './release-manifest.mjs'; +import { + CRATE_CARGO_PATHS, DEP_SETS, FETCH_DEP_PATHS, LOCK_MEMBERS, PKG_DIRS, PKG_PATHS, +} from './release-manifest.mjs'; const PYPROJECT_PATH = 'crates/mds-python/pyproject.toml'; export const WORKSPACE_VERSION = /(^\[workspace\.package\][ \t]*\r?\n(?:(?!\[)[^\r\n]*\r?\n)*?[ \t]*version[ \t]*=[ \t]*")([^"\r\n]+)(")/m; export const CORE_DEP_VERSION = /(package\s*=\s*"mds-core".*?version\s*=\s*")([^"\r\n]+)(")/g; +// The inline table form `mds-fetch = { path = "...", version = "..." }`. Another form +// matches nothing, so the gate fails closed on it. +export const FETCH_DEP_VERSION = /(^[ \t]*mds-fetch[ \t]*=[ \t]*\{[^}\r\n]*?version\s*=\s*")([^"\r\n]+)(")/gm; +// Each crate dependency that must use the workspace version: its crate name, the +// manifests that hold it and the pattern of its version. +export const VERSIONED_DEPS = Object.freeze([ + Object.freeze({ crate: 'mds-core', paths: CRATE_CARGO_PATHS, pattern: CORE_DEP_VERSION }), + Object.freeze({ crate: 'mds-fetch', paths: FETCH_DEP_PATHS, pattern: FETCH_DEP_VERSION }), +]); export const CARGO_LOCK_VERSION = /^([ \t]*version[ \t]*=[ \t]*")([^"\r\n]+)(")/; export const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value); @@ -133,12 +144,14 @@ export function checkVersions(files) { const version = WORKSPACE_VERSION.exec(files.get('Cargo.toml'))?.[2]; if (!version) return { version, problems: ['Cargo.toml: could not find [workspace.package] version'] }; const problems = []; - for (const path of CRATE_CARGO_PATHS) { - const matches = [...files.get(path).matchAll(CORE_DEP_VERSION)]; - if (matches.length === 0) problems.push(`${path}: no path+version dep on mds-core found`); - for (const [, , depVersion] of matches) { - if (depVersion !== version) { - problems.push(`${path}: mds-core dep version "${depVersion}" != workspace version "${version}"`); + for (const { crate, paths, pattern } of VERSIONED_DEPS) { + for (const path of paths) { + const matches = [...files.get(path).matchAll(pattern)]; + if (matches.length === 0) problems.push(`${path}: no path+version dep on ${crate} found`); + for (const [, , depVersion] of matches) { + if (depVersion !== version) { + problems.push(`${path}: ${crate} dep version "${depVersion}" != workspace version "${version}"`); + } } } } @@ -162,7 +175,10 @@ export function checkVersions(files) { export function readVersionFiles(root, extraPaths = []) { const files = new Map(); const problems = []; - const paths = ['Cargo.toml', 'Cargo.lock', 'package-lock.json', ...CRATE_CARGO_PATHS, ...PKG_PATHS, PYPROJECT_PATH, ...extraPaths]; + const paths = [...new Set([ + 'Cargo.toml', 'Cargo.lock', 'package-lock.json', ...CRATE_CARGO_PATHS, ...FETCH_DEP_PATHS, ...PKG_PATHS, + PYPROJECT_PATH, ...extraPaths, + ])]; for (const path of paths) { try { files.set(path, readFileSync(join(root, path), 'utf8')); diff --git a/spec.md b/spec.md index 8e500f16..23702963 100644 --- a/spec.md +++ b/spec.md @@ -16,7 +16,7 @@ MDS (Markdown Script) is a domain-specific language for composing, reusing, and 1. Looks like Markdown, not code 2. Minimal new syntax: leverage existing conventions (YAML frontmatter, `@` directives) 3. Composable: imports, functions, modules -4. Deterministic: same input always produces same output. The input includes the sources, the runtime variables and the local data files that `data:` entries name (§4.12). This release sends no network request. +4. Deterministic: same input always produces same output. The input includes the sources, the runtime variables and the local data files that `data:` entries name (§4.12). With `mds build --allow-net` (§7.2) the input also includes the responses of URL entries, so the same responses give the same output. 5. Fail fast: clear errors with file:line:col, no partial output --- @@ -162,6 +162,77 @@ A YAML data file also has the flow-nesting guard of frontmatter (1024 levels, `m A data value nested deeper than 64 levels fails with `mds::data` (`data_value_depth_accepts_the_cap_and_refuses_one_more_level` in `crates/mds-core/src/data/convert_tests.rs`). +**Request header limits:** + +| Limit | Value and stage | +|-------|-----------------| +| `MAX_REQUEST_HEADERS` | 32 headers in the request map of one entry, during declaration analysis | +| `MAX_HEADER_VALUE_BYTES` | 8 KiB (8192 bytes) per request header value: the expanded text, or the literal prefix and the secret value, checked before each append | + +These two values are choices of this release. 32 headers is above the header count of usual +API requests. 8 KiB is the header field limit of usual HTTP servers, so a longer value +fails at the server. Together they bound the header text of one request to 256 KiB. +Each fails with `mds::resource_limit`: +`"", entry "", field "headers": too many headers (max 32 per request)` and +`"", entry "", field "
": header value exceeds the maximum length of 8192 bytes` +(`header_count_cap_admits_exactly_the_cap` in `crates/mds-core/src/data/decl_tests.rs`, +`the_header_value_cap_admits_exactly_the_cap` in `crates/mds-core/src/data/encode_tests.rs`). + +**Network limits** (§4.12 "Network access"): + +| Limit | Value and stage | +|-------|-----------------| +| `MAX_REQUESTS_PER_COMPILE` | 64 request identities per compile, counted on each derive, before the compile returns a request. Thus a compile has at most 65 rounds | +| `MAX_REQUESTS_PER_RUN` | 512 sent requests per `mds build` run, over all of its compiles, counted before each round sends | +| `MAX_REDIRECTS` | 5 redirects per entry, counted on each derive, before the next hop request | +| `MAX_URL_BYTES` | 8 KiB (8192 bytes) per expanded URL and per redirect `location` | +| `MAX_RESPONSE_HEADER_BYTES` | 16 KiB of status line and headers per response, counted as they arrive | +| `MAX_RESPONSE_BYTES` | 10 MiB of body per response of every status, as received. The sender reads at most one byte more, and the core checks the length again before it follows a redirect or converts a body | +| `MAX_RESPONSE_BODY_BYTES_PER_COMPILE` | 200 MiB (209,715,200 bytes, the compile memory budget) of raw response bodies per compile, of every status, counted as each response enters the fetch state. In `mds build`, each send of a group reads at most its share of the bytes left | +| `REQUEST_TIMEOUT` | 10 s per request, from the name lookup to the end of the body | +| `COMPILE_DEADLINE` | 30 s of network work per compile, from its first send | +| `MAX_PARALLEL_SENDS` | 8 requests in flight at one time in one compile | +| `MAX_RESOLVED_ADDRS` | 64 addresses per name lookup | +| `MAX_ALLOW_ITEMS` | 64 items per allow list, when the host makes the policy | +| `MAX_SECRETS` | 16 host secrets per policy, when the host makes the policy | + +These bounds bind in this order: + +- In one compile, the per-compile request cap binds before the per-run cap. A directory build of + many files can reach the per-run cap. +- Each redirect hop is also a request identity. Thus the per-compile cap can bind before the + redirect cap when many entries redirect. +- The header cap binds before the body cap, because the headers come first. For a `location` + value, the URL cap binds before the header cap. A dense body can reach the node cap or the + compile memory budget before the body cap, as a data file can. +- When less than 10 s of the compile deadline is left, the deadline binds before the request + timeout. With no time left, the request is not sent and fails as a timeout. +- The body total counts every body that the host gives, before a step compile reads it. The + body of a redirect answer and of an error answer count too. For the bodies that entries + convert, the 32 MiB data total (`MAX_DATA_BYTES_PER_COMPILE`) binds first, in the next step + compile. +- `mds build` sends a group of at most 8 requests at one time, and each send of the group gets + an equal share of the body bytes left. A body past a share that is less than 10 MiB fails + with the body total error, also when the other bodies of the group are smaller. + +The request caps, the redirect cap and the body total fail with `mds::resource_limit` (exit 3): +`too many requests (max 64 per compile)`, `: too many redirects (max 5 per entry)`, +`one run sends at most 512 requests` and `response bodies exceed 209715200 bytes per compile`. +`` is the request location of §4.12 "Errors of a request". A response past a byte +cap, a timeout and a lookup past the address cap fail the request with `mds::network` (exit 2): +`the response body exceeds 10485760 bytes`, `the response headers exceed 16384 bytes`, +`the request timed out` and `the connection failed`. The body cap applies to a redirect answer +too. An allow list or a secret list past its cap is a host input error: `mds build` reports it as +`mds::invalid_options` (exit 2). Tests: `the_request_cap_binds_before_a_new_request_is_added`, +`redirect_chains_take_the_hop_cap`, `the_fetch_state_counts_every_body_against_one_total`, +`the_core_body_cap_binds_at_the_cap_and_fails_one_byte_over` and +`response_bodies_count_against_the_data_total_of_a_compile` in `crates/mds-core/src/data/`, +`the_run_cap_refuses_request_513`, `each_send_reads_at_most_its_share_of_the_bytes_left` and +`a_body_past_its_share_fails_with_the_body_total_error` in `crates/mds-cli/src/build/net.rs`, and +`the_body_cap_passes_at_the_cap_and_fails_one_byte_over`, +`response_headers_past_the_cap_fail`, `a_lookup_answer_past_the_cap_fails` and +`a_silent_server_times_out_at_the_narrowed_deadline` in `crates/mds-fetch/tests/plain.rs`. + --- ### 4.2 Interpolation @@ -1081,8 +1152,8 @@ The value of `data` is a mapping. Each key is an entry name. Each value has one | Form | Example | In this release | |------|---------|-----------------| | Local file | `./settings.json`, `../shared/rows.yml` | MDS reads and converts the file. | -| URL | `https://example.com/items/{{id}}` | MDS checks the declaration. It does not fetch the URL. | -| Request map | `{url: "https://example.com/items", method: POST, body: {id: 1}}` | MDS checks the declaration. It does not fetch the URL. | +| URL | `https://example.com/items/{{id}}` | MDS checks the declaration. `mds build --allow-net` and the Rust step API send a `GET` request. | +| Request map | `{url: "https://example.com/items", method: HEAD, envelope: true}` | MDS checks the declaration. `mds build --allow-net` and the Rust step API send a `GET` or `HEAD` request. Other methods are refused. | - A string that starts with `./` or `../` is a local file entry. The path rules are in §4.6 "Filesystem constraints", row "Data file path". @@ -1090,19 +1161,36 @@ The value of `data` is a mapping. Each key is an entry name. Each value has one - A string with a URI scheme is a URL entry. The scheme must be the literal `https` (`expected the literal https scheme`). The authority is literal and has no trailing host dot. The URL has no backslash and no fragment. A query needs a path. -- A request map has the fields `url` (required), `method`, `headers`, `body`, `cache` and `accept`. - `method` is `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE` or `OPTIONS`. `accept` is `json`, - `yaml` or `text`. `cache` is a count with the unit `s`, `m`, `h` or `d`, or `forever`, or `off`. +- The strict URL parser reads the literal URL of each URL entry and request map. Each reference + counts as the shortest text that it can give: one byte in a path segment, none in the query. + A host that is not a canonical name or address (for example `127.1`, `2130706433` or an + upper-case letter), a bad port, or a URL longer than 8192 bytes (`mds::resource_limit`) fails + at declaration. These rules also apply to an entry that replay satisfies. +- A request map has the fields `url` (required), `method`, `headers`, `body`, `cache`, `accept` + and `envelope`. The `url` of a request map can also have the literal `http` scheme. Such a URL + passes the declaration check and reaches the policy, which sends it only when an + `http://host:port` allow item names its origin ("Network access" below). `method` is + `GET` (the default), `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE` or `OPTIONS`. `accept` is `json` + (the default), `yaml` or `text`. `cache` is a count with the unit `s`, `m`, `h` or `d`, or + `forever`, or `off`. `envelope` is `true` or `false` (the default). A header name is a literal token. A header value is a string, or a map of `secret` (an - identifier) and `prefix` (a literal string). A `body` is a mapping or a literal string, with no - YAML tags. Another field fails (`unknown request field`). + identifier) and `prefix` (literal header text: visible ASCII characters and spaces). A `body` + is a mapping or a literal string, with no YAML tags. Another field fails (`unknown request field`). +- A `GET` or `HEAD` request cannot have a body. A `HEAD` request requires `envelope: true`. +- The headers `Authorization`, `Proxy-Authorization`, `Cookie` and `X-Api-Key`, in any letter + case, take the secret form only (`use the secret form for this header`). - Any other value fails with `mds::data`: `expected a dot-relative path, an HTTPS URL or a request map`. The help is `` `data` is reserved for data sources; rename the variable ``. A `data` value that is not a mapping fails with the same help (`expected a mapping of data entries`). Tests: `unknown_forms_have_rename_help`, `both_url_forms_require_a_literal_https_origin`, -`exact_method_accept_and_cache_grammars` and `header_grammar_keeps_names_and_secret_parts_literal` -in `crates/mds-core/src/data/decl_tests.rs`. +`exact_method_accept_and_cache_grammars`, `header_grammar_keeps_names_and_secret_parts_literal`, +`http_is_accepted_in_the_request_map_form_only`, `get_and_head_requests_cannot_have_a_body`, +`head_requires_the_envelope`, `credential_headers_take_the_secret_form_only`, +`literal_url_goes_through_the_strict_parser` and +`literal_url_at_the_length_cap_passes_and_one_byte_over_fails` in +`crates/mds-core/src/data/decl_tests.rs`, and `request_map_rules_run_before_replay` in +`crates/mds-core/tests/data_resolve.rs`. #### Entry names @@ -1156,7 +1244,7 @@ The declaration checks above still apply to a replayed entry (`replay_cannot_ski in `graph_tests.rs`), and so do the type checks of the body (`replay_keeps_static_type_checks` in `crates/mds-core/tests/data_tooling.rs`). The data rules below apply only to a file that MDS reads. -This release sends no network request. A URL entry with no replay value fails with +Without a network grant, a URL entry with no replay value fails with `mds::network_denied` (exit 2), for example: ```text @@ -1171,6 +1259,213 @@ entries in declaration order. The denial comes before any local data read `frontier_keeps_module_and_declaration_order` in `graph_tests.rs`, `build_denies_network_entries_without_replay_and_opens_no_connection` in `cli_data.rs`). +In this release, only `mds build --allow-net` (§7.2) and the Rust step API ("Step compiles" +below) give a network grant. The napi, WASM and Python bindings, `@mdscript/mds`, the Rust +compile functions, `mds watch`, `mds check`, `mds lint` and `mds fmt` send no request: they +refuse a URL entry with no replay value with `mds::network_denied`, as above. + +#### Network access + +A host gives a network grant as a `NetworkPolicy`: an allow list, the import opt-in and the +host secrets. The core checks each request against it before the request leaves the compile: + +- **Allow list.** It has 1 to 64 items. An item is `host`, `host:port`, `https://host[:port]` or + `http://host:port`. An item with no scheme is `https`. The host follows the strict URL parser: + a lower-case name or a canonical IP address, with no trailing dot. An item has no path, no + query, no fragment and no wildcard. An `http` item needs its scheme and a port. An item allows + exactly one origin: the same scheme, host and port. The default port and no port are equal. A + name never matches a subdomain (`allow_items_name_one_exact_origin`, + `allow_items_refuse_every_other_form` and `allow_items_match_the_exact_host_scheme_and_port` + in `crates/mds-core/src/data/policy_tests.rs`). +- **Import opt-in.** A URL entry of an imported module or of an `@extends` base sends only with + the import opt-in. The allow list applies first + (`origins_need_the_allow_list_then_the_import_opt_in`, + `a_url_entry_of_an_imported_module_needs_the_import_opt_in` in `step_tests.rs`). +- **Methods.** This release sends `GET` and `HEAD` only. Another method fails with + `mds::network_denied` (`method`) (`only_get_and_head_pass_the_method_check`). +- **Narrowing.** A host can make a narrower policy from a wider one. Each item must permit no + request that the wider list refuses, and the import opt-in can be on only when the wider + policy has it. An IP address item with a port can open a refused address (below), so it needs + a port in the wider item too (`narrowing_never_widens_a_policy`, + `narrowing_cannot_add_the_port_that_opens_an_address`). +- **Secrets.** A host secret has a name (an identifier), a value (one or more visible ASCII + characters) and one `https` origin. A policy has at most 16, each with its own name. A secret + header of the entry module (`{secret: NAME, prefix: …}`) binds only to a secret of that name + and of that exact origin. Else the request fails with `mds::network_denied` + (`secret-binding`). A secret value fills a header value only, never a URL, a body or the + output (`secrets_bind_to_their_name_and_origin_only`, `a_host_secret_is_only_a_header_value`). +- **Response check.** A response that holds the exact bytes of a host secret value, in a string + or a key of the converted value, in an envelope header or in a redirect `location`, fails with + `mds::network_denied` (`response-check`, `the response holds the value of a host secret`). + The check finds exact bytes only: a changed form of the value, such as base64, percent + encoding or a value split over two strings, is not found + (`a_secret_value_in_an_envelope_header_fails_the_response_check`). + +The sender checks each address that a name lookup gives before it connects. An address in a +refused range fails the request with `mds::network_denied` (`transport-address`). The refused +IPv4 ranges are `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, `127.0.0.0/8`, `169.254.0.0/16`, +`172.16.0.0/12`, `192.0.0.0/24`, `192.168.0.0/16`, `198.18.0.0/15`, `224.0.0.0/4`, +`240.0.0.0/4` and `255.255.255.255/32`. The refused IPv6 ranges are `::/96` (it holds `::` +and `::1`), `::ffff:0:0/96`, `::ffff:0:0:0/96`, `64:ff9b::/96`, `64:ff9b:1::/48`, `2001::/32`, +`2002::/16`, `fc00::/7`, `fe80::/10`, `fec0::/10` and `ff00::/8`. An +address in a refused range passes only when an allow item is that exact IP address with that +exact port. Thus a name can never open such an address that no allow item names +(`address_table_refuses_both_edges_of_each_range`, +`only_an_exact_ip_item_with_its_port_opens_a_refused_address`). + +#### Requests + +The core expands the URL and the header values of an entry in one pass over the literal +template. The place of each reference comes from the template, never from a value. A value is +inserted once and never scanned again. A reference value becomes text by this table: + +| Value | Text | +|-------|------| +| String | The string | +| `true`, `false` | `true`, `false` | +| An integer from -2^53 to 2^53 | Its decimal digits, with no exponent and no fraction | +| Another number, `null`, an array, an object | Fails with `mds::type_error` | + +Then the text goes through the encoder of its place: + +| Place | Rule | +|-------|------| +| URL path segment (before the first literal `?`) | Each byte outside `A-Z`, `a-z`, `0-9`, `-`, `.`, `_` and `~` becomes `%XX` (upper-case hex). Empty text, `.` and `..` fail with `mds::data` | +| URL query (after the first literal `?`) | The same byte rule, so `&`, `=`, `+` and `#` cannot add or cut a parameter | +| Header value | Bytes 0x20 to 0x7E only. Other text fails with `mds::data`. It is never encoded | + +Tests: `scalars_become_text_only_as_strings_booleans_and_exact_integers`, +`each_placement_encoder_gives_the_exact_bytes_or_its_refusal` and +`placement_comes_from_the_literal_template_never_from_a_value` in +`crates/mds-core/src/data/encode_tests.rs`, and `each_value_source_gives_the_same_request_bytes_or_refusal` +in `step_tests.rs`. + +The strict URL parser then reads the expanded URL. A request carries the method, the URL, the +`accept` format and the headers in declaration order. The native sender adds +`User-Agent: mds-fetch/`, `Accept: application/json, application/yaml, text/plain` and +`Accept-Encoding: identity`. + +A request cannot set the headers `Host`, `Content-Length`, `Transfer-Encoding`, `Connection`, +`Keep-Alive`, `Proxy-Connection`, `TE`, `Trailer` and `Upgrade`, in any letter case and in any +value form. The sender writes the host from the URL, so a request reaches only the origin that +the allow list and the secret origins check. The core sets the request method; headers that +change it are refused: `X-HTTP-Method-Override`, `X-HTTP-Method` and `X-Method-Override`, in +the same way. A step compile fails with `mds::data` +(`a request cannot set this header`) before any request exists +(`a_request_cannot_set_a_sender_header` in `step_tests.rs`). + +**Request identity.** Each request has a `RequestId`: the SHA-256 digest of a canonical text, +written as 64 lower-case hex digits. The text is a sequence of fields, each its byte length as +a u64 big-endian number and then its bytes: the version tag `mds-request-1`, the method, the +URL, the format (`json`, `yaml` or `text`), the header count, each header key in byte order, and +an empty body. A text header key is its lower-case name, NUL, `t`, and then the name and the text +as netstrings. A secret header key has `s`, the name, the secret name, the prefix and the hex +HMAC-SHA-256 of the secret value under the `RunKey` of the run. Thus equal requests share one +ID, any change of a part changes it, and the ID never shows a secret value +(`the_id_is_the_digest_of_the_canonical_text`, `each_request_part_changes_the_id` and +`the_run_key_changes_only_secret_request_ids` in `crates/mds-core/src/data/request_tests.rs`). + +**Redirects.** The sender follows no redirect. A `301`, `302`, `303`, `307` or `308` answer +goes back to the core, which checks the hop and derives the next request: + +- The answer has exactly one `location` header. It is an absolute URL or an absolute path, and + the strict URL parser reads it. Else the request fails with `mds::network_denied` + (`redirect-check` or `url-parser`). +- A chain has at most 5 hops (`mds::resource_limit`). A hop from `https` to `http` fails, and so + does a hop to an origin that the allow list does not name (`redirect-check`). +- A hop to another origin drops every secret header and the headers `Authorization`, + `Proxy-Authorization`, `Cookie` and `X-Api-Key`. A hop keeps the method. +- Each hop is a new request with its own identity, so the request cap counts it. + +A `300` or `304` answer is not a redirect: it binds with the envelope and fails without it. + +Tests: `redirect_hops_stay_on_the_allow_list_and_never_drop_to_http`, +`cross_origin_hops_drop_secret_and_credential_headers` in `policy_tests.rs`, and +`each_redirect_hop_passes_the_hop_checks`, `each_redirect_status_runs_the_hop_checks` and +`a_hop_to_another_origin_drops_the_secret_header` in `step_tests.rs`. + +#### Errors of a request + +A refused request fails with `mds::network_denied`, and a failed send with `mds::network`, both +exit 2. The message starts with the request location: the module, the entry, the URL as +declared and the origin, escaped. A refusal then names the check and its reason: + +```text +network access denied for data entries: "main.mds", entry "u", URL "https://api.example/items/{{id}}", origin "https://api.example": allow-list: the origin is not in the allow list +``` + +The checks are `allow-list`, `import-opt-in`, `url-parser`, `redirect-check`, +`secret-binding`, `transport-address`, `response-check` and `method`. Each check has its own +fixed help. A `response-check` refusal ends with the secret name, as ` (secret "NAME")`. A +transport failure gives `network error in : `. The message never holds +the expanded URL, a header value, a secret value or response text +(`layer_names_are_distinct_kebab_case_words` in `policy_tests.rs`, +`a_response_value_in_a_failed_url_never_reaches_stderr` in `crates/mds-cli/tests/cli_net.rs`). + +#### Step compiles + +The Rust API sends requests through a host loop: `compile_step_native_fs`, `compile_step_virtual_fs` +and `compile_step_str`. Each takes the arguments of its compile function plus a `FetchContext` +(the `NetworkPolicy` and a per-run `RunKey`) and a `FetchState`. It returns `Step::Done` with the +`CompileResult`, or `Step::Need` with the requests that the compile needs: + +- A host starts with an empty `FetchState::new()`. On `Step::Need` it sends each request once, + adds each answer with `FetchState::with_response(id, response)` and calls the same function + again with the new state. A chain of entries needs one round per level and one more + (`a_two_level_chain_needs_one_round_per_level_and_one_more` in `step_tests.rs`). +- Each call is a fresh compile with a fresh budget. It derives every request again and runs every + check again, so a narrower policy on a later call takes effect. +- An imported module and an `@extends` base are modules other than the entry module, so their URL + entries need the import opt-in of the policy (`import-opt-in`) and cannot use a secret header + (`mds::data`, `a secret header is allowed in the entry module only`) + (`a_base_url_entry_reads_a_child_frontmatter_variable` and + `an_extends_base_cannot_use_a_secret_header` in `crates/mds-core/src/data/step_tests.rs`). + The secret header rule also applies to an entry that replay satisfies, in a step compile and in + a plain compile (`a_replayed_secret_header_is_allowed_in_the_entry_module_only` in + `step_tests.rs` and in `crates/mds-core/tests/data_resolve.rs`). +- The state holds responses only, keyed by `RequestId` (64 lower-case hex digits). A second + response for one ID fails with `mds::invalid_options` + (`the fetch state already holds a response for this request`). More than 64 responses fail + with `mds::resource_limit`, and so does a body that takes the raw bodies of the state past + 200 MiB (§4.1 "Network limits"). `FetchState::body_bytes_left` gives the body bytes that the + state can still take, so that a host can cap its reads. A host read past its share gives + `MdsError::response_bodies_exceeded`, the error of the total. A response that the compile + did not request fails with `mds::invalid_options` (§5). +- A host gives a failure as a fixed `TransportFailure` kind. `AddressRefused` fails with + `mds::network_denied` (`transport-address`), each other kind with `mds::network`. +- `CompileResult.remote_inputs` lists each bound URL entry as its module, entry, URL as declared + and origin, never the expanded URL. `dependencies` never lists a URL. The canonical JSON writes + `remoteInputs` only when the list is not empty, with each field WIRE-escaped (§7.5). +- A message, a help, a warning, a `Debug` view and a result field show the URL as declared and + the origin only. They never show the expanded path or query, a header value, a secret value or + response text. A data rule error of a response body names the entry, without the key path that + a data file error names (§4.12 "Conversion"). `Debug` of a `Request` shows its ID, method, URL + as declared, origin and header names. + +Tests: `crates/mds-core/tests/data_step.rs` and `crates/mds-core/tests/net_sinks.rs`. + +#### Status envelope + +The value of a URL entry is the converted response body. A status that is not 2xx fails with +`mds::network` (`the server answered with HTTP status `). A request map with `envelope: true` +binds `{status, headers, body}` for any final status from 200 to 599: + +- `status` is the number. `body` is the converted body, and `null` for a `HEAD` request. +- A header name becomes lower case, and each `-` becomes `_`, so `{{a.headers.x_rate_limit}}` + reads `X-Rate-Limit`. A name that is then not an identifier is dropped. `set-cookie` and + `set-cookie2` are dropped. +- A repeated header joins its values with `, `, in received order. Two different names that give + the same key fail with `mds::data` (`two response header names give the same envelope key`). +- A header value follows the character rule of data strings below. A value that breaks it fails + with `mds::data`. The message names the field `headers`, never a header name or value. +- A redirect is followed as without the envelope. The envelope holds the final answer. +- One response can bind a body entry and an envelope entry of the same request. + +Tests: `envelope_tests.rs` in `crates/mds-core/src/data/`, and +`a_status_that_is_not_2xx_binds_only_with_the_envelope`, +`the_envelope_binds_a_status_from_200_to_599_only`, `a_head_envelope_has_a_null_body` and +`one_response_binds_a_body_entry_and_an_envelope_entry` in `crates/mds-core/src/data/step_tests.rs`. + #### Conversion The extension of the resolved file selects the parser. @@ -1399,7 +1694,6 @@ on a case-insensitive volume, a resolved key with no data extension - A `.json` file and a `.yaml` or `.yml` file use different parsers. The same text can give a value in one format and an error in the other. For example, a YAML comment is valid in a `.yaml` file and a syntax error in a `.json` file. -- This release fetches no URL. A URL entry needs a replay value. - A data file counts toward the compile memory budget (§5). Dense data can reach that budget before the 32 MiB data limit (`assert_data_items_share_one_limit` in `crates/mds-core/tests/memory_bound.rs`). - The WASM backend of `@mdscript/mds` reads each local data file that a module lists before the @@ -1636,7 +1930,7 @@ breaking change. "Exit" is the CLI exit class (§7.9) for `mds build`, `mds check`, `mds fmt` and `mds watch` startup — 1 template or content error, 2 I/O error, file-system error, or -network access denied, 3 resource limit, 101 internal compiler error — followed by the `mds lint` code, which +network access denied or a network failure, 3 resource limit, 101 internal compiler error — followed by the `mds lint` code, which reports analysis failures as 2 except for the two carve-outs shown. The CLI's own stream and I/O failures are described below the table. @@ -1647,7 +1941,7 @@ and I/O failures are described below the table. | `mds::undefined_fn` | Function not defined with `@define` or imported | validator | 1 / 2 | all | | `mds::arity` | Wrong number of arguments in a call | validator | 1 / 2 | all | | `mds::builtin` | A built-in function rejected its arguments at runtime | evaluator | 1 / 2 | all | -| `mds::type_error` | `@for` over a value that is not an array | evaluator | 1 / 2 | all | +| `mds::type_error` | `@for` over a value that is not an array; or a data value in a request URL or header that is not a string, a boolean or an exact integer up to 2^53 (null, an array, an object or another number). The data message names the project-relative module, the entry and the field, escaped, with no source span | evaluator, resolver | 1 / 2 | all | | `mds::type_mismatch` | Cross-type `==` / `!=` comparison | evaluator | 1 / 2 | all | | `mds::circular_import` | Import graph contains a cycle | resolver | 1 / 2 | all | | `mds::file_not_found` | Entry file, import target or local data file (§4.12) does not exist, or a directory above it does not, or the path cannot otherwise be resolved — a symlink loop, a name too long, a directory that cannot be searched (native filesystem) | `NativeFs`, CLI input check; `@mdscript/mds`'s WASM-backend file pre-scanner, with the native message | 2 / 2 | CLI, Rust, napi, Python, `@mdscript/mds` | @@ -1659,7 +1953,8 @@ and I/O failures are described below the table. | `mds::yaml` | Frontmatter YAML the parser refuses (syntax, duplicate keys, nesting beyond the parser's limits — §4.1), or a [reserved output key form error](#reserved-output-keys). Also, a syntax error in a YAML or JSON data file. For a data file, the message names the project-relative file and the entry, escaped, without source text. | resolver | 1 / 2 | all | | `mds::json` | Malformed JSON, or a non-object root, in `load_vars_str` and other JSON sites except data files | `mds-core` vars API | 1 / 2 | Rust, CLI | | `mds::data` | Invalid data declaration or a data value that violates the data rules, such as a duplicate key or a number outside the supported range. The message names the project-relative module and, where applicable, the entry and field. These labels are escaped. The error has no source span. | resolver | 1 / 2 | CLI, Rust, napi, WASM, Python | -| `mds::network_denied` | A compile needs a network data entry with no replay value. The message names the entries and their project-relative modules, escaped, with no source span. | resolver | 2 / 2 | CLI, Rust, napi, WASM, Python | +| `mds::network_denied` | A compile needs a network data entry with no replay value. The message names the entries and their project-relative modules, escaped, with no source span; the help is the replay help. Also a step compile that refuses a request (§4.12 "Step compiles"): the message names the module, the entry, the URL as declared and the origin, escaped, then the check (`allow-list`, `import-opt-in`, `url-parser`, `redirect-check`, `secret-binding`, `transport-address`, `response-check` or `method`) and its fixed reason, and a secret by name only. The help is fixed text for each check. The Rust constructor is `MdsError::network_refused`. | resolver | 2 / 2 | CLI, Rust, napi, WASM, Python | +| `mds::network` | A request of a network data entry failed in transport, or its answer has a status that is not 2xx and the entry has no status envelope (`the server answered with HTTP status `). The message names the project-relative module, the entry, the URL as declared and the origin, escaped, with no source span. It never holds the expanded URL, a header value or a body. | resolver | 2 / 2 | CLI, Rust | | `mds::invalid_vars` | `--vars` file is malformed JSON or not an object (`load_vars_file`) | `mds-core` vars API | 1 / 2 | CLI, Rust | | `mds::var_conflict` | Same key given to both `--set` and `--set-string` | CLI | 1 / 1 | CLI | | `mds::module_not_found` | Virtual backend: a key absent from the module map. For a data file: `data file '' is not in the virtual module map` (§4.12) | `VirtualFs`, `@mdscript/mds` WASM backend | 1 / 2 | napi, WASM, Python, Rust, `@mdscript/mds` | @@ -1671,7 +1966,7 @@ and I/O failures are described below the table. | `mds::expected_messages` | Rust API only: `CompileResult::into_messages()` on a markdown result | `mds-core` API | n/a | Rust | | `mds::formatter_invariant` | The formatter's rewrite failed the compile-equivalence gate — a formatter defect; nothing is written | formatter | 1 / n/a | CLI (`fmt`), Rust | | `mds::internal` | A lexer step that does not advance or a failed memory-counter check at the end of a compile (§5 "Compile memory budget"), or an evaluator read of a pending data entry, which the check calls never do (§4.12). Each gives `internal compiler error` with no help and no span. Also: a panic caught at a binding boundary, or a result that could not be serialised; the raw payload is attached as `detail` only under the off-by-default `debug-panics` feature (`SECURITY.md`). On the CLI, also the error `mds lint --format json` records for an input whose analysis panicked, with the fixed message `internal compiler error` and nothing of the panic (§5 "Panics on the CLI") | lexer (the progress check); resolver (the counter check); napi, WASM, Python; `mds lint` | 101 / 101 | all | -| `mds::invalid_options` | Malformed or type-incorrect options: unknown keys, wrong types, `basePath` on file methods or on the WASM backend, source-map options on `check`, an empty `basePath`, a WASM `moduleAliases` entry that is not a normalized module key or names no module (`options.moduleAliases[""]: `) | napi, WASM, Python, `@mdscript/mds` | n/a | napi, WASM, Python, `@mdscript/mds` | +| `mds::invalid_options` | Malformed or type-incorrect options: unknown keys, wrong types, `basePath` on file methods or on the WASM backend, source-map options on `check`, an empty `basePath`, a WASM `moduleAliases` entry that is not a normalized module key or names no module (`options.moduleAliases[""]: `). In the core, a step compile whose fetch state holds a response that the compile did not request (`invalid options: the fetch state holds a response that this compile did not request`), and a second response for one request ID in a fetch state (`invalid options: the fetch state already holds a response for this request`), fixed text with no source span (§4.12 "Step compiles"). In `mds build`, a network flag or a `network` key of `mds.json` that the policy refuses: an allow item, a `--secret` value, a `--tls-root` file that is not a PEM list of valid roots, or a `network` section that is wider than the flags (§7.2, §7.8). The message names the flag or the field, never a secret value | napi, WASM, Python, `@mdscript/mds`; resolver (step compile); CLI (`mds build`) | 2 / n/a | napi, WASM, Python, `@mdscript/mds`, Rust, CLI | | `mds::filename_collision` | `options.modules` already contains the entry `filename` | WASM (surfaced through `@mdscript/mds`) | n/a | WASM, `@mdscript/mds` | | `mds::invalid_backend_result` | The selected backend returned a result of an unexpected shape | `@mdscript/mds` | n/a | `@mdscript/mds` | @@ -1866,6 +2161,34 @@ mds build src/ --out-dir dist # Mirror subtree: src/a/b.mds → dis | `--inline` | Embed the source map as a data-URI comment in the compiled output instead of a sidecar. Requires `--source-map`. | | `--embed-sources` | Embed source file contents in `sourcesContent[]`. Ships full source text — use with care. Requires `--source-map`. | | `-q, --quiet` | Suppress status messages on stderr on a successful run. The directory-mode summary is suppressed on a fully-successful run; it is still emitted when any file fails. (The directory-depth warning is emitted regardless of `--quiet`. `--quiet` suppresses the warning that keeps a stale output or sidecar; one that cannot be read or removed is an error, and `--quiet` never suppresses an error.) | +| `--allow-net ` | Send the requests of URL data entries to these origins (§4.12 "Network access"). A comma-separated list of 1 to 64 allow items: `host`, `host:port`, `https://host[:port]` or `http://host:port`. Without this flag the network stays off, whatever `mds.json` holds, and a URL entry with no runtime value fails with `mds::network_denied`. A refused item fails with `mds::invalid_options` (exit 2) before the compile starts: `--allow-net item "": `. | +| `--allow-net-imports` | Let the URL entries of imported modules and `@extends` bases send. Requires `--allow-net`. | +| `--secret NAME=env:VAR@ORIGIN` | Give the host secret `NAME` with the value of the environment variable `VAR`, for requests to the `https` origin `ORIGIN` only (§4.12 "Network access"). Repeatable, at most 16. Requires `--allow-net`. A message names the index, `NAME` and `VAR`, never the value or the flag text: for example `--secret[0] "TOKEN": the environment variable API_TOKEN is not set` (`mds::invalid_options`, exit 2). In a directory build, each `.mds` file of the tree that is not a partial compiles as its own entry module with the same network flags, so each such file can use the secret header form (`{secret: NAME, prefix: …}`). | +| `--tls-root ` | Add the certificates of a PEM file to the trust roots. Repeatable. Requires `--allow-net`. A forbidden path character and a final symlink are refused, and the file must be a regular file of at most 1 MiB (`mds::io`, exit 2; a larger file is `mds::resource_limit`, exit 3). A file that is not PEM, holds no certificate or holds a root that is not a valid trust anchor fails with `mds::invalid_options` (exit 2) and names the file. | + +**Network access** (`--allow-net`): + +- `mds build` sends the requests of URL data entries only with `--allow-net`. The `network` + section of `mds.json` (§7.8) can only narrow the flags. `mds watch`, `mds check`, `mds lint` + and `mds fmt` have no network flags, so the parser refuses them there, and they send nothing. +- Each compile runs step compiles (§4.12 "Step compiles"). A round sends its requests in groups + of at most 8 at a time. Each request is sent once, with no retry. One 30 s deadline binds the + network work of a compile from its first send, and one run sends at most 512 requests over all + of its files (§4.1 "Network limits"). A directory build uses one grant and one count for all of + its files. Stdin builds send too. +- The sender ignores the proxy environment variables (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, + `NO_PROXY`, in upper or lower case). It uses TLS 1.2 or 1.3 and always checks the certificate. The + trust roots are the Mozilla list and the `--tls-root` files, never the roots of the system or + of the environment. +- A refused request fails with `mds::network_denied`, and a failed send with `mds::network`, both + exit 2 (§4.12 "Errors of a request"). The run prints no request text. + +Tests: `crates/mds-cli/tests/cli_net.rs` (`no_flag_opens_no_connection_whatever_mds_json_allows`, +`mds_json_can_only_narrow_the_flag`, `a_redirect_to_an_unlisted_origin_fails_with_no_connection`, +`an_echoed_secret_stops_the_chain_and_tls_needs_the_host_root`, +`an_unlisted_origin_is_denied_and_no_answer_is_a_network_failure`, +`an_imported_url_entry_needs_the_import_opt_in`, `proxy_variables_change_no_target`, +`stdin_and_directory_builds_send` and `tooling_never_sends_and_refuses_the_network_flags`). **Output path resolution** (precedence order, highest first): @@ -2392,6 +2715,12 @@ Place `mds.json` in the repository root or any ancestor directory of the input f | `build.embed_sources` | bool | Embed source file contents in `sourcesContent[]` (equivalent to `--embed-sources`). Has no effect when `build.source_map` is `false`. Default: `false`. | | `lint.rules` | object | Per-rule severity overrides for `mds lint`. Keys are rule names; values are `"off"`, `"info"`, `"warn"`, or `"error"`. Any other value fails config loading (exit 1; under `mds lint` an `mds::io` error, exit 2, §5), naming the rule and the value as the bindings name a `rules` value — `lint.rules[""]: unknown severity ""; expected "off", "info", "warn", or "error"`, or `lint.rules[""] must be a severity string, got ` for a value that is not a string — each WIRE-escaped (§7.5). An unknown rule name emits a warning naming it and listing the rules this build recognises, the config still loads, and lint continues — the unknown rule is not enforced (forward compat: a config naming a rule added in a newer release warns instead of failing on an older binary). Under `mds lint`, the warning goes to stderr, names `mds.json` as the run reached it (`warning: in ./mds.json: …`, `sub/../mds.json`, as a config error names it) and is suppressed by `--quiet`; `mds build`, `mds watch` and directory-mode `mds fmt` also read this file but do not emit the unknown-rule warning, and `mds check` does not read it. On the `lint` API surfaces it is returned in `lint_warnings`. | | `fmt.sort_frontmatter_keys` | bool | **Reserved — accepted, currently inert.** The key is parsed and type-checked (a non-boolean value is a hard config-load error, like any other field) so that `{"fmt": {"sort_frontmatter_keys": true}}` is valid today, but it drives no formatting behaviour in this version: `mds fmt` does not sort frontmatter keys and there is no matching CLI flag. Frontmatter key sorting is deferred to a future version; when it ships, this key will control it without a breaking `mds.json` schema change. Default: `true`. Pinned by `fmt_config_valid_section_loads_cleanly` and `fmt_config_malformed_bool_field_fails_loading` in `crates/mds-cli/src/build/config.rs`. | +| `network.allow` | array of strings | A narrower allow list for `mds build --allow-net` (§7.2). Each item has the grammar of `--allow-net` and is parsed when the config loads; a refused item fails config loading (exit 1, `network.allow[]: `). Each item must permit no request that the `--allow-net` list refuses; else `mds build` fails with `mds::invalid_options`, exit 2, before the compile starts (`./mds.json network.allow[]: the item permits a request that the --allow-net list refuses`). Default: the `--allow-net` list. | +| `network.allow_imports` | bool | The import opt-in for `mds build --allow-net`. `true` needs `--allow-net-imports`; else `mds build` fails with `mds::invalid_options`, exit 2 (`./mds.json network.allow_imports: true needs --allow-net-imports`). `false` turns the opt-in off. Default: the value of `--allow-net-imports`. | + +The `network` section can only narrow the flags. Without `--allow-net`, the network stays off, +whatever the section holds. Another key in `network` fails config loading (exit 1). `mds watch`, +`mds check`, `mds lint` and `mds fmt` send nothing, so the section has no effect on them. Maximum config file size: 1 MiB (1,048,576 bytes). @@ -2409,7 +2738,8 @@ Maximum config file size: 1 MiB (1,048,576 bytes). For data sources, `mds::data` is a content error (exit 1). A data file that does not parse is `mds::yaml` (exit 1, `tooling_reads_no_data_file` in `crates/mds-cli/tests/cli_data.rs`). -`mds::network_denied` has exit 2. A data limit has exit 3 (`mds::resource_limit`). +`mds::network_denied` and `mds::network` have exit 2. A data limit or a network limit has exit 3 (`mds::resource_limit`). +A network flag of `mds build`, or a `network` key of `mds.json`, that the policy refuses is `mds::invalid_options`, exit 2 (§7.2, §7.8). An output refused over a data file that the run reads is `mds::io`, exit 2 (§7.2, `build_never_writes_over_a_data_file_it_reads`). A closed stdout or stderr pipe never changes any of these codes (§5 "Streams and I/O failures"). @@ -2502,6 +2832,8 @@ Rules default to the severities shown below — **not all rules default to `warn | `duplicate-export` | **error** | yes (A) | A | The same export name is defined more than once in a single file. | | `legacy-interpolation` | warn | yes (A) | A | A legacy `{x}` interpolation can use `{{x}}` instead. | | `literal-directive` | warn | no | C | A conditional line stays literal: an indented line outside a fence without `indented-directives: true`, or a line in an unmarked fence with `@if …:` before `@end`. The rule skips fences with `mds` as the first info word. | +| `insecure-data-origin` | warn | no | C | A request map of a URL data entry (§4.12) names an `http://` URL. The http scheme does not encrypt the request or the response. The rule reads the declarations only and sends no request. | +| `literal-credential-header` | warn | no | C | A URL data entry (§4.12) sets a header to literal text, and the lower-case header name contains `token`, `secret`, `api-key`, `apikey` or `password`. A value with a `{{…}}` reference is not reported. The message names the entry and the header, never the value. Use the secret form `{secret: NAME, prefix: ''}`. | ¹ **`unused-import` is report-only in practice**: `fixable` is always `false` for this rule. A file that triggers `unused-import` contains at least one `@import` directive, making it non-*structural-standalone* (see below); Tier B fixes require a structural-standalone file. The rule is still useful — the warning clears as a side effect of applying other fixes (e.g. removing a duplicate import that was also the unused one). To silence it, set `"unused-import": "off"` in `mds.json`. @@ -2679,7 +3011,7 @@ These are intentionally deferred to keep the language simple and the compiler fo - TypeScript/JS *language* features (note: runtime bindings for calling the compiler from JS/TS *are* provided via the `@mdscript/mds` npm package; this item refers to in-template scripting, which is out of scope) - Unbounded recursion: direct recursion is rejected; indirect chains are capped at depth 128 (see §4.5) - Macros, async functions, streaming -- URL-based imports (remote modules). A `data:` URL entry (§4.12) names data, not a module. This release does not fetch it: a URL entry needs a replay value. +- URL-based imports (remote modules). A `data:` URL entry (§4.12) names data, not a module. Only `mds build --allow-net` and the Rust step API fetch it; elsewhere a URL entry needs a replay value. - Function calls in `@if` conditions (e.g. `@if length(items) == 0:`) — not supported - Function calls in `@for` iterables (e.g. `@for item in split(csv, ","):`) — not supported - Parenthesized sub-expressions in conditions (e.g. `@if (a || b) && c:`) — not supported