Skip to content

Commit 834b56e

Browse files
committed
feat(sandbox): openshell-sandbox debug-rpc subcommand for end-to-end testing
Adds a small subcommand to the supervisor binary that issues one-shot sandbox-class RPCs against the gateway using the supervisor's existing token-acquisition pipeline. Designed to be invoked via docker exec or kubectl exec into a running sandbox to verify the per-sandbox identity flow end-to-end without writing a custom test binary inside the sandbox image. Subcommands: - get-sandbox-config --sandbox-id <UUID> — call GetSandboxConfig - refresh — call RefreshSandboxToken - show-token — print raw gateway JWT bytes - show-principal — pretty-print decoded JWT claims Verification flow this enables (Docker path): docker exec sandbox-a openshell-sandbox debug-rpc show-principal docker exec sandbox-a openshell-sandbox debug-rpc \ get-sandbox-config --sandbox-id <sandbox-b-uuid> # → exit code 7 + "PermissionDenied: cross-sandbox access denied" K8s path: same RPCs, kubectl exec instead. show-token and show-principal intentionally don't trigger the K8s SA bootstrap exchange — they only read an already-cached token, so inspection doesn't burn a fresh JWT mint per call.
1 parent 45a349e commit 834b56e

3 files changed

Lines changed: 260 additions & 0 deletions

