[Backport 20.3.X] fix(http): enable XSRF protection for same-origin absolute URLs by SkyZeroZx · Pull Request #71295 · angular/angular · GitHub
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
4 changes: 2 additions & 2 deletions adev/src/content/guide/http/security.md
4 changes: 2 additions & 2 deletions adev/src/content/guide/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,10 +299,10 @@ The malicious code on `evil.com` can't.

`HttpClient` supports a [common mechanism](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Cookie-to-header_token) used to prevent XSRF attacks. When performing HTTP requests, an interceptor reads a token from a cookie, by default `XSRF-TOKEN`, and sets it as an HTTP header, `X-XSRF-TOKEN`. Because only code that runs on your domain could read the cookie, the backend can be certain that the HTTP request came from your client application and not an attacker.

By default, an interceptor sends this header on all mutating requests (such as `POST`) to relative URLs, but not on GET/HEAD requests or on requests with an absolute URL.
By default, an interceptor sends this header on all mutating requests (such as `POST`) to relative and same origin URLs, but not on `GET` or `HEAD` requests.

<docs-callout helpful title="Why not protect GET requests?">
CSRF protection is only needed for requests that can change state on the backend. By their nature, CSRF attacks cross domain boundaries, and the web's [same-origin policy](https://developer.mozilla.org/docs/Web/Security/Same-origin_policy) will prevent an attacking page from retrieving the results of authenticated GET requests.
CSRF protection is only needed for requests that can change state on the backend. By their nature, CSRF attacks cross domain boundaries, and the web's [same-origin policy](https://developer.mozilla.org/docs/Web/Security/Same-origin_policy) will prevent an attacking page from retrieving the results of authenticated `GET` requests.
</docs-callout>

To take advantage of this, your server needs to set a token in a JavaScript readable session cookie called `XSRF-TOKEN` on either the page load or the first GET request. On subsequent requests the server can verify that the cookie matches the `X-XSRF-TOKEN` HTTP header, and therefore be sure that only code running on your domain could have sent the request. The token must be unique for each user and must be verifiable by the server; this prevents the client from making up its own tokens. Set the token to a digest of your site's authentication cookie with a salt for added security.
Expand Down
35 changes: 19 additions & 16 deletions packages/common/http/src/xsrf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.dev/license
*/

import {DOCUMENT, ɵparseCookieValue as parseCookieValue} from '../../index';
import {DOCUMENT, ɵparseCookieValue as parseCookieValue, PlatformLocation} from '../../index';
import {
EnvironmentInjector,
Inject,
Expand Down Expand Up @@ -82,25 +82,28 @@ export class HttpXsrfCookieExtractor implements HttpXsrfTokenExtractor {
}
}

/**
* Regex to match absolute URLs, including protocol-relative URLs.
*/
const ABSOLUTE_URL_REGEX = /^(?:https?:)?\/\//i;

export function xsrfInterceptorFn(
req: HttpRequest<unknown>,
next: HttpHandlerFn,
): Observable<HttpEvent<unknown>> {
// Skip both non-mutating requests and absolute URLs.
// Non-mutating requests don't require a token, and absolute URLs require special handling
// anyway as the cookie set
// on our origin is not the same as the token expected by another origin.
if (
!inject(XSRF_ENABLED) ||
req.method === 'GET' ||
req.method === 'HEAD' ||
ABSOLUTE_URL_REGEX.test(req.url)
) {
// Skip both non-mutating requests
// Non-mutating requests generally don't require a token.
if (!inject(XSRF_ENABLED) || req.method === 'GET' || req.method === 'HEAD') {
return next(req);
}

try {
const locationHref = inject(PlatformLocation).href;
const {origin: locationOrigin} = new URL(locationHref);
// We can use `new URL` to normalize a relative URL like '//something.com' to
// 'https://something.com' in order to make consistent same-origin comparisons.
const {origin: requestOrigin} = new URL(req.url, locationOrigin);

if (locationOrigin !== requestOrigin) {
return next(req);
}
} catch {
// Handle invalid URLs gracefully.
return next(req);
}

Expand Down
1 change: 1 addition & 0 deletions packages/common/http/test/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ ts_project(
"//packages/common",
"//packages/common/http",
"//packages/common/http/testing",
"//packages/common/testing",
"//packages/core",
"//packages/core/testing",
"//packages/private/testing",
Expand Down
3 changes: 3 additions & 0 deletions packages/common/http/test/provider_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
PLATFORM_ID,
Provider,
} from '@angular/core';
import {MOCK_PLATFORM_LOCATION_CONFIG} from '@angular/common/testing';
import {TestBed} from '@angular/core/testing';
import {EMPTY, Observable, from} from 'rxjs';
import {tap} from 'rxjs/operators';
Expand Down Expand Up @@ -274,6 +275,7 @@ describe('provideHttpClient', () => {
provideHttpClient(),
provideHttpClientTesting(),
{provide: PLATFORM_ID, useValue: 'test'},
{provide: MOCK_PLATFORM_LOCATION_CONFIG, useValue: {startUrl: 'http://localhost/'}},
],
});

Expand All @@ -296,6 +298,7 @@ describe('provideHttpClient', () => {
),
provideHttpClientTesting(),
{provide: PLATFORM_ID, useValue: 'test'},
{provide: MOCK_PLATFORM_LOCATION_CONFIG, useValue: {startUrl: 'http://localhost/'}},
],
});

