Class: AgentAdmit::Middleware
- Inherits:
-
Object
- Object
- AgentAdmit::Middleware
- Defined in:
- lib/agentadmit/middleware.rb
Overview
Rack middleware that intercepts requests with ag_at_ tokens and validates them via introspection.
Sets env variables for downstream use:
env['agentadmit.auth_type'] -- "agent" or nil
env['agentadmit.user_id'] -- validated user ID
env['agentadmit.scopes'] -- granted scopes array
env['agentadmit.connection_id'] -- connection identifier
env['agentadmit.agent_label'] -- agent display name
env['agentadmit.presence'] -- human-presence block (Hash) or nil
Constant Summary collapse
- BEARER_AGENT_RE =
RFC 7235: the auth-scheme token is case-insensitive. Match "bearer", "Bearer", "BEARER", etc. followed by the ag_at_ prefix.
/\Abearer ag_at_/i
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app) ⇒ Middleware
constructor
A new instance of Middleware.
Constructor Details
#initialize(app) ⇒ Middleware
Returns a new instance of Middleware.
21 22 23 24 25 |
# File 'lib/agentadmit/middleware.rb', line 21 def initialize(app) @app = app @client = IntrospectionClient.new @config = AgentAdmit.configuration || Config.new end |
Instance Method Details
#call(env) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/agentadmit/middleware.rb', line 27 def call(env) auth = env["HTTP_AUTHORIZATION"] || "" if BEARER_AGENT_RE.match?(auth) # Strip the scheme prefix (case-insensitively) to get the bare token. token = auth.sub(/\Abearer /i, "") begin result = @client.verify(token) env["agentadmit.auth_type"] = "agent" env["agentadmit.user_id"] = result.user_id env["agentadmit.scopes"] = result.scopes env["agentadmit.connection_id"] = result.connection_id env["agentadmit.agent_label"] = result.agent_label env["agentadmit.presence"] = result.presence rescue InvalidTokenError => e return [401, { "Content-Type" => "application/json" }, [{ error: "invalid_token", error_description: e. }.to_json]] rescue IntrospectionError => e return [502, { "Content-Type" => "application/json" }, [{ error: "introspection_failed", error_description: e. }.to_json]] end end @app.call(env) end |