diff --git a/cli/src/commands/folder/folder.ts b/cli/src/commands/folder/folder.ts index a91be98083..07799ae810 100644 --- a/cli/src/commands/folder/folder.ts +++ b/cli/src/commands/folder/folder.ts @@ -291,10 +291,10 @@ const command = new Command() } const relative = testPath.slice(prefix.length); - const { minimatch } = await import("minimatch"); + const { folderRuleGlobMatches } = await import("../../utils/folder_rule_glob.ts"); for (let i = 0; i < rules.length; i++) { const rule = rules[i]; - if (minimatch(relative, rule.path_glob)) { + if (folderRuleGlobMatches(rule.path_glob, relative)) { if (opts.json) { console.log(JSON.stringify({ matched: true, rule_index: i, rule, relative_path: relative })); } else { diff --git a/cli/src/commands/sync/sync.ts b/cli/src/commands/sync/sync.ts index 43bba850ed..9d7d026ffd 100644 --- a/cli/src/commands/sync/sync.ts +++ b/cli/src/commands/sync/sync.ts @@ -26,6 +26,7 @@ import { } from "yaml"; import JSZip from "jszip"; import { minimatch } from "minimatch"; +import { folderRuleGlobMatches } from "../../utils/folder_rule_glob.ts"; import { yamlParseContent, yamlParseFile } from "../../utils/yaml.ts"; import * as wmill from "../../../gen/services.gen.ts"; @@ -5738,7 +5739,7 @@ export async function push( const relative = remotePath.slice(`f/${folderName}/`.length); if (!relative) continue; for (const rule of rules) { - if (minimatch(relative, rule.path_glob)) { + if (folderRuleGlobMatches(rule.path_glob, relative)) { folderDefaultAnnotations.set(change.path, rule.permissioned_as); break; } diff --git a/cli/src/core/permissioned_as.ts b/cli/src/core/permissioned_as.ts index 4f4483ba75..6bb4e1deae 100644 --- a/cli/src/core/permissioned_as.ts +++ b/cli/src/core/permissioned_as.ts @@ -10,7 +10,7 @@ import { } from "../utils/resource_folders.ts"; import { deploysWithRawApp } from "../utils/app_files.ts"; import { parseSyncBehavior } from "./conf.ts"; -import { minimatch } from "minimatch"; +import { folderRuleGlobMatches } from "../utils/folder_rule_glob.ts"; export interface PermissionedAsContext { userCache: Map; @@ -78,13 +78,7 @@ async function folderRuleMatches(workspace: string, path: string): Promise []); folderRules.set(key, rules); } - return (await rules).some((r) => { - try { - return minimatch(m[2], r.path_glob); - } catch { - return false; - } - }); + return (await rules).some((r) => folderRuleGlobMatches(r.path_glob, m[2])); } /** diff --git a/cli/src/utils/folder_rule_glob.ts b/cli/src/utils/folder_rule_glob.ts new file mode 100644 index 0000000000..4e2e827458 --- /dev/null +++ b/cli/src/utils/folder_rule_glob.ts @@ -0,0 +1,61 @@ +/** + * Whether a folder `default_permissioned_as` glob matches a path relative to its folder, with + * the semantics the server applies (`globset::Glob` defaults): `*` and `?` also match `/`, + * `**` spans any depth, `{a,b}` alternates, `[!x]` negates, and an invalid glob matches nothing. + * A push names its deployer where no rule matches, so a matcher that disagrees with the server + * makes that name override the rule the server would have applied. + */ +export function folderRuleGlobMatches(glob: string, relativePath: string): boolean { + const source = globToRegexSource(glob); + return source !== undefined && new RegExp(`^${source}$`, "s").test(relativePath); +} + +function globToRegexSource(glob: string): string | undefined { + let re = ""; + for (let i = 0; i < glob.length; i++) { + const c = glob[i]; + if (c === "*") { + if (glob[i + 1] !== "*") { + re += ".*"; + continue; + } + const atSegmentStart = i === 0 || glob[i - 1] === "/"; + i++; + if (atSegmentStart && glob[i + 1] === "/" && i + 2 < glob.length) { + re += "(?:.*/)?"; + i++; + } else { + re += ".*"; + if (glob[i + 1] === "/") i++; + } + } else if (c === "?") { + re += "."; + } else if (c === "[") { + const end = glob.indexOf("]", i + 2); + if (end < 0) return undefined; + let body = glob.slice(i + 1, end).replace(/[\\^]/g, "\\$&"); + if (body.startsWith("!")) body = "^" + body.slice(1); + re += `[${body}]`; + i = end; + } else if (c === "{") { + const end = glob.indexOf("}", i); + if (end < 0) return undefined; + const alternatives = glob + .slice(i + 1, end) + .split(",") + .map(globToRegexSource); + if (alternatives.some((a) => a === undefined)) return undefined; + re += `(?:${alternatives.join("|")})`; + i = end; + } else if (c === "\\" && i + 1 < glob.length) { + re += escapeRegex(glob[++i]); + } else { + re += escapeRegex(c); + } + } + return re; +} + +function escapeRegex(c: string): string { + return c.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&"); +} diff --git a/cli/test/folder_rule_glob_unit.test.ts b/cli/test/folder_rule_glob_unit.test.ts new file mode 100644 index 0000000000..e6c86d6066 --- /dev/null +++ b/cli/test/folder_rule_glob_unit.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, test } from "bun:test"; +import { folderRuleGlobMatches } from "../src/utils/folder_rule_glob.ts"; + +// Expected matches are what `globset::Glob::new(glob).compile_matcher()` answers on the server. +const PATHS = ["x", "jobs/a", "jobs/a/b", "a/b", "a/x/b", "a/c", "abc", "foo/z", "bar/z/q", "baz/z"]; +const CASES: [string, string[]][] = [ + ["**", PATHS], + ["*", PATHS], + ["**/", PATHS], + ["jobs/*", ["jobs/a", "jobs/a/b"]], + ["a/**/b", ["a/b", "a/x/b"]], + ["**/x", ["x"]], + ["a?c", ["a/c", "abc"]], + ["[!ab]*", ["x", "jobs/a", "jobs/a/b", "foo/z"]], + ["{foo,bar}/*", ["foo/z", "bar/z/q"]], + ["[unclosed", []], +]; + +describe("folderRuleGlobMatches", () => { + for (const [glob, expected] of CASES) { + test(`${glob} matches what the server matches`, () => { + expect(PATHS.filter((p) => folderRuleGlobMatches(glob, p))).toEqual(expected); + }); + } +}); diff --git a/frontend/src/lib/components/CompareWorkspaces.svelte b/frontend/src/lib/components/CompareWorkspaces.svelte index 6554c2a4d1..292ec3c769 100644 --- a/frontend/src/lib/components/CompareWorkspaces.svelte +++ b/frontend/src/lib/components/CompareWorkspaces.svelte @@ -60,6 +60,7 @@ type OnBehalfOfChoice, type OnBehalfOfDetails } from './OnBehalfOfSelector.svelte' + import { createFolderDefaultLookup } from './useFolderDefaultPermissionedAs.svelte' import { sendUserToast } from '$lib/toast' import { deepEqual } from 'fast-equals' import WorkspaceDeployLayout from './WorkspaceDeployLayout.svelte' @@ -500,6 +501,8 @@ let onBehalfOfInfo = $state>({}) let onBehalfOfChoice = $state>({}) let customOnBehalfOf = $state>({}) + // An item new in the target takes the target folder's rule unless the deploy names someone. + const targetFolderDefault = createFolderDefaultLookup() let deployTargetWorkspace = $derived(mergeIntoParent ? parentWorkspaceId : currentWorkspaceId) let deploySourceWorkspace = $derived(mergeIntoParent ? currentWorkspaceId : parentWorkspaceId) @@ -1694,6 +1697,10 @@ kind={diff.kind} canPreserve={canPreserveOnBehalfOf} customValue={customOnBehalfOf[key]?.permissionedAs} + folderDefault={canPreserveOnBehalfOf && + !(mergeIntoParent ? diff.exists_in_source : diff.exists_in_fork) + ? targetFolderDefault(deployTargetWorkspace, diff.path) + : undefined} /> {/if} {#if diff.kind === 'raw_app'} diff --git a/frontend/src/lib/components/DeployWorkspace.svelte b/frontend/src/lib/components/DeployWorkspace.svelte index 7eb27adfe8..4d37d1da8f 100644 --- a/frontend/src/lib/components/DeployWorkspace.svelte +++ b/frontend/src/lib/components/DeployWorkspace.svelte @@ -48,6 +48,7 @@ type OnBehalfOfChoice, type OnBehalfOfDetails } from './OnBehalfOfSelector.svelte' + import { createFolderDefaultLookup } from './useFolderDefaultPermissionedAs.svelte' import ParentWorkspaceProtectionAlert from './ParentWorkspaceProtectionAlert.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' @@ -104,6 +105,8 @@ let onBehalfOfChoice = $state>({}) let customOnBehalfOf = $state>({}) let canPreserveOnBehalfOf = $state(false) + // An item new in the target takes the target folder's rule unless the deploy names someone. + const targetFolderDefault = createFolderDefaultLookup() /** Who the deploy acts as in the target: on a remote instance, the remote token's user. */ let deployerEmail = $state(undefined) @@ -648,6 +651,9 @@ kind={item.kind} canPreserve={canPreserveOnBehalfOf} customValue={customOnBehalfOf[statusPath]?.permissionedAs} + folderDefault={canPreserveOnBehalfOf && exists === false + ? targetFolderDefault(workspaceToDeployTo!, item.path) + : undefined} /> {/if} diff --git a/frontend/src/lib/components/OnBehalfOfSelector.svelte b/frontend/src/lib/components/OnBehalfOfSelector.svelte index f4cfd80da6..50cd510bc7 100644 --- a/frontend/src/lib/components/OnBehalfOfSelector.svelte +++ b/frontend/src/lib/components/OnBehalfOfSelector.svelte @@ -160,7 +160,9 @@ onSelect('target') } else if (folderDefault && users.length > 0) { const username = folderDefault.startsWith('u/') ? folderDefault.slice(2) : folderDefault - const email = users.find((u) => u.username === username)?.email ?? folderDefault + // A group, or a user this list lacks, has no address to send: an empty one names nobody, + // so the server derives it from the principal rather than refusing a mismatched pair. + const email = users.find((u) => u.username === username)?.email ?? '' onSelect('custom', { email, permissionedAs: folderDefault }) } }) diff --git a/frontend/src/lib/components/ScriptBuilder.svelte b/frontend/src/lib/components/ScriptBuilder.svelte index 67b8fd8d61..1afc33678b 100644 --- a/frontend/src/lib/components/ScriptBuilder.svelte +++ b/frontend/src/lib/components/ScriptBuilder.svelte @@ -278,7 +278,7 @@ let originalOnBehalfOfEmail = $derived(savedScript?.on_behalf_of_email) let originalOnBehalfOfPermissionedAs = $derived(savedScript?.on_behalf_of) let onBehalfOfChoice: OnBehalfOfChoice = $state(undefined) - let customOnBehalfOfEmail: string = $state('') + let customOnBehalfOf: string = $state('') let myPermissionedAs = $derived($userStore?.username ? `u/${$userStore.username}` : undefined) // The rule applies on a script's first deploy only. const folderDefault = useFolderDefaultRunAs( @@ -2173,22 +2173,22 @@ if (choice === 'me') { script.on_behalf_of_email = $userStore?.email script.on_behalf_of = myPermissionedAs - customOnBehalfOfEmail = '' + customOnBehalfOf = '' } else if (choice === 'target') { // Keep the saved pair. A script that has no recorded principal yet // sends the email alone and the backend derives one from it. script.on_behalf_of_email = originalOnBehalfOfEmail script.on_behalf_of = originalOnBehalfOfPermissionedAs - customOnBehalfOfEmail = '' + customOnBehalfOf = '' } else if (choice === 'custom' && details) { script.on_behalf_of_email = details.email script.on_behalf_of = details.permissionedAs - customOnBehalfOfEmail = details.email + customOnBehalfOf = details.permissionedAs } }} kind="script" {canPreserve} - customValue={customOnBehalfOfEmail} + customValue={customOnBehalfOf} isDeployment={false} folderDefault={folderDefault.value} /> diff --git a/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte b/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte index e28cdab306..080517c3ec 100644 --- a/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte +++ b/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte @@ -156,7 +156,7 @@ let savedOnBehalfOfEmail = $derived(savedApp?.policy?.on_behalf_of_email) let savedOnBehalfOf = $derived(savedApp?.policy?.on_behalf_of) let onBehalfOfChoice: OnBehalfOfChoice = $state(undefined) - let customOnBehalfOfEmail: string = $state('') + let customOnBehalfOf: string = $state('') let myOnBehalfOf = $derived(actingUser?.username ? `u/${actingUser.username}` : undefined) // A new app starts on the folder rule its path matches, or on the deployer, and deploys // what is shown: naming nobody would let the server apply a rule this picker did not see. @@ -172,7 +172,7 @@ if (onBehalfOfChoice !== undefined && !defaultChosen) return defaultChosen = true onBehalfOfChoice = rule ? 'custom' : 'me' - customOnBehalfOfEmail = rule ?? '' + customOnBehalfOf = rule ?? '' policy.on_behalf_of = rule ?? myOnBehalfOf policy.on_behalf_of_email = rule ? undefined : $userStore?.email }) @@ -357,20 +357,20 @@ if (choice === 'me') { policy.on_behalf_of_email = $userStore?.email policy.on_behalf_of = `u/${$userStore?.username}` - customOnBehalfOfEmail = '' + customOnBehalfOf = '' } else if (choice === 'target') { policy.on_behalf_of_email = savedOnBehalfOfEmail policy.on_behalf_of = savedOnBehalfOf - customOnBehalfOfEmail = '' + customOnBehalfOf = '' } else if (choice === 'custom' && details) { policy.on_behalf_of_email = details.email policy.on_behalf_of = details.permissionedAs - customOnBehalfOfEmail = details.email + customOnBehalfOf = details.permissionedAs } }} kind="app" {canPreserve} - customValue={customOnBehalfOfEmail} + customValue={customOnBehalfOf} isDeployment={false} myPermissionedAs={myOnBehalfOf} readOnlyWithoutPreserve diff --git a/frontend/src/lib/components/flows/content/FlowSettings.svelte b/frontend/src/lib/components/flows/content/FlowSettings.svelte index d06f6d7a51..9c8c107ed6 100644 --- a/frontend/src/lib/components/flows/content/FlowSettings.svelte +++ b/frontend/src/lib/components/flows/content/FlowSettings.svelte @@ -66,7 +66,7 @@ let isDeployer = $derived(actingUser?.groups?.includes(WM_DEPLOYERS_GROUP) ?? false) let canPreserve = $derived(!!actingUser?.is_admin || !!actingUser?.is_super_admin || isDeployer) let onBehalfOfChoice: OnBehalfOfChoice = $state(undefined) - let customOnBehalfOfEmail: string = $state('') + let customOnBehalfOf: string = $state('') let myPermissionedAs = $derived($userStore?.username ? `u/${$userStore.username}` : undefined) // The rule applies on a flow's create only. const folderDefault = useFolderDefaultRunAs( @@ -513,22 +513,22 @@ if (choice === 'me') { flowStore.val.on_behalf_of_email = $userStore?.email flowStore.val.on_behalf_of = myPermissionedAs - customOnBehalfOfEmail = '' + customOnBehalfOf = '' } else if (choice === 'target') { // Keep the saved pair. A flow that has no recorded principal yet // sends the email alone and the backend derives one from it. flowStore.val.on_behalf_of_email = $savedOnBehalfOfEmail flowStore.val.on_behalf_of = $savedOnBehalfOfPermissionedAs - customOnBehalfOfEmail = '' + customOnBehalfOf = '' } else if (choice === 'custom' && details) { flowStore.val.on_behalf_of_email = details.email flowStore.val.on_behalf_of = details.permissionedAs - customOnBehalfOfEmail = details.email + customOnBehalfOf = details.permissionedAs } }} kind="flow" {canPreserve} - customValue={customOnBehalfOfEmail} + customValue={customOnBehalfOf} isDeployment={false} folderDefault={folderDefault.value} /> diff --git a/frontend/src/lib/components/useFolderDefaultPermissionedAs.svelte.ts b/frontend/src/lib/components/useFolderDefaultPermissionedAs.svelte.ts index 271fe0dd5b..7444718610 100644 --- a/frontend/src/lib/components/useFolderDefaultPermissionedAs.svelte.ts +++ b/frontend/src/lib/components/useFolderDefaultPermissionedAs.svelte.ts @@ -1,8 +1,25 @@ import { FolderService } from '$lib/gen' -import { Minimatch } from 'minimatch' import { resource } from 'runed' import { untrack } from 'svelte' import { workspaceStore, userStore } from '$lib/stores' +import { folderRuleGlobMatches } from '$lib/utils/folderRuleGlob' + +/** The folder rule a create at `path` takes on the server, for a caller it applies to. */ +export async function resolveFolderDefaultPermissionedAs( + workspace: string, + path: string +): Promise { + const m = path.match(/^f\/([^/]+)\/(.+)$/) + if (!m) return undefined + try { + const folder = await FolderService.getFolder({ workspace, name: m[1] }) + return (folder.default_permissioned_as ?? []).find((rule) => + folderRuleGlobMatches(rule.path_glob, m[2]) + )?.permissioned_as + } catch { + return undefined + } +} /** * Resolves the folder's `default_permissioned_as` rule that matches a given item path. @@ -37,29 +54,8 @@ export function useFolderDefaultPermissionedAs( async ({ path, workspace, user }) => { const canPreserve = user?.is_admin || user?.is_super_admin || (user?.groups ?? []).includes('wm_deployers') - if (!canPreserve || !workspace || !path?.startsWith('f/')) { - return undefined - } - const parts = path.split('/') - if (parts.length < 3) return undefined - const folderName = parts[1] - const relative = path.slice(`f/${folderName}/`.length) - if (!relative) return undefined - - try { - const folder = await FolderService.getFolder({ workspace, name: folderName }) - const rules = folder.default_permissioned_as ?? [] - const match = rules.find((rule) => { - try { - return new Minimatch(rule.path_glob).match(relative) - } catch { - return false - } - }) - return match?.permissioned_as - } catch { - return undefined - } + if (!canPreserve || !workspace || !path) return undefined + return resolveFolderDefaultPermissionedAs(workspace, path) } ) @@ -90,6 +86,8 @@ export function useFolderDefaultRunAs( const folderDefault = useFolderDefaultPermissionedAs(newPathGetter, wsGetter) let seeded: string | undefined = undefined $effect(() => { + // Creation ending (the first deploy) is not the path leaving the rule: keep the identity. + if (newPathGetter() === undefined || folderDefault.loading) return const rule = folderDefault.value untrack(() => { if (rule === seeded) return @@ -105,3 +103,20 @@ export function useFolderDefaultRunAs( }) return folderDefault } + +/** + * Folder rules a deploy into another workspace meets, looked up once per item on first read. + * Only an item new in that workspace takes one, so callers ask only for those. + */ +export function createFolderDefaultLookup() { + const values = $state>({}) + const requested = new Set() + return (workspace: string, path: string): string | undefined => { + const key = `${workspace}:${path}` + if (!requested.has(key)) { + requested.add(key) + resolveFolderDefaultPermissionedAs(workspace, path).then((v) => (values[key] = v)) + } + return values[key] + } +} diff --git a/frontend/src/lib/utils/folderRuleGlob.test.ts b/frontend/src/lib/utils/folderRuleGlob.test.ts new file mode 100644 index 0000000000..4e48882089 --- /dev/null +++ b/frontend/src/lib/utils/folderRuleGlob.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' +import { folderRuleGlobMatches } from './folderRuleGlob' + +// Expected matches are what `globset::Glob::new(glob).compile_matcher()` answers on the server. +const PATHS = ['x', 'jobs/a', 'jobs/a/b', 'a/b', 'a/x/b', 'a/c', 'abc', 'foo/z', 'bar/z/q', 'baz/z'] +const CASES: [string, string[]][] = [ + ['**', PATHS], + ['*', PATHS], + ['**/', PATHS], + ['jobs/*', ['jobs/a', 'jobs/a/b']], + ['a/**/b', ['a/b', 'a/x/b']], + ['**/x', ['x']], + ['a?c', ['a/c', 'abc']], + ['[!ab]*', ['x', 'jobs/a', 'jobs/a/b', 'foo/z']], + ['{foo,bar}/*', ['foo/z', 'bar/z/q']], + ['[unclosed', []] +] + +describe('folderRuleGlobMatches', () => { + it.each(CASES)('%s matches what the server matches', (glob, expected) => { + expect(PATHS.filter((p) => folderRuleGlobMatches(glob, p))).toEqual(expected) + }) +}) diff --git a/frontend/src/lib/utils/folderRuleGlob.ts b/frontend/src/lib/utils/folderRuleGlob.ts new file mode 100644 index 0000000000..c16c3705ac --- /dev/null +++ b/frontend/src/lib/utils/folderRuleGlob.ts @@ -0,0 +1,61 @@ +/** + * Whether a folder `default_permissioned_as` glob matches a path relative to its folder, with + * the semantics the server applies (`globset::Glob` defaults): `*` and `?` also match `/`, + * `**` spans any depth, `{a,b}` alternates, `[!x]` negates, and an invalid glob matches nothing. + * The editors send the rule they preview, so a matcher that disagrees with the server stores + * an identity other than the one the folder rule would have given. + */ +export function folderRuleGlobMatches(glob: string, relativePath: string): boolean { + const source = globToRegexSource(glob) + return source !== undefined && new RegExp(`^${source}$`, 's').test(relativePath) +} + +function globToRegexSource(glob: string): string | undefined { + let re = '' + for (let i = 0; i < glob.length; i++) { + const c = glob[i] + if (c === '*') { + if (glob[i + 1] !== '*') { + re += '.*' + continue + } + const atSegmentStart = i === 0 || glob[i - 1] === '/' + i++ + if (atSegmentStart && glob[i + 1] === '/' && i + 2 < glob.length) { + re += '(?:.*/)?' + i++ + } else { + re += '.*' + if (glob[i + 1] === '/') i++ + } + } else if (c === '?') { + re += '.' + } else if (c === '[') { + const end = glob.indexOf(']', i + 2) + if (end < 0) return undefined + let body = glob.slice(i + 1, end).replace(/[\\^]/g, '\\$&') + if (body.startsWith('!')) body = '^' + body.slice(1) + re += `[${body}]` + i = end + } else if (c === '{') { + const end = glob.indexOf('}', i) + if (end < 0) return undefined + const alternatives = glob + .slice(i + 1, end) + .split(',') + .map(globToRegexSource) + if (alternatives.some((a) => a === undefined)) return undefined + re += `(?:${alternatives.join('|')})` + i = end + } else if (c === '\\' && i + 1 < glob.length) { + re += escapeRegex(glob[++i]) + } else { + re += escapeRegex(c) + } + } + return re +} + +function escapeRegex(c: string): string { + return c.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&') +}