mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-28 18:55:32 +00:00
Merge remote-tracking branch 'origin/pr-3423' into stewardship/20261116
# Conflicts: # .claude-plugin/marketplace.json # .claude-plugin/plugin.json # .gemini/GEMINI.md # AGENTS.md # README.md # README.zh-CN.md # SOUL.md # docs/tr/AGENTS.md # docs/zh-CN/AGENTS.md # docs/zh-CN/README.md # manifests/context-packs/skill-triggers@1.json
This commit is contained in:
20 files changed
+1133
-15
No files matched your search
@@ -11,7 +11,7 @@
|
||||
{
|
||||
"name": "ecc",
|
||||
"source": "./",
|
||||
"description": "Harness-native ECC operator layer - 72 agents, 326 skills, 98 legacy command shims, reusable hooks, rules, selective install profiles, and production-ready workflows for Claude Code, Codex, OpenCode, Cursor, and related agent harnesses",
|
||||
"description": "Harness-native ECC operator layer - 72 agents, 327 skills, 98 legacy command shims, reusable hooks, rules, selective install profiles, and production-ready workflows for Claude Code, Codex, OpenCode, Cursor, and related agent harnesses",
|
||||
"version": "2.2.3",
|
||||
"author": {
|
||||
"name": "Affaan Mustafa",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ecc",
|
||||
"version": "2.2.3",
|
||||
"description": "Harness-native ECC plugin for engineering teams - 72 agents, 326 skills, 98 legacy command shims, reusable hooks, rules, MCP conventions, and operator workflows for Claude Code plus adjacent agent harnesses",
|
||||
"description": "Harness-native ECC plugin for engineering teams - 72 agents, 327 skills, 98 legacy command shims, reusable hooks, rules, MCP conventions, and operator workflows for Claude Code plus adjacent agent harnesses",
|
||||
"author": {
|
||||
"name": "Affaan Mustafa",
|
||||
"url": "https://x.com/affaanmustafa"
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ This file provides Gemini CLI with the baseline ECC workflow, review standards,
|
||||
|
||||
## Overview
|
||||
|
||||
ECC is a cross-harness coding system with 72 specialized agents, 326 skills, and 98 commands.
|
||||
ECC is a cross-harness coding system with 72 specialized agents, 327 skills, and 98 commands.
|
||||
|
||||
Gemini support is currently focused on a strong project-local instruction layer via `.gemini/GEMINI.md`, plus the shared MCP catalog and package-manager setup assets shipped by the installer.
|
||||
|
||||
|
||||
@@ -419,6 +419,36 @@ jobs:
|
||||
python -m pip install 'openai==2.34.0'
|
||||
python -m pytest tests/test_provider_tools.py tests/test_atlas_provider.py tests/test_astraflow_provider.py tests/test_resolver.py
|
||||
|
||||
rails-security-fixture:
|
||||
name: Rails Security Skill Fixture
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: '22.x'
|
||||
|
||||
# tests/skills/rails-security.test.js asserts its document claims without Ruby and
|
||||
# skips only the Active Storage cases, so this lane is what executes them.
|
||||
- name: Setup Ruby
|
||||
uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0
|
||||
with:
|
||||
ruby-version: '3.3'
|
||||
bundler-cache: true
|
||||
working-directory: tests/fixtures/rails-security
|
||||
|
||||
- name: Run the Rails security skill test
|
||||
run: node tests/skills/rails-security.test.js
|
||||
env:
|
||||
ECC_RAILS_FIXTURE_REQUIRED: '1'
|
||||
|
||||
security:
|
||||
name: Security Scan
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# ECC — Agent Instructions
|
||||
|
||||
This is a **production-ready AI coding plugin** providing 72 specialized agents, 326 skills, 98 commands, and automated hook workflows for software development.
|
||||
This is a **production-ready AI coding plugin** providing 72 specialized agents, 327 skills, 98 commands, and automated hook workflows for software development.
|
||||
|
||||
**Version:** 2.2.3
|
||||
|
||||
@@ -203,7 +203,7 @@ Troubleshoot failures: check test isolation → verify mocks → fix implementat
|
||||
|
||||
```
|
||||
agents/ — 72 specialized subagents
|
||||
skills/ — 326 workflow skills and domain knowledge
|
||||
skills/ — 327 workflow skills and domain knowledge
|
||||
commands/ — 98 slash commands
|
||||
hooks/ — Trigger-based automations
|
||||
rules/ — Always-follow guidelines (common + per-language)
|
||||
|
||||
@@ -142,12 +142,12 @@ Instead of rebuilding that process in every prompt, you install it once and make
|
||||
|
||||
ECC is MIT-licensed open source. It works best with Claude Code today, has native Codex and Qoder plugin paths, and provides capability-limited adapters for Cursor, OpenCode, Gemini, Zed, GitHub Copilot, Antigravity, Qwen, and other harnesses. See the [support status matrix](#platform-support) before assuming feature parity.
|
||||
|
||||
Access to 72 agents, 326 skills, and 98 legacy command shims, plus hooks, rules, memory, continuous learning, and AgentShield security scanning. The agents are specialized for planning, review, build repair, security, architecture, and domain work.
|
||||
Access to 72 agents, 327 skills, and 98 legacy command shims, plus hooks, rules, memory, continuous learning, and AgentShield security scanning. The agents are specialized for planning, review, build repair, security, architecture, and domain work.
|
||||
|
||||
| Included | Count | What it gives you |
|
||||
| ---------------- | ----------: | ------------------------------------------------------------------------------------ |
|
||||
| Agents | 72 agents | Planning, review, build repair, security, architecture, and domain work |
|
||||
| Skills | 326 skills | TDD, research, security, docs, frontend, data, ML, operations, and more |
|
||||
| Skills | 327 skills | TDD, research, security, docs, frontend, data, ML, operations, and more |
|
||||
| Commands | 98 commands | Convenient entry points while ECC moves to a skills-first surface |
|
||||
| Hooks and memory | Runtime | Enforcement, session summaries, continuous learning, instincts, and context controls |
|
||||
| Rules | Selective | Always-loaded standards you choose by language or project |
|
||||
@@ -862,7 +862,7 @@ Stable graduation of the 2.0 line: control-pane substrate, worktree lifecycle se
|
||||
```text
|
||||
ECC/
|
||||
|-- agents/ # 72 specialized subagents for delegation
|
||||
|-- skills/ # 326 reusable workflows loaded on demand
|
||||
|-- skills/ # 327 reusable workflows loaded on demand
|
||||
|-- commands/ # 98 maintained slash-command shims
|
||||
|-- rules/ # opt-in common and language standards
|
||||
|-- hooks/ # runtime automation and enforcement
|
||||
@@ -958,6 +958,7 @@ ECC/
|
||||
| |-- quarkus-tdd/ # Quarkus TDD
|
||||
| |-- quarkus-verification/ # Quarkus verification
|
||||
| |-- rails-patterns/ # Rails architecture patterns
|
||||
| |-- rails-security/ # Rails security practices
|
||||
| |-- springboot-patterns/ # Java Spring Boot patterns
|
||||
| |-- springboot-security/ # Spring Boot security
|
||||
| |-- springboot-tdd/ # Spring Boot TDD
|
||||
|
||||
+1
-1
@@ -200,7 +200,7 @@ Copy-Item -Recurse rules/typescript "$HOME/.claude/rules/"
|
||||
/plugin list ecc@ecc
|
||||
```
|
||||
|
||||
**完成!** 你现在可以使用 72 个代理、326 个技能和 98 个命令。
|
||||
**完成!** 你现在可以使用 72 个代理、327 个技能和 98 个命令。
|
||||
|
||||
### multi-* 命令需要额外配置
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Soul
|
||||
|
||||
## Core Identity
|
||||
ECC is a production-ready AI coding plugin with 72 specialized agents, 326 skills, 98 commands, and automated hook workflows for software development.
|
||||
ECC is a production-ready AI coding plugin with 72 specialized agents, 327 skills, 98 commands, and automated hook workflows for software development.
|
||||
|
||||
## Core Principles
|
||||
1. **Agent-First** — route work to the right specialist as early as possible.
|
||||
|
||||
@@ -144,6 +144,7 @@ skills:
|
||||
- quarkus-tdd
|
||||
- quarkus-verification
|
||||
- rails-patterns
|
||||
- rails-security
|
||||
- ralphinho-rfc-pipeline
|
||||
- react-patterns
|
||||
- react-performance
|
||||
|
||||
@@ -360,6 +360,7 @@
|
||||
"rules": ["common"],
|
||||
"skills": [
|
||||
"rails-patterns",
|
||||
"rails-security",
|
||||
"tdd-workflow",
|
||||
"verification-loop"
|
||||
],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# ECC — 智能体指令
|
||||
|
||||
这是一个**生产就绪的 AI 编码插件**,提供 72 个专业代理、326 项技能、98 条命令以及自动化钩子工作流,用于软件开发。
|
||||
这是一个**生产就绪的 AI 编码插件**,提供 72 个专业代理、327 项技能、98 条命令以及自动化钩子工作流,用于软件开发。
|
||||
|
||||
**版本:** 2.2.3
|
||||
|
||||
@@ -147,7 +147,7 @@
|
||||
|
||||
```
|
||||
agents/ — 72 个专业子代理
|
||||
skills/ — 326 个工作流技能和领域知识
|
||||
skills/ — 327 个工作流技能和领域知识
|
||||
commands/ — 98 个斜杠命令
|
||||
hooks/ — 基于触发的自动化
|
||||
rules/ — 始终遵循的指导方针(通用 + 每种语言)
|
||||
|
||||
@@ -264,7 +264,7 @@ Copy-Item -Recurse rules/typescript "$HOME/.claude/rules/"
|
||||
/plugin list ecc@ecc
|
||||
```
|
||||
|
||||
**搞定!** 你现在可以使用 72 个智能体、326 项技能和 98 个命令了。
|
||||
**搞定!** 你现在可以使用 72 个智能体、327 项技能和 98 个命令了。
|
||||
|
||||
***
|
||||
|
||||
@@ -1178,7 +1178,7 @@ opencode
|
||||
|---------|---------------|----------|--------|
|
||||
| 智能体 | PASS: 72 个 | PASS: 12 个 | **Claude Code 领先** |
|
||||
| 命令 | PASS: 98 个 | PASS: 35 个 | **Claude Code 领先** |
|
||||
| 技能 | PASS: 326 项 | PASS: 37 项 | **Claude Code 领先** |
|
||||
| 技能 | PASS: 327 项 | PASS: 37 项 | **Claude Code 领先** |
|
||||
| 钩子 | PASS: 8 种事件类型 | PASS: 11 种事件 | **OpenCode 更多!** |
|
||||
| 规则 | PASS: 29 条 | PASS: 13 条指令 | **Claude Code 领先** |
|
||||
| MCP 服务器 | PASS: 14 个 | PASS: 完整 | **完全对等** |
|
||||
@@ -1286,7 +1286,7 @@ ECC 是**第一个最大化利用每个主要 AI 编码工具的插件**。以
|
||||
|---------|-----------------------|------------|-----------|----------|
|
||||
| **智能体** | 72 | 共享 (AGENTS.md) | 共享 (AGENTS.md) | 12 |
|
||||
| **命令** | 98 | 共享 | 基于指令 | 35 |
|
||||
| **技能** | 326 | 共享 | 10 (原生格式) | 37 |
|
||||
| **技能** | 327 | 共享 | 10 (原生格式) | 37 |
|
||||
| **钩子事件** | 8 种类型 | 15 种类型 | SessionStart(1 种类型) | 11 种类型 |
|
||||
| **钩子脚本** | 20+ 个脚本 | 16 个脚本 (DRY 适配器) | 1 个 SessionStart 引导脚本 | 插件钩子 |
|
||||
| **规则** | 34 (通用 + 语言) | 34 (YAML 前页) | 基于指令 | 13 条指令 |
|
||||
|
||||
@@ -549,6 +549,7 @@
|
||||
"skills/nodejs-keccak256",
|
||||
"skills/perl-security",
|
||||
"skills/quarkus-security",
|
||||
"skills/rails-security",
|
||||
"skills/security-review",
|
||||
"skills/security-scan",
|
||||
"skills/security-bounty-hunter",
|
||||
|
||||
@@ -356,6 +356,7 @@
|
||||
"skills/quarkus-tdd/",
|
||||
"skills/quarkus-verification/",
|
||||
"skills/rails-patterns/",
|
||||
"skills/rails-security/",
|
||||
"skills/ralphinho-rfc-pipeline/",
|
||||
"skills/react-patterns/",
|
||||
"skills/react-performance/",
|
||||
|
||||
@@ -48,4 +48,6 @@ bundle exec brakeman --no-progress
|
||||
|
||||
## Reference
|
||||
|
||||
See skill: `rails-security` for Rails-specific security implementation patterns.
|
||||
|
||||
See skill: `security-review` for secure-by-default review patterns.
|
||||
@@ -0,0 +1,524 @@
|
||||
---
|
||||
name: rails-security
|
||||
description: Ruby on Rails security practices for Rails 7.1+ and 8.x apps. Covers production configuration, authentication, authorization, strong parameters, SQL injection, XSS and output escaping, CSRF, file uploads, API security, credentials, untrusted boundaries, and dependency scanning. Use when reviewing or writing Rails authentication, authorization, input handling, uploads, or deployment configuration.
|
||||
origin: community
|
||||
---
|
||||
|
||||
# Rails Security
|
||||
|
||||
Security practices for Ruby on Rails applications (Rails 7.1+ and 8.x). Rails is secure by
|
||||
default in most places; the vulnerabilities that reach production usually come from opting
|
||||
out of a default rather than failing to add protection. This skill is the "how." For the
|
||||
decisions about which control to reach for, see the Ruby security rules —
|
||||
`rules/ruby/security.md` in this repository, installed as `rules/ecc/ruby/security.md`.
|
||||
|
||||
## When to Activate
|
||||
|
||||
- Writing or reviewing authentication, sessions, or account recovery
|
||||
- Adding authorization checks to controllers or views
|
||||
- Handling user input, file uploads, or webhook payloads
|
||||
- Configuring a Rails app for production
|
||||
- Reviewing a PR that touches `config/`, `app/controllers/`, or `Gemfile`
|
||||
- Any use of `html_safe`, `raw`, `Arel.sql`, or raw SQL strings
|
||||
|
||||
## Production Configuration
|
||||
|
||||
```ruby
|
||||
# config/environments/production.rb
|
||||
Rails.application.configure do
|
||||
config.force_ssl = true
|
||||
# Only use when all requests pass through a proxy that rejects or redirects HTTP.
|
||||
config.assume_ssl = true # behind a proxy that terminates TLS
|
||||
|
||||
# Reject requests with unexpected Host headers.
|
||||
config.hosts << "example.com"
|
||||
config.hosts << /.*\.example\.com/
|
||||
|
||||
config.action_dispatch.cookies_same_site_protection = :lax
|
||||
config.log_level = :info
|
||||
end
|
||||
```
|
||||
|
||||
Filter sensitive values out of logs:
|
||||
|
||||
```ruby
|
||||
# config/initializers/filter_parameter_logging.rb
|
||||
Rails.application.config.filter_parameters += %i[
|
||||
passw secret token _key crypt salt certificate otp ssn cvv card_number
|
||||
]
|
||||
```
|
||||
|
||||
## Authentication
|
||||
|
||||
Rails 8 ships an authentication generator that produces session-based auth with password
|
||||
reset and metadata tracking:
|
||||
|
||||
```bash
|
||||
bin/rails generate authentication
|
||||
```
|
||||
|
||||
Use Devise when you need OAuth, MFA, confirmable, lockable, or multi-model auth. For
|
||||
hand-rolled auth, `has_secure_password` handles bcrypt hashing:
|
||||
|
||||
```ruby
|
||||
class User < ApplicationRecord
|
||||
has_secure_password
|
||||
|
||||
validates :email, presence: true, uniqueness: { case_sensitive: false }
|
||||
validates :password, length: { minimum: 12 }, allow_nil: true
|
||||
end
|
||||
```
|
||||
|
||||
`authenticate_by` looks up and verifies in one call, so a missing user and a wrong password
|
||||
take the same time:
|
||||
|
||||
```ruby
|
||||
# Bad: the timing difference reveals whether the email exists
|
||||
user = User.find_by(email: params[:email])
|
||||
if user&.authenticate(params[:password])
|
||||
|
||||
# Good
|
||||
user = User.authenticate_by(email: params[:email], password: params[:password])
|
||||
```
|
||||
|
||||
Rotate the session on sign-in and on any privilege change:
|
||||
|
||||
```ruby
|
||||
class SessionsController < ApplicationController
|
||||
def create
|
||||
user = User.authenticate_by(email: params[:email], password: params[:password])
|
||||
return render :new, status: :unprocessable_entity unless user
|
||||
|
||||
reset_session
|
||||
session[:user_id] = user.id
|
||||
redirect_to root_path
|
||||
end
|
||||
|
||||
def destroy
|
||||
reset_session
|
||||
redirect_to root_path
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
### Account recovery
|
||||
|
||||
Password reset tokens must expire, be single-use, and not reveal whether an account exists.
|
||||
Signed tokens generated by the model give you both:
|
||||
|
||||
```ruby
|
||||
class User < ApplicationRecord
|
||||
generates_token_for :password_reset, expires_in: 15.minutes do
|
||||
password_salt&.last(10) # invalidates the token once the password changes
|
||||
end
|
||||
end
|
||||
|
||||
user = User.find_by_token_for(:password_reset, params[:token])
|
||||
```
|
||||
|
||||
Render the same response whether or not the address matched.
|
||||
|
||||
## Authorization
|
||||
|
||||
Authentication is not authorization. Every action that touches a record must check that the
|
||||
current user may act on it.
|
||||
|
||||
```ruby
|
||||
# Bad: any signed-in user can load any invoice
|
||||
@invoice = Invoice.find(params[:id])
|
||||
|
||||
# Good: scope through the owner
|
||||
@invoice = current_user.invoices.find(params[:id])
|
||||
```
|
||||
|
||||
For anything past ownership, use a policy object (Pundit, Action Policy, or CanCanCan):
|
||||
|
||||
```ruby
|
||||
class InvoicePolicy < ApplicationPolicy
|
||||
def update?
|
||||
user.admin? || record.user_id == user.id
|
||||
end
|
||||
end
|
||||
|
||||
class InvoicesController < ApplicationController
|
||||
def update
|
||||
@invoice = Invoice.find(params[:id])
|
||||
authorize @invoice
|
||||
# ...
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
Fail closed — verify that authorization ran rather than trusting each action to remember:
|
||||
|
||||
```ruby
|
||||
class ApplicationController < ActionController::Base
|
||||
include Pundit::Authorization
|
||||
|
||||
after_action :verify_authorized, except: :index
|
||||
after_action :verify_policy_scoped, only: :index
|
||||
end
|
||||
|
||||
# Public actions have no record to authorize, so exempt them explicitly.
|
||||
class SessionsController < ApplicationController
|
||||
skip_after_action :verify_authorized
|
||||
end
|
||||
```
|
||||
|
||||
## Strong Parameters and Mass Assignment
|
||||
|
||||
Never pass raw `params` to a model. Permit an explicit list:
|
||||
|
||||
```ruby
|
||||
# Bad: a crafted request can set admin
|
||||
User.new(params[:user])
|
||||
|
||||
# Good
|
||||
def user_params
|
||||
params.require(:user).permit(:email, :name)
|
||||
end
|
||||
```
|
||||
|
||||
Rails 8 adds `expect`, which raises on a malformed structure instead of returning an empty
|
||||
hash:
|
||||
|
||||
```ruby
|
||||
def user_params
|
||||
params.expect(user: [:email, :name])
|
||||
end
|
||||
```
|
||||
|
||||
Attributes such as `admin`, `role`, `user_id`, and `account_id` should never appear in a
|
||||
permit list driven by request data. Assign them explicitly from the session or a checked
|
||||
policy.
|
||||
|
||||
## SQL Injection
|
||||
|
||||
Active Record parameterizes by default. Injection appears when a string is built by hand:
|
||||
|
||||
```ruby
|
||||
# Bad
|
||||
User.where("email = '#{params[:email]}'")
|
||||
Order.order("#{params[:sort]} #{params[:dir]}")
|
||||
|
||||
# Good
|
||||
User.where(email: params[:email])
|
||||
User.where("email = ?", params[:email])
|
||||
```
|
||||
|
||||
`order`, `pluck`, `group`, and `select` accept raw SQL and are not sanitized. Allowlist the
|
||||
input rather than escaping it:
|
||||
|
||||
```ruby
|
||||
SORTABLE = { "created_at" => "created_at", "total" => "total" }.freeze
|
||||
DIRECTIONS = { "asc" => "ASC", "desc" => "DESC" }.freeze
|
||||
|
||||
column = SORTABLE.fetch(params[:sort], "created_at")
|
||||
direction = DIRECTIONS.fetch(params[:dir], "DESC")
|
||||
Order.order(Arel.sql("#{column} #{direction}"))
|
||||
```
|
||||
|
||||
`LIKE` needs its own escaping, since `%` and `_` are wildcards:
|
||||
|
||||
```ruby
|
||||
term = User.sanitize_sql_like(params[:q])
|
||||
User.where("name LIKE ?", "%#{term}%")
|
||||
```
|
||||
|
||||
## XSS and Output Escaping
|
||||
|
||||
ERB escapes interpolated values by default. Every bypass is security-sensitive:
|
||||
|
||||
```erb
|
||||
<%# Bad: renders attacker-controlled markup %>
|
||||
<%= @comment.body.html_safe %>
|
||||
<%= raw @comment.body %>
|
||||
|
||||
<%# Good: escaped %>
|
||||
<%= @comment.body %>
|
||||
|
||||
<%# Good: allowlisted markup when the field is genuinely rich text %>
|
||||
<%= sanitize @comment.body, tags: %w[p br strong em a], attributes: %w[href] %>
|
||||
```
|
||||
|
||||
`html_safe` does not sanitize — it marks a string as already safe and skips escaping. Only
|
||||
call it on strings you constructed.
|
||||
|
||||
Interpolating into JavaScript needs the matching escape, not the HTML one:
|
||||
|
||||
```erb
|
||||
<script>
|
||||
const payload = <%= raw @data.to_json %>; // Bad
|
||||
const payload = <%= raw json_escape(@data.to_json) %>; // Good
|
||||
</script>
|
||||
```
|
||||
|
||||
`link_to`'s href accepts `javascript:` URLs, so validate user-supplied links:
|
||||
|
||||
```ruby
|
||||
uri = URI.parse(url) rescue nil
|
||||
safe = uri.is_a?(URI::HTTP) # URI::HTTPS subclasses URI::HTTP
|
||||
```
|
||||
|
||||
Set a Content Security Policy:
|
||||
|
||||
```ruby
|
||||
# config/initializers/content_security_policy.rb
|
||||
Rails.application.configure do
|
||||
config.content_security_policy do |policy|
|
||||
policy.default_src :self
|
||||
policy.script_src :self
|
||||
policy.object_src :none
|
||||
policy.frame_ancestors :none
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
## CSRF
|
||||
|
||||
Rails enables CSRF protection for new apps. Keep it on, and do not exempt actions to make a
|
||||
client work:
|
||||
|
||||
```ruby
|
||||
# Bad: disables protection for every action in the controller
|
||||
skip_before_action :verify_authenticity_token
|
||||
```
|
||||
|
||||
If an endpoint genuinely cannot carry the token — a third-party webhook, say — authenticate
|
||||
it another way (signature verification) and scope the exemption to that action alone.
|
||||
|
||||
API-only controllers inheriting from `ActionController::API` have no cookie session, so CSRF
|
||||
does not apply; token or session-cookie APIs still need it.
|
||||
|
||||
## File Uploads
|
||||
|
||||
The `content_type` a client sends is attacker-controlled, and `blob.content_type` is not a
|
||||
substitute for it. Active Storage derives that column through `Marcel::MimeType.for`, which
|
||||
treats the client's declared type as one candidate alongside magic-byte detection and keeps
|
||||
it when the bytes match nothing known — so opaque bytes declared `image/png` are stored as
|
||||
`image/png` with `identified?` true. Inspect the stored bytes yourself:
|
||||
|
||||
```ruby
|
||||
module Uploads
|
||||
Rejected = Class.new(StandardError)
|
||||
|
||||
MAGIC = {
|
||||
"application/pdf" => "%PDF-".b,
|
||||
"image/png" => "\x89PNG\r\n\x1a\n".b,
|
||||
"image/jpeg" => "\xFF\xD8\xFF".b
|
||||
}.freeze
|
||||
ALLOWED_EXTENSIONS = %w[.pdf .png .jpg .jpeg].freeze
|
||||
MAX_BYTES = 10.megabytes
|
||||
|
||||
def self.verified!(blob)
|
||||
# Fail closed: an object that is missing or still pending cannot be inspected.
|
||||
raise Rejected, "could not be verified" unless blob.service.exist?(blob.key)
|
||||
raise Rejected, "is too large" if blob.byte_size > MAX_BYTES
|
||||
|
||||
extension = File.extname(blob.filename.to_s).downcase
|
||||
raise Rejected, "extension not allowed" unless ALLOWED_EXTENSIONS.include?(extension)
|
||||
|
||||
head = blob.service.download_chunk(blob.key, 0...8)
|
||||
raise Rejected, "type not allowed" unless MAGIC.any? { |_mime, magic| head.start_with?(magic) }
|
||||
|
||||
blob
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
The check reads from storage, so it has to run where the bytes already exist. A form upload
|
||||
is not yet in storage when model validations run — Active Storage uploads on save — so
|
||||
upload explicitly first, and attach only what passed:
|
||||
|
||||
```ruby
|
||||
# Form upload
|
||||
blob = ActiveStorage::Blob.create_and_upload!(io: params[:file], filename: params[:file].original_filename)
|
||||
document.file.attach(Uploads.verified!(blob))
|
||||
|
||||
# Direct upload: the client already stored the object, so verify before the record
|
||||
# points at it.
|
||||
document.file.attach(Uploads.verified!(ActiveStorage::Blob.find_signed!(params[:file])))
|
||||
```
|
||||
|
||||
Attach to a private service — a public bucket makes every upload world-readable regardless
|
||||
of the checks above.
|
||||
|
||||
```ruby
|
||||
has_one_attached :file, service: :private_documents
|
||||
```
|
||||
|
||||
`rails_blob_url` and `url_for(attachment)` are stable references that never expire; they
|
||||
redirect to a short-lived service URL, so anyone holding one keeps access. Serve
|
||||
user-scoped files from your own controller that authorizes each request, with
|
||||
`config.active_storage.draw_routes = false`, which removes every default Active Storage
|
||||
route; apps using direct uploads need a replacement route:
|
||||
|
||||
```ruby
|
||||
get "documents/:id/file", to: "document_files#show", as: :document_file
|
||||
# Rails' direct-upload endpoint has no authentication of its own. This example uses a
|
||||
# hand-rolled session sign-in; see Devise or the Rails 8 generator for their equivalents.
|
||||
constraints ->(req) { req.session[:user_id].present? } do
|
||||
post "uploads", to: "active_storage/direct_uploads#create", as: :rails_direct_uploads
|
||||
end
|
||||
|
||||
class DocumentPolicy < ApplicationPolicy
|
||||
def show?
|
||||
record.user_id == user.id
|
||||
end
|
||||
end
|
||||
|
||||
class DocumentFilesController < ApplicationController
|
||||
def show
|
||||
document = current_user.documents.find(params[:id])
|
||||
authorize document, :show?
|
||||
redirect_to document.file.blob.url(expires_in: 5.minutes), allow_other_host: true
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
Never interpolate a user-supplied path into `send_file`:
|
||||
|
||||
```ruby
|
||||
# Bad: path traversal
|
||||
send_file Rails.root.join("storage", params[:name])
|
||||
```
|
||||
|
||||
## API Security
|
||||
|
||||
Rate-limit authentication and other abusable endpoints. Action Controller ships
|
||||
`rate_limit` from Rails 7.2; use `rack-attack` on 7.1 or for app-wide throttling:
|
||||
|
||||
```ruby
|
||||
class SessionsController < ApplicationController
|
||||
rate_limit to: 10, within: 3.minutes, only: :create
|
||||
end
|
||||
```
|
||||
|
||||
Verify webhook signatures with a constant-time comparison:
|
||||
|
||||
```ruby
|
||||
class WebhooksController < ApplicationController
|
||||
skip_before_action :verify_authenticity_token, only: :create
|
||||
|
||||
def create
|
||||
expected = OpenSSL::HMAC.hexdigest("SHA256", ENV.fetch("WEBHOOK_SECRET"), request.raw_post)
|
||||
given = request.headers["X-Signature"].to_s
|
||||
|
||||
unless ActiveSupport::SecurityUtils.secure_compare(expected, given)
|
||||
return head :unauthorized
|
||||
end
|
||||
|
||||
event_id = JSON.parse(request.raw_post).fetch("id")
|
||||
delivery = WebhookDelivery.create_or_find_by!(provider: "billing", delivery_id: event_id)
|
||||
return head :ok if delivery.processed_at?
|
||||
|
||||
ProcessWebhookJob.perform_later(delivery.id, request.raw_post)
|
||||
head :ok
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
```ruby
|
||||
add_index :webhook_deliveries, %i[provider delivery_id], unique: true
|
||||
```
|
||||
|
||||
The job marks `processed_at` when it finishes. Jobs retry, so `perform` must be
|
||||
idempotent for the same reason. Requires a stable id in the signed body.
|
||||
|
||||
Keep CORS narrow — never reflect an arbitrary origin alongside credentials:
|
||||
|
||||
```ruby
|
||||
# Bad
|
||||
origins "*"
|
||||
|
||||
# Good
|
||||
origins "https://app.example.com"
|
||||
```
|
||||
|
||||
Serialize responses explicitly so new columns do not leak:
|
||||
|
||||
```ruby
|
||||
# Bad: ships every column, including ones added later
|
||||
render json: @user
|
||||
|
||||
# Good
|
||||
render json: @user.as_json(only: %i[id name created_at])
|
||||
```
|
||||
|
||||
## Secrets and Credentials
|
||||
|
||||
Secrets belong in Rails credentials, environment variables, or a secret manager:
|
||||
|
||||
```bash
|
||||
bin/rails credentials:edit --environment production
|
||||
```
|
||||
|
||||
`config/credentials/production.key` must stay out of version control. Read secrets through
|
||||
`Rails.application.credentials` or `ENV.fetch` — `ENV[...]` returns `nil` and fails silently
|
||||
when a variable is missing:
|
||||
|
||||
```ruby
|
||||
# Bad
|
||||
ENV["STRIPE_SECRET"]
|
||||
|
||||
# Good
|
||||
Rails.application.credentials.dig(:stripe, :secret)
|
||||
ENV.fetch("STRIPE_SECRET")
|
||||
```
|
||||
|
||||
If a key is ever committed, rotate it. Removing the commit does not un-expose it.
|
||||
|
||||
## Untrusted Boundaries
|
||||
|
||||
Controller params are not the only entry point. Job arguments, webhook payloads, Action
|
||||
Cable messages, and Turbo Stream targets all carry outside data:
|
||||
|
||||
- Pass record IDs to jobs and re-scope inside `perform`; a queued job runs without the
|
||||
original request's session.
|
||||
- Authorize in `ApplicationCable::Connection` and in each channel's `subscribed`.
|
||||
- Never build a Turbo Stream target from user input.
|
||||
|
||||
```ruby
|
||||
class ExportJob < ApplicationJob
|
||||
def perform(user_id, invoice_id)
|
||||
user = User.find(user_id)
|
||||
invoice = user.invoices.find(invoice_id) # scoped, not Invoice.find
|
||||
# ...
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
## Dependency Scanning
|
||||
|
||||
Run these when the lockfile changes, and in CI:
|
||||
|
||||
```bash
|
||||
bundle exec bundle-audit check --update
|
||||
bundle exec brakeman --no-progress
|
||||
```
|
||||
|
||||
Brakeman flags the patterns above statically. Treat new warnings as blocking, and record
|
||||
deliberate exceptions in `config/brakeman.ignore` with a reason rather than lowering the
|
||||
confidence threshold.
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
- [ ] `force_ssl` and `config.hosts` set in production
|
||||
- [ ] Sensitive parameters filtered from logs
|
||||
- [ ] Sessions rotated on sign-in and privilege change
|
||||
- [ ] Every record lookup scoped to the current user or checked by a policy
|
||||
- [ ] No permit list contains a role, ownership, or account column
|
||||
- [ ] No raw SQL string interpolation; `order` and `pluck` inputs allowlisted
|
||||
- [ ] Every `html_safe` and `raw` reviewed
|
||||
- [ ] CSRF exemptions scoped to specific actions with another auth mechanism
|
||||
- [ ] Uploads validated against stored bytes, not `blob.content_type`, and fail closed when the object is unavailable
|
||||
- [ ] Auth endpoints rate-limited; webhook signatures compared in constant time
|
||||
- [ ] No secrets in version control; master key excluded
|
||||
- [ ] `bundle-audit` and `brakeman` clean
|
||||
|
||||
## Related Skills
|
||||
|
||||
- `rails-patterns` — the architectural patterns these controls sit inside
|
||||
- `security-review` — secure-by-default review patterns across languages
|
||||
- Ruby security rules (`rules/ruby/security.md`, installed as `rules/ecc/ruby/security.md`)
|
||||
— the decisions and when-to-use guidance this skill implements
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
# Dependencies for uploads.rb, which exercises the skills/rails-security upload verifier
|
||||
# against a real Active Storage lifecycle. 7.1 is the Rails floor the skill advertises.
|
||||
source "https://rubygems.org"
|
||||
|
||||
gem "rails", ">= 7.1", "< 9.0"
|
||||
gem "sqlite3"
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
GEM
|
||||
remote: https://rubygems.org/
|
||||
specs:
|
||||
actioncable (8.0.5.1)
|
||||
actionpack (= 8.0.5.1)
|
||||
activesupport (= 8.0.5.1)
|
||||
nio4r (~> 2.0)
|
||||
websocket-driver (>= 0.6.1)
|
||||
zeitwerk (~> 2.6)
|
||||
actionmailbox (8.0.5.1)
|
||||
actionpack (= 8.0.5.1)
|
||||
activejob (= 8.0.5.1)
|
||||
activerecord (= 8.0.5.1)
|
||||
activestorage (= 8.0.5.1)
|
||||
activesupport (= 8.0.5.1)
|
||||
mail (>= 2.8.0)
|
||||
actionmailer (8.0.5.1)
|
||||
actionpack (= 8.0.5.1)
|
||||
actionview (= 8.0.5.1)
|
||||
activejob (= 8.0.5.1)
|
||||
activesupport (= 8.0.5.1)
|
||||
mail (>= 2.8.0)
|
||||
rails-dom-testing (~> 2.2)
|
||||
actionpack (8.0.5.1)
|
||||
actionview (= 8.0.5.1)
|
||||
activesupport (= 8.0.5.1)
|
||||
nokogiri (>= 1.8.5)
|
||||
rack (>= 2.2.4)
|
||||
rack-session (>= 1.0.1)
|
||||
rack-test (>= 0.6.3)
|
||||
rails-dom-testing (~> 2.2)
|
||||
rails-html-sanitizer (~> 1.6)
|
||||
useragent (~> 0.16)
|
||||
actiontext (8.0.5.1)
|
||||
actionpack (= 8.0.5.1)
|
||||
activerecord (= 8.0.5.1)
|
||||
activestorage (= 8.0.5.1)
|
||||
activesupport (= 8.0.5.1)
|
||||
globalid (>= 0.6.0)
|
||||
nokogiri (>= 1.8.5)
|
||||
actionview (8.0.5.1)
|
||||
activesupport (= 8.0.5.1)
|
||||
builder (~> 3.1)
|
||||
erubi (~> 1.11)
|
||||
rails-dom-testing (~> 2.2)
|
||||
rails-html-sanitizer (~> 1.6)
|
||||
activejob (8.0.5.1)
|
||||
activesupport (= 8.0.5.1)
|
||||
globalid (>= 0.3.6)
|
||||
activemodel (8.0.5.1)
|
||||
activesupport (= 8.0.5.1)
|
||||
activerecord (8.0.5.1)
|
||||
activemodel (= 8.0.5.1)
|
||||
activesupport (= 8.0.5.1)
|
||||
timeout (>= 0.4.0)
|
||||
activestorage (8.0.5.1)
|
||||
actionpack (= 8.0.5.1)
|
||||
activejob (= 8.0.5.1)
|
||||
activerecord (= 8.0.5.1)
|
||||
activesupport (= 8.0.5.1)
|
||||
marcel (~> 1.0)
|
||||
activesupport (8.0.5.1)
|
||||
base64
|
||||
benchmark (>= 0.3)
|
||||
bigdecimal
|
||||
concurrent-ruby (~> 1.0, >= 1.3.1)
|
||||
connection_pool (>= 2.2.5)
|
||||
drb
|
||||
i18n (>= 1.6, < 2)
|
||||
logger (>= 1.4.2)
|
||||
minitest (>= 5.1)
|
||||
securerandom (>= 0.3)
|
||||
tzinfo (~> 2.0, >= 2.0.5)
|
||||
uri (>= 0.13.1)
|
||||
base64 (0.3.0)
|
||||
benchmark (0.5.0)
|
||||
bigdecimal (4.1.2)
|
||||
builder (3.3.0)
|
||||
concurrent-ruby (1.3.8)
|
||||
connection_pool (3.0.2)
|
||||
crass (1.0.7)
|
||||
date (3.5.1)
|
||||
drb (2.2.3)
|
||||
erb (6.0.7)
|
||||
erubi (1.13.1)
|
||||
globalid (1.4.0)
|
||||
activesupport (>= 6.1)
|
||||
i18n (1.15.2)
|
||||
concurrent-ruby (~> 1.0)
|
||||
io-console (0.9.5)
|
||||
irb (1.19.0)
|
||||
pp (>= 0.6.0)
|
||||
prism (>= 1.3.0)
|
||||
rdoc (>= 4.0.0)
|
||||
reline (>= 0.4.2)
|
||||
logger (1.7.0)
|
||||
loofah (2.25.2)
|
||||
crass (~> 1.0.2)
|
||||
nokogiri (>= 1.12.0)
|
||||
mail (2.9.1)
|
||||
logger
|
||||
mini_mime (>= 0.1.1)
|
||||
net-imap
|
||||
net-pop
|
||||
net-smtp
|
||||
marcel (1.2.1)
|
||||
mini_mime (1.1.5)
|
||||
minitest (6.0.6)
|
||||
drb (~> 2.0)
|
||||
prism (~> 1.5)
|
||||
net-imap (0.6.6)
|
||||
date
|
||||
net-protocol
|
||||
net-pop (0.1.2)
|
||||
net-protocol
|
||||
net-protocol (0.2.2)
|
||||
timeout
|
||||
net-smtp (0.5.1)
|
||||
net-protocol
|
||||
nio4r (2.7.5)
|
||||
nokogiri (1.19.4-arm64-darwin)
|
||||
racc (~> 1.4)
|
||||
nokogiri (1.19.4-x86_64-linux-gnu)
|
||||
racc (~> 1.4)
|
||||
pp (0.6.4)
|
||||
prettyprint
|
||||
prettyprint (0.2.1)
|
||||
prism (1.9.0)
|
||||
racc (1.8.1)
|
||||
rack (3.2.6)
|
||||
rack-session (2.1.2)
|
||||
base64 (>= 0.1.0)
|
||||
rack (>= 3.0.0)
|
||||
rack-test (2.2.0)
|
||||
rack (>= 1.3)
|
||||
rackup (2.3.1)
|
||||
rack (>= 3)
|
||||
rails (8.0.5.1)
|
||||
actioncable (= 8.0.5.1)
|
||||
actionmailbox (= 8.0.5.1)
|
||||
actionmailer (= 8.0.5.1)
|
||||
actionpack (= 8.0.5.1)
|
||||
actiontext (= 8.0.5.1)
|
||||
actionview (= 8.0.5.1)
|
||||
activejob (= 8.0.5.1)
|
||||
activemodel (= 8.0.5.1)
|
||||
activerecord (= 8.0.5.1)
|
||||
activestorage (= 8.0.5.1)
|
||||
activesupport (= 8.0.5.1)
|
||||
bundler (>= 1.15.0)
|
||||
railties (= 8.0.5.1)
|
||||
rails-dom-testing (2.3.0)
|
||||
activesupport (>= 5.0.0)
|
||||
minitest
|
||||
nokogiri (>= 1.6)
|
||||
rails-html-sanitizer (1.7.1)
|
||||
loofah (~> 2.25, >= 2.25.2)
|
||||
nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0)
|
||||
railties (8.0.5.1)
|
||||
actionpack (= 8.0.5.1)
|
||||
activesupport (= 8.0.5.1)
|
||||
irb (~> 1.13)
|
||||
rackup (>= 1.0.0)
|
||||
rake (>= 12.2)
|
||||
thor (~> 1.0, >= 1.2.2)
|
||||
tsort (>= 0.2)
|
||||
zeitwerk (~> 2.6)
|
||||
rake (13.4.2)
|
||||
rbs (4.1.3)
|
||||
logger
|
||||
prism (>= 1.6.0)
|
||||
tsort
|
||||
rdoc (8.1.0)
|
||||
erb
|
||||
prism (>= 1.6.0)
|
||||
rbs (>= 4.0.0)
|
||||
tsort
|
||||
reline (0.7.0)
|
||||
io-console (~> 0.5)
|
||||
securerandom (0.4.1)
|
||||
sqlite3 (2.8.0-arm64-darwin)
|
||||
sqlite3 (2.8.0-x86_64-linux-gnu)
|
||||
thor (1.5.0)
|
||||
timeout (0.6.1)
|
||||
tsort (0.2.0)
|
||||
tzinfo (2.0.6)
|
||||
concurrent-ruby (~> 1.0)
|
||||
uri (1.1.1)
|
||||
useragent (0.16.11)
|
||||
websocket-driver (0.8.2)
|
||||
base64
|
||||
websocket-extensions (>= 0.1.0)
|
||||
websocket-extensions (0.1.5)
|
||||
zeitwerk (2.8.3)
|
||||
|
||||
PLATFORMS
|
||||
arm64-darwin
|
||||
x86_64-linux
|
||||
|
||||
DEPENDENCIES
|
||||
rails (>= 7.1, < 9.0)
|
||||
sqlite3
|
||||
|
||||
BUNDLED WITH
|
||||
2.7.2
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
# Exercises the upload verifier published in skills/rails-security/SKILL.md against a real
|
||||
# Active Storage lifecycle: a migrated database, a disk service holding real bytes, and
|
||||
# blobs created the way Rails creates them.
|
||||
#
|
||||
# Prints one JSON object per case to stdout. tests/skills/rails-security.test.js asserts on
|
||||
# that output, so the contract is the JSON rather than this script's exit status.
|
||||
|
||||
require "json"
|
||||
require "tmpdir"
|
||||
require "fileutils"
|
||||
require "stringio"
|
||||
require "digest"
|
||||
require "rails"
|
||||
require "active_record/railtie"
|
||||
require "active_storage/engine"
|
||||
|
||||
ROOT = Dir.mktmpdir("ecc-rails-security-")
|
||||
at_exit { FileUtils.remove_entry(ROOT, true) }
|
||||
|
||||
FileUtils.mkdir_p(File.join(ROOT, "config"))
|
||||
File.write(File.join(ROOT, "config", "database.yml"), <<~YAML)
|
||||
test:
|
||||
adapter: sqlite3
|
||||
database: ":memory:"
|
||||
YAML
|
||||
|
||||
class FixtureApp < Rails::Application
|
||||
config.root = ROOT
|
||||
config.eager_load = false
|
||||
config.logger = Logger.new(IO::NULL)
|
||||
config.secret_key_base = "fixture-only-not-a-secret"
|
||||
config.active_support.to_time_preserves_timezone = :zone
|
||||
config.active_storage.service = :fixture_disk
|
||||
config.active_storage.service_configurations = {
|
||||
"fixture_disk" => { "service" => "Disk", "root" => File.join(ROOT, "storage") }
|
||||
}
|
||||
end
|
||||
|
||||
FixtureApp.initialize!
|
||||
|
||||
ActiveRecord::Migration.verbose = false
|
||||
|
||||
ActiveRecord::Schema.define do
|
||||
create_table :documents
|
||||
|
||||
create_table :active_storage_blobs do |t|
|
||||
t.string :key, null: false
|
||||
t.string :filename, null: false
|
||||
t.string :content_type
|
||||
t.text :metadata
|
||||
t.string :service_name, null: false
|
||||
t.bigint :byte_size, null: false
|
||||
t.string :checksum
|
||||
t.datetime :created_at, null: false
|
||||
t.index [:key], unique: true
|
||||
end
|
||||
|
||||
create_table :active_storage_attachments do |t|
|
||||
t.string :name, null: false
|
||||
t.references :record, null: false, polymorphic: true, index: false
|
||||
t.bigint :blob_id, null: false
|
||||
t.datetime :created_at, null: false
|
||||
t.index %i[record_type record_id name blob_id],
|
||||
name: :index_active_storage_attachments_uniqueness, unique: true
|
||||
end
|
||||
|
||||
create_table :active_storage_variant_records do |t|
|
||||
t.bigint :blob_id, null: false
|
||||
t.string :variation_digest, null: false
|
||||
t.index %i[blob_id variation_digest],
|
||||
name: :index_active_storage_variant_records_uniqueness, unique: true
|
||||
end
|
||||
end
|
||||
|
||||
class ApplicationRecord < ActiveRecord::Base
|
||||
self.abstract_class = true
|
||||
end
|
||||
|
||||
class Document < ApplicationRecord
|
||||
has_one_attached :file
|
||||
end
|
||||
|
||||
# --- The published verifier, copied from the skill --------------------------------------
|
||||
|
||||
module Uploads
|
||||
Rejected = Class.new(StandardError)
|
||||
|
||||
MAGIC = {
|
||||
"application/pdf" => "%PDF-".b,
|
||||
"image/png" => "\x89PNG\r\n\x1a\n".b,
|
||||
"image/jpeg" => "\xFF\xD8\xFF".b
|
||||
}.freeze
|
||||
ALLOWED_EXTENSIONS = %w[.pdf .png .jpg .jpeg].freeze
|
||||
MAX_BYTES = 10.megabytes
|
||||
|
||||
def self.verified!(blob)
|
||||
# Fail closed: an object that is missing or still pending cannot be inspected.
|
||||
raise Rejected, "could not be verified" unless blob.service.exist?(blob.key)
|
||||
raise Rejected, "is too large" if blob.byte_size > MAX_BYTES
|
||||
|
||||
extension = File.extname(blob.filename.to_s).downcase
|
||||
raise Rejected, "extension not allowed" unless ALLOWED_EXTENSIONS.include?(extension)
|
||||
|
||||
head = blob.service.download_chunk(blob.key, 0...8)
|
||||
raise Rejected, "type not allowed" unless MAGIC.any? { |_mime, magic| head.start_with?(magic) }
|
||||
|
||||
blob
|
||||
end
|
||||
end
|
||||
|
||||
# --- Cases ------------------------------------------------------------------------------
|
||||
|
||||
PNG_BYTES = "\x89PNG\r\n\x1a\n".b + ("\x00".b * 64)
|
||||
ZIP_BYTES = "PK\x03\x04".b + ("\x00".b * 64)
|
||||
OPAQUE_BYTES = "\x01\x02\x03\x04".b * 20
|
||||
|
||||
def upload(bytes, filename, declared)
|
||||
ActiveStorage::Blob.create_and_upload!(
|
||||
io: StringIO.new(bytes), filename: filename, content_type: declared
|
||||
)
|
||||
end
|
||||
|
||||
def report(name, blob)
|
||||
outcome = nil
|
||||
begin
|
||||
document = Document.create!
|
||||
document.file.attach(Uploads.verified!(blob))
|
||||
outcome = { case: name, attached: document.reload.file.attached?, rejected: nil }
|
||||
rescue Uploads::Rejected => error
|
||||
outcome = { case: name, attached: false, rejected: error.message }
|
||||
end
|
||||
puts JSON.generate(outcome.merge(
|
||||
stored_content_type: blob.content_type,
|
||||
identified: blob.identified?
|
||||
))
|
||||
end
|
||||
|
||||
# 1. A real PNG passes.
|
||||
report("legitimate_png", upload(PNG_BYTES, "chart.png", "image/png"))
|
||||
|
||||
# 2. Opaque bytes declared image/png. Marcel matches no magic, keeps the declared type,
|
||||
# and marks the blob identified — so content_type agrees with the attacker.
|
||||
report("opaque_declared_png", upload(OPAQUE_BYTES, "payload.png", "image/png"))
|
||||
|
||||
# 3. A ZIP declared image/png. Identification does detect the real type here, which is
|
||||
# why content_type cannot be the single gate either way.
|
||||
report("zip_declared_png", upload(ZIP_BYTES, "payload.png", "image/png"))
|
||||
|
||||
# 4. A disallowed extension on otherwise valid bytes.
|
||||
report("png_bytes_bad_extension", upload(PNG_BYTES, "chart.svg", "image/png"))
|
||||
|
||||
# 5. A direct upload whose object never arrived: the row exists, the bytes do not.
|
||||
pending = ActiveStorage::Blob.create_before_direct_upload!(
|
||||
filename: "pending.png", byte_size: PNG_BYTES.bytesize,
|
||||
checksum: Digest::MD5.base64digest(PNG_BYTES), content_type: "image/png"
|
||||
)
|
||||
pending.update!(identified: true)
|
||||
report("pending_direct_upload", pending)
|
||||
|
||||
# 6. The object is deleted after identification recorded a type. The row still claims
|
||||
# image/png, so only an explicit existence check catches it.
|
||||
vanished = upload(PNG_BYTES, "vanished.png", "image/png")
|
||||
vanished.service.delete(vanished.key)
|
||||
report("deleted_after_identification", vanished)
|
||||
@@ -0,0 +1,182 @@
|
||||
'use strict';
|
||||
|
||||
// Tests for the rails-security skill: the SKILL.md upload guidance must match what Rails
|
||||
// actually does. Assert the document's claims, then run the real Active Storage fixture so
|
||||
// the published example and its verified behavior share one source.
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { spawnSync } = require('child_process');
|
||||
|
||||
const repoRoot = path.resolve(__dirname, '..', '..');
|
||||
const skillPath = path.join(repoRoot, 'skills', 'rails-security', 'SKILL.md');
|
||||
const fixturePath = path.join(repoRoot, 'tests', 'fixtures', 'rails-security', 'uploads.rb');
|
||||
const skill = fs.readFileSync(skillPath, 'utf8');
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
let skipped = 0;
|
||||
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
passed += 1;
|
||||
console.log(` ✓ ${name}`);
|
||||
} catch (error) {
|
||||
failed += 1;
|
||||
console.log(` ✗ ${name}`);
|
||||
console.log(` ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function skip(name, reason) {
|
||||
skipped += 1;
|
||||
console.log(` - ${name} (${reason})`);
|
||||
}
|
||||
|
||||
console.log('\n=== Rails security skill tests ===\n');
|
||||
|
||||
// ---- Skill document claims ---------------------------------------------
|
||||
|
||||
test('upload guidance does not treat blob.content_type as byte evidence', () => {
|
||||
assert.doesNotMatch(skill, /ALLOWED\.include\?\(\s*(file\.)?blob\.content_type\s*\)/);
|
||||
assert.doesNotMatch(skill, /identify unless .*identified\?/);
|
||||
assert.match(skill, /download_chunk\(blob\.key, 0\.\.\.8\)/);
|
||||
});
|
||||
|
||||
test('upload guidance states the declared-type fallback', () => {
|
||||
assert.match(skill, /Marcel::MimeType\.for/);
|
||||
assert.match(skill, /bytes match nothing known/);
|
||||
});
|
||||
|
||||
test('upload guidance fails closed on an unavailable object', () => {
|
||||
assert.match(skill, /blob\.service\.exist\?\(blob\.key\)/);
|
||||
assert.match(skill, /could not be verified/);
|
||||
});
|
||||
|
||||
test('upload guidance names both upload entry points', () => {
|
||||
assert.match(skill, /ActiveStorage::Blob\.create_and_upload!/);
|
||||
assert.match(skill, /ActiveStorage::Blob\.find_signed!/);
|
||||
});
|
||||
|
||||
test('verification checklist matches the byte-level guidance', () => {
|
||||
assert.match(skill, /Uploads validated against stored bytes, not `blob\.content_type`/);
|
||||
});
|
||||
|
||||
// ---- The fixture carries the published verifier verbatim ----------------
|
||||
|
||||
function uploadsModule(source) {
|
||||
const start = source.indexOf('module Uploads');
|
||||
const end = source.indexOf('\nend\n', source.indexOf('def self.verified!'));
|
||||
assert.ok(start > -1 && end > start, 'Uploads module not found');
|
||||
return source.slice(start, end + 5).trim();
|
||||
}
|
||||
|
||||
test('fixture verifier has not drifted from the published example', () => {
|
||||
const documented = uploadsModule(skill);
|
||||
const fixture = uploadsModule(fs.readFileSync(fixturePath, 'utf8'));
|
||||
assert.strictEqual(fixture, documented, 'fixture drifted from the skill');
|
||||
});
|
||||
|
||||
// ---- Execute the fixture against a real Active Storage lifecycle --------
|
||||
|
||||
// Prefer `bundle exec` so a bundled Rails is found, and fall back to a plain
|
||||
// interpreter for developers who already have the gems installed.
|
||||
const RUNNERS = [
|
||||
['bundle', ['exec', 'ruby']],
|
||||
['ruby', []],
|
||||
];
|
||||
|
||||
function runFixture() {
|
||||
const env = { ...process.env, RAILS_ENV: 'test' };
|
||||
const probeSource = 'require "rails"; require "active_storage/engine"';
|
||||
|
||||
for (const [command, prefix] of RUNNERS) {
|
||||
const probe = spawnSync(command, [...prefix, '-e', probeSource], {
|
||||
encoding: 'utf8',
|
||||
cwd: path.dirname(fixturePath),
|
||||
env,
|
||||
});
|
||||
if (probe.error || probe.status !== 0) continue;
|
||||
|
||||
const result = spawnSync(command, [...prefix, fixturePath], {
|
||||
encoding: 'utf8',
|
||||
cwd: path.dirname(fixturePath),
|
||||
env,
|
||||
});
|
||||
assert.strictEqual(result.status, 0, `fixture failed:\n${result.stderr}`);
|
||||
return result.stdout
|
||||
.split('\n')
|
||||
.filter(line => line.startsWith('{'))
|
||||
.map(line => JSON.parse(line));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const cases = runFixture();
|
||||
|
||||
if (cases === null) {
|
||||
// The CI lane sets this so a missing toolchain fails rather than passing silently.
|
||||
if (process.env.ECC_RAILS_FIXTURE_REQUIRED === '1') {
|
||||
failed += 1;
|
||||
console.log(' ✗ Active Storage lifecycle cases');
|
||||
console.log(' ECC_RAILS_FIXTURE_REQUIRED=1 but ruby with rails could not run the fixture');
|
||||
} else {
|
||||
skip('Active Storage lifecycle cases', 'ruby with rails and activestorage not available');
|
||||
}
|
||||
} else {
|
||||
const byName = new Map(cases.map(entry => [entry.case, entry]));
|
||||
const expectCase = name => {
|
||||
const entry = byName.get(name);
|
||||
assert.ok(entry, `fixture did not report the ${name} case`);
|
||||
return entry;
|
||||
};
|
||||
|
||||
test('a legitimate PNG is attached', () => {
|
||||
const result = expectCase('legitimate_png');
|
||||
assert.strictEqual(result.attached, true);
|
||||
assert.strictEqual(result.rejected, null);
|
||||
});
|
||||
|
||||
test('opaque bytes are stored under the declared type and still rejected', () => {
|
||||
const result = expectCase('opaque_declared_png');
|
||||
// The bypass: Rails kept the client's declared type and marked the blob identified.
|
||||
assert.strictEqual(result.stored_content_type, 'image/png');
|
||||
assert.strictEqual(result.identified, true);
|
||||
assert.strictEqual(result.attached, false);
|
||||
assert.strictEqual(result.rejected, 'type not allowed');
|
||||
});
|
||||
|
||||
test('a ZIP declared image/png is rejected', () => {
|
||||
const result = expectCase('zip_declared_png');
|
||||
assert.strictEqual(result.attached, false);
|
||||
assert.strictEqual(result.rejected, 'type not allowed');
|
||||
});
|
||||
|
||||
test('a disallowed extension is rejected on otherwise valid bytes', () => {
|
||||
const result = expectCase('png_bytes_bad_extension');
|
||||
assert.strictEqual(result.attached, false);
|
||||
assert.strictEqual(result.rejected, 'extension not allowed');
|
||||
});
|
||||
|
||||
test('a pending direct upload fails closed', () => {
|
||||
const result = expectCase('pending_direct_upload');
|
||||
assert.strictEqual(result.attached, false);
|
||||
assert.strictEqual(result.rejected, 'could not be verified');
|
||||
});
|
||||
|
||||
test('an object deleted after identification fails closed', () => {
|
||||
const result = expectCase('deleted_after_identification');
|
||||
assert.strictEqual(result.stored_content_type, 'image/png');
|
||||
assert.strictEqual(result.attached, false);
|
||||
assert.strictEqual(result.rejected, 'could not be verified');
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`\nPassed: ${passed}`);
|
||||
if (skipped > 0) console.log(`Skipped: ${skipped}`);
|
||||
if (failed > 0) {
|
||||
console.log(`Failed: ${failed}`);
|
||||
process.exit(1);
|
||||
}
|
||||
Reference in new issue
Block a user