From 5a494f4265e7935f5c99203d12b25105c3875bfb Mon Sep 17 00:00:00 2001 From: Ernesto Tagwerker Date: Thu, 3 Dec 2026 16:27:00 -0500 Subject: [PATCH 1/5] Add JSON API for uploading and viewing Gemfile.lock reports POST /gemfiles and GET /gemfiles/:id now respond to JSON. JSON requests must send an X-API-Key header that matches one of the keys in the API_KEYS env var (comma-separated). HTML and PDF are unchanged and stay public. Closes #101 Co-Authored-By: Claude Opus 5.5 (1M context) --- app/controllers/gemfiles_controller.rb | 36 +++++++ config/initializers/api_keys.rb | 4 + test/controllers/gemfiles_controller_test.rb | 99 ++++++++++++++++++++ 3 files changed, 139 insertions(+) create mode 100644 config/initializers/api_keys.rb diff --git a/app/controllers/gemfiles_controller.rb b/app/controllers/gemfiles_controller.rb index c145222..bbcf167 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,27 @@ def gemfile_params params.permit(gemfile: [:file])[:gemfile] end + def json_request? + request.format.json? + end + + def authenticate_api_key + api_key = request.headers[API_KEY_HEADER].to_s + allowed = Rails.configuration.x.api_keys.any? do |key| + ActiveSupport::SecurityUtils.secure_compare(key, api_key) + end + + render json: {error: "Unauthorized"}, status: :unauthorized unless allowed + end + + def report_json(file, vulnerabilities) + { + id: file.alpha_id, + vulnerabilities_count: vulnerabilities_count(vulnerabilities), + **vulnerabilities + } + end + def render_vulnerabilities(file) @renderer = Redcarpet::Render::HTML.new(prettify: true) @markdown = Redcarpet::Markdown.new(@renderer, fenced_code_blocks: true) diff --git a/config/initializers/api_keys.rb b/config/initializers/api_keys.rb new file mode 100644 index 0000000..e306f8a --- /dev/null +++ b/config/initializers/api_keys.rb @@ -0,0 +1,4 @@ +# API keys allowed to use the JSON API (see GemfilesController). Set API_KEYS +# to a comma-separated list. When it's empty, every JSON request is rejected. +Rails.application.config.x.api_keys = + ENV.fetch("API_KEYS", "").split(",").map(&:strip).reject(&:empty?) diff --git a/test/controllers/gemfiles_controller_test.rb b/test/controllers/gemfiles_controller_test.rb index ec2fc73..7e2afc4 100644 --- a/test/controllers/gemfiles_controller_test.rb +++ b/test/controllers/gemfiles_controller_test.rb @@ -1,6 +1,15 @@ require "test_helper" class GemfilesControllerTest < ActionDispatch::IntegrationTest + setup do + @original_api_keys = Rails.configuration.x.api_keys + Rails.configuration.x.api_keys = %w[other secret] + end + + teardown do + Rails.configuration.x.api_keys = @original_api_keys + end + test "create with an empty file sets an error message in flash" do post gemfiles_path @@ -44,4 +53,94 @@ 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 returns 401 when no API keys are configured" do + Rails.configuration.x.api_keys = [] + + 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 "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 From 8db118a214ab63f211069c9fa78e304afd6f932f Mon Sep 17 00:00:00 2001 From: Ernesto Tagwerker Date: Thu, 3 Dec 2026 16:33:09 -0500 Subject: [PATCH 2/5] Document the JSON API in the README Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/README.md b/README.md index 5afe8c9..2e4a91a 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,45 @@ 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 one of the keys in the `API_KEYS` environment variable (comma-separated). If `API_KEYS` is empty, all JSON requests get a `401`. + +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-...", + "url": "https://...", + "title": "...", + "description": "..." + } + ] +} +``` + ## 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). From 68d5ad8f321b0e378cc45be2f2205b7139981eff Mon Sep 17 00:00:00 2001 From: Ernesto Tagwerker Date: Thu, 3 Dec 2026 21:56:41 -0500 Subject: [PATCH 3/5] Report each advisory's ids, severity and versions, and the database revision API clients store more than the title and url: the CVE and GHSA ids, the criticality and CVSS scores, the advisory's date, and the patched and unaffected versions are now in each advisory. JSON reports also say which ruby-advisory-db commit they were checked against, so a client can tell when to scan again. Each process used to update the database only at boot; it now also updates it before a scan once the last attempt is an hour old. Git runs with -C, since bundler-audit's update! and commit_id Dir.chdir the whole process while Puma serves requests from other threads. Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 22 +++++- app/controllers/gemfiles_controller.rb | 3 +- app/models/gemfile.rb | 37 +++++++--- lib/bundler_audit_database_preparer.rb | 59 +++++++++++++-- test/controllers/gemfiles_controller_test.rb | 11 +++ .../bundler_audit_database_preparer_test.rb | 71 ++++++++++++++++--- test/models/gemfile_test.rb | 25 +++++++ 7 files changed, 202 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 2e4a91a..13f2101 100644 --- a/README.md +++ b/README.md @@ -83,15 +83,31 @@ Both return: "label": "rack@2.0.1", "name": "rack", "version": "2.0.1", - "id": "CVE-...", + "id": "CVE-2024-47887", + "cve_id": "CVE-2024-47887", + "ghsa_id": "GHSA-vfg9-r3fq-jvx4", "url": "https://...", "title": "...", - "description": "..." + "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 bbcf167..82f2863 100644 --- a/app/controllers/gemfiles_controller.rb +++ b/app/controllers/gemfiles_controller.rb @@ -70,7 +70,8 @@ def report_json(file, vulnerabilities) { id: file.alpha_id, vulnerabilities_count: vulnerabilities_count(vulnerabilities), - **vulnerabilities + **vulnerabilities, + advisory_database: BundlerAuditDatabasePreparer.revision } 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/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 7e2afc4..b359798 100644 --- a/test/controllers/gemfiles_controller_test.rb +++ b/test/controllers/gemfiles_controller_test.rb @@ -130,6 +130,17 @@ class GemfilesControllerTest < ActionDispatch::IntegrationTest 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"))) 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/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 From 9dde761e2884deb6b5948cb7df4a60a4056cdb3b Mon Sep 17 00:00:00 2001 From: Ernesto Tagwerker Date: Thu, 3 Dec 2026 21:59:40 -0500 Subject: [PATCH 4/5] Store API keys in an api_keys table instead of an env var Each key has a name and a value. The value is generated with has_secure_token when you create a key with just a name. Co-Authored-By: Claude Opus 5.5 (1M context) --- .reek.yml | 4 ++++ README.md | 8 ++++++- app/controllers/gemfiles_controller.rb | 7 ++----- app/models/api_key.rb | 12 +++++++++++ config/initializers/api_keys.rb | 4 ---- db/migrate/20261204025827_create_api_keys.rb | 11 ++++++++++ db/schema.rb | 10 ++++++++- test/controllers/gemfiles_controller_test.rb | 12 +++-------- test/models/api_key_test.rb | 22 ++++++++++++++++++++ 9 files changed, 70 insertions(+), 20 deletions(-) create mode 100644 app/models/api_key.rb delete mode 100644 config/initializers/api_keys.rb create mode 100644 db/migrate/20261204025827_create_api_keys.rb create mode 100644 test/models/api_key_test.rb 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 13f2101..7f6dade 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,13 @@ Also run before opening a PR: ## 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 one of the keys in the `API_KEYS` environment variable (comma-separated). If `API_KEYS` is empty, all JSON requests get a `401`. +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 the `value` of a row in the `api_keys` table. Otherwise it gets a `401`. + +To create a key, give it a name and a value is generated for you: + +```ruby +ApiKey.create!(name: "Acme").value +``` Upload a lockfile (returns `201` with the report, or `422` with `errors`): diff --git a/app/controllers/gemfiles_controller.rb b/app/controllers/gemfiles_controller.rb index 82f2863..cf8729a 100644 --- a/app/controllers/gemfiles_controller.rb +++ b/app/controllers/gemfiles_controller.rb @@ -58,12 +58,9 @@ def json_request? end def authenticate_api_key - api_key = request.headers[API_KEY_HEADER].to_s - allowed = Rails.configuration.x.api_keys.any? do |key| - ActiveSupport::SecurityUtils.secure_compare(key, api_key) - end + return if ApiKey.valid_key?(request.headers[API_KEY_HEADER]) - render json: {error: "Unauthorized"}, status: :unauthorized unless allowed + render json: {error: "Unauthorized"}, status: :unauthorized end def report_json(file, vulnerabilities) diff --git a/app/models/api_key.rb b/app/models/api_key.rb new file mode 100644 index 0000000..66a57f3 --- /dev/null +++ b/app/models/api_key.rb @@ -0,0 +1,12 @@ +# Keys allowed to use the JSON API (see GemfilesController). `value` is +# generated automatically when you create a key with just a name. +class ApiKey < ApplicationRecord + has_secure_token :value + + validates :name, presence: true + validates :value, uniqueness: true + + def self.valid_key?(value) + value.present? && exists?(value: value) + end +end diff --git a/config/initializers/api_keys.rb b/config/initializers/api_keys.rb deleted file mode 100644 index e306f8a..0000000 --- a/config/initializers/api_keys.rb +++ /dev/null @@ -1,4 +0,0 @@ -# API keys allowed to use the JSON API (see GemfilesController). Set API_KEYS -# to a comma-separated list. When it's empty, every JSON request is rejected. -Rails.application.config.x.api_keys = - ENV.fetch("API_KEYS", "").split(",").map(&:strip).reject(&:empty?) diff --git a/db/migrate/20261204025827_create_api_keys.rb b/db/migrate/20261204025827_create_api_keys.rb new file mode 100644 index 0000000..0c898fe --- /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, null: false + + t.timestamps + end + add_index :api_keys, :value, unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index 42b2a0d..68686f0 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", null: false + t.index ["value"], name: "index_api_keys_on_value", 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/test/controllers/gemfiles_controller_test.rb b/test/controllers/gemfiles_controller_test.rb index b359798..4bb8f84 100644 --- a/test/controllers/gemfiles_controller_test.rb +++ b/test/controllers/gemfiles_controller_test.rb @@ -2,12 +2,8 @@ class GemfilesControllerTest < ActionDispatch::IntegrationTest setup do - @original_api_keys = Rails.configuration.x.api_keys - Rails.configuration.x.api_keys = %w[other secret] - end - - teardown do - Rails.configuration.x.api_keys = @original_api_keys + 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 @@ -68,9 +64,7 @@ class GemfilesControllerTest < ActionDispatch::IntegrationTest assert_response :unauthorized end - test "JSON create returns 401 when no API keys are configured" do - Rails.configuration.x.api_keys = [] - + 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" => ""} diff --git a/test/models/api_key_test.rb b/test/models/api_key_test.rb new file mode 100644 index 0000000..fea99de --- /dev/null +++ b/test/models/api_key_test.rb @@ -0,0 +1,22 @@ +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 "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 From 68088981f9c4d141b30b0e8b8da9307a122ee5e1 Mon Sep 17 00:00:00 2001 From: Ernesto Tagwerker Date: Thu, 3 Dec 2026 22:03:16 -0500 Subject: [PATCH 5/5] Store a SHA-256 digest of each API key instead of the key itself The plain-text key is only available on the record that created it. Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 6 ++-- app/models/api_key.rb | 29 ++++++++++++++++---- db/migrate/20261204025827_create_api_keys.rb | 4 +-- db/schema.rb | 4 +-- test/models/api_key_test.rb | 8 ++++++ 5 files changed, 40 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 7f6dade..a4e19cb 100644 --- a/README.md +++ b/README.md @@ -55,14 +55,16 @@ Also run before opening a PR: ## 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 the `value` of a row in the `api_keys` table. Otherwise it gets a `401`. +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`. -To create a key, give it a name and a value is generated for you: +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 diff --git a/app/models/api_key.rb b/app/models/api_key.rb index 66a57f3..07ac1c2 100644 --- a/app/models/api_key.rb +++ b/app/models/api_key.rb @@ -1,12 +1,31 @@ -# Keys allowed to use the JSON API (see GemfilesController). `value` is -# generated automatically when you create a key with just a name. +# 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 - has_secure_token :value + attr_reader :value validates :name, presence: true - validates :value, uniqueness: 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: 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/db/migrate/20261204025827_create_api_keys.rb b/db/migrate/20261204025827_create_api_keys.rb index 0c898fe..7b08ccb 100644 --- a/db/migrate/20261204025827_create_api_keys.rb +++ b/db/migrate/20261204025827_create_api_keys.rb @@ -2,10 +2,10 @@ class CreateApiKeys < ActiveRecord::Migration[8.1] def change create_table :api_keys do |t| t.string :name, null: false - t.string :value, null: false + t.string :value_digest, null: false t.timestamps end - add_index :api_keys, :value, unique: true + add_index :api_keys, :value_digest, unique: true end end diff --git a/db/schema.rb b/db/schema.rb index 68686f0..e5143c9 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -18,8 +18,8 @@ t.datetime "created_at", null: false t.string "name", null: false t.datetime "updated_at", null: false - t.string "value", null: false - t.index ["value"], name: "index_api_keys_on_value", unique: true + 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| diff --git a/test/models/api_key_test.rb b/test/models/api_key_test.rb index fea99de..fc1ea27 100644 --- a/test/models/api_key_test.rb +++ b/test/models/api_key_test.rb @@ -7,6 +7,14 @@ class ApiKeyTest < ActiveSupport::TestCase 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