Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions apps/docs/content/docs/en/platform/credentials.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ Both masking and model-bound projection match only exact values in either case.

Copilot's Function and code-execution tools receive a saved secret only when their code explicitly contains a valid `{{KEY}}` reference. Direct `environmentVariables.KEY` access, shell `$KEY`, dynamic names, literals, and configured-but-unused secrets do not mount a value. Code execution requires workspace write access, and the caller must be allowed to **use** the secret — the same set a workflow resolves for them: your own Personal secrets, and Workspace secrets you hold an active grant on as a Credential Member or Credential Admin, which a workspace admin holds on every key. A secret you hold no grant on does not mount, and neither does one whose grant is revoked or still pending.

This matches what a workflow Function block already resolves for the same person, deliberately. Being able to run a secret is not the same as being able to read it: the value stays masked under **Settings → Secrets**, and **See usage** stays visible only to that secret's admins, so a Credential Member using a secret in code is recorded for whoever can rotate it.
This matches what a workflow Function block already resolves for the same person, deliberately. Being able to run a secret is not normally the same as being able to read it: Credential Members can reveal a workspace secret under **Settings → Secrets** only when a Credential Admin has enabled **Show value in logs and Chat**. **See usage** remains visible only to that secret's admins, so a Credential Member using a secret in code is recorded for whoever can rotate it.

Headless surfaces use their saved **Secret access** setting:

Expand All @@ -118,7 +118,7 @@ Click **Details** on any secret row to open its detail view.

From here you can:

