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
1 change: 1 addition & 0 deletions crates/openshell-core/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut proto_config = tonic_prost_build::Config::new();
// Keep optional grant evidence off sandbox lifecycle futures' stacks.
proto_config.boxed(".openshell.v1.SandboxStatus.last_token_grant_failure");
proto_config.skip_debug([".openshell.v1.GetSandboxProviderAccessTokenRequest"]);
let proto_include = if use_vendored_protoc {
proto_config.protoc_executable(protoc_bin_vendored::protoc_bin_path()?);
Some(protoc_bin_vendored::include_path()?)
Expand Down
165 changes: 165 additions & 0 deletions crates/openshell-core/src/driver_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,61 @@ use std::path::{Path, PathBuf};

use crate::proto::compute::v1::DriverSandbox;

/// Check that a launch bundle's provider identities belong to this sandbox launch.
///
/// The stable ID must end in this gateway and sandbox. The launch ID must be
/// that stable ID followed by `/launch/<generation>`, so it changes exactly
/// when the gateway issues a new runtime generation. A driver calls this
/// before it marks a supervisor with the launch ID.
#[cfg(feature = "jwt")]
#[allow(clippy::result_large_err)]
pub fn validate_provider_launch_identity(
sandbox_id: &str,
generation_id: &str,
authentication: &crate::jwt::SandboxLaunchAuthentication,
) -> Result<(), tonic::Status> {
let invalid =
|| tonic::Status::invalid_argument("provider identity does not match the sandbox launch");
let supervisor = &authentication.supervisor;
if supervisor.runtime_generation.as_str() != generation_id {
return Err(invalid());
}
let sandbox_path = format!(
"/gateway/{}/sandbox/{sandbox_id}",
authentication.gateway_id
);
let prefix = supervisor
.provider_spiffe_id
.as_deref()
.and_then(|id| id.strip_suffix(&sandbox_path))
.ok_or_else(invalid)?;
let prefix = openshell_spiffe::SandboxSpiffeIdPrefix::parse(prefix).map_err(|_| invalid())?;
let expected = prefix
.supervisor_launch_spiffe_id(&authentication.gateway_id, sandbox_id, generation_id)
.map_err(|_| invalid())?;
if supervisor.provider_launch_spiffe_id.as_deref() != Some(expected.as_str()) {
return Err(invalid());
}
Ok(())
}

/// Gateway alias available inside a sandbox VM.
pub const VM_HOST_GATEWAY_ALIAS: &str = "host.openshell.internal";

/// Gateway hostnames that VM host supervisors rewrite to numeric loopback.
pub const VM_HOST_LOOPBACK_ALIASES: &[&str] = &[
VM_HOST_GATEWAY_ALIAS,
"host.containers.internal",
"host.docker.internal",
];

/// Supervisor command that reports whether it can see a Workload API socket.
pub const PROVIDER_WORKLOAD_IDENTITY_PROBE: &str = "provider-workload-identity-probe";

/// Exit statuses for the provider probe with a socket path argument.
pub const PROVIDER_WORKLOAD_SOCKET_PROBE_PRESENT: i32 = 70;
pub const PROVIDER_WORKLOAD_SOCKET_PROBE_UNAVAILABLE: i32 = 71;

// ---------------------------------------------------------------------------
// Sandbox container/pod label keys (openshell.ai/ namespace)
// ---------------------------------------------------------------------------
Expand All @@ -34,6 +89,9 @@ pub const LABEL_SANDBOX_WORKSPACE: &str = "openshell.ai/sandbox-workspace";
/// Label carrying the gateway identity on managed namespaces.
pub const LABEL_GATEWAY_ID: &str = "openshell.ai/gateway-id";

/// SPIFFE ID registered for one driver-owned supervisor launch.
pub const LABEL_PROVIDER_LAUNCH_SPIFFE_ID: &str = "openshell.ai/provider-launch-spiffe-id";

/// Label selector that matches all OpenShell-managed resources which carry a
/// sandbox ID label. Used by list and watch operations to exclude foreign
/// resources from the same namespace.
Expand Down Expand Up @@ -743,6 +801,24 @@ pub fn validate_provider_spiffe_unix_socket(path: &Path) -> Result<(), String> {
Ok(())
}

/// Check that an absolute path resolves to a Unix socket in the current filesystem.
pub fn provider_spiffe_socket_visible(path: &Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::FileTypeExt as _;

path.is_absolute()
&& path
.metadata()
.is_ok_and(|meta| meta.file_type().is_socket())
}
#[cfg(not(unix))]
{
let _ = path;
false
}
}

