Skip to content

App Check (Desktop): Support CLI-provisioned debug tokens and 403 recovery hints - #1957

Merged
AustinBenoit merged 15 commits into
mainfrom
feat/appcheck-seamless-debug-tokens
Nov 16, 2026
Merged

AustinBenoit merged 15 commits into
mainfrom
feat/appcheck-seamless-debug-tokens

Conversation

@AustinBenoit

@AustinBenoit AustinBenoit commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Description

Implements the C++ Desktop SDK portion of SDK/CLI Seamless Debug Tokens:

  1. Token Resolution Order in ResolveDebugToken():
    • Explicit programmatic override via DebugAppCheckProviderFactory::SetDebugToken()
    • Environment variables (FIREBASE_APPCHECK_DEBUG_TOKEN, falling back to AppCheckDebugToken and APP_CHECK_DEBUG_TOKEN)
    • Host Configstore JSON (~/.config/configstore/firebase-appcheck.json and $XDG_CONFIG_HOME/configstore/firebase-appcheck.json), parsed via firebase::util::JsonToVariant for tokens[app->options().app_id()]
    • Auto-generated UUID fallback (with console warning messages split across multiple LogWarning calls to stay under the 511-char buffer limit in app/src/log.cc)
  2. Development-Only & Diagnostic Logging:
    • Logs a development-only warning whenever DebugAppCheckProviderFactory is used while still supporting host configstore resolution on Desktop.
    • Logs source attribution ([FirebaseAppCheck] Debug token loaded from ...), setup diagnostics when the config file exists but lacks the current app_id or fails JSON parsing, and an actionable recovery hint when the backend returns HTTP 403 (Run 'firebase appcheck:debugtokens:create --force' to provision a new token.).

Testing

  • Added Desktop unit test suite firebase_app_check_test (app_check/tests/desktop/debug_provider_desktop_test.cc) covering token resolution precedence, configstore edge cases, development-only warning, and HTTP 403 recovery hint scenarios (passing via CTest).

Type of Change

Place an x the applicable box:

  • Bug fix. Add the issue # below if applicable.
  • New feature. A non-breaking change which adds functionality.
  • Other, such as a build process or documentation change.

@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 updates the Firebase App Check Desktop Debug Provider to automatically load CLI-provisioned debug tokens from the local configstore JSON file and environment variables, and adds unit tests to verify this behavior. The review feedback identifies a critical AB-BA deadlock risk during the destruction of DebugAppCheckProviderFactoryInternal and App on different threads, which can be resolved by releasing the factory lock before unregistering and deleting providers. Additionally, it is recommended to return std::string by value instead of const std::string& in DetermineDebugToken() to prevent potential thread-safety issues with the mutex-protected member variable.

@AustinBenoit

Copy link
Copy Markdown
Contributor Author

/gemini review

@AustinBenoit
AustinBenoit marked this pull request as ready for review November 10, 2026 13:38

@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 enhances the Firebase App Check Debug Provider for desktop platforms by automating the loading of CLI-provisioned debug tokens from standard configuration paths and environment variables. It also improves error handling by logging actionable recovery hints when a token is rejected (HTTP 403) and adds comprehensive unit tests. The review identified several critical areas for improvement, including adding a null pointer check for the app object, correcting the Windows configuration path to include %LOCALAPPDATA%, improving reliability of file I/O error checking, and ensuring safe string access when parsing JSON tokens.

// environment is read and files are opened through the UTF-16 APIs. A failed
// conversion yields an empty string instead of throwing.
using Utf8Utf16Converter =
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>;

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.

and std::wstring_convert are apparently deprecated in C++17, which will make this spit out warnings.
We already use MultiByteToWideChar / WideCharToMultiByte elsewhere, which might work better.

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.

Switched to MultiByteToWideChar / WideCharToMultiByte (CP_UTF8) and removed <codecvt> / std::wstring_convert.

AustinBenoit added a commit that referenced this pull request Nov 13, 2026
…ug warning

- Replace deprecated C++17 <codecvt>/std::wstring_convert with Win32
  MultiByteToWideChar and WideCharToMultiByte (CP_UTF8).
- Replace MSVC-specific std::ifstream(const std::wstring&) with _wfopen on
  Windows and std::fopen elsewhere so MinGW/libstdc++ builds cleanly and
  errno reporting is reliable.
- Log the DebugAppCheckProviderFactory development-only warning
  unconditionally without claiming an NDEBUG/Release app build.
…nd tests

Production:
- Fix SetDebugToken() ordering so a token set after CreateProvider() but
  before the first GetToken() is honored (provider consults the factory).
- Fix ~DebugAppCheckProvider() to shut down the scheduler worker before
  tearing down curl/rest, and remove the ABBA lock-order inversion between
  the factory mutex and CleanupNotifier in CreateProvider/RemoveProviderForApp.
- Fall back across all candidate configstore paths (XDG_CONFIG_HOME when
  absolute, USERPROFILE on Windows, HOME) and strip a UTF-8 BOM.
- Log the resolved configstore path in the source-attribution message;
  keep the design-mandated diagnostics (missing app ID, parse/IO errors,
  ENOENT silent, 403 recovery hint) while removing redundant logging.
