Skip to content

feat(security): add max-security OpenCode GitHub AI agent integration#18

Merged
marcusquinn merged 1 commit intomainfrom
feature/github-ai-agent-security
Jan 9, 2026
Merged

feat(security): add max-security OpenCode GitHub AI agent integration#18
marcusquinn merged 1 commit intomainfrom
feature/github-ai-agent-security

Conversation

@marcusquinn
Copy link
Copy Markdown
Owner

@marcusquinn marcusquinn commented Jan 9, 2026

Summary

Implements security-hardened GitHub Actions workflow for AI-powered issue resolution, inspired by oh-my-opencode's sisyphus-dev-ai approach but with comprehensive security controls to mitigate prompt injection and unauthorized access risks.

Security Features

Layer Protection
User validation OWNER/MEMBER/COLLABORATOR only
Label gate ai-approved required on issues
Pattern detection Blocks 15+ prompt injection patterns
Audit logging All invocations logged with context
Rate limiting Concurrency control, one at a time
Timeout 15-minute max execution
Permissions Minimal required only
System prompt Explicit forbidden actions

Threat Model

Mitigates:

  • Prompt injection via issues/comments
  • Unauthorized command execution
  • Credential exfiltration attempts
  • Workflow tampering
  • Resource exhaustion (API credit burning)

Files Changed

File Change
.github/workflows/opencode-agent.yml NEW - Secure workflow (265 lines)
.agent/tools/git/opencode-github-security.md NEW - Security documentation (349 lines)
.agent/tools/git/opencode-github.md Updated - Added security section
.agent/scripts/opencode-github-setup-helper.sh Updated - Added create-secure and create-labels commands
TODO.md Updated - Marked t028 complete

Quick Setup

# Create secure workflow
~/.aidevops/agents/scripts/opencode-github-setup-helper.sh create-secure

# Create required labels
~/.aidevops/agents/scripts/opencode-github-setup-helper.sh create-labels

# Add API key (manual)
# Repository → Settings → Secrets → ANTHROPIC_API_KEY

Testing

  • ShellCheck passes on helper script
  • Markdownlint passes on documentation
  • No secrets detected in new files

Closes t028

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced secure workflow setup command with hardened configurations and comprehensive setup guidance
    • Added command to create required security labels for workflow governance
  • Documentation

    • New comprehensive security guide detailing threat models, access controls, and operational safeguards
    • Updated GitHub integration documentation with security hardening recommendations and quick setup instructions

✏️ Tip: You can customize this high-level summary in your review settings.

Implement security-hardened GitHub Actions workflow for AI-powered issue
resolution, inspired by oh-my-opencode's sisyphus-dev-ai approach but with
comprehensive security controls.

Security features:
- Trusted users only (OWNER/MEMBER/COLLABORATOR)
- 'ai-approved' label required on issues before AI processing
- Prompt injection pattern detection (15+ suspicious patterns)
- Audit logging of all invocations with full context
- Rate limiting via concurrency controls
- 15-minute timeout to prevent runaway sessions
- Minimal permissions (no actions/packages/deployments access)
- Security-focused system prompt with explicit forbidden actions

New files:
- .github/workflows/opencode-agent.yml - Secure workflow
- .agent/tools/git/opencode-github-security.md - Full security docs

Updated:
- opencode-github-setup-helper.sh - Added create-secure and create-labels
- opencode-github.md - Added security hardening section

Closes t028
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jan 9, 2026

Walkthrough

This PR introduces a comprehensive security hardening system for the OpenCode GitHub AI agent integration. It adds a security-focused workflow with validation checks, audit logging, and command restriction enforcement; new setup helper commands for creating secure workflows and labels; and detailed security documentation outlining threat models, mitigations, and operational guidance.

Changes

Cohort / File(s) Summary
Setup Helper Script
.agent/scripts/opencode-github-setup-helper.sh
Adds three new public commands: create-secure generates security-hardened workflows (copied from template or generated inline), create-labels creates required GitHub labels (ai-approved, security-review), and extends base workflow creation with security guidance. Introduces cmd_create_secure_workflow(), create_secure_workflow_inline(), and cmd_create_labels() functions with validation and error handling.
Security Documentation
.agent/tools/git/opencode-github-security.md, .agent/tools/git/opencode-github.md
Creates new comprehensive security guide covering threat model, mitigations, access controls, label schemes, secrets handling, branch protection, and incident response. Updates existing GitHub integration docs with "Security Hardening (Recommended)" section referencing the new security implementation.
Agent Workflow
.github/workflows/opencode-agent.yml
Introduces new GitHub Actions workflow with three main jobs: security-check validates triggers, user trust levels, labels, and scans for suspicious command patterns; audit-log records structured audit data; opencode-agent executes the AI agent only if security checks pass, with restricted permissions and security-focused system prompts. Includes separate security-blocked job for warning on rejection.
Task Tracking
TODO.md
Marks task t028 as completed with notes documenting implementation of secure OpenCode GitHub integration, workflow creation, label requirements, and audit logging.