/// Return the guest/container path for a projected provider SPIFFE socket.
pub fn projected_provider_spiffe_socket_path(path: &Path) -> Result<String, String> {
validate_provider_spiffe_unix_socket(path)?;
Expand Down Expand Up @@ -1550,4 +1626,93 @@ mod tests {
})
.expect("an intercepting proxy's CA is meaningful without an https:// proxy URL");
}

#[cfg(feature = "jwt")]
#[test]
fn provider_launch_identity_binds_generation_sandbox_and_launch() {
use crate::jwt::{
CredentialEpoch, SandboxLaunchAuthentication, SecretJwt, SessionRotation,
SupervisorAuthBundle,
};
use crate::sandbox_generation::SandboxGenerationId;
use crate::sandbox_session::SandboxSessionId;

let sandbox = "spiffe://example.test/gateway/gateway/sandbox/sandbox-a";
let authentication = SandboxLaunchAuthentication {
supervisor: SupervisorAuthBundle {
session_id: SandboxSessionId::new(),
runtime_generation: SandboxGenerationId::parse("generation").unwrap(),
session_rotation: SessionRotation::new(1).unwrap(),
auth_epoch: CredentialEpoch::new(1).unwrap(),
gateway_token: SecretJwt::parse("gateway-token").unwrap(),
gateway_expires_at: 0,
sandbox_token: SecretJwt::parse("sandbox-token").unwrap(),
sandbox_expires_at: 0,
provider_spiffe_id: Some(sandbox.to_string()),
provider_launch_spiffe_id: Some(format!("{sandbox}/launch/generation")),
ssh_host_private_key: None,
traces_otlp_headers: None,
ocsf_otlp_headers: None,
agent_otlp_headers: None,
otlp_tls: Vec::new(),
traces_otlp_tls: None,
ocsf_otlp_tls: None,
agent_otlp_tls: None,
},
gateway_id: "gateway".to_string(),
verification_keys: Vec::new(),
};
validate_provider_launch_identity("sandbox-a", "generation", &authentication).unwrap();

let with_launch = |launch: Option<String>| {
let mut changed = authentication.clone();
changed.supervisor.provider_launch_spiffe_id = launch;
changed
};
for (case, sandbox_id, generation_id, bundle) in [
(
"another generation",
"sandbox-a",
"other-generation",
authentication.clone(),
),
(
"another sandbox",
"sandbox-b",
"generation",
authentication.clone(),
),
(
"no launch identity",
"sandbox-a",
"generation",
with_launch(None),
),
(
"a launch identity of another sandbox",
"sandbox-a",
"generation",
with_launch(Some(
"spiffe://example.test/gateway/gateway/sandbox/sandbox-b/launch/generation"
.to_string(),
)),
),
(
"a launch identity for another generation",
"sandbox-a",
"generation",
with_launch(Some(format!("{sandbox}/launch/earlier-generation"))),
),
(
"a launch identity with extra segments",
"sandbox-a",
"generation",
with_launch(Some(format!("{sandbox}/launch/generation/extra"))),
),
] {
let error =
validate_provider_launch_identity(sandbox_id, generation_id, &bundle).unwrap_err();
assert_eq!(error.code(), tonic::Code::InvalidArgument, "{case}");
}
}
}
27 changes: 14 additions & 13 deletions crates/openshell-core/src/extension_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ pub const COMPUTE_SUSPEND_RESUME: &str = "openshell.compute.suspend-resume";
pub const COMPUTE_UPDATE_SANDBOX_CONFIGURATION: &str =
"openshell.compute.update-sandbox-configuration";

