Skip to lesson

Secrets in code and Git history

A developer pushes a quick fix at night. By morning a bot has found the database password in the repository and is already using it. How do secrets leak, and what do you do when one has?

How secrets leak

A secret is any value that lets someone act as your app: the database password, the JWT signing key, a payment gateway key, a private key file. Whoever has the value can do what your app can do.

A key written as a constant in a Java class, and a program that reads it back out of the compiled file.

Example 1 · A hard-coded key is plain text in the .class file

SecretInClassDemo.javaJava
import java.io.InputStream;import java.nio.charset.StandardCharsets;
class PaymentClient {    // MISTAKE: a secret written into the code    static final String API_KEY = "demo_live_key_7Q2xK9pL4mN8";}
public class SecretInClassDemo {    public static void main(String[] args) throws Exception {        try (InputStream in = SecretInClassDemo.class.getResourceAsStream("PaymentClient.class")) {            // Read the compiled class as raw bytes, the way anyone with your JAR can            String bytes = new String(in.readAllBytes(), StandardCharsets.ISO_8859_1);            int at = bytes.indexOf("demo_live_key_");            System.out.println("Secret found in PaymentClient.class: " + (at >= 0));            System.out.println("Text at that position: " + bytes.substring(at, at + 26));        }    }}
Output
Secret found in PaymentClient.class: true
Text at that position: demo_live_key_7Q2xK9pL4mN8

What this code does

  • The program never calls PaymentClient. It only reads the bytes of PaymentClient.class, and the key is there as plain text.
  • Tools like javap -v or a simple text search do the same to any JAR. Compiling and packaging hide nothing.
  • The fix is not a cleverer place in the code: the value must come from outside the code, at runtime.

Secrets rarely leak through clever attacks; they leak because a developer wrote them where many people can read them. Compiling does not hide a constant: the string sits as plain text inside the .class file, and every JAR you share carries it. The usual places:

  • Hard-coded in a Java class (static final String API_KEY = "...").
  • In a committed application.properties, on GitHub for anyone to search.
  • In a screenshot of the IDE or a terminal pasted into a WhatsApp group.
  • In a log line or an error page that prints the configuration.

Find the bug

Spot the secret

Tap the line that puts a secret where many people can read it.

A payment client in a Java class. Which line is the bug?

Round 1 of 3
OWASP Top 10 2025 lists hard-coded and leaked secrets under A02 Security Misconfiguration and A04 Cryptographic Failures. In ShopLite's threat model this is risk R10.

Environment variables, ignored local files and a committed .example file

An environment variable is a named value that the operating system hands to a program when it starts. Spring reads one with ${NAME}, so committed files hold only the placeholder.

The ignore rules in .gitignore, then a check that Git really hides the secret files.

Properties
# .gitignore (top of the repository)# Local secrets and settings: never commit.envapplication-local.properties*.pem# .env.example (committed: names only, no values)DB_PASSWORD=JWT_SECRET=

Example 2 · Local secret files are ignored, the example file is committed

Runs in: a terminal in the shoplite-api repository

Terminal
git status --shortgit check-ignore -v .env application-local.properties .env.example
Output
?? .env.example
?? .gitignore
.gitignore:2:.env	.env
.gitignore:3:application-local.properties	application-local.properties

What this code does

