FIX: Provide better API for registering custom upload public types (#10697)

FIX: Provide better API for registering custom upload public types (#10697)

With secure media and the UploadSecurity class, we need a nice way for plugins to register custom upload types that should be considered public and never secure.

diff --git a/lib/upload_security.rb b/lib/upload_security.rb
index 52da01b..0a2acfd 100644
--- a/lib/upload_security.rb
+++ b/lib/upload_security.rb
@@ -14,10 +14,21 @@
 # on the current secure? status, otherwise there would be a lot of additional
 # complex queries and joins to perform.
 class UploadSecurity
+  @@custom_public_types = []
+
   PUBLIC_TYPES = %w[
-    avatar custom_emoji profile_background card_background category_logo category_background
+    avatar
+    custom_emoji
+    profile_background
+    card_background
+    category_logo
+    category_background
   ]
 
+  def self.register_custom_public_type(type)
+    @@custom_public_types << type if !@@custom_public_types.include?(type)
+  end
+
   def initialize(upload, opts = {})
     @upload = upload
     @opts = opts
@@ -30,8 +41,6 @@ class UploadSecurity
     uploading_in_secure_context?
   end
 
-  private
-
   def uploading_in_public_context?
     @upload.for_theme ||
       @upload.for_site_setting ||
@@ -49,6 +58,8 @@ class UploadSecurity
     uploading_in_composer? || @upload.for_private_message || @upload.for_group_message || @upload.secure?
   end
 
+  private
+
   # whether the upload should remain secure or not after posting depends on its context,
   # which is based on the post it is linked to via access_control_post_id.
   # if that post is with_secure_media? then the upload should also be secure.
@@ -62,7 +73,7 @@ class UploadSecurity
   end
 
   def public_type?
-    PUBLIC_TYPES.include?(@upload_type)
+    PUBLIC_TYPES.include?(@upload_type) || @@custom_public_types.include?(@upload_type)
   end
 
   def uploading_in_composer?
diff --git a/spec/lib/upload_security_spec.rb b/spec/lib/upload_security_spec.rb
index faba025..2ff1220 100644
--- a/spec/lib/upload_security_spec.rb
+++ b/spec/lib/upload_security_spec.rb
@@ -64,6 +64,18 @@ RSpec.describe UploadSecurity do
             expect(subject.should_be_secure?).to eq(false)
           end
         end
+        describe "for a custom public type" do
+          let(:type) { 'my_custom_type' }
+
+          it "returns true if the custom type has not been added" do
+            expect(subject.should_be_secure?).to eq(true)
+          end
+
+          it "returns false if the custom type has been added" do
+            UploadSecurity.register_custom_public_type(type)
+            expect(subject.should_be_secure?).to eq(false)
+          end
+        end
         describe "for_theme" do
           before do
             upload.stubs(:for_theme).returns(true)

GitHub sha: 14b324e5

This commit appears in #10697 which was merged by martin.