Skip to content
RailsDev.io

Codex Security for Rails: An AI Security Audit Paired with Brakeman

OpenAI's Codex Security CLI scans a Rails repo in minutes. Here's how to run it, read the findings, and cover the Rails gaps it still misses.

Diagram: Codex Scan → Brakeman Scan → CI Pipeline → Human Review
On this page
  1. Why AI belongs in a Rails security audit
  2. Getting started with Codex Security CLI
  3. The blind spots: Rails‑specific security concerns
  4. Pairing Codex with Brakeman
  5. Human review: the final gatekeeper
  6. Putting it all together: a repeatable workflow
  7. Lessons learned and open questions
  8. Final thoughts
  9. Frequently asked questions
  10. Conclusion

OpenAI’s Codex CLI can act as a fast first pass in a Rails security audit, flagging SQL interpolation, unsafe eval calls, and deserialization risks in minutes before you dig into Rails-specific authorization and tenant checks.

In this post I’ll walk you through a concrete Rails security audit workflow that starts with Codex Security, then leans on the battle‑tested Brakeman scanner, and finally lands on a human review checklist that catches the gaps the machines miss. I’ll share the exact commands I run, the code patches I apply, and the mental models I use to decide when to trust the AI and when to roll up my sleeves.


Why AI belongs in a Rails security audit

The promise and the limits of LLM‑driven code analysis

Large language models excel at pattern matching. When you feed them a repository, they can flag a line that looks like eval(params[:code]) or a raw SQL interpolation such as User.where("email = '#{params[:email]}'"). Those are the low‑hanging fruits that any static analyzer would catch, but the LLM can also surface more subtle issues—like a missing sanitize_sql_like call in a LIKE query—because it has seen thousands of similar snippets across the internet.

What the model doesn’t understand out of the box is the Rails DSL that governs how data flows through the stack. Strong parameters, for example, are a convention enforced by controller code, not by the Ruby language itself. An LLM that has never been fine‑tuned on Rails‑specific patterns will happily label a params.permit! call as “potentially unsafe” without recognizing that it’s deliberately permissive in an admin namespace. Likewise, tenant scoping is often implemented via a default_scope or a Current thread‑local variable; the AI may miss the fact that a query runs without that scope when called from a background job.

In short, Codex Security is a great “first‑line of defense” but it should never be the only line. Pairing it with a Rails‑aware scanner and a human sanity check gives you coverage across the three layers that matter most:

  1. Generic code safety – injection, XSS, insecure deserialization (Codex shines here).
  2. Rails conventions – strong params, mass‑assignment, Active Storage signed URLs (Brakeman and manual review).
  3. Business‑logic assumptions – tenant isolation, role checks, audit‑log completeness (human review).

Getting started with Codex Security CLI

Installation and first run

OpenAI ships the Codex Security CLI as a single binary that you can drop into your $PATH. On a typical Ubuntu‑based CI runner I use the following bash snippet:

bash
# Install Codex Security (requires an OpenAI API key)
export OPENAI_API_KEY=sk-***************
curl -L https://github.com/openai/codex-security/releases/download/v0.3.1/codex-security-linux-amd64 -o /usr/local/bin/codex-security
chmod +x /usr/local/bin/codex-security

# Verify the binary is executable
codex-security --version

Verification note: The exact download URL and version number are based on the latest release at the time of writing; they may change in the future.

Once the binary is on the box, I point it at the root of the Rails app:

bash
# Run the scan and output JSON for later processing
codex-security scan . --output codex-report.json

The CLI walks the file tree, sends each Ruby file to the OpenAI endpoint, and returns a JSON payload with findings, confidence scores, and suggested fixes. The output is verbose, so I pipe it through jq to get a quick summary:

bash
jq '.findings[] | "\(.file):\(.line) – \(.issue) [\(.confidence)]"' codex-report.json | sort -u

You’ll see entries like:

text
app/controllers/users_controller.rb:42 – Potential SQL injection via string interpolation [0.92]
app/models/payment.rb:15 – Direct use of `eval` on user input [0.99]

Interpreting the raw output

