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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ Do not rely on this file for a full inventory. The detailed public and contribut
| `crates/openshell-gateway/` | Gateway binary composition | Links selected first-party compute drivers into the backend-agnostic server registry |
| `crates/openshell-sdk/` | Shared client SDK | Async Rust gateway client (gRPC transport, TLS, OIDC refresh, edge tunnel); consumed by CLI, TUI, and `@openshell/sdk` |
| `crates/openshell-providers/` | Provider management | Credential provider backends |
| `crates/openshell-spiffe/` | SPIFFE identity types | Dependency-light SPIFFE ID mapping, claim parsing, and the sandbox identity provider interface |
| `crates/openshell-spire/` | SPIRE adapter | Gateway-owned SPIFFE Broker API client that issues and verifies stable sandbox JWT-SVIDs |
| `crates/openshell-spiffe/` | SPIFFE identity types | Dependency-light SPIFFE ID mapping and claim parsing |
| `crates/openshell-spire/` | SPIRE adapter | Gateway-owned SPIFFE Broker API client that issues and verifies stable sandbox JWT-SVIDs; implements the sandbox identity provider interface in `openshell-core` |
| `crates/openshell-tui/` | Terminal UI | Ratatui-based dashboard for monitoring |
| `crates/openshell-driver-launch/` | Driver launch protocol | `DriverLaunch` `GetLaunchInfo`/`Configure` service and the `Deferred` wrapper for launched compute drivers |
| `crates/openshell-driver-sdk/` | Launched-driver SDK | Stdin table reader, start-up exit codes, staged network-trust loader, telemetry and admission conversion, and gateway context |
Expand Down
1 change: 0 additions & 1 deletion Cargo.lock

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

10 changes: 10 additions & 0 deletions crates/openshell-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,13 @@ Use `openshell_core::proto_struct` when crossing between `serde_json` values and
`prost_types::{Struct, Value}`. Both conversion directions live in this module;
JSON-to-protobuf conversion is fallible so callers cannot silently replace an
unrepresentable number.

## Sandbox Identity

`sandbox_identity::SandboxIdentityProvider` is the gateway's interface for
obtaining a `SandboxIdentityAssertion`: a signed assertion of a sandbox's stable
identity, verified for one audience. The gateway passes its persisted driver
runtime identity as the workload reference. The implementation decides the
assertion's format and how it is verified. The interface reports the sanitized
`TokenGrantFailure`, and `SandboxIdentityAssertion` omits the token from `Debug`
output. `openshell-spire` implements the interface.
1 change: 1 addition & 0 deletions crates/openshell-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ pub mod resource_admission;
pub mod rpc_error;
pub mod sandbox_env;
pub mod sandbox_generation;
pub mod sandbox_identity;
pub mod sandbox_session;
pub mod sandbox_update;
pub mod secrets;
Expand Down
78 changes: 78 additions & 0 deletions crates/openshell-core/src/sandbox_identity.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// SPDX-License-Identifier: Apache-2.0

//! The gateway's source of sandbox identities for brokered provider tokens.
//!
//! The provider broker asks a [`SandboxIdentityProvider`] for a signed
//! assertion of a sandbox's identity and presents it to the token service.
//! The implementation decides the assertion's format and how it is verified.
//! `openshell-spire` implements the interface.

use std::fmt;

use crate::token_grant_failure::TokenGrantFailure;

/// A signed assertion of a sandbox's stable identity, verified for one
/// audience.
#[derive(Clone)]
pub struct SandboxIdentityAssertion {
/// The stable identity the assertion was issued and verified for.
pub identity: String,
/// The signed assertion. It is a credential and never printed.
pub token: String,
/// The verified expiry, in Unix seconds.
pub expires_at: i64,
}

impl fmt::Debug for SandboxIdentityAssertion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SandboxIdentityAssertion")
.field("identity", &self.identity)
.field("token", &"[REDACTED]")
.field("expires_at", &self.expires_at)
.finish()
}
}

