Skip to content

feat(hosting): ensure Firebase Hosting API is enabled before deploy and Hosting commands - #11296

Merged
bkendall merged 3 commits into
mainfrom
bk-ensure-hosting-api-enabled
Oct 15, 2026
Merged

bkendall merged 3 commits into
mainfrom
bk-ensure-hosting-api-enabled

Conversation

@bkendall

Copy link
Copy Markdown
Contributor

Description

Ensures that the Firebase Hosting API (firebasehosting.googleapis.com) is enabled on the target project(s) before deploying to Firebase Hosting or running hosting:* CLI commands (hosting:channel:*, hosting:sites:*, hosting:clone, hosting:disable).

Scenarios Tested

  • Unit tests for deploy command .before() hook (src/commands/deploy.spec.ts) and Hosting prepare step (src/deploy/hosting/prepare.spec.ts)
  • Unit tests for hosting:clone same-project and cross-project API enablement (src/commands/hosting-clone.spec.ts) and hosting:disable (src/commands/hosting-disable.spec.ts)

Sample Commands

firebase deploy --only hosting
firebase hosting:sites:list
firebase hosting:channel:deploy preview
firebase hosting:clone source-site:staging target-site:live
firebase hosting:disable

…nd Hosting commands

### Description
Ensures that the Firebase Hosting API (`firebasehosting.googleapis.com`) is enabled on the target project(s) before deploying to Firebase Hosting or running `hosting:*` CLI commands (`hosting:channel:*`, `hosting:sites:*`, `hosting:clone`, `hosting:disable`).

### Scenarios Tested
- Unit tests for `deploy` command `.before()` hook (`src/commands/deploy.spec.ts`) and Hosting `prepare` step (`src/deploy/hosting/prepare.spec.ts`)
- Unit tests for `hosting:clone` same-project and cross-project API enablement (`src/commands/hosting-clone.spec.ts`) and `hosting:disable` (`src/commands/hosting-disable.spec.ts`)

### Sample Commands
```bash
firebase deploy --only hosting
firebase hosting:sites:list
firebase hosting:channel:deploy preview
firebase hosting:clone source-site:staging target-site:live
firebase hosting:disable
```

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request ensures that the Firebase Hosting API is enabled before executing various Hosting commands (such as deploy, clone, disable, and channel/site management) by adding API enablement checks. The feedback suggests optimizing the hosting:clone command by running the API enablement checks concurrently using Promise.all, and refactoring the deploy command unit tests to dynamically locate the hosting hook rather than relying on a fragile hardcoded index.

Comment thread src/commands/hosting-clone.ts Resolved
Comment thread src/commands/deploy.spec.ts Resolved
@bkendall
bkendall marked this pull request as ready for review October 15, 2026 23:06
Comment thread src/commands/deploy.ts
}

