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
6 changes: 6 additions & 0 deletions crates/openshell-core/src/app_listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

/// Gateway browser credentials are reserved on both application access paths.
pub fn is_gateway_service_auth_cookie(name: &[u8]) -> bool {
name.eq_ignore_ascii_case(b"__Host-openshell-service-session")
|| name.eq_ignore_ascii_case(b"__Host-openshell-service-login")
}

/// Explicitly enabled application ingress. Deployment details such as TLS
/// Secret names belong to the driver, not to this common configuration.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
Expand Down
63 changes: 63 additions & 0 deletions crates/openshell-core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,13 @@ pub struct Config {
pub struct ServiceRoutingConfig {
/// Publish gateway URLs and forward application requests through the gateway.
pub enabled: bool,
/// Opt in to gateway authentication for proxied application requests.
/// Independent of the supervisor application listener.
pub enable_gateway_service_auth: bool,
/// Exact trusted HTTPS control-plane origins for browser service login.
/// Empty disables browser login without affecting bearer or mTLS access.
pub service_auth_login_origins: Vec<String>,

/// Base domains accepted for `sandbox--service.<domain>` routes.
/// The first domain is used when the gateway prints endpoint URLs.
pub base_domains: Vec<String>,
Expand Down Expand Up @@ -573,6 +580,23 @@ impl ServiceRoutingConfig {
/// deploying platform is responsible for, since a single gateway cannot
/// observe its siblings.
pub fn validate(&self, installation_name: &str) -> crate::error::Result<()> {
for value in &self.service_auth_login_origins {
let valid = url::Url::parse(value).is_ok_and(|origin| {
origin.scheme() == "https"
&& origin.host_str().is_some_and(|host| !host.contains('*'))
&& origin.username().is_empty()
&& origin.password().is_none()
&& origin.path() == "/"
&& origin.query().is_none()
&& origin.fragment().is_none()
&& origin.port() != Some(0)
});
if !valid {
return Err(crate::error::Error::Config {
message: "service_auth_login_origins must contain HTTPS origins without credentials, paths, queries, or fragments".into(),
});
}
}
if self.service_hostname_format == ServiceHostnameFormat::Hashed
&& !is_dns_label(installation_name)
{
Expand Down Expand Up @@ -1583,6 +1607,13 @@ impl Config {
self
}

/// Opt in to configured gateway authentication on application requests.
#[must_use]
pub const fn with_service_auth(mut self, enabled: bool) -> Self {
self.service_routing.enable_gateway_service_auth = enabled;
self
}

/// Enable or disable plaintext HTTP routing for loopback sandbox service
/// hostnames on TLS-enabled gateway listeners.
#[must_use]
Expand All @@ -1603,6 +1634,8 @@ impl Default for ServiceRoutingConfig {
fn default() -> Self {
Self {
enabled: true,
enable_gateway_service_auth: false,
service_auth_login_origins: Vec::new(),
base_domains: default_service_routing_domains(),
enable_loopback_service_http: default_enable_loopback_service_http(),
service_hostname_format: ServiceHostnameFormat::default(),
Expand Down Expand Up @@ -2174,6 +2207,30 @@ mod tests {
);
}

#[test]
fn browser_service_login_requires_exact_https_origins() {
let mut config = super::ServiceRoutingConfig::default();
assert!(config.service_auth_login_origins.is_empty());
for invalid in [
"http://gateway.example.com",
"https://*.example.com",
"https://user:password@gateway.example.com",
"https://gateway.example.com/login",
"https://gateway.example.com?query=1",
"https://gateway.example.com#fragment",
"https://gateway.example.com:0",
"not-an-origin",
] {
config.service_auth_login_origins = vec![invalid.into()];
assert!(config.validate("gateway").is_err());
}
config.service_auth_login_origins = vec![
"https://gateway.example.com".into(),
"https://127.0.0.1:8443".into(),
];
config.validate("gateway").unwrap();
}

#[test]
fn service_routing_allows_loopback_plaintext_http_by_default() {
let cfg = Config::new(None);
Expand All @@ -2182,6 +2239,12 @@ mod tests {
vec![DEFAULT_SERVICE_ROUTING_DOMAIN.to_string()]
);
assert!(cfg.service_routing.enable_loopback_service_http);
assert!(!cfg.service_routing.enable_gateway_service_auth);
assert!(
cfg.with_service_auth(true)
.service_routing
.enable_gateway_service_auth
);
}

#[test]
Expand Down
3 changes: 2 additions & 1 deletion crates/openshell-credential-issuer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,10 @@ This is the internal-refactoring increment of RFC phase 2, not remote readiness.

## Owners and compatibility

`SecretOwner` scopes each operation to a workspace and one of three kinds:
`SecretOwner` scopes each operation to a workspace and one of four kinds:

- `Provider`: the existing provider UUID and name.
- `ApplicationSession`: the gateway browser session storage identity (`service-session-<session ID>`), using the existing `gateway-service-session` driver scope.
- `Sandbox`: the sandbox UUID for its SSH host identity.
- `SupervisorInstance`: the sandbox UUID owning a launch-material assignment, not the shared supervisor route or host.

Expand Down
20 changes: 20 additions & 0 deletions crates/openshell-credential-issuer/src/owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ pub enum SecretOwnerKind<'a> {
Sandbox {
id: &'a str,
},
/// Gateway-owned browser application session storage identity.
ApplicationSession {
id: &'a str,
},
/// Launch material is owned by a sandbox assignment, not the host/route.
SupervisorInstance {
sandbox_id: &'a str,
Expand Down Expand Up @@ -65,9 +69,20 @@ impl<'a> SecretOwner<'a> {
}
}

/// `id` is the existing `service-session-<session ID>` storage identity.
pub fn application_session(workspace: &'a str, id: &'a str) -> Self {
Self {
workspace,
kind: SecretOwnerKind::ApplicationSession { id },
}
}

pub(crate) fn legacy_scope(self) -> LegacyScope<'a> {
let (provider, id) = match self.kind {
SecretOwnerKind::Provider { id, name } => (Cow::Borrowed(name), id),
SecretOwnerKind::ApplicationSession { id } => {
(Cow::Borrowed("gateway-service-session"), id)
}
SecretOwnerKind::Sandbox { id } => (Cow::Owned(format!("sandbox-ssh-{id}")), id),
SecretOwnerKind::SupervisorInstance { sandbox_id } => (
Cow::Owned(format!("sandbox-instance-{sandbox_id}")),
Expand Down Expand Up @@ -97,6 +112,11 @@ mod tests {
"provider-name",
"provider-id",
),
(
SecretOwner::application_session("workspace-a", "service-session-session-id"),
"gateway-service-session",
"service-session-session-id",
),
(
SecretOwner::sandbox("workspace-a", "sandbox-id"),
"sandbox-ssh-sandbox-id",
Expand Down
47 changes: 47 additions & 0 deletions crates/openshell-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,53 @@ must independently honor the advertised lease expiry.
Reconnect and relist on stream termination; revisions are opaque
equality tokens, not resumable cursors or an ordering across gateway replicas.

## Gateway application authentication

Gateway service authentication defaults to disabled, independently of the app
listener. Disabled mode preserves application routing, reserved-looking paths,
and the pre-existing header/cookie policy. CLI `--enable-gateway-service-auth` and
`OPENSHELL_ENABLE_GATEWAY_SERVICE_AUTH` override the TOML setting.

With `[openshell.gateway].enable_gateway_service_auth = true`, gateway-mediated
application HTTP requests and WebSocket upgrades authenticate
through the gateway chain or verified TLS client identity before endpoint lookup,
independently of app-listener enablement. User access requires TCP-forwarding
role/scope policy (`sandbox:write` when enforced) and current workspace membership;
operators retain their platform grant. Internal principals are rejected. Only
explicit local-development unauthenticated access bypasses this gate.

`/auth/services` hosts browser login on an exact control-plane origin allowed by
`[openshell.gateway].service_auth_login_origins`. The empty default disables
browser login without affecting bearer or mTLS application access. The application
origin receives a single-use bootstrap code bound to a browser login nonce, then
a distinct host-only, Secure/HttpOnly session cookie. Shared metadata contains
only credential-driver handles and hashes; the configured credential driver
stores the access token. Login codes expire after two minutes, sessions after
at most ten minutes or token expiry. Every request revalidates the token and
workspace authorization. Session deletion, credential revocation, and redemption
CAS use the shared database. Redemption atomically replaces the pending record
without consuming another session slot. Admission is per authenticated principal:
1,024 sessions and 12 login attempts per rolling minute, enforced in the shared
store. A paginated background reaper retires expired sessions, credential secrets,
and revocations on a ten-second cadence. WebSockets close at session/credential
expiry and check shared revocation state every five seconds with a two-second
check timeout.
The application path consumes standard gateway bearer headers, or authenticates
through a separate `X-OpenShell-Authorization`, browser session, or mTLS identity
while preserving application bearer passthrough and cookies. Gateway headers and
reserved cookies never reach the workload, and workloads cannot set reserved
browser auth cookies. Browser ambient credentials require origin checks for
unsafe methods and WebSocket upgrades. Direct supervisor ingress delegates
application authentication to its ingress provider.

The optional real-Chrome login test uses an isolated profile and local test
credentials. Run it with `OPENSHELL_BROWSER_E2E_CHROME` pointing to Chrome:

```shell
OPENSHELL_BROWSER_E2E_CHROME='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' \
mise run test:gateway-service-auth:browser
```

## Application URL publication

See [Supervisor application listener](../../docs/how-it-works/gateways/configuration.mdx#supervisor-application-listener)
Expand Down
21 changes: 20 additions & 1 deletion crates/openshell-server/src/auth/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,16 @@ fn sanitize_callback_host(raw: &Option<String>) -> (String, String) {

/// Create the auth router.
pub fn router(state: Arc<ServerState>) -> Router {
Router::new()
let mut router = Router::new();
if state.config.service_routing.enabled
&& state.config.service_routing.enable_gateway_service_auth
{
router = router.route(
"/auth/services",
get(service_browser_login).post(service_browser_login),
);
}
router
.route("/auth/connect", get(auth_connect))
.route("/auth/oidc-config", get(oidc_config_handler))
.route("/.well-known/jwks.json", get(gateway_jwks_handler))
Expand All @@ -101,6 +110,16 @@ pub fn router(state: Arc<ServerState>) -> Router {
.with_state(state)
}

async fn service_browser_login(
State(state): State<Arc<ServerState>>,
req: axum::extract::Request,
) -> axum::response::Response {
match super::service_session::control(&state, req).await {
Ok(response) => response,
Err(error) => super::service_session::error(&error),
}
}

/// Publish OIDC-shaped discovery metadata for extension services.
///
/// This lets an extension be configured with only the trusted gateway URL:
Expand Down
2 changes: 2 additions & 0 deletions crates/openshell-server/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ pub mod principal;
pub mod sandbox_jwt;
pub mod sandbox_methods;
pub mod sandbox_session;
pub mod service_access;
pub mod service_session;
pub mod supervisor_token;
pub mod workspace_authz;

Expand Down
Loading
Loading