From e6dbc5dd7963dc9f41e53b477ead3ccaeb080b96 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Wed, 2 Dec 2026 00:21:15 +0000 Subject: [PATCH] fix: let external jwt viewers render sandboxed apps (#12807) * fix: let external jwt viewers render sandboxed apps Co-Authored-By: Claude Opus 5.5 * fix: refuse archived workspaces and document the external jwt expiry Co-Authored-By: Claude Opus 5.5 * chore: update ee-repo-ref to 7791f1156fc04d7804548ad131f44880399d8de2 This commit updates the EE repository reference after PR #1041 was merged in windmill-ee-private. Previous ee-repo-ref: a4e2c5f2489b8b7389d393b0b5c1c4667ce227fd New ee-repo-ref: 7791f1156fc04d7804548ad131f44880399d8de2 Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: windmill-internal-app[bot] --- backend/ee-repo-ref.txt | 2 +- backend/tests/app_render_ext_jwt_viewer.rs | 122 ++++++++++++++----- backend/windmill-api-auth/src/lib.rs | 7 +- backend/windmill-api/src/apps.rs | 131 ++++++++++++++++++--- 4 files changed, 214 insertions(+), 48 deletions(-) diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 38db68c3ce..24288274a4 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -ae0aad4eb1f18c6d51150600579efec910480947 +7791f1156fc04d7804548ad131f44880399d8de2 diff --git a/backend/tests/app_render_ext_jwt_viewer.rs b/backend/tests/app_render_ext_jwt_viewer.rs index 11d005f2ec..5c283afc42 100644 --- a/backend/tests/app_render_ext_jwt_viewer.rs +++ b/backend/tests/app_render_ext_jwt_viewer.rs @@ -1,7 +1,8 @@ //! A viewer authenticated by an external JWT (`jwt_ext_`) has no `usr` row, yet is a -//! member of the workspace its JWT names. Isolating it would hand it an embed token -//! owned by its email, which token auth can never resolve, so the embedded app would -//! reload forever on 401s. It keeps the publisher's unsandboxed render instead. +//! member of the workspace its JWT names, so it keeps the publisher's unsandboxed +//! render. When the publisher isolates the app, its embed token must authenticate +//! without `usr`: a `token` row owned by the viewer's email never would, and the +//! embedded app would reload forever on 401s. //! //! The RSA keypair is a fixed test vector: `JWT_EXT_PUBLIC_KEY` is read once per //! process, so it is set before the server first authenticates a `jwt_ext_` bearer. @@ -15,46 +16,70 @@ use serde_json::json; use sqlx::{Pool, Postgres}; use windmill_test_utils::*; -const APP_PATH: &str = "u/test-user/ext_jwt_app"; - const PRIV: &str = "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDW0+VQN2+bO2ZA\nlXLaJgDvOxWL8Yt8JAjKxtBuoEXm7LKSlTRY/5IXPtfNu5NowYu2fW+4KUh89mQ4\ngg4oV6V7kS2qOBEUC4ODkxyKfOOfu+n+uTiZufD+xelaw2AClBFw8vzCIdzZofUJ\n8GJS9UNdEtUSYqzngV2QObN/cgN50JRJtymsbzgioOkvExGZY9qFOCpxxtsMBa/H\n6mwXPpAM4dO4cZq77aLn9erBjgBL5KaYZoHjMOSoWRCcY9mdgXx/FoR34Sk0khVF\n1JFAz1jD83+Yh9Y/slzCD2DL/6+GHa1lNwpaKDsYAQythHItErnKKJqsaaxdqHqU\nLGMzkKmDAgMBAAECggEAIShc0SrH8R++l+Kj8tkWyoCbbMQqu/hxMEsgyf0MN6j6\nTvb0jiAJk8jr/3cfjiBWyM3yO8HeIbDYpdgns0ED67SWuxp4QwMb7hJQv2yoqB5A\nREP2YSklR02TckzhjsRShNUcVM0WjLNwt3NWLxO9V/+bdNZXdaFZUvTKUwttTz8C\ncpsn2+Xw97NJk+xho2T0ddLpgP7gHORQ8Hwa8xyEXHWWftCaTw/1i61JGO5c6BvX\ncTAAsGpdSBQXEskwNc6J6v4KtcbE71FQM5wtxjbLIkt3etzJAMwByFd9Fm6gvprv\nyxugvgqI/XxCmK2+ecO5YNyxCzPJy/Om/9ZBuQAugQKBgQD7dZvFYQeB7IaoG5yB\ncIPj/mq7pGGrtpdBOsUUR9kDKV4b2b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/sXpWsNgApQRcPL8wiHc2aH1CfBiUvVD\nXRLVEmKs54FdkDmzf3IDedCUSbcprG84IqDpLxMRmWPahTgqccbbDAWvx+psFz6Q\nDOHTuHGau+2i5/XqwY4AS+SmmGaB4zDkqFkQnGPZnYF8fxaEd+EpNJIVRdSRQM9Y\nw/N/mIfWP7Jcwg9gy/+vhh2tZTcKWig7GAEMrYRyLRK5yiiarGmsXah6lCxjM5Cp\ngwIDAQAB\n-----END PUBLIC KEY-----\n"; -#[sqlx::test(fixtures("base"))] -async fn ext_jwt_viewer_keeps_the_unsandboxed_render(db: Pool) -> anyhow::Result<()> { - unsafe { std::env::set_var("JWT_EXT_PUBLIC_KEY", PUB) }; - initialize_tracing().await; - let server = ApiServer::start(db.clone()).await?; - let ws = format!( - "http://localhost:{}/api/w/test-workspace", - server.addr.port() - ); - let client = reqwest::Client::new(); - +async fn create_app( + client: &reqwest::Client, + db: &Pool, + ws: &str, + path: &str, + sandbox: bool, +) -> anyhow::Result { let resp = client .post(format!("{ws}/apps/create")) .header("Authorization", "Bearer SECRET_TOKEN") .json(&json!({ - "path": APP_PATH, + "path": path, "summary": "Embedded with an external JWT", "value": {}, - "policy": { "execution_mode": "publisher", "triggerables": {}, "sandbox": false } + "policy": { "execution_mode": "publisher", "triggerables": {}, "sandbox": sandbox } })) .send() .await?; assert_eq!(resp.status(), 201, "{}", resp.text().await?); // Read access through the group the JWT claims, as a publisher-mode app requires. sqlx::query("UPDATE app SET extra_perms = '{\"g/all\": false}' WHERE path = $1") - .bind(APP_PATH) - .execute(&db) + .bind(path) + .execute(db) .await?; - let secret = client - .get(format!("{ws}/apps/secret_of/{APP_PATH}")) + Ok(client + .get(format!("{ws}/apps/secret_of/{path}")) .header("Authorization", "Bearer SECRET_TOKEN") .send() .await? .text() + .await?) +} + +async fn get_json( + client: &reqwest::Client, + url: &str, + bearer: &str, +) -> anyhow::Result { + let resp = client + .get(url) + .header("Authorization", format!("Bearer {bearer}")) + .send() .await?; + assert_eq!(resp.status(), 200, "{url}: {}", resp.text().await?); + Ok(resp.json().await?) +} + +#[sqlx::test(fixtures("base"))] +async fn ext_jwt_viewer_renders_embedded_apps(db: Pool) -> anyhow::Result<()> { + unsafe { std::env::set_var("JWT_EXT_PUBLIC_KEY", PUB) }; + initialize_tracing().await; + set_jwt_secret().await; + let server = ApiServer::start(db.clone()).await?; + let ws = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + let client = reqwest::Client::new(); + let open_secret = create_app(&client, &db, &ws, "u/test-user/ext_jwt_open", false).await?; + let isolated_secret = + create_app(&client, &db, &ws, "u/test-user/ext_jwt_isolated", true).await?; let exp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() + 3600; let jwt = encode( @@ -71,18 +96,55 @@ async fn ext_jwt_viewer_keeps_the_unsandboxed_render(db: Pool) -> anyh }), &EncodingKey::from_rsa_pem(PRIV.as_bytes())?, )?; - let bearer = format!("Bearer jwt_ext_{jwt}"); + let viewer = format!("jwt_ext_{jwt}"); - let resp = client - .get(format!("{ws}/apps_u/embed_token/{secret}")) - .header("Authorization", &bearer) - .send() - .await?; - assert_eq!(resp.status(), 200, "{}", resp.text().await?); - let body: serde_json::Value = resp.json().await?; + let body = get_json( + &client, + &format!("{ws}/apps_u/embed_token/{open_secret}"), + &viewer, + ) + .await?; assert_eq!(body["sandbox"], json!(false), "{body}"); assert!(body["token"].is_null(), "no embed token to mint: {body}"); + let body = get_json( + &client, + &format!("{ws}/apps_u/embed_token/{isolated_secret}"), + &viewer, + ) + .await?; + assert_eq!(body["sandbox"], json!(true), "{body}"); + let embed = body["token"] + .as_str() + .expect("an isolated render gets a token"); + let expiration: chrono::DateTime = + serde_json::from_value(body["expiration"].clone())?; + assert!( + expiration.timestamp() <= exp as i64, + "capped on the viewer's JWT: {body}" + ); + let whoami = get_json(&client, &format!("{ws}/users/whoami"), embed).await?; + assert_eq!(whoami["email"], json!("embedded@example.com")); + get_json( + &client, + &format!("{ws}/apps_u/public_app/{isolated_secret}"), + embed, + ) + .await?; + // Held to the embed scopes: it cannot renew itself or reach another app. + for url in [ + format!("{ws}/apps_u/embed_token/{isolated_secret}"), + format!("{ws}/apps/get/p/u/test-user/ext_jwt_open"), + ] { + let status = client + .get(&url) + .header("Authorization", format!("Bearer {embed}")) + .send() + .await? + .status(); + assert!(status == 401 || status == 403, "{url}: {status}"); + } + let tokens: i64 = sqlx::query_scalar("SELECT count(*) FROM token WHERE email = $1") .bind("embedded@example.com") .fetch_one(&db) diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index c6efabac71..d541a57e3f 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -93,9 +93,10 @@ pub struct ApiAuthed { /// superadmin (`require_super_admin`), GHSA-hfh4-cx4h-3fcr. pub job_id: Option, /// When this credential itself expires, if it carries its own expiry rather than a - /// token row. Set for a guest JWT (its `exp`): a token minted from it is capped at - /// this, since the JWT's expiry is a guest's only revocation and there is no row to - /// look the limit up in. `None` for every credential whose limit lives in `token`. + /// token row. Set for a guest JWT and an external JWT (`jwt_ext_`), from its `exp`: a + /// token minted from either is capped at this, since there is no row to look the limit + /// up in, and an app's isolated render refuses to mint for an external JWT without it. + /// `None` for every credential whose limit lives in `token`. pub credential_expiry: Option>, /// The OAuth client of an external issuer acting for this user (`mcp_external_idp`). /// Recorded on the runs it starts and handed to their steps as `WM_MCP_CLIENT`. diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index 63a6f6c96b..8dce9f3f66 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -1599,6 +1599,7 @@ async fn mint_raw_app_sdk_token( w_id: &str, app_path: &str, authed: &ApiAuthed, + viewer_token: Option<&str>, scopes: &[String], job_id: Option, ) -> Result<(String, chrono::DateTime)> { @@ -1644,12 +1645,100 @@ async fn mint_raw_app_sdk_token( // session lacks. Some(authed.read_only), ); + mint_viewer_derived_token(db, w_id, authed, viewer_token, token_config, job_id).await +} + +/// Mints an app's embed or SDK token from the viewer's credential. A row in `token` +/// resolves its owner through `usr`, which an external-JWT viewer usually lacks, so +/// such a viewer gets a JWT the instance signs over its own claims instead: same +/// scopes, workspace and label, expiring no later than the viewer's JWT. A guest keeps +/// the row, which its label resolves without `usr`. +async fn mint_viewer_derived_token( + db: &DB, + w_id: &str, + authed: &ApiAuthed, + viewer_token: Option<&str>, + token_config: NewToken, + job_id: Option, +) -> Result<(String, chrono::DateTime)> { + let requested_exp = token_config + .expiration + .ok_or_else(|| Error::internal_err("viewer-derived token without expiry".to_string()))?; + if !is_ext_jwt_bearer(viewer_token) + || windmill_api_auth::scopes::has_guest_sentinel(authed.scopes.as_deref()) + { + let mut tx = db.begin().await?; + let token = create_token_internal(&mut *tx, db, authed, token_config).await?; + tx.commit().await?; + return Ok((token, requested_exp)); + } + // A JWT cannot carry these; an external-JWT viewer never holds them either. + if token_config.read_only == Some(true) || authed.allowed_ips.is_some() { + return Err(Error::internal_err( + "an external-JWT viewer cannot be held read-only or to networks".to_string(), + )); + } + let viewer_exp = authed.credential_expiry.ok_or_else(|| { + Error::NotAuthorized("the external JWT carries no expiry to cap on".to_string()) + })?; + let archived: bool = + sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM workspace WHERE id = $1 AND deleted)") + .bind(w_id) + .fetch_one(db) + .await?; + if archived { + return Err(Error::BadRequest( + "Cannot create a token for an archived workspace".to_string(), + )); + } + let expiration = requested_exp.min(viewer_exp); + let expires_in = (expiration - chrono::Utc::now()).num_seconds(); + if expires_in <= 0 { + return Err(Error::NotAuthorized( + "the external JWT has expired".to_string(), + )); + } + let token = windmill_common::auth::create_jwt_token_withholding( + windmill_common::db::Authed::from(authed.clone()), + w_id, + expires_in as u64, + job_id, + token_config.label.clone(), + None, + token_config.scopes.clone(), + (authed.admin_withheld, authed.super_admin_withheld), + ) + .await?; + let grant = windmill_api_auth::TokenAuditGrant { + label: token_config.label.as_deref(), + expiration: Some(expiration), + scopes: token_config.scopes.as_deref(), + workspace_id: Some(w_id), + read_only: false, + allowed_ips: None, + admin: authed.is_admin && !authed.admin_withheld, + super_admin: false, + } + .params(); let mut tx = db.begin().await?; - let token = create_token_internal(&mut *tx, db, authed, token_config).await?; + audit_log( + &mut *tx, + authed, + "users.token.create", + ActionKind::Create, + &"global", + token_config.label.as_deref(), + Some(windmill_api_auth::audit_params(&grant)), + ) + .await?; tx.commit().await?; Ok((token, expiration)) } +fn is_ext_jwt_bearer(viewer_token: Option<&str>) -> bool { + viewer_token.is_some_and(|t| t.starts_with("jwt_ext_")) +} + /// Label and expiry a token minted *by* a guest session must carry, or `None` for a /// non-guest minter. The label is what lets it resolve; the caller pushes the `guest` /// sentinel so every guest control still applies; the expiry is capped at the parent's, @@ -1739,14 +1828,23 @@ pub async fn build_embed_token_response( let (token, expiration) = if raw_app { match (&sdk_scopes, opt_authed) { (Some(scopes), Some(authed)) if sdk_consent => { - let (t, e) = - mint_raw_app_sdk_token(db, w_id, app_path, authed, scopes, job_id).await?; + let (t, e) = mint_raw_app_sdk_token( + db, + w_id, + app_path, + authed, + viewer_token, + scopes, + job_id, + ) + .await?; (Some(t), Some(e)) } _ => (None, None), } } else if sandbox { - let resp = mint_app_embed_token(db, w_id, app_path, opt_authed, job_id).await?; + let resp = + mint_app_embed_token(db, w_id, app_path, opt_authed, viewer_token, job_id).await?; (resp.token, resp.expiration) } else { (None, None) @@ -1773,9 +1871,7 @@ pub async fn build_embed_token_response( /// so the app renders isolated for them whatever its policy says. /// /// An external JWT (`jwt_ext_`) is a member without a `usr` row: the issuer vouches -/// for it in this workspace, and its auth already refused it for any other. It must -/// not be isolated, because the embed token isolation mints is owned by its email and -/// token auth resolves that owner through `usr`, so the token could never authenticate. +/// for it in this workspace, and its auth already refused it for any other. async fn viewer_is_workspace_member( db: &DB, w_id: &str, @@ -1788,7 +1884,7 @@ async fn viewer_is_workspace_member( if windmill_api_auth::scopes::has_guest_sentinel(authed.scopes.as_deref()) { return Ok(false); } - if viewer_token.is_some_and(|t| t.starts_with("jwt_ext_")) { + if is_ext_jwt_bearer(viewer_token) { return Ok(true); } let member: bool = sqlx::query_scalar( @@ -1830,14 +1926,23 @@ async fn require_full_apps(db: &DB, w_id: &str, authed: &ApiAuthed, action: &str async fn mint_preview_sdk_token( authed: ApiAuthed, OptJobAuthed { job_id, .. }: OptJobAuthed, + OptTokened { token: viewer_token }: OptTokened, Extension(db): Extension, Path(w_id): Path, Json(req): Json, ) -> Result { check_operator_can_build(&db, &w_id, &authed, BuilderKind::Apps, "preview raw apps").await?; check_scopes(&authed, || format!("apps:write:{}", req.path))?; - let (token, _expiration) = - mint_raw_app_sdk_token(&db, &w_id, &req.path, &authed, &req.scopes, job_id).await?; + let (token, _expiration) = mint_raw_app_sdk_token( + &db, + &w_id, + &req.path, + &authed, + viewer_token.as_deref(), + &req.scopes, + job_id, + ) + .await?; Ok(token) } @@ -1911,6 +2016,7 @@ pub async fn mint_app_embed_token( w_id: &str, app_path: &str, opt_authed: Option<&ApiAuthed>, + viewer_token: Option<&str>, job_id: Option, ) -> Result { let token_and_exp = if let Some(authed) = opt_authed { @@ -1973,10 +2079,7 @@ pub async fn mint_app_embed_token( // session lacks. Some(authed.read_only), ); - let mut tx = db.begin().await?; - let token = create_token_internal(&mut *tx, db, authed, token_config).await?; - tx.commit().await?; - Some((token, expiration)) + Some(mint_viewer_derived_token(db, w_id, authed, viewer_token, token_config, job_id).await?) } else { None };