Skip to content

Per-user sandbox ownership on a shared OpenShell gateway (owner-label approach) #1976

Closed

Description

@pdettori

Summary

Add per-user multi-tenancy to the OpenShell gateway so that OIDC-authenticated
users can create / list / connect / remove only their own sandboxes on a
single shared gateway — without a namespace (or gateway) per user.

The gateway already authenticates users via OIDC and threads an Identity into
every request. It does not yet record sandbox ownership or filter by it. This
issue adds an openshell.ai/owner label, stamped server-side from the verified
caller identity, and enforces it on the sandbox CRUD/connect paths — reusing the
label-selector filtering the store already supports.

Relates to: epic #1363. Background research: docs/research/openshell-mvp.md
(§5.2 "no per-user sandbox ownership", §10 "shared-gateway multi-tenancy" deferred),
docs/research/openshell-fork-analysis.md.

Motivation

The MVP (docs/research/openshell-mvp.md) achieves isolation with
namespace-per-team gateways, and within a team all openshell-user members
share every sandbox (§5.2). Pushing that model to per-user isolation would mean a
namespace (or a whole gateway stack) per user, which does not scale:

  • Namespace churn, RBAC/quota fragmentation, controller load, slow create.
  • Gateway-per-user multiplies pods, certs, and DBs.

K8s namespaces are a coarse blast-radius/quota boundary, not a per-user partition.
The scalable model is one shared gateway, ownership enforced at the application
layer
, with the namespace kept as a team/quota boundary.

What already exists (verified — grep to confirm exact lines)

Repo: kagenti/openshell (gateway, Rust), branch base = current mvp-v2 lineage (v0.0.49+).

Piece Location Notes
Identity { subject, display_name, roles, scopes, provider } crates/openshell-server/src/auth/identity.rs subject = OIDC sub; display_name = preferred_username
OIDC JWT validation + claim extraction crates/openshell-server/src/auth/oidc.rs issuer/audience validation, configurable roles/scopes claim paths
Principal::User(UserPrincipal { identity }) crates/openshell-server/src/auth/principal.rs also Sandbox, Anonymous variants
Principal inserted into request extensions crates/openshell-server/src/multiplex.rs (~:470) req.extensions_mut().insert(principal) — available to all handlers
Authz = role/scope only crates/openshell-server/src/auth/authz.rs (~:59 check) method-level gate; no resource-level check
Sandbox handlers crates/openshell-server/src/grpc/sandbox.rs handle_create_sandbox (:117), handle_get_sandbox (:226), handle_list_sandboxes (:247), handle_delete_sandbox_inner (:487) — none read Principal
Label-selector validation crates/openshell-server/src/grpc/validation.rs (~:464 validate_label_selector) equality-only, comma-separated k=v (AND), no set ops
List-with-selector (store) persistence/mod.rs (:461 list_messages_with_selector), persistence/postgres.rs (:398, JSONB @>, server-side), persistence/sqlite.rs (~:423, in-memory filter) scoped by object_type
Object metadata = labels, no owner proto/datamodel.proto ObjectMeta { id, name, created_at_ms, labels, resource_version }; migrations migrations/sqlite/001,004,005 no owner/subject/created_by column

The gap: CreateSandbox stamps no owner; ListSandboxes returns all
sandboxes; GetSandbox/DeleteSandbox/connect/exec have no ownership check.

Proposed approach

Reserved, server-set label openshell.ai/owner = <identity.subject>.

  1. Create — read Principal::User from request extensions; set
    metadata.labels["openshell.ai/owner"] = identity.subject. Strip any
    client-supplied openshell.ai/owner (and any openshell.ai/-reserved keys)
    from the incoming request so ownership cannot be spoofed.
  2. List — AND the caller's openshell.ai/owner=<subject> into the label
    selector before hitting the store. Admins bypass (see admin rule below).
  3. Get / connect / exec / SSH-bridge / policy-get — after fetching by
    name/ID, return PermissionDenied if labels["openshell.ai/owner"] != caller
    subject. (Find all handlers that resolve a sandbox by name/ID — not just the
    four above; e.g. ExecSandbox and the SSH bridge path.)
  4. Delete / update — same ownership check before mutating.
  5. Admin bypass — callers with role openshell-admin (already in
    Identity.roles, see authz.rs) skip the owner filter/check and operate on
    all sandboxes.

