diff --git a/backend/.sqlx/query-75d1618e12c4dfe5e9632ba8dc45b5aeb572e51ebd0732e6ebf80197acb3e577.json b/backend/.sqlx/query-75d1618e12c4dfe5e9632ba8dc45b5aeb572e51ebd0732e6ebf80197acb3e577.json deleted file mode 100644 index 817a13cb2f..0000000000 --- a/backend/.sqlx/query-75d1618e12c4dfe5e9632ba8dc45b5aeb572e51ebd0732e6ebf80197acb3e577.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT EXISTS (\n SELECT 1 FROM v2_job_completed c JOIN v2_job j USING (id)\n WHERE j.workspace_id = $2\n AND c.started_at > now() - interval '3 hours'\n AND c.result @> ('{\"s3\":\"' || $1 || '\"}')::jsonb\n AND j.trigger_kind = 'app'\n AND j.trigger = $3\n AND j.created_by = $4\n )", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "exists", - "type_info": "Bool" - } - ], - "parameters": { - "Left": [ - "Text", - "Text", - "Text", - "Text" - ] - }, - "nullable": [ - null - ] - }, - "hash": "75d1618e12c4dfe5e9632ba8dc45b5aeb572e51ebd0732e6ebf80197acb3e577" -} diff --git a/backend/.sqlx/query-b051ae8494073bc988dd272b2264520f36048ab3d12fe47652a854a41ddce1b0.json b/backend/.sqlx/query-b051ae8494073bc988dd272b2264520f36048ab3d12fe47652a854a41ddce1b0.json new file mode 100644 index 0000000000..7b16e81af2 --- /dev/null +++ b/backend/.sqlx/query-b051ae8494073bc988dd272b2264520f36048ab3d12fe47652a854a41ddce1b0.json @@ -0,0 +1,26 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (\n SELECT 1 FROM v2_job_completed c JOIN v2_job j USING (id)\n WHERE j.workspace_id = $2\n AND c.started_at > now() - interval '3 hours'\n AND j.trigger_kind = 'app'\n AND j.trigger = $3\n AND j.created_by = $4\n AND EXISTS (\n SELECT 1 FROM jsonb_array_elements(CASE jsonb_typeof(c.result)\n WHEN 'array' THEN c.result ELSE jsonb_build_array(c.result) END) o\n WHERE o->>'s3' = $1 AND o->>'storage' IS NOT DISTINCT FROM $5\n )\n )", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Text", + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "b051ae8494073bc988dd272b2264520f36048ab3d12fe47652a854a41ddce1b0" +} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index fb746f0ddd..9856fbbc53 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -20c54ad02dff7d771a1dbb820e12c57f5f9f6bf4 +b278e6b2bcaa04c27faa7293474d0ac5132dcaf9 diff --git a/backend/tests/app_s3_onbehalf.rs b/backend/tests/app_s3_onbehalf.rs index c11c94be1e..167713c012 100644 --- a/backend/tests/app_s3_onbehalf.rs +++ b/backend/tests/app_s3_onbehalf.rs @@ -360,7 +360,7 @@ async fn test_deployed_app_s3_presigned_bypasses_gate(db: Pool) -> any Ok(()) } -/// Seed a completed job whose result carries an s3 object. `app_trigger` sets the +/// Seed a completed job with `result`, which carries s3 objects. `app_trigger` sets the /// app-origination marker exactly as `execute_component` stamps it: `Some(app_path)` /// => `trigger_kind = 'app'` + `trigger = ` (an app-launched run); /// `None` => an ordinary direct `/jobs/run` (no app marker). `created_by` is the user @@ -369,9 +369,8 @@ async fn seed_completed_job( db: &Pool, created_by: &str, app_trigger: Option<&str>, - s3_key: &str, + result: serde_json::Value, ) -> anyhow::Result<()> { - let result = format!(r#"{{"s3":"{s3_key}"}}"#); sqlx::query( r#" WITH j AS ( @@ -437,10 +436,33 @@ async fn test_deployed_app_s3_onbehalf_flow_script_provenance( // Seed the produced-file jobs (all within the 3h window). The gate's `created_by` // filter uses "anonymous" for an unauthenticated caller. - seed_completed_job(&db, "anonymous", Some(FS_APP), OWN_KEY).await?; - seed_completed_job(&db, "test-user-2", Some(FS_APP), OTHER_CALLER_KEY).await?; - seed_completed_job(&db, "anonymous", Some(OTHER_APP), OTHER_APP_KEY).await?; - seed_completed_job(&db, "anonymous", None, FORGED_KEY).await?; + // A result that is a list of S3 objects, one of them in a secondary storage. + const LISTED_KEY: &str = "results/listed.csv"; + const SECONDARY_KEY: &str = "results/secondary.csv"; + + seed_completed_job(&db, "anonymous", Some(FS_APP), json!({ "s3": OWN_KEY })).await?; + seed_completed_job( + &db, + "test-user-2", + Some(FS_APP), + json!({ "s3": OTHER_CALLER_KEY }), + ) + .await?; + seed_completed_job( + &db, + "anonymous", + Some(OTHER_APP), + json!({ "s3": OTHER_APP_KEY }), + ) + .await?; + seed_completed_job(&db, "anonymous", None, json!({ "s3": FORGED_KEY })).await?; + seed_completed_job( + &db, + "anonymous", + Some(FS_APP), + json!([{ "s3": LISTED_KEY }, { "s3": SECONDARY_KEY, "storage": "secondary" }]), + ) + .await?; let denied = |body: &str| body.contains("is not accessible from this app"); // Anonymous GET (borrows `ws`, reusable across calls: the URL is built before the @@ -491,6 +513,26 @@ async fn test_deployed_app_s3_onbehalf_flow_script_provenance( "key produced by a different app must stay denied: {body}" ); + // Each object of a list result clears the gate, in the storage the result names only. + let body = anon_body(format!("download_s3_file/{FS_APP}?s3={LISTED_KEY}")).await; + assert!( + !denied(&body), + "a key from a list result must clear the gate: {body}" + ); + let body = anon_body(format!( + "download_s3_file/{FS_APP}?s3={SECONDARY_KEY}&storage=secondary" + )) + .await; + assert!( + !denied(&body), + "a key in its own storage must clear the gate: {body}" + ); + let body = anon_body(format!("download_s3_file/{FS_APP}?s3={SECONDARY_KEY}")).await; + assert!( + denied(&body), + "a key requested from another storage than its result's must stay denied: {body}" + ); + Ok(()) } diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 18207c9411..6dcbfa5f63 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -30629,9 +30629,10 @@ components: name: filters description: > JSON object, column name to filter. A number column takes an optional comparison - operator and a number (`>=10`), a boolean column a boolean, and any other column a - case-insensitive substring, or `=value` for an exact match. A `search_term` without - a `search_col` matches any column, case-insensitively. + operator and a number (`>=10`), a boolean column `true` or `false` (a boolean or that + string), and any other column a case-insensitive substring, or `=value` for an exact + match. Any other value on a boolean column, or an unknown column, is a 400. A + `search_term` without a `search_col` matches any column, case-insensitively. in: query schema: type: string diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index 4b10c08281..84197fe8a3 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -6158,20 +6158,27 @@ async fn check_if_allowed_to_access_s3_file_from_app( keys.iter() .any(|key| key.s3_path == file_query.s3 && key.storage == file_query.storage) }) || { + // The result is the S3 object itself or a list of them. The storage is matched with + // the key: the read goes to the requested storage as the author. sqlx::query_scalar!( r#"SELECT EXISTS ( SELECT 1 FROM v2_job_completed c JOIN v2_job j USING (id) WHERE j.workspace_id = $2 AND c.started_at > now() - interval '3 hours' - AND c.result @> ('{"s3":"' || $1 || '"}')::jsonb AND j.trigger_kind = 'app' AND j.trigger = $3 AND j.created_by = $4 + AND EXISTS ( + SELECT 1 FROM jsonb_array_elements(CASE jsonb_typeof(c.result) + WHEN 'array' THEN c.result ELSE jsonb_build_array(c.result) END) o + WHERE o->>'s3' = $1 AND o->>'storage' IS NOT DISTINCT FROM $5 + ) )"#, file_query.s3, w_id, path, creator, + file_query.storage, ) .fetch_one(db) .await? diff --git a/frontend/src/lib/components/DBTable.svelte b/frontend/src/lib/components/DBTable.svelte index 0ea2ec0fc5..0309bb39cc 100644 --- a/frontend/src/lib/components/DBTable.svelte +++ b/frontend/src/lib/components/DBTable.svelte @@ -15,8 +15,10 @@ const MIN_COL_WIDTH = 60 const DEFAULT_COL_WIDTH = 150 const MAX_AUTO_COL_WIDTH = 400 - // Header padding plus its sort and key icons. - const HEADER_CHROME = 48 + // Header padding, its key and sort icons with their gaps, and the cell's right border. + const HEADER_CHROME = 49 + // A pinned header's pin icon with its gap, and the thicker border at the pinned block's edge. + const PIN_CHROME = 17 const CELL_PADDING = 18 // A double click starts with a click: following a foreign key waits this long // so the double click can edit the cell instead. @@ -398,12 +400,16 @@ const next = { ...widths } for (const col of columns) { if (only ? !only.includes(col.field) : sizedColumns.has(col.field)) continue - let w = textWidth(col.field, `600 12px ${family}`) + HEADER_CHROME + let w = + textWidth(col.field, `600 12px ${family}`) + + HEADER_CHROME + + (pinned[col.field] ? PIN_CHROME : 0) for (const row of rows) { const text = formatCell(row[col.field]).slice(0, 200) || 'NULL' w = Math.max(w, textWidth(text, `400 12px ${family}`) + CELL_PADDING) } - next[col.field] = Math.round(Math.min(MAX_AUTO_COL_WIDTH, Math.max(MIN_COL_WIDTH, w))) + // Rounded up: a label a fraction of a pixel wider than its cell is cut. + next[col.field] = Math.ceil(Math.min(MAX_AUTO_COL_WIDTH, Math.max(MIN_COL_WIDTH, w))) sizedColumns.add(col.field) } widths = next diff --git a/frontend/src/lib/components/FilterSearchbar.svelte b/frontend/src/lib/components/FilterSearchbar.svelte index 76c0fa1cdb..9475881663 100644 --- a/frontend/src/lib/components/FilterSearchbar.svelte +++ b/frontend/src/lib/components/FilterSearchbar.svelte @@ -417,11 +417,14 @@ let highlightedIndex = $state(0) let taggedTextInput: TaggedTextInput | undefined = $state() + // A key is letters, digits and `_` in any script; `\b` and `\w` only know ASCII ones. + const KEY_START = '(? !s.hidden) .map(([key, filterSchema]) => ({ - regex: new RegExp(`\\b${key}:(?:\\\\.|[^\\s])*`, 'g'), + regex: new RegExp(`${KEY_START}${key}:(?:\\\\.|[^\\s])*`, 'gu'), id: key, onClear: () => (delete value[key], asText.reparse()) })) @@ -429,18 +432,18 @@ let keyHighlightRegex = $derived( new RegExp( - `\\b(${Object.entries(schema) + `${KEY_START}(${Object.entries(schema) .filter(([_, s]) => !s.hidden) .map(([k]) => k) .join('|')}):`, - 'g' + 'gu' ) ) let errorKeys = $derived(new Set(errors.flatMap((e) => e.fields))) let errorHighlights = $derived( [...errorKeys].map((key) => ({ - regex: new RegExp(`(?<=\\b${key}:)(?:\\\\.|[^\\s])+`), + regex: new RegExp(`(?<=${KEY_START}${key}:)(?:\\\\.|[^\\s])+`, 'u'), classes: 'text-red-500 dark:text-red-400' })) ) @@ -568,7 +571,7 @@ highlightedIndex = 0 }) - const kvRegex = /\b(\w+):((?:[^\s\\]|\\.)*)/g + const kvRegex = new RegExp(`${KEY_START}([\\p{L}\\p{N}_]+):((?:[^\\s\\\\]|\\\\.)*)`, 'gu') function parseFromText(text: string): Partial> { const parsed: Record = {} @@ -812,7 +815,16 @@ {autofocus} /> {#if asText.val} - (_value.current = {})} /> + { + _value.current = {} + // On a closed bar this click's mousedown just wrote the text, and the text skips the + // filter change that follows its own write: left to that sync, the old text stays. + asText.reparse() + }} + /> {:else if searchIconPosition === 'right'}
diff --git a/frontend/src/lib/components/ParqetCsvTableRenderer.svelte b/frontend/src/lib/components/ParqetCsvTableRenderer.svelte index da409b697a..8a685a9a7e 100644 --- a/frontend/src/lib/components/ParqetCsvTableRenderer.svelte +++ b/frontend/src/lib/components/ParqetCsvTableRenderer.svelte @@ -164,10 +164,15 @@ } let eGui: HTMLDivElement | undefined = $state() + // A remount (a new separator) builds a new grid in the same element: the previous one is + // destroyed, or it stays on top showing the old columns. + let gridApi: GridApi | undefined + let mounts = 0 let error: string | undefined = $state(undefined) async function mountGrid() { if (eGui) { + const mount = ++mounts try { const csv = s3resource.endsWith('.csv') @@ -175,8 +180,11 @@ limit: 0, csvSeparator: csv ? csvSeparatorChar : undefined })) as any + // The separator changed again while this one loaded: the later mount owns the grid. + if (mount !== mounts) return - createGrid( + gridApi?.destroy() + gridApi = createGrid( eGui, { rowModelType: 'infinite', @@ -213,6 +221,7 @@ ) error = undefined } catch (e) { + if (mount !== mounts) return error = e.body console.error(e) } @@ -244,7 +253,7 @@
diff --git a/frontend/src/lib/components/S3FilePreview.svelte b/frontend/src/lib/components/S3FilePreview.svelte index 4635d4f6c7..360b4e5940 100644 --- a/frontend/src/lib/components/S3FilePreview.svelte +++ b/frontend/src/lib/components/S3FilePreview.svelte @@ -322,7 +322,7 @@ diff --git a/frontend/src/lib/components/TaggedTextInput.svelte b/frontend/src/lib/components/TaggedTextInput.svelte index 9f19195b85..66f968f097 100644 --- a/frontend/src/lib/components/TaggedTextInput.svelte +++ b/frontend/src/lib/components/TaggedTextInput.svelte @@ -26,6 +26,13 @@ let contentEditableDiv: HTMLDivElement let isUpdating = false + /** A fresh global copy of `regex` for an exec loop, keeping its other flags (`u`, `i`). + * Not sticky: a sticky scan stops at the first text that is not a match. */ + function globalCopy(regex: RegExp): RegExp { + const flags = regex.flags.replace('y', '') + return new RegExp(regex, flags.includes('g') ? flags : flags + 'g') + } + $effect(() => { if (!value.trim() && value !== '') value = '' }) @@ -70,7 +77,7 @@ // Find all highlight matches in the raw text const hlMatches: Array<{ start: number; end: number; classes: string }> = [] for (const hl of highlights) { - const regex = new RegExp(hl.regex, 'g') + const regex = globalCopy(hl.regex) let m while ((m = regex.exec(rawText)) !== null) { hlMatches.push({ start: m.index, end: m.index + m[0].length, classes: hl.classes }) @@ -111,7 +118,7 @@ const matches: Array<{ start: number; end: number; tagIndex: number }> = [] tags.forEach((tag, tagIndex) => { - const regex = new RegExp(tag.regex, 'g') + const regex = globalCopy(tag.regex) let match while ((match = regex.exec(text)) !== null) { matches.push({ @@ -251,7 +258,7 @@ // Find all tag positions const tagPositions: Array<{ start: number; end: number }> = [] for (const tag of tags) { - const regex = new RegExp(tag.regex, 'g') + const regex = globalCopy(tag.regex) let match while ((match = regex.exec(value)) !== null) { tagPositions.push({ @@ -293,7 +300,7 @@ let currentTag: { id: string } | null = null for (const tag of tags) { - const regex = new RegExp(tag.regex, 'g') + const regex = globalCopy(tag.regex) let match while ((match = regex.exec(value)) !== null) { const start = match.index diff --git a/frontend/src/lib/components/dbTableFilters.test.ts b/frontend/src/lib/components/dbTableFilters.test.ts index 7e914d2f2a..d02ee9241a 100644 --- a/frontend/src/lib/components/dbTableFilters.test.ts +++ b/frontend/src/lib/components/dbTableFilters.test.ts @@ -25,6 +25,12 @@ describe('dbColumnKind', () => { expect(dbColumnKind('bigint unsigned')).toBe('number') expect(dbColumnKind('bit')).toBe('boolean') }) + + it('matches arrays of numbers as text, which a number comparison cannot', () => { + expect(dbColumnKind('integer[]')).toBe('text') + expect(dbColumnKind('_int4')).toBe('text') + expect(dbColumnKind('ARRAY')).toBe('text') + }) }) describe('renderColumnFilter', () => { @@ -38,10 +44,13 @@ describe('renderColumnFilter', () => { expect(renderColumnFilter('name', 'varchar', '=Bob', 'mysql')).toBe("`name` = 'Bob'") }) - it('compares PostgreSQL json as text for an exact match', () => { + it('compares PostgreSQL json and arrays as text for an exact match', () => { expect(renderColumnFilter('js', 'json', '={"a": 1}', 'postgresql')).toBe( `CAST("js" AS TEXT) = '{"a": 1}'` ) + expect(renderColumnFilter('tags', 'integer[]', '=4999', 'postgresql')).toBe( + `CAST("tags" AS TEXT) = '4999'` + ) }) it('serializes BigQuery complex columns, which have no cast to STRING', () => { @@ -80,4 +89,9 @@ describe('renderDbTableFilters', () => { ) ).toBe(`(contains(lower(CAST("first name" AS VARCHAR)), 'al b')) AND ("id" = 2)`) }) + + it('keeps letters of any script in a key', () => { + const schema = buildDbTableFilterSchema([col('ünïcødé 名前', 'text')]) + expect(schema.keyOfColumn['ünïcødé 名前']).toBe('ünïcødé_名前') + }) }) diff --git a/frontend/src/lib/components/dbTableFilters.ts b/frontend/src/lib/components/dbTableFilters.ts index c3266b3ac7..a816c1dceb 100644 --- a/frontend/src/lib/components/dbTableFilters.ts +++ b/frontend/src/lib/components/dbTableFilters.ts @@ -30,8 +30,16 @@ const NUMERIC_TYPE = /^(u?(tiny|small|medium|big|huge)?int(eger)?\d*|(small|big)?serial\d*|numeric|decimal|dec|float\d*|double|real|number|money|smallmoney|bignumeric)\b/ const BOOLEAN_TYPE = /^(bool|boolean|bit)\b/ +/** `integer[]`, Postgres's `_int4`, `ARRAY`. */ +function isArrayType(datatype: string | undefined): boolean { + const t = (datatype ?? '').trim().toLowerCase() + return t.endsWith(']') || t.startsWith('_') || t.startsWith('array') +} + export function dbColumnKind(datatype: string | undefined): DbColumnKind { const t = (datatype ?? '').trim().toLowerCase() + // An array of numbers is matched as text, not compared. + if (isArrayType(t)) return 'text' if (NUMERIC_TYPE.test(t)) return 'number' if (BOOLEAN_TYPE.test(t)) return 'boolean' return 'text' @@ -41,8 +49,8 @@ const NUMERIC_FILTER = /^(>=|<=|!=|<>|>|<|=)?\s*(-?\d+(\.\d+)?([eE][+-]?\d+)?)$/ export type DbTableFilterSchema = { schema: FilterSchemaRec - /** Search bar key → column name. The bar only recognises `\w+` keys, so - * other column names get a sanitized key. */ + /** Search bar key → column name. A key is letters, digits and `_`, so other + * column names get a sanitized key. */ columnOfKey: Record keyOfColumn: Record } @@ -53,7 +61,7 @@ export function buildDbTableFilterSchema(columns: ColumnDef[]): DbTableFilterSch const keyOfColumn: Record = {} for (const col of columns) { if (!col.field || col.filterable === false) continue - let base = col.field.replace(/\W+/g, '_') || 'column' + let base = col.field.replace(/[^\p{L}\p{N}_]+/gu, '_') || 'column' if (base === FREE_TEXT_KEY) base = `${base}col` let key = base for (let i = 2; key in schema; i++) key = `${base}_${i}` @@ -121,8 +129,12 @@ export function renderColumnFilter( : `STRPOS(LOWER(${serialized}), ${renderDbLiteral(text.toLowerCase(), dbType)}) > 0` } if (!text.startsWith('=')) return renderDbContainsFilter(column, text, dbType) - // PostgreSQL `json` has no `=`: compare as the text the grid shows. - if (dbType === 'postgresql' && /^jsonb?$/i.test((datatype ?? '').trim())) { + // PostgreSQL `json` has no `=`, and an array would read the value as an array + // literal and fail on any other text: compare as the text the grid shows. + if ( + dbType === 'postgresql' && + (/^jsonb?$/i.test((datatype ?? '').trim()) || isArrayType(datatype)) + ) { const literal = renderDbLiteral(text.slice(1), dbType)! return `CAST(${renderDbQuotedIdentifier(column, dbType)} AS TEXT) = ${literal}` } diff --git a/frontend/src/lib/components/meltComponents/Popover.svelte b/frontend/src/lib/components/meltComponents/Popover.svelte index 0ba7b647ab..cc706e7d50 100644 --- a/frontend/src/lib/components/meltComponents/Popover.svelte +++ b/frontend/src/lib/components/meltComponents/Popover.svelte @@ -242,10 +242,14 @@ isOpen && hostActive() && onKeyDown(e)} /> +