Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

t1412.2: Scoped short-lived GitHub tokens for worker agents#3094

Merged
marcusquinn merged 1 commit intomainfrom
feature/t1412.2-scoped-tokens
Mar 7, 2026
Merged

t1412.2: Scoped short-lived GitHub tokens for worker agents#3094
marcusquinn merged 1 commit intomainfrom
feature/t1412.2-scoped-tokens

Conversation

@marcusquinn
Copy link
Owner

Summary

  • Adds worker-token-helper.sh — scoped, short-lived GitHub token lifecycle management for headless worker agents
  • Integrates token creation/revocation into cron-dispatch.sh dispatch flow
  • Documents setup, usage, and security model across headless-dispatch, prompt-injection-defender, and opsec docs

What this does

Each headless worker session now receives a minimal-permission GitHub token scoped to the target repo only, with a configurable TTL (default 1h). This limits blast radius if a worker is compromised via prompt injection — the attacker can only access the target repo with contents:write, pull_requests:write, and issues:write permissions.

Two token strategies (tried in priority order):

Strategy Scoping TTL Setup
GitHub App installation token Enforced by GitHub 1h (GitHub enforced) One-time App install
Delegated token (fallback) Advisory (tracked locally) Configurable None (zero-config)

Files changed

  • New: .agents/scripts/worker-token-helper.sh — token lifecycle (create, validate, revoke, cleanup, status)
  • Modified: .agents/scripts/cron-dispatch.sh — creates scoped token before dispatch, revokes after
  • Modified: .agents/tools/ai-assistants/headless-dispatch.md — full scoped token documentation
  • Modified: .agents/tools/security/prompt-injection-defender.md — credential isolation defense layer
  • Modified: .agents/tools/security/opsec.md — added credential isolation as layer 4 mitigation
  • Modified: .gitignore — exception for worker-token-helper.sh (not a credential file)

Security model

  • Token files: 600 permissions, overwritten with random data before deletion
  • Metadata files: no token values, safe to inspect/log
  • JSONL audit log: records create/revoke events with timestamps (never token values)
  • GitHub App tokens: revoked via API on cleanup
  • Interactive sessions: unaffected (scoped tokens only apply to headless workers)

Testing

  • worker-token-helper.sh help — displays usage
  • worker-token-helper.sh status — shows configuration and active tokens
  • worker-token-helper.sh create --repo owner/repo --ttl 60 — creates delegated token (tested)
  • worker-token-helper.sh validate --token-file <path> — validates against GitHub API (tested)
  • worker-token-helper.sh revoke --token-file <path> — securely deletes token files (tested)
  • ShellCheck clean on all new/modified scripts

Closes #3072

Implement worker-token-helper.sh for creating minimal-permission, short-lived
GitHub tokens for headless worker sessions. Reduces blast radius if a worker
is compromised via prompt injection.

Two token strategies (tried in priority order):
1. GitHub App installation token — enforced by GitHub, repo-scoped, 1h TTL
2. Delegated token — uses existing gh auth token with advisory scoping

Token lifecycle: create (with audit log) -> pass via env -> revoke after session.
Token files use 600 permissions and are overwritten before deletion.

Integration:
- cron-dispatch.sh: creates scoped token before session, revokes after
- headless-dispatch.md: full documentation with setup guide
- prompt-injection-defender.md: credential isolation defense layer docs
- opsec.md: added credential isolation as layer 4 mitigation

Closes #3072
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 7, 2026

Warning

Rate limit exceeded

@marcusquinn has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 0 minutes and 30 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 733c3831-2563-4af5-a5c1-613cc1a866c9

📥 Commits

Reviewing files that changed from the base of the PR and between 2e15398 and bde2cc7.

📒 Files selected for processing (6)
  • .agents/scripts/cron-dispatch.sh
  • .agents/scripts/worker-token-helper.sh
  • .agents/tools/ai-assistants/headless-dispatch.md
  • .agents/tools/security/opsec.md
  • .agents/tools/security/prompt-injection-defender.md
  • .gitignore
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/t1412.2-scoped-tokens

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly bolsters the security posture of headless worker agents by introducing a system for generating and managing scoped, short-lived GitHub tokens. This change minimizes the potential impact of a security breach by ensuring that worker agents operate with only the necessary permissions for a limited duration, thereby reducing the blast radius of any compromised credentials.