File tree

Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
//! One-shot debug RPCs exposed via `openshell-sandbox debug-rpc`.
5+
//!
6+
//! Designed for end-to-end verification of the per-sandbox identity
7+
//! flow (issue #1354). A `docker exec` (or `kubectl exec`) into a
8+
//! running sandbox can issue raw sandbox-class gRPC calls without
9+
//! standing up a custom binary inside the sandbox image — useful for
10+
//! confirming the cross-sandbox IDOR guard and refresh semantics.
11+
//!
12+
//! Subcommands:
13+
//! - `get-sandbox-config --sandbox-id <id>` — call `GetSandboxConfig`
14+
//! - `refresh` — call `RefreshSandboxToken`
15+
//! - `show-token` — print the raw gateway JWT bytes
16+
//! - `show-principal` — pretty-print the decoded JWT claims
17+
//! (no signature verification — the supervisor already trusts the
18+
//! token's origin)
19+
20+
use base64::Engine as _;
21+
use miette::{IntoDiagnostic, Result, WrapErr};
22+
use openshell_core::proto::{
23+
GetSandboxConfigRequest, RefreshSandboxTokenRequest, open_shell_client::OpenShellClient,
24+
};
25+
26+
use crate::grpc_client::{AuthedChannel, connect_channel_pub};
27+
28+
/// Entry point for the `debug-rpc` subcommand. Returns the process exit
29+
/// code; `main` propagates it.
30+
pub async fn run(args: &[String]) -> Result<i32> {
31+
let cmd = args
32+
.first()
33+
.map(String::as_str)
34+
.ok_or_else(|| miette::miette!("{}", USAGE))?;
35+
36+
match cmd {
37+
"get-sandbox-config" => run_get_sandbox_config(&args[1..]).await,
38+
"refresh" => run_refresh().await,
39+
"show-token" => run_show_token(),
40+
"show-principal" => run_show_principal(),
41+
"--help" | "-h" => {
42+
println!("{USAGE}");
43+
Ok(0)
44+
}
45+
other => Err(miette::miette!(
46+
"unknown debug-rpc command '{other}'\n\n{USAGE}"
47+
)),
48+
}
49+
}
50+
51+
const USAGE: &str = "\
52+
usage: openshell-sandbox debug-rpc <command> [options]
53+
54+
commands:
55+
get-sandbox-config --sandbox-id <UUID> call GetSandboxConfig
56+
refresh call RefreshSandboxToken
57+
show-token print raw gateway JWT
58+
show-principal print decoded JWT claims
59+
60+
requires: OPENSHELL_ENDPOINT in env, plus one of OPENSHELL_SANDBOX_TOKEN,
61+
OPENSHELL_SANDBOX_TOKEN_FILE, or OPENSHELL_K8S_SA_TOKEN_FILE so the
62+
supervisor's normal token-acquisition path can resolve a JWT.";
63+
64+
async fn open_client() -> Result<OpenShellClient<AuthedChannel>> {
65+
let endpoint = std::env::var(openshell_core::sandbox_env::ENDPOINT)
66+
.into_diagnostic()
67+
.wrap_err("OPENSHELL_ENDPOINT must be set")?;
68+
let channel = connect_channel_pub(&endpoint).await?;
69+
Ok(OpenShellClient::new(channel))
70+
}
71+
72+
async fn run_get_sandbox_config(args: &[String]) -> Result<i32> {
73+
let sandbox_id = parse_flag(args, "--sandbox-id")
74+
.ok_or_else(|| miette::miette!("get-sandbox-config: --sandbox-id <UUID> is required"))?;
75+
let mut client = open_client().await?;
76+
let resp = client
77+
.get_sandbox_config(GetSandboxConfigRequest {
78+
sandbox_id: sandbox_id.to_string(),
79+
})
80+
.await;
81+
match resp {
82+
Ok(r) => {
83+
let inner = r.into_inner();
84+
println!(
85+
"version={} policy_hash={} config_revision={}",
86+
inner.version, inner.policy_hash, inner.config_revision
87+
);
88+
Ok(0)
89+
}
90+
Err(status) => {
91+
eprintln!("{}: {}", code_name(status.code()), status.message());
92+
// Map gRPC status to a non-zero exit so callers can branch
93+
// (e.g. expect-permission-denied in a shell test).
94+
Ok(match status.code() {
95+
tonic::Code::PermissionDenied => 7,
96+
tonic::Code::Unauthenticated => 16,
97+
tonic::Code::NotFound => 5,
98+
_ => 1,
99+
})
100+
}
101+
}
102+
}
103+
104+
async fn run_refresh() -> Result<i32> {
105+
let mut client = open_client().await?;
106+
let resp = client
107+
.refresh_sandbox_token(RefreshSandboxTokenRequest {})
108+
.await;
109+
match resp {
110+
Ok(r) => {
111+
let inner = r.into_inner();
112+
println!(
113+
"token={}\nexpires_at_ms={}",
114+
inner.token, inner.expires_at_ms
115+
);
116+
Ok(0)
117+
}
118+
Err(status) => {
119+
eprintln!("{}: {}", code_name(status.code()), status.message());
120+
Ok(1)
121+
}
122+
}
123+
}
124+
125+
fn run_show_token() -> Result<i32> {
126+
let token = read_local_token()?;
127+
println!("{token}");
128+
Ok(0)
129+
}
130+
131+
fn run_show_principal() -> Result<i32> {
132+
let token = read_local_token()?;
133+
let payload_b64 = token
134+
.split('.')
135+
.nth(1)
136+
.ok_or_else(|| miette::miette!("token has no payload segment"))?;
137+
let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
138+
.decode(payload_b64)
139+
.into_diagnostic()
140+
.wrap_err("failed to base64-decode token payload")?;
141+
let claims: serde_json::Value = serde_json::from_slice(&payload)
142+
.into_diagnostic()
143+
.wrap_err("failed to parse token payload as JSON")?;
144+
println!(
145+
"{}",
146+
serde_json::to_string_pretty(&claims).into_diagnostic()?
147+
);
148+
Ok(0)
149+
}
150+
151+
/// Read the token from the env/file/SA-bootstrap chain, but only the
152+
/// "already a gateway JWT" paths — show-token / show-principal don't
153+
/// want to actually exchange an SA token.
154+
fn read_local_token() -> Result<String> {
155+
if let Ok(t) = std::env::var(openshell_core::sandbox_env::SANDBOX_TOKEN)
156+
&& !t.is_empty()
157+
{
158+
return Ok(t);
159+
}
160+
if let Ok(path) = std::env::var(openshell_core::sandbox_env::SANDBOX_TOKEN_FILE)
161+
&& !path.is_empty()
162+
{
163+
return Ok(std::fs::read_to_string(&path)
164+
.into_diagnostic()
165+
.wrap_err_with(|| format!("failed to read sandbox token from {path}"))?
166+
.trim()
167+
.to_string());
168+
}
169+
Err(miette::miette!(
170+
"no in-process gateway JWT available — set OPENSHELL_SANDBOX_TOKEN or \
171+
OPENSHELL_SANDBOX_TOKEN_FILE. The K8s SA-bootstrap path is intentionally \
172+
excluded from `show-token` / `show-principal` to avoid issuing a fresh \
173+
token just for inspection."
174+
))
175+
}
176+
177+
fn parse_flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
178+
let mut iter = args.iter();
179+
while let Some(a) = iter.next() {
180+
if a == name {
181+
return iter.next().map(String::as_str);
182+
}
183+
if let Some(rest) = a.strip_prefix(&format!("{name}=")) {
184+
return Some(rest);
185+
}
186+
}
187+
None
188+
}
189+
190+
fn code_name(c: tonic::Code) -> &'static str {
191+
match c {
192+
tonic::Code::Ok => "OK",
193+
tonic::Code::Cancelled => "Cancelled",
194+
tonic::Code::Unknown => "Unknown",
195+
tonic::Code::InvalidArgument => "InvalidArgument",
196+
tonic::Code::DeadlineExceeded => "DeadlineExceeded",
197+
tonic::Code::NotFound => "NotFound",
198+
tonic::Code::AlreadyExists => "AlreadyExists",
199+
tonic::Code::PermissionDenied => "PermissionDenied",
200+
tonic::Code::ResourceExhausted => "ResourceExhausted",
201+
tonic::Code::FailedPrecondition => "FailedPrecondition",
202+
tonic::Code::Aborted => "Aborted",
203+
tonic::Code::OutOfRange => "OutOfRange",
204+
tonic::Code::Unimplemented => "Unimplemented",
205+
tonic::Code::Internal => "Internal",
206+
tonic::Code::Unavailable => "Unavailable",
207+
tonic::Code::DataLoss => "DataLoss",
208+
tonic::Code::Unauthenticated => "Unauthenticated",
209+
}
210+
}
211+
212+
#[cfg(test)]
213+
mod tests {
214+
use super::*;
215+
216+
#[test]
217+
fn parse_flag_handles_space_separated() {
218+
let args: Vec<String> = ["--sandbox-id", "abc-123"]
219+
.iter()
220+
.map(ToString::to_string)
221+
.collect();
222+
assert_eq!(parse_flag(&args, "--sandbox-id"), Some("abc-123"));
223+
}
224+
225+
#[test]
226+
fn parse_flag_handles_equals_separated() {
227+
let args: Vec<String> = ["--sandbox-id=abc-123".to_string()].to_vec();
228+
assert_eq!(parse_flag(&args, "--sandbox-id"), Some("abc-123"));
229+
}
230+
231+
#[test]
232+
fn parse_flag_returns_none_when_missing() {
233+
let args: Vec<String> = ["--other".to_string(), "x".to_string()].to_vec();
234+
assert!(parse_flag(&args, "--sandbox-id").is_none());
235+
}
236+
}

