masks 0.12.2 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +26 -0
- data/README.md +29 -0
- data/app/controllers/masks/rails/logouts_controller.rb +3 -3
- data/app/controllers/masks/rails/sessions_controller.rb +4 -26
- data/lib/masks/client/claims.rb +4 -9
- data/lib/masks/client/delegations.rb +16 -14
- data/lib/masks/client/device.rb +1 -1
- data/lib/masks/client/embedded.rb +3 -3
- data/lib/masks/client/enrollment.rb +1 -1
- data/lib/masks/client/errors.rb +72 -32
- data/lib/masks/client/failures.rb +81 -0
- data/lib/masks/client/fake.rb +732 -0
- data/lib/masks/client/handshake.rb +2 -2
- data/lib/masks/client/http.rb +15 -15
- data/lib/masks/client/id_token.rb +35 -0
- data/lib/masks/client/introspection.rb +2 -2
- data/lib/masks/client/issuer.rb +4 -7
- data/lib/masks/client/logout.rb +6 -12
- data/lib/masks/client/proof.rb +23 -22
- data/lib/masks/client/rack.rb +3 -3
- data/lib/masks/client/registration.rb +1 -1
- data/lib/masks/client/resource.rb +12 -13
- data/lib/masks/client/session.rb +16 -10
- data/lib/masks/client/tokens.rb +1 -1
- data/lib/masks/client/transport.rb +1 -1
- data/lib/masks/client/verifier.rb +53 -17
- data/lib/masks/client.rb +3 -0
- data/lib/masks/rails/authentication.rb +7 -7
- data/lib/masks/rails/cache.rb +6 -8
- data/lib/masks/rails/configuration.rb +5 -1
- data/lib/masks/rails/protected_resource.rb +8 -6
- data/lib/masks/version.rb +1 -1
- metadata +5 -2
|
@@ -0,0 +1,732 @@
|
|
|
1
|
+
require "masks/client"
|
|
2
|
+
require "monitor"
|
|
3
|
+
require "socket"
|
|
4
|
+
|
|
5
|
+
module Masks
|
|
6
|
+
module Client
|
|
7
|
+
class Fake
|
|
8
|
+
ALGORITHM = "RS256".freeze
|
|
9
|
+
UPSTREAM = "urn:masks:params:oauth:token-type:upstream_access_token".freeze
|
|
10
|
+
TENANT = { "uuid" => "t-1", "subdomain" => "demo", "name" => "Demo" }.freeze
|
|
11
|
+
SCOPE = "openid profile email".freeze
|
|
12
|
+
AUDIENCE = "https://app.test/mcp".freeze
|
|
13
|
+
PNG = "\x89PNG fake photo".b.freeze
|
|
14
|
+
REASONS = { 200 => "OK", 201 => "Created", 204 => "No Content", 302 => "Found", 400 => "Bad Request",
|
|
15
|
+
401 => "Unauthorized", 404 => "Not Found", 503 => "Service Unavailable" }.freeze
|
|
16
|
+
PEOPLE = {
|
|
17
|
+
"ada" => {
|
|
18
|
+
"name" => "Ada Lovelace",
|
|
19
|
+
"preferred_username" => "ada",
|
|
20
|
+
"email" => "ada@example.com",
|
|
21
|
+
"email_verified" => true,
|
|
22
|
+
"orgs" => [
|
|
23
|
+
{ "id" => "o-1", "key" => "acme", "name" => "Acme", "role" => "owner" },
|
|
24
|
+
{ "id" => "o-2", "key" => "globex", "name" => "Globex", "role" => "member" }
|
|
25
|
+
]
|
|
26
|
+
},
|
|
27
|
+
"bob" => {
|
|
28
|
+
"name" => "Bob",
|
|
29
|
+
"preferred_username" => "bob",
|
|
30
|
+
"email" => "bob@example.com",
|
|
31
|
+
"email_verified" => false,
|
|
32
|
+
"orgs" => [ { "id" => "o-1", "key" => "acme", "name" => "Acme", "role" => "member" } ]
|
|
33
|
+
}
|
|
34
|
+
}.freeze
|
|
35
|
+
|
|
36
|
+
Registered = Struct.new(:method, :secret, :jwks, :scope, :metadata, keyword_init: true)
|
|
37
|
+
|
|
38
|
+
attr_reader :key, :kid, :port, :tenant, :people, :requests, :received, :clients, :codes, :grants, :initial,
|
|
39
|
+
:registrations, :enrolled, :revoked, :handshakes, :exchanges, :authorized
|
|
40
|
+
attr_accessor :audience, :scope, :lifetime, :auth_time, :pending, :nonce, :foreign_uri, :backchannel,
|
|
41
|
+
:photo, :photo_type
|
|
42
|
+
|
|
43
|
+
def self.start(**options)
|
|
44
|
+
new(**options)
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def initialize(tenant: TENANT, audience: AUDIENCE, scope: SCOPE)
|
|
48
|
+
@key = OpenSSL::PKey::RSA.generate(2048)
|
|
49
|
+
@kid = SecureRandom.uuid
|
|
50
|
+
@tenant = tenant
|
|
51
|
+
@audience = audience
|
|
52
|
+
@scope = scope
|
|
53
|
+
@lifetime = 3600
|
|
54
|
+
@pending = 0
|
|
55
|
+
@slowed = false
|
|
56
|
+
@foreign_uri = false
|
|
57
|
+
@backchannel = true
|
|
58
|
+
@photo = PNG
|
|
59
|
+
@photo_type = "image/png"
|
|
60
|
+
@people = PEOPLE.transform_values { |person| JSON.parse(JSON.generate(person)) }
|
|
61
|
+
@requests = Hash.new(0)
|
|
62
|
+
@received = []
|
|
63
|
+
@overrides = {}
|
|
64
|
+
@clients = {}
|
|
65
|
+
@codes = {}
|
|
66
|
+
@grants = {}
|
|
67
|
+
@initial = {}
|
|
68
|
+
@registrations = {}
|
|
69
|
+
@enrolled = {}
|
|
70
|
+
@assertions = {}
|
|
71
|
+
@revoked = []
|
|
72
|
+
@handshakes = []
|
|
73
|
+
@exchanges = []
|
|
74
|
+
@lock = Monitor.new
|
|
75
|
+
@server = TCPServer.new("127.0.0.1", 0)
|
|
76
|
+
@port = @server.addr[1]
|
|
77
|
+
@thread = Thread.new { serve }
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def url
|
|
81
|
+
"http://127.0.0.1:#{port}"
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
def stop
|
|
85
|
+
@thread.kill
|
|
86
|
+
@server.close
|
|
87
|
+
rescue IOError
|
|
88
|
+
nil
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
def count(path)
|
|
92
|
+
@lock.synchronize { @requests[path] }
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def last(path)
|
|
96
|
+
@lock.synchronize { @received.reverse.find { |held| held[:path] == path } }
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def override(path, body)
|
|
100
|
+
@lock.synchronize { @overrides[path] = body }
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def add(client_id, method: "client_secret_basic", secret: nil, jwks: nil, scope: nil)
|
|
104
|
+
jwks = jwks.jwks if jwks.is_a?(Key)
|
|
105
|
+
|
|
106
|
+
@lock.synchronize do
|
|
107
|
+
@clients[client_id] = Registered.new(method: method, secret: secret, jwks: jwks || { "keys" => [] },
|
|
108
|
+
scope: scope, metadata: {})
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def person(subject)
|
|
113
|
+
held = @people[subject] || {}
|
|
114
|
+
|
|
115
|
+
{ "sub" => subject }.merge(held).merge(
|
|
116
|
+
"tenant" => tenant,
|
|
117
|
+
"masks:avatars" => { "photo" => "#{url}/avatars/#{subject}/photo", "identicon" => "#{url}/avatars/#{subject}/identicon" }
|
|
118
|
+
)
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
def jwks
|
|
122
|
+
{ "keys" => [ public_jwk ] }
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
def public_jwk
|
|
126
|
+
JWT::JWK.new(key, { kid: kid, use: "sig", alg: ALGORITHM }).export
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
def discovery
|
|
130
|
+
{
|
|
131
|
+
"issuer" => url,
|
|
132
|
+
"tenant" => tenant,
|
|
133
|
+
"authorization_endpoint" => "#{url}/authorize",
|
|
134
|
+
"token_endpoint" => "#{url}/token",
|
|
135
|
+
"userinfo_endpoint" => "#{url}/userinfo",
|
|
136
|
+
"jwks_uri" => "#{url}/.well-known/jwks.json",
|
|
137
|
+
"registration_endpoint" => "#{url}/register",
|
|
138
|
+
"enrollment_endpoint" => "#{url}/enrollments",
|
|
139
|
+
"device_authorization_endpoint" => "#{url}/device_authorization",
|
|
140
|
+
"handshake_endpoint" => "#{url}/handshake",
|
|
141
|
+
"revocation_endpoint" => "#{url}/revoke",
|
|
142
|
+
"introspection_endpoint" => "#{url}/introspect",
|
|
143
|
+
"end_session_endpoint" => "#{url}/logout",
|
|
144
|
+
"authorization_response_iss_parameter_supported" => true,
|
|
145
|
+
"backchannel_logout_supported" => backchannel
|
|
146
|
+
}
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def sign(claims, kid: self.kid, key: self.key, typ: "JWT")
|
|
150
|
+
JWT.encode(claims, key, ALGORITHM, { kid: kid, typ: typ })
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
def access_token(subject: "ada", scope: self.scope, audience: self.audience, expires_in: lifetime, **extra)
|
|
154
|
+
sign({
|
|
155
|
+
"iss" => url,
|
|
156
|
+
"sub" => subject,
|
|
157
|
+
"aud" => audience,
|
|
158
|
+
"exp" => Time.now.to_i + expires_in,
|
|
159
|
+
"iat" => Time.now.to_i,
|
|
160
|
+
"jti" => SecureRandom.uuid,
|
|
161
|
+
"scope" => scope,
|
|
162
|
+
"tenant" => tenant
|
|
163
|
+
}.merge(extra.transform_keys(&:to_s)).compact, typ: Verifier::ACCESS_TOKEN)
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
def logout_token(client_id, subject: "ada", sid: nil, **changes)
|
|
167
|
+
now = Time.now.to_i
|
|
168
|
+
claims = {
|
|
169
|
+
"iss" => url,
|
|
170
|
+
"aud" => client_id,
|
|
171
|
+
"iat" => now,
|
|
172
|
+
"exp" => now + 120,
|
|
173
|
+
"jti" => SecureRandom.uuid,
|
|
174
|
+
"events" => { Logout::EVENT => {} },
|
|
175
|
+
"sub" => subject,
|
|
176
|
+
"sid" => sid
|
|
177
|
+
}.merge(changes.transform_keys(&:to_s))
|
|
178
|
+
|
|
179
|
+
sign(claims.compact, typ: Verifier::LOGOUT_TOKEN)
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
def authorize(target, subject: "ada", organization: nil, error: nil, state: nil, iss: nil)
|
|
183
|
+
pairs = URI.decode_www_form(URI.parse(target).query.to_s)
|
|
184
|
+
asked = pairs.to_h
|
|
185
|
+
back = URI.parse(asked.fetch("redirect_uri"))
|
|
186
|
+
|
|
187
|
+
@lock.synchronize do
|
|
188
|
+
@authorized = asked
|
|
189
|
+
|
|
190
|
+
if error
|
|
191
|
+
answer = [ [ "error", error ], [ "error_description", "declined in the fake" ], [ "state", asked["state"] ] ]
|
|
192
|
+
else
|
|
193
|
+
code = SecureRandom.hex(16)
|
|
194
|
+
@codes[code] = {
|
|
195
|
+
"client_id" => asked["client_id"],
|
|
196
|
+
"redirect_uri" => asked["redirect_uri"],
|
|
197
|
+
"challenge" => asked["code_challenge"],
|
|
198
|
+
"nonce" => asked["nonce"],
|
|
199
|
+
"scope" => asked["scope"].to_s,
|
|
200
|
+
"resource" => pairs.select { |name, _| name == "resource" }.map(&:last),
|
|
201
|
+
"organization" => organization || asked["organization"],
|
|
202
|
+
"subject" => subject,
|
|
203
|
+
"sid" => "sid-#{SecureRandom.hex(8)}"
|
|
204
|
+
}
|
|
205
|
+
answer = [ [ "code", code ], [ "state", state || asked["state"] ], [ "iss", iss || url ] ]
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
back.query = [ back.query, URI.encode_www_form(answer) ].compact.join("&")
|
|
209
|
+
back.to_s
|
|
210
|
+
end
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
def handshake(target, error: nil, state: nil, iss: nil)
|
|
214
|
+
asked = URI.decode_www_form(URI.parse(target).query.to_s).to_h
|
|
215
|
+
back = URI.parse(asked.fetch("return_to"))
|
|
216
|
+
|
|
217
|
+
@lock.synchronize do
|
|
218
|
+
@handshakes << asked
|
|
219
|
+
|
|
220
|
+
if error
|
|
221
|
+
answer = [ [ "error", error ], [ "error_description", "declined in the fake" ], [ "state", asked["state"] ] ]
|
|
222
|
+
else
|
|
223
|
+
token = SecureRandom.hex(16)
|
|
224
|
+
@initial[token] = "app-#{SecureRandom.hex(6)}"
|
|
225
|
+
answer = [ [ "initial_access_token", token ], [ "iss", iss || url ], [ "state", state || asked["state"] ] ]
|
|
226
|
+
end
|
|
227
|
+
|
|
228
|
+
back.query = [ back.query, URI.encode_www_form(answer) ].compact.join("&")
|
|
229
|
+
back.to_s
|
|
230
|
+
end
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
private
|
|
234
|
+
|
|
235
|
+
def serve
|
|
236
|
+
loop do
|
|
237
|
+
socket = @server.accept
|
|
238
|
+
Thread.new { respond(socket) }
|
|
239
|
+
end
|
|
240
|
+
rescue IOError, Errno::EBADF
|
|
241
|
+
nil
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
def respond(socket)
|
|
245
|
+
line = socket.gets.to_s
|
|
246
|
+
headers = {}
|
|
247
|
+
|
|
248
|
+
while (header = socket.gets) && header.strip != ""
|
|
249
|
+
name, value = header.split(":", 2)
|
|
250
|
+
headers[name.to_s.strip.downcase] = value.to_s.strip
|
|
251
|
+
end
|
|
252
|
+
|
|
253
|
+
method, path = line.split(" ")
|
|
254
|
+
length = headers["content-length"].to_i
|
|
255
|
+
raw = length.positive? ? socket.read(length).to_s : ""
|
|
256
|
+
pairs = form_pairs(raw)
|
|
257
|
+
request = { method: method, path: path, headers: headers, body: parse(raw, pairs), pairs: pairs }
|
|
258
|
+
|
|
259
|
+
status, body, extra = @lock.synchronize do
|
|
260
|
+
@requests[path] += 1
|
|
261
|
+
@received << request
|
|
262
|
+
answer(request)
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
socket.print rendered(status, body, extra)
|
|
266
|
+
ensure
|
|
267
|
+
socket.close rescue nil
|
|
268
|
+
end
|
|
269
|
+
|
|
270
|
+
def rendered(status, body, extra)
|
|
271
|
+
extra = Hash(extra)
|
|
272
|
+
typed = extra.keys.any? { |name| name.to_s.casecmp?("content-type") }
|
|
273
|
+
payload = body.is_a?(String) ? body : JSON.generate(body)
|
|
274
|
+
lines = [ "HTTP/1.1 #{status} #{REASONS.fetch(status, 'OK')}" ]
|
|
275
|
+
|
|
276
|
+
lines << "Content-Type: application/json" unless typed || body.nil?
|
|
277
|
+
lines << "Content-Length: #{body.nil? ? 0 : payload.bytesize}"
|
|
278
|
+
lines << "Connection: close"
|
|
279
|
+
extra.each { |name, value| lines << "#{name}: #{value}" }
|
|
280
|
+
|
|
281
|
+
(lines + [ "", body.nil? ? "" : payload ]).join("\r\n")
|
|
282
|
+
end
|
|
283
|
+
|
|
284
|
+
def form_pairs(raw)
|
|
285
|
+
URI.decode_www_form(raw)
|
|
286
|
+
rescue ArgumentError
|
|
287
|
+
[]
|
|
288
|
+
end
|
|
289
|
+
|
|
290
|
+
def parse(raw, pairs)
|
|
291
|
+
JSON.parse(raw)
|
|
292
|
+
rescue JSON::ParserError
|
|
293
|
+
pairs.each_with_object({}) { |(name, value), held| held[name] = value }
|
|
294
|
+
rescue StandardError
|
|
295
|
+
{}
|
|
296
|
+
end
|
|
297
|
+
|
|
298
|
+
def answer(request)
|
|
299
|
+
return canned(request) if @overrides.key?(request[:path])
|
|
300
|
+
|
|
301
|
+
path, query = request[:path].to_s.split("?", 2)
|
|
302
|
+
|
|
303
|
+
case [ request[:method], path ]
|
|
304
|
+
when [ "GET", "/.well-known/openid-configuration" ] then [ 200, discovery ]
|
|
305
|
+
when [ "GET", "/.well-known/jwks.json" ] then [ 200, jwks ]
|
|
306
|
+
when [ "POST", "/token" ] then token(request)
|
|
307
|
+
when [ "POST", "/device_authorization" ] then device(request)
|
|
308
|
+
when [ "POST", "/revoke" ] then revoke(request)
|
|
309
|
+
when [ "POST", "/introspect" ] then introspect(request)
|
|
310
|
+
when [ "POST", "/register" ] then register(request)
|
|
311
|
+
when [ "POST", "/enrollments" ] then enroll(request)
|
|
312
|
+
when [ "GET", "/userinfo" ] then userinfo(request)
|
|
313
|
+
when [ "GET", "/authorize" ] then [ 302, nil, { "Location" => authorize("#{url}#{request[:path]}") } ]
|
|
314
|
+
when [ "GET", "/handshake" ] then [ 302, nil, { "Location" => handshake("#{url}#{request[:path]}") } ]
|
|
315
|
+
when [ "GET", "/logout" ] then end_session(query)
|
|
316
|
+
else routed(request, path)
|
|
317
|
+
end
|
|
318
|
+
end
|
|
319
|
+
|
|
320
|
+
def routed(request, path)
|
|
321
|
+
if path.start_with?("/register/")
|
|
322
|
+
registration(request, URI.decode_www_form_component(path.delete_prefix("/register/")))
|
|
323
|
+
elsif request[:method] == "DELETE" && path.start_with?("/enrollments/")
|
|
324
|
+
unenroll(request, URI.decode_www_form_component(path.delete_prefix("/enrollments/")))
|
|
325
|
+
elsif request[:method] == "GET" && path.start_with?("/avatars/")
|
|
326
|
+
avatar(request)
|
|
327
|
+
else
|
|
328
|
+
[ 404, { "error" => "not_found" } ]
|
|
329
|
+
end
|
|
330
|
+
end
|
|
331
|
+
|
|
332
|
+
def canned(request)
|
|
333
|
+
found = @overrides[request[:path]]
|
|
334
|
+
found = found.call(request[:body]) if found.respond_to?(:call)
|
|
335
|
+
status, found, extra = found.is_a?(Array) ? found : [ found ? 200 : 404, found ]
|
|
336
|
+
|
|
337
|
+
[ status, found || { "error" => "not_found" }, extra ]
|
|
338
|
+
end
|
|
339
|
+
|
|
340
|
+
def refused(status, code, extra = nil)
|
|
341
|
+
[ status, { "error" => code, "error_description" => "#{code} from the fake" }, extra ]
|
|
342
|
+
end
|
|
343
|
+
|
|
344
|
+
def resources(request)
|
|
345
|
+
request[:pairs].select { |name, _| name == "resource" }.map(&:last)
|
|
346
|
+
end
|
|
347
|
+
|
|
348
|
+
def decoded(token)
|
|
349
|
+
return nil if token.to_s.empty? || @revoked.include?(token)
|
|
350
|
+
|
|
351
|
+
JWT.decode(token, key, true, algorithms: [ ALGORITHM ], verify_aud: false).first
|
|
352
|
+
rescue JWT::DecodeError
|
|
353
|
+
nil
|
|
354
|
+
end
|
|
355
|
+
|
|
356
|
+
def authenticated(request)
|
|
357
|
+
header = request[:headers]["authorization"].to_s
|
|
358
|
+
form = request[:body]
|
|
359
|
+
|
|
360
|
+
if header.start_with?("Basic ")
|
|
361
|
+
id, secret = Base64.decode64(header[6..]).split(":", 2).map { |part| URI.decode_www_form_component(part.to_s) }
|
|
362
|
+
client = @clients[id]
|
|
363
|
+
|
|
364
|
+
return [ id, client, !client.nil? && client.method == "client_secret_basic" && client.secret == secret ]
|
|
365
|
+
end
|
|
366
|
+
|
|
367
|
+
id = form["client_id"]
|
|
368
|
+
client = @clients[id]
|
|
369
|
+
|
|
370
|
+
return [ id, nil, false ] if client.nil?
|
|
371
|
+
|
|
372
|
+
allowed = case client.method
|
|
373
|
+
when "client_secret_post" then form["client_secret"] == client.secret
|
|
374
|
+
when "none" then true
|
|
375
|
+
when "private_key_jwt" then asserted?(form, id, client)
|
|
376
|
+
else false
|
|
377
|
+
end
|
|
378
|
+
|
|
379
|
+
[ id, client, allowed ]
|
|
380
|
+
end
|
|
381
|
+
|
|
382
|
+
def asserted?(form, id, client)
|
|
383
|
+
return false unless form["client_assertion_type"] == Session::ASSERTION_TYPE
|
|
384
|
+
|
|
385
|
+
claims, = JWT.decode(form["client_assertion"].to_s, nil, true,
|
|
386
|
+
algorithms: [ "ES256" ], jwks: client.jwks, aud: [ url, "#{url}/token" ], verify_aud: true,
|
|
387
|
+
iss: id, verify_iss: true, sub: id, verify_sub: true)
|
|
388
|
+
|
|
389
|
+
return false if claims["jti"].to_s.empty? || @assertions[claims["jti"]]
|
|
390
|
+
return false if claims["exp"].to_i - claims["iat"].to_i > 3600
|
|
391
|
+
|
|
392
|
+
@assertions[claims["jti"]] = true
|
|
393
|
+
rescue JWT::DecodeError, JWT::JWKError
|
|
394
|
+
false
|
|
395
|
+
end
|
|
396
|
+
|
|
397
|
+
def proof(request, method, path, access_token: nil)
|
|
398
|
+
presented = request[:headers]["dpop"]
|
|
399
|
+
|
|
400
|
+
return [ nil, true ] if presented.nil?
|
|
401
|
+
|
|
402
|
+
header = JWT.decode(presented, nil, false).last
|
|
403
|
+
jwk = header["jwk"]
|
|
404
|
+
|
|
405
|
+
return [ nil, false ] unless header["typ"].to_s.casecmp?(Proof::TYPE) && Proof::ALGORITHMS.include?(header["alg"].to_s)
|
|
406
|
+
return [ nil, false ] unless jwk.is_a?(Hash) && (jwk.keys & Proof::SECRET).empty?
|
|
407
|
+
|
|
408
|
+
claims = JWT.decode(presented, JWT::JWK.new(jwk).verify_key, true, algorithms: [ header["alg"] ]).first
|
|
409
|
+
|
|
410
|
+
return [ nil, false ] unless claims["htm"] == method && claims["htu"] == "#{url}#{path}"
|
|
411
|
+
return [ nil, false ] unless access_token.nil? ? !claims.key?("ath") : claims["ath"] == Proof.digest(access_token)
|
|
412
|
+
return [ nil, false ] if nonce && claims["nonce"] != nonce
|
|
413
|
+
|
|
414
|
+
[ Proof.thumbprint(jwk), true ]
|
|
415
|
+
rescue JWT::DecodeError, JWT::JWKError, OpenSSL::PKey::PKeyError, ArgumentError
|
|
416
|
+
[ nil, false ]
|
|
417
|
+
end
|
|
418
|
+
|
|
419
|
+
def token(request)
|
|
420
|
+
form = request[:body]
|
|
421
|
+
jkt, proven = proof(request, "POST", "/token")
|
|
422
|
+
|
|
423
|
+
return refused(400, "use_dpop_nonce", { "DPoP-Nonce" => nonce }) if !proven && nonce
|
|
424
|
+
return refused(400, "invalid_dpop_proof") unless proven
|
|
425
|
+
|
|
426
|
+
id, client, allowed = authenticated(request)
|
|
427
|
+
|
|
428
|
+
return refused(401, "invalid_client") unless allowed
|
|
429
|
+
|
|
430
|
+
case form["grant_type"]
|
|
431
|
+
when "client_credentials"
|
|
432
|
+
signed_in(grant(id, id, form["scope"] || client.scope, resources(request)), id, jkt)
|
|
433
|
+
when "authorization_code" then redeem(request, id, jkt)
|
|
434
|
+
when "refresh_token" then refreshed(request, id, jkt)
|
|
435
|
+
when Device::GRANT_TYPE then polled(request, id, client, jkt)
|
|
436
|
+
when Tokens::EXCHANGE then exchange(request, id, jkt)
|
|
437
|
+
else refused(400, "unsupported_grant_type")
|
|
438
|
+
end
|
|
439
|
+
end
|
|
440
|
+
|
|
441
|
+
def grant(client_id, subject, scope, resource, **more)
|
|
442
|
+
{
|
|
443
|
+
"client_id" => client_id, "subject" => subject, "scope" => scope.to_s, "resource" => Array(resource),
|
|
444
|
+
"sid" => "sid-#{SecureRandom.hex(8)}"
|
|
445
|
+
}.merge(more)
|
|
446
|
+
end
|
|
447
|
+
|
|
448
|
+
def redeem(request, id, jkt)
|
|
449
|
+
form = request[:body]
|
|
450
|
+
held = @codes.delete(form["code"])
|
|
451
|
+
|
|
452
|
+
return refused(400, "invalid_grant") if held.nil? || held["client_id"] != id
|
|
453
|
+
return refused(400, "invalid_grant") unless held["redirect_uri"] == form["redirect_uri"]
|
|
454
|
+
return refused(400, "invalid_grant") unless Proof.digest(form["code_verifier"].to_s) == held["challenge"]
|
|
455
|
+
|
|
456
|
+
asked = resources(request)
|
|
457
|
+
held = held.merge("resource" => asked) unless asked.empty?
|
|
458
|
+
|
|
459
|
+
signed_in(held, id, jkt)
|
|
460
|
+
end
|
|
461
|
+
|
|
462
|
+
def refreshed(request, id, jkt)
|
|
463
|
+
form = request[:body]
|
|
464
|
+
held = @grants.delete(form["refresh_token"])
|
|
465
|
+
|
|
466
|
+
return refused(400, "invalid_grant") if held.nil? || held["client_id"] != id
|
|
467
|
+
|
|
468
|
+
held = held.merge("scope" => form["scope"]) if form["scope"]
|
|
469
|
+
asked = resources(request)
|
|
470
|
+
held = held.merge("resource" => asked) unless asked.empty?
|
|
471
|
+
|
|
472
|
+
signed_in(held, id, jkt)
|
|
473
|
+
end
|
|
474
|
+
|
|
475
|
+
def polled(request, id, client, jkt)
|
|
476
|
+
if @pending.positive?
|
|
477
|
+
@pending -= 1
|
|
478
|
+
|
|
479
|
+
return refused(400, "authorization_pending") if @slowed
|
|
480
|
+
|
|
481
|
+
@slowed = true
|
|
482
|
+
return refused(400, "slow_down")
|
|
483
|
+
end
|
|
484
|
+
|
|
485
|
+
signed_in(grant(id, "ada", request[:body]["scope"] || client.scope, resources(request)), id, jkt)
|
|
486
|
+
end
|
|
487
|
+
|
|
488
|
+
def signed_in(held, id, jkt)
|
|
489
|
+
scopes = held["scope"].split
|
|
490
|
+
subject = held["subject"]
|
|
491
|
+
person = subject == id ? nil : person(subject)
|
|
492
|
+
org = organization(person, held["organization"]) if person && scopes.include?("organization")
|
|
493
|
+
aud = held["resource"].empty? ? audience : held["resource"]
|
|
494
|
+
aud = aud.first if aud.is_a?(Array) && aud.size == 1
|
|
495
|
+
access = access_token(subject: subject, scope: held["scope"], audience: aud, client_id: id,
|
|
496
|
+
cnf: jkt && { "jkt" => jkt }, org: org)
|
|
497
|
+
refresh = SecureRandom.hex(16)
|
|
498
|
+
@grants[refresh] = held
|
|
499
|
+
|
|
500
|
+
body = {
|
|
501
|
+
"access_token" => access,
|
|
502
|
+
"token_type" => jkt ? Proof::SCHEME : "Bearer",
|
|
503
|
+
"expires_in" => lifetime,
|
|
504
|
+
"scope" => held["scope"],
|
|
505
|
+
"refresh_token" => refresh
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
body["id_token"] = id_token(held, id, access, person, org) if person && scopes.include?("openid")
|
|
509
|
+
|
|
510
|
+
delegated = scopes.filter_map { |scope| scope.delete_prefix("masks:delegate:") if scope.start_with?("masks:delegate:") }
|
|
511
|
+
|
|
512
|
+
unless delegated.empty?
|
|
513
|
+
body["delegations"] = delegated.map do |provider|
|
|
514
|
+
{ "connection" => "connection-#{provider}", "provider" => provider, "provider_name" => provider.capitalize,
|
|
515
|
+
"subject" => "#{subject}@#{provider}.example" }
|
|
516
|
+
end
|
|
517
|
+
end
|
|
518
|
+
|
|
519
|
+
[ 200, body ]
|
|
520
|
+
end
|
|
521
|
+
|
|
522
|
+
def organization(person, key)
|
|
523
|
+
orgs = Array(person["orgs"])
|
|
524
|
+
|
|
525
|
+
orgs.find { |org| org["key"] == key } || orgs.first
|
|
526
|
+
end
|
|
527
|
+
|
|
528
|
+
def id_token(held, id, access, person, org)
|
|
529
|
+
now = Time.now.to_i
|
|
530
|
+
claims = {
|
|
531
|
+
"iss" => url,
|
|
532
|
+
"sub" => held["subject"],
|
|
533
|
+
"aud" => id,
|
|
534
|
+
"exp" => now + 900,
|
|
535
|
+
"iat" => now,
|
|
536
|
+
"nonce" => held["nonce"],
|
|
537
|
+
"sid" => held["sid"],
|
|
538
|
+
"at_hash" => IdToken.half_hash(access),
|
|
539
|
+
"auth_time" => auth_time,
|
|
540
|
+
"org" => org
|
|
541
|
+
}.merge(person.slice("name", "preferred_username", "email", "email_verified", "tenant", "masks:avatars"))
|
|
542
|
+
|
|
543
|
+
sign(claims.compact)
|
|
544
|
+
end
|
|
545
|
+
|
|
546
|
+
def exchange(request, id, jkt)
|
|
547
|
+
form = request[:body]
|
|
548
|
+
@exchanges << form
|
|
549
|
+
|
|
550
|
+
return refused(400, "invalid_request") if form["subject_token"].to_s.empty?
|
|
551
|
+
|
|
552
|
+
if form["requested_token_type"] == UPSTREAM
|
|
553
|
+
return [ 200, { "access_token" => "upstream-#{SecureRandom.hex(8)}", "issued_token_type" => UPSTREAM,
|
|
554
|
+
"token_type" => "Bearer", "expires_in" => 600, "scope" => form["scope"].to_s } ]
|
|
555
|
+
end
|
|
556
|
+
|
|
557
|
+
subject = decoded(form["subject_token"])
|
|
558
|
+
|
|
559
|
+
return refused(400, "invalid_grant") if subject.nil?
|
|
560
|
+
return refused(400, "invalid_grant") if subject.dig("cnf", "jkt") && subject.dig("cnf", "jkt") != jkt
|
|
561
|
+
|
|
562
|
+
scope = form["scope"] || subject["scope"].to_s
|
|
563
|
+
aud = resources(request)
|
|
564
|
+
aud = subject["aud"] if aud.empty?
|
|
565
|
+
aud = aud.first if aud.is_a?(Array) && aud.size == 1
|
|
566
|
+
expires_in = [ form["requested_lifetime"].to_i.nonzero? || lifetime, lifetime ].min
|
|
567
|
+
actor = form["actor_token"] && decoded(form["actor_token"])
|
|
568
|
+
act = actor ? { "sub" => actor["sub"], "client_id" => actor["client_id"] } : { "sub" => id }
|
|
569
|
+
access = access_token(subject: subject["sub"], scope: scope, audience: aud, expires_in: expires_in,
|
|
570
|
+
client_id: id, cnf: jkt && { "jkt" => jkt }, act: act)
|
|
571
|
+
|
|
572
|
+
[ 200, { "access_token" => access, "issued_token_type" => Tokens::ACCESS_TOKEN,
|
|
573
|
+
"token_type" => jkt ? Proof::SCHEME : "Bearer", "expires_in" => expires_in, "scope" => scope } ]
|
|
574
|
+
end
|
|
575
|
+
|
|
576
|
+
def device(request)
|
|
577
|
+
id, _, allowed = authenticated(request)
|
|
578
|
+
|
|
579
|
+
return refused(401, "invalid_client") unless allowed && request[:body]["client_id"] == id
|
|
580
|
+
|
|
581
|
+
[ 200, { "device_code" => "device-#{SecureRandom.hex(8)}", "user_code" => "ABCD-EFGH",
|
|
582
|
+
"verification_uri" => "#{url}/device", "expires_in" => 600, "interval" => 0 } ]
|
|
583
|
+
end
|
|
584
|
+
|
|
585
|
+
def revoke(request)
|
|
586
|
+
_, _, allowed = authenticated(request)
|
|
587
|
+
|
|
588
|
+
return refused(401, "invalid_client") unless allowed
|
|
589
|
+
|
|
590
|
+
@revoked << request[:body]["token"].to_s
|
|
591
|
+
|
|
592
|
+
[ 200, {} ]
|
|
593
|
+
end
|
|
594
|
+
|
|
595
|
+
def introspect(request)
|
|
596
|
+
id, _, allowed = authenticated(request)
|
|
597
|
+
|
|
598
|
+
return refused(401, "invalid_client") unless allowed
|
|
599
|
+
|
|
600
|
+
claims = decoded(request[:body]["token"])
|
|
601
|
+
|
|
602
|
+
return [ 200, { "active" => false } ] if claims.nil?
|
|
603
|
+
|
|
604
|
+
held = {
|
|
605
|
+
"active" => true,
|
|
606
|
+
"scope" => claims["scope"].to_s,
|
|
607
|
+
"client_id" => claims["client_id"],
|
|
608
|
+
"token_type" => claims.key?("cnf") ? Proof::SCHEME : "Bearer",
|
|
609
|
+
"cnf" => claims["cnf"],
|
|
610
|
+
"exp" => claims["exp"],
|
|
611
|
+
"iat" => claims["iat"],
|
|
612
|
+
"sub" => claims["sub"],
|
|
613
|
+
"aud" => Array(claims["aud"]),
|
|
614
|
+
"iss" => url,
|
|
615
|
+
"jti" => claims["jti"],
|
|
616
|
+
"tenant" => tenant,
|
|
617
|
+
"asked_by" => id
|
|
618
|
+
}
|
|
619
|
+
held = held.merge(person(claims["sub"]).slice("preferred_username", "orgs"), "org" => claims["org"]) if @people.key?(claims["sub"])
|
|
620
|
+
|
|
621
|
+
[ 200, held.compact ]
|
|
622
|
+
end
|
|
623
|
+
|
|
624
|
+
def userinfo(request)
|
|
625
|
+
scheme, token = request[:headers]["authorization"].to_s.split(" ", 2)
|
|
626
|
+
claims = decoded(token)
|
|
627
|
+
|
|
628
|
+
return refused(401, "invalid_token") if claims.nil?
|
|
629
|
+
|
|
630
|
+
bound = claims.dig("cnf", "jkt")
|
|
631
|
+
|
|
632
|
+
return refused(401, "invalid_token") unless bound.nil? == (scheme.to_s.casecmp?("Bearer"))
|
|
633
|
+
|
|
634
|
+
if bound
|
|
635
|
+
jkt, proven = proof(request, "GET", "/userinfo", access_token: token)
|
|
636
|
+
|
|
637
|
+
return refused(401, "invalid_dpop_proof") unless proven && jkt == bound
|
|
638
|
+
end
|
|
639
|
+
|
|
640
|
+
[ 200, person(claims["sub"]) ]
|
|
641
|
+
end
|
|
642
|
+
|
|
643
|
+
def avatar(request)
|
|
644
|
+
return [ 401, nil ] if request[:headers]["authorization"].to_s.empty?
|
|
645
|
+
|
|
646
|
+
[ 200, photo, { "Content-Type" => photo_type } ]
|
|
647
|
+
end
|
|
648
|
+
|
|
649
|
+
def register(request)
|
|
650
|
+
presented = request[:headers]["authorization"].to_s.delete_prefix("Bearer ")
|
|
651
|
+
id = @initial.delete(presented)
|
|
652
|
+
|
|
653
|
+
return refused(401, "invalid_token") if id.nil?
|
|
654
|
+
|
|
655
|
+
metadata = request[:body].is_a?(Hash) ? request[:body] : {}
|
|
656
|
+
method = metadata["token_endpoint_auth_method"] || "client_secret_basic"
|
|
657
|
+
secret = SecureRandom.hex(16) if method.start_with?("client_secret")
|
|
658
|
+
token = SecureRandom.hex(16)
|
|
659
|
+
|
|
660
|
+
@clients[id] = Registered.new(method: method, secret: secret, jwks: metadata["jwks"] || { "keys" => [] },
|
|
661
|
+
scope: metadata["scope"], metadata: metadata)
|
|
662
|
+
@registrations[id] = token
|
|
663
|
+
uri = foreign_uri ? "https://elsewhere.example/register/#{id}" : "#{url}/register/#{id}"
|
|
664
|
+
|
|
665
|
+
[ 201, metadata.merge("client_id" => id, "client_secret" => secret, "registration_access_token" => token,
|
|
666
|
+
"registration_client_uri" => uri).compact ]
|
|
667
|
+
end
|
|
668
|
+
|
|
669
|
+
def registration(request, id)
|
|
670
|
+
held = @registrations[id]
|
|
671
|
+
client = @clients[id]
|
|
672
|
+
|
|
673
|
+
return refused(401, "invalid_token") if held.nil? || client.nil? || request[:headers]["authorization"] != "Bearer #{held}"
|
|
674
|
+
|
|
675
|
+
case request[:method]
|
|
676
|
+
when "DELETE"
|
|
677
|
+
@registrations.delete(id)
|
|
678
|
+
@clients.delete(id)
|
|
679
|
+
[ 204, nil ]
|
|
680
|
+
when "PUT"
|
|
681
|
+
metadata = request[:body].is_a?(Hash) ? request[:body] : {}
|
|
682
|
+
client.scope = metadata["scope"] || client.scope
|
|
683
|
+
client.metadata = client.metadata.merge(metadata)
|
|
684
|
+
[ 200, client.metadata.merge("client_id" => id) ]
|
|
685
|
+
else
|
|
686
|
+
[ 200, client.metadata.merge("client_id" => id, "token_endpoint_auth_method" => client.method, "scope" => client.scope).compact ]
|
|
687
|
+
end
|
|
688
|
+
end
|
|
689
|
+
|
|
690
|
+
def enroll(request)
|
|
691
|
+
id, _, allowed = authenticated(request)
|
|
692
|
+
|
|
693
|
+
return refused(401, "invalid_client") unless allowed
|
|
694
|
+
|
|
695
|
+
form = request[:body]
|
|
696
|
+
scope = form["scope"].to_s
|
|
697
|
+
|
|
698
|
+
return refused(400, "invalid_request") if scope.empty?
|
|
699
|
+
|
|
700
|
+
token = SecureRandom.hex(16)
|
|
701
|
+
machine = "machine-#{SecureRandom.hex(6)}"
|
|
702
|
+
@initial[token] = machine
|
|
703
|
+
@enrolled[machine] = id
|
|
704
|
+
|
|
705
|
+
[ 201, { "initial_access_token" => token, "expires_in" => (form["expires_in"] || 900).to_i, "scope" => scope } ]
|
|
706
|
+
end
|
|
707
|
+
|
|
708
|
+
def unenroll(request, machine)
|
|
709
|
+
id, _, allowed = authenticated(request)
|
|
710
|
+
|
|
711
|
+
return refused(401, "invalid_client") unless allowed
|
|
712
|
+
return refused(404, "invalid_request") unless @enrolled[machine] == id
|
|
713
|
+
|
|
714
|
+
@clients.delete(machine)
|
|
715
|
+
@registrations.delete(machine)
|
|
716
|
+
[ 204, nil ]
|
|
717
|
+
end
|
|
718
|
+
|
|
719
|
+
def end_session(query)
|
|
720
|
+
asked = URI.decode_www_form(query.to_s).to_h
|
|
721
|
+
target = asked["post_logout_redirect_uri"].to_s
|
|
722
|
+
|
|
723
|
+
return [ 200, { "signed_out" => true } ] if target.empty?
|
|
724
|
+
|
|
725
|
+
back = URI.parse(target)
|
|
726
|
+
back.query = [ back.query, URI.encode_www_form([ [ "state", asked["state"] ] ].reject { |_, value| value.nil? }) ].compact.reject(&:empty?).join("&")
|
|
727
|
+
|
|
728
|
+
[ 302, nil, { "Location" => back.to_s } ]
|
|
729
|
+
end
|
|
730
|
+
end
|
|
731
|
+
end
|
|
732
|
+
end
|