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
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
95 changes: 95 additions & 0 deletions crates/openshell-core/src/oauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,42 @@ pub fn effective_token_type(token_type: &str) -> &str {
}
}

/// The supervisor requests this JWT-SVID audience and the gateway verifies the
/// same value, so both sides must derive it here.
pub fn effective_jwt_svid_audience(token_endpoint: &str, jwt_svid_audience: &str) -> String {
if jwt_svid_audience.trim().is_empty() {
derive_issuer_from_token_endpoint(token_endpoint)
} else {
jwt_svid_audience.to_string()
}
}

/// Derive the issuer/realm URL from a token endpoint URL.
///
/// For Keycloak token endpoints like:
/// `https://auth.example.com/realms/openshell/protocol/openid-connect/token`
/// Returns:
/// `https://auth.example.com/realms/openshell`
///
/// This is used as the JWT-SVID audience claim when authenticating to the
/// authorization server via JWT client assertion (RFC 7523).
fn derive_issuer_from_token_endpoint(token_endpoint: &str) -> String {
// For Keycloak, strip everything after /realms/{realm-name}
if let Some(realms_idx) = token_endpoint.find("/realms/") {
// Find the next path segment after the realm name
let after_realms = &token_endpoint[realms_idx + "/realms/".len()..];
if let Some(slash_idx) = after_realms.find('/') {
// Return everything up to (but not including) the next slash
let realm_end = realms_idx + "/realms/".len() + slash_idx;
return token_endpoint[..realm_end].to_string();
}
}

// Fallback: if we can't parse it, use the full token endpoint
// This works for some OAuth2 servers that accept the token endpoint as aud
token_endpoint.to_string()
}

/// Cache lifetime for a granted access token.
///
/// A configured override is used exactly, including zero to disable caching.
Expand Down Expand Up @@ -987,6 +1023,65 @@ mod tests {
assert_eq!(request.request_id, None);
}

#[test]
fn jwt_svid_audience_is_the_configured_value_or_the_derived_issuer() {
const OPENSHELL_REALM: &str =
"https://auth.example.com/realms/openshell/protocol/openid-connect/token";
const SHORT_REALM: &str = "https://kc.example/realms/a/protocol/openid-connect/token";

for (case, token_endpoint, issuer) in [
(
"keycloak realm",
OPENSHELL_REALM,
"https://auth.example.com/realms/openshell",
),
(
"another keycloak realm",
"https://auth.example.com/realms/production/protocol/openid-connect/token",
"https://auth.example.com/realms/production",
),
// Fallback: returns the full token endpoint
(
"non-keycloak fallback",
"https://oauth.example.com/token",
"https://oauth.example.com/token",
),
] {
assert_eq!(
derive_issuer_from_token_endpoint(token_endpoint),
issuer,
"{case}"
);
}

for (case, token_endpoint, configured, audience) in [
(
"explicit override",
OPENSHELL_REALM,
"spiffe://custom-audience",
"spiffe://custom-audience",
),
(
"empty value",
SHORT_REALM,
"",
"https://kc.example/realms/a",
),
(
"blank value",
SHORT_REALM,
" ",
"https://kc.example/realms/a",
),
] {
assert_eq!(
effective_jwt_svid_audience(token_endpoint, configured),
audience,
"{case}"
);
}
}

#[test]
fn token_endpoint_url_allows_https_loopback_and_in_cluster_http() {
for endpoint in [
Expand Down
28 changes: 28 additions & 0 deletions crates/openshell-core/src/proto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,20 @@ pub use openshell::*;
pub use sandbox::v1::*;
pub use test::ObjectForTest;

impl std::fmt::Debug for GetSandboxProviderAccessTokenRequest {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("GetSandboxProviderAccessTokenRequest")
.field("credential_key", &self.credential_key)
.field("jwt_svid", &self.jwt_svid.as_ref().map(|_| "[REDACTED]"))
.field(
"launch_jwt_svid",
&self.launch_jwt_svid.as_ref().map(|_| "[REDACTED]"),
)
.finish()
}
}

impl SandboxPolicy {
/// Returns whether the explicitly present Cedar message selects the Cedar engine.
#[must_use]
Expand Down Expand Up @@ -134,6 +148,20 @@ mod tests {

use super::SandboxPolicy;

#[test]
fn provider_access_token_request_debug_redacts_the_assertion() {
let request = super::GetSandboxProviderAccessTokenRequest {
credential_key: "configured-key".into(),
jwt_svid: Some("oauth-assertion-canary".into()),
launch_jwt_svid: Some("launch-assertion-canary".into()),
};
let output = format!("{request:?}");
assert!(output.contains("configured-key"));
assert!(output.contains("[REDACTED]"));
assert!(!output.contains("oauth-assertion-canary"));
assert!(!output.contains("launch-assertion-canary"));
}

#[test]
fn empty_cedar_message_preserves_format_and_policy_identity() {
let yaml = SandboxPolicy::default();
Expand Down
6 changes: 6 additions & 0 deletions crates/openshell-core/src/sandbox_generation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ impl SandboxGenerationId {
&self.0
}

/// Audience requested for the JWT-SVID that accompanies the OAuth assertion.
#[must_use]
pub fn provider_spiffe_audience(&self) -> String {
format!("urn:openshell:provider-grants:launch:{self}")
}

#[must_use]
pub fn into_string(self) -> String {
self.0
Expand Down
8 changes: 8 additions & 0 deletions crates/openshell-gateway-interceptors/src/proto_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,14 @@ mod tests {
"openshell.v1.GetSandboxProviderEnvironmentResponse",
"environment",
),
(
"openshell.v1.GetSandboxProviderAccessTokenRequest",
"jwt_svid",
),
(
"openshell.v1.GetSandboxProviderAccessTokenRequest",
"launch_jwt_svid",
),
] {
let message = codec.message_descriptor(message_name).unwrap();
let field = message.get_field_by_name(field_name).unwrap();
Expand Down
2 changes: 2 additions & 0 deletions crates/openshell-server/src/grpc/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6568,6 +6568,8 @@ pub(super) mod tests {
let mut request = Request::new(
openshell_core::proto::GetSandboxProviderAccessTokenRequest {
credential_key: SECRET.to_string(),
jwt_svid: None,
launch_jwt_svid: None,
},
);
request
Expand Down
2 changes: 2 additions & 0 deletions crates/openshell-server/src/grpc/provider/access_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,8 @@ mod tests {
] {
let mut request = Request::new(GetSandboxProviderAccessTokenRequest {
credential_key: "untrusted".into(),
jwt_svid: None,
launch_jwt_svid: None,
});
request.extensions_mut().insert(principal);
let error = handle(&state, request).await.unwrap_err();
Expand Down
4 changes: 3 additions & 1 deletion crates/openshell-server/src/storage_proto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,10 @@ mod tests {
// and the public/durable overlap remain unchanged.
// The service backend HTTP version is part of both schemas. Legacy
// endpoint records omit it and continue to use HTTP/1.1.
// Provider access token requests accept two optional supervisor SVIDs.
// The fields are public-only and older requests still omit them.
const PUBLIC_RPC_SCHEMA_SHA256: &str =
"edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a";
"7e0830b5850c3fde8deb4ae9b1ff05c83a52bf9b8615e5a0c5020ee86e3727fb";
// The storage.v2 refresh root adds retired handles and the first mint's
// provider revision. All fields from the prior root retain their wire tags.
const DURABLE_SCHEMA_SHA256: &str =
Expand Down
Loading
Loading