if (options.filteredTargets.includes("hosting")) {
await ensure(needProjectId(options), hostingApiOrigin(), "hosting", true);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nit: Do this in the prepare step for hosting instead.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think I have to keep it here. With deferred Hosting, the site may not exist yet, and this is where we check for it. I could (in theory) move this check inside one of the calls here, but... that's fighting about where a single line should go, and this seems okay-ish to me.

Maybe we should push this deferred Hosting logic deeper, but there's dependencies between products I'm unable to think about I'm sure.

@f0urfingeredfish

f0urfingeredfish commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

If you used firebase init hosting:github before #6895 was released (2024-03-26) that added the serviceUsageConsumer grant this change caused a breaking change and 403 for:

"reason": "AUTH_PERMISSION_DENIED",
            "domain": "serviceusage.googleapis.com",
            "metadata": ***
              "service": "serviceusage.googleapis.com",
              "permission": "serviceusage.services.get",

It seems like this package doesn't strictly enforce semantic versioning, but for some consumers, this was a breaking change.

Also these docs are out of date for manually adding a SA for hosting FirebaseExtended/action-hosting-deploy#465

bkendall added a commit that referenced this pull request Nov 10, 2026
…PI is enabled (#11412)

* fix(hosting): warn instead of failing when unable to ensure Hosting API is enabled

### Description

Fixes #11335

Commit `57bb89ee9` (#11296) added hard `ensure(..., hostingApiOrigin(), "hosting", true)` gates across Hosting commands and deploy preparation. Because `ensure()` calls `serviceusage.services.get` (and `serviceusage.services.enable` if uncached/disabled), service accounts and service agents holding only `roles/firebasehosting.admin` or lacking `serviceusage.services.enable` fail with HTTP 403 before reaching `firebasehosting.googleapis.com`.

This change replaces all 15 hard `ensure()` calls for `firebasehosting.googleapis.com` across 13 Hosting files with a shared `hostingApi.ensureApiEnabled(projectId)` helper in `src/hosting/api.ts`:
- Attempts `ensure(projectId, apiUri, "hosting", true)` so users with Service Usage permissions still get automatic Hosting API enablement.
- Catches any error if verification or enablement fails, logs debug details via `logger.debug`, and emits a bold warning via `utils.logLabeledWarning("hosting", clc.bold(...))` with the Cloud Console enablement URL (routing through `logger.warn` so `--json` `stdout` stays valid JSON).
- Deduplicates in-flight and failed checks per `(projectId, apiName)` within a CLI invocation so commands executing both a `.before()` hook and `src/deploy/hosting/prepare.ts` (`deploy`, `hosting:channel:deploy`) do not repeat the failing Service Usage check or emit duplicate warnings.

### Scenarios Tested

- Unit tests in `src/hosting/api.spec.ts` verifying:
  - `ensureApiEnabled` resolves silently when `ensure()` succeeds.
  - `ensureApiEnabled` catches HTTP 403 `PERMISSION_DENIED` and non-`Error` rejections without throwing and emits a single bold warning with the Cloud Console enablement link.
  - Concurrent and sequential checks for the same `(projectId, apiName)` deduplicate to a single `ensure()` call and warning, while tracking distinct projects independently.
- Updated command and deploy preparation unit tests (`src/commands/deploy.spec.ts`, `src/deploy/hosting/prepare.spec.ts`, `src/commands/hosting-clone.spec.ts`, `src/commands/hosting-disable.spec.ts`) and full Hosting/Deploy Mocha test suites (`128 passing`).
- Prettier formatting check (`npx prettier --check`), ESLint (`npm run lint:changed-files` and `npx eslint --config .eslintrc.js --ext .ts,.js src --quiet`), and TypeScript build (`npm run build` and `npm run test:compile`).

### Sample Commands

```bash
firebase deploy --only hosting --project my-project
firebase hosting:channel:deploy preview --project my-project
firebase hosting:sites:list --project my-project
```

* fix(hosting): tailor Service Usage 403 warnings for check vs enable permissions

* feat(init): ensure Firebase Hosting API is enabled during hosting init

### Description

Ensures `firebasehosting.googleapis.com` is checked/enabled on a best-effort basis (via `hostingApi.ensureApiEnabled`) during Hosting initialization flows when a project ID is present:
- `src/init/features/hosting/index.ts` (`askQuestions`): calls `await ensureApiEnabled(setup.projectId)` inside `if (setup.projectId)` after framework redirect/cancellation guards and before checking `getDefaultHostingSite`.
- `src/init/features/hosting/index.ts` (`actuate`): calls `await ensureApiEnabled(setup.projectId)` inside `if (setup.projectId)` after the `redirectToAppHosting` guard so direct `actuate` invocations (such as `firebase_init` MCP tool execution) also ensure the API is enabled. Process-level deduplication in `src/hosting/api.ts` and `configstore` caching in `src/ensureApiEnabled.ts` avoid duplicate RPCs or warnings when both `askQuestions` and `actuate` run.
- `src/init/features/hosting/github.ts` (`initGitHub`): calls `await ensureApiEnabled(setup.projectId)` after validating `projectId` and existing Hosting config so standalone `firebase init hosting:github` runs also ensure the API is enabled.
- `CHANGELOG.md`: adds an entry covering the `firebase init hosting` and `firebase init hosting:github` update.

### Scenarios Tested

- Added and updated unit tests in `src/init/features/hosting/index.spec.ts` and `src/init/features/hosting/github.spec.ts` covering `askQuestions`, `actuate`, and `initGitHub` with and without `projectId`, App Hosting redirect/cancellation guards, and Hosting config sources (`firebase.json` and `featureInfo.hosting`).
- Verified differential RED/GREEN behavior (5 expected failures when temporarily reverting the `ensureApiEnabled` calls; all passing when restored).
- Ran `npx prettier --check`, `./node_modules/eslint/bin/eslint.js --config .eslintrc.js`, `npm run lint:changed-files`, `npm run test:compile`, targeted Mocha suites (141 passing), and full init/hosting/deploy Mocha glob suites (108 passing).

### Sample Commands

```bash
firebase init hosting --project my-project
firebase init hosting:github --project my-project
```

* fix(hosting): expire failed Hosting API checks and skip caching transient errors

### Description

Bounds `failedApiChecks` in `src/hosting/api.ts` so long-lived `firebase mcp` sessions do not permanently suppress `firebasehosting.googleapis.com` enablement checks after transient errors or out-of-band IAM/Console updates:
- Maps `${projectId}:${apiName}` entries in `failedApiChecks` to an expiration timestamp (`FAILED_API_CHECK_TTL_MS = 5 * 60 * 1000`) and evicts expired entries once `Date.now() >= failedUntil`.
- Caches only Service Usage permission errors (`isServiceUsagePermissionError(err)`, HTTP 403 / `PERMISSION_DENIED`) so transient errors (5xx, network errors) can retry immediately on subsequent calls while still deduplicating concurrent in-flight calls and short-window permission warnings.
- Clears any cached failure entry on successful `ensure(...)` completion.
- Updates unit tests in `src/hosting/api.spec.ts` to cover TTL expiration (before and at 5 minutes via `sinon.useFakeTimers()`) and non-caching of transient `500` errors.

### Scenarios Tested

- Verified differential RED/GREEN behavior (2 expected failures when reverting TTL expiration and 403 filtering; all passing when restored).
- Ran Prettier, ESLint, `npm run lint:changed-files`, `npm run test:compile`, `src/hosting/api.spec.ts` (71 passing), targeted Hosting/Init/Deploy Mocha suites (142 passing), and full init/hosting/deploy Mocha glob suites (108 passing).

### Sample Commands

```bash
firebase deploy --only hosting --project my-project
firebase init hosting --project my-project
```

---------

Co-authored-by: Joe Hanley <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants