From 9cd3c1ecade3a1ad6c85df9f958a95bcf48d1252 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Wed, 10 Jul 2024 13:30:12 -0400 Subject: [PATCH 1/6] Upgrade setup-gcloud to v2 (#8286) --- .github/workflows/health-metrics-pull-request.yml | 4 ++-- .github/workflows/health-metrics-release.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/health-metrics-pull-request.yml b/.github/workflows/health-metrics-pull-request.yml index 2148c6d5abf..3063c1abdb7 100644 --- a/.github/workflows/health-metrics-pull-request.yml +++ b/.github/workflows/health-metrics-pull-request.yml @@ -45,7 +45,7 @@ jobs: - uses: 'google-github-actions/auth@v0' with: credentials_json: '${{ secrets.GCP_SA_KEY }}' - - uses: google-github-actions/setup-gcloud@v0 + - uses: google-github-actions/setup-gcloud@v2 - run: yarn install - run: yarn build - name: Run health-metrics/binary-size test @@ -62,7 +62,7 @@ jobs: - uses: 'google-github-actions/auth@v0' with: credentials_json: '${{ secrets.GCP_SA_KEY }}' - - uses: google-github-actions/setup-gcloud@v0 + - uses: google-github-actions/setup-gcloud@v2 - run: yarn install - run: yarn build - name: Run health-metrics/modular-exports-binary-size test diff --git a/.github/workflows/health-metrics-release.yml b/.github/workflows/health-metrics-release.yml index 1fbb9b4d4a1..686c9f51496 100644 --- a/.github/workflows/health-metrics-release.yml +++ b/.github/workflows/health-metrics-release.yml @@ -26,7 +26,7 @@ jobs: - uses: 'google-github-actions/auth@v0' with: credentials_json: '${{ secrets.GCP_SA_KEY }}' - - uses: google-github-actions/setup-gcloud@v0 + - uses: google-github-actions/setup-gcloud@v2 - uses: FirebaseExtended/github-actions/health-metrics/release-diffing@master with: repo: ${{ github.repository }} From d752e809657cea68e6562b24d3f15e60c32ce079 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Wed, 10 Jul 2024 13:30:47 -0400 Subject: [PATCH 2/6] Upgrade firebase-admin and google/cloud-firestore in rules-unit-testing yarn lock (#8298) * Upgrade google-cloud-firestore in rules-unit-testing yarn lock The version of google-cloud-firestore in the rules-unit-testing yarn.lock was listed as 6.6.0, when it was actually 6.8.0. This change ugrades the listed version to be the real version. * Add changeset --- .changeset/chilly-plums-burn.md | 5 +++++ packages/rules-unit-testing/functions/yarn.lock | 12 ++++++------ 2 files changed, 11 insertions(+), 6 deletions(-) create mode 100644 .changeset/chilly-plums-burn.md diff --git a/.changeset/chilly-plums-burn.md b/.changeset/chilly-plums-burn.md new file mode 100644 index 00000000000..05dbf60d69c --- /dev/null +++ b/.changeset/chilly-plums-burn.md @@ -0,0 +1,5 @@ +--- +'@firebase/rules-unit-testing': patch +--- + +Upgrade firebase-admin to 11.11.1 diff --git a/packages/rules-unit-testing/functions/yarn.lock b/packages/rules-unit-testing/functions/yarn.lock index 4617e31a3c7..8a777c0ba14 100644 --- a/packages/rules-unit-testing/functions/yarn.lock +++ b/packages/rules-unit-testing/functions/yarn.lock @@ -78,7 +78,7 @@ dependencies: tslib "^2.1.0" -"@google-cloud/firestore@^6.6.0": +"@google-cloud/firestore@^6.8.0": version "6.8.0" resolved "https://registry.npmjs.org/@google-cloud/firestore/-/firestore-6.8.0.tgz#d8c852844c381afaf62592796606c10e178400b5" integrity sha512-JRpk06SmZXLGz0pNx1x7yU3YhkUXheKgH5hbDZ4kMsdhtfV5qPLJLRI4wv69K0cZorIk+zTMOwptue7hizo0eA== @@ -803,10 +803,10 @@ finalhandler@~1.1.2: statuses "~1.5.0" unpipe "~1.0.0" -firebase-admin@11.10.1: - version "11.10.1" - resolved "https://registry.npmjs.org/firebase-admin/-/firebase-admin-11.10.1.tgz#5f0f83a44627e89938d350c5e4bbac76596c963e" - integrity sha512-atv1E6GbuvcvWaD3eHwrjeP5dAVs+EaHEJhu9CThMzPY6In8QYDiUR6tq5SwGl4SdA/GcAU0nhwWc/FSJsAzfQ== +firebase-admin@11.11.1: + version "11.11.1" + resolved "https://registry.npmjs.org/firebase-admin/-/firebase-admin-11.11.1.tgz#6712923de70d218c9f514d73005d976d03339605" + integrity sha512-UyEbq+3u6jWzCYbUntv/HuJiTixwh36G1R9j0v71mSvGAx/YZEWEW7uSGLYxBYE6ckVRQoKMr40PYUEzrm/4dg== dependencies: "@fastify/busboy" "^1.2.1" "@firebase/database-compat" "^0.3.4" @@ -817,7 +817,7 @@ firebase-admin@11.10.1: node-forge "^1.3.1" uuid "^9.0.0" optionalDependencies: - "@google-cloud/firestore" "^6.6.0" + "@google-cloud/firestore" "^6.8.0" "@google-cloud/storage" "^6.9.5" firebase-functions@3.24.1: From 84fe88079842d2840a10eccc865c78bca2653f35 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Wed, 10 Jul 2024 16:43:43 -0400 Subject: [PATCH 3/6] Remove .git (#8362) --- .github/workflows/test-all.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/test-all.yml b/.github/workflows/test-all.yml index 2264ab233fd..3b431328658 100644 --- a/.github/workflows/test-all.yml +++ b/.github/workflows/test-all.yml @@ -50,6 +50,8 @@ jobs: yarn - name: yarn build run: yarn build + - name: Remove git directory + run: rm -rf .git - name: Archive build if: ${{ !cancelled() }} run: | From 4b4db85ff8f61df94309150198ef492dc702fd2f Mon Sep 17 00:00:00 2001 From: Tanzim Hossain Date: Mon, 15 Jul 2024 13:17:21 -0400 Subject: [PATCH 4/6] VertexAI: add support for mock responses versioning system (#8361) --- .../workflows/check-vertexai-responses.yml | 54 +++++++++++++++++++ packages/vertexai/package.json | 2 +- scripts/update_vertexai_responses.sh | 35 ++++++++++++ 3 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/check-vertexai-responses.yml create mode 100755 scripts/update_vertexai_responses.sh diff --git a/.github/workflows/check-vertexai-responses.yml b/.github/workflows/check-vertexai-responses.yml new file mode 100644 index 00000000000..61f9cd45549 --- /dev/null +++ b/.github/workflows/check-vertexai-responses.yml @@ -0,0 +1,54 @@ +# Copyright 2024 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. + +name: Check Vertex AI Responses + +on: pull_request + +jobs: + check-version: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Clone mock responses + run: scripts/update_vertexai_responses.sh + - name: Find cloned and latest versions + run: | + CLONED=$(git describe --tags) + LATEST=$(git tag --sort=v:refname | tail -n1) + echo "cloned_tag=$CLONED" >> $GITHUB_ENV + echo "latest_tag=$LATEST" >> $GITHUB_ENV + working-directory: packages/vertexai/test-utils/vertexai-sdk-test-data + - name: Find comment from previous run if exists + uses: peter-evans/find-comment@3eae4d37986fb5a8592848f6a574fdf654e61f9e + id: fc + with: + issue-number: ${{github.event.number}} + body-includes: Vertex AI Mock Responses Check + - name: Comment on PR if newer version is available + if: ${{env.cloned_tag != env.latest_tag && !steps.fc.outputs.comment-id}} + uses: peter-evans/create-or-update-comment@71345be0265236311c031f5c7866368bd1eff043 + with: + issue-number: ${{github.event.number}} + body: > + ### Vertex AI Mock Responses Check :warning: + + A newer major version of the mock responses for Vertex AI unit tests is available. + [update_vertexai_responses.sh](https://github.com/firebase/firebase-js-sdk/blob/main/scripts/update_vertexai_responses.sh) + should be updated to clone the latest version of the responses: `${{env.latest_tag}}` + - name: Delete comment when version gets updated + if: ${{env.cloned_tag == env.latest_tag && steps.fc.outputs.comment-id}} + uses: detomarco/delete-comment@850734dd44d8b15fef55b45252613b903ceb06f0 + with: + comment-id: ${{ steps.fc.outputs.comment-id }} diff --git a/packages/vertexai/package.json b/packages/vertexai/package.json index e6b7b0b5f6e..9c72f9484d6 100644 --- a/packages/vertexai/package.json +++ b/packages/vertexai/package.json @@ -33,7 +33,7 @@ "build": "rollup -c && yarn api-report", "build:deps": "lerna run --scope @firebase/vertexai --include-dependencies build", "dev": "rollup -c -w", - "update-responses": "cd test-utils && rm -rf vertexai-sdk-test-data && git clone --depth 1 https://github.com/FirebaseExtended/vertexai-sdk-test-data.git", + "update-responses": "../../scripts/update_vertexai_responses.sh", "testsetup": "yarn update-responses && yarn ts-node ./test-utils/convert-mocks.ts", "test": "run-p --npm-path npm lint test:browser", "test:ci": "yarn testsetup && node ../../scripts/run_tests_in_ci.js -s test", diff --git a/scripts/update_vertexai_responses.sh b/scripts/update_vertexai_responses.sh new file mode 100755 index 00000000000..98f69b14f96 --- /dev/null +++ b/scripts/update_vertexai_responses.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +# Copyright 2024 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. + +# This script replaces mock response files for Vertex AI unit tests with a fresh +# clone of the shared repository of Vertex AI test data. + +RESPONSES_VERSION='v1.*' # The major version of mock responses to use +REPO_NAME="vertexai-sdk-test-data" +REPO_LINK="https://github.com/FirebaseExtended/$REPO_NAME.git" + +cd "$(dirname "$0")/../packages/vertexai/test-utils" || exit +rm -rf "$REPO_NAME" +git clone "$REPO_LINK" --quiet || exit +cd "$REPO_NAME" || exit + +# Find and checkout latest tag matching major version +TAG=$(git tag -l "$RESPONSES_VERSION" --sort=v:refname | tail -n1) +if [ -z "$TAG" ]; then + echo "Error: No tag matching '$RESPONSES_VERSION' found in $REPO_NAME" + exit +fi +git checkout "$TAG" --quiet From f58d48cd42c9f09eab4d8b2a606af360528917f8 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Tue, 16 Jul 2024 10:55:12 -0400 Subject: [PATCH 5/6] Use safevalues to fix trusted types issues reported by tsec (#8301) * Use safevalues to fix trusted types issues reported by tsec * Upgrade to safevalues 0.6.0 * Remove exemptions, and untested usages of safevalues * Add dependency that was accidentally removed * Add FIXMEs for tsec violations * Run formatting * Compare against full Gtag script in tests * Check that full reCAPTCHA script URL was assigned to script element * Replace FIXMEs with TODOs * Remove auth, rtdb, messaging from changeset --- .changeset/happy-trees-battle.md | 6 ++ packages/analytics/package.json | 5 +- packages/analytics/src/helpers.test.ts | 78 ++----------------- packages/analytics/src/helpers.ts | 60 +++----------- packages/app-check/package.json | 1 + packages/app-check/src/recaptcha.test.ts | 12 ++- packages/app-check/src/recaptcha.ts | 15 +++- packages/auth/package.json | 3 +- packages/auth/src/platform_browser/index.ts | 4 + .../auth/src/platform_browser/load_js.test.ts | 4 + packages/auth/tsconfig.json | 10 ++- packages/database-compat/tsconfig.json | 10 ++- packages/database/package.json | 1 + .../src/realtime/BrowserPollConnection.ts | 6 ++ packages/database/tsconfig.json | 10 ++- packages/messaging/package.json | 1 + .../src/helpers/registerDefaultSw.ts | 1 + yarn.lock | 5 ++ 18 files changed, 95 insertions(+), 137 deletions(-) create mode 100644 .changeset/happy-trees-battle.md diff --git a/.changeset/happy-trees-battle.md b/.changeset/happy-trees-battle.md new file mode 100644 index 00000000000..bf4a10a3bfe --- /dev/null +++ b/.changeset/happy-trees-battle.md @@ -0,0 +1,6 @@ +--- +'@firebase/analytics': patch +'@firebase/app-check': patch +--- + +Begin using [safevalues](https://github.com/google/safevalues) to sanitize HTML vulnerable to XSS. diff --git a/packages/analytics/package.json b/packages/analytics/package.json index 5e200228a69..a967e04ce73 100644 --- a/packages/analytics/package.json +++ b/packages/analytics/package.json @@ -45,15 +45,16 @@ "@firebase/logger": "0.4.2", "@firebase/util": "1.9.7", "@firebase/component": "0.6.8", - "tslib": "^2.1.0" + "tslib": "^2.1.0", + "safevalues": "0.6.0" }, "license": "Apache-2.0", "devDependencies": { "@firebase/app": "0.10.6", - "rollup": "2.79.1", "@rollup/plugin-commonjs": "21.1.0", "@rollup/plugin-json": "4.1.0", "@rollup/plugin-node-resolve": "13.3.0", + "rollup": "2.79.1", "rollup-plugin-typescript2": "0.31.2", "typescript": "4.7.4" }, diff --git a/packages/analytics/src/helpers.test.ts b/packages/analytics/src/helpers.test.ts index ff06ba3ea6c..9145b625469 100644 --- a/packages/analytics/src/helpers.test.ts +++ b/packages/analytics/src/helpers.test.ts @@ -24,16 +24,12 @@ import { insertScriptTag, wrapOrCreateGtag, findGtagScriptOnPage, - promiseAllSettled, - createGtagTrustedTypesScriptURL, - createTrustedTypesPolicy + promiseAllSettled } from './helpers'; -import { GtagCommand, GTAG_URL } from './constants'; +import { GtagCommand } from './constants'; import { Deferred } from '@firebase/util'; import { ConsentSettings } from './public-types'; import { removeGtagScripts } from '../testing/gtag-script-util'; -import { logger } from './logger'; -import { AnalyticsError, ERROR_FACTORY } from './errors'; const fakeMeasurementId = 'abcd-efgh-ijkl'; const fakeAppId = 'my-test-app-1234'; @@ -50,71 +46,6 @@ const fakeDynamicConfig: DynamicConfig = { }; const fakeDynamicConfigPromises = [Promise.resolve(fakeDynamicConfig)]; -describe('Trusted Types policies and functions', () => { - if (window.trustedTypes) { - describe('Trusted types exists', () => { - let ttStub: SinonStub; - - beforeEach(() => { - ttStub = stub( - window.trustedTypes as TrustedTypePolicyFactory, - 'createPolicy' - ).returns({ - createScriptURL: (s: string) => s - } as any); - }); - - afterEach(() => { - removeGtagScripts(); - ttStub.restore(); - }); - - it('Verify trustedTypes is called if the API is available', () => { - const trustedTypesPolicy = createTrustedTypesPolicy( - 'firebase-js-sdk-policy', - { - createScriptURL: createGtagTrustedTypesScriptURL - } - ); - - expect(ttStub).to.be.called; - expect(trustedTypesPolicy).not.to.be.undefined; - }); - - it('createGtagTrustedTypesScriptURL verifies gtag URL base exists when a URL is provided', () => { - expect(createGtagTrustedTypesScriptURL(GTAG_URL)).to.equal(GTAG_URL); - }); - - it('createGtagTrustedTypesScriptURL rejects URLs with non-gtag base', () => { - const NON_GTAG_URL = 'http://iamnotgtag.com'; - const loggerWarnStub = stub(logger, 'warn'); - const errorMessage = ERROR_FACTORY.create( - AnalyticsError.INVALID_GTAG_RESOURCE, - { - gtagURL: NON_GTAG_URL - } - ).message; - - expect(createGtagTrustedTypesScriptURL(NON_GTAG_URL)).to.equal(''); - expect(loggerWarnStub).to.be.calledWith(errorMessage); - }); - }); - } - describe('Trusted types does not exist', () => { - it('Verify trustedTypes functions are not called if the API is not available', () => { - delete window.trustedTypes; - const trustedTypesPolicy = createTrustedTypesPolicy( - 'firebase-js-sdk-policy', - { - createScriptURL: createGtagTrustedTypesScriptURL - } - ); - - expect(trustedTypesPolicy).to.be.undefined; - }); - }); -}); - describe('Gtag wrapping functions', () => { afterEach(() => { removeGtagScripts(); @@ -136,8 +67,9 @@ describe('Gtag wrapping functions', () => { insertScriptTag(customDataLayerName, fakeMeasurementId); const scriptTag = findGtagScriptOnPage(customDataLayerName); expect(scriptTag).to.not.be.null; - expect(scriptTag!.src).to.contain(`l=customDataLayerName`); - expect(scriptTag!.src).to.contain(`id=${fakeMeasurementId}`); + expect(scriptTag!.src).to.equal( + `https://www.googletagmanager.com/gtag/js?l=${customDataLayerName}&id=${fakeMeasurementId}` + ); }); // The test above essentially already touches this functionality but it is still valuable diff --git a/packages/analytics/src/helpers.ts b/packages/analytics/src/helpers.ts index 2e9a46e03b2..a35ee0b01f4 100644 --- a/packages/analytics/src/helpers.ts +++ b/packages/analytics/src/helpers.ts @@ -24,25 +24,12 @@ import { import { DynamicConfig, DataLayer, Gtag, MinimalDynamicConfig } from './types'; import { GtagCommand, GTAG_URL } from './constants'; import { logger } from './logger'; -import { AnalyticsError, ERROR_FACTORY } from './errors'; +import { trustedResourceUrl } from 'safevalues'; +import { safeScriptEl } from 'safevalues/dom'; // Possible parameter types for gtag 'event' and 'config' commands type GtagConfigOrEventParams = ControlParams & EventParams & CustomParams; -/** - * Verifies and creates a TrustedScriptURL. - */ -export function createGtagTrustedTypesScriptURL(url: string): string { - if (!url.startsWith(GTAG_URL)) { - const err = ERROR_FACTORY.create(AnalyticsError.INVALID_GTAG_RESOURCE, { - gtagURL: url - }); - logger.warn(err.message); - return ''; - } - return url; -} - /** * Makeshift polyfill for Promise.allSettled(). Resolves when all promises * have either resolved or rejected. @@ -55,29 +42,6 @@ export function promiseAllSettled( return Promise.all(promises.map(promise => promise.catch(e => e))); } -/** - * Creates a TrustedTypePolicy object that implements the rules passed as policyOptions. - * - * @param policyName A string containing the name of the policy - * @param policyOptions Object containing implementations of instance methods for TrustedTypesPolicy, see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicy#instance_methods - * | the TrustedTypePolicy reference documentation}. - */ -export function createTrustedTypesPolicy( - policyName: string, - policyOptions: Partial -): Partial | undefined { - // Create a TrustedTypes policy that we can use for updating src - // properties - let trustedTypesPolicy: Partial | undefined; - if (window.trustedTypes) { - trustedTypesPolicy = window.trustedTypes.createPolicy( - policyName, - policyOptions - ); - } - return trustedTypesPolicy; -} - /** * Inserts gtag script tag into the page to asynchronously download gtag. * @param dataLayerName Name of datalayer (most often the default, "_dataLayer"). @@ -86,21 +50,17 @@ export function insertScriptTag( dataLayerName: string, measurementId: string ): void { - const trustedTypesPolicy = createTrustedTypesPolicy( - 'firebase-js-sdk-policy', - { - createScriptURL: createGtagTrustedTypesScriptURL - } - ); - const script = document.createElement('script'); + // We are not providing an analyticsId in the URL because it would trigger a `page_view` // without fid. We will initialize ga-id using gtag (config) command together with fid. - - const gtagScriptURL = `${GTAG_URL}?l=${dataLayerName}&id=${measurementId}`; - (script.src as string | TrustedScriptURL) = trustedTypesPolicy - ? (trustedTypesPolicy as TrustedTypePolicy)?.createScriptURL(gtagScriptURL) - : gtagScriptURL; + // + // We also have to ensure the template string before the first expression constitutes a valid URL + // start, as this is what the initial validation focuses on. If the template literal begins + // directly with an expression (e.g. `${GTAG_SCRIPT_URL}`), the validation fails due to an + // empty initial string. + const url = trustedResourceUrl`https://www.googletagmanager.com/gtag/js?l=${dataLayerName}&id=${measurementId}`; + safeScriptEl.setSrc(script, url); script.async = true; document.head.appendChild(script); diff --git a/packages/app-check/package.json b/packages/app-check/package.json index 07468c8738c..0a200953c0a 100644 --- a/packages/app-check/package.json +++ b/packages/app-check/package.json @@ -42,6 +42,7 @@ "@firebase/util": "1.9.7", "@firebase/component": "0.6.8", "@firebase/logger": "0.4.2", + "safevalues": "0.6.0", "tslib": "^2.1.0" }, "license": "Apache-2.0", diff --git a/packages/app-check/src/recaptcha.test.ts b/packages/app-check/src/recaptcha.test.ts index 7f028cca1a5..03c72dcab73 100644 --- a/packages/app-check/src/recaptcha.test.ts +++ b/packages/app-check/src/recaptcha.test.ts @@ -30,7 +30,9 @@ import { initializeV3, initializeEnterprise, getToken, - GreCAPTCHATopLevel + GreCAPTCHATopLevel, + RECAPTCHA_ENTERPRISE_URL, + RECAPTCHA_URL } from './recaptcha'; import * as utils from './util'; import { @@ -81,7 +83,9 @@ describe('recaptcha', () => { expect(findgreCAPTCHAScriptsOnPage().length).to.equal(0); await initializeV3(app, FAKE_SITE_KEY); - expect(findgreCAPTCHAScriptsOnPage().length).to.equal(1); + const greCATPCHAScripts = findgreCAPTCHAScriptsOnPage(); + expect(greCATPCHAScripts.length).to.equal(1); + expect(greCATPCHAScripts[0].src).to.equal(RECAPTCHA_URL); }); it('creates invisible widget', async () => { @@ -128,7 +132,9 @@ describe('recaptcha', () => { expect(findgreCAPTCHAScriptsOnPage().length).to.equal(0); await initializeEnterprise(app, FAKE_SITE_KEY); - expect(findgreCAPTCHAScriptsOnPage().length).to.equal(1); + const greCAPTCHAScripts = findgreCAPTCHAScriptsOnPage(); + expect(greCAPTCHAScripts.length).to.equal(1); + expect(greCAPTCHAScripts[0].src).to.equal(RECAPTCHA_ENTERPRISE_URL); }); it('creates invisible widget', async () => { diff --git a/packages/app-check/src/recaptcha.ts b/packages/app-check/src/recaptcha.ts index 8eb72e2add7..0f0650296af 100644 --- a/packages/app-check/src/recaptcha.ts +++ b/packages/app-check/src/recaptcha.ts @@ -19,7 +19,12 @@ import { FirebaseApp } from '@firebase/app'; import { getStateReference } from './state'; import { Deferred } from '@firebase/util'; import { getRecaptcha, ensureActivated } from './util'; +import { trustedResourceUrl } from 'safevalues'; +import { safeScriptEl } from 'safevalues/dom'; +// Note that these are used for testing. If they are changed, the URLs used in loadReCAPTCHAV3Script +// and loadReCAPTCHAEnterpriseScript must also be changed. They aren't used to create the URLs +// since trusted resource URLs must be created using template string literals. export const RECAPTCHA_URL = 'https://www.google.com/recaptcha/api.js'; export const RECAPTCHA_ENTERPRISE_URL = 'https://www.google.com/recaptcha/enterprise.js'; @@ -166,14 +171,20 @@ function renderInvisibleWidget( function loadReCAPTCHAV3Script(onload: () => void): void { const script = document.createElement('script'); - script.src = RECAPTCHA_URL; + safeScriptEl.setSrc( + script, + trustedResourceUrl`https://www.google.com/recaptcha/api.js` + ); script.onload = onload; document.head.appendChild(script); } function loadReCAPTCHAEnterpriseScript(onload: () => void): void { const script = document.createElement('script'); - script.src = RECAPTCHA_ENTERPRISE_URL; + safeScriptEl.setSrc( + script, + trustedResourceUrl`https://www.google.com/recaptcha/enterprise.js` + ); script.onload = onload; document.head.appendChild(script); } diff --git a/packages/auth/package.json b/packages/auth/package.json index 4d074795fef..c2007896e91 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -131,7 +131,8 @@ "@firebase/logger": "0.4.2", "@firebase/util": "1.9.7", "undici": "5.28.4", - "tslib": "^2.1.0" + "tslib": "^2.1.0", + "safevalues": "0.6.0" }, "license": "Apache-2.0", "devDependencies": { diff --git a/packages/auth/src/platform_browser/index.ts b/packages/auth/src/platform_browser/index.ts index f94525bfeb7..f2682da38ec 100644 --- a/packages/auth/src/platform_browser/index.ts +++ b/packages/auth/src/platform_browser/index.ts @@ -124,6 +124,10 @@ _setExternalJSProvider({ // TODO: consider adding timeout support & cancellation return new Promise((resolve, reject) => { const el = document.createElement('script'); + // TODO: Do not use setAttribute, since it can lead to XSS. Instead, use the safevalues library to + // safely set an attribute for a sanitized trustedResourceUrl. Since the trustedResourceUrl + // must be initialized from a template string literal, this could involve some heavy + // refactoring. el.setAttribute('src', url); el.onload = resolve; el.onerror = e => { diff --git a/packages/auth/src/platform_browser/load_js.test.ts b/packages/auth/src/platform_browser/load_js.test.ts index 972fb292065..0fda2a6d016 100644 --- a/packages/auth/src/platform_browser/load_js.test.ts +++ b/packages/auth/src/platform_browser/load_js.test.ts @@ -44,6 +44,8 @@ describe('platform-browser/load_js', () => { loadJS(url: string): Promise { return new Promise((resolve, reject) => { const el = document.createElement('script'); + // TODO: Do not use setAttribute, as this can lead to XSS. Instead, use the safevalues + // library, or get an exception for tests. el.setAttribute('src', url); el.onload = resolve; el.onerror = e => { @@ -65,6 +67,8 @@ describe('platform-browser/load_js', () => { // eslint-disable-next-line @typescript-eslint/no-floating-promises _loadJS('http://localhost/url'); + // TODO: Do not use setAttribute, as this can lead to XSS. Instead, use the safevalues + // library, or get an exception for tests. expect(el.setAttribute).to.have.been.calledWith( 'src', 'http://localhost/url' diff --git a/packages/auth/tsconfig.json b/packages/auth/tsconfig.json index 03897eed09c..f100c88aea0 100644 --- a/packages/auth/tsconfig.json +++ b/packages/auth/tsconfig.json @@ -1,10 +1,16 @@ { "extends": "../../config/tsconfig.base.json", "compilerOptions": { - "outDir": "dist" + "outDir": "dist", + "plugins": [ + { + "name": "tsec", + "reportTsecDiagnosticsOnly": true, + } + ] }, "exclude": [ "dist/**/*", "demo/**/*" ] -} \ No newline at end of file +} diff --git a/packages/database-compat/tsconfig.json b/packages/database-compat/tsconfig.json index ce12ac3c5dc..e2f493565c5 100644 --- a/packages/database-compat/tsconfig.json +++ b/packages/database-compat/tsconfig.json @@ -3,9 +3,15 @@ "compilerOptions": { "outDir": "dist", "strict": false, - "downlevelIteration": true + "downlevelIteration": true, + "plugins": [ + { + "name": "tsec", + "reportTsecDiagnosticsOnly": true, + } + ] }, "exclude": [ "dist/**/*" ] -} \ No newline at end of file +} diff --git a/packages/database/package.json b/packages/database/package.json index bb47fe500e8..6486c0d9fdf 100644 --- a/packages/database/package.json +++ b/packages/database/package.json @@ -56,6 +56,7 @@ "@firebase/app-check-interop-types": "0.3.2", "@firebase/auth-interop-types": "0.2.3", "faye-websocket": "0.11.4", + "safevalues": "0.6.0", "tslib": "^2.1.0" }, "devDependencies": { diff --git a/packages/database/src/realtime/BrowserPollConnection.ts b/packages/database/src/realtime/BrowserPollConnection.ts index 21396cecc8e..bcfd8bba09d 100644 --- a/packages/database/src/realtime/BrowserPollConnection.ts +++ b/packages/database/src/realtime/BrowserPollConnection.ts @@ -475,6 +475,8 @@ export class FirebaseIFrameScriptHolder { const iframeContents = '' + script + ''; try { this.myIFrame.doc.open(); + // TODO: Do not use document.write, since it can lead to XSS. Instead, use the safevalues + // library to sanitize the HTML in the iframeContents. this.myIFrame.doc.write(iframeContents); this.myIFrame.doc.close(); } catch (e) { @@ -717,6 +719,10 @@ export class FirebaseIFrameScriptHolder { const newScript = this.myIFrame.doc.createElement('script'); newScript.type = 'text/javascript'; newScript.async = true; + // TODO: We cannot assign an arbitrary URL to a script attached to the DOM, since it is + // at risk of XSS. We should use the safevalues library to create a safeScriptEl, and + // assign a sanitized trustedResourceURL to it. Since the URL must be a template string + // literal, this could require some heavy refactoring. newScript.src = url; // eslint-disable-next-line @typescript-eslint/no-explicit-any newScript.onload = (newScript as any).onreadystatechange = diff --git a/packages/database/tsconfig.json b/packages/database/tsconfig.json index ce12ac3c5dc..e2f493565c5 100644 --- a/packages/database/tsconfig.json +++ b/packages/database/tsconfig.json @@ -3,9 +3,15 @@ "compilerOptions": { "outDir": "dist", "strict": false, - "downlevelIteration": true + "downlevelIteration": true, + "plugins": [ + { + "name": "tsec", + "reportTsecDiagnosticsOnly": true, + } + ] }, "exclude": [ "dist/**/*" ] -} \ No newline at end of file +} diff --git a/packages/messaging/package.json b/packages/messaging/package.json index a1d61f92129..2fb2c2d2372 100644 --- a/packages/messaging/package.json +++ b/packages/messaging/package.json @@ -59,6 +59,7 @@ "@firebase/util": "1.9.7", "@firebase/component": "0.6.8", "idb": "7.1.1", + "safevalues": "0.6.0", "tslib": "^2.1.0" }, "devDependencies": { diff --git a/packages/messaging/src/helpers/registerDefaultSw.ts b/packages/messaging/src/helpers/registerDefaultSw.ts index 239e6ed8244..b0be350bf72 100644 --- a/packages/messaging/src/helpers/registerDefaultSw.ts +++ b/packages/messaging/src/helpers/registerDefaultSw.ts @@ -24,6 +24,7 @@ export async function registerDefaultSw( messaging: MessagingService ): Promise { try { + // TODO: Use safevalues to register the service worker with a sanitized trustedResourceUrl. messaging.swRegistration = await navigator.serviceWorker.register( DEFAULT_SW_PATH, { diff --git a/yarn.lock b/yarn.lock index 9d943a928b0..4f1fccdbdc3 100644 --- a/yarn.lock +++ b/yarn.lock @@ -15405,6 +15405,11 @@ safe-stable-stringify@^1.1.0: resolved "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz" integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== +safevalues@0.6.0: + version "0.6.0" + resolved "https://registry.npmjs.org/safevalues/-/safevalues-0.6.0.tgz#425eadbdb699c13d8cfd932485983f858222362a" + integrity sha512-MZ7DcTOcIoPXN36/UONVE9BT0pmwlCr9WcS7Pj/q4FxOwr33FkWC0CUWj/THQXYWxf/F7urbhaHaOeFPSqGqHA== + sauce-connect-launcher@^1.2.7: version "1.3.2" resolved "https://registry.npmjs.org/sauce-connect-launcher/-/sauce-connect-launcher-1.3.2.tgz" From fd8bd4b024a0b4a38fab1feedce702e5a12ec524 Mon Sep 17 00:00:00 2001 From: Daniel La Rocque Date: Tue, 16 Jul 2024 16:04:44 -0400 Subject: [PATCH 6/6] Disable extraneous import errors on violating lines in auth tests (#8363) --- packages/auth/test/helpers/integration/helpers.ts | 1 + packages/auth/test/integration/flows/totp.test.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/packages/auth/test/helpers/integration/helpers.ts b/packages/auth/test/helpers/integration/helpers.ts index 540c926dd99..d0e422038dd 100644 --- a/packages/auth/test/helpers/integration/helpers.ts +++ b/packages/auth/test/helpers/integration/helpers.ts @@ -17,6 +17,7 @@ import * as sinon from 'sinon'; import { FirebaseServerApp, deleteApp, initializeApp } from '@firebase/app'; +// eslint-disable-next-line import/no-extraneous-dependencies import { Auth, User } from '@firebase/auth'; import { getAuth, connectAuthEmulator } from '../../../'; // Use browser OR node dist entrypoint depending on test env. diff --git a/packages/auth/test/integration/flows/totp.test.ts b/packages/auth/test/integration/flows/totp.test.ts index 4a256b15659..d5e7aba94fe 100644 --- a/packages/auth/test/integration/flows/totp.test.ts +++ b/packages/auth/test/integration/flows/totp.test.ts @@ -18,6 +18,7 @@ import { expect, use } from 'chai'; import chaiAsPromised from 'chai-as-promised'; import sinonChai from 'sinon-chai'; +// eslint-disable-next-line import/no-extraneous-dependencies import { Auth, multiFactor,