Sensitive information in source code - API Key - Elixir

Sensitive information in source code - API Key - Elixir

Need

Prevent exposure of sensitive data in the source code

Context

  • Usage of Elixir (v1.11+) for building scalable and fault-tolerant applications
  • Usage of HTTPoison for making HTTP requests in Elixir

Description

Non compliant code

        defmodule MyApp do
  @api_key "MySecretApiKey"
  def request_data do
    HTTPoison.get!("https://example.com/data", [], [params: ["api_key": @api_key]])
  end
end
        
        

In this code, the application has a secret API key hardcoded directly in the source code. This is dangerous because anyone with access to the source code can see and potentially misuse the API key. Even if the source code is not intended to be public, it can be accidentally exposed, or access could be obtained through a breach.

Steps

  • Store the API key in an environment variable rather than hardcoding it in the source code.
  • Load the API key from the environment variable in your Elixir code.

Compliant code

        defmodule MyApp do
  def request_data do
    api_key = System.get_env("API_KEY")
    HTTPoison.get!("https://example.com/data", [], [params: ["api_key": api_key]])
  end
end
        
        

In this revised code, the application loads the API key from an environment variable. This is safer because the actual value of the API key is not included in the source code, and can be managed securely on the server. This prevents the API key from being exposed if the source code is accidentally made public or accessed through a breach.

References