Skip to content

Commit 9ea7a4a

Browse files
committed
feat(spiffe): verify provider workload identity across drivers
Signed-off-by: Shiju <shiju@nvidia.com>
1 parent 659b45f commit 9ea7a4a

83 files changed

Lines changed: 17336 additions & 2131 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎crates/openshell-core/build.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
5252
let mut proto_config = tonic_prost_build::Config::new();
5353
// Keep optional grant evidence off sandbox lifecycle futures' stacks.
5454
proto_config.boxed(".openshell.v1.SandboxStatus.last_token_grant_failure");
55+
proto_config.skip_debug([".openshell.v1.GetSandboxProviderAccessTokenRequest"]);
5556
let proto_include = if use_vendored_protoc {
5657
proto_config.protoc_executable(protoc_bin_vendored::protoc_bin_path()?);
5758
Some(protoc_bin_vendored::include_path()?)

‎crates/openshell-core/src/config.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,14 @@ impl SpiffeBrokerConfig {
335335
}
336336
}
337337

338+
/// Validate provider assertions from dedicated, platform-attested supervisors.
339+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
340+
#[serde(deny_unknown_fields)]
341+
pub struct SpiffeWorkloadIdentityConfig {
342+
pub spiffe_id_prefix: String,
343+
pub workload_api_socket_path: PathBuf,
344+
}
345+
338346
/// Server configuration.
339347
///
340348
/// Built programmatically in [`crate::Config::new`] and the gateway CLI from
@@ -419,6 +427,7 @@ pub struct Config {
419427
pub gateway_jwt: Option<GatewayJwtConfig>,
420428
/// Gateway-only access to SPIRE; shared supervisors receive access tokens.
421429
pub spiffe_broker: Option<SpiffeBrokerConfig>,
430+
pub spiffe_workload_identity: Option<SpiffeWorkloadIdentityConfig>,
422431

423432
/// Database URL for persistence.
424433
pub database_url: String,
@@ -1340,6 +1349,7 @@ impl Config {
13401349
audit: GatewayAuditConfig::default(),
13411350
gateway_jwt: None,
13421351
spiffe_broker: None,
1352+
spiffe_workload_identity: None,
13431353
database_url: String::new(),
13441354
database_auth: DatabaseAuthMode::default(),
13451355
database_max_connections: None,

‎crates/openshell-core/src/driver_utils.rs‎

Lines changed: 85 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,72 @@
55
66
use rustls::pki_types::{CertificateDer, pem::PemObject};
77
use std::path::{Path, PathBuf};
8+
use std::time::Duration;
89

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

12+
/// Time a managed driver defers an external stop signal while awaiting release.
13+
pub const EXTERNAL_STOP_GRACE: Duration = Duration::from_secs(30);
14+
15+
/// Time a driver gives admitted provider launch work to record its outcome.
16+
pub const PROVIDER_LAUNCH_DRAIN_GRACE: Duration = Duration::from_mins(3);
17+
18+
/// Bind an ordered start and its private credentials to one sandbox launch.
19+
#[cfg(feature = "jwt")]
20+
#[allow(clippy::result_large_err)]
21+
pub fn validate_ordered_start_authentication(
22+
sandbox_id: &str,
23+
generation_id: &str,
24+
operation: &crate::proto::compute::v1::OrderedStart,
25+
authentication: &crate::jwt::SandboxLaunchAuthentication,
26+
) -> Result<(), tonic::Status> {
27+
let invalid =
28+
|| tonic::Status::invalid_argument("ordered start does not match launch identity");
29+
let supervisor = &authentication.supervisor;
30+
if supervisor.runtime_generation.as_str() != generation_id {
31+
return Err(invalid());
32+
}
33+
let sandbox_path = format!(
34+
"/gateway/{}/sandbox/{sandbox_id}",
35+
authentication.gateway_id
36+
);
37+
let prefix = supervisor
38+
.provider_spiffe_id
39+
.as_deref()
40+
.and_then(|id| id.strip_suffix(&sandbox_path))
41+
.ok_or_else(invalid)?;
42+
let prefix = openshell_spiffe::SandboxSpiffeIdPrefix::parse(prefix).map_err(|_| invalid())?;
43+
let expected = prefix
44+
.supervisor_launch_spiffe_id(
45+
&authentication.gateway_id,
46+
sandbox_id,
47+
&operation.operation_id,
48+
)
49+
.map_err(|_| invalid())?;
50+
if supervisor.provider_launch_spiffe_id.as_deref() != Some(expected.as_str()) {
51+
return Err(invalid());
52+
}
53+
Ok(())
54+
}
55+
56+
/// Gateway alias available inside a sandbox VM.
57+
pub const VM_HOST_GATEWAY_ALIAS: &str = "host.openshell.internal";
58+
59+
/// Gateway hostnames that VM host supervisors rewrite to numeric loopback.
60+
pub const VM_HOST_LOOPBACK_ALIASES: &[&str] = &[
61+
VM_HOST_GATEWAY_ALIAS,
62+
"host.containers.internal",
63+
"host.docker.internal",
64+
];
65+
66+
/// Supervisor command that succeeds when it supports provider launch identity.
67+
pub const PROVIDER_WORKLOAD_IDENTITY_PROBE: &str = "provider-workload-identity-probe";
68+
69+
/// Exit statuses for the provider probe with a socket path argument.
70+
/// The legacy no-argument probe exits successfully with status zero.
71+
pub const PROVIDER_WORKLOAD_SOCKET_PROBE_PRESENT: i32 = 70;
72+
pub const PROVIDER_WORKLOAD_SOCKET_PROBE_UNAVAILABLE: i32 = 71;
73+
1174
// ---------------------------------------------------------------------------
1275
// Sandbox container/pod label keys (openshell.ai/ namespace)
1376
// ---------------------------------------------------------------------------
@@ -34,6 +97,9 @@ pub const LABEL_SANDBOX_WORKSPACE: &str = "openshell.ai/sandbox-workspace";
3497
/// Label carrying the gateway identity on managed namespaces.
3598
pub const LABEL_GATEWAY_ID: &str = "openshell.ai/gateway-id";
3699

100+
/// SPIFFE ID registered for one driver-owned supervisor launch.
101+
pub const LABEL_PROVIDER_LAUNCH_SPIFFE_ID: &str = "openshell.ai/provider-launch-spiffe-id";
102+
37103
/// Label selector that matches all OpenShell-managed resources which carry a
38104
/// sandbox ID label. Used by list and watch operations to exclude foreign
39105
/// resources from the same namespace.
@@ -743,6 +809,24 @@ pub fn validate_provider_spiffe_unix_socket(path: &Path) -> Result<(), String> {
743809
Ok(())
744810
}
745811

812+
/// Check that an absolute path resolves to a Unix socket in the current filesystem.
813+
pub fn provider_spiffe_socket_visible(path: &Path) -> bool {
814+
#[cfg(unix)]
815+
{
816+
use std::os::unix::fs::FileTypeExt as _;
817+
818+
path.is_absolute()
819+
&& path
820+
.metadata()
821+
.is_ok_and(|meta| meta.file_type().is_socket())
822+
}
823+
#[cfg(not(unix))]
824+
{
825+
let _ = path;
826+
false
827+
}
828+
}
829+
746830
/// Return the guest/container path for a projected provider SPIFFE socket.
747831
pub fn projected_provider_spiffe_socket_path(path: &Path) -> Result<String, String> {
748832
validate_provider_spiffe_unix_socket(path)?;
@@ -1257,7 +1341,7 @@ mod tests {
12571341
let err = read_upstream_proxy_credential_file(fifo.to_str().unwrap()).unwrap_err();
12581342
assert!(err.contains("regular file"), "{err}");
12591343
assert!(
1260-
start.elapsed() < std::time::Duration::from_secs(5),
1344+
start.elapsed() < Duration::from_secs(5),
12611345
"reading a FIFO must not block"
12621346
);
12631347
}

‎crates/openshell-core/src/error.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,9 @@ pub enum ComputeDriverError {
122122
/// A precondition for the operation was not met.
123123
#[error("{0}")]
124124
Precondition(String),
125+
/// Communication ended before the backend operation outcome was known.
126+
#[error("{0}")]
127+
BackendUnavailable(String),
125128
/// Generic error message.
126129
#[error("{0}")]
127130
Message(String),
@@ -134,6 +137,7 @@ impl From<ComputeDriverError> for tonic::Status {
134137
ComputeDriverError::NotFound => Self::not_found("sandbox not found"),
135138
ComputeDriverError::InvalidArgument(m) => Self::invalid_argument(m),
136139
ComputeDriverError::Precondition(m) => Self::failed_precondition(m),
140+
ComputeDriverError::BackendUnavailable(m) => Self::unavailable(m),
137141
ComputeDriverError::Message(m) => Self::internal(m),
138142
}
139143
}

‎crates/openshell-core/src/extension_protocol.rs‎

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,20 @@ pub const COMPUTE_SUSPEND_RESUME: &str = "openshell.compute.suspend-resume";
4747
pub const COMPUTE_UPDATE_SANDBOX_CONFIGURATION: &str =
4848
"openshell.compute.update-sandbox-configuration";
4949

50+
/// Driver provisions the Workload API, exposes the launch ID, and durably orders starts and stops.
51+
pub const COMPUTE_PROVIDER_WORKLOAD_IDENTITY: &str =
52+
"openshell.compute.provider-workload-identity.v5";
53+
54+
/// Driver fences provider launch effects using the revision sent with `StartSandbox`.
55+
pub const COMPUTE_ORDERED_PROVIDER_LAUNCH: &str = "openshell.compute.ordered-provider-launch";
56+
57+
/// Driver durably orders and replays starts for verified provider identity.
58+
pub const COMPUTE_ORDERED_PROVIDER_START: &str = "openshell.compute.ordered-provider-start";
59+
60+
/// Driver can return an ordered start receipt without admitting a start.
61+
pub const COMPUTE_ORDERED_PROVIDER_START_RECEIPT_LOOKUP: &str =
62+
"openshell.compute.ordered-provider-start.receipt-lookup";
63+
5064
/// Capability for supervisor middleware that implements HTTP hooks.
5165
///
5266
/// A service selects HTTP hooks for all of its HTTP bindings by
@@ -160,6 +174,10 @@ pub fn gateway_metadata(family: ExtensionFamily) -> PeerMetadata {
160174
supported_capabilities.push(COMPUTE_LAUNCH_AUTHENTICATION.to_string());
161175
supported_capabilities.push(COMPUTE_ISOLATION_BACKEND.to_string());
162176
supported_capabilities.push(COMPUTE_UPDATE_SANDBOX_CONFIGURATION.to_string());
177+
supported_capabilities.push(COMPUTE_PROVIDER_WORKLOAD_IDENTITY.to_string());
178+
supported_capabilities.push(COMPUTE_ORDERED_PROVIDER_LAUNCH.to_string());
179+
supported_capabilities.push(COMPUTE_ORDERED_PROVIDER_START.to_string());
180+
supported_capabilities.push(COMPUTE_ORDERED_PROVIDER_START_RECEIPT_LOOKUP.to_string());
163181
}
164182
ExtensionFamily::SupervisorMiddleware => {
165183
supported_capabilities.push(SUPERVISOR_MIDDLEWARE_HTTP_HOOKS.to_string());
@@ -458,20 +476,18 @@ mod tests {
458476
use super::*;
459477

460478
#[test]
461-
fn compute_gateway_advertises_both_optional_extensions() {
479+
fn compute_gateway_advertises_optional_extensions() {
462480
let gateway = gateway_metadata(ExtensionFamily::Compute);
463-
assert!(
464-
gateway
465-
.supported_capabilities
466-
.iter()
467-
.any(|c| c == COMPUTE_ISOLATION_BACKEND)
468-
);
469-
assert!(
470-
gateway
471-
.supported_capabilities
472-
.iter()
473-
.any(|c| c == COMPUTE_UPDATE_SANDBOX_CONFIGURATION)
474-
);
481+
for capability in [
482+
COMPUTE_ISOLATION_BACKEND,
483+
COMPUTE_UPDATE_SANDBOX_CONFIGURATION,
484+
COMPUTE_PROVIDER_WORKLOAD_IDENTITY,
485+
COMPUTE_ORDERED_PROVIDER_LAUNCH,
486+
COMPUTE_ORDERED_PROVIDER_START,
487+
COMPUTE_ORDERED_PROVIDER_START_RECEIPT_LOOKUP,
488+
] {
489+
assert!(has_capability(&gateway.supported_capabilities, capability));
490+
}
475491
}
476492

477493
fn compatible() -> (PeerMetadata, PeerMetadata) {

‎crates/openshell-core/src/grpc_client.rs‎

Lines changed: 91 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1747,6 +1747,13 @@ pub async fn exchange_provider_subject_token(
17471747
))
17481748
}
17491749

1750+
/// A dedicated supervisor's JWT-SVIDs for the provider and launch audiences.
1751+
#[derive(Clone)]
1752+
pub struct ProviderWorkloadAssertions {
1753+
pub jwt_svid: String,
1754+
pub launch_jwt_svid: String,
1755+
}
1756+
17501757
/// Final provider access tokens for one sandbox instance over one reused
17511758
/// gateway channel.
17521759
///
@@ -1782,19 +1789,37 @@ impl SandboxProviderTokenClient {
17821789
}
17831790
}
17841791

1785-
/// Obtain only the final access token; the gateway selects and verifies
1786-
/// the sandbox identity and resolves all grant parameters from its
1787-
/// configuration.
1792+
/// Validate the gateway before fetching a local workload assertion.
1793+
/// A plaintext endpoint must identify loopback without DNS.
1794+
///
1795+
/// # Errors
1796+
/// Returns a configuration failure for an invalid gateway URL or a
1797+
/// remote plaintext endpoint.
1798+
pub fn require_attested_transport(&self) -> std::result::Result<(), TokenGrantFailure> {
1799+
let (endpoint, _) = self.gateway.as_ref().map_err(|failure| *failure)?;
1800+
validate_attested_token_grant_transport(endpoint)
1801+
}
1802+
1803+
/// Obtain the final access token. The gateway verifies the sandbox
1804+
/// identity and resolves grant parameters from its configuration.
1805+
/// A dedicated supervisor can supply its attested JWT-SVIDs.
17881806
///
17891807
/// One deadline bounds connection readiness and the call. Network failures
17901808
/// do not serialize channel initialization for concurrent requests.
17911809
#[tracing::instrument(name = "supervisor.gateway.get_provider_access_token", skip_all)]
17921810
pub async fn get_access_token(
17931811
&self,
17941812
credential_key: &str,
1813+
assertions: Option<ProviderWorkloadAssertions>,
17951814
request_id: Option<&str>,
17961815
) -> std::result::Result<ProviderSubjectTokenExchangeResult, TokenGrantFailure> {
17971816
let (endpoint, gateway) = self.gateway.as_ref().map_err(|failure| *failure)?;
1817+
let (jwt_svid, launch_jwt_svid) = if let Some(assertions) = assertions {
1818+
self.require_attested_transport()?;
1819+
(Some(assertions.jwt_svid), Some(assertions.launch_jwt_svid))
1820+
} else {
1821+
(None, None)
1822+
};
17981823
// Like connect(), refuse locally revoked sandbox instance credentials
17991824
// before the call; the response boundary rejects them again.
18001825
let unavailable = || gateway_grant_failure(TokenGrantFailureKind::Unavailable);
@@ -1805,6 +1830,8 @@ impl SandboxProviderTokenClient {
18051830
.ok_or_else(|| gateway_grant_failure(TokenGrantFailureKind::Configuration))?;
18061831
let mut request = tonic::Request::new(crate::proto::GetSandboxProviderAccessTokenRequest {
18071832
credential_key: key,
1833+
jwt_svid,
1834+
launch_jwt_svid,
18081835
});
18091836
if let Some(value) = request_id.and_then(|value| value.parse().ok()) {
18101837
request.metadata_mut().insert("x-request-id", value);
@@ -1886,6 +1913,23 @@ pub fn token_grant_gateway_endpoint(
18861913
Ok(endpoint)
18871914
}
18881915

1916+
/// Check the transport of an authority parsed by [`token_grant_gateway_endpoint`].
1917+
/// Plain HTTP is permitted only on a numeric loopback address.
1918+
pub fn validate_attested_token_grant_transport(
1919+
endpoint: &url::Url,
1920+
) -> std::result::Result<(), TokenGrantFailure> {
1921+
let direct_loopback = match endpoint.host() {
1922+
Some(url::Host::Ipv4(address)) => address.is_loopback(),
1923+
Some(url::Host::Ipv6(address)) => address.is_loopback(),
1924+
_ => false,
1925+
};
1926+
if endpoint.scheme() == "https" || (endpoint.scheme() == "http" && direct_loopback) {
1927+
Ok(())
1928+
} else {
1929+
Err(gateway_grant_failure(TokenGrantFailureKind::Configuration))
1930+
}
1931+
}
1932+
18891933
fn provider_subject_token_exchange_result(
18901934
inner: crate::proto::ExchangeProviderSubjectTokenResponse,
18911935
) -> std::result::Result<ProviderSubjectTokenExchangeResult, TokenGrantFailure> {
@@ -1993,8 +2037,8 @@ mod token_grant_exchange_tests {
19932037
);
19942038
let started = tokio::time::Instant::now();
19952039
let results: [_; 2] = tokio::join!(
1996-
client.get_access_token("api.test\t443\t/\towner\tprovider:token", None),
1997-
client.get_access_token("api.test\t443\t/\towner\tprovider:token", None),
2040+
client.get_access_token("api.test\t443\t/\towner\tprovider:token", None, None),
2041+
client.get_access_token("api.test\t443\t/\towner\tprovider:token", None, None),
19982042
)
19992043
.into();
20002044
for result in results {
@@ -2016,10 +2060,51 @@ mod token_grant_exchange_tests {
20162060
TokenSource::Env,
20172061
),
20182062
));
2019-
let failure = invalid.get_access_token("key", None).await.err().unwrap();
2063+
let failure = invalid
2064+
.get_access_token("key", None, None)
2065+
.await
2066+
.err()
2067+
.unwrap();
20202068
assert_eq!(failure.kind(), TokenGrantFailureKind::Configuration);
20212069
}
20222070

2071+
#[tokio::test]
2072+
async fn access_token_client_keeps_assertions_off_nonlocal_plaintext() {
2073+
let client = |url| {
2074+
SandboxProviderTokenClient::new(GatewayEndpoint::new(
2075+
url,
2076+
GatewayCredentials::new(
2077+
AsciiMetadataValue::from_static("Bearer test"),
2078+
TokenSource::Env,
2079+
),
2080+
))
2081+
};
2082+
for url in ["http://192.0.2.2:8080", "http://localhost:8080"] {
2083+
let client = client(url);
2084+
let failure = client
2085+
.get_access_token(
2086+
"api.test\t443\t/\towner\tprovider:token",
2087+
Some(ProviderWorkloadAssertions {
2088+
jwt_svid: "oauth-assertion-canary".into(),
2089+
launch_jwt_svid: "launch-assertion-canary".into(),
2090+
}),
2091+
None,
2092+
)
2093+
.await
2094+
.err()
2095+
.expect("nonlocal plaintext must reject a workload assertion");
2096+
assert_eq!(failure.kind(), TokenGrantFailureKind::Configuration);
2097+
assert!(client.client.get().is_none());
2098+
}
2099+
for url in [
2100+
"https://gateway.test:8080",
2101+
"http://127.0.0.1:8080",
2102+
"http://[::1]:8080",
2103+
] {
2104+
assert!(client(url).require_attested_transport().is_ok());
2105+
}
2106+
}
2107+
20232108
#[test]
20242109
fn gateway_response_keeps_expiration_and_rejects_invalid_duration() {
20252110
let response = |seconds, nanos| crate::proto::ExchangeProviderSubjectTokenResponse {

0 commit comments

Comments
 (0)