Skip to content

Feature/18 oauth service session api #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/shift/api/core.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
require "shift/api/core/middleware"
require "shift/api/core/request_id"
require "shift/api/core/errors"
require "shift/api/core/models/create_token_from_api_key"
module Shift
module Api
#
Expand Down
35 changes: 34 additions & 1 deletion lib/shift/api/core/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,19 @@ class Config
# defaults to {}
# Can also be an object responding to :call (i.e. a proc or lambda etc..)
# which must return a hash of headers to add
# @!attribute [rw] shift_api_key
# Used to authenticate to the API
# Defaults to nil
# @!attribute [rw] shift_account_reference
# Specifies which account to use when authenticating with the API
# Defaults to nil
# @!attribute [rw] oauth2_server_url
# The base URL for the authentication server
# Defaults to nil
# @!attribute [rw] oauth2_client_id
# The client id for use in oauth2 auth
# @!attribute [rw] oauth2_client_secret
# The client secret for use in oauth2 auth
# @!attribute [rw] timeout
# The connection read timeout in seconds. If data is not received in
# this time, an error is raised.
Expand All @@ -62,7 +75,7 @@ class Config
# The connection open timeout in seconds - i.e. if it takes longer than
# this to open connection, an error is raised
# defaults to :default (15 seconds)
attr_reader :shift_root_url, :logger, :before_request_handlers, :after_response_handlers, :adapter, :headers, :timeout, :open_timeout
attr_reader :shift_root_url, :logger, :before_request_handlers, :after_response_handlers, :adapter, :headers, :timeout, :open_timeout, :shift_api_key, :shift_account_reference, :oauth2_server_url, :oauth2_client_id, :oauth2_client_secret

def initialize
@before_request_handlers = []
Expand Down Expand Up @@ -99,6 +112,26 @@ def open_timeout=(open_timeout)
@open_timeout = open_timeout.tap { reconfigure }
end

def shift_api_key=(api_key)
@shift_api_key = api_key.tap { reconfigure }
end

def shift_account_reference=(account_reference)
@shift_account_reference = account_reference.tap { reconfigure }
end

def oauth2_server_url=(url)
@oauth2_server_url = url.tap { reconfigure }
end

def oauth2_client_id=(id)
@oauth2_client_id = id.tap { reconfigure }
end

def oauth2_client_secret=(secret)
@oauth2_client_secret = secret.tap { reconfigure }
end

# Registers a handler that is to be called before the request is made
# to the server.
# Multiple handlers get called in the sequence they were registered
Expand Down
50 changes: 50 additions & 0 deletions lib/shift/api/core/middleware/oauth2_token_exchanger.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
module Shift
module Api
module Core
module Middleware
#
# Faraday middleware to exchange an api key for an oauth2 token
# and store this in the request headers
#
class Oauth2TokenExchanger < ::Faraday::Middleware
def initialize(app, api_key:, account_reference:, oauth_server_url:, client_id:, client_secret:, token_create_service: ::Shift::Api::Core::CreateTokenFromApiKey)
self.app = app
self.api_key = api_key
self.account_reference = account_reference
self.oauth_server_url = oauth_server_url
self.token_create_service = token_create_service
self.client_id = client_id
self.client_secret = client_secret
end

# Fetches new token if required then call app
# @param [Faraday::Env] env The environment from faraday
def call(env)
return app.call(env) if has_valid_token?(env)
fetch_token(env)
app.call(env)
end

private

def has_valid_token?(env)
env.request_headers.key?('Authorization')
end

def connection
@connection ||= connection_class.new(site: oauth_server_url)

end

def fetch_token(env)
token = token_create_service.call client_id: client_id, scope: "all", api_key: api_key
#response = connection.run :post, "/oauth2/application_token", client_id: client_id, client_secret: client_secret, scope: "all", api_key: api_key
env.request_headers.merge! "Authorization" => "Bearer #{token.access_token}"
end

attr_accessor :app, :api_key, :account_reference, :oauth_server_url, :token_create_service, :client_id, :client_secret
end
end
end
end
end
15 changes: 14 additions & 1 deletion lib/shift/api/core/model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
require "shift/api/core/middleware/custom_headers"
require "shift/api/core/middleware/inspector"
require "shift/api/core/middleware/error_handler"
require "shift/api/core/middleware/oauth2_token_exchanger"
module Shift
module Api
module Core
Expand All @@ -25,6 +26,7 @@ def self.reconfigure(config)
configure_timeout(config)
configure_open_timeout(config)
configure_headers(config)
configure_token_exchanger(config)
reconfigure_subclasses(config)
end

