query_guard 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: ab42a4becef74dd106779b1e16f65f3e0178762531ede328212958cb36dbb2f5
4
+ data.tar.gz: e49b0e60d3ede416580c4e92e2f46142f3bbcc0c13da5ac9fde9024a001cccca
5
+ SHA512:
6
+ metadata.gz: 756393f33c6e2c44650b377db916c3c516f5d49191ba9557461b8dfa9bcc8a977048fcf919b71c2ef101b0cb2bfe9f92fefe639ab88d28d01a09f9d565855046
7
+ data.tar.gz: 77f0b2337a0330922438eeb20ed1b946b0b0e1264622e577a4ad005cf7e9288efda5fafb34351d0691fa489cf2dc4f123c6ec8b1c9b4f413d1c5acf8fc770122
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-11-02
4
+
5
+ - Initial release
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Chitradevi36
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,10 @@
1
+ # query_guard
2
+
3
+ Guardrails for ActiveRecord queries per request: maximum query count, slow query flagging, and optional `SELECT *` blocking.
4
+
5
+ ## Installation
6
+
7
+ Add to your Gemfile:
8
+
9
+ ```ruby
10
+ gem "query_guard"
data/Rakefile ADDED
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
9
+
10
+ desc "Build gem"
11
+ task :build do
12
+ sh "gem build query_guard.gemspec"
13
+ end
14
+
15
+ desc "Release: build and push to RubyGems"
16
+ task :release do
17
+ version = File.read("lib/query_guard/version.rb")[/VERSION\s*=\s*["'](.+?)["']/, 1]
18
+ abort("Version not found") unless version
19
+ sh "gem build query_guard.gemspec"
20
+ sh "gem push query_guard-#{version}.gem"
21
+ end
@@ -0,0 +1,9 @@
1
+ QueryGuard.configure do |c|
2
+ c.enabled_environments = %i[development test] # Prod is usually off
3
+ c.max_queries_per_request = 100 # nil to disable
4
+ c.max_duration_ms_per_query = 100.0 # nil to disable
5
+ c.block_select_star = false
6
+ c.ignored_sql = [/^PRAGMA /i, /^SAVEPOINT/i]
7
+ c.raise_on_violation = false # true to raise 500
8
+ c.log_prefix = "[QueryGuard]"
9
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+ module QueryGuard
3
+ class Config
4
+ attr_accessor :enabled_environments, :max_queries_per_request,
5
+ :max_duration_ms_per_query, :block_select_star,
6
+ :ignored_sql, :raise_on_violation, :log_prefix
7
+
8
+ def initialize
9
+ @enabled_environments = %i[development test]
10
+ @max_queries_per_request = 100
11
+ @max_duration_ms_per_query = 100.0 # ms; set to nil to disable
12
+ @block_select_star = false
13
+ @ignored_sql = [/^PRAGMA /i, /^BEGIN/i, /^COMMIT/i]
14
+ @raise_on_violation = false
15
+ @log_prefix = "[QueryGuard]"
16
+ end
17
+
18
+ def enabled?(env)
19
+ @enabled_environments.map(&:to_sym).include?(env.to_sym)
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+ module QueryGuard
3
+ class Error < StandardError; end
4
+
5
+ class Middleware
6
+ def initialize(app, config)
7
+ @app = app
8
+ @config = config
9
+ end
10
+
11
+ def call(env)
12
+ unless @config.enabled?(rails_env)
13
+ return @app.call(env)
14
+ end
15
+
16
+ Thread.current[:query_guard_stats] = { count: 0, total_duration_ms: 0.0, violations: [] }
17
+
18
+ status, headers, body = @app.call(env)
19
+ check_and_report!
20
+ [status, headers, body]
21
+ ensure
22
+ Thread.current[:query_guard_stats] = nil
23
+ end
24
+
25
+ private
26
+
27
+ def rails_env
28
+ if defined?(Rails) && Rails.respond_to?(:env)
29
+ Rails.env.to_sym
30
+ else
31
+ (ENV["RACK_ENV"] || ENV["APP_ENV"] || "development").to_sym
32
+ end
33
+ end
34
+
35
+ def logger
36
+ if defined?(Rails) && Rails.respond_to?(:logger) && Rails.logger
37
+ Rails.logger
38
+ else
39
+ @logger ||= Logger.new($stdout)
40
+ end
41
+ end
42
+
43
+ def check_and_report!
44
+ stats = Thread.current[:query_guard_stats] || { count: 0, violations: [] }
45
+ violations = stats[:violations].dup
46
+
47
+ if @config.max_queries_per_request && stats[:count] > @config.max_queries_per_request
48
+ violations << { type: :too_many_queries, count: stats[:count], limit: @config.max_queries_per_request }
49
+ end
50
+
51
+ return if violations.empty?
52
+
53
+ message = format_message(stats, violations)
54
+ logger.warn(message)
55
+
56
+ raise QueryGuard::Error, message if @config.raise_on_violation
57
+ end
58
+
59
+ def format_message(stats, violations)
60
+ details = violations.map do |v|
61
+ case v[:type]
62
+ when :too_many_queries
63
+ "too_many_queries: count=#{v[:count]} limit=#{v[:limit]}"
64
+ when :slow_query
65
+ "slow_query: #{v[:duration_ms]}ms SQL=#{truncate_sql(v[:sql])}"
66
+ when :select_star
67
+ "select_star: SQL=#{truncate_sql(v[:sql])}"
68
+ else
69
+ v[:type].to_s
70
+ end
71
+ end.join(" | ")
72
+
73
+ "#{@config.log_prefix} queries=#{stats[:count]} total_ms=#{stats[:total_duration_ms].round(2)} | #{details}"
74
+ end
75
+
76
+ def truncate_sql(sql, max = 200)
77
+ sql.length > max ? "#{sql[0, max]}..." : sql
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+ require "active_support/notifications"
3
+
4
+ module QueryGuard
5
+ module Subscriber
6
+ SQL_EVENT = "sql.active_record"
7
+
8
+ def self.install!(config)
9
+ return if @installed
10
+ @config = config
11
+ @subscriber = ActiveSupport::Notifications.subscribe(SQL_EVENT) do |_, started, finished, _, payload|
12
+ stats = Thread.current[:query_guard_stats]
13
+ next unless stats # only track inside our middleware window
14
+
15
+ # Skip schema and ignored
16
+ name = payload[:name].to_s
17
+ next if name == "SCHEMA"
18
+
19
+ sql = payload[:sql].to_s
20
+ next if config.ignored_sql.any? { |r| r === sql }
21
+
22
+ duration_ms = (finished - started) * 1000.0
23
+ stats[:count] += 1
24
+ stats[:total_duration_ms] += duration_ms
25
+
26
+ if config.max_duration_ms_per_query && duration_ms > config.max_duration_ms_per_query
27
+ stats[:violations] << {
28
+ type: :slow_query,
29
+ duration_ms: duration_ms.round(2),
30
+ sql: sql
31
+ }
32
+ end
33
+
34
+ if config.block_select_star && sql =~ /\bSELECT\s+\*/i
35
+ stats[:violations] << { type: :select_star, sql: sql }
36
+ end
37
+ end
38
+ @installed = true
39
+ end
40
+
41
+ def self.uninstall!
42
+ return unless @installed && @subscriber
43
+ ActiveSupport::Notifications.unsubscribe(@subscriber)
44
+ @installed = false
45
+ @subscriber = nil
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module QueryGuard
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+ require "active_support"
3
+ require "active_support/notifications"
4
+ require "query_guard/version"
5
+ require "query_guard/config"
6
+ require "query_guard/subscriber"
7
+ require "query_guard/middleware"
8
+
9
+ module QueryGuard
10
+ class << self
11
+ def config
12
+ @config ||= Config.new
13
+ end
14
+
15
+ def configure
16
+ yield config
17
+ self
18
+ end
19
+
20
+ def install!(app = nil)
21
+ # Install SQL subscriber once
22
+ Subscriber.install!(config)
23
+
24
+ # Install middleware (Rails or Rack)
25
+ if defined?(Rails) && Rails.respond_to?(:application) && Rails.application
26
+ # Use a Railtie-less insert for safety if called early
27
+ Rails.application.config.middleware.use(QueryGuard::Middleware, config)
28
+ elsif app
29
+ app.use(QueryGuard::Middleware, config)
30
+ end
31
+ self
32
+ end
33
+ end
34
+ end
35
+
36
+ # Auto-install for Rails via Railtie
37
+ if defined?(Rails::Railtie)
38
+ class QueryGuard::Railtie < Rails::Railtie
39
+ initializer "query_guard.install" do |app|
40
+ QueryGuard.install!(app)
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,4 @@
1
+ module QueryGuard
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,95 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: query_guard
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Chitradevi36
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-11-02 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rake
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '13.2'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '13.2'
27
+ - !ruby/object:Gem::Dependency
28
+ name: activesupport
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '5.2'
34
+ - - "<"
35
+ - !ruby/object:Gem::Version
36
+ version: '8.0'
37
+ type: :runtime
38
+ prerelease: false
39
+ version_requirements: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: '5.2'
44
+ - - "<"
45
+ - !ruby/object:Gem::Version
46
+ version: '8.0'
47
+ description: query_guard tracks SQL in Rails requests and warns/raises on excessive
48
+ count, slow queries, or SELECT * usage.
49
+ email:
50
+ - chitra.rajaguru123@gmail.com
51
+ executables: []
52
+ extensions: []
53
+ extra_rdoc_files: []
54
+ files:
55
+ - ".rspec"
56
+ - CHANGELOG.md
57
+ - LICENSE.txt
58
+ - README.md
59
+ - Rakefile
60
+ - config/initializers/query_guard.rb
61
+ - lib/query_guard.rb
62
+ - lib/query_guard/config.rb
63
+ - lib/query_guard/middleware.rb
64
+ - lib/query_guard/subscriber.rb
65
+ - lib/query_guard/version.rb
66
+ - sig/query_guard.rbs
67
+ homepage: https://github.com/Chitradevi36/query_guard
68
+ licenses:
69
+ - MIT
70
+ metadata:
71
+ allowed_push_host: https://rubygems.org
72
+ homepage_uri: https://github.com/Chitradevi36/query_guard
73
+ source_code_uri: https://github.com/Chitradevi36/query_guard
74
+ changelog_uri: https://github.com/Chitradevi36/query_guard/blob/main/CHANGELOG.md
75
+ post_install_message:
76
+ rdoc_options: []
77
+ require_paths:
78
+ - lib
79
+ required_ruby_version: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - ">="
82
+ - !ruby/object:Gem::Version
83
+ version: 3.0.0
84
+ required_rubygems_version: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: '0'
89
+ requirements: []
90
+ rubygems_version: 3.2.3
91
+ signing_key:
92
+ specification_version: 4
93
+ summary: Guardrails for ActiveRecord queries per request (count, slow SQL, SELECT
94
+ *).
95
+ test_files: []