Skip to content

Commit ffae07e

Browse files
committed
Address PR #1957 review: Win32 UTF-16/file APIs and unconditional debug 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.
1 parent d82aed5 commit ffae07e

4 files changed

Lines changed: 120 additions & 37 deletions

File tree

‎app_check/src/android/debug_provider_android.cc‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -105,12 +105,10 @@ AppCheckProvider* DebugAppCheckProviderFactoryInternal::CreateProvider(
105105
FIREBASE_ASSERT_MESSAGE_RETURN(nullptr, g_methods_cached,
106106
kMethodsNotCachedError);
107107

108-
#if defined(NDEBUG)
109108
firebase::LogWarning(
110-
"[FirebaseAppCheck] DebugAppCheckProviderFactory is in use in a "
111-
"Release build (NDEBUG defined). Debug tokens are for development "
112-
"only; prefer a production provider where one is available.");
113-
#endif
109+
"[FirebaseAppCheck] DebugAppCheckProviderFactory is in use. Debug tokens "
110+
"are for development only; prefer a production provider where one is "
111+
"available.");
114112

115113
// Return the provider if it already exists.
116114
std::map<App*, AppCheckProvider*>::iterator it = created_providers_.find(app);

‎app_check/src/desktop/debug_provider_desktop.cc‎

Lines changed: 103 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,15 @@
1515
#include "app_check/src/desktop/debug_provider_desktop.h"
1616

1717
#include <cerrno>
18-
#include <codecvt>
1918
#include <cstdint>
2019
#include <cstdio>
2120
#include <cstdlib>
22-
#include <fstream>
23-
#include <iterator>
24-
#include <locale>
21+
#include <limits>
2522
#include <map>
2623
#include <memory>
24+
#include <optional>
2725
#include <string>
26+
#include <string_view>
2827
#include <utility>
2928
#include <vector>
3029

@@ -42,6 +41,15 @@
4241
#include "app_check/src/desktop/token_response.h"
4342
#include "firebase/app_check/debug_provider.h"
4443

44+
#if FIREBASE_PLATFORM_WINDOWS
45+
#ifndef WIN32_LEAN_AND_MEAN
46+
#define WIN32_LEAN_AND_MEAN
47+
#endif
48+
#include <windows.h>
49+
50+
#include <cwchar>
51+
#endif // FIREBASE_PLATFORM_WINDOWS
52+
4553
namespace firebase {
4654
namespace app_check {
4755
namespace internal {
@@ -63,18 +71,52 @@ std::string GenerateUuidString() {
6371
}
6472

6573
#if FIREBASE_PLATFORM_WINDOWS
66-
// Windows paths can contain characters outside the ANSI code page, so the
67-
// environment is read and files are opened through the UTF-16 APIs. A failed
68-
// conversion yields an empty string instead of throwing.
69-
using Utf8Utf16Converter =
70-
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>;
74+
// Windows paths and environment variables can contain characters outside the
75+
// ANSI code page, so they are accessed through the UTF-16 APIs. A failed
76+
// conversion yields std::nullopt / an empty string instead of throwing.
77+
std::optional<std::wstring> Utf8ToWide(std::string_view input) {
78+
if (input.empty()) return std::wstring();
79+
if (input.size() > static_cast<size_t>(std::numeric_limits<int>::max())) {
80+
return std::nullopt;
81+
}
82+
const int input_len = static_cast<int>(input.size());
83+
const int wide_len = ::MultiByteToWideChar(
84+
CP_UTF8, MB_ERR_INVALID_CHARS, input.data(), input_len, nullptr, 0);
85+
if (wide_len <= 0) return std::nullopt;
86+
std::wstring output(static_cast<size_t>(wide_len), L'\0');
87+
if (::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, input.data(),
88+
input_len, output.data(), wide_len) != wide_len) {
89+
return std::nullopt;
90+
}
91+
return output;
92+
}
93+
94+
std::string WideToUtf8(std::wstring_view input) {
95+
if (input.empty() ||
96+
input.size() > static_cast<size_t>(std::numeric_limits<int>::max())) {
97+
return "";
98+
}
99+
const int input_len = static_cast<int>(input.size());
100+
const int utf8_len =
101+
::WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, input.data(),
102+
input_len, nullptr, 0, nullptr, nullptr);
103+
if (utf8_len <= 0) return "";
104+
std::string output(static_cast<size_t>(utf8_len), '\0');
105+
if (::WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, input.data(),
106+
input_len, output.data(), utf8_len, nullptr,
107+
nullptr) != utf8_len) {
108+
return "";
109+
}
110+
return output;
111+
}
71112
#endif // FIREBASE_PLATFORM_WINDOWS
72113

