Sub topic 11
Why compile-time values are not secrets
This chapter assumes you can run flutter build from the command line, know how --dart-define and String.fromEnvironment work, and have an AppConfig class like the one built earlier in this tutorial. It explains why anything compiled into your app can be read by someone who has the app, and what to do instead.
The mistake
--dart-define is convenient. You pass a value on the command line or from a JSON file, and it appears in your app as a constant. That convenience makes it tempting to put every setting there, including an API key, a database password, or a signing token.
Compile-time does not mean hidden. It means the value is fixed when the app is built. Fixing a value into the app and hiding it from the app's users are different things.
{
"API_BASE_URL": "https://api.example.com",
"PAYMENT_SECRET_KEY": "sk_live_do_not_ship_this"
}The second entry is the problem. After the build, PAYMENT_SECRET_KEY is a string inside the binary that you hand to every user.
What happens to a defined value
String.fromEnvironment is resolved by the compiler. When it sees a constant call, it substitutes the value given with --dart-define and writes the result into the compiled program. The running app does not read an environment variable, and nothing is looked up at startup.
For the earlier AppConfig, the compiled app contains the literal text of the URL, as if you had typed it in the source file.
class AppConfig {
const AppConfig({required this.apiBaseUrl, required this.apiKey});
final String apiBaseUrl;
final String apiKey;
static const AppConfig fromEnvironment = AppConfig(
apiBaseUrl: String.fromEnvironment('API_BASE_URL'),
apiKey: String.fromEnvironment('API_KEY'),
);
}If you build with --dart-define=API_KEY=abc123, the string abc123 is stored in the app's data. Anyone who can obtain the app file can search for it.
How a value is extracted
You do not need special skills to read compiled strings. The steps are short.
- Download the APK or app bundle from a store, or copy it from a device.
- Unpack it. An APK is a ZIP archive, so any unzip tool opens it.
- Locate the compiled Dart code. On Android, release builds put it in
lib/<abi>/libapp.so. On iOS, it is in theApp.frameworkbinary. - Run a strings search on that file.
unzip -o app-release.apk -d extracted
strings extracted/lib/arm64-v8a/libapp.so | grep -i "abc123"The key shows up in the output. Release builds compile Dart ahead of time to machine code, but string constants stay as readable data. Even where a string is stored in a less obvious way, a determined person can attach a debugger or watch network traffic and see the value when the app uses it.
A key sent in an HTTP header can also be read from the network without opening the app at all. A person can route their phone through a proxy tool and read each request. HTTPS protects the data from third parties on the network. It does not protect it from the device owner, who can install their own certificate.
Because the exact diagram syntax matters, the diagram below uses the required fence.
Obfuscation does not fix it
Flutter can obfuscate Dart code with --obfuscate and --split-debug-info. This renames classes, functions, and variables so stack traces and reverse engineering are harder.
flutter build apk --release --obfuscate --split-debug-info=build/symbolsObfuscation changes identifiers. It does not encrypt string constants. The API key is still a string in the binary. You can also encode a key (for example in base64) or split it into pieces, but the app must rebuild the real value to use it. Anyone can watch for that moment or repeat the same steps. This only slows an attacker by a small amount, and it gives you a false sense of safety.
What is safe to put in compile-time values
Not every config value is sensitive. The rule is to ask what happens if a stranger reads it.
| Value | Safe as a compile-time value? | Reason |
|---|---|---|
| API base URL | Yes | The app must contact it, and the server is public anyway. |
| Feature flag such as `ENABLE_LOGGING` | Yes | Reveals nothing harmful. |
| Environment name | Yes | Only a label. |
| Analytics or maps client key restricted by app ID | Usually | Designed to be public, and restricted on the provider's side. |
| Firebase client config (API key, project ID) | Yes | Identifies the project. Security comes from backend rules. |
| Payment secret key | No | Allows charging and refunds. |
| Database password | No | Gives direct data access. |
| Private signing key or token | No | Lets someone impersonate your service. |
Some "keys" are public identifiers by design. A Firebase API key is an example. It tells the service which project a request belongs to. Access is controlled by security rules and authentication, not by hiding that key. Check the provider's documentation to see which kind of key you hold.
Where secrets belong
The principle is that a secret should live on a server you control, never on a device you do not control. The app asks your server to do the sensitive work.
There are three common patterns.
- A backend proxy. The app calls your own API. Your server holds the third-party secret and calls the provider for the app. The app never sees the secret.
- User authentication with short-lived tokens. The user signs in, and your server issues a token that expires. The app stores the token, not a master credential. If a token leaks, it works for a short time and for one user.
- Provider-side restrictions. For keys that must be in the client, limit them on the provider's dashboard. Restrict by Android package name and signing certificate, by iOS bundle ID, by allowed APIs, and by quota. A restricted key is much less useful to someone who copies it.
A sketch of the first pattern: the app sends the request to your server, with no third-party key in the app.
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'app_config.dart';
Future<Map<String, dynamic>> createPayment(
AppConfig config,
int amountCents,
String userToken,
) async {
final response = await http.post(
Uri.parse('${config.apiBaseUrl}/payments'),
headers: {
'Authorization': 'Bearer $userToken',
'Content-Type': 'application/json',
},
body: jsonEncode({'amount': amountCents}),
);
if (response.statusCode != 200) {
throw Exception('Payment failed: ${response.statusCode}');
}
return jsonDecode(response.body) as Map<String, dynamic>;
}The userToken identifies the signed-in user and expires. The payment provider's secret key stays on your server, which receives the amount and talks to the provider.
Secrets in the build pipeline
A related question is where the build gets its values. Your CI system can store sensitive values as encrypted secrets and write them into a config file at build time. This keeps them out of the repository. It does not keep them out of the app. Protecting a value in CI protects the repository and the build logs. It does nothing for the finished binary.
Keep these two concerns apart:
- Repository secrecy. Whether the value is visible in Git history and logs. CI secrets and
.gitignorehandle this. - Distribution secrecy. Whether the value is visible to people who install the app. Compile-time configuration cannot provide this.
Failure modes to watch for
- Leaked production key in a dev build. A dev flavor often ships to testers by email or a test platform. If it contains production credentials, many more people can extract them. Give each flavor its own credentials, and give dev and staging flavors only dev and staging resources.
- A key that cannot be rotated. Once an app with a key is published, old versions keep using it. Plan to revoke and replace keys on the server side, and expect old app versions to stop working.
- Debug output. Printing the whole
AppConfigfor logging can write secrets to device logs or crash reports. Print only fields that are safe. - Defaults that hold real values. A
defaultValueinString.fromEnvironmentis compiled into every build that omits the define. Never put a real credential there.
// Avoid: a real credential as a default ends up in every build.
const key = String.fromEnvironment('API_KEY', defaultValue: 'live-key-123');
// Better: an empty default, plus a check that fails early in development.
const safeKey = String.fromEnvironment('API_KEY');
void checkConfig() {
assert(safeKey.isNotEmpty, 'API_KEY was not provided with --dart-define');
}The assert runs only in debug builds. It catches a forgotten define while you develop, and it adds no cost to release builds.
A decision checklist
Before adding a value to --dart-define, ask these questions in order.
- Would it cause harm if a stranger read this value? If yes, it does not belong in the app.
- Is it a public identifier that the provider restricts on its side? If yes, it can go in the app, and you should apply those restrictions.
- Can a server perform the sensitive action instead? If yes, move the secret to the server.
- Does each flavor have its own value, so a leak in one environment does not expose another?
Exercise
A teammate adds --dart-define=STRIPE_SECRET_KEY=sk_live_... to the release build and runs the build with --obfuscate. They say the key is now protected. Explain why this is wrong and describe a safer design.
Show answer
String.fromEnvironment writes the value into the compiled app as a string constant. Obfuscation renames identifiers but does not encrypt strings, so anyone can unpack the app and run a strings search or watch the app's network traffic to read the key. A secret key lets an attacker charge and refund on your account. A safer design keeps the Stripe secret key on your own server. The app sends the amount to your API with a short-lived user token, and the server calls Stripe. If the old key was ever shipped, revoke and replace it.
Exercise
Sort these into "fine as compile-time values" and "must stay on a server": the API base URL, a database password, the environment name, a private token-signing key.
Show answer
Fine as compile-time values: the API base URL and the environment name. Must stay on a server: the database password and the private token-signing key.