Skip to content

Commit

Permalink
Implement rest of RUTv2 features. (#5360)
Browse files Browse the repository at this point in the history
* Implement loading rules and withFunctionTriggersDisabled.

* Implement clearFirestore and storage.

* Add missing await.

* Add default bucketUrl.

* Use alternative method to clear bucket.

* Use default param (review feedback).
  • Loading branch information
yuchenshi authored and Feiyang1 committed Aug 24, 2021
1 parent d998661 commit c8dc2c1
Show file tree
Hide file tree
Showing 13 changed files with 482 additions and 118 deletions.
39 changes: 35 additions & 4 deletions packages/messaging/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ import {
import { MessagingService } from './messaging-service';
import { deleteToken as _deleteToken } from './api/deleteToken';
import { getToken as _getToken } from './api/getToken';
import { isSwSupported, isWindowSupported } from './api/isSupported';
import { onBackgroundMessage as _onBackgroundMessage } from './api/onBackgroundMessage';
import { onMessage as _onMessage } from './api/onMessage';
import { _setDeliveryMetricsExportedToBigQueryEnabled } from './api/setDeliveryMetricsExportedToBigQueryEnabled';
import { ERROR_FACTORY, ErrorCode } from './util/errors';

/**
* Retrieves a Firebase Cloud Messaging instance.
Expand All @@ -43,6 +45,22 @@ import { _setDeliveryMetricsExportedToBigQueryEnabled } from './api/setDeliveryM
* @public
*/
export function getMessagingInWindow(app: FirebaseApp = getApp()): Messaging {
// Conscious decision to make this async check non-blocking during the messaging instance
// initialization phase for performance consideration. An error would be thrown latter for
// developer's information. Developers can then choose to import and call `isSupported` for
// special handling.
isWindowSupported().then(
isSupported => {
// If `isWindowSupported()` resolved, but returned false.
if (!isSupported) {
throw ERROR_FACTORY.create(ErrorCode.UNSUPPORTED_BROWSER);
}
},
_ => {
// If `isWindowSupported()` rejected.
throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNSUPPORTED);
}
);
return _getProvider(getModularInstance(app), 'messaging').getImmediate();
}

Expand All @@ -54,10 +72,23 @@ export function getMessagingInWindow(app: FirebaseApp = getApp()): Messaging {
* @public
*/
export function getMessagingInSw(app: FirebaseApp = getApp()): Messaging {
return _getProvider(
getModularInstance(app),
'messaging-sw'
).getImmediate();
// Conscious decision to make this async check non-blocking during the messaging instance
// initialization phase for performance consideration. An error would be thrown latter for
// developer's information. Developers can then choose to import and call `isSupported` for
// special handling.
isSwSupported().then(
isSupported => {
// If `isSwSupported()` resolved, but returned false.
if (!isSupported) {
throw ERROR_FACTORY.create(ErrorCode.UNSUPPORTED_BROWSER);
}
},
_ => {
// If `isSwSupported()` rejected.
throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNSUPPORTED);
}
);
return _getProvider(getModularInstance(app), 'messaging-sw').getImmediate();
}

/**
Expand Down
36 changes: 0 additions & 36 deletions packages/messaging/src/helpers/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ import {
ComponentType,
InstanceFactory
} from '@firebase/component';
import { ERROR_FACTORY, ErrorCode } from '../util/errors';
import { isSwSupported, isWindowSupported } from '../api/isSupported';
import {
onNotificationClick,
onPush,
Expand All @@ -40,8 +38,6 @@ import { messageEventListener } from '../listeners/window-listener';
const WindowMessagingFactory: InstanceFactory<'messaging'> = (
container: ComponentContainer
) => {
maybeThrowWindowError();

const messaging = new MessagingService(
container.getProvider('app').getImmediate(),
container.getProvider('installations-internal').getImmediate(),
Expand All @@ -58,8 +54,6 @@ const WindowMessagingFactory: InstanceFactory<'messaging'> = (
const WindowMessagingInternalFactory: InstanceFactory<'messaging-internal'> = (
container: ComponentContainer
) => {
maybeThrowWindowError();

const messaging = container
.getProvider('messaging')
.getImmediate() as MessagingService;
Expand All @@ -71,40 +65,10 @@ const WindowMessagingInternalFactory: InstanceFactory<'messaging-internal'> = (
return messagingInternal;
};

function maybeThrowWindowError(): void {
// Conscious decision to make this async check non-blocking during the messaging instance
// initialization phase for performance consideration. An error would be thrown latter for
// developer's information. Developers can then choose to import and call `isSupported` for
// special handling.
isWindowSupported()
.then(isSupported => {
if (!isSupported) {
throw ERROR_FACTORY.create(ErrorCode.UNSUPPORTED_BROWSER);
}
})
.catch(_ => {
throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNSUPPORTED);
});
}

declare const self: ServiceWorkerGlobalScope;
const SwMessagingFactory: InstanceFactory<'messaging'> = (
container: ComponentContainer
) => {
// Conscious decision to make this async check non-blocking during the messaging instance
// initialization phase for performance consideration. An error would be thrown latter for
// developer's information. Developers can then choose to import and call `isSupported` for
// special handling.
isSwSupported()
.then(isSupported => {
if (!isSupported) {
throw ERROR_FACTORY.create(ErrorCode.UNSUPPORTED_BROWSER);
}
})
.catch(_ => {
throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNSUPPORTED);
});

const messaging = new MessagingService(
container.getProvider('app').getImmediate(),
container.getProvider('installations-internal').getImmediate(),
Expand Down
33 changes: 1 addition & 32 deletions packages/rules-unit-testing/src/impl/discovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import { EmulatorConfig, HostAndPort } from '../public_types';
import nodeFetch from 'node-fetch';
import { makeUrl, fixHostname } from './url';

/**
* Use the Firebase Emulator hub to discover other running emulators.
Expand Down Expand Up @@ -79,20 +80,6 @@ export interface DiscoveredEmulators {
hub?: HostAndPort;
}

function makeUrl(hostAndPort: HostAndPort | string, path: string): URL {
if (typeof hostAndPort === 'object') {
const { host, port } = hostAndPort;
if (host.includes(':')) {
hostAndPort = `[${host}]:${port}`;
} else {
hostAndPort = `${host}:${port}`;
}
}
const url = new URL(`http://${hostAndPort}/`);
url.pathname = path;
return url;
}

/**
* @private
*/
Expand Down Expand Up @@ -169,21 +156,3 @@ function emulatorFromEnvVar(envVar: string): HostAndPort | undefined {
}
return { host, port };
}

