Skip to content

Commit

Permalink
Enhance PURL error handling in package lookup to manage invalid formats
Browse files Browse the repository at this point in the history
  • Loading branch information
andrew committed Nov 10, 2024
1 parent 8d1a205 commit 0ab94aa
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
20 changes: 15 additions & 5 deletions app/controllers/api/v1/packages_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,21 @@ def lookup
# if packages are not found, try to sync them
if @packages.empty?
if params[:purl].present?
purl = PackageURL.parse(params[:purl])
name = [purl.namespace, purl.name].compact.join(Ecosystem::Base.purl_type_to_namespace_seperator(purl.type))
ecosystem = Ecosystem::Base.purl_type_to_ecosystem(purl.type)
registry = Registry.find_by_ecosystem(ecosystem)
registry.sync_package_async(name) if registry
begin
purl = PackageURL.parse(params[:purl])
name = [purl.namespace, purl.name].compact.join(Ecosystem::Base.purl_type_to_namespace_seperator(purl.type))
ecosystem = Ecosystem::Base.purl_type_to_ecosystem(purl.type)
registry = Registry.find_by_ecosystem(ecosystem)
registry.sync_package_async(name) if registry
rescue ArgumentError => e
Rails.logger.error("ArgumentError in PURL parsing: #{e.message}")
if e.message.include?("type is required")
render json: { error: "Invalid PURL format (type is required): #{params[:purl]}" }, status: :unprocessable_entity and return
elsif e.message.downcase.include?('invalid')
render json: { error: "Invalid PURL format: #{params[:purl]}" }, status: :unprocessable_entity and return
end
raise e
end
elsif params[:ecosystem].present? && params[:name].present?
registry = Registry.find_by_ecosystem(params[:ecosystem])
registry.sync_package_async(params[:name]) if registry
Expand Down
11 changes: 11 additions & 0 deletions test/controllers/api/v1/packages_controller_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,17 @@ class ApiV1PackagesControllerTest < ActionDispatch::IntegrationTest
assert_equal actual_response.first['name'], @package.name
end

test 'lookup by purl with missing type' do
invalid_purl = 'pkg:/software.amazon.awssdk%3Ametrics-spi'

get lookup_api_v1_packages_path(purl: invalid_purl)

assert_response :unprocessable_entity
actual_response = Oj.load(@response.body)

assert_equal 'Invalid PURL format (type is required): pkg:/software.amazon.awssdk%3Ametrics-spi', actual_response['error']
end

test 'lookup by purl github actions' do
@registry = Registry.create(name: 'github actions', url: 'https://github.com/marketplace/actions/', ecosystem: 'actions')
@package = @registry.packages.create(ecosystem: 'actions', name: 'actions/checkout')
Expand Down

0 comments on commit 0ab94aa

Please sign in to comment.