From acf8425ed51f1219c89cbe702712b9c8202a58b6 Mon Sep 17 00:00:00 2001 From: "Paul B." Date: Mon, 25 Nov 2024 11:47:09 +0100 Subject: [PATCH] startup: load configuration (public key) at startup time (#10) This commit moves the parsing of the public key configuration during the loading of the proxy file (instead of during runtime while a request is made to the proxy). --- proxy_server.rb | 7 ++++--- spec/proxy_server_spec.rb | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/proxy_server.rb b/proxy_server.rb index f1b9792..958fb30 100644 --- a/proxy_server.rb +++ b/proxy_server.rb @@ -15,7 +15,9 @@ class ProxyServer < Sinatra::Base # set :logging, true # Secret key for JWT verification - PUBLIC_KEY = ENV.fetch("JWT_SIGNING_PUBLIC_KEY").gsub("\\n", "\n") + PUBLIC_KEY = OpenSSL::PKey.read( + ENV.fetch("JWT_SIGNING_PUBLIC_KEY").gsub("\\n", "\n") + ).freeze error JWT::ExpiredSignature do halt 401, {error: "Token has expired"}.to_json @@ -49,11 +51,10 @@ class ProxyServer < Sinatra::Base # Verify JWT token begin - public_key = OpenSSL::PKey.read(PUBLIC_KEY) # JWT.decode returns [payload, headers] @payload, _ = JWT.decode( token, - public_key, + ::ProxyServer::PUBLIC_KEY, true, # Verify signature { required_claims: ["exp", "verb", "path", "servers"], diff --git a/spec/proxy_server_spec.rb b/spec/proxy_server_spec.rb index b3afa68..907a561 100644 --- a/spec/proxy_server_spec.rb +++ b/spec/proxy_server_spec.rb @@ -384,4 +384,43 @@ def expect_json_body(k, v) end end end + + context "startup of ProxyServer" do + def load_config(writer, config) + fork do + begin + stub_const('ENV', config) + load File.expand_path("./proxy_server.rb"), true + writer.write "success!\n" + rescue + writer.write "fail: #{$!.message}\n" + end + writer.close + end + end + + context "with an incorrect configuration" do + it "should raise an error" do + # IO.pipe is used to share data between the forked processes + rd, writer = IO.pipe + load_config(writer, { 'JWT_SIGNING_PUBLIC_KEY' => 'OUPS-INCORRECT' }) + writer.close + + expect(rd.read).to eq("fail: Could not parse PKey\n") + end + end + + context "with an correct configuration" do + it "should load without any error" do + # IO.pipe is used to share data between the forked processes + rd, writer = IO.pipe + rsa_key = OpenSSL::PKey::RSA.new(2048) + load_config(writer, { 'JWT_SIGNING_PUBLIC_KEY' => rsa_key.public_key.to_pem }) + writer.close + + expect(rd.read).to eq("success!\n") + end + end + end + end