- Android/iOS: SetDebugToken() also sets/unsets FIREBASE_APPCHECK_DEBUG_TOKEN
  and AppCheckDebugToken so the explicit value is priority #1; log the
  NDEBUG warning on CreateProvider. Revert the Java apply()->commit()
  change (blocking disk write with no same-process benefit).
- Remove test-only release-build simulation hooks and unused helpers.

Tests:
- Rewrite debug_provider_desktop_test.cc using std::filesystem and three
  focused tests (priority order, configstore edge cases, live exchange +
  403) with a compact log oracle for the design-doc log contracts; fail
  fast on callback timeout; use '/'-joined expected paths so the
  attribution assertion is portable to Windows.
- Remove duplicate add_test() in app_check/tests/CMakeLists.txt.
…ory model

Drop the CleanupNotifier registration, RemoveProviderForApp(), the
provider->factory back-pointer, GetDebugToken(), and the factory mutex.
None of it is required by the design, and neither the Android nor iOS
factories do any of it: providers live in the factory map until the
singleton is destroyed, and SetDebugToken() is snapshotted when the
provider is created. The async exchange never dereferences App* after
scheduling, so there is no dangling-pointer hazard to defend against.

Keep the per-provider token_mutex_ (GetToken() is reached from other
SDKs' worker threads via the function registry) and the scheduler
shutdown ordering fix in the destructor.

Tests updated so SetDebugToken() precedes CreateProvider() (the
supported ordering) and the exchange test constructs its provider
directly rather than through the factory cache.
The Android App Check SDK never consults process environment variables
(InternalDebugSecretProvider -> injected resource -> SharedPreferences ->
UUID), so setting FIREBASE_APPCHECK_DEBUG_TOKEN / AppCheckDebugToken from
the C++ factory had no effect. SetDebugToken() is back to the pre-existing
behavior of storing the token for JniAppCheckDebugHelper at CreateProvider().

iOS keeps its setenv(): the iOS SDK documents AppCheckDebugToken as an
environment-variable source, which is how an explicit C++ SetDebugToken()
outranks a configstore/injected token there.
The CLI neither writes a BOM nor accepts one (JSON.parse rejects it), so
the SDK should not be more lenient than the tool that owns the file. A
BOM-prefixed file now logs the same parse warning and falls back.
…uard

The desktop factory ctor/dtor/CreateProvider/SetDebugToken are now
byte-identical to main (the null guard was redundant with
AppCheckInternal::GetProvider()). The auto-generated-token warning keeps
its original wording and is only split across LogWarning calls so each
piece fits log.cc's 512-byte buffer instead of being truncated.
DebugAppCheckProvider is only constructed by CreateProvider(), which is
only reached from AppCheckInternal::GetProvider() after it has checked
app_. AppOptions accessors return c_str() and are never null.
Resolve debug_token_ as a const member during provider construction via
ResolveDebugToken(), matching the Android and iOS debug providers. This
eliminates token_mutex_, logged_token_, and the DetermineDebugToken()
mutation path on GetTokenInternal(), making it obvious that GetToken()
reuses the immutable token.
lint_commenter.py already disables cpplint's build/c++11 check, and
cpplint 1.5.5 does not flag <filesystem>.
- tests/CMakeLists.txt: remove the firebase_app_check_desktop_test custom
  target (nothing references it) and -DFIREBASE_TESTING (only gates
  friend declarations in remote_config/heartbeat headers this test does
  not include).
- debug_provider_desktop.cc: call JsonToVariant() directly; the leading
  '{' pre-check was redundant with the is_map() check that follows.
- Test: drop an assertion that compared a const member with itself.
Unrelated to this change; the sibling provider factories have no such
guard.
USERPROFILE / HOME / XDG_CONFIG_HOME can contain characters outside the
ANSI code page. Read them with _wgetenv and open the file with a wide
path, converting to and from UTF-8 with wstring_convert as
app_desktop.cc and heartbeat_storage_desktop.cc already do. Conversion
failures yield an empty string rather than throwing.
…ug warning

- Replace deprecated C++17 <codecvt>/std::wstring_convert with Win32
  MultiByteToWideChar and WideCharToMultiByte (CP_UTF8).
- Replace MSVC-specific std::ifstream(const std::wstring&) with _wfopen on
  Windows and std::fopen elsewhere so MinGW/libstdc++ builds cleanly and
  errno reporting is reliable.
- Log the DebugAppCheckProviderFactory development-only warning
  unconditionally without claiming an NDEBUG/Release app build.
@AustinBenoit
AustinBenoit force-pushed the feat/appcheck-seamless-debug-tokens branch from 2bd1c9b to ffae07e Compare November 13, 2026 20:46
@AustinBenoit
AustinBenoit merged commit f916970 into main Nov 16, 2026
39 checks passed
@github-actions github-actions Bot added the tests: in-progress This PR's integration tests are in progress. label Nov 16, 2026
@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

✅  Integration test succeeded!

Requested by @AustinBenoit on commit f916970
Last updated: Mon Nov 16 14:22 PST 2026
View integration test log & download artifacts

@github-actions github-actions Bot added the tests: succeeded This PR's integration tests succeeded. label Nov 16, 2026
@firebase-workflow-trigger firebase-workflow-trigger Bot removed the tests: in-progress This PR's integration tests are in progress. label Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tests: succeeded This PR's integration tests succeeded.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants