1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
|
#!/usr/bin/env ruby
require "bundler/inline"
gemfile do
source "https://rubygems.org"
gem "bcrypt", "~> 3.1"
gem "declarative_policy", "~> 1.0"
gem "erb", "~> 4.0"
gem "globalid", "~> 1.0"
gem "google-protobuf", "~> 3.0"
gem "rack", "~> 3.0"
gem "rack-session", "~> 2.0"
gem "rackup", "~> 2.0"
gem "saml-kit", "~> 1.0"
gem "twirp", "~> 1.0"
gem "webrick", "~> 1.0"
end
lib_path = Pathname.new(__FILE__).parent.parent.join('lib').realpath.to_s
$LOAD_PATH.unshift(lib_path) unless $LOAD_PATH.include?(lib_path)
require 'authx/rpc'
$scheme = ENV.fetch("SCHEME", "http")
$port = ENV.fetch("PORT", 8282).to_i
$host = ENV.fetch("HOST", "localhost:#{$port}")
module HTTPHelpers
def current_user?(request)
current_user(request)
end
def current_user(request)
::Authn::User.find(request.session[:user_id])
end
def default_headers
{
'X-Powered-By' => 'IdP'
}
end
def http_not_found
[404, default_headers, []]
end
def http_ok(headers = {}, body = nil)
[200, default_headers.merge(headers), [body]]
end
def http_redirect_to(location)
[302, { 'Location' => "http://idp.example.com:8080#{location}" }, []]
end
end
module Authn
class User
include ::BCrypt
class << self
def all
@all ||= 10.times.map do |n|
new(
id: SecureRandom.uuid,
username: "username#{n}",
email: "username#{n}@example.org",
password_digest: password_digest = ::BCrypt::Password.create("password#{n}")
)
end
end
def find(id)
all.find do |user|
user[:id] == id
end
end
def find_by_username(username)
all.find do |user|
user[:username] == username
end
end
def find_by_credentials(params = {})
user = find_by_username(params["username"])
user&.valid_password?(params["password"]) ? user : nil
end
end
attr_reader :id
def initialize(attributes)
@attributes = attributes
@id = self[:id]
end
def [](attribute)
@attributes.fetch(attribute.to_sym)
end
def name_id_for(name_id_format)
if name_id_format == Saml::Kit::Namespaces::EMAIL_ADDRESS
self[:email]
else
self[:id]
end
end
def create_access_token
::Authz::JWT.new(sub: to_global_id.to_s, iat: Time.now.to_i)
end
def assertion_attributes_for(request)
{
email: self[:email],
}
end
def valid_password?(entered_password)
::BCrypt::Password.new(self[:password_digest]) == entered_password
end
def to_global_id
::GlobalID.create(self, app: "example").to_s
end
end
class OnDemandRegistry < Saml::Kit::DefaultRegistry
def metadata_for(entity_id)
found = super(entity_id)
return found if found
register_url(entity_id, verify_ssl: false)
super(entity_id)
end
end
class SessionsController
include ::HTTPHelpers
def call(env)
request = Rack::Request.new(env)
case request.request_method
when Rack::GET
case request.path
when '/sessions/new'
request.session.delete(:user_id)
return get_login(request)
end
when Rack::POST
case request.path
when '/sessions'
if (user = User.find_by_credentials(request.params))
request.session[:user_id] = user[:id]
path = request.params["redirect_back"] ? request.params["redirect_back"] : "/"
return http_redirect_to(path)
else
return http_redirect_to("/sessions/new")
end
when '/sessions/delete'
request.session.delete(:user_id)
return http_redirect_to('/')
end
end
http_not_found
end
private
def get_login(request)
template = <<~ERB
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<form id="login-form" action="/sessions" method="post">
<input type="input" placeholder="Username" id="username" name="username" value="" />
<input type="hidden" name="redirect_back" value="<%= request.params["redirect_back"] %>" />
<input type="password" placeholder="Password" id="password" name="password" value="" />
<input type="submit" id="login-button" value="Login" />
</form>
</body>
</html>
ERB
erb = ERB.new(template, trim_mode: '-')
html = erb.result(binding)
[200, { 'Content-Type' => "text/html" }, [html]]
end
end
class SAMLController
include ::HTTPHelpers
def initialize(scheme, host)
Saml::Kit.configure do |x|
x.entity_id = "#{$scheme}://#{$host}/saml/metadata.xml"
x.registry = OnDemandRegistry.new
x.logger = Logger.new("/dev/stderr")
end
@saml_metadata = Saml::Kit::Metadata.build do |builder|
builder.contact_email = 'hi@example.com'
builder.organization_name = "Acme, Inc"
builder.organization_url = "#{scheme}://#{host}"
builder.build_identity_provider do |x|
x.add_single_sign_on_service("#{scheme}://#{host}/saml/new", binding: :http_post)
x.name_id_formats = [Saml::Kit::Namespaces::PERSISTENT, Saml::Kit::Namespaces::EMAIL_ADDRESS]
x.attributes << :email
end
end
end
def call(env)
request = Rack::Request.new(env)
case request.request_method
when Rack::GET
case request.path
when "/saml/continue"
if current_user?(request)
saml_params = request.session[:saml_params]
return saml_post_back(request, current_user(request), saml_params)
else
return http_redirect_to("/sessions/new?redirect_back=/saml/continue")
end
when "/saml/metadata.xml"
return http_ok(
{ 'Content-Type' => "application/samlmetadata+xml" },
saml_metadata.to_xml(pretty: true)
)
end
when Rack::POST
case request.path
when "/saml/new"
saml_params = saml_params_from(request)
if current_user?(request)
return saml_post_back(request, current_user(request), saml_params)
else
request.session[:saml_params] = saml_params
return http_redirect_to("/sessions/new?redirect_back=/saml/continue")
end
end
end
http_not_found
end
private
attr_reader :saml_metadata
def saml_post_back(request, user, saml_params)
saml_request = binding_for(request).deserialize(saml_params)
@builder = nil
url, saml_params = saml_request.response_for(
user,
binding: :http_post,
relay_state: saml_params[:RelayState]
) { |builder| @builder = builder }
template = <<~ERB
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<h2>Recieved SAML Request</h2>
<textarea readonly="readonly" disabled="disabled" cols=225 rows=6><%=- saml_request.to_xml(pretty: true) -%></textarea>
<h2>Sending SAML Response (IdP -> SP)</h2>
<textarea readonly="readonly" disabled="disabled" cols=225 rows=40><%=- @builder.build.to_xml(pretty: true) -%></textarea>
<form id="postback-form" action="<%= url %>" method="post">
<%- saml_params.each do |(key, value)| -%>
<input type="hidden" name="<%= key %>" value="<%= value %>" />
<%- end -%>
<input id="submit-button" type="submit" value="Submit" />
</form>
</body>
</html>
ERB
erb = ERB.new(template, trim_mode: '-')
html = erb.result(binding)
[200, { 'Content-Type' => "text/html" }, [html]]
end
def saml_params_from(request)
if request.post?
{
"SAMLRequest" => request.params["SAMLRequest"],
"RelayState" => request.params["RelayState"],
}
else
query_string = request.query_string
on = query_string.include?("&") ? "&" : "&"
Hash[query_string.split(on).map { |x| x.split("=", 2) }].symbolize_keys
end
end
def binding_for(request)
Saml::Kit::Bindings::HttpPost.new(location: "#{$scheme}://#{$host}/saml/new")
end
end
end
class Organization
class << self
def find(id)
new
end
end
end
DeclarativePolicy.configure do
name_transformation do |name|
"::Authz::#{name}Policy"
end
end
module Authz
class OrganizationPolicy < DeclarativePolicy::Base
condition(:owner) { true }
rule { owner }.enable :read_project
rule { owner }.enable :create_project
end
class JWT
attr_reader :claims
def initialize(claims)
@claims = claims
end
def to_jwt
[
Base64.strict_encode64(JSON.generate(alg: "none")),
Base64.strict_encode64(JSON.generate(claims)),
""
].join(".")
end
end
module Rpc
class Ability
def allowed(request, env)
{
result: can?(request)
}
end
private
def can?(request)
subject = subject_of(request.subject)
resource = resource_from(request.resource)
permission = request.permission.to_sym
policy = DeclarativePolicy.policy_for(subject, resource)
policy.can?(permission)
rescue StandardError => error
puts error.inspect
false
end
def subject_of(token)
_header, claims, _signature = from_jwt(token)
claims[:sub]
end
def resource_from(global_id)
GlobalID::Locator.locate(global_id)
end
# TODO:: validate signature
def from_jwt(token)
token
.split('.', 3)
.map { |x| JSON.parse(Base64.strict_decode64(x), symbolize_names: true) rescue {} }
end
end
end
class OAuthController
include ::HTTPHelpers
def call(env)
request = Rack::Request.new(env)
case request.request_method
when Rack::GET
case request.path
when "/oauth/authorize/continue"
if current_user?(request)
return get_authorize(request.session[:oauth_params])
end
when "/oauth/authorize" # RFC-6749
oauth_params = request.params.slice('client_id', 'scope', 'redirect_uri', 'response_mode', 'response_type', 'state', 'code_challenge_method', 'code_challenge')
if current_user?(request)
return get_authorize(oauth_params)
else
request.session[:oauth_params] = oauth_params
return http_redirect_to("/sessions/new?redirect_back=/oauth/authorize/continue")
end
else
return http_not_found
end
when Rack::POST
case request.path
when "/oauth/authorize" # RFC-6749
return post_authorize(request)
when "/oauth/token" # RFC-6749
# TODO:: Look up authorization grant by (code, saml_assertion)
user = Authn::User.new(id: SecureRandom.uuid)
return [200, { 'Content-Type' => "application/json" }, [JSON.pretty_generate({
access_token: user.create_access_token.to_jwt,
token_type: "Bearer",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
expires_in: 3600,
refresh_token: SecureRandom.hex(32)
})]]
when "/oauth/revoke" # RFC-7009
# TODO:: Revoke the JWT token and make it ineligible for usage
return http_not_found
else
return http_not_found
end
end
http_not_found
end
def get_authorize(oauth_params)
template = <<~ERB
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<h2>Authorize?</h2>
<form id="authorize-form" action="/oauth/authorize" method="post">
<input type="hidden" name="client_id" value="<%= oauth_params['client_id'] %>" />
<input type="hidden" name="scope" value="<%= oauth_params['scope'] %>" />
<input type="hidden" name="redirect_uri" value="<%= oauth_params['redirect_uri'] %>" />
<input type="hidden" name="response_mode" value="<%= oauth_params['response_mode'] %>" />
<input type="hidden" name="response_type" value="<%= oauth_params['response_type'] %>" />
<input type="hidden" name="state" value="<%= oauth_params['state'] %>" />
<input type="hidden" name="code_challenge_method" value="<%= oauth_params['code_challenge_method'] %>" />
<input type="hidden" name="code_challenge" value="<%= oauth_params['code_challenge'] %>" />
<input id="submit-button" type="submit" value="Submit" />
</form>
</body>
</html>
ERB
html = ERB.new(template, trim_mode: '-').result(binding)
[200, { 'Content-Type' => "text/html" }, [html]]
end
def post_authorize(request)
params = request.params.slice('client_id', 'redirect_uri', 'response_type', 'response_mode', 'state', 'code_challenge_method', 'code_challenge', 'scope')
case params['response_type']
when 'code'
case params['response_mode']
when 'fragment'
return [302, { 'Location' => "#{params['redirect_uri']}#code=#{SecureRandom.uuid}&state=#{params['state']}" }, []]
when 'query'
return [302, { 'Location' => "#{params['redirect_uri']}?code=#{SecureRandom.uuid}&state=#{params['state']}" }, []]
else
# TODO:: form post
end
when 'token'
return http_not_found
else
return http_not_found
end
end
end
end
class IdentityProvider
include ::HTTPHelpers
def call(env)
request = Rack::Request.new(env)
case request.request_method
when Rack::GET
case request.path
when '/'
if current_user?(request)
return get_dashboard(request)
else
return http_redirect_to("/sessions/new")
end
when '/.well-known/openid-configuration'
return openid_metadata
when '/.well-known/oauth-authorization-server'
return oauth_metadata
when '/.well-known/webfinger' # RFC-7033
return http_not_found
else
return http_not_found
end
end
http_not_found
end
private
def get_dashboard(request)
template = <<~ERB
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<h1> Hello, <%= current_user(request)[:username] %></h1>
<form action="/sessions/delete" method="post">
<input type="submit" value="logout" />
</form>
</body>
</html>
ERB
erb = ERB.new(template, trim_mode: '-')
html = erb.result(binding)
[200, { 'Content-Type' => "text/html" }, [html]]
end
# GET /.well-known/oauth-authorization-server
def oauth_metadata
[200, { 'Content-Type' => "application/json" }, [JSON.pretty_generate({
issuer: "#{$scheme}://#{$host}/.well-known/oauth-authorization-server",
authorization_endpoint: "#{$scheme}://#{$host}/oauth/authorize",
token_endpoint: "#{$scheme}://#{$host}/oauth/token",
jwks_uri: "", # RFC-7517
registration_endpoint: "", # RFC-7591
scopes_supported: ["openid", "profile", "email"],
response_types_supported: ["code", "code id_token", "id_token", "token id_token"],
response_modes_supported: ["query", "fragment", "form_post"],
grant_types_supported: ["authorization_code", "implicit"], # RFC-7591
token_endpoint_auth_methods_supported: ["client_secret_basic"], # RFC-7591
token_endpoint_auth_signing_alg_values_supported: ["RS256"],
service_documentation: "",
ui_locales_supported: ["en-US"],
op_policy_uri: "",
op_tos_uri: "",
revocation_endpoint: "#{$scheme}://#{$host}/oauth/revoke", # RFC-7009
revocation_endpoint_auth_methods_supported: ["client_secret_basic"],
revocation_endpoint_auth_signing_alg_values_supported: ["RS256"],
introspection_endpoint: "#{$scheme}://#{$host}/oauth/introspect", # RFC-7662
introspection_endpoint_auth_methods_supported: ["client_secret_basic"],
introspection_endpoint_auth_signing_alg_values_supported: ["RS256"],
code_challenge_methods_supported: [], # RFC-7636
})]]
end
# GET /.well-known/openid-configuration
def openid_metadata
[200, { 'Content-Type' => "application/json" }, [JSON.pretty_generate({
issuer: "#{$scheme}://#{$host}/.well-known/oauth-authorization-server",
authorization_endpoint: "#{$scheme}://#{$host}/oauth/authorize",
token_endpoint: "#{$scheme}://#{$host}/oauth/token",
userinfo_endpoint: "#{$scheme}://#{$host}/oidc/user/",
jwks_uri: "", # RFC-7517
registration_endpoint: nil,
scopes_supported: ["openid", "profile", "email"],
response_types_supported: ["code", "code id_token", "id_token", "token id_token"],
response_modes_supported: ["query", "fragment", "form_post"],
grant_types_supported: ["authorization_code", "implicit"], # RFC-7591
acr_values_supported: [],
subject_types_supported: ["pairwise", "public"],
id_token_signing_alg_values_supported: ["RS256"],
id_token_encryption_alg_values_supported: [],
id_token_encryption_enc_values_supported: [],
userinfo_signing_alg_values_supported: ["RS256"],
userinfo_encryption_alg_values_supported: [],
userinfo_encryption_enc_values_supported: [],
request_object_signing_alg_values_supported: ["none", "RS256"],
request_object_encryption_alg_values_supported: [],
request_object_encryption_enc_values_supported: [],
token_endpoint_auth_methods_supported: ["client_secret_post", "client_secret_basic", "client_secret_jwt", "private_key_jwt"],
token_endpoint_auth_signing_alg_values_supported: [],
display_values_supported: [],
claim_types_supported: ["normal", "aggregated", "distributed"],
claims_supported: [
"acr",
"auth_time",
"email",
"email_verified",
"family_name",
"given_name",
"iss",
"locale",
"name",
"nickname",
"picture",
"profile",
"sub",
"website"
],
service_documentation: nil,
claims_locales_supported: [],
ui_locales_supported: ["en-US"],
claims_parameter_supported: false,
request_parameter_supported: false,
request_uri_paramater_supported: false,
require_request_uri_registration: false,
op_policy_uri: "",
op_tos_uri: "",
})]]
end
end
if __FILE__ == $0
app = Rack::Builder.new do
use Rack::CommonLogger
use Rack::Reloader
use Rack::Session::Cookie, { domain: $host.split(":", 2)[0], path: "/", secret: SecureRandom.hex(64) }
map "/twirp" do
# https://github.com/arthurnn/twirp-ruby/wiki/Service-Handlers
run ::Authx::Rpc::AbilityService.new(::Authz::Rpc::Ability.new)
end
map "/oauth" do
run ::Authz::OAuthController.new
end
map "/saml" do
run Authn::SAMLController.new($scheme, $host)
end
map "/sessions" do
run Authn::SessionsController.new
end
run IdentityProvider.new
end.to_app
Rackup::Server.start(app: app, Port: $port)
end
|