Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .agents/skills/generate-sandbox-policy/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,7 @@ Before presenting the policy to the user, verify correctness **and** flag breadt
- [ ] Middleware `order` values are unique and no selected chain exceeds 10 stages
- [ ] No fail-closed middleware selector can cover a `tls: skip` endpoint
- [ ] Any required WebSocket control advertises `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`, and the user understands that V1 does not inspect binary messages
- [ ] Endpoints contributed by a credentialed provider are not L4-only or `tls: skip` unless `allow_uninspected_credentials: true` explicitly records the exception

### Schema Warnings (log-only, but should be fixed)

Expand Down Expand Up @@ -418,6 +419,7 @@ Evaluate the generated policy for overly broad access and **include warnings in
| **Broad CIDR** in `allowed_ips` (e.g., `10.0.0.0/8`) | "This `allowed_ips` entry covers a very broad range. Consider narrowing to a specific subnet (e.g., `10.0.5.0/24`) to minimize exposure." |
| **`on_error: fail_open`** | "This middleware can be bypassed when it is unavailable, rejects configuration, returns an invalid result, or exceeds its body limit. Use `fail_closed` unless availability is more important than this control." |
| **Broad middleware host selector** | "This middleware attaches independently of the admitting network rule to every matching destination, then runs only for operation bindings its implementation advertises. Narrow `endpoints.include` or add exclusions if the attachment is not required for every matching host." |
| **`allow_uninspected_credentials: true`** | "This endpoint may carry provider credentials on traffic OpenShell cannot inspect or rewrite. Prefer an inspected protocol and credential rewrite; keep this exception only when raw traffic is required." |

Format breadth warnings clearly in the output, e.g.:

Expand Down
1 change: 1 addition & 0 deletions .agents/skills/openshell-cli/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,7 @@ Incrementally merge live network policy changes into the current sandbox policy.
Notes:

- The sandbox name defaults to the last-used sandbox.
- `--add-endpoint` options are comma-separated: `allowed-ip=<CIDR-or-IP>`, `websocket-credential-rewrite`, `request-body-credential-rewrite`, and `allow-uninspected-credentials`. The last option is a security-sensitive exception for provider-credentialed L4-only, `tls: skip`, or otherwise uninspectable traffic.
- `--add-allow` and `--add-deny` operate on REST and WebSocket endpoints. Use full YAML for JSON-RPC, MCP, SQL, or other policy structure.
- `--wait` cannot be combined with `--dry-run`.
- Use `policy set` when replacing the full policy or changing static sections.
Expand Down
2 changes: 1 addition & 1 deletion architecture/gateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ Supported auth modes:
| Plaintext | Local development or a trusted reverse proxy boundary. |
| Unauthenticated local users | Trusted Kubernetes dev or fully trusted proxy deployments only. |
| Cloudflare JWT | Edge-authenticated deployments where Cloudflare Access supplies identity. |
| OIDC | Bearer-token auth for users, with browser PKCE or client credentials login. |
| OIDC | Bearer-token auth for users, with browser or device-code PKCE and client credentials login. |

The CLI persists the scopes requested during OIDC login in gateway metadata and
reuses them when refreshing an access token. This preserves the intended API
Expand Down
64 changes: 64 additions & 0 deletions architecture/security-policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,70 @@ raw relay by default. A `protocol: rest` endpoint can opt in to
after an allowed `101` upgrade; server-to-client traffic and all other upgraded
protocols remain raw passthrough.

## Credentialed Endpoints

OpenShell keeps provider credentials on paths it can inspect or rewrite by
default. The gateway derives credential provenance from the attached providers
and stamps it onto the effective policy at composition time. This provenance is
internal, contains no credential identifiers or values, and is never trusted
from user-authored policy.

Every evaluation clears provenance across the whole policy and re-derives it
from two sources:

- the endpoints of attached provider profiles that carry credentials, and
- the valid `credential_binding` entries of the sandbox policy that name an
attached provider whose profile is endpointless.

A binding reduces to a host and port scope only. Dropping the path is
deliberate: a path is not observable on an L4 or `tls: skip` endpoint, so a
path-scoped derivation would omit the marker on exactly the surfaces the
uninspected-credential gate exists to catch. A malformed binding — empty
provider, missing host, or a port outside `1..=65535` — fails the evaluation
instead of contributing a scope. Bindings naming an endpointful profile or an
unattached provider contribute nothing; the gateway rejects those uses
separately.

Both sources merge into one deduplicated scope set, and each endpoint is
stamped once per evaluation from that set, so binding-derived scopes reach the
same gates as profile-derived ones. The stamp is an assignment, not an
accumulation, so an endpoint that stops matching a credentialed scope — or
whose binding was removed — loses its marker in the same pass. This must remain
a full recomputation: a delta-based derivation would let a series of
individually valid edits reach a state no single edit would have admitted.

