From 13d63f1f30b31f430abad8e2dcba8a9cce577cd7 Mon Sep 17 00:00:00 2001 From: Roman Rizzi Date: Wed, 6 Sep 2023 10:00:20 -0300 Subject: [PATCH] FIX: filter allowed categories from semantic search results (#206) --- lib/modules/embeddings/semantic_search.rb | 15 +++++---- .../embeddings/semantic_search_spec.rb | 32 +++++++++++++++++++ 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/lib/modules/embeddings/semantic_search.rb b/lib/modules/embeddings/semantic_search.rb index b40c30d6..487f98e0 100644 --- a/lib/modules/embeddings/semantic_search.rb +++ b/lib/modules/embeddings/semantic_search.rb @@ -68,12 +68,15 @@ module DiscourseAi offset: offset, ) - ::Post - .where(post_type: ::Topic.visible_post_types(guardian.user)) - .public_posts - .where("topics.visible") - .where(topic_id: candidate_topic_ids, post_number: 1) - .order("array_position(ARRAY#{candidate_topic_ids}, topic_id)") + semantic_results = + ::Post + .where(post_type: ::Topic.visible_post_types(guardian.user)) + .public_posts + .where("topics.visible") + .where(topic_id: candidate_topic_ids, post_number: 1) + .order("array_position(ARRAY#{candidate_topic_ids}, topic_id)") + + guardian.filter_allowed_categories(semantic_results) end private diff --git a/spec/lib/modules/embeddings/semantic_search_spec.rb b/spec/lib/modules/embeddings/semantic_search_spec.rb index fa05bda7..520d902d 100644 --- a/spec/lib/modules/embeddings/semantic_search_spec.rb +++ b/spec/lib/modules/embeddings/semantic_search_spec.rb @@ -106,6 +106,38 @@ RSpec.describe DiscourseAi::Embeddings::SemanticSearch do expect(posts).not_to include(post_2) end end + + context "when the post belongs to a secured category" do + fab!(:group) { Fabricate(:group) } + fab!(:private_category) { Fabricate(:private_category, group: group) } + + before do + post.topic.update!(category: private_category) + stub_candidate_ids([post.topic_id]) + end + + it "returns an empty list" do + posts = subject.search_for_topics(query) + + expect(posts).to be_empty + end + + it "returns the results if the user has access to the category" do + group.add(user) + + posts = subject.search_for_topics(query) + + expect(posts).to contain_exactly(post) + end + + context "while searching as anon" do + it "returns an empty list" do + posts = described_class.new(Guardian.new(nil)).search_for_topics(query) + + expect(posts).to be_empty + end + end + end end end end