Sequence Diagram

sequenceDiagram
    actor User
    participant GitHub as GitHub Event
    participant SecurityCheck as security-check Job
    participant AuditLog as audit-log Job
    participant Agent as opencode-agent Job
    
    User->>GitHub: Trigger /oc or /opencode
    GitHub->>SecurityCheck: Workflow triggered
    SecurityCheck->>SecurityCheck: Validate trigger patterns
    SecurityCheck->>SecurityCheck: Check user trust level
    SecurityCheck->>SecurityCheck: Verify ai-approved label
    SecurityCheck->>SecurityCheck: Scan for suspicious patterns
    
    alt Security validation passes
        SecurityCheck-->>AuditLog: allowed = true
        SecurityCheck-->>Agent: allowed = true
        AuditLog->>AuditLog: Record audit log entry
        Agent->>Agent: Execute with restricted permissions
        Agent-->>GitHub: Post completion reaction
    else Security validation fails
        SecurityCheck-->>GitHub: Post security warning
        SecurityCheck-->>GitHub: Add security-review label
        GitHub->>GitHub: Block execution
    end
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly Related PRs

Poem

🔐 A fortress built in workflows bright,
With labels, checks, and audit light,
The AI agent now stands tall and true,
Security-hardened through and through! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding security-hardened OpenCode GitHub AI agent integration with comprehensive controls.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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
Copy Markdown

Summary of Changes

Hello @marcusquinn, 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 enhances the security posture of the OpenCode GitHub AI agent integration. It focuses on creating a secure and controlled environment for AI-powered issue resolution by implementing a multi-layered defense strategy within a GitHub Actions workflow. The changes ensure that AI operations are restricted to trusted users, approved contexts, and are protected against common vulnerabilities like prompt injection, thereby fostering a safer and more reliable automated development process.

Highlights

  • Max-Security AI Agent Integration: Introduces a new GitHub Actions workflow for the OpenCode AI agent with comprehensive security controls to mitigate prompt injection and unauthorized access risks.
  • Robust Security Features: Implements user validation (OWNER/MEMBER/COLLABORATOR only), an 'ai-approved' label gate for issues, detection of 15+ prompt injection patterns, audit logging, rate limiting, a 15-minute timeout, and minimal required permissions.
  • Enhanced Setup Helper Script: The opencode-github-setup-helper.sh script now includes create-secure to deploy the hardened workflow and create-labels to set up the necessary ai-approved and security-review GitHub labels.
  • Comprehensive Security Documentation: A new markdown file, .agent/tools/git/opencode-github-security.md, provides detailed documentation on the threat model, attack vectors mitigated, security configurations, workflow deep dive, usage guide, monitoring, and incident response.
