Skip to content

Commit

Permalink
fix(@angular/build): support Vite allowedHosts option for developme…
Browse files Browse the repository at this point in the history
…nt server

Vite version 6.0.9+, which is now used by the Angular CLI, contains a potentially
breaking change for some development setups. Examples of such setups include those
that use reverse proxies or custom host names during development. The change within
a patch release was made by Vite to address a security vulnerability. For
projects that directly access the development server via `localhost`, no changes should
be needed. However, some development setups may now need to adjust the newly
introduced `allowedHosts` development server option. This option can include an array
of host names that are allowed to communicate with the development server. The option
sets the corresponding Vite option within the Angular CLI.
For more information on the option and its specific behavior, please see the Vite
documentation located here:
https://vite.dev/config/server-options.html#server-allowedhosts

The following is an example of the configuration option allowing `example.com`:
```
"serve": {
      "builder": "@angular/build:dev-server",
      "options": {
        "allowedHosts": ["example.com"]
      },
```

Additional details on the vulnerability can be found here:
GHSA-vg6x-rcgg-rjx6
  • Loading branch information
clydin committed Jan 23, 2025
1 parent eb98bbd commit f836be9
Show file tree
Hide file tree
Showing 8 changed files with 162 additions and 4 deletions.
1 change: 1 addition & 0 deletions goldens/public-api/angular/build/index.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export enum BuildOutputFileType {

// @public
export type DevServerBuilderOptions = {
allowedHosts?: AllowedHosts;
buildTarget: string;
headers?: {
[key: string]: string;
Expand Down
2 changes: 2 additions & 0 deletions packages/angular/build/src/builders/dev-server/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export async function normalizeOptions(
sslCert,
sslKey,
prebundle,
allowedHosts,
} = options;

// Return all the normalized options
Expand All @@ -128,5 +129,6 @@ export async function normalizeOptions(
// Prebundling defaults to true but requires caching to function
prebundle: cacheOptions.enabled && !optimization.scripts && prebundle,
inspect,
allowedHosts: allowedHosts ? allowedHosts : [],
};
}
17 changes: 17 additions & 0 deletions packages/angular/build/src/builders/dev-server/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,23 @@
"type": "string",
"description": "SSL certificate to use for serving HTTPS."
},
"allowedHosts": {
"description": "The hosts that can access the development server. This option sets the Vite option of the same name. For further details: https://vite.dev/config/server-options.html#server-allowedhosts",
"default": [],
"oneOf": [
{
"type": "array",
"description": "List of hosts that are allowed to access the development server.",
"items": {
"type": "string"
}
},
{
"type": "boolean",
"description": "Indicates that all hosts are allowed. This is not recommended and a security risk."
}
]
},
"headers": {
"type": "object",
"description": "Custom HTTP headers to be added to all responses.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
*/

import { lastValueFrom, mergeMap, take, timeout } from 'rxjs';
import { URL } from 'url';
import { get, IncomingMessage, RequestOptions } from 'node:http';
import { text } from 'node:stream/consumers';
import {
BuilderHarness,
BuilderHarnessExecutionOptions,
Expand Down Expand Up @@ -41,3 +42,49 @@ export async function executeOnceAndFetch<T>(
),
);
}

/**
* Executes the builder and then immediately performs a GET request
* via the Node.js `http` builtin module. This is useful for cases
* where the `fetch` API is limited such as testing different `Host`
* header values with the development server.
* The `fetch` based alternative is preferred otherwise.
*
* @param harness A builder harness instance.
* @param url The URL string to get.
* @param options An options object.
* @returns
*/
export async function executeOnceAndGet<T>(
harness: BuilderHarness<T>,
url: string,
options?: Partial<BuilderHarnessExecutionOptions> & { request?: RequestOptions },
): Promise<BuilderHarnessExecutionResult & { response?: IncomingMessage; content?: string }> {
return lastValueFrom(
harness.execute().pipe(
timeout(30000),
mergeMap(async (executionResult) => {
let response = undefined;
let content = undefined;
if (executionResult.result?.success) {
let baseUrl = `${executionResult.result.baseUrl}`;
baseUrl = baseUrl[baseUrl.length - 1] === '/' ? baseUrl : `${baseUrl}/`;
const resolvedUrl = new URL(url, baseUrl);

response = await new Promise<IncomingMessage>((resolve) =>
get(resolvedUrl, options?.request ?? {}, resolve),
);

if (response.statusCode === 200) {
content = await text(response);
}

response.resume();
}

return { ...executionResult, response, content };
}),
take(1),
),
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/

import { executeDevServer } from '../../index';
import { executeOnceAndGet } from '../execute-fetch';
import { describeServeBuilder } from '../jasmine-helpers';
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';

const FETCH_HEADERS = Object.freeze({ Host: 'example.com' });

describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => {
describe('option: "allowedHosts"', () => {
beforeEach(async () => {
setupTarget(harness);

// Application code is not needed for these tests
await harness.writeFile('src/main.ts', '');
});

it('does not allow an invalid host when option is not present', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
});

const { result, response } = await executeOnceAndGet(harness, '/', {
request: { headers: FETCH_HEADERS },
});

expect(result?.success).toBeTrue();
expect(response?.statusCode).toBe(403);
});

it('does not allow an invalid host when option is an empty array', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
allowedHosts: [],
});

const { result, response } = await executeOnceAndGet(harness, '/', {
request: { headers: FETCH_HEADERS },
});

expect(result?.success).toBeTrue();
expect(response?.statusCode).toBe(403);
});