  • The folder holds .env, application-local.properties, .env.example and .gitignore, but git status lists only the last two: Git does not even see the secret files.
  • git check-ignore -v names the rule and line that hides each file. .env.example prints nothing, so it is not ignored and will be committed.
  • Run this check once after editing .gitignore, before the first git add ..

Typing variables in every new terminal is tiring, so keep them in a local file instead, .env or application-local.properties, and list that file in .gitignore so Git never picks it up. Load it into your shell or IDE run configuration before you start the app (IntelliJ IDEA's run configuration has an Environment variables field). The file stays on your laptop only.

Commit a .env.example with the same names and empty values. A new teammate copies it to .env, fills in their own values, and knows exactly what the app needs.

A leaked secret stays in Git history: rotate it first

To rotate a secret is to create a new password or key, put it where the app reads it, and disable the old one. After rotation a leaked value is useless, even if someone copied it.

A password deleted in a later commit, and the Git command that still finds it.

A leaked password stays in Git history. Commit 1 holds password=Asha@1234 in application.properties. Commit 2 replaces it with ${DB_PASSWORD}, so the latest file looks clean, but commit 1 is still in the history and in every clone.

Example 3 · Deleted in the next commit, still in history

Runs in: a terminal in a Git repository

Terminal
git log --onelinegit log -p -S "Asha@1234" --format="%h %s" -- src/main/resources/application.properties
Sample output
1629e98 Read the database settings from environment variables
1664271 Connect to MySQL
1629e98 Read the database settings from environment variables

diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties
index b47966c..eade6d1 100644
--- a/src/main/resources/application.properties
+++ b/src/main/resources/application.properties
@@ -1,3 +1,3 @@
-spring.datasource.url=jdbc:mysql://localhost:3306/shoplite
-spring.datasource.username=root
-spring.datasource.password=Asha@1234
+spring.datasource.url=${DB_URL}
+spring.datasource.username=${DB_USER}
+spring.datasource.password=${DB_PASSWORD}
1664271 Connect to MySQL

diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties
new file mode 100644
index 0000000..b47966c
--- /dev/null
+++ b/src/main/resources/application.properties
@@ -0,0 +1,3 @@
+spring.datasource.url=jdbc:mysql://localhost:3306/shoplite
+spring.datasource.username=root
+spring.datasource.password=Asha@1234

What this code does

  • The second commit replaced the password with ${DB_PASSWORD}, and the latest file looks clean.
  • git log -S finds every commit that added or removed the text. Both commits still show Asha@1234 in full, to anyone who has the repository.
  • This is why rotation comes first: the password must be changed in MySQL, because the history cannot be trusted to forget it.

Git history is every version of every file that was ever committed. Deleting a password in a new commit changes only the latest version; the old commit still holds it, and anyone who cloned the repository already has a copy. So rotate first, then clean the history with a tool such as git filter-repo and force-push; cleaning without rotating is not enough, because forks, clones and caches keep the old commits.

After a leak, work in this order:

  1. Rotate: change the database password or create a new JWT key, and disable the old value.
  2. Update the environment variables on every server and restart the app.
  3. Check logs for use of the old value between the leak and the rotation.
  4. Remove the value from history (git filter-repo), force-push, and ask teammates to clone again.

Scanning for secrets: gitleaks and GitHub secret scanning

A secret scanner reads files or commits and reports text that looks like a secret: known key formats, private key headers, and properties named password or secret with a literal value.

Two gitleaks commands, then a small Java scanner that works the same way.

Terminal
gitleaks git -v          # every commit in this repositorygitleaks dir src -v      # the files as they are now

Example 4 · How a secret scanner works

SecretScanDemo.javaJava
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;
record Finding(String file, int line, String rule, String shown) {}
public class SecretScanDemo {    // key=value where the key names a secret and the value is a literal, not a ${PLACEHOLDER}    static final Pattern SECRET_PROPERTY = Pattern.compile(            "^\\s*([\\w.-]*(password|secret|api[-_.]?key|token)[\\w.-]*)\\s*[=:]\\s*(?!\\$\\{)(\\S+)",            Pattern.CASE_INSENSITIVE);    static final Pattern PRIVATE_KEY = Pattern.compile("-----BEGIN [A-Z ]*PRIVATE KEY-----");
    static List<Finding> scan(Map<String, String> files) {        List<Finding> findings = new ArrayList<>();        for (Map.Entry<String, String> file : files.entrySet()) {            String[] lines = file.getValue().split("\n");            for (int i = 0; i < lines.length; i++) {                Matcher m = SECRET_PROPERTY.matcher(lines[i]);                if (m.find()) {                    findings.add(new Finding(file.getKey(), i + 1, "secret-property",                            m.group(1) + "=" + mask(m.group(3))));                } else if (PRIVATE_KEY.matcher(lines[i]).find()) {                    findings.add(new Finding(file.getKey(), i + 1, "private-key", "-----BEGIN ... PRIVATE KEY-----"));                }            }        }        return findings;    }
    // A report must not leak what it found: show two characters only    static String mask(String value) {        return value.length() <= 4 ? "****" : value.substring(0, 2) + "****";    }
    public static void main(String[] args) {        Map<String, String> files = new LinkedHashMap<>();        files.put("src/main/resources/application.properties",                "spring.datasource.url=${DB_URL}\nspring.datasource.password=${DB_PASSWORD}\nshoplite.jwt.secret=${JWT_SECRET}\n");        files.put("src/main/resources/application-dev.properties",                "logging.level.com.shoplite=DEBUG\nspring.datasource.password=Asha@1234\n");        files.put("src/test/resources/application-test.properties",                "shoplite.jwt.secret=test-only-secret-0123456789abcdef\n");        files.put("deploy/server-key.pem",                "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC\n-----END PRIVATE KEY-----\n");
        List<Finding> findings = scan(files);        for (Finding f : findings) {            System.out.printf("%s:%d  %s  %s%n", f.file(), f.line(), f.rule(), f.shown());        }        System.out.println(findings.size() + " findings");    }}
Output
src/main/resources/application-dev.properties:2  secret-property  spring.datasource.password=As****
src/test/resources/application-test.properties:1  secret-property  shoplite.jwt.secret=te****
deploy/server-key.pem:1  private-key  -----BEGIN ... PRIVATE KEY-----
3 findings

What this code does

  • Two rules, like a tiny gitleaks: a property whose name says secret with a literal value, and a private key header. ${DB_PASSWORD} is skipped by the (?!\$\{) look-ahead.
  • The test file's key is a real finding for the scanner, even if it is harmless. Real tools let you allow-list such values in a config file instead of ignoring the whole rule.
  • The report masks what it found. A scanner that prints full secrets into a CI log creates a new leak.

A scanner cannot be sure, so it reports possible secrets and lets you mark harmless ones, such as a test-only value, as allowed. gitleaks is a free command-line scanner: gitleaks git scans every commit, gitleaks dir scans plain files, and the same tool can run as a pre-commit hook so a secret is stopped before it is even committed.

GitHub secret scanning checks pushed code for the formats of well-known services, and with push protection it blocks a push that contains one. Use both: the hook for your own commits, the platform for everyone's.

Different secrets per environment, and failing at startup

A required-variable check, then the real JwtProperties that refuses to start with a missing or weak key.

Example 5 · Fail fast when a required variable is missing

RequiredEnvDemo.javaJava
import java.util.Map;
public class RequiredEnvDemo {    static String required(Map<String, String> env, String name) {        String value = env.get(name);        if (value == null || value.isBlank()) {            throw new IllegalStateException(                    "Missing environment variable " + name + ". Set it before starting the app.");        }        return value;    }
    public static void main(String[] args) {        // 1. This computer: the variable is not set        try {            required(System.getenv(), "SHOPLITE_DEMO_DB_PASSWORD");            System.out.println("Started");        } catch (IllegalStateException e) {            System.out.println("Startup stopped: " + e.getMessage());        }
        // 2. A server where the variable is set (the value is never printed)        Map<String, String> server = Map.of("SHOPLITE_DEMO_DB_PASSWORD", "k7#Qe9-server-only");        String password = required(server, "SHOPLITE_DEMO_DB_PASSWORD");        System.out.println("Password loaded: " + password.length() + " characters");    }}
Output
Startup stopped: Missing environment variable SHOPLITE_DEMO_DB_PASSWORD. Set it before starting the app.
Password loaded: 18 characters

What this code does

  • System.getenv() returns the environment as a Map. Passing the map in makes the method easy to test with a fake server environment.
  • The error names the variable, so whoever deploys the app knows exactly what to set. It never prints a value.
  • Checking at startup turns a hidden problem (a wrong key used for hours) into an obvious one (the app does not start).

Example 6 · src/main/java/com/shoplite/auth/JwtProperties.java

Runs in: the shoplite-api Spring Boot project

JwtProperties.javaJava
package com.shoplite.auth;
import java.time.Duration;import java.util.Base64;
import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;
import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.boot.context.properties.bind.DefaultValue;
/** * Token settings under "shoplite.jwt". The secret comes from the JWT_SECRET environment variable: * a Base64 text of at least 32 random bytes (openssl rand -base64 32). */@ConfigurationProperties("shoplite.jwt")public record JwtProperties(        String secret,        @DefaultValue("shoplite-api") String issuer,        @DefaultValue("15m") Duration accessTokenTtl,        @DefaultValue("7d") Duration refreshTokenTtl,        @DefaultValue("30s") Duration clockSkew) {
    /** HS256 needs a key of at least 256 bits (32 bytes). */    static final int MIN_KEY_BYTES = 32;
    /** Runs while Spring binds the properties, so a missing or weak key stops the app at startup. */    public JwtProperties {        if (secret == null || secret.isBlank()) {            throw new IllegalArgumentException("shoplite.jwt.secret is empty. Set the JWT_SECRET environment variable.");        }        byte[] key;        try {            key = Base64.getDecoder().decode(secret.trim());        } catch (IllegalArgumentException e) {            throw new IllegalArgumentException("shoplite.jwt.secret must be Base64 text (openssl rand -base64 32).");        }        if (key.length < MIN_KEY_BYTES) {            throw new IllegalArgumentException("shoplite.jwt.secret is " + key.length                    + " bytes; HS256 needs at least " + MIN_KEY_BYTES + " random bytes.");        }    }
    /** The HMAC-SHA256 key that signs and checks every access token. */    public SecretKey signingKey() {        return new SecretKeySpec(Base64.getDecoder().decode(secret.trim()), "HmacSHA256");    }
    /** Records print every field; this one must never print the secret. */    @Override    public String toString() {        return "JwtProperties[secret=***, issuer=" + issuer + ", accessTokenTtl=" + accessTokenTtl                + ", refreshTokenTtl=" + refreshTokenTtl + ", clockSkew=" + clockSkew + "]";    }}
Sample output
$ JWT_SECRET=short mvn spring-boot:run
...
***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under 'shoplite.jwt' to com.shoplite.auth.JwtProperties:

    Reason: java.lang.IllegalArgumentException: shoplite.jwt.secret must be Base64 text (openssl rand -base64 32).

Action:

Update your application's configuration

What this code does

  • The compact constructor runs while Spring binds shoplite.jwt.*, so a missing, non-Base64 or short key stops the app before Tomcat opens a port.
  • The message names the property and how to make a good key, but never prints the value itself. openssl rand -base64 32 gives 32 random bytes: the HS256 minimum.
  • toString is overridden because records print every component: a log line such as log.info("{}", properties) must never show the key.

Each environment gets its own secrets: your laptop, the test server and production never share a database password or a JWT key, so a leaked development key cannot open production. A missing secret must stop the app at startup, with a message that names the variable. Never fall back to a default such as ${JWT_SECRET:changeme}: the app would start in production with a key printed in your GitHub repository.

In ShopLite, JwtProperties (the @ConfigurationProperties record from the JWT module, in com.shoplite.auth) checks the secret in its constructor while Spring binds shoplite.jwt.*. application.properties reads shoplite.jwt.secret=${JWT_SECRET:}, so a missing variable becomes an empty value, and the record refuses empty text, text that is not Base64, and keys shorter than 32 bytes. The app never starts with a missing or weak key.

Next step

Check your understanding

12 quick questions