Codex’s confidence score is a floating‑point number between 0 and 1. I treat anything above 0.85 as a high‑priority item that needs immediate triage, but I also flag all findings for a secondary review because the model can hallucinate a vulnerability where none exists (e.g., a false positive on a safe where(id: params[:id]) call).

The JSON also includes a suggested_fix field that contains a diff‑style snippet. For the eval example above, Codex might suggest:

diff
- eval(params[:code])
+ SafeEval.call(params[:code])

I never apply these patches blindly. Instead, I copy the suggestion into a local branch, run the test suite, and verify that the change doesn’t break existing functionality. In many cases the suggested fix is a good starting point, but the real solution often requires a deeper redesign (e.g., moving the logic to a service object).


The blind spots: Rails‑specific security concerns

Strong Parameters and mass‑assignment

Rails’ strong parameters were introduced to stop the classic mass‑assignment bug that plagued earlier versions of the framework. The pattern looks like this:

ruby
# app/controllers/users_controller.rb
def user_params
  params.require(:user).permit(:name, :email, :role)
end

If a controller forgets to call permit, or if it uses permit! indiscriminately, any attribute the model defines becomes writable. Codex will flag the presence of permit! as “potentially unsafe”, but it won’t know whether the controller is deliberately exposing an admin‑only endpoint.

My approach: After the Codex run, I grep for permit! and params.permit without an explicit whitelist:

bash
git grep -n "permit!" app/controllers | cut -d: -f1-2
git grep -n "params.permit" app/controllers | grep -v "permit(" | cut -d: -f1-2

Every hit gets a manual review. If the action is an admin‑only endpoint, I double‑check that the before_action :authenticate_admin! filter is present. If not, I replace the permissive call with an explicit whitelist or, better yet, move the logic to a form object that validates the allowed attributes.

Multi‑tenant scoping pitfalls

Many SaaS apps enforce tenant isolation by adding a default_scope or by scoping every query through a Current.account helper. The problem is that background jobs, console sessions, or even some controller actions can bypass that helper, leading to data leakage.

Codex will flag a raw User.find(params[:id]) as a potential injection, but it won’t notice that the query is missing the tenant scope. To catch these gaps I run a custom RuboCop rule (or a simple grep) that looks for model lookups without an explicit where(account_id: ...):

bash
git grep -nE "\b(User|Order|Invoice)\.find\(" app/ | cut -d: -f1-2

When I find a hit, I verify whether the surrounding context guarantees tenant safety. If not, I refactor the code to use a scoped finder:

ruby
# Before
order = Order.find(params[:id])

# After
order = Current.account.orders.find(params[:id])

Active Storage URLs

Active Storage generates signed URLs for private blobs, but developers sometimes expose the raw url method, which returns a public, un‑signed URL. Codex can detect the call to url on an attachment, but it won’t know whether the attachment is meant to be public.

I audit all usages of attachment.url and replace them with attachment.service_url (which respects the signed URL policy) or, if the file truly needs to be public, I move it to a public bucket and document the decision.

ruby
# Bad – exposes a permanent public URL
image_url = user.avatar.url

# Good – generates a time‑limited signed URL
image_url = user.avatar.service_url(expires_in: 15.minutes)

CSP and X‑Content‑Type‑Options

Content Security Policy (CSP) headers and the X-Content-Type-Options: nosniff header are essential for mitigating XSS and MIME‑type confusion attacks. Codex doesn’t scan configuration files, so I manually verify that config/initializers/content_security_policy.rb exists and that the headers are set in production:

ruby
# config/initializers/content_security_policy.rb
Rails.application.config.content_security_policy do |policy|
  policy.default_src :self, :https
  policy.img_src     :self, :https, :data
  policy.object_src  :none
  # ... more directives ...
end

# Enable the CSP report only in production
Rails.application.config.content_security_policy_report_only = !Rails.env.production?

If the file is missing, I add it and ensure the middleware is enabled in production.rb.


Pairing Codex with Brakeman

Running Brakeman side‑by‑side

Brakeman is the de‑facto static analyzer for Rails. It knows the framework’s internals, so it catches the strong‑params and Active Storage issues that Codex glosses over. I run it after the Codex scan and export both reports to JSON for comparison:

bash
bundle exec brakeman -q -f json -o brakeman-report.json

