feat(secrets): reveal visible values to members by icecrasher321 · Pull Request #7231 · simstudioai/sim · GitHub
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
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
Loading
Loading