Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .reek.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ detectors:
exclude:
- Gemfile#check_with_bundler_audit
- CreateGemfiles#change
- CreateApiKeys#change
InstanceVariableAssumption:
exclude:
- GemfilesController
Expand All @@ -38,6 +39,8 @@ detectors:
- BundlerAuditScannerStub
- CreateGemfiles
- AddAlphaIdToGemfiles
- CreateApiKeys
- ApiKeyTest
- BundlerAuditDatabasePreparerTest
- BundlerAuditDatabasePreparerTest::FakeLogger
TooManyInstanceVariables:
Expand All @@ -53,6 +56,7 @@ detectors:
exclude:
- BundlerAuditScannerStub#scan
- CreateGemfiles#change
- CreateApiKeys#change
UtilityFunction:
exclude:
- GemfilesController#vulnerabilities_count
Expand Down
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,69 @@ Also run before opening a PR:
bundle exec rubocop
bundle exec reek

## JSON API

You can upload a `Gemfile.lock` and get the bundler-audit report back as JSON. Every JSON request needs an `X-API-Key` header matching a key in the `api_keys` table. Otherwise it gets a `401`.

The table only stores a name and a SHA-256 digest of each key, so you can only see a key right when you create it. Give it a name and the key is generated for you:

```ruby
ApiKey.create!(name: "Acme").value
```

Copy it then. If it's lost, create a new key and delete the old row.

Upload a lockfile (returns `201` with the report, or `422` with `errors`):

```bash
curl -F "gemfile[file]=@Gemfile.lock" \
-H "X-API-Key: <your-api-key>" \
https://audit.fastruby.io/gemfiles.json
```

Fetch an existing report:

```bash
curl -H "X-API-Key: <your-api-key>" https://audit.fastruby.io/gemfiles/ABCD1234.json
```

Both return:

```json
{
"id": "ABCD1234",
"vulnerabilities_count": 1,
"warnings": [],
"advisories": [
{
"label": "rack@2.0.1",
"name": "rack",
"version": "2.0.1",
"id": "CVE-2024-47887",
"cve_id": "CVE-2024-47887",
"ghsa_id": "GHSA-vfg9-r3fq-jvx4",
"url": "https://...",
"title": "...",
"description": "...",
"criticality": "medium",
"cvss_v2": null,
"cvss_v3": 6.6,
"date": "2024-10-15",
"patched_versions": ["~> 7.1.4, >= 7.1.4.1", ">= 7.2.1.1"],
"unaffected_versions": []
}
],
"advisory_database": {
"commit_id": "0123456789abcdef0123456789abcdef01234567",
"committed_at": "2026-12-01T10:00:00-05:00"
}
}
```

`id` is the advisory's file name in [ruby-advisory-db](https://github.com/rubysec/ruby-advisory-db), usually its CVE or GHSA id; `cve_id` and `ghsa_id` are `null` when the advisory doesn't have one. `criticality` comes from the CVSS score (`none`, `low`, `medium`, `high` or `critical`), and is `null` without one.

`advisory_database` is the ruby-advisory-db commit the report was checked against (`null` if the database is missing). When it changes, a lockfile that was clean before may not be anymore. Each process updates the database at boot, and again before a scan once the last update is an hour old.

## Dual-boot Rails upgrades

