Commit b860827

mo khan <mo@mokhan.ca>
2025-03-06 19:06:21
refactor: connect twirp client/server components to rack
1 parent bad7655
Changed files (5)
bin/api
@@ -12,6 +12,7 @@ gemfile do
   gem "rack", "~> 3.0"
   gem "rackup", "~> 2.0"
   gem "securerandom", "~> 0.1"
+  gem "twirp", "~> 1.0"
   gem "webrick", "~> 1.0"
 end
 
@@ -79,12 +80,21 @@ class API
   def authorized?(request, permission)
     # TODO:: Check the JWT for the appropriate claim
     # Connect to the Authz RPC endpoint Ability.allowed?(subject, permission, resource)
-    client = ::Authx::Rpc::Ability::Stub.new('localhost:50051', :this_channel_is_insecure) # TODO:: memorize client
-    reply = client.allowed(::Authx::Rpc::AllowRequest.new(subject: "", permission: permission, resource: ""))
-    puts "***" * 10
-    puts reply.inspect
-    puts "***" * 10
-    reply&.result
+    if twirp?
+      client = ::Authx::Rpc::AbilityClient.new("http://idp.example.com:8080/twirp")
+      response = client.allowed(subject: "", permission: permission, resource: "")
+      puts response.inspect
+      response&.error&.nil? && response&.data&.result
+    else
+      client = ::Authx::Rpc::Ability::Stub.new('localhost:50051', :this_channel_is_insecure) # TODO:: memorize client
+      reply = client.allowed(::Authx::Rpc::AllowRequest.new(subject: "", permission: permission, resource: ""))
+      puts reply.inspect
+      reply&.result
+    end
+  end
+
+  def twirp?
+    true
   end
 
   def json_not_found
bin/idp
@@ -335,6 +335,11 @@ if __FILE__ == $0
   app = Rack::Builder.new do
     use Rack::CommonLogger
     use Rack::Reloader
+    map "/twirp" do
+      # https://github.com/arthurnn/twirp-ruby/wiki/Service-Handlers
+      run ::Authx::Rpc::AbilityService.new(::Authx::Rpc::AbilityHandler.new)
+    end
+
     run IdentityProvider.new
   end.to_app
 
bin/rpc
@@ -22,7 +22,7 @@ class ProjectPolicy < DeclarativePolicy::Base
   rule { owner }.enable :create_project
 end
 
-class AbilityHandler < ::Authx::Rpc::Ability::Service
+class RawAbilityHandler < ::Authx::Rpc::Ability::Service
   def allowed(request, _call)
     puts [request, _call].inspect
     GRPC.logger.info([request, _call].inspect)
@@ -47,5 +47,5 @@ server = GRPC::RpcServer.new
 server.add_http2_port(bind_addr, :this_port_is_insecure)
 GRPC.logger = Logger.new($stderr, level: :debug)
 GRPC.logger.info("... running insecurely on #{bind_addr}")
-server.handle(AbilityHandler.new)
+server.handle(RawAbilityHandler.new)
 server.run_till_terminated_or_interrupted([1, 'int', 'SIGQUIT'])
lib/authx/rpc/ability_handler.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module Authx
+  module Rpc
+    class AbilityHandler
+      def allowed(request, env)
+        puts [request, env].inspect
+
+        {
+          result: true
+        }
+      end
+    end
+  end
+end
lib/authx/rpc.rb
@@ -2,3 +2,4 @@
 
 require "authx/rpc/ability_pb"
 require "authx/rpc/ability_twirp"
+require "authx/rpc/ability_handler"