Skip to content

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

Merged
bkendall merged 5 commits into
mainfrom
revert_hosting_api_check
Nov 10, 2026
Merged

bkendall merged 5 commits into
mainfrom
revert_hosting_api_check

Conversation

@bkendall

@bkendall bkendall commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

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

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

…PI 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
```

@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 introduces a new ensureApiEnabled helper in src/hosting/api.ts to perform a best-effort check for the Firebase Hosting API. Instead of failing when the check fails (e.g., due to missing Service Usage permissions), it logs a warning and allows the command to proceed. All hosting-related commands and deployment preparation steps have been updated to use this new helper, simplifying their imports and API enablement checks. Unit tests have also been added to verify the behavior, deduplication, and error handling of this new helper. I have no feedback to provide as there are no review comments.

@joehan
joehan self-requested a review November 3, 2026 18:46
### 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
```
…ient 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
```
@bkendall
bkendall merged commit 87c3636 into main Nov 10, 2026
41 checks passed
@bkendall
bkendall deleted the revert_hosting_api_check branch November 10, 2026 18:55
opatry added a commit to opatry/my-bookshelf that referenced this pull request Nov 10, 2026
15.34.1 added a Hosting API enablement preflight that calls
serviceusage.googleapis.com, which needs serviceusage.services.get. The
deploy service account does not have it, so 'firebase deploy --only
hosting' fails with 403 (run 42925237127).

Upstream fixed it in firebase/firebase-tools#11412 (warn instead of fail)
but that is not released yet. 15.34.0 is the last version without the
preflight; its hosting deploy path only differs from 15.22.3 by passing
projectId to createVersion. Same npm audit result as 15.35.0.

Revisit once the fix ships: then bump and restore a caret range.
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.

hosting:channel:deploy fails with 403 on serviceusage.services.get since v15.34.1

2 participants