it('allows a host when specified in the option', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
allowedHosts: ['example.com'],
});

const { result, content } = await executeOnceAndGet(harness, '/', {
request: { headers: FETCH_HEADERS },
});

expect(result?.success).toBeTrue();
expect(content).toContain('<title>');
});

it('allows a host when option is true', async () => {
harness.useTarget('serve', {
...BASE_OPTIONS,
allowedHosts: true,
});

const { result, content } = await executeOnceAndGet(harness, '/', {
request: { headers: FETCH_HEADERS },
});

expect(result?.success).toBeTrue();
expect(content).toContain('<title>');
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -758,6 +758,7 @@ export async function setupServer(
strictPort: true,
host: serverOptions.host,
open: serverOptions.open,
allowedHosts: serverOptions.allowedHosts,
headers: serverOptions.headers,
// Disable the websocket if live reload is disabled (false/undefined are the only valid values)
ws: serverOptions.liveReload === false && serverOptions.hmr === false ? false : undefined,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,22 @@ export function execute(
// New build system defaults hmr option to the value of liveReload
normalizedOptions.hmr ??= normalizedOptions.liveReload;

// New build system uses Vite's allowedHost option convention of true for disabling host checks
if (normalizedOptions.disableHostCheck) {
(normalizedOptions as unknown as { allowedHosts: true }).allowedHosts = true;
} else {
normalizedOptions.allowedHosts ??= [];
}

return defer(() =>
Promise.all([import('@angular/build/private'), import('../browser-esbuild')]),
).pipe(
switchMap(([{ serveWithVite, buildApplicationInternal }, { convertBrowserOptions }]) =>
serveWithVite(
normalizedOptions as typeof normalizedOptions & { hmr: boolean },
normalizedOptions as typeof normalizedOptions & {
hmr: boolean;
allowedHosts: true | string[];
},
builderName,
(options, context, codePlugins) => {
return builderName === '@angular-devkit/build-angular:browser-esbuild'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
},
"allowedHosts": {
"type": "array",
"description": "List of hosts that are allowed to access the dev server. This option has no effect when using the 'application' or other esbuild-based builders.",
"description": "List of hosts that are allowed to access the dev server.",
"default": [],
"items": {
"type": "string"
Expand All @@ -79,7 +79,7 @@
},
"disableHostCheck": {
"type": "boolean",
"description": "Don't verify connected clients are part of allowed hosts. This option has no effect when using the 'application' or other esbuild-based builders.",
"description": "Don't verify connected clients are part of allowed hosts.",
"default": false
},
"hmr": {
Expand Down

0 comments on commit f836be9

Please sign in to comment.