JAVA.SV.LLM.APIKEY.HC

Hardcoded API key in LLM client

The JAVA.SV.LLM.APIKEY.HC checker flags code that hardcodes an API key when configuring an LLM client.

Vulnerability and risk

Hardcoded API keys can be exposed through source control, logs, build artifacts, or copied binaries. If an attacker obtains the key, they can make unauthorized requests, access protected LLM services, or incur unexpected usage charges.

Mitigation and prevention

Do not hardcode API keys in application source code. Load secrets from a secure source such as an environment variable, secret-management service, or deployment-specific configuration that is not committed with the application code.

Vulnerable code example 1

Copy
import com.google.genai.Client;

public class Example {
    public Client create() {
        return Client.builder().apiKey("sk-hardcoded-1234567890abcdef").build(); // hardcoded key
    }
}

Klocwork reports a JAVA.SV.LLM.APIKEY.HC defect on line 5 because the API key is embedded directly in the source code.

Fixed code example 1

Copy
import com.google.genai.Client;

public class Example {
    public Client create() {
        return Client.builder().apiKey(System.getenv("GOOGLE_API_KEY")).build(); // key from environment
    }
}

In this fixed example, Klocwork no longer reports a JAVA.SV.LLM.APIKEY.HC defect because the API key is read from an environment variable instead of being hardcoded.

Security training

Application security training materials provided by Secure Code Warrior.

Extension

This checker cannot be extended through the Klocwork knowledge base.