Skip to content

Commit 89ac37b

Browse files
crisbetoatscott
authored andcommitted
fix(platform-server): support ports in allowedHosts
Currently `allowedHosts` allows requests on any port as long as the host matches. These changes expand the check so consumers can also set the ports they want to allow within `allowedHosts`. (cherry picked from commit 46ea814)
1 parent 481e7dc commit 89ac37b

4 files changed

Lines changed: 230 additions & 25 deletions

File tree

‎adev/src/content/guide/security.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -432,7 +432,7 @@ NOTE: Most cloud providers and CDN providers perform automatic validation of the
432432

433433
### Configuring allowed hosts
434434

435-
To allow specific hostnames, you need to add them to the allowlist. This is critical for ensuring your application works correctly and securely when deployed. The patterns support wildcards for flexible hostname matching.
435+
To allow specific hostnames, you need to add them to the allowlist. This is critical for ensuring your application works correctly and securely when deployed. The patterns support wildcards and optional ports for flexible host matching.
436436

437437
You can configure the `allowedHosts` option in your `angular.json`:
438438

@@ -479,6 +479,16 @@ For the Node.js variant `AngularNodeAppEngine`, you can also provide `NG_ALLOWED
479479
export NG_ALLOWED_HOSTS="example.com,*.trusted-example.com"
480480
```
481481

