active_storage_av_scan 0.1.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: b6df5649080705ad47fb181490a51ab55ee685b4dc935cb8bf4a6847da82a641
4
+ data.tar.gz: 51026120b1bc776676b671af11086bd06720b2715a2437109d575c07259f71bf
5
+ SHA512:
6
+ metadata.gz: e09e7d0ece60314e0bb25dee6175de5c05f98f224bb549a1f17db84aab147750a72732bad24d413201c42a83c3f9cc2c858514fb248e6e51b6a662a66391b397
7
+ data.tar.gz: f46df87bf21899c76aee4f8668158aa96274843012f40a33b7945bc590cb471ad38adc567f18f657ef983210423ae50d870acdd74d136264897ee4e55f9976e4
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-11-07
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 TODO: Write your name
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
13
+ all 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
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,285 @@
1
+
2
+ # ActiveStorage AV Scan
3
+
4
+ A lightweight antivirus scanning extension for **Rails Active Storage**.
5
+ Automatically scans uploaded files using **ClamAV**, records results, and exposes clean helpers for models and views.
6
+
7
+ > ⚠️ Currently an **early release (`v0.1.0`)** — battle-tested in real Rails apps, but specs and HTTP/Lambda integrations are coming soon.
8
+
9
+ ---
10
+
11
+ ## Features
12
+
13
+ - Automatic background scanning of Active Storage attachments
14
+ - Adapter-agnostic — works with **Sidekiq**, **SolidQueue**, **Resque**, or any ActiveJob backend
15
+ - Built-in **ClamAV scanner**
16
+ - Dedicated `AttachmentScan` model to store results
17
+ - Easy **view helpers** for showing scan status
18
+ - Configurable **infection policy** (`infected_handler`)
19
+
20
+ ---
21
+
22
+ ## 🚀 Installation
23
+
24
+ Add to your Gemfile:
25
+
26
+ ```ruby
27
+ gem "active_storage_av_scan"
28
+ ````
29
+
30
+ Install and migrate:
31
+
32
+ ```bash
33
+ bundle install
34
+ bundle exec rails g active_storage_av_scan:install
35
+ bundle exec rails db:migrate
36
+ ```
37
+
38
+ This creates:
39
+
40
+ * The `active_storage_attachment_scans` table
41
+ * An initializer at `config/initializers/active_storage_av_scan.rb`
42
+
43
+ ---
44
+
45
+ ## ⚙️ Configuration
46
+
47
+ ### Default: Local ClamAV
48
+
49
+ ```ruby
50
+ # config/initializers/active_storage_av_scan.rb
51
+ ActiveStorageAvScan.queue_name = :av_scan
52
+ ActiveStorageAvScan.scanner = ActiveStorageAvScan::Scanners::Clamav.new
53
+ ```
54
+
55
+ > 💡 Check ClamAV is installed:
56
+ > macOS → `brew install clamav`
57
+ > Debian/Ubuntu → `sudo apt install clamav`
58
+
59
+
60
+
61
+ ### 💡 Custom Scanners
62
+
63
+ You can plug in **any custom scanner backend** by assigning your own object that implements the same simple `scan` interface:
64
+
65
+ ```ruby
66
+ class MyCustomScanner
67
+ include ActiveStorageAvScan::Scanner
68
+
69
+ # Must return an ActiveStorageAvScan::ScanResult
70
+ def scan(io:, filename:, blob: nil, **_opts)
71
+ # Example: call your external AV API or service
72
+ response = ExternalAV.scan(io)
73
+ if response.clean?
74
+ ActiveStorageAvScan::ScanResult.new(status: :clean, details: "Clean via ExternalAV")
75
+ else
76
+ ActiveStorageAvScan::ScanResult.new(
77
+ status: :infected,
78
+ virus_name: response.virus_name,
79
+ details: response.details
80
+ )
81
+ end
82
+ end
83
+ end
84
+
85
+ # Use it in your initializer
86
+ ActiveStorageAvScan.scanner = MyCustomScanner.new
87
+ ```
88
+
89
+ Any scanner that responds to:
90
+
91
+ ```ruby
92
+ scan(io:, filename:, blob: nil, **opts)
93
+ ```
94
+
95
+ and returns an instance of:
96
+
97
+ ```ruby
98
+ ActiveStorageAvScan::ScanResult.new(status:, virus_name:, details:)
99
+ ```
100
+
101
+ will work out of the box.
102
+
103
+ > *Upcoming:* the gem will include first-class support for **HTTP-based external scanners** (e.g. AWS Lambda AV, REST APIs) in a future release.
104
+
105
+ ---
106
+
107
+ ## Usage
108
+
109
+ ### 1. Enable scanning
110
+
111
+ Add `av_scanned_attachments` to your model:
112
+
113
+ ```ruby
114
+ class Expense < ApplicationRecord
115
+ has_many_attached :receipts
116
+
117
+ av_scanned_attachments :receipts
118
+ end
119
+ ```
120
+
121
+ Every upload triggers a background scan automatically.
122
+
123
+ ### 2. Check results
124
+
125
+ ```ruby
126
+ @expense.receipts_all_clean? # => true / false
127
+ @expense.receipts_any_infected? # => true / false
128
+ @expense.receipts_scan_statuses # => [[attachment, "clean"], ...]
129
+ ```
130
+
131
+ All results are stored in `ActiveStorageAvScan::AttachmentScan`.
132
+
133
+ ---
134
+
135
+ ## 🧠 Infection Handling
136
+
137
+ You can define what happens when a file is infected:
138
+
139
+ ```ruby
140
+ ActiveStorageAvScan.infected_handler = lambda do |blob, scan|
141
+ Rails.logger.warn "[AV] Infected file: #{blob.filename} (#{scan.virus_name})"
142
+ blob.attachments.each(&:purge_later)
143
+ end
144
+ ```
145
+
146
+ Handler signature:
147
+
148
+ ```ruby
149
+ ->(blob, scan_record) { ... }
150
+ ```
151
+
152
+ ---
153
+
154
+ ## 💻 View Helpers
155
+
156
+ Add scan badges next to your file links:
157
+
158
+ ```erb
159
+ <% @expense.receipts.each do |attachment| %>
160
+ <%= link_to attachment.filename, url_for(attachment) %>
161
+ <%= av_scan_badge(attachment) %>
162
+ <% end %>
163
+ ```
164
+
165
+ Default output:
166
+
167
+ ```html
168
+ <span class="av-scan-badge av-scan-badge-clean">Clean</span>
169
+ ```
170
+ You can also override classes inline for a specific badge:
171
+
172
+
173
+ ``` ruby
174
+ <%= av_scan_badge(attachment, css_class: "ml-2 text-xs") %>
175
+ ```
176
+
177
+ Customize badge classes for Tailwind/Bootstrap/etc.:
178
+ ```ruby
179
+ ActiveStorageAvScan.badge_class_map = {
180
+ "pending" => "text-gray-700 bg-gray-200 rounded px-2 py-0.5 text-xs",
181
+ "clean" => "text-green-800 bg-green-100 rounded px-2 py-0.5 text-xs",
182
+ "infected" => "text-red-800 bg-red-100 rounded px-2 py-0.5 text-xs",
183
+ "error" => "text-yellow-800 bg-yellow-100 rounded px-2 py-0.5 text-xs"
184
+ }
185
+
186
+ ```
187
+
188
+ > When you run `rails g active_storage_av_scan:install`, a default
189
+ > `app/assets/stylesheets/active_storage_av_scan.css` file is created to style scan-badges.
190
+ > You can import it into your main stylesheet, tweak it, or replace it
191
+ > entirely with your own styles or Tailwind/Bootstrap classes.
192
+
193
+ ---
194
+
195
+ ## 🔍 Model Reference
196
+
197
+ ### `ActiveStorageAvScan::AttachmentScan`
198
+
199
+ | Column | Type | Description |
200
+ | ------------ | -------- | ----------------------------------------------- |
201
+ | `blob_id` | bigint | References `ActiveStorage::Blob` |
202
+ | `status` | string | `"pending"`, `"clean"`, `"infected"`, `"error"` |
203
+ | `scanner` | string | Scanner class used |
204
+ | `virus_name` | string | Virus signature name (if any) |
205
+ | `details` | text | Raw output or error message |
206
+ | `scanned_at` | datetime | Time scanned |
207
+
208
+ ---
209
+
210
+ ## 🧩 Storage Compatibility
211
+
212
+ Works transparently with all Active Storage services:
213
+
214
+ ```yaml
215
+ amazon:
216
+ service: S3
217
+ bucket: your-bucket-<%= Rails.env %>
218
+
219
+ google:
220
+ service: GCS
221
+ bucket: your-bucket-<%= Rails.env %>
222
+
223
+ mirror:
224
+ service: Mirror
225
+ primary: amazon
226
+ mirrors: [google]
227
+ ```
228
+
229
+ The scanner only ever sees an IO object (`blob.open`), regardless of backend.
230
+
231
+ ---
232
+
233
+ ## 🔒 Requirements
234
+
235
+ * Ruby 3.0+
236
+ * Rails 6.1+ (tested on 6.1, 7.0, 7.1)
237
+ * Active Storage configured
238
+ * ClamAV installed (`clamscan` available in PATH)
239
+
240
+ ---
241
+
242
+ ## 🧰 Development
243
+
244
+ Clone and run locally:
245
+
246
+ ```bash
247
+ git clone git@github.com:ajazfarhad/active_storage_av_scan.git
248
+ cd active_storage_av_scan
249
+ bundle install
250
+ ```
251
+
252
+ You can test inside a sample Rails app:
253
+
254
+ ```bash
255
+ rails g active_storage_av_scan:install
256
+ rails db:migrate
257
+ ```
258
+
259
+ Attach a file and observe the scan results in the console or DB.
260
+
261
+ ---
262
+
263
+ ## 🧭 Roadmap
264
+
265
+ * [ ] HTTP / Lambda scanner backend
266
+ * [ ] Async result polling & notifications
267
+ * [ ] Slack / Email alert hooks
268
+ * [ ] CLI task (`rails active_storage_av_scan:scan_all`)
269
+ * [ ] Lightweight audit log
270
+ * [ ] Rails Admin / ActiveAdmin integration
271
+ * [ ] RSpec test coverage (planned for v0.2.0)
272
+
273
+ ---
274
+
275
+ ## 🧑‍💻 Contributing
276
+
277
+ Contributions welcome!
278
+ Bug reports and PRs on GitHub:
279
+ [https://github.com/ajazfarhad/active_storage_av_scan](https://github.com/)
280
+
281
+ ---
282
+
283
+ ## 📄 License
284
+
285
+ MIT License © 2025 [Ajaz Farhad]
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+ module ActiveStorageAvScan
3
+ class AttachmentScan < ::ActiveRecord::Base
4
+ self.table_name = "active_storage_attachment_scans"
5
+
6
+ belongs_to :blob, class_name: "ActiveStorage::Blob"
7
+
8
+ STATUSES = %w[pending clean infected error].freeze
9
+
10
+ STATUS_MAP = {
11
+ pending: "pending",
12
+ clean: "clean",
13
+ infected: "infected",
14
+ errored: "error"
15
+ }.freeze
16
+
17
+ validates :status, presence: true, inclusion: { in: STATUSES }
18
+
19
+ STATUS_MAP.each do |name, value|
20
+ # scopes: .pending, .clean, .infected, .errored
21
+ scope name, -> { where(status: value) }
22
+
23
+ # predicate methods: #pending?, #clean?, #infected?, #errored?
24
+ define_method("#{name}?") do
25
+ status == value
26
+ end
27
+ end
28
+ end
29
+ end
30
+
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveStorageAvScan
4
+ module Model
5
+ extend ActiveSupport::Concern
6
+
7
+ class_methods do
8
+ # Example usage:
9
+ # av_scanned_attachments :receipts, :invoice
10
+ #
11
+ def av_scanned_attachments(*attachment_names)
12
+ attachment_names = attachment_names.map(&:to_sym)
13
+
14
+ # record which attachment names are protected
15
+ class_attribute :av_scanned_attachment_names, instance_writer: false, default: []
16
+ self.av_scanned_attachment_names += attachment_names
17
+
18
+ # after commit, enqueue scans for any blobs without a scan record
19
+ after_commit(on: %i[create update]) do
20
+ self.class.av_scanned_attachment_names.each do |name|
21
+ attachments = send(name)
22
+ # supports has_one_attached and has_many_attached
23
+ Array(attachments.attachments).each do |attachment|
24
+ blob = attachment.blob
25
+ next if ActiveStorageAvScan::AttachmentScan.exists?(blob: blob)
26
+
27
+ ActiveStorageAvScan::ScanJob.perform_later(blob.id)
28
+ end
29
+ end
30
+ end
31
+
32
+ attachment_names.each do |name|
33
+ define_method :"#{name}_all_clean?" do
34
+ Array(send(name).attachments).all? do |attachment|
35
+ scan = ActiveStorageAvScan::AttachmentScan.find_by(blob: attachment.blob)
36
+ scan&.clean?
37
+ end
38
+ end
39
+
40
+ define_method :"#{name}_any_infected?" do
41
+ Array(send(name).attachments).any? do |attachment|
42
+ scan = ActiveStorageAvScan::AttachmentScan.find_by(blob: attachment.blob)
43
+ scan&.infected?
44
+ end
45
+ end
46
+
47
+ define_method :"#{name}_scan_statuses" do
48
+ Array(send(name).attachments).map do |attachment|
49
+ scan = ActiveStorageAvScan::AttachmentScan.find_by(blob: attachment.blob)
50
+ [attachment, scan&.status || "pending"]
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ if defined?(Rails::Railtie)
4
+ require "active_storage_av_scan/view_helpers"
5
+
6
+ module ActiveStorageAvScan
7
+ class Railtie < ::Rails::Railtie
8
+ initializer "active_storage_av_scan.model" do
9
+ ActiveSupport.on_load(:active_record) do
10
+ include ActiveStorageAvScan::Model
11
+ end
12
+ end
13
+
14
+ initializer "active_storage_av_scan.view_helpers" do
15
+ ActiveSupport.on_load(:action_view) do
16
+ include ActiveStorageAvScan::ViewHelpers
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveStorageAvScan
4
+ class ScanJob < ::ActiveJob::Base
5
+ queue_as do
6
+ ActiveStorageAvScan.queue_name.presence || :default
7
+ end
8
+
9
+ def perform(blob_id)
10
+ blob = ActiveStorage::Blob.find(blob_id)
11
+
12
+ scan_record = AttachmentScan.find_or_create_by!(blob: blob) do |scan|
13
+ scan.status = "pending"
14
+ scan.scanner = ActiveStorageAvScan.scanner&.class&.name
15
+ end
16
+
17
+ blob.open do |io|
18
+ result = ActiveStorageAvScan.scanner.scan(
19
+ io: io,
20
+ filename: blob.filename.to_s,
21
+ blob: blob
22
+ )
23
+
24
+ scan_record.status = result.status.to_s
25
+ scan_record.virus_name = result.virus_name
26
+ scan_record.details = result.details
27
+ scan_record.scanned_at = Time.current
28
+ scan_record.scanner ||= ActiveStorageAvScan.scanner&.class&.name
29
+ scan_record.save!
30
+ end
31
+
32
+ # Run policy hook for infected files, after we've saved the record
33
+ if scan_record.infected? && ActiveStorageAvScan.infected_handler.respond_to?(:call)
34
+ safely_call_infected_handler(blob, scan_record)
35
+ end
36
+ rescue => e
37
+ scan_record ||= AttachmentScan.find_or_initialize_by(blob: blob)
38
+ scan_record.status = "error"
39
+ scan_record.details = [scan_record.details, e.message].compact.join("\n")
40
+ scan_record.scanned_at = Time.current
41
+ scan_record.save!
42
+ raise
43
+ end
44
+
45
+ private
46
+
47
+ def safely_call_infected_handler(blob, scan_record)
48
+ ActiveStorageAvScan.infected_handler.call(blob, scan_record)
49
+ rescue => e
50
+ # Don't let a buggy handler break the scan job
51
+ if defined?(Rails) && Rails.respond_to?(:logger) && Rails.logger
52
+ Rails.logger.error("[ActiveStorageAvScan] infected_handler failed for blob #{blob.id}: #{e.class} - #{e.message}")
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveStorageAvScan
4
+ class ScanResult
5
+ attr_reader :status, :virus_name, :details
6
+
7
+ # status: :clean, :infected, :error
8
+ def initialize(status:, virus_name: nil, details: nil)
9
+ @status = status.to_sym
10
+ @virus_name = virus_name
11
+ @details = details
12
+ end
13
+
14
+ def clean? = status == :clean
15
+ def infected? = status == :infected
16
+ def error? = status == :error
17
+ end
18
+
19
+ # Base module for scanners – implement concrete (ClamAV, HTTP/Lambda, etc.)
20
+ module Scanner
21
+ # Default interface: scanners SHOULD accept blob: but can ignore it.
22
+ def scan(io:, filename:, blob: nil, **_opts)
23
+ raise NotImplementedError
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,41 @@
1
+ require "open3"
2
+ require "tempfile"
3
+
4
+ module ActiveStorageAvScan
5
+ module Scanners
6
+ class Clamav
7
+ include ActiveStorageAvScan::Scanner
8
+
9
+ # Accept blob: (even though we don't use it) to keep interface compatible
10
+ def scan(io:, filename:, blob: nil, **_opts)
11
+ # io is an IO-like object or a Tempfile
12
+ path = io.respond_to?(:path) ? io.path : write_tempfile(io, filename)
13
+
14
+ stdout, stderr, status = Open3.capture3("clamscan", "--no-summary", path)
15
+
16
+ if status.success?
17
+ ScanResult.new(status: :clean)
18
+ else
19
+ # crude parsing
20
+ virus = stdout.to_s.split(":").last&.strip
21
+ ScanResult.new(
22
+ status: :infected,
23
+ virus_name: virus,
24
+ details: stdout.presence || stderr
25
+ )
26
+ end
27
+ rescue => e
28
+ ScanResult.new(status: :error, details: e.message)
29
+ end
30
+
31
+ private
32
+
33
+ def write_tempfile(io, filename)
34
+ file = Tempfile.new(["avscan", File.extname(filename)])
35
+ IO.copy_stream(io, file)
36
+ file.rewind
37
+ file.path
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveStorageAvScan
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,46 @@
1
+ # lib/active_storage_av_scan/view_helpers.rb
2
+ # frozen_string_literal: true
3
+
4
+ module ActiveStorageAvScan
5
+ module ViewHelpers
6
+ # Returns "pending", "clean", "infected", or "error" for an attachment.
7
+ # If there's no scan record yet, defaults to "pending".
8
+ def av_scan_status(attachment)
9
+ scan = ActiveStorageAvScan::AttachmentScan.find_by(blob: attachment.blob)
10
+ scan&.status || "pending"
11
+ end
12
+
13
+ # Renders a small badge showing scan status.
14
+ #
15
+ # Options:
16
+ # label: custom text (default: "Pending"/"Clean"/"Infected"/"Error")
17
+ # css_class: extra CSS classes to append
18
+ # tag: HTML tag to use (default: :span)
19
+ #
20
+ # Example:
21
+ # <%= av_scan_badge(attachment) %>
22
+ # <%= av_scan_badge(attachment, css_class: "ml-2 text-xs") %>
23
+ #
24
+ def av_scan_badge(attachment, label: nil, css_class: nil, tag: :span, **attrs)
25
+ status = av_scan_status(attachment)
26
+ default_tag = tag || :span
27
+
28
+ text = label || default_label_for_status(status)
29
+ base_class = ActiveStorageAvScan.badge_class_for(status)
30
+ full_class = [base_class, css_class].compact.join(" ")
31
+
32
+ content_tag(default_tag, text, { class: full_class }.merge(attrs))
33
+ end
34
+
35
+ private
36
+
37
+ def default_label_for_status(status)
38
+ case status.to_s
39
+ when "clean" then "Clean"
40
+ when "infected" then "Infected"
41
+ when "error" then "Scan error"
42
+ else "Pending scan"
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support"
4
+ require "active_support/core_ext"
5
+ require "active_job"
6
+ require "active_record"
7
+
8
+ require "active_storage_av_scan/version"
9
+ require "active_storage_av_scan/railtie"
10
+ require "active_storage_av_scan/scanner"
11
+ require "active_storage_av_scan/attachment_scan"
12
+ require "active_storage_av_scan/model"
13
+ require "active_storage_av_scan/scan_job"
14
+ require "active_storage_av_scan/scanners/clamav"
15
+
16
+ module ActiveStorageAvScan
17
+ # configurable scanner backend (e.g. ClamavScanner, HttpScanner, etc.)
18
+ mattr_accessor :scanner
19
+
20
+ # queue name used by ScanJob (falls back to :default)
21
+ mattr_accessor :queue_name
22
+
23
+ # mapping from status => CSS classes
24
+ # apps can override this in an initializer
25
+ mattr_accessor :badge_class_map
26
+ self.badge_class_map = {
27
+ "pending" => "av-scan-badge av-scan-badge-pending",
28
+ "clean" => "av-scan-badge av-scan-badge-clean",
29
+ "infected" => "av-scan-badge av-scan-badge-infected",
30
+ "error" => "av-scan-badge av-scan-badge-error"
31
+ }
32
+
33
+ def self.badge_class_for(status)
34
+ badge_class_map[status.to_s] || "av-scan-badge"
35
+ end
36
+
37
+ # optional hook: called when a scan result is infected
38
+ # signature: ->(blob, attachment_scan) { ... }
39
+ mattr_accessor :infected_handler
40
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+ require "rails/generators/migration"
5
+
6
+ module ActiveStorageAvScan
7
+ module Generators
8
+ class InstallGenerator < Rails::Generators::Base
9
+ include Rails::Generators::Migration
10
+
11
+ desc "Install ActiveStorageAvScan (migration + initializer)."
12
+
13
+ source_root File.expand_path("templates", __dir__)
14
+
15
+ # Always use timestamped migrations
16
+ def self.next_migration_number(dirname)
17
+ Time.now.utc.strftime("%Y%m%d%H%M%S")
18
+ end
19
+
20
+ def copy_migration
21
+ check_requirements!
22
+ migration_template "create_active_storage_attachment_scans.rb",
23
+ "db/migrate/create_active_storage_attachment_scans.rb"
24
+ end
25
+
26
+ def copy_initializer
27
+ # We don't strictly need the checks here again, copy_migration already ran them
28
+ template "initializer.rb",
29
+ "config/initializers/active_storage_av_scan.rb"
30
+ end
31
+
32
+ def copy_stylesheet
33
+ # For classic asset pipeline / Sprockets:
34
+ if File.directory?("app/assets/stylesheets")
35
+ copy_file "active_storage_av_scan.css",
36
+ "app/assets/stylesheets/active_storage_av_scan.css"
37
+ # For cssbundling-rails apps (app/assets/builds or app/javascript/styles):
38
+ elsif File.directory?("app/assets/builds")
39
+ copy_file "active_storage_av_scan.css",
40
+ "app/assets/builds/active_storage_av_scan.css"
41
+ else
42
+ say_status :warning,
43
+ "Could not determine stylesheets directory; please copy active_storage_av_scan.css manually if needed.",
44
+ :yellow
45
+ end
46
+ end
47
+
48
+
49
+ private
50
+
51
+ def check_requirements!
52
+ check_active_storage!
53
+ check_clamav!
54
+ end
55
+
56
+ def check_active_storage!
57
+ unless defined?(ActiveStorage::Blob)
58
+ say_status :error, "Active Storage does not appear to be loaded.", :red
59
+ say "Add Active Storage and run `rails active_storage:install` and `rails db:migrate` first.", :red
60
+ raise Thor::Error, "Active Storage is required for active_storage_av_scan."
61
+ end
62
+
63
+ begin
64
+ unless ActiveRecord::Base.connection.data_source_exists?(ActiveStorage::Blob.table_name)
65
+ say_status :error, "Active Storage tables not found (#{ActiveStorage::Blob.table_name}).", :red
66
+ say "Run `rails active_storage:install` and `rails db:migrate`.", :red
67
+ raise Thor::Error, "Active Storage is required for active_storage_av_scan."
68
+ end
69
+ rescue ActiveRecord::NoDatabaseError
70
+ # During some setup flows the DB may not exist yet – let the user handle that.
71
+ say_status :warning, "Skipping Active Storage DB check (database not created yet).", :yellow
72
+ end
73
+ end
74
+
75
+ def check_clamav!
76
+ return if ENV["ACTIVE_STORAGE_AV_SCAN_SKIP_CLAMAV_CHECK"] == "1"
77
+
78
+ # Check if `clamscan` is available in PATH
79
+ if system("command -v clamscan >/dev/null 2>&1")
80
+ say_status :ok, "ClamAV detected (`clamscan` found in PATH).", :green
81
+ else
82
+ say_status :warning, "ClamAV not detected (`clamscan` not found in PATH).", :yellow
83
+ say "The default ClamAV scanner will not work until ClamAV is installed,", :yellow
84
+ say "or you configure `ActiveStorageAvScan.scanner` to a different backend.", :yellow
85
+ end
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,30 @@
1
+ /* Default styles for ActiveStorageAvScan badges.
2
+ * You can tweak or remove these in your app as needed.
3
+ */
4
+
5
+ .av-scan-badge {
6
+ display: inline-block;
7
+ padding: 0.1rem 0.4rem;
8
+ border-radius: 9999px;
9
+ font-size: 0.75rem;
10
+ }
11
+
12
+ .av-scan-badge-clean {
13
+ background: #e0f7e9;
14
+ color: #166534;
15
+ }
16
+
17
+ .av-scan-badge-infected {
18
+ background: #fee2e2;
19
+ color: #b91c1c;
20
+ }
21
+
22
+ .av-scan-badge-pending {
23
+ background: #e5e7eb;
24
+ color: #374151;
25
+ }
26
+
27
+ .av-scan-badge-error {
28
+ background: #fef3c7;
29
+ color: #92400e;
30
+ }
@@ -0,0 +1,16 @@
1
+ class CreateActiveStorageAttachmentScans < ActiveRecord::Migration[<%= Rails::VERSION::MAJOR %>.<%= Rails::VERSION::MINOR %>]
2
+ def change
3
+ create_table :active_storage_attachment_scans do |t|
4
+ t.references :blob, null: false, foreign_key: { to_table: :active_storage_blobs }
5
+ t.string :status, null: false, default: "pending"
6
+ t.string :scanner
7
+ t.string :virus_name
8
+ t.text :details
9
+ t.datetime :scanned_at
10
+
11
+ t.timestamps
12
+ end
13
+
14
+ add_index :active_storage_attachment_scans, :status
15
+ end
16
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Configure the scanner backend for ActiveStorageAvScan.
4
+ #
5
+ # You can use:
6
+ # - ActiveStorageAvScan::Scanners::Clamav (local clamscan/clamd)
7
+ # - ActiveStorageAvScan::Scanners::Http (remote HTTP / Lambda-based service)
8
+ #
9
+ # Example ClamAV:
10
+ # ActiveStorageAvScan.scanner = ActiveStorageAvScan::Scanners::Clamav.new
11
+ #
12
+
13
+ ActiveStorageAvScan.scanner ||= ActiveStorageAvScan::Scanners::Clamav.new
metadata ADDED
@@ -0,0 +1,94 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: active_storage_av_scan
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ajaz Farhad
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 2025-11-09 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rails
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '6.1'
19
+ - - "<"
20
+ - !ruby/object:Gem::Version
21
+ version: '9.0'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: '6.1'
29
+ - - "<"
30
+ - !ruby/object:Gem::Version
31
+ version: '9.0'
32
+ - !ruby/object:Gem::Dependency
33
+ name: rspec
34
+ requirement: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - "~>"
37
+ - !ruby/object:Gem::Version
38
+ version: '3.12'
39
+ type: :development
40
+ prerelease: false
41
+ version_requirements: !ruby/object:Gem::Requirement
42
+ requirements:
43
+ - - "~>"
44
+ - !ruby/object:Gem::Version
45
+ version: '3.12'
46
+ description: active_storage_av_scan adds background antivirus scanning to Rails Active
47
+ Storage attachments, with a ClamAV scanner, scan status model, view helpers, and
48
+ configurable infection handling.
49
+ executables: []
50
+ extensions: []
51
+ extra_rdoc_files: []
52
+ files:
53
+ - ".rspec"
54
+ - CHANGELOG.md
55
+ - CODE_OF_CONDUCT.md
56
+ - LICENSE.txt
57
+ - README.md
58
+ - lib/active_storage_av_scan.rb
59
+ - lib/active_storage_av_scan/attachment_scan.rb
60
+ - lib/active_storage_av_scan/model.rb
61
+ - lib/active_storage_av_scan/railtie.rb
62
+ - lib/active_storage_av_scan/scan_job.rb
63
+ - lib/active_storage_av_scan/scanner.rb
64
+ - lib/active_storage_av_scan/scanners/clamav.rb
65
+ - lib/active_storage_av_scan/version.rb
66
+ - lib/active_storage_av_scan/view_helpers.rb
67
+ - lib/generators/active_storage_av_scan/install/install_generator.rb
68
+ - lib/generators/active_storage_av_scan/install/templates/active_storage_av_scan.css
69
+ - lib/generators/active_storage_av_scan/install/templates/create_active_storage_attachment_scans.rb
70
+ - lib/generators/active_storage_av_scan/install/templates/initializer.rb
71
+ homepage: https://github.com/ajazfarhad/active_storage_av_scan
72
+ licenses:
73
+ - MIT
74
+ metadata:
75
+ source_code_uri: https://github.com/ajazfarhad/active_storage_av_scan
76
+ changelog_uri: https://github.com/ajazfarhad/active_storage_av_scan/blob/main/CHANGELOG.md
77
+ rdoc_options: []
78
+ require_paths:
79
+ - lib
80
+ required_ruby_version: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - ">="
83
+ - !ruby/object:Gem::Version
84
+ version: 3.0.0
85
+ required_rubygems_version: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ requirements: []
91
+ rubygems_version: 3.6.3
92
+ specification_version: 4
93
+ summary: Antivirus scanning for Rails Active Storage using ClamAV.
94
+ test_files: []