diff --git a/.agents/skills/build-from-issue/SKILL.md b/.agents/skills/build-from-issue/SKILL.md index 2e04e37f52..06d1324b02 100644 --- a/.agents/skills/build-from-issue/SKILL.md +++ b/.agents/skills/build-from-issue/SKILL.md @@ -62,7 +62,7 @@ Fetch issue + comments ├─ Triage incomplete, awaiting information, or awaiting human disposition? │ → Report the blocking state and STOP │ - ├─ state:accepted absent? + ├─ state:accepted and roadmap association both absent? │ → Human has not accepted the issue; STOP │ ├─ No plan comment and no direct planning request and agent:plan-requested absent? @@ -113,9 +113,9 @@ Stop before planning in any of these states: - `state:triage-needed`: the issue has not been assessed; use `triage-issue`. - `state:needs-info`: triage is waiting for evidence from the reporter. -- `state:validated`: triage is complete, but a human has not yet decided whether OpenShell should invest in the work. +- `state:validated` without roadmap placement: triage is complete, but a human has not yet decided whether OpenShell should invest in the work. -Next, require `state:accepted`. It records the human decision to pursue the work. If no plan exists, require either a direct user request for planning or the human-applied `agent:plan-requested` label before generating one. Record any roadmap association as sequencing context, but do not require one. Never add or remove `state:accepted`, either human request label, or the `roadmap` label. +Next, require a human acceptance signal: either `state:accepted` or placement on the roadmap. The label records acceptance without requiring scheduling; roadmap placement records acceptance and sequencing. If no plan exists, require either a direct user request for planning or the human-applied `agent:plan-requested` label before generating one. Never add or remove `state:accepted`, either human request label, or the `roadmap` label. ## Step 2: Fetch and Classify Comments @@ -160,7 +160,7 @@ Task tool with subagent_type="principal-engineer-reviewer" In the prompt, instruct the reviewer to: -1. Read the issue description thoroughly and identify what needs to change in the codebase. +1. Read the issue's user story and identify what needs to change in the codebase. Treat reporter diagnostics or solution ideas as optional context, not as authoritative or current analysis. 2. Map the requirements to existing code — read the relevant source files. 3. Determine the **issue type** — one of: `feat` (new feature), `fix` (bug fix), `refactor`, `chore`, `perf`, `docs`. 4. Propose the minimal set of changes that satisfies the requirements. @@ -174,6 +174,8 @@ In the prompt, instruct the reviewer to: 9. Assess **gateway config documentation impact** — if the change adds, removes, renames, or changes defaults for gateway TOML keys or driver-specific config options, the plan must include an update to `docs/reference/gateway-config.mdx`. If the change is surfaced through Helm or a compute-driver overview, also include `docs/reference/sandbox-compute-drivers.mdx` or the relevant deployment docs. 10. Assess **LSM compatibility** — if the change touches process identity, `/proc` filesystem access, binary execution, or inter-process visibility, flag whether it will behave differently on hosts running SELinux (enforcing) or AppArmor. In particular, tests that fork+exec into system binaries will fail on SELinux-enforcing hosts due to cross-label `/proc//exe` access restrictions. +Perform this investigation against the current branch and current product behavior. If the issue contains earlier diagnostics, verify them rather than relying on them. + ### A2: Post the Plan Comment Post the plan as a comment on the issue. This is the **canonical plan comment** that will be edited in place as the plan evolves. diff --git a/.agents/skills/create-github-issue/SKILL.md b/.agents/skills/create-github-issue/SKILL.md index 8352603e76..609d55ad15 100644 --- a/.agents/skills/create-github-issue/SKILL.md +++ b/.agents/skills/create-github-issue/SKILL.md @@ -17,27 +17,27 @@ This project uses YAML form issue templates. When creating issues, match the tem ### Bug Reports -Do not add a type label automatically. The body must include an **Agent Diagnostic** section — this is required by the template and enforced by project convention. The diagnostic must identify the OpenShell version tested, whether the latest release or known fixes were checked, and whether possible duplicate issues were searched. If the agent cannot verify the latest release or search existing issues, say so explicitly instead of guessing. Apply area or topic labels only when they are clearly known. +Do not add a type label automatically. The body must include a **User Story**, **Problem Statement**, **Impact / Why This Matters**, and **Acceptance Criteria**, followed by bug-specific reproduction steps and environment details. Logs are optional and must be concise and redacted. Apply area or topic labels only when they are clearly known. ```bash gh issue create \ --title "bug: " \ --body "$(cat <<'EOF' -## Agent Diagnostic +## User Story -- Skills loaded: -- OpenShell version tested: -- Latest release checked: -- Known fixes reviewed: -- Possible duplicates reviewed: -- Findings: -- Remaining reason for filing: +As a , I want , so that . -## Description +## Problem Statement + + + +## Impact / Why This Matters -**Actual behavior:** + -**Expected behavior:** +## Acceptance Criteria + +- [ ] ## Reproduction Steps @@ -46,16 +46,14 @@ gh issue create \ ## Environment -- OS: -- Docker: - OpenShell: -- Latest release checked: -- Possible duplicates checked: +- OS: +- Runtime, deployment, or integration: ## Logs ``` - + ``` EOF )" @@ -63,28 +61,39 @@ EOF ### Feature Requests -Do not add a type label automatically. The body must include a **Proposed Design** — not a "please build this" request. Apply area or topic labels only when they are clearly known. +Do not add a type label automatically. The body must include a **User Story**, **Problem Statement**, **Impact / Why This Matters**, **Proposed Design**, **Acceptance Criteria**, and **Alternatives Considered**. The proposed design should define the user-facing workflow and externally observable behavior without prescribing internal implementation. Agent investigation is optional. Apply area or topic labels only when they are clearly known. ```bash gh issue create \ --title "feat: " \ --body "$(cat <<'EOF' +## User Story + +As a , I want , so that . + ## Problem Statement - + + +## Impact / Why This Matters + + ## Proposed Design - + + +## Acceptance Criteria + +- [ ] ## Alternatives Considered - + ## Agent Investigation - + EOF )" ``` @@ -114,7 +123,7 @@ EOF GitHub built-in issue types (`Bug`, `Feature`, `Task`) should come from the matching issue template when possible, or be set manually afterward. Do not try to emulate them through labels. -Creating an issue does not accept it for roadmap work or queue agent work. Agents never apply the `roadmap` label, add issues to the roadmap project, or apply `agent:plan-requested` or `agent:implementation-requested`. Community issues proceed through `triage-issue`; a human decides whether technically validated work should be accepted and places it on the roadmap. The request labels queue work for unattended agents; a user may instead direct an agent to a specific issue. +Creating an issue does not accept it or queue agent work. Agents never apply `state:accepted`, the `roadmap` label, add issues to the roadmap project, or apply `agent:plan-requested` or `agent:implementation-requested`. Community issues proceed through `triage-issue`; a human accepts technically validated work with `state:accepted` or roadmap placement. The request labels queue work for unattended agents; a user may instead direct an agent to a specific issue. ## Useful Options diff --git a/.agents/skills/create-spike/SKILL.md b/.agents/skills/create-spike/SKILL.md index 4f30c3829a..63bcffb72b 100644 --- a/.agents/skills/create-spike/SKILL.md +++ b/.agents/skills/create-spike/SKILL.md @@ -211,7 +211,7 @@ gh issue create \ - --- -*Created by spike investigation. `state:validated` means the issue is ready for human disposition; `state:needs-info` means specific evidence is still required. A human applies `state:accepted` if OpenShell should pursue the work and places it on the roadmap separately. To queue unattended agent planning, a human applies `agent:plan-requested`; a direct request to an agent does not require that label.* +*Created by spike investigation. `state:validated` means the issue is ready for human disposition; `state:needs-info` means specific evidence is still required. A human applies `state:accepted` or places the issue on the roadmap if OpenShell should pursue the work. To queue unattended agent planning, a human applies `agent:plan-requested`; a direct request to an agent does not require that label.* EOF )" ``` @@ -235,7 +235,7 @@ After creating the issue, report: For `state:validated`: -> Review the issue and decide whether OpenShell should pursue it. If yes, replace `state:validated` with `state:accepted` and separately associate it with a roadmap item. The work may remain human-owned. Apply `agent:plan-requested` to queue planning for an unattended agent, or directly ask an agent to use `build-from-issue`. If no, close it as not planned and record the rationale. +> Review the issue and decide whether OpenShell should pursue it. If yes, apply `state:accepted`, associate it with a roadmap item, or do both. Either action records acceptance; roadmap placement additionally records sequencing. The work may remain human-owned. Apply `agent:plan-requested` to queue planning for an unattended agent, or directly ask an agent to use `build-from-issue`. If no, close it as not planned and record the rationale. For `state:needs-info`: diff --git a/.agents/skills/debug-openshell-cluster/SKILL.md b/.agents/skills/debug-openshell-cluster/SKILL.md index fbd19fa3c0..c407823aff 100644 --- a/.agents/skills/debug-openshell-cluster/SKILL.md +++ b/.agents/skills/debug-openshell-cluster/SKILL.md @@ -178,6 +178,13 @@ Common findings: - A workdir rejected as a special filesystem or OpenShell control-path collision cannot be made valid with permissions. Move the image workdir away from kernel-backed mounts and the concrete supervisor, TLS, token, runtime, and socket paths named in the error. - Docker driver cannot initialize because it cannot find `openshell-sandbox`: verify `OPENSHELL_DOCKER_SUPERVISOR_BIN`, the sibling binary next to `openshell-gateway`, or the configured supervisor image contains `/openshell-sandbox`. - Sandbox never registers: check gateway logs and supervisor callback endpoint. +- On macOS, repeated `Policy fetch failed after 5 attempts` messages with a + Homebrew gateway bound to `[::1]:17670` indicate that the Docker + `host-gateway` IPv4 route has no matching callback listener. Current releases + leave `bind_address` unset in the Homebrew config, use the built-in + `127.0.0.1:17670` primary listener, and reuse it for authenticated sandbox + callbacks. On an older release, set `bind_address = "127.0.0.1:17670"` or + upgrade. - Supervisor image exits before printing `openshell-sandbox --version`: the image should be the scratch supervisor image from `deploy/docker/Dockerfile.supervisor` and must contain a static executable at `/openshell-sandbox`. - `mise run e2e:docker:gpu` fails with `docker info --format json did not report any discovered NVIDIA CDI GPU devices`: Docker may report `CDISpecDirs` while still having no generated NVIDIA CDI specs. Verify `.DiscoveredDevices` contains entries such as `nvidia.com/gpu=all`, verify `/etc/cdi` or `/var/run/cdi` contains a generated NVIDIA spec, and check that `nvidia-cdi-refresh.service` and `nvidia-cdi-refresh.path` from NVIDIA Container Toolkit are enabled and healthy. The service is a one-shot unit, so `inactive (dead)` can be normal after a successful run; use `systemctl status` and `journalctl` to distinguish success from a skipped or failed refresh. NVIDIA recommends enabling the path and service units, and restarting `nvidia-cdi-refresh.service` to regenerate missing or stale CDI specs. If specs are generated but Docker still reports no discovered devices, restart Docker or reload the daemon and re-check `docker info`. @@ -207,14 +214,9 @@ Common findings: error: inspect `podman info --debug`, the configured Podman network, and the host's IPv4 default route. Rootless pasta uses the private source address selected by that route; rootful Podman uses the bridge gateway address. -- Callback discovery reports that the requested address equals the primary - listener: configure a distinct primary address. For Podman Machine, bind the - primary listener to IPv6 loopback, for example - `bind_address = "[::1]:17670"`, and register the CLI endpoint as - `https://localhost:17670`. The generated certificate includes `localhost`, - while a raw `https://[::1]:17670` endpoint can fail TLS setup with - `invalid dns name`. This leaves `127.0.0.1:17670` available for the - callback-only listener. +- Current gateways reuse the primary listener when it covers Podman's callback + address. If the primary does not cover that address, inspect the gateway + startup logs for the additional callback-only listener and its provenance. - Rootless slirp4netns, another named helper, or missing helper metadata requires an explicitly remote `grpc_endpoint`. An explicit `host_gateway_ip` cannot bypass slirp4netns host-loopback isolation. Do not work around @@ -471,6 +473,56 @@ kubectl -n logs -c openshell-supervisor-networ kubectl -n logs -c agent --tail=200 ``` +#### Corporate upstream proxy + +When the deployment routes sandbox egress through a corporate HTTP forward +proxy, the operator-owned settings render under `[openshell.drivers.kubernetes]` +from the Helm `upstreamProxy` values. Absent proxy configuration preserves +direct-dial egress; any present-but-invalid value fails closed at gateway +startup (`validate_upstream_proxy_config`) rather than silently reverting to a +direct connection. Confirm the rendered configuration first: + +```bash +kubectl -n openshell get configmap openshell-config -o jsonpath='{.data.gateway\.toml}' | grep -E 'https_proxy|no_proxy|proxy_auth_secret_(name|key)|proxy_auth_allow_insecure|proxy_connect_by_hostname' +helm -n openshell get values openshell | grep -A8 upstreamProxy +``` + +Only `http://host:port` forward proxies are supported; `https://` proxy URLs and +plain-HTTP egress are out of scope and rejected. Proxy credentials require +`topology = "sidecar"` — combined topology shares the credential mount with the +workload, so the gateway rejects credentials there. The credential Secret named +by `proxy_auth_secret_name` must exist in the sandbox namespace with the key +named by `proxy_auth_secret_key`, and Kubernetes will not create keys longer +than 253 bytes or named `.`/`..`. + +The proxy arguments and credential mount are injected only into the container +that runs network supervision (the `agent` container in combined topology, the +`openshell-supervisor-network` sidecar in sidecar topology). The one-shot +`openshell-network-init` container and the process `agent` container in sidecar +topology must never receive them. The credential is projected read-only as the +`openshell-upstream-proxy-auth` volume at `/run/openshell/upstream-proxy-auth` +and passed as `--upstream-proxy-auth-file`; it must never appear in env, +annotations, or command arguments. + +```bash +kubectl -n get secret -o jsonpath='{.data}' >/dev/null && echo "secret present" +kubectl -n get pod -o jsonpath='{range .spec.containers[*]}{.name}{" "}{.command}{"\n"}{end}' | grep -- '--upstream-' +kubectl -n get pod -o jsonpath='{range .spec.containers[*]}{.name}{": "}{range .volumeMounts[*]}{.name}{" "}{end}{"\n"}{end}' | grep upstream-proxy-auth +kubectl -n get events --sort-by=.lastTimestamp | grep -Ei 'secret|MountVolume' | tail -n 20 +``` + +A missing Secret or wrong key leaves the pod stuck with a +`MountVolume.SetUp failed` / `secret ... not found` event. If the pod starts but +egress still fails, the corporate proxy itself is the next suspect: policy- +approved TLS CONNECT requests that time out after policy evaluation usually mean +the proxy URL is unreachable from the sandbox namespace, or a cluster-internal +destination that should be direct is missing from `no_proxy`. Inspect the +network supervisor logs for CONNECT and upstream-proxy decisions: + +```bash +kubectl -n logs -c openshell-supervisor-network --tail=200 | grep -Ei 'upstream|connect|proxy' +``` + ### Step 7: Check VM-Backed Gateways Use the VM driver logs and host diagnostics available in the user's environment. Verify: @@ -494,7 +546,7 @@ openshell logs | `openshell status` fails | Gateway endpoint unreachable or auth mismatch | `openshell gateway info`, gateway logs | | Gateway starts but sandbox create fails | Compute driver cannot reach runtime | Docker/Podman/Kubernetes/VM driver logs | | Gateway exits while resolving compute-driver listener requirements | Callback alias topology is unsupported, the Podman network cannot be inspected, or the selected address is not private/authorized | Gateway startup error, `podman info --debug`, Podman network inspection, host IPv4 default route | -| Admin, health, reflection, or HTTP request is denied on a Docker/Podman callback address | Negotiated callback listeners intentionally expose only sandbox-callable gRPC methods | Retry through the gateway's primary endpoint; inspect the listener-purpose startup log if the address was unexpected | +| Admin, health, reflection, or HTTP request is denied on an additional Docker/Podman callback-only listener | Additional callback listeners intentionally expose only sandbox-callable gRPC methods | Retry through the gateway's primary endpoint; inspect the listener-purpose startup log if the address was unexpected | | Docker or Podman sandbox never registers | Wrong callback endpoint or supervisor startup failure | Gateway logs and sandbox container logs | | Docker GPU e2e fails before GPU sandbox comparison | NVIDIA CDI specs are missing or Docker has not discovered them | `docker info --format '{{json .DiscoveredDevices}}'`, `/etc/cdi`, `/var/run/cdi`, `nvidia-cdi-refresh.service` | | Kubernetes gateway pod pending | PVC unbound, taint, selector, or insufficient resources | `kubectl -n openshell describe pod ` | diff --git a/.agents/skills/sync-agent-infra/SKILL.md b/.agents/skills/sync-agent-infra/SKILL.md index e1d5b52c12..bd01bfebde 100644 --- a/.agents/skills/sync-agent-infra/SKILL.md +++ b/.agents/skills/sync-agent-infra/SKILL.md @@ -119,8 +119,8 @@ For each file in the table above, check for the following inconsistencies: ### Issue Templates -1. **`bug_report.yml`** — Skill names in the Agent Diagnostic guidance and checklist must exist. -2. **`feature_request.yml`** — Skill names in the Agent Investigation guidance must exist. +1. **`bug_report.yml`** — Must collect a User Story, Problem Statement, Impact / Why This Matters, Acceptance Criteria, Reproduction Steps, and Environment. Logs are optional and bug-specific; reporter diagnostics must not be required. +2. **`feature_request.yml`** — Must collect a User Story, Problem Statement, Impact / Why This Matters, Proposed Design, Acceptance Criteria, and Alternatives Considered. The design describes workflow and observable behavior without prescribing internal implementation; agent investigation is optional. 3. **`config.yml`** — Skill category descriptions in contact links should be accurate. ### Issue Triage Workflow diff --git a/.agents/skills/triage-issue/SKILL.md b/.agents/skills/triage-issue/SKILL.md index 5e5d503025..ebd353d6f8 100644 --- a/.agents/skills/triage-issue/SKILL.md +++ b/.agents/skills/triage-issue/SKILL.md @@ -25,7 +25,7 @@ Triage establishes technical validity; it does not decide whether valid work bel OpenShell has no `priority:*` labels. Sequencing comes from association with an item on the OpenShell Roadmap, and that association is a maintainer decision. -`state:validated` means the factual assessment is complete and awaits human disposition. A human declines by closing the issue as not planned with a rationale, or accepts by replacing `state:validated` with `state:accepted` and placing the issue on the roadmap as documented in `CONTRIBUTING.md`. Accepted work may remain human-owned. A maintainer can queue deeper agent investigation or planning with `agent:plan-requested`, or directly ask an agent to work on a specific issue. +`state:validated` means the factual assessment is complete and awaits human disposition. A human declines by closing the issue as not planned with a rationale, or accepts by applying `state:accepted`, placing the issue on the roadmap, or doing both as documented in `CONTRIBUTING.md`. Accepted work may remain human-owned. A maintainer can queue deeper agent investigation or planning with `agent:plan-requested`, or directly ask an agent to work on a specific issue. The optional `agent:*` workflow controls unattended queue pickup: `agent:plan-requested` queues planning, and `agent:implementation-requested` queues implementation after plan review. A direct user instruction separately authorizes the phase it requests and does not require either label. @@ -98,18 +98,14 @@ Search the issue comments for the triage agent marker (`> **📋 triage-agent**` - **If the marker is found** and no subsequent human comments exist with new information or questions, report that the issue has already been triaged and stop. - **If the marker is found** but there are newer human comments with additional information, proceed to Step 3 to re-evaluate with the new context. -- **If a human already declined the issue or applied `state:accepted`**, do not undo or reinterpret that decision. +- **If a human already declined the issue, applied `state:accepted`, or placed it on the roadmap**, do not undo or reinterpret that decision. - **If the marker is not found**, proceed to Step 3. -## Step 3: Validate the Agent-First Gate +## Step 3: Check Report Completeness -Check whether the issue body contains a substantive agent diagnostic section. Treat this as evidence quality, not as a reason to skip obvious safety or routing actions. Look for: +Check for a substantive User Story, Problem Statement, Impact / Why This Matters, and Acceptance Criteria. The impact should explain the consequences of the current behavior and any insufficient workaround. For bug reports, also identify the reproduction steps and relevant environment. For feature requests, review the Proposed Design and Alternatives Considered. Reporter-supplied diagnostics and agent output are optional and must not be used as an intake gate. -- An "Agent Diagnostic" heading or section (from the bug report template) -- Evidence that the reporter used agent skills (skill names mentioned, diagnostic output pasted) -- Concrete investigation output (not just placeholder text or "N/A") - -If the diagnostic is missing, continue when the report already contains enough concrete evidence to assess safely. Otherwise classify it as `needs-information`, request the exact missing evidence, remove `state:triage-needed`, and add `state:needs-info`. +If the report contains enough context to understand and assess the need, continue. If a required section lacks material information, classify it as `needs-information`, request only the exact missing information, remove `state:triage-needed`, and add `state:needs-info`. - If a public issue may disclose a security vulnerability, do not repeat or expand sensitive details. Classify it as `security-report` and direct the operator to `SECURITY.md`. - Route usage questions and support requests to the documented support venue. @@ -121,7 +117,7 @@ Proceed to Step 4 for reports requiring technical validation. Before deeper diagnosis, determine whether the report may already be fixed in a newer release. -1. Extract the reported OpenShell version from the issue body, Agent Diagnostic, environment section, logs, and comments. If no version is provided, record that as missing context and continue. +1. Extract the reported OpenShell version from the issue body, environment section, logs, and comments. If no version is provided, record that as missing context and continue. 2. Check current release information and known fixes when available: - `gh release list --limit 10` - `gh release view ` @@ -140,15 +136,17 @@ Assess the report by investigating the codebase. Use the `principal-engineer-rev ``` Prompt the sub-agent with: - The full issue title and body -- The reporter's agent diagnostic output - Instructions to evaluate with a skeptical lens: - 1. Is this report describing a real problem or user error? - 2. Can the described behavior be reproduced from the information given? - 3. Does the reporter's agent diagnostic match what you see in the codebase? - 4. If this is a bug, what component is affected? - 5. If this is a feature request, is it technically coherent and feasible? Do not decide whether the project should accept it. - 6. Are there any open or closed issues that duplicate this? - 7. What uncertainty remains, and what exact evidence would resolve it? + 1. What persona and desired capability does the user story establish? + 2. Does the problem statement match current product behavior? + 3. Does the impact explain the consequences, current workaround, and why that workaround is insufficient? + 4. Are the acceptance criteria specific, observable, and consistent with the user story? + 5. Can the described workflow be reproduced or otherwise validated from the information given? + 6. Does the current product support the requested outcome, and what component owns the behavior? + 7. Is the report best classified as a bug, feature request, support request, or another category? + 8. If this is a feature request, is the proposed design technically coherent and feasible? Do not decide whether the project should accept it. + 9. Are there any open or closed issues that duplicate this? + 10. What uncertainty remains, and what exact evidence would resolve it? ``` Based on the sub-agent's analysis, also attempt to validate the report directly: @@ -205,14 +203,14 @@ Post a structured comment with the triage marker: > - **Evidence quality:** > > ### Human Decision Required -> Decide whether OpenShell should address this issue. If yes, replace -> `state:validated` with `state:accepted`, associate it with a roadmap -> item, and decide whether the work remains human-owned. +> Decide whether OpenShell should address this issue. If yes, apply +> `state:accepted`, associate it with a roadmap item, or do both, and decide +> whether the work remains human-owned. Either action records acceptance; +> roadmap placement additionally records sequencing. > To queue investigation or planning for an unattended agent, also apply > `agent:plan-requested`. You can instead directly ask an agent to use > `create-spike` or `build-from-issue` on this issue. If no, close it as not > planned and record the rationale. -> Roadmap association is independent sequencing metadata. ``` For other outcomes, replace the impact and decision sections with the exact information request, objective resolution, or safe routing guidance. @@ -230,7 +228,7 @@ Community issue filed | state:validated | - human decline OR state:accepted + roadmap placement + human decline OR state:accepted / roadmap placement | create-spike (if deeper investigation is approved) | diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index de5d8112ae..dd774e25c8 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,39 +1,58 @@ name: Bug Report -description: Report a bug. Your agent should investigate first — see CONTRIBUTING.md. +description: Report unexpected behavior with a clear user story and expected outcome. type: Bug body: - type: markdown attributes: value: | - ## Agent-First Troubleshooting + ## Bug Reports - OpenShell is an agent-first project. Before filing this bug, point your coding agent at the repo and have it investigate using the available skills (`debug-openshell-cluster`, `debug-inference`, `openshell-cli`, etc.). See [CONTRIBUTING.md](https://github.com/NVIDIA/OpenShell/blob/main/CONTRIBUTING.md) for the full skills table. + Describe who encountered the bug, the problem it creates, why it matters, and the observable criteria for a fix. Please check the latest OpenShell release and search existing issues for possible duplicates before filing. - Please also check the latest OpenShell release and search existing issues for possible duplicates before filing. If you cannot upgrade, retest, or search existing issues, explain why in the diagnostic. + Do not report security vulnerabilities here; follow [SECURITY.md](https://github.com/NVIDIA/OpenShell/blob/main/SECURITY.md) instead. - type: textarea - id: agent-diagnostic + id: user-story attributes: - label: Agent Diagnostic + label: User Story + description: Describe who encountered this behavior, what they need to do, and why it matters. + placeholder: | + As a , + I want , + so that . + validations: + required: true + + - type: textarea + id: problem + attributes: + label: Problem Statement + description: Summarize what is broken or missing in the current behavior. Focus on the issue itself; describe its consequences and current workarounds in Impact / Why This Matters. + placeholder: Describe the gap or failure in OpenShell's current behavior and when it occurs. + validations: + required: true + + - type: textarea + id: impact + attributes: + label: Impact / Why This Matters description: | - Paste the output from your agent's investigation of this bug. What skills did it load? What did it find? What did it try? Which OpenShell version did it test, and did it check the latest release, known fixes, and possible duplicates? + Explain how the bug affects users and what they must do to work around it today. Describe the operational cost, security risk, data loss, blocked workflow, or other concrete consequence. Include evidence where available, but do not diagnose the cause or prescribe the fix. placeholder: | - Example: - - Loaded `debug-inference` skill - - Tested OpenShell v0.x.x - - Checked latest release / known fixes: no matching fix found - - Searched existing issues for duplicates: no matching issue found - - Ran `openshell inference get` and `openshell provider get ollama` - - Found `OPENAI_BASE_URL=http://127.0.0.1:11434/v1`, which is unreachable from the gateway - - Updated the provider to use `host.openshell.internal`, but the issue persists because the gateway is remote + When this happens, users must... + This results in... + This matters because... validations: required: true - type: textarea - id: description + id: acceptance-criteria attributes: - label: Description - description: What happened? What did you expect to happen? + label: Acceptance Criteria + description: List the specific, observable outcomes that would demonstrate the bug is fixed. + placeholder: | + - [ ] + - [ ] validations: required: true @@ -41,7 +60,7 @@ body: id: reproduction attributes: label: Reproduction Steps - description: Minimal steps to reproduce the issue. + description: Provide the minimal steps needed to reproduce the issue. placeholder: | 1. Run `openshell sandbox create -- claude` 2. ... @@ -52,13 +71,12 @@ body: id: environment attributes: label: Environment - description: OS, Docker version, OpenShell version tested, whether the latest release and existing issues were checked, and any other relevant details. + description: Include the OpenShell version and relevant OS, deployment mode, runtime, or integration details. placeholder: | - - OS: macOS 15.2 / Ubuntu 24.04 / Windows 11 + WSL2 - - Docker: Docker Desktop 4.x / Docker Engine 27.x - OpenShell: v0.x.x (output of `openshell --version`) - - Latest release checked: yes / no, because ... - - Possible duplicates checked: yes / no, because ... + - OS: macOS 15.2 / Ubuntu 24.04 / Windows 11 + WSL2 + - Runtime: Docker Desktop 4.x / Docker Engine 27.x / Kubernetes v1.x + - Deployment or integration: validations: required: true @@ -67,24 +85,8 @@ body: attributes: label: Logs description: | - Relevant log output, error messages, or stack traces. - Redact credentials, API keys, and tokens before pasting — verbose error output from some frameworks includes the full request config. + Include the smallest relevant log excerpt, error message, or stack trace. + Redact credentials, API keys, tokens, and query parameters before pasting. render: shell validations: required: false - - - type: checkboxes - id: checklist - attributes: - label: Agent-First Checklist - options: - - label: I pointed my agent at the repo and had it investigate this issue - required: true - - label: I loaded relevant skills (e.g., `debug-openshell-cluster`, `debug-inference`, `openshell-cli`) - required: true - - label: I checked the latest OpenShell release and either reproduced the issue there or explained why I cannot upgrade/test it - required: true - - label: I searched existing issues for possible duplicates or explained why I could not - required: true - - label: My agent could not resolve this — the diagnostic above explains why - required: true diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index bbc1188d7a..10ae9cbe50 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -1,5 +1,5 @@ name: Feature Request -description: Propose a feature with a design. Not a "please build this" request. +description: Propose a feature with a user story and design. Not a "please build this" request. type: Feature body: - type: markdown @@ -7,15 +7,40 @@ body: value: | ## Design-First Feature Proposals - OpenShell feature requests must include a design proposal — describe the system behavior you want, not just the outcome. New features start here, not as RFC pull requests. If maintainers decide an RFC is necessary, they will request one from this issue and assign the RFC number. + OpenShell feature requests must include a user story and workflow-level design proposal. Describe who needs the feature, the problem it solves, why the current gap matters, the desired user-facing workflow, and the observable criteria for success. Leave implementation choices to the people building the feature. New features start here, not as RFC pull requests. If maintainers decide an RFC is necessary, they will request one from this issue and assign the RFC number. If your agent explored the codebase to assess feasibility (e.g., using the `create-spike` skill), include its findings. + - type: textarea + id: user-story + attributes: + label: User Story + description: Describe who needs this feature, what they need to do, and why it matters. + placeholder: | + As a , + I want , + so that . + validations: + required: true + - type: textarea id: problem attributes: label: Problem Statement - description: What problem does this solve? Why does it matter? + description: Summarize the capability or behavior missing from OpenShell today. Focus on the gap itself; describe its consequences and current workarounds in Impact / Why This Matters. + validations: + required: true + + - type: textarea + id: impact + attributes: + label: Impact / Why This Matters + description: | + Explain what users must do today and why that is insufficient. Describe the operational cost, security risk, blocked workflow, or adoption barrier caused by the problem. Include concrete evidence where available, but do not prescribe the solution. + placeholder: | + Without this feature, users must... + This results in... + This matters because... validations: required: true @@ -24,7 +49,18 @@ body: attributes: label: Proposed Design description: | - How should this work? Describe the system behavior, components involved, and user-facing interface. This should be a design, not a wish list. + How should this work from the user's perspective? Describe the desired workflow and externally observable behavior. Avoid prescribing internal components or implementation unless they are essential constraints. + validations: + required: true + + - type: textarea + id: acceptance-criteria + attributes: + label: Acceptance Criteria + description: List specific, observable outcomes that would make this feature complete without prescribing how implementers achieve them. + placeholder: | + - [ ] + - [ ] validations: required: true @@ -32,7 +68,7 @@ body: id: alternatives attributes: label: Alternatives Considered - description: What other approaches did you evaluate? Why is the proposed design better? + description: What other user-facing workflows or behaviors did you consider? Why does the proposed approach best satisfy the user story? validations: required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index f6de74c859..2efbaac5d1 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -13,7 +13,7 @@ No issue required: ## Testing - + - [ ] `mise run pre-commit` passes - [ ] Unit tests added/updated - [ ] E2E tests added/updated (if applicable) diff --git a/.github/workflows/branch-checks.yml b/.github/workflows/branch-checks.yml index 8a26b3724a..1f058532a9 100644 --- a/.github/workflows/branch-checks.yml +++ b/.github/workflows/branch-checks.yml @@ -286,7 +286,7 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} steps: - - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install tools run: mise install --locked diff --git a/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml index dfa7cfed8c..35792bcb63 100644 --- a/.github/workflows/release-tag.yml +++ b/.github/workflows/release-tag.yml @@ -1087,7 +1087,7 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} steps: - - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ inputs.tag || github.ref }} diff --git a/.github/workflows/sync-docs.yml b/.github/workflows/sync-docs.yml index 586444e26e..db2f29f736 100644 --- a/.github/workflows/sync-docs.yml +++ b/.github/workflows/sync-docs.yml @@ -93,7 +93,7 @@ jobs: path: docs-website - name: Install uv - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + uses: astral-sh/setup-uv@ae62891fec2bb8e7d6c99fc78c9fec3a63790f8d # v10.0.0 with: version: "0.10.12" diff --git a/AGENTS.md b/AGENTS.md index 51483f88e0..fd1b97e258 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,9 +17,9 @@ Agent skills live in `.agents/skills/`. Your harness can discover and load them These pipelines connect skills into end-to-end workflows. Individual skill files don't describe these relationships. - **Community inflow:** `triage-issue` → human disposition and roadmap placement → `create-spike` when needed → `build-from-issue` - - Triage establishes facts and marks technically valid issues `state:validated`. A human applies `state:accepted` if the project should pursue the work and separately places it on the roadmap. The `agent:*` labels support unattended agents that scan for queued work: a human queues a plan with `agent:plan-requested`, the agent returns `agent:plan-ready`, and a human queues implementation with `agent:implementation-requested`. A direct user request to an agent authorizes the requested phase without those labels. + - Triage establishes facts and marks technically valid issues `state:validated`. A human signals that the project should pursue the work by applying `state:accepted` or placing the issue on the roadmap. The `agent:*` labels support unattended agents that scan for queued work: a human queues a plan with `agent:plan-requested`, the agent returns `agent:plan-ready`, and a human queues implementation with `agent:implementation-requested`. A direct user request to an agent authorizes the requested phase without those labels. - **Internal development:** `create-spike` → human disposition and roadmap placement → `build-from-issue` - - Spike explores feasibility and marks its issue `state:validated` when sufficient evidence exists. A human accepts it with `state:accepted` or declines it, separately places it on the roadmap, and optionally queues it through the `agent:*` workflow or directs an agent to it. + - Spike explores feasibility and marks its issue `state:validated` when sufficient evidence exists. A human accepts it with `state:accepted` or roadmap placement, or declines it, and optionally queues it through the `agent:*` workflow or directs an agent to it. - **Security:** `review-security-issue` → `fix-security-issue` - General build agents must not process `topic:security` issues. For unattended processing, a human queues specialized review with `agent:plan-requested`; review produces a severity assessment and remediation plan; a human queues remediation with `agent:implementation-requested`. Direct requests to the specialized skills do not require those labels. - **Policy iteration:** `openshell-cli` → `generate-sandbox-policy` @@ -74,11 +74,11 @@ These pipelines connect skills into end-to-end workflows. Individual skill files ## Issue and PR Conventions -- **Bug reports** must include an agent diagnostic section — proof that the reporter's agent investigated the issue before filing. See the issue template. -- **Feature requests** must include a design proposal, not just a "please build this" request. See the issue template. +- **Bug reports and feature requests** must include a User Story, Problem Statement, Impact / Why This Matters, and Acceptance Criteria. The impact should explain the consequences of the current behavior, the current workaround, and why that workaround is insufficient. Bug reports additionally require reproduction steps and environment details and may include concise, redacted logs. +- **Feature requests** must also include a Proposed Design and Alternatives Considered. The design should define the user-facing workflow and externally observable behavior while leaving internal implementation choices open. Agent investigation is optional. - **New features** must start as GitHub issues using the feature request template. Open an RFC only after an issue exists; maintainers decide when one is needed and assign RFC numbers from the issue. -- **Issue triage** establishes technical validity and impact evidence. Agents never decide roadmap acceptance, apply `state:accepted`, place issues on the roadmap, or apply `agent:plan-requested` or `agent:implementation-requested`. Humans accept or decline validated work and separately place it on the roadmap. The request labels queue work for unattended agents; an explicit user instruction can instead authorize an agent to plan or implement a specific issue. OpenShell has no `priority:*` labels; roadmap association carries sequencing. -- **PRs** must follow the PR template structure: Summary, Related Issue, Changes, Testing, Checklist. +- **Issue triage** establishes technical validity and impact evidence. Agents never decide acceptance, apply `state:accepted`, place issues on the roadmap, or apply `agent:plan-requested` or `agent:implementation-requested`. Humans accept or decline validated work; `state:accepted` or roadmap placement records acceptance, and roadmap association additionally carries sequencing. The request labels queue work for unattended agents; an explicit user instruction can instead authorize an agent to plan or implement a specific issue. OpenShell has no `priority:*` labels. +- **PRs** must follow the PR template structure: Summary, Related Issue, Changes, Testing, Checklist. Contributors should use their agent to investigate the current code and behavior for accepted issue-backed work, verify any diagnostics already on the issue, understand the change they submit, and report the resulting implementation and verification—not paste an earlier issue-filing diagnostic. - **PRs for features, user-visible behavior, public APIs, architecture, or multi-PR efforts** must link an accepted issue. Small docs fixes, mechanical maintenance, and obvious localized bug fixes may state why no issue is required. - **PRs from unvouched external contributors** are automatically closed. See the Vouch System section above. - **Security vulnerabilities** must NOT be filed as GitHub issues. Follow [SECURITY.md](SECURITY.md). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e6ea9d52d3..2562e8f11c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing to OpenShell -OpenShell is built agent-first. We design systems and use agents to implement them. Your agent is your first collaborator — point it at this repo before opening issues, asking questions, or submitting code. +OpenShell is built agent-first. We use agents to design and implement systems, while humans manage product decisions and the project roadmap. ## The Critical Rule @@ -34,30 +34,38 @@ We use a vouch system. This exists because AI makes it trivial to generate plaus Issues labeled [`good first issue`](https://github.com/NVIDIA/OpenShell/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) are scoped, well-documented, and friendly to new contributors. Start there. If you need guidance, comment on the issue. -An open issue is not necessarily accepted or ready to be worked on. Human contributors should look for `state:accepted`, `good first issue`, or `help wanted`, or ask a maintainer before starting. Unattended agents additionally require the appropriate human-applied `agent:*` request label; an agent directly asked to work on a specific issue does not. Roadmap placement describes sequencing and does not authorize work. +An open issue is not necessarily accepted or ready to be worked on. Human contributors should look for `state:accepted`, roadmap placement, `good first issue`, or `help wanted`, or ask a maintainer before starting. Unattended agents additionally require the appropriate human-applied `agent:*` request label; an agent directly asked to work on a specific issue does not. ## Before You Open an Issue -This project ships with [agent skills](#agent-skills-for-contributors) that can diagnose problems, explore the codebase, generate policies, and walk you through common workflows. Before filing an issue: +Search open and closed issues for the same need. Bug reports and feature requests must include: -1. Clone the repo and point your coding agent at it. -2. Load the relevant skill - `debug-openshell-cluster` for gateway or deployment problems, `debug-inference` for inference setup problems, `openshell-cli` for usage questions, `generate-sandbox-policy` for policy help. -3. Have your agent investigate. Let it run diagnostics, read the architecture docs, and attempt a fix. -4. If the agent cannot resolve it, open an issue **with the agent's diagnostic output attached**. The issue template requires this. +1. **User Story:** who needs the change and what they need to do. +2. **Problem Statement:** a concise summary of what is broken or missing in the current behavior. +3. **Impact / Why This Matters:** the consequences of the current behavior, the current workaround, and why that workaround is insufficient. +4. **Acceptance Criteria:** specific, observable outcomes that define success. + +Feature requests must also propose a user-facing workflow and describe alternatives considered. Define the externally observable behavior and leave internal implementation choices open. Bug reports instead include minimal reproduction steps, the OpenShell version and relevant environment, and a small, redacted log excerpt when it materially clarifies the behavior. + +The project includes optional [agent skills](#agent-skills-for-contributors) for self-service troubleshooting and exploration. Use them when they help you, but summarize any useful result in your own words rather than pasting a diagnostic transcript. ### When to Open an Issue -- A real bug that your agent confirmed and could not fix. -- A feature proposal with a design — not a "please build this" request. -- An infrastructure problem that the gateway deployment troubleshooting skill could not resolve. -- An inference setup problem that the `debug-inference` skill could not resolve. +- A workflow behaves differently from what you need or reasonably expect. +- OpenShell does not support an outcome that matters to your workflow. +- The available documentation or configuration does not explain how to complete a supported workflow. - Security vulnerabilities must follow [SECURITY.md](SECURITY.md) — **not** GitHub issues. ### When NOT to Open an Issue -- Questions about how things work — your agent can answer these from the codebase and architecture docs. -- Configuration problems - your agent can diagnose these with `openshell-cli`, `debug-openshell-cluster`, and `debug-inference`. -- "How do I..." requests — the skills cover CLI usage, policy generation, TUI development, and more. +- General questions or open-ended discussion — use [GitHub Discussions](https://github.com/NVIDIA/OpenShell/discussions). +- Security vulnerabilities — follow [SECURITY.md](SECURITY.md) instead. + +## Before You Submit a Change + +Do not start substantial issue-backed work until a maintainer has accepted the issue, unless a maintainer directly asks you to investigate or implement it. Once the work is authorized, use your agent to investigate the current code and behavior. If the issue contains earlier diagnostics, verify them rather than relying on them. + +Use agents and the repository skills as needed to understand the affected code, evaluate tradeoffs, implement the smallest coherent change, and verify it. The pull request should explain what changed and how it was tested; it should not substitute an agent transcript for the contributor's understanding. ## Agent Skills for Contributors @@ -111,11 +119,11 @@ Each issue can require four independent decisions: | Decision | Question | Recorded by | |---|---|---| | Assessment | Is the report technically valid, and is there enough evidence to act on it? | `state:*` | -| Disposition | Should OpenShell pursue the work? | `state:accepted` or closure as not planned | +| Disposition | Should OpenShell pursue the work? | `state:accepted`, roadmap placement, or closure as not planned | | Sequencing | Where does accepted work sit relative to everything else? | Placement on the [OpenShell Roadmap](https://github.com/orgs/NVIDIA/projects/233) | | Ownership | Will a human implement the issue, will a user directly instruct an agent, or will a maintainer queue it for an unattended agent? | Direct instruction or optional `agent:*` workflow | -Completing one decision does not imply the others. `state:validated` confirms that the factual assessment is complete, but it does not mean the project has accepted the work. Roadmap placement communicates sequencing, but it does not authorize an agent to begin. +`state:validated` confirms that the factual assessment is complete, but it does not mean the project has accepted the work. A maintainer signals acceptance with `state:accepted` or roadmap placement. Roadmap placement also communicates sequencing, but it does not assign an owner or queue an unattended agent. #### Who Controls Each Decision @@ -126,7 +134,7 @@ Agents investigate issues, collect evidence, and report technical findings. Huma | Assess technical validity and impact | Triage agent or human triager | | Request missing evidence | Triage agent or human triager | | Mark the assessment complete with `state:validated` | Triage agent or human triager | -| Accept or decline the work | Maintainer | +| Accept or decline the work with `state:accepted`, roadmap placement, or closure | Maintainer | | Place the issue on the roadmap or move it | Maintainer | | Directly request an agent plan | User | | Queue an agent plan with `agent:plan-requested` | Maintainer | @@ -153,7 +161,7 @@ Keep one of these states on an open issue. When new evidence resolves a `state:n #### Assessing an Incoming Issue -Triage checks the report, its diagnostic evidence, related issues, current releases, and the relevant code paths. The assessment ends in one of these outcomes: +Triage checks the user story, reproduction or workflow, environment, related issues, current releases, and the relevant code paths. The assessment ends in one of these outcomes: | Outcome | State or resolution | |---|---| @@ -172,17 +180,17 @@ Triage establishes facts and impact. It does not decide whether the project shou When an issue reaches `state:validated`, a maintainer chooses one of three paths: -- **Accept:** replace `state:validated` with `state:accepted` and place it on the roadmap. +- **Accept:** apply `state:accepted`, place the issue on the roadmap, or do both. Either action signals that OpenShell should pursue the work; roadmap placement additionally records sequencing. - **Decline:** close it as not planned and record the rationale. - **Await more evidence:** replace `state:validated` with `state:needs-info` and leave it off the roadmap. -Do not use `state:accepted` as shorthand for technical validity, roadmap sequencing, or agent authorization. It records only the human decision that OpenShell should pursue the work. +Do not use `state:accepted` as shorthand for technical validity, roadmap sequencing, or agent authorization. It records the human decision that OpenShell should pursue the work. Roadmap placement records the same acceptance decision plus sequencing. #### Roadmap -OpenShell does not use priority labels. Sequencing comes from the [OpenShell Roadmap](https://github.com/orgs/NVIDIA/projects/233): a maintainer associates an accepted issue with a roadmap item, and the roadmap item's own timing carries the urgency. Issues tracked on the roadmap carry the `roadmap` label. +OpenShell does not use priority labels. Sequencing comes from the [OpenShell Roadmap](https://github.com/orgs/NVIDIA/projects/233): a maintainer associates an issue with a roadmap item, signaling acceptance and giving it timing. Issues tracked on the roadmap carry the `roadmap` label. -An accepted issue with no roadmap association is real work the project intends to do, but it is not scheduled. Ask a maintainer before starting on one. +An issue with `state:accepted` and no roadmap association is real work the project intends to do, but it is not scheduled. Ask a maintainer before starting on one. Roadmap placement does not assign an owner. A roadmap issue still needs a human contributor, a direct user instruction to an agent, or an unattended-agent queue label. @@ -205,7 +213,7 @@ Maintainers use the `agent:*` workflow to queue work for always-on or unattended The normal delegated workflow is: ```text -state:accepted +(state:accepted OR roadmap placement) | +-- agent:plan-requested | @@ -248,12 +256,12 @@ A user may instead directly request review or remediation from the specialized s | You are | Ready when | |---|---| -| A human contributor | The issue has `state:accepted`, invites contribution or has maintainer confirmation, and has no conflicting owner or implementation. | -| An unattended agent scanning for planning work | The issue has `state:accepted` and the human-applied `agent:plan-requested` label. | -| An unattended agent scanning for implementation work | The issue has `state:accepted`, an approved plan, and the human-applied `agent:implementation-requested` label. | -| An agent directly instructed by a user | The issue has `state:accepted`, no conflicting owner or implementation, and the instruction explicitly requests the phase the agent will perform. | +| A human contributor | The issue has `state:accepted`, roadmap placement, an invitation to contribute, or maintainer confirmation, and has no conflicting owner or implementation. | +| An unattended agent scanning for planning work | The issue has `state:accepted` or roadmap placement, plus the human-applied `agent:plan-requested` label. | +| An unattended agent scanning for implementation work | The issue has `state:accepted` or roadmap placement, plus an approved plan and the human-applied `agent:implementation-requested` label. | +| An agent directly instructed by a user | The issue has `state:accepted` or roadmap placement, no conflicting owner or implementation, and the instruction explicitly requests the phase the agent will perform. | -Issues with `state:triage-needed`, `state:needs-info`, or `state:validated` are not ready for implementation. Roadmap placement alone never makes an issue ready. +Issues with `state:triage-needed`, `state:needs-info`, or `state:validated` are not ready for implementation unless a maintainer has separately placed them on the roadmap. Either `state:accepted` or roadmap placement records the required human acceptance decision. #### Stale Issues diff --git a/Cargo.lock b/Cargo.lock index c0afff104b..37b9140600 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3787,6 +3787,7 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tokio-stream", + "toml", "tonic", "tracing", "tracing-subscriber", diff --git a/README.md b/README.md index 0f64359c67..ff23302367 100644 --- a/README.md +++ b/README.md @@ -224,7 +224,7 @@ Your agent can load skills for CLI usage (`openshell-cli`), gateway troubleshoot OpenShell is developed using the same agent-driven workflows it enables. The `.agents/skills/` directory contains workflow automation that powers the project's development cycle: -- **Spike and build:** Investigate a problem with `create-spike`; a human accepts or declines it and separately places it on the [roadmap](https://github.com/orgs/NVIDIA/projects/233). Accepted work can remain human-owned or enter the optional, human-gated `agent:*` planning and implementation workflow. +- **Spike and build:** Investigate a problem with `create-spike`; a human accepts it with `state:accepted` or [roadmap](https://github.com/orgs/NVIDIA/projects/233) placement, or declines it. Accepted work can remain human-owned or enter the optional, human-gated `agent:*` planning and implementation workflow. - **Triage and route:** Community issues are assessed with `triage-issue`. Agents establish technical validity and impact; humans decide whether the project should act and where the work sits on the roadmap. - **Security review:** `review-security-issue` produces a severity assessment and remediation plan. `fix-security-issue` implements it. - **Policy authoring:** `generate-sandbox-policy` creates YAML policies from plain-language requirements or API documentation. @@ -252,7 +252,7 @@ All agent implementation work is human-gated: maintainers explicitly request a p ## Contributing -OpenShell is built agent-first — your agent is your first collaborator. Before opening issues or submitting code, point your agent at the repo and let it use the skills in `.agents/skills/` to investigate, diagnose, and prototype. See [CONTRIBUTING.md](CONTRIBUTING.md) for the full agent skills table, contribution workflow, and development setup. +OpenShell is built agent-first. Issues should include a user story, problem statement, impact, and acceptance criteria. The impact should explain the consequences of the current behavior and why existing workarounds are insufficient. Feature requests also require a workflow-level proposed design and alternatives; bug reports add reproduction steps, environment details, and relevant logs. Once maintainers accept work, contributors should use the skills in `.agents/skills/` to investigate the current code and behavior, implement the change, and verify it. If an issue contains earlier diagnostics, verify them rather than relying on them. See [CONTRIBUTING.md](CONTRIBUTING.md) for the full agent skills table, contribution workflow, and development setup. ## Telemetry diff --git a/architecture/gateway.md b/architecture/gateway.md index cac4f91e6b..a9831ae220 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -37,19 +37,17 @@ 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. -Docker and Podman may negotiate additional listeners that make the gateway -reachable from their local sandbox network topology. Those listeners accept +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 +authorization boundary. When the primary listener does not cover the address, +the gateway adds a callback-only listener. Additional callback listeners accept only gRPC methods classified as sandbox-callable by the gateway's generated authorization metadata. They reject user and administrator APIs, health, reflection, non-callback inference APIs, and HTTP routes before normal request authentication. The operator-configured primary listener retains the full multiplexed API surface. -The gateway rejects a callback requirement that resolves to the exact primary -listener address because one socket cannot preserve two authorization scopes. -A wildcard primary listener may cover a callback address because the accepted -connection's concrete local address still selects the callback-only scope. - The `rpc_auth` classification is also the source of truth for negotiated listener exposure: marking an RPC as `sandbox` or `dual` makes it callable on these listeners. Review such changes as both authorization and network-surface @@ -699,8 +697,10 @@ system entry instead of pretending to delete package-manager owned state. - Compute runtimes own the mechanics of starting workloads and injecting callback configuration. - Docker-backed local gateways use Docker's `host-gateway` callback alias on - macOS and Docker Desktop-style runtimes. Native Linux Docker may expose an - additional bridge-gateway listener because the host can bind that bridge IP. + macOS and Docker Desktop-style runtimes. They request IPv4 loopback callback + reachability and add a listener only when the primary does not cover it. + Native Linux Docker may expose an additional bridge-gateway listener because + the host can bind that bridge IP. - Podman-backed macOS gateways use gvproxy's host-loopback IP for sandbox host aliases by default so stale Podman machine images do not need Podman's `host-gateway` resolver. Linux Podman keeps the resolver unless diff --git a/architecture/sandbox.md b/architecture/sandbox.md index bd1feae1f2..82e3d046ea 100644 --- a/architecture/sandbox.md +++ b/architecture/sandbox.md @@ -190,6 +190,14 @@ file and builds the `Proxy-Authorization: Basic` header; a credential that is empty, contains control characters, or is not in `user:pass` form is fatal on both sides. +For Kubernetes sandboxes, the operator configures a Secret name and key rather +than a gateway-host file path. Kubernetes projects that Secret only into the +container that runs network supervision. Proxy credential Secrets require the +sidecar topology, which gives them a separate container boundary from the +workload. Combined topology is rejected because Kubernetes `fsGroup` volume +permission handling can make a shared credential mount readable by the sandbox +group. + The Basic header travels over the plain-TCP connection to the `http://` proxy, so it is readable on the network path between sandbox host and proxy. Configuring `proxy_auth_file` therefore requires the explicit opt-in diff --git a/crates/openshell-cli/src/tls.rs b/crates/openshell-cli/src/tls.rs index 2eadafc71a..c24b84c7dc 100644 --- a/crates/openshell-cli/src/tls.rs +++ b/crates/openshell-cli/src/tls.rs @@ -22,6 +22,7 @@ use tokio::sync::Mutex; use tonic::service::interceptor::InterceptedService; use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint, Identity}; use tracing::debug; +use url::{Host, Url}; /// Concrete gRPC client type used by all commands. pub type GrpcClient = OpenShellClient>; @@ -223,12 +224,33 @@ pub fn build_rustls_config(materials: &TlsMaterials) -> Result ClientTlsConfig { +pub fn build_tonic_tls_config(server: &str, materials: &TlsMaterials) -> Result { let ca_cert = Certificate::from_pem(materials.ca.clone()); let identity = Identity::from_pem(materials.cert.clone(), materials.key.clone()); - ClientTlsConfig::new() - .ca_certificate(ca_cert) - .identity(identity) + tls_config_with_server_name( + server, + ClientTlsConfig::new() + .ca_certificate(ca_cert) + .identity(identity), + ) +} + +fn tls_config_with_server_name(server: &str, config: ClientTlsConfig) -> Result { + Ok(config.domain_name(tls_server_name(server)?)) +} + +fn tls_server_name(server: &str) -> Result { + let endpoint = Url::parse(server) + .into_diagnostic() + .wrap_err_with(|| format!("invalid gateway endpoint '{server}'"))?; + let host = endpoint + .host() + .ok_or_else(|| miette::miette!("gateway endpoint '{server}' has no host"))?; + Ok(match host { + Host::Domain(domain) => domain.to_string(), + Host::Ipv4(address) => address.to_string(), + Host::Ipv6(address) => address.to_string(), + }) } #[derive(Debug)] @@ -402,22 +424,20 @@ pub async fn build_channel(server: &str, tls: &TlsOptions) -> Result { // Bearer auth over HTTPS: use mTLS certs for the transport layer when // available (server may still require client certs), and layer the // Bearer token on top via the interceptor. - require_tls_materials(server, tls).map_or_else( - |_| { - let resolved = tls.with_default_paths(server); - resolved - .ca - .as_ref() - .and_then(|ca_path| std::fs::read(ca_path).ok()) - .map_or_else( - || ClientTlsConfig::new().with_enabled_roots(), - |ca_pem| { - ClientTlsConfig::new().ca_certificate(Certificate::from_pem(ca_pem)) - }, - ) - }, - |materials| build_tonic_tls_config(&materials), - ) + if let Ok(materials) = require_tls_materials(server, tls) { + build_tonic_tls_config(server, &materials)? + } else { + let resolved = tls.with_default_paths(server); + let config = resolved + .ca + .as_ref() + .and_then(|ca_path| std::fs::read(ca_path).ok()) + .map_or_else( + || ClientTlsConfig::new().with_enabled_roots(), + |ca_pem| ClientTlsConfig::new().ca_certificate(Certificate::from_pem(ca_pem)), + ); + tls_config_with_server_name(server, config)? + } } else if tls.edge_token.is_some() { // Edge bearer mode — routed through tunnel above; if we reach here // the server is not HTTPS so connect plaintext. @@ -425,7 +445,7 @@ pub async fn build_channel(server: &str, tls: &TlsOptions) -> Result { } else { // Standard mTLS: private CA + client cert. let materials = require_tls_materials(server, tls)?; - build_tonic_tls_config(&materials) + build_tonic_tls_config(server, &materials)? }; endpoint = endpoint.tls_config(tls_config).into_diagnostic()?; endpoint.connect().await.into_diagnostic() @@ -451,3 +471,25 @@ pub async fn grpc_inference_client(server: &str, tls: &TlsOptions) -> Result, ssh_socket_path: String, stop_timeout_secs: u32, log_level: String, @@ -428,6 +429,8 @@ impl DockerComputeDriver { let host_gateway_ip = parse_optional_host_gateway_ip(&docker_config.host_gateway_ip)?; let gateway_route = docker_gateway_route(&info, bridge_gateway_ip, gateway_port, host_gateway_ip); + let gateway_callback_bind_address = + docker_gateway_callback_bind_address(&gateway_route, config.bind_address); let mut docker_config = docker_config.clone(); if docker_config.grpc_endpoint.trim().is_empty() { let scheme = if docker_guest_tls_configured(&docker_config) { @@ -456,6 +459,7 @@ impl DockerComputeDriver { grpc_endpoint, network_name, gateway_route, + gateway_callback_bind_address, ssh_socket_path: docker_config.ssh_socket_path.clone(), stop_timeout_secs: DEFAULT_STOP_TIMEOUT_SECS, log_level: config.log_level.clone(), @@ -1577,15 +1581,19 @@ impl ComputeDriver for DockerComputeDriver { &self, _request: Request, ) -> Result, Status> { - let requirements = match self.config.gateway_route { - DockerGatewayRoute::Bridge { bind_address, .. } => { - vec![GatewayListenerRequirement { - reason: "docker managed bridge gateway".to_string(), - selector: Some(Selector::ExactBindAddress(bind_address.to_string())), - }] - } - DockerGatewayRoute::HostGateway => Vec::new(), - }; + let requirements = + self.config + .gateway_callback_bind_address + .map_or_else(Vec::new, |bind_address| { + vec![GatewayListenerRequirement { + reason: match self.config.gateway_route { + DockerGatewayRoute::Bridge { .. } => "docker managed bridge gateway", + DockerGatewayRoute::HostGateway => "docker host-gateway IPv4 loopback", + } + .to_string(), + selector: Some(Selector::ExactBindAddress(bind_address.to_string())), + }] + }); Ok(Response::new(GetGatewayListenerRequirementsResponse { requirements, })) @@ -2793,6 +2801,22 @@ fn docker_gateway_route_for_host( } } +fn docker_gateway_callback_bind_address( + route: &DockerGatewayRoute, + primary_bind_address: SocketAddr, +) -> Option { + match route { + DockerGatewayRoute::Bridge { bind_address, .. } => Some(*bind_address), + DockerGatewayRoute::HostGateway => match primary_bind_address.ip() { + IpAddr::V4(ip) if ip.is_unspecified() || ip == Ipv4Addr::LOCALHOST => None, + _ => Some(SocketAddr::new( + IpAddr::V4(Ipv4Addr::LOCALHOST), + primary_bind_address.port(), + )), + }, + } +} + fn host_runtime_requires_host_gateway_alias() -> bool { cfg!(target_os = "macos") } diff --git a/crates/openshell-driver-docker/src/tests.rs b/crates/openshell-driver-docker/src/tests.rs index 845def5524..be8acbd79d 100644 --- a/crates/openshell-driver-docker/src/tests.rs +++ b/crates/openshell-driver-docker/src/tests.rs @@ -102,6 +102,10 @@ fn runtime_config() -> DockerDriverRuntimeConfig { ), host_alias_ip: IpAddr::V4(Ipv4Addr::new(172, 18, 0, 1)), }, + gateway_callback_bind_address: Some(SocketAddr::new( + IpAddr::V4(Ipv4Addr::new(172, 18, 0, 1)), + DEFAULT_SERVER_PORT, + )), ssh_socket_path: "/run/openshell/ssh.sock".to_string(), stop_timeout_secs: DEFAULT_STOP_TIMEOUT_SECS, log_level: "info".to_string(), @@ -186,6 +190,7 @@ async fn gateway_listener_requirements_report_managed_bridge_address() { async fn gateway_listener_requirements_are_empty_for_host_gateway_route() { let mut config = runtime_config(); config.gateway_route = DockerGatewayRoute::HostGateway; + config.gateway_callback_bind_address = None; let driver = test_driver_with_config(config); let response = driver @@ -197,6 +202,26 @@ async fn gateway_listener_requirements_are_empty_for_host_gateway_route() { assert!(response.requirements.is_empty()); } +#[tokio::test] +async fn host_gateway_route_reports_ipv4_loopback_callback_listener() { + let mut config = runtime_config(); + config.gateway_route = DockerGatewayRoute::HostGateway; + config.gateway_callback_bind_address = Some("127.0.0.1:17670".parse().unwrap()); + let driver = test_driver_with_config(config); + + let response = driver + .get_gateway_listener_requirements(Request::new(GetGatewayListenerRequirementsRequest {})) + .await + .unwrap() + .into_inner(); + + assert_eq!(response.requirements.len(), 1); + assert_eq!( + response.requirements[0].selector, + Some(Selector::ExactBindAddress("127.0.0.1:17670".to_string())) + ); +} + #[test] fn container_visible_endpoint_rewrites_loopback_hosts() { assert_eq!( @@ -298,6 +323,31 @@ fn docker_gateway_route_uses_host_gateway_for_docker_desktop() { ); } +#[test] +fn host_gateway_route_requests_ipv4_loopback_for_ipv6_primary() { + assert_eq!( + docker_gateway_callback_bind_address( + &DockerGatewayRoute::HostGateway, + "[::1]:17670".parse().unwrap(), + ), + Some("127.0.0.1:17670".parse().unwrap()) + ); +} + +#[test] +fn host_gateway_route_reuses_ipv4_primary_when_it_covers_loopback() { + for primary in ["127.0.0.1:17670", "0.0.0.0:17670"] { + assert_eq!( + docker_gateway_callback_bind_address( + &DockerGatewayRoute::HostGateway, + primary.parse().unwrap(), + ), + None, + "{primary} already covers the IPv4 loopback callback" + ); + } +} + #[test] fn docker_gateway_route_uses_host_gateway_for_colima() { let info = SystemInfo { diff --git a/crates/openshell-driver-kubernetes/Cargo.toml b/crates/openshell-driver-kubernetes/Cargo.toml index 2c02f864ab..f9f5bba398 100644 --- a/crates/openshell-driver-kubernetes/Cargo.toml +++ b/crates/openshell-driver-kubernetes/Cargo.toml @@ -37,6 +37,7 @@ miette = { workspace = true } [dev-dependencies] temp-env = "0.3" +toml = { workspace = true } [lints] workspace = true diff --git a/crates/openshell-driver-kubernetes/src/config.rs b/crates/openshell-driver-kubernetes/src/config.rs index 5311f56436..4ca02bd71c 100644 --- a/crates/openshell-driver-kubernetes/src/config.rs +++ b/crates/openshell-driver-kubernetes/src/config.rs @@ -253,6 +253,25 @@ pub struct KubernetesComputeConfig { pub topology: SupervisorTopology, /// Sidecar-only settings used when `topology = "sidecar"`. pub sidecar: KubernetesSidecarConfig, + /// Corporate HTTP forward proxy used by the network supervisor for + /// policy-approved TLS CONNECT egress. + pub https_proxy: Option, + /// Comma-separated destinations that bypass the corporate proxy while + /// continuing through `OpenShell` policy evaluation. + pub no_proxy: Option, + /// Name of the Kubernetes Secret holding the `user:pass` proxy credential. + /// The Secret is mounted only in the network-supervising container. The + /// driver validates this reference at startup; the supervisor validates + /// the Secret content when kubelet mounts it before accepting egress. + pub proxy_auth_secret_name: Option, + /// Key in `proxy_auth_secret_name` containing the `user:pass` credential. + pub proxy_auth_secret_key: Option, + /// Explicit acknowledgement that Basic authentication is cleartext over + /// the connection to an `http://` forward proxy. + pub proxy_auth_allow_insecure: Option, + /// Send hostnames rather than validated IPs in CONNECT requests. This is a + /// last-resort compatibility mode for hostname-filtering proxy ACLs. + pub proxy_connect_by_hostname: Option, pub grpc_endpoint: String, pub ssh_socket_path: String, pub client_tls_secret_name: String, @@ -346,6 +365,12 @@ impl Default for KubernetesComputeConfig { supervisor_sideload_method: SupervisorSideloadMethod::default(), topology: SupervisorTopology::default(), sidecar: KubernetesSidecarConfig::default(), + https_proxy: None, + no_proxy: None, + proxy_auth_secret_name: None, + proxy_auth_secret_key: None, + proxy_auth_allow_insecure: None, + proxy_connect_by_hostname: None, grpc_endpoint: String::new(), ssh_socket_path: openshell_core::container_paths::SSH_SOCKET_PATH.to_string(), client_tls_secret_name: String::new(), @@ -395,6 +420,101 @@ impl KubernetesComputeConfig { self.sidecar.validate_proxy_uid() } + /// Validate the operator-owned corporate upstream proxy configuration. + pub fn validate_upstream_proxy_config(&self) -> Result<(), String> { + use openshell_core::driver_utils::{UpstreamProxyUrlError, parse_upstream_proxy_url}; + + if let Some(url) = &self.https_proxy { + parse_upstream_proxy_url(url).map_err(|err| match err { + UpstreamProxyUrlError::Empty => "https_proxy must not be empty when set".to_string(), + UpstreamProxyUrlError::InlineCredentials => "https_proxy must not embed credentials in the URL; supply them through proxy_auth_secret_name and proxy_auth_secret_key".to_string(), + err => format!("https_proxy {err}"), + })?; + } + + if let Some(list) = self.no_proxy.as_deref() { + if list.trim().is_empty() { + return Err("no_proxy must not be empty when set; omit it instead".to_string()); + } + if self.https_proxy.is_none() { + return Err("no_proxy is set but no https_proxy is configured".to_string()); + } + } + + let secret_name = self.proxy_auth_secret_name.as_deref(); + let secret_key = self.proxy_auth_secret_key.as_deref(); + match (secret_name, secret_key) { + (None, None) => { + if self.proxy_auth_allow_insecure == Some(true) { + return Err("proxy_auth_allow_insecure is set but no proxy credential Secret is configured".to_string()); + } + } + (Some(name), Some(key)) => { + if name.trim().is_empty() || key.trim().is_empty() { + return Err( + "proxy credential Secret name and key must not be empty".to_string() + ); + } + if !is_dns1123_subdomain(name) { + return Err( + "proxy_auth_secret_name must be a valid Kubernetes DNS-1123 subdomain" + .to_string(), + ); + } + if !key + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')) + { + return Err( + "proxy_auth_secret_key must contain only letters, digits, '.', '-', or '_'" + .to_string(), + ); + } + // Kubernetes rejects Secret keys longer than 253 bytes and the + // reserved `.`/`..` names. Reject them here so an invalid + // deployment setting fails at gateway startup instead of + // surfacing as repeated Pod-provisioning failures. + if key.len() > 253 { + return Err( + "proxy_auth_secret_key must be at most 253 bytes to satisfy Kubernetes Secret key limits" + .to_string(), + ); + } + if key == "." || key == ".." { + return Err("proxy_auth_secret_key must not be '.' or '..'".to_string()); + } + if self.https_proxy.is_none() { + return Err( + "proxy credential Secret is set but no https_proxy is configured" + .to_string(), + ); + } + if self.proxy_auth_allow_insecure != Some(true) { + return Err("proxy credentials use cleartext Basic auth over the connection to the http:// proxy; set proxy_auth_allow_insecure = true to accept that exposure, or remove the credential Secret".to_string()); + } + if self.topology == SupervisorTopology::Combined { + return Err( + "proxy credential Secrets require topology = \"sidecar\"; combined topology shares the credential mount with the workload and fsGroup can make it readable by the sandbox user" + .to_string(), + ); + } + } + _ => { + return Err( + "proxy_auth_secret_name and proxy_auth_secret_key must be set together" + .to_string(), + ); + } + } + + if self.proxy_connect_by_hostname.is_some() && self.https_proxy.is_none() { + return Err( + "proxy_connect_by_hostname is set but no https_proxy is configured".to_string(), + ); + } + Ok(()) + } + /// Resolve the sandbox UID/GID pair. /// /// Resolution order: @@ -475,6 +595,20 @@ impl KubernetesComputeConfig { } } +fn is_dns1123_subdomain(value: &str) -> bool { + !value.is_empty() + && value.len() <= 253 + && value.split('.').all(|label| { + !label.is_empty() + && label.len() <= 63 + && !label.starts_with('-') + && !label.ends_with('-') + && label + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') + }) +} + fn validate_provider_spiffe_workload_api_socket_path_value( socket_path: &str, ) -> Result<(), String> { @@ -966,4 +1100,165 @@ mod tests { let uid = cfg.resolve_sandbox_uid(None); assert_eq!(cfg.resolve_sandbox_gid(uid, None), uid); } + + #[test] + fn upstream_proxy_config_accepts_http_proxy_without_credentials() { + let cfg = KubernetesComputeConfig { + https_proxy: Some("http://proxy.corp.example:8080".to_string()), + no_proxy: Some(".svc.cluster.local,10.96.0.0/12".to_string()), + ..KubernetesComputeConfig::default() + }; + assert!(cfg.validate_upstream_proxy_config().is_ok()); + } + + #[test] + fn upstream_proxy_config_accepts_secret_credentials_with_acknowledgement() { + let cfg = KubernetesComputeConfig { + topology: SupervisorTopology::Sidecar, + https_proxy: Some("http://proxy.corp.example:8080".to_string()), + proxy_auth_secret_name: Some("corporate-proxy-auth".to_string()), + proxy_auth_secret_key: Some("credentials".to_string()), + proxy_auth_allow_insecure: Some(true), + ..KubernetesComputeConfig::default() + }; + assert!(cfg.validate_upstream_proxy_config().is_ok()); + } + + #[test] + fn toml_deserializes_sidecar_upstream_proxy_settings() { + let cfg: KubernetesComputeConfig = toml::from_str( + r#" + topology = "sidecar" + https_proxy = "http://proxy.corp.example:8080" + no_proxy = ".svc.cluster.local,10.96.0.0/12" + proxy_auth_secret_name = "corporate-proxy-auth" + proxy_auth_secret_key = "credentials" + proxy_auth_allow_insecure = true + proxy_connect_by_hostname = true + "#, + ) + .unwrap(); + assert!(cfg.validate_upstream_proxy_config().is_ok()); + assert_eq!( + cfg.https_proxy.as_deref(), + Some("http://proxy.corp.example:8080") + ); + assert_eq!( + cfg.proxy_auth_secret_name.as_deref(), + Some("corporate-proxy-auth") + ); + } + + #[test] + fn upstream_proxy_config_rejects_incoherent_auxiliary_settings() { + for cfg in [ + KubernetesComputeConfig { + no_proxy: Some(".svc".to_string()), + ..KubernetesComputeConfig::default() + }, + KubernetesComputeConfig { + https_proxy: Some("http://proxy.corp.example:8080".to_string()), + proxy_auth_secret_name: Some("corporate-proxy-auth".to_string()), + ..KubernetesComputeConfig::default() + }, + KubernetesComputeConfig { + https_proxy: Some("http://proxy.corp.example:8080".to_string()), + proxy_auth_secret_name: Some("corporate-proxy-auth".to_string()), + proxy_auth_secret_key: Some("credentials".to_string()), + ..KubernetesComputeConfig::default() + }, + KubernetesComputeConfig { + proxy_connect_by_hostname: Some(true), + ..KubernetesComputeConfig::default() + }, + ] { + assert!(cfg.validate_upstream_proxy_config().is_err()); + } + } + + #[test] + fn upstream_proxy_config_rejects_unsupported_proxy_scheme() { + let cfg = KubernetesComputeConfig { + https_proxy: Some("https://proxy.corp.example:8443".to_string()), + ..KubernetesComputeConfig::default() + }; + let err = cfg.validate_upstream_proxy_config().unwrap_err(); + assert!(err.contains("https_proxy"), "{err}"); + } + + #[test] + fn upstream_proxy_config_rejects_invalid_secret_name() { + let cfg = KubernetesComputeConfig { + https_proxy: Some("http://proxy.corp.example:8080".to_string()), + proxy_auth_secret_name: Some("Not_A_Secret".to_string()), + proxy_auth_secret_key: Some("credentials".to_string()), + proxy_auth_allow_insecure: Some(true), + ..KubernetesComputeConfig::default() + }; + let err = cfg.validate_upstream_proxy_config().unwrap_err(); + assert!(err.contains("proxy_auth_secret_name"), "{err}"); + } + + #[test] + fn upstream_proxy_config_rejects_invalid_secret_key() { + // A key that Kubernetes cannot create must fail at gateway startup + // instead of surfacing as repeated Pod-provisioning failures. + for key in [ + "a".repeat(254), // exceeds the 253-byte Secret key limit + ".".to_string(), + "..".to_string(), + "bad key".to_string(), // whitespace is outside the allowed charset + ] { + let cfg = KubernetesComputeConfig { + topology: SupervisorTopology::Sidecar, + https_proxy: Some("http://proxy.corp.example:8080".to_string()), + proxy_auth_secret_name: Some("corporate-proxy-auth".to_string()), + proxy_auth_secret_key: Some(key.clone()), + proxy_auth_allow_insecure: Some(true), + ..KubernetesComputeConfig::default() + }; + let err = cfg.validate_upstream_proxy_config().unwrap_err(); + assert!( + err.contains("proxy_auth_secret_key"), + "key {key:?} should be rejected with a key-specific error: {err}" + ); + } + } + + #[test] + fn upstream_proxy_config_accepts_max_length_secret_key() { + let cfg = KubernetesComputeConfig { + topology: SupervisorTopology::Sidecar, + https_proxy: Some("http://proxy.corp.example:8080".to_string()), + proxy_auth_secret_name: Some("corporate-proxy-auth".to_string()), + proxy_auth_secret_key: Some("a".repeat(253)), + proxy_auth_allow_insecure: Some(true), + ..KubernetesComputeConfig::default() + }; + assert!(cfg.validate_upstream_proxy_config().is_ok()); + } + + #[test] + fn upstream_proxy_config_rejects_credentials_in_combined_topology() { + let cfg = KubernetesComputeConfig { + topology: SupervisorTopology::Combined, + https_proxy: Some("http://proxy.corp.example:8080".to_string()), + proxy_auth_secret_name: Some("corporate-proxy-auth".to_string()), + proxy_auth_secret_key: Some("credentials".to_string()), + proxy_auth_allow_insecure: Some(true), + ..KubernetesComputeConfig::default() + }; + let err = cfg.validate_upstream_proxy_config().unwrap_err(); + assert!(err.contains("topology = \"sidecar\""), "{err}"); + } + + #[test] + fn upstream_proxy_config_allows_explicit_false_acknowledgement_without_credentials() { + let cfg = KubernetesComputeConfig { + https_proxy: Some("http://proxy.corp.example:8080".to_string()), + proxy_auth_allow_insecure: Some(false), + ..KubernetesComputeConfig::default() + }; + assert!(cfg.validate_upstream_proxy_config().is_ok()); + } } diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 00e38f6dd2..0965c3676e 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -258,11 +258,13 @@ impl From<&KubernetesDriverVolumeMountConfig> for VolumeMount { } const CLIENT_TLS_VOLUME_NAME: &str = "openshell-client-tls"; +const UPSTREAM_PROXY_AUTH_VOLUME_NAME: &str = "openshell-upstream-proxy-auth"; const SERVICE_ACCOUNT_TOKEN_VOLUME_NAME: &str = "openshell-sa-token"; const SERVICE_ACCOUNT_TOKEN_MOUNT_PATH: &str = "/var/run/secrets/openshell"; const KUBERNETES_DRIVER_RESERVED_VOLUME_NAMES: &[&str] = &[ CLIENT_TLS_VOLUME_NAME, + UPSTREAM_PROXY_AUTH_VOLUME_NAME, SERVICE_ACCOUNT_TOKEN_VOLUME_NAME, SPIFFE_WORKLOAD_API_VOLUME_NAME, SUPERVISOR_VOLUME_NAME, @@ -471,6 +473,9 @@ impl KubernetesComputeDriver { config .validate_proxy_uid() .map_err(KubernetesDriverError::Precondition)?; + config + .validate_upstream_proxy_config() + .map_err(KubernetesDriverError::Precondition)?; let base_config = match kube::Config::incluster() { Ok(c) => c, Err(_) => kube::Config::infer() @@ -854,6 +859,12 @@ impl KubernetesComputeDriver { .config .sidecar .process_binary_aware_network_policy, + https_proxy: self.config.https_proxy.as_deref(), + no_proxy: self.config.no_proxy.as_deref(), + proxy_auth_secret_name: self.config.proxy_auth_secret_name.as_deref(), + proxy_auth_secret_key: self.config.proxy_auth_secret_key.as_deref(), + proxy_auth_allow_insecure: self.config.proxy_auth_allow_insecure == Some(true), + proxy_connect_by_hostname: self.config.proxy_connect_by_hostname == Some(true), service_account_name: &self.config.service_account_name, sandbox_id: &sandbox.id, sandbox_name: &sandbox.name, @@ -1717,19 +1728,20 @@ fn apply_supervisor_binary_source( /// side-loaded binary as root so it can create network namespaces, set up the /// proxy, and configure Landlock/seccomp. #[allow(clippy::similar_names)] -fn apply_supervisor_sideload( +fn apply_supervisor_sideload_with_params( pod_template: &mut serde_json::Value, - supervisor_image: &str, - supervisor_image_pull_policy: &str, - method: SupervisorSideloadMethod, - sandbox_uid: u32, - sandbox_gid: u32, + params: &SandboxPodParams<'_>, ) { let Some(spec) = pod_template.get_mut("spec").and_then(|v| v.as_object_mut()) else { return; }; - apply_supervisor_binary_source(spec, supervisor_image, supervisor_image_pull_policy, method); + apply_supervisor_binary_source( + spec, + params.supervisor_image, + params.supervisor_image_pull_policy, + params.supervisor_sideload_method, + ); // Find the agent container and add volume mount + command override let Some(containers) = spec.get_mut("containers").and_then(|v| v.as_array_mut()) else { @@ -1747,14 +1759,13 @@ fn apply_supervisor_sideload( if let Some(container) = containers.get_mut(index).and_then(|v| v.as_object_mut()) { // Override command to use the side-loaded supervisor binary - container.insert( - "command".to_string(), - serde_json::json!([ - format!("{}/openshell-sandbox", SUPERVISOR_MOUNT_PATH), - "--workdir", - driver_mounts::DEFAULT_WORKSPACE_ROOT - ]), - ); + let mut command = vec![ + format!("{}/openshell-sandbox", SUPERVISOR_MOUNT_PATH), + "--workdir".to_string(), + driver_mounts::DEFAULT_WORKSPACE_ROOT.to_string(), + ]; + command.extend(upstream_proxy_cli_args(params)); + container.insert("command".to_string(), serde_json::json!(command)); // Force the supervisor to run as root (UID 0). Sandbox images may set // a non-root USER directive (e.g. `USER sandbox`), but the supervisor @@ -1785,9 +1796,88 @@ fn apply_supervisor_sideload( .or_insert_with(|| serde_json::json!([])) .as_array_mut(); if let Some(env) = env { - apply_resolved_identity_env(env, sandbox_uid, sandbox_gid); + apply_resolved_identity_env(env, params.sandbox_uid, params.sandbox_gid); } + if has_upstream_proxy_credentials(params) { + let volume_mounts = container + .entry("volumeMounts") + .or_insert_with(|| serde_json::json!([])) + .as_array_mut(); + if let Some(volume_mounts) = volume_mounts { + volume_mounts.push(upstream_proxy_auth_volume_mount()); + } + } + } +} + +#[cfg(test)] +#[allow(clippy::similar_names)] +fn apply_supervisor_sideload( + pod_template: &mut serde_json::Value, + supervisor_image: &str, + supervisor_image_pull_policy: &str, + method: SupervisorSideloadMethod, + sandbox_uid: u32, + sandbox_gid: u32, +) { + let params = SandboxPodParams { + supervisor_image, + supervisor_image_pull_policy, + supervisor_sideload_method: method, + sandbox_uid, + sandbox_gid, + ..SandboxPodParams::default() + }; + apply_supervisor_sideload_with_params(pod_template, ¶ms); +} + +fn upstream_proxy_cli_args(params: &SandboxPodParams<'_>) -> Vec { + let mut args = Vec::new(); + if let Some(url) = params.https_proxy { + args.extend(["--upstream-proxy".to_string(), url.to_string()]); + } + if let Some(list) = params.no_proxy { + args.extend(["--upstream-no-proxy".to_string(), list.to_string()]); } + if has_upstream_proxy_credentials(params) { + args.extend([ + "--upstream-proxy-auth-file".to_string(), + openshell_core::container_paths::UPSTREAM_PROXY_AUTH_MOUNT_PATH.to_string(), + ]); + } + if params.proxy_auth_allow_insecure { + args.push("--upstream-proxy-auth-allow-insecure".to_string()); + } + if params.proxy_connect_by_hostname { + args.push("--upstream-proxy-connect-by-hostname".to_string()); + } + args +} + +fn upstream_proxy_auth_volume_mount() -> serde_json::Value { + serde_json::json!({ + "name": UPSTREAM_PROXY_AUTH_VOLUME_NAME, + "mountPath": upstream_proxy_auth_volume_mount_path(), + "readOnly": true, + }) +} + +fn upstream_proxy_auth_volume_mount_path() -> &'static str { + Path::new(openshell_core::container_paths::UPSTREAM_PROXY_AUTH_MOUNT_PATH) + .parent() + .and_then(Path::to_str) + .expect("upstream proxy auth path has a parent directory") +} + +fn upstream_proxy_auth_file_name() -> &'static str { + Path::new(openshell_core::container_paths::UPSTREAM_PROXY_AUTH_MOUNT_PATH) + .file_name() + .and_then(|name| name.to_str()) + .expect("upstream proxy auth path has a UTF-8 file name") +} + +fn has_upstream_proxy_credentials(params: &SandboxPodParams<'_>) -> bool { + params.proxy_auth_secret_name.is_some() && params.proxy_auth_secret_key.is_some() } fn sidecar_state_volume_mount() -> serde_json::Value { @@ -1927,6 +2017,14 @@ fn supervisor_sidecar_container( } ] }); + container["command"] + .as_array_mut() + .expect("network supervisor command is an array") + .extend( + upstream_proxy_cli_args(params) + .into_iter() + .map(serde_json::Value::String), + ); if !params.supervisor_image_pull_policy.is_empty() { container["imagePullPolicy"] = serde_json::json!(params.supervisor_image_pull_policy); } @@ -1940,6 +2038,12 @@ fn supervisor_sidecar_container( "readOnly": true, })); } + if has_upstream_proxy_credentials(params) { + container["volumeMounts"] + .as_array_mut() + .expect("volumeMounts is an array") + .push(upstream_proxy_auth_volume_mount()); + } if let Some(profile) = params.app_armor_profile { container["securityContext"]["appArmorProfile"] = app_armor_profile_to_k8s(profile); } @@ -2320,6 +2424,7 @@ fn default_workspace_volume_claim_templates( } /// Parameters shared by `sandbox_to_k8s_spec` and `sandbox_template_to_k8s`. +#[allow(clippy::struct_excessive_bools)] struct SandboxPodParams<'a> { default_image: &'a str, image_pull_policy: &'a str, @@ -2330,6 +2435,12 @@ struct SandboxPodParams<'a> { topology: SupervisorTopology, proxy_uid: u32, process_binary_aware_network_policy: bool, + https_proxy: Option<&'a str>, + no_proxy: Option<&'a str>, + proxy_auth_secret_name: Option<&'a str>, + proxy_auth_secret_key: Option<&'a str>, + proxy_auth_allow_insecure: bool, + proxy_connect_by_hostname: bool, service_account_name: &'a str, sandbox_id: &'a str, sandbox_name: &'a str, @@ -2365,6 +2476,12 @@ impl Default for SandboxPodParams<'_> { topology: SupervisorTopology::default(), proxy_uid: DEFAULT_PROXY_UID, process_binary_aware_network_policy: true, + https_proxy: None, + no_proxy: None, + proxy_auth_secret_name: None, + proxy_auth_secret_key: None, + proxy_auth_allow_insecure: false, + proxy_connect_by_hostname: false, service_account_name: DEFAULT_SANDBOX_SERVICE_ACCOUNT_NAME, sandbox_id: "", sandbox_name: "", @@ -2770,6 +2887,32 @@ fn sandbox_template_to_k8s_with_validated_config( } })); } + if has_upstream_proxy_credentials(params) { + let secret_name = params + .proxy_auth_secret_name + .expect("complete proxy credential reference has a Secret name"); + let secret_key = params + .proxy_auth_secret_key + .expect("complete proxy credential reference has a Secret key"); + // The credential volume is mounted only into the container that runs + // network supervision. Sidecar mode uses the pod fsGroup already + // required for its non-root network supervisor. + let default_mode = match params.topology { + SupervisorTopology::Combined => 0o400, + SupervisorTopology::Sidecar => 0o440, + }; + volumes.push(serde_json::json!({ + "name": UPSTREAM_PROXY_AUTH_VOLUME_NAME, + "secret": { + "secretName": secret_name, + "defaultMode": default_mode, + "items": [{ + "key": secret_key, + "path": upstream_proxy_auth_file_name(), + }] + } + })); + } if params.provider_spiffe_enabled { volumes.push(serde_json::json!({ "name": SPIFFE_WORKLOAD_API_VOLUME_NAME, @@ -2830,14 +2973,7 @@ fn sandbox_template_to_k8s_with_validated_config( match params.topology { SupervisorTopology::Combined => { - apply_supervisor_sideload( - &mut result, - params.supervisor_image, - params.supervisor_image_pull_policy, - params.supervisor_sideload_method, - params.sandbox_uid, - params.sandbox_gid, - ); + apply_supervisor_sideload_with_params(&mut result, params); } SupervisorTopology::Sidecar => { apply_supervisor_sidecar_topology( @@ -6431,4 +6567,101 @@ mod tests { .is_none() ); } + + #[test] + fn upstream_proxy_is_injected_only_into_network_supervisors() { + let params = SandboxPodParams { + topology: SupervisorTopology::Sidecar, + supervisor_sideload_method: SupervisorSideloadMethod::InitContainer, + supervisor_image: "supervisor-image:latest", + https_proxy: Some("http://proxy.corp.example:8080"), + no_proxy: Some(".svc.cluster.local,10.96.0.0/12"), + proxy_auth_secret_name: Some("corporate-proxy-auth"), + proxy_auth_secret_key: Some("credentials"), + proxy_auth_allow_insecure: true, + proxy_connect_by_hostname: true, + sandbox_uid: 1500, + sandbox_gid: 1500, + ..SandboxPodParams::default() + }; + let pod = sandbox_template_to_k8s( + &SandboxTemplate::default(), + false, + &std::collections::HashMap::new(), + false, + ¶ms, + ); + let containers = pod["spec"]["containers"].as_array().unwrap(); + let network = containers + .iter() + .find(|container| container["name"] == SUPERVISOR_NETWORK_SIDECAR_NAME) + .unwrap(); + let command = network["command"].as_array().unwrap(); + assert!(command.iter().any(|arg| arg == "--upstream-proxy")); + assert!(command.iter().any(|arg| arg == "--upstream-no-proxy")); + let auth_file_index = command + .iter() + .position(|arg| arg == "--upstream-proxy-auth-file") + .unwrap(); + assert_eq!( + command[auth_file_index + 1], + openshell_core::container_paths::UPSTREAM_PROXY_AUTH_MOUNT_PATH + ); + assert!( + command + .iter() + .any(|arg| arg == "--upstream-proxy-auth-allow-insecure") + ); + assert!( + command + .iter() + .any(|arg| arg == "--upstream-proxy-connect-by-hostname") + ); + assert!( + network["volumeMounts"] + .as_array() + .unwrap() + .iter() + .any(|mount| mount["name"] == UPSTREAM_PROXY_AUTH_VOLUME_NAME) + ); + + let init = pod["spec"]["initContainers"] + .as_array() + .unwrap() + .iter() + .find(|container| container["name"] == SUPERVISOR_NETWORK_INIT_CONTAINER_NAME) + .unwrap(); + assert!(!init["command"].as_array().unwrap().iter().any(|arg| { + arg.as_str() + .is_some_and(|arg| arg.starts_with("--upstream-")) + })); + let agent = containers + .iter() + .find(|container| container["name"] == "agent") + .unwrap(); + assert!( + !agent["volumeMounts"] + .as_array() + .unwrap() + .iter() + .any(|mount| mount["name"] == UPSTREAM_PROXY_AUTH_VOLUME_NAME) + ); + assert!(!agent["env"].as_array().unwrap().iter().any(|entry| { + entry["value"] == "corporate-proxy-auth" || entry["value"] == "credentials" + })); + + let volume = pod["spec"]["volumes"] + .as_array() + .unwrap() + .iter() + .find(|volume| volume["name"] == UPSTREAM_PROXY_AUTH_VOLUME_NAME) + .unwrap(); + assert_eq!(volume["secret"]["secretName"], "corporate-proxy-auth"); + assert_eq!(volume["secret"]["items"][0]["key"], "credentials"); + assert_eq!( + volume["secret"]["items"][0]["path"], + upstream_proxy_auth_file_name() + ); + assert_eq!(volume["secret"]["defaultMode"], 0o440); + } } diff --git a/crates/openshell-driver-kubernetes/src/main.rs b/crates/openshell-driver-kubernetes/src/main.rs index b7d5514ac2..99df4ea165 100644 --- a/crates/openshell-driver-kubernetes/src/main.rs +++ b/crates/openshell-driver-kubernetes/src/main.rs @@ -18,6 +18,7 @@ use openshell_driver_kubernetes::{ #[derive(Parser, Debug)] #[command(name = "openshell-driver-kubernetes")] #[command(version = VERSION)] +#[allow(clippy::struct_excessive_bools)] struct Args { #[arg( long, @@ -100,6 +101,30 @@ struct Args { )] sidecar_process_binary_aware_network_policy: bool, + /// Corporate HTTP forward proxy for policy-approved TLS CONNECT egress. + #[arg(long, env = "OPENSHELL_UPSTREAM_PROXY")] + https_proxy: Option, + + /// Comma-separated destinations that bypass the corporate proxy. + #[arg(long, env = "OPENSHELL_UPSTREAM_NO_PROXY")] + no_proxy: Option, + + /// Kubernetes Secret name containing the upstream proxy credential. + #[arg(long, env = "OPENSHELL_UPSTREAM_PROXY_AUTH_SECRET_NAME")] + proxy_auth_secret_name: Option, + + /// Kubernetes Secret key containing the upstream proxy credential. + #[arg(long, env = "OPENSHELL_UPSTREAM_PROXY_AUTH_SECRET_KEY")] + proxy_auth_secret_key: Option, + + /// Acknowledge cleartext Basic auth to an http:// upstream proxy. + #[arg(long, env = "OPENSHELL_UPSTREAM_PROXY_AUTH_ALLOW_INSECURE", action = ArgAction::SetTrue)] + proxy_auth_allow_insecure: bool, + + /// Send destination hostnames rather than validated IPs in CONNECT. + #[arg(long, env = "OPENSHELL_UPSTREAM_PROXY_CONNECT_BY_HOSTNAME", action = ArgAction::SetTrue)] + proxy_connect_by_hostname: bool, + #[arg(long, env = "OPENSHELL_ENABLE_USER_NAMESPACES")] enable_user_namespaces: bool, @@ -148,6 +173,12 @@ async fn main() -> Result<()> { proxy_uid: args.sidecar_proxy_uid, process_binary_aware_network_policy: args.sidecar_process_binary_aware_network_policy, }, + https_proxy: args.https_proxy, + no_proxy: args.no_proxy, + proxy_auth_secret_name: args.proxy_auth_secret_name, + proxy_auth_secret_key: args.proxy_auth_secret_key, + proxy_auth_allow_insecure: args.proxy_auth_allow_insecure.then_some(true), + proxy_connect_by_hostname: args.proxy_connect_by_hostname.then_some(true), grpc_endpoint: args.grpc_endpoint.unwrap_or_default(), ssh_socket_path: args.sandbox_ssh_socket_path, client_tls_secret_name: args.client_tls_secret_name.unwrap_or_default(), diff --git a/crates/openshell-driver-podman/NETWORKING.md b/crates/openshell-driver-podman/NETWORKING.md index 4b2ae7ff29..843cb0907d 100644 --- a/crates/openshell-driver-podman/NETWORKING.md +++ b/crates/openshell-driver-podman/NETWORKING.md @@ -275,13 +275,11 @@ and rootless pasta because the driver maps both local callback aliases to that literal. Other rootless helpers still fail closed. Podman Machine requests gateway loopback because its configured address is guest-visible and gvproxy terminates that route on host loopback. The gateway validates and binds every -accepted callback listener. A callback address cannot equal the exact primary -listener address because the gateway could not distinguish their authorization -scopes. In particular, a Podman Machine gateway using the IPv4 loopback -callback must place its primary listener on another address, such as IPv6 -loopback (`[::1]:17670`). Negotiated callback listeners expose only the -gateway's sandbox-callable gRPC methods. Operator, health, reflection, and HTTP -requests must use the primary listener. +accepted callback requirement. If the primary listener covers the requested +address, the gateway reuses it and relies on sandbox JWT authorization to limit +the supervisor's RPCs. Otherwise, it creates an additional listener that +exposes only the gateway's sandbox-callable gRPC methods. Operator, health, +reflection, and HTTP requests must use the primary listener. ### Layer 3 Inner Sandbox Network Namespace diff --git a/crates/openshell-server/src/gateway_listener.rs b/crates/openshell-server/src/gateway_listener.rs index b42069d848..4e4c7e80d0 100644 --- a/crates/openshell-server/src/gateway_listener.rs +++ b/crates/openshell-server/src/gateway_listener.rs @@ -103,7 +103,7 @@ fn gateway_listener_specs_with_default_route_ip( continue; }; validate_gateway_listener_requirement(bind_address, requirement)?; - add_callback_listener_spec(&mut specs, *address, requirement)?; + add_callback_listener_spec(&mut specs, *address, requirement); } for requirement in requirements { @@ -127,7 +127,7 @@ fn gateway_listener_specs_with_default_route_ip( } let address = SocketAddr::new(ip, bind_address.port()); validate_resolved_gateway_listener(bind_address, address)?; - add_callback_listener_spec(&mut specs, address, requirement)?; + add_callback_listener_spec(&mut specs, address, requirement); } for requirement in requirements { @@ -137,7 +137,7 @@ fn gateway_listener_specs_with_default_route_ip( validate_gateway_listener_requirement(bind_address, requirement)?; let address = SocketAddr::from(([127, 0, 0, 1], bind_address.port())); validate_resolved_gateway_listener(bind_address, address)?; - add_callback_listener_spec(&mut specs, address, requirement)?; + add_callback_listener_spec(&mut specs, address, requirement); } Ok(specs) @@ -147,20 +147,17 @@ fn add_callback_listener_spec( specs: &mut Vec, address: SocketAddr, requirement: &GatewayListenerRequirement, -) -> Result<()> { +) { let scope = GatewayListenerScope::ComputeDriverCallback; if let Some(existing) = specs .iter_mut() .find(|existing| listener_covers(existing.address, address)) { + if existing.scope == GatewayListenerScope::Primary { + return; + } if existing.address == address { - if existing.scope == GatewayListenerScope::Primary { - return Err(Error::config(format!( - "compute driver '{}' requested gateway callback listener {address}, but it is the same address as the primary listener; callback-only authorization cannot be preserved", - requirement.driver_name() - ))); - } - return Ok(()); + return; } if !existing .covered_addresses @@ -171,10 +168,9 @@ fn add_callback_listener_spec( .covered_addresses .push(CoveredGatewayAddress { address, scope }); } - return Ok(()); + return; } specs.push(callback_listener_spec(address, requirement)); - Ok(()) } fn callback_listener_spec( @@ -392,8 +388,8 @@ fn listener_covers(existing: SocketAddr, requested: SocketAddr) -> bool { #[cfg(test)] mod tests { use super::{ - CoveredGatewayAddress, GatewayListenerProvenance, GatewayListenerScope, - GatewayListenerSpec, bind_gateway_listeners, gateway_listener_specs, + GatewayListenerProvenance, GatewayListenerScope, GatewayListenerSpec, + bind_gateway_listeners, gateway_listener_specs, gateway_listener_specs_with_default_route_ip, }; use crate::compute::GatewayListenerRequirement; @@ -402,7 +398,7 @@ mod tests { use tokio::net::TcpListener; #[test] - fn gateway_listener_specs_track_driver_address_covered_by_wildcard() { + fn gateway_listener_specs_reuse_primary_when_wildcard_covers_driver_address() { let primary: SocketAddr = "0.0.0.0:8080".parse().unwrap(); let docker: SocketAddr = "172.18.0.1:8080".parse().unwrap(); let requirements = [ @@ -412,20 +408,12 @@ mod tests { assert_eq!( gateway_listener_specs(primary, &requirements).unwrap(), - vec![GatewayListenerSpec { - address: primary, - scope: GatewayListenerScope::Primary, - covered_addresses: vec![CoveredGatewayAddress { - address: docker, - scope: GatewayListenerScope::ComputeDriverCallback, - }], - provenance: None, - }] + vec![primary_listener_spec(primary)] ); } #[test] - fn gateway_listener_scope_for_local_addr_uses_covered_address_scope() { + fn gateway_listener_scope_for_reused_primary_remains_primary() { let primary: SocketAddr = "0.0.0.0:8080".parse().unwrap(); let docker: SocketAddr = "172.18.0.1:8080".parse().unwrap(); let loopback: SocketAddr = "127.0.0.1:8080".parse().unwrap(); @@ -436,7 +424,7 @@ mod tests { assert_eq!( spec.scope_for_local_addr(docker), - GatewayListenerScope::ComputeDriverCallback, + GatewayListenerScope::Primary, ); assert_eq!( spec.scope_for_local_addr(loopback), @@ -521,14 +509,14 @@ mod tests { } #[test] - fn gateway_listener_specs_track_podman_exact_when_primary_covers_it() { + fn gateway_listener_specs_reuse_primary_when_it_covers_podman_exact() { let primary: SocketAddr = "0.0.0.0:8080".parse().unwrap(); let podman_gateway: SocketAddr = "10.89.1.1:8080".parse().unwrap(); assert_eq!( gateway_listener_specs(primary, &[podman_listener_requirement(podman_gateway)],) .unwrap(), - vec![primary_listener_spec_with_covered(primary, podman_gateway,)] + vec![primary_listener_spec(primary)] ); } @@ -570,11 +558,9 @@ mod tests { } #[test] - fn gateway_listener_specs_track_default_route_when_primary_is_ipv4_wildcard() { + fn gateway_listener_specs_reuse_ipv4_wildcard_for_default_route() { let primary: SocketAddr = "0.0.0.0:8080".parse().unwrap(); let default_route_ip = "192.168.20.20".parse().unwrap(); - let callback = "192.168.20.20:8080".parse().unwrap(); - assert_eq!( gateway_listener_specs_with_default_route_ip( primary, @@ -582,7 +568,7 @@ mod tests { Some(default_route_ip), ) .unwrap(), - vec![primary_listener_spec_with_covered(primary, callback)] + vec![primary_listener_spec(primary)] ); } @@ -604,28 +590,23 @@ mod tests { } #[test] - fn gateway_listener_specs_track_podman_loopback_when_wildcard_primary_covers_it() { + fn gateway_listener_specs_reuse_wildcard_primary_for_podman_loopback() { let primary = "0.0.0.0:8080".parse().unwrap(); - let loopback = "127.0.0.1:8080".parse().unwrap(); assert_eq!( gateway_listener_specs(primary, &[podman_loopback_listener_requirement()]).unwrap(), - vec![primary_listener_spec_with_covered(primary, loopback)] + vec![primary_listener_spec(primary)] ); } #[test] - fn gateway_listener_specs_reject_callback_matching_primary_address() { + fn gateway_listener_specs_reuse_matching_primary_address() { let primary = "127.0.0.1:8080".parse().unwrap(); - let err = - gateway_listener_specs(primary, &[podman_loopback_listener_requirement()]).unwrap_err(); - - assert!( - err.to_string() - .contains("same address as the primary listener") + assert_eq!( + gateway_listener_specs(primary, &[podman_loopback_listener_requirement()]).unwrap(), + vec![primary_listener_spec(primary)] ); - assert!(err.to_string().contains("callback-only authorization")); } #[test] @@ -742,21 +723,6 @@ mod tests { } } - fn primary_listener_spec_with_covered( - address: SocketAddr, - covered_address: SocketAddr, - ) -> GatewayListenerSpec { - GatewayListenerSpec { - address, - scope: GatewayListenerScope::Primary, - covered_addresses: vec![CoveredGatewayAddress { - address: covered_address, - scope: GatewayListenerScope::ComputeDriverCallback, - }], - provenance: None, - } - } - fn callback_listener_spec( address: SocketAddr, driver_name: &str, diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index 5e75cbd678..8752b863d9 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -278,6 +278,13 @@ add `ci/values-spire.yaml` to the OpenShell release values files. | supervisor.sideloadMethod | string | `""` | How the supervisor binary is delivered into sandbox pods. Empty (default) = auto-detect from cluster version: K8s >= v1.35 -> "image-volume" (ImageVolume enabled by default; GA in v1.36) K8s < v1.35 -> "init-container" (copies via init container + emptyDir) On K8s v1.33-v1.34 with the ImageVolume feature gate manually enabled, set this to "image-volume" explicitly. | | supervisor.topology | string | `"combined"` | Supervisor pod topology for Kubernetes sandboxes. "combined" runs the current single supervisor container in the agent pod. "sidecar" runs network enforcement in a dedicated sidecar and the process supervisor as a low-capability wrapper in the agent container. | | tolerations | list | `[]` | Tolerations for the gateway pod. | +| upstreamProxy | object | `{"authAllowInsecure":false,"authSecret":{"key":"","name":""},"connectByHostname":false,"noProxy":"","url":""}` | Operator-owned corporate forward proxy for policy-approved TLS egress from Kubernetes sandboxes. The workload cannot select or override it. | +| upstreamProxy.authAllowInsecure | bool | `false` | Required when authSecret is configured because Basic auth to an HTTP proxy is cleartext. | +| upstreamProxy.authSecret.key | string | `""` | Secret key containing the proxy credential. | +| upstreamProxy.authSecret.name | string | `""` | Existing Secret in the sandbox namespace containing a user:pass value. | +| upstreamProxy.connectByHostname | bool | `false` | Last-resort option for hostname-filtering proxy ACLs. It lets the proxy resolve CONNECT targets. | +| upstreamProxy.noProxy | string | `""` | Comma-separated destinations that bypass only the corporate proxy. | +| upstreamProxy.url | string | `""` | HTTP proxy URL in http://host:port form. HTTPS-to-proxy is not supported. | | workload.allowMultiReplicaStatefulSet | bool | `false` | Allow replicaCount > 1 while rendering a StatefulSet. Prefer workload.kind=deployment for external database-backed multi-replica gateways; this override exists for operators who explicitly require StatefulSet identity or storage semantics. | | workload.kind | string | `"statefulset"` | Gateway workload controller kind. Use `statefulset` for the default SQLite database, or `deployment` when server.externalDbSecret points at an external database. | diff --git a/deploy/helm/openshell/ci/values-corporate-proxy-e2e.yaml b/deploy/helm/openshell/ci/values-corporate-proxy-e2e.yaml new file mode 100644 index 0000000000..35532440b2 --- /dev/null +++ b/deploy/helm/openshell/ci/values-corporate-proxy-e2e.yaml @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# The Kubernetes corporate-proxy e2e wrapper supplies the generated proxy URL +# and creates `openshell-e2e-proxy-auth` before Helm installs the gateway. +supervisor: + topology: sidecar + +upstreamProxy: + authSecret: + name: openshell-e2e-proxy-auth + key: proxy-auth + authAllowInsecure: true diff --git a/deploy/helm/openshell/templates/gateway-config.yaml b/deploy/helm/openshell/templates/gateway-config.yaml index 7aeaa0e4ed..40f5748df4 100644 --- a/deploy/helm/openshell/templates/gateway-config.yaml +++ b/deploy/helm/openshell/templates/gateway-config.yaml @@ -140,6 +140,24 @@ data: supervisor_sideload_method = {{ include "openshell.supervisorSideloadMethod" . | quote }} topology = {{ .Values.supervisor.topology | default "combined" | quote }} sa_token_ttl_secs = {{ .Values.server.sandboxJwt.k8sSaTokenTtlSecs | default 3600 }} + {{- if .Values.upstreamProxy.url }} + https_proxy = {{ .Values.upstreamProxy.url | quote }} + {{- end }} + {{- if .Values.upstreamProxy.noProxy }} + no_proxy = {{ .Values.upstreamProxy.noProxy | quote }} + {{- end }} + {{- if .Values.upstreamProxy.authSecret.name }} + proxy_auth_secret_name = {{ .Values.upstreamProxy.authSecret.name | quote }} + {{- end }} + {{- if .Values.upstreamProxy.authSecret.key }} + proxy_auth_secret_key = {{ .Values.upstreamProxy.authSecret.key | quote }} + {{- end }} + {{- if and .Values.upstreamProxy.authSecret.name .Values.upstreamProxy.authSecret.key }} + proxy_auth_allow_insecure = {{ .Values.upstreamProxy.authAllowInsecure }} + {{- end }} + {{- if .Values.upstreamProxy.connectByHostname }} + proxy_connect_by_hostname = true + {{- end }} {{- if .Values.server.providerTokenGrants.spiffe.enabled }} provider_spiffe_workload_api_socket_path = {{ .Values.server.providerTokenGrants.spiffe.workloadApiSocketPath | quote }} {{- end }} diff --git a/deploy/helm/openshell/tests/gateway_config_test.yaml b/deploy/helm/openshell/tests/gateway_config_test.yaml index b5774a4547..784180fcb3 100644 --- a/deploy/helm/openshell/tests/gateway_config_test.yaml +++ b/deploy/helm/openshell/tests/gateway_config_test.yaml @@ -113,6 +113,35 @@ tests: path: data["gateway.toml"] pattern: 'supervisor[_]topology\s*=' + - it: renders operator-owned upstream proxy settings under the Kubernetes driver + template: templates/gateway-config.yaml + set: + upstreamProxy.url: http://proxy.corp.example:8080 + upstreamProxy.noProxy: .svc.cluster.local,10.96.0.0/12 + upstreamProxy.authSecret.name: corporate-proxy-auth + upstreamProxy.authSecret.key: credentials + upstreamProxy.authAllowInsecure: true + upstreamProxy.connectByHostname: true + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: '(?ms)\[openshell\.drivers\.kubernetes\].*?https_proxy\s*=\s*"http://proxy\.corp\.example:8080"' + - matchRegex: + path: data["gateway.toml"] + pattern: 'proxy_auth_secret_name\s*=\s*"corporate-proxy-auth"' + - matchRegex: + path: data["gateway.toml"] + pattern: 'proxy_auth_secret_key\s*=\s*"credentials"' + - matchRegex: + path: data["gateway.toml"] + pattern: 'proxy_auth_allow_insecure\s*=\s*true' + - matchRegex: + path: data["gateway.toml"] + pattern: 'no_proxy\s*=\s*"\.svc\.cluster\.local,10\.96\.0\.0/12"' + - matchRegex: + path: data["gateway.toml"] + pattern: 'proxy_connect_by_hostname\s*=\s*true' + - it: uses the gateway built-in supervisor image by default template: templates/gateway-config.yaml asserts: diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index 9d04a9b443..4fbbf4915c 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -62,6 +62,23 @@ supervisor: # policy.binaries. processBinaryAwareNetworkPolicy: true +# -- Operator-owned corporate forward proxy for policy-approved TLS egress +# from Kubernetes sandboxes. The workload cannot select or override it. +upstreamProxy: + # -- HTTP proxy URL in http://host:port form. HTTPS-to-proxy is not supported. + url: "" + # -- Comma-separated destinations that bypass only the corporate proxy. + noProxy: "" + authSecret: + # -- Existing Secret in the sandbox namespace containing a user:pass value. + name: "" + # -- Secret key containing the proxy credential. + key: "" + # -- Required when authSecret is configured because Basic auth to an HTTP proxy is cleartext. + authAllowInsecure: false + # -- Last-resort option for hostname-filtering proxy ACLs. It lets the proxy resolve CONNECT targets. + connectByHostname: false + # -- Image pull secrets attached to gateway and helper pods. imagePullSecrets: [] # -- Override the chart name used in generated resource names. diff --git a/docs/about/installation.mdx b/docs/about/installation.mdx index 58cec98f37..e464d3da42 100644 --- a/docs/about/installation.mdx +++ b/docs/about/installation.mdx @@ -38,7 +38,7 @@ For detailed driver behavior, refer to [Sandbox Compute Drivers](/reference/sand On macOS, the install script uses Homebrew. The Homebrew package installs the `openshell` CLI, the gateway binary, and a Homebrew-managed gateway service. -The Homebrew service listens on `https://[::1]:17670` and generates a local mTLS bundle on install. The formula creates a Homebrew prefix config, such as `/opt/homebrew/var/openshell/gateway.toml`, with this IPv6 loopback default so Podman can use its separate IPv4 loopback callback listener. The gateway reads `~/.config/openshell/gateway.toml` instead when that file exists. Homebrew preserves existing prefix and user configs during upgrades. +The Homebrew service uses the gateway's built-in `127.0.0.1:17670` listener and generates a local mTLS bundle on install. The installer registers `https://localhost:17670` with the CLI so TLS uses a DNS name covered by the generated certificate. The formula creates a Homebrew prefix config, such as `/opt/homebrew/var/openshell/gateway.toml`, without overriding `bind_address`. Docker Desktop and Podman Machine reuse the primary listener for sandbox callbacks when they can reach it. The gateway reads `~/.config/openshell/gateway.toml` instead when that file exists. Homebrew preserves user-edited prefix and user configs during upgrades; it removes the IPv6 bind only from an unchanged config generated by the affected formula. The CLI reads the client bundle from `~/.config/openshell/gateways/openshell/mtls/`. diff --git a/docs/kubernetes/setup.mdx b/docs/kubernetes/setup.mdx index e342c9875c..d305cb0f8a 100644 --- a/docs/kubernetes/setup.mdx +++ b/docs/kubernetes/setup.mdx @@ -163,6 +163,7 @@ The most commonly changed values are: | `supervisor.sideloadMethod` | How the supervisor binary is delivered into sandbox pods. Leave empty to auto-detect based on cluster version: clusters running Kubernetes 1.35 or later use `image-volume` (ImageVolume GA in 1.36); older clusters use `init-container`. Set explicitly to `image-volume` on Kubernetes 1.33 or 1.34 with the ImageVolume feature gate enabled, or to `init-container` to force the legacy path on any version. | | `supervisor.topology` | Sandbox pod topology. Refer to [Topology](/kubernetes/topology). | | `supervisor.sidecar.proxyUid` | Non-root UID used when sidecar process/binary-aware network policy is disabled. The default binary-aware sidecar runs as UID 0 instead. The configured UID must not match the sandbox UID. | +| `upstreamProxy` | Operator-owned corporate HTTP forward proxy for policy-approved TLS egress. Refer to [Configure a Corporate Upstream Proxy](#configure-a-corporate-upstream-proxy). | Use a values file for repeatable deployments: @@ -198,6 +199,36 @@ server: - name: regcred ``` +## Configure a Corporate Upstream Proxy + +Configure a corporate forward proxy when sandbox TLS egress cannot dial the Internet directly. OpenShell evaluates policy and SSRF checks before it opens an HTTP CONNECT tunnel through the proxy. The proxy URL is operator-owned configuration. Sandbox environment variables cannot select, replace, or bypass it. + +Create the credential Secret in the sandbox namespace when the proxy requires Basic authentication. The Secret value uses the `user:pass` form. + +```shell +kubectl -n openshell create secret generic corporate-proxy-auth \ + --from-literal=credentials="$PROXY_USER:$PROXY_PASSWORD" +``` + +Add the proxy settings to your Helm values file. Replace the DNS suffixes and CIDRs in `noProxy` with values for your cluster. `noProxy` bypasses only the corporate proxy. OpenShell policy evaluation still applies. + +```yaml +upstreamProxy: + url: http://proxy.corp.example:8080 + noProxy: .svc,.svc.cluster.local,10.96.0.0/12,10.244.0.0/16 + authSecret: + name: corporate-proxy-auth + key: credentials + authAllowInsecure: true + +supervisor: + topology: sidecar +``` + +Use `authAllowInsecure: true` only when you accept that Basic authentication is cleartext on the connection to an `http://` proxy. The initial release supports `http://` proxy endpoints and TLS CONNECT egress. It does not support HTTPS-to-proxy, custom corporate CA bundles, or forwarding plain HTTP egress through the proxy. + +Proxy credentials require `sidecar` topology. It mounts the credential only into the dedicated network supervisor container. OpenShell rejects credential Secrets with `combined` topology because Kubernetes `fsGroup` volume permission handling can make a shared credential mount readable by the sandbox group. + ## RBAC The chart creates the following RBAC resources in the release namespace: diff --git a/docs/reference/gateway-auth.mdx b/docs/reference/gateway-auth.mdx index 2ef54de70c..1d318f109f 100644 --- a/docs/reference/gateway-auth.mdx +++ b/docs/reference/gateway-auth.mdx @@ -47,7 +47,7 @@ Set these environment variables before starting the gateway: For local access, the server certificate must be valid for the endpoint the CLI uses. Include `localhost`, `127.0.0.1`, and `::1` in the certificate SANs when users connect to a local gateway through loopback. -Package-managed local gateways generate this bundle automatically for the `openshell` gateway name. Homebrew uses `https://[::1]:17670` by default; Debian and RPM use `https://127.0.0.1:17670`. +Package-managed local gateways generate this bundle automatically for the `openshell` gateway name. Homebrew registers `https://localhost:17670`; Debian and RPM use `https://127.0.0.1:17670`. When you register a package-managed local gateway with `openshell gateway add --local --name openshell`, the CLI refreshes its mTLS bundle from the package-managed TLS directory. On Homebrew, the gateway service also mirrors the Docker sandbox client bundle into `$HOME/.local/state/openshell/homebrew/tls` before startup so Docker Desktop can bind-mount the files into sandbox containers. diff --git a/docs/reference/gateway-config.mdx b/docs/reference/gateway-config.mdx index fa55d18bd9..230ae77cee 100644 --- a/docs/reference/gateway-config.mdx +++ b/docs/reference/gateway-config.mdx @@ -31,7 +31,7 @@ Package-managed gateways do not require a TOML file. Create one at the package's The Fedora/RHEL RPM template leaves `[openshell.gateway].bind_address` unset. The gateway therefore uses its built-in `127.0.0.1:17670` primary listener. The Podman driver negotiates separate, restricted listeners for sandbox callbacks, so the primary listener does not need a wildcard address. Set `bind_address` explicitly only when clients must reach the primary multiplexed API through another interface. -The Homebrew formula creates its prefix config once with `bind_address = "[::1]:17670"`. Keeping the primary API on IPv6 loopback leaves IPv4 loopback available for Podman Machine's sandbox callback listener. A user config takes precedence, and upgrades do not overwrite either config. +The Homebrew formula creates its prefix config without setting `bind_address`, so the gateway uses its built-in `127.0.0.1:17670` primary listener. Docker Desktop and Podman Machine reuse that listener for sandbox callbacks. A user config takes precedence. Upgrades preserve user-edited configs and migrate only an unchanged prefix config generated with the affected IPv6-loopback default. ## Layout @@ -438,6 +438,32 @@ supervisor_sideload_method = "image-volume" # filesystem, and network enforcement in the agent container. "sidecar" moves # pod-level network enforcement and gateway session handling into a network sidecar. topology = "combined" +# Optional corporate HTTP forward proxy for policy-approved TLS egress. The +# sandbox workload cannot select or override these settings. Only http:// proxy +# endpoints and TLS CONNECT traffic are supported; plain HTTP egress remains +# direct. `no_proxy` bypasses only the corporate proxy, never OpenShell policy. +# https_proxy = "http://proxy.corp.example:8080" +# no_proxy = ".svc,.svc.cluster.local,10.96.0.0/12,10.244.0.0/16" +# Proxy credentials must be an existing Secret in the sandbox namespace. The +# key contains a `user:pass` value and is mounted only in the network +# supervisor container, never in workload environment or command arguments. +# proxy_auth_secret_name = "corporate-proxy-auth" +# proxy_auth_secret_key = "credentials" +# The gateway validates the Secret name/key syntax and their configuration +# relationship at startup; it does not read the Secret from the Kubernetes API. +# Kubernetes resolves the Secret when the Sandbox Pod starts. A missing key or +# Secret prevents that Pod from starting; unreadable or malformed `user:pass` +# content is validated fail-closed by the supervisor at startup and never +# falls back to direct egress. +# Proxy credential Secrets require `topology = "sidecar"`. Combined topology +# shares its credential mount with the workload and can make it readable by the +# sandbox group through Kubernetes `fsGroup` volume permission handling. +# Required with a credential Secret: Basic authentication to an http:// proxy +# is cleartext on the connection to that proxy. +# proxy_auth_allow_insecure = true +# Last resort for hostname-filtering proxy ACLs. The proxy resolves the target, +# so its ACL becomes part of the egress boundary for proxied connections. +# proxy_connect_by_hostname = true grpc_endpoint = "https://openshell-gateway.agents.svc:8080" ssh_socket_path = "/run/openshell/ssh.sock" client_tls_secret_name = "openshell-client-tls" diff --git a/docs/reference/sandbox-compute-drivers.mdx b/docs/reference/sandbox-compute-drivers.mdx index b05bf05581..189f685ff3 100644 --- a/docs/reference/sandbox-compute-drivers.mdx +++ b/docs/reference/sandbox-compute-drivers.mdx @@ -113,17 +113,15 @@ It overrides the gateway's configured default runtime class for that sandbox, while a typed `SandboxTemplate.runtime_class_name` value from the API still takes precedence. -Docker and Podman callback listeners accept only supervisor callback gRPC -methods. Use the gateway's primary endpoint for CLI, administrator, health, -reflection, inference-route management, and HTTP requests. A -`PermissionDenied` response from one of the sandbox-visible callback addresses -is expected for those requests. The gateway fails startup if a callback -requirement resolves to the exact primary listener address because one socket -cannot preserve both authorization scopes. For the IPv4-loopback callback used -by Podman Machine, set `bind_address = "[::1]:17670"` for the primary listener -and register `https://localhost:17670` as the CLI endpoint. The hostname matches -the generated certificate and avoids the TLS transport error produced by a raw -IPv6-literal endpoint. Do not broaden the primary listener to `0.0.0.0`. +Docker and Podman report the address through which their sandboxes can reach +the gateway. If the primary listener covers that address, the gateway reuses +it and sandbox JWT authentication restricts the supervisor to its callback RPC +allowlist. If the primary listener is not reachable through that address, the +gateway creates an additional callback-only listener. Use the primary endpoint +for CLI, administrator, health, reflection, inference-route management, and +HTTP requests. A `PermissionDenied` response from an additional callback-only +listener is expected for those requests. Do not broaden the primary listener +to `0.0.0.0` solely to make sandbox callbacks reachable. ## Docker Driver @@ -131,6 +129,11 @@ IPv6-literal endpoint. Do not broaden the primary listener to `0.0.0.0`. The gateway talks to the Docker daemon to create sandbox containers. Docker is also required for local image builds from directories or Dockerfiles. +Docker Desktop and compatible macOS runtimes route `host.openshell.internal` +through an IPv4 host-gateway alias. The gateway reuses an IPv4 primary listener +that already covers loopback. Otherwise, the Docker driver requests a separate +`127.0.0.1:` callback-only listener. + For maintainer-level implementation details, refer to the [Docker driver README](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-docker/README.md). Select Docker with `compute_drivers = ["docker"]` in `[openshell.gateway]`. Configure Docker driver values such as `socket_path`, `grpc_endpoint`, `network_name`, `supervisor_bin`, `supervisor_image`, `image_pull_policy`, `ssh_socket_path`, `sandbox_pids_limit`, and `guest_tls_*` in `[openshell.drivers.docker]`. When `socket_path` is unset, the driver uses the same responsive local socket selected by auto-detection. An explicitly selected Docker driver falls back to `/var/run/docker.sock` when no candidate responds. @@ -343,6 +346,12 @@ For maintainer-level implementation details, refer to the [Kubernetes driver REA | `supervisor_image_pull_policy` | `supervisor.image.pullPolicy` | Set the Kubernetes image pull policy for the supervisor image. | | `supervisor_sideload_method` | `supervisor.sideloadMethod` | How the supervisor binary is delivered into sandbox pods. Leave empty to auto-detect from cluster version. Set to `image-volume` to mount the supervisor OCI image directly as a volume (requires Kubernetes 1.33+ with the ImageVolume feature gate; GA in 1.36), or `init-container` to copy it through an init container on older clusters. | | `topology` | `supervisor.topology` | Set `combined` for the default single supervisor path, or `sidecar` to move pod-level network enforcement and the gateway session into a dedicated sidecar. | +| `https_proxy` | `upstreamProxy.url` | Set the operator-owned `http://host:port` corporate forward proxy used for policy-approved TLS CONNECT egress. | +| `no_proxy` | `upstreamProxy.noProxy` | Set destinations that bypass only the corporate proxy. OpenShell policy evaluation still applies. | +| `proxy_auth_secret_name` | `upstreamProxy.authSecret.name` | Set the existing Secret name in the sandbox namespace that contains the proxy credential. Requires `sidecar` topology. | +| `proxy_auth_secret_key` | `upstreamProxy.authSecret.key` | Set the Secret key containing the `user:pass` credential. Requires `sidecar` topology. | +| `proxy_auth_allow_insecure` | `upstreamProxy.authAllowInsecure` | Set `true` to acknowledge that Basic authentication to an HTTP proxy is cleartext. Required with a proxy credential Secret. | +| `proxy_connect_by_hostname` | `upstreamProxy.connectByHostname` | Send hostnames rather than validated IPs in CONNECT requests. Use only when proxy ACLs require hostname targets. | | `sidecar.proxy_uid` | `supervisor.sidecar.proxyUid` | Non-root UID used by the relaxed sidecar when process/binary-aware network policy is disabled. The default binary-aware sidecar runs as UID 0. The network init container exempts the effective sidecar UID from proxy redirection. | | `sidecar.process_binary_aware_network_policy` | `supervisor.sidecar.processBinaryAwareNetworkPolicy` | Keep process/binary-aware network policy enabled in `sidecar` topology. The default runs the sidecar as UID 0 with `SYS_PTRACE` and `DAC_READ_SEARCH`. Set false to run as `proxy_uid`, drop both capabilities, and enforce endpoint/L7 policy without matching `policy.binaries`. | | `app_armor_profile` | `server.appArmorProfile` | Set the sandbox agent container's AppArmor profile. Helm defaults this to `Unconfined` so AppArmor-enabled nodes do not block supervisor network namespace setup. Set the Helm value to an empty string to omit the field, or use `RuntimeDefault` or `Localhost/` for operator-managed profiles. | diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index 76881d1f5e..e2bc94d81d 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -89,6 +89,11 @@ name = "readyz_health" path = "tests/readyz_health.rs" required-features = ["e2e-kubernetes"] +[[test]] +name = "kubernetes_corporate_proxy" +path = "tests/kubernetes_corporate_proxy.rs" +required-features = ["e2e-kubernetes"] + [[test]] name = "credential_drivers" path = "tests/credential_drivers.rs" diff --git a/e2e/rust/src/harness/container.rs b/e2e/rust/src/harness/container.rs index 764ee6d0f6..eb24aac1e7 100644 --- a/e2e/rust/src/harness/container.rs +++ b/e2e/rust/src/harness/container.rs @@ -197,6 +197,115 @@ pub struct SupportContainer { engine: ContainerEngine, } +/// A TCP fixture published on the test host for Kubernetes sandbox e2e tests. +/// +/// Kubernetes sandboxes reach it through the chart-provided +/// `host.openshell.internal` alias. Unlike [`SupportContainer`], this does not +/// require the Docker e2e network used by local-container driver tests. +pub struct HostSupportContainer { + pub port: u16, + container_id: String, + engine: ContainerEngine, +} + +impl HostSupportContainer { + /// Start a Python fixture and publish `container_port` on a free host port. + pub async fn start_python(script: &str, container_port: u16) -> Result { + Self::start_python_on_host_port(script, container_port, find_free_port()).await + } + + /// Start a Python fixture on a caller-selected host port. + /// + /// Use this when the fixture endpoint must be known before the Helm chart + /// starts the gateway, such as the configured corporate forward proxy. + pub async fn start_python_on_host_port( + script: &str, + container_port: u16, + port: u16, + ) -> Result { + let engine = ContainerEngine::from_env()?; + let output = engine + .command() + .args([ + "run", + "--detach", + "--entrypoint", + "python3", + "-p", + &format!("{port}:{container_port}"), + DEFAULT_TEST_SERVER_IMAGE, + "-c", + script, + ]) + .output() + .map_err(|err| format!("start {} host fixture: {err}", engine.name()))?; + if !output.status.success() { + return Err(format!( + "{} run failed (exit {:?}):\n{}", + engine.name(), + output.status.code(), + String::from_utf8_lossy(&output.stderr) + )); + } + let fixture = Self { + port, + container_id: String::from_utf8_lossy(&output.stdout).trim().to_string(), + engine, + }; + fixture.wait_until_listening(container_port).await?; + Ok(fixture) + } + + async fn wait_until_listening(&self, container_port: u16) -> Result<(), String> { + let deadline = timeout(Duration::from_secs(60), async { + let mut tick = interval(Duration::from_millis(500)); + loop { + tick.tick().await; + let output = self + .engine + .command() + .args(["exec", &self.container_id, "python3", "-c", &format!("import socket; socket.create_connection(('127.0.0.1', {container_port}), timeout=1).close()")]) + .output() + .ok(); + if output.is_some_and(|output| output.status.success()) { + return; + } + } + }) + .await; + deadline.map_err(|_| { + format!( + "host fixture did not listen within 60s. Logs:\n{}", + self.logs().unwrap_or_else(|err| err) + ) + }) + } + + pub fn logs(&self) -> Result { + let output = self + .engine + .command() + .args(["logs", &self.container_id]) + .output() + .map_err(|err| format!("read {} fixture logs: {err}", self.engine.name()))?; + Ok(format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + )) + } +} + +impl Drop for HostSupportContainer { + fn drop(&mut self) { + let _ = self + .engine + .command() + .args(["rm", "-f", &self.container_id]) + .output(); + } +} + impl SupportContainer { /// Start a `python3 -c