Skip to Content
Course content

248: Handling Secrets in Kotlin Applications

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this happen in countless code reviews: a developer proudly points to their .gitignore file and says, "Don't worry, I put the API keys in a secrets.properties file, so they'll never be pushed to GitHub."

The "GitIgnore" Security Blanket

The misconception is that keeping a secret out of version control is the same thing as securing it. It's not. While ignoring a file prevents you from accidentally leaking your credentials to the entire internet, it does absolutely nothing to protect that secret once the application is compiled and deployed.

Let's look at a concrete example. Imagine you're using a service like SendGrid to send emails and you've done the "safe" thing by putting your key in a local file that Gradle reads to inject a constant into your code:

// This looks safe because the value comes from a local property file
val sendGridKey = BuildConfig.SENDGRID_API_KEY 

Here is the reality: BuildConfig constants are compiled directly into the Java bytecode as plain-text strings. If I get a hold of your compiled .jar or .apk, I don't need your source code. I can run a simple decompiler or even use strings on the binary, and your "secret" key will pop out in plain text. I've recovered "hidden" production keys from professional apps in about thirty seconds using this method. It's trivial.

Treating Secrets as Environment Data, Not Code

The first shift in mindset you need is this: Secrets are not part of your code; they are part of the environment the code runs in.

Instead of relying on build-time injection, you should fetch secrets at runtime. The most standard way to do this in a Kotlin backend application is through environment variables. This keeps the secret entirely out of the artifact. Here is how I typically implement a configuration wrapper to handle this safely:

object SecretConfig {
    val stripeApiKey: String by lazy {
        System.getenv("STRIPE_API_KEY") 
            ?: throw IllegalStateException("STRIPE_API_KEY environment variable is missing!")
    }
}

By using System.getenv(), the secret never touches your disk in a way that gets packaged into the build. It lives in the memory of the process running on your server or inside a container orchestration tool like Kubernetes. If you're working in a local development environment, you can use a .env file and a library like dotenv-kotlin to load these variables into your environment without hardcoding them.

Scaling Up to Secret Managers

Environment variables are a huge step up from .properties files, but in a professional production environment, they still have flaws—for one, anyone with access to the server's process list might be able to see them. If you're building something that handles sensitive financial or user data, you should move toward a dedicated Secret Manager (like AWS Secrets Manager, HashiCorp Vault, or Azure Key Vault).

The pattern remains the same: your Kotlin code asks for a key by name at runtime via an API call to the manager, authenticated by the machine's identity (like an IAM role), rather than by a password. This removes the "secret zero" problem—where you need a secret just to get your secrets.

My rule of thumb? If you can find a string in your compiled binary that allows you to authenticate with a third-party service, you haven't handled a secret; you've just hidden a password in plain sight.




📋 Practical Task

Build a Runtime Secret Validator

Your task is to create a DatabaseCredentials singleton that prevents the application from starting if critical secrets are missing from the environment, while providing a safe fallback for local development.

  • Create a DatabaseCredentials object.
  • Implement a property dbPassword that attempts to read from an environment variable named DB_PASSWORD.
  • Implement a property environment that reads APP_ENV (e.g., "production", "development").
  • Logic: If APP_ENV is "production" and DB_PASSWORD is null or empty, throw a SecurityException with a descriptive message. If APP_ENV is "development", allow a default fallback password of "dev_pass_123".
  • Write a main function to test both scenarios: one where the variables are missing (simulating a failed production boot) and one where you mock a development environment.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.