Highlights

  • Enhanced Security for Worker Agents: Implemented scoped, short-lived GitHub tokens for headless worker agents to significantly reduce the blast radius in case of a compromise.
  • Automated Token Lifecycle Management: Integrated the creation and revocation of these scoped tokens directly into the cron-dispatch.sh workflow, ensuring tokens are provisioned before a task and cleaned up afterwards.
  • Flexible Token Strategies: Introduced two primary token strategies: GitHub App installation tokens for enforced, repo-scoped permissions, and a delegated token fallback for advisory scoping.
  • Comprehensive Documentation: Updated relevant documentation (headless-dispatch.md, opsec.md, prompt-injection-defender.md) to detail the setup, usage, and security model of the new token system.
  • Robust Security Measures: Ensured token files have strict 600 permissions, are overwritten with random data before deletion, and all lifecycle events are recorded in a JSONL audit log without exposing token values.
Changelog
  • .agents/scripts/cron-dispatch.sh
    • Integrated logic for creating and revoking scoped worker tokens, including repository slug resolution and fallback mechanisms.
    • Added TOKEN_HELPER and WORKER_SCOPED_TOKENS variables to control token helper script path and feature enablement.
  • .agents/scripts/worker-token-helper.sh
    • Added a new utility script to handle the full lifecycle of GitHub tokens, supporting both GitHub App and delegated token strategies.
    • Implemented secure file management for tokens (600 permissions, overwrite before delete) and a JSONL audit log for lifecycle events.
    • Provided commands for creating, validating, revoking, cleaning up, and checking the status of worker tokens.
  • .agents/tools/ai-assistants/headless-dispatch.md
    • Expanded documentation to cover the new scoped worker token feature, detailing its mechanics, permissions, strategies, setup for GitHub Apps, and CLI usage.
    • Added 'Scoped tokens' as a new security best practice for headless dispatch.
  • .agents/tools/security/opsec.md
    • Updated the operational security guide to include 'Credential isolation' as a new layer 4 mitigation strategy, linking to the detailed documentation.
  • .agents/tools/security/prompt-injection-defender.md
    • Enhanced the prompt injection defender documentation with a new section on 'Credential Isolation,' explaining how scoped GitHub tokens contribute to enforcement-based defenses.
    • Added 'Scoped tokens' to the table of defense layers, highlighting its effectiveness against informed attackers.
    • Included a reference to scripts/worker-token-helper.sh in the 'Related' section.
  • .gitignore
    • Added an exclusion rule for worker-token-helper.sh to prevent it from being ignored, as it manages tokens but does not contain them.
Activity
  • Initial testing was performed, including verification of worker-token-helper.sh commands such as help, status, create, validate, and revoke.
  • All new and modified scripts passed ShellCheck linting, ensuring code quality and adherence to best practices.
  • This pull request addresses and closes issue t1412.2: Scoped short-lived GitHub tokens #3072, indicating resolution of a previously identified task or bug.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@github-actions
Copy link

github-actions bot commented Mar 7, 2026

🔍 Code Quality Report

