From 46dc18ece4395cacdf0095b0f81740b53e60ba17 Mon Sep 17 00:00:00 2001 From: PurpleCHOIms Date: Sat, 5 Dec 2026 10:06:11 +0900 Subject: [PATCH 1/2] Port sandbox web route learning store to Rust --- CHAGELOG.md | 2 + .../rust-sandbox-web-learning-20261205.md | 43 +++ runtime/sandbox-web/.gitignore | 1 + runtime/sandbox-web/Cargo.lock | 322 ++++++++++++++++++ runtime/sandbox-web/Cargo.toml | 5 + runtime/sandbox-web/README.md | 7 +- runtime/sandbox-web/src/learning.rs | 234 +++++++++++++ runtime/sandbox-web/src/lib.rs | 1 + runtime/sandbox-web/src/url_parts.rs | 4 + runtime/sandbox-web/tests/learning_store.rs | 133 ++++++++ 10 files changed, 750 insertions(+), 2 deletions(-) create mode 100644 docs/verification/rust-sandbox-web-learning-20261205.md create mode 100644 runtime/sandbox-web/.gitignore create mode 100644 runtime/sandbox-web/src/learning.rs create mode 100644 runtime/sandbox-web/tests/learning_store.rs diff --git a/CHAGELOG.md b/CHAGELOG.md index 1d6ecc430..b659df0fc 100644 --- a/CHAGELOG.md +++ b/CHAGELOG.md @@ -15,6 +15,8 @@ Keep proposed and unmerged changes out of released sections. ## [Unreleased] +- Proposed Rust sandbox web route learning ([change branch](https://github.com/BitterSecurity/Decepticon/compare/feat/rust-sandbox-web-core-pr...feat/sandbox-web-learning), stacked on [#1220](https://github.com/BitterSecurity/Decepticon/pull/1220)): port the per-host JSON route store, 30-day expiry, 500-entry cap, success counts and failure strikes. The active Python sandbox engine and Docker image remain in use; no user data migration or OSS release is required. [Local comparison and verification](docs/verification/rust-sandbox-web-learning-20261205.md). + - Proposed Rust sandbox web policy core ([#1220](https://github.com/BitterSecurity/Decepticon/pull/1220)): add a standalone local library for URL transforms, SSRF/redirect policy, WAF detection, allowlisted search parsing and response validation. The current Python sandbox engine and Docker image remain in use, so users need no migration step and existing behavior is unchanged. No OSS package version or release is assigned. [Local verification and remaining integration](docs/verification/rust-sandbox-web-core-20261205.md). - Proposed per-run proxy credential correction ([#1211](https://github.com/BitterSecurity/Decepticon/pull/1211)): preserve selected-model streaming, usage, token limits, retry/timeout settings, vendor protocol subclasses and HTTP transports when binding an engagement key. Refuse dispatch if an explicit key cannot be bound instead of silently using the environment account; requests without a per-run key are unchanged. No package version, publication or deployment. [Verification and compatibility](docs/verification/proxy-key-transport-20261120.md). diff --git a/docs/verification/rust-sandbox-web-learning-20261205.md b/docs/verification/rust-sandbox-web-learning-20261205.md new file mode 100644 index 000000000..f9232c676 --- /dev/null +++ b/docs/verification/rust-sandbox-web-learning-20261205.md @@ -0,0 +1,43 @@ +# Rust sandbox web learning store verification + +Source baseline: Decepticon OSS `6b15092d`, +`packages/decepticon/decepticon_sandbox/web/learning.py`. The new Rust module +is `runtime/sandbox-web/src/learning.rs` and stays outside the active sandbox +image. This PR is a proposed library port, with no release or Python removal. + +The Python CLI starts a fresh process for each web request. Two Rust shapes were +considered. Free functions could pass a path through every call. A +`LearningStore` owns that path and the TTL and entry limits, while each method +reloads the JSON file. The latter keeps the per-call file behavior and gives +future sandbox callers one configuration point. The store accepts a path from +its caller; it does not verify the engagement workspace. That check belongs to +the Rust command entry point when it is ported. + +With Python's clock fixed at `2026-12-05T00:00:00+00:00`, direct source calls +recorded these cases: + +| Case | Python result | Rust check | +| --- | --- | --- | +| URL `https://User:Pass@Example.COM:443/path?x=1`, mobile | `user:pass@example.com:443::mobile` | `python_recorded_keys_and_failure_classes` | +| Same route recorded twice | `wins=2`, `consecutive_fails=0` | `python_recorded_wins_and_failure_strikes` | +| Transient failure, then two real blocks | `0`, `1`, then entry removed | `python_recorded_wins_and_failure_strikes` | +| 31-day-old entry, invalid timestamp and two recent entries with cap 2 | `unknown::desktop`, `today::desktop` retained | `python_recorded_ttl_and_lru` | +| Timestamp with 123000 microseconds | `2026-12-05T00:00:00.123000+00:00` | `timestamp_keeps_python_microsecond_width` | + +The Rust store accepts the Python JSON format. It writes sorted keys through +a unique temporary file and replaces the destination. Like the Python source, +a corrupt or unreadable file reads as an empty store and a failed write does +not fail the fetch. Concurrent process writes can still lose one update; the +active Python store has the same limitation. + +Local gate on 2026-12-05: + +- `cargo +1.100 fmt --manifest-path runtime/sandbox-web/Cargo.toml --check` passed. +- `bash /home/catow/.local/bin/with-build-slot cargo +1.100 test --locked --offline --manifest-path runtime/sandbox-web/Cargo.toml --all-targets` passed: 31 library tests and five learning integration tests. +- `bash /home/catow/.local/bin/with-build-slot cargo +1.100 clippy --locked --offline --manifest-path runtime/sandbox-web/Cargo.toml --all-targets -- -D warnings` passed. +- `git diff --check` passed. + +These checks cover the library and source-recorded behavior. The sandbox image +still uses Python learning and Python fetch execution. Rust transport, fetch +chain, browser fallback and the CLI envelope must be ported and tested before +the image can switch to the Rust binary. diff --git a/runtime/sandbox-web/.gitignore b/runtime/sandbox-web/.gitignore new file mode 100644 index 000000000..b83d22266 --- /dev/null +++ b/runtime/sandbox-web/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/runtime/sandbox-web/Cargo.lock b/runtime/sandbox-web/Cargo.lock index ef5aae309..af85bb2dc 100644 --- a/runtime/sandbox-web/Cargo.lock +++ b/runtime/sandbox-web/Cargo.lock @@ -11,18 +11,66 @@ dependencies = [ "memchr", ] +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "cssparser" version = "0.38.0" @@ -50,12 +98,15 @@ dependencies = [ name = "decepticon-sandbox-web" version = "0.0.0" dependencies = [ + "chrono", "glob", + "indexmap", "regex", "scraper", "serde", "serde_json", "serde_yaml_ng", + "tempfile", "unicode-normalization", "url", ] @@ -119,12 +170,28 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + [[package]] name = "fastrand" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + [[package]] name = "form_urlencoded" version = "1.2.3" @@ -134,6 +201,30 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + [[package]] name = "getopts" version = "0.2.24" @@ -143,6 +234,17 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + [[package]] name = "glob" version = "0.3.4" @@ -166,6 +268,30 @@ dependencies = [ "memchr", ] +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "icu_collections" version = "2.4.0" @@ -278,6 +404,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown", + "serde", + "serde_core", ] [[package]] @@ -286,12 +414,29 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.3" @@ -336,6 +481,21 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + [[package]] name = "parking_lot" version = "0.12.5" @@ -418,6 +578,12 @@ dependencies = [ "siphasher", ] +[[package]] +name = "pin-project-lite" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" + [[package]] name = "potential_utf" version = "0.1.6" @@ -451,6 +617,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + [[package]] name = "redox_syscall" version = "0.5.18" @@ -504,6 +676,25 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + [[package]] name = "ryu" version = "1.0.23" @@ -618,12 +809,24 @@ dependencies = [ "stable_deref_trait", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "siphasher" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + [[package]] name = "smallvec" version = "1.16.6" @@ -693,6 +896,19 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + [[package]] name = "tendril" version = "0.5.1" @@ -772,6 +988,50 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + [[package]] name = "web_atoms" version = "0.3.0" @@ -784,12 +1044,74 @@ dependencies = [ "string_cache_codegen", ] +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "writeable" version = "0.6.4" diff --git a/runtime/sandbox-web/Cargo.toml b/runtime/sandbox-web/Cargo.toml index c6065b498..9f8569f37 100644 --- a/runtime/sandbox-web/Cargo.toml +++ b/runtime/sandbox-web/Cargo.toml @@ -9,7 +9,9 @@ publish = false path = "src/lib.rs" [dependencies] +chrono = { version = "=0.4.45", default-features = false, features = ["clock", "std"] } glob = "=0.3.4" +indexmap = { version = "=2.14.2", features = ["serde"] } regex = "=1.13.2" scraper = "=0.29.0" serde = { version = "=1.0.229", features = ["derive"] } @@ -17,3 +19,6 @@ serde_json = "=1.0.154" serde_yaml_ng = "=0.10.0" unicode-normalization = "=0.1.26" url = "=2.5.9" + +[dev-dependencies] +tempfile = "=3.27.0" diff --git a/runtime/sandbox-web/README.md b/runtime/sandbox-web/README.md index 0603b31ed..d454e6728 100644 --- a/runtime/sandbox-web/README.md +++ b/runtime/sandbox-web/README.md @@ -12,6 +12,7 @@ the bundled WAF profile catalog. The OSS application remains local-only. | `waf_detector` | Generic WAF signal matching against the bundled YAML catalog | | `providers` | Closed DuckDuckGo search provider and HTML result parsing | | `validators` | Status, challenge, JSON, selector and content-size verdicts | +| `learning` | Per-host route history, expiry, failure strikes and bounded JSON storage | From the repository root, with Rust 1.100 installed: @@ -25,5 +26,7 @@ The current sandbox image still executes the Python web engine. Integrating this library requires a Rust fetch transport and command envelope, per-hop RoE and redirect checks, and the browser fallback before removing Python code or image dependencies. Host tools must keep using the approved OpenShell sandbox -route. [Verification and limits](../../docs/verification/rust-sandbox-web-core-20261205.md) -are recorded separately. +route. The learning store loads the file on each operation, matching the Python +subprocess lifecycle. The caller must supply a path inside its approved +workspace. See the [policy core verification](../../docs/verification/rust-sandbox-web-core-20261205.md) +and [learning store verification](../../docs/verification/rust-sandbox-web-learning-20261205.md). diff --git a/runtime/sandbox-web/src/learning.rs b/runtime/sandbox-web/src/learning.rs new file mode 100644 index 000000000..ab94fa7e8 --- /dev/null +++ b/runtime/sandbox-web/src/learning.rs @@ -0,0 +1,234 @@ +//! Per-host route learning persisted in a JSON file. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, SecondsFormat, Timelike, Utc}; +use indexmap::IndexMap; +use serde_json::{Map, Value, json}; + +use crate::url_parts::{UrlParts, normalized_urlsplit_input}; + +const EVICT_AFTER_FAILS: u64 = 2; +static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); + +type StoreData = IndexMap; + +pub struct LearningStore { + path: PathBuf, + ttl_days: i64, + max_entries: usize, +} + +impl LearningStore { + pub fn new(path: impl Into) -> Self { + Self::with_limits(path, 30, 500) + } + + pub fn with_limits(path: impl Into, ttl_days: i64, max_entries: usize) -> Self { + Self { + path: path.into(), + ttl_days, + max_entries, + } + } + + pub fn lookup(&self, url: &str, device_class: &str) -> Option> { + self.lookup_at(url, device_class, Utc::now()) + } + + pub fn lookup_at( + &self, + url: &str, + device_class: &str, + now: DateTime, + ) -> Option> { + self.load_at(now) + .get(&key_for(url, device_class))? + .get("route")? + .as_object() + .cloned() + } + + pub fn record_success(&self, url: &str, device_class: &str, route: Map) { + self.record_success_at(url, device_class, route, Utc::now()); + } + + pub fn record_success_at( + &self, + url: &str, + device_class: &str, + route: Map, + now: DateTime, + ) { + let mut data = self.load_at(now); + let key = key_for(url, device_class); + let old = data.get(&key); + let wins = if old + .and_then(|entry| entry.get("route")) + .and_then(Value::as_object) + == Some(&route) + { + old.and_then(|entry| entry.get("wins")) + .and_then(Value::as_u64) + .unwrap_or(0) + .saturating_add(1) + } else { + 1 + }; + let timestamp = timestamp(now); + data.insert( + key, + json!({ + "route": route, + "wins": wins, + "consecutive_fails": 0, + "last_used": timestamp, + "last_success": timestamp, + }), + ); + self.save(&self.prune(data, now)); + } + + pub fn record_failure(&self, url: &str, device_class: &str, penalize: bool) { + self.record_failure_at(url, device_class, penalize, Utc::now()); + } + + pub fn record_failure_at( + &self, + url: &str, + device_class: &str, + penalize: bool, + now: DateTime, + ) { + let mut data = self.load_at(now); + let key = key_for(url, device_class); + let Some(entry) = data.get_mut(&key).and_then(Value::as_object_mut) else { + return; + }; + if penalize { + let fails = entry + .get("consecutive_fails") + .and_then(Value::as_u64) + .unwrap_or(0) + .saturating_add(1); + if fails >= EVICT_AFTER_FAILS { + data.shift_remove(&key); + } else { + entry.insert("consecutive_fails".into(), json!(fails)); + entry.insert("last_used".into(), json!(timestamp(now))); + } + } else { + entry.insert("last_used".into(), json!(timestamp(now))); + } + self.save(&self.prune(data, now)); + } + + fn load_at(&self, now: DateTime) -> StoreData { + let Ok(bytes) = fs::read(&self.path) else { + return StoreData::new(); + }; + let Ok(data) = serde_json::from_slice::(&bytes) else { + return StoreData::new(); + }; + self.prune(data, now) + } + + fn prune(&self, mut data: StoreData, now: DateTime) -> StoreData { + let cutoff = now - Duration::days(self.ttl_days); + data.retain(|_, entry| entry_time(entry).is_none_or(|last_used| last_used >= cutoff)); + if data.len() > self.max_entries { + let mut ordered: Vec<_> = data.into_iter().collect(); + ordered.sort_by(|(_, left), (_, right)| { + entry_time(right) + .unwrap_or(now) + .cmp(&entry_time(left).unwrap_or(now)) + }); + ordered.truncate(self.max_entries); + data = ordered.into_iter().collect(); + } + data + } + + fn save(&self, data: &StoreData) { + let parent = self + .path + .parent() + .filter(|path| !path.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + if fs::create_dir_all(parent).is_err() { + return; + } + let sorted: BTreeMap<_, _> = data.iter().collect(); + let Ok(contents) = serde_json::to_vec_pretty(&sorted) else { + return; + }; + let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed); + let temp = temporary_path(&self.path, sequence); + if fs::write(&temp, contents).is_err() { + let _ = fs::remove_file(&temp); + return; + } + if fs::rename(&temp, &self.path).is_err() { + let _ = fs::remove_file(temp); + } + } +} + +fn temporary_path(path: &Path, sequence: u64) -> PathBuf { + let mut name = path.as_os_str().to_os_string(); + name.push(format!(".tmp.{}.{}", std::process::id(), sequence)); + PathBuf::from(name) +} + +fn entry_time(entry: &Value) -> Option> { + parse_time(entry.get("last_used")?.as_str()?) +} + +fn parse_time(value: &str) -> Option> { + if let Ok(parsed) = DateTime::parse_from_rfc3339(value) { + return Some(parsed.with_timezone(&Utc)); + } + for format in ["%Y-%m-%dT%H:%M:%S%.f", "%Y-%m-%d %H:%M:%S%.f"] { + if let Ok(parsed) = NaiveDateTime::parse_from_str(value, format) { + return Some(DateTime::from_naive_utc_and_offset(parsed, Utc)); + } + } + NaiveDate::parse_from_str(value, "%Y-%m-%d") + .ok() + .and_then(|date| date.and_hms_opt(0, 0, 0)) + .map(|date| DateTime::from_naive_utc_and_offset(date, Utc)) +} + +fn timestamp(now: DateTime) -> String { + let micros = now.nanosecond() / 1_000; + now.with_nanosecond(micros * 1_000) + .expect("microsecond is in range") + .to_rfc3339_opts( + if micros == 0 { + SecondsFormat::Secs + } else { + SecondsFormat::Micros + }, + false, + ) +} + +pub fn is_real_failure(stop_reason: &str) -> bool { + matches!(stop_reason, "exhausted" | "challenge" | "blocked") +} + +pub fn key_for(url: &str, device_class: &str) -> String { + let normalized = normalized_urlsplit_input(url); + let host = UrlParts::split(&normalized) + .map(|parts| parts.authority().to_lowercase()) + .unwrap_or_default(); + let device = if device_class == "mobile" { + "mobile" + } else { + "desktop" + }; + format!("{host}::{device}") +} diff --git a/runtime/sandbox-web/src/lib.rs b/runtime/sandbox-web/src/lib.rs index f07ebe583..ba510179b 100644 --- a/runtime/sandbox-web/src/lib.rs +++ b/runtime/sandbox-web/src/lib.rs @@ -1,5 +1,6 @@ mod url_parts; +pub mod learning; pub mod providers; pub mod safety; pub mod url_transforms; diff --git a/runtime/sandbox-web/src/url_parts.rs b/runtime/sandbox-web/src/url_parts.rs index 079d60934..ad95506ac 100644 --- a/runtime/sandbox-web/src/url_parts.rs +++ b/runtime/sandbox-web/src/url_parts.rs @@ -88,6 +88,10 @@ impl<'a> UrlParts<'a> { raw.to_lowercase() } + pub(crate) fn authority(&self) -> &str { + self.authority + } + pub(crate) fn validate(&self) -> Result<(), UrlPartsError> { self.validate_brackets()?; self.validate_netloc() diff --git a/runtime/sandbox-web/tests/learning_store.rs b/runtime/sandbox-web/tests/learning_store.rs new file mode 100644 index 000000000..c949c526c --- /dev/null +++ b/runtime/sandbox-web/tests/learning_store.rs @@ -0,0 +1,133 @@ +use chrono::{TimeZone, Utc}; +use decepticon_sandbox_web::learning::{LearningStore, is_real_failure, key_for}; +use serde_json::{Value, json}; +use tempfile::tempdir; + +#[test] +fn python_recorded_keys_and_failure_classes() { + let url = "https://User:Pass@Example.COM:443/path?x=1"; + assert_eq!(key_for(url, "mobile"), "user:pass@example.com:443::mobile"); + assert_eq!(key_for(url, "auto"), "user:pass@example.com:443::desktop"); + assert_eq!(key_for("", "desktop"), "::desktop"); + for reason in ["exhausted", "challenge", "blocked"] { + assert!(is_real_failure(reason)); + } + for reason in ["rate_limited", "not_found", ""] { + assert!(!is_real_failure(reason)); + } +} + +#[test] +fn python_recorded_wins_and_failure_strikes() { + let directory = tempdir().expect("temporary directory"); + let path = directory.path().join("learned.json"); + let store = LearningStore::new(&path); + let now = Utc.with_ymd_and_hms(2026, 12, 5, 0, 0, 0).unwrap(); + let url = "https://User:Pass@Example.COM:443/path?x=1"; + let route = json!({"impersonate":"safari","phase":"curl"}) + .as_object() + .expect("route object") + .clone(); + + store.record_success_at(url, "mobile", route.clone(), now); + store.record_success_at(url, "mobile", route.clone(), now); + assert_eq!(store.lookup_at(url, "mobile", now), Some(route)); + let data: Value = + serde_json::from_slice(&std::fs::read(&path).expect("saved store")).expect("store JSON"); + let entry = &data["user:pass@example.com:443::mobile"]; + assert_eq!(entry["wins"], 2); + assert_eq!(entry["consecutive_fails"], 0); + assert_eq!(entry["last_success"], "2026-12-05T00:00:00+00:00"); + + store.record_failure_at(url, "mobile", false, now); + let data: Value = + serde_json::from_slice(&std::fs::read(&path).expect("saved store")).expect("store JSON"); + assert_eq!( + data["user:pass@example.com:443::mobile"]["consecutive_fails"], + 0 + ); + store.record_failure_at(url, "mobile", true, now); + let data: Value = + serde_json::from_slice(&std::fs::read(&path).expect("saved store")).expect("store JSON"); + assert_eq!( + data["user:pass@example.com:443::mobile"]["consecutive_fails"], + 1 + ); + store.record_failure_at(url, "mobile", true, now); + assert_eq!(store.lookup_at(url, "mobile", now), None); + assert_eq!(std::fs::read_to_string(path).expect("saved store"), "{}"); +} + +#[test] +fn python_recorded_ttl_and_lru() { + let directory = tempdir().expect("temporary directory"); + let path = directory.path().join("learned.json"); + std::fs::write( + &path, + r#"{ + "old::desktop":{"route":{"id":"old"},"last_used":"2026-11-04T00:00:00+00:00"}, + "recent::desktop":{"route":{"id":"recent"},"last_used":"2026-12-04T00:00:00+00:00"}, + "unknown::desktop":{"route":{"id":"unknown"},"last_used":"invalid"}, + "today::desktop":{"route":{"id":"today"},"last_used":"2026-12-05T00:00:00+00:00"} + }"#, + ) + .expect("seed store"); + let store = LearningStore::with_limits(&path, 30, 2); + let now = Utc.with_ymd_and_hms(2026, 12, 5, 0, 0, 0).unwrap(); + assert!(store.lookup_at("https://unknown", "desktop", now).is_some()); + assert!(store.lookup_at("https://today", "desktop", now).is_some()); + assert!(store.lookup_at("https://old", "desktop", now).is_none()); + assert!(store.lookup_at("https://recent", "desktop", now).is_none()); +} + +#[test] +fn new_route_resets_win_count_and_corrupt_store_is_ignored() { + let directory = tempdir().expect("temporary directory"); + let path = directory.path().join("learned.json"); + std::fs::write(&path, b"not JSON").expect("seed corrupt store"); + let store = LearningStore::new(&path); + let now = Utc.with_ymd_and_hms(2026, 12, 5, 0, 0, 0).unwrap(); + assert!( + store + .lookup_at("https://example.com", "auto", now) + .is_none() + ); + store.record_success_at( + "https://example.com", + "auto", + json!({"phase":"curl"}).as_object().unwrap().clone(), + now, + ); + store.record_success_at( + "https://example.com", + "auto", + json!({"phase":"browser"}).as_object().unwrap().clone(), + now, + ); + let data: Value = + serde_json::from_slice(&std::fs::read(path).expect("saved store")).expect("store JSON"); + assert_eq!(data["example.com::desktop"]["wins"], 1); + assert_eq!(data["example.com::desktop"]["route"]["phase"], "browser"); +} + +#[test] +fn timestamp_keeps_python_microsecond_width() { + let directory = tempdir().expect("temporary directory"); + let path = directory.path().join("learned.json"); + let store = LearningStore::new(&path); + let now = chrono::DateTime::parse_from_rfc3339("2026-12-05T00:00:00.123000+00:00") + .expect("fixed timestamp") + .with_timezone(&Utc); + store.record_success_at( + "https://example.com", + "desktop", + json!({"phase":"curl"}).as_object().unwrap().clone(), + now, + ); + let data: Value = + serde_json::from_slice(&std::fs::read(path).expect("saved store")).expect("store JSON"); + assert_eq!( + data["example.com::desktop"]["last_used"], + "2026-12-05T00:00:00.123000+00:00" + ); +} From d42700752d7b2641fe91e4190eb46a3f4e55a346 Mon Sep 17 00:00:00 2001 From: PurpleCHOIms Date: Sat, 5 Dec 2026 10:07:09 +0900 Subject: [PATCH 2/2] docs(chagelog): link sandbox web learning PR --- CHAGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHAGELOG.md b/CHAGELOG.md index b659df0fc..bcbb38dc1 100644 --- a/CHAGELOG.md +++ b/CHAGELOG.md @@ -15,7 +15,7 @@ Keep proposed and unmerged changes out of released sections. ## [Unreleased] -- Proposed Rust sandbox web route learning ([change branch](https://github.com/BitterSecurity/Decepticon/compare/feat/rust-sandbox-web-core-pr...feat/sandbox-web-learning), stacked on [#1220](https://github.com/BitterSecurity/Decepticon/pull/1220)): port the per-host JSON route store, 30-day expiry, 500-entry cap, success counts and failure strikes. The active Python sandbox engine and Docker image remain in use; no user data migration or OSS release is required. [Local comparison and verification](docs/verification/rust-sandbox-web-learning-20261205.md). +- Proposed Rust sandbox web route learning ([#1221](https://github.com/BitterSecurity/Decepticon/pull/1221), stacked on [#1220](https://github.com/BitterSecurity/Decepticon/pull/1220)): port the per-host JSON route store, 30-day expiry, 500-entry cap, success counts and failure strikes. The active Python sandbox engine and Docker image remain in use; no user data migration or OSS release is required. [Local comparison and verification](docs/verification/rust-sandbox-web-learning-20261205.md). - Proposed Rust sandbox web policy core ([#1220](https://github.com/BitterSecurity/Decepticon/pull/1220)): add a standalone local library for URL transforms, SSRF/redirect policy, WAF detection, allowlisted search parsing and response validation. The current Python sandbox engine and Docker image remain in use, so users need no migration step and existing behavior is unchanged. No OSS package version or release is assigned. [Local verification and remaining integration](docs/verification/rust-sandbox-web-core-20261205.md).