Skip to content

Add origin validation to popup/redirect flows #3730

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Sep 2, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
3 changes: 2 additions & 1 deletion packages-exp/auth-exp/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ export enum Endpoint {
FINALIZE_PHONE_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:finalize',
START_PHONE_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:start',
FINALIZE_PHONE_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:finalize',
WITHDRAW_MFA = '/v2/accounts/mfaEnrollment:withdraw'
WITHDRAW_MFA = '/v2/accounts/mfaEnrollment:withdraw',
GET_PROJECT_CONFIG = '/v1/projects'
}

export const DEFAULT_API_TIMEOUT_MS = new Delay(30_000, 60_000);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { expect, use } from 'chai';
import * as chaiAsPromised from 'chai-as-promised';

import { FirebaseError } from '@firebase/util';

import { Endpoint, HttpHeader } from '../';
import { mockEndpoint } from '../../../test/helpers/api/helper';
import { testAuth, TestAuth } from '../../../test/helpers/mock_auth';
import * as mockFetch from '../../../test/helpers/mock_fetch';
import { ServerError } from '../errors';
import { _getProjectConfig } from './get_project_config';

use(chaiAsPromised);

describe('api/project_config/getProjectConfig', () => {
let auth: TestAuth;

beforeEach(async () => {
auth = await testAuth();
mockFetch.setUp();
});

afterEach(mockFetch.tearDown);

it('should POST to the correct endpoint', async () => {
const mock = mockEndpoint(Endpoint.GET_PROJECT_CONFIG, {
authorizedDomains: ['google.com']
});

const response = await _getProjectConfig(auth);
expect(response.authorizedDomains).to.eql(['google.com']);
expect(mock.calls[0].method).to.eq('GET');
expect(mock.calls[0].headers!.get(HttpHeader.X_CLIENT_VERSION)).to.eq(
'testSDK/0.0.0'
);
});

it('should handle errors', async () => {
mockEndpoint(
Endpoint.GET_PROJECT_CONFIG,
{
error: {
code: 400,
message: ServerError.INVALID_PROVIDER_ID,
errors: [
{
message: ServerError.INVALID_PROVIDER_ID
}
]
}
},
400
);

await expect(_getProjectConfig(auth)).to.be.rejectedWith(
FirebaseError,
'Firebase: The specified provider ID is invalid. (auth/invalid-provider-id).'
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { _performApiRequest, Endpoint, HttpMethod } from '../';
import { AuthCore } from '../../model/auth';

export interface GetProjectConfigRequest {}

export interface GetProjectConfigResponse {
authorizedDomains: string[];
}

export async function _getProjectConfig(
auth: AuthCore
): Promise<GetProjectConfigResponse> {
return _performApiRequest<GetProjectConfigRequest, GetProjectConfigResponse>(
auth,
HttpMethod.GET,
Endpoint.GET_PROJECT_CONFIG,
{}
);
}
135 changes: 135 additions & 0 deletions packages-exp/auth-exp/src/core/util/validate_origin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { expect, use } from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as sinon from 'sinon';

import { FirebaseError } from '@firebase/util';

import { mockEndpoint } from '../../../test/helpers/api/helper';
import { testAuth } from '../../../test/helpers/mock_auth';
import * as fetch from '../../../test/helpers/mock_fetch';
import { Endpoint } from '../../api';
import { Auth } from '../../model/auth';
import * as location from './location';
import { _validateOrigin } from './validate_origin';

use(chaiAsPromised);

describe('core/util/validate_origin', () => {
let auth: Auth;
let authorizedDomains: string[];
let currentUrl: string;
beforeEach(async () => {
authorizedDomains = [];
currentUrl = '';

auth = await testAuth();
fetch.setUp();
mockEndpoint(Endpoint.GET_PROJECT_CONFIG, {
get authorizedDomains(): string[] {
return authorizedDomains;
}
});

sinon.stub(location, '_getCurrentUrl').callsFake(() => currentUrl);
});

afterEach(() => {
fetch.tearDown();
sinon.restore();
});

it('smoke test', async () => {
currentUrl = 'https://google.com';
authorizedDomains = ['google.com'];
await expect(_validateOrigin(auth)).to.be.fulfilled;
});

it('failure smoke test', async () => {
currentUrl = 'https://google.com';
authorizedDomains = ['youtube.com'];
await expect(_validateOrigin(auth)).to.be.rejectedWith(
FirebaseError,
'auth/unauthorized-domain'
);
});

it('works when one domain matches', async () => {
currentUrl = 'https://google.com';
authorizedDomains = ['youtube.com', 'google.com'];
await expect(_validateOrigin(auth)).to.be.fulfilled;
});

it('fails when all domains fail', async () => {
currentUrl = 'https://google.com';
authorizedDomains = ['youtube.com', 'firebase.com'];
await expect(_validateOrigin(auth)).to.be.rejectedWith(
FirebaseError,
'auth/unauthorized-domain'
);
});

it('works for chrome extensions', async () => {
currentUrl = 'chrome-extension://somereallylongcomplexstring';
authorizedDomains = [
'google.com',
'chrome-extension://somereallylongcomplexstring'
];
await expect(_validateOrigin(auth)).to.be.fulfilled;
});

it('fails for wrong chrome extensions', async () => {
currentUrl = 'chrome-extension://somereallylongcomplexstring';
authorizedDomains = [
'google.com',
'chrome-extension://someOTHERreallylongcomplexstring'
];
await expect(_validateOrigin(auth)).to.be.rejectedWith(
FirebaseError,
'auth/unauthorized-domain'
);
});

it('works for subdomains', async () => {
currentUrl = 'http://firebase.google.com';
authorizedDomains = ['google.com'];
await expect(_validateOrigin(auth)).to.be.fulfilled;
});

it('works for deeply-linked pages', async () => {
currentUrl = 'http://firebase.google.com/a/b/c/d/e/f/g.html';
authorizedDomains = ['google.com'];
await expect(_validateOrigin(auth)).to.be.fulfilled;
});

it('works with IP addresses', async () => {
currentUrl = 'http://192.168.0.1/a/b/c';
authorizedDomains = ['192.168.0.1'];
await expect(_validateOrigin(auth)).to.be.fulfilled;
});

it('fails with different IP addresses', async () => {
currentUrl = 'http://192.168.0.100/a/b/c';
authorizedDomains = ['192.168.0.1'];
await expect(_validateOrigin(auth)).to.be.rejectedWith(
FirebaseError,
'auth/unauthorized-domain'
);
});
});
81 changes: 81 additions & 0 deletions packages-exp/auth-exp/src/core/util/validate_origin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { _getProjectConfig } from '../../api/project_config/get_project_config';
import { Auth } from '../../model/auth';
import { AuthErrorCode } from '../errors';
import { fail } from './assert';
import { _getCurrentUrl } from './location';

const IP_ADDRESS_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
const HTTP_REGEX = /^https?/;

export async function _validateOrigin(auth: Auth): Promise<void> {
const { authorizedDomains } = await _getProjectConfig(auth);

for (const domain of authorizedDomains) {
try {
if (matchDomain(domain)) {
return;
}
} catch {
// Do nothing if there's a URL error; just continue searching
}
}

// In the old SDK, this error also provides helpful messages.
fail(AuthErrorCode.INVALID_ORIGIN, { appName: auth.name });
}

function matchDomain(expected: string): boolean {
const currentUrl = _getCurrentUrl();
Copy link
Contributor

Choose a reason for hiding this comment

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

doesn't this already do something funny on non-http? like force localhost?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Nah, you're thinking of something else. This function is defined as:

return (typeof self !== 'undefined' && self.location?.href) || '';

const { protocol, hostname } = new URL(currentUrl);
if (expected.startsWith('chrome-extension://')) {
const ceUrl = new URL(expected);

if (ceUrl.hostname === '' && hostname === '') {
// For some reason we're not parsing chrome URLs properly
return (
protocol === 'chrome-extension:' &&
expected.replace('chrome-extension://', '') ===
currentUrl.replace('chrome-extension://', '')
);
}

return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;
}

if (!HTTP_REGEX.test(protocol)) {
return false;
}

if (IP_ADDRESS_REGEX.test(expected)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

what about port specification?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Not sure-- this is copied directly from the old SDK fwiw

// The domain has to be exactly equal to the pattern, as an IP domain will
// only contain the IP, no extra character.
return hostname === expected;
}

// Dots in pattern should be escaped.
const escapedDomainPattern = expected.replace(/\./g, '\\.');
// Non ip address domains.
// domain.com = *.domain.com OR domain.com
const re = new RegExp(
'^(.+\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$',
'i'
);
return re.test(hostname);
}
Loading