Skip to content

Commit

Permalink
startup: load configuration (public key) at startup time (#10)
Browse files Browse the repository at this point in the history
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).
  • Loading branch information
paulRbr authored Nov 25, 2024
1 parent b608eef commit acf8425
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
7 changes: 4 additions & 3 deletions proxy_server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"],
Expand Down
39 changes: 39 additions & 0 deletions spec/proxy_server_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit acf8425

Please sign in to comment.