logo

Sensitive information in source code - API Key - Elixir


Need

Prevent exposure of sensitive data in the source code


Context

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

Description

Insecure Code Example

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

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

Secure Code Example

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

  • 142 - Sensitive information in source code - API Key

  • Last updated

    2023/09/18