Expand All @@ -49,7 +51,7 @@ def self.configure_adapter(config)

def self.configure_headers(config)
headers = config.headers
connection.use(::Shift::Api::Core::Middleware::CustomHeaders, headers: headers) unless headers.empty?
connection.use(::Shift::Api::Core::Middleware::CustomHeaders, headers: headers)
end

def self.configure_logger(config)
Expand Down Expand Up @@ -78,6 +80,17 @@ def self.configure_open_timeout(config)
connection.faraday.options.merge!(open_timeout: open_timeout.to_i) unless open_timeout == "default"
end

def self.configure_token_exchanger(config)
return if config.shift_api_key.nil?
connection.faraday.builder.insert_after(::Shift::Api::Core::Middleware::CustomHeaders,
::Shift::Api::Core::Middleware::Oauth2TokenExchanger,
api_key: config.shift_api_key,
account_reference: config.shift_account_reference,
oauth_server_url: config.oauth2_server_url,
client_id: config.oauth2_client_id,
client_secret: config.oauth2_client_secret)
end

def self.reconfigure_subclasses(config)
subclasses.each do |klass|
klass.reconfigure(config)
Expand Down
23 changes: 23 additions & 0 deletions lib/shift/api/core/models/create_token_from_api_key.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module Shift
module Api
module Core
class CreateTokenFromApiKey < Model
def self.configure_token_exchanger(config)
# Noop - this prevents this special model from using the token exchanger
end

def self.site=(url)
super(url.nil? ? url : url.gsub(/\/[^\/]*\/v1/, ""))
end

def self.table_name
"oauth2/application_token"
end

def self.call(attrs)
create(attrs)
end
end
end
end
end
1 change: 1 addition & 0 deletions shift-api-core.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,5 @@ Gem::Specification.new do |spec|
spec.add_development_dependency 'byebug'
spec.add_development_dependency 'webmock', '~> 2.3'
spec.add_runtime_dependency 'json_api_client', '~> 1.5'
spec.add_runtime_dependency "jwt-bouncer", "~> 0.1"
end
49 changes: 49 additions & 0 deletions spec/integration/token_exchange_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
require "spec_helper"
#
# Token Exchange Integration Spec
#
# The purpose of this spec is to prove that the gem will exchange an api key for a token
# when required before a request is made to the protected resources
RSpec.describe "token exchange integration", type: :api do
let(:account_reference) { SecureRandom.uuid }
let(:api_key) { SecureRandom.hex(16) }
let(:token_exchange_url) { "http://test.com/oauth2/application_token" }
before(:each) do
Shift::Api::Core::Config.new.batch_configure do |config|
config.shift_root_url = "http://test.com/anyservice/v1"
config.shift_api_key = api_key
config.shift_account_reference = account_reference
config.oauth2_server_url = token_exchange_url
end
end

before(:each) { stub_request(:post, "http://test.com/anyservice/v1/users").to_return(resource_stub_response) }

let(:resource_stub_response) do
{
body: {data: [{id: "1", type: "users", attributes: {name: "Shift User"}}]}.to_json,
status: 200,
headers: { "Content-Type": "application/vnd.api+json" }
}
end

let(:token_exchange_response) do
{
body: {data: {attributes: {token_type: "Bearer", expires_in: 60, access_token: "aaa"}}}.to_json,
status: 201,
headers: { "Content-Type": "application/vnd.api+json" }
}
end


class User < Shift::Api::Core::Model

end

it "should exchange the api key for a token and then access the resource" do
token_exchange_stub = stub_request(:post, token_exchange_url).to_return token_exchange_response
user = User.create(name: "Shift User")
expect(a_request(:post, token_exchange_url).with(headers: {"Content-Type" => "application/vnd.api+json", "Accept" => "application/vnd.api+json"})).to have_been_made
expect(a_request(:post, "http://test.com/anyservice/v1/users").with(headers: {"Authorization": "Bearer aaa"})).to have_been_made
end
end
1 change: 1 addition & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@
c.syntax = :expect
end
end
Dir[File.expand_path('../support/**/*.rb', __FILE__)].each { |f| require f }
56 changes: 56 additions & 0 deletions spec/support/jwt_bouncer_helpers.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
require 'jwt_bouncer/sign_request'

