[google_cloud] Add project ID discovery from credentials JSON file
google_cloud
# Add project ID discovery from credentials JSON file
## Description
### Problem
`projectIdFromEnvironment()` only checks environment variable values from the `gcpProjectIdEnvironmentVariables` list. It does not read the `project_id` field from the JSON file pointed to by the `GOOGLE_APPLICATION_CREDENTIALS` environment variable.
This means that when developers use a service account JSON file for authentication, the project ID from that file is ignored, requiring them to set an additional environment variable.
### Current Implementation
```dart
String? projectIdFromEnvironment() {
for (var envKey in gcpProjectIdEnvironmentVariables) {
final value = Platform.environment[envKey];
if (value != null) return value;
}
return null;
}
```
### Proposed Solution
Add a new function `projectIdFromCredentialsFile()` that reads the credentials file:
```dart
String? projectIdFromCredentialsFile() {
final path = Platform.environment['GOOGLE_APPLICATION_CREDENTIALS'];
if (path == null) return null;
try {
final json = jsonDecode(File(path).readAsStringSync());
return json['project_id'] as String?;
} catch (e) {
// If file doesn't exist or is invalid, return null
return null;
}
}
```
Then update `computeProjectId()` to check this source:
```dart
Future<String> computeProjectId() async {
// 1. Check environment variables
final envValue = projectIdFromEnvironment();
if (envValue != null) return envValue;
// 2. Check credentials file
final credentialsValue = projectIdFromCredentialsFile();
if (credentialsValue != null) return credentialsValue;
// 3. Check metadata server
return await projectIdFromMetadataServer();
}
```
### Use Case
This provides a more seamless developer experience:
```dart
// Before: Need both credentials file AND project ID env var
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
export GCP_PROJECT="my-project-id" // Redundant!
// After: Just credentials file is enough
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
// project_id is automatically read from the JSON file
```
### References
- Current implementation: [gcp_project.dart](https://github.com/invertase/functions-framework-dart/blob/main/google_cloud/lib/src/gcp_project.dart#L44-L51)
- Related to replacing `googleapis_auth_utils` functionality
关闭于 2026-02-11 0 条评论