diff --git a/AGENTS.md b/AGENTS.md index f22ec56fe6..b3d13d1466 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/CONTEXT.md b/CONTEXT.md index f015fff0a4..054960607c 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -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) diff --git a/backend/.sqlx/query-096ee8a2f9a1cecf8c0f4302cc5f0c68b9ab2ed1998a4baa1114a78bfeada890.json b/backend/.sqlx/query-096ee8a2f9a1cecf8c0f4302cc5f0c68b9ab2ed1998a4baa1114a78bfeada890.json deleted file mode 100644 index d2941d9091..0000000000 --- a/backend/.sqlx/query-096ee8a2f9a1cecf8c0f4302cc5f0c68b9ab2ed1998a4baa1114a78bfeada890.json +++ /dev/null @@ -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" -} diff --git a/backend/.sqlx/query-424247c6ef5bb5739a5f6894aaefdf47ac6dcbfd110401e0a924302581f7e206.json b/backend/.sqlx/query-424247c6ef5bb5739a5f6894aaefdf47ac6dcbfd110401e0a924302581f7e206.json deleted file mode 100644 index e009911fd7..0000000000 --- a/backend/.sqlx/query-424247c6ef5bb5739a5f6894aaefdf47ac6dcbfd110401e0a924302581f7e206.json +++ /dev/null @@ -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" -} diff --git a/backend/.sqlx/query-47ff60ebf7524c590818a7f61874966fde6268fe108fdfa6ee6703e804b4e799.json b/backend/.sqlx/query-47ff60ebf7524c590818a7f61874966fde6268fe108fdfa6ee6703e804b4e799.json deleted file mode 100644 index 825e0ba270..0000000000 --- a/backend/.sqlx/query-47ff60ebf7524c590818a7f61874966fde6268fe108fdfa6ee6703e804b4e799.json +++ /dev/null @@ -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" -} diff --git a/backend/.sqlx/query-6f00489d74a831b482edf8eee6691a81041fef67f2c8cc5d8f95f99dd0eca317.json b/backend/.sqlx/query-6f00489d74a831b482edf8eee6691a81041fef67f2c8cc5d8f95f99dd0eca317.json deleted file mode 100644 index 5e0e2d9e9f..0000000000 --- a/backend/.sqlx/query-6f00489d74a831b482edf8eee6691a81041fef67f2c8cc5d8f95f99dd0eca317.json +++ /dev/null @@ -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" -} diff --git a/backend/.sqlx/query-fc4f0ff56a6de0cbb24695b38f120b511c31f776f015cf20e2eb450c94956a03.json b/backend/.sqlx/query-fc4f0ff56a6de0cbb24695b38f120b511c31f776f015cf20e2eb450c94956a03.json deleted file mode 100644 index 01fe80cba1..0000000000 --- a/backend/.sqlx/query-fc4f0ff56a6de0cbb24695b38f120b511c31f776f015cf20e2eb450c94956a03.json +++ /dev/null @@ -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" -} diff --git a/backend/Cargo.lock b/backend/Cargo.lock index b7b631f218..75c2466a93 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -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", diff --git a/backend/parsers/windmill-parser-py-asset/src/lib.rs b/backend/parsers/windmill-parser-py-asset/src/lib.rs index e6a56132f6..2919b74607 100644 --- a/backend/parsers/windmill-parser-py-asset/src/lib.rs +++ b/backend/parsers/windmill-parser-py-asset/src/lib.rs @@ -10,8 +10,6 @@ use windmill_parser::asset_parser::{ }; use AssetUsageAccessType::*; -mod references; - pub fn parse_assets(input: &str) -> anyhow::Result { 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 { } 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), - ] - ); - } } diff --git a/backend/parsers/windmill-parser-py-asset/src/references.rs b/backend/parsers/windmill-parser-py-asset/src/references.rs deleted file mode 100644 index 38cbbc9c24..0000000000 --- a/backend/parsers/windmill-parser-py-asset/src/references.rs +++ /dev/null @@ -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 { - 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, - found: BTreeSet, -} - -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; - } - } - } -} diff --git a/backend/parsers/windmill-parser-ts-asset/src/lib.rs b/backend/parsers/windmill-parser-ts-asset/src/lib.rs index cb9e62be5b..68b1287aa0 100644 --- a/backend/parsers/windmill-parser-ts-asset/src/lib.rs +++ b/backend/parsers/windmill-parser-ts-asset/src/lib.rs @@ -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 { - parse_assets_as(code, TsDialect::Ts) -} - -pub fn parse_assets_as(code: &str, dialect: TsDialect) -> anyhow::Result { let cm: Lrc = 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` 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 { - 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 = vec![]; - let mut markup = String::new(); - let mut at = 0; - while let Some(open) = lower[at..].find("').map(|i| open + i + 1) else { - at = open; - break; - }; - let close = lower[body..] - .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![ - (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({ rows }: { rows: T[] }) { - return
getVariable("f/app/tsx_secret")}>{rows.length}
- } - "#; - let svelte = r#" - - -

{#await wmill.getVariable('f/app/markup_secret') then v}{v}{/await}

-"#; - 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); - } } diff --git a/backend/parsers/windmill-parser-ts-asset/src/references.rs b/backend/parsers/windmill-parser-ts-asset/src/references.rs deleted file mode 100644 index bda67082be..0000000000 --- a/backend/parsers/windmill-parser-ts-asset/src/references.rs +++ /dev/null @@ -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 { - 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, - found: BTreeSet, -} - -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 { - 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 { - match (tpl.exprs.as_slice(), tpl.quasis.as_slice()) { - ([], [quasi]) => Some(quasi.cooked.as_ref().unwrap_or(&quasi.raw).to_string()), - _ => None, - } -} diff --git a/backend/parsers/windmill-parser-yaml/src/asset_parser.rs b/backend/parsers/windmill-parser-yaml/src/asset_parser.rs index e237d94f6c..4dde12ad8e 100644 --- a/backend/parsers/windmill-parser-yaml/src/asset_parser.rs +++ b/backend/parsers/windmill-parser-yaml/src/asset_parser.rs @@ -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 { 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 { } 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 { - 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, + )) } diff --git a/backend/parsers/windmill-parser/src/asset_parser.rs b/backend/parsers/windmill-parser/src/asset_parser.rs index 88e30100db..5a68b390ed 100644 --- a/backend/parsers/windmill-parser/src/asset_parser.rs +++ b/backend/parsers/windmill-parser/src/asset_parser.rs @@ -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, pub sql_queries: Vec, - // 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, // 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, diff --git a/backend/parsers/windmill-parser/src/item_reference.rs b/backend/parsers/windmill-parser/src/item_reference.rs deleted file mode 100644 index 1bd3dfdf41..0000000000 --- a/backend/parsers/windmill-parser/src/item_reference.rs +++ /dev/null @@ -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 { - 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 { - 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 { - 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 { - scan(expr, INPUT_TRANSFORM_CALLS) -} - -const COMMENT_STARTS: [&str; 6] = ["//", "#", "--", "/*", "*", " -
+
{#if action} - - {#if error} - {error} - {:else if !needs || !needed} - - {:else} - {#if runsAs} - - {kind === 'app' - ? 'Only what its frontend reads, as whoever opens it, is listed.' - : `What it reads needs no grant for ${principal}.`} - - {/if} - {#if needed.items.length} -
- {#each needed.items as item (item.kind + ':' + item.path)} - {@const key = `${item.kind}:${item.path}`} - {@const already = covered(item)} - {@const result = results[key]} - - {/each} -
- {:else} -

Nothing {principal} needs was found in {path}.

- {/if} - {#if needed.others.length} - - {needed.others.map((o) => `${o.kind} ${o.path}`).join(', ')}. Access to these is set on the - storage or data table itself. - - {/if} - {#if needs.errors.length} - - {needs.errors.join('; ')} - - {/if} -
- - - 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". - - -
- {/if} -
diff --git a/frontend/src/lib/components/access/GrantNavigator.svelte b/frontend/src/lib/components/access/GrantNavigator.svelte index bae5601a11..75899c09ab 100644 --- a/frontend/src/lib/components/access/GrantNavigator.svelte +++ b/frontend/src/lib/components/access/GrantNavigator.svelte @@ -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 - } {#snippet leafIcon(leaf: DrillLeaf)} @@ -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 - }} />
diff --git a/frontend/src/lib/components/access/detectNeeds.test.ts b/frontend/src/lib/components/access/detectNeeds.test.ts deleted file mode 100644 index 5aaa0a5733..0000000000 --- a/frontend/src/lib/components/access/detectNeeds.test.ts +++ /dev/null @@ -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' - ]) - }) -}) diff --git a/frontend/src/lib/components/access/detectNeeds.ts b/frontend/src/lib/components/access/detectNeeds.ts deleted file mode 100644 index ed8e30c383..0000000000 --- a/frontend/src/lib/components/access/detectNeeds.ts +++ /dev/null @@ -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 - -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 { - 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() - 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() - 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()] } -}