rack-ai 0.2.0 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1d95d49cfff0cb1d7f62fb2f31680b6b2ce139ef8c2bf87c4bb86e5a5123c876
4
- data.tar.gz: 05ed2583e65ef1fa68dbb502bafcc4046ed67495b049ed1ffc41e4ed7240f283
3
+ metadata.gz: a73e35063e7e68e0af7c74603df68d971a2da7837b06d66c1721abc183929604
4
+ data.tar.gz: 9cca59b691a9a532944175d18c0b2b61e2c7d2e32c9a199b032180d7fbaea836
5
5
  SHA512:
6
- metadata.gz: 3fc2d6b2dcd73a946e20de45c66cf92bcf65c342f434adf939d79b1b732a4b16d42d4faa9f04b28c4dcc116baf3168c1cc014d29d7a7035b55bea915be441cda
7
- data.tar.gz: 8fbe16fb2da9b93e3ff3896e923c3e3832f69319f4bff630fb68fcab16530e70e0fb95b293a00559bb9ec95cb87a707b8cd69b5fa45398817ecbdacbe1beac2a
6
+ metadata.gz: ce2759602f6428f04102889998d096aa776a403f62c3751bc26c8a7ae47040e0f658e55823108135f930c34261339d9a40c9bd3d9341e6a7114ea2e7e2042d63
7
+ data.tar.gz: 9f77a8725714b6107fdf069f3b1fc1d4a1124cb37264ed45932929e4bcca221fee49dccbb053245571e664e60dee76761983fe763ded8606c3b6ec83f78dd50b
data/CHANGELOG.md CHANGED
@@ -7,27 +7,68 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.4.0] - 2025-01-11
11
+
12
+ ### Added
13
+ - **New Security Scanner Feature**: Advanced security threat detection with pattern matching for SQL injection, XSS, path traversal, and command injection
14
+ - **Rate Limiter Feature**: Built-in rate limiting with client identification, configurable windows, and penalty periods
15
+ - **Enhanced Logger**: Improved logging system with proper method delegation and structured output
16
+ - **Comprehensive Test Coverage**: Added complete test suites for new features with 96 passing tests
17
+
18
+ ### Changed
19
+ - **Improved Error Handling**: Enhanced configuration validation with safe method access patterns
20
+ - **Better Code Quality**: Fixed potential null pointer exceptions in classification and moderation features
21
+ - **Enhanced Security**: Added defensive programming patterns throughout the codebase
22
+
23
+ ### Fixed
24
+ - Logger method delegation issues - now properly uses structured logging
25
+ - Configuration access safety in classification feature routing checks
26
+ - Moderation feature configuration validation for toxicity thresholds
27
+ - Syntax errors in security scanner regex patterns
28
+
29
+ ### Security
30
+ - Advanced threat detection patterns for multiple attack vectors
31
+ - Improved rate limiting with client fingerprinting
32
+ - Enhanced input validation and sanitization
33
+
34
+ ## [0.3.0] - 2024-01-16
35
+
10
36
  ### Added
11
- - Rate limiting feature with configurable windows and thresholds
12
- - Anomaly detection with baseline learning and risk scoring
13
- - Enhanced logging system with JSON/structured output formats
14
- - Comprehensive example application demonstrating all features
15
- - Advanced error handling and edge case coverage
16
- - Performance optimizations and memory management
37
+ - **New Providers**: HuggingFace and Local provider implementations
38
+ - **New Features**:
39
+ - Caching with predictive analysis and Redis integration
40
+ - Smart routing based on AI classification results
41
+ - Enhanced logging with structured AI insights
42
+ - Content enhancement for SEO, readability, and accessibility
43
+ - Rate limiting with IP-based tracking and configurable windows
44
+ - Anomaly detection with baseline learning and risk scoring
45
+ - **Advanced Examples**:
46
+ - Rails integration with all features enabled
47
+ - Sinatra microservice with security-focused configuration
48
+ - Comprehensive example demonstrating all capabilities
49
+ - **Enhanced Configuration**: OpenStruct-based nested configuration for better usability
50
+ - **Improved Testing**: Complete test coverage for all providers and features
51
+ - **Better Error Handling**: Comprehensive error handling throughout the codebase
17
52
 
18
53
  ### Changed
19
- - Removed OStruct dependency to eliminate Ruby 3.5+ warnings
20
- - Improved configuration system with better validation
21
- - Enhanced middleware initialization and provider setup
22
- - Better test coverage and mocking strategies
54
+ - Configuration system now uses OpenStruct for nested settings
55
+ - Logger implementation simplified and warnings resolved
56
+ - Provider initialization improved with better validation
57
+ - Middleware now supports all implemented features
23
58
 