�[0;35m[MONITOR]�[0m Code Review Monitoring Report

�[0;34m[INFO]�[0m Latest Quality Status:
SonarCloud: 0 bugs, 0 vulnerabilities, 109 code smells

�[0;34m[INFO]�[0m Recent monitoring activity:
Sat Mar 7 12:27:20 UTC 2026: Code review monitoring started
Sat Mar 7 12:27:21 UTC 2026: SonarCloud - Bugs: 0, Vulnerabilities: 0, Code Smells: 109

📈 Current Quality Metrics

  • BUGS: 0
  • CODE SMELLS: 109
  • VULNERABILITIES: 0

Generated on: Sat Mar 7 12:27:23 UTC 2026


Generated by AI DevOps Framework Code Review Monitoring

@sonarqubecloud
Copy link

sonarqubecloud bot commented Mar 7, 2026

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a robust mechanism for creating scoped, short-lived GitHub tokens for worker agents, which is a significant security improvement. While the overall design aims to enhance security, the new utility script worker-token-helper.sh contains critical and high-severity vulnerabilities related to improper input validation. Specifically, the revoke and validate commands are vulnerable to path traversal, potentially allowing arbitrary file overwrite/deletion and arbitrary file read. Additionally, the create command is vulnerable to arithmetic injection via the --ttl parameter, which could lead to arbitrary command execution. These issues require strict input validation and ensuring file operations are restricted to the intended directory. Furthermore, the consistent use of 2>/dev/null to suppress command output in the shell scripts hides crucial error information, making debugging difficult. It is recommended to remove this suppression to improve error visibility.

Comment on lines +543 to +544
dd if=/dev/urandom bs=64 count=1 2>/dev/null | head -c 64 >"$token_file" 2>/dev/null || true
rm -f "$token_file"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-critical critical

The revoke command takes a --token-file argument and performs a secure deletion (overwriting with random data using dd and then removing with rm) without validating that the path is within the intended tokens directory. This allows an attacker who can execute the script to overwrite and delete arbitrary files on the system, leading to a critical denial-of-service or system compromise if run with elevated privileges.

;;
--ttl | -t)
ttl="$2"
if ((ttl > MAX_TTL)); then

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

The --ttl argument is used directly in a Bash arithmetic context ((ttl > MAX_TTL)) without prior validation. Bash arithmetic evaluation is susceptible to command injection if the variable contains a specially crafted expression (e.g., a[$(id>&2)0]). This allows an attacker to execute arbitrary commands in the context of the script.


# Validate token against GitHub API (without exposing the value)
local token
token=$(read_token_file "$token_file") || return 1

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

The validate command reads the content of the file specified by the --token-file argument and sends it to the GitHub API. Since there is no validation to ensure the file is within the expected tokens directory, an attacker can read arbitrary files from the system.

Comment on lines +198 to +206
response=$(curl -sf -X POST \
"https://api.github.com/app/installations/${installation_id}/access_tokens" \
-H "Authorization: Bearer ${jwt}" \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
-d "$request_body" 2>/dev/null) || {
log_token "WARN" "GitHub App token creation failed (API error)"
return 1
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Suppressing curl's stderr with 2>/dev/null hides critical information when the GitHub API call fails. Error messages from curl (e.g., network issues, DNS problems) or error responses from the API (which curl -f would print to stderr) are essential for debugging. The || block handles the failure, but the cause of the failure remains unknown.

Suggested change
response=$(curl -sf -X POST \
"https://api.github.com/app/installations/${installation_id}/access_tokens" \
-H "Authorization: Bearer ${jwt}" \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
-d "$request_body" 2>/dev/null) || {
log_token "WARN" "GitHub App token creation failed (API error)"
return 1
}
response=$(curl -sf -X POST \
"https://api.github.com/app/installations/${installation_id}/access_tokens" \
-H "Authorization: Bearer ${jwt}" \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
-d "$request_body") || {
log_token "WARN" "GitHub App token creation failed (API error)"
return 1
}
References
  1. Avoid using '2>/dev/null' for blanket suppression of command errors in shell scripts to ensure that authentication, syntax, or system issues remain visible for debugging.

Comment on lines +341 to +342
repo_slug=$(git -C "$workdir" remote get-url origin 2>/dev/null |
sed -E 's|.*github\.com[:/]||; s|\.git$||' || true)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The use of 2>/dev/null here suppresses potentially useful error messages from git. If git remote get-url origin fails for reasons other than the remote not existing (e.g., git not in PATH, or not a git repository), those errors will be hidden, making debugging more difficult. The || true already prevents the script from exiting on failure.

Suggested change
repo_slug=$(git -C "$workdir" remote get-url origin 2>/dev/null |
sed -E 's|.*github\.com[:/]||; s|\.git$||' || true)
repo_slug=$(git -C "$workdir" remote get-url origin |
sed -E 's|.*github\.com[:/]||; s|\.git$||' || true)
References
  1. Avoid blanket suppression of errors with '2>/dev/null' to ensure that diagnostic information remains visible for debugging, especially when '|| true' is used to handle failures.

fi

if [[ -n "$repo_slug" ]]; then
worker_token_file=$("$TOKEN_HELPER" create --repo "$repo_slug" --ttl "$timeout" 2>/dev/null) || {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Suppressing stderr from "$TOKEN_HELPER" with 2>/dev/null hides valuable debugging information if token creation fails. The helper script provides detailed logs on stderr. Allowing these logs to be displayed would make it easier to diagnose issues with token creation (e.g., misconfiguration, API errors). The failure is already handled gracefully by the || { ... } block.

Suggested change
worker_token_file=$("$TOKEN_HELPER" create --repo "$repo_slug" --ttl "$timeout" 2>/dev/null) || {
worker_token_file=$("$TOKEN_HELPER" create --repo "$repo_slug" --ttl "$timeout") || {
References
  1. Avoid using '2>/dev/null' to suppress command errors, as it can hide important diagnostic information needed for debugging authentication, syntax, or system issues.


# Revoke scoped worker token (t1412.2)
if [[ -n "$worker_token_file" ]] && [[ -x "$TOKEN_HELPER" ]]; then
"$TOKEN_HELPER" revoke --token-file "$worker_token_file" 2>/dev/null || true

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Suppressing stderr from "$TOKEN_HELPER" revoke with 2>/dev/null can hide errors during token revocation. While the script continues on failure due to || true, seeing the error message from the helper script could be important for diagnosing persistent issues.

Suggested change
"$TOKEN_HELPER" revoke --token-file "$worker_token_file" 2>/dev/null || true
"$TOKEN_HELPER" revoke --token-file "$worker_token_file" || true
References
  1. Avoid using '2>/dev/null' to suppress command errors, as it can hide important diagnostic information needed for debugging authentication, syntax, or system issues.

Comment on lines +137 to +139
app_id=$(jq -r '.app_id // empty' "$APP_CONFIG" 2>/dev/null)
private_key_path=$(jq -r '.private_key_path // empty' "$APP_CONFIG" 2>/dev/null)
installation_id=$(jq -r '.installation_id // empty' "$APP_CONFIG" 2>/dev/null)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using 2>/dev/null with jq here suppresses errors if the configuration file ($APP_CONFIG) is malformed or unreadable. Since file existence is checked earlier, any error from jq would indicate a problem with the file's content or permissions. Displaying these errors would aid in debugging configuration issues. The // empty syntax in jq already handles missing keys gracefully.

Suggested change
app_id=$(jq -r '.app_id // empty' "$APP_CONFIG" 2>/dev/null)
private_key_path=$(jq -r '.private_key_path // empty' "$APP_CONFIG" 2>/dev/null)
installation_id=$(jq -r '.installation_id // empty' "$APP_CONFIG" 2>/dev/null)
app_id=$(jq -r '.app_id // empty' "$APP_CONFIG")
private_key_path=$(jq -r '.private_key_path // empty' "$APP_CONFIG")
installation_id=$(jq -r '.installation_id // empty' "$APP_CONFIG")
References
  1. Avoid suppressing stderr with '2>/dev/null' on file operations like 'jq' reads, as it can mask important issues such as malformed files or permission errors, making debugging difficult.

Comment on lines +401 to +405
token_file=$(create_app_token "$repo" "$permissions" "$ttl" 2>/dev/null) && {
log_token "INFO" "Strategy: GitHub App installation token (enforced scoping)"
printf '%s' "$token_file"
return 0
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Suppressing stderr from create_app_token with 2>/dev/null prevents any of its diagnostic logs from being displayed. Since create_app_token contains important logging for debugging its internal steps (like JWT generation and API calls), these logs should be visible when this strategy is attempted.

Suggested change
token_file=$(create_app_token "$repo" "$permissions" "$ttl" 2>/dev/null) && {
log_token "INFO" "Strategy: GitHub App installation token (enforced scoping)"
printf '%s' "$token_file"
return 0
}
token_file=$(create_app_token "$repo" "$permissions" "$ttl") && {
log_token "INFO" "Strategy: GitHub App installation token (enforced scoping)"
printf '%s' "$token_file"
return 0
}
References
  1. Avoid using '2>/dev/null' for blanket suppression of command errors in shell scripts to ensure that authentication, syntax, or system issues remain visible for debugging.

@marcusquinn marcusquinn merged commit 28e1854 into main Mar 7, 2026
27 checks passed
@marcusquinn marcusquinn deleted the feature/t1412.2-scoped-tokens branch March 7, 2026 12:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

t1412.2: Scoped short-lived GitHub tokens

1 participant