summaryrefslogtreecommitdiff
path: root/test/pleroma/web/o_auth/o_auth_controller_test.exs
blob: 0fdd5b8e9fb853e6cd2f4a84ef6eb1ad39030292 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
# Pleroma: A lightweight social networking server
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Web.OAuth.OAuthControllerTest do
  use Pleroma.Web.ConnCase

  import Pleroma.Factory

  alias Pleroma.Helpers.AuthHelper
  alias Pleroma.MFA
  alias Pleroma.MFA.TOTP
  alias Pleroma.Repo
  alias Pleroma.User
  alias Pleroma.Web.OAuth.Authorization
  alias Pleroma.Web.OAuth.OAuthController
  alias Pleroma.Web.OAuth.Token

  @session_opts [
    store: :cookie,
    key: "_test",
    signing_salt: "cooldude"
  ]
  setup do
    clear_config([:instance, :account_activation_required])
    clear_config([:instance, :account_approval_required])
  end

  describe "in OAuth consumer mode, " do
    setup do
      [
        app: insert(:oauth_app),
        conn:
          build_conn()
          |> Plug.Session.call(Plug.Session.init(@session_opts))
          |> fetch_session()
      ]
    end

    setup do: clear_config([:auth, :oauth_consumer_strategies], ~w(twitter facebook))

    test "GET /oauth/authorize renders auth forms, including OAuth consumer form", %{
      app: app,
      conn: conn
    } do
      conn =
        get(
          conn,
          "/oauth/authorize",
          %{
            "response_type" => "code",
            "client_id" => app.client_id,
            "redirect_uri" => OAuthController.default_redirect_uri(app),
            "scope" => "read"
          }
        )

      assert response = html_response(conn, 200)
      assert response =~ "Sign in with Twitter"
      assert response =~ o_auth_path(conn, :prepare_request)
    end

    test "GET /oauth/prepare_request encodes parameters as `state` and redirects", %{
      app: app,
      conn: conn
    } do
      conn =
        get(
          conn,
          "/oauth/prepare_request",
          %{
            "provider" => "twitter",
            "authorization" => %{
              "scope" => "read follow",
              "client_id" => app.client_id,
              "redirect_uri" => OAuthController.default_redirect_uri(app),
              "state" => "a_state"
            }
          }
        )

      assert html_response(conn, 302)

      redirect_query = URI.parse(redirected_to(conn)).query
      assert %{"state" => state_param} = URI.decode_query(redirect_query)
      assert {:ok, state_components} = Jason.decode(state_param)

      expected_client_id = app.client_id
      expected_redirect_uri = app.redirect_uris

      assert %{
               "scope" => "read follow",
               "client_id" => ^expected_client_id,
               "redirect_uri" => ^expected_redirect_uri,
               "state" => "a_state"
             } = state_components
    end

    test "with user-bound registration, GET /oauth/<provider>/callback redirects to `redirect_uri` with `code`",
         %{app: app, conn: conn} do
      registration = insert(:registration)
      redirect_uri = OAuthController.default_redirect_uri(app)

      state_params = %{
        "scope" => Enum.join(app.scopes, " "),
        "client_id" => app.client_id,
        "redirect_uri" => redirect_uri,
        "state" => ""
      }

      conn =
        conn
        |> assign(:ueberauth_auth, %{provider: registration.provider, uid: registration.uid})
        |> get(
          "/oauth/twitter/callback",
          %{
            "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
            "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
            "provider" => "twitter",
            "state" => Jason.encode!(state_params)
          }
        )

      assert html_response(conn, 302)
      assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
    end

    test "with user-unbound registration, GET /oauth/<provider>/callback renders registration_details page",
         %{app: app, conn: conn} do
      user = insert(:user)

      state_params = %{
        "scope" => "read write",
        "client_id" => app.client_id,
        "redirect_uri" => OAuthController.default_redirect_uri(app),
        "state" => "a_state"
      }

      conn =
        conn
        |> assign(:ueberauth_auth, %{
          provider: "twitter",
          uid: "171799000",
          info: %{nickname: user.nickname, email: user.email, name: user.name, description: nil}
        })
        |> get(
          "/oauth/twitter/callback",
          %{
            "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
            "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
            "provider" => "twitter",
            "state" => Jason.encode!(state_params)
          }
        )

      assert response = html_response(conn, 200)
      assert response =~ ~r/name="op" type="submit" value="register"/
      assert response =~ ~r/name="op" type="submit" value="connect"/
      assert response =~ user.email
      assert response =~ user.nickname
    end

    test "on authentication error, GET /oauth/<provider>/callback redirects to `redirect_uri`", %{
      app: app,
      conn: conn
    } do
      state_params = %{
        "scope" => Enum.join(app.scopes, " "),
        "client_id" => app.client_id,
        "redirect_uri" => OAuthController.default_redirect_uri(app),
        "state" => ""
      }

      conn =
        conn
        |> assign(:ueberauth_failure, %{errors: [%{message: "(error description)"}]})
        |> get(
          "/oauth/twitter/callback",
          %{
            "oauth_token" => "G-5a3AAAAAAAwMH9AAABaektfSM",
            "oauth_verifier" => "QZl8vUqNvXMTKpdmUnGejJxuHG75WWWs",
            "provider" => "twitter",
            "state" => Jason.encode!(state_params)
          }
        )

      assert html_response(conn, 302)
      assert redirected_to(conn) == app.redirect_uris
      assert get_flash(conn, :error) == "Failed to authenticate: (error description)."
    end

    test "GET /oauth/registration_details renders registration details form", %{
      app: app,
      conn: conn
    } do
      conn =
        get(
          conn,
          "/oauth/registration_details",
          %{
            "authorization" => %{
              "scopes" => app.scopes,
              "client_id" => app.client_id,
              "redirect_uri" => OAuthController.default_redirect_uri(app),
              "state" => "a_state",
              "nickname" => nil,
              "email" => "john@doe.com"
            }
          }
        )

      assert response = html_response(conn, 200)
      assert response =~ ~r/name="op" type="submit" value="register"/
      assert response =~ ~r/name="op" type="submit" value="connect"/
    end

    test "with valid params, POST /oauth/register?op=register redirects to `redirect_uri` with `code`",
         %{
           app: app,
           conn: conn
         } do
      registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
      redirect_uri = OAuthController.default_redirect_uri(app)

      conn =
        conn
        |> put_session(:registration_id, registration.id)
        |> post(
          "/oauth/register",
          %{
            "op" => "register",
            "authorization" => %{
              "scopes" => app.scopes,
              "client_id" => app.client_id,
              "redirect_uri" => redirect_uri,
              "state" => "a_state",
              "nickname" => "availablenick",
              "email" => "available@email.com"
            }
          }
        )

      assert html_response(conn, 302)
      assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
    end

    test "with unlisted `redirect_uri`, POST /oauth/register?op=register results in HTTP 401",
         %{
           app: app,
           conn: conn
         } do
      registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})
      unlisted_redirect_uri = "http://cross-site-request.com"

      conn =
        conn
        |> put_session(:registration_id, registration.id)
        |> post(
          "/oauth/register",
          %{
            "op" => "register",
            "authorization" => %{
              "scopes" => app.scopes,
              "client_id" => app.client_id,
              "redirect_uri" => unlisted_redirect_uri,
              "state" => "a_state",
              "nickname" => "availablenick",
              "email" => "available@email.com"
            }
          }
        )

      assert html_response(conn, 401)
    end

    test "with invalid params, POST /oauth/register?op=register renders registration_details page",
         %{
           app: app,
           conn: conn
         } do
      another_user = insert(:user)
      registration = insert(:registration, user: nil, info: %{"nickname" => nil, "email" => nil})

      params = %{
        "op" => "register",
        "authorization" => %{
          "scopes" => app.scopes,
          "client_id" => app.client_id,
          "redirect_uri" => OAuthController.default_redirect_uri(app),
          "state" => "a_state",
          "nickname" => "availablenickname",
          "email" => "available@email.com"
        }
      }

      for {bad_param, bad_param_value} <-
            [{"nickname", another_user.nickname}, {"email", another_user.email}] do
        bad_registration_attrs = %{
          "authorization" => Map.put(params["authorization"], bad_param, bad_param_value)
        }

        bad_params = Map.merge(params, bad_registration_attrs)

        conn =
          conn
          |> put_session(:registration_id, registration.id)
          |> post("/oauth/register", bad_params)

        assert html_response(conn, 403) =~ ~r/name="op" type="submit" value="register"/
        assert get_flash(conn, :error) == "Error: #{bad_param} has already been taken."
      end
    end

    test "with valid params, POST /oauth/register?op=connect redirects to `redirect_uri` with `code`",
         %{
           app: app,
           conn: conn
         } do
      user = insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt("testpassword"))
      registration = insert(:registration, user: nil)
      redirect_uri = OAuthController.default_redirect_uri(app)

      conn =
        conn
        |> put_session(:registration_id, registration.id)
        |> post(
          "/oauth/register",
          %{
            "op" => "connect",
            "authorization" => %{
              "scopes" => app.scopes,
              "client_id" => app.client_id,
              "redirect_uri" => redirect_uri,
              "state" => "a_state",
              "name" => user.nickname,
              "password" => "testpassword"
            }
          }
        )

      assert html_response(conn, 302)
      assert redirected_to(conn) =~ ~r/#{redirect_uri}\?code=.+/
    end

    test "with unlisted `redirect_uri`, POST /oauth/register?op=connect results in HTTP 401`",
         %{
           app: app,
           conn: conn
         } do
      user = insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt("testpassword"))
      registration = insert(:registration, user: nil)
      unlisted_redirect_uri = "http://cross-site-request.com"

      conn =
        conn
        |> put_session(:registration_id, registration.id)
        |> post(
          "/oauth/register",
          %{
            "op" => "connect",
            "authorization" => %{
              "scopes" => app.scopes,
              "client_id" => app.client_id,
              "redirect_uri" => unlisted_redirect_uri,
              "state" => "a_state",
              "name" => user.nickname,
              "password" => "testpassword"
            }
          }
        )

      assert html_response(conn, 401)
    end

    test "with invalid params, POST /oauth/register?op=connect renders registration_details page",
         %{
           app: app,
           conn: conn
         } do
      user = insert(:user)
      registration = insert(:registration, user: nil)

      params = %{
        "op" => "connect",
        "authorization" => %{
          "scopes" => app.scopes,
          "client_id" => app.client_id,
          "redirect_uri" => OAuthController.default_redirect_uri(app),
          "state" => "a_state",
          "name" => user.nickname,
          "password" => "wrong password"
        }
      }

      conn =
        conn
        |> put_session(:registration_id, registration.id)
        |> post("/oauth/register", params)

      assert html_response(conn, 401) =~ ~r/name="op" type="submit" value="connect"/
      assert get_flash(conn, :error) == "Invalid Username/Password"
    end
  end

  describe "GET /oauth/authorize" do
    setup do
      [
        app: insert(:oauth_app, redirect_uris: "https://redirect.url"),
        conn:
          build_conn()
          |> Plug.Session.call(Plug.Session.init(@session_opts))
          |> fetch_session()
      ]
    end

    test "renders authentication page", %{app: app, conn: conn} do
      conn =
        get(
          conn,
          "/oauth/authorize",
          %{
            "response_type" => "code",
            "client_id" => app.client_id,
            "redirect_uri" => OAuthController.default_redirect_uri(app),
            "scope" => "read"
          }
        )

      assert html_response(conn, 200) =~ ~s(type="submit")
    end

    test "properly handles internal calls with `authorization`-wrapped params", %{
      app: app,
      conn: conn
    } do
      conn =
        get(
          conn,
          "/oauth/authorize",
          %{
            "authorization" => %{
              "response_type" => "code",
              "client_id" => app.client_id,
              "redirect_uri" => OAuthController.default_redirect_uri(app),
              "scope" => "read"
            }
          }
        )

      assert html_response(conn, 200) =~ ~s(type="submit")
    end

    test "renders authentication page if user is already authenticated but `force_login` is tru-ish",
         %{app: app, conn: conn} do
      token = insert(:oauth_token, app: app)

      conn =
        conn
        |> AuthHelper.put_session_token(token.token)
        |> get(
          "/oauth/authorize",
          %{
            "response_type" => "code",
            "client_id" => app.client_id,
            "redirect_uri" => OAuthController.default_redirect_uri(app),
            "scope" => "read",
            "force_login" => "true"
          }
        )

      assert html_response(conn, 200) =~ ~s(type="submit")
    end

    test "renders authentication page if user is already authenticated but user request with another client",
         %{
           app: app,
           conn: conn
         } do
      token = insert(:oauth_token, app: app)

      conn =
        conn
        |> AuthHelper.put_session_token(token.token)
        |> get(
          "/oauth/authorize",
          %{
            "response_type" => "code",
            "client_id" => "another_client_id",
            "redirect_uri" => OAuthController.default_redirect_uri(app),
            "scope" => "read"
          }
        )

      assert html_response(conn, 200) =~ ~s(type="submit")
    end

    test "with existing authentication and non-OOB `redirect_uri`, redirects to app with `token` and `state` params",
         %{
           app: app,
           conn: conn
         } do
      token = insert(:oauth_token, app: app)

      conn =
        conn
        |> AuthHelper.put_session_token(token.token)
        |> get(
          "/oauth/authorize",
          %{
            "response_type" => "code",
            "client_id" => app.client_id,
            "redirect_uri" => OAuthController.default_redirect_uri(app),
            "state" => "specific_client_state",
            "scope" => "read"
          }
        )

      assert URI.decode(redirected_to(conn)) ==
               "https://redirect.url?access_token=#{token.token}&state=specific_client_state"
    end

    test "with existing authentication and unlisted non-OOB `redirect_uri`, redirects without credentials",
         %{
           app: app,
           conn: conn
         } do
      unlisted_redirect_uri = "http://cross-site-request.com"
      token = insert(:oauth_token, app: app)

      conn =
        conn
        |> AuthHelper.put_session_token(token.token)
        |> get(
          "/oauth/authorize",
          %{
            "response_type" => "code",
            "client_id" => app.client_id,
            "redirect_uri" => unlisted_redirect_uri,
            "state" => "specific_client_state",
            "scope" => "read"
          }
        )

      assert redirected_to(conn) == unlisted_redirect_uri
    end

    test "with existing authentication and OOB `redirect_uri`, redirects to app with `token` and `state` params",
         %{
           app: app,
           conn: conn
         } do
      token = insert(:oauth_token, app: app)

      conn =
        conn
        |> AuthHelper.put_session_token(token.token)
        |> get(
          "/oauth/authorize",
          %{
            "response_type" => "code",
            "client_id" => app.client_id,
            "redirect_uri" => "urn:ietf:wg:oauth:2.0:oob",
            "scope" => "read"
          }
        )

      assert html_response(conn, 200) =~ "Authorization exists"
    end
  end

  describe "POST /oauth/authorize" do
    test "redirects with oauth authorization, " <>
           "granting requested app-supported scopes to both admin- and non-admin users" do
      app_scopes = ["read", "write", "admin", "secret_scope"]
      app = insert(:oauth_app, scopes: app_scopes)
      redirect_uri = OAuthController.default_redirect_uri(app)

      non_admin = insert(:user, is_admin: false)
      admin = insert(:user, is_admin: true)
      scopes_subset = ["read:subscope", "write", "admin"]

      # In case scope param is missing, expecting _all_ app-supported scopes to be granted
      for user <- [non_admin, admin],
          {requested_scopes, expected_scopes} <-
            %{scopes_subset => scopes_subset, nil: app_scopes} do
        conn =
          post(
            build_conn(),
            "/oauth/authorize",
            %{
              "authorization" => %{
                "name" => user.nickname,
                "password" => "test",
                "client_id" => app.client_id,
                "redirect_uri" => redirect_uri,
                "scope" => requested_scopes,
                "state" => "statepassed"
              }
            }
          )

        target = redirected_to(conn)
        assert target =~ redirect_uri

        query = URI.parse(target).query |> URI.query_decoder() |> Map.new()

        assert %{"state" => "statepassed", "code" => code} = query
        auth = Repo.get_by(Authorization, token: code)
        assert auth
        assert auth.scopes == expected_scopes
      end
    end

    test "authorize from cookie" do
      user = insert(:user)
      app = insert(:oauth_app)
      oauth_token = insert(:oauth_token, user: user, app: app)
      redirect_uri = OAuthController.default_redirect_uri(app)

      conn =
        build_conn()
        |> Plug.Session.call(Plug.Session.init(@session_opts))
        |> fetch_session()
        |> AuthHelper.put_session_token(oauth_token.token)
        |> post(
          "/oauth/authorize",
          %{
            "authorization" => %{
              "name" => user.nickname,
              "client_id" => app.client_id,
              "redirect_uri" => redirect_uri,
              "scope" => app.scopes,
              "state" => "statepassed"
            }
          }
        )

      target = redirected_to(conn)
      assert target =~ redirect_uri

      query = URI.parse(target).query |> URI.query_decoder() |> Map.new()

      assert %{"state" => "statepassed", "code" => code} = query
      auth = Repo.get_by(Authorization, token: code)
      assert auth
      assert auth.scopes == app.scopes
    end

    test "redirect to on two-factor auth page" do
      otp_secret = TOTP.generate_secret()

      user =
        insert(:user,
          multi_factor_authentication_settings: %MFA.Settings{
            enabled: true,
            totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
          }
        )

      app = insert(:oauth_app, scopes: ["read", "write", "follow"])

      conn =
        build_conn()
        |> post("/oauth/authorize", %{
          "authorization" => %{
            "name" => user.nickname,
            "password" => "test",
            "client_id" => app.client_id,
            "redirect_uri" => app.redirect_uris,
            "scope" => "read write",
            "state" => "statepassed"
          }
        })

      result = html_response(conn, 200)

      mfa_token = Repo.get_by(MFA.Token, user_id: user.id)
      assert result =~ app.redirect_uris
      assert result =~ "statepassed"
      assert result =~ mfa_token.token
      assert result =~ "Two-factor authentication"
    end

    test "returns 401 for wrong credentials", %{conn: conn} do
      user = insert(:user)
      app = insert(:oauth_app)
      redirect_uri = OAuthController.default_redirect_uri(app)

      result =
        conn
        |> post("/oauth/authorize", %{
          "authorization" => %{
            "name" => user.nickname,
            "password" => "wrong",
            "client_id" => app.client_id,
            "redirect_uri" => redirect_uri,
            "state" => "statepassed",
            "scope" => Enum.join(app.scopes, " ")
          }
        })
        |> html_response(:unauthorized)

      # Keep the details
      assert result =~ app.client_id
      assert result =~ redirect_uri

      # Error message
      assert result =~ "Invalid Username/Password"
    end

    test "returns 401 for missing scopes" do
      user = insert(:user, is_admin: false)
      app = insert(:oauth_app, scopes: ["read", "write", "admin"])
      redirect_uri = OAuthController.default_redirect_uri(app)

      result =
        build_conn()
        |> post("/oauth/authorize", %{
          "authorization" => %{
            "name" => user.nickname,
            "password" => "test",
            "client_id" => app.client_id,
            "redirect_uri" => redirect_uri,
            "state" => "statepassed",
            "scope" => ""
          }
        })
        |> html_response(:unauthorized)

      # Keep the details
      assert result =~ app.client_id
      assert result =~ redirect_uri

      # Error message
      assert result =~ "This action is outside the authorized scopes"
    end

    test "returns 401 for scopes beyond app scopes hierarchy", %{conn: conn} do
      user = insert(:user)
      app = insert(:oauth_app, scopes: ["read", "write"])
      redirect_uri = OAuthController.default_redirect_uri(app)

      result =
        conn
        |> post("/oauth/authorize", %{
          "authorization" => %{
            "name" => user.nickname,
            "password" => "test",
            "client_id" => app.client_id,
            "redirect_uri" => redirect_uri,
            "state" => "statepassed",
            "scope" => "read write follow"
          }
        })
        |> html_response(:unauthorized)

      # Keep the details
      assert result =~ app.client_id
      assert result =~ redirect_uri

      # Error message
      assert result =~ "This action is outside the authorized scopes"
    end
  end

  describe "POST /oauth/token" do
    test "issues a token for an all-body request" do
      user = insert(:user)
      app = insert(:oauth_app, scopes: ["read", "write"])

      {:ok, auth} = Authorization.create_authorization(app, user, ["write"])

      conn =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "authorization_code",
          "code" => auth.token,
          "redirect_uri" => OAuthController.default_redirect_uri(app),
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })

      assert %{"access_token" => token, "me" => ap_id} = json_response(conn, 200)

      token = Repo.get_by(Token, token: token)
      assert token
      assert token.scopes == auth.scopes
      assert user.ap_id == ap_id
    end

    test "issues a token for `password` grant_type with valid credentials, with full permissions by default" do
      password = "testpassword"
      user = insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password))

      app = insert(:oauth_app, scopes: ["read", "write"])

      # Note: "scope" param is intentionally omitted
      conn =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "password",
          "username" => user.nickname,
          "password" => password,
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })

      assert %{"id" => id, "access_token" => access_token} = json_response(conn, 200)

      token = Repo.get_by(Token, token: access_token)
      assert token
      assert token.id == id
      assert token.token == access_token
      assert token.scopes == app.scopes
    end

    test "issues a mfa token for `password` grant_type, when MFA enabled" do
      password = "testpassword"
      otp_secret = TOTP.generate_secret()

      user =
        insert(:user,
          password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
          multi_factor_authentication_settings: %MFA.Settings{
            enabled: true,
            totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}
          }
        )

      app = insert(:oauth_app, scopes: ["read", "write"])

      response =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "password",
          "username" => user.nickname,
          "password" => password,
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })
        |> json_response(403)

      assert match?(
               %{
                 "supported_challenge_types" => "totp",
                 "mfa_token" => _,
                 "error" => "mfa_required"
               },
               response
             )

      token = Repo.get_by(MFA.Token, token: response["mfa_token"])
      assert token.user_id == user.id
      assert token.authorization_id
    end

    test "issues a token for request with HTTP basic auth client credentials" do
      user = insert(:user)
      app = insert(:oauth_app, scopes: ["scope1", "scope2", "scope3"])

      {:ok, auth} = Authorization.create_authorization(app, user, ["scope1", "scope2"])
      assert auth.scopes == ["scope1", "scope2"]

      app_encoded =
        (URI.encode_www_form(app.client_id) <> ":" <> URI.encode_www_form(app.client_secret))
        |> Base.encode64()

      conn =
        build_conn()
        |> put_req_header("authorization", "Basic " <> app_encoded)
        |> post("/oauth/token", %{
          "grant_type" => "authorization_code",
          "code" => auth.token,
          "redirect_uri" => OAuthController.default_redirect_uri(app)
        })

      assert %{"access_token" => token, "scope" => scope} = json_response(conn, 200)

      assert scope == "scope1 scope2"

      token = Repo.get_by(Token, token: token)
      assert token
      assert token.scopes == ["scope1", "scope2"]
    end

    test "issue a token for client_credentials grant type" do
      app = insert(:oauth_app, scopes: ["read", "write"])

      conn =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "client_credentials",
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })

      assert %{"access_token" => token, "refresh_token" => refresh, "scope" => scope} =
               json_response(conn, 200)

      assert token
      token_from_db = Repo.get_by(Token, token: token)
      assert token_from_db
      assert refresh
      assert scope == "read write"
    end

    test "rejects token exchange with invalid client credentials" do
      user = insert(:user)
      app = insert(:oauth_app)

      {:ok, auth} = Authorization.create_authorization(app, user)

      conn =
        build_conn()
        |> put_req_header("authorization", "Basic JTIxOiVGMCU5RiVBNCVCNwo=")
        |> post("/oauth/token", %{
          "grant_type" => "authorization_code",
          "code" => auth.token,
          "redirect_uri" => OAuthController.default_redirect_uri(app)
        })

      assert resp = json_response(conn, 400)
      assert %{"error" => _} = resp
      refute Map.has_key?(resp, "access_token")
    end

    test "rejects token exchange for valid credentials belonging to unconfirmed user and confirmation is required" do
      clear_config([:instance, :account_activation_required], true)
      password = "testpassword"

      {:ok, user} =
        insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password))
        |> User.confirmation_changeset(set_confirmation: false)
        |> User.update_and_set_cache()

      refute Pleroma.User.account_status(user) == :active

      app = insert(:oauth_app)

      conn =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "password",
          "username" => user.nickname,
          "password" => password,
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })

      assert resp = json_response(conn, 403)
      assert %{"error" => _} = resp
      refute Map.has_key?(resp, "access_token")
    end

    test "rejects token exchange for valid credentials belonging to deactivated user" do
      password = "testpassword"

      user =
        insert(:user,
          password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
          is_active: false
        )

      app = insert(:oauth_app)

      resp =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "password",
          "username" => user.nickname,
          "password" => password,
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })
        |> json_response(403)

      assert resp == %{
               "error" => "Your account is currently disabled",
               "identifier" => "account_is_disabled"
             }
    end

    test "rejects token exchange for user with password_reset_pending set to true" do
      password = "testpassword"

      user =
        insert(:user,
          password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
          password_reset_pending: true
        )

      app = insert(:oauth_app, scopes: ["read", "write"])

      resp =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "password",
          "username" => user.nickname,
          "password" => password,
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })
        |> json_response(403)

      assert resp == %{
               "error" => "Password reset is required",
               "identifier" => "password_reset_required"
             }
    end

    test "rejects token exchange for user with confirmation_pending set to true" do
      clear_config([:instance, :account_activation_required], true)
      password = "testpassword"

      user =
        insert(:user,
          password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
          is_confirmed: false
        )

      app = insert(:oauth_app, scopes: ["read", "write"])

      resp =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "password",
          "username" => user.nickname,
          "password" => password,
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })
        |> json_response(403)

      assert resp == %{
               "error" => "Your login is missing a confirmed e-mail address",
               "identifier" => "missing_confirmed_email"
             }
    end

    test "rejects token exchange for valid credentials belonging to an unapproved user" do
      password = "testpassword"

      user =
        insert(:user,
          password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),
          is_approved: false
        )

      refute Pleroma.User.account_status(user) == :active

      app = insert(:oauth_app)

      conn =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "password",
          "username" => user.nickname,
          "password" => password,
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })

      assert resp = json_response(conn, 403)
      assert %{"error" => _} = resp
      refute Map.has_key?(resp, "access_token")
    end

    test "rejects an invalid authorization code" do
      app = insert(:oauth_app)

      conn =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "authorization_code",
          "code" => "Imobviouslyinvalid",
          "redirect_uri" => OAuthController.default_redirect_uri(app),
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })

      assert resp = json_response(conn, 400)
      assert %{"error" => _} = json_response(conn, 400)
      refute Map.has_key?(resp, "access_token")
    end
  end

  describe "POST /oauth/token - refresh token" do
    setup do: clear_config([:oauth2, :issue_new_refresh_token])

    test "issues a new access token with keep fresh token" do
      clear_config([:oauth2, :issue_new_refresh_token], true)
      user = insert(:user)
      app = insert(:oauth_app, scopes: ["read", "write"])

      {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
      {:ok, token} = Token.exchange_token(app, auth)

      response =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "refresh_token",
          "refresh_token" => token.refresh_token,
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })
        |> json_response(200)

      ap_id = user.ap_id

      assert match?(
               %{
                 "scope" => "write",
                 "token_type" => "Bearer",
                 "access_token" => _,
                 "refresh_token" => _,
                 "me" => ^ap_id
               },
               response
             )

      refute Repo.get_by(Token, token: token.token)
      new_token = Repo.get_by(Token, token: response["access_token"])
      assert new_token.refresh_token == token.refresh_token
      assert new_token.scopes == auth.scopes
      assert new_token.user_id == user.id
      assert new_token.app_id == app.id
    end

    test "issues a new access token with new fresh token" do
      clear_config([:oauth2, :issue_new_refresh_token], false)
      user = insert(:user)
      app = insert(:oauth_app, scopes: ["read", "write"])

      {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
      {:ok, token} = Token.exchange_token(app, auth)

      response =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "refresh_token",
          "refresh_token" => token.refresh_token,
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })
        |> json_response(200)

      ap_id = user.ap_id

      assert match?(
               %{
                 "scope" => "write",
                 "token_type" => "Bearer",
                 "access_token" => _,
                 "refresh_token" => _,
                 "me" => ^ap_id
               },
               response
             )

      refute Repo.get_by(Token, token: token.token)
      new_token = Repo.get_by(Token, token: response["access_token"])
      refute new_token.refresh_token == token.refresh_token
      assert new_token.scopes == auth.scopes
      assert new_token.user_id == user.id
      assert new_token.app_id == app.id
    end

    test "returns 400 if we try use access token" do
      user = insert(:user)
      app = insert(:oauth_app, scopes: ["read", "write"])

      {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
      {:ok, token} = Token.exchange_token(app, auth)

      response =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "refresh_token",
          "refresh_token" => token.token,
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })
        |> json_response(400)

      assert %{"error" => "Invalid credentials"} == response
    end

    test "returns 400 if refresh_token invalid" do
      app = insert(:oauth_app, scopes: ["read", "write"])

      response =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "refresh_token",
          "refresh_token" => "token.refresh_token",
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })
        |> json_response(400)

      assert %{"error" => "Invalid credentials"} == response
    end

    test "issues a new token if token expired" do
      user = insert(:user)
      app = insert(:oauth_app, scopes: ["read", "write"])

      {:ok, auth} = Authorization.create_authorization(app, user, ["write"])
      {:ok, token} = Token.exchange_token(app, auth)

      change =
        Ecto.Changeset.change(
          token,
          %{valid_until: NaiveDateTime.add(NaiveDateTime.utc_now(), -86_400 * 30)}
        )

      {:ok, access_token} = Repo.update(change)

      response =
        build_conn()
        |> post("/oauth/token", %{
          "grant_type" => "refresh_token",
          "refresh_token" => access_token.refresh_token,
          "client_id" => app.client_id,
          "client_secret" => app.client_secret
        })
        |> json_response(200)

      ap_id = user.ap_id

      assert match?(
               %{
                 "scope" => "write",
                 "token_type" => "Bearer",
                 "access_token" => _,
                 "refresh_token" => _,
                 "me" => ^ap_id
               },
               response
             )

      refute Repo.get_by(Token, token: token.token)
      token = Repo.get_by(Token, token: response["access_token"])
      assert token
      assert token.scopes == auth.scopes
      assert token.user_id == user.id
      assert token.app_id == app.id
    end
  end

  describe "POST /oauth/token - bad request" do
    test "returns 500" do
      response =
        build_conn()
        |> post("/oauth/token", %{})
        |> json_response(500)

      assert %{"error" => "Bad request"} == response
    end
  end

  describe "POST /oauth/revoke" do
    test "when authenticated with request token, revokes it and clears it from session" do
      oauth_token = insert(:oauth_token)

      conn =
        build_conn()
        |> Plug.Session.call(Plug.Session.init(@session_opts))
        |> fetch_session()
        |> AuthHelper.put_session_token(oauth_token.token)
        |> post("/oauth/revoke", %{"token" => oauth_token.token})

      assert json_response(conn, 200)

      refute AuthHelper.get_session_token(conn)
      assert Token.get_by_token(oauth_token.token) == {:error, :not_found}
    end

    test "if request is authenticated with a different token, " <>
           "revokes requested token but keeps session token" do
      user = insert(:user)
      oauth_token = insert(:oauth_token, user: user)
      other_app_oauth_token = insert(:oauth_token, user: user)

      conn =
        build_conn()
        |> Plug.Session.call(Plug.Session.init(@session_opts))
        |> fetch_session()
        |> AuthHelper.put_session_token(oauth_token.token)
        |> post("/oauth/revoke", %{"token" => other_app_oauth_token.token})

      assert json_response(conn, 200)

      assert AuthHelper.get_session_token(conn) == oauth_token.token
      assert Token.get_by_token(other_app_oauth_token.token) == {:error, :not_found}
    end

    test "returns 500 on bad request" do
      response =
        build_conn()
        |> post("/oauth/revoke", %{})
        |> json_response(500)

      assert %{"error" => "Bad request"} == response
    end
  end
end