Skip to content

Implement support for demo project ID namespace #3291

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
Apr 21, 2021
Merged
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 CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
- Include `appId` in web app configuration when using the Hosting emulator (#2798).
- Add support for emulating the `demo-*` project ID namespace with fake Admin and Web SDK configurations (#3291).
8 changes: 7 additions & 1 deletion src/emulator/adminSdkConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as apiv2 from "../apiv2";
import { configstore } from "../configstore";
import { FirebaseError } from "../error";
import { logger } from "../logger";
import { Constants } from "./constants";

export type AdminSdkConfig = {
projectId: string;
Expand Down Expand Up @@ -33,6 +34,11 @@ export function constructDefaultAdminSdkConfig(projectId: string): AdminSdkConfi
export async function getProjectAdminSdkConfigOrCached(
projectId: string
): Promise<AdminSdkConfig | undefined> {
// When using the emulators with a fake project Id, use a fake project config.
if (Constants.isDemoProject(projectId)) {
return constructDefaultAdminSdkConfig(projectId);
}

try {
const config = await getProjectAdminSdkConfig(projectId);
setCacheAdminSdkConfig(projectId, config);
Expand All @@ -46,7 +52,7 @@ export async function getProjectAdminSdkConfigOrCached(
/**
* Gets the Admin SDK configuration associated with a project.
*/
export async function getProjectAdminSdkConfig(projectId: string): Promise<AdminSdkConfig> {
async function getProjectAdminSdkConfig(projectId: string): Promise<AdminSdkConfig> {
const apiClient = new apiv2.Client({
auth: true,
apiVersion: "v1beta1",
Expand Down
8 changes: 8 additions & 0 deletions src/emulator/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ export const EMULATOR_DESCRIPTION: Record<Emulators, string> = {
const DEFAULT_HOST = "localhost";

export class Constants {
// GCP projects cannot start with 'demo' so we use 'demo-' as a prefix to denote
// an intentionally fake project.
static FAKE_PROJECT_ID_PREFIX = "demo-";

static DEFAULT_DATABASE_EMULATOR_NAMESPACE = "fake-server";

// Environment variable to override SDK/CLI to point at the Firestore emulator.
Expand Down Expand Up @@ -124,4 +128,8 @@ export class Constants {
const u = url.parse(normalized);
return u.hostname || DEFAULT_HOST;
}

static isDemoProject(projectId?: string): boolean {
return !!projectId && projectId.startsWith(this.FAKE_PROJECT_ID_PREFIX);
}
}
24 changes: 14 additions & 10 deletions src/emulator/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,19 +327,23 @@ export async function startAll(options: any, showUI: boolean = true): Promise<vo
const targets = filterEmulatorTargets(options);
options.targets = targets;

const projectId: string | undefined = getProjectId(options, true);

if (targets.length === 0) {
throw new FirebaseError(
`No emulators to start, run ${clc.bold("firebase init emulators")} to get started.`
);
}
const hubLogger = EmulatorLogger.forEmulator(Emulators.HUB);
hubLogger.logLabeled("BULLET", "emulators", `Starting emulators: ${targets.join(", ")}`);

const projectId: string | undefined = getProjectId(options, true);
if (Constants.isDemoProject(projectId)) {
hubLogger.logLabeled(
"BULLET",
"emulators",
`Detected demo project ID "${projectId}", emulated services will use a demo configuration and attempts to access non-emulated services for this project will fail.`
);
}

EmulatorLogger.forEmulator(Emulators.HUB).logLabeled(
"BULLET",
"emulators",
`Starting emulators: ${targets.join(", ")}`
);
const onlyOptions: string = options.only;
if (onlyOptions) {
const requested: string[] = onlyOptions.split(",").map((o) => {
Expand Down Expand Up @@ -385,7 +389,7 @@ export async function startAll(options: any, showUI: boolean = true): Promise<vo
if (foundMetadata) {
exportMetadata = foundMetadata;
} else {
EmulatorLogger.forEmulator(Emulators.HUB).logLabeled(
hubLogger.logLabeled(
"WARN",
"emulators",
`Could not find import/export metadata file, ${clc.bold("skipping data import!")}`
Expand Down Expand Up @@ -418,7 +422,7 @@ export async function startAll(options: any, showUI: boolean = true): Promise<vo
const emulatorsNotRunning = ALL_SERVICE_EMULATORS.filter((e) => {
return e !== Emulators.FUNCTIONS && !shouldStart(options, e);
});
if (emulatorsNotRunning.length > 0) {
if (emulatorsNotRunning.length > 0 && !Constants.isDemoProject(projectId)) {
functionsLogger.logLabeled(
"WARN",
"functions",
Expand Down Expand Up @@ -652,7 +656,7 @@ export async function startAll(options: any, showUI: boolean = true): Promise<vo
}

if (showUI && !shouldStart(options, Emulators.UI)) {
EmulatorLogger.forEmulator(Emulators.HUB).logLabeled(
hubLogger.logLabeled(
"WARN",
"emulators",
"The Emulator UI requires a project ID to start. Configure your default project with 'firebase use' or pass the --project flag."
Expand Down
19 changes: 19 additions & 0 deletions src/fetchWebSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { configstore } from "./configstore";
import { firebaseApiOrigin, hostingApiOrigin } from "./api";
import * as getProjectId from "./getProjectId";
import { logger } from "./logger";
import { Constants } from "./emulator/constants";

export interface WebConfig {
projectId: string;
Expand Down Expand Up @@ -76,6 +77,19 @@ async function listAllSites(projectId: string, nextPageToken?: string): Promise<
return sites;
}

/**
* Construct a fake configuration based on the project ID.
*/
function constructDefaultWebSetup(projectId: string): WebConfig {
return {
projectId,
databaseURL: `https://${projectId}.firebaseio.com`,
storageBucket: `${projectId}.appspot.com`,
apiKey: "fake-api-key",
authDomain: `${projectId}.firebaseapp.com`,
};
}

/**
* TODO: deprecate this function in favor of `getAppConfig()` in `/src/management/apps.ts`
* @param options CLI options.
Expand All @@ -84,6 +98,11 @@ async function listAllSites(projectId: string, nextPageToken?: string): Promise<
export async function fetchWebSetup(options: any): Promise<WebConfig> {
const projectId = getProjectId(options, false);

// When using the emulators with a fake project ID, use a fake web config
if (Constants.isDemoProject(projectId)) {
return constructDefaultWebSetup(projectId);
}

// Try to determine the appId from the default Hosting site, if it is linked.
let hostingAppId: string | undefined = undefined;
try {
Expand Down
15 changes: 15 additions & 0 deletions src/test/emulators/adminSdkConfig.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { expect } from "chai";
import { getProjectAdminSdkConfigOrCached } from "../../emulator/adminSdkConfig";

describe("adminSdkConfig", () => {
describe("getProjectAdminSdkConfigOrCached", () => {
it("should return a fake config for a demo project id", async () => {
const projectId = "demo-project-1234";
await expect(getProjectAdminSdkConfigOrCached(projectId)).to.eventually.deep.equal({
projectId: "demo-project-1234",
databaseURL: "https://demo-project-1234.firebaseio.com",
storageBucket: "demo-project-1234.appspot.com",
});
});
});
});
11 changes: 11 additions & 0 deletions src/test/fetchWebSetup.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,17 @@ describe("fetchWebSetup module", () => {
"Not Found"
);
});

it("should return a fake config for a demo project id", async () => {
const projectId = "demo-project-1234";
await expect(fetchWebSetup({ project: projectId })).to.eventually.deep.equal({
projectId: "demo-project-1234",
databaseURL: "https://demo-project-1234.firebaseio.com",
storageBucket: "demo-project-1234.appspot.com",
apiKey: "fake-api-key",
authDomain: "demo-project-1234.firebaseapp.com",
});
});
});

describe("getCachedWebSetup", () => {
Expand Down