diff --git a/.reek.yml b/.reek.yml index ded245b..ffec57b 100644 --- a/.reek.yml +++ b/.reek.yml @@ -12,6 +12,7 @@ detectors: exclude: - Gemfile#check_with_bundler_audit - CreateGemfiles#change + - CreateApiKeys#change InstanceVariableAssumption: exclude: - GemfilesController @@ -38,6 +39,8 @@ detectors: - BundlerAuditScannerStub - CreateGemfiles - AddAlphaIdToGemfiles + - CreateApiKeys + - ApiKeyTest - BundlerAuditDatabasePreparerTest - BundlerAuditDatabasePreparerTest::FakeLogger TooManyInstanceVariables: @@ -53,6 +56,7 @@ detectors: exclude: - BundlerAuditScannerStub#scan - CreateGemfiles#change + - CreateApiKeys#change UtilityFunction: exclude: - GemfilesController#vulnerabilities_count diff --git a/README.md b/README.md index 5afe8c9..a4e19cb 100644 --- a/README.md +++ b/README.md @@ -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: " \ + https://audit.fastruby.io/gemfiles.json +``` + +Fetch an existing report: + +```bash +curl -H "X-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). diff --git a/app/controllers/gemfiles_controller.rb b/app/controllers/gemfiles_controller.rb index c145222..cf8729a 100644 --- a/app/controllers/gemfiles_controller.rb +++ b/app/controllers/gemfiles_controller.rb @@ -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 @@ -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", @@ -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) diff --git a/app/models/api_key.rb b/app/models/api_key.rb new file mode 100644 index 0000000..07ac1c2 --- /dev/null +++ b/app/models/api_key.rb @@ -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 diff --git a/app/models/gemfile.rb b/app/models/gemfile.rb index 8498a9b..0d6c7c4 100644 --- a/app/models/gemfile.rb +++ b/app/models/gemfile.rb @@ -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 @@ -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) @@ -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? diff --git a/db/migrate/20261204025827_create_api_keys.rb b/db/migrate/20261204025827_create_api_keys.rb new file mode 100644 index 0000000..7b08ccb --- /dev/null +++ b/db/migrate/20261204025827_create_api_keys.rb @@ -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 diff --git a/db/schema.rb b/db/schema.rb index 42b2a0d..e5143c9 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -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 diff --git a/lib/bundler_audit_database_preparer.rb b/lib/bundler_audit_database_preparer.rb index d9b78f6..45f655c 100644 --- a/lib/bundler_audit_database_preparer.rb +++ b/lib/bundler_audit_database_preparer.rb @@ -1,18 +1,28 @@ 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 @@ -20,6 +30,45 @@ def self.call(path: Bundler::Audit::Database.path, logger: Rails.logger) 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) diff --git a/test/controllers/gemfiles_controller_test.rb b/test/controllers/gemfiles_controller_test.rb index ec2fc73..4bb8f84 100644 --- a/test/controllers/gemfiles_controller_test.rb +++ b/test/controllers/gemfiles_controller_test.rb @@ -1,6 +1,11 @@ require "test_helper" class GemfilesControllerTest < ActionDispatch::IntegrationTest + setup do + ApiKey.create!(name: "Other", value: "other") + ApiKey.create!(name: "Test", value: "secret") + end + test "create with an empty file sets an error message in flash" do post gemfiles_path @@ -44,4 +49,103 @@ class GemfilesControllerTest < ActionDispatch::IntegrationTest assert_equal "application/pdf", response.content_type assert response.body.start_with?("%PDF") end + + test "JSON create without an API key returns 401" do + post gemfiles_path(format: :json), params: {gemfile: {file: gemfile_lock_upload}} + + assert_response :unauthorized + assert_equal({"error" => "Unauthorized"}, response.parsed_body) + end + + test "JSON create with an API key that isn't allowed returns 401" do + post gemfiles_path(format: :json), params: {gemfile: {file: gemfile_lock_upload}}, + headers: {"X-API-Key" => "wrong"} + + assert_response :unauthorized + end + + test "JSON create with an empty API key returns 401" do + post gemfiles_path(format: :json), params: {gemfile: {file: gemfile_lock_upload}}, + headers: {"X-API-Key" => ""} + + assert_response :unauthorized + end + + test "JSON create with an allowed API key returns the report" do + assert_difference("Gemfile.count") do + post gemfiles_path(format: :json), params: {gemfile: {file: gemfile_lock_upload}}, + headers: {"X-API-Key" => "secret"} + end + + assert_response :created + body = response.parsed_body + gemfile = Gemfile.last + assert_equal gemfile.alpha_id, body["id"] + assert_equal gemfile_url(id: gemfile.alpha_id, format: :json), response.location + assert_kind_of Array, body["advisories"] + assert_kind_of Array, body["warnings"] + assert_equal body["advisories"].size + body["warnings"].size, body["vulnerabilities_count"] + end + + test "JSON create with an Accept header and no CSRF token works" do + ActionController::Base.allow_forgery_protection = true + post gemfiles_path, params: {gemfile: {file: gemfile_lock_upload}}, + headers: {"X-API-Key" => "secret", "Accept" => "application/json"} + + assert_response :created + ensure + ActionController::Base.allow_forgery_protection = false + end + + test "JSON create with an invalid file returns 422 with errors" do + post gemfiles_path(format: :json), + params: {gemfile: {file: fixture_file_upload(Rails.root.join("test/fixtures/files/corrupt.lock"))}}, + headers: {"X-API-Key" => "secret"} + + assert_response :unprocessable_content + assert_includes response.parsed_body["errors"], "File is invalid" + end + + test "JSON show without an API key returns 401" do + gemfile = Gemfile.create(file: File.new(Rails.root.join("test/fixtures/files/Gemfile.lock"))) + + get gemfile_path(id: gemfile.alpha_id, format: :json) + + assert_response :unauthorized + end + + test "JSON show with an allowed API key returns the report" do + gemfile = Gemfile.create(file: File.new(Rails.root.join("test/fixtures/files/Gemfile.lock"))) + + get gemfile_path(id: gemfile.alpha_id, format: :json), headers: {"X-API-Key" => "secret"} + + assert_response :success + assert_equal gemfile.alpha_id, response.parsed_body["id"] + assert_kind_of Array, response.parsed_body["advisories"] + end + + test "JSON reports say which advisory database they were checked against" do + gemfile = Gemfile.create(file: File.new(Rails.root.join("test/fixtures/files/Gemfile.lock"))) + revision = {commit_id: "0123456789abcdef0123456789abcdef01234567", committed_at: "2026-12-01T10:00:00-05:00"} + + BundlerAuditDatabasePreparer.stub :revision, revision do + get gemfile_path(id: gemfile.alpha_id, format: :json), headers: {"X-API-Key" => "secret"} + end + + assert_equal revision.stringify_keys, response.parsed_body["advisory_database"] + end + + test "HTML show still works without an API key" do + gemfile = Gemfile.create(file: File.new(Rails.root.join("test/fixtures/files/Gemfile.lock"))) + + get gemfile_path(id: gemfile.alpha_id) + + assert_response :success + end + + private + + def gemfile_lock_upload + fixture_file_upload(Rails.root.join("test/fixtures/files/Gemfile.lock")) + end end diff --git a/test/lib/bundler_audit_database_preparer_test.rb b/test/lib/bundler_audit_database_preparer_test.rb index e761446..182d2d6 100644 --- a/test/lib/bundler_audit_database_preparer_test.rb +++ b/test/lib/bundler_audit_database_preparer_test.rb @@ -32,16 +32,14 @@ def error(message) test "updates the database when the directory already exists" do logger = FakeLogger.new - updated = false - fake_database = Object.new - fake_database.define_singleton_method(:update!) { |*_args, **_kwargs| updated = true } + updated = nil Dir.mktmpdir do |path| - Bundler::Audit::Database.stub :new, fake_database do + BundlerAuditDatabasePreparer.stub :update, ->(updated_path) { updated = updated_path } do BundlerAuditDatabasePreparer.call(path: path, logger: logger) end - assert updated + assert_equal path, updated assert_empty logger.errors end end @@ -65,11 +63,9 @@ def error(message) test "logs, but does not raise, when the update fails" do logger = FakeLogger.new - fake_database = Object.new - fake_database.define_singleton_method(:update!) { |*_args, **_kwargs| raise Bundler::Audit::Database::UpdateFailed, "boom" } Dir.mktmpdir do |path| - Bundler::Audit::Database.stub :new, fake_database do + BundlerAuditDatabasePreparer.stub :update, ->(_path) { raise Bundler::Audit::Database::UpdateFailed, "boom" } do BundlerAuditDatabasePreparer.call(path: path, logger: logger) end @@ -77,4 +73,63 @@ def error(message) assert_match(/Could not prepare ruby-advisory-db.*UpdateFailed: boom/, logger.errors.first) end end + + test "refreshes a scan's database only once the last attempt is REFRESH_INTERVAL old" do + updates = 0 + + Dir.mktmpdir do |path| + BundlerAuditDatabasePreparer.stub :update, ->(_path) { updates += 1 } do + BundlerAuditDatabasePreparer.call(path: path, logger: FakeLogger.new) + BundlerAuditDatabasePreparer.refresh_if_stale(path: path, logger: FakeLogger.new) + assert_equal 1, updates + + travel BundlerAuditDatabasePreparer::REFRESH_INTERVAL + 1.second do + BundlerAuditDatabasePreparer.refresh_if_stale(path: path, logger: FakeLogger.new) + end + end + end + + assert_equal 2, updates + end + + test "update pulls the latest advisories, and revision reports the commit" do + Dir.mktmpdir do |dir| + origin = File.join(dir, "origin") + database = File.join(dir, "ruby-advisory-db") + git(dir, "init", "--quiet", "-b", "master", origin) + commit(origin, "first") + git(dir, "clone", "--quiet", origin, database) + commit(origin, "second") + + BundlerAuditDatabasePreparer.update(database) + + revision = BundlerAuditDatabasePreparer.revision(path: database) + assert_equal git(origin, "rev-parse", "HEAD"), revision[:commit_id] + assert_equal git(origin, "log", "-1", "--format=%cI"), revision[:committed_at] + end + end + + test "update raises when the pull fails" do + Dir.mktmpdir do |path| + assert_raises(Bundler::Audit::Database::UpdateFailed) { BundlerAuditDatabasePreparer.update(path) } + end + end + + test "revision is nil without a database" do + Dir.mktmpdir do |dir| + assert_nil BundlerAuditDatabasePreparer.revision(path: File.join(dir, "missing")) + end + end + + private + + def git(dir, *args) + output, status = Open3.capture2("git", "-C", dir, "-c", "user.name=Test", "-c", "user.email=test@example.com", *args) + assert status.success?, "git #{args.join(" ")} failed" + output.strip + end + + def commit(repository, message) + git(repository, "commit", "--quiet", "--allow-empty", "-m", message) + end end diff --git a/test/models/api_key_test.rb b/test/models/api_key_test.rb new file mode 100644 index 0000000..fc1ea27 --- /dev/null +++ b/test/models/api_key_test.rb @@ -0,0 +1,30 @@ +require "test_helper" + +class ApiKeyTest < ActiveSupport::TestCase + test "generates a value when created with just a name" do + api_key = ApiKey.create!(name: "Acme") + + assert_predicate api_key.value, :present? + end + + test "stores a digest of the value, not the value itself" do + api_key = ApiKey.create!(name: "Acme", value: "secret") + + assert_equal OpenSSL::Digest::SHA256.hexdigest("secret"), api_key.value_digest + assert_not_includes ApiKey.column_names, "value" + assert_nil ApiKey.find(api_key.id).value + end + + test "requires a name" do + assert_not ApiKey.new.valid? + end + + test "valid_key? is true only for stored values" do + api_key = ApiKey.create!(name: "Acme") + + assert ApiKey.valid_key?(api_key.value) + assert_not ApiKey.valid_key?("wrong") + assert_not ApiKey.valid_key?("") + assert_not ApiKey.valid_key?(nil) + end +end diff --git a/test/models/gemfile_test.rb b/test/models/gemfile_test.rb index 6054e04..57ba757 100644 --- a/test/models/gemfile_test.rb +++ b/test/models/gemfile_test.rb @@ -127,4 +127,29 @@ def stub_scanner(vulnerabilities = [], &block) assert_equal "Custom Description", last_advisory[:description] end end + + test "check_with_bundler_audit returns what the advisory says about the gem" do + advisory = Bundler::Audit::Advisory.new( + "/db/gems/actionpack/CVE-2024-47887.yml", "CVE-2024-47887", "https://github.com/advisories/GHSA-vfg9-r3fq-jvx4", + "Possible ReDoS vulnerability", Date.new(2024, 10, 15), "Description", nil, 6.6, "2024-47887", nil, + "vfg9-r3fq-jvx4", [Gem::Requirement.new("< 4.0.0")], [Gem::Requirement.new("~> 7.1.4", ">= 7.1.4.1"), Gem::Requirement.new(">= 7.2.1.1")] + ) + unpatched = Bundler::Audit::Results::UnpatchedGem.new(OpenStruct.new(name: "actionpack", version: Gem::Version.new("7.1.3")), advisory) + + stub_scanner([unpatched]) do + gemfile = Gemfile.new(file: valid_file) + assert gemfile.save + + assert_equal( + { + label: "actionpack@7.1.3", name: "actionpack", version: "7.1.3", id: "CVE-2024-47887", + cve_id: "CVE-2024-47887", ghsa_id: "GHSA-vfg9-r3fq-jvx4", url: "https://github.com/advisories/GHSA-vfg9-r3fq-jvx4", + title: "Possible ReDoS vulnerability", description: "Description", criticality: "medium", + cvss_v2: nil, cvss_v3: 6.6, date: "2024-10-15", + patched_versions: ["~> 7.1.4, >= 7.1.4.1", ">= 7.2.1.1"], unaffected_versions: ["< 4.0.0"] + }, + gemfile.check_with_bundler_audit[:advisories].sole + ) + end + end end