Skip to content

Commit b336f8b

Browse files
committed
test(auth): restore sandbox bootstrap coverage
Signed-off-by: Drew Newberry <385+drew@users.noreply.github.com>
1 parent 6f1576f commit b336f8b

10 files changed

Lines changed: 366 additions & 39 deletions

File tree

‎.agents/skills/debug-openshell-cluster/SKILL.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,7 @@ kubectl -n openshell get pod -l app.kubernetes.io/name=helm-chart -o jsonpath="{
392392
```
393393

394394
Sandbox pods using provider token grants should have an
395-
`openshell.io/sandbox-id` annotation, an `openshell.ai/managed-by=openshell`
395+
`openshell.ai/sandbox-id` annotation, an `openshell.ai/managed-by=openshell`
396396
label, supervisor env vars `OPENSHELL_K8S_SA_TOKEN_FILE` and
397397
`OPENSHELL_PROVIDER_SPIFFE_WORKLOAD_API_SOCKET`, plus both the projected
398398
`openshell-sa-token` volume and the `spiffe-workload-api` CSI volume.

‎crates/openshell-driver-docker/src/lib.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1741,6 +1741,19 @@ impl DockerComputeDriver {
17411741
impl ComputeDriver for ComputeDriverService {
17421742
type WatchSandboxesStream = WatchStream;
17431743

1744+
async fn authenticate_sandbox(
1745+
&self,
1746+
request: Request<openshell_core::proto::compute::v1::AuthenticateSandboxRequest>,
1747+
) -> Result<Response<openshell_core::proto::compute::v1::AuthenticateSandboxResponse>, Status>
1748+
{
1749+
self.trace_rpc(
1750+
"driver.authenticate_sandbox",
1751+
"authenticate_sandbox",
1752+
ComputeDriver::authenticate_sandbox(&self.driver, request),
1753+
)
1754+
.await
1755+
}
1756+
17441757
async fn get_capabilities(
17451758
&self,
17461759
request: Request<GetCapabilitiesRequest>,

‎crates/openshell-driver-kubernetes/src/config.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ pub struct KubernetesComputeConfig {
303303
#[serde(default, skip_serializing_if = "Option::is_none")]
304304
pub operator_namespace_file: Option<String>,
305305
/// Kubernetes `ServiceAccount` assigned to sandbox pods and accepted by
306-
/// the gateway's `TokenReview` bootstrap authenticator.
306+
/// the driver's `TokenReview` bootstrap authenticator.
307307
pub service_account_name: String,
308308
pub default_image: String,
309309
pub image_pull_policy: String,

‎crates/openshell-driver-kubernetes/src/driver.rs‎

Lines changed: 190 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -618,11 +618,7 @@ impl KubernetesComputeDriver {
618618
.ok_or_else(|| {
619619
tonic::Status::permission_denied("authenticated sandbox pod not found")
620620
})?;
621-
if pod.metadata.uid.as_deref() != Some(identity.pod_uid.as_str()) {
622-
return Err(tonic::Status::permission_denied(
623-
"sandbox credential pod UID mismatch",
624-
));
625-
}
621+
validate_pod_uid(&pod, &identity.pod_uid)?;
626622
let sandbox_id = pod_sandbox_id(&pod)?;
627623
let owner = sandbox_owner_reference(&pod)?;
628624
let sandboxes = self
@@ -635,32 +631,12 @@ impl KubernetesComputeDriver {
635631
warn!(sandbox = %owner.name, %error, "failed to read authenticated Sandbox resource");
636632
tonic::Status::internal("failed to read authenticated Sandbox resource")
637633
})?.ok_or_else(|| tonic::Status::permission_denied("sandbox owner not found"))?;
638-
if sandbox.metadata.uid.as_deref() != Some(owner.uid.as_str())
639-
|| sandbox
640-
.metadata
641-
.labels
642-
.as_ref()
643-
.and_then(|labels| labels.get(LABEL_SANDBOX_ID))
644-
!= Some(&sandbox_id)
645-
{
646-
return Err(tonic::Status::permission_denied(
647-
"pod identity does not match its Sandbox owner",
648-
));
649-
}
634+
validate_sandbox_owner_identity(owner, &sandbox_id, &sandbox)?;
650635
Ok(sandbox_id)
651636
}
652637

653638
fn accepts_auth_namespace(&self, namespace: &str) -> bool {
654-
match self.config.workspace_mode {
655-
WorkspaceMode::Shared => namespace == self.config.namespace,
656-
WorkspaceMode::Managed => {
657-
namespace.starts_with(&managed_namespace_prefix(&self.config.gateway_id))
658-
}
659-
WorkspaceMode::Operator => self
660-
.operator_allowlist
661-
.as_ref()
662-
.is_some_and(|allowlist| allowlist.contains(namespace)),
663-
}
639+
accepts_auth_namespace(&self.config, self.operator_allowlist.as_ref(), namespace)
664640
}
665641

666642
pub fn operator_allowlist(&self) -> Option<&OperatorNamespaceAllowlist> {
@@ -2450,6 +2426,16 @@ fn pod_sandbox_id(pod: &Pod) -> Result<String, tonic::Status> {
24502426
.ok_or_else(|| tonic::Status::permission_denied("pod is not bound to a sandbox identity"))
24512427
}
24522428

2429+
#[allow(clippy::result_large_err)]
2430+
fn validate_pod_uid(pod: &Pod, expected_uid: &str) -> Result<(), tonic::Status> {
2431+
if pod.metadata.uid.as_deref() == Some(expected_uid) {
2432+
return Ok(());
2433+
}
2434+
Err(tonic::Status::permission_denied(
2435+
"sandbox credential pod UID mismatch",
2436+
))
2437+
}
2438+
24532439
#[allow(clippy::result_large_err)]
24542440
fn sandbox_owner_reference(pod: &Pod) -> Result<&OwnerReference, tonic::Status> {
24552441
let mut owners = pod
@@ -2480,6 +2466,43 @@ fn sandbox_owner_reference(pod: &Pod) -> Result<&OwnerReference, tonic::Status>
24802466
Ok(owner)
24812467
}
24822468

2469+
#[allow(clippy::result_large_err)]
2470+
fn validate_sandbox_owner_identity(
2471+
owner: &OwnerReference,
2472+
sandbox_id: &str,
2473+
sandbox: &DynamicObject,
2474+
) -> Result<(), tonic::Status> {
2475+
let uid_matches = sandbox.metadata.uid.as_deref() == Some(owner.uid.as_str());
2476+
let sandbox_id_matches = sandbox
2477+
.metadata
2478+
.labels
2479+
.as_ref()
2480+
.and_then(|labels| labels.get(LABEL_SANDBOX_ID))
2481+
.is_some_and(|actual| actual == sandbox_id);
2482+
if uid_matches && sandbox_id_matches {
2483+
return Ok(());
2484+
}
2485+
Err(tonic::Status::permission_denied(
2486+
"pod identity does not match its Sandbox owner",
2487+
))
2488+
}
2489+
2490+
fn accepts_auth_namespace(
2491+
config: &KubernetesComputeConfig,
2492+
operator_allowlist: Option<&OperatorNamespaceAllowlist>,
2493+
namespace: &str,
2494+
) -> bool {
2495+
match config.workspace_mode {
2496+
WorkspaceMode::Shared => namespace == config.namespace,
2497+
WorkspaceMode::Managed => {
2498+
namespace.starts_with(&managed_namespace_prefix(&config.gateway_id))
2499+
}
2500+
WorkspaceMode::Operator => {
2501+
operator_allowlist.is_some_and(|allowlist| allowlist.contains(namespace))
2502+
}
2503+
}
2504+
}
2505+
24832506
fn annotation_or_label(obj: &DynamicObject, key: &str) -> Option<String> {
24842507
obj.metadata
24852508
.annotations
@@ -4892,6 +4915,7 @@ mod tests {
48924915
};
48934916
use openshell_core::proto::compute::v1::{GpuResourceRequirements, ResourceRequirements};
48944917
use prost_types::{Struct, Value, value::Kind};
4918+
use std::collections::BTreeSet;
48954919

48964920
static ENV_LOCK: std::sync::LazyLock<std::sync::Mutex<()>> =
48974921
std::sync::LazyLock::new(|| std::sync::Mutex::new(()));
@@ -5139,6 +5163,145 @@ mod tests {
51395163
assert_eq!(error.code(), tonic::Code::PermissionDenied);
51405164
}
51415165

5166+
#[test]
5167+
fn token_review_rejects_wrong_audience_and_missing_pod_binding() {
5168+
let mut wrong_audience =
5169+
authenticated_token_review("system:serviceaccount:workspaces:sandbox-sa");
5170+
wrong_audience.audiences = Some(vec!["kubernetes.default.svc".to_string()]);
5171+
let error = token_review_identity(&wrong_audience, "sandbox-sa").unwrap_err();
5172+
assert_eq!(error.code(), tonic::Code::Unauthenticated);
5173+
5174+
let mut missing_binding =
5175+
authenticated_token_review("system:serviceaccount:workspaces:sandbox-sa");
5176+
missing_binding.user.as_mut().unwrap().extra = None;
5177+
let error = token_review_identity(&missing_binding, "sandbox-sa").unwrap_err();
5178+
assert_eq!(error.code(), tonic::Code::PermissionDenied);
5179+
}
5180+
5181+
#[test]
5182+
fn token_review_returns_none_when_not_authenticated() {
5183+
let status = TokenReviewStatus {
5184+
authenticated: Some(false),
5185+
error: Some("token rejected".to_string()),
5186+
..Default::default()
5187+
};
5188+
5189+
assert!(
5190+
token_review_identity(&status, "sandbox-sa")
5191+
.unwrap()
5192+
.is_none()
5193+
);
5194+
}
5195+
5196+
#[test]
5197+
fn authentication_namespace_validation_covers_each_workspace_mode() {
5198+
let mut config = KubernetesComputeConfig {
5199+
namespace: "openshell".to_string(),
5200+
..Default::default()
5201+
};
5202+
assert!(accepts_auth_namespace(&config, None, "openshell"));
5203+
assert!(!accepts_auth_namespace(&config, None, "other"));
5204+
5205+
config.workspace_mode = WorkspaceMode::Managed;
5206+
config.gateway_id = "gateway-a".to_string();
5207+
assert!(accepts_auth_namespace(
5208+
&config,
5209+
None,
5210+
"openshell-gateway-a-workspace-a"
5211+
));
5212+
assert!(!accepts_auth_namespace(
5213+
&config,
5214+
None,
5215+
"openshell-gateway-b-workspace-a"
5216+
));
5217+
5218+
config.workspace_mode = WorkspaceMode::Operator;
5219+
let allowlist = OperatorNamespaceAllowlist::from_set(BTreeSet::from([
5220+
"team-a".to_string(),
5221+
"team-b".to_string(),
5222+
]));
5223+
assert!(accepts_auth_namespace(&config, Some(&allowlist), "team-a"));
5224+
assert!(!accepts_auth_namespace(&config, Some(&allowlist), "team-c"));
5225+
assert!(!accepts_auth_namespace(&config, None, "team-a"));
5226+
}
5227+
5228+
fn sandbox_owner_for_test(name: &str, uid: &str) -> OwnerReference {
5229+
OwnerReference {
5230+
api_version: "agents.x-k8s.io/v1beta1".to_string(),
5231+
block_owner_deletion: None,
5232+
controller: Some(true),
5233+
kind: SANDBOX_KIND.to_string(),
5234+
name: name.to_string(),
5235+
uid: uid.to_string(),
5236+
}
5237+
}
5238+
5239+
fn sandbox_object_for_test(uid: &str, sandbox_id: &str) -> DynamicObject {
5240+
let resource = ApiResource::from_gvk(&GroupVersionKind::gvk(
5241+
SANDBOX_GROUP,
5242+
SANDBOX_VERSION_V1BETA1,
5243+
SANDBOX_KIND,
5244+
));
5245+
let mut sandbox = DynamicObject::new("sandbox-a", &resource);
5246+
sandbox.metadata.uid = Some(uid.to_string());
5247+
sandbox.metadata.labels = Some(BTreeMap::from([(
5248+
LABEL_SANDBOX_ID.to_string(),
5249+
sandbox_id.to_string(),
5250+
)]));
5251+
sandbox
5252+
}
5253+
5254+
#[test]
5255+
fn pod_identity_requires_matching_uid_annotation_and_controlling_owner() {
5256+
let owner = sandbox_owner_for_test("sandbox-a", "sandbox-uid-a");
5257+
let pod = Pod {
5258+
metadata: ObjectMeta {
5259+
uid: Some("pod-uid-a".to_string()),
5260+
annotations: Some(BTreeMap::from([(
5261+
LABEL_SANDBOX_ID.to_string(),
5262+
"sandbox-id-a".to_string(),
5263+
)])),
5264+
owner_references: Some(vec![owner.clone()]),
5265+
..Default::default()
5266+
},
5267+
..Default::default()
5268+
};
5269+
5270+
validate_pod_uid(&pod, "pod-uid-a").expect("matching pod UID");
5271+
assert_eq!(pod_sandbox_id(&pod).unwrap(), "sandbox-id-a");
5272+
assert_eq!(sandbox_owner_reference(&pod).unwrap(), &owner);
5273+
5274+
let error = validate_pod_uid(&pod, "other-pod-uid").unwrap_err();
5275+
assert_eq!(error.code(), tonic::Code::PermissionDenied);
5276+
5277+
let mut missing_annotation = pod.clone();
5278+
missing_annotation.metadata.annotations = None;
5279+
let error = pod_sandbox_id(&missing_annotation).unwrap_err();
5280+
assert_eq!(error.code(), tonic::Code::PermissionDenied);
5281+
5282+
let mut non_controlling = pod;
5283+
non_controlling.metadata.owner_references.as_mut().unwrap()[0].controller = Some(false);
5284+
let error = sandbox_owner_reference(&non_controlling).unwrap_err();
5285+
assert_eq!(error.code(), tonic::Code::PermissionDenied);
5286+
}
5287+
5288+
#[test]
5289+
fn sandbox_owner_identity_requires_matching_uid_and_sandbox_id() {
5290+
let owner = sandbox_owner_for_test("sandbox-a", "sandbox-uid-a");
5291+
let sandbox = sandbox_object_for_test("sandbox-uid-a", "sandbox-id-a");
5292+
validate_sandbox_owner_identity(&owner, "sandbox-id-a", &sandbox)
5293+
.expect("matching owner identity");
5294+
5295+
let wrong_uid = sandbox_object_for_test("sandbox-uid-b", "sandbox-id-a");
5296+
let error =
5297+
validate_sandbox_owner_identity(&owner, "sandbox-id-a", &wrong_uid).unwrap_err();
5298+
assert_eq!(error.code(), tonic::Code::PermissionDenied);
5299+
5300+
let wrong_id = sandbox_object_for_test("sandbox-uid-a", "sandbox-id-b");
5301+
let error = validate_sandbox_owner_identity(&owner, "sandbox-id-a", &wrong_id).unwrap_err();
5302+
assert_eq!(error.code(), tonic::Code::PermissionDenied);
5303+
}
5304+
51425305
#[test]
51435306
fn sandbox_api_version_probe_retries_on_structured_and_raw_404() {
51445307
let structured = kube_api_error(404, "could not find the requested resource");

0 commit comments

Comments
 (0)