‎crates/openshell-sandbox/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
88
pub mod bypass_monitor;
99
mod child_env;
10+
pub mod debug_rpc;
1011
pub mod denial_aggregator;
1112
mod grpc_client;
1213
mod identity;

‎crates/openshell-sandbox/src/main.rs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ use openshell_sandbox::run_sandbox;
2424
/// performs the copy in pure Rust.
2525
const COPY_SELF_SUBCOMMAND: &str = "copy-self";
2626

27+
/// Subcommand for one-shot debug RPCs from inside a sandbox container.
28+
///
29+
/// Reads the same token sources as the supervisor (env, file, K8s SA
30+
/// bootstrap) and issues a single gRPC call against the gateway. Useful
31+
/// for end-to-end verification: e.g. `docker exec` into a sandbox, then
32+
/// run `openshell-sandbox debug-rpc get-sandbox-config --sandbox-id <other>`
33+
/// to confirm the cross-sandbox IDOR guard fires.
34+
const DEBUG_RPC_SUBCOMMAND: &str = "debug-rpc";
35+
2736
/// `OpenShell` Sandbox - process isolation and monitoring.
2837
#[derive(Parser, Debug)]
2938
#[command(name = "openshell-sandbox")]
@@ -150,6 +159,20 @@ fn main() -> Result<()> {
150159
return copy_self(dest);
151160
}
152161

162+
// Handle `debug-rpc <subcommand> [args]` before clap. Uses a small
163+
// dedicated runtime so we don't pay the supervisor's full startup cost.
164+
if raw_args.get(1).map(String::as_str) == Some(DEBUG_RPC_SUBCOMMAND) {
165+
let runtime = tokio::runtime::Builder::new_current_thread()
166+
.enable_all()
167+
.build()
168+
.into_diagnostic()?;
169+
return runtime.block_on(async move {
170+
let _ = rustls::crypto::ring::default_provider().install_default();
171+
let exit = openshell_sandbox::debug_rpc::run(&raw_args[2..]).await?;
172+
std::process::exit(exit);
173+
});
174+
}
175+
153176
let args = Args::parse();
154177

155178
// Try to open a rolling log file; fall back to stderr-only logging if it fails

0 commit comments

Comments
 (0)