Skip to content

Storage Emulator support in rules-unit-testing #4863

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 11 commits into from
May 6, 2021
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
5 changes: 5 additions & 0 deletions .changeset/moody-suits-punch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@firebase/rules-unit-testing': minor
---

Add support for Storage emulator to rules-unit-testing
3 changes: 3 additions & 0 deletions packages/rules-unit-testing/firebase.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
"functions": {
"port": 9004
},
"storage": {
"port": 9199
},
"ui": {
"enabled": false
}
Expand Down
1 change: 1 addition & 0 deletions packages/rules-unit-testing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export {
initializeTestApp,
loadDatabaseRules,
loadFirestoreRules,
loadStorageRules,
useEmulators,
withFunctionTriggersDisabled
} from './src/api';
120 changes: 109 additions & 11 deletions packages/rules-unit-testing/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,16 @@ const DATABASE_ADDRESS_ENV: string = 'FIREBASE_DATABASE_EMULATOR_HOST';
/** The default address for the local database emulator. */
const DATABASE_ADDRESS_DEFAULT: string = 'localhost:9000';

/** If any of environment variable is set, use it for the Firestore emulator. */
/** If this environment variable is set, use it for the Firestore emulator. */
const FIRESTORE_ADDRESS_ENV: string = 'FIRESTORE_EMULATOR_HOST';
/** The default address for the local Firestore emulator. */
const FIRESTORE_ADDRESS_DEFAULT: string = 'localhost:8080';

/** If this environment variable is set, use it for the Storage emulator. */
const STORAGE_ADDRESS_ENV: string = 'STORAGE_EMULATOR_HOST';
/** The default address for the local Firestore emulator. */
const STORAGE_ADDRESS_DEFAULT: string = 'localhost:9199';

/** Environment variable to locate the Emulator Hub */
const HUB_HOST_ENV: string = 'FIREBASE_EMULATOR_HUB';
/** The default address for the Emulator Hub */
Expand All @@ -47,6 +52,9 @@ let _databaseHost: string | undefined = undefined;
/** The actual address for the Firestore emulator */
let _firestoreHost: string | undefined = undefined;

/** The actual address for the Storage emulator */
let _storageHost: string | undefined = undefined;

/** The actual address for the Emulator Hub */
let _hubHost: string | undefined = undefined;

