From 6290b55ec567dbbaa42c9cb198dd4bc17f0c2330 Mon Sep 17 00:00:00 2001
From: Fabio Pitino <fpitino@gitlab.com>
Date: Mon, 4 Dec 2023 14:25:54 +0000
Subject: [PATCH] Fix 500 error when accessing resources as anonymous user

Fixes the nil exception and adds more test coverage.

Changelog: fixed
---
 app/models/ci/catalog/listing.rb       |  2 +-
 spec/models/ci/catalog/listing_spec.rb | 33 ++++++++++++++++++--------
 2 files changed, 24 insertions(+), 11 deletions(-)

diff --git a/app/models/ci/catalog/listing.rb b/app/models/ci/catalog/listing.rb
index 3b1edac7b62b..9baf5e7b2ccd 100644
--- a/app/models/ci/catalog/listing.rb
+++ b/app/models/ci/catalog/listing.rb
@@ -35,7 +35,7 @@ def find_resource(id:)
 
         return unless resource.present?
         return unless resource.published?
-        return unless current_user.can?(:read_code, resource.project)
+        return unless Ability.allowed?(current_user, :read_code, resource.project)
 
         resource
       end
diff --git a/spec/models/ci/catalog/listing_spec.rb b/spec/models/ci/catalog/listing_spec.rb
index 2d20acd40916..9d20d944e5ac 100644
--- a/spec/models/ci/catalog/listing_spec.rb
+++ b/spec/models/ci/catalog/listing_spec.rb
@@ -185,11 +185,11 @@
   end
 
   describe '#find_resource' do
+    let_it_be(:accessible_resource) { create(:ci_catalog_resource, :published, project: public_project) }
+
     subject { list.find_resource(id: id) }
 
     context 'when the resource is published and visible to the user' do
-      let_it_be(:accessible_resource) { create(:ci_catalog_resource, :published, project: public_project) }
-
       let(:id) { accessible_resource.id }
 
       it 'fetches the resource' do
@@ -200,9 +200,7 @@
     context 'when the resource is not found' do
       let(:id) { 'not-an-id' }
 
-      it 'returns nil' do
-        is_expected.to be_nil
-      end
+      it { is_expected.to be_nil }
     end
 
     context 'when the resource is not published' do
@@ -210,9 +208,7 @@
 
       let(:id) { draft_resource.id }
 
-      it 'returns nil' do
-        is_expected.to be_nil
-      end
+      it { is_expected.to be_nil }
     end
 
     context "when the current user cannot read code on the resource's project" do
@@ -220,8 +216,25 @@
 
       let(:id) { inaccessible_resource.id }
 
-      it 'returns nil' do
-        is_expected.to be_nil
+      it { is_expected.to be_nil }
+    end
+
+    context 'when the current user is anonymous' do
+      let(:user) { nil }
+
+      context 'when the resource is public' do
+        let(:id) { accessible_resource.id }
+
+        it 'fetches the public resource' do
+          is_expected.to eq(accessible_resource)
+        end
+      end
+
+      context 'when the resource is internal' do
+        let(:internal_resource) { create(:ci_catalog_resource, :published, project: internal_project) }
+        let(:id) { internal_resource.id }
+
+        it { is_expected.to be_nil }
       end
     end
   end
-- 
GitLab