diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 966a039f5a..ed62da83f6 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -e3d765239022d2b7a6615d28348a9da661a3faf5 +d16494953659e00dd169fb8f73266f22f937b862 diff --git a/backend/windmill-api/src/mcp/session/deploy.rs b/backend/windmill-api/src/mcp/session/deploy.rs index a5be2c0ecc..4ddb924e25 100644 --- a/backend/windmill-api/src/mcp/session/deploy.rs +++ b/backend/windmill-api/src/mcp/session/deploy.rs @@ -8,9 +8,9 @@ use serde_json::{json, Map, Value}; use super::flows::drop_stale_step_locks; use super::workspace::{ - api_message, app_source_to_draft_value, delete_draft, deployed_item_exists, draft_kind, - draft_page, get_deployed, get_draft_item, item_exists, item_type_arg, path_enc, service, - unified_patch, ITEM_TYPES, TRIGGER_KINDS, + api_message, app_source_to_draft_value, delete_draft, deployed_execution_mode, + deployed_item_exists, draft_kind, draft_page, get_deployed, get_draft_item, item_exists, + item_type_arg, path_enc, service, unified_patch, ITEM_TYPES, TRIGGER_KINDS, }; use super::{ array, bool_arg, enc, is_not_found, js_str, matches_glob, non_null, opt_str_arg, pretty, @@ -323,6 +323,18 @@ async fn guest_access_is_live(ctx: &Ctx<'_>) -> bool { truthy(usage.get("available")) } +/// Settles the access mode a raw app deploy states. Who can open a deployed app is set from the +/// Share dialog, so an update states none and the server keeps the deployed mode, under the row +/// lock a mode change also takes. A new app takes the drafted mode, members-only when the draft +/// names none. +fn settle_execution_mode(policy: &mut Map, exists: bool) { + if exists { + policy.remove("execution_mode"); + } else if !truthy(policy.get("execution_mode")) { + policy.insert("execution_mode".into(), json!("publisher")); + } +} + /// Deploys a raw app draft from its sources: the server bundles them on a worker and /// derives the policy's triggerables from the runnables. Returns the note for the result. async fn deploy_app( @@ -354,10 +366,6 @@ async fn deploy_app( .unwrap_or_default() }; let runnables = object_or_empty("runnables"); - let mut policy = object_or_empty("policy"); - if !truthy(policy.get("execution_mode")) { - policy.insert("execution_mode".into(), json!("publisher")); - } let mut notes = Vec::new(); let undeployed = undeployed_runnable_targets(ctx, &runnables).await; @@ -368,23 +376,6 @@ async fn deploy_app( undeployed.join(", ") )); } - // What a runnable runs as is the server's to decide, so the note names who can - // reach the app and never an identity. - match policy.get("execution_mode").and_then(Value::as_str) { - Some("anonymous") => notes.push( - "This app is deployed as anonymous: its backend runnables are now reachable by anyone \ - with the URL, without logging in. Tell the user plainly what is now reachable and by whom." - .to_string(), - ), - // `guest` is stored whether or not a guest is admitted: silent unless it is live. - Some("guest") if guest_access_is_live(ctx).await => notes.push( - "This app is deployed as guest: anyone the instance's identity provider authenticates \ - can now open it and run its backend runnables, member of this workspace or not. Tell \ - the user plainly what is now reachable and by whom." - .to_string(), - ), - _ => {} - } // An editor-created draft is parked at a synthetic storage key, its chosen path in // the stored draft. Only a missing item justifies falling back to the storage path. @@ -404,6 +395,11 @@ async fn deploy_app( Err(e) if is_not_found(&e) => path.to_string(), Err(e) => return Err(e), }; + let exists = item_exists(ctx, "app", None, &target).await?; + + let mut policy = object_or_empty("policy"); + settle_execution_mode(&mut policy, exists); + let created_mode = policy.get("execution_mode").cloned(); let mut app = Map::new(); app.insert("path".into(), json!(target)); @@ -432,7 +428,7 @@ async fn deploy_app( if let Some(message) = message { app.insert("deployment_message".into(), json!(message)); } - if item_exists(ctx, "app", None, &target).await? { + if exists { // `custom_path` stays out of an update: the server keeps it when absent, and // sending it takes admin rights. ctx.post( @@ -447,6 +443,35 @@ async fn deploy_app( ctx.post(&ctx.ws("apps/create_raw_source"), Value::Object(app)) .await?; } + + // An update keeps the deployed mode, so the note states the stored row's, read after the + // write. What a runnable runs as is the server's to decide, so the note names who can reach + // the app and never an identity. + let mode = if exists { + deployed_execution_mode(ctx, &target).await.ok().flatten() + } else { + created_mode + }; + match mode.as_ref().and_then(Value::as_str) { + Some("anonymous") => notes.push( + "This app is deployed as anonymous: its backend runnables are now reachable by anyone \ + with the URL, without logging in. Tell the user plainly what is now reachable and by whom." + .to_string(), + ), + // `guest` is stored whether or not a guest is admitted: silent unless it is live. + Some("guest") if guest_access_is_live(ctx).await => notes.push( + "This app is deployed as guest: anyone the instance's identity provider authenticates \ + can now open it and run its backend runnables, member of this workspace or not. Tell \ + the user plainly what is now reachable and by whom." + .to_string(), + ), + None => notes.push( + "Its access mode could not be read back after the deploy, so tell the user to check \ + who can open the app." + .to_string(), + ), + _ => {} + } Ok((!notes.is_empty()).then(|| notes.join(" "))) } @@ -2350,4 +2375,24 @@ mod tests { assert!(!matches_glob("f/dash/main/src/App.tsx", "f/dash/*.tsx")); assert!(!matches_glob("f/dash/main", "*.tsx")); } + + #[test] + fn an_update_leaves_the_access_mode_to_the_server() { + let settled = |drafted: Value, exists: bool| { + let mut policy = drafted.as_object().cloned().unwrap_or_default(); + settle_execution_mode(&mut policy, exists); + policy.get("execution_mode").cloned() + }; + // An update states no mode, whatever the draft names, so the deployed one stands. + assert_eq!( + settled(json!({ "execution_mode": "anonymous" }), true), + None + ); + // A new app takes the drafted mode, members-only when there is none. + assert_eq!( + settled(json!({ "execution_mode": "anonymous" }), false), + Some(json!("anonymous")) + ); + assert_eq!(settled(json!({}), false), Some(json!("publisher"))); + } } diff --git a/backend/windmill-api/src/mcp/session/workspace.rs b/backend/windmill-api/src/mcp/session/workspace.rs index ac8403c7c8..2eed15c464 100644 --- a/backend/windmill-api/src/mcp/session/workspace.rs +++ b/backend/windmill-api/src/mcp/session/workspace.rs @@ -277,6 +277,18 @@ pub(super) async fn get_deployed( .await } +/// Who can open the deployed app at `path`, which the Share dialog sets and a deploy keeps. +pub(super) async fn deployed_execution_mode( + ctx: &Ctx<'_>, + path: &str, +) -> Result, String> { + Ok(ctx + .get(&ctx.ws(&format!("apps/get/lite/{}", path_enc(path)))) + .await? + .pointer("/policy/execution_mode") + .cloned()) +} + pub(super) struct Draft { pub value: Value, pub created_at: Option, @@ -1493,12 +1505,19 @@ async fn read_workspace_item(ctx: &Ctx<'_>, args: &Value) -> ToolResult { if !deployed_only && !hub { if let Some((item, _)) = get_draft_item(ctx, item_type, path, trigger_kind).await? { - // The mode reported is the draft's, which is what deploying it will write. + // The mode reported is the one deploying the draft leaves: a deployed app keeps + // its own, which the Share dialog sets, and a never-deployed one takes the draft's. let mode = if item_type == "app" { - let mode = item - .get("value") - .and_then(|v| v.get("policy")) - .and_then(|p| p.get("execution_mode")); + let deployed = if item_exists(ctx, "app", None, path).await? { + deployed_execution_mode(ctx, path).await? + } else { + None + }; + let mode = deployed.as_ref().or_else(|| { + item.get("value") + .and_then(|v| v.get("policy")) + .and_then(|p| p.get("execution_mode")) + }); describe_app_exposure(ctx, mode).await } else { None diff --git a/docs/feature-telemetry.md b/docs/feature-telemetry.md index bf39baf201..82206dcd16 100644 --- a/docs/feature-telemetry.md +++ b/docs/feature-telemetry.md @@ -4,13 +4,13 @@ anonymous usage-stats payload. It answers "does anyone use this, and which variant do they pick" without any identifying data leaving the instance. -It currently carries 91 registered actions across thirty-five features (`ai_session`, `ai_chat`, +It currently carries 93 registered actions across thirty-six features (`ai_session`, `ai_chat`, `ai_fix`, `ai_agent`, `ai_decision`, `ai_agent_eval`, `app_sandbox`, `datatable`, `db_manager`, `flow_editor`, -`flow_run`, `flow_step`, `home`, `header_nav`, `run_form`, `debugger`, `trigger`, `command_script`, -`mcp`, `mcp_workspace`, `hub_script`, `usage_meter`, `sso_groups_claim`, `cloud_trial_offer`, -`job_token_scopes`, `worker_draining`, `worker_group`, `worker_resource_stats`, -`dev_workspace_isolation`, `slack_agent`, `variable_expiration`, `anthropic_federation`, -`deployment_request`, `fork_roles`, `git_sync_review`). Nearly all of the +`flow_run`, `flow_step`, `home`, `header_nav`, `run_form`, `sharing`, `debugger`, `trigger`, +`command_script`, `mcp`, `mcp_workspace`, `hub_script`, `usage_meter`, `sso_groups_claim`, +`cloud_trial_offer`, `job_token_scopes`, `worker_draining`, `worker_group`, +`worker_resource_stats`, `dev_workspace_isolation`, `slack_agent`, `variable_expiration`, +`anthropic_federation`, `deployment_request`, `fork_roles`, `git_sync_review`). Nearly all of the product is uninstrumented, so new user-facing work is the opportunity to change that. ## When to instrument diff --git a/frontend/src/lib/components/FlowBuilder.svelte b/frontend/src/lib/components/FlowBuilder.svelte index a1d4f29b13..a18d93893e 100644 --- a/frontend/src/lib/components/FlowBuilder.svelte +++ b/frontend/src/lib/components/FlowBuilder.svelte @@ -1,6 +1,7 @@ + dispatch('change', { path, kind })} /> + - -
- {#if defaultPerms.length > 0} -
- {defaultPermsLabel} - {#each defaultPerms as perm (perm.label)} -
- {perm.label} - {perm.write ? 'Writer' : 'Viewer'} -
- {/each} + + +
+ {#if linkedVarPaths.length > 0} +
+ +
    + {#each linkedVarPaths as varPath (varPath)} +
  • {varPath}
  • + {/each} +
{/if} -
- Extra members ({acls?.length ?? 0}) - {#if linkedVarPaths.length > 0} -
- -
    - {#each linkedVarPaths as varPath (varPath)} -
  • {varPath}
  • - {/each} -
-
- {/if} - {#if !own} - {#if readOnly($operatingWorkspace)} - - This session cannot change permissions while it is in Use mode. - - {:else} - Since you do not own this item, you cannot modify its permission - {/if} - {/if} -
- {#if own && sharingDisabled} - - {writeLock ?? DEMO_RESTRICTION_HINT} - - {:else if own} -
-
- (owner = '')}> - {#snippet children({ item })} - - - {/snippet} - -
- {#key ownerKind} - + + +
+ {/if} + + + + + + Name + Access from + Role + + + + + {#each shownRows as row (`${row.source}:${row.name}`)} + {@const size = groupSizes[row.name]} + + +
+ {row.name} + {#if size !== undefined} + + +
+ +
+ {/if} +
+
+ + {#if row.folder} + {@const folderName = row.folder} + +
+ +
+ {:else} + {row.source} + {/if} +
+ + {#if row.editable && canEdit} + +
+ row.write && setMember(row.name, false) + }, + { + displayName: 'Writer', + action: () => !row.write && setMember(row.name, true) + } + ]} + placement="bottom-start" + > + {#snippet buttonReplacement()} + + {/snippet} + +
+ {:else} + {row.write ? 'Writer' : 'Viewer'} + {/if} +
+ + {#if row.editable && canEdit} +
+
+ {/if} +
+
+ {/each} + {#if inherited?.note && !query} + + + {inherited.note} + + + {inherited.source} + + + + + {:else if shownRows.length === 0} + + + {query ? `No one matches “${search.trim()}”` : 'Only workspace admins'} + + + {/if} + +
+ + {#if inUseMode} + + This session cannot change who has access while it is in Use mode. + + {:else if !own && operatingUser.current} + + Only its owner and workspace admins can change who has access. + + {:else if own && (restricted || writeLock)} + {writeLock ?? DEMO_RESTRICTION_HINT} + {/if} +
+ + + loadGroupSize(`g/${name}`)} /> + diff --git a/frontend/src/lib/components/itemSettings/PathMoveNote.svelte b/frontend/src/lib/components/itemSettings/PathMoveNote.svelte new file mode 100644 index 0000000000..b62a44bcf2 --- /dev/null +++ b/frontend/src/lib/components/itemSettings/PathMoveNote.svelte @@ -0,0 +1,34 @@ + + +{#if deployedPath && path && path !== deployedPath} + {#if movesToAnotherOwner(deployedPath, path)} + + Deploying shows who loses access and asks you to confirm. + + {:else} + + {/if} +{/if} diff --git a/frontend/src/lib/components/itemSettings/ShareButton.svelte b/frontend/src/lib/components/itemSettings/ShareButton.svelte new file mode 100644 index 0000000000..fa3851de1f --- /dev/null +++ b/frontend/src/lib/components/itemSettings/ShareButton.svelte @@ -0,0 +1,26 @@ + + + diff --git a/frontend/src/lib/components/itemSettings/ShareDialog.svelte b/frontend/src/lib/components/itemSettings/ShareDialog.svelte new file mode 100644 index 0000000000..5934fe14f9 --- /dev/null +++ b/frontend/src/lib/components/itemSettings/ShareDialog.svelte @@ -0,0 +1,425 @@ + + + + + + open, (v) => (v ? (open = true) : close())} + title="Share {name}" + kind="X" + enterConfirms={false} + fitHeight + class="sm:max-w-xl" +> + +
+ {#if moveWarning} + + {moveWarning.body} Changes here apply to the deployed {noun} right away. + + {:else if fromEditor} + + + {/if} + + {#key path} + { + onChange?.() + if (moveTo) void loadMoveLoss() + }} + /> + {/key} + + {#if isApp} +
+

Who can open the app

+ {#if app} + {#if !canWriteApp} + + Only people who can edit this app can change who can open it. + + {:else if modeRefusal} + + {#if modeRefusal === 'unsandboxed'} + This app is not sandboxed yet. Deploy it so it is sandboxed, then change who can + open it. + {:else if modeRefusal === 'builder_run_as'} + This app runs on behalf of {runAs}. Pick yourself in the editor's Settings › + Permissions and deploy it, then change who can open it. An admin can change it + without taking the app over. + {:else} + This app runs on behalf of {runAs}. Deploy it so it runs on behalf of you, then + change who can open it. An admin or a member of wm_deployers can change + it without taking the app over. + {/if} + + {/if} + {#key path} + changeApp({ execution_mode: m })} + deployed={{ + customPath: app.custom_path ?? undefined, + onCustomPathChange: (p) => changeApp({ custom_path: p }) + }} + disabled={appBusy || !canWriteApp || !!modeRefusal} + /> + {/key} + {:else} + Loading… + {/if} +
+ {:else} +
+

Who can open the {noun}

+ + The people with access above, signed in to Windmill. + + +
+ {/if} + + {#if permissions} +
+ {#snippet badge()} + {permissions.summary} + {/snippet} +
+ {permissions.summary} + {permissions.body} + {#if permissions.canEdit} + + {fromEditor + ? 'To change it, edit Settings › Permissions and deploy.' + : `To change it, edit Settings › Permissions in the ${noun}'s editor and deploy.`} + + {/if} +
+
+ {/if} + +
+ + {fromEditor ? '' : 'Changes apply right away.'} + + {#if deployLabel} + + + {:else} + + {/if} +
+
+
diff --git a/frontend/src/lib/components/itemSettings/appAccess.test.ts b/frontend/src/lib/components/itemSettings/appAccess.test.ts new file mode 100644 index 0000000000..5265d3063b --- /dev/null +++ b/frontend/src/lib/components/itemSettings/appAccess.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it, vi } from 'vitest' + +vi.mock('$lib/gen', () => ({ + AppService: { + updateApp: vi.fn(async () => ({})), + getAppLiteByPath: vi.fn(async () => ({ policy: { execution_mode: 'anonymous' } })) + } +})) + +import { AppService } from '$lib/gen' +import { modeChangeRefusal, updateDeployedAppAccess } from './appAccess' + +describe('updateDeployedAppAccess', () => { + // A policy is written whole, so sending one would put back whatever a deploy wrote since it + // was read. The mode alone is applied by the server under the deploy's row lock. + it('sends the mode alone, never a policy', async () => { + await updateDeployedAppAccess('w', 'f/ops/app', { execution_mode: 'anonymous' }) + expect(vi.mocked(AppService.updateApp).mock.calls[0][0].requestBody).toEqual({ + execution_mode: 'anonymous', + skip_draft_deletion: true + }) + }) +}) + +// The server's mode-only checks: a mismatch shows enabled buttons that answer with a 403. +describe('modeChangeRefusal', () => { + const bob = { on_behalf_of: 'u/bob', sandbox: true } + const mine = { on_behalf_of: 'u/me', sandbox: true } + const as = (o: { canPreserveRunAs?: boolean; composeOnly?: boolean }) => ({ + username: 'me', + canPreserveRunAs: false, + composeOnly: false, + ...o + }) + + it('refuses an app run as someone else to a caller who may not keep that user', () => { + expect(modeChangeRefusal(bob, as({}))).toBe('run_as') + expect(modeChangeRefusal(bob, as({ canPreserveRunAs: true }))).toBeUndefined() + expect(modeChangeRefusal(mine, as({}))).toBeUndefined() + }) + + it('refuses a builder on an app run as someone else, or not sandboxed', () => { + expect(modeChangeRefusal(bob, as({ composeOnly: true }))).toBe('run_as') + // Their deploy keeps u/bob, so deploying alone does not lift this one. + expect(modeChangeRefusal(bob, as({ composeOnly: true, canPreserveRunAs: true }))).toBe( + 'builder_run_as' + ) + expect(modeChangeRefusal({ ...mine, sandbox: undefined }, as({ composeOnly: true }))).toBe( + 'unsandboxed' + ) + expect(modeChangeRefusal(mine, as({ composeOnly: true }))).toBeUndefined() + }) +}) diff --git a/frontend/src/lib/components/itemSettings/appAccess.ts b/frontend/src/lib/components/itemSettings/appAccess.ts new file mode 100644 index 0000000000..d80b3e722e --- /dev/null +++ b/frontend/src/lib/components/itemSettings/appAccess.ts @@ -0,0 +1,73 @@ +import { AppService, type AppWithLastVersion, type Policy } from '$lib/gen' + +export type AppAccessMode = 'publisher' | 'guest' | 'anonymous' + +export const CUSTOM_PATH_RE = /^[\w-]+(\/[\w-]+)*$/ + +/** The access a policy grants, on the three rungs the Share dialog offers. `viewer` runs the + * app as its viewer, which a guest cannot be, so it shows as members-only. */ +export function accessModeOf(policy: Policy | undefined): AppAccessMode { + const mode = policy?.execution_mode + return mode === 'anonymous' ? 'anonymous' : mode === 'guest' ? 'guest' : 'publisher' +} + +/** + * Why the server refuses to change who can open a deployed app, or undefined. Mirrors the + * mode-only checks of `update_app_internal`: an app that runs as someone else is refused to a + * caller who may not keep that run-as user and to a compose-only builder, who is also refused on + * an app that is not sandboxed. A deploy by the caller lifts either refusal, except that a builder + * who may keep the run-as user (`builder_run_as`) keeps it unless they pick themselves first. + */ +export function modeChangeRefusal( + policy: Pick, + opts: { username: string | undefined; canPreserveRunAs: boolean; composeOnly: boolean } +): 'run_as' | 'builder_run_as' | 'unsandboxed' | undefined { + const runsAsSomeoneElse = !!policy.on_behalf_of && policy.on_behalf_of !== `u/${opts.username}` + if (runsAsSomeoneElse && opts.composeOnly && opts.canPreserveRunAs) return 'builder_run_as' + if (runsAsSomeoneElse && (opts.composeOnly || !opts.canPreserveRunAs)) return 'run_as' + if (opts.composeOnly && policy.sandbox !== true) return 'unsandboxed' + return undefined +} + +/** Why a custom path cannot be used, or undefined. `own` is the app's current custom path. */ +export async function customPathError( + workspace: string, + customPath: string, + own: string | undefined +): Promise { + if (!CUSTOM_PATH_RE.test(customPath)) return 'Use letters, digits, - and _, separated by /' + if (customPath !== own && (await AppService.customPathExists({ workspace, customPath }))) { + return 'Path already taken' + } + return undefined +} + +/** + * Change who can open a deployed app, or its custom URL, without deploying it. + * + * The mode is sent alone, never in a policy: the server applies it to the deployed policy under + * the lock a deploy takes, so neither overwrites the other, and keeps the run-as user. No `value` + * is sent, so no new version is written, and `skip_draft_deletion` keeps every draft. Resolves to + * the row as it is after the write. + */ +export async function updateDeployedAppAccess( + workspace: string, + path: string, + change: { execution_mode: AppAccessMode } | { custom_path: string | null } +): Promise { + if ('execution_mode' in change) { + await AppService.updateApp({ + workspace, + path, + requestBody: { execution_mode: change.execution_mode, skip_draft_deletion: true } + }) + } else { + // The backend clears the custom path on an empty string and keeps it when absent. + await AppService.updateApp({ + workspace, + path, + requestBody: { custom_path: change.custom_path ?? '', skip_draft_deletion: true } + }) + } + return AppService.getAppLiteByPath({ workspace, path }) +} diff --git a/frontend/src/lib/components/itemSettings/inheritedAccess.test.ts b/frontend/src/lib/components/itemSettings/inheritedAccess.test.ts new file mode 100644 index 0000000000..0fd0e967b3 --- /dev/null +++ b/frontend/src/lib/components/itemSettings/inheritedAccess.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest' +import type { Folder } from '$lib/gen' +import { accessLostByMove, inheritedAccess, movesToAnotherOwner } from './inheritedAccess' + +describe('inheritedAccess', () => { + it('lists folder owners, then members that are not owners, each by name', () => { + const folder = { + name: 'finance', + owners: ['g/finance'], + extra_perms: { 'u/zoe': false, 'g/finance': true, 'u/marc': true } + } as unknown as Folder + expect(inheritedAccess('f/finance/sync', folder)).toEqual({ + source: 'Folder finance', + rows: [ + { name: 'g/finance', write: true }, + { name: 'u/marc', write: true }, + { name: 'u/zoe', write: false } + ] + }) + }) + + it('names the folder without listing it when it could not be read', () => { + const other = { name: 'ops', owners: ['u/x'], extra_perms: {} } as unknown as Folder + expect(inheritedAccess('f/finance/sync', other)).toEqual({ + source: 'Folder finance', + rows: [], + note: 'Members of folder finance' + }) + }) + + it('names the owning user or group', () => { + expect(inheritedAccess('u/alice/sync', undefined)).toEqual({ + source: 'Owner', + rows: [{ name: 'u/alice', write: true }] + }) + expect(inheritedAccess('g/ops/sync', undefined)?.source).toBe('Owning group') + }) +}) + +describe('accessLostByMove', () => { + const folder = (name: string, extra_perms: Record) => + ({ name, owners: [], extra_perms }) as unknown as Folder + + it('takes access from whom neither the new folder nor the item itself covers', () => { + const from = inheritedAccess( + 'f/sales/sync', + folder('sales', { 'g/sales': true, 'u/bob': false, 'u/dan': true, 'u/eve': true }) + ) + const to = inheritedAccess('f/ops/sync', folder('ops', { 'u/dan': false, 'u/eve': true })) + expect(accessLostByMove(from, to, { 'u/bob': false })).toEqual({ + lost: ['g/sales'], + demoted: ['u/dan'] + }) + expect(movesToAnotherOwner('f/sales/sync', 'f/sales/sync_v2')).toBe(false) + expect(movesToAnotherOwner('f/sales/sync', 'u/bob/sync')).toBe(true) + }) + + it('keeps a user whom a group reaching the item after the move covers', () => { + const from = inheritedAccess('f/sales/sync', folder('sales', { 'u/bob': true, 'u/eve': true })) + const to = inheritedAccess('f/ops/sync', folder('ops', { 'g/ops': false })) + expect(accessLostByMove(from, to, {}, { 'g/ops': ['bob'] })).toEqual({ + lost: ['u/eve'], + demoted: ['u/bob'] + }) + }) + + it('says nothing when a folder could not be read', () => { + const from = inheritedAccess('f/sales/sync', undefined) + const to = inheritedAccess('u/bob/sync', undefined) + expect(accessLostByMove(from, to, {})).toBeUndefined() + }) +}) diff --git a/frontend/src/lib/components/itemSettings/inheritedAccess.ts b/frontend/src/lib/components/itemSettings/inheritedAccess.ts new file mode 100644 index 0000000000..c3819702ac --- /dev/null +++ b/frontend/src/lib/components/itemSettings/inheritedAccess.ts @@ -0,0 +1,105 @@ +import type { Folder } from '$lib/gen' + +export type AccessRow = { + /** `u/name` or `g/name`. */ + name: string + write: boolean +} + +/** Who reaches an item through its path, and where that access comes from. */ +export type InheritedAccess = { + /** Shown in the access list's "Access from" column. */ + source: string + rows: AccessRow[] + /** Shown in place of the rows when they cannot be listed. */ + note?: string +} + +export function byName(a: AccessRow, b: AccessRow): number { + return a.name.localeCompare(b.name) +} + +/** The folder a path lives in, or undefined for a `u/` or `g/` path. */ +export function folderOfPath(path: string): string | undefined { + const parts = path.split('/') + return parts[0] === 'f' && parts.length >= 2 ? parts[1] : undefined +} + +/** The owner a path names, such as `u/alice` or `f/team`. */ +export function ownerOfPath(path: string): string { + return path.split('/').slice(0, 2).join('/') +} + +/** Whether moving an item between these paths changes who reaches it through its path. */ +export function movesToAnotherOwner(from: string, to: string): boolean { + return !!from && !!to && ownerOfPath(from) !== ownerOfPath(to) +} + +/** An owner as a sentence names it: "folder team", or the `u/` or `g/` name. */ +export function ownerLabel(path: string): string { + const folder = folderOfPath(path) + return folder !== undefined ? `folder ${folder}` : ownerOfPath(path) +} + +/** What moving an item to another owner takes away: the users and groups that reach it through + * the old owner and through neither the new one nor the item's own members, and the writers left + * with a viewer's role. `groupMembers` lists the usernames in each group that reaches the item + * after the move, so that a user one of them covers keeps access; a group missing from it counts + * as empty, which can only overstate the loss. Undefined when either owner's members could not be + * read. */ +export function accessLostByMove( + from: InheritedAccess | undefined, + to: InheritedAccess | undefined, + members: Record, + groupMembers: Record = {} +): { lost: string[]; demoted: string[] } | undefined { + if (!from || !to || from.note !== undefined || to.note !== undefined) return undefined + const after = new Map(to.rows.map((r) => [r.name, r.write])) + for (const [name, write] of Object.entries(members)) after.set(name, after.get(name) || write) + for (const [name, write] of [...after]) { + for (const username of groupMembers[name] ?? []) { + after.set(`u/${username}`, after.get(`u/${username}`) || write) + } + } + const lost: string[] = [] + const demoted: string[] = [] + for (const row of from.rows) { + const write = after.get(row.name) + if (write === undefined) lost.push(row.name) + else if (row.write && !write) demoted.push(row.name) + } + return { lost, demoted } +} + +/** Who reaches an item through its path rather than through its own extra_perms: the folder's + * owners and members for `f/`, the owning user or group for `u/` and `g/`. Workspace admins + * reach everything and are not listed. `folder` is the item's folder, undefined when it could + * not be read. Undefined for a name that is not a path, such as a volume's. */ +export function inheritedAccess( + path: string, + folder: Folder | undefined +): InheritedAccess | undefined { + const parts = path.split('/') + const folderName = folderOfPath(path) + if (folderName !== undefined) { + const source = `Folder ${folderName}` + if (folder?.name !== folderName) { + return { source, rows: [], note: `Members of folder ${folderName}` } + } + // Sorted by name: the API returns members in jsonb key order, shortest name first, which + // reads as no order at all in a folder shared with many people. + const owners = folder.owners.map((owner) => ({ name: owner, write: true })).sort(byName) + const members = Object.entries(folder.extra_perms ?? {}) + .filter(([member]) => !folder.owners.includes(member)) + .map(([member, write]) => ({ name: member, write: !!write })) + .sort(byName) + return { source, rows: [...owners, ...members] } + } + if ((parts[0] === 'u' || parts[0] === 'g') && parts.length >= 2) { + return { + source: parts[0] === 'u' ? 'Owner' : 'Owning group', + rows: [{ name: `${parts[0]}/${parts[1]}`, write: true }] + } + } + return undefined +} diff --git a/frontend/src/lib/components/itemSettings/onBehalfOf.test.ts b/frontend/src/lib/components/itemSettings/onBehalfOf.test.ts index 488f1fb6a4..7317ef20ba 100644 --- a/frontend/src/lib/components/itemSettings/onBehalfOf.test.ts +++ b/frontend/src/lib/components/itemSettings/onBehalfOf.test.ts @@ -1,5 +1,9 @@ import { describe, it, expect } from 'vitest' -import { deployAsksOnBehalfOf, deployedPermissionedAs } from './onBehalfOf' +import { + deployAsksOnBehalfOf, + deployOnBehalfOfQuestion, + deployedPermissionedAs +} from './onBehalfOf' // The deploy dialog names who the backend will leave the item running on behalf of, and asks only // when that differs from the deployed version. @@ -49,4 +53,42 @@ describe('onBehalfOf', () => { // The backend replaces the user with a deployer who may not preserve it. expect(deployAsksOnBehalfOf('flow', { user: member, ...bot, ...deployedAsBot })).toBe(true) }) + + it('asks to run on behalf of someone or to stop, and says when the user is the deployed one', () => { + const held = { + email: undefined, + permissionedAs: undefined, + savedEmail: undefined, + savedPermissionedAs: undefined, + isNew: true + } + expect(deployOnBehalfOfQuestion('app', admin, held)).toMatchObject({ + title: 'Run this app on behalf of u/admin (you)?', + folderDefaultNotMe: false + }) + expect( + deployOnBehalfOfQuestion('app', admin, { ...held, folderDefault: 'u/folder' }) + ).toMatchObject({ title: 'Run this app on behalf of u/folder?', folderDefaultNotMe: true }) + expect( + deployOnBehalfOfQuestion('flow', admin, { + ...held, + savedPermissionedAs: 'u/bot', + isNew: false + }) + ).toMatchObject({ stops: true, title: 'Stop running this flow on behalf of u/bot?' }) + expect( + deployOnBehalfOfQuestion('flow', admin, { + ...held, + email: 'bot@x.dev', + permissionedAs: 'u/bot', + savedPermissionedAs: 'u/bot', + isNew: false + }) + ).toMatchObject({ stops: false, runsAs: 'u/bot', unchanged: true }) + expect(deployOnBehalfOfQuestion('flow', admin, held)).toMatchObject({ + required: false, + on: false, + title: 'Deploy this flow?' + }) + }) }) diff --git a/frontend/src/lib/components/itemSettings/onBehalfOf.ts b/frontend/src/lib/components/itemSettings/onBehalfOf.ts index d1c7cad268..f2fdd37157 100644 --- a/frontend/src/lib/components/itemSettings/onBehalfOf.ts +++ b/frontend/src/lib/components/itemSettings/onBehalfOf.ts @@ -58,6 +58,58 @@ export function deployAsksOnBehalfOf( ) } +/** What a deploy asks about the user an item runs on behalf of: the question, whether the item + * must run on behalf of someone, whether it does, whether the deploy stops a flow or script + * running on behalf of the deployed user, and who it runs as otherwise. `email` and + * `permissionedAs` are the user the item holds, `saved*` the deployed one. */ +export function deployOnBehalfOfQuestion( + kind: 'flow' | 'script' | 'app', + user: DeployingUser, + held: { + email: string | undefined + permissionedAs: string | undefined + savedEmail: string | undefined + savedPermissionedAs: string | undefined + isNew: boolean + folderDefault?: string + } +): { + title: string + required: boolean + on: boolean + stops: boolean + runsAs: string | undefined + savedUser: string | undefined + /** The deploy leaves the deployed user as it is. */ + unchanged: boolean + /** The item takes its folder's default user, who is not the deployer. */ + folderDefaultNotMe: boolean +} { + const me = user?.username ? `u/${user.username}` : undefined + const savedUser = held.savedPermissionedAs ?? held.savedEmail + // The backend gives a new item in a folder with a default user that user unless the deploy + // names one, so only a flow or script outside that case can deploy with the setting off. + const required = kind === 'app' || !!held.folderDefault + const on = required || !!held.email + const stops = !on && !!savedUser + const runsAs = deployedPermissionedAs(user, held.permissionedAs, held.folderDefault) + const who = !runsAs ? 'you' : runsAs === me ? `${runsAs} (you)` : runsAs + return { + title: on + ? `Run this ${kind} on behalf of ${who}?` + : stops + ? `Stop running this ${kind} on behalf of ${savedUser}?` + : `Deploy this ${kind}?`, + required, + on, + stops, + runsAs, + savedUser, + unchanged: !held.isNew && !!held.savedPermissionedAs && runsAs === held.savedPermissionedAs, + folderDefaultNotMe: !!held.folderDefault && runsAs === held.folderDefault && runsAs !== me + } +} + /** What keeps lending the publisher's access to an app's viewers safe. */ export function appOnBehalfOfTooltip(rawApp: boolean): string { return `To keep this safe, the app can call only the runnables it was deployed with, and viewers can't override their static inputs.${rawApp ? " Inline runnables can instead be set to read data tables and object storage with the viewer's own access." : ''}` diff --git a/frontend/src/lib/components/itemSettings/sharingTelemetry.ts b/frontend/src/lib/components/itemSettings/sharingTelemetry.ts new file mode 100644 index 0000000000..62a82322fb --- /dev/null +++ b/frontend/src/lib/components/itemSettings/sharingTelemetry.ts @@ -0,0 +1,14 @@ +import { logFeatureUsage } from '$lib/utils/featureUsage' + +/** Where the Share dialog was opened from. `deploy` is a deploy that moves the item to another + * owner, which opens it to confirm; `home` is a card in Home's favorites and recent items. */ +export type ShareOpenSource = 'editor_header' | 'list' | 'detail' | 'deploy' | 'home' + +export function logShareOpen(source: ShareOpenSource) { + logFeatureUsage('sharing', 'open', { key: source }) +} + +/** How a first-deploy dialog ended. */ +export function logFirstDeploy(outcome: 'deployed' | 'cancelled') { + logFeatureUsage('sharing', 'first_deploy', { key: outcome }) +} diff --git a/frontend/src/lib/components/random_positive_adjetive.ts b/frontend/src/lib/components/random_positive_adjetive.ts index ce915f7ae7..bc9b26df6e 100644 --- a/frontend/src/lib/components/random_positive_adjetive.ts +++ b/frontend/src/lib/components/random_positive_adjetive.ts @@ -959,4 +959,11 @@ const adjectives = ["abundant", "youthful", "zippy"] -export function random_adj() { return adjectives[Math.floor(Math.random() * adjectives.length)] } \ No newline at end of file +export function random_adj() { return adjectives[Math.floor(Math.random() * adjectives.length)] } +/** Whether a path's last segment is a placeholder name, `_`, rather than one + * someone chose. */ +export function isPlaceholderName(path: string): boolean { + const name = path.split('/').pop() ?? '' + const m = /^([a-z]+)_(flow|script|app)$/.exec(name) + return !!m && adjectives.includes(m[1]) +} diff --git a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte index b94f5ed62d..ccb0a5a4e4 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte @@ -34,8 +34,16 @@ Redo, Settings, Undo, + UserPlus, WandSparkles } from 'lucide-svelte' + import ShareDialog from '$lib/components/itemSettings/ShareDialog.svelte' + import FirstDeployDialog, { + applyFirstDeployMembers + } from '$lib/components/itemSettings/FirstDeployDialog.svelte' + import ShareButton from '$lib/components/itemSettings/ShareButton.svelte' + import { accessModeOf } from '$lib/components/itemSettings/appAccess' + import { movesToAnotherOwner } from '$lib/components/itemSettings/inheritedAccess' import { onDestroy, untrack, type Snippet } from 'svelte' import { orderedJsonStringify, type Value, replaceFalseWithUndefined } from '../../utils' import { random_adj } from '$lib/components/random_positive_adjetive' @@ -61,7 +69,7 @@ import DeployButton from '$lib/components/DeployButton.svelte' import type { Runnable } from './RawAppInlineScriptRunnable.svelte' import { updateRawAppPolicy } from './rawAppPolicy' - import { policyForUpdate, publishAccessMode } from '$lib/components/apps/editor/publishAccessMode' + import { withoutSharedPolicySettings } from '../apps/editor/appDraftSettings' import { saveRawAppFork } from './forkRawApp.svelte' import { aiChatManager } from '../copilot/chat/AIChatManager.svelte' import { getContext } from 'svelte' @@ -354,7 +362,6 @@ let settingsOpen = $state(false) let settingsDrawer: AppSettingsDrawer | undefined = $state() - let deployRefused = $state(false) let historyBrowserDrawerOpen = $state(false) let recordDrawer = $state(undefined) let deploymentMsg: string | undefined = $state(undefined) @@ -402,25 +409,17 @@ return updateRawAppPolicy(runnables, policy) } - async function setAccessMode(mode: NonNullable) { - await publishAccessMode(opWorkspace!, appPath, mode) - if (savedApp) savedApp.policy = { ...savedApp.policy, execution_mode: mode } - sendUserToast( - mode == 'anonymous' - ? 'App require no login to be accessed' - : 'App require login and read-access' - ) - } - - async function createApp(path: string) { + /** Resolves to whether the app was created. */ + async function createApp(path: string): Promise { if (!app) { sendUserToast(`App hasn't been loaded yet`, true) - return + return false } if (!policy.execution_mode) { policy.execution_mode = 'publisher' } - setDeployedOnBehalfOf(policy, actingUser, folderDefault.value) + // Read for the path being created: the first-deploy dialog may have just chosen it. + setDeployedOnBehalfOf(policy, actingUser, await folderDefault.refetch()) try { const { js, css } = await getBundle() const deployedPolicy = await policyWithTriggerables() @@ -472,8 +471,10 @@ } onSavedNewAppPath?.(path) onDeploy?.({ path }) + return true } catch (e) { sendUserToast(`Error creating app: ${e.body ?? e.message}`, true) + return false } } @@ -651,9 +652,6 @@ return } const { js, css } = await getBundle() - if (!policy.execution_mode) { - policy.execution_mode = 'publisher' - } setDeployedOnBehalfOf(policy, actingUser) const deployedPolicy = await policyWithTriggerables() const deployed = await AppService.updateAppRaw({ @@ -663,14 +661,14 @@ app: { value: app!, summary: summary, - policy: policyForUpdate(deployedPolicy), + // Without the mode, which the Share dialog sets: the server keeps the deployed one, + // read under the row lock a mode change also takes. + policy: withoutSharedPolicySettings(deployedPolicy), path: npath, deployment_message: deploymentMsg, preserve_on_behalf_of: true, - // custom_path requires admin so to accept update without it, we need to send as undefined when non-admin (when undefined, it will be ignored) - // it also means that customPath needs to be set to '' instead of undefined to unset it (when admin) - custom_path: - actingUser?.is_admin || actingUser?.is_super_admin ? (customPath ?? '') : undefined, + // Absent keeps the custom URL, which the Share dialog sets. + custom_path: undefined, labels }, js, @@ -724,18 +722,59 @@ settingsDrawer?.openAt(setting) } + const neverDeployed = $derived(newApp || appPath == '' || savedApp?.no_deployed === true) + let shareDialog: ShareDialog | undefined = $state() + let firstDeployDialog: FirstDeployDialog | undefined = $state() + + function openShare() { + shareDialog?.openDialog('raw_app', appPath, { + source: 'editor_header', + fromEditor: true, + stagedPath: newEditedPath + }) + } + + // Chosen in the first-deploy dialog, added once the run-as confirmation has created the app. + let firstDeployMembers: Record = {} + async function deploy(message?: string) { if (app == undefined) return - if (pathError != '' || customPathError != '') { - deployRefused = true - openSettings(pathError != '' ? undefined : 'custom-url') + if (pathError != '') { + openSettings() return } deploymentMsg = message + firstDeployMembers = {} + if (isNewApp && ownsPageHeader) { + // The dialog also asks who the app runs on behalf of, for the path it chose. + const choice = await firstDeployDialog?.ask({ + kind: 'raw_app', + summary, + path: newEditedPath, + appMode: accessModeOf(policy), + runAs: { + email: policy.on_behalf_of_email, + permissionedAs: policy.on_behalf_of, + targetWorkspace: opWorkspace ?? '' + } + }) + if (!choice) return + summary = choice.summary + newEditedPath = choice.path + policy.execution_mode = choice.appMode + if (choice.runAs) { + policy.on_behalf_of_email = choice.runAs.email + policy.on_behalf_of = choice.runAs.permissionedAs + } + deploymentMsg = choice.message + firstDeployMembers = choice.members + await deployNow() + return + } // Compares against the user deployed right now; a failed lookup asks rather than trusting // the loaded one. deployedRunAs = isNewApp ? undefined : await fetchDeployedRunAs(opWorkspace!, appPath) - if ( + const asksRunAs = (!isNewApp && !deployedRunAs) || // Asks while the folder default is loading: the backend would apply it unconfirmed. folderDefault.loading || @@ -747,7 +786,19 @@ savedPermissionedAs: deployedRunAs?.on_behalf_of, folderDefault: folderDefault.value }) + if ( + shareDialog && + movesToAnotherOwner(appPath, newEditedPath) && + !(await shareDialog.confirmMove( + 'raw_app', + appPath, + newEditedPath, + asksRunAs ? 'Next' : 'Deploy' + )) ) { + return + } + if (asksRunAs) { deployDialogOpen = true return } @@ -756,7 +807,11 @@ async function deployNow() { if (isNewApp) { - await createApp(newEditedPath) + const members = firstDeployMembers + const workspace = opWorkspace! + if (await createApp(newEditedPath)) { + await applyFirstDeployMembers(workspace, 'raw_app', newEditedPath, members) + } } else { await handleUpdateApp(newEditedPath) } @@ -848,10 +903,27 @@ icon: Settings, action: () => openSettings() }, + ...(ownsPageHeader + ? [ + { + displayName: 'Share', + icon: UserPlus, + disabled: neverDeployed, + action: openShare + } + ] + : []), { displayName: 'Public URL', icon: Globe, - action: () => openSettings('access') + disabled: neverDeployed, + action: async () => { + const secretUrl = await AppService.getPublicSecretOfApp({ + workspace: opWorkspace!, + path: appPath + }) + window.open(`${window.location.origin}/public/${opWorkspace}/${secretUrl}`, '_blank') + } }, { displayName: 'Export', @@ -875,11 +947,11 @@ } ]) + let customPath = $state(savedApp?.custom_path) // Derived, so a draft synced in from another session reaches the header; an edit here overrides // the value until the next one arrives. - let customPath = $state(savedApp?.custom_path) - let customPathError = $state('') let labels = $derived(initialLabels) + let settingsHaveErrors = $derived(pathError != '') let jobsDrawerOpen = $state(false) @@ -897,8 +969,6 @@ labels }) ) - - let settingsHaveErrors = $derived(pathError != '' || customPathError != '') +{#if ownsPageHeader} + { + policy.execution_mode = row.policy.execution_mode + customPath = row.custom_path ?? undefined + if (savedApp) { + savedApp.policy = { ...savedApp.policy, execution_mode: row.policy.execution_mode } + savedApp.custom_path = row.custom_path ?? undefined + } + }} + /> + +{/if} + (historyBrowserDrawerOpen = false)}> onRestore?.(e.detail)} {appPath} /> @@ -1235,7 +1316,7 @@ - {#snippet fallback()} @@ -1253,6 +1334,14 @@ {/if} {/snippet} + {#if ownsPageHeader && !phoneTopbar} + + {/if} { shareModal?.openDrawer?.(path, 'resource') } diff --git a/frontend/src/lib/components/schedules/SchedulesList.svelte b/frontend/src/lib/components/schedules/SchedulesList.svelte index b0aeaab38e..e3d1b7f8b6 100644 --- a/frontend/src/lib/components/schedules/SchedulesList.svelte +++ b/frontend/src/lib/components/schedules/SchedulesList.svelte @@ -34,9 +34,9 @@ Play, Plus, SearchX, - Shield, Trash, - TriangleAlert + TriangleAlert, + UserPlus } from 'lucide-svelte' import { goto } from '$lib/navigation' import { sendUserToast } from '$lib/toast' @@ -652,8 +652,8 @@ } }, { - displayName: 'Permissions', - icon: Shield, + displayName: 'Share', + icon: UserPlus, action: () => { shareModal?.openDrawer(path, 'schedule') } diff --git a/frontend/src/lib/components/triggers/TriggerList.svelte b/frontend/src/lib/components/triggers/TriggerList.svelte index ee1d6a88f4..1fa1d7c66c 100644 --- a/frontend/src/lib/components/triggers/TriggerList.svelte +++ b/frontend/src/lib/components/triggers/TriggerList.svelte @@ -39,9 +39,9 @@ Pen, Plus, Route, - Shield, Trash, - Unplug + Unplug, + UserPlus } from 'lucide-svelte' import CenteredPage from '$lib/components/CenteredPage.svelte' import { Alert, Badge, Button, EmptyState, Skeleton } from '$lib/components/common' @@ -830,8 +830,8 @@ href: `/audit_logs?resource=${path}` }, { - displayName: 'Permissions', - icon: Shield, + displayName: 'Share', + icon: UserPlus, action: () => { shareModal?.openDrawer(path, config.shareKind as any) } diff --git a/frontend/src/lib/components/useFolderDefaultPermissionedAs.svelte.ts b/frontend/src/lib/components/useFolderDefaultPermissionedAs.svelte.ts index ab59693def..cc44f9a3f2 100644 --- a/frontend/src/lib/components/useFolderDefaultPermissionedAs.svelte.ts +++ b/frontend/src/lib/components/useFolderDefaultPermissionedAs.svelte.ts @@ -61,9 +61,12 @@ export function useFolderDefaultPermissionedAs( get loading() { const ws = workspace() return ( - folderResource.loading || - (!!ws && !!pathGetter()?.startsWith('f/') && !acting.resolved(ws)) + folderResource.loading || (!!ws && !!pathGetter()?.startsWith('f/') && !acting.resolved(ws)) ) + }, + /** Reads the default for the path as it is now: `value` follows a path change a fetch later. */ + refetch() { + return folderResource.refetch() } } } diff --git a/frontend/src/lib/components/variables/VariablesList.svelte b/frontend/src/lib/components/variables/VariablesList.svelte index e3e9640155..57ca58aae9 100644 --- a/frontend/src/lib/components/variables/VariablesList.svelte +++ b/frontend/src/lib/components/variables/VariablesList.svelte @@ -48,7 +48,7 @@ Link, Pen, RefreshCw, - Shield, + UserPlus, Trash, Building, CalendarClock, @@ -647,11 +647,11 @@ ] : []), { - displayName: 'Permissions', + displayName: 'Share', action: () => { shareModal?.openDrawer(path, 'variable') }, - icon: Shield + icon: UserPlus }, ...(account != undefined ? [ diff --git a/frontend/src/lib/rawAppDeploy.test.ts b/frontend/src/lib/rawAppDeploy.test.ts new file mode 100644 index 0000000000..6d3116543e --- /dev/null +++ b/frontend/src/lib/rawAppDeploy.test.ts @@ -0,0 +1,47 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('$lib/gen', () => ({ + AppService: { + getAppByPath: vi.fn(async () => ({ + policy: { execution_mode: 'anonymous' }, + draft: { files: {}, runnables: {}, policy: { execution_mode: 'anonymous' } } + })), + existsApp: vi.fn(async () => true), + updateAppRaw: vi.fn(async () => {}) + } +})) +vi.mock('$lib/components/copilot/chat/global/rawAppBundlerBridge', () => ({ + bundleRawAppDraft: vi.fn(async () => ({ js: '', css: '' })) +})) +vi.mock('$lib/components/raw_apps/rawAppPolicy', () => ({ + updateRawAppPolicy: vi.fn(async (_runnables: unknown, policy: unknown) => ({ ...(policy as {}) })) +})) + +import { AppService } from '$lib/gen' +import { deployRawAppDraft, deployRawAppValue } from './rawAppDeploy' + +// Who can open a deployed app is set from the Share dialog. A deploy stating a mode would put back +// the one it was given, so an update states none and the server keeps the deployed one. +describe('raw app deploys', () => { + beforeEach(() => { + vi.mocked(AppService.updateAppRaw).mockClear() + }) + + const sentPolicy = () => + (vi.mocked(AppService.updateAppRaw).mock.calls[0][0].formData.app as any).policy + + it('deploy a value without stating a mode', async () => { + await deployRawAppValue({ + workspace: 'w', + path: 'f/ops/app', + value: { files: {}, runnables: {} }, + policy: { execution_mode: 'anonymous' } as any + }) + expect(sentPolicy()).not.toHaveProperty('execution_mode') + }) + + it('deploy a draft without stating a mode', async () => { + await deployRawAppDraft('w', 'f/ops/app') + expect(sentPolicy()).not.toHaveProperty('execution_mode') + }) +}) diff --git a/frontend/src/lib/rawAppDeploy.ts b/frontend/src/lib/rawAppDeploy.ts index ce68c1091e..c6ef3b68da 100644 --- a/frontend/src/lib/rawAppDeploy.ts +++ b/frontend/src/lib/rawAppDeploy.ts @@ -12,11 +12,10 @@ */ import { AppService } from '$lib/gen' import type { Policy } from '$lib/gen' -import { isAdminIn } from '$lib/user' import { bundleRawAppDraft } from '$lib/components/copilot/chat/global/rawAppBundlerBridge' import type { AppDraftValue } from '$lib/components/copilot/chat/global/workspaceItems' import { updateRawAppPolicy } from '$lib/components/raw_apps/rawAppPolicy' -import { policyForUpdate } from '$lib/components/apps/editor/publishAccessMode' +import { withoutSharedPolicySettings } from '$lib/components/apps/editor/appDraftSettings' import { DEFAULT_DATA as DEFAULT_RAW_APP_DATA } from '$lib/components/raw_apps/dataTableRefUtils' import { appSourceToDraftValue, @@ -34,7 +33,6 @@ export async function deployRawAppValue({ value, summary, policy: currentPolicy, - customPath, deploymentMessage, allowKindChange }: { @@ -43,7 +41,6 @@ export async function deployRawAppValue({ value: any summary?: string policy?: Policy - customPath?: string | null deploymentMessage?: string /** Let this deploy turn a low-code app into a raw one. Off for every ordinary * deploy — see the backend's `allow_kind_change`. */ @@ -60,7 +57,6 @@ export async function deployRawAppValue({ const bundle = await bundleRawAppDraft({ workspace, files }) - const isAdmin = await isAdminIn(workspace) await AppService.updateAppRaw({ workspace, path, @@ -70,10 +66,12 @@ export async function deployRawAppValue({ // version can still carry the pre-`data` datatable shapes. value: { files, runnables, data: normalizeRawAppData(plainValue) }, summary: summary ?? '', - policy: policyForUpdate(policy), + // Without the mode, which the Share dialog sets: the server keeps the deployed one, + // read under the row lock a mode change also takes. + policy: withoutSharedPolicySettings(policy), deployment_message: deploymentMessage, - // custom_path changes require admin (see deployRawAppDraft). - custom_path: isAdmin ? (customPath ?? '') : undefined, + // Absent keeps the custom URL, which the Share dialog sets. + custom_path: undefined, preserve_on_behalf_of: policy.on_behalf_of ? true : undefined, allow_kind_change: allowKindChange || undefined }, @@ -122,13 +120,8 @@ export async function deployRawAppDraft( const summary = value.summary ?? '' if (await AppService.existsApp({ workspace, path })) { - // custom_path changes require admin. Mirror RawAppEditorHeader's update path: - // admins send the draft's value (`''` to clear), non-admins send undefined so - // the backend ignores it and preserves the existing route — otherwise a - // non-admin deploying a draft for an app that has a custom route would hit - // RequireAdmin (the deployed custom_path is sent via the appSourceToDraftValue - // fallback even when unchanged). - const isAdmin = await isAdminIn(workspace) + // Who can open the app and its custom URL are set from the Share dialog: the update states + // neither, and the server keeps the deployed ones. await AppService.updateAppRaw({ workspace, path, @@ -137,9 +130,9 @@ export async function deployRawAppDraft( path: targetPath, value: rawAppValue, summary, - policy: policyForUpdate(policy), + policy: withoutSharedPolicySettings(policy), deployment_message: deploymentMessage, - custom_path: isAdmin ? (value.custom_path ?? '') : undefined, + custom_path: undefined, labels: value.labels, // Preserve the policy's on_behalf_of: this draft-deploy path has no // on-behalf-of selector, so without the flag the backend resets it to diff --git a/frontend/src/lib/utils_draft_deploy.ts b/frontend/src/lib/utils_draft_deploy.ts index 7a5bf66553..76556c4b27 100644 --- a/frontend/src/lib/utils_draft_deploy.ts +++ b/frontend/src/lib/utils_draft_deploy.ts @@ -46,9 +46,9 @@ import { appDraftSettings, draftOrDeployedSettings, policySettings, - withDraftPolicySettings + withDraftPolicySettings, + withoutSharedPolicySettings } from '$lib/components/apps/editor/appDraftSettings' -import { policyForUpdate } from '$lib/components/apps/editor/publishAccessMode' import { invalidateWorkspaceDrafts } from '$lib/workspaceDrafts.svelte' import { invalidateWorkspaceComparison } from '$lib/workspaceComparison' import { setLocalDraftHint } from '$lib/localDraftHints.svelte' @@ -350,11 +350,14 @@ export async function getDraftDiffValues( // A staged rename (`draft_path`) changes where deploy lands the app — // compare it as `path` on both sides so a rename-only draft diffs. const rawDraftPath = (r.draft?.draft_path as string | undefined) ?? r.path + // Who can open a deployed app is set from the Share dialog, never drafted. + const shared = (v: Record) => + draftOnly ? v : { ...v, policy: withoutSharedPolicySettings(v.policy) } return { deployed: draftOnly ? canonicalRawAppDiffValue({}) - : { ...canonicalRawAppDiffValue(r), path: r.path }, - draft: { ...canonicalRawAppDiffValue(r.draft ?? r), path: rawDraftPath }, + : shared({ ...canonicalRawAppDiffValue(r), path: r.path }), + draft: shared({ ...canonicalRawAppDiffValue(r.draft ?? r), path: rawDraftPath }), hasDraft: r.draft != null, noDeployed: r.no_deployed === true } @@ -613,18 +616,18 @@ export async function deployDraft( appValue, withDraftPolicySettings(deployedPolicy, settings.policy) ) - // custom_path requires admin on update; non-admins send undefined so the - // backend preserves the existing route. The draft has no custom_path, so - // admins fall back to the deployed route (`''` when none). - const isAdmin = await isAdminIn(workspace) const requestBody = { value: appValue, summary: parts.summary ?? r.summary ?? '', - policy: draftOnly ? policy : policyForUpdate(policy), + // An update states no mode: the Share dialog sets it, and the server keeps the + // deployed one. + policy: draftOnly ? policy : withoutSharedPolicySettings(policy), // Honor the draft's intended path; `draft_path` holds the user-typed path // for a never-deployed app parked at a `u/{user}/draft_{uuid}` storage key. path: parts.draftPath ?? r.path ?? path, - custom_path: isAdmin ? (r.custom_path ?? '') : undefined, + // A deploy never writes the custom URL: the Share dialog sets it, and an update + // without one keeps it. + custom_path: undefined, labels: settings.labels, deployment_message: deploymentMessage, // Preserve the drafted on_behalf_of (the backend resets it to the deploying diff --git a/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte index 09a1e6ec01..e4e47b69b7 100644 --- a/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte @@ -26,6 +26,7 @@ } from '$lib/components/raw_apps/dataTableRefUtils' import { importStore } from '$lib/components/apps/store' import { UserDraft, draftValuesEqual } from '$lib/userDraft.svelte' + import { withoutSharedPolicySettings } from '$lib/components/apps/editor/appDraftSettings' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { usePageDraftSync } from '$lib/components/usePageDraftSync.svelte' import { OtherUserDraftLoad } from '$lib/components/otherUserDraftLoad.svelte' @@ -132,12 +133,15 @@ void summary void pendingDraftPath void pendingDraftSettings + // Who can open a deployed app is set from the Share dialog, not drafted; the custom URL is + // the deployed one. + const deployed = deployedBaseline !== undefined draftSync.draft = { files: currentFiles, runnables, data, summary, - policy, + policy: deployed ? withoutSharedPolicySettings(policy) : policy, custom_path: savedApp?.custom_path, labels: pendingDraftSettings ? pendingDraftSettings.labels : (labels ?? []), parent_version: parentVersion, @@ -373,7 +377,7 @@ runnables: backendApp.value?.runnables ?? {}, data: extractDataConfig(backendApp.value) ?? { ...DEFAULT_DATA }, summary: backendApp.summary ?? '', - policy: backendApp.policy, + policy: withoutSharedPolicySettings(backendApp.policy), custom_path: backendApp.custom_path, labels: backendApp.labels ?? [], parent_version: parentVersion @@ -420,9 +424,13 @@ data: savedRawAppDraft.data ?? backendApp.value?.data } if (savedRawAppDraft.summary !== undefined) backendApp.summary = savedRawAppDraft.summary - if (savedRawAppDraft.policy !== undefined) backendApp.policy = savedRawAppDraft.policy - if (savedRawAppDraft.custom_path !== undefined) - backendApp.custom_path = savedRawAppDraft.custom_path + // Who can open the app and its custom URL stay the deployed ones: a draft saved before + // a Share change must not revert it. + if (savedRawAppDraft.policy !== undefined) + backendApp.policy = { + ...savedRawAppDraft.policy, + execution_mode: backendApp.policy.execution_mode + } if (savedRawAppDraft.labels !== undefined) backendApp.labels = savedRawAppDraft.labels } const backendApp_ = structuredClone(stateSnapshot(backendApp)) @@ -431,7 +439,8 @@ value: backendApp_.value as any, path: backendApp_.path, // The deployed policy, not the draft's swapped in above: the header and the settings - // measure what a deploy changes against it. + // measure what a deploy changes against it. A deployed app's custom path is never + // swapped in, so the row's is the deployed one. policy: deployedBaseline ? structuredClone(stateSnapshot(deployedBaseline.policy)) : backendApp_.policy, @@ -482,7 +491,7 @@ runnables, data, summary, - policy, + policy: deployedBaseline ? withoutSharedPolicySettings(policy) : policy, custom_path: savedApp?.custom_path, labels: labels ?? [], parent_version: parentVersion,