/**
* Return a connectable hostname, replacing wildcard 0.0.0.0 or :: with loopback
* addresses 127.0.0.1 / ::1 correspondingly. See below for why this is needed:
* https://github.com/firebase/firebase-tools-ui/issues/286
*
* This assumes emulators are running on the same device as the Emulator UI
* server, which should hold if both are started from the same CLI command.
*/
function fixHostname(host: string, fallbackHost?: string): string {
host = host.replace('[', '').replace(']', ''); // Remove IPv6 brackets
if (host === '0.0.0.0') {
host = fallbackHost || '127.0.0.1';
} else if (host === '::') {
host = fallbackHost || '::1';
}
return host;
}
89 changes: 89 additions & 0 deletions packages/rules-unit-testing/src/impl/rules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/**
* @license
* Copyright 2021 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 { HostAndPort } from '../public_types';
import { makeUrl } from './url';
import fetch from 'node-fetch';

/**
* @private
*/
export async function loadDatabaseRules(
hostAndPort: HostAndPort,
databaseName: string,
rules: string
): Promise<void> {
const url = makeUrl(hostAndPort, '/.settings/rules.json');
url.searchParams.append('ns', databaseName);
const resp = await fetch(url, {
method: 'PUT',
headers: { Authorization: 'Bearer owner' },
body: rules
});

if (!resp.ok) {
throw new Error(await resp.text());
}
}

