Repository navigation
fix(runtime): tighten asset checks #768
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| import type { AddressInfo } from 'node:net' | ||
| import type { H3Event } from '#nuxtseo/h3' | ||
| import { createServer } from 'node:http' | ||
| import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' | ||
| import { fetchLocalAsset } from '../../src/runtime/server/util/fetchLocalAsset' | ||
|
|
||
| vi.mock('#nuxtseo/nitro', () => ({ fetchWithEvent: async () => undefined })) | ||
| vi.mock('#nuxtseo/h3', () => ({ getRequestURL: (event: { context: { origin: string } }) => new URL(event.context.origin) })) | ||
| vi.mock('#site-config/server/composables', () => ({ getNitroOrigin: (event: { context: { origin: string } }) => event.context.origin })) | ||
|
|
||
| describe('local asset external fallback', () => { | ||
| let targetHits = 0 | ||
| let origin = '' | ||
| let assetRequest: { path?: string, header?: string } = {} | ||
| const target = createServer((_, response) => { | ||
| targetHits++ | ||
| response.end('fixture bytes') | ||
| }) | ||
| const app = createServer((request, response) => { | ||
| if (request.url === '/redirect.png') { | ||
| response.writeHead(302, { location: `http://127.0.0.1:${(target.address() as AddressInfo).port}/asset.png` }) | ||
| response.end() | ||
| return | ||
| } | ||
| assetRequest = { path: request.url, header: request.headers['x-nuxt-og-image'] as string | undefined } | ||
| response.end('asset bytes') | ||
| }) | ||
|
|
||
| beforeAll(async () => { | ||
| for (const server of [target, app]) { | ||
| await new Promise<void>((resolve, reject) => { | ||
| server.once('error', reject) | ||
| server.listen(0, '127.0.0.1', resolve) | ||
| }) | ||
| } | ||
| origin = `http://127.0.0.1:${(app.address() as AddressInfo).port}` | ||
| }) | ||
|
|
||
| afterAll(async () => { | ||
| await Promise.all([target, app].map(server => new Promise<void>((resolve, reject) => { | ||
| server.close(error => error ? reject(error) : resolve()) | ||
| }))) | ||
| }) | ||
|
|
||
| function event(): H3Event { | ||
| return { context: { origin } } as unknown as H3Event | ||
| } | ||
|
|
||
| it('does not follow a redirect to another local listener', async () => { | ||
| const bytes = await fetchLocalAsset(event(), '/redirect.png', { fetchTimeout: 500, includeExternalFallback: true }) | ||
| expect(targetHits).toBe(0) | ||
| expect(bytes).toBeUndefined() | ||
| }) | ||
|
|
||
| it('fetches app assets with their query and headers', async () => { | ||
| const bytes = await fetchLocalAsset(event(), '/asset.png?width=32', { | ||
| fetchTimeout: 500, | ||
| includeExternalFallback: true, | ||
| headers: { 'x-nuxt-og-image': '1' }, | ||
| }) | ||
| expect(new TextDecoder().decode(bytes)).toBe('asset bytes') | ||
| expect(assetRequest).toEqual({ path: '/asset.png?width=32', header: '1' }) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import type { H3Event } from '#nuxtseo/h3' | ||
| import { createFetch } from 'ofetch' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
| import { fetchLocalAsset } from '../../src/runtime/server/util/fetchLocalAsset' | ||
|
|
||
| const transport = vi.hoisted(() => ({ external: vi.fn() })) | ||
| vi.mock('#nuxtseo/nitro', () => ({ | ||
| fetchWithEvent: (event: { $fetch: (path: string, options: unknown) => unknown }, path: string, options: unknown) => event.$fetch(path, options), | ||
| })) | ||
| vi.mock('#nuxtseo/h3', () => ({ getRequestURL: () => new URL('https://site.example/render') })) | ||
| vi.mock('#site-config/server/composables', () => ({ getNitroOrigin: () => 'https://site.example' })) | ||
| vi.mock('#og-image/bindings/fetch', () => ({ guardedFetch: transport.external })) | ||
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| transport.external.mockResolvedValue(new Response('asset bytes')) | ||
| }) | ||
|
|
||
| describe('local asset response', () => { | ||
| it.each([301, 302, 303, 307, 308, 404, 500])('uses the validated fallback after status %i', async (status) => { | ||
| const local = createFetch({ fetch: async () => new Response('response body', { status, headers: { location: '/actual.png' } }) }) | ||
| const event = { context: {}, $fetch: local } as unknown as H3Event | ||
| const bytes = await fetchLocalAsset(event, '/logo.png', { fetchTimeout: 100, includeExternalFallback: true }) | ||
| expect(new TextDecoder().decode(bytes)).toBe('asset bytes') | ||
| expect(transport.external).toHaveBeenCalledOnce() | ||
| }) | ||
|
|
||
| it('uses a successful local response without an external fetch', async () => { | ||
| const local = createFetch({ fetch: async () => new Response('local bytes') }) | ||
| const event = { context: {}, $fetch: local } as unknown as H3Event | ||
| const bytes = await fetchLocalAsset(event, '/logo.png', { fetchTimeout: 100, includeExternalFallback: true }) | ||
| expect(new TextDecoder().decode(bytes)).toBe('local bytes') | ||
| expect(transport.external).not.toHaveBeenCalled() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import type { H3Event } from '#nuxtseo/h3' | ||
| import type { OgImageRenderEventContext, VNode } from '../../src/runtime/types' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
| import { walkTree } from '../../src/runtime/server/og-image/core/plugins' | ||
| import imageSrc from '../../src/runtime/server/og-image/core/plugins/imageSrc' | ||
| import { fetchLocalAsset } from '../../src/runtime/server/util/fetchLocalAsset' | ||
|
|
||
| const transport = vi.hoisted(() => ({ local: vi.fn(), external: vi.fn() })) | ||
| vi.mock('#nuxtseo/nitro', () => ({ | ||
| fetchWithEvent: transport.local, | ||
| useStorage: () => ({ hasItem: async () => false }), | ||
| })) | ||
| vi.mock('#nuxtseo/h3', () => ({ getRequestURL: () => new URL('https://site.example/render') })) | ||
| vi.mock('#site-config/server/composables', () => ({ getNitroOrigin: () => 'https://site.example' })) | ||
| vi.mock('#og-image/bindings/fetch', () => ({ guardedFetch: transport.external })) | ||
|
|
||
| const crossOriginPaths = ['//other.example/logo.png', '/\\other.example/logo.png', '/\t/other.example/logo.png', '/\n/other.example/logo.png'] | ||
|
|
||
| function createEvent(assets?: { fetch: (url: string) => Promise<Response> }): H3Event { | ||
| return { context: { ASSETS: assets } } as unknown as H3Event | ||
| } | ||
|
|
||
| function createContext(): OgImageRenderEventContext { | ||
| return { | ||
| e: createEvent(), | ||
| publicStoragePath: 'public', | ||
| runtimeConfig: { app: { baseURL: '/' }, security: { imageFetchTimeout: 100 } }, | ||
| timings: { | ||
| measure: async <T>(_name: string, work: () => T | Promise<T>) => work(), | ||
| start: () => () => {}, | ||
| }, | ||
| } as unknown as OgImageRenderEventContext | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| transport.local.mockResolvedValue(undefined) | ||
| transport.external.mockResolvedValue(new Response(null, { status: 404 })) | ||
| }) | ||
|
|
||
| describe('local asset fetch', () => { | ||
| it.each(crossOriginPaths)('keeps %j outside local transports', async (path) => { | ||
| const assets = { fetch: vi.fn(async () => new Response('asset')) } | ||
| expect(await fetchLocalAsset(createEvent(assets), path, { fetchTimeout: 20, includeExternalFallback: true })).toBeUndefined() | ||
| expect(assets.fetch).not.toHaveBeenCalled() | ||
| expect(transport.local).not.toHaveBeenCalled() | ||
| expect(transport.external).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('keeps asset query parameters when using the local transport', async () => { | ||
| const bytes = new ArrayBuffer(4) | ||
| transport.local.mockResolvedValue(bytes) | ||
| const event = createEvent() | ||
| expect(await fetchLocalAsset(event, '/logo.png?width=32', { fetchTimeout: 20 })).toBe(bytes) | ||
| expect(transport.local).toHaveBeenCalledWith(event, '/logo.png?width=32', expect.objectContaining({ redirect: 'manual' })) | ||
| }) | ||
|
|
||
| it('reads a same-origin asset from the binding', async () => { | ||
| const assets = { fetch: vi.fn(async () => new Response('asset')) } | ||
| const bytes = await fetchLocalAsset(createEvent(assets), '/logo.png?width=32', { fetchTimeout: 20 }) | ||
| expect(new TextDecoder().decode(bytes)).toBe('asset') | ||
| expect(assets.fetch).toHaveBeenCalledWith('https://site.example/logo.png?width=32', expect.objectContaining({ redirect: 'manual' })) | ||
| expect(transport.local).not.toHaveBeenCalled() | ||
| }) | ||
| }) | ||
|
|
||
| describe('image asset transformation', () => { | ||
| it.each(crossOriginPaths)('removes %j from image nodes', async (src) => { | ||
| const node: VNode = { type: 'img', props: { src } } | ||
| await Promise.all(walkTree(createContext(), node, [imageSrc])) | ||
| expect(node.props.src).toBeUndefined() | ||
| expect(transport.local).not.toHaveBeenCalled() | ||
| expect(transport.external).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it.each(crossOriginPaths)('removes %j from background images', async (src) => { | ||
| const node: VNode = { type: 'div', props: { style: { backgroundImage: `url(${src})` } } } | ||
| await Promise.all(walkTree(createContext(), node, [imageSrc])) | ||
| expect(node.props.style?.backgroundImage).toBeUndefined() | ||
| expect(transport.local).not.toHaveBeenCalled() | ||
| expect(transport.external).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('removes an unavailable local image', async () => { | ||
| const node: VNode = { type: 'img', props: { src: '/logo.png?width=32' } } | ||
| await Promise.all(walkTree(createContext(), node, [imageSrc])) | ||
| expect(node.props.src).toBeUndefined() | ||
| }) | ||
|
|
||
| it('removes an unavailable local background image', async () => { | ||
| const node: VNode = { type: 'div', props: { style: { backgroundImage: 'url(/logo.png?width=32)' } } } | ||
| await Promise.all(walkTree(createContext(), node, [imageSrc])) | ||
| expect(node.props.style?.backgroundImage).toBeUndefined() | ||
| }) | ||
| }) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.