FIX: Restrict `personal_messages:` advanced search filter to admin.

FIX: Restrict personal_messages: advanced search filter to admin.

The filter noops if an incorrect username is passed. This filter is not exposed as part of the UI but is only used when an admin transitions from a search within a user’s personal messages to the full page search.

Follow-up to 4b3079905498e3d09517ee2766c8ff33c11e7ada.

diff --git a/lib/search.rb b/lib/search.rb
index 00a7001..8f5615e 100644
--- a/lib/search.rb
+++ b/lib/search.rb
@@ -694,9 +694,10 @@ class Search
         @search_pms = true
         nil
       elsif word =~ /^personal_messages:(.+)$/
-        @search_pms = true
+        raise Discourse::InvalidAccess.new unless @guardian.is_admin?
 
         if user = User.find_by_username($1)
+          @search_pms = true
           @search_context = user
         end
 
diff --git a/spec/components/search_spec.rb b/spec/components/search_spec.rb
index bfc92e0..c50037f 100644
--- a/spec/components/search_spec.rb
+++ b/spec/components/search_spec.rb
@@ -281,14 +281,32 @@ describe Search do
     end
 
     context 'personal_messages filter' do
-      it 'correctly searches for the PM of the given user' do
+      it 'does not allow a normal user to search for personal messages of another user' do
+        expect do
+          results = Search.execute(
+            "mars personal_messages:#{post.user.username}",
+            guardian: Guardian.new(post.user)
+          )
+        end.to raise_error(Discourse::InvalidAccess)
+      end
+
+      it 'searches correctly for the PM of the given user' do
         results = Search.execute(
           "mars personal_messages:#{post.user.username}",
-          guardian: Guardian.new(post.user)
+          guardian: Guardian.new(admin)
         )
 
         expect(results.posts).to contain_exactly(reply)
       end
+
+      it 'returns the right results if username is invalid' do
+        results = Search.execute(
+          "mars personal_messages:random_username",
+          guardian: Guardian.new(admin)
+        )
+
+        expect(results.posts).to eq([])
+      end
     end
 
     context 'personal-direct flag' do

GitHub sha: 05174df5