-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathauthorization.rb
More file actions
574 lines (487 loc) · 18.1 KB
/
authorization.rb
File metadata and controls
574 lines (487 loc) · 18.1 KB
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
require 'addressable/uri'
require 'faraday'
require 'faraday_middleware'
require 'securerandom'
require 'travis/api/app'
require 'travis/github/education'
require 'travis/github/oauth'
require 'travis/remote_vcs/user'
require 'travis/remote_vcs/response_error'
require 'uri'
class Travis::Api::App
class Endpoint
# You need to get hold of an access token in order to reach any
# endpoint requiring authorization.
# There are three ways to get hold of such a token: OAuth2, via a GitHub
# token you may already have or with Cross-Origin Window Messages.
#
# ## OAuth2
#
# API authorization is done via a subset of OAuth2 and is largely compatible
# with the [GitHub process](http://developer.github.com/v3/oauth/).
# Be aware that Travis CI will in turn use OAuth2 to authenticate (and
# authorize) against GitHub.
#
# This is the recommended way for third-party web apps.
# The entry point is [/auth/authorize](#/auth/authorize).
#
# ## GitHub Token
#
# If you already have a GitHub token with the same or greater scope than
# the tokens used by Travis CI, you can easily exchange it for a access
# token. Travis will not store the GitHub token and only use it for a single
# request to resolve the associated user and scopes.
#
# This is the recommended way for GitHub applications that also want Travis
# integration.
#
# The entry point is [/auth/github](#POST /auth/github).
#
# ## Cross-Origin Window Messages
#
# This is the recommended way for the official client. We might improve the
# authorization flow to support third-party clients in the future, too.
#
# The entry point is [/auth/post_message](#/auth/post_message).
class Authorization < Endpoint
enable :inline_templates
set prefix: '/auth'
set :check_auth, false
SUSPICIOUS_CODES = ['<', '>']
# Endpoint for retrieving an authorization code, which in turn can be used
# to generate an access token.
#
# NOTE: This endpoint is not yet implemented.
#
# Parameters:
#
# * **client_id**: your App's client id (required)
# * **redirect_uri**: URL to redirect to
# * **scope**: requested access scope
# * **state**: should be random string to prevent CSRF attacks
get '/authorize' do
raise NotImplementedError
end
# Endpoint for generating an access token from an authorization code.
#
# NOTE: This endpoint is not yet implemented.
#
# Parameters:
#
# * **client_id**: your App's client id (required)
# * **client_secret**: your App's client secret (required)
# * **code**: code retrieved from redirect from [/auth/authorize](#/auth/authorize) (required)
# * **redirect_uri**: URL to redirect to
# * **state**: same value sent to [/auth/authorize](#/auth/authorize)
post '/access_token' do
raise NotImplementedError
end
# Endpoint for generating an access token from a GitHub access token.
#
# Parameters:
#
# * **github_token**: GitHub token for checking authorization (required)
post '/github' do
unless params[:github_token]
halt 422, { "error" => "Must pass 'github_token' parameter" }
end
# For new provider method
# renew_access_token(token: params[:github_token], app_id: 1, provider: :github)
{ 'access_token' => github_to_travis(params[:github_token], app_id: 1, drop_token: true) }
end
# Endpoint for making sure user authorized Travis CI to access GitHub.
# There are no restrictions on where to redirect to after handshake.
# However, no information whatsoever is being sent with the redirect.
#
# Parameters:
#
# * **redirect_uri**: URI to redirect to after handshake.
get '/handshake/?:provider?' do
method = org? ? :handshake : :vcs_handshake
params[:provider] ||= 'github'
send(method) do |user, token, redirect_uri|
if target_ok? redirect_uri
content_type :html
data = { user: user, token: token, uri: redirect_uri }
erb(:post_payload, locals: data)
else
halt 401, 'target URI not allowed'
end
end
end
get '/post_message', scope: :public do
content_type :html
data = { check_third_party_cookies: !Travis.config.auth.disable_third_party_cookies_check }
erb(:container, locals: data)
end
error Faraday::Error::ClientError do
halt 401, 'could not resolve github token'
end
get '/confirm_user/:token' do
content_type :json
Travis::RemoteVCS::User.new.confirm_user(token: params[:token])
{ status: 200 }.to_json
rescue Travis::RemoteVCS::ResponseError
halt 404, 'The token is expired or not found.'
end
get '/request_confirmation/:id' do
content_type :json
Travis::RemoteVCS::User
.new.request_confirmation(id: current_user.id)
{ status: 200 }.to_json
end
private
# update first login date if not set
def update_first_login(user)
unless user.first_logged_in_at
user.update_attributes(first_logged_in_at: Time.now)
end
end
def serialize_user(user)
rendered = Travis::Api::Serialize.data(user, version: :v2)
token = user.tokens.asset.first.try(:token).to_s
rendered['user'].merge(
'token' => token,
'rss_token' => user.tokens.rss.first.try(:token) || token,
)
end
def oauth_endpoint
proxy = Travis.config.oauth2.proxy
proxy ? File.join(proxy, request.fullpath) : (ENV['AUTH_HANDSHAKE_HOST'] || url)
end
def log_with_request_id(line)
request_id = request.env["HTTP_X_REQUEST_ID"]
Travis.logger.info "#{line} <request_id=#{request_id}>"
end
def handshake
config = Travis.config.oauth2.to_h
endpoint = Addressable::URI.parse(config[:authorization_server])
values = {
client_id: config[:client_id],
scope: config[:scope],
redirect_uri: oauth_endpoint
}
log_with_request_id("[handshake] Starting handshake")
if params[:code]
unless state_ok?(params[:state])
log_with_request_id("[handshake] Handshake failed (state mismatch)")
handle_invalid_response
return
end
endpoint.path = config[:access_token_path]
values[:state] = params[:state]
values[:code] = params[:code]
values[:client_secret] = config[:client_secret]
github_token = get_token(endpoint.to_s, values)
user = user_for_github_token(github_token)
token = generate_token(user: user, app_id: 0)
payload = params[:state].split(":::", 2)[1]
update_first_login(user)
yield serialize_user(user), token, payload
else
values[:state] = create_state
endpoint.path = config[:authorize_path]
endpoint.query_values = values
redirect to(endpoint.to_s)
end
end
# VCS HANDSHAKE START
def remote_vcs_user
@remote_vcs_user ||= Travis::RemoteVCS::User.new
end
def vcs_handshake
if params[:code]
unless state_ok?(params[:state], params[:provider])
handle_invalid_response
return
end
vcs_data = remote_vcs_user.authenticate(
provider: params[:provider],
code: params[:code],
redirect_uri: oauth_endpoint
)
if vcs_data['redirect_uri'].present?
redirect to(vcs_data['redirect_uri'])
return
end
user = User.find(vcs_data['user']['id'])
update_first_login(user)
yield serialize_user(user), vcs_data['token'], payload(params[:provider])
else
state = vcs_create_state(params[:origin] || params[:redirect_uri])
vcs_data = remote_vcs_user.auth_request(
provider: params[:provider],
state: state,
redirect_uri: oauth_endpoint
)
response.set_cookie(cookie_name(params[:provider]), value: state, httponly: true)
redirect to(vcs_data['authorize_url'])
end
rescue ::Travis::RemoteVCS::ResponseError
halt 401, "Can't login"
end
def renew_access_token(token:, app_id:, provider:)
vcs_data = remote_vcs_user.generate_token(
provider: provider,
token: token,
app_id: app_id
)
if vcs_data['redirect_uri']
redirect to(vcs_data['redirect_uri'])
else
{ access_token: vcs_data['token'] }
end
rescue ::Travis::RemoteVCS::ResponseError
halt 401, "Can't renew token"
end
def vcs_create_state(payload)
state = SecureRandom.urlsafe_base64(16)
state << ":::" << payload if payload
state
end
def payload(provider)
request.cookies[cookie_name(provider)].split(':::').last
end
def cookie_name(provider = :github)
"travis.state-#{provider}"
end
# VCS HANDSHAKE END
def clear_state_cookies
response.delete_cookie cookie_name(:github)
response.delete_cookie cookie_name(:gitlab)
response.delete_cookie cookie_name(:bitbucket)
response.delete_cookie cookie_name(:assembla)
end
def handle_invalid_response
clear_state_cookies
redirect to("https://#{Travis.config.host}/")
end
def create_state
state = SecureRandom.urlsafe_base64(16)
redis.sadd('github:states', state)
redis.expire('github:states', 1800)
payload = params[:origin] || params[:redirect_uri]
state << ":::" << payload if payload
response.set_cookie(cookie_name, state)
state
end
def state_ok?(state, provider = :github)
cookie_state = request.cookies[cookie_name(provider)]
state == cookie_state and redis.srem('github:states', state.to_s.split(":::", 1))
end
def github_to_travis(token, options = {})
drop_token = options.delete(:drop_token)
generate_token options.merge(user: user_for_github_token(token, drop_token))
end
class UserManager < Struct.new(:data, :token, :drop_token)
include User::Renaming
attr_accessor :user
def initialize(*)
super
@user = ::User.find_by_github_id(data['id'])
end
def info(attributes = {})
info = data.to_hash.slice('name', 'login', 'gravatar_id')
info.merge! attributes.stringify_keys
if Travis::Features.feature_active?(:education_data_sync) ||
(user && Travis::Features.owner_active?(:education_data_sync, user))
info['education'] = education
end
info['github_id'] ||= data['id']
info['vcs_id'] ||= data['id']
info
end
def user_exists?
user
end
def education
Travis::Github::Education.new(token.to_s).student?
end
def fetch
retried ||= false
info = drop_token ? self.info : self.info(github_oauth_token: token)
ActiveRecord::Base.transaction do
if user
ensure_token_is_available
rename_repos_owner(user.login, info['login'])
user.update_attributes info
else
self.user = ::User.create! info
end
Travis::Github::Oauth.update_scopes(user) # unless Travis.env == 'test'
nullify_logins(user.github_id, user.login)
end
user
rescue ActiveRecord::RecordNotUnique
unless retried
retried = true
retry
end
end
def ensure_token_is_available
unless user.tokens.first
user.create_a_token
end
end
end
def user_for_github_token(token, drop_token = false)
data = GH.with(token: token.to_s, client_id: nil) { GH['user'] }
scopes = parse_scopes data.headers['x-oauth-scopes']
manager = UserManager.new(data, token, drop_token)
unless acceptable?(scopes, drop_token)
# TODO: we should probably only redirect if this is a web
# oauth request, are there any other possibilities to
# consider?
url = Travis.config.oauth2.insufficient_access_redirect_url
url += "#existing-user" if manager.user_exists?
redirect to(url)
end
user = manager.fetch
if user.nil?
log_with_request_id("[handshake] Fetching user failed")
halt 403, 'not a Travis user'
end
Travis.run_service(:sync_user, user)
user
rescue GH::Error
# not a valid token actually, but we don't want to expose that info
halt 403, 'not a Travis user'
end
def get_token(endpoint, values)
# Get base URL for when we setup Faraday since otherwise it'll ignore no_proxy
url = URI.parse(endpoint)
base_url = "#{url.scheme}://#{url.host}"
http_options = {url: base_url, ssl: Travis.config.ssl.to_h.merge(Travis.config.github.ssl || {}).compact}
conn = Faraday.new(http_options) do |conn|
conn.request :json
conn.use :instrumentation
conn.use OpenCensus::Trace::Integrations::FaradayMiddleware if Travis::Api::App::Middleware::OpenCensus.enabled?
conn.adapter :net_http_persistent
end
response = conn.post(endpoint, values)
parameters = Addressable::URI.form_unencode(response.body)
token_info = parameters.assoc("access_token")
unless token_info
log_with_request_id("[handshake] Could not fetch token, github's response: status=#{response.status}, body=#{parameters.inspect} headers=#{response.headers.inspect}")
halt 401, 'could not resolve github token'
end
token_info.last
end
def parse_scopes(data)
data.gsub(/\s/,'').split(',') if data
end
def generate_token(options)
AccessToken.create(options).token
end
def acceptable?(scopes, lossy = false)
Travis::Github::Oauth.wanted_scopes.all? do |scope|
acceptable_scopes_for(scope, lossy).any? { |s| scopes.include? s }
end
end
def acceptable_scopes_for(scope, lossy = false)
scopes = case scope = scope.to_s
when /^(.+):/ then [$1, scope]
when 'public_repo' then [scope, 'repo']
else [scope]
end
if lossy
scopes << 'repo'
scopes << 'public_repo' if lossy and scope != 'repo'
end
scopes
end
def post_message(payload)
content_type :html
erb(:post_message, locals: payload)
end
def invalid_target(target_origin)
content_type :html
erb(:invalid_target, {}, target_origin: target_origin)
end
def target_ok?(target_origin)
test_target_origin = URI.decode(target_origin).downcase
return if SUSPICIOUS_CODES.any? { |word| test_target_origin.include?(word) }
return unless uri = Addressable::URI.parse(target_origin)
if allowed_https_targets.include?(uri.host)
uri.scheme == 'https'
elsif uri.host =~ /\A(.+\.)?travis-ci\.(com|org)\Z/
uri.scheme == 'https'
elsif uri.host == 'localhost' or uri.host == '127.0.0.1'
uri.inferred_port.to_i > 1023
end
end
def allowed_https_targets
@allowed_https_targets ||= Travis.config.auth.target_origin.to_s.split(',')
end
end
end
end
__END__
@@ invalid_target
<script>
console.log('refusing to send a token to <%= target_origin.inspect %>, not safelisted!');
</script>
@@ common
function tellEveryone(msg, win) {
if(win == undefined) win = window;
win.postMessage(msg, '*');
if(win.parent != win) tellEveryone(msg, win.parent);
if(win.opener) tellEveryone(msg, win.opener);
}
@@ container
<!DOCTYPE html>
<html><body><script>
// === THE FLOW ===
// every serious program has a main function
function main() {
redirect();
}
// === THE LOGIC ===
function redirect() {
tellEveryone('redirect');
}
// === THE PLUMBING ===
<%= erb :common %>
var succeeded = false;
window.addEventListener("message", function(event) {
if(event.data === "done") {
succeeded = true
for(var i = 0; i < callbacks.length; i++) {
(callbacks[i])();
}
}
});
// === READY? GO! ===
main();
</script>
</body>
</html>
@@ post_message
<script>
<%= erb :common %>
function uberParent(win) {
return win.parent === win ? win : uberParent(win.parent);
}
function sendPayload(win) {
var payload = {
'user': <%= user.to_json %>,
'token': <%= token.inspect %>
};
uberParent(win).postMessage(payload, <%= target_origin.inspect %>);
}
if(window.parent == window) {
sendPayload(window.opener);
window.close();
} else {
tellEveryone('done');
sendPayload(window.parent);
}
</script>
@@ post_payload
<body onload='document.forms[0].submit()'>
<form action="<%= uri %>" method='post'>
<input type='hidden' name='token' value='<%= token %>'>
<input type='hidden' name='user' value="<%= user.to_json.gsub('"', '"') %>">
<input type='hidden' name='storage' value='localStorage'>
</form>
</body>