24
59
  ### Fixed
25
- - Configuration validation issues
26
- - Provider initialization edge cases
27
- - Test suite stability and reliability
28
- - Memory leaks in long-running applications
60
+ - Configuration hash access issues resolved
61
+ - Logger constant conflicts eliminated
62
+ - Test failures for provider implementations
63
+ - OStruct deprecation warnings addressed
64
+
65
+ ### Security
66
+ - Enhanced injection detection capabilities
67
+ - Improved anomaly detection algorithms
68
+ - Better rate limiting implementation
69
+ - Comprehensive security analysis features
29
70
 
30
- ## [0.1.0] - 2025-01-11
71
+ ## [0.2.0] - 2024-01-15
31
72
 
32
73
  ### Added
33
74
  - Initial release with core AI middleware functionality
@@ -0,0 +1,353 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Advanced Rails Integration Example for Rack::AI
4
+ # This example demonstrates how to integrate Rack::AI with a Rails application
5
+ # using all available features and advanced configuration options.
6
+
7
+ require 'rails'
8
+ require 'rack/ai'
9
+
10
+ class RailsAiIntegrationApp < Rails::Application
11
+ # Basic Rails configuration
12
+ config.load_defaults 7.0
13
+ config.eager_load = false
14
+ config.cache_classes = false
15
+ config.consider_all_requests_local = true
16
+ config.secret_key_base = 'test_secret_key_base_for_rack_ai_demo'
17
+
18
+ # Configure Rack::AI with all features enabled
19
+ config.middleware.use Rack::AI::Middleware,
20
+ provider: :openai,
21
+ api_key: ENV['OPENAI_API_KEY'] || 'your-openai-api-key-here',
22
+ features: [:classification, :security, :moderation, :caching, :routing, :logging, :enhancement, :rate_limiting, :anomaly_detection],
23
+ fail_safe: true,
24
+ async_processing: true,
25
+ sanitize_logs: true,
26
+ explain_decisions: true,
27
+
28
+ # Classification settings
29
+ classification: {
30
+ confidence_threshold: 0.8,
31
+ categories: [:human, :bot, :spam, :suspicious]
32
+ },
33
+
34
+ # Security settings
35
+ security: {
36
+ injection_detection: true,
37
+ anomaly_threshold: 0.7,
38
+ block_suspicious: true
39
+ },
40
+
41
+ # Moderation settings
42
+ moderation: {
43
+ toxicity_threshold: 0.6,
44
+ check_response: false,
45
+ block_on_violation: true
46
+ },
47
+
48
+ # Caching settings
49
+ caching: {
50
+ predictive_enabled: true,
51
+ prefetch_threshold: 0.9,
52
+ redis_url: ENV['REDIS_URL'] || 'redis://localhost:6379'
53
+ },
54
+
55
+ # Routing settings
56
+ routing: {
57
+ smart_routing_enabled: true,
58
+ suspicious_route: '/security/verify',
59
+ bot_route: '/api/bot'
60
+ },
61
+
62
+ # Rate limiting settings
63
+ rate_limiting: {
64
+ window_size: 3600, # 1 hour
65
+ max_requests: 1000,
66
+ block_duration: 3600,
67
+ cleanup_interval: 300
68
+ },
69
+
70
+ # Anomaly detection settings
71
+ anomaly_detection: {
72
+ baseline_window: 86400, # 24 hours
73
+ anomaly_threshold: 2.0, # z-score threshold
74
+ min_requests: 10,
75
+ learning_rate: 0.1
76
+ }
77
+
78
+ # Routes for demonstration
79
+ routes.draw do
80
+ # Main application routes
81
+ root 'home#index'
82
+
83
+ # API endpoints that will be analyzed by AI
84
+ namespace :api do
85
+ namespace :v1 do
86
+ resources :users, only: [:index, :show, :create, :update]
87
+ resources :posts, only: [:index, :show, :create, :update, :destroy]
88
+ resources :comments, only: [:create, :update, :destroy]
89
+ end
90
+ end
91
+
92
+ # Admin routes (high security)
93
+ namespace :admin do
94
+ resources :users
95
+ resources :settings
96
+ get 'dashboard', to: 'dashboard#index'
97
+ end
98
+
99
+ # Security routes (used by AI routing)
100
+ namespace :security do
101
+ get 'verify', to: 'verification#show'
102
+ post 'verify', to: 'verification#create'
103
+ get 'blocked', to: 'blocked#show'
104
+ end
105
+
106
+ # Health check endpoint (skipped by AI processing)
107
+ get 'health', to: 'health#check'
108
+
109
+ # AI analysis endpoints
110
+ namespace :ai do
111
+ get 'status', to: 'status#show'
112
+ get 'metrics', to: 'metrics#index'
113
+ get 'logs', to: 'logs#index'
114
+ end
115
+ end
116
+ end
117
+
118
+ # Controllers
119
+ class ApplicationController < ActionController::Base
120
+ protect_from_forgery with: :exception
121
+
122
+ # Access AI analysis results in controllers
123
+ before_action :check_ai_analysis
124
+
125
+ private
126
+
127
+ def check_ai_analysis
128
+ @ai_results = request.env['rack.ai']
129
+
130
+ # Log AI decisions for monitoring
131
+ if @ai_results && @ai_results[:results]
132
+ Rails.logger.info "AI Analysis: #{@ai_results[:results].inspect}"
133
+
134
+ # Handle high-risk requests
135
+ if high_risk_request?
136
+ Rails.logger.warn "High risk request detected: #{request.path}"
137
+ # Additional security measures could be implemented here
138
+ end
139
+ end
140
+ end
141
+
142
+ def high_risk_request?
143
+ return false unless @ai_results&.dig(:results)
144
+
145
+ classification = @ai_results[:results][:classification]
146
+ security = @ai_results[:results][:security]
147
+
148
+ (classification && classification[:classification] == :suspicious && classification[:confidence] > 0.8) ||
149
+ (security && security[:threat_level] == :high)
150
+ end
151
+ end
152
+
153
+ class HomeController < ApplicationController
154
+ def index
155
+ @ai_status = @ai_results ? 'Active' : 'Inactive'
156
+ @request_classification = @ai_results&.dig(:results, :classification, :classification)
157
+ @security_level = @ai_results&.dig(:results, :security, :threat_level)
158
+
159
+ render json: {
160
+ message: 'Welcome to Rails + Rack::AI Demo',
161
+ ai_status: @ai_status,
162
+ classification: @request_classification,
163
+ security_level: @security_level,
164
+ timestamp: Time.current.iso8601
165
+ }
166
+ end
167
+ end
168
+
169
+ class Api::V1::BaseController < ApplicationController
170
+ # API-specific AI handling
171
+ before_action :validate_api_request
172
+
173
+ private
174
+
175
+ def validate_api_request
176
+ if @ai_results&.dig(:results, :rate_limiting, :blocked)
177
+ render json: {
178
+ error: 'Rate limit exceeded',
179
+ retry_after: @ai_results[:results][:rate_limiting][:retry_after]
180
+ }, status: 429
181
+ return
182
+ end
183
+
184
+ if @ai_results&.dig(:results, :classification, :classification) == :spam
185
+ render json: { error: 'Request classified as spam' }, status: 403
186
+ return
187
+ end
188
+ end
189
+ end
190
+
191
+ class Api::V1::UsersController < Api::V1::BaseController
192
+ def index
193
+ # Simulate user data with AI enhancement
194
+ users = [
195
+ { id: 1, name: 'John Doe', email: 'john@example.com' },
196
+ { id: 2, name: 'Jane Smith', email: 'jane@example.com' }
197
+ ]
198
+
199
+ # AI enhancement could improve API responses
200
+ enhanced = @ai_results&.dig(:results, :enhancement, :enhancement_applied)
201
+
202
+ render json: {
203
+ users: users,
204
+ meta: {
205
+ total: users.length,
206
+ ai_enhanced: enhanced || false,
207
+ classification: @ai_results&.dig(:results, :classification, :classification)
208
+ }
209
+ }
210
+ end
211
+
212
+ def show
213
+ user_id = params[:id]
214
+
215
+ # Simulate anomaly detection for unusual access patterns
216
+ anomaly_detected = @ai_results&.dig(:results, :anomaly_detection, :risk_score)&.> 0.8
217
+
218
+ if anomaly_detected
219
+ Rails.logger.warn "Anomalous access pattern detected for user #{user_id}"
220
+ end
221
+
222
+ render json: {
223
+ id: user_id,
224
+ name: "User #{user_id}",
225
+ email: "user#{user_id}@example.com",
226
+ anomaly_detected: anomaly_detected
227
+ }
228
+ end
229
+
230
+ def create
231
+ # AI moderation for user-generated content
232
+ moderation_result = @ai_results&.dig(:results, :moderation)
233
+
234
+ if moderation_result&.dig(:flagged)
235
+ render json: {
236
+ error: 'Content violates community guidelines',
237
+ categories: moderation_result[:categories]
238
+ }, status: 422
239
+ return
240
+ end
241
+
242
+ render json: {
243
+ message: 'User created successfully',
244
+ moderation_passed: true
245
+ }, status: 201
246
+ end
247
+ end
248
+
249
+ class SecurityController < ApplicationController
250
+ def verify
251
+ render json: {
252
+ message: 'Security verification required',
253
+ reason: params[:reason] || 'suspicious_activity',
254
+ instructions: 'Please complete the verification process'
255
+ }
256
+ end
257
+
258
+ def blocked
259
+ render json: {
260
+ message: 'Access blocked',
261
+ reason: 'security_violation',
262
+ contact: 'security@example.com'
263
+ }, status: 403
264
+ end
265
+ end
266
+
267
+ class HealthController < ApplicationController
268
+ def check
269
+ render json: {
270
+ status: 'ok',
271
+ timestamp: Time.current.iso8601,
272
+ ai_middleware: 'active'
273
+ }
274
+ end
275
+ end
276
+
277
+ class Ai::StatusController < ApplicationController
278
+ def show
279
+ render json: {
280
+ ai_middleware: {
281
+ active: @ai_results.present?,
282
+ features: @ai_results&.dig(:results)&.keys || [],
283
+ processing_time: @ai_results&.dig(:processing_time),
284
+ provider: @ai_results&.dig(:provider)
285
+ },
286
+ request_analysis: @ai_results&.dig(:results) || {}
287
+ }
288
+ end
289
+ end
290
+
291
+ class Ai::MetricsController < ApplicationController
292
+ def index
293
+ # In a real application, this would fetch metrics from storage
294
+ render json: {
295
+ total_requests: 1500,
296
+ classifications: {
297
+ human: 1200,
298
+ bot: 200,
299
+ suspicious: 80,
300
+ spam: 20
301
+ },
302
+ security_threats: {
303
+ low: 1400,
304
+ medium: 80,
305
+ high: 20
306
+ },
307
+ rate_limiting: {
308
+ blocked_requests: 45,
309
+ current_limits: 1000
310
+ },
311
+ anomalies_detected: 12,
312
+ cache_hit_rate: 0.78
313
+ }
314
+ end
315
+ end
316
+
317
+ # Initialize and run the application
318
+ if __FILE__ == $0
319
+ # Set up environment
320
+ ENV['RAILS_ENV'] ||= 'development'
321
+
322
+ # Initialize Rails application
323
+ app = RailsAiIntegrationApp.new
324
+ app.initialize!
325
+
326
+ puts "🚀 Rails + Rack::AI Advanced Integration Demo"
327
+ puts "📊 Features enabled: Classification, Security, Moderation, Caching, Routing, Logging, Enhancement, Rate Limiting, Anomaly Detection"
328
+ puts "🔗 Available endpoints:"
329
+ puts " GET / - Home page with AI status"
330
+ puts " GET /api/v1/users - Users API (with AI analysis)"
331
+ puts " GET /api/v1/users/:id - User details (with anomaly detection)"
332
+ puts " POST /api/v1/users - Create user (with content moderation)"
333
+ puts " GET /admin/dashboard - Admin area (high security)"
334
+ puts " GET /security/verify - Security verification page"
335
+ puts " GET /health - Health check (AI processing skipped)"
336
+ puts " GET /ai/status - AI middleware status"
337
+ puts " GET /ai/metrics - AI analysis metrics"
338
+ puts ""
339
+ puts "🔧 Configuration:"
340
+ puts " - Set OPENAI_API_KEY environment variable for full functionality"
341
+ puts " - Set REDIS_URL for caching features (optional)"
342
+ puts " - All features are enabled with production-ready settings"
343
+ puts ""
344
+ puts "📝 Testing suggestions:"
345
+ puts " - Try different User-Agent strings to trigger bot detection"
346
+ puts " - Make rapid requests to test rate limiting"
347
+ puts " - Send suspicious payloads to test security features"
348
+ puts " - Access admin routes to see enhanced security analysis"
349
+
350
+ # Start the server
351
+ require 'rack'
352
+ Rack::Handler::WEBrick.run(app, Port: 3000, Host: '0.0.0.0')
353
+ end