Credentialed L4-only and `tls: skip` endpoints fail policy validation unless the
public `allow_uninspected_credentials` escape hatch is explicitly enabled. The
flag defaults to `false` and is security-flagged in policy approval flows.
Incremental merges only ever add the flag to a matching endpoint; clearing it
requires removing the endpoint or replacing the policy.

The network supervisor independently enforces the same boundary. Credentialed
WebSocket upgrades use the parsed relay, binary frames fail closed, and text
placeholders require rewrite. REST bodies can continue streaming when body
rewrite is disabled, but the relay withholds enough trailing bytes to detect a
placeholder split across reads before forwarding its marker. Explicitly opted-in
endpoints retain raw passthrough behavior.

Denials emit both the relevant network activity and a detection finding. Events
identify only the destination, policy, and traffic surface; they never include
credential names, placeholders, body content, or secret values.

Credential provenance is gateway-derived and deliberately absent from the policy
YAML schema, so it does not survive a policy that never transits the gateway.
Gateway-delivered policy is the authoritative source for this control, and a
policy without provenance applies neither the raw-tunnel refusal nor the
WebSocket binary-frame refusal. The request-body backstop still applies, because
it keys off the presence of a secret resolver rather than endpoint provenance.

Two paths load a policy without provenance. A supervisor booting from a
container-image policy is a bounded window: that policy is resynchronized to the
gateway, which then serves a stamped effective policy. An explicit local Rego and
data override is permanent, because gateway revisions are observed for settings
and providers but never replace the local policy. When that override is combined
with injected provider credentials, the supervisor emits a high-severity
detection finding at startup naming the inactive controls.

## Live Updates

The gateway stores sandbox-authored policy revisions separately from derived
Expand Down
65 changes: 65 additions & 0 deletions crates/openshell-bootstrap/src/oidc_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ pub fn oidc_token_path(gateway_name: &str) -> Result<PathBuf> {
Ok(user_gateway_dir(gateway_name)?.join("oidc_token.json"))
}

/// Path to the one-shot marker that asks the next browser login to prompt.
pub fn oidc_login_prompt_required_path(gateway_name: &str) -> Result<PathBuf> {
Ok(user_gateway_dir(gateway_name)?.join("oidc_login_prompt_required"))
}

/// Store an OIDC token bundle for a gateway.
pub fn store_oidc_token(gateway_name: &str, bundle: &OidcTokenBundle) -> Result<()> {
let path = oidc_token_path(gateway_name)?;
Expand All @@ -50,6 +55,7 @@ pub fn store_oidc_token(gateway_name: &str, bundle: &OidcTokenBundle) -> Result<
.into_diagnostic()
.wrap_err_with(|| format!("failed to write OIDC token to {}", path.display()))?;
set_file_owner_only(&path)?;
clear_oidc_login_prompt(gateway_name)?;
Ok(())
}

Expand All @@ -76,6 +82,33 @@ pub fn remove_oidc_token(gateway_name: &str) -> Result<()> {
Ok(())
}

/// Mark the next interactive OIDC login as requiring a fresh `IdP` prompt.
pub fn request_oidc_login_prompt(gateway_name: &str) -> Result<()> {
let path = oidc_login_prompt_required_path(gateway_name)?;
ensure_parent_dir_restricted(&path)?;
std::fs::write(&path, b"1\n")
.into_diagnostic()
.wrap_err_with(|| format!("failed to write {}", path.display()))?;
set_file_owner_only(&path)?;
Ok(())
}

/// Return whether the next interactive OIDC login should request a fresh prompt.
pub fn oidc_login_prompt_required(gateway_name: &str) -> bool {
oidc_login_prompt_required_path(gateway_name).is_ok_and(|path| path.exists())
}

/// Clear the one-shot fresh-login marker for a gateway.
pub fn clear_oidc_login_prompt(gateway_name: &str) -> Result<()> {
let path = oidc_login_prompt_required_path(gateway_name)?;
if path.exists() {
std::fs::remove_file(&path)
.into_diagnostic()
.wrap_err_with(|| format!("failed to remove {}", path.display()))?;
}
Ok(())
}

/// Check if the stored access token is expired or near expiry.
///
/// Returns `true` if the token expires within the next 30 seconds.
Expand Down Expand Up @@ -129,4 +162,36 @@ mod tests {
assert!(remove_oidc_token("../escape").is_err());
});
}

