Skip to content
Draft
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: 4 additions & 0 deletions crates/openshell-core/src/rpc_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ pub use tonic_types::{ErrorDetails, StatusExt};
/// Domain of gateway-owned machine-readable error reasons.
pub const ERROR_DOMAIN: &str = "openshell.nvidia.com";

/// Reason reported when a request carries protobuf fields or enum values the
/// gateway does not know (RFC 0027).
pub const UNKNOWN_PROTOBUF_FIELD: &str = "UNKNOWN_PROTOBUF_FIELD";

/// Reason reported when a request lost the mutation lock budget.
pub const MUTATION_LOCK_TIMEOUT: &str = "MUTATION_LOCK_TIMEOUT";

Expand Down
177 changes: 172 additions & 5 deletions crates/openshell-server/src/config_delivery/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1732,6 +1732,171 @@ mod tests {
}
}

fn policy_with_unknown_field() -> Vec<u8> {
use prost::Message as _;
let mut policy = openshell_core::proto::SandboxPolicy {
version: 1,
..Default::default()
}
.encode_to_vec();
prost::encoding::encode_varint(900 << 3, &mut policy);
prost::encoding::encode_varint(1, &mut policy);
policy
}

fn assert_not_admitted(built: Option<BuiltSandboxConfig>) {
let Some(BuiltSandboxConfig::Rejected {
sandbox_config,
error_code,
..
}) = built
else {
panic!("expected a rejected configuration");
};
assert_eq!(error_code, Code::FailedPrecondition);
assert!(!sandbox_config.configuration_admitted);
assert!(sandbox_config.policy.is_none());
}

#[tokio::test]
async fn stored_policy_revision_with_unknown_fields_is_not_admitted() {
use crate::policy_store::PolicyStoreExt as _;

let state = push_state().await;
put_sandbox(&state, "sandbox", &[]).await;
state
.store
.put_policy_revision(
&uuid::Uuid::new_v4().to_string(),
"sandbox",
"default",
1,
&policy_with_unknown_field(),
"hash",
)
.await
.unwrap();

assert_not_admitted(
build_sandbox_config(&state, "sandbox", Vec::new())
.await
.unwrap(),
);
}

#[tokio::test]
async fn sandbox_spec_policy_with_unknown_fields_is_not_admitted() {
use prost::Message as _;

let state = push_state().await;
let sandbox = Sandbox {
metadata: Some(ObjectMeta {
id: "sandbox".into(),
name: "sandbox".into(),
workspace: "default".into(),
..Default::default()
}),
spec: Some(SandboxSpec {
policy: Some(openshell_core::proto::SandboxPolicy {
version: 1,
..Default::default()
}),
..Default::default()
}),
..Default::default()
};
let payload = crate::wire_validation::sandbox_policy::splice_spec_policy(
&sandbox.encode_to_vec(),
Some(&policy_with_unknown_field()),
)
.unwrap();
state
.store
.put("sandbox", "sandbox", "sandbox", "default", &payload, None)
.await
.unwrap();

assert_not_admitted(
build_sandbox_config(&state, "sandbox", Vec::new())
.await
.unwrap(),
);
let error = crate::grpc::policy::initialize_policy_history(
state.store.as_ref(),
&state
.store
.get_message::<Sandbox>("sandbox")
.await
.unwrap()
.unwrap(),
crate::grpc::policy::InitialPolicyHistoryStatus::Pending,
)
.await
.unwrap_err();
assert_eq!(error.code(), Code::FailedPrecondition);
}

