feat: gate public apps on cloud plans and unpublish them on archive (#12321)

* feat: require a paid plan for public apps on Windmill Cloud

On the shared cloud, refuse any app deploy that leaves the app public
(execution_mode anonymous) unless the workspace's billing root is
premium: creating one, switching to public, and redeploying an app that
is already public. Switching away from public stays allowed; serving is
unchanged. The app access UI disables Public and links to the upgrade.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: word the public-app notice for undeployed apps and test switching to public

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: read the app workspace's own plan for the public option

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: make a workspace's public apps private when it is archived

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: archive public apps to publisher mode, not viewer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: use publisher as the non-public mode

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
hugocasa
2026-11-10 17:09:54 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 6a11d3033a
commit a9f5a9caa0
7 changed files with 267 additions and 3 deletions
@@ -0,0 +1,23 @@
{
"db_name": "PostgreSQL",
"query": "SELECT policy->>'execution_mode' = 'anonymous' FROM app\n WHERE path = $1 AND workspace_id = $2",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "?column?",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Text",
"Text"
]
},
"nullable": [
null
]
},
"hash": "1642ab69bebc6cde3760a4124fdb1192d9d25ebd688bf39806e92f8fe6e84529"
}
@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE app SET policy = jsonb_set(policy, '{execution_mode}', '\"publisher\"')\n WHERE workspace_id = $1 AND policy->>'execution_mode' = 'anonymous'",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text"
]
},
"nullable": []
},
"hash": "8aca507d5a1a548ddce49244b1222bbca953b9436f3b9541677e664c84d443ed"
}
+104
View File
@@ -0,0 +1,104 @@
//! On the shared cloud (`CLOUD_HOSTED`), public (`anonymous`) apps take a paid plan.
//!
//! One test in its own binary on purpose: `CLOUD_HOSTED` is read once into a
//! `lazy_static`, so it must be set before anything reads it.
#![cfg(feature = "cloud")]
use serde_json::json;
use sqlx::{Pool, Postgres};
use windmill_test_utils::*;
const ADMIN_TOKEN: &str = "SECRET_TOKEN";
const APP_PATH: &str = "u/test-user/public_app";
fn post(url: String) -> reqwest::RequestBuilder {
reqwest::Client::new()
.post(url)
.header("Authorization", format!("Bearer {ADMIN_TOKEN}"))
}
fn public_app() -> serde_json::Value {
json!({
"path": APP_PATH,
"summary": "Public app",
"value": {},
"policy": { "execution_mode": "anonymous", "triggerables": {} }
})
}
#[sqlx::test(fixtures("base"))]
async fn public_apps_take_a_paid_plan(db: Pool<Postgres>) -> anyhow::Result<()> {
unsafe { std::env::set_var("CLOUD_HOSTED", "true") };
initialize_tracing().await;
// A fork of a paid root draws the root's plan, though it is not premium itself.
sqlx::raw_sql(
"INSERT INTO workspace (id, name, owner, premium) VALUES ('paid-root', 'paid-root', 'test-user', true);
INSERT INTO workspace (id, name, owner, parent_workspace_id)
VALUES ('paid-fork', 'paid-fork', 'test-user', 'paid-root');
INSERT INTO workspace_settings (workspace_id) VALUES ('paid-root'), ('paid-fork');
INSERT INTO usr (workspace_id, email, username, is_admin, role)
VALUES ('paid-fork', 'test@windmill.dev', 'test-user', true, 'Admin');",
)
.execute(&db)
.await?;
let server = ApiServer::start(db.clone()).await?;
let api = format!("http://localhost:{}/api/w", server.addr.port());
let ws = format!("{api}/test-workspace");
let resp = post(format!("{ws}/apps/create"))
.json(&public_app())
.send()
.await?;
assert_eq!(
resp.status(),
400,
"a free workspace cannot create a public app"
);
assert!(resp.text().await?.contains("paid plan"));
// An app made public before the rule: its next version is refused too.
let mut app = public_app();
app["policy"]["execution_mode"] = json!("publisher");
let resp = post(format!("{ws}/apps/create")).json(&app).send().await?;
assert_eq!(resp.status(), 201, "{}", resp.text().await?);
let resp = post(format!("{ws}/apps/update/{APP_PATH}"))
.json(&json!({ "execution_mode": "anonymous" }))
.send()
.await?;
assert_eq!(resp.status(), 400, "an app cannot be switched to public");
sqlx::query(
"UPDATE app SET policy = jsonb_set(policy, '{execution_mode}', '\"anonymous\"')
WHERE path = $1 AND workspace_id = 'test-workspace'",
)
.bind(APP_PATH)
.execute(&db)
.await?;
let resp = post(format!("{ws}/apps/update/{APP_PATH}"))
.json(&json!({ "value": { "grid": [] } }))
.send()
.await?;
assert_eq!(
resp.status(),
400,
"an already-public app cannot be redeployed"
);
// Taking it out of public stays allowed.
let resp = post(format!("{ws}/apps/update/{APP_PATH}"))
.json(&json!({ "execution_mode": "publisher" }))
.send()
.await?;
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
let resp = post(format!("{api}/paid-fork/apps/create"))
.json(&public_app())
.send()
.await?;
assert_eq!(
resp.status(),
201,
"a fork of a paid root may publish: {}",
resp.text().await?
);
Ok(())
}
@@ -1324,3 +1324,41 @@ async fn test_create_workspace_validates_chosen_username(db: Pool<Postgres>) ->
Ok(())
}
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
async fn archiving_a_workspace_makes_its_public_apps_private(
db: Pool<Postgres>,
) -> anyhow::Result<()> {
initialize_tracing().await;
sqlx::query(
"INSERT INTO app (workspace_id, path, summary, policy, versions) VALUES
('test-workspace', 'u/test-user/public', '', '{\"execution_mode\": \"anonymous\"}', '{}'),
('test-workspace', 'u/test-user/members', '', '{\"execution_mode\": \"publisher\"}', '{}')",
)
.execute(&db)
.await?;
let server = ApiServer::start(db.clone()).await?;
let port = server.addr.port();
let resp = authed(client().post(format!(
"http://localhost:{port}/api/w/test-workspace/workspaces/archive"
)))
.send()
.await?;
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
let modes: Vec<(String, String)> = sqlx::query_as(
"SELECT path, policy->>'execution_mode' FROM app
WHERE workspace_id = 'test-workspace' ORDER BY path",
)
.fetch_all(&db)
.await?;
assert_eq!(
modes,
[
("u/test-user/members".to_string(), "publisher".to_string()),
("u/test-user/public".to_string(), "publisher".to_string()),
]
);
Ok(())
}
@@ -11641,6 +11641,20 @@ pub(crate) async fn archive_workspace_impl(
windmill_queue::schedule::clear_schedule(&mut tx, schedule_path, w_id).await?;
}
// Public apps are served without a session, so nothing else about an archived workspace
// stops them: take them private. `publisher`, not `viewer`: viewer mode runs as whoever opens
// the app and skips its runnable allowlist, which an operator-built app must never get.
// Unarchiving does not restore them.
let unpublished_apps = sqlx::query!(
"UPDATE app SET policy = jsonb_set(policy, '{execution_mode}', '\"publisher\"')
WHERE workspace_id = $1 AND policy->>'execution_mode' = 'anonymous'",
w_id
)
.execute(&mut *tx)
.await?
.rows_affected();
tracing::info!("Made {unpublished_apps} public apps private in workspace {w_id}");
// Delete non-session tokens scoped to this workspace
let deleted_tokens = sqlx::query_scalar!(
"DELETE FROM token WHERE workspace_id = $1 AND label IS DISTINCT FROM 'session' RETURNING token_prefix",
+47
View File
@@ -378,6 +378,31 @@ fn refuse_guest_mode_where_unavailable(
)))
}
/// Whether this workspace may deploy apps that stay public (`Anonymous`). On the
/// cloud that takes a paid plan, resolved through the fork/dev root; no workspace
/// admin can lift it, unlike `RestrictAnonymousAppDeployment`. Every deploy that
/// leaves an app public is refused, not only the transition into it, so a free
/// workspace's existing public apps stay frozen until it upgrades.
async fn public_apps_allowed(_db: &DB, _w_id: &str) -> Result<bool> {
#[cfg(feature = "cloud")]
if *CLOUD_HOSTED {
return Ok(
windmill_common::workspaces::get_team_plan_status(_db, _w_id)
.await?
.premium,
);
}
Ok(true)
}
fn public_app_requires_plan(path: &str) -> Error {
Error::BadRequest(format!(
"app {path} is public (accessible without login), which requires a paid plan on \
Windmill Cloud. Upgrade this workspace in Workspace Settings > Premium plans to publish \
or update public apps, or change who can open the app."
))
}
/// Gate a viewer on the app's `execution_mode`, as far as can be decided without an
/// ACL probe. `Ok(true)` means already authorized — anonymous admits anyone, guest
/// admits anyone signed in; `Ok(false)` means the caller is a member and still owes
@@ -2853,6 +2878,11 @@ async fn create_app_internal<'a>(
"Summary must be less than 300 characters on cloud".to_string(),
));
}
if app.policy.execution_mode() == ExecutionMode::Anonymous
&& !public_apps_allowed(&db, w_id).await?
{
return Err(public_app_requires_plan(&app.path));
}
}
// Resolve the on-behalf-of defaults on the (non-RLS) pool *before* opening
// the RLS transaction below: doing these lookups mid-transaction would hold
@@ -3878,6 +3908,10 @@ async fn update_app_internal<'a>(
}
}
// Resolved before the transaction for the reason above; checked against the row
// as written, once every field below has landed.
let public_apps_allowed = public_apps_allowed(&db, w_id).await?;
let mut tx = user_db.clone().begin(&authed).await?;
// `app_version.raw_app` is set by whichever endpoint writes the version, so a
@@ -4232,6 +4266,19 @@ async fn update_app_internal<'a>(
)));
}
};
if !public_apps_allowed
&& sqlx::query_scalar!(
"SELECT policy->>'execution_mode' = 'anonymous' FROM app
WHERE path = $1 AND workspace_id = $2",
npath,
w_id
)
.fetch_one(&mut *tx)
.await?
.unwrap_or(false)
{
return Err(public_app_requires_plan(&npath));
}
// CLI / git-sync deploys ask us to preserve any existing user draft at this
// path instead of wiping it as part of the deploy. Only wipe the deployer's
// own draft (plus the legacy NULL-email row) — see create_app_internal.
@@ -75,6 +75,12 @@
canUserBypassRuleKind('RestrictGuestAppDeployment', $userStore ?? undefined))
)
// The server refuses every deploy that leaves an app public on a free cloud workspace, so an
// already-public app can only be switched away from it. Read for `workspace`, which a session
// editor can set to another workspace than the one navigated to.
let premium = $state<boolean | undefined>(undefined)
let publicNeedsPlan = $derived(isCloudHosted() && premium === false)
let guestUsage = $state<GuestUsage | undefined>(undefined)
// The backend decides; the hostname stands in until it answers, the shared cloud being the
// only deployment where guests are unavailable.
@@ -84,6 +90,11 @@
let secretUrl: string | undefined = $state(undefined)
function load() {
if (isCloudHosted()) {
WorkspaceService.getIsPremium({ workspace })
.then((p) => (premium = p))
.catch(() => (premium = undefined))
}
WorkspaceService.getGuestUsage({ workspace })
.then((u) => (guestUsage = u))
.catch(() => (guestUsage = undefined))
@@ -150,7 +161,18 @@
</script>
<div class="flex flex-col gap-4">
{#if rulesetsLoaded && !canSetAnonymous && mode != 'anonymous'}
{#if publicNeedsPlan}
<Alert type="info" title="Public apps require a paid plan" size="xs">
On Windmill Cloud, publishing or updating an app that anyone can open without signing in
requires a paid plan.
{#if mode == 'anonymous'}
Switch this app to Members to deploy it.
{/if}
<a href="/workspace_settings?tab=premium" target="_blank" class="underline"
>Upgrade this workspace</a
>
</Alert>
{:else if rulesetsLoaded && !canSetAnonymous && mode != 'anonymous'}
<Alert type="warning" title="Restricted by a workspace protection rule" size="xs">
Opening this app to anyone with the link is restricted to workspace admins and bypass users by
a workspace protection rule
@@ -191,8 +213,10 @@
<ToggleButton
label="Public"
value="anonymous"
disabled={!canSetAnonymous && mode != 'anonymous'}
tooltip="Anyone with the secret URL. No login."
disabled={mode != 'anonymous' && (publicNeedsPlan || !canSetAnonymous)}
tooltip={publicNeedsPlan
? 'Requires a paid plan on Windmill Cloud.'
: 'Anyone with the secret URL. No login.'}
{item}
/>
{/snippet}