Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/yummy-hoops-grin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/netlify': patch
---

Hardens `remotePatterns` regex generation to match canonical wildcard semantics more strictly
13 changes: 7 additions & 6 deletions packages/integrations/netlify/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ export function remotePatternToRegex(

if (hostname) {
if (hostname.startsWith('**.')) {
// match any number of subdomains
regexStr += '([a-z0-9-]+\\.)*';
// match one or more subdomains
regexStr += '([a-z0-9-]+\\.)+';
hostname = hostname.substring(3);
} else if (hostname.startsWith('*.')) {
// match one subdomain
regexStr += '([a-z0-9-]+\\.)?';
// match exactly one subdomain
regexStr += '([a-z0-9-]+\\.)';
hostname = hostname.substring(2); // Remove '*.' from the beginning
}
// Escape dots in the hostname
Expand All @@ -78,8 +78,7 @@ export function remotePatternToRegex(
if (pathname.endsWith('/**')) {
// Match any path.
regexStr += `(\\${pathname.replace('/**', '')}.*)`;
}
if (pathname.endsWith('/*')) {
} else if (pathname.endsWith('/*')) {
// Match one level of path
regexStr += `(\\${pathname.replace('/*', '')}\/[^/?#]+)\/?`;
} else {
Expand All @@ -94,6 +93,8 @@ export function remotePatternToRegex(
// Match query, but only if it's not already matched by the pathname
regexStr += '([?][^#]*)?';
}
// Anchor to end of string so .test() can't match a prefix
regexStr += '$';
try {
// nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp
// This only validates the generated pattern before handing it to Netlify.
Expand Down
11 changes: 10 additions & 1 deletion packages/integrations/netlify/test/functions/image-cdn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ describe('Image CDN', { timeout: 120000 }, () => {

it('generates correct config for remotePatterns', async () => {
const patterns = regexes[2]!;
assert.equal(patterns.test('https://example.org/images/1.jpg'), true, 'should match domain');
assert.equal(
patterns.test('https://example.org/images/1.jpg'),
false,
'apex hostname should not match for *.example.org',
);
assert.equal(
patterns.test('https://www.example.org/images/2.jpg'),
true,
Expand All @@ -105,6 +109,11 @@ describe('Image CDN', { timeout: 120000 }, () => {
false,
'wrong path should not match',
);
assert.equal(
patterns.test('https://www.example.org/images/a/b.jpg'),
false,
'deeper path should not match for /images/*',
);
});

it('warns when remotepatterns generates an invalid regex', async () => {
Expand Down
Loading