/**
* @private
*/
export async function loadFirestoreRules(
hostAndPort: HostAndPort,
projectId: string,
rules: string
): Promise<void> {
const resp = await fetch(
makeUrl(hostAndPort, `/emulator/v1/projects/${projectId}:securityRules`),
{
method: 'PUT',
body: JSON.stringify({
rules: {
files: [{ content: rules }]
}
})
}
);

if (!resp.ok) {
throw new Error(await resp.text());
}
}

/**
* @private
*/
export async function loadStorageRules(
hostAndPort: HostAndPort,
rules: string
): Promise<void> {
const resp = await fetch(makeUrl(hostAndPort, '/internal/setRules'), {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
rules: {
files: [{ name: 'storage.rules', content: rules }]
}
})
});
if (!resp.ok) {
throw new Error(await resp.text());
}
}
31 changes: 27 additions & 4 deletions packages/rules-unit-testing/src/impl/test_environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* limitations under the License.
*/

import fetch from 'node-fetch';
import firebase from 'firebase/compat/app';
import 'firebase/firestore/compat';
import 'firebase/database/compat';
Expand All @@ -28,6 +29,7 @@ import {
} from '../public_types';

import { DiscoveredEmulators } from './discovery';
import { makeUrl } from './url';

/**
* An implementation of {@code RulesTestEnvironment}. This is private to hide the constructor,
Expand Down Expand Up @@ -100,14 +102,35 @@ export class RulesTestEnvironmentImpl implements RulesTestEnvironment {
});
}

clearFirestore(): Promise<void> {
async clearFirestore(): Promise<void> {
this.checkNotDestroyed();
throw new Error('Method not implemented.');
assertEmulatorRunning(this.emulators, 'firestore');

const resp = await fetch(
makeUrl(
this.emulators.firestore,
`/emulator/v1/projects/${this.projectId}/databases/(default)/documents`
),
{
method: 'DELETE'
}
);

if (!resp.ok) {
throw new Error(await resp.text());
}
}

clearStorage(): Promise<void> {
this.checkNotDestroyed();
throw new Error('Method not implemented.');
return this.withSecurityRulesDisabled(async context => {
const { items } = await context.storage().ref().listAll();
await Promise.all(
items.map(item => {
return item.delete();
})
);
});
}

async cleanup(): Promise<void> {
Expand Down Expand Up @@ -177,7 +200,7 @@ class RulesTestContextImpl implements RulesTestContext {
);
return database;
}
storage(bucketUrl?: string): firebase.storage.Storage {
storage(bucketUrl = `gs://${this.projectId}`): firebase.storage.Storage {
assertEmulatorRunning(this.emulators, 'storage');
const storage = this.getApp().storage(bucketUrl);
storage.useEmulator(
Expand Down
55 changes: 55 additions & 0 deletions packages/rules-unit-testing/src/impl/url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* @license
* Copyright 2021 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 { HostAndPort } from '../public_types';

/**
* Return a connectable hostname, replacing wildcard 0.0.0.0 or :: with loopback
* addresses 127.0.0.1 / ::1 correspondingly. See below for why this is needed:
* https://github.com/firebase/firebase-tools-ui/issues/286
*
* This assumes emulators are running on the same device as fallbackHost (e.g.
* hub), which should hold if both are started from the same CLI command.
* @private
*/
export function fixHostname(host: string, fallbackHost?: string): string {
host = host.replace('[', '').replace(']', ''); // Remove IPv6 brackets
if (host === '0.0.0.0') {
host = fallbackHost || '127.0.0.1';
} else if (host === '::') {
host = fallbackHost || '::1';
}
return host;
}

/**
* Create a URL with host, port, and path. Handles IPv6 bracketing correctly.
* @private
*/
export function makeUrl(hostAndPort: HostAndPort | string, path: string): URL {
if (typeof hostAndPort === 'object') {
const { host, port } = hostAndPort;
if (host.includes(':')) {
hostAndPort = `[${host}]:${port}`;
} else {
hostAndPort = `${host}:${port}`;
}
}
const url = new URL(`http://${hostAndPort}/`);
url.pathname = path;
return url;
}
Loading

0 comments on commit c8dc2c1

Please sign in to comment.