Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHAGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ Keep proposed and unmerged changes out of released sections.

## [Unreleased]

- Proposed Rust sandbox web session pool ([#1223](https://github.com/BitterSecurity/Decepticon/pull/1223), stacked on [#1222](https://github.com/BitterSecurity/Decepticon/pull/1222)): reuse browser-profile HTTP clients per host, warm the root once, transfer browser cookies and User-Agent, and report session statistics. The active Python sandbox engine and Docker image remain in use; no OSS release or data migration is required. [Local comparison and verification](docs/verification/rust-sandbox-web-session-pool-20261205.md).

- Proposed Rust sandbox web HTTP transport ([#1222](https://github.com/BitterSecurity/Decepticon/pull/1222), stacked on [#1221](https://github.com/BitterSecurity/Decepticon/pull/1221)): use pinned browser-profile HTTP clients with persistent cookies, check redirect targets before following them, and reject private address literals and DNS answers in the default unmanaged configuration. The active Python sandbox engine remains in use, and no OSS release or user data migration is required. [Local comparison and verification](docs/verification/rust-sandbox-web-transport-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).
Expand Down
59 changes: 59 additions & 0 deletions docs/verification/rust-sandbox-web-session-pool-20261205.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Rust sandbox web session pool verification

Source baseline: Decepticon OSS `6b15092d`,
`packages/decepticon/decepticon_sandbox/web/transport.py`. This stacked
Rust unit lives in `runtime/sandbox-web/src/session_pool.rs` and extends
`transport.rs`. The active sandbox image still runs Python.

The pool owns one browser-profile HTTP client and cookie jar per
`(lowercase host, profile)` key. It marks root warmup before making a request,
so concurrent calls cannot send duplicate warmups. It keeps the client's
cookies and connection state for later deep requests. Browser cookies are
added as typed cookies; a missing path defaults to `/` as in Python, and an
unrelated domain or public suffix is rejected before the jar sees it.
`__Secure-` and `__Host-` cookies retain Secure semantics, and
`__Host-` cookies stay host-only with path `/` even when the browser envelope
omits those attributes, matching
[curl_cffi's cookie setter](https://curl-cffi.readthedocs.io/en/v0.16.1/_modules/curl_cffi/requests/cookies.html).
The
caller supplies the same address policy and
optional RoE predicate used by the checked redirect transport. A blocked
initial request does not create a pool entry. A blocked root is marked
warmed without a network request. Requests retain the Python transport's
default Accept and Korean/English Accept-Language headers, plus an optional
Referer and caller header overrides.

The Python source was run locally with a fake session and
`INSANE_ALLOW_PRIVATE=1`. The recorded sequence produced
`warmup=True`, second warmup `False`, cookie injection `True`, statistics
`{sessions: 1, warmed: 1, requests: 1}`, injected User-Agent
`browser-agent`, and zeroed statistics after reset. Rust tests cover the
same one-time warmup and reset behavior, plus a real local HTTP exchange
where the warmup cookie reaches a deep request and an injected browser cookie
from that deep URL reaches a sibling path on the same profile. A blocked
warmup and unrelated cookie domain
are tested separately.

Local gate on 2026-12-05:

- Rust 1.100 format and `git diff --check`: passed.
- Shared-slot `cargo test --locked --offline --all-targets`: passed, with
33 library tests, five learning tests, four session pool tests and nine
transport tests.
- Shared-slot `cargo clippy --locked --offline --all-targets -- -D warnings`:
passed.

The WSL host needs `libclang.so` for wreq's BoringSSL binding generator.
The gate uses temporary Ubuntu libclang/LLVM files extracted under
`/dev/shm`, with process-local build environment variables. No system
package is installed.

The pool is not wired into the sandbox command or Docker image. The Rust
fetch chain, browser fallback and command envelope remain. Its browser
profiles have not been compared with curl_cffi fingerprints or success rates
on approved live targets. The current browser envelopes omit cookie path,
Secure and host-only scope. Both the Python bridge and this parity port can
broaden a path-scoped or host-only browser cookie when those fields are
missing. The browser envelope and Rust bridge must preserve the original
cookie scope before they replace the active path. No user data migration or OSS
release occurs.
18 changes: 18 additions & 0 deletions runtime/sandbox-web/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion runtime/sandbox-web/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ path = "src/lib.rs"

[dependencies]
chrono = { version = "=0.4.45", default-features = false, features = ["clock", "std"] }
cookie = "=0.18.3"
glob = "=0.3.4"
indexmap = { version = "=2.14.2", features = ["serde"] }
psl = "=2.1.243"
regex = "=1.13.2"
scraper = "=0.29.0"
serde = { version = "=1.0.229", features = ["derive"] }
Expand All @@ -20,7 +22,7 @@ serde_yaml_ng = "=0.10.0"
tokio = { version = "=1.52.3", features = ["io-util", "macros", "net", "rt-multi-thread", "time"] }
unicode-normalization = "=0.1.26"
url = "=2.5.9"
wreq = { version = "=0.16.5", default-features = false, features = ["tokio-rt", "webpki-roots", "cookies", "brotli", "deflate", "gzip"] }
wreq = { version = "=0.16.5", default-features = false, features = ["tokio-rt", "webpki-roots", "cookies", "cookies-psl", "brotli", "deflate", "gzip"] }
wreq-util = "=0.2.1"

[dev-dependencies]
Expand Down
22 changes: 14 additions & 8 deletions runtime/sandbox-web/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ the bundled WAF profile catalog. The OSS application remains local-only.
| `validators` | Status, challenge, JSON, selector and content-size verdicts |
| `learning` | Per-host route history, expiry, failure strikes and bounded JSON storage |
| `transport` | Browser-profile HTTP GET with manual, checked redirects |
| `session_pool` | Per-host/profile client reuse, root warmup, browser cookie bridge and request statistics |

From the repository root, with Rust 1.100 installed:

Expand All @@ -24,16 +25,21 @@ cargo +1.100 fmt --manifest-path runtime/sandbox-web/Cargo.toml --check
```

The current sandbox image still executes the Python web engine. Integrating
this library requires the fetch chain, command envelope, per-host session pool,
browser cookie bridge and browser fallback before removing Python code or image
dependencies. The Rust transport checks the supplied scope predicate and
address policy before every redirect target and disables automatic redirects
in its HTTP client. With the default unmanaged configuration, the client also
rejects private address literals, filters private and reserved DNS answers at connection time, and disables
system proxies. OpenShell remains the network authority for managed sessions.
this library requires the fetch chain, command envelope and browser fallback
before removing Python code or image dependencies. The Rust transport checks
the supplied scope predicate and address policy before every redirect target.
Its HTTP client disables automatic redirects. With the default unmanaged
configuration, the client also rejects private address literals, filters
private and reserved DNS answers at connection time, and disables system
proxies. OpenShell remains the network authority for managed sessions.
Host tools must keep using the approved OpenShell sandbox 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),
the [learning store verification](../../docs/verification/rust-sandbox-web-learning-20261205.md),
and the [transport verification](../../docs/verification/rust-sandbox-web-transport-20261205.md).
the [transport verification](../../docs/verification/rust-sandbox-web-transport-20261205.md),
and the [session pool verification](../../docs/verification/rust-sandbox-web-session-pool-20261205.md).
The session pool reuses one browser-profile client per host, warms a deep URL's
root once, and accepts cookies and User-Agent from a browser response.
The browser envelope and bridge must preserve each cookie's original path,
Secure flag and host-only scope before this bridge replaces the Python path.
1 change: 1 addition & 0 deletions runtime/sandbox-web/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod url_parts;
pub mod learning;
pub mod providers;
pub mod safety;
pub mod session_pool;
pub mod transport;
pub mod url_transforms;
pub mod validators;
Expand Down
204 changes: 204 additions & 0 deletions runtime/sandbox-web/src/session_pool.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
use std::collections::HashMap;
use std::env;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use crate::safety::{DnsResolver, SafetyPolicy, allow_private_default};
use crate::transport::{
BrowserCookie, FetchError, FetchOutcome, WreqHttpGet, canonical_url, check_url, fetch_following,
};

type SessionKey = (String, String);

struct Session {
client: WreqHttpGet,
warmed: AtomicBool,
injected_ua: Mutex<Option<String>>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PoolStats {
pub sessions: usize,
pub warmed: usize,
pub requests: usize,
}

pub struct RequestSpec<'a> {
pub url: &'a str,
pub profile: &'a str,
pub referer: Option<&'a str>,
pub headers: &'a [(String, String)],
pub timeout: Duration,
pub max_redirects: usize,
}

pub struct SessionPool {
entries: Mutex<HashMap<SessionKey, Arc<Session>>>,
allow_private: bool,
}

impl SessionPool {
pub fn new(allow_private: bool) -> Self {
Self {
entries: Mutex::new(HashMap::new()),
allow_private,
}
}

pub fn from_environment() -> Self {
Self::new(allow_private_default())
}

fn entry(&self, url: &str, profile: &str) -> Result<Arc<Session>, String> {
let parsed = url::Url::parse(url).map_err(|error| error.to_string())?;
let host = parsed
.host_str()
.ok_or_else(|| "URL has no host".to_owned())?
.to_ascii_lowercase();
let key = (host, profile.to_owned());
let mut entries = self.entries.lock().expect("session pool lock");
if let Some(entry) = entries.get(&key) {
return Ok(Arc::clone(entry));
}
let entry = Arc::new(Session {
client: WreqHttpGet::with_private_addresses(profile, self.allow_private)?,
warmed: AtomicBool::new(false),
injected_ua: Mutex::new(None),
});
entries.insert(key, Arc::clone(&entry));
Ok(entry)
}

pub async fn request<R: DnsResolver>(
&self,
policy: &SafetyPolicy<R>,
scope_check: Option<&dyn Fn(&str) -> bool>,
spec: RequestSpec<'_>,
) -> Result<FetchOutcome, FetchError> {
let canonical = canonical_url(spec.url)?;
check_url(policy, scope_check, &canonical, false)?;
let entry = self
.entry(&canonical, spec.profile)
.map_err(FetchError::Network)?;
let mut headers: Vec<(String, String)> = vec![
(
"Accept".into(),
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8".into(),
),
(
"Accept-Language".into(),
"ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7".into(),
),
];
if let Some(referer) = spec.referer.filter(|value| !value.is_empty()) {
headers.push(("Referer".into(), referer.into()));
}
for (name, value) in spec.headers {
if let Some((_, existing)) = headers
.iter_mut()
.find(|(existing, _)| existing.eq_ignore_ascii_case(name))
{
*existing = value.clone();
} else {
headers.push((name.clone(), value.clone()));
}
}
if !headers
.iter()
.any(|(name, _)| name.eq_ignore_ascii_case("user-agent"))
&& let Some(user_agent) = entry.injected_ua.lock().expect("injected UA lock").as_ref()
{
headers.push(("User-Agent".into(), user_agent.clone()));
}
fetch_following(
&entry.client,
policy,
scope_check,
&canonical,
&headers,
spec.timeout,
spec.max_redirects,
)
.await
}

pub async fn warmup<R: DnsResolver>(
&self,
policy: &SafetyPolicy<R>,
scope_check: Option<&dyn Fn(&str) -> bool>,
url: &str,
profile: &str,
timeout: Duration,
max_redirects: usize,
) -> bool {
let Ok(mut root) = url::Url::parse(url) else {
return false;
};
root.set_path("/");
root.set_query(None);
root.set_fragment(None);
let root = root.to_string();
if root == url {
return false;
}
let Ok(entry) = self.entry(url, profile) else {
return false;
};
if entry.warmed.swap(true, Ordering::AcqRel) {
return false;
}
fetch_following(
&entry.client,
policy,
scope_check,
&root,
&[],
timeout,
max_redirects,
)
.await
.is_ok()
}

pub fn inject_cookies(
&self,
url: &str,
profile: &str,
cookies: &[BrowserCookie],
user_agent: Option<&str>,
) -> Result<bool, String> {
let entry = self.entry(url, profile)?;
let added = entry.client.inject_cookies(url, cookies);
if let Some(user_agent) = user_agent.filter(|value| !value.is_empty()) {
*entry.injected_ua.lock().expect("injected UA lock") = Some(user_agent.to_owned());
}
Ok(added > 0)
}

pub fn stats(&self) -> PoolStats {
let entries = self.entries.lock().expect("session pool lock");
PoolStats {
sessions: entries.len(),
warmed: entries
.values()
.filter(|entry| entry.warmed.load(Ordering::Relaxed))
.count(),
requests: entries
.values()
.map(|entry| entry.client.requests_made())
.sum(),
}
}

pub fn reset(&self) {
self.entries.lock().expect("session pool lock").clear();
}
}

pub fn pool_enabled() -> bool {
!matches!(
env::var("INSANE_NO_SESSION_POOL").as_deref(),
Ok("1" | "true" | "yes")
)
}
Loading