Skip to content

Commit d932183

Browse files
committed
feat(sdk): add openshell-sdk crate
Additive extraction of the shared async gRPC client core (transport, TLS, OIDC single-flight refresh, edge tunnel, high-level sandbox surface, raw escape hatch) as a new workspace crate. No existing consumers yet; CLI/TUI migration follows in a separate PR. Signed-off-by: Max Dubrinsky <mdubrinsky@nvidia.com>
1 parent 474d2d4 commit d932183

16 files changed

Lines changed: 3221 additions & 0 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ These pipelines connect skills into end-to-end workflows. Individual skill files
3737
| `crates/openshell-bootstrap/` | Gateway metadata | Gateway registration metadata, auth token storage, mTLS bundle storage |
3838
| `crates/openshell-ocsf/` | OCSF logging | OCSF v1.7.0 event types, builders, shorthand/JSONL formatters, tracing layers |
3939
| `crates/openshell-core/` | Shared core | Common types, configuration, error handling |
40+
| `crates/openshell-sdk/` | Shared client SDK | Async Rust gateway client (gRPC transport, TLS, OIDC refresh, edge tunnel); consumed by CLI, TUI, and `@openshell/sdk` |
4041
| `crates/openshell-providers/` | Provider management | Credential provider backends |
4142
| `crates/openshell-tui/` | Terminal UI | Ratatui-based dashboard for monitoring |
4243
| `crates/openshell-driver-kubernetes/` | Kubernetes compute driver | In-process `ComputeDriver` backend for K8s sandbox pods |

‎Cargo.lock‎

Lines changed: 25 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/openshell-sdk/Cargo.toml‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
[package]
5+
name = "openshell-sdk"
6+
description = "Shared async Rust client for OpenShell gateways"
7+
version.workspace = true
8+
edition.workspace = true
9+
rust-version.workspace = true
10+
license.workspace = true
11+
repository.workspace = true
12+
13+
[dependencies]
14+
openshell-core = { path = "../openshell-core" }
15+
async-trait = "0.1"
16+
futures = { workspace = true }
17+
hyper = { workspace = true }
18+
hyper-util = { workspace = true }
19+
miette = { workspace = true }
20+
oauth2 = "5"
21+
reqwest = { workspace = true }
22+
rustls = { workspace = true }
23+
rustls-pemfile = { workspace = true }
24+
serde = { workspace = true }
25+
thiserror = { workspace = true }
26+
tokio = { workspace = true }
27+
tokio-rustls = { workspace = true }
28+
tokio-stream = { workspace = true }
29+
tokio-tungstenite = { workspace = true }
30+
tonic = { workspace = true, features = ["tls-native-roots"] }
31+
tower = { workspace = true }
32+
tracing = { workspace = true }
33+
34+
[dev-dependencies]
35+
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
36+
37+
[lints]
38+
workspace = true