/// Driver gives each dedicated supervisor a Workload API socket and marks it
/// with the launch SPIFFE ID from its launch bundle. A start whose bundle
/// names a different launch replaces the supervisor.
pub const COMPUTE_PROVIDER_WORKLOAD_IDENTITY: &str = "openshell.compute.provider-workload-identity";

/// Capability for supervisor middleware that implements HTTP hooks.
///
/// A service selects HTTP hooks for all of its HTTP bindings by
Expand Down Expand Up @@ -160,6 +165,7 @@ pub fn gateway_metadata(family: ExtensionFamily) -> PeerMetadata {
supported_capabilities.push(COMPUTE_LAUNCH_AUTHENTICATION.to_string());
supported_capabilities.push(COMPUTE_ISOLATION_BACKEND.to_string());
supported_capabilities.push(COMPUTE_UPDATE_SANDBOX_CONFIGURATION.to_string());
supported_capabilities.push(COMPUTE_PROVIDER_WORKLOAD_IDENTITY.to_string());
}
ExtensionFamily::SupervisorMiddleware => {
supported_capabilities.push(SUPERVISOR_MIDDLEWARE_HTTP_HOOKS.to_string());
Expand Down Expand Up @@ -458,20 +464,15 @@ mod tests {
use super::*;

#[test]
fn compute_gateway_advertises_both_optional_extensions() {
fn compute_gateway_advertises_optional_extensions() {
let gateway = gateway_metadata(ExtensionFamily::Compute);
assert!(
gateway
.supported_capabilities
.iter()
.any(|c| c == COMPUTE_ISOLATION_BACKEND)
);
assert!(
gateway
.supported_capabilities
.iter()
.any(|c| c == COMPUTE_UPDATE_SANDBOX_CONFIGURATION)
);
for capability in [
COMPUTE_ISOLATION_BACKEND,
COMPUTE_UPDATE_SANDBOX_CONFIGURATION,
COMPUTE_PROVIDER_WORKLOAD_IDENTITY,
] {
assert!(has_capability(&gateway.supported_capabilities, capability));
}
}

fn compatible() -> (PeerMetadata, PeerMetadata) {
Expand Down
97 changes: 91 additions & 6 deletions crates/openshell-core/src/grpc_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1747,6 +1747,13 @@ pub async fn exchange_provider_subject_token(
))
}

/// A dedicated supervisor's JWT-SVIDs for the provider and launch audiences.
#[derive(Clone)]
pub struct ProviderWorkloadAssertions {
pub jwt_svid: String,
pub launch_jwt_svid: String,
}

/// Final provider access tokens for one sandbox instance over one reused
/// gateway channel.
///
Expand Down Expand Up @@ -1782,19 +1789,37 @@ impl SandboxProviderTokenClient {
}
}

/// Obtain only the final access token; the gateway selects and verifies
/// the sandbox identity and resolves all grant parameters from its
/// configuration.
/// Validate the gateway before fetching a local workload assertion.
/// A plaintext endpoint must identify loopback without DNS.
///
/// # Errors
/// Returns a configuration failure for an invalid gateway URL or a
/// remote plaintext endpoint.
pub fn require_attested_transport(&self) -> std::result::Result<(), TokenGrantFailure> {
let (endpoint, _) = self.gateway.as_ref().map_err(|failure| *failure)?;
validate_attested_token_grant_transport(endpoint)
}

/// Obtain the final access token. The gateway verifies the sandbox
/// identity and resolves grant parameters from its configuration.
/// A dedicated supervisor can supply its attested JWT-SVIDs.
///
/// One deadline bounds connection readiness and the call. Network failures
/// do not serialize channel initialization for concurrent requests.
#[tracing::instrument(name = "supervisor.gateway.get_provider_access_token", skip_all)]
pub async fn get_access_token(
&self,
credential_key: &str,
assertions: Option<ProviderWorkloadAssertions>,
request_id: Option<&str>,
) -> std::result::Result<ProviderSubjectTokenExchangeResult, TokenGrantFailure> {
let (endpoint, gateway) = self.gateway.as_ref().map_err(|failure| *failure)?;
let (jwt_svid, launch_jwt_svid) = if let Some(assertions) = assertions {
self.require_attested_transport()?;
(Some(assertions.jwt_svid), Some(assertions.launch_jwt_svid))
} else {
(None, None)
};
// Like connect(), refuse locally revoked sandbox instance credentials
// before the call; the response boundary rejects them again.
let unavailable = || gateway_grant_failure(TokenGrantFailureKind::Unavailable);
Expand All @@ -1805,6 +1830,8 @@ impl SandboxProviderTokenClient {
.ok_or_else(|| gateway_grant_failure(TokenGrantFailureKind::Configuration))?;
let mut request = tonic::Request::new(crate::proto::GetSandboxProviderAccessTokenRequest {
credential_key: key,
jwt_svid,
launch_jwt_svid,
});
if let Some(value) = request_id.and_then(|value| value.parse().ok()) {
request.metadata_mut().insert("x-request-id", value);
Expand Down Expand Up @@ -1886,6 +1913,23 @@ pub fn token_grant_gateway_endpoint(
Ok(endpoint)
}

/// Check the transport of an authority parsed by [`token_grant_gateway_endpoint`].
/// Plain HTTP is permitted only on a numeric loopback address.
pub fn validate_attested_token_grant_transport(
endpoint: &url::Url,
) -> std::result::Result<(), TokenGrantFailure> {
let direct_loopback = match endpoint.host() {
Some(url::Host::Ipv4(address)) => address.is_loopback(),
Some(url::Host::Ipv6(address)) => address.is_loopback(),
_ => false,
};
if endpoint.scheme() == "https" || (endpoint.scheme() == "http" && direct_loopback) {
Ok(())
} else {
Err(gateway_grant_failure(TokenGrantFailureKind::Configuration))
}
}

fn provider_subject_token_exchange_result(
inner: crate::proto::ExchangeProviderSubjectTokenResponse,
) -> std::result::Result<ProviderSubjectTokenExchangeResult, TokenGrantFailure> {
Expand Down Expand Up @@ -1993,8 +2037,8 @@ mod token_grant_exchange_tests {
);
let started = tokio::time::Instant::now();
let results: [_; 2] = tokio::join!(
client.get_access_token("api.test\t443\t/\towner\tprovider:token", None),
client.get_access_token("api.test\t443\t/\towner\tprovider:token", None),
client.get_access_token("api.test\t443\t/\towner\tprovider:token", None, None),
client.get_access_token("api.test\t443\t/\towner\tprovider:token", None, None),
)
.into();
for result in results {
Expand All @@ -2016,10 +2060,51 @@ mod token_grant_exchange_tests {
TokenSource::Env,
),
));
let failure = invalid.get_access_token("key", None).await.err().unwrap();
let failure = invalid
.get_access_token("key", None, None)
.await
.err()
.unwrap();
assert_eq!(failure.kind(), TokenGrantFailureKind::Configuration);
}

#[tokio::test]
async fn access_token_client_keeps_assertions_off_nonlocal_plaintext() {
let client = |url| {
SandboxProviderTokenClient::new(GatewayEndpoint::new(
url,
GatewayCredentials::new(
AsciiMetadataValue::from_static("Bearer test"),
TokenSource::Env,
),
))
};
for url in ["http://192.0.2.2:8080", "http://localhost:8080"] {
let client = client(url);
let failure = client
.get_access_token(
"api.test\t443\t/\towner\tprovider:token",
Some(ProviderWorkloadAssertions {
jwt_svid: "oauth-assertion-canary".into(),
launch_jwt_svid: "launch-assertion-canary".into(),
}),
None,
)
.await
.err()
.expect("nonlocal plaintext must reject a workload assertion");
assert_eq!(failure.kind(), TokenGrantFailureKind::Configuration);
assert!(client.client.get().is_none());
}
for url in [
"https://gateway.test:8080",
"http://127.0.0.1:8080",
"http://[::1]:8080",
] {
assert!(client(url).require_attested_transport().is_ok());
}
}

#[test]
fn gateway_response_keeps_expiration_and_rejects_invalid_duration() {
let response = |seconds, nanos| crate::proto::ExchangeProviderSubjectTokenResponse {
Expand Down
Loading
Loading