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
58 changes: 58 additions & 0 deletions apps/sim/lib/internal/onepassword/json-patch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,55 @@ describe('applyOnePasswordPatch', () => {

expect(item.tags).toEqual(['two'])
})

it.each([
{ name: 'a missing field ID', op: 'replace', path: '/fields/missing-id/value' },
{ name: 'a missing array element', op: 'remove', path: '/fields/missing-id' },
{ name: 'an absent key', op: 'replace', path: '/title' },
{ name: 'removal of an absent key', op: 'remove', path: '/fields/0/label' },
{ name: 'a parent that is not a container', op: 'add', path: '/fields/0/value/x' },
{ name: 'an append that is not an add', op: 'replace', path: '/fields/-' },
] as const)('reports $name as missed and leaves the item unchanged', ({ op, path }) => {
const item: Record<string, unknown> = { fields: [{ id: 'password', value: 'old' }] }

expect(applyOnePasswordPatch(item, { op, path, value: 'new' })).toBe(false)
expect(item).toEqual({ fields: [{ id: 'password', value: 'old' }] })
})

it('inserts an array add at its index rather than overwriting the element there', () => {
const item: Record<string, unknown> = { tags: ['a', 'b'] }

expect(applyOnePasswordPatch(item, { op: 'add', path: '/tags/0', value: 'first' })).toBe(true)
expect(applyOnePasswordPatch(item, { op: 'add', path: '/tags/3', value: 'last' })).toBe(true)
expect(applyOnePasswordPatch(item, { op: 'add', path: '/tags/9', value: 'x' })).toBe(false)
expect(item.tags).toEqual(['first', 'a', 'b', 'last'])
})

it('resolves an add segment by ID before treating it as the array length', () => {
const item: Record<string, unknown> = { fields: [{ id: '1', value: 'by-id' }] }

expect(
applyOnePasswordPatch(item, { op: 'add', path: '/fields/1', value: { id: 'new' } })
).toBe(true)
expect(item.fields).toEqual([{ id: 'new' }, { id: '1', value: 'by-id' }])
})

it('appends a single field added at the fields array, as Connect does', () => {
const item: Record<string, unknown> = { fields: [{ id: 'password', value: 'old' }] }
const field = { label: 'API key', type: 'CONCEALED', value: 'secret' }

expect(applyOnePasswordPatch(item, { op: 'add', path: '/fields', value: field })).toBe(true)
expect(item.fields).toEqual([{ id: 'password', value: 'old' }, field])
})

it('adds a new key under an existing parent', () => {
const item: Record<string, unknown> = { fields: [{ id: 'password', value: 'old' }] }

expect(
applyOnePasswordPatch(item, { op: 'add', path: '/fields/password/label', value: 'pw' })
).toBe(true)
expect(item.fields).toEqual([{ id: 'password', value: 'old', label: 'pw' }])
})
})