73114
std::string GetNonEmptyEnv(const char* name) {
74115
#if FIREBASE_PLATFORM_WINDOWS
75-
Utf8Utf16Converter converter("", L"");
76-
const wchar_t* val = _wgetenv(converter.from_bytes(name).c_str());
77-
return val != nullptr ? converter.to_bytes(val) : "";
116+
std::optional<std::wstring> wide_name = Utf8ToWide(name);
117+
if (!wide_name.has_value() || wide_name->empty()) return "";
118+
const wchar_t* val = _wgetenv(wide_name->c_str());
119+
return val != nullptr ? WideToUtf8(val) : "";
78120
#else
79121
const char* val = std::getenv(name);
80122
return val != nullptr ? std::string(val) : "";
@@ -103,29 +145,66 @@ std::vector<std::string> ResolveConfigstorePaths() {
103145
return paths;
104146
}
105147

148+
struct FileCloser {
149+
void operator()(std::FILE* file) const { std::fclose(file); }
150+
};
151+
106152
} // namespace
107153

108154
std::string ResolveDebugTokenFromConfig(const std::string& config_path,
109155
const std::string& app_id) {
110156
if (config_path.empty() || app_id.empty()) return "";
111-
errno = 0;
112157
#if FIREBASE_PLATFORM_WINDOWS
113-
std::ifstream infile(Utf8Utf16Converter("", L"").from_bytes(config_path),
114-
std::ios::binary);
158+
std::optional<std::wstring> wide_path = Utf8ToWide(config_path);
159+
if (!wide_path.has_value()) {
160+
firebase::LogWarning(
161+
"[FirebaseAppCheck] Failed to convert config path to UTF-16: %s.",
162+
config_path.c_str());
163+
return "";
164+
}
165+
errno = 0;
166+
std::unique_ptr<std::FILE, FileCloser> file(
167+
_wfopen(wide_path->c_str(), L"rb"));
115168
#else
116-
std::ifstream infile(config_path.c_str(), std::ios::binary);
169+
errno = 0;
170+
std::unique_ptr<std::FILE, FileCloser> file(
171+
std::fopen(config_path.c_str(), "rb"));
117172
#endif // FIREBASE_PLATFORM_WINDOWS
118-
if (!infile.is_open()) {
173+
if (!file) {
174+
const int open_errno = errno;
119175
// ENOENT (file not created yet) stays silent so apps not using the CLI
120176
// flow do not log errors; other I/O failures are surfaced.
121-
if (errno != 0 && errno != ENOENT) {
177+
if (open_errno != 0 && open_errno != ENOENT) {
122178
firebase::LogWarning("[FirebaseAppCheck] Failed to open %s (errno=%d).",
123-
config_path.c_str(), errno);
179+
config_path.c_str(), open_errno);
124180
}
125181
return "";
126182
}
127-
std::string json_str((std::istreambuf_iterator<char>(infile)),
128-
std::istreambuf_iterator<char>());
183+
184+
// Cap reads so a corrupted or unexpected file cannot exhaust memory.
185+
constexpr size_t kMaxConfigBytes = 1024 * 1024;
186+
std::string json_str;
187+
char buffer[4096];
188+
while (true) {
189+
const size_t bytes_read = std::fread(buffer, 1, sizeof(buffer), file.get());
190+
if (bytes_read > 0) {
191+
if (json_str.size() + bytes_read > kMaxConfigBytes) {
192+
firebase::LogWarning(
193+
"[FirebaseAppCheck] Config file %s exceeds %zu bytes.",
194+
config_path.c_str(), kMaxConfigBytes);
195+
return "";
196+
}
197+
json_str.append(buffer, bytes_read);
198+
}
199+
if (bytes_read < sizeof(buffer)) {
200+
if (std::ferror(file.get()) != 0) {
201+
firebase::LogWarning("[FirebaseAppCheck] Failed to read %s.",
202+
config_path.c_str());
203+
return "";
204+
}
205+
break;
206+
}
207+
}
129208
size_t start = json_str.find_first_not_of(" \t\r\n");
130209
if (start == std::string::npos) return "";
131210

@@ -163,12 +242,10 @@ namespace {
163242
// 3. Local configstore (~/.config/configstore/firebase-appcheck.json)
164243
// 4. Auto-generated UUID
165244
std::string ResolveDebugToken(App* app, const std::string& explicit_token) {
166-
#if defined(NDEBUG)
167245
firebase::LogWarning(
168-
"[FirebaseAppCheck] DebugAppCheckProviderFactory is in use in a "
169-
"Release build (NDEBUG defined). Debug tokens are for development "
170-
"only; prefer a production provider where one is available.");
171-
#endif // defined(NDEBUG)
246+
"[FirebaseAppCheck] DebugAppCheckProviderFactory is in use. Debug tokens "
247+
"are for development only; prefer a production provider where one is "
248+
"available.");
172249

173250
// 1. Explicit token passed in from SetDebugToken() at provider creation.
174251
if (!explicit_token.empty()) {

‎app_check/src/ios/debug_provider_ios.mm‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,11 +93,9 @@ virtual void GetLimitedUseToken(
9393
}
9494

9595
AppCheckProvider* DebugAppCheckProviderFactoryInternal::CreateProvider(App* app) {
96-
#if defined(NDEBUG)
97-
firebase::LogWarning("[FirebaseAppCheck] DebugAppCheckProviderFactory is in use in a "
98-
"Release build (NDEBUG defined). Debug tokens are for development "
99-
"only; prefer a production provider where one is available.");
100-
#endif
96+
firebase::LogWarning("[FirebaseAppCheck] DebugAppCheckProviderFactory is in use. Debug tokens "
97+
"are for development only; prefer a production provider where one is "
98+
"available.");
10199
// Return the provider if it already exists.
102100
std::map<App*, AppCheckProvider*>::iterator it = created_providers_.find(app);
103101
if (it != created_providers_.end()) {

‎app_check/tests/desktop/debug_provider_desktop_test.cc‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,8 +178,13 @@ class DebugProviderDesktopTest : public ::testing::Test {
178178
};
179179

180180
TEST_F(DebugProviderDesktopTest, ResolutionPriorityOrder) {
181-
// 4. Default fallback: auto-generated 36-char UUID.
181+
// 4. Default fallback: auto-generated 36-char UUID, plus unconditional
182+
// development-only warning.
182183
EXPECT_EQ(DebugAppCheckProvider(app_, "").debug_token().size(), 36u);
184+
EXPECT_TRUE(LogContains(
185+
"[FirebaseAppCheck] DebugAppCheckProviderFactory is in use. Debug tokens "
186+
"are for development only; prefer a production provider where one is "
187+
"available."));
183188

184189
// 3. Configstore in HOME (~/.config/configstore/firebase-appcheck.json).
185190
WriteHomeConfigstore(std::string("{\"tokens\":{\"") + kTestAppId +
@@ -233,6 +238,11 @@ TEST_F(DebugProviderDesktopTest, ResolveDebugTokenFromConfigEdgeCases) {
233238
"");
234239
EXPECT_FALSE(LogContains("[FirebaseAppCheck]")) << logs_;
235240

241+
// Non-ENOENT I/O failure (e.g. opening/reading a directory) logs a warning.
242+
ClearLogs();
243+
EXPECT_EQ(ResolveDebugTokenFromConfig(temp_dir_.string(), kTestAppId), "");
244+
EXPECT_TRUE(LogContains("[FirebaseAppCheck]")) << logs_;
245+
236246
// File exists but lacks the target app ID -> diagnostic info log.
237247
std::string path =
238248
WriteHomeConfigstore("{\"tokens\":{\"1:000:web:other\":\"tok\"}}");

0 commit comments

Comments
 (0)