#[test]
fn oidc_login_prompt_marker_is_per_gateway() {
let tmp = tempfile::tempdir().unwrap();
with_tmp_xdg(tmp.path(), || {
assert!(!oidc_login_prompt_required("alpha"));
assert!(!oidc_login_prompt_required("beta"));

request_oidc_login_prompt("alpha").unwrap();

assert!(oidc_login_prompt_required("alpha"));
assert!(!oidc_login_prompt_required("beta"));

let bundle = OidcTokenBundle {
access_token: "token".to_string(),
refresh_token: None,
expires_at: None,
issuer: "https://issuer.example.com".to_string(),
client_id: "openshell-cli".to_string(),
};
store_oidc_token("alpha", &bundle).unwrap();

assert!(!oidc_login_prompt_required("alpha"));

request_oidc_login_prompt("alpha").unwrap();
assert!(oidc_login_prompt_required("alpha"));

clear_oidc_login_prompt("alpha").unwrap();

assert!(!oidc_login_prompt_required("alpha"));
});
}
}
38 changes: 38 additions & 0 deletions crates/openshell-cli/src/commands/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -905,13 +905,34 @@ pub async fn gateway_add(
false
}
}
} else if is_browser_suppressed() {
match crate::oidc_auth::oidc_device_code_flow(
issuer,
oidc_client_id,
oidc_audience,
oidc_scopes,
gateway_insecure,
)
.await
{
Ok(bundle) => {
openshell_bootstrap::oidc_token::store_oidc_token(name, &bundle)?;
eprintln!("{} Authenticated via device code", "✓".green().bold());
true
}
Err(e) => {
eprintln!("{} Authentication failed: {e}", "!".yellow());
false
}
}
} else {
match crate::oidc_auth::oidc_browser_auth_flow(
issuer,
oidc_client_id,
oidc_audience,
oidc_scopes,
gateway_insecure,
false,
)
.await
{
Expand Down Expand Up @@ -1116,6 +1137,8 @@ pub async fn gateway_login(name: &str, gateway_insecure: bool) -> Result<()> {
.unwrap_or("openshell-cli");
let audience = metadata.oidc_audience.as_deref();
let scopes = metadata.oidc_scopes.as_deref();
let force_fresh_login =
openshell_bootstrap::oidc_token::oidc_login_prompt_required(name);

let bundle = if std::env::var("OPENSHELL_OIDC_CLIENT_SECRET").is_ok() {
crate::oidc_auth::oidc_client_credentials_flow(
Expand All @@ -1126,19 +1149,30 @@ pub async fn gateway_login(name: &str, gateway_insecure: bool) -> Result<()> {
gateway_insecure,
)
.await?
} else if is_browser_suppressed() {
crate::oidc_auth::oidc_device_code_flow(
issuer,
client_id,
audience,
scopes,
gateway_insecure,
)
.await?
} else {
crate::oidc_auth::oidc_browser_auth_flow(
issuer,
client_id,
audience,
scopes,
gateway_insecure,
force_fresh_login,
)
.await?
};

let username = jwt_preferred_username(&bundle.access_token);
openshell_bootstrap::oidc_token::store_oidc_token(name, &bundle)?;
openshell_bootstrap::oidc_token::clear_oidc_login_prompt(name)?;

if let Some(user) = username {
eprintln!(
Expand Down Expand Up @@ -1184,6 +1218,7 @@ pub fn gateway_logout(name: &str) -> Result<()> {
match metadata.auth_mode.as_deref() {
Some("oidc") => {
openshell_bootstrap::oidc_token::remove_oidc_token(name)?;
openshell_bootstrap::oidc_token::request_oidc_login_prompt(name)?;
}
Some("cloudflare_jwt") => {
openshell_bootstrap::edge_token::remove_edge_token(name)?;
Expand Down Expand Up @@ -1430,6 +1465,9 @@ fn remove_gateway_registration(name: &str) {
if let Err(err) = openshell_bootstrap::oidc_token::remove_oidc_token(name) {
tracing::debug!("failed to remove oidc token: {err}");
}
if let Err(err) = openshell_bootstrap::oidc_token::clear_oidc_login_prompt(name) {
tracing::debug!("failed to clear oidc login prompt marker: {err}");
}
if let Err(err) = remove_gateway_metadata(name) {
tracing::debug!("failed to remove gateway metadata: {err}");
}
Expand Down
9 changes: 7 additions & 2 deletions crates/openshell-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1172,7 +1172,8 @@ enum GatewayCommands {
/// Authenticate with an edge-authenticated or OIDC gateway.
///
/// Opens a browser for the edge proxy's login flow and stores the
/// token locally. Use this to re-authenticate when a token expires.
/// token locally. After `gateway logout`, OIDC browser login requests a
/// fresh identity-provider prompt so you can switch users.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Login {
/// Gateway name (defaults to the active gateway).
Expand All @@ -1183,7 +1184,9 @@ enum GatewayCommands {
/// Clear stored authentication credentials for a gateway.
///
/// Removes the locally stored OIDC token or edge token so subsequent
/// commands require re-authentication via `gateway login`.
/// commands require re-authentication via `gateway login`. For OIDC
/// gateways, the next browser login asks the identity provider for a fresh
/// login instead of silently reusing an existing browser session.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Logout {
/// Gateway name (defaults to the active gateway).
Expand Down Expand Up @@ -1791,6 +1794,8 @@ enum PolicyCommands {
name: Option<String>,

/// Add or merge an endpoint: host:port[:access[:protocol[:enforcement[:options]]]].
/// Options include allowed-ip=..., credential rewrite flags, and
/// allow-uninspected-credentials.
#[arg(long = "add-endpoint")]
add_endpoints: Vec<String>,

Expand Down
Loading
Loading