Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

feat($http): support sending XSRF token to whitelisted origins #14890

Closed
Closed
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
1 change: 1 addition & 0 deletions src/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@
"urlResolve": false,
"urlIsSameOrigin": false,
"urlIsSameOriginAsBaseUrl": false,
"urlIsAllowedOriginFactory": false,

/* ng/controller.js */
"identifierForController": false,
Expand Down
98 changes: 81 additions & 17 deletions src/ng/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ function $HttpParamSerializerProvider() {
* * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
*
* Note that serializer will sort the request parameters alphabetically.
* */
*/

this.$get = function() {
return function ngParamSerializer(params) {
Expand Down Expand Up @@ -101,7 +101,7 @@ function $HttpParamSerializerJQLikeProvider() {
* });
* ```
*
* */
*/
this.$get = function() {
return function jQueryLikeParamSerializer(params) {
if (!params) return '';
Expand Down Expand Up @@ -261,7 +261,7 @@ function isSuccess(status) {
*
* @description
* Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
* */
*/
function $HttpProvider() {
/**
* @ngdoc property
Expand Down Expand Up @@ -315,7 +315,7 @@ function $HttpProvider() {
* - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
* XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
*
**/
*/
var defaults = this.defaults = {
// transform incoming response data
transformResponse: [defaultHttpResponseTransform],
Expand Down Expand Up @@ -362,7 +362,7 @@ function $HttpProvider() {
*
* @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
* otherwise, returns the current configured value.
**/
*/
this.useApplyAsync = function(value) {
if (isDefined(value)) {
useApplyAsync = !!value;
Expand All @@ -383,9 +383,51 @@ function $HttpProvider() {
* array, on request, but reverse order, on response.
*
* {@link ng.$http#interceptors Interceptors detailed info}
**/
*/
var interceptorFactories = this.interceptors = [];

/**
* @ngdoc property
* @name $httpProvider#xsrfWhitelistedOrigins
* @description
*
* Array containing URLs whose origins are trusted to receive the XSRF token. See the
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Array containing "origins" that are trusted?
Or if you explicitly accept URLs (but ignore the path etc) then change the name to xsrfWhitelistedUrls.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do want to explicitly accept URLs (but ignore the path etc), but I think xsrfWhitelistedUrls will be misleading in that case. It would sound like you can whitelist specific URLs.

How about I change the description to "...containing origins that are trusted..." and keep the name as is (and also mention below that path etc will be ignored)?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changing the description works for me.

* {@link ng.$http#security-considerations Security Considerations} sections for more details on
* XSRF.
*
* **Note:** An "origin" consists of the [URI scheme](https://en.wikipedia.org/wiki/URI_scheme),
* the [hostname](https://en.wikipedia.org/wiki/Hostname) and the
* [port number](https://en.wikipedia.org/wiki/Port_(computer_networking). For `http:` and
* `https:`, the port number can be omitted if using th default ports (80 and 443 respectively).
* Examples: `http://example.com`, `https://api.example.com:9876`
*
* <div class="alert alert-warning">
* It is not possible to whitelist specific URLs/paths. The `path`, `query` and `fragment` parts
* of a URL will be ignored. For example, `https://foo.com/path/bar?query=baz#fragment` will be
* treated as `https://foo.com`, meaning that **all** requests to URLs starting with
* `https://foo.com/` will include the XSRF token.
* </div>
*
* @example
*
* ```js
* // App served from `https://example.com/`.
* angular.
* module('xsrfWhitelistedOriginsExample', []).
* config(['$httpProvider', function($httpProvider) {
* $httpProvider.xsrfWhitelistedOrigins.push('https://api.example.com');
* }]).
* run(['$http', function($http) {
* // The XSRF token will be sent.
* $http.get('https://api.example.com/preferences').then(...);
*
* // The XSRF token will NOT be sent.
* $http.get('https://stats.example.com/activity').then(...);
* }]);
* ```
*/
var xsrfWhitelistedOrigins = this.xsrfWhitelistedOrigins = [];

this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',
function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {

Expand All @@ -409,6 +451,11 @@ function $HttpProvider() {
? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
});

/**
* A function to check request URLs against a list of allowed origins.
*/
var urlIsAllowedOrigin = urlIsAllowedOriginFactory(xsrfWhitelistedOrigins);

/**
* @ngdoc service
* @kind function
Expand Down Expand Up @@ -765,25 +812,42 @@ function $HttpProvider() {
* which the attacker can trick an authenticated user into unknowingly executing actions on your
* website. AngularJS provides a mechanism to counter XSRF. When performing XHR requests, the
* $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
* header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
* cookie, your server can be assured that the XHR came from JavaScript running on your domain.
* The header will not be set for cross-domain requests.
* header (by default `X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read
* the cookie, your server can be assured that the XHR came from JavaScript running on your
* domain.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have sent the request. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript from
* server can verify that the cookie matches the `X-XSRF-TOKEN` HTTP header, and therefore be
* sure that only JavaScript running on your domain could have sent the request. The token must
* be unique for each user and must be verifiable by the server (to prevent the JavaScript from
* making up its own tokens). We recommend that the token is a digest of your site's
* authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
* for added security.
*
* The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
* properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
* or the per-request config object.
* The header will &mdash; by default &mdash; **not** be set for cross-domain requests. This
* prevents unauthorized servers (e.g. malicious or compromised 3rd-party APIs) from gaining
* access to your users' XSRF tokens and exposing them to Cross Site Request Forgery. If you
* want to, you can whitelist additional origins to also receive the XSRF token, by adding them
* to {@link ng.$httpProvider#xsrfWhitelistedOrigins xsrfWhitelistedOrigins}. This might be
* useful, for example, if your application, served from `example.com`, needs to access your API
* at `api.example.com`.
* See {@link ng.$httpProvider#xsrfWhitelistedOrigins $httpProvider.xsrfWhitelistedOrigins} for
* more details.
*
* <div class="alert alert-danger">
* **Warning**<br />
* Only whitelist origins that you have control over and make sure you understand the
* implications of doing so.
* </div>
*
* The name of the cookie and the header can be specified using the `xsrfCookieName` and
* `xsrfHeaderName` properties of either `$httpProvider.defaults` at config-time,
* `$http.defaults` at run-time, or the per-request config object.
*
* In order to prevent collisions in environments where multiple AngularJS apps share the
* same domain or subdomain, we recommend that each application uses unique cookie name.
* same domain or subdomain, we recommend that each application uses a unique cookie name.
*
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
Expand Down Expand Up @@ -1343,7 +1407,7 @@ function $HttpProvider() {
// if we won't have the response in cache, set the xsrf headers and
// send the request to the backend
if (isUndefined(cachedResp)) {
var xsrfValue = urlIsSameOrigin(config.url)
var xsrfValue = urlIsAllowedOrigin(config.url)
? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
: undefined;
if (xsrfValue) {
Expand Down
57 changes: 45 additions & 12 deletions src/ng/urlUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ var baseUrlParsingNode;
* http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
*
* @kind function
* @param {string} url The URL to be parsed.
* @param {string|object} url The URL to be parsed. If `url` is not a string, it will be returned
* unchanged.
* @description Normalizes and parses a URL.
* @returns {object} Returns the normalized URL as a dictionary.
*
Expand All @@ -57,6 +58,8 @@ var baseUrlParsingNode;
*
*/
function urlResolve(url) {
if (!isString(url)) return url;

var href = url;

// Support: IE 9-11 only
Expand Down Expand Up @@ -84,7 +87,8 @@ function urlResolve(url) {
}

/**
* Parse a request URL and determine whether this is a same-origin request as the application document.
* Parse a request URL and determine whether this is a same-origin request as the application
* document.
*
* @param {string|object} requestUrl The url of the request as a string that will be resolved
* or a parsed URL object.
Expand All @@ -109,37 +113,66 @@ function urlIsSameOriginAsBaseUrl(requestUrl) {
}

/**
* Determines if two URLs share the same origin.
* Create a function that can check a URL's origin against a list of allowed/whitelisted origins.
* The current location's origin is implicitly trusted.
*
* @param {string|object} url1 First URL to compare as a string or a normalized URL in the form of
* a dictionary object returned by `urlResolve()`.
* @param {string|object} url2 Second URL to compare as a string or a normalized URL in the form of
* @param {string[]} whitelistedOriginUrls - A list of URLs (strings), whose origins are trusted.
*
* @returns {Function} - A function that receives a URL (string or parsed URL object) and returns
* whether it is of an allowed origin.
*/
function urlIsAllowedOriginFactory(whitelistedOriginUrls) {
var parsedAllowedOriginUrls = [originUrl].concat(whitelistedOriginUrls.map(urlResolve));

/**
* Check whether the specified URL (string or parsed URL object) has an origin that is allowed
* based on a list of whitelisted-origin URLs. The current location's origin is implicitly
* trusted.
*
* @param {string|Object} requestUrl - The URL to be checked (provided as a string that will be
* resolved or a parsed URL object).
*
* @returns {boolean} - Whether the specified URL is of an allowed origin.
*/
return function urlIsAllowedOrigin(requestUrl) {
var parsedUrl = urlResolve(requestUrl);
return parsedAllowedOriginUrls.some(urlsAreSameOrigin.bind(null, parsedUrl));
};
}

/**
* Determine if two URLs share the same origin.
*
* @param {string|Object} url1 - First URL to compare as a string or a normalized URL in the form of
* a dictionary object returned by `urlResolve()`.
* @return {boolean} True if both URLs have the same origin, and false otherwise.
* @param {string|object} url2 - Second URL to compare as a string or a normalized URL in the form
* of a dictionary object returned by `urlResolve()`.
*
* @returns {boolean} - True if both URLs have the same origin, and false otherwise.
*/
function urlsAreSameOrigin(url1, url2) {
url1 = (isString(url1)) ? urlResolve(url1) : url1;
url2 = (isString(url2)) ? urlResolve(url2) : url2;
url1 = urlResolve(url1);
url2 = urlResolve(url2);

return (url1.protocol === url2.protocol &&
url1.host === url2.host);
}

/**
* Returns the current document base URL.
* @return {string}
* @returns {string}
*/
function getBaseUrl() {
if (window.document.baseURI) {
return window.document.baseURI;
}

// document.baseURI is available everywhere except IE
// `document.baseURI` is available everywhere except IE
if (!baseUrlParsingNode) {
baseUrlParsingNode = window.document.createElement('a');
baseUrlParsingNode.href = '.';

// Work-around for IE bug described in Implementation Notes. The fix in urlResolve() is not
// Work-around for IE bug described in Implementation Notes. The fix in `urlResolve()` is not
// suitable here because we need to track changes to the base URL.
baseUrlParsingNode = baseUrlParsingNode.cloneNode(false);
}
Expand Down
3 changes: 2 additions & 1 deletion test/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,8 @@
/* urlUtils.js */
"urlResolve": false,
"urlIsSameOrigin": false,
"urlIsSameOriginAsBaseUrl": true,
"urlIsSameOriginAsBaseUrl": false,
"urlIsAllowedOriginFactory": false,

/* karma */
"dump": false,
Expand Down
Loading