mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-12-03 16:10:37 +00:00
Merge session-s3-files-tool into session-s3-query-table
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "1.894.1"
|
||||
".": "1.895.1"
|
||||
}
|
||||
|
||||
@@ -1,5 +1,31 @@
|
||||
# Changelog
|
||||
|
||||
## [1.895.1](https://github.com/windmill-labs/windmill/compare/v1.895.0...v1.895.1) (2026-12-02)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* reconnect GCP pull triggers whose streaming pull stops ([#12805](https://github.com/windmill-labs/windmill/issues/12805)) ([de40457](https://github.com/windmill-labs/windmill/commit/de40457c34de45037cfdd3eb89eac71d528156d4))
|
||||
|
||||
## [1.895.0](https://github.com/windmill-labs/windmill/compare/v1.894.1...v1.895.0) (2026-12-02)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* count MCP token shapes and URLs, offer an upgrade ([#12782](https://github.com/windmill-labs/windmill/issues/12782)) ([f8e049d](https://github.com/windmill-labs/windmill/commit/f8e049d426de144c084f93cf334a229430a654d7))
|
||||
* let MCP clients see the images a run returns ([#12674](https://github.com/windmill-labs/windmill/issues/12674)) ([67e5de0](https://github.com/windmill-labs/windmill/commit/67e5de0892e10efcf1b384a80f9cd4935b5503df))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* keep edited scopes of an MCP sign-in across token refreshes ([#12781](https://github.com/windmill-labs/windmill/issues/12781)) ([442ac5b](https://github.com/windmill-labs/windmill/commit/442ac5bfeb2c820d630c0b4a6f83d3717b2676df))
|
||||
* keep typographic quotes in powershell arguments ([#12780](https://github.com/windmill-labs/windmill/issues/12780)) ([9a3fd38](https://github.com/windmill-labs/windmill/commit/9a3fd388ec841f089449a33103d825804849228c))
|
||||
* let external jwt viewers render sandboxed apps ([#12807](https://github.com/windmill-labs/windmill/issues/12807)) ([e6dbc5d](https://github.com/windmill-labs/windmill/commit/e6dbc5dd7963dc9f41e53b477ead3ccaeb080b96))
|
||||
* load sandboxed raw apps behind a cookie-authenticated proxy ([#12787](https://github.com/windmill-labs/windmill/issues/12787)) ([9312b08](https://github.com/windmill-labs/windmill/commit/9312b08e9a2bb3a59d8235f0f60dafa47e4bb0c0))
|
||||
* read drafts in a folder just created through another token ([#12778](https://github.com/windmill-labs/windmill/issues/12778)) ([b0f7573](https://github.com/windmill-labs/windmill/commit/b0f7573a66876423e856ea96f606e4830a32d3c5))
|
||||
* render public apps unsandboxed for external jwt viewers ([#12806](https://github.com/windmill-labs/windmill/issues/12806)) ([f6c9f55](https://github.com/windmill-labs/windmill/commit/f6c9f55dfdcfe5d1d7557b3f3781fee87ab47089))
|
||||
* sign resume urls with a dedicated key ([#12797](https://github.com/windmill-labs/windmill/issues/12797)) ([994f9b8](https://github.com/windmill-labs/windmill/commit/994f9b8b27929538b0d3bc6f60bc2691b61dc089))
|
||||
|
||||
## [1.894.1](https://github.com/windmill-labs/windmill/compare/v1.894.0...v1.894.1) (2026-12-01)
|
||||
|
||||
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT name, (extra_perms ->> $2)::boolean AS \"grant\",\n $2 = ANY(owners) AS \"target_owner!\", NULL::text AS blocked\n FROM folder WHERE workspace_id = $1 ORDER BY name",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "name",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "grant",
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "target_owner!",
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "blocked",
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
null,
|
||||
null,
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "0ca9b2930531c353b953379061c7d6576977c5d7dac388a5d831c39a81076002"
|
||||
}
|
||||
+10
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\"\n FROM folder WHERE workspace_id = $1 AND name = ANY($2)",
|
||||
"query": "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\",\n (extra_perms ->> $4)::boolean AS \"grant\"\n FROM folder WHERE workspace_id = $1 AND name = ANY($2)",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -12,19 +12,26 @@
|
||||
"ordinal": 1,
|
||||
"name": "via!",
|
||||
"type_info": "TextArray"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "grant",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"TextArray",
|
||||
"TextArray"
|
||||
"TextArray",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
null,
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41"
|
||||
"hash": "15aa703d8684daadc959a0b04f8316f8f78ffa741edaaa7d94448bcc6836ffd7"
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT EXISTS (SELECT 1 FROM v2_job j, _sqlx_migrations m\n WHERE j.id = $1 AND j.workspace_id = $2 AND m.version = $3\n AND j.created_at < m.installed_on + interval '1 day') AS \"accepted!\"",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "accepted!",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid",
|
||||
"Text",
|
||||
"Int8"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "9a4aaac681b1eeb2a718d7cd05170d05f559d20a91c15e0ca629dd882db5d4b8"
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE mcp_oauth_refresh_token SET scopes = $1 WHERE access_token_hash = $2",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"TextArray",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "a90e708b76103d064432f69a5b7395ed698b5249e3a6a0b1f31498b4cf6945ee"
|
||||
}
|
||||
Generated
+287
-169
File diff suppressed because it is too large
Load Diff
+4
-2
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "windmill"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
@@ -88,7 +88,7 @@ members = [
|
||||
exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
authors = ["Ruben Fiszel <ruben@windmill.dev>"]
|
||||
edition = "2021"
|
||||
|
||||
@@ -618,6 +618,8 @@ once_cell = "1.17.1"
|
||||
dashmap = "6.1.0"
|
||||
gosyn = "0.2.6"
|
||||
bytes = "1.4.0"
|
||||
image = { version = "0.25.10", default-features = false, features = ["gif", "jpeg", "png", "webp"] }
|
||||
image-webp = "0.2.4"
|
||||
gethostname = "0.4.3"
|
||||
# Not pinned exactly: the excluded `parsers/windmill-parser-wasm` workspace pins
|
||||
# =0.2.103 to match its vendored `cli/wasm/*` artifacts, yet path-depends on
|
||||
|
||||
@@ -1 +1 @@
|
||||
84303c10a4d26410624ff5adc93d09ff8adc2f8a
|
||||
3dc5c2c69dd2e690c78e15498093627447aaafcb
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
SELECT 1;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- No schema change: the `installed_on` of this migration dates the resume key on this instance (see
|
||||
-- `RESUME_KEY_MIGRATION`). Do not edit, squash or re-record it, that would move the date.
|
||||
SELECT 1;
|
||||
+24
-24
@@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "windmill-common"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"aho-corasick",
|
||||
@@ -6430,7 +6430,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-macros"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -6442,7 +6442,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"convert_case",
|
||||
"serde",
|
||||
@@ -6451,7 +6451,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-bash"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6463,7 +6463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-csharp"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde_json",
|
||||
@@ -6475,7 +6475,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-go"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"gosyn",
|
||||
@@ -6487,7 +6487,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-graphql"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6499,7 +6499,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-java"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde_json",
|
||||
@@ -6511,7 +6511,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-nu"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"nu-parser",
|
||||
@@ -6522,7 +6522,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-php"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.14.0",
|
||||
@@ -6533,7 +6533,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-py"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.14.0",
|
||||
@@ -6545,7 +6545,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-py-asset"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ruff_python_ast",
|
||||
@@ -6556,7 +6556,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-py-imports"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-recursion",
|
||||
@@ -6579,7 +6579,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-r"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde_json",
|
||||
@@ -6591,7 +6591,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-ruby"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6605,7 +6605,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-rust"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"convert_case",
|
||||
@@ -6622,7 +6622,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-sql"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6635,7 +6635,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-sql-asset"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde",
|
||||
@@ -6647,7 +6647,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-ts"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6665,7 +6665,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-ts-asset"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde-wasm-bindgen",
|
||||
@@ -6681,7 +6681,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-wac"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ruff_python_ast",
|
||||
@@ -6698,7 +6698,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-wasm"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"getrandom 0.2.17",
|
||||
@@ -6730,7 +6730,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-yaml"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6744,7 +6744,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-types"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags",
|
||||
|
||||
@@ -12,7 +12,7 @@ resolver = "2"
|
||||
members = ["."]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
edition = "2021"
|
||||
authors = ["Ruben Fiszel <ruben@windmill.dev>"]
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
//! Another member's access lists paths the caller may not be able to read, so only a workspace
|
||||
//! admin may ask for it.
|
||||
//!
|
||||
//! The auth cache is process-wide and keyed by workspace and token, so a test that gives
|
||||
//! test-user-2 other groups or folders than another test does signs in with a token of its own.
|
||||
|
||||
use sqlx::{Pool, Postgres};
|
||||
|
||||
@@ -64,3 +67,68 @@ async fn test_member_cannot_read_another_members_access(db: Pool<Postgres>) -> a
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The navigator writes grants with the kind it is given, and `acls/add` sends a full-code app's
|
||||
/// change to git sync only under `raw_app`. `blocked` must refuse what `acls/add` would refuse.
|
||||
#[sqlx::test(fixtures("base"))]
|
||||
async fn test_browse_items_kind_and_blocked(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
sqlx::raw_sql(
|
||||
"INSERT INTO folder (workspace_id, name, display_name, owners, extra_perms, created_by)
|
||||
VALUES ('test-workspace', 'fin', 'fin', '{u/test-user}', '{\"u/test-user-2\": false}', 'test-user');
|
||||
INSERT INTO app (id, workspace_id, path, summary, policy, versions, extra_perms)
|
||||
VALUES (1, 'test-workspace', 'f/fin/dash', '', '{}', '{1}', '{}');
|
||||
INSERT INTO app_version (id, app_id, value, created_by, raw_app)
|
||||
VALUES (1, 1, '{}', 'test-user', true);
|
||||
INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin)
|
||||
VALUES (encode(sha256('BROWSE_TOKEN'::bytea), 'hex'), 'BROWSE_TOK', 'BROWSE_TOKEN',
|
||||
'test2@windmill.dev', 'browse', false);",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let url = format!(
|
||||
"http://localhost:{}/api/w/test-workspace/access/browse_items",
|
||||
server.addr.port()
|
||||
);
|
||||
let browse = |token: &str| {
|
||||
reqwest::Client::new()
|
||||
.get(&url)
|
||||
.query(&[("principal", "u/test-user-2"), ("prefix", "f/fin/")])
|
||||
.header("Authorization", format!("Bearer {token}"))
|
||||
.send()
|
||||
};
|
||||
|
||||
let member: serde_json::Value = browse("BROWSE_TOKEN")
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.json()
|
||||
.await?;
|
||||
assert_eq!(
|
||||
member["items"],
|
||||
serde_json::json!([{
|
||||
"kind": "raw_app",
|
||||
"path": "f/fin/dash",
|
||||
"grant": null,
|
||||
"blocked": "Only admins of the workspace or of f/fin can share it"
|
||||
}])
|
||||
);
|
||||
|
||||
let admin: serde_json::Value = browse("SECRET_TOKEN")
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.json()
|
||||
.await?;
|
||||
assert_eq!(admin["items"][0]["blocked"], serde_json::Value::Null);
|
||||
|
||||
// A mistyped principal is refused rather than listed as holding nothing.
|
||||
let resp = reqwest::Client::new()
|
||||
.get(&url)
|
||||
.query(&[("principal", "g/does_not_exist")])
|
||||
.header("Authorization", "Bearer SECRET_TOKEN")
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 404, "{}", resp.text().await?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
//! A viewer authenticated by an external JWT (`jwt_ext_`) has no `usr` row, yet is a
|
||||
//! 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.
|
||||
|
||||
#![cfg(all(feature = "enterprise", feature = "private"))]
|
||||
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
|
||||
use serde_json::json;
|
||||
use sqlx::{Pool, Postgres};
|
||||
use windmill_test_utils::*;
|
||||
|
||||
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/mq7pGGrtpdBOsUUR9kDKV4b2b0AB3+itsfra3YXQz7aKhy7DSCdzM/iz7sy\n/mnfKuLJm8CNDApWmQIZpj+TMWHUWaZPqQtLFnTVnbu/lYrMevKs6o62AgQaVH1i\n/kVHlXl/r5M0ASagT2l9CcXjYQKBgQDatPRN5T/wcikjA1nxOvr+6L5vBiSwSvoJ\nIUGZ5qjvE4z09BrwUnsCtxsmCQ1i3zmCEP/p9AkUgAVPtP9dcF8TJECtp1S6CVx6\n6Qu6z+nimUTW1bGYd3KMZ+XKa1Uml0cliF9/wxnbRJdBsLQAqxxlN2G7guHZs/PI\nVGMGth6bYwKBgHzXaeu3fXuyizQA6VWWH9Tcpe7c8KTItRVscRXdic85BYD8PAo8\nrtCAwIaPxoRMHXNAvxzaqpvNaFRp3720c6mZaBjB2/nqxWMy+cj0MdIJDVHY5Gne\nOj4gOwcnFWRLgSp9y+evWATiwVi1I783D/w3KKgM6h9ChwPGCVBLvtRhAoGBAJtl\n0+i9KW9JTl1odjHnPIx/B0CP1uXEgGCYVqppsEMfWxp5j+KOWIUXYZzm9bH49j2q\noouzL/h29k8qRgA4ZfWN3r8ElDkTibhzejgknwS47qbPc77nsGZ/NFFdbkVbW9wZ\nR/HZyLd5xxeP3HZVHnn0nebEGoG7UU5YV3xfTuQNAoGBALKl0/GGg8A52+pV/0z1\n4ZSaP0/wBBk6IKMHCLM+4/2hWoNMW8SndD8HYegJ9TunxOGhuC0sXC0r/fAJ3HF8\nAjtlFwVPfLONjHEWwOG8ll77K9jy5eBDL+csySOHqHI9wzIyxSzKg65uDkIiP0ni\ndOQkC+Yq6YYGhMoOQShezBfm\n-----END PRIVATE KEY-----\n";
|
||||
const PUB: &str = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1tPlUDdvmztmQJVy2iYA\n7zsVi/GLfCQIysbQbqBF5uyykpU0WP+SFz7XzbuTaMGLtn1vuClIfPZkOIIOKFel\ne5EtqjgRFAuDg5Mcinzjn7vp/rk4mbnw/sXpWsNgApQRcPL8wiHc2aH1CfBiUvVD\nXRLVEmKs54FdkDmzf3IDedCUSbcprG84IqDpLxMRmWPahTgqccbbDAWvx+psFz6Q\nDOHTuHGau+2i5/XqwY4AS+SmmGaB4zDkqFkQnGPZnYF8fxaEd+EpNJIVRdSRQM9Y\nw/N/mIfWP7Jcwg9gy/+vhh2tZTcKWig7GAEMrYRyLRK5yiiarGmsXah6lCxjM5Cp\ngwIDAQAB\n-----END PUBLIC KEY-----\n";
|
||||
|
||||
async fn create_app(
|
||||
client: &reqwest::Client,
|
||||
db: &Pool<Postgres>,
|
||||
ws: &str,
|
||||
path: &str,
|
||||
sandbox: bool,
|
||||
) -> anyhow::Result<String> {
|
||||
let resp = client
|
||||
.post(format!("{ws}/apps/create"))
|
||||
.header("Authorization", "Bearer SECRET_TOKEN")
|
||||
.json(&json!({
|
||||
"path": path,
|
||||
"summary": "Embedded with an external JWT",
|
||||
"value": {},
|
||||
"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(path)
|
||||
.execute(db)
|
||||
.await?;
|
||||
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<serde_json::Value> {
|
||||
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<Postgres>) -> 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(
|
||||
&Header::new(Algorithm::RS256),
|
||||
&json!({
|
||||
"email": "embedded@example.com",
|
||||
"username": "embedded",
|
||||
"is_admin": false,
|
||||
"is_operator": false,
|
||||
"groups": ["all"],
|
||||
"folders": [],
|
||||
"workspace_id": "test-workspace",
|
||||
"exp": exp,
|
||||
}),
|
||||
&EncodingKey::from_rsa_pem(PRIV.as_bytes())?,
|
||||
)?;
|
||||
let viewer = format!("jwt_ext_{jwt}");
|
||||
|
||||
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<chrono::Utc> =
|
||||
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)
|
||||
.await?;
|
||||
assert_eq!(tokens, 0);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! A draft read in a folder the caller just created works at once, from any of their tokens.
|
||||
//!
|
||||
//! The AI session tools create the folder through one token (a JWT minted per tool call) and
|
||||
//! read the draft through another, whose identity was cached before the folder existed. The
|
||||
//! folder has no deployed item yet, so nothing but the caller's folder set can admit the read.
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use sqlx::{Pool, Postgres};
|
||||
|
||||
use windmill_test_utils::*;
|
||||
|
||||
#[sqlx::test(fixtures("base"))]
|
||||
async fn test_draft_read_in_folder_created_through_another_token(
|
||||
db: Pool<Postgres>,
|
||||
) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
sqlx::query(
|
||||
"INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin)
|
||||
VALUES (encode(sha256('SECOND_TOKEN_2'::bytea), 'hex'), 'SECOND_TOK', 'SECOND_TOKEN_2',
|
||||
'test2@windmill.dev', 'second token', false)",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let base = format!(
|
||||
"http://localhost:{}/api/w/test-workspace",
|
||||
server.addr.port()
|
||||
);
|
||||
let client = reqwest::Client::new();
|
||||
let read = || {
|
||||
client
|
||||
.get(format!("{base}/drafts/get_own/script/f/fresh/hello"))
|
||||
.header("Authorization", "Bearer SECOND_TOKEN_2")
|
||||
.send()
|
||||
};
|
||||
|
||||
// Caches the second token's identity, without the folder.
|
||||
assert_eq!(read().await?.status(), 404);
|
||||
|
||||
let resp = client
|
||||
.post(format!("{base}/folders/create"))
|
||||
.header("Authorization", "Bearer SECRET_TOKEN_2")
|
||||
.json(&json!({ "name": "fresh" }))
|
||||
.send()
|
||||
.await?;
|
||||
assert!(resp.status().is_success(), "{}", resp.text().await?);
|
||||
|
||||
let resp = read().await?;
|
||||
let status = resp.status();
|
||||
let body = resp.text().await?;
|
||||
assert_eq!(status, 200, "draft read in the new folder refused: {body}");
|
||||
assert_eq!(serde_json::from_str::<Value>(&body)?, Value::Null);
|
||||
Ok(())
|
||||
}
|
||||
@@ -289,7 +289,6 @@ async fn wac_concurrent_colliding_mints_admit_exactly_one(
|
||||
async fn resume_signatures_are_bound_to_the_run_and_its_workspace(
|
||||
db: Pool<Postgres>,
|
||||
) -> anyhow::Result<()> {
|
||||
use hmac::Mac;
|
||||
initialize_tracing().await;
|
||||
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
@@ -330,10 +329,12 @@ async fn resume_signatures_are_bound_to_the_run_and_its_workspace(
|
||||
}
|
||||
}
|
||||
|
||||
let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(b"test-key-2")?;
|
||||
mac.update(uuid::Uuid::parse_str(WAC_JOB)?.as_bytes());
|
||||
mac.update(&5u32.to_be_bytes());
|
||||
let foreign = hex::encode(mac.finalize().into_bytes());
|
||||
let foreign = windmill_common::variables::resume_signature(
|
||||
"test-key-2",
|
||||
uuid::Uuid::parse_str(WAC_JOB)?,
|
||||
5,
|
||||
None,
|
||||
)?;
|
||||
for op in ["resume", "cancel"] {
|
||||
let status = client
|
||||
.post(format!(
|
||||
|
||||
@@ -206,8 +206,12 @@ impl AuthCache {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn invalidate(&self, w_id: &str, token: String) {
|
||||
AUTH_CACHE.remove(&(w_id.to_string(), token));
|
||||
/// Drops every cached identity of `email`, whatever token it was resolved from. A change
|
||||
/// to what the user can reach must reach all of them: the AI session tools act through a
|
||||
/// JWT minted from the caller's cached identity, so the token presenting the change is
|
||||
/// not the one that will present the next request.
|
||||
pub fn invalidate_user(&self, email: &str) {
|
||||
AUTH_CACHE.retain(|_, cached| cached.authed.email != email);
|
||||
}
|
||||
|
||||
/// `client_ip` is the address of the request presenting `token` (`ClientIp`), `None` outside
|
||||
|
||||
@@ -93,9 +93,10 @@ pub struct ApiAuthed {
|
||||
/// superadmin (`require_super_admin`), GHSA-hfh4-cx4h-3fcr.
|
||||
pub job_id: Option<uuid::Uuid>,
|
||||
/// 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<chrono::DateTime<chrono::Utc>>,
|
||||
/// 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`.
|
||||
|
||||
@@ -18,14 +18,20 @@ use windmill_api_auth::ApiAuthed;
|
||||
use windmill_common::{
|
||||
auth::fetch_authed_from_permissioned_as,
|
||||
db::UserDB,
|
||||
error::{Error, JsonResult},
|
||||
error::{Error, JsonResult, Result},
|
||||
workspaces::{check_operator_can_manage, ManageKind},
|
||||
DB,
|
||||
};
|
||||
|
||||
pub fn workspaced_service() -> Router {
|
||||
Router::new().route("/get", get(get_access))
|
||||
Router::new()
|
||||
.route("/get", get(get_access))
|
||||
.route("/browse_folders", get(browse_folders))
|
||||
.route("/browse_items", get(browse_items))
|
||||
}
|
||||
|
||||
const BROWSE_PAGE: i64 = 100;
|
||||
|
||||
/// `(kind, table, extra filter)`. Captures, capture configs and eval datasets are left out on
|
||||
/// purpose: they are test data attached to an item, not something access is granted to.
|
||||
const ITEM_TABLES: [(&str, &str, &str); 17] = [
|
||||
@@ -74,6 +80,12 @@ struct FolderAccess {
|
||||
owner: bool,
|
||||
/// The `extra_perms` keys (`u/<user>` or `g/<group>`) that grant the folder.
|
||||
via: Vec<String>,
|
||||
/// The principal's own entry in `extra_perms`: absent when none, false for read, true for write.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
grant: Option<bool>,
|
||||
/// Why the caller cannot change the principal's own entry. Set only where there is one.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
blocked: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -82,6 +94,9 @@ struct ItemAccess {
|
||||
path: String,
|
||||
write: bool,
|
||||
reasons: Vec<Reason>,
|
||||
/// Why the caller cannot change the principal's own grant. Set only where there is one.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
blocked: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -112,12 +127,27 @@ struct ItemRow {
|
||||
folder_write: bool,
|
||||
}
|
||||
|
||||
/// The `kind` column for a row of `table`. Full-code apps live in `app` too, but their grants must
|
||||
/// be written with kind `raw_app`, which git sync dispatches to `<path>.raw_app` rather than `.app`.
|
||||
fn kind_column(kind: &str, table: &str) -> String {
|
||||
if kind == "app" {
|
||||
format!(
|
||||
"CASE WHEN (SELECT raw_app FROM app_version \
|
||||
WHERE id = {table}.versions[array_upper({table}.versions, 1)]) \
|
||||
THEN 'raw_app' ELSE 'app' END"
|
||||
)
|
||||
} else {
|
||||
format!("'{kind}'::text")
|
||||
}
|
||||
}
|
||||
|
||||
fn items_query() -> String {
|
||||
let union = ITEM_TABLES
|
||||
.iter()
|
||||
.map(|(kind, table, filter)| {
|
||||
let kind = kind_column(kind, table);
|
||||
format!(
|
||||
"SELECT '{kind}'::text AS kind, path::text AS path, extra_perms FROM {table} \
|
||||
"SELECT {kind} AS kind, path::text AS path, extra_perms FROM {table} \
|
||||
WHERE workspace_id = $1 {filter}"
|
||||
)
|
||||
})
|
||||
@@ -175,20 +205,15 @@ impl From<ItemRow> for ItemAccess {
|
||||
*write
|
||||
}
|
||||
});
|
||||
ItemAccess { kind: r.kind, path: r.path, write, reasons }
|
||||
ItemAccess { kind: r.kind, path: r.path, write, reasons, blocked: None }
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_access(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(AccessQuery { principal }): Query<AccessQuery>,
|
||||
) -> JsonResult<AccessReport> {
|
||||
/// Splits `u/<user>` or `g/<group>` and refuses callers who may not look at that principal.
|
||||
fn check_principal<'a>(authed: &ApiAuthed, principal: &'a str) -> Result<(&'a str, &'a str)> {
|
||||
let (prefix, name) = principal
|
||||
.split_once('/')
|
||||
.filter(|(_, name)| !name.is_empty())
|
||||
.filter(|(prefix, name)| matches!(*prefix, "u" | "g") && !name.is_empty())
|
||||
.ok_or_else(|| Error::BadRequest("principal must be u/<user> or g/<group>".into()))?;
|
||||
|
||||
// Another principal's list names paths the caller may not be able to read. A group's reach is
|
||||
@@ -196,8 +221,7 @@ async fn get_access(
|
||||
let allowed = authed.is_admin
|
||||
|| match prefix {
|
||||
"u" => name == authed.username,
|
||||
"g" => authed.groups.iter().any(|g| g == name),
|
||||
_ => false,
|
||||
_ => authed.groups.iter().any(|g| g == name),
|
||||
};
|
||||
if !allowed {
|
||||
return Err(Error::PermissionDenied(
|
||||
@@ -205,15 +229,36 @@ async fn get_access(
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
Ok((prefix, name))
|
||||
}
|
||||
|
||||
let email = match prefix {
|
||||
/// The principal as it would be authenticated, with its groups and the folders it reaches.
|
||||
async fn fetch_target(
|
||||
db: &DB,
|
||||
w_id: &str,
|
||||
prefix: &str,
|
||||
name: &str,
|
||||
principal: &str,
|
||||
) -> Result<windmill_common::db::Authed> {
|
||||
let email = target_email(db, w_id, prefix, name).await?;
|
||||
let mut target = fetch_authed_from_permissioned_as(principal, &email, w_id, db).await?;
|
||||
// A workspace group and an instance group can share a name, and both come back.
|
||||
target.groups.sort();
|
||||
target.groups.dedup();
|
||||
Ok(target)
|
||||
}
|
||||
|
||||
/// The principal's email, empty for a group. Not found when the principal does not exist, so
|
||||
/// no route answers for a mistyped one as if it existed with no grants.
|
||||
async fn target_email(db: &DB, w_id: &str, prefix: &str, name: &str) -> Result<String> {
|
||||
Ok(match prefix {
|
||||
"u" => {
|
||||
let usr = sqlx::query!(
|
||||
"SELECT email, disabled FROM usr WHERE workspace_id = $1 AND username = $2",
|
||||
&w_id,
|
||||
w_id,
|
||||
name
|
||||
)
|
||||
.fetch_optional(&db)
|
||||
.fetch_optional(db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::NotFound(format!("user {name} not found")))?;
|
||||
if usr.disabled {
|
||||
@@ -224,15 +269,15 @@ async fn get_access(
|
||||
usr.email
|
||||
}
|
||||
"g" => {
|
||||
// Instance groups are granted through the same `g/<name>` keys, and the check above
|
||||
// Instance groups are granted through the same `g/<name>` keys, and the callers' check
|
||||
// lets their members ask, so a name from either table is a group here.
|
||||
let exists = sqlx::query_scalar!(
|
||||
"SELECT EXISTS(SELECT 1 FROM group_ WHERE workspace_id = $1 AND name = $2)
|
||||
OR EXISTS(SELECT 1 FROM instance_group WHERE name = $2)",
|
||||
&w_id,
|
||||
w_id,
|
||||
name
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.fetch_one(db)
|
||||
.await?
|
||||
.unwrap_or(false);
|
||||
if !exists {
|
||||
@@ -245,12 +290,19 @@ async fn get_access(
|
||||
"principal must be u/<user> or g/<group>".into(),
|
||||
))
|
||||
}
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
let mut target = fetch_authed_from_permissioned_as(&principal, &email, &w_id, &db).await?;
|
||||
// A workspace group and an instance group can share a name, and both come back.
|
||||
target.groups.sort();
|
||||
target.groups.dedup();
|
||||
async fn get_access(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(AccessQuery { principal }): Query<AccessQuery>,
|
||||
) -> JsonResult<AccessReport> {
|
||||
let (prefix, name) = check_principal(&authed, &principal)?;
|
||||
|
||||
let target = fetch_target(&db, &w_id, prefix, name, &principal).await?;
|
||||
|
||||
if target.is_admin {
|
||||
return Ok(Json(AccessReport {
|
||||
@@ -276,38 +328,54 @@ async fn get_access(
|
||||
.map(|f| f.0.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut via = sqlx::query!(
|
||||
"SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\"
|
||||
"SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\",
|
||||
(extra_perms ->> $4)::boolean AS \"grant\"
|
||||
FROM folder WHERE workspace_id = $1 AND name = ANY($2)",
|
||||
&w_id,
|
||||
&folder_names,
|
||||
&perms
|
||||
&perms,
|
||||
&principal
|
||||
)
|
||||
.fetch_all(&db)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|r| (r.name, r.via))
|
||||
.map(|r| (r.name, (r.via, r.grant)))
|
||||
.collect::<std::collections::HashMap<_, _>>();
|
||||
let mut folders = target
|
||||
.folders
|
||||
.iter()
|
||||
.map(|(name, write, owner)| FolderAccess {
|
||||
name: name.clone(),
|
||||
write: *write,
|
||||
owner: *owner,
|
||||
via: via.remove(name).unwrap_or_default(),
|
||||
.map(|(name, write, owner)| {
|
||||
let (via, grant) = via.remove(name).unwrap_or_default();
|
||||
// An owner keeps write whatever its entry says, so there is nothing to change.
|
||||
let blocked =
|
||||
(grant.is_some() && !*owner && !windmill_api_auth::is_owner(&authed, name))
|
||||
.then(|| folder_blocked(name));
|
||||
FolderAccess { name: name.clone(), write: *write, owner: *owner, via, grant, blocked }
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
folders.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
|
||||
let mut tx = user_db.begin(&target).await?;
|
||||
let items = sqlx::query_as::<_, ItemRow>(&items_query())
|
||||
let rows = sqlx::query_as::<_, ItemRow>(&items_query())
|
||||
.bind(&w_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(ItemAccess::from)
|
||||
.collect();
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
let denied = manage_denied(&db, &w_id, &authed).await?;
|
||||
let items = rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let direct = match prefix {
|
||||
"u" => r.user_grant.is_some(),
|
||||
_ => r.group_read.iter().any(|g| g == name),
|
||||
};
|
||||
let mut item = ItemAccess::from(r);
|
||||
if direct {
|
||||
item.blocked = item_blocked(&authed, &denied, &item.kind, &item.path);
|
||||
}
|
||||
item
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Json(AccessReport {
|
||||
principal,
|
||||
@@ -317,3 +385,204 @@ async fn get_access(
|
||||
items,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct BrowseFolder {
|
||||
name: String,
|
||||
/// The principal's own entry in the folder's `extra_perms`: absent, read (false) or write.
|
||||
grant: Option<bool>,
|
||||
/// Owners always keep write; `acls/add` refuses to lower it.
|
||||
target_owner: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
blocked: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, sqlx::FromRow)]
|
||||
struct BrowseItem {
|
||||
kind: String,
|
||||
path: String,
|
||||
grant: Option<bool>,
|
||||
#[sqlx(skip)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
blocked: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct BrowseItems {
|
||||
items: Vec<BrowseItem>,
|
||||
has_more: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct BrowseItemsQuery {
|
||||
principal: String,
|
||||
/// Only paths starting with this, e.g. `f/billing/` or `u/alice/`.
|
||||
prefix: Option<String>,
|
||||
kind: Option<String>,
|
||||
search: Option<String>,
|
||||
offset: Option<i64>,
|
||||
}
|
||||
|
||||
/// Why the caller cannot change grants on `path`, mirroring the checks `acls/add` makes.
|
||||
fn grant_blocked(authed: &ApiAuthed, path: &str) -> Option<String> {
|
||||
if authed.is_admin {
|
||||
return None;
|
||||
}
|
||||
let mut parts = path.splitn(3, '/');
|
||||
match (parts.next(), parts.next()) {
|
||||
(Some("u"), Some(owner)) if owner == authed.username => None,
|
||||
(Some("u"), Some(owner)) => {
|
||||
Some(format!("Only u/{owner} and workspace admins can share it"))
|
||||
}
|
||||
(Some("f"), Some(folder)) if windmill_api_auth::is_owner(authed, folder) => None,
|
||||
(Some("f"), Some(folder)) => Some(folder_blocked(folder)),
|
||||
_ => Some("Only workspace admins can share items under g/".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn folder_blocked(folder: &str) -> String {
|
||||
format!("Only admins of the workspace or of f/{folder} can share it")
|
||||
}
|
||||
|
||||
async fn browse_folders(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(AccessQuery { principal }): Query<AccessQuery>,
|
||||
) -> JsonResult<Vec<BrowseFolder>> {
|
||||
let (prefix, name) = check_principal(&authed, &principal)?;
|
||||
// Ownership can come through one of the principal's groups, as in `/access/get`.
|
||||
let target = fetch_target(&db, &w_id, prefix, name, &principal).await?;
|
||||
let owned = target
|
||||
.folders
|
||||
.iter()
|
||||
.filter(|(_, _, owner)| *owner)
|
||||
.map(|(name, ..)| name.as_str())
|
||||
.collect::<std::collections::HashSet<_>>();
|
||||
let mut tx = user_db.begin(&authed).await?;
|
||||
let mut folders = sqlx::query_as!(
|
||||
BrowseFolder,
|
||||
"SELECT name, (extra_perms ->> $2)::boolean AS \"grant\",
|
||||
$2 = ANY(owners) AS \"target_owner!\", NULL::text AS blocked
|
||||
FROM folder WHERE workspace_id = $1 ORDER BY name",
|
||||
&w_id,
|
||||
&principal
|
||||
)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
for folder in &mut folders {
|
||||
folder.target_owner |= owned.contains(folder.name.as_str());
|
||||
if !windmill_api_auth::is_owner(&authed, &folder.name) {
|
||||
folder.blocked = Some(folder_blocked(&folder.name));
|
||||
}
|
||||
}
|
||||
Ok(Json(folders))
|
||||
}
|
||||
|
||||
async fn browse_items(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(q): Query<BrowseItemsQuery>,
|
||||
) -> JsonResult<BrowseItems> {
|
||||
let (prefix, name) = check_principal(&authed, &q.principal)?;
|
||||
target_email(&db, &w_id, prefix, name).await?;
|
||||
let tables = ITEM_TABLES
|
||||
.iter()
|
||||
.filter(|(kind, ..)| {
|
||||
q.kind
|
||||
.as_deref()
|
||||
.map_or(true, |k| k == *kind || (k == "raw_app" && *kind == "app"))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if tables.is_empty() {
|
||||
return Err(Error::BadRequest("unknown kind".into()));
|
||||
}
|
||||
// SAFETY: table names and filters come from the `ITEM_TABLES` constant, never from the request.
|
||||
let union = tables
|
||||
.iter()
|
||||
.map(|(kind, table, filter)| {
|
||||
let kind = kind_column(kind, table);
|
||||
format!(
|
||||
"SELECT {kind} AS kind, path::text AS path, (extra_perms ->> $2)::boolean AS \"grant\"
|
||||
FROM {table} WHERE workspace_id = $1 {filter}"
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" UNION ALL ");
|
||||
let sql = format!(
|
||||
"SELECT kind, path, \"grant\" FROM ({union}) i
|
||||
WHERE ($3::text IS NULL OR starts_with(path, $3))
|
||||
AND ($4::text IS NULL OR strpos(lower(path), lower($4)) > 0)
|
||||
AND ($7::text IS NULL OR kind = $7)
|
||||
ORDER BY path, kind LIMIT $5 OFFSET $6"
|
||||
);
|
||||
let mut tx = user_db.begin(&authed).await?;
|
||||
let mut items = sqlx::query_as::<_, BrowseItem>(&sql)
|
||||
.bind(&w_id)
|
||||
.bind(&q.principal)
|
||||
.bind(q.prefix.as_deref().filter(|p| !p.is_empty()))
|
||||
.bind(q.search.as_deref().map(str::trim).filter(|s| !s.is_empty()))
|
||||
.bind(BROWSE_PAGE + 1)
|
||||
.bind(q.offset.unwrap_or(0).max(0))
|
||||
.bind(q.kind.as_deref())
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
let has_more = items.len() as i64 > BROWSE_PAGE;
|
||||
items.truncate(BROWSE_PAGE as usize);
|
||||
|
||||
let denied = manage_denied(&db, &w_id, &authed).await?;
|
||||
for item in &mut items {
|
||||
item.blocked = item_blocked(&authed, &denied, &item.kind, &item.path);
|
||||
}
|
||||
Ok(Json(BrowseItems { items, has_more }))
|
||||
}
|
||||
|
||||
/// Operators may be barred from managing schedules and triggers, `/acls` included.
|
||||
/// Only a refusal becomes a lock text; any other error (the role lookup failing) is returned, so
|
||||
/// an outage is not shown as a decision.
|
||||
async fn manage_denied(
|
||||
db: &DB,
|
||||
w_id: &str,
|
||||
authed: &ApiAuthed,
|
||||
) -> Result<Vec<(ManageKind, String)>> {
|
||||
let mut denied = vec![];
|
||||
if !authed.is_admin {
|
||||
for kind in [ManageKind::Schedules, ManageKind::Triggers] {
|
||||
match check_operator_can_manage(db, w_id, authed, kind).await {
|
||||
Ok(()) => {}
|
||||
// A plain sentence like the path rules' texts, so without the "Permission
|
||||
// denied: " prefix the error's display adds.
|
||||
Err(Error::PermissionDenied(reason)) => denied.push((kind, reason)),
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(denied)
|
||||
}
|
||||
|
||||
/// Why the caller cannot change grants on this item: the operator gate first, then the path.
|
||||
fn item_blocked(
|
||||
authed: &ApiAuthed,
|
||||
denied: &[(ManageKind, String)],
|
||||
kind: &str,
|
||||
path: &str,
|
||||
) -> Option<String> {
|
||||
let manage_kind = match kind {
|
||||
"schedule" => Some(ManageKind::Schedules),
|
||||
k if k.ends_with("_trigger") => Some(ManageKind::Triggers),
|
||||
_ => None,
|
||||
};
|
||||
manage_kind
|
||||
.and_then(|mk| {
|
||||
denied
|
||||
.iter()
|
||||
.find(|(k, _)| *k == mk)
|
||||
.map(|(_, e)| e.clone())
|
||||
})
|
||||
.or_else(|| grant_blocked(authed, path))
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use windmill_api_auth::{
|
||||
build_scope_path_filter, build_scope_path_predicate, check_scopes, ApiAuthed, AuthCache,
|
||||
ScopePathFilter, Tokened,
|
||||
ScopePathFilter,
|
||||
};
|
||||
use windmill_audit::audit_oss::{audit_log, AuditAuthorable};
|
||||
use windmill_audit::ActionKind;
|
||||
@@ -263,7 +263,6 @@ lazy_static! {
|
||||
|
||||
async fn create_folder(
|
||||
authed: ApiAuthed,
|
||||
Tokened { token }: Tokened,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Extension(webhook): Extension<WebhookShared>,
|
||||
@@ -295,7 +294,6 @@ async fn create_folder(
|
||||
)));
|
||||
}
|
||||
check_name_conflict(&mut tx, &w_id, &ng.name).await?;
|
||||
cache.invalidate(&w_id, token).await;
|
||||
let owner = username_to_permissioned_as(&authed.username);
|
||||
let owners = ng.owners.unwrap_or_else(|| vec![owner.clone()]);
|
||||
let owners = if owners.contains(&owner) {
|
||||
@@ -394,6 +392,8 @@ async fn create_folder(
|
||||
.await?;
|
||||
|
||||
tx.commit().await?;
|
||||
// After the commit: a request resolving the identity in between would cache the old folders.
|
||||
cache.invalidate_user(&authed.email);
|
||||
|
||||
handle_deployment_metadata(
|
||||
&authed.email,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Deleting an MCP OAuth access token revokes its refresh grant, and only that one; an access
|
||||
//! token removed by the expiry sweep keeps its grant refreshable, until its user is disabled.
|
||||
//! Editing an access token's scopes holds across refreshes.
|
||||
#![cfg(feature = "mcp")]
|
||||
|
||||
use serde_json::json;
|
||||
@@ -110,6 +111,27 @@ async fn test_deleted_mcp_token_cannot_refresh(db: Pool<Postgres>) -> anyhow::Re
|
||||
"invalid_grant"
|
||||
);
|
||||
|
||||
let (edited_client, edited_access, edited_refresh) = connect("SECRET_TOKEN").await?;
|
||||
// The last two leave the access token unrestricted, which the grant must not become.
|
||||
for scopes in [json!(["mcp:all", "mcp:read_only"]), json!([]), json!(null)] {
|
||||
let resp = http
|
||||
.post(format!(
|
||||
"{base}/users/tokens/update_scopes/{}",
|
||||
&edited_access[..10]
|
||||
))
|
||||
.bearer_auth("SECRET_TOKEN")
|
||||
.json(&json!({ "scopes": scopes }))
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
}
|
||||
let resp = refresh(&edited_client, &edited_refresh).await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
assert_eq!(
|
||||
resp.json::<serde_json::Value>().await?["scope"],
|
||||
"mcp:all mcp:read_only"
|
||||
);
|
||||
|
||||
expire_and_sweep(idle_access).await?;
|
||||
let resp = refresh(&idle_client, &idle_refresh).await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
use sqlx::{Pool, Postgres};
|
||||
use uuid::Uuid;
|
||||
use windmill_test_utils::*;
|
||||
|
||||
/// A suspended flow created `days` after now.
|
||||
async fn suspended_flow(db: &Pool<Postgres>, id: Uuid, days: i32) -> anyhow::Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO v2_job (id, workspace_id, created_by, permissioned_as, kind, tag, args, created_at)
|
||||
VALUES ($1, 'test-workspace', 'test-user', 'u/test-user', 'flow', 'flow', '{}'::jsonb,
|
||||
now() + make_interval(days => $2))",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(days)
|
||||
.execute(db)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, tag, running, suspend)
|
||||
VALUES ($1, 'test-workspace', now(), 'flow', true, 1)",
|
||||
)
|
||||
.bind(id)
|
||||
.execute(db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A signature made with the bare workspace key, which the fixture sets to `test-key`.
|
||||
fn bare_key_signature(job: Uuid, tail: &[u8]) -> String {
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(b"test-key").unwrap();
|
||||
mac.update(job.as_bytes());
|
||||
mac.update(tail);
|
||||
hex::encode(mac.finalize().into_bytes())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
|
||||
async fn resume_signatures_have_their_own_key(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let base = format!(
|
||||
"http://localhost:{}/api/w/test-workspace",
|
||||
server.addr.port()
|
||||
);
|
||||
let client = reqwest::Client::new();
|
||||
let resume = async |job: Uuid, resume_id: u32, sig: &str, approver: &str| {
|
||||
client
|
||||
.post(format!("{base}/jobs_u/resume/{job}/{resume_id}/{sig}"))
|
||||
.query(&[("approver", approver)])
|
||||
.json(&serde_json::json!({}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.status()
|
||||
.as_u16()
|
||||
};
|
||||
|
||||
// The layouts of the other messages the workspace key signs are not resume signatures.
|
||||
for (job_prefix, tail) in [
|
||||
("", "view_token"),
|
||||
("", "public_view_token"),
|
||||
("", "approval_token"),
|
||||
("file_key=0123456", "789&exp=4102444800"),
|
||||
("test-workspace:n", "extcloud:1:nonce:user"),
|
||||
("wm-fork-test:nex", "tcloud:1:nonce:user"),
|
||||
("test-workspace:g", "oogle:1:nonce"),
|
||||
("test-workspace:G", "oogle:1:nonce:path:user"),
|
||||
] {
|
||||
let job = Uuid::from_slice(job_prefix.as_bytes()).unwrap_or_else(|_| Uuid::new_v4());
|
||||
suspended_flow(&db, job, 0).await?;
|
||||
let sig = bare_key_signature(job, tail.as_bytes());
|
||||
let (resume_id, approver) = tail.split_at(4);
|
||||
let resume_id = u32::from_be_bytes(resume_id.as_bytes().try_into()?);
|
||||
assert!(
|
||||
resume(job, resume_id, &sig, approver).await >= 400,
|
||||
"{job_prefix}{tail}"
|
||||
);
|
||||
}
|
||||
|
||||
// Bare-key URLs already handed out keep working; a job created more than a day after the resume
|
||||
// key migration (which has just run here) only takes the new ones.
|
||||
for (days, takes_bare_key) in [(0, true), (2, false)] {
|
||||
let job = Uuid::new_v4();
|
||||
suspended_flow(&db, job, days).await?;
|
||||
let bare = bare_key_signature(job, b"\0\0\0\x01bob");
|
||||
assert_eq!(resume(job, 1, &bare, "bob").await == 201, takes_bare_key);
|
||||
|
||||
let job = Uuid::new_v4();
|
||||
suspended_flow(&db, job, days).await?;
|
||||
let sig = client
|
||||
.get(format!("{base}/jobs/job_signature/{job}/1?approver=bob"))
|
||||
.bearer_auth("SECRET_TOKEN")
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.text()
|
||||
.await?;
|
||||
assert_ne!(sig, bare_key_signature(job, b"\0\0\0\x01bob"));
|
||||
assert_eq!(resume(job, 1, &sig, "bob").await, 201);
|
||||
}
|
||||
|
||||
server.close().await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -4629,6 +4629,21 @@ async fn update_token_scopes(
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
// A refresh re-issues the grant's scopes. A grant is never left unrestricted, which an empty
|
||||
// list is too: it keeps its own scopes then.
|
||||
let restricted = req
|
||||
.scopes
|
||||
.as_deref()
|
||||
.filter(|s| !windmill_api_auth::is_effectively_unscoped(Some(s)));
|
||||
if let Some(scopes) = restricted {
|
||||
sqlx::query!(
|
||||
"UPDATE mcp_oauth_refresh_token SET scopes = $1 WHERE access_token_hash = $2",
|
||||
scopes,
|
||||
&token.token_hash,
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
let prefix = token_prefix;
|
||||
|
||||
let scopes_json = serde_json::to_string(&req.scopes).unwrap_or_default();
|
||||
|
||||
@@ -48,7 +48,7 @@ sqs_trigger = ["dep:windmill-trigger-sqs", "windmill-store/sqs_trigger"]
|
||||
gcp_trigger = ["dep:windmill-trigger-gcp", "windmill-store/gcp_trigger"]
|
||||
azure_trigger = ["dep:windmill-trigger-azure", "windmill-store/azure_trigger"]
|
||||
cloud = ["windmill-common/cloud", "windmill-api-auth/cloud", "windmill-store/cloud", "windmill-api-workspaces/cloud"]
|
||||
mcp = ["dep:windmill-mcp", "windmill-mcp/server", "windmill-mcp/auth", "windmill-api-auth/mcp", "windmill-store/mcp"]
|
||||
mcp = ["dep:windmill-mcp", "dep:image", "dep:image-webp", "windmill-mcp/server", "windmill-mcp/auth", "windmill-api-auth/mcp", "windmill-store/mcp"]
|
||||
bedrock = ["windmill-ai/bedrock"]
|
||||
python = ["windmill-dep-map/python", "dep:windmill-parser-py", "dep:windmill-parser-py-imports", "windmill-api-scripts/python", "windmill-api-configs/python", "windmill-api-agent-workers?/python", "windmill-trigger/python", "windmill-common/python"]
|
||||
no_auth = ["windmill-api-auth/no_auth", "windmill-store/no_auth", "windmill-api-users/no_auth"]
|
||||
@@ -107,6 +107,8 @@ chrono.workspace = true
|
||||
hex.workspace = true
|
||||
base64.workspace = true
|
||||
base32.workspace = true
|
||||
image = { workspace = true, optional = true }
|
||||
image-webp = { workspace = true, optional = true }
|
||||
serde_urlencoded.workspace = true
|
||||
serde_yml.workspace = true
|
||||
cron.workspace = true
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: "3.0.3"
|
||||
|
||||
info:
|
||||
version: 1.894.1
|
||||
version: 1.895.1
|
||||
title: Windmill API
|
||||
|
||||
contact:
|
||||
@@ -30,6 +30,10 @@ paths:
|
||||
/version:
|
||||
get:
|
||||
summary: get backend version
|
||||
description: |
|
||||
The edition and version (e.g. `EE v1.893.0`) for an authenticated caller. Without
|
||||
credentials it answers 200 with the edition alone (`EE` or `CE`), so it stays usable as a
|
||||
liveness probe.
|
||||
operationId: backendVersion
|
||||
tags:
|
||||
- settings
|
||||
@@ -26899,6 +26903,102 @@ paths:
|
||||
schema:
|
||||
$ref: "#/components/schemas/PrincipalAccess"
|
||||
|
||||
/w/{workspace}/access/browse_folders:
|
||||
get:
|
||||
summary: list the folders the caller can read, with the principal's direct grant on each
|
||||
operationId: browseAccessFolders
|
||||
tags:
|
||||
- granular_acl
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- name: principal
|
||||
description: "`u/<username>` or `g/<group>`"
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: folders
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
grant:
|
||||
description: the principal's entry in the folder's extra_perms; absent when none, false for read, true for write
|
||||
type: boolean
|
||||
nullable: true
|
||||
target_owner:
|
||||
type: boolean
|
||||
blocked:
|
||||
description: why the caller cannot change this grant
|
||||
type: string
|
||||
required: [name, target_owner]
|
||||
|
||||
/w/{workspace}/access/browse_items:
|
||||
get:
|
||||
summary: list items the caller can read, with the principal's direct grant on each
|
||||
operationId: browseAccessItems
|
||||
tags:
|
||||
- granular_acl
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- name: principal
|
||||
description: "`u/<username>` or `g/<group>`"
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
- name: prefix
|
||||
description: only paths starting with this, e.g. `f/billing/`
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: kind
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: search
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: offset
|
||||
in: query
|
||||
schema:
|
||||
type: integer
|
||||
responses:
|
||||
"200":
|
||||
description: a page of 100 items
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
path:
|
||||
type: string
|
||||
grant:
|
||||
type: boolean
|
||||
nullable: true
|
||||
blocked:
|
||||
description: why the caller cannot change this grant
|
||||
type: string
|
||||
required: [kind, path]
|
||||
has_more:
|
||||
type: boolean
|
||||
required: [items, has_more]
|
||||
|
||||
/w/{workspace}/acls/get/{kind}/{path}:
|
||||
get:
|
||||
summary: get granular acls
|
||||
@@ -39539,6 +39639,12 @@ components:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
grant:
|
||||
description: the principal's own entry on the folder; absent when none, false for read, true for write
|
||||
type: boolean
|
||||
blocked:
|
||||
description: why the caller cannot change the principal's own entry; set only where there is one
|
||||
type: string
|
||||
required: [name, write, owner, via]
|
||||
items:
|
||||
type: array
|
||||
@@ -39555,6 +39661,9 @@ components:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/AccessReason"
|
||||
blocked:
|
||||
description: why the caller cannot change the principal's own grant; set only where there is one
|
||||
type: string
|
||||
required: [kind, path, write, reasons]
|
||||
required: [principal, is_admin, groups, folders, items]
|
||||
|
||||
|
||||
@@ -2707,7 +2707,7 @@
|
||||
},
|
||||
{
|
||||
"name": "read_s3_file",
|
||||
"description": "Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text or JSON file, the columns, their types and the first 50 rows of a CSV, TSV, NDJSON or Parquet file, or the image itself for a png, jpeg, gif or webp of up to 3.75 MB, which you then see. Other files return their metadata only.",
|
||||
"description": "Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text or JSON file, the columns, their types and the first 50 rows of a CSV, TSV, NDJSON or Parquet file, or the image itself for a png, jpeg, gif or webp of up to 30 MB, which you then see (one past 3.75 MB or 8000 px comes as a smaller JPEG copy). Other files return their metadata only.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
//! Image files handed to an MCP client's model: a file within the limits as it is, a file past
|
||||
//! them as a JPEG copy, and why an image is left out. Which results are images is `runs.rs`'s.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::{Semaphore, SemaphorePermit};
|
||||
|
||||
use super::ToolImage;
|
||||
|
||||
/// The largest image handed to the model, in bytes. Its base64 is at most 5,000,000
|
||||
/// characters: the 5 MB per image that Claude takes on Amazon Bedrock, the lowest of its
|
||||
/// platforms (the Claude API takes 10 MB).
|
||||
pub(super) const MAX_IMAGE_BYTES: usize = 3_750_000;
|
||||
/// The largest file read to be copied, and its base64 in characters.
|
||||
pub(super) const MAX_SOURCE_BYTES: usize = 30_000_000;
|
||||
pub(super) const MAX_SOURCE_CHARS: usize = MAX_SOURCE_BYTES / 3 * 4;
|
||||
|
||||
/// A server reads this many images at once, from the read of a file to the end of its copy:
|
||||
/// each holds its file, up to 30 MB, and decoding the largest peaks at about 200 MB. A call
|
||||
/// that waits longer than `READ_WAIT` leaves its image out rather than queue.
|
||||
static READ_SLOTS: Semaphore = Semaphore::const_new(2);
|
||||
const READ_WAIT: Duration = Duration::from_secs(5);
|
||||
|
||||
pub(super) type ReadSlot = SemaphorePermit<'static>;
|
||||
|
||||
pub(super) async fn read_slot() -> Result<ReadSlot, Unattached> {
|
||||
match tokio::time::timeout(READ_WAIT, READ_SLOTS.acquire()).await {
|
||||
Ok(Ok(slot)) => Ok(slot),
|
||||
_ => Err(Unattached {
|
||||
key: "busy",
|
||||
why: "the server is busy reading other images, call the tool again".to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// An image as the model is handed it, and for a file past the limits, the copy it is.
|
||||
#[cfg_attr(not(feature = "mcp"), allow(dead_code))]
|
||||
pub(super) struct Attachment {
|
||||
pub image: ToolImage,
|
||||
pub copy: Option<String>,
|
||||
}
|
||||
|
||||
/// Why an image is left out of an answer: what the model reads, and the `feature_usage`
|
||||
/// key it counts under.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Unattached {
|
||||
pub key: &'static str,
|
||||
pub why: String,
|
||||
}
|
||||
|
||||
pub(super) fn too_large() -> Unattached {
|
||||
let why = format!("larger than {} MB", MAX_SOURCE_BYTES as f64 / 1e6);
|
||||
Unattached { key: "too_large", why }
|
||||
}
|
||||
|
||||
pub(super) fn not_image(why: &str) -> Unattached {
|
||||
Unattached { key: "not_image", why: why.to_string() }
|
||||
}
|
||||
|
||||
pub(super) fn unreadable(why: String) -> Unattached {
|
||||
Unattached { key: "unreadable", why }
|
||||
}
|
||||
|
||||
/// An image of a result's base64, `slot` held when its read took one.
|
||||
pub(super) async fn decode_inline_image(
|
||||
data: &str,
|
||||
slot: Option<ReadSlot>,
|
||||
) -> Result<Attachment, Unattached> {
|
||||
use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD};
|
||||
use base64::Engine;
|
||||
let data: String = data.chars().filter(|c| !matches!(c, '\n' | '\r')).collect();
|
||||
let bytes = STANDARD
|
||||
.decode(&data)
|
||||
.or_else(|_| STANDARD_NO_PAD.decode(&data))
|
||||
.map_err(|_| not_image("its content is not base64"))?;
|
||||
image_from_bytes(bytes, slot).await
|
||||
}
|
||||
|
||||
/// A file within the limits as it is, a file past them as a JPEG copy, made holding `slot`,
|
||||
/// or one taken here. The header is read first, so an image already in the result and within
|
||||
/// the limits never waits for another's copy.
|
||||
#[cfg(feature = "mcp")]
|
||||
pub(super) async fn image_from_bytes(
|
||||
bytes: Vec<u8>,
|
||||
slot: Option<ReadSlot>,
|
||||
) -> Result<Attachment, Unattached> {
|
||||
let (bytes, format, as_is) = blocking(move || {
|
||||
let format = image_format(&bytes)?;
|
||||
let as_is = image_as_is(&bytes, format)?;
|
||||
Ok((bytes, format, as_is))
|
||||
})
|
||||
.await?;
|
||||
if let Some(attachment) = as_is {
|
||||
return Ok(attachment);
|
||||
}
|
||||
let slot = match slot {
|
||||
Some(slot) => slot,
|
||||
None => read_slot().await?,
|
||||
};
|
||||
blocking(move || {
|
||||
// Held until the decoding ends, also when the answer is no longer awaited.
|
||||
let _slot = slot;
|
||||
image_copy(&bytes, format)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Only an MCP client is handed images, and the image crates are built only with it.
|
||||
#[cfg(not(feature = "mcp"))]
|
||||
pub(super) async fn image_from_bytes(
|
||||
_bytes: Vec<u8>,
|
||||
_slot: Option<ReadSlot>,
|
||||
) -> Result<Attachment, Unattached> {
|
||||
Err(unreadable(
|
||||
"images are read only for MCP clients".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
/// The widest or tallest image handed to the model: the Claude API refuses a larger one, and
|
||||
/// with it the whole request.
|
||||
#[cfg(feature = "mcp")]
|
||||
const MAX_IMAGE_SIDE: u32 = 8000;
|
||||
/// The longest side of the JPEG copy handed for an image past either limit: the most Claude
|
||||
/// reads, which scales a larger image down itself.
|
||||
#[cfg(feature = "mcp")]
|
||||
const COPY_SIDE: u32 = 2576;
|
||||
/// The most memory an image copied takes decoded: a 6000x4000 RGBA image, or a 42 MP photo.
|
||||
#[cfg(feature = "mcp")]
|
||||
const MAX_DECODED_BYTES: u64 = 128_000_000;
|
||||
/// The most a decoder allocates besides the pixels, for the file's metadata mostly. A PNG's
|
||||
/// color profile is compressed, and the decoder's default allowance (512 MiB) lets a file of
|
||||
/// a few hundred KB inflate it to hundreds of MB.
|
||||
#[cfg(feature = "mcp")]
|
||||
const MAX_METADATA_BYTES: u64 = 16_000_000;
|
||||
|
||||
/// A file's type, read from its bytes: the key or extension only says an image is worth
|
||||
/// reading, and a provider can refuse the whole request for an image whose bytes are not the
|
||||
/// type it is sent as.
|
||||
#[cfg(feature = "mcp")]
|
||||
fn image_format(bytes: &[u8]) -> Result<image::ImageFormat, Unattached> {
|
||||
use image::ImageFormat;
|
||||
image::guess_format(bytes)
|
||||
.ok()
|
||||
.filter(|format| {
|
||||
matches!(
|
||||
format,
|
||||
ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::Gif | ImageFormat::WebP
|
||||
)
|
||||
})
|
||||
.ok_or_else(|| not_image("not a PNG, JPEG, GIF or WebP file"))
|
||||
}
|
||||
|
||||
/// The file itself, when it is within the limits.
|
||||
#[cfg(feature = "mcp")]
|
||||
fn image_as_is(bytes: &[u8], format: image::ImageFormat) -> Result<Option<Attachment>, Unattached> {
|
||||
use base64::Engine;
|
||||
let (width, height) = image_reader(bytes, format)
|
||||
.into_dimensions()
|
||||
.map_err(|_| not_image("its width and height cannot be read"))?;
|
||||
if bytes.len() > MAX_IMAGE_BYTES || width.max(height) > MAX_IMAGE_SIDE {
|
||||
return Ok(None);
|
||||
}
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(bytes);
|
||||
let image = ToolImage { data, mime_type: format.to_mime_type() };
|
||||
Ok(Some(Attachment { image, copy: None }))
|
||||
}
|
||||
|
||||
/// Work that takes CPU time, run off the async threads. A decoder that panics leaves the
|
||||
/// image out.
|
||||
#[cfg(feature = "mcp")]
|
||||
async fn blocking<T: Send + 'static>(
|
||||
work: impl FnOnce() -> Result<T, Unattached> + Send + 'static,
|
||||
) -> Result<T, Unattached> {
|
||||
tokio::task::spawn_blocking(work)
|
||||
.await
|
||||
.unwrap_or_else(|_| Err(not_image("it cannot be decoded")))
|
||||
}
|
||||
|
||||
/// A reader whose decoder allocates at most `MAX_METADATA_BYTES` besides the pixels.
|
||||
#[cfg(feature = "mcp")]
|
||||
fn image_reader(
|
||||
bytes: &[u8],
|
||||
format: image::ImageFormat,
|
||||
) -> image::ImageReader<std::io::Cursor<&[u8]>> {
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(MAX_METADATA_BYTES);
|
||||
let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes), format);
|
||||
reader.limits(limits);
|
||||
reader
|
||||
}
|
||||
|
||||
/// A JPEG copy of an image, at most `COPY_SIDE` on its longest side and its quality lowered
|
||||
/// until it is within `MAX_IMAGE_BYTES`.
|
||||
#[cfg(feature = "mcp")]
|
||||
fn image_copy(bytes: &[u8], format: image::ImageFormat) -> Result<Attachment, Unattached> {
|
||||
use base64::Engine;
|
||||
use image::codecs::jpeg::JpegEncoder;
|
||||
use image::metadata::Orientation;
|
||||
use image::{DynamicImage, ImageDecoder};
|
||||
let undecodable =
|
||||
|error: image::ImageError| not_image(&format!("it cannot be decoded: {error}"));
|
||||
let mut decoder = image_reader(bytes, format)
|
||||
.into_decoder()
|
||||
.map_err(undecodable)?;
|
||||
let (mut width, mut height) = decoder.dimensions();
|
||||
if decoder.total_bytes() > MAX_DECODED_BYTES {
|
||||
let why = format!("{width}x{height} px, too large to decode");
|
||||
return Err(Unattached { key: "too_large", why });
|
||||
}
|
||||
let orientation = match format {
|
||||
image::ImageFormat::WebP => webp_orientation(bytes),
|
||||
_ => decoder.orientation().ok(),
|
||||
}
|
||||
.unwrap_or(Orientation::NoTransforms);
|
||||
let mut pixels = DynamicImage::from_decoder(decoder).map_err(undecodable)?;
|
||||
if width.max(height) > COPY_SIDE {
|
||||
pixels = pixels.thumbnail(COPY_SIDE, COPY_SIDE);
|
||||
}
|
||||
// The copy keeps no EXIF data, so a photo taken sideways is turned as viewers show it.
|
||||
pixels.apply_orientation(orientation);
|
||||
if matches!(
|
||||
orientation,
|
||||
Orientation::Rotate90
|
||||
| Orientation::Rotate270
|
||||
| Orientation::Rotate90FlipH
|
||||
| Orientation::Rotate270FlipH
|
||||
) {
|
||||
(width, height) = (height, width);
|
||||
}
|
||||
let pixels = over_white(pixels);
|
||||
for quality in [85, 70, 50, 30] {
|
||||
let mut jpeg = Vec::new();
|
||||
JpegEncoder::new_with_quality(&mut jpeg, quality)
|
||||
.encode_image(&pixels)
|
||||
.map_err(|error| unreadable(format!("its copy cannot be encoded: {error}")))?;
|
||||
if jpeg.len() <= MAX_IMAGE_BYTES {
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(&jpeg);
|
||||
let (copy_width, copy_height) = pixels.dimensions();
|
||||
let copy =
|
||||
format!("a {copy_width}x{copy_height} JPEG copy of the {width}x{height} px file");
|
||||
let image = ToolImage { data, mime_type: "image/jpeg" };
|
||||
return Ok(Attachment { image, copy: Some(copy) });
|
||||
}
|
||||
}
|
||||
let why = format!(
|
||||
"larger than {} MB even as a JPEG copy",
|
||||
MAX_IMAGE_BYTES as f64 / 1e6
|
||||
);
|
||||
Err(Unattached { key: "too_large", why })
|
||||
}
|
||||
|
||||
/// A WebP's orientation, from its EXIF chunk. image's WebP decoder ignores `max_alloc`, and
|
||||
/// allocates an EXIF chunk at the length its header declares, up to 4 GB, before reading it,
|
||||
/// so the chunk is read through image-webp with the metadata limit.
|
||||
#[cfg(feature = "mcp")]
|
||||
fn webp_orientation(bytes: &[u8]) -> Option<image::metadata::Orientation> {
|
||||
let mut decoder = image_webp::WebPDecoder::new(std::io::Cursor::new(bytes)).ok()?;
|
||||
decoder.set_memory_limit(MAX_METADATA_BYTES as usize);
|
||||
image::metadata::Orientation::from_exif_chunk(&decoder.exif_metadata().ok()??)
|
||||
}
|
||||
|
||||
/// An image's pixels as RGB, its transparent parts over white: a JPEG keeps no transparency,
|
||||
/// and the color under it is often black, the color of the text drawn on it.
|
||||
#[cfg(feature = "mcp")]
|
||||
fn over_white(pixels: image::DynamicImage) -> image::RgbImage {
|
||||
if !pixels.has_alpha() {
|
||||
return pixels.into_rgb8();
|
||||
}
|
||||
let rgba = pixels.into_rgba8();
|
||||
image::RgbImage::from_fn(rgba.width(), rgba.height(), |x, y| {
|
||||
let [r, g, b, a] = rgba.get_pixel(x, y).0.map(u32::from);
|
||||
let over = |c: u32| ((c * a + 255 * (255 - a)) / 255) as u8;
|
||||
image::Rgb([over(r), over(g), over(b)])
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "mcp"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A black JPEG of `width` x `height`.
|
||||
fn jpeg(width: u32, height: u32) -> Vec<u8> {
|
||||
let mut file = Vec::new();
|
||||
image::codecs::jpeg::JpegEncoder::new(&mut file)
|
||||
.encode_image(&image::RgbImage::new(width, height))
|
||||
.unwrap();
|
||||
file
|
||||
}
|
||||
|
||||
fn decoded(attachment: &Attachment) -> image::DynamicImage {
|
||||
use base64::Engine;
|
||||
let bytes = base64::engine::general_purpose::STANDARD
|
||||
.decode(&attachment.image.data)
|
||||
.unwrap();
|
||||
image::load_from_memory(&bytes).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_image_within_the_limits_is_sent_as_the_type_its_bytes_are() {
|
||||
use base64::Engine;
|
||||
// A `{"png": ...}` holding a JPEG goes out as one, unchanged but for its line breaks.
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(jpeg(3, 2));
|
||||
let wrapped = format!("{}\n{}", &data[..8], &data[8..]);
|
||||
let sent = decode_inline_image(&wrapped, None).await.unwrap();
|
||||
assert_eq!(
|
||||
(sent.image.mime_type, sent.image.data.as_str(), sent.copy),
|
||||
("image/jpeg", data.as_str(), None)
|
||||
);
|
||||
let page = decode_inline_image("PGh0bWw+", None).await;
|
||||
assert!(matches!(page, Err(Unattached { key: "not_image", .. })));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_image_past_the_limits_is_sent_as_a_jpeg_copy() {
|
||||
// EXIF orientation 6, a photo taken sideways: the copy is turned as viewers show it.
|
||||
let exif = b"\xff\xe1\0\x22Exif\0\0MM\0\x2a\0\0\0\x08\0\x01\x01\x12\0\x03\0\0\0\x01\0\x06\0\0\0\0\0\0";
|
||||
let file = jpeg(9000, 10);
|
||||
let sideways = [&file[..2], exif.as_slice(), &file[2..]].concat();
|
||||
let sent = image_from_bytes(sideways, None).await.unwrap();
|
||||
assert_eq!(
|
||||
sent.copy.as_deref(),
|
||||
Some("a 3x2576 JPEG copy of the 10x9000 px file")
|
||||
);
|
||||
let copy = decoded(&sent);
|
||||
assert_eq!(
|
||||
(sent.image.mime_type, copy.width(), copy.height()),
|
||||
("image/jpeg", 3, 2576)
|
||||
);
|
||||
|
||||
// Transparent parts are drawn over white.
|
||||
let mut png = Vec::new();
|
||||
image::RgbaImage::new(9000, 2)
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let copy = decoded(&image_from_bytes(png, None).await.unwrap()).to_rgb8();
|
||||
assert!(copy.pixels().all(|pixel| pixel.0.iter().all(|&c| c > 250)));
|
||||
|
||||
// An image too large to decode is refused from its header: a 10000x10000 GIF.
|
||||
let gif = b"GIF89a\x10\x27\x10\x27\0\0\0,\0\0\0\0\x10\x27\x10\x27\0\x02\x02\x44\x01\0;";
|
||||
let refused = image_from_bytes(gif.to_vec(), None).await;
|
||||
assert!(matches!(refused, Err(Unattached { key: "too_large", .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_profile_past_the_metadata_limit_is_dropped() {
|
||||
use image::{ImageDecoder, ImageEncoder};
|
||||
let mut png = Vec::new();
|
||||
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
|
||||
encoder
|
||||
.set_icc_profile(vec![0; MAX_METADATA_BYTES as usize + 1])
|
||||
.unwrap();
|
||||
encoder
|
||||
.write_image(&[0; 3], 1, 1, image::ExtendedColorType::Rgb8)
|
||||
.unwrap();
|
||||
let mut decoder = image_reader(&png, image::ImageFormat::Png)
|
||||
.into_decoder()
|
||||
.unwrap();
|
||||
assert_eq!(decoder.icc_profile().unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_webp_exif_chunk_past_the_metadata_limit_is_not_read() {
|
||||
use image::ImageEncoder;
|
||||
// EXIF orientation 6: viewers turn the image a quarter turn clockwise.
|
||||
let mut exif = b"II*\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0\x06\0\0\0\0\0\0\0".to_vec();
|
||||
let copy = |exif: &[u8]| {
|
||||
let mut webp = Vec::new();
|
||||
let mut encoder = image::codecs::webp::WebPEncoder::new_lossless(&mut webp);
|
||||
encoder.set_exif_metadata(exif.to_vec()).unwrap();
|
||||
encoder
|
||||
.write_image(&[0; 6], 2, 1, image::ExtendedColorType::Rgb8)
|
||||
.unwrap();
|
||||
image_copy(&webp, image::ImageFormat::WebP)
|
||||
.unwrap()
|
||||
.copy
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(copy(&exif), "a 1x2 JPEG copy of the 1x2 px file");
|
||||
exif.resize(MAX_METADATA_BYTES as usize + 1, 0);
|
||||
assert_eq!(copy(&exif), "a 2x1 JPEG copy of the 2x1 px file");
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,7 @@ mod data;
|
||||
mod deploy;
|
||||
mod flows;
|
||||
mod guidance;
|
||||
mod images;
|
||||
#[cfg(feature = "mcp")]
|
||||
mod instructions;
|
||||
mod items;
|
||||
@@ -265,6 +266,15 @@ pub(crate) fn session_tools(access: SessionAccess) -> impl Iterator<Item = ToolI
|
||||
/// What a tool hands back: the text the model reads, or the message of a failed call.
|
||||
pub(super) type ToolResult = Result<String, String>;
|
||||
|
||||
/// An image the model reads beside a tool's text: an MCP `image` content block, or for the
|
||||
/// chat, an image it attaches to the conversation.
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct ToolImage {
|
||||
/// Standard base64.
|
||||
pub data: String,
|
||||
pub mime_type: &'static str,
|
||||
}
|
||||
|
||||
/// The caller, and the API reached as them.
|
||||
pub(crate) struct Ctx<'a> {
|
||||
pub auth: &'a ApiAuthed,
|
||||
@@ -284,18 +294,11 @@ pub(crate) struct Ctx<'a> {
|
||||
/// What the card draws of this call, as `(key, value)`: returned in the result's
|
||||
/// `_meta`, which the model never reads.
|
||||
pub view: std::sync::Mutex<Option<(&'static str, Value)>>,
|
||||
/// Images the model sees beside the text: MCP sends them as image content, the chat
|
||||
/// The images the model reads beside the text: MCP sends them as image content, the chat
|
||||
/// attaches them to the conversation.
|
||||
pub images: std::sync::Mutex<Vec<ToolImage>>,
|
||||
}
|
||||
|
||||
/// An image a tool returns, base64-encoded.
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct ToolImage {
|
||||
pub mime_type: String,
|
||||
pub data: String,
|
||||
}
|
||||
|
||||
impl<'a> Ctx<'a> {
|
||||
pub(crate) fn new(
|
||||
auth: &'a ApiAuthed,
|
||||
@@ -318,6 +321,13 @@ impl<'a> Ctx<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the model reads images beside the text. The chat's providers take a tool
|
||||
/// result as text only (OpenAI's tool messages cannot carry an image), so only an MCP
|
||||
/// client is handed any.
|
||||
pub(super) fn reads_images(&self) -> bool {
|
||||
self.surface == Surface::Mcp
|
||||
}
|
||||
|
||||
/// Hand the chat something to apply. A no-op for MCP, which has no editor.
|
||||
pub(super) fn effect(&self, effect: chat::Effect) {
|
||||
if self.surface == Surface::Chat {
|
||||
@@ -335,15 +345,6 @@ impl Ctx<'_> {
|
||||
*self.view.lock().unwrap() = Some((key, value));
|
||||
}
|
||||
|
||||
/// Return an image to the model with the call's text.
|
||||
pub fn push_image(&self, mime_type: &str, bytes: &[u8]) {
|
||||
use base64::Engine;
|
||||
self.images.lock().unwrap().push(ToolImage {
|
||||
mime_type: mime_type.to_string(),
|
||||
data: base64::engine::general_purpose::STANDARD.encode(bytes),
|
||||
});
|
||||
}
|
||||
|
||||
/// Call the API as the caller. `path` follows `/api`; a non-2xx answer is the error.
|
||||
pub async fn request(&self, method: &str, path: &str, body: Option<Value>) -> ToolResult {
|
||||
self.request_within(method, path, body, REQUEST_TIMEOUT)
|
||||
@@ -360,22 +361,43 @@ impl Ctx<'_> {
|
||||
body: Option<Value>,
|
||||
timeout: std::time::Duration,
|
||||
) -> ToolResult {
|
||||
let bytes = self.request_bytes(method, path, body, timeout).await?;
|
||||
Ok(String::from_utf8_lossy(&bytes).into_owned())
|
||||
let (status, bytes) = self.send(method, path, body, timeout, usize::MAX).await?;
|
||||
let text = String::from_utf8_lossy(bytes.as_deref().unwrap_or_default()).into_owned();
|
||||
match status.is_success() {
|
||||
true => Ok(text),
|
||||
false => Err(api_error(status, &text)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET` a route that answers with bytes, such as a file's content.
|
||||
pub async fn get_bytes(&self, path: &str) -> Result<Vec<u8>, String> {
|
||||
self.request_bytes("GET", path, None, REQUEST_TIMEOUT).await
|
||||
/// `GET` an answer as bytes, at most `max_bytes` of them: `None` for a longer answer,
|
||||
/// which is not read past the limit.
|
||||
pub async fn get_bytes(
|
||||
&self,
|
||||
path: &str,
|
||||
max_bytes: usize,
|
||||
) -> Result<Option<bytes::Bytes>, String> {
|
||||
let (status, bytes) = self
|
||||
.send("GET", path, None, REQUEST_TIMEOUT, max_bytes)
|
||||
.await?;
|
||||
match status.is_success() {
|
||||
true => Ok(bytes),
|
||||
false => {
|
||||
let text = String::from_utf8_lossy(bytes.as_deref().unwrap_or_default());
|
||||
Err(api_error(status, &text))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn request_bytes(
|
||||
/// Call the API as the caller and read at most `max_bytes` of the answer: `None` past
|
||||
/// that.
|
||||
async fn send(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<Value>,
|
||||
timeout: std::time::Duration,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
max_bytes: usize,
|
||||
) -> Result<(http::StatusCode, Option<bytes::Bytes>), String> {
|
||||
let url = guarded_url(self.base_internal_url, self.w_id, method, path, self.access)?;
|
||||
// No route scope: this server only admits `mcp:all`, several routes (hub, embeddings)
|
||||
// map to none, and `guarded_url` is what keeps a call on its route. The tag fence
|
||||
@@ -394,23 +416,15 @@ impl Ctx<'_> {
|
||||
.unwrap()
|
||||
.get(self.base_internal_url)
|
||||
.cloned();
|
||||
let (status, bytes) = match router {
|
||||
match router {
|
||||
Some(router) => {
|
||||
self.call_router(router, method, &url, body, scopes, timeout)
|
||||
.await?
|
||||
self.call_router(router, method, &url, body, scopes, timeout, max_bytes)
|
||||
.await
|
||||
}
|
||||
None => {
|
||||
self.call_http(method, &url, body, scopes, timeout, max_bytes)
|
||||
.await
|
||||
}
|
||||
None => self.call_http(method, &url, body, scopes, timeout).await?,
|
||||
};
|
||||
if status.is_success() {
|
||||
return Ok(bytes);
|
||||
}
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
if text.trim().is_empty() {
|
||||
// What a browser's request reports for an answer with no body.
|
||||
let reason = status.canonical_reason().unwrap_or_default();
|
||||
Err(format!("{}: {reason}", status.as_u16()))
|
||||
} else {
|
||||
Err(format!("{}: {}", status.as_u16(), text))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -424,7 +438,8 @@ impl Ctx<'_> {
|
||||
body: Option<Value>,
|
||||
scopes: Option<Vec<String>>,
|
||||
timeout: std::time::Duration,
|
||||
) -> Result<(http::StatusCode, Vec<u8>), String> {
|
||||
max_bytes: usize,
|
||||
) -> Result<(http::StatusCode, Option<bytes::Bytes>), String> {
|
||||
use tower::ServiceExt;
|
||||
let parsed = reqwest::Url::parse(url).map_err(|e| e.to_string())?;
|
||||
// The router does not see the base URL's own path prefix.
|
||||
@@ -454,10 +469,8 @@ impl Ctx<'_> {
|
||||
tokio::time::timeout(timeout, async {
|
||||
let Ok(response) = router.oneshot(request).await;
|
||||
let status = response.status();
|
||||
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok((status, bytes.to_vec()))
|
||||
let body = read_capped(response.into_body().into_data_stream(), max_bytes).await?;
|
||||
Ok((status, body))
|
||||
})
|
||||
.await
|
||||
.map_err(|_| format!("Failed to execute request: {method} {url} timed out"))?
|
||||
@@ -471,7 +484,8 @@ impl Ctx<'_> {
|
||||
body: Option<Value>,
|
||||
scopes: Option<Vec<String>>,
|
||||
timeout: std::time::Duration,
|
||||
) -> Result<(http::StatusCode, Vec<u8>), String> {
|
||||
max_bytes: usize,
|
||||
) -> Result<(http::StatusCode, Option<bytes::Bytes>), String> {
|
||||
let method = http::Method::from_bytes(method.as_bytes()).map_err(|e| e.to_string())?;
|
||||
let token = self
|
||||
.jwt
|
||||
@@ -490,8 +504,14 @@ impl Ctx<'_> {
|
||||
.await
|
||||
.map_err(|e| format!("Failed to execute request: {e}"))?;
|
||||
let status = response.status();
|
||||
let bytes = response.bytes().await.map_err(|e| e.to_string())?;
|
||||
Ok((status, bytes.to_vec()))
|
||||
if response
|
||||
.content_length()
|
||||
.is_some_and(|len| len > max_bytes as u64)
|
||||
{
|
||||
return Ok((status, None));
|
||||
}
|
||||
let body = read_capped(response.bytes_stream(), max_bytes).await?;
|
||||
Ok((status, body))
|
||||
}
|
||||
|
||||
pub async fn get(&self, path: &str) -> Result<Value, String> {
|
||||
@@ -549,6 +569,36 @@ impl Ctx<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A failed API call as the session reads it: the status code, then the answer.
|
||||
fn api_error(status: http::StatusCode, body: &str) -> String {
|
||||
if body.trim().is_empty() {
|
||||
// What a browser's request reports for an answer with no body.
|
||||
let reason = status.canonical_reason().unwrap_or_default();
|
||||
format!("{}: {reason}", status.as_u16())
|
||||
} else {
|
||||
format!("{}: {body}", status.as_u16())
|
||||
}
|
||||
}
|
||||
|
||||
/// A body read in full while it stays within `max` bytes: `None` once it passes that,
|
||||
/// without reading the rest.
|
||||
async fn read_capped<E: std::fmt::Display>(
|
||||
stream: impl futures::Stream<Item = Result<bytes::Bytes, E>>,
|
||||
max: usize,
|
||||
) -> Result<Option<bytes::Bytes>, String> {
|
||||
use futures::StreamExt;
|
||||
let mut stream = std::pin::pin!(stream);
|
||||
let mut body = bytes::BytesMut::new();
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let chunk = chunk.map_err(|e| e.to_string())?;
|
||||
if body.len().saturating_add(chunk.len()) > max {
|
||||
return Ok(None);
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok(Some(body.freeze()))
|
||||
}
|
||||
|
||||
/// Routes outside the workspace that a tool reads.
|
||||
const INSTANCE_ROUTES: &[&str] = &[
|
||||
"/docs/",
|
||||
@@ -816,10 +866,11 @@ pub(crate) async fn call_session_tool(
|
||||
name: &str,
|
||||
args: Value,
|
||||
) -> Result<ToolOutcome, CallRefused> {
|
||||
if ctx.surface == Surface::Mcp && views::TOOLS.contains(&name) {
|
||||
return Ok(outcome(views::call(ctx, name, &args).await));
|
||||
}
|
||||
let result = call_generated_tool(ctx, name, &args).await?;
|
||||
let result = if ctx.surface == Surface::Mcp && views::TOOLS.contains(&name) {
|
||||
views::call(ctx, name, &args).await
|
||||
} else {
|
||||
call_generated_tool(ctx, name, &args).await?
|
||||
};
|
||||
let mut outcome = outcome(result);
|
||||
if !outcome.is_error {
|
||||
outcome.images = std::mem::take(&mut *ctx.images.lock().unwrap());
|
||||
|
||||
@@ -7,6 +7,10 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use super::chat::{Effect, RunPhase};
|
||||
use super::images::{
|
||||
decode_inline_image, image_from_bytes, not_image, read_slot, too_large, unreadable, Attachment,
|
||||
Unattached, MAX_IMAGE_BYTES, MAX_SOURCE_BYTES, MAX_SOURCE_CHARS,
|
||||
};
|
||||
use super::workspace::{
|
||||
api_message, get_draft, infer_script_schema, load_flow, load_script_to_run, path_enc,
|
||||
};
|
||||
@@ -216,6 +220,9 @@ pub(super) async fn finish_run(
|
||||
"\n\nFor per-step statuses and results (subflow steps included), call get_run with id=\"{id}\"."
|
||||
));
|
||||
}
|
||||
if ctx.reads_images() {
|
||||
summary.push_str(&image_hint(&id, job.get("result")).unwrap_or_default());
|
||||
}
|
||||
summary.push_str(&run_page);
|
||||
Ok(summary)
|
||||
}
|
||||
@@ -2311,10 +2318,15 @@ async fn read_run(ctx: &Ctx<'_>, args: &Value, card: bool) -> ToolResult {
|
||||
enc(step)
|
||||
);
|
||||
let response = ctx.get(&route).await?;
|
||||
if let Some(job_id) = finished_step_job(&response) {
|
||||
let finished = finished_step_job(&response);
|
||||
if let Some(job_id) = finished {
|
||||
ctx.effect(Effect::InspectedRun { job_id: job_id.to_string() });
|
||||
}
|
||||
return Ok(step_result(&response, step));
|
||||
let images = match finished.filter(|_| ctx.reads_images() && !card) {
|
||||
Some(job_id) => step_images(ctx, job_id, &response["entries"][0]).await,
|
||||
None => None,
|
||||
};
|
||||
return Ok(step_result(&response, step, images.as_ref()));
|
||||
}
|
||||
|
||||
// Only the job read is load-bearing: logs and the step tree each answer part of
|
||||
@@ -2396,7 +2408,12 @@ async fn read_run(ctx: &Ctx<'_>, args: &Value, card: bool) -> ToolResult {
|
||||
None => report_run(ctx, id, Some(job), details),
|
||||
}
|
||||
}
|
||||
let run = shape_run(id, &job?, logs, &results);
|
||||
let job = job?;
|
||||
let images = match ctx.reads_images() && !card {
|
||||
true => attach_result_images(ctx, id, job.get("result"), results["entries"].get(0)).await,
|
||||
false => None,
|
||||
};
|
||||
let run = shape_run(id, &job, logs, &results, images.as_ref());
|
||||
ctx.effect(Effect::InspectedRun { job_id: id.to_string() });
|
||||
Ok(match ctx.link(&format!("/run/{}", enc(id))) {
|
||||
Some(url) => format!("{run}\n\nRun page: {url}"),
|
||||
@@ -2404,6 +2421,24 @@ async fn read_run(ctx: &Ctx<'_>, args: &Value, card: bool) -> ToolResult {
|
||||
})
|
||||
}
|
||||
|
||||
/// The kind of image a result the job read swapped for a marker looks like (`png`, `jpeg`,
|
||||
/// `gif` or `svg`), from the head of it the step tree carries, and the result's length in
|
||||
/// characters.
|
||||
fn too_big_image<'a>(result: Option<&Value>, root: Option<&'a Value>) -> Option<(&'a str, u64)> {
|
||||
if result? != TOO_BIG {
|
||||
return None;
|
||||
}
|
||||
let root = root?;
|
||||
let kind = root["result_prefix"]
|
||||
.as_str()?
|
||||
.strip_prefix("{\"")?
|
||||
.split('"')
|
||||
.next()?;
|
||||
["png", "jpeg", "gif", "svg"]
|
||||
.contains(&kind)
|
||||
.then_some((kind, root["result_length"].as_u64()?))
|
||||
}
|
||||
|
||||
/// The job read swaps a result past ~90 KB for a marker, so an image under the card's cap
|
||||
/// is read again by its one field. The step tree's head of the result says which it is.
|
||||
async fn big_image_result(
|
||||
@@ -2412,29 +2447,30 @@ async fn big_image_result(
|
||||
job: &Value,
|
||||
root: Option<&Value>,
|
||||
) -> Option<Value> {
|
||||
if job.get("result")? != TOO_BIG {
|
||||
return None;
|
||||
}
|
||||
let root = root?;
|
||||
let kind = root["result_prefix"]
|
||||
.as_str()?
|
||||
.strip_prefix("{\"")?
|
||||
.split('"')
|
||||
.next()?;
|
||||
if !["png", "jpeg", "gif", "svg"].contains(&kind)
|
||||
|| root["result_length"].as_u64()? > CARD_IMAGE_CHARS as u64 + 64
|
||||
{
|
||||
let (kind, length) = too_big_image(job.get("result"), root)?;
|
||||
if length > CARD_IMAGE_CHARS as u64 + 64 {
|
||||
return None;
|
||||
}
|
||||
read_whole_image(ctx, id, kind, length).await.ok().flatten()
|
||||
}
|
||||
|
||||
/// A swapped result read again by its one field `kind`, `length` being the result's text in
|
||||
/// characters: `None` when the result holds more than that field.
|
||||
async fn read_whole_image(
|
||||
ctx: &Ctx<'_>,
|
||||
id: &str,
|
||||
kind: &str,
|
||||
length: u64,
|
||||
) -> Result<Option<Value>, String> {
|
||||
let route = ctx.ws(&format!(
|
||||
"jobs/completed/get_result/{}?json_path={kind}",
|
||||
enc(id)
|
||||
));
|
||||
let field = ctx.get(&route).await.ok()?;
|
||||
let field = ctx.get(&route).await?;
|
||||
// The field alone must be the whole result, as `card_image` requires: a result with more
|
||||
// keys is no image, and keeps its marker. The length is the result's text, in characters.
|
||||
let whole = json!({ kind: field });
|
||||
(jsonb_text_len(&whole) == root["result_length"].as_u64()?).then_some(whole)
|
||||
Ok((jsonb_text_len(&whole) == length).then_some(whole))
|
||||
}
|
||||
|
||||
/// The length in characters of a value as PostgreSQL prints a jsonb: `", "` between items
|
||||
@@ -2457,6 +2493,316 @@ fn jsonb_text_len(value: &Value) -> u64 {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Images the model reads: a result Windmill draws as an image, attached to
|
||||
// `get_run`'s answer for an MCP client.
|
||||
// ============================================================================
|
||||
|
||||
/// The images one answer carries at most, and their bytes together.
|
||||
const MAX_IMAGES: usize = 4;
|
||||
const MAX_IMAGES_BYTES: usize = 2 * MAX_IMAGE_BYTES;
|
||||
/// The object storage files the run page draws as an image, and GIFs, which models read.
|
||||
const IMAGE_EXTENSIONS: [&str; 5] = [".png", ".jpg", ".jpeg", ".gif", ".webp"];
|
||||
|
||||
/// Where an image result's bytes are.
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum ImageRef<'a> {
|
||||
/// Base64 in the result itself, under the kind its key names.
|
||||
Inline { kind: &'a str, data: &'a str },
|
||||
/// A file in the workspace's object storage.
|
||||
S3 { key: &'a str, storage: Option<&'a str> },
|
||||
}
|
||||
|
||||
/// The images a result is, in the shapes the run page draws as one: `{png|jpeg|gif}` of
|
||||
/// base64, a file in object storage with an image extension, or a list of such files.
|
||||
fn image_refs(result: &Value) -> Vec<ImageRef<'_>> {
|
||||
match result.as_array() {
|
||||
// The run page lists files only when every item is one, up to 100 of them.
|
||||
Some(items)
|
||||
if items.len() <= 100
|
||||
&& items
|
||||
.iter()
|
||||
.all(|item| item.is_object() && s3_file(item).is_some()) =>
|
||||
{
|
||||
items.iter().filter_map(s3_image).collect()
|
||||
}
|
||||
Some(_) => Vec::new(),
|
||||
None => inline_image(result)
|
||||
.or_else(|| s3_image(result))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The object storage file a value names, `{s3, storage?}` or `s3://<storage>/<key>`, as
|
||||
/// its key and storage.
|
||||
fn s3_file(value: &Value) -> Option<(&str, Option<&str>)> {
|
||||
let (key, storage) = match value {
|
||||
Value::String(uri) => {
|
||||
let (storage, key) = uri.strip_prefix("s3://")?.split_once('/')?;
|
||||
(key, Some(storage))
|
||||
}
|
||||
Value::Object(file) => (
|
||||
file.get("s3")?.as_str()?,
|
||||
file.get("storage").and_then(Value::as_str),
|
||||
),
|
||||
_ => return None,
|
||||
};
|
||||
(!key.is_empty()).then_some((key, storage.filter(|s| !s.is_empty())))
|
||||
}
|
||||
|
||||
fn s3_image(value: &Value) -> Option<ImageRef<'_>> {
|
||||
let (key, storage) = s3_file(value)?;
|
||||
let lower = key.to_ascii_lowercase();
|
||||
IMAGE_EXTENSIONS
|
||||
.iter()
|
||||
.any(|ext| lower.ends_with(ext))
|
||||
.then_some(ImageRef::S3 { key, storage })
|
||||
}
|
||||
|
||||
/// A one-key result's value as text, bare or as a file's `content`: how a script returns
|
||||
/// an image or a page inline, as `{"png": "<base64>"}`.
|
||||
fn single_file(result: &Value) -> Option<(&str, &str)> {
|
||||
let [(kind, value)] = result.as_object()?.iter().collect::<Vec<_>>()[..] else {
|
||||
return None;
|
||||
};
|
||||
let data = value
|
||||
.as_str()
|
||||
.or_else(|| value.get("content").and_then(Value::as_str))
|
||||
.filter(|d| !d.is_empty())?;
|
||||
Some((kind.as_str(), data))
|
||||
}
|
||||
|
||||
fn is_base64(data: &str) -> bool {
|
||||
data.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=' | b'\n' | b'\r'))
|
||||
}
|
||||
|
||||
fn inline_image(result: &Value) -> Option<ImageRef<'_>> {
|
||||
let (kind, data) = single_file(result)?;
|
||||
(matches!(kind, "png" | "jpeg" | "gif") && is_base64(data))
|
||||
.then_some(ImageRef::Inline { kind, data })
|
||||
}
|
||||
|
||||
/// What `get_run` writes beside a result's images: under `key`, what became of them, and
|
||||
/// for an inline image the label standing in for its base64, which tells the model nothing.
|
||||
struct ImageNote {
|
||||
key: &'static str,
|
||||
text: String,
|
||||
label: Option<String>,
|
||||
}
|
||||
|
||||
fn image_label(kind: &str) -> String {
|
||||
format!("{} image", kind.to_uppercase())
|
||||
}
|
||||
|
||||
/// Attach the images `result` is, `entry` being its job's entry in the step tree, which
|
||||
/// says what a result the job read swapped for a marker was. `None` for a result that is no
|
||||
/// image. A failed read leaves its image out and says why; it never fails the answer.
|
||||
async fn attach_result_images(
|
||||
ctx: &Ctx<'_>,
|
||||
job_id: &str,
|
||||
result: Option<&Value>,
|
||||
entry: Option<&Value>,
|
||||
) -> Option<ImageNote> {
|
||||
let result = result?;
|
||||
let swapped = too_big_image(Some(result), entry).filter(|(kind, _)| *kind != "svg");
|
||||
let (label, total, reads) = match swapped {
|
||||
Some((kind, length)) => {
|
||||
let read = read_swapped_image(ctx, job_id, kind, length).await?;
|
||||
(Some(image_label(kind)), 1, vec![(None, read)])
|
||||
}
|
||||
None => {
|
||||
let refs = image_refs(result);
|
||||
let label = match refs.first()? {
|
||||
ImageRef::Inline { kind, .. } => Some(image_label(kind)),
|
||||
ImageRef::S3 { .. } => None,
|
||||
};
|
||||
// One after another, so an answer holds one of the server's read slots at a time.
|
||||
let mut reads = Vec::new();
|
||||
for image in refs.iter().take(MAX_IMAGES) {
|
||||
let name = match image {
|
||||
ImageRef::S3 { key, .. } => Some(*key),
|
||||
ImageRef::Inline { .. } => None,
|
||||
};
|
||||
reads.push((name, read_image(ctx, image).await));
|
||||
}
|
||||
(label, refs.len(), reads)
|
||||
}
|
||||
};
|
||||
let mut budget = MAX_IMAGES_BYTES;
|
||||
let outcomes: Vec<(Option<&str>, Result<Option<String>, String>)> = reads
|
||||
.into_iter()
|
||||
.map(|(name, read)| {
|
||||
let outcome = read.and_then(|Attachment { image, copy }| {
|
||||
let bytes = image.data.len() / 4 * 3;
|
||||
if bytes > budget {
|
||||
let why = format!(
|
||||
"this answer already carries {} MB of images",
|
||||
MAX_IMAGES_BYTES as f64 / 1e6
|
||||
);
|
||||
return Err(Unattached { key: "too_large", why });
|
||||
}
|
||||
budget -= bytes;
|
||||
ctx.images.lock().unwrap().push(image);
|
||||
Ok(copy)
|
||||
});
|
||||
// Only an object storage file is named, by its key.
|
||||
let source = if name.is_some() { "s3" } else { "inline" };
|
||||
let key = match &outcome {
|
||||
Ok(Some(_)) => "copy",
|
||||
Ok(None) => source,
|
||||
Err(skip) => skip.key,
|
||||
};
|
||||
windmill_common::feature_usage::log_feature_usage("mcp_workspace", "result_image", key);
|
||||
(name, outcome.map_err(|skip| skip.why))
|
||||
})
|
||||
.collect();
|
||||
Some(ImageNote {
|
||||
key: if result.is_array() {
|
||||
"result_images"
|
||||
} else {
|
||||
"result_image"
|
||||
},
|
||||
text: image_note_text(&outcomes, total, result.is_array()),
|
||||
label,
|
||||
})
|
||||
}
|
||||
|
||||
fn image_note_text(
|
||||
outcomes: &[(Option<&str>, Result<Option<String>, String>)],
|
||||
total: usize,
|
||||
listed: bool,
|
||||
) -> String {
|
||||
if !listed {
|
||||
return match outcomes.first().map(|(_, outcome)| outcome) {
|
||||
Some(Err(why)) => format!("not attached: {why}"),
|
||||
Some(Ok(Some(copy))) => format!("attached as {copy}"),
|
||||
_ => "attached".to_string(),
|
||||
};
|
||||
}
|
||||
let attached = outcomes.iter().filter(|(_, o)| o.is_ok()).count();
|
||||
let mut text = format!("{attached} of {total} images attached");
|
||||
for (name, outcome) in outcomes {
|
||||
if let Ok(Some(copy)) = outcome {
|
||||
text.push_str(&format!("; {} as {copy}", name.unwrap_or("image")));
|
||||
}
|
||||
}
|
||||
let failed: Vec<String> = outcomes
|
||||
.iter()
|
||||
.filter_map(|(name, outcome)| {
|
||||
let why = outcome.as_ref().err()?;
|
||||
Some(format!("{} ({why})", name.unwrap_or("image")))
|
||||
})
|
||||
.collect();
|
||||
if !failed.is_empty() {
|
||||
text.push_str(&format!("; not attached: {}", failed.join(", ")));
|
||||
}
|
||||
if total > outcomes.len() {
|
||||
text.push_str(&format!(
|
||||
"; an answer carries at most {MAX_IMAGES}, the rest are on the run page"
|
||||
));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// One image as the model is handed it, or why not.
|
||||
async fn read_image(ctx: &Ctx<'_>, image: &ImageRef<'_>) -> Result<Attachment, Unattached> {
|
||||
match *image {
|
||||
ImageRef::Inline { data, .. } => decode_inline_image(data, None).await,
|
||||
ImageRef::S3 { key, storage } => read_s3_image(ctx, key, storage).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// An inline image the job read swapped for a marker, read again by its one field. `None`
|
||||
/// when the result holds more than that field, and so is no image.
|
||||
async fn read_swapped_image(
|
||||
ctx: &Ctx<'_>,
|
||||
job_id: &str,
|
||||
kind: &str,
|
||||
length: u64,
|
||||
) -> Option<Result<Attachment, Unattached>> {
|
||||
if length > MAX_SOURCE_CHARS as u64 + 64 {
|
||||
return Some(Err(too_large()));
|
||||
}
|
||||
let slot = match read_slot().await {
|
||||
Ok(slot) => slot,
|
||||
Err(busy) => return Some(Err(busy)),
|
||||
};
|
||||
let whole = match read_whole_image(ctx, job_id, kind, length).await {
|
||||
Ok(whole) => whole?,
|
||||
Err(error) => {
|
||||
let why = format!("its read failed: {}", js_head(api_message(&error), 300));
|
||||
return Some(Err(unreadable(why)));
|
||||
}
|
||||
};
|
||||
Some(match inline_image(&whole) {
|
||||
Some(ImageRef::Inline { data, .. }) => decode_inline_image(data, Some(slot)).await,
|
||||
_ => Err(not_image("its content is not base64")),
|
||||
})
|
||||
}
|
||||
|
||||
/// A file of the workspace's object storage, read as the caller through the route the run
|
||||
/// page previews it with, so the same storage permission rules apply.
|
||||
pub(super) async fn read_s3_image(
|
||||
ctx: &Ctx<'_>,
|
||||
key: &str,
|
||||
storage: Option<&str>,
|
||||
) -> Result<Attachment, Unattached> {
|
||||
if !cfg!(all(feature = "private", feature = "parquet")) {
|
||||
let why = "reading object storage needs Windmill Enterprise Edition";
|
||||
return Err(unreadable(why.to_string()));
|
||||
}
|
||||
let storage = storage
|
||||
.map(|s| format!("&storage={}", enc(s)))
|
||||
.unwrap_or_default();
|
||||
let route = ctx.ws(&format!(
|
||||
"job_helpers/load_image_preview?file_key={}{storage}",
|
||||
enc(key)
|
||||
));
|
||||
let slot = read_slot().await?;
|
||||
match ctx.get_bytes(&route, MAX_SOURCE_BYTES).await {
|
||||
Ok(Some(bytes)) => image_from_bytes(bytes.into(), Some(slot)).await,
|
||||
Ok(None) => Err(too_large()),
|
||||
Err(error) => Err(unreadable(format!(
|
||||
"object storage answered: {}",
|
||||
js_head(api_message(&error), 300)
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The images of a finished step's result. Its entry carries the whole result when it is
|
||||
/// short, and only its head otherwise.
|
||||
async fn step_images(ctx: &Ctx<'_>, job_id: &str, entry: &Value) -> Option<ImageNote> {
|
||||
let prefix = entry["result_prefix"].as_str()?;
|
||||
let whole = entry["result_length"]
|
||||
.as_u64()
|
||||
.is_none_or(|length| length == prefix.chars().count() as u64);
|
||||
let result = match whole {
|
||||
true => serde_json::from_str(prefix).ok()?,
|
||||
false => json!(TOO_BIG),
|
||||
};
|
||||
attach_result_images(ctx, job_id, Some(&result), Some(entry)).await
|
||||
}
|
||||
|
||||
/// What a run tool adds about a result only `get_run` attaches: an image, or a result too
|
||||
/// big to show, which may be one.
|
||||
fn image_hint(id: &str, result: Option<&Value>) -> Option<String> {
|
||||
let result = result?;
|
||||
if result == TOO_BIG {
|
||||
return Some(format!(
|
||||
"\n\nThe result is too large to show here. If it is an image, get_run with id=\"{id}\" attaches it."
|
||||
));
|
||||
}
|
||||
if image_refs(result).is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(match result.is_array() {
|
||||
true => format!("\n\nThe result lists images: call get_run with id=\"{id}\" to see them."),
|
||||
false => format!("\n\nThe result is an image: call get_run with id=\"{id}\" to see it."),
|
||||
})
|
||||
}
|
||||
|
||||
/// The end of a job's log, read without the rest of it: an offset past the end returns
|
||||
/// no log but where it ends, and a second read starts just before that. A log grows as long
|
||||
/// as its job runs, and the card asks again on every refresh. The result stream's offset is
|
||||
@@ -2933,19 +3279,9 @@ fn describe_result(result: &Value) -> Option<String> {
|
||||
/// An image result as Windmill draws it, for the card to draw too: base64 for PNG, JPEG and
|
||||
/// GIF, the markup itself for SVG, either bare or as a file's `content`.
|
||||
fn card_image(result: &Value) -> Option<Value> {
|
||||
let [(kind, value)] = result.as_object()?.iter().collect::<Vec<_>>()[..] else {
|
||||
return None;
|
||||
};
|
||||
let data = value
|
||||
.as_str()
|
||||
.or_else(|| value.get("content").and_then(Value::as_str))
|
||||
.filter(|d| !d.is_empty() && d.len() <= CARD_IMAGE_CHARS)?;
|
||||
let base64 = |d: &str| {
|
||||
d.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=' | b'\n' | b'\r'))
|
||||
};
|
||||
match kind.as_str() {
|
||||
"png" | "jpeg" | "gif" if base64(data) => Some(json!({ "type": kind, "data": data })),
|
||||
let (kind, data) = single_file(result).filter(|(_, data)| data.len() <= CARD_IMAGE_CHARS)?;
|
||||
match kind {
|
||||
"png" | "jpeg" | "gif" if is_base64(data) => Some(json!({ "type": kind, "data": data })),
|
||||
"svg" => Some(json!({ "type": "svg", "data": data })),
|
||||
_ => None,
|
||||
}
|
||||
@@ -3094,8 +3430,14 @@ fn run_card(id: &str, job: Option<&Value>) -> Map<String, Value> {
|
||||
|
||||
/// A run as `get_run` reports it: its summary, args, result and logs around the step
|
||||
/// tree. `logs` is the log read's own outcome, so a failed read is told apart from an
|
||||
/// empty log.
|
||||
fn shape_run(id: &str, job: &Value, logs: Result<String, String>, results: &Value) -> String {
|
||||
/// empty log. `images` says what became of the images the result is.
|
||||
fn shape_run(
|
||||
id: &str,
|
||||
job: &Value,
|
||||
logs: Result<String, String>,
|
||||
results: &Value,
|
||||
images: Option<&ImageNote>,
|
||||
) -> String {
|
||||
let mut run = summarize_run(job);
|
||||
run.shift_remove("id");
|
||||
// Why a run ended badly.
|
||||
@@ -3115,8 +3457,8 @@ fn shape_run(id: &str, job: &Value, logs: Result<String, String>, results: &Valu
|
||||
run.insert("steps_unavailable".into(), true.into());
|
||||
}
|
||||
// The server swaps a payload too big to send for a marker, each field in its own
|
||||
// form. That is reported, never fetched around: the result keeps the head the step
|
||||
// tree carries.
|
||||
// form. That is reported, and fetched around only for an image the model is handed:
|
||||
// otherwise the result keeps the head the step tree carries.
|
||||
if let Some(job_args) = job.get("args").filter(|a| truthy(Some(a))) {
|
||||
let too_big = job_args
|
||||
.as_object()
|
||||
@@ -3128,10 +3470,19 @@ fn shape_run(id: &str, job: &Value, logs: Result<String, String>, results: &Valu
|
||||
}
|
||||
}
|
||||
if let Some(result) = job.get("result") {
|
||||
if result == TOO_BIG {
|
||||
run.insert("result_truncated".into(), true.into());
|
||||
} else {
|
||||
run.insert("result".into(), cap(&stringify(result), false).into());
|
||||
match images.and_then(|note| note.label.as_deref()) {
|
||||
Some(label) => {
|
||||
run.insert("result".into(), label.into());
|
||||
}
|
||||
None if result == TOO_BIG => {
|
||||
run.insert("result_truncated".into(), true.into());
|
||||
}
|
||||
None => {
|
||||
run.insert("result".into(), cap(&stringify(result), false).into());
|
||||
}
|
||||
}
|
||||
if let Some(note) = images {
|
||||
run.insert(note.key.into(), note.text.clone().into());
|
||||
}
|
||||
}
|
||||
let logs = match logs {
|
||||
@@ -3160,7 +3511,8 @@ fn finished_step_job(response: &Value) -> Option<&str> {
|
||||
}
|
||||
|
||||
/// One step's result in full, from the single entry the server resolved its address to.
|
||||
fn step_result(response: &Value, step: &str) -> String {
|
||||
/// `images` says what became of the images the result is.
|
||||
fn step_result(response: &Value, step: &str, images: Option<&ImageNote>) -> String {
|
||||
if let Some(error) = response["step_error"].as_str().filter(|e| !e.is_empty()) {
|
||||
let hidden = if truthy(response.get("scope_filtered")) {
|
||||
" (Steps running on tags outside your token’s scope are hidden.)"
|
||||
@@ -3187,7 +3539,14 @@ fn step_result(response: &Value, step: &str) -> String {
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
format!("Step \"{step}\" (job {job_id}, {status}) result:\n{prefix}{truncated}")
|
||||
let mut body = match images.and_then(|note| note.label.as_deref()) {
|
||||
Some(label) => label.to_string(),
|
||||
None => format!("{prefix}{truncated}"),
|
||||
};
|
||||
if let Some(note) = images {
|
||||
body.push_str(&format!("\n\n{}: {}", note.key, note.text));
|
||||
}
|
||||
format!("Step \"{step}\" (job {job_id}, {status}) result:\n{body}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -3585,6 +3944,68 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_results_are_the_shapes_the_run_page_draws() {
|
||||
let inline = |kind, data| vec![ImageRef::Inline { kind, data }];
|
||||
let s3 = |key, storage| ImageRef::S3 { key, storage };
|
||||
assert_eq!(
|
||||
image_refs(&json!({ "png": "iVBORw0KGgo=" })),
|
||||
inline("png", "iVBORw0KGgo=")
|
||||
);
|
||||
assert_eq!(
|
||||
image_refs(&json!({ "jpeg": { "content": "/9j/4A==" } })),
|
||||
inline("jpeg", "/9j/4A==")
|
||||
);
|
||||
assert_eq!(
|
||||
image_refs(&json!({ "s3": "charts/q3.PNG" })),
|
||||
vec![s3("charts/q3.PNG", None)]
|
||||
);
|
||||
assert_eq!(
|
||||
image_refs(&json!("s3://secondary/a.webp")),
|
||||
vec![s3("a.webp", Some("secondary"))]
|
||||
);
|
||||
// A list counts when every item is a file, and only its images are read.
|
||||
let files = json!([{ "s3": "a.png", "storage": "secondary" }, { "s3": "b.csv" }, { "s3": "c.jpg" }]);
|
||||
assert_eq!(
|
||||
image_refs(&files),
|
||||
vec![s3("a.png", Some("secondary")), s3("c.jpg", None)]
|
||||
);
|
||||
for not_an_image in [
|
||||
json!([{ "s3": "a.png" }, { "rows": 1 }]),
|
||||
json!({ "svg": "<svg/>" }),
|
||||
json!({ "chart": { "png": "iVBORw0KGgo=" } }),
|
||||
json!({ "png": "iVBORw0KGgo=", "rows": 1 }),
|
||||
json!({ "png": "not base64!" }),
|
||||
json!({ "s3": "report.pdf" }),
|
||||
] {
|
||||
assert!(image_refs(¬_an_image).is_empty(), "{not_an_image}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attached_inline_image_reads_as_its_label() {
|
||||
let job =
|
||||
json!({ "type": "CompletedJob", "success": true, "result": { "png": "iVBORw0KGgo=" } });
|
||||
let note = ImageNote {
|
||||
key: "result_image",
|
||||
text: "attached".into(),
|
||||
label: Some("PNG image".into()),
|
||||
};
|
||||
let text = shape_run(
|
||||
"j",
|
||||
&job,
|
||||
Ok(String::new()),
|
||||
&json!({ "entries": [] }),
|
||||
Some(¬e),
|
||||
);
|
||||
assert!(
|
||||
text.contains(r#""result": "PNG image""#)
|
||||
&& text.contains(r#""result_image": "attached""#),
|
||||
"{text}"
|
||||
);
|
||||
assert!(!text.contains("iVBORw0KGgo"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_are_named_from_the_flow_at_any_depth() {
|
||||
let flow = json!({ "modules": [{
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use super::data::with_query;
|
||||
use super::images::{Attachment, Unattached};
|
||||
use super::runs::read_s3_image;
|
||||
use super::workspace::path_enc;
|
||||
use super::{array, bool_arg, opt_str_arg, pretty, str_arg, Ctx, ToolResult};
|
||||
|
||||
@@ -49,9 +51,6 @@ const MAX_CELL_CHARS: usize = 1000;
|
||||
const DEFAULT_QUERY_ROWS: u64 = 50;
|
||||
const MAX_QUERY_ROWS: u64 = 500;
|
||||
const QUERY_HINT: &str = "Filter, sort or page it with query_s3_table.";
|
||||
/// Anthropic refuses an image whose base64 data passes 5 MB, and the server has no image
|
||||
/// library to downscale with.
|
||||
const MAX_IMAGE_BYTES: u64 = 5 * 1024 * 1024 / 4 * 3;
|
||||
/// What the S3 file browser shows as an image.
|
||||
const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp"];
|
||||
|
||||
@@ -230,27 +229,15 @@ async fn read_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
}
|
||||
}
|
||||
if is_image_key(key) {
|
||||
if size > MAX_IMAGE_BYTES {
|
||||
out.insert("image".into(), "not attached: larger than 3.75 MB".into());
|
||||
} else {
|
||||
let bytes = ctx
|
||||
.get_bytes(&with_query(
|
||||
ctx.ws("job_helpers/load_image_preview"),
|
||||
&[("file_key", Some(key)), ("storage", storage)],
|
||||
))
|
||||
.await?;
|
||||
// Model APIs refuse an image whose declared type is not its content's, so
|
||||
// the type comes from the bytes, never from the key's extension.
|
||||
if let Some(mime_type) = sniff_image(&bytes) {
|
||||
ctx.push_image(mime_type, &bytes);
|
||||
out.insert("image".into(), "attached".into());
|
||||
} else {
|
||||
out.insert(
|
||||
"image".into(),
|
||||
"not attached: not a png, jpeg, gif or webp image".into(),
|
||||
);
|
||||
// As `get_run` hands a run's images: one past the model's limits goes as a JPEG copy.
|
||||
let note = match read_s3_image(ctx, key, storage).await {
|
||||
Ok(Attachment { image, copy }) => {
|
||||
ctx.images.lock().unwrap().push(image);
|
||||
copy.map_or("attached".to_string(), |copy| format!("attached as {copy}"))
|
||||
}
|
||||
}
|
||||
Err(Unattached { why, .. }) => format!("not attached: {why}"),
|
||||
};
|
||||
out.insert("image".into(), note.into());
|
||||
} else {
|
||||
let mut length = size.min(PREVIEW_BYTES);
|
||||
let mut preview = text_preview(ctx, key, storage, size, length).await?;
|
||||
@@ -488,20 +475,6 @@ fn is_image_key(key: &str) -> bool {
|
||||
.is_some_and(|(_, ext)| IMAGE_EXTENSIONS.contains(&ext.to_lowercase().as_str()))
|
||||
}
|
||||
|
||||
fn sniff_image(bytes: &[u8]) -> Option<&'static str> {
|
||||
if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||
Some("image/png")
|
||||
} else if bytes.starts_with(&[0xff, 0xd8, 0xff]) {
|
||||
Some("image/jpeg")
|
||||
} else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
|
||||
Some("image/gif")
|
||||
} else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
|
||||
Some("image/webp")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of `value` once pretty-printed `depth` levels deep in the result.
|
||||
fn pretty_len(value: &Value, depth: usize) -> usize {
|
||||
let s = pretty(value);
|
||||
@@ -824,11 +797,4 @@ mod tests {
|
||||
assert_eq!(table_endpoint("a/b.NDJSON"), Some("load_csv_preview"));
|
||||
assert_eq!(table_endpoint("a/b.json"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_type_comes_from_the_bytes() {
|
||||
assert_eq!(sniff_image(b"\xff\xd8\xff\xe0rest"), Some("image/jpeg"));
|
||||
assert_eq!(sniff_image(b"RIFF\0\0\0\0WEBPVP8 "), Some("image/webp"));
|
||||
assert_eq!(sniff_image(b"<svg"), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1030,7 +1030,8 @@ async fn get_raw_app_data(
|
||||
|
||||
/// HTML wrapper that hosts a raw-app bundle inside a sandboxed, opaque-origin
|
||||
/// iframe. Served by [`get_raw_app_data`] for the `.html` "file type". It loads
|
||||
/// the bundle `.js`/`.css` as same-path subresources, shims web storage (which
|
||||
/// the bundle `.js`/`.css` as same-path subresources (from the embedder when those
|
||||
/// requests are refused), shims web storage (which
|
||||
/// an opaque origin disallows), and waits for the embedder's handshake before
|
||||
/// evaluating the bundle, so `window.ctx` — and `window.process.env` when the
|
||||
/// viewer approved SDK scopes — is set synchronously when it runs. That token is
|
||||
@@ -1040,7 +1041,7 @@ fn raw_app_wrapper_html(secret: &str) -> String {
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="stylesheet" href="./__SECRET__.css" />
|
||||
<link id="__wm_css" rel="stylesheet" href="./__SECRET__.css" onerror="this.wmFailed = true" />
|
||||
<script>
|
||||
(function () {
|
||||
// Storage shim: an opaque-origin (sandboxed) document has no localStorage and
|
||||
@@ -1107,11 +1108,54 @@ fn raw_app_wrapper_html(secret: &str) -> String {
|
||||
// synchronously when the bundle runs. The bundle <script> is injected only
|
||||
// after this, never inline, so it always observes a ready context.
|
||||
var loaded = false;
|
||||
var hs;
|
||||
try { hs = new URLSearchParams(window.location.search).get('wm_hs') || undefined; } catch (_) {}
|
||||
|
||||
// Requests from an opaque origin are cross-site, so a cookie-authenticated proxy
|
||||
// can refuse the .js/.css below. The embedder's own requests carry the cookie, so
|
||||
// it is asked for what failed. Never the first choice: a bundle run from a blob:
|
||||
// URL cannot resolve URLs against document.currentScript.src.
|
||||
function askEmbedder(ext) {
|
||||
return new Promise(function (resolve) {
|
||||
if (!hs) return resolve();
|
||||
var ch = new MessageChannel();
|
||||
ch.port1.onmessage = function (e) { resolve(e.data); };
|
||||
window.parent.postMessage({ type: 'windmill:asset', ext: ext, nonce: hs }, '*', [ch.port2]);
|
||||
});
|
||||
}
|
||||
var cssRecovery;
|
||||
function recoverCss() {
|
||||
cssRecovery = askEmbedder('css').then(function (css) {
|
||||
if (typeof css !== 'string') return;
|
||||
var st = document.createElement('style');
|
||||
st.textContent = css;
|
||||
link.replaceWith(st);
|
||||
});
|
||||
}
|
||||
var link = document.getElementById('__wm_css');
|
||||
// The stylesheet can fail before this script runs.
|
||||
if (link.wmFailed) recoverCss(); else link.onerror = recoverCss;
|
||||
|
||||
function runScript(src) {
|
||||
var s = document.createElement('script');
|
||||
s.src = src;
|
||||
document.body.appendChild(s);
|
||||
return s;
|
||||
}
|
||||
function loadByUrl() { return runScript('./__SECRET__.js'); }
|
||||
function recoverBundle(otherwise) {
|
||||
Promise.all([askEmbedder('js'), cssRecovery]).then(function (r) {
|
||||
if (typeof r[0] !== 'string') return otherwise && otherwise();
|
||||
var url = URL.createObjectURL(new Blob([r[0]], { type: 'text/javascript' }));
|
||||
runScript(url).onload = function () { URL.revokeObjectURL(url); };
|
||||
});
|
||||
}
|
||||
function loadBundle() {
|
||||
if (loaded) return; loaded = true;
|
||||
var s = document.createElement('script');
|
||||
s.src = './__SECRET__.js';
|
||||
document.body.appendChild(s);
|
||||
// A refused stylesheet means the script is refused too, and WebKit fires `load`,
|
||||
// not `error`, on a script answered with a login page lacking `nosniff`.
|
||||
if (cssRecovery) recoverBundle(loadByUrl);
|
||||
else loadByUrl().onerror = function () { recoverBundle(); };
|
||||
}
|
||||
function applyCtx(d) {
|
||||
if (!d || d.type !== 'windmill:ctx') return;
|
||||
@@ -1136,7 +1180,6 @@ fn raw_app_wrapper_html(secret: &str) -> String {
|
||||
// read it), and our own port says the answer reaches only this document
|
||||
// (replacing the document discards the port).
|
||||
try {
|
||||
var hs = new URLSearchParams(window.location.search).get('wm_hs') || undefined;
|
||||
var ch = new MessageChannel();
|
||||
ch.port1.onmessage = function (e) { applyCtx(e.data); };
|
||||
window.parent.postMessage({ type: 'windmill:ready', nonce: hs }, '*', [ch.port2]);
|
||||
@@ -1599,6 +1642,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<uuid::Uuid>,
|
||||
) -> Result<(String, chrono::DateTime<chrono::Utc>)> {
|
||||
@@ -1644,12 +1688,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<uuid::Uuid>,
|
||||
) -> Result<(String, chrono::DateTime<chrono::Utc>)> {
|
||||
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,
|
||||
@@ -1700,10 +1832,12 @@ pub async fn build_embed_token_response(
|
||||
raw_app: bool,
|
||||
policy: &EmbedPolicyView,
|
||||
opt_authed: Option<&ApiAuthed>,
|
||||
viewer_token: Option<&str>,
|
||||
sdk_consent: bool,
|
||||
job_id: Option<uuid::Uuid>,
|
||||
) -> Result<EmbedTokenResponse> {
|
||||
let sandbox = policy.sandbox || !viewer_is_workspace_member(db, w_id, opt_authed).await?;
|
||||
let sandbox =
|
||||
policy.sandbox || !viewer_is_workspace_member(db, w_id, opt_authed, viewer_token).await?;
|
||||
// Only advertise scopes where a token could actually be minted, so the viewer
|
||||
// is never shown a permission prompt that can grant nothing: an anonymous
|
||||
// visitor has no identity to mint against.
|
||||
@@ -1737,14 +1871,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)
|
||||
@@ -1769,10 +1912,14 @@ pub async fn build_embed_token_response(
|
||||
/// author's `sandbox: false` holds. Anyone else (anonymous, a guest, a superadmin of
|
||||
/// another workspace) holds a session the author has no business running code with,
|
||||
/// 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.
|
||||
async fn viewer_is_workspace_member(
|
||||
db: &DB,
|
||||
w_id: &str,
|
||||
opt_authed: Option<&ApiAuthed>,
|
||||
viewer_token: Option<&str>,
|
||||
) -> Result<bool> {
|
||||
let Some(authed) = opt_authed else {
|
||||
return Ok(false);
|
||||
@@ -1780,6 +1927,9 @@ async fn viewer_is_workspace_member(
|
||||
if windmill_api_auth::scopes::has_guest_sentinel(authed.scopes.as_deref()) {
|
||||
return Ok(false);
|
||||
}
|
||||
if is_ext_jwt_bearer(viewer_token) {
|
||||
return Ok(true);
|
||||
}
|
||||
let member: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM usr WHERE workspace_id = $1 AND email = $2 AND NOT disabled)",
|
||||
)
|
||||
@@ -1819,14 +1969,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<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
Json(req): Json<PreviewSdkTokenRequest>,
|
||||
) -> Result<String> {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -1900,6 +2059,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<uuid::Uuid>,
|
||||
) -> Result<EmbedTokenResponse> {
|
||||
let token_and_exp = if let Some(authed) = opt_authed {
|
||||
@@ -1962,10 +2122,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
|
||||
};
|
||||
@@ -2083,6 +2240,7 @@ async fn get_app_embed_token(
|
||||
raw_app,
|
||||
&policy,
|
||||
authed_for_token.as_ref(),
|
||||
token.as_deref(),
|
||||
sdk_query.sdk_consent,
|
||||
job_id,
|
||||
)
|
||||
@@ -2134,6 +2292,7 @@ pub fn parse_embed_policy(policy_str: &str) -> Result<EmbedPolicyView> {
|
||||
async fn get_app_embed_token_for_path(
|
||||
authed: ApiAuthed,
|
||||
OptJobAuthed { job_id, .. }: OptJobAuthed,
|
||||
OptTokened { token }: OptTokened,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Extension(db): Extension<DB>,
|
||||
Path((w_id, path)): Path<(String, StripPath)>,
|
||||
@@ -2168,6 +2327,7 @@ async fn get_app_embed_token_for_path(
|
||||
raw_app,
|
||||
&policy,
|
||||
Some(&authed),
|
||||
token.as_deref(),
|
||||
sdk_query.sdk_consent,
|
||||
job_id,
|
||||
)
|
||||
|
||||
@@ -154,6 +154,19 @@ async fn list_drafts(
|
||||
// otherwise the broadened listing would disclose the path/summary/authors
|
||||
// of items the caller can't see. Unreadable rows are dropped, mirroring the
|
||||
// `require_can_read_path` gate on `/drafts/get`.
|
||||
// The folder set is refreshed once here, so the per-row read checks need not each
|
||||
// refresh it for every draft in a folder the caller cannot read.
|
||||
let unknown_folder = rows.iter().find(|row| {
|
||||
!row.mine
|
||||
&& row.path.strip_prefix("f/").is_some_and(|rest| {
|
||||
let folder = rest.split('/').next().unwrap_or_default();
|
||||
!authed.folders.iter().any(|(name, _, _)| name == folder)
|
||||
})
|
||||
});
|
||||
let authed = match unknown_folder {
|
||||
Some(_) => with_current_folders(authed, &w_id, &db).await?,
|
||||
None => authed,
|
||||
};
|
||||
let mut out = Vec::with_capacity(rows.len());
|
||||
for mut row in rows {
|
||||
if row.mine {
|
||||
@@ -177,7 +190,7 @@ async fn list_drafts(
|
||||
// `require_can_read_path` denies with `NotFound` (it hides existence)
|
||||
// and, for some paths, `NotAuthorized` — both mean "not visible to the
|
||||
// caller", so drop the row. Any other error is a real failure.
|
||||
match require_can_read_path(&authed, &user_db, &w_id, row.kind, &row.path).await {
|
||||
match require_can_read_path(&authed, None, &user_db, &w_id, row.kind, &row.path).await {
|
||||
Ok(()) => {
|
||||
row.can_write = false;
|
||||
out.push(row);
|
||||
@@ -574,7 +587,9 @@ async fn update_draft(
|
||||
// answer whether an item was moved away from a path they only guessed at.
|
||||
Err(Error::NotAuthorized(e)) if moved_to.is_some() => {
|
||||
return Err(Error::NotAuthorized(
|
||||
match require_can_read_path(&authed, &user_db, &w_id, kind, url_path).await {
|
||||
match require_can_read_path(&authed, Some(&db), &user_db, &w_id, kind, url_path)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
"this draft's item was moved to a path you cannot write".to_string()
|
||||
}
|
||||
@@ -734,7 +749,9 @@ async fn update_draft(
|
||||
// module. Without it, discarding at a guessed path reads `draft_move`.
|
||||
let disclosed = match moved_to {
|
||||
Some(dest) => {
|
||||
match require_can_read_path(&authed, &user_db, &w_id, kind, &dest).await {
|
||||
match require_can_read_path(&authed, Some(&db), &user_db, &w_id, kind, &dest)
|
||||
.await
|
||||
{
|
||||
Ok(()) => Some(dest),
|
||||
Err(Error::NotFound(_))
|
||||
| Err(Error::NotAuthorized(_))
|
||||
@@ -1518,7 +1535,7 @@ async fn get_draft_for_user(
|
||||
"drafts for this item kind are private to their owner".to_string(),
|
||||
));
|
||||
}
|
||||
require_can_read_path(&authed, &user_db, &w_id, kind, path).await?;
|
||||
require_can_read_path(&authed, Some(&db), &user_db, &w_id, kind, path).await?;
|
||||
|
||||
// Username -> email, scoped to the workspace. None signals "fetch the
|
||||
// legacy NULL-email row" (distinct from a username with no draft, which
|
||||
@@ -1577,7 +1594,7 @@ async fn get_own_draft(
|
||||
Path((w_id, kind, path)): Path<(String, UserDraftItemKind, windmill_common::utils::StripPath)>,
|
||||
) -> Result<Json<Option<DraftForUser>>> {
|
||||
let path = path.to_path();
|
||||
require_can_read_path(&authed, &user_db, &w_id, kind, path).await?;
|
||||
require_can_read_path(&authed, Some(&db), &user_db, &w_id, kind, path).await?;
|
||||
let row = sqlx::query_as!(
|
||||
DraftForUser,
|
||||
r#"SELECT value as "value!: sqlx::types::Json<Box<serde_json::value::RawValue>>", created_at
|
||||
@@ -1654,8 +1671,7 @@ pub(crate) async fn require_can_write_path(
|
||||
if has_write(authed) {
|
||||
return Ok(());
|
||||
}
|
||||
let refreshed =
|
||||
windmill_api_auth::maybe_refresh_folders(path, w_id, authed.clone(), db).await;
|
||||
let refreshed = with_current_folders(authed.clone(), w_id, db).await?;
|
||||
if has_write(&refreshed) {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -1700,6 +1716,17 @@ pub(crate) async fn require_can_write_path(
|
||||
)))
|
||||
}
|
||||
|
||||
/// `authed` with its folder set re-read, for a folder created since the identity was cached.
|
||||
/// Its groups are kept, not re-read: they can be narrower than the stored memberships (an
|
||||
/// external IdP token carries only the managed groups it names), and folders reached through a
|
||||
/// stored group the identity does not hold must stay out.
|
||||
async fn with_current_folders(authed: ApiAuthed, w_id: &str, db: &DB) -> Result<ApiAuthed> {
|
||||
let folders =
|
||||
windmill_common::auth::get_folders_for_user(w_id, &authed.username, &authed.groups, db)
|
||||
.await?;
|
||||
Ok(ApiAuthed { folders, ..authed })
|
||||
}
|
||||
|
||||
/// Resolves to `Ok(())` if `authed` can read at `path`. Three layers:
|
||||
/// 1. admin → always.
|
||||
/// 2. Path-prefix match against own `u/{username}`, a group in `authed.groups`, or any
|
||||
@@ -1714,8 +1741,12 @@ pub(crate) async fn require_can_write_path(
|
||||
/// deployed content, so an operator can view a collaborator's draft for the
|
||||
/// cross-user kinds they can already read, while never writing one. Drawer
|
||||
/// kinds never reach this (`get_draft_for_user` rejects them up front).
|
||||
///
|
||||
/// `refresh_from` re-reads the folder set when `path`'s folder is missing from it; a caller
|
||||
/// checking many paths passes `None` after refreshing `authed` once itself.
|
||||
async fn require_can_read_path(
|
||||
authed: &ApiAuthed,
|
||||
refresh_from: Option<&DB>,
|
||||
user_db: &UserDB,
|
||||
w_id: &str,
|
||||
kind: UserDraftItemKind,
|
||||
@@ -1734,9 +1765,18 @@ async fn require_can_read_path(
|
||||
"g" if authed.groups.iter().any(|g| g == parts[1]) => return Ok(()),
|
||||
"f" => {
|
||||
let folder = parts[1];
|
||||
if authed.folders.iter().any(|(name, _, _)| name == folder) {
|
||||
let can_read = |a: &ApiAuthed| a.folders.iter().any(|(name, _, _)| name == folder);
|
||||
if can_read(authed) {
|
||||
return Ok(());
|
||||
}
|
||||
// As `require_can_write_path` does: a folder created since the identity was
|
||||
// cached has no deployed row for the probe below, so only a refresh finds it.
|
||||
if let Some(db) = refresh_from {
|
||||
let refreshed = with_current_folders(authed.clone(), w_id, db).await?;
|
||||
if can_read(&refreshed) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -6638,15 +6638,18 @@ async fn verify_suspended_secret(
|
||||
approver: &QueryApprover,
|
||||
secret: String,
|
||||
) -> Result<(), Error> {
|
||||
let key = get_workspace_key(w_id, db).await?;
|
||||
let mut mac = HmacSha256::new_from_slice(key.as_bytes()).map_err(to_anyhow)?;
|
||||
mac.update(job_id.as_bytes());
|
||||
mac.update(resume_id.to_be_bytes().as_ref());
|
||||
if let Some(approver) = approver.approver.clone() {
|
||||
mac.update(approver.as_bytes());
|
||||
let valid = windmill_common::variables::verify_resume_signature(
|
||||
db,
|
||||
w_id,
|
||||
job_id,
|
||||
resume_id,
|
||||
approver.approver.as_deref(),
|
||||
&hex::decode(secret)?,
|
||||
)
|
||||
.await?;
|
||||
if !valid {
|
||||
return Err(anyhow::anyhow!("Invalid signature").into());
|
||||
}
|
||||
mac.verify_slice(hex::decode(secret)?.as_ref())
|
||||
.map_err(|_| anyhow::anyhow!("Invalid signature"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -7183,13 +7186,7 @@ fn create_signature(
|
||||
resume_id: u32,
|
||||
approver: Option<String>,
|
||||
) -> Result<String, Error> {
|
||||
let mut mac = HmacSha256::new_from_slice(key.as_bytes()).map_err(to_anyhow)?;
|
||||
mac.update(job_id.as_bytes());
|
||||
mac.update(resume_id.to_be_bytes().as_ref());
|
||||
if let Some(approver) = approver {
|
||||
mac.update(approver.as_bytes());
|
||||
}
|
||||
Ok(hex::encode(mac.finalize().into_bytes()))
|
||||
windmill_common::variables::resume_signature(&key, job_id, resume_id, approver.as_deref())
|
||||
}
|
||||
|
||||
fn build_resume_url(
|
||||
|
||||
@@ -634,7 +634,7 @@ pub async fn run_server(
|
||||
#[cfg(feature = "mcp")]
|
||||
if server_mode || mcp_mode {
|
||||
use mcp::{
|
||||
add_www_authenticate_header, add_www_authenticate_header_gateway,
|
||||
add_www_authenticate_header, add_www_authenticate_header_gateway, count_mcp_url,
|
||||
extract_workspace_from_token, reject_token_query_param,
|
||||
};
|
||||
let (mcp_router, session_router, mcp_cancellation_token) = setup_mcp_server(
|
||||
@@ -649,6 +649,7 @@ pub async fn run_server(
|
||||
|| axum::middleware::from_fn(mcp::external_idp::external_idp_auth);
|
||||
let workspaced_mcp_router = mcp_router
|
||||
.clone()
|
||||
.route_layer(from_fn_with_state("workspace", count_mcp_url))
|
||||
.route_layer(from_extractor::<ApiAuthed>())
|
||||
.layer(external_idp_auth())
|
||||
.layer(axum::middleware::from_fn(reject_token_query_param))
|
||||
@@ -656,6 +657,7 @@ pub async fn run_server(
|
||||
.layer(axum::middleware::from_fn(extract_and_store_workspace_id));
|
||||
// Gateway MCP router — resolves workspace from token
|
||||
let gateway_mcp_router = mcp_router
|
||||
.route_layer(from_fn_with_state("gateway", count_mcp_url))
|
||||
.route_layer(from_extractor::<ApiAuthed>())
|
||||
.layer(external_idp_auth())
|
||||
.layer(axum::middleware::from_fn(extract_workspace_from_token))
|
||||
@@ -665,6 +667,7 @@ pub async fn run_server(
|
||||
));
|
||||
// The workspace server. Its tools name their workspace; the token bounds which.
|
||||
let gateway_session_router = session_router
|
||||
.route_layer(from_fn_with_state("global", count_mcp_url))
|
||||
.route_layer(from_extractor::<ApiAuthed>())
|
||||
.layer(external_idp_auth())
|
||||
.layer(axum::middleware::from_fn(extract_workspace_from_token))
|
||||
@@ -1423,7 +1426,7 @@ pub async fn run_server(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn is_up_to_date() -> Result<String, AppError> {
|
||||
async fn is_up_to_date(_authed: ApiAuthed) -> Result<String, AppError> {
|
||||
let error_reading_version = || anyhow::anyhow!("Error reading latest released version");
|
||||
let version = HTTP_CLIENT
|
||||
.get("https://api.github.com/repos/windmill-labs/windmill/releases/latest")
|
||||
@@ -1451,13 +1454,18 @@ async fn is_up_to_date() -> Result<String, AppError> {
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
async fn git_v() -> String {
|
||||
format!("EE {GIT_VERSION}")
|
||||
}
|
||||
|
||||
const EDITION: &str = "EE";
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
async fn git_v() -> String {
|
||||
format!("CE {GIT_VERSION}")
|
||||
const EDITION: &str = "CE";
|
||||
|
||||
/// Load balancers and k8s probes call this without credentials, so it must keep answering 200
|
||||
/// to them; the exact version is kept for authenticated callers.
|
||||
async fn git_v(authed: Option<ApiAuthed>) -> String {
|
||||
if authed.is_some() {
|
||||
format!("{EDITION} {GIT_VERSION}")
|
||||
} else {
|
||||
EDITION.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// The caller's address as token IP allowlists see it, so a device can learn what to put in a
|
||||
@@ -1515,17 +1523,49 @@ async fn ee_license() -> String {
|
||||
}
|
||||
}
|
||||
|
||||
async fn openapi() -> Response {
|
||||
const OPENAPI_YAML: &str = include_str!("../openapi-deref.yaml");
|
||||
const OPENAPI_JSON: &str = include_str!("../openapi-deref.json");
|
||||
|
||||
// The spec stays public (the API docs page, SDK generation), but release builds stamp the exact
|
||||
// version into `info.version`, which a logged-out caller must not read: it gets the edition.
|
||||
static OPENAPI_YAML_ANON: std::sync::LazyLock<String> =
|
||||
std::sync::LazyLock::new(|| hide_spec_version(OPENAPI_YAML, "\n version: ", "\n"));
|
||||
static OPENAPI_JSON_ANON: std::sync::LazyLock<String> =
|
||||
std::sync::LazyLock::new(|| hide_spec_version(OPENAPI_JSON, "\"version\": \"", "\""));
|
||||
|
||||
/// Replaces the value after the first `key` with the edition: `info` is the first block carrying
|
||||
/// a `version` key in both generated files.
|
||||
fn hide_spec_version(spec: &str, key: &str, end: &str) -> String {
|
||||
let Some(start) = spec.find(key).map(|i| i + key.len()) else {
|
||||
return spec.to_string();
|
||||
};
|
||||
let Some(len) = spec[start..].find(end) else {
|
||||
return spec.to_string();
|
||||
};
|
||||
format!("{}{EDITION}{}", &spec[..start], &spec[start + len..])
|
||||
}
|
||||
|
||||
async fn openapi(authed: Option<ApiAuthed>) -> Response {
|
||||
let spec = if authed.is_some() {
|
||||
OPENAPI_YAML
|
||||
} else {
|
||||
OPENAPI_YAML_ANON.as_str()
|
||||
};
|
||||
Response::builder()
|
||||
.header("content-type", "application/yaml")
|
||||
.body(Body::from(include_str!("../openapi-deref.yaml")))
|
||||
.body(Body::from(spec))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn openapi_json() -> Response {
|
||||
async fn openapi_json(authed: Option<ApiAuthed>) -> Response {
|
||||
let spec = if authed.is_some() {
|
||||
OPENAPI_JSON
|
||||
} else {
|
||||
OPENAPI_JSON_ANON.as_str()
|
||||
};
|
||||
Response::builder()
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(include_str!("../openapi-deref.json")))
|
||||
.body(Body::from(spec))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
@@ -1628,3 +1668,34 @@ pub async fn cleanup_stale_server_heartbeats(db: &DB) -> anyhow::Result<u64> {
|
||||
.await?;
|
||||
Ok(res.rows_affected())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod openapi_version_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn anonymous_spec_carries_the_edition_only() {
|
||||
for (anon, full, expected) in [
|
||||
(
|
||||
OPENAPI_YAML_ANON.as_str(),
|
||||
OPENAPI_YAML,
|
||||
format!(" version: {EDITION}"),
|
||||
),
|
||||
(
|
||||
OPENAPI_JSON_ANON.as_str(),
|
||||
OPENAPI_JSON,
|
||||
format!(" \"version\": \"{EDITION}\","),
|
||||
),
|
||||
] {
|
||||
let changed: Vec<&str> = anon
|
||||
.lines()
|
||||
.zip(full.lines())
|
||||
.filter(|(a, f)| a != f)
|
||||
.map(|(a, _)| a)
|
||||
.collect();
|
||||
assert_eq!(anon.lines().count(), full.lines().count());
|
||||
assert_eq!(changed.len(), 1, "only info.version may differ");
|
||||
assert_eq!(changed[0], expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use windmill_mcp::common::SESSION_SCOPE;
|
||||
use windmill_mcp::common::{parse_mcp_scopes, SESSION_SCOPE};
|
||||
use windmill_mcp::server::{
|
||||
LocalSessionManager, McpToken, MultiWorkspaceMcp, NoEndpointTools, Runner, SessionRunner,
|
||||
StreamableHttpServerConfig, StreamableHttpService,
|
||||
@@ -45,7 +45,7 @@ use windmill_mcp::server::{
|
||||
use windmill_mcp::WorkspaceId;
|
||||
|
||||
use axum::{
|
||||
extract::{Extension, Path},
|
||||
extract::{Extension, Path, State},
|
||||
http::Request,
|
||||
middleware::Next,
|
||||
response::{IntoResponse, Response},
|
||||
@@ -405,6 +405,20 @@ impl McpBackend for WindmillBackend {
|
||||
"endpoint_tool_call",
|
||||
&endpoint_tool.name,
|
||||
);
|
||||
if let Ok(scope) = parse_mcp_scopes(auth.scopes.as_deref().unwrap_or_default()) {
|
||||
let shape = scope.endpoint_shape();
|
||||
windmill_common::feature_usage::log_feature_usage("mcp", "endpoint_call_shape", shape);
|
||||
if ["create", "update", "delete", "apply"]
|
||||
.iter()
|
||||
.any(|verb| endpoint_tool.name.starts_with(verb))
|
||||
{
|
||||
windmill_common::feature_usage::log_feature_usage(
|
||||
"mcp",
|
||||
"endpoint_write_shape",
|
||||
shape,
|
||||
);
|
||||
}
|
||||
}
|
||||
let args_map = match &args {
|
||||
Value::Object(map) => map,
|
||||
_ => {
|
||||
@@ -612,6 +626,19 @@ fn serves_session_toolset(scopes: &[String]) -> bool {
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct McpEndpoint(pub &'static str);
|
||||
|
||||
/// Counts MCP messages by the URL that served them. Layered inside authentication, so a probe
|
||||
/// without a valid token is not counted; a client's `GET` stream attempt carries no message.
|
||||
pub async fn count_mcp_url(
|
||||
State(url): State<&'static str>,
|
||||
request: Request<axum::body::Body>,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
if request.method() == axum::http::Method::POST {
|
||||
windmill_common::feature_usage::log_feature_usage("mcp", "url_request", url);
|
||||
}
|
||||
next.run(request).await
|
||||
}
|
||||
|
||||
/// Extract workspace ID from path and store it in request extensions
|
||||
pub async fn extract_and_store_workspace_id(
|
||||
Path(params): Path<String>,
|
||||
|
||||
@@ -12,7 +12,7 @@ mod utils;
|
||||
// Re-export only what's needed externally
|
||||
pub mod oauth_server;
|
||||
pub use core::{
|
||||
add_www_authenticate_header, add_www_authenticate_header_gateway,
|
||||
add_www_authenticate_header, add_www_authenticate_header_gateway, count_mcp_url,
|
||||
extract_and_store_workspace_id, extract_workspace_from_token, list_tools_service,
|
||||
reject_token_query_param, setup_mcp_server, toolset_service, McpEndpoint,
|
||||
};
|
||||
|
||||
@@ -693,8 +693,8 @@ async fn handle_refresh_token_grant(
|
||||
Some(&new_access_token)
|
||||
};
|
||||
let new_refresh_token = rd_string(32);
|
||||
// Re-issues the already-approved (hence already-contained) scopes verbatim;
|
||||
// containment is enforced once at approval time, so no re-check here.
|
||||
// Re-issues the grant's scopes verbatim: containment is enforced where they are written, at
|
||||
// approval and by `update_token_scopes`, so no re-check here.
|
||||
let scopes = token_row.scopes;
|
||||
|
||||
// Create new access token (rejects archived workspaces inline)
|
||||
|
||||
@@ -203,11 +203,10 @@ async fn verify_slack_callback_signature(
|
||||
/// whether or not a Slack signing secret is set.
|
||||
type SlackPayloadHmac = Hmac<Sha256>;
|
||||
|
||||
/// Domain-separation tag prepended to every Slack-payload MAC. The workspace key is also used
|
||||
/// for resume-secret signatures (`create_signature` in `jobs.rs`), and those secrets are
|
||||
/// distributed to approvers in resume URLs — so a fixed, scheme-specific prefix makes the two
|
||||
/// MAC families non-interchangeable by construction rather than relying on their byte layouts
|
||||
/// happening to differ. Bump the version suffix if the signed layout ever changes.
|
||||
/// Domain-separation tag prepended to every Slack-payload MAC, as the workspace key also signs
|
||||
/// job tokens, S3 objects and OAuth states. A prefix only separates it from message layouts that
|
||||
/// cannot start with it, so a layout whose leading bytes a caller picks (as resume URLs have)
|
||||
/// must use a key of its own. Bump the version suffix if the signed layout ever changes.
|
||||
const SLACK_PAYLOAD_HMAC_DOMAIN: &[u8] = b"slack_payload_v1\0";
|
||||
|
||||
/// Sign the security-sensitive fields of a Slack callback payload with the workspace key.
|
||||
|
||||
@@ -436,6 +436,109 @@ pub fn approval_token_from_key(key: &str, job_id: uuid::Uuid) -> crate::error::R
|
||||
Ok(hex::encode(mac.finalize().into_bytes()))
|
||||
}
|
||||
|
||||
/// Resume URLs are signed with a key of their own derived from the workspace key, which signs
|
||||
/// other kinds of message too. Every message the workspace key itself signs is longer than this
|
||||
/// domain, so none of their signatures equals the derived key.
|
||||
const RESUME_KEY_DOMAIN: &[u8] = b"resume_v2";
|
||||
|
||||
fn resume_mac(
|
||||
key: &[u8],
|
||||
job_id: uuid::Uuid,
|
||||
resume_id: u32,
|
||||
approver: Option<&str>,
|
||||
) -> crate::error::Result<hmac::Hmac<sha2::Sha256>> {
|
||||
use hmac::{Hmac, Mac};
|
||||
let mut mac = Hmac::<sha2::Sha256>::new_from_slice(key)
|
||||
.map_err(|e| crate::Error::internal_err(format!("HMAC key error: {e}")))?;
|
||||
mac.update(job_id.as_bytes());
|
||||
mac.update(&resume_id.to_be_bytes());
|
||||
if let Some(approver) = approver {
|
||||
mac.update(approver.as_bytes());
|
||||
}
|
||||
Ok(mac)
|
||||
}
|
||||
|
||||
fn resume_key(workspace_key: &str) -> crate::error::Result<Vec<u8>> {
|
||||
use hmac::{Hmac, Mac};
|
||||
let mut mac = Hmac::<sha2::Sha256>::new_from_slice(workspace_key.as_bytes())
|
||||
.map_err(|e| crate::Error::internal_err(format!("HMAC key error: {e}")))?;
|
||||
mac.update(RESUME_KEY_DOMAIN);
|
||||
Ok(mac.finalize().into_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// The signature in a resume or cancel URL of a suspended job.
|
||||
pub fn resume_signature(
|
||||
workspace_key: &str,
|
||||
job_id: uuid::Uuid,
|
||||
resume_id: u32,
|
||||
approver: Option<&str>,
|
||||
) -> crate::error::Result<String> {
|
||||
use hmac::Mac;
|
||||
let mac = resume_mac(&resume_key(workspace_key)?, job_id, resume_id, approver)?;
|
||||
Ok(hex::encode(mac.finalize().into_bytes()))
|
||||
}
|
||||
|
||||
/// Whether the bare-key message of a resume URL has the layout of another message the workspace
|
||||
/// key signs or has signed: a job token, a Slack payload, an S3 object or an OAuth state (four to
|
||||
/// six fields, depending on the release). Any new kind of message must be signed with a key of
|
||||
/// its own (as [`resume_key`]) or be listed here.
|
||||
fn reads_as_other_token(job_id: uuid::Uuid, resume_id: u32, approver: Option<&str>) -> bool {
|
||||
let tail = [
|
||||
&resume_id.to_be_bytes()[..],
|
||||
approver.unwrap_or_default().as_bytes(),
|
||||
]
|
||||
.concat();
|
||||
let message = [&job_id.as_bytes()[..], &tail].concat();
|
||||
[
|
||||
VIEW_TOKEN_DOMAIN,
|
||||
PUBLIC_VIEW_TOKEN_DOMAIN,
|
||||
b"approval_token",
|
||||
]
|
||||
.contains(&tail.as_slice())
|
||||
|| message.starts_with(b"slack_payload_v1\0")
|
||||
|| message.starts_with(b"file_key=")
|
||||
|| std::str::from_utf8(&message).is_ok_and(|m| m.split(':').count() >= 4)
|
||||
}
|
||||
|
||||
/// Migration whose `installed_on` is when the instance started signing with the resume key.
|
||||
const RESUME_KEY_MIGRATION: i64 = 20261201163725;
|
||||
|
||||
/// Verify a signature made by [`resume_signature`]. One made with the bare workspace key is taken
|
||||
/// only for a job that predates the resume key, plus a day for a rolling upgrade, whose processes
|
||||
/// on an older release still sign that way.
|
||||
pub async fn verify_resume_signature(
|
||||
db: &DB,
|
||||
w_id: &str,
|
||||
job_id: uuid::Uuid,
|
||||
resume_id: u32,
|
||||
approver: Option<&str>,
|
||||
signature: &[u8],
|
||||
) -> crate::error::Result<bool> {
|
||||
use hmac::Mac;
|
||||
let workspace_key = get_workspace_key(w_id, db).await?;
|
||||
let verifies = |key: &[u8]| -> crate::error::Result<bool> {
|
||||
Ok(resume_mac(key, job_id, resume_id, approver)?
|
||||
.verify_slice(signature)
|
||||
.is_ok())
|
||||
};
|
||||
if verifies(&resume_key(&workspace_key)?)? {
|
||||
return Ok(true);
|
||||
}
|
||||
if reads_as_other_token(job_id, resume_id, approver) || !verifies(workspace_key.as_bytes())? {
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(sqlx::query_scalar!(
|
||||
"SELECT EXISTS (SELECT 1 FROM v2_job j, _sqlx_migrations m
|
||||
WHERE j.id = $1 AND j.workspace_id = $2 AND m.version = $3
|
||||
AND j.created_at < m.installed_on + interval '1 day') AS \"accepted!\"",
|
||||
job_id,
|
||||
w_id,
|
||||
RESUME_KEY_MIGRATION,
|
||||
)
|
||||
.fetch_one(db)
|
||||
.await?)
|
||||
}
|
||||
|
||||
/// Domain separator of the member-audience view token (see [`generate_view_token`]).
|
||||
pub const VIEW_TOKEN_DOMAIN: &[u8] = b"view_token";
|
||||
|
||||
|
||||
@@ -34,6 +34,21 @@ pub struct McpScopeConfig {
|
||||
}
|
||||
|
||||
impl McpScopeConfig {
|
||||
/// How the token came to have endpoint tools, as a closed set of telemetry keys.
|
||||
pub fn endpoint_shape(&self) -> &'static str {
|
||||
if self.all {
|
||||
"all"
|
||||
} else if self.favorites {
|
||||
"favorites"
|
||||
} else if self.endpoints.is_empty() {
|
||||
"runnables_only"
|
||||
} else if self.endpoints.iter().any(|e| e == "*") {
|
||||
"selection_all_endpoints"
|
||||
} else {
|
||||
"selection_picked_endpoints"
|
||||
}
|
||||
}
|
||||
|
||||
pub fn allows_workspace(&self, workspace_id: &str) -> bool {
|
||||
self.workspaces
|
||||
.as_ref()
|
||||
@@ -415,6 +430,31 @@ mod tests {
|
||||
parse_mcp_scopes(&scopes.iter().map(|s| s.to_string()).collect::<Vec<_>>()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_endpoint_shape() {
|
||||
assert_eq!(cfg(&["mcp:all"]).endpoint_shape(), "all");
|
||||
assert_eq!(
|
||||
cfg(&["mcp:favorites", "mcp:hub:slack"]).endpoint_shape(),
|
||||
"favorites"
|
||||
);
|
||||
assert_eq!(
|
||||
cfg(&["mcp:scripts:f/a/*", "mcp:endpoints:*"]).endpoint_shape(),
|
||||
"selection_all_endpoints"
|
||||
);
|
||||
assert_eq!(
|
||||
cfg(&["mcp:all:f/a/*"]).endpoint_shape(),
|
||||
"selection_all_endpoints"
|
||||
);
|
||||
assert_eq!(
|
||||
cfg(&["mcp:scripts:f/a/*", "mcp:endpoints:listJobs,getJob"]).endpoint_shape(),
|
||||
"selection_picked_endpoints"
|
||||
);
|
||||
assert_eq!(
|
||||
cfg(&["mcp:scripts:f/a/*"]).endpoint_shape(),
|
||||
"runnables_only"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_any() {
|
||||
// mcp:all grants everything by path.
|
||||
|
||||
@@ -243,9 +243,7 @@ pub(super) fn workspace_not_granted(workspace_id: &str) -> ErrorData {
|
||||
}
|
||||
|
||||
/// How an endpoint tool interacts with the token's `mcp:scripts:` / `mcp:flows:`
|
||||
/// path scopes. Mirrored in
|
||||
/// `frontend/src/lib/components/mcp/endpointScopePolicy.ts` so the scope picker
|
||||
/// only advertises tools this policy will actually list — keep the two in sync.
|
||||
/// path scopes.
|
||||
enum EndpointPathPolicy {
|
||||
/// Executes the script/flow named by the `path` argument. Gated by the
|
||||
/// script/flow scope alone (an endpoint scope is not enough to run things):
|
||||
|
||||
@@ -752,10 +752,17 @@ pub const TEMP_SCRIPT_REFS_ARG: &str = "_TEMP_SCRIPT_REFS";
|
||||
/// `WM_OBJECT_PATH` derive from it; the worker honors it only on `JobKind::Preview` jobs.
|
||||
pub const FLOW_PATH_ARG: &str = "_FLOW_PATH";
|
||||
|
||||
/// Job-arg keys the run form sets for PowerShell's common parameters; the worker turns them
|
||||
/// into preference variables of the script instead of passing them as parameters.
|
||||
pub const PS_VERBOSE_ARG: &str = "_wm_ps_verbose";
|
||||
pub const PS_DEBUG_ARG: &str = "_wm_ps_debug";
|
||||
pub const PS_ERROR_ACTION_ARG: &str = "_wm_ps_error_action";
|
||||
|
||||
/// Job-arg keys that steer *how* a runnable runs rather than what it is given: which
|
||||
/// function the worker calls instead of `main` ([`ENTRYPOINT_OVERRIDE`]), what module files
|
||||
/// are written into the job directory ([`MODULES_ARG`]), where its workspace imports
|
||||
/// resolve from ([`TEMP_SCRIPT_REFS_ARG`]) and where its state lives ([`FLOW_PATH_ARG`]).
|
||||
/// resolve from ([`TEMP_SCRIPT_REFS_ARG`]), where its state lives ([`FLOW_PATH_ARG`]) and
|
||||
/// PowerShell's preference variables ([`PS_VERBOSE_ARG`] and its siblings).
|
||||
///
|
||||
/// Each is legitimate for a caller that runs code it authored under its own identity (the
|
||||
/// script editor's preprocessor test, dynamic-select helpers, the CLI, workflow-as-code), so
|
||||
@@ -763,11 +770,14 @@ pub const FLOW_PATH_ARG: &str = "_FLOW_PATH";
|
||||
/// payload runs under somebody else's identity — an HTTP route body, a native trigger
|
||||
/// message, a public app viewer's inputs — which is what `sanitize_untrusted_args` in
|
||||
/// `windmill_common::jobs` drops.
|
||||
pub const RESERVED_CONTROL_ARGS: [&str; 4] = [
|
||||
pub const RESERVED_CONTROL_ARGS: [&str; 7] = [
|
||||
ENTRYPOINT_OVERRIDE,
|
||||
MODULES_ARG,
|
||||
TEMP_SCRIPT_REFS_ARG,
|
||||
FLOW_PATH_ARG,
|
||||
PS_VERBOSE_ARG,
|
||||
PS_DEBUG_ARG,
|
||||
PS_ERROR_ACTION_ARG,
|
||||
];
|
||||
|
||||
/// Reserved job-arg key holding the inbound W3C `traceparent` captured from the
|
||||
|
||||
@@ -4361,13 +4361,8 @@ pub async fn handle_wac_v2_output(
|
||||
windmill_common::variables::approval_token_from_key(&wkey, job.id)?;
|
||||
|
||||
let (resume_url, cancel_url, approval_page_url) = {
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(wkey.as_bytes())
|
||||
.map_err(|e| error::Error::internal_err(format!("HMAC key error: {e}")))?;
|
||||
mac.update(job.id.as_bytes());
|
||||
mac.update(resume_id.to_be_bytes().as_ref());
|
||||
let signature = hex::encode(mac.finalize().into_bytes());
|
||||
let signature =
|
||||
windmill_common::variables::resume_signature(&wkey, job.id, resume_id, None)?;
|
||||
|
||||
let base_url = (**windmill_common::BASE_URL.load()).clone();
|
||||
let w_id = &job.workspace_id;
|
||||
|
||||
@@ -6,6 +6,7 @@ use sqlx::types::Json;
|
||||
use tokio::process::Command;
|
||||
use windmill_common::client::AuthedClient;
|
||||
use windmill_common::error::Error;
|
||||
use windmill_common::jobs::{PS_DEBUG_ARG, PS_ERROR_ACTION_ARG, PS_VERBOSE_ARG};
|
||||
use windmill_common::scripts::ScriptLang;
|
||||
use windmill_common::worker::{to_raw_value, write_file, Connection};
|
||||
use windmill_common::workspace_dependencies::clean_lock_from_annotations;
|
||||
@@ -37,6 +38,22 @@ use crate::{
|
||||
POWERSHELL_REPO_URL, TZ_ENV,
|
||||
};
|
||||
|
||||
/// Escape a value for interpolation into a single-quoted PowerShell string literal.
|
||||
///
|
||||
/// PowerShell treats U+2018, U+2019, U+201A and U+201B as single quotes too, and any
|
||||
/// of them closes a literal opened by an ASCII `'`, so all five must be doubled (same
|
||||
/// as PowerShell's own `CodeGeneration.EscapeSingleQuotedStringContent`).
|
||||
fn escape_pwsh_single_quoted(s: &str) -> String {
|
||||
let mut escaped = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
if matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}') {
|
||||
escaped.push(c);
|
||||
}
|
||||
escaped.push(c);
|
||||
}
|
||||
escaped
|
||||
}
|
||||
|
||||
fn val_to_pwsh_param(v: serde_json::Value) -> String {
|
||||
match v {
|
||||
serde_json::Value::Array(x) => format!(
|
||||
@@ -48,13 +65,13 @@ fn val_to_pwsh_param(v: serde_json::Value) -> String {
|
||||
),
|
||||
serde_json::Value::Object(x) => {
|
||||
let str = serde_json::to_string(&x).unwrap_or_else(|_| "{}".to_string());
|
||||
let escaped = str.replace("'", "''");
|
||||
let escaped = escape_pwsh_single_quoted(&str);
|
||||
format!("(ConvertFrom-Json '{escaped}')")
|
||||
}
|
||||
serde_json::Value::Null => "$null".to_string(),
|
||||
serde_json::Value::Bool(x) => format!("${x}"),
|
||||
serde_json::Value::String(x) => {
|
||||
let escaped = x.replace("'", "''");
|
||||
let escaped = escape_pwsh_single_quoted(&x);
|
||||
format!("'{escaped}'")
|
||||
}
|
||||
serde_json::Value::Number(x) => x.to_string(),
|
||||
@@ -415,17 +432,17 @@ pub async fn handle_powershell_job(
|
||||
// (not CLI args) so they only affect user code, not module loading.
|
||||
let mut preference_lines: Vec<String> = Vec::new();
|
||||
if let Some(args_map) = job_args {
|
||||
if let Some(v) = args_map.get("_wm_ps_verbose") {
|
||||
if let Some(v) = args_map.get(PS_VERBOSE_ARG) {
|
||||
if serde_json::from_str::<bool>(v.get()).unwrap_or(false) {
|
||||
preference_lines.push("$VerbosePreference = 'Continue'".to_string());
|
||||
}
|
||||
}
|
||||
if let Some(v) = args_map.get("_wm_ps_debug") {
|
||||
if let Some(v) = args_map.get(PS_DEBUG_ARG) {
|
||||
if serde_json::from_str::<bool>(v.get()).unwrap_or(false) {
|
||||
preference_lines.push("$DebugPreference = 'Continue'".to_string());
|
||||
}
|
||||
}
|
||||
if let Some(v) = args_map.get("_wm_ps_error_action") {
|
||||
if let Some(v) = args_map.get(PS_ERROR_ACTION_ARG) {
|
||||
if let Ok(action) = serde_json::from_str::<String>(v.get()) {
|
||||
if matches!(action.as_str(), "Stop" | "Continue" | "SilentlyContinue") {
|
||||
preference_lines.push(format!("$ErrorActionPreference = '{action}'"));
|
||||
@@ -536,9 +553,9 @@ pub async fn handle_powershell_job(
|
||||
// Defense-in-depth: escape single quotes so a name/version can never
|
||||
// break out of the PowerShell string literal, even if validation is
|
||||
// bypassed. Mirrors val_to_pwsh_param.
|
||||
let name = module_req.name.replace("'", "''");
|
||||
let name = escape_pwsh_single_quoted(&module_req.name);
|
||||
if let Some(version) = &module_req.version {
|
||||
let version = version.replace("'", "''");
|
||||
let version = escape_pwsh_single_quoted(version);
|
||||
format!("@{{ Name = '{}'; Version = '{}' }}", name, version)
|
||||
} else {
|
||||
format!("@{{ Name = '{}'; Version = $null }}", name)
|
||||
@@ -558,11 +575,11 @@ pub async fn handle_powershell_job(
|
||||
// break out of the literal (same sink as the module names above).
|
||||
.replace(
|
||||
"{private_repo_url}",
|
||||
&powershell_repo_url.unwrap_or_default().replace("'", "''"),
|
||||
&escape_pwsh_single_quoted(&powershell_repo_url.unwrap_or_default()),
|
||||
)
|
||||
.replace(
|
||||
"{private_repo_pat}",
|
||||
&powershell_repo_pat.unwrap_or_default().replace("'", "''"),
|
||||
&escape_pwsh_single_quoted(&powershell_repo_pat.unwrap_or_default()),
|
||||
)
|
||||
.replace("{modules}", &modules_list);
|
||||
let mut cmd = Command::new(POWERSHELL_PATH.as_str());
|
||||
@@ -1228,4 +1245,22 @@ Write-Host "Hello""#;
|
||||
assert_eq!(modules.len(), 1);
|
||||
assert_eq!(modules[0].name, "PSWriteColor");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_raw_to_pwsh_param_typographic_quotes() {
|
||||
for q in ['\'', '\u{2018}', '\u{2019}', '\u{201A}', '\u{201B}'] {
|
||||
assert_eq!(
|
||||
raw_to_pwsh_param(&format!("\"it{q}s\"")),
|
||||
format!("'it{q}{q}s'")
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
raw_to_pwsh_param("[\"it\u{2019}s\"]"),
|
||||
"@('it\u{2019}\u{2019}s')"
|
||||
);
|
||||
assert_eq!(
|
||||
raw_to_pwsh_param("{\"a\":\"it\u{2019}s\"}"),
|
||||
"(ConvertFrom-Json '{\"a\":\"it\u{2019}\u{2019}s\"}')"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts";
|
||||
import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts";
|
||||
import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts";
|
||||
|
||||
export const VERSION = "v1.894.1";
|
||||
export const VERSION = "v1.895.1";
|
||||
|
||||
export async function login(email: string, password: string): Promise<string> {
|
||||
return await windmill.UserService.login({
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@windmill-labs/chat-sdk",
|
||||
"version": "1.894.1",
|
||||
"version": "1.895.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@windmill-labs/chat-sdk",
|
||||
"version": "1.894.1",
|
||||
"version": "1.895.1",
|
||||
"license": "Apache-2.0",
|
||||
"devDependencies": {
|
||||
"@ai-sdk/react": "^4.0.102",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@windmill-labs/chat-sdk",
|
||||
"description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app",
|
||||
"version": "1.894.1",
|
||||
"version": "1.895.1",
|
||||
"author": "Ruben Fiszel",
|
||||
"license": "Apache-2.0",
|
||||
"homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme",
|
||||
|
||||
@@ -10,6 +10,16 @@ let GLOBAL_VERSIONS: {
|
||||
};
|
||||
|
||||
export function updateGlobalVersions(version: string) {
|
||||
// A server answers with the edition alone ("EE"/"CE") when the request's token cannot
|
||||
// authenticate on a global route (none, scoped, workspace-bound or a job token). Only
|
||||
// servers far past 1.585 do that, so it reads as a current one.
|
||||
if (!/\d/.test(version)) {
|
||||
GLOBAL_VERSIONS = {
|
||||
remoteMajor: 1,
|
||||
remoteMinor: Number.MAX_SAFE_INTEGER,
|
||||
};
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const [prefix, remoteMinorStr] = version.split(".");
|
||||
|
||||
|
||||
@@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork";
|
||||
// (e.g. utils.ts) can read it without importing main.ts and creating a circular
|
||||
// dependency (main → workspace → utils → main) that triggers a TDZ.
|
||||
// Re-exported from main.ts for backwards compatibility.
|
||||
export const VERSION = "1.894.1";
|
||||
export const VERSION = "1.895.1";
|
||||
|
||||
+10
-2
@@ -747,8 +747,16 @@ export async function resolveWorkspace(
|
||||
return process.exit(-1);
|
||||
}
|
||||
|
||||
export async function fetchVersion(baseUrl: string): Promise<string> {
|
||||
// Without a token the server answers with the edition alone, so pass the workspace's token
|
||||
// wherever a caller needs the version number.
|
||||
export async function fetchVersion(
|
||||
baseUrl: string,
|
||||
token?: string
|
||||
): Promise<string> {
|
||||
const requestHeaders = new Headers();
|
||||
if (token) {
|
||||
requestHeaders.set("Authorization", "Bearer " + token);
|
||||
}
|
||||
|
||||
const extraHeaders = getHeaders();
|
||||
if (extraHeaders) {
|
||||
@@ -785,7 +793,7 @@ export async function tryResolveVersion(
|
||||
const workspaceRes = await tryResolveWorkspace(opts);
|
||||
if (workspaceRes.isError) return undefined;
|
||||
const workspace = (workspaceRes as { isError: false; value: Workspace }).value;
|
||||
const version = await fetchVersion(workspace.remote);
|
||||
const version = await fetchVersion(workspace.remote, workspace.token);
|
||||
|
||||
try {
|
||||
return Number.parseInt(
|
||||
|
||||
+1
-1
@@ -254,7 +254,7 @@ const command = new Command()
|
||||
const workspace = await getActiveWorkspace(opts as GlobalOptions);
|
||||
if (workspace) {
|
||||
try {
|
||||
const backendVersion = await fetchVersion(workspace.remote);
|
||||
const backendVersion = await fetchVersion(workspace.remote, workspace.token);
|
||||
console.log("Backend Version: " + backendVersion);
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
|
||||
@@ -373,7 +373,7 @@ export function writeIfChanged(path: string, content: string): boolean {
|
||||
export async function fetchRemoteVersion(
|
||||
workspace: Workspace
|
||||
): Promise<string> {
|
||||
const version = await fetchVersion(workspace.remote);
|
||||
const version = await fetchVersion(workspace.remote, workspace.token);
|
||||
if (version) {
|
||||
updateGlobalVersions(version);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import {
|
||||
isVersionsGeq1585,
|
||||
updateGlobalVersions,
|
||||
} from "../src/commands/sync/global.ts";
|
||||
|
||||
// A server gives the bare edition to a token that cannot authenticate on /api/version; read as
|
||||
// an old server, `sync push` would rewrite every app's runnables to their legacy type names.
|
||||
test("an edition-only version reads as a current server", () => {
|
||||
updateGlobalVersions("EE v1.500.0");
|
||||
expect(isVersionsGeq1585()).toBe(false);
|
||||
updateGlobalVersions("EE");
|
||||
expect(isVersionsGeq1585()).toBe(true);
|
||||
updateGlobalVersions("CE v1.895.1");
|
||||
expect(isVersionsGeq1585()).toBe(true);
|
||||
});
|
||||
@@ -161,6 +161,8 @@ Symbols, not line numbers, are cited: they drift less.
|
||||
`ensure_grant_within_caller` accepts: scopes within the caller's, no superadmin unless the caller
|
||||
is unscoped and carries it, no admin the caller withholds, networks within the caller's. A later
|
||||
expiration goes through `cap_token_expiration`, and changing it re-registers the expiry warning.
|
||||
Scopes edited on an MCP OAuth sign-in are carried to its refresh grant, unless they leave the
|
||||
token unrestricted.
|
||||
Only user tokens (`is_user_token`) take limit edits, and only they or an MCP OAuth sign-in widen
|
||||
scopes: a system token is minted narrow for wherever it is handed. Every job token is refused,
|
||||
since `$WM_TOKEN` is unscoped and narrowing breaks whatever holds the token.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
anonymous usage-stats payload. It answers "does anyone use this, and which variant do they pick"
|
||||
without any identifying data leaving the instance.
|
||||
|
||||
It currently carries 113 registered actions across forty-four features (`access_view`, `ai_session`, `ai_chat`,
|
||||
It currently carries 117 registered actions across forty-four features (`access_view`, `ai_session`, `ai_chat`,
|
||||
`autoscaling_diagnostics`, `code_mode`,
|
||||
`ai_fix`, `ai_agent`, `ai_decision`, `ai_agent_eval`, `app_sandbox`, `datatable`, `db_manager`, `flow_editor`,
|
||||
`flow_run`, `flow_step`, `home`, `header_nav`, `run_form`, `sharing`, `debugger`, `trigger`,
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@windmill-labs/components",
|
||||
"version": "1.894.1",
|
||||
"version": "1.895.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@windmill-labs/components",
|
||||
"version": "1.894.1",
|
||||
"version": "1.895.1",
|
||||
"hasInstallScript": true,
|
||||
"license": "AGPL-3.0",
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@windmill-labs/components",
|
||||
"version": "1.894.1",
|
||||
"version": "1.895.1",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev",
|
||||
|
||||
@@ -146,6 +146,26 @@
|
||||
}
|
||||
})()
|
||||
</script>
|
||||
<script>
|
||||
// In an opaque-origin frame every request is cross-origin, and Vite preloads a
|
||||
// dynamic import's CSS with `crossorigin`: a stylesheet served (or cached) without
|
||||
// CORS headers fails and rejects the whole import, leaving the app viewer blank. A
|
||||
// stylesheet applies without CORS, so load it again without `crossorigin` and let
|
||||
// the import go on.
|
||||
if (self.origin === 'null') {
|
||||
addEventListener('vite:preloadError', function (e) {
|
||||
var m = /^Unable to preload CSS for (.+)$/.exec((e.payload && e.payload.message) || '')
|
||||
if (!m) return
|
||||
e.preventDefault()
|
||||
var links = document.querySelectorAll('link[rel="stylesheet"][crossorigin]')
|
||||
for (var i = 0; i < links.length; i++) if (links[i].href === m[1]) links[i].remove()
|
||||
var link = document.createElement('link')
|
||||
link.rel = 'stylesheet'
|
||||
link.href = m[1]
|
||||
document.head.appendChild(link)
|
||||
})
|
||||
}
|
||||
</script>
|
||||
<script>
|
||||
// Public app pages (`/public/<ws>/<secret>`, `/a/<custom path>`): skip the loading
|
||||
// screen, and start the API calls the page makes first so they overlap the module
|
||||
|
||||
@@ -8,11 +8,16 @@
|
||||
import Row from './table/Row.svelte'
|
||||
import RowIcon from './common/table/RowIcon.svelte'
|
||||
import { Tooltip } from './meltComponents'
|
||||
import Popover from './meltComponents/Popover.svelte'
|
||||
import DropdownV2 from './DropdownV2.svelte'
|
||||
import { GranularAclService, type PrincipalAccess } from '$lib/gen'
|
||||
import { useOperatingWorkspace } from './operatingWorkspace.svelte'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
import { pluralize } from '$lib/utils'
|
||||
import { pluralize, type Item } from '$lib/utils'
|
||||
import { itemHref } from './offboarding-utils'
|
||||
import GrantNavigator, { navigatorMaxHeight } from './access/GrantNavigator.svelte'
|
||||
import { KIND_LABELS, setGrant, type GrantLevel } from './access/access'
|
||||
import {
|
||||
buildAccessTree,
|
||||
flattenAccessTree,
|
||||
@@ -27,6 +32,9 @@
|
||||
ExternalLink,
|
||||
Folder,
|
||||
FolderTree,
|
||||
Loader2,
|
||||
Lock,
|
||||
Plus,
|
||||
User,
|
||||
Users
|
||||
} from 'lucide-svelte'
|
||||
@@ -39,26 +47,6 @@
|
||||
// A short list opens fully, so every item shows at once. A longer one starts at its folders.
|
||||
const OPEN_UP_TO = 30
|
||||
|
||||
const KIND_LABELS: Record<string, string> = {
|
||||
script: 'Script',
|
||||
flow: 'Flow',
|
||||
app: 'App',
|
||||
resource: 'Resource',
|
||||
variable: 'Variable',
|
||||
schedule: 'Schedule',
|
||||
http_trigger: 'HTTP route',
|
||||
websocket_trigger: 'WebSocket trigger',
|
||||
kafka_trigger: 'Kafka trigger',
|
||||
nats_trigger: 'NATS trigger',
|
||||
postgres_trigger: 'Postgres trigger',
|
||||
mqtt_trigger: 'MQTT trigger',
|
||||
amqp_trigger: 'AMQP trigger',
|
||||
gcp_trigger: 'GCP Pub/Sub trigger',
|
||||
azure_trigger: 'Azure trigger',
|
||||
sqs_trigger: 'SQS trigger',
|
||||
email_trigger: 'Email trigger'
|
||||
}
|
||||
|
||||
let drawer: Drawer | undefined = $state()
|
||||
let principal = $state('')
|
||||
let access: PrincipalAccess | undefined = $state()
|
||||
@@ -69,6 +57,15 @@
|
||||
/** Rows opened or closed by hand, by path prefix. The rest follow `expandAll`. */
|
||||
let openState: Record<string, boolean> = $state({})
|
||||
let expandAll: boolean | undefined = $state()
|
||||
let grantOpen = $state(false)
|
||||
let navigator: GrantNavigator | undefined = $state()
|
||||
/** The row menu that is open, as `kind:path`. */
|
||||
let openMenu: string | undefined = $state()
|
||||
/** The row whose grant is being written, as `kind:path`. Its menu would otherwise send the
|
||||
* same change again before the tree reloads with the new level. */
|
||||
let changing: string | undefined = $state()
|
||||
let grantPopover: Popover | undefined = $state()
|
||||
let grantAnchor: HTMLElement | undefined = $state()
|
||||
// Responses are not ordered: a slow answer for the previous principal must not land on this one.
|
||||
let requestId = 0
|
||||
|
||||
@@ -81,13 +78,18 @@
|
||||
nbDisplayed = PAGE
|
||||
openState = {}
|
||||
expandAll = undefined
|
||||
grantOpen = false
|
||||
drawer?.openDrawer()
|
||||
logFeatureUsage('access_view', 'opened', { key: target })
|
||||
await reload()
|
||||
}
|
||||
|
||||
async function reload(): Promise<void> {
|
||||
const id = ++requestId
|
||||
try {
|
||||
const result = await GranularAclService.getPrincipalAccess({
|
||||
workspace: $operatingWorkspace!,
|
||||
principal: nextPrincipal
|
||||
principal
|
||||
})
|
||||
if (id === requestId) access = result
|
||||
} catch (e) {
|
||||
@@ -95,6 +97,76 @@
|
||||
}
|
||||
}
|
||||
|
||||
function setGrantOpen(next: boolean) {
|
||||
if (next) placeGrantPopover()
|
||||
grantOpen = next
|
||||
if (next) logFeatureUsage('access_view', 'grant_opened')
|
||||
}
|
||||
|
||||
// The side is picked once, for the navigator's tallest height: melt fits the popover to the room
|
||||
// on the side it first lands on, so a list that grows later would never flip on its own.
|
||||
function placeGrantPopover() {
|
||||
if (!grantAnchor) return
|
||||
const rect = grantAnchor.getBoundingClientRect()
|
||||
const gutter = 8
|
||||
const spaceBelow = window.innerHeight - rect.bottom - gutter
|
||||
const spaceAbove = rect.top - gutter
|
||||
const below = navigatorMaxHeight() <= spaceBelow || spaceBelow >= spaceAbove
|
||||
grantPopover?.updatePositioning({
|
||||
placement: below ? 'bottom-end' : 'top-end',
|
||||
strategy: 'absolute',
|
||||
gutter,
|
||||
overflowPadding: 16,
|
||||
flip: false,
|
||||
fitViewport: true,
|
||||
overlap: false
|
||||
})
|
||||
}
|
||||
|
||||
/** The principal's own entry on an item: `true` for write, `false` for read. */
|
||||
function ownItemGrant(item: AccessItem): boolean | undefined {
|
||||
const reason = item.reasons.find((r) =>
|
||||
isGroup ? r.type === 'group' && r.group === name : r.type === 'user'
|
||||
)
|
||||
return reason ? !!reason.write : undefined
|
||||
}
|
||||
|
||||
async function changeGrant(kind: string, path: string, level: GrantLevel) {
|
||||
if (changing) return
|
||||
changing = `${kind}:${path}`
|
||||
// The spinner replaces the menu before its close reaches `bind:open`, so a stale
|
||||
// `openMenu` would reopen it after the reload and swallow the next Escape.
|
||||
openMenu = undefined
|
||||
try {
|
||||
await setGrant($operatingWorkspace!, kind, path, principal, level)
|
||||
} catch (e) {
|
||||
const what = kind === 'folder' ? `f/${path}` : path
|
||||
sendUserToast(`Could not change access to ${what}: ${e?.body ?? e}`, true)
|
||||
}
|
||||
await reload()
|
||||
changing = undefined
|
||||
}
|
||||
|
||||
/** `current` is the grant's level: `true` for write, `false` for read. */
|
||||
function grantActions(kind: string, path: string, current: boolean): Item[] {
|
||||
return [
|
||||
{
|
||||
displayName: 'Read',
|
||||
disabled: current === false,
|
||||
action: () => changeGrant(kind, path, 'read')
|
||||
},
|
||||
{
|
||||
displayName: 'Write',
|
||||
disabled: current === true,
|
||||
action: () => changeGrant(kind, path, 'write')
|
||||
},
|
||||
{ displayName: 'Remove', type: 'delete', action: () => changeGrant(kind, path, 'none') }
|
||||
]
|
||||
}
|
||||
|
||||
// The tree's folder rows carry no grant of their own, so the menu reads it from here.
|
||||
const foldersByName = $derived(new Map((access?.folders ?? []).map((f) => [f.name, f])))
|
||||
|
||||
const name = $derived(principal.slice(2))
|
||||
const isGroup = $derived(principal.startsWith('g/'))
|
||||
const who = $derived(isGroup ? `members of ${principal}` : principal)
|
||||
@@ -163,13 +235,29 @@
|
||||
return `${principal} is a member of ${node.key}, so ${principal} can write every item under ${node.key}/, including items added later.`
|
||||
}
|
||||
|
||||
/** Grants on the item itself. What its folder or space gives is said once, on that row. */
|
||||
/** Grants on the item itself, which decide whether its level reads as its own. */
|
||||
function itemGrants(item: AccessItem): string[] {
|
||||
return item.reasons.flatMap((r) =>
|
||||
r.type === 'user' ? ['Shared directly'] : r.type === 'group' ? [viaLabel(`g/${r.group}`)] : []
|
||||
)
|
||||
}
|
||||
|
||||
/** Every reason the item is held: its own grants, then its folder or space. */
|
||||
function itemReasons(item: AccessItem): string[] {
|
||||
const labels = item.reasons.map((r) =>
|
||||
r.type === 'user'
|
||||
? 'Shared directly'
|
||||
: r.type === 'group'
|
||||
? viaLabel(`g/${r.group}`)
|
||||
: r.type === 'folder'
|
||||
? `Through f/${r.folder}`
|
||||
: r.type === 'group_path'
|
||||
? `Through g/${r.group}`
|
||||
: 'Own path'
|
||||
)
|
||||
return [...new Set(labels)]
|
||||
}
|
||||
|
||||
function levelClass(item: AccessItem, grants: string[], owner: AccessOwnerNode): string {
|
||||
if (!grants.length) return 'text-hint'
|
||||
return item.write && owner.whole && !owner.write ? 'font-semibold text-emphasis' : ''
|
||||
@@ -205,6 +293,49 @@
|
||||
</button>
|
||||
{/snippet}
|
||||
|
||||
{#snippet grantMenu(kind: string, path: string, current: boolean, blocked: string | undefined)}
|
||||
{#if blocked}
|
||||
<Tooltip>
|
||||
<Lock size={14} class="text-secondary" aria-label={blocked} />
|
||||
{#snippet text()}{blocked}{/snippet}
|
||||
</Tooltip>
|
||||
{:else if changing === `${kind}:${path}`}
|
||||
<span class="flex size-5 items-center justify-center -my-0.5" role="status" aria-label="Saving">
|
||||
<Loader2 size={14} class="animate-spin text-secondary" />
|
||||
</span>
|
||||
{:else}
|
||||
{@const key = `${kind}:${path}`}
|
||||
<DropdownV2
|
||||
disabled={!!changing}
|
||||
size="xs"
|
||||
fixedHeight={false}
|
||||
class="-my-0.5"
|
||||
items={grantActions(kind, path, current)}
|
||||
bind:open={
|
||||
() => openMenu === key,
|
||||
(next) => {
|
||||
if (next) openMenu = key
|
||||
else if (openMenu === key) openMenu = undefined
|
||||
}
|
||||
}
|
||||
/>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
<!-- The drawer answers Escape on window too, and `preventEscape` is read after a popover or menu
|
||||
has already closed, so with the Grant popover or a row menu open its Escape is taken here
|
||||
before either sees it. The navigator's own dialog or row dropdown closes first. -->
|
||||
<svelte:window
|
||||
onkeydowncapture={(e) => {
|
||||
if (e.key !== 'Escape' || (!grantOpen && !openMenu)) return
|
||||
e.stopPropagation()
|
||||
e.preventDefault()
|
||||
if (grantOpen && navigator?.escape(e.target)) return
|
||||
grantOpen = false
|
||||
openMenu = undefined
|
||||
}}
|
||||
/>
|
||||
|
||||
<Drawer bind:this={drawer} size="1000px">
|
||||
<DrawerContent title={`Access of ${principal}`} on:close={() => drawer?.closeDrawer()}>
|
||||
<div class="flex flex-col gap-6">
|
||||
@@ -213,8 +344,8 @@
|
||||
What members of g/{name} can read through this group alone, and which grant gives each item.
|
||||
Members may reach more through their own grants and other groups.
|
||||
{:else}
|
||||
What {principal} can read, and which grant gives each item. Jobs that run as
|
||||
{principal} read exactly this set.
|
||||
What {principal} can read, and which grant gives each item.
|
||||
{#if access && !access.is_admin}Jobs that run as {principal} read exactly this set.{/if}
|
||||
{/if}
|
||||
</p>
|
||||
|
||||
@@ -242,6 +373,36 @@
|
||||
{/if}
|
||||
|
||||
<Section label={`Items (${access.items.length})`} small>
|
||||
{#snippet action()}
|
||||
<div bind:this={grantAnchor}>
|
||||
<Popover
|
||||
bind:this={grantPopover}
|
||||
placement="bottom-end"
|
||||
usePointerDownOutside
|
||||
disableFocusTrap
|
||||
closeOnOtherPopoverOpen
|
||||
bind:isOpen={() => grantOpen, setGrantOpen}
|
||||
openFocus="[data-workspace-picker-search]"
|
||||
contentClasses="flex flex-col overflow-hidden"
|
||||
>
|
||||
{#snippet trigger()}
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
nonCaptureEvent
|
||||
startIcon={{ icon: Plus }}
|
||||
>
|
||||
Grant
|
||||
</Button>
|
||||
{/snippet}
|
||||
{#snippet content()}
|
||||
{#if access}
|
||||
<GrantNavigator bind:this={navigator} {principal} {access} onChange={reload} />
|
||||
{/if}
|
||||
{/snippet}
|
||||
</Popover>
|
||||
</div>
|
||||
{/snippet}
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="flex gap-2 items-center">
|
||||
<TextInput
|
||||
@@ -280,7 +441,8 @@
|
||||
<tr>
|
||||
<Cell head first>Name</Cell>
|
||||
<Cell head>Access</Cell>
|
||||
<Cell head last>Granted by</Cell>
|
||||
<Cell head>Granted by</Cell>
|
||||
<Cell head last actions />
|
||||
</tr>
|
||||
</Head>
|
||||
<tbody>
|
||||
@@ -335,7 +497,15 @@
|
||||
{#snippet text()}{ownerExplanation(node)}{/snippet}
|
||||
</Tooltip>
|
||||
</Cell>
|
||||
<Cell last>{ownerGrant(node)}</Cell>
|
||||
<Cell>{ownerGrant(node)}</Cell>
|
||||
<Cell last actions shouldStopPropagation>
|
||||
{@const folder = node.key.startsWith('f/')
|
||||
? foldersByName.get(node.key.slice(2))
|
||||
: undefined}
|
||||
{#if folder && !folder.owner && folder.grant != undefined}
|
||||
{@render grantMenu('folder', folder.name, folder.grant, folder.blocked)}
|
||||
{/if}
|
||||
</Cell>
|
||||
</Row>
|
||||
{:else if row.type === 'subfolder'}
|
||||
<Row hoverable on:click={() => toggle(row.node.key, row.open)}>
|
||||
@@ -351,7 +521,8 @@
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell></Cell>
|
||||
<Cell last></Cell>
|
||||
<Cell></Cell>
|
||||
<Cell last actions></Cell>
|
||||
</Row>
|
||||
{:else}
|
||||
{@const item = row.item}
|
||||
@@ -388,7 +559,13 @@
|
||||
>{item.write ? 'Write' : 'Read'}</span
|
||||
>
|
||||
</Cell>
|
||||
<Cell last>{grants.join(', ')}</Cell>
|
||||
<Cell>{itemReasons(item).join(', ')}</Cell>
|
||||
<Cell last actions>
|
||||
{@const own = ownItemGrant(item)}
|
||||
{#if own !== undefined}
|
||||
{@render grantMenu(item.kind, item.path, own, item.blocked)}
|
||||
{/if}
|
||||
</Cell>
|
||||
</tr>
|
||||
{/if}
|
||||
{/each}
|
||||
|
||||
@@ -13,7 +13,8 @@ level *up*. Filter (internal or `externalFilter`) is global across all
|
||||
leaves and ignores the current scope.
|
||||
-->
|
||||
<script lang="ts" generics="L">
|
||||
import { ChevronLeft, ChevronRight, Loader2 } from 'lucide-svelte'
|
||||
import { CheckCircle2, ChevronLeft, ChevronRight, Loader2 } from 'lucide-svelte'
|
||||
import { fade, fly } from 'svelte/transition'
|
||||
import TextInput from '$lib/components/text_input/TextInput.svelte'
|
||||
import SearchItems from '$lib/components/SearchItems.svelte'
|
||||
import Portal from '$lib/components/Portal.svelte'
|
||||
@@ -30,6 +31,7 @@ leaves and ignores the current scope.
|
||||
type DrillBranch,
|
||||
type DrillIcon,
|
||||
type DrillLeaf,
|
||||
type DrillLeafAction,
|
||||
type DrillNode
|
||||
} from './drillPicker'
|
||||
import Badge from '$lib/components/common/badge/Badge.svelte'
|
||||
@@ -39,7 +41,10 @@ leaves and ignores the current scope.
|
||||
|
||||
interface Props {
|
||||
tree: DrillNode<L>[]
|
||||
onPick: (leaf: DrillLeaf<L>) => void
|
||||
/** Picking a leaf: a click, or Enter on its highlighted row. Without it, a click on a leaf
|
||||
* does nothing and Enter runs the highlighted row's selected `leafActions` button, for a
|
||||
* picker whose rows act only through their buttons. */
|
||||
onPick?: (leaf: DrillLeaf<L>) => void
|
||||
/** Drill path to land on initially. Empty = root. */
|
||||
initialScope?: string[]
|
||||
/** Composite key of the row to highlight initially. */
|
||||
@@ -87,13 +92,22 @@ leaves and ignores the current scope.
|
||||
leaf: DrillLeaf<L>
|
||||
) => { icon: DrillIcon; label: string; title: string; run: () => void } | undefined
|
||||
/** Status badge on the right of a leaf row. Returns `undefined` for a leaf with
|
||||
* nothing to report. The hover action, when there is one, covers it. */
|
||||
* nothing to report. The hover action, when there is one, covers it. With `leafActions` it
|
||||
* is plain text and `color` is unused. */
|
||||
leafBadge?: (leaf: DrillLeaf<L>) => { label: string; color: BadgeColor } | undefined
|
||||
/** Where picking a leaf navigates, for a host whose pick is a navigation. The row then
|
||||
* renders as a link: a plain click still goes through `onPick`, while a middle or
|
||||
* ⌘/Ctrl-click opens it in a new tab — taking ⌘/Ctrl-click from `leafAction`, which
|
||||
* keeps ⌘/Ctrl-Enter. */
|
||||
leafHref?: (leaf: DrillLeaf<L>) => string | undefined
|
||||
/** What a leaf row offers, laid over its end while the row is highlighted (hovered or reached
|
||||
* with the arrow keys), so the row does not reflow: the `preferred` one (else the first) as a
|
||||
* button, which Enter runs when there is no `onPick`, and the others in its dropdown. In
|
||||
* place of `leafAction`, not with it. */
|
||||
leafActions?: (leaf: DrillLeaf<L>) => DrillLeafAction[] | undefined
|
||||
/** What a `leafActions` button just did on a leaf ("Read granted"), shown over the row's
|
||||
* end, highlighted or not, while it returns a text. */
|
||||
leafDone?: (leaf: DrillLeaf<L>) => string | undefined
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -113,7 +127,9 @@ leaves and ignores the current scope.
|
||||
rowTooltip,
|
||||
leafAction,
|
||||
leafBadge,
|
||||
leafHref
|
||||
leafHref,
|
||||
leafActions,
|
||||
leafDone
|
||||
}: Props = $props()
|
||||
|
||||
let searchInput: TextInput | undefined = $state()
|
||||
@@ -302,7 +318,9 @@ leaves and ignores the current scope.
|
||||
// Ignored until the user actually moves the mouse. Prevents the
|
||||
// cursor (parked over a row) from clobbering keyboard-driven
|
||||
// selection when the layout shifts beneath it.
|
||||
if (mouseActive) highlightedKey = key
|
||||
// A row's open menu sits over the rows below it, and the pointer crosses them to reach it:
|
||||
// moving the highlight would take the menu's button away.
|
||||
if (mouseActive && !actionMenuOpen) highlightedKey = key
|
||||
}
|
||||
|
||||
/** `alt` picks the row's second action (see `leafAction`) rather than the row
|
||||
@@ -310,6 +328,10 @@ leaves and ignores the current scope.
|
||||
* that only appears on hover. A leaf with no second action ignores it. */
|
||||
function pick(leaf: DrillLeaf<L>, alt = false) {
|
||||
if (leaf.disabled) return
|
||||
if (!onPick) {
|
||||
if (leaf.key === highlightedKey) runMainAction()
|
||||
return
|
||||
}
|
||||
// The second action is the row's other destination (its editor, for the deployed page
|
||||
// this tab shows), so it stays available on the current row the plain pick skips.
|
||||
if (alt) {
|
||||
@@ -323,6 +345,25 @@ leaves and ignores the current scope.
|
||||
onPick(leaf)
|
||||
}
|
||||
|
||||
function runMainAction() {
|
||||
const action = mainAction
|
||||
if (action && !action.disabled && !action.loading) runAction(action)
|
||||
}
|
||||
|
||||
/** The button area's width when each row's action ran, the least its success pill takes. Read
|
||||
* from `actionsWidth` live, the pill would resize on hover, which moves the highlighted row. */
|
||||
let pillWidths: Record<string, number> = $state({})
|
||||
function runAction(action: DrillLeafAction) {
|
||||
if (highlightedKey) pillWidths[highlightedKey] = actionsWidth
|
||||
action.run()
|
||||
}
|
||||
|
||||
/** Fades out what lies under the highlighted row's buttons, which sit over its end. */
|
||||
function fadeUnder(width: number): string {
|
||||
const mask = `linear-gradient(to left, transparent ${width}px, #000 ${width + 16}px)`
|
||||
return `mask-image: ${mask}; -webkit-mask-image: ${mask}`
|
||||
}
|
||||
|
||||
// Single shared hover tooltip (opt-in via `rowTooltip`): one floating node
|
||||
// re-anchored to the hovered row, instead of a popover per row — rows can
|
||||
// number in the hundreds. Portaled to body because the picker often lives
|
||||
@@ -385,6 +426,17 @@ leaves and ignores the current scope.
|
||||
}
|
||||
|
||||
function handleSearchKeydown(e: KeyboardEvent) {
|
||||
// A row's button has focus only after a click: it keeps its own keys, and Enter must not
|
||||
// also reach the row. ↑/↓ and Escape return to the search field.
|
||||
if ((e.target as HTMLElement | null)?.closest?.('[data-drill-action]')) {
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
focus()
|
||||
if (e.key !== 'Escape') moveHighlight(e.key === 'ArrowDown' ? 1 : -1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
@@ -400,6 +452,8 @@ leaves and ignores the current scope.
|
||||
// highlighted row so an unrelated Tab in an empty picker still
|
||||
// falls through to natural focus movement.
|
||||
if (e.key === 'Tab' && !highlightedKey) return
|
||||
// Without `onPick`, Enter on a leaf runs its selected button, which Tab must not do.
|
||||
if (e.key === 'Tab' && !onPick && leafForKey(highlightedKey!)) return
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
mouseActive = false
|
||||
@@ -484,6 +538,35 @@ leaves and ignores the current scope.
|
||||
})
|
||||
|
||||
const branchLoading = $derived(currentBranch ? (currentBranch.loading ?? false) : rootLoading)
|
||||
|
||||
const highlightedNode = $derived.by<DrillNode<L> | undefined>(() => {
|
||||
if (!highlightedKey) return undefined
|
||||
if (isSearching) return (searchedItems ?? []).find((r) => r.leaf.key === highlightedKey)?.leaf
|
||||
return entryList.find((e) => e.key === highlightedKey)?.node
|
||||
})
|
||||
|
||||
const highlightedActions = $derived(
|
||||
highlightedNode?.type === 'leaf' && !highlightedNode.disabled
|
||||
? (leafActions?.(highlightedNode) ?? [])
|
||||
: []
|
||||
)
|
||||
const mainAction = $derived(highlightedActions.find((a) => a.preferred) ?? highlightedActions[0])
|
||||
const otherActions = $derived(highlightedActions.filter((a) => a !== mainAction))
|
||||
let actionMenuOpen = $state(false)
|
||||
|
||||
/** Answers an Escape a host takes before the picker can: closes a row's dropdown, which hands
|
||||
* focus back to its chevron, or leaves a row's button for the search field. False when neither
|
||||
* applies, so the host closes instead. */
|
||||
export function escape(target: EventTarget | null): boolean {
|
||||
if (actionMenuOpen) {
|
||||
actionMenuOpen = false
|
||||
return true
|
||||
}
|
||||
if (!(target as HTMLElement | null)?.closest?.('[data-drill-action]')) return false
|
||||
focus()
|
||||
return true
|
||||
}
|
||||
let actionsWidth = $state(0)
|
||||
</script>
|
||||
|
||||
<SearchItems
|
||||
@@ -525,110 +608,183 @@ leaves and ignores the current scope.
|
||||
{@const action = leaf.disabled ? undefined : leafAction?.(leaf)}
|
||||
{@const badge = leafBadge?.(leaf)}
|
||||
{@const href = leaf.disabled ? undefined : leafHref?.(leaf)}
|
||||
{@const inert = !onPick}
|
||||
{@const actions = isHl ? highlightedActions : []}
|
||||
{@const done = leafDone?.(leaf)}
|
||||
<!-- The row's action sits BESIDE the option rather than inside it: a button nested in
|
||||
a button is invalid markup. The wrapper carries the row's padding, highlight and
|
||||
hover group so the two still read as one row. -->
|
||||
<!-- Hover is tracked on the wrapper, not on the option button: the row's action is a
|
||||
sibling of that button, so entering it would otherwise read as leaving the row and
|
||||
drop the highlight out from under the pointer. -->
|
||||
<!-- A disabled option dims through `disabled:opacity-50` and shows its cursor on this wrapper:
|
||||
the base `button:disabled` rule in tailwind.config.cjs outranks a plain `opacity-50` and
|
||||
turns pointer events off on the button itself. -->
|
||||
<!-- `leafActions` show only on the highlighted row, so a pointer that comes back after the
|
||||
arrow keys moved the highlight takes it on its first move, not on the next row it enters. -->
|
||||
<div
|
||||
class="group flex items-center transition-colors pr-3 {baseClass} {isHl
|
||||
class="group relative flex items-center transition-colors pr-3 {baseClass} {isHl
|
||||
? 'bg-surface-hover'
|
||||
: ''}"
|
||||
: ''} {leaf.disabled ? 'cursor-not-allowed' : ''}"
|
||||
onmouseenter={(e) => {
|
||||
setHoverHighlight(key)
|
||||
tooltipEnter(e.currentTarget as HTMLElement, leaf)
|
||||
}}
|
||||
onmousemove={leafActions && !isHl ? () => setHoverHighlight(key) : undefined}
|
||||
onmouseleave={tooltipLeave}
|
||||
>
|
||||
<svelte:element
|
||||
this={href ? 'a' : 'button'}
|
||||
type={href ? undefined : 'button'}
|
||||
{href}
|
||||
id={idFor(key)}
|
||||
role="option"
|
||||
aria-selected={isHl}
|
||||
data-nav-key={key}
|
||||
aria-current={isCur ? 'true' : undefined}
|
||||
aria-label={tip ? `${leaf.label} — ${tip}` : undefined}
|
||||
class="min-w-0 flex-1 text-left flex items-center gap-2 pl-3 {isCur
|
||||
? 'cursor-default text-emphasis font-medium'
|
||||
: 'text-[color:inherit]'} {leaf.disabled ? 'opacity-50 cursor-not-allowed' : ''}"
|
||||
disabled={href ? undefined : leaf.disabled}
|
||||
tabindex={0}
|
||||
onmousedown={(e: MouseEvent) => e.preventDefault()}
|
||||
onclickcapture={(e: MouseEvent) => {
|
||||
// Capture, not a delegated onclick: the picker is portalled outside the app root,
|
||||
// where a delegated handler runs after SvelteKit's link handler has already
|
||||
// followed the href, too late for preventDefault to keep a plain click on `pick`.
|
||||
if (href && isNewTabClick(e)) return
|
||||
e.preventDefault()
|
||||
pick(leaf, e.metaKey || e.ctrlKey)
|
||||
}}
|
||||
<!-- With `leafActions`, what fades out under the row's buttons; `contents` otherwise. -->
|
||||
<div
|
||||
class={leafActions ? 'min-w-0 flex-1 flex items-center' : 'contents'}
|
||||
style={actions.length ? fadeUnder(actionsWidth) : undefined}
|
||||
>
|
||||
{@render defaultLeafIcon(leaf)}
|
||||
<!-- Centred in a two-line row's height so a one-line leaf sits where a two-line
|
||||
one's pair does, rather than riding high against the top. A list with no
|
||||
second line anywhere (a picker's pages) keeps its rows one line tall. -->
|
||||
<div
|
||||
class="min-w-0 flex-1 flex flex-col justify-center {twoLineHeight ? 'min-h-[2.25rem]' : ''}"
|
||||
<svelte:element
|
||||
this={href ? 'a' : inert ? 'div' : 'button'}
|
||||
type={href || inert ? undefined : 'button'}
|
||||
{href}
|
||||
id={idFor(key)}
|
||||
role="option"
|
||||
aria-selected={isHl}
|
||||
aria-disabled={inert && leaf.disabled ? 'true' : undefined}
|
||||
data-nav-key={key}
|
||||
aria-current={isCur ? 'true' : undefined}
|
||||
aria-label={tip ? `${leaf.label} — ${tip}` : undefined}
|
||||
class="min-w-0 flex-1 text-left flex items-center gap-2 pl-3 {isCur
|
||||
? 'cursor-default text-emphasis font-medium'
|
||||
: 'text-[color:inherit]'} {inert
|
||||
? leaf.disabled
|
||||
? 'opacity-50'
|
||||
: 'cursor-default'
|
||||
: 'disabled:opacity-50'}"
|
||||
disabled={href || inert ? undefined : leaf.disabled}
|
||||
tabindex={inert ? -1 : 0}
|
||||
onmousedown={(e: MouseEvent) => e.preventDefault()}
|
||||
onclickcapture={inert
|
||||
? undefined
|
||||
: (e: MouseEvent) => {
|
||||
// Capture, not a delegated onclick: the picker is portalled outside the app root,
|
||||
// where a delegated handler runs after SvelteKit's link handler has already
|
||||
// followed the href, too late for preventDefault to keep a plain click on `pick`.
|
||||
if (href && isNewTabClick(e)) return
|
||||
e.preventDefault()
|
||||
pick(leaf, e.metaKey || e.ctrlKey)
|
||||
}}
|
||||
>
|
||||
{#if leaf.secondary}
|
||||
<div class="text-xs text-primary font-normal truncate">{leaf.label}</div>
|
||||
<div class="text-2xs text-hint font-normal font-mono truncate">
|
||||
{secondary ?? leaf.secondary}
|
||||
</div>
|
||||
{:else}
|
||||
<div
|
||||
class="text-xs text-primary font-normal truncate {secondary === undefined &&
|
||||
leaf.plainLabel
|
||||
? ''
|
||||
: 'font-mono'}"
|
||||
>
|
||||
{secondary ?? leaf.label}
|
||||
</div>
|
||||
{@render defaultLeafIcon(leaf)}
|
||||
<!-- Centred in a two-line row's height so a one-line leaf sits where a two-line
|
||||
one's pair does, rather than riding high against the top. A list with no
|
||||
second line anywhere (a picker's pages) keeps its rows one line tall. -->
|
||||
<div
|
||||
class="min-w-0 flex-1 flex flex-col justify-center {twoLineHeight
|
||||
? 'min-h-[2.25rem]'
|
||||
: ''}"
|
||||
>
|
||||
{#if leaf.secondary}
|
||||
<div class="text-xs text-primary font-normal truncate">{leaf.label}</div>
|
||||
<div class="text-2xs text-hint font-normal font-mono truncate">
|
||||
{secondary ?? leaf.secondary}
|
||||
</div>
|
||||
{:else}
|
||||
<div
|
||||
class="text-xs text-primary font-normal truncate {secondary === undefined &&
|
||||
leaf.plainLabel
|
||||
? ''
|
||||
: 'font-mono'}"
|
||||
>
|
||||
{secondary ?? leaf.label}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</svelte:element>
|
||||
{#if leafActions}
|
||||
<!-- Plain text beside the row's buttons, which sit over it while the row is
|
||||
highlighted: a filled badge reads as one more button. -->
|
||||
{#if badge}
|
||||
<span class="shrink-0 pl-2 text-xs text-secondary">{badge.label}</span>
|
||||
{/if}
|
||||
<!-- Keyed on the props rather than on this leaf's own badge or action, so a picker
|
||||
that has either holds the column open on every row: paths then truncate at one
|
||||
column and the button lands in the same place down the list. -->
|
||||
{:else if leafBadge || leafAction}
|
||||
<!-- Both sit in one grid cell so they cross-fade in place rather than sitting
|
||||
side by side or shifting the row as one replaces the other. -->
|
||||
<div class="shrink-0 w-[4.5rem] grid justify-items-end items-center pl-2">
|
||||
{#if action}
|
||||
<!-- `invisible`, not `hidden`: display cannot be transitioned, while
|
||||
visibility both fades with opacity and keeps the button out of the tab
|
||||
order while it is out of sight — the picker's focus belongs to its
|
||||
search field, and rows are reached with the arrow keys.
|
||||
The classes sit on this wrapper, not on the Button: `wrapperClasses` is
|
||||
twMerged with the button's own `flex`, which drops a conflicting
|
||||
display and leaves it showing beside the badge. -->
|
||||
<div
|
||||
class="col-start-1 row-start-1 invisible opacity-0 transition-[opacity,visibility] duration-150 group-hover:visible group-hover:opacity-100"
|
||||
>
|
||||
<Button
|
||||
unifiedSize="xs"
|
||||
variant="default"
|
||||
title={action.title}
|
||||
startIcon={{ icon: action.icon }}
|
||||
onClick={action.run}
|
||||
wrapperClasses="shrink-0"
|
||||
>
|
||||
{action.label}
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
{#if badge}
|
||||
<div
|
||||
class="col-start-1 row-start-1 transition-[opacity,visibility] duration-150 {action
|
||||
? 'group-hover:invisible group-hover:opacity-0'
|
||||
: ''}"
|
||||
>
|
||||
<Badge small color={badge.color}>{badge.label}</Badge>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{#if actions.length}
|
||||
<!-- Over the row's end, so a row keeps its layout whether or not it shows them. -->
|
||||
<div
|
||||
class="absolute inset-y-0 right-3 flex items-center gap-1"
|
||||
bind:clientWidth={actionsWidth}
|
||||
>
|
||||
{#if mainAction && !done}
|
||||
<!-- Local, so it waits for the pill to leave but not for a hover. -->
|
||||
<span data-drill-action in:fade={{ delay: 150, duration: 100 }}>
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="default"
|
||||
startIcon={mainAction.icon ? { icon: mainAction.icon } : undefined}
|
||||
loading={mainAction.loading}
|
||||
disabled={mainAction.disabled}
|
||||
onClick={() => mainAction && runAction(mainAction)}
|
||||
dropdownItems={otherActions.map((a) => ({
|
||||
label: a.label,
|
||||
description: a.hint,
|
||||
icon: a.icon,
|
||||
disabled: a.disabled || a.loading,
|
||||
onClick: () => runAction(a)
|
||||
}))}
|
||||
bind:dropdownOpen={actionMenuOpen}
|
||||
>
|
||||
{mainAction.label}
|
||||
</Button>
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
</svelte:element>
|
||||
<!-- Keyed on the props rather than on this leaf's own badge or action, so a picker
|
||||
that has either holds the column open on every row: paths then truncate at one
|
||||
column and the button lands in the same place down the list. -->
|
||||
{#if leafBadge || leafAction}
|
||||
<!-- Both sit in one grid cell so they cross-fade in place rather than sitting
|
||||
side by side or shifting the row as one replaces the other. -->
|
||||
<div class="shrink-0 w-[4.5rem] grid justify-items-end items-center pl-2">
|
||||
{#if action}
|
||||
<!-- `invisible`, not `hidden`: display cannot be transitioned, while
|
||||
visibility both fades with opacity and keeps the button out of the tab
|
||||
order while it is out of sight — the picker's focus belongs to its
|
||||
search field, and rows are reached with the arrow keys.
|
||||
The classes sit on this wrapper, not on the Button: `wrapperClasses` is
|
||||
twMerged with the button's own `flex`, which drops a conflicting
|
||||
display and leaves it showing beside the badge. -->
|
||||
<div
|
||||
class="col-start-1 row-start-1 invisible opacity-0 transition-[opacity,visibility] duration-150 group-hover:visible group-hover:opacity-100"
|
||||
>
|
||||
<Button
|
||||
unifiedSize="xs"
|
||||
variant="default"
|
||||
title={action.title}
|
||||
startIcon={{ icon: action.icon }}
|
||||
onClick={action.run}
|
||||
wrapperClasses="shrink-0"
|
||||
>
|
||||
{action.label}
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
{#if badge}
|
||||
<div
|
||||
class="col-start-1 row-start-1 transition-[opacity,visibility] duration-150 {action
|
||||
? 'group-hover:invisible group-hover:opacity-0'
|
||||
: ''}"
|
||||
>
|
||||
<Badge small color={badge.color}>{badge.label}</Badge>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
{#if done}
|
||||
<!-- SaveButton's success pill, over the row's button and its dropdown chevron. -->
|
||||
<div
|
||||
class="absolute inset-y-0 my-auto h-7 right-3 z-10 flex items-center justify-center gap-1.5 px-2 rounded-md text-xs font-medium whitespace-nowrap bg-green-200 dark:bg-green-800 text-green-800 dark:text-green-200"
|
||||
style={pillWidths[leaf.key] ? `min-width: ${pillWidths[leaf.key]}px` : undefined}
|
||||
role="status"
|
||||
transition:fly={{ y: -10, duration: 150 }}
|
||||
>
|
||||
<CheckCircle2 size={14} class="shrink-0" />
|
||||
{done}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -753,6 +909,11 @@ leaves and ignores the current scope.
|
||||
>
|
||||
{@render defaultBranchIcon(entry.node)}
|
||||
<span class="flex-1 truncate">{entry.node.label}</span>
|
||||
{#if entry.node.badge}
|
||||
<span class="shrink-0 pl-2 text-xs font-sans font-normal text-secondary"
|
||||
>{entry.node.badge}</span
|
||||
>
|
||||
{/if}
|
||||
{#if entry.node.loading}
|
||||
<Loader2 size={12} class="animate-spin text-tertiary" />
|
||||
{/if}
|
||||
@@ -767,6 +928,8 @@ leaves and ignores the current scope.
|
||||
<div role="status" class="px-3 py-1.5 text-xs text-tertiary flex items-center gap-2">
|
||||
<Loader2 size={14} class="animate-spin" /> Loading…
|
||||
</div>
|
||||
{:else if currentBranch?.note}
|
||||
<div role="status" class="px-3 py-2 text-xs text-tertiary">{currentBranch.note}</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import Version from './Version.svelte'
|
||||
import DarkModeToggle from './sidebar/DarkModeToggle.svelte'
|
||||
import WindmillIcon from './icons/WindmillIcon.svelte'
|
||||
import { whitelabelNameStore } from '$lib/stores'
|
||||
import { superadmin, whitelabelNameStore } from '$lib/stores'
|
||||
import { capitalize } from '$lib/utils'
|
||||
|
||||
interface Props {
|
||||
@@ -35,7 +35,10 @@
|
||||
{#if showVersion}
|
||||
<div class="font-mono flex-col flex p-2 justify-center">
|
||||
<Version />
|
||||
<Uptodate />
|
||||
<!-- The update check needs a session, and only a superadmin can act on it. -->
|
||||
{#if $superadmin}
|
||||
<Uptodate />
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
<!--
|
||||
@component
|
||||
The access view's "+ Grant" list: the caller's own `u/` folder and every folder, with their items.
|
||||
A row does nothing when clicked. The highlighted row offers each change to the principal's own
|
||||
grant on it that changes what the principal can do (grant read or write, revoke write or read),
|
||||
the most useful one as its button and the others in its dropdown. The "All of f/x" row
|
||||
changes the grant on the whole folder.
|
||||
-->
|
||||
<script module lang="ts">
|
||||
/** The navigator's tallest height, `max-h-[min(460px,60vh)]` below, for its host to place it. */
|
||||
export function navigatorMaxHeight(): number {
|
||||
return Math.min(460, window.innerHeight * 0.6)
|
||||
}
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import DrillPicker from '$lib/components/DrillPicker.svelte'
|
||||
import type { DrillLeaf, DrillLeafAction, DrillNode } from '$lib/components/drillPicker'
|
||||
import RowIcon from '$lib/components/common/table/RowIcon.svelte'
|
||||
import {
|
||||
GranularAclService,
|
||||
type AccessReason,
|
||||
type BrowseAccessFoldersResponse,
|
||||
type BrowseAccessItemsResponse,
|
||||
type PrincipalAccess
|
||||
} from '$lib/gen'
|
||||
import {
|
||||
useOperatingUser,
|
||||
useOperatingWorkspace
|
||||
} from '$lib/components/operatingWorkspace.svelte'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { debounce } from '$lib/utils'
|
||||
import { Folder, User, Users } from 'lucide-svelte'
|
||||
import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte'
|
||||
import { setOverlayHost } from '$lib/components/common/overlayHost.svelte'
|
||||
import { setGrant, type GrantLevel, type GrantSource } from './access'
|
||||
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
const operatingUser = useOperatingUser()
|
||||
|
||||
type Row = BrowseAccessItemsResponse['items'][number]
|
||||
/** `kind` `folder` is the "All of f/x" row, its `path` the folder name. */
|
||||
type Leaf = Row & { owner?: boolean }
|
||||
/** What the principal holds on a row besides its own entry: the level, `undefined` where the
|
||||
* access report cannot tell, and where it comes from, in the access table's words. */
|
||||
type Inherited = { level: GrantLevel | undefined; hows: string[] }
|
||||
|
||||
let {
|
||||
principal,
|
||||
access,
|
||||
onChange,
|
||||
source
|
||||
}: {
|
||||
principal: string
|
||||
access: PrincipalAccess
|
||||
/** After each change to a grant, for the host to reload `access`. */
|
||||
onChange: () => void
|
||||
source?: GrantSource
|
||||
} = $props()
|
||||
|
||||
const api: GrantSource = {
|
||||
get ownSpace() {
|
||||
return `u/${operatingUser.current?.username}`
|
||||
},
|
||||
folders: () =>
|
||||
GranularAclService.browseAccessFolders({ workspace: $operatingWorkspace!, principal }),
|
||||
items: (query) =>
|
||||
GranularAclService.browseAccessItems({
|
||||
workspace: $operatingWorkspace!,
|
||||
principal,
|
||||
...query
|
||||
}),
|
||||
set: (kind, path, level) => setGrant($operatingWorkspace!, kind, path, principal, level)
|
||||
}
|
||||
const data = $derived(source ?? api)
|
||||
const own = $derived(data.ownSpace)
|
||||
|
||||
let picker: { focus: () => void; escape: (target: EventTarget | null) => boolean } | undefined =
|
||||
$state()
|
||||
let folders: BrowseAccessFoldersResponse | undefined = $state()
|
||||
/** Rows by top-level branch (`u/alice`, `f/billing`), then by `kind:path`. */
|
||||
let rows: Record<string, Record<string, Row>> = $state({})
|
||||
let loading: Record<string, boolean> = $state({})
|
||||
const loaded = new Set<string>()
|
||||
/** Branches whose every page has arrived, so no rows there means the folder has no items. */
|
||||
let complete: Record<string, boolean> = $state({})
|
||||
/** The change in flight, as `kind:path:label`. */
|
||||
let pending: string | undefined = $state()
|
||||
/** Runs before this time are ignored: the second press of a double click or Enter would
|
||||
* otherwise run the button that took the first one's place. */
|
||||
let settledUntil = 0
|
||||
|
||||
function branchOf(path: string): string {
|
||||
return path.split('/', 2).join('/')
|
||||
}
|
||||
|
||||
function merge(items: Row[]) {
|
||||
for (const item of items) {
|
||||
const branch = branchOf(item.path)
|
||||
rows[branch] ??= {}
|
||||
rows[branch][`${item.kind}:${item.path}`] = item
|
||||
}
|
||||
}
|
||||
|
||||
async function loadFolders() {
|
||||
try {
|
||||
folders = await data.folders()
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not load folders: ${e?.body ?? e}`, true)
|
||||
// The picker shows its loader for as long as there are no folders.
|
||||
folders = []
|
||||
}
|
||||
}
|
||||
|
||||
async function loadBranch(branch: string) {
|
||||
if (loaded.has(branch)) return
|
||||
loaded.add(branch)
|
||||
loading[branch] = true
|
||||
try {
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const page = await data.items({ prefix: `${branch}/`, offset })
|
||||
merge(page.items)
|
||||
// The branch shows from its first page; later pages fill it in as they arrive.
|
||||
loading[branch] = false
|
||||
if (!page.has_more) break
|
||||
offset += page.items.length
|
||||
}
|
||||
complete[branch] = true
|
||||
} catch (e) {
|
||||
loaded.delete(branch)
|
||||
sendUserToast(`Could not load ${branch}: ${e?.body ?? e}`, true)
|
||||
} finally {
|
||||
loading[branch] = false
|
||||
}
|
||||
}
|
||||
|
||||
// The picker searches only the rows it holds, so matches anywhere are fetched into the tree.
|
||||
let searchId = 0
|
||||
const searchSoon = debounce(async (search: string) => {
|
||||
const id = ++searchId
|
||||
try {
|
||||
let offset = 0
|
||||
// Every page of matches, unless a newer search has replaced this one.
|
||||
while (id === searchId) {
|
||||
const page = await data.items({ search, offset })
|
||||
merge(page.items)
|
||||
if (!page.has_more) break
|
||||
offset += page.items.length
|
||||
}
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not search: ${e?.body ?? e}`, true)
|
||||
}
|
||||
}, 250).debounced
|
||||
|
||||
loadFolders()
|
||||
|
||||
function itemLeaf(row: Row): DrillLeaf<Leaf> {
|
||||
return {
|
||||
type: 'leaf',
|
||||
key: `${row.kind}:${row.path}`,
|
||||
label: row.path.split('/').slice(2).join('/'),
|
||||
secondary: row.path,
|
||||
searchableText: row.path,
|
||||
data: row,
|
||||
disabled: !!row.blocked
|
||||
}
|
||||
}
|
||||
|
||||
function itemLeaves(branch: string): DrillLeaf<Leaf>[] {
|
||||
return Object.values(rows[branch] ?? {})
|
||||
.sort((a, b) => a.path.localeCompare(b.path) || a.kind.localeCompare(b.kind))
|
||||
.map(itemLeaf)
|
||||
}
|
||||
|
||||
function folderData(folder: BrowseAccessFoldersResponse[number]): Leaf {
|
||||
return {
|
||||
kind: 'folder',
|
||||
path: folder.name,
|
||||
grant: folder.grant,
|
||||
blocked: folder.blocked,
|
||||
owner: folder.target_owner
|
||||
}
|
||||
}
|
||||
|
||||
const tree = $derived.by<DrillNode<Leaf>[]>(() => {
|
||||
const folderNames = new Set((folders ?? []).map((f) => `f/${f.name}`))
|
||||
const others = Object.keys(rows)
|
||||
.filter((b) => b !== own && !folderNames.has(b))
|
||||
.sort()
|
||||
return [
|
||||
{
|
||||
type: 'branch',
|
||||
key: own,
|
||||
label: own,
|
||||
icon: User,
|
||||
searchGroup: true,
|
||||
loading: loading[own],
|
||||
children: itemLeaves(own)
|
||||
},
|
||||
...(folders ?? []).map((folder): DrillNode<Leaf> => {
|
||||
const branch = `f/${folder.name}`
|
||||
const items = itemLeaves(branch)
|
||||
const level = levelOf(folderData(folder), `folder:${folder.name}`)
|
||||
return {
|
||||
type: 'branch',
|
||||
key: branch,
|
||||
label: branch,
|
||||
icon: Folder,
|
||||
searchGroup: true,
|
||||
loading: loading[branch],
|
||||
badge: level === 'none' ? undefined : LEVEL_LABELS[level],
|
||||
note:
|
||||
complete[branch] && items.length === 0
|
||||
? `${branch} has no items yet. A grant on the whole folder covers the items added later.`
|
||||
: undefined,
|
||||
children: [
|
||||
{
|
||||
type: 'leaf',
|
||||
key: `folder:${folder.name}`,
|
||||
label: `All of f/${folder.name}`,
|
||||
searchableText: branch,
|
||||
data: folderData(folder),
|
||||
disabled: folder.target_owner || !!folder.blocked
|
||||
},
|
||||
...items
|
||||
]
|
||||
}
|
||||
}),
|
||||
// Other users' and groups' items appear once a search finds them.
|
||||
...others.map(
|
||||
(b): DrillNode<Leaf> => ({
|
||||
type: 'branch',
|
||||
key: b,
|
||||
label: b,
|
||||
icon: b.startsWith('g/') ? Users : User,
|
||||
searchGroup: true,
|
||||
children: itemLeaves(b)
|
||||
})
|
||||
)
|
||||
]
|
||||
})
|
||||
|
||||
const reasons = $derived(
|
||||
new Map<string, AccessReason[]>(
|
||||
access.items.map((i) => [`${i.kind}:${i.path}`, i.reasons] as const)
|
||||
)
|
||||
)
|
||||
const reachedFolders = $derived(new Map(access.folders.map((f) => [f.name, f])))
|
||||
|
||||
const isGroup = $derived(principal.startsWith('g/'))
|
||||
const who = $derived(isGroup ? `members of ${principal}` : principal)
|
||||
|
||||
/** What read and write let the principal do, by kind. */
|
||||
const GIVES: Record<string, { read: string; write: string }> = {
|
||||
folder: { read: 'read all its items, new ones included', write: 'edit and add items' },
|
||||
script: { read: 'see and run it', write: 'edit it' },
|
||||
flow: { read: 'see and run it', write: 'edit it' },
|
||||
app: { read: 'open and use it', write: 'edit it' },
|
||||
raw_app: { read: 'open and use it', write: 'edit it' },
|
||||
resource: { read: 'use it and see its value', write: 'change its value' },
|
||||
variable: { read: 'use it and see its value', write: 'change its value' },
|
||||
schedule: { read: 'see it', write: 'edit, enable and disable it' }
|
||||
}
|
||||
const GIVES_OTHER = { read: 'see it', write: 'edit it' }
|
||||
|
||||
const LEVELS: GrantLevel[] = ['none', 'read', 'write']
|
||||
const LEVEL_LABELS: Record<GrantLevel, string> = {
|
||||
none: 'No access',
|
||||
read: 'Read',
|
||||
write: 'Write'
|
||||
}
|
||||
|
||||
function maxLevel(a: GrantLevel, b: GrantLevel): GrantLevel {
|
||||
return LEVELS.indexOf(a) >= LEVELS.indexOf(b) ? a : b
|
||||
}
|
||||
|
||||
function entryLevel(grant: boolean | null | undefined): GrantLevel {
|
||||
return grant == undefined ? 'none' : grant ? 'write' : 'read'
|
||||
}
|
||||
|
||||
/** The principal's own entry on an item, which `grant` on its row holds. */
|
||||
function isOwnEntry(r: AccessReason): boolean {
|
||||
return r.type === 'user' || (r.type === 'group' && `g/${r.group}` === principal)
|
||||
}
|
||||
|
||||
function reasonLabel(r: AccessReason): string {
|
||||
switch (r.type) {
|
||||
case 'folder':
|
||||
return `through f/${r.folder}`
|
||||
case 'group':
|
||||
return `through g/${r.group}`
|
||||
case 'own':
|
||||
return `under ${principal}/`
|
||||
case 'group_path':
|
||||
return `under g/${r.group}/`
|
||||
default:
|
||||
return 'shared directly'
|
||||
}
|
||||
}
|
||||
|
||||
function inheritedOf(row: Leaf, key: string): Inherited {
|
||||
if (row.kind === 'folder') {
|
||||
if (row.owner) return { level: 'write', hows: ['folder admin'] }
|
||||
const folder = reachedFolders.get(row.path)
|
||||
const others = (folder?.via ?? []).filter((v) => v !== principal)
|
||||
if (!folder || others.length === 0) return { level: 'none', hows: [] }
|
||||
// `via` names the other entries without their levels, so next to the principal's own
|
||||
// write the report cannot tell whether one of them gives write too.
|
||||
const level = folder.grant === true ? undefined : folder.write ? 'write' : 'read'
|
||||
return { level, hows: others.map((v) => `through ${v}`) }
|
||||
}
|
||||
const others = (reasons.get(key) ?? []).filter((r) => !isOwnEntry(r))
|
||||
const level: GrantLevel =
|
||||
others.length === 0
|
||||
? 'none'
|
||||
: others.some((r) => r.type === 'own' || r.type === 'group_path' || r.write)
|
||||
? 'write'
|
||||
: 'read'
|
||||
return { level, hows: others.map(reasonLabel) }
|
||||
}
|
||||
|
||||
/** The level held on a row. The own entry is read from the row, which a change made here
|
||||
* updates before `access` reloads. */
|
||||
function levelOf(row: Leaf, key: string): GrantLevel {
|
||||
return maxLevel(inheritedOf(row, key).level ?? 'read', entryLevel(row.grant))
|
||||
}
|
||||
|
||||
function pathOf(row: Leaf): string {
|
||||
return row.kind === 'folder' ? `f/${row.path}` : row.path
|
||||
}
|
||||
|
||||
/** Why a dimmed row can't be changed, for its tooltip. */
|
||||
function lockedText(row: Leaf): string | undefined {
|
||||
if (row.owner)
|
||||
return `${principal} is an admin of f/${row.path}, so ${isGroup ? 'its members' : 'they'} can write every item in it.`
|
||||
return row.blocked
|
||||
}
|
||||
|
||||
/** Selected on a highlighted row, the first of these it offers. */
|
||||
const PREFERRED = ['Grant read', 'Grant write', 'Revoke write', 'Revoke read']
|
||||
|
||||
function actionsFor(leaf: DrillLeaf<Leaf>): DrillLeafAction[] {
|
||||
const row = leaf.data
|
||||
const ownLevel = entryLevel(row.grant)
|
||||
const inherited = inheritedOf(row, leaf.key)
|
||||
const level = maxLevel(inherited.level ?? 'read', ownLevel)
|
||||
const gives = GIVES[row.kind] ?? GIVES_OTHER
|
||||
// In the order of the level each one leaves, so the buttons read from less to more access.
|
||||
const changes: { label: string; to: GrantLevel; hint: string }[] = []
|
||||
if (ownLevel !== 'none' && inherited.level === 'none') {
|
||||
changes.push({
|
||||
label: 'Revoke read',
|
||||
to: 'none',
|
||||
hint: `${who} can no longer ${gives.read}.`
|
||||
})
|
||||
}
|
||||
if (level === 'none') {
|
||||
changes.push({ label: 'Grant read', to: 'read', hint: `${who} can ${gives.read}.` })
|
||||
}
|
||||
if (ownLevel === 'write' && inherited.level !== 'write') {
|
||||
changes.push({
|
||||
label: 'Revoke write',
|
||||
to: 'read',
|
||||
hint: inherited.level
|
||||
? `${who} can no longer ${gives.write}, only ${gives.read}.`
|
||||
: `the grant becomes read, but ${who} may still write ${inherited.hows.join(' or ')}.`
|
||||
})
|
||||
}
|
||||
if (level !== 'write') {
|
||||
const folder =
|
||||
row.kind !== 'folder' && ownLevel === 'none'
|
||||
? (reasons.get(leaf.key) ?? []).find((r) => r.type === 'folder')?.folder
|
||||
: undefined
|
||||
changes.push({
|
||||
label: 'Grant write',
|
||||
to: 'write',
|
||||
hint:
|
||||
level === 'none'
|
||||
? `${who} can ${gives.read}, and ${gives.write}.`
|
||||
: `${who} can also ${gives.write}.` +
|
||||
(folder ? ` This grant stays if f/${folder} is no longer shared.` : '')
|
||||
})
|
||||
}
|
||||
const preferred = PREFERRED.find((label) => changes.some((c) => c.label === label))
|
||||
return changes.map((c) => ({
|
||||
label: c.label,
|
||||
hint: c.hint,
|
||||
preferred: c.label === preferred,
|
||||
loading: pending === `${leaf.key}:${c.label}`,
|
||||
disabled: pending !== undefined,
|
||||
run: () => change(leaf, c.label, c.to)
|
||||
}))
|
||||
}
|
||||
|
||||
/** A change to a whole folder, waiting for the dialog. */
|
||||
let confirming:
|
||||
| { leaf: DrillLeaf<Leaf>; label: string; level: GrantLevel; hint: string }
|
||||
| undefined = $state()
|
||||
|
||||
function change(leaf: DrillLeaf<Leaf>, label: string, level: GrantLevel) {
|
||||
if (pending !== undefined || Date.now() < settledUntil) return
|
||||
if (leaf.data.kind !== 'folder') {
|
||||
apply(leaf, label, level)
|
||||
return
|
||||
}
|
||||
const hint = actionsFor(leaf).find((a) => a.label === label)?.hint ?? ''
|
||||
confirming = { leaf, label, level, hint }
|
||||
// Else the second press of a double click or Enter would confirm it at once.
|
||||
settledUntil = Date.now() + 400
|
||||
}
|
||||
|
||||
async function confirmFolder() {
|
||||
if (!confirming || pending !== undefined || Date.now() < settledUntil) return
|
||||
await apply(confirming.leaf, confirming.label, confirming.level)
|
||||
confirming = undefined
|
||||
}
|
||||
|
||||
function cancelFolder() {
|
||||
if (pending !== undefined) return
|
||||
confirming = undefined
|
||||
picker?.focus()
|
||||
}
|
||||
|
||||
/** Focus stays in the search field under the dialog, so its keys are answered here: the
|
||||
* dialog's own window listener leaves alone keys that start inside a popover, which is where
|
||||
* the access drawer shows this list. */
|
||||
function dialogKeys(e: KeyboardEvent) {
|
||||
if (!confirming || e.key === 'Tab') return
|
||||
e.stopPropagation()
|
||||
// A focused dialog button activates itself, so Enter on Cancel cancels.
|
||||
const onButton = !!(e.target as HTMLElement | null)?.closest?.('[role="dialog"] button')
|
||||
if (onButton && (e.key === 'Enter' || e.key === ' ')) return
|
||||
e.preventDefault()
|
||||
if (e.key === 'Enter') confirmFolder()
|
||||
else if (e.key === 'Escape') cancelFolder()
|
||||
}
|
||||
|
||||
/** Answers an Escape a host takes before the navigator can: cancels the folder dialog, or
|
||||
* passes it to the picker. False when nothing here was open, so the host closes instead. */
|
||||
export function escape(target: EventTarget | null): boolean {
|
||||
if (confirming) {
|
||||
cancelFolder()
|
||||
return true
|
||||
}
|
||||
return !!picker?.escape(target)
|
||||
}
|
||||
|
||||
let root: HTMLElement | undefined = $state()
|
||||
// The dialog covers this list rather than the page: a click on a dialog over the page lands
|
||||
// outside the drawer's popover, which closes it and the dialog with it.
|
||||
setOverlayHost({ el: () => root, drawers: { val: [] }, active: () => true })
|
||||
|
||||
const DONE: Record<string, string> = {
|
||||
'Grant read': 'Read granted',
|
||||
'Grant write': 'Write granted',
|
||||
'Revoke write': 'Write revoked',
|
||||
'Revoke read': 'Access revoked'
|
||||
}
|
||||
|
||||
/** The row a change just landed on, and what it did ("Read granted"), for 1.5s. */
|
||||
let done: { key: string; text: string } | undefined = $state()
|
||||
let doneTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
function showDone(key: string, text: string) {
|
||||
clearTimeout(doneTimer)
|
||||
done = { key, text }
|
||||
doneTimer = setTimeout(() => (done = undefined), 1000)
|
||||
}
|
||||
|
||||
async function apply(leaf: DrillLeaf<Leaf>, label: string, level: GrantLevel) {
|
||||
const row = leaf.data
|
||||
pending = `${leaf.key}:${label}`
|
||||
try {
|
||||
await data.set(row.kind, row.path, level)
|
||||
row.grant = level === 'none' ? null : level === 'write'
|
||||
if (row.kind === 'folder') {
|
||||
const folder = folders?.find((f) => f.name === row.path)
|
||||
if (folder) folder.grant = row.grant
|
||||
}
|
||||
onChange()
|
||||
showDone(leaf.key, DONE[label] ?? 'Done')
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not ${label.toLowerCase()} on ${pathOf(row)}: ${e?.body ?? e}`, true)
|
||||
} finally {
|
||||
pending = undefined
|
||||
settledUntil = Date.now() + 400
|
||||
// A click left focus on a button, which may be gone now.
|
||||
picker?.focus()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet leafIcon(leaf: DrillLeaf<Leaf>)}
|
||||
<RowIcon kind={leaf.data.kind as 'folder'} size={12} />
|
||||
{/snippet}
|
||||
|
||||
<div
|
||||
bind:this={root}
|
||||
class="relative flex flex-col max-h-[min(460px,60vh)]"
|
||||
onkeydowncapture={dialogKeys}
|
||||
role="presentation"
|
||||
>
|
||||
{#if confirming}
|
||||
{@const folder = pathOf(confirming.leaf.data)}
|
||||
<ConfirmationModal
|
||||
open
|
||||
title="{confirming.label} on {folder}?"
|
||||
confirmationText={confirming.label}
|
||||
type={confirming.label.startsWith('Revoke') ? 'danger' : 'info'}
|
||||
loading={pending !== undefined}
|
||||
onConfirmed={confirmFolder}
|
||||
onCanceled={cancelFolder}
|
||||
>
|
||||
<p>It applies to every item in {folder}: {confirming.hint}</p>
|
||||
</ConfirmationModal>
|
||||
{/if}
|
||||
<DrillPicker
|
||||
bind:this={picker}
|
||||
{tree}
|
||||
{leafIcon}
|
||||
rowTooltip={(leaf) => lockedText(leaf.data)}
|
||||
rootLoading={!folders}
|
||||
onScopeChange={(scope) => scope.length === 1 && loadBranch(scope[0])}
|
||||
onFilterChange={(filter) => filter.trim() && searchSoon(filter.trim())}
|
||||
leafActions={actionsFor}
|
||||
leafDone={(leaf) => (done && done.key === leaf.key ? done.text : undefined)}
|
||||
leafBadge={(leaf) => {
|
||||
const level = levelOf(leaf.data, leaf.key)
|
||||
return level === 'none'
|
||||
? undefined
|
||||
: { label: LEVEL_LABELS[level], color: level === 'write' ? 'blue' : 'gray' }
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
GranularAclService,
|
||||
type BrowseAccessFoldersResponse,
|
||||
type BrowseAccessItemsResponse
|
||||
} from '$lib/gen'
|
||||
|
||||
export type GrantLevel = 'none' | 'read' | 'write'
|
||||
|
||||
/** Where the Grant navigator reads and changes grants. Without one it uses the API, in the
|
||||
* operating workspace. */
|
||||
export type GrantSource = {
|
||||
/** The caller's own `u/` space, listed first. */
|
||||
ownSpace: string
|
||||
folders: () => Promise<BrowseAccessFoldersResponse>
|
||||
items: (query: {
|
||||
prefix?: string
|
||||
search?: string
|
||||
offset?: number
|
||||
}) => Promise<BrowseAccessItemsResponse>
|
||||
/** Sets the principal's own entry, as `setGrant` does. */
|
||||
set: (kind: string, path: string, level: GrantLevel) => Promise<void>
|
||||
}
|
||||
|
||||
type AclKind = Parameters<typeof GranularAclService.addGranularAcls>[0]['kind']
|
||||
|
||||
export const KIND_LABELS: Record<string, string> = {
|
||||
script: 'Script',
|
||||
flow: 'Flow',
|
||||
app: 'App',
|
||||
raw_app: 'Full-code app',
|
||||
resource: 'Resource',
|
||||
variable: 'Variable',
|
||||
schedule: 'Schedule',
|
||||
http_trigger: 'HTTP route',
|
||||
websocket_trigger: 'WebSocket trigger',
|
||||
kafka_trigger: 'Kafka trigger',
|
||||
nats_trigger: 'NATS trigger',
|
||||
postgres_trigger: 'Postgres trigger',
|
||||
mqtt_trigger: 'MQTT trigger',
|
||||
amqp_trigger: 'AMQP trigger',
|
||||
gcp_trigger: 'GCP Pub/Sub trigger',
|
||||
azure_trigger: 'Azure trigger',
|
||||
sqs_trigger: 'SQS trigger',
|
||||
email_trigger: 'Email trigger'
|
||||
}
|
||||
|
||||
/** Sets `principal`'s own entry on an item or folder (`kind` `folder`, `path` the folder name). */
|
||||
export async function setGrant(
|
||||
workspace: string,
|
||||
kind: string,
|
||||
path: string,
|
||||
principal: string,
|
||||
level: GrantLevel
|
||||
): Promise<void> {
|
||||
if (level === 'none') {
|
||||
await GranularAclService.removeGranularAcls({
|
||||
workspace,
|
||||
kind: kind as AclKind,
|
||||
path,
|
||||
requestBody: { owner: principal }
|
||||
})
|
||||
} else {
|
||||
await GranularAclService.addGranularAcls({
|
||||
workspace,
|
||||
kind: kind as AclKind,
|
||||
path,
|
||||
requestBody: { owner: principal, write: level === 'write' }
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -516,9 +516,11 @@
|
||||
'rounded-md m-0 p-0 center-center h-full',
|
||||
variant === 'border' ? 'border-0 border-r border-y ' : 'border-0',
|
||||
'rounded-r-md !rounded-l-none',
|
||||
size === 'xs2' || size === 'xs' || unifiedSize === 'md' || unifiedSize === 'sm'
|
||||
? '!w-8'
|
||||
: '!w-10',
|
||||
unifiedSize === 'xs' || unifiedSize === '2xs'
|
||||
? '!w-6'
|
||||
: size === 'xs2' || size === 'xs' || unifiedSize === 'md' || unifiedSize === 'sm'
|
||||
? '!w-8'
|
||||
: '!w-10',
|
||||
dropdownBtnClasses
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -115,7 +115,7 @@ const listS3FilesToolDef = createToolDef(
|
||||
const readS3FileToolDef = createToolDef(
|
||||
readS3FileSchema,
|
||||
'read_s3_file',
|
||||
"Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text or JSON file, the columns, their types and the first 50 rows of a CSV, TSV, NDJSON or Parquet file, or the image itself for a png, jpeg, gif or webp of up to 3.75 MB, which you then see. Other files return their metadata only."
|
||||
"Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text or JSON file, the columns, their types and the first 50 rows of a CSV, TSV, NDJSON or Parquet file, or the image itself for a png, jpeg, gif or webp of up to 30 MB, which you then see (one past 3.75 MB or 8000 px comes as a smaller JPEG copy). Other files return their metadata only."
|
||||
)
|
||||
const queryS3TableToolDef = createToolDef(
|
||||
queryS3TableSchema,
|
||||
|
||||
@@ -35,6 +35,19 @@ export type DrillLeaf<L> = {
|
||||
plainLabel?: boolean
|
||||
}
|
||||
|
||||
/** Something a leaf row offers (see the picker's `leafActions`). */
|
||||
export type DrillLeafAction = {
|
||||
label: string
|
||||
icon?: DrillIcon
|
||||
/** What running it does, shown under its label in the row's dropdown. */
|
||||
hint?: string
|
||||
/** The row's button, with the others in its dropdown; the first one is otherwise. */
|
||||
preferred?: boolean
|
||||
loading?: boolean
|
||||
disabled?: boolean
|
||||
run: () => void
|
||||
}
|
||||
|
||||
/** Branch node — interior entry the user drills into. */
|
||||
export type DrillBranch<L> = {
|
||||
type: 'branch'
|
||||
@@ -44,6 +57,11 @@ export type DrillBranch<L> = {
|
||||
children: DrillNode<L>[]
|
||||
/** Show a spinner alongside the branch (async loading in progress). */
|
||||
loading?: boolean
|
||||
/** Plain text on the right of the branch's row ("Read"), like a leaf's `leafBadge`. */
|
||||
badge?: string
|
||||
/** A line under the branch's entries once drilled in and loaded, for a branch whose entries
|
||||
* never leave it empty ("f/x has no items yet"), so the picker's "Empty" cannot show. */
|
||||
note?: string
|
||||
/** Hide from search index traversal. Used by the workspace adapter to
|
||||
* keep the cross-kind 'all' branch out of search (its leaves are
|
||||
* duplicates of the per-kind branches' leaves). */
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { Button, Drawer, DrawerContent, Tab, TabContent, Tabs } from '$lib/components/common'
|
||||
import McpUpgradeNotice from '$lib/components/mcp/McpUpgradeNotice.svelte'
|
||||
import CreateToken from '$lib/components/settings/CreateToken.svelte'
|
||||
import CopyableCodeBlock from '$lib/components/details/CopyableCodeBlock.svelte'
|
||||
import { Bot, ExternalLink, Terminal } from 'lucide-svelte'
|
||||
@@ -120,6 +121,7 @@ wmill sync pull`)
|
||||
</div>
|
||||
|
||||
{#key openVersion}
|
||||
<McpUpgradeNotice />
|
||||
<CreateToken
|
||||
mcpOnly
|
||||
lockWorkspace
|
||||
|
||||
@@ -180,12 +180,7 @@
|
||||
</p>
|
||||
<!-- A selection names paths of one workspace, so switching workspace starts it over. -->
|
||||
{#key workspaceId}
|
||||
<McpScopeSelector
|
||||
{workspaceId}
|
||||
bind:scope={selection}
|
||||
initialScope={initialSelection}
|
||||
runnablesOnly
|
||||
/>
|
||||
<McpScopeSelector {workspaceId} bind:scope={selection} initialScope={initialSelection} />
|
||||
{/key}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -9,14 +9,7 @@
|
||||
import { listHubIntegrationsShared } from '$lib/components/displayNameLoaders'
|
||||
import TextInput from '$lib/components/text_input/TextInput.svelte'
|
||||
import { FlowService, FolderService, ScriptService } from '$lib/gen'
|
||||
import { mcpEndpointTools } from '$lib/mcpEndpointTools'
|
||||
import {
|
||||
endpointPathPolicy,
|
||||
isEndpointExposed,
|
||||
matchesAnyPattern,
|
||||
parseMcpScopeState,
|
||||
pruneEndpointSelection
|
||||
} from '$lib/components/mcp/endpointScopePolicy'
|
||||
import { matchesAnyPattern } from '$lib/components/mcp/scopePatterns'
|
||||
import InfoIcon from 'lucide-svelte/icons/info'
|
||||
import { SvelteMap } from 'svelte/reactivity'
|
||||
|
||||
@@ -24,20 +17,9 @@
|
||||
workspaceId: string
|
||||
scope: string
|
||||
initialScope?: string
|
||||
readOnly?: boolean
|
||||
/** Scripts and flows alone, for `/api/mcp`: a selection gets no endpoint tools there, so
|
||||
* endpoints are left out, and since `mcp:all` is the full toolset, "All scripts/flows"
|
||||
* is written as `mcp:scripts:* mcp:flows:*`. */
|
||||
runnablesOnly?: boolean
|
||||
}
|
||||
|
||||
let {
|
||||
workspaceId,
|
||||
scope = $bindable(),
|
||||
initialScope,
|
||||
readOnly = false,
|
||||
runnablesOnly = false
|
||||
}: Props = $props()
|
||||
let { workspaceId, scope = $bindable(), initialScope }: Props = $props()
|
||||
|
||||
// Mirrors ITEMS_FETCH_MAX_LIMIT in backend/windmill-api/src/mcp/utils.rs: the
|
||||
// server exposes at most this many scripts and this many flows (per type) as
|
||||
@@ -45,27 +27,6 @@
|
||||
// silently drops the overflow, so we warn at configuration time.
|
||||
const MCP_TOOL_FETCH_LIMIT = 100
|
||||
|
||||
// Endpoints we can actually advertise to a read-only MCP token. Mirrors the
|
||||
// runner's filter (only GET endpoints).
|
||||
const visibleEndpointTools = $derived(
|
||||
readOnly ? mcpEndpointTools.filter((e) => e.method === 'GET') : mcpEndpointTools
|
||||
)
|
||||
|
||||
// Endpoints the "API Endpoints" list actually governs. The run-by-path tools
|
||||
// are gated by the script/flow selection instead, so listing them here would
|
||||
// offer a checkbox the server ignores; they get their own section.
|
||||
const selectableEndpointTools = $derived(
|
||||
visibleEndpointTools.filter((e) => endpointPathPolicy(e.name)?.kind !== 'runByPath')
|
||||
)
|
||||
|
||||
$effect(() => {
|
||||
if (selectedEndpoints.length === 0) return
|
||||
const filtered = pruneEndpointSelection(selectedEndpoints, readOnly)
|
||||
if (filtered.length !== selectedEndpoints.length) {
|
||||
selectedEndpoints = filtered
|
||||
}
|
||||
})
|
||||
|
||||
const parsedInitial = parseInitialScope(initialScope)
|
||||
|
||||
let selectedMode = $state<'favorites' | 'all' | 'folder' | 'custom'>(parsedInitial.mode)
|
||||
@@ -75,7 +36,6 @@
|
||||
let folderNamesCache = new Map<string, string[]>()
|
||||
let selectedScripts = $state<string[]>(parsedInitial.scripts)
|
||||
let selectedFlows = $state<string[]>(parsedInitial.flows)
|
||||
let selectedEndpoints = $state<string[]>(parsedInitial.endpoints)
|
||||
let customScriptPatterns = $state<string>(parsedInitial.scriptPatterns)
|
||||
let customFlowPatterns = $state<string>(parsedInitial.flowPatterns)
|
||||
let newMcpApps = $state<string[]>(parsedInitial.hubApps)
|
||||
@@ -102,7 +62,6 @@
|
||||
folders: string[]
|
||||
scripts: string[]
|
||||
flows: string[]
|
||||
endpoints: string[]
|
||||
scriptPatterns: string
|
||||
flowPatterns: string
|
||||
hubApps: string[]
|
||||
@@ -114,7 +73,6 @@
|
||||
folders: [],
|
||||
scripts: [],
|
||||
flows: [],
|
||||
endpoints: [],
|
||||
scriptPatterns: '',
|
||||
flowPatterns: '',
|
||||
hubApps: []
|
||||
@@ -125,6 +83,7 @@
|
||||
if (parts.length === 0) return empty
|
||||
|
||||
const byKind: Record<string, string[]> = {}
|
||||
let namesEndpoints = false
|
||||
let mode: ParsedScope['mode'] = 'custom'
|
||||
const hubApps: string[] = []
|
||||
|
||||
@@ -140,12 +99,13 @@
|
||||
} else if (part.startsWith('mcp:flows:')) {
|
||||
byKind.flows = parsePatterns(part.slice('mcp:flows:'.length))
|
||||
} else if (part.startsWith('mcp:endpoints:')) {
|
||||
byKind.endpoints = parsePatterns(part.slice('mcp:endpoints:'.length))
|
||||
namesEndpoints = true
|
||||
}
|
||||
}
|
||||
|
||||
// Detect folder mode: scripts and flows are exclusively `f/X/*` patterns
|
||||
// for the same set of folders, and endpoints is exactly `*`.
|
||||
// for the same set of folders. An older token that also names endpoints
|
||||
// opens as a custom selection.
|
||||
const folderRe = /^f\/([^/]+)\/\*$/
|
||||
const scriptFolders = (byKind.scripts ?? []).map((p) => p.match(folderRe)?.[1])
|
||||
const flowFolders = (byKind.flows ?? []).map((p) => p.match(folderRe)?.[1])
|
||||
@@ -156,22 +116,18 @@
|
||||
allFlowsAreFolders &&
|
||||
scriptFolders.length === flowFolders.length &&
|
||||
scriptFolders.every((f, i) => f === flowFolders[i])
|
||||
const endpointsIsAll = byKind.endpoints?.length === 1 && byKind.endpoints[0] === '*'
|
||||
// Without endpoints, scopes say "folder" or "all" with the scripts and flows alone.
|
||||
const endpointsAsExpected = runnablesOnly ? !byKind.endpoints : endpointsIsAll
|
||||
const isWildcard = (patterns?: string[]) => patterns?.length === 1 && patterns[0] === '*'
|
||||
|
||||
if (runnablesOnly && isWildcard(byKind.scripts) && isWildcard(byKind.flows)) {
|
||||
if (isWildcard(byKind.scripts) && isWildcard(byKind.flows)) {
|
||||
return { ...empty, mode: 'all', hubApps }
|
||||
}
|
||||
|
||||
if (mode !== 'favorites' && mode !== 'all' && sameFolders && endpointsAsExpected) {
|
||||
if (mode !== 'favorites' && mode !== 'all' && sameFolders && !namesEndpoints) {
|
||||
return {
|
||||
mode: 'folder',
|
||||
folders: scriptFolders.filter((f): f is string => !!f),
|
||||
scripts: [],
|
||||
flows: [],
|
||||
endpoints: [],
|
||||
scriptPatterns: '',
|
||||
flowPatterns: '',
|
||||
hubApps
|
||||
@@ -192,16 +148,13 @@
|
||||
folders: [],
|
||||
scripts: [],
|
||||
flows: [],
|
||||
endpoints: byKind.endpoints ?? [],
|
||||
scriptPatterns: (byKind.scripts ?? []).join(','),
|
||||
flowPatterns: (byKind.flows ?? []).join(','),
|
||||
hubApps
|
||||
}
|
||||
}
|
||||
|
||||
// Compute scope string from selections. Derived rather than assigned straight
|
||||
// to `scope` so the exposure previews below can read it in the same pass as
|
||||
// the selection that changed it.
|
||||
// Compute scope string from selections.
|
||||
const computedScope = $derived.by(() => {
|
||||
let scopeParts: string[] = []
|
||||
|
||||
@@ -221,24 +174,17 @@
|
||||
if (flowPaths.length > 0) {
|
||||
scopeParts.push(`mcp:flows:${flowPaths.join(',')}`)
|
||||
}
|
||||
|
||||
if (!runnablesOnly && selectedEndpoints.length > 0) {
|
||||
scopeParts.push(`mcp:endpoints:${selectedEndpoints.join(',')}`)
|
||||
}
|
||||
} else if (selectedMode === 'folder') {
|
||||
const folderPaths = selectedFolders.map((f) => `f/${f}/*`).join(',')
|
||||
if (selectedFolders.length > 0) {
|
||||
scopeParts = [`mcp:scripts:${folderPaths}`, `mcp:flows:${folderPaths}`]
|
||||
if (!runnablesOnly) {
|
||||
scopeParts.push(`mcp:endpoints:*`)
|
||||
}
|
||||
}
|
||||
} else if (selectedMode === 'all' && runnablesOnly) {
|
||||
} else if (selectedMode === 'all') {
|
||||
// `mcp:all` is the full toolset on `/api/mcp`: every script and flow as its own
|
||||
// tool is said with wildcards instead.
|
||||
scopeParts = ['mcp:scripts:*', 'mcp:flows:*']
|
||||
} else {
|
||||
scopeParts = [`mcp:${selectedMode}`]
|
||||
scopeParts = ['mcp:favorites']
|
||||
}
|
||||
|
||||
if (newMcpApps.length > 0) {
|
||||
@@ -501,7 +447,6 @@
|
||||
})
|
||||
|
||||
const truncationWarning = $derived.by(() => {
|
||||
if (readOnly) return undefined
|
||||
const parts: string[] = []
|
||||
if ((exposedScriptCount ?? 0) > MCP_TOOL_FETCH_LIMIT)
|
||||
parts.push(`${exposedScriptCount} scripts`)
|
||||
@@ -510,39 +455,6 @@
|
||||
return `This scope matches ${parts.join(' and ')}. Only the ${MCP_TOOL_FETCH_LIMIT} most recent of each type are exposed as MCP tools; the rest are omitted. Narrow the scope to avoid overloading the assistant's context.`
|
||||
})
|
||||
|
||||
// Parsed from the emitted scope string rather than from the selections, so the
|
||||
// previews below answer "what will the server expose for this token" with the
|
||||
// same input the server gets.
|
||||
const scopeState = $derived(
|
||||
parseMcpScopeState(computedScope.split(/\s+/).filter((s) => s.length > 0))
|
||||
)
|
||||
|
||||
const exposedEndpointTools = $derived(
|
||||
visibleEndpointTools.filter((e) => isEndpointExposed(scopeState, e.name))
|
||||
)
|
||||
|
||||
const runByPathTools = $derived(
|
||||
visibleEndpointTools.flatMap((e) => {
|
||||
const policy = endpointPathPolicy(e.name)
|
||||
return policy?.kind === 'runByPath'
|
||||
? [
|
||||
{
|
||||
name: e.name,
|
||||
resource: policy.resource,
|
||||
exposed: isEndpointExposed(scopeState, e.name)
|
||||
}
|
||||
]
|
||||
: []
|
||||
})
|
||||
)
|
||||
|
||||
// Endpoints the user picked that the server will still withhold: the ones
|
||||
// that cannot be confined to a path (run-preview, delete-by-hash) once the
|
||||
// token is limited to specific script paths.
|
||||
const withheldEndpoints = $derived(
|
||||
selectedEndpoints.filter((name) => !isEndpointExposed(scopeState, name))
|
||||
)
|
||||
|
||||
function selectAllScripts() {
|
||||
selectedScripts = [...allScripts]
|
||||
}
|
||||
@@ -555,12 +467,6 @@
|
||||
function clearAllFlows() {
|
||||
selectedFlows = []
|
||||
}
|
||||
function selectAllEndpoints() {
|
||||
selectedEndpoints = [...selectableEndpointTools.map((e) => e.name)]
|
||||
}
|
||||
function clearAllEndpoints() {
|
||||
selectedEndpoints = []
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
@@ -590,7 +496,7 @@
|
||||
{item}
|
||||
value="custom"
|
||||
label="Custom"
|
||||
tooltip="Select exactly which scripts, flows, and endpoints to expose"
|
||||
tooltip="Select exactly which scripts and flows to expose"
|
||||
/>
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
@@ -680,56 +586,8 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if !runnablesOnly}
|
||||
<div class="flex flex-col gap-2 mt-2">
|
||||
{@render sectionHeader('API Endpoints', selectAllEndpoints, clearAllEndpoints)}
|
||||
<MultiSelect
|
||||
items={safeSelectItems(selectableEndpointTools.map((e) => e.name))}
|
||||
placeholder="Select endpoints"
|
||||
bind:value={selectedEndpoints}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !runnablesOnly && withheldEndpoints.length > 0}
|
||||
<Alert type="warning" size="xs" title="Some selected endpoints will not be exposed">
|
||||
<span class="text-xs">
|
||||
Endpoints that cannot be limited to specific script paths are withheld from a token
|
||||
restricted to a script selection: {withheldEndpoints.join(', ')}. Widening the script
|
||||
wildcard pattern to <code>*</code> exposes them, and keeps the run tools below available.
|
||||
</span>
|
||||
</Alert>
|
||||
{/if}
|
||||
|
||||
{#if !runnablesOnly && runByPathTools.length > 0}
|
||||
<div class="flex flex-col gap-2 mt-2">
|
||||
<span class="block text-xs font-semibold">Run tools</span>
|
||||
<p class="text-xs text-tertiary">
|
||||
Running a script or flow by path is granted by the Scripts and Flows selections above,
|
||||
not by the endpoint list, so a token can never run something outside its scope.
|
||||
</p>
|
||||
<div class="flex flex-col gap-1">
|
||||
{#each runByPathTools as tool (tool.name)}
|
||||
<div class="flex items-center gap-2">
|
||||
<Badge rounded small color={tool.exposed ? 'green' : 'gray'}>{tool.name}</Badge>
|
||||
<span class="text-xs text-tertiary">
|
||||
{#if tool.exposed}
|
||||
exposed
|
||||
{:else}
|
||||
not exposed — select at least one {tool.resource} above, or add a {tool.resource}
|
||||
wildcard pattern
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="text-xs text-primary mt-2">
|
||||
Selected: {selectedScripts.length} scripts, {selectedFlows.length} flows{#if !runnablesOnly},
|
||||
{selectedEndpoints.length}
|
||||
endpoints{/if}
|
||||
Selected: {selectedScripts.length} scripts, {selectedFlows.length} flows
|
||||
</div>
|
||||
|
||||
<!-- Wildcard Patterns Section -->
|
||||
@@ -786,51 +644,25 @@
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-2">
|
||||
{#if !readOnly}
|
||||
<span class="block text-xs">Scripts & Flows that will be available via MCP</span>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#if includedRunnables.length > 0 && includedRunnables.length <= 5}
|
||||
{#each includedRunnables as scriptOrFlow (scriptOrFlow)}
|
||||
<Badge rounded small color="blue">{scriptOrFlow}</Badge>
|
||||
{/each}
|
||||
{:else if includedRunnables.length > 0}
|
||||
{#each includedRunnables.slice(0, 3) as scriptOrFlow (scriptOrFlow)}
|
||||
<Badge rounded small color="blue">{scriptOrFlow}</Badge>
|
||||
{/each}
|
||||
<Badge rounded small color="dark-gray">
|
||||
+{includedRunnables.length - 3} more
|
||||
</Badge>
|
||||
{:else}
|
||||
<p class="text-xs text-primary">
|
||||
{warning}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-xs text-tertiary">
|
||||
Scripts and flows are hidden because this token is read-only.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
{#if !runnablesOnly}
|
||||
<span class="block text-xs mt-2">API endpoint tools that will be available via MCP</span>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#each exposedEndpointTools as endpoint (endpoint.name)}
|
||||
<Popover notClickable>
|
||||
{#snippet text()}
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="text-xs">{endpoint.description}</div>
|
||||
<div class="text-xs">
|
||||
{endpoint.method}
|
||||
{endpoint.path}
|
||||
</div>
|
||||
</div>
|
||||
{/snippet}
|
||||
<Badge rounded small color="green">{endpoint.name}</Badge>
|
||||
</Popover>
|
||||
<span class="block text-xs">Scripts & Flows that will be available via MCP</span>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#if includedRunnables.length > 0 && includedRunnables.length <= 5}
|
||||
{#each includedRunnables as scriptOrFlow (scriptOrFlow)}
|
||||
<Badge rounded small color="blue">{scriptOrFlow}</Badge>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{:else if includedRunnables.length > 0}
|
||||
{#each includedRunnables.slice(0, 3) as scriptOrFlow (scriptOrFlow)}
|
||||
<Badge rounded small color="blue">{scriptOrFlow}</Badge>
|
||||
{/each}
|
||||
<Badge rounded small color="dark-gray">
|
||||
+{includedRunnables.length - 3} more
|
||||
</Badge>
|
||||
{:else}
|
||||
<p class="text-xs text-primary">
|
||||
{warning}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
<script lang="ts">
|
||||
import { resource } from 'runed'
|
||||
import { SvelteSet } from 'svelte/reactivity'
|
||||
import { UserService, type TruncatedToken } from '$lib/gen'
|
||||
import { Alert } from '$lib/components/common'
|
||||
import Checkbox from '$lib/components/common/checkbox/Checkbox.svelte'
|
||||
import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { displayDate, pluralize } from '$lib/utils'
|
||||
import { MCP_SESSION } from './McpAccessPicker.svelte'
|
||||
import { upgradableMcpTokens } from './mcpUpgrade'
|
||||
|
||||
let open = $state(false)
|
||||
let upgrading = $state(false)
|
||||
const unchecked = new SvelteSet<string>()
|
||||
|
||||
// All of them rather than a first page: the tokens looked for are among the oldest.
|
||||
const tokens = resource(
|
||||
() => undefined,
|
||||
async () =>
|
||||
upgradableMcpTokens(await UserService.listTokens({ excludeEphemeral: true, perPage: 10000 }))
|
||||
)
|
||||
const listed = $derived(tokens.current ?? [])
|
||||
const selected = $derived(listed.filter((t) => !unchecked.has(t.token_prefix)))
|
||||
|
||||
function name(token: TruncatedToken): string {
|
||||
if (token.label?.startsWith('mcp-oauth-')) return 'OAuth sign-in'
|
||||
return token.label || 'Unnamed token'
|
||||
}
|
||||
|
||||
function review() {
|
||||
unchecked.clear()
|
||||
open = true
|
||||
}
|
||||
|
||||
// From our own state: `Checkbox` is back to its old value by the time `change` fires.
|
||||
function toggle(prefix: string) {
|
||||
if (!unchecked.delete(prefix)) unchecked.add(prefix)
|
||||
}
|
||||
|
||||
async function upgrade() {
|
||||
upgrading = true
|
||||
const failures: string[] = []
|
||||
const picked = selected
|
||||
for (const token of picked) {
|
||||
try {
|
||||
await UserService.updateTokenScopes({
|
||||
tokenPrefix: token.token_prefix,
|
||||
requestBody: { scopes: [...(token.scopes ?? []), MCP_SESSION] }
|
||||
})
|
||||
} catch (err) {
|
||||
failures.push(`${name(token)} (${token.token_prefix}****): ${err.body ?? err.message}`)
|
||||
}
|
||||
}
|
||||
const upgraded = picked.length - failures.length
|
||||
if (upgraded > 0) {
|
||||
sendUserToast(
|
||||
`${pluralize(upgraded, 'connection')} upgraded. Reconnect your AI client to load the new tools.`
|
||||
)
|
||||
}
|
||||
if (failures.length > 0) {
|
||||
sendUserToast(`Failed to upgrade ${failures.join(', ')}`, true)
|
||||
}
|
||||
await tokens.refetch()
|
||||
upgrading = false
|
||||
// On a failure too: the dialog would dim the toasts. What failed is still listed on reopening.
|
||||
open = false
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if listed.length > 0}
|
||||
<Alert
|
||||
type="info"
|
||||
size="xs"
|
||||
title="An improved MCP toolset is available for {listed.length === 1
|
||||
? 'one'
|
||||
: listed.length} of your connections"
|
||||
actions={[{ label: 'Review and upgrade', onClick: review }]}
|
||||
/>
|
||||
|
||||
<!-- Portalled out of the drawer the notice sits in, which would confine the dialog. -->
|
||||
<ConfirmationModal
|
||||
{open}
|
||||
alwaysPortal
|
||||
type="info"
|
||||
showIcon={false}
|
||||
title="Upgrade to the improved MCP toolset"
|
||||
confirmationText="Upgrade {pluralize(selected.length, 'connection')}"
|
||||
confirmDisabled={selected.length === 0}
|
||||
loading={upgrading}
|
||||
onConfirmed={upgrade}
|
||||
onCanceled={() => (open = false)}
|
||||
>
|
||||
<div class="flex flex-col gap-3 text-xs">
|
||||
<p>
|
||||
We rebuilt the MCP toolset for building on Windmill. Your AI client gets the same tools as
|
||||
Windmill's AI sessions, to build apps, flows, triggers, data tables and AI agents.
|
||||
</p>
|
||||
<ul class="flex max-h-60 flex-col gap-2 overflow-y-auto p-1 -m-1">
|
||||
{#each listed as token (token.token_prefix)}
|
||||
<li>
|
||||
<label class="flex items-center gap-2">
|
||||
<Checkbox
|
||||
class="shrink-0"
|
||||
checked={!unchecked.has(token.token_prefix)}
|
||||
disabled={upgrading}
|
||||
onChange={() => toggle(token.token_prefix)}
|
||||
/>
|
||||
<span class="min-w-0 truncate">
|
||||
<span class="font-semibold text-emphasis">{name(token)}</span>
|
||||
<span class="font-mono">{token.token_prefix}****</span>, last used
|
||||
{displayDate(token.last_used_at)}
|
||||
</span>
|
||||
</label>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
<p class="text-2xs text-hint">This cannot be undone from this page.</p>
|
||||
</div>
|
||||
</ConfirmationModal>
|
||||
{/if}
|
||||
@@ -1,68 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
endpointPathPolicy,
|
||||
isEndpointExposed,
|
||||
parseMcpScopeState,
|
||||
pruneEndpointSelection
|
||||
} from './endpointScopePolicy'
|
||||
import { mcpEndpointTools } from '$lib/mcpEndpointTools'
|
||||
|
||||
const state = (...scopes: string[]) => parseMcpScopeState(scopes)
|
||||
|
||||
describe('isEndpointExposed', () => {
|
||||
it('gates run-by-path tools on the script/flow scope, not the endpoint scope', () => {
|
||||
// Selecting the endpoint without any script path exposes nothing...
|
||||
const endpointsOnly = state('mcp:endpoints:runScriptByPath,listScripts')
|
||||
expect(isEndpointExposed(endpointsOnly, 'runScriptByPath')).toBe(false)
|
||||
expect(isEndpointExposed(endpointsOnly, 'listScripts')).toBe(true)
|
||||
|
||||
// ...while a script path exposes it without any endpoint scope.
|
||||
expect(isEndpointExposed(state('mcp:scripts:f/team/*'), 'runScriptByPath')).toBe(true)
|
||||
expect(isEndpointExposed(state('mcp:scripts:f/team/*'), 'runFlowByPath')).toBe(false)
|
||||
|
||||
// Favorites reach their runnables through per-item tools only.
|
||||
expect(isEndpointExposed(state('mcp:favorites'), 'runScriptByPath')).toBe(false)
|
||||
expect(isEndpointExposed(state('mcp:all'), 'runScriptByPath')).toBe(true)
|
||||
})
|
||||
|
||||
// A script/flow tool the URL addresses by path but the policy does not name falls
|
||||
// through to "no policy", which is "not path-confined at all" — a scoped token then
|
||||
// reaches every path of that kind. Catch the omission here rather than in a review.
|
||||
it('gives every path-addressed script/flow tool a policy', () => {
|
||||
const unpoliced = mcpEndpointTools
|
||||
.filter((e) => /\/(scripts|flows)\//.test(e.path) && e.path.includes('{path}'))
|
||||
.map((e) => e.name)
|
||||
.filter((name) => endpointPathPolicy(name) === undefined)
|
||||
expect(unpoliced).toEqual([])
|
||||
})
|
||||
|
||||
it('withholds unconfinable tools from path-confined tokens', () => {
|
||||
const confined = state('mcp:scripts:f/team/*', 'mcp:endpoints:*')
|
||||
expect(isEndpointExposed(confined, 'runScriptPreviewAndWaitResult')).toBe(false)
|
||||
expect(isEndpointExposed(confined, 'getScriptByPath')).toBe(true)
|
||||
|
||||
// A `*` script pattern is not a confinement.
|
||||
expect(
|
||||
isEndpointExposed(state('mcp:scripts:*', 'mcp:endpoints:*'), 'runScriptPreviewAndWaitResult')
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('pruneEndpointSelection', () => {
|
||||
it('keeps a `*` endpoint scope, which would otherwise revoke every endpoint tool', () => {
|
||||
expect(pruneEndpointSelection(['*'], false)).toEqual(['*'])
|
||||
expect(pruneEndpointSelection(['*'], true)).toEqual(['*'])
|
||||
})
|
||||
|
||||
it('drops only names the endpoint scope cannot honor', () => {
|
||||
expect(pruneEndpointSelection(['runScriptByPath', 'listScripts'], false)).toEqual([
|
||||
'listScripts'
|
||||
])
|
||||
// Non-GET endpoints go only when the token is read-only.
|
||||
expect(pruneEndpointSelection(['createScript', 'listScripts'], false)).toEqual([
|
||||
'createScript',
|
||||
'listScripts'
|
||||
])
|
||||
expect(pruneEndpointSelection(['createScript', 'listScripts'], true)).toEqual(['listScripts'])
|
||||
})
|
||||
})
|
||||
@@ -1,164 +0,0 @@
|
||||
/**
|
||||
* Mirrors `endpoint_path_policy` / `endpoint_tool_in_scope` in
|
||||
* backend/windmill-mcp/src/server/runner.rs. Two endpoint tools are not governed
|
||||
* by the `mcp:endpoints:` scope at all, and two more are hidden from tokens
|
||||
* confined to specific script paths — without mirroring that here, the scope
|
||||
* picker advertises tools the server will never list.
|
||||
*/
|
||||
|
||||
import { mcpEndpointTools } from '$lib/mcpEndpointTools'
|
||||
|
||||
export type McpResourceKind = 'script' | 'flow'
|
||||
|
||||
export type EndpointPathPolicy =
|
||||
/** Runs the script/flow named by the `path` argument. Listed when the token
|
||||
* grants at least one path of that kind; the endpoint scope is ignored. */
|
||||
| { kind: 'runByPath'; resource: McpResourceKind }
|
||||
/** Reads/writes a script/flow named by a path argument, itself confined to
|
||||
* the token's path patterns. Listed by the endpoint scope. */
|
||||
| { kind: 'pathArgs'; resource: McpResourceKind }
|
||||
/** Takes no checkable path (delete-by-hash) or runs arbitrary code
|
||||
* (preview); hidden from tokens confined to specific paths. */
|
||||
| { kind: 'unconfinable'; resource: McpResourceKind }
|
||||
|
||||
export function endpointPathPolicy(name: string): EndpointPathPolicy | undefined {
|
||||
switch (name) {
|
||||
case 'runScriptByPath':
|
||||
return { kind: 'runByPath', resource: 'script' }
|
||||
case 'runFlowByPath':
|
||||
return { kind: 'runByPath', resource: 'flow' }
|
||||
case 'getScriptByPath':
|
||||
case 'deleteScriptByPath':
|
||||
case 'createScript':
|
||||
case 'updateScript':
|
||||
return { kind: 'pathArgs', resource: 'script' }
|
||||
case 'getFlowByPath':
|
||||
case 'deleteFlowByPath':
|
||||
case 'createFlow':
|
||||
case 'updateFlow':
|
||||
return { kind: 'pathArgs', resource: 'flow' }
|
||||
case 'deleteScriptByHash':
|
||||
case 'runScriptPreviewAndWaitResult':
|
||||
return { kind: 'unconfinable', resource: 'script' }
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** The parsed shape of an MCP token's scopes, as `McpScopeConfig` on the backend. */
|
||||
export type McpScopeState = {
|
||||
/** Legacy `mcp:all` — grants every path and endpoint. */
|
||||
all: boolean
|
||||
/** Legacy `mcp:favorites` — reaches favorites through per-item tools only. */
|
||||
favorites: boolean
|
||||
scripts: string[]
|
||||
flows: string[]
|
||||
endpoints: string[]
|
||||
}
|
||||
|
||||
function parseResourceList(resources: string): string[] {
|
||||
return resources
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.length > 0)
|
||||
}
|
||||
|
||||
/** Mirrors `parse_mcp_scopes` so the picker can preview exactly what the server
|
||||
* will make of the scope string it is about to emit. `mcp:hub:` is deliberately
|
||||
* ignored: hub apps select which hub scripts become tools and never affect
|
||||
* endpoint-tool exposure. */
|
||||
export function parseMcpScopeState(scopes: string[]): McpScopeState {
|
||||
const state: McpScopeState = {
|
||||
all: false,
|
||||
favorites: false,
|
||||
scripts: [],
|
||||
flows: [],
|
||||
endpoints: []
|
||||
}
|
||||
for (const scope of scopes) {
|
||||
if (scope === 'mcp:all') {
|
||||
state.all = true
|
||||
state.scripts.push('*')
|
||||
state.flows.push('*')
|
||||
state.endpoints.push('*')
|
||||
} else if (scope === 'mcp:favorites') {
|
||||
state.favorites = true
|
||||
} else if (scope.startsWith('mcp:all:')) {
|
||||
const folder = scope.slice('mcp:all:'.length)
|
||||
state.scripts.push(folder)
|
||||
state.flows.push(folder)
|
||||
state.endpoints.push('*')
|
||||
} else if (scope.startsWith('mcp:scripts:')) {
|
||||
state.scripts.push(...parseResourceList(scope.slice('mcp:scripts:'.length)))
|
||||
} else if (scope.startsWith('mcp:flows:')) {
|
||||
state.flows.push(...parseResourceList(scope.slice('mcp:flows:'.length)))
|
||||
} else if (scope.startsWith('mcp:endpoints:')) {
|
||||
state.endpoints.push(...parseResourceList(scope.slice('mcp:endpoints:'.length)))
|
||||
}
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
function patterns(state: McpScopeState, resource: McpResourceKind): string[] {
|
||||
return resource === 'script' ? state.scripts : state.flows
|
||||
}
|
||||
|
||||
/** Whether the token grants access to any concrete path of this kind. */
|
||||
function hasAnyResource(state: McpScopeState, resource: McpResourceKind): boolean {
|
||||
return state.all || patterns(state, resource).length > 0
|
||||
}
|
||||
|
||||
/** Whether the token restricts this kind to specific paths. A `*` pattern grants
|
||||
* every path, so it is not a confinement. */
|
||||
function isPathConfined(state: McpScopeState, resource: McpResourceKind): boolean {
|
||||
if (state.all) return false
|
||||
const list = patterns(state, resource)
|
||||
return list.length > 0 && !list.includes('*')
|
||||
}
|
||||
|
||||
function matchesPattern(name: string, pattern: string): boolean {
|
||||
if (pattern === name) return true
|
||||
if (!pattern.endsWith('/*')) return false
|
||||
const prefix = pattern.slice(0, -2)
|
||||
if (!name.startsWith(prefix)) return false
|
||||
return name.length === prefix.length || name[prefix.length] === '/'
|
||||
}
|
||||
|
||||
/** Mirrors `is_resource_allowed`: whether a path (or endpoint name) is granted by
|
||||
* any of these patterns, where a pattern is `*`, an exact path, or `<prefix>/*`. */
|
||||
export function matchesAnyPattern(path: string, patterns: string[]): boolean {
|
||||
if (patterns.length === 0) return false
|
||||
if (patterns.includes('*')) return true
|
||||
return patterns.some((pattern) => matchesPattern(path, pattern))
|
||||
}
|
||||
|
||||
const nonGetEndpoints = new Set(
|
||||
mcpEndpointTools.filter((e) => e.method !== 'GET').map((e) => e.name)
|
||||
)
|
||||
|
||||
/** Strip from an `mcp:endpoints:` selection only the names that scope cannot
|
||||
* honor: run-by-path tools, which `isEndpointExposed` gates on the script/flow
|
||||
* scope instead, and — for a read-only token — the non-GET endpoints the server
|
||||
* refuses. Every other entry is preserved, notably a `*` wildcard, which is a
|
||||
* valid endpoint scope that dropping would silently revoke every endpoint tool. */
|
||||
export function pruneEndpointSelection(selected: string[], readOnly: boolean): string[] {
|
||||
return selected.filter(
|
||||
(name) =>
|
||||
endpointPathPolicy(name)?.kind !== 'runByPath' && !(readOnly && nonGetEndpoints.has(name))
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether the server will list this endpoint tool for a token with these scopes. */
|
||||
export function isEndpointExposed(state: McpScopeState, name: string): boolean {
|
||||
const granular = !state.all && !state.favorites
|
||||
const endpointAllowed = !granular || matchesAnyPattern(name, state.endpoints)
|
||||
const policy = endpointPathPolicy(name)
|
||||
switch (policy?.kind) {
|
||||
case 'runByPath':
|
||||
return hasAnyResource(state, policy.resource)
|
||||
case 'unconfinable':
|
||||
return endpointAllowed && !isPathConfined(state, policy.resource)
|
||||
default:
|
||||
return endpointAllowed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { canUpgradeMcpScopes } from './mcpUpgrade'
|
||||
|
||||
describe('canUpgradeMcpScopes', () => {
|
||||
it('takes an unmarked mcp:all token alone', () => {
|
||||
expect(canUpgradeMcpScopes(['mcp:all'])).toBe(true)
|
||||
expect(canUpgradeMcpScopes(['mcp:all', 'mcp:workspaces:a,b'])).toBe(true)
|
||||
expect(canUpgradeMcpScopes(['mcp:favorites'])).toBe(false)
|
||||
expect(canUpgradeMcpScopes(['mcp:all:f/x/*'])).toBe(false)
|
||||
expect(canUpgradeMcpScopes([])).toBe(false)
|
||||
})
|
||||
|
||||
it('leaves out a token that already gets the session toolset', () => {
|
||||
expect(canUpgradeMcpScopes(['mcp:all', 'mcp:session'])).toBe(false)
|
||||
expect(canUpgradeMcpScopes(['mcp:all', 'mcp:read_only'])).toBe(false)
|
||||
expect(canUpgradeMcpScopes(['mcp:all', 'mcp:read_run'])).toBe(false)
|
||||
})
|
||||
|
||||
it('leaves out a token the upgrade would take something from', () => {
|
||||
expect(canUpgradeMcpScopes(['mcp:all', 'mcp:hub:slack'])).toBe(false)
|
||||
expect(canUpgradeMcpScopes(['mcp:all', 'variables:read:u/a/*'])).toBe(false)
|
||||
expect(canUpgradeMcpScopes(['mcp:all', 'if_jobs:filter_tags:gpu'])).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { TruncatedToken } from '$lib/gen'
|
||||
import { MCP_SESSION, RUNNABLES_AS_TOOLS } from './McpAccessPicker.svelte'
|
||||
|
||||
const RECENT_MS = 30 * 24 * 60 * 60 * 1000
|
||||
|
||||
/** Scopes that already decide the toolset of an `mcp:all` token. */
|
||||
const DECIDED = [MCP_SESSION, RUNNABLES_AS_TOOLS, 'mcp:read_only', 'mcp:read_run']
|
||||
|
||||
/** Whether adding `mcp:session` moves this token from the endpoint tools to the session toolset
|
||||
* without losing anything else: the session toolset has no hub scripts as tools, and refuses a
|
||||
* token carrying a non-MCP scope (`admits` in backend/windmill-mcp/src/server/session.rs). */
|
||||
export function canUpgradeMcpScopes(scopes: string[]): boolean {
|
||||
return (
|
||||
scopes.includes('mcp:all') &&
|
||||
scopes.every(
|
||||
(s) =>
|
||||
(s.startsWith('mcp:') && !s.startsWith('mcp:hub:') && !DECIDED.includes(s)) ||
|
||||
s.startsWith('if_jobs:filter_tags:')
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/** Recently used tokens the upgrade applies to. */
|
||||
export function upgradableMcpTokens(tokens: TruncatedToken[], now = Date.now()): TruncatedToken[] {
|
||||
return tokens.filter(
|
||||
(t) =>
|
||||
canUpgradeMcpScopes(t.scopes ?? []) &&
|
||||
now - Date.parse(t.last_used_at) < RECENT_MS &&
|
||||
(!t.expiration || Date.parse(t.expiration) > now)
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
function matchesPattern(name: string, pattern: string): boolean {
|
||||
if (pattern === name) return true
|
||||
if (!pattern.endsWith('/*')) return false
|
||||
const prefix = pattern.slice(0, -2)
|
||||
if (!name.startsWith(prefix)) return false
|
||||
return name.length === prefix.length || name[prefix.length] === '/'
|
||||
}
|
||||
|
||||
/** Mirrors `is_resource_allowed` in backend/windmill-mcp/src/common/scope.rs: whether a path is
|
||||
* granted by any of these patterns, where a pattern is `*`, an exact path, or `<prefix>/*`. */
|
||||
export function matchesAnyPattern(path: string, patterns: string[]): boolean {
|
||||
if (patterns.length === 0) return false
|
||||
if (patterns.includes('*')) return true
|
||||
return patterns.some((pattern) => matchesPattern(path, pattern))
|
||||
}
|
||||
@@ -109,6 +109,8 @@ export function itemHref(kind: string, path: string): string | undefined {
|
||||
case 'app':
|
||||
case 'apps':
|
||||
return `/apps/get/${path}`
|
||||
case 'raw_app':
|
||||
return `/apps_raw/get/${path}`
|
||||
case 'resource':
|
||||
case 'resources':
|
||||
return `/resources#/resource/${path}`
|
||||
|
||||
@@ -221,6 +221,28 @@
|
||||
port.postMessage(payload)
|
||||
}
|
||||
|
||||
/** Fetches a bundle file for a sandboxed wrapper whose own request failed: from its
|
||||
* opaque origin it cannot send a proxy's cookie, this page can. Nonce-gated and sent
|
||||
* on the asker's port, as in `respondCtx`. The text enters the sandbox, so it must be
|
||||
* the bundle and not, say, the proxy's login page: no redirect, exact content type. */
|
||||
async function respondAsset(ext: unknown, nonceEcho: unknown, port?: MessagePort) {
|
||||
if (!port || nonceEcho !== handshakeNonce || (ext !== 'js' && ext !== 'css')) return
|
||||
let text: string | undefined = undefined
|
||||
try {
|
||||
const res = await fetch(`/api/w/${workspace}/apps_u/get_data/v/${secret}.${ext}`, {
|
||||
redirect: 'error'
|
||||
})
|
||||
const contentType = res.headers.get('content-type')?.split(';')[0].trim()
|
||||
if (!res.ok || contentType !== (ext === 'js' ? 'text/javascript' : 'text/css')) {
|
||||
throw new Error(`unexpected response: ${res.status} ${contentType}`)
|
||||
}
|
||||
text = await res.text()
|
||||
} catch (e) {
|
||||
console.error(`Could not load the raw app's ${ext} bundle`, e)
|
||||
}
|
||||
port.postMessage(text)
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
initialHash = pageHash()
|
||||
if (framed) {
|
||||
@@ -286,6 +308,8 @@
|
||||
pendingNonce = nonceEcho
|
||||
pendingPort = port
|
||||
}
|
||||
} else if (data?.type === 'windmill:asset') {
|
||||
respondAsset(data.ext, data.nonce, event.ports?.[0])
|
||||
} else if (data?.type === 'wm_ls_op') {
|
||||
// The bundle mutated localStorage — apply it to the shared store.
|
||||
if (!framed) {
|
||||
|
||||
@@ -753,12 +753,7 @@
|
||||
|
||||
{#if !scopes || scopes.length === 0}
|
||||
<div class="mt-4">
|
||||
<ScopesPicker
|
||||
mode="standard"
|
||||
workspaceId={scopeWorkspaceId}
|
||||
bind:value={pickedScopes}
|
||||
bind:readOnly
|
||||
/>
|
||||
<ScopesPicker workspaceId={scopeWorkspaceId} bind:value={pickedScopes} bind:readOnly />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
|
||||
@@ -255,12 +255,7 @@
|
||||
/>
|
||||
</div>
|
||||
{:else}
|
||||
<ScopesPicker
|
||||
mode="standard"
|
||||
workspaceId={mcpWorkspaceId}
|
||||
{initialScopes}
|
||||
bind:value={pickedScopes}
|
||||
/>
|
||||
<ScopesPicker workspaceId={mcpWorkspaceId} {initialScopes} bind:value={pickedScopes} />
|
||||
{/if}
|
||||
{/key}
|
||||
</div>
|
||||
|
||||
@@ -1,113 +1,70 @@
|
||||
<script lang="ts">
|
||||
import Toggle from '../Toggle.svelte'
|
||||
import ScopeSelector from './ScopeSelector.svelte'
|
||||
import McpScopeSelector from '../mcp/McpScopeSelector.svelte'
|
||||
|
||||
interface Props {
|
||||
mode: 'standard' | 'mcp'
|
||||
workspaceId?: string
|
||||
/** Existing scopes (used for both initial standard selection and parsing MCP scope) */
|
||||
/** Existing scopes, seeding the selection */
|
||||
initialScopes?: string[]
|
||||
/** Final scope value: null = unrestricted/full access, array = explicit list */
|
||||
value: string[] | null
|
||||
/** Read-only flag; also forwarded to McpScopeSelector to filter incompatible
|
||||
* endpoints/runnables. Two-way bound so the inline toggle below the
|
||||
* "Restrict to specific scopes" switch (and the MCP variant) writes back. */
|
||||
/** Read-only flag, two-way bound so the inline toggle below the
|
||||
* "Restrict to specific scopes" switch writes back. */
|
||||
readOnly?: boolean
|
||||
}
|
||||
|
||||
let {
|
||||
mode,
|
||||
workspaceId = '',
|
||||
initialScopes,
|
||||
value = $bindable(),
|
||||
readOnly = $bindable(false)
|
||||
}: Props = $props()
|
||||
|
||||
// In standard mode, only meaningful when the user has turned "Limit token
|
||||
// permissions" on. Reset when they un-limit so the flag doesn't quietly
|
||||
// stick if they re-enable later.
|
||||
// Only meaningful when the user has turned "Limit token permissions" on.
|
||||
// Reset when they un-limit so the flag doesn't quietly stick if they
|
||||
// re-enable later.
|
||||
$effect(() => {
|
||||
if (mode === 'standard' && !limited && readOnly) {
|
||||
if (!limited && readOnly) {
|
||||
readOnly = false
|
||||
}
|
||||
})
|
||||
|
||||
const initialMcpScope = $derived(
|
||||
(initialScopes ?? []).length > 0 ? (initialScopes ?? []).join(' ') : undefined
|
||||
)
|
||||
|
||||
// Standard-mode local state, seeded from initialScopes if any.
|
||||
let limited = $state((initialScopes ?? []).length > 0)
|
||||
let standardScopes = $state<string[]>([...(initialScopes ?? [])])
|
||||
|
||||
// MCP-mode local state. When no initial scope is provided we fall back
|
||||
// to `mcp:favorites` (matches the create-token default).
|
||||
let mcpScope = $state(initialMcpScope ?? 'mcp:favorites')
|
||||
|
||||
$effect(() => {
|
||||
if (mode === 'mcp') {
|
||||
const parts = mcpScope
|
||||
.split(' ')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.length > 0)
|
||||
value = parts.length > 0 ? parts : null
|
||||
} else {
|
||||
value = limited && standardScopes.length > 0 ? standardScopes : null
|
||||
}
|
||||
value = limited && standardScopes.length > 0 ? standardScopes : null
|
||||
})
|
||||
</script>
|
||||
|
||||
{#if mode === 'standard'}
|
||||
<div class="flex flex-col gap-2">
|
||||
<Toggle
|
||||
bind:checked={limited}
|
||||
options={{
|
||||
right: 'Restrict to specific scopes',
|
||||
rightTooltip:
|
||||
'When off, the token can call any endpoint its rights allow. Turn on to allow only the scopes you pick: this narrows what the token can do, never widens it.'
|
||||
}}
|
||||
size="xs"
|
||||
/>
|
||||
{#if limited && standardScopes.length === 0}
|
||||
<p class="text-2xs text-yellow-600 dark:text-yellow-400">
|
||||
Pick at least one scope: with none picked, the token is not restricted.
|
||||
</p>
|
||||
{/if}
|
||||
{#if limited}
|
||||
<ScopeSelector bind:selectedScopes={standardScopes} workspaceId={workspaceId || undefined}>
|
||||
{#snippet topSlot()}
|
||||
<Toggle
|
||||
bind:checked={readOnly}
|
||||
options={{
|
||||
right: 'Read-only',
|
||||
rightTooltip:
|
||||
'Restricts this token to GET/HEAD endpoints. Any mutating request (POST/PUT/PATCH/DELETE) or job-run action will be rejected with 403, regardless of the scopes selected below.'
|
||||
}}
|
||||
size="xs"
|
||||
/>
|
||||
{/snippet}
|
||||
</ScopeSelector>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="text-tertiary">
|
||||
<Toggle
|
||||
bind:checked={readOnly}
|
||||
options={{
|
||||
right: 'Read-only',
|
||||
rightTooltip:
|
||||
'Restricts this MCP URL to read-only endpoints. The LLM will only see read tools — script and flow runs will be hidden.'
|
||||
}}
|
||||
size="2xs"
|
||||
/>
|
||||
</div>
|
||||
<McpScopeSelector
|
||||
{workspaceId}
|
||||
bind:scope={mcpScope}
|
||||
initialScope={initialMcpScope}
|
||||
{readOnly}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="flex flex-col gap-2">
|
||||
<Toggle
|
||||
bind:checked={limited}
|
||||
options={{
|
||||
right: 'Restrict to specific scopes',
|
||||
rightTooltip:
|
||||
'When off, the token can call any endpoint its rights allow. Turn on to allow only the scopes you pick: this narrows what the token can do, never widens it.'
|
||||
}}
|
||||
size="xs"
|
||||
/>
|
||||
{#if limited && standardScopes.length === 0}
|
||||
<p class="text-2xs text-yellow-600 dark:text-yellow-400">
|
||||
Pick at least one scope: with none picked, the token is not restricted.
|
||||
</p>
|
||||
{/if}
|
||||
{#if limited}
|
||||
<ScopeSelector bind:selectedScopes={standardScopes} workspaceId={workspaceId || undefined}>
|
||||
{#snippet topSlot()}
|
||||
<Toggle
|
||||
bind:checked={readOnly}
|
||||
options={{
|
||||
right: 'Read-only',
|
||||
rightTooltip:
|
||||
'Restricts this token to GET/HEAD endpoints. Any mutating request (POST/PUT/PATCH/DELETE) or job-run action will be rejected with 403, regardless of the scopes selected below.'
|
||||
}}
|
||||
size="xs"
|
||||
/>
|
||||
{/snippet}
|
||||
</ScopeSelector>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
+17
-2
@@ -330,6 +330,21 @@ const cookieDomain = isolateDevAuth ? '' : 'localhost'
|
||||
// with it so that one worktree's login does not stand for another's session.
|
||||
const sessionHintCookie = isolateDevAuth ? `${authCookie}_hint` : 'wm_session'
|
||||
|
||||
// `changeOrigin` rewrites Host to the backend's, so pass on the host the browser addressed:
|
||||
// over plain http to a LAN or Tailscale address there is no Sec-Fetch-Site, and the backend's
|
||||
// cross-site check (request_site.rs) then matches Origin against the hosts it can see.
|
||||
function forwardHost(proxy) {
|
||||
proxy.on('proxyReq', (proxyReq, req) => {
|
||||
if (req.headers.host && !req.headers['x-forwarded-host'])
|
||||
proxyReq.setHeader('x-forwarded-host', req.headers.host)
|
||||
})
|
||||
}
|
||||
|
||||
function configureApiProxy(proxy) {
|
||||
forwardHost(proxy)
|
||||
isolateAuthCookie(proxy)
|
||||
}
|
||||
|
||||
function isolateAuthCookie(proxy) {
|
||||
if (!isolateDevAuth) return
|
||||
proxy.on('proxyReq', (proxyReq, req) => {
|
||||
@@ -454,7 +469,7 @@ const config = {
|
||||
target: remoteUrl,
|
||||
changeOrigin: true,
|
||||
cookieDomainRewrite: cookieDomain,
|
||||
configure: isolateAuthCookie
|
||||
configure: configureApiProxy
|
||||
},
|
||||
'^/api/w/[^/]+/s3_proxy/.*': {
|
||||
target: remoteUrl,
|
||||
@@ -474,7 +489,7 @@ const config = {
|
||||
target: remoteUrl,
|
||||
changeOrigin: true,
|
||||
cookieDomainRewrite: cookieDomain,
|
||||
configure: isolateAuthCookie
|
||||
configure: configureApiProxy
|
||||
},
|
||||
'^/ws/.*': {
|
||||
target: process.env.REMOTE_LSP ?? process.env.REMOTE_EXTRA ?? 'https://app.windmill.dev',
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ verify_ssl = true
|
||||
name = "pypi"
|
||||
|
||||
[packages]
|
||||
wmill = ">=1.894.1"
|
||||
wmill = ">=1.895.1"
|
||||
sendgrid = "*"
|
||||
mysql-connector-python = "*"
|
||||
pymongo = "*"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: '3.0.3'
|
||||
|
||||
info:
|
||||
version: 1.894.1
|
||||
version: 1.895.1
|
||||
title: OpenFlow Spec
|
||||
contact:
|
||||
name: Ruben Fiszel
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
RootModule = 'WindmillClient.psm1'
|
||||
|
||||
# Version number of this module.
|
||||
ModuleVersion = '1.894.1'
|
||||
ModuleVersion = '1.895.1'
|
||||
|
||||
# Supported PSEditions
|
||||
# CompatiblePSEditions = @()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "wmill"
|
||||
version = "1.894.1"
|
||||
version = "1.895.1"
|
||||
description = "A client library for accessing Windmill server wrapping the Windmill client API"
|
||||
license = "Apache-2.0"
|
||||
homepage = "https://windmill.dev"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@windmill/windmill",
|
||||
"version": "1.894.1",
|
||||
"version": "1.895.1",
|
||||
"exports": "./src/index.ts",
|
||||
"publish": {
|
||||
"exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts", "./taskParams.ts"]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "windmill-client",
|
||||
"description": "Windmill SDK client for browsers and Node.js",
|
||||
"version": "1.894.1",
|
||||
"version": "1.895.1",
|
||||
"author": "Ruben Fiszel",
|
||||
"license": "Apache 2.0",
|
||||
"homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme",
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
1.894.1
|
||||
1.895.1
|
||||
|
||||
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "windmill-yaml-validator",
|
||||
"version": "1.894.1",
|
||||
"version": "1.895.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "windmill-yaml-validator",
|
||||
"version": "1.894.1",
|
||||
"version": "1.895.1",
|
||||
"license": "Apache 2.0",
|
||||
"dependencies": {
|
||||
"@stoplight/yaml": "^4.3.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "windmill-yaml-validator",
|
||||
"version": "1.894.1",
|
||||
"version": "1.895.1",
|
||||
"description": "YAML validator for Windmill flow, schedule, and trigger files",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
||||
Reference in New Issue
Block a user