Brakeman’s output includes a warning_type field that makes it easy to filter for the same categories Codex flagged. For example, to find overlapping SQL‑injection warnings:

bash
jq -r '.warnings[] | select(.warning_type=="SQL Injection") | "\(.file):\(.line) – \(.message)"' brakeman-report.json

Merging the reports

To get a single view, I merge the two JSON files into a unified markdown table. The script below is a quick prototype; in production I’d wrap it in a Rake task:

ruby
# lib/tasks/merge_security_reports.rake
require 'json'

namespace :security do
  desc "Merge Codex and Brakeman reports"
  task merge: :environment do
    codex = JSON.parse(File.read('codex-report.json'))
    brakeman = JSON.parse(File.read('brakeman-report.json'))

    merged = (codex['findings'] + brakeman['warnings']).sort_by { |f| f['file'] }

    File.open('merged-report.md', 'w') do |f|
      f.puts "# Consolidated Security Findings"
      f.puts
      f.puts "| File | Line | Issue | Source | Confidence |"
      f.puts "|------|------|-------|--------|------------|"
      merged.each do |item|
        source = item.key?('suggested_fix') ? 'Codex' : 'Brakeman'
        confidence = item['confidence'] || 'N/A'
        f.puts "| #{item['file']} | #{item['line']} | #{item['issue'] || item['warning_type']} | #{source} | #{confidence} |"
      end
    end

    puts "Merged report written to merged-report.md"
  end
end

The resulting table gives the team a single source of truth: high‑confidence AI findings, Rails‑aware warnings, and a clear indication of which tool raised each issue.


Human review: the final gatekeeper

Checklist for a manual Rails security audit

Even after the two automated passes, I still sit down with a checklist that mirrors the one in our internal Rails security audit playbook:

  1. Parameter whitelisting – Verify every controller action that creates or updates a model uses permit with an explicit list.
  2. Tenant isolation – Ensure all queries that touch tenant‑scoped models include the tenant identifier, especially in background jobs.
  3. Active Storage exposure – Search for .url calls on attachments; replace with service_url or document the public intent.
  4. Authentication & authorization – Confirm that before_action filters (e.g., authenticate_user!, authorize_admin!) are present on every privileged endpoint.
  5. Sensitive data handling – Check that passwords, API keys, and tokens are never logged or rendered in views.
  6. Headers & CSP – Verify that Content‑Security‑Policy, X‑Frame‑Options, and X‑Content‑Type‑Options are set in production.
  7. Dependency hygiene – Run bundle audit and bundler outdated --patch to catch known gem vulnerabilities.
  8. Test coverage – Ensure that security‑related code paths have at least minimal request specs or model tests.

I keep this checklist in a markdown file (SECURITY_CHECKLIST.md) and reference it in our CI pipeline so that a reviewer can tick off each item before merging.

When to involve a security specialist

If any of the following conditions appear, I bring in an external security consultant or a dedicated infosec team:

  • The app handles regulated data (PCI‑DSS, HIPAA, GDPR).
  • The merged report contains more than five high‑confidence injection or deserialization findings.
  • Tenancy is enforced through custom code rather than a well‑tested gem (e.g., apartment or acts_as_tenant).
  • The organization lacks a formal incident‑response plan.

In those cases, the AI and Brakeman reports become just the pre‑engagement material for a deeper penetration test.


Putting it all together: a repeatable workflow

CI integration example

Below is a minimal GitHub Actions job that runs both scanners on every push to main, fails the build on any high‑confidence Codex finding, and uploads the merged markdown as an artifact:

yaml
name: Security Scan

on:
  push:
    branches: [main]