‎crates/openshell-sdk/README.md‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# openshell-sdk
2+
3+
`openshell-sdk` is the shared async Rust client for OpenShell gateways. It owns
4+
the gRPC transport and auth stack so the CLI, the TUI, and language bindings
5+
share one implementation of channel setup, TLS, OIDC refresh, and the
6+
Cloudflare Access tunnel.
7+
8+
Designed in [RFC 0008](../../rfc/0008-shared-sdk-core-and-ts-binding/README.md).
9+
10+
## Two layers
11+
12+
- `OpenShellClient` — the curated, sandbox-focused surface: health, sandbox
13+
CRUD, readiness/deletion waits, and non-streaming exec.
14+
- `raw` — direct access to the generated tonic clients for RPCs the curated
15+
surface doesn't yet cover (inference, providers, policy, logs, settings, SSH,
16+
forwarding).
17+
18+
## Responsibilities
19+
20+
- Construct the gRPC channel and select the transport (plaintext vs TLS).
21+
- Load TLS material and set up mTLS channels.
22+
- Attach edge-auth bearer tokens and refresh OIDC tokens, with single-flight
23+
coalescing so only one refresh is in flight at a time.
24+
- Proxy connections through the Cloudflare Access tunnel for hosted gateways.
25+
- Map transport and gateway failures to a typed `SdkError` with a discriminable
26+
kind.
27+
28+
## Non-responsibilities
29+
30+
- Gateway-name resolution, default config-path lookups, and the OIDC browser
31+
flow. These are user-facing concerns owned by `openshell-cli`; the SDK
32+
consumes a `Refresh` trait the CLI implements.
33+
- Reading tokens from disk. Callers pass an explicit token; the SDK performs no
34+
filesystem access.
35+
- Defining the gRPC contract. The protos and generated types are owned by
36+
`openshell-core`.
37+
38+
## Transport and auth modes
39+
40+
Covers the connectivity modes the CLI exercises in production, except mTLS:
41+
42+
- Plaintext (local development)
43+
- Server-authenticated TLS over HTTPS (system roots, or a pinned private CA via `ca_cert`)
44+
- OIDC bearer over HTTPS (gateways behind an OAuth2/OIDC IdP)
45+
- Cloudflare Access tunnel (hosted gateways)
46+
- Insecure TLS (development/debug; certificate verification disabled)
47+
48+
mTLS (client certificates) is intentionally out of scope; gateways that require
49+
it continue to use `openshell-cli`'s legacy mTLS path until that auth method is
50+
retired.
51+
52+
## Public surface
53+
54+
`OpenShellClient::connect(ClientConfig)` returns a connected client exposing
55+
`health`, `create_sandbox`, `get_sandbox`, `list_sandboxes`, `delete_sandbox`,
56+
`wait_ready`, `wait_deleted`, and `exec`. Curated types (`SandboxSpec`,
57+
`SandboxRef`, `Health`, `ListOptions`, `ExecOptions`, `SandboxPhase`) use
58+
SDK-shaped enums rather than raw proto integers.
59+
60+
## Modules
61+
62+
| Module | Purpose |
63+
|---|---|
64+
| `client` | High-level `OpenShellClient` and the curated sandbox surface. |
65+
| `config` | `ClientConfig`, `AuthConfig`. |
66+
| `transport` | Channel construction, TLS resolution, request interceptors. |
67+
| `auth` | `EdgeAuthInterceptor` for bearer-token attachment. |
68+
| `oidc` | OIDC token handling at the transport layer. |
69+
| `refresh` | `Refresh` trait and single-flight refresh coalescing. |
70+
| `edge_tunnel` | Cloudflare Access tunnel dialer. |
71+
| `error` | `SdkError` taxonomy. |
72+
| `types` | Curated request/response types and proto conversions. |
73+
| `raw` | Escape hatch re-exporting the generated tonic clients. |
74+
75+
## Consumers
76+
77+
`openshell-cli`, `openshell-tui`, and `openshell-sdk-node` (published as
78+
`@openshell/sdk`).
79+
80+
## Notes
81+
82+
- Async-only. Tonic is async-native; callers needing a blocking call can wrap
83+
with their own runtime.
84+
- The surface is alpha and will grow as more RPCs graduate from `raw` into the
85+
curated client.