module JwtBouncerHelpers

def self.included(spec)
spec.after do
clear_authorization_header
end
end

def clear_authorization_header
set_jwt_bouncer_shared_secret

Shift::Api::Core.config do |config|
config.headers = { }
end
end

def generate_authorization_token(account_reference:, permissions:, shared_secret:, expiry: nil, actor: { type: 'user', id: 1, name: 'Jenkins' })
JwtBouncer::SignRequest.generate_token(
permissions: permissions,
actor: actor,
account_reference: account_reference,
shared_secret: shared_secret,
expiry: expiry
)
end

def decode_jwt_token(token, shared_secret:)
decoded = JwtBouncer::Token.decode(token, shared_secret)
decoded['permissions'] = JwtBouncer::Permissions.decompress(decoded['permissions'])
decoded['actor'] = decoded['actor'].with_indifferent_access
OpenStruct.new(decoded).freeze
end

def set_authorization_header(**options)
clear_authorization_header

token = generate_authorization_token(**options)

Shift::Api::Core.config do |config|
config.headers = { 'Authorization' => "Bearer #{token}" }
end
end

def set_jwt_bouncer_shared_secret
ENV['JWT_BOUNCER_SHARED_SECRET'] ||= 'Some shared secret'
end

end

RSpec.configure do |config|

config.include JwtBouncerHelpers

end
83 changes: 83 additions & 0 deletions spec/unit/shift/api/core/config_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,92 @@
config_instance.headers = headers
headers.merge!(unwanted: :key)
expect(subject.headers).to eql(key: :value)
end
end

describe "shift_api_key=" do
it "should have a default value of nil" do
expect(config_instance.shift_api_key).to be_nil
end

it "should request a reconfigure" do
config_instance.shift_api_key = SecureRandom.hex(16)
expect(mock_base_model).to have_received(:reconfigure).with(subject)
end

it "should store the value set" do
key = SecureRandom.hex(16)
config_instance.shift_api_key = key
expect(config_instance.shift_api_key).to eql key
end
end

describe "shift_account_reference=" do
it "should have a default value of nil" do
expect(config_instance.shift_account_reference).to be_nil
end

it "should request a reconfigure" do
config_instance.shift_account_reference = SecureRandom.uuid
expect(mock_base_model).to have_received(:reconfigure).with(subject)
end

it "should store the value set" do
account_reference = SecureRandom.uuid
config_instance.shift_account_reference = account_reference
expect(config_instance.shift_account_reference).to eql account_reference
end
end

describe "oauth2_server_url=" do
it "should have a default value of nil" do
expect(config_instance.oauth2_server_url).to be_nil
end

it "should request a reconfigure" do
config_instance.oauth2_server_url = "http://test.com"
expect(mock_base_model).to have_received(:reconfigure).with(subject)
end

it "should store the value set" do
url = "http://test.com"
config_instance.oauth2_server_url = url
expect(config_instance.oauth2_server_url).to eql url
end
end

describe "oauth2_client_id=" do
it "should have a default value of nil" do
expect(config_instance.oauth2_client_id).to be_nil
end

it "should request a reconfigure" do
config_instance.oauth2_client_id = "clientid"
expect(mock_base_model).to have_received(:reconfigure).with(subject)
end

it "should store the value set" do
client_id = "clientid"
config_instance.oauth2_client_id = client_id
expect(config_instance.oauth2_client_id).to eql client_id
end
end

describe "oauth2_client_secret=" do
it "should have a default value of nil" do
expect(config_instance.oauth2_client_secret).to be_nil
end

it "should request a reconfigure" do
config_instance.oauth2_client_secret = "secret"
expect(mock_base_model).to have_received(:reconfigure).with(subject)
end

it "should store the value set" do
client_secret = "secret"
config_instance.oauth2_client_secret = client_secret
expect(config_instance.oauth2_client_secret).to eql client_secret
end
end

describe "#before_request" do
Expand Down
Loading