refactor: move what an item reads into its own pull request

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-11-11 03:17:19 -08:00
co-authored by Claude Opus 5.5
parent 373f02f0ce
commit 9b8eec16b7
33 changed files with 50 additions and 3413 deletions
-3
View File
@@ -47,9 +47,6 @@ Open-source platform for internal tools, workflows, API integrations, background
- **Workspace roles**: `docs/workspace-roles.md` — instance-defined roles with per-workspace
overrides, the capabilities a role holds, why `ApiAuthed::is_operator` must be derived from the
role, and the `role_seat` table billing reads
- **Access reads**: `docs/access-reads.md` — what `/access/reads` says an item reads and who
performs each read (its caller, its account, a step's own account, an app's viewer). The scan
mirrors who the runtime runs each piece as, so changing that changes `tag` in `access_reads.rs`.
- **Operator write rights**: `docs/operator-write-rights.md` — which `operator_settings` flags are
enforced rather than cosmetic, and why a right that is granted-unless-withdrawn needs `Option`
fields and a jsonb merge rather than a serde default
-7
View File
@@ -92,10 +92,3 @@ _Avoid_: permission level, access level, rank
Reserved for the path prefix that says where an item lives — `u/alice` or `f/team`. A folder's
`owners` column in the database is its admin members; call those admins, never owners, in the UI.
_Avoid_: using "owner" for a folder admin
**Reference**:
A workspace item that a script, flow or app names by path: a resource or variable it reads or
writes, or a script or flow its code starts. The access views turn references into grants. An
**asset** is the data the code touches, such as a data table or an object storage file, recorded
in `asset` rows; a resource can be both, but only a reference says what access the code needs.
_Avoid_: dependency (the packages in a lockfile), asset (for an item the code names)
@@ -1,92 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT path AS \"path!\", hash AS \"hash!\", language AS \"language!: ScriptLang\",\n content AS \"content!\", schema AS \"schema?\", modules AS \"modules?\",\n on_behalf_of AS \"on_behalf_of?\"\n FROM script\n WHERE workspace_id = $1 AND hash = ANY($2) AND deleted = false",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "path!",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "hash!",
"type_info": "Int8"
},
{
"ordinal": 2,
"name": "language!: ScriptLang",
"type_info": {
"Custom": {
"name": "script_lang",
"kind": {
"Enum": [
"python3",
"deno",
"go",
"bash",
"postgresql",
"nativets",
"bun",
"mysql",
"bigquery",
"snowflake",
"graphql",
"powershell",
"mssql",
"php",
"bunnative",
"rust",
"ansible",
"csharp",
"oracledb",
"nu",
"java",
"duckdb",
"ruby",
"rlang",
"dbt"
]
}
}
}
},
{
"ordinal": 3,
"name": "content!",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "schema?",
"type_info": "Json"
},
{
"ordinal": 5,
"name": "modules?",
"type_info": "Jsonb"
},
{
"ordinal": 6,
"name": "on_behalf_of?",
"type_info": "Varchar"
}
],
"parameters": {
"Left": [
"Text",
"Int8Array"
]
},
"nullable": [
false,
false,
false,
false,
true,
true,
true
]
},
"hash": "096ee8a2f9a1cecf8c0f4302cc5f0c68b9ab2ed1998a4baa1114a78bfeada890"
}
@@ -1,29 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT path AS \"path!\", value AS \"value?\"\n FROM resource\n WHERE workspace_id = $1 AND path = ANY($2)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "path!",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "value?",
"type_info": "Jsonb"
}
],
"parameters": {
"Left": [
"Text",
"TextArray"
]
},
"nullable": [
false,
true
]
},
"hash": "424247c6ef5bb5739a5f6894aaefdf47ac6dcbfd110401e0a924302581f7e206"
}
@@ -1,92 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT DISTINCT ON (path) path AS \"path!\", hash AS \"hash!\",\n language AS \"language!: ScriptLang\", content AS \"content!\",\n schema AS \"schema?\", modules AS \"modules?\", on_behalf_of AS \"on_behalf_of?\"\n FROM script\n WHERE workspace_id = $1 AND path = ANY($2) AND deleted = false\n ORDER BY path, (lock IS NOT NULL AND lock_error_logs IS NULL) DESC, created_at DESC",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "path!",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "hash!",
"type_info": "Int8"
},
{
"ordinal": 2,
"name": "language!: ScriptLang",
"type_info": {
"Custom": {
"name": "script_lang",
"kind": {
"Enum": [
"python3",
"deno",
"go",
"bash",
"postgresql",
"nativets",
"bun",
"mysql",
"bigquery",
"snowflake",
"graphql",
"powershell",
"mssql",
"php",
"bunnative",
"rust",
"ansible",
"csharp",
"oracledb",
"nu",
"java",
"duckdb",
"ruby",
"rlang",
"dbt"
]
}
}
}
},
{
"ordinal": 3,
"name": "content!",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "schema?",
"type_info": "Json"
},
{
"ordinal": 5,
"name": "modules?",
"type_info": "Jsonb"
},
{
"ordinal": 6,
"name": "on_behalf_of?",
"type_info": "Varchar"
}
],
"parameters": {
"Left": [
"Text",
"TextArray"
]
},
"nullable": [
false,
false,
false,
false,
true,
true,
true
]
},
"hash": "47ff60ebf7524c590818a7f61874966fde6268fe108fdfa6ee6703e804b4e799"
}
@@ -1,29 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT app.policy AS \"policy!\", app_version.value AS \"value!\"\n FROM app\n JOIN app_version ON app_version.id = app.versions[array_upper(app.versions, 1)]\n WHERE app.workspace_id = $1 AND app.path = $2",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "policy!",
"type_info": "Jsonb"
},
{
"ordinal": 1,
"name": "value!",
"type_info": "Json"
}
],
"parameters": {
"Left": [
"Text",
"Text"
]
},
"nullable": [
false,
false
]
},
"hash": "6f00489d74a831b482edf8eee6691a81041fef67f2c8cc5d8f95f99dd0eca317"
}
@@ -1,41 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT flow.path AS \"path!\", flow.on_behalf_of AS \"on_behalf_of?\",\n flow_version.value AS \"value?\", flow_version.schema AS \"schema?\"\n FROM flow\n LEFT JOIN flow_version\n ON flow_version.id = flow.versions[array_upper(flow.versions, 1)]\n WHERE flow.workspace_id = $1 AND flow.path = ANY($2)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "path!",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "on_behalf_of?",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "value?",
"type_info": "Jsonb"
},
{
"ordinal": 3,
"name": "schema?",
"type_info": "Json"
}
],
"parameters": {
"Left": [
"Text",
"TextArray"
]
},
"nullable": [
false,
true,
false,
true
]
},
"hash": "fc4f0ff56a6de0cbb24695b38f120b511c31f776f015cf20e2eb450c94956a03"
}
-2
View File
@@ -16069,11 +16069,9 @@ dependencies = [
"serde_json",
"sql-builder",
"sqlx",
"tokio",
"tracing",
"uuid",
"windmill-api-auth",
"windmill-api-scripts",
"windmill-api-workspaces",
"windmill-audit",
"windmill-common",
@@ -10,8 +10,6 @@ use windmill_parser::asset_parser::{
};
use AssetUsageAccessType::*;
mod references;
pub fn parse_assets(input: &str) -> anyhow::Result<ParseAssetsOutput> {
let ast = parse_module(input)
.map_err(|e| anyhow::anyhow!("Error parsing code: {}", e.to_string()))?
@@ -34,10 +32,11 @@ pub fn parse_assets(input: &str) -> anyhow::Result<ParseAssetsOutput> {
}
let pipeline = parse_pipeline_annotations(input);
let mut output =
ParseAssetsOutput::new(merge_assets(assets_finder.assets), Vec::new(), pipeline);
output.references = references::find_references(&ast);
Ok(output)
Ok(ParseAssetsOutput::new(
merge_assets(assets_finder.assets),
Vec::new(),
pipeline,
))
}
type VarAssetName = String;
@@ -895,36 +894,4 @@ def main():
])
);
}
#[test]
fn test_py_references_follow_renamed_imports_and_argument_positions() {
use windmill_parser::item_reference::{ItemKind::*, ItemReference, ReferenceAccess::*};
let input = r#"
import wmill
from wmill import get_variable as secret, task_script
def main():
# wmill.get_variable("u/admin/commented_out")
key = secret("f/ops/api_key")
wmill.set_resource("f/ops/state", {"a": 1})
wmill.Windmill().set_resource({"a": 1}, "f/ops/client_state")
wmill.load_s3_file("s3:///a.csv", s3_resource_path="f/ops/bucket")
wmill.run_script_async("8e5d6c4f1a2b3c4d")
wmill.run_flow_async(path="f/ops/sync")
task_script("f/ops/step")
"#;
let reference =
|kind, path: &str, access| ItemReference { kind, path: path.to_string(), access };
assert_eq!(
parse_assets(input).unwrap().references,
vec![
reference(Resource, "f/ops/bucket", Read),
reference(Resource, "f/ops/client_state", Write),
reference(Resource, "f/ops/state", Write),
reference(Variable, "f/ops/api_key", Read),
reference(Script, "f/ops/step", Task),
reference(Flow, "f/ops/sync", Run),
]
);
}
}
@@ -1,183 +0,0 @@
//! The workspace items Python code names through the Windmill SDK, read from the same AST as its
//! assets.
use std::collections::{BTreeSet, HashMap};
use ruff_python_ast::{
visitor::{walk_expr, walk_stmt, Visitor},
Expr, ExprCall, Stmt,
};
use windmill_parser::item_reference::{ItemKind, ItemReference, ReferenceAccess};
struct SdkCall {
name: &'static str,
kind: ItemKind,
access: ReferenceAccess,
/// The positions that can hold the path, tried in order. `set_resource` lists two: the
/// module function takes the path first, a `Windmill` client method second.
args: &'static [usize],
keywords: &'static [&'static str],
}
const fn call(
name: &'static str,
kind: ItemKind,
access: ReferenceAccess,
args: &'static [usize],
keywords: &'static [&'static str],
) -> SdkCall {
SdkCall { name, kind, access, args, keywords }
}
use ItemKind::*;
use ReferenceAccess::*;
const PATH: &[&str] = &["path"];
const S3_RESOURCE: &[&str] = &["s3_resource_path"];
/// The SDK functions (`wmill`) that take an item path, and where.
const SDK_CALLS: &[SdkCall] = &[
call("get_variable", Variable, Read, &[0], PATH),
call("set_variable", Variable, Write, &[0], PATH),
call("get_resource", Resource, Read, &[0], PATH),
call("set_resource", Resource, Write, &[0, 1], PATH),
call("load_s3_file", Resource, Read, &[1], S3_RESOURCE),
call("load_s3_file_reader", Resource, Read, &[1], S3_RESOURCE),
call("write_s3_file", Resource, Read, &[2], S3_RESOURCE),
call(
"duckdb_connection_settings",
Resource,
Read,
&[0],
S3_RESOURCE,
),
call(
"polars_connection_settings",
Resource,
Read,
&[0],
S3_RESOURCE,
),
call(
"boto3_connection_settings",
Resource,
Read,
&[0],
S3_RESOURCE,
),
call(
"get_duckdb_connection_settings",
Resource,
Read,
&[0],
S3_RESOURCE,
),
call(
"get_polars_connection_settings",
Resource,
Read,
&[0],
S3_RESOURCE,
),
call(
"get_boto3_connection_settings",
Resource,
Read,
&[0],
S3_RESOURCE,
),
call(
"request_interactive_slack_approval",
Resource,
Read,
&[0],
&["slack_resource_path"],
),
call("run_script", Script, Run, &[0], PATH),
call("run_script_by_path", Script, Run, &[0], PATH),
call(
"run_script_async",
Script,
Run,
&[0],
&["path", "hash_or_path"],
),
call("run_script_by_path_async", Script, Run, &[0], PATH),
call("run_script_by_path_sync", Script, Run, &[0], PATH),
call("run_flow_async", Flow, Run, &[0], PATH),
call("task_script", Script, Task, &[0], PATH),
call("task_flow", Flow, Task, &[0], PATH),
];
fn sdk_call(name: &str) -> Option<&'static SdkCall> {
SDK_CALLS.iter().find(|c| c.name == name)
}
pub(crate) fn find_references(suite: &[Stmt]) -> Vec<ItemReference> {
let mut finder = ReferencesFinder { renamed: HashMap::new(), found: BTreeSet::new() };
finder.visit_body(suite);
finder.found.into_iter().collect()
}
struct ReferencesFinder {
/// Local names bound by `from wmill import get_variable as gv`.
renamed: HashMap<String, &'static SdkCall>,
found: BTreeSet<ItemReference>,
}
impl<'a> Visitor<'a> for ReferencesFinder {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
if let Stmt::ImportFrom(node) = stmt {
for alias in &node.names {
if let (Some(local), Some(call)) = (&alias.asname, sdk_call(alias.name.as_str())) {
self.renamed.insert(local.to_string(), call);
}
}
}
walk_stmt(self, stmt);
}
fn visit_expr(&mut self, expr: &'a Expr) {
match expr {
Expr::Call(node) => self.record_call(node),
Expr::StringLiteral(s) => self
.found
.extend(ItemReference::of_prefixed(s.value.to_str())),
_ => {}
}
walk_expr(self, expr);
}
}
impl ReferencesFinder {
fn record_call(&mut self, node: &ExprCall) {
let name = node
.func
.as_name_expr()
.map(|n| n.id.as_str())
.or_else(|| node.func.as_attribute_expr().map(|a| a.attr.as_str()));
let Some(call) = name.and_then(|n| self.renamed.get(n).copied().or_else(|| sdk_call(n)))
else {
return;
};
let keyword = node.arguments.keywords.iter().find(|k| {
k.arg
.as_ref()
.is_some_and(|a| call.keywords.contains(&a.as_str()))
});
let candidates = call
.args
.iter()
.filter_map(|i| node.arguments.args.get(*i))
.chain(keyword.map(|k| &k.value));
for candidate in candidates {
let Expr::StringLiteral(s) = candidate else {
continue;
};
if let Some(r) = ItemReference::of(call.kind, call.access, s.value.to_str()) {
self.found.insert(r);
return;
}
}
}
}
@@ -8,28 +8,14 @@ use windmill_parser::asset_parser::{
asset_was_used, merge_assets, parse_asset_syntax, parse_pipeline_annotations, AssetKind,
AssetUsageAccessType, ParseAssetsOutput, ParseAssetsResult, SqlQueryDetails,
};
use windmill_parser::item_reference::{scan_sdk_calls, ItemReference};
use AssetUsageAccessType::*;
mod references;
#[derive(Clone, Copy, PartialEq)]
pub enum TsDialect {
Ts,
/// TypeScript with JSX, for `.tsx` and `.jsx` files.
Tsx,
}
pub fn parse_assets(code: &str) -> anyhow::Result<ParseAssetsOutput> {
parse_assets_as(code, TsDialect::Ts)
}
pub fn parse_assets_as(code: &str, dialect: TsDialect) -> anyhow::Result<ParseAssetsOutput> {
let cm: Lrc<SourceMap> = Default::default();
let fm = cm.new_source_file(FileName::Custom("main.ts".into()).into(), code.to_string());
let lexer = Lexer::new(
// We want to parse ecmascript
Syntax::Typescript(TsSyntax { tsx: dialect == TsDialect::Tsx, ..Default::default() }),
Syntax::Typescript(TsSyntax::default()),
// EsVersion defaults to es5
Default::default(),
StringInput::from(&*fm),
@@ -53,73 +39,11 @@ pub fn parse_assets_as(code: &str, dialect: TsDialect) -> anyhow::Result<ParseAs
AssetsFinder { assets: vec![], sql_queries: vec![], var_identifiers: HashMap::new() };
assets_finder.visit_module_items(&ast);
let pipeline = parse_pipeline_annotations(code);
let mut output = ParseAssetsOutput::new(
Ok(ParseAssetsOutput::new(
merge_assets(assets_finder.assets),
assets_finder.sql_queries,
pipeline,
);
output.references = references::find_references(&ast);
Ok(output)
}
/// What a full-code app's frontend file reads, by its extension: TypeScript and JavaScript are
/// parsed, a Svelte or Vue component has its `<script>` blocks parsed and its markup scanned,
/// and any other file is `None`. Code that fails to parse is scanned instead.
pub fn parse_app_file(file_name: &str, content: &str) -> Option<ParseAssetsOutput> {
let extension = file_name.rsplit_once('.')?.1.to_ascii_lowercase();
match extension.as_str() {
"ts" | "js" | "mjs" | "cjs" | "mts" | "cts" => Some(parse_or_scan(content, TsDialect::Ts)),
"tsx" | "jsx" => Some(parse_or_scan(content, TsDialect::Tsx)),
"svelte" | "vue" => Some(parse_component(content)),
_ => None,
}
}
/// An app file this large is a bundle, not source: its AST would cost memory in proportion,
/// and the lexical scan finds the same SDK calls.
const MAX_PARSED_FILE: usize = 1 << 20;
fn parse_or_scan(code: &str, dialect: TsDialect) -> ParseAssetsOutput {
let parsed = if code.len() > MAX_PARSED_FILE {
None
} else {
parse_assets_as(code, dialect).ok()
};
parsed.unwrap_or_else(|| ParseAssetsOutput {
references: scan_sdk_calls(code),
..Default::default()
})
}
fn parse_component(content: &str) -> ParseAssetsOutput {
let lower = content.to_ascii_lowercase();
let mut output = ParseAssetsOutput::default();
let mut references: Vec<ItemReference> = vec![];
let mut markup = String::new();
let mut at = 0;
while let Some(open) = lower[at..].find("<script").map(|i| at + i) {
markup.push_str(&content[at..open]);
let Some(body) = lower[open..].find('>').map(|i| open + i + 1) else {
at = open;
break;
};
let close = lower[body..]
.find("</script")
.map_or(content.len(), |i| body + i);
let block = parse_or_scan(&content[body..close], TsDialect::Ts);
output.assets.extend(block.assets);
references.extend(block.references);
at = lower[close..]
.find('>')
.map_or(content.len(), |i| close + i + 1);
}
markup.push_str(&content[at..]);
references.extend(scan_sdk_calls(&markup));
references.sort();
references.dedup();
output.assets = merge_assets(output.assets);
output.references = references;
output
))
}
type VarAssetName = String;
@@ -1144,87 +1068,4 @@ mod tests {
assert_eq!(result.assets.len(), 1);
assert_eq!(result.assets[0].path, "dt/friends");
}
use windmill_parser::item_reference::{ItemKind, ReferenceAccess};
fn reference(kind: ItemKind, path: &str, access: ReferenceAccess) -> ItemReference {
ItemReference { kind, path: path.to_string(), access }
}
#[test]
fn test_ts_references_follow_renamed_imports_and_argument_positions() {
use windmill_parser::item_reference::{ItemKind::*, ReferenceAccess::*};
let input = r#"
import * as wmill from "windmill-client"
import { getVariable as secret, taskScript } from "windmill-client"
export async function main(name: string) {
// wmill.getVariable("u/admin/commented_out")
const key = await secret(`f/ops/api_key`)
await wmill.setVariable("f/ops/counter", "1")
await wmill.setResource({ token: key }, "f/ops/state")
await wmill.getResource(`f/ops/${name}`)
await wmill.loadS3File({ s3: "a.csv" }, "f/ops/bucket")
await wmill.runScriptByPath("f/ops/cleanup", {})
await taskScript("f/ops/step")({})
return "$res:f/ops/db"
}
"#;
let output = parse_assets(input).unwrap();
assert_eq!(
output.references,
vec![
reference(Resource, "f/ops/bucket", Read),
reference(Resource, "f/ops/db", Read),
reference(Resource, "f/ops/state", Write),
reference(Variable, "f/ops/api_key", Read),
reference(Variable, "f/ops/counter", Write),
reference(Script, "f/ops/cleanup", Run),
reference(Script, "f/ops/step", Task),
]
);
assert_eq!(
output
.assets
.iter()
.map(|a| (a.kind, a.path.as_str(), a.access_type))
.collect::<Vec<_>>(),
vec![
(AssetKind::S3Object, "/a.csv", Some(R)),
(AssetKind::Resource, "f/ops/db", None),
(AssetKind::Resource, "f/ops/state", Some(W)),
]
);
}
#[test]
fn test_ts_app_files_by_extension() {
use windmill_parser::item_reference::{ItemKind::*, ReferenceAccess::*};
let tsx = r#"
import { getVariable } from "windmill-client"
export function App<T,>({ rows }: { rows: T[] }) {
return <div onClick={() => getVariable("f/app/tsx_secret")}>{rows.length}</div>
}
"#;
let svelte = r#"
<script lang="ts">
import * as wmill from "windmill-client"
let db = $state(wmill.getResource("f/app/script_db"))
</script>
<p>{#await wmill.getVariable('f/app/markup_secret') then v}{v}{/await}</p>
"#;
let refs = |name, content| parse_app_file(name, content).map(|o| o.references);
assert_eq!(
refs("/App.tsx", tsx),
Some(vec![reference(Variable, "f/app/tsx_secret", Read)])
);
assert_eq!(
refs("/App.svelte", svelte),
Some(vec![
reference(Resource, "f/app/script_db", Read),
reference(Variable, "f/app/markup_secret", Read),
])
);
assert_eq!(refs("/notes.md", "getVariable('f/app/not_code')"), None);
}
}
@@ -1,153 +0,0 @@
//! The workspace items TypeScript code names through the Windmill SDK, read from the same AST as
//! its assets.
use std::collections::{BTreeSet, HashMap};
use swc_ecma_ast::{
CallExpr, Expr, ImportDecl, ImportSpecifier, Lit, MemberExpr, MemberProp, ModuleExportName,
ModuleItem, Str, Tpl,
};
use swc_ecma_visit::{Visit, VisitWith};
use windmill_parser::item_reference::{ItemKind, ItemReference, ReferenceAccess};
use crate::object_str_prop;
enum Arg {
Index(usize),
/// A field of the object passed at this position.
Field(usize, &'static str),
}
struct SdkCall {
name: &'static str,
kind: ItemKind,
access: ReferenceAccess,
arg: Arg,
}
const fn call(name: &'static str, kind: ItemKind, access: ReferenceAccess, arg: Arg) -> SdkCall {
SdkCall { name, kind, access, arg }
}
use Arg::*;
use ItemKind::*;
use ReferenceAccess::*;
/// The SDK functions (`windmill-client`) that take an item path, and where.
const SDK_CALLS: &[SdkCall] = &[
call("getResource", Resource, Read, Index(0)),
call("setResource", Resource, Write, Index(1)),
call("getVariable", Variable, Read, Index(0)),
call("setVariable", Variable, Write, Index(0)),
call("databaseUrlFromResource", Resource, Read, Index(0)),
call("denoS3LightClientSettings", Resource, Read, Index(0)),
call("duckdbConnectionSettings", Resource, Read, Index(0)),
call("polarsConnectionSettings", Resource, Read, Index(0)),
call("loadS3File", Resource, Read, Index(1)),
call("loadS3FileStream", Resource, Read, Index(1)),
call("writeS3File", Resource, Read, Index(2)),
call(
"requestInteractiveSlackApproval",
Resource,
Read,
Field(0, "slackResourcePath"),
),
call("runScript", Script, Run, Index(0)),
call("runScriptAsync", Script, Run, Index(0)),
call("runScriptByPath", Script, Run, Index(0)),
call("runScriptByPathAsync", Script, Run, Index(0)),
call("runFlow", Flow, Run, Index(0)),
call("runFlowAsync", Flow, Run, Index(0)),
call("taskScript", Script, Task, Index(0)),
call("taskFlow", Flow, Task, Index(0)),
];
fn sdk_call(name: &str) -> Option<&'static SdkCall> {
SDK_CALLS.iter().find(|c| c.name == name)
}
pub(crate) fn find_references(module: &[ModuleItem]) -> Vec<ItemReference> {
let mut finder = ReferencesFinder { renamed: HashMap::new(), found: BTreeSet::new() };
finder.visit_module_items(module);
finder.found.into_iter().collect()
}
struct ReferencesFinder {
/// Local names bound by `import { getVariable as gv }`.
renamed: HashMap<String, &'static SdkCall>,
found: BTreeSet<ItemReference>,
}
impl Visit for ReferencesFinder {
fn visit_import_decl(&mut self, node: &ImportDecl) {
for specifier in &node.specifiers {
let ImportSpecifier::Named(named) = specifier else {
continue;
};
let imported = match &named.imported {
Some(ModuleExportName::Ident(i)) => i.sym.as_str(),
Some(ModuleExportName::Str(s)) => s.value.as_str(),
None => continue,
};
if let Some(call) = sdk_call(imported) {
self.renamed.insert(named.local.sym.to_string(), call);
}
}
}
fn visit_call_expr(&mut self, node: &CallExpr) {
let name = match node.callee.as_expr().map(AsRef::as_ref) {
Some(Expr::Ident(i)) => Some(i.sym.as_str()),
Some(Expr::Member(MemberExpr { prop: MemberProp::Ident(i), .. })) => {
Some(i.sym.as_str())
}
_ => None,
};
let call = name.and_then(|n| self.renamed.get(n).copied().or_else(|| sdk_call(n)));
if let Some(call) = call {
let (index, field) = match call.arg {
Index(i) => (i, None),
Field(i, name) => (i, Some(name)),
};
let literal = node
.args
.get(index)
.and_then(|a| match (a.expr.as_ref(), field) {
(Expr::Object(obj), Some(name)) => object_str_prop(obj, name),
(expr, None) => literal_value(expr),
_ => None,
});
if let Some(r) = literal.and_then(|l| ItemReference::of(call.kind, call.access, &l)) {
self.found.insert(r);
}
}
node.visit_children_with(self);
}
fn visit_str(&mut self, node: &Str) {
self.found.extend(ItemReference::of_prefixed(&node.value));
}
fn visit_tpl(&mut self, node: &Tpl) {
if let Some(value) = template_value(node) {
self.found.extend(ItemReference::of_prefixed(&value));
}
node.visit_children_with(self);
}
}
fn literal_value(expr: &Expr) -> Option<String> {
match expr {
Expr::Lit(Lit::Str(s)) => Some(s.value.to_string()),
Expr::Tpl(t) => template_value(t),
_ => None,
}
}
/// A template literal's text when it interpolates nothing.
fn template_value(tpl: &Tpl) -> Option<String> {
match (tpl.exprs.as_slice(), tpl.quasis.as_slice()) {
([], [quasi]) => Some(quasi.cooked.as_ref().unwrap_or(&quasi.raw).to_string()),
_ => None,
}
}
@@ -1,20 +1,13 @@
use std::collections::BTreeSet;
use windmill_parser::{
asset_parser::{
merge_assets, parse_pipeline_annotations, AssetKind, AssetUsageAccessType,
ParseAssetsOutput, ParseAssetsResult,
},
item_reference::{ItemKind, ItemReference, ReferenceAccess},
use windmill_parser::asset_parser::{
merge_assets, parse_pipeline_annotations, AssetKind, AssetUsageAccessType, ParseAssetsOutput,
ParseAssetsResult,
};
use crate::{parse_ansible_reqs, AnsibleRequirements, ResourceOrVariablePath};
use crate::{parse_ansible_reqs, ResourceOrVariablePath};
pub fn parse_assets(input: &str) -> anyhow::Result<ParseAssetsOutput> {
let mut assets = vec![];
let mut references = vec![];
if let (_, Some(ansible_reqs), _) = parse_ansible_reqs(input)? {
references = item_references(&ansible_reqs);
if let Some(delegate_to_git_repo_details) = ansible_reqs.delegate_to_git_repo {
assets.push(ParseAssetsResult {
kind: AssetKind::Resource,
@@ -48,37 +41,9 @@ pub fn parse_assets(input: &str) -> anyhow::Result<ParseAssetsOutput> {
}
let pipeline = parse_pipeline_annotations(input);
let mut output = ParseAssetsOutput::new(merge_assets(assets), Vec::new(), pipeline);
output.references = references;
Ok(output)
}
/// The resources and variables the Ansible executor reads with the job's identity.
fn item_references(reqs: &AnsibleRequirements) -> Vec<ItemReference> {
let resource = |p: &str| ItemReference::of(ItemKind::Resource, ReferenceAccess::Read, p);
let variable = |p: &str| ItemReference::of(ItemKind::Variable, ReferenceAccess::Read, p);
let mut found = BTreeSet::new();
found.extend(
reqs.delegate_to_git_repo
.iter()
.filter_map(|d| resource(&d.resource)),
);
found.extend(
reqs.inventories
.iter()
.filter_map(|i| i.pinned_resource.as_deref().and_then(resource)),
);
found.extend(
reqs.file_resources
.iter()
.filter_map(|f| match &f.resource_path {
ResourceOrVariablePath::Resource(p) => resource(p),
ResourceOrVariablePath::Variable(p) => variable(p),
}),
);
found.extend(reqs.vars.iter().filter_map(|(_, v)| variable(v)));
found.extend(reqs.resources.iter().filter_map(|(_, r)| resource(r)));
found.extend(reqs.vault_password.as_deref().and_then(variable));
found.extend(reqs.git_ssh_identity.iter().filter_map(|p| variable(p)));
found.into_iter().collect()
Ok(ParseAssetsOutput::new(
merge_assets(assets),
Vec::new(),
pipeline,
))
}
@@ -2,8 +2,6 @@ use serde::Serialize;
use std::borrow::Cow;
use std::collections::BTreeMap;
use crate::item_reference::ItemReference;
// Token recognized inside declared asset URIs that the runtime substitutes
// with the current partition value (e.g. `s3://lake/{partition}.parquet`
// becomes `s3://lake/2024-04-29.parquet` when materialized for that day).
@@ -23,7 +21,7 @@ pub enum AssetUsageAccessType {
use AssetUsageAccessType::*;
#[derive(Serialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Debug)]
#[derive(Serialize, PartialEq, Clone, Copy, Debug)]
#[serde(rename_all(serialize = "lowercase"))]
pub enum AssetKind {
S3Object,
@@ -64,11 +62,6 @@ pub struct SqlQueryDetails {
pub struct ParseAssetsOutput {
pub assets: Vec<ParseAssetsResult>,
pub sql_queries: Vec<SqlQueryDetails>,
// The workspace items the code names by path, which the access views turn into grants.
// Kept off `ParseAssetsResult` on purpose: `asset` rows store those, and a reference is not
// an asset.
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub references: Vec<ItemReference>,
// Bare `// pipeline` (or `#` / `--`) on its own line — opt-in marker
// that sets auto_kind='pipeline' and includes the script in its
// folder's pipeline. Pipeline membership is broader than
@@ -662,7 +655,6 @@ impl ParseAssetsOutput {
ParseAssetsOutput {
assets,
sql_queries,
references: Vec::new(),
in_pipeline: pipeline.in_pipeline,
triggers: pipeline.triggers,
partition: pipeline.partition,
@@ -1,427 +0,0 @@
//! Workspace items that code names by path, and what it does with each.
//!
//! Assets describe the data a script touches; references describe the items whoever runs the
//! code needs permission on: the resources and variables it reads or writes, and the scripts
//! and flows it starts.
use std::collections::BTreeSet;
use serde::Serialize;
#[derive(Serialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "lowercase")]
pub enum ItemKind {
Resource,
Variable,
Script,
Flow,
}
#[derive(Serialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "lowercase")]
pub enum ReferenceAccess {
Read,
Write,
/// Started through the run API, which reads the item as the caller.
Run,
/// Dispatched as a workflow-as-code task. The worker resolves it without the caller's
/// permissions, so it needs no grant, but it still runs as the target's identity.
Task,
}
#[derive(Serialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ItemReference {
pub kind: ItemKind,
pub path: String,
pub access: ReferenceAccess,
}
const PREFIXES: [(&str, ItemKind); 5] = [
("$res:", ItemKind::Resource),
("res://", ItemKind::Resource),
("$var:", ItemKind::Variable),
("$jsonvar:", ItemKind::Variable),
("var://", ItemKind::Variable),
];
impl ItemReference {
/// `literal` as a reference when it names an item: a bare path, or a resource or variable
/// path written with one of its prefixes.
pub fn of(kind: ItemKind, access: ReferenceAccess, literal: &str) -> Option<Self> {
let literal = literal.trim();
let path = PREFIXES
.iter()
.find(|(prefix, k)| *k == kind && literal.starts_with(prefix))
.map_or(literal, |(prefix, _)| &literal[prefix.len()..]);
let path = match kind {
// A resource named as an asset can carry `?table=…`: the item is what precedes it.
ItemKind::Resource => path.split('?').next().unwrap_or(path),
// The runtime parses a script or flow path with `RunnableRef::from_path`, which drops
// one leading `/`.
ItemKind::Script | ItemKind::Flow => path.strip_prefix('/').unwrap_or(path),
ItemKind::Variable => path,
};
is_item_path(path).then(|| ItemReference { kind, path: path.to_string(), access })
}
/// A literal that names a resource or variable by its prefix (`$res:…`, `var://…`), as a read.
pub fn of_prefixed(literal: &str) -> Option<Self> {
let (_, kind) = PREFIXES
.iter()
.find(|(prefix, _)| literal.starts_with(prefix))?;
Self::of(*kind, ReferenceAccess::Read, literal)
}
}
/// Mirrors the `proper_id` CHECK on item paths: `u/`, `f/` or `g/` followed by at least two
/// segments of letters, digits, `_` and `-`.
pub fn is_item_path(path: &str) -> bool {
let mut segments = path.split('/');
if !matches!(segments.next(), Some("u" | "f" | "g")) || path.chars().count() > 255 {
return false;
}
let mut count = 0;
for segment in segments {
if segment.is_empty()
|| !segment
.chars()
.all(|c| c.is_alphanumeric() || c == '_' || c == '-')
{
return false;
}
count += 1;
}
count >= 2
}
/// A call the lexical scan recognizes by name. `args` are the argument positions that can hold
/// the path, tried in order: an SDK whose argument order differs across languages lists both.
struct LexicalCall {
names: &'static [&'static str],
kind: ItemKind,
access: ReferenceAccess,
args: &'static [usize],
}
const SDK_CALLS: &[LexicalCall] = &[
LexicalCall {
names: &["getVariable", "get_variable", "GetVariable"],
kind: ItemKind::Variable,
access: ReferenceAccess::Read,
args: &[0],
},
LexicalCall {
names: &["setVariable", "set_variable", "SetVariable"],
kind: ItemKind::Variable,
access: ReferenceAccess::Write,
args: &[0],
},
LexicalCall {
names: &[
"getResource",
"get_resource",
"GetResource",
"databaseUrlFromResource",
"denoS3LightClientSettings",
"duckdbConnectionSettings",
"polarsConnectionSettings",
"duckdb_connection_settings",
"polars_connection_settings",
"boto3_connection_settings",
"get_duckdb_connection_settings",
"get_polars_connection_settings",
"get_boto3_connection_settings",
"request_interactive_slack_approval",
],
kind: ItemKind::Resource,
access: ReferenceAccess::Read,
args: &[0],
},
LexicalCall {
names: &["setResource", "set_resource", "SetResource"],
kind: ItemKind::Resource,
access: ReferenceAccess::Write,
args: &[0, 1],
},
LexicalCall {
names: &[
"loadS3File",
"loadS3FileStream",
"load_s3_file",
"load_s3_file_reader",
],
kind: ItemKind::Resource,
access: ReferenceAccess::Read,
args: &[1],
},
LexicalCall {
names: &["writeS3File", "write_s3_file"],
kind: ItemKind::Resource,
access: ReferenceAccess::Read,
args: &[2],
},
LexicalCall {
names: &[
"runScript",
"runScriptAsync",
"runScriptByPath",
"runScriptByPathAsync",
"run_script",
"run_script_async",
"run_script_by_path",
"run_script_by_path_async",
"run_script_by_path_sync",
],
kind: ItemKind::Script,
access: ReferenceAccess::Run,
args: &[0],
},
LexicalCall {
names: &["runFlow", "runFlowAsync", "run_flow", "run_flow_async"],
kind: ItemKind::Flow,
access: ReferenceAccess::Run,
args: &[0],
},
LexicalCall {
names: &["taskScript", "task_script"],
kind: ItemKind::Script,
access: ReferenceAccess::Task,
args: &[0],
},
LexicalCall {
names: &["taskFlow", "task_flow"],
kind: ItemKind::Flow,
access: ReferenceAccess::Task,
args: &[0],
},
];
const INPUT_TRANSFORM_CALLS: &[LexicalCall] = &[
LexicalCall {
names: &["variable"],
kind: ItemKind::Variable,
access: ReferenceAccess::Read,
args: &[0],
},
LexicalCall {
names: &["resource"],
kind: ItemKind::Resource,
access: ReferenceAccess::Read,
args: &[0],
},
];
/// References in code no AST parser reads: languages without one, component markup, and code
/// that fails to parse. Finds SDK calls whose path argument is a quoted literal, and quoted
/// `$res:`/`$var:` literals. Lines that start as a comment are skipped.
pub fn scan_sdk_calls(code: &str) -> Vec<ItemReference> {
scan(code, SDK_CALLS)
}
/// References in a flow input transform: its `variable('…')` and `resource('…')` calls, and
/// quoted `$res:`/`$var:` literals.
pub fn scan_input_transform(expr: &str) -> Vec<ItemReference> {
scan(expr, INPUT_TRANSFORM_CALLS)
}
const COMMENT_STARTS: [&str; 6] = ["//", "#", "--", "/*", "*", "<!--"];
/// How far past a call's name its arguments are looked for, which keeps the scan linear.
const MAX_CALL_SPAN: usize = 4096;
/// How long a quoted literal can be and still be read as a path.
const MAX_LITERAL: usize = 512;
fn scan(code: &str, calls: &[LexicalCall]) -> Vec<ItemReference> {
let bytes = code.as_bytes();
let mut found = BTreeSet::new();
let mut i = 0;
let mut line_start = true;
while i < bytes.len() {
if line_start {
line_start = false;
while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
i += 1;
}
if COMMENT_STARTS.iter().any(|c| code[i..].starts_with(c)) {
match code[i..].find('\n') {
Some(n) => {
i += n + 1;
line_start = true;
continue;
}
None => break,
}
}
continue;
}
let b = bytes[i];
if b == b'\n' {
line_start = true;
i += 1;
} else if is_quote(b) {
if let Some((literal, _)) = read_literal(code, i) {
found.extend(ItemReference::of_prefixed(literal));
}
i += 1;
} else if is_ident_start(b) && (i == 0 || !is_ident_char(bytes[i - 1])) {
let start = i;
while i < bytes.len() && is_ident_char(bytes[i]) {
i += 1;
}
let name = &code[start..i];
if let Some(call) = calls.iter().find(|c| c.names.contains(&name)) {
found.extend(read_call(code, i, call));
}
} else {
i += 1;
}
}
found.into_iter().collect()
}
/// The reference a call names, reading its arguments from just after its name.
fn read_call(code: &str, from: usize, call: &LexicalCall) -> Option<ItemReference> {
let bytes = code.as_bytes();
let limit = (from + MAX_CALL_SPAN).min(bytes.len());
let mut i = skip_blank(bytes, from, limit);
if bytes.get(i) != Some(&b'(') {
return None;
}
i += 1;
let last = *call.args.iter().max()?;
for arg in 0..=last {
i = skip_blank(bytes, i, limit);
if i >= limit {
return None;
}
let literal = if is_quote(bytes[i]) {
read_literal(code, i)
} else {
None
};
i = match literal {
Some((value, end)) => {
let next = skip_blank(bytes, end, limit);
let whole = matches!(bytes.get(next), Some(b',' | b')'));
if whole && call.args.contains(&arg) {
if let Some(r) = ItemReference::of(call.kind, call.access, value) {
return Some(r);
}
}
next
}
None => skip_argument(bytes, i, limit),
};
if bytes.get(i) != Some(&b',') {
return None;
}
i += 1;
}
None
}
/// A quoted literal starting at `at`, refused when it holds an escape, a line break or an
/// interpolation, since its text is then not the value the code uses.
fn read_literal(code: &str, at: usize) -> Option<(&str, usize)> {
let bytes = code.as_bytes();
let quote = bytes[at];
let start = at + 1;
let end = start
+ bytes[start..(start + MAX_LITERAL).min(bytes.len())]
.iter()
.position(|b| *b == quote)?;
let value = &code[start..end];
let refused =
value.contains('\\') || value.contains('\n') || (quote == b'`' && value.contains("${"));
(!refused).then_some((value, end + 1))
}
/// The position of the `,` or `)` that ends the argument starting at `from`.
fn skip_argument(bytes: &[u8], from: usize, limit: usize) -> usize {
let mut depth = 0usize;
let mut i = from;
while i < limit {
match bytes[i] {
b'(' | b'[' | b'{' => depth += 1,
b')' | b']' | b'}' if depth == 0 => return i,
b')' | b']' | b'}' => depth -= 1,
b',' if depth == 0 => return i,
q if is_quote(q) => {
i += 1;
while i < limit && bytes[i] != q {
if bytes[i] == b'\\' {
i += 1;
}
i += 1;
}
}
_ => {}
}
i += 1;
}
limit
}
fn skip_blank(bytes: &[u8], mut i: usize, limit: usize) -> usize {
while i < limit && bytes[i].is_ascii_whitespace() {
i += 1;
}
i
}
fn is_quote(b: u8) -> bool {
matches!(b, b'"' | b'\'' | b'`')
}
fn is_ident_start(b: u8) -> bool {
b.is_ascii_alphabetic() || b == b'_' || b == b'$'
}
fn is_ident_char(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_' || b == b'$'
}
#[cfg(test)]
mod tests {
use super::*;
use ItemKind::*;
use ReferenceAccess::*;
fn r(kind: ItemKind, path: &str, access: ReferenceAccess) -> ItemReference {
ItemReference { kind, path: path.to_string(), access }
}
#[test]
fn lexical_scan_reads_only_whole_literal_arguments() {
let code = r#"
package inner
// wmill.GetVariable("u/admin/commented_out")
func main() {
token, _ := wmill.GetVariable("f/ops/token")
wmill.SetResource(map[string]any{"a": 1}, "f/ops/state")
wmill.GetVariable(`f/ops/${name}`)
wmill.GetResource("f/ops/" + name)
run_script_by_path('f/ops/cleanup', args)
other := "$res:f/ops/db"
}
"#;
assert_eq!(
scan_sdk_calls(code),
vec![
r(Resource, "f/ops/db", Read),
r(Resource, "f/ops/state", Write),
r(Variable, "f/ops/token", Read),
r(Script, "f/ops/cleanup", Run),
]
);
}
#[test]
fn a_script_or_flow_path_may_start_with_one_slash() {
assert_eq!(
ItemReference::of(Script, Task, "/f/ops/cleanup"),
Some(r(Script, "f/ops/cleanup", Task))
);
assert_eq!(ItemReference::of(Flow, Run, "//f/ops/nightly"), None);
}
}
@@ -15,7 +15,6 @@ use serde_json::Value;
pub mod asset_parser;
pub mod duckdb_builtins;
pub mod duckdb_macros;
pub mod item_reference;
pub mod json_schema;
pub mod sql_materialize;
-125
View File
@@ -4,7 +4,6 @@
//! 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 serde_json::json;
use sqlx::{Pool, Postgres};
use windmill_test_utils::*;
@@ -124,127 +123,3 @@ async fn test_browse_items_kind_and_blocked(db: Pool<Postgres>) -> anyhow::Resul
Ok(())
}
async fn reads(port: u16, body: serde_json::Value) -> anyhow::Result<(u16, serde_json::Value)> {
let resp = reqwest::Client::new()
.post(format!(
"http://localhost:{port}/api/w/test-workspace/access/reads"
))
.header("Authorization", "Bearer READS_TOKEN")
.json(&body)
.send()
.await?;
let status = resp.status().as_u16();
let text = resp.text().await?;
Ok((
status,
serde_json::from_str(&text).unwrap_or(serde_json::Value::String(text)),
))
}
/// A step runs as its target's own account when it has one, and only what the caller can read
/// is followed.
#[sqlx::test(fixtures("base", "access_reads"))]
async fn test_access_reads_flow(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let port = server.addr.port();
let root = json!({"type": "root"});
let bot = json!({"type": "account", "principal": "u/test-user"});
let (status, flow) = reads(port, json!({"kind": "flow", "path": "u/test-user-2/flow"})).await?;
assert_eq!(status, 200, "{flow}");
assert_eq!(
flow,
json!({
"runs_as": {"type": "caller"},
"references": [
// A path step's static input is resolved by the step's own job.
{"kind": "resource", "path": "u/test-user-2/bot_input", "access": "read",
"reader": bot, "sources": ["u/test-user-2/flow › Bot"]},
{"kind": "variable", "path": "u/test-user-2/bot_token", "access": "read",
"reader": bot, "sources": ["u/test-user-2/bot"]},
{"kind": "variable", "path": "u/test-user-2/expr_var", "access": "read",
"reader": root, "sources": ["u/test-user-2/flow › Inline"]},
{"kind": "variable", "path": "u/test-user-2/linked", "access": "read",
"reader": bot, "sources": ["u/test-user-2/bot_input"]},
// The pinned version's read, not the latest version's.
{"kind": "variable", "path": "u/test-user-2/old_var", "access": "read",
"reader": root, "sources": ["u/test-user-2/versioned"]},
{"kind": "variable", "path": "u/test-user-2/state", "access": "write",
"reader": root, "sources": ["u/test-user-2/flow › Inline"]},
{"kind": "script", "path": "u/test-user-2/bot", "access": "run",
"reader": root, "sources": ["u/test-user-2/flow › Inline"]},
],
"others": [],
"errors": ["u/test-user/private: not found or not readable"],
})
);
// Unsaved content stands in for the saved item, including where it names its own path.
let (status, draft) = reads(
port,
json!({
"kind": "script",
"path": "u/test-user-2/versioned",
"source": {"language": "bun", "content": "import * as wmill from 'windmill-client'
await wmill.getVariable('u/test-user-2/draft_var')
await wmill.runScriptByPath('u/test-user-2/versioned')"},
}),
)
.await?;
assert_eq!(status, 200, "{draft}");
assert_eq!(
draft["references"],
json!([
{"kind": "variable", "path": "u/test-user-2/draft_var", "access": "read",
"reader": root, "sources": ["u/test-user-2/versioned"]},
{"kind": "script", "path": "u/test-user-2/versioned", "access": "run",
"reader": root, "sources": ["u/test-user-2/versioned"]},
])
);
let (status, private) = reads(
port,
json!({"kind": "script", "path": "u/test-user/private"}),
)
.await?;
assert_eq!(status, 404, "{private}");
Ok(())
}
/// A full-code app's frontend reads as whoever opens it, and its runnables read as the app
/// whatever account the script they call runs as.
#[sqlx::test(fixtures("base", "access_reads"))]
async fn test_access_reads_app(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let root = json!({"type": "root"});
let viewer = json!({"type": "viewer"});
let (status, app) = reads(
server.addr.port(),
json!({"kind": "app", "path": "u/test-user-2/app"}),
)
.await?;
assert_eq!(status, 200, "{app}");
assert_eq!(
app,
json!({
"runs_as": {"type": "account", "principal": "u/test-user"},
"references": [
{"kind": "variable", "path": "u/test-user-2/bot_token", "access": "read",
"reader": root, "sources": ["u/test-user-2/bot"]},
{"kind": "variable", "path": "u/test-user-2/runnable_var", "access": "read",
"reader": root, "sources": ["u/test-user-2/app › a"]},
{"kind": "variable", "path": "u/test-user-2/svelte_var", "access": "read",
"reader": viewer, "sources": ["u/test-user-2/app › /Widget.svelte"]},
{"kind": "variable", "path": "u/test-user-2/tsx_var", "access": "read",
"reader": viewer, "sources": ["u/test-user-2/app › /index.tsx"]},
],
"others": [],
"errors": [],
})
);
Ok(())
}
-60
View File
@@ -1,60 +0,0 @@
-- Items `/access/reads` follows as test-user-2: its own, one private to test-user, and a script
-- that runs as test-user.
INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin) VALUES
(encode(sha256('READS_TOKEN'::bytea), 'hex'), 'READS_TOKE', 'READS_TOKEN', 'test2@windmill.dev',
'reads', false);
INSERT INTO script (workspace_id, hash, path, content, language, created_by, created_at, schema,
summary, description, lock, archived, on_behalf_of) VALUES
('test-workspace', 1, 'u/test-user-2/versioned',
'import * as wmill from "windmill-client"
export async function main() { return await wmill.getVariable("u/test-user-2/old_var") }',
'bun', 'test-user-2', now() - interval '1 day', '{}', '', '', '', true, NULL),
('test-workspace', 2, 'u/test-user-2/versioned',
'import * as wmill from "windmill-client"
export async function main() { return await wmill.getVariable("u/test-user-2/new_var") }',
'bun', 'test-user-2', now(), '{}', '', '', '', false, NULL),
('test-workspace', 3, 'u/test-user-2/bot',
'import * as wmill from "windmill-client"
export async function main(input: object) { return await wmill.getVariable("u/test-user-2/bot_token") }',
'bun', 'test-user-2', now(), '{}', '', '', '', false, 'u/test-user'),
('test-workspace', 4, 'u/test-user/private', 'export async function main() {}',
'bun', 'test-user', now(), '{}', '', '', '', false, NULL);
INSERT INTO resource (workspace_id, path, value, resource_type, extra_perms, created_by) VALUES
('test-workspace', 'u/test-user-2/bot_input', '{"password": "$var:u/test-user-2/linked"}',
'object', '{}', 'test-user-2');
INSERT INTO flow (workspace_id, path, summary, description, value, edited_by, edited_at, schema,
extra_perms, versions) VALUES
('test-workspace', 'u/test-user-2/flow', '', '', '{}', 'test-user-2', now(), '{}', '{}', '{10}');
INSERT INTO flow_version (id, workspace_id, path, value, schema, created_by) VALUES
(10, 'test-workspace', 'u/test-user-2/flow', '{"modules": [
{"id": "a", "summary": "Pinned", "value": {"type": "script", "path": "u/test-user-2/versioned",
"hash": "0000000000000001", "input_transforms": {}}},
{"id": "b", "summary": "Inline", "value": {"type": "rawscript", "language": "bun",
"content": "import * as wmill from \"windmill-client\"\nexport async function main() {\n await wmill.setVariable(\"u/test-user-2/state\", \"x\")\n await wmill.runScriptByPath(\"u/test-user-2/bot\", {})\n}",
"input_transforms": {"token": {"type": "javascript", "expr": "variable(''u/test-user-2/expr_var'')"}}}},
{"id": "c", "summary": "Bot", "value": {"type": "script", "path": "u/test-user-2/bot",
"input_transforms": {"input": {"type": "static", "value": "$res:u/test-user-2/bot_input"}}}},
{"id": "d", "value": {"type": "script", "path": "u/test-user/private", "input_transforms": {}}}
]}', '{}', 'test-user-2');
INSERT INTO app (id, workspace_id, path, summary, policy, versions, extra_perms) VALUES
(20, 'test-workspace', 'u/test-user-2/app', '',
'{"execution_mode": "publisher", "on_behalf_of": "u/test-user"}', '{20}', '{}');
INSERT INTO app_version (id, app_id, value, created_by, raw_app) VALUES
(20, 20, '{
"runnables": {
"a": {"name": "a", "type": "inline", "inlineScript": {"language": "bun",
"content": "import * as wmill from \"windmill-client\"\nexport async function main() { return await wmill.getVariable(\"u/test-user-2/runnable_var\") }"}},
"b": {"name": "b", "type": "runnableByPath", "runType": "script", "path": "u/test-user-2/bot"}
},
"files": {
"/index.tsx": "import * as wmill from \"windmill-client\"\nexport default function App() { wmill.getVariable(\"u/test-user-2/tsx_var\"); return <div /> }",
"/Widget.svelte": "<script lang=\"ts\">import { getVariable } from \"windmill-client\"; const v = getVariable(\"u/test-user-2/svelte_var\")</script>\n<p>{v}</p>",
"/notes.md": "Call getVariable(\"u/test-user-2/md_var\") to read it."
}
}', 'test-user-2', true);
-2
View File
@@ -18,7 +18,6 @@ private = ["windmill-common/private", "windmill-api-workspaces/private"]
[dependencies]
windmill-common = { workspace = true, default-features = false }
windmill-api-auth.workspace = true
windmill-api-scripts.workspace = true
windmill-api-workspaces.workspace = true
windmill-audit.workspace = true
windmill-git-sync.workspace = true
@@ -32,6 +31,5 @@ serde.workspace = true
serde_json.workspace = true
sql-builder.workspace = true
sqlx.workspace = true
tokio.workspace = true
tracing.workspace = true
uuid.workspace = true
+2 -7
View File
@@ -9,8 +9,8 @@
//! What a workspace member or group can reach, and why.
use axum::{
extract::{DefaultBodyLimit, Extension, Path, Query},
routing::{get, post},
extract::{Extension, Path, Query},
routing::get,
Json, Router,
};
use serde::{Deserialize, Serialize};
@@ -28,11 +28,6 @@ pub fn workspaced_service() -> Router {
.route("/get", get(get_access))
.route("/browse_folders", get(browse_folders))
.route("/browse_items", get(browse_items))
// The body can carry a full-code app's files.
.route(
"/reads",
post(crate::access_reads::get_reads).layer(DefaultBodyLimit::max(16 << 20)),
)
}
const BROWSE_PAGE: i64 = 100;
File diff suppressed because it is too large Load Diff
-1
View File
@@ -1,5 +1,4 @@
pub mod access;
mod access_reads;
pub mod folder_history;
pub mod folders;
pub mod granular_acls;
@@ -19,7 +19,6 @@
use std::collections::BTreeMap;
use crate::body_parse::parse_body;
use windmill_common::{
assets::{
asset_access_type_from_parser, asset_kind_from_parser, AssetKind, AssetUsageAccessType,
@@ -35,34 +34,34 @@ fn parse_assets_for_lang(
lang: &ScriptLang,
content: &str,
) -> Option<Vec<windmill_parser::asset_parser::ParseAssetsResult>> {
// dbt is left out because its assets are not a function of the script
// content: they come from `manifest.json`, which needs a clone of the
// project's repo and a dbt invocation. The deploy-time dependency job
// does that parse and writes the `asset` rows itself
// (`dbt_executor::dbt_dep`), so returning None here is what keeps this
// path from clobbering them with an empty list.
let has_parser = match lang {
ScriptLang::DuckDb
| ScriptLang::Bun
| ScriptLang::Deno
| ScriptLang::Nativets
| ScriptLang::Ansible => true,
let parsed = match lang {
ScriptLang::DuckDb => windmill_parser_sql_asset::parse_assets(content),
ScriptLang::Bun | ScriptLang::Deno | ScriptLang::Nativets => {
windmill_parser_ts_asset::parse_assets(content)
}
#[cfg(feature = "python")]
ScriptLang::Python3 => true,
_ => false,
ScriptLang::Python3 => windmill_parser_py_asset::parse_assets(content),
ScriptLang::Ansible => windmill_parser_yaml::parse_assets(content),
// dbt is the one language whose assets are not a function of the script
// content: they come from `manifest.json`, which needs a clone of the
// project's repo and a dbt invocation. The deploy-time dependency job
// does that parse and writes the `asset` rows itself
// (`dbt_executor::dbt_dep`), so returning None here is what keeps this
// path from clobbering them with an empty list.
ScriptLang::Dbt => return None,
_ => return None,
};
if !has_parser {
return None;
match parsed {
Ok(out) => Some(out.assets),
Err(e) => {
tracing::warn!(
"server-side asset inference failed for a {} script; falling back to \
client-supplied assets: {e:#}",
lang.as_str()
);
None
}
}
let body = parse_body(lang, content);
if let Some(e) = body.error {
tracing::warn!(
"server-side asset inference failed for a {} script; falling back to \
client-supplied assets: {e:#}",
lang.as_str()
);
}
body.parsed.then_some(body.output.assets)
}
/// Mirror of the frontend `getCommentPrefix` (infer.ts) — the languages whose
@@ -1,66 +0,0 @@
/*
* Author: Ruben Fiszel
* Copyright: Windmill Labs, Inc 2026
* This file and its contents are licensed under the AGPLv3 License.
* Please see the included NOTICE for copyright information and
* LICENSE-AGPL for a copy of the license.
*/
//! One parse of a script body, for its assets and for the workspace items it references.
use windmill_common::scripts::ScriptLang;
use windmill_parser::{
asset_parser::ParseAssetsOutput,
item_reference::{scan_sdk_calls, ItemKind, ItemReference, ReferenceAccess},
};
pub use windmill_parser::{asset_parser, item_reference};
pub use windmill_parser_ts_asset::parse_app_file;
pub struct ParsedBody {
/// The body's assets and references. When no AST parser read it, only the references the
/// lexical scan found.
pub output: ParseAssetsOutput,
/// Whether an AST parser read the body.
pub parsed: bool,
/// Why the AST parser failed, when it did.
pub error: Option<anyhow::Error>,
}
impl ParsedBody {
fn scanned(references: Vec<ItemReference>, error: Option<anyhow::Error>) -> Self {
ParsedBody {
output: ParseAssetsOutput { references, ..Default::default() },
parsed: false,
error,
}
}
}
pub fn parse_body(lang: &ScriptLang, content: &str) -> ParsedBody {
let parsed = match lang {
ScriptLang::DuckDb => windmill_parser_sql_asset::parse_assets(content),
ScriptLang::Bun | ScriptLang::Bunnative | ScriptLang::Deno | ScriptLang::Nativets => {
windmill_parser_ts_asset::parse_assets(content)
}
#[cfg(feature = "python")]
ScriptLang::Python3 => windmill_parser_py_asset::parse_assets(content),
ScriptLang::Ansible => windmill_parser_yaml::parse_assets(content),
// Their executors read the resource on the `-- database` line with the job's identity.
ScriptLang::Postgresql
| ScriptLang::Mysql
| ScriptLang::Bigquery
| ScriptLang::Snowflake
| ScriptLang::Mssql
| ScriptLang::OracleDB => {
let database = windmill_parser_sql::parse_db_resource(content)
.and_then(|p| ItemReference::of(ItemKind::Resource, ReferenceAccess::Read, &p));
return ParsedBody::scanned(database.into_iter().collect(), None);
}
_ => return ParsedBody::scanned(scan_sdk_calls(content), None),
};
match parsed {
Ok(output) => ParsedBody { output, parsed: true, error: None },
Err(e) => ParsedBody::scanned(scan_sdk_calls(content), Some(e)),
}
}
-1
View File
@@ -7,5 +7,4 @@
*/
pub mod asset_inference;
pub mod body_parse;
pub mod scripts;
-143
View File
@@ -25500,31 +25500,6 @@ paths:
type: boolean
required: [items, has_more]
/w/{workspace}/access/reads:
post:
summary: list what an item reads when it runs, and who performs each read
description: >-
Reads only what the caller can read: anything else is listed under `errors`, with the
same line whether it is missing or hidden.
operationId: getAccessReads
tags:
- granular_acl
parameters:
- $ref: "#/components/parameters/WorkspaceId"
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/AccessReadsRequest"
responses:
"200":
description: what the item reads, each read with who performs it
content:
application/json:
schema:
$ref: "#/components/schemas/AccessReads"
/w/{workspace}/acls/get/{kind}/{path}:
get:
summary: get granular acls
@@ -37677,124 +37652,6 @@ components:
type: boolean
required: [type]
AccessReadsRequest:
type: object
properties:
kind:
type: string
enum: [script, flow, app]
path:
description: the saved item to scan or, with `source`, the path that labels it
type: string
source:
$ref: "#/components/schemas/AccessReadsSource"
required: [kind]
AccessReadsSource:
description: unsaved editor content, scanned in place of the saved item
type: object
properties:
language:
description: a script's language
type: string
content:
description: a script's code, required for a script
type: string
modules:
description: a script's other files, by name
value:
description: a flow's or an app's value, required for those
schema:
description: a script's or a flow's input schema
on_behalf_of:
description: the account a script or flow runs as, when it has one
type: string
policy:
description: an app's policy, which says who its runnables run as
AccessReads:
type: object
properties:
runs_as:
$ref: "#/components/schemas/AccessRunsAs"
references:
type: array
items:
$ref: "#/components/schemas/AccessReference"
others:
description: assets that are not workspace items, such as data tables and object storage files
type: array
items:
$ref: "#/components/schemas/AccessOtherAsset"
errors:
description: what could not be followed, one line each
type: array
items:
type: string
required: [runs_as, references, others, errors]
AccessRunsAs:
description: who the scanned item runs as
type: object
properties:
type:
type: string
enum: [caller, account]
principal:
description: the account, for `account`; missing for an app whose policy names none
type: string
required: [type]
AccessReader:
description: >-
who performs a read: `viewer` is whoever opens the app, `root` whoever the scanned item
runs as, and `account` the fixed identity of a runnable the item reaches
type: object
properties:
type:
type: string
enum: [viewer, root, account]
principal:
description: the account, for `account`
type: string
required: [type]
AccessReference:
type: object
properties:
kind:
type: string
enum: [resource, variable, script, flow]
path:
type: string
access:
description: "`run` is a script or flow started through the run API, which takes read on it"
type: string
enum: [read, write, run]
reader:
$ref: "#/components/schemas/AccessReader"
sources:
description: the parts of the item that make the read, as `<path> › <step or file>`
type: array
items:
type: string
required: [kind, path, access, reader, sources]
AccessOtherAsset:
type: object
properties:
kind:
$ref: "#/components/schemas/AssetKind"
path:
type: string
reader:
$ref: "#/components/schemas/AccessReader"
sources:
type: array
items:
type: string
required: [kind, path, reader, sources]
Group:
type: object
properties:
-56
View File
@@ -1,56 +0,0 @@
# What an item reads, and who reads it
`POST /w/{workspace}/access/reads` (`backend/windmill-api-groups/src/access_reads.rs`) returns
what a script, flow or app reads when it runs, with each read credited to the identity the
runtime performs it as. Two features take a slice of that answer
(`frontend/src/lib/components/access/detectNeeds.ts`):
- The access view's "What it reads" (`neededByGrantee`) lists what a member needs to run the
item: what whoever opens it reads, the item's own reads when it runs as its caller or as that
member, and the reads of a nested runnable that runs as that member.
- The run-as settings (`neededByRunAs`) list what an account needs when the item runs as it: the
item's own reads and the reads of a nested runnable that runs as that account.
## Who performs each read
The scan mirrors the runtime. A change to who a step, a runnable or a task runs as must change
`tag` in `access_reads.rs` too.
| Code that reads | Reads as |
|---|---|
| A script or flow with no `on_behalf_of` | whoever starts it |
| A script or flow with `on_behalf_of` | that account |
| A flow's inline step, and the JavaScript of its input transforms (`variable('…')`) | the flow's runner |
| A static `$res:`/`$var:` argument | the job that receives it: the flow's runner for an inline step, the step's own runner for a path step |
| A flow step calling a script or flow by path | the target's `on_behalf_of` if set, else the flow's runner; the step needs no read on its target |
| A workflow-as-code `taskScript`/`taskFlow`, an AI agent's tool | like a flow step |
| An AI agent's MCP server and its linked `agent` resource | the agent step's job |
| An SDK `runScriptByPath`/`runFlow` call | the calling job, which needs read on the target; the target then runs as its own `on_behalf_of` if set |
| An app runnable in `publisher`, `guest` or `anonymous` mode, inline or by path | the policy's `on_behalf_of`; a called script's own `on_behalf_of` is dropped |
| An app runnable in `viewer` mode | whoever opens the app |
| A full-code app's frontend files (`value.files`) | whoever opens the app, in every mode |
| A `$res:`/`$var:` link inside a resource's value | whoever reads the resource |
An app in `publisher`, `guest` or `anonymous` mode whose policy has no `on_behalf_of` fails every
run until it is redeployed. The response's `runs_as` then has no principal, and `errors` says so.
## How it reads
- Every item is fetched under the caller's RLS and token scopes, in `user_db` transactions, so
the answer never shows more than the caller can open. The handler takes no `DB`, which keeps a
plain-pool read from being added by accident. An item that is missing and one the caller cannot
read give the same error line.
- A script called by path is read at the version a run starts: its newest version with a lock,
else its newest. A step pinned to a hash reads that hash.
- Code is parsed by the parsers the deploy-time asset inference uses
(`windmill-api-scripts/src/body_parse.rs`), which return the item references beside the assets.
A language with no parser, and code that fails to parse, is scanned lexically for literal SDK
calls.
- A resource asset's access type describes the data behind the resource, and reaching that data
takes read on the resource either way. A write comes only from `setResource`/`setVariable`.
- Assets that are not workspace items, such as data tables and object storage files, are listed
under `others`: item grants do not cover them.
- Not found: a path built while the item runs, passed through a helper, or read in a module the
item imports.
- Limits: 4 levels of steps, SDK runs and agents (resource links add none), 500 items, and 1 MiB
of code parsed per file; past that, code is scanned lexically.
@@ -16,10 +16,8 @@
import { logFeatureUsage } from '$lib/utils/featureUsage'
import { pluralize, type Item } from '$lib/utils'
import { itemHref } from './offboarding-utils'
import AddNeededAccess from './access/AddNeededAccess.svelte'
import GrantNavigator, { navigatorMaxHeight } from './access/GrantNavigator.svelte'
import { KIND_LABELS, setGrant, type GrantLevel } from './access/access'
import type { RunnableKind } from './access/detectNeeds'
import {
buildAccessTree,
flattenAccessTree,
@@ -63,7 +61,6 @@
let openMenu: string | undefined = $state()
let grantPopover: Popover | undefined = $state()
let grantAnchor: HTMLElement | undefined = $state()
let needsOf: { kind: RunnableKind; path: string } | undefined = $state()
// Responses are not ordered: a slow answer for the previous principal must not land on this one.
let requestId = 0
@@ -77,7 +74,6 @@
openState = {}
expandAll = undefined
grantOpen = false
needsOf = undefined
drawer?.openDrawer()
logFeatureUsage('access_view', 'opened', { key: target })
await reload()
@@ -122,11 +118,6 @@
})
}
function findReads(kind: RunnableKind, path: string) {
grantOpen = false
needsOf = { kind, path }
}
/** 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) =>
@@ -162,7 +153,6 @@
]
}
const held = $derived(new Map((access?.items ?? []).map((i) => [`${i.kind}:${i.path}`, i.write])))
// 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])))
@@ -374,30 +364,13 @@
{/snippet}
{#snippet content()}
{#if access}
<GrantNavigator
{principal}
{access}
onGranted={reload}
onFindReads={findReads}
/>
<GrantNavigator {principal} {access} onGranted={reload} />
{/if}
{/snippet}
</Popover>
</div>
{/snippet}
<div class="flex flex-col gap-2">
{#if needsOf}
{#key `${needsOf.kind}:${needsOf.path}`}
<AddNeededAccess
{principal}
kind={needsOf.kind}
path={needsOf.path}
{held}
onGranted={reload}
onClose={() => (needsOf = undefined)}
/>
{/key}
{/if}
<div class="flex gap-2 items-center">
<TextInput
bind:value={search}
@@ -594,7 +594,7 @@ leaves and ignores the current scope.
{#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 min-w-[4.5rem] grid justify-items-end items-center pl-2">
<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
@@ -604,7 +604,7 @@ leaves and ignores the current scope.
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 whitespace-nowrap invisible opacity-0 transition-[opacity,visibility] duration-150 group-hover:visible group-hover:opacity-100"
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"
@@ -1,204 +0,0 @@
<script lang="ts">
import { Alert, Button, Skeleton } from '$lib/components/common'
import Checkbox from '$lib/components/common/checkbox/Checkbox.svelte'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import { Info, X } from 'lucide-svelte'
import { setGrant } from './access'
import {
detectNeeds,
neededByGrantee,
type NeededItem,
type Needs,
type RunnableKind
} from './detectNeeds'
const operatingWorkspace = useOperatingWorkspace()
let {
principal,
kind,
path,
held,
onGranted,
onClose
}: {
principal: string
kind: RunnableKind
path: string
/** `kind:path` of every item the principal reaches through any grant, to whether it can write it. */
held: Map<string, boolean>
onGranted: () => void
onClose: () => void
} = $props()
const KIND_LABELS: Record<NeededItem['kind'], string> = {
resource: 'Resource',
variable: 'Variable',
script: 'Script',
flow: 'Flow'
}
let needs: Needs | undefined = $state()
let error: string | undefined = $state()
let selected: Record<string, boolean> = $state({})
/** Rows the last Grant sent: true once granted, the refusal's text when refused. */
let results: Record<string, true | string> = $state({})
let granting = $state(false)
const needed = $derived(needs && neededByGrantee(needs, principal))
/** The account the item's own reads are made as, when it is not the principal. */
const runsAs = $derived(
needs?.runs_as.type === 'account' && needs.runs_as.principal !== principal
? needs.runs_as.principal
: undefined
)
function covered(item: NeededItem): boolean {
const write = held.get(`${item.kind}:${item.path}`)
return write !== undefined && (write || item.level === 'read')
}
function status(item: NeededItem): string {
if (covered(item)) return 'Already has it'
if (held.get(`${item.kind}:${item.path}`) === false) return 'Has read, needs write'
return item.level === 'write' ? 'Write' : 'Read'
}
// The host keys this component on the runnable, so it detects once per runnable.
detectNeeds($operatingWorkspace!, kind, path)
.then((found) => {
needs = found
selected = Object.fromEntries(
neededByGrantee(found, principal).items.map((i) => [`${i.kind}:${i.path}`, !covered(i)])
)
})
.catch((e) => (error = `${e?.body ?? e}`))
async function grant() {
if (!needed) return
granting = true
for (const item of needed.items) {
const key = `${item.kind}:${item.path}`
// A row covered since the scan, from the navigator or the table, is not sent: a grant
// replaces the principal's entry, so sending it at `item.level` can lower a write to read.
if (!selected[key] || covered(item)) continue
try {
await setGrant($operatingWorkspace!, item.kind, item.path, principal, item.level)
results[key] = true
selected[key] = false
} catch (e) {
results[key] = `${e?.body ?? e}`
}
}
granting = false
onGranted()
}
const selectedCount = $derived(
needed?.items.filter((i) => selected[`${i.kind}:${i.path}`] && !covered(i)).length ?? 0
)
</script>
<div class="flex flex-col gap-3 rounded-md border p-3">
<div class="flex items-start justify-between gap-2">
<div class="flex flex-col gap-0.5 min-w-0">
<span class="text-xs font-semibold text-emphasis truncate">What {path} reads</span>
<span class="text-2xs text-secondary">
What {principal} needs to run it: the resources and variables it reads, and the scripts and flows
its code starts. A step that calls a script or flow by path needs no grant on it.
</span>
</div>
<Button
variant="subtle"
unifiedSize="xs"
iconOnly
startIcon={{ icon: X }}
title="Dismiss"
onClick={onClose}
/>
</div>
{#if error}
<Alert type="error" size="xs" title="Could not read {path}">{error}</Alert>
{:else if !needs || !needed}
<Skeleton layout={[[2], 0.5, [2]]} />
{:else}
{#if runsAs}
<Alert
type="info"
size="xs"
title={kind === 'app' ? `Its runnables run as ${runsAs}` : `Runs as ${runsAs}`}
>
{kind === 'app'
? 'Only what its frontend reads, as whoever opens it, is listed.'
: `What it reads needs no grant for ${principal}.`}
</Alert>
{/if}
{#if needed.items.length}
<div class="flex flex-col divide-y border rounded-md">
{#each needed.items as item (item.kind + ':' + item.path)}
{@const key = `${item.kind}:${item.path}`}
{@const already = covered(item)}
{@const result = results[key]}
<label class="flex items-start gap-2 px-3 py-1.5 text-xs">
<Checkbox
class="mt-0.5"
checked={selected[key] && !already}
disabled={already || granting}
onChange={() => (selected[key] = !selected[key])}
/>
<span class="flex flex-col grow min-w-0">
<span class="font-mono text-2xs text-emphasis truncate">{item.path}</span>
<span class="text-2xs text-secondary truncate">
{KIND_LABELS[item.kind]}, used by {item.sources.join(', ')}
</span>
{#if typeof result === 'string'}
<span class="text-2xs text-red-500">{result}</span>
{/if}
</span>
<span
class="text-2xs shrink-0 {typeof result === 'string'
? 'text-red-500'
: 'text-secondary'}"
>
{result === true
? 'Granted'
: typeof result === 'string'
? 'Not granted'
: status(item)}
</span>
</label>
{/each}
</div>
{:else}
<p class="text-xs text-secondary">Nothing {principal} needs was found in {path}.</p>
{/if}
{#if needed.others.length}
<Alert type="info" size="xs" title="Also used, not granted here">
{needed.others.map((o) => `${o.kind} ${o.path}`).join(', ')}. Access to these is set on the
storage or data table itself.
</Alert>
{/if}
{#if needs.errors.length}
<Alert type="warning" size="xs" title="Some of it could not be read">
{needs.errors.join('; ')}
</Alert>
{/if}
<div class="flex items-center justify-between gap-2">
<span class="flex items-center gap-1 text-2xs text-secondary">
<Info size={12} class="shrink-0" />
Finds paths written literally in its code and inputs. A path built while it runs, passed through
a helper, or read in a script it imports isn't found: grant it with "Grant".
</span>
<Button
variant="accent"
unifiedSize="sm"
disabled={selectedCount === 0}
loading={granting}
onClick={grant}
>
Grant access to {selectedCount}
</Button>
</div>
{/if}
</div>
@@ -27,9 +27,8 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w
} from '$lib/components/operatingWorkspace.svelte'
import { sendUserToast } from '$lib/toast'
import { debounce } from '$lib/utils'
import { Folder, ScanSearch, User, Users } from 'lucide-svelte'
import { Folder, User, Users } from 'lucide-svelte'
import { setGrant } from './access'
import type { RunnableKind } from './detectNeeds'
const operatingWorkspace = useOperatingWorkspace()
const operatingUser = useOperatingUser()
@@ -41,13 +40,11 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w
let {
principal,
access,
onGranted,
onFindReads
onGranted
}: {
principal: string
access: PrincipalAccess
onGranted: () => void
onFindReads: (kind: RunnableKind, path: string) => void
} = $props()
const own = $derived(`u/${operatingUser.current?.username}`)
@@ -242,12 +239,6 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w
? `${already} through f/${folder}: picking it adds a direct grant, which stays even if f/${folder} is no longer shared`
: `${already}: picking it adds a direct grant, which stays even if that access is removed`
}
/** The kind detectNeeds reads it as: a full-code app is read like any app. */
function runnableKind(kind: string): RunnableKind | undefined {
if (kind === 'raw_app') return 'app'
return kind === 'flow' || kind === 'script' || kind === 'app' ? kind : undefined
}
</script>
{#snippet leafIcon(leaf: DrillLeaf<Leaf>)}
@@ -269,16 +260,5 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w
? undefined
: { label: write ? 'Writes' : 'Reads', color: write ? 'blue' : 'gray' }
}}
leafAction={(leaf) => {
const kind = runnableKind(leaf.data.kind)
return kind
? {
icon: ScanSearch,
label: 'What it reads',
title: `Grant what ${leaf.data.path} reads when it runs`,
run: () => onFindReads(kind, leaf.data.path)
}
: undefined
}}
/>
</div>
@@ -1,66 +0,0 @@
import { describe, expect, it } from 'vitest'
import { neededByGrantee, neededByRunAs, type NeededAccess, type Needs } from './detectNeeds'
const root = { type: 'root' } as const
const account = (principal: string) => ({ type: 'account', principal }) as const
function needs(runs_as: Needs['runs_as']): Needs {
return {
runs_as,
references: [
{
kind: 'variable',
path: 'f/x/front',
access: 'read',
reader: { type: 'viewer' },
sources: ['f/x/app › /App.tsx']
},
{ kind: 'resource', path: 'f/x/db', access: 'read', reader: root, sources: ['f/x/app › a'] },
{ kind: 'resource', path: 'f/x/db', access: 'write', reader: root, sources: ['f/x/app › b'] },
{ kind: 'script', path: 'f/x/helper', access: 'run', reader: root, sources: ['f/x/app › a'] },
{
kind: 'variable',
path: 'f/x/bot_token',
access: 'read',
reader: account('u/bot'),
sources: ['f/x/bot']
}
],
others: [{ kind: 'datatable', path: 'main', reader: root, sources: ['f/x/app › a'] }],
errors: []
}
}
const rows = (access: NeededAccess) => access.items.map((i) => `${i.kind}:${i.path}:${i.level}`)
describe('neededByGrantee', () => {
it('lists what the item reads when it runs as whoever starts it', () => {
const access = neededByGrantee(needs({ type: 'caller' }), 'u/alice')
expect(rows(access)).toEqual([
'variable:f/x/front:read',
'resource:f/x/db:write',
'script:f/x/helper:read'
])
expect(access.items[1].sources).toEqual(['f/x/app › a', 'f/x/app › b'])
expect(access.others.map((o) => o.path)).toEqual(['main'])
})
it('leaves out what an account reads unless the grantee is that account', () => {
const owned = needs(account('u/owner'))
expect(rows(neededByGrantee(owned, 'u/alice'))).toEqual(['variable:f/x/front:read'])
expect(rows(neededByGrantee(owned, 'u/bot'))).toEqual([
'variable:f/x/front:read',
'variable:f/x/bot_token:read'
])
})
})
describe('neededByRunAs', () => {
it('lists what the account reads, not what whoever opens the app reads', () => {
expect(rows(neededByRunAs(needs(account('u/bot')), 'u/bot'))).toEqual([
'resource:f/x/db:write',
'script:f/x/helper:read',
'variable:f/x/bot_token:read'
])
})
})
@@ -1,108 +0,0 @@
import {
GranularAclService,
type AccessOtherAsset,
type AccessReader,
type AccessReads,
type AccessReadsSource,
type AccessReference
} from '$lib/gen'
export type RunnableKind = 'script' | 'flow' | 'app'
/** What an item reads when it runs, each read with who performs it. */
export type Needs = AccessReads
/** Unsaved editor content, scanned in place of the saved item. */
export type NeedsSource = AccessReadsSource & { kind?: RunnableKind }
/** Something access is granted on item by item, at the level its reads take. */
export type NeededItem = {
kind: AccessReference['kind']
path: string
level: 'read' | 'write'
sources: string[]
}
/** Something it reads that item grants do not cover (S3 objects, data tables, …). */
export type OtherAsset = Omit<AccessOtherAsset, 'reader'>
export type NeededAccess = { items: NeededItem[]; others: OtherAsset[] }
/**
* What a script, flow or app reads when it runs, and who performs each read: the server scans
* the item and everything it calls (`docs/access-reads.md`). `source` stands in for the saved
* item, as unsaved editor content.
*/
export async function detectNeeds(
workspace: string,
kind: RunnableKind,
path: string,
source?: NeedsSource
): Promise<Needs> {
return await GranularAclService.getAccessReads({
workspace,
requestBody: { kind, path: path || undefined, source }
})
}
/**
* What `principal` needs to run the item: what whoever opens it reads, what the item reads when
* it runs as its caller or as `principal`, and what a runnable it reaches reads as `principal`.
*/
export function neededByGrantee(needs: Needs, principal: string): NeededAccess {
const runsAsGrantee = needs.runs_as.type === 'caller' || needs.runs_as.principal === principal
return select(
needs,
(reader) =>
reader.type === 'viewer' ||
(reader.type === 'root' && runsAsGrantee) ||
(reader.type === 'account' && reader.principal === principal)
)
}
/**
* What `account` needs when the item runs as it: what the item reads, and what a runnable it
* reaches reads as `account`. A full-code app's frontend reads as whoever opens it, so none of
* that is listed.
*/
export function neededByRunAs(needs: Needs, account?: string): NeededAccess {
return select(
needs,
(reader) =>
reader.type === 'root' ||
(account !== undefined && reader.type === 'account' && reader.principal === account)
)
}
/** One row per item: a write is needed when any read writes, and running an item takes read. */
function select(needs: Needs, performs: (reader: AccessReader) => boolean): NeededAccess {
const items = new Map<string, NeededItem>()
for (const reference of needs.references) {
if (!performs(reference.reader)) continue
const key = `${reference.kind}:${reference.path}`
const level = reference.access === 'write' ? 'write' : 'read'
const item = items.get(key)
if (item) {
if (level === 'write') item.level = 'write'
item.sources = [...new Set([...item.sources, ...reference.sources])]
} else {
items.set(key, {
kind: reference.kind,
path: reference.path,
level,
sources: reference.sources
})
}
}
const others = new Map<string, OtherAsset>()
for (const { reader, ...asset } of needs.others) {
if (!performs(reader)) continue
const key = `${asset.kind}:${asset.path}`
const other = others.get(key)
others.set(
key,
other ? { ...other, sources: [...new Set([...other.sources, ...asset.sources])] } : asset
)
}
return { items: [...items.values()], others: [...others.values()] }
}