Expand Down
56 changes: 54 additions & 2 deletions packages/common/http/test/xsrf_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
* found in the LICENSE file at https://angular.dev/license
*/

import {MockPlatformLocation} from '@angular/common/testing';
import {PlatformLocation} from '../..';
import {HttpHeaders} from '../src/headers';
import {HttpRequest} from '../src/request';
import {
Expand Down Expand Up @@ -46,32 +48,43 @@ describe('HttpXsrfInterceptor', () => {
provide: XSRF_ENABLED,
useValue: true,
},
{
provide: PlatformLocation,
useFactory: () =>
new MockPlatformLocation({
startUrl: 'http://sub.example.com/',
}),
},
HttpXsrfInterceptor,
],
});

interceptor = TestBed.inject(HttpXsrfInterceptor);
backend = new HttpClientTestingBackend();
});

it('applies XSRF protection to outgoing requests', () => {
interceptor.intercept(new HttpRequest('POST', '/test', {}), backend).subscribe();
const req = backend.expectOne('/test');
expect(req.request.headers.get('X-XSRF-TOKEN')).toEqual('test');
req.flush({});
});

it('does not apply XSRF protection when request is a GET', () => {
interceptor.intercept(new HttpRequest('GET', '/test'), backend).subscribe();
const req = backend.expectOne('/test');
expect(req.request.headers.has('X-XSRF-TOKEN')).toEqual(false);
req.flush({});
});

it('does not apply XSRF protection when request is a HEAD', () => {
interceptor.intercept(new HttpRequest('HEAD', '/test'), backend).subscribe();
const req = backend.expectOne('/test');
expect(req.request.headers.has('X-XSRF-TOKEN')).toEqual(false);
req.flush({});
});

it('does not apply XSRF protection when request is absolute', () => {
it('does not apply XSRF protection when request is absolute and cross-origin', () => {
interceptor
.intercept(new HttpRequest('POST', 'https://example.com/test', {}), backend)
.subscribe();
Expand All @@ -80,13 +93,52 @@ describe('HttpXsrfInterceptor', () => {
req.flush({});
});

it('does not apply XSRF protection when request is protocol relative', () => {
it('does not apply XSRF protection when request is protocol relative and cross-origin', () => {
interceptor.intercept(new HttpRequest('POST', '//example.com/test', {}), backend).subscribe();
const req = backend.expectOne('//example.com/test');
expect(req.request.headers.has('X-XSRF-TOKEN')).toBeFalse();
req.flush({});
});

it('does not apply XSRF protection when request uses backslashes or whitespace and is cross-origin', () => {
Comment thread
SkyZeroZx marked this conversation as resolved.
// Browsers read `\` as `/`, drop leading spaces and control characters, and remove tabs and
// newlines anywhere, so all of these URLs point to `example.com`.
const urls = [
'/\\example.com/test',
'\\\\example.com/test',
'http:\\\\example.com/test',
' //example.com/test',
'\u0000//example.com/test',
'\t//example.com/test',
'/\n/example.com/test',
'ht\ttp://example.com/test',
];
for (const url of urls) {
interceptor.intercept(new HttpRequest('POST', url, {}), backend).subscribe();
const req = backend.expectOne(url);
expect(req.request.headers.has('X-XSRF-TOKEN')).withContext(JSON.stringify(url)).toBeFalse();
req.flush({});
}
});

it('does apply XSRF protection when request is same-origin', () => {
interceptor
.intercept(new HttpRequest('POST', 'http://sub.example.com/test', {}), backend)
.subscribe();
const req = backend.expectOne('http://sub.example.com/test');
expect(req.request.headers.has('X-XSRF-TOKEN')).toBeTrue();
req.flush({});
});

it('does apply XSRF protection when request is protocol relative and same-origin', () => {
interceptor
.intercept(new HttpRequest('POST', '//sub.example.com/test', {}), backend)
.subscribe();
const req = backend.expectOne('//sub.example.com/test');
expect(req.request.headers.has('X-XSRF-TOKEN')).toBeTrue();
req.flush({});
});

it('does not overwrite existing header', () => {
interceptor
.intercept(
Expand Down
31 changes: 17 additions & 14 deletions packages/core/src/render3/i18n/i18n_apply.ts
Loading