Ignored Files
  • Ignored by pattern: .github/workflows/** (1)
    • .github/workflows/opencode-agent.yml
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.

@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud bot commented Jan 9, 2026

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Jan 9, 2026

🔍 Code Quality Report

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

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

�[0;34m[INFO]�[0m Recent monitoring activity:
Fri Jan 9 01:32:52 UTC 2026: Code review monitoring started
Fri Jan 9 01:32:53 UTC 2026: SonarCloud - Bugs: 0, Vulnerabilities: 0, Code Smells: 223
Fri Jan 9 01:32:53 UTC 2026: Qlty - 0 issues found, auto-formatting applied
Fri Jan 9 01:32:55 UTC 2026: Codacy analysis completed with auto-fixes

📈 Current Quality Metrics

  • BUGS: 0
  • CODE SMELLS: 223
  • VULNERABILITIES: 0

Generated on: Fri Jan 9 01:33:29 UTC 2026


Generated by AI DevOps Framework Code Review Monitoring

Copy link
Copy Markdown

@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 comprehensive, security-hardened GitHub Actions workflow for an AI agent, complete with setup scripts and detailed documentation. The security model is well-thought-out, incorporating multiple layers of protection like user validation, label gating, and prompt injection detection. My review focuses on enhancing the robustness of the setup script, ensuring the implementation matches the documentation, and adhering to security best practices for GitHub Actions. I've provided suggestions to address a few issues, including pinning the action version for better security and aligning the implemented prompt injection patterns with the more extensive list in the documentation.

Comment on lines +610 to +617
const suspiciousPatterns = [
/ignore\s+(previous|all|prior)\s+(instructions?|prompts?)/i,
/system\s*prompt/i,
/\bsudo\b/i,
/rm\s+-rf/i,
/\.env\b/i,
/password|secret|token|credential/i,
];
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

The list of suspiciousPatterns implemented here is significantly shorter than the one documented in .agent/tools/git/opencode-github-security.md. This discrepancy gives a false sense of security. The implementation should be updated to include all documented patterns to provide the advertised protection against prompt injection.

Suggested change
const suspiciousPatterns = [
/ignore\s+(previous|all|prior)\s+(instructions?|prompts?)/i,
/system\s*prompt/i,
/\bsudo\b/i,
/rm\s+-rf/i,
/\.env\b/i,
/password|secret|token|credential/i,
];
const suspiciousPatterns = [
/ignore\s+(previous|all|prior)\s+(instructions?|prompts?)/i,
/system\s*prompt/i,
/\bsudo\b/i,
/rm\s+-rf/i,
/curl\s+.*\|\s*(ba)?sh/i,
/eval\s*\(/i,
/exec\s*\(/i,
/__import__/i,
/os\.system/i,
/subprocess/i,
/ssh[_-]?key/i,
/authorized[_-]?keys/i,
/\.env\b/i,
/password|secret|token|credential/i,
/base64\s+(decode|encode)/i,
];

with:
fetch-depth: 1

- uses: sst/opencode/github@latest
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

Using sst/opencode/github@latest is a significant security and reliability risk, as it can automatically pull in breaking or malicious changes. It is a security best practice to pin actions to a specific, trusted version via a tag or, for maximum security, a commit SHA.

Suggested change
- uses: sst/opencode/github@latest
- uses: sst/opencode/github@v1 # Pin to a specific version

fi

# Check if aidevops has the template
local template_path="$HOME/.aidevops/agents/scripts/../../../.github/workflows/opencode-agent.yml"
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The local variable template_path is declared but never used. It should be removed to improve code clarity and maintainability.


# Check if aidevops has the template
local template_path="$HOME/.aidevops/agents/scripts/../../../.github/workflows/opencode-agent.yml"
local aidevops_template="$HOME/Git/aidevops/.github/workflows/opencode-agent.yml"
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The path for aidevops_template is hardcoded to $HOME/Git/aidevops/.... This is brittle as it assumes a specific local directory structure that may not exist for all users, causing this check to fail. While there is a fallback, it would be more robust to make this path configurable, for example, by checking for an environment variable first.

with:
script: |
const comment = context.payload.comment;
const sender = context.payload.sender;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The constant sender is declared but its value is never used. It should be removed to keep the code clean and avoid confusion.


```bash
# Copy the secure workflow
cp .github/workflows/opencode-agent.yml .github/workflows/opencode.yml
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The command cp .github/workflows/opencode-agent.yml .github/workflows/opencode.yml is confusing. The helper script creates opencode-agent.yml as a separate, secure workflow. This command suggests overwriting the basic opencode.yml workflow, which may not be the user's intent and could cause confusion. It would be clearer to instruct users to use the opencode-github-setup-helper.sh create-secure command and explain the purpose of the generated opencode-agent.yml file.

@augmentcode
Copy link
Copy Markdown

augmentcode bot commented Jan 9, 2026

🤖 Augment PR Summary

Summary: Adds a “max-security” OpenCode GitHub Actions integration to let collaborators invoke an AI agent via /oc or /opencode while reducing prompt-injection and abuse risk.

Changes:

  • Added .github/workflows/opencode-agent.yml with a security gate, audit logging, concurrency rate limiting, and a 15‑minute timeout.
  • Restricted execution to trusted user associations (OWNER/MEMBER/COLLABORATOR) and required an ai-approved label on issues.
  • Implemented suspicious-pattern scanning to block risky requests and auto-apply security-review.
  • Extended .agent/scripts/opencode-github-setup-helper.sh with create-secure and create-labels commands.
  • Added .agent/tools/git/opencode-github-security.md and linked it from the base OpenCode GitHub guide.

Technical Notes: Uses actions/github-script for validation/logging and sst/opencode/github to run Claude Sonnet; TODO t028 is marked complete.

🤖 Was this summary useful? React with 👍 or 👎

Copy link
Copy Markdown

@augmentcode augmentcode bot left a comment

Choose a reason for hiding this comment

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

Review completed. 5 suggestions posted.

Fix All in Augment

Comment augment review to trigger a new review at any time.

script: |
const comment = context.payload.comment;
const sender = context.payload.sender;
const issue = context.payload.issue;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

For pull_request_review_comment events, context.payload.issue is not present (payload uses pull_request / review objects), so this will throw and prevent the workflow from running on review comments. Consider either handling both event payload shapes or dropping the pull_request_review_comment trigger to avoid unexpected failures.

Fix This in Augment

🤖 Was this useful? React with 👍 or 👎

with:
script: |
const issue = context.payload.issue;
await github.rest.reactions.createForIssueComment({
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

These reaction calls use reactions.createForIssueComment, but the pull_request_review_comment trigger provides a PR review comment ID, not an issue comment ID, so this step will fail for that event type. If review comments are in scope, the reactions API needs to match the comment type.

Fix This in Augment

🤖 Was this useful? React with 👍 or 👎

core.setOutput('reason', `User ${sender.login} has association '${association}', requires: ${trustedAssociations.join(', ')}`);

// Post warning comment
await github.rest.issues.createComment({
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

security-check calls github.rest.issues.createComment/addLabels, which requires issues: write on GITHUB_TOKEN; if repo defaults are read-only, the gate will fail and potentially block all runs. Consider setting explicit minimal permissions: on security-check (and audit-log if needed) so behavior doesn’t depend on repo-level defaults.

Fix This in Augment

🤖 Was this useful? React with 👍 or 👎

fi

# Check if aidevops has the template
local template_path="$HOME/.aidevops/agents/scripts/../../../.github/workflows/opencode-agent.yml"
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

In cmd_create_secure_workflow, template_path is defined but never used, and the only checked template location is $HOME/Git/aidevops/..., so many installs may fall back to create_secure_workflow_inline. That inline workflow omits features this command advertises (e.g., audit logging and a larger suspicious-pattern set), which could lead to weaker security than expected.

Fix This in Augment

🤖 Was this useful? React with 👍 or 👎

**Mitigations**:
- System prompt forbids accessing credential files
- Pattern detection blocks requests mentioning secrets/tokens/passwords
- No network access beyond GitHub API
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The statement “No network access beyond GitHub API” is misleading for GitHub Actions runners, which typically have outbound network access unless additionally constrained. Consider rephrasing to reflect that exfiltration is mitigated mainly by policy/pattern checks, not by a hard network sandbox.

Fix This in Augment

🤖 Was this useful? React with 👍 or 👎

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Fix all issues with AI agents
In @.agent/scripts/opencode-github-setup-helper.sh:
- Around line 504-516: Remove the unused variable and avoid brittle hardcoded
paths: delete the unused template_path variable declaration and change the
lookup for the aidevops template (aidevops_template) to be configurable or
discoverable (e.g., respect an env var like AIDEVOPS_DIR or search common
locations) before falling back to create_secure_workflow_inline; keep the
existing copy-and-print_success behavior when a valid template is found and
ensure create_secure_workflow_inline is used as the fallback.

In @.github/workflows/opencode-agent.yml:
- Line 213: Replace the mutable action reference "uses:
sst/opencode/github@latest" with an immutable commit SHA (e.g., "uses:
sst/opencode/github@<commit-sha>"); locate the line containing uses:
sst/opencode/github@latest, look up the desired commit SHA in the sst/opencode
GitHub repo, update the workflow to pin to that SHA, and add a short inline
comment recording the chosen SHA and why it was pinned for future
maintainability.
🧹 Nitpick comments (1)
.agent/scripts/opencode-github-setup-helper.sh (1)

736-754: Help text updated but examples section is incomplete.

The Commands section correctly documents the new commands with (recommended) for create-secure. However, the Examples section (lines 741-749) still only shows the basic commands—adding examples for the new security-focused workflow would improve discoverability.

📝 Add examples for new commands
   # Create workflow file
   opencode-github-setup-helper.sh create-workflow

+  # Create security-hardened workflow (recommended for production)
+  opencode-github-setup-helper.sh create-secure
+
+  # Create required labels for secure workflow
+  opencode-github-setup-helper.sh create-labels
+
 For more information:
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2d22f73 and d3c8f55.

📒 Files selected for processing (5)
  • .agent/scripts/opencode-github-setup-helper.sh
  • .agent/tools/git/opencode-github-security.md
  • .agent/tools/git/opencode-github.md
  • .github/workflows/opencode-agent.yml
  • TODO.md
🧰 Additional context used
📓 Path-based instructions (2)
**/*.md