#[tokio::test]
async fn unreadable_provider_profile_rejects_only_dependent_configurations() {
use openshell_core::proto::{NetworkEndpoint, ProviderProfile};
use prost::Message as _;

// A newer endpoint restriction, and a group that legacy migration
// cannot walk: both affect only sandboxes that use the profile.
let unknown_field = {
let mut bytes = Vec::new();
prost::encoding::encode_varint(900 << 3, &mut bytes);
prost::encoding::encode_varint(1, &mut bytes);
bytes
};
let group = vec![0xa3, 0x38, 0xa4, 0x38];
for unreadable in [unknown_field, group] {
let state = push_state().await;
let mut endpoint = NetworkEndpoint {
host: "api.github.com".into(),
port: 443,
..Default::default()
}
.encode_to_vec();
endpoint.extend_from_slice(&unreadable);
let mut profile = ProviderProfile {
id: "github".into(),
..Default::default()
}
.encode_to_vec();
prost::encoding::bytes::encode(6, &endpoint, &mut profile);
let mut stored = Vec::new();
prost::encoding::bytes::encode(2, &profile, &mut stored);
state
.store
.put(
"provider_profile",
"github-profile",
"github",
"",
&stored,
None,
)
.await
.unwrap();
put_provider(&state, "gh").await;
put_sandbox(&state, "uses-profile", &["gh"]).await;
put_sandbox(&state, "unrelated", &[]).await;

assert_not_admitted(
build_sandbox_config(&state, "uses-profile", Vec::new())
.await
.unwrap(),
);
assert!(matches!(
build_sandbox_config(&state, "unrelated", Vec::new())
.await
.unwrap(),
Some(BuiltSandboxConfig::Built(..))
));
}
}

#[test]
fn fanout_marks_ten_thousand_sessions_once_each() {
let delivery = ConfigDelivery::for_db_connections(5);
Expand Down Expand Up @@ -2257,14 +2422,16 @@ mod tests {
.await
.unwrap();

let mut sandbox = state
// Compare-and-swap: the gateway concurrently records the rejection
// admission on the same sandbox, and an unconditional write could
// lose to its update.
state
.store
.get_message::<Sandbox>("large-config")
.update_message_cas::<Sandbox, _>("large-config", 0, |sandbox| {
sandbox.spec.as_mut().unwrap().providers.truncate(16);
})
.await
.unwrap()
.unwrap();
sandbox.spec.as_mut().unwrap().providers.truncate(16);
state.store.put_message(&sandbox).await.unwrap();
change_policy(&state, "large-config", 3).await;
publish_sandbox(&state, "large-config");
let recovery = sent_config(
Expand Down
5 changes: 5 additions & 0 deletions crates/openshell-server/src/grpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,11 @@ pub fn persistence_error_to_status(
format!("{operation} failed: the database is unavailable; retry the request"),
std::time::Duration::from_secs(1),
),
error @ PersistenceError::UnknownFields(_) => {
crate::wire_validation::stored::incompatible_status(&format!(
"{operation} failed: {error}"
))
}
other => Status::internal(format!("{operation} failed: {other}")),
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -718,3 +718,58 @@ async fn interactive_wire_start_is_admitted_under_its_own_method_namespace() {
drop(output);
server.abort();
}

fn with_unknown_field(mut message: Vec<u8>, tag: u64) -> Vec<u8> {
prost::encoding::encode_varint(tag << 3, &mut message);
prost::encoding::encode_varint(1, &mut message);
message
}

#[tokio::test]
async fn interactive_start_rejected_by_ingress_leaves_request_id_unused() {
use crate::grpc::OpenShellService;
use openshell_core::proto::open_shell_server::OpenShell;

let directory = tempfile::tempdir().unwrap();
let state = setup("sqlite::memory:", &directory).await;
let req = request(&state).await;
let invalid = with_unknown_field(interactive_start(req.clone()).encode_to_vec(), 900);
let stream = crate::wire_validation::ingress::validated_request_stream::<ExecSandboxInput>(
"/openshell.v1.OpenShell/ExecSandboxInteractive",
&[invalid],
);

let status = OpenShellService::new(state.clone())
.exec_sandbox_interactive(authed_request(stream))
.await
.unwrap_err();

assert_eq!(status.code(), tonic::Code::InvalidArgument);
assert_eq!(reason(&status), rpc_error::UNKNOWN_PROTOBUF_FIELD);
assert!(
state
.store
.list_by_type_after(OBJECT_TYPE, None, 100)
.await
.unwrap()
.is_empty(),
"a rejected start frame writes no admission record"
);

// The same request_id still admits a valid start.
let mut messages = register(&state, &sandbox_id(&state, &req).await);
let (mut client, server) = wire_client(state.clone(), None, None).await;
let output = exec_rpc(&mut client, req, true).await.unwrap();
receive_relay(&state, &mut messages).await;
assert_eq!(
state
.store
.list_by_type_after(OBJECT_TYPE, None, 100)
.await
.unwrap()
.len(),
1
);
drop(output);
server.abort();
}
Loading
Loading