/** * @module witness/space/proxy-readonly-space/proxy-readonly-space.respec * * Respec unit tests for ProxyReadonlySpace_V1. */ import { respecfully, ifWe, ifWeMight, iReckon } from '@ibgib/helper-gib/dist/respec-gib/respec-gib.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { createStoneTestHelper } from '../../../test-helpers.mjs'; import { createInMemoryTempMetaspaceAndSpace } from '../metaspace/metaspace-innerspace/metaspace-innerspace.mjs'; import { ReadOnlySpaceError } from '../readonly-space-wrapper.mjs'; import { IbGibSpaceOptionsCmd } from '../space-types.mjs'; import { ProxyReadonlySpace_V1 } from './proxy-readonly-space-v1.mjs'; import { ProxyReadonlyFetchFn } from './proxy-readonly-space-types.mjs'; const lc = `[proxy-readonly-space.respec.mts]`; await respecfully(lc, `ProxyReadonlySpace_V1 Unit Specs`, async () => { await respecfully(lc, `Mutation Protection (ReadOnlySpaceError)`, async () => { await ifWe(lc, `rejects put and delete commands with ReadOnlySpaceError`, async () => { const proxySpace = new ProxyReadonlySpace_V1(undefined, undefined, { serverBaseUrl: 'https://test.ibgib.space', identityHandle: 'alice', cosmosName: 'my-cosmos', customFetch: async () => new Response('{}', { status: 200 }), }); await proxySpace.initialized; let putError: any; try { const putArg = await proxySpace.argy({ argData: { cmd: IbGibSpaceOptionsCmd.put, ibGibAddrs: ['test^gib'], }, ibGibs: [{ ib: 'test', gib: 'gib' }], }); await proxySpace.witness(putArg); } catch (err) { putError = err; } iReckon(lc, putError).asTo('put command threw').isGonnaBeTruthy(); iReckon(lc, putError instanceof ReadOnlySpaceError || putError?.name === 'ReadOnlySpaceError').asTo('put threw ReadOnlySpaceError').willEqual(true); let deleteError: any; try { const deleteArg = await proxySpace.argy({ argData: { cmd: IbGibSpaceOptionsCmd.delete, ibGibAddrs: ['test^gib'], }, }); await proxySpace.witness(deleteArg); } catch (err) { deleteError = err; } iReckon(lc, deleteError).asTo('delete command threw').isGonnaBeTruthy(); iReckon(lc, deleteError instanceof ReadOnlySpaceError || deleteError?.name === 'ReadOnlySpaceError').asTo('delete threw ReadOnlySpaceError').willEqual(true); }); }); await respecfully(lc, `Fetch and Intrinsic Security Validation`, async () => { await ifWe(lc, `fetches valid ibGib record over mock HTTP and validates intrinsically`, async () => { const validIbGib = await createStoneTestHelper({ ib: 'doc hello', data: { text: 'Hello, world!' }, uuid: true, }); const validAddr = getIbGibAddr({ ibGib: validIbGib }); let requestedUrl = ''; const mockFetch: ProxyReadonlyFetchFn = async (url) => { requestedUrl = url; return new Response(JSON.stringify(validIbGib), { status: 200, headers: { 'Content-Type': 'application/json' }, }); }; const proxySpace = new ProxyReadonlySpace_V1(undefined, undefined, { serverBaseUrl: 'https://staging.ibgib.space', identityHandle: '@alice', cosmosName: 'demo-cosmos', customFetch: mockFetch, }); await proxySpace.initialized; const getArg = await proxySpace.argy({ argData: { cmd: IbGibSpaceOptionsCmd.get, ibGibAddrs: [validAddr], }, }); const getRes = await proxySpace.witness(getArg); iReckon(lc, requestedUrl).includes('/api/alice/demo-cosmos/ibgib/'); const ibGibs = (getRes as any)?.ibGibs as IbGib_V1[]; iReckon(lc, ibGibs?.length).willEqual(1); iReckon(lc, getIbGibAddr({ ibGib: ibGibs[0] })).willEqual(validAddr); }); await ifWe(lc, `rejects tampered ibGib with corrupted intrinsic hash`, async () => { const legitIbGib = await createStoneTestHelper({ ib: 'doc legit', data: { text: 'Untampered' }, uuid: true, }); const tamperedIbGib = { ...legitIbGib, data: { text: 'Malicious Modification' }, }; const originalAddr = getIbGibAddr({ ibGib: legitIbGib }); const mockFetch: ProxyReadonlyFetchFn = async () => { return new Response(JSON.stringify(tamperedIbGib), { status: 200, headers: { 'Content-Type': 'application/json' }, }); }; const proxySpace = new ProxyReadonlySpace_V1(undefined, undefined, { serverBaseUrl: 'https://staging.ibgib.space', identityHandle: 'alice', cosmosName: 'demo-cosmos', customFetch: mockFetch, }); await proxySpace.initialized; let fetchError: any; try { const getArg = await proxySpace.argy({ argData: { cmd: IbGibSpaceOptionsCmd.get, ibGibAddrs: [originalAddr], }, }); await proxySpace.witness(getArg); } catch (err) { fetchError = err; } iReckon(lc, fetchError).asTo('tampered record threw security error').isGonnaBeTruthy(); iReckon(lc, fetchError?.message).includes('Security validation failed'); }); await ifWe(lc, `caches fetched ibGib in local cacheSpace, avoiding subsequent HTTP requests`, async () => { const { space: cacheSpace } = await createInMemoryTempMetaspaceAndSpace(); const validIbGib = await createStoneTestHelper({ ib: 'doc cached', data: { text: 'Cache me please' }, uuid: true, }); const validAddr = getIbGibAddr({ ibGib: validIbGib }); let fetchCount = 0; const mockFetch: ProxyReadonlyFetchFn = async () => { fetchCount++; return new Response(JSON.stringify(validIbGib), { status: 200, headers: { 'Content-Type': 'application/json' }, }); }; const proxySpace = new ProxyReadonlySpace_V1(undefined, undefined, { serverBaseUrl: 'https://staging.ibgib.space', identityHandle: 'alice', cosmosName: 'demo-cosmos', cacheSpace, customFetch: mockFetch, }); await proxySpace.initialized; // First get: hits HTTP mock const getArg1 = await proxySpace.argy({ argData: { cmd: IbGibSpaceOptionsCmd.get, ibGibAddrs: [validAddr] }, }); const res1 = await proxySpace.witness(getArg1); iReckon(lc, fetchCount).willEqual(1); iReckon(lc, (res1 as any)?.ibGibs?.length).willEqual(1); // Second get: served from cacheSpace without calling fetch const getArg2 = await proxySpace.argy({ argData: { cmd: IbGibSpaceOptionsCmd.get, ibGibAddrs: [validAddr] }, }); const res2 = await proxySpace.witness(getArg2); iReckon(lc, fetchCount).willEqual(1); // Unchanged! iReckon(lc, (res2 as any)?.ibGibs?.length).willEqual(1); }); await ifWe(lc, `getLatestAddrs returns latestAddrsMap and addrs matching Metaspace contract`, async () => { const mockFetch: ProxyReadonlyFetchFn = async (url) => { if (url.includes('getLatest=true')) { return new Response(JSON.stringify({ addr: 'resolved_addr^gib' }), { status: 200, headers: { 'Content-Type': 'application/json' }, }); } return new Response('{}', { status: 404 }); }; const proxySpace = new ProxyReadonlySpace_V1(undefined, undefined, { serverBaseUrl: 'https://staging.ibgib.space', identityHandle: 'alice', cosmosName: 'demo-cosmos', galaxyName: 'code-1', branchName: 'main', customFetch: mockFetch, }); await proxySpace.initialized; const latestArg = await proxySpace.argy({ argData: { cmd: IbGibSpaceOptionsCmd.get, cmdModifiers: ['latest'], ibGibAddrs: ['initial_addr^gib'], }, }); const res = await proxySpace.witness(latestArg) as any; iReckon(lc, res?.data?.success).willEqual(true); iReckon(lc, res?.data?.latestAddrsMap?.['initial_addr^gib']).willEqual('resolved_addr^gib'); iReckon(lc, res?.data?.addrs?.[0]).willEqual('resolved_addr^gib'); iReckon(lc, res?.data?.latestAddrs?.[0]).willEqual('resolved_addr^gib'); }); await ifWe(lc, `deduplicates concurrent fetches in serialized critical section queue`, async () => { const { space: cacheSpace } = await createInMemoryTempMetaspaceAndSpace(); const validIbGib = await createStoneTestHelper({ ib: 'doc concurrent', data: { text: 'Parallel request item' }, uuid: true, }); const validAddr = getIbGibAddr({ ibGib: validIbGib }); let fetchCount = 0; const mockFetch: ProxyReadonlyFetchFn = async () => { fetchCount++; // Small delay to simulate network latency await new Promise(r => setTimeout(r, 20)); return new Response(JSON.stringify(validIbGib), { status: 200, headers: { 'Content-Type': 'application/json' }, }); }; const proxySpace = new ProxyReadonlySpace_V1(undefined, undefined, { serverBaseUrl: 'https://staging.ibgib.space', identityHandle: 'alice', cosmosName: 'demo-cosmos', cacheSpace, customFetch: mockFetch, }); await proxySpace.initialized; // Fire 5 concurrent get requests for the exact same address const requests = Array.from({ length: 5 }, async () => { const getArg = await proxySpace.argy({ argData: { cmd: IbGibSpaceOptionsCmd.get, ibGibAddrs: [validAddr] }, }); return await proxySpace.witness(getArg); }); const results = await Promise.all(requests); // Exactly 1 network fetch should have occurred! iReckon(lc, fetchCount).willEqual(1); // All 5 callers received the authentic stone for (const res of results) { const ibGibs = (res as any)?.ibGibs as IbGib_V1[]; iReckon(lc, ibGibs?.length).willEqual(1); iReckon(lc, getIbGibAddr({ ibGib: ibGibs[0] })).willEqual(validAddr); } }); await ifWe(lc, `snapshot-driven getLatestAddrs resolves matching tjpGib without HTTP roundtrip`, async () => { let fetchCount = 0; const mockFetch: ProxyReadonlyFetchFn = async () => { fetchCount++; return new Response('{}', { status: 404 }); }; const proxySpace = new ProxyReadonlySpace_V1(undefined, undefined, { serverBaseUrl: 'https://staging.ibgib.space', identityHandle: 'alice', cosmosName: 'demo-cosmos', galaxyName: 'root-code', branchName: 'main', customFetch: mockFetch, }); await proxySpace.initialized; const latestFileAddr = 'b2tfs_item file index v1 abc^PUNCTILIAR_LATEST.TJP12345'; const latestBranchAddr = 'b2tfs_branch main v1 branch_uuid^BRANCH_LATEST.BRANCHTJP'; // Seed snapshot on the proxy space const mockSnapshot: any = { ib: 'b2tfs_snapshot v1', gib: 'snapshot_gib', data: { items: { 'src/index.ts': [latestFileAddr, undefined], }, rootItemAddr: 'b2tfs_item folder root v1 root_uuid^ROOT_LATEST.ROOTTJP', branchTjpAddr: 'b2tfs_branch main v1 branch_uuid^BRANCHTJP', prevBranchAddr: latestBranchAddr, }, rel8ns: {}, }; proxySpace.snapshotIbGib = mockSnapshot; // Query earlier address on the same timeline (same tjpGib 'TJP12345') const queryAddr = 'b2tfs_item file index v1 abc^PUNCTILIAR_OLD.TJP12345'; const latestArg = await proxySpace.argy({ argData: { cmd: IbGibSpaceOptionsCmd.get, cmdModifiers: ['latest'], ibGibAddrs: [queryAddr], }, }); const res = await proxySpace.witness(latestArg) as any; iReckon(lc, fetchCount).willEqual(0); // ZERO network requests! iReckon(lc, res?.data?.success).willEqual(true); iReckon(lc, res?.data?.latestAddrsMap?.[queryAddr]).willEqual(latestFileAddr); iReckon(lc, res?.data?.addrs?.[0]).willEqual(latestFileAddr); iReckon(lc, res?.data?.latestAddrs?.[0]).willEqual(latestFileAddr); }); }); });