No proto change and no DB migration are required for the MVP of this feature —
ownership rides in the existing labels map and the existing selector path.

Why labels (not a new column) for v1

  • Reuses validate_label_selector, the Postgres JSONB filter, and the SQLite
    filter that already exist — minimal surface area.
  • Correctness holds on both stores immediately.
  • A dedicated indexed owner column (proto field + migration) is the tidy
    long-term option and is listed under Scaling below, not blocking v1.

Key decisions / sharp edges (must be handled in the PRs)

  • Owner is server-set from the verified Principal, never client input.
    Strip reserved keys on CreateSandbox. This is the security crux — call it out
    in the PR and cover it with a test.
  • Label-value charset. Gateway validates label values (validate_label_value)
    and K8s pod labels are stricter (alnum/-/_/., <=63). Keycloak's sub is a
    UUID and satisfies this. If a deployment's IdP issues email-style subjects
    (alice@corp), it will fail validation — document that the Kagenti Keycloak
    realm must use UUID sub (default), or hash the subject into a valid value.
    Put the sanitization in one helper so a future column-based swap is localized.
  • Sandbox name is globally unique per object type in the store — two users
    cannot both create a sandbox named dev. Decide one of: (a) server-prefix the
    stored name with an owner token, (b) require unique names, or (c) make
    name-uniqueness owner-scoped. Document the choice; (a) or (c) is preferred for
    UX. This needs a deliberate decision — flag it in the PR.
  • Defense-in-depth, not a substitute. Owner filtering is a control-plane
    visibility/authz control. Pod-level isolation (separate SA, NetworkPolicy,
    SPIFFE, supervisor Landlock/seccomp/netns) remains the data-plane boundary.

Implementation tasks (by repo)

A. kagenti/openshell (gateway, Rust) — core PR

  • Add a constant for the reserved label key openshell.ai/owner and a
    subject -> label-value sanitizer helper.
  • CreateSandbox: extract Principal::User; reject Anonymous; strip
    reserved openshell.ai/ keys from request.labels; stamp owner label.
  • ListSandboxes: inject owner equality into the effective selector;
    admin-role bypass.
  • GetSandbox, DeleteSandbox, and every other handler resolving a sandbox
    by name/ID (ExecSandbox, SSH bridge, policy get): ownership check + admin
    bypass. Audit grpc/sandbox.rs and grpc/ for sandbox lookups.
  • Shared helper "may this principal access this sandbox" reused across handlers.
  • Unit tests: owner stamped on create; client-supplied owner stripped; list
    filtered to caller; get/delete cross-user -> PermissionDenied; admin sees
    all; anonymous rejected.
  • Keep behavior backward-compatible when OIDC is disabled
    (OPENSHELL_OIDC_ENABLED=false / LocalDev/mTLS principals): define behavior
    explicitly (e.g. owner = principal subject for mTLS CN; skip when Anonymous
    auth is the configured mode). Document it.

B. kagenti/openshell-driver-openshift (compute driver, Go) — small PR

  • Propagate openshell.ai/owner onto the created sandbox pod labels
    (alongside the existing openshell.ai/tenant / kagenti.io/team labels)
    for data-plane traceability and future NetworkPolicy/SPIFFE scoping. The
    gateway passes labels through the ComputeDriver gRPC contract — confirm the
    owner label is carried.

