Fastest Path: rafter ci init
Auto-generate CI config for GitHub Actions, GitLab CI, or CircleCI:
.github/workflows/rafter-security.yml for GitHub, with equivalent paths for GitLab CI and CircleCI). Review it, push, done.
--with-backend is a deprecated alias for --with-remote kept for old invocations. Use --with-remote.Two CI Modes
Rafter supports two approaches in CI. Choose based on whether you have a Rafter API key.Mode 1: Local Secret Scanning (no API key required)
Usesrafter secrets — the fast, deterministic scanner that runs pattern matching and Betterleaks secret detection (v0.8.0+; gitleaks successor) directly on the runner. Same inputs, same findings, every time.
1 fails the pipeline if secrets are detected. No account or API key needed.
When to use: Open-source projects, teams without a Rafter subscription, or any repo where fast secret scanning at commit time is enough.
Mode 2: Backend Code Analysis (API key required)
Usesrafter run to trigger the Rafter code analysis engine for full SAST coverage — a wider range of vulnerability classes beyond secrets. Your code is deleted immediately after the analysis engine completes.
When to use: Teams with a Rafter subscription who want full SAST coverage on every push.
See Step 3 below for the complete workflow.
Introduction
Automated security scanning transforms security from an afterthought into a seamless part of your development workflow. Instead of remembering to run scans manually (and inevitably forgetting), your CI/CD pipeline automatically checks every commit and pull request for vulnerabilities. This guide shows you two approaches:- Manual setup: Step-by-step instructions for hands-on configuration
- AI-assisted setup: Copy-paste workflows with AI prompts for rapid deployment
Why Automated Security Scanning Matters
The Manual Scanning Problem
Manual security scanning has three critical flaws:- Human Error: Developers forget to run scans, especially under pressure
- Inconsistent Coverage: Different team members use different tools or settings
- Late Detection: Vulnerabilities are found after code reaches production
The Automated Solution
Automated scanning eliminates these problems by:- Running on every push: No forgotten scans
- Consistent configuration: Same rules applied every time
- Early detection: Vulnerabilities caught before deployment
- Build failure: Critical issues block deployment automatically
Understanding API Keys in CI/CD
What Are API Keys?
API keys are authentication tokens that allow automated tools to access services on your behalf. Think of them as digital keys that unlock specific capabilities—in this case, security scanning services like Rafter.Why API Keys Are Secure
API keys are designed for programmatic access and include several security features:- Scoped permissions: Keys can only access specific services
- Usage tracking: All API calls are logged and monitored
- Easy rotation: Keys can be regenerated instantly if compromised
- Environment isolation: Keys are stored separately from your code
How GitHub Secrets Protect Your Keys
GitHub Secrets provide enterprise-grade security for sensitive data:- Encryption at rest: Keys are encrypted when stored
- Encryption in transit: Keys are encrypted when accessed
- Access control: Only authorized workflows can use secrets
- Audit logging: All secret access is logged
Manual Setup: Step-by-Step Configuration
Step 1: Choose Your Mode
Refer to Two CI Modes above. If you’re using local scan, skip to Step 3 and use the local scan workflow. If you’re using backend scan, continue with Step 2 to get your API key.Step 2: Get Your Rafter API Key
(Backend scan only — skip if using local scan.) If you have an existing key saved to a safe place, copy it. Otherwise, generate a new key… Rafter protects your API keys by not storing them. You get access once, when you generate/refresh the key. Then, refreshing the key invalidates the previous key to keep it safe. It’s a way to help you rotate keys, which is best practice. Navigate to Account Settings- Go to your Rafter account settings
- Look for the “API Keys” section
- Click “Generate New API Key” or “Refresh API Key”
- The key is automatically copied to your clipboard (it won’t be shown/copiable again)
API keys are sensitive credentials. Never commit them to your repository or share them in plain text.Add API Key to GitHub Secrets
- Navigate to your GitHub repository
- Click “Settings” → “Secrets and variables” → “Actions”
- Click “New repository secret”
- Name:
RAFTER_API_KEY - Value: Paste your API key
- Click “Add secret”
Step 3: Create GitHub Workflow
Create Workflow Directory.github/workflows/security-scan.yml:
1 fails the job automatically if secrets are detected.
Option B — Backend Code Analysis Workflow (API key required)
Create .github/workflows/security-scan.yml:
Raftersecurity/rafter-cli@v1. Runs rafter secrets on the runner, the same engine as Option A:
Remote code analysis, API key required —
Raftersecurity/rafter-cli/github-action@main. Calls the scan API directly with curl (it doesn’t shell out to the rafter CLI), posts a PR comment with the severity breakdown, and uploads SARIF to the Security tab:
Count outputs are written only when
status is completed — a report the action cannot read is never reported as a clean scan.
Step 4: Test Your Setup
Make a Test Commit- Go to your repository’s “Actions” tab
- Look for the workflow
- Verify it runs successfully
AI-Assisted Setup
Tell your AI assistant:Understanding the Workflow Components
Trigger Configuration
- On every push to the main branch
- Automatically, without manual intervention
CLI-Based Code Analysis
The backend workflow uses the Rafter CLI which handles auto-detection, polling, and retries:- Auto-detects repo and branch from the git checkout
- Polls until complete — no manual loop needed
- Returns structured JSON with consistent schema and documented exit codes
Exit Codes
The CLI uses stable exit codes that CI pipelines can rely on:
Results are also available in your Rafter dashboard.
Vulnerability Checking
- Parses scan results using jq
- Counts error-level vulnerabilities
- Fails the build if critical issues are found
- Provides clear feedback to developers
Advanced Configuration Options
While we’ve outlined some powerful use cases below, see our documentation for more advanced configuration options: Rafter CI/CD Documentation.Customizing Triggers
You can customize when Rafter runs:Adjusting Failure Thresholds
Modify the vulnerability checking logic:Adding Notifications
rafter notify posts scan results directly to a Slack or Discord webhook — no third-party action needed:
-w/--webhook, then the RAFTER_NOTIFY_WEBHOOK env var, then agent.notifications.webhook in the global config (rafter agent config set agent.notifications.webhook <url>). The platform (Slack vs. Discord vs. a generic {text, content} payload) is auto-detected from the webhook’s host; force it with -p/--platform slack|discord|generic. --quiet suppresses the “Posting to… channel” status line.
The message counts the scan’s vulnerabilities[] by severity (critical; error as High; warning as Medium; note as Low) and lists the top findings as file:line. It reports “Clean” only for a completed scan with zero findings.
Generating an HTML Report
rafter report turns local secret-scan findings into a standalone HTML file — useful as a build artifact or email attachment:
-o/--output defaults to stdout; --title defaults to “Rafter Security Report”. It accepts the JSON output of rafter secrets --json only — piping rafter run/rafter get --format json output into it is rejected with exit code 2 (render those with rafter get <scan_id> --format md instead).
Filing GitHub Issues from Findings
rafter issues create from-scan opens a GitHub issue per finding, deduplicated against already-open issues. It shells out to the GitHub CLI (gh), which is preinstalled and auto-authenticated on GitHub-hosted runners via the default GITHUB_TOKEN:
--scan-id <id> --api-key <key> instead of --from-local <path> to file issues from a remote rafter run scan. --no-dedup skips the existing-issue check; --dry-run prints the drafts as JSON instead of creating anything. A backend scan that hasn’t finished (or failed, or returned an unreadable payload) exits 1 with a message naming the scan — it is never reported as zero findings.
rafter issues create from-text takes free-form text (stdin, --file, or --text) and files a single issue, extracting a title, severity label, and security label heuristically — handy for turning an ad-hoc report into a tracked issue from a script or chat command.
Troubleshooting Common Issues
API Key Not Found
Error (from the CLI):No API key provided. Use --api-key, set RAFTER_API_KEY, or run 'rafter agent config set backend.apiKey <key>'
Solution:
- Verify the secret exists in GitHub repository settings
- Check the secret name matches exactly:
RAFTER_API_KEY - Ensure the workflow passes
${{ secrets.RAFTER_API_KEY }}— as theRAFTER_API_KEYenv var for the CLI, or as theapi-keyinput for the official action
Scan Request Fails
The CLI prints the API’s error to stderr and exits with the matching code:- HTTP 401 (“Invalid or inactive API key”): printed as-is, exit
1— check your key is current - HTTP 403:
Error: This API key only has read access...(exit4, wrong scope) orError: <Mode> scan limit reached (used/limit)...(exit3, quota/plan limit) — the CLI distinguishes these from the response body - HTTP 429 on submit:
Quota exhausted, exit3, even when the response carriesRetry-After - HTTP 404 on
rafter get <scan_id>:Scan '<scan_id>' not found, exit2— verify the scan ID - Branch not pushed:
rafter runchecks that an auto-detected branch exists onoriginbefore submitting, and fails immediately with a clear message if it hasn’t been pushed — push the branch or pass--branchexplicitly
Scan Status Issues
Symptom: scan stuck in “processing” or “pending” for a long time.rafter runandrafter get --interactivealready poll every 10 seconds and retry transient 5xx/network failures with exponential backoff (2s/4s/8s/16s, up to 5 consecutive or 20 total failures) before giving up — no custom polling loop is needed around the CLI. A 429 while polling is retried only when it carries a singleRetry-Afterin seconds, after sleepingmin(Retry-After, 60s), against the same budget; a bare 429 fails at once. If the CLI gives up on repeated 429s, its message says the API rate limited it.- The official GitHub Action enforces
timeout-minutesas a real wall-clock deadline (not a poll count, as it was before CLI 0.11). If a scan genuinely takes longer, raisetimeout-minutes.
Scan Results Not Found
Error:scan-results.json: No such file or directory
Solution:
- The CLI never writes
scan-results.jsonon its own — that filename only exists if your workflow redirects output itself, as in Option B (rafter run --format json --quiet > scan-results.json). There is no companion.mdfile unless you generate one separately withrafter get <scan_id> --format md. - If the redirect produced an empty or missing file, the command before it likely exited non-zero — check the step’s own log for the printed error rather than assuming the file write failed silently.
- With the official GitHub Action, use its
statusand count outputs instead of a file:statusisunreadablewhen the scan may have finished but its report couldn’t be parsed, and count outputs are only ever written whenstatusiscompleted.
Security Best Practices
API Key Management
- Rotate keys regularly: Generate new keys every 90 days
- Monitor usage: Check API key usage logs for anomalies
- Use least privilege: Only grant necessary permissions
- Never log keys: Ensure keys don’t appear in logs or outputs
Workflow Security
- Pin action versions: Use specific commit SHAs instead of tags
- Review permissions: Limit workflow permissions to minimum required
- Audit regularly: Review workflow changes and access patterns
- Use trusted sources: Only use official GitHub Actions
Repository Security
- Enable branch protection: Require status checks before merging
- Use required reviewers: Require security team review for workflow changes
- Monitor secrets: Regularly audit repository secrets
- Enable security alerts: Use GitHub’s security features
Measuring Success
Key Metrics to Track
- Scan Coverage: Percentage of commits scanned
- Detection Rate: Vulnerabilities found per scan
- Fix Time: Average time from detection to resolution
- False Positive Rate: Incorrect vulnerability reports
Success Indicators
- Zero critical vulnerabilities in production deployments
- Consistent scan execution across all branches
- Rapid vulnerability resolution (under 24 hours)
- Developer adoption of security-first practices
Conclusion
Whether you use the local secret scanner or the full code analysis engine, the result is the same: security coverage on every commit with stable exit codes and structured output that CI pipelines can act on. Start withrafter ci init, customize as needed, and let the code analysis engine do the work.