This app uses the [`next_rails`](https://github.com/fastruby/next_rails) dual-boot pattern to upgrade Rails one minor version at a time. `Gemfile.next` is a symlink to `Gemfile`; the `if next?` check in `Gemfile` switches the Rails constraint when Bundler is invoked with `BUNDLE_GEMFILE=Gemfile.next` (e.g. `web_next` above, or CI).
Expand Down
34 changes: 34 additions & 0 deletions app/controllers/gemfiles_controller.rb
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
class GemfilesController < ApplicationController
API_KEY_HEADER = "X-API-Key".freeze

# JSON clients authenticate with an API key instead of a session, so there's
# no CSRF token to check. Browsers can't set the API key header cross-site.
skip_forgery_protection if: :json_request?
before_action :authenticate_api_key, if: :json_request?

def create
@file = Gemfile.new(gemfile_params)

respond_to do |format|
if @file.save
format.html { redirect_to gemfile_path(id: @file.alpha_id) }
format.json do
render json: report_json(@file, @file.check_with_bundler_audit), status: :created,
location: gemfile_url(id: @file.alpha_id, format: :json)
end
else
format.html do
flash[:error] = @file.errors.full_messages.join('. ')
redirect_to root_path
end
format.json do
render json: {errors: @file.errors.full_messages}, status: :unprocessable_content
end
end
end
end
Expand All @@ -23,6 +37,7 @@ def show

respond_to do |format|
format.html
format.json { render json: report_json(@file, @vulnerabilities) }
format.pdf do
render pdf: "vulnerabilities_list",
template: "gemfiles/show",
Expand All @@ -38,6 +53,25 @@ def gemfile_params
params.permit(gemfile: [:file])[:gemfile]
end

def json_request?
request.format.json?
end

def authenticate_api_key
return if ApiKey.valid_key?(request.headers[API_KEY_HEADER])

render json: {error: "Unauthorized"}, status: :unauthorized
end

def report_json(file, vulnerabilities)
{
id: file.alpha_id,
vulnerabilities_count: vulnerabilities_count(vulnerabilities),
**vulnerabilities,
advisory_database: BundlerAuditDatabasePreparer.revision
}
end

def render_vulnerabilities(file)
@renderer = Redcarpet::Render::HTML.new(prettify: true)
@markdown = Redcarpet::Markdown.new(@renderer, fenced_code_blocks: true)
Expand Down
31 changes: 31 additions & 0 deletions app/models/api_key.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Keys allowed to use the JSON API (see GemfilesController). Only a SHA-256
# digest of each key is stored, so `value` is readable just once, on the
# record that created it. Keys are long random tokens, so a fast digest is
# enough and lets us look them up with an indexed query.
class ApiKey < ApplicationRecord
attr_reader :value

validates :name, presence: true
validates :value_digest, presence: true, uniqueness: true

before_validation :generate_value, on: :create

def self.digest(value)
OpenSSL::Digest::SHA256.hexdigest(value)
end

def self.valid_key?(value)
value.present? && exists?(value_digest: digest(value))
end

def value=(value)
@value = value
self.value_digest = self.class.digest(value)
end

private

def generate_value
self.value = SecureRandom.base58(24) if value_digest.blank?
end
end
37 changes: 28 additions & 9 deletions app/models/gemfile.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,7 @@ def check_with_bundler_audit
when Bundler::Audit::Results::InsecureSource
@result[:warnings] << "Insecure Source URI found: #{result.source}"
when Bundler::Audit::Results::UnpatchedGem
@result[:advisories] << {
label: "#{result.gem.name}@#{result.gem.version.to_s}",
name: result.gem.name,
version: result.gem.version.to_s,
id: result.advisory.id,
url: result.advisory.url,
title: result.advisory.title,
description: result.advisory.description
}
@result[:advisories] << advisory_attributes(result.gem, result.advisory)
end
end

Expand Down Expand Up @@ -66,6 +58,7 @@ def temp_file
end

def scanner
BundlerAuditDatabasePreparer.refresh_if_stale
Bundler::Audit::Scanner.new(
File.dirname(temp_file.path),
File.basename(temp_file.path)
Expand All @@ -74,6 +67,32 @@ def scanner

private

# id is the advisory's file name in ruby-advisory-db, usually its CVE or
# GHSA id, but not always: cve_id and ghsa_id say which ids it has. The
# versions are requirements, like ">= 7.1.5".
# :reek:FeatureEnvy
def advisory_attributes(gem, advisory)
name = gem.name
version = gem.version.to_s
{
label: "#{name}@#{version}",
name: name,
version: version,
id: advisory.id,
cve_id: advisory.cve_id,
ghsa_id: advisory.ghsa_id,
url: advisory.url,
title: advisory.title,
description: advisory.description,
criticality: advisory.criticality&.to_s,
cvss_v2: advisory.cvss_v2,
cvss_v3: advisory.cvss_v3,
date: advisory.date&.iso8601,
patched_versions: Array(advisory.patched_versions).map(&:to_s),
unaffected_versions: Array(advisory.unaffected_versions).map(&:to_s)
}
end

def generate_alpha_id
return if alpha_id.present?

Expand Down
11 changes: 11 additions & 0 deletions db/migrate/20261204025827_create_api_keys.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class CreateApiKeys < ActiveRecord::Migration[8.1]
def change
create_table :api_keys do |t|
t.string :name, null: false
t.string :value_digest, null: false

t.timestamps
end
add_index :api_keys, :value_digest, unique: true
end
end
10 changes: 9 additions & 1 deletion db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,18 @@
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema[8.1].define(version: 2018_03_25_143727) do
ActiveRecord::Schema[8.1].define(version: 2026_12_04_025827) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"

create_table "api_keys", force: :cascade do |t|
t.datetime "created_at", null: false
t.string "name", null: false
t.datetime "updated_at", null: false
t.string "value_digest", null: false
t.index ["value_digest"], name: "index_api_keys_on_value_digest", unique: true
end

create_table "gemfiles", force: :cascade do |t|
t.string "alpha_id"
t.datetime "created_at", precision: nil, null: false
Expand Down
59 changes: 54 additions & 5 deletions lib/bundler_audit_database_preparer.rb
Original file line number Diff line number Diff line change
@@ -1,25 +1,74 @@
require "bundler/audit/database"
require "open3"

# Clones or updates the local ruby-advisory-db checkout that
# Bundler::Audit::Scanner needs. Failures are logged instead of raised so a
# transient clone/update problem never takes down app boot -- but they must
# be logged, not swallowed, or every later scan fails with an opaque
# ArgumentError ("... is not a directory") and no trace of why.
#
# Git runs with -C instead of through bundler-audit's Database#update! and
# #commit_id, which Dir.chdir: that changes the directory of the whole
# process, and Puma serves other requests from other threads meanwhile.
module BundlerAuditDatabasePreparer
# A dyno only restarts about once a day, so scans also refresh the database
# when the last attempt is older than this.
REFRESH_INTERVAL = 1.hour

@mutex = Mutex.new
@refreshed_at = Time.at(0)

def self.call(path: Bundler::Audit::Database.path, logger: Rails.logger)
# A failed attempt counts too, so an outage isn't retried on every scan.
@refreshed_at = Time.current
begin
if File.directory?(path)
Bundler::Audit::Database.new(path).update!(quiet: true)
else
Bundler::Audit::Database.download(path: path, quiet: true)
end
prepare(path)
rescue Bundler::Audit::Database::DownloadFailed, Bundler::Audit::Database::UpdateFailed => error
logger.error("[bundler-audit] Could not prepare ruby-advisory-db at #{path}: #{error.class}: #{error.message}")
end

log_if_still_missing(path, logger)
end

# Updates the database unless the last attempt was less than
# REFRESH_INTERVAL ago. Scans that start while another thread updates wait
# for it to finish.
def self.refresh_if_stale(path: Bundler::Audit::Database.path, logger: Rails.logger)
@mutex.synchronize do
call(path: path, logger: logger) if @refreshed_at <= REFRESH_INTERVAL.ago
end
end

def self.update(path)
return if git(path, "pull", "--quiet", "origin", "master")

raise Bundler::Audit::Database::UpdateFailed, "failed to update #{path.inspect}"
end

# The commit the database is at and when it was made, so API clients can tell
# whether the advisories changed since their last scan. nil when there's no
# database.
def self.revision(path: Bundler::Audit::Database.path)
commit_id, committed_at = git(path, "log", "-1", "--format=%H %cI")&.split
{commit_id: commit_id, committed_at: committed_at} if commit_id
end

def self.prepare(path)
if File.directory?(path)
update(path)
else
Bundler::Audit::Database.download(path: path, quiet: true)
end
end
private_class_method :prepare

# The command's output, or nil when it failed.
def self.git(path, *args)
output, _error, status = Open3.capture3("git", "-C", path.to_s, *args)
output.strip if status.success?
end
private_class_method :git

def self.log_if_still_missing(path, logger)
return if File.directory?(path)

Expand Down
Loading
Loading