C. kagenti/kagenti — wiring, tests, docs

  • e2e: per-user isolation tests (extend kagenti/tests/e2e/). Alice and Bob
    authenticate to the same gateway; Alice creates a sandbox; assert Bob's
    list does not show it and Bob's get/delete/connect on it ->
    permission denied; assert admin sees both. Mirrors MVP §9.2 criteria add banner #6/fix typo in readme #7
    but at the user level on a shared gateway.
  • Helm charts/openshell/: support a shared-gateway deployment mode (one
    gateway serving multiple users in a namespace) in addition to the existing
    per-tenant mode. Gate behind a value, default off.
  • Docs: add docs/research/openshell-per-user-tenancy.md (or fold into the
    MVP doc §10) describing the model and the namespace-as-coarse-boundary
    stance.

D. Scaling follow-ups (separate issues, not blocking v1)

  • Shared Postgres store instead of SQLite-per-gateway (enables server-side
    owner filtering at scale and gateway HA, which the MVP defers). Add a
    JSONB index on (object_type, (labels->>'openshell.ai/owner')).
  • Optional: promote owner from a label to a dedicated indexed owner column
    (ObjectMeta proto field + migration) once the label approach is proven.
  • Provider/credential ownership (out of scope here — this issue covers
    sandboxes only).

Acceptance criteria

  • On a single shared gateway with OIDC enabled and two users (alice, bob):
    • alice create -> sandbox carries openshell.ai/owner=<alice-sub>.
    • bob list does not include alice's sandbox; alice list does.
    • bob get/delete/connect/exec on alice's sandbox -> PermissionDenied.
    • a client attempting to set openshell.ai/owner on create has it overwritten
      by the server value.
    • openshell-admin lists/operates across all users' sandboxes.
  • Behavior with OIDC disabled is explicitly defined and tested.
  • e2e suite (task C) green on Kind.

Out of scope

  • Per-user provider/credential ownership.
  • SPIFFE/SPIRE sandbox identity.
  • Postgres migration and gateway HA (tracked as follow-ups in D).
  • Any upstream NVIDIA/OpenShell contribution (kagenti fork only for now).

References

  • docs/research/openshell-mvp.md — §5.2 (no per-user ownership), §10 (deferred)
  • docs/research/openshell-fork-analysis.md — fork branches, image tags, store
  • Gateway code: kagenti/openshell crates/openshell-server/src/{auth,grpc,persistence}/

