Skip to content

Commit 9c019a9

Browse files
Wire authorization into workspace model (#2445)
* feat(auth): implement RFC 0011 Phase 2 workspace authorization Signed-off-by: Derek Carr <[email protected]> * fix(auth): address PR review feedback on workspace authorization - Docker e2e: add --health-port and switch readiness probe from `openshell status` to `curl /healthz`, fixing a false-positive readiness check in OIDC mode where the CLI exited 0 without actually contacting the gateway - ListWorkspaces: move membership filtering from post-query N+1 lookups into a SQL EXISTS subquery so pagination applies to the visible set, not the global ordering. Add generic list_with_membership to the persistence layer. - Descriptor validator: reject role/scope fields on unauthenticated and sandbox auth modes, and allow-list workspace_role as user/admin and global_role as platform_admin to catch typos at startup Signed-off-by: Derek Carr <[email protected]> * fix(server): use authed request in delete telemetry test The workspace authorization added by the Phase 2 auth changes requires a Principal on every delete request. The delete-telemetry test was still using a bare Request::new, so extract_principal failed before the handler could acquire the delete gate, causing a 5-second timeout flake. Signed-off-by: Derek Carr <[email protected]> * fix(auth): address gator review findings for workspace authorization - Inject unauthenticated-local-dev principal in no-auth gateway mode so handlers that call extract_principal() always find one. - Cap label-selector membership query at MAX_PAGE_SIZE instead of u32::MAX to bound the in-memory read. - Authorize workspace membership before resolving workspace existence in all sandbox RPCs to prevent workspace-name enumeration by non-members. - Remove dead_code allow on AuthorizedWorkspace.workspace now that callers use the normalized name from the authz result. Signed-off-by: Derek Carr <[email protected]> * fix(auth): close workspace-name oracle and label-selector truncation Swap authorize-before-resolve ordering in 27 handlers across provider.rs, service.rs, policy.rs, and workspace.rs to prevent CWE-203 workspace-name enumeration by non-members. Add combined membership+label SQL query (list_with_membership_and_selector) to both persistence backends so ListWorkspaces with label selectors no longer silently drops results beyond the first page of membership matches. Signed-off-by: Derek Carr <[email protected]> * test(auth): add non-member rejection and membership+label persistence tests Add comprehensive test coverage for workspace authorization changes: - Non-member rejection tests across all 44 workspace-scoped handlers (sandbox, provider, service, policy, workspace, inference) verifying PERMISSION_DENIED is returned instead of NOT_FOUND to prevent CWE-203 workspace-name oracle - Persistence test for list_with_membership_and_selector verifying SQL-level membership EXISTS + label filtering, multiple predicates, no-match cases, and pagination Signed-off-by: Derek Carr <[email protected]> * fix(auth): format merged import line in sandbox tests Signed-off-by: Derek Carr <[email protected]> * fix(auth): address gator re-review findings on workspace authorization - Fix TUI unconditionally setting providers_v2_enabled after provider refresh; read the actual gateway setting via GetGatewayConfig at startup instead - Fix SQLite json_extract with dotted label keys (e.g. example.com/env) by quoting the key in the JSON path - Add authed_request wrappers to upstream OCI identity tests that were missing a principal after rebase - Add test proving GetGatewayConfig is accessible without Platform Admin - Add test for dotted/prefixed Kubernetes-style label key filtering Signed-off-by: Derek Carr <[email protected]> * fix(auth): address second gator re-review findings - Loosen GetGatewayConfig from platform_admin to scope-only so workspace users can discover providers_v2_enabled during sandbox creation with inferred-provider commands; update proto descriptor, descriptor validation, and RFC 0011 access table - Add validate_label_selector to handle_list_workspaces and escape single quotes in SQLite json_extract interpolation (CWE-89 defense-in-depth) - Re-fetch providers_v2_enabled after TUI gateway switch so the new gateway's capability is reflected - Add e2e test for workspace user with inferred-provider command - Add persistence test for adversarial label keys with SQL injection attempts - Add handler test for invalid label selector rejection in ListWorkspaces Signed-off-by: Derek Carr <[email protected]> * fix(auth): address third gator review findings - Cap label selector pairs at 64 (CWE-400) to bound SQLite dynamic SQL - Add SCOPE_ONLY_METHODS allowlist for scope-without-role RPCs (CWE-863) - Normalize ID-based data-plane handlers to return NOT_FOUND for unauthorized sandboxes, closing the cross-workspace oracle (CWE-203) - Fix TUI provider profile cache lookup key mismatch for legacy providers with empty profile_workspace - Add whoami to CLI skill reference command tree - Update TUI skill doc with workspace, provider, and settings coverage - Document scope/workspace orthogonality on GetGatewayConfig proto Signed-off-by: Derek Carr <[email protected]> * fix(auth): extend CWE-203 normalization to policy.rs sandbox handlers GetSandboxConfig and GetSandboxLogs in policy.rs had the same fetch-before-authorize pattern that leaked cross-workspace sandbox existence. Promote fetch_and_authorize_sandbox to pub(super) and use it from both sandbox.rs and policy.rs handlers. Signed-off-by: Derek Carr <[email protected]> * test(auth): update assertions for CWE-203 sandbox ID normalization Cross-workspace sandbox access via ID-based handlers now returns NOT_FOUND instead of PERMISSION_DENIED to prevent existence inference. Update the unit test and OIDC e2e assertion to match. Signed-off-by: Derek Carr <[email protected]> * fix(auth): narrow CWE-203 error mapping and correct whoami output formats Only remap PERMISSION_DENIED to NOT_FOUND in fetch_and_authorize_sandbox and RevokeSshSession, letting INTERNAL and UNAUTHENTICATED propagate as-is. Fix whoami --output format values in cli-reference.md to match the actual CLI (table/json/yaml, not text/json). Signed-off-by: Derek Carr <[email protected]> * fix(ci): share network namespace with Keycloak in containerized CI In GitHub Actions job containers, Docker port publishing lands on the host, not inside the job container. Detect this environment and attach Keycloak to the job container's network namespace instead, with hardened defaults (cap-drop ALL, no-new-privileges, loopback-only listener). Signed-off-by: Derek Carr <[email protected]> --------- Signed-off-by: Derek Carr <[email protected]>
1 parent 1cbfc0d commit 9c019a9

69 files changed

Lines changed: 9008 additions & 1462 deletions

Some content is hidden

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

‎.agents/skills/openshell-cli/SKILL.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,15 @@ Use an `http://` endpoint only for trusted local port-forwarding or a protected
5252

5353
```bash
5454
openshell status
55+
openshell whoami
5556
```
5657

5758
Confirm the gateway is reachable, authentication is valid or not required, and
5859
the output shows a version. `Status: Connected` only proves the public health
5960
endpoint is reachable; inspect the separate `Authentication` line before
60-
running protected commands.
61+
running protected commands. `openshell whoami` reports the identity validated
62+
by the gateway, including the subject an administrator uses for workspace
63+
membership. Add `--output json` for automation.
6164

6265
### Step 3: Create a sandbox
6366

@@ -625,6 +628,7 @@ $ openshell sandbox upload --help
625628
|------|---------|
626629
| Register local port-forwarded gateway | `openshell gateway add http://127.0.0.1:8080 --local --name local` |
627630
| Check gateway health and authentication | `openshell status` |
631+
| Show authenticated identity and subject | `openshell whoami` |
628632
| List/switch gateways | `openshell gateway select [name]` |
629633
| Connect directly to a gateway | `openshell --gateway-endpoint <url> status` |
630634
| Create sandbox (interactive) | `openshell sandbox create` |

‎.agents/skills/openshell-cli/cli-reference.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ openshell
3939
│ ├── list
4040
│ └── select [name]
4141
├── status
42+
├── whoami [--output <format>]
4243
├── inference
4344
│ ├── set --provider --model
4445
│ ├── update [--provider] [--model]
@@ -186,6 +187,15 @@ gateway. Connectivity uses the public health RPC; authentication is checked
186187
with the protected gateway-info capability query and can fail while the gateway
187188
remains connected.
188189

190+
### `openshell whoami`
191+
192+
Show the authenticated user identity: subject, display name, roles, scopes, and
193+
identity provider. Requires an authenticated gateway connection.
194+
195+
| Flag | Description |
196+
|------|-------------|
197+
| `--output <FORMAT>` | Output format: `table` (default), `json`, or `yaml` |
198+
189199
---
190200

191201
## Sandbox Commands

‎.agents/skills/tui-development/SKILL.md‎

Lines changed: 157 additions & 37 deletions
Large diffs are not rendered by default.

‎.github/workflows/e2e-test.yml‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,12 @@ jobs:
5050
- suite: python
5151
cmd: "mise run --no-deps --skip-deps e2e:python"
5252
apt_packages: ""
53+
- suite: oidc-python
54+
cmd: "mise run --no-deps --skip-deps e2e:oidc-python:docker"
55+
apt_packages: ""
56+
- suite: oidc-pkce-docker
57+
cmd: "mise run --no-deps --skip-deps e2e:oidc-pkce:docker"
58+
apt_packages: "openssh-client"
5359
- suite: rust-docker
5460
cmd: "mise run --no-deps --skip-deps e2e:rust"
5561
apt_packages: "openssh-client"
@@ -111,7 +117,7 @@ jobs:
111117
run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin
112118

113119
- name: Install Python dependencies and generate protobuf stubs
114-
if: matrix.suite == 'python'
120+
if: matrix.suite == 'python' || matrix.suite == 'oidc-python'
115121
run: uv sync --frozen && mise run --no-deps python:proto
116122

117123
- name: Run tests

‎Cargo.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎architecture/gateway.md‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,8 +157,15 @@ does not grant sandbox identity. Kubernetes deployments use the
157157
gateway-minted JWT bootstrap path: the supervisor starts with a projected
158158
ServiceAccount token, exchanges it for a gateway-minted sandbox JWT, and uses
159159
that JWT on subsequent gateway RPCs.
160-
User-facing mutations are authorized by role policy when OIDC or edge identity
161-
is enabled.
160+
User-facing RPCs are authorized by descriptor-declared role and scope policy
161+
when OIDC or edge identity is enabled. The OIDC admin role grants platform-wide
162+
access and bypasses workspace membership checks. Workspace Admin and Workspace
163+
User roles are durable membership records keyed by workspace and authenticated
164+
subject. Handlers resolve the resource workspace and require sufficient
165+
membership after the middleware validates the global role and optional scope.
166+
The authenticated `GetCurrentUser` endpoint exposes the gateway's validated
167+
user subject, display name, roles, scopes, and identity provider for CLI
168+
identity inspection without client-side token decoding.
162169

163170
Sandbox secrets are gateway-signed JWTs bound to a single sandbox ID. Docker,
164171
Podman, and VM drivers deliver the initial token through supervisor-only

‎crates/openshell-cli/src/main.rs‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,7 @@ const HELP_TEMPLATE: &str = "\
263263
\x1b[1mGATEWAY COMMANDS\x1b[0m
264264
gateway: Manage gateways
265265
status: Show gateway status and information
266+
whoami: Show the authenticated user identity
266267
inference: Manage inference configuration
267268
doctor: Diagnose gateway issues
268269
@@ -588,6 +589,14 @@ enum Commands {
588589
output: OutputFormat,
589590
},
590591

592+
/// Show the identity validated by the gateway.
593+
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
594+
Whoami {
595+
/// Output format.
596+
#[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table)]
597+
output: OutputFormat,
598+
},
599+
591600
/// Manage inference configuration.
592601
#[command(after_help = INFERENCE_EXAMPLES, help_template = SUBCOMMAND_HELP_TEMPLATE)]
593602
Inference {
@@ -2312,6 +2321,16 @@ async fn main() -> Result<()> {
23122321
}
23132322
}
23142323

2324+
// -----------------------------------------------------------
2325+
// Top-level current identity
2326+
// -----------------------------------------------------------
2327+
Some(Commands::Whoami { output }) => {
2328+
let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?;
2329+
let mut tls = tls.with_gateway_name(&ctx.name);
2330+
apply_auth(&mut tls, &ctx.name);
2331+
run::whoami(&ctx.endpoint, &tls, output.as_str()).await?;
2332+
}
2333+
23152334
// -----------------------------------------------------------
23162335
// Top-level forward (was `sandbox forward`)
23172336
// -----------------------------------------------------------
@@ -3924,6 +3943,19 @@ mod tests {
39243943
assert!(matches!(cli.command, Some(Commands::Status { .. })));
39253944
}
39263945

3946+
#[test]
3947+
fn whoami_accepts_output_json() {
3948+
let cli = Cli::try_parse_from(["openshell", "whoami", "--output", "json"])
3949+
.expect("whoami --output json should parse");
3950+
3951+
assert!(matches!(
3952+
cli.command,
3953+
Some(Commands::Whoami {
3954+
output: OutputFormat::Json
3955+
})
3956+
));
3957+
}
3958+
39273959
#[test]
39283960
fn gateway_info_accepts_output_json() {
39293961
let cli = Cli::try_parse_from(["openshell", "gateway", "info", "-o", "json"])

‎crates/openshell-cli/src/run.rs‎

Lines changed: 82 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -38,20 +38,21 @@ use openshell_core::proto::{
3838
CreateSandboxRequest, CreateSshSessionRequest, DeleteInferenceRouteRequest,
3939
DeleteProviderProfileRequest, DeleteProviderRefreshRequest, DeleteProviderRequest,
4040
DeleteSandboxRequest, DeleteServiceRequest, DetachSandboxProviderRequest, ExecSandboxRequest,
41-
ExposeServiceRequest, GetDraftHistoryRequest, GetDraftPolicyRequest, GetGatewayConfigRequest,
42-
GetInferenceRouteRequest, GetProviderProfileRequest, GetProviderRefreshStatusRequest,
43-
GetProviderRequest, GetSandboxConfigRequest, GetSandboxConfigResponse, GetSandboxLogsRequest,
44-
GetSandboxPolicyStatusRequest, GetSandboxRequest, GetServiceRequest, GpuResourceRequirements,
45-
ImportProviderProfilesRequest, LintProviderProfilesRequest, ListProviderProfilesRequest,
46-
ListProvidersRequest, ListSandboxPoliciesRequest, ListSandboxProvidersRequest,
47-
ListSandboxesRequest, ListServicesRequest, PolicySource, PolicyStatus, Provider,
48-
ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, ProviderProfile,
49-
ProviderProfileDiagnostic, ProviderProfileImportItem, RejectDraftChunkRequest,
50-
ResourceRequirements, RevokeSshSessionRequest, RotateProviderCredentialRequest, Sandbox,
51-
SandboxPhase, SandboxPolicy, SandboxSpec, SandboxTemplate, ServiceEndpointResponse,
52-
SetInferenceRouteRequest, SettingScope, TcpForwardFrame, TcpForwardInit, TcpRelayTarget,
53-
UpdateConfigRequest, UpdateProviderProfilesRequest, UpdateProviderRequest, WatchSandboxRequest,
54-
exec_sandbox_event, setting_value, tcp_forward_init,
41+
ExposeServiceRequest, GetCurrentUserRequest, GetDraftHistoryRequest, GetDraftPolicyRequest,
42+
GetGatewayConfigRequest, GetInferenceRouteRequest, GetProviderProfileRequest,
43+
GetProviderRefreshStatusRequest, GetProviderRequest, GetSandboxConfigRequest,
44+
GetSandboxConfigResponse, GetSandboxLogsRequest, GetSandboxPolicyStatusRequest,
45+
GetSandboxRequest, GetServiceRequest, GpuResourceRequirements, ImportProviderProfilesRequest,
46+
LintProviderProfilesRequest, ListProviderProfilesRequest, ListProvidersRequest,
47+
ListSandboxPoliciesRequest, ListSandboxProvidersRequest, ListSandboxesRequest,
48+
ListServicesRequest, PolicySource, PolicyStatus, Provider, ProviderCredentialRefreshStatus,
49+
ProviderCredentialRefreshStrategy, ProviderProfile, ProviderProfileDiagnostic,
50+
ProviderProfileImportItem, RejectDraftChunkRequest, ResourceRequirements,
51+
RevokeSshSessionRequest, RotateProviderCredentialRequest, Sandbox, SandboxPhase, SandboxPolicy,
52+
SandboxSpec, SandboxTemplate, ServiceEndpointResponse, SetInferenceRouteRequest, SettingScope,
53+
TcpForwardFrame, TcpForwardInit, TcpRelayTarget, UpdateConfigRequest,
54+
UpdateProviderProfilesRequest, UpdateProviderRequest, WatchSandboxRequest, exec_sandbox_event,
55+
setting_value, tcp_forward_init,
5556
};
5657
use openshell_core::settings;
5758
use openshell_core::{ObjectId, ObjectName, ObjectWorkspace};
@@ -115,6 +116,65 @@ impl ProgressOutput {
115116
}
116117
}
117118

119+
#[derive(Debug, Clone)]
120+
struct CurrentUserView {
121+
subject: String,
122+
display_name: Option<String>,
123+
roles: Vec<String>,
124+
scopes: Vec<String>,
125+
identity_provider: String,
126+
}
127+
128+
/// Show the identity validated by the selected gateway.
129+
pub async fn whoami(server: &str, tls: &TlsOptions, output: &str) -> Result<()> {
130+
let mut client = grpc_client(server, tls).await?;
131+
let identity = client
132+
.get_current_user(GetCurrentUserRequest {})
133+
.await
134+
.map_err(|err| match err.code() {
135+
Code::Unimplemented => miette!("whoami is not supported by this gateway version"),
136+
Code::Unauthenticated => miette!("whoami requires authentication: {err}"),
137+
_ => miette!("get_current_user failed: {err}"),
138+
})?
139+
.into_inner();
140+
141+
let view = CurrentUserView {
142+
subject: identity.subject,
143+
display_name: (!identity.display_name.is_empty()).then_some(identity.display_name),
144+
roles: identity.roles,
145+
scopes: identity.scopes,
146+
identity_provider: identity.identity_provider,
147+
};
148+
print_current_user(&view, output)
149+
}
150+
151+
fn print_current_user(view: &CurrentUserView, output: &str) -> Result<()> {
152+
if crate::output::print_output_single(output, view, current_user_to_json)? {
153+
return Ok(());
154+
}
155+
156+
println!("{}", "Current User".cyan().bold());
157+
println!();
158+
println!(" {} {}", "Subject:".dimmed(), view.subject);
159+
if let Some(display_name) = &view.display_name {
160+
println!(" {} {}", "Name:".dimmed(), display_name);
161+
}
162+
println!(" {} {}", "Provider:".dimmed(), view.identity_provider);
163+
println!(" {} {}", "Roles:".dimmed(), view.roles.join(", "));
164+
println!(" {} {}", "Scopes:".dimmed(), view.scopes.join(", "));
165+
Ok(())
166+
}
167+
168+
fn current_user_to_json(view: &CurrentUserView) -> serde_json::Value {
169+
serde_json::json!({
170+
"subject": &view.subject,
171+
"display_name": &view.display_name,
172+
"roles": &view.roles,
173+
"scopes": &view.scopes,
174+
"identity_provider": &view.identity_provider,
175+
})
176+
}
177+
118178
/// Validate system prerequisites for running a gateway.
119179
///
120180
/// Checks Docker connectivity and reports the result. Returns exit code 0
@@ -420,11 +480,17 @@ pub async fn sandbox_create(
420480
}
421481
None => None,
422482
};
423-
let providers_v2_enabled = gateway_providers_v2_enabled(&mut client).await?;
483+
let inferred_provider = inferred_provider_type(command);
484+
let providers_v2_enabled =
485+
if inferred_provider.is_some() && auto_providers_override != Some(false) {
486+
gateway_providers_v2_enabled(&mut client).await?
487+
} else {
488+
false
489+
};
424490
let inferred_types: Vec<String> = if providers_v2_enabled {
425491
Vec::new()
426492
} else {
427-
inferred_provider_type(command).into_iter().collect()
493+
inferred_provider.into_iter().collect()
428494
};
429495
let configured_providers = ensure_required_providers(
430496
&mut client,

‎crates/openshell-cli/tests/ensure_providers_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,13 @@ impl TestOpenShell {
7979

8080
#[tonic::async_trait]
8181
impl OpenShell for TestOpenShell {
82+
async fn get_current_user(
83+
&self,
84+
_request: tonic::Request<openshell_core::proto::GetCurrentUserRequest>,
85+
) -> Result<Response<openshell_core::proto::GetCurrentUserResponse>, Status> {
86+
Err(Status::unimplemented("not used by this test server"))
87+
}
88+
8289
async fn health(
8390
&self,
8491
_request: tonic::Request<HealthRequest>,

‎crates/openshell-cli/tests/mtls_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@ struct TestOpenShell;
3333

3434
#[tonic::async_trait]
3535
impl OpenShell for TestOpenShell {
36+
async fn get_current_user(
37+
&self,
38+
_request: tonic::Request<openshell_core::proto::GetCurrentUserRequest>,
39+
) -> Result<Response<openshell_core::proto::GetCurrentUserResponse>, Status> {
40+
Err(Status::unimplemented("not used by this test server"))
41+
}
42+
3643
async fn health(
3744
&self,
3845
_request: tonic::Request<HealthRequest>,

0 commit comments

Comments
 (0)