test(e2e): port corporate-proxy tests from e2e/rust to features/corporate-proxy (#5786)

* test(tmachine): add a corporate-proxy environment with a TLS-intercepting proxy

Run one corporate proxy in the guest that serves TLS, requires Basic auth and
intercepts the TLS in every tunnel with its own CA. It merges the three
fixture proxies from the legacy corporate-proxy tests into one asyncio
service, since TLS inside the listener's TLS needs asyncio's start_tls.

Point the gateway's driver at it through the gateway_overrides role, with a
port-qualified no_proxy entry, and publish
OPENSHELL_TEST_CORPORATE_PROXY_{URL,CA_CERT,BYPASS_PORT,LOG}.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>

* test(support): add a corporate-proxy fixture that reads the proxy's CONNECT log

Read OPENSHELL_TEST_CORPORATE_PROXY_* and parse the proxy's JSON-lines log
from a cursor, so a test sees only the CONNECTs its own sandbox made.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>

* test(support): check whether a named Podman secret exists

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>

* test(features): port the corporate-proxy e2e tests to testkit

Check sandbox egress through the environment's corporate proxy: approved
requests are proxied with credentials and a validated IP target, denied ones
never reach the proxy, the no_proxy port is dialed direct, and on Podman the
per-sandbox credentials secret goes away with the sandbox. A second test
checks that the supervisor and the workload both trust the intercepting
proxy's CA.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>

* test(e2e): run the corporate-proxy suite on Docker and Podman environments

Add features/corporate-proxy rows for the rootful Docker and the rootful and
rootless Podman corporate-proxy environments, and list the environment's
OPENSHELL_TEST_CORPORATE_PROXY_* variables in the contract table.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>

* test(e2e): remove the legacy Docker and Podman corporate-proxy tests

features/corporate-proxy replaces them. Their TOML-editing helper test
checked only the file's own helper, so it goes with the file.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>

* ci(e2e): drop the rootless Podman corporate-proxy row

Sandbox creation fails there because Podman can't relabel the root-owned
proxy CA bind mount. Tracked in #5795.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>

* test(features): run the corporate-proxy suite with testkit's own harness

Declare the test target with harness = false and call testkit::main, as
every feature package does since #5789, and point the new crates at the
ai-openshell repository.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>

* ci(e2e): run corporate-proxy on rootless Podman and skip its known failures

Add the fedora-podman-rootless-corporate-proxy row back and list both tests
as unsupported there until #5795 is fixed.

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>

---------

Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>
This commit is contained in:
Matthew Grossman
2026-12-01 16:38:35 +00:00
committed by GitHub
parent 2ba7db55b4
commit 6a8afe9de1
23 changed files with 1226 additions and 2066 deletions
+3
View File
@@ -103,6 +103,9 @@ jobs:
{"environment":"ubuntu-docker-rootful-cdi","installer":"deb","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"fedora-podman-rootful-cdi","installer":"rpm","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"fedora-podman-rootless-cdi","installer":"rpm","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"ubuntu-docker-rootful-corporate-proxy","installer":"deb","family":"features","package":"corporate-proxy","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"fedora-podman-rootful-corporate-proxy","installer":"rpm","family":"features","package":"corporate-proxy","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"fedora-podman-rootless-corporate-proxy","installer":"rpm","family":"features","package":"corporate-proxy","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"ubuntu-docker-rootful-keycloak","installer":"deb","family":"features","package":"keycloak-provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"oci-image","gateway":"openshell","runner":"ubuntu-24.04"},
{"environment":"fedora-podman-rootful","installer":"rpm","family":"features","package":"oci-image","gateway":"openshell","runner":"ubuntu-24.04"},
+1 -1
View File
@@ -1029,7 +1029,7 @@ cargo test --manifest-path e2e/rust/Cargo.toml --features e2e --test sync
Run a single Docker-only test directly with cargo:
```shell
cargo test --manifest-path e2e/rust/Cargo.toml --features e2e-docker --test docker_corporate_proxy
cargo test --manifest-path e2e/rust/Cargo.toml --features e2e-docker --test gateway_start
```
The harness (`e2e/rust/src/harness/`) provides:
-10
View File
@@ -83,11 +83,6 @@ name = "vm_bind_mount"
path = "tests/vm_bind_mount.rs"
required-features = ["e2e-vm"]
[[test]]
name = "docker_corporate_proxy"
path = "tests/docker_corporate_proxy.rs"
required-features = ["e2e-docker"]
[[test]]
name = "additional_ca"
path = "tests/additional_ca.rs"
@@ -128,11 +123,6 @@ name = "ocsf_jsonl_conformance"
path = "tests/ocsf_jsonl_conformance.rs"
required-features = ["e2e-podman"]
[[test]]
name = "podman_corporate_proxy"
path = "tests/podman_corporate_proxy.rs"
required-features = ["e2e-podman"]
[[test]]
name = "podman_resource_limits"
path = "tests/podman_resource_limits.rs"
-1
View File
@@ -29,7 +29,6 @@ PODMAN_CI_TESTS=(
local_driver_token_restart
ocsf_jsonl_conformance
otlp_relay
podman_corporate_proxy
podman_gateway_start
podman_host_gateway
provider_github_app
File diff suppressed because it is too large Load Diff
-918
View File
@@ -1,918 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
#![cfg(feature = "e2e-podman")]
//! Cross-layer E2E coverage for corporate forward-proxy egress (issue #1792).
//!
//! Every other test for this feature builds a config struct or calls a CONNECT
//! helper directly, so none of them can catch a break in the wiring *between*
//! layers. This test drives the whole chain end to end:
//!
//! gateway TOML → Podman driver config → supervisor argv + secret mount →
//! supervisor CLI parsing → policy evaluation → proxied CONNECT
//!
//! against a fake authenticated forward proxy, and asserts the four properties
//! that only a real run can establish:
//!
//! 1. A policy-approved HTTPS request reaches its destination *through* the
//! proxy, and the CONNECT target is a validated IP rather than a hostname.
//! 2. A policy-denied destination never reaches the proxy at all.
//! 3. Credentials arrive via the mounted Podman secret — the proxy answers 407
//! to an unauthenticated CONNECT, so a 200 response proves delivery.
//! 4. Deleting the sandbox removes the per-sandbox Podman secret.
use std::io::Write as _;
use std::os::unix::fs::PermissionsExt as _;
use std::path::PathBuf;
use std::time::Duration;
use openshell_e2e::harness::cli::wait_for_healthy;
use openshell_e2e::harness::container::{ContainerEngine, HostSupportContainer};
use openshell_e2e::harness::gateway::ManagedGateway;
use openshell_e2e::harness::port::find_free_port;
use openshell_e2e::harness::sandbox::SandboxGuard;
use serial_test::serial;
use tempfile::NamedTempFile;
const HOST_ALIAS: &str = "host.openshell.internal";
const PROXY_USER: &str = "proxyuser";
const PROXY_PASS: &str = "proxypass";
const ALLOWED_MARKER: &str = "corp-proxy-e2e-allowed-upstream";
const DENIED_MARKER: &str = "corp-proxy-e2e-denied-upstream";
const READY_MARKER: &str = "corp-proxy-e2e-workload-done";
const SECRET_PREFIX: &str = "openshell-proxy-auth-";
/// A forward proxy that requires Basic auth and logs every CONNECT it sees.
///
/// The log lines are the test's evidence: they record the exact CONNECT target
/// (proving validated-IP vs hostname form) and whether credentials arrived.
fn proxy_script(port: u16) -> String {
format!(
r#"
import base64, select, socket, threading
EXPECTED = 'Basic ' + base64.b64encode(b'{PROXY_USER}:{PROXY_PASS}').decode()
def log(msg):
print(msg, flush=True)
def read_head(conn):
data = b''
while b'\r\n\r\n' not in data:
chunk = conn.recv(4096)
if not chunk:
return None
data += chunk
if len(data) > 65536:
return None
return data
def pipe(a, b):
try:
while True:
ready, _, _ = select.select([a, b], [], [])
for sock in ready:
chunk = sock.recv(65536)
if not chunk:
return
(b if sock is a else a).sendall(chunk)
except OSError:
return
def handle(conn):
try:
head = read_head(conn)
if head is None:
# Readiness probes connect and close without sending a request.
return
lines = head.decode('latin-1').split('\r\n')
parts = lines[0].split()
if len(parts) < 2 or parts[0].upper() != 'CONNECT':
log('NON_CONNECT %s' % lines[0])
conn.sendall(b'HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n')
return
target = parts[1]
auth = None
for line in lines[1:]:
if line.lower().startswith('proxy-authorization:'):
auth = line.split(':', 1)[1].strip()
if auth != EXPECTED:
log('CONNECT %s auth=fail' % target)
conn.sendall(b'HTTP/1.1 407 Proxy Authentication Required\r\n'
b'Proxy-Authenticate: Basic realm="corp"\r\n'
b'Content-Length: 0\r\n\r\n')
return
host, _, port = target.rpartition(':')
host = host.strip('[]')
try:
upstream = socket.create_connection((host, int(port)), timeout=10)
except OSError:
log('CONNECT %s auth=ok dial=fail' % target)
conn.sendall(b'HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n')
return
log('CONNECT %s auth=ok' % target)
conn.sendall(b'HTTP/1.1 200 Connection Established\r\n\r\n')
pipe(conn, upstream)
upstream.close()
except OSError:
pass
finally:
conn.close()
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', {port}))
server.listen(64)
log('proxy-listening')
while True:
client, _ = server.accept()
threading.Thread(target=handle, args=(client,), daemon=True).start()
"#
)
}
// Delimits the proxy's CA certificate in its stdout, so the test can recover
// it and hand it back as the corporate CA bundle.
const CA_BEGIN: &str = "---PROXY-CA-BEGIN---";
const CA_END: &str = "---PROXY-CA-END---";
/// A forward proxy that terminates TLS with a CA-signed certificate and logs
/// every CONNECT it sees.
///
/// The container generates a corporate CA and a separate listener leaf signed
/// by it (SAN = the proxy alias, which is the name the supervisor uses for
/// SNI), serves the leaf, and prints the CA between [`CA_BEGIN`]/[`CA_END`] so
/// the test can trust it via `proxy_ca_bundle`. The listener certificate must
/// be a leaf: rustls rejects a `CA:TRUE` certificate presented as an
/// end-entity certificate (`CaUsedAsEndEntity`), so a single self-signed
/// `openssl req -x509` certificate — which is a CA by default — cannot serve
/// as both the anchor and the listener identity. Signing a leaf also matches
/// what a real intercepting proxy does. No Basic auth: this test isolates the
/// `https://` proxy + corporate-CA path; credential delivery is covered by the
/// plaintext-proxy test.
fn tls_proxy_script(port: u16) -> String {
format!(
r"
import os, select, socket, ssl, subprocess, tempfile, threading
workdir = tempfile.mkdtemp()
ca_key = os.path.join(workdir, 'ca-key.pem')
ca_crt = os.path.join(workdir, 'ca.pem')
leaf_key = os.path.join(workdir, 'leaf-key.pem')
leaf_csr = os.path.join(workdir, 'leaf.csr')
leaf_crt = os.path.join(workdir, 'leaf.pem')
chain = os.path.join(workdir, 'chain.pem')
ext = os.path.join(workdir, 'leaf.ext')
def run(*args):
subprocess.run(args, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
run('openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes',
'-keyout', ca_key, '-out', ca_crt, '-days', '1',
'-subj', '/CN=corp-proxy-e2e-ca')
with open(ext, 'w') as fh:
fh.write('basicConstraints=critical,CA:FALSE\n'
'subjectAltName=DNS:{HOST_ALIAS}\n'
'extendedKeyUsage=serverAuth\n')
run('openssl', 'req', '-newkey', 'rsa:2048', '-nodes',
'-keyout', leaf_key, '-out', leaf_csr, '-subj', '/CN={HOST_ALIAS}')
run('openssl', 'x509', '-req', '-in', leaf_csr, '-CA', ca_crt, '-CAkey', ca_key,
'-CAcreateserial', '-out', leaf_crt, '-days', '1', '-extfile', ext)
with open(chain, 'w') as out:
for part in (leaf_crt, ca_crt):
with open(part) as fh:
out.write(fh.read())
with open(ca_crt) as fh:
print('{CA_BEGIN}\n' + fh.read() + '{CA_END}', flush=True)
def log(msg):
print(msg, flush=True)
def read_head(conn):
data = b''
while b'\r\n\r\n' not in data:
chunk = conn.recv(4096)
if not chunk:
return None
data += chunk
if len(data) > 65536:
return None
return data
def pipe(a, b):
try:
while True:
ready, _, _ = select.select([a, b], [], [])
for sock in ready:
chunk = sock.recv(65536)
if not chunk:
return
(b if sock is a else a).sendall(chunk)
except OSError:
return
def handle(conn):
try:
head = read_head(conn)
if head is None:
return
lines = head.decode('latin-1').split('\r\n')
parts = lines[0].split()
if len(parts) < 2 or parts[0].upper() != 'CONNECT':
log('NON_CONNECT %s' % lines[0])
conn.sendall(b'HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n')
return
target = parts[1]
host, _, port = target.rpartition(':')
host = host.strip('[]')
try:
upstream = socket.create_connection((host, int(port)), timeout=10)
except OSError:
log('CONNECT %s dial=fail' % target)
conn.sendall(b'HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n')
return
log('CONNECT %s ok' % target)
conn.sendall(b'HTTP/1.1 200 Connection Established\r\n\r\n')
pipe(conn, upstream)
upstream.close()
except OSError:
pass
finally:
conn.close()
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(chain, leaf_key)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', {port}))
server.listen(64)
log('tls-proxy-listening')
while True:
raw, _ = server.accept()
try:
conn = ctx.wrap_socket(raw, server_side=True)
except OSError:
# Readiness probes open a bare TCP connection; the failed handshake is
# expected and must not spam the log.
raw.close()
continue
threading.Thread(target=handle, args=(conn,), daemon=True).start()
"
)
}
/// Extract the proxy's CA certificate PEM from its stdout.
fn ca_cert_from_logs(logs: &str) -> Result<String, String> {
let start = logs
.find(CA_BEGIN)
.ok_or_else(|| format!("proxy CA begin marker not found in logs:\n{logs}"))?
+ CA_BEGIN.len();
let end = logs[start..]
.find(CA_END)
.ok_or_else(|| format!("proxy CA end marker not found in logs:\n{logs}"))?;
Ok(logs[start..start + end].trim().to_string())
}
/// A TLS server with a self-signed certificate, serving one identifying marker.
///
/// The sandbox workload uses an unverified TLS context, so the certificate only
/// needs to exist — but the TLS handshake itself must be real, because it is
/// what proves bytes flowed end to end through the tunnel.
fn tls_upstream_script(common_name: &str, marker: &str, port: u16) -> String {
format!(
r#"
import http.server, os, ssl, subprocess, tempfile
workdir = tempfile.mkdtemp()
key = os.path.join(workdir, 'key.pem')
crt = os.path.join(workdir, 'cert.pem')
subprocess.run(
['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes',
'-keyout', key, '-out', crt, '-days', '1', '-subj', '/CN={common_name}'],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
body = b'{{"upstream":"{marker}"}}'
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, fmt, *args):
pass
class Server(http.server.HTTPServer):
# Readiness probes open a bare TCP connection and close it; the failed
# handshake is expected and must not spam the log.
def handle_error(self, request, client_address):
pass
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(crt, key)
server = Server(('0.0.0.0', {port}), Handler)
server.socket = ctx.wrap_socket(server.socket, server_side=True)
print('tls-upstream-listening', flush=True)
server.serve_forever()
"#
)
}
/// Workload: one approved HTTPS request, one denied, then idle so the test can
/// inspect the live sandbox's Podman secret before deleting it.
fn workload_script(allowed_port: u16, denied_port: u16) -> String {
format!(
r"
import json, ssl, time, urllib.request
ctx = ssl._create_unverified_context()
def fetch(url, retries):
last = {{'status': -1, 'error': 'not attempted'}}
for attempt in range(retries):
try:
with urllib.request.urlopen(url, timeout=30, context=ctx) as resp:
return {{'status': resp.status, 'body': resp.read().decode()}}
except Exception as err:
last = {{'status': -1, 'error': str(err)}}
time.sleep(1)
return last
# The approved request is retried: policy reload during sandbox startup can
# transiently surface as a 403 in the forward proxy.
print('ALLOWED_RESULT ' + json.dumps(
fetch('https://{HOST_ALIAS}:{allowed_port}/', 6)), flush=True)
# The denied request must fail, so a single attempt is enough.
print('DENIED_RESULT ' + json.dumps(
fetch('https://{HOST_ALIAS}:{denied_port}/', 1)), flush=True)
print('{READY_MARKER}', flush=True)
while True:
time.sleep(1)
"
)
}
/// Policy allowing only the approved upstream. `tls: skip` keeps the tunnel raw
/// so the workload's TLS session runs end to end to the upstream, which is what
/// makes the proxied CONNECT path observable.
fn policy_yaml(allowed_port: u16) -> String {
format!(
r#"version: 1
filesystem_policy:
include_workdir: true
read_only:
- /usr
- /lib
- /proc
- /dev/urandom
- /app
- /etc
- /var/log
read_write:
- /sandbox
- /tmp
- /dev/null
landlock:
compatibility: best_effort
process:
run_as_user: sandbox
run_as_group: sandbox
network_policies:
corporate_proxy_e2e:
name: corporate_proxy_e2e
endpoints:
- host: {HOST_ALIAS}
port: {allowed_port}
tls: skip
enforcement: enforce
allowed_ips:
- "10.0.0.0/8"
- "172.0.0.0/8"
- "192.168.0.0/16"
- "fc00::/7"
binaries:
- path: /usr/bin/curl
- path: /usr/bin/python*
- path: /usr/local/bin/python*
- path: /sandbox/.venv/bin/python*
- path: /sandbox/.uv/python/*/bin/python*
"#
)
}
/// Appends corporate-proxy keys to the harness-generated gateway TOML and
/// restores the original file when dropped.
///
/// The `[openshell.drivers.podman]` table is the last one the harness writes,
/// so appending bare keys lands in that table without introducing a duplicate
/// table header.
struct GatewayProxyConfig {
config_path: PathBuf,
original: Vec<u8>,
restored: bool,
}
impl GatewayProxyConfig {
/// Locate the gateway's `--config` path from the wrapper's args file.
fn config_path_from_args() -> Result<PathBuf, String> {
let args_file = std::env::var("OPENSHELL_E2E_GATEWAY_ARGS_FILE")
.map_err(|_| "OPENSHELL_E2E_GATEWAY_ARGS_FILE must be set".to_string())?;
let raw = std::fs::read(&args_file)
.map_err(|err| format!("read gateway args file '{args_file}': {err}"))?;
let args: Vec<String> = raw
.split(|byte| *byte == 0)
.filter(|arg| !arg.is_empty())
.map(|arg| String::from_utf8_lossy(arg).into_owned())
.collect();
args.iter()
.position(|arg| arg == "--config")
.and_then(|index| args.get(index + 1))
.map(PathBuf::from)
.ok_or_else(|| format!("no --config argument in gateway args file '{args_file}'"))
}
/// Rewrite the gateway config with corporate-proxy settings and restart the
/// gateway so the Podman driver picks them up.
async fn apply(proxy_url: &str, auth_file: &str) -> Result<Self, String> {
Self::apply_with(proxy_url, Some(auth_file), None).await
}
/// Like [`apply`], but with optional proxy credentials and an optional
/// corporate CA bundle path (for an `https://` proxy).
async fn apply_with(
proxy_url: &str,
auth_file: Option<&str>,
ca_bundle: Option<&str>,
) -> Result<Self, String> {
let config_path = Self::config_path_from_args()?;
let original = std::fs::read(&config_path)
.map_err(|err| format!("read gateway config '{}': {err}", config_path.display()))?;
let mut proxy_config = format!("https_proxy = \"{proxy_url}\"\n");
if let Some(auth_file) = auth_file {
proxy_config.push_str(&format!(
"proxy_auth_file = \"{auth_file}\"\n\
proxy_auth_allow_insecure = true\n"
));
}
if let Some(ca_bundle) = ca_bundle {
proxy_config.push_str(&format!("proxy_ca_bundle = \"{ca_bundle}\"\n"));
}
// Insert the proxy fields at the end of the Podman driver table. The
// generated config may add driver subtables (for example
// `resource_admission`) before the gateway JWT and auth tables, so a
// gateway-table marker is not a reliable boundary.
let podman_table = b"[openshell.drivers.podman]";
let table_start = original
.windows(podman_table.len())
.position(|window| window == podman_table)
.ok_or_else(|| {
format!(
"gateway config '{}' has no Podman driver table",
config_path.display()
)
})?;
let table_body = table_start + podman_table.len();
let next_table = b"\n[";
let offset = original[table_body..]
.windows(next_table.len())
.position(|window| window == next_table)
.map_or(original.len(), |relative| table_body + relative);
let mut updated = Vec::with_capacity(original.len() + proxy_config.len() + 1);
updated.extend_from_slice(&original[..offset]);
if !updated.ends_with(b"\n") {
updated.push(b'\n');
}
updated.extend_from_slice(proxy_config.as_bytes());
updated.extend_from_slice(&original[offset..]);
std::fs::write(&config_path, &updated)
.map_err(|err| format!("write gateway config '{}': {err}", config_path.display()))?;
let guard = Self {
config_path,
original,
restored: false,
};
restart_gateway().await?;
Ok(guard)
}
/// Restore the original config and restart the gateway.
async fn restore(&mut self) -> Result<(), String> {
if self.restored {
return Ok(());
}
std::fs::write(&self.config_path, &self.original).map_err(|err| {
format!(
"restore gateway config '{}': {err}",
self.config_path.display()
)
})?;
restart_gateway().await?;
self.restored = true;
Ok(())
}
}
impl Drop for GatewayProxyConfig {
fn drop(&mut self) {
if self.restored {
return;
}
// Panic path: put the original config back and synchronously restart the
// gateway so later test binaries in this run inherit neither the proxy
// settings on disk nor the temporary configuration still loaded in the
// running process. Nothing else restarts it here: the only
// `ManagedGateway` is the short-lived one inside `restart_gateway`, and
// its `Drop` only calls `start`, which does not reload config for an
// already-running gateway.
let _ = std::fs::write(&self.config_path, &self.original);
if let Ok(Some(gateway)) = ManagedGateway::from_env() {
let _ = gateway.stop();
let _ = gateway.start();
}
}
}
async fn restart_gateway() -> Result<(), String> {
let gateway = ManagedGateway::from_env()?
.ok_or_else(|| "managed gateway metadata disappeared".to_string())?;
gateway.stop()?;
gateway.start()?;
wait_for_healthy(Duration::from_mins(2)).await
}
/// Names of the per-sandbox corporate proxy credential secrets.
fn proxy_auth_secret_names() -> Result<Vec<String>, String> {
let engine = ContainerEngine::from_env()?;
let output = engine
.command()
.args(["secret", "ls", "--format", "{{.Name}}"])
.output()
.map_err(|err| format!("list container secrets: {err}"))?;
if !output.status.success() {
return Err(format!(
"secret ls failed (exit {:?}):\n{}",
output.status.code(),
String::from_utf8_lossy(&output.stderr)
));
}
Ok(String::from_utf8_lossy(&output.stdout)
.lines()
.map(str::trim)
.filter(|name| name.starts_with(SECRET_PREFIX))
.map(ToOwned::to_owned)
.collect())
}
async fn wait_for_secret_removal(secret: &str, timeout: Duration) -> Result<(), String> {
let start = std::time::Instant::now();
loop {
if !proxy_auth_secret_names()?.iter().any(|name| name == secret) {
return Ok(());
}
if start.elapsed() > timeout {
return Err(format!(
"proxy-auth secret '{secret}' still present {}s after sandbox deletion",
timeout.as_secs()
));
}
tokio::time::sleep(Duration::from_secs(2)).await;
}
}
/// Assert the workload's results and the proxy's own record of what it saw.
///
/// `output` is the sandbox's stdout; `proxy_logs` is the fake proxy's log,
/// which is the only place the CONNECT target form and the credential outcome
/// are observable.
fn assert_proxied_egress(output: &str, proxy_logs: &str, allowed_port: u16, denied_port: u16) {
// The approved request succeeded and its body came from the upstream,
// proving bytes traversed the tunnel rather than the proxy short-circuiting.
assert!(
output.contains("ALLOWED_RESULT") && output.contains(ALLOWED_MARKER),
"approved HTTPS request should have reached the upstream through the proxy:\n{output}"
);
assert!(
output.contains(r#""status": 200"#),
"approved HTTPS request should have returned 200:\n{output}"
);
// The denied destination failed inside the sandbox. Depending on where the
// isolated Podman path rejects it, this is either the supervisor's HTTP 403
// or a fail-closed socket permission error. The proxy-log assertion below
// rules out a vacuous failure after upstream contact.
let denied_line = output
.lines()
.find(|line| line.contains("DENIED_RESULT"))
.unwrap_or_default();
assert!(
denied_line.contains(r#""status": -1"#)
&& (denied_line.contains("403") || denied_line.contains("Permission denied")),
"denied destination should have been refused by policy:\n{output}"
);
assert!(
!output.contains(DENIED_MARKER),
"denied destination's body must never reach the sandbox:\n{output}"
);
// Credentials arrived through the mounted secret: the proxy answers 407
// without them, so a completed CONNECT is proof of delivery.
assert!(
proxy_logs.lines().any(|line| {
line.starts_with("CONNECT ") && line.contains(&format!(":{allowed_port} auth=ok"))
}),
"proxy should have seen an authenticated validated-IP CONNECT to \
host port {allowed_port}.\nProxy logs:\n{proxy_logs}\nSandbox output:\n{output}"
);
assert!(
!proxy_logs.contains("auth=fail"),
"proxy must never see an unauthenticated CONNECT:\n{proxy_logs}"
);
// The CONNECT target is a validated IP, not a hostname — the proxy performs
// no DNS resolution of its own, so the tunnel stays bound to the address
// that passed SSRF and allowed_ips validation.
assert!(
!proxy_logs.contains(HOST_ALIAS),
"CONNECT should target a validated IP, not the hostname:\n{proxy_logs}"
);
// The denied destination never reached the proxy: policy denial happens
// before any upstream contact. Its dedicated host port makes this
// observable even though both fixtures use the driver-neutral host alias.
assert!(
!proxy_logs
.lines()
.any(|line| line.starts_with("CONNECT ") && line.contains(&format!(":{denied_port} "))),
"policy-denied host port {denied_port} must never reach the proxy:\n{proxy_logs}"
);
}
#[tokio::test]
#[serial(corporate_proxy)]
async fn podman_corporate_proxy_routes_approved_tls_egress() {
if std::env::var("OPENSHELL_E2E_DRIVER").as_deref() != Ok("podman") {
eprintln!("Skipping corporate proxy test: e2e driver is not podman");
return;
}
if ManagedGateway::from_env()
.expect("load managed e2e gateway metadata")
.is_none()
{
eprintln!("Skipping corporate proxy test: e2e gateway is not managed by this test run");
return;
}
// The split Podman supervisor uses host networking and cannot resolve
// container-network aliases. Run each fixture on a distinct host port and
// reach it through the driver-neutral host alias.
let proxy_port = find_free_port();
let proxy =
HostSupportContainer::start_python_on_host_network(&proxy_script(proxy_port), proxy_port)
.await
.expect("start fake corporate proxy");
let allowed_port = find_free_port();
let allowed = HostSupportContainer::start_python_on_host_network(
&tls_upstream_script(HOST_ALIAS, ALLOWED_MARKER, allowed_port),
allowed_port,
)
.await
.expect("start approved TLS upstream");
let denied_port = find_free_port();
let denied = HostSupportContainer::start_python_on_host_network(
&tls_upstream_script(HOST_ALIAS, DENIED_MARKER, denied_port),
denied_port,
)
.await
.expect("start denied TLS upstream");
assert_ne!(
allowed.port, denied.port,
"approved and denied upstreams must have distinct host ports"
);
// ── Point the gateway at the corporate proxy ──────────────────────
let mut auth_file = NamedTempFile::new().expect("create proxy auth file");
writeln!(auth_file, "{PROXY_USER}:{PROXY_PASS}").expect("write proxy credentials");
auth_file.flush().expect("flush proxy credentials");
let auth_path = auth_file
.path()
.to_str()
.expect("proxy auth path should be utf-8")
.to_string();
let secrets_before = proxy_auth_secret_names().expect("snapshot proxy-auth secrets");
let mut gateway_config =
GatewayProxyConfig::apply(&format!("http://{HOST_ALIAS}:{}", proxy.port), &auth_path)
.await
.expect("apply corporate proxy gateway config");
// ── Run the workload ──────────────────────────────────────────────
let mut policy = NamedTempFile::new().expect("create policy file");
policy
.write_all(policy_yaml(allowed.port).as_bytes())
.expect("write policy file");
policy.flush().expect("flush policy file");
let policy_path = policy
.path()
.to_str()
.expect("policy path should be utf-8")
.to_string();
let script = workload_script(allowed.port, denied.port);
let mut sandbox = SandboxGuard::create_keep_with_args(
&["--policy", &policy_path],
&["python3", "-c", &script],
READY_MARKER,
)
.await
.expect("create sandbox behind the corporate proxy");
assert_proxied_egress(
&sandbox.create_output,
&proxy.logs().expect("read fake proxy logs"),
allowed.port,
denied.port,
);
// ── Secret lifecycle ──────────────────────────────────────────────
let secrets_live = proxy_auth_secret_names().expect("list proxy-auth secrets while sandbox up");
let new_secrets: Vec<&String> = secrets_live
.iter()
.filter(|name| !secrets_before.contains(name))
.collect();
assert_eq!(
new_secrets.len(),
1,
"exactly one proxy-auth secret should exist for the running sandbox. \
Before: {secrets_before:?}, now: {secrets_live:?}"
);
let sandbox_secret = new_secrets[0].clone();
sandbox.cleanup().await;
wait_for_secret_removal(&sandbox_secret, Duration::from_mins(1))
.await
.expect("sandbox deletion should remove the proxy-auth secret");
gateway_config
.restore()
.await
.expect("restore gateway config");
}
/// Assert the approved destination reached the `https://` proxy over the
/// tunnel and the denied one never did. The TLS proxy logs `CONNECT
/// <ip>:<port> ok` (no auth dimension in this test).
fn assert_https_proxied_egress(
output: &str,
proxy_logs: &str,
allowed_port: u16,
denied_port: u16,
) {
assert!(
output.contains(READY_MARKER),
"workload did not finish; output:\n{output}"
);
assert!(
output.contains(&format!(
"\"body\": \"{{\\\"upstream\\\":\\\"{ALLOWED_MARKER}\\\""
)),
"approved upstream body missing — egress did not complete through the https proxy:\n{output}"
);
assert!(
proxy_logs.lines().any(|line| {
line.starts_with("CONNECT ") && line.contains(&format!(":{allowed_port} ok"))
}),
"https proxy should have seen a validated-IP CONNECT to approved host port {allowed_port}:\n{proxy_logs}"
);
assert!(
!proxy_logs
.lines()
.any(|line| line.starts_with("CONNECT ") && line.contains(&format!(":{denied_port} "))),
"policy-denied host port {denied_port} must never reach the https proxy:\n{proxy_logs}"
);
}
#[tokio::test]
#[serial(corporate_proxy)]
async fn podman_corporate_proxy_trusts_ca_bundle_for_https_proxy() {
if std::env::var("OPENSHELL_E2E_DRIVER").as_deref() != Ok("podman") {
eprintln!("Skipping https corporate proxy test: e2e driver is not podman");
return;
}
if ManagedGateway::from_env()
.expect("load managed e2e gateway metadata")
.is_none()
{
eprintln!(
"Skipping https corporate proxy test: e2e gateway is not managed by this test run"
);
return;
}
let proxy_port = find_free_port();
let proxy = HostSupportContainer::start_python_on_host_network(
&tls_proxy_script(proxy_port),
proxy_port,
)
.await
.expect("start fake https corporate proxy");
let allowed_port = find_free_port();
let allowed = HostSupportContainer::start_python_on_host_network(
&tls_upstream_script(HOST_ALIAS, ALLOWED_MARKER, allowed_port),
allowed_port,
)
.await
.expect("start approved TLS upstream");
let denied_port = find_free_port();
let denied = HostSupportContainer::start_python_on_host_network(
&tls_upstream_script(HOST_ALIAS, DENIED_MARKER, denied_port),
denied_port,
)
.await
.expect("start denied TLS upstream");
assert_ne!(
allowed.port, denied.port,
"approved and denied upstreams must have distinct host ports"
);
// Recover the proxy's self-signed CA from its logs and hand it back as the
// corporate CA bundle the supervisor must trust for the proxy handshake.
let ca_pem = ca_cert_from_logs(&proxy.logs().expect("read proxy logs for CA"))
.expect("extract proxy CA certificate");
let mut ca_file = NamedTempFile::new().expect("create proxy CA bundle file");
ca_file
.write_all(ca_pem.as_bytes())
.expect("write proxy CA bundle");
ca_file.flush().expect("flush proxy CA bundle");
ca_file
.as_file()
.set_permissions(std::fs::Permissions::from_mode(0o644))
.expect("make proxy CA bundle readable by the non-root supervisor");
let ca_path = ca_file
.path()
.to_str()
.expect("CA bundle path should be utf-8")
.to_string();
// ── Point the gateway at the https:// proxy with the CA bundle ─────
let mut gateway_config = GatewayProxyConfig::apply_with(
&format!("https://{HOST_ALIAS}:{}", proxy.port),
None,
Some(&ca_path),
)
.await
.expect("apply https corporate proxy gateway config");
// ── Run the workload ──────────────────────────────────────────────
let mut policy = NamedTempFile::new().expect("create policy file");
policy
.write_all(policy_yaml(allowed.port).as_bytes())
.expect("write policy file");
policy.flush().expect("flush policy file");
let policy_path = policy
.path()
.to_str()
.expect("policy path should be utf-8")
.to_string();
let script = workload_script(allowed.port, denied.port);
let mut sandbox = SandboxGuard::create_keep_with_args(
&["--policy", &policy_path],
&["python3", "-c", &script],
READY_MARKER,
)
.await
.expect("create sandbox behind the https corporate proxy");
assert_https_proxied_egress(
&sandbox.create_output,
&proxy.logs().expect("read fake proxy logs"),
allowed.port,
denied.port,
);
sandbox.cleanup().await;
gateway_config
.restore()
.await
.expect("restore gateway config");
}
+20
View File
@@ -583,6 +583,26 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "corporate-proxy"
version = "0.0.0"
dependencies = [
"container-engine-support",
"corporate-proxy-support",
"host-server-support",
"openshell-testkit",
"serde_json",
]
[[package]]
name = "corporate-proxy-support"
version = "0.0.0"
dependencies = [
"openshell-testkit",
"serde",
"serde_json",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -0,0 +1,24 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
[package]
name = "corporate-proxy"
description = "Features suite: sandbox egress through an authenticated, TLS-intercepting corporate proxy"
version = "0.0.0"
edition = "2024"
rust-version = "1.94"
license = "Apache-2.0"
repository = "https://github.com/ai-openshell/openshell"
publish = false
[[test]]
name = "corporate-proxy"
path = "tests/corporate_proxy.rs"
harness = false
[dependencies]
container-engine-support = { path = "../../../support/container-engine" }
corporate-proxy-support = { path = "../../../support/corporate-proxy" }
host-server-support = { path = "../../../support/host-server" }
openshell-testkit = { path = "../../../testkit/testkit" }
serde_json = "1"
@@ -0,0 +1,338 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! Sandbox egress through a corporate proxy that the gateway's driver is
//! configured with.
//!
//! The environment runs one proxy (see `corporate-proxy-support`). It serves
//! TLS, requires Basic auth and intercepts the TLS in every tunnel, re-signing
//! it with its own CA, and logs each CONNECT. The gateway's `no_proxy` sends
//! one destination port, the bypass port, direct.
//!
//! The upstreams are TLS servers on the test host with certificates from a
//! [`TestCa`] that nothing trusts, so only the proxy's re-signed certificate
//! can satisfy a client that verifies.
//!
//! Ported from `e2e/rust/tests/docker_corporate_proxy.rs` and
//! `podman_corporate_proxy.rs`, which started their own proxy per test and
//! rewrote the gateway's configuration.
use std::time::Duration;
use container_engine_support::Engine;
use corporate_proxy_support::{Auth, Connect, CorporateProxy, Outcome};
use host_server_support::{HttpRecorder, Identity, TEST_HOST, TestCa};
use testkit::policy::{self, Endpoint as _};
use testkit::sdk::raw::proto;
use testkit::{Context, PYTHON_BINARIES, Poll, ResultExt as _, Sandbox};
fn main() -> std::process::ExitCode {
testkit::main()
}
/// Requests `https://<argv[2]>:<port>/` for each `<name>:<port>:<attempts>`
/// after `argv[2]` and prints one JSON object of results by name. With
/// `argv[1]` `verify`, the client verifies the server against the image's
/// trust store, which the driver adds the proxy's CA to; with `insecure`, it
/// doesn't verify. A failed request is retried, since a policy reload while
/// the sandbox starts can deny it once.
const CLIENT: &str = r#"
import json, ssl, sys, time, urllib.request
mode, host = sys.argv[1], sys.argv[2]
if mode == "verify":
context = ssl.create_default_context()
else:
context = ssl._create_unverified_context()
def fetch(port, attempts):
result = {"status": -1, "error": "not attempted"}
for attempt in range(attempts):
if attempt:
time.sleep(1)
try:
url = f"https://{host}:{port}/"
with urllib.request.urlopen(url, timeout=30, context=context) as response:
return {"status": response.status, "body": response.read().decode()}
except Exception as error:
result = {"status": -1, "error": f"{type(error).__name__}: {error}"}
return result
results = {}
for spec in sys.argv[3:]:
name, port, attempts = spec.split(":")
results[name] = fetch(int(port), int(attempts))
print(json.dumps(results))
"#;
/// The address ranges a sandbox may reach `host.openshell.internal` at,
/// across drivers.
const HOST_RANGES: &[&str] = &["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"];
/// How long the driver may take to remove a deleted sandbox's secret.
const SECRET_REMOVAL_TIMEOUT: Duration = Duration::from_mins(1);
/// A policy-approved request goes through the proxy with its credentials and
/// a validated IP as the CONNECT target. A denied one never reaches the
/// proxy, and one to the bypass port is dialed direct. On Podman, the
/// credentials reach the supervisor in a per-sandbox secret that deleting
/// the sandbox removes.
///
/// The workload's tunnels skip the supervisor's TLS inspection and don't
/// verify the server, so the proxy's interception doesn't matter here.
#[testkit::test]
async fn approved_egress_uses_authenticated_proxy(cx: &mut Context) -> testkit::Result {
let proxy = CorporateProxy::from_env()?;
let identity = TestCa::new()?.leaf(&[TEST_HOST])?;
let allowed = upstream(&identity, format!("allowed-{}", cx.run_id()), None).await?;
let denied = upstream(&identity, format!("denied-{}", cx.run_id()), None).await?;
let bypass = upstream(
&identity,
format!("bypass-{}", cx.run_id()),
Some(proxy.bypass_port()),
)
.await?;
let mut policy = policy::base();
for port in [allowed.port, bypass.port] {
allow(&mut policy, port).tls_skip();
}
let cursor = proxy.log_cursor()?;
let sandbox = python_sandbox(cx, "cpegr", policy).await?;
let results = fetch(
&sandbox,
"insecure",
&[
("allowed", allowed.port, 6),
("bypass", bypass.port, 6),
("denied", denied.port, 1),
],
)
.await?;
let connects = proxy.connects_since(&cursor)?;
let report = log_report(&connects);
expect_body(&results, "allowed", &allowed, &report)?;
let to_allowed = connects_to(&connects, allowed.port);
testkit::ensure!(
to_allowed
.iter()
.any(|connect| connect.auth == Auth::Ok && connect.host() != TEST_HOST),
"the proxy saw no authenticated CONNECT to a validated IP on port {}:\n{report}",
allowed.port
);
testkit::ensure!(
connects.iter().all(|connect| connect.auth == Auth::Ok),
"every CONNECT should carry the proxy's credentials:\n{report}"
);
expect_denied(&results, &denied, &connects, &report)?;
expect_body(&results, "bypass", &bypass, &report)?;
testkit::ensure!(
connects_to(&connects, bypass.port).is_empty(),
"the bypass port {} is in no_proxy, so its requests must not reach the proxy:\n{report}",
bypass.port
);
if cx.compute_driver().await? == "podman" {
expect_secret_removed_with(&sandbox).await?;
}
Ok(())
}
/// The proxy's CA, which the driver adds to the sandbox's trust bundle, is
/// trusted both by the supervisor when it inspects TLS and by the workload
/// when its TLS goes through the tunnel unchanged.
#[testkit::test]
async fn intercepting_proxy_ca_is_trusted_by_supervisor_and_workload(
cx: &mut Context,
) -> testkit::Result {
let proxy = CorporateProxy::from_env()?;
let identity = TestCa::new()?.leaf(&[TEST_HOST])?;
let inspected = upstream(&identity, format!("inspected-{}", cx.run_id()), None).await?;
let raw = upstream(&identity, format!("raw-{}", cx.run_id()), None).await?;
let denied = upstream(&identity, format!("denied-{}", cx.run_id()), None).await?;
let mut policy = policy::base();
allow(&mut policy, inspected.port);
allow(&mut policy, raw.port).tls_skip();
let cursor = proxy.log_cursor()?;
let sandbox = python_sandbox(cx, "cpca", policy).await?;
let results = fetch(
&sandbox,
"verify",
&[
("inspected", inspected.port, 6),
("raw", raw.port, 6),
("denied", denied.port, 1),
],
)
.await?;
let connects = proxy.connects_since(&cursor)?;
let report = log_report(&connects);
expect_body(&results, "inspected", &inspected, &report)
.context("the supervisor should trust the proxy's re-signed certificate")?;
expect_body(&results, "raw", &raw, &report)
.context("the workload should trust the proxy's re-signed certificate")?;
for server in [&inspected, &raw] {
testkit::ensure!(
connects_to(&connects, server.port)
.iter()
.any(|connect| connect.result == Outcome::Intercepted),
"the proxy intercepted no tunnel to port {}:\n{report}",
server.port
);
}
expect_denied(&results, &denied, &connects, &report)
}
/// A TLS server on the test host that answers every request with its
/// marker.
struct Upstream {
server: HttpRecorder,
marker: String,
port: u16,
}
/// Start an [`Upstream`] answering with `marker`, on `port` or a random free
/// one.
async fn upstream(
identity: &Identity,
marker: String,
port: Option<u16>,
) -> testkit::Result<Upstream> {
let mut builder = HttpRecorder::builder().tls(identity);
if let Some(port) = port {
builder = builder.port(port);
}
let server = builder.start(marker.clone()).await?;
Ok(Upstream {
port: server.port,
server,
marker,
})
}
/// Let the image's Python reach `TEST_HOST` on `port`, under a network
/// policy of its own.
fn allow(policy: &mut proto::SandboxPolicy, port: u16) -> &mut proto::NetworkEndpoint {
let endpoint = policy::allow(
policy,
&format!("upstream_{port}"),
TEST_HOST,
port,
PYTHON_BINARIES,
);
endpoint.allowed_ips = HOST_RANGES.iter().map(ToString::to_string).collect();
endpoint
}
async fn python_sandbox(
cx: &Context,
suffix: &str,
policy: proto::SandboxPolicy,
) -> testkit::Result<Sandbox> {
cx.sandbox(suffix)
.image(testkit::python_image())
.command(["sleep", "infinity"])
.policy(policy)
.create_ready()
.await
}
/// Run [`CLIENT`] in `sandbox` for each `(name, port, attempts)`.
async fn fetch(
sandbox: &Sandbox,
mode: &str,
targets: &[(&str, u16, u32)],
) -> testkit::Result<serde_json::Value> {
let mut args = vec![mode.to_string(), TEST_HOST.to_string()];
args.extend(
targets
.iter()
.map(|(name, port, attempts)| format!("{name}:{port}:{attempts}")),
);
let args: Vec<&str> = args.iter().map(String::as_str).collect();
sandbox.run_python(CLIENT, &args).await?.last_json()
}
fn connects_to(connects: &[Connect], port: u16) -> Vec<&Connect> {
connects
.iter()
.filter(|connect| connect.port() == Some(port))
.collect()
}
fn log_report(connects: &[Connect]) -> String {
if connects.is_empty() {
return "the proxy logged no CONNECT".to_string();
}
let lines: Vec<String> = connects.iter().map(ToString::to_string).collect();
format!("the proxy logged:\n{}", lines.join("\n"))
}
/// Fail unless the request `name` got `upstream`'s response.
fn expect_body(
results: &serde_json::Value,
name: &str,
upstream: &Upstream,
report: &str,
) -> testkit::Result {
let result = &results[name];
testkit::ensure!(
result["status"] == 200 && result["body"].as_str() == Some(upstream.marker.as_str()),
"the {name} request to port {} failed: {result}\n{report}",
upstream.port
);
Ok(())
}
/// The policy denied the request to `denied`, so it neither reached the
/// proxy nor the server.
fn expect_denied(
results: &serde_json::Value,
denied: &Upstream,
connects: &[Connect],
report: &str,
) -> testkit::Result {
testkit::ensure!(
results["denied"]["status"] != 200 && denied.server.requests().is_empty(),
"the policy-denied request to port {} reached the server: {}",
denied.port,
results["denied"]
);
testkit::ensure!(
connects_to(connects, denied.port).is_empty(),
"the policy-denied port {} must not reach the proxy:\n{report}",
denied.port
);
Ok(())
}
/// Podman's driver gives the supervisor the proxy credentials in a
/// per-sandbox secret: it exists while the sandbox runs, and deleting the
/// sandbox removes it.
async fn expect_secret_removed_with(sandbox: &Sandbox) -> testkit::Result {
let engine = Engine::from_env()?;
let secret = format!("openshell-proxy-auth-{}", sandbox.id());
testkit::ensure!(
engine.secret_exists(&secret).await?,
"Podman secret {secret} should hold the running sandbox's proxy credentials"
);
sandbox.delete().await?;
testkit::poll_until(
&format!("removal of Podman secret {secret}"),
SECRET_REMOVAL_TIMEOUT,
Duration::from_secs(1),
async || {
Ok(if engine.secret_exists(&secret).await? {
Poll::Pending(format!("{secret} still exists"))
} else {
Poll::Ready(())
})
},
)
.await
}
+11
View File
@@ -28,3 +28,14 @@
environments:
- ubuntu-k3s/k3s-ha
- ubuntu-k3s-ipv6/k3s-ha
# Rootless Podman can't relabel the root-owned proxy CA that the driver
# bind-mounts, so sandbox creation fails (#5795).
- test: corporate_proxy::approved_egress_uses_authenticated_proxy
issue: https://github.com/ai-openshell/openshell/issues/5795
environments:
- fedora-podman-rootless-corporate-proxy/rpm
- test: corporate_proxy::intercepting_proxy_ca_is_trusted_by_supervisor_and_workload
issue: https://github.com/ai-openshell/openshell/issues/5795
environments:
- fedora-podman-rootless-corporate-proxy/rpm
+10
View File
@@ -566,6 +566,16 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "corporate-proxy-support"
version = "0.0.0"
dependencies = [
"openshell-testkit",
"serde",
"serde_json",
"tempfile",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
+1 -1
View File
@@ -5,4 +5,4 @@
# environment runs. Suites depend on them by path.
[workspace]
resolver = "2"
members = ["container-engine", "host-server", "keycloak", "podman", "sandbox-clients"]
members = ["container-engine", "corporate-proxy", "host-server", "keycloak", "podman", "sandbox-clients"]
+4
View File
@@ -25,6 +25,10 @@ never skips it. Add a row when you add a variable. The runner also sets
| `OPENSHELL_TEST_KEYCLOAK_CLIENT_ID` | `<base>-keycloak` | `keycloak-support` | A client in that realm that allows password grants. |
| `OPENSHELL_TEST_KEYCLOAK_USERNAME` | `<base>-keycloak` | `keycloak-support` | The realm user that tests sign in as. |
| `OPENSHELL_TEST_KEYCLOAK_PASSWORD` | `<base>-keycloak` | `keycloak-support` | That user's password. |
| `OPENSHELL_TEST_CORPORATE_PROXY_URL` | `<base>-corporate-proxy` (`playbooks/corporate-proxy.yaml`) | `corporate-proxy-support` | The corporate proxy URL that the gateway's driver sends sandbox egress through, such as `https://host.openshell.internal:3128`. |
| `OPENSHELL_TEST_CORPORATE_PROXY_CA_CERT` | `<base>-corporate-proxy` | `corporate-proxy-support` | The path of the proxy's CA certificate, in PEM. It signs the proxy's listener certificate and the certificates it re-signs tunnels with. |
| `OPENSHELL_TEST_CORPORATE_PROXY_BYPASS_PORT` | `<base>-corporate-proxy` | `corporate-proxy-support` | The port a test listens on for a destination that the gateway's `no_proxy` sends direct. |
| `OPENSHELL_TEST_CORPORATE_PROXY_LOG` | `<base>-corporate-proxy` | `corporate-proxy-support` | The path of the proxy's log, one JSON line per CONNECT, readable by the test user. |
| `OPENSHELL_TEST_ADDITIONAL_CA_CERT` | The additional-CA environment, which sets `openshell.supervisor.network.additional_ca_bundle` (added by #5729) | `host-server-support` (`TestCa::from_env`) | The path of the CA certificate, in PEM, that the supervisor trusts for sandbox egress. |
| `OPENSHELL_TEST_ADDITIONAL_CA_KEY` | The additional-CA environment | `host-server-support` (`TestCa::from_env`) | The path of that CA's private key, in PEM, readable by the test user. Tests sign server certificates with it. |
| `OPENSHELL_TEST_BASE_IMAGE` | Optional; you, for example to use a mirror | `testkit::base_image()` | The default sandbox image. Unset, it is `nvcr.io/nvidia/base/ubuntu:24.04`. |
@@ -146,6 +146,15 @@ impl Engine {
.await
}
/// Whether a secret named exactly `name` exists. Podman only: Docker
/// lists secrets only in swarm mode.
pub async fn secret_exists(&self, name: &str) -> Result<bool> {
let names = self
.output(["secret", "ls", "--format", "{{.Name}}"])
.await?;
Ok(names.lines().any(|line| line.trim() == name))
}
/// Run the engine with `args` and return its trimmed standard output.
/// A non-zero exit is an error that includes the engine's output.
pub async fn output<I, S>(&self, args: I) -> Result<String>
+20
View File
@@ -0,0 +1,20 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
[package]
name = "corporate-proxy-support"
description = "The environment's corporate proxy and the CONNECTs it logged, for test suites"
version = "0.0.0"
edition = "2024"
rust-version = "1.94"
license = "Apache-2.0"
repository = "https://github.com/ai-openshell/openshell"
publish = false
[dependencies]
openshell-testkit = { path = "../../testkit/testkit" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
tempfile = "3"
+354
View File
@@ -0,0 +1,354 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! The environment's corporate proxy, for suites that check sandbox egress
//! through it.
//!
//! The environment runs one proxy and configures the gateway's driver to send
//! sandbox egress through it. The proxy serves TLS, requires Basic auth and
//! intercepts the TLS in every tunnel, all with one CA of its own. The
//! gateway's `no_proxy` sends one destination port, the bypass port, direct.
//! The environment publishes:
//!
//! | Variable | Meaning |
//! |---|---|
//! | `OPENSHELL_TEST_CORPORATE_PROXY_URL` | The proxy URL the gateway uses, e.g. `https://host.openshell.internal:3128` |
//! | `OPENSHELL_TEST_CORPORATE_PROXY_CA_CERT` | The path of the proxy's CA certificate, in PEM |
//! | `OPENSHELL_TEST_CORPORATE_PROXY_BYPASS_PORT` | The port a test listens on for a destination that the gateway's `no_proxy` sends direct |
//! | `OPENSHELL_TEST_CORPORATE_PROXY_LOG` | The path of the proxy's log, readable by the tests |
//!
//! Under `openshell-test-runner`, the tmachine `<base>-corporate-proxy`
//! environments do that (`tests/tmachine/ansible/playbooks/corporate-proxy.yaml`).
//! A missing variable fails the test; it never skips it.
//!
//! The log has one JSON line per CONNECT and lasts as long as the
//! environment, so a test takes a [`LogCursor`] before its sandbox starts
//! and reads only what came after it, for the ports it started servers on:
//!
//! ```ignore
//! let proxy = CorporateProxy::from_env()?;
//! let cursor = proxy.log_cursor()?;
//! // ... run a sandbox that reaches a server on `port` ...
//! let connects = proxy.connects_to(&cursor, port)?;
//! ```
//!
//! Tests that bind the bypass port can't run at the same time.
use std::fmt;
use std::io::{Read as _, Seek as _, SeekFrom};
use std::path::{Path, PathBuf};
use serde::Deserialize;
use testkit::{Error, Result};
pub const URL_ENV: &str = "OPENSHELL_TEST_CORPORATE_PROXY_URL";
pub const CA_CERT_ENV: &str = "OPENSHELL_TEST_CORPORATE_PROXY_CA_CERT";
pub const BYPASS_PORT_ENV: &str = "OPENSHELL_TEST_CORPORATE_PROXY_BYPASS_PORT";
pub const LOG_ENV: &str = "OPENSHELL_TEST_CORPORATE_PROXY_LOG";
/// How to reach the environment's corporate proxy and read its log.
#[derive(Clone, Debug)]
pub struct CorporateProxy {
url: String,
ca_cert: PathBuf,
bypass_port: u16,
log: PathBuf,
}
/// A point in the proxy's log. [`CorporateProxy::connects_since`] reads the
/// CONNECTs logged after it.
#[derive(Clone, Copy, Debug)]
pub struct LogCursor(u64);
/// One CONNECT the proxy received.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct Connect {
/// The CONNECT target, `host:port`. The supervisor sends a validated IP
/// unless the gateway sets `proxy_connect_by_hostname`.
pub target: String,
pub auth: Auth,
pub result: Outcome,
/// Why the CONNECT failed, for failure messages.
#[serde(default)]
pub error: Option<String>,
}
/// Whether the CONNECT carried the proxy's credentials.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Auth {
Ok,
Missing,
Wrong,
}
/// What the proxy did with the CONNECT.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
/// Answered 407, because the credentials were missing or wrong.
Rejected,
/// Answered 502, because the target refused or timed out.
DialFailed,
/// The client rejected the proxy's re-signed certificate, or dropped the
/// tunnel's TLS handshake.
ClientTlsFailed,
/// The target's TLS handshake failed.
UpstreamTlsFailed,
/// The proxy terminated the tunnel's TLS and relayed it to the target.
Intercepted,
}
impl Connect {
/// The CONNECT target's host, without IPv6 brackets.
pub fn host(&self) -> &str {
self.target
.rsplit_once(':')
.map_or(self.target.as_str(), |(host, _)| host)
.trim_start_matches('[')
.trim_end_matches(']')
}
/// The CONNECT target's port.
pub fn port(&self) -> Option<u16> {
self.target.rsplit_once(':')?.1.parse().ok()
}
}
impl fmt::Display for Connect {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"CONNECT {} auth={:?} result={:?}",
self.target, self.auth, self.result
)?;
if let Some(error) = &self.error {
write!(f, " error={error}")?;
}
Ok(())
}
}
impl CorporateProxy {
/// Read `OPENSHELL_TEST_CORPORATE_PROXY_*`. Fails naming the first
/// missing variable.
pub fn from_env() -> Result<Self> {
Self::from_vars(|name| std::env::var(name).ok())
}
fn from_vars(var: impl Fn(&str) -> Option<String>) -> Result<Self> {
let required = |name: &str| {
var(name)
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
.ok_or_else(|| {
Error::msg(format!(
"{name} is not set; this suite needs a corporate proxy (see the corporate-proxy-support crate docs)"
))
})
};
let url = required(URL_ENV)?;
let ca_cert = required(CA_CERT_ENV)?.into();
let bypass_port = required(BYPASS_PORT_ENV)?;
let bypass_port = bypass_port.parse().map_err(|error| {
Error::msg(format!(
"{BYPASS_PORT_ENV} is {bypass_port:?}, not a port: {error}"
))
})?;
let log = required(LOG_ENV)?.into();
Ok(Self {
url,
ca_cert,
bypass_port,
log,
})
}
/// The proxy URL the gateway uses.
pub fn url(&self) -> &str {
&self.url
}
/// The path of the proxy's CA certificate, in PEM.
pub fn ca_cert(&self) -> &Path {
&self.ca_cert
}
/// The destination port the gateway's `no_proxy` sends direct.
pub fn bypass_port(&self) -> u16 {
self.bypass_port
}
/// The end of the log now.
pub fn log_cursor(&self) -> Result<LogCursor> {
let metadata = std::fs::metadata(&self.log)
.map_err(|error| Error::msg(format!("read {}: {error}", self.log.display())))?;
Ok(LogCursor(metadata.len()))
}
/// The CONNECTs logged after `cursor`, oldest first. A line the proxy is
/// still writing is left out.
pub fn connects_since(&self, cursor: &LogCursor) -> Result<Vec<Connect>> {
let read =
|error: std::io::Error| Error::msg(format!("read {}: {error}", self.log.display()));
let mut file = std::fs::File::open(&self.log).map_err(read)?;
let len = file.metadata().map_err(read)?.len();
testkit::ensure!(
len >= cursor.0,
"{} is {len} bytes, shorter than the cursor at {}; was it truncated?",
self.log.display(),
cursor.0
);
file.seek(SeekFrom::Start(cursor.0)).map_err(read)?;
let mut text = String::new();
file.read_to_string(&mut text).map_err(read)?;
parse(&text).map_err(|error| Error::msg(format!("{}: {error}", self.log.display())))
}
/// The CONNECTs to `port` logged after `cursor`.
pub fn connects_to(&self, cursor: &LogCursor, port: u16) -> Result<Vec<Connect>> {
Ok(self
.connects_since(cursor)?
.into_iter()
.filter(|connect| connect.port() == Some(port))
.collect())
}
}
/// Parse the complete lines of `text`.
fn parse(text: &str) -> std::result::Result<Vec<Connect>, String> {
let complete = text.rfind('\n').map_or("", |end| &text[..end]);
complete
.lines()
.filter(|line| !line.trim().is_empty())
.map(|line| {
serde_json::from_str(line).map_err(|error| format!("bad log line {line:?}: {error}"))
})
.collect()
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::io::Write as _;
use super::*;
fn vars(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
let map: HashMap<String, String> = pairs
.iter()
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
.collect();
move |name| map.get(name).cloned()
}
const ALL: &[(&str, &str)] = &[
(URL_ENV, "https://host.openshell.internal:3128"),
(CA_CERT_ENV, "/etc/ca.pem"),
(BYPASS_PORT_ENV, "39443"),
(LOG_ENV, "/var/log/proxy.jsonl"),
];
#[test]
fn reads_every_variable() {
let proxy = CorporateProxy::from_vars(vars(ALL)).unwrap();
assert_eq!(proxy.url(), "https://host.openshell.internal:3128");
assert_eq!(proxy.ca_cert(), Path::new("/etc/ca.pem"));
assert_eq!(proxy.bypass_port(), 39443);
}
#[test]
fn missing_or_empty_variables_fail_naming_them() {
for name in [URL_ENV, CA_CERT_ENV, BYPASS_PORT_ENV, LOG_ENV] {
let without: Vec<_> = ALL
.iter()
.copied()
.filter(|(key, _)| *key != name)
.collect();
let error = CorporateProxy::from_vars(vars(&without)).unwrap_err();
assert!(error.to_string().contains(name), "{error}");
let mut empty = without.clone();
empty.push((name, " "));
let error = CorporateProxy::from_vars(vars(&empty)).unwrap_err();
assert!(error.to_string().contains(name), "{error}");
}
}
#[test]
fn bad_bypass_port_fails() {
let mut pairs = ALL.to_vec();
pairs.retain(|(key, _)| *key != BYPASS_PORT_ENV);
pairs.push((BYPASS_PORT_ENV, "70000"));
let error = CorporateProxy::from_vars(vars(&pairs)).unwrap_err();
assert!(error.to_string().contains("not a port"), "{error}");
}
#[test]
fn connect_target_parts() {
let connect = |target: &str| Connect {
target: target.into(),
auth: Auth::Ok,
result: Outcome::Intercepted,
error: None,
};
assert_eq!(connect("10.0.2.15:443").host(), "10.0.2.15");
assert_eq!(connect("10.0.2.15:443").port(), Some(443));
assert_eq!(connect("[fd00::1]:8443").host(), "fd00::1");
assert_eq!(connect("[fd00::1]:8443").port(), Some(8443));
assert_eq!(connect("nonsense").port(), None);
}
#[test]
fn reads_only_complete_lines_after_the_cursor() {
let mut log = tempfile::NamedTempFile::new().unwrap();
writeln!(
log,
r#"{{"time": 1.0, "target": "10.0.0.1:1", "auth": "missing", "result": "rejected"}}"#
)
.unwrap();
let proxy = CorporateProxy {
log: log.path().to_owned(),
..CorporateProxy::from_vars(vars(ALL)).unwrap()
};
let cursor = proxy.log_cursor().unwrap();
writeln!(
log,
r#"{{"time": 2.0, "target": "10.0.0.1:443", "auth": "ok", "result": "intercepted"}}"#
)
.unwrap();
writeln!(
log,
r#"{{"time": 3.0, "target": "10.0.0.1:444", "auth": "ok", "result": "dial_failed", "error": "refused"}}"#
)
.unwrap();
write!(log, r#"{{"time": 4.0, "target": "10.0"#).unwrap();
log.flush().unwrap();
let connects = proxy.connects_since(&cursor).unwrap();
assert_eq!(
connects,
[
Connect {
target: "10.0.0.1:443".into(),
auth: Auth::Ok,
result: Outcome::Intercepted,
error: None,
},
Connect {
target: "10.0.0.1:444".into(),
auth: Auth::Ok,
result: Outcome::DialFailed,
error: Some("refused".into()),
},
]
);
assert_eq!(proxy.connects_to(&cursor, 443).unwrap(), connects[..1]);
}
#[test]
fn bad_lines_fail() {
let error = parse("not json\n").unwrap_err();
assert!(error.contains("not json"), "{error}");
}
}
@@ -0,0 +1,25 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# Run a corporate proxy, point the gateway's driver at it and publish how
# tests read it. The corporate-proxy fixture (tests/support/corporate-proxy)
# reads the variables published below.
---
- name: Corporate proxy for tests
hosts: all
gather_facts: false
pre_tasks:
- name: Wait for SSH
ansible.builtin.wait_for_connection:
roles:
- corporate_proxy
tasks:
- name: Publish corporate proxy test variables
ansible.builtin.include_tasks: test-env.yaml
vars:
test_env_name: corporate-proxy
test_env_vars:
OPENSHELL_TEST_CORPORATE_PROXY_URL: "https://{{ corporate_proxy_host }}:{{ corporate_proxy_port }}"
OPENSHELL_TEST_CORPORATE_PROXY_CA_CERT: "{{ corporate_proxy_config_dir }}/ca.pem"
OPENSHELL_TEST_CORPORATE_PROXY_BYPASS_PORT: "{{ corporate_proxy_bypass_port }}"
OPENSHELL_TEST_CORPORATE_PROXY_LOG: "{{ corporate_proxy_log }}"
@@ -0,0 +1,22 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
---
# Files the gateway and the tests read: the proxy's CA, its listener
# certificate and the credentials file.
corporate_proxy_config_dir: /etc/openshell-test/corporate-proxy
# Only the proxy reads the private keys.
corporate_proxy_key_dir: /etc/openshell-test/corporate-proxy/private
corporate_proxy_script: /usr/local/libexec/openshell-test/corporate-proxy.py
corporate_proxy_log: /var/log/openshell-test/corporate-proxy.jsonl
corporate_proxy_service: openshell-corporate-proxy.service
# The name sandboxes reach the guest by. The listener certificate and the
# re-signed tunnel certificates are issued for it.
corporate_proxy_host: host.openshell.internal
corporate_proxy_port: 3128
# The destination port that no_proxy sends direct. Tests bind it themselves.
corporate_proxy_bypass_port: 39443
# Throwaway credentials for a proxy that only this guest can reach.
corporate_proxy_username: proxyuser
corporate_proxy_password: proxypass
corporate_proxy_cert_days: 3650
@@ -0,0 +1,185 @@
#!/usr/bin/env python3
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""A corporate forward proxy for tests.
It does what a strict corporate proxy does, all at once:
- serves its listener over TLS, with a certificate signed by its own CA;
- requires Basic auth on every CONNECT;
- intercepts the TLS inside every tunnel, re-signing it with the same
certificate, and opens its own unverified TLS connection to the target.
It appends one JSON line per CONNECT to the log, which tests read to see what
went through the proxy:
{"time": 1.0, "target": "10.0.2.15:41234", "auth": "ok", "result": "intercepted"}
`auth` is `ok`, `missing` or `wrong`. `result` is `rejected` (407),
`dial_failed` (502), `client_tls_failed` (the client didn't accept the
proxy's certificate), `upstream_tls_failed` or `intercepted`. The log never
holds credentials.
"""
import argparse
import asyncio
import base64
import json
import ssl
import time
from pathlib import Path
MAX_HEAD = 65536
DIAL_TIMEOUT = 10
HANDSHAKE_TIMEOUT = 10
CHUNK = 65536
class Proxy:
def __init__(self, args):
credentials = Path(args.auth_file).read_text(encoding="utf-8").strip()
self.expected_auth = "Basic " + base64.b64encode(credentials.encode()).decode()
self.server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
self.server_context.load_cert_chain(args.cert, args.key)
self.upstream_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
self.upstream_context.check_hostname = False
self.upstream_context.verify_mode = ssl.CERT_NONE
self.log_file = Path(args.log).open("a", encoding="utf-8") # noqa: SIM115
def log(self, target, auth, result, **extra):
entry = {"time": time.time(), "target": target, "auth": auth, "result": result}
entry.update(extra)
self.log_file.write(json.dumps(entry) + "\n")
self.log_file.flush()
async def handle(self, reader, writer):
try:
await self.connect(reader, writer)
except (
OSError,
asyncio.IncompleteReadError,
asyncio.LimitOverrunError,
ssl.SSLError,
):
pass
finally:
writer.close()
async def connect(self, reader, writer):
head = await reader.readuntil(b"\r\n\r\n")
lines = head.decode("latin-1").split("\r\n")
parts = lines[0].split()
if len(parts) < 2 or parts[0].upper() != "CONNECT":
writer.write(
b"HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n"
)
await writer.drain()
return
target = parts[1]
auth = "missing"
for line in lines[1:]:
name, _, value = line.partition(":")
if name.strip().lower() == "proxy-authorization":
auth = "ok" if value.strip() == self.expected_auth else "wrong"
if auth != "ok":
self.log(target, auth, "rejected")
writer.write(
b"HTTP/1.1 407 Proxy Authentication Required\r\n"
b'Proxy-Authenticate: Basic realm="corp"\r\n'
b"Content-Length: 0\r\n\r\n"
)
await writer.drain()
return
host, _, port = target.rpartition(":")
try:
upstream_reader, upstream_writer = await asyncio.wait_for(
asyncio.open_connection(host.strip("[]"), int(port)), DIAL_TIMEOUT
)
except (OSError, ValueError, TimeoutError) as error:
self.log(target, auth, "dial_failed", error=repr(error))
writer.write(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n")
await writer.drain()
return
try:
writer.write(b"HTTP/1.1 200 Connection Established\r\n\r\n")
await writer.drain()
# TLS inside the listener's TLS. asyncio supports this from Python
# 3.11; ssl.SSLSocket can't be wrapped a second time.
try:
await writer.start_tls(
self.server_context, ssl_handshake_timeout=HANDSHAKE_TIMEOUT
)
except (OSError, ssl.SSLError, TimeoutError) as error:
self.log(target, auth, "client_tls_failed", error=repr(error))
return
try:
await upstream_writer.start_tls(
self.upstream_context, ssl_handshake_timeout=HANDSHAKE_TIMEOUT
)
except (OSError, ssl.SSLError, TimeoutError) as error:
self.log(target, auth, "upstream_tls_failed", error=repr(error))
return
self.log(target, auth, "intercepted")
await relay(reader, writer, upstream_reader, upstream_writer)
finally:
upstream_writer.close()
async def pipe(reader, writer):
while chunk := await reader.read(CHUNK):
writer.write(chunk)
await writer.drain()
async def relay(client_reader, client_writer, upstream_reader, upstream_writer):
tasks = [
asyncio.ensure_future(pipe(client_reader, upstream_writer)),
asyncio.ensure_future(pipe(upstream_reader, client_writer)),
]
# TLS streams can't half-close, so the tunnel ends when either side does.
_, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in pending:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
def ignore_disconnects(loop, context):
# Probes and clients that drop the listener's TLS handshake would
# otherwise fill the journal.
if isinstance(context.get("exception"), (OSError, ssl.SSLError)):
return
loop.default_exception_handler(context)
async def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--listen", default="0.0.0.0")
parser.add_argument("--port", type=int, required=True)
parser.add_argument(
"--cert", required=True, help="PEM certificate chain, leaf first"
)
parser.add_argument("--key", required=True)
parser.add_argument("--auth-file", required=True, help="a user:password file")
parser.add_argument("--log", required=True)
args = parser.parse_args()
proxy = Proxy(args)
asyncio.get_running_loop().set_exception_handler(ignore_disconnects)
server = await asyncio.start_server(
proxy.handle,
args.listen,
args.port,
ssl=proxy.server_context,
ssl_handshake_timeout=HANDSHAKE_TIMEOUT,
limit=MAX_HEAD,
)
print(f"corporate proxy listening on {args.listen}:{args.port}", flush=True)
async with server:
await server.serve_forever()
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,179 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# Run a corporate proxy in the guest and point the gateway's driver at it.
# The proxy (files/corporate-proxy.py) serves TLS, requires Basic auth and
# intercepts the TLS in every tunnel, all with one CA of its own.
---
- name: Require the environment's compute driver
ansible.builtin.assert:
that: [environment_driver is defined]
fail_msg: environment_driver names the gateway driver and comes from the environment's base in config.nix
- name: Install OpenSSL and Python
become: true
ansible.builtin.package:
name: [openssl, python3]
state: present
- name: Require Python 3.11 or later for TLS inside TLS
ansible.builtin.command:
argv: [/usr/bin/python3, -c, "import sys; sys.exit(sys.version_info < (3, 11))"]
changed_when: false
- name: Create the corporate proxy directories
become: true
ansible.builtin.file:
path: "{{ item.path }}"
state: directory
owner: root
group: root
mode: "{{ item.mode }}"
loop:
- { path: "{{ corporate_proxy_config_dir }}", mode: "0755" }
- { path: "{{ corporate_proxy_key_dir }}", mode: "0700" }
- { path: "{{ corporate_proxy_script | dirname }}", mode: "0755" }
- { path: "{{ corporate_proxy_log | dirname }}", mode: "0755" }
# The listener certificate must be a leaf: rustls rejects a CA certificate
# presented as a server's. Python 3.13 and later also require its authority
# key identifier. The same leaf re-signs every tunnel, since sandboxes
# reach every destination by corporate_proxy_host.
- name: Create the corporate proxy CA and listener certificate
become: true
ansible.builtin.shell:
cmd: |
set -eu
umask 077
keys={{ corporate_proxy_key_dir }}
conf={{ corporate_proxy_config_dir }}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
openssl req -x509 -newkey rsa:2048 -nodes -days {{ corporate_proxy_cert_days }} \
-keyout "$keys/ca-key.pem" -out "$work/ca.pem" \
-subj '/CN=OpenShell test corporate proxy CA' \
-addext 'basicConstraints=critical,CA:TRUE' \
-addext 'keyUsage=critical,keyCertSign,cRLSign'
openssl req -newkey rsa:2048 -nodes -subj '/CN={{ corporate_proxy_host }}' \
-keyout "$keys/proxy-key.pem" -out "$work/proxy.csr"
printf '%s\n' 'basicConstraints=critical,CA:FALSE' \
'subjectAltName=DNS:{{ corporate_proxy_host }}' \
'extendedKeyUsage=serverAuth' \
'keyUsage=critical,digitalSignature,keyEncipherment' \
'subjectKeyIdentifier=hash' 'authorityKeyIdentifier=keyid' > "$work/proxy.ext"
openssl x509 -req -in "$work/proxy.csr" -CA "$work/ca.pem" -CAkey "$keys/ca-key.pem" \
-CAcreateserial -days {{ corporate_proxy_cert_days }} -extfile "$work/proxy.ext" \
-out "$work/proxy.pem"
cat "$work/proxy.pem" "$work/ca.pem" > "$work/proxy-chain.pem"
install -m 0644 "$work/proxy-chain.pem" "$conf/proxy-chain.pem"
install -m 0644 "$work/ca.pem" "$conf/ca.pem"
creates: "{{ corporate_proxy_config_dir }}/ca.pem"
# Every gateway user (root, tmachine or the package's) must read these.
- name: Write the corporate proxy credentials
become: true
ansible.builtin.copy:
dest: "{{ corporate_proxy_config_dir }}/auth"
content: "{{ corporate_proxy_username }}:{{ corporate_proxy_password }}\n"
owner: root
group: root
mode: "0644"
- name: Install the corporate proxy
become: true
ansible.builtin.copy:
src: corporate-proxy.py
dest: "{{ corporate_proxy_script }}"
owner: root
group: root
mode: "0755"
# Tests read the log as the tmachine user.
- name: Create the corporate proxy log
become: true
ansible.builtin.file:
path: "{{ corporate_proxy_log }}"
state: touch
owner: root
group: root
mode: "0644"
access_time: preserve
modification_time: preserve
- name: Install the corporate proxy unit
become: true
ansible.builtin.template:
src: openshell-corporate-proxy.service.j2
dest: /etc/systemd/system/{{ corporate_proxy_service }}
owner: root
group: root
mode: "0644"
- name: Start the corporate proxy
block:
- name: Start the corporate proxy service
become: true
ansible.builtin.systemd_service:
name: "{{ corporate_proxy_service }}"
daemon_reload: true
enabled: true
state: restarted
# Check what a sandbox's supervisor relies on: the listener's certificate
# verifies against the CA for corporate_proxy_host, and a CONNECT without
# credentials gets a 407.
- name: Check that the corporate proxy serves TLS and requires auth
ansible.builtin.command:
argv:
- /usr/bin/python3
- -c
- |
import socket, ssl, sys, time
ca, host, port = sys.argv[1], sys.argv[2], int(sys.argv[3])
context = ssl.create_default_context(cafile=ca)
deadline = time.monotonic() + 15
while True:
try:
raw = socket.create_connection(("127.0.0.1", port), timeout=5)
break
except OSError:
if time.monotonic() > deadline:
raise
time.sleep(0.5)
with context.wrap_socket(raw, server_hostname=host) as conn:
conn.sendall(b"CONNECT 127.0.0.1:1 HTTP/1.1\r\nHost: 127.0.0.1:1\r\n\r\n")
status = conn.recv(4096).split(b"\r\n", 1)[0]
sys.exit(0 if b" 407 " in status else f"expected a 407, got {status!r}")
- "{{ corporate_proxy_config_dir }}/ca.pem"
- "{{ corporate_proxy_host }}"
- "{{ corporate_proxy_port }}"
changed_when: false
rescue:
- name: Collect corporate proxy diagnostics
become: true
ansible.builtin.shell: |
systemctl status {{ corporate_proxy_service }} --no-pager -l
journalctl -u {{ corporate_proxy_service }} --no-pager -n 40
changed_when: false
failed_when: false
register: corporate_proxy_diagnostics
- name: Report why the corporate proxy did not start
ansible.builtin.fail:
msg: "{{ corporate_proxy_service }} did not start:\n{{ corporate_proxy_diagnostics.stdout }}\n{{ corporate_proxy_diagnostics.stderr }}"
# Basic credentials go over the proxy's TLS listener, so the gateway needs no
# proxy_auth_allow_insecure. The CA covers the listener and the re-signed
# tunnels, for both the supervisor and the workload.
- name: Point the gateway's driver at the corporate proxy
ansible.builtin.include_role:
name: gateway_overrides
vars:
gateway_overrides_name: corporate-proxy
gateway_overrides_content: |
[openshell.drivers.{{ environment_driver }}]
https_proxy = "https://{{ corporate_proxy_host }}:{{ corporate_proxy_port }}"
proxy_auth_file = "{{ corporate_proxy_config_dir }}/auth"
proxy_ca_bundle = "{{ corporate_proxy_config_dir }}/ca.pem"
no_proxy = "{{ corporate_proxy_host }}:{{ corporate_proxy_bypass_port }}"
@@ -0,0 +1,13 @@
{# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. #}
{# SPDX-License-Identifier: Apache-2.0 #}
[Unit]
Description=OpenShell test corporate proxy
After=network-online.target
Wants=network-online.target
[Service]
ExecStart=/usr/bin/python3 {{ corporate_proxy_script }} --port {{ corporate_proxy_port }} --cert {{ corporate_proxy_config_dir }}/proxy-chain.pem --key {{ corporate_proxy_key_dir }}/proxy-key.pem --auth-file {{ corporate_proxy_config_dir }}/auth --log {{ corporate_proxy_log }}
Restart=always
[Install]
WantedBy=multi-user.target
+1 -2
View File
@@ -91,11 +91,10 @@ let
# `enable_bind_mounts`), which the tmachine gateway does not enable. Wrapper
# lane.
"driver_config_volume"
# The next three self-skip without wrapper-owned gateway metadata (restart
# The next two self-skip without wrapper-owned gateway metadata (restart
# and configuration control), so exclude them rather than report false
# passes. Wrapper lane.
"local_driver_token_restart"
"podman_corporate_proxy"
"podman_gateway_start"
# Needs the SPIFFE fixtures that the wrapper sets up. Wrapper lane.
"provider_token_exchange"
+6
View File
@@ -118,6 +118,12 @@ let
bases = dockerBases ++ podmanBases;
setup.playbooks = [ "ansible/playbooks/cdi.yaml" ];
};
# A TLS-intercepting corporate proxy with Basic auth that the gateway's
# driver sends sandbox egress through, for the corporate-proxy suite.
corporate-proxy = {
bases = dockerBases ++ podmanBases;
setup.playbooks = [ "ansible/playbooks/corporate-proxy.yaml" ];
};
};
featureEnvironments = pkgs.lib.concatMap (
feature: map (base: withSetup base feature features.${feature}.setup) features.${feature}.bases