Expand Down Expand Up @@ -133,6 +141,10 @@ export type FirebaseEmulatorOptions = {
host: string;
port: number;
};
storage?: {
host: string;
port: number;
};
hub?: {
host: string;
port: number;
Expand Down Expand Up @@ -193,6 +205,7 @@ export function apps(): firebase.app.App[] {
export type AppOptions = {
databaseName?: string;
projectId?: string;
storageBucket?: string;
auth?: TokenOptions;
};
/** Construct an App authenticated with options.auth. */
Expand All @@ -201,19 +214,20 @@ export function initializeTestApp(options: AppOptions): firebase.app.App {
? createUnsecuredJwt(options.auth, options.projectId)
: undefined;

return initializeApp(jwt, options.databaseName, options.projectId);
return initializeApp(jwt, options.databaseName, options.projectId, options.storageBucket);
}

export type AdminAppOptions = {
databaseName?: string;
projectId?: string;
storageBucket?: string;
};
/** Construct an App authenticated as an admin user. */
export function initializeAdminApp(options: AdminAppOptions): firebase.app.App {
const admin = require('firebase-admin');

const app = admin.initializeApp(
getAppOptions(options.databaseName, options.projectId),
getAppOptions(options.databaseName, options.projectId, options.storageBucket),
getRandomAppName()
);

Expand Down Expand Up @@ -248,6 +262,10 @@ export function useEmulators(options: FirebaseEmulatorOptions): void {
_firestoreHost = getAddress(options.firestore.host, options.firestore.port);
}

if (options.storage) {
_storageHost = getAddress(options.storage.host, options.storage.port);
}

if (options.hub) {
_hubHost = getAddress(options.hub.host, options.hub.port);
}
Expand Down Expand Up @@ -301,6 +319,13 @@ export async function discoverEmulators(
};
}

if (data.storage) {
options.storage = {
host: data.storage.host,
port: data.storage.port
};
}

if (data.hub) {
options.hub = {
host: data.hub.host,
Expand Down Expand Up @@ -351,6 +376,22 @@ function getFirestoreHost() {
return _firestoreHost;
}

function getStorageHost() {
if (!_storageHost) {
const fromEnv = process.env[STORAGE_ADDRESS_ENV];
if (fromEnv) {
_storageHost = fromEnv;
} else {
console.warn(
`Warning: ${STORAGE_ADDRESS_ENV} not set, using default value ${STORAGE_ADDRESS_DEFAULT}`
);
_storageHost = STORAGE_ADDRESS_DEFAULT;
}
}

return _storageHost;
}

function getHubHost() {
if (!_hubHost) {
const fromEnv = process.env[HUB_HOST_ENV];
Expand All @@ -367,34 +408,53 @@ function getHubHost() {
return _hubHost;
}

function parseHost(host: string): { hostname: string, port: number } {
const u = new URL(host);
return {
hostname: u.hostname,
port: Number.parseInt(u.port, 10)
}
}

function getRandomAppName(): string {
return 'app-' + new Date().getTime() + '-' + Math.random();
}

function getDatabaseUrl(databaseName: string) {
return `http://${getDatabaseHost()}?ns=${databaseName}`;
}

function getAppOptions(
databaseName?: string,
projectId?: string
projectId?: string,
storageBucket?: string,
): { [key: string]: string } {
let appOptions: { [key: string]: string } = {};

if (databaseName) {
appOptions[
'databaseURL'
] = `http://${getDatabaseHost()}?ns=${databaseName}`;
] = getDatabaseUrl(databaseName);
}

if (projectId) {
appOptions['projectId'] = projectId;
}

if (storageBucket) {
appOptions['storgeBucket'] = storageBucket;
}

return appOptions;
}

function initializeApp(
accessToken?: string,
databaseName?: string,
projectId?: string
projectId?: string,
storageBucket?: string,
): firebase.app.App {
const appOptions = getAppOptions(databaseName, projectId);
const appOptions = getAppOptions(databaseName, projectId, storageBucket);
const app = firebase.initializeApp(appOptions, getRandomAppName());
if (accessToken) {
const mockAuthComponent = new Component(
Expand All @@ -417,17 +477,22 @@ function initializeApp(
);
}
if (databaseName) {
const { hostname, port } = parseHost(getDatabaseHost());
app.database().useEmulator(hostname, port);

// Toggle network connectivity to force a reauthentication attempt.
// This mitigates a minor race condition where the client can send the
// first database request before authenticating.
app.database().goOffline();
app.database().goOnline();
}
if (projectId) {
app.firestore().settings({
host: getFirestoreHost(),
ssl: false
});
const { hostname, port } = parseHost(getFirestoreHost());
app.firestore().useEmulator(hostname, port);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Moving to consistently use useEmulator across the board.

}
if (storageBucket) {
const { hostname, port } = parseHost(getStorageHost());
app.storage().useEmulator(hostname, port);
}
/**
Mute warnings for the previously-created database and whatever other
Expand Down Expand Up @@ -498,6 +563,39 @@ export async function loadFirestoreRules(
}
}

export type LoadStorageRulesOptions = {
storageBucket: string;
rules: string;
};
export async function loadStorageRules(
options: LoadStorageRulesOptions
): Promise<void> {
if (!options.storageBucket) {
throw new Error('storageBucket not specified');
}

if (!options.rules) {
throw new Error('must provide rules to loadStorageRules');
}

// TODO: This endpoint is not yet implemented! Will need a change in firebase-tools
// to make this real.
const resp = await requestPromise(request.put, {
method: 'PUT',
uri: `http://${getStorageHost()}/internal/setRules`,
body: JSON.stringify({
storageBucket: options.storageBucket,
rules: {
files: [{ content: options.rules }]
}
})
});

if (resp.statusCode !== 200) {
throw new Error(JSON.parse(resp.body.error));
}
}

export type ClearFirestoreDataOptions = {
projectId: string;
};
Expand Down
4 changes: 4 additions & 0 deletions packages/rules-unit-testing/test/database.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,10 @@ describe('Testing Module Tests', function () {
host: 'localhost',
port: 9003
},
storage: {
host: 'localhost',
port: 9199
},
hub: {
host: 'localhost',
port: 4400
Expand Down