From 6cc7ec856fa7ef3db043ff41ecdc5afeb3678ac5 Mon Sep 17 00:00:00 2001 From: Vasco Santos Date: Mon, 7 Mar 2022 17:43:15 +0100 Subject: [PATCH] fix: gateway ipfs path error on invalid cid (#1548) --- packages/gateway/src/ipfs.js | 8 +++++++- packages/gateway/test/ipfs-path.spec.js | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/gateway/src/ipfs.js b/packages/gateway/src/ipfs.js index ed6fa0f058..203420a513 100644 --- a/packages/gateway/src/ipfs.js +++ b/packages/gateway/src/ipfs.js @@ -1,4 +1,5 @@ import { normalizeCid } from './utils/cid.js' +import { InvalidUrlError } from './errors.js' /** * Handle gateway request @@ -16,7 +17,12 @@ export async function ipfsGet(request, env) { const redirectQueryString = reqQueryString ? `?${reqQueryString}` : '' // Parse and normalize CID - const nCid = normalizeCid(cid) + let nCid + try { + nCid = normalizeCid(cid) + } catch (err) { + throw new InvalidUrlError(`invalid CID: ${cid}: ${err.message}`) + } const url = new URL( `https://${nCid}.${env.GATEWAY_HOSTNAME}${redirectPath}${redirectQueryString}` ) diff --git a/packages/gateway/test/ipfs-path.spec.js b/packages/gateway/test/ipfs-path.spec.js index d1ccdaa381..7878b5e8f5 100644 --- a/packages/gateway/test/ipfs-path.spec.js +++ b/packages/gateway/test/ipfs-path.spec.js @@ -1,4 +1,5 @@ import test from 'ava' +import { createErrorHtmlContent } from '../src/errors.js' import { getMiniflare } from './utils.js' @@ -9,6 +10,21 @@ test.beforeEach((t) => { } }) +test('Fails when invalid cid with IPFS canonical resolution', async (t) => { + const { mf } = t.context + + const response = await mf.dispatchFetch( + 'https://localhost:8787/ipfs/bafy.../path' + ) + t.is(response.status, 400) + + const textResponse = await response.text() + t.is( + textResponse, + createErrorHtmlContent(400, 'invalid CID: bafy...: Non-base32 character') + ) +}) + test('should resolve a cid v0 with IPFS canonical resolution', async (t) => { const { mf } = t.context