/// Source of verified sandbox identity assertions for the gateway's provider
/// broker.
///
/// The gateway authorizes the sandbox session and the provider credential
/// before each request; implementations own issuance and verification only.
#[async_trait::async_trait]
pub trait SandboxIdentityProvider: fmt::Debug + Send + Sync {
/// Issue an assertion for `audience` whose identity is exactly the stable
/// identity of `sandbox_id` under `gateway_id`.
/// `runtime_identity` is the compute driver's immutable runtime reference
/// persisted by the gateway. It must never come from a workload request;
/// adapters use it to bind issuance to the attested backing object.
///
/// # Errors
///
/// Fails when issuance or verification fails, or when the IDs cannot
/// form a stable identity. The failure must not carry credentials or
/// upstream diagnostics.
async fn issue_assertion(
&self,
gateway_id: &str,
sandbox_id: &str,
audience: &str,
runtime_identity: &str,
) -> Result<SandboxIdentityAssertion, TokenGrantFailure>;
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn sandbox_identity_assertion_debug_redacts_the_token() {
let assertion = SandboxIdentityAssertion {
identity: "openshell/gateway/gw/sandbox/sb".into(),
token: "secret-token".into(),
expires_at: 1,
};
let printed = format!("{assertion:?}");
assert!(!printed.contains("secret-token"));
assert!(printed.contains("sandbox/sb"));
}
}
11 changes: 6 additions & 5 deletions crates/openshell-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -373,8 +373,8 @@ revision, the matched configured key and grant, and the subject token, which is
resolved before every lookup so its revocation or rotation also applies to
cached tokens. Concurrent misses for one cache key wait for a single
acquisition, then use its cached token. A token is served until the usual skew
before the earliest of its `expires_in`, its JWT `exp`, and the session, SVID,
and subject expiries, and no longer than the default cache lifetime; a
before the earliest of its `expires_in`, its JWT `exp`, and the session,
identity assertion, and subject expiries, and no longer than the default cache lifetime; a
configured cache TTL can only shorten that. The response reports the remaining
lifetime. The session is authorized again around each SPIRE and
token-service call. A cache hit and a fresh token then pass the same final
Expand All @@ -383,9 +383,10 @@ authorized. A fresh token is cached only after that check. Startup validates
the Broker API settings, and gateway state construction builds the
[`openshell-spire`](../openshell-spire/README.md) adapter once and returns a
configuration error when they are invalid. The broker depends only on
[`openshell-spiffe`](../openshell-spiffe/README.md)'s `SandboxIdentityProvider`
with `TokenGrantFailure` as its error, which returns a JWT-SVID
verified for the requested gateway, sandbox, and audience; each cache miss
[`openshell-core`](../openshell-core/README.md)'s `SandboxIdentityProvider`,
which returns an identity assertion
verified for the requested gateway, sandbox, and audience. With the SPIRE
adapter the assertion is a JWT-SVID; each cache miss
fetches a new SVID and the agent's current JWT bundle. SPIRE attests the referenced Sandbox resource UID and enforces the gateway's
`impersonate-via-spire` authorization for that object.

Expand Down
28 changes: 14 additions & 14 deletions crates/openshell-server/src/grpc/provider/access_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ use openshell_core::proto::{
GetSandboxProviderAccessTokenRequest, GetSandboxProviderAccessTokenResponse,
ProviderCredentialTokenGrant,
};
use openshell_core::sandbox_identity::SandboxIdentityProvider;
use openshell_core::token_grant_failure::BROKERED_TOKEN_GATEWAY_DEADLINE;
use openshell_spiffe::SandboxIdentityProvider;
use std::time::Duration;

