rack-ai 0.1.0 → 0.3.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.
@@ -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