Activity

  1. pdettori commented on Jun 16, 2026

    @pdettori
    MemberAuthor

    Task A: Implementation Plan — kagenti/openshell per-user ownership

    Code audit findings

    I've audited the gateway source (crates/openshell-server/src/grpc/sandbox.rs, service.rs, policy.rs) and confirmed the issue's mapping. Here's the complete list of handlers that resolve a sandbox by name/ID — all need ownership enforcement:

    Handler Sandbox resolution Request type
    handle_create_sandbox Creates new Request<CreateSandboxRequest>
    handle_get_sandbox by name Request<GetSandboxRequest>
    handle_list_sandboxes label selector Request<ListSandboxesRequest>
    handle_delete_sandbox by name Request<DeleteSandboxRequest>
    handle_watch_sandbox by ID Request<WatchSandboxRequest>
    handle_exec_sandbox by ID Request<ExecSandboxRequest>
    handle_exec_sandbox_interactive by ID (streaming) Request<Streaming<ExecSandboxInput>>
    handle_forward_tcp by ID (streaming) Request<Streaming<TcpForwardFrame>>
    handle_create_ssh_session by ID Request<CreateSshSessionRequest>
    handle_expose_service by name (in service.rs) Request<ExposeServiceRequest>
    handle_attach_sandbox_provider by name Request<AttachSandboxProviderRequest>
    handle_detach_sandbox_provider by name Request<DetachSandboxProviderRequest>

    Additional paths via policy.rs: handle_get_sandbox_config, handle_get_sandbox_policy_status, handle_get_sandbox_logs, handle_get_sandbox_provider_environment — these already extract Principal from extensions for sandbox-caller validation.

    Current state

    • Principal is inserted into req.extensions_mut() at multiplex.rs:470 — available to all handlers
    • Handlers currently call request.into_inner() immediately, discarding extensions (except policy.rs)
    • AuthzPolicy.check() validates roles/scopes but has no resource-level ownership check
    • Labels exist in ObjectMeta and are validated/stored already (including label-selector filtering in the store)

    Proposed implementation structure

    crates/openshell-server/src/
    ├── auth/
    │   ├── ownership.rs  (NEW — constants, sanitizer, helper)
    │   └── mod.rs        (re-export)
    └── grpc/
        └── sandbox.rs    (modify handlers)
    

    auth/ownership.rs — single module containing:

    1. const OWNER_LABEL: &str = "openshell.ai/owner" + reserved prefix "openshell.ai/"
    2. fn sanitize_subject(subject: &str) -> Result<String, Status> — UUID passthrough, hash fallback for non-conforming subjects
    3. fn stamp_owner(labels: &mut HashMap<String, String>, principal: &Principal) -> Result<(), Status> — strips reserved keys, sets owner
    4. fn check_owner(sandbox: &Sandbox, principal: &Principal, admin_role: &str) -> Result<(), Status> — returns PermissionDenied if not owner and not admin
    5. fn owner_selector(principal: &Principal, existing_selector: &str) -> Result<String, Status> — ANDs owner filter for list

    Pattern for handler changes

    // Before (current):
    pub(super) async fn handle_get_sandbox(
        state: &Arc<ServerState>,
        request: Request<GetSandboxRequest>,
    ) -> Result<Response<SandboxResponse>, Status> {
        let name = request.into_inner().name;
        ...
    }
    
    // After:
    pub(super) async fn handle_get_sandbox(
        state: &Arc<ServerState>,
        request: Request<GetSandboxRequest>,
    ) -> Result<Response<SandboxResponse>, Status> {
        let principal = request.extensions().get::<Principal>().cloned();
        let name = request.into_inner().name;
        ...
        let sandbox = ...;
        ownership::check_owner(&sandbox, principal.as_ref(), &state.authz_policy.admin_role)?;
        Ok(Response::new(SandboxResponse { sandbox: Some(sandbox) }))
    }

    Streaming handlers (exec_interactive, forward_tcp)

    These call request.into_inner() to get the stream, discarding extensions. The fix: extract Principal from extensions before consuming the request:

    let principal = request.extensions().get::<Principal>().cloned();
    let mut input_stream = request.into_inner();

    Questions / decisions needed

    1. Name uniqueness scope (issue calls this out): Do we go with (a) server-prefix stored name with owner token, (b) globally unique names (simplest, current behavior preserved), or (c) owner-scoped uniqueness? I'd lean toward (b) for v1 — simplest, no store changes, document the constraint. Thoughts?

    2. OIDC-disabled behavior: When OPENSHELL_OIDC_ENABLED=false, the Principal in extensions is either Anonymous or LocalDev. Proposal: skip ownership entirely when principal is Anonymous (backward compat with existing single-user local dev). For LocalDev/Mtls principals, stamp identity.subject as owner normally.

    3. authz_policy.admin_role: The AuthzPolicy struct is available on ServerState (via config). I'll use state.authz_policy.admin_role for the admin-bypass check. Confirm this is the right place (vs. a separate ownership config)?

    Commit plan (incremental, each green)

    1. Add auth/ownership.rs with constants, sanitizer, stamp_owner, check_owner, owner_selector + unit tests
    2. Wire stamp_owner into handle_create_sandbox (strips reserved keys, stamps owner) + tests
    3. Wire owner_selector into handle_list_sandboxes + tests
    4. Wire check_owner into get/delete/watch/exec/ssh/service handlers + tests
    5. Handle streaming handlers (exec_interactive, forward_tcp) + tests
    6. Handle OIDC-disabled / Anonymous / LocalDev principal cases + tests

    Each commit adds at least one new passing test. No reverts, no amends.

  2. pdettori commented on Jun 16, 2026

    @pdettori
    MemberAuthor

    Per-User Resource Ownership — Extended Requirements (Providers, Inference, Policy)

    Findings from live testing

    Sandbox ownership (Task A/B/C) is working correctly on Kind:

    • alice/bob can only see their own sandboxes ✅
    • Cross-user get/delete returns PermissionDenied ✅
    • Admin bypass works ✅

    However, providers and inference routes are currently shared/admin-scoped resources with no per-user isolation. This creates a gap for credentials that are inherently per-user (e.g., personal GitHub PATs, individual API keys).

    Current scoping model (as-is)

    Resource Create requires Scoped to Owner-filtered?
    Sandbox user role Per-user (openshell.ai/owner) ✅ Yes
    Provider admin role Gateway-wide (shared) ❌ No
    Inference route admin role Gateway-wide (shared) ❌ No
    Policy N/A (part of sandbox spec) Per-sandbox (inherits sandbox ownership) ✅ Yes (via sandbox)
    • Provider credentials are captured at provider creation time from the admin's local env vars and stored in the gateway's persistent store. All sandboxes sharing that provider use the same credential.
    • Inference routes (openshell inference set) are cluster-wide routing rules (provider + model → endpoint). Admin-only write.
    • Policies are embedded in the sandbox spec at create time — already per-user since sandboxes are per-user.

    Requirements for per-user providers (Option A)

    Goal: Allow regular users to create their own providers with personal credentials, invisible to other users on the same gateway.

    Design

    1. Relax create_provider auth from admin → user (or add a new create_user_provider RPC with user role).
    2. Apply openshell.ai/owner to providers — same pattern as sandboxes:
      • Create stamps owner from verified identity
      • List filtered by owner
      • Get/Delete returns PermissionDenied cross-user
      • Admin bypasses ownership filter
    3. Sandbox ↔ Provider binding respects ownership — a user can only bind their sandbox to providers they own OR admin-created shared providers (no owner label = shared).
    4. Provider name uniqueness scoped to owner — alice and bob can both have a provider named gh without conflict.

    Shared vs. user-owned providers

    Provider type Owner label Visible to Created by
    Shared (team) none All users Admin
    User-owned openshell.ai/owner=<sub> Owner + admin User

    A sandbox can reference:

    • User-owned providers belonging to the same user
    • Shared providers (no owner)
    • ❌ NOT another user's providers

    Inference routes: no change needed

    Inference routes are routing configuration (provider → model → endpoint), not credentials. They should remain admin-only and gateway-wide:

    • Admin sets openshell inference set --provider claude --model claude-sonnet-4-6
    • This tells the gateway how to route inference.local — applicable to all sandboxes regardless of owner
    • The credential resolution still happens per-provider (shared or user-owned)

    If a user-owned provider is bound to a sandbox, the inference route uses that provider's credentials (the user's personal key), even though the route itself is shared config.

    Policy: no change needed

    Policies are already per-sandbox (embedded in sandbox spec). Since sandboxes are per-user, policies are inherently per-user. No additional scoping needed.

    Summary of work

    Item Change needed Scope
    Provider ownership openshell.ai/owner on providers, relax create auth Gateway Rust code (new issue)
    Provider list/get/delete filtering Same pattern as sandbox ownership Gateway Rust code
    Sandbox-provider binding validation Owner match or shared provider Gateway Rust code
    Provider name uniqueness Scope to (owner, name) not just name Store layer
    Inference routes No change — remains admin/shared —
    Policy No change — already per-sandbox —

    Next step

    Create a dedicated follow-up issue for per-user provider ownership (this issue's acceptance criteria are met for sandbox ownership).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions