Files
windmill/backend/windmill-api-integration-tests/tests/drafts.rs
T
484a7699db feat: move a live ai session into a workspace fork with its drafts (#11602)
* feat: move a live ai session into a workspace fork with its drafts

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: guard session moves against concurrent turns and unsaved edits

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: harden the draft transfer against bound tokens, key drift and concurrent saves

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore: point ee-repo-ref at the moved_to_fork registration

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore: point ee-repo-ref at the ee branch merged with its matching main

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: re-copy drafts into a new fork and keep other tabs in step with a move

- A new fork now gets the same transfer as an existing one, with
  replace_existing set only when this move created the fork, so a draft
  saved after the clone reaches the fork and an existing fork's own drafts
  still go through the conflict check.
- The transfer runs the operator composition check on each draft in the
  target workspace, the same check as a direct save there.
- Editors already open on a moved item in the fork reload it from the
  server.
- Other tabs on the session hold their composer during a move and adopt
  the session's new workspace when it ends.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: lock the composer during a move and copy only the locked source drafts

- The tab doing a move disables its composer until the move ends, and the
  move checks again for a running turn once a new fork exists.
- Saves still pending in editors open in an existing fork are flushed
  before the transfer, so they surface as conflicts instead of landing on
  the moved draft later.
- The transfer copies, conflict-checks and removes only the source rows it
  locked and validated; a draft saved at a requested key after the lock is
  left out.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: keep fork drafts with no source row and re-read the move's drafts on confirm

- replace_existing deletes only the fork drafts the transfer replaces, so a
  draft discarded in the parent after the clone does not take the fork's
  copy with it.
- Confirming a move lists the session's drafts again once no turn can
  start, and sends the user back to the dialog if the list changed.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: let a move be retried after its conflicts are resolved

- Move stays enabled while the dialog lists conflicts; confirming re-reads
  them, so a draft discarded in the fork meanwhile no longer blocks it.
- A dialog left open while another tab moved the session closes instead of
  moving from the old workspace.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: refuse to confirm a move while a turn runs

A turn started while the move dialog was open owns the cross-tab hold the
move would take, and the move would release it while the turn still runs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: disable moving a session again while a move runs

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: re-read the session's drafts once a new fork exists

Creating the fork takes seconds, during which an edit in the session's
preview can save a draft in the parent that the move's list did not have.
The move now flushes and lists the drafts again before the transfer, and
reopens the dialog on the created fork when they changed.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: keep restricted roles from creating a fork through a session move

The move's fork gate checked only the workspace's forking rule. A role
missing a capability would get the default role in a fork it creates, so
the gate also refuses restricted roles, as the workspace picker does.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: hold the session read-only while it moves into a fork

An edit in the session's preview during a move saves a draft in the
workspace being left, after the move listed what it brings, at any of
its awaits. The session now reads as read-only for the whole move, so
the preview shows its items without an editor until the move ends.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: close only draft editors during a move, and say why

Variable, resource and trigger editors save on click and write no draft,
so closing them during a move protected nothing and lost a half-filled
form when the move stopped. Only the editors that save drafts close, and
the pipeline tab names the move instead of Use mode.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: close variable, resource and trigger editors during a move too

They keep their edits as drafts like the other editors, so an edit during
the move could save one in the workspace being left. Their state lives in
the draft, so closing them loses nothing; they reopen in the fork.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: flush every code editor through one registry, and name the move in editor tabs

- Monaco's Editor registers in pendingEditorFlush next to SimpleEditor,
  and the move drains that registry, so SimpleEditor buffers (step input
  expressions, resource and variable JSON fields) also land before it.
  The separate keystroke registry is gone.
- A flow, script or app editor tab closed for a move says it reopens
  once the move ends, instead of showing the parent's viewer.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: re-point unresolvable identities in drafts a move copies into a fork

Fork creation re-points an app policy or trigger in a cloned draft that
names nobody in the fork at its creator, since a deploy there rejects an
identity that does not resolve. The transfer copied drafts without that
step, and replace_existing overwrote the clone's repaired copy. The draft
half of the repoint is now shared and runs on the rows a transfer copies.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: drop script lineage a fork does not have when copying drafts into it

A script draft kept its base and parent_hash on the grounds that a fork
shares its parent's script hashes. That holds for what the fork cloned,
but not for a version deployed in the parent afterwards, and a deploy in
the fork naming it as parent is refused. The copy now keeps the lineage
only when the target has that version.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test: pin that a transfer keeps script lineage the fork has

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: drain draft editors before closing them for a move

Closing an editor drops an edit it has not yet handed to its draft save,
so a keystroke typed just before the move could be lost. The editors are
now flushed while still mounted, and closed right after with no await in
between.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: hold every turn during a move, and state the repoint's contract

- The chat manager refuses sends, retries and message edits while a move
  runs, from its first step, handing the text back. The composer was
  locked but a retry or an edit could still start a turn in the parent.
- A move into an existing fork checks again for a running turn after
  saving that fork's pending edits.
- repoint_unresolvable_draft_identities documents that it authorizes
  nothing and when its unscoped form may be used.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: refuse a move while an editor holds text that is not valid JSON

That text never reaches the draft, and the move closes the editor holding
it. The move now refuses before closing anything, as opening a session
from a page drawer already does.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: check for invalid JSON after the editors have parsed what was flushed

The JSON editors parse a flushed buffer in an effect, so the check reads
the registry after a tick, as RunForm and the page drawer already do. The
message says the editor is in the preview.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* perf: look script lineage up by key when copying drafts

The lineage check compared a hex rendering of every script hash, which
ruled out the primary key and scanned the target's script versions for
each script draft, fork creation included. It now converts the draft's
16-digit hex to the bigint column, guarded so a malformed value never
reaches the cast.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: stop preview input from the move's first step

The editors stay mounted while the move drains them, and a keystroke
typed during that drain was lost when they closed, or left in the parent
of an existing fork. The preview tabs are inert from the move's first
step, so nothing new reaches an editor after the drain starts.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix: update the local draft markers for drafts a move transfers

The transfer bypasses the syncer that keeps localDraftHints, and lists
prefer a hint over the server's flag, so the parent kept its markers after
"Remove these drafts". The parent's hints are cleared for removed drafts
and the fork's set for copied ones.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat: move a session to any workspace of its family

A session could only move into a direct fork of its workspace. The picker
now lists the whole family and lets a new fork be based on any of its
workspaces, and /drafts/transfer accepts any target with the same root.
A fork the move creates from elsewhere holds that base's drafts, so its
drafts are never replaced.

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

* fix: gate fork creation in the move picker on the fork capability

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

* fix: refuse to move a pipeline draft based on a version the target lacks

A pipeline node deploys with its script hash as parent_hash, so a move to a
workspace without that version left a draft whose Deploy all fails there.

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

* fix: check the move's token against the target by re-authenticating it

The transfer endpoint looked the caller's token up in the `token` table, so
an external-JWT login, which has no row there, could never move a session.
It now resolves the same token against the target workspace, which refuses a
token bound to the source whatever its kind, and still refuses job tokens.

Also stop calling the move target a fork in the model note, the menu item,
the editor placeholders and the moving notices: it can be the root or a
sibling.

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

* fix: check a move's writes with the rights its token carries in the target

The transfer re-authenticated the token against the target but then checked
writes with the user's database membership there, so a JWT whose claims are
narrower than that membership could copy a draft to a path it cannot save to
directly. The identity the re-authentication returns is now the one the
checks and the copy use.

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

* fix: keep an unsent session out of the move after main's session refactor

An unsent session holds its workspace in `pending_workspace_id`, which
`createSession` rewrites when it reuses the blank session; moving it set
`workspace_id`, so a later new session from the old workspace acted on the
fork. The move menu item is hidden until the session has a `workspace_id`.

The transfer test's JWT claims also set main's new `mcp_client` field.

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

* fix: move the drafts a session's user edited by hand

The move's draft list read only the chats' `modifiedItems`, so a draft the
user edited in a session tab, which main now records in `sessionHandEdits`
and the Changes bar counts, stayed behind in the workspace left.

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

* fix: keep raw app edits and report draft races on session move

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

* feat: offer to move the session when switching fork in the breadcrumb

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

* fix: pass the optional don't move handler through onClick

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

* chore: update ee-repo-ref to 3ad072124c3682e282829dd7213e42a6e28cf1fa

This commit updates the EE repository reference after PR #856 was merged in windmill-ee-private.

Previous ee-repo-ref: 90af10fe72bfcb981abaa119239a63d085030215

New ee-repo-ref: 3ad072124c3682e282829dd7213e42a6e28cf1fa

Automated by sync-ee-ref workflow.

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Ruben Fiszel <ruben@windmill.dev>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
2026-11-11 16:55:42 +01:00

650 lines
23 KiB
Rust

use serde_json::json;
use sqlx::{Pool, Postgres};
use windmill_test_utils::*;
const WS: &str = "test-workspace";
/// A reqwest client that sends `Authorization: Bearer <token>`. The base
/// fixture seeds: SECRET_TOKEN (test-user, admin), SECRET_TOKEN_2
/// (test-user-2, non-admin), SECRET_TOKEN_3 (test-user-3, non-admin).
fn client_for(token: &str) -> reqwest::Client {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
reqwest::header::AUTHORIZATION,
reqwest::header::HeaderValue::from_str(&format!("Bearer {token}")).unwrap(),
);
reqwest::ClientBuilder::new()
.default_headers(headers)
.build()
.unwrap()
}
fn save_url(port: u16, kind: &str, path: &str) -> String {
format!("http://localhost:{port}/api/w/{WS}/drafts/update/{kind}/{path}")
}
async fn draft_count(db: &Pool<Postgres>, path: &str, kind: &str, email: &str) -> i64 {
sqlx::query_scalar::<_, i64>(
"SELECT count(*) FROM draft WHERE workspace_id = $1 AND path = $2 \
AND typ = $3::text::DRAFT_KIND AND email = $4",
)
.bind(WS)
.bind(path)
.bind(kind)
.bind(email)
.fetch_one(db)
.await
.unwrap()
}
/// Upsert → conflict (stale last_sync) → force-overwrite → delete, the
/// optimistic-concurrency contract `update_draft` exists to enforce.
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
async fn test_update_draft_conflict_lifecycle(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let port = server.addr.port();
let c = client_for("SECRET_TOKEN");
let path = "u/test-user/draft_x";
let url = save_url(port, "script", path);
// First save: no last_sync ("treat as fresh") → saved.
let r = c
.post(&url)
.json(&json!({ "value": { "n": 1 } }))
.send()
.await?;
assert_eq!(r.status(), 200, "first save");
let body: serde_json::Value = r.json().await?;
assert_eq!(body["status"], "saved");
let ts1 = body["current_timestamp"].as_str().unwrap().to_string();
assert_eq!(
draft_count(&db, path, "script", "test@windmill.dev").await,
1
);
// A tiny gap so the next now() is strictly greater than ts1.
tokio::time::sleep(std::time::Duration::from_millis(15)).await;
// Save with the matching last_sync → not stale → saved, newer ts.
let r = c
.post(&url)
.json(&json!({ "value": { "n": 2 }, "last_sync": ts1 }))
.send()
.await?;
let body: serde_json::Value = r.json().await?;
assert_eq!(body["status"], "saved", "in-order save");
let ts2 = body["current_timestamp"].as_str().unwrap().to_string();
assert_ne!(ts1, ts2, "timestamp should advance");
// Save with the now-stale ts1 → conflict, server reports its current ts.
let r = c
.post(&url)
.json(&json!({ "value": { "n": 3 }, "last_sync": ts1 }))
.send()
.await?;
let body: serde_json::Value = r.json().await?;
assert_eq!(body["status"], "conflict", "stale save must conflict");
assert_eq!(body["current_timestamp"].as_str().unwrap(), ts2);
// The conflicting write must NOT have landed — value is still {n:2}.
let stored: serde_json::Value = sqlx::query_scalar::<_, sqlx::types::Json<serde_json::Value>>(
"SELECT value FROM draft WHERE workspace_id = $1 AND path = $2 \
AND typ = 'script' AND email = 'test@windmill.dev'",
)
.bind(WS)
.bind(path)
.fetch_one(&db)
.await?
.0;
assert_eq!(stored["n"], 2, "conflicting write must be rejected");
// force = true overrides the conflict check.
let r = c
.post(&url)
.json(&json!({ "value": { "n": 3 }, "last_sync": ts1, "force": true }))
.send()
.await?;
assert_eq!(
r.json::<serde_json::Value>().await?["status"],
"saved",
"force"
);
// Delete (value: null) → saved, row gone.
let r = c.post(&url).json(&json!({ "value": null })).send().await?;
assert_eq!(
r.json::<serde_json::Value>().await?["status"],
"saved",
"delete"
);
assert_eq!(
draft_count(&db, path, "script", "test@windmill.dev").await,
0,
"row removed after delete"
);
Ok(())
}
/// require_can_write_path: own namespace allowed, another user's namespace
/// rejected, operators rejected outright.
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
async fn test_update_draft_write_authorization(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let port = server.addr.port();
let user2 = client_for("SECRET_TOKEN_2"); // test-user-2, non-admin
// Own namespace → allowed.
let r = user2
.post(save_url(port, "script", "u/test-user-2/own"))
.json(&json!({ "value": { "a": 1 } }))
.send()
.await?;
assert_eq!(r.status(), 200, "own namespace allowed");
let r = user2
.post(save_url(port, "data_pipeline", "u/test-user-2/pipeline"))
.json(&json!({ "value": { "a": 1 } }))
.send()
.await?;
assert_eq!(r.status(), 200, "a developer saves data pipeline drafts");
// Another user's namespace, no grant → rejected.
let r = user2
.post(save_url(port, "script", "u/test-user/theirs"))
.json(&json!({ "value": { "a": 1 } }))
.send()
.await?;
assert_eq!(r.status(), 401, "other user's namespace rejected");
// Operators can't save drafts at all.
sqlx::query(
"UPDATE usr SET operator = true WHERE workspace_id = $1 AND username = 'test-user-3'",
)
.bind(WS)
.execute(&db)
.await?;
let op = client_for("SECRET_TOKEN_3");
let r = op
.post(save_url(port, "script", "u/test-user-3/own"))
.json(&json!({ "value": { "a": 1 } }))
.send()
.await?;
assert_eq!(r.status(), 403, "operator rejected");
let r = op
.post(save_url(port, "data_pipeline", "u/test-user-3/pipeline"))
.json(&json!({ "value": { "a": 1 } }))
.send()
.await?;
assert_eq!(
r.status(),
403,
"a role that cannot code has no pipeline drafts"
);
Ok(())
}
/// The item-level extra_perms fallback: a user granted write on a deployed
/// item (via the Share dialog) can save a draft on it even though it's
/// outside their namespace. Regression test for the authz drop.
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
async fn test_update_draft_extra_perms_writer(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let port = server.addr.port();
let path = "u/test-user/shared";
// A deployed script owned by test-user, shared with test-user-2 (write).
sqlx::query(
"INSERT INTO script (workspace_id, hash, path, summary, description, content, \
language, schema, extra_perms, created_by) \
VALUES ($1, 1, $2, '', '', 'x', 'deno', '{}'::jsonb, \
'{\"u/test-user-2\": true}'::jsonb, 'test-user')",
)
.bind(WS)
.bind(path)
.execute(&db)
.await?;
let user2 = client_for("SECRET_TOKEN_2");
let r = user2
.post(save_url(port, "script", path))
.json(&json!({ "value": { "a": 1 } }))
.send()
.await?;
assert_eq!(
r.status(),
200,
"extra_perms writer can save a draft: {}",
r.text().await?
);
// Without a grant on a different shared item → still rejected.
sqlx::query(
"INSERT INTO script (workspace_id, hash, path, summary, description, content, \
language, schema, extra_perms, created_by) \
VALUES ($1, 2, 'u/test-user/private', '', '', 'x', 'deno', '{}'::jsonb, \
'{}'::jsonb, 'test-user')",
)
.bind(WS)
.execute(&db)
.await?;
let r = user2
.post(save_url(port, "script", "u/test-user/private"))
.json(&json!({ "value": { "a": 1 } }))
.send()
.await?;
assert_eq!(r.status(), 401, "no grant → rejected");
// A READ-ONLY grant (`extra_perms` value false) must not allow draft
// saves: the write check defers to RLS via `SELECT ... FOR UPDATE`,
// and locking applies the UPDATE policies — visibility under the
// SELECT policy alone isn't enough. Pins the FOR UPDATE semantics the
// probe relies on.
sqlx::query(
"INSERT INTO script (workspace_id, hash, path, summary, description, content, \
language, schema, extra_perms, created_by) \
VALUES ($1, 3, 'u/test-user/readonly', '', '', 'x', 'deno', '{}'::jsonb, \
'{\"u/test-user-2\": false}'::jsonb, 'test-user')",
)
.bind(WS)
.execute(&db)
.await?;
let r = user2
.post(save_url(port, "script", "u/test-user/readonly"))
.json(&json!({ "value": { "a": 1 } }))
.send()
.await?;
assert_eq!(r.status(), 401, "read-only grant → rejected");
Ok(())
}
/// Cross-user draft viewing (`GET /drafts/get/{kind}/{path}`) is disabled
/// for the drawer kinds (resource/variable/triggers) so a viewer can't
/// read another user's draft; it stays available for script/flow/app.
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
async fn test_cross_user_draft_privacy(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let port = server.addr.port();
// test-user saves a variable draft and a script draft in a shared folder.
let admin = client_for("SECRET_TOKEN");
admin
.post(save_url(port, "variable", "f/shared/v"))
.json(&json!({ "value": { "variable": { "value": "x", "is_secret": false } } }))
.send()
.await?;
let user2 = client_for("SECRET_TOKEN_2");
// Variable is a drawer kind → cross-user view is forbidden regardless of
// path access (the kind gate fires first).
let r = user2
.get(format!(
"http://localhost:{port}/api/w/{WS}/drafts/get/variable/f/shared/v?username=test-user"
))
.send()
.await?;
assert_eq!(
r.status(),
404,
"variable drafts are private to their owner"
);
// Sharing kinds (script) are NOT gated by the kind check — a missing
// draft / no access yields 404 too, but the "private to their owner"
// wording is specific to the drawer kinds, so assert it's absent here.
let r = user2
.get(format!(
"http://localhost:{port}/api/w/{WS}/drafts/get/script/f/shared/s?username=test-user"
))
.send()
.await?;
let body = r.text().await?;
assert!(
!body.contains("private to their owner"),
"script kind must not be blocked by the cross-user privacy gate: {body}"
);
Ok(())
}
/// Moving a session's drafts into a fork is all-or-nothing: a draft the caller already has in
/// the fork blocks the whole transfer rather than one side silently winning, unless the caller
/// asks to replace it, and the source copy is removed only together with a successful copy.
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
async fn test_transfer_drafts_to_fork(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let port = server.addr.port();
let c = client_for("SECRET_TOKEN");
let me = "test@windmill.dev";
let fork = "wm-fork-transfer";
let transfer_url = format!("http://localhost:{port}/api/w/{WS}/drafts/transfer");
let fork_count = |path: &'static str| {
sqlx::query_scalar::<_, i64>(
"SELECT count(*) FROM draft WHERE workspace_id = $1 AND path = $2 AND email = $3",
)
.bind(fork)
.bind(path)
.bind(me)
.fetch_one(&db)
};
let r = c
.post(save_url(port, "script", "u/test-user/a"))
.json(&json!({ "value": { "content": "a" } }))
.send()
.await?;
assert_eq!(r.status(), 200);
let r = c
.post(format!(
"http://localhost:{port}/api/w/{WS}/workspaces/create_fork"
))
.json(&json!({ "id": fork, "name": "transfer" }))
.send()
.await?;
assert!(r.status().is_success(), "create fork: {}", r.text().await?);
// Created after the fork, so only the source has it.
let r = c
.post(save_url(port, "script", "u/test-user/b"))
.json(&json!({ "value": { "content": "b" } }))
.send()
.await?;
assert_eq!(r.status(), 200);
let items = json!([
{ "kind": "script", "path": "u/test-user/a" },
{ "kind": "script", "path": "u/test-user/b" }
]);
// A token bound to the source authenticates on its routes but must not write the fork.
sqlx::query(
"INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin, workspace_id)
VALUES (encode(sha256('BOUND_TOKEN'::bytea), 'hex'), 'BOUND_TOK', 'BOUND_TOKEN', $1, 'bound', true, $2)",
)
.bind(me)
.bind(WS)
.execute(&db)
.await?;
let r = client_for("BOUND_TOKEN")
.post(&transfer_url)
.json(&json!({ "target_workspace": fork, "items": items }))
.send()
.await?;
assert_eq!(r.status(), 403);
assert_eq!(fork_count("u/test-user/b").await?, 0);
// A JWT has no `token` row: its own claims decide which workspaces it reaches.
set_jwt_secret().await;
let jwt = |workspace_ids: Vec<&str>, job_id: Option<&str>, is_admin: bool| {
windmill_common::jwt::encode_with_internal_secret(windmill_common::auth::JWTAuthClaims {
email: me.to_string(),
username: "test-user".to_string(),
is_admin,
is_operator: false,
groups: vec![],
folders: vec![],
label: None,
workspace_id: None,
workspace_ids: Some(workspace_ids.into_iter().map(String::from).collect()),
exp: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as usize
+ 3600,
job_id: job_id.map(String::from),
scopes: None,
audit_span: None,
mcp_client: None,
})
};
let job_id = uuid::Uuid::new_v4().to_string();
let r = c
.post(save_url(port, "script", "u/someone-else/x"))
.json(&json!({ "value": { "content": "x" } }))
.send()
.await?;
assert_eq!(r.status(), 200);
for (claims, path, status) in [
(jwt(vec![WS], None, true).await?, "u/test-user/a", 403),
(
jwt(vec![WS, fork], Some(&job_id), true).await?,
"u/test-user/a",
403,
),
(jwt(vec![WS, fork], None, true).await?, "u/test-user/a", 200),
// An admin in the fork's database, but the JWT does not claim it: the claims win.
(
jwt(vec![WS, fork], None, false).await?,
"u/someone-else/x",
401,
),
] {
let r = client_for(&format!("jwt_{claims}"))
.post(&transfer_url)
.json(
&json!({ "target_workspace": fork, "items": [{ "kind": "script", "path": path }] }),
)
.send()
.await?;
assert_eq!(r.status(), status, "{path}: {}", r.text().await?);
}
assert_eq!(fork_count("u/someone-else/x").await?, 0);
// `a` was cloned into the fork: the whole transfer is refused and nothing moves.
let body: serde_json::Value = c
.post(&transfer_url)
.json(&json!({ "target_workspace": fork, "items": items, "remove_from_source": true }))
.send()
.await?
.json()
.await?;
assert_eq!(
body["conflicts"],
json!([{ "kind": "script", "path": "u/test-user/a" }])
);
assert_eq!(fork_count("u/test-user/b").await?, 0);
assert_eq!(draft_count(&db, "u/test-user/a", "script", me).await, 1);
assert_eq!(draft_count(&db, "u/test-user/b", "script", me).await, 1);
// A save after the clone: replacing the clone's copy must carry it into the fork.
let r = c
.post(save_url(port, "script", "u/test-user/a"))
.json(&json!({ "value": { "content": "a2" } }))
.send()
.await?;
assert_eq!(r.status(), 200);
let body: serde_json::Value = c
.post(&transfer_url)
.json(&json!({
"target_workspace": fork, "items": items,
"remove_from_source": true, "replace_existing": true
}))
.send()
.await?
.json()
.await?;
assert_eq!(body["conflicts"], json!([]));
assert_eq!(body["copied"].as_array().unwrap().len(), 2);
assert_eq!(body["removed"].as_array().unwrap().len(), 2);
assert_eq!(fork_count("u/test-user/a").await?, 1);
assert_eq!(fork_count("u/test-user/b").await?, 1);
let a_in_fork: String = sqlx::query_scalar(
"SELECT value->>'content' FROM draft WHERE workspace_id = $1 AND path = 'u/test-user/a'",
)
.bind(fork)
.fetch_one(&db)
.await?;
assert_eq!(a_in_fork, "a2");
assert_eq!(draft_count(&db, "u/test-user/a", "script", me).await, 0);
assert_eq!(draft_count(&db, "u/test-user/b", "script", me).await, 0);
// With nothing left in the source to replace them, the fork's drafts stay.
let r = c
.post(&transfer_url)
.json(&json!({
"target_workspace": fork, "items": items,
"remove_from_source": true, "replace_existing": true
}))
.send()
.await?;
assert_eq!(r.status(), 200);
assert_eq!(fork_count("u/test-user/a").await?, 1);
assert_eq!(fork_count("u/test-user/b").await?, 1);
// An app policy naming someone who is not a member of the fork is re-pointed at the user, as
// the fork's own clone does: a deploy in the fork rejects an identity that does not resolve.
let r = c
.post(save_url(port, "raw_app", "u/test-user/app"))
.json(&json!({ "value": { "policy": {
"on_behalf_of": "u/not-in-fork", "on_behalf_of_email": "ghost@windmill.dev"
} } }))
.send()
.await?;
assert_eq!(r.status(), 200, "{}", r.text().await?);
let r = c
.post(&transfer_url)
.json(&json!({
"target_workspace": fork,
"items": [{ "kind": "raw_app", "path": "u/test-user/app" }]
}))
.send()
.await?;
assert_eq!(r.status(), 200, "{}", r.text().await?);
let on_behalf_of: String = sqlx::query_scalar(
"SELECT value->'policy'->>'on_behalf_of' FROM draft
WHERE workspace_id = $1 AND path = 'u/test-user/app'",
)
.bind(fork)
.fetch_one(&db)
.await?;
assert_eq!(on_behalf_of, "u/test-user");
// A script version the fork does not have (deployed in the source after the fork was made)
// is no lineage there: a deploy naming it as parent would be refused.
let r = c
.post(save_url(port, "script", "u/test-user/lineage"))
.json(&json!({ "value": { "content": "l", "parent_hash": "0123456789abcdef" } }))
.send()
.await?;
assert_eq!(r.status(), 200, "{}", r.text().await?);
let r = c
.post(&transfer_url)
.json(&json!({
"target_workspace": fork,
"items": [{ "kind": "script", "path": "u/test-user/lineage" }]
}))
.send()
.await?;
assert_eq!(r.status(), 200, "{}", r.text().await?);
let (parent_hash, base): (Option<String>, Option<String>) = sqlx::query_as(
"SELECT value->>'parent_hash', base FROM draft
WHERE workspace_id = $1 AND path = 'u/test-user/lineage'",
)
.bind(fork)
.fetch_one(&db)
.await?;
assert_eq!((parent_hash, base), (None, None));
// A version the fork has keeps its lineage. Its hash has the high bit set, so the match also
// holds for a negative i64, which serializes as 16 hex digits.
sqlx::query(
"INSERT INTO script (workspace_id, hash, path, summary, description, content, created_by)
VALUES ($1, -1, 'u/test-user/lineage', '', '', 'l', 'test-user')",
)
.bind(fork)
.execute(&db)
.await?;
let r = c
.post(save_url(port, "script", "u/test-user/lineage"))
.json(&json!({ "value": { "content": "l2", "parent_hash": "ffffffffffffffff" } }))
.send()
.await?;
assert_eq!(r.status(), 200, "{}", r.text().await?);
let r = c
.post(&transfer_url)
.json(&json!({
"target_workspace": fork,
"items": [{ "kind": "script", "path": "u/test-user/lineage" }],
"replace_existing": true
}))
.send()
.await?;
assert_eq!(r.status(), 200, "{}", r.text().await?);
let (parent_hash, base): (Option<String>, Option<String>) = sqlx::query_as(
"SELECT value->>'parent_hash', base FROM draft
WHERE workspace_id = $1 AND path = 'u/test-user/lineage'",
)
.bind(fork)
.fetch_one(&db)
.await?;
assert_eq!(
(parent_hash.as_deref(), base.as_deref()),
(Some("ffffffffffffffff"), Some("ffffffffffffffff"))
);
// Any workspace of the family takes them: here back from the fork to its parent.
let r = c
.post(format!(
"http://localhost:{port}/api/w/{fork}/drafts/transfer"
))
.json(&json!({
"target_workspace": WS,
"items": [{ "kind": "script", "path": "u/test-user/a" }],
"remove_from_source": true
}))
.send()
.await?;
assert_eq!(r.status(), 200, "{}", r.text().await?);
assert_eq!(draft_count(&db, "u/test-user/a", "script", me).await, 1);
assert_eq!(fork_count("u/test-user/a").await?, 0);
// A workspace outside the family is refused.
let r = c
.post(&transfer_url)
.json(&json!({ "target_workspace": "admins", "items": items }))
.send()
.await?;
assert_eq!(r.status(), 400);
// A pipeline node based on a version the target lacks would fail Deploy all there: refused,
// and the source keeps it. One based on a version the target has moves.
let pipeline = |hash: &str| json!({ "drafts": [["f/p/n", { "localId": "n", "script": { "path": "f/p/n", "hash": hash } }]] });
for (path, hash) in [
("f/p_stale", "00000000000abcde"),
("f/p_ok", "ffffffffffffffff"),
] {
sqlx::query(
"INSERT INTO draft (workspace_id, path, typ, value, email) VALUES ($1, $2, 'data_pipeline', $3, $4)",
)
.bind(WS)
.bind(path)
.bind(pipeline(hash))
.bind(me)
.execute(&db)
.await?;
}
let move_pipeline = |path: &'static str| {
c.post(&transfer_url)
.json(&json!({
"target_workspace": fork,
"items": [{ "kind": "data_pipeline", "path": path }],
"remove_from_source": true
}))
.send()
};
let r = move_pipeline("f/p_stale").await?;
assert_eq!(r.status(), 400, "{}", r.text().await?);
assert_eq!(draft_count(&db, "f/p_stale", "data_pipeline", me).await, 1);
assert_eq!(fork_count("f/p_stale").await?, 0);
let r = move_pipeline("f/p_ok").await?;
assert_eq!(r.status(), 200, "{}", r.text().await?);
assert_eq!(fork_count("f/p_ok").await?, 1);
Ok(())
}