‎crates/openshell-sdk/src/auth.rs‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
//! Bearer-token authentication interceptor for outgoing gRPC requests.
5+
6+
use crate::error::{Result, SdkError};
7+
use std::sync::{Arc, RwLock};
8+
use tonic::metadata::{Ascii, MetadataValue};
9+
10+
/// Shared, mutable OIDC bearer header.
11+
///
12+
/// The interceptor reads it on every request and a [`crate::TokenSource`]
13+
/// overwrites it in place on refresh, so rotation propagates to an
14+
/// already-connected client without rebuilding the channel. Mirrors the slot
15+
/// pattern in `openshell-core`'s gRPC client.
16+
pub type BearerSlot = Arc<RwLock<Option<MetadataValue<Ascii>>>>;
17+
18+
/// Build the `authorization` header value for an OIDC bearer token.
19+
pub fn bearer_metadata(token: &str) -> Result<MetadataValue<Ascii>> {
20+
format!("Bearer {token}")
21+
.parse()
22+
.map_err(|_| SdkError::auth("invalid OIDC token value"))
23+
}
24+
25+
/// Interceptor that injects authentication headers into every outgoing gRPC request.
26+
///
27+
/// Supports OIDC Bearer tokens (standard `authorization` header) and
28+
/// Cloudflare Access tokens (custom headers). When no token is set, acts
29+
/// as a no-op. OIDC takes precedence over edge tokens.
30+
///
31+
/// The OIDC bearer is held in a shared [`BearerSlot`] so token refresh can
32+
/// update it live; edge tokens are captured once at construction (the edge
33+
/// tunnel binds the credential at handshake time).
34+
#[derive(Clone)]
35+
pub struct EdgeAuthInterceptor {
36+
bearer: Option<BearerSlot>,
37+
header_value: Option<MetadataValue<Ascii>>,
38+
cookie_value: Option<MetadataValue<Ascii>>,
39+
}
40+
41+
impl EdgeAuthInterceptor {
42+
/// Create an interceptor from optional token strings.
43+
///
44+
/// OIDC bearer token takes precedence over edge token. Returns a no-op
45+
/// interceptor when neither token is provided.
46+
pub fn new(oidc_token: Option<&str>, edge_token: Option<&str>) -> Result<Self> {
47+
if let Some(token) = oidc_token {
48+
let bearer = bearer_metadata(token)?;
49+
return Ok(Self {
50+
bearer: Some(Arc::new(RwLock::new(Some(bearer)))),
51+
header_value: None,
52+
cookie_value: None,
53+
});
54+
}
55+
56+
let (header_value, cookie_value) = match edge_token {
57+
Some(t) => {
58+
let hv: MetadataValue<Ascii> = t
59+
.parse()
60+
.map_err(|_| SdkError::auth("invalid edge token value"))?;
61+
let cv: MetadataValue<Ascii> = format!("CF_Authorization={t}")
62+
.parse()
63+
.map_err(|_| SdkError::auth("invalid edge token value for cookie"))?;
64+
(Some(hv), Some(cv))
65+
}
66+
None => (None, None),
67+
};
68+
Ok(Self {
69+
bearer: None,
70+
header_value,
71+
cookie_value,
72+
})
73+
}
74+
75+
/// No-op interceptor that passes requests through without modification.
76+
pub fn noop() -> Self {
77+
Self {
78+
bearer: None,
79+
header_value: None,
80+
cookie_value: None,
81+
}
82+
}
83+
84+
/// Handle to the live OIDC bearer slot, if this interceptor carries one.
85+
///
86+
/// The high-level client uses this to overwrite the token in place after
87+
/// a refresh. `None` for edge-token and no-op interceptors.
88+
pub fn bearer_slot(&self) -> Option<BearerSlot> {
89+
self.bearer.clone()
90+
}
91+
}
92+
93+
impl tonic::service::Interceptor for EdgeAuthInterceptor {
94+
fn call(
95+
&mut self,
96+
mut req: tonic::Request<()>,
97+
) -> std::result::Result<tonic::Request<()>, tonic::Status> {
98+
if let Some(slot) = &self.bearer
99+
&& let Some(val) = slot.read().ok().and_then(|g| g.clone())
100+
{
101+
req.metadata_mut().insert("authorization", val);
102+
}
103+
if let Some(ref val) = self.header_value {
104+
req.metadata_mut()
105+
.insert("cf-access-jwt-assertion", val.clone());
106+
}
107+
if let Some(ref val) = self.cookie_value {
108+
req.metadata_mut().insert("cookie", val.clone());
109+
}
110+
Ok(req)
111+
}
112+
}

0 commit comments

Comments
 (0)