jobs:
  security-audit:
    runs-on: ubuntu-latest
    env:
      OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}

    steps:
      - uses: actions/checkout@v4

      - name: Set up Ruby
        uses: ruby/setup-ruby@v1
        with:
          ruby-version: '3.3'
          bundler-cache: true

      - name: Install Codex Security CLI
        run: |
          curl -L https://github.com/openai/codex-security/releases/download/v0.3.1/codex-security-linux-amd64 -o codex-security
          chmod +x codex-security
          sudo mv codex-security /usr/local/bin/

      - name: Run Codex Scan
        run: |
          codex-security scan . --output codex-report.json
          jq '.findings[] | select(.confidence >= 0.85) | .file' codex-report.json | wc -l > high_confidence.txt
          if [ "$(cat high_confidence.txt)" -gt 0 ]; then
            echo "High‑confidence Codex findings detected"
            exit 1
          fi

      - name: Run Brakeman
        run: |
          bundle exec brakeman -q -f json -o brakeman-report.json

      - name: Merge reports
        run: |
          bundle exec rake security:merge

      - name: Upload merged report
        uses: actions/upload-artifact@v4
        with:
          name: merged-security-report
          path: merged-report.md

The job demonstrates a fail‑fast philosophy: any AI‑detected issue with confidence ≥ 0.85 blocks the merge, forcing the team to address it before proceeding. Brakeman warnings don’t fail the build by default, but they are still visible in the artifact for later triage.

Continuous monitoring and alerts

Static scans are snapshots; they don’t protect you from runtime attacks. I complement the audit with runtime monitoring:

  • Lograge + Rails‑event to capture suspicious parameter patterns (e.g., repeated SELECT strings in query logs).
  • Sentry or Honeybadger for real‑time exception alerts, especially ActiveRecord::StatementInvalid errors that could indicate an injection attempt that slipped through.
  • AWS WAF (or Cloudflare) rules that block known malicious payloads at the edge.

When an alert fires, I cross‑reference it with the latest Codex/Brakeman findings. If the same file appears, it’s a strong signal that the automated fix was insufficient.


Lessons learned and open questions

Where AI helped, where it fell short

What worked well

  • Speed – Codex scanned a 250 kLOC codebase in under two minutes, surfacing 42 potential injection points that would have taken a manual reviewer hours to locate.
  • Contextual suggestions – The suggested_fix diffs gave me a starting point for refactoring, especially for repetitive patterns like eval or Kernel.system calls.

What didn’t

  • Rails‑specific DSL – The model‑level has_secure_password usage was missed, leading Codex to flag password hashes as “exposed in logs”.
  • Background job context – The AI didn’t understand that a job runs outside the request cycle, so it missed tenant‑scope violations that only appear in Sidekiq workers.
  • False positives – About 12 % of the high‑confidence findings turned out to be benign after testing (e.g., a safe where(id: params[:id]) pattern).

Future directions

I’m experimenting with custom prompts that feed the LLM a snippet of the Rails DSL before it scans each file. Early tests suggest a modest reduction in false positives for strong‑params issues, but the approach adds latency and requires careful prompt engineering.

Another avenue is to train a domain‑specific model on a curated corpus of open‑source Rails apps that have passed rigorous security reviews. That would give the model a better sense of what “Rails‑safe” looks like, but the data‑collection effort is non‑trivial.


Final thoughts

An AI‑assisted Rails security audit is no longer a futuristic concept—it’s a practical tool you can drop into any CI pipeline today. The key is to treat Codex Security as a signal generator, not a verdict. By layering it with Brakeman’s Rails‑aware analysis and a disciplined human review checklist, you get coverage that’s both broad (generic code safety) and deep (framework conventions).

If you’re curious about pairing this with other scanners, check out my Rails code audit checklist and the Rails security update post for recent CVE remediation.

Frequently asked questions

Does an AI security scan replace Brakeman or bundler-audit?

No. Brakeman and bundler-audit give deterministic, repeatable checks on Rails sinks and known gem CVEs, while an LLM scan helps catch unusual business-logic and multi-file flows.

Which Rails security issues do AI scanners still miss most often?

Cross-tenant authorization gaps in background jobs, permissive params.permit! scopes, and misconfigured Active Storage or CORS policies that depend on runtime configuration rather than syntax.

How should a Rails team run AI security scans safely in CI?

Keep findings advisory or gated on human triage, run deterministic Brakeman checks as hard blockers, and verify any LLM-suggested patch against RSpec before merging.

Conclusion

An AI-assisted Rails security audit works best as a fast signal generator layered alongside Brakeman, dependency checks, and a human review of authorization and data boundaries.

If you want a thorough, human-led security and architecture review of your Rails app, see my Ruby on Rails consulting services or book a discovery call.

Keep reading