static ACCESS_TOKENS: LazyLock<IntermediateTokenCache> = LazyLock::new(IntermediateTokenCache::new);
Expand Down Expand Up @@ -382,7 +382,7 @@ async fn acquire(
state: &ServerState,
bearer: &str,
session: &AuthenticatedSandboxSession,
identity: &dyn SandboxIdentityProvider<Error = TokenGrantFailure>,
identity: &dyn SandboxIdentityProvider,
gateway_id: &str,
grant: &ProviderCredentialTokenGrant,
subject: Option<&Subject>,
Expand All @@ -406,8 +406,8 @@ async fn acquire(
.get(crate::compute::COMPUTE_RUNTIME_IDENTITY_ANNOTATION)
})
.map_or("", String::as_str);
let svid = identity
.fetch_jwt_svid(
let assertion = identity
.issue_assertion(
gateway_id,
session.sandbox_id.as_str(),
&audience,
Expand Down Expand Up @@ -435,7 +435,7 @@ async fn acquire(
client_assertion_type: &grant.client_assertion_type,
subject_token: &subject.value,
subject_token_type: &subject.token_type,
audience: &svid.spiffe_id,
audience: &assertion.identity,
scopes: &[],
requested_token_type: &grant.requested_token_type,
},
Expand All @@ -447,7 +447,7 @@ async fn acquire(
client,
&grant.token_endpoint,
&TokenExchangeParams {
client_assertion: &svid.token,
client_assertion: &assertion.token,
client_assertion_type: &grant.client_assertion_type,
subject_token: &intermediate.access_token,
subject_token_type: oauth::ACCESS_TOKEN_TYPE,
Expand All @@ -464,7 +464,7 @@ async fn acquire(
client,
&grant.token_endpoint,
&oauth::TokenGrantParams {
client_assertion: &svid.token,
client_assertion: &assertion.token,
client_assertion_type: &grant.client_assertion_type,
audience: &grant.audience,
scopes: &grant.scopes,
Expand All @@ -478,7 +478,7 @@ async fn acquire(
let identity_expires_at_ms = session
.expires_at
.saturating_mul(1000)
.min(svid.expires_at.saturating_mul(1000))
.min(assertion.expires_at.saturating_mul(1000))
.min(subject_expiry.unwrap_or(i64::MAX));
let serve_until_ms =
serve_until_ms(&token, ttl_override, obtained_at_ms, identity_expires_at_ms).ok_or_else(
Expand All @@ -498,12 +498,12 @@ async fn acquire(
/// or `None` when it is already expired.
///
/// The issuer's `expires_in`, a parseable JWT `exp` of the access token, and
/// the session, SVID, and subject expiries each bound the token; `exp` can
/// only shorten it. Serving stops the usual skew before the earliest bound,
/// after at least one second, and never later than the default cache lifetime
/// (whose fallback applies when the issuer omits `expires_in`). A configured
/// cache TTL may shorten that lifetime but, unlike a dedicated supervisor's
/// cache, never extends it.
/// the session, identity assertion, and subject expiries each bound the token;
/// `exp` can only shorten it. Serving stops the usual skew before the earliest
/// bound, after at least one second, and never later than the default cache
/// lifetime (whose fallback applies when the issuer omits `expires_in`). A
/// configured cache TTL may shorten that lifetime but, unlike a dedicated
/// supervisor's cache, never extends it.
fn serve_until_ms(
token: &oauth::OAuthTokenResponse,
ttl_override: Option<Duration>,
Expand Down
10 changes: 4 additions & 6 deletions crates/openshell-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,13 @@ use hyper_util::{
service::TowerToHyperService,
};
use openshell_core::net::set_tcp_nodelay_best_effort;
use openshell_core::sandbox_identity::SandboxIdentityProvider;
use openshell_core::telemetry::TelemetryComputeDriver;
use openshell_core::token_grant_failure::TokenGrantFailure;
use openshell_core::{Config, Error, NetworkSupervisorTrustBundle, ObjectLabels, Result};
use openshell_extension_core::{
BearerTokenSlot, ExtensionAudience, ExtensionCallerKind, ExtensionKind, MAX_EXTENSION_TOKEN_TTL,
};
use openshell_ocsf::{ConfigStateChangeBuilder, SeverityId, StateId, StatusId};
use openshell_spiffe::SandboxIdentityProvider;
use openshell_supervisor_middleware::MiddlewareRegistry;
use std::collections::{BTreeMap, HashMap};
use std::io::ErrorKind;
Expand Down Expand Up @@ -453,10 +452,9 @@ pub struct ServerState {
/// on demand when the user source is configured.
pub(crate) provider_profile_sources: provider_profile_sources::ProviderProfileSources,

/// Source of sandbox JWT-SVIDs for brokered provider tokens, built once
/// from the SPIRE broker settings. `None` when disabled.
pub(crate) sandbox_identity:
Option<Arc<dyn SandboxIdentityProvider<Error = TokenGrantFailure>>>,
/// Source of sandbox identity assertions for brokered provider tokens,
/// built once from the SPIRE broker settings. `None` when disabled.
pub(crate) sandbox_identity: Option<Arc<dyn SandboxIdentityProvider>>,

/// OIDC admin role name for workspace-level authorization.
/// Empty when OIDC is not configured — `authorize_workspace()` treats
Expand Down
5 changes: 2 additions & 3 deletions crates/openshell-server/src/spiffe_broker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
use std::sync::Arc;

use openshell_core::config::{Config, SpiffeBrokerConfig};
use openshell_core::token_grant_failure::TokenGrantFailure;
use openshell_spiffe::SandboxIdentityProvider;
use openshell_core::sandbox_identity::SandboxIdentityProvider;

/// Check the broker settings `config` enables without building them.
///
Expand All @@ -29,7 +28,7 @@ pub fn validate_config(config: &Config) -> Result<(), String> {
/// Rejects what [`validate_config`] rejects.
pub fn sandbox_identity_provider(
config: &Config,
) -> Result<Option<Arc<dyn SandboxIdentityProvider<Error = TokenGrantFailure>>>, String> {
) -> Result<Option<Arc<dyn SandboxIdentityProvider>>, String> {
let Some(broker) = enabled(config)? else {
return Ok(None);
};
Expand Down
3 changes: 1 addition & 2 deletions crates/openshell-spiffe/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@

[package]
name = "openshell-spiffe"
description = "SPIFFE identity types, parsing, and sandbox identity provider interface for OpenShell"
description = "SPIFFE identity types and parsing for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
async-trait = "0.1"
base64 = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
Expand Down
6 changes: 0 additions & 6 deletions crates/openshell-spiffe/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,6 @@ depend on it without a cycle.
be SPIFFE path segments; nothing is encoded, so distinct IDs always map to
distinct SPIFFE IDs. `SpiffeBrokerConfig::validate` in `openshell-core`
uses it.
- `SandboxIdentityProvider` is the gateway's interface for obtaining a
`SandboxJwtSvid` verified for that stable identity and one audience, using
the gateway's persisted driver runtime identity as the workload reference. The
error is an associated type: the SPIRE adapter in `openshell-spire` uses the
sanitized `TokenGrantFailure`. `SandboxJwtSvid` omits the token from `Debug`
output.
- `workload_api_endpoint`, `trust_domain`, and `is_spiffe_path_segment` handle
Workload API endpoints and SPIFFE ID parts.
- `parse_unverified_jwt_svid_claims` decodes JWT-SVID claims without checking
Expand Down
69 changes: 3 additions & 66 deletions crates/openshell-spiffe/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@

//! Shared SPIFFE helpers used by the gateway and sandbox supervisor.
//!
//! Protocol types, unverified claim parsing, stable sandbox identity mapping,
//! and the sandbox identity provider interface. Signature verification and
//! SPIRE access belong to the crates that implement the interface.
//! Protocol types, unverified claim parsing, and stable sandbox identity
//! mapping. This crate verifies no signatures and has no Workload API or
//! Broker API client.

use std::fmt;
use std::path::Path;

use base64::Engine as _;
Expand Down Expand Up @@ -144,56 +143,6 @@ impl SandboxSpiffeIdPrefix {
}
}

/// A JWT-SVID verified for a sandbox's stable SPIFFE ID and one audience.
#[derive(Clone)]
pub struct SandboxJwtSvid {
/// The stable SPIFFE ID the token was issued and verified for.
pub spiffe_id: String,
/// The signed token. It is a credential and never printed.
pub token: String,
/// The verified `exp` claim, in Unix seconds.
pub expires_at: i64,
}

impl fmt::Debug for SandboxJwtSvid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SandboxJwtSvid")
.field("spiffe_id", &self.spiffe_id)
.field("token", &"[REDACTED]")
.field("expires_at", &self.expires_at)
.finish()
}
}

/// Source of verified sandbox JWT-SVIDs for the gateway's provider broker.
///
/// The gateway authorizes the sandbox session and the provider credential
/// before each request; implementations own issuance and verification only.
#[async_trait::async_trait]
pub trait SandboxIdentityProvider: fmt::Debug + Send + Sync {
/// Failure the implementation reports. It must not carry credentials or
/// upstream diagnostics.
type Error;

/// Obtain a JWT-SVID for `audience` whose identity is exactly the stable
/// SPIFFE ID of `sandbox_id` under `gateway_id`.
/// `runtime_identity` is the compute driver's immutable runtime reference
/// persisted by the gateway. It must never come from a workload request;
/// adapters use it to bind issuance to the attested backing object.
///
/// # Errors
///
/// Fails when issuance or verification fails, or when the IDs cannot
/// form a stable SPIFFE ID.
async fn fetch_jwt_svid(
&self,
gateway_id: &str,
sandbox_id: &str,
audience: &str,
runtime_identity: &str,
) -> Result<SandboxJwtSvid, Self::Error>;
}

/// A non-empty SPIFFE path segment other than `.` and `..`.
#[must_use]
pub fn is_spiffe_path_segment(segment: &str) -> bool {
Expand Down Expand Up @@ -313,18 +262,6 @@ mod tests {
}
}

#[test]
fn sandbox_jwt_svid_debug_redacts_the_token() {
let svid = SandboxJwtSvid {
spiffe_id: "spiffe://example.org/openshell/gateway/gw/sandbox/sb".into(),
token: "secret-token".into(),
expires_at: 1,
};
let printed = format!("{svid:?}");
assert!(!printed.contains("secret-token"));
assert!(printed.contains("sandbox/sb"));
}

#[test]
fn trust_domain_extracts_domain_from_spiffe_id() {
assert_eq!(
Expand Down
Loading
Loading