📄 CodeRabbit inference engine (AGENTS.md)

Use placeholders in examples and note secure storage location in documentation

Files:

  • TODO.md
.agent/scripts/*.sh

⚙️ CodeRabbit configuration file

.agent/scripts/*.sh: Automation scripts - focus on:

  • Reliability and robustness
  • Clear logging and feedback
  • Proper exit codes
  • Error recovery mechanisms

Files:

  • .agent/scripts/opencode-github-setup-helper.sh
🧠 Learnings (9)
📓 Common learnings
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: templates/home/AGENTS.md:0-0
Timestamp: 2025-12-22T01:24:53.937Z
Learning: Follow all security protocols and working directory specifications defined in ~/Git/aidevops/AGENTS.md
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: templates/home/git/AGENTS.md:0-0
Timestamp: 2025-12-22T01:25:03.138Z
Learning: Follow security protocols for all git and DevOps operations
📚 Learning: 2025-11-29T04:34:27.158Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-29T04:34:27.158Z
Learning: All instructions, documentation, and operational guidance should be maintained in AGENTS.md as the single source of truth

Applied to files:

  • .agent/tools/git/opencode-github-security.md
📚 Learning: 2025-11-29T04:34:30.742Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: GEMINI.md:0-0
Timestamp: 2025-11-29T04:34:30.742Z
Learning: Maintain all instructions, documentation, and operational guidance in AGENTS.md as the single source of truth

Applied to files:

  • .agent/tools/git/opencode-github-security.md
📚 Learning: 2025-11-29T04:34:42.033Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: AGENT.md:0-0
Timestamp: 2025-11-29T04:34:42.033Z
Learning: Maintain all AI assistant instructions, documentation, and operational guidance in AGENTS.md as the single source of truth

Applied to files:

  • .agent/tools/git/opencode-github-security.md
📚 Learning: 2025-11-29T04:34:42.033Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: AGENT.md:0-0
Timestamp: 2025-11-29T04:34:42.033Z
Learning: Reference AGENTS.md (authoritative) instead of AGENT.md for AI assistant guidance

Applied to files:

  • .agent/tools/git/opencode-github-security.md
📚 Learning: 2025-12-22T01:24:53.937Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: templates/home/AGENTS.md:0-0
Timestamp: 2025-12-22T01:24:53.937Z
Learning: Follow all security protocols and working directory specifications defined in ~/Git/aidevops/AGENTS.md

Applied to files:

  • .agent/tools/git/opencode-github-security.md
  • .agent/tools/git/opencode-github.md
  • .agent/scripts/opencode-github-setup-helper.sh
  • .github/workflows/opencode-agent.yml
📚 Learning: 2025-12-22T01:25:03.138Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: templates/home/git/AGENTS.md:0-0
Timestamp: 2025-12-22T01:25:03.138Z
Learning: Follow security protocols for all git and DevOps operations

Applied to files:

  • .agent/tools/git/opencode-github-security.md
  • .agent/tools/git/opencode-github.md
  • .agent/scripts/opencode-github-setup-helper.sh
📚 Learning: 2025-12-22T01:24:53.937Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: templates/home/AGENTS.md:0-0
Timestamp: 2025-12-22T01:24:53.937Z
Learning: Reference the authoritative repository at ~/Git/aidevops/ for all detailed AI assistant instructions and configurations

Applied to files:

  • .agent/tools/git/opencode-github-security.md
  • .agent/tools/git/opencode-github.md
📚 Learning: 2025-12-22T01:24:53.937Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: templates/home/AGENTS.md:0-0
Timestamp: 2025-12-22T01:24:53.937Z
Learning: Never store credentials in working directories (~/.aidevops/.agent-workspace/), Git repositories, home directory root, or hardcoded in code and scripts

Applied to files:

  • .agent/tools/git/opencode-github.md
🪛 GitHub Check: Codacy Static Code Analysis
.github/workflows/opencode-agent.yml

[warning] 213-213: .github/workflows/opencode-agent.yml#L213
An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release.

🪛 LanguageTool
TODO.md

[uncategorized] ~77-~77: The official name of this software platform is spelled with a capital “H”.
Context: ...ion with max security approach. Created .github/workflows/opencode-agent.yml with trus...

(GITHUB)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (19)
TODO.md (1)

76-77: ✓ Task completion properly documented.

Task t028 is correctly marked complete with timestamp and detailed implementation notes. The Notes block clearly describes the security hardening approach (trusted-user-only access, label gate, pattern detection, audit logging, 15-min timeout) and references the new workflow, documentation, and updated helper script.

.agent/tools/git/opencode-github.md (3)

271-283: ✓ Trusted-user validation condition is well-structured.

The YAML conditional properly restricts execution to OWNER/MEMBER/COLLABORATOR authors. Uses correct GitHub Actions context variable (github.event.comment.author_association) and clear boolean logic. This is a solid baseline security gate before enabling AI command execution.


292-301: ✓ Quick setup provides clear, actionable steps.

The copy and label-creation commands are concise and immediately useful. Assumes GitHub CLI (gh) availability, which is reasonable given the GitHub-first context. The label colors (green for approved, red for security review) provide intuitive visual distinction.


324-324: ✓ Related link properly cross-references security documentation.

The addition of the security hardening guide link maintains consistency with other "Related" entries and provides clear navigation path for readers needing deeper security details.

.agent/tools/git/opencode-github-security.md (8)

37-100: ✓ Threat model is comprehensive and addresses realistic attack vectors.

Five well-articulated attack scenarios (prompt injection, unauthorized execution, credential exfiltration, workflow tampering, resource exhaustion) with corresponding mitigations. The residual risk table appropriately acknowledges that novel injection attempts and compromised collaborators remain possible—reflecting realistic security posture vs. false assurance.


102-141: ✓ Security configuration properly scoped and documented.

Labels are well-defined with clear purposes. Secrets configuration correctly advises storing only ANTHROPIC_API_KEY and explicitly warns against adding Personal Access Tokens or deployment credentials—aligned with credential storage principles. Branch protection checklist ensures human review gates AI-generated PRs.


164-180: ✓ Pattern detection list is comprehensive and well-targeted.

Fifteen regex patterns span critical attack categories: prompt injection (ignore/system prompt), privilege escalation (sudo, rm -rf, curl|bash), code execution (eval, exec, imports), credential access (ssh_key, .env, passwords), and encoding (base64). Each pattern addresses real threat vectors without obvious false-positive triggers.


206-219: ✓ Permission model enforces least-privilege with explicit denials.

Grants only essential permissions (contents:write for commits, pull-requests/issues:write for feedback, id-token:write for OpenCode auth). Explicitly denies actions, packages, security-events, deployments, and secrets—preventing workflow tampering and privilege escalation. Good security discipline.


186-202: ✓ Audit logging captures full invocation context.

JSON structure includes all critical fields: timestamp, event type, allowed/denied flag, user identity, user association level, issue number, command text, and Actions run URL. This enables thorough forensic review and detection of suspicious patterns over time.


221-270: ✓ Usage guide effectively educates users on expected behavior.

Separated guidance for maintainers (approval workflow), collaborators (safe vs. blocked commands with examples), and external contributors (clear explanation of restriction). Concrete examples of blocked patterns (prompt injection, credential access, workflow tampering) help teams understand the security boundaries without requiring deep threat modeling knowledge.


301-332: ✓ Incident response provides clear operational playbook.

Five-step procedure (disable workflow → investigate logs → contain commits → rotate API key → document) covers immediate action through remediation. Specific gh commands (gh workflow disable, gh run list, git revert) eliminate ambiguity about what to execute during an incident. Proper handling of compromised API keys (immediate rotation in Anthropic dashboard, GitHub Secrets update).


164-180: Implementation verified — all 15 suspicious patterns are correctly implemented in the security-check job within .github/workflows/opencode-agent.yml and match the documentation exactly.

No action required.

.github/workflows/opencode-agent.yml (4)

1-25: Well-structured workflow foundation with proper concurrency controls.

The header documentation clearly outlines security features, and the concurrency configuration with cancel-in-progress: false correctly ensures queued jobs wait rather than getting cancelled—critical for reliable AI agent operations.


88-128: Comprehensive prompt injection detection patterns.

The suspicious pattern list covers key attack vectors: prompt injection phrases, shell command execution, credential keywords, and code injection patterns. The automatic security-review label addition creates a solid audit trail for maintainers.

Consider adding patterns for wget pipe-to-shell and gh auth token extraction attempts in future iterations:

/wget\s+.*\|\s*(ba)?sh/i,
/gh\s+auth\s+token/i,

256-265: Clean notification mechanism for blocked requests.

The ::warning:: annotation ensures blocked requests are visible in the Actions UI without creating noise. This complements the audit-log job well.


183-183: No action required — id-token: write is correctly configured.

The SST OpenCode GitHub Action documentation explicitly requires permissions: id-token: write for OIDC authentication with the OpenCode backend. The workflow correctly implements least-privilege by only granting necessary permissions (contents, pull-requests, issues, id-token) while explicitly denying dangerous capabilities (actions, packages, security-events, deployments). The permission is not unused—it is essential for the OpenCode action to function.

Likely an incorrect or invalid review comment.

.agent/scripts/opencode-github-setup-helper.sh (3)

479-483: Good guidance steering users toward secure configuration.

Proactively warning users about the basic workflow and recommending create-secure for production use is excellent UX that promotes security-first practices.


700-712: Robust label creation with graceful handling of existing labels.

Good error recovery pattern: attempting creation and handling "already exists" as a warning rather than failure. The color choices (green for approved, red-orange for security-review) provide intuitive visual cues.

One minor enhancement: could use gh label list --search to check existence first for cleaner output, but the current approach works reliably.


779-784: Consistent command routing with intuitive aliases.

The pattern of command|shorthand matches the existing style (check|status, setup|install). The aliases secure and labels are discoverable and memorable.

Comment on lines +504 to +516
# Check if aidevops has the template
local template_path="$HOME/.aidevops/agents/scripts/../../../.github/workflows/opencode-agent.yml"
local aidevops_template="$HOME/Git/aidevops/.github/workflows/opencode-agent.yml"

mkdir -p .github/workflows

if [[ -f "$aidevops_template" ]]; then
cp "$aidevops_template" .github/workflows/opencode-agent.yml
print_success "Copied secure workflow from aidevops template"
else
# Create inline if template not found
create_secure_workflow_inline
fi
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Unused variable and fragile path assumptions.

Line 505 defines template_path but it's never used—only aidevops_template is checked. Additionally, hardcoding $HOME/Git/aidevops/ assumes a specific directory structure that may not exist for all users.

🧹 Remove unused variable and document path assumption
     # Check if aidevops has the template
-    local template_path="$HOME/.aidevops/agents/scripts/../../../.github/workflows/opencode-agent.yml"
+    # Template location assumes standard aidevops installation at ~/Git/aidevops
     local aidevops_template="$HOME/Git/aidevops/.github/workflows/opencode-agent.yml"
     
     mkdir -p .github/workflows
     
     if [[ -f "$aidevops_template" ]]; then
         cp "$aidevops_template" .github/workflows/opencode-agent.yml
         print_success "Copied secure workflow from aidevops template"
     else
-        # Create inline if template not found
+        # Create inline if template not found (fallback for non-standard installations)
         create_secure_workflow_inline
     fi
🤖 Prompt for AI Agents
In @.agent/scripts/opencode-github-setup-helper.sh around lines 504 - 516,
Remove the unused variable and avoid brittle hardcoded paths: delete the unused
template_path variable declaration and change the lookup for the aidevops
template (aidevops_template) to be configurable or discoverable (e.g., respect
an env var like AIDEVOPS_DIR or search common locations) before falling back to
create_secure_workflow_inline; keep the existing copy-and-print_success behavior
when a valid template is found and ensure create_secure_workflow_inline is used
as the fallback.

Comment on lines +610 to +617
const suspiciousPatterns = [
/ignore\s+(previous|all|prior)\s+(instructions?|prompts?)/i,
/system\s*prompt/i,
/\bsudo\b/i,
/rm\s+-rf/i,
/\.env\b/i,
/password|secret|token|credential/i,
];
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Inline workflow has fewer security patterns than the main workflow.

The inline fallback only includes 6 suspicious patterns compared to 15 in the main opencode-agent.yml. This creates an inconsistent security posture depending on installation method.

Additionally, line 652 uses @latest which should be pinned (same issue as the main workflow).

Consider either:

  1. Keeping the inline version in sync with the main workflow's pattern list
  2. Documenting that the inline version is a minimal subset, with guidance to upgrade

For the @latest issue, apply the same fix as recommended for the main workflow file.

Also applies to: 652-652

Comment on lines +149 to +150
const allowed = '${{ needs.security-check.outputs.allowed }}';
const reason = '${{ needs.security-check.outputs.reason }}';
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Potential script injection via unescaped output interpolation.

The reason output is interpolated directly into JavaScript code with single quotes. If reason ever contains a single quote (e.g., from user input in the future), it could break the script or introduce injection.

🔧 Safer approach using environment variables
       uses: actions/github-script@v7
+      env:
+        ALLOWED: ${{ needs.security-check.outputs.allowed }}
+        REASON: ${{ needs.security-check.outputs.reason }}
       with:
         script: |
           const comment = context.payload.comment;
           const sender = context.payload.sender;
           const issue = context.payload.issue;
-          const allowed = '${{ needs.security-check.outputs.allowed }}';
-          const reason = '${{ needs.security-check.outputs.reason }}';
+          const allowed = process.env.ALLOWED;
+          const reason = process.env.REASON;

});

- name: Run OpenCode Agent
uses: sst/opencode/github@latest
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

GitHub actions security best practices pinning commit SHA

💡 Result:

Key points & practical best practices for SHA‑pinning GitHub Actions

  • Pin third‑party actions to the full commit SHA (not tags or short SHAs). This makes the action immutably referenceable. [1][2]
  • Verify the SHA comes from the action’s original repository (not a fork) and record the human‑readable tag/version in a comment for ease of review. [1][3]
  • Enforce SHA pinning via GitHub’s “allowed actions & reusable workflows” policy at repo/org/enterprise level (supports blocking entries and SHA‑pin enforcement). [4]
  • Audit the action’s source (look for exfiltration, logging of secrets, unpinned transitive deps) and prefer “verified” maintainers on Marketplace. Use Dependabot/Dependabot alerts to surface updates. [1][6]
  • Be aware of limits: SHA pinning only guarantees the pinned repo snapshot. Actions that pull dynamic code or have unpinned/transitive dependencies (“unpinnable” actions) can still introduce risk — audit or avoid those, or vendor/fork and pin their dependencies. Research shows many supply‑chain incidents exploit transitive or dynamic dependencies. [5][2]
  • Mitigations beyond pinning: fork trusted actions into an org you control and pin those SHAs; use self‑hosted/isolated runners for sensitive jobs; restrict GITHUB_TOKEN and job permissions to least privilege; require PR approvals or protected environments for workflows that use secrets. [7][1][6]

If you’d like, I can:

  • scan one of your workflow files and mark which actions are unpinned or likely “unpinnable,” or
  • generate a checklist/policy snippet to enforce SHA pinning and least‑privilege permissions in your org.

🏁 Script executed:

#!/bin/bash
# Check the actual file content to confirm the line and action
cat -n .github/workflows/opencode-agent.yml | sed -n '210,220p'

Repository: marcusquinn/aidevops

Length of output: 513


🌐 Web query:

sst/opencode/github action GitHub marketplace

💡 Result:

Yes — sst/opencode publishes a GitHub Action you can use from the Marketplace (or directly from the repo). Install/use via:

  • Repository and action: sst/opencode (actions and the action package sst/opencode/github). [1]
  • Docs with example workflow and inputs (example .github/workflows/opencode.yml using uses: sst/opencode/github@latest). [2]

References

  1. GitHub repo (sst/opencode) — actions page. [1]
  2. OpenCode GitHub docs — GitHub Actions usage and workflow example. [2]

🏁 Script executed:

#!/bin/bash
# Check if there are any version tags or releases referenced for this action elsewhere in the repo
rg "sst/opencode" --type yaml --type yml -A 2 -B 2

Repository: marcusquinn/aidevops

Length of output: 91


🏁 Script executed:

#!/bin/bash
# Search for sst/opencode references in workflow files
rg "sst/opencode" .github/workflows/ -A 2 -B 2

Repository: marcusquinn/aidevops

Length of output: 404


🏁 Script executed:

#!/bin/bash
# Check if there are any pinned versions or SHAs for other actions in this workflow file
cat -n .github/workflows/opencode-agent.yml | grep "uses:" | head -20

Repository: marcusquinn/aidevops

Length of output: 336


Pin third-party action to a commit SHA for supply chain security.

The sst/opencode/github@latest tag is mutable and can change without notice, potentially introducing vulnerabilities or breaking changes. This workflow has elevated permissions and uses the ANTHROPIC_API_KEY secret, making supply chain security critical. Pinning to a commit SHA ensures immutable, auditable action execution.

🔒 Pin to a specific commit SHA
      - name: Run OpenCode Agent
-       uses: sst/opencode/github@latest
+       uses: sst/opencode/github@<COMMIT_SHA>  # Pin to specific version for supply chain security
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

To find the current commit SHA, check the sst/opencode repository and record the SHA of the desired release tag in a comment for maintainability.

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Check: Codacy Static Code Analysis

[warning] 213-213: .github/workflows/opencode-agent.yml#L213
An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release.

🤖 Prompt for AI Agents
In @.github/workflows/opencode-agent.yml at line 213, Replace the mutable action
reference "uses: sst/opencode/github@latest" with an immutable commit SHA (e.g.,
"uses: sst/opencode/github@<commit-sha>"); locate the line containing uses:
sst/opencode/github@latest, look up the desired commit SHA in the sst/opencode
GitHub repo, update the workflow to pin to that SHA, and add a short inline
comment recording the chosen SHA and why it was pinned for future
maintainability.

@marcusquinn marcusquinn merged commit 717dd39 into main Jan 9, 2026
26 of 33 checks passed
@marcusquinn marcusquinn deleted the feature/github-ai-agent-security branch January 9, 2026 01:52
marcusquinn added a commit that referenced this pull request Mar 8, 2026
…ecurity

Update from stale SHA (0cf0294, Jan 2026) to latest release v1.2.21
(a52d640, Mar 7 2026). Replace misleading '# latest' comment with
actual version tag for maintainability.

Addresses CodeRabbit + Codacy findings from PR #18.

Closes #3814
marcusquinn added a commit that referenced this pull request Mar 8, 2026
…ecurity (#3824)

Update from stale SHA (0cf0294, Jan 2026) to latest release v1.2.21
(a52d640, Mar 7 2026). Replace misleading '# latest' comment with
actual version tag for maintainability.

Addresses CodeRabbit + Codacy findings from PR #18.

Closes #3814
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.

1 participant