From 5c2327f178ed9206074feeaf3f6f86509fb97b8b Mon Sep 17 00:00:00 2001 From: Andrey Gruzdev Date: Sat, 28 Nov 2026 15:04:26 +0100 Subject: [PATCH 1/2] fix(verify): reject stale blocks and registry read failures Since verification is pinned to one block (#11), a request can name a historical blockId. The controller then rebuilt the code deployed at that block and called set_contract with its older hash and height. The registry's set_contract does not compare heights, so this replaced the record for the code deployed now. The controller could not guard against that because it never knew whether a record existed: VerifierService.getContract returned null for every error, and the controller swallowed errors too, so an RPC outage looked like "no record" and led to a full rebuild, an IPFS pin and a second signed write. getContract now returns null only when get_contract answers JSON null (it returns Option), and throws a 503 when the registry can't be read or its answer isn't a record. The controller returns 503 with a retry message before any other read or build. With the record and the deployed hash at the pinned block known before cloning, the controller now: - returns the existing 400 "Code hash didn't change" when the record already holds the deployed hash, instead of after a Docker build; - refuses (500) when the record's block_height is not a safe non-negative integer or a canonical decimal string; - rejects (409) a pinned block below the record's block_height. The post-build unchanged-hash check stays as a backstop. nest/Dockerfile pins near-cli-rs to 0.31.1, the version production runs: the controller parses this CLI's output and relies on at-block-hash. Two jobs that finish in reverse order can still let the older one write last; fixing that needs the registry contract to compare heights. Co-Authored-By: Claude Opus 5.5 --- nest/Dockerfile | 5 +- .../verify/verify.controller.spec.ts | 150 +++++++++++++++--- .../controllers/verify/verify.controller.ts | 57 ++++++- .../near/services/verifier.service.spec.ts | 73 +++++++++ .../modules/near/services/verifier.service.ts | 33 ++-- 5 files changed, 284 insertions(+), 34 deletions(-) create mode 100644 nest/src/modules/near/services/verifier.service.spec.ts diff --git a/nest/Dockerfile b/nest/Dockerfile index 258f1b4..d61c337 100644 --- a/nest/Dockerfile +++ b/nest/Dockerfile @@ -46,8 +46,9 @@ RUN mkdir -p $RUSTUP_HOME $CARGO_HOME \ # Add Rust to the PATH environment variable for all subsequent commands ENV PATH="/usr/local/cargo/bin:$PATH" -# Install near-cli-rs for contract verification -RUN cargo install near-cli-rs --locked +# Install near-cli-rs for contract verification. Pinned: the verify controller +# parses this CLI's output and relies on its at-block-hash argument. +RUN cargo install near-cli-rs --version 0.31.1 --locked # Set environment variable for near-cli-rs to run in non-interactive mode ENV NEAR_CI=1 diff --git a/nest/src/controllers/verify/verify.controller.spec.ts b/nest/src/controllers/verify/verify.controller.spec.ts index a681405..f9cbeb2 100644 --- a/nest/src/controllers/verify/verify.controller.spec.ts +++ b/nest/src/controllers/verify/verify.controller.spec.ts @@ -20,6 +20,12 @@ describe('VerifyController snapshot', () => { const verifier = { getContract: jest.fn(), setContract: jest.fn() }; const compiler = { verifyContract: jest.fn() }; const ipfs = { addFolder: jest.fn() }; + const github = { + parseSourceCodeSnapshot: () => ({ repoUrl: 'repo', sha: 'sha' }), + clone: jest.fn(), + checkout: jest.fn(), + getRepoPath: () => 'path', + }; const response = { status: jest.fn().mockReturnThis(), json: jest.fn() }; const verify = (blockId?: number) => controller.verifyRust( @@ -49,15 +55,7 @@ describe('VerifyController snapshot', () => { providers: [ { provide: CompilerService, useValue: compiler }, { provide: ExecService, useValue: {} }, - { - provide: GithubService, - useValue: { - parseSourceCodeSnapshot: () => ({ repoUrl: 'repo', sha: 'sha' }), - clone: jest.fn(), - checkout: jest.fn(), - getRepoPath: () => 'path', - }, - }, + { provide: GithubService, useValue: github }, { provide: TempService, useValue: { createFolder: () => 'tmp', deleteFolder: jest.fn() }, @@ -111,18 +109,132 @@ describe('VerifyController snapshot', () => { expect(verifier.setContract).not.toHaveBeenCalled(); }); - it('keeps the existing response for an already verified hash', async () => { - verifier.getContract.mockResolvedValueOnce({ - block_height: height, - code_hash: hash, - }); - await verify(); - expect(response.status).toHaveBeenCalledWith(400); - expect(response.json).toHaveBeenCalledWith({ - message: "Code hash didn't change", - }); + const expectNothingBuiltOrWritten = () => { + expect(github.clone).not.toHaveBeenCalled(); + expect(compiler.verifyContract).not.toHaveBeenCalled(); expect(ipfs.addFolder).not.toHaveBeenCalled(); expect(verifier.setContract).not.toHaveBeenCalled(); + }; + + // An unchanged hash needs no height check: nothing would be written + it.each([height, height + 1, 'malformed'])( + 'returns the existing response for an already verified hash before building (record height: %s)', + async (recordHeight) => { + verifier.getContract.mockResolvedValueOnce({ + block_height: recordHeight, + code_hash: hash, + }); + await verify(height); + expect(response.status).toHaveBeenCalledWith(400); + expect(response.json).toHaveBeenCalledWith({ + message: "Code hash didn't change", + }); + expectNothingBuiltOrWritten(); + }, + ); + + it.each([height + 1, String(height + 1)])( + 'rejects a block older than the existing record (record height: %p)', + async (recordHeight) => { + verifier.getContract.mockResolvedValueOnce({ + block_height: recordHeight, + code_hash: 'old', + }); + await verify(height); + expect(response.status).toHaveBeenCalledWith(409); + expect(response.json).toHaveBeenCalledWith({ + message: `Block ${height} is older than the verified record for test.near at block ${height + 1}. Verify at block ${height + 1} or later.`, + }); + expectNothingBuiltOrWritten(); + }, + ); + + it.each([height, height - 1, String(height), String(height - 1), 0, '0'])( + 'verifies a block at or after the existing record (record height: %p)', + async (recordHeight) => { + verifier.getContract.mockResolvedValueOnce({ + block_height: recordHeight, + code_hash: 'old', + }); + await verify(height); + expect(compiler.verifyContract).toHaveBeenCalledWith( + 'test.near', + 'mainnet', + block, + ); + expect(verifier.setContract).toHaveBeenCalledWith( + 'test.near', + 'cid', + hash, + height, + 'rust', + ); + expect(response.status).toHaveBeenCalledWith(200); + }, + ); + + it.each([ + undefined, + null, + -1, + 1.5, + NaN, + Infinity, + Number.MAX_SAFE_INTEGER + 1, + '', + ' 1', + '-1', + '1.5', + '1e3', + '0x10', + '01', + '9007199254740993', + true, + [1], + {}, + ])( + 'refuses to compare against a malformed record height (%p)', + async (recordHeight) => { + verifier.getContract.mockResolvedValueOnce({ + block_height: recordHeight, + code_hash: 'old', + }); + await verify(height); + expect(response.status).toHaveBeenCalledWith(500); + expect(response.json).toHaveBeenCalledWith({ + message: + 'Pre-verification checks failed: Invalid block height in registry record', + }); + expectNothingBuiltOrWritten(); + }, + ); + + it('returns 503 without building when the registry cannot be read', async () => { + verifier.getContract.mockRejectedValueOnce(new Error('RPC timeout')); + await verify(height); + expect(response.status).toHaveBeenCalledWith(503); + expect(response.json).toHaveBeenCalledWith({ + message: + 'Could not read the verifier registry for test.near. Please retry later.', + }); + expect(rpc.callFunction).not.toHaveBeenCalled(); + expect(rpc.viewCode).not.toHaveBeenCalled(); + expectNothingBuiltOrWritten(); + }); + + it('verifies when the registry has no record', async () => { + verifier.getContract.mockResolvedValueOnce(null); + await verify(height); + expect(compiler.verifyContract).toHaveBeenCalled(); + expect(ipfs.addFolder).toHaveBeenCalled(); + expect(verifier.setContract).toHaveBeenCalledWith( + 'test.near', + 'cid', + hash, + height, + 'rust', + ); + expect(response.status).toHaveBeenCalledWith(200); }); it('rejects inconsistent RPC snapshots before building', async () => { diff --git a/nest/src/controllers/verify/verify.controller.ts b/nest/src/controllers/verify/verify.controller.ts index 961da95..0df62cf 100644 --- a/nest/src/controllers/verify/verify.controller.ts +++ b/nest/src/controllers/verify/verify.controller.ts @@ -31,6 +31,21 @@ import { CompilerService } from '../../services/compiler/compiler.service'; import { IpfsService } from '../../services/ipfs/ipfs.service'; import { TempService } from '../../services/temp/temp.service'; +/** + * Reads a registry block height. The registry serializes its u64 as a JSON + * number; a canonical decimal string (near_sdk's U64 form) is accepted too. + * Returns null for anything else, including heights past the safe-integer range. + */ +function parseBlockHeight(value: unknown): number | null { + const height = + typeof value === 'string' && /^(0|[1-9][0-9]*)$/.test(value) + ? Number(value) + : value; + return Number.isSafeInteger(height) && (height as number) >= 0 + ? (height as number) + : null; +} + @ApiTags('verify') @ApiExtraModels(HttpException) @Controller('verify') @@ -83,11 +98,20 @@ export class VerifyController { throw new HttpException('Invalid network ID', 400); } - let contractData: ContractData = null; + // The existing record decides whether this request may replace it, so an + // unreadable registry stops the request; only a null answer means no record. + // It is read at the latest final block, not the verification block, + // because the guards below compare against the record as it is now. + let contractData: ContractData | null; try { contractData = await verifierService.getContract(accountId); - } catch { - // Contract not found in verifier, continue + } catch (error) { + this.logger.error( + `Registry read failed for ${accountId}: ${error.message}`, + ); + return res.status(503).json({ + message: `Could not read the verifier registry for ${accountId}. Please retry later.`, + }); } // Pre-verification checks: Get contract metadata and validate repository accessibility @@ -142,6 +166,31 @@ export class VerifyController { } deployedHash = code.hash; + if (contractData) { + // The record already holds the deployed code: nothing to build or write + if (contractData.code_hash === deployedHash) { + this.logger.log( + `Code hash unchanged for ${accountId}: ${deployedHash} (already verified)`, + ); + return res.status(400).json({ message: "Code hash didn't change" }); + } + + // set_contract replaces the record without comparing heights, so an + // older block must not get that far + const recordHeight = parseBlockHeight(contractData.block_height); + if (recordHeight === null) { + throw new Error('Invalid block height in registry record'); + } + if (blockHeight < recordHeight) { + this.logger.warn( + `Rejected stale block for ${accountId}: block ${blockHeight} is older than the record at block ${recordHeight}`, + ); + return res.status(409).json({ + message: `Block ${blockHeight} is older than the verified record for ${accountId} at block ${recordHeight}. Verify at block ${recordHeight} or later.`, + }); + } + } + // Extract the repository URL and pinned commit SHA const { repoUrl, sha } = this.githubService.parseSourceCodeSnapshot( buildInfo.source_code_snapshot, @@ -247,7 +296,7 @@ export class VerifyController { .json({ message: 'Contract verification failed' }); } - // Check if the code hash is the same as the one in the verifier contract + // Backstop for the pre-build check: never rewrite an unchanged hash if (contractData && contractData.code_hash === checksum) { this.logger.log( `Code hash unchanged for ${accountId}: ${checksum} (already verified)`, diff --git a/nest/src/modules/near/services/verifier.service.spec.ts b/nest/src/modules/near/services/verifier.service.spec.ts new file mode 100644 index 0000000..8e7bce4 --- /dev/null +++ b/nest/src/modules/near/services/verifier.service.spec.ts @@ -0,0 +1,73 @@ +import { HttpException } from '@nestjs/common'; +import { KeyPair } from '@near-js/crypto'; +import { VerifierService } from './verifier.service'; + +describe('VerifierService.getContract', () => { + const record = { + cid: 'cid', + lang: 'rust', + code_hash: '5KaX9FM9NtjpfahksL8TMWQk3LF7k8Sv88Qem4tGrVDW', + block_height: 165753012, + votes: [], + comments: [], + }; + const answer = (json: string) => ({ + result: [...Buffer.from(json)], + logs: [], + block_hash: '56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW', + block_height: 165753100, + }); + let service: VerifierService; + let query: jest.Mock; + + beforeEach(() => { + service = new VerifierService({ + accountId: 'registry.near', + nodeUrl: 'http://127.0.0.1:1', + privateKey: KeyPair.fromRandom('ed25519').toString(), + } as any); + query = jest.fn(); + (service as any).provider = { query }; + }); + + it('reads the record from the registry at the final block', async () => { + query.mockResolvedValueOnce(answer(JSON.stringify(record))); + await expect(service.getContract('test.near')).resolves.toEqual(record); + expect(query).toHaveBeenCalledWith({ + request_type: 'call_function', + account_id: 'registry.near', + method_name: 'get_contract', + args_base64: Buffer.from('{"account_id":"test.near"}').toString('base64'), + finality: 'final', + }); + }); + + it('returns null only for a genuinely absent record', async () => { + query.mockResolvedValueOnce(answer('null')); + await expect(service.getContract('test.near')).resolves.toBeNull(); + }); + + it('throws a 503 when the registry RPC fails', async () => { + query.mockRejectedValueOnce(new Error('fetch failed')); + const error = await service.getContract('test.near').catch((e) => e); + expect(error).toBeInstanceOf(HttpException); + expect(error.getStatus()).toBe(503); + }); + + it.each(['', 'not json', '{"code_hash":', '42', '"record"', 'true', '[]'])( + 'throws a 503 when the registry answer is not a record or null (%p)', + async (json) => { + query.mockResolvedValueOnce(answer(json)); + const error = await service.getContract('test.near').catch((e) => e); + expect(error).toBeInstanceOf(HttpException); + expect(error.getStatus()).toBe(503); + }, + ); + + it('throws a 503 when the RPC answer has no result bytes', async () => { + query.mockResolvedValueOnce({ logs: [] }); + const error = await service.getContract('test.near').catch((e) => e); + expect(error).toBeInstanceOf(HttpException); + expect(error.getStatus()).toBe(503); + }); +}); diff --git a/nest/src/modules/near/services/verifier.service.ts b/nest/src/modules/near/services/verifier.service.ts index 8c68d37..39b6f51 100644 --- a/nest/src/modules/near/services/verifier.service.ts +++ b/nest/src/modules/near/services/verifier.service.ts @@ -37,9 +37,18 @@ export class VerifierService { this.account = new Account(this.config.accountId, this.provider, signer); } + /** + * Reads the registry record for an account. + * + * Returns null only when the registry answers that no record exists + * (`get_contract` returns `Option`, so that is JSON `null`). Throws when the + * registry can't be read or its answer can't be parsed, because callers + * must not mistake an outage for a missing record. + */ async getContract(accountId: string): Promise { this.logger.log(`Fetching contract data for account ID: ${accountId}`); + let contractData: unknown; try { const result = await this.provider.query({ request_type: 'call_function', @@ -51,21 +60,27 @@ export class VerifierService { finality: 'final', }); - const contractData: ContractData = JSON.parse( - Buffer.from(result.result).toString(), - ); - - this.logger.log( - `Contract data fetched successfully for account ID: ${accountId}`, - ); - return contractData; + contractData = JSON.parse(Buffer.from(result.result).toString()); + if ( + contractData !== null && + (typeof contractData !== 'object' || Array.isArray(contractData)) + ) { + throw new Error('get_contract returned neither a record nor null'); + } } catch (error) { this.logger.error( `Error fetching contract data for account ID: ${accountId}`, error.stack, ); - return null; + throw new HttpException('Failed to read the verifier registry', 503); } + + this.logger.log( + contractData === null + ? `No registry record for account ID: ${accountId}` + : `Contract data fetched successfully for account ID: ${accountId}`, + ); + return contractData as ContractData | null; } async setContract( From 057f26f9d6f45cae7a24f0e4021ae1b3946e26dc Mon Sep 17 00:00:00 2001 From: Andrey Gruzdev Date: Sat, 28 Nov 2026 15:15:24 +0100 Subject: [PATCH 2/2] fix(verify): treat malformed registry replies as unreadable getContract decoded the RPC result with Buffer.from, which also accepts a string, so a malformed reply whose result was the text "null" decoded to JSON null and counted as an absent record. That skipped both pre-build guards and could lead to a clone, build, IPFS pin and write where a retryable 503 is required. A decoded object without a string code_hash was also returned as a record, so the unchanged-hash check fell through to a build and write. getContract now requires the result to be an array of bytes, and requires a returned record to have a non-empty string code_hash and a block_height that is a safe non-negative integer or a canonical decimal string. It returns block_height as a number. Anything else throws the same 503 as an RPC failure. The height parsing moved from the controller into the service, so a malformed record height is now a 503 instead of a 500. The absent-record controller test also asserts the success body. Co-Authored-By: Claude Opus 5.5 --- .../verify/verify.controller.spec.ts | 72 +++-------- .../controllers/verify/verify.controller.ts | 23 +--- .../near/services/verifier.service.spec.ts | 115 +++++++++++++++--- .../modules/near/services/verifier.service.ts | 65 ++++++++-- 4 files changed, 178 insertions(+), 97 deletions(-) diff --git a/nest/src/controllers/verify/verify.controller.spec.ts b/nest/src/controllers/verify/verify.controller.spec.ts index f9cbeb2..9177e09 100644 --- a/nest/src/controllers/verify/verify.controller.spec.ts +++ b/nest/src/controllers/verify/verify.controller.spec.ts @@ -117,7 +117,7 @@ describe('VerifyController snapshot', () => { }; // An unchanged hash needs no height check: nothing would be written - it.each([height, height + 1, 'malformed'])( + it.each([height, height + 1])( 'returns the existing response for an already verified hash before building (record height: %s)', async (recordHeight) => { verifier.getContract.mockResolvedValueOnce({ @@ -133,23 +133,21 @@ describe('VerifyController snapshot', () => { }, ); - it.each([height + 1, String(height + 1)])( - 'rejects a block older than the existing record (record height: %p)', - async (recordHeight) => { - verifier.getContract.mockResolvedValueOnce({ - block_height: recordHeight, - code_hash: 'old', - }); - await verify(height); - expect(response.status).toHaveBeenCalledWith(409); - expect(response.json).toHaveBeenCalledWith({ - message: `Block ${height} is older than the verified record for test.near at block ${height + 1}. Verify at block ${height + 1} or later.`, - }); - expectNothingBuiltOrWritten(); - }, - ); + // getContract returns block_height as a number; its parsing is tested there + it('rejects a block older than the existing record', async () => { + verifier.getContract.mockResolvedValueOnce({ + block_height: height + 1, + code_hash: 'old', + }); + await verify(height); + expect(response.status).toHaveBeenCalledWith(409); + expect(response.json).toHaveBeenCalledWith({ + message: `Block ${height} is older than the verified record for test.near at block ${height + 1}. Verify at block ${height + 1} or later.`, + }); + expectNothingBuiltOrWritten(); + }); - it.each([height, height - 1, String(height), String(height - 1), 0, '0'])( + it.each([height, height - 1, 0])( 'verifies a block at or after the existing record (record height: %p)', async (recordHeight) => { verifier.getContract.mockResolvedValueOnce({ @@ -173,42 +171,6 @@ describe('VerifyController snapshot', () => { }, ); - it.each([ - undefined, - null, - -1, - 1.5, - NaN, - Infinity, - Number.MAX_SAFE_INTEGER + 1, - '', - ' 1', - '-1', - '1.5', - '1e3', - '0x10', - '01', - '9007199254740993', - true, - [1], - {}, - ])( - 'refuses to compare against a malformed record height (%p)', - async (recordHeight) => { - verifier.getContract.mockResolvedValueOnce({ - block_height: recordHeight, - code_hash: 'old', - }); - await verify(height); - expect(response.status).toHaveBeenCalledWith(500); - expect(response.json).toHaveBeenCalledWith({ - message: - 'Pre-verification checks failed: Invalid block height in registry record', - }); - expectNothingBuiltOrWritten(); - }, - ); - it('returns 503 without building when the registry cannot be read', async () => { verifier.getContract.mockRejectedValueOnce(new Error('RPC timeout')); await verify(height); @@ -235,6 +197,10 @@ describe('VerifyController snapshot', () => { 'rust', ); expect(response.status).toHaveBeenCalledWith(200); + expect(response.json).toHaveBeenCalledWith({ + message: 'Contract verified successfully', + checksum: hash, + }); }); it('rejects inconsistent RPC snapshots before building', async () => { diff --git a/nest/src/controllers/verify/verify.controller.ts b/nest/src/controllers/verify/verify.controller.ts index 0df62cf..780ea08 100644 --- a/nest/src/controllers/verify/verify.controller.ts +++ b/nest/src/controllers/verify/verify.controller.ts @@ -31,21 +31,6 @@ import { CompilerService } from '../../services/compiler/compiler.service'; import { IpfsService } from '../../services/ipfs/ipfs.service'; import { TempService } from '../../services/temp/temp.service'; -/** - * Reads a registry block height. The registry serializes its u64 as a JSON - * number; a canonical decimal string (near_sdk's U64 form) is accepted too. - * Returns null for anything else, including heights past the safe-integer range. - */ -function parseBlockHeight(value: unknown): number | null { - const height = - typeof value === 'string' && /^(0|[1-9][0-9]*)$/.test(value) - ? Number(value) - : value; - return Number.isSafeInteger(height) && (height as number) >= 0 - ? (height as number) - : null; -} - @ApiTags('verify') @ApiExtraModels(HttpException) @Controller('verify') @@ -99,7 +84,8 @@ export class VerifyController { } // The existing record decides whether this request may replace it, so an - // unreadable registry stops the request; only a null answer means no record. + // unreadable registry or record stops the request; only a null answer + // means no record. getContract checks code_hash and block_height. // It is read at the latest final block, not the verification block, // because the guards below compare against the record as it is now. let contractData: ContractData | null; @@ -177,10 +163,7 @@ export class VerifyController { // set_contract replaces the record without comparing heights, so an // older block must not get that far - const recordHeight = parseBlockHeight(contractData.block_height); - if (recordHeight === null) { - throw new Error('Invalid block height in registry record'); - } + const recordHeight = contractData.block_height; if (blockHeight < recordHeight) { this.logger.warn( `Rejected stale block for ${accountId}: block ${blockHeight} is older than the record at block ${recordHeight}`, diff --git a/nest/src/modules/near/services/verifier.service.spec.ts b/nest/src/modules/near/services/verifier.service.spec.ts index 8e7bce4..f3192ae 100644 --- a/nest/src/modules/near/services/verifier.service.spec.ts +++ b/nest/src/modules/near/services/verifier.service.spec.ts @@ -11,15 +11,28 @@ describe('VerifierService.getContract', () => { votes: [], comments: [], }; - const answer = (json: string) => ({ - result: [...Buffer.from(json)], + const reply = (result: unknown) => ({ + result, logs: [], block_hash: '56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW', block_height: 165753100, }); + // A well-formed call_function reply: the JSON answer as an array of bytes + const answer = (json: string) => reply([...Buffer.from(json)]); + // A record in raw JSON, so fields can hold values JSON.stringify can't write + const recordJson = (fields: Record) => + `{${Object.entries(fields) + .map(([key, value]) => `"${key}":${value}`) + .join(',')}}`; let service: VerifierService; let query: jest.Mock; + const expectUnreadable = async () => { + const error = await service.getContract('test.near').catch((e) => e); + expect(error).toBeInstanceOf(HttpException); + expect(error.getStatus()).toBe(503); + }; + beforeEach(() => { service = new VerifierService({ accountId: 'registry.near', @@ -49,25 +62,99 @@ describe('VerifierService.getContract', () => { it('throws a 503 when the registry RPC fails', async () => { query.mockRejectedValueOnce(new Error('fetch failed')); - const error = await service.getContract('test.near').catch((e) => e); - expect(error).toBeInstanceOf(HttpException); - expect(error.getStatus()).toBe(503); + await expectUnreadable(); + }); + + it('throws a 503 when the RPC reply is missing', async () => { + query.mockResolvedValueOnce(undefined); + await expectUnreadable(); }); + // Buffer.from also accepts strings, so a text "null" must not decode to + // an absent record + it.each([ + 'null', + JSON.stringify(record), + undefined, + null, + 42, + {}, + { 0: 110, length: 1 }, + [256], + [-1], + [1.5], + ['n'], + [null], + ])( + 'throws a 503 when the RPC result is not an array of bytes (%p)', + async (result) => { + query.mockResolvedValueOnce(reply(result)); + await expectUnreadable(); + }, + ); + it.each(['', 'not json', '{"code_hash":', '42', '"record"', 'true', '[]'])( 'throws a 503 when the registry answer is not a record or null (%p)', async (json) => { query.mockResolvedValueOnce(answer(json)); - const error = await service.getContract('test.near').catch((e) => e); - expect(error).toBeInstanceOf(HttpException); - expect(error.getStatus()).toBe(503); + await expectUnreadable(); }, ); - it('throws a 503 when the RPC answer has no result bytes', async () => { - query.mockResolvedValueOnce({ logs: [] }); - const error = await service.getContract('test.near').catch((e) => e); - expect(error).toBeInstanceOf(HttpException); - expect(error.getStatus()).toBe(503); - }); + it.each([undefined, 'null', '42', '""', '["hash"]', '{}'])( + 'throws a 503 when the record code_hash is not a non-empty string (%p)', + async (codeHash) => { + const fields: Record = { block_height: '165753012' }; + if (codeHash !== undefined) fields.code_hash = codeHash; + query.mockResolvedValueOnce(answer(recordJson(fields))); + await expectUnreadable(); + }, + ); + + it.each([ + ['165753012', 165753012], + ['"165753012"', 165753012], + ['0', 0], + ['"0"', 0], + ])( + 'returns block_height %s as the number %p', + async (blockHeight, expected) => { + query.mockResolvedValueOnce( + answer(recordJson({ code_hash: '"hash"', block_height: blockHeight })), + ); + await expect(service.getContract('test.near')).resolves.toEqual({ + code_hash: 'hash', + block_height: expected, + }); + }, + ); + + it.each([ + undefined, + 'null', + '-1', + '1.5', + '1e400', + '9007199254740992', + '9007199254740993', + '""', + '" 1"', + '"-1"', + '"1.5"', + '"1e3"', + '"0x10"', + '"01"', + '"9007199254740993"', + 'true', + '[1]', + '{}', + ])( + 'throws a 503 when the record block_height is malformed (%p)', + async (blockHeight) => { + const fields: Record = { code_hash: '"hash"' }; + if (blockHeight !== undefined) fields.block_height = blockHeight; + query.mockResolvedValueOnce(answer(recordJson(fields))); + await expectUnreadable(); + }, + ); }); diff --git a/nest/src/modules/near/services/verifier.service.ts b/nest/src/modules/near/services/verifier.service.ts index 39b6f51..edbf0fe 100644 --- a/nest/src/modules/near/services/verifier.service.ts +++ b/nest/src/modules/near/services/verifier.service.ts @@ -14,6 +14,51 @@ interface RpcQueryResult { block_hash: string; } +/** A call_function result is a JSON array of bytes; anything else is malformed. */ +function isByteArray(value: unknown): value is number[] { + return ( + Array.isArray(value) && + value.every((byte) => Number.isInteger(byte) && byte >= 0 && byte <= 255) + ); +} + +/** + * Reads a registry block height. The registry serializes its u64 as a JSON + * number; a canonical decimal string (near_sdk's U64 form) is accepted too. + * Returns null for anything else, including heights past the safe-integer range. + */ +function parseBlockHeight(value: unknown): number | null { + const height = + typeof value === 'string' && /^(0|[1-9][0-9]*)$/.test(value) + ? Number(value) + : value; + return Number.isSafeInteger(height) && (height as number) >= 0 + ? (height as number) + : null; +} + +/** + * Checks the fields the verify guards rely on and returns the record with a + * numeric block_height. JSON null is the registry's answer for no record. + */ +function parseRecord(value: unknown): ContractData | null { + if (value === null) { + return null; + } + if (typeof value !== 'object' || Array.isArray(value)) { + throw new Error('get_contract returned neither a record nor null'); + } + const record = value as Record; + if (typeof record.code_hash !== 'string' || !record.code_hash) { + throw new Error('Registry record has an invalid code_hash'); + } + const blockHeight = parseBlockHeight(record.block_height); + if (blockHeight === null) { + throw new Error('Registry record has an invalid block_height'); + } + return { ...(record as unknown as ContractData), block_height: blockHeight }; +} + @Injectable() export class VerifierService { private readonly logger = new Logger(VerifierService.name); @@ -42,13 +87,14 @@ export class VerifierService { * * Returns null only when the registry answers that no record exists * (`get_contract` returns `Option`, so that is JSON `null`). Throws when the - * registry can't be read or its answer can't be parsed, because callers - * must not mistake an outage for a missing record. + * registry can't be read, its answer isn't a byte array of JSON, or the + * record lacks a string code_hash or a valid block_height, because callers + * must not mistake an outage or an unreadable record for a missing one. */ async getContract(accountId: string): Promise { this.logger.log(`Fetching contract data for account ID: ${accountId}`); - let contractData: unknown; + let contractData: ContractData | null; try { const result = await this.provider.query({ request_type: 'call_function', @@ -60,13 +106,12 @@ export class VerifierService { finality: 'final', }); - contractData = JSON.parse(Buffer.from(result.result).toString()); - if ( - contractData !== null && - (typeof contractData !== 'object' || Array.isArray(contractData)) - ) { - throw new Error('get_contract returned neither a record nor null'); + if (!isByteArray(result.result)) { + throw new Error('get_contract result is not a byte array'); } + contractData = parseRecord( + JSON.parse(Buffer.from(result.result).toString()), + ); } catch (error) { this.logger.error( `Error fetching contract data for account ID: ${accountId}`, @@ -80,7 +125,7 @@ export class VerifierService { ? `No registry record for account ID: ${accountId}` : `Contract data fetched successfully for account ID: ${accountId}`, ); - return contractData as ContractData | null; + return contractData; } async setContract(