describe('prototype paths', () => {
Expand Down Expand Up @@ -83,6 +132,15 @@ describe('patch bounds', () => {
expect(isSafeOnePasswordPatch(operations)).toBe(false)
})

it.each(['add', 'replace'])(
'refuses a %s without a value, which would blank its target',
(op) => {
expect(isSafeOnePasswordPatch([{ op, path: '/fields/password/value' }])).toBe(false)
expect(isSafeOnePasswordPatch([{ op, path: '/fields/password/value', value: '' }])).toBe(true)
expect(isSafeOnePasswordPatch([{ op: 'remove', path: '/fields/password' }])).toBe(true)
}
)

it('refuses a patch with more operations than the cap', () => {
const operations = Array.from({ length: MAX_PATCH_OPERATIONS + 1 }, () => ({
op: 'replace',
Expand Down
93 changes: 47 additions & 46 deletions apps/sim/lib/internal/onepassword/json-patch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ export const MAX_PATCH_PATH_DEPTH = 16
const PATCH_OPS = new Set<unknown>(['add', 'remove', 'replace'])

/**
* Whether every operation is one 1Password accepts and its path names a field of the item's own
* data, within the size bounds. Patches are applied to a plain object in this process, so a path
* through `__proto__` would write onto every object here, and a path naming nothing would report
* success for a patch that changed nothing.
* Whether every operation is one 1Password accepts and its path is a non-empty path of safe keys,
* within the size bounds. Patches are applied to a plain object in this process, so a path through
* `__proto__` would write onto every object here. Whether a path reaches a field of the item is
* known only once applied ({@link applyOnePasswordPatch}).
*/
export function isSafeOnePasswordPatch(operations: unknown): operations is JsonPatchOperation[] {
return (
Expand All @@ -35,7 +35,9 @@ export function isSafeOnePasswordPatch(operations: unknown): operations is JsonP
operations.every((operation) => {
const record = recordValue(operation)
const path = record?.path
if (!PATCH_OPS.has(record?.op) || typeof path !== 'string') return false
if (!record || !PATCH_OPS.has(record.op) || typeof path !== 'string') return false
// RFC 6902: add and replace carry a value; without one the target would be blanked.
if (record.op !== 'remove' && !Object.hasOwn(record, 'value')) return false
const segments = path.split('/').filter(Boolean)
return (
segments.length > 0 &&
Expand Down Expand Up @@ -63,57 +65,56 @@ function arrayElementForSegment(target: unknown[], segment: string): unknown {
return index === -1 ? undefined : target[index]
}

/** Applies the Connect API's ID-aware RFC6902 path semantics. */
/**
* Applies one operation with the Connect API's ID-aware RFC 6902 path semantics, and returns
* whether it reached its target. As in RFC 6902, `replace` and `remove` need an existing target,
* `add` an existing parent, and `add` into an array inserts. As in the Connect API, a single element
* added at an array appends to it. A patch naming nothing is refused, never reported as a change.
*/
export function applyOnePasswordPatch(
item: Record<string, unknown>,
operation: JsonPatchOperation
): void {
): boolean {
const segments = operation.path.split('/').filter(Boolean)
const rootKey = segments[0]
if (!rootKey || !segments.every((segment) => isSafeKey(segment))) return

if (segments.length === 1) {
if (operation.op === 'replace' || operation.op === 'add') {
item[rootKey] = operation.value
} else {
delete item[rootKey]
}
return
}
const lastSegment = segments.at(-1)
if (!lastSegment || !segments.every((segment) => isSafeKey(segment))) return false

let target: unknown = item
for (let index = 0; index < segments.length - 1; index++) {
const segment = segments[index]
if (!segment) return
if (Array.isArray(target)) {
target = arrayElementForSegment(target, segment)
} else {
target = ownValue(recordValue(target), segment)
}
if (target === undefined || target === null) return
for (const segment of segments.slice(0, -1)) {
target = Array.isArray(target)
? arrayElementForSegment(target, segment)
: ownValue(recordValue(target), segment)
if (target === undefined) return false
}

const lastSegment = segments.at(-1)
if (!lastSegment) return

if (operation.op === 'replace' || operation.op === 'add') {
if (Array.isArray(target) && lastSegment === '-') {
target.push(operation.value)
} else if (Array.isArray(target)) {
const index = arrayIndexForSegment(target, lastSegment)
if (index !== -1) target[index] = operation.value
} else {
const record = recordValue(target)
if (record) record[lastSegment] = operation.value
if (Array.isArray(target)) {
if (operation.op === 'add') {
const found = lastSegment === '-' ? -1 : arrayIndexForSegment(target, lastSegment)
const index =
found === -1 && (lastSegment === '-' || lastSegment === String(target.length))
? target.length
: found
if (index === -1) return false
target.splice(index, 0, operation.value)
return true
}
return
const index = arrayIndexForSegment(target, lastSegment)
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
if (index === -1) return false
if (operation.op === 'remove') target.splice(index, 1)
else target[index] = operation.value
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
return true
}

if (Array.isArray(target)) {
const index = arrayIndexForSegment(target, lastSegment)
if (index !== -1) target.splice(index, 1)
} else {
const record = recordValue(target)
if (record) delete record[lastSegment]
const record = recordValue(target)
if (!record) return false
const existing = ownValue(record, lastSegment)
// Connect appends a single element added to an array, e.g. a field added at `/fields`.
if (operation.op === 'add' && Array.isArray(existing) && !Array.isArray(operation.value)) {
existing.push(operation.value)
return true
}
if (operation.op !== 'add' && !Object.hasOwn(record, lastSegment)) return false
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
if (operation.op === 'remove') delete record[lastSegment]
else record[lastSegment] = operation.value
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
return true
}
53 changes: 53 additions & 0 deletions apps/sim/lib/internal/onepassword/operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,59 @@ describe('1Password operations', () => {
expect(put).toHaveBeenCalledOnce()
})

it('updates the notes the SDK item carries', async () => {
const existing = { id: 'item-1', notes: 'old notes', fields: [] }
// The real normalizer leaves notes out of the Connect shape.
clientMocks.normalizeSdkItem.mockImplementationOnce(
({ notes, ...connectShape }) => connectShape
)
const put = vi.fn().mockImplementation(async (item) => item)
clientMocks.createOnePasswordClient.mockResolvedValue({
items: { get: vi.fn().mockResolvedValue(existing), put },
})

await executeOnePasswordUpdateItem(
{
...SERVICE_CREDENTIALS,
vaultId: 'vault-1',
itemId: 'item-1',
operations: '[{"op":"replace","path":"/notes","value":"new notes"}]',
},
{}
)

expect(clientMocks.connectItemToSdkItem).toHaveBeenCalledWith(
expect.objectContaining({ notes: 'new notes' }),
existing
)
expect(put).toHaveBeenCalledOnce()
})

it('refuses a patch naming a field the item does not have, without saving', async () => {
const put = vi.fn()
clientMocks.createOnePasswordClient.mockResolvedValue({
items: {
get: vi
.fn()
.mockResolvedValue({ id: 'item-1', fields: [{ id: 'password', value: 'old' }] }),
put,
},
})

await expect(
executeOnePasswordUpdateItem(
{
...SERVICE_CREDENTIALS,
vaultId: 'vault-1',
itemId: 'item-1',
operations: '[{"op":"replace","path":"/fields/missing-id/value","value":"new"}]',
},
{}
)
).rejects.toMatchObject<Partial<OnePasswordOperationError>>({ status: 400 })
expect(put).not.toHaveBeenCalled()
})

it('bounds SDK file reads before and after materialization', async () => {
const read = vi.fn().mockResolvedValue(new Uint8Array(6))
clientMocks.createOnePasswordClient.mockResolvedValue({
Expand Down
13 changes: 11 additions & 2 deletions apps/sim/lib/internal/onepassword/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,8 +289,17 @@ export async function executeOnePasswordUpdateItem(
const existing = await runSdk(context.signal, () =>
client.items.get(input.vaultId, input.itemId)
)
const connectItem: Record<string, unknown> = { ...normalizeSdkItem(existing) }
for (const operation of operations) applyOnePasswordPatch(connectItem, operation)
// The Connect shape has no notes, but the SDK item has them and saves a patch to them.
const connectItem: Record<string, unknown> = {
...normalizeSdkItem(existing),
notes: existing.notes,
}
const missed = operations.find((operation) => !applyOnePasswordPatch(connectItem, operation))
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
if (missed) {
throw new OnePasswordOperationError(400, {
error: `Patch operation "${missed.op} ${missed.path}" names nothing on this item, so the item was not changed.`,
})
}
const result = await runSdk(context.signal, () =>
client.items.put(connectItemToSdkItem(connectItem, existing))
)
Expand Down
Loading