Sub topic 6
Giving the Job Credentials Without Leaking Them
An unattended agent job needs credentials to work: an API key or login for the agent itself, a token to push a branch, and perhaps cloud access. No one is at the terminal to type them in. The job must find them on its own, and they must not end up in logs, in the repository, or in the agent's context.
This chapter assumes you have read the earlier chapters on headless mode, scheduler environments, and least-privilege permissions. You should be comfortable with environment variables and file permissions.
What the job needs, and what can go wrong
A scheduled agent run typically touches three kinds of secrets:
- Agent credentials: the key or login that lets the agent call its model provider.
- Repository credentials: a token or deploy key used to fetch code and push a branch.
- Service credentials: anything the prompt asks the agent to reach, such as a cloud account or an issue tracker.
Each can leak in a few common ways:
| Leak path | Example |
|---|---|
| Committed to the repository | A `.env` file added by `git add .` |
| Written to a log | A script run with `set -x` that echoes `TOKEN=...` |
| Visible in the process list | `my-agent --api-key sk-...` on the command line |
| Pasted into the prompt | A prompt file containing "use this token: ..." |
| Overly broad scope | A personal token with access to every repository |
The rest of the chapter addresses each path.
Where to store secrets, by scheduler
The scheduler you chose earlier determines where secrets should live.
| Scheduler | Recommended storage | Notes |
|---|---|---|
| cron | A file readable only by the job's user, loaded by the wrapper script | Do not put secrets in the crontab. Crontabs are easy to print and copy. |
| systemd timer | `EnvironmentFile=` pointing to a root-owned file, or `LoadCredential=` | Keep the file out of the repository and out of unit files. |
| CI schedule | The CI system's encrypted secrets store | Secrets are masked in logs, but masking is not a complete defense. |
cron: a locked-down file
Create a file that only the job's user can read, and have the wrapper script load it.
install -m 600 /dev/null "$HOME/.config/nightly-agent.env"
# Edit the file and add lines such as:
# AGENT_API_KEY=...
# GIT_PUSH_TOKEN=...Mode 600 means only the owner can read or write the file. Then load it in the wrapper script, before the agent starts:
#!/usr/bin/env bash
set -u
ENV_FILE="$HOME/.config/nightly-agent.env"
# Refuse to run if the secrets file is readable by other users.
perms=$(stat -c '%a' "$ENV_FILE" 2>/dev/null || stat -f '%Lp' "$ENV_FILE")
if [ "$perms" != "600" ]; then
echo "refusing to run: $ENV_FILE has mode $perms, expected 600" >&2
exit 1
fi
set -a # export every variable defined while this is on
. "$ENV_FILE"
set +aThe permission check turns a silent mistake into a loud failure. The stat call tries the GNU form first and falls back to the macOS form.
systemd: environment files and credentials
In the service unit from the earlier chapter, EnvironmentFile=/etc/nightly-agent.env already loads variables. Set the file to mode 600, owned by root, so only root and systemd can read it. For stronger handling, systemd can pass a secret as a file that only the service can see:
[Service]
LoadCredential=agent-key:/etc/credstore/agent-keyThe service then reads the secret from the path in $CREDENTIALS_DIRECTORY. This keeps the value out of the environment, which matters because environment variables are inherited by every child process the agent starts.
CI: encrypted secrets
In GitHub Actions, store values as repository or environment secrets and map only the ones the job needs into the step that needs them:
- name: Run agent
env:
AGENT_API_KEY: ${{ secrets.AGENT_API_KEY }}
run: ./scripts/nightly-agent.shSetting env on the step, not the whole workflow, limits which steps can read the value. Note that the workflow in this tutorial uses permissions: contents: read. That setting limits the built-in GITHUB_TOKEN. If the agent must push a branch, grant contents: write on that job only, or use a separate narrowly scoped token.
Choosing narrow credentials
Least privilege applies to credentials as much as to tool permissions. Prefer these options, roughly in order:
- Short-lived tokens issued for each run, such as OIDC federation in CI, which exchanges the job's identity for a temporary cloud credential.
- A dedicated machine account or GitHub App with access to one repository.
- A deploy key limited to one repository, read-only unless the job must push.
- A fine-grained personal access token with an expiry date.
Avoid a personal token that carries your full account rights. If the job runs under your identity, a leak exposes everything you can do. A dedicated account also makes the audit trail clear: commits and API calls from the job are visibly from the job.
Give the job a branch-only push right where you can. Combined with branch protection on main, a stolen token can create a branch but cannot change the released code. This connects to the later chapter on delivering results as pull requests.
Keeping secrets out of the agent's reach
The agent can read anything the process can read. That has two consequences.
First, any secret in the environment is visible to commands the agent runs. If the agent has a shell tool, it could run env and the output would land in the log and in the model's context. Pass the agent only the variables it needs. When launching it, you can clear the rest:
env -i \
PATH="$PATH" \
HOME="$HOME" \
AGENT_API_KEY="$AGENT_API_KEY" \
timeout 20m $AGENT_CMD < prompts/nightly.md > "$LOG" 2>&1Here env -i starts the command with an empty environment, and only the four listed variables are passed in. Variables such as GIT_PUSH_TOKEN stay in the wrapper, which does the push itself after the agent finishes. This split is worth considering: the agent edits files, and the wrapper holds the push credential.
Second, do not store secrets in files inside the working directory. The agent may read them, and a careless git add may commit them. Keep secret files outside the repository, and make sure .gitignore lists any local env files.
A related point from the prompt-injection chapter applies here. If the agent reads untrusted text, such as an issue body, that text can instruct it to reveal secrets. The fewer secrets the agent process holds, the less an injected instruction can steal.
Keeping secrets out of logs
Logs are the most common leak, because the earlier chapters encouraged you to capture everything. Take these steps:
- Never put secrets on a command line. Arguments appear in
psoutput and often in logs. Use environment variables or files. - Avoid
set -xin wrapper scripts that handle secrets. It prints each expanded command, including any token. - Never
echoa variable to debug it. Print whether it is set instead:
: "${AGENT_API_KEY:?AGENT_API_KEY is not set}"
echo "AGENT_API_KEY is set (${#AGENT_API_KEY} characters)"- Restrict log directory permissions with
chmod 700 "$LOG_DIR", since agent output can contain anything the agent saw. - Add a redaction pass if logs are shipped elsewhere:
sed -E 's/(sk-|ghp_|github_pat_)[A-Za-z0-9_]+/\1[REDACTED]/g' "$LOG" > "$LOG.redacted"The pattern above matches a few common token prefixes. It is a safety net and cannot catch every format, so treat it as a second layer behind not logging secrets at all.
Rotation and revocation
Assume that a secret will eventually leak, and plan for replacing it.
- Give every token an expiry date and put a reminder on your calendar before it lapses. An expired token produces a failed run, and the failure alerting from the earlier chapter should catch it.
- Keep one token per job, so revoking one does not break others.
- Document where each secret lives and who can replace it.
- If a secret appears in a log or commit, revoke it immediately. Deleting the log line or rewriting Git history is not enough, because copies may already exist elsewhere.
A quick scan before each commit helps. Tools such as gitleaks or git-secrets can run as a pre-commit hook or CI step and block a push that contains a recognizable secret.
How the pieces fit together
Summary checklist
- Store secrets outside the repository, in a file with mode
600, a systemd credential, or the CI secret store. - Use narrow, expiring, dedicated credentials, and prefer short-lived tokens.
- Pass the agent only the variables it needs. Keep the push token in the wrapper.
- Keep secrets out of command lines,
set -xoutput, and logs. - Know how to revoke and replace each secret.
Exercise
Your nightly wrapper starts the agent with my-agent --api-key "$AGENT_API_KEY". Give two reasons this is risky and describe one fix.
Show answer
The key becomes part of the process arguments, so any user on the machine can see it with ps, and it may be written to logs or shell history if the command is echoed or traced with set -x. A fix is to pass the key as an environment variable, for example AGENT_API_KEY="$AGENT_API_KEY" my-agent, if the agent supports reading it that way, or to load it from a mode 600 file the agent reads. Check your agent's documentation for the supported method.
Exercise
A CI job uses a personal access token with write access to all of your repositories, so the agent can push a branch. Describe a safer setup using two changes.
Show answer
Replace the personal token with a narrowly scoped credential, such as a fine-grained token, deploy key, or GitHub App limited to the one repository and to branch pushes, with an expiry date. Also protect main with branch protection so that even a leaked token can only create branches that need review. Keeping the push step in the wrapper, away from the agent process, is a further improvement.