malmal-rails 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 84adfebeeebe373dd5eacbb9ab94a94d7eb60ff3d388ef6f87016326013e83dd
4
+ data.tar.gz: 9645e507dc7332a7b9a0a85331ac32f04694dfe4650550d57f61e5d7195fa93a
5
+ SHA512:
6
+ metadata.gz: 1474f3b5084175c8cd2a6db3ab9944e1e73fc0a836b4110f62b0debf4b3371240d755a501e43981c2661ae0e012a7b3f93b507fbce34f8f130328393efa5d36e
7
+ data.tar.gz: 5857cb2dda79c34cc144b7fd5d0088882457eaded7ec5b179a7ef2bf620e2158354a28e52ead7c59da00852dbbdd5729b755b82a336438b97335eaace6305008
data/LICENSE-APACHE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 nguyenthuan155632
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nguyenthuan155632
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,137 @@
1
+ # malmal-rails
2
+
3
+ Rails integration of the [malmal](https://github.com/nguyenthuan155632/malmal) upload
4
+ scanner: an Active Storage validator, a scan of every stored blob, attachments rebuilt
5
+ from what they draw, and one scanner for the application built from `config.malmal`.
6
+ Rails 7.1 to 8.1, Ruby 3.2 or newer. The scanner itself is the
7
+ [malmal](../malmal/README.md) gem, whose platform gems carry the library: no Rust needed.
8
+
9
+ ```bash
10
+ bundle add malmal-rails
11
+ bin/rails generate malmal:install # writes config/initializers/malmal.rb
12
+ ```
13
+
14
+ ## Refusing an upload
15
+
16
+ ```ruby
17
+ class Document < ApplicationRecord
18
+ has_one_attached :file
19
+ has_many_attached :pages
20
+ validates :file, malmal: true
21
+ validates :pages, malmal: { policy: :documents, types: %i[pdf] }
22
+ end
23
+ ```
24
+
25
+ The validator scans what is being attached, before it is uploaded: a file from a form,
26
+ an `{io:, filename:}` hash, or a blob already stored (a direct upload, a signed id),
27
+ which is read back up to the size limit. It uses the file name and the `Content-Type`
28
+ the client gave. Attachments the record already has are not scanned again; every file of
29
+ a `has_many_attached` is.
30
+
31
+ A file that is not clean adds `:malmal_suspicious` or `:malmal_malicious` to the
32
+ attribute, and one that could not be scanned `:malmal_error`. The details carry the
33
+ finding codes and the file name:
34
+
35
+ ```ruby
36
+ document.errors.details[:file]
37
+ # => [{error: :malmal_malicious, filename: "photo.jpg", codes: ["type.executable"], count: 1}]
38
+ document.errors.full_messages
39
+ # => ["File could not be accepted: photo.jpg looks malicious"]
40
+ ```
41
+
42
+ The messages are under `errors.messages.malmal_*` in `config/locales/en.yml`, to
43
+ override or translate. The validator takes the scanning options (`policy`, `allow`,
44
+ `types`, `max_memory`, `wait`, `pdf_passwords`), and `message:`; each set is built once
45
+ into a scanner of its own. An unknown option raises when the model is loaded.
46
+
47
+ ## Rebuilding an attachment
48
+
49
+ ```ruby
50
+ class User < ApplicationRecord
51
+ has_one_attached :avatar
52
+ sanitizes_attachment :avatar, types: %i[jpeg png webp]
53
+ end
54
+ ```
55
+
56
+ Before validation, the upload is replaced with a file written anew from its pixels, so
57
+ nothing else from it is stored. The new file keeps the name of the upload, with the
58
+ extension of its type, which is not always the type of the upload (a BMP becomes a PNG).
59
+ A file that is not clean is refused as the validator does; one that cannot be rebuilt
60
+ adds `:malmal_not_rebuilt`, or is kept as it was with `on_not_rebuilt: :keep`, which is
61
+ best paired with the validator. The options are those of `Malmal::Scanner#sanitize`:
62
+ `types`, `jpeg_quality`, `pdf_dpi`, `pdf_jpeg`, `pdf_text`, `pdf_vector_text`.
63
+
64
+ ## Stored blobs
65
+
66
+ Direct uploads reach the storage service before any validation runs. With
67
+ `config.malmal.scan_blobs` (on by default), every blob is scanned when Active Storage
68
+ analyzes it, in the analyze job, and the result is kept in its metadata:
69
+
70
+ ```ruby
71
+ blob.metadata["malmal"] # => {"verdict" => "malicious", "codes" => ["type.executable"]}
72
+ blob.malmal_clean? # => false; nil before the scan
73
+ ```
74
+
75
+ With `config.malmal.purge_unclean`, a blob that is not clean is purged, with its
76
+ attachments.
77
+
78
+ ## Configuration
79
+
80
+ ```ruby
81
+ # config/initializers/malmal.rb
82
+ Rails.application.configure do
83
+ config.malmal.policy = :documents # :default, :strict, :documents
84
+ config.malmal.allow = %w[pdf.xfa]
85
+ config.malmal.types = %i[jpeg png gif webp pdf]
86
+ config.malmal.limits = { max_size: 20.megabytes, scan_timeout: 10 }
87
+ config.malmal.max_memory = 256.megabytes
88
+ config.malmal.wait = 30
89
+ config.malmal.pdf_passwords = []
90
+ config.malmal.scan_blobs = true
91
+ config.malmal.purge_unclean = false
92
+ config.malmal.log_filenames = false
93
+ end
94
+ ```
95
+
96
+ `Malmal::Rails.scanner` is built from it on first use and shared by every thread. To
97
+ scan with a running `malmald` instead, which gives the sandbox and `--hard-timeout`:
98
+
99
+ ```ruby
100
+ config.malmal.client_url = "http://127.0.0.1:8080"
101
+ config.malmal.client_token = ENV["MALMAL_TOKEN"]
102
+ ```
103
+
104
+ The scanning options are then the daemon's flags, and a validator that sets its own
105
+ raises `ArgumentError`.
106
+
107
+ ## Instrumentation
108
+
109
+ Each scan is an `ActiveSupport::Notifications` event `scan.malmal`, and each rebuild
110
+ `sanitize.malmal`; the payload has `filename`, `content_type`, and `report` or
111
+ `sanitized`. A scan that is not clean is logged as a warning, with its codes, and with
112
+ the file name only when `config.malmal.log_filenames` is on.
113
+
114
+ ```ruby
115
+ ActiveSupport::Notifications.subscribe("scan.malmal") do |event|
116
+ StatsD.increment("uploads.#{event.payload[:report].verdict}")
117
+ end
118
+ ```
119
+
120
+ `Malmal::Rails.scan(io, filename:)` and `Malmal::Rails.sanitize` scan outside a model
121
+ with the same scanner and events.
122
+
123
+ ## Development
124
+
125
+ ```bash
126
+ cargo build --release -p malmal-ffi
127
+ cd bindings/ruby/malmal-rails
128
+ bundle install
129
+ MALMAL_LIBRARY=../../../target/release/libmalmal_ffi.so bundle exec rake test
130
+ BUNDLE_GEMFILE=gemfiles/rails_7_1.gemfile bundle install # another Rails
131
+ ```
132
+
133
+ [examples/rails](../../../examples/rails) is an application that uses all of it.
134
+
135
+ ## License
136
+
137
+ MIT or Apache-2.0, at your option.
@@ -0,0 +1,7 @@
1
+ en:
2
+ errors:
3
+ messages:
4
+ malmal_suspicious: "could not be accepted: %{filename} looks suspicious"
5
+ malmal_malicious: "could not be accepted: %{filename} looks malicious"
6
+ malmal_error: "could not be checked; try again"
7
+ malmal_not_rebuilt: "could not be accepted: %{filename} is not a file that can be rebuilt"
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators/base"
4
+
5
+ module Malmal
6
+ module Generators
7
+ # bin/rails generate malmal:install
8
+ class InstallGenerator < ::Rails::Generators::Base
9
+ source_root File.expand_path("templates", __dir__)
10
+ desc "Writes config/initializers/malmal.rb, where the scanner is configured."
11
+
12
+ def copy_initializer
13
+ template "malmal.rb", "config/initializers/malmal.rb"
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The scanner the application uses for every upload. See
4
+ # https://github.com/nguyenthuan155632/malmal/tree/main/bindings/ruby/malmal-rails
5
+ Rails.application.configure do
6
+ # :default, :strict, or :documents (XFA forms and attachments in PDFs do not
7
+ # count against a file; what they contain still does).
8
+ config.malmal.policy = :default
9
+
10
+ # Finding codes that do not count against a file (docs/findings.md).
11
+ # config.malmal.allow = %w[pdf.xfa]
12
+
13
+ # The file types accepted; every supported type when nil.
14
+ # config.malmal.types = %i[jpeg png gif webp pdf]
15
+
16
+ # The limits of one scan.
17
+ # config.malmal.limits = { max_size: 20.megabytes, scan_timeout: 10 }
18
+
19
+ # Answer within this many seconds even if a step of a scan never ends.
20
+ # config.malmal.wait = 30
21
+
22
+ # Scan with a running malmald instead of in this process.
23
+ # config.malmal.client_url = "http://127.0.0.1:8080"
24
+ # config.malmal.client_token = ENV["MALMAL_TOKEN"]
25
+
26
+ # Scan every stored blob when Active Storage analyzes it, and record the
27
+ # result in blob.metadata["malmal"].
28
+ config.malmal.scan_blobs = true
29
+
30
+ # Purge a stored blob that is not clean, with its attachments.
31
+ config.malmal.purge_unclean = false
32
+
33
+ # Log the names of files that are not clean.
34
+ config.malmal.log_filenames = false
35
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Malmal
4
+ module Rails
5
+ # What is being attached to a record, read back from Active Storage's
6
+ # pending changes before anything is uploaded.
7
+ module Attachables
8
+ # One file being attached: its bytes come from +io+ (an upload not yet
9
+ # stored) or from +blob+ (one already stored, as after a direct upload).
10
+ Upload = Struct.new(:attachable, :blob, :filename, :content_type, :io, keyword_init: true) do
11
+ def stored?
12
+ io.nil?
13
+ end
14
+ end
15
+
16
+ module_function
17
+
18
+ # The uploads that +record+ is about to attach as +name+; none when
19
+ # nothing new is being attached.
20
+ def pending(record, name)
21
+ return [] unless record.respond_to?(:attachment_changes)
22
+
23
+ change = record.attachment_changes[name.to_s]
24
+ pairs = case change
25
+ when ::ActiveStorage::Attached::Changes::CreateOne
26
+ [[change.attachable, change.blob]]
27
+ when ::ActiveStorage::Attached::Changes::CreateMany
28
+ change.attachables.zip(change.blobs)
29
+ else
30
+ []
31
+ end
32
+ pairs.filter_map { |attachable, blob| upload(attachable, blob) }
33
+ end
34
+
35
+ def upload(attachable, blob)
36
+ case attachable
37
+ when ::ActiveStorage::Blob, ::ActiveStorage::Attachment, String
38
+ return nil if already_attached?(blob)
39
+
40
+ Upload.new(attachable: attachable, blob: blob, filename: blob.filename.to_s,
41
+ content_type: blob.content_type)
42
+ when Hash
43
+ options = attachable.symbolize_keys
44
+ Upload.new(attachable: attachable, blob: blob, io: options.fetch(:io),
45
+ filename: options[:filename].to_s, content_type: options[:content_type])
46
+ else
47
+ io = attachable.respond_to?(:tempfile) ? attachable.tempfile : attachable
48
+ filename = attachable.respond_to?(:original_filename) ? attachable.original_filename : blob.filename.to_s
49
+ content_type = attachable.respond_to?(:content_type) ? attachable.content_type : blob.content_type
50
+ Upload.new(attachable: attachable, blob: blob, io: io, filename: filename.to_s, content_type: content_type)
51
+ end
52
+ end
53
+
54
+ # A blob the record already had is not scanned again on every save.
55
+ def already_attached?(blob)
56
+ blob.persisted? && blob.attachments.exists?
57
+ end
58
+
59
+ # The bytes of an upload, at most +limit+ of them.
60
+ def read(upload, limit)
61
+ return read_stored(upload.blob, limit) if upload.stored?
62
+
63
+ io = upload.io
64
+ io.rewind if io.respond_to?(:rewind)
65
+ bytes = io.read(limit) || +""
66
+ io.rewind if io.respond_to?(:rewind)
67
+ bytes.b
68
+ end
69
+
70
+ def read_stored(blob, limit)
71
+ return blob.download_chunk(0...limit).b if blob.byte_size.to_i > limit
72
+
73
+ blob.download.b
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Malmal
4
+ module Rails
5
+ # Scans a stored blob when Active Storage analyzes it, which it does in a
6
+ # job after every upload, direct ones included, and records the result
7
+ # in its metadata:
8
+ #
9
+ # blob.metadata["malmal"] # => {"verdict" => "malicious", "codes" => ["type.executable"]}
10
+ # blob.malmal_clean? # => false
11
+ #
12
+ # With +config.malmal.purge_unclean+, a blob that is not clean is purged,
13
+ # with its attachments. Validations do not see direct uploads until the
14
+ # record is saved; this is what catches the ones that are never attached.
15
+ module BlobScan
16
+ module_function
17
+
18
+ def call(blob)
19
+ return unless Malmal::Rails.config.scan_blobs
20
+
21
+ report = Malmal::Rails.scan(read(blob), filename: blob.filename.to_s, content_type: blob.content_type)
22
+ record(blob, report.verdict.to_s, report.codes)
23
+ purge(blob) if !report.clean? && Malmal::Rails.config.purge_unclean
24
+ rescue Malmal::ScanError, Malmal::LoadError => e
25
+ Malmal::Rails.logger&.error("[malmal] blob #{blob.id} was not scanned: #{e.message}")
26
+ record(blob, "error", [])
27
+ purge(blob) if Malmal::Rails.config.purge_unclean
28
+ end
29
+
30
+ def read(blob)
31
+ Attachables.read_stored(blob, Malmal::Rails.read_limit)
32
+ end
33
+
34
+ def record(blob, verdict, codes)
35
+ result = { "verdict" => verdict, "codes" => codes, "version" => Malmal::VERSION }
36
+ blob.update!(metadata: blob.metadata.merge("malmal" => result))
37
+ end
38
+
39
+ def purge(blob)
40
+ Malmal::Rails.logger&.warn("[malmal] purging blob #{blob.id}, which is not clean")
41
+ attachments = blob.attachments.to_a
42
+ if attachments.empty?
43
+ blob.purge
44
+ else
45
+ attachments.each(&:purge)
46
+ end
47
+ end
48
+
49
+ # Included in ActiveStorage::Blob.
50
+ module Blob
51
+ def analyze
52
+ super
53
+ Malmal::Rails::BlobScan.call(self)
54
+ end
55
+
56
+ # Whether the last scan of this blob came back clean; nil if it has
57
+ # not been scanned.
58
+ def malmal_clean?
59
+ verdict = metadata.dig("malmal", "verdict")
60
+ verdict && verdict == "clean"
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/railtie"
4
+
5
+ module Malmal
6
+ module Rails
7
+ # Sets up +config.malmal+, the validator, the scans of stored blobs and
8
+ # +sanitizes_attachment+.
9
+ class Railtie < ::Rails::Railtie
10
+ config.malmal = Malmal::Rails.config
11
+
12
+ initializer "malmal.config" do |app|
13
+ Malmal::Rails.config = app.config.malmal
14
+ Malmal::Rails.reset!
15
+ end
16
+
17
+ initializer "malmal.i18n" do
18
+ ActiveSupport.on_load(:i18n) do
19
+ I18n.load_path << File.expand_path("../../../config/locales/en.yml", __dir__)
20
+ end
21
+ end
22
+
23
+ initializer "malmal.active_record" do
24
+ ActiveSupport.on_load(:active_record) do
25
+ include Malmal::Rails::SanitizesAttachment
26
+ end
27
+ end
28
+
29
+ initializer "malmal.active_storage" do
30
+ ActiveSupport.on_load(:active_storage_blob) do
31
+ prepend Malmal::Rails::BlobScan::Blob
32
+ end
33
+ end
34
+
35
+ generators do
36
+ require_relative "../../generators/malmal/install/install_generator"
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/concern"
4
+ require "stringio"
5
+
6
+ module Malmal
7
+ module Rails
8
+ # Replaces what is attached with a file written anew from what it draws,
9
+ # before the record is validated, so that nothing else from the upload
10
+ # is stored:
11
+ #
12
+ # class User < ApplicationRecord
13
+ # has_one_attached :avatar
14
+ # sanitizes_attachment :avatar, types: %i[jpeg png webp]
15
+ # end
16
+ #
17
+ # The new file keeps the name of the upload, with the extension of its
18
+ # type, which is not always the type of the upload (a BMP becomes a PNG).
19
+ # An upload that is not clean adds +:malmal_suspicious+ or
20
+ # +:malmal_malicious+ to the attribute; one that cannot be rebuilt adds
21
+ # +:malmal_not_rebuilt+, or is kept as it was with
22
+ # <tt>on_not_rebuilt: :keep</tt> (pair that with the validator). Other
23
+ # options are those of Malmal::Scanner#sanitize: +types+, +jpeg_quality+,
24
+ # +pdf_dpi+, +pdf_jpeg+, +pdf_text+, +pdf_vector_text+.
25
+ module SanitizesAttachment
26
+ extend ActiveSupport::Concern
27
+
28
+ ON_NOT_REBUILT = %i[reject keep].freeze
29
+
30
+ class_methods do
31
+ def sanitizes_attachment(*names, on_not_rebuilt: :reject, **options)
32
+ unless ON_NOT_REBUILT.include?(on_not_rebuilt)
33
+ raise ArgumentError, "on_not_rebuilt is :reject or :keep, not #{on_not_rebuilt.inspect}"
34
+ end
35
+
36
+ unknown = options.keys - Malmal::Scanner::SANITIZE_OPTIONS - [:jpeg_quality]
37
+ raise ArgumentError, "unknown option #{unknown.first.inspect}" unless unknown.empty?
38
+
39
+ names.each do |name|
40
+ before_validation { malmal_sanitize_attachment(name, on_not_rebuilt, options) }
41
+ validate { malmal_sanitize_errors(name) }
42
+ end
43
+ end
44
+ end
45
+
46
+ private
47
+
48
+ def malmal_sanitize_attachment(name, on_not_rebuilt, options)
49
+ uploads = Attachables.pending(self, name)
50
+ return if uploads.empty?
51
+
52
+ failures = (@malmal_sanitize_failures ||= {})[name.to_s] = []
53
+ rebuilt = uploads.map do |upload|
54
+ malmal_rebuild(upload, on_not_rebuilt, options, failures)
55
+ end
56
+ return unless failures.empty?
57
+
58
+ many = attachment_changes[name.to_s].is_a?(::ActiveStorage::Attached::Changes::CreateMany)
59
+ public_send(:"#{name}=", many ? keep_existing(name, rebuilt) : rebuilt.first)
60
+ end
61
+
62
+ def malmal_rebuild(upload, on_not_rebuilt, options, failures)
63
+ data = Attachables.read(upload, Malmal::Rails.read_limit)
64
+ sanitized = Malmal::Rails.sanitize(data, filename: upload.filename, content_type: upload.content_type,
65
+ **options)
66
+ { io: StringIO.new(sanitized.data), filename: rebuilt_filename(upload.filename, sanitized),
67
+ content_type: sanitized.content_type }
68
+ rescue Malmal::Rejected => e
69
+ failures << [:"malmal_#{e.report.verdict}", upload, e.report.codes]
70
+ nil
71
+ rescue Malmal::NotRebuilt
72
+ failures << [:malmal_not_rebuilt, upload, []] if on_not_rebuilt == :reject
73
+ upload.attachable
74
+ rescue Malmal::ScanError, Malmal::LoadError => e
75
+ Malmal::Rails.logger&.error("[malmal] #{upload.filename.inspect} was not rebuilt: #{e.message}")
76
+ failures << [:malmal_error, upload, []]
77
+ nil
78
+ end
79
+
80
+ # A has_many_attached assignment replaces every attachment; the ones
81
+ # the record had are given back as they were.
82
+ def keep_existing(name, rebuilt)
83
+ change = attachment_changes[name.to_s]
84
+ pending = Attachables.pending(self, name).map(&:attachable)
85
+ queue = rebuilt.dup
86
+ change.attachables.map { |attachable| pending.include?(attachable) ? queue.shift : attachable }
87
+ end
88
+
89
+ def rebuilt_filename(filename, sanitized)
90
+ base = File.basename(filename.to_s, ".*")
91
+ base = "file" if base.empty?
92
+ "#{base}#{sanitized.extension}"
93
+ end
94
+
95
+ def malmal_sanitize_errors(name)
96
+ Array(@malmal_sanitize_failures&.delete(name.to_s)).each do |error, upload, codes|
97
+ errors.add(name, error, filename: upload.filename, codes: codes, count: codes.size)
98
+ end
99
+ end
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_model"
4
+
5
+ module Malmal
6
+ module Rails
7
+ # Validates what is being attached to an Active Storage attachment:
8
+ #
9
+ # class Document < ApplicationRecord
10
+ # has_one_attached :file
11
+ # validates :file, malmal: true
12
+ # # or: validates :file, malmal: { policy: :documents, types: %i[pdf png jpeg] }
13
+ # end
14
+ #
15
+ # Each new upload is scanned before it is stored, with the file name and
16
+ # Content-Type the client gave; a blob already stored (a direct upload,
17
+ # a signed id) is read back and scanned. Attachments the record already
18
+ # had are not scanned again. A file that is not clean adds an error to
19
+ # the attribute: +:malmal_suspicious+, +:malmal_malicious+, or
20
+ # +:malmal_error+ when it could not be scanned, with the finding codes in
21
+ # +errors.details+ (+codes:+) and the file name (+filename:+).
22
+ #
23
+ # Options: +policy+, +allow+, +types+, +max_memory+, +wait+ and
24
+ # +pdf_passwords+ build a scanner of their own from +config.malmal+ with
25
+ # those changes. +message+ replaces the error message, as with any
26
+ # validator.
27
+ class Validator < ::ActiveModel::EachValidator
28
+ def check_validity!
29
+ unknown = options.keys - SCANNER_OPTIONS - %i[message if unless on allow_nil allow_blank strict]
30
+ raise ArgumentError, "unknown malmal option #{unknown.first.inspect}" unless unknown.empty?
31
+ end
32
+
33
+ def validate_each(record, attribute, _value)
34
+ Attachables.pending(record, attribute).each do |upload|
35
+ check(record, attribute, upload)
36
+ end
37
+ end
38
+
39
+ private
40
+
41
+ def check(record, attribute, upload)
42
+ data = Attachables.read(upload, Malmal::Rails.read_limit)
43
+ report = Malmal::Rails.scan(data, filename: upload.filename, content_type: upload.content_type,
44
+ scanner: Malmal::Rails.scanner_for(options))
45
+ return if report.clean?
46
+
47
+ add(record, attribute, :"malmal_#{report.verdict}", upload, report.codes)
48
+ rescue Malmal::ScanError, Malmal::LoadError => e
49
+ Malmal::Rails.logger&.error("[malmal] #{upload.filename.inspect} was not scanned: #{e.message}")
50
+ add(record, attribute, :malmal_error, upload, [])
51
+ end
52
+
53
+ def add(record, attribute, error, upload, codes)
54
+ details = { filename: upload.filename, codes: codes, count: codes.size }
55
+ details[:message] = options[:message] if options[:message]
56
+ record.errors.add(attribute, error, **details)
57
+ end
58
+ end
59
+ end
60
+ end
61
+
62
+ # `validates :file, malmal: true` looks the validator up by this name.
63
+ MalmalValidator = Malmal::Rails::Validator unless defined?(MalmalValidator)
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Malmal
4
+ module Rails
5
+ VERSION = Malmal::VERSION
6
+ end
7
+ end
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "malmal"
4
+ require "active_support"
5
+ require "active_support/core_ext/module/attribute_accessors"
6
+ require "active_support/ordered_options"
7
+
8
+ module Malmal
9
+ # Rails integration: one scanner for the application, built from
10
+ # +config.malmal+, an Active Storage validator, scans of stored blobs, and
11
+ # attachments rebuilt from what they draw.
12
+ module Rails
13
+ # The options +config.malmal+ starts with.
14
+ DEFAULTS = {
15
+ policy: :default,
16
+ allow: [],
17
+ types: nil,
18
+ limits: {},
19
+ max_memory: Malmal::Scanner::DEFAULT_MAX_MEMORY,
20
+ wait: nil,
21
+ pdf_passwords: [],
22
+ client_url: nil,
23
+ client_token: nil,
24
+ scan_blobs: true,
25
+ purge_unclean: false,
26
+ log_filenames: false
27
+ }.freeze
28
+
29
+ SCANNER_OPTIONS = %i[policy allow types max_memory wait pdf_passwords].freeze
30
+
31
+ LOCK = Mutex.new
32
+ private_constant :LOCK
33
+
34
+ class << self
35
+ # The options in use; in an application, +config.malmal+.
36
+ def config
37
+ @config ||= ActiveSupport::OrderedOptions.new.merge!(DEFAULTS.deep_dup)
38
+ end
39
+
40
+ attr_writer :config
41
+
42
+ # What scans for the application: a Malmal::Scanner, or a
43
+ # Malmal::Client when +client_url+ is set. Built on first use, then
44
+ # shared by every thread.
45
+ def scanner
46
+ @scanner || LOCK.synchronize { @scanner ||= build(config) }
47
+ end
48
+
49
+ # A scanner with +overrides+ of the scanning options of +config+, for a
50
+ # validator that asks for its own policy or types; built once for each
51
+ # set of overrides.
52
+ def scanner_for(overrides)
53
+ overrides = overrides.slice(*SCANNER_OPTIONS)
54
+ return scanner if overrides.empty?
55
+
56
+ if config.client_url
57
+ raise ArgumentError, "#{overrides.keys.join(", ")} cannot be set per validator when scanning with malmald; " \
58
+ "start the daemon with them instead"
59
+ end
60
+ LOCK.synchronize do
61
+ @scanners ||= {}
62
+ @scanners[overrides] ||= build(config.merge(overrides))
63
+ end
64
+ end
65
+
66
+ # Forget the scanners built so far, so that the next scan builds them
67
+ # from the configuration again.
68
+ def reset!
69
+ LOCK.synchronize do
70
+ @scanner = nil
71
+ @scanners = nil
72
+ end
73
+ end
74
+
75
+ # Scan +data+ (a String or an IO) with +scanner+, and tell
76
+ # ActiveSupport::Notifications (+scan.malmal+) and the log about it.
77
+ def scan(data, filename: nil, content_type: nil, scanner: self.scanner)
78
+ payload = { filename: filename, content_type: content_type }
79
+ report = ActiveSupport::Notifications.instrument("scan.malmal", payload) do
80
+ payload[:report] = scanner.scan(data, filename: filename, content_type: content_type)
81
+ end
82
+ log(report, filename) unless report.clean?
83
+ report
84
+ end
85
+
86
+ # Rebuild +data+ with +scanner+; +sanitize.malmal+ is instrumented.
87
+ def sanitize(data, filename: nil, content_type: nil, scanner: self.scanner, **options)
88
+ payload = { filename: filename, content_type: content_type }
89
+ ActiveSupport::Notifications.instrument("sanitize.malmal", payload) do
90
+ payload[:sanitized] = scanner.sanitize(data, filename: filename, content_type: content_type, **options)
91
+ end
92
+ end
93
+
94
+ # The size limit of a scan and one byte past it: what is read of an
95
+ # upload, so that an oversized one is reported as such.
96
+ def read_limit
97
+ limits = (config.limits || {}).to_h.symbolize_keys
98
+ (limits[:max_size] || (64 << 20)) + 1
99
+ end
100
+
101
+ def logger
102
+ defined?(::Rails.logger) && ::Rails.logger ? ::Rails.logger : nil
103
+ end
104
+
105
+ private
106
+
107
+ def build(options)
108
+ return Malmal::Client.new(options[:client_url], token: options[:client_token]) if options[:client_url]
109
+
110
+ Malmal::Scanner.new(
111
+ policy: options[:policy] || :default,
112
+ allow: options[:allow] || [],
113
+ types: options[:types],
114
+ pdf_passwords: options[:pdf_passwords] || [],
115
+ max_memory: options[:max_memory],
116
+ wait: options[:wait],
117
+ **(options[:limits] || {}).to_h.symbolize_keys
118
+ )
119
+ end
120
+
121
+ def log(report, filename)
122
+ return unless logger
123
+
124
+ name = config.log_filenames && filename ? " #{filename.inspect}" : ""
125
+ logger.warn("[malmal] #{report.verdict} upload#{name}: #{report.codes.join(", ")}")
126
+ end
127
+ end
128
+ end
129
+ end
130
+
131
+ require_relative "rails/version"
132
+ require_relative "rails/attachables"
133
+ require_relative "rails/validator"
134
+ require_relative "rails/blob_scan"
135
+ require_relative "rails/sanitizes_attachment"
136
+ require_relative "rails/railtie" if defined?(Rails::Railtie)
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "malmal/rails"
metadata ADDED
@@ -0,0 +1,115 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: malmal-rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.4.0
5
+ platform: ruby
6
+ authors:
7
+ - nguyenthuan155632
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: activestorage
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '7.1'
19
+ - - "<"
20
+ - !ruby/object:Gem::Version
21
+ version: '9'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: '7.1'
29
+ - - "<"
30
+ - !ruby/object:Gem::Version
31
+ version: '9'
32
+ - !ruby/object:Gem::Dependency
33
+ name: malmal
34
+ requirement: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - '='
37
+ - !ruby/object:Gem::Version
38
+ version: 0.4.0
39
+ type: :runtime
40
+ prerelease: false
41
+ version_requirements: !ruby/object:Gem::Requirement
42
+ requirements:
43
+ - - '='
44
+ - !ruby/object:Gem::Version
45
+ version: 0.4.0
46
+ - !ruby/object:Gem::Dependency
47
+ name: railties
48
+ requirement: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: '7.1'
53
+ - - "<"
54
+ - !ruby/object:Gem::Version
55
+ version: '9'
56
+ type: :runtime
57
+ prerelease: false
58
+ version_requirements: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: '7.1'
63
+ - - "<"
64
+ - !ruby/object:Gem::Version
65
+ version: '9'
66
+ description: |
67
+ Rails integration for the malmal upload scanner: a validator for Active Storage
68
+ attachments, scans of stored blobs (direct uploads included) recorded in their
69
+ metadata, attachments rebuilt from what they draw, and config.malmal.
70
+ executables: []
71
+ extensions: []
72
+ extra_rdoc_files: []
73
+ files:
74
+ - LICENSE-APACHE
75
+ - LICENSE-MIT
76
+ - README.md
77
+ - config/locales/en.yml
78
+ - lib/generators/malmal/install/install_generator.rb
79
+ - lib/generators/malmal/install/templates/malmal.rb
80
+ - lib/malmal-rails.rb
81
+ - lib/malmal/rails.rb
82
+ - lib/malmal/rails/attachables.rb
83
+ - lib/malmal/rails/blob_scan.rb
84
+ - lib/malmal/rails/railtie.rb
85
+ - lib/malmal/rails/sanitizes_attachment.rb
86
+ - lib/malmal/rails/validator.rb
87
+ - lib/malmal/rails/version.rb
88
+ homepage: https://github.com/nguyenthuan155632/malmal
89
+ licenses:
90
+ - MIT
91
+ - Apache-2.0
92
+ metadata:
93
+ homepage_uri: https://github.com/nguyenthuan155632/malmal
94
+ source_code_uri: https://github.com/nguyenthuan155632/malmal/tree/main/bindings/ruby/malmal-rails
95
+ changelog_uri: https://github.com/nguyenthuan155632/malmal/blob/main/CHANGELOG.md
96
+ bug_tracker_uri: https://github.com/nguyenthuan155632/malmal/issues
97
+ rubygems_mfa_required: 'true'
98
+ rdoc_options: []
99
+ require_paths:
100
+ - lib
101
+ required_ruby_version: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - ">="
104
+ - !ruby/object:Gem::Version
105
+ version: '3.2'
106
+ required_rubygems_version: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ requirements: []
112
+ rubygems_version: 3.6.9
113
+ specification_version: 4
114
+ summary: Scan and rebuild Active Storage uploads with malmal
115
+ test_files: []