Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (claude): transactional holdings write, clean FK 400, missing-org 404

Adam Eivyefa6fb4d2aa6
diff --git a/server/routes/privacy.js b/server/routes/privacy.js
index 7d5259ac0a..a27c7af8b2 100644
--- a/server/routes/privacy.js
+++ b/server/routes/privacy.js
@@ -112,6 +112,8 @@ router.delete('/orgs/:id', asyncHandler(async (req, res) => {
router.get('/orgs/:id/holdings', asyncHandler(async (req, res) => {
const { id } = validateRequest(privacyOrgIdParamsSchema, req.params);
+ const org = await getOrg(id);
+ if (!org) throw new ServerError('Organization not found', { status: 404, code: 'NOT_FOUND' });
res.json(await getHoldingsForOrg(id));
}));
diff --git a/server/routes/privacy.test.js b/server/routes/privacy.test.js
index 252fe54070..e43b3e4e81 100644
--- a/server/routes/privacy.test.js
+++ b/server/routes/privacy.test.js
@@ -185,10 +185,17 @@ describe('DELETE /api/privacy/orgs/:id', () => {
describe('GET /api/privacy/orgs/:id/holdings', () => {
it('returns the joined masked holdings for the org', async () => {
+ orgService.getOrg.mockResolvedValueOnce({ id: VALID_UUID, name: 'Acme Bank' });
const res = await request(makeApp()).get(`/api/privacy/orgs/${VALID_UUID}/holdings`);
expect(res.status).toBe(200);
expect(res.body).toEqual([{ orgId: 'o1', vaultRecordId: 'v1', vaultMaskedValue: 'a•••@b.com' }]);
});
+
+ it('404s a missing org before ever querying holdings', async () => {
+ const res = await request(makeApp()).get(`/api/privacy/orgs/${VALID_UUID}/holdings`);
+ expect(res.status).toBe(404);
+ expect(orgService.getHoldingsForOrg).not.toHaveBeenCalled();
+ });
});
describe('PUT /api/privacy/orgs/:id/holdings', () => {
diff --git a/server/services/privacyOrgs.db.test.js b/server/services/privacyOrgs.db.test.js
index 703c56cb61..397c7b4140 100644
--- a/server/services/privacyOrgs.db.test.js
+++ b/server/services/privacyOrgs.db.test.js
@@ -109,6 +109,25 @@ describe.skipIf(!dbReady)('privacy orgs DB round-trip', () => {
expect(await orgs.getOrg(org.id)).toBe(null);
});
+ it('rejects a nonexistent vaultRecordId as a 400 and rolls back the whole call (transactional)', async () => {
+ const record = await vault.createVaultRecord({ type: 'custom', label: 'Real one', value: 'z' });
+ createdVaultRecords.push(record.id);
+ const org = await orgs.createOrg({ name: 'Rollback Org' });
+ createdOrgs.push(org.id);
+ // Seed one real holding so we can confirm it survives the failed call untouched.
+ await orgs.setOrgHoldings(org.id, [{ vaultRecordId: record.id }]);
+
+ await expect(orgs.setOrgHoldings(org.id, [
+ { vaultRecordId: record.id }, { vaultRecordId: '00000000-0000-4000-8000-000000000000' },
+ ])).rejects.toMatchObject({ status: 400, code: 'VAULT_RECORD_NOT_FOUND' });
+
+ // The transaction must have rolled back the DELETE-complement too — the
+ // pre-existing holding for `record.id` is still there, unchanged.
+ const holdings = await orgs.getHoldingsForOrg(org.id);
+ expect(holdings).toHaveLength(1);
+ expect(holdings[0].vaultRecordId).toBe(record.id);
+ });
+
it('cascades: deleting the vault record drops its holdings', async () => {
const record = await vault.createVaultRecord({ type: 'custom', label: 'Misc2', value: 'y' });
const org = await orgs.createOrg({ name: 'Another Org' });
diff --git a/server/services/privacyOrgs.js b/server/services/privacyOrgs.js
index 3c9329d58d..9fb8176d39 100644
--- a/server/services/privacyOrgs.js
+++ b/server/services/privacyOrgs.js
@@ -13,7 +13,7 @@
*/
import { randomUUID } from 'crypto';
-import { query } from '../lib/db.js';
+import { query, withTransaction } from '../lib/db.js';
import { ServerError } from '../lib/errorHandler.js';
const ORG_COLUMNS = `id, name, category, website, trust, status, contact,
@@ -160,30 +160,44 @@ export async function getOrgsHoldingRecord(vaultRecordId) {
* anything not listed is removed. Runs as one statement per side (delete the
* complement, upsert the rest) rather than a delete-all + reinsert, so an
* unrelated concurrent read never sees a momentarily-empty holdings set.
+ * The whole delete+upsert sequence runs inside ONE transaction — without it,
+ * a bad `vaultRecordId` partway through the upsert loop (foreign key
+ * violation, see below) would leave the DELETE committed but only some of
+ * the new rows written: neither the old nor the requested holdings set.
*/
export async function setOrgHoldings(orgId, holdings) {
- const org = await getOrg(orgId);
- if (!org) throw new ServerError('Organization not found', { status: 404, code: 'NOT_FOUND' });
+ await withTransaction(async (client) => {
+ const { rows: orgRows } = await client.query(`SELECT id FROM privacy_orgs WHERE id = $1`, [orgId]);
+ if (!orgRows[0]) throw new ServerError('Organization not found', { status: 404, code: 'NOT_FOUND' });
- const ids = holdings.map((h) => h.vaultRecordId);
- if (ids.length === 0) {
- await query(`DELETE FROM privacy_org_holdings WHERE org_id = $1`, [orgId]);
- } else {
- await query(
- `DELETE FROM privacy_org_holdings WHERE org_id = $1 AND vault_record_id != ALL($2::uuid[])`,
- [orgId, ids],
- );
- for (const h of holdings) {
- await query(
- `INSERT INTO privacy_org_holdings (org_id, vault_record_id, status, noted_at, updated_at)
- VALUES ($1, $2, $3, NOW(), NOW())
- ON CONFLICT (org_id, vault_record_id)
- DO UPDATE SET status = EXCLUDED.status, updated_at = NOW()`,
- [orgId, h.vaultRecordId, h.status ?? 'current'],
+ const ids = holdings.map((h) => h.vaultRecordId);
+ if (ids.length === 0) {
+ await client.query(`DELETE FROM privacy_org_holdings WHERE org_id = $1`, [orgId]);
+ } else {
+ await client.query(
+ `DELETE FROM privacy_org_holdings WHERE org_id = $1 AND vault_record_id != ALL($2::uuid[])`,
+ [orgId, ids],
);
+ for (const h of holdings) {
+ // A vaultRecordId that doesn't exist (stale UI id, typo, raced with a
+ // deletion) trips the FK constraint — surface it as a clean 400
+ // instead of a raw Postgres constraint-violation 500.
+ await client.query(
+ `INSERT INTO privacy_org_holdings (org_id, vault_record_id, status, noted_at, updated_at)
+ VALUES ($1, $2, $3, NOW(), NOW())
+ ON CONFLICT (org_id, vault_record_id)
+ DO UPDATE SET status = EXCLUDED.status, updated_at = NOW()`,
+ [orgId, h.vaultRecordId, h.status ?? 'current'],
+ ).catch((err) => {
+ if (err?.code === '23503') {
+ throw new ServerError(`Vault record ${h.vaultRecordId} not found`, { status: 400, code: 'VAULT_RECORD_NOT_FOUND' });
+ }
+ throw err;
+ });
+ }
}
- }
- console.log(`🔗 Set ${ids.length} holdings for privacy org ${orgId}`);
+ console.log(`🔗 Set ${ids.length} holdings for privacy org ${orgId}`);
+ });
return getHoldingsForOrg(orgId);
}
diff --git a/server/services/privacyOrgs.test.js b/server/services/privacyOrgs.test.js
index e5cc6e4ab7..665aaa7b4c 100644
--- a/server/services/privacyOrgs.test.js
+++ b/server/services/privacyOrgs.test.js
@@ -7,16 +7,29 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-const { queryMock } = vi.hoisted(() => ({ queryMock: vi.fn() }));
+const { queryMock, withTransactionMock } = vi.hoisted(() => ({
+ queryMock: vi.fn(),
+ withTransactionMock: vi.fn(),
+}));
-vi.mock('../lib/db.js', () => ({ query: queryMock }));
+vi.mock('../lib/db.js', () => ({ query: queryMock, withTransaction: withTransactionMock }));
const {
createOrg, listOrgs, getOrg, updateOrg, deleteOrg,
getHoldingsForOrg, getOrgsHoldingRecord, setOrgHoldings, setHoldingsStatus, getHoldingsSummary,
} = await import('./privacyOrgs.js');
-beforeEach(() => { queryMock.mockReset(); });
+beforeEach(() => {
+ queryMock.mockReset();
+ withTransactionMock.mockReset();
+});
+
+/** Fakes a transactional client whose `.query` is driven by the given handler. */
+function mockTransaction(handler) {
+ const client = { query: vi.fn(handler) };
+ withTransactionMock.mockImplementation(async (fn) => fn(client));
+ return client;
+}
const orgRow = (overrides = {}) => ({
id: 'o1', name: 'Acme Bank', category: 'bank', website: 'https://acme.example',
@@ -127,40 +140,57 @@ describe('getHoldingsForOrg / getOrgsHoldingRecord', () => {
});
describe('setOrgHoldings', () => {
- it('404s an unknown org before writing anything', async () => {
- queryMock.mockResolvedValueOnce({ rows: [] }); // getOrg
+ it('404s an unknown org before writing anything, inside the transaction', async () => {
+ const client = mockTransaction(async (sql) => {
+ if (/FROM privacy_orgs WHERE id/.test(sql)) return { rows: [] };
+ throw new Error(`unexpected query: ${sql}`);
+ });
await expect(setOrgHoldings('missing', [{ vaultRecordId: 'v1' }]))
.rejects.toMatchObject({ status: 404 });
- expect(queryMock).toHaveBeenCalledTimes(1);
+ expect(client.query).toHaveBeenCalledTimes(1);
+ expect(queryMock).not.toHaveBeenCalled(); // getHoldingsForOrg never reached
});
- it('deletes the complement and upserts the given set', async () => {
- queryMock.mockImplementation(async (sql) => {
+ it('deletes the complement and upserts the given set, all inside one transaction', async () => {
+ const client = mockTransaction(async (sql) => {
if (/FROM privacy_orgs WHERE id/.test(sql)) return { rows: [orgRow()] };
if (/DELETE FROM privacy_org_holdings/.test(sql)) return { rows: [] };
if (/INSERT INTO privacy_org_holdings/.test(sql)) return { rows: [] };
- if (/SELECT h\.org_id/.test(sql)) return { rows: [] };
- throw new Error(`unexpected query: ${sql}`);
+ throw new Error(`unexpected client query: ${sql}`);
});
+ queryMock.mockResolvedValue({ rows: [] }); // getHoldingsForOrg after commit
await setOrgHoldings('o1', [{ vaultRecordId: 'v1', status: 'current' }, { vaultRecordId: 'v2' }]);
- const deleteCall = queryMock.mock.calls.find(([sql]) => /DELETE FROM privacy_org_holdings/.test(sql));
+ const deleteCall = client.query.mock.calls.find(([sql]) => /DELETE FROM privacy_org_holdings/.test(sql));
expect(deleteCall[1]).toEqual(['o1', ['v1', 'v2']]);
- const insertCalls = queryMock.mock.calls.filter(([sql]) => /INSERT INTO privacy_org_holdings/.test(sql));
+ const insertCalls = client.query.mock.calls.filter(([sql]) => /INSERT INTO privacy_org_holdings/.test(sql));
expect(insertCalls).toHaveLength(2);
expect(insertCalls[1][1]).toEqual(['o1', 'v2', 'current']); // default status applied
+ expect(withTransactionMock).toHaveBeenCalledTimes(1);
});
it('clears all holdings when given an empty list', async () => {
- queryMock.mockImplementation(async (sql) => {
+ const client = mockTransaction(async (sql) => {
if (/FROM privacy_orgs WHERE id/.test(sql)) return { rows: [orgRow()] };
if (/DELETE FROM privacy_org_holdings WHERE org_id = \$1$/.test(sql)) return { rows: [] };
- if (/SELECT h\.org_id/.test(sql)) return { rows: [] };
- throw new Error(`unexpected query: ${sql}`);
+ throw new Error(`unexpected client query: ${sql}`);
});
+ queryMock.mockResolvedValue({ rows: [] });
await setOrgHoldings('o1', []);
- const deleteCall = queryMock.mock.calls.find(([sql]) => /DELETE FROM privacy_org_holdings/.test(sql));
+ const deleteCall = client.query.mock.calls.find(([sql]) => /DELETE FROM privacy_org_holdings/.test(sql));
expect(deleteCall[1]).toEqual(['o1']);
});
+
+ it('surfaces a stale/unknown vaultRecordId as a 400, not a raw FK-violation 500', async () => {
+ const fkError = Object.assign(new Error('insert or update on table violates foreign key constraint'), { code: '23503' });
+ mockTransaction(async (sql) => {
+ if (/FROM privacy_orgs WHERE id/.test(sql)) return { rows: [orgRow()] };
+ if (/DELETE FROM privacy_org_holdings/.test(sql)) return { rows: [] };
+ if (/INSERT INTO privacy_org_holdings/.test(sql)) throw fkError;
+ throw new Error(`unexpected client query: ${sql}`);
+ });
+ await expect(setOrgHoldings('o1', [{ vaultRecordId: 'missing-vault-id' }]))
+ .rejects.toMatchObject({ status: 400, code: 'VAULT_RECORD_NOT_FOUND' });
+ });
});
describe('setHoldingsStatus', () => {