feat: create service accounts at deploy and check what they can read

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-11-02 00:29:01 -08:00
co-authored by Claude Opus 5.5
parent 19d20dacf6
commit cd41d8e070
23 changed files with 1423 additions and 218 deletions
@@ -1741,6 +1741,8 @@
kind={diff.kind}
canPreserve={canPreserveOnBehalfOf}
customValue={customOnBehalfOf[key]?.permissionedAs}
size="sm"
class="w-44"
/>
{/if}
{#if diff.kind === 'raw_app'}
@@ -643,6 +643,8 @@
kind={item.kind}
canPreserve={canPreserveOnBehalfOf}
customValue={customOnBehalfOf[statusPath]?.permissionedAs}
size="sm"
class="w-44"
/>
{/if}
+17 -1
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import DeployOnBehalfOfDialog from '$lib/components/itemSettings/DeployOnBehalfOfDialog.svelte'
import { dropStalePending } from '$lib/components/access/serviceAccounts.svelte'
import { deployAsksOnBehalfOf } from '$lib/components/itemSettings/onBehalfOf'
import { movesToAnotherOwner } from '$lib/components/itemSettings/inheritedAccess'
import { useFolderDefaultPermissionedAs } from '$lib/components/useFolderDefaultPermissionedAs.svelte'
@@ -217,6 +218,10 @@
// indicatorPath is the matching draft path.
const opWorkspace = $derived(autosaveWorkspace ?? $operatingWorkspace)
const indicatorPath = $derived(autosavePath ?? liveEditorDraftStoragePath)
dropStalePending(
untrack(() => opWorkspace),
flowStore.val
)
let initialPathStore = writable(initialPath)
@@ -519,7 +524,12 @@
runAs: {
email: flowStore.val.on_behalf_of_email,
permissionedAs: flowStore.val.on_behalf_of,
targetWorkspace: opWorkspace ?? ''
targetWorkspace: opWorkspace ?? '',
needsSource: () => ({
kind: 'flow',
value: flowStore.val.value,
schema: flowStore.val.schema
})
}
})
if (!choice) return
@@ -1740,6 +1750,12 @@
folderDefault={folderDefault.value}
folderDefaultLoading={folderDefault.loading}
targetWorkspace={opWorkspace ?? ''}
itemPath={$pathStore}
needsSource={() => ({
kind: 'flow',
value: flowStore.val.value,
schema: flowStore.val.schema
})}
onConfirmed={() => deployFlow(deployDialogMsg)}
/>
@@ -28,13 +28,18 @@
</script>
<script lang="ts">
import { Check, User as UserIcon, UserCog, Users, ExternalLink } from 'lucide-svelte'
import MeltPopover from './meltComponents/Popover.svelte'
import Portal from './Portal.svelte'
import Modal from './common/modal/Modal.svelte'
import { userStore } from '$lib/stores'
import { Bot, ChevronDown, PlusIcon, User as UserIcon, UserCog, Users } from 'lucide-svelte'
import Select from './select/Select.svelte'
import { Button, Drawer, DrawerContent } from './common'
import { enterpriseLicense, userStore } from '$lib/stores'
import { UserService, type User } from '$lib/gen'
import TextInput from './text_input/TextInput.svelte'
import {
getPendingServiceAccount,
PENDING_EMAIL_DOMAIN,
useServiceAccounts
} from './access/serviceAccounts.svelte'
import NewServiceAccountForm from './access/NewServiceAccountForm.svelte'
import type { NeedsSource } from './access/detectNeeds'
interface Props {
targetWorkspace: string
@@ -51,7 +56,7 @@
canPreserve: boolean
/** The value of the custom-selected user (for display) */
customValue?: string | undefined
/** When false, labels say "current" instead of "target" and modal text refers to "this workspace" */
/** When false, the saved value is labelled "current" instead of "target" */
isDeployment?: boolean
/**
* Folder default permissioned_as for this item path — resolved by the parent via
@@ -61,14 +66,14 @@
*/
folderDefault?: string | undefined
/**
* Raises the popover and user picker above a `ConfirmationModal`, which renders at a
* z-index above the popover layer — without this they open behind the dialog hosting them.
* Raises the list and the creation drawer above a `ConfirmationModal`, which renders at a
* z-index above both — without this they open behind the dialog hosting them.
*/
aboveConfirmationModal?: boolean
/**
* Fires as the user picker opens and closes. A host that binds its own Enter/Escape handler
* must suspend it meanwhile: both handlers sit on `window`, where `stopPropagation` can't
* separate them, so Escape in the picker would also dismiss the host.
* Fires as the list or the creation drawer opens and closes. A host that binds its own
* Enter/Escape handler must suspend it meanwhile: both handlers sit on `window`, where
* `stopPropagation` can't separate them, so Escape in the picker would also dismiss the host.
*/
onPickerOpenChange?: (open: boolean) => void
/**
@@ -76,9 +81,19 @@
* one is the wrong name whenever the deploy targets a different workspace.
*/
myPermissionedAs?: string
/** Without `canPreserve`, show the current user as plain text instead of a popover whose
/** Without `canPreserve`, show the current user as plain text instead of a list whose
* only enabled option is "me". The host must treat that as the choice already made. */
readOnlyWithoutPreserve?: boolean
/** The item's path, which a new service account is named after and given read on. */
itemPath?: string
/** The item as its editor holds it, read for what a new service account needs. */
needsSource?: () => NeedsSource | undefined
/** Offer to create a service account. Only a host whose deploy creates the pending account
* may pass it: elsewhere the item would be deployed as an account that never exists. */
offerCreate?: boolean
size?: 'sm' | 'md'
/** Width of the input, e.g. a fixed one in a table row so the row doesn't reflow. */
class?: string
}
let {
@@ -94,24 +109,18 @@
aboveConfirmationModal = false,
onPickerOpenChange = undefined,
myPermissionedAs = undefined,
readOnlyWithoutPreserve = false
readOnlyWithoutPreserve = false,
itemPath = undefined,
needsSource = undefined,
offerCreate = false,
size = 'md',
class: className = 'w-56'
}: Props = $props()
const isTrigger = $derived(kind === 'trigger' || isTriggerOrScheduleKind(kind))
let label = $derived(
isTrigger
? 'Set the user this will be permissioned as:'
: 'Set the user this will be run on behalf of:'
)
let users = $state<User[]>([])
let usersLoaded = $state(false)
let modalOpen = $state(false)
let searchQuery = $state('')
async function loadUsers() {
if (usersLoaded) return
try {
users = await UserService.listUsers({ workspace: targetWorkspace })
} catch {
@@ -127,6 +136,7 @@
function resolveDisplayName(value: string | undefined): string | undefined {
if (!value) return undefined
if (value.startsWith('u/') || value.startsWith('g/')) return value
if (value.endsWith(`@${PENDING_EMAIL_DOMAIN}`)) return `u/${value.split('@')[0]}`
const username = users.find((u) => u.email === value)?.username
return username ? `u/${username}` : value
}
@@ -137,28 +147,153 @@
myPermissionedAs ?? ($userStore?.username ? `u/${$userStore.username}` : undefined)
)
let activeUsers = $derived(users.filter((u) => !u.disabled))
let filteredUsers = $derived(
searchQuery
? activeUsers.filter((u) => {
const q = searchQuery.toLowerCase()
return (
u.username.toLowerCase().includes(q) ||
u.email.toLowerCase().includes(q) ||
(u.name?.toLowerCase()?.includes(q) ?? false)
)
})
: activeUsers
const serviceAccounts = useServiceAccounts(() => targetWorkspace)
type Row = {
value: string
label: string
subtitle?: string
disabled?: boolean
group: string
kind: 'account' | 'person' | 'group'
email?: string
pending?: boolean
}
const GROUP_OF: Record<Row['kind'], string> = {
account: 'Service accounts',
person: 'People',
group: 'Groups'
}
const GROUP_ORDER = Object.values(GROUP_OF)
// One row per user: the saved value and "me" are tags on the account or person row when it is
// listed, and rows of their own, at the top of the group of what they name, when it is not.
let rows: Row[] = $derived.by(() => {
const tags = new Map<string, string[]>()
const tag = (name: string | undefined, t: string) =>
name && tags.set(name, [...(tags.get(name) ?? []), t])
if (targetValue) tag(targetDisplayName, isDeployment ? '(target)' : '(current)')
tag(myDisplayName, '(me)')
const listed: Omit<Row, 'label'>[] = [
...serviceAccounts.current
.filter((a) => a.pending || canPreserve)
.sort(
(a, b) =>
Number(!!b.pending) - Number(!!a.pending) || a.username.localeCompare(b.username)
)
.map((a) => ({
value: `u/${a.username}`,
group: 'Service accounts',
kind: 'account' as const,
email: a.email,
pending: a.pending,
subtitle: a.folders.length
? `reads ${a.folders.map((f) => `f/${f}`).join(', ')}`
: 'no folder shared'
})),
...(canPreserve ? users : [])
.filter((u) => !u.disabled && !u.is_service_account)
.map((u) => ({
value: `u/${u.username}`,
group: 'People',
kind: 'person' as const,
email: u.email,
subtitle: u.email
}))
]
const listedNames = new Set(listed.map((r) => r.value))
const own: Omit<Row, 'label'>[] = [...tags.keys()]
.filter((name) => !listedNames.has(name))
.map((name) => {
const rowKind: Row['kind'] = name.startsWith('g/')
? 'group'
: serviceAccounts.current.some((a) => `u/${a.username}` === name)
? 'account'
: 'person'
return {
value: name,
group: GROUP_OF[rowKind],
kind: rowKind,
disabled: name !== myDisplayName && !canPreserve
}
})
// Select draws a header wherever the group changes, so each group's rows must be contiguous.
return [...own, ...listed]
.sort((a, b) => GROUP_ORDER.indexOf(a.group) - GROUP_ORDER.indexOf(b.group))
.map((r) => ({
...r,
label: [r.value, ...(tags.get(r.value) ?? [])].join(' ')
}))
})
let rowsByValue = $derived(new Map(rows.map((r) => [r.value, r])))
function pick(value: string | undefined) {
if (!value) return
if (targetValue && value === targetDisplayName && canPreserve) {
onSelect('target')
} else if (value === myDisplayName) {
onSelect('me')
} else {
const email = rowsByValue.get(value)?.email
if (email) onSelect('custom', { email, permissionedAs: value })
}
}
// Service accounts are created at deploy time for the runnables a deploy dialog confirms; a
// trigger's identity is set where it is saved, with no dialog to create one from.
const offersCreate = $derived(
offerCreate && (kind === 'script' || kind === 'flow' || kind === 'app' || kind === 'raw_app')
)
const canCreate = $derived(!!$enterpriseLicense && !!$userStore?.is_admin)
let filterText = $state('')
let selectOpen = $state(false)
let drawerOpen = $state(false)
let createForm: NewServiceAccountForm | undefined = $state()
let createName: string | undefined = $state()
function setSelectOpen(open: boolean) {
selectOpen = open
onPickerOpenChange?.(selectOpen || drawerOpen)
}
function setDrawerOpen(open: boolean) {
drawerOpen = open
onPickerOpenChange?.(selectOpen || drawerOpen)
}
function startCreate() {
createName = filterText.trim() || undefined
// Cleared first, as Select's own pick does: Select reopens the list while a search is typed.
filterText = ''
setDrawerOpen(true)
setSelectOpen(false)
}
let noMatchingItems = $derived(
!!filterText && !rows.some((r) => r.label.toLowerCase().includes(filterText.toLowerCase()))
)
function handleSelectKeydown(e: KeyboardEvent) {
if (e.key === 'Enter' && selectOpen && noMatchingItems && offersCreate && canCreate) {
e.preventDefault()
startCreate()
}
}
function isPending(value: string | undefined): boolean {
return !!getPendingServiceAccount(targetWorkspace, resolveDisplayName(value))
}
// Preselect "target" when available and user has permission to preserve.
// When no target is set but a folder default is, preselect that as a custom value.
// We track `users.length` so the effect re-runs once the async user list loads.
$effect(() => {
if (selected !== undefined || !canPreserve) return
if (targetValue) {
if (selected !== undefined) return
if (targetValue && canPreserve) {
onSelect('target')
} else if (folderDefault && users.length > 0) {
} else if (folderDefault && canPreserve && users.length > 0) {
const username = folderDefault.startsWith('u/') ? folderDefault.slice(2) : folderDefault
const email = users.find((u) => u.username === username)?.email ?? folderDefault
onSelect('custom', { email, permissionedAs: folderDefault })
@@ -169,22 +304,6 @@
selected === 'custom' && folderDefault !== undefined && customValue === folderDefault
)
function openModal() {
loadUsers()
searchQuery = ''
modalOpen = true
}
function selectUser(user: User) {
onSelect('custom', { email: user.email, permissionedAs: `u/${user.username}` })
modalOpen = false
}
// Covers every close path — the X, the overlay, Escape — not just `selectUser`.
$effect(() => {
onPickerOpenChange?.(modalOpen)
})
let selectedDisplayName = $derived.by(() => {
if (selected === 'target') return targetDisplayName
if (selected === 'me') return myDisplayName
@@ -193,144 +312,123 @@
})
</script>
{#snippet statusIcon()}
<UserCog size={14} class={selected ? 'text-green-500' : 'text-yellow-500'} />
{/snippet}
{#if readOnlyWithoutPreserve && !canPreserve}
<span class="inline-flex items-center gap-1 text-xs text-secondary">
<UserIcon class="w-4 h-4" />
{myDisplayName}
</span>
{:else}
<MeltPopover
placement="bottom"
contentClasses={aboveConfirmationModal ? 'z-[10001]' : ''}
on:openChange={(e) => e.detail && loadUsers()}
>
{#snippet trigger()}
<span class="inline-flex items-center gap-1">
<UserCog class="w-4 h-4 {selected ? 'text-green-500' : 'text-yellow-500'}" />
{#if selectedDisplayName}
<span class="text-xs truncate max-w-24">{selectedDisplayName}</span>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
<div class="inline-flex items-center gap-2" role="group" onkeydown={handleSelectKeydown}>
<Select
items={rows}
bind:value={() => selectedDisplayName, pick}
bind:filterText
bind:open={() => selectOpen, setSelectOpen}
groupBy={(r) => r.group}
loading={!usersLoaded}
noItemsMsg="No user or service account found"
placeholder="Select a user"
{size}
class={className}
dropdownClass={aboveConfirmationModal ? 'z-[10001]' : undefined}
RightIcon={ChevronDown}
inputLeadingSnippet={statusIcon}
>
{#snippet startSnippet({ item })}
{@const rowKind = rowsByValue.get(item.value)?.kind}
{@const Icon = rowKind === 'account' ? Bot : rowKind === 'group' ? Users : UserIcon}
<Icon size={14} class="shrink-0 text-secondary" />
{/snippet}
{#snippet endSnippet({ item })}
{#if rowsByValue.get(item.value)?.pending}
<span class="text-2xs text-blue-700 dark:text-blue-300">new</span>
{/if}
{#if isFolderDefaultSelected}
<span
class="text-[10px] px-1 py-0.5 rounded bg-blue-50 dark:bg-blue-950/50 text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-900"
title="From this folder's default_permissioned_as rule"
>
folder default
</span>
{/if}
</span>
{/snippet}
{#snippet content({ close: closePopover })}
<div class="p-3 flex flex-col gap-2 min-w-48">
<div class="text-xs font-medium text-secondary mb-1">{label}</div>
<!-- Target option -->
{#if targetValue}
{/snippet}
{#snippet bottomSnippet()}
{#if offersCreate}
<button
class="flex items-center gap-2 px-2 py-1.5 rounded text-left text-xs hover:bg-surface-hover {!canPreserve
? 'opacity-50 cursor-not-allowed'
class="sticky py-2 px-4 w-full text-left text-xs font-medium flex items-center justify-center gap-2 border-t border-border-light {canCreate
? 'hover:bg-surface-hover'
: 'text-disabled cursor-not-allowed'} {noMatchingItems && canCreate
? 'bg-surface-hover'
: ''}"
disabled={!canPreserve}
onclick={() => onSelect('target')}
disabled={!canCreate}
onclick={startCreate}
>
<Check class="w-3 h-3 {selected === 'target' ? 'opacity-100' : 'opacity-0'}" />
<span class="truncate max-w-40">{targetDisplayName}</span>
<span class="text-xs text-tertiary">{isDeployment ? '(target)' : '(current)'}</span>
<PlusIcon class="inline" size={16} />
Create service account
{#if !$enterpriseLicense}
<span class="text-2xs font-medium px-1.5 rounded bg-surface-secondary text-secondary"
>EE</span
>
{/if}
</button>
{/if}
<!-- Me option -->
<button
class="flex items-center gap-2 px-2 py-1.5 rounded text-left text-xs hover:bg-surface-hover"
onclick={() => onSelect('me')}
>
<Check class="w-3 h-3 {selected === 'me' ? 'opacity-100' : 'opacity-0'}" />
<span class="truncate max-w-40">{myDisplayName}</span>
<span class="text-xs text-tertiary">(me)</span>
</button>
<!-- Custom / Pick from workspace -->
<button
class="flex items-center gap-2 px-2 py-1.5 rounded text-left text-xs hover:bg-surface-hover {!canPreserve
? 'opacity-50 cursor-not-allowed'
: ''}"
disabled={!canPreserve}
onclick={() => {
closePopover()
openModal()
}}
>
{#if selected === 'custom' && customDisplayName}
<Check class="w-3 h-3 opacity-100" />
<span class="truncate max-w-40">{customDisplayName}</span>
<span class="text-xs text-tertiary">(custom)</span>
{:else}
<Check class="w-3 h-3 opacity-0" />
<Users class="w-3 h-3 text-tertiary" />
<span>Pick from workspace&hellip;</span>
{/if}
</button>
</div>
{/snippet}
</MeltPopover>
{/if}
<!-- User selection modal. Portalled: the modal positions itself with `fixed`, which resolves
against the nearest transformed ancestor — inside a dialog card (which is transformed for
its open transition) it would be laid out within that card instead of the viewport. -->
<Portal>
<Modal
title="Select a user"
bind:open={modalOpen}
kind="X"
minZIndex={aboveConfirmationModal ? 10001 : undefined}
>
<div class="flex flex-col gap-4">
<div class="text-xs text-secondary">
{#if isTrigger}
Choose the user this trigger will be permissioned as {isDeployment
? 'in the target workspace'
: 'in this workspace'}. The selected user's permissions will be used when the trigger
fires.
{:else}
Choose the user this {kind} will run on behalf of {isDeployment
? 'in the target workspace'
: 'in this workspace'}. The selected user's permissions will be used when executing.
{/if}
<a
href="https://www.windmill.dev/docs/core_concepts/roles_and_permissions"
target="_blank"
rel="noopener noreferrer"
class="text-blue-500 hover:underline inline-flex items-center gap-0.5"
>
Learn more
<ExternalLink class="w-3 h-3" />
</a>
</div>
<TextInput bind:value={searchQuery} inputProps={{ placeholder: 'Search users...' }} />
<div class="max-h-60 overflow-y-auto border rounded">
{#each filteredUsers as user (user.email)}
<button
class="w-full flex items-center gap-3 px-3 py-2 text-left text-sm hover:bg-surface-hover border-b last:border-b-0"
onclick={() => selectUser(user)}
>
<div class="flex flex-col min-w-0">
<span class="font-medium truncate">u/{user.username}</span>
<span class="text-xs text-tertiary truncate">{user.email}</span>
{#if $enterpriseLicense && !canCreate}
<div class="px-4 pb-2 text-center text-2xs text-secondary">
Only workspace admins can create one.
</div>
{#if selected === 'custom' && (customValue === `u/${user.username}` || customValue === user.email)}
<Check class="w-4 h-4 text-green-500 ml-auto flex-shrink-0" />
{/if}
</button>
{:else}
<div class="px-3 py-4 text-sm text-tertiary text-center">
{#if !usersLoaded}
Loading users&hellip;
{:else}
No users found
{/if}
</div>
{/each}
</div>
</div>
</Modal>
</Portal>
{/if}
{/if}
{/snippet}
</Select>
{#if selected === 'custom' && isPending(customValue)}
<span
class="text-[10px] px-1 py-0.5 rounded bg-blue-50 dark:bg-blue-950/50 text-blue-700 dark:text-blue-300"
title="Created when you deploy">new</span
>
{/if}
{#if isFolderDefaultSelected}
<span
class="text-[10px] px-1 py-0.5 rounded bg-blue-50 dark:bg-blue-950/50 text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-900 whitespace-nowrap"
title="From this folder's default_permissioned_as rule"
>
folder default
</span>
{/if}
</div>
{#if offersCreate}
<Drawer
bind:open={() => drawerOpen, setDrawerOpen}
size="600px"
minZIndex={aboveConfirmationModal ? 10001 : undefined}
>
<DrawerContent title="New service account" on:close={() => setDrawerOpen(false)}>
{#snippet actions()}
<Button
variant="accent"
unifiedSize="md"
startIcon={{ icon: PlusIcon }}
disabled={!createForm?.canCreate()}
onClick={() => createForm?.create()}
>
Create service account
</Button>
{/snippet}
{#if drawerOpen}
<NewServiceAccountForm
bind:this={createForm}
workspace={targetWorkspace}
itemKind={kind === 'raw_app' ? 'app' : (kind as 'script' | 'flow' | 'app')}
{itemPath}
{needsSource}
initialName={createName}
onCreate={(permissionedAs) => {
onSelect('custom', {
email: `${permissionedAs.slice(2)}@${PENDING_EMAIL_DOMAIN}`,
permissionedAs
})
setDrawerOpen(false)
}}
/>
{/if}
</DrawerContent>
</Drawer>
{/if}
{/if}
@@ -1,5 +1,6 @@
<script lang="ts">
import DeployOnBehalfOfDialog from '$lib/components/itemSettings/DeployOnBehalfOfDialog.svelte'
import { dropStalePending } from '$lib/components/access/serviceAccounts.svelte'
import { deployAsksOnBehalfOf } from '$lib/components/itemSettings/onBehalfOf'
import { movesToAnotherOwner } from '$lib/components/itemSettings/inheritedAccess'
import PathMoveNote from '$lib/components/itemSettings/PathMoveNote.svelte'
@@ -271,6 +272,10 @@
})
}
const indicatorPath = $derived(autosavePath ?? userDraftPath)
dropStalePending(
untrack(() => opWorkspace),
script
)
// The shared `workerTags` store caches tags for the navigation workspace. A
// session editor deploys to `opWorkspace` (a fork), so it keeps a local list to
@@ -707,7 +712,13 @@
runAs: {
email: script.on_behalf_of_email,
permissionedAs: script.on_behalf_of,
targetWorkspace: opWorkspace ?? ''
targetWorkspace: opWorkspace ?? '',
needsSource: () => ({
kind: 'script',
language: script.language,
content: script.content,
schema: script.schema
})
}
})
if (!choice) return
@@ -1561,6 +1572,13 @@
folderDefault={folderDefault.value}
folderDefaultLoading={folderDefault.loading}
targetWorkspace={opWorkspace ?? ''}
itemPath={script.path}
needsSource={() => ({
kind: 'script',
language: script.language,
content: script.content,
schema: script.schema
})}
onConfirmed={() => deployScript(deployDialogStay, deployDialogMsg)}
/>
@@ -1991,6 +2009,13 @@
savedPermissionedAs={savedRunAs?.on_behalf_of}
targetWorkspace={opWorkspace ?? ''}
isNew={neverDeployed}
itemPath={script.path}
needsSource={() => ({
kind: 'script',
language: script.language,
content: script.content,
schema: script.schema
})}
/>
<InvisibleRunsSetting
kind="script"
@@ -324,6 +324,8 @@
aboveConfirmationModal
onPickerOpenChange={(open) => (pickerOpen = open)}
myPermissionedAs={access?.value.me?.permissionedAs}
size="sm"
class="w-44"
/>
</div>
{#if onBehalfOfUnset}
@@ -0,0 +1,237 @@
<script lang="ts">
import { Button } from '$lib/components/common'
import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte'
import Cell from '$lib/components/table/Cell.svelte'
import DataTable from '$lib/components/table/DataTable.svelte'
import Head from '$lib/components/table/Head.svelte'
import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte'
import { GranularAclService } from '$lib/gen'
import { AlertTriangle, Check } from 'lucide-svelte'
import { resource } from 'runed'
import { setGrant } from './access'
import {
detectNeeds,
type NeededItem,
type Needs,
type NeedsSource,
type RunnableKind
} from './detectNeeds'
import { getPendingServiceAccount, type PendingServiceAccount } from './serviceAccounts.svelte'
let {
workspace,
kind,
itemPath,
needsSource,
account
}: {
workspace: string
kind: RunnableKind
itemPath?: string
/** Read when the identity changes or the section mounts, so unsaved edits count. */
needsSource?: () => NeedsSource | undefined
/** `u/<username>` the item runs as; unset when it runs as whoever runs it. */
account: string | undefined
} = $props()
type Report = {
key: string
needs: Needs
reads?: Set<string> | 'all'
accessError?: string
}
const operatingUser = useOperatingUser()
const me = $derived(
operatingUser.current?.username ? `u/${operatingUser.current.username}` : undefined
)
const isAdmin = $derived(!!operatingUser.current?.is_admin)
const pending = $derived(getPendingServiceAccount(workspace, account))
// Reading another principal's access is admin-only; anyone may read their own. A pending
// account is marked from the grants planned for it, as it has no access yet.
const mode = $derived(
!account ? 'caller' : pending ? 'pending' : account === me || isAdmin ? 'checked' : 'unmarked'
)
const key = $derived(
itemPath || needsSource ? `${workspace}:${mode}:${account ?? ''}` : undefined
)
let report: Report | undefined = $state()
let grantErrors: Record<string, string> = $state({})
let granting: string | undefined = $state()
let confirming: NeededItem | undefined = $state()
// Responses are not ordered: a slow answer for the previous identity must not land.
let requestId = 0
async function check(): Promise<void> {
const id = ++requestId
const forKey = key
if (!forKey) return
const principal = mode === 'checked' ? account : undefined
// A saved run-as user that is disabled or deleted fails the access check; the list still
// matters most then, so only the scan failing hides the section.
const access = principal
? GranularAclService.getPrincipalAccess({ workspace, principal }).then(
(a) => ({
reads: a.is_admin
? ('all' as const)
: new Set(a.items.map((i) => `${i.kind}:${i.path}`))
}),
(e: any) => ({ accessError: `${e?.body ?? e}` })
)
: Promise.resolve({})
try {
const [needs, result] = await Promise.all([
detectNeeds(workspace, kind, itemPath ?? '', needsSource?.()),
access
])
if (id === requestId) report = { key: forKey, needs, ...result }
} catch {
if (id === requestId) report = undefined
}
}
resource(
() => key,
() => {
grantErrors = {}
return check()
}
)
function plannedRead(account: PendingServiceAccount, item: NeededItem): boolean {
return account.grants.some((g) =>
g.kind === 'folder'
? item.path.startsWith(`f/${g.path}/`)
: g.kind === item.kind && g.path === item.path
)
}
const shown = $derived(report && report.key === key ? report : undefined)
const items = $derived(shown?.needs.items ?? [])
const readable = $derived.by((): ((item: NeededItem) => boolean) | undefined => {
const reads = shown?.reads
if (mode === 'pending' && pending) return (i) => plannedRead(pending, i)
if (mode === 'checked' && reads) {
return (i) => reads === 'all' || reads.has(`${i.kind}:${i.path}`)
}
return undefined
})
async function grantRead(item: NeededItem): Promise<void> {
if (!account) return
const itemKey = `${item.kind}:${item.path}`
granting = itemKey
try {
await setGrant(workspace, item.kind, item.path, account, 'read')
delete grantErrors[itemKey]
} catch (e) {
grantErrors[itemKey] = `${e?.body ?? e}`
}
await check()
granting = undefined
confirming = undefined
}
</script>
<!-- Portalled and raised: this section also renders inside the deploy drawer and its run-as
confirmation dialog. -->
<ConfirmationModal
open={!!confirming}
title="Grant read access"
confirmationText="Grant read to {account}"
type="info"
loading={!!granting}
alwaysPortal
zIndexClass="z-[10000]"
onConfirmed={() => confirming && grantRead(confirming)}
onCanceled={() => (confirming = undefined)}
>
{#if confirming}
<p class="text-xs text-primary">
{account} gets read access to the {confirming.kind}
<span class="font-mono">{confirming.path}</span>. The grant applies now, before you deploy.
</p>
{/if}
</ConfirmationModal>
{#if items.length}
<div class="flex flex-col gap-1.5 text-2xs">
<span class="text-secondary">This {kind} needs read access to:</span>
<DataTable size="xs">
<Head>
<tr>
<Cell head first>Path</Cell>
<Cell head last={!readable}>Kind</Cell>
{#if readable}
<Cell head>{account}</Cell>
<Cell head last actions />
{/if}
</tr>
</Head>
<tbody class="divide-y">
{#each items as item (item.kind + ':' + item.path)}
{@const itemKey = `${item.kind}:${item.path}`}
{@const ok = readable?.(item)}
<tr>
<Cell first><span class="font-mono text-2xs">{item.path}</span></Cell>
<Cell last={!readable}>{item.kind}</Cell>
{#if readable}
<Cell>
{#if grantErrors[itemKey]}
<span class="text-red-600 dark:text-red-400">{grantErrors[itemKey]}</span>
{:else if ok}
<span class="flex items-center gap-1.5">
<Check size={12} class="text-green-600 dark:text-green-400" />
Can read
</span>
{:else}
<span class="flex items-center gap-1.5 text-yellow-600 dark:text-yellow-400">
<AlertTriangle size={12} class="text-yellow-500" />
{mode === 'pending' ? "Won't be able to read" : "Can't read"}
</span>
{/if}
</Cell>
<Cell last actions>
{#if !ok && mode === 'checked' && isAdmin}
<Button
variant="default"
unifiedSize="xs"
disabled={!!granting}
onClick={() => (confirming = item)}
>
Grant read to {account}
</Button>
{/if}
</Cell>
{/if}
</tr>
{/each}
</tbody>
</DataTable>
{#if shown?.accessError}
<span class="text-secondary">Couldn't check {account}'s access: {shown.accessError}</span>
{/if}
{#if mode === 'caller'}
<span class="text-secondary">
It runs as whoever runs it, so each of them needs read access to these.
</span>
{/if}
{#if shown?.needs.others.length}
<span class="text-secondary">
Also uses {shown.needs.others.map((o) => `${o.kind} ${o.path}`).join(', ')}; access to these
is set on the storage or data table itself.
</span>
{/if}
{#if shown?.needs.errors.length}
<span class="text-secondary">
Some of it could not be read, so this list may be incomplete: {shown.needs.errors.join(
'; '
)}.
</span>
{/if}
<span class="text-secondary">
Only paths written out in the code are found; a path the code builds while it runs isn't.
</span>
</div>
{/if}
@@ -0,0 +1,226 @@
<script lang="ts">
import { Skeleton } from '$lib/components/common'
import Checkbox from '$lib/components/common/checkbox/Checkbox.svelte'
import Select from '$lib/components/select/Select.svelte'
import TextInput from '$lib/components/text_input/TextInput.svelte'
import { FolderService, UserService } from '$lib/gen'
import { Database, Folder, Info, KeyRound } from 'lucide-svelte'
import { detectNeeds, type NeedsSource, type RunnableKind } from './detectNeeds'
import { setPendingServiceAccount, type Grant } from './serviceAccounts.svelte'
let {
workspace,
itemKind,
itemPath,
needsSource,
initialName,
onCreate
}: {
workspace: string
itemKind: RunnableKind
/** Path of the item being deployed; unset while it has none. */
itemPath?: string
/** The item as its editor holds it, read for what it uses. */
needsSource?: () => NeedsSource | undefined
/** Typed in the picker's search. */
initialName?: string
/** The account is pending: the deploy creates it. */
onCreate: (permissionedAs: string) => void
} = $props()
type Row = Grant & { detail: string; checked: boolean }
const NAME = /^[a-zA-Z0-9_]+$/
const itemFolder = $derived(
itemPath?.startsWith('f/') ? itemPath.split('/')[1] || undefined : undefined
)
let name = $state('')
let rows: Row[] = $state([])
/** Whether the item's folder already names default users; unknown until loaded. */
let folderHasDefaults: boolean | undefined = $state(undefined)
let usernames: string[] = $state([])
let folderNames: string[] = $state([])
let detecting = $state(true)
let detectionErrors: string[] = $state([])
async function init(): Promise<void> {
const base = initialName?.trim() || (itemFolder ?? itemPath?.split('/').at(-1) ?? 'service')
const [users, folders] = await Promise.all([
UserService.listUsernames({ workspace }).catch(() => [] as string[]),
FolderService.listFolderNames({ workspace }).catch(() => [] as string[])
])
usernames = users
folderNames = folders
const wanted = initialName?.trim() ? base : `${base.replace(/[^a-zA-Z0-9_]/g, '_')}_bot`
let candidate = wanted
for (let i = 2; users.includes(candidate); i++) candidate = `${wanted}_${i}`
name = candidate
if (itemFolder) {
rows = [
{
kind: 'folder',
path: itemFolder,
detail: `The ${itemKind}'s folder: everything it uses there`,
checked: true
}
]
FolderService.getFolder({ workspace, name: itemFolder }).then(
(f) => (folderHasDefaults = !!f.default_permissioned_as?.length),
() => (folderHasDefaults = true)
)
}
if (!itemPath) {
detecting = false
return
}
try {
const needs = await detectNeeds(workspace, itemKind, itemPath, needsSource?.())
detectionErrors = needs.errors
const outside = needs.items.filter(
(i) => !itemFolder || !i.path.startsWith(`f/${itemFolder}/`)
)
rows = [
...rows,
...outside.map((i) => ({
kind: i.kind,
path: i.path,
detail: `${i.kind === 'resource' ? 'Resource' : 'Variable'}, read by ${i.sources[0]}`,
checked: true
}))
]
} catch (e) {
detectionErrors = [String(e?.body ?? e)]
} finally {
detecting = false
}
}
init()
const nameError = $derived(
!name
? 'Pick a name'
: !NAME.test(name)
? 'Letters, digits and _ only'
: usernames.includes(name)
? `u/${name} already exists`
: undefined
)
const principal = $derived(`u/${name}`)
const chosen = $derived(rows.filter((r) => r.checked))
const addableFolders = $derived(
folderNames
.filter((f) => !rows.some((r) => r.kind === 'folder' && r.path === f))
.map((f) => ({ value: f, label: `f/${f}` }))
)
/** For the host's header action. */
export function canCreate(): boolean {
return !nameError && !detecting
}
export function create(): void {
if (!canCreate()) return
setPendingServiceAccount(workspace, {
username: name,
grants: chosen.map(({ kind, path }) => ({ kind, path }))
})
onCreate(principal)
}
</script>
<div class="flex flex-col gap-5">
<p class="text-xs text-secondary">
A service account can't sign in. The {itemKind} runs with only the access you give it here, and keeps
it when people leave. Nothing is created until you deploy.
</p>
<div class="flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">Name</span>
<TextInput
bind:value={name}
size="sm"
error={nameError}
inputProps={{ placeholder: 'billing_bot', 'aria-label': 'Name' }}
/>
<span class="text-2xs text-secondary">
{nameError ?? `Shown as ${principal} in runs and audit logs.`}
</span>
</div>
<div class="flex flex-col gap-2">
<div class="flex flex-col">
<span class="text-xs font-semibold text-emphasis">What it can read</span>
<span class="text-2xs text-secondary"
>Found in this {itemKind}. Each gets read-only access.</span
>
</div>
{#if detecting}
<Skeleton layout={[[2], 0.5, [2]]} />
{:else}
<div class="flex flex-col rounded-md border divide-y">
{#each rows as row (row.kind + ':' + row.path)}
<label class="flex items-start gap-2 px-3 py-2 cursor-pointer">
<Checkbox
class="mt-0.5"
checked={row.checked}
onChange={() => (row.checked = !row.checked)}
/>
{#if row.kind === 'folder'}
<Folder size={14} class="mt-0.5 shrink-0 text-secondary" />
{:else if row.kind === 'resource'}
<Database size={14} class="mt-0.5 shrink-0 text-secondary" />
{:else}
<KeyRound size={14} class="mt-0.5 shrink-0 text-secondary" />
{/if}
<span class="flex grow flex-col min-w-0">
<span class="font-mono text-xs text-primary truncate">
{row.kind === 'folder' ? `f/${row.path}` : row.path}
</span>
<span class="text-2xs text-secondary truncate">{row.detail}</span>
</span>
<span class="text-2xs text-secondary">Read</span>
</label>
{:else}
<div class="px-3 py-2 text-2xs text-secondary">
Nothing found. Add the folders it needs below.
</div>
{/each}
</div>
<div class="w-72">
<Select
items={addableFolders}
bind:value={
() => undefined,
(v) =>
v &&
(rows = [...rows, { kind: 'folder', path: v, detail: 'Added by you', checked: true }])
}
placeholder="Add a folder"
size="sm"
/>
</div>
<div class="flex items-start gap-1.5 text-2xs text-secondary">
<Info size={12} class="mt-0.5 shrink-0" />
<span>
A path the code builds while it runs can't be found.
{#if detectionErrors.length}
Some of it could not be read: {detectionErrors[0]}.
{/if}
</span>
</div>
{/if}
</div>
{#if itemFolder && folderHasDefaults}
<span class="text-2xs text-secondary">
<code>f/{itemFolder}</code> already sets who new items in it run as. Change that in the
folder's settings on the <a href="/folders">Folders</a> page.
</span>
{/if}
<span class="border-t pt-3 text-2xs text-secondary">
Created when you deploy, with the access above. Counts as half a seat.
</span>
</div>
@@ -0,0 +1,182 @@
<script lang="ts">
import { Alert, Button, Drawer, DrawerContent } from '$lib/components/common'
import {
canPreserveOnBehalfOf,
WM_DEPLOYERS_GROUP
} from '$lib/components/itemSettings/onBehalfOf'
import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte'
import { enterpriseLicense } from '$lib/stores'
import { Bot, Folder, PlusIcon } from 'lucide-svelte'
import type { NeedsSource } from './detectNeeds'
import ItemReads from './ItemReads.svelte'
import NewServiceAccountForm from './NewServiceAccountForm.svelte'
import {
getPendingServiceAccount,
PENDING_EMAIL_DOMAIN,
useServiceAccounts
} from './serviceAccounts.svelte'
let {
kind,
targetWorkspace,
itemPath,
needsSource,
runsAs,
isNew,
savedPermissionedAs,
runnablesRunAsCaller = false,
onUseAccount,
onCreatingChange
}: {
kind: 'script' | 'flow' | 'app'
targetWorkspace: string
itemPath?: string
needsSource?: () => NeedsSource | undefined
/** `u/<username>` the deploy leaves the item running as; unset when it runs as its caller. */
runsAs: string | undefined
isNew: boolean
savedPermissionedAs: string | undefined
/** An app in viewer mode runs its runnables as each viewer, whoever `runsAs` names. */
runnablesRunAsCaller?: boolean
onUseAccount: (username: string, email: string) => void
/** See `OnBehalfOfSelector`'s `onPickerOpenChange`. */
onCreatingChange?: (open: boolean) => void
} = $props()
const operatingUser = useOperatingUser()
const me = $derived(
operatingUser.current?.username ? `u/${operatingUser.current.username}` : undefined
)
const serviceAccounts = useServiceAccounts(() => targetWorkspace)
const pending = $derived(getPendingServiceAccount(targetWorkspace, runsAs))
const itemFolder = $derived(
itemPath?.startsWith('f/') ? itemPath.split('/')[1] || undefined : undefined
)
const canPick = $derived(canPreserveOnBehalfOf(operatingUser.current))
const canCreate = $derived(!!$enterpriseLicense && !!operatingUser.current?.is_admin)
// An account that already reads the item's folder, which the deployer may deploy as.
const folderAccount = $derived(
itemFolder && canPick
? serviceAccounts.current
.filter((a) => !a.pending && a.folders.includes(itemFolder))
.sort((a, b) => a.username.localeCompare(b.username))[0]
: undefined
)
const suggestsAccount = $derived(
!!$enterpriseLicense &&
!!itemFolder &&
!!me &&
runsAs === me &&
((canPick && !!folderAccount) || canCreate)
)
// The deployed version runs as a service account this deployer can't keep: the deploy takes it
// off and runs the item as them instead.
const dropsAccount = $derived(
!isNew &&
!!savedPermissionedAs &&
runsAs !== savedPermissionedAs &&
!canPreserveOnBehalfOf(operatingUser.current) &&
serviceAccounts.current.some((a) => `u/${a.username}` === savedPermissionedAs)
)
let creatingOpen = $state(false)
let createForm: NewServiceAccountForm | undefined = $state()
function setCreating(open: boolean) {
creatingOpen = open
onCreatingChange?.(open)
}
</script>
{#if suggestsAccount}
<div class="flex flex-col items-start gap-1.5 text-2xs text-secondary">
<span>
It runs with your access: if you leave or lose access to <code>f/{itemFolder}</code>, it stops
working for everyone who {kind === 'app' ? 'opens' : 'runs'} it.
</span>
{#if canPick && folderAccount}
<Button
variant="default"
unifiedSize="xs"
startIcon={{ icon: Bot }}
onClick={() => onUseAccount(folderAccount.username, folderAccount.email)}
>
Use u/{folderAccount.username}, which reads f/{itemFolder}
</Button>
{:else}
<Button
variant="default"
unifiedSize="xs"
startIcon={{ icon: Bot }}
onClick={() => setCreating(true)}
>
Use a service account instead
</Button>
{/if}
</div>
{/if}
<ItemReads
workspace={targetWorkspace}
{kind}
{itemPath}
{needsSource}
account={runnablesRunAsCaller ? undefined : runsAs}
/>
{#if pending}
<div class="flex flex-col gap-1.5 rounded-md border bg-surface-secondary px-3 py-2 text-xs">
<span class="font-semibold text-emphasis">Deploying also</span>
<span class="flex items-start gap-2">
<Bot size={14} class="mt-0.5 shrink-0 text-secondary" />
<span>Creates the service account <strong>{pending.username}</strong>, half a seat</span>
</span>
{#if pending.grants.length}
<span class="flex items-start gap-2">
<Folder size={14} class="mt-0.5 shrink-0 text-secondary" />
<span>
Shares {pending.grants
.map((g) => (g.kind === 'folder' ? `f/${g.path}` : g.path))
.join(', ')} with it, read-only
</span>
</span>
{/if}
</div>
{/if}
{#if dropsAccount}
<Alert type="warning" size="xs" title={`This takes ${savedPermissionedAs} off the ${kind}`}>
Only workspace admins and members of {WM_DEPLOYERS_GROUP} can deploy as it. The {kind} will run with
your access, and stop working for everyone if you leave.
</Alert>
{/if}
<Drawer bind:open={() => creatingOpen, setCreating} size="600px" minZIndex={10001}>
<DrawerContent title="New service account" on:close={() => setCreating(false)}>
{#snippet actions()}
<Button
variant="accent"
unifiedSize="md"
startIcon={{ icon: PlusIcon }}
disabled={!createForm?.canCreate()}
onClick={() => createForm?.create()}
>
Create service account
</Button>
{/snippet}
{#if creatingOpen}
<NewServiceAccountForm
bind:this={createForm}
workspace={targetWorkspace}
itemKind={kind}
{itemPath}
{needsSource}
onCreate={(account) => {
const username = account.slice(2)
onUseAccount(username, `${username}@${PENDING_EMAIL_DOMAIN}`)
setCreating(false)
}}
/>
{/if}
</DrawerContent>
</Drawer>
@@ -12,6 +12,11 @@ export type OtherAsset = { kind: AssetKind | string; path: string; sources: stri
export type Needs = { items: NeededItem[]; others: OtherAsset[]; errors: string[] }
/** The runnable as its editor holds it: a first deploy has nothing on the server to read. */
export type NeedsSource =
| { kind: 'script'; language: string; content: string; schema?: unknown }
| { kind: 'flow' | 'app'; value: unknown; schema?: unknown }
const MAX_DEPTH = 4
const ITEM_PATH = /^[ufg]\/[^/]+\/.+/
const STATIC_REF = /^\$(res|var):(.+)$/
@@ -27,7 +32,8 @@ const VARIABLE_CALL = /\b(?:getVariable|get_variable)\(\s*["'`]([^"'`]+)["'`]/g
export async function detectNeeds(
workspace: string,
kind: RunnableKind,
path: string
path: string,
source?: NeedsSource
): Promise<Needs> {
const items = new Map<string, NeededItem>()
const others = new Map<string, OtherAsset>()
@@ -139,7 +145,17 @@ export async function detectNeeds(
}
}
await follow(kind, path, 0)
if (source) {
visited.add(`${kind}:${path}`)
await Promise.all([
source.kind === 'script'
? scanCode(source.language, source.content, path)
: walk(source.value, path, 0),
walk(source.schema, path, 0)
])
} else {
await follow(kind, path, 0)
}
const byPath = (a: { path: string }, b: { path: string }) => a.path.localeCompare(b.path)
return {
items: [...items.values()].sort(byPath),
@@ -0,0 +1,169 @@
import { resource } from 'runed'
import { SvelteMap } from 'svelte/reactivity'
import { FolderService, UserService, WorkspaceService } from '$lib/gen'
import { setGrant } from './access'
import { sendUserToast } from '$lib/toast'
export type ServiceAccount = {
username: string
email: string
/** Folders shared with the account by name. */
folders: string[]
/** Items shared with it one by one; known only for a pending account. */
items?: string[]
/** Chosen in a picker, created when the item deploys. */
pending?: boolean
}
export type Grant = { kind: 'folder' | 'resource' | 'variable'; path: string }
/** A service account picked before it exists: the deploy creates it, then gives it the rest. */
export type PendingServiceAccount = {
username: string
/** Read access, folders by name. */
grants: Grant[]
}
// The deploy dialog's run-as field needs an email for the account before it exists; the deploy
// replaces it with the real one, which only the server's creation knows.
export const PENDING_EMAIL_DOMAIN = 'pending.sa.wm.dev'
const pending = new SvelteMap<string, PendingServiceAccount>()
const key = (workspace: string, permissionedAs: string) => `${workspace}:${permissionedAs}`
export function setPendingServiceAccount(workspace: string, account: PendingServiceAccount): void {
pending.set(key(workspace, `u/${account.username}`), account)
}
export function getPendingServiceAccount(
workspace: string,
permissionedAs: string | undefined
): PendingServiceAccount | undefined {
return permissionedAs ? pending.get(key(workspace, permissionedAs)) : undefined
}
/** Clears a run-as that names a placeholder email this tab no longer holds an account for, as a
* draft saved before its deploy does after a reload: the server knows no such user. */
export function dropStalePending(
workspace: string | undefined,
item: { on_behalf_of?: string; on_behalf_of_email?: string }
): void {
const email = item.on_behalf_of_email
if (!workspace || !email?.endsWith(`@${PENDING_EMAIL_DOMAIN}`)) return
if (getPendingServiceAccount(workspace, `u/${email.split('@')[0]}`)) return
item.on_behalf_of = undefined
item.on_behalf_of_email = undefined
}
const TTL_MS = 60_000
const asked = new Map<string, { at: number; accounts: Promise<ServiceAccount[]> }>()
async function loadServiceAccounts(workspace: string): Promise<ServiceAccount[]> {
const [users, folders] = await Promise.all([
UserService.listUsers({ workspace }),
FolderService.listFolders({ workspace, perPage: 1000 }).catch(() => [])
])
return users
.filter((u) => u.is_service_account && !u.disabled)
.map((u) => {
const principal = `u/${u.username}`
return {
username: u.username,
email: u.email,
folders: folders
.filter(
(f) =>
f.owners.includes(principal) ||
Object.keys((f.extra_perms ?? {}) as Record<string, boolean>).includes(principal)
)
.map((f) => f.name)
}
})
}
function fetchServiceAccounts(workspace: string): Promise<ServiceAccount[]> {
const hit = asked.get(workspace)
if (hit && Date.now() - hit.at < TTL_MS) return hit.accounts
const accounts = loadServiceAccounts(workspace).catch(() => [])
asked.set(workspace, { at: Date.now(), accounts })
return accounts
}
/** The workspace's service accounts with the folders each reads, followed by the ones picked in
* this tab that a deploy has yet to create. */
export function useServiceAccounts(workspace: () => string | undefined) {
const accounts = resource(workspace, (ws) =>
ws ? fetchServiceAccounts(ws) : Promise.resolve([])
)
return {
get current(): ServiceAccount[] {
const ws = workspace()
const existing = accounts.current ?? []
const waiting = [...pending.entries()]
.filter(
([k, p]) => k.startsWith(`${ws}:`) && !existing.some((a) => a.username === p.username)
)
.map(([, p]) => ({
username: p.username,
email: `${p.username}@${PENDING_EMAIL_DOMAIN}`,
folders: p.grants.filter((g) => g.kind === 'folder').map((g) => g.path),
items: p.grants.filter((g) => g.kind !== 'folder').map((g) => g.path),
pending: true
}))
return [...waiting, ...existing]
},
get loading(): boolean {
return accounts.loading
}
}
}
/**
* Creates the pending account `permissionedAs` names and gives it what was chosen with it, and
* returns its email; `undefined` when nothing is pending under that name. Each step can rerun, so
* a deploy that fails partway retries against the account it already made.
*/
export async function createPendingServiceAccount(
workspace: string,
permissionedAs: string | undefined
): Promise<string | undefined> {
const account = getPendingServiceAccount(workspace, permissionedAs)
if (!account || !permissionedAs) return undefined
const { username } = account
const existing = await UserService.getUser({ workspace, username }).catch(() => undefined)
// Someone may have taken the name since it was picked: granting to it would hand a person, or
// a disabled account, what was meant for the new one.
if (existing && (!existing.is_service_account || existing.disabled)) {
throw new Error(`${username} is already taken by a user that is not an enabled service account`)
}
if (!existing) {
await WorkspaceService.createServiceAccount({
workspace,
requestBody: { username, operator: true }
})
}
for (const grant of account.grants) {
await setGrant(workspace, grant.kind, grant.path, permissionedAs, 'read')
}
const { email } = await UserService.getUser({ workspace, username })
pending.delete(key(workspace, permissionedAs))
asked.delete(workspace)
return email
}
/** Creates the pending account an app's policy runs as, and points the policy at its email.
* False, after telling the user, when that failed and the deploy must not go ahead. */
export async function createPolicyServiceAccount(
workspace: string,
policy: { on_behalf_of?: string; on_behalf_of_email?: string }
): Promise<boolean> {
dropStalePending(workspace, policy)
try {
const email = await createPendingServiceAccount(workspace, policy.on_behalf_of)
if (email) policy.on_behalf_of_email = email
return true
} catch (e) {
sendUserToast(`Could not create ${policy.on_behalf_of}: ${e?.body ?? e?.message ?? e}`, true)
return false
}
}
@@ -63,6 +63,7 @@
import AppEditorBottomPanel from './AppEditorBottomPanel.svelte'
import panzoom from 'panzoom'
import { BG_PREFIX, findGridItem } from './appUtilsCore'
import { dropStalePending } from '$lib/components/access/serviceAccounts.svelte'
let {
app,
@@ -217,6 +218,11 @@
writablePath.set(path)
}
dropStalePending(
$workspaceStore,
untrack(() => policy)
)
setContext<AppViewerContext>('AppViewerContext', {
worldStore,
app: appStore,
@@ -77,6 +77,8 @@
import AppSettingsDrawer from './AppSettingsDrawer.svelte'
import DeployButton from '$lib/components/DeployButton.svelte'
import { updatePolicy } from './appPolicy'
import { createPolicyServiceAccount } from '$lib/components/access/serviceAccounts.svelte'
import type { NeedsSource } from '$lib/components/access/detectNeeds'
import { appDraftSettings, withoutSharedPolicySettings } from './appDraftSettings'
import ShareDialog from '$lib/components/itemSettings/ShareDialog.svelte'
import { showAppLinks } from '$lib/components/itemSettings/AppLinksModal.svelte'
@@ -322,8 +324,11 @@
return classicAppDraftParts(a).value as T
}
const needsSource = (): NeedsSource => ({ kind: 'app', value: $app })
/** Resolves to whether the app was created. */
async function createApp(path: string): Promise<boolean> {
if (!(await createPolicyServiceAccount($workspaceStore!, policy))) return false
// In place: the settings drawer and the draft mirror hold this object.
Object.assign(policy, await updatePolicy($app, policy))
// Read for the path being created: the first-deploy dialog may have just chosen it.
@@ -376,6 +381,7 @@
}
async function handleUpdateApp(npath: string) {
if (!(await createPolicyServiceAccount($workspaceStore!, policy))) return
// We have to make sure there is no updates when we clicked the button
await compareVersions()
@@ -552,7 +558,8 @@
runAs: {
email: policy.on_behalf_of_email,
permissionedAs: policy.on_behalf_of,
targetWorkspace: $workspaceStore ?? ''
targetWorkspace: $workspaceStore ?? '',
needsSource
}
})
if (!choice) return
@@ -1012,6 +1019,8 @@
folderDefaultLoading={folderDefault.loading}
executionMode={policy.execution_mode}
targetWorkspace={$workspaceStore ?? ''}
itemPath={newEditedPath || $appPath}
{needsSource}
onConfirmed={deployNow}
/>
@@ -1063,6 +1072,7 @@
bind:labels
bind:customPath
onAppChanged={applyAppAccess}
{needsSource}
/>
{#if offersSharing}
@@ -11,14 +11,23 @@
import TextInput from '$lib/components/text_input/TextInput.svelte'
import LabelsInput from '$lib/components/LabelsInput.svelte'
import RunOnBehalfOfSetting from '$lib/components/itemSettings/RunOnBehalfOfSetting.svelte'
import { appOnBehalfOfTooltip } from '$lib/components/itemSettings/onBehalfOf'
import {
appOnBehalfOfTooltip,
deployedPermissionedAs
} from '$lib/components/itemSettings/onBehalfOf'
import RunAsNotes from '$lib/components/access/RunAsNotes.svelte'
import { dropStalePending } from '$lib/components/access/serviceAccounts.svelte'
import type { NeedsSource } from '$lib/components/access/detectNeeds'
import SettingToggle from '$lib/components/itemSettings/SettingToggle.svelte'
import SettingIcons from '$lib/components/itemSettings/SettingIcons.svelte'
import { getAppMetadataBadges, getAppPermissionBadges } from './appSettingsBadges'
import PathMoveNote from '$lib/components/itemSettings/PathMoveNote.svelte'
import { FRONTEND_SDK_SCOPES, sdkScopesToConfirm } from '$lib/components/raw_apps/sdkScopes'
import { logFeatureUsage } from '$lib/utils/featureUsage'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import {
useOperatingUser,
useOperatingWorkspace
} from '$lib/components/operatingWorkspace.svelte'
import AppAccessSection from '$lib/components/itemSettings/AppAccessSection.svelte'
import DeployedAppAccess from '$lib/components/itemSettings/DeployedAppAccess.svelte'
import { accessModeOf } from '$lib/components/itemSettings/appAccess'
@@ -43,7 +52,8 @@
newApp = false,
operatingWorkspace = undefined,
customPath = $bindable(),
onAppChanged
onAppChanged,
needsSource
}: {
open: boolean
/** Mutated in place; deployed with the app, like every other setting here. */
@@ -67,6 +77,8 @@
customPath?: string | undefined
/** Called after a write to the deployed app row, with the row as it now is. */
onAppChanged?: (row: AppWithLastVersion) => void
/** The app as the editor holds it, read for what its runnables use. */
needsSource?: () => NeedsSource | undefined
} = $props()
let body: HTMLElement | undefined = $state()
@@ -81,6 +93,25 @@
const opWs = $derived(operatingWorkspace ?? $operatingWorkspaceStore)
const operatingUser = useOperatingUser()
// A draft-only app's saved policy is its draft, which can name an account never created; the
// deploy then runs it as the deployer, as a new app's draft records.
const savedRunAs = $derived.by(() => {
const runAs = {
on_behalf_of: savedApp?.policy?.on_behalf_of as string | undefined,
on_behalf_of_email: savedApp?.policy?.on_behalf_of_email as string | undefined
}
dropStalePending(opWs, runAs)
const me = operatingUser.current?.username
return runAs.on_behalf_of_email || !savedApp?.policy?.on_behalf_of_email
? runAs
: {
on_behalf_of: me ? `u/${me}` : undefined,
on_behalf_of_email: operatingUser.current?.email
}
})
const runsAs = $derived(deployedPermissionedAs(operatingUser.current, policy.on_behalf_of))
let path: Path | undefined = $state(undefined)
let dirtyPath = $state(false)
@@ -217,17 +248,36 @@
/>
{/snippet}
<div class="flex flex-col gap-6">
<RunOnBehalfOfSetting
kind="app"
required
tooltip={appOnBehalfOfTooltip(rawApp)}
bind:email={policy.on_behalf_of_email}
bind:permissionedAs={policy.on_behalf_of}
savedEmail={savedApp?.policy?.on_behalf_of_email}
savedPermissionedAs={savedApp?.policy?.on_behalf_of}
targetWorkspace={opWs ?? ''}
isNew={newApp}
/>
<div class="flex flex-col gap-1.5">
<RunOnBehalfOfSetting
kind="app"
required
tooltip={appOnBehalfOfTooltip(rawApp)}
bind:email={policy.on_behalf_of_email}
bind:permissionedAs={policy.on_behalf_of}
savedEmail={savedRunAs.on_behalf_of_email}
savedPermissionedAs={savedRunAs.on_behalf_of}
targetWorkspace={opWs ?? ''}
isNew={newApp}
itemPath={newEditedPath || appPath}
{needsSource}
showReads={false}
/>
<RunAsNotes
kind="app"
targetWorkspace={opWs ?? ''}
itemPath={newEditedPath || appPath}
{needsSource}
{runsAs}
isNew={newApp}
savedPermissionedAs={savedRunAs.on_behalf_of}
runnablesRunAsCaller={policy.execution_mode == 'viewer'}
onUseAccount={(username, email) => {
policy.on_behalf_of_email = email
policy.on_behalf_of = `u/${username}`
}}
/>
</div>
<SettingToggle
setting="sandbox"
@@ -30,6 +30,8 @@
children?: import('svelte').Snippet<[any]>
/** Asked before a click away or Escape closes it; resolving false keeps it open. */
confirmClose?: () => boolean | Promise<boolean>
/** See `Disposable`'s `minZIndex`: lifts the drawer above a dialog it is opened from. */
minZIndex?: number
}
let {
@@ -46,7 +48,8 @@
positionClass = undefined,
name = undefined,
children: children_render,
confirmClose
confirmClose,
minZIndex = 0
}: Props = $props()
if (open === undefined) {
@@ -150,6 +153,7 @@
onClose={() => dispatch('close')}
{preventEscape}
{confirmClose}
{minZIndex}
>
{#snippet children({ handleClickAway, zIndex, isTop })}
<aside
@@ -403,6 +403,12 @@
savedPermissionedAs={$savedOnBehalfOfPermissionedAs}
targetWorkspace={opWorkspace?.() ?? $operatingWorkspace ?? ''}
isNew={newFlow || $initialPathStore == ''}
itemPath={$pathStore}
needsSource={() => ({
kind: 'flow',
value: flowStore.val.value,
schema: flowStore.val.schema
})}
/>
<InvisibleRunsSetting
kind="flow"
@@ -4,6 +4,12 @@
import DeployOnBehalfOfFields from './DeployOnBehalfOfFields.svelte'
import { deployOnBehalfOfQuestion } from './onBehalfOf'
import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte'
import {
createPendingServiceAccount,
getPendingServiceAccount
} from '$lib/components/access/serviceAccounts.svelte'
import type { NeedsSource } from '$lib/components/access/detectNeeds'
import { sendUserToast } from '$lib/toast'
interface Props {
open: boolean
@@ -25,6 +31,9 @@
/** Apps: who can open the app, which decides whether viewers are recorded at all. */
executionMode?: string
rawApp?: boolean
/** The item's path and its editor's copy: what a service account made here is built from. */
itemPath?: string
needsSource?: () => NeedsSource | undefined
onConfirmed: () => void
}
@@ -42,6 +51,8 @@
targetWorkspace,
executionMode,
rawApp = false,
itemPath,
needsSource,
onConfirmed
}: Props = $props()
@@ -57,6 +68,26 @@
})
)
let pickerOpen = $state(false)
let creatingOpen = $state(false)
let deploying = $state(false)
async function confirm() {
const runsAs = question.runsAs
if (getPendingServiceAccount(targetWorkspace, runsAs)) {
deploying = true
try {
const created = await createPendingServiceAccount(targetWorkspace, runsAs)
if (created) email = created
} catch (e) {
sendUserToast(`Could not create ${runsAs}: ${e?.body ?? e?.message ?? e}`, true)
return
} finally {
deploying = false
}
}
open = false
onConfirmed()
}
</script>
<ConfirmationModal
@@ -65,12 +96,10 @@
title={question.title}
confirmationText="Deploy"
confirmDisabled={folderDefaultLoading}
keyListen={!pickerOpen}
loading={deploying}
keyListen={!pickerOpen && !creatingOpen}
alwaysPortal
onConfirmed={() => {
open = false
onConfirmed()
}}
onConfirmed={confirm}
onCanceled={() => (open = false)}
>
<div class="flex flex-col gap-4">
@@ -87,6 +116,9 @@
{rawApp}
aboveConfirmationModal
onPickerOpenChange={(o) => (pickerOpen = o)}
{itemPath}
{needsSource}
onCreatingChange={(o) => (creatingOpen = o)}
/>
<TextInput bind:value={message} inputProps={{ placeholder: 'Deployment message' }} />
</div>
@@ -3,6 +3,8 @@
import { appOnBehalfOfTooltip, deployOnBehalfOfQuestion } from './onBehalfOf'
import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte'
import { AlertTriangle } from 'lucide-svelte'
import RunAsNotes from '$lib/components/access/RunAsNotes.svelte'
import type { NeedsSource } from '$lib/components/access/detectNeeds'
/** The body of a deploy's question about the user an item runs on behalf of, which the host
* titles with `deployOnBehalfOfQuestion`. */
@@ -24,6 +26,10 @@
/** Inside a `ConfirmationModal`: see `OnBehalfOfSelector`. */
aboveConfirmationModal?: boolean
onPickerOpenChange?: (open: boolean) => void
/** The item's path and its editor's copy: what a service account made here is built from. */
itemPath?: string
needsSource?: () => NeedsSource | undefined
onCreatingChange?: (open: boolean) => void
}
let {
@@ -38,7 +44,10 @@
executionMode,
rawApp = false,
aboveConfirmationModal = false,
onPickerOpenChange
onPickerOpenChange,
itemPath,
needsSource,
onCreatingChange
}: Props = $props()
const operatingUser = useOperatingUser()
@@ -90,6 +99,9 @@
{aboveConfirmationModal}
{onPickerOpenChange}
hideDescription
{itemPath}
{needsSource}
showReads={false}
/>
{#if question.on && question.unchanged}
<!-- pl-9 lines it up under the switch's label, as SettingToggle indents its contents. -->
@@ -107,3 +119,18 @@
</div>
{/if}
</div>
<RunAsNotes
{kind}
{targetWorkspace}
{itemPath}
{needsSource}
runsAs={question.on ? question.runsAs : undefined}
{isNew}
{savedPermissionedAs}
runnablesRunAsCaller={executionMode === 'viewer'}
onUseAccount={(username, accountEmail) => {
email = accountEmail
permissionedAs = `u/${username}`
}}
{onCreatingChange}
/>
@@ -57,6 +57,11 @@
import DeployOnBehalfOfFields from './DeployOnBehalfOfFields.svelte'
import { deployAsksOnBehalfOf, deployOnBehalfOfQuestion } from './onBehalfOf'
import { logFirstDeploy } from './sharingTelemetry'
import type { NeedsSource } from '$lib/components/access/detectNeeds'
import {
createPendingServiceAccount,
getPendingServiceAccount
} from '$lib/components/access/serviceAccounts.svelte'
const operatingWorkspace = useOperatingWorkspace()
const operatingUser = useOperatingUser()
@@ -76,6 +81,8 @@
let runAsWorkspace: string | undefined = $state()
let runAsEmail: string | undefined = $state()
let runAsPermissionedAs: string | undefined = $state()
let needsSource: (() => NeedsSource | undefined) | undefined = $state()
let deploying = $state(false)
let pathField: Path | undefined = $state()
let resolve: ((choice: FirstDeployChoice | undefined) => void) | undefined
@@ -136,6 +143,8 @@
email: string | undefined
permissionedAs: string | undefined
targetWorkspace: string
/** The item as its editor holds it, read for what it uses. */
needsSource?: () => NeedsSource | undefined
}
}): Promise<FirstDeployChoice | undefined> {
resolve?.(undefined)
@@ -144,6 +153,7 @@
runAsWorkspace = opts.runAs?.targetWorkspace
runAsEmail = opts.runAs?.email
runAsPermissionedAs = opts.runAs?.permissionedAs
needsSource = opts.runAs?.needsSource
summary = opts.summary
pathError = ''
// A new item is parked at `draft_<uuid>` or named `<adjective>_<kind>` until someone names it.
@@ -182,8 +192,21 @@
else deploy()
}
function deploy() {
async function deploy() {
if (!path || pathError) return
const runsAs = question.on ? question.runsAs : undefined
if (runAsWorkspace !== undefined && getPendingServiceAccount(runAsWorkspace, runsAs)) {
deploying = true
try {
const created = await createPendingServiceAccount(runAsWorkspace, runsAs)
if (created) runAsEmail = created
} catch (e) {
sendUserToast(`Could not create ${runsAs}: ${e?.body ?? e?.message ?? e}`, true)
return
} finally {
deploying = false
}
}
finish({
summary,
path,
@@ -231,11 +254,17 @@
targetWorkspace={runAsWorkspace ?? ''}
executionMode={isApp ? appMode : undefined}
rawApp={kind === 'raw_app'}
itemPath={path}
{needsSource}
/>
<div class="flex flex-row justify-end gap-2">
<Button variant="default" unifiedSize="md" onclick={() => (step = 'details')}>Back</Button>
<Button variant="accent" unifiedSize="md" disabled={folderDefault.loading} onclick={deploy}
>Deploy</Button
<Button
variant="accent"
unifiedSize="md"
disabled={folderDefault.loading}
loading={deploying}
onclick={deploy}>Deploy</Button
>
</div>
</div>
@@ -9,6 +9,9 @@
import { AlertTriangle } from 'lucide-svelte'
import SettingToggle from './SettingToggle.svelte'
import { canPreserveOnBehalfOf, deployedPermissionedAs, WM_DEPLOYERS_GROUP } from './onBehalfOf'
import { useServiceAccounts } from '$lib/components/access/serviceAccounts.svelte'
import type { NeedsSource } from '$lib/components/access/detectNeeds'
import ItemReads from '$lib/components/access/ItemReads.svelte'
const DOCS_LINK =
'https://www.windmill.dev/docs/core_concepts/roles_and_permissions#run-on-behalf-of'
@@ -34,6 +37,11 @@
hideDescription?: boolean
/** The folder's default for a new item's path, which a deploy holding no user takes. */
folderDefault?: string
/** See `OnBehalfOfSelector`: what a service account created from the picker is built from. */
itemPath?: string
needsSource?: () => NeedsSource | undefined
/** Off where the host renders `RunAsNotes`, which lists what the item reads itself. */
showReads?: boolean
}
let {
@@ -49,7 +57,10 @@
aboveConfirmationModal = false,
onPickerOpenChange,
hideDescription = false,
folderDefault
folderDefault,
itemPath,
needsSource,
showReads = true
}: Props = $props()
// The label keeps the docs' term; the description says what it gives, access to resources,
@@ -103,6 +114,19 @@
deployPermissionedAs !== savedPermissionedAs
)
const serviceAccounts = useServiceAccounts(() => targetWorkspace)
const serviceAccount = $derived(
enabled && deployPermissionedAs
? serviceAccounts.current.find((a) => `u/${a.username}` === deployPermissionedAs)
: undefined
)
const serviceAccountReads = $derived(
serviceAccount
? [...serviceAccount.folders.map((f) => `f/${f}`), ...(serviceAccount.items ?? [])]
: []
)
function setMe() {
email = actingUser?.email
permissionedAs = myPermissionedAs
@@ -137,6 +161,9 @@
readOnlyWithoutPreserve
{aboveConfirmationModal}
{onPickerOpenChange}
{itemPath}
{needsSource}
offerCreate
/>
{#if willChange}
<AlertTriangle size={14} class="text-yellow-500" />
@@ -145,6 +172,16 @@
>
{/if}
</div>
{#if serviceAccount}
<div class="text-2xs text-secondary">
{serviceAccount.pending
? 'New service account, created when you deploy.'
: 'Service account.'}
{serviceAccountReads.length
? `Reads ${serviceAccountReads.join(', ')}.`
: 'No folder is shared with it.'}
</div>
{/if}
{#if composesApp}
<div class="text-2xs text-secondary">
Apps you build run on behalf of you once you deploy them.
@@ -208,3 +245,16 @@
{@render picker()}
</SettingToggle>
{/if}
<!-- pl-9 lines it up under the switch's label. -->
{#if showReads}
<div class={required ? 'mt-1' : 'mt-1 pl-9'}>
<ItemReads
workspace={targetWorkspace}
{kind}
{itemPath}
{needsSource}
account={deployPermissionedAs}
/>
</div>
{/if}
@@ -100,6 +100,7 @@
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import { useRoleCapabilities } from '$lib/operatorWriteRights'
import { conformBuilderAppPolicy } from './builderAppPolicy'
import { dropStalePending } from '../access/serviceAccounts.svelte'
const operatingWorkspace = useOperatingWorkspace()
const roleCaps = useRoleCapabilities()
@@ -280,6 +281,10 @@
// Everything under the editor acts on it too (see operatingWorkspace.svelte.ts).
setOperatingWorkspace(() => opWorkspace)
const operatingUser = useActingUser(() => opWorkspace)
dropStalePending(
untrack(() => opWorkspace),
untrack(() => policy)
)
let previewOnBehalfOf = $derived(appPreviewOnBehalfOf(operatingUser.current, policy))
// The path autosaves land on, which is what the session preview loads the app by.
@@ -70,6 +70,8 @@
import DeployButton from '$lib/components/DeployButton.svelte'
import type { Runnable } from './RawAppInlineScriptRunnable.svelte'
import { updateRawAppPolicy } from './rawAppPolicy'
import { createPolicyServiceAccount } from '../access/serviceAccounts.svelte'
import type { NeedsSource } from '../access/detectNeeds'
import { withoutSharedPolicySettings } from '../apps/editor/appDraftSettings'
import { saveRawAppFork } from './forkRawApp.svelte'
import { aiChatManager } from '../copilot/chat/AIChatManager.svelte'
@@ -413,6 +415,8 @@
return updateRawAppPolicy(runnables, policy)
}
const needsSource = (): NeedsSource => ({ kind: 'app', value: runnables })
/** Resolves to whether the app was created. */
async function createApp(path: string): Promise<boolean> {
if (!app) {
@@ -422,6 +426,7 @@
if (!policy.execution_mode) {
policy.execution_mode = 'publisher'
}
if (!(await createPolicyServiceAccount(opWorkspace!, policy))) return false
// Read for the path being created: the first-deploy dialog may have just chosen it.
setDeployedOnBehalfOf(policy, actingUser, await folderDefault.refetch())
try {
@@ -483,6 +488,7 @@
}
async function handleUpdateApp(npath: string) {
if (!(await createPolicyServiceAccount(opWorkspace!, policy))) return
// We have to make sure there is no updates when we clicked the button
await compareVersions()
@@ -760,7 +766,8 @@
runAs: {
email: policy.on_behalf_of_email,
permissionedAs: policy.on_behalf_of,
targetWorkspace: opWorkspace ?? ''
targetWorkspace: opWorkspace ?? '',
needsSource
}
})
if (!choice) return
@@ -1006,6 +1013,8 @@
executionMode={policy.execution_mode}
targetWorkspace={opWorkspace ?? ''}
rawApp
itemPath={newEditedPath || appPath}
{needsSource}
onConfirmed={deployNow}
/>
@@ -1036,6 +1045,7 @@
bind:labels
bind:customPath
onAppChanged={applyAppAccess}
{needsSource}
/>
{#if offersSharing}
@@ -119,10 +119,11 @@
>
{#each processedItems ?? [] as item, itemIndex}
{#if (item.__select_group && itemIndex === 0) || processedItems?.[itemIndex - 1]?.__select_group !== item.__select_group}
<!-- Same section title as DropdownV2's `sectionTitle`, so grouped menus read alike. -->
<li
class={twMerge(
'mx-4 pb-1 mb-2 text-xs font-semibold text-primary border-b border-border-light',
itemIndex === 0 ? 'mt-3' : 'mt-6'
'px-4 pt-1.5 pb-1 text-2xs uppercase tracking-wide text-secondary',
itemIndex === 0 ? 'mt-1' : 'mt-1 border-t border-border-light pt-2.5'
)}
>
{item.__select_group}