- View the **Key** and edit the **Value**
- View the **Key** and reveal the **Value** when visibility is enabled; Credential Admins can edit it
- Toggle **Visibility** — show the value unmasked in run output; see [Visibility](#visibility)
- Edit the **Description** — an optional note telling teammates what the secret is for. Workspace secrets only; a personal secret is not shared, so it has none
- Manage **Members** — invite teammates by email and assign them an **Admin** or **Member** role
Expand All @@ -135,6 +135,7 @@ By default, a secret's resolved value is masked everywhere Sim shows run output
- Run logs, Chat, and code output show the real value instead of `{{KEY}}`
- Files a run writes with the value in them stay readable and attachable
- The Secrets API list includes the value for this secret, so external agents can read it directly instead of scraping logs
- Credential Members can reveal the value under **Settings → Secrets**, without gaining permission to edit it

The value becomes visible to **anyone who can see this workspace's runs** — including publicly shared log links and log exports, and regardless of member restrictions on the secret itself. Only turn it on for values you'd be comfortable printing in a log.

Expand All @@ -146,7 +147,7 @@ The switch applies to future runs only. Logs written while the secret was masked

This answers the question worth asking before rotating a key: who has been using it, inside what, and how recently.

Only people who can read the value can see it — a Credential Admin on a workspace secret, or the owner of a personal one. For everyone else the action is visible but disabled, because the trail names workflows, people, and run IDs, which is the same information masking withholds. Two people who each hold a personal secret under the same name see only their own runs.
Only Credential Admins on a workspace secret, or the owner of a personal one, can see its usage. For everyone else the action is visible but disabled because the trail names workflows, people, and run IDs. Two people who each hold a personal secret under the same name see only their own runs.

<Callout>
Usage is recorded independently of execution logs, so it outlives them: logs expire under your workspace's retention setting, while the record of who touched a credential does not. It records what a run resolved, subject to the recognition limits under [Execution log protection](#execution-log-protection) — a read Sim cannot attribute is left out rather than guessed at, so treat an empty trail as "nothing recognized," not proof a secret was never used.
Expand All @@ -157,7 +158,7 @@ Usage is recorded independently of execution logs, so it outlives them: logs exp
| | Workspace | Personal |
|---|---|---|
| **Who sees the name** | All workspace members, including external workspace members | Only you |
| **Who sees the value** | Workspace admins and that secret's Credential Admins | Only you |
| **Who sees the value** | Workspace admins and that secret's Credential Admins; Credential Members when **Show value in logs and Chat** is enabled | Only you |
| **Use in workflows and code** | Any member can use | Only you can use |
| **Best for** | Production workflows, shared services | Testing, personal API keys |
| **Who can edit** | Workspace admins and that secret's Credential Admins | Only you |
Expand Down
21 changes: 21 additions & 0 deletions apps/sim/app/api/workspaces/[id]/environment/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ describe('GET /api/workspaces/[id]/environment', () => {
personalDecrypted: { PERSONAL: 'personal-secret', SHARED_PERSONAL: 'shared-secret' },
personalOwners: { PERSONAL: 'u-1', SHARED_PERSONAL: 'owner-2' },
conflicts: [],
workspaceUnredactedKeys: [],
})
mockGetPersonalEnvKeyRawAccess.mockResolvedValue({
ownedKeys: new Set(['PERSONAL']),
Expand Down Expand Up @@ -101,6 +102,26 @@ describe('GET /api/workspaces/[id]/environment', () => {
expect(body.data.workspace.DATABASE_URL).toBe('')
})

it('reveals an unredacted workspace value to a read-only credential member', async () => {
mockGetUserEntityPermissions.mockResolvedValue('read')
mockGetWorkspaceEnvKeyAdminAccess.mockResolvedValue({
adminKeys: new Set<string>(),
knownKeys: new Set(['OPENAI_API_KEY', 'DATABASE_URL']),
})
mockGetPersonalAndWorkspaceEnv.mockResolvedValue({
workspaceDecrypted: { OPENAI_API_KEY: 'sk-secret', DATABASE_URL: 'postgres://secret' },
personalDecrypted: {},
personalOwners: {},
conflicts: [],
workspaceUnredactedKeys: ['OPENAI_API_KEY'],
})

const { body } = await callGet()

expect(body.data.workspace.OPENAI_API_KEY).toBe('sk-secret')
expect(body.data.workspace.DATABASE_URL).toBe('')
})

it('reveals legacy keys (no per-secret ACL) only to workspace admins', async () => {
mockGetUserEntityPermissions.mockResolvedValue('admin')
mockGetWorkspaceEnvKeyAdminAccess.mockResolvedValue({
Expand Down
25 changes: 16 additions & 9 deletions apps/sim/app/api/workspaces/[id]/environment/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,25 +36,26 @@ import {
const logger = createLogger('WorkspaceEnvironmentAPI')

/**
* Restricts decrypted workspace env values to administrators. Members (including
* read-only) receive the variable names with empty values so editor autocomplete
* and conflict detection keep working without leaking secret values. A value is
* revealed when the caller is a workspace admin (which includes organization
* admins) or a per-secret credential admin of that key. Mirrors the per-key edit
* gating in PUT/DELETE: if you can administer a secret, you can read it.
* Reveals a workspace secret only to a workspace administrator, that secret's
* credential administrator, or a caller allowed to use a secret explicitly
* marked visible. The environment snapshot has already limited
* `workspaceUnredactedKeys` to secrets the caller may use.
*/
async function maskWorkspaceEnvForViewer({
workspaceDecrypted,
workspaceId,
userId,
permission,
workspaceUnredactedKeys,
}: {
workspaceDecrypted: Record<string, string>
workspaceId: string
userId: string
permission: PermissionType
workspaceUnredactedKeys: readonly string[]
}): Promise<Record<string, string>> {
const workspaceKeys = Object.keys(workspaceDecrypted)
const unredactedKeys = new Set(workspaceUnredactedKeys)
const { adminKeys } = await getWorkspaceEnvKeyAdminAccess({
workspaceId,
envKeys: workspaceKeys,
Expand All @@ -63,7 +64,7 @@ async function maskWorkspaceEnvForViewer({

const masked: Record<string, string> = {}
for (const key of workspaceKeys) {
const canViewValue = permission === 'admin' || adminKeys.has(key)
const canViewValue = permission === 'admin' || adminKeys.has(key) || unredactedKeys.has(key)
masked[key] = canViewValue ? workspaceDecrypted[key] : ''
}
return masked
Expand Down Expand Up @@ -119,14 +120,20 @@ export const GET = withRouteHandler(
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

const { workspaceDecrypted, personalDecrypted, personalOwners, conflicts } =
await getPersonalAndWorkspaceEnv(userId, workspaceId)
const {
workspaceDecrypted,
personalDecrypted,
personalOwners,
conflicts,
workspaceUnredactedKeys,
} = await getPersonalAndWorkspaceEnv(userId, workspaceId)

const workspace = await maskWorkspaceEnvForViewer({
workspaceDecrypted,
workspaceId,
userId,
permission,
workspaceUnredactedKeys,
})
const personal = await maskPersonalEnvForViewer({
personalDecrypted,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* @vitest-environment jsdom
*/
import { act, type ComponentProps } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

vi.mock('@sim/emcn', () => ({
ChipInput: (props: ComponentProps<'input'>) => <input {...props} />,
}))

import { SecretValueField } from '@/app/workspace/[workspaceId]/settings/components/secrets/components/secret-value-field/secret-value-field'

let container: HTMLDivElement
let root: Root

function input(): HTMLInputElement {
const field = container.querySelector('input')
if (!field) throw new Error('Secret value field did not render')
return field
}

beforeEach(() => {
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
})

afterEach(() => {
act(() => root.unmount())
container.remove()
})

describe('SecretValueField', () => {
it('lets a read-only viewer reveal an allowed value without making it editable', () => {
act(() => root.render(<SecretValueField value='visible-secret' canEdit={false} canReveal />))

expect(input().readOnly).toBe(true)
expect(input().value).toBe('•'.repeat(10))

act(() => input().focus())

expect(input().value).toBe('visible-secret')
expect(input().readOnly).toBe(true)
})

it('never places a withheld value in the field', () => {
act(() => root.render(<SecretValueField value='hidden-secret' canEdit={false} />))

expect(input().value).toBe('•'.repeat(10))
act(() => input().focus())
expect(input().value).toBe('•'.repeat(10))
})

it('keeps an empty editable value empty while unfocused', () => {
act(() => root.render(<SecretValueField value='' />))

expect(input().value).toBe('')
})
})
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
'use client'

import type { ComponentProps, CSSProperties } from 'react'
import type { ComponentProps } from 'react'
import { useState } from 'react'
import { ChipInput } from '@sim/emcn'

const BULLET = '\u2022'

/**
* Viewers always see this many bullets regardless of the real value, which the
* server withholds (empty string) for non-admins. A fixed length also avoids
* leaking the secret's length.
*/
/** Fixed-length masks avoid disclosing the secret's length. */
const VIEWER_MASK_LENGTH = 10

type SecretValueFieldProps = Omit<
Expand All @@ -20,11 +16,11 @@ type SecretValueFieldProps = Omit<
value: string
onChange?: (value: string) => void
/**
* Whether the caller may reveal (on focus) and edit the value. When `false`
* the real value is never shown — only a fixed-length mask — and the field is
* read-only (e.g. a non-admin viewer).
* Whether the caller may edit the value. Editors can always reveal it.
*/
canEdit?: boolean
/** Whether a read-only caller may reveal the value on focus. */
canReveal?: boolean
/** Render the real value without masking, e.g. an overridden/conflicted field. */
unmasked?: boolean
/** Force read-only even when {@link canEdit} is true (e.g. a conflicted field). */
Expand All @@ -33,9 +29,9 @@ type SecretValueFieldProps = Omit<

/**
* The single source of truth for displaying an environment-variable value:
* masks the value with bullets while unfocused, reveals it on focus for editors,
* and keeps the field read-only (masked) for viewers who can't edit. Shared by
* the secrets list and the secret detail page so masking never diverges.
* masks revealable values while unfocused, reveals them on focus, and grants
* editing independently. Callers without reveal access receive a fixed-length
* mask. Shared by the secrets list and secret detail page.
*
* Rendered as a {@link ChipInput}; the chip chrome carries the canonical 30px
* chip-field height, and the caller's `className` only positions it (e.g.
Expand All @@ -46,6 +42,7 @@ export function SecretValueField({
value,
onChange,
canEdit = true,
canReveal = false,
unmasked = false,
readOnly = false,
onFocus,
Expand All @@ -56,12 +53,10 @@ export function SecretValueField({
}: SecretValueFieldProps) {
const [focused, setFocused] = useState(false)
const editable = canEdit && !readOnly
const maskActive = canEdit && !unmasked && !focused
const displayValue = canEdit ? value : BULLET.repeat(VIEWER_MASK_LENGTH)

const mergedStyle: CSSProperties | undefined = maskActive
? ({ ...style, WebkitTextSecurity: 'disc' } as CSSProperties)
: style
const revealable = canEdit || canReveal
const maskActive = revealable && !unmasked && !focused
const displayValue =
!revealable || (maskActive && value.length > 0) ? BULLET.repeat(VIEWER_MASK_LENGTH) : value

return (
<ChipInput
Expand All @@ -70,7 +65,7 @@ export function SecretValueField({
type='text'
value={displayValue}
readOnly
style={mergedStyle}
style={style}
onChange={(event) => {
if (editable) onChange?.(event.target.value)
}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ interface WorkspaceVariableRowProps {
pendingKeyValue: string
hasCredential: boolean
canEdit: boolean
canReveal: boolean
/** Renaming creates a new key + deletes the old, so it also needs create access. */
canRename: boolean
onRenameStart: (key: string) => void
Expand All @@ -211,6 +212,7 @@ function WorkspaceVariableRow({
pendingKeyValue,
hasCredential,
canEdit,
canReveal,
canRename,
onRenameStart,
onPendingKeyChange,
Expand Down Expand Up @@ -252,6 +254,7 @@ function WorkspaceVariableRow({
value={value}
onChange={(next) => onValueChange(envKey, next)}
canEdit={canEdit}
canReveal={canReveal}
name={`workspace_env_value_${envKey}_${autofillSalt}`}
/>
<SecretRowMenu
Expand Down Expand Up @@ -1035,6 +1038,8 @@ export function SecretsManager() {
).map(([key, value]) => {
const cred = workspaceEnvKeyToCredential.get(key)
const canEditRow = canCreateWorkspaceSecret && cred?.role === 'admin'
const canRevealRow =
isWorkspaceAdmin || cred?.role === 'admin' || Boolean(cred?.unredacted)
return (
<WorkspaceVariableRow
key={key}
Expand All @@ -1044,15 +1049,14 @@ export function SecretsManager() {
pendingKeyValue={pendingKeyValue}
hasCredential={Boolean(cred)}
canEdit={canEditRow}
canReveal={canRevealRow}
canRename={canCreateWorkspaceSecret && canEditRow}
onRenameStart={setRenamingKey}
onPendingKeyChange={setPendingKeyValue}
onRenameEnd={handleWorkspaceKeyRename}
onValueChange={handleWorkspaceValueChange}
onDelete={handleDeleteWorkspaceVar}
onViewDetails={
canCreateWorkspaceSecret && cred ? handleViewDetails : undefined
}
onViewDetails={cred ? handleViewDetails : undefined}
/>
)
})}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ export function SecretDetail({ workspaceId, credentialId }: SecretDetailProps) {
value={valueField.value}
onChange={valueField.setValue}
canEdit={valueField.canEdit}
canReveal={!isPersonal && credential.unredacted}
Comment thread
icecrasher321 marked this conversation as resolved.
unmasked={valueField.isConflicted}
readOnly={valueField.isConflicted}
placeholder='Enter value'
Expand Down
41 changes: 40 additions & 1 deletion apps/sim/hooks/queries/environment.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ vi.mock('@/lib/environment/api', () => ({
fetchWorkspaceEnvironment: mockFetchWorkspaceEnvironment,
}))

import { useWorkspaceEnvironment } from '@/hooks/queries/environment'
import { environmentKeys, useWorkspaceEnvironment } from '@/hooks/queries/environment'

function renderWorkspaceEnvironment(workspaceId: string, enabled?: boolean) {
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
Expand Down Expand Up @@ -59,4 +59,43 @@ describe('useWorkspaceEnvironment', () => {
expect(mockFetchWorkspaceEnvironment).not.toHaveBeenCalled()
unmount()
})

it('does not retain decrypted values while a different workspace loads', () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const container = document.createElement('div')
const root = createRoot(container)
const pendingWorkspace = new Promise<never>(() => {})

queryClient.setQueryData(environmentKeys.workspace('workspace-1'), {
workspace: { SHARED_KEY: 'workspace-1-secret' },
personal: {},
conflicts: [],
})
mockFetchWorkspaceEnvironment.mockReturnValueOnce(pendingWorkspace)

function Probe({ workspaceId }: { workspaceId: string }) {
const { data } = useWorkspaceEnvironment(workspaceId)
return <span>{data?.workspace.SHARED_KEY ?? 'loading'}</span>
}

act(() => {
root.render(
<QueryClientProvider client={queryClient}>
<Probe workspaceId='workspace-1' />
</QueryClientProvider>
)
})
expect(container.textContent).toBe('workspace-1-secret')

act(() => {
root.render(
<QueryClientProvider client={queryClient}>
<Probe workspaceId='workspace-2' />
</QueryClientProvider>
)
})

expect(container.textContent).toBe('loading')
act(() => root.unmount())
})
})
Loading
Loading