forked from discourse/discourse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathomniauth_callbacks_controller_spec.rb
1105 lines (844 loc) · 37.4 KB
/
omniauth_callbacks_controller_spec.rb
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# frozen_string_literal: true
require "discourse_connect_base"
RSpec.describe Users::OmniauthCallbacksController do
fab!(:user) { Fabricate(:user) }
before { OmniAuth.config.test_mode = true }
after do
Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:google_oauth2] = nil
Rails.application.env_config["omniauth.origin"] = nil
OmniAuth.config.test_mode = false
end
describe ".find_authenticator" do
it "fails if a provider is disabled" do
SiteSetting.enable_twitter_logins = false
expect do Users::OmniauthCallbacksController.find_authenticator("twitter") end.to raise_error(
Discourse::InvalidAccess,
)
end
it "fails for unknown" do
expect do
Users::OmniauthCallbacksController.find_authenticator("twitter1")
end.to raise_error(Discourse::InvalidAccess)
end
it "finds an authenticator when enabled" do
SiteSetting.enable_twitter_logins = true
expect(Users::OmniauthCallbacksController.find_authenticator("twitter")).not_to eq(nil)
end
context "with a plugin-contributed auth provider" do
let :provider do
provider = Auth::AuthProvider.new
provider.authenticator =
Class
.new(Auth::Authenticator) do
def name
"ubuntu"
end
def enabled?
SiteSetting.ubuntu_login_enabled
end
end
.new
provider.enabled_setting = "ubuntu_login_enabled"
provider
end
before { DiscoursePluginRegistry.register_auth_provider(provider) }
after { DiscoursePluginRegistry.reset! }
it "finds an authenticator when enabled" do
SiteSetting.stubs(:ubuntu_login_enabled).returns(true)
expect(Users::OmniauthCallbacksController.find_authenticator("ubuntu")).to be(
provider.authenticator,
)
end
it "fails if an authenticator is disabled" do
SiteSetting.stubs(:ubuntu_login_enabled).returns(false)
expect { Users::OmniauthCallbacksController.find_authenticator("ubuntu") }.to raise_error(
Discourse::InvalidAccess,
)
end
end
end
describe "Google Oauth2" do
before { SiteSetting.enable_google_oauth2_logins = true }
it "should display the failure message if needed" do
get "/auth/failure"
expect(response.status).to eq(200)
expect(response.body).to include(I18n.t("login.omniauth_error.generic"))
end
describe "request" do
it "should error for non existant authenticators" do
post "/auth/fake_auth"
expect(response.status).to eq(404)
get "/auth/fake_auth"
expect(response.status).to eq(403)
end
it "should error for disabled authenticators" do
SiteSetting.enable_google_oauth2_logins = false
post "/auth/google_oauth2"
expect(response.status).to eq(404)
get "/auth/google_oauth2"
expect(response.status).to eq(403)
end
it "should handle common errors" do
OmniAuth::Strategies::GoogleOauth2
.any_instance
.stubs(:mock_request_call)
.raises(
OAuth::Unauthorized.new(
mock().tap do |m|
m.stubs(:code).returns(403)
m.stubs(:message).returns("Message")
end,
),
)
post "/auth/google_oauth2"
expect(response.status).to eq(302)
expect(response.location).to include("/auth/failure?message=request_error")
OmniAuth::Strategies::GoogleOauth2
.any_instance
.stubs(:mock_request_call)
.raises(JWT::InvalidIatError.new)
post "/auth/google_oauth2"
expect(response.status).to eq(302)
expect(response.location).to include("/auth/failure?message=invalid_iat")
end
it "should only start auth with a POST request" do
post "/auth/google_oauth2"
expect(response.status).to eq(302)
get "/auth/google_oauth2"
expect(response.status).to eq(200)
end
context "with CSRF protection enabled" do
before { ActionController::Base.allow_forgery_protection = true }
after { ActionController::Base.allow_forgery_protection = false }
it "should be CSRF protected" do
post "/auth/google_oauth2"
expect(response.status).to eq(302)
expect(response.location).to include("/auth/failure?message=csrf_detected")
post "/auth/google_oauth2", params: { authenticity_token: "faketoken" }
expect(response.status).to eq(302)
expect(response.location).to include("/auth/failure?message=csrf_detected")
get "/session/csrf.json"
token = response.parsed_body["csrf"]
post "/auth/google_oauth2", params: { authenticity_token: token }
expect(response.status).to eq(302)
end
it "should not be CSRF protected if it is the only auth method" do
get "/auth/google_oauth2"
expect(response.status).to eq(200)
SiteSetting.enable_local_logins = false
get "/auth/google_oauth2"
expect(response.status).to eq(302)
end
end
end
context "when in readonly mode" do
use_redis_snapshotting
it "should return a 503" do
Discourse.enable_readonly_mode
get "/auth/google_oauth2/callback"
expect(response.code).to eq("503")
end
end
context "when in staff writes only mode" do
use_redis_snapshotting
before { Discourse.enable_readonly_mode(Discourse::STAFF_WRITES_ONLY_MODE_KEY) }
it "returns a 503 for non-staff" do
mock_auth(user.email, user.username, user.name)
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(503)
logged_on_user = Discourse.current_user_provider.new(request.env).current_user
expect(logged_on_user).to eq(nil)
end
it "completes for staff" do
user.update!(admin: true)
mock_auth(user.email, user.username, user.name)
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
logged_on_user = Discourse.current_user_provider.new(request.env).current_user
expect(logged_on_user).not_to eq(nil)
end
end
context "without an `omniauth.auth` env" do
it "should return a 404" do
get "/auth/eviltrout/callback"
expect(response.code).to eq("404")
end
end
describe "when user not found" do
let(:email) { "[email protected]" }
let(:username) { "somename" }
let(:name) { "Some Name" }
before { mock_auth(email, username, name) }
it "should return the right response" do
destination_url = "/somepath"
Rails.application.env_config["omniauth.origin"] = destination_url
events = DiscourseEvent.track_events { get "/auth/google_oauth2/callback.json" }
expect(events.any? { |e| e[:event_name] == :before_auth }).to eq(true)
expect(
events.any? do |e|
e[:event_name] === :after_auth && Auth::GoogleOAuth2Authenticator === e[:params][0] &&
!e[:params][1].failed?
end,
).to eq(true)
expect(response.status).to eq(302)
data = JSON.parse(cookies[:authentication_data])
expect(data["email"]).to eq(email)
expect(data["username"]).to eq(username)
expect(data["name"]).to eq(name)
expect(data["auth_provider"]).to eq("google_oauth2")
expect(data["email_valid"]).to eq(true)
expect(data["can_edit_username"]).to eq(true)
expect(data["destination_url"]).to eq(destination_url)
end
it "should return the right response for staged users" do
Fabricate(:user, username: username, email: email, staged: true)
destination_url = "/somepath"
Rails.application.env_config["omniauth.origin"] = destination_url
events = DiscourseEvent.track_events { get "/auth/google_oauth2/callback.json" }
expect(events.any? { |e| e[:event_name] == :before_auth }).to eq(true)
expect(
events.any? do |e|
e[:event_name] === :after_auth && Auth::GoogleOAuth2Authenticator === e[:params][0] &&
!e[:params][1].failed?
end,
).to eq(true)
expect(response.status).to eq(302)
data = JSON.parse(cookies[:authentication_data])
expect(data["email"]).to eq(email)
expect(data["username"]).to eq(username)
expect(data["auth_provider"]).to eq("google_oauth2")
expect(data["email_valid"]).to eq(true)
expect(data["can_edit_username"]).to eq(true)
expect(data["name"]).to eq("Some Name")
expect(data["destination_url"]).to eq(destination_url)
end
it "should include destination url in response" do
destination_url = "/cookiepath"
cookies[:destination_url] = destination_url
get "/auth/google_oauth2/callback.json"
data = JSON.parse(cookies[:authentication_data])
expect(data["destination_url"]).to eq(destination_url)
end
it "should return an associate url when multiple login methods are enabled" do
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
data = JSON.parse(cookies[:authentication_data])
expect(data["associate_url"]).to start_with("/associate/")
SiteSetting.enable_local_logins = false
get "/auth/google_oauth2/callback.json"
data = JSON.parse(cookies[:authentication_data])
expect(data["associate_url"]).to eq(nil)
end
it "does not use email for username suggestions if disabled in settings" do
SiteSetting.use_email_for_username_and_name_suggestions = false
username = ""
name = ""
email = "[email protected]"
mock_auth(email, username, name)
get "/auth/google_oauth2/callback.json"
data = JSON.parse(cookies[:authentication_data])
expect(data["username"]).to eq("user1") # not "billmailbox" that can be extracted from email
end
it "uses email for username suggestions if enabled in settings" do
SiteSetting.use_email_for_username_and_name_suggestions = true
username = ""
name = ""
email = "[email protected]"
mock_auth(email, username, name)
get "/auth/google_oauth2/callback.json"
data = JSON.parse(cookies[:authentication_data])
expect(data["username"]).to eq("billmailbox")
end
it "stops using name for username suggestions if disabled in settings" do
SiteSetting.use_name_for_username_suggestions = false
username = ""
name = "John Smith"
email = "[email protected]"
mock_auth(email, username, name)
get "/auth/google_oauth2/callback.json"
data = JSON.parse(cookies[:authentication_data])
expect(data["username"]).to eq("user1")
end
describe "when site is invite_only" do
before { SiteSetting.invite_only = true }
it "should return the right response without any origin" do
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
data = JSON.parse(response.cookies["authentication_data"])
expect(data["requires_invite"]).to eq(true)
end
it "returns the right response for an invalid origin" do
Rails.application.env_config["omniauth.origin"] = "/invitesinvites"
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
end
it "should return the right response when origin is invites page" do
origin =
Rails.application.routes.url_helpers.invite_url(
Fabricate(:invite).invite_key,
host: Discourse.base_url,
)
Rails.application.env_config["omniauth.origin"] = origin
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
expect(response).to redirect_to(origin)
data = JSON.parse(response.cookies["authentication_data"])
expect(data["requires_invite"]).to eq(nil)
end
end
end
describe "when user has been verified" do
let(:uid) { 12_345 }
before { mock_auth(user.email, "Somenickname", "Some name", uid) }
it "should return the right response" do
expect(user.email_confirmed?).to eq(false)
events = DiscourseEvent.track_events { get "/auth/google_oauth2/callback.json" }
expect(events.map { |event| event[:event_name] }).to include(
:user_logged_in,
:user_first_logged_in,
)
expect(response.status).to eq(302)
data = JSON.parse(cookies[:authentication_data])
expect(data["authenticated"]).to eq(true)
expect(data["awaiting_activation"]).to eq(false)
expect(data["awaiting_approval"]).to eq(false)
expect(data["not_allowed_from_ip_address"]).to eq(false)
expect(data["admin_not_allowed_from_ip_address"]).to eq(false)
user.reload
expect(user.email_confirmed?).to eq(true)
end
it "should return the authenticated response with the correct path for subfolders" do
set_subfolder "/forum"
events = DiscourseEvent.track_events { get "/auth/google_oauth2/callback.json" }
expect(
response.headers["Set-Cookie"].match(%r{^authentication_data=.*; path=/forum}),
).not_to eq(nil)
expect(events.map { |event| event[:event_name] }).to include(
:user_logged_in,
:user_first_logged_in,
)
expect(response.status).to eq(302)
data = JSON.parse(response.cookies["authentication_data"])
expect(data["authenticated"]).to eq(true)
expect(data["awaiting_activation"]).to eq(false)
expect(data["awaiting_approval"]).to eq(false)
expect(data["not_allowed_from_ip_address"]).to eq(false)
expect(data["admin_not_allowed_from_ip_address"]).to eq(false)
user.reload
expect(user.email_confirmed?).to eq(true)
end
it "should confirm email even when the tokens are expired" do
user.email_tokens.update_all(confirmed: false, expired: true)
user.reload
expect(user.email_confirmed?).to eq(false)
events = DiscourseEvent.track_events { get "/auth/google_oauth2/callback.json" }
expect(events.map { |event| event[:event_name] }).to include(
:user_logged_in,
:user_first_logged_in,
)
expect(response.status).to eq(302)
user.reload
expect(user.email_confirmed?).to eq(true)
end
it "should treat a staged user the same as an unregistered user" do
user.update!(staged: true, registration_ip_address: nil)
user.reload
expect(user.staged).to eq(true)
expect(user.registration_ip_address).to eq(nil)
events = DiscourseEvent.track_events { get "/auth/google_oauth2/callback.json" }
expect(events.map { |event| event[:event_name] }).to include(:before_auth, :after_auth)
expect(response.status).to eq(302)
data = JSON.parse(cookies[:authentication_data])
expect(data["username"]).to eq("Somenickname")
user.reload
expect(user.staged).to eq(true)
expect(user.registration_ip_address).to eq(nil)
# Now register
UsersController.any_instance.stubs(:honeypot_value).returns(nil)
UsersController.any_instance.stubs(:challenge_value).returns(nil)
post "/u.json",
params: {
name: "My new name",
username: "mynewusername",
email: user.email,
}
expect(response.status).to eq(200)
user.reload
expect(user.staged).to eq(false)
expect(user.registration_ip_address).to be_present
expect(user.name).to eq("My new name")
end
it "should activate user with matching email" do
user.update!(password: "securepassword", active: false, registration_ip_address: "1.1.1.1")
user.reload
expect(user.active).to eq(false)
expect(user.confirm_password?("securepassword")).to eq(true)
get "/auth/google_oauth2/callback.json"
user.reload
expect(user.active).to eq(true)
# Delete the password, it may have been set by someone else
expect(user.confirm_password?("securepassword")).to eq(false)
end
it "should work if the user has no email_tokens, and an invite" do
# Confirming existing email_tokens has a side effect of redeeming invites.
# Pretend we don't have any email_tokens
user.email_tokens.destroy_all
invite = Fabricate(:invite, invited_by: Fabricate(:admin))
invite.update_column(:email, user.email) # (avoid validation)
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
expect(invite.reload.invalidated_at).not_to eq(nil)
end
it "should update name/username/email when SiteSetting.auth_overrides_* are enabled" do
SiteSetting.email_editable = false
SiteSetting.auth_overrides_email = true
SiteSetting.auth_overrides_name = true
SiteSetting.auth_overrides_username = true
UserAssociatedAccount.create!(
provider_name: "google_oauth2",
user_id: user.id,
provider_uid: uid,
)
old_email = user.email
user.update!(name: "somename", username: "somusername", email: "[email protected]")
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
user.reload
expect(user.email).to eq(old_email)
expect(user.username).to eq("Somenickname")
expect(user.name).to eq("Some name")
end
it "should preserve username when several users login with the same username" do
SiteSetting.auth_overrides_username = true
# if several users have username "bill" on the external site,
# they will have usernames bill, bill1, bill2 etc in Discourse:
Fabricate(:user, username: "bill")
Fabricate(:user, username: "bill1")
Fabricate(:user, username: "bill2")
Fabricate(:user, username: "bill4")
# the number should be preserved during subsequent logins
# bill3 should remain bill3
user.update!(username: "bill3")
uid = "12345"
UserAssociatedAccount.create!(
provider_name: "google_oauth2",
user_id: user.id,
provider_uid: uid,
)
mock_auth(user.email, "bill", uid)
get "/auth/google_oauth2/callback.json"
user.reload
expect(user.username).to eq("bill3")
end
it "will not update email if not verified" do
SiteSetting.email_editable = false
SiteSetting.auth_overrides_email = true
OmniAuth.config.mock_auth[:google_oauth2][:extra][:raw_info][:email_verified] = false
UserAssociatedAccount.create!(
provider_name: "google_oauth2",
user_id: user.id,
provider_uid: "123545",
)
old_email = user.email
user.update!(email: "[email protected]")
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
user.reload
expect(user.email).to eq("[email protected]")
end
it "shows error when auth_overrides_email causes a validation error" do
SiteSetting.email_editable = false
SiteSetting.auth_overrides_email = true
UserAssociatedAccount.create!(
provider_name: "google_oauth2",
user_id: user.id,
provider_uid: uid,
)
google_email = user.email
user.update!(email: "[email protected]")
Fabricate(:user, email: google_email) # Another user has the google account email
get "/auth/google_oauth2/callback"
expect(response.status).to eq(200)
expect(response.body).to include(I18n.t("errors.messages.taken"))
expect(session[:current_user_id]).to eq(nil)
user.reload
expect(user.email).to eq("[email protected]")
end
context "when user has TOTP enabled" do
before { user.create_totp(enabled: true) }
it "should return the right response" do
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
data = JSON.parse(cookies[:authentication_data])
expect(data["email"]).to eq(user.email)
expect(data["omniauth_disallow_totp"]).to eq(true)
user.update!(email: "[email protected]")
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
expect(JSON.parse(cookies[:authentication_data])["email"]).to eq(user.email)
end
end
context "when user has security key enabled" do
before { Fabricate(:user_security_key_with_random_credential, user: user) }
it "should return the right response" do
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
data = JSON.parse(cookies[:authentication_data])
expect(data["email"]).to eq(user.email)
expect(data["omniauth_disallow_totp"]).to eq(true)
user.update!(email: "[email protected]")
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
expect(JSON.parse(cookies[:authentication_data])["email"]).to eq(user.email)
end
end
context "when sso_payload cookie exist" do
before do
SiteSetting.enable_discourse_connect_provider = true
SiteSetting.discourse_connect_secret = "topsecret"
@sso = DiscourseConnectBase.new
@sso.nonce = "mynonce"
@sso.sso_secret = SiteSetting.discourse_connect_secret
@sso.return_sso_url = "http://somewhere.over.rainbow/sso"
cookies[:sso_payload] = @sso.payload
provider_uid = 12_345
UserAssociatedAccount.create!(
provider_name: "google_oauth2",
provider_uid: provider_uid,
user: user,
)
mock_auth(user.email, nil, nil, provider_uid)
end
it "should return the right response" do
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
data = JSON.parse(cookies[:authentication_data])
expect(data["destination_url"]).to match(%r{/session/sso_provider\?sso\=.*\&sig\=.*})
end
end
context "when user has not verified his email" do
before do
provider_uid = "12345"
UserAssociatedAccount.create!(
provider_name: "google_oauth2",
provider_uid: provider_uid,
user: user,
)
user.update!(active: false)
another_email = "[email protected]"
mock_auth(another_email, nil, nil, provider_uid)
end
it "should return the right response" do
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
data = JSON.parse(cookies[:authentication_data])
expect(user.reload.active).to eq(false)
expect(data["authenticated"]).to eq(false)
expect(data["awaiting_activation"]).to eq(true)
end
end
it "doesn't attempt redirect to external origin" do
post "/auth/google_oauth2?origin=https://example.com/external"
get "/auth/google_oauth2/callback"
expect(response.status).to eq 302
expect(response.location).to eq "http://test.localhost/"
cookie_data = JSON.parse(response.cookies["authentication_data"])
expect(cookie_data["destination_url"]).to eq("/")
end
it "redirects to internal origin" do
post "/auth/google_oauth2?origin=http://test.localhost/t/123"
get "/auth/google_oauth2/callback"
expect(response.status).to eq 302
expect(response.location).to eq "http://test.localhost/t/123"
cookie_data = JSON.parse(response.cookies["authentication_data"])
expect(cookie_data["destination_url"]).to eq("/t/123")
end
it "redirects to internal origin on subfolder" do
set_subfolder "/subpath"
post "/auth/google_oauth2?origin=http://test.localhost/subpath/t/123"
get "/auth/google_oauth2/callback"
expect(response.status).to eq 302
expect(response.location).to eq "http://test.localhost/subpath/t/123"
cookie_data = JSON.parse(response.cookies["authentication_data"])
expect(cookie_data["destination_url"]).to eq("/subpath/t/123")
end
it "never redirects to /auth/ origin" do
post "/auth/google_oauth2?origin=http://test.localhost/auth/google_oauth2"
get "/auth/google_oauth2/callback"
expect(response.status).to eq 302
expect(response.location).to eq "http://test.localhost/"
cookie_data = JSON.parse(response.cookies["authentication_data"])
expect(cookie_data["destination_url"]).to eq("/")
end
it "never redirects to /auth/ origin on subfolder" do
set_subfolder "/subpath"
post "/auth/google_oauth2?origin=http://test.localhost/subpath/auth/google_oauth2"
get "/auth/google_oauth2/callback"
expect(response.status).to eq 302
expect(response.location).to eq "http://test.localhost/subpath"
cookie_data = JSON.parse(response.cookies["authentication_data"])
expect(cookie_data["destination_url"]).to eq("/subpath")
end
it "redirects to relative origin" do
post "/auth/google_oauth2?origin=/t/123"
get "/auth/google_oauth2/callback"
expect(response.status).to eq 302
expect(response.location).to eq "http://test.localhost/t/123"
cookie_data = JSON.parse(response.cookies["authentication_data"])
expect(cookie_data["destination_url"]).to eq("/t/123")
end
it "redirects with query" do
post "/auth/google_oauth2?origin=/t/123?foo=bar"
get "/auth/google_oauth2/callback"
expect(response.status).to eq 302
expect(response.location).to eq "http://test.localhost/t/123?foo=bar"
cookie_data = JSON.parse(response.cookies["authentication_data"])
expect(cookie_data["destination_url"]).to eq("/t/123?foo=bar")
end
it "removes authentication_data cookie on logout" do
post "/auth/google_oauth2?origin=https://example.com/external"
get "/auth/google_oauth2/callback"
provider = log_in_user(Fabricate(:user))
expect(cookies["authentication_data"]).to be
log_out_user(provider)
expect(cookies["authentication_data"]).to be_nil
end
it "removes disallowed characters from username" do
username = "strange_name*&^"
fixed_username = "strange_name"
mock_auth("[email protected]", username)
get "/auth/google_oauth2/callback.json"
data = JSON.parse(cookies[:authentication_data])
expect(data["username"]).to eq(fixed_username)
end
context "when groups are enabled" do
let(:private_key) { OpenSSL::PKey::RSA.generate(2048) }
let(:group1) { { id: "12345", name: "group1" } }
let(:group2) { { id: "67890", name: "group2" } }
let(:uid) { "12345" }
let(:token) { "1245678" }
let(:domain) { "mydomain.com" }
def mock_omniauth_for_groups(groups)
mock_auth = OmniAuth.config.mock_auth[:google_oauth2]
OmniAuth.config.mock_auth[:google_oauth2] = mock_auth
Rails.application.env_config["omniauth.auth"] = mock_auth
SiteSetting.google_oauth2_hd_groups_service_account_admin_email = "[email protected]"
SiteSetting.google_oauth2_hd_groups_service_account_json = {
"private_key" => private_key.to_s,
:"client_email" => "[email protected]",
}.to_json
SiteSetting.google_oauth2_hd_groups = true
stub_request(:post, "https://oauth2.googleapis.com/token").to_return do |request|
jwt = Rack::Utils.parse_query(request.body)["assertion"]
decoded_token = JWT.decode(jwt, private_key.public_key, true, { algorithm: "RS256" })
{
status: 200,
body: { "access_token" => token, "type" => "bearer" }.to_json,
headers: {
"Content-Type" => "application/json",
},
}
end
stub_request(
:get,
"https://admin.googleapis.com/admin/directory/v1/groups?userKey=#{mock_auth.uid}",
)
.with(headers: { "Authorization" => "Bearer #{token}" })
.to_return do
{
status: 200,
body: { groups: groups }.to_json,
headers: {
"Content-Type" => "application/json",
},
}
end
end
before do
SiteSetting.google_oauth2_hd = domain
SiteSetting.google_oauth2_hd_groups_service_account_admin_email = "[email protected]"
SiteSetting.google_oauth2_hd_groups_service_account_json = "{}"
SiteSetting.google_oauth2_hd_groups = true
end
it "updates associated groups" do
mock_omniauth_for_groups([group1, group2])
get "/auth/google_oauth2/callback.json", params: { code: "abcde", hd: domain }
expect(response.status).to eq(302)
associated_groups = AssociatedGroup.where(provider_name: "google_oauth2")
expect(associated_groups.length).to eq(2)
expect(associated_groups.exists?(name: group1[:name])).to eq(true)
expect(associated_groups.exists?(name: group2[:name])).to eq(true)
user_associated_groups = UserAssociatedGroup.where(user_id: user.id)
expect(user_associated_groups.length).to eq(2)
expect(
user_associated_groups.exists?(associated_group_id: associated_groups.first.id),
).to eq(true)
expect(
user_associated_groups.exists?(associated_group_id: associated_groups.second.id),
).to eq(true)
mock_omniauth_for_groups([group1])
get "/auth/google_oauth2/callback.json", params: { code: "abcde", hd: domain }
expect(response.status).to eq(302)
user_associated_groups = UserAssociatedGroup.where(user_id: user.id)
expect(user_associated_groups.length).to eq(1)
expect(
user_associated_groups.exists?(associated_group_id: associated_groups.first.id),
).to eq(true)
expect(
user_associated_groups.exists?(associated_group_id: associated_groups.second.id),
).to eq(false)
mock_omniauth_for_groups([])
get "/auth/google_oauth2/callback.json", params: { code: "abcde", hd: domain }
expect(response.status).to eq(302)
user_associated_groups = UserAssociatedGroup.where(user_id: user.id)
expect(user_associated_groups.length).to eq(0)
expect(
user_associated_groups.exists?(associated_group_id: associated_groups.first.id),
).to eq(false)
expect(
user_associated_groups.exists?(associated_group_id: associated_groups.second.id),
).to eq(false)
end
it "handles failure to retrieve groups" do
mock_omniauth_for_groups([])
get "/auth/google_oauth2/callback.json", params: { code: "abcde", hd: domain }
expect(response.status).to eq(302)
associated_groups = AssociatedGroup.where(provider_name: "google_oauth2")
expect(associated_groups.exists?).to eq(false)
end
end
end
context "when attempting reconnect" do
fab!(:user2) { Fabricate(:user) }
let(:user1_provider_id) { "12345" }
let(:user2_provider_id) { "123456" }
before do
UserAssociatedAccount.create!(
provider_name: "google_oauth2",
provider_uid: user1_provider_id,
user: user,
)
UserAssociatedAccount.create!(
provider_name: "google_oauth2",
provider_uid: user2_provider_id,
user: user2,
)
mock_auth("[email protected]", nil, nil, user1_provider_id)
end
it "should not reconnect normally" do
# Log in normally
post "/auth/google_oauth2"
expect(response.status).to eq(302)
expect(session[:auth_reconnect]).to eq(false)
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
expect(session[:current_user_id]).to eq(user.id)
# Log into another user
OmniAuth.config.mock_auth[:google_oauth2].uid = user2_provider_id
post "/auth/google_oauth2"
expect(response.status).to eq(302)
expect(session[:auth_reconnect]).to eq(false)
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
expect(session[:current_user_id]).to eq(user2.id)
expect(UserAssociatedAccount.count).to eq(2)
end
it "should redirect to associate URL if parameter supplied" do
# Log in normally
post "/auth/google_oauth2?reconnect=true"
expect(response.status).to eq(302)
expect(session[:auth_reconnect]).to eq(true)
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)
expect(session[:current_user_id]).to eq(user.id)
# Clear cookie after login
expect(session[:auth_reconnect]).to eq(nil)
# Disconnect
UserAssociatedAccount.find_by(user_id: user.id).destroy
# Reconnect flow:
post "/auth/google_oauth2?reconnect=true"
expect(response.status).to eq(302)
expect(session[:auth_reconnect]).to eq(true)
OmniAuth.config.mock_auth[:google_oauth2].uid = user2_provider_id
get "/auth/google_oauth2/callback.json"
expect(response.status).to eq(302)