482+
#### Restricting ports
483+
484+
Omitting a port from an `allowedHosts` entry allows requests on any port for that host. To restrict requests to specific ports, append `:port` to an entry:
485+
486+
- `example.com:443`: Allows `example.com` only on port `443` (including default `https://example.com` requests).
487+
- `*.example.com:8443`: Allows any subdomain of `example.com` only on port `8443`.
488+
- `[::1]:4200`: Allows the IPv6 loopback address only on port `4200`.
489+
- `localhost:*`: Allows `localhost` on any port.
490+
- `*:8443`: Allows any host on port `8443`.
491+
482492
IMPORTANT: You can use `*` as a value in `allowedHosts` to allow all hostnames, though this is generally discouraged and presents a security risk. Accepting any host header can expose your application to host header injection and [Server-Side Request Forgery (SSRF)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/SSRF) attacks. This configuration should only be used when validation for `Host` and `X-Forwarded-Host` headers is performed in another layer, such as a load balancer or reverse proxy. For better security, we recommend using an explicit list of allowed hosts whenever possible. See [GHSA-x288-3778-4hhx](https://github.com/angular/angular-cli/security/advisories/GHSA-x288-3778-4hhx) for more details.
483493

484494
### Configuring trusted proxy headers

‎adev/src/content/reference/configs/workspace-config.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -568,10 +568,10 @@ When supplying the value as a string the filename of the specified path will be
568568

569569
The `security` option is an object that enables individual security features.
570570

571-
| Options | Details |
572-
| :------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
573-
| `autoCsp` | Generates a hash-based Content Security Policy when set to `true`, or to `{"unsafeEval": true}` to also allow `eval`. See [Hash inline scripts with `autoCsp`](best-practices/security#hash-inline-scripts-with-autocsp). |
574-
| `allowedHosts` | The hostnames allowed to access the server-side application. See [Preventing Server-Side Request Forgery (SSRF)](best-practices/security#preventing-server-side-request-forgery-ssrf). |
571+
| Options | Details |
572+
| :------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
573+
| `autoCsp` | Generates a hash-based Content Security Policy when set to `true`, or to `{"unsafeEval": true}` to also allow `eval`. See [Hash inline scripts with `autoCsp`](best-practices/security#hash-inline-scripts-with-autocsp). |
574+
| `allowedHosts` | The hostnames (and optional ports, such as `example.com:443` or `*.example.com:8443`) allowed to access the server-side application. Omitting a port allows any port for that host. See [Preventing Server-Side Request Forgery (SSRF)](best-practices/security#preventing-server-side-request-forgery-ssrf). |
575575

576576
### Output path configuration
577577

‎packages/platform-server/src/utils.ts‎

Lines changed: 76 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,9 @@ function sanitizeServerContext(serverContext: string): string {
317317
* - `url` - the URL for the current render request.
318318
* - `extraProviders` - set of platform level providers for the current render request.
319319
* - `allowedHosts` - the allowed hosts list for host validation in server-side rendering.
320+
* Entries may include an optional port (for example, `example.com:443`,
321+
* `*.example.com:8443`, `[::1]:4200`, `localhost:*`, or `*:8443`).
322+
* Omitting the port allows any port for that host.
320323
* @publicApi
321324
*/
322325
export async function renderModule<T>(
@@ -376,6 +379,9 @@ export async function renderModule<T>(
376379
* - `url` - the URL for the current render request.
377380
* - `platformProviders` - the platform level providers for the current render request.
378381
* - `allowedHosts` - the allowed hosts list for host validation in server-side rendering.
382+
* Entries may include an optional port (for example, `example.com:443`,
383+
* `*.example.com:8443`, `[::1]:4200`, `localhost:*`, or `*:8443`).
384+
* Omitting the port allows any port for that host.
379385
*
380386
* @returns A Promise, that returns serialized (to a string) rendered page, once resolved.
381387
*
@@ -429,33 +435,72 @@ export async function renderApplication(
429435
}
430436

431437
function validateAllowedHosts(url: string | undefined, allowedHosts: string[] | undefined) {
432-
if (typeof url === 'string') {
433-
const parsedUrl = resolveUrl(url);
434-
if (parsedUrl !== null) {
435-
const hostname = parsedUrl.hostname;
436-
const allowedHostsSet: ReadonlySet<string> = new Set(allowedHosts);
437-
if (!isHostAllowed(hostname, allowedHostsSet)) {
438-
throw new RuntimeError(
439-
RuntimeErrorCode.HOST_NOT_ALLOWED,
440-
typeof ngDevMode === 'undefined' || ngDevMode
441-
? `Host ${url} is not allowed. You can configure \`allowedHosts\` option.`
442-
: url,
443-
);
444-
}
445-
}
438+
if (typeof url !== 'string') {
439+
return;
440+
}
441+
442+
const parsedUrl = resolveUrl(url);
443+
if (parsedUrl === null) {
444+
return;
445+
}
446+
447+
let effectivePort: string | undefined;
448+
449+
if (parsedUrl.port) {
450+
effectivePort = parsedUrl.port;
451+
} else if (parsedUrl.protocol === 'https:') {
452+
effectivePort = '443';
453+
} else if (parsedUrl.protocol === 'http:') {
454+
effectivePort = '80';
455+
}
456+
457+
const allowedHostsSet: ReadonlySet<string> = new Set(
458+
allowedHosts?.map((host) => host.toLowerCase()),
459+
);
460+
if (!isHostAllowed(parsedUrl.hostname, allowedHostsSet, effectivePort)) {
461+
throw new RuntimeError(
462+
RuntimeErrorCode.HOST_NOT_ALLOWED,
463+
typeof ngDevMode === 'undefined' || ngDevMode
464+
? `Host ${url} is not allowed. You can configure \`allowedHosts\` option.`
465+
: url,
466+
);
446467
}
447468
}
448469

449470
/**
450-
* Checks if the hostname is allowed.
451-
* @param hostname - The hostname to check.
452-
* @param allowedHosts - A set of allowed hostnames.
471+
* Checks if the hostname (and optional port) is allowed.
472+
*
473+
* Entries in `allowedHosts` must be lowercase and may be bare hostnames
474+
* (e.g., `example.com`, `*.example.com`, `[::1]`), which allow any port, or port-qualified entries
475+
* (e.g., `example.com:443`, `localhost:4206`, `*.example.com:8443`, `[::1]:4200`, `localhost:*`,
476+
* `*:8443`, `*:*`), which enforce port matching.
477+
*
478+
* @param hostname - The lowercase hostname to check (for example, from `URL.hostname`).
479+
* @param allowedHosts - A set of lowercase allowed hosts (optionally including `:port`).
480+
* @param port - Optional port to validate against port-qualified entries.
453481
* @returns `true` if the hostname is allowed, `false` otherwise.
454482
* @note Used also in `@angular/ssr`.
455483
* @private
456484
*/
457-
export function isHostAllowed(hostname: string, allowedHosts: ReadonlySet<string>): boolean {
458-
if (allowedHosts.has('*') || allowedHosts.has(hostname)) {
485+
export function isHostAllowed(
486+
hostname: string,
487+
allowedHosts: ReadonlySet<string>,
488+
port?: string,
489+
): boolean {
490+
if (allowedHosts.size === 0) {
491+
return false;
492+
}
493+
494+
if (
495+
allowedHosts.has('*') ||
496+
allowedHosts.has('*:*') ||
497+
allowedHosts.has(hostname) ||
498+
allowedHosts.has(`${hostname}:*`)
499+
) {
500+
return true;
501+
}
502+
503+
if (port && (allowedHosts.has(`${hostname}:${port}`) || allowedHosts.has(`*:${port}`))) {
459504
return true;
460505
}
461506

@@ -464,7 +509,18 @@ export function isHostAllowed(hostname: string, allowedHosts: ReadonlySet<string
464509
continue;
465510
}
466511

467-
const domain = allowedHost.slice(1);
512+
const colonIndex = allowedHost.indexOf(':');
513+
let domain: string;
514+
if (colonIndex !== -1) {
515+
const allowedPort = allowedHost.slice(colonIndex + 1);
516+
if (allowedPort !== '*' && (!port || allowedPort !== port)) {
517+
continue;
518+
}
519+
domain = allowedHost.slice(1, colonIndex);
520+
} else {
521+
domain = allowedHost.slice(1);
522+
}
523+
468524
if (hostname.endsWith(domain)) {
469525
return true;
470526
}

‎packages/platform-server/test/utils_spec.ts‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,74 @@ describe('isHostAllowed', () => {
4949
it('allows all hostnames when * is in allowedHosts list', () => {
5050
expect(isHostAllowed('anydomain.com', new Set(['*']))).toBeTrue();
5151
});
52+
53+
it('rejects any hostname when allowedHosts is empty', () => {
54+
expect(isHostAllowed('localhost', new Set())).toBeFalse();
55+
expect(isHostAllowed('localhost', new Set(), '4206')).toBeFalse();
56+
});
57+
58+
it('allows any port when allowedHosts entry omits a port', () => {
59+
expect(isHostAllowed('localhost', new Set(['localhost']), '4206')).toBeTrue();
60+
expect(isHostAllowed('sub.example.com', new Set(['*.example.com']), '8443')).toBeTrue();
61+
expect(isHostAllowed('[::1]', new Set(['[::1]']), '4200')).toBeTrue();
62+
});
63+
64+
it('validates port when allowedHosts entry specifies an explicit port', () => {
65+
expect(isHostAllowed('localhost', new Set(['localhost:4206']), '4206')).toBeTrue();
66+
expect(isHostAllowed('localhost', new Set(['localhost:4206']), '19200')).toBeFalse();
67+
expect(isHostAllowed('localhost', new Set(['localhost:4206']))).toBeFalse();
68+
expect(isHostAllowed('localhost', new Set(['localhost:4206']), '')).toBeFalse();
69+
});
70+
71+
it('validates port on wildcard hostname entries', () => {
72+
const allowed = new Set(['*.example.com:8443']);
73+
expect(isHostAllowed('api.example.com', allowed, '8443')).toBeTrue();
74+
expect(isHostAllowed('api.example.com', allowed, '9000')).toBeFalse();
75+
expect(isHostAllowed('example.com', allowed, '8443')).toBeFalse();
76+
expect(isHostAllowed('api.example.com', allowed)).toBeFalse();
77+
expect(isHostAllowed('api.example.com', allowed, '')).toBeFalse();
78+
});
79+
80+
it('supports wildcard port and wildcard host combinations', () => {
81+
expect(isHostAllowed('localhost', new Set(['localhost:*']), '4206')).toBeTrue();
82+
expect(isHostAllowed('localhost', new Set(['localhost:*']), '19200')).toBeTrue();
83+
expect(isHostAllowed('localhost', new Set(['localhost:*']))).toBeTrue();
84+
expect(isHostAllowed('evil.com', new Set(['localhost:*']), '4206')).toBeFalse();
85+
86+
expect(isHostAllowed('any.example', new Set(['*:8443']), '8443')).toBeTrue();
87+
expect(isHostAllowed('any.example', new Set(['*:8443']), '9000')).toBeFalse();
88+
expect(isHostAllowed('any.example', new Set(['*:8443']))).toBeFalse();
89+
expect(isHostAllowed('any.example', new Set(['*:8443']), '')).toBeFalse();
90+
91+
expect(isHostAllowed('any.example', new Set(['*:*']), '8443')).toBeTrue();
92+
expect(isHostAllowed('any.example', new Set(['*:*']))).toBeTrue();
93+
94+
expect(isHostAllowed('api.example.com', new Set(['*.example.com:*']), '8443')).toBeTrue();
95+
expect(isHostAllowed('api.example.com', new Set(['*.example.com:*']))).toBeTrue();
96+
expect(isHostAllowed('example.com', new Set(['*.example.com:*']), '8443')).toBeFalse();
97+
});
98+
99+
it('handles bracketed and unbracketed IPv6 literals', () => {
100+
expect(isHostAllowed('[::1]', new Set(['[::1]:4200']), '4200')).toBeTrue();
101+
expect(isHostAllowed('[::1]', new Set(['[::1]:4200']), '9000')).toBeFalse();
102+
expect(isHostAllowed('[::1]', new Set(['[::1]:4200']))).toBeFalse();
103+
expect(isHostAllowed('[::1]', new Set(['[::1]:4200']), '')).toBeFalse();
104+
expect(isHostAllowed('[::1]', new Set(['[::1]']))).toBeTrue();
105+
expect(isHostAllowed('::1', new Set(['::1']))).toBeTrue();
106+
expect(isHostAllowed('::1', new Set(['::1']), '4200')).toBeTrue();
107+
expect(isHostAllowed('::1', new Set(['[::1]']))).toBeFalse();
108+
});
109+
110+
it('rejects empty port suffixes', () => {
111+
expect(isHostAllowed('localhost', new Set(['localhost:']), '4206')).toBeFalse();
112+
expect(isHostAllowed('localhost', new Set(['localhost:']), '')).toBeFalse();
113+
expect(isHostAllowed('[::1]', new Set(['[::1]:']), '4200')).toBeFalse();
114+
expect(isHostAllowed('[::1]', new Set(['[::1]:']), '')).toBeFalse();
115+
expect(isHostAllowed('any.example', new Set(['*:']), '8443')).toBeFalse();
116+
expect(isHostAllowed('any.example', new Set(['*:']), '')).toBeFalse();
117+
expect(isHostAllowed('api.example.com', new Set(['*.example.com:']), '8443')).toBeFalse();
118+
expect(isHostAllowed('api.example.com', new Set(['*.example.com:']), '')).toBeFalse();
119+
});
52120
});
53121

54122
describe('allowedHosts validation in renderApplication', () => {
@@ -101,6 +169,57 @@ describe('allowedHosts validation in renderApplication', () => {
101169
}
102170
});
103171

172+
it('should validate ports when allowedHosts includes port-qualified entries', async () => {
173+
const allowedCases: Array<{url: string; allowedHosts: string[]}> = [
174+
{url: 'http://localhost:4206/dashboard', allowedHosts: ['localhost:4206']},
175+
{url: 'https://example.com/dashboard', allowedHosts: ['example.com:443']},
176+
{url: 'https://example.com:443/dashboard', allowedHosts: ['example.com:443']},
177+
{url: 'http://example.com/dashboard', allowedHosts: ['example.com:80']},
178+
{url: 'http://example.com:80/dashboard', allowedHosts: ['example.com:80']},
179+
{url: 'https://api.example.com:8443/dashboard', allowedHosts: ['*.example.com:8443']},
180+
{url: 'http://[::1]:4200/dashboard', allowedHosts: ['[::1]:4200']},
181+
{url: 'https://Example.COM/dashboard', allowedHosts: ['example.com:443']},
182+
{url: 'https://example.com/dashboard', allowedHosts: ['Example.COM:443']},
183+
// Bare hostnames remain backwards-compatible and allow any port.
184+
{url: 'http://localhost:19200/dashboard', allowedHosts: ['localhost']},
185+
];
186+
187+
for (const {url, allowedHosts} of allowedCases) {
188+
destroyPlatform();
189+
await expectAsync(
190+
renderApplication(bootstrap, {
191+
document: '<app></app>',
192+
url,
193+
allowedHosts,
194+
}),
195+
)
196+
.withContext(`Expected allowed: ${url} with ${JSON.stringify(allowedHosts)}`)
197+
.toBeResolved();
198+
}
199+
200+
const rejectedCases: Array<{url: string; allowedHosts: string[]}> = [
201+
{url: 'http://localhost:19200/dashboard', allowedHosts: ['localhost:4206']},
202+
{url: 'http://localhost/dashboard', allowedHosts: ['localhost:4206']},
203+
{url: 'http://example.com/dashboard', allowedHosts: ['example.com:443']},
204+
{url: 'https://example.com:8443/dashboard', allowedHosts: ['example.com:443']},
205+
{url: 'https://api.example.com:9000/dashboard', allowedHosts: ['*.example.com:8443']},
206+
{url: 'http://[::1]:9000/dashboard', allowedHosts: ['[::1]:4200']},
207+
];
208+
209+
for (const {url, allowedHosts} of rejectedCases) {
210+
destroyPlatform();
211+
await expectAsync(
212+
renderApplication(bootstrap, {
213+
document: '<app></app>',
214+
url,
215+
allowedHosts,
216+
}),
217+
)
218+
.withContext(`Expected rejected: ${url} with ${JSON.stringify(allowedHosts)}`)
219+
.toBeRejectedWithError(/Host .+ is not allowed/);
220+
}
221+
});
222+
104223
it('should throw an error for malformed absolute URLs (SSRF bypass attempt)', async () => {
105224
const malformedUrls = [
106225
'http://evil.com:80:80/path',
@@ -159,6 +278,26 @@ describe('allowedHosts validation in renderModule', () => {
159278
}
160279
});
161280

281+
it('should validate ports when allowedHosts includes port-qualified entries', async () => {
282+
await expectAsync(
283+
renderModule(MockNgModule, {
284+
document: '<app></app>',
285+
url: 'http://localhost:4206/deep/path',
286+
allowedHosts: ['localhost:4206'],
287+
}),
288+
).toBeResolved();
289+
290+
destroyPlatform();
291+
292+
await expectAsync(
293+
renderModule(MockNgModule, {
294+
document: '<app></app>',
295+
url: 'http://localhost:19200/deep/path',
296+
allowedHosts: ['localhost:4206'],
297+
}),
298+
).toBeRejectedWithError(/Host http:\/\/localhost:19200\/deep\/path is not allowed/);
299+
});
300+
162301
it('should throw an error for malformed absolute URLs (SSRF bypass attempt)', async () => {
163302
const malformedUrls = [
164303
'http://evil.com:80:80/path',

0 commit comments

Comments
 (0)