Compose Desktop projects: how to include API keys (or other secrets) without committing?

927 views Asked by At

In Compose Desktop projects, how can we manage secret keys without committing?

In Android projects, Gradle has the buildConfigField() and resValue() functions. They will generate a BuildConfig.java during compile time, and we can use the values during runtime.

For example, in an Android project, first, we create two environment variables — RELEASE_API_KEY and STAGING_API_KEY (It can be either local computer, or a CI/CD environment).

Then in build.gradle file we can say:

android {
   buildTypes {
     release {
       buildConfigField("String", "API_KEY", "\"${System.getenv('RELEASE_API_KEY')}\"")
     }
     staging {
       buildConfigField("String", "API_KEY", "\"{System.getenv('STAGING_API_KEY')}\"")
     }
   }
}

..and in the Kotlin code we can use:

val apiManager = ApiManager( BuildConfig.API_KEY )

Is there a similar approach in Compose Desktop projects so that:

  1. I don't have to commit the secret to the source repository?
  2. I can easily configure secrets in a CI/CD environment?
1

There are 1 answers

1
spierce7 On BEST ANSWER

So there are some Gradle plugins that were built to solve just a problem like this - inject build time constants into our runtime code. Here is the one that came up in a Google search:

https://github.com/gmazzo/gradle-buildconfig-plugin

And here is the one that came up when I swapped the c in config for a k (you know these Kotlin devs can't resist it right?)

https://github.com/yshrsmz/BuildKonfig

Of course - if you don't want to mess around with gradle plugins like this, the easy solution is to just create a file with your dev code where the same constants are nulled out or are empty strings, or reference an ignored file to get the value, and then just overwrite the file in CI using bash, replacing all the constants with what you want. This approach is very useful when you don't have access to gradle, like in a js project:

#!/usr/bin/env bash

AWS_FILE=<your aws credentials file here>
if [ -f "$AWS_FILE" ]; then
    echo "Injecting the AWS Credentials"
    echo "export const AWS_CREDENTIALS = {
    clientId: \"$AWS_CLIENT_ID\",
    secret: \"$AWS_CLIENT_SECRET\"}" > $AWS_FILE
else
    echo "$AWS_FILE doesn't exist."
    exit 1
fi