From 90dbe5454bb87b2b1adc47e1147e0b8aed02d260 Mon Sep 17 00:00:00 2001 From: Mrunal Patel Date: Thu, 10 Sep 2026 20:38:50 +0000 Subject: [PATCH 01/12] feat(api): add typed workspace selectors (#3245) * feat(api)!: add typed workspace selectors Signed-off-by: Mrunal Patel * fix(cli): preserve template workspace metadata Signed-off-by: Mrunal Patel * test(e2e): migrate workspace request selectors Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com> * test(api): update public schema inventory Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com> --------- Signed-off-by: Mrunal Patel Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com> Co-authored-by: John Myers <9696606+johntmyers@users.noreply.github.com> --- .agents/skills/tui-development/SKILL.md | 34 +- architecture/gateway.md | 14 +- crates/openshell-cli/src/commands/provider.rs | 50 +- crates/openshell-cli/src/completers.rs | 10 +- crates/openshell-cli/src/run.rs | 123 +- crates/openshell-cli/src/ssh.rs | 2 +- .../tests/provider_commands_integration.rs | 2 +- .../sandbox_create_lifecycle_integration.rs | 39 +- crates/openshell-core/src/grpc_client.rs | 5 +- crates/openshell-core/src/proto/mod.rs | 16 + .../src/proto_json.rs | 8 +- .../src/runtime.rs | 5 +- crates/openshell-sdk/README.md | 5 + crates/openshell-sdk/src/client.rs | 78 +- crates/openshell-sdk/src/types.rs | 2 - crates/openshell-sdk/tests/client_mock.rs | 107 +- .../src/auth/workspace_authz.rs | 151 +- crates/openshell-server/src/grpc/policy.rs | 531 ++++-- crates/openshell-server/src/grpc/provider.rs | 368 +++-- crates/openshell-server/src/grpc/sandbox.rs | 348 ++-- crates/openshell-server/src/grpc/service.rs | 222 +-- crates/openshell-server/src/grpc/workspace.rs | 2 +- crates/openshell-server/src/multiplex.rs | 10 +- crates/openshell-server/src/storage_proto.rs | 4 +- crates/openshell-tui/src/lib.rs | 81 +- docs/sandboxes/manage-workspaces.mdx | 28 +- e2e/python/oidc/oidc_auth_test.py | 59 +- e2e/python/oidc/workspace_authz_test.py | 204 ++- e2e/python/test_policy_validation.py | 29 +- e2e/python/test_sandbox_providers.py | 76 +- examples/governance-interceptor/src/main.rs | 4 +- .../src/smoke_client.rs | 1 + proto/datamodel.proto | 20 + proto/openshell.proto | 247 ++- python/openshell/sandbox.py | 48 +- python/openshell/sandbox_test.py | 67 +- rfc/0011-multi-player-design/README.md | 42 +- sdk/go/docs/src/api/providers.md | 3 + sdk/go/docs/src/api/sandbox-templates.md | 4 +- sdk/go/docs/src/api/sandboxes.md | 3 + sdk/go/docs/src/api/services.md | 3 + sdk/go/openshell/v1/config_client.go | 4 +- sdk/go/openshell/v1/exec_client_test.go | 3 + sdk/go/openshell/v1/fake/provider.go | 12 +- sdk/go/openshell/v1/fake/sandbox.go | 12 +- sdk/go/openshell/v1/fake/sandbox_template.go | 10 +- .../v1/fake/sandbox_template_test.go | 2 +- sdk/go/openshell/v1/fake/service.go | 8 + sdk/go/openshell/v1/policy_client.go | 76 +- sdk/go/openshell/v1/policy_client_test.go | 14 +- sdk/go/openshell/v1/provider.go | 1 + sdk/go/openshell/v1/provider_client.go | 27 +- sdk/go/openshell/v1/refresh_client.go | 20 +- sdk/go/openshell/v1/sandbox.go | 1 + sdk/go/openshell/v1/sandbox_client.go | 55 +- sdk/go/openshell/v1/sandbox_template.go | 1 + .../openshell/v1/sandbox_template_client.go | 26 +- .../v1/sandbox_template_client_test.go | 14 +- sdk/go/openshell/v1/service.go | 1 + sdk/go/openshell/v1/service_client.go | 35 +- sdk/go/openshell/v1/service_client_test.go | 16 + sdk/go/openshell/v1/ssh_client_test.go | 3 + sdk/go/openshell/v1/tcp_client_test.go | 3 + sdk/go/openshell/v1/types/options.go | 1 - sdk/go/openshell/v1/workspace_scope.go | 18 + sdk/go/proto/datamodelv1/datamodel.pb.go | 237 ++- sdk/go/proto/openshellv1/openshell.pb.go | 1467 +++++++++-------- sdk/typescript/README.md | 18 +- sdk/typescript/src/client.test.ts | 116 +- sdk/typescript/src/client.ts | 78 +- sdk/typescript/src/index.ts | 1 + 71 files changed, 3336 insertions(+), 1999 deletions(-) create mode 100644 sdk/go/openshell/v1/workspace_scope.go diff --git a/.agents/skills/tui-development/SKILL.md b/.agents/skills/tui-development/SKILL.md index 5abc534f77..edd1397d56 100644 --- a/.agents/skills/tui-development/SKILL.md +++ b/.agents/skills/tui-development/SKILL.md @@ -469,14 +469,20 @@ Proto types come from `openshell-core` which generates them from `OUT_DIR` via ` ```rust use openshell_core::proto::openshell_client::OpenShellClient; -use openshell_core::proto::{ListSandboxesRequest, GetSandboxLogsRequest, ...}; +use openshell_core::proto::{ + all_workspaces_selector, workspace_selector, GetSandboxLogsRequest, + ListSandboxesRequest, ... +}; ``` ### Proto field gotchas - `DeleteSandboxRequest` uses the `name` field (not `id`): ```rust - let req = openshell_core::proto::DeleteSandboxRequest { name: sandbox_name }; + let req = openshell_core::proto::DeleteSandboxRequest { + name: sandbox_name, + workspace_scope: Some(workspace_selector(workspace)), + }; ``` - `WatchSandboxRequest` has extra fields beyond what you might need — always use `..Default::default()`: ```rust @@ -490,12 +496,24 @@ use openshell_core::proto::{ListSandboxesRequest, GetSandboxLogsRequest, ...}; }; ``` - `SandboxLogLine` proto fields: `sandbox_id`, `timestamp_ms`, `level`, `target`, `message`, `source`, `fields` (HashMap). -- `GetSandboxLogsRequest` fields: `sandbox_id`, `lines` (u32), `since_ms` (i64), `sources` (Vec), `min_level` (String), `workspace` (String). -- `ListSandboxesRequest` fields: `limit` (i64), `offset` (i64), `label_selector` (String), `workspace` (String), `all_workspaces` (bool). -- `ListProvidersRequest` fields: `limit` (i64), `offset` (i64), `workspace` (String), `all_workspaces` (bool). -- `ListWorkspacesRequest` fields: `limit` (i64), `offset` (i64), `label_selector` (String). -- `UpdateConfigRequest` fields: `name` (String, sandbox name or empty for global), `setting_key`, `setting_value`, `delete_setting` (bool), `global` (bool), `workspace`. -- Most resource requests include a `workspace` field that scopes the operation to the current workspace. +- Workspace-scoped request fields use `workspace_scope: Option`. + Select one workspace with `Some(workspace_selector(name))`. List requests that + explicitly support cross-workspace access also accept + `Some(all_workspaces_selector())`; do not use that marker on other requests. +- `GetSandboxLogsRequest` fields: `sandbox_id`, `lines` (u32), `since_ms` (i64), + `sources` (Vec), `min_level` (String), `workspace_scope`. +- `ListSandboxesRequest` fields: `limit` (u32), `offset` (u32), + `label_selector` (String), `workspace_scope`. +- `ListProvidersRequest` fields: `limit` (u32), `offset` (u32), + `workspace_scope`. +- `ListWorkspacesRequest` fields: `limit` (u32), `offset` (u32), + `label_selector` (String). +- `UpdateConfigRequest` fields include `name` (String, sandbox name or empty for + global), `setting_key`, `setting_value`, `delete_setting` (bool), `global` + (bool), and `workspace_scope`. Sandbox-scoped updates require a named selector; + gateway-global updates must leave `workspace_scope` as `None`. +- Most resource requests require an explicit named `workspace_scope`, including + the `default` workspace. An omitted selector is not an implicit default. ### gRPC timeouts diff --git a/architecture/gateway.md b/architecture/gateway.md index 2fbd46533e..59b2bd52ed 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -54,6 +54,16 @@ health, metrics, or tunnel routes. The plaintext service router also rejects browser requests whose Fetch Metadata, Origin, or Referer headers indicate a cross-origin or sibling-subdomain request. +Public workspace-scoped RPCs carry a typed `WorkspaceSelector`. A request must +select one non-empty workspace explicitly; `default` is an ordinary explicit +name, not an omitted-value fallback. Sandbox, sandbox template, provider, and +service list RPCs also accept an all-workspaces marker after Platform Admin +authorization. Single-workspace handlers reject that marker. Platform-global +policy operations require the selector to be absent, while workspace policy +operations require it. The gateway authorizes the selected scope before +performing resource lookup so malformed, unsupported, and unauthorized scopes +have consistent behavior across resource types. + Docker and Podman report the local address through which their sandboxes can reach the gateway. When the primary listener covers that address, the gateway reuses it; sandbox JWT authentication and its RPC allowlist remain the callback @@ -318,8 +328,8 @@ public descriptor set generated by `openshell-core`; a fingerprint test in Compute-driver, credential-driver, gateway-interceptor, and supervisor-middleware services are compiled contracts for internal extension boundaries, not public gateway RPCs. The current public inventory has 74 -methods, 276 messages, and 12 enums -(`042034fe4d0000279ee4ed27e587ab8e530934b8d5c3aa36dc9769f81dfa6e51`). +methods, 278 messages, and 12 enums +(`c95ae90962c10fb28747db2b645adf4044562a3d208d84dfe4699d677e4364ee`). Storage-only messages live in the private, versioned `openshell.storage.v1` package under `crates/openshell-server/proto`. The server diff --git a/crates/openshell-cli/src/commands/provider.rs b/crates/openshell-cli/src/commands/provider.rs index c903156af0..e966eb690e 100644 --- a/crates/openshell-cli/src/commands/provider.rs +++ b/crates/openshell-cli/src/commands/provider.rs @@ -59,7 +59,7 @@ pub async fn sandbox_provider_list( let response = client .list_sandbox_providers(ListSandboxProvidersRequest { sandbox_name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -91,7 +91,7 @@ pub async fn sandbox_provider_attach( let sandbox = client .get_sandbox(GetSandboxRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -106,7 +106,7 @@ pub async fn sandbox_provider_attach( sandbox_name: name.to_string(), provider_name: provider.to_string(), expected_resource_version: resource_version, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await { @@ -147,7 +147,7 @@ pub async fn sandbox_provider_detach( let sandbox = client .get_sandbox(GetSandboxRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -162,7 +162,7 @@ pub async fn sandbox_provider_detach( sandbox_name: name.to_string(), provider_name: provider.to_string(), expected_resource_version: resource_version, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await { @@ -305,8 +305,7 @@ pub async fn ensure_required_providers( .list_providers(ListProvidersRequest { limit, offset, - workspace: workspace.to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -490,7 +489,7 @@ async fn auto_create_provider( profile_workspace: workspace.to_string(), credential_handles: HashMap::new(), }), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }; let response = client.create_provider(request).await.map_err(|status| { @@ -538,7 +537,7 @@ async fn auto_create_provider( profile_workspace: workspace.to_string(), credential_handles: HashMap::new(), }), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }; match client.create_provider(request).await { @@ -672,7 +671,7 @@ async fn rollback_provider_create_after_gcloud_adc_failure( match client .delete_provider(DeleteProviderRequest { name: provider_name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await { @@ -1119,7 +1118,7 @@ pub async fn provider_create_with_options(options: ProviderCreateOptions<'_>) -> profile_workspace: profile_workspace.to_string(), credential_handles: HashMap::new(), }), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -1149,7 +1148,7 @@ pub async fn provider_create_with_options(options: ProviderCreateOptions<'_>) -> "refresh_token".to_string(), ], expires_at_ms: None, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await { @@ -1167,7 +1166,7 @@ pub async fn provider_create_with_options(options: ProviderCreateOptions<'_>) -> .rotate_provider_credential(RotateProviderCredentialRequest { provider: provider_name.clone(), credential_key: adc_credential_key, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await { @@ -1208,7 +1207,7 @@ pub async fn provider_get( let response = client .get_provider(GetProviderRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -1339,12 +1338,11 @@ pub async fn provider_list( .list_providers(ListProvidersRequest { limit, offset, - workspace: if all_workspaces { - String::new() + workspace_scope: Some(if all_workspaces { + openshell_core::proto::all_workspaces_selector() } else { - workspace.to_string() - }, - all_workspaces, + openshell_core::proto::workspace_selector(workspace) + }), }) .await .into_diagnostic()?; @@ -1713,7 +1711,7 @@ pub async fn provider_refresh_status( .get_provider_refresh_status(GetProviderRefreshStatusRequest { provider: name.to_string(), credential_key: credential_key.unwrap_or_default().to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -1794,7 +1792,7 @@ pub async fn provider_refresh_config( material, secret_material_keys, expires_at_ms: input.credential_expires_at_ms, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -1823,7 +1821,7 @@ pub async fn provider_rotate( .rotate_provider_credential(RotateProviderCredentialRequest { provider: name.to_string(), credential_key: credential_key.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -1860,7 +1858,7 @@ pub async fn provider_refresh_delete( .delete_provider_refresh(DeleteProviderRefreshRequest { provider: name.to_string(), credential_key: credential_key.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -2236,7 +2234,7 @@ pub async fn provider_update(options: ProviderUpdateOptions<'_>) -> Result<()> { let existing = match client .get_provider(GetProviderRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await { @@ -2319,7 +2317,7 @@ pub async fn provider_update(options: ProviderUpdateOptions<'_>) -> Result<()> { credential_handles: HashMap::new(), }), credential_expires_at_ms, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -2349,7 +2347,7 @@ pub async fn provider_delete( let response = match client .delete_provider(DeleteProviderRequest { name: name.clone(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await { diff --git a/crates/openshell-cli/src/completers.rs b/crates/openshell-cli/src/completers.rs index 9d3b88d594..0778babbf1 100644 --- a/crates/openshell-cli/src/completers.rs +++ b/crates/openshell-cli/src/completers.rs @@ -39,8 +39,9 @@ pub fn complete_sandbox_names(_prefix: &OsStr) -> Vec { limit: 200, offset: 0, label_selector: String::new(), - workspace: workspace_from_args(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + workspace_from_args(), + )), }) .await .ok()?; @@ -64,8 +65,9 @@ pub fn complete_provider_names(_prefix: &OsStr) -> Vec { .list_providers(ListProvidersRequest { limit: 200, offset: 0, - workspace: workspace_from_args(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + workspace_from_args(), + )), }) .await .ok()?; diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index fbad0d505f..3421f0f871 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -643,7 +643,7 @@ pub async fn sandbox_create( name: name.unwrap_or_default().to_string(), labels, annotations, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), await_main_process_attachment, workload_template_name: template.unwrap_or_default().to_string(), }; @@ -689,7 +689,7 @@ pub async fn sandbox_create( name: sandbox_name.clone(), setting_key: settings::PROPOSAL_APPROVAL_MODE_KEY.to_string(), setting_value: Some(setting), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), ..Default::default() }) .await @@ -1307,7 +1307,7 @@ async fn stage_rootfs_tar( // archive over its configured limit, before allocating anything. let slot = client .begin_rootfs_tar_staging(BeginRootfsTarStagingRequest { - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), file_name, size_bytes: source_meta.len(), }) @@ -1495,7 +1495,7 @@ pub async fn sandbox_get( let response = client .get_sandbox(GetSandboxRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -1657,7 +1657,7 @@ pub async fn sandbox_exec_grpc( let sandbox = client .get_sandbox(GetSandboxRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -1891,7 +1891,7 @@ async fn fetch_ready_sandbox_for_forward( let response = match client .get_sandbox(GetSandboxRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await { @@ -2249,12 +2249,11 @@ pub async fn sandbox_list( limit, offset, label_selector: label_selector.unwrap_or("").to_string(), - workspace: if all_workspaces { - String::new() + workspace_scope: Some(if all_workspaces { + openshell_core::proto::all_workspaces_selector() } else { - workspace.to_string() - }, - all_workspaces, + openshell_core::proto::workspace_selector(workspace) + }), }) .await .into_diagnostic()?; @@ -2490,7 +2489,7 @@ pub async fn sandbox_template_create( labels, resource_version: 0, annotations, - workspace: String::new(), + workspace: workspace.to_string(), deletion_timestamp_ms: 0, }), spec: Some(SandboxWorkloadTemplateSpec { @@ -2503,7 +2502,7 @@ pub async fn sandbox_template_create( desired_service_level, }), }), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -2568,7 +2567,7 @@ pub async fn sandbox_template_get( let response = client .get_sandbox_template(GetSandboxTemplateRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -2602,12 +2601,11 @@ pub async fn sandbox_template_list( .list_sandbox_templates(ListSandboxTemplatesRequest { limit, offset, - workspace: if all_workspaces { - String::new() + workspace_scope: Some(if all_workspaces { + openshell_core::proto::all_workspaces_selector() } else { - workspace.to_string() - }, - all_workspaces, + openshell_core::proto::workspace_selector(workspace) + }), label_selector: label_selector.unwrap_or_default().to_string(), }) .await @@ -2651,7 +2649,7 @@ pub async fn sandbox_template_delete( let response = client .delete_sandbox_template(DeleteSandboxTemplateRequest { name: name.clone(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -3036,8 +3034,7 @@ pub async fn sandbox_delete( limit: 1000, offset: 0, label_selector: String::new(), - workspace: workspace.to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -3069,7 +3066,7 @@ pub async fn sandbox_delete( let response = match client .delete_sandbox(DeleteSandboxRequest { name: name.clone(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await { @@ -3121,7 +3118,7 @@ pub async fn sandbox_stop( let sandbox = client .stop_sandbox(StopSandboxRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -3144,7 +3141,7 @@ pub async fn sandbox_start( let sandbox = client .start_sandbox(StartSandboxRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -3245,7 +3242,7 @@ pub async fn service_expose( service: service.to_string(), target_port: u32::from(target_port), domain: true, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .map_err(service_expose_status_error)? @@ -3295,12 +3292,11 @@ pub async fn service_list( sandbox: sandbox.unwrap_or_default().to_string(), limit, offset, - workspace: if all_workspaces { - String::new() + workspace_scope: Some(if all_workspaces { + openshell_core::proto::all_workspaces_selector() } else { - workspace.to_string() - }, - all_workspaces, + openshell_core::proto::workspace_selector(workspace) + }), }) .await .map_err(|status| service_status_error("list services", "sandbox:read", status))? @@ -3340,7 +3336,7 @@ pub async fn service_get( .get_service(GetServiceRequest { sandbox: sandbox.to_string(), service: service.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .map_err(|status| service_status_error("get service", "sandbox:read", status))? @@ -3362,7 +3358,7 @@ pub async fn service_delete( .delete_service(DeleteServiceRequest { sandbox: sandbox.to_string(), service: service.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .map_err(|status| service_status_error("delete service", "sandbox:write", status))? @@ -4139,7 +4135,7 @@ pub async fn sandbox_policy_set_global( yes: bool, wait: bool, _timeout_secs: u64, - workspace: &str, + _workspace: &str, tls: &TlsOptions, ) -> Result<()> { if wait { @@ -4159,7 +4155,6 @@ pub async fn sandbox_policy_set_global( name: String::new(), policy: Some(policy), global: true, - workspace: workspace.to_string(), ..Default::default() }) .await @@ -4190,7 +4185,7 @@ pub async fn sandbox_settings_get( let sandbox = client .get_sandbox(GetSandboxRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -4348,7 +4343,7 @@ pub async fn gateway_setting_set( key: &str, value: &str, yes: bool, - workspace: &str, + _workspace: &str, tls: &TlsOptions, ) -> Result<()> { let setting_value = parse_cli_setting_value(key, value)?; @@ -4361,7 +4356,6 @@ pub async fn gateway_setting_set( setting_key: key.to_string(), setting_value: Some(setting_value), global: true, - workspace: workspace.to_string(), ..Default::default() }) .await @@ -4394,7 +4388,7 @@ pub async fn sandbox_setting_set( name: name.to_string(), setting_key: key.to_string(), setting_value: Some(setting_value), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), ..Default::default() }) .await @@ -4416,7 +4410,7 @@ pub async fn gateway_setting_delete( server: &str, key: &str, yes: bool, - workspace: &str, + _workspace: &str, tls: &TlsOptions, ) -> Result<()> { confirm_global_setting_delete(key, yes)?; @@ -4428,7 +4422,6 @@ pub async fn gateway_setting_delete( setting_key: key.to_string(), delete_setting: true, global: true, - workspace: workspace.to_string(), ..Default::default() }) .await @@ -4461,7 +4454,7 @@ pub async fn sandbox_setting_delete( name: name.to_string(), setting_key: key.to_string(), delete_setting: true, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), ..Default::default() }) .await @@ -4507,7 +4500,7 @@ pub async fn sandbox_policy_set( name: name.to_string(), version: 0, global: false, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .ok() @@ -4518,7 +4511,7 @@ pub async fn sandbox_policy_set( .update_config(UpdateConfigRequest { name: name.to_string(), policy: Some(policy), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), ..Default::default() }) .await @@ -4566,7 +4559,7 @@ pub async fn sandbox_policy_set( name: name.to_string(), version: resp.version, global: false, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -4643,7 +4636,7 @@ pub async fn sandbox_policy_update( let sandbox = client .get_sandbox(GetSandboxRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -4692,7 +4685,7 @@ pub async fn sandbox_policy_update( .update_config(UpdateConfigRequest { name: name.to_string(), merge_operations: plan.merge_operations, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), ..Default::default() }) .await @@ -4740,7 +4733,7 @@ pub async fn sandbox_policy_update( name: name.to_string(), version: response.version, global: false, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -4848,7 +4841,7 @@ where name: name.to_string(), version, global: false, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -4930,7 +4923,7 @@ where let sandbox = client .get_sandbox(GetSandboxRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -5032,7 +5025,7 @@ pub async fn sandbox_policy_get_global( version: u32, view: PolicyGetView, output: &str, - workspace: &str, + _workspace: &str, tls: &TlsOptions, ) -> Result<()> { let mut client = grpc_client(server, tls).await?; @@ -5042,7 +5035,7 @@ pub async fn sandbox_policy_get_global( name: String::new(), version, global: true, - workspace: workspace.to_string(), + workspace_scope: None, }) .await .into_diagnostic()?; @@ -5183,7 +5176,7 @@ pub async fn sandbox_policy_list( limit, offset: 0, global: false, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -5207,7 +5200,7 @@ pub async fn sandbox_policy_list_global( server: &str, limit: u32, output: &str, - workspace: &str, + _workspace: &str, tls: &TlsOptions, ) -> Result<()> { let mut client = grpc_client(server, tls).await?; @@ -5218,7 +5211,7 @@ pub async fn sandbox_policy_list_global( limit, offset: 0, global: true, - workspace: workspace.to_string(), + workspace_scope: None, }) .await .into_diagnostic()?; @@ -5310,7 +5303,7 @@ pub async fn sandbox_logs( let sandbox = client .get_sandbox(GetSandboxRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -5375,7 +5368,7 @@ pub async fn sandbox_logs( since_ms, sources: source_filter, min_level: level.to_uppercase(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -5451,7 +5444,7 @@ pub async fn sandbox_draft_get( .get_draft_policy(GetDraftPolicyRequest { name: name.to_string(), status_filter: status_filter.unwrap_or("").to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -5559,7 +5552,7 @@ pub async fn sandbox_draft_approve( .get_draft_policy(GetDraftPolicyRequest { name: name.to_string(), status_filter: String::new(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -5574,7 +5567,7 @@ pub async fn sandbox_draft_approve( .approve_draft_chunk(ApproveDraftChunkRequest { name: name.to_string(), chunk_id: chunk_id.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), review_token, }) .await @@ -5607,7 +5600,7 @@ pub async fn sandbox_draft_reject( name: name.to_string(), chunk_id: chunk_id.to_string(), reason: reason.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -5630,7 +5623,7 @@ pub async fn sandbox_draft_approve_all( .get_draft_policy(GetDraftPolicyRequest { name: name.to_string(), status_filter: "pending".to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? @@ -5647,7 +5640,7 @@ pub async fn sandbox_draft_approve_all( .approve_all_draft_chunks(ApproveAllDraftChunksRequest { name: name.to_string(), include_security_flagged, - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), approvals, }) .await @@ -5677,7 +5670,7 @@ pub async fn sandbox_draft_clear( let response = client .clear_draft_chunks(ClearDraftChunksRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; @@ -5704,7 +5697,7 @@ pub async fn sandbox_draft_history( let response = client .get_draft_history(GetDraftHistoryRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; diff --git a/crates/openshell-cli/src/ssh.rs b/crates/openshell-cli/src/ssh.rs index 126cea652d..c0937db484 100644 --- a/crates/openshell-cli/src/ssh.rs +++ b/crates/openshell-cli/src/ssh.rs @@ -92,7 +92,7 @@ async fn ssh_session_config( let sandbox = client .get_sandbox(GetSandboxRequest { name: name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()? diff --git a/crates/openshell-cli/tests/provider_commands_integration.rs b/crates/openshell-cli/tests/provider_commands_integration.rs index 2d1b3f25d3..912835faa3 100644 --- a/crates/openshell-cli/tests/provider_commands_integration.rs +++ b/crates/openshell-cli/tests/provider_commands_integration.rs @@ -2920,7 +2920,7 @@ async fn provider_create_supports_nvidia_type_with_nvidia_api_key() { let response = client .get_provider(GetProviderRequest { name: "my-nvidia".to_string(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }) .await .expect("get provider should succeed") diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index d9e3cdad98..6ed9a74339 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -43,6 +43,19 @@ use tokio_stream::wrappers::TcpListenerStream; use tonic::transport::{Certificate as TlsCertificate, Identity, Server, ServerTlsConfig}; use tonic::{Response, Status}; +fn selected_workspace( + scope: &Option, +) -> Option<&str> { + match scope.as_ref()?.selection.as_ref()? { + openshell_core::proto::datamodel::v1::workspace_selector::Selection::Workspace( + workspace, + ) => Some(workspace), + openshell_core::proto::datamodel::v1::workspace_selector::Selection::AllWorkspaces(_) => { + None + } + } +} + #[derive(Clone, Default)] struct SandboxState { deleted_names: Arc>>>, @@ -217,7 +230,9 @@ impl OpenShell for TestOpenShell { .unwrap_or_default(), resource_version: 1, annotations: HashMap::new(), - workspace: request.workspace.clone(), + workspace: selected_workspace(&request.workspace_scope) + .unwrap_or("default") + .to_string(), deletion_timestamp_ms: 0, }); self.state @@ -249,7 +264,9 @@ impl OpenShell for TestOpenShell { labels: HashMap::new(), resource_version: 1, annotations: HashMap::new(), - workspace: request.workspace, + workspace: selected_workspace(&request.workspace_scope) + .unwrap_or("default") + .to_string(), deletion_timestamp_ms: 0, }), spec: None, @@ -1774,7 +1791,7 @@ async fn sandbox_create_with_template_sends_workload_template_name() { } #[tokio::test] -async fn sandbox_template_create_sends_workload_template_resource() { +async fn sandbox_template_create_sends_non_default_workspace_in_scope_and_metadata() { let server = run_server().await; let fake_ssh_dir = tempfile::tempdir().unwrap(); let xdg_dir = tempfile::tempdir().unwrap(); @@ -1795,7 +1812,7 @@ async fn sandbox_template_create_sends_workload_template_resource() { HashMap::from([("owner".to_string(), "platform".to_string())]), HashMap::from([("FEATURE_FLAG".to_string(), "on".to_string())]), "table", - "default", + "team-a", &tls, ) .await @@ -1805,10 +1822,11 @@ async fn sandbox_template_create_sends_workload_template_resource() { let request = requests .first() .expect("template create request should be recorded"); - assert_eq!(request.workspace, "default"); + assert_eq!(selected_workspace(&request.workspace_scope), Some("team-a")); let template = request.template.as_ref().expect("template should be sent"); let metadata = template.metadata.as_ref().expect("metadata should be sent"); assert_eq!(metadata.name, "gpu-kata"); + assert_eq!(metadata.workspace, "team-a"); assert_eq!(metadata.labels.get("team"), Some(&"runtime".to_string())); assert_eq!( metadata.annotations.get("owner"), @@ -1877,15 +1895,20 @@ async fn sandbox_template_list_and_delete_send_workspace_requests() { assert_eq!(list_request.limit, 25); assert_eq!(list_request.offset, 5); assert_eq!(list_request.label_selector, "team=runtime"); - assert_eq!(list_request.workspace, "default"); - assert!(!list_request.all_workspaces); + assert_eq!( + selected_workspace(&list_request.workspace_scope), + Some("default") + ); let delete_requests = template_delete_requests(&server).await; let delete_request = delete_requests .first() .expect("template delete request should be recorded"); assert_eq!(delete_request.name, "gpu-kata"); - assert_eq!(delete_request.workspace, "default"); + assert_eq!( + selected_workspace(&delete_request.workspace_scope), + Some("default") + ); } #[tokio::test] diff --git a/crates/openshell-core/src/grpc_client.rs b/crates/openshell-core/src/grpc_client.rs index 315ff0b72f..38b91e8501 100644 --- a/crates/openshell-core/src/grpc_client.rs +++ b/crates/openshell-core/src/grpc_client.rs @@ -28,6 +28,7 @@ use crate::proto::{ NetworkActivitySummary, PolicyChunk, PolicySource, PolicyStatus, RefreshSandboxTokenRequest, ReportPolicyStatusRequest, SandboxPolicy as ProtoSandboxPolicy, SubmitPolicyAnalysisRequest, SubmitPolicyAnalysisResponse, UpdateConfigRequest, open_shell_client::OpenShellClient, + workspace_selector, }; use crate::sandbox_env; use miette::{IntoDiagnostic, Result, WrapErr}; @@ -752,7 +753,7 @@ async fn sync_policy_with_client( .update_config(UpdateConfigRequest { name: sandbox.to_string(), policy: Some(policy.clone()), - workspace: workspace.to_string(), + workspace_scope: Some(workspace_selector(workspace)), ..Default::default() }) .await @@ -1180,7 +1181,7 @@ impl CachedOpenShellClient { .get_draft_policy(GetDraftPolicyRequest { name: sandbox_name.to_string(), status_filter: status_filter.to_string(), - workspace: self.workspace(), + workspace_scope: Some(workspace_selector(self.workspace())), }) .await .into_diagnostic()?; diff --git a/crates/openshell-core/src/proto/mod.rs b/crates/openshell-core/src/proto/mod.rs index cd4b24afe9..d0b976ff24 100644 --- a/crates/openshell-core/src/proto/mod.rs +++ b/crates/openshell-core/src/proto/mod.rs @@ -73,3 +73,19 @@ pub use middleware::v1::*; pub use openshell::*; pub use sandbox::v1::*; pub use test::ObjectForTest; + +/// Build a selector for one explicitly named workspace. +pub fn workspace_selector(workspace: impl Into) -> WorkspaceSelector { + WorkspaceSelector { + selection: Some(workspace_selector::Selection::Workspace(workspace.into())), + } +} + +/// Build a selector for every workspace supported by a cross-workspace request. +pub fn all_workspaces_selector() -> WorkspaceSelector { + WorkspaceSelector { + selection: Some(workspace_selector::Selection::AllWorkspaces( + AllWorkspaces {}, + )), + } +} diff --git a/crates/openshell-gateway-interceptors/src/proto_json.rs b/crates/openshell-gateway-interceptors/src/proto_json.rs index 70f6667321..dde37190e6 100644 --- a/crates/openshell-gateway-interceptors/src/proto_json.rs +++ b/crates/openshell-gateway-interceptors/src/proto_json.rs @@ -291,7 +291,7 @@ mod tests { use openshell_core::proto::{ CreateProviderRequest, CreateSandboxRequest, GpuResourceRequirements, Provider, - SandboxSpec, UpdateConfigRequest, + SandboxSpec, UpdateConfigRequest, workspace_selector, }; use prost::Message as _; use prost_types::{ @@ -315,7 +315,7 @@ mod tests { name: "demo".to_string(), labels: HashMap::from([("team".to_string(), "agent".to_string())]), annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(workspace_selector("default")), await_main_process_attachment: false, workload_template_name: String::new(), }; @@ -345,7 +345,7 @@ mod tests { config: HashMap::from([("region".to_string(), "us-west".to_string())]), ..Provider::default() }), - workspace: String::new(), + workspace_scope: Some(workspace_selector("default")), }; let encoded = request.encode_to_vec(); @@ -400,6 +400,7 @@ mod tests { environment: HashMap::from([("FEATURE_FLAG".to_string(), "on".to_string())]), ..SandboxSpec::default() }), + workspace_scope: Some(workspace_selector("default")), ..CreateSandboxRequest::default() }; @@ -454,6 +455,7 @@ mod tests { "openshell.nvidia.com/policy-signature".to_string(), "signed".to_string(), )]), + workspace_scope: Some(workspace_selector("default")), ..Default::default() }; let bytes = request.encode_to_vec(); diff --git a/crates/openshell-gateway-interceptors/src/runtime.rs b/crates/openshell-gateway-interceptors/src/runtime.rs index cd0f59ea3c..0bd1ba2b47 100644 --- a/crates/openshell-gateway-interceptors/src/runtime.rs +++ b/crates/openshell-gateway-interceptors/src/runtime.rs @@ -764,7 +764,7 @@ mod tests { config: HashMap::from([("region".to_string(), "old".to_string())]), ..Provider::default() }), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }; let json = codec .decode_message_to_json("openshell.v1.CreateProviderRequest", &request) @@ -1017,6 +1017,7 @@ mod tests { ("policy-signature-kid".to_string(), "kid".to_string()), ("correlation-id".to_string(), "reload-1".to_string()), ]), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..UpdateConfigRequest::default() }; let body = GrpcFrame { @@ -1074,7 +1075,7 @@ mod tests { name: "demo".to_string(), labels: HashMap::new(), annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), await_main_process_attachment: false, workload_template_name: String::new(), }; diff --git a/crates/openshell-sdk/README.md b/crates/openshell-sdk/README.md index c773de627d..dc57d5ec11 100644 --- a/crates/openshell-sdk/README.md +++ b/crates/openshell-sdk/README.md @@ -46,6 +46,7 @@ mTLS (client certificates) is not supported. `health`, `create_sandbox`, `get_sandbox`, `list_sandboxes`, `delete_sandbox`, `create_sandbox_from_template`, `create_sandbox_template`, `get_sandbox_template`, `list_sandbox_templates`, `delete_sandbox_template`, +`list_sandboxes_all_workspaces`, `list_sandbox_templates_all_workspaces`, `wait_ready`, `wait_deleted`, and `exec`. Curated types (`SandboxSpec`, `SandboxRef`, `Health`, `ListOptions`, `SandboxTemplateListOptions`, `ExecOptions`, `SandboxPhase`) use SDK-shaped enums rather than raw proto @@ -54,6 +55,10 @@ integers where practical. Reusable template resources are exposed as portable workload shape and driver config. Failures map to a typed `SdkError` with a discriminable kind. +Curated calls without a workspace argument explicitly select the `default` +workspace. Cross-workspace listing uses the separate `*_all_workspaces` +methods and requires Platform Admin access. + ```rust use openshell_sdk::{ ClientConfig, OpenShellClient, SandboxTemplateCreateSpec, diff --git a/crates/openshell-sdk/src/client.rs b/crates/openshell-sdk/src/client.rs index cd48c41558..4713f0ed1c 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -169,7 +169,7 @@ impl OpenShellClient { .unary(|mut grpc| { let request = proto::CreateSandboxTemplateRequest { template: Some(template.clone()), - workspace: String::new(), + workspace_scope: Some(proto::workspace_selector("default")), }; async move { grpc.create_sandbox_template(request).await } }) @@ -183,7 +183,7 @@ impl OpenShellClient { .unary(|mut grpc| { let request = proto::GetSandboxTemplateRequest { name: name.to_string(), - workspace: String::new(), + workspace_scope: Some(proto::workspace_selector("default")), }; async move { grpc.get_sandbox_template(request).await } }) @@ -191,7 +191,7 @@ impl OpenShellClient { sandbox_template_from_response(response.template) } - /// List reusable sandbox templates in the default workspace or across all workspaces. + /// List reusable sandbox templates in the default workspace. pub async fn list_sandbox_templates( &self, opts: SandboxTemplateListOptions, @@ -201,9 +201,27 @@ impl OpenShellClient { let request = proto::ListSandboxTemplatesRequest { limit: opts.limit, offset: opts.offset, - workspace: String::new(), - all_workspaces: opts.all_workspaces, label_selector: opts.label_selector.clone(), + workspace_scope: Some(proto::workspace_selector("default")), + }; + async move { grpc.list_sandbox_templates(request).await } + }) + .await?; + Ok(response.templates) + } + + /// List reusable sandbox templates across all workspaces. + pub async fn list_sandbox_templates_all_workspaces( + &self, + opts: SandboxTemplateListOptions, + ) -> Result> { + let response = self + .unary(|mut grpc| { + let request = proto::ListSandboxTemplatesRequest { + limit: opts.limit, + offset: opts.offset, + label_selector: opts.label_selector.clone(), + workspace_scope: Some(proto::all_workspaces_selector()), }; async move { grpc.list_sandbox_templates(request).await } }) @@ -217,7 +235,7 @@ impl OpenShellClient { .unary(|mut grpc| { let request = proto::DeleteSandboxTemplateRequest { name: name.to_string(), - workspace: String::new(), + workspace_scope: Some(proto::workspace_selector("default")), }; async move { grpc.delete_sandbox_template(request).await } }) @@ -231,7 +249,7 @@ impl OpenShellClient { .unary(|mut grpc| { let request = proto::GetSandboxRequest { name: name.to_string(), - workspace: String::new(), + workspace_scope: Some(proto::workspace_selector("default")), }; async move { grpc.get_sandbox(request).await } }) @@ -247,8 +265,7 @@ impl OpenShellClient { limit: opts.limit, offset: opts.offset, label_selector: opts.label_selector.clone().unwrap_or_default(), - workspace: String::new(), - all_workspaces: false, + workspace_scope: Some(proto::workspace_selector("default")), }; async move { grpc.list_sandboxes(request).await } }) @@ -271,7 +288,7 @@ impl OpenShellClient { .unary(|mut grpc| { let request = proto::DeleteSandboxRequest { name: name.to_string(), - workspace: String::new(), + workspace_scope: Some(proto::workspace_selector("default")), }; async move { grpc.delete_sandbox(request).await } }) @@ -285,7 +302,7 @@ impl OpenShellClient { .unary(|mut grpc| { let request = proto::StopSandboxRequest { name: name.to_string(), - workspace: String::new(), + workspace_scope: Some(proto::workspace_selector("default")), }; async move { grpc.stop_sandbox(request).await } }) @@ -299,7 +316,7 @@ impl OpenShellClient { .unary(|mut grpc| { let request = proto::StartSandboxRequest { name: name.to_string(), - workspace: String::new(), + workspace_scope: Some(proto::workspace_selector("default")), }; async move { grpc.start_sandbox(request).await } }) @@ -373,8 +390,7 @@ impl OpenShellClient { limit: opts.limit, offset: opts.offset, label_selector: opts.label_selector.clone().unwrap_or_default(), - workspace: String::new(), - all_workspaces: true, + workspace_scope: Some(proto::all_workspaces_selector()), }; async move { grpc.list_sandboxes(request).await } }) @@ -618,7 +634,7 @@ impl WorkspaceScopedClient { /// Create a new sandbox in this workspace. pub async fn create_sandbox(&self, spec: SandboxSpec) -> Result { let mut request = create_sandbox_request(spec); - request.workspace = self.workspace.clone(); + request.workspace_scope = Some(proto::workspace_selector(&self.workspace)); let response = self .client .unary(|mut grpc| { @@ -635,7 +651,7 @@ impl WorkspaceScopedClient { spec: SandboxTemplateCreateSpec, ) -> Result { let mut request = create_sandbox_from_template_request(spec); - request.workspace = self.workspace.clone(); + request.workspace_scope = Some(proto::workspace_selector(&self.workspace)); let response = self .client .unary(|mut grpc| { @@ -656,7 +672,7 @@ impl WorkspaceScopedClient { .unary(|mut grpc| { let request = proto::CreateSandboxTemplateRequest { template: Some(template.clone()), - workspace: self.workspace.clone(), + workspace_scope: Some(proto::workspace_selector(&self.workspace)), }; async move { grpc.create_sandbox_template(request).await } }) @@ -671,7 +687,7 @@ impl WorkspaceScopedClient { .unary(|mut grpc| { let request = proto::GetSandboxTemplateRequest { name: name.to_string(), - workspace: self.workspace.clone(), + workspace_scope: Some(proto::workspace_selector(&self.workspace)), }; async move { grpc.get_sandbox_template(request).await } }) @@ -679,7 +695,7 @@ impl WorkspaceScopedClient { sandbox_template_from_response(response.template) } - /// List reusable sandbox templates in this workspace, or across all workspaces. + /// List reusable sandbox templates in this workspace. pub async fn list_sandbox_templates( &self, opts: SandboxTemplateListOptions, @@ -690,13 +706,8 @@ impl WorkspaceScopedClient { let request = proto::ListSandboxTemplatesRequest { limit: opts.limit, offset: opts.offset, - workspace: if opts.all_workspaces { - String::new() - } else { - self.workspace.clone() - }, - all_workspaces: opts.all_workspaces, label_selector: opts.label_selector.clone(), + workspace_scope: Some(proto::workspace_selector(&self.workspace)), }; async move { grpc.list_sandbox_templates(request).await } }) @@ -711,7 +722,7 @@ impl WorkspaceScopedClient { .unary(|mut grpc| { let request = proto::DeleteSandboxTemplateRequest { name: name.to_string(), - workspace: self.workspace.clone(), + workspace_scope: Some(proto::workspace_selector(&self.workspace)), }; async move { grpc.delete_sandbox_template(request).await } }) @@ -726,7 +737,7 @@ impl WorkspaceScopedClient { .unary(|mut grpc| { let request = proto::GetSandboxRequest { name: name.to_string(), - workspace: self.workspace.clone(), + workspace_scope: Some(proto::workspace_selector(&self.workspace)), }; async move { grpc.get_sandbox(request).await } }) @@ -743,8 +754,7 @@ impl WorkspaceScopedClient { limit: opts.limit, offset: opts.offset, label_selector: opts.label_selector.clone().unwrap_or_default(), - workspace: self.workspace.clone(), - all_workspaces: false, + workspace_scope: Some(proto::workspace_selector(&self.workspace)), }; async move { grpc.list_sandboxes(request).await } }) @@ -763,7 +773,7 @@ impl WorkspaceScopedClient { .unary(|mut grpc| { let request = proto::DeleteSandboxRequest { name: name.to_string(), - workspace: self.workspace.clone(), + workspace_scope: Some(proto::workspace_selector(&self.workspace)), }; async move { grpc.delete_sandbox(request).await } }) @@ -778,7 +788,7 @@ impl WorkspaceScopedClient { .unary(|mut grpc| { let request = proto::StopSandboxRequest { name: name.to_string(), - workspace: self.workspace.clone(), + workspace_scope: Some(proto::workspace_selector(&self.workspace)), }; async move { grpc.stop_sandbox(request).await } }) @@ -793,7 +803,7 @@ impl WorkspaceScopedClient { .unary(|mut grpc| { let request = proto::StartSandboxRequest { name: name.to_string(), - workspace: self.workspace.clone(), + workspace_scope: Some(proto::workspace_selector(&self.workspace)), }; async move { grpc.start_sandbox(request).await } }) @@ -987,7 +997,7 @@ fn create_sandbox_request(spec: SandboxSpec) -> proto::CreateSandboxRequest { name: name.unwrap_or_default(), labels, annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(proto::workspace_selector("default")), await_main_process_attachment: false, workload_template_name: String::new(), } @@ -1016,7 +1026,7 @@ fn create_sandbox_from_template_request( name: name.unwrap_or_default(), labels, annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(proto::workspace_selector("default")), workload_template_name: template_name, await_main_process_attachment: false, } diff --git a/crates/openshell-sdk/src/types.rs b/crates/openshell-sdk/src/types.rs index db2944474b..12b5a72cb9 100644 --- a/crates/openshell-sdk/src/types.rs +++ b/crates/openshell-sdk/src/types.rs @@ -167,8 +167,6 @@ pub struct SandboxTemplateListOptions { pub offset: u32, /// Optional label selector in `key=value,key2=value2` form. pub label_selector: String, - /// List templates across all workspaces. - pub all_workspaces: bool, } /// Reference to a sandbox owned by the gateway. diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 89cc68bf0f..5fd2133b5c 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -23,6 +23,22 @@ use tokio::sync::Mutex; use tokio_stream::wrappers::TcpListenerStream; use tonic::{Response, Status}; +fn selected_workspace(scope: &Option) -> Option<&str> { + match scope.as_ref()?.selection.as_ref()? { + proto::datamodel::v1::workspace_selector::Selection::Workspace(workspace) => { + Some(workspace) + } + proto::datamodel::v1::workspace_selector::Selection::AllWorkspaces(_) => None, + } +} + +fn selects_all_workspaces(scope: &Option) -> bool { + matches!( + scope.as_ref().and_then(|scope| scope.selection.as_ref()), + Some(proto::datamodel::v1::workspace_selector::Selection::AllWorkspaces(_)) + ) +} + /// Captured fixture state — what the mock observed and the canned replies it /// returned. One per test so assertions are scoped. #[derive(Default)] @@ -243,11 +259,7 @@ impl OpenShell for TestOpenShell { request: tonic::Request, ) -> Result, Status> { let request = request.into_inner(); - let workspace = if request.workspace.is_empty() { - "default" - } else { - &request.workspace - }; + let workspace = selected_workspace(&request.workspace_scope).unwrap_or("default"); let template = workload_template_proto(&request.name, workspace); *self.state.last_template_get.lock().await = Some(request); Ok(Response::new(proto::SandboxTemplateResponse { @@ -287,7 +299,7 @@ impl OpenShell for TestOpenShell { let sandbox = sandbox_with_phase_ws( &request.name, proto::SandboxPhase::Stopped, - &request.workspace, + selected_workspace(&request.workspace_scope).unwrap_or("default"), ); *self.state.last_stop.lock().await = Some(request); Ok(Response::new(proto::SandboxResponse { @@ -303,7 +315,7 @@ impl OpenShell for TestOpenShell { let sandbox = sandbox_with_phase_ws( &request.name, proto::SandboxPhase::Starting, - &request.workspace, + selected_workspace(&request.workspace_scope).unwrap_or("default"), ); *self.state.last_start.lock().await = Some(request); Ok(Response::new(proto::SandboxResponse { @@ -318,7 +330,8 @@ impl OpenShell for TestOpenShell { let req = request.into_inner(); let name = req.name; *self.state.last_get_name.lock().await = Some(name.clone()); - *self.state.last_get_workspace.lock().await = Some(req.workspace.clone()); + *self.state.last_get_workspace.lock().await = + selected_workspace(&req.workspace_scope).map(str::to_string); let count = self.state.get_calls.fetch_add(1, Ordering::SeqCst); if self.state.get_returns_not_found { @@ -387,7 +400,8 @@ impl OpenShell for TestOpenShell { ) -> Result, Status> { let req = request.into_inner(); *self.state.last_delete_name.lock().await = Some(req.name); - *self.state.last_delete_workspace.lock().await = Some(req.workspace); + *self.state.last_delete_workspace.lock().await = + selected_workspace(&req.workspace_scope).map(str::to_string); Ok(Response::new(proto::DeleteSandboxResponse { deleted: true, })) @@ -965,7 +979,10 @@ async fn sandbox_template_crud_uses_default_workspace() { assert_eq!(created.metadata.as_ref().unwrap().name, "python"); let observed_create = state.last_template_create.lock().await.clone().unwrap(); - assert!(observed_create.workspace.is_empty()); + assert_eq!( + selected_workspace(&observed_create.workspace_scope), + Some("default") + ); assert_eq!( observed_create .template @@ -980,14 +997,16 @@ async fn sandbox_template_crud_uses_default_workspace() { assert_eq!(fetched.metadata.as_ref().unwrap().name, "python"); let observed_get = state.last_template_get.lock().await.clone().unwrap(); assert_eq!(observed_get.name, "python"); - assert!(observed_get.workspace.is_empty()); + assert_eq!( + selected_workspace(&observed_get.workspace_scope), + Some("default") + ); let listed = client - .list_sandbox_templates(SandboxTemplateListOptions { + .list_sandbox_templates_all_workspaces(SandboxTemplateListOptions { limit: 10, offset: 2, label_selector: String::new(), - all_workspaces: true, }) .await .unwrap(); @@ -995,14 +1014,16 @@ async fn sandbox_template_crud_uses_default_workspace() { let observed_list = state.last_template_list.lock().await.clone().unwrap(); assert_eq!(observed_list.limit, 10); assert_eq!(observed_list.offset, 2); - assert!(observed_list.workspace.is_empty()); - assert!(observed_list.all_workspaces); + assert!(selects_all_workspaces(&observed_list.workspace_scope)); let deleted = client.delete_sandbox_template("python").await.unwrap(); assert!(deleted); let observed_delete = state.last_template_delete.lock().await.clone().unwrap(); assert_eq!(observed_delete.name, "python"); - assert!(observed_delete.workspace.is_empty()); + assert_eq!( + selected_workspace(&observed_delete.workspace_scope), + Some("default") + ); } #[tokio::test] @@ -1084,7 +1105,7 @@ async fn stop_and_start_map_requests_and_phases() { assert_eq!(stopped.phase, SandboxPhase::Stopped); let stop = state.last_stop.lock().await.clone().unwrap(); assert_eq!(stop.name, "sleepy"); - assert!(stop.workspace.is_empty()); + assert_eq!(selected_workspace(&stop.workspace_scope), Some("default")); let started = client .workspace("team-a") @@ -1094,7 +1115,7 @@ async fn stop_and_start_map_requests_and_phases() { assert_eq!(started.phase, SandboxPhase::Starting); let start = state.last_start.lock().await.clone().unwrap(); assert_eq!(start.name, "sleepy"); - assert_eq!(start.workspace, "team-a"); + assert_eq!(selected_workspace(&start.workspace_scope), Some("team-a")); } #[tokio::test] @@ -1337,7 +1358,10 @@ async fn workspace_scoped_create_passes_workspace() { assert_eq!(result.name, "my-box"); let observed = state.last_create.lock().await.clone().unwrap(); - assert_eq!(observed.workspace, "staging"); + assert_eq!( + selected_workspace(&observed.workspace_scope), + Some("staging") + ); } #[tokio::test] @@ -1362,7 +1386,10 @@ async fn workspace_scoped_create_from_template_passes_workspace() { assert_eq!(sandbox.name, "from-template"); let observed = state.last_create.lock().await.clone().unwrap(); - assert_eq!(observed.workspace, "staging"); + assert_eq!( + selected_workspace(&observed.workspace_scope), + Some("staging") + ); assert_eq!(observed.workload_template_name, "python"); assert_eq!(observed.spec.unwrap().policy.unwrap().version, 2); } @@ -1395,8 +1422,7 @@ async fn workspace_scoped_list_passes_workspace() { assert_eq!(items.len(), 2); let observed = state.last_list_request.lock().await.clone().unwrap(); - assert_eq!(observed.workspace, "dev"); - assert!(!observed.all_workspaces); + assert_eq!(selected_workspace(&observed.workspace_scope), Some("dev")); } #[tokio::test] @@ -1410,12 +1436,18 @@ async fn workspace_scoped_sandbox_template_crud_passes_workspace() { .await .unwrap(); let observed_create = state.last_template_create.lock().await.clone().unwrap(); - assert_eq!(observed_create.workspace, "staging"); + assert_eq!( + selected_workspace(&observed_create.workspace_scope), + Some("staging") + ); ws.get_sandbox_template("python").await.unwrap(); let observed_get = state.last_template_get.lock().await.clone().unwrap(); assert_eq!(observed_get.name, "python"); - assert_eq!(observed_get.workspace, "staging"); + assert_eq!( + selected_workspace(&observed_get.workspace_scope), + Some("staging") + ); let listed = ws .list_sandbox_templates(SandboxTemplateListOptions::default()) @@ -1423,24 +1455,26 @@ async fn workspace_scoped_sandbox_template_crud_passes_workspace() { .unwrap(); assert_eq!(listed.len(), 2); let observed_list = state.last_template_list.lock().await.clone().unwrap(); - assert_eq!(observed_list.workspace, "staging"); - assert!(!observed_list.all_workspaces); + assert_eq!( + selected_workspace(&observed_list.workspace_scope), + Some("staging") + ); - ws.list_sandbox_templates(SandboxTemplateListOptions { - all_workspaces: true, - ..Default::default() - }) - .await - .unwrap(); + client + .list_sandbox_templates_all_workspaces(SandboxTemplateListOptions::default()) + .await + .unwrap(); let observed_all = state.last_template_list.lock().await.clone().unwrap(); - assert!(observed_all.workspace.is_empty()); - assert!(observed_all.all_workspaces); + assert!(selects_all_workspaces(&observed_all.workspace_scope)); let deleted = ws.delete_sandbox_template("python").await.unwrap(); assert!(deleted); let observed_delete = state.last_template_delete.lock().await.clone().unwrap(); assert_eq!(observed_delete.name, "python"); - assert_eq!(observed_delete.workspace, "staging"); + assert_eq!( + selected_workspace(&observed_delete.workspace_scope), + Some("staging") + ); } #[tokio::test] @@ -1470,8 +1504,7 @@ async fn list_sandboxes_all_workspaces_sets_flag() { assert_eq!(items.len(), 2); let observed = state.last_list_request.lock().await.clone().unwrap(); - assert!(observed.all_workspaces); - assert!(observed.workspace.is_empty()); + assert!(selects_all_workspaces(&observed.workspace_scope)); } // ---- Workspace CRUD tests ---- diff --git a/crates/openshell-server/src/auth/workspace_authz.rs b/crates/openshell-server/src/auth/workspace_authz.rs index e23d2287a3..2958d656c7 100644 --- a/crates/openshell-server/src/auth/workspace_authz.rs +++ b/crates/openshell-server/src/auth/workspace_authz.rs @@ -9,7 +9,10 @@ //! and workspace-level role. use super::principal::Principal; -use openshell_core::proto::WorkspaceRole as ProtoWorkspaceRole; +use openshell_core::proto::{ + WorkspaceRole as ProtoWorkspaceRole, WorkspaceSelector, + workspace_selector::Selection as WorkspaceSelection, +}; use tonic::Status; use crate::persistence::Store; @@ -39,7 +42,7 @@ impl MinWorkspaceRole { /// Result of a successful workspace authorization check. #[derive(Debug)] pub struct AuthorizedWorkspace { - /// Resolved workspace name (empty string normalized to `"default"`). + /// Explicit workspace name selected by the caller. pub workspace: String, /// How the caller was authorized. pub grant: AuthGrant, @@ -56,6 +59,75 @@ pub enum AuthGrant { Sandbox, } +/// Authorized scope for a request that supports one workspace or all workspaces. +#[derive(Debug)] +pub enum AuthorizedWorkspaceScope { + /// One explicitly named workspace. + Workspace(AuthorizedWorkspace), + /// All workspaces, authorized for a platform administrator. + AllWorkspaces, +} + +/// Authorize the required named selector on a single-workspace request. +#[allow(clippy::result_large_err)] +pub async fn authorize_workspace_selector( + store: &Store, + admin_role: &str, + principal: &Principal, + selector: Option<&WorkspaceSelector>, + min_role: MinWorkspaceRole, +) -> Result { + let workspace = selected_workspace_name(selector)?; + authorize_workspace(store, admin_role, principal, workspace, min_role).await +} + +/// Authorize a selector on a request that explicitly supports all workspaces. +#[allow(clippy::result_large_err)] +pub async fn authorize_list_workspace_selector( + store: &Store, + admin_role: &str, + principal: &Principal, + selector: Option<&WorkspaceSelector>, + min_role: MinWorkspaceRole, +) -> Result { + match selected_workspace(selector)? { + WorkspaceSelection::Workspace(workspace) => { + authorize_workspace(store, admin_role, principal, workspace, min_role) + .await + .map(AuthorizedWorkspaceScope::Workspace) + } + WorkspaceSelection::AllWorkspaces(_) => { + require_platform_admin(admin_role, principal)?; + Ok(AuthorizedWorkspaceScope::AllWorkspaces) + } + } +} + +/// Return the explicitly selected workspace name, rejecting missing, empty, +/// or all-workspaces selections. +#[allow(clippy::result_large_err)] +pub fn selected_workspace_name(selector: Option<&WorkspaceSelector>) -> Result<&str, Status> { + match selected_workspace(selector)? { + WorkspaceSelection::Workspace(workspace) => Ok(workspace), + WorkspaceSelection::AllWorkspaces(_) => Err(Status::invalid_argument( + "all_workspaces is not supported by this request", + )), + } +} + +#[allow(clippy::result_large_err)] +fn selected_workspace(selector: Option<&WorkspaceSelector>) -> Result<&WorkspaceSelection, Status> { + let selection = selector + .and_then(|selector| selector.selection.as_ref()) + .ok_or_else(|| Status::invalid_argument("workspace_scope is required"))?; + + if let WorkspaceSelection::Workspace(workspace) = selection { + crate::grpc::workspace::validate_workspace_name(workspace)?; + } + + Ok(selection) +} + /// Authorize a workspace-scoped operation for a user principal. /// /// Checks workspace membership and role. Platform admins (callers whose @@ -72,7 +144,7 @@ pub async fn authorize_workspace( workspace: &str, min_role: MinWorkspaceRole, ) -> Result { - let workspace = normalize_workspace(workspace); + let workspace = workspace.to_string(); match principal { Principal::User(user) => { @@ -186,14 +258,6 @@ fn role_satisfies(member_role: ProtoWorkspaceRole, min_role: MinWorkspaceRole) - } } -fn normalize_workspace(workspace: &str) -> String { - if workspace.is_empty() { - "default".to_string() - } else { - workspace.to_string() - } -} - #[cfg(test)] mod tests { use super::*; @@ -401,20 +465,75 @@ mod tests { } #[tokio::test] - async fn empty_workspace_normalizes_to_default() { + async fn empty_named_selector_is_rejected() { let store = test_store().await; add_member(&store, "default", "user-d", ProtoWorkspaceRole::User).await; let principal = user_principal("user-d", &["openshell-user"]); - let result = authorize_workspace( + let result = authorize_workspace_selector( &store, "openshell-admin", &principal, - "", + Some(&openshell_core::proto::workspace_selector("")), MinWorkspaceRole::User, ) .await; - assert!(result.is_ok()); - assert_eq!(result.unwrap().workspace, "default"); + let err = result.unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert_eq!(err.message(), "workspace name is required"); + } + + #[test] + fn missing_and_unset_selectors_are_rejected() { + let missing = selected_workspace_name(None).unwrap_err(); + assert_eq!(missing.code(), tonic::Code::InvalidArgument); + assert_eq!(missing.message(), "workspace_scope is required"); + + let unset = selected_workspace_name(Some(&WorkspaceSelector::default())).unwrap_err(); + assert_eq!(unset.code(), tonic::Code::InvalidArgument); + assert_eq!(unset.message(), "workspace_scope is required"); + } + + #[test] + fn all_workspaces_is_rejected_for_single_workspace_requests() { + let err = selected_workspace_name(Some(&openshell_core::proto::all_workspaces_selector())) + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert_eq!( + err.message(), + "all_workspaces is not supported by this request" + ); + } + + #[tokio::test] + async fn all_workspaces_requires_platform_admin() { + let store = test_store().await; + let selector = openshell_core::proto::all_workspaces_selector(); + let principal = user_principal("workspace-user", &["openshell-user"]); + let err = authorize_list_workspace_selector( + &store, + "openshell-admin", + &principal, + Some(&selector), + MinWorkspaceRole::User, + ) + .await + .unwrap_err(); + assert_eq!(err.code(), tonic::Code::PermissionDenied); + + let admin = user_principal("platform-admin", &["openshell-admin"]); + let authorized = authorize_list_workspace_selector( + &store, + "openshell-admin", + &admin, + Some(&selector), + MinWorkspaceRole::User, + ) + .await + .unwrap(); + assert!(matches!( + authorized, + AuthorizedWorkspaceScope::AllWorkspaces + )); } #[tokio::test] diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 4940cd1aa3..4f2855dd0b 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -13,7 +13,8 @@ use crate::ServerState; use crate::auth::principal::Principal; use crate::auth::workspace_authz::{ - MinWorkspaceRole, authorize_sandbox_workspace, authorize_workspace, require_platform_admin, + MinWorkspaceRole, authorize_sandbox_workspace, authorize_workspace_selector, + require_platform_admin, selected_workspace_name, }; use crate::persistence::{ DraftChunkRecord, ObjectId, ObjectName, ObjectType, ObjectWorkspace, PolicyRecord, Store, @@ -3240,6 +3241,11 @@ async fn handle_update_config_inner( let req = request.into_inner(); validate_annotations(&req.annotations, "annotations")?; let workspace = if req.global { + if req.workspace_scope.is_some() { + return Err(Status::invalid_argument( + "workspace_scope must be omitted when global is true", + )); + } require_platform_admin(&state.admin_role, principal)?; String::new() } else { @@ -3248,15 +3254,16 @@ async fn handle_update_config_inner( } else { MinWorkspaceRole::Admin }; + let workspace = selected_workspace_name(req.workspace_scope.as_ref())?; authorize_sandbox_workspace( &state.store, &state.admin_role, principal, - &req.workspace, + workspace, min_role, ) .await?; - super::workspace::resolve_workspace(state.store.as_ref(), &req.workspace) + super::workspace::resolve_workspace(state.store.as_ref(), workspace) .await? .name }; @@ -3922,14 +3929,19 @@ pub(super) async fn handle_get_sandbox_policy_status( let principal = super::extract_principal(&request)?; let req = request.into_inner(); let workspace = if req.global { + if req.workspace_scope.is_some() { + return Err(Status::invalid_argument( + "workspace_scope must be omitted when global is true", + )); + } require_platform_admin(&state.admin_role, &principal)?; String::new() } else { - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -3990,14 +4002,19 @@ pub(super) async fn handle_list_sandbox_policies( let principal = super::extract_principal(&request)?; let req = request.into_inner(); let workspace = if req.global { + if req.workspace_scope.is_some() { + return Err(Status::invalid_argument( + "workspace_scope must be omitted when global is true", + )); + } require_platform_admin(&state.admin_role, &principal)?; String::new() } else { - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -4129,8 +4146,22 @@ pub(super) async fn handle_get_sandbox_logs( if req.sandbox_id.is_empty() { return Err(Status::invalid_argument("sandbox_id is required")); } - let _sandbox = + let authz = authorize_workspace_selector( + &state.store, + &state.admin_role, + &principal, + req.workspace_scope.as_ref(), + MinWorkspaceRole::User, + ) + .await?; + let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) + .await? + .name; + let sandbox = super::sandbox::fetch_and_authorize_sandbox(state, &principal, &req.sandbox_id).await?; + if sandbox.object_workspace() != workspace { + return Err(Status::not_found("sandbox not found")); + } let lines = if req.lines == 0 { 2000 } else { req.lines }; let tail = state.tracing_log_bus.tail(&req.sandbox_id, lines as usize); @@ -4661,15 +4692,16 @@ pub(super) async fn handle_get_draft_policy( .cloned() .ok_or_else(|| Status::unauthenticated("missing principal"))?; let req = request.into_inner(); + let workspace_name = selected_workspace_name(req.workspace_scope.as_ref())?; authorize_sandbox_workspace( &state.store, &state.admin_role, &principal, - &req.workspace, + workspace_name, MinWorkspaceRole::User, ) .await?; - let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &req.workspace) + let workspace = super::workspace::resolve_workspace(state.store.as_ref(), workspace_name) .await? .name; if req.name.is_empty() { @@ -4742,11 +4774,11 @@ async fn handle_approve_draft_chunk_inner( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -4897,11 +4929,11 @@ async fn handle_reject_draft_chunk_inner( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -5007,11 +5039,11 @@ async fn handle_approve_all_draft_chunks_inner( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -5315,11 +5347,11 @@ pub(super) async fn handle_edit_draft_chunk( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -5396,11 +5428,11 @@ async fn handle_undo_draft_chunk_inner( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -5493,11 +5525,11 @@ pub(super) async fn handle_clear_draft_chunks( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -5541,11 +5573,11 @@ pub(super) async fn handle_get_draft_history( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -7538,6 +7570,7 @@ mod tests { with_user(Request::new(GetSandboxPolicyStatusRequest { name: "stored-invalid-history".to_string(), version: 2, + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() })), ) @@ -7555,6 +7588,7 @@ mod tests { with_user(Request::new(ListSandboxPoliciesRequest { name: "stored-invalid-history".to_string(), limit: 10, + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() })), ) @@ -7917,6 +7951,7 @@ mod tests { with_user(Request::new(UpdateConfigRequest { name: sandbox_name, policy: Some(mcp_policy_with_versions(&["2025-11-25"])), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() })), ) @@ -8023,6 +8058,7 @@ mod tests { with_user(Request::new(UpdateConfigRequest { name: sandbox_name.to_string(), policy: Some(candidate.clone()), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() })), ) @@ -8081,6 +8117,7 @@ mod tests { with_user(Request::new(UpdateConfigRequest { name: sandbox_name.to_string(), policy: Some(candidate.clone()), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() })), ) @@ -8409,6 +8446,7 @@ mod tests { let req = UpdateConfigRequest { name: "sandbox-1".to_string(), policy: Some(ProtoSandboxPolicy::default()), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() }; assert!(validate_sandbox_caller_update(&req).is_ok()); @@ -8431,6 +8469,7 @@ mod tests { name: "sandbox-1".to_string(), setting_key: "inference.model".to_string(), setting_value: Some(SettingValue { value: None }), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() }; let err = validate_sandbox_caller_update(&req).unwrap_err(); @@ -8511,7 +8550,9 @@ mod tests { &state, with_user(Request::new(GetSandboxLogsRequest { sandbox_id: "sandbox-b-id".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), ..GetSandboxLogsRequest::default() })), ) @@ -8597,6 +8638,47 @@ mod tests { ); } + #[tokio::test] + async fn global_policy_requests_reject_workspace_selectors() { + let state = test_server_state().await; + + let update_error = handle_update_config( + &state, + authed_request(UpdateConfigRequest { + global: true, + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + }), + ) + .await + .unwrap_err(); + assert_eq!(update_error.code(), Code::InvalidArgument); + + let get_error = handle_get_sandbox_policy_status( + &state, + authed_request(GetSandboxPolicyStatusRequest { + global: true, + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + }), + ) + .await + .unwrap_err(); + assert_eq!(get_error.code(), Code::InvalidArgument); + + let list_error = handle_list_sandbox_policies( + &state, + authed_request(ListSandboxPoliciesRequest { + global: true, + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + }), + ) + .await + .unwrap_err(); + assert_eq!(list_error.code(), Code::InvalidArgument); + } + #[tokio::test] async fn update_config_rejects_missing_principal() { let state = test_server_state().await; @@ -8888,7 +8970,9 @@ mod tests { Request::new(GetDraftPolicyRequest { name: "sandbox-b".to_string(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), "sb-a", ); @@ -8905,6 +8989,7 @@ mod tests { Request::new(UpdateConfigRequest { name: "missing-sandbox".to_string(), policy: Some(ProtoSandboxPolicy::default()), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() }), "sb-a", @@ -8940,7 +9025,9 @@ mod tests { Request::new(GetDraftPolicyRequest { name: "missing-sandbox".to_string(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), "sb-a", ); @@ -9996,7 +10083,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "ambiguous-update".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), policy: Some(test_ambiguous_policy()), ..Default::default() })), @@ -10033,7 +10122,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "unattached-binding".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), policy: Some(test_policy_with_credential_binding( "cloud", "api.cloud.example", @@ -10078,7 +10169,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "double-binding".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), policy: Some(test_policy_with_credential_binding( "cloud", "api.cloud.example", @@ -10146,7 +10239,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "endpointless-gating".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), policy: Some(l4.clone()), ..Default::default() })), @@ -10169,7 +10264,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "endpointless-gating".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), policy: Some(tls_skip.clone()), ..Default::default() })), @@ -10183,7 +10280,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "endpointless-gating".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), merge_operations: vec![add_bound_rule(&l4)], ..Default::default() })), @@ -10197,7 +10296,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "endpointless-gating".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), merge_operations: vec![add_bound_rule(&tls_skip)], ..Default::default() })), @@ -10228,7 +10329,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "endpointless-gating".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), merge_operations: vec![add_bound_rule(&opted_in)], ..Default::default() })), @@ -10261,7 +10364,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "signing-no-source".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), policy: Some(test_sigv4_policy("s3.amazonaws.com", None)), ..Default::default() })), @@ -10307,7 +10412,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "signing-unbound-aws".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), policy: Some(test_sigv4_policy("s3.amazonaws.com", None)), ..Default::default() })), @@ -10344,7 +10451,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "signing-bound-aws".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), policy: Some(test_sigv4_policy("s3.amazonaws.com", Some("aws-prod"))), ..Default::default() })), @@ -10388,7 +10497,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "signing-profile-endpoint".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), policy: Some(policy), ..Default::default() })), @@ -10418,7 +10529,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "signing-profile-mismatch".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), policy: Some(test_sigv4_policy("api.example.com", None)), ..Default::default() })), @@ -10526,7 +10639,9 @@ mod tests { sandbox_name: "provider-ambiguity".to_string(), provider_name: "candidate-provider".to_string(), expected_resource_version: 0, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -11153,7 +11268,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "policy-binding".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), policy: Some(next_policy.clone()), ..Default::default() })), @@ -11208,7 +11325,9 @@ mod tests { &state, with_user(Request::new(UpdateConfigRequest { name: "policy-binding".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), policy: Some(unbound_policy), ..Default::default() })), @@ -11994,7 +12113,9 @@ mod tests { sandbox_name: "attach-lifecycle".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -12032,7 +12153,9 @@ mod tests { sandbox_name: "attach-lifecycle".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12164,7 +12287,9 @@ mod tests { sandbox_name: "attach-lifecycle".to_string(), provider_name: "work-custom".to_string(), expected_resource_version: 0, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -12205,7 +12330,9 @@ mod tests { sandbox_name: "attach-lifecycle".to_string(), provider_name: "work-custom".to_string(), expected_resource_version: 0, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12512,7 +12639,9 @@ mod tests { &state, with_user(Request::new(ApproveAllDraftChunksRequest { name: sandbox_name.to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), approvals: chunks .iter() .map(|chunk| openshell_core::proto::DraftChunkApproval { @@ -12639,7 +12768,9 @@ mod tests { &state, with_user(Request::new(ApproveAllDraftChunksRequest { name: sandbox_name.to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), approvals: chunks .iter() .map(|chunk| openshell_core::proto::DraftChunkApproval { @@ -12841,7 +12972,9 @@ mod tests { with_user(Request::new(ApproveAllDraftChunksRequest { name: sandbox_name.to_string(), include_security_flagged: false, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), approvals: vec![openshell_core::proto::DraftChunkApproval { chunk_id: chunk_id.clone(), review_token: chunk.review_token.clone(), @@ -12869,7 +13002,9 @@ mod tests { with_user(Request::new(ApproveAllDraftChunksRequest { name: sandbox_name.to_string(), include_security_flagged: true, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), approvals: vec![openshell_core::proto::DraftChunkApproval { chunk_id: chunk_id.clone(), review_token: chunk.review_token.clone(), @@ -12947,7 +13082,9 @@ mod tests { name: sandbox_name.to_string(), chunk_id: chunk_id.clone(), proposed_rule: Some(private_rule), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -12966,7 +13103,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name.to_string(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -12983,7 +13122,9 @@ mod tests { with_user(Request::new(ApproveAllDraftChunksRequest { name: sandbox_name.to_string(), include_security_flagged: false, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), ..Default::default() })), ) @@ -13049,7 +13190,9 @@ mod tests { with_user(Request::new(ApproveAllDraftChunksRequest { name: sandbox_name.to_string(), include_security_flagged: false, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), ..Default::default() })), ) @@ -13119,7 +13262,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name.to_string(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -13233,7 +13378,9 @@ mod tests { name: sandbox_name.to_string(), chunk_id: chunk_id.clone(), proposed_rule: Some(finding_rule), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -13366,7 +13513,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name.clone(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -13386,7 +13535,9 @@ mod tests { authed_request(ApproveDraftChunkRequest { name: sandbox_name.clone(), chunk_id: chunk_id.clone(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), review_token, }), ) @@ -13400,7 +13551,9 @@ mod tests { &state, authed_request(GetDraftHistoryRequest { name: sandbox_name.clone(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -13418,7 +13571,9 @@ mod tests { limit: 10, offset: 0, global: false, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -13432,7 +13587,9 @@ mod tests { authed_request(UndoDraftChunkRequest { name: sandbox_name.clone(), chunk_id: chunk_id.clone(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -13446,7 +13603,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name.clone(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -13459,7 +13618,9 @@ mod tests { &state, authed_request(GetDraftHistoryRequest { name: sandbox_name.clone(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -13475,7 +13636,9 @@ mod tests { limit: 10, offset: 0, global: false, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -13489,7 +13652,9 @@ mod tests { &state, authed_request(ClearDraftChunksRequest { name: sandbox_name.clone(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -13502,7 +13667,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name.clone(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -13514,7 +13681,9 @@ mod tests { &state, authed_request(GetDraftHistoryRequest { name: sandbox_name, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -13591,7 +13760,9 @@ mod tests { name: sandbox_name.clone(), chunk_id: chunk_id.clone(), reason: guidance.to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -13602,7 +13773,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -13709,7 +13882,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -13822,7 +13997,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name.clone(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -13898,7 +14075,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -14028,7 +14207,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -14132,7 +14313,9 @@ mod tests { &state, with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), ..Default::default() })), ) @@ -14255,7 +14438,9 @@ mod tests { &state, with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), ..Default::default() })), ) @@ -14386,7 +14571,9 @@ mod tests { with_user(Request::new(ApproveDraftChunkRequest { name: sandbox_name, chunk_id: chunk_id.clone(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), review_token: before.review_token.clone(), })), ) @@ -14570,7 +14757,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -14674,7 +14863,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -14771,7 +14962,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -14859,7 +15052,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -14951,7 +15146,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -15046,7 +15243,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -15220,7 +15419,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name.to_string(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -15293,7 +15494,9 @@ mod tests { with_user(Request::new(ApproveDraftChunkRequest { name: sandbox_name.to_string(), chunk_id: chunk.id.clone(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), ..Default::default() })), ) @@ -15404,7 +15607,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -15504,7 +15709,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -15593,7 +15800,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -15753,7 +15962,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name.clone(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -15783,7 +15994,9 @@ mod tests { authed_request(ApproveDraftChunkRequest { name: sandbox_name, chunk_id, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), review_token: chunk.review_token.clone(), }), ) @@ -15971,7 +16184,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -16122,7 +16337,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name.clone(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -16144,7 +16361,9 @@ mod tests { name: sandbox_name, chunk_id: second.accepted_chunk_ids[0].clone(), reason: "redraft test".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -16228,7 +16447,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -16344,7 +16565,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name.clone(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -16365,7 +16588,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name.clone(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -16608,7 +16833,9 @@ mod tests { name: sandbox_name.clone(), chunk_id: chunk_id.clone(), reason: "scope too broad".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -16619,7 +16846,9 @@ mod tests { authed_request(ApproveDraftChunkRequest { name: sandbox_name.clone(), chunk_id: chunk_id.clone(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), review_token, }), ) @@ -16631,7 +16860,9 @@ mod tests { authed_request(UndoDraftChunkRequest { name: sandbox_name.clone(), chunk_id: chunk_id.clone(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -16642,7 +16873,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -16754,7 +16987,9 @@ mod tests { with_user(Request::new(GetDraftPolicyRequest { name: sandbox_a.object_name().to_string(), status_filter: String::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), })), ) .await @@ -16769,7 +17004,9 @@ mod tests { authed_request(ApproveDraftChunkRequest { name: other_name.clone(), chunk_id: chunk_id.clone(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), review_token: String::new(), }), ) @@ -16783,7 +17020,9 @@ mod tests { name: other_name.clone(), chunk_id: chunk_id.clone(), reason: "wrong sandbox".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -16796,7 +17035,9 @@ mod tests { name: other_name.clone(), chunk_id: chunk_id.clone(), proposed_rule: Some(proposed_rule.clone()), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -16808,7 +17049,9 @@ mod tests { authed_request(ApproveDraftChunkRequest { name: sandbox_a.object_name().to_string(), chunk_id: chunk_id.clone(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), review_token, }), ) @@ -16820,7 +17063,9 @@ mod tests { authed_request(UndoDraftChunkRequest { name: other_name, chunk_id, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -18926,7 +19171,9 @@ mod tests { merge_operations: vec![], expected_resource_version: current_version, annotations: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -19022,7 +19269,9 @@ mod tests { merge_operations: vec![], expected_resource_version: current_version, annotations: annotations.clone(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -19095,6 +19344,7 @@ mod tests { "openshell.nvidia.com/policy-signature".to_string(), "same-hash-signature".to_string(), )]), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() }), ) @@ -19178,6 +19428,7 @@ mod tests { name: "idempotent-provenance".to_string(), policy: Some(policy.clone()), annotations: annotations.clone(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() })), ) @@ -19190,6 +19441,7 @@ mod tests { name: "idempotent-provenance".to_string(), policy: Some(policy), annotations: annotations.clone(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() })), ) @@ -19243,6 +19495,7 @@ mod tests { with_user(Request::new(UpdateConfigRequest { name: "preserve-full".to_string(), policy: Some(updated), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() })), ) @@ -19306,6 +19559,7 @@ mod tests { }, )), }], + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() })), ) @@ -19378,6 +19632,7 @@ mod tests { )), }], annotations: provenance.clone(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() })), ) @@ -19439,6 +19694,7 @@ mod tests { name: "preserve-backfill".to_string(), policy: Some(ProtoSandboxPolicy::default()), expected_resource_version: current_version, + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() }), ) @@ -19513,7 +19769,9 @@ mod tests { name: sandbox_name.to_string(), policy: Some(unsafe_replacement), expected_resource_version: current_version, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), ..Default::default() })), ) @@ -19589,7 +19847,9 @@ mod tests { name: sandbox_name.to_string(), policy: Some(mcp_policy_with_versions(versions)), expected_resource_version: current_version, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), ..Default::default() })), ) @@ -19671,7 +19931,9 @@ mod tests { name: sandbox_name.clone(), policy: Some(policy), expected_resource_version: current_version, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), ..Default::default() })), ) @@ -19760,7 +20022,9 @@ mod tests { "2025-03-26", ])), expected_resource_version: current_version, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), ..Default::default() })), ) @@ -19835,6 +20099,7 @@ mod tests { name: "invalid-annotation".to_string(), policy: Some(ProtoSandboxPolicy::default()), annotations: HashMap::from([("bad key".to_string(), "value".to_string())]), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() })), ) @@ -19867,6 +20132,7 @@ mod tests { "_provider_work_github", "api.github.com", )), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() })), ) @@ -19933,6 +20199,7 @@ mod tests { name: "sync-strip".to_string(), policy: Some(synced_policy), expected_resource_version: current_version, + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() }), "sb-sync-strip", @@ -20034,7 +20301,9 @@ mod tests { merge_operations: vec![], expected_resource_version: 99, // stale version annotations: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -20133,7 +20402,9 @@ mod tests { merge_operations: vec![], expected_resource_version: initial_version, annotations: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -20215,7 +20486,7 @@ mod tests { let err = handle_get_sandbox_policy_status( &state, non_member_request(GetSandboxPolicyStatusRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -20231,7 +20502,7 @@ mod tests { let err = handle_list_sandbox_policies( &state, non_member_request(ListSandboxPoliciesRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -20247,7 +20518,7 @@ mod tests { let err = handle_update_config( &state, non_member_request(UpdateConfigRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -20263,7 +20534,7 @@ mod tests { let err = handle_get_draft_policy( &state, non_member_request(GetDraftPolicyRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -20279,7 +20550,7 @@ mod tests { let err = handle_approve_draft_chunk( &state, non_member_request(ApproveDraftChunkRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -20295,7 +20566,7 @@ mod tests { let err = handle_reject_draft_chunk( &state, non_member_request(RejectDraftChunkRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -20311,7 +20582,7 @@ mod tests { let err = handle_approve_all_draft_chunks( &state, non_member_request(ApproveAllDraftChunksRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -20327,7 +20598,7 @@ mod tests { let err = handle_edit_draft_chunk( &state, non_member_request(EditDraftChunkRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -20343,7 +20614,7 @@ mod tests { let err = handle_undo_draft_chunk( &state, non_member_request(UndoDraftChunkRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -20359,7 +20630,7 @@ mod tests { let err = handle_clear_draft_chunks( &state, non_member_request(ClearDraftChunksRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -20375,7 +20646,7 @@ mod tests { let err = handle_get_draft_history( &state, non_member_request(GetDraftHistoryRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -20389,9 +20660,8 @@ mod tests { ); } - /// ID-based policy handlers must return `NOT_FOUND` — never - /// `PERMISSION_DENIED` — when the caller lacks workspace access, so that - /// cross-workspace sandbox existence cannot be inferred (CWE-203). + /// ID-only policy handlers hide cross-workspace resources, while requests + /// with an explicit workspace selector authorize that selector first. #[tokio::test] async fn id_based_policy_handlers_hide_cross_workspace_sandboxes() { let mut state = test_server_state().await; @@ -20440,6 +20710,7 @@ mod tests { &state, non_member_request(GetSandboxLogsRequest { sandbox_id: "sandbox-other".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() }), ) @@ -20447,8 +20718,8 @@ mod tests { .unwrap_err(); assert_eq!( err.code(), - Code::NotFound, - "handle_get_sandbox_logs must return NotFound, not PermissionDenied" + Code::PermissionDenied, + "handle_get_sandbox_logs must authorize the selected workspace before lookup" ); } diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index 0039872afd..46eb9ce9be 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -2350,7 +2350,10 @@ use std::sync::{Arc, LazyLock, RwLock}; use tonic::{Request, Response}; use crate::auth::principal::Principal; -use crate::auth::workspace_authz::{MinWorkspaceRole, authorize_workspace, require_platform_admin}; +use crate::auth::workspace_authz::{ + AuthorizedWorkspaceScope, MinWorkspaceRole, authorize_list_workspace_selector, + authorize_workspace, authorize_workspace_selector, require_platform_admin, +}; use openshell_core::oauth::{ self, TokenExchangeParams, effective_client_assertion_type, effective_token_type, }; @@ -2468,11 +2471,11 @@ pub(super) async fn handle_create_provider( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -2542,11 +2545,11 @@ pub(super) async fn handle_get_provider( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -2566,15 +2569,17 @@ pub(super) async fn handle_list_providers( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let request = request.into_inner(); - if request.all_workspaces && !request.workspace.is_empty() { - return Err(Status::invalid_argument( - "all_workspaces and workspace are mutually exclusive", - )); - } let limit = clamp_limit(request.limit, 100, MAX_PAGE_SIZE); - let providers = if request.all_workspaces { - require_platform_admin(&state.admin_role, &principal)?; + let scope = authorize_list_workspace_selector( + &state.store, + &state.admin_role, + &principal, + request.workspace_scope.as_ref(), + MinWorkspaceRole::User, + ) + .await?; + let providers = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { let all: Vec = state .store .list_all_messages(limit, request.offset) @@ -2582,14 +2587,9 @@ pub(super) async fn handle_list_providers( .map_err(|e| Status::internal(format!("list providers failed: {e}")))?; all.into_iter().map(redact_provider_credentials).collect() } else { - let authz = authorize_workspace( - &state.store, - &state.admin_role, - &principal, - &request.workspace, - MinWorkspaceRole::User, - ) - .await?; + let AuthorizedWorkspaceScope::Workspace(authz) = scope else { + unreachable!("all-workspaces scope handled above") + }; let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) .await? .name; @@ -3697,11 +3697,11 @@ pub(super) async fn handle_update_provider( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -4228,11 +4228,11 @@ pub(super) async fn handle_get_provider_refresh_status( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let request = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &request.workspace, + request.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -4281,11 +4281,11 @@ pub(super) async fn handle_configure_provider_refresh( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let request = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &request.workspace, + request.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -4678,11 +4678,11 @@ pub(super) async fn handle_rotate_provider_credential( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let request = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &request.workspace, + request.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -4748,11 +4748,11 @@ pub(super) async fn handle_delete_provider_refresh( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let request = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &request.workspace, + request.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -4826,11 +4826,11 @@ pub(super) async fn handle_delete_provider( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -6568,7 +6568,9 @@ mod tests { sandbox_name: "sandbox-custom".to_string(), provider_name: "custom-provider".to_string(), expected_resource_version: 0, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -6663,7 +6665,9 @@ mod tests { // credential storage by omitting this advisory list. secret_material_keys: Vec::new(), expires_at_ms: Some(expires_at_ms), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -6678,7 +6682,9 @@ mod tests { authed_request(GetProviderRefreshStatusRequest { provider: "msgraph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -6745,7 +6751,9 @@ mod tests { ]), secret_material_keys: vec!["client_secret".to_string()], expires_at_ms: Some(expires_at_ms), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -6770,7 +6778,9 @@ mod tests { authed_request(DeleteProviderRefreshRequest { provider: "msgraph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -6784,7 +6794,9 @@ mod tests { authed_request(GetProviderRefreshStatusRequest { provider: "msgraph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -6836,7 +6848,9 @@ mod tests { ]), secret_material_keys: vec!["client_secret".to_string()], expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }; handle_configure_provider_refresh(&state, authed_request(request("original-secret"))) .await @@ -6956,7 +6970,9 @@ mod tests { ]), secret_material_keys: vec!["client_secret".to_string()], expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }; let (first_store_hit, release_first_store) = first_state.credentials.gate_next_store(); @@ -7081,7 +7097,9 @@ mod tests { material: HashMap::new(), secret_material_keys: Vec::new(), expires_at_ms: Some(expires_at_ms), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -7156,7 +7174,9 @@ mod tests { authed_request(DeleteProviderRefreshRequest { provider: "provider-a".to_string(), credential_key: "REFRESH_TOKEN".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -7225,7 +7245,9 @@ mod tests { ]), secret_material_keys: vec!["private_key".to_string()], expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -7291,7 +7313,9 @@ mod tests { ]), secret_material_keys: vec!["client_secret".to_string()], expires_at_ms: Some(refresh_expires_at_ms), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -7331,7 +7355,9 @@ mod tests { authed_request(DeleteProviderRefreshRequest { provider: "msgraph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -7394,7 +7420,9 @@ mod tests { )]), secret_material_keys: Vec::new(), expires_at_ms: Some(refresh_expires_at_ms), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -7437,7 +7465,9 @@ mod tests { authed_request(DeleteProviderRefreshRequest { provider: "aws-delete".to_string(), credential_key: "AWS_ACCESS_KEY_ID".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -7615,7 +7645,9 @@ mod tests { ]), secret_material_keys: vec!["client_secret".to_string()], expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -7695,7 +7727,9 @@ mod tests { ]), secret_material_keys: vec!["client_secret".to_string()], expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -7714,7 +7748,9 @@ mod tests { ]), secret_material_keys: vec!["client_secret".to_string()], expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -7777,7 +7813,9 @@ mod tests { ]), secret_material_keys: vec!["client_secret".to_string()], expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -7794,7 +7832,9 @@ mod tests { material: HashMap::from([("tenant_id".to_string(), "tenant".to_string())]), secret_material_keys: vec!["client_secret".to_string()], expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -7848,7 +7888,9 @@ mod tests { material: HashMap::new(), secret_material_keys: Vec::new(), expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -7971,7 +8013,9 @@ mod tests { &task_state, authed_request(CreateProviderRequest { provider: Some(provider), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -8405,7 +8449,9 @@ mod tests { "openai", "OPENAI_API_KEY", )), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -8422,7 +8468,9 @@ mod tests { &state, authed_request(CreateProviderRequest { provider: Some(provider_with_values("legacy-gitlab", "gitlab")), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -8451,7 +8499,9 @@ mod tests { profile_workspace: "default".to_string(), ..Default::default() }), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -8493,7 +8543,9 @@ mod tests { profile_workspace: "default".to_string(), ..Default::default() }), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -8549,7 +8601,9 @@ mod tests { "GITHUB_TOKEN", "test-token", )), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -8595,7 +8649,9 @@ mod tests { "OPENAI_API_KEY", "sk-test", )), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -8710,7 +8766,9 @@ mod tests { "subject_token", "test-token", )), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -8746,7 +8804,9 @@ mod tests { "OPENAI_API_KEY", )), credential_expires_at_ms: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -9708,7 +9768,9 @@ mod tests { ]), secret_material_keys: vec!["client_secret".to_string()], expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }; handle_configure_provider_refresh(&state, authed_request(configure())) .await @@ -9773,7 +9835,9 @@ mod tests { ..Default::default() }), credential_expires_at_ms: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -11587,7 +11651,9 @@ mod tests { "OPENAI_API_KEY", "sk-test", )), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -11611,7 +11677,9 @@ mod tests { authed_request(UpdateProviderRequest { provider: Some(update), credential_expires_at_ms: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -11633,7 +11701,9 @@ mod tests { "OPENAI_API_KEY", "sk-test", )), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -11656,7 +11726,9 @@ mod tests { authed_request(UpdateProviderRequest { provider: Some(update), credential_expires_at_ms: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -11678,7 +11750,9 @@ mod tests { &state, authed_request(CreateProviderRequest { provider: Some(provider.clone()), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -11707,7 +11781,9 @@ mod tests { authed_request(UpdateProviderRequest { provider: Some(updated_provider.clone()), credential_expires_at_ms: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -11744,7 +11820,9 @@ mod tests { &state, authed_request(CreateProviderRequest { provider: Some(provider.clone()), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -11773,7 +11851,9 @@ mod tests { authed_request(UpdateProviderRequest { provider: Some(stale_provider), credential_expires_at_ms: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -11822,7 +11902,9 @@ mod tests { "OPENAI_API_KEY", "sk-first", )), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -11846,7 +11928,9 @@ mod tests { authed_request(UpdateProviderRequest { provider: Some(stale_provider), credential_expires_at_ms: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -11886,7 +11970,9 @@ mod tests { &state, authed_request(CreateProviderRequest { provider: Some(provider.clone()), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -11918,7 +12004,9 @@ mod tests { authed_request(UpdateProviderRequest { provider: Some(updated), credential_expires_at_ms: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12012,7 +12100,9 @@ mod tests { )]), secret_material_keys: Vec::new(), expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12074,7 +12164,9 @@ mod tests { ]), secret_material_keys: Vec::new(), expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12148,7 +12240,9 @@ mod tests { ]), secret_material_keys: Vec::new(), expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12204,7 +12298,9 @@ mod tests { ]), secret_material_keys: vec!["aws_session_token".to_string()], expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12254,7 +12350,9 @@ mod tests { )]), secret_material_keys: Vec::new(), expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12332,7 +12430,9 @@ mod tests { )]), secret_material_keys: Vec::new(), expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12356,7 +12456,9 @@ mod tests { ..Default::default() }), credential_expires_at_ms: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12422,7 +12524,9 @@ mod tests { )]), secret_material_keys: Vec::new(), expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12474,7 +12578,9 @@ mod tests { )]), secret_material_keys: Vec::new(), expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12652,7 +12758,9 @@ mod tests { )]), secret_material_keys: Vec::new(), expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12727,7 +12835,9 @@ mod tests { )]), secret_material_keys: Vec::new(), expires_at_ms: None, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }) }; @@ -12930,12 +13040,14 @@ mod tests { labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), - workspace: String::new(), + workspace: "default".to_string(), deletion_timestamp_ms: 0, }); p }), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12960,12 +13072,14 @@ mod tests { labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), - workspace: String::new(), + workspace: "default".to_string(), deletion_timestamp_ms: 0, }); p }), - workspace: "beta".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "beta".to_string(), + )), }), ) .await @@ -12985,7 +13099,9 @@ mod tests { &state, authed_request(GetProviderRequest { name: "shared-name".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -12997,7 +13113,9 @@ mod tests { &state, authed_request(GetProviderRequest { name: "shared-name".to_string(), - workspace: "beta".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "beta".to_string(), + )), }), ) .await @@ -13011,8 +13129,9 @@ mod tests { authed_request(ListProvidersRequest { limit: 100, offset: 0, - workspace: "default".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -13026,8 +13145,9 @@ mod tests { authed_request(ListProvidersRequest { limit: 100, offset: 0, - workspace: "beta".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "beta".to_string(), + )), }), ) .await @@ -13041,7 +13161,9 @@ mod tests { &state, authed_request(DeleteProviderRequest { name: "shared-name".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -13054,8 +13176,9 @@ mod tests { authed_request(ListProvidersRequest { limit: 100, offset: 0, - workspace: "default".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -13067,7 +13190,9 @@ mod tests { &state, authed_request(GetProviderRequest { name: "shared-name".to_string(), - workspace: "beta".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "beta".to_string(), + )), }), ) .await @@ -13089,12 +13214,14 @@ mod tests { labels: HashMap::new(), resource_version: 0, annotations: HashMap::new(), - workspace: String::new(), + workspace: "default".to_string(), deletion_timestamp_ms: 0, }); p }), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -13105,28 +13232,13 @@ mod tests { authed_request(ListProvidersRequest { limit: 100, offset: 0, - workspace: String::new(), - all_workspaces: true, + workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), }), ) .await .unwrap() .into_inner(); assert_eq!(listed.providers.len(), 2); - - // all_workspaces with non-empty workspace is rejected. - let err = handle_list_providers( - &state, - authed_request(ListProvidersRequest { - limit: 100, - offset: 0, - workspace: "default".to_string(), - all_workspaces: true, - }), - ) - .await - .unwrap_err(); - assert_eq!(err.code(), Code::InvalidArgument); } #[tokio::test] @@ -13938,7 +14050,7 @@ mod tests { let err = handle_create_provider( &state, non_member_request(CreateProviderRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -13953,7 +14065,7 @@ mod tests { let err = handle_get_provider( &state, non_member_request(GetProviderRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -13968,7 +14080,7 @@ mod tests { let err = handle_list_providers( &state, non_member_request(ListProvidersRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -13983,7 +14095,7 @@ mod tests { let err = handle_update_provider( &state, non_member_request(UpdateProviderRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -13998,7 +14110,7 @@ mod tests { let err = handle_get_provider_refresh_status( &state, non_member_request(GetProviderRefreshStatusRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -14013,7 +14125,7 @@ mod tests { let err = handle_configure_provider_refresh( &state, non_member_request(ConfigureProviderRefreshRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -14028,7 +14140,7 @@ mod tests { let err = handle_rotate_provider_credential( &state, non_member_request(RotateProviderCredentialRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -14043,7 +14155,7 @@ mod tests { let err = handle_delete_provider_refresh( &state, non_member_request(DeleteProviderRefreshRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -14058,7 +14170,7 @@ mod tests { let err = handle_delete_provider( &state, non_member_request(DeleteProviderRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index e0ff130ebc..17ae70d2fb 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -11,7 +11,8 @@ use crate::ServerState; use crate::auth::workspace_authz::{ - MinWorkspaceRole, authorize_sandbox_workspace, authorize_workspace, require_platform_admin, + AuthorizedWorkspaceScope, MinWorkspaceRole, authorize_list_workspace_selector, + authorize_sandbox_workspace, authorize_workspace_selector, }; use crate::persistence::{ObjectLabels, ObjectType, WriteCondition, generate_name}; use futures::future; @@ -193,11 +194,11 @@ pub(super) async fn handle_begin_rootfs_tar_staging( let principal = super::extract_principal(&request)?; let request = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &request.workspace, + request.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -330,11 +331,11 @@ async fn handle_create_sandbox_inner( validate_create_sandbox_request_pre_io(&request, &workload_template_name)?; - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &request.workspace, + request.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -665,11 +666,11 @@ pub(super) async fn handle_get_sandbox( if req.name.is_empty() { return Err(Status::invalid_argument("name is required")); } - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -695,15 +696,17 @@ pub(super) async fn handle_list_sandboxes( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let request = request.into_inner(); - if request.all_workspaces && !request.workspace.is_empty() { - return Err(Status::invalid_argument( - "all_workspaces and workspace are mutually exclusive", - )); - } let limit = clamp_limit(request.limit, 100, MAX_PAGE_SIZE); - let sandboxes: Vec = if request.all_workspaces { - require_platform_admin(&state.admin_role, &principal)?; + let scope = authorize_list_workspace_selector( + &state.store, + &state.admin_role, + &principal, + request.workspace_scope.as_ref(), + MinWorkspaceRole::User, + ) + .await?; + let sandboxes: Vec = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { if request.label_selector.is_empty() { state .store @@ -719,14 +722,9 @@ pub(super) async fn handle_list_sandboxes( .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))? } } else { - let authz = authorize_workspace( - &state.store, - &state.admin_role, - &principal, - &request.workspace, - MinWorkspaceRole::User, - ) - .await?; + let AuthorizedWorkspaceScope::Workspace(authz) = scope else { + unreachable!("all-workspaces scope handled above") + }; let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) .await? .name; @@ -766,11 +764,11 @@ pub(super) async fn handle_create_sandbox_template( .template .ok_or_else(|| Status::invalid_argument("template is required"))?; let metadata = template.metadata.clone().unwrap_or_default(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -856,11 +854,11 @@ pub(super) async fn handle_get_sandbox_template( if req.name.is_empty() { return Err(Status::invalid_argument("name is required")); } - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -884,14 +882,16 @@ pub(super) async fn handle_list_sandbox_templates( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let request = request.into_inner(); - if request.all_workspaces && !request.workspace.is_empty() { - return Err(Status::invalid_argument( - "all_workspaces and workspace are mutually exclusive", - )); - } let limit = clamp_limit(request.limit, 100, MAX_PAGE_SIZE); - let templates = if request.all_workspaces { - require_platform_admin(&state.admin_role, &principal)?; + let scope = authorize_list_workspace_selector( + &state.store, + &state.admin_role, + &principal, + request.workspace_scope.as_ref(), + MinWorkspaceRole::User, + ) + .await?; + let templates = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { if request.label_selector.is_empty() { state .store @@ -911,14 +911,9 @@ pub(super) async fn handle_list_sandbox_templates( .map_err(|e| Status::internal(format!("list sandbox templates failed: {e}")))? } } else { - let authz = authorize_workspace( - &state.store, - &state.admin_role, - &principal, - &request.workspace, - MinWorkspaceRole::User, - ) - .await?; + let AuthorizedWorkspaceScope::Workspace(authz) = scope else { + unreachable!("all-workspaces scope handled above") + }; let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) .await? .name; @@ -956,11 +951,11 @@ pub(super) async fn handle_delete_sandbox_template( if req.name.is_empty() { return Err(Status::invalid_argument("name is required")); } - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -1042,11 +1037,11 @@ pub(super) async fn handle_list_sandbox_providers( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -1064,11 +1059,11 @@ pub(super) async fn handle_attach_sandbox_provider( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let request = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &request.workspace, + request.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -1213,11 +1208,11 @@ pub(super) async fn handle_detach_sandbox_provider( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let request = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &request.workspace, + request.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -1333,11 +1328,11 @@ async fn handle_delete_sandbox_inner( if name.is_empty() { return Err(Status::invalid_argument("name is required")); } - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -1381,11 +1376,11 @@ async fn handle_stop_sandbox_inner( if req.name.is_empty() { return Err(Status::invalid_argument("name is required")); } - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -1425,11 +1420,11 @@ async fn handle_start_sandbox_inner( if req.name.is_empty() { return Err(Status::invalid_argument("name is required")); } - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -3164,6 +3159,7 @@ mod tests { ..SandboxSpec::default() }), workload_template_name: "gpu-kata".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..CreateSandboxRequest::default() }; let created = Sandbox { @@ -3201,6 +3197,7 @@ mod tests { ..SandboxSpec::default() }), workload_template_name: "missing-template".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..CreateSandboxRequest::default() }; @@ -3633,7 +3630,9 @@ mod tests { &delete_state, authed_request(DeleteSandboxRequest { name: "reused-name".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -3692,7 +3691,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -3733,7 +3732,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -3771,7 +3770,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -3822,7 +3821,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -3847,7 +3846,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -3894,7 +3893,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "work-gcp".to_string(), expected_resource_version: 0, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -3932,7 +3931,7 @@ mod tests { &state, authed_request(ListSandboxProvidersRequest { sandbox_name: "work".to_string(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -3962,7 +3961,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "missing".to_string(), expected_resource_version: 0, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -4137,7 +4136,7 @@ mod tests { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), await_main_process_attachment: false, workload_template_name: String::new(), }), @@ -4162,7 +4161,7 @@ mod tests { spec: Some(SandboxSpec::default()), labels: HashMap::new(), annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), await_main_process_attachment: false, workload_template_name: String::new(), }), @@ -4199,7 +4198,7 @@ mod tests { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), await_main_process_attachment: false, workload_template_name: String::new(), }), @@ -4306,7 +4305,7 @@ mod tests { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() }), ) @@ -4363,7 +4362,7 @@ mod tests { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() }), ) @@ -4462,7 +4461,7 @@ mod tests { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() }), ) @@ -4530,7 +4529,7 @@ mod tests { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() }), ) @@ -4563,7 +4562,7 @@ mod tests { spec: Some(SandboxSpec::default()), labels: HashMap::new(), annotations: HashMap::from([(annotation_key.clone(), annotation_value.clone())]), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), await_main_process_attachment: false, workload_template_name: String::new(), }), @@ -4585,7 +4584,7 @@ mod tests { &state, authed_request(GetSandboxRequest { name: "annotated".to_string(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -4624,7 +4623,7 @@ mod tests { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), await_main_process_attachment: false, workload_template_name: String::new(), }), @@ -4649,7 +4648,7 @@ mod tests { &state, authed_request(GetSandboxRequest { name: "partial-id".to_string(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -4689,7 +4688,7 @@ mod tests { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), await_main_process_attachment: false, workload_template_name: String::new(), }), @@ -4721,7 +4720,7 @@ mod tests { spec: Some(SandboxSpec::default()), labels: HashMap::from([("team".to_string(), "x".repeat(512))]), annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), await_main_process_attachment: false, workload_template_name: String::new(), }), @@ -4755,7 +4754,7 @@ mod tests { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), await_main_process_attachment: false, workload_template_name: String::new(), }), @@ -4790,7 +4789,9 @@ mod tests { &state, authed_request(CreateSandboxTemplateRequest { template: Some(test_workload_template("gpu-kata")), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -4809,7 +4810,9 @@ mod tests { &state, authed_request(GetSandboxTemplateRequest { name: "gpu-kata".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -4825,8 +4828,9 @@ mod tests { authed_request(ListSandboxTemplatesRequest { limit: 100, offset: 0, - workspace: "default".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), label_selector: String::new(), }), ) @@ -4841,7 +4845,9 @@ mod tests { &state, authed_request(DeleteSandboxTemplateRequest { name: "gpu-kata".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -4853,7 +4859,9 @@ mod tests { &state, authed_request(GetSandboxTemplateRequest { name: "gpu-kata".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -4875,7 +4883,9 @@ mod tests { &state, authed_request(CreateSandboxTemplateRequest { template: Some(gpu), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -4891,7 +4901,9 @@ mod tests { &state, authed_request(CreateSandboxTemplateRequest { template: Some(cpu), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -4902,8 +4914,9 @@ mod tests { authed_request(ListSandboxTemplatesRequest { limit: 100, offset: 0, - workspace: "default".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), label_selector: "team=runtime".to_string(), }), ) @@ -4924,7 +4937,9 @@ mod tests { &state, authed_request(CreateSandboxTemplateRequest { template: Some(test_workload_template(" gpu-kata ")), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -4938,8 +4953,9 @@ mod tests { authed_request(ListSandboxTemplatesRequest { limit: 100, offset: 0, - workspace: "default".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), label_selector: String::new(), }), ) @@ -4972,7 +4988,7 @@ mod tests { &state, authed_request(CreateSandboxTemplateRequest { template: Some(template), - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -4986,8 +5002,9 @@ mod tests { authed_request(ListSandboxTemplatesRequest { limit: 100, offset: 0, - workspace: "beta".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "beta".to_string(), + )), label_selector: String::new(), }), ) @@ -5008,7 +5025,9 @@ mod tests { &state, authed_request(CreateSandboxTemplateRequest { template: Some(template), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -5145,7 +5164,9 @@ mod tests { &state, authed_request(CreateSandboxTemplateRequest { template: Some(test_workload_template("overflow")), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -5174,7 +5195,9 @@ mod tests { &state, authed_request(CreateSandboxTemplateRequest { template: Some(test_workload_template(&format!("overflow-{index}"))), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -5272,7 +5295,9 @@ mod tests { &state, authed_request(CreateSandboxTemplateRequest { template: Some(test_workload_template("gpu-kata")), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -5303,7 +5328,9 @@ mod tests { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), workload_template_name: "gpu-kata".to_string(), await_main_process_attachment: false, }), @@ -5372,7 +5399,9 @@ mod tests { &state, authed_request(CreateSandboxTemplateRequest { template: Some(template), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -5385,7 +5414,9 @@ mod tests { spec: Some(SandboxSpec::default()), labels: HashMap::new(), annotations: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), workload_template_name: "default-image".to_string(), await_main_process_attachment: false, }), @@ -5419,7 +5450,9 @@ mod tests { &state, authed_request(CreateSandboxTemplateRequest { template: Some(template), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -5432,7 +5465,9 @@ mod tests { spec: Some(SandboxSpec::default()), labels: HashMap::new(), annotations: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), workload_template_name: "default-gpu".to_string(), await_main_process_attachment: false, }), @@ -5469,7 +5504,9 @@ mod tests { spec: Some(SandboxSpec::default()), labels: HashMap::new(), annotations: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), workload_template_name: "corrupt-template".to_string(), await_main_process_attachment: false, }), @@ -5488,7 +5525,9 @@ mod tests { &state, authed_request(CreateSandboxTemplateRequest { template: Some(test_workload_template("gpu-kata")), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -5504,7 +5543,9 @@ mod tests { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), workload_template_name: "gpu-kata".to_string(), await_main_process_attachment: false, }), @@ -5527,7 +5568,9 @@ mod tests { spec: Some(SandboxSpec::default()), labels: HashMap::new(), annotations: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), workload_template_name: "Invalid_Template_Name".to_string(), await_main_process_attachment: false, }), @@ -5553,7 +5596,9 @@ mod tests { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), workload_template_name: "missing-template".to_string(), await_main_process_attachment: false, }), @@ -5579,7 +5624,9 @@ mod tests { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: "missing-workspace".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "missing-workspace".to_string(), + )), workload_template_name: String::new(), await_main_process_attachment: false, }), @@ -5616,7 +5663,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "provider-b".to_string(), expected_resource_version: 0, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -5663,7 +5710,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "provider-31".to_string(), expected_resource_version: 0, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -5718,7 +5765,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "provider-32".to_string(), expected_resource_version: 0, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -5765,7 +5812,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: long_name, expected_resource_version: 0, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -5792,7 +5839,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: long_name, expected_resource_version: 0, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -5991,7 +6038,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "github".to_string(), expected_resource_version: current_version, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -6043,7 +6090,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "github".to_string(), expected_resource_version: 99, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -6106,7 +6153,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "github".to_string(), expected_resource_version: current_version, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -6158,7 +6205,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: "github".to_string(), expected_resource_version: 99, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -6239,7 +6286,7 @@ mod tests { sandbox_name: "work".to_string(), provider_name: format!("provider-{i}"), expected_resource_version: initial_version, - workspace: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), ) .await @@ -6323,7 +6370,9 @@ mod tests { &state, authed_request(GetSandboxRequest { name: "shared-name".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -6336,7 +6385,9 @@ mod tests { &state, authed_request(GetSandboxRequest { name: "shared-name".to_string(), - workspace: "beta".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "beta".to_string(), + )), }), ) .await @@ -6351,8 +6402,9 @@ mod tests { limit: 100, offset: 0, label_selector: String::new(), - workspace: "default".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -6368,8 +6420,9 @@ mod tests { limit: 100, offset: 0, label_selector: String::new(), - workspace: "beta".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "beta".to_string(), + )), }), ) .await @@ -6392,8 +6445,9 @@ mod tests { limit: 100, offset: 0, label_selector: String::new(), - workspace: "default".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -6406,7 +6460,9 @@ mod tests { &state, authed_request(GetSandboxRequest { name: "shared-name".to_string(), - workspace: "beta".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "beta".to_string(), + )), }), ) .await @@ -6434,29 +6490,13 @@ mod tests { limit: 100, offset: 0, label_selector: String::new(), - workspace: String::new(), - all_workspaces: true, + workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), }), ) .await .unwrap() .into_inner(); assert_eq!(listed.sandboxes.len(), 2); - - // all_workspaces with non-empty workspace is rejected. - let err = handle_list_sandboxes( - &state, - authed_request(ListSandboxesRequest { - limit: 100, - offset: 0, - label_selector: String::new(), - workspace: "default".to_string(), - all_workspaces: true, - }), - ) - .await - .unwrap_err(); - assert_eq!(err.code(), tonic::Code::InvalidArgument); } /// Non-members must receive `PERMISSION_DENIED` — never `NOT_FOUND` — when @@ -6492,7 +6532,7 @@ mod tests { let err = handle_create_sandbox( &state, non_member_request(CreateSandboxRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), spec: Some(SandboxSpec::default()), ..Default::default() }), @@ -6510,7 +6550,7 @@ mod tests { let err = handle_get_sandbox( &state, non_member_request(GetSandboxRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), name: "any".into(), }), ) @@ -6526,7 +6566,7 @@ mod tests { let err = handle_list_sandboxes( &state, non_member_request(ListSandboxesRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -6542,7 +6582,7 @@ mod tests { let err = handle_list_sandbox_providers( &state, non_member_request(ListSandboxProvidersRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -6558,7 +6598,7 @@ mod tests { let err = handle_attach_sandbox_provider( &state, non_member_request(AttachSandboxProviderRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -6574,7 +6614,7 @@ mod tests { let err = handle_detach_sandbox_provider( &state, non_member_request(DetachSandboxProviderRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -6591,7 +6631,7 @@ mod tests { let err = handle_delete_sandbox( &state, non_member_request(DeleteSandboxRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), name: "any".into(), }), ) @@ -6607,7 +6647,7 @@ mod tests { handle_stop_sandbox( &state, non_member_request(StopSandboxRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), name: "any".into(), }), ) @@ -6615,7 +6655,7 @@ mod tests { handle_start_sandbox( &state, non_member_request(StartSandboxRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), name: "any".into(), }), ) diff --git a/crates/openshell-server/src/grpc/service.rs b/crates/openshell-server/src/grpc/service.rs index 790e26d618..34c7d62d3f 100644 --- a/crates/openshell-server/src/grpc/service.rs +++ b/crates/openshell-server/src/grpc/service.rs @@ -15,7 +15,10 @@ use tonic::{Request, Response, Status}; use uuid::Uuid; use crate::ServerState; -use crate::auth::workspace_authz::{MinWorkspaceRole, authorize_workspace, require_platform_admin}; +use crate::auth::workspace_authz::{ + AuthorizedWorkspaceScope, MinWorkspaceRole, authorize_list_workspace_selector, + authorize_workspace_selector, +}; use crate::persistence::{ObjectType, WriteCondition}; use crate::service_routing; @@ -28,11 +31,11 @@ pub(super) async fn handle_expose_service( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -147,11 +150,11 @@ pub(super) async fn handle_get_service( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -174,54 +177,53 @@ pub(super) async fn handle_list_services( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - if req.all_workspaces && !req.workspace.is_empty() { - return Err(Status::invalid_argument( - "all_workspaces and workspace are mutually exclusive", - )); - } if !req.sandbox.is_empty() { validate_endpoint_name("sandbox", &req.sandbox, MAX_SANDBOX_NAME_LEN)?; } let limit = super::clamp_limit(req.limit, 100, super::MAX_PAGE_SIZE); - let endpoints: Vec = if req.all_workspaces { - require_platform_admin(&state.admin_role, &principal)?; - if !req.sandbox.is_empty() { - return Err(Status::invalid_argument( - "sandbox filter is not supported with all_workspaces", - )); - } - state.store.list_all_messages(limit, req.offset).await - } else { - let authz = authorize_workspace( - &state.store, - &state.admin_role, - &principal, - &req.workspace, - MinWorkspaceRole::User, - ) - .await?; - let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) - .await? - .name; - if req.sandbox.is_empty() { - state - .store - .list_messages(&workspace, limit, req.offset) - .await + let scope = authorize_list_workspace_selector( + &state.store, + &state.admin_role, + &principal, + req.workspace_scope.as_ref(), + MinWorkspaceRole::User, + ) + .await?; + let endpoints: Vec = + if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { + if !req.sandbox.is_empty() { + return Err(Status::invalid_argument( + "sandbox filter is not supported with all_workspaces", + )); + } + state.store.list_all_messages(limit, req.offset).await } else { - state - .store - .list_messages_with_selector( - &workspace, - &format!("sandbox={}", req.sandbox), - limit, - req.offset, - ) - .await + let AuthorizedWorkspaceScope::Workspace(authz) = scope else { + unreachable!("all-workspaces scope handled above") + }; + let workspace = + super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) + .await? + .name; + if req.sandbox.is_empty() { + state + .store + .list_messages(&workspace, limit, req.offset) + .await + } else { + state + .store + .list_messages_with_selector( + &workspace, + &format!("sandbox={}", req.sandbox), + limit, + req.offset, + ) + .await + } } - } - .map_err(|e| Status::internal(format!("list endpoints failed: {e}")))?; + .map_err(|e| Status::internal(format!("list endpoints failed: {e}")))?; let services = endpoints .into_iter() @@ -237,11 +239,11 @@ pub(super) async fn handle_delete_service( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); - let authz = authorize_workspace( + let authz = authorize_workspace_selector( &state.store, &state.admin_role, &principal, - &req.workspace, + req.workspace_scope.as_ref(), MinWorkspaceRole::User, ) .await?; @@ -413,7 +415,9 @@ mod tests { service: "web".to_string(), target_port: 8080, domain: true, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -427,8 +431,9 @@ mod tests { sandbox: "my-sandbox".to_string(), limit: 0, offset: 0, - workspace: "default".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -445,7 +450,9 @@ mod tests { authed_request(GetServiceRequest { sandbox: "my-sandbox".to_string(), service: "web".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -458,7 +465,9 @@ mod tests { authed_request(DeleteServiceRequest { sandbox: "my-sandbox".to_string(), service: "web".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -471,7 +480,9 @@ mod tests { authed_request(GetServiceRequest { sandbox: "my-sandbox".to_string(), service: "web".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -484,8 +495,9 @@ mod tests { sandbox: "my-sandbox".to_string(), limit: 0, offset: 0, - workspace: "default".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -509,7 +521,9 @@ mod tests { service: "web".to_string(), target_port: 8080, domain: true, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -524,7 +538,9 @@ mod tests { service: "web".to_string(), target_port: 9090, domain: true, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -549,8 +565,9 @@ mod tests { sandbox: "my-sandbox".to_string(), limit: 0, offset: 0, - workspace: "default".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -572,7 +589,9 @@ mod tests { service: "web".to_string(), target_port: 7070, domain: true, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -588,7 +607,9 @@ mod tests { service: "web".to_string(), target_port: 8080, domain: true, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -603,7 +624,9 @@ mod tests { service: "web".to_string(), target_port: 9090, domain: true, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -626,7 +649,9 @@ mod tests { authed_request(GetServiceRequest { sandbox: "my-sandbox".to_string(), service: "web".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -687,7 +712,9 @@ mod tests { service: "web".to_string(), target_port: 8080, domain: true, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -700,7 +727,9 @@ mod tests { service: "web".to_string(), target_port: 9090, domain: true, - workspace: "beta".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "beta".to_string(), + )), }), ) .await @@ -712,7 +741,9 @@ mod tests { authed_request(GetServiceRequest { sandbox: "my-sandbox".to_string(), service: "web".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -726,7 +757,9 @@ mod tests { authed_request(GetServiceRequest { sandbox: "my-sandbox".to_string(), service: "web".to_string(), - workspace: "beta".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "beta".to_string(), + )), }), ) .await @@ -741,8 +774,9 @@ mod tests { sandbox: "my-sandbox".to_string(), limit: 100, offset: 0, - workspace: "default".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -760,8 +794,9 @@ mod tests { sandbox: "my-sandbox".to_string(), limit: 100, offset: 0, - workspace: "beta".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "beta".to_string(), + )), }), ) .await @@ -779,7 +814,9 @@ mod tests { authed_request(DeleteServiceRequest { sandbox: "my-sandbox".to_string(), service: "web".to_string(), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -793,8 +830,9 @@ mod tests { sandbox: "my-sandbox".to_string(), limit: 100, offset: 0, - workspace: "default".to_string(), - all_workspaces: false, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -807,7 +845,9 @@ mod tests { authed_request(GetServiceRequest { sandbox: "my-sandbox".to_string(), service: "web".to_string(), - workspace: "beta".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "beta".to_string(), + )), }), ) .await @@ -824,7 +864,9 @@ mod tests { service: "api".to_string(), target_port: 3000, domain: true, - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), }), ) .await @@ -836,29 +878,13 @@ mod tests { sandbox: String::new(), limit: 100, offset: 0, - workspace: String::new(), - all_workspaces: true, + workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), }), ) .await .unwrap() .into_inner(); assert_eq!(listed.services.len(), 2); - - // all_workspaces with non-empty workspace is rejected. - let err = handle_list_services( - &state, - authed_request(ListServicesRequest { - sandbox: String::new(), - limit: 100, - offset: 0, - workspace: "default".to_string(), - all_workspaces: true, - }), - ) - .await - .unwrap_err(); - assert_eq!(err.code(), tonic::Code::InvalidArgument); } /// Non-member callers must receive `PERMISSION_DENIED` — not `NOT_FOUND` — @@ -889,7 +915,7 @@ mod tests { let err = handle_expose_service( &state, non_member_request(ExposeServiceRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -905,7 +931,7 @@ mod tests { let err = handle_get_service( &state, non_member_request(GetServiceRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -921,7 +947,7 @@ mod tests { let err = handle_list_services( &state, non_member_request(ListServicesRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) @@ -937,7 +963,7 @@ mod tests { let err = handle_delete_service( &state, non_member_request(DeleteServiceRequest { - workspace: "no-such-ws".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), ..Default::default() }), ) diff --git a/crates/openshell-server/src/grpc/workspace.rs b/crates/openshell-server/src/grpc/workspace.rs index f360cb6c1d..546934a6ed 100644 --- a/crates/openshell-server/src/grpc/workspace.rs +++ b/crates/openshell-server/src/grpc/workspace.rs @@ -70,7 +70,7 @@ fn membership_filter_subject<'a>( } } -fn validate_workspace_name(name: &str) -> Result<(), Status> { +pub fn validate_workspace_name(name: &str) -> Result<(), Status> { if name.is_empty() { return Err(Status::invalid_argument("workspace name is required")); } diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 21315f9830..f03aa4d07f 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -48,7 +48,7 @@ use crate::{ auth::identity::Identity, auth::oidc::{self, OidcAuthenticator}, auth::principal::{Principal, UserPrincipal}, - auth::workspace_authz::{MinWorkspaceRole, authorize_workspace}, + auth::workspace_authz::{MinWorkspaceRole, authorize_workspace_selector}, gateway_listener::GatewayListenerScope, http_router, service_http_router, }; @@ -552,11 +552,11 @@ async fn hydrate_update_provider_identity( let principal = principal.ok_or_else(|| tonic::Status::unauthenticated("authentication required"))?; - let authorized = authorize_workspace( + let authorized = authorize_workspace_selector( state.store.as_ref(), &state.admin_role, principal, - &request.workspace, + request.workspace_scope.as_ref(), MinWorkspaceRole::Admin, ) .await?; @@ -1740,7 +1740,9 @@ mod tests { )]), ..Default::default() }), - workspace: "default".to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), ..Default::default() }; let authed = crate::grpc::test_support::authed_request(()); diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 0d6d33c01f..cd5e065dee 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -119,7 +119,7 @@ mod tests { const STORAGE_V1_SCHEMA_SHA256: &str = "79c72615d957fc0653c672f61998bf7d8d21b757bc05d07b3fff92bd70fc8f52"; const PUBLIC_RPC_SCHEMA_SHA256: &str = - "042034fe4d0000279ee4ed27e587ab8e530934b8d5c3aa36dc9769f81dfa6e51"; + "c95ae90962c10fb28747db2b645adf4044562a3d208d84dfe4699d677e4364ee"; const DURABLE_SCHEMA_SHA256: &str = "920a5243dfb37ce709f0f562a47d17791a5ede90fd7f662ed01542abd60a0dfb"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = @@ -487,7 +487,7 @@ mod tests { assert_eq!( (public_closure.messages.len(), public_closure.enums.len()), - (276, 12) + (278, 12) ); assert_eq!( (durable_closure.messages.len(), durable_closure.enums.len()), diff --git a/crates/openshell-tui/src/lib.rs b/crates/openshell-tui/src/lib.rs index 174f9910d0..2ab19d89d7 100644 --- a/crates/openshell-tui/src/lib.rs +++ b/crates/openshell-tui/src/lib.rs @@ -40,6 +40,21 @@ const PROVIDER_PROFILE_PAGE_SIZE: u32 = 100; type ProviderProfileCache = HashMap<(String, String), openshell_core::proto::ProviderProfile>; +fn named_workspace_scope(workspace: impl Into) -> openshell_core::proto::WorkspaceSelector { + openshell_core::proto::workspace_selector(workspace) +} + +fn list_workspace_scope( + workspace: impl Into, + all_workspaces: bool, +) -> openshell_core::proto::WorkspaceSelector { + if all_workspaces { + openshell_core::proto::all_workspaces_selector() + } else { + openshell_core::proto::workspace_selector(workspace) + } +} + // Re-export for use by the CLI crate. pub use theme::ThemeMode; @@ -648,7 +663,7 @@ fn spawn_log_stream(app: &mut App, tx: mpsc::UnboundedSender) { since_ms: 0, sources: vec![], min_level: String::new(), - workspace, + workspace_scope: Some(named_workspace_scope(workspace)), }; match tokio::time::timeout(Duration::from_secs(5), client.get_sandbox_logs(req)).await { @@ -751,7 +766,7 @@ async fn handle_sandbox_delete(app: &mut App) { let req = openshell_core::proto::DeleteSandboxRequest { name: sandbox_name, - workspace: app.selected_sandbox_workspace(), + workspace_scope: Some(named_workspace_scope(app.selected_sandbox_workspace())), }; match app.client.delete_sandbox(req).await { Ok(_) => { @@ -784,7 +799,7 @@ async fn fetch_sandbox_detail(app: &mut App) { let req = openshell_core::proto::GetSandboxRequest { name: sandbox_name.clone(), - workspace: app.selected_sandbox_workspace(), + workspace_scope: Some(named_workspace_scope(app.selected_sandbox_workspace())), }; // Step 1: Fetch sandbox metadata (providers, sandbox ID). @@ -870,7 +885,7 @@ async fn handle_shell_connect( let sandbox_id = { let req = openshell_core::proto::GetSandboxRequest { name: sandbox_name.clone(), - workspace: app.selected_sandbox_workspace(), + workspace_scope: Some(named_workspace_scope(app.selected_sandbox_workspace())), }; match tokio::time::timeout(Duration::from_secs(5), app.client.get_sandbox(req)).await { Ok(Ok(resp)) => { @@ -1027,7 +1042,7 @@ async fn handle_exec_command( let sandbox_id = { let req = openshell_core::proto::GetSandboxRequest { name: sandbox_name.to_string(), - workspace: workspace.to_string(), + workspace_scope: Some(named_workspace_scope(workspace)), }; match tokio::time::timeout(Duration::from_secs(5), app.client.get_sandbox(req)).await { Ok(Ok(resp)) => { @@ -1403,7 +1418,7 @@ fn spawn_create_sandbox(app: &mut App, tx: mpsc::UnboundedSender) { }), labels: HashMap::new(), annotations: HashMap::new(), - workspace: workspace.clone(), + workspace_scope: Some(named_workspace_scope(&workspace)), await_main_process_attachment: false, workload_template_name: String::new(), }; @@ -1446,7 +1461,7 @@ fn spawn_create_sandbox(app: &mut App, tx: mpsc::UnboundedSender) { let req = openshell_core::proto::GetSandboxRequest { name: sandbox_name.clone(), - workspace: workspace.clone(), + workspace_scope: Some(named_workspace_scope(&workspace)), }; // Retry on transient errors. if let Ok(resp) = client.get_sandbox(req).await @@ -1688,7 +1703,7 @@ fn spawn_create_provider(app: &App, tx: mpsc::UnboundedSender) { profile_workspace: workspace.clone(), credential_handles: HashMap::default(), }), - workspace: workspace.clone(), + workspace_scope: Some(named_workspace_scope(&workspace)), }; match client.create_provider(req).await { @@ -1729,7 +1744,10 @@ fn spawn_get_provider(app: &App, tx: mpsc::UnboundedSender) { let workspace = app.selected_provider_workspace(); tokio::spawn(async move { - let req = openshell_core::proto::GetProviderRequest { name, workspace }; + let req = openshell_core::proto::GetProviderRequest { + name, + workspace_scope: Some(named_workspace_scope(workspace)), + }; match tokio::time::timeout(Duration::from_secs(5), client.get_provider(req)).await { Ok(Ok(resp)) => { if let Some(provider) = resp.into_inner().provider { @@ -1803,7 +1821,7 @@ fn spawn_update_provider(app: &App, tx: mpsc::UnboundedSender) { credential_handles: HashMap::default(), }), credential_expires_at_ms: HashMap::default(), - workspace, + workspace_scope: Some(named_workspace_scope(workspace)), }; match tokio::time::timeout(Duration::from_secs(5), client.update_provider(req)).await { @@ -1832,7 +1850,10 @@ fn spawn_delete_provider(app: &App, tx: mpsc::UnboundedSender) { let workspace = app.selected_provider_workspace(); tokio::spawn(async move { - let req = openshell_core::proto::DeleteProviderRequest { name, workspace }; + let req = openshell_core::proto::DeleteProviderRequest { + name, + workspace_scope: Some(named_workspace_scope(workspace)), + }; match tokio::time::timeout(Duration::from_secs(5), client.delete_provider(req)).await { Ok(Ok(resp)) => { let _ = tx.send(Event::ProviderDeleteResult(Ok(resp.into_inner().deleted))); @@ -1875,7 +1896,7 @@ fn spawn_draft_approve(app: &App, tx: mpsc::UnboundedSender) { let req = openshell_core::proto::ApproveDraftChunkRequest { name, chunk_id, - workspace, + workspace_scope: Some(named_workspace_scope(workspace)), review_token, }; match tokio::time::timeout(Duration::from_secs(5), client.approve_draft_chunk(req)).await { @@ -1921,7 +1942,7 @@ fn spawn_draft_reject(app: &App, tx: mpsc::UnboundedSender) { name, chunk_id, reason: String::new(), - workspace, + workspace_scope: Some(named_workspace_scope(workspace)), }; match tokio::time::timeout(Duration::from_secs(5), client.reject_draft_chunk(req)).await { Ok(Ok(_)) => { @@ -1970,7 +1991,7 @@ fn spawn_draft_approve_all( let req = openshell_core::proto::ApproveAllDraftChunksRequest { name, include_security_flagged: false, - workspace, + workspace_scope: Some(named_workspace_scope(workspace)), approvals, }; match tokio::time::timeout( @@ -2094,12 +2115,10 @@ async fn refresh_providers(app: &mut App) { let req = openshell_core::proto::ListProvidersRequest { limit: 100, offset: 0, - workspace: if app.all_workspaces { - String::new() - } else { - app.current_workspace.clone() - }, - all_workspaces: app.all_workspaces, + workspace_scope: Some(list_workspace_scope( + &app.current_workspace, + app.all_workspaces, + )), }; let response = match tokio::time::timeout(Duration::from_secs(5), app.client.list_providers(req)).await { @@ -2247,7 +2266,7 @@ async fn refresh_global_settings(app: &mut App) { limit: 1, offset: 0, global: true, - workspace: String::new(), + workspace_scope: None, }; match tokio::time::timeout( Duration::from_secs(5), @@ -2327,7 +2346,6 @@ fn spawn_set_global_setting(app: &App, tx: mpsc::UnboundedSender) { setting_key: key, setting_value: Some(SettingValue { value: Some(value) }), global: true, - workspace: String::new(), ..Default::default() }; @@ -2361,7 +2379,6 @@ fn spawn_delete_global_setting(app: &App, tx: mpsc::UnboundedSender) { setting_key: key, delete_setting: true, global: true, - workspace: String::new(), ..Default::default() }; @@ -2429,7 +2446,7 @@ fn spawn_set_sandbox_setting(app: &App, tx: mpsc::UnboundedSender) { name, setting_key: key, setting_value: Some(SettingValue { value: Some(value) }), - workspace, + workspace_scope: Some(named_workspace_scope(workspace)), ..Default::default() }; @@ -2467,7 +2484,7 @@ fn spawn_delete_sandbox_setting(app: &App, tx: mpsc::UnboundedSender) { name, setting_key: key, delete_setting: true, - workspace, + workspace_scope: Some(named_workspace_scope(workspace)), ..Default::default() }; @@ -2511,12 +2528,10 @@ async fn refresh_sandboxes(app: &mut App) { limit: 100, offset: 0, label_selector: String::new(), - workspace: if app.all_workspaces { - String::new() - } else { - app.current_workspace.clone() - }, - all_workspaces: app.all_workspaces, + workspace_scope: Some(list_workspace_scope( + &app.current_workspace, + app.all_workspaces, + )), }; let result = tokio::time::timeout(Duration::from_secs(5), app.client.list_sandboxes(req)).await; match result { @@ -2665,7 +2680,7 @@ async fn refresh_draft_chunks(app: &mut App) { let req = openshell_core::proto::GetDraftPolicyRequest { name: sandbox_name, status_filter: String::new(), - workspace: app.selected_sandbox_workspace(), + workspace_scope: Some(named_workspace_scope(app.selected_sandbox_workspace())), }; if let Ok(Ok(resp)) = @@ -2696,7 +2711,7 @@ async fn refresh_sandbox_draft_counts(app: &mut App) { let req = openshell_core::proto::GetDraftPolicyRequest { name: name.clone(), status_filter: "pending".to_string(), - workspace: ws, + workspace_scope: Some(named_workspace_scope(ws)), }; if let Ok(Ok(resp)) = tokio::time::timeout(Duration::from_secs(2), app.client.get_draft_policy(req)).await diff --git a/docs/sandboxes/manage-workspaces.mdx b/docs/sandboxes/manage-workspaces.mdx index 2212eb93e7..003201ac21 100644 --- a/docs/sandboxes/manage-workspaces.mdx +++ b/docs/sandboxes/manage-workspaces.mdx @@ -149,8 +149,9 @@ export OPENSHELL_WORKSPACE=team-ml openshell sandbox list ``` -An empty workspace value resolves to `default`. It never means all -workspaces. +When `--workspace` is omitted, the CLI intentionally selects the `default` +workspace. An empty workspace name is invalid and never means either `default` +or all workspaces. Platform Admins can opt into cross-workspace list operations: @@ -160,6 +161,29 @@ openshell provider list --all-workspaces openshell service list --all-workspaces ``` +The public API represents this choice with a `WorkspaceSelector` oneof. Set +`workspace` to a non-empty name, including the literal `default`, or set the +`all_workspaces` marker on list requests that support it. Omitting the selector +or sending an unset selector is invalid for workspace-scoped operations. The +all-workspaces variant is accepted only by sandbox, sandbox template, provider, +and service list requests, and it requires Platform Admin access. + +Clients migrating from the previous request fields should make the scope +explicit: + +| Previous request | Typed selector | +| --- | --- | +| `workspace: "team-ml"` | `workspace_scope.workspace: "team-ml"` | +| Empty or omitted `workspace` for the default | `workspace_scope.workspace: "default"` | +| `all_workspaces: true` | `workspace_scope.all_workspaces: {}` | +| `global: true` | Omit `workspace_scope` | + +The Rust and Python SDKs expose separate all-workspaces list methods. The Go +SDK uses `ListAll`, and the TypeScript SDK uses a discriminated option type, so +a caller cannot select a named workspace and all workspaces in one typed call. +The TUI starts in the `default` workspace and sends that named selector +explicitly. Its all-workspaces view sends the marker instead. + Provider profiles and policy also have explicit `--global` operations. Those operations target platform scope and require Platform Admin access. A Workspace Admin should use `--workspace` for workspace-scoped profiles and diff --git a/e2e/python/oidc/oidc_auth_test.py b/e2e/python/oidc/oidc_auth_test.py index 39cd076af0..06b5199a6f 100644 --- a/e2e/python/oidc/oidc_auth_test.py +++ b/e2e/python/oidc/oidc_auth_test.py @@ -51,11 +51,12 @@ def test_admin_can_create_provider(self) -> None: token = get_token("admin@test", "admin", scopes="openid openshell:all") stub, metadata = stub_with_token(token) req = openshell_pb2.CreateProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta(name="e2e-oidc-admin-test"), type="claude", credentials={"ANTHROPIC_API_KEY": "test-value"}, - ) + ), ) try: stub.CreateProvider(req, metadata=metadata) @@ -67,7 +68,12 @@ def test_admin_can_create_provider(self) -> None: finally: with contextlib.suppress(grpc.RpcError): stub.DeleteProvider( - openshell_pb2.DeleteProviderRequest(name="e2e-oidc-admin-test"), + openshell_pb2.DeleteProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector( + workspace="default" + ), + name="e2e-oidc-admin-test", + ), metadata=metadata, ) @@ -75,11 +81,12 @@ def test_user_cannot_create_provider(self) -> None: token = get_token("user@test", "user", scopes="openid openshell:all") stub, metadata = stub_with_token(token) req = openshell_pb2.CreateProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta(name="e2e-oidc-user-blocked"), type="claude", credentials={"ANTHROPIC_API_KEY": "test-value"}, - ) + ), ) with pytest.raises(grpc.RpcError) as exc_info: stub.CreateProvider(req, metadata=metadata) @@ -103,7 +110,10 @@ def test_user_can_list_sandboxes(self) -> None: ) try: user_stub.ListSandboxes( - openshell_pb2.ListSandboxesRequest(), metadata=user_md + openshell_pb2.ListSandboxesRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default") + ), + metadata=user_md, ) finally: with contextlib.suppress(grpc.RpcError): @@ -118,7 +128,11 @@ def test_request_without_bearer_token_rejected(self) -> None: channel = grpc_channel() stub = openshell_pb2_grpc.OpenShellStub(channel) with pytest.raises(grpc.RpcError) as exc_info: - stub.ListSandboxes(openshell_pb2.ListSandboxesRequest()) + stub.ListSandboxes( + openshell_pb2.ListSandboxesRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default") + ) + ) assert exc_info.value.code() in ( grpc.StatusCode.UNAUTHENTICATED, grpc.StatusCode.PERMISSION_DENIED, @@ -151,7 +165,12 @@ def test_sandbox_scoped_token_can_list_sandboxes(self) -> None: "admin@test", "admin", scopes="openid sandbox:read sandbox:write" ) stub, metadata = stub_with_token(token) - stub.ListSandboxes(openshell_pb2.ListSandboxesRequest(), metadata=metadata) + stub.ListSandboxes( + openshell_pb2.ListSandboxesRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default") + ), + metadata=metadata, + ) def test_sandbox_scoped_token_cannot_list_providers(self) -> None: token = get_token( @@ -159,21 +178,41 @@ def test_sandbox_scoped_token_cannot_list_providers(self) -> None: ) stub, metadata = stub_with_token(token) with pytest.raises(grpc.RpcError) as exc_info: - stub.ListProviders(openshell_pb2.ListProvidersRequest(), metadata=metadata) + stub.ListProviders( + openshell_pb2.ListProvidersRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default") + ), + metadata=metadata, + ) assert exc_info.value.code() == grpc.StatusCode.PERMISSION_DENIED assert "provider:read" in exc_info.value.details() def test_openshell_all_grants_full_access(self) -> None: token = get_token("admin@test", "admin", scopes="openid openshell:all") stub, metadata = stub_with_token(token) - stub.ListSandboxes(openshell_pb2.ListSandboxesRequest(), metadata=metadata) - stub.ListProviders(openshell_pb2.ListProvidersRequest(), metadata=metadata) + stub.ListSandboxes( + openshell_pb2.ListSandboxesRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default") + ), + metadata=metadata, + ) + stub.ListProviders( + openshell_pb2.ListProvidersRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default") + ), + metadata=metadata, + ) def test_no_openshell_scopes_denied(self) -> None: token = get_token("admin@test", "admin") stub, metadata = stub_with_token(token) with pytest.raises(grpc.RpcError) as exc_info: - stub.ListSandboxes(openshell_pb2.ListSandboxesRequest(), metadata=metadata) + stub.ListSandboxes( + openshell_pb2.ListSandboxesRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default") + ), + metadata=metadata, + ) assert exc_info.value.code() == grpc.StatusCode.PERMISSION_DENIED diff --git a/e2e/python/oidc/workspace_authz_test.py b/e2e/python/oidc/workspace_authz_test.py index 9a904810cb..fe8ad4bcea 100644 --- a/e2e/python/oidc/workspace_authz_test.py +++ b/e2e/python/oidc/workspace_authz_test.py @@ -176,7 +176,7 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: "CreateSandbox", lambda s, m: s.CreateSandbox( openshell_pb2.CreateSandboxRequest( - workspace=WS, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), spec=openshell_pb2.SandboxSpec( template=openshell_pb2.SandboxTemplate(image="ubuntu:24.04") ), @@ -187,20 +187,29 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: ( "GetSandbox", lambda s, m: s.GetSandbox( - openshell_pb2.GetSandboxRequest(name="nonexistent", workspace=WS), + openshell_pb2.GetSandboxRequest( + name="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), + ), metadata=m, ), ), ( "ListSandboxes", lambda s, m: s.ListSandboxes( - openshell_pb2.ListSandboxesRequest(workspace=WS), metadata=m + openshell_pb2.ListSandboxesRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS) + ), + metadata=m, ), ), ( "DeleteSandbox", lambda s, m: s.DeleteSandbox( - openshell_pb2.DeleteSandboxRequest(name="nonexistent", workspace=WS), + openshell_pb2.DeleteSandboxRequest( + name="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), + ), metadata=m, ), ), @@ -208,7 +217,8 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: "ListSandboxProviders", lambda s, m: s.ListSandboxProviders( openshell_pb2.ListSandboxProvidersRequest( - sandbox_name="nonexistent", workspace=WS + sandbox_name="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -219,7 +229,7 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: openshell_pb2.AttachSandboxProviderRequest( sandbox_name="nonexistent", provider_name="nonexistent", - workspace=WS, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -230,7 +240,7 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: openshell_pb2.DetachSandboxProviderRequest( sandbox_name="nonexistent", provider_name="nonexistent", - workspace=WS, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -240,7 +250,7 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: "CreateProvider", lambda s, m: s.CreateProvider( openshell_pb2.CreateProviderRequest( - workspace=WS, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta( name="authz-test", workspace=WS @@ -255,21 +265,27 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: ( "GetProvider", lambda s, m: s.GetProvider( - openshell_pb2.GetProviderRequest(name="nonexistent", workspace=WS), + openshell_pb2.GetProviderRequest( + name="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), + ), metadata=m, ), ), ( "ListProviders", lambda s, m: s.ListProviders( - openshell_pb2.ListProvidersRequest(workspace=WS), metadata=m + openshell_pb2.ListProvidersRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS) + ), + metadata=m, ), ), ( "UpdateProvider", lambda s, m: s.UpdateProvider( openshell_pb2.UpdateProviderRequest( - workspace=WS, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta( name="nonexistent", workspace=WS @@ -284,7 +300,10 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: ( "DeleteProvider", lambda s, m: s.DeleteProvider( - openshell_pb2.DeleteProviderRequest(name="nonexistent", workspace=WS), + openshell_pb2.DeleteProviderRequest( + name="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), + ), metadata=m, ), ), @@ -337,7 +356,8 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: "GetProviderRefreshStatus", lambda s, m: s.GetProviderRefreshStatus( openshell_pb2.GetProviderRefreshStatusRequest( - provider="nonexistent", workspace=WS + provider="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -349,7 +369,7 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: provider="nonexistent", credential_key="k", strategy=openshell_pb2.PROVIDER_CREDENTIAL_REFRESH_STRATEGY_STATIC, - workspace=WS, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -360,7 +380,7 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: openshell_pb2.RotateProviderCredentialRequest( provider="nonexistent", credential_key="k", - workspace=WS, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -371,7 +391,7 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: openshell_pb2.DeleteProviderRefreshRequest( provider="nonexistent", credential_key="k", - workspace=WS, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -384,7 +404,7 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: sandbox="nonexistent", service="svc", target_port=8080, - workspace=WS, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -393,7 +413,9 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: "GetService", lambda s, m: s.GetService( openshell_pb2.GetServiceRequest( - sandbox="nonexistent", service="svc", workspace=WS + sandbox="nonexistent", + service="svc", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -401,14 +423,19 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: ( "ListServices", lambda s, m: s.ListServices( - openshell_pb2.ListServicesRequest(workspace=WS), metadata=m + openshell_pb2.ListServicesRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS) + ), + metadata=m, ), ), ( "DeleteService", lambda s, m: s.DeleteService( openshell_pb2.DeleteServiceRequest( - sandbox="nonexistent", service="svc", workspace=WS + sandbox="nonexistent", + service="svc", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -418,7 +445,8 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: "GetSandboxPolicyStatus", lambda s, m: s.GetSandboxPolicyStatus( openshell_pb2.GetSandboxPolicyStatusRequest( - name="nonexistent", workspace=WS + name="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -427,7 +455,8 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: "ListSandboxPolicies", lambda s, m: s.ListSandboxPolicies( openshell_pb2.ListSandboxPoliciesRequest( - name="nonexistent", workspace=WS + name="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -435,7 +464,10 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: ( "GetDraftPolicy", lambda s, m: s.GetDraftPolicy( - openshell_pb2.GetDraftPolicyRequest(name="nonexistent", workspace=WS), + openshell_pb2.GetDraftPolicyRequest( + name="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), + ), metadata=m, ), ), @@ -443,7 +475,9 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: "ApproveDraftChunk", lambda s, m: s.ApproveDraftChunk( openshell_pb2.ApproveDraftChunkRequest( - name="nonexistent", chunk_id="x", workspace=WS + name="nonexistent", + chunk_id="x", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -452,7 +486,9 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: "RejectDraftChunk", lambda s, m: s.RejectDraftChunk( openshell_pb2.RejectDraftChunkRequest( - name="nonexistent", chunk_id="x", workspace=WS + name="nonexistent", + chunk_id="x", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -461,7 +497,8 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: "ApproveAllDraftChunks", lambda s, m: s.ApproveAllDraftChunks( openshell_pb2.ApproveAllDraftChunksRequest( - name="nonexistent", workspace=WS + name="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -470,7 +507,9 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: "EditDraftChunk", lambda s, m: s.EditDraftChunk( openshell_pb2.EditDraftChunkRequest( - name="nonexistent", chunk_id="x", workspace=WS + name="nonexistent", + chunk_id="x", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -479,7 +518,9 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: "UndoDraftChunk", lambda s, m: s.UndoDraftChunk( openshell_pb2.UndoDraftChunkRequest( - name="nonexistent", chunk_id="x", workspace=WS + name="nonexistent", + chunk_id="x", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=m, ), @@ -487,14 +528,20 @@ def _workspace_rpcs() -> list[tuple[str, Callable]]: ( "ClearDraftChunks", lambda s, m: s.ClearDraftChunks( - openshell_pb2.ClearDraftChunksRequest(name="nonexistent", workspace=WS), + openshell_pb2.ClearDraftChunksRequest( + name="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), + ), metadata=m, ), ), ( "GetDraftHistory", lambda s, m: s.GetDraftHistory( - openshell_pb2.GetDraftHistoryRequest(name="nonexistent", workspace=WS), + openshell_pb2.GetDraftHistoryRequest( + name="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), + ), metadata=m, ), ), @@ -558,18 +605,14 @@ def _global_policy_read_rpcs() -> list[tuple[str, Callable]]: ( "GetSandboxPolicyStatus", lambda s, m: s.GetSandboxPolicyStatus( - openshell_pb2.GetSandboxPolicyStatusRequest( - workspace="", **{"global": True} - ), + openshell_pb2.GetSandboxPolicyStatusRequest(**{"global": True}), metadata=m, ), ), ( "ListSandboxPolicies", lambda s, m: s.ListSandboxPolicies( - openshell_pb2.ListSandboxPoliciesRequest( - workspace="", **{"global": True} - ), + openshell_pb2.ListSandboxPoliciesRequest(**{"global": True}), metadata=m, ), ), @@ -626,7 +669,9 @@ def seed_provider(self, admin_ctx: Any, workspace: str) -> Any: with contextlib.suppress(grpc.RpcError): stub.CreateProvider( openshell_pb2.CreateProviderRequest( - workspace=workspace, + workspace_scope=datamodel_pb2.WorkspaceSelector( + workspace=workspace + ), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta( name=prov_name, workspace=workspace @@ -641,7 +686,10 @@ def seed_provider(self, admin_ctx: Any, workspace: str) -> Any: with contextlib.suppress(grpc.RpcError): stub.DeleteProvider( openshell_pb2.DeleteProviderRequest( - name=prov_name, workspace=workspace + name=prov_name, + workspace_scope=datamodel_pb2.WorkspaceSelector( + workspace=workspace + ), ), metadata=metadata, ) @@ -673,7 +721,10 @@ def test_non_member_rejected_update_config( stub, metadata, user_sub = user_ctx with pytest.raises(grpc.RpcError) as exc_info: stub.UpdateConfig( - openshell_pb2.UpdateConfigRequest(name="nonexistent", workspace=WS), + openshell_pb2.UpdateConfigRequest( + name="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), + ), metadata=metadata, ) _assert_non_member_denial( @@ -713,7 +764,9 @@ def test_get_sandbox_logs_rejects_spoofed_workspace( response = admin_stub.CreateSandbox( openshell_pb2.CreateSandboxRequest( name=sandbox_name, - workspace=other_workspace, + workspace_scope=datamodel_pb2.WorkspaceSelector( + workspace=other_workspace + ), spec=openshell_pb2.SandboxSpec(), ), metadata=admin_md, @@ -724,7 +777,7 @@ def test_get_sandbox_logs_rejects_spoofed_workspace( user_stub.GetSandboxLogs( openshell_pb2.GetSandboxLogsRequest( sandbox_id=sandbox_id, - workspace=WS, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=user_md, ) @@ -740,7 +793,9 @@ def test_get_sandbox_logs_rejects_spoofed_workspace( admin_stub.DeleteSandbox( openshell_pb2.DeleteSandboxRequest( name=sandbox_name, - workspace=other_workspace, + workspace_scope=datamodel_pb2.WorkspaceSelector( + workspace=other_workspace + ), ), metadata=admin_md, ) @@ -773,7 +828,6 @@ def test_global_update_rejected_for_default_workspace_admin( with pytest.raises(grpc.RpcError) as exc_info: user_stub.UpdateConfig( openshell_pb2.UpdateConfigRequest( - workspace="", setting_key="log_level", delete_setting=True, **{"global": True}, @@ -824,7 +878,9 @@ def test_platform_admin_list_sandboxes( ) -> None: stub, metadata = admin_ctx stub.ListSandboxes( - openshell_pb2.ListSandboxesRequest(workspace=WS), + openshell_pb2.ListSandboxesRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS) + ), metadata=metadata, ) @@ -835,7 +891,10 @@ def test_platform_admin_get_provider( ) -> None: stub, metadata = admin_ctx resp = stub.GetProvider( - openshell_pb2.GetProviderRequest(name=seed_provider, workspace=WS), + openshell_pb2.GetProviderRequest( + name=seed_provider, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), + ), metadata=metadata, ) assert resp.provider.metadata.name == seed_provider @@ -846,7 +905,9 @@ def test_platform_admin_list_services( ) -> None: stub, metadata = admin_ctx stub.ListServices( - openshell_pb2.ListServicesRequest(workspace=WS), + openshell_pb2.ListServicesRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS) + ), metadata=metadata, ) @@ -858,7 +919,10 @@ def test_platform_admin_get_draft_history( # May fail with NOT_FOUND for the sandbox name, but should not fail with PERMISSION_DENIED try: stub.GetDraftHistory( - openshell_pb2.GetDraftHistoryRequest(name="nonexistent", workspace=WS), + openshell_pb2.GetDraftHistoryRequest( + name="nonexistent", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), + ), metadata=metadata, ) except grpc.RpcError as e: @@ -888,26 +952,35 @@ def test_user_member_read_operations( # ListSandboxes user_stub.ListSandboxes( - openshell_pb2.ListSandboxesRequest(workspace=WS), + openshell_pb2.ListSandboxesRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS) + ), metadata=user_md, ) # GetProvider resp = user_stub.GetProvider( - openshell_pb2.GetProviderRequest(name=seed_provider, workspace=WS), + openshell_pb2.GetProviderRequest( + name=seed_provider, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), + ), metadata=user_md, ) assert resp.provider.metadata.name == seed_provider # ListProviders user_stub.ListProviders( - openshell_pb2.ListProvidersRequest(workspace=WS), + openshell_pb2.ListProvidersRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS) + ), metadata=user_md, ) # ListServices user_stub.ListServices( - openshell_pb2.ListServicesRequest(workspace=WS), + openshell_pb2.ListServicesRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS) + ), metadata=user_md, ) @@ -937,7 +1010,7 @@ def test_user_member_admin_operations_denied( with pytest.raises(grpc.RpcError) as exc_info: user_stub.CreateProvider( openshell_pb2.CreateProviderRequest( - workspace=WS, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta( name="user-blocked", workspace=WS @@ -978,7 +1051,7 @@ def test_user_member_admin_operations_denied( openshell_pb2.ApproveDraftChunkRequest( name="nonexistent", chunk_id="x", - workspace=WS, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), ), metadata=user_md, ) @@ -1008,7 +1081,7 @@ def test_workspace_admin_can_create_provider( try: user_stub.CreateProvider( openshell_pb2.CreateProviderRequest( - workspace=WS, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta(name=prov_name, workspace=WS), type="claude", @@ -1031,7 +1104,10 @@ def test_workspace_admin_can_create_provider( finally: with contextlib.suppress(grpc.RpcError): admin_stub.DeleteProvider( - openshell_pb2.DeleteProviderRequest(name=prov_name, workspace=WS), + openshell_pb2.DeleteProviderRequest( + name=prov_name, + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=WS), + ), metadata=admin_md, ) _remove_member(admin_stub, admin_md, WS, user_sub) @@ -1052,21 +1128,33 @@ def test_all_workspaces_rejected_for_workspace_admin( try: with pytest.raises(grpc.RpcError) as exc_info: user_stub.ListSandboxes( - openshell_pb2.ListSandboxesRequest(all_workspaces=True), + openshell_pb2.ListSandboxesRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector( + all_workspaces=datamodel_pb2.AllWorkspaces() + ) + ), metadata=user_md, ) assert exc_info.value.code() == grpc.StatusCode.PERMISSION_DENIED with pytest.raises(grpc.RpcError) as exc_info: user_stub.ListProviders( - openshell_pb2.ListProvidersRequest(all_workspaces=True), + openshell_pb2.ListProvidersRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector( + all_workspaces=datamodel_pb2.AllWorkspaces() + ) + ), metadata=user_md, ) assert exc_info.value.code() == grpc.StatusCode.PERMISSION_DENIED with pytest.raises(grpc.RpcError) as exc_info: user_stub.ListServices( - openshell_pb2.ListServicesRequest(all_workspaces=True), + openshell_pb2.ListServicesRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector( + all_workspaces=datamodel_pb2.AllWorkspaces() + ) + ), metadata=user_md, ) assert exc_info.value.code() == grpc.StatusCode.PERMISSION_DENIED diff --git a/e2e/python/test_policy_validation.py b/e2e/python/test_policy_validation.py index 323804c4d9..7beb7e146f 100644 --- a/e2e/python/test_policy_validation.py +++ b/e2e/python/test_policy_validation.py @@ -69,7 +69,13 @@ def test_create_sandbox_rejects_root_user( stub = sandbox_client._stub with pytest.raises(grpc.RpcError) as exc_info: - stub.CreateSandbox(openshell_pb2.CreateSandboxRequest(name="", spec=spec)) + stub.CreateSandbox( + openshell_pb2.CreateSandboxRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), + name="", + spec=spec, + ) + ) assert exc_info.value.code() == grpc.StatusCode.INVALID_ARGUMENT assert "root" in exc_info.value.details().lower() @@ -93,7 +99,13 @@ def test_create_sandbox_rejects_path_traversal( stub = sandbox_client._stub with pytest.raises(grpc.RpcError) as exc_info: - stub.CreateSandbox(openshell_pb2.CreateSandboxRequest(name="", spec=spec)) + stub.CreateSandbox( + openshell_pb2.CreateSandboxRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), + name="", + spec=spec, + ) + ) assert exc_info.value.code() == grpc.StatusCode.INVALID_ARGUMENT assert "traversal" in exc_info.value.details().lower() @@ -117,7 +129,13 @@ def test_create_sandbox_rejects_overly_broad_paths( stub = sandbox_client._stub with pytest.raises(grpc.RpcError) as exc_info: - stub.CreateSandbox(openshell_pb2.CreateSandboxRequest(name="", spec=spec)) + stub.CreateSandbox( + openshell_pb2.CreateSandboxRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), + name="", + spec=spec, + ) + ) assert exc_info.value.code() == grpc.StatusCode.INVALID_ARGUMENT assert "broad" in exc_info.value.details().lower() @@ -153,7 +171,7 @@ def test_create_sandbox_materializes_default_mcp_version( stored = sandbox_client._stub.GetSandbox( openshell_pb2.GetSandboxRequest( name=created.name, - workspace="default", + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), ) ) stored_endpoint = stored.sandbox.spec.policy.network_policies[ @@ -210,6 +228,9 @@ def test_update_policy_rejects_immutable_fields( with pytest.raises(grpc.RpcError) as exc_info: stub.UpdateConfig( openshell_pb2.UpdateConfigRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector( + workspace="default" + ), name=sandbox_name, policy=unsafe_policy, ) diff --git a/e2e/python/test_sandbox_providers.py b/e2e/python/test_sandbox_providers.py index 3ef4276f13..0b3c9b0a83 100644 --- a/e2e/python/test_sandbox_providers.py +++ b/e2e/python/test_sandbox_providers.py @@ -81,12 +81,13 @@ def provider( _delete_provider(stub, name) stub.CreateProvider( openshell_pb2.CreateProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta(name=name), type=provider_type, credentials=credentials, profile_workspace=profile_workspace, - ) + ), ) ) try: @@ -98,7 +99,12 @@ def provider( def _delete_provider(stub: object, name: str) -> None: """Delete a provider, ignoring not-found errors.""" try: - stub.DeleteProvider(openshell_pb2.DeleteProviderRequest(name=name)) + stub.DeleteProvider( + openshell_pb2.DeleteProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), + name=name, + ) + ) except grpc.RpcError as exc: if hasattr(exc, "code") and exc.code() == grpc.StatusCode.NOT_FOUND: pass @@ -337,13 +343,14 @@ def test_profileless_provider_creation_is_rejected( with pytest.raises(grpc.RpcError) as exc_info: sandbox_client._stub.CreateProvider( openshell_pb2.CreateProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta( name="e2e-test-profileless-provider" ), type="generic", credentials={"CUSTOM_SERVICE_TOKEN": "token-generic-123"}, - ) + ), ) ) assert exc_info.value.code() == grpc.StatusCode.INVALID_ARGUMENT @@ -496,6 +503,9 @@ def wait_for_token(sb: Sandbox, expected: str) -> None: try: stub.AttachSandboxProvider( openshell_pb2.AttachSandboxProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector( + workspace="default" + ), sandbox_name=sb.sandbox.name, provider_name=provider_name, ) @@ -507,6 +517,9 @@ def wait_for_token(sb: Sandbox, expected: str) -> None: stub.DetachSandboxProvider( openshell_pb2.DetachSandboxProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector( + workspace="default" + ), sandbox_name=sb.sandbox.name, provider_name=provider_name, ) @@ -516,6 +529,9 @@ def wait_for_token(sb: Sandbox, expected: str) -> None: try: stub.DetachSandboxProvider( openshell_pb2.DetachSandboxProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector( + workspace="default" + ), sandbox_name=sb.sandbox.name, provider_name=provider_name, ) @@ -750,7 +766,12 @@ def test_credentials_not_in_persisted_spec_environment( with sandbox(spec=spec, delete_on_exit=True) as sb: fetched = sandbox_client._stub.GetSandbox( - openshell_pb2.GetSandboxRequest(name=sb.sandbox.name) + openshell_pb2.GetSandboxRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector( + workspace="default" + ), + name=sb.sandbox.name, + ) ) persisted_env = dict(fetched.sandbox.spec.environment) assert "ANTHROPIC_API_KEY" not in persisted_env, ( @@ -774,6 +795,7 @@ def test_update_provider_preserves_unset_credentials_and_config( try: stub.CreateProvider( openshell_pb2.CreateProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta(name=name), type="codex", @@ -783,21 +805,27 @@ def test_update_provider_preserves_unset_credentials_and_config( "CODEX_AUTH_ACCOUNT_ID": "account-id", }, config={"BASE_URL": "https://example.com"}, - ) + ), ) ) stub.UpdateProvider( openshell_pb2.UpdateProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta(name=name), type="", credentials={"CODEX_AUTH_ACCESS_TOKEN": "rotated-a"}, - ) + ), ) ) - got = stub.GetProvider(openshell_pb2.GetProviderRequest(name=name)) + got = stub.GetProvider( + openshell_pb2.GetProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), + name=name, + ) + ) p = got.provider # Credential keys are preserved but values are redacted. assert len(p.credentials) > 0, "credential keys should be preserved" @@ -823,25 +851,32 @@ def test_update_provider_empty_maps_preserves_all( try: stub.CreateProvider( openshell_pb2.CreateProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta(name=name), type="openai", credentials={"OPENAI_API_KEY": "secret"}, config={"URL": "https://api.example.com"}, - ) + ), ) ) stub.UpdateProvider( openshell_pb2.UpdateProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta(name=name), type="", - ) + ), ) ) - got = stub.GetProvider(openshell_pb2.GetProviderRequest(name=name)) + got = stub.GetProvider( + openshell_pb2.GetProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), + name=name, + ) + ) p = got.provider # Credential keys are preserved but values are redacted. assert len(p.credentials) > 0, "credential keys should be preserved" @@ -865,26 +900,33 @@ def test_update_provider_merges_config_preserves_credentials( try: stub.CreateProvider( openshell_pb2.CreateProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta(name=name), type="openai", credentials={"OPENAI_API_KEY": "original-key"}, config={"ENDPOINT": "https://old.example.com"}, - ) + ), ) ) stub.UpdateProvider( openshell_pb2.UpdateProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta(name=name), type="", config={"ENDPOINT": "https://new.example.com"}, - ) + ), ) ) - got = stub.GetProvider(openshell_pb2.GetProviderRequest(name=name)) + got = stub.GetProvider( + openshell_pb2.GetProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), + name=name, + ) + ) p = got.provider # Credential keys are preserved but values are redacted. assert len(p.credentials) > 0, "credential keys should be preserved" @@ -908,21 +950,25 @@ def test_update_provider_rejects_type_change( try: stub.CreateProvider( openshell_pb2.CreateProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector(workspace="default"), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta(name=name), type="openai", credentials={"OPENAI_API_KEY": "val"}, - ) + ), ) ) with pytest.raises(grpc.RpcError) as exc_info: stub.UpdateProvider( openshell_pb2.UpdateProviderRequest( + workspace_scope=datamodel_pb2.WorkspaceSelector( + workspace="default" + ), provider=datamodel_pb2.Provider( metadata=datamodel_pb2.ObjectMeta(name=name), type="nvidia", - ) + ), ) ) assert exc_info.value.code() == grpc.StatusCode.INVALID_ARGUMENT diff --git a/examples/governance-interceptor/src/main.rs b/examples/governance-interceptor/src/main.rs index 207727622a..eefeb695fa 100644 --- a/examples/governance-interceptor/src/main.rs +++ b/examples/governance-interceptor/src/main.rs @@ -1233,8 +1233,7 @@ async fn propagate_policy_to_running_sandboxes( limit, offset, label_selector: String::new(), - workspace: String::new(), - all_workspaces: true, + workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), }) .await .map_err(|status| format!("list sandboxes failed: {status}"))? @@ -1257,6 +1256,7 @@ async fn propagate_policy_to_running_sandboxes( policy: Some(policy_state.policy_proto.clone()), annotations: policy_update_annotations(policy_state, &correlation_id), expected_resource_version: resource_version, + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() }) .await; diff --git a/examples/governance-interceptor/src/smoke_client.rs b/examples/governance-interceptor/src/smoke_client.rs index e1dfde4038..25d9ef2f69 100644 --- a/examples/governance-interceptor/src/smoke_client.rs +++ b/examples/governance-interceptor/src/smoke_client.rs @@ -85,6 +85,7 @@ async fn main() -> Result<(), Box> { .update_config(UpdateConfigRequest { name: sandbox_name.clone(), policy: Some(widened_policy), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() }) .await; diff --git a/proto/datamodel.proto b/proto/datamodel.proto index b990f05768..d39ee75500 100644 --- a/proto/datamodel.proto +++ b/proto/datamodel.proto @@ -7,6 +7,26 @@ package openshell.datamodel.v1; import "options.proto"; +// Selects the workspace scope for a public API request. +// +// Requests that operate on one workspace require a non-empty `workspace`. +// Cross-workspace list requests additionally accept `all_workspaces`. The +// containing request documents which selections it supports; an omitted +// selector is invalid for workspace-scoped operations. +message WorkspaceSelector { + oneof selection { + // One explicitly named workspace. Use `default` to select the gateway's + // default workspace; an empty name is invalid. + string workspace = 1; + // All workspaces the caller is authorized to access. Only supported by + // requests that explicitly document cross-workspace behavior. + AllWorkspaces all_workspaces = 2; + } +} + +// Marker for the all-workspaces selector variant. +message AllWorkspaces {} + // Kubernetes-style metadata shared by all top-level OpenShell domain objects. // // This structure provides consistent metadata (identity, labels, annotations, diff --git a/proto/openshell.proto b/proto/openshell.proto index 36f1026d84..580cb2ce2c 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -1117,6 +1117,8 @@ message PlatformEvent { // Create sandbox request. message CreateSandboxRequest { + reserved 5; + reserved "workspace"; SandboxSpec spec = 1; // Optional user-supplied sandbox name. When empty the server generates one. string name = 2; @@ -1124,43 +1126,49 @@ message CreateSandboxRequest { map labels = 3; // Optional annotations for the sandbox (non-selector metadata). map annotations = 4; - // Workspace for the sandbox. Empty defaults to "default". - string workspace = 5; // One-shot launch hint indicating that the creating client will attach to // the canonical main process. The supervisor keeps the terminal transport // alive until that attachment connects and closes naturally. bool await_main_process_attachment = 6; // Workspace-scoped SandboxWorkloadTemplate name to resolve at creation time. string workload_template_name = 7; + // Explicit workspace for the sandbox. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 8; } message CreateSandboxTemplateRequest { + reserved 2; + reserved "workspace"; SandboxWorkloadTemplate template = 1; - // Workspace for the template. Empty defaults to "default". - string workspace = 2; + // Explicit workspace for the template. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; } message GetSandboxTemplateRequest { + reserved 2; + reserved "workspace"; string name = 1; - // Workspace scope. Empty defaults to "default". - string workspace = 2; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; } message ListSandboxTemplatesRequest { + reserved 3, 4; + reserved "workspace", "all_workspaces"; uint32 limit = 1; uint32 offset = 2; - // Workspace scope. Empty defaults to "default". - string workspace = 3; - // List across all workspaces. Mutually exclusive with workspace. - bool all_workspaces = 4; // Optional label selector in key=value comma-separated form. string label_selector = 5; + // Explicit named or all-workspaces scope. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 6; } message DeleteSandboxTemplateRequest { + reserved 2; + reserved "workspace"; string name = 1; - // Workspace scope. Empty defaults to "default". - string workspace = 2; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; } message SandboxTemplateResponse { @@ -1177,15 +1185,17 @@ message DeleteSandboxTemplateResponse { // Request a gateway-owned staging slot for a local rootfs tar archive. message BeginRootfsTarStagingRequest { - // Workspace that will own the sandbox created from this archive. Empty - // defaults to "default", matching CreateSandboxRequest.workspace. - string workspace = 1; + reserved 1; + reserved "workspace"; // Base file name of the local archive. The gateway uses it only to name the // staged file; path separators and traversal components are rejected. string file_name = 2; // Size of the local archive in bytes, checked against the driver limit // before the gateway allocates a slot. uint64 size_bytes = 3; + // Explicit workspace that will own the sandbox created from this archive. + // The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; } // Gateway-issued staging slot. @@ -1204,34 +1214,40 @@ message BeginRootfsTarStagingResponse { // Get sandbox request. message GetSandboxRequest { + reserved 2; + reserved "workspace"; // Sandbox name (canonical lookup key). string name = 1; - // Workspace scope. Empty defaults to "default". - string workspace = 2; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; } // List sandboxes request. message ListSandboxesRequest { + reserved 4, 5; + reserved "workspace", "all_workspaces"; uint32 limit = 1; uint32 offset = 2; // Optional label selector for filtering (format: "key1=value1,key2=value2"). string label_selector = 3; - // Workspace scope. Empty defaults to "default". - string workspace = 4; - // List across all workspaces. Mutually exclusive with workspace. - bool all_workspaces = 5; + // Explicit named or all-workspaces scope. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 6; } // List providers attached to a sandbox request. message ListSandboxProvidersRequest { + reserved 2; + reserved "workspace"; // Sandbox name (canonical lookup key). string sandbox_name = 1; - // Workspace scope. Empty defaults to "default". - string workspace = 2; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; } // Attach provider to sandbox request. message AttachSandboxProviderRequest { + reserved 4; + reserved "workspace"; // Sandbox name (canonical lookup key). string sandbox_name = 1; // Provider name to attach. @@ -1241,12 +1257,14 @@ message AttachSandboxProviderRequest { // If non-zero, the server validates that the sandbox's current resource_version // matches this value before applying the mutation, returning ABORTED on mismatch. uint64 expected_resource_version = 3; - // Workspace scope. Empty defaults to "default". - string workspace = 4; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; } // Detach provider from sandbox request. message DetachSandboxProviderRequest { + reserved 4; + reserved "workspace"; // Sandbox name (canonical lookup key). string sandbox_name = 1; // Provider name to detach. @@ -1256,32 +1274,38 @@ message DetachSandboxProviderRequest { // If non-zero, the server validates that the sandbox's current resource_version // matches this value before applying the mutation, returning ABORTED on mismatch. uint64 expected_resource_version = 3; - // Workspace scope. Empty defaults to "default". - string workspace = 4; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; } // Delete sandbox request. message DeleteSandboxRequest { + reserved 2; + reserved "workspace"; // Sandbox name (canonical lookup key). string name = 1; - // Workspace scope. Empty defaults to "default". - string workspace = 2; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; } // Stop sandbox request. message StopSandboxRequest { + reserved 2; + reserved "workspace"; // Sandbox name (canonical lookup key). string name = 1; - // Workspace scope. Empty defaults to "default". - string workspace = 2; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; } // Start sandbox request. message StartSandboxRequest { + reserved 2; + reserved "workspace"; // Sandbox name (canonical lookup key). string name = 1; - // Workspace scope. Empty defaults to "default". - string workspace = 2; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; } // Sandbox response. @@ -1360,6 +1384,8 @@ message CreateSshSessionResponse { // Request to expose an HTTP service running inside a sandbox. message ExposeServiceRequest { + reserved 5; + reserved "workspace"; // Sandbox name. string sandbox = 1; // Service name within the sandbox. @@ -1368,32 +1394,34 @@ message ExposeServiceRequest { uint32 target_port = 3; // Whether to print/use the browser-facing service URL. bool domain = 4; - // Workspace scope. Empty defaults to "default". - string workspace = 5; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 6; } // Request to fetch an exposed sandbox service endpoint. message GetServiceRequest { + reserved 3; + reserved "workspace"; // Sandbox name. string sandbox = 1; // Service name within the sandbox. Empty selects the unnamed endpoint. string service = 2; - // Workspace scope. Empty defaults to "default". - string workspace = 3; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; } // Request to list exposed sandbox service endpoints. message ListServicesRequest { + reserved 4, 5; + reserved "workspace", "all_workspaces"; // Optional sandbox name. Empty lists endpoints for all sandboxes. string sandbox = 1; // Page size. Zero uses the server default. uint32 limit = 2; // Page offset. uint32 offset = 3; - // Workspace scope. Empty defaults to "default". - string workspace = 4; - // List across all workspaces. Mutually exclusive with workspace. - bool all_workspaces = 5; + // Explicit named or all-workspaces scope. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 6; } // Response containing exposed sandbox service endpoints. @@ -1403,12 +1431,14 @@ message ListServicesResponse { // Request to delete an exposed sandbox service endpoint. message DeleteServiceRequest { + reserved 3; + reserved "workspace"; // Sandbox name. string sandbox = 1; // Service name within the sandbox. Empty selects the unnamed endpoint. string service = 2; - // Workspace scope. Empty defaults to "default". - string workspace = 3; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; } // Response for deleting an exposed sandbox service endpoint. @@ -1645,43 +1675,51 @@ message SandboxStreamWarning { // Create provider request. message CreateProviderRequest { + reserved 2; + reserved "workspace"; openshell.datamodel.v1.Provider provider = 1; - // Workspace for the provider. Empty defaults to "default". - string workspace = 2; + // Explicit workspace for the provider. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; } // Get provider request. message GetProviderRequest { + reserved 2; + reserved "workspace"; string name = 1; - // Workspace scope. Empty defaults to "default". - string workspace = 2; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; } // List providers request. message ListProvidersRequest { + reserved 3, 4; + reserved "workspace", "all_workspaces"; uint32 limit = 1; uint32 offset = 2; - // Workspace scope. Empty defaults to "default". - string workspace = 3; - // List across all workspaces. Mutually exclusive with workspace. - bool all_workspaces = 4; + // Explicit named or all-workspaces scope. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; } // Update provider request. message UpdateProviderRequest { + reserved 3; + reserved "workspace"; openshell.datamodel.v1.Provider provider = 1; // Optional per-credential expiry timestamps to merge into the provider. // A zero value removes the expiry for that credential. map credential_expires_at_ms = 2; - // Workspace scope. Empty defaults to "default". - string workspace = 3; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; } // Delete provider request. message DeleteProviderRequest { + reserved 2; + reserved "workspace"; string name = 1; - // Workspace scope. Empty defaults to "default". - string workspace = 2; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; } // Provider response. @@ -1886,10 +1924,12 @@ message ProviderProfileDiscovery { } message GetProviderRefreshStatusRequest { + reserved 3; + reserved "workspace"; string provider = 1; string credential_key = 2; - // Workspace scope. Empty defaults to "default". - string workspace = 3; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; } message GetProviderRefreshStatusResponse { @@ -1897,6 +1937,8 @@ message GetProviderRefreshStatusResponse { } message ConfigureProviderRefreshRequest { + reserved 7; + reserved "workspace"; string provider = 1; string credential_key = 2; ProviderCredentialRefreshStrategy strategy = 3; @@ -1906,8 +1948,8 @@ message ConfigureProviderRefreshRequest { // the authoritative provider profile and refresh strategy. repeated string secret_material_keys = 5; optional int64 expires_at_ms = 6; - // Workspace scope. Empty defaults to "default". - string workspace = 7; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 8; } message ConfigureProviderRefreshResponse { @@ -1915,10 +1957,12 @@ message ConfigureProviderRefreshResponse { } message RotateProviderCredentialRequest { + reserved 3; + reserved "workspace"; string provider = 1; string credential_key = 2; - // Workspace scope. Empty defaults to "default". - string workspace = 3; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; } message RotateProviderCredentialResponse { @@ -1926,10 +1970,12 @@ message RotateProviderCredentialResponse { } message DeleteProviderRefreshRequest { + reserved 3; + reserved "workspace"; string provider = 1; string credential_key = 2; - // Workspace scope. Empty defaults to "default". - string workspace = 3; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; } message DeleteProviderRefreshResponse { @@ -2133,6 +2179,8 @@ message ExchangeProviderSubjectTokenResponse { // Update sandbox policy request. message UpdateConfigRequest { + reserved 10; + reserved "workspace"; // Sandbox name (canonical lookup key). Required for sandbox-scoped updates. // Not required when `global=true`. string name = 1; @@ -2169,8 +2217,9 @@ message UpdateConfigRequest { // sandbox metadata as a convenience projection. For setting-only updates, it // only merges them into sandbox metadata. map annotations = 9; - // Workspace scope. Empty defaults to "default". Ignored for global-scoped updates. - string workspace = 10; + // Explicit workspace scope for sandbox-scoped updates. Omit only when + // `global` is true; the all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 11; } message PolicyMergeOperation { @@ -2232,14 +2281,17 @@ message UpdateConfigResponse { // Get sandbox policy status request. message GetSandboxPolicyStatusRequest { + reserved 4; + reserved "workspace"; // Sandbox name (canonical lookup key). Ignored when global is true. string name = 1; // The specific policy version to query. 0 means latest. uint32 version = 2; // Query global policy revisions instead of a sandbox-scoped one. bool global = 3; - // Workspace scope. Empty defaults to "default". Ignored when global is true. - string workspace = 4; + // Explicit workspace scope for sandbox-scoped queries. Omit only when + // `global` is true; the all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; } // Get sandbox policy status response. @@ -2252,14 +2304,17 @@ message GetSandboxPolicyStatusResponse { // List sandbox policies request. message ListSandboxPoliciesRequest { + reserved 5; + reserved "workspace"; // Sandbox name (canonical lookup key). Ignored when global is true. string name = 1; uint32 limit = 2; uint32 offset = 3; // List global policy revisions instead of sandbox-scoped ones. bool global = 4; - // Workspace scope. Empty defaults to "default". Ignored when global is true. - string workspace = 5; + // Explicit workspace scope for sandbox-scoped queries. Omit only when + // `global` is true; the all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 6; } // List sandbox policies response. @@ -2330,6 +2385,8 @@ enum PolicyStatus { // Get sandbox logs request (one-shot fetch). message GetSandboxLogsRequest { + reserved 6; + reserved "workspace"; // Sandbox id. string sandbox_id = 1; // Maximum number of log lines to return. 0 means use default (2000). @@ -2340,8 +2397,8 @@ message GetSandboxLogsRequest { repeated string sources = 4; // Minimum log level to include (e.g. "INFO", "WARN", "ERROR"). Empty means all levels. string min_level = 5; - // Workspace scope. Empty defaults to "default". - string workspace = 6; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 7; } // Batch of log lines pushed from sandbox to server. @@ -2694,12 +2751,14 @@ message SubmitPolicyAnalysisResponse { // Get draft policy for a sandbox. message GetDraftPolicyRequest { + reserved 3; + reserved "workspace"; // Sandbox name. string name = 1; // Optional status filter: "pending", "approved", "rejected", or "" for all. string status_filter = 2; - // Workspace scope. Empty defaults to "default". - string workspace = 3; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; } message GetDraftPolicyResponse { @@ -2715,15 +2774,17 @@ message GetDraftPolicyResponse { // Approve a single draft chunk. message ApproveDraftChunkRequest { + reserved 3; + reserved "workspace"; // Sandbox name. string name = 1; // Chunk ID to approve. string chunk_id = 2; - // Workspace scope. Empty defaults to "default". - string workspace = 3; // Token returned with the reviewed PolicyChunk. Approval fails with // FAILED_PRECONDITION if live decision inputs no longer match it. string review_token = 4; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; } message ApproveDraftChunkResponse { @@ -2735,14 +2796,16 @@ message ApproveDraftChunkResponse { // Reject a single draft chunk. message RejectDraftChunkRequest { + reserved 4; + reserved "workspace"; // Sandbox name. string name = 1; // Chunk ID to reject. string chunk_id = 2; // Optional reason for rejection (fed to LLM context in future analysis). string reason = 3; - // Workspace scope. Empty defaults to "default". - string workspace = 4; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; } message RejectDraftChunkResponse {} @@ -2754,15 +2817,17 @@ message DraftChunkApproval { } message ApproveAllDraftChunksRequest { + reserved 3; + reserved "workspace"; // Sandbox name. string name = 1; // Include chunks with security_notes (default false: skips them). bool include_security_flagged = 2; - // Workspace scope. Empty defaults to "default". - string workspace = 3; // Exact reviewed chunks and tokens. The server validates them against one // live snapshot, stages compatible operations in order, and writes once. repeated DraftChunkApproval approvals = 4; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; } message ApproveAllDraftChunksResponse { @@ -2779,26 +2844,30 @@ message ApproveAllDraftChunksResponse { // Edit a pending chunk in-place. message EditDraftChunkRequest { + reserved 4; + reserved "workspace"; // Sandbox name. string name = 1; // Chunk ID to edit. string chunk_id = 2; // The modified rule (replaces existing proposed_rule). openshell.sandbox.v1.NetworkPolicyRule proposed_rule = 3; - // Workspace scope. Empty defaults to "default". - string workspace = 4; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; } message EditDraftChunkResponse {} // Reverse an approval (remove merged rule from active policy). message UndoDraftChunkRequest { + reserved 3; + reserved "workspace"; // Sandbox name. string name = 1; // Chunk ID to undo. string chunk_id = 2; - // Workspace scope. Empty defaults to "default". - string workspace = 3; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; } message UndoDraftChunkResponse { @@ -2810,10 +2879,12 @@ message UndoDraftChunkResponse { // Clear all pending draft chunks for a sandbox. message ClearDraftChunksRequest { + reserved 2; + reserved "workspace"; // Sandbox name. string name = 1; - // Workspace scope. Empty defaults to "default". - string workspace = 2; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; } message ClearDraftChunksResponse { @@ -2823,10 +2894,12 @@ message ClearDraftChunksResponse { // Get decision history for a sandbox's draft policy. message GetDraftHistoryRequest { + reserved 2; + reserved "workspace"; // Sandbox name. string name = 1; - // Workspace scope. Empty defaults to "default". - string workspace = 2; + // Explicit workspace scope. The all-workspaces selection is invalid. + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; } message DraftHistoryEntry { diff --git a/python/openshell/sandbox.py b/python/openshell/sandbox.py index c34a2c05fe..343d75edcc 100644 --- a/python/openshell/sandbox.py +++ b/python/openshell/sandbox.py @@ -37,6 +37,16 @@ _OAUTH_MAX_RESPONSE_BYTES = 1 << 20 +def _workspace_scope(workspace: str) -> datamodel_pb2.WorkspaceSelector: + if not workspace: + raise ValueError("workspace must be non-empty") + return datamodel_pb2.WorkspaceSelector(workspace=workspace) + + +def _all_workspaces_scope() -> datamodel_pb2.WorkspaceSelector: + return datamodel_pb2.WorkspaceSelector(all_workspaces=datamodel_pb2.AllWorkspaces()) + + class _ClientCallDetails(_ClientCallDetailsBase, grpc.ClientCallDetails): pass @@ -722,7 +732,7 @@ def create( spec=request_spec, name=name or "", labels=dict(labels) if labels else {}, - workspace=workspace, + workspace_scope=_workspace_scope(workspace), ), timeout=self._timeout, ) @@ -748,7 +758,7 @@ def create_from_template( spec=request_spec, name=name or "", labels=dict(labels) if labels else {}, - workspace=workspace, + workspace_scope=_workspace_scope(workspace), workload_template_name=template_name, ), timeout=self._timeout, @@ -795,7 +805,9 @@ def sandbox_templates(self) -> SandboxTemplateClient: def get(self, sandbox_name: str, *, workspace: str) -> SandboxRef: response = self._stub.GetSandbox( - openshell_pb2.GetSandboxRequest(name=sandbox_name, workspace=workspace), + openshell_pb2.GetSandboxRequest( + name=sandbox_name, workspace_scope=_workspace_scope(workspace) + ), timeout=self._timeout, ) return _sandbox_ref(response.sandbox) @@ -812,7 +824,7 @@ def list( label_selector: str | None = None, ) -> builtins.list[SandboxRef]: request = openshell_pb2.ListSandboxesRequest( - workspace=workspace, + workspace_scope=_workspace_scope(workspace), limit=limit, offset=offset, label_selector=label_selector or "", @@ -828,7 +840,7 @@ def list_for_all_workspaces( label_selector: str | None = None, ) -> builtins.list[SandboxRef]: request = openshell_pb2.ListSandboxesRequest( - all_workspaces=True, + workspace_scope=_all_workspaces_scope(), limit=limit, offset=offset, label_selector=label_selector or "", @@ -872,21 +884,27 @@ def list_ids_for_all_workspaces( def delete(self, sandbox_name: str, *, workspace: str) -> bool: response = self._stub.DeleteSandbox( - openshell_pb2.DeleteSandboxRequest(name=sandbox_name, workspace=workspace), + openshell_pb2.DeleteSandboxRequest( + name=sandbox_name, workspace_scope=_workspace_scope(workspace) + ), timeout=self._timeout, ) return bool(response.deleted) def stop(self, sandbox_name: str, *, workspace: str) -> SandboxRef: response = self._stub.StopSandbox( - openshell_pb2.StopSandboxRequest(name=sandbox_name, workspace=workspace), + openshell_pb2.StopSandboxRequest( + name=sandbox_name, workspace_scope=_workspace_scope(workspace) + ), timeout=self._timeout, ) return _sandbox_ref(response.sandbox) def start(self, sandbox_name: str, *, workspace: str) -> SandboxRef: response = self._stub.StartSandbox( - openshell_pb2.StartSandboxRequest(name=sandbox_name, workspace=workspace), + openshell_pb2.StartSandboxRequest( + name=sandbox_name, workspace_scope=_workspace_scope(workspace) + ), timeout=self._timeout, ) return _sandbox_ref(response.sandbox) @@ -1138,7 +1156,7 @@ def create( response = self._stub.CreateSandboxTemplate( openshell_pb2.CreateSandboxTemplateRequest( - workspace=workspace, + workspace_scope=_workspace_scope(workspace), template=template, ), timeout=self._timeout, @@ -1152,7 +1170,9 @@ def get( workspace: str, ) -> openshell_pb2.SandboxWorkloadTemplate: response = self._stub.GetSandboxTemplate( - openshell_pb2.GetSandboxTemplateRequest(name=name, workspace=workspace), + openshell_pb2.GetSandboxTemplateRequest( + name=name, workspace_scope=_workspace_scope(workspace) + ), timeout=self._timeout, ) return response.template @@ -1167,7 +1187,7 @@ def list( ) -> builtins.list[openshell_pb2.SandboxWorkloadTemplate]: response = self._stub.ListSandboxTemplates( openshell_pb2.ListSandboxTemplatesRequest( - workspace=workspace, + workspace_scope=_workspace_scope(workspace), limit=limit, offset=offset, label_selector=label_selector, @@ -1185,7 +1205,7 @@ def list_for_all_workspaces( ) -> builtins.list[openshell_pb2.SandboxWorkloadTemplate]: response = self._stub.ListSandboxTemplates( openshell_pb2.ListSandboxTemplatesRequest( - all_workspaces=True, + workspace_scope=_all_workspaces_scope(), limit=limit, offset=offset, label_selector=label_selector, @@ -1196,7 +1216,9 @@ def list_for_all_workspaces( def delete(self, name: str, *, workspace: str) -> bool: response = self._stub.DeleteSandboxTemplate( - openshell_pb2.DeleteSandboxTemplateRequest(name=name, workspace=workspace), + openshell_pb2.DeleteSandboxTemplateRequest( + name=name, workspace_scope=_workspace_scope(workspace) + ), timeout=self._timeout, ) return bool(response.deleted) diff --git a/python/openshell/sandbox_test.py b/python/openshell/sandbox_test.py index fd9e2bcb5b..772a327239 100644 --- a/python/openshell/sandbox_test.py +++ b/python/openshell/sandbox_test.py @@ -42,6 +42,17 @@ ) +def _request_workspace(request: Any) -> str | None: + scope = request.workspace_scope + if scope.WhichOneof("selection") == "workspace": + return cast("str", scope.workspace) + return None + + +def _request_selects_all_workspaces(request: Any) -> bool: + return request.workspace_scope.WhichOneof("selection") == "all_workspaces" + + def _client_credentials_fixture() -> dict[str, Any]: return json.loads( ( @@ -1981,7 +1992,9 @@ def GetSandbox( _ = timeout return SimpleNamespace( sandbox=_make_sandbox_proto( - "sandbox-1", request.name, workspace=request.workspace or "default" + "sandbox-1", + request.name, + workspace=_request_workspace(request) or "default", ) ) @@ -2006,7 +2019,7 @@ def StopSandbox( "sandbox-1", request.name, phase=openshell_pb2.SANDBOX_PHASE_STOPPED, - workspace=request.workspace, + workspace=_request_workspace(request) or "default", ) ) @@ -2022,7 +2035,7 @@ def StartSandbox( "sandbox-1", request.name, phase=openshell_pb2.SANDBOX_PHASE_STARTING, - workspace=request.workspace, + workspace=_request_workspace(request) or "default", ) ) @@ -2038,7 +2051,7 @@ def CreateSandbox( "sandbox-1", request.name or "generated", dict(request.labels), - workspace=request.workspace or "default", + workspace=_request_workspace(request) or "default", ) ) @@ -2071,7 +2084,7 @@ def GetSandboxTemplate( return SimpleNamespace( template=_make_workload_template_proto( request.name, - workspace=request.workspace or "default", + workspace=_request_workspace(request) or "default", ) ) @@ -2217,7 +2230,7 @@ def test_sandbox_template_create_builds_template_from_public_fields() -> None: assert created.metadata.name == "gpu-kata" assert stub.create_template_request is not None - assert stub.create_template_request.workspace == "default" + assert _request_workspace(stub.create_template_request) == "default" template = stub.create_template_request.template assert template.metadata.name == "gpu-kata" assert dict(template.metadata.labels) == {"team": "runtime"} @@ -2361,7 +2374,7 @@ def test_sandbox_template_client_crud_forwards_requests() -> None: assert created.metadata.name == "gpu-kata" assert stub.create_template_request is not None - assert stub.create_template_request.workspace == "default" + assert _request_workspace(stub.create_template_request) == "default" assert ( stub.create_template_request.template.spec.workload.image == "ghcr.io/test/gpu-kata:latest" @@ -2377,34 +2390,34 @@ def test_sandbox_template_client_crud_forwards_requests() -> None: assert got.metadata.name == "gpu-kata" assert stub.get_template_request is not None assert stub.get_template_request.name == "gpu-kata" - assert stub.get_template_request.workspace == "default" + assert _request_workspace(stub.get_template_request) == "default" listed = client.list( workspace="default", limit=50, offset=10, label_selector="team=runtime" ) assert len(listed) == 1 assert stub.list_template_request is not None - assert stub.list_template_request.workspace == "default" + assert _request_workspace(stub.list_template_request) == "default" assert stub.list_template_request.limit == 50 assert stub.list_template_request.offset == 10 assert stub.list_template_request.label_selector == "team=runtime" - assert not stub.list_template_request.all_workspaces + assert not _request_selects_all_workspaces(stub.list_template_request) assert client.delete("gpu-kata", workspace="default") is True assert stub.delete_template_request is not None assert stub.delete_template_request.name == "gpu-kata" - assert stub.delete_template_request.workspace == "default" + assert _request_workspace(stub.delete_template_request) == "default" -def test_sandbox_template_list_for_all_workspaces_clears_workspace() -> None: +def test_sandbox_template_list_for_all_workspaces_selects_all() -> None: stub = _FakeSandboxStub() client = _template_client_with_fake_stub(stub) client.list_for_all_workspaces(limit=100, offset=5, label_selector="team=runtime") assert stub.list_template_request is not None - assert stub.list_template_request.all_workspaces - assert stub.list_template_request.workspace == "" + assert _request_selects_all_workspaces(stub.list_template_request) + assert _request_workspace(stub.list_template_request) is None assert stub.list_template_request.limit == 100 assert stub.list_template_request.offset == 5 assert stub.list_template_request.label_selector == "team=runtime" @@ -2417,13 +2430,13 @@ def test_stop_and_start_forward_workspace_and_return_phase() -> None: stopped = client.stop("job-1", workspace="team-a") assert stub.stop_request is not None assert stub.stop_request.name == "job-1" - assert stub.stop_request.workspace == "team-a" + assert _request_workspace(stub.stop_request) == "team-a" assert stopped.phase == openshell_pb2.SANDBOX_PHASE_STOPPED starting = client.start("job-1", workspace="team-a") assert stub.start_request is not None assert stub.start_request.name == "job-1" - assert stub.start_request.workspace == "team-a" + assert _request_workspace(stub.start_request) == "team-a" assert starting.phase == openshell_pb2.SANDBOX_PHASE_STARTING @@ -2449,7 +2462,7 @@ def GetSandbox( "sandbox-1", request.name, phase=phase, - workspace=request.workspace, + workspace=_request_workspace(request) or "default", ) ) @@ -2471,7 +2484,7 @@ def test_create_without_args_sends_empty_metadata() -> None: assert stub.create_request is not None assert stub.create_request.name == "" assert dict(stub.create_request.labels) == {} - assert stub.create_request.workspace == "default" + assert _request_workspace(stub.create_request) == "default" def test_create_copies_caller_labels() -> None: @@ -2508,7 +2521,7 @@ def test_list_forwards_label_selector() -> None: assert stub.list_request is not None assert stub.list_request.label_selector == "aiq=deep-research" - assert stub.list_request.workspace == "default" + assert _request_workspace(stub.list_request) == "default" def test_list_without_selector_sends_empty_string() -> None: @@ -2725,7 +2738,7 @@ def test_create_passes_workspace_to_proto() -> None: ref = client.create(workspace="staging", name="job-1") assert stub.create_request is not None - assert stub.create_request.workspace == "staging" + assert _request_workspace(stub.create_request) == "staging" assert ref.workspace == "staging" @@ -2736,7 +2749,7 @@ def test_get_passes_workspace_to_proto() -> None: ref = client.get("job-1", workspace="production") assert stub.get_request is not None - assert stub.get_request.workspace == "production" + assert _request_workspace(stub.get_request) == "production" assert ref.workspace == "production" @@ -2748,7 +2761,7 @@ def test_delete_passes_workspace_to_proto() -> None: assert result is True assert stub.delete_request is not None - assert stub.delete_request.workspace == "staging" + assert _request_workspace(stub.delete_request) == "staging" def test_list_for_all_workspaces_sets_flag() -> None: @@ -2758,8 +2771,8 @@ def test_list_for_all_workspaces_sets_flag() -> None: client.list_for_all_workspaces() assert stub.list_request is not None - assert stub.list_request.all_workspaces is True - assert stub.list_request.workspace == "" + assert _request_selects_all_workspaces(stub.list_request) + assert _request_workspace(stub.list_request) is None def test_list_with_workspace_passes_workspace() -> None: @@ -2769,8 +2782,8 @@ def test_list_with_workspace_passes_workspace() -> None: client.list(workspace="staging") assert stub.list_request is not None - assert stub.list_request.workspace == "staging" - assert stub.list_request.all_workspaces is False + assert _request_workspace(stub.list_request) == "staging" + assert not _request_selects_all_workspaces(stub.list_request) def test_sandbox_ref_includes_workspace_from_proto() -> None: @@ -2809,4 +2822,4 @@ def test_sandbox_session_delete_passes_workspace() -> None: session.delete() assert stub.delete_request is not None - assert stub.delete_request.workspace == "staging" + assert _request_workspace(stub.delete_request) == "staging" diff --git a/rfc/0011-multi-player-design/README.md b/rfc/0011-multi-player-design/README.md index 32a2f584e1..87fb5f558a 100644 --- a/rfc/0011-multi-player-design/README.md +++ b/rfc/0011-multi-player-design/README.md @@ -312,8 +312,8 @@ Within a workspace, access varies by resource type: boundary — within a workspace, all members share the same trust domain and the same provider credentials, so there is no security benefit to restricting sandbox access by owner. Platform Admins can list across workspaces using - `all_workspaces = true` on list RPCs (see Cross-Workspace List Operations - below). + the `all_workspaces` `WorkspaceSelector` variant on list RPCs (see + Cross-Workspace List Operations below). - **Providers.** Users can list and reference providers by name within their workspace but cannot create, update, or delete them, and cannot see raw @@ -507,7 +507,8 @@ resolves it, and the runtime consumes it directly. that depends on a request field. Handlers may strengthen, but never weaken, the declared baseline for these cases: -- `all_workspaces: true` requires Platform Admin on cross-workspace list RPCs. +- The `all_workspaces` selector requires Platform Admin on cross-workspace list + RPCs. - `global: true` requires Platform Admin for global configuration and policy reads or writes. - An empty provider-profile workspace selects platform scope and requires @@ -861,16 +862,16 @@ analogous to `kubectl get pods --all-namespaces`. This is an explicit opt-in on list RPCs, not the default behavior. **RPC mechanism.** Workspace-scoped list RPCs (`ListSandboxes`, -`ListProviders`, `ListServices`) gain an `all_workspaces` boolean field. When -`all_workspaces = true`, the handler bypasses workspace scoping and returns -results from all workspaces. The caller must have the Platform Admin global role; -workspace-scoped roles cannot set `all_workspaces`. Results include the -`workspace` field in each resource's `ObjectMeta` so the caller can distinguish -provenance. +`ListSandboxTemplates`, `ListProviders`, `ListServices`) use a +`WorkspaceSelector` oneof with either a non-empty named workspace or an +`all_workspaces` marker. The all-workspaces variant bypasses workspace scoping +and returns results from all workspaces. The caller must have the Platform +Admin global role; workspace-scoped roles cannot select all workspaces. Results +include the `workspace` field in each resource's `ObjectMeta` so the caller can +distinguish provenance. -This is distinct from passing an empty workspace string. Empty workspace is -resolved to `"default"` by the gateway's `resolve_workspace()` logic for -backwards compatibility — it does not mean "all workspaces." +An omitted selector, an unset selector, and an empty named workspace are +invalid. The default workspace is selected explicitly with the name `default`. **Store query.** The `all_workspaces` handler path uses the same `list_by_type(object_type, limit, offset)` store method as the internal @@ -1081,8 +1082,8 @@ etc.). Unlike the CLI, the SDK does not default to `"default"` — programmatic callers must always specify the target workspace. This is a deliberate design choice: agents and automation scripts should be explicit about which workspace they operate on, and a silent default could mask workspace-routing bugs. -Passing `workspace=None` to `list()` uses `all_workspaces=True` for -cross-workspace queries. +Cross-workspace queries use the separate `list_for_all_workspaces()` method so +named and all-workspaces scopes cannot conflict. ## Implementation plan @@ -1149,8 +1150,9 @@ foundations. The work can be phased to deliver value incrementally: workspace through `StoredProviderCredentialRefreshState` so the provider refresh worker can unambiguously resolve workspace-scoped providers — with multiple workspaces, `provider_name` alone is insufficient because different - workspaces can have same-named providers. Add `all_workspaces` field to - workspace-scoped list RPCs for Platform Admin cross-workspace visibility. + workspaces can have same-named providers. Add the typed `WorkspaceSelector` + to workspace-scoped request RPCs and its `all_workspaces` variant to list + RPCs for Platform Admin cross-workspace visibility. Add `ObjectWorkspace::requires_workspace()` trait method and validation in store write helpers (`put_message`, `put_scoped_message`) that returns an error when a workspace-scoped resource is persisted with an empty workspace. @@ -1270,10 +1272,10 @@ depend only on Phase 1. - **Cross-workspace store query authorization.** The `list_by_type` store method has no access-control gate — it is a persistence-layer primitive. Authorization for cross-workspace queries is enforced at the gRPC handler level (Platform - Admin check for `all_workspaces` on list RPCs) and by code-level access - control for internal operations (only the reconciler, start, and refresh - worker call it). This relies on internal code discipline rather than an - enforced store-level boundary. A future extension could add a store-level + Admin check for the `all_workspaces` selector on list RPCs) and by code-level + access control for internal operations (only the reconciler, start, and + refresh worker call it). This relies on internal code discipline rather than + an enforced store-level boundary. A future extension could add a store-level caller identity parameter if defense-in-depth is desired. - **Remote compute driver channel security.** The `RemoteComputeDriver` gRPC diff --git a/sdk/go/docs/src/api/providers.md b/sdk/go/docs/src/api/providers.md index 9eec23f675..87c82379a1 100644 --- a/sdk/go/docs/src/api/providers.md +++ b/sdk/go/docs/src/api/providers.md @@ -59,6 +59,9 @@ providers, err = client.Providers().List(ctx, "default", v1.ListOptions{ Limit: 10, Offset: 0, }) + +// Platform Admin only: list across all workspaces +allProviders, err := client.Providers().ListAll(ctx) ``` ## Update diff --git a/sdk/go/docs/src/api/sandbox-templates.md b/sdk/go/docs/src/api/sandbox-templates.md index d1dcc86e47..03e8ae43e8 100644 --- a/sdk/go/docs/src/api/sandbox-templates.md +++ b/sdk/go/docs/src/api/sandbox-templates.md @@ -97,8 +97,8 @@ templates, err := client.SandboxTemplates().List(ctx, "default", v1.ListOptions{ Offset: 0, }) -allTemplates, err := client.SandboxTemplates().List(ctx, "", v1.ListOptions{ - AllWorkspaces: true, +allTemplates, err := client.SandboxTemplates().ListAll(ctx, v1.ListOptions{ + Limit: 50, }) ``` diff --git a/sdk/go/docs/src/api/sandboxes.md b/sdk/go/docs/src/api/sandboxes.md index 698982fe13..af026a17cb 100644 --- a/sdk/go/docs/src/api/sandboxes.md +++ b/sdk/go/docs/src/api/sandboxes.md @@ -69,6 +69,9 @@ sandboxes, err := client.Sandboxes().List(ctx, "default", v1.ListOptions{ Offset: 0, LabelSelector: "team=platform", }) + +// Platform Admin only: list across all workspaces +allSandboxes, err := client.Sandboxes().ListAll(ctx) ``` ## Delete diff --git a/sdk/go/docs/src/api/services.md b/sdk/go/docs/src/api/services.md index 6d3195e1ad..0c44567d2f 100644 --- a/sdk/go/docs/src/api/services.md +++ b/sdk/go/docs/src/api/services.md @@ -30,6 +30,9 @@ if err != nil { for _, svc := range services { fmt.Printf(" %s -> port %d (%s)\n", svc.ServiceName, svc.TargetPort, svc.URL) } + +// Platform Admin only: list services across all workspaces +allServices, err := client.Services().ListAll(ctx) ``` ## Delete diff --git a/sdk/go/openshell/v1/config_client.go b/sdk/go/openshell/v1/config_client.go index e7086b9b6c..b2cb3fd372 100644 --- a/sdk/go/openshell/v1/config_client.go +++ b/sdk/go/openshell/v1/config_client.go @@ -58,7 +58,9 @@ func (c *configClient) Update(ctx context.Context, workspace string, update *Con if convErr != nil { return nil, &StatusError{Code: ErrorInvalidArgument, Message: convErr.Error()} } - req.Workspace = workspace + if !req.GetGlobal() { + req.WorkspaceScope = namedWorkspaceScope(workspace) + } resp, err := c.client.UpdateConfig(ctx, req) if err != nil { return nil, converter.FromGRPCError(err) diff --git a/sdk/go/openshell/v1/exec_client_test.go b/sdk/go/openshell/v1/exec_client_test.go index 1c649ac0b7..53acc1e8bc 100644 --- a/sdk/go/openshell/v1/exec_client_test.go +++ b/sdk/go/openshell/v1/exec_client_test.go @@ -40,6 +40,9 @@ func (r *stubSandboxResolver) Create(context.Context, string, string, *SandboxSp func (r *stubSandboxResolver) List(context.Context, string, ...ListOptions) ([]*Sandbox, error) { panic("not implemented") } +func (r *stubSandboxResolver) ListAll(context.Context, ...ListOptions) ([]*Sandbox, error) { + panic("not implemented") +} func (r *stubSandboxResolver) Delete(context.Context, string, string) error { panic("not implemented") } diff --git a/sdk/go/openshell/v1/fake/provider.go b/sdk/go/openshell/v1/fake/provider.go index 1f5ce4d831..7ba0345880 100644 --- a/sdk/go/openshell/v1/fake/provider.go +++ b/sdk/go/openshell/v1/fake/provider.go @@ -113,16 +113,20 @@ func (c *fakeProviderClient) Get(_ context.Context, workspace, name string) (*ty // List returns all providers. ListOptions are accepted for interface // compatibility but filtering is not implemented. -func (c *fakeProviderClient) List(_ context.Context, workspace string, opts ...v1.ListOptions) ([]*types.Provider, error) { +func (c *fakeProviderClient) List(_ context.Context, workspace string, _ ...v1.ListOptions) ([]*types.Provider, error) { if c.closedFunc() { return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} } - if len(opts) > 0 && opts[0].AllWorkspaces { - return c.store.ListAll(), nil - } return c.store.List(workspace), nil } +func (c *fakeProviderClient) ListAll(_ context.Context, _ ...v1.ListOptions) ([]*types.Provider, error) { + if c.closedFunc() { + return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} + } + return c.store.ListAll(), nil +} + // Update replaces an existing provider's data. ResourceVersion is // incremented automatically. func (c *fakeProviderClient) Update(_ context.Context, workspace string, provider *types.Provider) (*types.Provider, error) { diff --git a/sdk/go/openshell/v1/fake/sandbox.go b/sdk/go/openshell/v1/fake/sandbox.go index 5de3062d96..8191594a5c 100644 --- a/sdk/go/openshell/v1/fake/sandbox.go +++ b/sdk/go/openshell/v1/fake/sandbox.go @@ -447,16 +447,20 @@ func (c *fakeSandboxClient) Get(_ context.Context, workspace, name string) (*typ // List returns all sandboxes. ListOptions are accepted for interface // compatibility but filtering is not implemented. -func (c *fakeSandboxClient) List(_ context.Context, workspace string, opts ...v1.ListOptions) ([]*types.Sandbox, error) { +func (c *fakeSandboxClient) List(_ context.Context, workspace string, _ ...v1.ListOptions) ([]*types.Sandbox, error) { if c.closedFunc() { return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} } - if len(opts) > 0 && opts[0].AllWorkspaces { - return c.store.ListAll(), nil - } return c.store.List(workspace), nil } +func (c *fakeSandboxClient) ListAll(_ context.Context, _ ...v1.ListOptions) ([]*types.Sandbox, error) { + if c.closedFunc() { + return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} + } + return c.store.ListAll(), nil +} + // Stop transitions a sandbox to the Stopped phase. func (c *fakeSandboxClient) Stop(_ context.Context, workspace, name string) (*types.Sandbox, error) { if c.closedFunc() { diff --git a/sdk/go/openshell/v1/fake/sandbox_template.go b/sdk/go/openshell/v1/fake/sandbox_template.go index 8dbf68cc12..b105de7c13 100644 --- a/sdk/go/openshell/v1/fake/sandbox_template.go +++ b/sdk/go/openshell/v1/fake/sandbox_template.go @@ -106,6 +106,14 @@ func (c *fakeSandboxTemplateClient) Get(_ context.Context, workspace, name strin } func (c *fakeSandboxTemplateClient) List(_ context.Context, workspace string, opts ...v1.ListOptions) ([]*types.SandboxWorkloadTemplate, error) { + return c.list(workspace, false, opts...) +} + +func (c *fakeSandboxTemplateClient) ListAll(_ context.Context, opts ...v1.ListOptions) ([]*types.SandboxWorkloadTemplate, error) { + return c.list("", true, opts...) +} + +func (c *fakeSandboxTemplateClient) list(workspace string, allWorkspaces bool, opts ...v1.ListOptions) ([]*types.SandboxWorkloadTemplate, error) { if c.closedFunc() { return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} } @@ -120,7 +128,7 @@ func (c *fakeSandboxTemplateClient) List(_ context.Context, workspace string, op } } var templates []*types.SandboxWorkloadTemplate - if options.AllWorkspaces { + if allWorkspaces { templates = c.store.ListAll() } else { templates = c.store.List(workspace) diff --git a/sdk/go/openshell/v1/fake/sandbox_template_test.go b/sdk/go/openshell/v1/fake/sandbox_template_test.go index 06a5187227..6caa0da684 100644 --- a/sdk/go/openshell/v1/fake/sandbox_template_test.go +++ b/sdk/go/openshell/v1/fake/sandbox_template_test.go @@ -108,7 +108,7 @@ func TestSandboxTemplate_ListAllWorkspaces(t *testing.T) { _, _ = tc.Create(ctx, "default", testSandboxWorkloadTemplate("default-template")) _, _ = tc.Create(ctx, "team-a", testSandboxWorkloadTemplate("team-template")) - listed, err := tc.List(ctx, "default", types.ListOptions{AllWorkspaces: true}) + listed, err := tc.ListAll(ctx) require.NoError(t, err) assert.Len(t, listed, 2) } diff --git a/sdk/go/openshell/v1/fake/service.go b/sdk/go/openshell/v1/fake/service.go index 8b0c4e1482..4b3029012f 100644 --- a/sdk/go/openshell/v1/fake/service.go +++ b/sdk/go/openshell/v1/fake/service.go @@ -45,6 +45,14 @@ func (c *fakeServiceClient) List(_ context.Context, _, _ string, _ ...v1.ListOpt return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "List is not supported by the fake client"} } +// ListAll returns Unimplemented. +func (c *fakeServiceClient) ListAll(_ context.Context, _ ...v1.ListOptions) ([]*types.ServiceEndpoint, error) { + if c.closedFunc() { + return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} + } + return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "ListAll is not supported by the fake client"} +} + // Delete returns Unimplemented. func (c *fakeServiceClient) Delete(_ context.Context, _, _, _ string) error { if c.closedFunc() { diff --git a/sdk/go/openshell/v1/policy_client.go b/sdk/go/openshell/v1/policy_client.go index f002caf9d9..12801af02a 100644 --- a/sdk/go/openshell/v1/policy_client.go +++ b/sdk/go/openshell/v1/policy_client.go @@ -23,9 +23,9 @@ func newPolicyClient(conn grpc.ClientConnInterface) *policyClient { func (p *policyClient) GetDraft(ctx context.Context, workspace, sandboxName string, opts ...GetDraftOption) (*DraftPolicy, error) { cfg := types.ApplyGetDraftOptions(opts) resp, err := p.client.GetDraftPolicy(ctx, &pb.GetDraftPolicyRequest{ - Name: sandboxName, - StatusFilter: cfg.StatusFilter(), - Workspace: workspace, + Name: sandboxName, + StatusFilter: cfg.StatusFilter(), + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -35,10 +35,10 @@ func (p *policyClient) GetDraft(ctx context.Context, workspace, sandboxName stri func (p *policyClient) ApproveDraftChunk(ctx context.Context, workspace, sandboxName, chunkID, reviewToken string) (*ApproveResult, error) { resp, err := p.client.ApproveDraftChunk(ctx, &pb.ApproveDraftChunkRequest{ - Name: sandboxName, - ChunkId: chunkID, - Workspace: workspace, - ReviewToken: reviewToken, + Name: sandboxName, + ChunkId: chunkID, + WorkspaceScope: namedWorkspaceScope(workspace), + ReviewToken: reviewToken, }) if err != nil { return nil, converter.FromGRPCError(err) @@ -48,10 +48,10 @@ func (p *policyClient) ApproveDraftChunk(ctx context.Context, workspace, sandbox func (p *policyClient) RejectDraftChunk(ctx context.Context, workspace, sandboxName, chunkID, reason string) error { _, err := p.client.RejectDraftChunk(ctx, &pb.RejectDraftChunkRequest{ - Name: sandboxName, - ChunkId: chunkID, - Reason: reason, - Workspace: workspace, + Name: sandboxName, + ChunkId: chunkID, + Reason: reason, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return converter.FromGRPCError(err) @@ -71,7 +71,7 @@ func (p *policyClient) ApproveAllDraftChunks(ctx context.Context, workspace, san resp, err := p.client.ApproveAllDraftChunks(ctx, &pb.ApproveAllDraftChunksRequest{ Name: sandboxName, IncludeSecurityFlagged: cfg.IncludeSecurityFlagged(), - Workspace: workspace, + WorkspaceScope: namedWorkspaceScope(workspace), Approvals: approvals, }) if err != nil { @@ -82,8 +82,8 @@ func (p *policyClient) ApproveAllDraftChunks(ctx context.Context, workspace, san func (p *policyClient) ClearDraftChunks(ctx context.Context, workspace, sandboxName string) (*ClearResult, error) { resp, err := p.client.ClearDraftChunks(ctx, &pb.ClearDraftChunksRequest{ - Name: sandboxName, - Workspace: workspace, + Name: sandboxName, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -93,8 +93,8 @@ func (p *policyClient) ClearDraftChunks(ctx context.Context, workspace, sandboxN func (p *policyClient) GetDraftHistory(ctx context.Context, workspace, sandboxName string) ([]DraftHistoryEntry, error) { resp, err := p.client.GetDraftHistory(ctx, &pb.GetDraftHistoryRequest{ - Name: sandboxName, - Workspace: workspace, + Name: sandboxName, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -114,12 +114,15 @@ func (p *policyClient) GetDraftHistory(ctx context.Context, workspace, sandboxNa func (p *policyClient) GetStatus(ctx context.Context, workspace, sandboxName string, opts ...GetStatusOption) (*PolicyStatusResult, error) { cfg := types.ApplyGetStatusOptions(opts) - resp, err := p.client.GetSandboxPolicyStatus(ctx, &pb.GetSandboxPolicyStatusRequest{ - Name: sandboxName, - Version: cfg.Version(), - Workspace: workspace, - Global: cfg.Global(), - }) + req := &pb.GetSandboxPolicyStatusRequest{ + Name: sandboxName, + Version: cfg.Version(), + Global: cfg.Global(), + } + if !cfg.Global() { + req.WorkspaceScope = namedWorkspaceScope(workspace) + } + resp, err := p.client.GetSandboxPolicyStatus(ctx, req) if err != nil { return nil, converter.FromGRPCError(err) } @@ -128,12 +131,15 @@ func (p *policyClient) GetStatus(ctx context.Context, workspace, sandboxName str func (p *policyClient) List(ctx context.Context, workspace string, opts ...ListPolicyOption) ([]SandboxPolicyRevision, error) { cfg := types.ApplyListPolicyOptions(opts) - resp, err := p.client.ListSandboxPolicies(ctx, &pb.ListSandboxPoliciesRequest{ - Workspace: workspace, - Limit: cfg.Limit(), - Offset: cfg.Offset(), - Global: cfg.Global(), - }) + req := &pb.ListSandboxPoliciesRequest{ + Limit: cfg.Limit(), + Offset: cfg.Offset(), + Global: cfg.Global(), + } + if !cfg.Global() { + req.WorkspaceScope = namedWorkspaceScope(workspace) + } + resp, err := p.client.ListSandboxPolicies(ctx, req) if err != nil { return nil, converter.FromGRPCError(err) } @@ -152,10 +158,10 @@ func (p *policyClient) List(ctx context.Context, workspace string, opts ...ListP func (p *policyClient) EditDraftChunk(ctx context.Context, workspace, sandboxName, chunkID string, proposedRule *NetworkPolicyRule) error { _, err := p.client.EditDraftChunk(ctx, &pb.EditDraftChunkRequest{ - Name: sandboxName, - ChunkId: chunkID, - ProposedRule: converter.NetworkPolicyRuleToProto(proposedRule), - Workspace: workspace, + Name: sandboxName, + ChunkId: chunkID, + ProposedRule: converter.NetworkPolicyRuleToProto(proposedRule), + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return converter.FromGRPCError(err) @@ -165,9 +171,9 @@ func (p *policyClient) EditDraftChunk(ctx context.Context, workspace, sandboxNam func (p *policyClient) UndoDraftChunk(ctx context.Context, workspace, sandboxName, chunkID string) (*UndoResult, error) { resp, err := p.client.UndoDraftChunk(ctx, &pb.UndoDraftChunkRequest{ - Name: sandboxName, - ChunkId: chunkID, - Workspace: workspace, + Name: sandboxName, + ChunkId: chunkID, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) diff --git a/sdk/go/openshell/v1/policy_client_test.go b/sdk/go/openshell/v1/policy_client_test.go index d572ca8e33..a0e16f5a40 100644 --- a/sdk/go/openshell/v1/policy_client_test.go +++ b/sdk/go/openshell/v1/policy_client_test.go @@ -650,7 +650,7 @@ func TestPolicyGetStatus_WithGlobal(t *testing.T) { mock.mu.Lock() assert.True(t, mock.lastStatusReq.GetGlobal()) assert.Empty(t, mock.lastStatusReq.GetName()) - assert.Empty(t, mock.lastStatusReq.GetWorkspace()) + assert.Nil(t, mock.lastStatusReq.GetWorkspaceScope()) mock.mu.Unlock() } @@ -676,7 +676,7 @@ func TestPolicyGetStatus_WithGlobalIgnoresNonEmptyName(t *testing.T) { mock.mu.Lock() assert.True(t, mock.lastStatusReq.GetGlobal()) assert.Equal(t, "some-sandbox", mock.lastStatusReq.GetName()) - assert.Equal(t, "some-workspace", mock.lastStatusReq.GetWorkspace()) + assert.Nil(t, mock.lastStatusReq.GetWorkspaceScope()) mock.mu.Unlock() } @@ -731,7 +731,7 @@ func TestPolicyGetStatus_WithoutGlobal_PreservesExistingBehavior(t *testing.T) { // Verify global flag is false by default. mock.mu.Lock() assert.False(t, mock.lastStatusReq.GetGlobal()) - assert.Equal(t, "default", mock.lastStatusReq.GetWorkspace()) + assert.Equal(t, "default", mock.lastStatusReq.GetWorkspaceScope().GetWorkspace()) assert.Equal(t, "my-sandbox", mock.lastStatusReq.GetName()) mock.mu.Unlock() } @@ -780,7 +780,7 @@ func TestPolicyList(t *testing.T) { // Verify request was forwarded (no pagination options). mock.mu.Lock() - assert.Equal(t, "default", mock.lastListReq.GetWorkspace()) + assert.Equal(t, "default", mock.lastListReq.GetWorkspaceScope().GetWorkspace()) assert.Equal(t, uint32(0), mock.lastListReq.GetLimit()) assert.Equal(t, uint32(0), mock.lastListReq.GetOffset()) mock.mu.Unlock() @@ -855,7 +855,7 @@ func TestPolicyList_WithGlobal(t *testing.T) { // Verify global flag was forwarded in the proto request. mock.mu.Lock() assert.True(t, mock.lastListReq.GetGlobal()) - assert.Empty(t, mock.lastListReq.GetWorkspace()) + assert.Nil(t, mock.lastListReq.GetWorkspaceScope()) mock.mu.Unlock() } @@ -877,7 +877,7 @@ func TestPolicyList_WithGlobalIgnoresWorkspace(t *testing.T) { mock.mu.Lock() assert.True(t, mock.lastListReq.GetGlobal()) - assert.Equal(t, "some-workspace", mock.lastListReq.GetWorkspace()) + assert.Nil(t, mock.lastListReq.GetWorkspaceScope()) mock.mu.Unlock() } @@ -928,7 +928,7 @@ func TestPolicyList_WithoutGlobal_PreservesExistingBehavior(t *testing.T) { // Verify global flag is false by default. mock.mu.Lock() assert.False(t, mock.lastListReq.GetGlobal()) - assert.Equal(t, "default", mock.lastListReq.GetWorkspace()) + assert.Equal(t, "default", mock.lastListReq.GetWorkspaceScope().GetWorkspace()) mock.mu.Unlock() } diff --git a/sdk/go/openshell/v1/provider.go b/sdk/go/openshell/v1/provider.go index f1ab67c482..42788f8855 100644 --- a/sdk/go/openshell/v1/provider.go +++ b/sdk/go/openshell/v1/provider.go @@ -21,6 +21,7 @@ type ProviderInterface interface { Create(ctx context.Context, workspace string, provider *Provider) (*Provider, error) Get(ctx context.Context, workspace, name string) (*Provider, error) List(ctx context.Context, workspace string, opts ...ListOptions) ([]*Provider, error) + ListAll(ctx context.Context, opts ...ListOptions) ([]*Provider, error) Update(ctx context.Context, workspace string, provider *Provider) (*Provider, error) Delete(ctx context.Context, workspace, name string) error Ensure(ctx context.Context, workspace string, provider *Provider) (*Provider, error) diff --git a/sdk/go/openshell/v1/provider_client.go b/sdk/go/openshell/v1/provider_client.go index 19784b6346..237325a1e3 100644 --- a/sdk/go/openshell/v1/provider_client.go +++ b/sdk/go/openshell/v1/provider_client.go @@ -35,8 +35,8 @@ func (p *providerClient) Refresh() RefreshInterface { func (p *providerClient) Create(ctx context.Context, workspace string, provider *Provider) (*Provider, error) { resp, err := p.client.CreateProvider(ctx, &pb.CreateProviderRequest{ - Provider: converter.ProviderToProto(provider), - Workspace: workspace, + Provider: converter.ProviderToProto(provider), + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -46,8 +46,8 @@ func (p *providerClient) Create(ctx context.Context, workspace string, provider func (p *providerClient) Get(ctx context.Context, workspace, name string) (*Provider, error) { resp, err := p.client.GetProvider(ctx, &pb.GetProviderRequest{ - Name: name, - Workspace: workspace, + Name: name, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -57,8 +57,16 @@ func (p *providerClient) Get(ctx context.Context, workspace, name string) (*Prov func (p *providerClient) List(ctx context.Context, workspace string, opts ...ListOptions) ([]*Provider, error) { req := &pb.ListProvidersRequest{ - Workspace: workspace, + WorkspaceScope: namedWorkspaceScope(workspace), } + return p.list(ctx, req, opts...) +} + +func (p *providerClient) ListAll(ctx context.Context, opts ...ListOptions) ([]*Provider, error) { + return p.list(ctx, &pb.ListProvidersRequest{WorkspaceScope: allWorkspacesScope()}, opts...) +} + +func (p *providerClient) list(ctx context.Context, req *pb.ListProvidersRequest, opts ...ListOptions) ([]*Provider, error) { if len(opts) > 0 { if opts[0].Limit < 0 { return nil, &StatusError{Code: ErrorInvalidArgument, Message: "limit must not be negative"} @@ -68,7 +76,6 @@ func (p *providerClient) List(ctx context.Context, workspace string, opts ...Lis } req.Limit = uint32(opts[0].Limit) req.Offset = uint32(opts[0].Offset) - req.AllWorkspaces = opts[0].AllWorkspaces } resp, err := p.client.ListProviders(ctx, req) @@ -86,8 +93,8 @@ func (p *providerClient) List(ctx context.Context, workspace string, opts ...Lis func (p *providerClient) Update(ctx context.Context, workspace string, provider *Provider) (*Provider, error) { proto := converter.ProviderToProto(provider) req := &pb.UpdateProviderRequest{ - Provider: proto, - Workspace: workspace, + Provider: proto, + WorkspaceScope: namedWorkspaceScope(workspace), } if proto != nil { req.CredentialExpiresAtMs = proto.CredentialExpiresAtMs @@ -102,8 +109,8 @@ func (p *providerClient) Update(ctx context.Context, workspace string, provider func (p *providerClient) Delete(ctx context.Context, workspace, name string) error { _, err := p.client.DeleteProvider(ctx, &pb.DeleteProviderRequest{ - Name: name, - Workspace: workspace, + Name: name, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return converter.FromGRPCError(err) diff --git a/sdk/go/openshell/v1/refresh_client.go b/sdk/go/openshell/v1/refresh_client.go index ec98316a93..dc182da844 100644 --- a/sdk/go/openshell/v1/refresh_client.go +++ b/sdk/go/openshell/v1/refresh_client.go @@ -21,9 +21,9 @@ func newRefreshClient(conn grpc.ClientConnInterface) *refreshClient { func (r *refreshClient) GetStatus(ctx context.Context, workspace, provider, credentialKey string) ([]*RefreshStatus, error) { resp, err := r.client.GetProviderRefreshStatus(ctx, &pb.GetProviderRefreshStatusRequest{ - Provider: provider, - CredentialKey: credentialKey, - Workspace: workspace, + Provider: provider, + CredentialKey: credentialKey, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -38,7 +38,7 @@ func (r *refreshClient) GetStatus(ctx context.Context, workspace, provider, cred func (r *refreshClient) Configure(ctx context.Context, workspace string, config *RefreshConfig) (*RefreshStatus, error) { req := converter.RefreshConfigToProto(config) - req.Workspace = workspace + req.WorkspaceScope = namedWorkspaceScope(workspace) resp, err := r.client.ConfigureProviderRefresh(ctx, req) if err != nil { return nil, converter.FromGRPCError(err) @@ -48,9 +48,9 @@ func (r *refreshClient) Configure(ctx context.Context, workspace string, config func (r *refreshClient) Rotate(ctx context.Context, workspace, provider, credentialKey string) (*RefreshStatus, error) { resp, err := r.client.RotateProviderCredential(ctx, &pb.RotateProviderCredentialRequest{ - Provider: provider, - CredentialKey: credentialKey, - Workspace: workspace, + Provider: provider, + CredentialKey: credentialKey, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -60,9 +60,9 @@ func (r *refreshClient) Rotate(ctx context.Context, workspace, provider, credent func (r *refreshClient) Delete(ctx context.Context, workspace, provider, credentialKey string) (bool, error) { resp, err := r.client.DeleteProviderRefresh(ctx, &pb.DeleteProviderRefreshRequest{ - Provider: provider, - CredentialKey: credentialKey, - Workspace: workspace, + Provider: provider, + CredentialKey: credentialKey, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return false, converter.FromGRPCError(err) diff --git a/sdk/go/openshell/v1/sandbox.go b/sdk/go/openshell/v1/sandbox.go index 79174ac7f3..59ab37ee91 100644 --- a/sdk/go/openshell/v1/sandbox.go +++ b/sdk/go/openshell/v1/sandbox.go @@ -56,6 +56,7 @@ type SandboxInterface interface { Create(ctx context.Context, workspace, name string, spec *SandboxSpec, labels map[string]string, opts ...CreateOptions) (*Sandbox, error) Get(ctx context.Context, workspace, name string) (*Sandbox, error) List(ctx context.Context, workspace string, opts ...ListOptions) ([]*Sandbox, error) + ListAll(ctx context.Context, opts ...ListOptions) ([]*Sandbox, error) Stop(ctx context.Context, workspace, name string) (*Sandbox, error) Start(ctx context.Context, workspace, name string) (*Sandbox, error) Delete(ctx context.Context, workspace, name string) error diff --git a/sdk/go/openshell/v1/sandbox_client.go b/sdk/go/openshell/v1/sandbox_client.go index 75d8d4caa3..4028634e2d 100644 --- a/sdk/go/openshell/v1/sandbox_client.go +++ b/sdk/go/openshell/v1/sandbox_client.go @@ -34,10 +34,10 @@ func (s *sandboxClient) Create(ctx context.Context, workspace, name string, spec return nil, &StatusError{Code: ErrorInvalidArgument, Message: err.Error()} } req := &pb.CreateSandboxRequest{ - Name: name, - Spec: protoSpec, - Labels: labels, - Workspace: workspace, + Name: name, + Spec: protoSpec, + Labels: labels, + WorkspaceScope: namedWorkspaceScope(workspace), } if len(opts) > 0 { req.Annotations = converter.CopyStringMap(opts[0].Annotations) @@ -64,7 +64,7 @@ func (s *sandboxClient) CreateFromTemplate(ctx context.Context, workspace, name, Name: name, Spec: protoSpec, Labels: labels, - Workspace: workspace, + WorkspaceScope: namedWorkspaceScope(workspace), WorkloadTemplateName: templateName, } if len(opts) > 0 { @@ -89,8 +89,8 @@ func validateTemplateCreateSpec(spec *SandboxSpec) error { func (s *sandboxClient) Get(ctx context.Context, workspace, name string) (*Sandbox, error) { resp, err := s.client.GetSandbox(ctx, &pb.GetSandboxRequest{ - Name: name, - Workspace: workspace, + Name: name, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -100,8 +100,16 @@ func (s *sandboxClient) Get(ctx context.Context, workspace, name string) (*Sandb func (s *sandboxClient) List(ctx context.Context, workspace string, opts ...ListOptions) ([]*Sandbox, error) { req := &pb.ListSandboxesRequest{ - Workspace: workspace, + WorkspaceScope: namedWorkspaceScope(workspace), } + return s.list(ctx, req, opts...) +} + +func (s *sandboxClient) ListAll(ctx context.Context, opts ...ListOptions) ([]*Sandbox, error) { + return s.list(ctx, &pb.ListSandboxesRequest{WorkspaceScope: allWorkspacesScope()}, opts...) +} + +func (s *sandboxClient) list(ctx context.Context, req *pb.ListSandboxesRequest, opts ...ListOptions) ([]*Sandbox, error) { if len(opts) > 0 { if opts[0].Limit < 0 { return nil, &StatusError{Code: ErrorInvalidArgument, Message: "limit must not be negative"} @@ -112,7 +120,6 @@ func (s *sandboxClient) List(ctx context.Context, workspace string, opts ...List req.Limit = uint32(opts[0].Limit) req.Offset = uint32(opts[0].Offset) req.LabelSelector = opts[0].LabelSelector - req.AllWorkspaces = opts[0].AllWorkspaces } resp, err := s.client.ListSandboxes(ctx, req) @@ -129,8 +136,8 @@ func (s *sandboxClient) List(ctx context.Context, workspace string, opts ...List func (s *sandboxClient) Delete(ctx context.Context, workspace, name string) error { _, err := s.client.DeleteSandbox(ctx, &pb.DeleteSandboxRequest{ - Name: name, - Workspace: workspace, + Name: name, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return converter.FromGRPCError(err) @@ -140,8 +147,8 @@ func (s *sandboxClient) Delete(ctx context.Context, workspace, name string) erro func (s *sandboxClient) Stop(ctx context.Context, workspace, name string) (*Sandbox, error) { resp, err := s.client.StopSandbox(ctx, &pb.StopSandboxRequest{ - Name: name, - Workspace: workspace, + Name: name, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -151,8 +158,8 @@ func (s *sandboxClient) Stop(ctx context.Context, workspace, name string) (*Sand func (s *sandboxClient) Start(ctx context.Context, workspace, name string) (*Sandbox, error) { resp, err := s.client.StartSandbox(ctx, &pb.StartSandboxRequest{ - Name: name, - Workspace: workspace, + Name: name, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -165,7 +172,7 @@ func (s *sandboxClient) AttachProvider(ctx context.Context, workspace, sandboxNa SandboxName: sandboxName, ProviderName: providerName, ExpectedResourceVersion: expectedResourceVersion, - Workspace: workspace, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -181,7 +188,7 @@ func (s *sandboxClient) DetachProvider(ctx context.Context, workspace, sandboxNa SandboxName: sandboxName, ProviderName: providerName, ExpectedResourceVersion: expectedResourceVersion, - Workspace: workspace, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -194,8 +201,8 @@ func (s *sandboxClient) DetachProvider(ctx context.Context, workspace, sandboxNa func (s *sandboxClient) ListProviders(ctx context.Context, workspace, sandboxName string) ([]*Provider, error) { resp, err := s.client.ListSandboxProviders(ctx, &pb.ListSandboxProvidersRequest{ - SandboxName: sandboxName, - Workspace: workspace, + SandboxName: sandboxName, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -361,11 +368,11 @@ func (s *sandboxClient) GetLogs(ctx context.Context, workspace, sandboxName stri cfg := types.ApplyLogOptions(opts) req := &pb.GetSandboxLogsRequest{ - SandboxId: sb.ID, - Lines: cfg.Lines(), - Sources: cfg.Sources(), - MinLevel: cfg.MinLevel(), - Workspace: workspace, + SandboxId: sb.ID, + Lines: cfg.Lines(), + Sources: cfg.Sources(), + MinLevel: cfg.MinLevel(), + WorkspaceScope: namedWorkspaceScope(workspace), } if !cfg.Since().IsZero() { req.SinceMs = converter.MillisFromTime(cfg.Since()) diff --git a/sdk/go/openshell/v1/sandbox_template.go b/sdk/go/openshell/v1/sandbox_template.go index e2f2d71874..395b254bac 100644 --- a/sdk/go/openshell/v1/sandbox_template.go +++ b/sdk/go/openshell/v1/sandbox_template.go @@ -41,5 +41,6 @@ type SandboxTemplateInterface interface { Create(ctx context.Context, workspace string, template *SandboxWorkloadTemplate) (*SandboxWorkloadTemplate, error) Get(ctx context.Context, workspace, name string) (*SandboxWorkloadTemplate, error) List(ctx context.Context, workspace string, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) + ListAll(ctx context.Context, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) Delete(ctx context.Context, workspace, name string) (bool, error) } diff --git a/sdk/go/openshell/v1/sandbox_template_client.go b/sdk/go/openshell/v1/sandbox_template_client.go index de6e19237c..fd9ddb53e3 100644 --- a/sdk/go/openshell/v1/sandbox_template_client.go +++ b/sdk/go/openshell/v1/sandbox_template_client.go @@ -30,8 +30,8 @@ func (s *sandboxTemplateClient) Create(ctx context.Context, workspace string, te return nil, &StatusError{Code: ErrorInvalidArgument, Message: err.Error()} } resp, err := s.client.CreateSandboxTemplate(ctx, &pb.CreateSandboxTemplateRequest{ - Template: protoTemplate, - Workspace: workspace, + Template: protoTemplate, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -41,8 +41,8 @@ func (s *sandboxTemplateClient) Create(ctx context.Context, workspace string, te func (s *sandboxTemplateClient) Get(ctx context.Context, workspace, name string) (*SandboxWorkloadTemplate, error) { resp, err := s.client.GetSandboxTemplate(ctx, &pb.GetSandboxTemplateRequest{ - Name: name, - Workspace: workspace, + Name: name, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -52,8 +52,16 @@ func (s *sandboxTemplateClient) Get(ctx context.Context, workspace, name string) func (s *sandboxTemplateClient) List(ctx context.Context, workspace string, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) { req := &pb.ListSandboxTemplatesRequest{ - Workspace: workspace, + WorkspaceScope: namedWorkspaceScope(workspace), } + return s.list(ctx, req, opts...) +} + +func (s *sandboxTemplateClient) ListAll(ctx context.Context, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) { + return s.list(ctx, &pb.ListSandboxTemplatesRequest{WorkspaceScope: allWorkspacesScope()}, opts...) +} + +func (s *sandboxTemplateClient) list(ctx context.Context, req *pb.ListSandboxTemplatesRequest, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) { if len(opts) > 0 { if opts[0].Limit < 0 { return nil, &StatusError{Code: ErrorInvalidArgument, Message: "limit must not be negative"} @@ -64,10 +72,6 @@ func (s *sandboxTemplateClient) List(ctx context.Context, workspace string, opts req.Limit = uint32(opts[0].Limit) req.Offset = uint32(opts[0].Offset) req.LabelSelector = opts[0].LabelSelector - req.AllWorkspaces = opts[0].AllWorkspaces - if req.AllWorkspaces { - req.Workspace = "" - } } resp, err := s.client.ListSandboxTemplates(ctx, req) @@ -84,8 +88,8 @@ func (s *sandboxTemplateClient) List(ctx context.Context, workspace string, opts func (s *sandboxTemplateClient) Delete(ctx context.Context, workspace, name string) (bool, error) { resp, err := s.client.DeleteSandboxTemplate(ctx, &pb.DeleteSandboxTemplateRequest{ - Name: name, - Workspace: workspace, + Name: name, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return false, converter.FromGRPCError(err) diff --git a/sdk/go/openshell/v1/sandbox_template_client_test.go b/sdk/go/openshell/v1/sandbox_template_client_test.go index 4f9e3058c0..48045dbec8 100644 --- a/sdk/go/openshell/v1/sandbox_template_client_test.go +++ b/sdk/go/openshell/v1/sandbox_template_client_test.go @@ -57,7 +57,7 @@ func (s *mockSandboxTemplateServer) CreateSandboxTemplate(_ context.Context, req if template.Metadata == nil { template.Metadata = &dm.ObjectMeta{} } - template.Metadata.Workspace = req.GetWorkspace() + template.Metadata.Workspace = req.GetWorkspaceScope().GetWorkspace() template.Metadata.ResourceVersion = 1 s.templates[template.Metadata.GetName()] = template return &pb.SandboxTemplateResponse{Template: proto.Clone(template).(*pb.SandboxWorkloadTemplate)}, nil @@ -164,7 +164,7 @@ func TestSandboxTemplateCreate(t *testing.T) { mock.mu.Lock() defer mock.mu.Unlock() require.NotNil(t, mock.createRequest) - assert.Equal(t, "default", mock.createRequest.Workspace) + assert.Equal(t, "default", mock.createRequest.GetWorkspaceScope().GetWorkspace()) assert.Equal(t, "gpu-kata", mock.createRequest.Template.Metadata.Name) assert.Equal(t, "2", mock.createRequest.Template.Spec.Workload.Resources.Cpu) assert.Equal(t, "8Gi", mock.createRequest.Template.Spec.Workload.Resources.Memory) @@ -220,11 +220,10 @@ func TestSandboxTemplateGetListDelete(t *testing.T) { assert.Equal(t, "gpu-kata", got.Name) assert.Equal(t, "img:v1", got.Spec.Workload.Image) - list, err := client.List(context.Background(), "default", ListOptions{ + list, err := client.ListAll(context.Background(), ListOptions{ Limit: 10, Offset: 2, LabelSelector: "team=runtime", - AllWorkspaces: true, }) require.NoError(t, err) require.Len(t, list, 1) @@ -237,16 +236,15 @@ func TestSandboxTemplateGetListDelete(t *testing.T) { mock.mu.Lock() defer mock.mu.Unlock() require.NotNil(t, mock.getRequest) - assert.Equal(t, "default", mock.getRequest.Workspace) + assert.Equal(t, "default", mock.getRequest.GetWorkspaceScope().GetWorkspace()) assert.Equal(t, "gpu-kata", mock.getRequest.Name) require.NotNil(t, mock.listRequest) - assert.Empty(t, mock.listRequest.Workspace) + assert.NotNil(t, mock.listRequest.GetWorkspaceScope().GetAllWorkspaces()) assert.Equal(t, uint32(10), mock.listRequest.Limit) assert.Equal(t, uint32(2), mock.listRequest.Offset) assert.Equal(t, "team=runtime", mock.listRequest.LabelSelector) - assert.True(t, mock.listRequest.AllWorkspaces) require.NotNil(t, mock.deleteRequest) - assert.Equal(t, "default", mock.deleteRequest.Workspace) + assert.Equal(t, "default", mock.deleteRequest.GetWorkspaceScope().GetWorkspace()) assert.Equal(t, "gpu-kata", mock.deleteRequest.Name) } diff --git a/sdk/go/openshell/v1/service.go b/sdk/go/openshell/v1/service.go index 4ee819c522..acdcd1eeb6 100644 --- a/sdk/go/openshell/v1/service.go +++ b/sdk/go/openshell/v1/service.go @@ -17,5 +17,6 @@ type ServiceInterface interface { Expose(ctx context.Context, workspace, sandboxName, serviceName string, targetPort uint32, domain bool) (*ServiceEndpoint, error) Get(ctx context.Context, workspace, sandboxName, serviceName string) (*ServiceEndpoint, error) List(ctx context.Context, workspace, sandboxName string, opts ...ListOptions) ([]*ServiceEndpoint, error) + ListAll(ctx context.Context, opts ...ListOptions) ([]*ServiceEndpoint, error) Delete(ctx context.Context, workspace, sandboxName, serviceName string) error } diff --git a/sdk/go/openshell/v1/service_client.go b/sdk/go/openshell/v1/service_client.go index a16dd0dc05..86013f8b30 100644 --- a/sdk/go/openshell/v1/service_client.go +++ b/sdk/go/openshell/v1/service_client.go @@ -21,11 +21,11 @@ func newServiceClient(conn grpc.ClientConnInterface) *serviceClient { func (s *serviceClient) Expose(ctx context.Context, workspace, sandboxName, serviceName string, targetPort uint32, domain bool) (*ServiceEndpoint, error) { resp, err := s.client.ExposeService(ctx, &pb.ExposeServiceRequest{ - Sandbox: sandboxName, - Service: serviceName, - TargetPort: targetPort, - Domain: domain, - Workspace: workspace, + Sandbox: sandboxName, + Service: serviceName, + TargetPort: targetPort, + Domain: domain, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -35,9 +35,9 @@ func (s *serviceClient) Expose(ctx context.Context, workspace, sandboxName, serv func (s *serviceClient) Get(ctx context.Context, workspace, sandboxName, serviceName string) (*ServiceEndpoint, error) { resp, err := s.client.GetService(ctx, &pb.GetServiceRequest{ - Sandbox: sandboxName, - Service: serviceName, - Workspace: workspace, + Sandbox: sandboxName, + Service: serviceName, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return nil, converter.FromGRPCError(err) @@ -47,9 +47,17 @@ func (s *serviceClient) Get(ctx context.Context, workspace, sandboxName, service func (s *serviceClient) List(ctx context.Context, workspace, sandboxName string, opts ...ListOptions) ([]*ServiceEndpoint, error) { req := &pb.ListServicesRequest{ - Sandbox: sandboxName, - Workspace: workspace, + Sandbox: sandboxName, + WorkspaceScope: namedWorkspaceScope(workspace), } + return s.list(ctx, req, opts...) +} + +func (s *serviceClient) ListAll(ctx context.Context, opts ...ListOptions) ([]*ServiceEndpoint, error) { + return s.list(ctx, &pb.ListServicesRequest{WorkspaceScope: allWorkspacesScope()}, opts...) +} + +func (s *serviceClient) list(ctx context.Context, req *pb.ListServicesRequest, opts ...ListOptions) ([]*ServiceEndpoint, error) { if len(opts) > 0 { if opts[0].Limit < 0 { return nil, &StatusError{Code: ErrorInvalidArgument, Message: "limit must not be negative"} @@ -59,7 +67,6 @@ func (s *serviceClient) List(ctx context.Context, workspace, sandboxName string, } req.Limit = uint32(opts[0].Limit) req.Offset = uint32(opts[0].Offset) - req.AllWorkspaces = opts[0].AllWorkspaces } resp, err := s.client.ListServices(ctx, req) @@ -76,9 +83,9 @@ func (s *serviceClient) List(ctx context.Context, workspace, sandboxName string, func (s *serviceClient) Delete(ctx context.Context, workspace, sandboxName, serviceName string) error { _, err := s.client.DeleteService(ctx, &pb.DeleteServiceRequest{ - Sandbox: sandboxName, - Service: serviceName, - Workspace: workspace, + Sandbox: sandboxName, + Service: serviceName, + WorkspaceScope: namedWorkspaceScope(workspace), }) if err != nil { return converter.FromGRPCError(err) diff --git a/sdk/go/openshell/v1/service_client_test.go b/sdk/go/openshell/v1/service_client_test.go index 334acd215a..bf0b4eccb8 100644 --- a/sdk/go/openshell/v1/service_client_test.go +++ b/sdk/go/openshell/v1/service_client_test.go @@ -30,6 +30,7 @@ type mockServiceServer struct { getErr error listErr error deleteErr error + lastList *pb.ListServicesRequest } func newMockServiceServer() *mockServiceServer { @@ -85,6 +86,7 @@ func (s *mockServiceServer) GetService(_ context.Context, req *pb.GetServiceRequ func (s *mockServiceServer) ListServices(_ context.Context, req *pb.ListServicesRequest) (*pb.ListServicesResponse, error) { s.mu.Lock() defer s.mu.Unlock() + s.lastList = req if s.listErr != nil { return nil, s.listErr } @@ -266,6 +268,20 @@ func TestServiceList_WithOptions(t *testing.T) { assert.Len(t, endpoints, 1) } +func TestServiceListAll_SelectsAllWorkspaces(t *testing.T) { + mock := newMockServiceServer() + client, cleanup := setupServiceTest(t, mock) + defer cleanup() + + endpoints, err := client.ListAll(context.Background(), ListOptions{Limit: 10}) + + require.NoError(t, err) + assert.Empty(t, endpoints) + require.NotNil(t, mock.lastList) + assert.Empty(t, mock.lastList.GetSandbox()) + assert.NotNil(t, mock.lastList.GetWorkspaceScope().GetAllWorkspaces()) +} + func TestServiceList_Error(t *testing.T) { mock := newMockServiceServer() mock.listErr = status.Errorf(codes.Unavailable, "unavailable") diff --git a/sdk/go/openshell/v1/ssh_client_test.go b/sdk/go/openshell/v1/ssh_client_test.go index 5b600b3370..f1d0516ca1 100644 --- a/sdk/go/openshell/v1/ssh_client_test.go +++ b/sdk/go/openshell/v1/ssh_client_test.go @@ -152,6 +152,9 @@ func (m *mockSandboxResolver) Get(_ context.Context, _, name string) (*Sandbox, func (m *mockSandboxResolver) List(_ context.Context, _ string, _ ...ListOptions) ([]*Sandbox, error) { return nil, nil } +func (m *mockSandboxResolver) ListAll(_ context.Context, _ ...ListOptions) ([]*Sandbox, error) { + return nil, nil +} func (m *mockSandboxResolver) Delete(_ context.Context, _, _ string) error { return nil } func (m *mockSandboxResolver) AttachProvider(_ context.Context, _, _, _ string, _ uint64) (*AttachProviderResult, error) { return nil, nil diff --git a/sdk/go/openshell/v1/tcp_client_test.go b/sdk/go/openshell/v1/tcp_client_test.go index e445ab2fab..100a746ccb 100644 --- a/sdk/go/openshell/v1/tcp_client_test.go +++ b/sdk/go/openshell/v1/tcp_client_test.go @@ -999,6 +999,9 @@ func (r *flippableResolver) Create(context.Context, string, string, *SandboxSpec func (r *flippableResolver) List(context.Context, string, ...ListOptions) ([]*Sandbox, error) { panic("not implemented") } +func (r *flippableResolver) ListAll(context.Context, ...ListOptions) ([]*Sandbox, error) { + panic("not implemented") +} func (r *flippableResolver) Delete(context.Context, string, string) error { panic("not implemented") } diff --git a/sdk/go/openshell/v1/types/options.go b/sdk/go/openshell/v1/types/options.go index b0f6145999..0d9136a407 100644 --- a/sdk/go/openshell/v1/types/options.go +++ b/sdk/go/openshell/v1/types/options.go @@ -15,7 +15,6 @@ type ListOptions struct { Limit int Offset int LabelSelector string - AllWorkspaces bool } // WatchOptions configures watch behavior. diff --git a/sdk/go/openshell/v1/workspace_scope.go b/sdk/go/openshell/v1/workspace_scope.go new file mode 100644 index 0000000000..0ae2e8d52e --- /dev/null +++ b/sdk/go/openshell/v1/workspace_scope.go @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package v1 + +import dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1" + +func namedWorkspaceScope(workspace string) *dm.WorkspaceSelector { + return &dm.WorkspaceSelector{ + Selection: &dm.WorkspaceSelector_Workspace{Workspace: workspace}, + } +} + +func allWorkspacesScope() *dm.WorkspaceSelector { + return &dm.WorkspaceSelector{ + Selection: &dm.WorkspaceSelector_AllWorkspaces{AllWorkspaces: &dm.AllWorkspaces{}}, + } +} diff --git a/sdk/go/proto/datamodelv1/datamodel.pb.go b/sdk/go/proto/datamodelv1/datamodel.pb.go index a672bf3d8b..1b9eec16b4 100644 --- a/sdk/go/proto/datamodelv1/datamodel.pb.go +++ b/sdk/go/proto/datamodelv1/datamodel.pb.go @@ -75,6 +75,135 @@ func (WorkspacePhase) EnumDescriptor() ([]byte, []int) { return file_datamodel_proto_rawDescGZIP(), []int{0} } +// Selects the workspace scope for a public API request. +// +// Requests that operate on one workspace require a non-empty `workspace`. +// Cross-workspace list requests additionally accept `all_workspaces`. The +// containing request documents which selections it supports; an omitted +// selector is invalid for workspace-scoped operations. +type WorkspaceSelector struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Types that are valid to be assigned to Selection: + // + // *WorkspaceSelector_Workspace + // *WorkspaceSelector_AllWorkspaces + Selection isWorkspaceSelector_Selection `protobuf_oneof:"selection"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkspaceSelector) Reset() { + *x = WorkspaceSelector{} + mi := &file_datamodel_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkspaceSelector) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkspaceSelector) ProtoMessage() {} + +func (x *WorkspaceSelector) ProtoReflect() protoreflect.Message { + mi := &file_datamodel_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkspaceSelector.ProtoReflect.Descriptor instead. +func (*WorkspaceSelector) Descriptor() ([]byte, []int) { + return file_datamodel_proto_rawDescGZIP(), []int{0} +} + +func (x *WorkspaceSelector) GetSelection() isWorkspaceSelector_Selection { + if x != nil { + return x.Selection + } + return nil +} + +func (x *WorkspaceSelector) GetWorkspace() string { + if x != nil { + if x, ok := x.Selection.(*WorkspaceSelector_Workspace); ok { + return x.Workspace + } + } + return "" +} + +func (x *WorkspaceSelector) GetAllWorkspaces() *AllWorkspaces { + if x != nil { + if x, ok := x.Selection.(*WorkspaceSelector_AllWorkspaces); ok { + return x.AllWorkspaces + } + } + return nil +} + +type isWorkspaceSelector_Selection interface { + isWorkspaceSelector_Selection() +} + +type WorkspaceSelector_Workspace struct { + // One explicitly named workspace. Use `default` to select the gateway's + // default workspace; an empty name is invalid. + Workspace string `protobuf:"bytes,1,opt,name=workspace,proto3,oneof"` +} + +type WorkspaceSelector_AllWorkspaces struct { + // All workspaces the caller is authorized to access. Only supported by + // requests that explicitly document cross-workspace behavior. + AllWorkspaces *AllWorkspaces `protobuf:"bytes,2,opt,name=all_workspaces,json=allWorkspaces,proto3,oneof"` +} + +func (*WorkspaceSelector_Workspace) isWorkspaceSelector_Selection() {} + +func (*WorkspaceSelector_AllWorkspaces) isWorkspaceSelector_Selection() {} + +// Marker for the all-workspaces selector variant. +type AllWorkspaces struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AllWorkspaces) Reset() { + *x = AllWorkspaces{} + mi := &file_datamodel_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AllWorkspaces) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AllWorkspaces) ProtoMessage() {} + +func (x *AllWorkspaces) ProtoReflect() protoreflect.Message { + mi := &file_datamodel_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AllWorkspaces.ProtoReflect.Descriptor instead. +func (*AllWorkspaces) Descriptor() ([]byte, []int) { + return file_datamodel_proto_rawDescGZIP(), []int{1} +} + // Kubernetes-style metadata shared by all top-level OpenShell domain objects. // // This structure provides consistent metadata (identity, labels, annotations, @@ -110,7 +239,7 @@ type ObjectMeta struct { func (x *ObjectMeta) Reset() { *x = ObjectMeta{} - mi := &file_datamodel_proto_msgTypes[0] + mi := &file_datamodel_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -122,7 +251,7 @@ func (x *ObjectMeta) String() string { func (*ObjectMeta) ProtoMessage() {} func (x *ObjectMeta) ProtoReflect() protoreflect.Message { - mi := &file_datamodel_proto_msgTypes[0] + mi := &file_datamodel_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -135,7 +264,7 @@ func (x *ObjectMeta) ProtoReflect() protoreflect.Message { // Deprecated: Use ObjectMeta.ProtoReflect.Descriptor instead. func (*ObjectMeta) Descriptor() ([]byte, []int) { - return file_datamodel_proto_rawDescGZIP(), []int{0} + return file_datamodel_proto_rawDescGZIP(), []int{2} } func (x *ObjectMeta) GetId() string { @@ -204,7 +333,7 @@ type WorkspaceStatus struct { func (x *WorkspaceStatus) Reset() { *x = WorkspaceStatus{} - mi := &file_datamodel_proto_msgTypes[1] + mi := &file_datamodel_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -216,7 +345,7 @@ func (x *WorkspaceStatus) String() string { func (*WorkspaceStatus) ProtoMessage() {} func (x *WorkspaceStatus) ProtoReflect() protoreflect.Message { - mi := &file_datamodel_proto_msgTypes[1] + mi := &file_datamodel_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -229,7 +358,7 @@ func (x *WorkspaceStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceStatus.ProtoReflect.Descriptor instead. func (*WorkspaceStatus) Descriptor() ([]byte, []int) { - return file_datamodel_proto_rawDescGZIP(), []int{1} + return file_datamodel_proto_rawDescGZIP(), []int{3} } func (x *WorkspaceStatus) GetPhase() WorkspacePhase { @@ -255,7 +384,7 @@ type Workspace struct { func (x *Workspace) Reset() { *x = Workspace{} - mi := &file_datamodel_proto_msgTypes[2] + mi := &file_datamodel_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -267,7 +396,7 @@ func (x *Workspace) String() string { func (*Workspace) ProtoMessage() {} func (x *Workspace) ProtoReflect() protoreflect.Message { - mi := &file_datamodel_proto_msgTypes[2] + mi := &file_datamodel_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -280,7 +409,7 @@ func (x *Workspace) ProtoReflect() protoreflect.Message { // Deprecated: Use Workspace.ProtoReflect.Descriptor instead. func (*Workspace) Descriptor() ([]byte, []int) { - return file_datamodel_proto_rawDescGZIP(), []int{2} + return file_datamodel_proto_rawDescGZIP(), []int{4} } func (x *Workspace) GetMetadata() *ObjectMeta { @@ -313,7 +442,7 @@ type CredentialHandle struct { func (x *CredentialHandle) Reset() { *x = CredentialHandle{} - mi := &file_datamodel_proto_msgTypes[3] + mi := &file_datamodel_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -325,7 +454,7 @@ func (x *CredentialHandle) String() string { func (*CredentialHandle) ProtoMessage() {} func (x *CredentialHandle) ProtoReflect() protoreflect.Message { - mi := &file_datamodel_proto_msgTypes[3] + mi := &file_datamodel_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -338,7 +467,7 @@ func (x *CredentialHandle) ProtoReflect() protoreflect.Message { // Deprecated: Use CredentialHandle.ProtoReflect.Descriptor instead. func (*CredentialHandle) Descriptor() ([]byte, []int) { - return file_datamodel_proto_rawDescGZIP(), []int{3} + return file_datamodel_proto_rawDescGZIP(), []int{5} } func (x *CredentialHandle) GetDriver() string { @@ -389,7 +518,7 @@ type Provider struct { func (x *Provider) Reset() { *x = Provider{} - mi := &file_datamodel_proto_msgTypes[4] + mi := &file_datamodel_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -401,7 +530,7 @@ func (x *Provider) String() string { func (*Provider) ProtoMessage() {} func (x *Provider) ProtoReflect() protoreflect.Message { - mi := &file_datamodel_proto_msgTypes[4] + mi := &file_datamodel_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -414,7 +543,7 @@ func (x *Provider) ProtoReflect() protoreflect.Message { // Deprecated: Use Provider.ProtoReflect.Descriptor instead. func (*Provider) Descriptor() ([]byte, []int) { - return file_datamodel_proto_rawDescGZIP(), []int{4} + return file_datamodel_proto_rawDescGZIP(), []int{6} } func (x *Provider) GetMetadata() *ObjectMeta { @@ -470,7 +599,12 @@ var File_datamodel_proto protoreflect.FileDescriptor const file_datamodel_proto_rawDesc = "" + "\n" + - "\x0fdatamodel.proto\x12\x16openshell.datamodel.v1\x1a\roptions.proto\"\xeb\x03\n" + + "\x0fdatamodel.proto\x12\x16openshell.datamodel.v1\x1a\roptions.proto\"\x90\x01\n" + + "\x11WorkspaceSelector\x12\x1e\n" + + "\tworkspace\x18\x01 \x01(\tH\x00R\tworkspace\x12N\n" + + "\x0eall_workspaces\x18\x02 \x01(\v2%.openshell.datamodel.v1.AllWorkspacesH\x00R\rallWorkspacesB\v\n" + + "\tselection\"\x0f\n" + + "\rAllWorkspaces\"\xeb\x03\n" + "\n" + "ObjectMeta\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + @@ -537,40 +671,43 @@ func file_datamodel_proto_rawDescGZIP() []byte { } var file_datamodel_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_datamodel_proto_msgTypes = make([]protoimpl.MessageInfo, 12) +var file_datamodel_proto_msgTypes = make([]protoimpl.MessageInfo, 14) var file_datamodel_proto_goTypes = []any{ - (WorkspacePhase)(0), // 0: openshell.datamodel.v1.WorkspacePhase - (*ObjectMeta)(nil), // 1: openshell.datamodel.v1.ObjectMeta - (*WorkspaceStatus)(nil), // 2: openshell.datamodel.v1.WorkspaceStatus - (*Workspace)(nil), // 3: openshell.datamodel.v1.Workspace - (*CredentialHandle)(nil), // 4: openshell.datamodel.v1.CredentialHandle - (*Provider)(nil), // 5: openshell.datamodel.v1.Provider - nil, // 6: openshell.datamodel.v1.ObjectMeta.LabelsEntry - nil, // 7: openshell.datamodel.v1.ObjectMeta.AnnotationsEntry - nil, // 8: openshell.datamodel.v1.CredentialHandle.MetadataEntry - nil, // 9: openshell.datamodel.v1.Provider.CredentialsEntry - nil, // 10: openshell.datamodel.v1.Provider.ConfigEntry - nil, // 11: openshell.datamodel.v1.Provider.CredentialExpiresAtMsEntry - nil, // 12: openshell.datamodel.v1.Provider.CredentialHandlesEntry + (WorkspacePhase)(0), // 0: openshell.datamodel.v1.WorkspacePhase + (*WorkspaceSelector)(nil), // 1: openshell.datamodel.v1.WorkspaceSelector + (*AllWorkspaces)(nil), // 2: openshell.datamodel.v1.AllWorkspaces + (*ObjectMeta)(nil), // 3: openshell.datamodel.v1.ObjectMeta + (*WorkspaceStatus)(nil), // 4: openshell.datamodel.v1.WorkspaceStatus + (*Workspace)(nil), // 5: openshell.datamodel.v1.Workspace + (*CredentialHandle)(nil), // 6: openshell.datamodel.v1.CredentialHandle + (*Provider)(nil), // 7: openshell.datamodel.v1.Provider + nil, // 8: openshell.datamodel.v1.ObjectMeta.LabelsEntry + nil, // 9: openshell.datamodel.v1.ObjectMeta.AnnotationsEntry + nil, // 10: openshell.datamodel.v1.CredentialHandle.MetadataEntry + nil, // 11: openshell.datamodel.v1.Provider.CredentialsEntry + nil, // 12: openshell.datamodel.v1.Provider.ConfigEntry + nil, // 13: openshell.datamodel.v1.Provider.CredentialExpiresAtMsEntry + nil, // 14: openshell.datamodel.v1.Provider.CredentialHandlesEntry } var file_datamodel_proto_depIdxs = []int32{ - 6, // 0: openshell.datamodel.v1.ObjectMeta.labels:type_name -> openshell.datamodel.v1.ObjectMeta.LabelsEntry - 7, // 1: openshell.datamodel.v1.ObjectMeta.annotations:type_name -> openshell.datamodel.v1.ObjectMeta.AnnotationsEntry - 0, // 2: openshell.datamodel.v1.WorkspaceStatus.phase:type_name -> openshell.datamodel.v1.WorkspacePhase - 1, // 3: openshell.datamodel.v1.Workspace.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 2, // 4: openshell.datamodel.v1.Workspace.status:type_name -> openshell.datamodel.v1.WorkspaceStatus - 8, // 5: openshell.datamodel.v1.CredentialHandle.metadata:type_name -> openshell.datamodel.v1.CredentialHandle.MetadataEntry - 1, // 6: openshell.datamodel.v1.Provider.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 9, // 7: openshell.datamodel.v1.Provider.credentials:type_name -> openshell.datamodel.v1.Provider.CredentialsEntry - 10, // 8: openshell.datamodel.v1.Provider.config:type_name -> openshell.datamodel.v1.Provider.ConfigEntry - 11, // 9: openshell.datamodel.v1.Provider.credential_expires_at_ms:type_name -> openshell.datamodel.v1.Provider.CredentialExpiresAtMsEntry - 12, // 10: openshell.datamodel.v1.Provider.credential_handles:type_name -> openshell.datamodel.v1.Provider.CredentialHandlesEntry - 4, // 11: openshell.datamodel.v1.Provider.CredentialHandlesEntry.value:type_name -> openshell.datamodel.v1.CredentialHandle - 12, // [12:12] is the sub-list for method output_type - 12, // [12:12] is the sub-list for method input_type - 12, // [12:12] is the sub-list for extension type_name - 12, // [12:12] is the sub-list for extension extendee - 0, // [0:12] is the sub-list for field type_name + 2, // 0: openshell.datamodel.v1.WorkspaceSelector.all_workspaces:type_name -> openshell.datamodel.v1.AllWorkspaces + 8, // 1: openshell.datamodel.v1.ObjectMeta.labels:type_name -> openshell.datamodel.v1.ObjectMeta.LabelsEntry + 9, // 2: openshell.datamodel.v1.ObjectMeta.annotations:type_name -> openshell.datamodel.v1.ObjectMeta.AnnotationsEntry + 0, // 3: openshell.datamodel.v1.WorkspaceStatus.phase:type_name -> openshell.datamodel.v1.WorkspacePhase + 3, // 4: openshell.datamodel.v1.Workspace.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 4, // 5: openshell.datamodel.v1.Workspace.status:type_name -> openshell.datamodel.v1.WorkspaceStatus + 10, // 6: openshell.datamodel.v1.CredentialHandle.metadata:type_name -> openshell.datamodel.v1.CredentialHandle.MetadataEntry + 3, // 7: openshell.datamodel.v1.Provider.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 11, // 8: openshell.datamodel.v1.Provider.credentials:type_name -> openshell.datamodel.v1.Provider.CredentialsEntry + 12, // 9: openshell.datamodel.v1.Provider.config:type_name -> openshell.datamodel.v1.Provider.ConfigEntry + 13, // 10: openshell.datamodel.v1.Provider.credential_expires_at_ms:type_name -> openshell.datamodel.v1.Provider.CredentialExpiresAtMsEntry + 14, // 11: openshell.datamodel.v1.Provider.credential_handles:type_name -> openshell.datamodel.v1.Provider.CredentialHandlesEntry + 6, // 12: openshell.datamodel.v1.Provider.CredentialHandlesEntry.value:type_name -> openshell.datamodel.v1.CredentialHandle + 13, // [13:13] is the sub-list for method output_type + 13, // [13:13] is the sub-list for method input_type + 13, // [13:13] is the sub-list for extension type_name + 13, // [13:13] is the sub-list for extension extendee + 0, // [0:13] is the sub-list for field type_name } func init() { file_datamodel_proto_init() } @@ -578,13 +715,17 @@ func file_datamodel_proto_init() { if File_datamodel_proto != nil { return } + file_datamodel_proto_msgTypes[0].OneofWrappers = []any{ + (*WorkspaceSelector_Workspace)(nil), + (*WorkspaceSelector_AllWorkspaces)(nil), + } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_datamodel_proto_rawDesc), len(file_datamodel_proto_rawDesc)), NumEnums: 1, - NumMessages: 12, + NumMessages: 14, NumExtensions: 0, NumServices: 0, }, diff --git a/sdk/go/proto/openshellv1/openshell.pb.go b/sdk/go/proto/openshellv1/openshell.pb.go index 1716e006ee..6443c3a361 100644 --- a/sdk/go/proto/openshellv1/openshell.pb.go +++ b/sdk/go/proto/openshellv1/openshell.pb.go @@ -2477,16 +2477,16 @@ type CreateSandboxRequest struct { Labels map[string]string `protobuf:"bytes,3,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // Optional annotations for the sandbox (non-selector metadata). Annotations map[string]string `protobuf:"bytes,4,rep,name=annotations,proto3" json:"annotations,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - // Workspace for the sandbox. Empty defaults to "default". - Workspace string `protobuf:"bytes,5,opt,name=workspace,proto3" json:"workspace,omitempty"` // One-shot launch hint indicating that the creating client will attach to // the canonical main process. The supervisor keeps the terminal transport // alive until that attachment connects and closes naturally. AwaitMainProcessAttachment bool `protobuf:"varint,6,opt,name=await_main_process_attachment,json=awaitMainProcessAttachment,proto3" json:"await_main_process_attachment,omitempty"` // Workspace-scoped SandboxWorkloadTemplate name to resolve at creation time. WorkloadTemplateName string `protobuf:"bytes,7,opt,name=workload_template_name,json=workloadTemplateName,proto3" json:"workload_template_name,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace for the sandbox. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,8,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *CreateSandboxRequest) Reset() { @@ -2547,13 +2547,6 @@ func (x *CreateSandboxRequest) GetAnnotations() map[string]string { return nil } -func (x *CreateSandboxRequest) GetWorkspace() string { - if x != nil { - return x.Workspace - } - return "" -} - func (x *CreateSandboxRequest) GetAwaitMainProcessAttachment() bool { if x != nil { return x.AwaitMainProcessAttachment @@ -2568,13 +2561,20 @@ func (x *CreateSandboxRequest) GetWorkloadTemplateName() string { return "" } +func (x *CreateSandboxRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { + if x != nil { + return x.WorkspaceScope + } + return nil +} + type CreateSandboxTemplateRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Template *SandboxWorkloadTemplate `protobuf:"bytes,1,opt,name=template,proto3" json:"template,omitempty"` - // Workspace for the template. Empty defaults to "default". - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace for the template. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *CreateSandboxTemplateRequest) Reset() { @@ -2614,20 +2614,20 @@ func (x *CreateSandboxTemplateRequest) GetTemplate() *SandboxWorkloadTemplate { return nil } -func (x *CreateSandboxTemplateRequest) GetWorkspace() string { +func (x *CreateSandboxTemplateRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type GetSandboxTemplateRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetSandboxTemplateRequest) Reset() { @@ -2667,25 +2667,23 @@ func (x *GetSandboxTemplateRequest) GetName() string { return "" } -func (x *GetSandboxTemplateRequest) GetWorkspace() string { +func (x *GetSandboxTemplateRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type ListSandboxTemplatesRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Limit uint32 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"` Offset uint32 `protobuf:"varint,2,opt,name=offset,proto3" json:"offset,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` - // List across all workspaces. Mutually exclusive with workspace. - AllWorkspaces bool `protobuf:"varint,4,opt,name=all_workspaces,json=allWorkspaces,proto3" json:"all_workspaces,omitempty"` // Optional label selector in key=value comma-separated form. LabelSelector string `protobuf:"bytes,5,opt,name=label_selector,json=labelSelector,proto3" json:"label_selector,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit named or all-workspaces scope. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,6,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ListSandboxTemplatesRequest) Reset() { @@ -2732,34 +2730,27 @@ func (x *ListSandboxTemplatesRequest) GetOffset() uint32 { return 0 } -func (x *ListSandboxTemplatesRequest) GetWorkspace() string { +func (x *ListSandboxTemplatesRequest) GetLabelSelector() string { if x != nil { - return x.Workspace + return x.LabelSelector } return "" } -func (x *ListSandboxTemplatesRequest) GetAllWorkspaces() bool { - if x != nil { - return x.AllWorkspaces - } - return false -} - -func (x *ListSandboxTemplatesRequest) GetLabelSelector() string { +func (x *ListSandboxTemplatesRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.LabelSelector + return x.WorkspaceScope } - return "" + return nil } type DeleteSandboxTemplateRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *DeleteSandboxTemplateRequest) Reset() { @@ -2799,11 +2790,11 @@ func (x *DeleteSandboxTemplateRequest) GetName() string { return "" } -func (x *DeleteSandboxTemplateRequest) GetWorkspace() string { +func (x *DeleteSandboxTemplateRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type SandboxTemplateResponse struct { @@ -2941,17 +2932,17 @@ func (x *DeleteSandboxTemplateResponse) GetDeleted() bool { // Request a gateway-owned staging slot for a local rootfs tar archive. type BeginRootfsTarStagingRequest struct { state protoimpl.MessageState `protogen:"open.v1"` - // Workspace that will own the sandbox created from this archive. Empty - // defaults to "default", matching CreateSandboxRequest.workspace. - Workspace string `protobuf:"bytes,1,opt,name=workspace,proto3" json:"workspace,omitempty"` // Base file name of the local archive. The gateway uses it only to name the // staged file; path separators and traversal components are rejected. FileName string `protobuf:"bytes,2,opt,name=file_name,json=fileName,proto3" json:"file_name,omitempty"` // Size of the local archive in bytes, checked against the driver limit // before the gateway allocates a slot. - SizeBytes uint64 `protobuf:"varint,3,opt,name=size_bytes,json=sizeBytes,proto3" json:"size_bytes,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + SizeBytes uint64 `protobuf:"varint,3,opt,name=size_bytes,json=sizeBytes,proto3" json:"size_bytes,omitempty"` + // Explicit workspace that will own the sandbox created from this archive. + // The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *BeginRootfsTarStagingRequest) Reset() { @@ -2984,13 +2975,6 @@ func (*BeginRootfsTarStagingRequest) Descriptor() ([]byte, []int) { return file_openshell_proto_rawDescGZIP(), []int{39} } -func (x *BeginRootfsTarStagingRequest) GetWorkspace() string { - if x != nil { - return x.Workspace - } - return "" -} - func (x *BeginRootfsTarStagingRequest) GetFileName() string { if x != nil { return x.FileName @@ -3005,6 +2989,13 @@ func (x *BeginRootfsTarStagingRequest) GetSizeBytes() uint64 { return 0 } +func (x *BeginRootfsTarStagingRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { + if x != nil { + return x.WorkspaceScope + } + return nil +} + // Gateway-issued staging slot. type BeginRootfsTarStagingResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -3085,10 +3076,10 @@ type GetSandboxRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Sandbox name (canonical lookup key). Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetSandboxRequest) Reset() { @@ -3128,11 +3119,11 @@ func (x *GetSandboxRequest) GetName() string { return "" } -func (x *GetSandboxRequest) GetWorkspace() string { +func (x *GetSandboxRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // List sandboxes request. @@ -3142,12 +3133,10 @@ type ListSandboxesRequest struct { Offset uint32 `protobuf:"varint,2,opt,name=offset,proto3" json:"offset,omitempty"` // Optional label selector for filtering (format: "key1=value1,key2=value2"). LabelSelector string `protobuf:"bytes,3,opt,name=label_selector,json=labelSelector,proto3" json:"label_selector,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,4,opt,name=workspace,proto3" json:"workspace,omitempty"` - // List across all workspaces. Mutually exclusive with workspace. - AllWorkspaces bool `protobuf:"varint,5,opt,name=all_workspaces,json=allWorkspaces,proto3" json:"all_workspaces,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit named or all-workspaces scope. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,6,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ListSandboxesRequest) Reset() { @@ -3201,18 +3190,11 @@ func (x *ListSandboxesRequest) GetLabelSelector() string { return "" } -func (x *ListSandboxesRequest) GetWorkspace() string { - if x != nil { - return x.Workspace - } - return "" -} - -func (x *ListSandboxesRequest) GetAllWorkspaces() bool { +func (x *ListSandboxesRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.AllWorkspaces + return x.WorkspaceScope } - return false + return nil } // List providers attached to a sandbox request. @@ -3220,10 +3202,10 @@ type ListSandboxProvidersRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Sandbox name (canonical lookup key). SandboxName string `protobuf:"bytes,1,opt,name=sandbox_name,json=sandboxName,proto3" json:"sandbox_name,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ListSandboxProvidersRequest) Reset() { @@ -3263,11 +3245,11 @@ func (x *ListSandboxProvidersRequest) GetSandboxName() string { return "" } -func (x *ListSandboxProvidersRequest) GetWorkspace() string { +func (x *ListSandboxProvidersRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Attach provider to sandbox request. @@ -3282,10 +3264,10 @@ type AttachSandboxProviderRequest struct { // If non-zero, the server validates that the sandbox's current resource_version // matches this value before applying the mutation, returning ABORTED on mismatch. ExpectedResourceVersion uint64 `protobuf:"varint,3,opt,name=expected_resource_version,json=expectedResourceVersion,proto3" json:"expected_resource_version,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,4,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *AttachSandboxProviderRequest) Reset() { @@ -3339,11 +3321,11 @@ func (x *AttachSandboxProviderRequest) GetExpectedResourceVersion() uint64 { return 0 } -func (x *AttachSandboxProviderRequest) GetWorkspace() string { +func (x *AttachSandboxProviderRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Detach provider from sandbox request. @@ -3358,10 +3340,10 @@ type DetachSandboxProviderRequest struct { // If non-zero, the server validates that the sandbox's current resource_version // matches this value before applying the mutation, returning ABORTED on mismatch. ExpectedResourceVersion uint64 `protobuf:"varint,3,opt,name=expected_resource_version,json=expectedResourceVersion,proto3" json:"expected_resource_version,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,4,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *DetachSandboxProviderRequest) Reset() { @@ -3415,11 +3397,11 @@ func (x *DetachSandboxProviderRequest) GetExpectedResourceVersion() uint64 { return 0 } -func (x *DetachSandboxProviderRequest) GetWorkspace() string { +func (x *DetachSandboxProviderRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Delete sandbox request. @@ -3427,10 +3409,10 @@ type DeleteSandboxRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Sandbox name (canonical lookup key). Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *DeleteSandboxRequest) Reset() { @@ -3470,11 +3452,11 @@ func (x *DeleteSandboxRequest) GetName() string { return "" } -func (x *DeleteSandboxRequest) GetWorkspace() string { +func (x *DeleteSandboxRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Stop sandbox request. @@ -3482,10 +3464,10 @@ type StopSandboxRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Sandbox name (canonical lookup key). Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *StopSandboxRequest) Reset() { @@ -3525,11 +3507,11 @@ func (x *StopSandboxRequest) GetName() string { return "" } -func (x *StopSandboxRequest) GetWorkspace() string { +func (x *StopSandboxRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Start sandbox request. @@ -3537,10 +3519,10 @@ type StartSandboxRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Sandbox name (canonical lookup key). Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *StartSandboxRequest) Reset() { @@ -3580,11 +3562,11 @@ func (x *StartSandboxRequest) GetName() string { return "" } -func (x *StartSandboxRequest) GetWorkspace() string { +func (x *StartSandboxRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Sandbox response. @@ -4042,10 +4024,10 @@ type ExposeServiceRequest struct { TargetPort uint32 `protobuf:"varint,3,opt,name=target_port,json=targetPort,proto3" json:"target_port,omitempty"` // Whether to print/use the browser-facing service URL. Domain bool `protobuf:"varint,4,opt,name=domain,proto3" json:"domain,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,5,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,6,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExposeServiceRequest) Reset() { @@ -4106,11 +4088,11 @@ func (x *ExposeServiceRequest) GetDomain() bool { return false } -func (x *ExposeServiceRequest) GetWorkspace() string { +func (x *ExposeServiceRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Request to fetch an exposed sandbox service endpoint. @@ -4120,10 +4102,10 @@ type GetServiceRequest struct { Sandbox string `protobuf:"bytes,1,opt,name=sandbox,proto3" json:"sandbox,omitempty"` // Service name within the sandbox. Empty selects the unnamed endpoint. Service string `protobuf:"bytes,2,opt,name=service,proto3" json:"service,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetServiceRequest) Reset() { @@ -4170,11 +4152,11 @@ func (x *GetServiceRequest) GetService() string { return "" } -func (x *GetServiceRequest) GetWorkspace() string { +func (x *GetServiceRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Request to list exposed sandbox service endpoints. @@ -4186,12 +4168,10 @@ type ListServicesRequest struct { Limit uint32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` // Page offset. Offset uint32 `protobuf:"varint,3,opt,name=offset,proto3" json:"offset,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,4,opt,name=workspace,proto3" json:"workspace,omitempty"` - // List across all workspaces. Mutually exclusive with workspace. - AllWorkspaces bool `protobuf:"varint,5,opt,name=all_workspaces,json=allWorkspaces,proto3" json:"all_workspaces,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit named or all-workspaces scope. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,6,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ListServicesRequest) Reset() { @@ -4245,18 +4225,11 @@ func (x *ListServicesRequest) GetOffset() uint32 { return 0 } -func (x *ListServicesRequest) GetWorkspace() string { - if x != nil { - return x.Workspace - } - return "" -} - -func (x *ListServicesRequest) GetAllWorkspaces() bool { +func (x *ListServicesRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.AllWorkspaces + return x.WorkspaceScope } - return false + return nil } // Response containing exposed sandbox service endpoints. @@ -4311,10 +4284,10 @@ type DeleteServiceRequest struct { Sandbox string `protobuf:"bytes,1,opt,name=sandbox,proto3" json:"sandbox,omitempty"` // Service name within the sandbox. Empty selects the unnamed endpoint. Service string `protobuf:"bytes,2,opt,name=service,proto3" json:"service,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *DeleteServiceRequest) Reset() { @@ -4361,11 +4334,11 @@ func (x *DeleteServiceRequest) GetService() string { return "" } -func (x *DeleteServiceRequest) GetWorkspace() string { +func (x *DeleteServiceRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Response for deleting an exposed sandbox service endpoint. @@ -5858,10 +5831,10 @@ func (x *SandboxStreamWarning) GetMessage() string { type CreateProviderRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Provider *datamodelv1.Provider `protobuf:"bytes,1,opt,name=provider,proto3" json:"provider,omitempty"` - // Workspace for the provider. Empty defaults to "default". - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace for the provider. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *CreateProviderRequest) Reset() { @@ -5901,21 +5874,21 @@ func (x *CreateProviderRequest) GetProvider() *datamodelv1.Provider { return nil } -func (x *CreateProviderRequest) GetWorkspace() string { +func (x *CreateProviderRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Get provider request. type GetProviderRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetProviderRequest) Reset() { @@ -5955,11 +5928,11 @@ func (x *GetProviderRequest) GetName() string { return "" } -func (x *GetProviderRequest) GetWorkspace() string { +func (x *GetProviderRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // List providers request. @@ -5967,12 +5940,10 @@ type ListProvidersRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Limit uint32 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"` Offset uint32 `protobuf:"varint,2,opt,name=offset,proto3" json:"offset,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` - // List across all workspaces. Mutually exclusive with workspace. - AllWorkspaces bool `protobuf:"varint,4,opt,name=all_workspaces,json=allWorkspaces,proto3" json:"all_workspaces,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit named or all-workspaces scope. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ListProvidersRequest) Reset() { @@ -6019,18 +5990,11 @@ func (x *ListProvidersRequest) GetOffset() uint32 { return 0 } -func (x *ListProvidersRequest) GetWorkspace() string { - if x != nil { - return x.Workspace - } - return "" -} - -func (x *ListProvidersRequest) GetAllWorkspaces() bool { +func (x *ListProvidersRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.AllWorkspaces + return x.WorkspaceScope } - return false + return nil } // Update provider request. @@ -6040,10 +6004,10 @@ type UpdateProviderRequest struct { // Optional per-credential expiry timestamps to merge into the provider. // A zero value removes the expiry for that credential. CredentialExpiresAtMs map[string]int64 `protobuf:"bytes,2,rep,name=credential_expires_at_ms,json=credentialExpiresAtMs,proto3" json:"credential_expires_at_ms,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *UpdateProviderRequest) Reset() { @@ -6090,21 +6054,21 @@ func (x *UpdateProviderRequest) GetCredentialExpiresAtMs() map[string]int64 { return nil } -func (x *UpdateProviderRequest) GetWorkspace() string { +func (x *UpdateProviderRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Delete provider request. type DeleteProviderRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *DeleteProviderRequest) Reset() { @@ -6144,11 +6108,11 @@ func (x *DeleteProviderRequest) GetName() string { return "" } -func (x *DeleteProviderRequest) GetWorkspace() string { +func (x *DeleteProviderRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Provider response. @@ -7301,10 +7265,10 @@ type GetProviderRefreshStatusRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Provider string `protobuf:"bytes,1,opt,name=provider,proto3" json:"provider,omitempty"` CredentialKey string `protobuf:"bytes,2,opt,name=credential_key,json=credentialKey,proto3" json:"credential_key,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetProviderRefreshStatusRequest) Reset() { @@ -7351,11 +7315,11 @@ func (x *GetProviderRefreshStatusRequest) GetCredentialKey() string { return "" } -func (x *GetProviderRefreshStatusRequest) GetWorkspace() string { +func (x *GetProviderRefreshStatusRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type GetProviderRefreshStatusResponse struct { @@ -7413,10 +7377,10 @@ type ConfigureProviderRefreshRequest struct { // the authoritative provider profile and refresh strategy. SecretMaterialKeys []string `protobuf:"bytes,5,rep,name=secret_material_keys,json=secretMaterialKeys,proto3" json:"secret_material_keys,omitempty"` ExpiresAtMs *int64 `protobuf:"varint,6,opt,name=expires_at_ms,json=expiresAtMs,proto3,oneof" json:"expires_at_ms,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,7,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,8,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ConfigureProviderRefreshRequest) Reset() { @@ -7491,11 +7455,11 @@ func (x *ConfigureProviderRefreshRequest) GetExpiresAtMs() int64 { return 0 } -func (x *ConfigureProviderRefreshRequest) GetWorkspace() string { +func (x *ConfigureProviderRefreshRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type ConfigureProviderRefreshResponse struct { @@ -7546,10 +7510,10 @@ type RotateProviderCredentialRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Provider string `protobuf:"bytes,1,opt,name=provider,proto3" json:"provider,omitempty"` CredentialKey string `protobuf:"bytes,2,opt,name=credential_key,json=credentialKey,proto3" json:"credential_key,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *RotateProviderCredentialRequest) Reset() { @@ -7596,11 +7560,11 @@ func (x *RotateProviderCredentialRequest) GetCredentialKey() string { return "" } -func (x *RotateProviderCredentialRequest) GetWorkspace() string { +func (x *RotateProviderCredentialRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type RotateProviderCredentialResponse struct { @@ -7651,10 +7615,10 @@ type DeleteProviderRefreshRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Provider string `protobuf:"bytes,1,opt,name=provider,proto3" json:"provider,omitempty"` CredentialKey string `protobuf:"bytes,2,opt,name=credential_key,json=credentialKey,proto3" json:"credential_key,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *DeleteProviderRefreshRequest) Reset() { @@ -7701,11 +7665,11 @@ func (x *DeleteProviderRefreshRequest) GetCredentialKey() string { return "" } -func (x *DeleteProviderRefreshRequest) GetWorkspace() string { +func (x *DeleteProviderRefreshRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type DeleteProviderRefreshResponse struct { @@ -8953,10 +8917,11 @@ type UpdateConfigRequest struct { // sandbox metadata as a convenience projection. For setting-only updates, it // only merges them into sandbox metadata. Annotations map[string]string `protobuf:"bytes,9,rep,name=annotations,proto3" json:"annotations,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - // Workspace scope. Empty defaults to "default". Ignored for global-scoped updates. - Workspace string `protobuf:"bytes,10,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope for sandbox-scoped updates. Omit only when + // `global` is true; the all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,11,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *UpdateConfigRequest) Reset() { @@ -9052,11 +9017,11 @@ func (x *UpdateConfigRequest) GetAnnotations() map[string]string { return nil } -func (x *UpdateConfigRequest) GetWorkspace() string { +func (x *UpdateConfigRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type PolicyMergeOperation struct { @@ -9624,10 +9589,11 @@ type GetSandboxPolicyStatusRequest struct { Version uint32 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` // Query global policy revisions instead of a sandbox-scoped one. Global bool `protobuf:"varint,3,opt,name=global,proto3" json:"global,omitempty"` - // Workspace scope. Empty defaults to "default". Ignored when global is true. - Workspace string `protobuf:"bytes,4,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope for sandbox-scoped queries. Omit only when + // `global` is true; the all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetSandboxPolicyStatusRequest) Reset() { @@ -9681,11 +9647,11 @@ func (x *GetSandboxPolicyStatusRequest) GetGlobal() bool { return false } -func (x *GetSandboxPolicyStatusRequest) GetWorkspace() string { +func (x *GetSandboxPolicyStatusRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Get sandbox policy status response. @@ -9752,10 +9718,11 @@ type ListSandboxPoliciesRequest struct { Offset uint32 `protobuf:"varint,3,opt,name=offset,proto3" json:"offset,omitempty"` // List global policy revisions instead of sandbox-scoped ones. Global bool `protobuf:"varint,4,opt,name=global,proto3" json:"global,omitempty"` - // Workspace scope. Empty defaults to "default". Ignored when global is true. - Workspace string `protobuf:"bytes,5,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope for sandbox-scoped queries. Omit only when + // `global` is true; the all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,6,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ListSandboxPoliciesRequest) Reset() { @@ -9816,11 +9783,11 @@ func (x *ListSandboxPoliciesRequest) GetGlobal() bool { return false } -func (x *ListSandboxPoliciesRequest) GetWorkspace() string { +func (x *ListSandboxPoliciesRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // List sandbox policies response. @@ -10107,10 +10074,10 @@ type GetSandboxLogsRequest struct { Sources []string `protobuf:"bytes,4,rep,name=sources,proto3" json:"sources,omitempty"` // Minimum log level to include (e.g. "INFO", "WARN", "ERROR"). Empty means all levels. MinLevel string `protobuf:"bytes,5,opt,name=min_level,json=minLevel,proto3" json:"min_level,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,6,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,7,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetSandboxLogsRequest) Reset() { @@ -10178,11 +10145,11 @@ func (x *GetSandboxLogsRequest) GetMinLevel() string { return "" } -func (x *GetSandboxLogsRequest) GetWorkspace() string { +func (x *GetSandboxLogsRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } // Batch of log lines pushed from sandbox to server. @@ -12343,10 +12310,10 @@ type GetDraftPolicyRequest struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Optional status filter: "pending", "approved", "rejected", or "" for all. StatusFilter string `protobuf:"bytes,2,opt,name=status_filter,json=statusFilter,proto3" json:"status_filter,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetDraftPolicyRequest) Reset() { @@ -12393,11 +12360,11 @@ func (x *GetDraftPolicyRequest) GetStatusFilter() string { return "" } -func (x *GetDraftPolicyRequest) GetWorkspace() string { +func (x *GetDraftPolicyRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type GetDraftPolicyResponse struct { @@ -12479,13 +12446,13 @@ type ApproveDraftChunkRequest struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Chunk ID to approve. ChunkId string `protobuf:"bytes,2,opt,name=chunk_id,json=chunkId,proto3" json:"chunk_id,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` // Token returned with the reviewed PolicyChunk. Approval fails with // FAILED_PRECONDITION if live decision inputs no longer match it. - ReviewToken string `protobuf:"bytes,4,opt,name=review_token,json=reviewToken,proto3" json:"review_token,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + ReviewToken string `protobuf:"bytes,4,opt,name=review_token,json=reviewToken,proto3" json:"review_token,omitempty"` + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ApproveDraftChunkRequest) Reset() { @@ -12532,18 +12499,18 @@ func (x *ApproveDraftChunkRequest) GetChunkId() string { return "" } -func (x *ApproveDraftChunkRequest) GetWorkspace() string { +func (x *ApproveDraftChunkRequest) GetReviewToken() string { if x != nil { - return x.Workspace + return x.ReviewToken } return "" } -func (x *ApproveDraftChunkRequest) GetReviewToken() string { +func (x *ApproveDraftChunkRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.ReviewToken + return x.WorkspaceScope } - return "" + return nil } type ApproveDraftChunkResponse struct { @@ -12609,10 +12576,10 @@ type RejectDraftChunkRequest struct { ChunkId string `protobuf:"bytes,2,opt,name=chunk_id,json=chunkId,proto3" json:"chunk_id,omitempty"` // Optional reason for rejection (fed to LLM context in future analysis). Reason string `protobuf:"bytes,3,opt,name=reason,proto3" json:"reason,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,4,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *RejectDraftChunkRequest) Reset() { @@ -12666,11 +12633,11 @@ func (x *RejectDraftChunkRequest) GetReason() string { return "" } -func (x *RejectDraftChunkRequest) GetWorkspace() string { +func (x *RejectDraftChunkRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type RejectDraftChunkResponse struct { @@ -12768,13 +12735,13 @@ type ApproveAllDraftChunksRequest struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Include chunks with security_notes (default false: skips them). IncludeSecurityFlagged bool `protobuf:"varint,2,opt,name=include_security_flagged,json=includeSecurityFlagged,proto3" json:"include_security_flagged,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` // Exact reviewed chunks and tokens. The server validates them against one // live snapshot, stages compatible operations in order, and writes once. - Approvals []*DraftChunkApproval `protobuf:"bytes,4,rep,name=approvals,proto3" json:"approvals,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + Approvals []*DraftChunkApproval `protobuf:"bytes,4,rep,name=approvals,proto3" json:"approvals,omitempty"` + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ApproveAllDraftChunksRequest) Reset() { @@ -12821,16 +12788,16 @@ func (x *ApproveAllDraftChunksRequest) GetIncludeSecurityFlagged() bool { return false } -func (x *ApproveAllDraftChunksRequest) GetWorkspace() string { +func (x *ApproveAllDraftChunksRequest) GetApprovals() []*DraftChunkApproval { if x != nil { - return x.Workspace + return x.Approvals } - return "" + return nil } -func (x *ApproveAllDraftChunksRequest) GetApprovals() []*DraftChunkApproval { +func (x *ApproveAllDraftChunksRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Approvals + return x.WorkspaceScope } return nil } @@ -12917,10 +12884,10 @@ type EditDraftChunkRequest struct { ChunkId string `protobuf:"bytes,2,opt,name=chunk_id,json=chunkId,proto3" json:"chunk_id,omitempty"` // The modified rule (replaces existing proposed_rule). ProposedRule *sandboxv1.NetworkPolicyRule `protobuf:"bytes,3,opt,name=proposed_rule,json=proposedRule,proto3" json:"proposed_rule,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,4,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *EditDraftChunkRequest) Reset() { @@ -12974,11 +12941,11 @@ func (x *EditDraftChunkRequest) GetProposedRule() *sandboxv1.NetworkPolicyRule { return nil } -func (x *EditDraftChunkRequest) GetWorkspace() string { +func (x *EditDraftChunkRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type EditDraftChunkResponse struct { @@ -13024,10 +12991,10 @@ type UndoDraftChunkRequest struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Chunk ID to undo. ChunkId string `protobuf:"bytes,2,opt,name=chunk_id,json=chunkId,proto3" json:"chunk_id,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *UndoDraftChunkRequest) Reset() { @@ -13074,11 +13041,11 @@ func (x *UndoDraftChunkRequest) GetChunkId() string { return "" } -func (x *UndoDraftChunkRequest) GetWorkspace() string { +func (x *UndoDraftChunkRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type UndoDraftChunkResponse struct { @@ -13140,10 +13107,10 @@ type ClearDraftChunksRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Sandbox name. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ClearDraftChunksRequest) Reset() { @@ -13183,11 +13150,11 @@ func (x *ClearDraftChunksRequest) GetName() string { return "" } -func (x *ClearDraftChunksRequest) GetWorkspace() string { +func (x *ClearDraftChunksRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type ClearDraftChunksResponse struct { @@ -13240,10 +13207,10 @@ type GetDraftHistoryRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Sandbox name. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Workspace scope. Empty defaults to "default". - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Explicit workspace scope. The all-workspaces selection is invalid. + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetDraftHistoryRequest) Reset() { @@ -13283,11 +13250,11 @@ func (x *GetDraftHistoryRequest) GetName() string { return "" } -func (x *GetDraftHistoryRequest) GetWorkspace() string { +func (x *GetDraftHistoryRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { if x != nil { - return x.Workspace + return x.WorkspaceScope } - return "" + return nil } type DraftHistoryEntry struct { @@ -14395,84 +14362,82 @@ const file_openshell_proto_rawDesc = "" + "\bmetadata\x18\x06 \x03(\v2).openshell.v1.PlatformEvent.MetadataEntryR\bmetadata\x1a;\n" + "\rMetadataEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x8a\x04\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xd1\x04\n" + "\x14CreateSandboxRequest\x12-\n" + "\x04spec\x18\x01 \x01(\v2\x19.openshell.v1.SandboxSpecR\x04spec\x12\x12\n" + "\x04name\x18\x02 \x01(\tR\x04name\x12F\n" + "\x06labels\x18\x03 \x03(\v2..openshell.v1.CreateSandboxRequest.LabelsEntryR\x06labels\x12U\n" + - "\vannotations\x18\x04 \x03(\v23.openshell.v1.CreateSandboxRequest.AnnotationsEntryR\vannotations\x12\x1c\n" + - "\tworkspace\x18\x05 \x01(\tR\tworkspace\x12A\n" + + "\vannotations\x18\x04 \x03(\v23.openshell.v1.CreateSandboxRequest.AnnotationsEntryR\vannotations\x12A\n" + "\x1dawait_main_process_attachment\x18\x06 \x01(\bR\x1aawaitMainProcessAttachment\x124\n" + - "\x16workload_template_name\x18\a \x01(\tR\x14workloadTemplateName\x1a9\n" + + "\x16workload_template_name\x18\a \x01(\tR\x14workloadTemplateName\x12R\n" + + "\x0fworkspace_scope\x18\b \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x1a9\n" + "\vLabelsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1a>\n" + "\x10AnnotationsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x7f\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01J\x04\b\x05\x10\x06R\tworkspace\"\xc6\x01\n" + "\x1cCreateSandboxTemplateRequest\x12A\n" + - "\btemplate\x18\x01 \x01(\v2%.openshell.v1.SandboxWorkloadTemplateR\btemplate\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"M\n" + + "\btemplate\x18\x01 \x01(\v2%.openshell.v1.SandboxWorkloadTemplateR\btemplate\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\x94\x01\n" + "\x19GetSandboxTemplateRequest\x12\x12\n" + - "\x04name\x18\x01 \x01(\tR\x04name\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"\xb7\x01\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\xed\x01\n" + "\x1bListSandboxTemplatesRequest\x12\x14\n" + "\x05limit\x18\x01 \x01(\rR\x05limit\x12\x16\n" + - "\x06offset\x18\x02 \x01(\rR\x06offset\x12\x1c\n" + - "\tworkspace\x18\x03 \x01(\tR\tworkspace\x12%\n" + - "\x0eall_workspaces\x18\x04 \x01(\bR\rallWorkspaces\x12%\n" + - "\x0elabel_selector\x18\x05 \x01(\tR\rlabelSelector\"P\n" + + "\x06offset\x18\x02 \x01(\rR\x06offset\x12%\n" + + "\x0elabel_selector\x18\x05 \x01(\tR\rlabelSelector\x12R\n" + + "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\tworkspaceR\x0eall_workspaces\"\x97\x01\n" + "\x1cDeleteSandboxTemplateRequest\x12\x12\n" + - "\x04name\x18\x01 \x01(\tR\x04name\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"\\\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\\\n" + "\x17SandboxTemplateResponse\x12A\n" + "\btemplate\x18\x01 \x01(\v2%.openshell.v1.SandboxWorkloadTemplateR\btemplate\"c\n" + "\x1cListSandboxTemplatesResponse\x12C\n" + "\ttemplates\x18\x01 \x03(\v2%.openshell.v1.SandboxWorkloadTemplateR\ttemplates\"9\n" + "\x1dDeleteSandboxTemplateResponse\x12\x18\n" + - "\adeleted\x18\x01 \x01(\bR\adeleted\"x\n" + - "\x1cBeginRootfsTarStagingRequest\x12\x1c\n" + - "\tworkspace\x18\x01 \x01(\tR\tworkspace\x12\x1b\n" + + "\adeleted\x18\x01 \x01(\bR\adeleted\"\xbf\x01\n" + + "\x1cBeginRootfsTarStagingRequest\x12\x1b\n" + "\tfile_name\x18\x02 \x01(\tR\bfileName\x12\x1d\n" + "\n" + - "size_bytes\x18\x03 \x01(\x04R\tsizeBytes\"\xa6\x01\n" + + "size_bytes\x18\x03 \x01(\x04R\tsizeBytes\x12R\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x01\x10\x02R\tworkspace\"\xa6\x01\n" + "\x1dBeginRootfsTarStagingResponse\x12#\n" + "\rstaging_token\x18\x01 \x01(\tR\fstagingToken\x12\x1f\n" + "\vupload_path\x18\x02 \x01(\tR\n" + "uploadPath\x12\x1b\n" + "\tmax_bytes\x18\x03 \x01(\x04R\bmaxBytes\x12\"\n" + - "\rexpires_at_ms\x18\x04 \x01(\x03R\vexpiresAtMs\"E\n" + + "\rexpires_at_ms\x18\x04 \x01(\x03R\vexpiresAtMs\"\x8c\x01\n" + "\x11GetSandboxRequest\x12\x12\n" + - "\x04name\x18\x01 \x01(\tR\x04name\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"\xb0\x01\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\xe6\x01\n" + "\x14ListSandboxesRequest\x12\x14\n" + "\x05limit\x18\x01 \x01(\rR\x05limit\x12\x16\n" + "\x06offset\x18\x02 \x01(\rR\x06offset\x12%\n" + - "\x0elabel_selector\x18\x03 \x01(\tR\rlabelSelector\x12\x1c\n" + - "\tworkspace\x18\x04 \x01(\tR\tworkspace\x12%\n" + - "\x0eall_workspaces\x18\x05 \x01(\bR\rallWorkspaces\"^\n" + + "\x0elabel_selector\x18\x03 \x01(\tR\rlabelSelector\x12R\n" + + "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05J\x04\b\x05\x10\x06R\tworkspaceR\x0eall_workspaces\"\xa5\x01\n" + "\x1bListSandboxProvidersRequest\x12!\n" + - "\fsandbox_name\x18\x01 \x01(\tR\vsandboxName\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"\xc0\x01\n" + + "\fsandbox_name\x18\x01 \x01(\tR\vsandboxName\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\x87\x02\n" + "\x1cAttachSandboxProviderRequest\x12!\n" + "\fsandbox_name\x18\x01 \x01(\tR\vsandboxName\x12#\n" + "\rprovider_name\x18\x02 \x01(\tR\fproviderName\x12:\n" + - "\x19expected_resource_version\x18\x03 \x01(\x04R\x17expectedResourceVersion\x12\x1c\n" + - "\tworkspace\x18\x04 \x01(\tR\tworkspace\"\xc0\x01\n" + + "\x19expected_resource_version\x18\x03 \x01(\x04R\x17expectedResourceVersion\x12R\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05R\tworkspace\"\x87\x02\n" + "\x1cDetachSandboxProviderRequest\x12!\n" + "\fsandbox_name\x18\x01 \x01(\tR\vsandboxName\x12#\n" + "\rprovider_name\x18\x02 \x01(\tR\fproviderName\x12:\n" + - "\x19expected_resource_version\x18\x03 \x01(\x04R\x17expectedResourceVersion\x12\x1c\n" + - "\tworkspace\x18\x04 \x01(\tR\tworkspace\"H\n" + + "\x19expected_resource_version\x18\x03 \x01(\x04R\x17expectedResourceVersion\x12R\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05R\tworkspace\"\x8f\x01\n" + "\x14DeleteSandboxRequest\x12\x12\n" + - "\x04name\x18\x01 \x01(\tR\x04name\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"F\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\x8d\x01\n" + "\x12StopSandboxRequest\x12\x12\n" + - "\x04name\x18\x01 \x01(\tR\x04name\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"G\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\x8e\x01\n" + "\x13StartSandboxRequest\x12\x12\n" + - "\x04name\x18\x01 \x01(\tR\x04name\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"B\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"B\n" + "\x0fSandboxResponse\x12/\n" + "\asandbox\x18\x01 \x01(\v2\x15.openshell.v1.SandboxR\asandbox\"L\n" + "\x15ListSandboxesResponse\x123\n" + @@ -14498,30 +14463,29 @@ const file_openshell_proto_rawDesc = "" + "\fgateway_port\x18\x04 \x01(\rR\vgatewayPort\x12%\n" + "\x0egateway_scheme\x18\x05 \x01(\tR\rgatewayScheme\x120\n" + "\x14host_key_fingerprint\x18\a \x01(\tR\x12hostKeyFingerprint\x12\"\n" + - "\rexpires_at_ms\x18\b \x01(\x03R\vexpiresAtMs\"\xa1\x01\n" + + "\rexpires_at_ms\x18\b \x01(\x03R\vexpiresAtMs\"\xe8\x01\n" + "\x14ExposeServiceRequest\x12\x18\n" + "\asandbox\x18\x01 \x01(\tR\asandbox\x12\x18\n" + "\aservice\x18\x02 \x01(\tR\aservice\x12\x1f\n" + "\vtarget_port\x18\x03 \x01(\rR\n" + "targetPort\x12\x16\n" + - "\x06domain\x18\x04 \x01(\bR\x06domain\x12\x1c\n" + - "\tworkspace\x18\x05 \x01(\tR\tworkspace\"e\n" + + "\x06domain\x18\x04 \x01(\bR\x06domain\x12R\n" + + "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x05\x10\x06R\tworkspace\"\xac\x01\n" + "\x11GetServiceRequest\x12\x18\n" + "\asandbox\x18\x01 \x01(\tR\asandbox\x12\x18\n" + - "\aservice\x18\x02 \x01(\tR\aservice\x12\x1c\n" + - "\tworkspace\x18\x03 \x01(\tR\tworkspace\"\xa2\x01\n" + + "\aservice\x18\x02 \x01(\tR\aservice\x12R\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"\xd8\x01\n" + "\x13ListServicesRequest\x12\x18\n" + "\asandbox\x18\x01 \x01(\tR\asandbox\x12\x14\n" + "\x05limit\x18\x02 \x01(\rR\x05limit\x12\x16\n" + - "\x06offset\x18\x03 \x01(\rR\x06offset\x12\x1c\n" + - "\tworkspace\x18\x04 \x01(\tR\tworkspace\x12%\n" + - "\x0eall_workspaces\x18\x05 \x01(\bR\rallWorkspaces\"Y\n" + + "\x06offset\x18\x03 \x01(\rR\x06offset\x12R\n" + + "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05J\x04\b\x05\x10\x06R\tworkspaceR\x0eall_workspaces\"Y\n" + "\x14ListServicesResponse\x12A\n" + - "\bservices\x18\x01 \x03(\v2%.openshell.v1.ServiceEndpointResponseR\bservices\"h\n" + + "\bservices\x18\x01 \x03(\v2%.openshell.v1.ServiceEndpointResponseR\bservices\"\xaf\x01\n" + "\x14DeleteServiceRequest\x12\x18\n" + "\asandbox\x18\x01 \x01(\tR\asandbox\x12\x18\n" + - "\aservice\x18\x02 \x01(\tR\aservice\x12\x1c\n" + - "\tworkspace\x18\x03 \x01(\tR\tworkspace\"1\n" + + "\aservice\x18\x02 \x01(\tR\aservice\x12R\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"1\n" + "\x15DeleteServiceResponse\x12\x18\n" + "\adeleted\x18\x01 \x01(\bR\adeleted\"\xef\x01\n" + "\x0fServiceEndpoint\x12>\n" + @@ -14632,28 +14596,27 @@ const file_openshell_proto_rawDesc = "" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"0\n" + "\x14SandboxStreamWarning\x12\x18\n" + - "\amessage\x18\x01 \x01(\tR\amessage\"s\n" + + "\amessage\x18\x01 \x01(\tR\amessage\"\xba\x01\n" + "\x15CreateProviderRequest\x12<\n" + - "\bprovider\x18\x01 \x01(\v2 .openshell.datamodel.v1.ProviderR\bprovider\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"F\n" + + "\bprovider\x18\x01 \x01(\v2 .openshell.datamodel.v1.ProviderR\bprovider\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\x8d\x01\n" + "\x12GetProviderRequest\x12\x12\n" + - "\x04name\x18\x01 \x01(\tR\x04name\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"\x89\x01\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\xbf\x01\n" + "\x14ListProvidersRequest\x12\x14\n" + "\x05limit\x18\x01 \x01(\rR\x05limit\x12\x16\n" + - "\x06offset\x18\x02 \x01(\rR\x06offset\x12\x1c\n" + - "\tworkspace\x18\x03 \x01(\tR\tworkspace\x12%\n" + - "\x0eall_workspaces\x18\x04 \x01(\bR\rallWorkspaces\"\xb6\x02\n" + + "\x06offset\x18\x02 \x01(\rR\x06offset\x12R\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\tworkspaceR\x0eall_workspaces\"\xfd\x02\n" + "\x15UpdateProviderRequest\x12<\n" + "\bprovider\x18\x01 \x01(\v2 .openshell.datamodel.v1.ProviderR\bprovider\x12w\n" + - "\x18credential_expires_at_ms\x18\x02 \x03(\v2>.openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntryR\x15credentialExpiresAtMs\x12\x1c\n" + - "\tworkspace\x18\x03 \x01(\tR\tworkspace\x1aH\n" + + "\x18credential_expires_at_ms\x18\x02 \x03(\v2>.openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntryR\x15credentialExpiresAtMs\x12R\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x1aH\n" + "\x1aCredentialExpiresAtMsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\x03R\x05value:\x028\x01\"I\n" + + "\x05value\x18\x02 \x01(\x03R\x05value:\x028\x01J\x04\b\x03\x10\x04R\tworkspace\"\x90\x01\n" + "\x15DeleteProviderRequest\x12\x12\n" + - "\x04name\x18\x01 \x01(\tR\x04name\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"P\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"P\n" + "\x10ProviderResponse\x12<\n" + "\bprovider\x18\x01 \x01(\v2 .openshell.datamodel.v1.ProviderR\bprovider\"W\n" + "\x15ListProvidersResponse\x12>\n" + @@ -14752,37 +14715,37 @@ const file_openshell_proto_rawDesc = "" + "\x16provider_error_subtype\x18\f \x01(\tR\x14providerErrorSubtype\x12'\n" + "\x10last_error_at_ms\x18\r \x01(\x03R\rlastErrorAtMs\"<\n" + "\x18ProviderProfileDiscovery\x12 \n" + - "\vcredentials\x18\x01 \x03(\tR\vcredentials\"\x82\x01\n" + + "\vcredentials\x18\x01 \x03(\tR\vcredentials\"\xc9\x01\n" + "\x1fGetProviderRefreshStatusRequest\x12\x1a\n" + "\bprovider\x18\x01 \x01(\tR\bprovider\x12%\n" + - "\x0ecredential_key\x18\x02 \x01(\tR\rcredentialKey\x12\x1c\n" + - "\tworkspace\x18\x03 \x01(\tR\tworkspace\"s\n" + + "\x0ecredential_key\x18\x02 \x01(\tR\rcredentialKey\x12R\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"s\n" + " GetProviderRefreshStatusResponse\x12O\n" + - "\vcredentials\x18\x01 \x03(\v2-.openshell.v1.ProviderCredentialRefreshStatusR\vcredentials\"\xd8\x03\n" + + "\vcredentials\x18\x01 \x03(\v2-.openshell.v1.ProviderCredentialRefreshStatusR\vcredentials\"\x9f\x04\n" + "\x1fConfigureProviderRefreshRequest\x12\x1a\n" + "\bprovider\x18\x01 \x01(\tR\bprovider\x12%\n" + "\x0ecredential_key\x18\x02 \x01(\tR\rcredentialKey\x12K\n" + "\bstrategy\x18\x03 \x01(\x0e2/.openshell.v1.ProviderCredentialRefreshStrategyR\bstrategy\x12]\n" + "\bmaterial\x18\x04 \x03(\v2;.openshell.v1.ConfigureProviderRefreshRequest.MaterialEntryB\x04\x88\xb5\x18\x01R\bmaterial\x120\n" + "\x14secret_material_keys\x18\x05 \x03(\tR\x12secretMaterialKeys\x12'\n" + - "\rexpires_at_ms\x18\x06 \x01(\x03H\x00R\vexpiresAtMs\x88\x01\x01\x12\x1c\n" + - "\tworkspace\x18\a \x01(\tR\tworkspace\x1a;\n" + + "\rexpires_at_ms\x18\x06 \x01(\x03H\x00R\vexpiresAtMs\x88\x01\x01\x12R\n" + + "\x0fworkspace_scope\x18\b \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x1a;\n" + "\rMaterialEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01B\x10\n" + - "\x0e_expires_at_ms\"i\n" + + "\x0e_expires_at_msJ\x04\b\a\x10\bR\tworkspace\"i\n" + " ConfigureProviderRefreshResponse\x12E\n" + - "\x06status\x18\x01 \x01(\v2-.openshell.v1.ProviderCredentialRefreshStatusR\x06status\"\x82\x01\n" + + "\x06status\x18\x01 \x01(\v2-.openshell.v1.ProviderCredentialRefreshStatusR\x06status\"\xc9\x01\n" + "\x1fRotateProviderCredentialRequest\x12\x1a\n" + "\bprovider\x18\x01 \x01(\tR\bprovider\x12%\n" + - "\x0ecredential_key\x18\x02 \x01(\tR\rcredentialKey\x12\x1c\n" + - "\tworkspace\x18\x03 \x01(\tR\tworkspace\"i\n" + + "\x0ecredential_key\x18\x02 \x01(\tR\rcredentialKey\x12R\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"i\n" + " RotateProviderCredentialResponse\x12E\n" + - "\x06status\x18\x01 \x01(\v2-.openshell.v1.ProviderCredentialRefreshStatusR\x06status\"\x7f\n" + + "\x06status\x18\x01 \x01(\v2-.openshell.v1.ProviderCredentialRefreshStatusR\x06status\"\xc6\x01\n" + "\x1cDeleteProviderRefreshRequest\x12\x1a\n" + "\bprovider\x18\x01 \x01(\tR\bprovider\x12%\n" + - "\x0ecredential_key\x18\x02 \x01(\tR\rcredentialKey\x12\x1c\n" + - "\tworkspace\x18\x03 \x01(\tR\tworkspace\"9\n" + + "\x0ecredential_key\x18\x02 \x01(\tR\rcredentialKey\x12R\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"9\n" + "\x1dDeleteProviderRefreshResponse\x12\x18\n" + "\adeleted\x18\x01 \x01(\bR\adeleted\"\xd8\x05\n" + "\x0fProviderProfile\x12\x0e\n" + @@ -14878,7 +14841,7 @@ const file_openshell_proto_rawDesc = "" + "\n" + "expires_in\x18\x02 \x01(\x03R\texpiresIn\x12\x1d\n" + "\n" + - "token_type\x18\x03 \x01(\tR\ttokenType\"\xce\x04\n" + + "token_type\x18\x03 \x01(\tR\ttokenType\"\x95\x05\n" + "\x13UpdateConfigRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12;\n" + "\x06policy\x18\x02 \x01(\v2#.openshell.sandbox.v1.SandboxPolicyR\x06policy\x12\x1f\n" + @@ -14889,12 +14852,12 @@ const file_openshell_proto_rawDesc = "" + "\x06global\x18\x06 \x01(\bR\x06global\x12M\n" + "\x10merge_operations\x18\a \x03(\v2\".openshell.v1.PolicyMergeOperationR\x0fmergeOperations\x12:\n" + "\x19expected_resource_version\x18\b \x01(\x04R\x17expectedResourceVersion\x12T\n" + - "\vannotations\x18\t \x03(\v22.openshell.v1.UpdateConfigRequest.AnnotationsEntryR\vannotations\x12\x1c\n" + - "\tworkspace\x18\n" + - " \x01(\tR\tworkspace\x1a>\n" + + "\vannotations\x18\t \x03(\v22.openshell.v1.UpdateConfigRequest.AnnotationsEntryR\vannotations\x12R\n" + + "\x0fworkspace_scope\x18\v \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x1a>\n" + "\x10AnnotationsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xc7\x03\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01J\x04\b\n" + + "\x10\vR\tworkspace\"\xc7\x03\n" + "\x14PolicyMergeOperation\x129\n" + "\badd_rule\x18\x01 \x01(\v2\x1c.openshell.v1.AddNetworkRuleH\x00R\aaddRule\x12N\n" + "\x0fremove_endpoint\x18\x02 \x01(\v2#.openshell.v1.RemoveNetworkEndpointH\x00R\x0eremoveEndpoint\x12B\n" + @@ -14935,21 +14898,21 @@ const file_openshell_proto_rawDesc = "" + "\vannotations\x18\x05 \x03(\v23.openshell.v1.UpdateConfigResponse.AnnotationsEntryR\vannotations\x1a>\n" + "\x10AnnotationsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x83\x01\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xca\x01\n" + "\x1dGetSandboxPolicyStatusRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x18\n" + "\aversion\x18\x02 \x01(\rR\aversion\x12\x16\n" + - "\x06global\x18\x03 \x01(\bR\x06global\x12\x1c\n" + - "\tworkspace\x18\x04 \x01(\tR\tworkspace\"\x88\x01\n" + + "\x06global\x18\x03 \x01(\bR\x06global\x12R\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05R\tworkspace\"\x88\x01\n" + "\x1eGetSandboxPolicyStatusResponse\x12?\n" + "\brevision\x18\x01 \x01(\v2#.openshell.v1.SandboxPolicyRevisionR\brevision\x12%\n" + - "\x0eactive_version\x18\x02 \x01(\rR\ractiveVersion\"\x94\x01\n" + + "\x0eactive_version\x18\x02 \x01(\rR\ractiveVersion\"\xdb\x01\n" + "\x1aListSandboxPoliciesRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" + "\x05limit\x18\x02 \x01(\rR\x05limit\x12\x16\n" + "\x06offset\x18\x03 \x01(\rR\x06offset\x12\x16\n" + - "\x06global\x18\x04 \x01(\bR\x06global\x12\x1c\n" + - "\tworkspace\x18\x05 \x01(\tR\tworkspace\"`\n" + + "\x06global\x18\x04 \x01(\bR\x06global\x12R\n" + + "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x05\x10\x06R\tworkspace\"`\n" + "\x1bListSandboxPoliciesResponse\x12A\n" + "\trevisions\x18\x01 \x03(\v2#.openshell.v1.SandboxPolicyRevisionR\trevisions\"\xa7\x01\n" + "\x19ReportPolicyStatusRequest\x12\x1d\n" + @@ -14976,15 +14939,15 @@ const file_openshell_proto_rawDesc = "" + "provenance\x1a=\n" + "\x0fProvenanceEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xbc\x01\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x83\x02\n" + "\x15GetSandboxLogsRequest\x12\x1d\n" + "\n" + "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x14\n" + "\x05lines\x18\x02 \x01(\rR\x05lines\x12\x19\n" + "\bsince_ms\x18\x03 \x01(\x03R\asinceMs\x12\x18\n" + "\asources\x18\x04 \x03(\tR\asources\x12\x1b\n" + - "\tmin_level\x18\x05 \x01(\tR\bminLevel\x12\x1c\n" + - "\tworkspace\x18\x06 \x01(\tR\tworkspace\"i\n" + + "\tmin_level\x18\x05 \x01(\tR\bminLevel\x12R\n" + + "\x0fworkspace_scope\x18\a \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x06\x10\aR\tworkspace\"i\n" + "\x16PushSandboxLogsRequest\x12\x1d\n" + "\n" + "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x120\n" + @@ -15149,67 +15112,67 @@ const file_openshell_proto_rawDesc = "" + "\x0faccepted_chunks\x18\x01 \x01(\rR\x0eacceptedChunks\x12'\n" + "\x0frejected_chunks\x18\x02 \x01(\rR\x0erejectedChunks\x12+\n" + "\x11rejection_reasons\x18\x03 \x03(\tR\x10rejectionReasons\x12,\n" + - "\x12accepted_chunk_ids\x18\x04 \x03(\tR\x10acceptedChunkIds\"n\n" + + "\x12accepted_chunk_ids\x18\x04 \x03(\tR\x10acceptedChunkIds\"\xb5\x01\n" + "\x15GetDraftPolicyRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12#\n" + - "\rstatus_filter\x18\x02 \x01(\tR\fstatusFilter\x12\x1c\n" + - "\tworkspace\x18\x03 \x01(\tR\tworkspace\"\xc8\x01\n" + + "\rstatus_filter\x18\x02 \x01(\tR\fstatusFilter\x12R\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"\xc8\x01\n" + "\x16GetDraftPolicyResponse\x121\n" + "\x06chunks\x18\x01 \x03(\v2\x19.openshell.v1.PolicyChunkR\x06chunks\x12'\n" + "\x0frolling_summary\x18\x02 \x01(\tR\x0erollingSummary\x12#\n" + "\rdraft_version\x18\x03 \x01(\x04R\fdraftVersion\x12-\n" + - "\x13last_analyzed_at_ms\x18\x04 \x01(\x03R\x10lastAnalyzedAtMs\"\x8a\x01\n" + + "\x13last_analyzed_at_ms\x18\x04 \x01(\x03R\x10lastAnalyzedAtMs\"\xd1\x01\n" + "\x18ApproveDraftChunkRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x19\n" + - "\bchunk_id\x18\x02 \x01(\tR\achunkId\x12\x1c\n" + - "\tworkspace\x18\x03 \x01(\tR\tworkspace\x12!\n" + - "\freview_token\x18\x04 \x01(\tR\vreviewToken\"c\n" + + "\bchunk_id\x18\x02 \x01(\tR\achunkId\x12!\n" + + "\freview_token\x18\x04 \x01(\tR\vreviewToken\x12R\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"c\n" + "\x19ApproveDraftChunkResponse\x12%\n" + "\x0epolicy_version\x18\x01 \x01(\rR\rpolicyVersion\x12\x1f\n" + "\vpolicy_hash\x18\x02 \x01(\tR\n" + - "policyHash\"~\n" + + "policyHash\"\xc5\x01\n" + "\x17RejectDraftChunkRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x19\n" + "\bchunk_id\x18\x02 \x01(\tR\achunkId\x12\x16\n" + - "\x06reason\x18\x03 \x01(\tR\x06reason\x12\x1c\n" + - "\tworkspace\x18\x04 \x01(\tR\tworkspace\"\x1a\n" + + "\x06reason\x18\x03 \x01(\tR\x06reason\x12R\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05R\tworkspace\"\x1a\n" + "\x18RejectDraftChunkResponse\"R\n" + "\x12DraftChunkApproval\x12\x19\n" + "\bchunk_id\x18\x01 \x01(\tR\achunkId\x12!\n" + - "\freview_token\x18\x02 \x01(\tR\vreviewToken\"\xca\x01\n" + + "\freview_token\x18\x02 \x01(\tR\vreviewToken\"\x91\x02\n" + "\x1cApproveAllDraftChunksRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x128\n" + - "\x18include_security_flagged\x18\x02 \x01(\bR\x16includeSecurityFlagged\x12\x1c\n" + - "\tworkspace\x18\x03 \x01(\tR\tworkspace\x12>\n" + - "\tapprovals\x18\x04 \x03(\v2 .openshell.v1.DraftChunkApprovalR\tapprovals\"\xb7\x01\n" + + "\x18include_security_flagged\x18\x02 \x01(\bR\x16includeSecurityFlagged\x12>\n" + + "\tapprovals\x18\x04 \x03(\v2 .openshell.v1.DraftChunkApprovalR\tapprovals\x12R\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"\xb7\x01\n" + "\x1dApproveAllDraftChunksResponse\x12%\n" + "\x0epolicy_version\x18\x01 \x01(\rR\rpolicyVersion\x12\x1f\n" + "\vpolicy_hash\x18\x02 \x01(\tR\n" + "policyHash\x12'\n" + "\x0fchunks_approved\x18\x03 \x01(\rR\x0echunksApproved\x12%\n" + - "\x0echunks_skipped\x18\x04 \x01(\rR\rchunksSkipped\"\xb2\x01\n" + + "\x0echunks_skipped\x18\x04 \x01(\rR\rchunksSkipped\"\xf9\x01\n" + "\x15EditDraftChunkRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x19\n" + "\bchunk_id\x18\x02 \x01(\tR\achunkId\x12L\n" + - "\rproposed_rule\x18\x03 \x01(\v2'.openshell.sandbox.v1.NetworkPolicyRuleR\fproposedRule\x12\x1c\n" + - "\tworkspace\x18\x04 \x01(\tR\tworkspace\"\x18\n" + - "\x16EditDraftChunkResponse\"d\n" + + "\rproposed_rule\x18\x03 \x01(\v2'.openshell.sandbox.v1.NetworkPolicyRuleR\fproposedRule\x12R\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05R\tworkspace\"\x18\n" + + "\x16EditDraftChunkResponse\"\xab\x01\n" + "\x15UndoDraftChunkRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x19\n" + - "\bchunk_id\x18\x02 \x01(\tR\achunkId\x12\x1c\n" + - "\tworkspace\x18\x03 \x01(\tR\tworkspace\"`\n" + + "\bchunk_id\x18\x02 \x01(\tR\achunkId\x12R\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"`\n" + "\x16UndoDraftChunkResponse\x12%\n" + "\x0epolicy_version\x18\x01 \x01(\rR\rpolicyVersion\x12\x1f\n" + "\vpolicy_hash\x18\x02 \x01(\tR\n" + - "policyHash\"K\n" + + "policyHash\"\x92\x01\n" + "\x17ClearDraftChunksRequest\x12\x12\n" + - "\x04name\x18\x01 \x01(\tR\x04name\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"A\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"A\n" + "\x18ClearDraftChunksResponse\x12%\n" + - "\x0echunks_cleared\x18\x01 \x01(\rR\rchunksCleared\"J\n" + + "\x0echunks_cleared\x18\x01 \x01(\rR\rchunksCleared\"\x91\x01\n" + "\x16GetDraftHistoryRequest\x12\x12\n" + - "\x04name\x18\x01 \x01(\tR\x04name\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"\x92\x01\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\x92\x01\n" + "\x11DraftHistoryEntry\x12!\n" + "\ftimestamp_ms\x18\x01 \x01(\x03R\vtimestampMs\x12\x1d\n" + "\n" + @@ -15728,18 +15691,19 @@ var file_openshell_proto_goTypes = []any{ (*sandboxv1.SandboxPolicy)(nil), // 237: openshell.sandbox.v1.SandboxPolicy (*structpb.Struct)(nil), // 238: google.protobuf.Struct (*durationpb.Duration)(nil), // 239: google.protobuf.Duration - (*datamodelv1.Provider)(nil), // 240: openshell.datamodel.v1.Provider - (*sandboxv1.NetworkEndpoint)(nil), // 241: openshell.sandbox.v1.NetworkEndpoint - (*sandboxv1.NetworkBinary)(nil), // 242: openshell.sandbox.v1.NetworkBinary - (*sandboxv1.SettingValue)(nil), // 243: openshell.sandbox.v1.SettingValue - (*sandboxv1.NetworkPolicyRule)(nil), // 244: openshell.sandbox.v1.NetworkPolicyRule - (*sandboxv1.L7DenyRule)(nil), // 245: openshell.sandbox.v1.L7DenyRule - (*sandboxv1.L7Rule)(nil), // 246: openshell.sandbox.v1.L7Rule - (*datamodelv1.Workspace)(nil), // 247: openshell.datamodel.v1.Workspace - (*sandboxv1.GetSandboxConfigRequest)(nil), // 248: openshell.sandbox.v1.GetSandboxConfigRequest - (*sandboxv1.GetGatewayConfigRequest)(nil), // 249: openshell.sandbox.v1.GetGatewayConfigRequest - (*sandboxv1.GetSandboxConfigResponse)(nil), // 250: openshell.sandbox.v1.GetSandboxConfigResponse - (*sandboxv1.GetGatewayConfigResponse)(nil), // 251: openshell.sandbox.v1.GetGatewayConfigResponse + (*datamodelv1.WorkspaceSelector)(nil), // 240: openshell.datamodel.v1.WorkspaceSelector + (*datamodelv1.Provider)(nil), // 241: openshell.datamodel.v1.Provider + (*sandboxv1.NetworkEndpoint)(nil), // 242: openshell.sandbox.v1.NetworkEndpoint + (*sandboxv1.NetworkBinary)(nil), // 243: openshell.sandbox.v1.NetworkBinary + (*sandboxv1.SettingValue)(nil), // 244: openshell.sandbox.v1.SettingValue + (*sandboxv1.NetworkPolicyRule)(nil), // 245: openshell.sandbox.v1.NetworkPolicyRule + (*sandboxv1.L7DenyRule)(nil), // 246: openshell.sandbox.v1.L7DenyRule + (*sandboxv1.L7Rule)(nil), // 247: openshell.sandbox.v1.L7Rule + (*datamodelv1.Workspace)(nil), // 248: openshell.datamodel.v1.Workspace + (*sandboxv1.GetSandboxConfigRequest)(nil), // 249: openshell.sandbox.v1.GetSandboxConfigRequest + (*sandboxv1.GetGatewayConfigRequest)(nil), // 250: openshell.sandbox.v1.GetGatewayConfigRequest + (*sandboxv1.GetSandboxConfigResponse)(nil), // 251: openshell.sandbox.v1.GetSandboxConfigResponse + (*sandboxv1.GetGatewayConfigResponse)(nil), // 252: openshell.sandbox.v1.GetGatewayConfigResponse } var file_openshell_proto_depIdxs = []int32{ 214, // 0: openshell.v1.RefreshSandboxTokenResponse.extension_credentials:type_name -> openshell.v1.ExtensionServiceCredential @@ -15781,285 +15745,324 @@ var file_openshell_proto_depIdxs = []int32{ 25, // 36: openshell.v1.CreateSandboxRequest.spec:type_name -> openshell.v1.SandboxSpec 221, // 37: openshell.v1.CreateSandboxRequest.labels:type_name -> openshell.v1.CreateSandboxRequest.LabelsEntry 222, // 38: openshell.v1.CreateSandboxRequest.annotations:type_name -> openshell.v1.CreateSandboxRequest.AnnotationsEntry - 29, // 39: openshell.v1.CreateSandboxTemplateRequest.template:type_name -> openshell.v1.SandboxWorkloadTemplate - 29, // 40: openshell.v1.SandboxTemplateResponse.template:type_name -> openshell.v1.SandboxWorkloadTemplate - 29, // 41: openshell.v1.ListSandboxTemplatesResponse.templates:type_name -> openshell.v1.SandboxWorkloadTemplate - 24, // 42: openshell.v1.SandboxResponse.sandbox:type_name -> openshell.v1.Sandbox - 24, // 43: openshell.v1.ListSandboxesResponse.sandboxes:type_name -> openshell.v1.Sandbox - 240, // 44: openshell.v1.ListSandboxProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider - 24, // 45: openshell.v1.AttachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox - 24, // 46: openshell.v1.DetachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox - 72, // 47: openshell.v1.ListServicesResponse.services:type_name -> openshell.v1.ServiceEndpointResponse - 236, // 48: openshell.v1.ServiceEndpoint.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 71, // 49: openshell.v1.ServiceEndpointResponse.endpoint:type_name -> openshell.v1.ServiceEndpoint - 223, // 50: openshell.v1.ExecSandboxRequest.environment:type_name -> openshell.v1.ExecSandboxRequest.EnvironmentEntry - 76, // 51: openshell.v1.ExecSandboxEvent.stdout:type_name -> openshell.v1.ExecSandboxStdout - 77, // 52: openshell.v1.ExecSandboxEvent.stderr:type_name -> openshell.v1.ExecSandboxStderr - 78, // 53: openshell.v1.ExecSandboxEvent.exit:type_name -> openshell.v1.ExecSandboxExit - 167, // 54: openshell.v1.TcpForwardInit.ssh:type_name -> openshell.v1.SshRelayTarget - 168, // 55: openshell.v1.TcpForwardInit.tcp:type_name -> openshell.v1.TcpRelayTarget - 80, // 56: openshell.v1.TcpForwardFrame.init:type_name -> openshell.v1.TcpForwardInit - 75, // 57: openshell.v1.ExecSandboxInput.start:type_name -> openshell.v1.ExecSandboxRequest - 83, // 58: openshell.v1.ExecSandboxInput.resize:type_name -> openshell.v1.ExecSandboxWindowResize - 236, // 59: openshell.v1.SshSession.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 24, // 60: openshell.v1.SandboxStreamEvent.sandbox:type_name -> openshell.v1.Sandbox - 87, // 61: openshell.v1.SandboxStreamEvent.log:type_name -> openshell.v1.SandboxLogLine - 38, // 62: openshell.v1.SandboxStreamEvent.event:type_name -> openshell.v1.PlatformEvent - 88, // 63: openshell.v1.SandboxStreamEvent.warning:type_name -> openshell.v1.SandboxStreamWarning - 178, // 64: openshell.v1.SandboxStreamEvent.draft_policy_update:type_name -> openshell.v1.DraftPolicyUpdate - 224, // 65: openshell.v1.SandboxLogLine.fields:type_name -> openshell.v1.SandboxLogLine.FieldsEntry - 240, // 66: openshell.v1.CreateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider - 240, // 67: openshell.v1.UpdateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider - 225, // 68: openshell.v1.UpdateProviderRequest.credential_expires_at_ms:type_name -> openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry - 240, // 69: openshell.v1.ProviderResponse.provider:type_name -> openshell.datamodel.v1.Provider - 240, // 70: openshell.v1.ListProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider - 117, // 71: openshell.v1.ProviderProfileImportItem.profile:type_name -> openshell.v1.ProviderProfile - 100, // 72: openshell.v1.ProviderCredentialTokenGrant.audience_overrides:type_name -> openshell.v1.ProviderCredentialTokenGrantAudienceOverride - 1, // 73: openshell.v1.ProviderCredentialTokenGrant.grant_type:type_name -> openshell.v1.ProviderCredentialTokenGrantType - 101, // 74: openshell.v1.ProviderCredentialTokenGrant.subject_token:type_name -> openshell.v1.ProviderCredentialTokenGrantSubjectToken - 106, // 75: openshell.v1.ProviderProfileCredential.refresh:type_name -> openshell.v1.ProviderCredentialRefresh - 102, // 76: openshell.v1.ProviderProfileCredential.token_grant:type_name -> openshell.v1.ProviderCredentialTokenGrant - 2, // 77: openshell.v1.ProviderCredentialRefresh.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 104, // 78: openshell.v1.ProviderCredentialRefresh.material:type_name -> openshell.v1.ProviderCredentialRefreshMaterial - 105, // 79: openshell.v1.ProviderCredentialRefresh.additional_outputs:type_name -> openshell.v1.ProviderCredentialRefreshOutput - 2, // 80: openshell.v1.ProviderCredentialRefreshStatus.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 7, // 81: openshell.v1.ProviderCredentialRefreshStatus.recovery_action:type_name -> openshell.v1.ProviderCredentialRefreshRecoveryAction - 107, // 82: openshell.v1.GetProviderRefreshStatusResponse.credentials:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 2, // 83: openshell.v1.ConfigureProviderRefreshRequest.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 226, // 84: openshell.v1.ConfigureProviderRefreshRequest.material:type_name -> openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry - 107, // 85: openshell.v1.ConfigureProviderRefreshResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 107, // 86: openshell.v1.RotateProviderCredentialResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 3, // 87: openshell.v1.ProviderProfile.category:type_name -> openshell.v1.ProviderProfileCategory - 103, // 88: openshell.v1.ProviderProfile.credentials:type_name -> openshell.v1.ProviderProfileCredential - 241, // 89: openshell.v1.ProviderProfile.endpoints:type_name -> openshell.sandbox.v1.NetworkEndpoint - 242, // 90: openshell.v1.ProviderProfile.binaries:type_name -> openshell.sandbox.v1.NetworkBinary - 108, // 91: openshell.v1.ProviderProfile.discovery:type_name -> openshell.v1.ProviderProfileDiscovery - 227, // 92: openshell.v1.ProviderProfile.annotations:type_name -> openshell.v1.ProviderProfile.AnnotationsEntry - 117, // 93: openshell.v1.ProviderProfileResponse.profile:type_name -> openshell.v1.ProviderProfile - 117, // 94: openshell.v1.ListProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile - 98, // 95: openshell.v1.ImportProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem - 99, // 96: openshell.v1.ImportProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 117, // 97: openshell.v1.ImportProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile - 98, // 98: openshell.v1.UpdateProviderProfilesRequest.profile:type_name -> openshell.v1.ProviderProfileImportItem - 99, // 99: openshell.v1.UpdateProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 117, // 100: openshell.v1.UpdateProviderProfilesResponse.profile:type_name -> openshell.v1.ProviderProfile - 98, // 101: openshell.v1.LintProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem - 99, // 102: openshell.v1.LintProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 130, // 103: openshell.v1.StaticCredentialBinding.endpoints:type_name -> openshell.v1.StaticCredentialEndpointBinding - 228, // 104: openshell.v1.GetSandboxProviderEnvironmentResponse.environment:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry - 229, // 105: openshell.v1.GetSandboxProviderEnvironmentResponse.credential_expires_at_ms:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry - 230, // 106: openshell.v1.GetSandboxProviderEnvironmentResponse.dynamic_credentials:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry - 231, // 107: openshell.v1.GetSandboxProviderEnvironmentResponse.static_credential_bindings:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry - 237, // 108: openshell.v1.UpdateConfigRequest.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 243, // 109: openshell.v1.UpdateConfigRequest.setting_value:type_name -> openshell.sandbox.v1.SettingValue - 136, // 110: openshell.v1.UpdateConfigRequest.merge_operations:type_name -> openshell.v1.PolicyMergeOperation - 232, // 111: openshell.v1.UpdateConfigRequest.annotations:type_name -> openshell.v1.UpdateConfigRequest.AnnotationsEntry - 137, // 112: openshell.v1.PolicyMergeOperation.add_rule:type_name -> openshell.v1.AddNetworkRule - 138, // 113: openshell.v1.PolicyMergeOperation.remove_endpoint:type_name -> openshell.v1.RemoveNetworkEndpoint - 139, // 114: openshell.v1.PolicyMergeOperation.remove_rule:type_name -> openshell.v1.RemoveNetworkRule - 140, // 115: openshell.v1.PolicyMergeOperation.add_deny_rules:type_name -> openshell.v1.AddDenyRules - 141, // 116: openshell.v1.PolicyMergeOperation.add_allow_rules:type_name -> openshell.v1.AddAllowRules - 142, // 117: openshell.v1.PolicyMergeOperation.remove_binary:type_name -> openshell.v1.RemoveNetworkBinary - 244, // 118: openshell.v1.AddNetworkRule.rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 245, // 119: openshell.v1.AddDenyRules.deny_rules:type_name -> openshell.sandbox.v1.L7DenyRule - 246, // 120: openshell.v1.AddAllowRules.rules:type_name -> openshell.sandbox.v1.L7Rule - 233, // 121: openshell.v1.UpdateConfigResponse.annotations:type_name -> openshell.v1.UpdateConfigResponse.AnnotationsEntry - 150, // 122: openshell.v1.GetSandboxPolicyStatusResponse.revision:type_name -> openshell.v1.SandboxPolicyRevision - 150, // 123: openshell.v1.ListSandboxPoliciesResponse.revisions:type_name -> openshell.v1.SandboxPolicyRevision - 4, // 124: openshell.v1.ReportPolicyStatusRequest.status:type_name -> openshell.v1.PolicyStatus - 4, // 125: openshell.v1.SandboxPolicyRevision.status:type_name -> openshell.v1.PolicyStatus - 237, // 126: openshell.v1.SandboxPolicyRevision.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 234, // 127: openshell.v1.SandboxPolicyRevision.provenance:type_name -> openshell.v1.SandboxPolicyRevision.ProvenanceEntry - 87, // 128: openshell.v1.PushSandboxLogsRequest.logs:type_name -> openshell.v1.SandboxLogLine - 87, // 129: openshell.v1.GetSandboxLogsResponse.logs:type_name -> openshell.v1.SandboxLogLine - 157, // 130: openshell.v1.SupervisorMessage.hello:type_name -> openshell.v1.SupervisorHello - 160, // 131: openshell.v1.SupervisorMessage.heartbeat:type_name -> openshell.v1.SupervisorHeartbeat - 171, // 132: openshell.v1.SupervisorMessage.relay_open_result:type_name -> openshell.v1.RelayOpenResult - 172, // 133: openshell.v1.SupervisorMessage.relay_close:type_name -> openshell.v1.RelayClose - 158, // 134: openshell.v1.GatewayMessage.session_accepted:type_name -> openshell.v1.SessionAccepted - 159, // 135: openshell.v1.GatewayMessage.session_rejected:type_name -> openshell.v1.SessionRejected - 161, // 136: openshell.v1.GatewayMessage.heartbeat:type_name -> openshell.v1.GatewayHeartbeat - 166, // 137: openshell.v1.GatewayMessage.relay_open:type_name -> openshell.v1.RelayOpen - 172, // 138: openshell.v1.GatewayMessage.relay_close:type_name -> openshell.v1.RelayClose - 167, // 139: openshell.v1.RelayOpen.ssh:type_name -> openshell.v1.SshRelayTarget - 168, // 140: openshell.v1.RelayOpen.tcp:type_name -> openshell.v1.TcpRelayTarget - 169, // 141: openshell.v1.RelayFrame.init:type_name -> openshell.v1.RelayInit - 173, // 142: openshell.v1.DenialSummary.l7_request_samples:type_name -> openshell.v1.L7RequestSample - 175, // 143: openshell.v1.NetworkActivitySummary.denials_by_group:type_name -> openshell.v1.DenialGroupCount - 244, // 144: openshell.v1.PolicyChunk.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 237, // 145: openshell.v1.PolicyChunk.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 237, // 146: openshell.v1.PolicyChunk.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 174, // 147: openshell.v1.SubmitPolicyAnalysisRequest.summaries:type_name -> openshell.v1.DenialSummary - 177, // 148: openshell.v1.SubmitPolicyAnalysisRequest.proposed_chunks:type_name -> openshell.v1.PolicyChunk - 176, // 149: openshell.v1.SubmitPolicyAnalysisRequest.network_activity_summaries:type_name -> openshell.v1.NetworkActivitySummary - 177, // 150: openshell.v1.GetDraftPolicyResponse.chunks:type_name -> openshell.v1.PolicyChunk - 187, // 151: openshell.v1.ApproveAllDraftChunksRequest.approvals:type_name -> openshell.v1.DraftChunkApproval - 244, // 152: openshell.v1.EditDraftChunkRequest.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 197, // 153: openshell.v1.GetDraftHistoryResponse.entries:type_name -> openshell.v1.DraftHistoryEntry - 235, // 154: openshell.v1.CreateWorkspaceRequest.labels:type_name -> openshell.v1.CreateWorkspaceRequest.LabelsEntry - 247, // 155: openshell.v1.CreateWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace - 247, // 156: openshell.v1.GetWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace - 247, // 157: openshell.v1.ListWorkspacesResponse.workspaces:type_name -> openshell.datamodel.v1.Workspace - 236, // 158: openshell.v1.WorkspaceMember.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 6, // 159: openshell.v1.WorkspaceMember.role:type_name -> openshell.v1.WorkspaceRole - 6, // 160: openshell.v1.AddWorkspaceMemberRequest.role:type_name -> openshell.v1.WorkspaceRole - 207, // 161: openshell.v1.AddWorkspaceMemberResponse.member:type_name -> openshell.v1.WorkspaceMember - 207, // 162: openshell.v1.ListWorkspaceMembersResponse.members:type_name -> openshell.v1.WorkspaceMember - 103, // 163: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry.value:type_name -> openshell.v1.ProviderProfileCredential - 131, // 164: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry.value:type_name -> openshell.v1.StaticCredentialBinding - 12, // 165: openshell.v1.OpenShell.Health:input_type -> openshell.v1.HealthRequest - 14, // 166: openshell.v1.OpenShell.GetCurrentUser:input_type -> openshell.v1.GetCurrentUserRequest - 16, // 167: openshell.v1.OpenShell.GetGatewayInfo:input_type -> openshell.v1.GetGatewayInfoRequest - 39, // 168: openshell.v1.OpenShell.CreateSandbox:input_type -> openshell.v1.CreateSandboxRequest - 47, // 169: openshell.v1.OpenShell.BeginRootfsTarStaging:input_type -> openshell.v1.BeginRootfsTarStagingRequest - 49, // 170: openshell.v1.OpenShell.GetSandbox:input_type -> openshell.v1.GetSandboxRequest - 50, // 171: openshell.v1.OpenShell.ListSandboxes:input_type -> openshell.v1.ListSandboxesRequest - 40, // 172: openshell.v1.OpenShell.CreateSandboxTemplate:input_type -> openshell.v1.CreateSandboxTemplateRequest - 41, // 173: openshell.v1.OpenShell.GetSandboxTemplate:input_type -> openshell.v1.GetSandboxTemplateRequest - 42, // 174: openshell.v1.OpenShell.ListSandboxTemplates:input_type -> openshell.v1.ListSandboxTemplatesRequest - 43, // 175: openshell.v1.OpenShell.DeleteSandboxTemplate:input_type -> openshell.v1.DeleteSandboxTemplateRequest - 51, // 176: openshell.v1.OpenShell.ListSandboxProviders:input_type -> openshell.v1.ListSandboxProvidersRequest - 52, // 177: openshell.v1.OpenShell.AttachSandboxProvider:input_type -> openshell.v1.AttachSandboxProviderRequest - 53, // 178: openshell.v1.OpenShell.DetachSandboxProvider:input_type -> openshell.v1.DetachSandboxProviderRequest - 54, // 179: openshell.v1.OpenShell.DeleteSandbox:input_type -> openshell.v1.DeleteSandboxRequest - 55, // 180: openshell.v1.OpenShell.StopSandbox:input_type -> openshell.v1.StopSandboxRequest - 56, // 181: openshell.v1.OpenShell.StartSandbox:input_type -> openshell.v1.StartSandboxRequest - 63, // 182: openshell.v1.OpenShell.CreateSshSession:input_type -> openshell.v1.CreateSshSessionRequest - 65, // 183: openshell.v1.OpenShell.ExposeService:input_type -> openshell.v1.ExposeServiceRequest - 66, // 184: openshell.v1.OpenShell.GetService:input_type -> openshell.v1.GetServiceRequest - 67, // 185: openshell.v1.OpenShell.ListServices:input_type -> openshell.v1.ListServicesRequest - 69, // 186: openshell.v1.OpenShell.DeleteService:input_type -> openshell.v1.DeleteServiceRequest - 73, // 187: openshell.v1.OpenShell.RevokeSshSession:input_type -> openshell.v1.RevokeSshSessionRequest - 75, // 188: openshell.v1.OpenShell.ExecSandbox:input_type -> openshell.v1.ExecSandboxRequest - 81, // 189: openshell.v1.OpenShell.ForwardTcp:input_type -> openshell.v1.TcpForwardFrame - 82, // 190: openshell.v1.OpenShell.ExecSandboxInteractive:input_type -> openshell.v1.ExecSandboxInput - 89, // 191: openshell.v1.OpenShell.CreateProvider:input_type -> openshell.v1.CreateProviderRequest - 90, // 192: openshell.v1.OpenShell.GetProvider:input_type -> openshell.v1.GetProviderRequest - 91, // 193: openshell.v1.OpenShell.ListProviders:input_type -> openshell.v1.ListProvidersRequest - 96, // 194: openshell.v1.OpenShell.ListProviderProfiles:input_type -> openshell.v1.ListProviderProfilesRequest - 97, // 195: openshell.v1.OpenShell.GetProviderProfile:input_type -> openshell.v1.GetProviderProfileRequest - 120, // 196: openshell.v1.OpenShell.ImportProviderProfiles:input_type -> openshell.v1.ImportProviderProfilesRequest - 122, // 197: openshell.v1.OpenShell.UpdateProviderProfiles:input_type -> openshell.v1.UpdateProviderProfilesRequest - 124, // 198: openshell.v1.OpenShell.LintProviderProfiles:input_type -> openshell.v1.LintProviderProfilesRequest - 92, // 199: openshell.v1.OpenShell.UpdateProvider:input_type -> openshell.v1.UpdateProviderRequest - 109, // 200: openshell.v1.OpenShell.GetProviderRefreshStatus:input_type -> openshell.v1.GetProviderRefreshStatusRequest - 111, // 201: openshell.v1.OpenShell.ConfigureProviderRefresh:input_type -> openshell.v1.ConfigureProviderRefreshRequest - 113, // 202: openshell.v1.OpenShell.RotateProviderCredential:input_type -> openshell.v1.RotateProviderCredentialRequest - 115, // 203: openshell.v1.OpenShell.DeleteProviderRefresh:input_type -> openshell.v1.DeleteProviderRefreshRequest - 93, // 204: openshell.v1.OpenShell.DeleteProvider:input_type -> openshell.v1.DeleteProviderRequest - 127, // 205: openshell.v1.OpenShell.DeleteProviderProfile:input_type -> openshell.v1.DeleteProviderProfileRequest - 248, // 206: openshell.v1.OpenShell.GetSandboxConfig:input_type -> openshell.sandbox.v1.GetSandboxConfigRequest - 249, // 207: openshell.v1.OpenShell.GetGatewayConfig:input_type -> openshell.sandbox.v1.GetGatewayConfigRequest - 135, // 208: openshell.v1.OpenShell.UpdateConfig:input_type -> openshell.v1.UpdateConfigRequest - 144, // 209: openshell.v1.OpenShell.GetSandboxPolicyStatus:input_type -> openshell.v1.GetSandboxPolicyStatusRequest - 146, // 210: openshell.v1.OpenShell.ListSandboxPolicies:input_type -> openshell.v1.ListSandboxPoliciesRequest - 148, // 211: openshell.v1.OpenShell.ReportPolicyStatus:input_type -> openshell.v1.ReportPolicyStatusRequest - 129, // 212: openshell.v1.OpenShell.GetSandboxProviderEnvironment:input_type -> openshell.v1.GetSandboxProviderEnvironmentRequest - 133, // 213: openshell.v1.OpenShell.ExchangeProviderSubjectToken:input_type -> openshell.v1.ExchangeProviderSubjectTokenRequest - 151, // 214: openshell.v1.OpenShell.GetSandboxLogs:input_type -> openshell.v1.GetSandboxLogsRequest - 152, // 215: openshell.v1.OpenShell.PushSandboxLogs:input_type -> openshell.v1.PushSandboxLogsRequest - 155, // 216: openshell.v1.OpenShell.ConnectSupervisor:input_type -> openshell.v1.SupervisorMessage - 162, // 217: openshell.v1.OpenShell.ReportMainProcessExit:input_type -> openshell.v1.ReportMainProcessExitRequest - 164, // 218: openshell.v1.OpenShell.FinalizeMainProcessExit:input_type -> openshell.v1.FinalizeMainProcessExitRequest - 170, // 219: openshell.v1.OpenShell.RelayStream:input_type -> openshell.v1.RelayFrame - 85, // 220: openshell.v1.OpenShell.WatchSandbox:input_type -> openshell.v1.WatchSandboxRequest - 179, // 221: openshell.v1.OpenShell.SubmitPolicyAnalysis:input_type -> openshell.v1.SubmitPolicyAnalysisRequest - 181, // 222: openshell.v1.OpenShell.GetDraftPolicy:input_type -> openshell.v1.GetDraftPolicyRequest - 183, // 223: openshell.v1.OpenShell.ApproveDraftChunk:input_type -> openshell.v1.ApproveDraftChunkRequest - 185, // 224: openshell.v1.OpenShell.RejectDraftChunk:input_type -> openshell.v1.RejectDraftChunkRequest - 188, // 225: openshell.v1.OpenShell.ApproveAllDraftChunks:input_type -> openshell.v1.ApproveAllDraftChunksRequest - 190, // 226: openshell.v1.OpenShell.EditDraftChunk:input_type -> openshell.v1.EditDraftChunkRequest - 192, // 227: openshell.v1.OpenShell.UndoDraftChunk:input_type -> openshell.v1.UndoDraftChunkRequest - 194, // 228: openshell.v1.OpenShell.ClearDraftChunks:input_type -> openshell.v1.ClearDraftChunksRequest - 196, // 229: openshell.v1.OpenShell.GetDraftHistory:input_type -> openshell.v1.GetDraftHistoryRequest - 8, // 230: openshell.v1.OpenShell.IssueSandboxToken:input_type -> openshell.v1.IssueSandboxTokenRequest - 10, // 231: openshell.v1.OpenShell.RefreshSandboxToken:input_type -> openshell.v1.RefreshSandboxTokenRequest - 199, // 232: openshell.v1.OpenShell.CreateWorkspace:input_type -> openshell.v1.CreateWorkspaceRequest - 201, // 233: openshell.v1.OpenShell.GetWorkspace:input_type -> openshell.v1.GetWorkspaceRequest - 203, // 234: openshell.v1.OpenShell.ListWorkspaces:input_type -> openshell.v1.ListWorkspacesRequest - 205, // 235: openshell.v1.OpenShell.DeleteWorkspace:input_type -> openshell.v1.DeleteWorkspaceRequest - 208, // 236: openshell.v1.OpenShell.AddWorkspaceMember:input_type -> openshell.v1.AddWorkspaceMemberRequest - 210, // 237: openshell.v1.OpenShell.RemoveWorkspaceMember:input_type -> openshell.v1.RemoveWorkspaceMemberRequest - 212, // 238: openshell.v1.OpenShell.ListWorkspaceMembers:input_type -> openshell.v1.ListWorkspaceMembersRequest - 13, // 239: openshell.v1.OpenShell.Health:output_type -> openshell.v1.HealthResponse - 15, // 240: openshell.v1.OpenShell.GetCurrentUser:output_type -> openshell.v1.GetCurrentUserResponse - 17, // 241: openshell.v1.OpenShell.GetGatewayInfo:output_type -> openshell.v1.GetGatewayInfoResponse - 57, // 242: openshell.v1.OpenShell.CreateSandbox:output_type -> openshell.v1.SandboxResponse - 48, // 243: openshell.v1.OpenShell.BeginRootfsTarStaging:output_type -> openshell.v1.BeginRootfsTarStagingResponse - 57, // 244: openshell.v1.OpenShell.GetSandbox:output_type -> openshell.v1.SandboxResponse - 58, // 245: openshell.v1.OpenShell.ListSandboxes:output_type -> openshell.v1.ListSandboxesResponse - 44, // 246: openshell.v1.OpenShell.CreateSandboxTemplate:output_type -> openshell.v1.SandboxTemplateResponse - 44, // 247: openshell.v1.OpenShell.GetSandboxTemplate:output_type -> openshell.v1.SandboxTemplateResponse - 45, // 248: openshell.v1.OpenShell.ListSandboxTemplates:output_type -> openshell.v1.ListSandboxTemplatesResponse - 46, // 249: openshell.v1.OpenShell.DeleteSandboxTemplate:output_type -> openshell.v1.DeleteSandboxTemplateResponse - 59, // 250: openshell.v1.OpenShell.ListSandboxProviders:output_type -> openshell.v1.ListSandboxProvidersResponse - 60, // 251: openshell.v1.OpenShell.AttachSandboxProvider:output_type -> openshell.v1.AttachSandboxProviderResponse - 61, // 252: openshell.v1.OpenShell.DetachSandboxProvider:output_type -> openshell.v1.DetachSandboxProviderResponse - 62, // 253: openshell.v1.OpenShell.DeleteSandbox:output_type -> openshell.v1.DeleteSandboxResponse - 57, // 254: openshell.v1.OpenShell.StopSandbox:output_type -> openshell.v1.SandboxResponse - 57, // 255: openshell.v1.OpenShell.StartSandbox:output_type -> openshell.v1.SandboxResponse - 64, // 256: openshell.v1.OpenShell.CreateSshSession:output_type -> openshell.v1.CreateSshSessionResponse - 72, // 257: openshell.v1.OpenShell.ExposeService:output_type -> openshell.v1.ServiceEndpointResponse - 72, // 258: openshell.v1.OpenShell.GetService:output_type -> openshell.v1.ServiceEndpointResponse - 68, // 259: openshell.v1.OpenShell.ListServices:output_type -> openshell.v1.ListServicesResponse - 70, // 260: openshell.v1.OpenShell.DeleteService:output_type -> openshell.v1.DeleteServiceResponse - 74, // 261: openshell.v1.OpenShell.RevokeSshSession:output_type -> openshell.v1.RevokeSshSessionResponse - 79, // 262: openshell.v1.OpenShell.ExecSandbox:output_type -> openshell.v1.ExecSandboxEvent - 81, // 263: openshell.v1.OpenShell.ForwardTcp:output_type -> openshell.v1.TcpForwardFrame - 79, // 264: openshell.v1.OpenShell.ExecSandboxInteractive:output_type -> openshell.v1.ExecSandboxEvent - 94, // 265: openshell.v1.OpenShell.CreateProvider:output_type -> openshell.v1.ProviderResponse - 94, // 266: openshell.v1.OpenShell.GetProvider:output_type -> openshell.v1.ProviderResponse - 95, // 267: openshell.v1.OpenShell.ListProviders:output_type -> openshell.v1.ListProvidersResponse - 119, // 268: openshell.v1.OpenShell.ListProviderProfiles:output_type -> openshell.v1.ListProviderProfilesResponse - 118, // 269: openshell.v1.OpenShell.GetProviderProfile:output_type -> openshell.v1.ProviderProfileResponse - 121, // 270: openshell.v1.OpenShell.ImportProviderProfiles:output_type -> openshell.v1.ImportProviderProfilesResponse - 123, // 271: openshell.v1.OpenShell.UpdateProviderProfiles:output_type -> openshell.v1.UpdateProviderProfilesResponse - 125, // 272: openshell.v1.OpenShell.LintProviderProfiles:output_type -> openshell.v1.LintProviderProfilesResponse - 94, // 273: openshell.v1.OpenShell.UpdateProvider:output_type -> openshell.v1.ProviderResponse - 110, // 274: openshell.v1.OpenShell.GetProviderRefreshStatus:output_type -> openshell.v1.GetProviderRefreshStatusResponse - 112, // 275: openshell.v1.OpenShell.ConfigureProviderRefresh:output_type -> openshell.v1.ConfigureProviderRefreshResponse - 114, // 276: openshell.v1.OpenShell.RotateProviderCredential:output_type -> openshell.v1.RotateProviderCredentialResponse - 116, // 277: openshell.v1.OpenShell.DeleteProviderRefresh:output_type -> openshell.v1.DeleteProviderRefreshResponse - 126, // 278: openshell.v1.OpenShell.DeleteProvider:output_type -> openshell.v1.DeleteProviderResponse - 128, // 279: openshell.v1.OpenShell.DeleteProviderProfile:output_type -> openshell.v1.DeleteProviderProfileResponse - 250, // 280: openshell.v1.OpenShell.GetSandboxConfig:output_type -> openshell.sandbox.v1.GetSandboxConfigResponse - 251, // 281: openshell.v1.OpenShell.GetGatewayConfig:output_type -> openshell.sandbox.v1.GetGatewayConfigResponse - 143, // 282: openshell.v1.OpenShell.UpdateConfig:output_type -> openshell.v1.UpdateConfigResponse - 145, // 283: openshell.v1.OpenShell.GetSandboxPolicyStatus:output_type -> openshell.v1.GetSandboxPolicyStatusResponse - 147, // 284: openshell.v1.OpenShell.ListSandboxPolicies:output_type -> openshell.v1.ListSandboxPoliciesResponse - 149, // 285: openshell.v1.OpenShell.ReportPolicyStatus:output_type -> openshell.v1.ReportPolicyStatusResponse - 132, // 286: openshell.v1.OpenShell.GetSandboxProviderEnvironment:output_type -> openshell.v1.GetSandboxProviderEnvironmentResponse - 134, // 287: openshell.v1.OpenShell.ExchangeProviderSubjectToken:output_type -> openshell.v1.ExchangeProviderSubjectTokenResponse - 154, // 288: openshell.v1.OpenShell.GetSandboxLogs:output_type -> openshell.v1.GetSandboxLogsResponse - 153, // 289: openshell.v1.OpenShell.PushSandboxLogs:output_type -> openshell.v1.PushSandboxLogsResponse - 156, // 290: openshell.v1.OpenShell.ConnectSupervisor:output_type -> openshell.v1.GatewayMessage - 163, // 291: openshell.v1.OpenShell.ReportMainProcessExit:output_type -> openshell.v1.ReportMainProcessExitResponse - 165, // 292: openshell.v1.OpenShell.FinalizeMainProcessExit:output_type -> openshell.v1.FinalizeMainProcessExitResponse - 170, // 293: openshell.v1.OpenShell.RelayStream:output_type -> openshell.v1.RelayFrame - 86, // 294: openshell.v1.OpenShell.WatchSandbox:output_type -> openshell.v1.SandboxStreamEvent - 180, // 295: openshell.v1.OpenShell.SubmitPolicyAnalysis:output_type -> openshell.v1.SubmitPolicyAnalysisResponse - 182, // 296: openshell.v1.OpenShell.GetDraftPolicy:output_type -> openshell.v1.GetDraftPolicyResponse - 184, // 297: openshell.v1.OpenShell.ApproveDraftChunk:output_type -> openshell.v1.ApproveDraftChunkResponse - 186, // 298: openshell.v1.OpenShell.RejectDraftChunk:output_type -> openshell.v1.RejectDraftChunkResponse - 189, // 299: openshell.v1.OpenShell.ApproveAllDraftChunks:output_type -> openshell.v1.ApproveAllDraftChunksResponse - 191, // 300: openshell.v1.OpenShell.EditDraftChunk:output_type -> openshell.v1.EditDraftChunkResponse - 193, // 301: openshell.v1.OpenShell.UndoDraftChunk:output_type -> openshell.v1.UndoDraftChunkResponse - 195, // 302: openshell.v1.OpenShell.ClearDraftChunks:output_type -> openshell.v1.ClearDraftChunksResponse - 198, // 303: openshell.v1.OpenShell.GetDraftHistory:output_type -> openshell.v1.GetDraftHistoryResponse - 9, // 304: openshell.v1.OpenShell.IssueSandboxToken:output_type -> openshell.v1.IssueSandboxTokenResponse - 11, // 305: openshell.v1.OpenShell.RefreshSandboxToken:output_type -> openshell.v1.RefreshSandboxTokenResponse - 200, // 306: openshell.v1.OpenShell.CreateWorkspace:output_type -> openshell.v1.CreateWorkspaceResponse - 202, // 307: openshell.v1.OpenShell.GetWorkspace:output_type -> openshell.v1.GetWorkspaceResponse - 204, // 308: openshell.v1.OpenShell.ListWorkspaces:output_type -> openshell.v1.ListWorkspacesResponse - 206, // 309: openshell.v1.OpenShell.DeleteWorkspace:output_type -> openshell.v1.DeleteWorkspaceResponse - 209, // 310: openshell.v1.OpenShell.AddWorkspaceMember:output_type -> openshell.v1.AddWorkspaceMemberResponse - 211, // 311: openshell.v1.OpenShell.RemoveWorkspaceMember:output_type -> openshell.v1.RemoveWorkspaceMemberResponse - 213, // 312: openshell.v1.OpenShell.ListWorkspaceMembers:output_type -> openshell.v1.ListWorkspaceMembersResponse - 239, // [239:313] is the sub-list for method output_type - 165, // [165:239] is the sub-list for method input_type - 165, // [165:165] is the sub-list for extension type_name - 165, // [165:165] is the sub-list for extension extendee - 0, // [0:165] is the sub-list for field type_name + 240, // 39: openshell.v1.CreateSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 29, // 40: openshell.v1.CreateSandboxTemplateRequest.template:type_name -> openshell.v1.SandboxWorkloadTemplate + 240, // 41: openshell.v1.CreateSandboxTemplateRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 42: openshell.v1.GetSandboxTemplateRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 43: openshell.v1.ListSandboxTemplatesRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 44: openshell.v1.DeleteSandboxTemplateRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 29, // 45: openshell.v1.SandboxTemplateResponse.template:type_name -> openshell.v1.SandboxWorkloadTemplate + 29, // 46: openshell.v1.ListSandboxTemplatesResponse.templates:type_name -> openshell.v1.SandboxWorkloadTemplate + 240, // 47: openshell.v1.BeginRootfsTarStagingRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 48: openshell.v1.GetSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 49: openshell.v1.ListSandboxesRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 50: openshell.v1.ListSandboxProvidersRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 51: openshell.v1.AttachSandboxProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 52: openshell.v1.DetachSandboxProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 53: openshell.v1.DeleteSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 54: openshell.v1.StopSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 55: openshell.v1.StartSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 24, // 56: openshell.v1.SandboxResponse.sandbox:type_name -> openshell.v1.Sandbox + 24, // 57: openshell.v1.ListSandboxesResponse.sandboxes:type_name -> openshell.v1.Sandbox + 241, // 58: openshell.v1.ListSandboxProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider + 24, // 59: openshell.v1.AttachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox + 24, // 60: openshell.v1.DetachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox + 240, // 61: openshell.v1.ExposeServiceRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 62: openshell.v1.GetServiceRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 63: openshell.v1.ListServicesRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 72, // 64: openshell.v1.ListServicesResponse.services:type_name -> openshell.v1.ServiceEndpointResponse + 240, // 65: openshell.v1.DeleteServiceRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 236, // 66: openshell.v1.ServiceEndpoint.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 71, // 67: openshell.v1.ServiceEndpointResponse.endpoint:type_name -> openshell.v1.ServiceEndpoint + 223, // 68: openshell.v1.ExecSandboxRequest.environment:type_name -> openshell.v1.ExecSandboxRequest.EnvironmentEntry + 76, // 69: openshell.v1.ExecSandboxEvent.stdout:type_name -> openshell.v1.ExecSandboxStdout + 77, // 70: openshell.v1.ExecSandboxEvent.stderr:type_name -> openshell.v1.ExecSandboxStderr + 78, // 71: openshell.v1.ExecSandboxEvent.exit:type_name -> openshell.v1.ExecSandboxExit + 167, // 72: openshell.v1.TcpForwardInit.ssh:type_name -> openshell.v1.SshRelayTarget + 168, // 73: openshell.v1.TcpForwardInit.tcp:type_name -> openshell.v1.TcpRelayTarget + 80, // 74: openshell.v1.TcpForwardFrame.init:type_name -> openshell.v1.TcpForwardInit + 75, // 75: openshell.v1.ExecSandboxInput.start:type_name -> openshell.v1.ExecSandboxRequest + 83, // 76: openshell.v1.ExecSandboxInput.resize:type_name -> openshell.v1.ExecSandboxWindowResize + 236, // 77: openshell.v1.SshSession.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 24, // 78: openshell.v1.SandboxStreamEvent.sandbox:type_name -> openshell.v1.Sandbox + 87, // 79: openshell.v1.SandboxStreamEvent.log:type_name -> openshell.v1.SandboxLogLine + 38, // 80: openshell.v1.SandboxStreamEvent.event:type_name -> openshell.v1.PlatformEvent + 88, // 81: openshell.v1.SandboxStreamEvent.warning:type_name -> openshell.v1.SandboxStreamWarning + 178, // 82: openshell.v1.SandboxStreamEvent.draft_policy_update:type_name -> openshell.v1.DraftPolicyUpdate + 224, // 83: openshell.v1.SandboxLogLine.fields:type_name -> openshell.v1.SandboxLogLine.FieldsEntry + 241, // 84: openshell.v1.CreateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider + 240, // 85: openshell.v1.CreateProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 86: openshell.v1.GetProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 87: openshell.v1.ListProvidersRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 241, // 88: openshell.v1.UpdateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider + 225, // 89: openshell.v1.UpdateProviderRequest.credential_expires_at_ms:type_name -> openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry + 240, // 90: openshell.v1.UpdateProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 91: openshell.v1.DeleteProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 241, // 92: openshell.v1.ProviderResponse.provider:type_name -> openshell.datamodel.v1.Provider + 241, // 93: openshell.v1.ListProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider + 117, // 94: openshell.v1.ProviderProfileImportItem.profile:type_name -> openshell.v1.ProviderProfile + 100, // 95: openshell.v1.ProviderCredentialTokenGrant.audience_overrides:type_name -> openshell.v1.ProviderCredentialTokenGrantAudienceOverride + 1, // 96: openshell.v1.ProviderCredentialTokenGrant.grant_type:type_name -> openshell.v1.ProviderCredentialTokenGrantType + 101, // 97: openshell.v1.ProviderCredentialTokenGrant.subject_token:type_name -> openshell.v1.ProviderCredentialTokenGrantSubjectToken + 106, // 98: openshell.v1.ProviderProfileCredential.refresh:type_name -> openshell.v1.ProviderCredentialRefresh + 102, // 99: openshell.v1.ProviderProfileCredential.token_grant:type_name -> openshell.v1.ProviderCredentialTokenGrant + 2, // 100: openshell.v1.ProviderCredentialRefresh.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 104, // 101: openshell.v1.ProviderCredentialRefresh.material:type_name -> openshell.v1.ProviderCredentialRefreshMaterial + 105, // 102: openshell.v1.ProviderCredentialRefresh.additional_outputs:type_name -> openshell.v1.ProviderCredentialRefreshOutput + 2, // 103: openshell.v1.ProviderCredentialRefreshStatus.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 7, // 104: openshell.v1.ProviderCredentialRefreshStatus.recovery_action:type_name -> openshell.v1.ProviderCredentialRefreshRecoveryAction + 240, // 105: openshell.v1.GetProviderRefreshStatusRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 107, // 106: openshell.v1.GetProviderRefreshStatusResponse.credentials:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 2, // 107: openshell.v1.ConfigureProviderRefreshRequest.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 226, // 108: openshell.v1.ConfigureProviderRefreshRequest.material:type_name -> openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry + 240, // 109: openshell.v1.ConfigureProviderRefreshRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 107, // 110: openshell.v1.ConfigureProviderRefreshResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 240, // 111: openshell.v1.RotateProviderCredentialRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 107, // 112: openshell.v1.RotateProviderCredentialResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 240, // 113: openshell.v1.DeleteProviderRefreshRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 3, // 114: openshell.v1.ProviderProfile.category:type_name -> openshell.v1.ProviderProfileCategory + 103, // 115: openshell.v1.ProviderProfile.credentials:type_name -> openshell.v1.ProviderProfileCredential + 242, // 116: openshell.v1.ProviderProfile.endpoints:type_name -> openshell.sandbox.v1.NetworkEndpoint + 243, // 117: openshell.v1.ProviderProfile.binaries:type_name -> openshell.sandbox.v1.NetworkBinary + 108, // 118: openshell.v1.ProviderProfile.discovery:type_name -> openshell.v1.ProviderProfileDiscovery + 227, // 119: openshell.v1.ProviderProfile.annotations:type_name -> openshell.v1.ProviderProfile.AnnotationsEntry + 117, // 120: openshell.v1.ProviderProfileResponse.profile:type_name -> openshell.v1.ProviderProfile + 117, // 121: openshell.v1.ListProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile + 98, // 122: openshell.v1.ImportProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem + 99, // 123: openshell.v1.ImportProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 117, // 124: openshell.v1.ImportProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile + 98, // 125: openshell.v1.UpdateProviderProfilesRequest.profile:type_name -> openshell.v1.ProviderProfileImportItem + 99, // 126: openshell.v1.UpdateProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 117, // 127: openshell.v1.UpdateProviderProfilesResponse.profile:type_name -> openshell.v1.ProviderProfile + 98, // 128: openshell.v1.LintProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem + 99, // 129: openshell.v1.LintProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 130, // 130: openshell.v1.StaticCredentialBinding.endpoints:type_name -> openshell.v1.StaticCredentialEndpointBinding + 228, // 131: openshell.v1.GetSandboxProviderEnvironmentResponse.environment:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry + 229, // 132: openshell.v1.GetSandboxProviderEnvironmentResponse.credential_expires_at_ms:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry + 230, // 133: openshell.v1.GetSandboxProviderEnvironmentResponse.dynamic_credentials:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry + 231, // 134: openshell.v1.GetSandboxProviderEnvironmentResponse.static_credential_bindings:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry + 237, // 135: openshell.v1.UpdateConfigRequest.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 244, // 136: openshell.v1.UpdateConfigRequest.setting_value:type_name -> openshell.sandbox.v1.SettingValue + 136, // 137: openshell.v1.UpdateConfigRequest.merge_operations:type_name -> openshell.v1.PolicyMergeOperation + 232, // 138: openshell.v1.UpdateConfigRequest.annotations:type_name -> openshell.v1.UpdateConfigRequest.AnnotationsEntry + 240, // 139: openshell.v1.UpdateConfigRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 137, // 140: openshell.v1.PolicyMergeOperation.add_rule:type_name -> openshell.v1.AddNetworkRule + 138, // 141: openshell.v1.PolicyMergeOperation.remove_endpoint:type_name -> openshell.v1.RemoveNetworkEndpoint + 139, // 142: openshell.v1.PolicyMergeOperation.remove_rule:type_name -> openshell.v1.RemoveNetworkRule + 140, // 143: openshell.v1.PolicyMergeOperation.add_deny_rules:type_name -> openshell.v1.AddDenyRules + 141, // 144: openshell.v1.PolicyMergeOperation.add_allow_rules:type_name -> openshell.v1.AddAllowRules + 142, // 145: openshell.v1.PolicyMergeOperation.remove_binary:type_name -> openshell.v1.RemoveNetworkBinary + 245, // 146: openshell.v1.AddNetworkRule.rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 246, // 147: openshell.v1.AddDenyRules.deny_rules:type_name -> openshell.sandbox.v1.L7DenyRule + 247, // 148: openshell.v1.AddAllowRules.rules:type_name -> openshell.sandbox.v1.L7Rule + 233, // 149: openshell.v1.UpdateConfigResponse.annotations:type_name -> openshell.v1.UpdateConfigResponse.AnnotationsEntry + 240, // 150: openshell.v1.GetSandboxPolicyStatusRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 150, // 151: openshell.v1.GetSandboxPolicyStatusResponse.revision:type_name -> openshell.v1.SandboxPolicyRevision + 240, // 152: openshell.v1.ListSandboxPoliciesRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 150, // 153: openshell.v1.ListSandboxPoliciesResponse.revisions:type_name -> openshell.v1.SandboxPolicyRevision + 4, // 154: openshell.v1.ReportPolicyStatusRequest.status:type_name -> openshell.v1.PolicyStatus + 4, // 155: openshell.v1.SandboxPolicyRevision.status:type_name -> openshell.v1.PolicyStatus + 237, // 156: openshell.v1.SandboxPolicyRevision.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 234, // 157: openshell.v1.SandboxPolicyRevision.provenance:type_name -> openshell.v1.SandboxPolicyRevision.ProvenanceEntry + 240, // 158: openshell.v1.GetSandboxLogsRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 87, // 159: openshell.v1.PushSandboxLogsRequest.logs:type_name -> openshell.v1.SandboxLogLine + 87, // 160: openshell.v1.GetSandboxLogsResponse.logs:type_name -> openshell.v1.SandboxLogLine + 157, // 161: openshell.v1.SupervisorMessage.hello:type_name -> openshell.v1.SupervisorHello + 160, // 162: openshell.v1.SupervisorMessage.heartbeat:type_name -> openshell.v1.SupervisorHeartbeat + 171, // 163: openshell.v1.SupervisorMessage.relay_open_result:type_name -> openshell.v1.RelayOpenResult + 172, // 164: openshell.v1.SupervisorMessage.relay_close:type_name -> openshell.v1.RelayClose + 158, // 165: openshell.v1.GatewayMessage.session_accepted:type_name -> openshell.v1.SessionAccepted + 159, // 166: openshell.v1.GatewayMessage.session_rejected:type_name -> openshell.v1.SessionRejected + 161, // 167: openshell.v1.GatewayMessage.heartbeat:type_name -> openshell.v1.GatewayHeartbeat + 166, // 168: openshell.v1.GatewayMessage.relay_open:type_name -> openshell.v1.RelayOpen + 172, // 169: openshell.v1.GatewayMessage.relay_close:type_name -> openshell.v1.RelayClose + 167, // 170: openshell.v1.RelayOpen.ssh:type_name -> openshell.v1.SshRelayTarget + 168, // 171: openshell.v1.RelayOpen.tcp:type_name -> openshell.v1.TcpRelayTarget + 169, // 172: openshell.v1.RelayFrame.init:type_name -> openshell.v1.RelayInit + 173, // 173: openshell.v1.DenialSummary.l7_request_samples:type_name -> openshell.v1.L7RequestSample + 175, // 174: openshell.v1.NetworkActivitySummary.denials_by_group:type_name -> openshell.v1.DenialGroupCount + 245, // 175: openshell.v1.PolicyChunk.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 237, // 176: openshell.v1.PolicyChunk.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 237, // 177: openshell.v1.PolicyChunk.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 174, // 178: openshell.v1.SubmitPolicyAnalysisRequest.summaries:type_name -> openshell.v1.DenialSummary + 177, // 179: openshell.v1.SubmitPolicyAnalysisRequest.proposed_chunks:type_name -> openshell.v1.PolicyChunk + 176, // 180: openshell.v1.SubmitPolicyAnalysisRequest.network_activity_summaries:type_name -> openshell.v1.NetworkActivitySummary + 240, // 181: openshell.v1.GetDraftPolicyRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 177, // 182: openshell.v1.GetDraftPolicyResponse.chunks:type_name -> openshell.v1.PolicyChunk + 240, // 183: openshell.v1.ApproveDraftChunkRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 184: openshell.v1.RejectDraftChunkRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 187, // 185: openshell.v1.ApproveAllDraftChunksRequest.approvals:type_name -> openshell.v1.DraftChunkApproval + 240, // 186: openshell.v1.ApproveAllDraftChunksRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 245, // 187: openshell.v1.EditDraftChunkRequest.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 240, // 188: openshell.v1.EditDraftChunkRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 189: openshell.v1.UndoDraftChunkRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 190: openshell.v1.ClearDraftChunksRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 240, // 191: openshell.v1.GetDraftHistoryRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 197, // 192: openshell.v1.GetDraftHistoryResponse.entries:type_name -> openshell.v1.DraftHistoryEntry + 235, // 193: openshell.v1.CreateWorkspaceRequest.labels:type_name -> openshell.v1.CreateWorkspaceRequest.LabelsEntry + 248, // 194: openshell.v1.CreateWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace + 248, // 195: openshell.v1.GetWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace + 248, // 196: openshell.v1.ListWorkspacesResponse.workspaces:type_name -> openshell.datamodel.v1.Workspace + 236, // 197: openshell.v1.WorkspaceMember.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 6, // 198: openshell.v1.WorkspaceMember.role:type_name -> openshell.v1.WorkspaceRole + 6, // 199: openshell.v1.AddWorkspaceMemberRequest.role:type_name -> openshell.v1.WorkspaceRole + 207, // 200: openshell.v1.AddWorkspaceMemberResponse.member:type_name -> openshell.v1.WorkspaceMember + 207, // 201: openshell.v1.ListWorkspaceMembersResponse.members:type_name -> openshell.v1.WorkspaceMember + 103, // 202: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry.value:type_name -> openshell.v1.ProviderProfileCredential + 131, // 203: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry.value:type_name -> openshell.v1.StaticCredentialBinding + 12, // 204: openshell.v1.OpenShell.Health:input_type -> openshell.v1.HealthRequest + 14, // 205: openshell.v1.OpenShell.GetCurrentUser:input_type -> openshell.v1.GetCurrentUserRequest + 16, // 206: openshell.v1.OpenShell.GetGatewayInfo:input_type -> openshell.v1.GetGatewayInfoRequest + 39, // 207: openshell.v1.OpenShell.CreateSandbox:input_type -> openshell.v1.CreateSandboxRequest + 47, // 208: openshell.v1.OpenShell.BeginRootfsTarStaging:input_type -> openshell.v1.BeginRootfsTarStagingRequest + 49, // 209: openshell.v1.OpenShell.GetSandbox:input_type -> openshell.v1.GetSandboxRequest + 50, // 210: openshell.v1.OpenShell.ListSandboxes:input_type -> openshell.v1.ListSandboxesRequest + 40, // 211: openshell.v1.OpenShell.CreateSandboxTemplate:input_type -> openshell.v1.CreateSandboxTemplateRequest + 41, // 212: openshell.v1.OpenShell.GetSandboxTemplate:input_type -> openshell.v1.GetSandboxTemplateRequest + 42, // 213: openshell.v1.OpenShell.ListSandboxTemplates:input_type -> openshell.v1.ListSandboxTemplatesRequest + 43, // 214: openshell.v1.OpenShell.DeleteSandboxTemplate:input_type -> openshell.v1.DeleteSandboxTemplateRequest + 51, // 215: openshell.v1.OpenShell.ListSandboxProviders:input_type -> openshell.v1.ListSandboxProvidersRequest + 52, // 216: openshell.v1.OpenShell.AttachSandboxProvider:input_type -> openshell.v1.AttachSandboxProviderRequest + 53, // 217: openshell.v1.OpenShell.DetachSandboxProvider:input_type -> openshell.v1.DetachSandboxProviderRequest + 54, // 218: openshell.v1.OpenShell.DeleteSandbox:input_type -> openshell.v1.DeleteSandboxRequest + 55, // 219: openshell.v1.OpenShell.StopSandbox:input_type -> openshell.v1.StopSandboxRequest + 56, // 220: openshell.v1.OpenShell.StartSandbox:input_type -> openshell.v1.StartSandboxRequest + 63, // 221: openshell.v1.OpenShell.CreateSshSession:input_type -> openshell.v1.CreateSshSessionRequest + 65, // 222: openshell.v1.OpenShell.ExposeService:input_type -> openshell.v1.ExposeServiceRequest + 66, // 223: openshell.v1.OpenShell.GetService:input_type -> openshell.v1.GetServiceRequest + 67, // 224: openshell.v1.OpenShell.ListServices:input_type -> openshell.v1.ListServicesRequest + 69, // 225: openshell.v1.OpenShell.DeleteService:input_type -> openshell.v1.DeleteServiceRequest + 73, // 226: openshell.v1.OpenShell.RevokeSshSession:input_type -> openshell.v1.RevokeSshSessionRequest + 75, // 227: openshell.v1.OpenShell.ExecSandbox:input_type -> openshell.v1.ExecSandboxRequest + 81, // 228: openshell.v1.OpenShell.ForwardTcp:input_type -> openshell.v1.TcpForwardFrame + 82, // 229: openshell.v1.OpenShell.ExecSandboxInteractive:input_type -> openshell.v1.ExecSandboxInput + 89, // 230: openshell.v1.OpenShell.CreateProvider:input_type -> openshell.v1.CreateProviderRequest + 90, // 231: openshell.v1.OpenShell.GetProvider:input_type -> openshell.v1.GetProviderRequest + 91, // 232: openshell.v1.OpenShell.ListProviders:input_type -> openshell.v1.ListProvidersRequest + 96, // 233: openshell.v1.OpenShell.ListProviderProfiles:input_type -> openshell.v1.ListProviderProfilesRequest + 97, // 234: openshell.v1.OpenShell.GetProviderProfile:input_type -> openshell.v1.GetProviderProfileRequest + 120, // 235: openshell.v1.OpenShell.ImportProviderProfiles:input_type -> openshell.v1.ImportProviderProfilesRequest + 122, // 236: openshell.v1.OpenShell.UpdateProviderProfiles:input_type -> openshell.v1.UpdateProviderProfilesRequest + 124, // 237: openshell.v1.OpenShell.LintProviderProfiles:input_type -> openshell.v1.LintProviderProfilesRequest + 92, // 238: openshell.v1.OpenShell.UpdateProvider:input_type -> openshell.v1.UpdateProviderRequest + 109, // 239: openshell.v1.OpenShell.GetProviderRefreshStatus:input_type -> openshell.v1.GetProviderRefreshStatusRequest + 111, // 240: openshell.v1.OpenShell.ConfigureProviderRefresh:input_type -> openshell.v1.ConfigureProviderRefreshRequest + 113, // 241: openshell.v1.OpenShell.RotateProviderCredential:input_type -> openshell.v1.RotateProviderCredentialRequest + 115, // 242: openshell.v1.OpenShell.DeleteProviderRefresh:input_type -> openshell.v1.DeleteProviderRefreshRequest + 93, // 243: openshell.v1.OpenShell.DeleteProvider:input_type -> openshell.v1.DeleteProviderRequest + 127, // 244: openshell.v1.OpenShell.DeleteProviderProfile:input_type -> openshell.v1.DeleteProviderProfileRequest + 249, // 245: openshell.v1.OpenShell.GetSandboxConfig:input_type -> openshell.sandbox.v1.GetSandboxConfigRequest + 250, // 246: openshell.v1.OpenShell.GetGatewayConfig:input_type -> openshell.sandbox.v1.GetGatewayConfigRequest + 135, // 247: openshell.v1.OpenShell.UpdateConfig:input_type -> openshell.v1.UpdateConfigRequest + 144, // 248: openshell.v1.OpenShell.GetSandboxPolicyStatus:input_type -> openshell.v1.GetSandboxPolicyStatusRequest + 146, // 249: openshell.v1.OpenShell.ListSandboxPolicies:input_type -> openshell.v1.ListSandboxPoliciesRequest + 148, // 250: openshell.v1.OpenShell.ReportPolicyStatus:input_type -> openshell.v1.ReportPolicyStatusRequest + 129, // 251: openshell.v1.OpenShell.GetSandboxProviderEnvironment:input_type -> openshell.v1.GetSandboxProviderEnvironmentRequest + 133, // 252: openshell.v1.OpenShell.ExchangeProviderSubjectToken:input_type -> openshell.v1.ExchangeProviderSubjectTokenRequest + 151, // 253: openshell.v1.OpenShell.GetSandboxLogs:input_type -> openshell.v1.GetSandboxLogsRequest + 152, // 254: openshell.v1.OpenShell.PushSandboxLogs:input_type -> openshell.v1.PushSandboxLogsRequest + 155, // 255: openshell.v1.OpenShell.ConnectSupervisor:input_type -> openshell.v1.SupervisorMessage + 162, // 256: openshell.v1.OpenShell.ReportMainProcessExit:input_type -> openshell.v1.ReportMainProcessExitRequest + 164, // 257: openshell.v1.OpenShell.FinalizeMainProcessExit:input_type -> openshell.v1.FinalizeMainProcessExitRequest + 170, // 258: openshell.v1.OpenShell.RelayStream:input_type -> openshell.v1.RelayFrame + 85, // 259: openshell.v1.OpenShell.WatchSandbox:input_type -> openshell.v1.WatchSandboxRequest + 179, // 260: openshell.v1.OpenShell.SubmitPolicyAnalysis:input_type -> openshell.v1.SubmitPolicyAnalysisRequest + 181, // 261: openshell.v1.OpenShell.GetDraftPolicy:input_type -> openshell.v1.GetDraftPolicyRequest + 183, // 262: openshell.v1.OpenShell.ApproveDraftChunk:input_type -> openshell.v1.ApproveDraftChunkRequest + 185, // 263: openshell.v1.OpenShell.RejectDraftChunk:input_type -> openshell.v1.RejectDraftChunkRequest + 188, // 264: openshell.v1.OpenShell.ApproveAllDraftChunks:input_type -> openshell.v1.ApproveAllDraftChunksRequest + 190, // 265: openshell.v1.OpenShell.EditDraftChunk:input_type -> openshell.v1.EditDraftChunkRequest + 192, // 266: openshell.v1.OpenShell.UndoDraftChunk:input_type -> openshell.v1.UndoDraftChunkRequest + 194, // 267: openshell.v1.OpenShell.ClearDraftChunks:input_type -> openshell.v1.ClearDraftChunksRequest + 196, // 268: openshell.v1.OpenShell.GetDraftHistory:input_type -> openshell.v1.GetDraftHistoryRequest + 8, // 269: openshell.v1.OpenShell.IssueSandboxToken:input_type -> openshell.v1.IssueSandboxTokenRequest + 10, // 270: openshell.v1.OpenShell.RefreshSandboxToken:input_type -> openshell.v1.RefreshSandboxTokenRequest + 199, // 271: openshell.v1.OpenShell.CreateWorkspace:input_type -> openshell.v1.CreateWorkspaceRequest + 201, // 272: openshell.v1.OpenShell.GetWorkspace:input_type -> openshell.v1.GetWorkspaceRequest + 203, // 273: openshell.v1.OpenShell.ListWorkspaces:input_type -> openshell.v1.ListWorkspacesRequest + 205, // 274: openshell.v1.OpenShell.DeleteWorkspace:input_type -> openshell.v1.DeleteWorkspaceRequest + 208, // 275: openshell.v1.OpenShell.AddWorkspaceMember:input_type -> openshell.v1.AddWorkspaceMemberRequest + 210, // 276: openshell.v1.OpenShell.RemoveWorkspaceMember:input_type -> openshell.v1.RemoveWorkspaceMemberRequest + 212, // 277: openshell.v1.OpenShell.ListWorkspaceMembers:input_type -> openshell.v1.ListWorkspaceMembersRequest + 13, // 278: openshell.v1.OpenShell.Health:output_type -> openshell.v1.HealthResponse + 15, // 279: openshell.v1.OpenShell.GetCurrentUser:output_type -> openshell.v1.GetCurrentUserResponse + 17, // 280: openshell.v1.OpenShell.GetGatewayInfo:output_type -> openshell.v1.GetGatewayInfoResponse + 57, // 281: openshell.v1.OpenShell.CreateSandbox:output_type -> openshell.v1.SandboxResponse + 48, // 282: openshell.v1.OpenShell.BeginRootfsTarStaging:output_type -> openshell.v1.BeginRootfsTarStagingResponse + 57, // 283: openshell.v1.OpenShell.GetSandbox:output_type -> openshell.v1.SandboxResponse + 58, // 284: openshell.v1.OpenShell.ListSandboxes:output_type -> openshell.v1.ListSandboxesResponse + 44, // 285: openshell.v1.OpenShell.CreateSandboxTemplate:output_type -> openshell.v1.SandboxTemplateResponse + 44, // 286: openshell.v1.OpenShell.GetSandboxTemplate:output_type -> openshell.v1.SandboxTemplateResponse + 45, // 287: openshell.v1.OpenShell.ListSandboxTemplates:output_type -> openshell.v1.ListSandboxTemplatesResponse + 46, // 288: openshell.v1.OpenShell.DeleteSandboxTemplate:output_type -> openshell.v1.DeleteSandboxTemplateResponse + 59, // 289: openshell.v1.OpenShell.ListSandboxProviders:output_type -> openshell.v1.ListSandboxProvidersResponse + 60, // 290: openshell.v1.OpenShell.AttachSandboxProvider:output_type -> openshell.v1.AttachSandboxProviderResponse + 61, // 291: openshell.v1.OpenShell.DetachSandboxProvider:output_type -> openshell.v1.DetachSandboxProviderResponse + 62, // 292: openshell.v1.OpenShell.DeleteSandbox:output_type -> openshell.v1.DeleteSandboxResponse + 57, // 293: openshell.v1.OpenShell.StopSandbox:output_type -> openshell.v1.SandboxResponse + 57, // 294: openshell.v1.OpenShell.StartSandbox:output_type -> openshell.v1.SandboxResponse + 64, // 295: openshell.v1.OpenShell.CreateSshSession:output_type -> openshell.v1.CreateSshSessionResponse + 72, // 296: openshell.v1.OpenShell.ExposeService:output_type -> openshell.v1.ServiceEndpointResponse + 72, // 297: openshell.v1.OpenShell.GetService:output_type -> openshell.v1.ServiceEndpointResponse + 68, // 298: openshell.v1.OpenShell.ListServices:output_type -> openshell.v1.ListServicesResponse + 70, // 299: openshell.v1.OpenShell.DeleteService:output_type -> openshell.v1.DeleteServiceResponse + 74, // 300: openshell.v1.OpenShell.RevokeSshSession:output_type -> openshell.v1.RevokeSshSessionResponse + 79, // 301: openshell.v1.OpenShell.ExecSandbox:output_type -> openshell.v1.ExecSandboxEvent + 81, // 302: openshell.v1.OpenShell.ForwardTcp:output_type -> openshell.v1.TcpForwardFrame + 79, // 303: openshell.v1.OpenShell.ExecSandboxInteractive:output_type -> openshell.v1.ExecSandboxEvent + 94, // 304: openshell.v1.OpenShell.CreateProvider:output_type -> openshell.v1.ProviderResponse + 94, // 305: openshell.v1.OpenShell.GetProvider:output_type -> openshell.v1.ProviderResponse + 95, // 306: openshell.v1.OpenShell.ListProviders:output_type -> openshell.v1.ListProvidersResponse + 119, // 307: openshell.v1.OpenShell.ListProviderProfiles:output_type -> openshell.v1.ListProviderProfilesResponse + 118, // 308: openshell.v1.OpenShell.GetProviderProfile:output_type -> openshell.v1.ProviderProfileResponse + 121, // 309: openshell.v1.OpenShell.ImportProviderProfiles:output_type -> openshell.v1.ImportProviderProfilesResponse + 123, // 310: openshell.v1.OpenShell.UpdateProviderProfiles:output_type -> openshell.v1.UpdateProviderProfilesResponse + 125, // 311: openshell.v1.OpenShell.LintProviderProfiles:output_type -> openshell.v1.LintProviderProfilesResponse + 94, // 312: openshell.v1.OpenShell.UpdateProvider:output_type -> openshell.v1.ProviderResponse + 110, // 313: openshell.v1.OpenShell.GetProviderRefreshStatus:output_type -> openshell.v1.GetProviderRefreshStatusResponse + 112, // 314: openshell.v1.OpenShell.ConfigureProviderRefresh:output_type -> openshell.v1.ConfigureProviderRefreshResponse + 114, // 315: openshell.v1.OpenShell.RotateProviderCredential:output_type -> openshell.v1.RotateProviderCredentialResponse + 116, // 316: openshell.v1.OpenShell.DeleteProviderRefresh:output_type -> openshell.v1.DeleteProviderRefreshResponse + 126, // 317: openshell.v1.OpenShell.DeleteProvider:output_type -> openshell.v1.DeleteProviderResponse + 128, // 318: openshell.v1.OpenShell.DeleteProviderProfile:output_type -> openshell.v1.DeleteProviderProfileResponse + 251, // 319: openshell.v1.OpenShell.GetSandboxConfig:output_type -> openshell.sandbox.v1.GetSandboxConfigResponse + 252, // 320: openshell.v1.OpenShell.GetGatewayConfig:output_type -> openshell.sandbox.v1.GetGatewayConfigResponse + 143, // 321: openshell.v1.OpenShell.UpdateConfig:output_type -> openshell.v1.UpdateConfigResponse + 145, // 322: openshell.v1.OpenShell.GetSandboxPolicyStatus:output_type -> openshell.v1.GetSandboxPolicyStatusResponse + 147, // 323: openshell.v1.OpenShell.ListSandboxPolicies:output_type -> openshell.v1.ListSandboxPoliciesResponse + 149, // 324: openshell.v1.OpenShell.ReportPolicyStatus:output_type -> openshell.v1.ReportPolicyStatusResponse + 132, // 325: openshell.v1.OpenShell.GetSandboxProviderEnvironment:output_type -> openshell.v1.GetSandboxProviderEnvironmentResponse + 134, // 326: openshell.v1.OpenShell.ExchangeProviderSubjectToken:output_type -> openshell.v1.ExchangeProviderSubjectTokenResponse + 154, // 327: openshell.v1.OpenShell.GetSandboxLogs:output_type -> openshell.v1.GetSandboxLogsResponse + 153, // 328: openshell.v1.OpenShell.PushSandboxLogs:output_type -> openshell.v1.PushSandboxLogsResponse + 156, // 329: openshell.v1.OpenShell.ConnectSupervisor:output_type -> openshell.v1.GatewayMessage + 163, // 330: openshell.v1.OpenShell.ReportMainProcessExit:output_type -> openshell.v1.ReportMainProcessExitResponse + 165, // 331: openshell.v1.OpenShell.FinalizeMainProcessExit:output_type -> openshell.v1.FinalizeMainProcessExitResponse + 170, // 332: openshell.v1.OpenShell.RelayStream:output_type -> openshell.v1.RelayFrame + 86, // 333: openshell.v1.OpenShell.WatchSandbox:output_type -> openshell.v1.SandboxStreamEvent + 180, // 334: openshell.v1.OpenShell.SubmitPolicyAnalysis:output_type -> openshell.v1.SubmitPolicyAnalysisResponse + 182, // 335: openshell.v1.OpenShell.GetDraftPolicy:output_type -> openshell.v1.GetDraftPolicyResponse + 184, // 336: openshell.v1.OpenShell.ApproveDraftChunk:output_type -> openshell.v1.ApproveDraftChunkResponse + 186, // 337: openshell.v1.OpenShell.RejectDraftChunk:output_type -> openshell.v1.RejectDraftChunkResponse + 189, // 338: openshell.v1.OpenShell.ApproveAllDraftChunks:output_type -> openshell.v1.ApproveAllDraftChunksResponse + 191, // 339: openshell.v1.OpenShell.EditDraftChunk:output_type -> openshell.v1.EditDraftChunkResponse + 193, // 340: openshell.v1.OpenShell.UndoDraftChunk:output_type -> openshell.v1.UndoDraftChunkResponse + 195, // 341: openshell.v1.OpenShell.ClearDraftChunks:output_type -> openshell.v1.ClearDraftChunksResponse + 198, // 342: openshell.v1.OpenShell.GetDraftHistory:output_type -> openshell.v1.GetDraftHistoryResponse + 9, // 343: openshell.v1.OpenShell.IssueSandboxToken:output_type -> openshell.v1.IssueSandboxTokenResponse + 11, // 344: openshell.v1.OpenShell.RefreshSandboxToken:output_type -> openshell.v1.RefreshSandboxTokenResponse + 200, // 345: openshell.v1.OpenShell.CreateWorkspace:output_type -> openshell.v1.CreateWorkspaceResponse + 202, // 346: openshell.v1.OpenShell.GetWorkspace:output_type -> openshell.v1.GetWorkspaceResponse + 204, // 347: openshell.v1.OpenShell.ListWorkspaces:output_type -> openshell.v1.ListWorkspacesResponse + 206, // 348: openshell.v1.OpenShell.DeleteWorkspace:output_type -> openshell.v1.DeleteWorkspaceResponse + 209, // 349: openshell.v1.OpenShell.AddWorkspaceMember:output_type -> openshell.v1.AddWorkspaceMemberResponse + 211, // 350: openshell.v1.OpenShell.RemoveWorkspaceMember:output_type -> openshell.v1.RemoveWorkspaceMemberResponse + 213, // 351: openshell.v1.OpenShell.ListWorkspaceMembers:output_type -> openshell.v1.ListWorkspaceMembersResponse + 278, // [278:352] is the sub-list for method output_type + 204, // [204:278] is the sub-list for method input_type + 204, // [204:204] is the sub-list for extension type_name + 204, // [204:204] is the sub-list for extension extendee + 0, // [0:204] is the sub-list for field type_name } func init() { file_openshell_proto_init() } diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index 322b1a092c..112bfdc5fe 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -190,9 +190,9 @@ await client.sandboxTemplates.list({ workspace: 'default', limit: 100 }) await client.sandboxTemplates.delete('python', { workspace: 'default' }) ``` -Use `allWorkspaces: true` on `list()` for a platform-admin view. The SDK clears -the workspace field in that request because the gateway treats `workspace` and -`allWorkspaces` as mutually exclusive. +Use `allWorkspaces: true` on `list()` for a platform-admin view. The +discriminated option type makes `workspace` and `allWorkspaces` mutually +exclusive. Omitting both options explicitly selects the `default` workspace. ## Surface and roadmap @@ -212,14 +212,24 @@ Curated methods are added deliberately, so some gateway RPCs are not yet wrapped `client.raw` is a generated client for every gateway RPC, including surface the curated sub-clients do not wrap yet (gateway config, provider CRUD, policy status, watch, logs, and the full observed `Sandbox`). `client.transport` is the shared connection, so extra clients reuse one socket. Generated request and response types live at `@nvidia/openshell-sdk/raw`. ```ts +import { create } from '@bufbuild/protobuf' import { OpenShellClient } from '@nvidia/openshell-sdk' +import { WorkspaceSelectorSchema } from '@nvidia/openshell-sdk/raw' import type { GetGatewayConfigResponse } from '@nvidia/openshell-sdk/raw' const client = await OpenShellClient.connect({ gateway, oidcToken }) // Reach RPCs the curated surface does not wrap yet: const cfg: GetGatewayConfigResponse = await client.raw.getGatewayConfig({}) -const status = await client.raw.getSandboxPolicyStatus({ name: 'my-sandbox', version: 0, global: false }) +const defaultWorkspace = create(WorkspaceSelectorSchema, { + selection: { case: 'workspace', value: 'default' }, +}) +const status = await client.raw.getSandboxPolicyStatus({ + name: 'my-sandbox', + version: 0, + global: false, + workspaceScope: defaultWorkspace, +}) ``` The raw layer returns the generated wire messages verbatim, preserving proto distinctions (an omitted optional versus an explicitly empty map) that the curated types may smooth over. As curated sub-clients land, prefer them; `raw` stays as the always-available floor. diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index 5b12a48e23..60cd5c3f0e 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -56,6 +56,19 @@ function readySandbox( const enc = (s: string) => new TextEncoder().encode(s); +type ScopedRequest = { + workspaceScope?: { selection?: { case?: string; value?: unknown } }; +}; + +function selectedWorkspace(req: ScopedRequest): string | undefined { + const selection = req.workspaceScope?.selection; + return selection?.case === 'workspace' && typeof selection.value === 'string' ? selection.value : undefined; +} + +function selectsAllWorkspaces(req: ScopedRequest): boolean { + return req.workspaceScope?.selection?.case === 'allWorkspaces'; +} + describe('exec / execStream', () => { it('resolves the id via get, frames tty:false, and buffers the result (backward compat)', async () => { let execReq: { sandboxId?: string; tty?: boolean; command?: string[] } = {}; @@ -276,7 +289,7 @@ describe('create', () => { let created: { workloadTemplateName?: string; name?: string; - workspace?: string; + workspaceScope?: ScopedRequest['workspaceScope']; labels?: Record; spec?: { policy?: { version?: number }; @@ -289,7 +302,7 @@ describe('create', () => { const sandbox = client({ createSandbox: (req) => { created = req; - return readySandbox('job-1', 'sb-id', 7n, undefined, req.workspace || 'default'); + return readySandbox('job-1', 'sb-id', 7n, undefined, selectedWorkspace(req) ?? 'default'); }, }); const ref = await sandbox.createFromTemplate({ @@ -305,7 +318,7 @@ describe('create', () => { expect(created.workloadTemplateName).toBe('gpu-kata'); expect(created.name).toBe('job-1'); - expect(created.workspace).toBe('staging'); + expect(selectedWorkspace(created)).toBe('staging'); expect(created.labels).toEqual({ team: 'runtime' }); expect(created.spec?.providers).toEqual(['github']); expect(created.spec?.command).toEqual(['/opt/worker', '--serve']); @@ -317,15 +330,15 @@ describe('create', () => { it('propagates workspace through sandbox lifecycle calls', async () => { const observed: { - create?: { workspace?: string }; - get?: { workspace?: string }; - list?: { workspace?: string; allWorkspaces?: boolean }; - delete?: { workspace?: string }; - attach?: { workspace?: string }; - detach?: { workspace?: string }; - listProviders?: { workspace?: string }; - updatePolicy?: { workspace?: string }; - updateSetting?: { workspace?: string }; + create?: ScopedRequest; + get?: ScopedRequest; + list?: ScopedRequest; + delete?: ScopedRequest; + attach?: ScopedRequest; + detach?: ScopedRequest; + listProviders?: ScopedRequest; + updatePolicy?: ScopedRequest; + updateSetting?: ScopedRequest; configGets: string[]; execGet?: string; interactiveGet?: string; @@ -335,16 +348,17 @@ describe('create', () => { const sandbox = client({ createSandbox: (req) => { observed.create = req; - return readySandbox(req.name || 'sb', 'sb-created', 7n, undefined, req.workspace || 'default'); + return readySandbox(req.name || 'sb', 'sb-created', 7n, undefined, selectedWorkspace(req) ?? 'default'); }, getSandbox: (req) => { - if (req.name === 'exec') observed.execGet = req.workspace; - else if (req.name === 'interactive') observed.interactiveGet = req.workspace; - else if (req.name === 'ssh') observed.sshGet = req.workspace; - else if (req.name === 'forward') observed.forwardGet = req.workspace; - else if (req.name === 'config') observed.configGets.push(req.workspace); + const workspace = selectedWorkspace(req); + if (req.name === 'exec') observed.execGet = workspace; + else if (req.name === 'interactive') observed.interactiveGet = workspace; + else if (req.name === 'ssh') observed.sshGet = workspace; + else if (req.name === 'forward') observed.forwardGet = workspace; + else if (req.name === 'config' && workspace) observed.configGets.push(workspace); else observed.get = req; - return readySandbox(req.name, `${req.name}-id`, 7n, undefined, req.workspace || 'default'); + return readySandbox(req.name, `${req.name}-id`, 7n, undefined, workspace ?? 'default'); }, listSandboxes: (req) => { observed.list = req; @@ -354,7 +368,7 @@ describe('create', () => { metadata: { id: 'listed-id', name: 'listed', - workspace: req.workspace || 'default', + workspace: selectedWorkspace(req) ?? 'default', labels: { team: 'aire' }, resourceVersion: 7n, }, @@ -370,14 +384,16 @@ describe('create', () => { attachSandboxProvider: (req) => { observed.attach = req; return { - sandbox: readySandbox(req.sandboxName, 'attach-id', 7n, undefined, req.workspace || 'default').sandbox, + sandbox: readySandbox(req.sandboxName, 'attach-id', 7n, undefined, selectedWorkspace(req) ?? 'default') + .sandbox, attached: true, }; }, detachSandboxProvider: (req) => { observed.detach = req; return { - sandbox: readySandbox(req.sandboxName, 'detach-id', 7n, undefined, req.workspace || 'default').sandbox, + sandbox: readySandbox(req.sandboxName, 'detach-id', 7n, undefined, selectedWorkspace(req) ?? 'default') + .sandbox, detached: true, }; }, @@ -451,19 +467,20 @@ describe('create', () => { expect(deleted).toBe(true); expect(attached.sandbox.workspace).toBe('staging'); expect(detached.sandbox.workspace).toBe('staging'); - expect(observed.create?.workspace).toBe('staging'); - expect(observed.get?.workspace).toBe('staging'); - expect(observed.list).toMatchObject({ workspace: 'staging', allWorkspaces: false }); - expect(observed.delete?.workspace).toBe('staging'); + expect(selectedWorkspace(observed.create ?? {})).toBe('staging'); + expect(selectedWorkspace(observed.get ?? {})).toBe('staging'); + expect(selectedWorkspace(observed.list ?? {})).toBe('staging'); + expect(selectsAllWorkspaces(observed.list ?? {})).toBe(false); + expect(selectedWorkspace(observed.delete ?? {})).toBe('staging'); expect(observed.execGet).toBe('staging'); expect(observed.interactiveGet).toBe('staging'); expect(observed.sshGet).toBe('staging'); - expect(observed.attach?.workspace).toBe('staging'); - expect(observed.detach?.workspace).toBe('staging'); - expect(observed.listProviders?.workspace).toBe('staging'); + expect(selectedWorkspace(observed.attach ?? {})).toBe('staging'); + expect(selectedWorkspace(observed.detach ?? {})).toBe('staging'); + expect(selectedWorkspace(observed.listProviders ?? {})).toBe('staging'); expect(observed.configGets).toContain('staging'); - expect(observed.updatePolicy?.workspace).toBe('staging'); - expect(observed.updateSetting?.workspace).toBe('staging'); + expect(selectedWorkspace(observed.updatePolicy ?? {})).toBe('staging'); + expect(selectedWorkspace(observed.updateSetting ?? {})).toBe('staging'); }); it('createFromTemplate rejects an empty template name locally', async () => { @@ -521,8 +538,7 @@ describe('create', () => { describe('sandbox templates', () => { it('create sends the template resource and workspace', async () => { - let observed: { - workspace?: string; + let observed: ScopedRequest & { template?: { metadata?: { name?: string; labels?: Record }; spec?: { @@ -544,7 +560,7 @@ describe('sandbox templates', () => { id: 'template-python', name: req.template?.metadata?.name ?? '', labels: req.template?.metadata?.labels ?? {}, - workspace: req.workspace, + workspace: selectedWorkspace(req), resourceVersion: 1n, }, spec: req.template?.spec, @@ -568,7 +584,7 @@ describe('sandbox templates', () => { { workspace: 'default' }, ); - expect(observed.workspace).toBe('default'); + expect(selectedWorkspace(observed)).toBe('default'); expect(observed.template?.metadata?.name).toBe('python'); expect(observed.template?.metadata?.labels).toEqual({ team: 'runtime' }); expect(observed.template?.spec?.workload?.environment).toEqual({ FEATURE_FLAG: 'on' }); @@ -579,16 +595,16 @@ describe('sandbox templates', () => { it('get list and delete forward workspace and pagination', async () => { const observed: { - get?: { name?: string; workspace?: string }; - list?: { limit?: number; offset?: number; workspace?: string; allWorkspaces?: boolean }; - delete?: { name?: string; workspace?: string }; + get?: ScopedRequest & { name?: string }; + list?: ScopedRequest & { limit?: number; offset?: number; labelSelector?: string }; + delete?: ScopedRequest & { name?: string }; } = {}; const templates = templateClient({ getSandboxTemplate: (req) => { observed.get = req; return { template: { - metadata: { id: 'template-gpu-kata', name: req.name, workspace: req.workspace }, + metadata: { id: 'template-gpu-kata', name: req.name, workspace: selectedWorkspace(req) }, spec: { workload: { image: 'img:v1' } }, }, }; @@ -598,7 +614,7 @@ describe('sandbox templates', () => { return { templates: [ { - metadata: { id: 'template-python', name: 'python', workspace: req.workspace || 'default' }, + metadata: { id: 'template-python', name: 'python', workspace: selectedWorkspace(req) ?? 'default' }, spec: { workload: { image: 'img:v1' } }, }, ], @@ -617,19 +633,21 @@ describe('sandbox templates', () => { expect(got.metadata?.name).toBe('gpu-kata'); expect(listed).toHaveLength(1); expect(deleted).toBe(true); - expect(observed.get).toMatchObject({ name: 'gpu-kata', workspace: 'staging' }); + expect(observed.get).toMatchObject({ name: 'gpu-kata' }); + expect(selectedWorkspace(observed.get ?? {})).toBe('staging'); expect(observed.list).toMatchObject({ limit: 10, offset: 2, - workspace: 'staging', - allWorkspaces: false, labelSelector: 'team=runtime', }); - expect(observed.delete).toMatchObject({ name: 'gpu-kata', workspace: 'staging' }); + expect(selectedWorkspace(observed.list ?? {})).toBe('staging'); + expect(selectsAllWorkspaces(observed.list ?? {})).toBe(false); + expect(observed.delete).toMatchObject({ name: 'gpu-kata' }); + expect(selectedWorkspace(observed.delete ?? {})).toBe('staging'); }); - it('list clears workspace when allWorkspaces is set', async () => { - let observed: { workspace?: string; allWorkspaces?: boolean } = {}; + it('list selects all workspaces explicitly', async () => { + let observed: ScopedRequest = {}; const templates = templateClient({ listSandboxTemplates: (req) => { observed = req; @@ -637,10 +655,10 @@ describe('sandbox templates', () => { }, }); - await templates.list({ workspace: 'staging', allWorkspaces: true }); + await templates.list({ allWorkspaces: true }); - expect(observed.workspace).toBe(''); - expect(observed.allWorkspaces).toBe(true); + expect(selectedWorkspace(observed)).toBeUndefined(); + expect(selectsAllWorkspaces(observed)).toBe(true); }); it('rejects empty names and missing template responses locally', async () => { diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index 4d1ff362ac..839a425e2b 100644 --- a/sdk/typescript/src/client.ts +++ b/sdk/typescript/src/client.ts @@ -16,7 +16,7 @@ import * as net from 'node:net'; import type { MessageInitShape } from '@bufbuild/protobuf'; import { type CallOptions, type Client, createClient, type Transport } from '@connectrpc/connect'; import { errorCode, fromConnect, SdkError } from './errors.js'; -import type { Provider } from './gen/datamodel_pb.js'; +import type { Provider, WorkspaceSelectorSchema } from './gen/datamodel_pb.js'; import type { Sandbox, SandboxWorkloadTemplate, UpdateConfigResponse } from './gen/openshell_pb.js'; import { type ExecSandboxInputSchema, @@ -86,7 +86,7 @@ export interface Health { export interface SandboxSpec { name?: string; - /** Workspace scope. Omit or use an empty string for the gateway default workspace. */ + /** Workspace name. Omit for `default`; empty strings are invalid. */ workspace?: string; image?: string; labels?: Record; @@ -115,7 +115,7 @@ export interface SandboxSpec { export interface SandboxFromTemplateSpec { name?: string; - /** Workspace scope. Omit or use an empty string for the gateway default workspace. */ + /** Workspace name. Omit for `default`; empty strings are invalid. */ workspace?: string; templateName: string; labels?: Record; @@ -149,36 +149,37 @@ export interface SandboxWorkloadTemplateProvenance { resourceVersion: string; } -export interface ListOptions { +interface PaginationOptions { limit?: number; offset?: number; labelSelector?: string; - /** Workspace scope. Omit or use an empty string for the gateway default workspace. */ - workspace?: string; - /** List across all workspaces. Requires platform admin permission. */ - allWorkspaces?: boolean; } +/** Mutually exclusive named/default or all-workspaces list scope. */ +export type WorkspaceListScope = + | { workspace?: string; allWorkspaces?: false | undefined } + | { workspace?: never; allWorkspaces: true }; + +export type ListOptions = PaginationOptions & WorkspaceListScope; + export interface SandboxWorkspaceOptions { - /** Workspace scope. Omit or use an empty string for the gateway default workspace. */ + /** Workspace name. Omit for `default`; empty strings are invalid. */ workspace?: string; } export type SandboxCallOptions = CallOptions & SandboxWorkspaceOptions; export interface SandboxTemplateWorkspaceOptions { - /** Workspace scope. Omit or use an empty string for the gateway default workspace. */ + /** Workspace name. Omit for `default`; empty strings are invalid. */ workspace?: string; } -export interface SandboxTemplateListOptions extends SandboxTemplateWorkspaceOptions { +export type SandboxTemplateListOptions = WorkspaceListScope & { limit?: number; offset?: number; /** Optional label selector in key=value comma-separated form. */ labelSelector?: string; - /** List templates across all workspaces. Requires platform admin permission. */ - allWorkspaces?: boolean; -} +}; export interface ExecOptions extends SandboxWorkspaceOptions { workdir?: string; @@ -491,8 +492,18 @@ function versionPin(value: string | undefined): bigint { const FORWARD_CHUNK = 64 * 1024; -function workspaceOption(options?: SandboxWorkspaceOptions | null): string { - return options?.workspace ?? ''; +function workspaceName(options?: SandboxWorkspaceOptions | null): string { + const workspace = options?.workspace ?? 'default'; + if (workspace.trim() === '') throw new SdkError('invalid_config', 'workspace must be non-empty'); + return workspace; +} + +function workspaceScope(options?: SandboxWorkspaceOptions | null): MessageInitShape { + return { selection: { case: 'workspace', value: workspaceName(options) } }; +} + +function listWorkspaceScope(options?: WorkspaceListScope | null): MessageInitShape { + return options?.allWorkspaces ? { selection: { case: 'allWorkspaces', value: {} } } : workspaceScope(options); } function requestCallOptions(options?: SandboxCallOptions | null): CallOptions | undefined { @@ -653,7 +664,7 @@ export class SandboxTemplateClient { try { const resp = await this.grpc.createSandboxTemplate({ template, - workspace: options?.workspace ?? '', + workspaceScope: workspaceScope(options), }); return sandboxTemplate(resp.template); } catch (e) { @@ -666,7 +677,7 @@ export class SandboxTemplateClient { try { const resp = await this.grpc.getSandboxTemplate({ name, - workspace: options?.workspace ?? '', + workspaceScope: workspaceScope(options), }); return sandboxTemplate(resp.template); } catch (e) { @@ -676,13 +687,11 @@ export class SandboxTemplateClient { async list(options?: SandboxTemplateListOptions | null): Promise { try { - const allWorkspaces = options?.allWorkspaces ?? false; const resp = await this.grpc.listSandboxTemplates({ limit: options?.limit ?? 0, offset: options?.offset ?? 0, - workspace: allWorkspaces ? '' : (options?.workspace ?? ''), - allWorkspaces, labelSelector: options?.labelSelector ?? '', + workspaceScope: listWorkspaceScope(options), }); return resp.templates; } catch (e) { @@ -695,7 +704,7 @@ export class SandboxTemplateClient { try { const resp = await this.grpc.deleteSandboxTemplate({ name, - workspace: options?.workspace ?? '', + workspaceScope: workspaceScope(options), }); return resp.deleted; } catch (e) { @@ -758,7 +767,7 @@ export class SandboxClient { const resp = await this.grpc.createSandbox({ name: spec.name ?? '', labels: spec.labels ?? {}, - workspace: spec.workspace ?? '', + workspaceScope: workspaceScope(spec), spec: specInit, }); return sandboxRef(resp.sandbox); @@ -773,7 +782,7 @@ export class SandboxClient { const resp = await this.grpc.createSandbox({ name: spec.name ?? '', labels: spec.labels ?? {}, - workspace: spec.workspace ?? '', + workspaceScope: workspaceScope(spec), spec: { providers: spec.providers ?? [], command: spec.command ?? [], @@ -791,7 +800,7 @@ export class SandboxClient { async get(name: string, options?: SandboxCallOptions | null): Promise { try { const resp = await this.grpc.getSandbox( - { name, workspace: workspaceOption(options) }, + { name, workspaceScope: workspaceScope(options) }, requestCallOptions(options), ); return sandboxRef(resp.sandbox); @@ -802,13 +811,11 @@ export class SandboxClient { async list(options?: ListOptions | null): Promise { try { - const allWorkspaces = options?.allWorkspaces ?? false; const resp = await this.grpc.listSandboxes({ limit: options?.limit ?? 0, offset: options?.offset ?? 0, labelSelector: options?.labelSelector ?? '', - workspace: allWorkspaces ? '' : (options?.workspace ?? ''), - allWorkspaces, + workspaceScope: listWorkspaceScope(options), }); return resp.sandboxes.map((s) => sandboxRef(s)); } catch (e) { @@ -818,7 +825,7 @@ export class SandboxClient { async delete(name: string, options?: SandboxWorkspaceOptions | null): Promise { try { - const resp = await this.grpc.deleteSandbox({ name, workspace: workspaceOption(options) }); + const resp = await this.grpc.deleteSandbox({ name, workspaceScope: workspaceScope(options) }); return resp.deleted; } catch (e) { throw fromConnect(e); @@ -1307,7 +1314,7 @@ export class SandboxClient { sandboxName: name, providerName: provider, expectedResourceVersion: versionPin(options?.expectedResourceVersion), - workspace: workspaceOption(options), + workspaceScope: workspaceScope(options), }); return { sandbox: sandboxRef(resp.sandbox), changed: resp.attached }; } catch (e) { @@ -1325,7 +1332,7 @@ export class SandboxClient { sandboxName: name, providerName: provider, expectedResourceVersion: versionPin(options?.expectedResourceVersion), - workspace: workspaceOption(options), + workspaceScope: workspaceScope(options), }); return { sandbox: sandboxRef(resp.sandbox), changed: resp.detached }; } catch (e) { @@ -1335,7 +1342,10 @@ export class SandboxClient { async listProviders(name: string, options?: SandboxWorkspaceOptions | null): Promise { try { - const resp = await this.grpc.listSandboxProviders({ sandboxName: name, workspace: workspaceOption(options) }); + const resp = await this.grpc.listSandboxProviders({ + sandboxName: name, + workspaceScope: workspaceScope(options), + }); return resp.providers.map((p) => providerRef(p)); } catch (e) { throw fromConnect(e); @@ -1367,7 +1377,7 @@ export class SandboxClient { policy, global: false, expectedResourceVersion: versionPin(options?.expectedResourceVersion), - workspace: workspaceOption(options), + workspaceScope: workspaceScope(options), }); const result = updateConfigResult(resp); if (options?.wait) @@ -1392,7 +1402,7 @@ export class SandboxClient { settingKey: key, settingValue: value, global: false, - workspace: workspaceOption(options), + workspaceScope: workspaceScope(options), }); return updateConfigResult(resp); } catch (e) { diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index 31571865be..5d02fe6b61 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -43,6 +43,7 @@ export type { SshSession, UpdateConfigResult, WaitOptions, + WorkspaceListScope, } from './client.js'; export { errorCode, OpenShellClient, SandboxClient, SandboxTemplateClient } from './client.js'; export type { SdkErrorCode } from './errors.js'; From 5643e1f905f36dbf7d1e922174aaf513919c2260 Mon Sep 17 00:00:00 2001 From: Shiju Date: Thu, 10 Sep 2026 20:40:38 +0000 Subject: [PATCH 02/12] fix(policy): normalize protocol names before OPA validation (#3251) * fix(supervisor): canonicalize L7 protocols before OPA Normalize recognized protocol spellings before supervisor validation and Rego authorization so mixed-case MCP policies cannot take the REST rule path. Reject null MCP configuration instead of silently defaulting it, and cover both behaviors with regression tests. Signed-off-by: Shiju * test(policy): cover normalization for every supported protocol Exercise TCP, REST, WebSocket, GraphQL, SQL, JSON-RPC and MCP through YAML and protobuf loading with lowercase, uppercase and mixed-case names. Assert canonical names in raw OPA data and returned L7 configuration, preserve TCP L4 behavior, and verify that normalization leaves unrelated data unchanged and is idempotent. Signed-off-by: Shiju --------- Signed-off-by: Shiju --- .../openshell-supervisor-network/src/opa.rs | 340 +++++++++++++++++- 1 file changed, 339 insertions(+), 1 deletion(-) diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index d2191f8ed3..d2ed593782 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -13,7 +13,7 @@ use openshell_core::policy::{ FilesystemPolicy, LandlockCompatibility, LandlockPolicy, ProcessPolicy, }; use openshell_core::proto::SandboxPolicy as ProtoSandboxPolicy; -use openshell_policy::L7ConfigStanza; +use openshell_policy::{L7ConfigStanza, L7Protocol as PolicyL7Protocol}; use openshell_supervisor_middleware::{ChainEntry, ChainRunner, MiddlewareRegistry}; use std::path::{Path, PathBuf}; use std::sync::{ @@ -446,6 +446,7 @@ impl OpaEngine { let mut data: serde_json::Value = serde_json::from_str(&data_json_str) .map_err(|e| miette::miette!("internal: failed to parse proto JSON: {e}"))?; inject_runtime_policy_data(&mut data, require_binary_identity); + normalize_endpoint_protocols(&mut data); // Validate BEFORE expanding presets let (errors, warnings) = crate::l7::validate_l7_policies(&data); @@ -1387,6 +1388,7 @@ fn preprocess_yaml_data( let mut data: serde_json::Value = serde_yml::from_str(yaml_str) .map_err(|e| miette::miette!("failed to parse YAML data: {e}"))?; inject_runtime_policy_data(&mut data, require_binary_identity); + normalize_endpoint_protocols(&mut data); // Normalize port → ports for all endpoints so Rego always sees "ports" array. normalize_endpoint_ports(&mut data); @@ -1436,6 +1438,57 @@ fn preprocess_yaml_data( serde_json::to_string(&data).map_err(|e| miette::miette!("failed to serialize data: {e}")) } +/// Canonicalize recognized protocol spellings before L7 validation or Rego use. +/// +/// Rust parses protocol names case-insensitively, while Rego compares stable +/// wire keys. Publishing one canonical spelling keeps rule validation, typed +/// routing, and authorization on the same protocol branch. +fn normalize_endpoint_protocols(data: &mut serde_json::Value) { + let Some(policies) = data + .get_mut("network_policies") + .and_then(serde_json::Value::as_object_mut) + else { + return; + }; + + for policy in policies.values_mut() { + let Some(endpoints) = policy + .get_mut("endpoints") + .and_then(serde_json::Value::as_array_mut) + else { + continue; + }; + + for endpoint in endpoints { + let Some(endpoint) = endpoint.as_object_mut() else { + continue; + }; + let Some(protocol) = endpoint.get("protocol").and_then(serde_json::Value::as_str) + else { + continue; + }; + let canonical = if protocol.eq_ignore_ascii_case("tcp") { + Some("tcp") + } else { + PolicyL7Protocol::parse(protocol).map(|protocol| match protocol { + PolicyL7Protocol::Rest => "rest", + PolicyL7Protocol::Websocket => "websocket", + PolicyL7Protocol::Graphql => "graphql", + PolicyL7Protocol::Sql => "sql", + PolicyL7Protocol::JsonRpc => "json-rpc", + PolicyL7Protocol::Mcp => "mcp", + }) + }; + if let Some(canonical) = canonical { + endpoint.insert( + "protocol".to_string(), + serde_json::Value::String(canonical.to_string()), + ); + } + } + } +} + /// Normalize endpoint port/ports in JSON data. /// /// YAML policies may use `port: N` (single) or `ports: [N, M]` (multi). @@ -1547,6 +1600,9 @@ fn normalize_l7_config_alias( }; if config.is_null() { ep.remove(key); + if stanza == L7ConfigStanza::Mcp { + errors.push(format!("{loc}.{key}: mcp config must be an object")); + } return; } match openshell_policy::l7_config_alias_runtime_fields(stanza, config) { @@ -5026,6 +5082,199 @@ network_policies: ); } + const PROTOCOL_NAME_CASES: [(&str, &str); 7] = [ + ("tcp", "TcP"), + ("rest", "ReSt"), + ("websocket", "WeBsOcKeT"), + ("graphql", "GrApHqL"), + ("sql", "SqL"), + ("json-rpc", "JsOn-RpC"), + ("mcp", "McP"), + ]; + + fn assert_loaded_protocol_name(engine: &OpaEngine, authored: &str, canonical: &str) { + // Inspect stored data before typed parsing, which accepts mixed case and + // would otherwise hide a missing normalization step in either loader. + let data = engine.engine.lock().expect("OPA engine lock").get_data(); + assert_eq!( + data["network_policies"]["protocol_names"]["endpoints"][0]["protocol"], + regorus::Value::from(canonical), + "stored protocol for {authored}" + ); + + let input = NetworkInput { + host: "protocol.example.com".into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/curl"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let config = engine + .query_endpoint_config(&input) + .expect("endpoint query"); + if canonical == "tcp" { + // TCP remains an L4 endpoint; canonical spelling must not opt it + // into request inspection or change its network-level allowance. + assert!(config.is_none(), "TCP must not return L7 configuration"); + assert!(matches!( + engine + .evaluate_network_action(&input) + .expect("network query"), + NetworkAction::Allow { .. } + )); + } else { + let config = config.expect("L7 endpoint configuration"); + assert_eq!( + config["protocol"], + regorus::Value::from(canonical), + "published endpoint protocol for {authored}" + ); + crate::l7::parse_l7_config(&config).expect("valid typed L7 configuration"); + } + } + + #[test] + fn protocol_names_yaml_load_canonicalizes_all_supported_values() { + for (canonical, mixed_case) in PROTOCOL_NAME_CASES { + let fields = match canonical { + "tcp" => "", + "rest" | "websocket" => { + "enforcement: enforce\n rules: [{allow: {method: GET, path: /status}}]" + } + "graphql" => { + "enforcement: enforce\n rules: [{allow: {operation_type: query, fields: [viewer]}}]" + } + // SQL inspection supports audit mode, not enforce mode. + "sql" => "enforcement: audit\n rules: [{allow: {command: SELECT}}]", + "json-rpc" => "enforcement: enforce\n rules: [{allow: {method: status}}]", + "mcp" => "enforcement: enforce\n rules: [{allow: {method: tools/list}}]", + _ => unreachable!("fixture must name a supported protocol"), + }; + for authored in [ + canonical.to_string(), + canonical.to_ascii_uppercase(), + mixed_case.into(), + ] { + let yaml = format!( + r#" +network_policies: + protocol_names: + name: protocol_names + endpoints: + - host: protocol.example.com + port: 443 + protocol: {authored} + {fields} + binaries: + - {{ path: /usr/bin/curl }} +"# + ); + let engine = OpaEngine::from_strings(TEST_POLICY, &yaml) + .unwrap_or_else(|error| panic!("valid YAML protocol {authored}: {error}")); + assert_loaded_protocol_name(&engine, &authored, canonical); + } + } + } + + #[test] + fn protocol_names_proto_load_canonicalizes_all_supported_values() { + for (canonical, mixed_case) in PROTOCOL_NAME_CASES { + let allow = match canonical { + "tcp" => None, + "rest" | "websocket" => Some(L7Allow { + method: "GET".into(), + path: "/status".into(), + ..Default::default() + }), + "graphql" => Some(L7Allow { + operation_type: "query".into(), + fields: vec!["viewer".into()], + ..Default::default() + }), + "sql" => Some(L7Allow { + command: "SELECT".into(), + ..Default::default() + }), + "json-rpc" | "mcp" => Some(L7Allow { + method: if canonical == "mcp" { + "tools/list" + } else { + "status" + } + .into(), + ..Default::default() + }), + _ => unreachable!("fixture must name a supported protocol"), + }; + for authored in [ + canonical.to_string(), + canonical.to_ascii_uppercase(), + mixed_case.into(), + ] { + let mut policy = openshell_policy::restrictive_default_policy(); + policy.network_policies.insert( + "protocol_names".into(), + NetworkPolicyRule { + name: "protocol_names".into(), + endpoints: vec![NetworkEndpoint { + host: "protocol.example.com".into(), + port: 443, + protocol: authored.clone(), + // TCP has no L7 settings; SQL only supports audit. + enforcement: match canonical { + "tcp" => "", + "sql" => "audit", + _ => "enforce", + } + .into(), + rules: allow + .clone() + .map(|allow| L7Rule { allow: Some(allow) }) + .into_iter() + .collect(), + ..Default::default() + }], + binaries: vec![NetworkBinary { + path: "/usr/bin/curl".into(), + ..Default::default() + }], + }, + ); + let engine = OpaEngine::from_proto(&policy) + .unwrap_or_else(|error| panic!("valid protobuf protocol {authored}: {error}")); + assert_loaded_protocol_name(&engine, &authored, canonical); + } + } + } + + #[test] + fn protocol_names_normalization_preserves_other_data_and_is_idempotent() { + let mut data = serde_json::json!({ + "network_policies": { + "first": { + "endpoints": [ + {"protocol": "ReSt", "path": "/KeepCase", "host": "KeepCase.example"}, + {"protocol": "FutureProtocol"}, + {"protocol": ""}, + {"protocol": null}, + {"protocol": 42}, + {"host": "no-protocol.example"} + ] + }, + "second": {"endpoints": [{"protocol": "JsOn-RpC"}]} + } + }); + let mut expected = data.clone(); + expected["network_policies"]["first"]["endpoints"][0]["protocol"] = "rest".into(); + expected["network_policies"]["second"]["endpoints"][0]["protocol"] = "json-rpc".into(); + + normalize_endpoint_protocols(&mut data); + assert_eq!(data, expected, "only recognized protocol names may change"); + normalize_endpoint_protocols(&mut data); + assert_eq!(data, expected, "normalization must be idempotent"); + } + #[test] fn yaml_load_accepts_mixed_case_mcp_protocol_with_default_versions() { let data = r#" @@ -5057,7 +5306,55 @@ network_policies: .expect("expected MCP endpoint config"); let l7 = crate::l7::parse_l7_config(&config).expect("parse L7 endpoint config"); + let config_json: serde_json::Value = serde_json::from_str( + &config + .to_json_str() + .expect("endpoint config must serialize as JSON"), + ) + .expect("endpoint config must be valid JSON"); + assert_eq!( + config_json["protocol"], + serde_json::json!("mcp"), + "OPA data must use the canonical protocol key" + ); assert_eq!(l7.mcp_versions, vec![DEFAULT_MCP_PROTOCOL_VERSION]); + assert!(eval_l7( + &engine, + &l7_jsonrpc_input("mcp.example.com", 443, "/", "tools/list") + )); + assert!(!eval_l7( + &engine, + &l7_jsonrpc_input("mcp.example.com", 443, "/", "tools/call") + )); + } + + #[test] + fn yaml_load_rejects_rest_shaped_rules_on_mixed_case_mcp_protocol() { + let data = r#" +network_policies: + mcp: + name: mcp + endpoints: + - host: mcp.example.com + port: 443 + protocol: MCP + rules: + - allow: + method: POST + path: "**" + binaries: + - { path: /usr/bin/curl } +"#; + + let Err(error) = OpaEngine::from_strings(TEST_POLICY, data) else { + panic!("mixed-case MCP must not bypass MCP rule validation"); + }; + assert!( + error + .to_string() + .contains("mcp L7 rules must use method/tool, not path/query"), + "{error}" + ); } #[test] @@ -5128,6 +5425,40 @@ network_policies: ); } + #[test] + fn yaml_load_rejects_null_mcp_config_before_defaulting() { + for mcp_fields in [ + "mcp: null", + "mcp: null\n mcp_versions: [\"2025-11-25\"]", + ] { + let data = format!( + r#" +network_policies: + mcp: + name: mcp + endpoints: + - host: mcp.example.com + port: 443 + protocol: mcp + {mcp_fields} + rules: + - allow: + method: tools/list + binaries: + - {{ path: /usr/bin/curl }} +"# + ); + + let Err(error) = OpaEngine::from_strings(TEST_POLICY, &data) else { + panic!("null MCP config must reject activation"); + }; + assert!( + error.to_string().contains("mcp config must be an object"), + "{error}" + ); + } + } + #[test] fn yaml_load_rejects_mcp_versions_on_non_mcp_protocols() { for mcp_fields in [ @@ -5607,6 +5938,13 @@ network_policies: .query_endpoint_config(&input) .expect("query endpoint config") .expect("expected MCP endpoint config"); + let config_json: serde_json::Value = serde_json::from_str( + &config + .to_json_str() + .expect("endpoint config must serialize as JSON"), + ) + .expect("endpoint config must be valid JSON"); + assert_eq!(config_json["protocol"], serde_json::json!("mcp")); let l7 = crate::l7::parse_l7_config(&config).expect("parse L7 endpoint config"); assert_eq!( l7.mcp_versions, From e61adb3b1fa19c696c75d9ccf20f9d693de880cf Mon Sep 17 00:00:00 2001 From: Jordan Ganoff Date: Thu, 10 Sep 2026 14:50:43 -0700 Subject: [PATCH 03/12] rfc-0012: Isolation Backend interface (#2048) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * docs(rfc): RFC 0012 Isolation Backend interface Introduces RFC 0012, the runtime-selectable Isolation Backend contract: a pluggable component that establishes and enforces an agent's isolation boundary across network, filesystem, syscall, and identity, while the supervisor stays the policy authority (proxy, policy, audit) and the agent's only egress. Includes the supporting topology matrix and codebase-grounding notes. Signed-off-by: Jordan Ganoff * docs(rfc): complete RFC 0012 contract detail and corrections Tighten RFC 0012 for review without changing its structure or tone: - Remove the undefined `BoundaryIntent` from `attach`, and state that `claim` is the only transition that binds sandbox identity, policy, agent, and resources; an attached boundary holds no claimed or untrusted workload. - Add the runtime interface definitions (`BoundaryExec`/`ExecSession`, `BoundaryPortForward`, `EventSource`) and their semantics: owned distinct stdio, PTY resize, placement-neutral exit and signals, stable repeated `wait`, validated loopback targets, and single-consumer events. - Make boundary confirmation mandatory (`MUST`) and lifetime-long, and state retry, termination, and cleanup semantics (only attach is auto-retryable; a lost `start_agent` returns the existing process; descendants are owned; `wait_terminated` and an idempotent `shutdown`). - Require trusted admission to supply the expected backend id, contract version, policy digest, and capabilities that a backend cannot lower; add the no-silent-weakening policy invariant; mark `VerifiedBoundaryDescriptor` privately constructed and distinguish envelope from contract version; make `ResourceBinding` driver-issued, bound, and non-wideable. - Make the rollout executable and forbid a silent default backend. topology-matrix: rename "sidecar proxy" to sidecar-assisted (the proxy stays with the supervisor), frame sidecar and node as composite backends, move the single-pod outer sandbox to the shared-kernel cell, and note a node enforcer alone is not `restricted`-compatible. codebase-grounding: re-pin anchors to the RFC's parent ba21bb32 (driver.rs and proxy.rs line numbers refreshed) and add a permalink base; correct the event wording so a denial carries `Evidence` plus request-specific L7 data. Set state: review and link PR #2048. Signed-off-by: Jordan Ganoff * docs(rfc): RFC 0012 cleanup Contract completion: add MediationIngress/MediatedConnection so the proxy receives connections placement-neutrally; complete the runtime types (BoundaryExitStatus/BoundarySignal, BoundaryTerminal::resize, IdentitySource Send+Sync) and a machine-readable BackendErrorKind; name the AdmittedBoundary- Requirements admission block retained by VerifiedBoundaryDescriptor; show claim_id/generation in ClaimContext; require a canonical bounded descriptor encoding; define capability comparison. Mark MediationIngress, the admission block, and claim generation as contract additions the in-pod POC does not yet implement. Security semantics: make confirmation mandatory and lifetime-long, but correct the enforcement model: Landlock/seccomp are monotonic while netns/nftables are mutable, so require the mutation authority fenced from the workload, atomic default-deny updates, and fail-closed on lease loss rather than calling the boundary irreversible. "Confirms effective enforcement", not "reads rules back". Bind Attested identity to sandbox and claim id/generation. Tighten the execution-domain invariant (admission-visible named capability + audit, whole descendant trees). Distinguish structural pre-Running ordering from dynamic post-termination rejection; note adoption must remove legacy bypass paths. Lifecycle: drop the "establishes before supervisor boot" contradiction; add shutdown to the supervisor sequence; rewrite the in-pod migration appendix (policy-free attach, netns/rules at claim/bind, agent().wait(), wait_terminated, idempotent shutdown). The RFC is implemented only after the in-pod backend passes its release gates. Topology: narrow node-enforcer claims to "network-setup capabilities off the pod"; nuance NetworkPolicy (coarse L3/L4 defense in depth, not a proxy replacement); drop the proxy-policy-reprograms-boundary claim; label the containment table a kernel-compromise ceiling. Grounding: re-pin to the RFC's parent a5161d0 (process.rs and proxy.rs line numbers refreshed; others unchanged and reverified). Signed-off-by: Jordan Ganoff * docs(rfc): simplify isolation backend contract This removes a lot of detail to keep the RFC succinct. * removed POC and intermediate stage references The RFC should describe the end state, and not intermediate milestones or POCs. * revised based on feedback: - Introduced topology nomenclature to align with how we've been talking about this in other conversations - Simplified the explanation in the proposal section - Clarified binary identity - Simplified the initial contract to require the minimal interface necessary to satisfy all known topologies - Confirmed this will work with the proposed mxc (RFC 0013) proposal * docs(rfc): update RFC 0012 supporting docs for sidecar topology - Repin codebase-grounding.md to 8eacb477 (sidecar supervisor topology, #2076); update capabilities line numbers (1534→2538, 1540→2544), init container line numbers (191→423, 993→1506, 1185→2113), and remove the stale "no native sidecars today" claim. Add openshell-network-init and openshell-supervisor-network sidecar entries and expand the rg pattern. - Add Implementation column to topology-matrix.md; mark Co-located/in-pod and Same-pod composite as implemented (original topology and #2076 respectively); remaining patterns noted as proposed. Signed-off-by: Jordan Ganoff * docs(rfc): fully reground RFC 0012 codebase references to 8eacb477 All line numbers and function names verified against the post-sidecar state of the codebase (commit 8eacb477, #2076). Changes: - process.rs: ProcessHandle::spawn 440→527, netns param 446→535; drop_privileges call sites 603/700→710/812, enforcement 613/705→721/818-819; enter_netns_and_sandbox now documented at ssh.rs:1245 - CLONE_NEWNET call sites: process.rs:589→695, ssh.rs:619/1186→653/1262, supervisor_session.rs:610→735, netns/mod.rs:363→342 (226 unchanged) - CLONE_NEWNS: was one unshare at :393; now unshare at :449 and a new setns at :480 added for sidecar mount-namespace entry - nft fail-open: line 264→265, return Ok(()) range 272-277→277; note that the sidecar path (netns/mod.rs:477) requires nft and returns an error if absent, fixing the invariant bug for the sidecar topology - nft_ruleset.rs: policy accept 41→53; accept rules 43-49→56-92; reject rules now at 106+ - VM driver MASQUERADE: runtime.rs:417/436→418/437 - Agent command: main.rs:331→601; sleep infinity driver.rs:1886→2937, clarify it is set via SANDBOX_COMMAND env var - OPA evaluation: proxy.rs:1611 / evaluate_opa_tcp renamed to authorize_egress_intent at proxy.rs:1955; NetworkInput built at :2032 - openshell.proto: clarify no lifecycle Attach; note AttachSandboxProvider (provider record attachment, not isolation lifecycle) - README.md appendix: update pinned commit reference a5161d0→8eacb477 Signed-off-by: Jordan Ganoff * docs(rfc): address feedback and clean ups Signed-off-by: Jordan Ganoff * docs(rfc): preserve binary identity semantics Keep RFC 0012 focused on placing binary-aware enforcement behind the Isolation Backend contract instead of requiring a new connection-initiation capture mechanism. Define identity as trusted resolution for an accepted connection before policy evaluation, retain fail-closed attribution requirements, and document the current authorization-time procfs behavior. This preserves RFC 0002's binary gating baseline while allowing future backends to provide stronger identity resolution without changing the contract. Signed-off-by: Jordan Ganoff * docs(rfc): simplify isolation backend proposal Addresses PR feedback: Removed the implementation plan and codebase grounding, renamed the forwarding primitive to BoundaryLoopbackConnector, and clarified that conformance tests exercise the deployed topology, including delegated components and their transport. --------- Signed-off-by: Jordan Ganoff --- rfc/0012-isolation-backend/README.md | 383 ++++++++++++++++++ rfc/0012-isolation-backend/topology-matrix.md | 36 ++ 2 files changed, 419 insertions(+) create mode 100644 rfc/0012-isolation-backend/README.md create mode 100644 rfc/0012-isolation-backend/topology-matrix.md diff --git a/rfc/0012-isolation-backend/README.md b/rfc/0012-isolation-backend/README.md new file mode 100644 index 0000000000..a074292794 --- /dev/null +++ b/rfc/0012-isolation-backend/README.md @@ -0,0 +1,383 @@ +--- +authors: + - "@jganoff" +state: review +links: + - https://github.com/NVIDIA/OpenShell/issues/1737 + - https://github.com/NVIDIA/OpenShell/pull/2048 + - https://github.com/NVIDIA/OpenShell/issues/899 + - https://github.com/NVIDIA/OpenShell/issues/981 + - https://github.com/NVIDIA/OpenShell/issues/1511 + - https://github.com/NVIDIA/OpenShell/issues/1650 + - https://github.com/NVIDIA/OpenShell/issues/1680 + - https://github.com/NVIDIA/OpenShell/pull/2606 +--- + +# RFC 0012 - Isolation Backend Interface + +## Summary + +Today the supervisor both builds the workload's isolation boundary and applies its network policy. Because the supervisor runs inside the agent container, the privilege needed to build that boundary sits beside the code it confines. This RFC moves boundary construction and process operations behind a pluggable **Isolation Backend**. The supervisor continues to apply approved network policy through network mediation. + +The compute driver provisions the workload and trusted components. The logical supervisor is the trusted bridge between the gateway and the workload: it maintains the gateway connection, handles authorized requests, and drives the backend. The backend establishes the isolation controls, manages workload processes, and routes egress to network mediation. The same lifecycle supports today's in-pod implementation and future delegated implementations without topology-specific supervisor paths. + +## Motivation + +Boundary construction is embedded in the supervisor, so moving it anywhere else means changing the supervisor. That placement creates three problems: + +- A compromise reaches the boundary-building privilege in the same container. +- Building the boundary inside the agent container requires capabilities that conflict with restricted deployments. Delegating construction removes that requirement but does not guarantee Pod Security Standards compliance. See #899 for background. +- Each new placement adds another branch to the supervisor. + +All three come from coupling boundary construction to boundary operation. A common interface lets deployments move privilege without changing the supervisor. + +## Non-goals + +- **Implementing a delegated backend.** Each topology requires its own design and implementation. +- **Changing authorization.** [RFC 0001](../0001-core-architecture/README.md) owns control-plane and sandbox identity. A delegated backend must still authenticate callers and scope them to one boundary. +- **Standardizing backend-internal component coordination.** A backend may coordinate helper, sidecar, or interception processes behind one lifecycle; how those components cooperate is backend-specific, not contract surface. +- **Changing gateway lifecycle or public status.** This RFC adds no gateway activation operation, public phase, or status API, and it does not define how a boundary's effective isolation model is surfaced to operators. + +## Proposal + +The mental model has three roles: + +- The **compute driver** provisions the sandbox instance according to the selected placement of the workload and trusted isolation components. That placement is the **topology**. +- The **Isolation Backend** establishes and operates the topology-specific controls around the workload. It also routes workload egress to network mediation and provides process operations. +- The **logical supervisor** is the trusted control-plane bridge between the gateway and the workload. It drives the backend, handles authorized gateway requests, and applies approved network policy through network mediation. + +Together, network policy, filesystem isolation, syscall filtering, and sandbox identity form the workload's isolation boundary. The roles above enforce that boundary and may run in one process or across several trusted components. Their placement does not change the contract. + +Each active boundary has at most one logical supervisor, which may span multiple coupled processes. The backend routes all workload egress through a per-boundary source, and the supervisor consumes that source. Internal delegation and transport remain topology-private. + +[RFC 0001](../0001-core-architecture/README.md) continues to own sandbox authentication and authorization. In this contract, sandbox identity means binding the authenticated sandbox context to the isolation boundary. + +Admission selects the sandbox's topology and determines its trusted context. The compute driver sets up the topology and gives the logical supervisor a `TopologyDescriptor` describing what it provisioned. The supervisor uses the descriptor to attach the matching Isolation Backend. The backend prepares the required controls before the agent starts. + +```mermaid +flowchart TB + Gateway["Gateway"] -->|"create sandbox"| Driver["Compute driver"] + + subgraph Topology["Driver-provisioned topology (placement varies)"] + Supervisor["Supervisor"] + Backend["Isolation Backend (may coordinate components)"] + subgraph Boundary["Isolation boundary"] + Mediator["Network mediation"] + subgraph Execution["Workload execution environment"] + Workload["Workload"] + end + end + + Supervisor -->|"drives contract"| Backend + Backend -->|"establishes and confirms"| Boundary + Backend -.->|"routes all workload egress to"| Mediator + Supervisor -.->|"applies network policy through"| Mediator + Backend -->|"after Ready: makes admitted agent runnable"| Workload + Workload ==>|"only egress"| Mediator + end + + Driver -->|"resources + TopologyDescriptor"| Supervisor + Mediator -->|"allowed egress"| Egress["Egress"] +``` + +In the in-pod topology, the supervisor drives a backend implemented in the same process. Other topologies may delegate backend operations without changing the supervisor lifecycle. + +A boundary is active from successful `attach` until normal backend cleanup releases the binding or the topology's trusted cleanup path invalidates it. A backend may coordinate multiple trusted helper or interception processes for that boundary. The backend owns the active-boundary binding; the compute driver owns the sandbox instance and topology lifecycle. + +### Contract invariants + +Six invariants hold for every boundary: + +1. Workload egress is denied except through network mediation for the boundary's lifetime. +2. No untrusted instruction executes until every admitted control applicable to that process is in force. +3. An operation is authorized only when the complete effective policy permits it; network operations are decided through network mediation. There is no silent weakening. +4. Agent startup, `exec`, and forwarding occur only through the active backend, and every workload process remains in the compute driver's provisioned execution environment. +5. Shared infrastructure preserves strict per-boundary lifecycle, policy, identity, enforcement, and cleanup isolation. +6. If the logical supervisor is lost, the boundary remains under its last confirmed enforcement state while supervisor-dependent operations fail closed. Loss of required enforcement ends `Running` and terminates all workload processes within a documented bound; detection and termination may be performed by a trusted node or control-plane actor. Network-mediation unavailability denies outbound connections and never enables direct egress. + +Each backend states its termination bound in its implementation documentation. Loss of the logical supervisor means loss of the components holding the backend lifecycle, not loss of the gateway connection; gateway disconnection follows RFC 0001's reconnection semantics. + +### Provisioning + +Provisioning runs on the control plane, and three rules hold in every topology: + +1. **Admission selects the topology** from trusted deployment configuration, not `SandboxPolicy`, and records its required backend. The `TopologyDescriptor` supplied by the compute driver must name that backend, and resolution never falls back to another backend. +2. **The compute driver provisions the topology** and anything the selected backend needs. +3. **The backend establishes standing enforcement before untrusted code runs**, during provisioning or `attach`, depending on the backend. + +If a topology depends on cluster-scoped coverage or registration, admission verifies that the prerequisite covers the boundary's placement before untrusted code runs. + +Every topology provides a trusted cleanup path that does not depend on logical-supervisor availability. + +A compute driver may provision a resource and `TopologyDescriptor` before the control plane assigns it to a sandbox. No untrusted workload runs while the resource is unassigned. After claim or assignment produces a trusted `SandboxContext`, the supervisor calls `attach`; the backend either binds that context to the prepared resource and returns `Bound`, or rejects it as incompatible. Pool creation, claim, reset, release, and recycling remain outside this contract. + +### The topology descriptor + +The driver supplies a descriptor for every provisioned topology, including in-pod and resources prepared before assignment. The common envelope names the backend and carries an opaque payload. + +```rust +struct TopologyDescriptor { + backend_name: String, + version: u32, + payload: Vec, +} +``` + +`version` is the Isolation Backend interface version. Backend name and version match exactly; this contract does not negotiate compatibility ranges. The descriptor is transport-neutral. Provisioning supplies it to the supervisor before `attach`; how it is transported is topology-specific and outside this contract, and every transport preserves one property: workload-controlled input cannot select or modify the descriptor. + +The opaque payload identifies, or gives the backend enough information to resolve, the exact driver-provisioned resource. It may also carry topology-specific endpoint or helper-role information; there are no common topology or role fields. + +Common verification requires: + +- the descriptor's `backend_name` matches the backend required by the admitted topology; +- the descriptor's version is one the supervisor supports, and the resolved backend reports that same version; and +- `SandboxContext` is constructed after the control plane assigns the resource to the admitted sandbox, using authenticated control-plane and trusted supervisor state. + +The supervisor validates the descriptor's common fields and produces a `VerifiedTopologyDescriptor`, then resolves its `backend_name` and version without fallback. Verification does not imply that the opaque payload is valid; the selected backend validates it and atomically binds the provisioned resource to the trusted `SandboxContext` during `attach`. Any failure rejects the sandbox. + +### The lifecycle + +The contract does not prescribe enforcement mechanisms; it standardizes how the supervisor drives whichever backend a deployment admits. + +A backend registers under a `backend_name` and version. The supervisor attaches to the admitted topology and drives the boundary through a fixed sequence of states. Each transition consumes the prior state, so the supervisor cannot skip a stage or invoke a later transition through an earlier handle. The Rust names are illustrative; the states and their semantics are normative. + +```text +attach topology + sandbox context -> Bound -> confirm -> Ready -> start_agent -> Running +``` + +```rust +#[async_trait] +trait IsolationBackend: Send + Sync { + fn backend_name(&self) -> &str; + fn version(&self) -> u32; + + async fn attach( + &self, + descriptor: VerifiedTopologyDescriptor, + sandbox: SandboxContext, + ) -> Result, BackendError>; +} + +struct SandboxContext { + sandbox_id: SandboxId, + policy: SandboxPolicy, + agent: AgentSpec, +} + +#[async_trait] +trait BoundBoundary: Send { + fn network_mediation_source(&self) -> Arc; + + async fn confirm( + self: Box, + ) -> Result, BackendError>; +} + +#[async_trait] +trait ReadyBoundary: Send { + async fn start_agent( + self: Box, + ) -> Result, BackendError>; +} + +#[async_trait] +trait RunningBoundary: Send + Sync { + fn agent(&self) -> Arc; + fn exec(&self) -> Arc; + fn loopback_connector(&self) -> Arc; +} +``` + +`AgentSpec` carries the complete admitted agent launch specification, including command, arguments, working directory, timeout, and interactive mode. + +`SandboxContext` carries the admitted create-time policy. [RFC 0002](../0002-agent-driven-policy-management/README.md) defines how network-policy revisions are proposed and approved. Approved revisions reach the supervisor through the existing [`GetSandboxConfig`](../../proto/sandbox.proto) gateway-supervisor contract, described in the [gateway](../../architecture/gateway.md) and [sandbox](../../architecture/sandbox.md#policy-revision-acknowledgement) architecture. The supervisor makes approved network-policy revisions effective through network mediation. If an approved network-policy revision cannot be loaded, it never becomes effective; the configured rejection posture retains the last valid generation or denies network access until a valid generation is loaded. + +The states have normative meanings: + +- **Bound:** the topology descriptor and trusted sandbox context are bound to the same resource, and the network-mediation source is available. No untrusted workload code is running. +- **Ready:** the backend has confirmed standing enforcement for this concrete boundary and is prepared to apply the admitted launch-time controls before untrusted execution. +- **Running:** `start_agent` has made the admitted agent runnable and returned `RunningBoundary`. Every applicable launch-time control was in force before the first untrusted instruction. Whether the backend creates the agent process or releases a held, driver-provisioned execution object is backend-specific; the contract fixes the ordering, not the mechanism. + +`confirm` is the pre-launch commit point. The supervisor calls it only after connecting the boundary's network-mediation source to network mediation. The backend confirms standing enforcement for the concrete boundary and may rely on a trusted provisioning-time or out-of-pod signal tied to that boundary's placement, but not on general placement health alone. + +`attach` rejects a resource already bound to an active boundary. A boundary that cannot enforce the complete admitted policy does not reach `Ready`: the backend fails `attach` or `confirm`, or the supervisor fails network-mediation initialization. + +**Standing enforcement** is established independently of a workload process. **Launch-time controls** must be in force before a process executes its first untrusted instruction. Both `start_agent` and `BoundaryExec::exec` enforce this ordering and preserve the provisioned execution environment. + +`start_agent` is the sole operation that may make the admitted agent runnable. The backend may create or release the process, but workload-controlled code cannot run before `start_agent` applies the required controls. + +`RunningBoundary::agent()` returns a handle for the admitted agent process. Processes started through `BoundaryExec` run in the same boundary and have their own process handles. Every workload process remains within the provisioned execution environment. Any exit of the admitted agent ends `Running`; the backend then terminates every remaining workload process within that environment and rejects further runtime operations, except `wait` as defined below. + +### Runtime operations + +```rust +#[async_trait] +trait BoundaryProcess: Send + Sync { // the agent, or a process started via exec + async fn wait(&self) -> Result; // one stable result where process-exit observation is retained + async fn signal(&self, signal: BoundarySignal) -> Result<(), BackendError>; + async fn terminate(&self) -> Result<(), BackendError>; // this process and its descendants +} + +#[async_trait] +trait BoundaryExec: Send + Sync { + async fn exec(&self, spec: ExecSpec) -> Result; +} + +struct ExecSession { // owned; outlives the exec call + process: Arc, + stdin: Option, + stdout: BoundaryOutput, // distinct from stderr for non-PTY exec + stderr: Option, + terminal: Option>, // present when a PTY was requested +} + +#[async_trait] +trait BoundaryLoopbackConnector: Send + Sync { + async fn connect(&self, target: LoopbackTarget) -> Result; +} + +#[async_trait] +trait BoundaryTerminal: Send + Sync { + async fn resize(&self, cols: u16, rows: u16) -> Result<(), BackendError>; +} +``` + +`ExecSpec` carries command, arguments, environment, working directory, and PTY settings. Streams are owned, non-PTY stdout and stderr remain separate, and PTYs support resize. The loopback connector accepts only validated loopback targets and supports both port forwarding and service exposure. Exit status and signals are explicit and placement-neutral; a local PID is never the process handle. These operations carry the existing agent, SSH, exec, and forwarding paths behind the contract, and all of them are mandatory conformance. + +`BoundaryProcess::wait` returns one stable exit status or `Terminated` error while the backend retains process-exit observation. + +### Network mediation + +```rust +#[async_trait] +trait NetworkMediationSource: Send + Sync { + async fn accept(&self) -> Result; +} + +struct MediatedConnection { + stream: BoundaryDuplexStream, + binary_identity: Result, +} +``` + +`NetworkMediationSource` supplies outbound connections from one boundary to supervisor-owned network mediation. The backend routes all workload egress through that source and authoritatively associates each connection with the boundary without relying solely on workload-provided data. Capture, transport, placement, and coordination are backend-private. + +Every topology may use the same supervisor-owned mediation libraries or services; the source does not require a backend-specific policy engine. + +Shared implementations isolate each boundary's state and enforcement. Failure or teardown of one boundary cannot weaken another. Network-mediation unavailability never enables direct egress. + +### Binary identity + +The backend resolves executable identity for every accepted connection and delivers the result on `MediatedConnection` before network mediation evaluates policy. + +```rust +struct BinaryIdentity { + binary_path: PathBuf, // absolute executable path + binary_digest: Option, // bytes of the resolved executable object + ancestors: Vec, // nearest first + cmdline_paths: Vec, // diagnostic context; never authorizes +} +``` + +Identity describes the executable identity resolved for the accepted connection before policy evaluation. Paths are expressed in the workload's filesystem namespace. + +If binary identity cannot be resolved, the connection is denied. `ResolveError` reports that failure. A missing digest is represented as `None`. How a backend resolves identity is implementation-specific. + +Every identity field used for authorization is obtained by a trusted component from boundary or kernel state, rather than accepted as a workload claim. The result is bound to the active boundary and accepted connection; a transport tuple or workload-supplied identifier alone is not authoritative. Workload-supplied identity may be retained only as non-authorizing diagnostic context. If attribution is ambiguous or any required identity field cannot be established, the connection is denied. + +Binary identity is mandatory conformance: RFC 0002 makes it part of the outbound-policy baseline. There is no capability flag and no mode that exempts a backend from resolving identity. + +### The supervisor sequence + +The logical supervisor resolves `backend_name` and version through a trusted implementation registry. Adding a backend adds an implementation and registration, not branches in lifecycle, proxy, SSH, or session code. Delegated transport and coordination remain backend-private. + +The supervisor runs the same sequence for every backend: + +1. Obtain the `TopologyDescriptor` and trusted `SandboxContext`. +2. Verify the descriptor and resolve its `backend_name` and version without fallback. +3. Call `attach` to obtain `Bound`. +4. Connect the boundary's `NetworkMediationSource` to network mediation. +5. Call `confirm` to obtain `Ready`, then `start_agent` to obtain `Running`. +6. Use the returned runtime handles for agent wait, `exec`, and port forwarding while network mediation consumes outbound connections. + +This RFC supersedes RFC 0001's fixed in-sandbox supervisor placement and its assignment of topology-specific isolation controls to that process, generalizing the supervisor into a logical role. RFC 0001's authentication, sandbox-identity, outbound-connection, session, and reconnection requirements continue to apply. The component hosting the logical supervisor holds the required outbound gateway connection. A driver-hosted or shared supervisor routes gateway `exec`, SSH, and forwarding requests through the backend; the gateway does not initiate a connection to the boundary. + +### Failure semantics + +Every failure carries a machine-readable kind for supervisor status mapping: + +```rust +enum BackendErrorKind { Invalid, Denied, Unavailable, Failed, Terminated } +``` + +`Invalid` covers descriptor, version, and backend mismatches; `Denied` covers authenticated attachment rejection; `Unavailable` covers transient inability to serve an operation; `Failed` covers other backend faults; and `Terminated` reports boundary or workload termination, or an operation against an inactive boundary. An error never advances the lifecycle or authorizes an operation, and backend selection never falls back. + +A backend may retry backend-private work within one `attach` call. The supervisor calls `attach` at most once per provisioned topology. If it does not return `Bound`, the topology is reclaimed rather than reused. + +Failures resolve as follows: + +- an `attach` or `confirm` failure, or network-mediation initialization failure while `Bound`, prevents untrusted workload execution and causes the driver to reclaim the topology; +- if `start_agent` does not return `Running`, no untrusted process from that attempt remains, and the driver reclaims the topology; +- if `exec` or loopback `connect` fails, the backend terminates any process or closes any connection created by that attempt while the boundary otherwise remains active; +- after `Running`, supervisor or enforcement loss follows invariant 6; when enforcement loss ends the agent, `BoundaryProcess::wait` fails with `BackendErrorKind::Terminated` where process-exit observation survives; +- network-mediation errors yield no authorized connection and do not by themselves end `Running`; and +- retained runtime handles and the network-mediation source reject new operations whenever the boundary ends, except `BoundaryProcess::wait` where the backend can still return its stable result. + +Whenever a boundary ends, the backend terminates remaining workload processes and releases the active-boundary binding before the compute driver reclaims or deprovisions the topology. If normal backend cleanup is unavailable, the compute driver uses the topology's trusted cleanup path to terminate the execution environment and invalidate the binding before reclaim or reuse. On normal agent exit, `BoundaryProcess::wait` returns the stable exit status. A retained `wait` result may outlive teardown. + +### Topologies + +The contract fixes the roles; a topology fixes their placement. Components may be co-located with the workload or hosted in trusted services, and one component may implement multiple roles. Every arrangement preserves the same lifecycle, interfaces, and invariants. Actual containment depends on the workload's kernel relationship to the trusted components. The non-normative [topology matrix](./topology-matrix.md) catalogs representative placements. + +## Conformance + +Every admitted backend and topology must pass tests for the six contract invariants plus descriptor verification, lifecycle ordering, runtime operations, and failure semantics. + +The conformance suite exercises each backend in its deployed topology, including delegated components and their transport. It verifies observable contract behavior while transport details remain backend-private. + +## Risks + +| Risk | Mitigation | +|---|---| +| The Isolation Backend could duplicate compute-driver responsibilities or allow topology-specific behavior to leak back into the supervisor. | Keep the responsibility boundary explicit: the compute driver owns, provisions, and deprovisions the topology; the backend binds and operates the active boundary. The same component may implement both roles. | +| Contract conformance could be mistaken for equivalent isolation across topologies. | Treat conformance as behavioral, not as a security-strength rating. Document and validate each topology's actual containment and reject policy it cannot enforce. | +| Shared backend or network-mediation components concentrate privilege and failure impact. | Isolate state, connection attribution, enforcement, and control authority per boundary. Failure of one boundary must not weaken another or enable direct egress. | +| The mandatory contract may exclude otherwise useful but incomplete backends. | Keep the network-mediation source, binary identity, process control, `exec`, and port forwarding mandatory. An incomplete backend does not claim conformance or silently degrade. | +| A future topology may not fit the lifecycle or interfaces. | Keep placement and coordination backend-private. Add versioned contract surface only when a concrete implementation requires new common semantics. | +| A component restart may interrupt boundary operation. | Keep the last confirmed enforcement state in force and deny supervisor-dependent operations. | + +## Alternatives + +### Keep isolation embedded in the supervisor + +OpenShell could keep the current in-pod design and add topology-specific supervisor and compute-driver paths as new requirements arise. + +Doing nothing avoids a new interface, but retains privileged boundary construction beside the workload. Implementing each delegated topology as a one-off supervisor change moves that privilege for one placement but accretes topology-specific supervisor behavior. The proposed contract instead keeps one supervisor lifecycle while allowing the topology to change. + +### Extend the compute-driver contract + +The compute driver could own both provisioning and active-boundary operation. + +This is natural for topologies such as MXC, and the same component may implement both responsibilities. The interfaces remain distinct because they serve different callers and lifecycles: the gateway uses the compute driver to provision and deprovision resources, while the supervisor uses the Isolation Backend to operate an active boundary. Combining them would couple runtime policy, identity, network mediation, and process operations to the gateway-facing driver API. + +### Start with a remote backend service + +The contract could be expressed as a gRPC service or plugin ABI rather than an in-process Rust contract. [RFC 0001](../0001-core-architecture/README.md) chose gRPC for its gateway-facing drivers, so the question applies here. + +The callers differ. A gateway driver is a control-plane peer with its own release cycle, while the Isolation Backend is driven by the supervisor that operates the boundary, and the co-located topology needs no transport at all. Starting in-process serves that case directly and lets delegated implementations carry their own transport behind the same interface. A transport-bearing surface is not precluded: it is versioned contract surface, added when a concrete delegated backend requires it. + +### Standardize topology and capabilities + +The contract could expose common topology roles, placement fields, capability flags, and recovery behavior so the supervisor can compose backend components. + +That would make known deployments explicit, but it would also encode current topology assumptions and introduce capability-dependent supervisor paths. The proposal keeps placement and coordination in the opaque descriptor, requires one baseline contract, and uses the non-normative topology matrix to document representative arrangements. + +## Prior art + +- **Driver-backed subsystems (CRI/CNI/CSI).** Kubernetes factors runtime, networking, and storage into pluggable driver contracts so the orchestrator drives one interface while implementations vary. RFC 0001 describes OpenShell's other subsystems the same way; this RFC specifies the one it left open: isolation. +- **Istio privilege placement.** Init-sidecar and node-agent modes demonstrate that network setup can move without changing the policy data path. OpenShell keeps its identity-aware proxy. +- **CRI exec/attach/port-forward.** `exec` and `connect` follow CRI's `Exec` and `PortForward` shape; lifecycle and network mediation remain OpenShell-specific. + +## Open questions + +None. diff --git a/rfc/0012-isolation-backend/topology-matrix.md b/rfc/0012-isolation-backend/topology-matrix.md new file mode 100644 index 0000000000..8dc14d84ba --- /dev/null +++ b/rfc/0012-isolation-backend/topology-matrix.md @@ -0,0 +1,36 @@ +# Topology matrix + +This non-normative matrix compares representative mappings of RFC 0012's logical +roles. It records role placement, sharing, and relationship to the workload +kernel; it does not select a deployment or establish conformance. + +## Representative placements + +| Pattern | Logical supervisor and network-mediation placement | Backend placement | Workload-kernel relationship | Topology status | +|---|---|---|---|---| +| **Co-located/in-pod** | With the workload | In the supervisor process | Trusted components share the workload's host, guest, or application kernel, depending on the runtime | Placement implemented (original topology) | +| **Same-pod composite** | Spans the workload-local supervisor process and, when used, a network-mediation sidecar | In the workload-local supervisor process | Components share the workload's kernel | Placement implemented (#2076) | +| **Delegated backend components** | With the workload and any delegated mediation component | A node or remote helper establishes some controls behind a workload-local backend | Depends on which trusted components remain with the workload | Placement proposed (#2606) | +| **Driver-hosted/shared service** | With the compute driver or another trusted service; no in-sandbox supervisor process is required | May be co-located with the logical supervisor; one host may operate many isolated boundaries | Depends on the workload runtime | Placement proposed | + +## Durable rules + +- Every active boundary has one verified descriptor, one trusted + `SandboxContext`, and at most one logical supervisor, which may span multiple + coupled processes. +- Physical processes and listeners may be shared, but lifecycle state, policy, + binary identity, enforcement, and cleanup remain isolated per boundary. +- Moving a privileged component does not itself provide kernel separation. + +## Kernel relationships + +| Relationship | Meaning | +|---|---| +| **Shared host kernel** | The workload and the trusted components relied on for containment run on the host's kernel. | +| **Shared guest or application kernel** | The workload and those trusted components share one isolated kernel: a VM guest kernel or a userspace application kernel. | +| **Kernel-separated** | The trusted components relied on for containment run outside the workload's kernel. | + +## Status + +This matrix is non-normative. It illustrates implementations of RFC 0012; it +does not extend the contract. From 3c0f58872ea956816abf82cdf50fa94601329cc5 Mon Sep 17 00:00:00 2001 From: krishicks Date: Thu, 10 Sep 2026 21:46:08 +0000 Subject: [PATCH 04/12] refactor(ocsf): rename SandboxContext to EventContext (#3263) Rename the shared OCSF context and its callers without changing event behavior. Signed-off-by: Kris Hicks --- AGENTS.md | 2 +- .../src/builders/api_activity.rs | 6 ++--- crates/openshell-ocsf/src/builders/base.rs | 6 ++--- crates/openshell-ocsf/src/builders/config.rs | 6 ++--- crates/openshell-ocsf/src/builders/finding.rs | 6 ++--- crates/openshell-ocsf/src/builders/http.rs | 6 ++--- .../openshell-ocsf/src/builders/lifecycle.rs | 6 ++--- crates/openshell-ocsf/src/builders/mod.rs | 10 ++++---- crates/openshell-ocsf/src/builders/network.rs | 6 ++--- crates/openshell-ocsf/src/builders/process.rs | 6 ++--- crates/openshell-ocsf/src/builders/ssh.rs | 6 ++--- crates/openshell-ocsf/src/ctx.rs | 14 +++++------ crates/openshell-ocsf/src/lib.rs | 6 ++--- crates/openshell-ocsf/tests/event_identity.rs | 8 +++---- crates/openshell-ocsf/tests/roundtrip.rs | 12 +++++----- crates/openshell-sandbox/src/lib.rs | 4 ++-- crates/openshell-server/src/grpc/policy.rs | 4 ++-- .../openshell-server/src/service_routing.rs | 10 ++++---- crates/openshell-server/src/tls.rs | 6 ++--- .../src/l7/middleware.rs | 4 ++-- .../src/l7/relay.rs | 6 ++--- .../src/log_push.rs | 6 ++--- .../openshell-supervisor-process/src/run.rs | 2 +- .../src/supervisor_session.rs | 24 ++++++++----------- 24 files changed, 84 insertions(+), 88 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0b35bd02f7..954ffe1147 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -173,7 +173,7 @@ ocsf_emit!(event); ### Key points -- `crate::ocsf_ctx()` returns the process-wide `SandboxContext`. It is always available (falls back to defaults in tests). +- `crate::ocsf_ctx()` returns the process-wide `EventContext`. It is always available (falls back to defaults in tests). - `ocsf_emit!()` is non-blocking and cannot panic. It stores the event in a thread-local and emits via `tracing::info!()`. - The shorthand layer and JSONL layer extract the event from the thread-local. The shorthand format is derived automatically from the builder fields. - For security findings, **dual-emit**: one domain event (e.g., `SshActivityBuilder`) AND one `DetectionFindingBuilder` for the same incident. diff --git a/crates/openshell-ocsf/src/builders/api_activity.rs b/crates/openshell-ocsf/src/builders/api_activity.rs index f3cddbad8e..1d1f2b98f2 100644 --- a/crates/openshell-ocsf/src/builders/api_activity.rs +++ b/crates/openshell-ocsf/src/builders/api_activity.rs @@ -3,7 +3,7 @@ //! Builder for API Activity [6003] events. -use crate::builders::SandboxContext; +use crate::builders::EventContext; use crate::enums::{SeverityId, StatusId}; use crate::events::base_event::BaseEventData; use crate::events::{ApiActivityEvent, OcsfEvent}; @@ -26,7 +26,7 @@ fn sanitize_model_name(name: &str) -> String { /// Builder for API Activity [6003] events. pub struct ApiActivityBuilder<'a> { - ctx: &'a SandboxContext, + ctx: &'a EventContext, severity: SeverityId, status: Option, message: Option, @@ -39,7 +39,7 @@ pub struct ApiActivityBuilder<'a> { impl<'a> ApiActivityBuilder<'a> { #[must_use] - pub fn new(ctx: &'a SandboxContext, operation: impl Into) -> Self { + pub fn new(ctx: &'a EventContext, operation: impl Into) -> Self { Self { ctx, severity: SeverityId::Informational, diff --git a/crates/openshell-ocsf/src/builders/base.rs b/crates/openshell-ocsf/src/builders/base.rs index ac51f7dd7f..c2edb5b169 100644 --- a/crates/openshell-ocsf/src/builders/base.rs +++ b/crates/openshell-ocsf/src/builders/base.rs @@ -3,14 +3,14 @@ //! Builder for Base Event [0]. -use crate::builders::SandboxContext; +use crate::builders::EventContext; use crate::enums::{SeverityId, StatusId}; use crate::events::base_event::BaseEventData; use crate::events::{BaseEvent, OcsfEvent}; /// Builder for Base Event [0] — events without a specific OCSF class. pub struct BaseEventBuilder<'a> { - ctx: &'a SandboxContext, + ctx: &'a EventContext, severity: SeverityId, status: Option, message: Option, @@ -20,7 +20,7 @@ pub struct BaseEventBuilder<'a> { impl<'a> BaseEventBuilder<'a> { #[must_use] - pub fn new(ctx: &'a SandboxContext) -> Self { + pub fn new(ctx: &'a EventContext) -> Self { Self { ctx, severity: SeverityId::Informational, diff --git a/crates/openshell-ocsf/src/builders/config.rs b/crates/openshell-ocsf/src/builders/config.rs index d8d40dd24d..1bc415b612 100644 --- a/crates/openshell-ocsf/src/builders/config.rs +++ b/crates/openshell-ocsf/src/builders/config.rs @@ -3,14 +3,14 @@ //! Builder for Device Config State Change [5019] events. -use crate::builders::SandboxContext; +use crate::builders::EventContext; use crate::enums::{SecurityLevelId, SeverityId, StateId, StatusId}; use crate::events::base_event::BaseEventData; use crate::events::{DeviceConfigStateChangeEvent, OcsfEvent}; /// Builder for Device Config State Change [5019] events. pub struct ConfigStateChangeBuilder<'a> { - ctx: &'a SandboxContext, + ctx: &'a EventContext, severity: SeverityId, status: Option, state_id: Option, @@ -23,7 +23,7 @@ pub struct ConfigStateChangeBuilder<'a> { impl<'a> ConfigStateChangeBuilder<'a> { #[must_use] - pub fn new(ctx: &'a SandboxContext) -> Self { + pub fn new(ctx: &'a EventContext) -> Self { Self { ctx, severity: SeverityId::Informational, diff --git a/crates/openshell-ocsf/src/builders/finding.rs b/crates/openshell-ocsf/src/builders/finding.rs index fecb1e9275..c21eddd258 100644 --- a/crates/openshell-ocsf/src/builders/finding.rs +++ b/crates/openshell-ocsf/src/builders/finding.rs @@ -3,7 +3,7 @@ //! Builder for Detection Finding [2004] events. -use crate::builders::SandboxContext; +use crate::builders::EventContext; use crate::enums::{ActionId, ActivityId, ConfidenceId, DispositionId, RiskLevelId, SeverityId}; use crate::events::base_event::BaseEventData; use crate::events::{DetectionFindingEvent, OcsfEvent}; @@ -11,7 +11,7 @@ use crate::objects::{Attack, Evidence, FindingInfo, Remediation}; /// Builder for Detection Finding [2004] events. pub struct DetectionFindingBuilder<'a> { - ctx: &'a SandboxContext, + ctx: &'a EventContext, activity: ActivityId, severity: SeverityId, action: Option, @@ -30,7 +30,7 @@ pub struct DetectionFindingBuilder<'a> { impl<'a> DetectionFindingBuilder<'a> { #[must_use] - pub fn new(ctx: &'a SandboxContext) -> Self { + pub fn new(ctx: &'a EventContext) -> Self { Self { ctx, activity: ActivityId::Open, diff --git a/crates/openshell-ocsf/src/builders/http.rs b/crates/openshell-ocsf/src/builders/http.rs index ae91cf7c41..a46032a505 100644 --- a/crates/openshell-ocsf/src/builders/http.rs +++ b/crates/openshell-ocsf/src/builders/http.rs @@ -3,7 +3,7 @@ //! Builder for HTTP Activity [4002] events. -use crate::builders::SandboxContext; +use crate::builders::EventContext; use crate::enums::{ActionId, ActivityId, DispositionId, SeverityId, StatusId}; use crate::events::base_event::BaseEventData; use crate::events::{HttpActivityEvent, OcsfEvent}; @@ -11,7 +11,7 @@ use crate::objects::{Actor, Endpoint, FirewallRule, HttpRequest, HttpResponse}; /// Builder for HTTP Activity [4002] events. pub struct HttpActivityBuilder<'a> { - ctx: &'a SandboxContext, + ctx: &'a EventContext, activity: ActivityId, action: Option, disposition: Option, @@ -30,7 +30,7 @@ pub struct HttpActivityBuilder<'a> { impl<'a> HttpActivityBuilder<'a> { #[must_use] - pub fn new(ctx: &'a SandboxContext) -> Self { + pub fn new(ctx: &'a EventContext) -> Self { Self { ctx, activity: ActivityId::Unknown, diff --git a/crates/openshell-ocsf/src/builders/lifecycle.rs b/crates/openshell-ocsf/src/builders/lifecycle.rs index fc210dc745..8fc648ee37 100644 --- a/crates/openshell-ocsf/src/builders/lifecycle.rs +++ b/crates/openshell-ocsf/src/builders/lifecycle.rs @@ -3,7 +3,7 @@ //! Builder for Application Lifecycle [6002] events. -use crate::builders::SandboxContext; +use crate::builders::EventContext; use crate::enums::{ActivityId, SeverityId, StatusId}; use crate::events::base_event::BaseEventData; use crate::events::{ApplicationLifecycleEvent, OcsfEvent}; @@ -11,7 +11,7 @@ use crate::objects::Product; /// Builder for Application Lifecycle [6002] events. pub struct AppLifecycleBuilder<'a> { - ctx: &'a SandboxContext, + ctx: &'a EventContext, activity: ActivityId, severity: SeverityId, status: Option, @@ -20,7 +20,7 @@ pub struct AppLifecycleBuilder<'a> { impl<'a> AppLifecycleBuilder<'a> { #[must_use] - pub fn new(ctx: &'a SandboxContext) -> Self { + pub fn new(ctx: &'a EventContext) -> Self { Self { ctx, activity: ActivityId::Unknown, diff --git a/crates/openshell-ocsf/src/builders/mod.rs b/crates/openshell-ocsf/src/builders/mod.rs index f51579c60e..eacd608b07 100644 --- a/crates/openshell-ocsf/src/builders/mod.rs +++ b/crates/openshell-ocsf/src/builders/mod.rs @@ -3,7 +3,7 @@ //! Ergonomic builders for constructing OCSF events. //! -//! Each event class has a builder that takes a `SandboxContext` reference +//! Each event class has a builder that takes a `EventContext` reference //! and provides chainable methods for setting event fields. /// Generate the shared `severity`, `status`, and `message` setter methods that @@ -180,7 +180,7 @@ use crate::objects::{Container, Device, Endpoint, Image, Metadata, Product}; /// Passed to every event builder to populate shared OCSF fields /// (metadata, container, device, proxy endpoint). #[derive(Debug, Clone)] -pub struct SandboxContext { +pub struct EventContext { /// Sandbox unique identifier. pub sandbox_id: String, /// Sandbox display name. @@ -197,7 +197,7 @@ pub struct SandboxContext { pub proxy_port: u16, } -impl SandboxContext { +impl EventContext { /// Build the OCSF `Metadata` object for any event. #[must_use] pub fn metadata(&self, profiles: &[&str]) -> Metadata { @@ -259,8 +259,8 @@ impl SandboxContext { } #[cfg(test)] -pub(crate) fn test_sandbox_context() -> SandboxContext { - SandboxContext { +pub(crate) fn test_sandbox_context() -> EventContext { + EventContext { sandbox_id: "sandbox-abc123".to_string(), sandbox_name: "my-sandbox".to_string(), container_image: "ghcr.io/openshell/sandbox:latest".to_string(), diff --git a/crates/openshell-ocsf/src/builders/network.rs b/crates/openshell-ocsf/src/builders/network.rs index 1a0390bd1e..8f405aba45 100644 --- a/crates/openshell-ocsf/src/builders/network.rs +++ b/crates/openshell-ocsf/src/builders/network.rs @@ -3,7 +3,7 @@ //! Builder for Network Activity [4001] events. -use crate::builders::SandboxContext; +use crate::builders::EventContext; use crate::enums::{ActionId, ActivityId, DispositionId, SeverityId, StatusId}; use crate::events::base_event::BaseEventData; use crate::events::{NetworkActivityEvent, OcsfEvent}; @@ -11,7 +11,7 @@ use crate::objects::{Actor, ConnectionInfo, Endpoint, FirewallRule}; /// Builder for Network Activity [4001] events. pub struct NetworkActivityBuilder<'a> { - ctx: &'a SandboxContext, + ctx: &'a EventContext, activity: ActivityId, activity_name: Option, action: Option, @@ -33,7 +33,7 @@ pub struct NetworkActivityBuilder<'a> { impl<'a> NetworkActivityBuilder<'a> { /// Start building a Network Activity event. #[must_use] - pub fn new(ctx: &'a SandboxContext) -> Self { + pub fn new(ctx: &'a EventContext) -> Self { Self { ctx, activity: ActivityId::Unknown, diff --git a/crates/openshell-ocsf/src/builders/process.rs b/crates/openshell-ocsf/src/builders/process.rs index 0974bac71f..6e06e6c6e7 100644 --- a/crates/openshell-ocsf/src/builders/process.rs +++ b/crates/openshell-ocsf/src/builders/process.rs @@ -3,7 +3,7 @@ //! Builder for Process Activity [1007] events. -use crate::builders::SandboxContext; +use crate::builders::EventContext; use crate::enums::{ActionId, ActivityId, DispositionId, LaunchTypeId, SeverityId, StatusId}; use crate::events::base_event::BaseEventData; use crate::events::{OcsfEvent, ProcessActivityEvent}; @@ -11,7 +11,7 @@ use crate::objects::{Actor, Process}; /// Builder for Process Activity [1007] events. pub struct ProcessActivityBuilder<'a> { - ctx: &'a SandboxContext, + ctx: &'a EventContext, activity: ActivityId, severity: SeverityId, status: Option, @@ -26,7 +26,7 @@ pub struct ProcessActivityBuilder<'a> { impl<'a> ProcessActivityBuilder<'a> { #[must_use] - pub fn new(ctx: &'a SandboxContext) -> Self { + pub fn new(ctx: &'a EventContext) -> Self { Self { ctx, activity: ActivityId::Unknown, diff --git a/crates/openshell-ocsf/src/builders/ssh.rs b/crates/openshell-ocsf/src/builders/ssh.rs index 4ca6a80f04..36383ae9f4 100644 --- a/crates/openshell-ocsf/src/builders/ssh.rs +++ b/crates/openshell-ocsf/src/builders/ssh.rs @@ -3,7 +3,7 @@ //! Builder for SSH Activity [4007] events. -use crate::builders::SandboxContext; +use crate::builders::EventContext; use crate::enums::{ActionId, ActivityId, AuthTypeId, DispositionId, SeverityId, StatusId}; use crate::events::base_event::BaseEventData; use crate::events::{OcsfEvent, SshActivityEvent}; @@ -11,7 +11,7 @@ use crate::objects::{Actor, Endpoint}; /// Builder for SSH Activity [4007] events. pub struct SshActivityBuilder<'a> { - ctx: &'a SandboxContext, + ctx: &'a EventContext, activity: ActivityId, action: Option, disposition: Option, @@ -28,7 +28,7 @@ pub struct SshActivityBuilder<'a> { impl<'a> SshActivityBuilder<'a> { #[must_use] - pub fn new(ctx: &'a SandboxContext) -> Self { + pub fn new(ctx: &'a EventContext) -> Self { Self { ctx, activity: ActivityId::Unknown, diff --git a/crates/openshell-ocsf/src/ctx.rs b/crates/openshell-ocsf/src/ctx.rs index 6916c55215..f714b77ab2 100644 --- a/crates/openshell-ocsf/src/ctx.rs +++ b/crates/openshell-ocsf/src/ctx.rs @@ -1,19 +1,19 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Process-wide [`SandboxContext`] singleton. +//! Process-wide [`EventContext`] singleton. //! //! Initialised once via [`set_ctx`] during sandbox start; read by every event //! builder via [`ctx`]. Falls back to a default context when the singleton has //! not been set (e.g. unit tests that exercise builders without booting the //! sandbox). -use crate::SandboxContext; +use crate::EventContext; use std::sync::{LazyLock, OnceLock}; -static OCSF_CTX: OnceLock = OnceLock::new(); +static OCSF_CTX: OnceLock = OnceLock::new(); -static OCSF_CTX_FALLBACK: LazyLock = LazyLock::new(|| SandboxContext { +static OCSF_CTX_FALLBACK: LazyLock = LazyLock::new(|| EventContext { sandbox_id: String::new(), sandbox_name: String::new(), container_image: String::new(), @@ -27,15 +27,15 @@ static OCSF_CTX_FALLBACK: LazyLock = LazyLock::new(|| SandboxCon /// /// Returns `false` if the context was already set; the caller may log and /// continue. Intended to be called exactly once during sandbox startup. -pub fn set_ctx(ctx: SandboxContext) -> bool { +pub fn set_ctx(ctx: EventContext) -> bool { OCSF_CTX.set(ctx).is_ok() } -/// Return a reference to the process-wide [`SandboxContext`]. +/// Return a reference to the process-wide [`EventContext`]. /// /// Falls back to a default context if [`set_ctx`] has not been called (e.g. /// during unit tests that exercise individual builders). #[must_use] -pub fn ctx() -> &'static SandboxContext { +pub fn ctx() -> &'static EventContext { OCSF_CTX.get().unwrap_or(&OCSF_CTX_FALLBACK) } diff --git a/crates/openshell-ocsf/src/lib.rs b/crates/openshell-ocsf/src/lib.rs index c954fc5628..e6be8c2644 100644 --- a/crates/openshell-ocsf/src/lib.rs +++ b/crates/openshell-ocsf/src/lib.rs @@ -12,7 +12,7 @@ //! State Change, and Base Event //! - **Typed enums and objects**: All OCSF enum and object types used by the //! event classes -//! - **Builders**: Ergonomic per-class builders with `SandboxContext` for shared +//! - **Builders**: Ergonomic per-class builders with `EventContext` for shared //! metadata //! - **Dual formatters**: `format_shorthand()` for human-readable single-line //! output, and `to_json()`/`to_json_line()` for OCSF-compliant JSONL @@ -58,8 +58,8 @@ pub use objects::{ // --- Builders --- pub use builders::{ ApiActivityBuilder, AppLifecycleBuilder, BaseEventBuilder, ConfigStateChangeBuilder, - DetectionFindingBuilder, HttpActivityBuilder, NetworkActivityBuilder, ProcessActivityBuilder, - SandboxContext, SshActivityBuilder, + DetectionFindingBuilder, EventContext, HttpActivityBuilder, NetworkActivityBuilder, + ProcessActivityBuilder, SshActivityBuilder, }; // --- Tracing layers --- diff --git a/crates/openshell-ocsf/tests/event_identity.rs b/crates/openshell-ocsf/tests/event_identity.rs index 3d8618bdd2..9fa51cc8bd 100644 --- a/crates/openshell-ocsf/tests/event_identity.rs +++ b/crates/openshell-ocsf/tests/event_identity.rs @@ -5,10 +5,10 @@ use std::net::{IpAddr, Ipv4Addr}; -use openshell_ocsf::{ActivityId, NetworkActivityBuilder, OcsfEvent, SandboxContext, SeverityId}; +use openshell_ocsf::{ActivityId, EventContext, NetworkActivityBuilder, OcsfEvent, SeverityId}; -fn sandbox_ctx(container_image: &str) -> SandboxContext { - SandboxContext { +fn sandbox_ctx(container_image: &str) -> EventContext { + EventContext { sandbox_id: "sb-1".to_string(), sandbox_name: "agent-01".to_string(), container_image: container_image.to_string(), @@ -19,7 +19,7 @@ fn sandbox_ctx(container_image: &str) -> SandboxContext { } } -fn event(ctx: &SandboxContext) -> OcsfEvent { +fn event(ctx: &EventContext) -> OcsfEvent { NetworkActivityBuilder::new(ctx) .activity(ActivityId::Open) .severity(SeverityId::Medium) diff --git a/crates/openshell-ocsf/tests/roundtrip.rs b/crates/openshell-ocsf/tests/roundtrip.rs index d179510b1a..42664400ab 100644 --- a/crates/openshell-ocsf/tests/roundtrip.rs +++ b/crates/openshell-ocsf/tests/roundtrip.rs @@ -12,14 +12,14 @@ use std::net::{IpAddr, Ipv4Addr}; use openshell_ocsf::{ ActionId, ActivityId, AiModel, ApiActivityBuilder, AppLifecycleBuilder, Attack, AuthTypeId, BaseEventBuilder, ConfidenceId, ConfigStateChangeBuilder, ConnectionInfo, - DetectionFindingBuilder, DispositionId, Endpoint, FindingInfo, HttpActivityBuilder, HttpMethod, - HttpRequest, HttpResponse, LaunchTypeId, NetworkActivityBuilder, OcsfEvent, Process, - ProcessActivityBuilder, RiskLevelId, SandboxContext, SecurityLevelId, SeverityId, - SshActivityBuilder, StateId, StatusId, Url, + DetectionFindingBuilder, DispositionId, Endpoint, EventContext, FindingInfo, + HttpActivityBuilder, HttpMethod, HttpRequest, HttpResponse, LaunchTypeId, + NetworkActivityBuilder, OcsfEvent, Process, ProcessActivityBuilder, RiskLevelId, + SecurityLevelId, SeverityId, SshActivityBuilder, StateId, StatusId, Url, }; -fn ctx() -> SandboxContext { - SandboxContext { +fn ctx() -> EventContext { + EventContext { sandbox_id: "sb-7f3a9c2e14b8".to_string(), sandbox_name: "agent-workspace-01".to_string(), container_image: "ghcr.io/nvidia/openshell-community/sandboxes/base:latest".to_string(), diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index d86c94b97b..b5b9358ac0 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -38,7 +38,7 @@ use openshell_core::PolicyValidationFailureMode; use openshell_ocsf::{ ActionId, ActivityId, AppLifecycleBuilder, ConfidenceId, ConfigStateChangeBuilder, - DetectionFindingBuilder, DispositionId, FindingInfo, OcsfEvent, SandboxContext, SeverityId, + DetectionFindingBuilder, DispositionId, EventContext, FindingInfo, OcsfEvent, SeverityId, StateId, StatusId, ocsf_emit, }; @@ -142,7 +142,7 @@ pub async fn run_sandbox( |s| s.trim().to_string(), ); - if !openshell_ocsf::ctx::set_ctx(SandboxContext { + if !openshell_ocsf::ctx::set_ctx(EventContext { sandbox_id: sandbox_id.clone().unwrap_or_default(), sandbox_name: sandbox.as_deref().unwrap_or_default().to_string(), container_image: std::env::var("OPENSHELL_CONTAINER_IMAGE").unwrap_or_default(), diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 4f2855dd0b..62bc0f8575 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -60,7 +60,7 @@ use openshell_core::{ settings::{self, SettingValueKind}, }; use openshell_ocsf::{ - ConfigStateChangeBuilder, OCSF_TARGET, OcsfEvent, SandboxContext, SeverityId, StateId, StatusId, + ConfigStateChangeBuilder, EventContext, OCSF_TARGET, OcsfEvent, SeverityId, StateId, StatusId, }; use openshell_policy::{ PolicyMergeOp, ProviderPolicyLayer, canonicalize_advisor_add_rule, compose_effective_policy, @@ -234,7 +234,7 @@ fn build_gateway_policy_audit_message( policy_hash: &str, extra_fields: &[(&str, String)], ) -> String { - let ctx = SandboxContext { + let ctx = EventContext { sandbox_id: sandbox_id.to_string(), sandbox_name: sandbox_name.to_string(), container_image: "openshell/gateway".to_string(), diff --git a/crates/openshell-server/src/service_routing.rs b/crates/openshell-server/src/service_routing.rs index 3e80bc26f5..926f78094c 100644 --- a/crates/openshell-server/src/service_routing.rs +++ b/crates/openshell-server/src/service_routing.rs @@ -13,9 +13,9 @@ use openshell_core::config::ServiceRoutingConfig; use openshell_core::proto::{Sandbox, SandboxPhase, ServiceEndpoint, TcpRelayTarget, relay_open}; use openshell_core::{ObjectId, VERSION}; use openshell_ocsf::{ - ActionId, ActivityId, ConfigStateChangeBuilder, DispositionId, Endpoint, HttpActivityBuilder, - HttpRequest, HttpResponse as OcsfHttpResponse, NetworkActivityBuilder, OCSF_TARGET, OcsfEvent, - SandboxContext, SeverityId, StateId, StatusId, Url as OcsfUrl, + ActionId, ActivityId, ConfigStateChangeBuilder, DispositionId, Endpoint, EventContext, + HttpActivityBuilder, HttpRequest, HttpResponse as OcsfHttpResponse, NetworkActivityBuilder, + OCSF_TARGET, OcsfEvent, SeverityId, StateId, StatusId, Url as OcsfUrl, }; use std::net::{IpAddr, Ipv4Addr}; use std::sync::Arc; @@ -760,8 +760,8 @@ fn emit_gateway_ocsf_event(sandbox_id: &str, event: OcsfEvent) { ); } -fn gateway_ocsf_ctx(sandbox_id: &str, sandbox_name: &str) -> SandboxContext { - SandboxContext { +fn gateway_ocsf_ctx(sandbox_id: &str, sandbox_name: &str) -> EventContext { + EventContext { sandbox_id: sandbox_id.to_string(), sandbox_name: sandbox_name.to_string(), container_image: "openshell/gateway".to_string(), diff --git a/crates/openshell-server/src/tls.rs b/crates/openshell-server/src/tls.rs index 531daf7873..9154034dfd 100644 --- a/crates/openshell-server/src/tls.rs +++ b/crates/openshell-server/src/tls.rs @@ -15,7 +15,7 @@ use notify::event::EventKind; use notify::{Event, RecursiveMode, Watcher}; use openshell_core::{Error, Result}; use openshell_ocsf::{ - ConfigStateChangeBuilder, OCSF_TARGET, SandboxContext, SeverityId, StateId, StatusId, + ConfigStateChangeBuilder, EventContext, OCSF_TARGET, SeverityId, StateId, StatusId, }; use rustls::ServerConfig; use rustls::crypto::aws_lc_rs::sign; @@ -473,8 +473,8 @@ fn load_key(path: &Path) -> Result> { } /// Build an OCSF context for gateway-level (non-sandbox) events. -fn tls_ocsf_ctx() -> SandboxContext { - SandboxContext { +fn tls_ocsf_ctx() -> EventContext { + EventContext { sandbox_id: String::new(), sandbox_name: String::new(), container_image: "openshell/gateway".to_string(), diff --git a/crates/openshell-supervisor-network/src/l7/middleware.rs b/crates/openshell-supervisor-network/src/l7/middleware.rs index 6305653f6a..f2df288019 100644 --- a/crates/openshell-supervisor-network/src/l7/middleware.rs +++ b/crates/openshell-supervisor-network/src/l7/middleware.rs @@ -611,7 +611,7 @@ pub async fn send_middleware_admission_exhausted_response< #[allow(clippy::too_many_arguments)] pub(super) fn middleware_request_input( - sandbox: &openshell_ocsf::SandboxContext, + sandbox: &openshell_ocsf::EventContext, scheme: &str, req: &crate::l7::provider::L7Request, ctx: &L7EvalContext, @@ -1087,7 +1087,7 @@ mod tests { #[test] fn middleware_input_carries_real_sandbox_name() { - let sandbox = openshell_ocsf::SandboxContext { + let sandbox = openshell_ocsf::EventContext { sandbox_id: "sbx-123".into(), sandbox_name: "nightly-build".into(), container_image: String::new(), diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index d022622a38..cd2df94118 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -1149,10 +1149,10 @@ pub(crate) async fn websocket_middleware_preflight( /// Build the WebSocket preflight input from the sandbox and evaluation /// contexts. Kept separate from `websocket_middleware_preflight` (and taking an -/// explicit `SandboxContext`) so the identifier copy is unit-testable with a +/// explicit `EventContext`) so the identifier copy is unit-testable with a /// real sandbox name, mirroring `middleware_request_input` on the HTTP path. fn websocket_preflight_input( - sandbox: &openshell_ocsf::SandboxContext, + sandbox: &openshell_ocsf::EventContext, ctx: &L7EvalContext, req: &crate::l7::provider::L7Request, scheme: &str, @@ -3022,7 +3022,7 @@ mod tests { #[test] fn websocket_preflight_input_carries_real_sandbox_name() { - let sandbox = openshell_ocsf::SandboxContext { + let sandbox = openshell_ocsf::EventContext { sandbox_id: "sbx-123".into(), sandbox_name: "nightly-build".into(), container_image: String::new(), diff --git a/crates/openshell-supervisor-process/src/log_push.rs b/crates/openshell-supervisor-process/src/log_push.rs index 256fbff4a4..b24382787c 100644 --- a/crates/openshell-supervisor-process/src/log_push.rs +++ b/crates/openshell-supervisor-process/src/log_push.rs @@ -317,13 +317,13 @@ impl tracing::field::Visit for LogVisitor { mod tests { use super::*; use openshell_ocsf::{ - ActionId, ActivityId, DispositionId, Endpoint, NetworkActivityBuilder, SandboxContext, + ActionId, ActivityId, DispositionId, Endpoint, EventContext, NetworkActivityBuilder, SeverityId, StatusId, ocsf_emit, }; use tracing_subscriber::layer::SubscriberExt; - fn ocsf_ctx() -> SandboxContext { - SandboxContext { + fn ocsf_ctx() -> EventContext { + EventContext { sandbox_id: "sb-test".to_string(), sandbox_name: "test-sandbox".to_string(), container_image: "openshell/sandbox:test".to_string(), diff --git a/crates/openshell-supervisor-process/src/run.rs b/crates/openshell-supervisor-process/src/run.rs index 8c47e789ba..ef40fbd760 100644 --- a/crates/openshell-supervisor-process/src/run.rs +++ b/crates/openshell-supervisor-process/src/run.rs @@ -51,7 +51,7 @@ pub enum SidecarExitReport { }, } -fn ocsf_ctx() -> &'static openshell_ocsf::SandboxContext { +fn ocsf_ctx() -> &'static openshell_ocsf::EventContext { openshell_ocsf::ctx::ctx() } diff --git a/crates/openshell-supervisor-process/src/supervisor_session.rs b/crates/openshell-supervisor-process/src/supervisor_session.rs index 98a3c0497b..a8f60a5681 100644 --- a/crates/openshell-supervisor-process/src/supervisor_session.rs +++ b/crates/openshell-supervisor-process/src/supervisor_session.rs @@ -24,7 +24,7 @@ use openshell_core::proto::{ SupervisorMessage, TcpRelayTarget, gateway_message, relay_open, supervisor_message, }; use openshell_ocsf::{ - ActivityId, ConnectionInfo, Endpoint, NetworkActivityBuilder, OcsfEvent, SandboxContext, + ActivityId, ConnectionInfo, Endpoint, EventContext, NetworkActivityBuilder, OcsfEvent, SeverityId, StatusId, ocsf_emit, }; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; @@ -55,7 +55,7 @@ fn ocsf_gateway_endpoint(endpoint: &str) -> Endpoint { } fn session_established_event( - ctx: &SandboxContext, + ctx: &EventContext, endpoint: &str, session_id: &str, heartbeat_secs: u32, @@ -71,7 +71,7 @@ fn session_established_event( .build() } -fn session_closed_event(ctx: &SandboxContext, endpoint: &str, sandbox_id: &str) -> OcsfEvent { +fn session_closed_event(ctx: &EventContext, endpoint: &str, sandbox_id: &str) -> OcsfEvent { NetworkActivityBuilder::new(ctx) .activity(ActivityId::Close) .severity(SeverityId::Informational) @@ -82,7 +82,7 @@ fn session_closed_event(ctx: &SandboxContext, endpoint: &str, sandbox_id: &str) } fn session_failed_event( - ctx: &SandboxContext, + ctx: &EventContext, endpoint: &str, attempt: u64, error: &str, @@ -139,7 +139,7 @@ fn relay_target_message( } fn relay_open_event( - ctx: &SandboxContext, + ctx: &EventContext, open: &RelayOpen, ssh_socket_path: &std::path::Path, ) -> OcsfEvent { @@ -157,7 +157,7 @@ fn relay_open_event( } fn relay_closed_event( - ctx: &SandboxContext, + ctx: &EventContext, open: &RelayOpen, ssh_socket_path: &std::path::Path, ) -> OcsfEvent { @@ -175,7 +175,7 @@ fn relay_closed_event( } fn relay_failed_event( - ctx: &SandboxContext, + ctx: &EventContext, open: &RelayOpen, ssh_socket_path: &std::path::Path, error: &str, @@ -196,11 +196,7 @@ fn relay_failed_event( builder.build() } -fn relay_close_from_gateway_event( - ctx: &SandboxContext, - channel_id: &str, - reason: &str, -) -> OcsfEvent { +fn relay_close_from_gateway_event(ctx: &EventContext, channel_id: &str, reason: &str) -> OcsfEvent { NetworkActivityBuilder::new(ctx) .activity(ActivityId::Close) .severity(SeverityId::Informational) @@ -895,8 +891,8 @@ mod target_tests { mod ocsf_event_tests { use super::*; - fn ctx() -> SandboxContext { - SandboxContext { + fn ctx() -> EventContext { + EventContext { sandbox_id: "sbx-1".into(), sandbox_name: "sandbox".into(), container_image: "img".into(), From 226a83b3232ddf3e6534e4c0889c5a1c04b22297 Mon Sep 17 00:00:00 2001 From: "John T. Myers" <9696606+johntmyers@users.noreply.github.com> Date: Thu, 10 Sep 2026 23:10:01 +0000 Subject: [PATCH 05/12] fix(supervisor): classify credential placeholders in request bodies (#3246) * fix(supervisor): classify credential placeholders in request bodies Closes #2904 Signed-off-by: John Myers * fix(supervisor): preserve same-provider placeholders in request bodies Signed-off-by: John Myers --------- Signed-off-by: John Myers Co-authored-by: John Myers --- architecture/security-policy.md | 20 +- .../src/provider_credentials.rs | 220 +++++++- crates/openshell-core/src/secrets.rs | 3 + crates/openshell-core/src/secrets_body.rs | 482 ++++++++++++++++++ crates/openshell-providers/src/profiles.rs | 69 +++ .../src/l7/relay.rs | 76 ++- .../src/l7/rest.rs | 289 ++++++++--- .../openshell-supervisor-network/src/proxy.rs | 189 +++++-- .../src/proxy/relay.rs | 2 + .../src/proxy/tests/compatibility.rs | 6 +- docs/reference/policy-schema.mdx | 2 +- docs/sandboxes/policies.mdx | 20 +- e2e/rust/tests/credential_gating.rs | 130 +++-- skills/debug-inference/SKILL.md | 1 + 14 files changed, 1338 insertions(+), 171 deletions(-) create mode 100644 crates/openshell-core/src/secrets_body.rs diff --git a/architecture/security-policy.md b/architecture/security-policy.md index 5b49118b93..18472ed5b0 100644 --- a/architecture/security-policy.md +++ b/architecture/security-policy.md @@ -144,13 +144,25 @@ requires removing the endpoint or replacing the policy. The network supervisor independently enforces the same boundary. Credentialed WebSocket upgrades use the parsed relay, binary frames fail closed, and text -placeholders require rewrite. REST bodies can continue streaming when body -rewrite is disabled, but the relay withholds enough trailing bytes to detect a -placeholder split across reads before forwarding its marker. Explicitly opted-in +placeholders require rewrite. REST bodies continue streaming when body rewrite is disabled. The relay holds +complete placeholder candidates until a request-scoped metadata snapshot can +classify them. Authoritatively unknown keys and valid credentials with a current +binding pass unchanged, including references bound to the destination itself. +Revoked or invalid identities and unavailable classification state +fail closed. Classification never substitutes secret values and shares the request's +credential revision; stale credential or policy generations terminate forwarding. +Header rewriting scans only headers. Body bytes received in the initial proxy +read follow the same body classifier or explicit rewriter as later reads. +Candidates are limited to 4096 wire bytes, including percent encoding. Malformed +or oversized candidates fail closed; HTTP trailers retain prefix-based rejection. Explicitly opted-in endpoints retain raw passthrough behavior. +Body denials return `credential_placeholder_in_request_body` in a local HTTP 403 +response and discard any partially written upstream request. Safe preceding bytes +may already have reached upstream. + Denials emit both the relevant network activity and a detection finding. Events -identify only the destination, policy, and traffic surface; they never include +identify only the destination, policy, traffic surface, and controlled denial reason; they never include credential names, placeholders, body content, or secret values. Credential provenance is gateway-derived and deliberately absent from the policy diff --git a/crates/openshell-core/src/provider_credentials.rs b/crates/openshell-core/src/provider_credentials.rs index 2b1537a21b..f82fd066af 100644 --- a/crates/openshell-core/src/provider_credentials.rs +++ b/crates/openshell-core/src/provider_credentials.rs @@ -32,6 +32,8 @@ struct ProviderCredentialStateInner { non_secret_environment_keys: HashSet, static_credential_bindings: HashMap, known_static_credential_keys: HashSet, + body_inventory_available: bool, + known_body_keys: HashSet, static_credential_identity_epochs: HashMap, } @@ -97,13 +99,15 @@ impl ProviderCredentialState { Self { inner: Arc::new(RwLock::new(ProviderCredentialStateInner { - current: snapshot, + current: snapshot.clone(), generations, current_resolver, combined_resolver, suppressed_keys: HashSet::new(), non_secret_environment_keys: HashSet::new(), static_credential_bindings: HashMap::new(), + body_inventory_available: true, + known_body_keys: snapshot.child_env.keys().cloned().collect(), known_static_credential_keys: HashSet::new(), static_credential_identity_epochs: HashMap::new(), })), @@ -149,13 +153,15 @@ impl ProviderCredentialState { Ok(Self { inner: Arc::new(RwLock::new(ProviderCredentialStateInner { - current: snapshot, + current: snapshot.clone(), generations, current_resolver, combined_resolver, suppressed_keys: HashSet::new(), non_secret_environment_keys: non_secret_environment_keys.into_iter().collect(), static_credential_bindings, + body_inventory_available: true, + known_body_keys: snapshot.child_env.keys().cloned().collect(), known_static_credential_keys, static_credential_identity_epochs, })), @@ -179,13 +185,15 @@ impl ProviderCredentialState { Self { inner: Arc::new(RwLock::new(ProviderCredentialStateInner { - current: snapshot, + current: snapshot.clone(), generations: VecDeque::new(), current_resolver: None, combined_resolver: None, suppressed_keys: HashSet::new(), non_secret_environment_keys: HashSet::new(), static_credential_bindings: HashMap::new(), + body_inventory_available: false, + known_body_keys: snapshot.child_env.keys().cloned().collect(), known_static_credential_keys: HashSet::new(), static_credential_identity_epochs: HashMap::new(), })), @@ -224,6 +232,7 @@ impl ProviderCredentialState { inner.static_credential_bindings.clear(); inner.known_static_credential_keys.clear(); inner.static_credential_identity_epochs.clear(); + inner.body_inventory_available = false; inner.current.child_env.len() } @@ -269,6 +278,23 @@ impl ProviderCredentialState { port: u16, path: &str, ) -> (Option>, u64) { + let (resolver, _, revision) = + self.resolver_and_body_classifier_for_endpoint(host, port, path); + (resolver, revision) + } + + /// Obtain value resolution and body classification from the same revision. + #[must_use] + pub fn resolver_and_body_classifier_for_endpoint( + &self, + host: &str, + port: u16, + path: &str, + ) -> ( + Option>, + Option>, + u64, + ) { let request_path = path.split_once('?').map_or(path, |(path, _)| path); let request_path = crate::secrets::redact_target_for_policy(request_path); let normalized_host = host.to_ascii_lowercase(); @@ -282,7 +308,7 @@ impl ProviderCredentialState { // Binding authorization must not depend on real credential // material. Malformed placeholder syntax cannot be normalized // safely, so expose no endpoint-scoped resolver. - return (None, revision); + return (None, None, revision); }; let allowed: HashSet = inner .static_credential_bindings @@ -294,6 +320,28 @@ impl ProviderCredentialState { }) .map(|(key, _)| key.clone()) .collect(); + let classifier = inner.body_inventory_available.then(|| { + Arc::new(crate::secrets::body::BodyCredentialClassifier::new( + inner.combined_resolver.as_deref(), + inner + .known_body_keys + .union(&inner.known_static_credential_keys) + .cloned() + .collect(), + inner.static_credential_bindings.keys().cloned().collect(), + inner + .static_credential_identity_epochs + .iter() + .filter(|(key, epoch)| { + inner + .static_credential_bindings + .get(*key) + .is_some_and(|binding| binding.credential_identity == epoch.identity) + }) + .map(|(key, epoch)| (key.clone(), epoch.revisions.clone())) + .collect(), + )) + }); let resolver = inner.combined_resolver.as_ref().map(|resolver| { let revision_fallback_allowed_revisions = inner .static_credential_identity_epochs @@ -313,7 +361,7 @@ impl ProviderCredentialState { revision_fallback_allowed_revisions, )) }); - (resolver, revision) + (resolver, classifier, revision) } #[must_use] @@ -483,6 +531,9 @@ impl ProviderCredentialState { child_env, dynamic_credentials, }); + inner.body_inventory_available = true; + let body_keys = inner.current.child_env.keys().cloned().collect::>(); + inner.known_body_keys.extend(body_keys); inner.current_resolver = current_resolver.map(Arc::new); if let Some(resolver) = generation_resolver { @@ -545,6 +596,9 @@ impl ProviderCredentialState { child_env, dynamic_credentials, }); + inner.body_inventory_available = true; + let body_keys = inner.current.child_env.keys().cloned().collect::>(); + inner.known_body_keys.extend(body_keys); inner.current_resolver = current_resolver.map(Arc::new); if static_credential_identities(&inner.static_credential_bindings) != static_credential_identities(&static_credential_bindings) @@ -606,6 +660,7 @@ impl ProviderCredentialState { inner.combined_resolver = None; inner.non_secret_environment_keys.clear(); inner.static_credential_bindings.clear(); + inner.body_inventory_available = false; } } @@ -799,6 +854,161 @@ mod tests { use super::*; use crate::google_cloud; + #[test] + fn body_classification_distinguishes_literal_foreign_bound_and_revoked() { + use crate::secrets::body::BodyCredentialError; + let state = ProviderCredentialState::from_bound_environment( + 42, + HashMap::from([("API_KEY".into(), "test-secret".into())]), + HashMap::new(), + HashMap::new(), + HashMap::from([( + "API_KEY".into(), + binding("api.github.com", 443, "/allowed/**"), + )]), + vec![], + ) + .unwrap(); + let token = state.snapshot().child_env["API_KEY"].clone(); + for (host, port, path) in [ + ("api.openai.com", 443, "/v1/responses"), + ("api.github.com", 443, "/allowed/foo"), + ("api.github.com", 444, "/allowed/foo"), + ("api.github.com", 443, "/other"), + ] { + let (_, classifier, _) = + state.resolver_and_body_classifier_for_endpoint(host, port, path); + let classifier = classifier.unwrap(); + assert_eq!(classifier.check(&token), Ok(())); + assert_eq!( + classifier.check("sk-OPENSHELL-RESOLVE-ENV-v42_API_KEY"), + Ok(()) + ); + assert_eq!(classifier.check("openshell:resolve:env:KEY"), Ok(())); + assert_eq!(classifier.check("sk-OPENSHELL-RESOLVE-ENV-KEY"), Ok(())); + assert_eq!( + classifier.check("openshell:resolve:env:v999_API_KEY"), + Err(BodyCredentialError::KnownUnavailable) + ); + assert_eq!( + classifier.check("openshell:resolve:env:API_KEY"), + Err(BodyCredentialError::KnownUnavailable) + ); + assert_eq!( + classifier.check("openshell:resolve:env:sbroken_API_KEY"), + Err(BodyCredentialError::KnownUnavailable) + ); + } + let (_, classifier, _) = + state.resolver_and_body_classifier_for_endpoint("api.github.com", 443, "/allowed/foo"); + assert_eq!(classifier.unwrap().check(&token), Ok(())); + assert_eq!( + state + .resolver_and_body_classifier_for_endpoint("api.github.com", 443, "/allowed/foo") + .1 + .unwrap() + .check("sk-OPENSHELL-RESOLVE-ENV-v42_API_KEY"), + Ok(()) + ); + state.revoke_static_provider_environment(43); + assert!( + state + .resolver_and_body_classifier_for_endpoint("api.openai.com", 443, "/") + .1 + .is_none() + ); + state + .install_bound_environment( + 44, + HashMap::new(), + HashMap::new(), + HashMap::new(), + HashMap::new(), + vec![], + ) + .unwrap(); + let classifier = state + .resolver_and_body_classifier_for_endpoint("api.openai.com", 443, "/") + .1 + .unwrap(); + assert_eq!( + classifier.check(&token), + Err(BodyCredentialError::KnownUnavailable) + ); + assert_eq!(classifier.check("openshell:resolve:env:KEY"), Ok(())); + } + + #[test] + fn body_classification_rejects_expired_invalid_and_replaced_credentials() { + use crate::secrets::body::BodyCredentialError; + for (value, expires) in [("secret", 1), ("bad\r\nvalue", 0)] { + let state = ProviderCredentialState::from_bound_environment( + 42, + HashMap::from([("API_KEY".into(), value.into())]), + HashMap::from([("API_KEY".into(), expires)]), + HashMap::new(), + HashMap::from([("API_KEY".into(), binding("api.github.com", 443, "/**"))]), + vec![], + ) + .unwrap(); + let token = state.snapshot().child_env["API_KEY"].clone(); + for host in ["api.openai.com", "api.github.com"] { + let classifier = state + .resolver_and_body_classifier_for_endpoint(host, 443, "/") + .1 + .unwrap(); + assert_eq!( + classifier.check(&token), + Err(BodyCredentialError::KnownUnavailable) + ); + } + } + let handle = "a".repeat(64); + let state = ProviderCredentialState::from_bound_environment( + 42, + HashMap::from([("API_KEY".into(), "secret".into())]), + HashMap::new(), + HashMap::new(), + HashMap::from([( + "API_KEY".into(), + stable_binding("api.github.com", 443, "/**", &handle), + )]), + vec![], + ) + .unwrap(); + let token = state.snapshot().child_env["API_KEY"].clone(); + let classifier = state + .resolver_and_body_classifier_for_endpoint("api.openai.com", 443, "/") + .1 + .unwrap(); + assert_eq!(classifier.check(&token), Ok(())); + assert_eq!( + classifier.check(&token.replace(&handle, &"b".repeat(64))), + Err(BodyCredentialError::KnownUnavailable) + ); + state + .install_bound_environment( + 43, + HashMap::from([("API_KEY".into(), "new-secret".into())]), + HashMap::new(), + HashMap::new(), + HashMap::from([( + "API_KEY".into(), + stable_binding("api.github.com", 443, "/**", &"b".repeat(64)), + )]), + vec![], + ) + .unwrap(); + assert_eq!( + state + .resolver_and_body_classifier_for_endpoint("api.openai.com", 443, "/") + .1 + .unwrap() + .check(&token), + Err(BodyCredentialError::KnownUnavailable) + ); + } + fn binding(host: &str, port: u32, path: &str) -> StaticCredentialBinding { StaticCredentialBinding { endpoints: vec![StaticCredentialEndpointBinding { diff --git a/crates/openshell-core/src/secrets.rs b/crates/openshell-core/src/secrets.rs index 0ec130bd8e..479d2b4a2c 100644 --- a/crates/openshell-core/src/secrets.rs +++ b/crates/openshell-core/src/secrets.rs @@ -1,6 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +#[path = "secrets_body.rs"] +pub mod body; + use crate::time::now_ms; use base64::Engine as _; use std::collections::{HashMap, HashSet}; diff --git a/crates/openshell-core/src/secrets_body.rs b/crates/openshell-core/src/secrets_body.rs new file mode 100644 index 0000000000..c9464f8e50 --- /dev/null +++ b/crates/openshell-core/src/secrets_body.rs @@ -0,0 +1,482 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Metadata-only classification for REST bodies whose credential rewrite is disabled. + +use super::{ + CREDENTIAL_MARKER_SCAN_TAIL_BYTES, PLACEHOLDER_PREFIX, PROVIDER_ALIAS_MARKER, SecretResolver, + alias_env_key, is_alias_token_char, is_env_key_char, now_ms, placeholder_env_key, + placeholder_for_env_key, revisioned_placeholder_parts, split_revisioned_env_key, + stable_placeholder_parts, validate_resolved_secret, +}; +use std::collections::{HashMap, HashSet}; +use std::fmt; +use std::sync::Arc; + +/// Why a reserved body token cannot be forwarded. Contains no request data. +#[derive(Clone, Copy, Debug, PartialEq, Eq, miette::Diagnostic)] +pub enum BodyCredentialError { + KnownUnavailable, + ClassificationUnavailable, + InvalidToken, + TokenTooLong, + Trailer, +} + +impl BodyCredentialError { + pub const fn reason(self) -> &'static str { + match self { + Self::KnownUnavailable => "known_unavailable", + Self::ClassificationUnavailable => "classification_unavailable", + Self::InvalidToken => "invalid_token", + Self::TokenTooLong => "token_too_long", + Self::Trailer => "trailer", + } + } +} + +impl fmt::Display for BodyCredentialError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "request body credential placeholder denied because rewrite is disabled ({})", + self.reason() + ) + } +} +impl std::error::Error for BodyCredentialError {} + +#[derive(Clone, Copy)] +struct ValueStatus { + valid: bool, + expires_at_ms: i64, +} + +/// Immutable classification snapshot. It deliberately contains no secret values. +#[derive(Clone, Default)] +pub struct BodyCredentialClassifier { + values: HashMap, + known: HashSet, + bound: HashSet, + revisions: HashMap>>, +} + +impl fmt::Debug for BodyCredentialClassifier { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("BodyCredentialClassifier") + .finish_non_exhaustive() + } +} + +impl BodyCredentialClassifier { + pub(crate) fn new( + resolver: Option<&SecretResolver>, + known: HashSet, + bound: HashSet, + revisions: HashMap>>, + ) -> Self { + let mut result = Self { + known, + bound, + revisions, + ..Self::default() + }; + if let Some(resolver) = resolver { + for (token, value) in &resolver.by_placeholder { + if let Some(key) = placeholder_env_key(token) { + result.known.insert(key.to_owned()); + } + result.values.insert( + token.clone(), + ValueStatus { + valid: validate_resolved_secret(&value.value).is_ok(), + expires_at_ms: value.expires_at_ms, + }, + ); + } + } + result + } + + /// Authorize forwarding a complete token unchanged; never resolve it. + pub fn check(&self, token: &str) -> Result<(), BodyCredentialError> { + // Provider-shaped aliases use canonical-key fallback in the resolver. + // Normalize that spelling here too, including revision/handle suffixes. + if let Some(key) = alias_env_key(token) { + return self.check(&placeholder_for_env_key(key)); + } + let key = placeholder_env_key(token).ok_or(BodyCredentialError::InvalidToken)?; + if key.is_empty() || !key.bytes().all(is_env_key_char) { + return Err(BodyCredentialError::InvalidToken); + } + // Reserved identity namespaces must parse completely, including u64 overflow. + if let Some(suffix) = token.strip_prefix(PLACEHOLDER_PREFIX) + && split_revisioned_env_key(suffix).is_some() + && revisioned_placeholder_parts(token).is_none() + { + return Err(BodyCredentialError::InvalidToken); + } + if let Some(suffix) = token.strip_prefix(PLACEHOLDER_PREFIX) + && let Some((identity, underlying)) = suffix.split_once('_') + && (identity.starts_with('v') || identity.starts_with('s')) + && self.known.contains(underlying) + && revisioned_placeholder_parts(token).is_none() + && stable_placeholder_parts(token).is_none() + { + return Err(BodyCredentialError::KnownUnavailable); + } + if !self.known.contains(key) { + return Ok(()); + } + // A tombstone or a legacy unbound key is not a currently issued credential. + // Destination membership does not matter: this guard never resolves body text. + if !self.bound.contains(key) { + return Err(BodyCredentialError::KnownUnavailable); + } + let revision = revisioned_placeholder_parts(token); + if revision.is_none() && stable_placeholder_parts(token).is_none() { + return Err(BodyCredentialError::KnownUnavailable); + } + if let Some((revision, _)) = revision + && self + .revisions + .get(key) + .is_none_or(|allowed| !allowed.contains(&revision)) + { + return Err(BodyCredentialError::KnownUnavailable); + } + let value = self + .values + .get(token) + .or_else(|| revision.and_then(|_| self.values.get(&placeholder_for_env_key(key)))) + .ok_or(BodyCredentialError::KnownUnavailable)?; + if !value.valid || (value.expires_at_ms > 0 && value.expires_at_ms <= now_ms()) { + return Err(BodyCredentialError::KnownUnavailable); + } + Ok(()) + } +} + +/// Maximum retained candidate on the wire, including percent encoding. +const MAX_BODY_TOKEN_BYTES: usize = 4096; + +/// Withholds complete reserved candidates while streaming unrelated body bytes. +#[derive(Default)] +pub struct BodyPlaceholderGuard<'a> { + pending: Vec, + classifier: Option<&'a BodyCredentialClassifier>, + previous_decoded: Option, +} + +impl<'a> BodyPlaceholderGuard<'a> { + pub fn new(classifier: Option<&'a BodyCredentialClassifier>) -> Self { + Self { + classifier, + ..Self::default() + } + } + + pub fn push(&mut self, bytes: &[u8]) -> Result, BodyCredentialError> { + let mut output = Vec::new(); + // Bound pending storage even if the caller supplies an entire large body. + for block in bytes.chunks(MAX_BODY_TOKEN_BYTES) { + self.pending.extend_from_slice(block); + output.extend(self.release(false)?); + } + Ok(output) + } + + pub fn finish(mut self) -> Result, BodyCredentialError> { + self.release(true) + } + + fn release(&mut self, eof: bool) -> Result, BodyCredentialError> { + // Track wire offsets so permitted bytes are released without normalization. + let mut decoded = Vec::new(); + let mut offsets = Vec::new(); + let mut wire = 0; + while wire < self.pending.len() { + offsets.push(wire); + if self.pending[wire] == b'%' { + if wire + 2 >= self.pending.len() && !eof { + offsets.pop(); + break; + } + if let Some(pair) = self.pending.get(wire + 1..wire + 3) + && let (Some(hi), Some(lo)) = ( + (pair[0] as char).to_digit(16), + (pair[1] as char).to_digit(16), + ) + { + decoded.push(u8::try_from(hi * 16 + lo).expect("two hex digits fit a byte")); + wire += 3; + continue; + } + } + decoded.push(self.pending[wire]); + wire += 1; + } + offsets.push(wire); + let mut safe = if eof { + wire + } else { + wire.saturating_sub(CREDENTIAL_MARKER_SCAN_TAIL_BYTES) + }; + let mut pos = 0; + while pos < decoded.len() { + let canonical = decoded[pos..].starts_with(PLACEHOLDER_PREFIX.as_bytes()); + let alias = decoded[pos..].starts_with(PROVIDER_ALIAS_MARKER.as_bytes()); + if !canonical && !alias { + pos += 1; + continue; + } + let start = pos; + let key_start = pos + + if canonical { + PLACEHOLDER_PREFIX.len() + } else { + PROVIDER_ALIAS_MARKER.len() + }; + let mut end = key_start; + while end < decoded.len() && is_env_key_char(decoded[end]) { + // Adjacent canonical references are separate tokens. + if end > key_start && decoded[end..].starts_with(PLACEHOLDER_PREFIX.as_bytes()) { + break; + } + end += 1; + } + if offsets[end] - offsets[start] > MAX_BODY_TOKEN_BYTES { + return Err(BodyCredentialError::TokenTooLong); + } + if end == decoded.len() && !eof { + // Without metadata, preserve the prefix-only fail-closed behavior. + if self.classifier.is_none() { + return Err(BodyCredentialError::ClassificationUnavailable); + } + safe = safe.min(offsets[start]); + break; + } + if end == key_start { + return Err(BodyCredentialError::InvalidToken); + } + let mut token = String::new(); + if alias { + if decoded + .get(end) + .is_some_and(|byte| is_alias_token_char(*byte)) + { + return Err(BodyCredentialError::InvalidToken); + } + let previous = start + .checked_sub(1) + .map(|i| decoded[i]) + .or(self.previous_decoded); + if previous.is_none_or(|byte| !is_alias_token_char(byte)) { + return Err(BodyCredentialError::InvalidToken); + } + // Alias prefix spelling does not select the env key. + token.push('x'); + } + token.push_str( + std::str::from_utf8(&decoded[start..end]) + .map_err(|_| BodyCredentialError::InvalidToken)?, + ); + self.classifier + .ok_or(BodyCredentialError::ClassificationUnavailable)? + .check(&token)?; + safe = safe.max(offsets[end]); + pos = end; + } + // Never split a percent triplet, which would change the next scan's view. + let index = offsets + .partition_point(|offset| *offset <= safe) + .saturating_sub(1); + safe = offsets[index]; + if index > 0 { + self.previous_decoded = Some(decoded[index - 1]); + } + Ok(self.pending.drain(..safe).collect()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn encode_all(token: &str) -> String { + use std::fmt::Write as _; + let mut encoded = String::new(); + for byte in token.bytes() { + write!(encoded, "%{byte:02X}").unwrap(); + } + encoded + } + + #[test] + fn unknown_conversation_tokens_survive_every_wire_split() { + let classifier = BodyCredentialClassifier::default(); + for token in [ + "openshell:resolve:env:KEY", + "sk-OPENSHELL-RESOLVE-ENV-KEY", + "openshell:resolve:env:v42_KEY", + "openshell:resolve:env:s0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef_KEY", + ] { + for encoded in [false, true] { + let token = if encoded { + encode_all(token) + } else { + token.to_owned() + }; + let body = format!("{{\"tool_output\":\"{} {token}\"}}", "a".repeat(100)); + for split in 0..=body.len() { + let mut guard = BodyPlaceholderGuard::new(Some(&classifier)); + let mut output = guard.push(&body.as_bytes()[..split]).unwrap(); + output.extend(guard.push(&body.as_bytes()[split..]).unwrap()); + output.extend(guard.finish().unwrap()); + assert_eq!(output, body.as_bytes(), "split {split}"); + } + } + } + } + + #[test] + fn issued_tokens_survive_every_wire_split_without_secret_substitution() { + use crate::proto::{StaticCredentialBinding, StaticCredentialEndpointBinding}; + use crate::provider_credentials::ProviderCredentialState; + for handle in [String::new(), "a".repeat(64)] { + let state = ProviderCredentialState::from_bound_environment( + 42, + HashMap::from([("KEY".into(), "private-test-secret".into())]), + HashMap::new(), + HashMap::new(), + HashMap::from([( + "KEY".into(), + StaticCredentialBinding { + credential_identity: "provider".into(), + workload_credential_handle: handle, + endpoints: vec![StaticCredentialEndpointBinding { + host: "api.example.com".into(), + port: 443, + path: "/**".into(), + }], + }, + )]), + vec![], + ) + .unwrap(); + let token = state.snapshot().child_env["KEY"].clone(); + let alias = format!( + "sk-OPENSHELL-RESOLVE-ENV-{}", + token.strip_prefix(PLACEHOLDER_PREFIX).unwrap() + ); + for host in ["api.example.com", "other.example.com"] { + let (_, classifier, _) = + state.resolver_and_body_classifier_for_endpoint(host, 443, "/chat"); + for token in [&token, &alias] { + for wire_token in [token.clone(), encode_all(token), token.replace(':', "%3a")] + { + // JSON, arbitrary binary, and EOF-terminated tokens use the same streaming contract. + for body in [ + format!(r#"{{"output":"{wire_token}"}}"#).into_bytes(), + [b"\xff\0".as_slice(), wire_token.as_bytes()].concat(), + ] { + for split in 0..=body.len() { + let mut guard = BodyPlaceholderGuard::new(classifier.as_deref()); + let mut output = guard.push(&body[..split]).unwrap(); + output.extend(guard.push(&body[split..]).unwrap()); + output.extend(guard.finish().unwrap()); + assert_eq!(output, body, "host {host}, split {split}"); + assert!( + !String::from_utf8_lossy(&output) + .contains("private-test-secret") + ); + } + } + } + } + } + } + } + + #[test] + fn unavailable_tokens_never_release_the_marker_at_any_split() { + let classifier = BodyCredentialClassifier { + known: HashSet::from(["KEY".to_owned()]), + ..BodyCredentialClassifier::default() + }; + for token in ["openshell:resolve:env:KEY", "sk-OPENSHELL-RESOLVE-ENV-KEY"] { + for token in [token.to_owned(), encode_all(token)] { + let body = format!("{} {token}!", "safe ".repeat(100)); + for split in 0..body.len() { + let mut guard = BodyPlaceholderGuard::new(Some(&classifier)); + match guard.push(&body.as_bytes()[..split]) { + Err(error) => assert_eq!(error, BodyCredentialError::KnownUnavailable), + Ok(output) => { + assert!(!super::super::contains_reserved_credential_marker_bytes( + &output + )); + assert_eq!( + guard.push(&body.as_bytes()[split..]).unwrap_err(), + BodyCredentialError::KnownUnavailable + ); + } + } + } + } + } + } + + #[test] + fn eof_adjacent_tokens_and_binary_surroundings_preserve_bytes() { + let classifier = BodyCredentialClassifier::default(); + for body in [ + b"\xff\0openshell:resolve:env:KEY".as_slice(), + b"openshell:resolve:env:KEYopenshell:resolve:env:OTHER", + b"partial openshell:res", + b"openshell%3Aresolve:env:KEY%21", + ] { + let mut guard = BodyPlaceholderGuard::new(Some(&classifier)); + let mut output = Vec::new(); + for byte in body { + output.extend(guard.push(&[*byte]).unwrap()); + } + output.extend(guard.finish().unwrap()); + assert_eq!(output, body); + } + } + + #[test] + fn malformed_and_oversized_candidates_fail_closed() { + let classifier = BodyCredentialClassifier::default(); + for token in [ + "openshell:resolve:env:", + "OPENSHELL-RESOLVE-ENV-KEY", + "sk-OPENSHELL-RESOLVE-ENV-KEY-suffix", + ] { + let mut guard = BodyPlaceholderGuard::new(Some(&classifier)); + let result = guard.push(token.as_bytes()).and_then(|_| guard.finish()); + assert_eq!(result.unwrap_err(), BodyCredentialError::InvalidToken); + } + let mut guard = BodyPlaceholderGuard::new(Some(&classifier)); + let oversized = format!("openshell:resolve:env:{}", "A".repeat(MAX_BODY_TOKEN_BYTES)); + assert_eq!( + guard.push(oversized.as_bytes()).unwrap_err(), + BodyCredentialError::TokenTooLong + ); + let mut guard = BodyPlaceholderGuard::new(Some(&classifier)); + for _ in 0..1000 { + guard.push(&[b'x'; 1000]).unwrap(); + assert!(guard.pending.len() <= CREDENTIAL_MARKER_SCAN_TAIL_BYTES); + } + } + + #[test] + fn missing_metadata_denies_without_releasing_marker() { + let mut guard = BodyPlaceholderGuard::default(); + assert!(guard.push(b"openshell:res").unwrap().is_empty()); + assert_eq!( + guard.push(b"olve:env:KEY").unwrap_err(), + BodyCredentialError::ClassificationUnavailable + ); + } +} diff --git a/crates/openshell-providers/src/profiles.rs b/crates/openshell-providers/src/profiles.rs index 9cdf2257ad..c47a418d4b 100644 --- a/crates/openshell-providers/src/profiles.rs +++ b/crates/openshell-providers/src/profiles.rs @@ -3271,6 +3271,75 @@ mod tests { .unwrap_or_else(|| panic!("built-in profile {id} should exist")) } + #[test] + fn builtin_agent_conversation_defaults_preserve_own_and_foreign_body_text() { + use openshell_core::proto::{StaticCredentialBinding, StaticCredentialEndpointBinding}; + use openshell_core::provider_credentials::ProviderCredentialState; + use openshell_core::secrets::body::BodyPlaceholderGuard; + let binding = |profile: &ProviderTypeProfile| StaticCredentialBinding { + credential_identity: profile.id.clone(), + workload_credential_handle: String::new(), + endpoints: profile + .to_proto() + .endpoints + .iter() + .map(|endpoint| StaticCredentialEndpointBinding { + host: endpoint.host.clone(), + port: endpoint.port, + path: endpoint.path.clone(), + }) + .collect(), + }; + for id in ["codex", "claude-code", "copilot"] { + let profile = builtin_profile(id); + let model_key = profile.credential_env_vars()[0].to_owned(); + let state = ProviderCredentialState::from_bound_environment( + 42, + HashMap::from([ + ("GITHUB_TOKEN".into(), "github-test-secret".into()), + (model_key.clone(), "model-test-secret".into()), + ]), + HashMap::new(), + HashMap::new(), + HashMap::from([ + ("GITHUB_TOKEN".into(), binding(builtin_profile("github"))), + (model_key.clone(), binding(profile)), + ]), + vec![], + ) + .unwrap(); + for endpoint in profile + .endpoints + .iter() + .filter(|endpoint| endpoint.protocol == "rest") + { + assert!(!endpoint.request_body_credential_rewrite); + assert!(!endpoint.allow_uninspected_credentials); + let (_, classifier, _) = state.resolver_and_body_classifier_for_endpoint( + &endpoint.host, + u16::try_from(endpoint.port).unwrap(), + "/v1/responses", + ); + let classifier = classifier.unwrap(); + for token in [ + "openshell:resolve:env:KEY".to_owned(), + state.snapshot().child_env["GITHUB_TOKEN"].clone(), + state.snapshot().child_env[&model_key].clone(), + ] { + let body = format!(r#"{{"tool_output":"Token: {token}"}}"#); + let mut guard = BodyPlaceholderGuard::new(Some(&classifier)); + let mut forwarded = guard.push(body.as_bytes()).unwrap(); + forwarded.extend(guard.finish().unwrap()); + assert_eq!(forwarded, body.as_bytes()); + } + assert_eq!( + classifier.check(&state.snapshot().child_env[&model_key]), + Ok(()) + ); + } + } + } + #[test] fn builtin_profiles_are_sorted_by_id() { let ids = builtin_profiles() diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index cd2df94118..aa036dee94 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -64,6 +64,7 @@ pub struct L7EvalContext { /// resolver. Used to reject a request if credentials change again before /// its first upstream write. pub(crate) provider_credential_revision: Option, + pub(crate) body_classifier: Option>, /// Anonymous activity counter channel. pub(crate) activity_tx: Option, /// Dynamic credentials (token grants) keyed by endpoint-bound provider metadata. @@ -99,13 +100,15 @@ fn scoped_context_for_request( // credential use. Clearing the resolver makes any placeholder or // signing attempt fail closed before an upstream write. scoped.secret_resolver = None; + scoped.body_classifier = None; scoped.provider_credential_revision = None; return Some(scoped); } let credentials = ctx.provider_credentials.as_ref()?; - let (resolver, revision) = - credentials.resolver_for_endpoint_with_revision(&ctx.host, ctx.port, &request.target); + let (resolver, classifier, revision) = + credentials.resolver_and_body_classifier_for_endpoint(&ctx.host, ctx.port, &request.target); scoped.secret_resolver = resolver; + scoped.body_classifier = classifier; scoped.provider_credential_revision = Some(revision); Some(scoped) } @@ -369,6 +372,26 @@ where Ok(()) } +pub(crate) async fn reject_body_credential( + client: &mut C, + error: secrets::body::BodyCredentialError, +) -> Result<()> { + let body = serde_json::json!({"error": { + "code": "credential_placeholder_in_request_body", + "reason": error.reason(), + "message": "A credential placeholder in the request body cannot be forwarded. Remove the reference from conversation history or restore provider access; body credential rewriting is disabled." + }}).to_string(); + let response = format!( + "HTTP/1.1 403 Forbidden\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + client + .write_all(response.as_bytes()) + .await + .into_diagnostic()?; + client.flush().await.into_diagnostic() +} + async fn relay_http_request_with_credential_rejection( request: &crate::l7::provider::L7Request, client: &mut C, @@ -387,7 +410,12 @@ where { Ok(outcome) => Ok(Some(outcome)), Err(report) => { - if let Some(error) = report.downcast_ref::() { + if let Some(error) = report.downcast_ref::() { + let _ = upstream.shutdown().await; + reject_body_credential(client, *error).await?; + Ok(None) + } else if let Some(error) = report.downcast_ref::() + { reject_credential_resolution(client, ctx, error).await?; Ok(None) } else { @@ -929,6 +957,7 @@ where upstream, crate::l7::rest::RelayRequestOptions { resolver: ctx.secret_resolver.as_deref(), + body_classifier: ctx.body_classifier.as_deref(), credential_generation: credential_generation_guard(ctx), generation_guard: Some(engine.generation_guard()), websocket_extensions: websocket_extension_mode( @@ -1668,6 +1697,7 @@ where upstream, crate::l7::rest::RelayRequestOptions { resolver: ctx.secret_resolver.as_deref(), + body_classifier: ctx.body_classifier.as_deref(), credential_generation: credential_generation_guard(ctx), generation_guard: Some(engine.generation_guard()), websocket_extensions: websocket_extension_mode( @@ -2046,6 +2076,7 @@ where upstream, crate::l7::rest::RelayRequestOptions { resolver: ctx.secret_resolver.as_deref(), + body_classifier: ctx.body_classifier.as_deref(), credential_generation: credential_generation_guard(ctx), generation_guard: Some(engine.generation_guard()), ..Default::default() @@ -2281,6 +2312,7 @@ where upstream, crate::l7::rest::RelayRequestOptions { resolver: ctx.secret_resolver.as_deref(), + body_classifier: ctx.body_classifier.as_deref(), credential_generation: credential_generation_guard(ctx), generation_guard: Some(engine.generation_guard()), ..Default::default() @@ -2984,6 +3016,44 @@ mod tests { use std::path::PathBuf; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt}; + #[tokio::test] + async fn body_denial_returns_actionable_local_json() { + let req = crate::l7::provider::L7Request { + action: "POST".into(), target: "/v1/responses".into(), query_params: TestHashMap::new(), + raw_header: b"POST /v1/responses HTTP/1.1\r\nHost: api.openai.com\r\nContent-Length: 25\r\n\r\nopenshell:resolve:env:KEY".to_vec(), + body_length: crate::l7::provider::BodyLength::ContentLength(25), + }; + let (mut client, mut caller) = tokio::io::duplex(4096); + let (mut upstream, mut server) = tokio::io::duplex(4096); + let outcome = relay_http_request_with_credential_rejection( + &req, + &mut client, + &mut upstream, + crate::l7::rest::RelayRequestOptions { + deny_uninspected_credentials: true, + ..Default::default() + }, + &L7EvalContext::default(), + ) + .await + .unwrap(); + assert!(outcome.is_none()); + drop(client); + let mut response = String::new(); + caller.read_to_string(&mut response).await.unwrap(); + assert!(response.starts_with("HTTP/1.1 403 Forbidden")); + let body: serde_json::Value = + serde_json::from_str(response.split_once("\r\n\r\n").unwrap().1).unwrap(); + assert_eq!( + body["error"]["code"], + "credential_placeholder_in_request_body" + ); + assert_eq!(body["error"]["reason"], "classification_unavailable"); + let mut sent = String::new(); + server.read_to_string(&mut sent).await.unwrap(); + assert!(!sent.contains("openshell:resolve:")); + } + const TEST_POLICY: &str = include_str!("../../data/sandbox-policy.rego"); fn endpoint_binding(identity: &str) -> StaticCredentialBinding { diff --git a/crates/openshell-supervisor-network/src/l7/rest.rs b/crates/openshell-supervisor-network/src/l7/rest.rs index 42bf3a33df..d34a05bd1b 100644 --- a/crates/openshell-supervisor-network/src/l7/rest.rs +++ b/crates/openshell-supervisor-network/src/l7/rest.rs @@ -14,8 +14,8 @@ use base64::Engine as _; use miette::{IntoDiagnostic, Result, miette}; use openshell_core::proto::{ExistingHeaderAction, HeaderMutation, header_mutation}; use openshell_core::secrets::{ - CREDENTIAL_MARKER_SCAN_TAIL_BYTES, SecretResolver, contains_reserved_credential_marker, - contains_reserved_credential_marker_bytes, rewrite_http_header_block, + SecretResolver, contains_reserved_credential_marker, contains_reserved_credential_marker_bytes, + rewrite_http_header_block, }; use openshell_ocsf::ctx::ctx as ocsf_ctx; use sha1::{Digest, Sha1}; @@ -723,6 +723,7 @@ where upstream, RelayRequestOptions { resolver, + body_classifier: None, credential_generation: None, generation_guard, websocket_extensions: WebSocketExtensionMode::Preserve, @@ -748,6 +749,7 @@ pub(crate) enum WebSocketExtensionMode { #[derive(Clone, Copy, Default)] pub(crate) struct RelayRequestOptions<'a> { pub(crate) resolver: Option<&'a SecretResolver>, + pub(crate) body_classifier: Option<&'a openshell_core::secrets::body::BodyCredentialClassifier>, pub(crate) credential_generation: Option>, pub(crate) generation_guard: Option<&'a PolicyGenerationGuard>, pub(crate) websocket_extensions: WebSocketExtensionMode, @@ -1097,12 +1099,12 @@ where upstream, &rewrite_result.rewritten, &req.raw_header[header_end..], - options.generation_guard, + options, ) .await { - if error.to_string().contains("credential placeholder") { - emit_uninspected_body_credential_denial(req, &options); + if let Some(reason) = error.downcast_ref::() { + emit_uninspected_body_credential_denial(req, &options, *reason); } return Err(error); } @@ -1158,34 +1160,43 @@ where Ok(outcome) } -#[derive(Default)] -struct ReservedMarkerStreamGuard { - pending: Vec, -} +use openshell_core::secrets::body::{ + BodyCredentialError, BodyPlaceholderGuard as ReservedMarkerStreamGuard, +}; -impl ReservedMarkerStreamGuard { - fn push(&mut self, bytes: &[u8]) -> Result> { - self.pending.extend_from_slice(bytes); - if contains_reserved_credential_marker_bytes(&self.pending) { - return Err(miette!( - "request body credential placeholder denied because rewrite is disabled" - )); - } - let safe_len = self - .pending - .len() - .saturating_sub(CREDENTIAL_MARKER_SCAN_TAIL_BYTES); - Ok(self.pending.drain(..safe_len).collect()) +fn ensure_body_generation_current(options: RelayRequestOptions<'_>) -> Result<()> { + ensure_credential_generation_current(options)?; + if let Some(guard) = options.generation_guard { + guard.ensure_current()?; } + Ok(()) +} - fn finish(mut self) -> Result> { - if contains_reserved_credential_marker_bytes(&self.pending) { - return Err(miette!( - "request body credential placeholder denied because rewrite is disabled" - )); - } - Ok(std::mem::take(&mut self.pending)) +async fn write_body_bytes( + writer: &mut W, + bytes: &[u8], + options: RelayRequestOptions<'_>, +) -> Result<()> { + ensure_body_generation_current(options)?; + writer.write_all(bytes).await.into_diagnostic() +} + +async fn write_guarded_chunk( + writer: &mut W, + payload: &[u8], + options: RelayRequestOptions<'_>, +) -> Result<()> { + if payload.is_empty() { + return Ok(()); } + write_body_bytes( + writer, + format!("{:X}\r\n", payload.len()).as_bytes(), + options, + ) + .await?; + write_body_bytes(writer, payload, options).await?; + write_body_bytes(writer, b"\r\n", options).await } async fn relay_request_body_with_marker_guard( @@ -1194,30 +1205,28 @@ async fn relay_request_body_with_marker_guard( upstream: &mut U, headers: &[u8], already_read: &[u8], - generation_guard: Option<&PolicyGenerationGuard>, + options: RelayRequestOptions<'_>, ) -> Result<()> where C: AsyncRead + Unpin, U: AsyncWrite + Unpin, { + ensure_body_generation_current(options)?; upstream.write_all(headers).await.into_diagnostic()?; match req.body_length { BodyLength::None => { - let mut scanner = ReservedMarkerStreamGuard::default(); + let mut scanner = ReservedMarkerStreamGuard::new(options.body_classifier); let safe = scanner.push(already_read)?; - upstream.write_all(&safe).await.into_diagnostic()?; - upstream - .write_all(&scanner.finish()?) - .await - .into_diagnostic()?; + write_body_bytes(upstream, &safe, options).await?; + write_body_bytes(upstream, &scanner.finish()?, options).await?; } BodyLength::ContentLength(len) => { let initial_len = usize::try_from(len) .unwrap_or(usize::MAX) .min(already_read.len()); - let mut scanner = ReservedMarkerStreamGuard::default(); + let mut scanner = ReservedMarkerStreamGuard::new(options.body_classifier); let safe = scanner.push(&already_read[..initial_len])?; - upstream.write_all(&safe).await.into_diagnostic()?; + write_body_bytes(upstream, &safe, options).await?; let mut remaining = len.saturating_sub(initial_len as u64); let mut buf = vec![0u8; RELAY_BUF_SIZE]; while remaining > 0 { @@ -1230,55 +1239,37 @@ where "Connection closed with {remaining} body bytes remaining" )); } - if let Some(guard) = generation_guard { - guard.ensure_current()?; - } + ensure_body_generation_current(options)?; let safe = scanner.push(&buf[..n])?; - upstream.write_all(&safe).await.into_diagnostic()?; + write_body_bytes(upstream, &safe, options).await?; remaining -= n as u64; } - upstream - .write_all(&scanner.finish()?) - .await - .into_diagnostic()?; + write_body_bytes(upstream, &scanner.finish()?, options).await?; } BodyLength::Chunked => { - relay_chunked_with_marker_guard(client, upstream, already_read, generation_guard) - .await?; + relay_chunked_with_marker_guard(client, upstream, already_read, options).await?; } } Ok(()) } -async fn write_chunk(writer: &mut W, payload: &[u8]) -> Result<()> { - if payload.is_empty() { - return Ok(()); - } - writer - .write_all(format!("{:X}\r\n", payload.len()).as_bytes()) - .await - .into_diagnostic()?; - writer.write_all(payload).await.into_diagnostic()?; - writer.write_all(b"\r\n").await.into_diagnostic()?; - Ok(()) -} - async fn relay_chunked_with_marker_guard( client: &mut C, upstream: &mut U, already_read: &[u8], - generation_guard: Option<&PolicyGenerationGuard>, + options: RelayRequestOptions<'_>, ) -> Result<()> where C: AsyncRead + Unpin, U: AsyncWrite + Unpin, { + let generation_guard = options.generation_guard; let mut read_state = ChunkedReadState { buffered_pos: 0, wire_bytes: 0, max_wire_bytes: None, }; - let mut scanner = ReservedMarkerStreamGuard::default(); + let mut scanner = ReservedMarkerStreamGuard::new(options.body_classifier); loop { let size_line = read_chunked_line(client, already_read, &mut read_state, generation_guard) @@ -1295,20 +1286,18 @@ where .map_err(|_| miette!("Invalid chunk size token: {size_token:?}"))?; if chunk_size == 0 { - write_chunk(upstream, &scanner.finish()?).await?; - upstream.write_all(b"0\r\n").await.into_diagnostic()?; + write_guarded_chunk(upstream, &scanner.finish()?, options).await?; + write_body_bytes(upstream, b"0\r\n", options).await?; loop { let trailer = read_chunked_line(client, already_read, &mut read_state, generation_guard) .await .map_err(CollectChunkedError::into_report)?; if contains_reserved_credential_marker_bytes(&trailer) { - return Err(miette!( - "request body credential placeholder denied because rewrite is disabled" - )); + return Err(BodyCredentialError::Trailer.into()); } - upstream.write_all(&trailer).await.into_diagnostic()?; - upstream.write_all(b"\r\n").await.into_diagnostic()?; + write_body_bytes(upstream, &trailer, options).await?; + write_body_bytes(upstream, b"\r\n", options).await?; if trailer.is_empty() { return Ok(()); } @@ -1329,7 +1318,7 @@ where ) .await .map_err(CollectChunkedError::into_report)?; - write_chunk(upstream, &scanner.push(&block)?).await?; + write_guarded_chunk(upstream, &scanner.push(&block)?, options).await?; remaining -= block_len; } @@ -1350,7 +1339,11 @@ where } } -fn emit_uninspected_body_credential_denial(req: &L7Request, options: &RelayRequestOptions<'_>) { +fn emit_uninspected_body_credential_denial( + req: &L7Request, + options: &RelayRequestOptions<'_>, + reason: BodyCredentialError, +) { let event = openshell_ocsf::NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(openshell_ocsf::ActivityId::Traffic) .action(openshell_ocsf::ActionId::Denied) @@ -1367,7 +1360,20 @@ fn emit_uninspected_body_credential_denial(req: &L7Request, options: &RelayReque )) .build(); openshell_ocsf::ocsf_emit!(event); - crate::l7::emit_uninspected_credential_finding(options.host, "", "http-request-body"); + let finding = openshell_ocsf::DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(openshell_ocsf::SeverityId::High) + .finding_info(openshell_ocsf::FindingInfo::new( + "openshell.credentials.traffic_uninspectable", + "Credential-bearing traffic cannot be inspected", + )) + .evidence_pairs(&[ + ("host", options.host), + ("surface", "http-request-body"), + ("reason", reason.reason()), + ]) + .message("Request body credential placeholder denied") + .build(); + openshell_ocsf::ocsf_emit!(finding); } struct PreparedRequestBody { @@ -7212,6 +7218,141 @@ mod tests { assert!(!lower.contains("upgrade: h2c")); } + #[tokio::test] + async fn guarded_conversation_body_preserves_literals_own_and_foreign_tokens() { + use openshell_core::proto::{StaticCredentialBinding, StaticCredentialEndpointBinding}; + use openshell_core::provider_credentials::ProviderCredentialState; + let state = ProviderCredentialState::from_bound_environment( + 42, + HashMap::from([("GITHUB_TOKEN".into(), "private-test-secret".into())]), + HashMap::new(), + HashMap::new(), + HashMap::from([( + "GITHUB_TOKEN".into(), + StaticCredentialBinding { + credential_identity: "github".into(), + workload_credential_handle: String::new(), + endpoints: vec![StaticCredentialEndpointBinding { + host: "api.github.com".into(), + port: 443, + path: "/**".into(), + }], + }, + )]), + vec![], + ) + .unwrap(); + // Same REST defaults as each built-in conversation profile, with real scoped bindings. + for host in [ + "api.openai.com", + "api.anthropic.com", + "api.githubcopilot.com", + "api.github.com", + ] { + let (_, classifier, revision) = + state.resolver_and_body_classifier_for_endpoint(host, 443, "/v1/responses"); + let issued = state.snapshot().child_env["GITHUB_TOKEN"].clone(); + for token in [ + "openshell:resolve:env:KEY".to_owned(), + issued.clone(), + issued.replace(':', "%3A"), + format!( + "sk-OPENSHELL-RESOLVE-ENV-{}", + issued.strip_prefix("openshell:resolve:env:").unwrap() + ), + ] { + let body = format!( + r#"{{"input":[{{"type":"function_call_output","output":"Token: {token}"}}]}}"# + ); + for chunked in [false, true] { + let wire = if chunked { + let mut wire = Vec::new(); + for byte in body.bytes() { + wire.extend_from_slice(&[b'1', b'\r', b'\n', byte, b'\r', b'\n']); + } + wire.extend_from_slice(b"0\r\n\r\n"); + wire + } else { + body.as_bytes().to_vec() + }; + let req = L7Request { + action: "POST".into(), + target: "/v1/responses".into(), + query_params: HashMap::new(), + raw_header: Vec::new(), + body_length: if chunked { + BodyLength::Chunked + } else { + BodyLength::ContentLength(wire.len() as u64) + }, + }; + let mut input = wire.as_slice(); + let mut output = Vec::new(); + relay_request_body_with_marker_guard( + &req, + &mut input, + &mut output, + b"", + b"", + RelayRequestOptions { + body_classifier: classifier.as_deref(), + credential_generation: Some(CredentialGenerationGuard::new( + &state, revision, + )), + ..Default::default() + }, + ) + .await + .unwrap(); + if chunked { + let mut cursor = output.as_slice(); + let mut decoded = Vec::new(); + loop { + let end = cursor.windows(2).position(|w| w == b"\r\n").unwrap(); + let len = usize::from_str_radix( + std::str::from_utf8(&cursor[..end]).unwrap(), + 16, + ) + .unwrap(); + cursor = &cursor[end + 2..]; + if len == 0 { + break; + } + decoded.extend_from_slice(&cursor[..len]); + cursor = &cursor[len + 2..]; + } + assert_eq!(decoded, body.as_bytes()); + } else { + assert_eq!(output, body.as_bytes()); + } + assert!(!String::from_utf8_lossy(&output).contains("private-test-secret")); + } + } + } + } + + #[tokio::test] + async fn guarded_body_rejects_stale_credentials_before_writing() { + let state = openshell_core::provider_credentials::ProviderCredentialState::from_environment( + 1, + HashMap::new(), + HashMap::new(), + HashMap::new(), + ); + let options = RelayRequestOptions { + credential_generation: Some(CredentialGenerationGuard::new(&state, 1)), + ..Default::default() + }; + state.revoke_static_provider_environment(2); + let mut output = Vec::new(); + assert!( + write_body_bytes(&mut output, b"must not forward", options) + .await + .is_err() + ); + assert!(output.is_empty()); + } + #[test] fn streamed_body_guard_detects_marker_split_across_reads() { let mut guard = ReservedMarkerStreamGuard::default(); @@ -7304,7 +7445,7 @@ mod tests { &mut tokio::io::empty(), &mut upstream_writer, wire, - None, + RelayRequestOptions::default(), ) .await .expect_err("encoded placeholder must fail closed"); diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index add7be9b33..e3a481941c 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -3650,6 +3650,7 @@ fn endpoint_secret_resolver( } struct ForwardEndpointCredentials { + body_classifier: Option>, resolver: Option>, revision: Option, } @@ -3664,12 +3665,14 @@ fn endpoint_credentials_for_request( let Some(credentials) = provider_credentials else { return ForwardEndpointCredentials { resolver: fallback, + body_classifier: None, revision: None, }; }; - let (resolver, revision) = - credentials.resolver_for_endpoint_with_revision(host, port, canonical_path); + let (resolver, body_classifier, revision) = + credentials.resolver_and_body_classifier_for_endpoint(host, port, canonical_path); ForwardEndpointCredentials { + body_classifier, resolver, revision: Some(revision), } @@ -3779,7 +3782,6 @@ fn rewrite_forward_request( path: &str, canonical_authority: &str, secret_resolver: Option<&SecretResolver>, - request_body_credential_rewrite: bool, ) -> Result, secrets::UnresolvedPlaceholderError> { let header_end = raw[..used] .windows(4) @@ -3898,13 +3900,10 @@ fn rewrite_forward_request( output.extend_from_slice(&overflow[..body_prefix_len]); } - // Fail-closed: scan for any remaining unresolved placeholders - let scan_end = if request_body_credential_rewrite { - rewritten_header_end - } else { - output.len() - }; - let output_str = String::from_utf8_lossy(&output[..scan_end]); + // Header resolution only owns headers. Body bytes from the initial read + // must reach the same guarded relay as bytes read later, regardless of + // whether that relay classifies literal text or explicitly rewrites it. + let output_str = String::from_utf8_lossy(&output[..rewritten_header_end]); if output_str.contains(secrets::PLACEHOLDER_PREFIX_PUBLIC) || output_str.contains(secrets::PROVIDER_ALIAS_MARKER_PUBLIC) { @@ -3975,6 +3974,7 @@ fn complete_chunked_body_prefix_len(bytes: &[u8]) -> Option { } struct ForwardRelayOptions<'a> { + body_classifier: Option<&'a secrets::body::BodyCredentialClassifier>, generation_guard: &'a PolicyGenerationGuard, credential_generation: Option>, websocket_extensions: crate::l7::rest::WebSocketExtensionMode, @@ -4021,6 +4021,7 @@ where upstream, crate::l7::rest::RelayRequestOptions { resolver: options.secret_resolver, + body_classifier: options.body_classifier, credential_generation: options.credential_generation, generation_guard: Some(options.generation_guard), websocket_extensions: options.websocket_extensions, @@ -5131,7 +5132,6 @@ async fn handle_forward_proxy( &upstream_target, &canonical_authority, secret_resolver.as_deref(), - request_body_credential_rewrite, ) { Ok(bytes) => bytes, Err(e) => { @@ -5330,6 +5330,7 @@ async fn handle_forward_proxy( credential_generation, websocket_extensions, secret_resolver: secret_resolver.as_deref(), + body_classifier: endpoint_credentials.body_classifier.as_deref(), request_body_credential_rewrite, deny_uninspected_credentials, credential_signing, @@ -5342,6 +5343,16 @@ async fn handle_forward_proxy( .await; let outcome_result = match outcome_result { Err(report) => { + if let Some(error) = report.downcast_ref::() { + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::MiddlewareSessionEndReason::Cancellation) + .await; + } + let _ = upstream.shutdown().await; + crate::l7::relay::reject_body_credential(client, *error).await?; + return Ok(()); + } if let Some(error) = report.downcast_ref::() { if let Some(session) = middleware_session.take() { session @@ -7266,7 +7277,6 @@ network_policies: &prepared.upstream_target, "api.example.test", credentials.resolver.as_deref(), - false, ); assert!( rewrite.is_err(), @@ -7358,6 +7368,25 @@ network_policies: raw: &[u8], resolver: Option<&SecretResolver>, request_body_credential_rewrite: bool, + ) -> Result { + relay_forward_request_and_capture_classified( + method, + path, + raw, + resolver, + request_body_credential_rewrite, + None, + ) + .await + } + + async fn relay_forward_request_and_capture_classified( + method: &str, + path: &str, + raw: &[u8], + resolver: Option<&SecretResolver>, + request_body_credential_rewrite: bool, + body_classifier: Option<&secrets::body::BodyCredentialClassifier>, ) -> Result { let guard = forward_test_guard(); let target_uri = std::str::from_utf8(raw) @@ -7368,15 +7397,8 @@ network_policies: .expect("forward test request has an absolute target"); let (_, host, port, _) = parse_proxy_uri(target_uri)?; let authority = canonical_forward_authority(&host, port); - let rewritten = rewrite_forward_request( - raw, - raw.len(), - path, - &authority, - resolver, - request_body_credential_rewrite, - ) - .map_err(|e| miette::miette!("{e}"))?; + let rewritten = rewrite_forward_request(raw, raw.len(), path, &authority, resolver) + .map_err(|e| miette::miette!("{e}"))?; let (mut proxy_to_upstream, mut upstream_side) = tokio::io::duplex(8192); let (mut _app_side, mut proxy_to_client) = tokio::io::duplex(8192); @@ -7427,10 +7449,11 @@ network_policies: ForwardRelayOptions { generation_guard: &guard, credential_generation: None, + body_classifier, websocket_extensions: crate::l7::rest::WebSocketExtensionMode::Preserve, secret_resolver: resolver, request_body_credential_rewrite, - deny_uninspected_credentials: false, + deny_uninspected_credentials: body_classifier.is_some(), credential_signing: crate::l7::CredentialSigning::None, signing_service: "", signing_region: "", @@ -7672,7 +7695,6 @@ network_policies: path, &canonical_forward_authority(&host, port), None, - false, ) .expect("forward websocket request should rewrite to origin form"); let websocket_extensions = crate::l7::relay::websocket_extension_mode(&config, false); @@ -7692,6 +7714,7 @@ network_policies: ForwardRelayOptions { generation_guard: guard, credential_generation: None, + body_classifier: None, websocket_extensions, secret_resolver: None, request_body_credential_rewrite: false, @@ -9646,7 +9669,6 @@ network_policies: "/v1/projects", "api.example.test:8080", None, - false, ) .expect("forward request should rewrite"); let rewritten = String::from_utf8_lossy(&rewritten); @@ -9672,7 +9694,6 @@ network_policies: "/v1/projects", "api.example.test:8080", None, - false, ) .expect("forward request should rewrite"); let rewritten = String::from_utf8_lossy(&rewritten); @@ -9720,7 +9741,7 @@ network_policies: fn test_rewrite_get_request() { let raw = b"GET http://10.0.0.1:8000/api HTTP/1.1\r\nHost: 10.0.0.1:8000\r\nAccept: */*\r\n\r\n"; - let result = rewrite_forward_request(raw, raw.len(), "/api", "10.0.0.1:8000", None, false) + let result = rewrite_forward_request(raw, raw.len(), "/api", "10.0.0.1:8000", None) .expect("should succeed"); let result_str = String::from_utf8_lossy(&result); assert!(result_str.starts_with("GET /api HTTP/1.1\r\n")); @@ -9767,7 +9788,7 @@ network_policies: assert!(!canonical.contains("second.example.test")); assert!(canonical.ends_with("\r\n\r\nbody")); - let rewritten = rewrite_forward_request(raw, raw.len(), "/api", authority, None, false) + let rewritten = rewrite_forward_request(raw, raw.len(), "/api", authority, None) .expect("final rewrite enforces canonical Host"); let rewritten = String::from_utf8(rewritten).expect("rewritten request is UTF-8"); assert_eq!( @@ -9852,7 +9873,6 @@ network_policies: "/api", authority, None, - false, ) .expect("rewrite middleware-selected request"); let rewritten = String::from_utf8(rewritten).expect("rewritten request is UTF-8"); @@ -9873,8 +9893,8 @@ network_policies: #[test] fn test_rewrite_strips_proxy_headers() { let raw = b"GET http://host/p HTTP/1.1\r\nHost: host\r\nProxy-Authorization: Basic abc\r\nProxy-Connection: keep-alive\r\nAccept: */*\r\n\r\n"; - let result = rewrite_forward_request(raw, raw.len(), "/p", "host", None, false) - .expect("should succeed"); + let result = + rewrite_forward_request(raw, raw.len(), "/p", "host", None).expect("should succeed"); let result_str = String::from_utf8_lossy(&result); assert!( !result_str @@ -9888,8 +9908,8 @@ network_policies: #[test] fn test_rewrite_replaces_connection_header() { let raw = b"GET http://host/p HTTP/1.1\r\nHost: host\r\nConnection: keep-alive\r\n\r\n"; - let result = rewrite_forward_request(raw, raw.len(), "/p", "host", None, false) - .expect("should succeed"); + let result = + rewrite_forward_request(raw, raw.len(), "/p", "host", None).expect("should succeed"); let result_str = String::from_utf8_lossy(&result); assert!(result_str.contains("Connection: close")); assert!(!result_str.contains("keep-alive")); @@ -9898,8 +9918,8 @@ network_policies: #[test] fn test_rewrite_strips_connection_nominated_headers() { let raw = b"GET http://host/p HTTP/1.1\r\nHost: host\r\nX-Guard: hidden\r\nConnection: keep-alive, x-guard\r\nKeep-Alive: timeout=5\r\nX-Visible: yes\r\n\r\n"; - let result = rewrite_forward_request(raw, raw.len(), "/p", "host", None, false) - .expect("should succeed"); + let result = + rewrite_forward_request(raw, raw.len(), "/p", "host", None).expect("should succeed"); let result_str = String::from_utf8_lossy(&result); let lower = result_str.to_ascii_lowercase(); @@ -9912,8 +9932,8 @@ network_policies: #[test] fn test_rewrite_preserves_body_overflow() { let raw = b"POST http://host/api HTTP/1.1\r\nHost: host\r\nContent-Length: 13\r\n\r\n{\"key\":\"val\"}"; - let result = rewrite_forward_request(raw, raw.len(), "/api", "host", None, false) - .expect("should succeed"); + let result = + rewrite_forward_request(raw, raw.len(), "/api", "host", None).expect("should succeed"); let result_str = String::from_utf8_lossy(&result); assert!(result_str.contains("{\"key\":\"val\"}")); assert!(result_str.contains("POST /api HTTP/1.1")); @@ -9922,8 +9942,8 @@ network_policies: #[test] fn test_rewrite_preserves_existing_via() { let raw = b"GET http://host/p HTTP/1.1\r\nHost: host\r\nVia: 1.0 upstream\r\n\r\n"; - let result = rewrite_forward_request(raw, raw.len(), "/p", "host", None, false) - .expect("should succeed"); + let result = + rewrite_forward_request(raw, raw.len(), "/p", "host", None).expect("should succeed"); let result_str = String::from_utf8_lossy(&result); assert!(result_str.contains("Via: 1.0 upstream")); // Should not add a second Via header @@ -9946,7 +9966,7 @@ network_policies: .expect("canonicalization should succeed for the attack payload"); assert_eq!(canon.path, "/secret"); - let rewritten = rewrite_forward_request(raw, raw.len(), &canon.path, "host", None, false) + let rewritten = rewrite_forward_request(raw, raw.len(), &canon.path, "host", None) .expect("rewrite_forward_request should succeed"); let rewritten_str = String::from_utf8_lossy(&rewritten); assert!( @@ -9972,9 +9992,8 @@ network_policies: _ => canon.path, }; - let rewritten = - rewrite_forward_request(raw, raw.len(), &upstream_target, "host", None, false) - .expect("rewrite_forward_request should succeed"); + let rewritten = rewrite_forward_request(raw, raw.len(), &upstream_target, "host", None) + .expect("rewrite_forward_request should succeed"); let rewritten_str = String::from_utf8_lossy(&rewritten); assert!( rewritten_str.starts_with( @@ -9992,14 +10011,84 @@ network_policies: .collect(), ); let raw = b"GET http://host/p HTTP/1.1\r\nHost: host\r\nAuthorization: Bearer openshell:resolve:env:ANTHROPIC_API_KEY\r\n\r\n"; - let result = - rewrite_forward_request(raw, raw.len(), "/p", "host", resolver.as_ref(), false) - .expect("should succeed"); + let result = rewrite_forward_request(raw, raw.len(), "/p", "host", resolver.as_ref()) + .expect("should succeed"); let result_str = String::from_utf8_lossy(&result); assert!(result_str.contains("Authorization: Bearer sk-test")); assert!(!result_str.contains("openshell:resolve:env:ANTHROPIC_API_KEY")); } + #[tokio::test] + async fn forward_initial_body_is_classified_separately_from_auth_headers() { + use openshell_core::proto::{StaticCredentialBinding, StaticCredentialEndpointBinding}; + let state = ProviderCredentialState::from_bound_environment( + 42, + TestHashMap::from([("API_KEY".into(), "private-test-secret".into())]), + TestHashMap::new(), + TestHashMap::new(), + TestHashMap::from([( + "API_KEY".into(), + StaticCredentialBinding { + credential_identity: "provider".into(), + workload_credential_handle: String::new(), + endpoints: vec![StaticCredentialEndpointBinding { + host: "api.example.com".into(), + port: 80, + path: "/**".into(), + }], + }, + )]), + vec![], + ) + .unwrap(); + let issued = state.snapshot().child_env["API_KEY"].clone(); + let (resolver, classifier, _) = + state.resolver_and_body_classifier_for_endpoint("api.example.com", 80, "/chat"); + for token in [ + "openshell:resolve:env:KEY".to_owned(), + issued.clone(), + issued.replace(':', "%3A"), + format!( + "sk-OPENSHELL-RESOLVE-ENV-{}", + issued.strip_prefix("openshell:resolve:env:").unwrap() + ), + ] { + let body = format!(r#"{{"messages":[{{"role":"tool","content":"{token}"}}]}}"#); + let raw = format!( + "POST http://api.example.com/chat HTTP/1.1\r\nHost: api.example.com\r\nAuthorization: Bearer {issued}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + for _ in 0..2 { + let forwarded = relay_forward_request_and_capture_classified( + "POST", + "/chat", + raw.as_bytes(), + resolver.as_deref(), + false, + classifier.as_deref(), + ) + .await + .unwrap(); + let (headers, actual_body) = forwarded.split_once("\r\n\r\n").unwrap(); + assert!(headers.contains("Authorization: Bearer private-test-secret")); + assert_eq!(actual_body, body); + assert!(!actual_body.contains("private-test-secret")); + } + } + // Header placeholders remain fail-closed even when the body can be literal. + let raw = b"POST http://api.example.com/chat HTTP/1.1\r\nHost: api.example.com\r\nAuthorization: Bearer openshell:resolve:env:MISSING\r\nContent-Length: 0\r\n\r\n"; + assert!( + rewrite_forward_request( + raw, + raw.len(), + "/chat", + "api.example.com", + resolver.as_deref() + ) + .is_err() + ); + } + #[tokio::test] async fn forward_relay_rewrites_urlencoded_body_alias_from_initial_read() { let (_, resolver) = SecretResolver::from_provider_env( @@ -10118,7 +10207,6 @@ network_policies: "/api/messages", "api.example.com", Some(&resolver), - true, ) .expect("header rewrite should defer body overflow to body rewriter"); let (mut proxy_to_upstream, mut upstream_side) = tokio::io::duplex(8192); @@ -10133,6 +10221,7 @@ network_policies: ForwardRelayOptions { generation_guard: &guard, credential_generation: None, + body_classifier: None, websocket_extensions: crate::l7::rest::WebSocketExtensionMode::Preserve, secret_resolver: Some(&resolver), request_body_credential_rewrite: true, @@ -10214,6 +10303,7 @@ network_policies: ForwardRelayOptions { generation_guard: &guard, credential_generation: None, + body_classifier: None, websocket_extensions: crate::l7::rest::WebSocketExtensionMode::Preserve, secret_resolver: Some(&resolver), request_body_credential_rewrite: false, @@ -10261,7 +10351,6 @@ network_policies: "/ws", "gateway.example.test", None, - false, ) .expect("websocket forward rewrite should succeed"); let result_str = String::from_utf8_lossy(&result); @@ -10289,7 +10378,7 @@ network_policies: engine.reload(policy, policy_data).unwrap(); let raw = b"GET http://host/api HTTP/1.1\r\nHost: host\r\n\r\n"; - let rewritten = rewrite_forward_request(raw, raw.len(), "/api", "host", None, false) + let rewritten = rewrite_forward_request(raw, raw.len(), "/api", "host", None) .expect("rewrite should succeed"); let (mut proxy_to_upstream, mut upstream_side) = tokio::io::duplex(8192); let (mut _app_side, mut proxy_to_client) = tokio::io::duplex(8192); @@ -10303,6 +10392,7 @@ network_policies: ForwardRelayOptions { generation_guard: &guard, credential_generation: None, + body_classifier: None, websocket_extensions: crate::l7::rest::WebSocketExtensionMode::Preserve, secret_resolver: None, request_body_credential_rewrite: false, @@ -10339,7 +10429,7 @@ network_policies: .unwrap(); let raw = b"POST http://host/api HTTP/1.1\r\nHost: host\r\nContent-Length: 4\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n"; - let rewritten = rewrite_forward_request(raw, raw.len(), "/api", "host", None, false) + let rewritten = rewrite_forward_request(raw, raw.len(), "/api", "host", None) .expect("rewrite should succeed"); let (mut proxy_to_upstream, mut upstream_side) = tokio::io::duplex(8192); let (mut _app_side, mut proxy_to_client) = tokio::io::duplex(8192); @@ -10353,6 +10443,7 @@ network_policies: ForwardRelayOptions { generation_guard: &guard, credential_generation: None, + body_classifier: None, websocket_extensions: crate::l7::rest::WebSocketExtensionMode::Preserve, secret_resolver: None, request_body_credential_rewrite: false, diff --git a/crates/openshell-supervisor-network/src/proxy/relay.rs b/crates/openshell-supervisor-network/src/proxy/relay.rs index d5d1828622..b40f4dee68 100644 --- a/crates/openshell-supervisor-network/src/proxy/relay.rs +++ b/crates/openshell-supervisor-network/src/proxy/relay.rs @@ -82,6 +82,7 @@ pub(super) fn http_context( secret_resolver, provider_credentials, provider_credential_revision: None, + body_classifier: None, activity_tx, dynamic_credentials: dynamic_credentials.clone(), token_grant_resolver: dynamic_credentials @@ -353,6 +354,7 @@ mod tests { secret_resolver: None, provider_credentials: None, provider_credential_revision: None, + body_classifier: None, activity_tx: None, dynamic_credentials: None, token_grant_resolver: None, diff --git a/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs b/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs index 30ee3d701a..badff5c42a 100644 --- a/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs +++ b/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs @@ -414,7 +414,7 @@ fn forward_rewrite_does_not_treat_a_pipelined_request_as_body_overflow() { Host: target.example\r\n\ Content-Length: 0\r\n\r\n"; let rewritten = - rewrite_forward_request(raw, raw.len(), "/allowed", "target.example", None, false).unwrap(); + rewrite_forward_request(raw, raw.len(), "/allowed", "target.example", None).unwrap(); let rewritten = String::from_utf8(rewritten).unwrap(); assert!(rewritten.starts_with("GET /allowed HTTP/1.1\r\n")); @@ -431,7 +431,7 @@ fn forward_rewrite_trims_pipeline_after_content_length_body() { GET http://target.example/blocked HTTP/1.1\r\n\ Host: target.example\r\n\r\n"; let rewritten = - rewrite_forward_request(raw, raw.len(), "/allowed", "target.example", None, false).unwrap(); + rewrite_forward_request(raw, raw.len(), "/allowed", "target.example", None).unwrap(); let rewritten = String::from_utf8(rewritten).unwrap(); assert!(rewritten.ends_with("\r\n\r\nbody")); @@ -447,7 +447,7 @@ fn forward_rewrite_trims_pipeline_after_complete_chunked_body() { GET http://target.example/blocked HTTP/1.1\r\n\ Host: target.example\r\n\r\n"; let rewritten = - rewrite_forward_request(raw, raw.len(), "/allowed", "target.example", None, false).unwrap(); + rewrite_forward_request(raw, raw.len(), "/allowed", "target.example", None).unwrap(); let rewritten = String::from_utf8(rewritten).unwrap(); assert!(rewritten.ends_with("4\r\nbody\r\n0\r\n\r\n")); diff --git a/docs/reference/policy-schema.mdx b/docs/reference/policy-schema.mdx index 8f7baa3130..5369ff9656 100644 --- a/docs/reference/policy-schema.mdx +++ b/docs/reference/policy-schema.mdx @@ -174,7 +174,7 @@ Each endpoint defines a reachable destination and optional inspection rules. | `allowed_ips` | list of string | No | CIDR or IP allowlist for SSRF override. Exact user-declared hostname endpoints may resolve to RFC 1918 private addresses without this field, but wildcard, hostless, and policy-advisor-proposed endpoints still require `allowed_ips` for private resolved IPs. A hostless allowlist is valid only for the legacy proxy path and cannot be combined with `protocol: tcp`. Entries overlapping loopback (`127.0.0.0/8`), link-local (`169.254.0.0/16`), or unspecified (`0.0.0.0`) are rejected at load time. | | `allow_encoded_slash` | bool | No | When `true`, L7 request parsing preserves `%2F` inside path segments instead of rejecting it. Use this for registries and APIs such as npm scoped packages (`/@scope%2Fname`). Defaults to `false`. | | `websocket_credential_rewrite` | bool | No | When `true` on a `protocol: rest` or `protocol: websocket` endpoint, OpenShell rewrites credential placeholders in client-to-server WebSocket text messages after an allowed HTTP `101` upgrade. On provider-credentialed endpoints without `allow_uninspected_credentials`, OpenShell uses the parsed relay and rejects binary frames; text frames containing placeholders fail closed when rewrite is disabled. Defaults to `false`. | -| `request_body_credential_rewrite` | bool | No | When `true` on a `protocol: rest` endpoint, OpenShell rewrites credential placeholders in UTF-8 `application/json`, `application/x-www-form-urlencoded`, and `text/*` request bodies before forwarding upstream. The proxy buffers at most 256 KiB and updates `Content-Length` after rewriting. For chunked requests, the limit counts framing, extensions, and trailers. When rewrite is disabled and the sandbox has provider credentials, ordinary bodies continue to stream, but a reserved credential placeholder is rejected before its marker reaches upstream, including for providers without endpoint profiles. Defaults to `false`. Mutually exclusive with `credential_signing`. | +| `request_body_credential_rewrite` | bool | No | When `true` on a `protocol: rest` endpoint, OpenShell rewrites credential placeholders in UTF-8 `application/json`, `application/x-www-form-urlencoded`, and `text/*` request bodies before forwarding upstream. The proxy buffers at most 256 KiB and updates `Content-Length` after rewriting. For chunked requests, the limit counts framing, extensions, and trailers. When rewrite is disabled and the sandbox has provider credentials, bodies continue to stream. Authoritatively unknown placeholder keys and valid issued credentials pass unchanged, including credentials bound to the destination. Invalid or unavailable credentials, and unavailable classification metadata fail closed with `credential_placeholder_in_request_body` (HTTP 403). Candidates are limited to 4096 wire bytes. No secret is substituted. Defaults to `false`. Mutually exclusive with `credential_signing`. | | `allow_uninspected_credentials` | bool | No | Explicit security-sensitive opt-in that permits a provider-credentialed endpoint to use traffic paths OpenShell cannot inspect or rewrite, including L4-only and `tls: skip` tunnels. Defaults to `false`. Policy proposals that set it require explicit security-flagged approval. | | `credential_signing` | string | No | Proxy-side credential signing mode. When set, the proxy strips the sandbox client's `Authorization` header and re-signs with real provider credentials. Values: `sigv4` (auto-detect payload mode from client headers), `sigv4:body` (buffer and hash body, max 10 MiB), `sigv4:no_body` (unsigned payload, stream body). Mutually exclusive with `request_body_credential_rewrite`. See [AWS SigV4](/providers/aws-sigv4). | | `signing_service` | string | No | AWS service name for SigV4 signing (e.g. `bedrock`, `s3`, `sts`). Required when `credential_signing` is set. | diff --git a/docs/sandboxes/policies.mdx b/docs/sandboxes/policies.mdx index af25238a6b..6404eabcb9 100644 --- a/docs/sandboxes/policies.mdx +++ b/docs/sandboxes/policies.mdx @@ -72,6 +72,24 @@ When a hot reload changes rules, the supervisor publishes a new policy generatio | `network_policies` | Dynamic | Controls outbound traffic from the sandbox, including native model-provider endpoints. Each block has a name, a list of endpoints (host, port, protocol, and optional rules), and a list of binaries allowed to use those endpoints.
Every outbound connection passes through the network supervisor, which queries the [policy engine](/about/how-it-works#core-components) with the destination and calling binary. A connection is allowed only when both match an entry in the same policy block. Attached provider profiles can contribute endpoint and binary entries to the effective policy.
For endpoints with `protocol: rest`, the proxy auto-detects TLS and terminates it so each HTTP request can be checked against that endpoint's `rules` (method and path). For endpoints with `protocol: websocket`, the proxy validates the RFC 6455 upgrade and evaluates `GET` rules for the handshake plus either `WEBSOCKET_TEXT` rules for raw client text messages or GraphQL operation rules for GraphQL-over-WebSocket messages. Set `websocket_credential_rewrite: true` only when a WebSocket or REST compatibility endpoint must keep placeholder credentials in sandbox-owned text frames and resolve them at the OpenShell relay boundary.
Endpoints with `protocol: tcp` allow ordinary DNS resolution and native TCP connections without inspecting payloads. Endpoints without `protocol` retain L4 passthrough through an explicit proxy.
If no endpoint matches, the connection is denied. | | `network_middlewares` | Dynamic | Declares keyed HTTP and WebSocket middleware configs. After network and L7 policy admit a request or upgrade, OpenShell matches each config's host selectors independently and runs matching entries by their unique ascending `order` before credential injection. WebSocket-capable entries continue on complete client text messages. | +When REST body credential rewriting is disabled, OpenShell forwards placeholder +text unchanged if trusted metadata identifies an unknown key or a valid credential +with a current binding, including to the destination itself. For example, an +OpenRouter placeholder printed by `printenv` can remain in an OpenRouter +conversation, just like an unknown documentation example or a GitHub placeholder. +OpenShell preserves the body bytes and does not substitute the secret. Header +credential resolution remains separate: the same placeholder can resolve in an +authentication header while remaining literal text in the body. + +Known invalid or revoked references and unavailable classification +metadata also fail closed. The local HTTP 403 response uses the error code +`credential_placeholder_in_request_body`. Remove the offending reference from +conversation history before retrying; if metadata is unavailable, restore provider +access first. Do not enable body rewriting or `allow_uninspected_credentials` just +to forward conversation text. Malformed placeholder candidates and candidates +longer than 4096 wire bytes are denied. Authentication headers and HTTP trailers +retain their credential restrictions. + ## Supervisor Middleware Supervisor middleware can inspect, deny, or replace admitted HTTP request bodies and client WebSocket text messages before provider credentials are injected. Middleware selection is independent of the `network_policies` rule that admitted the traffic: each keyed `network_middlewares` entry matches the destination host through `endpoints.include` and `endpoints.exclude`. @@ -368,7 +386,7 @@ Use the `websocket-credential-rewrite` endpoint option with `protocol: websocket Use the `request-body-credential-rewrite` endpoint option with `protocol: rest` when an API expects OpenShell-managed credentials in UTF-8 JSON, form, or text request bodies. OpenShell buffers up to 256 KiB, rewrites recognized credential placeholders, updates `Content-Length`, and rejects unresolved placeholders instead of forwarding them. For chunked requests, the 256 KiB limit counts the complete wire representation, including framing, extensions, and trailers. The option is rejected for WebSocket, GraphQL, SQL, and plain L4 endpoints. -Use `allow-uninspected-credentials` only when a provider-credentialed endpoint must remain L4-only, use `tls: skip`, or carry uninspectable WebSocket traffic. Without this explicit opt-in, the gateway rejects credentialed L4-only and `tls: skip` endpoints. REST bodies without placeholders continue to work when body rewrite is disabled; a body containing an OpenShell credential placeholder fails closed. +Use `allow-uninspected-credentials` only when a provider-credentialed endpoint must remain L4-only, use `tls: skip`, or carry uninspectable WebSocket traffic. Without this explicit opt-in, the gateway rejects credentialed L4-only and `tls: skip` endpoints. When REST body rewriting is disabled, unknown placeholder text and valid issued placeholders pass unchanged; invalid or unavailable references fail closed. Credential rewrite recognizes the canonical `openshell:resolve:env:KEY` placeholder form and whole-token provider-shaped aliases such as `provider-OPENSHELL-RESOLVE-ENV-API_TOKEN` when the referenced environment key exists in the configured provider credentials. diff --git a/e2e/rust/tests/credential_gating.rs b/e2e/rust/tests/credential_gating.rs index 25d5516543..850b4f9860 100644 --- a/e2e/rust/tests/credential_gating.rs +++ b/e2e/rust/tests/credential_gating.rs @@ -311,6 +311,7 @@ process: struct BodyObservation { saw_placeholder: bool, saw_secret: bool, + authenticated: bool, } struct HttpProbeServer { @@ -528,11 +529,20 @@ async fn handle_http_probe( } } + let header_end = received + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map_or(received.len(), |end| end + 4); + let headers = String::from_utf8_lossy(&received[..header_end]); + let body = &received[header_end..]; let observation = BodyObservation { - saw_placeholder: received + authenticated: headers + .lines() + .any(|line| line == format!("Authorization: Bearer {TEST_SECRET}")), + saw_placeholder: body .windows(PLACEHOLDER_PREFIX.len()) .any(|window| window == PLACEHOLDER_PREFIX.as_bytes()), - saw_secret: received + saw_secret: body .windows(TEST_SECRET.len()) .any(|window| window == TEST_SECRET.as_bytes()), }; @@ -540,14 +550,23 @@ async fn handle_http_probe( if expected_total.is_some_and(|expected| received.len() >= expected) { let result = if observation.saw_secret && !observation.saw_placeholder { "BODY_REWRITTEN" + } else if observation.saw_placeholder && !observation.saw_secret { + "BODY_TEXT" } else { "BODY_BAD" }; + // Echo admitted literal bodies so clients can assert exact preservation. + let response_body = if result == "BODY_TEXT" { + [b"BODY_TEXT\n".as_slice(), body].concat() + } else { + result.as_bytes().to_vec() + }; let response = format!( - "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{result}", - result.len() + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + response_body.len() ); stream.write_all(response.as_bytes()).await?; + stream.write_all(&response_body).await?; } Ok(()) } @@ -594,7 +613,7 @@ with socket.create_connection((proxy.hostname, proxy.port or 80), timeout=10) as if not chunk: break response += chunk - print("BODY_REWRITTEN" if b"BODY_REWRITTEN" in response else "BODY_DENIED") + print("BODY_REWRITTEN" if b"BODY_REWRITTEN" in response else "BODY_TEXT" if b"BODY_TEXT" in response else "BODY_DENIED") "# ) } @@ -857,13 +876,55 @@ async fn run_body_sandbox( Ok(output) } -async fn run_profile_body_sandbox(port: u16) -> Result { - let policy = write_base_policy()?; - let policy_path = policy - .path() - .to_str() - .ok_or_else(|| "body policy path is not UTF-8".to_string())?; - let script = body_client_script(port); +async fn assert_conversation_placeholders_pass( + server: &HttpProbeServer, + own_provider: bool, +) -> Result<(), String> { + let policy = if own_provider { + write_base_policy()? + } else { + write_policy( + server.port, + EndpointMode::RestBody { rewrite: false }, + CredentialSource::ProviderProfile, + )? + }; + let policy_path = policy.path().to_str().ok_or("invalid policy path")?; + let script = format!( + r#" +import http.client +import json +import os +import urllib.parse + +proxy_url = next(os.environ[name] for name in + ("HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy") + if os.environ.get(name)) +proxy = urllib.parse.urlparse(proxy_url) +target = "{host}:{port}" +issued = os.environ[{env:?}] +for token in ("openshell:resolve:env:KEY", issued): + body = json.dumps({{"messages": [{{"role": "tool", "content": "{env}=" + token}}, {{"role": "user", "content": "hi"}}]}}).encode() + for tunnel in (False, True): + for replay in range(2): + connection = http.client.HTTPConnection(proxy.hostname, proxy.port or 80, timeout=10) + if tunnel: + connection.set_tunnel({host:?}, {port}) + headers = {{"Content-Type": "application/json", "Connection": "close"}} + if {own}: + headers["Authorization"] = "Bearer " + issued + connection.request("POST", "/token" if tunnel else "http://" + target + "/token", body, headers) + response = connection.getresponse() + assert response.status == 200, response.status + assert response.read() == b"BODY_TEXT\n" + body, "body changed" + connection.close() + print("BODY_TEXT") +"#, + host = TEST_HOST, + port = server.port, + env = TOKEN_ENV, + own = if own_provider { "True" } else { "False" }, + ); let mut sandbox = SandboxGuard::create(&[ "--policy", policy_path, @@ -877,16 +938,21 @@ async fn run_profile_body_sandbox(port: u16) -> Result { .await?; let output = sandbox.create_output.clone(); sandbox.cleanup().await; - Ok(output) -} - -async fn assert_rest_body_backstop(server: &HttpProbeServer) -> Result<(), String> { - let denied = run_profile_body_sandbox(server.port).await?; - assert!(denied.contains("BODY_DENIED")); - let observations = server.wait_for_observations(1).await; - assert_eq!(observations.len(), 1, "observations: {observations:?}"); - assert!(!observations[0].saw_placeholder); - assert!(!observations[0].saw_secret); + assert_eq!( + output.matches("BODY_TEXT").count(), + 8, + "conversation did not survive replay: {output}" + ); + assert!(!output.contains(TEST_SECRET)); + let observations = server.wait_for_observations(8).await; + assert_eq!(observations.len(), 8); + assert!( + observations + .iter() + .all(|observation| observation.saw_placeholder + && !observation.saw_secret + && observation.authenticated == own_provider) + ); Ok(()) } @@ -932,7 +998,9 @@ async fn credentialed_endpoint_gates_work_end_to_end() { .expect("install credentialed provider"); let result = async { - assert_rest_body_backstop(&server).await?; + assert_conversation_placeholders_pass(&server, true).await?; + let foreign_server = HttpProbeServer::start().await?; + assert_conversation_placeholders_pass(&foreign_server, false).await?; assert_websocket_binary_denied(&websocket_server).await } .await; @@ -945,13 +1013,13 @@ async fn credentialed_endpoint_gates_work_end_to_end() { .expect("install endpointless provider"); let endpointless_result = async { assert_gateway_admission(server.port, CredentialSource::PolicyBinding).await?; - let denied = run_body_sandbox( + let literal = run_body_sandbox( server.port, EndpointMode::RestBody { rewrite: false }, CredentialSource::PolicyBinding, ) .await?; - assert!(denied.contains("BODY_DENIED")); + assert!(literal.contains("BODY_TEXT")); let rewritten = run_body_sandbox( server.port, EndpointMode::RestBody { rewrite: true }, @@ -961,12 +1029,12 @@ async fn credentialed_endpoint_gates_work_end_to_end() { assert!(rewritten.contains("BODY_REWRITTEN")); assert!(!rewritten.contains(TEST_SECRET)); assert!(!rewritten.contains(PLACEHOLDER_PREFIX)); - let observations = server.wait_for_observations(3).await; - assert_eq!(observations.len(), 3, "observations: {observations:?}"); - assert!(!observations[1].saw_placeholder); - assert!(!observations[1].saw_secret); - assert!(!observations[2].saw_placeholder); - assert!(observations[2].saw_secret); + let observations = server.wait_for_observations(10).await; + assert_eq!(observations.len(), 10, "observations: {observations:?}"); + assert!(observations[8].saw_placeholder); + assert!(!observations[8].saw_secret); + assert!(!observations[9].saw_placeholder); + assert!(observations[9].saw_secret); assert_endpointless_provider_env_live_update(server.port).await?; Ok::<(), String>(()) } diff --git a/skills/debug-inference/SKILL.md b/skills/debug-inference/SKILL.md index c888bfb043..1ba416ce3e 100644 --- a/skills/debug-inference/SKILL.md +++ b/skills/debug-inference/SKILL.md @@ -97,6 +97,7 @@ inference request using the provider's documented API shape. | Symptom | Likely cause | Fix | |---|---|---| +| `credential_placeholder_in_request_body` | A body reference is invalid/revoked, or classification metadata is unavailable | Check the controlled denial reason; remove the reference from conversation history or restore provider access. Do not enable body credential rewriting or bypass flags to send tool output. Unknown literals and valid issued placeholders pass unchanged, including the model provider’s own placeholder. Header resolution does not enable body rewriting. | | `Could not resolve host: inference.local` | Client still uses the removed managed endpoint | Configure the provider's native base URL and attach an endpoint-bearing provider profile | | Direct request is denied | Missing attachment, endpoint policy, HTTP rule, or binary authorization | Inspect the attached provider profile and sandbox effective policy | | `credential_endpoint_mismatch` | Credential profile does not authorize the request recipient | Correct the host/port/path or import a narrowly scoped profile for the intended endpoint | From ce25acca5a57220ddc89795f946f3df666ec78bd Mon Sep 17 00:00:00 2001 From: Piotr Mlocek Date: Thu, 10 Sep 2026 23:19:13 +0000 Subject: [PATCH 06/12] fix(build): honor Cargo target directory when staging binaries (#3262) Signed-off-by: Piotr Mlocek --- tasks/scripts/stage-prebuilt-binaries.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tasks/scripts/stage-prebuilt-binaries.sh b/tasks/scripts/stage-prebuilt-binaries.sh index b3f75bbaba..8f40788ffa 100755 --- a/tasks/scripts/stage-prebuilt-binaries.sh +++ b/tasks/scripts/stage-prebuilt-binaries.sh @@ -171,6 +171,7 @@ build_component_for_arch() { local current_host_os local current_host_arch local binary_path + local cargo_output_dir local build_rustflags resolve_component "$component" @@ -257,7 +258,8 @@ build_component_for_arch() { CARGO_INCREMENTAL=0 mise x -- ${cargo_env[@]+"${cargo_env[@]}"} "${cargo_subcommand[@]}" "${args[@]}" ) - binary_path="${ROOT}/target/${target}/release/${binary}" + cargo_output_dir="$(cd "$ROOT" && mise x -- cargo metadata --format-version=1 --no-deps | jq -er '.target_directory')" + binary_path="${cargo_output_dir}/${target}/release/${binary}" if [[ "$component" == "gateway" ]]; then "$SCRIPT_DIR/verify-glibc-symbols.sh" 2.28 "$binary_path" elif [[ "$component" == "supervisor" ]]; then From ddc8bba9677ed8413849c8f148364df2f0146a6d Mon Sep 17 00:00:00 2001 From: Piotr Mlocek Date: Thu, 10 Sep 2026 23:53:01 +0000 Subject: [PATCH 07/12] ci(windows): add Windows MSVC CI jobs (#2738) * fix(ci): preserve Windows Rust build cache Signed-off-by: Piotr Mlocek * fix(ci): invalidate empty Windows caches Signed-off-by: Piotr Mlocek * perf(ci): cache Windows builds with sccache Signed-off-by: Piotr Mlocek * ci(windows): restore target directory caching Signed-off-by: Piotr Mlocek * perf(ci): use prebuilt Z3 on Windows Signed-off-by: Piotr Mlocek * perf(ci): layer sccache on Windows target cache Signed-off-by: Piotr Mlocek * ci(windows): split PR checks from main validation Signed-off-by: Piotr Mlocek * ci(windows): separate checks builds and cache seeding Signed-off-by: Piotr Mlocek * fix(ci): simplify Windows build dependency Signed-off-by: Piotr Mlocek * fix(ci): rely on Windows job dependency status Signed-off-by: Piotr Mlocek * fix(ci): use valid opt-in Windows ARM runner Signed-off-by: Piotr Mlocek * ci(windows): keep ARM64 validation local Signed-off-by: Piotr Mlocek * fix(ci): install Clippy for Windows validation Signed-off-by: Piotr Mlocek * ci(windows): focus platform lint coverage Signed-off-by: Piotr Mlocek * docs(licenses): explain bzip2 allowance Signed-off-by: Piotr Mlocek * ci(windows): simplify workflow name Signed-off-by: Piotr Mlocek * fix(windows): allow async platform stub Signed-off-by: Piotr Mlocek * fix(network): make file fingerprints portable Signed-off-by: Piotr Mlocek * ci(windows): lint supported deliverables Signed-off-by: Piotr Mlocek * ci(windows): allow platform-gated lint Signed-off-by: Piotr Mlocek * chore(ci): align Windows cache action with main Signed-off-by: Piotr Mlocek * fix(ci): align Windows validation with prerequisites Signed-off-by: Piotr Mlocek * ci(windows): pin Rust toolchain action Signed-off-by: Piotr Mlocek * fix(ci): use enterprise-approved Windows actions Signed-off-by: Piotr Mlocek * fix(windows): restore strict MSVC validation Signed-off-by: Piotr Mlocek * ci(windows): run Rust tests with nextest Signed-off-by: Piotr Mlocek * fix(ci): normalize nextest lock provenance Signed-off-by: Piotr Mlocek * ci(windows): add native arm64 validation Signed-off-by: Piotr Mlocek * fix(ci): lock nextest for Windows ARM64 Signed-off-by: Piotr Mlocek * fix(windows): resolve duplicate MXC authentication method Signed-off-by: Piotr Mlocek * test(conformance): use native absolute paths on Windows Signed-off-by: Piotr Mlocek * docs(windows): address MSVC review feedback Signed-off-by: Piotr Mlocek * ci(windows): simplify cache key names Signed-off-by: Piotr Mlocek * fix(ci): isolate Windows Rust toolchains for stable caches Signed-off-by: Piotr Mlocek * fix(ci): configure Rustup home in runner setup Signed-off-by: Piotr Mlocek * ci(windows): surface sccache server write diagnostics Signed-off-by: Piotr Mlocek * ci(windows): remove temporary cache diagnostics Signed-off-by: Piotr Mlocek * ci(windows): address review feedback Signed-off-by: Piotr Mlocek * fix(windows): reconcile merged driver capabilities Signed-off-by: Piotr Mlocek * fix(deps): preserve AWS-LC-only lockfile Signed-off-by: Piotr Mlocek * chore(deps): allow z3 prebuilt TLS wrapper Signed-off-by: Piotr Mlocek --------- Signed-off-by: Piotr Mlocek --- .../build-openshell-mxc-windows/SKILL.md | 56 +++-- .../build-openshell-mxc-windows/reference.md | 16 +- .github/workflows/windows-msvc.yml | 211 ++++++++++++++++-- CONTRIBUTING.md | 20 +- Cargo.lock | 101 +++++++++ architecture/windows-msvc-build.md | 106 +++++---- crates/openshell-conformance/src/plan.rs | 22 +- crates/openshell-driver-mxc/src/driver.rs | 7 +- crates/openshell-driver-mxc/src/grpc.rs | 14 ++ crates/openshell-prover/Cargo.toml | 1 + crates/openshell-server/Cargo.toml | 1 + crates/openshell-server/src/config_file.rs | 4 +- deny.toml | 7 +- mise.lock | 34 +++ mise.toml | 1 + tasks/scripts/windows-msvc.ps1 | 164 +++----------- tasks/windows.toml | 23 +- 17 files changed, 526 insertions(+), 262 deletions(-) diff --git a/.agents/skills/build-openshell-mxc-windows/SKILL.md b/.agents/skills/build-openshell-mxc-windows/SKILL.md index 5f0d617b08..8ce602ce9d 100644 --- a/.agents/skills/build-openshell-mxc-windows/SKILL.md +++ b/.agents/skills/build-openshell-mxc-windows/SKILL.md @@ -30,7 +30,7 @@ The Windows build lane is implemented by these tracked files: | `tasks/windows.toml` | Mise task entry points for `windows:*` commands. | | `tasks/rust.toml`, `tasks/test.toml`, and `tasks/markdown.toml` | Windows routing for compiler-bearing checks, explicit Unix-only test skips, and Markdown dependency setup. | | `tasks/scripts/windows-msvc.ps1` | PowerShell wrapper that enters the Visual Studio developer environment and invokes Cargo. | -| `.github/workflows/windows-msvc.yml` | Manually dispatched GitHub Actions jobs with architecture-specific Rust caches for x64 and future ARM64 Windows validation. | +| `.github/workflows/windows-msvc.yml` | PR/merge-queue lint and test plus main/manual cache seeding and dependent binary builds on native x64 and ARM64 runners. | | `architecture/windows-msvc-build.md` | Design notes and validation contract. | | `.agents/skills/build-openshell-mxc-windows/` | This skill and companion reference material. | @@ -114,8 +114,8 @@ The lane targets a Windows host with Visual Studio Build Tools and rustup. | Visual Studio 2022 or newer | `where.exe cl.exe` from a Developer PowerShell | Build Tools, Community, Professional, and Enterprise editions work when the target C++ components are installed. The wrapper discovers `VsDevCmd.bat` through `OPENSHELL_VSDEVCMD`, `vswhere`, or installed release directories such as `18` and `2022`. | | Visual C++ ARM64 tools | `vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.ARM64 -property installationPath` | Required for native ARM64 check, build, and tests and for x64-to-ARM64 check/build. Tests always require a native runner. | | Visual C++ ARM64 Spectre-mitigated libraries | `vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre -property installationPath` | Required by `regorus` through `msvc_spectre_libs`; the build fails when the selected MSVC toolset lacks `lib\spectre\arm64`. | -| Visual C++ Clang tools | `vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Llvm.Clang -property installationPath` | Provides host-native `libclang.dll` for `bindgen` and `clang-cl.exe` for ARM64 crypto dependencies such as `ring` and `aws-lc-sys`. On ARM64, the wrapper uses `VC\Tools\Llvm\Arm64\bin`. | -| Visual C++ CMake tools | `vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.CMake.Project -property installationPath` | Provides CMake and Ninja. The x64-to-ARM64 path adds Ninja to `PATH` for native dependencies but keeps bundled Z3 on CMake's Visual Studio ARM64 generator with native MSVC `cl.exe`. | +| Visual C++ Clang tools | `vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Llvm.Clang -property installationPath` | Provides host-native `libclang.dll` for `bindgen` and `clang-cl.exe` for ARM64 crypto dependencies such as `aws-lc-sys`. On ARM64, the wrapper uses `VC\Tools\Llvm\Arm64\bin`. | +| Visual C++ CMake tools | `vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.CMake.Project -property installationPath` | Provides CMake and Ninja for native dependencies. The x64-to-ARM64 path adds Ninja to `PATH`; Z3 uses an architecture-specific prebuilt release. | | Windows SDK | `where.exe rc.exe` from a Developer PowerShell | Install an SDK containing target libraries and ARM64 tools. | | Rust via rustup | `rustc --version` | Add each target being validated: `x86_64-pc-windows-msvc` and/or `aarch64-pc-windows-msvc`. The wrapper also adds the selected target. | | mise | `mise --version` | Used as a task runner only. | @@ -135,8 +135,9 @@ from this skill. | `CARGO_TARGET_DIR` | `target` under repo root | Override Cargo output location. Use a short absolute path when x64-to-ARM64 builds approach Windows path-length limits. | | `Z3_LIBRARY_PATH_OVERRIDE` | unset | Directory containing an x64 system `libz3.lib`; not valid for ARM64. | | `Z3_SYS_Z3_HEADER` | unset | Full `z3.h` path required with a system Z3 library. | -| `Z3_SYS_BUNDLED_DIR_OVERRIDE` | pinned source cached under `CARGO_TARGET_DIR` when explicit, otherwise `%LOCALAPPDATA%\OpenShell\cache\z3` | Use an existing Z3 source tree containing `src/api/z3.h`; otherwise the wrapper fetches the pinned revision through Git and sets this automatically. | -| `RUSTC_WRAPPER` | cleared by wrapper | The wrapper clears inherited values because `--skip-tools` does not provision `sccache`. | +| `Z3_SYS_Z3_VERSION` | `4.16.0` | Pinned official prebuilt Z3 release selected by the wrapper. | +| `READ_ONLY_GITHUB_TOKEN` | unset | Optional token for the Z3 release lookup; GitHub Actions supplies `github.token`. | +| `RUSTC_WRAPPER` | inherited | The wrapper resolves an available command to an absolute path. If it is unavailable, the wrapper warns and continues without compiler caching. | Legacy fork variables such as `OPENSHELL_UPSTREAM`, `OPENSHELL_MXC_FORK_DIR`, and `OPENSHELL_MXC_FORK_BRANCH` are no longer part @@ -189,17 +190,19 @@ order: 6. Focused unsupported-driver contract tests. 7. Artifact reporting. -The GitHub Actions jobs use architecture-specific `Swatinem/rust-cache` -entries for the Cargo registry and dependency target artifacts. Failed runs -also save their usable dependency artifacts. The workflow remains manually -dispatched until cache-hit runtimes justify restoring automatic triggers. +The GitHub Actions jobs layer architecture-specific `Swatinem/rust-cache` +entries for Cargo registry and dependency target artifacts with sccache's GHA +backend for cacheable Rust compiler outputs. Failed runs also save their usable +dependency artifacts. Pull-request mirrors and merge queues run Clippy for the +Windows-supported workspace and e2e crates plus Rust tests. Pushes to `main` and +manual dispatches run the same lint and test commands in a cache-seed job, +followed by a dependent release-binary build job. The seed and PR jobs use the +same cache namespaces. The binaries are not uploaded or published. The ARM64 check/build steps in this x64-host contract are cross-builds. The wrapper discovers and adds host-native LLVM and Ninja to `PATH`, requires the ARM64 compiler and Spectre-mitigated libraries, lets ARM64 crypto crates select -`clang-cl`, and keeps bundled Z3 on native MSVC `cl.exe` with CMake's Visual -Studio ARM64 generator. Z3 does not use Ninja because `z3-sys 0.10.9` passes -the MSBuild-only `-m` argument. +`clang-cl`, and downloads the official prebuilt ARM64 Z3 static library. On ARM64 hosts, validate the native ARM64 check, build, and test path. The wrapper rejects test targets that do not match the host architecture, so x64 @@ -209,7 +212,8 @@ commands above on an ARM64 host. The repository-wide `mise run pre-commit` task is also supported on Windows. Its Rust check, Clippy, and test dependencies enter the same MSVC environment -for the native host target and clear inherited `RUSTC_WRAPPER`. Linux glibc +for the native host target and use an inherited compiler wrapper when it is +available. Linux glibc installer tests and Linux service/RPM packaging-asset tests skip explicitly; the Linux build-environment shell-helper test also skips; cross-platform checks continue to run. The blocking Windows Clippy pass excludes unsupported @@ -261,9 +265,9 @@ The focused contract tasks for either native architecture run: windows_builtin_compute_drivers_report_unsupported ``` -These tests are also included in the full x64 workspace test run; the focused -task intentionally re-runs them so unsupported Windows behavior is visible in -the CI report. +These tests are also included in the full x64 workspace test run. The focused +task is available for local diagnosis; GitHub Actions does not re-run it after +the full suite. ## Test Accounting Guidance @@ -293,19 +297,13 @@ Useful log files: | `test-x86_64-pc-windows-msvc-unsupported-*.log` | Focused unsupported-driver contract output. | | `test-aarch64-pc-windows-msvc-unsupported-*.log` | Focused native ARM64 contract output. | -The first bundled-Z3 check or test can spend several minutes in CMake/MSBuild -without much console output because Cargo output is redirected to the log. Look -for native `MSBuild.exe` workers before treating the process as stalled. The -wrapper fetches the pinned Z3 source through Git before Cargo starts. It caches -under an explicitly configured `CARGO_TARGET_DIR`, or under the current user's -local application data directory when Cargo uses its default target tree. -Concurrent commands publish the validated source through an atomic directory -rename, so x64 and ARM64 validation can share the cache safely. The wrapper does -not rely on the rate-limited GitHub Contents API used by `z3-sys`. A failed -fetch reports the partial checkout path for diagnosis. The artifact report -computes SHA256 through .NET directly and does not rely on the -`Get-FileHash` module being available inside the mise-launched Windows -PowerShell process. +The first check downloads the pinned official Z3 archive for the target +architecture through `z3-sys`. GitHub Actions authenticates the lookup with its +read-only workflow token; local users can set `READ_ONLY_GITHUB_TOKEN` if an +unauthenticated lookup is rate-limited. Cargo stores the extracted library in +its target tree, so the Windows target cache reuses it. The artifact report +computes SHA256 through .NET directly and does not rely on the `Get-FileHash` +module being available inside the mise-launched Windows PowerShell process. ## Common Fix Patterns diff --git a/.agents/skills/build-openshell-mxc-windows/reference.md b/.agents/skills/build-openshell-mxc-windows/reference.md index 16b9a48586..6859ce1f71 100644 --- a/.agents/skills/build-openshell-mxc-windows/reference.md +++ b/.agents/skills/build-openshell-mxc-windows/reference.md @@ -9,7 +9,7 @@ maintaining the existing build-only Windows MSVC lane. |---|---| | `tasks/windows.toml` | Mise task definitions for `windows:*`. | | `tasks/scripts/windows-msvc.ps1` | Visual Studio environment discovery, rustup target setup, Cargo invocation, logs, artifact report. | -| `.github/workflows/windows-msvc.yml` | Manual GitHub Actions x64 job and disabled ARM64 scaffold, each with an architecture-specific Rust dependency cache. | +| `.github/workflows/windows-msvc.yml` | PR/merge-queue lint and test plus main/manual cache seeding and dependent binary builds on native x64 and ARM64 runners. | | `architecture/windows-msvc-build.md` | Human-readable design contract. | ## Commands @@ -46,8 +46,9 @@ if ($arch -eq [System.Runtime.InteropServices.Architecture]::Arm64) { The native test tasks reject a target that does not match the host architecture. Do not report x64 compatibility-under-emulation coverage from an ARM64 run. -The wrapper adds missing rustup targets and clears inherited -`RUSTC_WRAPPER`. It does not install Visual Studio, Rust, Docker, Kubernetes, +The wrapper adds missing rustup targets and preserves an inherited +`RUSTC_WRAPPER` when the command is available. Otherwise, it warns and clears +the setting. It does not install Visual Studio, Rust, Docker, Kubernetes, Podman, WSL, Hyper-V, or VM tooling. On Windows, `mise run pre-commit` routes `rust:check`, `rust:lint`, and @@ -67,11 +68,10 @@ file. For ARM64, verify the Visual Studio instance contains the ARM64 MSVC tools, ARM64 Spectre-mitigated libraries, Clang tools, CMake tools, and a Windows SDK. Clang supplies host-native `libclang.dll` for `bindgen` and `clang-cl.exe` for -ARM64 crypto dependencies such as `ring` and `aws-lc-sys`. Native ARM64 uses -the normal bundled-Z3 CMake path. An x64-to-ARM64 check/build discovers and -adds host-native Ninja to `PATH`, while the crypto crates select `clang-cl`. -Bundled Z3 uses CMake's Visual Studio ARM64 generator with native MSVC `cl.exe` -because `z3-sys 0.10.9` passes the MSBuild-only `-m` argument. Use a short +ARM64 crypto dependencies such as `aws-lc-sys`. Native and +x64-to-ARM64 builds use the official prebuilt Z3 4.16.0 static library for the +target architecture. An x64-to-ARM64 check/build discovers and adds host-native +Ninja to `PATH`, while the crypto crates select `clang-cl`. Use a short `CARGO_TARGET_DIR` if Windows path-length limits are reached. ## Unsupported Driver Rules diff --git a/.github/workflows/windows-msvc.yml b/.github/workflows/windows-msvc.yml index 3ad1cc68f0..4c7f0d29b8 100644 --- a/.github/workflows/windows-msvc.yml +++ b/.github/workflows/windows-msvc.yml @@ -1,50 +1,213 @@ -name: Windows MSVC (build-only) +name: Windows MSVC + on: + merge_group: + types: [checks_requested] + push: + branches: + - main + - "pull-request/[0-9]+" workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + # sccache cannot cache incremental Rust compilations, and rust-cache removes + # incremental artifacts before saving the target directory. + CARGO_INCREMENTAL: "0" + jobs: - x64: - runs-on: windows-2025 + pr_metadata: + name: Resolve PR metadata + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + outputs: + should_run: ${{ github.ref == 'refs/heads/main' || steps.gate.outputs.should_run == 'true' }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: jdx/mise-action@c2a87611a18de5b3828c5652fe268e992400cb5c # v4.3.0 + + - id: gate + if: github.ref != 'refs/heads/main' + uses: ./.github/actions/pr-gate + + pr-check: + name: PR lint and test (${{ matrix.arch }}) + needs: pr_metadata + if: >- + needs.pr_metadata.outputs.should_run == 'true' && + github.ref != 'refs/heads/main' && + github.event_name != 'workflow_dispatch' + strategy: + fail-fast: false + matrix: + include: + - arch: x64 + runner: windows-2025 + rust_target: x86_64-pc-windows-msvc + - arch: arm64 + runner: windows-11-arm + rust_target: aarch64-pc-windows-msvc + runs-on: ${{ matrix.runner }} + env: + READ_ONLY_GITHUB_TOKEN: ${{ github.token }} + SCCACHE_GHA_ENABLED: "true" + SCCACHE_GHA_VERSION: windows-msvc-${{ matrix.arch }} + SCCACHE_CLIENT_SIDE: "1" + SCCACHE_BASEDIRS: ${{ github.workspace }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: jdx/mise-action@e6a8b3978addb5a52f2b4cd9d91eafa7f0ab959d # v4.2.0 with: install: false experimental: true - - uses: dtolnay/rust-toolchain@master - with: - toolchain: "1.95.0" - targets: x86_64-pc-windows-msvc + - name: Configure GHA sccache backend + uses: mozilla-actions/sccache-action@9e7fa8a12102821edf02ca5dbea1acd0f89a2696 # v0.0.10 + - name: Isolate Rust toolchains + # rust-cache hashes every installed toolchain, including unused runner defaults. + run: '"RUSTUP_HOME=$env:RUNNER_TEMP/openshell-rustup" >> $env:GITHUB_ENV' + - name: Install Rust toolchain + # GitHub-hosted runners include rustup. With no toolchain argument, + # rustup installs the checked-in rust-toolchain.toml configuration: + # https://github.com/dtolnay/rust-toolchain/issues/133#issuecomment-2610825530 + run: | + rustup set profile minimal + rustup toolchain install + rustup component add clippy + rustup target add ${{ matrix.rust_target }} + - name: Install cargo-nextest + run: mise install --locked github:nextest-rs/nextest - name: Cache Rust target and registry uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + env: + # Keep rust-cache's cargo metadata calls independent of the compiler + # wrapper; build steps still inherit sccache from the job. + RUSTC_WRAPPER: "" with: - shared-key: windows-msvc-x64 + shared-key: windows-msvc-${{ matrix.arch }} cache-targets: "true" cache-on-failure: "true" cache-bin: "false" - - run: mise run --skip-tools windows:check:x64 - - run: mise run --skip-tools windows:build:x64 - - run: mise run --skip-tools windows:test:x64 - - run: mise run --skip-tools windows:test:unsupported:x64 - arm64: - # TODO: provision a windows-arm64 self-hosted runner - runs-on: [self-hosted, windows-arm64] - if: false # flip to true once the runner is online + - name: Lint Windows-supported crates + run: mise run --skip-tools windows:lint:${{ matrix.arch }} + - name: Test + run: mise run --skip-tools windows:test:${{ matrix.arch }} + - name: sccache stats + if: always() + run: sccache --show-stats + + cache-seed: + name: Seed cache (${{ matrix.arch }}) + needs: pr_metadata + if: >- + needs.pr_metadata.outputs.should_run == 'true' && + (github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch') + strategy: + fail-fast: false + matrix: + include: + - arch: x64 + runner: windows-2025 + rust_target: x86_64-pc-windows-msvc + - arch: arm64 + runner: windows-11-arm + rust_target: aarch64-pc-windows-msvc + runs-on: ${{ matrix.runner }} + env: + READ_ONLY_GITHUB_TOKEN: ${{ github.token }} + SCCACHE_GHA_ENABLED: "true" + SCCACHE_GHA_VERSION: windows-msvc-${{ matrix.arch }} + SCCACHE_CLIENT_SIDE: "1" + SCCACHE_BASEDIRS: ${{ github.workspace }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: jdx/mise-action@c2a87611a18de5b3828c5652fe268e992400cb5c # v4.3.0 + - uses: jdx/mise-action@e6a8b3978addb5a52f2b4cd9d91eafa7f0ab959d # v4.2.0 with: install: false experimental: true - - uses: dtolnay/rust-toolchain@master + - name: Configure GHA sccache backend + uses: mozilla-actions/sccache-action@9e7fa8a12102821edf02ca5dbea1acd0f89a2696 # v0.0.10 + - name: Isolate Rust toolchains + run: '"RUSTUP_HOME=$env:RUNNER_TEMP/openshell-rustup" >> $env:GITHUB_ENV' + - name: Install Rust toolchain + run: | + rustup set profile minimal + rustup toolchain install + rustup component add clippy + rustup target add ${{ matrix.rust_target }} + - name: Install cargo-nextest + run: mise install --locked github:nextest-rs/nextest + - name: Cache Rust target and registry + uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + env: + RUSTC_WRAPPER: "" with: - toolchain: "1.95.0" - targets: aarch64-pc-windows-msvc + shared-key: windows-msvc-${{ matrix.arch }} + cache-targets: "true" + cache-on-failure: "true" + cache-bin: "false" + - name: Lint Windows-supported crates + # Keep the seed workload identical to the pull-request workload so its + # target and compiler caches are reusable by subsequent pull requests. + run: mise run --skip-tools windows:lint:${{ matrix.arch }} + - name: Test + run: mise run --skip-tools windows:test:${{ matrix.arch }} + - name: sccache stats + if: always() + run: sccache --show-stats + + build: + name: Build binaries (${{ matrix.arch }}) + needs: cache-seed + strategy: + fail-fast: false + matrix: + include: + - arch: x64 + runner: windows-2025 + rust_target: x86_64-pc-windows-msvc + - arch: arm64 + runner: windows-11-arm + rust_target: aarch64-pc-windows-msvc + runs-on: ${{ matrix.runner }} + env: + READ_ONLY_GITHUB_TOKEN: ${{ github.token }} + SCCACHE_GHA_ENABLED: "true" + SCCACHE_GHA_VERSION: windows-msvc-${{ matrix.arch }} + SCCACHE_CLIENT_SIDE: "1" + SCCACHE_BASEDIRS: ${{ github.workspace }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: jdx/mise-action@e6a8b3978addb5a52f2b4cd9d91eafa7f0ab959d # v4.2.0 + with: + install: false + experimental: true + - name: Configure GHA sccache backend + uses: mozilla-actions/sccache-action@9e7fa8a12102821edf02ca5dbea1acd0f89a2696 # v0.0.10 + - name: Isolate Rust toolchains + run: '"RUSTUP_HOME=$env:RUNNER_TEMP/openshell-rustup" >> $env:GITHUB_ENV' + - name: Install Rust toolchain + run: | + rustup set profile minimal + rustup toolchain install + rustup target add ${{ matrix.rust_target }} - name: Cache Rust target and registry uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + env: + RUSTC_WRAPPER: "" with: - shared-key: windows-msvc-arm64 + shared-key: windows-msvc-${{ matrix.arch }} cache-targets: "true" cache-on-failure: "true" cache-bin: "false" - - run: mise run --skip-tools windows:check:arm64 - - run: mise run --skip-tools windows:build:arm64 + - name: Build release binaries + run: mise run --skip-tools windows:build:${{ matrix.arch }} + - name: sccache stats + if: always() + run: sccache --show-stats diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 12fb5c0f4c..931d97500f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -338,13 +338,21 @@ compiles Z3 from source during the Rust build and requires CMake 3.16+: cargo build -p openshell-prover --features bundled-z3 ``` -For x86-64 Windows MSVC builds, use one of these Z3 paths: - +For x86-64 and ARM64 Windows MSVC builds, use one of these Z3 paths: + +- Prebuilt Z3 (the default for `windows:*` tasks): `z3-sys` downloads the + pinned Z3 4.16.0 GitHub release for the target architecture on the first + build. Cargo reuses the extracted archive from its target directory. Windows + CI authenticates the GitHub API request with `READ_ONLY_GITHUB_TOKEN` and + preserves the archive in the architecture-specific Cargo target cache. For + cold local builds, you may set `READ_ONLY_GITHUB_TOKEN` to avoid anonymous + GitHub API rate limits. - System Z3: point `Z3_LIBRARY_PATH_OVERRIDE` at the directory containing the - 64-bit MSVC Z3 library and `Z3_SYS_Z3_HEADER` at the full path to `z3.h`. + target-compatible MSVC Z3 library and `Z3_SYS_Z3_HEADER` at the full path to `z3.h`. The `windows:*` tasks use this path automatically when `Z3_LIBRARY_PATH_OVERRIDE` is set. -- Bundled Z3: pass `--features bundled-z3` so `z3-sys` builds Z3 from source. +- Bundled Z3: for direct Cargo builds, pass `--features bundled-z3` so `z3-sys` + builds Z3 from source. `openshell-prover` itself has no `bindgen`/`libclang` dependency, so building just this crate does not require `LIBCLANG_PATH`: @@ -357,7 +365,7 @@ cargo build -p openshell-prover --target x86_64-pc-windows-msvc --features bundl To build the full set of Windows binaries, including `openshell-gateway.exe` and `openshell.exe`, use the `windows:build:x64` mise task instead of a -single-crate `cargo build`. It builds Z3 from source (bundled) by default. A +single-crate `cargo build`. It downloads the pinned prebuilt Z3 release by default. A full build also compiles crates that use `bindgen` (e.g. the MXC driver on Windows), so it requires `libclang.dll`; if LLVM is not on the default search path, set `LIBCLANG_PATH` to the directory containing `libclang.dll`: @@ -367,7 +375,7 @@ $env:LIBCLANG_PATH='C:\Program Files\Microsoft Visual Studio\2022\\VC\T mise run --skip-tools windows:build:x64 ``` -To use a local x64 Z3 release instead of the bundled build, set +To use a local x64 Z3 release instead of the prebuilt download, set `Z3_LIBRARY_PATH_OVERRIDE` and `Z3_SYS_Z3_HEADER` before running the task: ```powershell diff --git a/Cargo.lock b/Cargo.lock index 6a7436cb90..c4ee4d0699 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -908,6 +908,15 @@ dependencies = [ "either", ] +[[package]] +name = "bzip2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c" +dependencies = [ + "libbz2-rs-sys", +] + [[package]] name = "capctl" version = "0.2.4" @@ -1163,6 +1172,12 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + [[package]] name = "core-foundation" version = "0.10.1" @@ -1495,6 +1510,12 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" +[[package]] +name = "deflate64" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2" + [[package]] name = "delegate" version = "0.13.5" @@ -1626,6 +1647,7 @@ dependencies = [ "const-oid 0.10.2", "crypto-common 0.2.2", "ctutils", + "zeroize", ] [[package]] @@ -1974,6 +1996,7 @@ checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" dependencies = [ "crc32fast", "miniz_oxide", + "zlib-rs", ] [[package]] @@ -2614,6 +2637,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", + "webpki-roots", ] [[package]] @@ -3332,6 +3356,12 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" +[[package]] +name = "libbz2-rs-sys" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c" + [[package]] name = "libc" version = "0.2.189" @@ -3425,6 +3455,15 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" +[[package]] +name = "lzma-rust2" +version = "0.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca93e534d1142d1d0dcca6d25fe302508a5dfb40b302802904577725ea0b695b" +dependencies = [ + "sha2 0.11.0", +] + [[package]] name = "matchers" version = "0.2.0" @@ -5208,6 +5247,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +[[package]] +name = "ppmd-rust" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efca4c95a19a79d1c98f791f10aebd5c1363b473244630bb7dbde1dc98455a24" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -5782,6 +5827,7 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "webpki-roots", ] [[package]] @@ -7242,6 +7288,7 @@ checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" dependencies = [ "deranged", "itoa", + "js-sys", "num-conv", "powerfmt", "serde_core", @@ -7712,6 +7759,12 @@ dependencies = [ "thiserror 2.0.18", ] +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "typenum" version = "1.20.1" @@ -8765,7 +8818,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c18b0a91a13522d21b3414847667de2b2056a721a3edcb5b6ee6858352d58db4" dependencies = [ "pkg-config", + "reqwest 0.12.28", + "serde_json", "z3-src", + "zip", ] [[package]] @@ -8862,12 +8918,57 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "zip" +version = "8.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +dependencies = [ + "aes", + "bzip2", + "constant_time_eq", + "crc32fast", + "deflate64", + "flate2", + "getrandom 0.4.2", + "hmac 0.13.0", + "indexmap", + "lzma-rust2", + "memchr", + "pbkdf2", + "ppmd-rust", + "sha1 0.11.0", + "time", + "typed-path", + "zeroize", + "zopfli", + "zstd", +] + +[[package]] +name = "zlib-rs" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b142a20ec14a91d5bc708c1dc21b080c550113d8aa77afa29635673a65dd02c5" + [[package]] name = "zmij" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" +[[package]] +name = "zopfli" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zstd" version = "0.13.3" diff --git a/architecture/windows-msvc-build.md b/architecture/windows-msvc-build.md index 6b0d675a9c..cdea4a3fdc 100644 --- a/architecture/windows-msvc-build.md +++ b/architecture/windows-msvc-build.md @@ -54,11 +54,18 @@ creating misleading Windows driver artifacts. ## Mise Lane -The GitHub Actions workflow is manually dispatched. Each architecture restores -and saves a dedicated Rust cache containing the Cargo registry and dependency -build artifacts, including artifacts from failed runs. Keep the workflow manual -until cache-hit runtimes demonstrate that it is suitable for pull requests and -merges to `main`. +The GitHub Actions workflow runs Clippy for the Windows-supported workspace and +e2e crates plus Rust tests for pull-request mirror branches and merge queues. On +pushes to `main`, a cache-seed job runs the same lint and test commands before a +dependent job builds the release binaries. Manual dispatches exercise the same +seed-then-build path. The binaries remain CI validation artifacts and are not +uploaded or published. + +Each job restores and saves a dedicated Rust cache containing the Cargo +registry and dependency build artifacts, including artifacts from failed runs. +The seed job and pull-request job use the same Cargo target and sccache +namespaces. The release build waits for the seed job, then restores its newly +warmed cache rather than compiling concurrently from a cold cache. Windows validation is exposed through `tasks/windows.toml`: @@ -66,10 +73,12 @@ Windows validation is exposed through `tasks/windows.toml`: |---|---| | `windows:check:x64` | Check the x64 MSVC gateway/CLI build graph. | | `windows:check:arm64` | Check the ARM64 MSVC gateway/CLI build graph. | +| `windows:lint:x64` | Run Clippy over the Windows-supported workspace for x64 MSVC. | +| `windows:lint:arm64` | Run Clippy over the Windows-supported workspace for ARM64 MSVC. | | `windows:build:x64` | Build release x64 `openshell-gateway.exe` and `openshell.exe`. | | `windows:build:arm64` | Build release ARM64 `openshell-gateway.exe` and `openshell.exe`. | -| `windows:test:x64` | Run native x64 workspace tests, including MXC mapper and lifecycle tests, while excluding unsupported Windows packages as top-level test targets. | -| `windows:test:arm64` | Run native ARM64 workspace tests with the same package exclusions. | +| `windows:test:x64` | Run native x64 workspace tests with the nextest CI profile and server test support, while excluding unsupported Windows packages as top-level test targets. | +| `windows:test:arm64` | Run the same suite natively on ARM64. | | `windows:test:unsupported:x64` | Run focused gateway-composition tests for unsupported driver contracts. | | `windows:test:unsupported:arm64` | Run the same focused contracts natively on ARM64. | | `windows:ci` | Run check, build, test, unsupported-contract tests, and artifact reporting. | @@ -77,8 +86,10 @@ Windows validation is exposed through `tasks/windows.toml`: The Windows tasks call `tasks/scripts/windows-msvc.ps1`. The wrapper discovers Visual Studio's `VsDevCmd.bat` with `vswhere` or by enumerating installed release directories, validates the requested compiler and ARM64 Spectre -libraries, adds rustup MSVC targets, clears inherited `RUSTC_WRAPPER`, and -keeps build artifacts under the normal Cargo target tree. +libraries, adds rustup MSVC targets, preserves an inherited `RUSTC_WRAPPER` +when the command is available, and keeps build artifacts under the normal +Cargo target tree. If the wrapper command is unavailable, it warns and clears +the setting so local builds continue without compiler caching. On Windows, the generic `rust:check`, `rust:lint`, and `test:rust` tasks call the same wrapper with the host-native MSVC target. The wrapper preserves the Unix Cargo commands on Linux and macOS, excludes unsupported Windows runtime @@ -90,20 +101,25 @@ packaging-asset tests; its cross-platform Python, Markdown, license, and documentation checks still run. Test tasks require the Rust target architecture to match the Windows host, so an ARM64 test result is native coverage rather than x64 emulation coverage. -By default it enables bundled Z3 for reproducible Windows builds. When +By default it enables the `z3-sys` prebuilt-release feature and pins Z3 4.16.0. +On a clean target directory, `z3-sys` downloads the official static library for +the selected Windows architecture instead of compiling Z3 through +CMake/MSBuild. GitHub Actions supplies its read-only workflow token for the +release lookup, and the Cargo target cache preserves the extracted library for +subsequent runs. When `Z3_LIBRARY_PATH_OVERRIDE` points at a directory containing `libz3.lib`, the wrapper uses that system Z3 instead and requires `Z3_SYS_Z3_HEADER` to point at -the full path to `z3.h`. For bundled builds, the wrapper fetches the Z3 source -revision pinned by `z3-sys` through Git and sets -`Z3_SYS_BUNDLED_DIR_OVERRIDE`. When `CARGO_TARGET_DIR` is explicit, the wrapper -uses it for the source cache. Otherwise, it caches under the current user's -local application data directory, outside the checkout. Publishing uses an -atomic directory rename so concurrent x64 and ARM64 commands can share the -cache safely. This keeps downloaded sources outside the checkout by default and -avoids the unauthenticated GitHub API lookup in the `z3-sys` build script, which -can fail with HTTP 403 when a shared runner or developer network exhausts its -API rate limit. An explicitly set `Z3_SYS_BUNDLED_DIR_OVERRIDE` remains -supported and must contain `src/api/z3.h`. +the full path to `z3.h`. Local clean builds use the unauthenticated GitHub API +unless `READ_ONLY_GITHUB_TOKEN` is set. + +GitHub Actions layers the Cargo target cache with sccache's GitHub Actions +backend. The target cache lets Cargo skip intact dependency builds; sccache +recovers cacheable Rust compiler outputs when source changes invalidate part of +that target tree. CI enables client-side mode and normalizes the checkout root +for stable compiler cache keys. The target-cache action runs its metadata step +with `RUSTC_WRAPPER` cleared so cache maintenance does not depend on sccache. +Hosted jobs use an isolated `RUSTUP_HOME` containing the pinned toolchain so +unused toolchains in runner images cannot change the target-cache restore key. The lane uses `mise run --skip-tools windows:*` because Windows Rust comes from rustup and linking comes from Visual Studio Build Tools. Mise orchestrates the @@ -114,45 +130,47 @@ Spectre-mitigated libraries, host-native Clang tools, CMake tools, and an ARM64-capable Windows SDK. Clang provides `libclang.dll` for `bindgen` and `clang-cl.exe` for ARM64 crypto dependencies. During x64-to-ARM64 check/build, the wrapper discovers and adds the Visual Studio-bundled Ninja to `PATH` for -native dependencies. It lets `cmake-rs` select the Visual Studio ARM64 -generator with native MSVC `cl.exe` for bundled Z3 so the Z3 build does not -inherit the crypto crates' compiler requirement. Z3 stays on the Visual Studio -generator because `z3-sys` emits an MSBuild-only `-m` argument that Ninja -rejects. Artifact hashing uses .NET SHA256 directly because module autoloading -in the mise-launched Windows PowerShell process is not guaranteed. +native dependencies. Z3 uses the official prebuilt ARM64 static library, so it +does not inherit compiler settings from those native dependencies. Artifact +hashing uses .NET SHA256 directly because module autoloading in the +mise-launched Windows PowerShell process is not guaranteed. The wrapper defaults Cargo compilation to four jobs. Set `OPENSHELL_WINDOWS_BUILD_JOBS` to a positive integer to override that limit. A host-local mutex serializes wrapper-owned Cargo commands so concurrent -pre-commit tasks do not multiply the process count while bundled Z3 compiles. +pre-commit tasks do not multiply the compiler process count. The wrapper does not set `CL` or `_CL_`: those variables are also consumed by `clang-cl`, where MSVC's `/MP` option can be interpreted as an input file and break ARM64 crypto dependency builds. ## CI Shape -The x64 GitHub Actions job runs on `windows-2025` and executes: +The x64 GitHub Actions jobs run on `windows-2025`; native ARM64 jobs run on +`windows-11-arm`. Pull-request mirrors and merge queues execute the matching +architecture-specific tasks: ```powershell -mise run --skip-tools windows:check:x64 -mise run --skip-tools windows:build:x64 -mise run --skip-tools windows:test:x64 -mise run --skip-tools windows:test:unsupported:x64 +mise run --skip-tools windows:lint: +mise run --skip-tools windows:test: ``` -The cache is partitioned by architecture so incompatible x64 and ARM64 target -artifacts cannot collide. It does not cache Cargo-installed binaries, which -also keeps the disabled self-hosted ARM64 scaffold from modifying persistent -runner tooling. +Pushes to `main` and manual dispatches first seed the shared caches with those +same lint and test commands. After the seed succeeds, a separate job executes: -The local aggregate `windows:ci` task cross-builds ARM64 on an x64 host. The -GitHub x64 job currently runs only the x64 tasks, and native ARM64 tests remain -exclusive to an ARM64 runner. +```powershell +mise run --skip-tools windows:build: +``` + +The server test-support suite includes the unsupported-driver contract test, so +CI does not run the focused test task a second time. The focused task remains +available for local diagnosis. + +The hosted workflow uses architecture-specific cache namespaces and does not +cache Cargo-installed binaries. -The ARM64 job is scaffolded but disabled until a Windows ARM64 runner is -available. Once enabled, it should run check, release build, native workspace -tests, and the focused unsupported-driver contracts for -`aarch64-pc-windows-msvc`. +The local aggregate `windows:ci` task can still cross-build ARM64 on an x64 +host. Hosted tests use architecture-matched runners, so ARM64 test results are +native rather than emulated coverage. ## Validation Contract diff --git a/crates/openshell-conformance/src/plan.rs b/crates/openshell-conformance/src/plan.rs index ad955ea5f6..955c4b7765 100644 --- a/crates/openshell-conformance/src/plan.rs +++ b/crates/openshell-conformance/src/plan.rs @@ -124,9 +124,19 @@ fn validate_command(label: &str, command: &Path, timeout_secs: u64) -> Result<() mod tests { use super::*; + #[cfg(not(windows))] + const RESTART_GATEWAY_COMMAND: &str = "/usr/local/libexec/restart-gateway"; + #[cfg(windows)] + const RESTART_GATEWAY_COMMAND: &str = r"C:\usr\local\libexec\restart-gateway"; + + #[cfg(not(windows))] + const DIAGNOSTICS_COMMAND: &str = "/usr/local/libexec/diagnostics"; + #[cfg(windows)] + const DIAGNOSTICS_COMMAND: &str = r"C:\usr\local\libexec\diagnostics"; + #[test] fn parses_a_smoke_and_continuity_plan() { - let plan = ConformancePlan::parse( + let plan = ConformancePlan::parse(&format!( r#" version = 1 @@ -139,10 +149,10 @@ mod tests { [[runs.actions]] name = "gateway-upgrade" - command = "/usr/local/libexec/restart-gateway" + command = '{RESTART_GATEWAY_COMMAND}' timeout_secs = 120 "#, - ) + )) .expect("valid plan"); assert_eq!(plan.runs.len(), 2); @@ -151,18 +161,18 @@ mod tests { #[test] fn parses_plan_diagnostics() { - let plan = ConformancePlan::parse( + let plan = ConformancePlan::parse(&format!( r#" version = 1 [diagnostics] - command = "/usr/local/libexec/diagnostics" + command = '{DIAGNOSTICS_COMMAND}' timeout_secs = 60 [[runs]] scenario = "smoke" "#, - ) + )) .expect("valid plan with diagnostics"); assert_eq!( diff --git a/crates/openshell-driver-mxc/src/driver.rs b/crates/openshell-driver-mxc/src/driver.rs index 62f134205b..816597390d 100644 --- a/crates/openshell-driver-mxc/src/driver.rs +++ b/crates/openshell-driver-mxc/src/driver.rs @@ -293,10 +293,11 @@ impl MxcComputeBackend { driver_reports_runtime_readiness: true, resource_capabilities: None, rootfs_tar_staging_dir: String::new(), + rootfs_tar_max_bytes: 0, } } - fn validate_sandbox_fields(&self, sandbox: &DriverSandbox) -> Result<(), tonic::Status> { + fn validate_sandbox_fields(sandbox: &DriverSandbox) -> Result<(), tonic::Status> { if let Some(spec) = &sandbox.spec { if effective_driver_gpu_count(driver_gpu_requirements( spec.resource_requirements.as_ref(), @@ -337,7 +338,7 @@ impl MxcComputeBackend { } pub fn validate_sandbox_create(&self, sandbox: &DriverSandbox) -> Result<(), tonic::Status> { - self.validate_sandbox_fields(sandbox)?; + Self::validate_sandbox_fields(sandbox)?; let policy = sandbox.spec.as_ref().and_then(|spec| spec.policy.as_ref()); self.map_sandbox_policy(&sandbox.id, policy)?; Ok(()) @@ -358,7 +359,7 @@ impl MxcComputeBackend { pub async fn create_sandbox(&self, sandbox: &DriverSandbox) -> Result<(), tonic::Status> { let sandbox_id = sandbox.id.clone(); - self.validate_sandbox_fields(sandbox)?; + Self::validate_sandbox_fields(sandbox)?; let sandbox_config = sandbox_config(sandbox)?; // Policy translation is deterministic and side-effect free. Do it before diff --git a/crates/openshell-driver-mxc/src/grpc.rs b/crates/openshell-driver-mxc/src/grpc.rs index dfe8f66b29..9a166057ef 100644 --- a/crates/openshell-driver-mxc/src/grpc.rs +++ b/crates/openshell-driver-mxc/src/grpc.rs @@ -202,6 +202,20 @@ mod tests { assert!(error.message().contains("does not support restarting")); } + #[tokio::test] + async fn sandbox_authentication_is_not_supported() { + let service = + ComputeDriverService::new(MxcComputeBackend::new(MxcComputeConfig::default())); + + let error = service + .authenticate_sandbox(Request::new(AuthenticateSandboxRequest::default())) + .await + .expect_err("MXC must not advertise sandbox credential authentication"); + + assert_eq!(error.code(), tonic::Code::Unimplemented); + assert!(error.message().contains("does not authenticate")); + } + #[tokio::test] async fn workspace_lifecycle_is_an_idempotent_no_op() { let service = diff --git a/crates/openshell-prover/Cargo.toml b/crates/openshell-prover/Cargo.toml index ee815f3a3f..b620280e46 100644 --- a/crates/openshell-prover/Cargo.toml +++ b/crates/openshell-prover/Cargo.toml @@ -12,6 +12,7 @@ repository.workspace = true [features] bundled-z3 = ["z3/bundled"] +prebuilt-z3 = ["z3/gh-release"] [dependencies] z3 = { workspace = true } diff --git a/crates/openshell-server/Cargo.toml b/crates/openshell-server/Cargo.toml index efff4f36b0..f712665d2a 100644 --- a/crates/openshell-server/Cargo.toml +++ b/crates/openshell-server/Cargo.toml @@ -118,6 +118,7 @@ default = ["telemetry"] ## that contains no telemetry endpoint, HTTP client, or emission code. telemetry = ["openshell-core/telemetry"] bundled-z3 = ["openshell-prover/bundled-z3"] +prebuilt-z3 = ["openshell-prover/prebuilt-z3"] test-support = [] [build-dependencies] diff --git a/crates/openshell-server/src/config_file.rs b/crates/openshell-server/src/config_file.rs index 64ac953624..c4aa8e371b 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -332,7 +332,7 @@ pub enum ConfigFileError { Parse { path: PathBuf, #[source] - source: toml::de::Error, + source: Box, }, #[error( "unsupported gateway config version {version}; this build only supports version {SCHEMA_VERSION}" @@ -387,7 +387,7 @@ pub fn load(path: &Path) -> Result { } let file: ConfigFile = toml::from_str(&contents).map_err(|source| ConfigFileError::Parse { path: path.to_path_buf(), - source, + source: Box::new(source), })?; if let Some(version) = file.openshell.version diff --git a/deny.toml b/deny.toml index b91a0699ff..032cfcce3b 100644 --- a/deny.toml +++ b/deny.toml @@ -38,6 +38,9 @@ allow = [ "BSD-2-Clause", "BSD-3-Clause", "BSL-1.0", + # Permissive, non-copyleft license pulled in by the prebuilt Z3 archive + # path (z3-sys -> zip -> bzip2); compatible with this Apache-2.0 project. + "bzip2-1.0.6", "ISC", "Zlib", "0BSD", @@ -53,7 +56,9 @@ registries = [] # -- Bans ---------------------------------------------------------------------- [bans] -deny = [{ name = "ring", reason = "Use the AWS-LC crypto backend instead." }] +deny = [ + { name = "ring", wrappers = ["rustls", "rustls-webpki"], reason = "Use the AWS-LC crypto backend instead. These wrappers are required only by z3-sys's prebuilt archive downloader." }, +] multiple-versions = "warn" wildcards = "allow" highlight = "all" diff --git a/mise.lock b/mise.lock index 597f54fecb..522084b559 100644 --- a/mise.lock +++ b/mise.lock @@ -134,6 +134,40 @@ checksum = "sha256:b8514ed7552e148b0a032114f745118dcb801791adafafeaf9935e4bfb0ed url = "https://github.com/mozilla/sccache/releases/download/v0.16.0/sccache-v0.16.0-x86_64-pc-windows-msvc.zip" url_api = "https://api.github.com/repos/mozilla/sccache/releases/assets/452060720" +[[tools."github:nextest-rs/nextest"]] +version = "cargo-nextest-0.9.143" +backend = "github:nextest-rs/nextest" + +[tools."github:nextest-rs/nextest"."platforms.linux-arm64"] +checksum = "sha256:2a64b3566a92508550a7ab29c3e8db25472ca37730ecb4d22100b6aa440c2a68" +url = "https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-0.9.143/cargo-nextest-0.9.143-aarch64-unknown-linux-gnu.tar.gz" +url_api = "https://api.github.com/repos/nextest-rs/nextest/releases/assets/501881925" +provenance = "github-attestations" + +[tools."github:nextest-rs/nextest"."platforms.linux-x64"] +checksum = "sha256:66786b9abe23920d022a182d1416b1bbc8130dd4872a9553d76985a1708dcd1e" +url = "https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-0.9.143/cargo-nextest-0.9.143-x86_64-unknown-linux-gnu.tar.gz" +url_api = "https://api.github.com/repos/nextest-rs/nextest/releases/assets/501882467" +provenance = "github-attestations" + +[tools."github:nextest-rs/nextest"."platforms.macos-arm64"] +checksum = "sha256:4830d430411148d17602a75cc880bfb4dc8dac153dea59a48a2ef4cc93577f07" +url = "https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-0.9.143/cargo-nextest-0.9.143-universal-apple-darwin.tar.gz" +url_api = "https://api.github.com/repos/nextest-rs/nextest/releases/assets/501885637" +provenance = "github-attestations" + +[tools."github:nextest-rs/nextest"."platforms.windows-arm64"] +checksum = "sha256:58c1637ba2396e6c556aa0092f9aa4388695594b8ddda5a4b8b39212574678ce" +url = "https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-0.9.143/cargo-nextest-0.9.143-aarch64-pc-windows-msvc.zip" +url_api = "https://api.github.com/repos/nextest-rs/nextest/releases/assets/501886128" +provenance = "github-attestations" + +[tools."github:nextest-rs/nextest"."platforms.windows-x64"] +checksum = "sha256:c670ba18e8731fd2eff33a47af33a0fa53d1afa6d0678344e82dc6f8fc7344ac" +url = "https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-0.9.143/cargo-nextest-0.9.143-x86_64-pc-windows-msvc.zip" +url_api = "https://api.github.com/repos/nextest-rs/nextest/releases/assets/501885754" +provenance = "github-attestations" + [[tools."github:rust-cross/cargo-zigbuild"]] version = "0.22.3" backend = "github:rust-cross/cargo-zigbuild" diff --git a/mise.toml b/mise.toml index 94cafcc738..89d4ef5727 100644 --- a/mise.toml +++ b/mise.toml @@ -45,6 +45,7 @@ k3d = { version = "5.8.3", os = ["macos"] } zig = "0.14.1" "github:rust-secure-code/cargo-auditable" = "0.7.5" "github:rust-cross/cargo-zigbuild" = "0.22.3" +"github:nextest-rs/nextest" = { version = "cargo-nextest-0.9.143", os = ["windows"] } "npm:markdownlint-cli2" = "0.22.0" [tools."github:mozilla/sccache"] diff --git a/tasks/scripts/windows-msvc.ps1 b/tasks/scripts/windows-msvc.ps1 index 0a0410f4ca..cab42fb719 100644 --- a/tasks/scripts/windows-msvc.ps1 +++ b/tasks/scripts/windows-msvc.ps1 @@ -32,24 +32,11 @@ if (-not (Test-Path $LogDir)) { } $LogDir = (Resolve-Path $LogDir).Path -$TargetDirWasConfigured = -not [string]::IsNullOrWhiteSpace($env:CARGO_TARGET_DIR) $TargetDir = $env:CARGO_TARGET_DIR -if (-not $TargetDirWasConfigured) { +if ([string]::IsNullOrWhiteSpace($TargetDir)) { $TargetDir = Join-Path $RepoRoot "target" } -$BundledZ3CacheRoot = $TargetDir -if (-not $TargetDirWasConfigured) { - $userCacheRoot = [Environment]::GetFolderPath([Environment+SpecialFolder]::LocalApplicationData) - if ([string]::IsNullOrWhiteSpace($userCacheRoot)) { - $userCacheRoot = $env:LOCALAPPDATA - } - if ([string]::IsNullOrWhiteSpace($userCacheRoot)) { - $userCacheRoot = [IO.Path]::GetTempPath() - } - $BundledZ3CacheRoot = Join-Path $userCacheRoot "OpenShell\cache\z3" -} - $BuildJobsValue = $env:OPENSHELL_WINDOWS_BUILD_JOBS if ([string]::IsNullOrWhiteSpace($BuildJobsValue)) { $BuildJobsValue = $env:CARGO_BUILD_JOBS @@ -66,14 +53,11 @@ $WindowsCargoMutex = [System.Threading.Mutex]::new($false, "Local\OpenShellWindo $UnsupportedDriverPackageExcludes = "--exclude openshell-driver-docker --exclude openshell-driver-kubernetes --exclude openshell-driver-kubernetes-secrets --exclude openshell-driver-podman --exclude openshell-driver-vault --exclude openshell-driver-vm --exclude openshell-sandbox --exclude openshell-supervisor-network --exclude openshell-supervisor-process --exclude openshell-vfio" $WindowsClippyPackageExcludes = $UnsupportedDriverPackageExcludes $WindowsClippyLintArgs = "-D warnings -A dead-code -A unused-imports -A clippy::unused-async" -$BundledZ3WorkspaceFeatures = "--features openshell-prover/bundled-z3" -$BundledZ3ServerFeatures = "--features openshell-server/bundled-z3,openshell-prover/bundled-z3" -$BundledZ3Repository = "https://github.com/Z3Prover/z3.git" -$BundledZ3SysVersion = "0.11.0" -# This is the matching Z3 4.16.0 source revision. Update both pins together. -$BundledZ3Revision = "ddb49568d3520e99799e364fb22f35fc67d887b1" -$Z3WorkspaceFeatures = $BundledZ3WorkspaceFeatures -$Z3ServerFeatures = $BundledZ3ServerFeatures +$PrebuiltZ3WorkspaceFeatures = "--features openshell-prover/prebuilt-z3" +$PrebuiltZ3ServerFeatures = "--features openshell-server/prebuilt-z3,openshell-prover/prebuilt-z3" +$PrebuiltZ3Version = "4.16.0" +$Z3WorkspaceFeatures = $PrebuiltZ3WorkspaceFeatures +$Z3ServerFeatures = $PrebuiltZ3ServerFeatures function Get-VsInstallRoots { $programFiles = @( @@ -367,109 +351,14 @@ function Resolve-Z3HeaderPath([string] $HeaderPath) { return (Resolve-Path $HeaderPath).Path } -function Assert-BundledZ3Source([string] $SourcePath, [string] $ExpectedRevision) { - if (-not (Test-Path $SourcePath -PathType Container)) { - throw "Bundled Z3 source directory does not exist: $SourcePath" - } - - $header = Join-Path $SourcePath "src\api\z3.h" - if (-not (Test-Path $header -PathType Leaf)) { - throw "Bundled Z3 source directory does not contain src\api\z3.h: $SourcePath" - } - - if (-not [string]::IsNullOrWhiteSpace($ExpectedRevision)) { - $actualRevision = (& git -C $SourcePath rev-parse HEAD 2>$null) - if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($actualRevision)) { - throw "Could not verify the bundled Z3 source revision at: $SourcePath" - } - if ($actualRevision.Trim() -ne $ExpectedRevision) { - throw "Bundled Z3 source revision mismatch at ${SourcePath}: expected $ExpectedRevision, found $($actualRevision.Trim())" - } - } - - return (Resolve-Path $SourcePath).Path -} - -function Resolve-BundledZ3Source { - if (-not [string]::IsNullOrWhiteSpace($env:Z3_SYS_BUNDLED_DIR_OVERRIDE)) { - return Assert-BundledZ3Source $env:Z3_SYS_BUNDLED_DIR_OVERRIDE "" - } - - $cargoLock = Get-Content (Join-Path $RepoRoot "Cargo.lock") -Raw - $packagePattern = '(?ms)^\[\[package\]\]\s+name = "z3-sys"\s+version = "([^"]+)"' - $packageMatches = [regex]::Matches($cargoLock, $packagePattern) - if ($packageMatches.Count -ne 1 -or $packageMatches[0].Groups[1].Value -ne $BundledZ3SysVersion) { - throw "Bundled Z3 source pin expects z3-sys $BundledZ3SysVersion. Update the version and revision pins for the z3-sys version in Cargo.lock." - } - - $revisionPrefix = $BundledZ3Revision.Substring(0, 12) - $sourcePath = Join-Path $BundledZ3CacheRoot "z3-source-$revisionPrefix" - if (Test-Path $sourcePath) { - return Assert-BundledZ3Source $sourcePath $BundledZ3Revision - } - - if (-not (Get-Command git.exe -ErrorAction SilentlyContinue)) { - throw "Bundled Z3 source preparation requires git.exe on PATH." - } - if (-not (Test-Path $BundledZ3CacheRoot -PathType Container)) { - New-Item -ItemType Directory -Force -Path $BundledZ3CacheRoot | Out-Null - } - - $stagingPath = "$sourcePath.partial-$([guid]::NewGuid().ToString('N'))" - Write-Host "==> Fetching bundled Z3 source" - Write-Host " repository: $BundledZ3Repository" - Write-Host " revision: $BundledZ3Revision" - Write-Host " cache: $sourcePath" - - & git init --quiet $stagingPath - if ($LASTEXITCODE -ne 0) { - throw "git init failed while preparing bundled Z3 source at: $stagingPath" - } - & git -C $stagingPath remote add origin $BundledZ3Repository - if ($LASTEXITCODE -ne 0) { - throw "git remote add failed while preparing bundled Z3 source at: $stagingPath" - } - & git -C $stagingPath fetch --quiet --depth 1 origin $BundledZ3Revision - if ($LASTEXITCODE -ne 0) { - throw "git fetch failed for bundled Z3 revision $BundledZ3Revision. Partial source remains at: $stagingPath" - } - & git -C $stagingPath checkout --quiet --detach FETCH_HEAD - if ($LASTEXITCODE -ne 0) { - throw "git checkout failed for bundled Z3 revision $BundledZ3Revision. Partial source remains at: $stagingPath" - } - - Assert-BundledZ3Source $stagingPath $BundledZ3Revision | Out-Null - try { - # Directory.Move is an atomic rename on the same volume and, unlike - # Move-Item, fails when the destination already exists. A concurrent - # x64/ARM64 invocation can therefore win publication without the loser - # nesting its staging directory inside the shared cache. - [IO.Directory]::Move($stagingPath, $sourcePath) - } catch { - if (-not (Test-Path $sourcePath -PathType Container)) { - throw - } - Write-Host "==> Reusing bundled Z3 source published by another process" - } finally { - if (Test-Path $stagingPath -PathType Container) { - try { - Remove-Item -LiteralPath $stagingPath -Recurse -Force - } catch { - Write-Warning "Could not remove redundant bundled Z3 staging directory: $stagingPath" - } - } - } - return Assert-BundledZ3Source $sourcePath $BundledZ3Revision -} - function Configure-Z3 { if ([string]::IsNullOrWhiteSpace($env:Z3_LIBRARY_PATH_OVERRIDE)) { - Write-Host "==> Z3: bundled" - $env:Z3_SYS_BUNDLED_DIR_OVERRIDE = Resolve-BundledZ3Source - Write-Host " Z3_SYS_BUNDLED_DIR_OVERRIDE=$env:Z3_SYS_BUNDLED_DIR_OVERRIDE" + Write-Host "==> Z3: prebuilt release" + $env:Z3_SYS_Z3_VERSION = $PrebuiltZ3Version + Write-Host " Z3_SYS_Z3_VERSION=$env:Z3_SYS_Z3_VERSION" return [pscustomobject]@{ - WorkspaceFeatures = $BundledZ3WorkspaceFeatures - ServerFeatures = $BundledZ3ServerFeatures + WorkspaceFeatures = $PrebuiltZ3WorkspaceFeatures + ServerFeatures = $PrebuiltZ3ServerFeatures } } @@ -516,15 +405,24 @@ function Invoke-VsCargo { $targetArch = Get-VsTargetArch $RustTarget $hostArch = Get-HostArch $logPath = Join-Path $LogDir $LogName + $rustcWrapper = "" + if (-not [string]::IsNullOrWhiteSpace($env:RUSTC_WRAPPER)) { + $wrapperCommand = Get-Command $env:RUSTC_WRAPPER -ErrorAction SilentlyContinue + if ($wrapperCommand) { + $rustcWrapper = $wrapperCommand.Source + } else { + Write-Warning "RUSTC_WRAPPER '$env:RUSTC_WRAPPER' was not found; continuing without it." + } + } $environmentSetup = @( "set `"CARGO_TARGET_DIR=$TargetDir`"", "set `"CARGO_BUILD_JOBS=$WindowsBuildJobs`"", "set `"CARGO_INCREMENTAL=0`"", - "set `"RUSTC_WRAPPER=`"" + "set `"RUSTC_WRAPPER=$rustcWrapper`"" ) if ($hostArch -eq "amd64" -and $RustTarget -eq "aarch64-pc-windows-msvc") { - # Let cmake-rs select MSVC cl.exe for bundled Z3. AWS-LC selects - # clang-cl inside its own ARM64 build script. + # Native ARM64 dependencies select their own compilers. Clear inherited + # overrides so AWS-LC can select clang-cl inside its build script. $environmentSetup += @( "set `"CC=`"", "set `"CXX=`"", @@ -605,6 +503,10 @@ function Invoke-Lint([string] $RustTarget) { -RustTarget $RustTarget ` -CargoArgs "cargo clippy --manifest-path e2e/rust/Cargo.toml --all-targets --no-deps --target $RustTarget -- $WindowsClippyLintArgs" ` -LogName "lint-$RustTarget-e2e.log" + Invoke-VsCargo ` + -RustTarget $RustTarget ` + -CargoArgs "cargo check --manifest-path examples/governance-interceptor/Cargo.toml --all-targets --target $RustTarget" ` + -LogName "lint-$RustTarget-governance-interceptor.log" } function Invoke-Build([string] $RustTarget) { @@ -618,7 +520,7 @@ function Invoke-Test([string] $RustTarget) { Assert-NativeTestTarget $RustTarget Invoke-VsCargo ` -RustTarget $RustTarget ` - -CargoArgs "cargo test --workspace $UnsupportedDriverPackageExcludes --target $RustTarget --no-fail-fast $Z3WorkspaceFeatures" ` + -CargoArgs "cargo nextest run --profile ci --workspace $UnsupportedDriverPackageExcludes --target $RustTarget $Z3WorkspaceFeatures" ` -LogName "test-$RustTarget.log" } @@ -626,12 +528,8 @@ function Invoke-PreCommitTest([string] $RustTarget) { Assert-NativeTestTarget $RustTarget Invoke-VsCargo ` -RustTarget $RustTarget ` - -CargoArgs "cargo test --workspace --exclude openshell-server $UnsupportedDriverPackageExcludes --target $RustTarget --no-fail-fast $Z3WorkspaceFeatures" ` - -LogName "test-$RustTarget-precommit-workspace.log" - Invoke-VsCargo ` - -RustTarget $RustTarget ` - -CargoArgs "cargo test -p openshell-server --features test-support --target $RustTarget --no-fail-fast $Z3ServerFeatures" ` - -LogName "test-$RustTarget-precommit-server.log" + -CargoArgs "cargo nextest run --profile ci --workspace $UnsupportedDriverPackageExcludes --target $RustTarget --features openshell-server/test-support $Z3ServerFeatures" ` + -LogName "test-$RustTarget-precommit.log" } function Invoke-UnsupportedContractTests([string] $RustTarget) { @@ -750,7 +648,7 @@ switch ($Action) { foreach ($rustTarget in $targets) { Invoke-Build $rustTarget } - Invoke-Test "x86_64-pc-windows-msvc" + Invoke-PreCommitTest "x86_64-pc-windows-msvc" Invoke-UnsupportedContractTests "x86_64-pc-windows-msvc" Show-Artifacts $targets } diff --git a/tasks/windows.toml b/tasks/windows.toml index 59c2a8f2c2..708ba2c248 100644 --- a/tasks/windows.toml +++ b/tasks/windows.toml @@ -1,8 +1,9 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# Windows MSVC build-only tasks. These intentionally live outside the default -# Linux/macOS `ci` task so the established Linux build path remains unchanged. +# Windows MSVC validation and build tasks. These intentionally live outside +# the Linux/macOS task definitions so each hosted workflow has an explicit +# platform-native entry point. ["windows:check"] description = "Check Windows x64 and ARM64 MSVC targets" @@ -19,6 +20,16 @@ description = "Check Windows ARM64 MSVC target" run = "echo 'windows:* tasks require a Windows MSVC host' && exit 1" run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 check aarch64-pc-windows-msvc" +["windows:lint:x64"] +description = "Lint Windows x64 MSVC workspace targets with Clippy" +run = "echo 'windows:* tasks require a Windows MSVC host' && exit 1" +run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 lint x86_64-pc-windows-msvc" + +["windows:lint:arm64"] +description = "Lint Windows ARM64 MSVC workspace targets with Clippy" +run = "echo 'windows:* tasks require a Windows MSVC host' && exit 1" +run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 lint aarch64-pc-windows-msvc" + ["windows:build"] description = "Build Windows x64 and ARM64 release binaries" run = "echo 'windows:* tasks require a Windows MSVC host' && exit 1" @@ -35,14 +46,14 @@ run = "echo 'windows:* tasks require a Windows MSVC host' && exit 1" run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 build aarch64-pc-windows-msvc" ["windows:test:x64"] -description = "Run Windows x64 MSVC workspace tests" +description = "Run Windows x64 MSVC workspace tests with the CI nextest profile and server test support" run = "echo 'windows:* tasks require a Windows MSVC host' && exit 1" -run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 test x86_64-pc-windows-msvc" +run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 test-precommit x86_64-pc-windows-msvc" ["windows:test:arm64"] -description = "Run Windows ARM64 MSVC workspace tests on a native ARM64 host" +description = "Run Windows ARM64 MSVC workspace tests with the CI nextest profile and server test support on a native ARM64 host" run = "echo 'windows:* tasks require a Windows MSVC host' && exit 1" -run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 test aarch64-pc-windows-msvc" +run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 test-precommit aarch64-pc-windows-msvc" ["windows:test:unsupported:x64"] description = "Run focused Windows unsupported compute-driver contract tests" From 33bbda3d3374b85fe6c3ea0bcce1d456512607df Mon Sep 17 00:00:00 2001 From: Drew Newberry Date: Fri, 11 Sep 2026 00:02:07 +0000 Subject: [PATCH 08/12] refactor(persistence): adopt continuation-token pagination (#3249) * refactor(persistence): adopt continuation-token pagination Signed-off-by: Drew Newberry * fix(pagination): address continuation review findings Signed-off-by: Drew Newberry * fix(tui): recover completed list refreshes Signed-off-by: Drew Newberry * fix(pagination): address review scalability findings Signed-off-by: Drew Newberry * fix(pagination): repair branch validation Signed-off-by: Drew Newberry * docs(go): use page size in template example Signed-off-by: Drew Newberry --------- Signed-off-by: Drew Newberry --- .agents/skills/create-github-pr/SKILL.md | 8 +- .agents/skills/tui-development/SKILL.md | 27 +- Cargo.lock | 1 + architecture/gateway.md | 34 +- crates/openshell-cli/src/commands/provider.rs | 62 +- crates/openshell-cli/src/completers.rs | 12 +- crates/openshell-cli/src/main.rs | 161 ++-- crates/openshell-cli/src/output.rs | 179 +++++ crates/openshell-cli/src/run.rs | 172 +++-- .../tests/ensure_providers_integration.rs | 10 +- .../tests/provider_commands_integration.rs | 18 +- .../sandbox_create_lifecycle_integration.rs | 13 +- .../src/scenarios/smoke.rs | 40 +- crates/openshell-core/src/proto/mod.rs | 5 + crates/openshell-sdk/README.md | 6 + crates/openshell-sdk/src/client.rs | 254 ++++--- crates/openshell-sdk/src/types.rs | 12 +- crates/openshell-sdk/tests/client_mock.rs | 71 +- .../postgres/008_add_pagination_indexes.sql | 6 + .../sqlite/008_add_pagination_indexes.sql | 6 + crates/openshell-server/src/compute/mod.rs | 39 +- crates/openshell-server/src/grpc/mod.rs | 43 -- crates/openshell-server/src/grpc/policy.rs | 169 ++++- crates/openshell-server/src/grpc/provider.rs | 301 +++++--- crates/openshell-server/src/grpc/sandbox.rs | 219 +++--- crates/openshell-server/src/grpc/service.rs | 116 +-- crates/openshell-server/src/grpc/workspace.rs | 104 +-- crates/openshell-server/src/lib.rs | 1 + crates/openshell-server/src/pagination.rs | 245 ++++++ .../openshell-server/src/persistence/mod.rs | 148 +++- .../src/persistence/postgres.rs | 128 +++- .../src/persistence/sqlite.rs | 216 ++++-- .../openshell-server/src/persistence/tests.rs | 44 +- crates/openshell-server/src/policy_store.rs | 28 + .../src/provider_profile_sources.rs | 10 +- .../openshell-server/src/provider_refresh.rs | 53 +- crates/openshell-server/src/storage_proto.rs | 2 +- crates/openshell-tui/Cargo.toml | 1 + crates/openshell-tui/src/app.rs | 30 + crates/openshell-tui/src/event.rs | 4 + crates/openshell-tui/src/lib.rs | 699 ++++++++++++------ docs/sandboxes/manage-providers.mdx | 9 +- docs/sandboxes/manage-sandboxes.mdx | 14 +- docs/sandboxes/manage-workspaces.mdx | 4 +- docs/sandboxes/policies.mdx | 6 +- e2e/python/conftest.py | 2 +- e2e/python/test_sandbox_api.py | 2 +- e2e/python/test_sandbox_providers.py | 8 +- examples/governance-interceptor/src/main.rs | 13 +- examples/transparent-tcp-redis/demo.sh | 2 +- proto/openshell.proto | 82 +- proto/pagination.proto | 40 + python/openshell/sandbox.py | 151 ++-- python/openshell/sandbox_test.py | 50 +- sdk/go/docs/src/api/providers.md | 8 +- sdk/go/docs/src/api/sandbox-templates.md | 8 +- sdk/go/docs/src/api/sandboxes.md | 8 +- sdk/go/openshell/v1/fake/policy.go | 14 +- sdk/go/openshell/v1/fake/policy_test.go | 15 +- sdk/go/openshell/v1/fake/sandbox_template.go | 23 +- .../v1/fake/sandbox_template_test.go | 24 +- sdk/go/openshell/v1/options.go | 15 + sdk/go/openshell/v1/policy.go | 7 +- sdk/go/openshell/v1/policy_client.go | 35 +- sdk/go/openshell/v1/policy_client_test.go | 24 +- sdk/go/openshell/v1/profile_client.go | 34 +- sdk/go/openshell/v1/profile_client_test.go | 7 +- sdk/go/openshell/v1/provider_client.go | 33 +- sdk/go/openshell/v1/provider_client_test.go | 1 + sdk/go/openshell/v1/sandbox_client.go | 35 +- sdk/go/openshell/v1/sandbox_client_test.go | 47 +- .../openshell/v1/sandbox_template_client.go | 35 +- .../v1/sandbox_template_client_test.go | 23 +- sdk/go/openshell/v1/service_client.go | 33 +- sdk/go/openshell/v1/service_client_test.go | 5 +- sdk/go/openshell/v1/types/options.go | 3 +- sdk/go/openshell/v1/types/policy.go | 29 +- sdk/go/openshell/v1/workspace_client.go | 70 +- sdk/go/openshell/v1/workspace_test.go | 39 +- sdk/go/proto/openshellv1/openshell.pb.go | 370 +++++---- sdk/typescript/README.md | 4 +- sdk/typescript/src/client.test.ts | 38 +- sdk/typescript/src/client.ts | 48 +- skills/openshell-cli/SKILL.md | 2 +- 84 files changed, 3544 insertions(+), 1573 deletions(-) create mode 100644 crates/openshell-server/migrations/postgres/008_add_pagination_indexes.sql create mode 100644 crates/openshell-server/migrations/sqlite/008_add_pagination_indexes.sql create mode 100644 crates/openshell-server/src/pagination.rs create mode 100644 proto/pagination.proto diff --git a/.agents/skills/create-github-pr/SKILL.md b/.agents/skills/create-github-pr/SKILL.md index 8e14bc5f9a..5eafc91f9b 100644 --- a/.agents/skills/create-github-pr/SKILL.md +++ b/.agents/skills/create-github-pr/SKILL.md @@ -187,7 +187,7 @@ gh pr create \ --body "$(cat <<'EOF' ## Summary -Add `--limit` and `--offset` flags to `openshell sandbox list` for pagination. +Add `--page-size` and `--page-token` flags to `openshell sandbox list` for continuation-token pagination. ## Related Issue @@ -195,9 +195,9 @@ Closes #456 ## Changes -- Added `offset` and `limit` query parameters to the sandbox list API call -- Default limit is 20, max is 100 -- Response includes `total_count` field +- Added `page_size` and `page_token` fields to the sandbox list API call +- Default page size is 100, max is 1,000 +- Structured responses include `next_page_token` ## Testing diff --git a/.agents/skills/tui-development/SKILL.md b/.agents/skills/tui-development/SKILL.md index edd1397d56..ceb6d45405 100644 --- a/.agents/skills/tui-development/SKILL.md +++ b/.agents/skills/tui-development/SKILL.md @@ -170,13 +170,15 @@ Phase 1: GetSandboxLogs → 500 initial lines → send via Event::LogLines Phase 2: WatchSandbox(follow_logs: true) → live tail → send via Event::LogLines ``` -**Sandboxes**: Fetched via `ListSandboxes` on a 2-second tick, scoped to the current workspace (or all workspaces). +**Sandboxes**: Fetched via `ListSandboxes` in a background collection-refresh task scheduled from the 2-second tick, scoped to the current workspace (or all workspaces). Follow `next_page_token` until empty so the dashboard reflects the complete collection. -**Providers**: Fetched via `ListProviders` on each tick. Provider profiles are fetched per-workspace via `ListProviderProfiles` and cached in a `ProviderProfileCache` keyed by `(workspace, profile_id)`. +**Providers**: Fetched via `ListProviders` in the background collection-refresh task. Provider profiles are fetched per-workspace via `ListProviderProfiles` and cached in a `ProviderProfileCache` keyed by `(workspace, profile_id)`. Follow each list RPC's `next_page_token` until empty. **Settings**: Global settings are fetched via `GetGatewayConfig` on each tick. Sandbox settings are fetched alongside the sandbox policy via `GetSandboxConfig` and refreshed on each tick when viewing a sandbox. -**Workspaces**: The workspace list is fetched via `ListWorkspaces` on each tick. +**Workspaces**: The workspace list is fetched via `ListWorkspaces` in the background collection-refresh task, following `next_page_token` until empty. + +Only one collection-refresh task may run at a time. Workspace and gateway changes abort the active task, and refresh results carry their gateway/workspace context so stale results are discarded. ### Never block the event loop @@ -411,9 +413,9 @@ All actions are accessible via keyboard shortcuts displayed in the nav bar. The | File | Purpose | | --- | --- | | `crates/openshell-tui/Cargo.toml` | Crate manifest — dependencies on `openshell-core`, `openshell-bootstrap`, `ratatui`, `crossterm`, `tonic`, `tokio` | -| `crates/openshell-tui/src/lib.rs` | Entry point. Event loop, gRPC calls (`refresh_data`, `refresh_providers`, `refresh_global_settings`, `refresh_workspaces`, `refresh_sandboxes`, `spawn_log_stream`, `handle_sandbox_delete`), gateway switching, mTLS channel building, provider CRUD spawners, settings CRUD spawners, draft approval spawners | +| `crates/openshell-tui/src/lib.rs` | Entry point. Event loop, background collection refresh (`spawn_list_refresh`), gRPC calls (`refresh_global_settings`, `spawn_log_stream`, `handle_sandbox_delete`), gateway switching, mTLS channel building, provider CRUD spawners, settings CRUD spawners, draft approval spawners | | `crates/openshell-tui/src/app.rs` | `App` state struct, `Screen`/`Focus`/`InputMode`/`LogSourceFilter`/`MiddlePaneTab`/`SandboxPolicyTab` enums, `LogLine`/`GatewayEntry`/`GlobalSettingEntry`/`SandboxSettingEntry`/`ProviderListEntry`/`ProviderDetailView` structs, create sandbox/provider form state, all key handling logic | -| `crates/openshell-tui/src/event.rs` | `Event` enum (`Key`, `Mouse`, `Tick`, `Redraw`, `Resize`, `LogLines`, `CreateResult`, `ProviderCreateResult`, `ProviderDetailFetched`, `ProviderUpdateResult`, `ProviderDeleteResult`, `DraftActionResult`, `GlobalSettingsFetched`, `GlobalSettingSetResult`, `GlobalSettingDeleteResult`, `SandboxSettingSetResult`, `SandboxSettingDeleteResult`, `ForwardWarnings`), `EventHandler` with mpsc channels and crossterm polling | +| `crates/openshell-tui/src/event.rs` | `Event` enum (`Key`, `Mouse`, `Tick`, `Redraw`, `Resize`, `LogLines`, `ListRefreshCompleted`, `CreateResult`, `ProviderCreateResult`, `ProviderDetailFetched`, `ProviderUpdateResult`, `ProviderDeleteResult`, `DraftActionResult`, `GlobalSettingsFetched`, `GlobalSettingSetResult`, `GlobalSettingDeleteResult`, `SandboxSettingSetResult`, `SandboxSettingDeleteResult`, `ForwardWarnings`), `EventHandler` with mpsc channels and crossterm polling | | `crates/openshell-tui/src/theme.rs` | `colors` module (NVIDIA_GREEN, EVERGLADE, BG, FG) and `styles` module (all `Style` constants) | | `crates/openshell-tui/src/clipboard.rs` | Clipboard copy support for log lines | | `crates/openshell-tui/src/ui/mod.rs` | Top-level `draw()` dispatcher, `draw_title_bar` (with workspace display), `draw_nav_bar`, `draw_command_bar`, screen routing, shared setting-edit overlay, modal helpers | @@ -502,12 +504,15 @@ use openshell_core::proto::{ `Some(all_workspaces_selector())`; do not use that marker on other requests. - `GetSandboxLogsRequest` fields: `sandbox_id`, `lines` (u32), `since_ms` (i64), `sources` (Vec), `min_level` (String), `workspace_scope`. -- `ListSandboxesRequest` fields: `limit` (u32), `offset` (u32), +- `ListSandboxesRequest` fields: `page_size` (i32), `page_token` (String), `label_selector` (String), `workspace_scope`. -- `ListProvidersRequest` fields: `limit` (u32), `offset` (u32), +- `ListProvidersRequest` fields: `page_size` (i32), `page_token` (String), `workspace_scope`. -- `ListWorkspacesRequest` fields: `limit` (u32), `offset` (u32), +- `ListWorkspacesRequest` fields: `page_size` (i32), `page_token` (String), `label_selector` (String). +- Paginated list responses return `next_page_token`. Continue with the same + request parameters and that token until it is empty; changing filters or + scope invalidates the token. - `UpdateConfigRequest` fields include `name` (String, sandbox name or empty for global), `setting_key`, `setting_value`, `delete_setting` (bool), `global` (bool), and `workspace_scope`. Sandbox-scoped updates require a named selector; @@ -543,7 +548,7 @@ The connect timeout for gateway switching is 10 seconds with HTTP/2 keepalive at 4. On success: - `app.client` is replaced with a new intercepted client - `reset_sandbox_state()` clears all sandbox/log/draft/policy data - - `refresh_data()` runs the full capability refresh sequence: `refresh_health` → `refresh_global_settings` → `refresh_workspaces` → `refresh_providers` → `refresh_sandboxes` + - health and global settings are refreshed, then `spawn_list_refresh()` starts the cancellable workspace/provider/sandbox refresh task 5. On failure: `status_text` shows the error ### Initial startup lifecycle @@ -551,13 +556,13 @@ The connect timeout for gateway switching is 10 seconds with HTTP/2 keepalive at On launch, before the event loop starts: 1. `refresh_gateway_list()` — discover gateways from disk -2. `refresh_data()` — full refresh (health, global settings, workspaces, providers, sandboxes) +2. Refresh health and global settings, then start `spawn_list_refresh()` for workspaces, providers, and sandboxes ### Workspace switching lifecycle 1. User presses `[w]` on the providers or sandboxes panel → `cycle_workspace()` advances through discovered workspace names, then "all" 2. `pending_workspace_refresh = true` is set, cursor indices are reset -3. Event loop calls `refresh_providers()` and `refresh_sandboxes()` with the new workspace scope +3. Event loop cancels any in-flight collection refresh and starts `spawn_list_refresh()` with the new workspace scope ### Settings CRUD lifecycle (global and sandbox) diff --git a/Cargo.lock b/Cargo.lock index c4ee4d0699..99638e63be 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4707,6 +4707,7 @@ version = "0.0.0" dependencies = [ "base64", "crossterm 0.28.1", + "futures", "indexmap", "miette", "openshell-bootstrap", diff --git a/architecture/gateway.md b/architecture/gateway.md index 59b2bd52ed..588b9f56a4 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -329,7 +329,7 @@ Compute-driver, credential-driver, gateway-interceptor, and supervisor-middleware services are compiled contracts for internal extension boundaries, not public gateway RPCs. The current public inventory has 74 methods, 278 messages, and 12 enums -(`c95ae90962c10fb28747db2b645adf4044562a3d208d84dfe4699d677e4364ee`). +(`0f14943574349d02bdc61076c8c5a59a98b627325564ef1a6d21d7941825dc46`). Storage-only messages live in the private, versioned `openshell.storage.v1` package under `crates/openshell-server/proto`. The server @@ -529,11 +529,33 @@ modes: `UpdateProvider`, `UpdateProviderProfiles`, and `UpdateConfig` (policy backfill and sandbox annotation updates). -**Lists.** The `list_messages` and `list_messages_with_selector` helpers decode -protobuf payloads from list results and hydrate `resource_version` from the -authoritative database column into each decoded message, mirroring the -`get_message` pattern. This ensures list responses carry correct versions -without requiring callers to manually hydrate each record. +**Lists.** Public list RPCs follow AIP-158: requests carry direct `page_size` +and `page_token` fields, and responses carry `next_page_token`. The gateway +clamps page sizes to 1,000 and returns opaque base64url continuation tokens. +Tokens bind the RPC and every request parameter except `page_size`, contain no +authorization grant, and use immutable keyset cursors rather than database +offsets. Each page repeats normal authentication and authorization. Pagination +is weakly consistent under concurrent writes and deletes; it does not provide a +historical snapshot. + +The token wire format is a private shared protobuf used only by the gateway. +Public request and response messages repeat the standard AIP fields directly +instead of wrapping them in a shared pagination message. + +The CLI returns paginated JSON and YAML as response-shaped envelopes containing +the resource collection and `next_page_token`; table output reports a non-empty +token on stderr. The TUI traverses complete workspace, provider, profile, and +sandbox collections in one cancellable background refresh task, never overlaps +periodic list refreshes, and discards results after a gateway or workspace +change. + +Persistence distinguishes one-page operations from exhaustive scans. +`list_object_page` and `list_message_page` return one keyset page and its next +cursor. `collect_records` and `collect_messages` exhaust those pages, fail on +database or protobuf decode errors, and hydrate `resource_version` from the +authoritative database column. Internal callers that require every matching +record use the exhaustive helpers; bounded lookups continue to use page-level +methods. **Deletes.** Delete operations are not yet CAS-protected -- the delete request protos do not carry `expected_resource_version`. A `delete_if` primitive exists diff --git a/crates/openshell-cli/src/commands/provider.rs b/crates/openshell-cli/src/commands/provider.rs index e966eb690e..b85fef0013 100644 --- a/crates/openshell-cli/src/commands/provider.rs +++ b/crates/openshell-cli/src/commands/provider.rs @@ -298,18 +298,18 @@ pub async fn ensure_required_providers( let mut known_names: HashSet = HashSet::new(); let mut type_to_name: HashMap = HashMap::new(); { - let mut offset = 0_u32; - let limit = 100_u32; + let mut page_token = String::new(); loop { let response = client .list_providers(ListProvidersRequest { - limit, - offset, + page_size: 100, + page_token, workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; - let providers = response.into_inner().providers; + let response = response.into_inner(); + let providers = response.providers; for provider in &providers { known_names.insert(provider.object_name().to_string()); if !provider.r#type.is_empty() { @@ -319,10 +319,10 @@ pub async fn ensure_required_providers( .or_insert_with(|| provider.object_name().to_string()); } } - if providers.len() < limit as usize { + if response.next_page_token.is_empty() { break; } - offset = offset.saturating_add(limit); + page_token = response.next_page_token; } } @@ -1325,8 +1325,8 @@ fn provider_credential_keys(provider: &Provider) -> Vec { #[allow(clippy::too_many_arguments)] pub async fn provider_list( server: &str, - limit: u32, - offset: u32, + page_size: i32, + page_token: &str, names_only: bool, output: &str, workspace: &str, @@ -1336,8 +1336,8 @@ pub async fn provider_list( let mut client = grpc_client(server, tls).await?; let response = client .list_providers(ListProvidersRequest { - limit, - offset, + page_size, + page_token: page_token.to_string(), workspace_scope: Some(if all_workspaces { openshell_core::proto::all_workspaces_selector() } else { @@ -1346,12 +1346,21 @@ pub async fn provider_list( }) .await .into_diagnostic()?; - let providers = response.into_inner().providers; + let response = response.into_inner(); + let next_page_token = response.next_page_token; + let providers = response.providers; // Handle structured output formats (json, yaml) - if crate::output::print_output_collection(output, &providers, provider_to_json)? { + if crate::output::print_paginated_output_collection( + output, + "providers", + &providers, + &next_page_token, + provider_to_json, + )? { return Ok(()); } + crate::output::print_next_page_token(&next_page_token); if providers.is_empty() { if !names_only { @@ -1444,15 +1453,24 @@ pub async fn provider_list_profiles( tls: &TlsOptions, ) -> Result<()> { let mut client = grpc_client(server, tls).await?; - let response = client - .list_provider_profiles(ListProviderProfilesRequest { - limit: 100, - offset: 0, - workspace: workspace.to_string(), - }) - .await - .into_diagnostic()?; - let mut profiles = response.into_inner().profiles; + let mut page_token = String::new(); + let mut profiles = Vec::new(); + loop { + let response = client + .list_provider_profiles(ListProviderProfilesRequest { + page_size: 100, + page_token, + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()? + .into_inner(); + profiles.extend(response.profiles); + if response.next_page_token.is_empty() { + break; + } + page_token = response.next_page_token; + } profiles.sort_by(|left, right| { left.category .cmp(&right.category) diff --git a/crates/openshell-cli/src/completers.rs b/crates/openshell-cli/src/completers.rs index 0778babbf1..c5fec20634 100644 --- a/crates/openshell-cli/src/completers.rs +++ b/crates/openshell-cli/src/completers.rs @@ -36,8 +36,8 @@ pub fn complete_sandbox_names(_prefix: &OsStr) -> Vec { let mut client = completion_grpc_client(&endpoint, &gateway_name).await?; let response = client .list_sandboxes(ListSandboxesRequest { - limit: 200, - offset: 0, + page_size: 200, + page_token: String::new(), label_selector: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( workspace_from_args(), @@ -63,8 +63,8 @@ pub fn complete_provider_names(_prefix: &OsStr) -> Vec { let mut client = completion_grpc_client(&endpoint, &gateway_name).await?; let response = client .list_providers(ListProvidersRequest { - limit: 200, - offset: 0, + page_size: 200, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( workspace_from_args(), )), @@ -89,8 +89,8 @@ pub fn complete_workspace_names(_prefix: &OsStr) -> Vec { let mut client = completion_grpc_client(&endpoint, &gateway_name).await?; let response = client .list_workspaces(ListWorkspacesRequest { - limit: 200, - offset: 0, + page_size: 200, + page_token: String::new(), label_selector: String::new(), }) .await diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index db18795b68..bffd137c09 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -877,13 +877,13 @@ enum ProviderCommands { /// List providers. #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] List { - /// Maximum number of providers to return. + /// Maximum number of providers to return in this page. #[arg(long, default_value_t = 100)] - limit: u32, + page_size: i32, - /// Offset into the provider list. - #[arg(long, default_value_t = 0)] - offset: u32, + /// Opaque continuation token from a previous page. + #[arg(long, default_value = "")] + page_token: String, /// Print only provider names, one per line. #[arg(long, conflicts_with = "output")] @@ -1440,13 +1440,13 @@ enum SandboxCommands { /// List sandboxes. #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] List { - /// Maximum number of sandboxes to return. + /// Maximum number of sandboxes to return in this page. #[arg(long, default_value_t = 100)] - limit: u32, + page_size: i32, - /// Offset into the sandbox list. - #[arg(long, default_value_t = 0)] - offset: u32, + /// Opaque continuation token from a previous page. + #[arg(long, default_value = "")] + page_token: String, /// Print only sandbox ids (one per line). #[arg(long, conflicts_with_all = ["names", "output"])] @@ -1744,13 +1744,13 @@ enum SandboxTemplateCommands { /// List sandbox workload templates. #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] List { - /// Maximum number of templates to return. + /// Maximum number of templates to return in this page. #[arg(long, default_value_t = 100)] - limit: u32, + page_size: i32, - /// Offset into the template list. - #[arg(long, default_value_t = 0)] - offset: u32, + /// Opaque continuation token from a previous page. + #[arg(long, default_value = "")] + page_token: String, /// Filter templates by labels, e.g. env=prod,team=runtime. #[arg(long)] @@ -1958,9 +1958,13 @@ enum PolicyCommands { #[arg(add = ArgValueCompleter::new(completers::complete_sandbox_names))] name: Option, - /// Maximum number of revisions to return. + /// Maximum number of revisions to return in this page. #[arg(long, default_value_t = 20)] - limit: u32, + page_size: i32, + + /// Opaque continuation token from a previous page. + #[arg(long, default_value = "")] + page_token: String, /// List global policy revisions. #[arg(long)] @@ -2128,13 +2132,13 @@ enum ServiceCommands { #[arg(add = ArgValueCompleter::new(completers::complete_sandbox_names))] sandbox: Option, - /// Maximum number of endpoints to return. + /// Maximum number of endpoints to return in this page. #[arg(long, default_value_t = 100)] - limit: u32, + page_size: i32, - /// Number of endpoints to skip. - #[arg(long, default_value_t = 0)] - offset: u32, + /// Opaque continuation token from a previous page. + #[arg(long, default_value = "")] + page_token: String, /// List services across all workspaces (overrides --workspace). #[arg(long)] @@ -2193,13 +2197,13 @@ enum WorkspaceCommands { /// List workspaces. #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] List { - /// Maximum number of workspaces to return. + /// Maximum number of workspaces to return in this page. #[arg(long, default_value_t = 100)] - limit: u32, + page_size: i32, - /// Offset into the workspace list. - #[arg(long, default_value_t = 0)] - offset: u32, + /// Opaque continuation token from a previous page. + #[arg(long, default_value = "")] + page_token: String, /// Filter by label selector (e.g. "env=staging"). #[arg(long)] @@ -2260,13 +2264,13 @@ enum WorkspaceMemberCommands { #[arg(long, add = ArgValueCompleter::new(completers::complete_workspace_names))] workspace: String, - /// Maximum number of members to return. + /// Maximum number of members to return in this page. #[arg(long, default_value_t = 100)] - limit: u32, + page_size: i32, - /// Offset into the member list. - #[arg(long, default_value_t = 0)] - offset: u32, + /// Opaque continuation token from a previous page. + #[arg(long, default_value = "")] + page_token: String, /// Output format. #[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table)] @@ -2665,16 +2669,16 @@ async fn run_async() -> Result<()> { } ServiceCommands::List { sandbox, - limit, - offset, + page_size, + page_token, all_workspaces, output, } => { run::service_list( &ctx.endpoint, sandbox.as_deref(), - limit, - offset, + page_size, + &page_token, &cli.workspace, all_workspaces, output.as_str(), @@ -2839,14 +2843,16 @@ async fn run_async() -> Result<()> { } PolicyCommands::List { name, - limit, + page_size, + page_token, global, output, } => { if global { run::sandbox_policy_list_global( &ctx.endpoint, - limit, + page_size, + &page_token, output.as_str(), &cli.workspace, &tls, @@ -2857,7 +2863,8 @@ async fn run_async() -> Result<()> { run::sandbox_policy_list( &ctx.endpoint, &name, - limit, + page_size, + &page_token, output.as_str(), &cli.workspace, &tls, @@ -3232,8 +3239,8 @@ async fn run_async() -> Result<()> { .await?; } SandboxCommands::List { - limit, - offset, + page_size, + page_token, ids, names, selector, @@ -3242,8 +3249,8 @@ async fn run_async() -> Result<()> { } => { run::sandbox_list( endpoint, - limit, - offset, + page_size, + &page_token, ids, names, selector.as_deref(), @@ -3423,8 +3430,8 @@ async fn run_async() -> Result<()> { .await?; } SandboxTemplateCommands::List { - limit, - offset, + page_size, + page_token, label_selector, names, output, @@ -3432,8 +3439,8 @@ async fn run_async() -> Result<()> { } => { run::sandbox_template_list( endpoint, - limit, - offset, + page_size, + &page_token, label_selector.as_deref(), names, output.as_str(), @@ -3477,15 +3484,15 @@ async fn run_async() -> Result<()> { run::workspace_get(endpoint, &name, &tls).await?; } WorkspaceCommands::List { - limit, - offset, + page_size, + page_token, label_selector, output, } => { run::workspace_list( endpoint, - limit, - offset, + page_size, + &page_token, label_selector.as_deref().unwrap_or(""), output.as_str(), &tls, @@ -3509,15 +3516,15 @@ async fn run_async() -> Result<()> { } WorkspaceMemberCommands::List { workspace, - limit, - offset, + page_size, + page_token, output, } => { run::workspace_member_list( endpoint, &workspace, - limit, - offset, + page_size, + &page_token, output.as_str(), &tls, ) @@ -3642,16 +3649,16 @@ async fn run_async() -> Result<()> { run::provider_get(endpoint, &name, &cli.workspace, &tls).await?; } ProviderCommands::List { - limit, - offset, + page_size, + page_token, names, output, all_workspaces, } => { run::provider_list( endpoint, - limit, - offset, + page_size, + &page_token, names, output.as_str(), &cli.workspace, @@ -5742,10 +5749,10 @@ mod tests { "--all-workspaces", "--label-selector", "team=runtime", - "--limit", + "--page-size", "25", - "--offset", - "5", + "--page-token", + "next-template-page", ]) .expect("sandbox template list should parse"); @@ -5753,8 +5760,8 @@ mod tests { Some(Commands::Sandbox { command: Some(SandboxCommands::Template(SandboxTemplateCommands::List { - limit, - offset, + page_size, + page_token, label_selector, names, all_workspaces, @@ -5762,8 +5769,8 @@ mod tests { })), .. }) => { - assert_eq!(limit, 25); - assert_eq!(offset, 5); + assert_eq!(page_size, 25); + assert_eq!(page_token, "next-template-page"); assert_eq!(label_selector.as_deref(), Some("team=runtime")); assert!(names); assert!(all_workspaces); @@ -6014,10 +6021,10 @@ mod tests { "service", "list", "my-sandbox", - "--limit", + "--page-size", "10", - "--offset", - "2", + "--page-token", + "next-service-page", ]) .expect("service list should parse optional sandbox and paging"); @@ -6026,14 +6033,14 @@ mod tests { command: Some(ServiceCommands::List { sandbox, - limit, - offset, + page_size, + page_token, .. }), }) => { assert_eq!(sandbox.as_deref(), Some("my-sandbox")); - assert_eq!(limit, 10); - assert_eq!(offset, 2); + assert_eq!(page_size, 10); + assert_eq!(page_token, "next-service-page"); } other => panic!("expected service list command, got: {other:?}"), } @@ -6046,14 +6053,14 @@ mod tests { command: Some(ServiceCommands::List { sandbox, - limit, - offset, + page_size, + page_token, .. }), }) => { assert_eq!(sandbox, None); - assert_eq!(limit, 100); - assert_eq!(offset, 0); + assert_eq!(page_size, 100); + assert!(page_token.is_empty()); } other => panic!("expected service list command, got: {other:?}"), } diff --git a/crates/openshell-cli/src/output.rs b/crates/openshell-cli/src/output.rs index 55c548787e..fee304870a 100644 --- a/crates/openshell-cli/src/output.rs +++ b/crates/openshell-cli/src/output.rs @@ -34,6 +34,74 @@ use miette::{IntoDiagnostic, Result}; use std::io::Write; +/// Report a continuation token for table output. +pub fn print_next_page_token(next_page_token: &str) { + if !next_page_token.is_empty() { + eprintln!("Next page token: {next_page_token}"); + } +} + +fn paginated_collection_value( + collection_name: &str, + items: &[T], + next_page_token: &str, + to_json: F, +) -> serde_json::Value +where + F: Fn(&T) -> serde_json::Value, +{ + let mut envelope = serde_json::Map::new(); + envelope.insert( + collection_name.to_string(), + serde_json::Value::Array(items.iter().map(to_json).collect()), + ); + envelope.insert( + "next_page_token".to_string(), + serde_json::Value::String(next_page_token.to_string()), + ); + serde_json::Value::Object(envelope) +} + +/// Print a single page as a structured response envelope. +/// +/// JSON and YAML output include both the named collection and +/// `next_page_token`, so callers can continue without scraping stderr. Table +/// output is not handled; callers should render the table and may report the +/// token with [`print_next_page_token`]. +pub fn print_paginated_output_collection( + format: impl AsRef, + collection_name: &str, + items: &[T], + next_page_token: &str, + to_json: F, +) -> Result +where + F: Fn(&T) -> serde_json::Value, +{ + match format.as_ref() { + "json" => { + let envelope = + paginated_collection_value(collection_name, items, next_page_token, to_json); + println!( + "{}", + serde_json::to_string_pretty(&envelope).into_diagnostic()? + ); + Ok(true) + } + "yaml" => { + let envelope = + paginated_collection_value(collection_name, items, next_page_token, to_json); + print!("{}", serde_yml::to_string(&envelope).into_diagnostic()?); + Ok(true) + } + "table" => Ok(false), + _ => Err(miette::miette!( + "unsupported output format: {}", + format.as_ref() + )), + } +} + /// Print collection output in specified format (json/yaml/table). /// /// # Returns @@ -210,6 +278,50 @@ where } } +/// Writer variant of [`print_paginated_output_collection`]. +pub fn print_paginated_output_collection_to_writer( + format: impl AsRef, + writer: &mut W, + collection_name: &str, + items: &[T], + next_page_token: &str, + to_json: F, +) -> Result +where + W: Write, + F: Fn(&T) -> serde_json::Value, +{ + match format.as_ref() { + "json" => { + let envelope = + paginated_collection_value(collection_name, items, next_page_token, to_json); + writeln!( + writer, + "{}", + serde_json::to_string_pretty(&envelope).into_diagnostic()? + ) + .into_diagnostic()?; + Ok(true) + } + "yaml" => { + let envelope = + paginated_collection_value(collection_name, items, next_page_token, to_json); + write!( + writer, + "{}", + serde_yml::to_string(&envelope).into_diagnostic()? + ) + .into_diagnostic()?; + Ok(true) + } + "table" => Ok(false), + _ => Err(miette::miette!( + "unsupported output format: {}", + format.as_ref() + )), + } +} + /// Print single item output to a custom writer in specified format (json/yaml/table). /// /// Writer variant for commands that need custom output destinations. @@ -472,6 +584,73 @@ mod tests { assert!(output.contains("name: test")); } + #[test] + fn test_print_paginated_output_collection_to_writer_json() { + let items = vec![TestItem { + id: 1, + name: "test".to_string(), + }]; + let mut buffer = Vec::new(); + + let handled = print_paginated_output_collection_to_writer( + "json", + &mut buffer, + "items", + &items, + "next-token", + test_item_to_json, + ) + .unwrap(); + + assert!(handled); + let output: serde_json::Value = serde_json::from_slice(&buffer).unwrap(); + assert_eq!(output["items"][0]["id"], 1); + assert_eq!(output["next_page_token"], "next-token"); + } + + #[test] + fn test_print_paginated_output_collection_to_writer_yaml() { + let items = vec![TestItem { + id: 1, + name: "test".to_string(), + }]; + let mut buffer = Vec::new(); + + let handled = print_paginated_output_collection_to_writer( + "yaml", + &mut buffer, + "items", + &items, + "", + test_item_to_json, + ) + .unwrap(); + + assert!(handled); + let output: serde_json::Value = serde_yml::from_slice(&buffer).unwrap(); + assert_eq!(output["items"][0]["name"], "test"); + assert_eq!(output["next_page_token"], ""); + } + + #[test] + fn test_print_paginated_output_collection_table_is_not_handled() { + let items = Vec::::new(); + let mut buffer = Vec::new(); + + let handled = print_paginated_output_collection_to_writer( + "table", + &mut buffer, + "items", + &items, + "next-token", + test_item_to_json, + ) + .unwrap(); + + assert!(!handled); + assert!(buffer.is_empty()); + } + #[test] fn test_print_output_single_to_writer_json() { let item = TestItem { diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 3421f0f871..a89e3c30b3 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -2232,8 +2232,8 @@ async fn sandbox_exec_interactive_grpc( #[allow(clippy::too_many_arguments)] pub async fn sandbox_list( server: &str, - limit: u32, - offset: u32, + page_size: i32, + page_token: &str, ids_only: bool, names_only: bool, label_selector: Option<&str>, @@ -2246,8 +2246,8 @@ pub async fn sandbox_list( let response = client .list_sandboxes(ListSandboxesRequest { - limit, - offset, + page_size, + page_token: page_token.to_string(), label_selector: label_selector.unwrap_or("").to_string(), workspace_scope: Some(if all_workspaces { openshell_core::proto::all_workspaces_selector() @@ -2258,11 +2258,20 @@ pub async fn sandbox_list( .await .into_diagnostic()?; - let sandboxes = response.into_inner().sandboxes; + let response = response.into_inner(); + let next_page_token = response.next_page_token; + let sandboxes = response.sandboxes; - if crate::output::print_output_collection(output, &sandboxes, sandbox_to_json)? { + if crate::output::print_paginated_output_collection( + output, + "sandboxes", + &sandboxes, + &next_page_token, + sandbox_to_json, + )? { return Ok(()); } + crate::output::print_next_page_token(&next_page_token); if sandboxes.is_empty() { if !ids_only && !names_only { @@ -2587,8 +2596,8 @@ pub async fn sandbox_template_get( #[allow(clippy::too_many_arguments)] pub async fn sandbox_template_list( server: &str, - limit: u32, - offset: u32, + page_size: i32, + page_token: &str, label_selector: Option<&str>, names_only: bool, output: &str, @@ -2599,8 +2608,8 @@ pub async fn sandbox_template_list( let mut client = grpc_client(server, tls).await?; let response = client .list_sandbox_templates(ListSandboxTemplatesRequest { - limit, - offset, + page_size, + page_token: page_token.to_string(), workspace_scope: Some(if all_workspaces { openshell_core::proto::all_workspaces_selector() } else { @@ -2610,11 +2619,20 @@ pub async fn sandbox_template_list( }) .await .into_diagnostic()?; - let templates = response.into_inner().templates; + let response = response.into_inner(); + let next_page_token = response.next_page_token; + let templates = response.templates; - if crate::output::print_output_collection(output, &templates, sandbox_template_to_json)? { + if crate::output::print_paginated_output_collection( + output, + "templates", + &templates, + &next_page_token, + sandbox_template_to_json, + )? { return Ok(()); } + crate::output::print_next_page_token(&next_page_token); if templates.is_empty() { if !names_only { @@ -3028,17 +3046,25 @@ pub async fn sandbox_delete( let mut client = grpc_client(server, tls).await?; let names_to_delete: Vec = if all { - // Fetch all sandboxes (use a large page size). - let response = client - .list_sandboxes(ListSandboxesRequest { - limit: 1000, - offset: 0, - label_selector: String::new(), - workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), - }) - .await - .into_diagnostic()?; - let sandboxes = response.into_inner().sandboxes; + let mut page_token = String::new(); + let mut sandboxes = Vec::new(); + loop { + let response = client + .list_sandboxes(ListSandboxesRequest { + page_size: 1000, + page_token, + label_selector: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), + }) + .await + .into_diagnostic()? + .into_inner(); + sandboxes.extend(response.sandboxes); + if response.next_page_token.is_empty() { + break; + } + page_token = response.next_page_token; + } if sandboxes.is_empty() { println!("No sandboxes to delete."); return Ok(()); @@ -3279,8 +3305,8 @@ fn service_expose_status_error(status: Status) -> miette::Report { pub async fn service_list( server: &str, sandbox: Option<&str>, - limit: u32, - offset: u32, + page_size: i32, + page_token: &str, workspace: &str, all_workspaces: bool, output: &str, @@ -3290,8 +3316,8 @@ pub async fn service_list( let response = client .list_services(ListServicesRequest { sandbox: sandbox.unwrap_or_default().to_string(), - limit, - offset, + page_size, + page_token: page_token.to_string(), workspace_scope: Some(if all_workspaces { openshell_core::proto::all_workspaces_selector() } else { @@ -3302,14 +3328,22 @@ pub async fn service_list( .map_err(|status| service_status_error("list services", "sandbox:read", status))? .into_inner(); + let next_page_token = response.next_page_token.clone(); let services = response .services .iter() .filter_map(|response| service_endpoint_to_json(response, server)) .collect::>(); - if crate::output::print_output_collection(output, &services, Clone::clone)? { + if crate::output::print_paginated_output_collection( + output, + "services", + &services, + &next_page_token, + Clone::clone, + )? { return Ok(()); } + crate::output::print_next_page_token(&next_page_token); if response.services.is_empty() { if let Some(sandbox) = sandbox { @@ -3646,8 +3680,8 @@ pub async fn workspace_get(server: &str, name: &str, tls: &TlsOptions) -> Result pub async fn workspace_list( server: &str, - limit: u32, - offset: u32, + page_size: i32, + page_token: &str, label_selector: &str, output: &str, tls: &TlsOptions, @@ -3657,17 +3691,26 @@ pub async fn workspace_list( let mut client = grpc_client(server, tls).await?; let response = client .list_workspaces(ListWorkspacesRequest { - limit, - offset, + page_size, + page_token: page_token.to_string(), label_selector: label_selector.to_string(), }) .await .into_diagnostic()?; - let workspaces = response.into_inner().workspaces; + let response = response.into_inner(); + let next_page_token = response.next_page_token; + let workspaces = response.workspaces; - if crate::output::print_output_collection(output, &workspaces, workspace_to_json)? { + if crate::output::print_paginated_output_collection( + output, + "workspaces", + &workspaces, + &next_page_token, + workspace_to_json, + )? { return Ok(()); } + crate::output::print_next_page_token(&next_page_token); if workspaces.is_empty() { println!("No workspaces found."); @@ -3817,8 +3860,8 @@ pub async fn workspace_member_remove( pub async fn workspace_member_list( server: &str, workspace: &str, - limit: u32, - offset: u32, + page_size: i32, + page_token: &str, output: &str, tls: &TlsOptions, ) -> Result<()> { @@ -3828,16 +3871,25 @@ pub async fn workspace_member_list( let response = client .list_workspace_members(ListWorkspaceMembersRequest { workspace: workspace.to_string(), - limit, - offset, + page_size, + page_token: page_token.to_string(), }) .await .into_diagnostic()?; - let members = response.into_inner().members; + let response = response.into_inner(); + let next_page_token = response.next_page_token; + let members = response.members; - if crate::output::print_output_collection(output, &members, workspace_member_to_json)? { + if crate::output::print_paginated_output_collection( + output, + "members", + &members, + &next_page_token, + workspace_member_to_json, + )? { return Ok(()); } + crate::output::print_next_page_token(&next_page_token); if members.is_empty() { println!("No members found in workspace {workspace}."); @@ -5163,7 +5215,8 @@ fn policy_for_view(policy: &SandboxPolicy, view: PolicyGetView) -> Cow<'_, Sandb pub async fn sandbox_policy_list( server: &str, name: &str, - limit: u32, + page_size: i32, + page_token: &str, output: &str, workspace: &str, tls: &TlsOptions, @@ -5173,19 +5226,28 @@ pub async fn sandbox_policy_list( let resp = client .list_sandbox_policies(ListSandboxPoliciesRequest { name: name.to_string(), - limit, - offset: 0, + page_size, + page_token: page_token.to_string(), global: false, workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await .into_diagnostic()?; - let revisions = resp.into_inner().revisions; + let resp = resp.into_inner(); + let next_page_token = resp.next_page_token; + let revisions = resp.revisions; let structured = policy_revision_list_json("sandbox", Some(name), &revisions)?; - if crate::output::print_output_collection(output, &structured, Clone::clone)? { + if crate::output::print_paginated_output_collection( + output, + "revisions", + &structured, + &next_page_token, + Clone::clone, + )? { return Ok(()); } + crate::output::print_next_page_token(&next_page_token); if revisions.is_empty() { eprintln!("No policy history found for sandbox '{name}'"); @@ -5198,7 +5260,8 @@ pub async fn sandbox_policy_list( pub async fn sandbox_policy_list_global( server: &str, - limit: u32, + page_size: i32, + page_token: &str, output: &str, _workspace: &str, tls: &TlsOptions, @@ -5208,19 +5271,28 @@ pub async fn sandbox_policy_list_global( let resp = client .list_sandbox_policies(ListSandboxPoliciesRequest { name: String::new(), - limit, - offset: 0, + page_size, + page_token: page_token.to_string(), global: true, workspace_scope: None, }) .await .into_diagnostic()?; - let revisions = resp.into_inner().revisions; + let resp = resp.into_inner(); + let next_page_token = resp.next_page_token; + let revisions = resp.revisions; let structured = policy_revision_list_json("global", None, &revisions)?; - if crate::output::print_output_collection(output, &structured, Clone::clone)? { + if crate::output::print_paginated_output_collection( + output, + "revisions", + &structured, + &next_page_token, + Clone::clone, + )? { return Ok(()); } + crate::output::print_next_page_token(&next_page_token); if revisions.is_empty() { eprintln!("No global policy history found"); diff --git a/crates/openshell-cli/tests/ensure_providers_integration.rs b/crates/openshell-cli/tests/ensure_providers_integration.rs index 7545786a12..7b17ee7a35 100644 --- a/crates/openshell-cli/tests/ensure_providers_integration.rs +++ b/crates/openshell-cli/tests/ensure_providers_integration.rs @@ -314,7 +314,10 @@ impl OpenShell for TestOpenShell { .values() .cloned() .collect::>(); - Ok(Response::new(ListProvidersResponse { providers })) + Ok(Response::new(ListProvidersResponse { + providers, + next_page_token: String::new(), + })) } async fn list_provider_profiles( @@ -326,7 +329,10 @@ impl OpenShell for TestOpenShell { .map(openshell_providers::ProviderTypeProfile::to_proto) .collect(); Ok(Response::new( - openshell_core::proto::ListProviderProfilesResponse { profiles }, + openshell_core::proto::ListProviderProfilesResponse { + profiles, + next_page_token: String::new(), + }, )) } diff --git a/crates/openshell-cli/tests/provider_commands_integration.rs b/crates/openshell-cli/tests/provider_commands_integration.rs index 912835faa3..5b8ae54333 100644 --- a/crates/openshell-cli/tests/provider_commands_integration.rs +++ b/crates/openshell-cli/tests/provider_commands_integration.rs @@ -480,7 +480,10 @@ impl OpenShell for TestOpenShell { .values() .cloned() .collect::>(); - Ok(Response::new(ListProvidersResponse { providers })) + Ok(Response::new(ListProvidersResponse { + providers, + next_page_token: String::new(), + })) } async fn list_provider_profiles( @@ -493,7 +496,10 @@ impl OpenShell for TestOpenShell { .collect::>(); profiles.extend(self.state.profiles.lock().await.values().cloned()); Ok(Response::new( - openshell_core::proto::ListProviderProfilesResponse { profiles }, + openshell_core::proto::ListProviderProfilesResponse { + profiles, + next_page_token: String::new(), + }, )) } @@ -1357,7 +1363,7 @@ async fn provider_cli_run_functions_support_full_crud_flow() { run::provider_list( &ts.endpoint, 100, - 0, + "", false, "table", "default", @@ -1428,7 +1434,7 @@ async fn provider_list_json_output() { run::provider_list( &ts.endpoint, 100, - 0, + "", false, "json", "default", @@ -1471,7 +1477,7 @@ async fn provider_list_yaml_output() { run::provider_list( &ts.endpoint, 100, - 0, + "", false, "yaml", "default", @@ -1499,7 +1505,7 @@ async fn provider_list_json_empty() { run::provider_list( &ts.endpoint, 100, - 0, + "", false, "json", "default", diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index 6ed9a74339..5c24fc6695 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -285,6 +285,7 @@ impl OpenShell for TestOpenShell { .push(request.into_inner()); Ok(Response::new(ListSandboxTemplatesResponse { templates: Vec::new(), + next_page_token: String::new(), })) } @@ -461,6 +462,7 @@ impl OpenShell for TestOpenShell { ) -> Result, Status> { Ok(Response::new(ListProvidersResponse { providers: self.state.providers.lock().await.clone(), + next_page_token: String::new(), })) } @@ -473,7 +475,10 @@ impl OpenShell for TestOpenShell { .map(openshell_providers::ProviderTypeProfile::to_proto) .collect(); Ok(Response::new( - openshell_core::proto::ListProviderProfilesResponse { profiles }, + openshell_core::proto::ListProviderProfilesResponse { + profiles, + next_page_token: String::new(), + }, )) } @@ -1874,7 +1879,7 @@ async fn sandbox_template_list_and_delete_send_workspace_requests() { run::sandbox_template_list( &server.endpoint, 25, - 5, + "next-template-page", Some("team=runtime"), false, "table", @@ -1892,8 +1897,8 @@ async fn sandbox_template_list_and_delete_send_workspace_requests() { let list_request = list_requests .first() .expect("template list request should be recorded"); - assert_eq!(list_request.limit, 25); - assert_eq!(list_request.offset, 5); + assert_eq!(list_request.page_size, 25); + assert_eq!(list_request.page_token, "next-template-page"); assert_eq!(list_request.label_selector, "team=runtime"); assert_eq!( selected_workspace(&list_request.workspace_scope), diff --git a/crates/openshell-conformance/src/scenarios/smoke.rs b/crates/openshell-conformance/src/scenarios/smoke.rs index 7c5fa0068c..59f2d2b38f 100644 --- a/crates/openshell-conformance/src/scenarios/smoke.rs +++ b/crates/openshell-conformance/src/scenarios/smoke.rs @@ -22,6 +22,12 @@ struct SandboxListEntry { phase: String, } +#[derive(Debug, Deserialize)] +struct SandboxListPage { + sandboxes: Vec, + next_page_token: String, +} + /// Certify status -> create -> list Ready -> exec -> delete -> list empty. pub const SMOKE_SCENARIO: Scenario = Scenario { name: "smoke", @@ -162,22 +168,22 @@ async fn find_sandbox( sandbox_name: &str, step: &str, ) -> Result, String> { - let mut offset = 0u32; + let mut page_token = String::new(); + let mut page = 0u32; loop { - let limit = LIST_PAGE_SIZE.to_string(); - let page_offset = offset.to_string(); + let page_size = LIST_PAGE_SIZE.to_string(); let result = runner - .step(format!("{step}/{offset}")) - .description(format!("sandbox list page at offset {offset} succeeds")) + .step(format!("{step}/{page}")) + .description(format!("sandbox list page {page} succeeds")) .with_timeout(LIST_ATTEMPT_TIMEOUT) .run(&[ "sandbox", "list", - "--limit", - &limit, - "--offset", - &page_offset, + "--page-size", + &page_size, + "--page-token", + &page_token, "--output", "json", ]) @@ -185,10 +191,11 @@ async fn find_sandbox( .map_err(|error| error.to_string())?; result.require_success()?; - let sandboxes = result - .json::>() + let response = result + .json::() .map_err(|error| error.to_string())?; - if let Some(sandbox) = sandboxes + if let Some(sandbox) = response + .sandboxes .iter() .find(|sandbox| sandbox.name == sandbox_name) { @@ -197,12 +204,13 @@ async fn find_sandbox( phase: sandbox.phase.clone(), })); } - if sandboxes.len() < LIST_PAGE_SIZE as usize { + if response.next_page_token.is_empty() { return Ok(None); } - offset = offset - .checked_add(LIST_PAGE_SIZE) - .ok_or_else(|| "sandbox list pagination offset overflowed".to_string())?; + page_token = response.next_page_token; + page = page + .checked_add(1) + .ok_or_else(|| "sandbox list page counter overflowed".to_string())?; } } diff --git a/crates/openshell-core/src/proto/mod.rs b/crates/openshell-core/src/proto/mod.rs index d0b976ff24..43d2bce267 100644 --- a/crates/openshell-core/src/proto/mod.rs +++ b/crates/openshell-core/src/proto/mod.rs @@ -63,6 +63,11 @@ pub mod middleware { pub use super::generated::openshell::middleware::v1; } +#[doc(hidden)] +pub mod pagination { + pub use super::generated::openshell::internal::pagination::v1; +} + pub mod gateway_interceptor { pub use super::generated::openshell::gateway_interceptor::v1; } diff --git a/crates/openshell-sdk/README.md b/crates/openshell-sdk/README.md index dc57d5ec11..4ff8aca91c 100644 --- a/crates/openshell-sdk/README.md +++ b/crates/openshell-sdk/README.md @@ -59,6 +59,12 @@ Curated calls without a workspace argument explicitly select the `default` workspace. Cross-workspace listing uses the separate `*_all_workspaces` methods and requires Platform Admin access. +Curated list methods follow continuation tokens until the collection is +exhausted. `ListOptions::page_size` and +`SandboxTemplateListOptions::page_size` control the size of each gateway +request; callers that need explicit page boundaries can use the raw protobuf +client. + ```rust use openshell_sdk::{ ClientConfig, OpenShellClient, SandboxTemplateCreateSpec, diff --git a/crates/openshell-sdk/src/client.rs b/crates/openshell-sdk/src/client.rs index 4713f0ed1c..d8f1b26205 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -196,18 +196,27 @@ impl OpenShellClient { &self, opts: SandboxTemplateListOptions, ) -> Result> { - let response = self - .unary(|mut grpc| { - let request = proto::ListSandboxTemplatesRequest { - limit: opts.limit, - offset: opts.offset, - label_selector: opts.label_selector.clone(), - workspace_scope: Some(proto::workspace_selector("default")), - }; - async move { grpc.list_sandbox_templates(request).await } - }) - .await?; - Ok(response.templates) + let mut templates = Vec::new(); + let mut page_token = String::new(); + loop { + let response = self + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListSandboxTemplatesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone(), + workspace_scope: Some(proto::workspace_selector("default")), + }; + async move { grpc.list_sandbox_templates(request).await } + }) + .await?; + templates.extend(response.templates); + if response.next_page_token.is_empty() { + return Ok(templates); + } + page_token = response.next_page_token; + } } /// List reusable sandbox templates across all workspaces. @@ -215,18 +224,27 @@ impl OpenShellClient { &self, opts: SandboxTemplateListOptions, ) -> Result> { - let response = self - .unary(|mut grpc| { - let request = proto::ListSandboxTemplatesRequest { - limit: opts.limit, - offset: opts.offset, - label_selector: opts.label_selector.clone(), - workspace_scope: Some(proto::all_workspaces_selector()), - }; - async move { grpc.list_sandbox_templates(request).await } - }) - .await?; - Ok(response.templates) + let mut templates = Vec::new(); + let mut page_token = String::new(); + loop { + let response = self + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListSandboxTemplatesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone(), + workspace_scope: Some(proto::all_workspaces_selector()), + }; + async move { grpc.list_sandbox_templates(request).await } + }) + .await?; + templates.extend(response.templates); + if response.next_page_token.is_empty() { + return Ok(templates); + } + page_token = response.next_page_token; + } } /// Delete a reusable sandbox template by name from the default workspace. @@ -259,22 +277,27 @@ impl OpenShellClient { /// List sandboxes. pub async fn list_sandboxes(&self, opts: ListOptions) -> Result> { - let response = self - .unary(|mut grpc| { - let request = proto::ListSandboxesRequest { - limit: opts.limit, - offset: opts.offset, - label_selector: opts.label_selector.clone().unwrap_or_default(), - workspace_scope: Some(proto::workspace_selector("default")), - }; - async move { grpc.list_sandboxes(request).await } - }) - .await?; - Ok(response - .sandboxes - .into_iter() - .map(SandboxRef::from_proto) - .collect()) + let mut sandboxes = Vec::new(); + let mut page_token = String::new(); + loop { + let response = self + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListSandboxesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone().unwrap_or_default(), + workspace_scope: Some(proto::workspace_selector("default")), + }; + async move { grpc.list_sandboxes(request).await } + }) + .await?; + sandboxes.extend(response.sandboxes.into_iter().map(SandboxRef::from_proto)); + if response.next_page_token.is_empty() { + return Ok(sandboxes); + } + page_token = response.next_page_token; + } } /// Delete a sandbox by name. @@ -384,22 +407,27 @@ impl OpenShellClient { &self, opts: ListOptions, ) -> Result> { - let response = self - .unary(|mut grpc| { - let request = proto::ListSandboxesRequest { - limit: opts.limit, - offset: opts.offset, - label_selector: opts.label_selector.clone().unwrap_or_default(), - workspace_scope: Some(proto::all_workspaces_selector()), - }; - async move { grpc.list_sandboxes(request).await } - }) - .await?; - Ok(response - .sandboxes - .into_iter() - .map(SandboxRef::from_proto) - .collect()) + let mut sandboxes = Vec::new(); + let mut page_token = String::new(); + loop { + let response = self + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListSandboxesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone().unwrap_or_default(), + workspace_scope: Some(proto::all_workspaces_selector()), + }; + async move { grpc.list_sandboxes(request).await } + }) + .await?; + sandboxes.extend(response.sandboxes.into_iter().map(SandboxRef::from_proto)); + if response.next_page_token.is_empty() { + return Ok(sandboxes); + } + page_token = response.next_page_token; + } } /// Create a new workspace. @@ -441,21 +469,31 @@ impl OpenShellClient { /// List workspaces. pub async fn list_workspaces(&self, opts: ListOptions) -> Result> { - let response = self - .unary(|mut grpc| { - let request = proto::ListWorkspacesRequest { - limit: opts.limit, - offset: opts.offset, - label_selector: opts.label_selector.clone().unwrap_or_default(), - }; - async move { grpc.list_workspaces(request).await } - }) - .await?; - Ok(response - .workspaces - .into_iter() - .map(WorkspaceRef::from_proto) - .collect()) + let mut workspaces = Vec::new(); + let mut page_token = String::new(); + loop { + let response = self + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListWorkspacesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone().unwrap_or_default(), + }; + async move { grpc.list_workspaces(request).await } + }) + .await?; + workspaces.extend( + response + .workspaces + .into_iter() + .map(WorkspaceRef::from_proto), + ); + if response.next_page_token.is_empty() { + return Ok(workspaces); + } + page_token = response.next_page_token; + } } /// Delete a workspace by name. @@ -700,19 +738,28 @@ impl WorkspaceScopedClient { &self, opts: SandboxTemplateListOptions, ) -> Result> { - let response = self - .client - .unary(|mut grpc| { - let request = proto::ListSandboxTemplatesRequest { - limit: opts.limit, - offset: opts.offset, - label_selector: opts.label_selector.clone(), - workspace_scope: Some(proto::workspace_selector(&self.workspace)), - }; - async move { grpc.list_sandbox_templates(request).await } - }) - .await?; - Ok(response.templates) + let mut templates = Vec::new(); + let mut page_token = String::new(); + loop { + let response = self + .client + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListSandboxTemplatesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone(), + workspace_scope: Some(proto::workspace_selector(&self.workspace)), + }; + async move { grpc.list_sandbox_templates(request).await } + }) + .await?; + templates.extend(response.templates); + if response.next_page_token.is_empty() { + return Ok(templates); + } + page_token = response.next_page_token; + } } /// Delete a reusable sandbox template by name in this workspace. @@ -747,23 +794,28 @@ impl WorkspaceScopedClient { /// List sandboxes in this workspace. pub async fn list_sandboxes(&self, opts: ListOptions) -> Result> { - let response = self - .client - .unary(|mut grpc| { - let request = proto::ListSandboxesRequest { - limit: opts.limit, - offset: opts.offset, - label_selector: opts.label_selector.clone().unwrap_or_default(), - workspace_scope: Some(proto::workspace_selector(&self.workspace)), - }; - async move { grpc.list_sandboxes(request).await } - }) - .await?; - Ok(response - .sandboxes - .into_iter() - .map(SandboxRef::from_proto) - .collect()) + let mut sandboxes = Vec::new(); + let mut page_token = String::new(); + loop { + let response = self + .client + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListSandboxesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone().unwrap_or_default(), + workspace_scope: Some(proto::workspace_selector(&self.workspace)), + }; + async move { grpc.list_sandboxes(request).await } + }) + .await?; + sandboxes.extend(response.sandboxes.into_iter().map(SandboxRef::from_proto)); + if response.next_page_token.is_empty() { + return Ok(sandboxes); + } + page_token = response.next_page_token; + } } /// Delete a sandbox by name in this workspace. diff --git a/crates/openshell-sdk/src/types.rs b/crates/openshell-sdk/src/types.rs index 12b5a72cb9..1c3fa7014d 100644 --- a/crates/openshell-sdk/src/types.rs +++ b/crates/openshell-sdk/src/types.rs @@ -161,10 +161,8 @@ pub type SandboxStartup = proto::SandboxStartup; /// Options for listing reusable sandbox templates. #[derive(Clone, Debug, Default)] pub struct SandboxTemplateListOptions { - /// Maximum templates to return. `0` defers to the server default. - pub limit: u32, - /// Offset into the result list. - pub offset: u32, + /// Page size requested while collecting templates. `0` uses the server default. + pub page_size: i32, /// Optional label selector in `key=value,key2=value2` form. pub label_selector: String, } @@ -247,10 +245,8 @@ impl WorkspaceRef { /// Options for listing sandboxes. #[derive(Clone, Debug, Default)] pub struct ListOptions { - /// Maximum sandboxes to return. `0` defers to the server default. - pub limit: u32, - /// Offset into the result list. - pub offset: u32, + /// Page size requested while collecting results. `0` uses the server default. + pub page_size: i32, /// Optional Kubernetes-style label selector (e.g. `env=prod,team=core`). pub label_selector: Option, } diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 5fd2133b5c..7acce33e0e 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -55,12 +55,14 @@ struct MockState { last_stop: Mutex>, last_start: Mutex>, last_list_request: Mutex>, + list_requests: Mutex>, last_exec_request: Mutex>, last_workspace_request: Mutex>, get_calls: AtomicU32, phase_sequence: Vec, get_returns_not_found: bool, not_found_after: Option, + paginate_list: bool, /// When set, `health` rejects any request whose `authorization` header /// does not match this exact value (e.g. `"Bearer fresh-token"`). require_bearer: Option, @@ -278,6 +280,7 @@ impl OpenShell for TestOpenShell { workload_template_proto("python", "default"), workload_template_proto("cuda", "gpu"), ], + next_page_token: String::new(), })) } @@ -360,12 +363,36 @@ impl OpenShell for TestOpenShell { &self, request: tonic::Request, ) -> Result, Status> { - *self.state.last_list_request.lock().await = Some(request.into_inner()); + let request = request.into_inner(); + *self.state.last_list_request.lock().await = Some(request.clone()); + self.state.list_requests.lock().await.push(request.clone()); + if self.state.paginate_list { + let (sandboxes, next_page_token) = if request.page_token.is_empty() { + ( + vec![sandbox_with_phase("alpha", proto::SandboxPhase::Ready)], + "page-2".to_string(), + ) + } else { + assert_eq!(request.page_token, "page-2"); + ( + vec![sandbox_with_phase( + "beta", + proto::SandboxPhase::Provisioning, + )], + String::new(), + ) + }; + return Ok(Response::new(proto::ListSandboxesResponse { + sandboxes, + next_page_token, + })); + } Ok(Response::new(proto::ListSandboxesResponse { sandboxes: vec![ sandbox_with_phase("alpha", proto::SandboxPhase::Ready), sandbox_with_phase("beta", proto::SandboxPhase::Provisioning), ], + next_page_token: String::new(), })) } @@ -826,6 +853,7 @@ impl OpenShell for TestOpenShell { workspace_proto("default", proto::datamodel::v1::WorkspacePhase::Active), workspace_proto("staging", proto::datamodel::v1::WorkspacePhase::Active), ], + next_page_token: String::new(), })) } @@ -1004,16 +1032,15 @@ async fn sandbox_template_crud_uses_default_workspace() { let listed = client .list_sandbox_templates_all_workspaces(SandboxTemplateListOptions { - limit: 10, - offset: 2, + page_size: 10, label_selector: String::new(), }) .await .unwrap(); assert_eq!(listed.len(), 2); let observed_list = state.last_template_list.lock().await.clone().unwrap(); - assert_eq!(observed_list.limit, 10); - assert_eq!(observed_list.offset, 2); + assert_eq!(observed_list.page_size, 10); + assert!(observed_list.page_token.is_empty()); assert!(selects_all_workspaces(&observed_list.workspace_scope)); let deleted = client.delete_sandbox_template("python").await.unwrap(); @@ -1066,8 +1093,7 @@ async fn list_sandboxes_propagates_filters() { let client = connect(&endpoint).await; let opts = ListOptions { - limit: 25, - offset: 5, + page_size: 25, label_selector: Some("team=core".to_string()), }; let items = client.list_sandboxes(opts).await.unwrap(); @@ -1077,11 +1103,38 @@ async fn list_sandboxes_propagates_filters() { assert_eq!(items[1].phase, SandboxPhase::Provisioning); let observed = state.last_list_request.lock().await.clone().unwrap(); - assert_eq!(observed.limit, 25); - assert_eq!(observed.offset, 5); + assert_eq!(observed.page_size, 25); + assert!(observed.page_token.is_empty()); assert_eq!(observed.label_selector, "team=core"); } +#[tokio::test] +async fn list_sandboxes_follows_continuation_tokens() { + let state = Arc::new(MockState { + paginate_list: true, + ..Default::default() + }); + let endpoint = start_mock(state.clone()).await; + let client = connect(&endpoint).await; + + let items = client + .list_sandboxes(ListOptions { + page_size: 1, + label_selector: Some("team=core".to_string()), + }) + .await + .unwrap(); + + assert_eq!(items.len(), 2); + assert_eq!(items[0].name, "alpha"); + assert_eq!(items[1].name, "beta"); + let requests = state.list_requests.lock().await; + assert_eq!(requests.len(), 2); + assert!(requests[0].page_token.is_empty()); + assert_eq!(requests[1].page_token, "page-2"); + assert_eq!(requests[1].label_selector, "team=core"); +} + #[tokio::test] async fn delete_sandbox_returns_server_ack() { let state = Arc::new(MockState::default()); diff --git a/crates/openshell-server/migrations/postgres/008_add_pagination_indexes.sql b/crates/openshell-server/migrations/postgres/008_add_pagination_indexes.sql new file mode 100644 index 0000000000..b6c9934e78 --- /dev/null +++ b/crates/openshell-server/migrations/postgres/008_add_pagination_indexes.sql @@ -0,0 +1,6 @@ +-- Support workspace-scoped and platform-wide keyset pagination orderings. +CREATE INDEX IF NOT EXISTS objects_workspace_page_idx + ON objects (object_type, workspace, created_at_ms, COALESCE(name, ''), id); + +CREATE INDEX IF NOT EXISTS objects_all_workspaces_page_idx + ON objects (object_type, created_at_ms, COALESCE(name, ''), workspace, id); diff --git a/crates/openshell-server/migrations/sqlite/008_add_pagination_indexes.sql b/crates/openshell-server/migrations/sqlite/008_add_pagination_indexes.sql new file mode 100644 index 0000000000..b6c9934e78 --- /dev/null +++ b/crates/openshell-server/migrations/sqlite/008_add_pagination_indexes.sql @@ -0,0 +1,6 @@ +-- Support workspace-scoped and platform-wide keyset pagination orderings. +CREATE INDEX IF NOT EXISTS objects_workspace_page_idx + ON objects (object_type, workspace, created_at_ms, COALESCE(name, ''), id); + +CREATE INDEX IF NOT EXISTS objects_all_workspaces_page_idx + ON objects (object_type, created_at_ms, COALESCE(name, ''), workspace, id); diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 70356e1add..70ffb5fe5d 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -10,8 +10,8 @@ pub mod rootfs_tar; use crate::grpc::policy::SANDBOX_SETTINGS_OBJECT_TYPE; use crate::otel_tracing::TraceContextInterceptor; use crate::persistence::{ - DRAFT_CHUNK_OBJECT_TYPE, ObjectCursor, ObjectId, ObjectName, ObjectRecord, ObjectType, - POLICY_OBJECT_TYPE, Store, WriteCondition, + DRAFT_CHUNK_OBJECT_TYPE, ObjectCursor, ObjectId, ObjectListQuery, ObjectName, ObjectRecord, + ObjectType, POLICY_OBJECT_TYPE, Store, WriteCondition, }; use crate::sandbox_index::SandboxIndex; use crate::sandbox_watch::SandboxWatchBus; @@ -2491,25 +2491,11 @@ impl ComputeRuntime { } async fn list_persisted_sandbox_ids(&self, operation: &str) -> Result, String> { - let mut sandbox_ids = Vec::new(); - let mut offset = 0u32; - loop { - let records = self - .store - .list_by_type(Sandbox::object_type(), LIFECYCLE_SWEEP_PAGE_SIZE, offset) - .await - .map_err(|err| format!("failed to list sandboxes for {operation}: {err}"))?; - let page_len = u32::try_from(records.len()) - .map_err(|_| format!("sandbox page size overflow during {operation}"))?; - sandbox_ids.extend(records.into_iter().map(|record| record.id)); - if page_len < LIFECYCLE_SWEEP_PAGE_SIZE { - break; - } - offset = offset - .checked_add(page_len) - .ok_or_else(|| format!("sandbox pagination offset overflow during {operation}"))?; - } - Ok(sandbox_ids) + self.store + .collect_records(Sandbox::object_type(), ObjectListQuery::AllWorkspaces) + .await + .map(|records| records.into_iter().map(|record| record.id).collect()) + .map_err(|err| format!("failed to list sandboxes for {operation}: {err}")) } async fn mark_sandbox_error(&self, sandbox: &Sandbox, reason: &str, message: &str) { @@ -2791,7 +2777,7 @@ impl ComputeRuntime { let records = self .store - .list_by_type(Sandbox::object_type(), 500, 0) + .collect_records(Sandbox::object_type(), ObjectListQuery::AllWorkspaces) .await .map_err(|e| e.to_string()) .inspect_err(|_| crate::otel_tracing::mark_error(&tracing::Span::current()))?; @@ -3501,10 +3487,6 @@ impl ComputeRuntime { .await } - // TODO: introduce a per-sandbox cap on service endpoints and paginate - // this cleanup loop, or query by sandbox label instead of scanning the - // full workspace. Without a cap the flat 1,000-record page could miss - // endpoints in large workspaces. async fn cleanup_sandbox_service_endpoints( &self, sandbox_id: &str, @@ -3512,7 +3494,10 @@ impl ComputeRuntime { ) -> Result<(), String> { let records = self .store - .list(ServiceEndpoint::object_type(), workspace, 1000, 0) + .collect_records( + ServiceEndpoint::object_type(), + ObjectListQuery::Workspace(workspace), + ) .await .map_err(|e| format!("list service endpoints: {e}"))?; diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index c5a12a15b5..95bd6eaa3b 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -68,24 +68,6 @@ use tonic::{Request, Response, Status}; use crate::ServerState; -// --------------------------------------------------------------------------- -// Public re-exports -// --------------------------------------------------------------------------- - -/// Maximum number of records a single list RPC may return. -/// -/// Client-provided `limit` values are clamped to this ceiling to prevent -/// unbounded memory allocation from an excessively large page request. -pub const MAX_PAGE_SIZE: u32 = 1000; - -/// Clamp a client-provided page `limit`. -/// -/// Returns `default` when `raw` is 0 (the protobuf zero-value convention), -/// otherwise returns the smaller of `raw` and `max`. -pub fn clamp_limit(raw: u32, default: u32, max: u32) -> u32 { - if raw == 0 { default } else { raw.min(max) } -} - /// Map a `PersistenceError` to an appropriate gRPC `Status`. /// /// CAS conflicts (optimistic concurrency failures) are mapped to `ABORTED` @@ -932,31 +914,6 @@ mod tests { ResourceCapabilities as DriverResourceCapabilities, }; - #[test] - fn clamp_limit_zero_returns_default() { - assert_eq!(clamp_limit(0, 100, MAX_PAGE_SIZE), 100); - assert_eq!(clamp_limit(0, 50, MAX_PAGE_SIZE), 50); - } - - #[test] - fn clamp_limit_within_range_passes_through() { - assert_eq!(clamp_limit(1, 100, MAX_PAGE_SIZE), 1); - assert_eq!(clamp_limit(500, 100, MAX_PAGE_SIZE), 500); - assert_eq!( - clamp_limit(MAX_PAGE_SIZE, 100, MAX_PAGE_SIZE), - MAX_PAGE_SIZE - ); - } - - #[test] - fn clamp_limit_exceeding_max_is_capped() { - assert_eq!( - clamp_limit(MAX_PAGE_SIZE + 1, 100, MAX_PAGE_SIZE), - MAX_PAGE_SIZE - ); - assert_eq!(clamp_limit(u32::MAX, 100, MAX_PAGE_SIZE), MAX_PAGE_SIZE); - } - #[test] fn public_resource_capabilities_preserves_reported_fields() { let driver_capabilities = DriverResourceCapabilities { diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 62bc0f8575..814ee1b567 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -16,8 +16,10 @@ use crate::auth::workspace_authz::{ MinWorkspaceRole, authorize_sandbox_workspace, authorize_workspace_selector, require_platform_admin, selected_workspace_name, }; +use crate::pagination::Pagination; use crate::persistence::{ - DraftChunkRecord, ObjectId, ObjectName, ObjectType, ObjectWorkspace, PolicyRecord, Store, + DraftChunkRecord, ObjectId, ObjectListQuery, ObjectName, ObjectType, ObjectWorkspace, + PolicyRecord, Store, }; use crate::policy_store::{AtomicPolicyRevisionWrite, PolicyStoreExt}; use crate::provider_profile_sources::EffectiveProviderProfileCatalog; @@ -88,7 +90,7 @@ use super::validation::{ validate_no_reserved_provider_policy_keys, validate_policy_safety, validate_static_fields_unchanged, }; -use super::{MAX_PAGE_SIZE, StoredSettingValue, StoredSettings, clamp_limit}; +use super::{StoredSettingValue, StoredSettings}; use crate::persistence::current_time_ms; // --------------------------------------------------------------------------- @@ -100,6 +102,7 @@ const GLOBAL_SETTINGS_OBJECT_TYPE: &str = "gateway_settings"; const GLOBAL_SETTINGS_NAME: &str = "global"; /// Internal object type for durable sandbox-scoped settings. pub const SANDBOX_SETTINGS_OBJECT_TYPE: &str = "sandbox_settings"; +const PROVIDER_COMPOSITION_VALIDATION_PAGE_SIZE: u32 = 1000; /// Reserved settings key used to store global policy payload. const POLICY_SETTING_KEY: &str = "policy"; /// Sentinel `sandbox_id` used to store global policy revisions. @@ -2094,18 +2097,20 @@ fn provider_policy_composition_enabled_in(settings: &StoredSettings) -> Result Result<(), Status> { - let mut offset = 0; let mut catalogs = HashMap::::new(); - + let mut cursor = None; loop { - let sandboxes = state + let page = state .store - .list_all_messages::(MAX_PAGE_SIZE, offset) + .list_message_page::( + ObjectListQuery::AllWorkspaces, + cursor.as_ref(), + PROVIDER_COMPOSITION_VALIDATION_PAGE_SIZE, + ) .await .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))?; - let page_len = sandboxes.len(); - for sandbox in sandboxes { + for sandbox in page.messages { let provider_names = sandbox .spec .as_ref() @@ -2146,13 +2151,11 @@ async fn validate_provider_composition_for_existing_sandboxes( })?; } - if page_len < MAX_PAGE_SIZE as usize { - break; - } - offset = offset.saturating_add(MAX_PAGE_SIZE); + let Some(next_cursor) = page.next_cursor else { + return Ok(()); + }; + cursor = Some(next_cursor); } - - Ok(()) } pub async fn validate_provider_composition_startup_preflight( @@ -4038,19 +4041,44 @@ pub(super) async fn handle_list_sandbox_policies( sandbox.object_id().to_string() }; - let limit = clamp_limit(req.limit, 50, MAX_PAGE_SIZE); - let records = state + let pagination = Pagination::new( + req.page_size, + &req.page_token, + "ListSandboxPolicies", + &[ + &req.name, + if req.global { "true" } else { "false" }, + &workspace, + ], + )?; + let mut records = state .store - .list_policies(&policy_id, limit, req.offset) + .list_policies_before( + &policy_id, + pagination.page_size() + 1, + pagination.policy_cursor()?, + ) .await .map_err(|e| Status::internal(format!("list policies failed: {e}")))?; + let page_size = usize::try_from(pagination.page_size()) + .map_err(|_| Status::internal("page size does not fit usize"))?; + let has_more = records.len() > page_size; + records.truncate(page_size); + let next_page_token = pagination.next_policy_token( + has_more + .then(|| records.last().map(|record| record.version)) + .flatten(), + ); let revisions = records .iter() .map(|r| policy_record_to_revision(r, false)) .collect::, Status>>()?; - Ok(Response::new(ListSandboxPoliciesResponse { revisions })) + Ok(Response::new(ListSandboxPoliciesResponse { + revisions, + next_page_token, + })) } pub(super) async fn handle_report_policy_status( @@ -7261,6 +7289,101 @@ mod tests { .expect("test global policy must be present") } + #[tokio::test] + async fn list_sandbox_policies_traverses_multiple_pages_exactly_once() { + let state = test_server_state().await; + let policy = ProtoSandboxPolicy::default(); + let payload = policy.encode_to_vec(); + for version in 1..=7 { + state + .store + .put_policy_revision( + &format!("global-policy-{version}"), + GLOBAL_POLICY_SANDBOX_ID, + "", + version, + &payload, + &format!("hash-{version}"), + ) + .await + .expect("store policy revision"); + } + + let mut versions = Vec::new(); + let mut page_token = String::new(); + let mut page_size = 2; + loop { + let page = handle_list_sandbox_policies( + &state, + authed_request(ListSandboxPoliciesRequest { + page_size, + page_token, + global: true, + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + versions.extend(page.revisions.into_iter().map(|revision| revision.version)); + if page.next_page_token.is_empty() { + break; + } + page_token = page.next_page_token; + page_size = 3; + } + + assert_eq!(versions, vec![7, 6, 5, 4, 3, 2, 1]); + } + + #[tokio::test] + async fn list_sandbox_policies_rejects_token_from_different_filter() { + let state = test_server_state().await; + let policy = ProtoSandboxPolicy::default(); + let payload = policy.encode_to_vec(); + for version in 1..=2 { + state + .store + .put_policy_revision( + &format!("global-policy-{version}"), + GLOBAL_POLICY_SANDBOX_ID, + "", + version, + &payload, + &format!("hash-{version}"), + ) + .await + .expect("store policy revision"); + } + let first = handle_list_sandbox_policies( + &state, + authed_request(ListSandboxPoliciesRequest { + page_size: 1, + global: true, + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + assert!(!first.next_page_token.is_empty()); + + let error = handle_list_sandbox_policies( + &state, + authed_request(ListSandboxPoliciesRequest { + page_size: 1, + page_token: first.next_page_token, + global: true, + name: "different".to_string(), + ..Default::default() + }), + ) + .await + .unwrap_err(); + + assert_eq!(error.code(), Code::InvalidArgument); + } + #[tokio::test] async fn get_sandbox_config_rejects_invalid_spec_policy_before_history_backfill() { let state = test_server_state().await; @@ -7587,7 +7710,7 @@ mod tests { &state, with_user(Request::new(ListSandboxPoliciesRequest { name: "stored-invalid-history".to_string(), - limit: 10, + page_size: 10, workspace_scope: Some(openshell_core::proto::workspace_selector("default")), ..Default::default() })), @@ -13568,8 +13691,8 @@ mod tests { &state, authed_request(ListSandboxPoliciesRequest { name: sandbox_name.clone(), - limit: 10, - offset: 0, + page_size: 10, + page_token: String::new(), global: false, workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -13633,8 +13756,8 @@ mod tests { &state, authed_request(ListSandboxPoliciesRequest { name: sandbox_name.clone(), - limit: 10, - offset: 0, + page_size: 10, + page_token: String::new(), global: false, workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index 46eb9ce9be..0500b668e8 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -7,12 +7,14 @@ #[cfg(test)] use crate::credentials::RefreshMaterialScope; +use crate::pagination::Pagination; use crate::persistence::{ - ObjectId, ObjectLabels, ObjectName, ObjectType, Store, WriteCondition, generate_name, + ObjectId, ObjectLabels, ObjectListQuery, ObjectName, ObjectType, Store, WriteCondition, + generate_name, }; use crate::provider_profile_sources::{ - EffectiveProviderProfileCatalog, ProviderProfileSources, profile_response_payload, - profile_storage_payload, stored_profile_resource_version, + EffectiveProviderProfileCatalog, ProfileScope, ProviderProfileSources, + profile_response_payload, profile_storage_payload, stored_profile_resource_version, }; use crate::storage_proto::{StoredProviderCredentialRefreshState, StoredProviderProfile}; use openshell_core::metadata::ObjectWorkspace; @@ -33,9 +35,7 @@ use tonic::Status; use tracing::warn; use super::validation::{validate_provider_fields, validate_provider_mutable_fields}; -use super::{ - MAX_MAP_KEY_LEN, MAX_MAP_VALUE_LEN, MAX_PAGE_SIZE, MAX_PROVIDER_CONFIG_ENTRIES, clamp_limit, -}; +use super::{MAX_MAP_KEY_LEN, MAX_MAP_VALUE_LEN, MAX_PROVIDER_CONFIG_ENTRIES}; const GATEWAY_SPIFFE_WORKLOAD_API_SOCKET: &str = "OPENSHELL_GATEWAY_SPIFFE_WORKLOAD_API_SOCKET"; @@ -277,6 +277,7 @@ pub(super) async fn get_provider_record( .map(redact_provider_credentials) } +#[cfg(test)] pub(super) async fn list_provider_records( store: &Store, workspace: &str, @@ -627,32 +628,15 @@ async fn scan_sandboxes_inner( where F: FnMut(Sandbox) -> Option, { - let mut out = Vec::new(); - let mut offset = 0u32; - loop { - let records = if let Some(ws) = workspace { - store.list(Sandbox::object_type(), ws, 1000, offset).await - } else { - store - .list_by_type(Sandbox::object_type(), 1000, offset) - .await - } + let query = workspace.map_or(ObjectListQuery::AllWorkspaces, ObjectListQuery::Workspace); + let sandboxes: Vec = store + .collect_messages(query) + .await .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))?; - if records.is_empty() { - break; - } - offset = offset - .checked_add( - u32::try_from(records.len()) - .map_err(|_| Status::internal("sandbox page size exceeded u32"))?, - ) - .ok_or_else(|| Status::internal("sandbox pagination offset overflow"))?; - for record in records { - let sandbox = Sandbox::decode(record.payload.as_slice()) - .map_err(|e| Status::internal(format!("decode sandbox failed: {e}")))?; - if let Some(item) = f(sandbox) { - out.push(item); - } + let mut out = Vec::new(); + for sandbox in sandboxes { + if let Some(item) = f(sandbox) { + out.push(item); } } Ok(out) @@ -664,43 +648,28 @@ async fn providers_using_profile( profile_id: &str, ) -> Result, Status> { let is_platform_scope = workspace.is_empty(); - let mut offset = 0u32; let mut blocking = Vec::new(); - loop { - let records = if is_platform_scope { - store - .list_by_type(Provider::object_type(), 1000, offset) - .await - } else { - store - .list(Provider::object_type(), workspace, 1000, offset) - .await - } + let query = if is_platform_scope { + ObjectListQuery::AllWorkspaces + } else { + ObjectListQuery::Workspace(workspace) + }; + let providers: Vec = store + .collect_messages(query) + .await .map_err(|e| Status::internal(format!("list providers failed: {e}")))?; - if records.is_empty() { - break; - } - offset = offset - .checked_add( - u32::try_from(records.len()) - .map_err(|_| Status::internal("provider page size exceeded u32"))?, - ) - .ok_or_else(|| Status::internal("provider pagination offset overflow"))?; - for record in records { - let provider = Provider::decode(record.payload.as_slice()) - .map_err(|e| Status::internal(format!("decode provider failed: {e}")))?; - if provider.profile_workspace != workspace - || normalize_profile_id(&provider.r#type).as_deref() != Some(profile_id) - { - continue; - } - let label = if is_platform_scope { - format!("{}/{}", provider.object_workspace(), provider.object_name()) - } else { - provider.object_name().to_string() - }; - blocking.push(label); + for provider in providers { + if provider.profile_workspace != workspace + || normalize_profile_id(&provider.r#type).as_deref() != Some(profile_id) + { + continue; } + let label = if is_platform_scope { + format!("{}/{}", provider.object_workspace(), provider.object_name()) + } else { + provider.object_name().to_string() + }; + blocking.push(label); } blocking.sort(); blocking.dedup(); @@ -2569,8 +2538,6 @@ pub(super) async fn handle_list_providers( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let request = request.into_inner(); - let limit = clamp_limit(request.limit, 100, MAX_PAGE_SIZE); - let scope = authorize_list_workspace_selector( &state.store, &state.admin_role, @@ -2579,13 +2546,8 @@ pub(super) async fn handle_list_providers( MinWorkspaceRole::User, ) .await?; - let providers = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { - let all: Vec = state - .store - .list_all_messages(limit, request.offset) - .await - .map_err(|e| Status::internal(format!("list providers failed: {e}")))?; - all.into_iter().map(redact_provider_credentials).collect() + let workspace = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { + None } else { let AuthorizedWorkspaceScope::Workspace(authz) = scope else { unreachable!("all-workspaces scope handled above") @@ -2593,10 +2555,34 @@ pub(super) async fn handle_list_providers( let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) .await? .name; - list_provider_records(state.store.as_ref(), &workspace, limit, request.offset).await? + Some(workspace) }; - - Ok(Response::new(ListProvidersResponse { providers })) + let scope_fingerprint = workspace.as_deref().unwrap_or("*"); + let pagination = Pagination::new( + request.page_size, + &request.page_token, + "ListProviders", + &[scope_fingerprint], + )?; + let after = pagination.object_cursor()?; + let query = workspace + .as_deref() + .map_or(ObjectListQuery::AllWorkspaces, ObjectListQuery::Workspace); + let page = state + .store + .list_message_page::(query, after.as_ref(), pagination.page_size()) + .await + .map_err(|e| Status::internal(format!("list providers failed: {e}")))?; + let providers = page + .messages + .into_iter() + .map(redact_provider_credentials) + .collect(); + let next_page_token = pagination.next_object_token(page.next_cursor.as_ref()); + Ok(Response::new(ListProvidersResponse { + providers, + next_page_token, + })) } /// Return provider profiles visible in the given workspace scope. @@ -2618,21 +2604,47 @@ pub(super) async fn handle_list_provider_profiles( ) .await? .name; - let limit = clamp_limit(request.limit, 100, MAX_PAGE_SIZE) as usize; - let offset = request.offset as usize; + let pagination = Pagination::new( + request.page_size, + &request.page_token, + "ListProviderProfiles", + &[&request.workspace], + )?; + let after = pagination.profile_cursor()?; let catalog = state .provider_profile_sources .snapshot_catalog(state.store.as_ref(), &workspace) .await?; - let profiles = catalog + let mut profiles = catalog .list_all_scoped_profiles() .into_iter() - .map(|(_, profile)| profile) - .skip(offset) - .take(limit) - .collect(); - - Ok(Response::new(ListProviderProfilesResponse { profiles })) + .map(|(scope, profile)| { + let scope = match scope { + ProfileScope::Static => "static", + ProfileScope::Platform => "platform", + ProfileScope::Workspace => "workspace", + }; + (format!("{}\0{scope}", profile.id), profile) + }) + .collect::>(); + profiles.sort_unstable_by(|left, right| left.0.cmp(&right.0)); + if let Some(after) = after { + profiles.retain(|(key, _)| key.as_str() > after); + } + let page_size = usize::try_from(pagination.page_size()) + .map_err(|_| Status::internal("page_size does not fit usize"))?; + let has_more = profiles.len() > page_size; + profiles.truncate(page_size); + let next_key = if has_more { + profiles.last().map(|(key, _)| key.as_str()) + } else { + None + }; + let next_page_token = pagination.next_profile_token(next_key); + Ok(Response::new(ListProviderProfilesResponse { + profiles: profiles.into_iter().map(|(_, profile)| profile).collect(), + next_page_token, + })) } pub(super) async fn handle_get_provider_profile( @@ -3012,7 +3024,7 @@ pub(super) async fn get_provider_type_profile( ) -> Result, Status> { // Query stored profiles scoped to the requested workspace. let stored: Vec = store - .list_messages(workspace, 10_000, 0) + .collect_messages(ObjectListQuery::Workspace(workspace)) .await .map_err(|e| Status::internal(format!("list provider profiles failed: {e}")))?; let id_norm = normalize_profile_id(id); @@ -5852,8 +5864,8 @@ mod tests { let response = handle_list_provider_profiles( &state, authed_request(ListProviderProfilesRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace: "default".to_string(), }), ) @@ -5898,6 +5910,81 @@ mod tests { ); } + #[tokio::test] + async fn list_provider_profiles_traverses_multiple_pages_exactly_once() { + let state = test_server_state().await; + let all = handle_list_provider_profiles( + &state, + authed_request(ListProviderProfilesRequest { + page_size: 100, + page_token: String::new(), + workspace: "default".to_string(), + }), + ) + .await + .unwrap() + .into_inner() + .profiles; + + let mut listed = Vec::new(); + let mut page_token = String::new(); + let mut page_size = 2; + loop { + let page = handle_list_provider_profiles( + &state, + authed_request(ListProviderProfilesRequest { + page_size, + page_token, + workspace: "default".to_string(), + }), + ) + .await + .unwrap() + .into_inner(); + listed.extend(page.profiles); + if page.next_page_token.is_empty() { + break; + } + page_token = page.next_page_token; + page_size = 3; + } + + assert_eq!( + listed.iter().map(|profile| &profile.id).collect::>(), + all.iter().map(|profile| &profile.id).collect::>() + ); + } + + #[tokio::test] + async fn list_provider_profiles_rejects_token_from_different_workspace_filter() { + let state = test_server_state().await; + let first = handle_list_provider_profiles( + &state, + authed_request(ListProviderProfilesRequest { + page_size: 1, + page_token: String::new(), + workspace: "default".to_string(), + }), + ) + .await + .unwrap() + .into_inner(); + assert!(!first.next_page_token.is_empty()); + + let error = handle_list_provider_profiles( + &state, + authed_request(ListProviderProfilesRequest { + page_size: 1, + page_token: first.next_page_token, + workspace: String::new(), + }), + ) + .await + .unwrap_err(); + + assert_eq!(error.code(), Code::InvalidArgument); + } + #[tokio::test] async fn get_provider_profile_returns_profile_or_not_found() { let state = test_server_state().await; @@ -5954,8 +6041,8 @@ mod tests { let listed = handle_list_provider_profiles( &state, authed_request(ListProviderProfilesRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace: "default".to_string(), }), ) @@ -13127,8 +13214,8 @@ mod tests { let listed = handle_list_providers( &state, authed_request(ListProvidersRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), @@ -13143,8 +13230,8 @@ mod tests { let listed = handle_list_providers( &state, authed_request(ListProvidersRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "beta".to_string(), )), @@ -13174,8 +13261,8 @@ mod tests { let listed = handle_list_providers( &state, authed_request(ListProvidersRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), @@ -13230,8 +13317,8 @@ mod tests { let listed = handle_list_providers( &state, authed_request(ListProvidersRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), }), ) @@ -13596,8 +13683,8 @@ mod tests { handle_list_provider_profiles( &state, authed_request(ListProviderProfilesRequest { - limit: 200, - offset: 0, + page_size: 200, + page_token: String::new(), workspace, }), ) @@ -13720,8 +13807,8 @@ mod tests { let resp = handle_list_provider_profiles( &state, authed_request(ListProviderProfilesRequest { - limit: 200, - offset: 0, + page_size: 200, + page_token: String::new(), workspace: "default".to_string(), }), ) @@ -13765,8 +13852,8 @@ mod tests { let resp = handle_list_provider_profiles( &state, authed_request(ListProviderProfilesRequest { - limit: 200, - offset: 0, + page_size: 200, + page_token: String::new(), workspace: "default".to_string(), }), ) @@ -13905,8 +13992,8 @@ mod tests { let resp = handle_list_provider_profiles( &state, authed_request(ListProviderProfilesRequest { - limit: 200, - offset: 0, + page_size: 200, + page_token: String::new(), workspace: String::new(), }), ) diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 17ae70d2fb..d428e64569 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -14,7 +14,10 @@ use crate::auth::workspace_authz::{ AuthorizedWorkspaceScope, MinWorkspaceRole, authorize_list_workspace_selector, authorize_sandbox_workspace, authorize_workspace_selector, }; -use crate::persistence::{ObjectLabels, ObjectType, WriteCondition, generate_name}; +use crate::pagination::Pagination; +use crate::persistence::{ + ObjectLabels, ObjectListQuery, ObjectType, WriteCondition, generate_name, +}; use futures::future; use openshell_core::net::set_tcp_nodelay_best_effort; use openshell_core::proto::datamodel::v1::ObjectMeta; @@ -66,7 +69,7 @@ use super::validation::{ validate_exec_request_fields, validate_no_reserved_provider_policy_keys, validate_policy_safety, validate_sandbox_governance_spec, validate_sandbox_spec, }; -use super::{MAX_PAGE_SIZE, MAX_PROVIDERS, MAX_ROUTABLE_NAME_LEN, clamp_limit}; +use super::{MAX_PROVIDERS, MAX_ROUTABLE_NAME_LEN}; use crate::persistence::current_time_ms; const TCP_FORWARD_CHUNK_SIZE: usize = 64 * 1024; @@ -696,8 +699,6 @@ pub(super) async fn handle_list_sandboxes( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let request = request.into_inner(); - let limit = clamp_limit(request.limit, 100, MAX_PAGE_SIZE); - let scope = authorize_list_workspace_selector( &state.store, &state.admin_role, @@ -706,21 +707,11 @@ pub(super) async fn handle_list_sandboxes( MinWorkspaceRole::User, ) .await?; - let sandboxes: Vec = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { - if request.label_selector.is_empty() { - state - .store - .list_all_messages(limit, request.offset) - .await - .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))? - } else { - crate::grpc::validation::validate_label_selector(&request.label_selector)?; - state - .store - .list_all_messages_with_selector(&request.label_selector, limit, request.offset) - .await - .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))? - } + if !request.label_selector.is_empty() { + crate::grpc::validation::validate_label_selector(&request.label_selector)?; + } + let workspace = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { + None } else { let AuthorizedWorkspaceScope::Workspace(authz) = scope else { unreachable!("all-workspaces scope handled above") @@ -728,30 +719,35 @@ pub(super) async fn handle_list_sandboxes( let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) .await? .name; - if request.label_selector.is_empty() { - state - .store - .list_messages(&workspace, limit, request.offset) - .await - .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))? - } else { - crate::grpc::validation::validate_label_selector(&request.label_selector)?; - state - .store - .list_messages_with_selector( - &workspace, - &request.label_selector, - limit, - request.offset, - ) - .await - .map_err(|e| { - Status::internal(format!("list sandboxes with selector failed: {e}")) - })? - } + Some(workspace) }; - - Ok(Response::new(ListSandboxesResponse { sandboxes })) + let scope_fingerprint = workspace.as_deref().unwrap_or("*"); + let pagination = Pagination::new( + request.page_size, + &request.page_token, + "ListSandboxes", + &[scope_fingerprint, &request.label_selector], + )?; + let after = pagination.object_cursor()?; + let query = match (workspace.as_deref(), request.label_selector.as_str()) { + (None, "") => ObjectListQuery::AllWorkspaces, + (None, selector) => ObjectListQuery::AllWorkspacesSelector(selector), + (Some(workspace), "") => ObjectListQuery::Workspace(workspace), + (Some(workspace), selector) => ObjectListQuery::WorkspaceSelector { + workspace, + label_selector: selector, + }, + }; + let page = state + .store + .list_message_page::(query, after.as_ref(), pagination.page_size()) + .await + .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))?; + let next_page_token = pagination.next_object_token(page.next_cursor.as_ref()); + Ok(Response::new(ListSandboxesResponse { + sandboxes: page.messages, + next_page_token, + })) } pub(super) async fn handle_create_sandbox_template( @@ -882,7 +878,6 @@ pub(super) async fn handle_list_sandbox_templates( ) -> Result, Status> { let principal = super::extract_principal(&request)?; let request = request.into_inner(); - let limit = clamp_limit(request.limit, 100, MAX_PAGE_SIZE); let scope = authorize_list_workspace_selector( &state.store, &state.admin_role, @@ -891,25 +886,11 @@ pub(super) async fn handle_list_sandbox_templates( MinWorkspaceRole::User, ) .await?; - let templates = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { - if request.label_selector.is_empty() { - state - .store - .list_all_messages::(limit, request.offset) - .await - .map_err(|e| Status::internal(format!("list sandbox templates failed: {e}")))? - } else { - crate::grpc::validation::validate_label_selector(&request.label_selector)?; - state - .store - .list_all_messages_with_selector::( - &request.label_selector, - limit, - request.offset, - ) - .await - .map_err(|e| Status::internal(format!("list sandbox templates failed: {e}")))? - } + if !request.label_selector.is_empty() { + crate::grpc::validation::validate_label_selector(&request.label_selector)?; + } + let workspace = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { + None } else { let AuthorizedWorkspaceScope::Workspace(authz) = scope else { unreachable!("all-workspaces scope handled above") @@ -917,29 +898,35 @@ pub(super) async fn handle_list_sandbox_templates( let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) .await? .name; - if request.label_selector.is_empty() { - state - .store - .list_messages::(&workspace, limit, request.offset) - .await - .map_err(|e| Status::internal(format!("list sandbox templates failed: {e}")))? - } else { - crate::grpc::validation::validate_label_selector(&request.label_selector)?; - state - .store - .list_messages_with_selector::( - &workspace, - &request.label_selector, - limit, - request.offset, - ) - .await - .map_err(|e| { - Status::internal(format!("list sandbox templates with selector failed: {e}")) - })? - } + Some(workspace) + }; + let scope_fingerprint = workspace.as_deref().unwrap_or("*"); + let pagination = Pagination::new( + request.page_size, + &request.page_token, + "ListSandboxTemplates", + &[scope_fingerprint, &request.label_selector], + )?; + let after = pagination.object_cursor()?; + let query = match (workspace.as_deref(), request.label_selector.as_str()) { + (None, "") => ObjectListQuery::AllWorkspaces, + (None, selector) => ObjectListQuery::AllWorkspacesSelector(selector), + (Some(workspace), "") => ObjectListQuery::Workspace(workspace), + (Some(workspace), selector) => ObjectListQuery::WorkspaceSelector { + workspace, + label_selector: selector, + }, }; - Ok(Response::new(ListSandboxTemplatesResponse { templates })) + let page = state + .store + .list_message_page::(query, after.as_ref(), pagination.page_size()) + .await + .map_err(|e| Status::internal(format!("list sandbox templates failed: {e}")))?; + let next_page_token = pagination.next_object_token(page.next_cursor.as_ref()); + Ok(Response::new(ListSandboxTemplatesResponse { + templates: page.messages, + next_page_token, + })) } pub(super) async fn handle_delete_sandbox_template( @@ -4826,8 +4813,8 @@ mod tests { let listed = handle_list_sandbox_templates( &state, authed_request(ListSandboxTemplatesRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), @@ -4912,8 +4899,8 @@ mod tests { let listed = handle_list_sandbox_templates( &state, authed_request(ListSandboxTemplatesRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), @@ -4951,8 +4938,8 @@ mod tests { let listed = handle_list_sandbox_templates( &state, authed_request(ListSandboxTemplatesRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), @@ -5000,8 +4987,8 @@ mod tests { let listed = handle_list_sandbox_templates( &state, authed_request(ListSandboxTemplatesRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "beta".to_string(), )), @@ -6399,8 +6386,8 @@ mod tests { let listed = handle_list_sandboxes( &state, authed_request(ListSandboxesRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), label_selector: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -6417,8 +6404,8 @@ mod tests { let listed = handle_list_sandboxes( &state, authed_request(ListSandboxesRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), label_selector: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "beta".to_string(), @@ -6442,8 +6429,8 @@ mod tests { let listed = handle_list_sandboxes( &state, authed_request(ListSandboxesRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), label_selector: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -6487,8 +6474,8 @@ mod tests { let listed = handle_list_sandboxes( &state, authed_request(ListSandboxesRequest { - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), label_selector: String::new(), workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), }), @@ -6497,6 +6484,38 @@ mod tests { .unwrap() .into_inner(); assert_eq!(listed.sandboxes.len(), 2); + let first_page = handle_list_sandboxes( + &state, + authed_request(ListSandboxesRequest { + page_size: 1, + page_token: String::new(), + label_selector: String::new(), + workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(first_page.sandboxes.len(), 1); + assert!(!first_page.next_page_token.is_empty()); + let second_page = handle_list_sandboxes( + &state, + authed_request(ListSandboxesRequest { + page_size: 100, + page_token: first_page.next_page_token, + label_selector: String::new(), + workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(second_page.sandboxes.len(), 1); + assert!(second_page.next_page_token.is_empty()); + assert_ne!( + first_page.sandboxes[0].object_id(), + second_page.sandboxes[0].object_id() + ); } /// Non-members must receive `PERMISSION_DENIED` — never `NOT_FOUND` — when diff --git a/crates/openshell-server/src/grpc/service.rs b/crates/openshell-server/src/grpc/service.rs index 34c7d62d3f..a691ec0ecf 100644 --- a/crates/openshell-server/src/grpc/service.rs +++ b/crates/openshell-server/src/grpc/service.rs @@ -19,7 +19,8 @@ use crate::auth::workspace_authz::{ AuthorizedWorkspaceScope, MinWorkspaceRole, authorize_list_workspace_selector, authorize_workspace_selector, }; -use crate::persistence::{ObjectType, WriteCondition}; +use crate::pagination::Pagination; +use crate::persistence::{ObjectListQuery, ObjectType, WriteCondition}; use crate::service_routing; const MAX_SERVICE_NAME_LEN: usize = super::MAX_ROUTABLE_NAME_LEN; @@ -181,7 +182,6 @@ pub(super) async fn handle_list_services( validate_endpoint_name("sandbox", &req.sandbox, MAX_SANDBOX_NAME_LEN)?; } - let limit = super::clamp_limit(req.limit, 100, super::MAX_PAGE_SIZE); let scope = authorize_list_workspace_selector( &state.store, &state.admin_role, @@ -190,47 +190,59 @@ pub(super) async fn handle_list_services( MinWorkspaceRole::User, ) .await?; - let endpoints: Vec = - if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { - if !req.sandbox.is_empty() { - return Err(Status::invalid_argument( - "sandbox filter is not supported with all_workspaces", - )); - } - state.store.list_all_messages(limit, req.offset).await - } else { - let AuthorizedWorkspaceScope::Workspace(authz) = scope else { - unreachable!("all-workspaces scope handled above") - }; - let workspace = - super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) - .await? - .name; - if req.sandbox.is_empty() { - state - .store - .list_messages(&workspace, limit, req.offset) - .await - } else { - state - .store - .list_messages_with_selector( - &workspace, - &format!("sandbox={}", req.sandbox), - limit, - req.offset, - ) - .await - } + let workspace = if matches!(scope, AuthorizedWorkspaceScope::AllWorkspaces) { + if !req.sandbox.is_empty() { + return Err(Status::invalid_argument( + "sandbox filter is not supported with all_workspaces", + )); } + None + } else { + let AuthorizedWorkspaceScope::Workspace(authz) = scope else { + unreachable!("all-workspaces scope handled above") + }; + let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) + .await? + .name; + Some(workspace) + }; + let scope_fingerprint = workspace.as_deref().unwrap_or("*"); + let pagination = Pagination::new( + req.page_size, + &req.page_token, + "ListServices", + &[&req.sandbox, scope_fingerprint], + )?; + let after = pagination.object_cursor()?; + let selector = (!req.sandbox.is_empty()).then(|| format!("sandbox={}", req.sandbox)); + let query = match (workspace.as_deref(), selector.as_deref()) { + (None, None) => ObjectListQuery::AllWorkspaces, + (Some(workspace), None) => ObjectListQuery::Workspace(workspace), + (Some(workspace), Some(selector)) => ObjectListQuery::WorkspaceSelector { + workspace, + label_selector: selector, + }, + (None, Some(_)) => { + return Err(Status::invalid_argument( + "sandbox filter cannot be combined with all_workspaces", + )); + } + }; + let page = state + .store + .list_message_page::(query, after.as_ref(), pagination.page_size()) + .await .map_err(|e| Status::internal(format!("list endpoints failed: {e}")))?; - - let services = endpoints + let services = page + .messages .into_iter() .map(|ep| service_endpoint_response(state, ep)) .collect(); - - Ok(Response::new(ListServicesResponse { services })) + let next_page_token = pagination.next_object_token(page.next_cursor.as_ref()); + Ok(Response::new(ListServicesResponse { + services, + next_page_token, + })) } pub(super) async fn handle_delete_service( @@ -429,8 +441,8 @@ mod tests { &state, authed_request(ListServicesRequest { sandbox: "my-sandbox".to_string(), - limit: 0, - offset: 0, + page_size: 0, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), @@ -493,8 +505,8 @@ mod tests { &state, authed_request(ListServicesRequest { sandbox: "my-sandbox".to_string(), - limit: 0, - offset: 0, + page_size: 0, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), @@ -563,8 +575,8 @@ mod tests { &state, authed_request(ListServicesRequest { sandbox: "my-sandbox".to_string(), - limit: 0, - offset: 0, + page_size: 0, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), @@ -772,8 +784,8 @@ mod tests { &state, authed_request(ListServicesRequest { sandbox: "my-sandbox".to_string(), - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), @@ -792,8 +804,8 @@ mod tests { &state, authed_request(ListServicesRequest { sandbox: "my-sandbox".to_string(), - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "beta".to_string(), )), @@ -828,8 +840,8 @@ mod tests { &state, authed_request(ListServicesRequest { sandbox: "my-sandbox".to_string(), - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), )), @@ -876,8 +888,8 @@ mod tests { &state, authed_request(ListServicesRequest { sandbox: String::new(), - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), }), ) diff --git a/crates/openshell-server/src/grpc/workspace.rs b/crates/openshell-server/src/grpc/workspace.rs index 546934a6ed..c18819be52 100644 --- a/crates/openshell-server/src/grpc/workspace.rs +++ b/crates/openshell-server/src/grpc/workspace.rs @@ -23,15 +23,14 @@ use tonic::{Request, Response, Status}; use crate::ServerState; use crate::auth::principal::Principal; use crate::auth::workspace_authz::{AuthGrant, MinWorkspaceRole, authorize_workspace}; +use crate::pagination::Pagination; use crate::persistence::{ - DRAFT_CHUNK_OBJECT_TYPE, ObjectLabels, ObjectType, POLICY_OBJECT_TYPE, WriteCondition, - current_time_ms, + DRAFT_CHUNK_OBJECT_TYPE, ObjectLabels, ObjectListQuery, ObjectType, POLICY_OBJECT_TYPE, + WriteCondition, current_time_ms, }; use crate::storage_proto::{StoredProviderCredentialRefreshState, StoredProviderProfile}; use std::collections::HashMap; -use super::{MAX_PAGE_SIZE, clamp_limit}; - pub const WORKSPACE_OBJECT_TYPE: &str = "workspace"; pub const DEFAULT_WORKSPACE_NAME: &str = "default"; const MAX_WORKSPACE_MEMBERS: u32 = 1000; @@ -248,40 +247,42 @@ pub(super) async fn handle_list_workspaces( let principal = super::extract_principal(&request)?; let req = request.into_inner(); super::validation::validate_label_selector(&req.label_selector)?; - let limit = clamp_limit(req.limit, 100, MAX_PAGE_SIZE); let subject = membership_filter_subject(state, &principal)?; - let member_type = WorkspaceMember::object_type(); - let workspaces = match subject { - Some(subject) if req.label_selector.is_empty() => state - .store - .list_messages_with_membership::(member_type, subject, limit, req.offset) - .await - .map_err(|e| Status::internal(format!("list workspaces failed: {e}")))?, - Some(subject) => state - .store - .list_messages_with_membership_and_selector::( - member_type, - subject, - &req.label_selector, - limit, - req.offset, - ) - .await - .map_err(|e| Status::internal(format!("list workspaces failed: {e}")))?, - None if req.label_selector.is_empty() => state - .store - .list_messages("", limit, req.offset) - .await - .map_err(|e| Status::internal(format!("list workspaces failed: {e}")))?, - None => state - .store - .list_messages_with_selector("", &req.label_selector, limit, req.offset) - .await - .map_err(|e| Status::internal(format!("list workspaces failed: {e}")))?, + let pagination = Pagination::new( + req.page_size, + &req.page_token, + "ListWorkspaces", + &[&req.label_selector, subject.unwrap_or("")], + )?; + let after = pagination.object_cursor()?; + let query = match (subject, req.label_selector.as_str()) { + (Some(subject), "") => ObjectListQuery::Membership { + member_type, + member_name: subject, + }, + (Some(subject), selector) => ObjectListQuery::MembershipSelector { + member_type, + member_name: subject, + label_selector: selector, + }, + (None, "") => ObjectListQuery::Workspace(""), + (None, selector) => ObjectListQuery::WorkspaceSelector { + workspace: "", + label_selector: selector, + }, }; + let page = state + .store + .list_message_page::(query, after.as_ref(), pagination.page_size()) + .await + .map_err(|e| Status::internal(format!("list workspaces failed: {e}")))?; + let next_page_token = pagination.next_object_token(page.next_cursor.as_ref()); - Ok(Response::new(ListWorkspacesResponse { workspaces })) + Ok(Response::new(ListWorkspacesResponse { + workspaces: page.messages, + next_page_token, + })) } pub(super) async fn handle_delete_workspace( @@ -603,15 +604,28 @@ pub(super) async fn handle_list_workspace_members( .await? .name; - let limit = clamp_limit(req.limit, 100, MAX_PAGE_SIZE); - - let members: Vec = state + let pagination = Pagination::new( + req.page_size, + &req.page_token, + "ListWorkspaceMembers", + &[&req.workspace], + )?; + let after = pagination.object_cursor()?; + let page = state .store - .list_messages(&workspace, limit, req.offset) + .list_message_page::( + ObjectListQuery::Workspace(&workspace), + after.as_ref(), + pagination.page_size(), + ) .await .map_err(|e| Status::internal(format!("list workspace members failed: {e}")))?; + let next_page_token = pagination.next_object_token(page.next_cursor.as_ref()); - Ok(Response::new(ListWorkspaceMembersResponse { members })) + Ok(Response::new(ListWorkspaceMembersResponse { + members: page.messages, + next_page_token, + })) } #[cfg(test)] @@ -1044,8 +1058,8 @@ mod tests { &state, authed_request(ListWorkspaceMembersRequest { workspace: "default".to_string(), - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), }), ) .await @@ -1086,8 +1100,8 @@ mod tests { &state, authed_request(ListWorkspaceMembersRequest { workspace: "default".to_string(), - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), }), ) .await @@ -1166,8 +1180,8 @@ mod tests { &state, authed_request(ListWorkspaceMembersRequest { workspace: "cleanup-test".to_string(), - limit: 100, - offset: 0, + page_size: 100, + page_token: String::new(), }), ) .await diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 50c4f98696..6bea00e6a0 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -26,6 +26,7 @@ mod http; mod middleware; mod multiplex; mod otel_tracing; +mod pagination; mod persistence; pub(crate) mod policy_store; mod provider_profile_sources; diff --git a/crates/openshell-server/src/pagination.rs b/crates/openshell-server/src/pagination.rs new file mode 100644 index 0000000000..66dd1d092e --- /dev/null +++ b/crates/openshell-server/src/pagination.rs @@ -0,0 +1,245 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Shared AIP-158 pagination validation and opaque continuation-token codec. + +use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; +use openshell_core::proto::pagination::v1::{ + ObjectCursor as ProtoObjectCursor, PageToken, PolicyCursor, ProfileCursor, page_token::Cursor, +}; +use prost::Message; +use sha2::{Digest, Sha256}; +use tonic::Status; + +use crate::persistence::ObjectCursor; + +const TOKEN_VERSION: u32 = 1; +pub const DEFAULT_PAGE_SIZE: u32 = 100; +pub const MAX_PAGE_SIZE: u32 = 1000; + +/// Validated pagination state for one list request. +#[derive(Debug)] +pub struct Pagination { + page_size: u32, + method: &'static str, + request_fingerprint: Vec, + cursor: Option, +} + +impl Pagination { + pub fn new( + page_size: i32, + page_token: &str, + method: &'static str, + request_parameters: &[&str], + ) -> Result { + if page_size < 0 { + return Err(Status::invalid_argument("page_size must not be negative")); + } + let page_size = if page_size == 0 { + DEFAULT_PAGE_SIZE + } else { + u32::try_from(page_size) + .expect("a positive i32 always fits in u32") + .min(MAX_PAGE_SIZE) + }; + let request_fingerprint = fingerprint(request_parameters); + let cursor = if page_token.is_empty() { + None + } else { + let bytes = URL_SAFE_NO_PAD + .decode(page_token) + .map_err(|_| Status::invalid_argument("page_token is malformed"))?; + let token = PageToken::decode(bytes.as_slice()) + .map_err(|_| Status::invalid_argument("page_token is malformed"))?; + if token.version != TOKEN_VERSION + || token.method != method + || token.request_fingerprint != request_fingerprint + { + return Err(Status::invalid_argument( + "page_token does not match this list request", + )); + } + token.cursor + }; + + Ok(Self { + page_size, + method, + request_fingerprint, + cursor, + }) + } + + pub fn page_size(&self) -> u32 { + self.page_size + } + + pub fn object_cursor(&self) -> Result, Status> { + match &self.cursor { + None => Ok(None), + Some(Cursor::Object(cursor)) => Ok(Some(ObjectCursor { + created_at_ms: cursor.created_at_ms, + name: cursor.name.clone(), + workspace: cursor.workspace.clone(), + id: cursor.id.clone(), + })), + Some(_) => Err(Status::invalid_argument( + "page_token has the wrong cursor type", + )), + } + } + + pub fn policy_cursor(&self) -> Result, Status> { + match &self.cursor { + None => Ok(None), + Some(Cursor::Policy(cursor)) => Ok(Some(cursor.version)), + Some(_) => Err(Status::invalid_argument( + "page_token has the wrong cursor type", + )), + } + } + + pub fn profile_cursor(&self) -> Result, Status> { + match &self.cursor { + None => Ok(None), + Some(Cursor::Profile(cursor)) => Ok(Some(&cursor.key)), + Some(_) => Err(Status::invalid_argument( + "page_token has the wrong cursor type", + )), + } + } + + pub fn next_object_token(&self, cursor: Option<&ObjectCursor>) -> String { + cursor.map_or_else(String::new, |cursor| { + self.encode(Cursor::Object(ProtoObjectCursor { + created_at_ms: cursor.created_at_ms, + name: cursor.name.clone(), + workspace: cursor.workspace.clone(), + id: cursor.id.clone(), + })) + }) + } + + pub fn next_policy_token(&self, version: Option) -> String { + version.map_or_else(String::new, |version| { + self.encode(Cursor::Policy(PolicyCursor { version })) + }) + } + + pub fn next_profile_token(&self, key: Option<&str>) -> String { + key.map_or_else(String::new, |key| { + self.encode(Cursor::Profile(ProfileCursor { + key: key.to_string(), + })) + }) + } + + fn encode(&self, cursor: Cursor) -> String { + URL_SAFE_NO_PAD.encode( + PageToken { + version: TOKEN_VERSION, + method: self.method.to_string(), + request_fingerprint: self.request_fingerprint.clone(), + cursor: Some(cursor), + } + .encode_to_vec(), + ) + } +} + +fn fingerprint(parameters: &[&str]) -> Vec { + let mut hasher = Sha256::new(); + for parameter in parameters { + hasher.update( + u64::try_from(parameter.len()) + .unwrap_or(u64::MAX) + .to_le_bytes(), + ); + hasher.update(parameter.as_bytes()); + } + hasher.finalize().to_vec() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn page_size_defaults_clamps_and_rejects_negative_values() { + assert_eq!( + Pagination::new(0, "", "list", &[]).unwrap().page_size(), + 100 + ); + assert_eq!( + Pagination::new(1500, "", "list", &[]).unwrap().page_size(), + 1000 + ); + assert_eq!( + Pagination::new(-1, "", "list", &[]).unwrap_err().code(), + tonic::Code::InvalidArgument + ); + } + + #[test] + fn object_token_round_trips_and_allows_page_size_changes() { + let first = Pagination::new(10, "", "sandboxes", &["default", "env=prod"]).unwrap(); + let cursor = ObjectCursor { + created_at_ms: 42, + name: "sandbox".into(), + workspace: "default".into(), + id: "id".into(), + }; + let token = first.next_object_token(Some(&cursor)); + assert!( + token + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')) + ); + + let next = Pagination::new(20, &token, "sandboxes", &["default", "env=prod"]) + .unwrap() + .object_cursor() + .unwrap() + .unwrap(); + assert_eq!(next.id, cursor.id); + assert_eq!(next.created_at_ms, cursor.created_at_ms); + } + + #[test] + fn token_rejects_method_filter_and_cursor_mismatches() { + let page = Pagination::new(10, "", "sandboxes", &["default"]).unwrap(); + let token = page.next_profile_token(Some("profile")); + + assert!(Pagination::new(10, &token, "providers", &["default"]).is_err()); + assert!(Pagination::new(10, &token, "sandboxes", &["other"]).is_err()); + assert!( + Pagination::new(10, &token, "sandboxes", &["default"]) + .unwrap() + .object_cursor() + .is_err() + ); + } + + #[test] + fn token_rejects_malformed_and_unsupported_versions() { + let malformed = Pagination::new(10, "not+base64", "sandboxes", &["default"]) + .expect_err("malformed tokens must be rejected"); + assert_eq!(malformed.code(), tonic::Code::InvalidArgument); + + let unsupported = URL_SAFE_NO_PAD.encode( + PageToken { + version: TOKEN_VERSION + 1, + method: "sandboxes".to_string(), + request_fingerprint: fingerprint(&["default"]), + cursor: Some(Cursor::Profile(ProfileCursor { + key: "profile".to_string(), + })), + } + .encode_to_vec(), + ); + let error = Pagination::new(10, &unsupported, "sandboxes", &["default"]) + .expect_err("unsupported token versions must be rejected"); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + } +} diff --git a/crates/openshell-server/src/persistence/mod.rs b/crates/openshell-server/src/persistence/mod.rs index 066ce6cc3a..e22f5f99b9 100644 --- a/crates/openshell-server/src/persistence/mod.rs +++ b/crates/openshell-server/src/persistence/mod.rs @@ -45,6 +45,8 @@ pub enum PersistenceError { Decode(String), #[error("encode error: {0}")] Encode(String), + #[error("pagination error: {0}")] + Pagination(String), #[error("unique violation{constraint_msg}")] UniqueViolation { constraint: Option, @@ -109,9 +111,8 @@ pub struct ObjectRecord { /// Stable position in the global object-listing order. /// -/// Keyset consumers must use the matching store method for the order encoded -/// here: workspace-scoped lists use `created_at_ms`, `name`, and `id`; global -/// lists additionally include `workspace`. +/// Keyset consumers must use the matching store method for the total +/// `(created_at_ms, name, workspace, id)` order encoded here. #[derive(Debug, Clone)] pub struct ObjectCursor { pub created_at_ms: i64, @@ -131,6 +132,44 @@ impl From<&ObjectRecord> for ObjectCursor { } } +/// Filters supported by the shared object-store keyset pager. +#[derive(Debug, Clone, Copy)] +pub enum ObjectListQuery<'a> { + Workspace(&'a str), + AllWorkspaces, + Scope(&'a str), + WorkspaceSelector { + workspace: &'a str, + label_selector: &'a str, + }, + AllWorkspacesSelector(&'a str), + Membership { + member_type: &'a str, + member_name: &'a str, + }, + MembershipSelector { + member_type: &'a str, + member_name: &'a str, + label_selector: &'a str, + }, +} + +/// One keyset page of raw object records. +#[derive(Debug)] +pub struct ObjectPage { + pub records: Vec, + pub next_cursor: Option, +} + +/// One keyset page of decoded protobuf messages. +#[derive(Debug)] +pub struct MessagePage { + pub messages: Vec, + pub next_cursor: Option, +} + +const FULL_SCAN_PAGE_SIZE: u32 = 1000; + /// Write condition for compare-and-swap operations. #[derive(Debug, Clone, Copy)] pub enum WriteCondition { @@ -619,6 +658,109 @@ impl Store { store_dispatch_traced!(self.list_by_type_after(object_type, after, limit)) } + /// Return one keyset page for an explicit query shape. + /// + /// The page is ordered by the immutable total key + /// `(created_at_ms, name, workspace, id)`. `next_cursor` is present only + /// when another page exists. + pub async fn list_object_page( + &self, + object_type: &str, + query: ObjectListQuery<'_>, + after: Option<&ObjectCursor>, + page_size: u32, + ) -> PersistenceResult { + if page_size == 0 { + return Err(PersistenceError::Pagination( + "page size must be greater than zero".into(), + )); + } + let fetch_size = page_size.checked_add(1).ok_or_else(|| { + PersistenceError::Pagination("page size overflow while probing next page".into()) + })?; + let mut records = match self { + Self::Postgres(store) => { + store + .list_object_page(object_type, query, after, fetch_size) + .await + } + Self::Sqlite(store) => { + store + .list_object_page(object_type, query, after, fetch_size) + .await + } + }?; + let has_more = records.len() + > usize::try_from(page_size) + .map_err(|_| PersistenceError::Pagination("page size does not fit usize".into()))?; + if has_more { + records.truncate(usize::try_from(page_size).map_err(|_| { + PersistenceError::Pagination("page size does not fit usize".into()) + })?); + } + let next_cursor = if has_more { + records.last().map(ObjectCursor::from) + } else { + None + }; + Ok(ObjectPage { + records, + next_cursor, + }) + } + + /// Return one decoded keyset page and hydrate every resource version. + pub async fn list_message_page( + &self, + query: ObjectListQuery<'_>, + after: Option<&ObjectCursor>, + page_size: u32, + ) -> PersistenceResult> { + let page = self + .list_object_page(T::object_type(), query, after, page_size) + .await?; + Ok(MessagePage { + messages: page + .records + .into_iter() + .map(decode_record) + .collect::>>()?, + next_cursor: page.next_cursor, + }) + } + + /// Exhaust every keyset page and return all matching raw records. + pub async fn collect_records( + &self, + object_type: &str, + query: ObjectListQuery<'_>, + ) -> PersistenceResult> { + let mut records = Vec::new(); + let mut cursor = None; + loop { + let page = self + .list_object_page(object_type, query, cursor.as_ref(), FULL_SCAN_PAGE_SIZE) + .await?; + records.extend(page.records); + let Some(next_cursor) = page.next_cursor else { + return Ok(records); + }; + cursor = Some(next_cursor); + } + } + + /// Exhaust every keyset page and return all matching decoded messages. + /// + /// Database and protobuf decode failures abort the operation; no partial + /// result is returned. + pub async fn collect_messages( + &self, + query: ObjectListQuery<'_>, + ) -> PersistenceResult> { + let records = self.collect_records(T::object_type(), query).await?; + records.into_iter().map(decode_record).collect() + } + /// List objects by type and application-owned scope. /// /// Workspace filtering is intentionally omitted: scope values are sandbox diff --git a/crates/openshell-server/src/persistence/postgres.rs b/crates/openshell-server/src/persistence/postgres.rs index 449f8f6df3..3fa54151b5 100644 --- a/crates/openshell-server/src/persistence/postgres.rs +++ b/crates/openshell-server/src/persistence/postgres.rs @@ -2,8 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 use super::{ - DraftChunkRecord, ObjectCursor, ObjectRecord, PersistenceError, PersistenceResult, - PolicyRecord, WriteCondition, WriteResult, current_time_ms, map_db_error, map_migrate_error, + DraftChunkRecord, ObjectCursor, ObjectListQuery, ObjectRecord, PersistenceError, + PersistenceResult, PolicyRecord, WriteCondition, WriteResult, current_time_ms, map_db_error, + map_migrate_error, }; use crate::policy_store::{ AtomicPolicyRevisionWrite, draft_chunk_payload_from_record, draft_chunk_record_from_parts, @@ -625,6 +626,103 @@ LIMIT $2 OFFSET $3 Ok(rows.into_iter().map(row_to_object_record).collect()) } + pub async fn list_object_page( + &self, + object_type: &str, + query: ObjectListQuery<'_>, + after: Option<&ObjectCursor>, + limit: u32, + ) -> PersistenceResult> { + use super::parse_label_selector; + + let mut sql = QueryBuilder::::new( + "SELECT o.object_type, o.id, o.name, o.workspace, o.payload, \ + o.created_at_ms, o.updated_at_ms, o.labels, o.resource_version \ + FROM objects o WHERE o.object_type = ", + ); + sql.push_bind(object_type); + + match query { + ObjectListQuery::Workspace(workspace) => { + sql.push(" AND o.workspace = ").push_bind(workspace); + } + ObjectListQuery::AllWorkspaces => {} + ObjectListQuery::Scope(scope) => { + sql.push(" AND o.scope = ").push_bind(scope); + } + ObjectListQuery::WorkspaceSelector { + workspace, + label_selector, + } => { + let labels = serde_json::to_value(parse_label_selector(label_selector)?) + .map_err(|e| PersistenceError::Encode(e.to_string()))?; + sql.push(" AND o.workspace = ") + .push_bind(workspace) + .push(" AND o.labels @> ") + .push_bind(labels); + } + ObjectListQuery::AllWorkspacesSelector(label_selector) => { + let labels = serde_json::to_value(parse_label_selector(label_selector)?) + .map_err(|e| PersistenceError::Encode(e.to_string()))?; + sql.push(" AND o.labels @> ").push_bind(labels); + } + ObjectListQuery::Membership { + member_type, + member_name, + } => { + sql.push( + " AND o.workspace = '' AND EXISTS (SELECT 1 FROM objects m \ + WHERE m.object_type = ", + ) + .push_bind(member_type) + .push(" AND m.workspace = o.name AND m.name = ") + .push_bind(member_name) + .push(")"); + } + ObjectListQuery::MembershipSelector { + member_type, + member_name, + label_selector, + } => { + let labels = serde_json::to_value(parse_label_selector(label_selector)?) + .map_err(|e| PersistenceError::Encode(e.to_string()))?; + sql.push( + " AND o.workspace = '' AND EXISTS (SELECT 1 FROM objects m \ + WHERE m.object_type = ", + ) + .push_bind(member_type) + .push(" AND m.workspace = o.name AND m.name = ") + .push_bind(member_name) + .push(") AND o.labels @> ") + .push_bind(labels); + } + } + + if let Some(cursor) = after { + sql.push(" AND (o.created_at_ms, COALESCE(o.name, ''), o.workspace, o.id) > (") + .push_bind(cursor.created_at_ms) + .push(", ") + .push_bind(&cursor.name) + .push(", ") + .push_bind(&cursor.workspace) + .push(", ") + .push_bind(&cursor.id) + .push(")"); + } + sql.push( + " ORDER BY o.created_at_ms ASC, COALESCE(o.name, '') ASC, \ + o.workspace ASC, o.id ASC LIMIT ", + ) + .push_bind(i64::from(limit)); + + let rows = sql + .build() + .fetch_all(&self.pool) + .await + .map_err(|e| map_db_error(&e))?; + Ok(rows.into_iter().map(row_to_object_record).collect()) + } + pub async fn list_with_membership( &self, object_type: &str, @@ -1038,6 +1136,32 @@ LIMIT $3 OFFSET $4 rows.into_iter().map(row_to_policy_record).collect() } + pub async fn list_policies_before( + &self, + sandbox_id: &str, + limit: u32, + before_version: Option, + ) -> PersistenceResult> { + let rows = sqlx::query( + r" +SELECT id, scope, version, status, payload, created_at_ms +FROM objects +WHERE object_type = $1 AND scope = $2 AND ($3::BIGINT IS NULL OR version < $3) +ORDER BY version DESC +LIMIT $4 +", + ) + .bind(POLICY_OBJECT_TYPE) + .bind(sandbox_id) + .bind(before_version) + .bind(i64::from(limit)) + .fetch_all(&self.pool) + .await + .map_err(|e| map_db_error(&e))?; + + rows.into_iter().map(row_to_policy_record).collect() + } + pub async fn update_policy_status( &self, sandbox_id: &str, diff --git a/crates/openshell-server/src/persistence/sqlite.rs b/crates/openshell-server/src/persistence/sqlite.rs index 5497b96c22..4c274386ca 100644 --- a/crates/openshell-server/src/persistence/sqlite.rs +++ b/crates/openshell-server/src/persistence/sqlite.rs @@ -2,8 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 use super::{ - DraftChunkRecord, ObjectCursor, ObjectRecord, PersistenceError, PersistenceResult, - PolicyRecord, WriteCondition, WriteResult, current_time_ms, map_db_error, map_migrate_error, + DraftChunkRecord, ObjectCursor, ObjectListQuery, ObjectRecord, PersistenceError, + PersistenceResult, PolicyRecord, WriteCondition, WriteResult, current_time_ms, map_db_error, + map_migrate_error, }; use crate::policy_store::{ AtomicPolicyRevisionWrite, draft_chunk_payload_from_record, draft_chunk_record_from_parts, @@ -42,6 +43,27 @@ pub struct SqliteStore { in_memory_keepalive: Option>>>, } +fn push_label_selector( + sql: &mut QueryBuilder, + label_selector: &str, +) -> PersistenceResult<()> { + let mut labels: Vec<_> = super::parse_label_selector(label_selector)? + .into_iter() + .collect(); + labels.sort_unstable_by(|left, right| left.0.cmp(&right.0)); + for (key, value) in labels { + let escaped_key = key + .replace('\\', "\\\\") + .replace('"', "\\\"") + .replace('\'', "''"); + sql.push(format!( + " AND json_extract(o.labels, '$.\"{escaped_key}\"') = " + )) + .push_bind(value); + } + Ok(()) +} + #[cfg(test)] pub(super) async fn replace_pool_connection(store: &SqliteStore) -> PersistenceResult<()> { let connection = store.pool.acquire().await.map_err(|e| map_db_error(&e))?; @@ -743,6 +765,93 @@ LIMIT ?2 Ok(rows.into_iter().map(row_to_object_record).collect()) } + pub async fn list_object_page( + &self, + object_type: &str, + query: ObjectListQuery<'_>, + after: Option<&ObjectCursor>, + limit: u32, + ) -> PersistenceResult> { + let mut sql = QueryBuilder::::new( + "SELECT o.object_type, o.id, o.name, o.workspace, o.payload, \ + o.created_at_ms, o.updated_at_ms, o.labels, o.resource_version \ + FROM objects o WHERE o.object_type = ", + ); + sql.push_bind(object_type); + + match query { + ObjectListQuery::Workspace(workspace) => { + sql.push(" AND o.workspace = ").push_bind(workspace); + } + ObjectListQuery::AllWorkspaces => {} + ObjectListQuery::Scope(scope) => { + sql.push(" AND o.scope = ").push_bind(scope); + } + ObjectListQuery::WorkspaceSelector { + workspace, + label_selector, + } => { + sql.push(" AND o.workspace = ").push_bind(workspace); + push_label_selector(&mut sql, label_selector)?; + } + ObjectListQuery::AllWorkspacesSelector(label_selector) => { + push_label_selector(&mut sql, label_selector)?; + } + ObjectListQuery::Membership { + member_type, + member_name, + } => { + sql.push( + " AND o.workspace = '' AND EXISTS (SELECT 1 FROM objects m \ + WHERE m.object_type = ", + ) + .push_bind(member_type) + .push(" AND m.workspace = o.name AND m.name = ") + .push_bind(member_name) + .push(")"); + } + ObjectListQuery::MembershipSelector { + member_type, + member_name, + label_selector, + } => { + sql.push( + " AND o.workspace = '' AND EXISTS (SELECT 1 FROM objects m \ + WHERE m.object_type = ", + ) + .push_bind(member_type) + .push(" AND m.workspace = o.name AND m.name = ") + .push_bind(member_name) + .push(")"); + push_label_selector(&mut sql, label_selector)?; + } + } + + if let Some(cursor) = after { + sql.push(" AND (o.created_at_ms, COALESCE(o.name, ''), o.workspace, o.id) > (") + .push_bind(cursor.created_at_ms) + .push(", ") + .push_bind(&cursor.name) + .push(", ") + .push_bind(&cursor.workspace) + .push(", ") + .push_bind(&cursor.id) + .push(")"); + } + sql.push( + " ORDER BY o.created_at_ms ASC, COALESCE(o.name, '') ASC, \ + o.workspace ASC, o.id ASC LIMIT ", + ) + .push_bind(i64::from(limit)); + + let rows = sql + .build() + .fetch_all(&self.pool) + .await + .map_err(|e| map_db_error(&e))?; + Ok(rows.into_iter().map(row_to_object_record).collect()) + } + pub async fn list_with_membership( &self, object_type: &str, @@ -884,27 +993,24 @@ LIMIT ?3 OFFSET ?4 limit: u32, offset: u32, ) -> PersistenceResult> { - use super::parse_label_selector; - - let required_labels = parse_label_selector(label_selector)?; - let all_records = self.list(object_type, workspace, u32::MAX, 0).await?; - - let filtered: Vec = all_records - .into_iter() - .filter(|record| { - let labels_json = record.labels.as_deref().unwrap_or("{}"); - let labels: std::collections::HashMap = - serde_json::from_str(labels_json).unwrap_or_default(); - - required_labels - .iter() - .all(|(key, value)| labels.get(key).is_some_and(|v| v == value)) - }) - .skip(offset as usize) - .take(limit as usize) - .collect(); - - Ok(filtered) + let mut sql = QueryBuilder::::new( + r#"SELECT o."object_type", o."id", o."name", o."workspace", o."payload", o."created_at_ms", o."updated_at_ms", o."labels", o."resource_version" +FROM "objects" o +WHERE o."object_type" = "#, + ); + sql.push_bind(object_type).push(" AND o.\"workspace\" = "); + sql.push_bind(workspace); + push_label_selector(&mut sql, label_selector)?; + sql.push(" ORDER BY o.\"created_at_ms\" ASC, o.\"name\" ASC LIMIT ") + .push_bind(i64::from(limit)) + .push(" OFFSET ") + .push_bind(i64::from(offset)); + let rows = sql + .build() + .fetch_all(&self.pool) + .await + .map_err(|e| map_db_error(&e))?; + Ok(rows.into_iter().map(row_to_object_record).collect()) } pub async fn list_all_with_selector( @@ -914,27 +1020,23 @@ LIMIT ?3 OFFSET ?4 limit: u32, offset: u32, ) -> PersistenceResult> { - use super::parse_label_selector; - - let required_labels = parse_label_selector(label_selector)?; - let all_records = self.list_by_type(object_type, u32::MAX, 0).await?; - - let filtered: Vec = all_records - .into_iter() - .filter(|record| { - let labels_json = record.labels.as_deref().unwrap_or("{}"); - let labels: std::collections::HashMap = - serde_json::from_str(labels_json).unwrap_or_default(); - - required_labels - .iter() - .all(|(key, value)| labels.get(key).is_some_and(|v| v == value)) - }) - .skip(offset as usize) - .take(limit as usize) - .collect(); - - Ok(filtered) + let mut sql = QueryBuilder::::new( + r#"SELECT o."object_type", o."id", o."name", o."workspace", o."payload", o."created_at_ms", o."updated_at_ms", o."labels", o."resource_version" +FROM "objects" o +WHERE o."object_type" = "#, + ); + sql.push_bind(object_type); + push_label_selector(&mut sql, label_selector)?; + sql.push(" ORDER BY o.\"created_at_ms\" ASC, o.\"name\" ASC LIMIT ") + .push_bind(i64::from(limit)) + .push(" OFFSET ") + .push_bind(i64::from(offset)); + let rows = sql + .build() + .fetch_all(&self.pool) + .await + .map_err(|e| map_db_error(&e))?; + Ok(rows.into_iter().map(row_to_object_record).collect()) } pub async fn put_policy_revision( &self, @@ -1176,6 +1278,32 @@ LIMIT ?3 OFFSET ?4 rows.into_iter().map(row_to_policy_record).collect() } + pub async fn list_policies_before( + &self, + sandbox_id: &str, + limit: u32, + before_version: Option, + ) -> PersistenceResult> { + let rows = sqlx::query( + r#" +SELECT "id", "scope", "version", "status", "payload", "created_at_ms" +FROM "objects" +WHERE "object_type" = ?1 AND "scope" = ?2 AND (?3 IS NULL OR "version" < ?3) +ORDER BY "version" DESC +LIMIT ?4 +"#, + ) + .bind(POLICY_OBJECT_TYPE) + .bind(sandbox_id) + .bind(before_version) + .bind(i64::from(limit)) + .fetch_all(&self.pool) + .await + .map_err(|e| map_db_error(&e))?; + + rows.into_iter().map(row_to_policy_record).collect() + } + pub async fn update_policy_status( &self, sandbox_id: &str, diff --git a/crates/openshell-server/src/persistence/tests.rs b/crates/openshell-server/src/persistence/tests.rs index 169fa81538..a292926270 100644 --- a/crates/openshell-server/src/persistence/tests.rs +++ b/crates/openshell-server/src/persistence/tests.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use super::{ObjectType, PersistenceError, Store, generate_name, test_store}; +use super::{ObjectListQuery, ObjectType, PersistenceError, Store, generate_name, test_store}; use crate::policy_store::{AtomicPolicyRevisionWrite, PolicyStoreExt}; use openshell_core::proto::datamodel::v1::ObjectMeta as ProtoObjectMeta; use openshell_core::proto::{ObjectForTest, Sandbox, SandboxPolicy, SandboxSpec}; @@ -124,6 +124,32 @@ async fn sqlite_put_get_round_trip() { assert_eq!(record.payload, b"payload"); } +#[tokio::test] +async fn collect_records_exhausts_multiple_keyset_pages_exactly_once() { + let store = test_store().await; + let expected = 1005_usize; + for index in 0..expected { + let id = format!("collect-{index:04}"); + let name = format!("sandbox-{index:04}"); + store + .put("sandbox", &id, &name, "collect-test", b"payload", None) + .await + .unwrap(); + } + + let records = store + .collect_records("sandbox", ObjectListQuery::Workspace("collect-test")) + .await + .unwrap(); + let ids = records + .iter() + .map(|record| record.id.as_str()) + .collect::>(); + + assert_eq!(records.len(), expected); + assert_eq!(ids.len(), expected, "every record is visited exactly once"); +} + #[tokio::test] async fn sqlite_connect_runs_embedded_migrations() { let store = test_store().await; @@ -182,6 +208,22 @@ fn embedded_migrators_include_inference_route_removal() { } } +#[test] +fn embedded_migrators_include_pagination_indexes() { + for (backend, migration) in [ + ("sqlite", super::sqlite::embedded_migration_sql(8)), + ("postgres", super::postgres::embedded_migration_sql(8)), + ] { + let sql = + migration.unwrap_or_else(|| panic!("{backend} migrator is missing migration 008")); + assert!( + sql.contains("objects_workspace_page_idx") + && sql.contains("objects_all_workspaces_page_idx"), + "{backend} migration 008 must add both keyset pagination indexes" + ); + } +} + #[tokio::test] async fn sqlite_in_memory_store_survives_pool_connection_replacement() { for url in ["sqlite::memory:", "sqlite://?mode=memory"] { diff --git a/crates/openshell-server/src/policy_store.rs b/crates/openshell-server/src/policy_store.rs index 8b1b6df335..8538e72205 100644 --- a/crates/openshell-server/src/policy_store.rs +++ b/crates/openshell-server/src/policy_store.rs @@ -125,6 +125,7 @@ pub trait PolicyStoreExt { version: i64, ) -> PersistenceResult>; + #[allow(dead_code)] async fn list_policies( &self, sandbox_id: &str, @@ -132,6 +133,13 @@ pub trait PolicyStoreExt { offset: u32, ) -> PersistenceResult>; + async fn list_policies_before( + &self, + sandbox_id: &str, + limit: u32, + before_version: Option, + ) -> PersistenceResult>; + async fn update_policy_status( &self, sandbox_id: &str, @@ -282,6 +290,26 @@ impl PolicyStoreExt for Store { } } + async fn list_policies_before( + &self, + sandbox_id: &str, + limit: u32, + before_version: Option, + ) -> PersistenceResult> { + match self { + Self::Postgres(store) => { + store + .list_policies_before(sandbox_id, limit, before_version) + .await + } + Self::Sqlite(store) => { + store + .list_policies_before(sandbox_id, limit, before_version) + .await + } + } + } + async fn update_policy_status( &self, sandbox_id: &str, diff --git a/crates/openshell-server/src/provider_profile_sources.rs b/crates/openshell-server/src/provider_profile_sources.rs index cea7faf31b..a62d9dc201 100644 --- a/crates/openshell-server/src/provider_profile_sources.rs +++ b/crates/openshell-server/src/provider_profile_sources.rs @@ -23,7 +23,7 @@ use sha2::{Digest, Sha256}; use tonic::Status; use tracing::debug; -use crate::persistence::{ObjectType, Store}; +use crate::persistence::{ObjectListQuery, ObjectType, Store}; use crate::storage_proto::StoredProviderProfile; const BUILTIN_SOURCE_ID: &str = "builtin"; @@ -130,8 +130,10 @@ impl ProviderProfileSource for UserProviderProfileSource { let mut hasher = Sha256::new(); hasher.update(b"openshell-user-provider-profile-source-v1"); - let platform_stored: Vec = - store.list_messages("", 10_000, 0).await.map_err(|e| { + let platform_stored: Vec = store + .collect_messages(ObjectListQuery::Workspace("")) + .await + .map_err(|e| { Status::internal(format!("list platform provider profiles failed: {e}")) })?; for stored in platform_stored { @@ -150,7 +152,7 @@ impl ProviderProfileSource for UserProviderProfileSource { if !workspace.is_empty() { let ws_stored: Vec = store - .list_messages(workspace, 10_000, 0) + .collect_messages(ObjectListQuery::Workspace(workspace)) .await .map_err(|e| { Status::internal(format!("list workspace provider profiles failed: {e}")) diff --git a/crates/openshell-server/src/provider_refresh.rs b/crates/openshell-server/src/provider_refresh.rs index e8386abcb8..f322be0dd0 100644 --- a/crates/openshell-server/src/provider_refresh.rs +++ b/crates/openshell-server/src/provider_refresh.rs @@ -6,13 +6,15 @@ #![allow(clippy::result_large_err)] use crate::credentials::RefreshMaterialScope; -use crate::persistence::{ObjectType, PersistenceError, Store, WriteCondition, current_time_ms}; +use crate::persistence::{ + ObjectListQuery, ObjectType, PersistenceError, Store, WriteCondition, current_time_ms, +}; use openshell_core::ObjectWorkspace; use openshell_core::proto::{ CredentialHandle, Provider, ProviderCredentialRefreshRecoveryAction, ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, }; -use openshell_core::{ObjectId, ObjectName, SetResourceVersion}; +use openshell_core::{ObjectId, ObjectName}; use prost::Message; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -26,7 +28,6 @@ const DEFAULT_REFRESH_BEFORE_SECONDS: i64 = 300; const DEFAULT_MAX_LIFETIME_SECONDS: i64 = 3600; const REFRESH_ERROR_RETRY_SECONDS: i64 = 60; const REFRESH_CONFIGURATION_RETRY_SECONDS: i64 = 60 * 60; -const REFRESH_WORKER_PAGE_SIZE: u32 = 1000; const MAX_OAUTH_ERROR_RESPONSE_BYTES: usize = 8 * 1024; pub fn refresh_material_scope( @@ -171,51 +172,19 @@ pub async fn list_refresh_states_for_provider( store: &Store, provider_id: &str, ) -> Result, Status> { - let records = store - .list_by_scope( - StoredProviderCredentialRefreshState::object_type(), - provider_id, - 1000, - 0, - ) + store + .collect_messages(ObjectListQuery::Scope(provider_id)) .await - .map_err(|e| Status::internal(format!("list provider refresh states failed: {e}")))?; - - let mut states = Vec::with_capacity(records.len()); - for record in records { - let mut state = StoredProviderCredentialRefreshState::decode(record.payload.as_slice()) - .map_err(|e| Status::internal(format!("decode provider refresh state failed: {e}")))?; - state.set_resource_version(record.resource_version); - states.push(state); - } - Ok(states) + .map_err(|e| Status::internal(format!("list provider refresh states failed: {e}"))) } pub async fn list_all_refresh_states( store: &Store, ) -> Result, Status> { - let mut states = Vec::new(); - let mut offset = 0; - loop { - let page = store - .list_all_messages::( - REFRESH_WORKER_PAGE_SIZE, - offset, - ) - .await - .map_err(|e| Status::internal(format!("list provider refresh states failed: {e}")))?; - if page.is_empty() { - break; - } - offset = offset - .checked_add( - u32::try_from(page.len()) - .map_err(|_| Status::internal("provider refresh page size exceeded u32"))?, - ) - .ok_or_else(|| Status::internal("provider refresh pagination offset overflow"))?; - states.extend(page); - } - Ok(states) + store + .collect_messages(ObjectListQuery::AllWorkspaces) + .await + .map_err(|e| Status::internal(format!("list provider refresh states failed: {e}"))) } pub async fn get_refresh_state( diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index cd5e065dee..8f7c55914f 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -119,7 +119,7 @@ mod tests { const STORAGE_V1_SCHEMA_SHA256: &str = "79c72615d957fc0653c672f61998bf7d8d21b757bc05d07b3fff92bd70fc8f52"; const PUBLIC_RPC_SCHEMA_SHA256: &str = - "c95ae90962c10fb28747db2b645adf4044562a3d208d84dfe4699d677e4364ee"; + "0f14943574349d02bdc61076c8c5a59a98b627325564ef1a6d21d7941825dc46"; const DURABLE_SCHEMA_SHA256: &str = "920a5243dfb37ce709f0f562a47d17791a5ede90fd7f662ed01542abd60a0dfb"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = diff --git a/crates/openshell-tui/Cargo.toml b/crates/openshell-tui/Cargo.toml index c1c64d83cb..bc79d114b2 100644 --- a/crates/openshell-tui/Cargo.toml +++ b/crates/openshell-tui/Cargo.toml @@ -17,6 +17,7 @@ openshell-policy = { path = "../openshell-policy" } openshell-providers = { path = "../openshell-providers" } base64 = { workspace = true } +futures = { workspace = true } ratatui = { workspace = true } crossterm = { workspace = true } terminal-colorsaurus = { workspace = true } diff --git a/crates/openshell-tui/src/app.rs b/crates/openshell-tui/src/app.rs index cf7464fcd8..64d9bd5806 100644 --- a/crates/openshell-tui/src/app.rs +++ b/crates/openshell-tui/src/app.rs @@ -599,6 +599,14 @@ pub struct App { pub all_workspaces: bool, pub workspace_names: Vec, pub pending_workspace_refresh: bool, + /// Monotonic identity for the active background list refresh. + pub list_refresh_generation: u64, + /// Active list refresh task. New ticks do not overlap this task. + pub list_refresh_handle: Option>, + /// Monotonic identity for the active draft-count refresh. + pub draft_counts_refresh_generation: u64, + /// Active draft-count refresh task. New ticks do not overlap this task. + pub draft_counts_refresh_handle: Option>, // Provider list pub provider_profiles: Vec, @@ -981,6 +989,10 @@ impl App { all_workspaces: false, workspace_names: Vec::new(), pending_workspace_refresh: false, + list_refresh_generation: 0, + list_refresh_handle: None, + draft_counts_refresh_generation: 0, + draft_counts_refresh_handle: None, provider_profiles: Vec::new(), provider_entries: Vec::new(), provider_names: Vec::new(), @@ -3479,6 +3491,23 @@ impl App { } } + /// Cancel any in-flight collection refresh and invalidate queued results. + pub fn cancel_list_refresh(&mut self) { + if let Some(handle) = self.list_refresh_handle.take() { + handle.abort(); + } + self.list_refresh_generation = self.list_refresh_generation.wrapping_add(1); + self.cancel_draft_counts_refresh(); + } + + /// Cancel any in-flight draft-count refresh and invalidate queued results. + pub fn cancel_draft_counts_refresh(&mut self) { + if let Some(handle) = self.draft_counts_refresh_handle.take() { + handle.abort(); + } + self.draft_counts_refresh_generation = self.draft_counts_refresh_generation.wrapping_add(1); + } + /// Stop the animation ticker if running. pub fn stop_anim(&mut self) { if let Some(h) = self.anim_handle.take() { @@ -3490,6 +3519,7 @@ impl App { pub fn reset_sandbox_state(&mut self) { self.stop_anim(); self.cancel_log_stream(); + self.cancel_list_refresh(); self.sandbox_ids.clear(); self.sandbox_names.clear(); self.sandbox_phases.clear(); diff --git a/crates/openshell-tui/src/event.rs b/crates/openshell-tui/src/event.rs index 151589e8c5..f24ab54ed7 100644 --- a/crates/openshell-tui/src/event.rs +++ b/crates/openshell-tui/src/event.rs @@ -20,6 +20,10 @@ pub enum Event { Resize(u16, u16), /// A batch of log lines from the streaming log task. LogLines(Vec), + /// Completed workspace/provider/sandbox list refresh from a background task. + ListRefreshCompleted(crate::ListRefreshResult), + /// Completed per-sandbox draft-count refresh from a background task. + DraftCountsRefreshCompleted(crate::DraftCountsRefreshResult), /// Result of a create sandbox request: `Ok((name, workspace))` or `Err(message)`. CreateResult(Result<(String, String), String>), /// Result of creating a provider on the gateway: `Ok(name)` or `Err(message)`. diff --git a/crates/openshell-tui/src/lib.rs b/crates/openshell-tui/src/lib.rs index 2ab19d89d7..55fbcaff87 100644 --- a/crates/openshell-tui/src/lib.rs +++ b/crates/openshell-tui/src/lib.rs @@ -18,6 +18,7 @@ use crossterm::execute; use crossterm::terminal::{ EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode, }; +use futures::{StreamExt, stream}; use miette::{IntoDiagnostic, Result}; use openshell_bootstrap::list_gateways_with_source; use openshell_core::auth::EdgeAuthInterceptor; @@ -28,6 +29,7 @@ use ratatui::Terminal; use ratatui::backend::CrosstermBackend; use tokio::sync::mpsc; use tonic::Code; +use tonic::service::interceptor::InterceptedService; use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint, Identity}; use app::{App, Focus, GatewayEntry, LogLine, Screen}; @@ -36,9 +38,39 @@ use event::{Event, EventHandler}; /// Duration to show the splash screen before auto-dismissing. const SPLASH_DURATION: Duration = Duration::from_secs(3); const PROVIDER_PROFILE_SCOPE_WORKSPACE: &str = "workspace"; -const PROVIDER_PROFILE_PAGE_SIZE: u32 = 100; +const PROVIDER_PROFILE_PAGE_SIZE: i32 = 100; +const DRAFT_COUNT_REFRESH_CONCURRENCY: usize = 16; type ProviderProfileCache = HashMap<(String, String), openshell_core::proto::ProviderProfile>; +type TuiClient = OpenShellClient>; + +#[derive(Debug)] +pub(crate) struct ListRefreshResult { + generation: u64, + gateway_name: String, + workspace: String, + all_workspaces: bool, + workspaces: Result, String>, + providers: Result, + sandboxes: Result, String>, +} + +#[derive(Debug)] +pub(crate) struct DraftCountsRefreshResult { + generation: u64, + gateway_name: String, + workspace: String, + all_workspaces: bool, + sandboxes: Vec<(String, String)>, + counts: Vec, +} + +#[derive(Debug)] +struct ProviderListRefresh { + providers: Vec, + profiles: ProviderProfileCache, + workspace_profiles: Vec, +} fn named_workspace_scope(workspace: impl Into) -> openshell_core::proto::WorkspaceSelector { openshell_core::proto::workspace_selector(workspace) @@ -96,7 +128,9 @@ pub async fn run( let mut events = EventHandler::new(Duration::from_secs(2)); refresh_gateway_list(&mut app); - refresh_data(&mut app).await; + refresh_health(&mut app).await; + refresh_global_settings(&mut app).await; + spawn_list_refresh(&mut app, events.sender()); while app.running { terminal @@ -108,7 +142,7 @@ pub async fn run( app.handle_key(key); // Handle async actions triggered by key presses. if app.pending_gateway_switch.is_some() { - handle_gateway_switch(&mut app).await; + handle_gateway_switch(&mut app, events.sender()).await; } if app.pending_log_fetch { app.pending_log_fetch = false; @@ -116,7 +150,7 @@ pub async fn run( } if app.pending_sandbox_delete { app.pending_sandbox_delete = false; - handle_sandbox_delete(&mut app).await; + handle_sandbox_delete(&mut app, events.sender()).await; } if app.pending_create_sandbox { app.pending_create_sandbox = false; @@ -183,10 +217,17 @@ pub async fn run( } if app.pending_workspace_refresh { app.pending_workspace_refresh = false; - refresh_providers(&mut app).await; - refresh_sandboxes(&mut app).await; + app.cancel_list_refresh(); + spawn_list_refresh(&mut app, events.sender()); } } + Some(Event::ListRefreshCompleted(result)) => { + apply_list_refresh(&mut app, result); + spawn_sandbox_draft_counts_refresh(&mut app, events.sender()); + } + Some(Event::DraftCountsRefreshCompleted(result)) => { + apply_sandbox_draft_counts_refresh(&mut app, result); + } Some(Event::LogLines(lines)) => { app.sandbox_log_lines.extend(lines); if app.log_autoscroll { @@ -224,7 +265,8 @@ pub async fn run( Ok(name) => { app.update_provider_form = None; app.status_text = format!("Updated provider: {name}"); - refresh_providers(&mut app).await; + app.cancel_list_refresh(); + spawn_list_refresh(&mut app, events.sender()); } Err(msg) => { if let Some(form) = app.update_provider_form.as_mut() { @@ -235,7 +277,8 @@ pub async fn run( Some(Event::ProviderDeleteResult(result)) => match result { Ok(true) => { app.status_text = "Provider deleted.".to_string(); - refresh_providers(&mut app).await; + app.cancel_list_refresh(); + spawn_list_refresh(&mut app, events.sender()); } Ok(false) => { app.status_text = "Provider not found.".to_string(); @@ -255,7 +298,8 @@ pub async fn run( } // Refresh draft chunks + counts immediately after any action. refresh_draft_chunks(&mut app).await; - refresh_sandbox_draft_counts(&mut app).await; + app.cancel_draft_counts_refresh(); + spawn_sandbox_draft_counts_refresh(&mut app, events.sender()); } Some(Event::GlobalSettingsFetched(result)) => match result { Ok((settings, revision)) => { @@ -340,10 +384,12 @@ pub async fn run( } refresh_gateway_list(&mut app); - refresh_data(&mut app).await; + refresh_health(&mut app).await; + refresh_global_settings(&mut app).await; + spawn_list_refresh(&mut app, events.sender()); // Refresh per-sandbox draft counts for badges (dashboard + detail). - refresh_sandbox_draft_counts(&mut app).await; + spawn_sandbox_draft_counts_refresh(&mut app, events.sender()); // Auto-refresh sandbox detail (policy, settings, drafts) on // every tick when viewing a sandbox. The gRPC call is @@ -386,7 +432,6 @@ pub async fn run( format!(" (forwarding port(s) {list})") }; app.status_text = format!("Created sandbox: {name}{port_info}"); - refresh_sandboxes(&mut app).await; // If a command was specified, suspend TUI and exec it. if !command.is_empty() { @@ -400,6 +445,8 @@ pub async fn run( ) .await?; } + app.cancel_list_refresh(); + spawn_list_refresh(&mut app, events.sender()); } Some(Err(msg)) => { if let Some(form) = app.create_form.as_mut() { @@ -431,7 +478,8 @@ pub async fn run( Some(Ok(name)) => { app.create_provider_form = None; app.status_text = format!("Created provider: {name}"); - refresh_providers(&mut app).await; + app.cancel_list_refresh(); + spawn_list_refresh(&mut app, events.sender()); } Some(Err(msg)) => { if let Some(form) = app.create_provider_form.as_mut() { @@ -499,7 +547,7 @@ fn refresh_gateway_list(app: &mut App) { } /// Handle a pending gateway switch requested by the user. -async fn handle_gateway_switch(app: &mut App) { +async fn handle_gateway_switch(app: &mut App, tx: mpsc::UnboundedSender) { let Some(name) = app.pending_gateway_switch.take() else { return; }; @@ -516,7 +564,9 @@ async fn handle_gateway_switch(app: &mut App) { app.gateway_name = name; app.endpoint = endpoint; app.reset_sandbox_state(); - refresh_data(app).await; + refresh_health(app).await; + refresh_global_settings(app).await; + spawn_list_refresh(app, tx); } Err(e) => { app.status_text = format!("switch failed: {e}"); @@ -747,7 +797,7 @@ fn proto_to_log_line(log: openshell_core::proto::SandboxLogLine) -> LogLine { } /// Delete the currently selected sandbox. -async fn handle_sandbox_delete(app: &mut App) { +async fn handle_sandbox_delete(app: &mut App, tx: mpsc::UnboundedSender) { let sandbox_name = match app.selected_sandbox_name() { Some(n) => n.to_string(), None => return, @@ -773,7 +823,8 @@ async fn handle_sandbox_delete(app: &mut App) { app.cancel_log_stream(); app.screen = Screen::Dashboard; app.focus = Focus::Sandboxes; - refresh_sandboxes(app).await; + app.cancel_list_refresh(); + spawn_list_refresh(app, tx); } Err(e) => { app.status_text = format!("delete failed: {}", e.message()); @@ -977,6 +1028,7 @@ async fn handle_shell_connect( // Step 6: Cancel log stream and pause event handler before suspending. app.cancel_log_stream(); + app.cancel_list_refresh(); events.pause(); // Wait for the reader task to finish its current poll cycle (tick_rate = 2s max). tokio::time::sleep(Duration::from_millis(100)).await; @@ -1021,6 +1073,7 @@ async fn handle_shell_connect( .into_diagnostic()?; events.discard_pending(); events.resume(); + spawn_list_refresh(app, events.sender()); Ok(()) } @@ -1140,6 +1193,7 @@ async fn handle_exec_command( // Step 4: Suspend TUI. app.cancel_log_stream(); + app.cancel_list_refresh(); events.pause(); tokio::time::sleep(Duration::from_millis(100)).await; @@ -1179,6 +1233,7 @@ async fn handle_exec_command( terminal.clear().into_diagnostic()?; events.discard_pending(); events.resume(); + spawn_list_refresh(app, events.sender()); Ok(()) } @@ -1505,9 +1560,7 @@ fn spawn_create_sandbox(app: &mut App, tx: mpsc::UnboundedSender) { /// This is called from within the create-sandbox task so the pacman animation /// keeps running while forwards are being established. async fn start_port_forwards( - client: &mut OpenShellClient< - tonic::service::interceptor::InterceptedService, - >, + client: &mut TuiClient, endpoint: &str, gateway_name: &str, sandbox_name: &str, @@ -2037,34 +2090,98 @@ fn format_draft_approve_all_result( // Data refresh // --------------------------------------------------------------------------- -async fn refresh_data(app: &mut App) { - refresh_health(app).await; - refresh_global_settings(app).await; - refresh_workspaces(app).await; - refresh_providers(app).await; - refresh_sandboxes(app).await; +fn spawn_list_refresh(app: &mut App, tx: mpsc::UnboundedSender) { + if let Some(handle) = app.list_refresh_handle.as_ref() { + if !handle.is_finished() { + return; + } + app.list_refresh_handle.take(); + } + + app.list_refresh_generation = app.list_refresh_generation.wrapping_add(1); + let generation = app.list_refresh_generation; + let gateway_name = app.gateway_name.clone(); + let refresh_workspace = app.current_workspace.clone(); + let all_workspaces = app.all_workspaces; + let client = app.client.clone(); + let handle = tokio::spawn(async move { + let (workspaces, providers, sandboxes) = tokio::join!( + fetch_workspaces(client.clone()), + fetch_providers(client.clone(), refresh_workspace.clone(), all_workspaces), + fetch_sandboxes(client, refresh_workspace.clone(), all_workspaces), + ); + let _ = tx.send(Event::ListRefreshCompleted(ListRefreshResult { + generation, + gateway_name, + workspace: refresh_workspace, + all_workspaces, + workspaces, + providers, + sandboxes, + })); + }); + app.list_refresh_handle = Some(handle); } -async fn refresh_workspaces(app: &mut App) { - let req = openshell_core::proto::ListWorkspacesRequest { - limit: 100, - offset: 0, - label_selector: String::new(), - }; - match tokio::time::timeout(Duration::from_secs(5), app.client.list_workspaces(req)).await { - Ok(Ok(resp)) => { - app.workspace_names = resp - .into_inner() - .workspaces - .into_iter() - .filter_map(|w| w.metadata.map(|m| m.name)) - .collect(); - } - Ok(Err(e)) => { - app.status_text = format!("failed to list workspaces: {}", e.message()); - } - Err(_) => { - app.status_text = "list workspaces timed out".to_string(); +fn apply_list_refresh(app: &mut App, result: ListRefreshResult) { + if result.generation != app.list_refresh_generation { + return; + } + app.list_refresh_handle.take(); + if result.gateway_name != app.gateway_name { + return; + } + if result.workspace != app.current_workspace { + return; + } + if result.all_workspaces != app.all_workspaces { + return; + } + app.cancel_draft_counts_refresh(); + + match result.workspaces { + Ok(workspaces) => app.workspace_names = workspaces, + Err(message) => app.status_text = message, + } + match result.providers { + Ok(providers) => apply_provider_refresh(app, providers), + Err(message) => app.status_text = message, + } + match result.sandboxes { + Ok(sandboxes) => apply_sandbox_refresh(app, sandboxes), + Err(message) => app.status_text = message, + } +} + +async fn fetch_workspaces(mut client: TuiClient) -> std::result::Result, String> { + let mut workspace_names = Vec::new(); + let mut page_token = String::new(); + loop { + let req = openshell_core::proto::ListWorkspacesRequest { + page_size: 100, + page_token, + label_selector: String::new(), + }; + match tokio::time::timeout(Duration::from_secs(5), client.list_workspaces(req)).await { + Ok(Ok(resp)) => { + let response = resp.into_inner(); + workspace_names.extend( + response + .workspaces + .into_iter() + .filter_map(|workspace| workspace.metadata.map(|metadata| metadata.name)), + ); + if response.next_page_token.is_empty() { + return Ok(workspace_names); + } + page_token = response.next_page_token; + } + Ok(Err(e)) => { + return Err(format!("failed to list workspaces: {}", e.message())); + } + Err(_) => { + return Err("list workspaces timed out".to_string()); + } } } } @@ -2111,28 +2228,36 @@ fn cached_provider_profile( .cloned() } -async fn refresh_providers(app: &mut App) { - let req = openshell_core::proto::ListProvidersRequest { - limit: 100, - offset: 0, - workspace_scope: Some(list_workspace_scope( - &app.current_workspace, - app.all_workspaces, - )), - }; - let response = - match tokio::time::timeout(Duration::from_secs(5), app.client.list_providers(req)).await { - Ok(Ok(resp)) => resp.into_inner(), +async fn fetch_providers( + mut client: TuiClient, + current_workspace: String, + all_workspaces: bool, +) -> std::result::Result { + let mut providers = Vec::new(); + let mut page_token = String::new(); + loop { + let req = openshell_core::proto::ListProvidersRequest { + page_size: 100, + page_token, + workspace_scope: Some(list_workspace_scope(¤t_workspace, all_workspaces)), + }; + match tokio::time::timeout(Duration::from_secs(5), client.list_providers(req)).await { + Ok(Ok(resp)) => { + let response = resp.into_inner(); + providers.extend(response.providers); + if response.next_page_token.is_empty() { + break; + } + page_token = response.next_page_token; + } Ok(Err(e)) => { - app.status_text = format!("failed to list providers: {}", e.message()); - return; + return Err(format!("failed to list providers: {}", e.message())); } Err(_) => { - app.status_text = "list providers timed out".to_string(); - return; + return Err("list providers timed out".to_string()); } - }; - let providers = response.providers; + } + } let mut workspaces: std::collections::HashSet = providers .iter() @@ -2141,21 +2266,21 @@ async fn refresh_providers(app: &mut App) { // turn that missing context into a platform-scoped profile request. .filter(|workspace| !workspace.is_empty()) .collect(); - if !app.all_workspaces { - workspaces.insert(app.current_workspace.clone()); + if !all_workspaces { + workspaces.insert(current_workspace.clone()); } let mut profiles = HashMap::new(); - app.provider_profiles.clear(); + let mut workspace_profiles = Vec::new(); for ws in &workspaces { - let client = app.client.clone(); + let client = client.clone(); let workspace = ws.clone(); - if let Some(listed) = collect_provider_profile_pages(move |offset| { + if let Some(listed) = collect_provider_profile_pages(move |page_token| { let mut client = client.clone(); let workspace = workspace.clone(); async move { let req = openshell_core::proto::ListProviderProfilesRequest { - limit: PROVIDER_PROFILE_PAGE_SIZE, - offset, + page_size: PROVIDER_PROFILE_PAGE_SIZE, + page_token, workspace, }; match tokio::time::timeout( @@ -2164,21 +2289,39 @@ async fn refresh_providers(app: &mut App) { ) .await { - Ok(Ok(response)) => Some(response.into_inner().profiles), + Ok(Ok(response)) => { + let response = response.into_inner(); + Some((response.profiles, response.next_page_token)) + } _ => None, } } }) .await { - if !app.all_workspaces && ws == &app.current_workspace { - app.provider_profiles.clone_from(&listed); + if !all_workspaces && ws == ¤t_workspace { + workspace_profiles.clone_from(&listed); } for profile in listed { cache_provider_profile(&mut profiles, ws, profile); } } } + + Ok(ProviderListRefresh { + providers, + profiles, + workspace_profiles, + }) +} + +fn apply_provider_refresh(app: &mut App, refresh: ProviderListRefresh) { + let ProviderListRefresh { + providers, + profiles, + workspace_profiles, + } = refresh; + app.provider_profiles = workspace_profiles; app.sync_create_provider_types(); app.provider_count = providers.len(); @@ -2218,19 +2361,18 @@ async fn collect_provider_profile_pages( mut fetch_page: F, ) -> Option> where - F: FnMut(u32) -> Fut, - Fut: Future>>, + F: FnMut(String) -> Fut, + Fut: Future, String)>>, { let mut profiles = Vec::new(); - let mut offset = 0; + let mut page_token = String::new(); loop { - let page = fetch_page(offset).await?; - let page_len = page.len(); + let (page, next_page_token) = fetch_page(page_token).await?; profiles.extend(page); - if page_len < PROVIDER_PROFILE_PAGE_SIZE as usize { + if next_page_token.is_empty() { return Some(profiles); } - offset = offset.saturating_add(PROVIDER_PROFILE_PAGE_SIZE); + page_token = next_page_token; } } @@ -2263,8 +2405,8 @@ async fn refresh_global_settings(app: &mut App) { // Check for an active global policy only while the caller can read it. let policy_req = openshell_core::proto::ListSandboxPoliciesRequest { name: String::new(), - limit: 1, - offset: 0, + page_size: 1, + page_token: String::new(), global: true, workspace_scope: None, }; @@ -2523,113 +2665,126 @@ async fn refresh_health(app: &mut App) { } } -async fn refresh_sandboxes(app: &mut App) { - let req = openshell_core::proto::ListSandboxesRequest { - limit: 100, - offset: 0, - label_selector: String::new(), - workspace_scope: Some(list_workspace_scope( - &app.current_workspace, - app.all_workspaces, - )), - }; - let result = tokio::time::timeout(Duration::from_secs(5), app.client.list_sandboxes(req)).await; - match result { - Ok(Err(e)) => { - app.status_text = format!("failed to list sandboxes: {}", e.message()); - } - Err(_) => { - app.status_text = "list sandboxes timed out".to_string(); - } - Ok(Ok(resp)) => { - let sandboxes = resp.into_inner().sandboxes; - app.sandbox_count = sandboxes.len(); - app.sandbox_ids = sandboxes - .iter() - .map(|s| s.object_id().to_string()) - .collect(); - app.sandbox_names = sandboxes - .iter() - .map(|s| s.object_name().to_string()) - .collect(); - app.sandbox_phases = sandboxes.iter().map(|s| phase_label(s.phase())).collect(); - app.sandbox_images = sandboxes - .iter() - .map(|s| { - s.spec - .as_ref() - .and_then(|spec| spec.template.as_ref()) - .map(|t| t.image.as_str()) - .filter(|img| !img.is_empty()) - .unwrap_or("-") - .to_string() - }) - .collect(); - app.sandbox_ages = sandboxes - .iter() - .map(|s| { - s.metadata - .as_ref() - .map_or_else(|| "?".to_string(), |m| format_age(m.created_at_ms)) - }) - .collect(); - app.sandbox_created = sandboxes - .iter() - .map(|s| { - s.metadata - .as_ref() - .map_or_else(|| "?".to_string(), |m| format_timestamp(m.created_at_ms)) - }) - .collect(); - - app.sandbox_policy_versions = sandboxes - .iter() - .map(openshell_core::proto::Sandbox::current_policy_version) - .collect(); - - // Build NOTES column from active port forwards. - let forwards = openshell_core::forward::list_forwards().unwrap_or_default(); - app.sandbox_notes = sandboxes - .iter() - .map(|s| { - let name = s.object_name(); - openshell_core::forward::build_sandbox_notes(name, &forwards) - }) - .collect(); - - // Build LABELS column from metadata. - app.sandbox_labels = sandboxes - .iter() - .map(|s| { - s.object_labels() - .as_ref() - .map(app::format_labels) - .unwrap_or_default() - }) - .collect(); - - app.sandbox_annotations = sandboxes - .iter() - .map(|s| { - s.metadata - .as_ref() - .map(|metadata| app::format_annotations(&metadata.annotations)) - .unwrap_or_default() - }) - .collect(); - - app.sandbox_workspaces = sandboxes - .iter() - .map(|s| s.object_workspace().to_string()) - .collect(); - - if app.sandbox_selected >= app.sandbox_count && app.sandbox_count > 0 { - app.sandbox_selected = app.sandbox_count - 1; +async fn fetch_sandboxes( + mut client: TuiClient, + current_workspace: String, + all_workspaces: bool, +) -> std::result::Result, String> { + let mut page_token = String::new(); + let mut sandboxes = Vec::new(); + loop { + let req = openshell_core::proto::ListSandboxesRequest { + page_size: 100, + page_token, + label_selector: String::new(), + workspace_scope: Some(list_workspace_scope(¤t_workspace, all_workspaces)), + }; + let result = tokio::time::timeout(Duration::from_secs(5), client.list_sandboxes(req)).await; + match result { + Ok(Err(e)) => { + return Err(format!("failed to list sandboxes: {}", e.message())); + } + Err(_) => { + return Err("list sandboxes timed out".to_string()); + } + Ok(Ok(resp)) => { + let response = resp.into_inner(); + sandboxes.extend(response.sandboxes); + if response.next_page_token.is_empty() { + return Ok(sandboxes); + } + page_token = response.next_page_token; } } } } +fn apply_sandbox_refresh(app: &mut App, sandboxes: Vec) { + app.sandbox_count = sandboxes.len(); + app.sandbox_ids = sandboxes + .iter() + .map(|s| s.object_id().to_string()) + .collect(); + app.sandbox_names = sandboxes + .iter() + .map(|s| s.object_name().to_string()) + .collect(); + app.sandbox_phases = sandboxes.iter().map(|s| phase_label(s.phase())).collect(); + app.sandbox_images = sandboxes + .iter() + .map(|s| { + s.spec + .as_ref() + .and_then(|spec| spec.template.as_ref()) + .map(|t| t.image.as_str()) + .filter(|img| !img.is_empty()) + .unwrap_or("-") + .to_string() + }) + .collect(); + app.sandbox_ages = sandboxes + .iter() + .map(|s| { + s.metadata + .as_ref() + .map_or_else(|| "?".to_string(), |m| format_age(m.created_at_ms)) + }) + .collect(); + app.sandbox_created = sandboxes + .iter() + .map(|s| { + s.metadata + .as_ref() + .map_or_else(|| "?".to_string(), |m| format_timestamp(m.created_at_ms)) + }) + .collect(); + + app.sandbox_policy_versions = sandboxes + .iter() + .map(openshell_core::proto::Sandbox::current_policy_version) + .collect(); + + // Build NOTES column from active port forwards. + let forwards = openshell_core::forward::list_forwards().unwrap_or_default(); + app.sandbox_notes = sandboxes + .iter() + .map(|s| { + let name = s.object_name(); + openshell_core::forward::build_sandbox_notes(name, &forwards) + }) + .collect(); + + // Build LABELS column from metadata. + app.sandbox_labels = sandboxes + .iter() + .map(|s| { + s.object_labels() + .as_ref() + .map(app::format_labels) + .unwrap_or_default() + }) + .collect(); + + app.sandbox_annotations = sandboxes + .iter() + .map(|s| { + s.metadata + .as_ref() + .map(|metadata| app::format_annotations(&metadata.annotations)) + .unwrap_or_default() + }) + .collect(); + + app.sandbox_workspaces = sandboxes + .iter() + .map(|s| s.object_workspace().to_string()) + .collect(); + + if app.sandbox_selected >= app.sandbox_count && app.sandbox_count > 0 { + app.sandbox_selected = app.sandbox_count - 1; + } +} + /// Re-fetch only the sandbox policy when a version change is detected. /// /// Unlike `fetch_sandbox_detail()`, this skips the `GetSandbox` metadata call @@ -2695,31 +2850,127 @@ async fn refresh_draft_chunks(app: &mut App) { } } -/// Fetch the count of pending draft recommendations for every sandbox. -/// -/// This runs on the Dashboard tick so the sandbox list can show notification -/// badges without entering the sandbox detail view. -async fn refresh_sandbox_draft_counts(app: &mut App) { - let names: Vec = app.sandbox_names.clone(); - let workspaces: Vec = app.sandbox_workspaces.clone(); - let mut counts = vec![0usize; names.len()]; - for (i, name) in names.iter().enumerate() { - let ws = workspaces - .get(i) - .cloned() - .unwrap_or_else(|| app.current_workspace.clone()); - let req = openshell_core::proto::GetDraftPolicyRequest { - name: name.clone(), - status_filter: "pending".to_string(), - workspace_scope: Some(named_workspace_scope(ws)), - }; - if let Ok(Ok(resp)) = - tokio::time::timeout(Duration::from_secs(2), app.client.get_draft_policy(req)).await - { - counts[i] = resp.into_inner().chunks.len(); +/// Start a bounded, non-overlapping background refresh of pending draft counts. +fn spawn_sandbox_draft_counts_refresh(app: &mut App, tx: mpsc::UnboundedSender) { + if let Some(handle) = app.draft_counts_refresh_handle.as_ref() { + if !handle.is_finished() { + return; } + app.draft_counts_refresh_handle.take(); + } + + let sandboxes: Vec<_> = app + .sandbox_names + .iter() + .cloned() + .enumerate() + .map(|(index, name)| { + let workspace = app + .sandbox_workspaces + .get(index) + .cloned() + .unwrap_or_else(|| app.current_workspace.clone()); + (name, workspace) + }) + .collect(); + if sandboxes.is_empty() { + app.sandbox_draft_counts.clear(); + return; + } + + app.draft_counts_refresh_generation = app.draft_counts_refresh_generation.wrapping_add(1); + let generation = app.draft_counts_refresh_generation; + let gateway_name = app.gateway_name.clone(); + let workspace = app.current_workspace.clone(); + let all_workspaces = app.all_workspaces; + let client = app.client.clone(); + let refresh_sandboxes = sandboxes.clone(); + let handle = tokio::spawn(async move { + let counts = fetch_sandbox_draft_counts(client, refresh_sandboxes).await; + let _ = tx.send(Event::DraftCountsRefreshCompleted( + DraftCountsRefreshResult { + generation, + gateway_name, + workspace, + all_workspaces, + sandboxes, + counts, + }, + )); + }); + app.draft_counts_refresh_handle = Some(handle); +} + +async fn fetch_sandbox_draft_counts( + client: TuiClient, + sandboxes: Vec<(String, String)>, +) -> Vec { + let count = sandboxes.len(); + let results = stream::iter(sandboxes.into_iter().enumerate().map( + |(index, (name, workspace))| { + let mut client = client.clone(); + async move { + let req = openshell_core::proto::GetDraftPolicyRequest { + name, + status_filter: "pending".to_string(), + workspace_scope: Some(named_workspace_scope(workspace)), + }; + let count = match tokio::time::timeout( + Duration::from_secs(2), + client.get_draft_policy(req), + ) + .await + { + Ok(Ok(resp)) => resp.into_inner().chunks.len(), + _ => 0, + }; + (index, count) + } + }, + )) + .buffer_unordered(DRAFT_COUNT_REFRESH_CONCURRENCY) + .collect::>() + .await; + let mut counts = vec![0; count]; + for (index, value) in results { + counts[index] = value; + } + counts +} + +fn apply_sandbox_draft_counts_refresh(app: &mut App, result: DraftCountsRefreshResult) { + if result.generation != app.draft_counts_refresh_generation { + return; + } + app.draft_counts_refresh_handle.take(); + if ( + result.gateway_name.as_str(), + result.workspace.as_str(), + result.all_workspaces, + ) != ( + app.gateway_name.as_str(), + app.current_workspace.as_str(), + app.all_workspaces, + ) { + return; + } + let current: Vec<_> = app + .sandbox_names + .iter() + .cloned() + .enumerate() + .map(|(index, name)| { + let workspace = app + .sandbox_workspaces + .get(index) + .cloned() + .unwrap_or_else(|| app.current_workspace.clone()); + (name, workspace) + }) + .collect(); + if result.sandboxes == current { + app.sandbox_draft_counts = result.counts; } - app.sandbox_draft_counts = counts; } fn phase_label(phase: i32) -> String { @@ -2896,29 +3147,31 @@ mod provider_profile_pagination_tests { #[tokio::test] async fn profile_fetch_continues_until_page_two_is_collected() { - let requested_offsets = Arc::new(Mutex::new(Vec::new())); - let offsets = Arc::clone(&requested_offsets); + let requested_tokens = Arc::new(Mutex::new(Vec::new())); + let tokens = Arc::clone(&requested_tokens); - let profiles = collect_provider_profile_pages(move |offset| { - let offsets = Arc::clone(&offsets); + let profiles = collect_provider_profile_pages(move |page_token| { + let tokens = Arc::clone(&tokens); async move { - offsets.lock().unwrap().push(offset); - match offset { - 0 => Some( + tokens.lock().unwrap().push(page_token.clone()); + match page_token.as_str() { + "" => Some(( (0..PROVIDER_PROFILE_PAGE_SIZE) .map(|index| openshell_core::proto::ProviderProfile { id: format!("profile-{index}"), ..Default::default() }) .collect(), - ), - PROVIDER_PROFILE_PAGE_SIZE => { - Some(vec![openshell_core::proto::ProviderProfile { + "next".to_string(), + )), + "next" => Some(( + vec![openshell_core::proto::ProviderProfile { id: "page-two-profile".to_string(), ..Default::default() - }]) - } - _ => panic!("unexpected profile page offset {offset}"), + }], + String::new(), + )), + _ => panic!("unexpected profile page token {page_token}"), } } }) @@ -2926,8 +3179,8 @@ mod provider_profile_pagination_tests { .expect("all pages should load"); assert_eq!( - *requested_offsets.lock().unwrap(), - vec![0, PROVIDER_PROFILE_PAGE_SIZE] + *requested_tokens.lock().unwrap(), + vec![String::new(), "next".to_string()] ); assert_eq!(profiles.len(), PROVIDER_PROFILE_PAGE_SIZE as usize + 1); assert_eq!(profiles.last().unwrap().id, "page-two-profile"); diff --git a/docs/sandboxes/manage-providers.mdx b/docs/sandboxes/manage-providers.mdx index 895d6761ca..93f5b004b6 100644 --- a/docs/sandboxes/manage-providers.mdx +++ b/docs/sandboxes/manage-providers.mdx @@ -157,7 +157,14 @@ openshell provider list -o json openshell provider list -o yaml ``` -Structured output includes provider metadata (`id`, `name`, `type`), credential key names, config key names, labels, creation timestamp, resource version, and credential expiration times. Only credential and config keys are exposed, never values, preventing accidental credential leakage in logs or output. For details on how credentials are injected into sandboxes, refer to [Credential Injection](#how-credential-injection-works). +Structured list output is an envelope with `providers` and +`next_page_token` fields. Each provider includes metadata (`id`, `name`, +`type`), credential key names, config key names, labels, creation timestamp, +resource version, and credential expiration times. Only credential and config +keys are exposed, never values, preventing accidental credential leakage in +logs or output. Pass the returned token to `--page-token` to continue. For +details on how credentials are injected into sandboxes, refer to +[Credential Injection](#how-credential-injection-works). Inspect a provider: diff --git a/docs/sandboxes/manage-sandboxes.mdx b/docs/sandboxes/manage-sandboxes.mdx index dd192d40fe..41fe7e9e81 100644 --- a/docs/sandboxes/manage-sandboxes.mdx +++ b/docs/sandboxes/manage-sandboxes.mdx @@ -262,6 +262,10 @@ Use `--all-workspaces` with `sandbox template list` when you need an admin view openshell sandbox template list --all-workspaces ``` +For JSON or YAML, template list output contains `templates` and +`next_page_token` fields. Pass the returned token to `--page-token` to +continue. + ## Base Sandbox Container The `base` sandbox container is the default runtime image for standard OpenShell sandboxes unless the gateway overrides its default sandbox image. It is published as `ghcr.io/nvidia/openshell-community/sandboxes/base:latest` and maintained in the [OpenShell Community](https://github.com/NVIDIA/OpenShell-Community/tree/main/sandboxes/base) repository. @@ -465,9 +469,10 @@ openshell service list --output json openshell service list my-sandbox --output yaml ``` -Each record contains `workspace`, `sandbox`, `service`, `target_port`, and -`url`. The unnamed service uses an empty `service` string. An empty result is -an empty collection. +Structured list output contains `services` and `next_page_token` fields. Each +record contains `workspace`, `sandbox`, `service`, `target_port`, and `url`. +The unnamed service uses an empty `service` string. Pass the returned token to +`--page-token` to continue. An empty result has an empty `services` collection. Show or delete one endpoint: @@ -508,6 +513,9 @@ openshell sandbox list -o json openshell sandbox list -o yaml ``` +Structured list output contains `sandboxes` and `next_page_token` fields. +Pass the returned token to `--page-token` to continue. + Get detailed information about a specific sandbox. The output lists **Policy source** (`sandbox` or `global`), **Revision** (the active policy’s row version for that source), and the formatted active policy YAML: ```shell diff --git a/docs/sandboxes/manage-workspaces.mdx b/docs/sandboxes/manage-workspaces.mdx index 003201ac21..635fa1e7e3 100644 --- a/docs/sandboxes/manage-workspaces.mdx +++ b/docs/sandboxes/manage-workspaces.mdx @@ -126,7 +126,9 @@ openshell workspace member remove \ Add `--output json` or `--output yaml` to list membership records for automation. Each record contains `subject` and a normalized `role` of `admin`, -`user`, or `unknown`. An empty result is an empty collection. +`user`, or `unknown`. Structured output is an envelope with `members` and +`next_page_token` fields; pass the returned token to `--page-token` to +continue. An empty result has an empty `members` collection. To change a member's role, remove the existing membership and add it again with the new role. A Platform Admin must perform any change to `admin`. diff --git a/docs/sandboxes/policies.mdx b/docs/sandboxes/policies.mdx index 6404eabcb9..da2cb16eb4 100644 --- a/docs/sandboxes/policies.mdx +++ b/docs/sandboxes/policies.mdx @@ -253,9 +253,11 @@ The following steps outline the hot-reload policy update workflow. ``` Add `--output json` or `--output yaml` for automation. Structured policy - history contains the scope, sandbox name when applicable, version, full + history is an envelope with `revisions` and `next_page_token` fields. Each + revision contains the scope, sandbox name when applicable, version, full hash, status, and available revision timestamps, load error, and provenance. - Use `openshell policy list --global --output json` for global history. + Pass the returned token to `--page-token` to continue. Use + `openshell policy list --global --output json` for global history. ### Validation failures diff --git a/e2e/python/conftest.py b/e2e/python/conftest.py index 502f2540e1..ed8775017e 100644 --- a/e2e/python/conftest.py +++ b/e2e/python/conftest.py @@ -64,7 +64,7 @@ def sandbox_client(cluster_name: str | None) -> Iterator[SandboxClient]: def ensure_sandbox_persistence_ready(sandbox_client: SandboxClient) -> None: for _ in range(60): try: - sandbox_client.list_ids(workspace="default", limit=1) + sandbox_client.list_ids(workspace="default", page_size=1) return except grpc.RpcError as exc: details = exc.details() or "" diff --git a/e2e/python/test_sandbox_api.py b/e2e/python/test_sandbox_api.py index bc7e4d5f8c..954eb228de 100644 --- a/e2e/python/test_sandbox_api.py +++ b/e2e/python/test_sandbox_api.py @@ -42,7 +42,7 @@ def read(self, path: str) -> str: fetched = sandbox_client.get(sb.sandbox.name, workspace="default") assert fetched.id == sb.id - ids = set(sandbox_client.list_ids(workspace="default", limit=100)) + ids = set(sandbox_client.list_ids(workspace="default", page_size=100)) assert sb.id in ids result = sb.exec(["python", "-c", "print('sandbox-ok')"]) diff --git a/e2e/python/test_sandbox_providers.py b/e2e/python/test_sandbox_providers.py index 0b3c9b0a83..85a1a354ba 100644 --- a/e2e/python/test_sandbox_providers.py +++ b/e2e/python/test_sandbox_providers.py @@ -1091,7 +1091,7 @@ def _cleanup() -> None: assert resp.imported, "workspace-scoped import should succeed" platform_list = stub.ListProviderProfiles( - openshell_pb2.ListProviderProfilesRequest(limit=200, workspace="") + openshell_pb2.ListProviderProfilesRequest(page_size=200, workspace="") ) platform_ids = [p.id for p in platform_list.profiles] assert platform_id in platform_ids, ( @@ -1102,7 +1102,7 @@ def _cleanup() -> None: ) workspace_list = stub.ListProviderProfiles( - openshell_pb2.ListProviderProfilesRequest(limit=200, workspace="default") + openshell_pb2.ListProviderProfilesRequest(page_size=200, workspace="default") ) workspace_ids = [p.id for p in workspace_list.profiles] assert workspace_id in workspace_ids, ( @@ -1158,14 +1158,14 @@ def _make_profile() -> openshell_pb2.ProviderProfileImportItem: assert resp_b.imported, "import into ws-b should succeed" list_a = stub.ListProviderProfiles( - openshell_pb2.ListProviderProfilesRequest(limit=200, workspace=ws_a) + openshell_pb2.ListProviderProfilesRequest(page_size=200, workspace=ws_a) ) assert any(p.id == profile_id for p in list_a.profiles), ( "profile should appear in ws-a" ) list_b = stub.ListProviderProfiles( - openshell_pb2.ListProviderProfilesRequest(limit=200, workspace=ws_b) + openshell_pb2.ListProviderProfilesRequest(page_size=200, workspace=ws_b) ) assert any(p.id == profile_id for p in list_b.profiles), ( "profile should appear in ws-b" diff --git a/examples/governance-interceptor/src/main.rs b/examples/governance-interceptor/src/main.rs index eefeb695fa..3636ec0570 100644 --- a/examples/governance-interceptor/src/main.rs +++ b/examples/governance-interceptor/src/main.rs @@ -1224,21 +1224,20 @@ async fn propagate_policy_to_running_sandboxes( .await .map_err(|err| format!("connect to gateway {gateway_endpoint} failed: {err}"))?; let mut client = OpenShellClient::new(channel); - let mut offset = 0_u32; - let limit = 100_u32; + let mut page_token = String::new(); let correlation_id = format!("{}:{}", RELOAD_CORRELATION_PREFIX, now_secs()); loop { let response = client .list_sandboxes(ListSandboxesRequest { - limit, - offset, + page_size: 100, + page_token, label_selector: String::new(), workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), }) .await .map_err(|status| format!("list sandboxes failed: {status}"))? .into_inner(); - let count = response.sandboxes.len(); + let next_page_token = response.next_page_token; for sandbox in response.sandboxes { if !sandbox_accepts_policy_reload(&sandbox) { continue; @@ -1279,10 +1278,10 @@ async fn propagate_policy_to_running_sandboxes( } } } - if count < usize::try_from(limit).unwrap_or(usize::MAX) { + if next_page_token.is_empty() { break; } - offset = offset.saturating_add(limit); + page_token = next_page_token; } Ok(()) } diff --git a/examples/transparent-tcp-redis/demo.sh b/examples/transparent-tcp-redis/demo.sh index 687513f363..0d8b24c523 100755 --- a/examples/transparent-tcp-redis/demo.sh +++ b/examples/transparent-tcp-redis/demo.sh @@ -82,7 +82,7 @@ if ! docker network inspect "$DOCKER_NETWORK" >/dev/null 2>&1; then exit 1 fi -if ! openshell sandbox list --limit 1 >/dev/null 2>&1; then +if ! openshell sandbox list --page-size 1 >/dev/null 2>&1; then printf 'The configured OpenShell gateway is not reachable.\n' >&2 printf 'Start or select a Docker-backed gateway and try again.\n' >&2 exit 1 diff --git a/proto/openshell.proto b/proto/openshell.proto index 580cb2ce2c..def6d7c473 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -1155,8 +1155,12 @@ message GetSandboxTemplateRequest { message ListSandboxTemplatesRequest { reserved 3, 4; reserved "workspace", "all_workspaces"; - uint32 limit = 1; - uint32 offset = 2; + // The maximum number of templates to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + int32 page_size = 1; + // Token from a previous ListSandboxTemplates response. All other request + // parameters except page_size must match the request that produced it. + string page_token = 2; // Optional label selector in key=value comma-separated form. string label_selector = 5; // Explicit named or all-workspaces scope. @@ -1177,6 +1181,8 @@ message SandboxTemplateResponse { message ListSandboxTemplatesResponse { repeated SandboxWorkloadTemplate templates = 1; + // Token for the next page. Empty when there are no subsequent pages. + string next_page_token = 2; } message DeleteSandboxTemplateResponse { @@ -1226,8 +1232,12 @@ message GetSandboxRequest { message ListSandboxesRequest { reserved 4, 5; reserved "workspace", "all_workspaces"; - uint32 limit = 1; - uint32 offset = 2; + // The maximum number of sandboxes to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + int32 page_size = 1; + // Token from a previous ListSandboxes response. All other request parameters + // except page_size must match the request that produced it. + string page_token = 2; // Optional label selector for filtering (format: "key1=value1,key2=value2"). string label_selector = 3; // Explicit named or all-workspaces scope. @@ -1316,6 +1326,8 @@ message SandboxResponse { // List sandboxes response. message ListSandboxesResponse { repeated Sandbox sandboxes = 1; + // Token for the next page. Empty when there are no subsequent pages. + string next_page_token = 2; } // List providers attached to a sandbox response. @@ -1416,10 +1428,12 @@ message ListServicesRequest { reserved "workspace", "all_workspaces"; // Optional sandbox name. Empty lists endpoints for all sandboxes. string sandbox = 1; - // Page size. Zero uses the server default. - uint32 limit = 2; - // Page offset. - uint32 offset = 3; + // The maximum number of services to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + int32 page_size = 2; + // Token from a previous ListServices response. All other request parameters + // except page_size must match the request that produced it. + string page_token = 3; // Explicit named or all-workspaces scope. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 6; } @@ -1427,6 +1441,8 @@ message ListServicesRequest { // Response containing exposed sandbox service endpoints. message ListServicesResponse { repeated ServiceEndpointResponse services = 1; + // Token for the next page. Empty when there are no subsequent pages. + string next_page_token = 2; } // Request to delete an exposed sandbox service endpoint. @@ -1695,8 +1711,12 @@ message GetProviderRequest { message ListProvidersRequest { reserved 3, 4; reserved "workspace", "all_workspaces"; - uint32 limit = 1; - uint32 offset = 2; + // The maximum number of providers to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + int32 page_size = 1; + // Token from a previous ListProviders response. All other request parameters + // except page_size must match the request that produced it. + string page_token = 2; // Explicit named or all-workspaces scope. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; } @@ -1730,12 +1750,18 @@ message ProviderResponse { // List providers response. message ListProvidersResponse { repeated openshell.datamodel.v1.Provider providers = 1; + // Token for the next page. Empty when there are no subsequent pages. + string next_page_token = 2; } // List provider type profiles request. message ListProviderProfilesRequest { - uint32 limit = 1; - uint32 offset = 2; + // The maximum number of profiles to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + int32 page_size = 1; + // Token from a previous ListProviderProfiles response. All other request + // parameters except page_size must match the request that produced it. + string page_token = 2; // Workspace scope. When set, returns workspace-scoped + built-in profiles. // When empty, returns platform-scoped + built-in only. string workspace = 3; @@ -2027,6 +2053,8 @@ message ProviderProfileResponse { // List provider profiles response. message ListProviderProfilesResponse { repeated ProviderProfile profiles = 1; + // Token for the next page. Empty when there are no subsequent pages. + string next_page_token = 2; } // Import custom provider profiles request. @@ -2308,8 +2336,12 @@ message ListSandboxPoliciesRequest { reserved "workspace"; // Sandbox name (canonical lookup key). Ignored when global is true. string name = 1; - uint32 limit = 2; - uint32 offset = 3; + // The maximum number of revisions to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + int32 page_size = 2; + // Token from a previous ListSandboxPolicies response. All other request + // parameters except page_size must match the request that produced it. + string page_token = 3; // List global policy revisions instead of sandbox-scoped ones. bool global = 4; // Explicit workspace scope for sandbox-scoped queries. Omit only when @@ -2322,6 +2354,8 @@ message ListSandboxPoliciesResponse { // Invalid historical payloads remain visible as failed projections so one // legacy row cannot hide the rest of the policy history. repeated SandboxPolicyRevision revisions = 1; + // Token for the next page. Empty when there are no subsequent pages. + string next_page_token = 2; } // Report policy load status (called by sandbox runtime after reload attempt). @@ -2949,8 +2983,12 @@ message GetWorkspaceResponse { // List workspaces request. message ListWorkspacesRequest { - uint32 limit = 1; - uint32 offset = 2; + // The maximum number of workspaces to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + int32 page_size = 1; + // Token from a previous ListWorkspaces response. All other request parameters + // except page_size must match the request that produced it. + string page_token = 2; // Optional label selector for filtering (format: "key1=value1,key2=value2"). string label_selector = 3; } @@ -2958,6 +2996,8 @@ message ListWorkspacesRequest { // List workspaces response. message ListWorkspacesResponse { repeated openshell.datamodel.v1.Workspace workspaces = 1; + // Token for the next page. Empty when there are no subsequent pages. + string next_page_token = 2; } // Delete workspace request. @@ -3035,13 +3075,19 @@ message RemoveWorkspaceMemberResponse { message ListWorkspaceMembersRequest { // Workspace name. string workspace = 1; - uint32 limit = 2; - uint32 offset = 3; + // The maximum number of members to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + int32 page_size = 2; + // Token from a previous ListWorkspaceMembers response. All other request + // parameters except page_size must match the request that produced it. + string page_token = 3; } // List workspace members response. message ListWorkspaceMembersResponse { repeated WorkspaceMember members = 1; + // Token for the next page. Empty when there are no subsequent pages. + string next_page_token = 2; } // Short-lived credential for one policy-authorized extension service. diff --git a/proto/pagination.proto b/proto/pagination.proto new file mode 100644 index 0000000000..05fcaef17f --- /dev/null +++ b/proto/pagination.proto @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +package openshell.internal.pagination.v1; + +// Private, versioned state carried by an opaque public page token. +// +// This message is an implementation detail. Public list RPCs expose only the +// AIP-158 string page_token and next_page_token fields. +message PageToken { + uint32 version = 1; + string method = 2; + bytes request_fingerprint = 3; + + oneof cursor { + ObjectCursor object = 4; + PolicyCursor policy = 5; + ProfileCursor profile = 6; + } +} + +// Cursor for the total object-store order. +message ObjectCursor { + int64 created_at_ms = 1; + string name = 2; + string workspace = 3; + string id = 4; +} + +// Cursor for descending policy revision order. +message PolicyCursor { + int64 version = 1; +} + +// Cursor for a deterministically ordered provider-profile catalog. +message ProfileCursor { + string key = 1; +} diff --git a/python/openshell/sandbox.py b/python/openshell/sandbox.py index 343d75edcc..cfffdf6307 100644 --- a/python/openshell/sandbox.py +++ b/python/openshell/sandbox.py @@ -819,49 +819,61 @@ def list( self, *, workspace: str, - limit: int = 100, - offset: int = 0, + page_size: int = 100, label_selector: str | None = None, ) -> builtins.list[SandboxRef]: - request = openshell_pb2.ListSandboxesRequest( - workspace_scope=_workspace_scope(workspace), - limit=limit, - offset=offset, - label_selector=label_selector or "", - ) - response = self._stub.ListSandboxes(request, timeout=self._timeout) - return [_sandbox_ref(item) for item in response.sandboxes] + sandboxes: builtins.list[SandboxRef] = [] + page_token = "" + while True: + response = self._stub.ListSandboxes( + openshell_pb2.ListSandboxesRequest( + workspace_scope=_workspace_scope(workspace), + page_size=page_size, + page_token=page_token, + label_selector=label_selector or "", + ), + timeout=self._timeout, + ) + sandboxes.extend(_sandbox_ref(item) for item in response.sandboxes) + if not getattr(response, "next_page_token", ""): + return sandboxes + page_token = response.next_page_token def list_for_all_workspaces( self, *, - limit: int = 100, - offset: int = 0, + page_size: int = 100, label_selector: str | None = None, ) -> builtins.list[SandboxRef]: - request = openshell_pb2.ListSandboxesRequest( - workspace_scope=_all_workspaces_scope(), - limit=limit, - offset=offset, - label_selector=label_selector or "", - ) - response = self._stub.ListSandboxes(request, timeout=self._timeout) - return [_sandbox_ref(item) for item in response.sandboxes] + sandboxes: builtins.list[SandboxRef] = [] + page_token = "" + while True: + response = self._stub.ListSandboxes( + openshell_pb2.ListSandboxesRequest( + workspace_scope=_all_workspaces_scope(), + page_size=page_size, + page_token=page_token, + label_selector=label_selector or "", + ), + timeout=self._timeout, + ) + sandboxes.extend(_sandbox_ref(item) for item in response.sandboxes) + if not getattr(response, "next_page_token", ""): + return sandboxes + page_token = response.next_page_token def list_ids( self, *, workspace: str, - limit: int = 100, - offset: int = 0, + page_size: int = 100, label_selector: str | None = None, ) -> builtins.list[str]: return [ item.id for item in self.list( workspace=workspace, - limit=limit, - offset=offset, + page_size=page_size, label_selector=label_selector, ) ] @@ -869,15 +881,13 @@ def list_ids( def list_ids_for_all_workspaces( self, *, - limit: int = 100, - offset: int = 0, + page_size: int = 100, label_selector: str | None = None, ) -> builtins.list[str]: return [ item.id for item in self.list_for_all_workspaces( - limit=limit, - offset=offset, + page_size=page_size, label_selector=label_selector, ) ] @@ -1181,38 +1191,48 @@ def list( self, *, workspace: str, - limit: int = 100, - offset: int = 0, + page_size: int = 100, label_selector: str = "", ) -> builtins.list[openshell_pb2.SandboxWorkloadTemplate]: - response = self._stub.ListSandboxTemplates( - openshell_pb2.ListSandboxTemplatesRequest( - workspace_scope=_workspace_scope(workspace), - limit=limit, - offset=offset, - label_selector=label_selector, - ), - timeout=self._timeout, - ) - return list(response.templates) + templates: builtins.list[openshell_pb2.SandboxWorkloadTemplate] = [] + page_token = "" + while True: + response = self._stub.ListSandboxTemplates( + openshell_pb2.ListSandboxTemplatesRequest( + workspace_scope=_workspace_scope(workspace), + page_size=page_size, + page_token=page_token, + label_selector=label_selector, + ), + timeout=self._timeout, + ) + templates.extend(response.templates) + if not getattr(response, "next_page_token", ""): + return templates + page_token = response.next_page_token def list_for_all_workspaces( self, *, - limit: int = 100, - offset: int = 0, + page_size: int = 100, label_selector: str = "", ) -> builtins.list[openshell_pb2.SandboxWorkloadTemplate]: - response = self._stub.ListSandboxTemplates( - openshell_pb2.ListSandboxTemplatesRequest( - workspace_scope=_all_workspaces_scope(), - limit=limit, - offset=offset, - label_selector=label_selector, - ), - timeout=self._timeout, - ) - return list(response.templates) + templates: builtins.list[openshell_pb2.SandboxWorkloadTemplate] = [] + page_token = "" + while True: + response = self._stub.ListSandboxTemplates( + openshell_pb2.ListSandboxTemplatesRequest( + workspace_scope=_all_workspaces_scope(), + page_size=page_size, + page_token=page_token, + label_selector=label_selector, + ), + timeout=self._timeout, + ) + templates.extend(response.templates) + if not getattr(response, "next_page_token", ""): + return templates + page_token = response.next_page_token def delete(self, name: str, *, workspace: str) -> bool: response = self._stub.DeleteSandboxTemplate( @@ -1276,19 +1296,24 @@ def get(self, name: str) -> WorkspaceRef: def list( self, *, - limit: int = 100, - offset: int = 0, + page_size: int = 100, label_selector: str | None = None, ) -> builtins.list[WorkspaceRef]: - response = self._stub.ListWorkspaces( - openshell_pb2.ListWorkspacesRequest( - limit=limit, - offset=offset, - label_selector=label_selector or "", - ), - timeout=self._timeout, - ) - return [_workspace_ref(ws) for ws in response.workspaces] + workspaces: builtins.list[WorkspaceRef] = [] + page_token = "" + while True: + response = self._stub.ListWorkspaces( + openshell_pb2.ListWorkspacesRequest( + page_size=page_size, + page_token=page_token, + label_selector=label_selector or "", + ), + timeout=self._timeout, + ) + workspaces.extend(_workspace_ref(ws) for ws in response.workspaces) + if not getattr(response, "next_page_token", ""): + return workspaces + page_token = response.next_page_token def delete(self, name: str) -> bool: response = self._stub.DeleteWorkspace( diff --git a/python/openshell/sandbox_test.py b/python/openshell/sandbox_test.py index 772a327239..e436f714db 100644 --- a/python/openshell/sandbox_test.py +++ b/python/openshell/sandbox_test.py @@ -1963,7 +1963,11 @@ def _make_workload_template_proto( class _FakeSandboxStub: - def __init__(self, listed: list[openshell_pb2.Sandbox] | None = None) -> None: + def __init__( + self, + listed: list[openshell_pb2.Sandbox] | None = None, + listed_pages: list[list[openshell_pb2.Sandbox]] | None = None, + ) -> None: self.create_request: openshell_pb2.CreateSandboxRequest | None = None self.list_request: openshell_pb2.ListSandboxesRequest | None = None self.get_request: openshell_pb2.GetSandboxRequest | None = None @@ -1981,6 +1985,8 @@ def __init__(self, listed: list[openshell_pb2.Sandbox] | None = None) -> None: openshell_pb2.DeleteSandboxTemplateRequest | None ) = None self._listed = listed or [] + self._listed_pages = listed_pages + self.list_requests: list[openshell_pb2.ListSandboxesRequest] = [] self._templates: list[openshell_pb2.SandboxWorkloadTemplate] = [] def GetSandbox( @@ -2061,7 +2067,17 @@ def ListSandboxes( timeout: float | None = None, ) -> Any: self.list_request = request + self.list_requests.append(deepcopy(request)) _ = timeout + if self._listed_pages is not None: + page = int(request.page_token or "0") + next_page_token = ( + str(page + 1) if page + 1 < len(self._listed_pages) else "" + ) + return SimpleNamespace( + sandboxes=list(self._listed_pages[page]), + next_page_token=next_page_token, + ) return SimpleNamespace(sandboxes=list(self._listed)) def CreateSandboxTemplate( @@ -2393,13 +2409,13 @@ def test_sandbox_template_client_crud_forwards_requests() -> None: assert _request_workspace(stub.get_template_request) == "default" listed = client.list( - workspace="default", limit=50, offset=10, label_selector="team=runtime" + workspace="default", page_size=50, label_selector="team=runtime" ) assert len(listed) == 1 assert stub.list_template_request is not None assert _request_workspace(stub.list_template_request) == "default" - assert stub.list_template_request.limit == 50 - assert stub.list_template_request.offset == 10 + assert stub.list_template_request.page_size == 50 + assert stub.list_template_request.page_token == "" assert stub.list_template_request.label_selector == "team=runtime" assert not _request_selects_all_workspaces(stub.list_template_request) @@ -2413,13 +2429,13 @@ def test_sandbox_template_list_for_all_workspaces_selects_all() -> None: stub = _FakeSandboxStub() client = _template_client_with_fake_stub(stub) - client.list_for_all_workspaces(limit=100, offset=5, label_selector="team=runtime") + client.list_for_all_workspaces(page_size=100, label_selector="team=runtime") assert stub.list_template_request is not None assert _request_selects_all_workspaces(stub.list_template_request) assert _request_workspace(stub.list_template_request) is None - assert stub.list_template_request.limit == 100 - assert stub.list_template_request.offset == 5 + assert stub.list_template_request.page_size == 100 + assert stub.list_template_request.page_token == "" assert stub.list_template_request.label_selector == "team=runtime" @@ -2534,6 +2550,26 @@ def test_list_without_selector_sends_empty_string() -> None: assert stub.list_request.label_selector == "" +def test_list_follows_continuation_tokens() -> None: + stub = _FakeSandboxStub( + listed_pages=[ + [_make_sandbox_proto("sandbox-1", "job-1")], + [_make_sandbox_proto("sandbox-2", "job-2")], + ] + ) + client = _client_with_fake_stub(stub) + + sandboxes = client.list( + workspace="default", page_size=1, label_selector="team=core" + ) + + assert [sandbox.name for sandbox in sandboxes] == ["job-1", "job-2"] + assert len(stub.list_requests) == 2 + assert stub.list_requests[0].page_token == "" + assert stub.list_requests[1].page_token == "1" + assert stub.list_requests[1].label_selector == "team=core" + + def test_list_ids_forwards_label_selector() -> None: stub = _FakeSandboxStub(listed=[_make_sandbox_proto("sandbox-1", "job-1")]) client = _client_with_fake_stub(stub) diff --git a/sdk/go/docs/src/api/providers.md b/sdk/go/docs/src/api/providers.md index 87c82379a1..f9b1a8c967 100644 --- a/sdk/go/docs/src/api/providers.md +++ b/sdk/go/docs/src/api/providers.md @@ -42,7 +42,8 @@ fmt.Println("Provider type:", provider.Type) ## List -List all registered providers, with optional pagination. +List all registered providers. The SDK follows gateway continuation tokens +automatically; `PageSize` controls each request. ```go // List all providers @@ -54,10 +55,9 @@ for _, p := range providers { fmt.Println(p.Name, p.Type) } -// With pagination +// With a smaller page size providers, err = client.Providers().List(ctx, "default", v1.ListOptions{ - Limit: 10, - Offset: 0, + PageSize: 10, }) // Platform Admin only: list across all workspaces diff --git a/sdk/go/docs/src/api/sandbox-templates.md b/sdk/go/docs/src/api/sandbox-templates.md index 03e8ae43e8..e955dc1f29 100644 --- a/sdk/go/docs/src/api/sandbox-templates.md +++ b/sdk/go/docs/src/api/sandbox-templates.md @@ -89,16 +89,16 @@ fmt.Println(template.Spec.Workload.Image) ## List -Lists templates in one workspace or across all workspaces. +Lists every matching template in one workspace or across all workspaces. The +SDK follows gateway continuation tokens automatically. ```go templates, err := client.SandboxTemplates().List(ctx, "default", v1.ListOptions{ - Limit: 50, - Offset: 0, + PageSize: 50, }) allTemplates, err := client.SandboxTemplates().ListAll(ctx, v1.ListOptions{ - Limit: 50, + PageSize: 50, }) ``` diff --git a/sdk/go/docs/src/api/sandboxes.md b/sdk/go/docs/src/api/sandboxes.md index af026a17cb..e9ab530690 100644 --- a/sdk/go/docs/src/api/sandboxes.md +++ b/sdk/go/docs/src/api/sandboxes.md @@ -57,16 +57,16 @@ fmt.Println(sb.Status.Phase) // "Ready", "Provisioning", etc. ## List -Lists sandboxes with optional pagination and label filtering. +Lists every matching sandbox, following gateway continuation tokens +automatically. `PageSize` controls the size of each request. ```go // List all sandboxes sandboxes, err := client.Sandboxes().List(ctx, "default") -// With pagination and label filtering +// With a page size and label filtering sandboxes, err := client.Sandboxes().List(ctx, "default", v1.ListOptions{ - Limit: 10, - Offset: 0, + PageSize: 10, LabelSelector: "team=platform", }) diff --git a/sdk/go/openshell/v1/fake/policy.go b/sdk/go/openshell/v1/fake/policy.go index 7360af1b03..e69c7bad8e 100644 --- a/sdk/go/openshell/v1/fake/policy.go +++ b/sdk/go/openshell/v1/fake/policy.go @@ -179,6 +179,9 @@ func (c *fakePolicyClient) List(_ context.Context, workspace string, opts ...v1. return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} } cfg := types.ApplyListPolicyOptions(opts) + if cfg.PageSize() < 0 { + return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "page size must not be negative"} + } c.mu.RLock() defer c.mu.RUnlock() @@ -211,17 +214,6 @@ func (c *fakePolicyClient) List(_ context.Context, workspace string, opts ...v1. return 0 }) - // Apply pagination. - offset := int(cfg.Offset()) - if offset >= len(revisions) { - return nil, nil - } - revisions = revisions[offset:] - - if limit := int(cfg.Limit()); limit > 0 && limit < len(revisions) { - revisions = revisions[:limit] - } - result := make([]types.SandboxPolicyRevision, len(revisions)) for i, r := range revisions { result[i] = copySandboxPolicyRevision(r) diff --git a/sdk/go/openshell/v1/fake/policy_test.go b/sdk/go/openshell/v1/fake/policy_test.go index f48398a137..d2ff4e3b0e 100644 --- a/sdk/go/openshell/v1/fake/policy_test.go +++ b/sdk/go/openshell/v1/fake/policy_test.go @@ -132,26 +132,19 @@ func TestFakePolicy_List_NoIsolationCrossContamination(t *testing.T) { assert.Nil(t, revisions) } -func TestFakePolicy_List_GlobalWithPagination(t *testing.T) { +func TestFakePolicy_List_GlobalPageSizeStillReturnsAll(t *testing.T) { c := newFakePolicyClient(func() bool { return false }) c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 1}) c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 2}) c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 3}) - // Limit to 2. - revisions, err := c.List(context.Background(), "", types.WithListGlobal(true), types.WithLimit(2)) + revisions, err := c.List(context.Background(), "", types.WithListGlobal(true), types.WithPageSize(2)) require.NoError(t, err) - require.Len(t, revisions, 2) + require.Len(t, revisions, 3) assert.Equal(t, uint32(1), revisions[0].Version) assert.Equal(t, uint32(2), revisions[1].Version) - - // Offset by 1, limit 2. - revisions, err = c.List(context.Background(), "", types.WithListGlobal(true), types.WithLimit(2), types.WithOffset(1)) - require.NoError(t, err) - require.Len(t, revisions, 2) - assert.Equal(t, uint32(2), revisions[0].Version) - assert.Equal(t, uint32(3), revisions[1].Version) + assert.Equal(t, uint32(3), revisions[2].Version) } func TestFakePolicy_GetStatus_Sandbox(t *testing.T) { diff --git a/sdk/go/openshell/v1/fake/sandbox_template.go b/sdk/go/openshell/v1/fake/sandbox_template.go index b105de7c13..f58f8f6eaf 100644 --- a/sdk/go/openshell/v1/fake/sandbox_template.go +++ b/sdk/go/openshell/v1/fake/sandbox_template.go @@ -120,11 +120,8 @@ func (c *fakeSandboxTemplateClient) list(workspace string, allWorkspaces bool, o var options v1.ListOptions if len(opts) > 0 { options = opts[0] - if options.Limit < 0 { - return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "limit must not be negative"} - } - if options.Offset < 0 { - return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "offset must not be negative"} + if options.PageSize < 0 { + return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "page size must not be negative"} } } var templates []*types.SandboxWorkloadTemplate @@ -138,7 +135,7 @@ func (c *fakeSandboxTemplateClient) list(workspace string, allWorkspaces bool, o if err != nil { return nil, err } - return paginateSandboxWorkloadTemplates(templates, options), nil + return templates, nil } func (c *fakeSandboxTemplateClient) Delete(_ context.Context, workspace, name string) (bool, error) { @@ -248,20 +245,6 @@ func compareSandboxWorkloadTemplatesForList(a, b *types.SandboxWorkloadTemplate) return 0 } -func paginateSandboxWorkloadTemplates( - templates []*types.SandboxWorkloadTemplate, - options v1.ListOptions, -) []*types.SandboxWorkloadTemplate { - if options.Offset >= len(templates) { - return templates[:0] - } - templates = templates[options.Offset:] - if options.Limit > 0 && options.Limit < len(templates) { - return templates[:options.Limit] - } - return templates -} - func isDNS1123Label(name string) bool { if len(name) == 0 || len(name) > 63 || name[0] == '-' || name[len(name)-1] == '-' { return false diff --git a/sdk/go/openshell/v1/fake/sandbox_template_test.go b/sdk/go/openshell/v1/fake/sandbox_template_test.go index 6caa0da684..1df35f8436 100644 --- a/sdk/go/openshell/v1/fake/sandbox_template_test.go +++ b/sdk/go/openshell/v1/fake/sandbox_template_test.go @@ -143,16 +143,12 @@ func TestSandboxTemplate_ListRejectsNegativePagination(t *testing.T) { tc := newTestSandboxTemplateClient() ctx := context.Background() - _, err := tc.List(ctx, "default", types.ListOptions{Limit: -1}) - require.Error(t, err) - assert.True(t, types.IsInvalidArgument(err)) - - _, err = tc.List(ctx, "default", types.ListOptions{Offset: -1}) + _, err := tc.List(ctx, "default", types.ListOptions{PageSize: -1}) require.Error(t, err) assert.True(t, types.IsInvalidArgument(err)) } -func TestSandboxTemplate_ListAppliesPaginationAfterFiltering(t *testing.T) { +func TestSandboxTemplate_ListReturnsAllFilteredResults(t *testing.T) { tc := newTestSandboxTemplateClient() ctx := context.Background() @@ -180,21 +176,13 @@ func TestSandboxTemplate_ListAppliesPaginationAfterFiltering(t *testing.T) { listed, err := tc.List(ctx, "default", types.ListOptions{ LabelSelector: "team=runtime", - Offset: 1, - Limit: 1, - }) - - require.NoError(t, err) - require.Len(t, listed, 1) - assert.Equal(t, "runtime-b", listed[0].Name) - - listed, err = tc.List(ctx, "default", types.ListOptions{ - LabelSelector: "team=runtime", - Offset: 2, + PageSize: 1, }) require.NoError(t, err) - assert.Empty(t, listed) + require.Len(t, listed, 2) + assert.Equal(t, "runtime-a", listed[0].Name) + assert.Equal(t, "runtime-b", listed[1].Name) } func TestSandboxTemplate_CreateSandboxFromTemplateRequiresExistingTemplate(t *testing.T) { diff --git a/sdk/go/openshell/v1/options.go b/sdk/go/openshell/v1/options.go index caac82c96b..78a6179a8f 100644 --- a/sdk/go/openshell/v1/options.go +++ b/sdk/go/openshell/v1/options.go @@ -4,6 +4,8 @@ package v1 import ( + "math" + "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types" ) @@ -21,3 +23,16 @@ type WaitOptions = types.WaitOptions // ExecOptions configures command execution. type ExecOptions = types.ExecOptions + +func listPageSize(opts []ListOptions) (int32, error) { + if len(opts) == 0 { + return 0, nil + } + if opts[0].PageSize < 0 { + return 0, &StatusError{Code: ErrorInvalidArgument, Message: "page size must not be negative"} + } + if opts[0].PageSize > math.MaxInt32 { + return math.MaxInt32, nil + } + return int32(opts[0].PageSize), nil +} diff --git a/sdk/go/openshell/v1/policy.go b/sdk/go/openshell/v1/policy.go index cbe2e8621a..a6025074df 100644 --- a/sdk/go/openshell/v1/policy.go +++ b/sdk/go/openshell/v1/policy.go @@ -87,11 +87,8 @@ var WithVersion = types.WithVersion // ListPolicyOption configures a List call. type ListPolicyOption = types.ListPolicyOption -// WithLimit sets the maximum number of revisions to return. -var WithLimit = types.WithLimit - -// WithOffset sets the pagination offset. -var WithOffset = types.WithOffset +// WithPageSize sets the page size used while collecting every revision. +var WithPageSize = types.WithPageSize // WithListGlobal enables global policy mode on List. When true, the query // retrieves gateway-global policy revisions instead of sandbox-scoped ones. diff --git a/sdk/go/openshell/v1/policy_client.go b/sdk/go/openshell/v1/policy_client.go index 12801af02a..1dec3fad7e 100644 --- a/sdk/go/openshell/v1/policy_client.go +++ b/sdk/go/openshell/v1/policy_client.go @@ -131,29 +131,32 @@ func (p *policyClient) GetStatus(ctx context.Context, workspace, sandboxName str func (p *policyClient) List(ctx context.Context, workspace string, opts ...ListPolicyOption) ([]SandboxPolicyRevision, error) { cfg := types.ApplyListPolicyOptions(opts) + if cfg.PageSize() < 0 { + return nil, &StatusError{Code: ErrorInvalidArgument, Message: "page size must not be negative"} + } req := &pb.ListSandboxPoliciesRequest{ - Limit: cfg.Limit(), - Offset: cfg.Offset(), - Global: cfg.Global(), + PageSize: cfg.PageSize(), + Global: cfg.Global(), } if !cfg.Global() { req.WorkspaceScope = namedWorkspaceScope(workspace) } - resp, err := p.client.ListSandboxPolicies(ctx, req) - if err != nil { - return nil, converter.FromGRPCError(err) - } - revisions := resp.GetRevisions() - if len(revisions) == 0 { - return nil, nil - } - result := make([]SandboxPolicyRevision, 0, len(revisions)) - for _, r := range revisions { - if converted := converter.SandboxPolicyRevisionFromProto(r); converted != nil { - result = append(result, *converted) + var result []SandboxPolicyRevision + for { + resp, err := p.client.ListSandboxPolicies(ctx, req) + if err != nil { + return nil, converter.FromGRPCError(err) + } + for _, revision := range resp.GetRevisions() { + if converted := converter.SandboxPolicyRevisionFromProto(revision); converted != nil { + result = append(result, *converted) + } } + if resp.GetNextPageToken() == "" { + return result, nil + } + req.PageToken = resp.GetNextPageToken() } - return result, nil } func (p *policyClient) EditDraftChunk(ctx context.Context, workspace, sandboxName, chunkID string, proposedRule *NetworkPolicyRule) error { diff --git a/sdk/go/openshell/v1/policy_client_test.go b/sdk/go/openshell/v1/policy_client_test.go index a0e16f5a40..ebb2491ea3 100644 --- a/sdk/go/openshell/v1/policy_client_test.go +++ b/sdk/go/openshell/v1/policy_client_test.go @@ -781,8 +781,8 @@ func TestPolicyList(t *testing.T) { // Verify request was forwarded (no pagination options). mock.mu.Lock() assert.Equal(t, "default", mock.lastListReq.GetWorkspaceScope().GetWorkspace()) - assert.Equal(t, uint32(0), mock.lastListReq.GetLimit()) - assert.Equal(t, uint32(0), mock.lastListReq.GetOffset()) + assert.Equal(t, int32(0), mock.lastListReq.GetPageSize()) + assert.Empty(t, mock.lastListReq.GetPageToken()) mock.mu.Unlock() assert.Equal(t, uint32(1), revisions[0].Version) @@ -794,7 +794,7 @@ func TestPolicyList(t *testing.T) { assert.Equal(t, PolicyLoadStatusLoaded, revisions[1].Status) } -func TestPolicyList_WithPagination(t *testing.T) { +func TestPolicyList_WithPageSize(t *testing.T) { mock := newMockPolicyServer() mock.listResp = &pb.ListSandboxPoliciesResponse{ Revisions: []*pb.SandboxPolicyRevision{ @@ -806,17 +806,16 @@ func TestPolicyList_WithPagination(t *testing.T) { defer cleanup() revisions, err := client.List(context.Background(), "default", - types.WithLimit(10), - types.WithOffset(20), + types.WithPageSize(10), ) require.NoError(t, err) require.Len(t, revisions, 1) - // Verify pagination options were forwarded. + // Verify page size was forwarded and the initial token is empty. mock.mu.Lock() - assert.Equal(t, uint32(10), mock.lastListReq.GetLimit()) - assert.Equal(t, uint32(20), mock.lastListReq.GetOffset()) + assert.Equal(t, int32(10), mock.lastListReq.GetPageSize()) + assert.Empty(t, mock.lastListReq.GetPageToken()) mock.mu.Unlock() } @@ -892,11 +891,10 @@ func TestPolicyList_WithGlobalAndPagination(t *testing.T) { client, cleanup := setupPolicyTest(t, mock) defer cleanup() - // Global flag composes with pagination options. + // Global flag composes with page-size options. revisions, err := client.List(context.Background(), "", types.WithListGlobal(true), - types.WithLimit(10), - types.WithOffset(20), + types.WithPageSize(10), ) require.NoError(t, err) @@ -904,8 +902,8 @@ func TestPolicyList_WithGlobalAndPagination(t *testing.T) { mock.mu.Lock() assert.True(t, mock.lastListReq.GetGlobal()) - assert.Equal(t, uint32(10), mock.lastListReq.GetLimit()) - assert.Equal(t, uint32(20), mock.lastListReq.GetOffset()) + assert.Equal(t, int32(10), mock.lastListReq.GetPageSize()) + assert.Empty(t, mock.lastListReq.GetPageToken()) mock.mu.Unlock() } diff --git a/sdk/go/openshell/v1/profile_client.go b/sdk/go/openshell/v1/profile_client.go index 67f2d36a4e..11808c2faa 100644 --- a/sdk/go/openshell/v1/profile_client.go +++ b/sdk/go/openshell/v1/profile_client.go @@ -20,30 +20,28 @@ func newProfileClient(conn grpc.ClientConnInterface) *profileClient { } func (p *profileClient) List(ctx context.Context, workspace string, opts ...ListOptions) ([]*ProviderProfile, error) { + pageSize, err := listPageSize(opts) + if err != nil { + return nil, err + } req := &pb.ListProviderProfilesRequest{ Workspace: workspace, + PageSize: pageSize, } - if len(opts) > 0 { - if opts[0].Limit < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "limit must not be negative"} + profiles := make([]*ProviderProfile, 0) + for { + resp, err := p.client.ListProviderProfiles(ctx, req) + if err != nil { + return nil, converter.FromGRPCError(err) } - if opts[0].Offset < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "offset must not be negative"} + for _, profile := range resp.GetProfiles() { + profiles = append(profiles, converter.ProviderProfileFromProto(profile)) } - req.Limit = uint32(opts[0].Limit) - req.Offset = uint32(opts[0].Offset) - } - - resp, err := p.client.ListProviderProfiles(ctx, req) - if err != nil { - return nil, converter.FromGRPCError(err) - } - - profiles := make([]*ProviderProfile, 0, len(resp.GetProfiles())) - for _, pp := range resp.GetProfiles() { - profiles = append(profiles, converter.ProviderProfileFromProto(pp)) + if resp.GetNextPageToken() == "" { + return profiles, nil + } + req.PageToken = resp.GetNextPageToken() } - return profiles, nil } func (p *profileClient) Get(ctx context.Context, workspace, id string) (*ProviderProfile, error) { diff --git a/sdk/go/openshell/v1/profile_client_test.go b/sdk/go/openshell/v1/profile_client_test.go index b071038c54..979fe5bbad 100644 --- a/sdk/go/openshell/v1/profile_client_test.go +++ b/sdk/go/openshell/v1/profile_client_test.go @@ -233,6 +233,7 @@ func TestProfileList_Empty(t *testing.T) { profiles, err := client.List(context.Background(), "default") require.NoError(t, err) + assert.NotNil(t, profiles) assert.Empty(t, profiles) } @@ -242,13 +243,13 @@ func TestProfileList_WithOptions(t *testing.T) { client, cleanup := setupProfileTest(t, mock) defer cleanup() - profiles, err := client.List(context.Background(), "default", ListOptions{Limit: 10, Offset: 5}) + profiles, err := client.List(context.Background(), "default", ListOptions{PageSize: 10}) require.NoError(t, err) assert.Len(t, profiles, 1) require.NotNil(t, mock.lastListReq) - assert.Equal(t, uint32(10), mock.lastListReq.GetLimit()) - assert.Equal(t, uint32(5), mock.lastListReq.GetOffset()) + assert.Equal(t, int32(10), mock.lastListReq.GetPageSize()) + assert.Empty(t, mock.lastListReq.GetPageToken()) } func TestProfileList_Error(t *testing.T) { diff --git a/sdk/go/openshell/v1/provider_client.go b/sdk/go/openshell/v1/provider_client.go index 237325a1e3..fdfb4c0bc9 100644 --- a/sdk/go/openshell/v1/provider_client.go +++ b/sdk/go/openshell/v1/provider_client.go @@ -67,27 +67,26 @@ func (p *providerClient) ListAll(ctx context.Context, opts ...ListOptions) ([]*P } func (p *providerClient) list(ctx context.Context, req *pb.ListProvidersRequest, opts ...ListOptions) ([]*Provider, error) { - if len(opts) > 0 { - if opts[0].Limit < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "limit must not be negative"} - } - if opts[0].Offset < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "offset must not be negative"} - } - req.Limit = uint32(opts[0].Limit) - req.Offset = uint32(opts[0].Offset) - } - - resp, err := p.client.ListProviders(ctx, req) + pageSize, err := listPageSize(opts) if err != nil { - return nil, converter.FromGRPCError(err) + return nil, err } + req.PageSize = pageSize - providers := make([]*Provider, 0, len(resp.GetProviders())) - for _, proto := range resp.GetProviders() { - providers = append(providers, converter.ProviderFromProto(proto)) + providers := make([]*Provider, 0) + for { + resp, err := p.client.ListProviders(ctx, req) + if err != nil { + return nil, converter.FromGRPCError(err) + } + for _, proto := range resp.GetProviders() { + providers = append(providers, converter.ProviderFromProto(proto)) + } + if resp.GetNextPageToken() == "" { + return providers, nil + } + req.PageToken = resp.GetNextPageToken() } - return providers, nil } func (p *providerClient) Update(ctx context.Context, workspace string, provider *Provider) (*Provider, error) { diff --git a/sdk/go/openshell/v1/provider_client_test.go b/sdk/go/openshell/v1/provider_client_test.go index 55edddf16d..51830b7881 100644 --- a/sdk/go/openshell/v1/provider_client_test.go +++ b/sdk/go/openshell/v1/provider_client_test.go @@ -202,6 +202,7 @@ func TestProviderList_Empty(t *testing.T) { result, err := client.List(context.Background(), "default") require.NoError(t, err) + assert.NotNil(t, result) assert.Empty(t, result) } diff --git a/sdk/go/openshell/v1/sandbox_client.go b/sdk/go/openshell/v1/sandbox_client.go index 4028634e2d..187c826d8b 100644 --- a/sdk/go/openshell/v1/sandbox_client.go +++ b/sdk/go/openshell/v1/sandbox_client.go @@ -110,28 +110,29 @@ func (s *sandboxClient) ListAll(ctx context.Context, opts ...ListOptions) ([]*Sa } func (s *sandboxClient) list(ctx context.Context, req *pb.ListSandboxesRequest, opts ...ListOptions) ([]*Sandbox, error) { + pageSize, err := listPageSize(opts) + if err != nil { + return nil, err + } + req.PageSize = pageSize if len(opts) > 0 { - if opts[0].Limit < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "limit must not be negative"} - } - if opts[0].Offset < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "offset must not be negative"} - } - req.Limit = uint32(opts[0].Limit) - req.Offset = uint32(opts[0].Offset) req.LabelSelector = opts[0].LabelSelector } - resp, err := s.client.ListSandboxes(ctx, req) - if err != nil { - return nil, converter.FromGRPCError(err) - } - - sandboxes := make([]*Sandbox, 0, len(resp.GetSandboxes())) - for _, proto := range resp.GetSandboxes() { - sandboxes = append(sandboxes, converter.SandboxFromProto(proto)) + sandboxes := make([]*Sandbox, 0) + for { + resp, err := s.client.ListSandboxes(ctx, req) + if err != nil { + return nil, converter.FromGRPCError(err) + } + for _, proto := range resp.GetSandboxes() { + sandboxes = append(sandboxes, converter.SandboxFromProto(proto)) + } + if resp.GetNextPageToken() == "" { + return sandboxes, nil + } + req.PageToken = resp.GetNextPageToken() } - return sandboxes, nil } func (s *sandboxClient) Delete(ctx context.Context, workspace, name string) error { diff --git a/sdk/go/openshell/v1/sandbox_client_test.go b/sdk/go/openshell/v1/sandbox_client_test.go index 7926b28a16..53429c6d1b 100644 --- a/sdk/go/openshell/v1/sandbox_client_test.go +++ b/sdk/go/openshell/v1/sandbox_client_test.go @@ -30,6 +30,8 @@ type mockSandboxServer struct { createErr error getErr error listErr error + listPages [][]*pb.Sandbox + listRequests []*pb.ListSandboxesRequest deleteErr error attachErr error detachErr error @@ -98,12 +100,27 @@ func (s *mockSandboxServer) setPhase(name string, phase pb.SandboxPhase) { } } -func (s *mockSandboxServer) ListSandboxes(_ context.Context, _ *pb.ListSandboxesRequest) (*pb.ListSandboxesResponse, error) { +func (s *mockSandboxServer) ListSandboxes(_ context.Context, req *pb.ListSandboxesRequest) (*pb.ListSandboxesResponse, error) { s.mu.Lock() defer s.mu.Unlock() + s.listRequests = append(s.listRequests, proto.Clone(req).(*pb.ListSandboxesRequest)) if s.listErr != nil { return nil, s.listErr } + if s.listPages != nil { + page := 0 + if req.GetPageToken() == "page-2" { + page = 1 + } + nextPageToken := "" + if page+1 < len(s.listPages) { + nextPageToken = "page-2" + } + return &pb.ListSandboxesResponse{ + Sandboxes: s.listPages[page], + NextPageToken: nextPageToken, + }, nil + } var list []*pb.Sandbox for _, sb := range s.sandboxes { list = append(list, sb) @@ -416,6 +433,7 @@ func TestSandboxList_Empty(t *testing.T) { result, err := client.List(context.Background(), "default") require.NoError(t, err) + assert.NotNil(t, result) assert.Empty(t, result) } @@ -428,12 +446,37 @@ func TestSandboxList_WithOptions(t *testing.T) { client, cleanup := setupSandboxTest(t, mock) defer cleanup() - result, err := client.List(context.Background(), "default", ListOptions{Limit: 10, Offset: 0}) + result, err := client.List(context.Background(), "default", ListOptions{PageSize: 10}) require.NoError(t, err) assert.Len(t, result, 1) } +func TestSandboxList_FollowsContinuationTokens(t *testing.T) { + mock := newMockSandboxServer() + mock.listPages = [][]*pb.Sandbox{ + {{Metadata: &dm.ObjectMeta{Name: "first"}}}, + {{Metadata: &dm.ObjectMeta{Name: "second"}}}, + } + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + result, err := client.List(context.Background(), "default", ListOptions{ + PageSize: 1, + LabelSelector: "team=core", + }) + + require.NoError(t, err) + require.Len(t, result, 2) + assert.Equal(t, "first", result[0].Name) + assert.Equal(t, "second", result[1].Name) + require.Len(t, mock.listRequests, 2) + assert.Empty(t, mock.listRequests[0].GetPageToken()) + assert.Equal(t, "page-2", mock.listRequests[1].GetPageToken()) + assert.Equal(t, int32(1), mock.listRequests[1].GetPageSize()) + assert.Equal(t, "team=core", mock.listRequests[1].GetLabelSelector()) +} + func TestSandboxDelete(t *testing.T) { mock := newMockSandboxServer() mock.sandboxes["deleteme"] = &pb.Sandbox{ diff --git a/sdk/go/openshell/v1/sandbox_template_client.go b/sdk/go/openshell/v1/sandbox_template_client.go index fd9ddb53e3..3b14e36e66 100644 --- a/sdk/go/openshell/v1/sandbox_template_client.go +++ b/sdk/go/openshell/v1/sandbox_template_client.go @@ -62,28 +62,29 @@ func (s *sandboxTemplateClient) ListAll(ctx context.Context, opts ...ListOptions } func (s *sandboxTemplateClient) list(ctx context.Context, req *pb.ListSandboxTemplatesRequest, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) { + pageSize, err := listPageSize(opts) + if err != nil { + return nil, err + } + req.PageSize = pageSize if len(opts) > 0 { - if opts[0].Limit < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "limit must not be negative"} - } - if opts[0].Offset < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "offset must not be negative"} - } - req.Limit = uint32(opts[0].Limit) - req.Offset = uint32(opts[0].Offset) req.LabelSelector = opts[0].LabelSelector } - resp, err := s.client.ListSandboxTemplates(ctx, req) - if err != nil { - return nil, converter.FromGRPCError(err) - } - - templates := make([]*SandboxWorkloadTemplate, 0, len(resp.GetTemplates())) - for _, protoTemplate := range resp.GetTemplates() { - templates = append(templates, converter.SandboxWorkloadTemplateFromProto(protoTemplate)) + templates := make([]*SandboxWorkloadTemplate, 0) + for { + resp, err := s.client.ListSandboxTemplates(ctx, req) + if err != nil { + return nil, converter.FromGRPCError(err) + } + for _, protoTemplate := range resp.GetTemplates() { + templates = append(templates, converter.SandboxWorkloadTemplateFromProto(protoTemplate)) + } + if resp.GetNextPageToken() == "" { + return templates, nil + } + req.PageToken = resp.GetNextPageToken() } - return templates, nil } func (s *sandboxTemplateClient) Delete(ctx context.Context, workspace, name string) (bool, error) { diff --git a/sdk/go/openshell/v1/sandbox_template_client_test.go b/sdk/go/openshell/v1/sandbox_template_client_test.go index 48045dbec8..2f63c6c042 100644 --- a/sdk/go/openshell/v1/sandbox_template_client_test.go +++ b/sdk/go/openshell/v1/sandbox_template_client_test.go @@ -221,8 +221,7 @@ func TestSandboxTemplateGetListDelete(t *testing.T) { assert.Equal(t, "img:v1", got.Spec.Workload.Image) list, err := client.ListAll(context.Background(), ListOptions{ - Limit: 10, - Offset: 2, + PageSize: 10, LabelSelector: "team=runtime", }) require.NoError(t, err) @@ -240,8 +239,8 @@ func TestSandboxTemplateGetListDelete(t *testing.T) { assert.Equal(t, "gpu-kata", mock.getRequest.Name) require.NotNil(t, mock.listRequest) assert.NotNil(t, mock.listRequest.GetWorkspaceScope().GetAllWorkspaces()) - assert.Equal(t, uint32(10), mock.listRequest.Limit) - assert.Equal(t, uint32(2), mock.listRequest.Offset) + assert.Equal(t, int32(10), mock.listRequest.PageSize) + assert.Empty(t, mock.listRequest.PageToken) assert.Equal(t, "team=runtime", mock.listRequest.LabelSelector) require.NotNil(t, mock.deleteRequest) assert.Equal(t, "default", mock.deleteRequest.GetWorkspaceScope().GetWorkspace()) @@ -253,11 +252,19 @@ func TestSandboxTemplateList_RejectsNegativePagination(t *testing.T) { client, cleanup := setupSandboxTemplateTest(t, mock) defer cleanup() - _, err := client.List(context.Background(), "default", ListOptions{Limit: -1}) + _, err := client.List(context.Background(), "default", ListOptions{PageSize: -1}) require.Error(t, err) assert.True(t, IsInvalidArgument(err)) +} - _, err = client.List(context.Background(), "default", ListOptions{Offset: -1}) - require.Error(t, err) - assert.True(t, IsInvalidArgument(err)) +func TestSandboxTemplateList_EmptyReturnsNonNilSlice(t *testing.T) { + mock := newMockSandboxTemplateServer() + client, cleanup := setupSandboxTemplateTest(t, mock) + defer cleanup() + + templates, err := client.List(context.Background(), "default") + + require.NoError(t, err) + assert.NotNil(t, templates) + assert.Empty(t, templates) } diff --git a/sdk/go/openshell/v1/service_client.go b/sdk/go/openshell/v1/service_client.go index 86013f8b30..3ab60d2da7 100644 --- a/sdk/go/openshell/v1/service_client.go +++ b/sdk/go/openshell/v1/service_client.go @@ -58,27 +58,26 @@ func (s *serviceClient) ListAll(ctx context.Context, opts ...ListOptions) ([]*Se } func (s *serviceClient) list(ctx context.Context, req *pb.ListServicesRequest, opts ...ListOptions) ([]*ServiceEndpoint, error) { - if len(opts) > 0 { - if opts[0].Limit < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "limit must not be negative"} - } - if opts[0].Offset < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "offset must not be negative"} - } - req.Limit = uint32(opts[0].Limit) - req.Offset = uint32(opts[0].Offset) - } - - resp, err := s.client.ListServices(ctx, req) + pageSize, err := listPageSize(opts) if err != nil { - return nil, converter.FromGRPCError(err) + return nil, err } + req.PageSize = pageSize - endpoints := make([]*ServiceEndpoint, 0, len(resp.GetServices())) - for _, svc := range resp.GetServices() { - endpoints = append(endpoints, converter.ServiceEndpointFromProto(svc)) + endpoints := make([]*ServiceEndpoint, 0) + for { + resp, err := s.client.ListServices(ctx, req) + if err != nil { + return nil, converter.FromGRPCError(err) + } + for _, svc := range resp.GetServices() { + endpoints = append(endpoints, converter.ServiceEndpointFromProto(svc)) + } + if resp.GetNextPageToken() == "" { + return endpoints, nil + } + req.PageToken = resp.GetNextPageToken() } - return endpoints, nil } func (s *serviceClient) Delete(ctx context.Context, workspace, sandboxName, serviceName string) error { diff --git a/sdk/go/openshell/v1/service_client_test.go b/sdk/go/openshell/v1/service_client_test.go index bf0b4eccb8..ace6a25099 100644 --- a/sdk/go/openshell/v1/service_client_test.go +++ b/sdk/go/openshell/v1/service_client_test.go @@ -251,6 +251,7 @@ func TestServiceList_Empty(t *testing.T) { endpoints, err := client.List(context.Background(), "default", "web-app") require.NoError(t, err) + assert.NotNil(t, endpoints) assert.Empty(t, endpoints) } @@ -262,7 +263,7 @@ func TestServiceList_WithOptions(t *testing.T) { _, err := client.Expose(context.Background(), "default", "web-app", "api", 8080, true) require.NoError(t, err) - endpoints, err := client.List(context.Background(), "default", "web-app", ListOptions{Limit: 10, Offset: 0}) + endpoints, err := client.List(context.Background(), "default", "web-app", ListOptions{PageSize: 10}) require.NoError(t, err) assert.Len(t, endpoints, 1) @@ -273,7 +274,7 @@ func TestServiceListAll_SelectsAllWorkspaces(t *testing.T) { client, cleanup := setupServiceTest(t, mock) defer cleanup() - endpoints, err := client.ListAll(context.Background(), ListOptions{Limit: 10}) + endpoints, err := client.ListAll(context.Background(), ListOptions{PageSize: 10}) require.NoError(t, err) assert.Empty(t, endpoints) diff --git a/sdk/go/openshell/v1/types/options.go b/sdk/go/openshell/v1/types/options.go index 0d9136a407..8f220248ef 100644 --- a/sdk/go/openshell/v1/types/options.go +++ b/sdk/go/openshell/v1/types/options.go @@ -12,8 +12,7 @@ type CreateOptions struct { // ListOptions configures resource listing with pagination and filtering. type ListOptions struct { - Limit int - Offset int + PageSize int LabelSelector string } diff --git a/sdk/go/openshell/v1/types/policy.go b/sdk/go/openshell/v1/types/policy.go index 4cd39eb081..858cc2c162 100644 --- a/sdk/go/openshell/v1/types/policy.go +++ b/sdk/go/openshell/v1/types/policy.go @@ -363,25 +363,17 @@ func (c *getStatusConfig) Global() bool { // listPolicyConfig holds configuration for List calls. type listPolicyConfig struct { - limit uint32 - offset uint32 - global bool + pageSize int32 + global bool } // ListPolicyOption configures a List call. type ListPolicyOption func(*listPolicyConfig) -// WithLimit sets the maximum number of revisions to return. -func WithLimit(limit uint32) ListPolicyOption { +// WithPageSize sets the page size used while collecting every revision. +func WithPageSize(pageSize int32) ListPolicyOption { return func(c *listPolicyConfig) { - c.limit = limit - } -} - -// WithOffset sets the pagination offset. -func WithOffset(offset uint32) ListPolicyOption { - return func(c *listPolicyConfig) { - c.offset = offset + c.pageSize = pageSize } } @@ -401,14 +393,9 @@ func ApplyListPolicyOptions(opts []ListPolicyOption) listPolicyConfig { //nolint return cfg } -// Limit returns the configured limit (0 means server default). -func (c *listPolicyConfig) Limit() uint32 { - return c.limit -} - -// Offset returns the configured offset. -func (c *listPolicyConfig) Offset() uint32 { - return c.offset +// PageSize returns the configured page size (0 means server default). +func (c *listPolicyConfig) PageSize() int32 { + return c.pageSize } // Global returns whether global policy mode is enabled. diff --git a/sdk/go/openshell/v1/workspace_client.go b/sdk/go/openshell/v1/workspace_client.go index b036217737..852c32969b 100644 --- a/sdk/go/openshell/v1/workspace_client.go +++ b/sdk/go/openshell/v1/workspace_client.go @@ -49,29 +49,29 @@ func (w *workspaceClient) Get(ctx context.Context, name string) (*Workspace, err } func (w *workspaceClient) List(ctx context.Context, opts ...ListOptions) ([]*Workspace, error) { - req := &pb.ListWorkspacesRequest{} + pageSize, err := listPageSize(opts) + if err != nil { + return nil, err + } + req := &pb.ListWorkspacesRequest{PageSize: pageSize} if len(opts) > 0 { - if opts[0].Limit < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "limit must not be negative"} - } - if opts[0].Offset < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "offset must not be negative"} - } - req.Limit = uint32(opts[0].Limit) - req.Offset = uint32(opts[0].Offset) req.LabelSelector = opts[0].LabelSelector } - resp, err := w.client.ListWorkspaces(ctx, req) - if err != nil { - return nil, converter.FromGRPCError(err) - } - - workspaces := make([]*Workspace, 0, len(resp.GetWorkspaces())) - for _, proto := range resp.GetWorkspaces() { - workspaces = append(workspaces, converter.WorkspaceFromProto(proto)) + workspaces := make([]*Workspace, 0) + for { + resp, err := w.client.ListWorkspaces(ctx, req) + if err != nil { + return nil, converter.FromGRPCError(err) + } + for _, proto := range resp.GetWorkspaces() { + workspaces = append(workspaces, converter.WorkspaceFromProto(proto)) + } + if resp.GetNextPageToken() == "" { + return workspaces, nil + } + req.PageToken = resp.GetNextPageToken() } - return workspaces, nil } func (w *workspaceClient) Delete(ctx context.Context, name string) error { @@ -135,28 +135,26 @@ func (w *workspaceClient) ListMembers(ctx context.Context, workspace string, opt return nil, &StatusError{Code: ErrorInvalidArgument, Message: "workspace name must not be empty"} } + pageSize, err := listPageSize(opts) + if err != nil { + return nil, err + } req := &pb.ListWorkspaceMembersRequest{ Workspace: workspace, + PageSize: pageSize, } - if len(opts) > 0 { - if opts[0].Limit < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "limit must not be negative"} + members := make([]*WorkspaceMember, 0) + for { + resp, err := w.client.ListWorkspaceMembers(ctx, req) + if err != nil { + return nil, converter.FromGRPCError(err) } - if opts[0].Offset < 0 { - return nil, &StatusError{Code: ErrorInvalidArgument, Message: "offset must not be negative"} + for _, proto := range resp.GetMembers() { + members = append(members, converter.WorkspaceMemberFromProto(proto)) } - req.Limit = uint32(opts[0].Limit) - req.Offset = uint32(opts[0].Offset) - } - - resp, err := w.client.ListWorkspaceMembers(ctx, req) - if err != nil { - return nil, converter.FromGRPCError(err) - } - - members := make([]*WorkspaceMember, 0, len(resp.GetMembers())) - for _, proto := range resp.GetMembers() { - members = append(members, converter.WorkspaceMemberFromProto(proto)) + if resp.GetNextPageToken() == "" { + return members, nil + } + req.PageToken = resp.GetNextPageToken() } - return members, nil } diff --git a/sdk/go/openshell/v1/workspace_test.go b/sdk/go/openshell/v1/workspace_test.go index f64a76e998..743a9be0eb 100644 --- a/sdk/go/openshell/v1/workspace_test.go +++ b/sdk/go/openshell/v1/workspace_test.go @@ -239,17 +239,28 @@ func TestWorkspaceList_WithOptions(t *testing.T) { wc := newWorkspaceClient(conn) _, err := wc.List(context.Background(), ListOptions{ - Limit: 10, - Offset: 5, + PageSize: 10, LabelSelector: "team=platform", }) require.NoError(t, err) - assert.Equal(t, uint32(10), mock.lastListReq.GetLimit()) - assert.Equal(t, uint32(5), mock.lastListReq.GetOffset()) + assert.Equal(t, int32(10), mock.lastListReq.GetPageSize()) + assert.Empty(t, mock.lastListReq.GetPageToken()) assert.Equal(t, "team=platform", mock.lastListReq.GetLabelSelector()) } +func TestWorkspaceList_EmptyReturnsNonNilSlice(t *testing.T) { + mock := &mockWorkspaceServer{listResp: &pb.ListWorkspacesResponse{}} + conn, cleanup := newMockWorkspaceServer(mock) + defer cleanup() + + workspaces, err := newWorkspaceClient(conn).List(context.Background()) + + require.NoError(t, err) + assert.NotNil(t, workspaces) + assert.Empty(t, workspaces) +} + func TestWorkspaceDelete_Success(t *testing.T) { mock := &mockWorkspaceServer{ deleteResp: &pb.DeleteWorkspaceResponse{Deleted: true}, @@ -452,6 +463,20 @@ func TestListMembers_EmptyWorkspace(t *testing.T) { assert.True(t, IsInvalidArgument(err)) } +func TestListMembers_EmptyResultReturnsNonNilSlice(t *testing.T) { + mock := &mockWorkspaceServer{ + listMembersResp: &pb.ListWorkspaceMembersResponse{}, + } + conn, cleanup := newMockWorkspaceServer(mock) + defer cleanup() + + members, err := newWorkspaceClient(conn).ListMembers(context.Background(), "test-ws") + + require.NoError(t, err) + assert.NotNil(t, members) + assert.Empty(t, members) +} + func TestListMembers_WithOptions(t *testing.T) { mock := &mockWorkspaceServer{ listMembersResp: &pb.ListWorkspaceMembersResponse{}, @@ -460,9 +485,9 @@ func TestListMembers_WithOptions(t *testing.T) { defer cleanup() wc := newWorkspaceClient(conn) - _, err := wc.ListMembers(context.Background(), "test-ws", ListOptions{Limit: 5, Offset: 2}) + _, err := wc.ListMembers(context.Background(), "test-ws", ListOptions{PageSize: 5}) require.NoError(t, err) - assert.Equal(t, uint32(5), mock.lastListMembersReq.GetLimit()) - assert.Equal(t, uint32(2), mock.lastListMembersReq.GetOffset()) + assert.Equal(t, int32(5), mock.lastListMembersReq.GetPageSize()) + assert.Empty(t, mock.lastListMembersReq.GetPageToken()) } diff --git a/sdk/go/proto/openshellv1/openshell.pb.go b/sdk/go/proto/openshellv1/openshell.pb.go index 6443c3a361..735c17bc88 100644 --- a/sdk/go/proto/openshellv1/openshell.pb.go +++ b/sdk/go/proto/openshellv1/openshell.pb.go @@ -2675,9 +2675,13 @@ func (x *GetSandboxTemplateRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSe } type ListSandboxTemplatesRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Limit uint32 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"` - Offset uint32 `protobuf:"varint,2,opt,name=offset,proto3" json:"offset,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + // The maximum number of templates to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + PageSize int32 `protobuf:"varint,1,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` + // Token from a previous ListSandboxTemplates response. All other request + // parameters except page_size must match the request that produced it. + PageToken string `protobuf:"bytes,2,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` // Optional label selector in key=value comma-separated form. LabelSelector string `protobuf:"bytes,5,opt,name=label_selector,json=labelSelector,proto3" json:"label_selector,omitempty"` // Explicit named or all-workspaces scope. @@ -2716,18 +2720,18 @@ func (*ListSandboxTemplatesRequest) Descriptor() ([]byte, []int) { return file_openshell_proto_rawDescGZIP(), []int{34} } -func (x *ListSandboxTemplatesRequest) GetLimit() uint32 { +func (x *ListSandboxTemplatesRequest) GetPageSize() int32 { if x != nil { - return x.Limit + return x.PageSize } return 0 } -func (x *ListSandboxTemplatesRequest) GetOffset() uint32 { +func (x *ListSandboxTemplatesRequest) GetPageToken() string { if x != nil { - return x.Offset + return x.PageToken } - return 0 + return "" } func (x *ListSandboxTemplatesRequest) GetLabelSelector() string { @@ -2842,8 +2846,10 @@ func (x *SandboxTemplateResponse) GetTemplate() *SandboxWorkloadTemplate { } type ListSandboxTemplatesResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Templates []*SandboxWorkloadTemplate `protobuf:"bytes,1,rep,name=templates,proto3" json:"templates,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + Templates []*SandboxWorkloadTemplate `protobuf:"bytes,1,rep,name=templates,proto3" json:"templates,omitempty"` + // Token for the next page. Empty when there are no subsequent pages. + NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -2885,6 +2891,13 @@ func (x *ListSandboxTemplatesResponse) GetTemplates() []*SandboxWorkloadTemplate return nil } +func (x *ListSandboxTemplatesResponse) GetNextPageToken() string { + if x != nil { + return x.NextPageToken + } + return "" +} + type DeleteSandboxTemplateResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Deleted bool `protobuf:"varint,1,opt,name=deleted,proto3" json:"deleted,omitempty"` @@ -3128,9 +3141,13 @@ func (x *GetSandboxRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { // List sandboxes request. type ListSandboxesRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Limit uint32 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"` - Offset uint32 `protobuf:"varint,2,opt,name=offset,proto3" json:"offset,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + // The maximum number of sandboxes to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + PageSize int32 `protobuf:"varint,1,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` + // Token from a previous ListSandboxes response. All other request parameters + // except page_size must match the request that produced it. + PageToken string `protobuf:"bytes,2,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` // Optional label selector for filtering (format: "key1=value1,key2=value2"). LabelSelector string `protobuf:"bytes,3,opt,name=label_selector,json=labelSelector,proto3" json:"label_selector,omitempty"` // Explicit named or all-workspaces scope. @@ -3169,18 +3186,18 @@ func (*ListSandboxesRequest) Descriptor() ([]byte, []int) { return file_openshell_proto_rawDescGZIP(), []int{42} } -func (x *ListSandboxesRequest) GetLimit() uint32 { +func (x *ListSandboxesRequest) GetPageSize() int32 { if x != nil { - return x.Limit + return x.PageSize } return 0 } -func (x *ListSandboxesRequest) GetOffset() uint32 { +func (x *ListSandboxesRequest) GetPageToken() string { if x != nil { - return x.Offset + return x.PageToken } - return 0 + return "" } func (x *ListSandboxesRequest) GetLabelSelector() string { @@ -3616,8 +3633,10 @@ func (x *SandboxResponse) GetSandbox() *Sandbox { // List sandboxes response. type ListSandboxesResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Sandboxes []*Sandbox `protobuf:"bytes,1,rep,name=sandboxes,proto3" json:"sandboxes,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + Sandboxes []*Sandbox `protobuf:"bytes,1,rep,name=sandboxes,proto3" json:"sandboxes,omitempty"` + // Token for the next page. Empty when there are no subsequent pages. + NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -3659,6 +3678,13 @@ func (x *ListSandboxesResponse) GetSandboxes() []*Sandbox { return nil } +func (x *ListSandboxesResponse) GetNextPageToken() string { + if x != nil { + return x.NextPageToken + } + return "" +} + // List providers attached to a sandbox response. type ListSandboxProvidersResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -4164,10 +4190,12 @@ type ListServicesRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Optional sandbox name. Empty lists endpoints for all sandboxes. Sandbox string `protobuf:"bytes,1,opt,name=sandbox,proto3" json:"sandbox,omitempty"` - // Page size. Zero uses the server default. - Limit uint32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` - // Page offset. - Offset uint32 `protobuf:"varint,3,opt,name=offset,proto3" json:"offset,omitempty"` + // The maximum number of services to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` + // Token from a previous ListServices response. All other request parameters + // except page_size must match the request that produced it. + PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` // Explicit named or all-workspaces scope. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,6,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` unknownFields protoimpl.UnknownFields @@ -4211,18 +4239,18 @@ func (x *ListServicesRequest) GetSandbox() string { return "" } -func (x *ListServicesRequest) GetLimit() uint32 { +func (x *ListServicesRequest) GetPageSize() int32 { if x != nil { - return x.Limit + return x.PageSize } return 0 } -func (x *ListServicesRequest) GetOffset() uint32 { +func (x *ListServicesRequest) GetPageToken() string { if x != nil { - return x.Offset + return x.PageToken } - return 0 + return "" } func (x *ListServicesRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { @@ -4234,8 +4262,10 @@ func (x *ListServicesRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector // Response containing exposed sandbox service endpoints. type ListServicesResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Services []*ServiceEndpointResponse `protobuf:"bytes,1,rep,name=services,proto3" json:"services,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + Services []*ServiceEndpointResponse `protobuf:"bytes,1,rep,name=services,proto3" json:"services,omitempty"` + // Token for the next page. Empty when there are no subsequent pages. + NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -4277,6 +4307,13 @@ func (x *ListServicesResponse) GetServices() []*ServiceEndpointResponse { return nil } +func (x *ListServicesResponse) GetNextPageToken() string { + if x != nil { + return x.NextPageToken + } + return "" +} + // Request to delete an exposed sandbox service endpoint. type DeleteServiceRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -5937,9 +5974,13 @@ func (x *GetProviderRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector // List providers request. type ListProvidersRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Limit uint32 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"` - Offset uint32 `protobuf:"varint,2,opt,name=offset,proto3" json:"offset,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + // The maximum number of providers to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + PageSize int32 `protobuf:"varint,1,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` + // Token from a previous ListProviders response. All other request parameters + // except page_size must match the request that produced it. + PageToken string `protobuf:"bytes,2,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` // Explicit named or all-workspaces scope. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` unknownFields protoimpl.UnknownFields @@ -5976,18 +6017,18 @@ func (*ListProvidersRequest) Descriptor() ([]byte, []int) { return file_openshell_proto_rawDescGZIP(), []int{83} } -func (x *ListProvidersRequest) GetLimit() uint32 { +func (x *ListProvidersRequest) GetPageSize() int32 { if x != nil { - return x.Limit + return x.PageSize } return 0 } -func (x *ListProvidersRequest) GetOffset() uint32 { +func (x *ListProvidersRequest) GetPageToken() string { if x != nil { - return x.Offset + return x.PageToken } - return 0 + return "" } func (x *ListProvidersRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { @@ -6162,8 +6203,10 @@ func (x *ProviderResponse) GetProvider() *datamodelv1.Provider { // List providers response. type ListProvidersResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Providers []*datamodelv1.Provider `protobuf:"bytes,1,rep,name=providers,proto3" json:"providers,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + Providers []*datamodelv1.Provider `protobuf:"bytes,1,rep,name=providers,proto3" json:"providers,omitempty"` + // Token for the next page. Empty when there are no subsequent pages. + NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -6205,11 +6248,22 @@ func (x *ListProvidersResponse) GetProviders() []*datamodelv1.Provider { return nil } +func (x *ListProvidersResponse) GetNextPageToken() string { + if x != nil { + return x.NextPageToken + } + return "" +} + // List provider type profiles request. type ListProviderProfilesRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Limit uint32 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"` - Offset uint32 `protobuf:"varint,2,opt,name=offset,proto3" json:"offset,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + // The maximum number of profiles to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + PageSize int32 `protobuf:"varint,1,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` + // Token from a previous ListProviderProfiles response. All other request + // parameters except page_size must match the request that produced it. + PageToken string `protobuf:"bytes,2,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` // Workspace scope. When set, returns workspace-scoped + built-in profiles. // When empty, returns platform-scoped + built-in only. Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` @@ -6247,18 +6301,18 @@ func (*ListProviderProfilesRequest) Descriptor() ([]byte, []int) { return file_openshell_proto_rawDescGZIP(), []int{88} } -func (x *ListProviderProfilesRequest) GetLimit() uint32 { +func (x *ListProviderProfilesRequest) GetPageSize() int32 { if x != nil { - return x.Limit + return x.PageSize } return 0 } -func (x *ListProviderProfilesRequest) GetOffset() uint32 { +func (x *ListProviderProfilesRequest) GetPageToken() string { if x != nil { - return x.Offset + return x.PageToken } - return 0 + return "" } func (x *ListProviderProfilesRequest) GetWorkspace() string { @@ -7912,8 +7966,10 @@ func (x *ProviderProfileResponse) GetProfile() *ProviderProfile { // List provider profiles response. type ListProviderProfilesResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Profiles []*ProviderProfile `protobuf:"bytes,1,rep,name=profiles,proto3" json:"profiles,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + Profiles []*ProviderProfile `protobuf:"bytes,1,rep,name=profiles,proto3" json:"profiles,omitempty"` + // Token for the next page. Empty when there are no subsequent pages. + NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -7955,6 +8011,13 @@ func (x *ListProviderProfilesResponse) GetProfiles() []*ProviderProfile { return nil } +func (x *ListProviderProfilesResponse) GetNextPageToken() string { + if x != nil { + return x.NextPageToken + } + return "" +} + // Import custom provider profiles request. type ImportProviderProfilesRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -9713,9 +9776,13 @@ func (x *GetSandboxPolicyStatusResponse) GetActiveVersion() uint32 { type ListSandboxPoliciesRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Sandbox name (canonical lookup key). Ignored when global is true. - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Limit uint32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` - Offset uint32 `protobuf:"varint,3,opt,name=offset,proto3" json:"offset,omitempty"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // The maximum number of revisions to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` + // Token from a previous ListSandboxPolicies response. All other request + // parameters except page_size must match the request that produced it. + PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` // List global policy revisions instead of sandbox-scoped ones. Global bool `protobuf:"varint,4,opt,name=global,proto3" json:"global,omitempty"` // Explicit workspace scope for sandbox-scoped queries. Omit only when @@ -9762,18 +9829,18 @@ func (x *ListSandboxPoliciesRequest) GetName() string { return "" } -func (x *ListSandboxPoliciesRequest) GetLimit() uint32 { +func (x *ListSandboxPoliciesRequest) GetPageSize() int32 { if x != nil { - return x.Limit + return x.PageSize } return 0 } -func (x *ListSandboxPoliciesRequest) GetOffset() uint32 { +func (x *ListSandboxPoliciesRequest) GetPageToken() string { if x != nil { - return x.Offset + return x.PageToken } - return 0 + return "" } func (x *ListSandboxPoliciesRequest) GetGlobal() bool { @@ -9795,7 +9862,9 @@ type ListSandboxPoliciesResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // Invalid historical payloads remain visible as failed projections so one // legacy row cannot hide the rest of the policy history. - Revisions []*SandboxPolicyRevision `protobuf:"bytes,1,rep,name=revisions,proto3" json:"revisions,omitempty"` + Revisions []*SandboxPolicyRevision `protobuf:"bytes,1,rep,name=revisions,proto3" json:"revisions,omitempty"` + // Token for the next page. Empty when there are no subsequent pages. + NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -9837,6 +9906,13 @@ func (x *ListSandboxPoliciesResponse) GetRevisions() []*SandboxPolicyRevision { return nil } +func (x *ListSandboxPoliciesResponse) GetNextPageToken() string { + if x != nil { + return x.NextPageToken + } + return "" +} + // Report policy load status (called by sandbox runtime after reload attempt). type ReportPolicyStatusRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -13568,9 +13644,13 @@ func (x *GetWorkspaceResponse) GetWorkspace() *datamodelv1.Workspace { // List workspaces request. type ListWorkspacesRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Limit uint32 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"` - Offset uint32 `protobuf:"varint,2,opt,name=offset,proto3" json:"offset,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + // The maximum number of workspaces to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + PageSize int32 `protobuf:"varint,1,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` + // Token from a previous ListWorkspaces response. All other request parameters + // except page_size must match the request that produced it. + PageToken string `protobuf:"bytes,2,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` // Optional label selector for filtering (format: "key1=value1,key2=value2"). LabelSelector string `protobuf:"bytes,3,opt,name=label_selector,json=labelSelector,proto3" json:"label_selector,omitempty"` unknownFields protoimpl.UnknownFields @@ -13607,18 +13687,18 @@ func (*ListWorkspacesRequest) Descriptor() ([]byte, []int) { return file_openshell_proto_rawDescGZIP(), []int{195} } -func (x *ListWorkspacesRequest) GetLimit() uint32 { +func (x *ListWorkspacesRequest) GetPageSize() int32 { if x != nil { - return x.Limit + return x.PageSize } return 0 } -func (x *ListWorkspacesRequest) GetOffset() uint32 { +func (x *ListWorkspacesRequest) GetPageToken() string { if x != nil { - return x.Offset + return x.PageToken } - return 0 + return "" } func (x *ListWorkspacesRequest) GetLabelSelector() string { @@ -13630,8 +13710,10 @@ func (x *ListWorkspacesRequest) GetLabelSelector() string { // List workspaces response. type ListWorkspacesResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Workspaces []*datamodelv1.Workspace `protobuf:"bytes,1,rep,name=workspaces,proto3" json:"workspaces,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + Workspaces []*datamodelv1.Workspace `protobuf:"bytes,1,rep,name=workspaces,proto3" json:"workspaces,omitempty"` + // Token for the next page. Empty when there are no subsequent pages. + NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -13673,6 +13755,13 @@ func (x *ListWorkspacesResponse) GetWorkspaces() []*datamodelv1.Workspace { return nil } +func (x *ListWorkspacesResponse) GetNextPageToken() string { + if x != nil { + return x.NextPageToken + } + return "" +} + // Delete workspace request. type DeleteWorkspaceRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -14040,9 +14129,13 @@ func (x *RemoveWorkspaceMemberResponse) GetRemoved() bool { type ListWorkspaceMembersRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Workspace name. - Workspace string `protobuf:"bytes,1,opt,name=workspace,proto3" json:"workspace,omitempty"` - Limit uint32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` - Offset uint32 `protobuf:"varint,3,opt,name=offset,proto3" json:"offset,omitempty"` + Workspace string `protobuf:"bytes,1,opt,name=workspace,proto3" json:"workspace,omitempty"` + // The maximum number of members to return. Zero uses 100. Values above + // 1000 are coerced to 1000; negative values are invalid. + PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` + // Token from a previous ListWorkspaceMembers response. All other request + // parameters except page_size must match the request that produced it. + PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -14084,24 +14177,26 @@ func (x *ListWorkspaceMembersRequest) GetWorkspace() string { return "" } -func (x *ListWorkspaceMembersRequest) GetLimit() uint32 { +func (x *ListWorkspaceMembersRequest) GetPageSize() int32 { if x != nil { - return x.Limit + return x.PageSize } return 0 } -func (x *ListWorkspaceMembersRequest) GetOffset() uint32 { +func (x *ListWorkspaceMembersRequest) GetPageToken() string { if x != nil { - return x.Offset + return x.PageToken } - return 0 + return "" } // List workspace members response. type ListWorkspaceMembersResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Members []*WorkspaceMember `protobuf:"bytes,1,rep,name=members,proto3" json:"members,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + Members []*WorkspaceMember `protobuf:"bytes,1,rep,name=members,proto3" json:"members,omitempty"` + // Token for the next page. Empty when there are no subsequent pages. + NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -14143,6 +14238,13 @@ func (x *ListWorkspaceMembersResponse) GetMembers() []*WorkspaceMember { return nil } +func (x *ListWorkspaceMembersResponse) GetNextPageToken() string { + if x != nil { + return x.NextPageToken + } + return "" +} + // Short-lived credential for one policy-authorized extension service. // Kept at the end of the file so adding it does not renumber existing // generated message descriptors. @@ -14382,19 +14484,21 @@ const file_openshell_proto_rawDesc = "" + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\x94\x01\n" + "\x19GetSandboxTemplateRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + - "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\xed\x01\n" + - "\x1bListSandboxTemplatesRequest\x12\x14\n" + - "\x05limit\x18\x01 \x01(\rR\x05limit\x12\x16\n" + - "\x06offset\x18\x02 \x01(\rR\x06offset\x12%\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\xfb\x01\n" + + "\x1bListSandboxTemplatesRequest\x12\x1b\n" + + "\tpage_size\x18\x01 \x01(\x05R\bpageSize\x12\x1d\n" + + "\n" + + "page_token\x18\x02 \x01(\tR\tpageToken\x12%\n" + "\x0elabel_selector\x18\x05 \x01(\tR\rlabelSelector\x12R\n" + "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\tworkspaceR\x0eall_workspaces\"\x97\x01\n" + "\x1cDeleteSandboxTemplateRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\\\n" + "\x17SandboxTemplateResponse\x12A\n" + - "\btemplate\x18\x01 \x01(\v2%.openshell.v1.SandboxWorkloadTemplateR\btemplate\"c\n" + + "\btemplate\x18\x01 \x01(\v2%.openshell.v1.SandboxWorkloadTemplateR\btemplate\"\x8b\x01\n" + "\x1cListSandboxTemplatesResponse\x12C\n" + - "\ttemplates\x18\x01 \x03(\v2%.openshell.v1.SandboxWorkloadTemplateR\ttemplates\"9\n" + + "\ttemplates\x18\x01 \x03(\v2%.openshell.v1.SandboxWorkloadTemplateR\ttemplates\x12&\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"9\n" + "\x1dDeleteSandboxTemplateResponse\x12\x18\n" + "\adeleted\x18\x01 \x01(\bR\adeleted\"\xbf\x01\n" + "\x1cBeginRootfsTarStagingRequest\x12\x1b\n" + @@ -14410,10 +14514,11 @@ const file_openshell_proto_rawDesc = "" + "\rexpires_at_ms\x18\x04 \x01(\x03R\vexpiresAtMs\"\x8c\x01\n" + "\x11GetSandboxRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + - "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\xe6\x01\n" + - "\x14ListSandboxesRequest\x12\x14\n" + - "\x05limit\x18\x01 \x01(\rR\x05limit\x12\x16\n" + - "\x06offset\x18\x02 \x01(\rR\x06offset\x12%\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\xf4\x01\n" + + "\x14ListSandboxesRequest\x12\x1b\n" + + "\tpage_size\x18\x01 \x01(\x05R\bpageSize\x12\x1d\n" + + "\n" + + "page_token\x18\x02 \x01(\tR\tpageToken\x12%\n" + "\x0elabel_selector\x18\x03 \x01(\tR\rlabelSelector\x12R\n" + "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05J\x04\b\x05\x10\x06R\tworkspaceR\x0eall_workspaces\"\xa5\x01\n" + "\x1bListSandboxProvidersRequest\x12!\n" + @@ -14439,9 +14544,10 @@ const file_openshell_proto_rawDesc = "" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"B\n" + "\x0fSandboxResponse\x12/\n" + - "\asandbox\x18\x01 \x01(\v2\x15.openshell.v1.SandboxR\asandbox\"L\n" + + "\asandbox\x18\x01 \x01(\v2\x15.openshell.v1.SandboxR\asandbox\"t\n" + "\x15ListSandboxesResponse\x123\n" + - "\tsandboxes\x18\x01 \x03(\v2\x15.openshell.v1.SandboxR\tsandboxes\"^\n" + + "\tsandboxes\x18\x01 \x03(\v2\x15.openshell.v1.SandboxR\tsandboxes\x12&\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"^\n" + "\x1cListSandboxProvidersResponse\x12>\n" + "\tproviders\x18\x01 \x03(\v2 .openshell.datamodel.v1.ProviderR\tproviders\"l\n" + "\x1dAttachSandboxProviderResponse\x12/\n" + @@ -14474,14 +14580,16 @@ const file_openshell_proto_rawDesc = "" + "\x11GetServiceRequest\x12\x18\n" + "\asandbox\x18\x01 \x01(\tR\asandbox\x12\x18\n" + "\aservice\x18\x02 \x01(\tR\aservice\x12R\n" + - "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"\xd8\x01\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"\xe6\x01\n" + "\x13ListServicesRequest\x12\x18\n" + - "\asandbox\x18\x01 \x01(\tR\asandbox\x12\x14\n" + - "\x05limit\x18\x02 \x01(\rR\x05limit\x12\x16\n" + - "\x06offset\x18\x03 \x01(\rR\x06offset\x12R\n" + - "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05J\x04\b\x05\x10\x06R\tworkspaceR\x0eall_workspaces\"Y\n" + + "\asandbox\x18\x01 \x01(\tR\asandbox\x12\x1b\n" + + "\tpage_size\x18\x02 \x01(\x05R\bpageSize\x12\x1d\n" + + "\n" + + "page_token\x18\x03 \x01(\tR\tpageToken\x12R\n" + + "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05J\x04\b\x05\x10\x06R\tworkspaceR\x0eall_workspaces\"\x81\x01\n" + "\x14ListServicesResponse\x12A\n" + - "\bservices\x18\x01 \x03(\v2%.openshell.v1.ServiceEndpointResponseR\bservices\"\xaf\x01\n" + + "\bservices\x18\x01 \x03(\v2%.openshell.v1.ServiceEndpointResponseR\bservices\x12&\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\xaf\x01\n" + "\x14DeleteServiceRequest\x12\x18\n" + "\asandbox\x18\x01 \x01(\tR\asandbox\x12\x18\n" + "\aservice\x18\x02 \x01(\tR\aservice\x12R\n" + @@ -14602,10 +14710,11 @@ const file_openshell_proto_rawDesc = "" + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\x8d\x01\n" + "\x12GetProviderRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + - "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\xbf\x01\n" + - "\x14ListProvidersRequest\x12\x14\n" + - "\x05limit\x18\x01 \x01(\rR\x05limit\x12\x16\n" + - "\x06offset\x18\x02 \x01(\rR\x06offset\x12R\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\xcd\x01\n" + + "\x14ListProvidersRequest\x12\x1b\n" + + "\tpage_size\x18\x01 \x01(\x05R\bpageSize\x12\x1d\n" + + "\n" + + "page_token\x18\x02 \x01(\tR\tpageToken\x12R\n" + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\tworkspaceR\x0eall_workspaces\"\xfd\x02\n" + "\x15UpdateProviderRequest\x12<\n" + "\bprovider\x18\x01 \x01(\v2 .openshell.datamodel.v1.ProviderR\bprovider\x12w\n" + @@ -14618,12 +14727,14 @@ const file_openshell_proto_rawDesc = "" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"P\n" + "\x10ProviderResponse\x12<\n" + - "\bprovider\x18\x01 \x01(\v2 .openshell.datamodel.v1.ProviderR\bprovider\"W\n" + + "\bprovider\x18\x01 \x01(\v2 .openshell.datamodel.v1.ProviderR\bprovider\"\x7f\n" + "\x15ListProvidersResponse\x12>\n" + - "\tproviders\x18\x01 \x03(\v2 .openshell.datamodel.v1.ProviderR\tproviders\"i\n" + - "\x1bListProviderProfilesRequest\x12\x14\n" + - "\x05limit\x18\x01 \x01(\rR\x05limit\x12\x16\n" + - "\x06offset\x18\x02 \x01(\rR\x06offset\x12\x1c\n" + + "\tproviders\x18\x01 \x03(\v2 .openshell.datamodel.v1.ProviderR\tproviders\x12&\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"w\n" + + "\x1bListProviderProfilesRequest\x12\x1b\n" + + "\tpage_size\x18\x01 \x01(\x05R\bpageSize\x12\x1d\n" + + "\n" + + "page_token\x18\x02 \x01(\tR\tpageToken\x12\x1c\n" + "\tworkspace\x18\x03 \x01(\tR\tworkspace\"I\n" + "\x19GetProviderProfileRequest\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12\x1c\n" + @@ -14767,9 +14878,10 @@ const file_openshell_proto_rawDesc = "" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"R\n" + "\x17ProviderProfileResponse\x127\n" + - "\aprofile\x18\x01 \x01(\v2\x1d.openshell.v1.ProviderProfileR\aprofile\"Y\n" + + "\aprofile\x18\x01 \x01(\v2\x1d.openshell.v1.ProviderProfileR\aprofile\"\x81\x01\n" + "\x1cListProviderProfilesResponse\x129\n" + - "\bprofiles\x18\x01 \x03(\v2\x1d.openshell.v1.ProviderProfileR\bprofiles\"\x82\x01\n" + + "\bprofiles\x18\x01 \x03(\v2\x1d.openshell.v1.ProviderProfileR\bprofiles\x12&\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\x82\x01\n" + "\x1dImportProviderProfilesRequest\x12C\n" + "\bprofiles\x18\x01 \x03(\v2'.openshell.v1.ProviderProfileImportItemR\bprofiles\x12\x1c\n" + "\tworkspace\x18\x02 \x01(\tR\tworkspace\"\xc2\x01\n" + @@ -14906,15 +15018,17 @@ const file_openshell_proto_rawDesc = "" + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05R\tworkspace\"\x88\x01\n" + "\x1eGetSandboxPolicyStatusResponse\x12?\n" + "\brevision\x18\x01 \x01(\v2#.openshell.v1.SandboxPolicyRevisionR\brevision\x12%\n" + - "\x0eactive_version\x18\x02 \x01(\rR\ractiveVersion\"\xdb\x01\n" + + "\x0eactive_version\x18\x02 \x01(\rR\ractiveVersion\"\xe9\x01\n" + "\x1aListSandboxPoliciesRequest\x12\x12\n" + - "\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" + - "\x05limit\x18\x02 \x01(\rR\x05limit\x12\x16\n" + - "\x06offset\x18\x03 \x01(\rR\x06offset\x12\x16\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12\x1b\n" + + "\tpage_size\x18\x02 \x01(\x05R\bpageSize\x12\x1d\n" + + "\n" + + "page_token\x18\x03 \x01(\tR\tpageToken\x12\x16\n" + "\x06global\x18\x04 \x01(\bR\x06global\x12R\n" + - "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x05\x10\x06R\tworkspace\"`\n" + + "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x05\x10\x06R\tworkspace\"\x88\x01\n" + "\x1bListSandboxPoliciesResponse\x12A\n" + - "\trevisions\x18\x01 \x03(\v2#.openshell.v1.SandboxPolicyRevisionR\trevisions\"\xa7\x01\n" + + "\trevisions\x18\x01 \x03(\v2#.openshell.v1.SandboxPolicyRevisionR\trevisions\x12&\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\xa7\x01\n" + "\x19ReportPolicyStatusRequest\x12\x1d\n" + "\n" + "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x18\n" + @@ -15192,15 +15306,17 @@ const file_openshell_proto_rawDesc = "" + "\x13GetWorkspaceRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\"W\n" + "\x14GetWorkspaceResponse\x12?\n" + - "\tworkspace\x18\x01 \x01(\v2!.openshell.datamodel.v1.WorkspaceR\tworkspace\"l\n" + - "\x15ListWorkspacesRequest\x12\x14\n" + - "\x05limit\x18\x01 \x01(\rR\x05limit\x12\x16\n" + - "\x06offset\x18\x02 \x01(\rR\x06offset\x12%\n" + - "\x0elabel_selector\x18\x03 \x01(\tR\rlabelSelector\"[\n" + + "\tworkspace\x18\x01 \x01(\v2!.openshell.datamodel.v1.WorkspaceR\tworkspace\"z\n" + + "\x15ListWorkspacesRequest\x12\x1b\n" + + "\tpage_size\x18\x01 \x01(\x05R\bpageSize\x12\x1d\n" + + "\n" + + "page_token\x18\x02 \x01(\tR\tpageToken\x12%\n" + + "\x0elabel_selector\x18\x03 \x01(\tR\rlabelSelector\"\x83\x01\n" + "\x16ListWorkspacesResponse\x12A\n" + "\n" + "workspaces\x18\x01 \x03(\v2!.openshell.datamodel.v1.WorkspaceR\n" + - "workspaces\",\n" + + "workspaces\x12&\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\",\n" + "\x16DeleteWorkspaceRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\"3\n" + "\x17DeleteWorkspaceResponse\x12\x18\n" + @@ -15219,13 +15335,15 @@ const file_openshell_proto_rawDesc = "" + "\tworkspace\x18\x01 \x01(\tR\tworkspace\x12+\n" + "\x11principal_subject\x18\x02 \x01(\tR\x10principalSubject\"9\n" + "\x1dRemoveWorkspaceMemberResponse\x12\x18\n" + - "\aremoved\x18\x01 \x01(\bR\aremoved\"i\n" + + "\aremoved\x18\x01 \x01(\bR\aremoved\"w\n" + "\x1bListWorkspaceMembersRequest\x12\x1c\n" + - "\tworkspace\x18\x01 \x01(\tR\tworkspace\x12\x14\n" + - "\x05limit\x18\x02 \x01(\rR\x05limit\x12\x16\n" + - "\x06offset\x18\x03 \x01(\rR\x06offset\"W\n" + + "\tworkspace\x18\x01 \x01(\tR\tworkspace\x12\x1b\n" + + "\tpage_size\x18\x02 \x01(\x05R\bpageSize\x12\x1d\n" + + "\n" + + "page_token\x18\x03 \x01(\tR\tpageToken\"\x7f\n" + "\x1cListWorkspaceMembersResponse\x127\n" + - "\amembers\x18\x01 \x03(\v2\x1d.openshell.v1.WorkspaceMemberR\amembers\"\x7f\n" + + "\amembers\x18\x01 \x03(\v2\x1d.openshell.v1.WorkspaceMemberR\amembers\x12&\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\x7f\n" + "\x1aExtensionServiceCredential\x12!\n" + "\fservice_name\x18\x01 \x01(\tR\vserviceName\x12\x1a\n" + "\x05token\x18\x02 \x01(\tB\x04\x88\xb5\x18\x01R\x05token\x12\"\n" + diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index 112bfdc5fe..01689c61e8 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -186,13 +186,15 @@ const sandbox = await client.sandbox.createFromTemplate({ }) await client.sandboxTemplates.get('python', { workspace: 'default' }) -await client.sandboxTemplates.list({ workspace: 'default', limit: 100 }) +await client.sandboxTemplates.list({ workspace: 'default', pageSize: 100 }) await client.sandboxTemplates.delete('python', { workspace: 'default' }) ``` Use `allWorkspaces: true` on `list()` for a platform-admin view. The discriminated option type makes `workspace` and `allWorkspaces` mutually exclusive. Omitting both options explicitly selects the `default` workspace. +List methods follow continuation tokens automatically; `pageSize` controls +each gateway request. ## Surface and roadmap diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index 60cd5c3f0e..824ab4a115 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -438,7 +438,7 @@ describe('create', () => { const created = await sandbox.create({ name: 'direct', workspace: 'staging', image: 'img' }); const got = await sandbox.get('lookup', { workspace: 'staging' }); - const listed = await sandbox.list({ workspace: 'staging', limit: 10 }); + const listed = await sandbox.list({ workspace: 'staging', pageSize: 10 }); const deleted = await sandbox.delete('lookup', { workspace: 'staging' }); await expect(sandbox.waitReady('lookup', 1, { workspace: 'staging' })).resolves.toMatchObject({ workspace: 'staging', @@ -483,6 +483,32 @@ describe('create', () => { expect(selectedWorkspace(observed.updateSetting ?? {})).toBe('staging'); }); + it('follows sandbox list continuation tokens', async () => { + const requests: Array<{ pageToken?: string; pageSize?: number; labelSelector?: string }> = []; + const sandbox = client({ + listSandboxes: (req) => { + requests.push(req); + if (req.pageToken === '') { + return { + sandboxes: [readySandbox('first', 'first-id').sandbox ?? {}], + nextPageToken: 'page-2', + }; + } + return { + sandboxes: [readySandbox('second', 'second-id').sandbox ?? {}], + nextPageToken: '', + }; + }, + }); + + const listed = await sandbox.list({ pageSize: 1, labelSelector: 'team=core' }); + + expect(listed.map((item) => item.name)).toEqual(['first', 'second']); + expect(requests).toHaveLength(2); + expect(requests[0]).toMatchObject({ pageToken: '', pageSize: 1, labelSelector: 'team=core' }); + expect(requests[1]).toMatchObject({ pageToken: 'page-2', pageSize: 1, labelSelector: 'team=core' }); + }); + it('createFromTemplate rejects an empty template name locally', async () => { const sandbox = client({}); await expect(sandbox.createFromTemplate({ templateName: ' ' })).rejects.toMatchObject({ @@ -593,10 +619,10 @@ describe('sandbox templates', () => { expect(created.metadata?.resourceVersion).toBe(1n); }); - it('get list and delete forward workspace and pagination', async () => { + it('get list and delete forward workspace and page size', async () => { const observed: { get?: ScopedRequest & { name?: string }; - list?: ScopedRequest & { limit?: number; offset?: number; labelSelector?: string }; + list?: ScopedRequest & { pageSize?: number; pageToken?: string; labelSelector?: string }; delete?: ScopedRequest & { name?: string }; } = {}; const templates = templateClient({ @@ -627,7 +653,7 @@ describe('sandbox templates', () => { }); const got = await templates.get('gpu-kata', { workspace: 'staging' }); - const listed = await templates.list({ workspace: 'staging', limit: 10, offset: 2, labelSelector: 'team=runtime' }); + const listed = await templates.list({ workspace: 'staging', pageSize: 10, labelSelector: 'team=runtime' }); const deleted = await templates.delete('gpu-kata', { workspace: 'staging' }); expect(got.metadata?.name).toBe('gpu-kata'); @@ -636,8 +662,8 @@ describe('sandbox templates', () => { expect(observed.get).toMatchObject({ name: 'gpu-kata' }); expect(selectedWorkspace(observed.get ?? {})).toBe('staging'); expect(observed.list).toMatchObject({ - limit: 10, - offset: 2, + pageSize: 10, + pageToken: '', labelSelector: 'team=runtime', }); expect(selectedWorkspace(observed.list ?? {})).toBe('staging'); diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index 839a425e2b..989ce2f0a7 100644 --- a/sdk/typescript/src/client.ts +++ b/sdk/typescript/src/client.ts @@ -150,8 +150,8 @@ export interface SandboxWorkloadTemplateProvenance { } interface PaginationOptions { - limit?: number; - offset?: number; + /** Page size used while collecting every result. */ + pageSize?: number; labelSelector?: string; } @@ -175,8 +175,8 @@ export interface SandboxTemplateWorkspaceOptions { } export type SandboxTemplateListOptions = WorkspaceListScope & { - limit?: number; - offset?: number; + /** Page size used while collecting every result. */ + pageSize?: number; /** Optional label selector in key=value comma-separated form. */ labelSelector?: string; }; @@ -687,13 +687,19 @@ export class SandboxTemplateClient { async list(options?: SandboxTemplateListOptions | null): Promise { try { - const resp = await this.grpc.listSandboxTemplates({ - limit: options?.limit ?? 0, - offset: options?.offset ?? 0, - labelSelector: options?.labelSelector ?? '', - workspaceScope: listWorkspaceScope(options), - }); - return resp.templates; + const templates: SandboxWorkloadTemplate[] = []; + let pageToken = ''; + do { + const resp = await this.grpc.listSandboxTemplates({ + pageSize: options?.pageSize ?? 0, + pageToken, + labelSelector: options?.labelSelector ?? '', + workspaceScope: listWorkspaceScope(options), + }); + templates.push(...resp.templates); + pageToken = resp.nextPageToken; + } while (pageToken !== ''); + return templates; } catch (e) { throw fromConnect(e); } @@ -811,13 +817,19 @@ export class SandboxClient { async list(options?: ListOptions | null): Promise { try { - const resp = await this.grpc.listSandboxes({ - limit: options?.limit ?? 0, - offset: options?.offset ?? 0, - labelSelector: options?.labelSelector ?? '', - workspaceScope: listWorkspaceScope(options), - }); - return resp.sandboxes.map((s) => sandboxRef(s)); + const sandboxes: SandboxRef[] = []; + let pageToken = ''; + do { + const resp = await this.grpc.listSandboxes({ + pageSize: options?.pageSize ?? 0, + pageToken, + labelSelector: options?.labelSelector ?? '', + workspaceScope: listWorkspaceScope(options), + }); + sandboxes.push(...resp.sandboxes.map((sandbox) => sandboxRef(sandbox))); + pageToken = resp.nextPageToken; + } while (pageToken !== ''); + return sandboxes; } catch (e) { throw fromConnect(e); } diff --git a/skills/openshell-cli/SKILL.md b/skills/openshell-cli/SKILL.md index ed64496190..d986a45cc1 100644 --- a/skills/openshell-cli/SKILL.md +++ b/skills/openshell-cli/SKILL.md @@ -542,7 +542,7 @@ Return to Step 2. Continue monitoring logs and refining the policy until all req View all revisions to understand how the policy evolved: ```bash -openshell policy list dev --limit 50 +openshell policy list dev --page-size 50 openshell policy list dev --output json ``` From 1860010850d3c1520d4f5d82f7c30b6a366bb747 Mon Sep 17 00:00:00 2001 From: Drew Newberry Date: Fri, 11 Sep 2026 00:02:08 +0000 Subject: [PATCH 09/12] feat(sdk): add lazy pagination pagers (#3256) * feat(sdk): add lazy pagination pagers Signed-off-by: Drew Newberry * test(sdk): harden pager edge cases Signed-off-by: Drew Newberry * test(sdk): cover initial resume token Signed-off-by: Drew Newberry * docs(go): fix all-workspaces pager examples Signed-off-by: Drew Newberry --------- Signed-off-by: Drew Newberry --- architecture/gateway.md | 4 + crates/openshell-sdk/README.md | 24 +- crates/openshell-sdk/src/client.rs | 383 +++++++++++------- crates/openshell-sdk/src/lib.rs | 4 +- crates/openshell-sdk/src/pagination.rs | 143 +++++++ crates/openshell-sdk/src/types.rs | 8 +- crates/openshell-sdk/tests/client_mock.rs | 66 ++- docs/sandboxes/manage-sandboxes.mdx | 8 +- docs/sandboxes/manage-workspaces.mdx | 5 +- e2e/python/oidc/oidc_auth_test.py | 2 +- e2e/python/test_sandbox_api.py | 8 +- e2e/python/test_workspace_api.py | 2 +- python/openshell/__init__.py | 4 + python/openshell/sandbox.py | 201 ++++++--- python/openshell/sandbox_test.py | 62 ++- sdk/go/README.md | 25 ++ sdk/go/docs/src/api/overview.md | 7 +- sdk/go/docs/src/api/policy.md | 5 +- sdk/go/docs/src/api/profiles.md | 5 +- sdk/go/docs/src/api/providers.md | 12 +- sdk/go/docs/src/api/sandbox-templates.md | 10 +- sdk/go/docs/src/api/sandboxes.md | 16 +- sdk/go/docs/src/api/services.md | 9 +- sdk/go/docs/src/architecture.md | 2 +- sdk/go/docs/src/testing.md | 2 +- sdk/go/openshell/v1/doc.go | 39 +- sdk/go/openshell/v1/example_fake_test.go | 2 +- sdk/go/openshell/v1/example_test.go | 2 +- sdk/go/openshell/v1/exec_client_test.go | 4 +- sdk/go/openshell/v1/fake/fake_test.go | 2 +- sdk/go/openshell/v1/fake/pager.go | 48 +++ sdk/go/openshell/v1/fake/policy.go | 28 +- sdk/go/openshell/v1/fake/policy_test.go | 24 +- sdk/go/openshell/v1/fake/profile.go | 10 +- sdk/go/openshell/v1/fake/profile_test.go | 4 +- sdk/go/openshell/v1/fake/provider.go | 24 +- sdk/go/openshell/v1/fake/provider_test.go | 6 +- sdk/go/openshell/v1/fake/sandbox.go | 24 +- sdk/go/openshell/v1/fake/sandbox_template.go | 22 +- .../v1/fake/sandbox_template_test.go | 14 +- sdk/go/openshell/v1/fake/sandbox_test.go | 6 +- sdk/go/openshell/v1/fake/service.go | 4 +- sdk/go/openshell/v1/fake/service_test.go | 4 +- sdk/go/openshell/v1/fake/workspace.go | 34 +- sdk/go/openshell/v1/fake/workspace_test.go | 20 +- sdk/go/openshell/v1/pager.go | 73 ++++ sdk/go/openshell/v1/pager_test.go | 81 ++++ sdk/go/openshell/v1/policy.go | 8 +- sdk/go/openshell/v1/policy_client.go | 33 +- sdk/go/openshell/v1/policy_client_test.go | 20 +- sdk/go/openshell/v1/profile.go | 3 +- sdk/go/openshell/v1/profile_client.go | 26 +- sdk/go/openshell/v1/profile_client_test.go | 8 +- sdk/go/openshell/v1/provider.go | 4 +- sdk/go/openshell/v1/provider_client.go | 43 +- sdk/go/openshell/v1/provider_client_test.go | 25 +- sdk/go/openshell/v1/sandbox.go | 4 +- sdk/go/openshell/v1/sandbox_client.go | 50 ++- sdk/go/openshell/v1/sandbox_client_test.go | 25 +- sdk/go/openshell/v1/sandbox_template.go | 4 +- .../openshell/v1/sandbox_template_client.go | 46 ++- .../v1/sandbox_template_client_test.go | 8 +- sdk/go/openshell/v1/service.go | 4 +- sdk/go/openshell/v1/service_client.go | 47 ++- sdk/go/openshell/v1/service_client_test.go | 13 +- sdk/go/openshell/v1/ssh_client_test.go | 8 +- sdk/go/openshell/v1/tcp_client_test.go | 4 +- sdk/go/openshell/v1/types/options.go | 7 +- sdk/go/openshell/v1/types/policy.go | 19 +- sdk/go/openshell/v1/workspace.go | 6 +- sdk/go/openshell/v1/workspace_client.go | 52 ++- sdk/go/openshell/v1/workspace_test.go | 14 +- sdk/typescript/README.md | 15 +- sdk/typescript/src/client.test.ts | 36 +- sdk/typescript/src/client.ts | 102 +++-- sdk/typescript/src/index.ts | 3 +- 76 files changed, 1532 insertions(+), 597 deletions(-) create mode 100644 crates/openshell-sdk/src/pagination.rs create mode 100644 sdk/go/openshell/v1/fake/pager.go create mode 100644 sdk/go/openshell/v1/pager.go create mode 100644 sdk/go/openshell/v1/pager_test.go diff --git a/architecture/gateway.md b/architecture/gateway.md index 588b9f56a4..8771fd4c38 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -549,6 +549,10 @@ sandbox collections in one cancellable background refresh task, never overlaps periodic list refreshes, and discards results after a gateway or workspace change. +Curated Rust, Python, Go, and TypeScript SDK list methods return lazy pagers. +Advancing a pager issues one list RPC and exposes its continuation token; +explicit `list_all` helpers are the only curated APIs that exhaust a collection. + Persistence distinguishes one-page operations from exhaustive scans. `list_object_page` and `list_message_page` return one keyset page and its next cursor. `collect_records` and `collect_messages` exhaust those pages, fail on diff --git a/crates/openshell-sdk/README.md b/crates/openshell-sdk/README.md index 4ff8aca91c..3adbcba375 100644 --- a/crates/openshell-sdk/README.md +++ b/crates/openshell-sdk/README.md @@ -43,7 +43,7 @@ mTLS (client certificates) is not supported. ## Public surface `OpenShellClient::connect(ClientConfig)` returns a connected client exposing -`health`, `create_sandbox`, `get_sandbox`, `list_sandboxes`, `delete_sandbox`, +`health`, `create_sandbox`, `get_sandbox`, `list_sandboxes`, `list_all_sandboxes`, `delete_sandbox`, `create_sandbox_from_template`, `create_sandbox_template`, `get_sandbox_template`, `list_sandbox_templates`, `delete_sandbox_template`, `list_sandboxes_all_workspaces`, `list_sandbox_templates_all_workspaces`, @@ -59,11 +59,22 @@ Curated calls without a workspace argument explicitly select the `default` workspace. Cross-workspace listing uses the separate `*_all_workspaces` methods and requires Platform Admin access. -Curated list methods follow continuation tokens until the collection is -exhausted. `ListOptions::page_size` and -`SandboxTemplateListOptions::page_size` control the size of each gateway -request; callers that need explicit page boundaries can use the raw protobuf -client. +Curated `list_*` methods return a lazy `Pager`. Each `next_page()` call +issues at most one RPC and returns a `Page` with its opaque continuation +token. The explicit `list_all_*` conveniences exhaust that pager; `page_size` +always controls one gateway request, and `page_token` resumes a saved traversal. + +```rust +let mut pages = client.list_sandboxes(ListOptions { + page_size: 100, + ..Default::default() +}); +while let Some(page) = pages.next_page().await? { + for sandbox in page.items { + println!("{}", sandbox.name); + } +} +``` ```rust use openshell_sdk::{ @@ -115,6 +126,7 @@ let _sandbox = client | `refresh` | `Refresh` trait and single-flight refresh coalescing. | | `edge_tunnel` | Cloudflare Access tunnel dialer. | | `error` | `SdkError` taxonomy. | +| `pagination` | Lazy `Pager` and response `Page`. | | `types` | Curated request/response types and proto conversions. | | `raw` | Escape hatch re-exporting the generated tonic clients. | diff --git a/crates/openshell-sdk/src/client.rs b/crates/openshell-sdk/src/client.rs index d8f1b26205..c789aded99 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -11,6 +11,7 @@ use crate::auth::{BearerSlot, EdgeAuthInterceptor, bearer_metadata}; use crate::config::{AuthConfig, ClientConfig}; use crate::error::{Result, SdkError}; +use crate::pagination::{Page, Pager}; use crate::raw::AuthedGrpcClient; use crate::refresh::{RefreshedToken, TokenSource}; use crate::transport; @@ -192,59 +193,83 @@ impl OpenShellClient { } /// List reusable sandbox templates in the default workspace. - pub async fn list_sandbox_templates( + pub fn list_sandbox_templates( &self, opts: SandboxTemplateListOptions, - ) -> Result> { - let mut templates = Vec::new(); - let mut page_token = String::new(); - loop { - let response = self - .unary(|mut grpc| { - let page_token = page_token.clone(); - let request = proto::ListSandboxTemplatesRequest { - page_size: opts.page_size, - page_token, - label_selector: opts.label_selector.clone(), - workspace_scope: Some(proto::workspace_selector("default")), - }; - async move { grpc.list_sandbox_templates(request).await } + ) -> Pager { + let client = self.clone(); + let initial_page_token = opts.page_token.clone(); + Pager::new(initial_page_token, move |page_token| { + let client = client.clone(); + let opts = opts.clone(); + async move { + let response = client + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListSandboxTemplatesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone(), + workspace_scope: Some(proto::workspace_selector("default")), + }; + async move { grpc.list_sandbox_templates(request).await } + }) + .await?; + Ok(Page { + items: response.templates, + next_page_token: response.next_page_token, }) - .await?; - templates.extend(response.templates); - if response.next_page_token.is_empty() { - return Ok(templates); } - page_token = response.next_page_token; - } + }) } - /// List reusable sandbox templates across all workspaces. - pub async fn list_sandbox_templates_all_workspaces( + /// List and collect every reusable sandbox template. + pub async fn list_all_sandbox_templates( &self, opts: SandboxTemplateListOptions, ) -> Result> { - let mut templates = Vec::new(); - let mut page_token = String::new(); - loop { - let response = self - .unary(|mut grpc| { - let page_token = page_token.clone(); - let request = proto::ListSandboxTemplatesRequest { - page_size: opts.page_size, - page_token, - label_selector: opts.label_selector.clone(), - workspace_scope: Some(proto::all_workspaces_selector()), - }; - async move { grpc.list_sandbox_templates(request).await } + self.list_sandbox_templates(opts).collect_all().await + } + + /// List reusable sandbox templates across all workspaces. + pub fn list_sandbox_templates_all_workspaces( + &self, + opts: SandboxTemplateListOptions, + ) -> Pager { + let client = self.clone(); + let initial_page_token = opts.page_token.clone(); + Pager::new(initial_page_token, move |page_token| { + let client = client.clone(); + let opts = opts.clone(); + async move { + let response = client + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListSandboxTemplatesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone(), + workspace_scope: Some(proto::all_workspaces_selector()), + }; + async move { grpc.list_sandbox_templates(request).await } + }) + .await?; + Ok(Page { + items: response.templates, + next_page_token: response.next_page_token, }) - .await?; - templates.extend(response.templates); - if response.next_page_token.is_empty() { - return Ok(templates); } - page_token = response.next_page_token; - } + }) + } + + /// List and collect every reusable sandbox template across all workspaces. + pub async fn list_all_sandbox_templates_all_workspaces( + &self, + opts: SandboxTemplateListOptions, + ) -> Result> { + self.list_sandbox_templates_all_workspaces(opts) + .collect_all() + .await } /// Delete a reusable sandbox template by name from the default workspace. @@ -276,28 +301,40 @@ impl OpenShellClient { } /// List sandboxes. - pub async fn list_sandboxes(&self, opts: ListOptions) -> Result> { - let mut sandboxes = Vec::new(); - let mut page_token = String::new(); - loop { - let response = self - .unary(|mut grpc| { - let page_token = page_token.clone(); - let request = proto::ListSandboxesRequest { - page_size: opts.page_size, - page_token, - label_selector: opts.label_selector.clone().unwrap_or_default(), - workspace_scope: Some(proto::workspace_selector("default")), - }; - async move { grpc.list_sandboxes(request).await } + pub fn list_sandboxes(&self, opts: ListOptions) -> Pager { + let client = self.clone(); + let initial_page_token = opts.page_token.clone(); + Pager::new(initial_page_token, move |page_token| { + let client = client.clone(); + let opts = opts.clone(); + async move { + let response = client + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListSandboxesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone().unwrap_or_default(), + workspace_scope: Some(proto::workspace_selector("default")), + }; + async move { grpc.list_sandboxes(request).await } + }) + .await?; + Ok(Page { + items: response + .sandboxes + .into_iter() + .map(SandboxRef::from_proto) + .collect(), + next_page_token: response.next_page_token, }) - .await?; - sandboxes.extend(response.sandboxes.into_iter().map(SandboxRef::from_proto)); - if response.next_page_token.is_empty() { - return Ok(sandboxes); } - page_token = response.next_page_token; - } + }) + } + + /// List and collect every sandbox in the default workspace. + pub async fn list_all_sandboxes(&self, opts: ListOptions) -> Result> { + self.list_sandboxes(opts).collect_all().await } /// Delete a sandbox by name. @@ -403,31 +440,43 @@ impl OpenShellClient { } /// List sandboxes across all workspaces. - pub async fn list_sandboxes_all_workspaces( + pub fn list_sandboxes_all_workspaces(&self, opts: ListOptions) -> Pager { + let client = self.clone(); + let initial_page_token = opts.page_token.clone(); + Pager::new(initial_page_token, move |page_token| { + let client = client.clone(); + let opts = opts.clone(); + async move { + let response = client + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListSandboxesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone().unwrap_or_default(), + workspace_scope: Some(proto::all_workspaces_selector()), + }; + async move { grpc.list_sandboxes(request).await } + }) + .await?; + Ok(Page { + items: response + .sandboxes + .into_iter() + .map(SandboxRef::from_proto) + .collect(), + next_page_token: response.next_page_token, + }) + } + }) + } + + /// List and collect every sandbox across all workspaces. + pub async fn list_all_sandboxes_all_workspaces( &self, opts: ListOptions, ) -> Result> { - let mut sandboxes = Vec::new(); - let mut page_token = String::new(); - loop { - let response = self - .unary(|mut grpc| { - let page_token = page_token.clone(); - let request = proto::ListSandboxesRequest { - page_size: opts.page_size, - page_token, - label_selector: opts.label_selector.clone().unwrap_or_default(), - workspace_scope: Some(proto::all_workspaces_selector()), - }; - async move { grpc.list_sandboxes(request).await } - }) - .await?; - sandboxes.extend(response.sandboxes.into_iter().map(SandboxRef::from_proto)); - if response.next_page_token.is_empty() { - return Ok(sandboxes); - } - page_token = response.next_page_token; - } + self.list_sandboxes_all_workspaces(opts).collect_all().await } /// Create a new workspace. @@ -468,32 +517,39 @@ impl OpenShellClient { } /// List workspaces. - pub async fn list_workspaces(&self, opts: ListOptions) -> Result> { - let mut workspaces = Vec::new(); - let mut page_token = String::new(); - loop { - let response = self - .unary(|mut grpc| { - let page_token = page_token.clone(); - let request = proto::ListWorkspacesRequest { - page_size: opts.page_size, - page_token, - label_selector: opts.label_selector.clone().unwrap_or_default(), - }; - async move { grpc.list_workspaces(request).await } + pub fn list_workspaces(&self, opts: ListOptions) -> Pager { + let client = self.clone(); + let initial_page_token = opts.page_token.clone(); + Pager::new(initial_page_token, move |page_token| { + let client = client.clone(); + let opts = opts.clone(); + async move { + let response = client + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListWorkspacesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone().unwrap_or_default(), + }; + async move { grpc.list_workspaces(request).await } + }) + .await?; + Ok(Page { + items: response + .workspaces + .into_iter() + .map(WorkspaceRef::from_proto) + .collect(), + next_page_token: response.next_page_token, }) - .await?; - workspaces.extend( - response - .workspaces - .into_iter() - .map(WorkspaceRef::from_proto), - ); - if response.next_page_token.is_empty() { - return Ok(workspaces); } - page_token = response.next_page_token; - } + }) + } + + /// List and collect every workspace. + pub async fn list_all_workspaces(&self, opts: ListOptions) -> Result> { + self.list_workspaces(opts).collect_all().await } /// Delete a workspace by name. @@ -734,32 +790,44 @@ impl WorkspaceScopedClient { } /// List reusable sandbox templates in this workspace. - pub async fn list_sandbox_templates( + pub fn list_sandbox_templates( &self, opts: SandboxTemplateListOptions, - ) -> Result> { - let mut templates = Vec::new(); - let mut page_token = String::new(); - loop { - let response = self - .client - .unary(|mut grpc| { - let page_token = page_token.clone(); - let request = proto::ListSandboxTemplatesRequest { - page_size: opts.page_size, - page_token, - label_selector: opts.label_selector.clone(), - workspace_scope: Some(proto::workspace_selector(&self.workspace)), - }; - async move { grpc.list_sandbox_templates(request).await } + ) -> Pager { + let client = self.client.clone(); + let workspace = self.workspace.clone(); + let initial_page_token = opts.page_token.clone(); + Pager::new(initial_page_token, move |page_token| { + let client = client.clone(); + let workspace = workspace.clone(); + let opts = opts.clone(); + async move { + let response = client + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListSandboxTemplatesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone(), + workspace_scope: Some(proto::workspace_selector(&workspace)), + }; + async move { grpc.list_sandbox_templates(request).await } + }) + .await?; + Ok(Page { + items: response.templates, + next_page_token: response.next_page_token, }) - .await?; - templates.extend(response.templates); - if response.next_page_token.is_empty() { - return Ok(templates); } - page_token = response.next_page_token; - } + }) + } + + /// List and collect every reusable sandbox template in this scope. + pub async fn list_all_sandbox_templates( + &self, + opts: SandboxTemplateListOptions, + ) -> Result> { + self.list_sandbox_templates(opts).collect_all().await } /// Delete a reusable sandbox template by name in this workspace. @@ -793,29 +861,42 @@ impl WorkspaceScopedClient { } /// List sandboxes in this workspace. - pub async fn list_sandboxes(&self, opts: ListOptions) -> Result> { - let mut sandboxes = Vec::new(); - let mut page_token = String::new(); - loop { - let response = self - .client - .unary(|mut grpc| { - let page_token = page_token.clone(); - let request = proto::ListSandboxesRequest { - page_size: opts.page_size, - page_token, - label_selector: opts.label_selector.clone().unwrap_or_default(), - workspace_scope: Some(proto::workspace_selector(&self.workspace)), - }; - async move { grpc.list_sandboxes(request).await } + pub fn list_sandboxes(&self, opts: ListOptions) -> Pager { + let client = self.client.clone(); + let workspace = self.workspace.clone(); + let initial_page_token = opts.page_token.clone(); + Pager::new(initial_page_token, move |page_token| { + let client = client.clone(); + let workspace = workspace.clone(); + let opts = opts.clone(); + async move { + let response = client + .unary(|mut grpc| { + let page_token = page_token.clone(); + let request = proto::ListSandboxesRequest { + page_size: opts.page_size, + page_token, + label_selector: opts.label_selector.clone().unwrap_or_default(), + workspace_scope: Some(proto::workspace_selector(&workspace)), + }; + async move { grpc.list_sandboxes(request).await } + }) + .await?; + Ok(Page { + items: response + .sandboxes + .into_iter() + .map(SandboxRef::from_proto) + .collect(), + next_page_token: response.next_page_token, }) - .await?; - sandboxes.extend(response.sandboxes.into_iter().map(SandboxRef::from_proto)); - if response.next_page_token.is_empty() { - return Ok(sandboxes); } - page_token = response.next_page_token; - } + }) + } + + /// List and collect every sandbox in this workspace. + pub async fn list_all_sandboxes(&self, opts: ListOptions) -> Result> { + self.list_sandboxes(opts).collect_all().await } /// Delete a sandbox by name in this workspace. diff --git a/crates/openshell-sdk/src/lib.rs b/crates/openshell-sdk/src/lib.rs index 8dfb549294..b94b211f2f 100644 --- a/crates/openshell-sdk/src/lib.rs +++ b/crates/openshell-sdk/src/lib.rs @@ -25,7 +25,7 @@ //! # async fn run() -> Result<(), openshell_sdk::SdkError> { //! let client = OpenShellClient::connect(ClientConfig::new("http://127.0.0.1:8080")).await?; //! let health = client.health().await?; -//! let sandboxes = client.list_sandboxes(ListOptions::default()).await?; +//! let sandboxes = client.list_all_sandboxes(ListOptions::default()).await?; //! # Ok(()) //! # } //! ``` @@ -36,6 +36,7 @@ pub mod config; pub mod edge_tunnel; pub mod error; pub mod oidc; +pub mod pagination; pub mod raw; pub mod refresh; pub mod transport; @@ -45,6 +46,7 @@ pub use auth::EdgeAuthInterceptor; pub use client::{OpenShellClient, WorkspaceScopedClient}; pub use config::{AuthConfig, ClientConfig}; pub use error::SdkError; +pub use pagination::{Page, Pager}; pub use refresh::{Refresh, RefreshError, RefreshedToken, TokenSource}; pub use types::{ ExecOptions, ExecResult, Health, ListOptions, SandboxPhase, SandboxRef, SandboxResources, diff --git a/crates/openshell-sdk/src/pagination.rs b/crates/openshell-sdk/src/pagination.rs new file mode 100644 index 0000000000..8f35d03dab --- /dev/null +++ b/crates/openshell-sdk/src/pagination.rs @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Lazy pagination primitives for curated SDK list methods. + +use crate::error::Result; +use std::future::Future; +use std::pin::Pin; + +type PageFuture = Pin>> + Send>>; +type PageFetcher = Box PageFuture + Send + Sync>; + +/// One response page from a list operation. +#[derive(Clone, Debug)] +pub struct Page { + /// Resources returned by this request. + pub items: Vec, + /// Opaque token that resumes after this page, or an empty string at the end. + pub next_page_token: String, +} + +/// A lazy, single-pass iterator over response pages. +/// +/// Constructed by curated `list_*` methods. No RPC is issued until +/// [`Pager::next_page`] is called, and each call fetches at most one page. +pub struct Pager { + fetch: PageFetcher, + next_page_token: Option, +} + +impl Pager { + pub(crate) fn new(page_token: String, fetch: F) -> Self + where + F: Fn(String) -> Fut + Send + Sync + 'static, + Fut: Future>> + Send + 'static, + { + Self { + fetch: Box::new(move |token| Box::pin(fetch(token))), + next_page_token: Some(page_token), + } + } + + /// Fetch the next page, or return `None` after the final page. + pub async fn next_page(&mut self) -> Result>> { + let Some(page_token) = self.next_page_token.clone() else { + return Ok(None); + }; + let page = (self.fetch)(page_token).await?; + self.next_page_token = + (!page.next_page_token.is_empty()).then(|| page.next_page_token.clone()); + Ok(Some(page)) + } + + /// Consume the pager and collect every remaining item. + pub async fn collect_all(mut self) -> Result> { + let mut items = Vec::new(); + while let Some(page) = self.next_page().await? { + items.extend(page.items); + } + Ok(items) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[tokio::test] + async fn pager_is_lazy_and_fetches_one_page_at_a_time() { + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let mut pager = Pager::new("resume".to_string(), move |token| { + let calls = observed.clone(); + async move { + let call = calls.fetch_add(1, Ordering::SeqCst); + if call == 0 { + assert_eq!(token, "resume"); + Ok(Page { + items: vec![1], + next_page_token: "next".to_string(), + }) + } else { + assert_eq!(token, "next"); + Ok(Page { + items: vec![2], + next_page_token: String::new(), + }) + } + } + }); + + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert_eq!(pager.next_page().await.unwrap().unwrap().items, vec![1]); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(pager.next_page().await.unwrap().unwrap().items, vec![2]); + assert!(pager.next_page().await.unwrap().is_none()); + } + + #[tokio::test] + async fn collect_all_consumes_remaining_pages() { + let pager = Pager::new(String::new(), |token| async move { + if token.is_empty() { + Ok(Page { + items: vec![1, 2], + next_page_token: "next".to_string(), + }) + } else { + Ok(Page { + items: vec![3], + next_page_token: String::new(), + }) + } + }); + + assert_eq!(pager.collect_all().await.unwrap(), vec![1, 2, 3]); + } + + #[tokio::test] + async fn failed_fetch_retries_the_same_token() { + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let mut pager = Pager::new("resume".to_string(), move |token| { + let calls = observed.clone(); + async move { + assert_eq!(token, "resume"); + if calls.fetch_add(1, Ordering::SeqCst) == 0 { + Err(crate::error::SdkError::connect("temporary failure")) + } else { + Ok(Page { + items: vec![1], + next_page_token: String::new(), + }) + } + } + }); + + assert!(pager.next_page().await.is_err()); + assert_eq!(pager.next_page().await.unwrap().unwrap().items, vec![1]); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } +} diff --git a/crates/openshell-sdk/src/types.rs b/crates/openshell-sdk/src/types.rs index 1c3fa7014d..a165c37124 100644 --- a/crates/openshell-sdk/src/types.rs +++ b/crates/openshell-sdk/src/types.rs @@ -161,8 +161,10 @@ pub type SandboxStartup = proto::SandboxStartup; /// Options for listing reusable sandbox templates. #[derive(Clone, Debug, Default)] pub struct SandboxTemplateListOptions { - /// Page size requested while collecting templates. `0` uses the server default. + /// Maximum templates requested per page. `0` uses the server default. pub page_size: i32, + /// Opaque token from a previous page. Empty starts at the beginning. + pub page_token: String, /// Optional label selector in `key=value,key2=value2` form. pub label_selector: String, } @@ -245,8 +247,10 @@ impl WorkspaceRef { /// Options for listing sandboxes. #[derive(Clone, Debug, Default)] pub struct ListOptions { - /// Page size requested while collecting results. `0` uses the server default. + /// Maximum resources requested per page. `0` uses the server default. pub page_size: i32, + /// Opaque token from a previous page. Empty starts at the beginning. + pub page_token: String, /// Optional Kubernetes-style label selector (e.g. `env=prod,team=core`). pub label_selector: Option, } diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 7acce33e0e..549f715d9b 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -1031,9 +1031,10 @@ async fn sandbox_template_crud_uses_default_workspace() { ); let listed = client - .list_sandbox_templates_all_workspaces(SandboxTemplateListOptions { + .list_all_sandbox_templates_all_workspaces(SandboxTemplateListOptions { page_size: 10, label_selector: String::new(), + ..Default::default() }) .await .unwrap(); @@ -1095,8 +1096,9 @@ async fn list_sandboxes_propagates_filters() { let opts = ListOptions { page_size: 25, label_selector: Some("team=core".to_string()), + ..Default::default() }; - let items = client.list_sandboxes(opts).await.unwrap(); + let items = client.list_all_sandboxes(opts).await.unwrap(); assert_eq!(items.len(), 2); assert_eq!(items[0].name, "alpha"); assert_eq!(items[0].phase, SandboxPhase::Ready); @@ -1117,17 +1119,22 @@ async fn list_sandboxes_follows_continuation_tokens() { let endpoint = start_mock(state.clone()).await; let client = connect(&endpoint).await; - let items = client - .list_sandboxes(ListOptions { - page_size: 1, - label_selector: Some("team=core".to_string()), - }) - .await - .unwrap(); - - assert_eq!(items.len(), 2); - assert_eq!(items[0].name, "alpha"); - assert_eq!(items[1].name, "beta"); + let mut pager = client.list_sandboxes(ListOptions { + page_size: 1, + label_selector: Some("team=core".to_string()), + ..Default::default() + }); + assert!(state.list_requests.lock().await.is_empty()); + + let first = pager.next_page().await.unwrap().unwrap(); + assert_eq!(first.items.len(), 1); + assert_eq!(first.items[0].name, "alpha"); + assert_eq!(first.next_page_token, "page-2"); + let second = pager.next_page().await.unwrap().unwrap(); + assert_eq!(second.items.len(), 1); + assert_eq!(second.items[0].name, "beta"); + assert!(second.next_page_token.is_empty()); + assert!(pager.next_page().await.unwrap().is_none()); let requests = state.list_requests.lock().await; assert_eq!(requests.len(), 2); assert!(requests[0].page_token.is_empty()); @@ -1135,6 +1142,29 @@ async fn list_sandboxes_follows_continuation_tokens() { assert_eq!(requests[1].label_selector, "team=core"); } +#[tokio::test] +async fn list_sandboxes_passes_initial_page_token() { + let state = Arc::new(MockState { + paginate_list: true, + ..Default::default() + }); + let endpoint = start_mock(state.clone()).await; + let client = connect(&endpoint).await; + + let mut pager = client.list_sandboxes(ListOptions { + page_size: 1, + page_token: "page-2".to_string(), + ..Default::default() + }); + let page = pager.next_page().await.unwrap().unwrap(); + + assert_eq!(page.items.len(), 1); + assert_eq!(page.items[0].name, "beta"); + let requests = state.list_requests.lock().await; + assert_eq!(requests.len(), 1); + assert_eq!(requests[0].page_token, "page-2"); +} + #[tokio::test] async fn delete_sandbox_returns_server_ack() { let state = Arc::new(MockState::default()); @@ -1471,7 +1501,7 @@ async fn workspace_scoped_list_passes_workspace() { let client = connect(&endpoint).await; let ws = client.workspace("dev"); - let items = ws.list_sandboxes(ListOptions::default()).await.unwrap(); + let items = ws.list_all_sandboxes(ListOptions::default()).await.unwrap(); assert_eq!(items.len(), 2); let observed = state.last_list_request.lock().await.clone().unwrap(); @@ -1503,7 +1533,7 @@ async fn workspace_scoped_sandbox_template_crud_passes_workspace() { ); let listed = ws - .list_sandbox_templates(SandboxTemplateListOptions::default()) + .list_all_sandbox_templates(SandboxTemplateListOptions::default()) .await .unwrap(); assert_eq!(listed.len(), 2); @@ -1514,7 +1544,7 @@ async fn workspace_scoped_sandbox_template_crud_passes_workspace() { ); client - .list_sandbox_templates_all_workspaces(SandboxTemplateListOptions::default()) + .list_all_sandbox_templates_all_workspaces(SandboxTemplateListOptions::default()) .await .unwrap(); let observed_all = state.last_template_list.lock().await.clone().unwrap(); @@ -1551,7 +1581,7 @@ async fn list_sandboxes_all_workspaces_sets_flag() { let client = connect(&endpoint).await; let items = client - .list_sandboxes_all_workspaces(ListOptions::default()) + .list_all_sandboxes_all_workspaces(ListOptions::default()) .await .unwrap(); assert_eq!(items.len(), 2); @@ -1600,7 +1630,7 @@ async fn list_workspaces_returns_all() { let client = connect(&endpoint).await; let workspaces = client - .list_workspaces(ListOptions::default()) + .list_all_workspaces(ListOptions::default()) .await .unwrap(); assert_eq!(workspaces.len(), 2); diff --git a/docs/sandboxes/manage-sandboxes.mdx b/docs/sandboxes/manage-sandboxes.mdx index 41fe7e9e81..e5dadeb284 100644 --- a/docs/sandboxes/manage-sandboxes.mdx +++ b/docs/sandboxes/manage-sandboxes.mdx @@ -400,10 +400,14 @@ with SandboxClient.from_active_cluster() as client: sandbox = client.create(workspace="default", name="deep-research-1", labels={"env": "dev", "team": "platform"}) assert sandbox.labels["team"] == "platform" - matches = client.list(workspace="default", label_selector="env=dev,team=platform") + matches = client.list_all(workspace="default", label_selector="env=dev,team=platform") assert sandbox.id in {s.id for s in matches} ``` +Python SDK `list` methods return a lazy `Pager` whose iteration yields one +`Page` per gateway request. Use `list_all` only when you want to exhaust the +collection; pass `page_token` to resume from a token saved from an earlier page. + Create reusable sandbox templates through the Python SDK when several runs should share the same workload shape: @@ -431,7 +435,7 @@ from openshell import ClientCredentialsAuth, SandboxClient auth = ClientCredentialsAuth(client_secret=lambda: load_secret()) with SandboxClient.from_active_cluster(client_credentials=auth) as client: - sandboxes = client.list(workspace="default") + sandboxes = client.list_all(workspace="default") ``` ## Expose Long Running Services diff --git a/docs/sandboxes/manage-workspaces.mdx b/docs/sandboxes/manage-workspaces.mdx index 635fa1e7e3..5bff9755e9 100644 --- a/docs/sandboxes/manage-workspaces.mdx +++ b/docs/sandboxes/manage-workspaces.mdx @@ -181,8 +181,9 @@ explicit: | `global: true` | Omit `workspace_scope` | The Rust and Python SDKs expose separate all-workspaces list methods. The Go -SDK uses `ListAll`, and the TypeScript SDK uses a discriminated option type, so -a caller cannot select a named workspace and all workspaces in one typed call. +SDK passes `AllWorkspaces: true` in `ListOptions` to `ListAll`, and the +TypeScript SDK uses a discriminated option type, so a caller cannot select a +named workspace and all workspaces in one typed call. The TUI starts in the `default` workspace and sends that named selector explicitly. Its all-workspaces view sends the marker instead. diff --git a/e2e/python/oidc/oidc_auth_test.py b/e2e/python/oidc/oidc_auth_test.py index 06b5199a6f..8b0a1f70f9 100644 --- a/e2e/python/oidc/oidc_auth_test.py +++ b/e2e/python/oidc/oidc_auth_test.py @@ -258,7 +258,7 @@ def test_ci_token_can_list_sandboxes(self) -> None: metadata=admin_md, ) try: - ci_client.list(workspace="default") + ci_client.list_all(workspace="default") finally: ci_client.close() with contextlib.suppress(grpc.RpcError): diff --git a/e2e/python/test_sandbox_api.py b/e2e/python/test_sandbox_api.py index 954eb228de..5407bdf69e 100644 --- a/e2e/python/test_sandbox_api.py +++ b/e2e/python/test_sandbox_api.py @@ -211,10 +211,10 @@ def test_sandbox_labels_and_selectors(sandbox_client: SandboxClient) -> None: # A specific selector filters to exactly the primary sandbox. assert { - s.name for s in sandbox_client.list(workspace="default", label_selector=primary_selector) + s.name for s in sandbox_client.list_all(workspace="default", label_selector=primary_selector) } == {job_a} # The shared group label returns both. - assert {s.name for s in sandbox_client.list(workspace="default", label_selector=group_selector)} == { + assert {s.name for s in sandbox_client.list_all(workspace="default", label_selector=group_selector)} == { job_a, job_b, } @@ -223,7 +223,7 @@ def test_sandbox_labels_and_selectors(sandbox_client: SandboxClient) -> None: assert sandbox_client.delete(job_a, workspace="default") sandbox_client.wait_deleted(job_a, workspace="default") created.remove(job_a) - assert {s.name for s in sandbox_client.list(workspace="default", label_selector=group_selector)} == { + assert {s.name for s in sandbox_client.list_all(workspace="default", label_selector=group_selector)} == { job_b } @@ -231,7 +231,7 @@ def test_sandbox_labels_and_selectors(sandbox_client: SandboxClient) -> None: assert sandbox_client.delete(job_b, workspace="default") sandbox_client.wait_deleted(job_b, workspace="default") created.remove(job_b) - assert not sandbox_client.list(workspace="default", label_selector=group_selector) + assert not sandbox_client.list_all(workspace="default", label_selector=group_selector) finally: for name in created: with contextlib.suppress(Exception): diff --git a/e2e/python/test_workspace_api.py b/e2e/python/test_workspace_api.py index 01be5c341e..1fb33123eb 100644 --- a/e2e/python/test_workspace_api.py +++ b/e2e/python/test_workspace_api.py @@ -52,7 +52,7 @@ def test_workspace_list_includes_created(workspace_client: WorkspaceClient) -> N try: workspace_client.create(name) - names = {ws.name for ws in workspace_client.list()} + names = {ws.name for ws in workspace_client.list_all()} assert name in names assert "default" in names finally: diff --git a/python/openshell/__init__.py b/python/openshell/__init__.py index f20b76e9c2..775e9f7b16 100644 --- a/python/openshell/__init__.py +++ b/python/openshell/__init__.py @@ -9,6 +9,8 @@ ClientCredentialsAuth, ExecChunk, ExecResult, + Page, + Pager, Sandbox, SandboxClient, SandboxError, @@ -33,6 +35,8 @@ "ClientCredentialsAuth", "ExecChunk", "ExecResult", + "Page", + "Pager", "Sandbox", "SandboxClient", "SandboxError", diff --git a/python/openshell/sandbox.py b/python/openshell/sandbox.py index cfffdf6307..931fa1e2ab 100644 --- a/python/openshell/sandbox.py +++ b/python/openshell/sandbox.py @@ -17,7 +17,7 @@ import time from collections import namedtuple from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Never, SupportsIndex, cast +from typing import TYPE_CHECKING, Any, Generic, Never, SupportsIndex, TypeVar, cast from urllib.parse import urlparse import grpc @@ -35,6 +35,37 @@ ) _OAUTH_MAX_RESPONSE_BYTES = 1 << 20 +T = TypeVar("T") + + +@dataclass(frozen=True) +class Page(Generic[T]): + """One response page from a list operation.""" + + items: builtins.list[T] + next_page_token: str + + +class Pager(Generic[T]): + """Lazy, single-pass iterator that fetches one RPC page per advance.""" + + def __init__(self, fetch: Callable[[str], Page[T]], page_token: str = "") -> None: + self._fetch = fetch + self._page_token: str | None = page_token + + def __iter__(self) -> Pager[T]: + return self + + def __next__(self) -> Page[T]: + if self._page_token is None: + raise StopIteration + page = self._fetch(self._page_token) + self._page_token = page.next_page_token or None + return page + + def all(self) -> builtins.list[T]: + """Consume the pager and collect every remaining item.""" + return [item for page in self for item in page.items] def _workspace_scope(workspace: str) -> datamodel_pb2.WorkspaceSelector: @@ -820,47 +851,77 @@ def list( *, workspace: str, page_size: int = 100, + page_token: str = "", label_selector: str | None = None, - ) -> builtins.list[SandboxRef]: - sandboxes: builtins.list[SandboxRef] = [] - page_token = "" - while True: + ) -> Pager[SandboxRef]: + def fetch(token: str) -> Page[SandboxRef]: response = self._stub.ListSandboxes( openshell_pb2.ListSandboxesRequest( workspace_scope=_workspace_scope(workspace), page_size=page_size, - page_token=page_token, + page_token=token, label_selector=label_selector or "", ), timeout=self._timeout, ) - sandboxes.extend(_sandbox_ref(item) for item in response.sandboxes) - if not getattr(response, "next_page_token", ""): - return sandboxes - page_token = response.next_page_token + return Page( + items=[_sandbox_ref(item) for item in response.sandboxes], + next_page_token=getattr(response, "next_page_token", ""), + ) - def list_for_all_workspaces( + return Pager(fetch, page_token) + + def list_all( self, *, + workspace: str, page_size: int = 100, + page_token: str = "", label_selector: str | None = None, ) -> builtins.list[SandboxRef]: - sandboxes: builtins.list[SandboxRef] = [] - page_token = "" - while True: + return self.list( + workspace=workspace, + page_size=page_size, + page_token=page_token, + label_selector=label_selector, + ).all() + + def list_for_all_workspaces( + self, + *, + page_size: int = 100, + page_token: str = "", + label_selector: str | None = None, + ) -> Pager[SandboxRef]: + def fetch(token: str) -> Page[SandboxRef]: response = self._stub.ListSandboxes( openshell_pb2.ListSandboxesRequest( workspace_scope=_all_workspaces_scope(), page_size=page_size, - page_token=page_token, + page_token=token, label_selector=label_selector or "", ), timeout=self._timeout, ) - sandboxes.extend(_sandbox_ref(item) for item in response.sandboxes) - if not getattr(response, "next_page_token", ""): - return sandboxes - page_token = response.next_page_token + return Page( + items=[_sandbox_ref(item) for item in response.sandboxes], + next_page_token=getattr(response, "next_page_token", ""), + ) + + return Pager(fetch, page_token) + + def list_all_for_all_workspaces( + self, + *, + page_size: int = 100, + page_token: str = "", + label_selector: str | None = None, + ) -> builtins.list[SandboxRef]: + return self.list_for_all_workspaces( + page_size=page_size, + page_token=page_token, + label_selector=label_selector, + ).all() def list_ids( self, @@ -871,7 +932,7 @@ def list_ids( ) -> builtins.list[str]: return [ item.id - for item in self.list( + for item in self.list_all( workspace=workspace, page_size=page_size, label_selector=label_selector, @@ -886,7 +947,7 @@ def list_ids_for_all_workspaces( ) -> builtins.list[str]: return [ item.id - for item in self.list_for_all_workspaces( + for item in self.list_all_for_all_workspaces( page_size=page_size, label_selector=label_selector, ) @@ -1192,47 +1253,77 @@ def list( *, workspace: str, page_size: int = 100, + page_token: str = "", label_selector: str = "", - ) -> builtins.list[openshell_pb2.SandboxWorkloadTemplate]: - templates: builtins.list[openshell_pb2.SandboxWorkloadTemplate] = [] - page_token = "" - while True: + ) -> Pager[openshell_pb2.SandboxWorkloadTemplate]: + def fetch(token: str) -> Page[openshell_pb2.SandboxWorkloadTemplate]: response = self._stub.ListSandboxTemplates( openshell_pb2.ListSandboxTemplatesRequest( workspace_scope=_workspace_scope(workspace), page_size=page_size, - page_token=page_token, + page_token=token, label_selector=label_selector, ), timeout=self._timeout, ) - templates.extend(response.templates) - if not getattr(response, "next_page_token", ""): - return templates - page_token = response.next_page_token + return Page( + items=list(response.templates), + next_page_token=getattr(response, "next_page_token", ""), + ) - def list_for_all_workspaces( + return Pager(fetch, page_token) + + def list_all( self, *, + workspace: str, page_size: int = 100, + page_token: str = "", label_selector: str = "", ) -> builtins.list[openshell_pb2.SandboxWorkloadTemplate]: - templates: builtins.list[openshell_pb2.SandboxWorkloadTemplate] = [] - page_token = "" - while True: + return self.list( + workspace=workspace, + page_size=page_size, + page_token=page_token, + label_selector=label_selector, + ).all() + + def list_for_all_workspaces( + self, + *, + page_size: int = 100, + page_token: str = "", + label_selector: str = "", + ) -> Pager[openshell_pb2.SandboxWorkloadTemplate]: + def fetch(token: str) -> Page[openshell_pb2.SandboxWorkloadTemplate]: response = self._stub.ListSandboxTemplates( openshell_pb2.ListSandboxTemplatesRequest( workspace_scope=_all_workspaces_scope(), page_size=page_size, - page_token=page_token, + page_token=token, label_selector=label_selector, ), timeout=self._timeout, ) - templates.extend(response.templates) - if not getattr(response, "next_page_token", ""): - return templates - page_token = response.next_page_token + return Page( + items=list(response.templates), + next_page_token=getattr(response, "next_page_token", ""), + ) + + return Pager(fetch, page_token) + + def list_all_for_all_workspaces( + self, + *, + page_size: int = 100, + page_token: str = "", + label_selector: str = "", + ) -> builtins.list[openshell_pb2.SandboxWorkloadTemplate]: + return self.list_for_all_workspaces( + page_size=page_size, + page_token=page_token, + label_selector=label_selector, + ).all() def delete(self, name: str, *, workspace: str) -> bool: response = self._stub.DeleteSandboxTemplate( @@ -1297,23 +1388,37 @@ def list( self, *, page_size: int = 100, + page_token: str = "", label_selector: str | None = None, - ) -> builtins.list[WorkspaceRef]: - workspaces: builtins.list[WorkspaceRef] = [] - page_token = "" - while True: + ) -> Pager[WorkspaceRef]: + def fetch(token: str) -> Page[WorkspaceRef]: response = self._stub.ListWorkspaces( openshell_pb2.ListWorkspacesRequest( page_size=page_size, - page_token=page_token, + page_token=token, label_selector=label_selector or "", ), timeout=self._timeout, ) - workspaces.extend(_workspace_ref(ws) for ws in response.workspaces) - if not getattr(response, "next_page_token", ""): - return workspaces - page_token = response.next_page_token + return Page( + items=[_workspace_ref(ws) for ws in response.workspaces], + next_page_token=getattr(response, "next_page_token", ""), + ) + + return Pager(fetch, page_token) + + def list_all( + self, + *, + page_size: int = 100, + page_token: str = "", + label_selector: str | None = None, + ) -> builtins.list[WorkspaceRef]: + return self.list( + page_size=page_size, + page_token=page_token, + label_selector=label_selector, + ).all() def delete(self, name: str) -> bool: response = self._stub.DeleteWorkspace( diff --git a/python/openshell/sandbox_test.py b/python/openshell/sandbox_test.py index e436f714db..0675bc7338 100644 --- a/python/openshell/sandbox_test.py +++ b/python/openshell/sandbox_test.py @@ -23,6 +23,8 @@ _PYTHON_CLOUDPICKLE_BOOTSTRAP, _SANDBOX_PYTHON_BIN, ClientCredentialsAuth, + Page, + Pager, Sandbox, SandboxClient, SandboxError, @@ -2408,7 +2410,7 @@ def test_sandbox_template_client_crud_forwards_requests() -> None: assert stub.get_template_request.name == "gpu-kata" assert _request_workspace(stub.get_template_request) == "default" - listed = client.list( + listed = client.list_all( workspace="default", page_size=50, label_selector="team=runtime" ) assert len(listed) == 1 @@ -2429,7 +2431,7 @@ def test_sandbox_template_list_for_all_workspaces_selects_all() -> None: stub = _FakeSandboxStub() client = _template_client_with_fake_stub(stub) - client.list_for_all_workspaces(page_size=100, label_selector="team=runtime") + client.list_all_for_all_workspaces(page_size=100, label_selector="team=runtime") assert stub.list_template_request is not None assert _request_selects_all_workspaces(stub.list_template_request) @@ -2533,7 +2535,7 @@ def test_list_forwards_label_selector() -> None: stub = _FakeSandboxStub() client = _client_with_fake_stub(stub) - client.list(workspace="default", label_selector="aiq=deep-research") + client.list_all(workspace="default", label_selector="aiq=deep-research") assert stub.list_request is not None assert stub.list_request.label_selector == "aiq=deep-research" @@ -2544,7 +2546,7 @@ def test_list_without_selector_sends_empty_string() -> None: stub = _FakeSandboxStub() client = _client_with_fake_stub(stub) - client.list(workspace="default") + client.list_all(workspace="default") assert stub.list_request is not None assert stub.list_request.label_selector == "" @@ -2559,17 +2561,55 @@ def test_list_follows_continuation_tokens() -> None: ) client = _client_with_fake_stub(stub) - sandboxes = client.list( - workspace="default", page_size=1, label_selector="team=core" - ) - - assert [sandbox.name for sandbox in sandboxes] == ["job-1", "job-2"] + pager = client.list(workspace="default", page_size=1, label_selector="team=core") + + assert stub.list_requests == [] + first = next(pager) + assert [sandbox.name for sandbox in first.items] == ["job-1"] + assert first.next_page_token == "1" + second = next(pager) + assert [sandbox.name for sandbox in second.items] == ["job-2"] + assert second.next_page_token == "" + with pytest.raises(StopIteration): + next(pager) assert len(stub.list_requests) == 2 assert stub.list_requests[0].page_token == "" assert stub.list_requests[1].page_token == "1" assert stub.list_requests[1].label_selector == "team=core" +def test_list_passes_initial_page_token() -> None: + stub = _FakeSandboxStub( + listed_pages=[ + [_make_sandbox_proto("sandbox-1", "skipped")], + [_make_sandbox_proto("sandbox-2", "resumed")], + ] + ) + client = _client_with_fake_stub(stub) + + page = next(client.list(workspace="default", page_token="1")) + + assert [sandbox.name for sandbox in page.items] == ["resumed"] + assert stub.list_requests[0].page_token == "1" + + +def test_pager_retries_same_token_after_fetch_error() -> None: + tokens: list[str] = [] + + def fetch(token: str) -> Page[int]: + tokens.append(token) + if len(tokens) == 1: + raise RuntimeError("temporary failure") + return Page(items=[1], next_page_token="") + + pager = Pager(fetch, page_token="resume") + with pytest.raises(RuntimeError, match="temporary failure"): + next(pager) + + assert next(pager).items == [1] + assert tokens == ["resume", "resume"] + + def test_list_ids_forwards_label_selector() -> None: stub = _FakeSandboxStub(listed=[_make_sandbox_proto("sandbox-1", "job-1")]) client = _client_with_fake_stub(stub) @@ -2804,7 +2844,7 @@ def test_list_for_all_workspaces_sets_flag() -> None: stub = _FakeSandboxStub() client = _client_with_fake_stub(stub) - client.list_for_all_workspaces() + client.list_all_for_all_workspaces() assert stub.list_request is not None assert _request_selects_all_workspaces(stub.list_request) @@ -2815,7 +2855,7 @@ def test_list_with_workspace_passes_workspace() -> None: stub = _FakeSandboxStub() client = _client_with_fake_stub(stub) - client.list(workspace="staging") + client.list_all(workspace="staging") assert stub.list_request is not None assert _request_workspace(stub.list_request) == "staging" diff --git a/sdk/go/README.md b/sdk/go/README.md index 4d09733884..86c6e25479 100644 --- a/sdk/go/README.md +++ b/sdk/go/README.md @@ -76,6 +76,31 @@ if err != nil { fmt.Println(string(result.Stdout)) ``` +### Pagination + +List methods return a lazy pager without issuing a request. `NextPage` fetches +one page with the supplied context, while `ListAll` explicitly exhausts every +page. `PageSize` is a per-request maximum and `PageToken` resumes a prior query. + +```go +pager, err := client.Sandboxes().List("default", v1.ListOptions{PageSize: 100}) +if err != nil { + log.Fatal(err) +} +for { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatal(err) + } + if page == nil { + break + } + for _, sandbox := range page.Items { + fmt.Println(sandbox.Name) + } +} +``` + ### With automatic token refresh For OIDC gateways, use `RefreshableToken` to wrap any `oauth2.TokenSource` with diff --git a/sdk/go/docs/src/api/overview.md b/sdk/go/docs/src/api/overview.md index 0ff01c4ce4..0630c1057a 100644 --- a/sdk/go/docs/src/api/overview.md +++ b/sdk/go/docs/src/api/overview.md @@ -56,9 +56,10 @@ Each interface has a reference page with method signatures and usage examples: ## Common Patterns -All SDK methods follow these conventions: +SDK methods follow these conventions: -- Every method takes `context.Context` as its first argument +- Network operations take `context.Context`; list constructors return a pager, + and each `NextPage` call accepts the request context - Methods that can fail return `(result, error)` -- List methods accept variadic option arguments +- List methods accept variadic options and `ListAll` is the explicit exhaustive path - Errors from the gateway carry a `StatusError` with a typed code (see [Error Handling](../error-handling.md)) diff --git a/sdk/go/docs/src/api/policy.md b/sdk/go/docs/src/api/policy.md index 62f475cd68..e4107ee5b9 100644 --- a/sdk/go/docs/src/api/policy.md +++ b/sdk/go/docs/src/api/policy.md @@ -48,10 +48,11 @@ fmt.Printf("Active version: %d, revision status: %s\n", ## List -List all policy revisions for a sandbox. +`List` returns a lazy pager over policy revisions for one sandbox. Use +`ListAll` to collect every page. ```go -revisions, err := client.Policy().List(ctx, "default", "my-sandbox") +revisions, err := client.Policy().ListAll(ctx, "default", "my-sandbox") if err != nil { log.Fatal(err) } diff --git a/sdk/go/docs/src/api/profiles.md b/sdk/go/docs/src/api/profiles.md index 0cd91d5742..57b3b949c6 100644 --- a/sdk/go/docs/src/api/profiles.md +++ b/sdk/go/docs/src/api/profiles.md @@ -7,10 +7,11 @@ credentials, and model mappings for providers like OpenAI, Anthropic, or custom ## List -List all provider profiles visible to the current user. +`List` returns a lazy pager over visible provider profiles. Use `ListAll` to +collect every page. ```go -profiles, err := client.Providers().Profiles().List(ctx, "default") +profiles, err := client.Providers().Profiles().ListAll(ctx, "default") if err != nil { log.Fatal(err) } diff --git a/sdk/go/docs/src/api/providers.md b/sdk/go/docs/src/api/providers.md index f9b1a8c967..3a21ca96b0 100644 --- a/sdk/go/docs/src/api/providers.md +++ b/sdk/go/docs/src/api/providers.md @@ -42,12 +42,12 @@ fmt.Println("Provider type:", provider.Type) ## List -List all registered providers. The SDK follows gateway continuation tokens -automatically; `PageSize` controls each request. +`List` returns a lazy pager over registered providers. `ListAll` follows every +continuation token; `PageSize` controls each request. ```go // List all providers -providers, err := client.Providers().List(ctx, "default") +providers, err := client.Providers().ListAll(ctx, "default") if err != nil { log.Fatal(err) } @@ -56,12 +56,14 @@ for _, p := range providers { } // With a smaller page size -providers, err = client.Providers().List(ctx, "default", v1.ListOptions{ +providers, err = client.Providers().ListAll(ctx, "default", v1.ListOptions{ PageSize: 10, }) // Platform Admin only: list across all workspaces -allProviders, err := client.Providers().ListAll(ctx) +allProviders, err := client.Providers().ListAll(ctx, "", v1.ListOptions{ + AllWorkspaces: true, +}) ``` ## Update diff --git a/sdk/go/docs/src/api/sandbox-templates.md b/sdk/go/docs/src/api/sandbox-templates.md index e955dc1f29..764014400c 100644 --- a/sdk/go/docs/src/api/sandbox-templates.md +++ b/sdk/go/docs/src/api/sandbox-templates.md @@ -89,16 +89,16 @@ fmt.Println(template.Spec.Workload.Image) ## List -Lists every matching template in one workspace or across all workspaces. The -SDK follows gateway continuation tokens automatically. +`List` returns a lazy pager over matching templates in one workspace or across +all workspaces. Use `ListAll` to follow every continuation token automatically. ```go -templates, err := client.SandboxTemplates().List(ctx, "default", v1.ListOptions{ +templates, err := client.SandboxTemplates().ListAll(ctx, "default", v1.ListOptions{ PageSize: 50, }) -allTemplates, err := client.SandboxTemplates().ListAll(ctx, v1.ListOptions{ - PageSize: 50, +allTemplates, err := client.SandboxTemplates().ListAll(ctx, "", v1.ListOptions{ + AllWorkspaces: true, }) ``` diff --git a/sdk/go/docs/src/api/sandboxes.md b/sdk/go/docs/src/api/sandboxes.md index e9ab530690..21ee14a1bf 100644 --- a/sdk/go/docs/src/api/sandboxes.md +++ b/sdk/go/docs/src/api/sandboxes.md @@ -57,21 +57,27 @@ fmt.Println(sb.Status.Phase) // "Ready", "Provisioning", etc. ## List -Lists every matching sandbox, following gateway continuation tokens -automatically. `PageSize` controls the size of each request. +`List` constructs a lazy pager; `NextPage` fetches one page at a time. +`PageSize` controls each request, and `ListAll` explicitly exhausts the pager. ```go // List all sandboxes -sandboxes, err := client.Sandboxes().List(ctx, "default") +sandboxes, err := client.Sandboxes().ListAll(ctx, "default") + +// Process one page at a time +pages, err := client.Sandboxes().List("default", v1.ListOptions{PageSize: 10}) +page, err := pages.NextPage(ctx) // With a page size and label filtering -sandboxes, err := client.Sandboxes().List(ctx, "default", v1.ListOptions{ +sandboxes, err := client.Sandboxes().ListAll(ctx, "default", v1.ListOptions{ PageSize: 10, LabelSelector: "team=platform", }) // Platform Admin only: list across all workspaces -allSandboxes, err := client.Sandboxes().ListAll(ctx) +allSandboxes, err := client.Sandboxes().ListAll(ctx, "", v1.ListOptions{ + AllWorkspaces: true, +}) ``` ## Delete diff --git a/sdk/go/docs/src/api/services.md b/sdk/go/docs/src/api/services.md index 0c44567d2f..d309f7975f 100644 --- a/sdk/go/docs/src/api/services.md +++ b/sdk/go/docs/src/api/services.md @@ -20,10 +20,11 @@ fmt.Printf("Service available at: %s\n", endpoint.URL) ## List -List all exposed services for a sandbox. +`List` returns a lazy pager over exposed services. Use `ListAll` to collect +every page. ```go -services, err := client.Services().List(ctx, "default", "my-sandbox") +services, err := client.Services().ListAll(ctx, "default", "my-sandbox") if err != nil { log.Fatal(err) } @@ -32,7 +33,9 @@ for _, svc := range services { } // Platform Admin only: list services across all workspaces -allServices, err := client.Services().ListAll(ctx) +allServices, err := client.Services().ListAll(ctx, "", "", v1.ListOptions{ + AllWorkspaces: true, +}) ``` ## Delete diff --git a/sdk/go/docs/src/architecture.md b/sdk/go/docs/src/architecture.md index c9c6948d80..0a52481118 100644 --- a/sdk/go/docs/src/architecture.md +++ b/sdk/go/docs/src/architecture.md @@ -76,7 +76,7 @@ exec := client.Exec() Some sub-clients have their own sub-clients. `ProviderInterface` exposes `Profiles()` and `Refresh()`: ```go -profiles, err := client.Providers().Profiles().List(ctx, "default") +profiles, err := client.Providers().Profiles().ListAll(ctx, "default") status, err := client.Providers().Refresh().GetStatus(ctx, "default", "openai", "api-key") ``` diff --git a/sdk/go/docs/src/testing.md b/sdk/go/docs/src/testing.md index af1851ae83..138738ab19 100644 --- a/sdk/go/docs/src/testing.md +++ b/sdk/go/docs/src/testing.md @@ -66,7 +66,7 @@ client.AddProvider(&types.Provider{ }) // List returns the seeded provider -providers, _ := client.Providers().List(ctx, "default") +providers, _ := client.Providers().ListAll(ctx, "default") // len(providers) == 1 ``` diff --git a/sdk/go/openshell/v1/doc.go b/sdk/go/openshell/v1/doc.go index 900d86c643..ecf995dd43 100644 --- a/sdk/go/openshell/v1/doc.go +++ b/sdk/go/openshell/v1/doc.go @@ -5,8 +5,9 @@ // // The SDK follows the Kubernetes client-go sub-client pattern: a single Client // provides typed accessors for each resource domain (Sandboxes, Providers, Exec, -// Files, Health, Services, SSH, TCP, Config, Policy, and Workspaces). All operations accept a context.Context and return idiomatic -// Go types. Proto-generated types never appear in the public API. +// Files, Health, Services, SSH, TCP, Config, Policy, and Workspaces). Network +// operations accept a context.Context and return idiomatic Go types. +// Proto-generated types never appear in the public API. // // # Quick Start // @@ -34,6 +35,28 @@ // log.Fatal(err) // } // +// # Pagination +// +// List methods construct a lazy Pager without issuing an RPC. Each NextPage +// call fetches one page; ListAll is the explicit exhaustive convenience. +// +// pages, err := client.Sandboxes().List("default", v1.ListOptions{PageSize: 100}) +// if err != nil { +// log.Fatal(err) +// } +// for { +// page, err := pages.NextPage(ctx) +// if err != nil { +// log.Fatal(err) +// } +// if page == nil { +// break +// } +// for _, sandbox := range page.Items { +// fmt.Println(sandbox.Name) +// } +// } +// // # Command Execution // // result, err := client.Exec().Run(ctx, "default", sandbox.Name, []string{"echo", "hello"}, v1.ExecOptions{}) @@ -86,7 +109,7 @@ // } // fmt.Printf("Service URL: %s\n", endpoint.URL) // -// endpoints, err := client.Services().List(ctx, "default", "my-sandbox") +// endpoints, err := client.Services().ListAll(ctx, "default", "my-sandbox") // if err != nil { // log.Fatal(err) // } @@ -98,7 +121,7 @@ // // List available provider profiles and import new ones: // -// profiles, err := client.Providers().Profiles().List(ctx, "default") +// profiles, err := client.Providers().Profiles().ListAll(ctx, "default") // if err != nil { // log.Fatal(err) // } @@ -314,7 +337,7 @@ // // Read a policy back from revision history: // -// revisions, err := client.Policy().List(ctx, "default") +// revisions, err := client.Policy().ListAll(ctx, "default", "my-sandbox") // if err != nil { // log.Fatal(err) // } @@ -328,7 +351,7 @@ // // List gateway-global policy revisions (no sandbox name or workspace needed): // -// revisions, err := client.Policy().List(ctx, "", v1.WithListGlobal(true)) +// revisions, err := client.Policy().ListAll(ctx, "", "", v1.WithListGlobal(true)) // if err != nil { // log.Fatal(err) // } @@ -359,7 +382,7 @@ // } // fmt.Printf("Workspace %s created (phase: %s)\n", ws.Name, ws.Phase) // -// workspaces, err := client.Workspaces().List(ctx) +// workspaces, err := client.Workspaces().ListAll(ctx) // if err != nil { // log.Fatal(err) // } @@ -378,7 +401,7 @@ // } // fmt.Printf("Added %s as %s\n", member.PrincipalSubject, member.Role) // -// members, err := client.Workspaces().ListMembers(ctx, "team-alpha") +// members, err := client.Workspaces().ListAllMembers(ctx, "team-alpha") // if err != nil { // log.Fatal(err) // } diff --git a/sdk/go/openshell/v1/example_fake_test.go b/sdk/go/openshell/v1/example_fake_test.go index 94c9ccbd7c..32a2c262ff 100644 --- a/sdk/go/openshell/v1/example_fake_test.go +++ b/sdk/go/openshell/v1/example_fake_test.go @@ -55,7 +55,7 @@ func ExampleNewClient_addProvider() { ctx := context.Background() - providers, err := client.Providers().List(ctx, "default") + providers, err := client.Providers().ListAll(ctx, "default") if err != nil { log.Fatal(err) } diff --git a/sdk/go/openshell/v1/example_test.go b/sdk/go/openshell/v1/example_test.go index eb96fe8c11..d0f6e115c7 100644 --- a/sdk/go/openshell/v1/example_test.go +++ b/sdk/go/openshell/v1/example_test.go @@ -62,7 +62,7 @@ func ExampleClient_Providers() { } // List all providers - providers, err := client.Providers().List(ctx, "default") + providers, err := client.Providers().ListAll(ctx, "default") if err != nil { log.Fatal(err) } diff --git a/sdk/go/openshell/v1/exec_client_test.go b/sdk/go/openshell/v1/exec_client_test.go index 53acc1e8bc..183940ec8b 100644 --- a/sdk/go/openshell/v1/exec_client_test.go +++ b/sdk/go/openshell/v1/exec_client_test.go @@ -37,10 +37,10 @@ func (r *stubSandboxResolver) Get(_ context.Context, _, name string) (*Sandbox, func (r *stubSandboxResolver) Create(context.Context, string, string, *SandboxSpec, map[string]string, ...CreateOptions) (*Sandbox, error) { panic("not implemented") } -func (r *stubSandboxResolver) List(context.Context, string, ...ListOptions) ([]*Sandbox, error) { +func (r *stubSandboxResolver) List(string, ...ListOptions) (*Pager[*Sandbox], error) { panic("not implemented") } -func (r *stubSandboxResolver) ListAll(context.Context, ...ListOptions) ([]*Sandbox, error) { +func (r *stubSandboxResolver) ListAll(context.Context, string, ...ListOptions) ([]*Sandbox, error) { panic("not implemented") } func (r *stubSandboxResolver) Delete(context.Context, string, string) error { diff --git a/sdk/go/openshell/v1/fake/fake_test.go b/sdk/go/openshell/v1/fake/fake_test.go index d749b1eac4..dcc494d283 100644 --- a/sdk/go/openshell/v1/fake/fake_test.go +++ b/sdk/go/openshell/v1/fake/fake_test.go @@ -152,7 +152,7 @@ func TestFakeClient_AddSandbox_InList(t *testing.T) { fc.AddSandbox("default", &types.Sandbox{Name: "sb-1"}) fc.AddSandbox("default", &types.Sandbox{Name: "sb-2"}) - list, err := fc.Sandboxes().List(ctx, "default") + list, err := fc.Sandboxes().ListAll(ctx, "default") require.NoError(t, err) assert.Len(t, list, 2) } diff --git a/sdk/go/openshell/v1/fake/pager.go b/sdk/go/openshell/v1/fake/pager.go new file mode 100644 index 0000000000..fed00135d5 --- /dev/null +++ b/sdk/go/openshell/v1/fake/pager.go @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package fake + +import ( + "context" + "strconv" + + v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1" + "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types" +) + +func newSlicePager[T any](items []T, pageSize int, pageToken string) (*v1.Pager[T], error) { + if pageSize < 0 { + return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "page size must not be negative"} + } + if pageSize == 0 { + pageSize = 100 + } + if _, err := parsePageOffset(pageToken, len(items)); err != nil { + return nil, err + } + return v1.NewPager(pageToken, func(_ context.Context, token string) (*v1.Page[T], error) { + start, err := parsePageOffset(token, len(items)) + if err != nil { + return nil, err + } + end := min(start+pageSize, len(items)) + next := "" + if end < len(items) { + next = strconv.Itoa(end) + } + pageItems := append(make([]T, 0, end-start), items[start:end]...) + return &v1.Page[T]{Items: pageItems, NextPageToken: next}, nil + }), nil +} + +func parsePageOffset(token string, length int) (int, error) { + if token == "" { + return 0, nil + } + offset, err := strconv.Atoi(token) + if err != nil || offset < 0 || offset > length { + return 0, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "invalid page token"} + } + return offset, nil +} diff --git a/sdk/go/openshell/v1/fake/policy.go b/sdk/go/openshell/v1/fake/policy.go index e69c7bad8e..323b17faa6 100644 --- a/sdk/go/openshell/v1/fake/policy.go +++ b/sdk/go/openshell/v1/fake/policy.go @@ -7,7 +7,6 @@ import ( "context" "maps" "slices" - "strings" "sync" v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1" @@ -174,7 +173,7 @@ func (c *fakePolicyClient) GetStatus(_ context.Context, workspace, sandboxName s // List returns policy revisions. When the global option is set, it returns // global revisions; otherwise it returns all sandbox-scoped revisions for the // given workspace. -func (c *fakePolicyClient) List(_ context.Context, workspace string, opts ...v1.ListPolicyOption) ([]types.SandboxPolicyRevision, error) { +func (c *fakePolicyClient) List(workspace, sandboxName string, opts ...v1.ListPolicyOption) (*v1.Pager[types.SandboxPolicyRevision], error) { if c.closedFunc() { return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} } @@ -182,6 +181,9 @@ func (c *fakePolicyClient) List(_ context.Context, workspace string, opts ...v1. if cfg.PageSize() < 0 { return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "page size must not be negative"} } + if !cfg.Global() && sandboxName == "" { + return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "sandbox name must not be empty"} + } c.mu.RLock() defer c.mu.RUnlock() @@ -190,17 +192,7 @@ func (c *fakePolicyClient) List(_ context.Context, workspace string, opts ...v1. if cfg.Global() { revisions = slices.Clone(c.globalRevisions) } else { - // Collect all revisions for sandboxes in this workspace. - prefix := workspace + "/" - for key, revs := range c.sandboxRevisions { - if strings.HasPrefix(key, prefix) { - revisions = append(revisions, revs...) - } - } - } - - if len(revisions) == 0 { - return nil, nil + revisions = slices.Clone(c.sandboxRevisions[workspace+"/"+sandboxName]) } // Sort by version for deterministic ordering (map iteration is random). @@ -218,7 +210,15 @@ func (c *fakePolicyClient) List(_ context.Context, workspace string, opts ...v1. for i, r := range revisions { result[i] = copySandboxPolicyRevision(r) } - return result, nil + return newSlicePager(result, int(cfg.PageSize()), cfg.PageToken()) +} + +func (c *fakePolicyClient) ListAll(ctx context.Context, workspace, sandboxName string, opts ...v1.ListPolicyOption) ([]types.SandboxPolicyRevision, error) { + pager, err := c.List(workspace, sandboxName, opts...) + if err != nil { + return nil, err + } + return pager.All(ctx) } // EditDraftChunk returns Unimplemented. diff --git a/sdk/go/openshell/v1/fake/policy_test.go b/sdk/go/openshell/v1/fake/policy_test.go index d2ff4e3b0e..924bd2fab6 100644 --- a/sdk/go/openshell/v1/fake/policy_test.go +++ b/sdk/go/openshell/v1/fake/policy_test.go @@ -64,11 +64,12 @@ func TestFakePolicy_GetStatus_EmptyReturnsNotFound(t *testing.T) { assert.True(t, types.IsNotFound(err)) } -func TestFakePolicy_List_EmptyReturnsNil(t *testing.T) { +func TestFakePolicy_List_EmptyReturnsNonNil(t *testing.T) { c := newFakePolicyClient(func() bool { return false }) - revisions, err := c.List(context.Background(), "default") + revisions, err := c.ListAll(context.Background(), "default", "sb-1") require.NoError(t, err) - assert.Nil(t, revisions) + assert.NotNil(t, revisions) + assert.Empty(t, revisions) } func TestFakePolicy_EditDraftChunk_ReturnsUnimplemented(t *testing.T) { @@ -96,7 +97,7 @@ func TestFakePolicy_List_Global(t *testing.T) { c.AddRevision("default", "sb-1", types.SandboxPolicyRevision{Version: 1, PolicyHash: "sha256:sb-v1", Status: types.PolicyLoadStatusLoaded}) // List global revisions. - revisions, err := c.List(context.Background(), "", types.WithListGlobal(true)) + revisions, err := c.ListAll(context.Background(), "", "", types.WithListGlobal(true)) require.NoError(t, err) require.Len(t, revisions, 2) assert.Equal(t, uint32(1), revisions[0].Version) @@ -113,7 +114,7 @@ func TestFakePolicy_List_Sandbox(t *testing.T) { c.AddRevision("default", "sb-1", types.SandboxPolicyRevision{Version: 2, PolicyHash: "sha256:sb-v2", Status: types.PolicyLoadStatusPending}) // List sandbox-scoped revisions (no global flag). - revisions, err := c.List(context.Background(), "default") + revisions, err := c.ListAll(context.Background(), "default", "sb-1") require.NoError(t, err) require.Len(t, revisions, 2) assert.Equal(t, "sha256:sb-v1", revisions[0].PolicyHash) @@ -127,9 +128,10 @@ func TestFakePolicy_List_NoIsolationCrossContamination(t *testing.T) { c.AddRevision("default", "sb-1", types.SandboxPolicyRevision{Version: 1, PolicyHash: "sha256:sb-v1"}) // Global list returns empty (no global revisions seeded). - revisions, err := c.List(context.Background(), "", types.WithListGlobal(true)) + revisions, err := c.ListAll(context.Background(), "", "", types.WithListGlobal(true)) require.NoError(t, err) - assert.Nil(t, revisions) + assert.NotNil(t, revisions) + assert.Empty(t, revisions) } func TestFakePolicy_List_GlobalPageSizeStillReturnsAll(t *testing.T) { @@ -139,7 +141,7 @@ func TestFakePolicy_List_GlobalPageSizeStillReturnsAll(t *testing.T) { c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 2}) c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 3}) - revisions, err := c.List(context.Background(), "", types.WithListGlobal(true), types.WithPageSize(2)) + revisions, err := c.ListAll(context.Background(), "", "", types.WithListGlobal(true), types.WithPageSize(2)) require.NoError(t, err) require.Len(t, revisions, 3) assert.Equal(t, uint32(1), revisions[0].Version) @@ -229,14 +231,14 @@ func TestFakePolicy_DeepCopyWithPolicy(t *testing.T) { ctx := context.Background() // Get global revision and mutate it. - revisions, err := fc.Policy().List(ctx, "", types.WithListGlobal(true)) + revisions, err := fc.Policy().ListAll(ctx, "", "", types.WithListGlobal(true)) require.NoError(t, err) require.Len(t, revisions, 1) require.NotNil(t, revisions[0].Policy) revisions[0].Policy.NetworkPolicies["rule-1"] = types.NetworkPolicyRule{Name: "mutated"} // Verify internal state is not corrupted. - revisions2, err := fc.Policy().List(ctx, "", types.WithListGlobal(true)) + revisions2, err := fc.Policy().ListAll(ctx, "", "", types.WithListGlobal(true)) require.NoError(t, err) assert.Equal(t, "rule-1", revisions2[0].Policy.NetworkPolicies["rule-1"].Name) @@ -249,7 +251,7 @@ func TestFakePolicy_DeepCopyWithPolicy(t *testing.T) { func TestFakePolicy_List_ClosedReturnsUnavailable(t *testing.T) { c := newFakePolicyClient(func() bool { return true }) - _, err := c.List(context.Background(), "", types.WithListGlobal(true)) + _, err := c.ListAll(context.Background(), "", "", types.WithListGlobal(true)) require.Error(t, err) assert.True(t, types.IsUnavailable(err)) } diff --git a/sdk/go/openshell/v1/fake/profile.go b/sdk/go/openshell/v1/fake/profile.go index 067a62c627..b8298ee00d 100644 --- a/sdk/go/openshell/v1/fake/profile.go +++ b/sdk/go/openshell/v1/fake/profile.go @@ -22,13 +22,21 @@ func newFakeProfileClient(closedFunc func() bool) *fakeProfileClient { } // List returns Unimplemented. -func (c *fakeProfileClient) List(_ context.Context, _ string, _ ...v1.ListOptions) ([]*types.ProviderProfile, error) { +func (c *fakeProfileClient) List(_ string, _ ...v1.ListOptions) (*v1.Pager[*types.ProviderProfile], error) { if c.closedFunc() { return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} } return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "List is not supported by the fake client"} } +// ListAll returns Unimplemented. +func (c *fakeProfileClient) ListAll(_ context.Context, _ string, _ ...v1.ListOptions) ([]*types.ProviderProfile, error) { + if c.closedFunc() { + return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} + } + return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "ListAll is not supported by the fake client"} +} + // Get returns Unimplemented. func (c *fakeProfileClient) Get(_ context.Context, _, _ string) (*types.ProviderProfile, error) { if c.closedFunc() { diff --git a/sdk/go/openshell/v1/fake/profile_test.go b/sdk/go/openshell/v1/fake/profile_test.go index a0698c1f0b..b22ed9709d 100644 --- a/sdk/go/openshell/v1/fake/profile_test.go +++ b/sdk/go/openshell/v1/fake/profile_test.go @@ -17,7 +17,7 @@ import ( func TestFakeProfile_List_ReturnsUnimplemented(t *testing.T) { c := newFakeProfileClient(func() bool { return false }) - _, err := c.List(context.Background(), "default") + _, err := c.ListAll(context.Background(), "default") require.Error(t, err) assert.True(t, types.IsUnimplemented(err)) } @@ -59,7 +59,7 @@ func TestFakeProfile_Delete_ReturnsUnimplemented(t *testing.T) { func TestFakeProfile_List_ClosedReturnsUnavailable(t *testing.T) { c := newFakeProfileClient(func() bool { return true }) - _, err := c.List(context.Background(), "default") + _, err := c.ListAll(context.Background(), "default") require.Error(t, err) assert.True(t, types.IsUnavailable(err)) } diff --git a/sdk/go/openshell/v1/fake/provider.go b/sdk/go/openshell/v1/fake/provider.go index 7ba0345880..2fd466f054 100644 --- a/sdk/go/openshell/v1/fake/provider.go +++ b/sdk/go/openshell/v1/fake/provider.go @@ -111,20 +111,28 @@ func (c *fakeProviderClient) Get(_ context.Context, workspace, name string) (*ty return c.store.Get(workspace, name) } -// List returns all providers. ListOptions are accepted for interface -// compatibility but filtering is not implemented. -func (c *fakeProviderClient) List(_ context.Context, workspace string, _ ...v1.ListOptions) ([]*types.Provider, error) { +// List returns a lazy pager over providers. Filtering is not implemented. +func (c *fakeProviderClient) List(workspace string, opts ...v1.ListOptions) (*v1.Pager[*types.Provider], error) { if c.closedFunc() { return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} } - return c.store.List(workspace), nil + var options v1.ListOptions + if len(opts) > 0 { + options = opts[0] + } + items := c.store.List(workspace) + if len(opts) > 0 && opts[0].AllWorkspaces { + items = c.store.ListAll() + } + return newSlicePager(items, options.PageSize, options.PageToken) } -func (c *fakeProviderClient) ListAll(_ context.Context, _ ...v1.ListOptions) ([]*types.Provider, error) { - if c.closedFunc() { - return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} +func (c *fakeProviderClient) ListAll(ctx context.Context, workspace string, opts ...v1.ListOptions) ([]*types.Provider, error) { + pager, err := c.List(workspace, opts...) + if err != nil { + return nil, err } - return c.store.ListAll(), nil + return pager.All(ctx) } // Update replaces an existing provider's data. ResourceVersion is diff --git a/sdk/go/openshell/v1/fake/provider_test.go b/sdk/go/openshell/v1/fake/provider_test.go index 4bc6122c65..df3d1cb470 100644 --- a/sdk/go/openshell/v1/fake/provider_test.go +++ b/sdk/go/openshell/v1/fake/provider_test.go @@ -83,7 +83,7 @@ func TestProvider_List_Empty(t *testing.T) { pc := newTestProviderClient() ctx := context.Background() - list, err := pc.List(ctx, "default") + list, err := pc.ListAll(ctx, "default") require.NoError(t, err) assert.Empty(t, list) } @@ -95,7 +95,7 @@ func TestProvider_List(t *testing.T) { _, _ = pc.Create(ctx, "default", &types.Provider{Name: "openai", Type: "openai"}) _, _ = pc.Create(ctx, "default", &types.Provider{Name: "anthropic", Type: "anthropic"}) - list, err := pc.List(ctx, "default") + list, err := pc.ListAll(ctx, "default") require.NoError(t, err) assert.Len(t, list, 2) } @@ -265,7 +265,7 @@ func TestProvider_ConcurrentCreateGetListDeleteEnsure(_ *testing.T) { p := &types.Provider{Name: name, Type: "test"} _, _ = pc.Create(ctx, "default", p) _, _ = pc.Get(ctx, "default", name) - _, _ = pc.List(ctx, "default") + _, _ = pc.ListAll(ctx, "default") _, _ = pc.Update(ctx, "default", &types.Provider{Name: name, Type: "updated"}) _, _ = pc.Ensure(ctx, "default", &types.Provider{Name: name, Type: "ensured"}) _ = pc.Delete(ctx, "default", name) diff --git a/sdk/go/openshell/v1/fake/sandbox.go b/sdk/go/openshell/v1/fake/sandbox.go index 8191594a5c..9f8e6c2287 100644 --- a/sdk/go/openshell/v1/fake/sandbox.go +++ b/sdk/go/openshell/v1/fake/sandbox.go @@ -445,20 +445,28 @@ func (c *fakeSandboxClient) Get(_ context.Context, workspace, name string) (*typ return c.store.Get(workspace, name) } -// List returns all sandboxes. ListOptions are accepted for interface -// compatibility but filtering is not implemented. -func (c *fakeSandboxClient) List(_ context.Context, workspace string, _ ...v1.ListOptions) ([]*types.Sandbox, error) { +// List returns a lazy pager over sandboxes. Filtering is not implemented. +func (c *fakeSandboxClient) List(workspace string, opts ...v1.ListOptions) (*v1.Pager[*types.Sandbox], error) { if c.closedFunc() { return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} } - return c.store.List(workspace), nil + var options v1.ListOptions + if len(opts) > 0 { + options = opts[0] + } + items := c.store.List(workspace) + if len(opts) > 0 && opts[0].AllWorkspaces { + items = c.store.ListAll() + } + return newSlicePager(items, options.PageSize, options.PageToken) } -func (c *fakeSandboxClient) ListAll(_ context.Context, _ ...v1.ListOptions) ([]*types.Sandbox, error) { - if c.closedFunc() { - return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} +func (c *fakeSandboxClient) ListAll(ctx context.Context, workspace string, opts ...v1.ListOptions) ([]*types.Sandbox, error) { + pager, err := c.List(workspace, opts...) + if err != nil { + return nil, err } - return c.store.ListAll(), nil + return pager.All(ctx) } // Stop transitions a sandbox to the Stopped phase. diff --git a/sdk/go/openshell/v1/fake/sandbox_template.go b/sdk/go/openshell/v1/fake/sandbox_template.go index f58f8f6eaf..438bbf532f 100644 --- a/sdk/go/openshell/v1/fake/sandbox_template.go +++ b/sdk/go/openshell/v1/fake/sandbox_template.go @@ -105,15 +105,7 @@ func (c *fakeSandboxTemplateClient) Get(_ context.Context, workspace, name strin return c.store.Get(workspace, name) } -func (c *fakeSandboxTemplateClient) List(_ context.Context, workspace string, opts ...v1.ListOptions) ([]*types.SandboxWorkloadTemplate, error) { - return c.list(workspace, false, opts...) -} - -func (c *fakeSandboxTemplateClient) ListAll(_ context.Context, opts ...v1.ListOptions) ([]*types.SandboxWorkloadTemplate, error) { - return c.list("", true, opts...) -} - -func (c *fakeSandboxTemplateClient) list(workspace string, allWorkspaces bool, opts ...v1.ListOptions) ([]*types.SandboxWorkloadTemplate, error) { +func (c *fakeSandboxTemplateClient) List(workspace string, opts ...v1.ListOptions) (*v1.Pager[*types.SandboxWorkloadTemplate], error) { if c.closedFunc() { return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} } @@ -125,7 +117,7 @@ func (c *fakeSandboxTemplateClient) list(workspace string, allWorkspaces bool, o } } var templates []*types.SandboxWorkloadTemplate - if allWorkspaces { + if options.AllWorkspaces { templates = c.store.ListAll() } else { templates = c.store.List(workspace) @@ -135,7 +127,15 @@ func (c *fakeSandboxTemplateClient) list(workspace string, allWorkspaces bool, o if err != nil { return nil, err } - return templates, nil + return newSlicePager(templates, options.PageSize, options.PageToken) +} + +func (c *fakeSandboxTemplateClient) ListAll(ctx context.Context, workspace string, opts ...v1.ListOptions) ([]*types.SandboxWorkloadTemplate, error) { + pager, err := c.List(workspace, opts...) + if err != nil { + return nil, err + } + return pager.All(ctx) } func (c *fakeSandboxTemplateClient) Delete(_ context.Context, workspace, name string) (bool, error) { diff --git a/sdk/go/openshell/v1/fake/sandbox_template_test.go b/sdk/go/openshell/v1/fake/sandbox_template_test.go index 1df35f8436..19bf8909b6 100644 --- a/sdk/go/openshell/v1/fake/sandbox_template_test.go +++ b/sdk/go/openshell/v1/fake/sandbox_template_test.go @@ -71,7 +71,7 @@ func TestSandboxTemplate_CreateGetListDelete(t *testing.T) { assert.Equal(t, "python:3.12", got.Spec.Workload.Image) assert.Equal(t, "kata", got.Spec.DriverConfig["kubernetes"].(map[string]any)["runtime_class_name"]) - listed, err := tc.List(ctx, "default") + listed, err := tc.ListAll(ctx, "default") require.NoError(t, err) require.Len(t, listed, 1) assert.Equal(t, "gpu-kata", listed[0].Name) @@ -108,7 +108,7 @@ func TestSandboxTemplate_ListAllWorkspaces(t *testing.T) { _, _ = tc.Create(ctx, "default", testSandboxWorkloadTemplate("default-template")) _, _ = tc.Create(ctx, "team-a", testSandboxWorkloadTemplate("team-template")) - listed, err := tc.ListAll(ctx) + listed, err := tc.ListAll(ctx, "default", types.ListOptions{AllWorkspaces: true}) require.NoError(t, err) assert.Len(t, listed, 2) } @@ -132,7 +132,7 @@ func TestSandboxTemplate_ListFiltersByLabelSelector(t *testing.T) { }, }) - listed, err := tc.List(ctx, "default", types.ListOptions{LabelSelector: "team=runtime"}) + listed, err := tc.ListAll(ctx, "default", types.ListOptions{LabelSelector: "team=runtime"}) require.NoError(t, err) require.Len(t, listed, 1) @@ -143,7 +143,7 @@ func TestSandboxTemplate_ListRejectsNegativePagination(t *testing.T) { tc := newTestSandboxTemplateClient() ctx := context.Background() - _, err := tc.List(ctx, "default", types.ListOptions{PageSize: -1}) + _, err := tc.ListAll(ctx, "default", types.ListOptions{PageSize: -1}) require.Error(t, err) assert.True(t, types.IsInvalidArgument(err)) } @@ -174,7 +174,7 @@ func TestSandboxTemplate_ListReturnsAllFilteredResults(t *testing.T) { }, }) - listed, err := tc.List(ctx, "default", types.ListOptions{ + listed, err := tc.ListAll(ctx, "default", types.ListOptions{ LabelSelector: "team=runtime", PageSize: 1, }) @@ -293,7 +293,7 @@ func TestSandboxTemplate_CreateSandboxFromTemplateRejectsWorkloadOverrides(t *te }) } - listed, err := client.Sandboxes().List(ctx, "default") + listed, err := client.Sandboxes().ListAll(ctx, "default") require.NoError(t, err) assert.Empty(t, listed) } @@ -453,7 +453,7 @@ func TestSandboxTemplate_CreateRejectsInvalidTemplate(t *testing.T) { }) } - listed, err := tc.List(ctx, "default") + listed, err := tc.ListAll(ctx, "default") require.NoError(t, err) assert.Empty(t, listed) } diff --git a/sdk/go/openshell/v1/fake/sandbox_test.go b/sdk/go/openshell/v1/fake/sandbox_test.go index 75ff32da2d..1a2673808a 100644 --- a/sdk/go/openshell/v1/fake/sandbox_test.go +++ b/sdk/go/openshell/v1/fake/sandbox_test.go @@ -192,7 +192,7 @@ func TestSandbox_List_Empty(t *testing.T) { sc := newTestSandboxClient() ctx := context.Background() - list, err := sc.List(ctx, "default") + list, err := sc.ListAll(ctx, "default") require.NoError(t, err) assert.Empty(t, list) } @@ -204,7 +204,7 @@ func TestSandbox_List(t *testing.T) { _, _ = sc.Create(ctx, "default", "sb-1", &types.SandboxSpec{}, nil) _, _ = sc.Create(ctx, "default", "sb-2", &types.SandboxSpec{}, nil) - list, err := sc.List(ctx, "default") + list, err := sc.ListAll(ctx, "default") require.NoError(t, err) assert.Len(t, list, 2) } @@ -567,7 +567,7 @@ func TestSandbox_ConcurrentCreateGetDeleteWatch(t *testing.T) { name := fmt.Sprintf("sb-%d-%d", id, j) _, _ = sc.Create(ctx, "default", name, &types.SandboxSpec{LogLevel: "info"}, nil) _, _ = sc.Get(ctx, "default", name) - _, _ = sc.List(ctx, "default") + _, _ = sc.ListAll(ctx, "default") _, _ = sc.WaitReady(ctx, "default", name) _ = sc.Delete(ctx, "default", name) } diff --git a/sdk/go/openshell/v1/fake/service.go b/sdk/go/openshell/v1/fake/service.go index 4b3029012f..e3e08c5796 100644 --- a/sdk/go/openshell/v1/fake/service.go +++ b/sdk/go/openshell/v1/fake/service.go @@ -38,7 +38,7 @@ func (c *fakeServiceClient) Get(_ context.Context, _, _, _ string) (*types.Servi } // List returns Unimplemented. -func (c *fakeServiceClient) List(_ context.Context, _, _ string, _ ...v1.ListOptions) ([]*types.ServiceEndpoint, error) { +func (c *fakeServiceClient) List(_, _ string, _ ...v1.ListOptions) (*v1.Pager[*types.ServiceEndpoint], error) { if c.closedFunc() { return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} } @@ -46,7 +46,7 @@ func (c *fakeServiceClient) List(_ context.Context, _, _ string, _ ...v1.ListOpt } // ListAll returns Unimplemented. -func (c *fakeServiceClient) ListAll(_ context.Context, _ ...v1.ListOptions) ([]*types.ServiceEndpoint, error) { +func (c *fakeServiceClient) ListAll(_ context.Context, _, _ string, _ ...v1.ListOptions) ([]*types.ServiceEndpoint, error) { if c.closedFunc() { return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} } diff --git a/sdk/go/openshell/v1/fake/service_test.go b/sdk/go/openshell/v1/fake/service_test.go index 3e3a6b7ca8..19e689e07f 100644 --- a/sdk/go/openshell/v1/fake/service_test.go +++ b/sdk/go/openshell/v1/fake/service_test.go @@ -31,7 +31,7 @@ func TestFakeService_Get_ReturnsUnimplemented(t *testing.T) { func TestFakeService_List_ReturnsUnimplemented(t *testing.T) { c := newFakeServiceClient(func() bool { return false }) - _, err := c.List(context.Background(), "default", "sb1") + _, err := c.ListAll(context.Background(), "default", "sb1") require.Error(t, err) assert.True(t, types.IsUnimplemented(err)) } @@ -59,7 +59,7 @@ func TestFakeService_Get_ClosedReturnsUnavailable(t *testing.T) { func TestFakeService_List_ClosedReturnsUnavailable(t *testing.T) { c := newFakeServiceClient(func() bool { return true }) - _, err := c.List(context.Background(), "default", "sb1") + _, err := c.ListAll(context.Background(), "default", "sb1") require.Error(t, err) assert.True(t, types.IsUnavailable(err)) } diff --git a/sdk/go/openshell/v1/fake/workspace.go b/sdk/go/openshell/v1/fake/workspace.go index 026eac43a5..0cf20019a3 100644 --- a/sdk/go/openshell/v1/fake/workspace.go +++ b/sdk/go/openshell/v1/fake/workspace.go @@ -90,12 +90,24 @@ func (c *fakeWorkspaceClient) Get(_ context.Context, name string) (*types.Worksp return c.workspaceStore.Get("", name) } -// List returns all workspaces. ListOptions are accepted for interface compatibility but filtering is not implemented. -func (c *fakeWorkspaceClient) List(_ context.Context, _ ...v1.ListOptions) ([]*types.Workspace, error) { +// List returns a lazy pager over workspaces. +func (c *fakeWorkspaceClient) List(opts ...v1.ListOptions) (*v1.Pager[*types.Workspace], error) { if c.closedFunc() { return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} } - return c.workspaceStore.ListAll(), nil + var options v1.ListOptions + if len(opts) > 0 { + options = opts[0] + } + return newSlicePager(c.workspaceStore.ListAll(), options.PageSize, options.PageToken) +} + +func (c *fakeWorkspaceClient) ListAll(ctx context.Context, opts ...v1.ListOptions) ([]*types.Workspace, error) { + pager, err := c.List(opts...) + if err != nil { + return nil, err + } + return pager.All(ctx) } // Delete removes a workspace. Unlike the sandbox fake (which treats delete as @@ -161,12 +173,24 @@ func (c *fakeWorkspaceClient) RemoveMember(_ context.Context, workspace, princip } // ListMembers returns all members for the workspace. ListOptions are accepted for interface compatibility but filtering is not implemented. -func (c *fakeWorkspaceClient) ListMembers(_ context.Context, workspace string, _ ...v1.ListOptions) ([]*types.WorkspaceMember, error) { +func (c *fakeWorkspaceClient) ListMembers(workspace string, opts ...v1.ListOptions) (*v1.Pager[*types.WorkspaceMember], error) { if c.closedFunc() { return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} } if workspace == "" { return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "workspace name must not be empty"} } - return c.memberStore.List(workspace), nil + var options v1.ListOptions + if len(opts) > 0 { + options = opts[0] + } + return newSlicePager(c.memberStore.List(workspace), options.PageSize, options.PageToken) +} + +func (c *fakeWorkspaceClient) ListAllMembers(ctx context.Context, workspace string, opts ...v1.ListOptions) ([]*types.WorkspaceMember, error) { + pager, err := c.ListMembers(workspace, opts...) + if err != nil { + return nil, err + } + return pager.All(ctx) } diff --git a/sdk/go/openshell/v1/fake/workspace_test.go b/sdk/go/openshell/v1/fake/workspace_test.go index 32ebf6434a..c9a909ffdc 100644 --- a/sdk/go/openshell/v1/fake/workspace_test.go +++ b/sdk/go/openshell/v1/fake/workspace_test.go @@ -21,7 +21,7 @@ func TestWorkspaceDelete_RemovesMembers(t *testing.T) { require.NoError(t, err) require.NoError(t, fc.Workspaces().Delete(ctx, "team")) - members, err := fc.Workspaces().ListMembers(ctx, "team") + members, err := fc.Workspaces().ListAllMembers(ctx, "team") require.NoError(t, err) assert.Empty(t, members) } @@ -101,14 +101,14 @@ func TestFakeWorkspace_List(t *testing.T) { _, _ = fc.Workspaces().Create(context.Background(), "ws-1", nil) _, _ = fc.Workspaces().Create(context.Background(), "ws-2", nil) - workspaces, err := fc.Workspaces().List(context.Background()) + workspaces, err := fc.Workspaces().ListAll(context.Background()) require.NoError(t, err) assert.Len(t, workspaces, 2) } func TestFakeWorkspace_List_Empty(t *testing.T) { fc := NewClient() - workspaces, err := fc.Workspaces().List(context.Background()) + workspaces, err := fc.Workspaces().ListAll(context.Background()) require.NoError(t, err) assert.Empty(t, workspaces) } @@ -191,7 +191,7 @@ func TestFakeWorkspace_RemoveMember(t *testing.T) { err := fc.Workspaces().RemoveMember(context.Background(), "ws", "user@example.com") require.NoError(t, err) - members, err := fc.Workspaces().ListMembers(context.Background(), "ws") + members, err := fc.Workspaces().ListAllMembers(context.Background(), "ws") require.NoError(t, err) assert.Empty(t, members) } @@ -225,14 +225,14 @@ func TestFakeWorkspace_ListMembers(t *testing.T) { _, _ = fc.Workspaces().AddMember(context.Background(), "ws", "user1@example.com", types.WorkspaceRoleAdmin) _, _ = fc.Workspaces().AddMember(context.Background(), "ws", "user2@example.com", types.WorkspaceRoleUser) - members, err := fc.Workspaces().ListMembers(context.Background(), "ws") + members, err := fc.Workspaces().ListAllMembers(context.Background(), "ws") require.NoError(t, err) assert.Len(t, members, 2) } func TestFakeWorkspace_ListMembers_EmptyWorkspace(t *testing.T) { fc := NewClient() - _, err := fc.Workspaces().ListMembers(context.Background(), "") + _, err := fc.Workspaces().ListAllMembers(context.Background(), "") require.Error(t, err) assert.True(t, types.IsInvalidArgument(err)) @@ -243,12 +243,12 @@ func TestFakeWorkspace_ListMembers_Isolation(t *testing.T) { _, _ = fc.Workspaces().AddMember(context.Background(), "ws-a", "user@example.com", types.WorkspaceRoleAdmin) _, _ = fc.Workspaces().AddMember(context.Background(), "ws-b", "other@example.com", types.WorkspaceRoleUser) - membersA, err := fc.Workspaces().ListMembers(context.Background(), "ws-a") + membersA, err := fc.Workspaces().ListAllMembers(context.Background(), "ws-a") require.NoError(t, err) assert.Len(t, membersA, 1) assert.Equal(t, "user@example.com", membersA[0].PrincipalSubject) - membersB, err := fc.Workspaces().ListMembers(context.Background(), "ws-b") + membersB, err := fc.Workspaces().ListAllMembers(context.Background(), "ws-b") require.NoError(t, err) assert.Len(t, membersB, 1) assert.Equal(t, "other@example.com", membersB[0].PrincipalSubject) @@ -264,7 +264,7 @@ func TestFakeWorkspace_Closed(t *testing.T) { _, err = fc.Workspaces().Get(context.Background(), "ws") assert.True(t, types.IsUnavailable(err)) - _, err = fc.Workspaces().List(context.Background()) + _, err = fc.Workspaces().ListAll(context.Background()) assert.True(t, types.IsUnavailable(err)) err = fc.Workspaces().Delete(context.Background(), "ws") @@ -276,7 +276,7 @@ func TestFakeWorkspace_Closed(t *testing.T) { err = fc.Workspaces().RemoveMember(context.Background(), "ws", "user") assert.True(t, types.IsUnavailable(err)) - _, err = fc.Workspaces().ListMembers(context.Background(), "ws") + _, err = fc.Workspaces().ListAllMembers(context.Background(), "ws") assert.True(t, types.IsUnavailable(err)) } diff --git a/sdk/go/openshell/v1/pager.go b/sdk/go/openshell/v1/pager.go new file mode 100644 index 0000000000..558fda4694 --- /dev/null +++ b/sdk/go/openshell/v1/pager.go @@ -0,0 +1,73 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package v1 + +import ( + "context" + "errors" +) + +// Page is one response page from a list operation. +type Page[T any] struct { + Items []T + NextPageToken string +} + +type pageFetcher[T any] func(context.Context, string) (*Page[T], error) + +// Pager lazily fetches one RPC page per call to NextPage. +// +// A Pager is single-pass and must not be used concurrently. +type Pager[T any] struct { + fetch pageFetcher[T] + nextPageToken *string +} + +// NewPager constructs a pager from an RPC page fetcher. +func NewPager[T any](pageToken string, fetch func(context.Context, string) (*Page[T], error)) *Pager[T] { + return &Pager[T]{fetch: fetch, nextPageToken: &pageToken} +} + +func newPager[T any](pageToken string, fetch pageFetcher[T]) *Pager[T] { + return NewPager(pageToken, fetch) +} + +// NextPage fetches the next page. It returns nil after the final page. +func (p *Pager[T]) NextPage(ctx context.Context) (*Page[T], error) { + if p.nextPageToken == nil { + return nil, nil + } + page, err := p.fetch(ctx, *p.nextPageToken) + if err != nil { + return nil, err + } + if page == nil { + return nil, errors.New("pager fetch returned a nil page") + } + if page.Items == nil { + page.Items = make([]T, 0) + } + if page.NextPageToken == "" { + p.nextPageToken = nil + } else { + next := page.NextPageToken + p.nextPageToken = &next + } + return page, nil +} + +// All consumes the pager and collects every remaining item. +func (p *Pager[T]) All(ctx context.Context) ([]T, error) { + items := make([]T, 0) + for { + page, err := p.NextPage(ctx) + if err != nil { + return nil, err + } + if page == nil { + return items, nil + } + items = append(items, page.Items...) + } +} diff --git a/sdk/go/openshell/v1/pager_test.go b/sdk/go/openshell/v1/pager_test.go new file mode 100644 index 0000000000..55dc74eb28 --- /dev/null +++ b/sdk/go/openshell/v1/pager_test.go @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package v1 + +import ( + "context" + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPagerIsLazyAndFetchesOnePageAtATime(t *testing.T) { + requests := make([]string, 0) + pager := NewPager("resume-token", func(_ context.Context, token string) (*Page[string], error) { + requests = append(requests, token) + if token == "resume-token" { + return &Page[string]{Items: []string{"first"}, NextPageToken: "second-token"}, nil + } + return &Page[string]{Items: []string{"second"}}, nil + }) + + assert.Empty(t, requests) + first, err := pager.NextPage(context.Background()) + require.NoError(t, err) + assert.Equal(t, []string{"first"}, first.Items) + assert.Equal(t, "second-token", first.NextPageToken) + assert.Equal(t, []string{"resume-token"}, requests) + + second, err := pager.NextPage(context.Background()) + require.NoError(t, err) + assert.Equal(t, []string{"second"}, second.Items) + assert.Equal(t, []string{"resume-token", "second-token"}, requests) + + done, err := pager.NextPage(context.Background()) + require.NoError(t, err) + assert.Nil(t, done) +} + +func TestPagerAllRetriesTheCurrentTokenAfterError(t *testing.T) { + wantErr := errors.New("temporary") + attempts := 0 + pager := NewPager("", func(_ context.Context, token string) (*Page[int], error) { + assert.Empty(t, token) + attempts++ + if attempts == 1 { + return nil, wantErr + } + return &Page[int]{Items: []int{1, 2}}, nil + }) + + _, err := pager.NextPage(context.Background()) + assert.ErrorIs(t, err, wantErr) + items, err := pager.All(context.Background()) + require.NoError(t, err) + assert.Equal(t, []int{1, 2}, items) +} + +func TestPagerNormalizesEmptyItems(t *testing.T) { + pager := NewPager("", func(_ context.Context, _ string) (*Page[string], error) { + return &Page[string]{}, nil + }) + + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + assert.NotNil(t, page.Items) + assert.Empty(t, page.Items) +} + +func TestPagerRejectsNilPage(t *testing.T) { + pager := NewPager("resume-token", func(_ context.Context, token string) (*Page[string], error) { + assert.Equal(t, "resume-token", token) + return nil, nil + }) + + page, err := pager.NextPage(context.Background()) + assert.Nil(t, page) + assert.EqualError(t, err, "pager fetch returned a nil page") +} diff --git a/sdk/go/openshell/v1/policy.go b/sdk/go/openshell/v1/policy.go index a6025074df..c995eeaf7d 100644 --- a/sdk/go/openshell/v1/policy.go +++ b/sdk/go/openshell/v1/policy.go @@ -87,9 +87,12 @@ var WithVersion = types.WithVersion // ListPolicyOption configures a List call. type ListPolicyOption = types.ListPolicyOption -// WithPageSize sets the page size used while collecting every revision. +// WithPageSize sets the maximum revisions requested per page. var WithPageSize = types.WithPageSize +// WithPageToken resumes listing from an opaque token returned by a previous page. +var WithPageToken = types.WithPageToken + // WithListGlobal enables global policy mode on List. When true, the query // retrieves gateway-global policy revisions instead of sandbox-scoped ones. var WithListGlobal = types.WithListGlobal @@ -108,7 +111,8 @@ type PolicyInterface interface { ClearDraftChunks(ctx context.Context, workspace, sandboxName string) (*ClearResult, error) GetDraftHistory(ctx context.Context, workspace, sandboxName string) ([]DraftHistoryEntry, error) GetStatus(ctx context.Context, workspace, sandboxName string, opts ...GetStatusOption) (*PolicyStatusResult, error) - List(ctx context.Context, workspace string, opts ...ListPolicyOption) ([]SandboxPolicyRevision, error) + List(workspace, sandboxName string, opts ...ListPolicyOption) (*Pager[SandboxPolicyRevision], error) + ListAll(ctx context.Context, workspace, sandboxName string, opts ...ListPolicyOption) ([]SandboxPolicyRevision, error) EditDraftChunk(ctx context.Context, workspace, sandboxName, chunkID string, proposedRule *NetworkPolicyRule) error UndoDraftChunk(ctx context.Context, workspace, sandboxName, chunkID string) (*UndoResult, error) } diff --git a/sdk/go/openshell/v1/policy_client.go b/sdk/go/openshell/v1/policy_client.go index 1dec3fad7e..16f1fe4ec2 100644 --- a/sdk/go/openshell/v1/policy_client.go +++ b/sdk/go/openshell/v1/policy_client.go @@ -129,34 +129,41 @@ func (p *policyClient) GetStatus(ctx context.Context, workspace, sandboxName str return converter.PolicyStatusResultFromProto(resp), nil } -func (p *policyClient) List(ctx context.Context, workspace string, opts ...ListPolicyOption) ([]SandboxPolicyRevision, error) { +func (p *policyClient) List(workspace, sandboxName string, opts ...ListPolicyOption) (*Pager[SandboxPolicyRevision], error) { cfg := types.ApplyListPolicyOptions(opts) if cfg.PageSize() < 0 { return nil, &StatusError{Code: ErrorInvalidArgument, Message: "page size must not be negative"} } - req := &pb.ListSandboxPoliciesRequest{ - PageSize: cfg.PageSize(), - Global: cfg.Global(), + if !cfg.Global() && sandboxName == "" { + return nil, &StatusError{Code: ErrorInvalidArgument, Message: "sandbox name must not be empty"} } - if !cfg.Global() { - req.WorkspaceScope = namedWorkspaceScope(workspace) - } - var result []SandboxPolicyRevision - for { + return newPager(cfg.PageToken(), func(ctx context.Context, pageToken string) (*Page[SandboxPolicyRevision], error) { + req := &pb.ListSandboxPoliciesRequest{ + Name: sandboxName, PageSize: cfg.PageSize(), PageToken: pageToken, Global: cfg.Global(), + } + if !cfg.Global() { + req.WorkspaceScope = namedWorkspaceScope(workspace) + } resp, err := p.client.ListSandboxPolicies(ctx, req) if err != nil { return nil, converter.FromGRPCError(err) } + result := make([]SandboxPolicyRevision, 0, len(resp.GetRevisions())) for _, revision := range resp.GetRevisions() { if converted := converter.SandboxPolicyRevisionFromProto(revision); converted != nil { result = append(result, *converted) } } - if resp.GetNextPageToken() == "" { - return result, nil - } - req.PageToken = resp.GetNextPageToken() + return &Page[SandboxPolicyRevision]{Items: result, NextPageToken: resp.GetNextPageToken()}, nil + }), nil +} + +func (p *policyClient) ListAll(ctx context.Context, workspace, sandboxName string, opts ...ListPolicyOption) ([]SandboxPolicyRevision, error) { + pager, err := p.List(workspace, sandboxName, opts...) + if err != nil { + return nil, err } + return pager.All(ctx) } func (p *policyClient) EditDraftChunk(ctx context.Context, workspace, sandboxName, chunkID string, proposedRule *NetworkPolicyRule) error { diff --git a/sdk/go/openshell/v1/policy_client_test.go b/sdk/go/openshell/v1/policy_client_test.go index ebb2491ea3..10e8fd7bb3 100644 --- a/sdk/go/openshell/v1/policy_client_test.go +++ b/sdk/go/openshell/v1/policy_client_test.go @@ -773,7 +773,7 @@ func TestPolicyList(t *testing.T) { client, cleanup := setupPolicyTest(t, mock) defer cleanup() - revisions, err := client.List(context.Background(), "default") + revisions, err := client.ListAll(context.Background(), "default", "sandbox") require.NoError(t, err) require.Len(t, revisions, 2) @@ -781,6 +781,7 @@ func TestPolicyList(t *testing.T) { // Verify request was forwarded (no pagination options). mock.mu.Lock() assert.Equal(t, "default", mock.lastListReq.GetWorkspaceScope().GetWorkspace()) + assert.Equal(t, "sandbox", mock.lastListReq.GetName()) assert.Equal(t, int32(0), mock.lastListReq.GetPageSize()) assert.Empty(t, mock.lastListReq.GetPageToken()) mock.mu.Unlock() @@ -805,7 +806,7 @@ func TestPolicyList_WithPageSize(t *testing.T) { client, cleanup := setupPolicyTest(t, mock) defer cleanup() - revisions, err := client.List(context.Background(), "default", + revisions, err := client.ListAll(context.Background(), "default", "sandbox", types.WithPageSize(10), ) @@ -826,10 +827,11 @@ func TestPolicyList_Empty(t *testing.T) { client, cleanup := setupPolicyTest(t, mock) defer cleanup() - revisions, err := client.List(context.Background(), "default") + revisions, err := client.ListAll(context.Background(), "default", "sandbox") require.NoError(t, err) - assert.Nil(t, revisions) + assert.NotNil(t, revisions) + assert.Empty(t, revisions) } func TestPolicyList_WithGlobal(t *testing.T) { @@ -844,7 +846,7 @@ func TestPolicyList_WithGlobal(t *testing.T) { defer cleanup() // List with global flag and empty workspace. - revisions, err := client.List(context.Background(), "", types.WithListGlobal(true)) + revisions, err := client.ListAll(context.Background(), "", "", types.WithListGlobal(true)) require.NoError(t, err) require.Len(t, revisions, 1) @@ -869,7 +871,7 @@ func TestPolicyList_WithGlobalIgnoresWorkspace(t *testing.T) { client, cleanup := setupPolicyTest(t, mock) defer cleanup() - revisions, err := client.List(context.Background(), "some-workspace", types.WithListGlobal(true)) + revisions, err := client.ListAll(context.Background(), "some-workspace", "", types.WithListGlobal(true)) require.NoError(t, err) require.Len(t, revisions, 1) @@ -892,7 +894,7 @@ func TestPolicyList_WithGlobalAndPagination(t *testing.T) { defer cleanup() // Global flag composes with page-size options. - revisions, err := client.List(context.Background(), "", + revisions, err := client.ListAll(context.Background(), "", "", types.WithListGlobal(true), types.WithPageSize(10), ) @@ -918,7 +920,7 @@ func TestPolicyList_WithoutGlobal_PreservesExistingBehavior(t *testing.T) { client, cleanup := setupPolicyTest(t, mock) defer cleanup() - revisions, err := client.List(context.Background(), "default") + revisions, err := client.ListAll(context.Background(), "default", "sandbox") require.NoError(t, err) require.Len(t, revisions, 1) @@ -937,7 +939,7 @@ func TestPolicyList_Error(t *testing.T) { client, cleanup := setupPolicyTest(t, mock) defer cleanup() - revisions, err := client.List(context.Background(), "default") + revisions, err := client.ListAll(context.Background(), "default", "sandbox") assert.Nil(t, revisions) require.Error(t, err) diff --git a/sdk/go/openshell/v1/profile.go b/sdk/go/openshell/v1/profile.go index c0518bc95a..4460bfcb96 100644 --- a/sdk/go/openshell/v1/profile.go +++ b/sdk/go/openshell/v1/profile.go @@ -55,7 +55,8 @@ const ( // ProfileInterface defines operations for managing provider profiles. type ProfileInterface interface { - List(ctx context.Context, workspace string, opts ...ListOptions) ([]*ProviderProfile, error) + List(workspace string, opts ...ListOptions) (*Pager[*ProviderProfile], error) + ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*ProviderProfile, error) Get(ctx context.Context, workspace, id string) (*ProviderProfile, error) Import(ctx context.Context, workspace string, items []ProfileImportItem) (*ImportResult, error) Update(ctx context.Context, workspace, id string, expectedResourceVersion uint64, item ProfileImportItem) (*UpdateResult, error) diff --git a/sdk/go/openshell/v1/profile_client.go b/sdk/go/openshell/v1/profile_client.go index 11808c2faa..f1eb66707d 100644 --- a/sdk/go/openshell/v1/profile_client.go +++ b/sdk/go/openshell/v1/profile_client.go @@ -19,29 +19,35 @@ func newProfileClient(conn grpc.ClientConnInterface) *profileClient { return &profileClient{client: pb.NewOpenShellClient(conn)} } -func (p *profileClient) List(ctx context.Context, workspace string, opts ...ListOptions) ([]*ProviderProfile, error) { +func (p *profileClient) List(workspace string, opts ...ListOptions) (*Pager[*ProviderProfile], error) { pageSize, err := listPageSize(opts) if err != nil { return nil, err } - req := &pb.ListProviderProfilesRequest{ - Workspace: workspace, - PageSize: pageSize, + var pageToken string + if len(opts) > 0 { + pageToken = opts[0].PageToken } - profiles := make([]*ProviderProfile, 0) - for { + return newPager(pageToken, func(ctx context.Context, pageToken string) (*Page[*ProviderProfile], error) { + req := &pb.ListProviderProfilesRequest{Workspace: workspace, PageSize: pageSize, PageToken: pageToken} resp, err := p.client.ListProviderProfiles(ctx, req) if err != nil { return nil, converter.FromGRPCError(err) } + profiles := make([]*ProviderProfile, 0, len(resp.GetProfiles())) for _, profile := range resp.GetProfiles() { profiles = append(profiles, converter.ProviderProfileFromProto(profile)) } - if resp.GetNextPageToken() == "" { - return profiles, nil - } - req.PageToken = resp.GetNextPageToken() + return &Page[*ProviderProfile]{Items: profiles, NextPageToken: resp.GetNextPageToken()}, nil + }), nil +} + +func (p *profileClient) ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*ProviderProfile, error) { + pager, err := p.List(workspace, opts...) + if err != nil { + return nil, err } + return pager.All(ctx) } func (p *profileClient) Get(ctx context.Context, workspace, id string) (*ProviderProfile, error) { diff --git a/sdk/go/openshell/v1/profile_client_test.go b/sdk/go/openshell/v1/profile_client_test.go index 979fe5bbad..86f7898313 100644 --- a/sdk/go/openshell/v1/profile_client_test.go +++ b/sdk/go/openshell/v1/profile_client_test.go @@ -219,7 +219,7 @@ func TestProfileList(t *testing.T) { client, cleanup := setupProfileTest(t, mock) defer cleanup() - profiles, err := client.List(context.Background(), "default") + profiles, err := client.ListAll(context.Background(), "default") require.NoError(t, err) assert.Len(t, profiles, 2) @@ -230,7 +230,7 @@ func TestProfileList_Empty(t *testing.T) { client, cleanup := setupProfileTest(t, mock) defer cleanup() - profiles, err := client.List(context.Background(), "default") + profiles, err := client.ListAll(context.Background(), "default") require.NoError(t, err) assert.NotNil(t, profiles) @@ -243,7 +243,7 @@ func TestProfileList_WithOptions(t *testing.T) { client, cleanup := setupProfileTest(t, mock) defer cleanup() - profiles, err := client.List(context.Background(), "default", ListOptions{PageSize: 10}) + profiles, err := client.ListAll(context.Background(), "default", ListOptions{PageSize: 10}) require.NoError(t, err) assert.Len(t, profiles, 1) @@ -258,7 +258,7 @@ func TestProfileList_Error(t *testing.T) { client, cleanup := setupProfileTest(t, mock) defer cleanup() - profiles, err := client.List(context.Background(), "default") + profiles, err := client.ListAll(context.Background(), "default") assert.Nil(t, profiles) require.Error(t, err) diff --git a/sdk/go/openshell/v1/provider.go b/sdk/go/openshell/v1/provider.go index 42788f8855..99c0bd731c 100644 --- a/sdk/go/openshell/v1/provider.go +++ b/sdk/go/openshell/v1/provider.go @@ -20,8 +20,8 @@ type ProviderSpec = types.ProviderSpec type ProviderInterface interface { Create(ctx context.Context, workspace string, provider *Provider) (*Provider, error) Get(ctx context.Context, workspace, name string) (*Provider, error) - List(ctx context.Context, workspace string, opts ...ListOptions) ([]*Provider, error) - ListAll(ctx context.Context, opts ...ListOptions) ([]*Provider, error) + List(workspace string, opts ...ListOptions) (*Pager[*Provider], error) + ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*Provider, error) Update(ctx context.Context, workspace string, provider *Provider) (*Provider, error) Delete(ctx context.Context, workspace, name string) error Ensure(ctx context.Context, workspace string, provider *Provider) (*Provider, error) diff --git a/sdk/go/openshell/v1/provider_client.go b/sdk/go/openshell/v1/provider_client.go index fdfb4c0bc9..5d991052fd 100644 --- a/sdk/go/openshell/v1/provider_client.go +++ b/sdk/go/openshell/v1/provider_client.go @@ -55,38 +55,41 @@ func (p *providerClient) Get(ctx context.Context, workspace, name string) (*Prov return converter.ProviderFromProto(resp.GetProvider()), nil } -func (p *providerClient) List(ctx context.Context, workspace string, opts ...ListOptions) ([]*Provider, error) { - req := &pb.ListProvidersRequest{ - WorkspaceScope: namedWorkspaceScope(workspace), - } - return p.list(ctx, req, opts...) -} - -func (p *providerClient) ListAll(ctx context.Context, opts ...ListOptions) ([]*Provider, error) { - return p.list(ctx, &pb.ListProvidersRequest{WorkspaceScope: allWorkspacesScope()}, opts...) -} - -func (p *providerClient) list(ctx context.Context, req *pb.ListProvidersRequest, opts ...ListOptions) ([]*Provider, error) { +func (p *providerClient) List(workspace string, opts ...ListOptions) (*Pager[*Provider], error) { pageSize, err := listPageSize(opts) if err != nil { return nil, err } - req.PageSize = pageSize - - providers := make([]*Provider, 0) - for { + var pageToken string + var allWorkspaces bool + if len(opts) > 0 { + pageToken = opts[0].PageToken + allWorkspaces = opts[0].AllWorkspaces + } + workspaceScope := namedWorkspaceScope(workspace) + if allWorkspaces { + workspaceScope = allWorkspacesScope() + } + return newPager(pageToken, func(ctx context.Context, pageToken string) (*Page[*Provider], error) { + req := &pb.ListProvidersRequest{WorkspaceScope: workspaceScope, PageSize: pageSize, PageToken: pageToken} resp, err := p.client.ListProviders(ctx, req) if err != nil { return nil, converter.FromGRPCError(err) } + providers := make([]*Provider, 0, len(resp.GetProviders())) for _, proto := range resp.GetProviders() { providers = append(providers, converter.ProviderFromProto(proto)) } - if resp.GetNextPageToken() == "" { - return providers, nil - } - req.PageToken = resp.GetNextPageToken() + return &Page[*Provider]{Items: providers, NextPageToken: resp.GetNextPageToken()}, nil + }), nil +} + +func (p *providerClient) ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*Provider, error) { + pager, err := p.List(workspace, opts...) + if err != nil { + return nil, err } + return pager.All(ctx) } func (p *providerClient) Update(ctx context.Context, workspace string, provider *Provider) (*Provider, error) { diff --git a/sdk/go/openshell/v1/provider_client_test.go b/sdk/go/openshell/v1/provider_client_test.go index 51830b7881..251799502c 100644 --- a/sdk/go/openshell/v1/provider_client_test.go +++ b/sdk/go/openshell/v1/provider_client_test.go @@ -22,6 +22,7 @@ import ( type mockProviderServer struct { pb.UnimplementedOpenShellServer providers map[string]*dm.Provider + lastList *pb.ListProvidersRequest createErr error getErr error listErr error @@ -57,7 +58,8 @@ func (s *mockProviderServer) GetProvider(_ context.Context, req *pb.GetProviderR return &pb.ProviderResponse{Provider: p}, nil } -func (s *mockProviderServer) ListProviders(_ context.Context, _ *pb.ListProvidersRequest) (*pb.ListProvidersResponse, error) { +func (s *mockProviderServer) ListProviders(_ context.Context, req *pb.ListProvidersRequest) (*pb.ListProvidersResponse, error) { + s.lastList = req if s.listErr != nil { return nil, s.listErr } @@ -188,7 +190,7 @@ func TestProviderList(t *testing.T) { client, cleanup := setupProviderTest(t, mock) defer cleanup() - result, err := client.List(context.Background(), "default") + result, err := client.ListAll(context.Background(), "default") require.NoError(t, err) assert.Len(t, result, 2) @@ -199,13 +201,30 @@ func TestProviderList_Empty(t *testing.T) { client, cleanup := setupProviderTest(t, mock) defer cleanup() - result, err := client.List(context.Background(), "default") + result, err := client.ListAll(context.Background(), "default") require.NoError(t, err) assert.NotNil(t, result) assert.Empty(t, result) } +func TestProviderListAll_SelectsAllWorkspaces(t *testing.T) { + mock := newMockProviderServer() + client, cleanup := setupProviderTest(t, mock) + defer cleanup() + + providers, err := client.ListAll(context.Background(), "", ListOptions{ + PageSize: 10, + AllWorkspaces: true, + }) + + require.NoError(t, err) + assert.Empty(t, providers) + require.NotNil(t, mock.lastList) + assert.Equal(t, int32(10), mock.lastList.GetPageSize()) + assert.NotNil(t, mock.lastList.GetWorkspaceScope().GetAllWorkspaces()) +} + func TestProviderUpdate(t *testing.T) { mock := newMockProviderServer() mock.providers["updatable"] = &dm.Provider{ diff --git a/sdk/go/openshell/v1/sandbox.go b/sdk/go/openshell/v1/sandbox.go index 59ab37ee91..1fb166825d 100644 --- a/sdk/go/openshell/v1/sandbox.go +++ b/sdk/go/openshell/v1/sandbox.go @@ -55,8 +55,8 @@ var WithLogMinLevel = types.WithLogMinLevel type SandboxInterface interface { Create(ctx context.Context, workspace, name string, spec *SandboxSpec, labels map[string]string, opts ...CreateOptions) (*Sandbox, error) Get(ctx context.Context, workspace, name string) (*Sandbox, error) - List(ctx context.Context, workspace string, opts ...ListOptions) ([]*Sandbox, error) - ListAll(ctx context.Context, opts ...ListOptions) ([]*Sandbox, error) + List(workspace string, opts ...ListOptions) (*Pager[*Sandbox], error) + ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*Sandbox, error) Stop(ctx context.Context, workspace, name string) (*Sandbox, error) Start(ctx context.Context, workspace, name string) (*Sandbox, error) Delete(ctx context.Context, workspace, name string) error diff --git a/sdk/go/openshell/v1/sandbox_client.go b/sdk/go/openshell/v1/sandbox_client.go index 187c826d8b..0760d4469b 100644 --- a/sdk/go/openshell/v1/sandbox_client.go +++ b/sdk/go/openshell/v1/sandbox_client.go @@ -98,41 +98,47 @@ func (s *sandboxClient) Get(ctx context.Context, workspace, name string) (*Sandb return converter.SandboxFromProto(resp.GetSandbox()), nil } -func (s *sandboxClient) List(ctx context.Context, workspace string, opts ...ListOptions) ([]*Sandbox, error) { - req := &pb.ListSandboxesRequest{ - WorkspaceScope: namedWorkspaceScope(workspace), - } - return s.list(ctx, req, opts...) -} - -func (s *sandboxClient) ListAll(ctx context.Context, opts ...ListOptions) ([]*Sandbox, error) { - return s.list(ctx, &pb.ListSandboxesRequest{WorkspaceScope: allWorkspacesScope()}, opts...) -} - -func (s *sandboxClient) list(ctx context.Context, req *pb.ListSandboxesRequest, opts ...ListOptions) ([]*Sandbox, error) { +func (s *sandboxClient) List(workspace string, opts ...ListOptions) (*Pager[*Sandbox], error) { pageSize, err := listPageSize(opts) if err != nil { return nil, err } - req.PageSize = pageSize + var pageToken, labelSelector string + var allWorkspaces bool if len(opts) > 0 { - req.LabelSelector = opts[0].LabelSelector - } - - sandboxes := make([]*Sandbox, 0) - for { + pageToken = opts[0].PageToken + labelSelector = opts[0].LabelSelector + allWorkspaces = opts[0].AllWorkspaces + } + workspaceScope := namedWorkspaceScope(workspace) + if allWorkspaces { + workspaceScope = allWorkspacesScope() + } + return newPager(pageToken, func(ctx context.Context, pageToken string) (*Page[*Sandbox], error) { + req := &pb.ListSandboxesRequest{ + WorkspaceScope: workspaceScope, + PageSize: pageSize, + PageToken: pageToken, + LabelSelector: labelSelector, + } resp, err := s.client.ListSandboxes(ctx, req) if err != nil { return nil, converter.FromGRPCError(err) } + sandboxes := make([]*Sandbox, 0, len(resp.GetSandboxes())) for _, proto := range resp.GetSandboxes() { sandboxes = append(sandboxes, converter.SandboxFromProto(proto)) } - if resp.GetNextPageToken() == "" { - return sandboxes, nil - } - req.PageToken = resp.GetNextPageToken() + return &Page[*Sandbox]{Items: sandboxes, NextPageToken: resp.GetNextPageToken()}, nil + }), nil +} + +func (s *sandboxClient) ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*Sandbox, error) { + pager, err := s.List(workspace, opts...) + if err != nil { + return nil, err } + return pager.All(ctx) } func (s *sandboxClient) Delete(ctx context.Context, workspace, name string) error { diff --git a/sdk/go/openshell/v1/sandbox_client_test.go b/sdk/go/openshell/v1/sandbox_client_test.go index 53429c6d1b..0494249775 100644 --- a/sdk/go/openshell/v1/sandbox_client_test.go +++ b/sdk/go/openshell/v1/sandbox_client_test.go @@ -419,7 +419,7 @@ func TestSandboxList(t *testing.T) { client, cleanup := setupSandboxTest(t, mock) defer cleanup() - result, err := client.List(context.Background(), "default") + result, err := client.ListAll(context.Background(), "default") require.NoError(t, err) assert.Len(t, result, 2) @@ -430,13 +430,30 @@ func TestSandboxList_Empty(t *testing.T) { client, cleanup := setupSandboxTest(t, mock) defer cleanup() - result, err := client.List(context.Background(), "default") + result, err := client.ListAll(context.Background(), "default") require.NoError(t, err) assert.NotNil(t, result) assert.Empty(t, result) } +func TestSandboxListAll_SelectsAllWorkspaces(t *testing.T) { + mock := newMockSandboxServer() + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + sandboxes, err := client.ListAll(context.Background(), "", ListOptions{ + PageSize: 10, + AllWorkspaces: true, + }) + + require.NoError(t, err) + assert.Empty(t, sandboxes) + require.Len(t, mock.listRequests, 1) + assert.Equal(t, int32(10), mock.listRequests[0].GetPageSize()) + assert.NotNil(t, mock.listRequests[0].GetWorkspaceScope().GetAllWorkspaces()) +} + func TestSandboxList_WithOptions(t *testing.T) { mock := newMockSandboxServer() mock.sandboxes["sb1"] = &pb.Sandbox{ @@ -446,7 +463,7 @@ func TestSandboxList_WithOptions(t *testing.T) { client, cleanup := setupSandboxTest(t, mock) defer cleanup() - result, err := client.List(context.Background(), "default", ListOptions{PageSize: 10}) + result, err := client.ListAll(context.Background(), "default", ListOptions{PageSize: 10}) require.NoError(t, err) assert.Len(t, result, 1) @@ -461,7 +478,7 @@ func TestSandboxList_FollowsContinuationTokens(t *testing.T) { client, cleanup := setupSandboxTest(t, mock) defer cleanup() - result, err := client.List(context.Background(), "default", ListOptions{ + result, err := client.ListAll(context.Background(), "default", ListOptions{ PageSize: 1, LabelSelector: "team=core", }) diff --git a/sdk/go/openshell/v1/sandbox_template.go b/sdk/go/openshell/v1/sandbox_template.go index 395b254bac..ed635177d1 100644 --- a/sdk/go/openshell/v1/sandbox_template.go +++ b/sdk/go/openshell/v1/sandbox_template.go @@ -40,7 +40,7 @@ type SandboxWorkloadTemplateProvenance = types.SandboxWorkloadTemplateProvenance type SandboxTemplateInterface interface { Create(ctx context.Context, workspace string, template *SandboxWorkloadTemplate) (*SandboxWorkloadTemplate, error) Get(ctx context.Context, workspace, name string) (*SandboxWorkloadTemplate, error) - List(ctx context.Context, workspace string, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) - ListAll(ctx context.Context, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) + List(workspace string, opts ...ListOptions) (*Pager[*SandboxWorkloadTemplate], error) + ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) Delete(ctx context.Context, workspace, name string) (bool, error) } diff --git a/sdk/go/openshell/v1/sandbox_template_client.go b/sdk/go/openshell/v1/sandbox_template_client.go index 3b14e36e66..511b6f9952 100644 --- a/sdk/go/openshell/v1/sandbox_template_client.go +++ b/sdk/go/openshell/v1/sandbox_template_client.go @@ -50,41 +50,45 @@ func (s *sandboxTemplateClient) Get(ctx context.Context, workspace, name string) return converter.SandboxWorkloadTemplateFromProto(resp.GetTemplate()), nil } -func (s *sandboxTemplateClient) List(ctx context.Context, workspace string, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) { - req := &pb.ListSandboxTemplatesRequest{ - WorkspaceScope: namedWorkspaceScope(workspace), - } - return s.list(ctx, req, opts...) -} - -func (s *sandboxTemplateClient) ListAll(ctx context.Context, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) { - return s.list(ctx, &pb.ListSandboxTemplatesRequest{WorkspaceScope: allWorkspacesScope()}, opts...) -} - -func (s *sandboxTemplateClient) list(ctx context.Context, req *pb.ListSandboxTemplatesRequest, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) { +func (s *sandboxTemplateClient) List(workspace string, opts ...ListOptions) (*Pager[*SandboxWorkloadTemplate], error) { pageSize, err := listPageSize(opts) if err != nil { return nil, err } - req.PageSize = pageSize + var pageToken, labelSelector string + var allWorkspaces bool if len(opts) > 0 { - req.LabelSelector = opts[0].LabelSelector + pageToken = opts[0].PageToken + labelSelector = opts[0].LabelSelector + allWorkspaces = opts[0].AllWorkspaces } - - templates := make([]*SandboxWorkloadTemplate, 0) - for { + workspaceScope := namedWorkspaceScope(workspace) + if allWorkspaces { + workspaceScope = allWorkspacesScope() + } + return newPager(pageToken, func(ctx context.Context, pageToken string) (*Page[*SandboxWorkloadTemplate], error) { + req := &pb.ListSandboxTemplatesRequest{ + WorkspaceScope: workspaceScope, PageSize: pageSize, PageToken: pageToken, + LabelSelector: labelSelector, + } resp, err := s.client.ListSandboxTemplates(ctx, req) if err != nil { return nil, converter.FromGRPCError(err) } + templates := make([]*SandboxWorkloadTemplate, 0, len(resp.GetTemplates())) for _, protoTemplate := range resp.GetTemplates() { templates = append(templates, converter.SandboxWorkloadTemplateFromProto(protoTemplate)) } - if resp.GetNextPageToken() == "" { - return templates, nil - } - req.PageToken = resp.GetNextPageToken() + return &Page[*SandboxWorkloadTemplate]{Items: templates, NextPageToken: resp.GetNextPageToken()}, nil + }), nil +} + +func (s *sandboxTemplateClient) ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) { + pager, err := s.List(workspace, opts...) + if err != nil { + return nil, err } + return pager.All(ctx) } func (s *sandboxTemplateClient) Delete(ctx context.Context, workspace, name string) (bool, error) { diff --git a/sdk/go/openshell/v1/sandbox_template_client_test.go b/sdk/go/openshell/v1/sandbox_template_client_test.go index 2f63c6c042..115d31f097 100644 --- a/sdk/go/openshell/v1/sandbox_template_client_test.go +++ b/sdk/go/openshell/v1/sandbox_template_client_test.go @@ -220,7 +220,7 @@ func TestSandboxTemplateGetListDelete(t *testing.T) { assert.Equal(t, "gpu-kata", got.Name) assert.Equal(t, "img:v1", got.Spec.Workload.Image) - list, err := client.ListAll(context.Background(), ListOptions{ + list, err := client.ListAll(context.Background(), "default", ListOptions{ PageSize: 10, LabelSelector: "team=runtime", }) @@ -238,7 +238,7 @@ func TestSandboxTemplateGetListDelete(t *testing.T) { assert.Equal(t, "default", mock.getRequest.GetWorkspaceScope().GetWorkspace()) assert.Equal(t, "gpu-kata", mock.getRequest.Name) require.NotNil(t, mock.listRequest) - assert.NotNil(t, mock.listRequest.GetWorkspaceScope().GetAllWorkspaces()) + assert.Equal(t, "default", mock.listRequest.GetWorkspaceScope().GetWorkspace()) assert.Equal(t, int32(10), mock.listRequest.PageSize) assert.Empty(t, mock.listRequest.PageToken) assert.Equal(t, "team=runtime", mock.listRequest.LabelSelector) @@ -252,7 +252,7 @@ func TestSandboxTemplateList_RejectsNegativePagination(t *testing.T) { client, cleanup := setupSandboxTemplateTest(t, mock) defer cleanup() - _, err := client.List(context.Background(), "default", ListOptions{PageSize: -1}) + _, err := client.ListAll(context.Background(), "default", ListOptions{PageSize: -1}) require.Error(t, err) assert.True(t, IsInvalidArgument(err)) } @@ -262,7 +262,7 @@ func TestSandboxTemplateList_EmptyReturnsNonNilSlice(t *testing.T) { client, cleanup := setupSandboxTemplateTest(t, mock) defer cleanup() - templates, err := client.List(context.Background(), "default") + templates, err := client.ListAll(context.Background(), "default") require.NoError(t, err) assert.NotNil(t, templates) diff --git a/sdk/go/openshell/v1/service.go b/sdk/go/openshell/v1/service.go index acdcd1eeb6..44a316be3e 100644 --- a/sdk/go/openshell/v1/service.go +++ b/sdk/go/openshell/v1/service.go @@ -16,7 +16,7 @@ type ServiceEndpoint = types.ServiceEndpoint type ServiceInterface interface { Expose(ctx context.Context, workspace, sandboxName, serviceName string, targetPort uint32, domain bool) (*ServiceEndpoint, error) Get(ctx context.Context, workspace, sandboxName, serviceName string) (*ServiceEndpoint, error) - List(ctx context.Context, workspace, sandboxName string, opts ...ListOptions) ([]*ServiceEndpoint, error) - ListAll(ctx context.Context, opts ...ListOptions) ([]*ServiceEndpoint, error) + List(workspace, sandboxName string, opts ...ListOptions) (*Pager[*ServiceEndpoint], error) + ListAll(ctx context.Context, workspace, sandboxName string, opts ...ListOptions) ([]*ServiceEndpoint, error) Delete(ctx context.Context, workspace, sandboxName, serviceName string) error } diff --git a/sdk/go/openshell/v1/service_client.go b/sdk/go/openshell/v1/service_client.go index 3ab60d2da7..fcca16936b 100644 --- a/sdk/go/openshell/v1/service_client.go +++ b/sdk/go/openshell/v1/service_client.go @@ -45,39 +45,44 @@ func (s *serviceClient) Get(ctx context.Context, workspace, sandboxName, service return converter.ServiceEndpointFromProto(resp), nil } -func (s *serviceClient) List(ctx context.Context, workspace, sandboxName string, opts ...ListOptions) ([]*ServiceEndpoint, error) { - req := &pb.ListServicesRequest{ - Sandbox: sandboxName, - WorkspaceScope: namedWorkspaceScope(workspace), - } - return s.list(ctx, req, opts...) -} - -func (s *serviceClient) ListAll(ctx context.Context, opts ...ListOptions) ([]*ServiceEndpoint, error) { - return s.list(ctx, &pb.ListServicesRequest{WorkspaceScope: allWorkspacesScope()}, opts...) -} - -func (s *serviceClient) list(ctx context.Context, req *pb.ListServicesRequest, opts ...ListOptions) ([]*ServiceEndpoint, error) { +func (s *serviceClient) List(workspace, sandboxName string, opts ...ListOptions) (*Pager[*ServiceEndpoint], error) { pageSize, err := listPageSize(opts) if err != nil { return nil, err } - req.PageSize = pageSize - - endpoints := make([]*ServiceEndpoint, 0) - for { + var pageToken string + var allWorkspaces bool + if len(opts) > 0 { + pageToken = opts[0].PageToken + allWorkspaces = opts[0].AllWorkspaces + } + workspaceScope := namedWorkspaceScope(workspace) + if allWorkspaces { + workspaceScope = allWorkspacesScope() + } + return newPager(pageToken, func(ctx context.Context, pageToken string) (*Page[*ServiceEndpoint], error) { + req := &pb.ListServicesRequest{ + Sandbox: sandboxName, WorkspaceScope: workspaceScope, PageSize: pageSize, + PageToken: pageToken, + } resp, err := s.client.ListServices(ctx, req) if err != nil { return nil, converter.FromGRPCError(err) } + endpoints := make([]*ServiceEndpoint, 0, len(resp.GetServices())) for _, svc := range resp.GetServices() { endpoints = append(endpoints, converter.ServiceEndpointFromProto(svc)) } - if resp.GetNextPageToken() == "" { - return endpoints, nil - } - req.PageToken = resp.GetNextPageToken() + return &Page[*ServiceEndpoint]{Items: endpoints, NextPageToken: resp.GetNextPageToken()}, nil + }), nil +} + +func (s *serviceClient) ListAll(ctx context.Context, workspace, sandboxName string, opts ...ListOptions) ([]*ServiceEndpoint, error) { + pager, err := s.List(workspace, sandboxName, opts...) + if err != nil { + return nil, err } + return pager.All(ctx) } func (s *serviceClient) Delete(ctx context.Context, workspace, sandboxName, serviceName string) error { diff --git a/sdk/go/openshell/v1/service_client_test.go b/sdk/go/openshell/v1/service_client_test.go index ace6a25099..ade5de5af4 100644 --- a/sdk/go/openshell/v1/service_client_test.go +++ b/sdk/go/openshell/v1/service_client_test.go @@ -237,7 +237,7 @@ func TestServiceList(t *testing.T) { _, err = client.Expose(context.Background(), "default", "web-app", "web", 3000, false) require.NoError(t, err) - endpoints, err := client.List(context.Background(), "default", "web-app") + endpoints, err := client.ListAll(context.Background(), "default", "web-app") require.NoError(t, err) assert.Len(t, endpoints, 2) @@ -248,7 +248,7 @@ func TestServiceList_Empty(t *testing.T) { client, cleanup := setupServiceTest(t, mock) defer cleanup() - endpoints, err := client.List(context.Background(), "default", "web-app") + endpoints, err := client.ListAll(context.Background(), "default", "web-app") require.NoError(t, err) assert.NotNil(t, endpoints) @@ -263,7 +263,7 @@ func TestServiceList_WithOptions(t *testing.T) { _, err := client.Expose(context.Background(), "default", "web-app", "api", 8080, true) require.NoError(t, err) - endpoints, err := client.List(context.Background(), "default", "web-app", ListOptions{PageSize: 10}) + endpoints, err := client.ListAll(context.Background(), "default", "web-app", ListOptions{PageSize: 10}) require.NoError(t, err) assert.Len(t, endpoints, 1) @@ -274,7 +274,10 @@ func TestServiceListAll_SelectsAllWorkspaces(t *testing.T) { client, cleanup := setupServiceTest(t, mock) defer cleanup() - endpoints, err := client.ListAll(context.Background(), ListOptions{PageSize: 10}) + endpoints, err := client.ListAll(context.Background(), "", "", ListOptions{ + PageSize: 10, + AllWorkspaces: true, + }) require.NoError(t, err) assert.Empty(t, endpoints) @@ -289,7 +292,7 @@ func TestServiceList_Error(t *testing.T) { client, cleanup := setupServiceTest(t, mock) defer cleanup() - endpoints, err := client.List(context.Background(), "default", "web-app") + endpoints, err := client.ListAll(context.Background(), "default", "web-app") assert.Nil(t, endpoints) require.Error(t, err) diff --git a/sdk/go/openshell/v1/ssh_client_test.go b/sdk/go/openshell/v1/ssh_client_test.go index f1d0516ca1..d06edb115b 100644 --- a/sdk/go/openshell/v1/ssh_client_test.go +++ b/sdk/go/openshell/v1/ssh_client_test.go @@ -149,10 +149,12 @@ func (m *mockSandboxResolver) Get(_ context.Context, _, name string) (*Sandbox, return sb, nil } -func (m *mockSandboxResolver) List(_ context.Context, _ string, _ ...ListOptions) ([]*Sandbox, error) { - return nil, nil +func (m *mockSandboxResolver) List(_ string, _ ...ListOptions) (*Pager[*Sandbox], error) { + return NewPager("", func(_ context.Context, _ string) (*Page[*Sandbox], error) { + return &Page[*Sandbox]{Items: make([]*Sandbox, 0)}, nil + }), nil } -func (m *mockSandboxResolver) ListAll(_ context.Context, _ ...ListOptions) ([]*Sandbox, error) { +func (m *mockSandboxResolver) ListAll(_ context.Context, _ string, _ ...ListOptions) ([]*Sandbox, error) { return nil, nil } func (m *mockSandboxResolver) Delete(_ context.Context, _, _ string) error { return nil } diff --git a/sdk/go/openshell/v1/tcp_client_test.go b/sdk/go/openshell/v1/tcp_client_test.go index 100a746ccb..4ea96dbbab 100644 --- a/sdk/go/openshell/v1/tcp_client_test.go +++ b/sdk/go/openshell/v1/tcp_client_test.go @@ -996,10 +996,10 @@ func (r *flippableResolver) Get(_ context.Context, _, name string) (*Sandbox, er func (r *flippableResolver) Create(context.Context, string, string, *SandboxSpec, map[string]string, ...CreateOptions) (*Sandbox, error) { panic("not implemented") } -func (r *flippableResolver) List(context.Context, string, ...ListOptions) ([]*Sandbox, error) { +func (r *flippableResolver) List(string, ...ListOptions) (*Pager[*Sandbox], error) { panic("not implemented") } -func (r *flippableResolver) ListAll(context.Context, ...ListOptions) ([]*Sandbox, error) { +func (r *flippableResolver) ListAll(context.Context, string, ...ListOptions) ([]*Sandbox, error) { panic("not implemented") } func (r *flippableResolver) Delete(context.Context, string, string) error { diff --git a/sdk/go/openshell/v1/types/options.go b/sdk/go/openshell/v1/types/options.go index 8f220248ef..def5ca0fff 100644 --- a/sdk/go/openshell/v1/types/options.go +++ b/sdk/go/openshell/v1/types/options.go @@ -12,8 +12,13 @@ type CreateOptions struct { // ListOptions configures resource listing with pagination and filtering. type ListOptions struct { - PageSize int + // PageSize is the maximum number of resources requested per RPC. + PageSize int + // PageToken resumes after a page returned by the same list query. + PageToken string LabelSelector string + // AllWorkspaces selects a platform-admin view across workspace boundaries. + AllWorkspaces bool } // WatchOptions configures watch behavior. diff --git a/sdk/go/openshell/v1/types/policy.go b/sdk/go/openshell/v1/types/policy.go index 858cc2c162..8fb0712b60 100644 --- a/sdk/go/openshell/v1/types/policy.go +++ b/sdk/go/openshell/v1/types/policy.go @@ -363,20 +363,28 @@ func (c *getStatusConfig) Global() bool { // listPolicyConfig holds configuration for List calls. type listPolicyConfig struct { - pageSize int32 - global bool + pageSize int32 + pageToken string + global bool } // ListPolicyOption configures a List call. type ListPolicyOption func(*listPolicyConfig) -// WithPageSize sets the page size used while collecting every revision. +// WithPageSize sets the maximum revisions requested per page. func WithPageSize(pageSize int32) ListPolicyOption { return func(c *listPolicyConfig) { c.pageSize = pageSize } } +// WithPageToken resumes listing from an opaque token returned by a previous page. +func WithPageToken(pageToken string) ListPolicyOption { + return func(c *listPolicyConfig) { + c.pageToken = pageToken + } +} + // WithListGlobal enables global policy mode on List. When true, the query // retrieves gateway-global policy revisions instead of sandbox-scoped ones, // and the workspace parameter is ignored. @@ -398,6 +406,11 @@ func (c *listPolicyConfig) PageSize() int32 { return c.pageSize } +// PageToken returns the configured initial continuation token. +func (c *listPolicyConfig) PageToken() string { + return c.pageToken +} + // Global returns whether global policy mode is enabled. func (c *listPolicyConfig) Global() bool { return c.global diff --git a/sdk/go/openshell/v1/workspace.go b/sdk/go/openshell/v1/workspace.go index 15f46ef4e0..cff33185f8 100644 --- a/sdk/go/openshell/v1/workspace.go +++ b/sdk/go/openshell/v1/workspace.go @@ -39,9 +39,11 @@ const ( type WorkspaceInterface interface { Create(ctx context.Context, name string, labels map[string]string) (*Workspace, error) Get(ctx context.Context, name string) (*Workspace, error) - List(ctx context.Context, opts ...ListOptions) ([]*Workspace, error) + List(opts ...ListOptions) (*Pager[*Workspace], error) + ListAll(ctx context.Context, opts ...ListOptions) ([]*Workspace, error) Delete(ctx context.Context, name string) error AddMember(ctx context.Context, workspace, principalSubject string, role WorkspaceRole) (*WorkspaceMember, error) RemoveMember(ctx context.Context, workspace, principalSubject string) error - ListMembers(ctx context.Context, workspace string, opts ...ListOptions) ([]*WorkspaceMember, error) + ListMembers(workspace string, opts ...ListOptions) (*Pager[*WorkspaceMember], error) + ListAllMembers(ctx context.Context, workspace string, opts ...ListOptions) ([]*WorkspaceMember, error) } diff --git a/sdk/go/openshell/v1/workspace_client.go b/sdk/go/openshell/v1/workspace_client.go index 852c32969b..e17f268643 100644 --- a/sdk/go/openshell/v1/workspace_client.go +++ b/sdk/go/openshell/v1/workspace_client.go @@ -48,30 +48,36 @@ func (w *workspaceClient) Get(ctx context.Context, name string) (*Workspace, err return converter.WorkspaceFromProto(resp.GetWorkspace()), nil } -func (w *workspaceClient) List(ctx context.Context, opts ...ListOptions) ([]*Workspace, error) { +func (w *workspaceClient) List(opts ...ListOptions) (*Pager[*Workspace], error) { pageSize, err := listPageSize(opts) if err != nil { return nil, err } - req := &pb.ListWorkspacesRequest{PageSize: pageSize} + var pageToken, labelSelector string if len(opts) > 0 { - req.LabelSelector = opts[0].LabelSelector + pageToken = opts[0].PageToken + labelSelector = opts[0].LabelSelector } - - workspaces := make([]*Workspace, 0) - for { + return newPager(pageToken, func(ctx context.Context, pageToken string) (*Page[*Workspace], error) { + req := &pb.ListWorkspacesRequest{PageSize: pageSize, PageToken: pageToken, LabelSelector: labelSelector} resp, err := w.client.ListWorkspaces(ctx, req) if err != nil { return nil, converter.FromGRPCError(err) } + workspaces := make([]*Workspace, 0, len(resp.GetWorkspaces())) for _, proto := range resp.GetWorkspaces() { workspaces = append(workspaces, converter.WorkspaceFromProto(proto)) } - if resp.GetNextPageToken() == "" { - return workspaces, nil - } - req.PageToken = resp.GetNextPageToken() + return &Page[*Workspace]{Items: workspaces, NextPageToken: resp.GetNextPageToken()}, nil + }), nil +} + +func (w *workspaceClient) ListAll(ctx context.Context, opts ...ListOptions) ([]*Workspace, error) { + pager, err := w.List(opts...) + if err != nil { + return nil, err } + return pager.All(ctx) } func (w *workspaceClient) Delete(ctx context.Context, name string) error { @@ -130,7 +136,7 @@ func (w *workspaceClient) RemoveMember(ctx context.Context, workspace, principal return nil } -func (w *workspaceClient) ListMembers(ctx context.Context, workspace string, opts ...ListOptions) ([]*WorkspaceMember, error) { +func (w *workspaceClient) ListMembers(workspace string, opts ...ListOptions) (*Pager[*WorkspaceMember], error) { if workspace == "" { return nil, &StatusError{Code: ErrorInvalidArgument, Message: "workspace name must not be empty"} } @@ -139,22 +145,28 @@ func (w *workspaceClient) ListMembers(ctx context.Context, workspace string, opt if err != nil { return nil, err } - req := &pb.ListWorkspaceMembersRequest{ - Workspace: workspace, - PageSize: pageSize, + var pageToken string + if len(opts) > 0 { + pageToken = opts[0].PageToken } - members := make([]*WorkspaceMember, 0) - for { + return newPager(pageToken, func(ctx context.Context, pageToken string) (*Page[*WorkspaceMember], error) { + req := &pb.ListWorkspaceMembersRequest{Workspace: workspace, PageSize: pageSize, PageToken: pageToken} resp, err := w.client.ListWorkspaceMembers(ctx, req) if err != nil { return nil, converter.FromGRPCError(err) } + members := make([]*WorkspaceMember, 0, len(resp.GetMembers())) for _, proto := range resp.GetMembers() { members = append(members, converter.WorkspaceMemberFromProto(proto)) } - if resp.GetNextPageToken() == "" { - return members, nil - } - req.PageToken = resp.GetNextPageToken() + return &Page[*WorkspaceMember]{Items: members, NextPageToken: resp.GetNextPageToken()}, nil + }), nil +} + +func (w *workspaceClient) ListAllMembers(ctx context.Context, workspace string, opts ...ListOptions) ([]*WorkspaceMember, error) { + pager, err := w.ListMembers(workspace, opts...) + if err != nil { + return nil, err } + return pager.All(ctx) } diff --git a/sdk/go/openshell/v1/workspace_test.go b/sdk/go/openshell/v1/workspace_test.go index 743a9be0eb..37dde6eba4 100644 --- a/sdk/go/openshell/v1/workspace_test.go +++ b/sdk/go/openshell/v1/workspace_test.go @@ -223,7 +223,7 @@ func TestWorkspaceList_Success(t *testing.T) { defer cleanup() wc := newWorkspaceClient(conn) - workspaces, err := wc.List(context.Background()) + workspaces, err := wc.ListAll(context.Background()) require.NoError(t, err) require.Len(t, workspaces, 1) @@ -238,7 +238,7 @@ func TestWorkspaceList_WithOptions(t *testing.T) { defer cleanup() wc := newWorkspaceClient(conn) - _, err := wc.List(context.Background(), ListOptions{ + _, err := wc.ListAll(context.Background(), ListOptions{ PageSize: 10, LabelSelector: "team=platform", }) @@ -254,7 +254,7 @@ func TestWorkspaceList_EmptyReturnsNonNilSlice(t *testing.T) { conn, cleanup := newMockWorkspaceServer(mock) defer cleanup() - workspaces, err := newWorkspaceClient(conn).List(context.Background()) + workspaces, err := newWorkspaceClient(conn).ListAll(context.Background()) require.NoError(t, err) assert.NotNil(t, workspaces) @@ -444,7 +444,7 @@ func TestListMembers_Success(t *testing.T) { defer cleanup() wc := newWorkspaceClient(conn) - members, err := wc.ListMembers(context.Background(), "test-ws") + members, err := wc.ListAllMembers(context.Background(), "test-ws") require.NoError(t, err) require.Len(t, members, 1) @@ -457,7 +457,7 @@ func TestListMembers_EmptyWorkspace(t *testing.T) { defer cleanup() wc := newWorkspaceClient(conn) - _, err := wc.ListMembers(context.Background(), "") + _, err := wc.ListAllMembers(context.Background(), "") require.Error(t, err) assert.True(t, IsInvalidArgument(err)) @@ -470,7 +470,7 @@ func TestListMembers_EmptyResultReturnsNonNilSlice(t *testing.T) { conn, cleanup := newMockWorkspaceServer(mock) defer cleanup() - members, err := newWorkspaceClient(conn).ListMembers(context.Background(), "test-ws") + members, err := newWorkspaceClient(conn).ListAllMembers(context.Background(), "test-ws") require.NoError(t, err) assert.NotNil(t, members) @@ -485,7 +485,7 @@ func TestListMembers_WithOptions(t *testing.T) { defer cleanup() wc := newWorkspaceClient(conn) - _, err := wc.ListMembers(context.Background(), "test-ws", ListOptions{PageSize: 5}) + _, err := wc.ListAllMembers(context.Background(), "test-ws", ListOptions{PageSize: 5}) require.NoError(t, err) assert.Equal(t, int32(5), mock.lastListMembersReq.GetPageSize()) diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index 01689c61e8..23d5d8f84b 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -186,15 +186,24 @@ const sandbox = await client.sandbox.createFromTemplate({ }) await client.sandboxTemplates.get('python', { workspace: 'default' }) -await client.sandboxTemplates.list({ workspace: 'default', pageSize: 100 }) +await client.sandboxTemplates.listAll({ workspace: 'default', pageSize: 100 }) await client.sandboxTemplates.delete('python', { workspace: 'default' }) ``` Use `allWorkspaces: true` on `list()` for a platform-admin view. The discriminated option type makes `workspace` and `allWorkspaces` mutually exclusive. Omitting both options explicitly selects the `default` workspace. -List methods follow continuation tokens automatically; `pageSize` controls -each gateway request. +List methods follow continuation tokens through a lazy `Pager`; each advance +fetches one RPC page. Use `listAll()` only +when you want to exhaust the collection. `pageSize` controls one request and +`pageToken` resumes a saved traversal. + +```ts +const pages = client.sandbox.list({ workspace: 'default', pageSize: 100 }) +for await (const page of pages) { + for (const sandbox of page.items) console.log(sandbox.name) +} +``` ## Surface and roadmap diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index 824ab4a115..d440c75108 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -13,6 +13,7 @@ import { Code, ConnectError, createRouterTransport, type ServiceImpl, type Trans import { describe, expect, it } from 'vitest'; import { errorCode, + Pager, PHASE_NAMES, POLICY_SOURCE_NAMES, Pushable, @@ -438,7 +439,7 @@ describe('create', () => { const created = await sandbox.create({ name: 'direct', workspace: 'staging', image: 'img' }); const got = await sandbox.get('lookup', { workspace: 'staging' }); - const listed = await sandbox.list({ workspace: 'staging', pageSize: 10 }); + const listed = await sandbox.listAll({ workspace: 'staging', pageSize: 10 }); const deleted = await sandbox.delete('lookup', { workspace: 'staging' }); await expect(sandbox.waitReady('lookup', 1, { workspace: 'staging' })).resolves.toMatchObject({ workspace: 'staging', @@ -488,7 +489,7 @@ describe('create', () => { const sandbox = client({ listSandboxes: (req) => { requests.push(req); - if (req.pageToken === '') { + if (req.pageToken === 'resume') { return { sandboxes: [readySandbox('first', 'first-id').sandbox ?? {}], nextPageToken: 'page-2', @@ -501,14 +502,33 @@ describe('create', () => { }, }); - const listed = await sandbox.list({ pageSize: 1, labelSelector: 'team=core' }); - - expect(listed.map((item) => item.name)).toEqual(['first', 'second']); + const pager = sandbox.list({ pageSize: 1, pageToken: 'resume', labelSelector: 'team=core' }); + expect(requests).toHaveLength(0); + const first = await pager.nextPage(); + expect(first?.items.map((item) => item.name)).toEqual(['first']); + expect(first?.nextPageToken).toBe('page-2'); + const second = await pager.nextPage(); + expect(second?.items.map((item) => item.name)).toEqual(['second']); + expect(second?.nextPageToken).toBe(''); + await expect(pager.nextPage()).resolves.toBeUndefined(); expect(requests).toHaveLength(2); - expect(requests[0]).toMatchObject({ pageToken: '', pageSize: 1, labelSelector: 'team=core' }); + expect(requests[0]).toMatchObject({ pageToken: 'resume', pageSize: 1, labelSelector: 'team=core' }); expect(requests[1]).toMatchObject({ pageToken: 'page-2', pageSize: 1, labelSelector: 'team=core' }); }); + it('retries the same page token after a fetch error', async () => { + const tokens: string[] = []; + const pager = new Pager(async (token) => { + tokens.push(token); + if (tokens.length === 1) throw new Error('temporary failure'); + return { items: [1], nextPageToken: '' }; + }, 'resume'); + + await expect(pager.nextPage()).rejects.toThrow('temporary failure'); + await expect(pager.nextPage()).resolves.toEqual({ items: [1], nextPageToken: '' }); + expect(tokens).toEqual(['resume', 'resume']); + }); + it('createFromTemplate rejects an empty template name locally', async () => { const sandbox = client({}); await expect(sandbox.createFromTemplate({ templateName: ' ' })).rejects.toMatchObject({ @@ -653,7 +673,7 @@ describe('sandbox templates', () => { }); const got = await templates.get('gpu-kata', { workspace: 'staging' }); - const listed = await templates.list({ workspace: 'staging', pageSize: 10, labelSelector: 'team=runtime' }); + const listed = await templates.listAll({ workspace: 'staging', pageSize: 10, labelSelector: 'team=runtime' }); const deleted = await templates.delete('gpu-kata', { workspace: 'staging' }); expect(got.metadata?.name).toBe('gpu-kata'); @@ -681,7 +701,7 @@ describe('sandbox templates', () => { }, }); - await templates.list({ allWorkspaces: true }); + await templates.listAll({ allWorkspaces: true }); expect(selectedWorkspace(observed)).toBeUndefined(); expect(selectsAllWorkspaces(observed)).toBe(true); diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index 989ce2f0a7..37f145c4c3 100644 --- a/sdk/typescript/src/client.ts +++ b/sdk/typescript/src/client.ts @@ -150,8 +150,10 @@ export interface SandboxWorkloadTemplateProvenance { } interface PaginationOptions { - /** Page size used while collecting every result. */ + /** Maximum resources requested per page. */ pageSize?: number; + /** Opaque token from a previous page. Omit to start at the beginning. */ + pageToken?: string; labelSelector?: string; } @@ -175,8 +177,10 @@ export interface SandboxTemplateWorkspaceOptions { } export type SandboxTemplateListOptions = WorkspaceListScope & { - /** Page size used while collecting every result. */ + /** Maximum templates requested per page. */ pageSize?: number; + /** Opaque token from a previous page. Omit to start at the beginning. */ + pageToken?: string; /** Optional label selector in key=value comma-separated form. */ labelSelector?: string; }; @@ -636,6 +640,47 @@ export class Pushable implements AsyncIterable { } } +/** One response page from a list operation. */ +export interface Page { + readonly items: T[]; + readonly nextPageToken: string; +} + +/** Lazy, single-pass iterator that fetches one RPC page per advance. */ +export class Pager implements AsyncIterable> { + private nextToken: string | undefined; + + constructor( + private readonly fetch: (pageToken: string) => Promise>, + pageToken = '', + ) { + this.nextToken = pageToken; + } + + /** Fetch the next page, or return undefined after the final page. */ + async nextPage(): Promise | undefined> { + if (this.nextToken === undefined) return undefined; + const page = await this.fetch(this.nextToken); + this.nextToken = page.nextPageToken === '' ? undefined : page.nextPageToken; + return page; + } + + /** Consume the pager and collect every remaining item. */ + async all(): Promise { + const items: T[] = []; + for await (const page of this) items.push(...page.items); + return items; + } + + async *[Symbol.asyncIterator](): AsyncIterator> { + for (;;) { + const page = await this.nextPage(); + if (page === undefined) return; + yield page; + } + } +} + // ---- sandbox template client ---------------------------------------------- // Reusable sandbox workload template lifecycle. Templates intentionally return @@ -685,24 +730,25 @@ export class SandboxTemplateClient { } } - async list(options?: SandboxTemplateListOptions | null): Promise { - try { - const templates: SandboxWorkloadTemplate[] = []; - let pageToken = ''; - do { + list(options?: SandboxTemplateListOptions | null): Pager { + return new Pager(async (pageToken) => { + try { const resp = await this.grpc.listSandboxTemplates({ pageSize: options?.pageSize ?? 0, pageToken, labelSelector: options?.labelSelector ?? '', workspaceScope: listWorkspaceScope(options), }); - templates.push(...resp.templates); - pageToken = resp.nextPageToken; - } while (pageToken !== ''); - return templates; - } catch (e) { - throw fromConnect(e); - } + return { items: resp.templates, nextPageToken: resp.nextPageToken }; + } catch (e) { + throw fromConnect(e); + } + }, options?.pageToken ?? ''); + } + + /** List and collect every sandbox template in this scope. */ + async listAll(options?: SandboxTemplateListOptions | null): Promise { + return this.list(options).all(); } async delete(name: string, options?: SandboxTemplateWorkspaceOptions | null): Promise { @@ -815,24 +861,28 @@ export class SandboxClient { } } - async list(options?: ListOptions | null): Promise { - try { - const sandboxes: SandboxRef[] = []; - let pageToken = ''; - do { + list(options?: ListOptions | null): Pager { + return new Pager(async (pageToken) => { + try { const resp = await this.grpc.listSandboxes({ pageSize: options?.pageSize ?? 0, pageToken, labelSelector: options?.labelSelector ?? '', workspaceScope: listWorkspaceScope(options), }); - sandboxes.push(...resp.sandboxes.map((sandbox) => sandboxRef(sandbox))); - pageToken = resp.nextPageToken; - } while (pageToken !== ''); - return sandboxes; - } catch (e) { - throw fromConnect(e); - } + return { + items: resp.sandboxes.map((sandbox) => sandboxRef(sandbox)), + nextPageToken: resp.nextPageToken, + }; + } catch (e) { + throw fromConnect(e); + } + }, options?.pageToken ?? ''); + } + + /** List and collect every sandbox in this scope. */ + async listAll(options?: ListOptions | null): Promise { + return this.list(options).all(); } async delete(name: string, options?: SandboxWorkspaceOptions | null): Promise { diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index 5d02fe6b61..4935f49b1d 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -18,6 +18,7 @@ export type { Health, HealthStatus, ListOptions, + Page, PolicySourceName, ProviderChange, ProviderChangeOptions, @@ -45,7 +46,7 @@ export type { WaitOptions, WorkspaceListScope, } from './client.js'; -export { errorCode, OpenShellClient, SandboxClient, SandboxTemplateClient } from './client.js'; +export { errorCode, OpenShellClient, Pager, SandboxClient, SandboxTemplateClient } from './client.js'; export type { SdkErrorCode } from './errors.js'; export { SdkError } from './errors.js'; export type { ClientCredentialsOptions, OidcTokenProvider } from './oidc.js'; From 38f2aef930140a74ecc573811ab7f3ac15d14b8a Mon Sep 17 00:00:00 2001 From: Drew Newberry Date: Fri, 11 Sep 2026 00:36:09 +0000 Subject: [PATCH 10/12] feat(gateway): support selective compute driver builds (#3118) * feat(gateway): support selective compute driver builds Signed-off-by: Drew Newberry * feat(gateway): support selective Windows MXC builds Signed-off-by: Drew Newberry --------- Signed-off-by: Drew Newberry --- .../build-openshell-mxc-windows/SKILL.md | 18 ++- .github/workflows/branch-checks.yml | 10 ++ Cargo.lock | 2 + README.md | 15 ++ architecture/compute-runtimes.md | 19 ++- architecture/windows-msvc-build.md | 8 + crates/openshell-driver-mxc/Cargo.toml | 2 +- crates/openshell-gateway/Cargo.toml | 15 +- crates/openshell-gateway/src/lib.rs | 142 ++++++++++++++---- docs/reference/sandbox-compute-drivers.mdx | 27 ++++ skills/debug-openshell-cluster/SKILL.md | 20 ++- tasks/scripts/windows-msvc.ps1 | 12 +- 12 files changed, 240 insertions(+), 50 deletions(-) diff --git a/.agents/skills/build-openshell-mxc-windows/SKILL.md b/.agents/skills/build-openshell-mxc-windows/SKILL.md index 8ce602ce9d..17d62a64f5 100644 --- a/.agents/skills/build-openshell-mxc-windows/SKILL.md +++ b/.agents/skills/build-openshell-mxc-windows/SKILL.md @@ -252,6 +252,13 @@ in the gateway build graph, but their Unix-socket standalone binaries do not. Windows must continue to reject unsupported compute drivers clearly. +The gateway's `compute-driver-mxc` feature independently links and registers +MXC on Windows. Each other `compute-driver-*` feature installs its own Windows +rejection stub without linking that driver crate. The default +`in-tree-compute-drivers` alias enables all five features. An MXC-only build +uses `--no-default-features --features compute-driver-mxc` (add `telemetry` +and `bundled-z3` as needed). + | Driver | Windows build behavior | Runtime behavior | |---|---|---| | Docker | Driver crate excluded; gateway registration stub retained. | Gateway construction returns unsupported. | @@ -263,11 +270,16 @@ The focused contract tasks for either native architecture run: ```text windows_builtin_compute_drivers_report_unsupported +default_registry_contains_exactly_the_enabled_compute_drivers ``` -These tests are also included in the full x64 workspace test run. The focused -task is available for local diagnosis; GitHub Actions does not re-run it after -the full suite. +The same tasks also run gateway library tests for protocol-only, MXC-only, +Docker-stub-only, and MXC plus Docker-stub builds. Their logs use +`test--selective-.log`. + +The default-feature tests are also included in the full workspace test run. +The focused task is available for local diagnosis and selective-build +validation; GitHub Actions does not re-run it after the full suite. ## Test Accounting Guidance diff --git a/.github/workflows/branch-checks.yml b/.github/workflows/branch-checks.yml index 6739434bf0..15d49b82b3 100644 --- a/.github/workflows/branch-checks.yml +++ b/.github/workflows/branch-checks.yml @@ -182,6 +182,16 @@ jobs: cargo build -p openshell-sandbox --bin openshell-sandbox --no-default-features --features defaults-without-telemetry tasks/scripts/verify-telemetry-compiled-out.sh absent target/debug/openshell-sandbox + - name: Verify selective gateway compute-driver builds + run: | + cargo test -p openshell-gateway --all-targets --no-default-features + cargo test -p openshell-gateway --all-targets --no-default-features --features compute-driver-docker + cargo test -p openshell-gateway --all-targets --no-default-features --features compute-driver-kubernetes + cargo test -p openshell-gateway --all-targets --no-default-features --features compute-driver-podman + cargo test -p openshell-gateway --all-targets --no-default-features --features compute-driver-vm + cargo test -p openshell-gateway --all-targets --no-default-features --features compute-driver-mxc + cargo test -p openshell-gateway --all-targets --no-default-features --features compute-driver-docker,compute-driver-vm + - name: Verify the defaults-without-telemetry feature alias tracks the default feature set run: tasks/scripts/verify-defaults-without-telemetry.sh diff --git a/Cargo.lock b/Cargo.lock index 99638e63be..a452bcfac7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5812,6 +5812,7 @@ dependencies = [ "log", "percent-encoding", "pin-project-lite", + "quinn", "rustls", "rustls-native-certs", "rustls-pki-types", @@ -6124,6 +6125,7 @@ dependencies = [ "aws-lc-rs", "log", "once_cell", + "ring", "rustls-pki-types", "rustls-webpki", "subtle", diff --git a/README.md b/README.md index 35faf5c1bc..70e6e5c09f 100644 --- a/README.md +++ b/README.md @@ -274,6 +274,21 @@ cargo build --release -p openshell-driver-vm --no-default-features --features de The resulting binaries contain no telemetry endpoint, no telemetry HTTP client, and no emission code. With telemetry compiled out, the gateway emits nothing and reports telemetry disabled to the sandboxes it launches. Cargo has no way to subtract a single default feature, so `defaults-without-telemetry` must be paired with `--no-default-features`; passing it on its own leaves the defaults in place and fails the build rather than producing a binary that still emits. +The gateway also exposes separate Cargo features for its built-in compute drivers: `compute-driver-kubernetes`, `compute-driver-docker`, `compute-driver-podman`, `compute-driver-vm`, and `compute-driver-mxc`. Disable the default feature set, then enable only the drivers and telemetry mode required by the target binary. For example: + +```shell +# Docker only, with telemetry support. +cargo build --release -p openshell-gateway --no-default-features --features telemetry,compute-driver-docker + +# Docker and VM only, with telemetry compiled out. +cargo build --release -p openshell-gateway --no-default-features --features compute-driver-docker,compute-driver-vm + +# Windows MXC only, with telemetry support and bundled Z3. +cargo build --release -p openshell-gateway --no-default-features --features telemetry,compute-driver-mxc,bundled-z3 +``` + +Regular builds retain their platform driver set through the default `in-tree-compute-drivers` compatibility feature. On Windows, `compute-driver-mxc` selects MXC; the other four features install unsupported-driver stubs. On other platforms, MXC is excluded. + Telemetry events are limited to anonymous operational categories and counts, such as sandbox lifecycle outcomes, provider profile buckets, policy decision counts, and aggregate network activity denial categories. OpenShell telemetry does not collect sandbox names or IDs, hostnames, file paths, binary paths, prompts, credentials, provider names, model names, or user content. Opting out applies only to telemetry emitted by OpenShell. Third-party services, model providers, inference endpoints, agents, or tools that you configure and use with OpenShell may have their own terms and privacy practices. diff --git a/architecture/compute-runtimes.md b/architecture/compute-runtimes.md index e1e731a0ce..2210a7d28f 100644 --- a/architecture/compute-runtimes.md +++ b/architecture/compute-runtimes.md @@ -133,13 +133,18 @@ server constructs the common runtime adapter and snapshots `GetCapabilities` for either result. A configured UDS endpoint still takes precedence over a compiled registration with the same name. -The `openshell-gateway` composition crate groups first-party registrations -behind the `in-tree-compute-drivers` feature. `openshell-server` has no compute -driver dependencies or backend-name dispatch. Protocol-only gateway builds -disable the composition feature and link no compute-driver crates. E2E lanes -compose that gateway with Docker, Podman, Kubernetes, and VM driver executables -over the public UDS gRPC contract so an in-tree driver cannot silently depend -on a server-only API. +The `openshell-gateway` composition crate exposes one feature per first-party +registration: `compute-driver-kubernetes`, `compute-driver-docker`, +`compute-driver-podman`, `compute-driver-vm`, and `compute-driver-mxc`. Builds +can enable any subset. MXC links only on Windows; the other four features +install rejection stubs on Windows and link their drivers on other platforms. +The default `in-tree-compute-drivers` feature remains an alias for all five, +preserving each platform's default registrations. +`openshell-server` has no compute driver dependencies or backend-name dispatch. +Protocol-only gateway builds disable the default features and link no +compute-driver crates. E2E lanes compose that gateway with Docker, Podman, +Kubernetes, and VM driver executables over the public UDS gRPC contract so an +in-tree driver cannot silently depend on a server-only API. ## Stop and Start Lifecycle diff --git a/architecture/windows-msvc-build.md b/architecture/windows-msvc-build.md index cdea4a3fdc..dfcdbe6dd5 100644 --- a/architecture/windows-msvc-build.md +++ b/architecture/windows-msvc-build.md @@ -31,6 +31,14 @@ Windows. These registrations preserve config-file selection and reject unsupported drivers with a clear error without depending on their runtime crates. +Each stub follows its corresponding `compute-driver-*` Cargo feature. +`compute-driver-mxc` independently links and registers MXC, so a gateway built +with only that feature has only the MXC registration. The default +`in-tree-compute-drivers` alias enables all five features and preserves the +existing MXC plus unsupported-driver registrations. The focused Windows +contract tasks cover default, protocol-only, MXC-only, Docker-stub-only, and +MXC plus Docker-stub compositions. + The Windows lane does not build, release, package, or smoke-test standalone driver binaries for Docker, Kubernetes, Podman, or VM. Those binaries are Linux or macOS deliverables only. diff --git a/crates/openshell-driver-mxc/Cargo.toml b/crates/openshell-driver-mxc/Cargo.toml index 2f82e50e3b..1785c78133 100644 --- a/crates/openshell-driver-mxc/Cargo.toml +++ b/crates/openshell-driver-mxc/Cargo.toml @@ -14,7 +14,7 @@ repository.workspace = true name = "openshell_driver_mxc" [dependencies] -openshell-core = { path = "../openshell-core" } +openshell-core = { path = "../openshell-core", default-features = false } tokio = { workspace = true } tonic = { workspace = true } futures = { workspace = true } diff --git a/crates/openshell-gateway/Cargo.toml b/crates/openshell-gateway/Cargo.toml index f9d02027e0..ce3bf3b499 100644 --- a/crates/openshell-gateway/Cargo.toml +++ b/crates/openshell-gateway/Cargo.toml @@ -40,9 +40,17 @@ openshell-driver-mxc = { path = "../openshell-driver-mxc", optional = true } [features] default = ["telemetry", "in-tree-compute-drivers"] in-tree-compute-drivers = [ - "dep:openshell-driver-docker", - "dep:openshell-driver-kubernetes", - "dep:openshell-driver-podman", + "compute-driver-docker", + "compute-driver-kubernetes", + "compute-driver-podman", + "compute-driver-vm", + "compute-driver-mxc", +] +compute-driver-mxc = ["dep:openshell-driver-mxc"] +compute-driver-docker = ["dep:openshell-driver-docker", "dep:openshell-otel"] +compute-driver-kubernetes = ["dep:openshell-driver-kubernetes", "dep:openshell-otel"] +compute-driver-podman = ["dep:openshell-driver-podman", "dep:openshell-otel"] +compute-driver-vm = [ "dep:openshell-otel", "dep:hyper-util", "dep:nix", @@ -51,7 +59,6 @@ in-tree-compute-drivers = [ "dep:tonic", "dep:tower", "dep:tracing", - "dep:openshell-driver-mxc", ] telemetry = ["openshell-core/telemetry", "openshell-server/telemetry"] ## Convenience alias: every default feature except `telemetry`. Build a diff --git a/crates/openshell-gateway/src/lib.rs b/crates/openshell-gateway/src/lib.rs index 54ae5e5de3..bd05a27dac 100644 --- a/crates/openshell-gateway/src/lib.rs +++ b/crates/openshell-gateway/src/lib.rs @@ -16,12 +16,29 @@ compile_error!( build a telemetry-free gateway with `--no-default-features --features defaults-without-telemetry`" ); -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[cfg(all(not(target_os = "windows"), feature = "compute-driver-vm"))] mod vm; -#[cfg(feature = "in-tree-compute-drivers")] +#[cfg(any( + all(target_os = "windows", feature = "compute-driver-mxc"), + all( + not(target_os = "windows"), + any( + feature = "compute-driver-docker", + feature = "compute-driver-kubernetes", + feature = "compute-driver-podman", + feature = "compute-driver-vm" + ) + ) +))] use openshell_core::telemetry::TelemetryComputeDriver; -#[cfg(feature = "in-tree-compute-drivers")] +#[cfg(any( + target_os = "windows", + feature = "compute-driver-docker", + feature = "compute-driver-kubernetes", + feature = "compute-driver-podman", + feature = "compute-driver-vm" +))] use openshell_server::ComputeDriverRegistration; use openshell_server::ComputeDriverRegistry; @@ -30,14 +47,24 @@ use openshell_server::ComputeDriverRegistry; pub fn install_default_compute_drivers() -> ComputeDriverRegistry { #[allow(unused_mut)] let mut registry = ComputeDriverRegistry::new(); - #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] + #[cfg(all( + not(target_os = "windows"), + any( + feature = "compute-driver-docker", + feature = "compute-driver-kubernetes", + feature = "compute-driver-podman", + feature = "compute-driver-vm" + ) + ))] install_in_tree_compute_drivers(&mut registry); - #[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] + #[cfg(all(target_os = "windows", feature = "compute-driver-mxc"))] install_mxc_compute_driver(&mut registry); + #[cfg(target_os = "windows")] + install_unsupported_windows_compute_drivers(&mut registry); registry } -#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] +#[cfg(all(target_os = "windows", feature = "compute-driver-mxc"))] fn install_mxc_compute_driver(registry: &mut ComputeDriverRegistry) { let registration = ComputeDriverRegistration::new("mxc", u16::MAX, None, MxcFactory) .expect("first-party driver name is valid") @@ -46,8 +73,21 @@ fn install_mxc_compute_driver(registry: &mut ComputeDriverRegistry) { registry .install(registration) .expect("first-party driver names are unique"); +} - for name in ["docker", "kubernetes", "podman", "vm"] { +#[cfg(target_os = "windows")] +fn install_unsupported_windows_compute_drivers(registry: &mut ComputeDriverRegistry) { + let names: &[&str] = &[ + #[cfg(feature = "compute-driver-docker")] + "docker", + #[cfg(feature = "compute-driver-kubernetes")] + "kubernetes", + #[cfg(feature = "compute-driver-podman")] + "podman", + #[cfg(feature = "compute-driver-vm")] + "vm", + ]; + for &name in names { let registration = ComputeDriverRegistration::new( name, u16::MAX, @@ -61,13 +101,13 @@ fn install_mxc_compute_driver(registry: &mut ComputeDriverRegistry) { } } -#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] +#[cfg(target_os = "windows")] #[derive(Clone, Copy)] struct UnsupportedWindowsFactory { name: &'static str, } -#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] +#[cfg(target_os = "windows")] #[async_trait::async_trait] impl openshell_server::ComputeDriverFactory for UnsupportedWindowsFactory { async fn build( @@ -78,16 +118,16 @@ impl openshell_server::ComputeDriverFactory for UnsupportedWindowsFactory { } } -#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] +#[cfg(target_os = "windows")] fn unsupported_windows_compute_driver(name: &str) -> openshell_core::Error { openshell_core::Error::config(format!("compute driver '{name}' is unsupported on Windows")) } -#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] +#[cfg(all(target_os = "windows", feature = "compute-driver-mxc"))] #[derive(Clone, Copy)] struct MxcFactory; -#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] +#[cfg(all(target_os = "windows", feature = "compute-driver-mxc"))] #[async_trait::async_trait] impl openshell_server::ComputeDriverFactory for MxcFactory { async fn build( @@ -103,9 +143,18 @@ impl openshell_server::ComputeDriverFactory for MxcFactory { } } -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[cfg(all( + not(target_os = "windows"), + any( + feature = "compute-driver-docker", + feature = "compute-driver-kubernetes", + feature = "compute-driver-podman", + feature = "compute-driver-vm" + ) +))] fn install_in_tree_compute_drivers(registry: &mut ComputeDriverRegistry) { for registration in [ + #[cfg(feature = "compute-driver-kubernetes")] ComputeDriverRegistration::new( "kubernetes", 100, @@ -128,6 +177,7 @@ fn install_in_tree_compute_drivers(registry: &mut ComputeDriverRegistry) { "sa_token_ttl_secs", ]) }), + #[cfg(feature = "compute-driver-podman")] ComputeDriverRegistration::new( "podman", 200, @@ -148,6 +198,7 @@ fn install_in_tree_compute_drivers(registry: &mut ComputeDriverRegistry) { "guest_tls_key", ]) }), + #[cfg(feature = "compute-driver-docker")] ComputeDriverRegistration::new( "docker", 300, @@ -169,6 +220,7 @@ fn install_in_tree_compute_drivers(registry: &mut ComputeDriverRegistry) { "guest_tls_key", ]) }), + #[cfg(feature = "compute-driver-vm")] ComputeDriverRegistration::new("vm", u16::MAX, None, VmFactory).map(|registration| { registration .with_telemetry_category(TelemetryComputeDriver::anonymous_category("vm")) @@ -187,11 +239,11 @@ fn install_in_tree_compute_drivers(registry: &mut ComputeDriverRegistry) { } } -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[cfg(all(not(target_os = "windows"), feature = "compute-driver-kubernetes"))] #[derive(Clone, Copy)] struct KubernetesFactory; -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[cfg(all(not(target_os = "windows"), feature = "compute-driver-kubernetes"))] #[async_trait::async_trait] impl openshell_server::ComputeDriverFactory for KubernetesFactory { async fn build( @@ -219,11 +271,11 @@ impl openshell_server::ComputeDriverFactory for KubernetesFactory { } } -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[cfg(all(not(target_os = "windows"), feature = "compute-driver-docker"))] #[derive(Clone, Copy)] struct DockerFactory; -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[cfg(all(not(target_os = "windows"), feature = "compute-driver-docker"))] #[async_trait::async_trait] impl openshell_server::ComputeDriverFactory for DockerFactory { async fn build( @@ -251,11 +303,11 @@ impl openshell_server::ComputeDriverFactory for DockerFactory { } } -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[cfg(all(not(target_os = "windows"), feature = "compute-driver-podman"))] #[derive(Clone, Copy)] struct PodmanFactory; -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[cfg(all(not(target_os = "windows"), feature = "compute-driver-podman"))] #[async_trait::async_trait] impl openshell_server::ComputeDriverFactory for PodmanFactory { async fn build( @@ -289,11 +341,11 @@ impl openshell_server::ComputeDriverFactory for PodmanFactory { } } -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[cfg(all(not(target_os = "windows"), feature = "compute-driver-vm"))] #[derive(Clone, Copy)] struct VmFactory; -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[cfg(all(not(target_os = "windows"), feature = "compute-driver-vm"))] #[async_trait::async_trait] impl openshell_server::ComputeDriverFactory for VmFactory { async fn build( @@ -333,7 +385,14 @@ impl openshell_server::ComputeDriverFactory for VmFactory { } } -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[cfg(all( + not(target_os = "windows"), + any( + feature = "compute-driver-docker", + feature = "compute-driver-podman", + feature = "compute-driver-vm" + ) +))] fn apply_guest_tls( ca: &mut Option, cert: &mut Option, @@ -351,19 +410,17 @@ fn apply_guest_tls( } } -#[cfg(all(test, target_os = "windows", feature = "in-tree-compute-drivers"))] +#[cfg(all(test, target_os = "windows"))] mod windows_tests { use super::*; #[test] fn windows_builtin_compute_drivers_report_unsupported() { let registry = install_default_compute_drivers(); - assert_eq!( - registry.installed_driver_names().collect::>(), - ["docker", "kubernetes", "mxc", "podman", "vm"] - ); - - for name in ["docker", "kubernetes", "podman", "vm"] { + for name in registry + .installed_driver_names() + .filter(|name| *name != "mxc") + { let message = unsupported_windows_compute_driver(name).to_string(); assert!( message.contains("unsupported on Windows"), @@ -372,3 +429,30 @@ mod windows_tests { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_registry_contains_exactly_the_enabled_compute_drivers() { + let expected: Vec<&str> = vec![ + #[cfg(feature = "compute-driver-docker")] + "docker", + #[cfg(feature = "compute-driver-kubernetes")] + "kubernetes", + #[cfg(all(target_os = "windows", feature = "compute-driver-mxc"))] + "mxc", + #[cfg(feature = "compute-driver-podman")] + "podman", + #[cfg(feature = "compute-driver-vm")] + "vm", + ]; + assert_eq!( + install_default_compute_drivers() + .installed_driver_names() + .collect::>(), + expected + ); + } +} diff --git a/docs/reference/sandbox-compute-drivers.mdx b/docs/reference/sandbox-compute-drivers.mdx index e46ebf8a23..885d897e4d 100644 --- a/docs/reference/sandbox-compute-drivers.mdx +++ b/docs/reference/sandbox-compute-drivers.mdx @@ -40,6 +40,33 @@ an exited canonical process remains a terminal sandbox result. Exit code zero produces `Completed`; a nonzero or signal-normalized exit produces `Error` with the exact exit code. Driver and supervisor failures remain `Error`. +## Build with Selected Compute Drivers + +Source builds of `openshell-gateway` can include any subset of the Docker, +Podman, Kubernetes, VM, and MXC drivers. Enable the corresponding +`compute-driver-docker`, `compute-driver-podman`, `compute-driver-kubernetes`, +`compute-driver-vm`, or `compute-driver-mxc` Cargo features. For example, build +a Docker-only gateway with telemetry support: + +```shell +cargo build --release -p openshell-gateway --no-default-features --features telemetry,compute-driver-docker +``` + +On Windows, select only MXC with: + +```shell +cargo build --release -p openshell-gateway --no-default-features --features telemetry,compute-driver-mxc,bundled-z3 +``` + +The default `in-tree-compute-drivers` feature retains the full platform driver +set, including MXC on Windows. MXC links only on Windows. The other four +features link drivers on non-Windows platforms; on Windows they install +registrations that report the driver as unsupported. A build with no default +features and no driver features connects to external drivers only. +Auto-detection probes only compiled registrations. +To select a driver omitted from a custom build, configure its external +`socket_path` as described below. + ## Configure a Compute Driver Configure the compute driver on the gateway. Current releases accept one driver per gateway. Set `compute_drivers` in the gateway TOML file: diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 7d47b18065..5b460ce7f6 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -21,11 +21,21 @@ The target deployment flow is: The `openshell-gateway` composition crate explicitly installs its compiled Docker, Podman, Kubernetes, and VM registrations at startup; `openshell-server` -does not link compute-driver crates. With no configured driver, the -gateway probes only installed registrations in priority order (Kubernetes, -Podman, then Docker); VM has no probe and remains opt-in. A custom gateway -binary may install a different set, so confirm the binary's registered drivers -when auto-detection reports that no suitable driver is available. +does not link compute-driver crates. Custom gateway binaries may include a +subset of those registrations. With no configured driver, the gateway probes only +installed registrations in priority order (Kubernetes, Podman, then Docker); +VM has no probe and remains opt-in. Confirm the binary's registered drivers +when auto-detection reports that no suitable driver is available. If +configuration selects a driver that was not compiled in, the gateway treats +the name as an external driver and reports a missing `socket_path` unless an +endpoint is configured. + +On Windows, custom binaries can include MXC independently. Registrations for +Docker, Podman, Kubernetes, and VM are rejection stubs when included; they do +not enable those runtimes on Windows. + +See the [compute driver reference](https://docs.nvidia.com/openshell/latest/reference/sandbox-compute-drivers.md) +for selective-build options and external-driver configuration. For local evaluation only, TLS may be disabled and the gateway can be reached through `http://127.0.0.1:`. diff --git a/tasks/scripts/windows-msvc.ps1 b/tasks/scripts/windows-msvc.ps1 index cab42fb719..63384e5cf7 100644 --- a/tasks/scripts/windows-msvc.ps1 +++ b/tasks/scripts/windows-msvc.ps1 @@ -536,7 +536,8 @@ function Invoke-UnsupportedContractTests([string] $RustTarget) { Assert-NativeTestTarget $RustTarget $tests = @( - "windows_builtin_compute_drivers_report_unsupported" + "windows_builtin_compute_drivers_report_unsupported", + "default_registry_contains_exactly_the_enabled_compute_drivers" ) foreach ($test in $tests) { Invoke-VsCargo ` @@ -544,6 +545,15 @@ function Invoke-UnsupportedContractTests([string] $RustTarget) { -CargoArgs "cargo test -p openshell-gateway --target $RustTarget $test $Z3ServerFeatures" ` -LogName "test-$RustTarget-unsupported-$test.log" } + + foreach ($features in @("", "compute-driver-mxc", "compute-driver-docker", "compute-driver-mxc,compute-driver-docker")) { + $featureArgs = if ($features) { "--features $features" } else { "" } + $variant = if ($features) { $features.Replace(",", "-") } else { "protocol-only" } + Invoke-VsCargo ` + -RustTarget $RustTarget ` + -CargoArgs "cargo test -p openshell-gateway --lib --target $RustTarget --no-default-features $featureArgs $Z3ServerFeatures" ` + -LogName "test-$RustTarget-selective-$variant.log" + } } function Get-Sha256([string] $Path) { From 35f15d8fcd2f96408e2e69f2ce069a1c3cadafe4 Mon Sep 17 00:00:00 2001 From: Piotr Mlocek Date: Fri, 11 Sep 2026 01:00:07 +0000 Subject: [PATCH 11/12] fix(packaging): refresh root Cargo lockfile (#3267) Signed-off-by: Piotr Mlocek From 0569c3a20a97bc8b60dd83cfba1d91fd3a76f375 Mon Sep 17 00:00:00 2001 From: Piotr Mlocek Date: Fri, 11 Sep 2026 01:29:34 +0000 Subject: [PATCH 12/12] ci(windows): make PR checks opt-in and main jobs advisory (#3268) Signed-off-by: Piotr Mlocek --- .agents/skills/build-openshell-mxc-windows/SKILL.md | 9 ++++++--- .github/workflows/windows-msvc.yml | 7 +++++-- CI.md | 6 ++++++ architecture/windows-msvc-build.md | 10 +++++++--- 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/.agents/skills/build-openshell-mxc-windows/SKILL.md b/.agents/skills/build-openshell-mxc-windows/SKILL.md index 17d62a64f5..cd5689d7bb 100644 --- a/.agents/skills/build-openshell-mxc-windows/SKILL.md +++ b/.agents/skills/build-openshell-mxc-windows/SKILL.md @@ -30,7 +30,7 @@ The Windows build lane is implemented by these tracked files: | `tasks/windows.toml` | Mise task entry points for `windows:*` commands. | | `tasks/rust.toml`, `tasks/test.toml`, and `tasks/markdown.toml` | Windows routing for compiler-bearing checks, explicit Unix-only test skips, and Markdown dependency setup. | | `tasks/scripts/windows-msvc.ps1` | PowerShell wrapper that enters the Visual Studio developer environment and invokes Cargo. | -| `.github/workflows/windows-msvc.yml` | PR/merge-queue lint and test plus main/manual cache seeding and dependent binary builds on native x64 and ARM64 runners. | +| `.github/workflows/windows-msvc.yml` | Opt-in PR lint and test plus advisory main/manual cache seeding and dependent binary builds on native x64 and ARM64 runners. | | `architecture/windows-msvc-build.md` | Design notes and validation contract. | | `.agents/skills/build-openshell-mxc-windows/` | This skill and companion reference material. | @@ -193,11 +193,14 @@ order: The GitHub Actions jobs layer architecture-specific `Swatinem/rust-cache` entries for Cargo registry and dependency target artifacts with sccache's GHA backend for cacheable Rust compiler outputs. Failed runs also save their usable -dependency artifacts. Pull-request mirrors and merge queues run Clippy for the +dependency artifacts. Pull-request mirrors labeled `test:windows` run Clippy for the Windows-supported workspace and e2e crates plus Rust tests. Pushes to `main` and manual dispatches run the same lint and test commands in a cache-seed job, followed by a dependent release-binary build job. The seed and PR jobs use the -same cache namespaces. The binaries are not uploaded or published. +same cache namespaces. Merge queues do not run this workflow. Main/manual seed +and build jobs use job-level `continue-on-error: true`; opt-in PR jobs report +failures normally. Applying the label alone does not start a run: re-run all +jobs in the current mirror push run, or push a new mirrored commit. The binaries are not uploaded or published. The ARM64 check/build steps in this x64-host contract are cross-builds. The wrapper discovers and adds host-native LLVM and Ninja to `PATH`, requires the diff --git a/.github/workflows/windows-msvc.yml b/.github/workflows/windows-msvc.yml index 4c7f0d29b8..00c41d9ca9 100644 --- a/.github/workflows/windows-msvc.yml +++ b/.github/workflows/windows-msvc.yml @@ -1,8 +1,6 @@ name: Windows MSVC on: - merge_group: - types: [checks_requested] push: branches: - main @@ -36,6 +34,8 @@ jobs: - id: gate if: github.ref != 'refs/heads/main' uses: ./.github/actions/pr-gate + with: + required_label: test:windows pr-check: name: PR lint and test (${{ matrix.arch }}) @@ -104,6 +104,8 @@ jobs: cache-seed: name: Seed cache (${{ matrix.arch }}) + # Keep main/manual Windows validation advisory while the lane matures. + continue-on-error: true needs: pr_metadata if: >- needs.pr_metadata.outputs.should_run == 'true' && @@ -164,6 +166,7 @@ jobs: build: name: Build binaries (${{ matrix.arch }}) + continue-on-error: true needs: cache-seed strategy: fail-fast: false diff --git a/CI.md b/CI.md index a84bd90638..4838595cc5 100644 --- a/CI.md +++ b/CI.md @@ -12,6 +12,12 @@ PR CI that runs on NVIDIA self-hosted runners uses NVIDIA's copy-pr-bot. The bot Merge queue validation is a second integration gate for `main`. After a PR has passed the required PR-head statuses, a maintainer adds it to the merge queue. GitHub creates a temporary merge-group branch that combines the latest `main`, the queued PR, and any earlier queued PRs. The same required `OpenShell / ...` status contexts are then published against the merge-group SHA before GitHub merges it. +Windows PR checks are opt-in: add `test:windows`, then select **Re-run all jobs** +on the current Windows MSVC run. Subsequent mirrored commits run them automatically. +Windows checks are not required for merging and do not run in merge queues. +Main and manual runs also build release binaries, with `continue-on-error: true` +so Windows failures do not fail the workflow. + Three opt-in labels enable the long-running E2E suites: - `test:e2e` runs the Docker, rootless Podman, Kubernetes, and VM E2E suites diff --git a/architecture/windows-msvc-build.md b/architecture/windows-msvc-build.md index dfcdbe6dd5..956b1b3e9c 100644 --- a/architecture/windows-msvc-build.md +++ b/architecture/windows-msvc-build.md @@ -63,7 +63,8 @@ creating misleading Windows driver artifacts. ## Mise Lane The GitHub Actions workflow runs Clippy for the Windows-supported workspace and -e2e crates plus Rust tests for pull-request mirror branches and merge queues. On +e2e crates plus Rust tests for pull-request mirror branches labeled `test:windows`. +Merge queues do not run this workflow. On pushes to `main`, a cache-seed job runs the same lint and test commands before a dependent job builds the release binaries. Manual dispatches exercise the same seed-then-build path. The binaries remain CI validation artifacts and are not @@ -154,7 +155,7 @@ break ARM64 crypto dependency builds. ## CI Shape The x64 GitHub Actions jobs run on `windows-2025`; native ARM64 jobs run on -`windows-11-arm`. Pull-request mirrors and merge queues execute the matching +`windows-11-arm`. Pull-request mirrors labeled `test:windows` execute the matching architecture-specific tasks: ```powershell @@ -163,7 +164,10 @@ mise run --skip-tools windows:test: ``` Pushes to `main` and manual dispatches first seed the shared caches with those -same lint and test commands. After the seed succeeds, a separate job executes: +same lint and test commands. Both seed and build jobs use job-level +`continue-on-error: true`, so Windows job failures do not fail the main/manual +workflow. Opt-in PR jobs still report failures normally. After the seed job +finishes, a separate job executes: ```powershell mise run --skip-tools windows:build: