ybelkada HF Staff commited on
Commit
031086d
·
verified ·
1 Parent(s): 369c312

Harbor format: 871 coding_baseline tasks (part 45)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted-inventory.json +392 -0
  2. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/__init__.py +3 -0
  3. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/__init__.py +0 -0
  4. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/__init__.py +0 -0
  5. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/__init__.py +0 -0
  6. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/test_access_token.py +91 -0
  7. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/test_authorization.py +54 -0
  8. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/test_base.py +406 -0
  9. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/test_request_token.py +90 -0
  10. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/test_resource.py +102 -0
  11. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/test_signature_only.py +50 -0
  12. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/test_client.py +269 -0
  13. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/test_parameters.py +90 -0
  14. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/test_request_validator.py +68 -0
  15. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/test_signatures.py +903 -0
  16. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/test_utils.py +138 -0
  17. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/__init__.py +0 -0
  18. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/__init__.py +0 -0
  19. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/__init__.py +0 -0
  20. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/test_backend_application.py +86 -0
  21. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/test_base.py +394 -0
  22. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/test_legacy_application.py +140 -0
  23. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/test_mobile_application.py +111 -0
  24. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/test_service_application.py +185 -0
  25. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/test_web_application.py +264 -0
  26. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/__init__.py +0 -0
  27. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_base_endpoint.py +75 -0
  28. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_client_authentication.py +162 -0
  29. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_credentials_preservation.py +128 -0
  30. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_error_responses.py +491 -0
  31. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_extra_credentials.py +69 -0
  32. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_introspect_endpoint.py +168 -0
  33. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_metadata.py +148 -0
  34. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_resource_owner_association.py +108 -0
  35. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_revocation_endpoint.py +148 -0
  36. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_scope_handling.py +193 -0
  37. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_utils.py +11 -0
  38. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/grant_types/__init__.py +0 -0
  39. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/grant_types/test_authorization_code.py +382 -0
  40. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/grant_types/test_client_credentials.py +76 -0
  41. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/grant_types/test_implicit.py +62 -0
  42. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/grant_types/test_refresh_token.py +227 -0
  43. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/grant_types/test_resource_owner_password.py +156 -0
  44. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/test_parameters.py +304 -0
  45. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/test_request_validator.py +51 -0
  46. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/test_server.py +391 -0
  47. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/test_tokens.py +170 -0
  48. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/test_utils.py +100 -0
  49. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc8628/__init__.py +0 -0
  50. tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc8628/clients/__init__.py +0 -0
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted-inventory.json ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "directory_roots": [
3
+ "tests"
4
+ ],
5
+ "files": {
6
+ "setup.cfg": {
7
+ "bytes": 282,
8
+ "mode": 420,
9
+ "sha256": "a47feae20d4ebb4d7efb4b255c108bf0266b28a71cec1df666ff9cfa6ac5f955"
10
+ },
11
+ "setup.py": {
12
+ "bytes": 2302,
13
+ "mode": 493,
14
+ "sha256": "f8d6807ba2aff45cd7698f84eb6c15f676462b3a6210cf6fa7f08b0f9759958e"
15
+ },
16
+ "tests/__init__.py": {
17
+ "bytes": 42,
18
+ "mode": 420,
19
+ "sha256": "97c9814564feec3ef5f81703f69b939619048c9b825972ee39f02528310b306c"
20
+ },
21
+ "tests/oauth1/__init__.py": {
22
+ "bytes": 0,
23
+ "mode": 420,
24
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
25
+ },
26
+ "tests/oauth1/rfc5849/__init__.py": {
27
+ "bytes": 0,
28
+ "mode": 420,
29
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
30
+ },
31
+ "tests/oauth1/rfc5849/endpoints/__init__.py": {
32
+ "bytes": 0,
33
+ "mode": 420,
34
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
35
+ },
36
+ "tests/oauth1/rfc5849/endpoints/test_access_token.py": {
37
+ "bytes": 4011,
38
+ "mode": 420,
39
+ "sha256": "8f4bc584d1416345acd5ca17d293b00ccb684a61b3a972e718aba66db357fe8f"
40
+ },
41
+ "tests/oauth1/rfc5849/endpoints/test_authorization.py": {
42
+ "bytes": 2246,
43
+ "mode": 420,
44
+ "sha256": "cb5cc7a1a05023b63ff7df76961406a141f32e9df7f67a21378afa1962c15562"
45
+ },
46
+ "tests/oauth1/rfc5849/endpoints/test_base.py": {
47
+ "bytes": 16520,
48
+ "mode": 420,
49
+ "sha256": "05f73b1d086175ae2a80ef8c43d3d2e38c2f867275f1d941a165a314e92aba1d"
50
+ },
51
+ "tests/oauth1/rfc5849/endpoints/test_request_token.py": {
52
+ "bytes": 3845,
53
+ "mode": 420,
54
+ "sha256": "bb6f6c9ee2cf3c524d2a86c3099f12f8f5edf16f74aeb9487ab592889eba3d0e"
55
+ },
56
+ "tests/oauth1/rfc5849/endpoints/test_resource.py": {
57
+ "bytes": 4576,
58
+ "mode": 420,
59
+ "sha256": "6fdf7e9f6ef017ad7ad23c6c0ae139e313b4ba717d0314f1699b861ae1507e26"
60
+ },
61
+ "tests/oauth1/rfc5849/endpoints/test_signature_only.py": {
62
+ "bytes": 1957,
63
+ "mode": 420,
64
+ "sha256": "2503bfc83942e1e25bbf4e584b3d25dc98d38c50e40a1c7823cedf2e204c4b30"
65
+ },
66
+ "tests/oauth1/rfc5849/test_client.py": {
67
+ "bytes": 12907,
68
+ "mode": 420,
69
+ "sha256": "7ca99bfe6ee6a59ca18ea75572051401d280796c8015632e5bf2a08f832906f3"
70
+ },
71
+ "tests/oauth1/rfc5849/test_parameters.py": {
72
+ "bytes": 3795,
73
+ "mode": 420,
74
+ "sha256": "3d8c68179054c97565e456b7143ec8372ff7dca06ddc44ba67e199467c317c17"
75
+ },
76
+ "tests/oauth1/rfc5849/test_request_validator.py": {
77
+ "bytes": 3175,
78
+ "mode": 420,
79
+ "sha256": "7786296c27263a0a24e1a7487eb6eea17e473f8e2b6116587350f97db784dee7"
80
+ },
81
+ "tests/oauth1/rfc5849/test_signatures.py": {
82
+ "bytes": 36122,
83
+ "mode": 420,
84
+ "sha256": "8873fd8233d2fd8d4633a778e21da3734a0c21ffc1c9cf6285ce6adb5524e41c"
85
+ },
86
+ "tests/oauth1/rfc5849/test_utils.py": {
87
+ "bytes": 5336,
88
+ "mode": 420,
89
+ "sha256": "33910da3f441c7889987fdcb5a229dc7e301cef0100df4356dff19ae24396af1"
90
+ },
91
+ "tests/oauth2/__init__.py": {
92
+ "bytes": 0,
93
+ "mode": 420,
94
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
95
+ },
96
+ "tests/oauth2/rfc6749/__init__.py": {
97
+ "bytes": 0,
98
+ "mode": 420,
99
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
100
+ },
101
+ "tests/oauth2/rfc6749/clients/__init__.py": {
102
+ "bytes": 0,
103
+ "mode": 420,
104
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
105
+ },
106
+ "tests/oauth2/rfc6749/clients/test_backend_application.py": {
107
+ "bytes": 3248,
108
+ "mode": 420,
109
+ "sha256": "8d5cb1803365d07fabf97973e3f2db4f94117fa677a8b6ddb28628ee290b7dd3"
110
+ },
111
+ "tests/oauth2/rfc6749/clients/test_base.py": {
112
+ "bytes": 17268,
113
+ "mode": 420,
114
+ "sha256": "f057c4c2331ef28a951eab702860f2261ca9a43525ac14be8ceef8cb09063622"
115
+ },
116
+ "tests/oauth2/rfc6749/clients/test_legacy_application.py": {
117
+ "bytes": 6427,
118
+ "mode": 420,
119
+ "sha256": "1d0ec6190934e867540574592fd380672c3360bbb7831735ddb3364877b07525"
120
+ },
121
+ "tests/oauth2/rfc6749/clients/test_mobile_application.py": {
122
+ "bytes": 4162,
123
+ "mode": 420,
124
+ "sha256": "28f7eb23dd56aa468d614a328c11e54f932feaa7a44c910a598a8eb6e9e4dc67"
125
+ },
126
+ "tests/oauth2/rfc6749/clients/test_service_application.py": {
127
+ "bytes": 7569,
128
+ "mode": 420,
129
+ "sha256": "533004e7664b09032f803e6cf8d591eec6c2d3630121d8f9075cd8027d3969ba"
130
+ },
131
+ "tests/oauth2/rfc6749/clients/test_web_application.py": {
132
+ "bytes": 11929,
133
+ "mode": 420,
134
+ "sha256": "6b68b515752fd2f2caaef0b7547174dc030af3cc59d93a70cebafdb480b929aa"
135
+ },
136
+ "tests/oauth2/rfc6749/endpoints/__init__.py": {
137
+ "bytes": 0,
138
+ "mode": 420,
139
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
140
+ },
141
+ "tests/oauth2/rfc6749/endpoints/test_base_endpoint.py": {
142
+ "bytes": 2486,
143
+ "mode": 420,
144
+ "sha256": "bb9bee6c00fd77f4045e33c75da89eb2963e574a2c7e12d64028938fccb623f3"
145
+ },
146
+ "tests/oauth2/rfc6749/endpoints/test_client_authentication.py": {
147
+ "bytes": 6821,
148
+ "mode": 420,
149
+ "sha256": "8b0b010755e4ace1f912bf3c1ada9e73035d4008ee43f01d93327342c5b3b504"
150
+ },
151
+ "tests/oauth2/rfc6749/endpoints/test_credentials_preservation.py": {
152
+ "bytes": 5448,
153
+ "mode": 420,
154
+ "sha256": "05e637379b11983ec0beab82648450bd35912f33991c6f3d0943de1ba0d5ef1c"
155
+ },
156
+ "tests/oauth2/rfc6749/endpoints/test_error_responses.py": {
157
+ "bytes": 22688,
158
+ "mode": 420,
159
+ "sha256": "41e6c46453e736ead538b0c93254049a62a1205408446a644e184a79d6bfa481"
160
+ },
161
+ "tests/oauth2/rfc6749/endpoints/test_extra_credentials.py": {
162
+ "bytes": 2611,
163
+ "mode": 420,
164
+ "sha256": "1045827b3a75c1e26f58390292ecf4add86725e90e090753c72bdb397c9f2333"
165
+ },
166
+ "tests/oauth2/rfc6749/endpoints/test_introspect_endpoint.py": {
167
+ "bytes": 7718,
168
+ "mode": 420,
169
+ "sha256": "1bd3411cced35721fb6d4c3c8d87b90849abe37e166a6b9717efd2e41de1ef3b"
170
+ },
171
+ "tests/oauth2/rfc6749/endpoints/test_metadata.py": {
172
+ "bytes": 5726,
173
+ "mode": 420,
174
+ "sha256": "a83370ac0025d009462a3f53d99cbdd97610a1e46de5cc8b58da96ef38850640"
175
+ },
176
+ "tests/oauth2/rfc6749/endpoints/test_resource_owner_association.py": {
177
+ "bytes": 4311,
178
+ "mode": 420,
179
+ "sha256": "330006312918be9ef846ab4b1b30ce533faa30e995b36c9ecd5b9b74b04d68d0"
180
+ },
181
+ "tests/oauth2/rfc6749/endpoints/test_revocation_endpoint.py": {
182
+ "bytes": 6820,
183
+ "mode": 420,
184
+ "sha256": "85277b81048e9f8be8329068f05ffb1b6d99de4ecfb26d7d782329d5bfa7dce9"
185
+ },
186
+ "tests/oauth2/rfc6749/endpoints/test_scope_handling.py": {
187
+ "bytes": 8768,
188
+ "mode": 420,
189
+ "sha256": "2f42c9b45108ded2f6023498211fd9baf1b18cfca6fdfb832588bd5d8165946e"
190
+ },
191
+ "tests/oauth2/rfc6749/endpoints/test_utils.py": {
192
+ "bytes": 296,
193
+ "mode": 420,
194
+ "sha256": "36a7a5645ba5d95480e12da0503a1d092765d105d5178fe919cec7ad76c4bca1"
195
+ },
196
+ "tests/oauth2/rfc6749/grant_types/__init__.py": {
197
+ "bytes": 0,
198
+ "mode": 420,
199
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
200
+ },
201
+ "tests/oauth2/rfc6749/grant_types/test_authorization_code.py": {
202
+ "bytes": 18267,
203
+ "mode": 420,
204
+ "sha256": "9c54caf051d0ccd02faa2f6f4bac79c6101d2e68abe4b00275defb74ac8df7e0"
205
+ },
206
+ "tests/oauth2/rfc6749/grant_types/test_client_credentials.py": {
207
+ "bytes": 3281,
208
+ "mode": 420,
209
+ "sha256": "d8d4f5808a2ec1b73feb265874cc18f209caaf8a3b4d7c15c76c553e4d966a28"
210
+ },
211
+ "tests/oauth2/rfc6749/grant_types/test_implicit.py": {
212
+ "bytes": 2662,
213
+ "mode": 420,
214
+ "sha256": "6f01071dbf729df005cc1d83177e2f2a0f5f8e91c468f880990a2d297d8d94fc"
215
+ },
216
+ "tests/oauth2/rfc6749/grant_types/test_refresh_token.py": {
217
+ "bytes": 10339,
218
+ "mode": 420,
219
+ "sha256": "7801ce4212389a67e82e2e041fd43969f13daee24c1dd3faade3dcc4896e4292"
220
+ },
221
+ "tests/oauth2/rfc6749/grant_types/test_resource_owner_password.py": {
222
+ "bytes": 7233,
223
+ "mode": 420,
224
+ "sha256": "5f6460f1e9095f86f7c7366e88924166b819a6d54b865a613ff502a7611d3291"
225
+ },
226
+ "tests/oauth2/rfc6749/test_parameters.py": {
227
+ "bytes": 14417,
228
+ "mode": 420,
229
+ "sha256": "052a2e2f3478967188aa3b05ffc634eebe1a6a95016a5374b700b67793f3b498"
230
+ },
231
+ "tests/oauth2/rfc6749/test_request_validator.py": {
232
+ "bytes": 2640,
233
+ "mode": 420,
234
+ "sha256": "d2f92c963abc7495a256181ff2a49ae0d662a9c6c5379dd48d3b939b43c09054"
235
+ },
236
+ "tests/oauth2/rfc6749/test_server.py": {
237
+ "bytes": 16651,
238
+ "mode": 420,
239
+ "sha256": "7f7b32adc6b6c7e8d8d533b8223bbbee66e1833a008a49ffe721bc3feba0b5d0"
240
+ },
241
+ "tests/oauth2/rfc6749/test_tokens.py": {
242
+ "bytes": 6411,
243
+ "mode": 420,
244
+ "sha256": "437ec199a7127e15ed7615463e2bf04c67c753add6e438aaef6a3926fc20d37e"
245
+ },
246
+ "tests/oauth2/rfc6749/test_utils.py": {
247
+ "bytes": 3725,
248
+ "mode": 420,
249
+ "sha256": "27e3a6e2793b47844141e103059f5c68aa5e222dea5568d241a4dccf236a4846"
250
+ },
251
+ "tests/oauth2/rfc8628/__init__.py": {
252
+ "bytes": 0,
253
+ "mode": 420,
254
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
255
+ },
256
+ "tests/oauth2/rfc8628/clients/__init__.py": {
257
+ "bytes": 0,
258
+ "mode": 420,
259
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
260
+ },
261
+ "tests/oauth2/rfc8628/clients/test_device.py": {
262
+ "bytes": 2032,
263
+ "mode": 420,
264
+ "sha256": "62156c48b39e45b7112e8e7295dc58265085dce1186774cc4788fd1cecc35bfa"
265
+ },
266
+ "tests/oauth2/rfc8628/endpoints/__init__.py": {
267
+ "bytes": 0,
268
+ "mode": 420,
269
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
270
+ },
271
+ "tests/oauth2/rfc8628/endpoints/test_error_responses.py": {
272
+ "bytes": 3701,
273
+ "mode": 420,
274
+ "sha256": "08ce848430fc47519ca30a5d6bc78b051b447df557239dc18fef4017fdb6d647"
275
+ },
276
+ "tests/oauth2/rfc8628/test_server.py": {
277
+ "bytes": 4463,
278
+ "mode": 420,
279
+ "sha256": "8d4cf7f7c4f5ad49da6c680df078c7490cdd108b433e7a4d5af0068f97ba8e55"
280
+ },
281
+ "tests/openid/__init__.py": {
282
+ "bytes": 0,
283
+ "mode": 420,
284
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
285
+ },
286
+ "tests/openid/connect/__init__.py": {
287
+ "bytes": 0,
288
+ "mode": 420,
289
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
290
+ },
291
+ "tests/openid/connect/core/__init__.py": {
292
+ "bytes": 0,
293
+ "mode": 420,
294
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
295
+ },
296
+ "tests/openid/connect/core/endpoints/__init__.py": {
297
+ "bytes": 0,
298
+ "mode": 420,
299
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
300
+ },
301
+ "tests/openid/connect/core/endpoints/test_claims_handling.py": {
302
+ "bytes": 4579,
303
+ "mode": 420,
304
+ "sha256": "b4e10383d52bbb22bbeb56b046f72098a46314df5f4ef7c1bbbb6356f139ef27"
305
+ },
306
+ "tests/openid/connect/core/endpoints/test_openid_connect_params_handling.py": {
307
+ "bytes": 3012,
308
+ "mode": 420,
309
+ "sha256": "d63db805c3302fe9291d93fcac863fca1ef4dc7d6f03acf79faf7d29be948ecd"
310
+ },
311
+ "tests/openid/connect/core/endpoints/test_refresh_token.py": {
312
+ "bytes": 1182,
313
+ "mode": 420,
314
+ "sha256": "43bf47946224d7068dcc03535778e7592a1d7a44b3f3fec1480eb8cabcd34d0a"
315
+ },
316
+ "tests/openid/connect/core/endpoints/test_userinfo_endpoint.py": {
317
+ "bytes": 2522,
318
+ "mode": 420,
319
+ "sha256": "76c65f0183cfbcc77ea99b660ba34358a461a4ccf6ad8f1e11bb3d618c3f5d67"
320
+ },
321
+ "tests/openid/connect/core/grant_types/__init__.py": {
322
+ "bytes": 0,
323
+ "mode": 420,
324
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
325
+ },
326
+ "tests/openid/connect/core/grant_types/test_authorization_code.py": {
327
+ "bytes": 8365,
328
+ "mode": 420,
329
+ "sha256": "bdc575d2a2fbc053bba205caa799bb7e88f409817597e3458c9b5558dbf5cd99"
330
+ },
331
+ "tests/openid/connect/core/grant_types/test_base.py": {
332
+ "bytes": 4784,
333
+ "mode": 420,
334
+ "sha256": "f9118f0cd3a4fe04ec281f38f51ceffbd67e0c35940a3cad3757dccbcb527878"
335
+ },
336
+ "tests/openid/connect/core/grant_types/test_dispatchers.py": {
337
+ "bytes": 4780,
338
+ "mode": 420,
339
+ "sha256": "22aab25f7963aa7c46157392228137320373f159b45cf31ae1044cf27861c7d4"
340
+ },
341
+ "tests/openid/connect/core/grant_types/test_hybrid.py": {
342
+ "bytes": 4407,
343
+ "mode": 420,
344
+ "sha256": "cc8e215d9cb9e722661504198edabf4c8fdbe624b9513b4422c24719fab25e67"
345
+ },
346
+ "tests/openid/connect/core/grant_types/test_implicit.py": {
347
+ "bytes": 7637,
348
+ "mode": 420,
349
+ "sha256": "aec5b5d2271c52c1f9358afc189812d3e2ea7dea51dda11a7b9d608b0a9d6eda"
350
+ },
351
+ "tests/openid/connect/core/grant_types/test_refresh_token.py": {
352
+ "bytes": 3695,
353
+ "mode": 420,
354
+ "sha256": "11e6452185dd8e9364ac08e8330ea3ddcb0fed4d06edc6f7980cdb6adb2fc442"
355
+ },
356
+ "tests/openid/connect/core/test_request_validator.py": {
357
+ "bytes": 1432,
358
+ "mode": 420,
359
+ "sha256": "7419dfaf9b98d661c486b2cad2237b29d3c5fa3f4bad65ef28192b7a2a1fe9b9"
360
+ },
361
+ "tests/openid/connect/core/test_server.py": {
362
+ "bytes": 7836,
363
+ "mode": 420,
364
+ "sha256": "98c069146380b64ddd99ae6439b26e25b80700345710e1d9a2419096962154a2"
365
+ },
366
+ "tests/openid/connect/core/test_tokens.py": {
367
+ "bytes": 6288,
368
+ "mode": 420,
369
+ "sha256": "303520dfff7f8504b10de30d4e0dcb1fb42b86fc62057cfccb382cb280b1652b"
370
+ },
371
+ "tests/test_common.py": {
372
+ "bytes": 8808,
373
+ "mode": 420,
374
+ "sha256": "176c0a6663ed03b5ad73dde735cf61103c5bbdb415eb69a40fff86122911c292"
375
+ },
376
+ "tests/test_uri_validate.py": {
377
+ "bytes": 4636,
378
+ "mode": 420,
379
+ "sha256": "82048de3af5e8c74197c8e893cb4c093d4cb655a081f3339e63dfd4b10695339"
380
+ },
381
+ "tests/unittest/__init__.py": {
382
+ "bytes": 1381,
383
+ "mode": 420,
384
+ "sha256": "0110380aba402ce499e829738228f618570f64582f32de9e6e04a1751f5f480a"
385
+ },
386
+ "tox.ini": {
387
+ "bytes": 659,
388
+ "mode": 420,
389
+ "sha256": "527a9899fdc310dd96ffbdd0d2175dd79e62060db3d716d52a5891290341b563"
390
+ }
391
+ }
392
+ }
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ import oauthlib
2
+
3
+ oauthlib.set_debug(True)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/__init__.py ADDED
File without changes
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/__init__.py ADDED
File without changes
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/__init__.py ADDED
File without changes
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/test_access_token.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unittest.mock import ANY, MagicMock
2
+
3
+ from oauthlib.oauth1 import RequestValidator
4
+ from oauthlib.oauth1.rfc5849 import Client
5
+ from oauthlib.oauth1.rfc5849.endpoints import AccessTokenEndpoint
6
+
7
+ from tests.unittest import TestCase
8
+
9
+
10
+ class AccessTokenEndpointTest(TestCase):
11
+
12
+ def setUp(self):
13
+ self.validator = MagicMock(wraps=RequestValidator())
14
+ self.validator.check_client_key.return_value = True
15
+ self.validator.check_request_token.return_value = True
16
+ self.validator.check_verifier.return_value = True
17
+ self.validator.allowed_signature_methods = ['HMAC-SHA1']
18
+ self.validator.get_client_secret.return_value = 'bar'
19
+ self.validator.get_request_token_secret.return_value = 'secret'
20
+ self.validator.get_realms.return_value = ['foo']
21
+ self.validator.timestamp_lifetime = 600
22
+ self.validator.validate_client_key.return_value = True
23
+ self.validator.validate_request_token.return_value = True
24
+ self.validator.validate_verifier.return_value = True
25
+ self.validator.validate_timestamp_and_nonce.return_value = True
26
+ self.validator.invalidate_request_token.return_value = True
27
+ self.validator.dummy_client = 'dummy'
28
+ self.validator.dummy_secret = 'dummy'
29
+ self.validator.dummy_request_token = 'dummy'
30
+ self.validator.save_access_token = MagicMock()
31
+ self.endpoint = AccessTokenEndpoint(self.validator)
32
+ self.client = Client('foo',
33
+ client_secret='bar',
34
+ resource_owner_key='token',
35
+ resource_owner_secret='secret',
36
+ verifier='verfier')
37
+ self.uri, self.headers, self.body = self.client.sign(
38
+ 'https://i.b/access_token')
39
+
40
+ def test_check_request_token(self):
41
+ self.validator.check_request_token.return_value = False
42
+ h, b, s = self.endpoint.create_access_token_response(
43
+ self.uri, headers=self.headers)
44
+ self.assertEqual(s, 400)
45
+ self.assertIn('invalid_request', b)
46
+
47
+ def test_check_verifier(self):
48
+ self.validator.check_verifier.return_value = False
49
+ h, b, s = self.endpoint.create_access_token_response(
50
+ self.uri, headers=self.headers)
51
+ self.assertEqual(s, 400)
52
+ self.assertIn('invalid_request', b)
53
+
54
+ def test_validate_client_key(self):
55
+ self.validator.validate_client_key.return_value = False
56
+ h, b, s = self.endpoint.create_access_token_response(
57
+ self.uri, headers=self.headers)
58
+ self.assertEqual(s, 401)
59
+
60
+ def test_validate_request_token(self):
61
+ self.validator.validate_request_token.return_value = False
62
+ h, b, s = self.endpoint.create_access_token_response(
63
+ self.uri, headers=self.headers)
64
+ self.assertEqual(s, 401)
65
+
66
+ def test_validate_verifier(self):
67
+ self.validator.validate_verifier.return_value = False
68
+ h, b, s = self.endpoint.create_access_token_response(
69
+ self.uri, headers=self.headers)
70
+ self.assertEqual(s, 401)
71
+
72
+ def test_validate_signature(self):
73
+ client = Client('foo',
74
+ resource_owner_key='token',
75
+ resource_owner_secret='secret',
76
+ verifier='verfier')
77
+ _, headers, _ = client.sign(self.uri + '/extra')
78
+ h, b, s = self.endpoint.create_access_token_response(
79
+ self.uri, headers=headers)
80
+ self.assertEqual(s, 401)
81
+
82
+ def test_valid_request(self):
83
+ h, b, s = self.endpoint.create_access_token_response(
84
+ self.uri, headers=self.headers)
85
+ self.assertEqual(s, 200)
86
+ self.assertIn('oauth_token', b)
87
+ self.validator.validate_timestamp_and_nonce.assert_called_once_with(
88
+ self.client.client_key, ANY, ANY, ANY,
89
+ request_token=self.client.resource_owner_key)
90
+ self.validator.invalidate_request_token.assert_called_once_with(
91
+ self.client.client_key, self.client.resource_owner_key, ANY)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/test_authorization.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unittest.mock import MagicMock
2
+
3
+ from oauthlib.oauth1 import RequestValidator
4
+ from oauthlib.oauth1.rfc5849 import errors
5
+ from oauthlib.oauth1.rfc5849.endpoints import AuthorizationEndpoint
6
+
7
+ from tests.unittest import TestCase
8
+
9
+
10
+ class AuthorizationEndpointTest(TestCase):
11
+
12
+ def setUp(self):
13
+ self.validator = MagicMock(wraps=RequestValidator())
14
+ self.validator.verify_request_token.return_value = True
15
+ self.validator.verify_realms.return_value = True
16
+ self.validator.get_realms.return_value = ['test']
17
+ self.validator.save_verifier = MagicMock()
18
+ self.endpoint = AuthorizationEndpoint(self.validator)
19
+ self.uri = 'https://i.b/authorize?oauth_token=foo'
20
+
21
+ def test_get_realms_and_credentials(self):
22
+ realms, credentials = self.endpoint.get_realms_and_credentials(self.uri)
23
+ self.assertEqual(realms, ['test'])
24
+
25
+ def test_verify_token(self):
26
+ self.validator.verify_request_token.return_value = False
27
+ self.assertRaises(errors.InvalidClientError,
28
+ self.endpoint.get_realms_and_credentials, self.uri)
29
+ self.assertRaises(errors.InvalidClientError,
30
+ self.endpoint.create_authorization_response, self.uri)
31
+
32
+ def test_verify_realms(self):
33
+ self.validator.verify_realms.return_value = False
34
+ self.assertRaises(errors.InvalidRequestError,
35
+ self.endpoint.create_authorization_response,
36
+ self.uri,
37
+ realms=['bar'])
38
+
39
+ def test_create_authorization_response(self):
40
+ self.validator.get_redirect_uri.return_value = 'https://c.b/cb'
41
+ h, b, s = self.endpoint.create_authorization_response(self.uri)
42
+ self.assertEqual(s, 302)
43
+ self.assertIn('Location', h)
44
+ location = h['Location']
45
+ self.assertTrue(location.startswith('https://c.b/cb'))
46
+ self.assertIn('oauth_verifier', location)
47
+
48
+ def test_create_authorization_response_oob(self):
49
+ self.validator.get_redirect_uri.return_value = 'oob'
50
+ h, b, s = self.endpoint.create_authorization_response(self.uri)
51
+ self.assertEqual(s, 200)
52
+ self.assertNotIn('Location', h)
53
+ self.assertIn('oauth_verifier', b)
54
+ self.assertIn('oauth_token', b)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/test_base.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from re import sub
2
+ from unittest.mock import MagicMock
3
+
4
+ from oauthlib.common import CaseInsensitiveDict, safe_string_equals
5
+ from oauthlib.oauth1 import Client, RequestValidator
6
+ from oauthlib.oauth1.rfc5849 import (
7
+ SIGNATURE_HMAC, SIGNATURE_PLAINTEXT, SIGNATURE_RSA, errors,
8
+ )
9
+ from oauthlib.oauth1.rfc5849.endpoints import (
10
+ BaseEndpoint, RequestTokenEndpoint,
11
+ )
12
+
13
+ from tests.unittest import TestCase
14
+
15
+ URLENCODED = {"Content-Type": "application/x-www-form-urlencoded"}
16
+
17
+
18
+ class BaseEndpointTest(TestCase):
19
+
20
+ def setUp(self):
21
+ self.validator = MagicMock(spec=RequestValidator)
22
+ self.validator.allowed_signature_methods = ['HMAC-SHA1']
23
+ self.validator.timestamp_lifetime = 600
24
+ self.endpoint = RequestTokenEndpoint(self.validator)
25
+ self.client = Client('foo', callback_uri='https://c.b/cb')
26
+ self.uri, self.headers, self.body = self.client.sign(
27
+ 'https://i.b/request_token')
28
+
29
+ def test_ssl_enforcement(self):
30
+ uri, headers, _ = self.client.sign('http://i.b/request_token')
31
+ h, b, s = self.endpoint.create_request_token_response(
32
+ uri, headers=headers)
33
+ self.assertEqual(s, 400)
34
+ self.assertIn('insecure_transport_protocol', b)
35
+
36
+ def test_missing_parameters(self):
37
+ h, b, s = self.endpoint.create_request_token_response(self.uri)
38
+ self.assertEqual(s, 400)
39
+ self.assertIn('invalid_request', b)
40
+
41
+ def test_signature_methods(self):
42
+ headers = {}
43
+ headers['Authorization'] = self.headers['Authorization'].replace(
44
+ 'HMAC', 'RSA')
45
+ h, b, s = self.endpoint.create_request_token_response(
46
+ self.uri, headers=headers)
47
+ self.assertEqual(s, 400)
48
+ self.assertIn('invalid_signature_method', b)
49
+
50
+ def test_invalid_version(self):
51
+ headers = {}
52
+ headers['Authorization'] = self.headers['Authorization'].replace(
53
+ '1.0', '2.0')
54
+ h, b, s = self.endpoint.create_request_token_response(
55
+ self.uri, headers=headers)
56
+ self.assertEqual(s, 400)
57
+ self.assertIn('invalid_request', b)
58
+
59
+ def test_expired_timestamp(self):
60
+ headers = {}
61
+ for pattern in ('12345678901', '4567890123', '123456789K'):
62
+ headers['Authorization'] = sub(r'timestamp="\d*k?"',
63
+ 'timestamp="%s"' % pattern,
64
+ self.headers['Authorization'])
65
+ h, b, s = self.endpoint.create_request_token_response(
66
+ self.uri, headers=headers)
67
+ self.assertEqual(s, 400)
68
+ self.assertIn('invalid_request', b)
69
+
70
+ def test_client_key_check(self):
71
+ self.validator.check_client_key.return_value = False
72
+ h, b, s = self.endpoint.create_request_token_response(
73
+ self.uri, headers=self.headers)
74
+ self.assertEqual(s, 400)
75
+ self.assertIn('invalid_request', b)
76
+
77
+ def test_noncecheck(self):
78
+ self.validator.check_nonce.return_value = False
79
+ h, b, s = self.endpoint.create_request_token_response(
80
+ self.uri, headers=self.headers)
81
+ self.assertEqual(s, 400)
82
+ self.assertIn('invalid_request', b)
83
+
84
+ def test_enforce_ssl(self):
85
+ """Ensure SSL is enforced by default."""
86
+ v = RequestValidator()
87
+ e = BaseEndpoint(v)
88
+ c = Client('foo')
89
+ u, h, b = c.sign('http://example.com')
90
+ r = e._create_request(u, 'GET', b, h)
91
+ self.assertRaises(errors.InsecureTransportError,
92
+ e._check_transport_security, r)
93
+
94
+ def test_multiple_source_params(self):
95
+ """Check for duplicate params"""
96
+ v = RequestValidator()
97
+ e = BaseEndpoint(v)
98
+ self.assertRaises(errors.InvalidRequestError, e._create_request,
99
+ 'https://a.b/?oauth_signature_method=HMAC-SHA1',
100
+ 'GET', 'oauth_version=foo', URLENCODED)
101
+ headers = {'Authorization': 'OAuth oauth_signature="foo"'}
102
+ headers.update(URLENCODED)
103
+ self.assertRaises(errors.InvalidRequestError, e._create_request,
104
+ 'https://a.b/?oauth_signature_method=HMAC-SHA1',
105
+ 'GET',
106
+ 'oauth_version=foo',
107
+ headers)
108
+ headers = {'Authorization': 'OAuth oauth_signature_method="foo"'}
109
+ headers.update(URLENCODED)
110
+ self.assertRaises(errors.InvalidRequestError, e._create_request,
111
+ 'https://a.b/',
112
+ 'GET',
113
+ 'oauth_signature=foo',
114
+ headers)
115
+
116
+ def test_duplicate_params(self):
117
+ """Ensure params are only supplied once"""
118
+ v = RequestValidator()
119
+ e = BaseEndpoint(v)
120
+ self.assertRaises(errors.InvalidRequestError, e._create_request,
121
+ 'https://a.b/?oauth_version=a&oauth_version=b',
122
+ 'GET', None, URLENCODED)
123
+ self.assertRaises(errors.InvalidRequestError, e._create_request,
124
+ 'https://a.b/', 'GET', 'oauth_version=a&oauth_version=b',
125
+ URLENCODED)
126
+
127
+ def test_mandated_params(self):
128
+ """Ensure all mandatory params are present."""
129
+ v = RequestValidator()
130
+ e = BaseEndpoint(v)
131
+ r = e._create_request('https://a.b/', 'GET',
132
+ 'oauth_signature=a&oauth_consumer_key=b&oauth_nonce',
133
+ URLENCODED)
134
+ self.assertRaises(errors.InvalidRequestError,
135
+ e._check_mandatory_parameters, r)
136
+
137
+ def test_oauth_version(self):
138
+ """OAuth version must be 1.0 if present."""
139
+ v = RequestValidator()
140
+ e = BaseEndpoint(v)
141
+ r = e._create_request('https://a.b/', 'GET',
142
+ ('oauth_signature=a&oauth_consumer_key=b&oauth_nonce=c&'
143
+ 'oauth_timestamp=a&oauth_signature_method=RSA-SHA1&'
144
+ 'oauth_version=2.0'),
145
+ URLENCODED)
146
+ self.assertRaises(errors.InvalidRequestError,
147
+ e._check_mandatory_parameters, r)
148
+
149
+ def test_oauth_timestamp(self):
150
+ """Check for a valid UNIX timestamp."""
151
+ v = RequestValidator()
152
+ e = BaseEndpoint(v)
153
+
154
+ # Invalid timestamp length, must be 10
155
+ r = e._create_request('https://a.b/', 'GET',
156
+ ('oauth_signature=a&oauth_consumer_key=b&oauth_nonce=c&'
157
+ 'oauth_version=1.0&oauth_signature_method=RSA-SHA1&'
158
+ 'oauth_timestamp=123456789'),
159
+ URLENCODED)
160
+ self.assertRaises(errors.InvalidRequestError,
161
+ e._check_mandatory_parameters, r)
162
+
163
+ # Invalid timestamp age, must be younger than 10 minutes
164
+ r = e._create_request('https://a.b/', 'GET',
165
+ ('oauth_signature=a&oauth_consumer_key=b&oauth_nonce=c&'
166
+ 'oauth_version=1.0&oauth_signature_method=RSA-SHA1&'
167
+ 'oauth_timestamp=1234567890'),
168
+ URLENCODED)
169
+ self.assertRaises(errors.InvalidRequestError,
170
+ e._check_mandatory_parameters, r)
171
+
172
+ # Timestamp must be an integer
173
+ r = e._create_request('https://a.b/', 'GET',
174
+ ('oauth_signature=a&oauth_consumer_key=b&oauth_nonce=c&'
175
+ 'oauth_version=1.0&oauth_signature_method=RSA-SHA1&'
176
+ 'oauth_timestamp=123456789a'),
177
+ URLENCODED)
178
+ self.assertRaises(errors.InvalidRequestError,
179
+ e._check_mandatory_parameters, r)
180
+
181
+ def test_case_insensitive_headers(self):
182
+ """Ensure headers are case-insensitive"""
183
+ v = RequestValidator()
184
+ e = BaseEndpoint(v)
185
+ r = e._create_request('https://a.b', 'POST',
186
+ ('oauth_signature=a&oauth_consumer_key=b&oauth_nonce=c&'
187
+ 'oauth_version=1.0&oauth_signature_method=RSA-SHA1&'
188
+ 'oauth_timestamp=123456789a'),
189
+ URLENCODED)
190
+ self.assertIsInstance(r.headers, CaseInsensitiveDict)
191
+
192
+ def test_signature_method_validation(self):
193
+ """Ensure valid signature method is used."""
194
+
195
+ body = ('oauth_signature=a&oauth_consumer_key=b&oauth_nonce=c&'
196
+ 'oauth_version=1.0&oauth_signature_method=%s&'
197
+ 'oauth_timestamp=1234567890')
198
+
199
+ uri = 'https://example.com/'
200
+
201
+ class HMACValidator(RequestValidator):
202
+
203
+ @property
204
+ def allowed_signature_methods(self):
205
+ return (SIGNATURE_HMAC,)
206
+
207
+ v = HMACValidator()
208
+ e = BaseEndpoint(v)
209
+ r = e._create_request(uri, 'GET', body % 'RSA-SHA1', URLENCODED)
210
+ self.assertRaises(errors.InvalidSignatureMethodError,
211
+ e._check_mandatory_parameters, r)
212
+ r = e._create_request(uri, 'GET', body % 'PLAINTEXT', URLENCODED)
213
+ self.assertRaises(errors.InvalidSignatureMethodError,
214
+ e._check_mandatory_parameters, r)
215
+ r = e._create_request(uri, 'GET', body % 'shibboleth', URLENCODED)
216
+ self.assertRaises(errors.InvalidSignatureMethodError,
217
+ e._check_mandatory_parameters, r)
218
+
219
+ class RSAValidator(RequestValidator):
220
+
221
+ @property
222
+ def allowed_signature_methods(self):
223
+ return (SIGNATURE_RSA,)
224
+
225
+ v = RSAValidator()
226
+ e = BaseEndpoint(v)
227
+ r = e._create_request(uri, 'GET', body % 'HMAC-SHA1', URLENCODED)
228
+ self.assertRaises(errors.InvalidSignatureMethodError,
229
+ e._check_mandatory_parameters, r)
230
+ r = e._create_request(uri, 'GET', body % 'PLAINTEXT', URLENCODED)
231
+ self.assertRaises(errors.InvalidSignatureMethodError,
232
+ e._check_mandatory_parameters, r)
233
+ r = e._create_request(uri, 'GET', body % 'shibboleth', URLENCODED)
234
+ self.assertRaises(errors.InvalidSignatureMethodError,
235
+ e._check_mandatory_parameters, r)
236
+
237
+ class PlainValidator(RequestValidator):
238
+
239
+ @property
240
+ def allowed_signature_methods(self):
241
+ return (SIGNATURE_PLAINTEXT,)
242
+
243
+ v = PlainValidator()
244
+ e = BaseEndpoint(v)
245
+ r = e._create_request(uri, 'GET', body % 'HMAC-SHA1', URLENCODED)
246
+ self.assertRaises(errors.InvalidSignatureMethodError,
247
+ e._check_mandatory_parameters, r)
248
+ r = e._create_request(uri, 'GET', body % 'RSA-SHA1', URLENCODED)
249
+ self.assertRaises(errors.InvalidSignatureMethodError,
250
+ e._check_mandatory_parameters, r)
251
+ r = e._create_request(uri, 'GET', body % 'shibboleth', URLENCODED)
252
+ self.assertRaises(errors.InvalidSignatureMethodError,
253
+ e._check_mandatory_parameters, r)
254
+
255
+
256
+ class ClientValidator(RequestValidator):
257
+ clients = ['foo']
258
+ nonces = [('foo', 'once', '1234567891', 'fez')]
259
+ owners = {'foo': ['abcdefghijklmnopqrstuvxyz', 'fez']}
260
+ assigned_realms = {('foo', 'abcdefghijklmnopqrstuvxyz'): 'photos'}
261
+ verifiers = {('foo', 'fez'): 'shibboleth'}
262
+
263
+ @property
264
+ def client_key_length(self):
265
+ return 1, 30
266
+
267
+ @property
268
+ def request_token_length(self):
269
+ return 1, 30
270
+
271
+ @property
272
+ def access_token_length(self):
273
+ return 1, 30
274
+
275
+ @property
276
+ def nonce_length(self):
277
+ return 2, 30
278
+
279
+ @property
280
+ def verifier_length(self):
281
+ return 2, 30
282
+
283
+ @property
284
+ def realms(self):
285
+ return ['photos']
286
+
287
+ @property
288
+ def timestamp_lifetime(self):
289
+ # Disabled check to allow hardcoded verification signatures
290
+ return 1000000000
291
+
292
+ @property
293
+ def dummy_client(self):
294
+ return 'dummy'
295
+
296
+ @property
297
+ def dummy_request_token(self):
298
+ return 'dumbo'
299
+
300
+ @property
301
+ def dummy_access_token(self):
302
+ return 'dumbo'
303
+
304
+ def validate_timestamp_and_nonce(self, client_key, timestamp, nonce,
305
+ request, request_token=None, access_token=None):
306
+ resource_owner_key = request_token if request_token else access_token
307
+ return (client_key, nonce, timestamp, resource_owner_key) not in self.nonces
308
+
309
+ def validate_client_key(self, client_key):
310
+ return client_key in self.clients
311
+
312
+ def validate_access_token(self, client_key, access_token, request):
313
+ return (self.owners.get(client_key) and
314
+ access_token in self.owners.get(client_key))
315
+
316
+ def validate_request_token(self, client_key, request_token, request):
317
+ return (self.owners.get(client_key) and
318
+ request_token in self.owners.get(client_key))
319
+
320
+ def validate_requested_realm(self, client_key, realm, request):
321
+ return True
322
+
323
+ def validate_realm(self, client_key, access_token, request, uri=None,
324
+ required_realm=None):
325
+ return (client_key, access_token) in self.assigned_realms
326
+
327
+ def validate_verifier(self, client_key, request_token, verifier,
328
+ request):
329
+ return ((client_key, request_token) in self.verifiers and
330
+ safe_string_equals(verifier, self.verifiers.get(
331
+ (client_key, request_token))))
332
+
333
+ def validate_redirect_uri(self, client_key, redirect_uri, request):
334
+ return redirect_uri.startswith('http://client.example.com/')
335
+
336
+ def get_client_secret(self, client_key, request):
337
+ return 'super secret'
338
+
339
+ def get_access_token_secret(self, client_key, access_token, request):
340
+ return 'even more secret'
341
+
342
+ def get_request_token_secret(self, client_key, request_token, request):
343
+ return 'even more secret'
344
+
345
+ def get_rsa_key(self, client_key, request):
346
+ return ("-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNA"
347
+ "DCBiQKBgQDVLQCATX8iK+aZuGVdkGb6uiar\nLi/jqFwL1dYj0JLIsdQc"
348
+ "KaMWtPC06K0+vI+RRZcjKc6sNB9/7kJcKN9Ekc9BUxyT\n/D09Cz47cmC"
349
+ "YsUoiW7G8NSqbE4wPiVpGkJRzFAxaCWwOSSQ+lpC9vwxnvVQfOoZ1\nnp"
350
+ "mWbCdA0iTxsMahwQIDAQAB\n-----END PUBLIC KEY-----")
351
+
352
+
353
+ class SignatureVerificationTest(TestCase):
354
+
355
+ def setUp(self):
356
+ v = ClientValidator()
357
+ self.e = BaseEndpoint(v)
358
+
359
+ self.uri = 'https://example.com/'
360
+ self.sig = ('oauth_signature=%s&'
361
+ 'oauth_timestamp=1234567890&'
362
+ 'oauth_nonce=abcdefghijklmnopqrstuvwxyz&'
363
+ 'oauth_version=1.0&'
364
+ 'oauth_signature_method=%s&'
365
+ 'oauth_token=abcdefghijklmnopqrstuvxyz&'
366
+ 'oauth_consumer_key=foo')
367
+
368
+ def test_signature_too_short(self):
369
+ short_sig = ('oauth_signature=fmrXnTF4lO4o%2BD0%2FlZaJHP%2FXqEY&'
370
+ 'oauth_timestamp=1234567890&'
371
+ 'oauth_nonce=abcdefghijklmnopqrstuvwxyz&'
372
+ 'oauth_version=1.0&oauth_signature_method=HMAC-SHA1&'
373
+ 'oauth_token=abcdefghijklmnopqrstuvxyz&'
374
+ 'oauth_consumer_key=foo')
375
+ r = self.e._create_request(self.uri, 'GET', short_sig, URLENCODED)
376
+ self.assertFalse(self.e._check_signature(r))
377
+
378
+ plain = ('oauth_signature=correctlengthbutthewrongcontent1111&'
379
+ 'oauth_timestamp=1234567890&'
380
+ 'oauth_nonce=abcdefghijklmnopqrstuvwxyz&'
381
+ 'oauth_version=1.0&oauth_signature_method=PLAINTEXT&'
382
+ 'oauth_token=abcdefghijklmnopqrstuvxyz&'
383
+ 'oauth_consumer_key=foo')
384
+ r = self.e._create_request(self.uri, 'GET', plain, URLENCODED)
385
+ self.assertFalse(self.e._check_signature(r))
386
+
387
+ def test_hmac_signature(self):
388
+ hmac_sig = "fmrXnTF4lO4o%2BD0%2FlZaJHP%2FXqEY%3D"
389
+ sig = self.sig % (hmac_sig, "HMAC-SHA1")
390
+ r = self.e._create_request(self.uri, 'GET', sig, URLENCODED)
391
+ self.assertTrue(self.e._check_signature(r))
392
+
393
+ def test_rsa_signature(self):
394
+ rsa_sig = ("fxFvCx33oKlR9wDquJ%2FPsndFzJphyBa3RFPPIKi3flqK%2BJ7yIrMVbH"
395
+ "YTM%2FLHPc7NChWz4F4%2FzRA%2BDN1k08xgYGSBoWJUOW6VvOQ6fbYhMA"
396
+ "FkOGYbuGDbje487XMzsAcv6ZjqZHCROSCk5vofgLk2SN7RZ3OrgrFzf4in"
397
+ "xetClqA%3D")
398
+ sig = self.sig % (rsa_sig, "RSA-SHA1")
399
+ r = self.e._create_request(self.uri, 'GET', sig, URLENCODED)
400
+ self.assertTrue(self.e._check_signature(r))
401
+
402
+ def test_plaintext_signature(self):
403
+ plain_sig = "super%252520secret%26even%252520more%252520secret"
404
+ sig = self.sig % (plain_sig, "PLAINTEXT")
405
+ r = self.e._create_request(self.uri, 'GET', sig, URLENCODED)
406
+ self.assertTrue(self.e._check_signature(r))
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/test_request_token.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unittest.mock import ANY, MagicMock
2
+
3
+ from oauthlib.oauth1 import RequestValidator
4
+ from oauthlib.oauth1.rfc5849 import Client
5
+ from oauthlib.oauth1.rfc5849.endpoints import RequestTokenEndpoint
6
+
7
+ from tests.unittest import TestCase
8
+
9
+
10
+ class RequestTokenEndpointTest(TestCase):
11
+
12
+ def setUp(self):
13
+ self.validator = MagicMock(wraps=RequestValidator())
14
+ self.validator.check_client_key.return_value = True
15
+ self.validator.allowed_signature_methods = ['HMAC-SHA1']
16
+ self.validator.get_client_secret.return_value = 'bar'
17
+ self.validator.get_default_realms.return_value = ['foo']
18
+ self.validator.timestamp_lifetime = 600
19
+ self.validator.check_realms.return_value = True
20
+ self.validator.validate_client_key.return_value = True
21
+ self.validator.validate_requested_realms.return_value = True
22
+ self.validator.validate_redirect_uri.return_value = True
23
+ self.validator.validate_timestamp_and_nonce.return_value = True
24
+ self.validator.dummy_client = 'dummy'
25
+ self.validator.dummy_secret = 'dummy'
26
+ self.validator.save_request_token = MagicMock()
27
+ self.endpoint = RequestTokenEndpoint(self.validator)
28
+ self.client = Client('foo', client_secret='bar', realm='foo',
29
+ callback_uri='https://c.b/cb')
30
+ self.uri, self.headers, self.body = self.client.sign(
31
+ 'https://i.b/request_token')
32
+
33
+ def test_check_redirect_uri(self):
34
+ client = Client('foo')
35
+ uri, headers, _ = client.sign(self.uri)
36
+ h, b, s = self.endpoint.create_request_token_response(
37
+ uri, headers=headers)
38
+ self.assertEqual(s, 400)
39
+ self.assertIn('invalid_request', b)
40
+
41
+ def test_check_realms(self):
42
+ self.validator.check_realms.return_value = False
43
+ h, b, s = self.endpoint.create_request_token_response(
44
+ self.uri, headers=self.headers)
45
+ self.assertEqual(s, 400)
46
+ self.assertIn('invalid_request', b)
47
+
48
+ def test_validate_client_key(self):
49
+ self.validator.validate_client_key.return_value = False
50
+ h, b, s = self.endpoint.create_request_token_response(
51
+ self.uri, headers=self.headers)
52
+ self.assertEqual(s, 401)
53
+
54
+ def test_validate_realms(self):
55
+ self.validator.validate_requested_realms.return_value = False
56
+ h, b, s = self.endpoint.create_request_token_response(
57
+ self.uri, headers=self.headers)
58
+ self.assertEqual(s, 401)
59
+
60
+ def test_validate_redirect_uri(self):
61
+ self.validator.validate_redirect_uri.return_value = False
62
+ h, b, s = self.endpoint.create_request_token_response(
63
+ self.uri, headers=self.headers)
64
+ self.assertEqual(s, 401)
65
+
66
+ def test_validate_signature(self):
67
+ client = Client('foo', callback_uri='https://c.b/cb')
68
+ _, headers, _ = client.sign(self.uri + '/extra')
69
+ h, b, s = self.endpoint.create_request_token_response(
70
+ self.uri, headers=headers)
71
+ self.assertEqual(s, 401)
72
+
73
+ def test_valid_request(self):
74
+ h, b, s = self.endpoint.create_request_token_response(
75
+ self.uri, headers=self.headers)
76
+ self.assertEqual(s, 200)
77
+ self.assertIn('oauth_token', b)
78
+ self.validator.validate_timestamp_and_nonce.assert_called_once_with(
79
+ self.client.client_key, ANY, ANY, ANY,
80
+ request_token=self.client.resource_owner_key)
81
+
82
+ def test_uri_provided_realm(self):
83
+ client = Client('foo', callback_uri='https://c.b/cb',
84
+ client_secret='bar')
85
+ uri = self.uri + '?realm=foo'
86
+ _, headers, _ = client.sign(uri)
87
+ h, b, s = self.endpoint.create_request_token_response(
88
+ uri, headers=headers)
89
+ self.assertEqual(s, 200)
90
+ self.assertIn('oauth_token', b)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/test_resource.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unittest.mock import ANY, MagicMock
2
+
3
+ from oauthlib.oauth1 import RequestValidator
4
+ from oauthlib.oauth1.rfc5849 import Client
5
+ from oauthlib.oauth1.rfc5849.endpoints import ResourceEndpoint
6
+
7
+ from tests.unittest import TestCase
8
+
9
+
10
+ class ResourceEndpointTest(TestCase):
11
+
12
+ def setUp(self):
13
+ self.validator = MagicMock(wraps=RequestValidator())
14
+ self.validator.check_client_key.return_value = True
15
+ self.validator.check_access_token.return_value = True
16
+ self.validator.allowed_signature_methods = ['HMAC-SHA1']
17
+ self.validator.get_client_secret.return_value = 'bar'
18
+ self.validator.get_access_token_secret.return_value = 'secret'
19
+ self.validator.timestamp_lifetime = 600
20
+ self.validator.validate_client_key.return_value = True
21
+ self.validator.validate_access_token.return_value = True
22
+ self.validator.validate_timestamp_and_nonce.return_value = True
23
+ self.validator.validate_realms.return_value = True
24
+ self.validator.dummy_client = 'dummy'
25
+ self.validator.dummy_secret = 'dummy'
26
+ self.validator.dummy_access_token = 'dummy'
27
+ self.endpoint = ResourceEndpoint(self.validator)
28
+ self.client = Client('foo',
29
+ client_secret='bar',
30
+ resource_owner_key='token',
31
+ resource_owner_secret='secret')
32
+ self.uri, self.headers, self.body = self.client.sign(
33
+ 'https://i.b/protected_resource')
34
+
35
+ def test_missing_parameters(self):
36
+ self.validator.check_access_token.return_value = False
37
+ v, r = self.endpoint.validate_protected_resource_request(
38
+ self.uri)
39
+ self.assertFalse(v)
40
+
41
+ def test_check_access_token(self):
42
+ self.validator.check_access_token.return_value = False
43
+ v, r = self.endpoint.validate_protected_resource_request(
44
+ self.uri, headers=self.headers)
45
+ self.assertFalse(v)
46
+
47
+ def test_validate_client_key(self):
48
+ self.validator.validate_client_key.return_value = False
49
+ v, r = self.endpoint.validate_protected_resource_request(
50
+ self.uri, headers=self.headers)
51
+ self.assertFalse(v)
52
+ # the validator log should have `False` values
53
+ self.assertFalse(r.validator_log['client'])
54
+ self.assertTrue(r.validator_log['realm'])
55
+ self.assertTrue(r.validator_log['resource_owner'])
56
+ self.assertTrue(r.validator_log['signature'])
57
+
58
+ def test_validate_access_token(self):
59
+ self.validator.validate_access_token.return_value = False
60
+ v, r = self.endpoint.validate_protected_resource_request(
61
+ self.uri, headers=self.headers)
62
+ self.assertFalse(v)
63
+ # the validator log should have `False` values
64
+ self.assertTrue(r.validator_log['client'])
65
+ self.assertTrue(r.validator_log['realm'])
66
+ self.assertFalse(r.validator_log['resource_owner'])
67
+ self.assertTrue(r.validator_log['signature'])
68
+
69
+ def test_validate_realms(self):
70
+ self.validator.validate_realms.return_value = False
71
+ v, r = self.endpoint.validate_protected_resource_request(
72
+ self.uri, headers=self.headers)
73
+ self.assertFalse(v)
74
+ # the validator log should have `False` values
75
+ self.assertTrue(r.validator_log['client'])
76
+ self.assertFalse(r.validator_log['realm'])
77
+ self.assertTrue(r.validator_log['resource_owner'])
78
+ self.assertTrue(r.validator_log['signature'])
79
+
80
+ def test_validate_signature(self):
81
+ client = Client('foo',
82
+ resource_owner_key='token',
83
+ resource_owner_secret='secret')
84
+ _, headers, _ = client.sign(self.uri + '/extra')
85
+ v, r = self.endpoint.validate_protected_resource_request(
86
+ self.uri, headers=headers)
87
+ self.assertFalse(v)
88
+ # the validator log should have `False` values
89
+ self.assertTrue(r.validator_log['client'])
90
+ self.assertTrue(r.validator_log['realm'])
91
+ self.assertTrue(r.validator_log['resource_owner'])
92
+ self.assertFalse(r.validator_log['signature'])
93
+
94
+ def test_valid_request(self):
95
+ v, r = self.endpoint.validate_protected_resource_request(
96
+ self.uri, headers=self.headers)
97
+ self.assertTrue(v)
98
+ self.validator.validate_timestamp_and_nonce.assert_called_once_with(
99
+ self.client.client_key, ANY, ANY, ANY,
100
+ access_token=self.client.resource_owner_key)
101
+ # everything in the validator_log should be `True`
102
+ self.assertTrue(all(r.validator_log.items()))
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/endpoints/test_signature_only.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unittest.mock import ANY, MagicMock
2
+
3
+ from oauthlib.oauth1 import RequestValidator
4
+ from oauthlib.oauth1.rfc5849 import Client
5
+ from oauthlib.oauth1.rfc5849.endpoints import SignatureOnlyEndpoint
6
+
7
+ from tests.unittest import TestCase
8
+
9
+
10
+ class SignatureOnlyEndpointTest(TestCase):
11
+
12
+ def setUp(self):
13
+ self.validator = MagicMock(wraps=RequestValidator())
14
+ self.validator.check_client_key.return_value = True
15
+ self.validator.allowed_signature_methods = ['HMAC-SHA1']
16
+ self.validator.get_client_secret.return_value = 'bar'
17
+ self.validator.timestamp_lifetime = 600
18
+ self.validator.validate_client_key.return_value = True
19
+ self.validator.validate_timestamp_and_nonce.return_value = True
20
+ self.validator.dummy_client = 'dummy'
21
+ self.validator.dummy_secret = 'dummy'
22
+ self.endpoint = SignatureOnlyEndpoint(self.validator)
23
+ self.client = Client('foo', client_secret='bar')
24
+ self.uri, self.headers, self.body = self.client.sign(
25
+ 'https://i.b/protected_resource')
26
+
27
+ def test_missing_parameters(self):
28
+ v, r = self.endpoint.validate_request(
29
+ self.uri)
30
+ self.assertFalse(v)
31
+
32
+ def test_validate_client_key(self):
33
+ self.validator.validate_client_key.return_value = False
34
+ v, r = self.endpoint.validate_request(
35
+ self.uri, headers=self.headers)
36
+ self.assertFalse(v)
37
+
38
+ def test_validate_signature(self):
39
+ client = Client('foo')
40
+ _, headers, _ = client.sign(self.uri + '/extra')
41
+ v, r = self.endpoint.validate_request(
42
+ self.uri, headers=headers)
43
+ self.assertFalse(v)
44
+
45
+ def test_valid_request(self):
46
+ v, r = self.endpoint.validate_request(
47
+ self.uri, headers=self.headers)
48
+ self.assertTrue(v)
49
+ self.validator.validate_timestamp_and_nonce.assert_called_once_with(
50
+ self.client.client_key, ANY, ANY, ANY)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/test_client.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from oauthlib.common import Request
3
+ from oauthlib.oauth1 import (
4
+ SIGNATURE_HMAC_SHA1, SIGNATURE_HMAC_SHA256, SIGNATURE_PLAINTEXT,
5
+ SIGNATURE_RSA, SIGNATURE_TYPE_BODY, SIGNATURE_TYPE_QUERY,
6
+ )
7
+ from oauthlib.oauth1.rfc5849 import Client
8
+
9
+ from tests.unittest import TestCase
10
+
11
+
12
+ class ClientRealmTests(TestCase):
13
+
14
+ def test_client_no_realm(self):
15
+ client = Client("client-key")
16
+ uri, header, body = client.sign("http://example-uri")
17
+ self.assertTrue(
18
+ header["Authorization"].startswith('OAuth oauth_nonce='))
19
+
20
+ def test_client_realm_sign_with_default_realm(self):
21
+ client = Client("client-key", realm="moo-realm")
22
+ self.assertEqual(client.realm, "moo-realm")
23
+ uri, header, body = client.sign("http://example-uri")
24
+ self.assertTrue(
25
+ header["Authorization"].startswith('OAuth realm="moo-realm",'))
26
+
27
+ def test_client_realm_sign_with_additional_realm(self):
28
+ client = Client("client-key", realm="moo-realm")
29
+ uri, header, body = client.sign("http://example-uri", realm="baa-realm")
30
+ self.assertTrue(
31
+ header["Authorization"].startswith('OAuth realm="baa-realm",'))
32
+ # make sure sign() does not override the default realm
33
+ self.assertEqual(client.realm, "moo-realm")
34
+
35
+
36
+ class ClientConstructorTests(TestCase):
37
+
38
+ def test_convert_to_unicode_resource_owner(self):
39
+ client = Client('client-key',
40
+ resource_owner_key=b'owner key')
41
+ self.assertNotIsInstance(client.resource_owner_key, bytes)
42
+ self.assertEqual(client.resource_owner_key, 'owner key')
43
+
44
+ def test_give_explicit_timestamp(self):
45
+ client = Client('client-key', timestamp='1')
46
+ params = dict(client.get_oauth_params(Request('http://example.com')))
47
+ self.assertEqual(params['oauth_timestamp'], '1')
48
+
49
+ def test_give_explicit_nonce(self):
50
+ client = Client('client-key', nonce='1')
51
+ params = dict(client.get_oauth_params(Request('http://example.com')))
52
+ self.assertEqual(params['oauth_nonce'], '1')
53
+
54
+ def test_decoding(self):
55
+ client = Client('client_key', decoding='utf-8')
56
+ uri, headers, body = client.sign('http://a.b/path?query',
57
+ http_method='POST', body='a=b',
58
+ headers={'Content-Type': 'application/x-www-form-urlencoded'})
59
+ self.assertIsInstance(uri, bytes)
60
+ self.assertIsInstance(body, bytes)
61
+ for k, v in headers.items():
62
+ self.assertIsInstance(k, bytes)
63
+ self.assertIsInstance(v, bytes)
64
+
65
+ def test_hmac_sha1(self):
66
+ client = Client('client_key')
67
+ # instance is using the correct signer method
68
+ self.assertEqual(Client.SIGNATURE_METHODS[SIGNATURE_HMAC_SHA1],
69
+ client.SIGNATURE_METHODS[client.signature_method])
70
+
71
+ def test_hmac_sha256(self):
72
+ client = Client('client_key', signature_method=SIGNATURE_HMAC_SHA256)
73
+ # instance is using the correct signer method
74
+ self.assertEqual(Client.SIGNATURE_METHODS[SIGNATURE_HMAC_SHA256],
75
+ client.SIGNATURE_METHODS[client.signature_method])
76
+
77
+ def test_rsa(self):
78
+ client = Client('client_key', signature_method=SIGNATURE_RSA)
79
+ # instance is using the correct signer method
80
+ self.assertEqual(Client.SIGNATURE_METHODS[SIGNATURE_RSA],
81
+ client.SIGNATURE_METHODS[client.signature_method])
82
+ # don't need an RSA key to instantiate
83
+ self.assertIsNone(client.rsa_key)
84
+
85
+
86
+ class SignatureMethodTest(TestCase):
87
+
88
+ def test_hmac_sha1_method(self):
89
+ client = Client('client_key', timestamp='1234567890', nonce='abc')
90
+ u, h, b = client.sign('http://example.com')
91
+ correct = ('OAuth oauth_nonce="abc", oauth_timestamp="1234567890", '
92
+ 'oauth_version="1.0", oauth_signature_method="HMAC-SHA1", '
93
+ 'oauth_consumer_key="client_key", '
94
+ 'oauth_signature="hH5BWYVqo7QI4EmPBUUe9owRUUQ%3D"')
95
+ self.assertEqual(h['Authorization'], correct)
96
+
97
+ def test_hmac_sha256_method(self):
98
+ client = Client('client_key', signature_method=SIGNATURE_HMAC_SHA256,
99
+ timestamp='1234567890', nonce='abc')
100
+ u, h, b = client.sign('http://example.com')
101
+ correct = ('OAuth oauth_nonce="abc", oauth_timestamp="1234567890", '
102
+ 'oauth_version="1.0", oauth_signature_method="HMAC-SHA256", '
103
+ 'oauth_consumer_key="client_key", '
104
+ 'oauth_signature="JzgJWBxX664OiMW3WE4MEjtYwOjI%2FpaUWHqtdHe68Es%3D"')
105
+ self.assertEqual(h['Authorization'], correct)
106
+
107
+ def test_rsa_method(self):
108
+ private_key = (
109
+ "-----BEGIN RSA PRIVATE KEY-----\nMIICXgIBAAKBgQDk1/bxy"
110
+ "S8Q8jiheHeYYp/4rEKJopeQRRKKpZI4s5i+UPwVpupG\nAlwXWfzXw"
111
+ "SMaKPAoKJNdu7tqKRniqst5uoHXw98gj0x7zamu0Ck1LtQ4c7pFMVa"
112
+ "h\n5IYGhBi2E9ycNS329W27nJPWNCbESTu7snVlG8V8mfvGGg3xNjT"
113
+ "MO7IdrwIDAQAB\nAoGBAOQ2KuH8S5+OrsL4K+wfjoCi6MfxCUyqVU9"
114
+ "GxocdM1m30WyWRFMEz2nKJ8fR\np3vTD4w8yplTOhcoXdQZl0kRoaD"
115
+ "zrcYkm2VvJtQRrX7dKFT8dR8D/Tr7dNQLOXfC\nDY6xveQczE7qt7V"
116
+ "k7lp4FqmxBsaaEuokt78pOOjywZoInjZhAkEA9wz3zoZNT0/i\nrf6"
117
+ "qv2qTIeieUB035N3dyw6f1BGSWYaXSuerDCD/J1qZbAPKKhyHZbVaw"
118
+ "Ft3UMhe\n542UftBaxQJBAO0iJy1I8GQjGnS7B3yvyH3CcLYGy296+"
119
+ "XO/2xKp/d/ty1OIeovx\nC60pLNwuFNF3z9d2GVQAdoQ89hUkOtjZL"
120
+ "eMCQQD0JO6oPHUeUjYT+T7ImAv7UKVT\nSuy30sKjLzqoGw1kR+wv7"
121
+ "C5PeDRvscs4wa4CW9s6mjSrMDkDrmCLuJDtmf55AkEA\nkmaMg2PNr"
122
+ "jUR51F0zOEFycaaqXbGcFwe1/xx9zLmHzMDXd4bsnwt9kk+fe0hQzV"
123
+ "S\nJzatanQit3+feev1PN3QewJAWv4RZeavEUhKv+kLe95Yd0su7lT"
124
+ "LVduVgh4v5yLT\nGa6FHdjGPcfajt+nrpB1n8UQBEH9ZxniokR/IPv"
125
+ "dMlxqXA==\n-----END RSA PRIVATE KEY-----"
126
+ )
127
+ client = Client('client_key', signature_method=SIGNATURE_RSA,
128
+ rsa_key=private_key, timestamp='1234567890', nonce='abc')
129
+ u, h, b = client.sign('http://example.com')
130
+ correct = ('OAuth oauth_nonce="abc", oauth_timestamp="1234567890", '
131
+ 'oauth_version="1.0", oauth_signature_method="RSA-SHA1", '
132
+ 'oauth_consumer_key="client_key", '
133
+ 'oauth_signature="ktvzkUhtrIawBcq21DRJrAyysTc3E1Zq5GdGu8EzH'
134
+ 'OtbeaCmOBDLGHAcqlm92mj7xp5E1Z6i2vbExPimYAJL7FzkLnkRE5YEJR4'
135
+ 'rNtIgAf1OZbYsIUmmBO%2BCLuStuu5Lg3tAluwC7XkkgoXCBaRKT1mUXzP'
136
+ 'HJILzZ8iFOvS6w5E%3D"')
137
+ self.assertEqual(h['Authorization'], correct)
138
+
139
+ def test_plaintext_method(self):
140
+ client = Client('client_key',
141
+ signature_method=SIGNATURE_PLAINTEXT,
142
+ timestamp='1234567890',
143
+ nonce='abc',
144
+ client_secret='foo',
145
+ resource_owner_secret='bar')
146
+ u, h, b = client.sign('http://example.com')
147
+ correct = ('OAuth oauth_nonce="abc", oauth_timestamp="1234567890", '
148
+ 'oauth_version="1.0", oauth_signature_method="PLAINTEXT", '
149
+ 'oauth_consumer_key="client_key", '
150
+ 'oauth_signature="foo%26bar"')
151
+ self.assertEqual(h['Authorization'], correct)
152
+
153
+ def test_invalid_method(self):
154
+ client = Client('client_key', signature_method='invalid')
155
+ self.assertRaises(ValueError, client.sign, 'http://example.com')
156
+
157
+ def test_rsa_no_key(self):
158
+ client = Client('client_key', signature_method=SIGNATURE_RSA)
159
+ self.assertRaises(ValueError, client.sign, 'http://example.com')
160
+
161
+ def test_register_method(self):
162
+ Client.register_signature_method('PIZZA',
163
+ lambda base_string, client: 'PIZZA')
164
+
165
+ self.assertIn('PIZZA', Client.SIGNATURE_METHODS)
166
+
167
+ client = Client('client_key', signature_method='PIZZA',
168
+ timestamp='1234567890', nonce='abc')
169
+
170
+ u, h, b = client.sign('http://example.com')
171
+
172
+ self.assertEqual(h['Authorization'], (
173
+ 'OAuth oauth_nonce="abc", oauth_timestamp="1234567890", '
174
+ 'oauth_version="1.0", oauth_signature_method="PIZZA", '
175
+ 'oauth_consumer_key="client_key", '
176
+ 'oauth_signature="PIZZA"'
177
+ ))
178
+
179
+
180
+ class SignatureTypeTest(TestCase):
181
+
182
+ def test_params_in_body(self):
183
+ client = Client('client_key', signature_type=SIGNATURE_TYPE_BODY,
184
+ timestamp='1378988215', nonce='14205877133089081931378988215')
185
+ _, h, b = client.sign('http://i.b/path', http_method='POST', body='a=b',
186
+ headers={'Content-Type': 'application/x-www-form-urlencoded'})
187
+ self.assertEqual(h['Content-Type'], 'application/x-www-form-urlencoded')
188
+ correct = ('a=b&oauth_nonce=14205877133089081931378988215&'
189
+ 'oauth_timestamp=1378988215&'
190
+ 'oauth_version=1.0&'
191
+ 'oauth_signature_method=HMAC-SHA1&'
192
+ 'oauth_consumer_key=client_key&'
193
+ 'oauth_signature=2JAQomgbShqoscqKWBiYQZwWq94%3D')
194
+ self.assertEqual(b, correct)
195
+
196
+ def test_params_in_query(self):
197
+ client = Client('client_key', signature_type=SIGNATURE_TYPE_QUERY,
198
+ timestamp='1378988215', nonce='14205877133089081931378988215')
199
+ u, _, _ = client.sign('http://i.b/path', http_method='POST')
200
+ correct = ('http://i.b/path?oauth_nonce=14205877133089081931378988215&'
201
+ 'oauth_timestamp=1378988215&'
202
+ 'oauth_version=1.0&'
203
+ 'oauth_signature_method=HMAC-SHA1&'
204
+ 'oauth_consumer_key=client_key&'
205
+ 'oauth_signature=08G5Snvw%2BgDAzBF%2BCmT5KqlrPKo%3D')
206
+ self.assertEqual(u, correct)
207
+
208
+ def test_invalid_signature_type(self):
209
+ client = Client('client_key', signature_type='invalid')
210
+ self.assertRaises(ValueError, client.sign, 'http://i.b/path')
211
+
212
+
213
+ class SigningTest(TestCase):
214
+
215
+ def test_case_insensitive_headers(self):
216
+ client = Client('client_key')
217
+ # Uppercase
218
+ _, h, _ = client.sign('http://i.b/path', http_method='POST', body='',
219
+ headers={'Content-Type': 'application/x-www-form-urlencoded'})
220
+ self.assertEqual(h['Content-Type'], 'application/x-www-form-urlencoded')
221
+
222
+ # Lowercase
223
+ _, h, _ = client.sign('http://i.b/path', http_method='POST', body='',
224
+ headers={'content-type': 'application/x-www-form-urlencoded'})
225
+ self.assertEqual(h['content-type'], 'application/x-www-form-urlencoded')
226
+
227
+ # Capitalized
228
+ _, h, _ = client.sign('http://i.b/path', http_method='POST', body='',
229
+ headers={'Content-type': 'application/x-www-form-urlencoded'})
230
+ self.assertEqual(h['Content-type'], 'application/x-www-form-urlencoded')
231
+
232
+ # Random
233
+ _, h, _ = client.sign('http://i.b/path', http_method='POST', body='',
234
+ headers={'conTent-tYpe': 'application/x-www-form-urlencoded'})
235
+ self.assertEqual(h['conTent-tYpe'], 'application/x-www-form-urlencoded')
236
+
237
+ def test_sign_no_body(self):
238
+ client = Client('client_key', decoding='utf-8')
239
+ self.assertRaises(ValueError, client.sign, 'http://i.b/path',
240
+ http_method='POST', body=None,
241
+ headers={'Content-Type': 'application/x-www-form-urlencoded'})
242
+
243
+ def test_sign_body(self):
244
+ client = Client('client_key')
245
+ _, h, b = client.sign('http://i.b/path', http_method='POST', body='',
246
+ headers={'Content-Type': 'application/x-www-form-urlencoded'})
247
+ self.assertEqual(h['Content-Type'], 'application/x-www-form-urlencoded')
248
+
249
+ def test_sign_get_with_body(self):
250
+ client = Client('client_key')
251
+ for method in ('GET', 'HEAD'):
252
+ self.assertRaises(ValueError, client.sign, 'http://a.b/path?query',
253
+ http_method=method, body='a=b',
254
+ headers={
255
+ 'Content-Type': 'application/x-www-form-urlencoded'
256
+ })
257
+
258
+ def test_sign_unicode(self):
259
+ client = Client('client_key', nonce='abc', timestamp='abc')
260
+ _, h, b = client.sign('http://i.b/path', http_method='POST',
261
+ body='status=%E5%95%A6%E5%95%A6',
262
+ headers={'Content-Type': 'application/x-www-form-urlencoded'})
263
+ self.assertEqual(b, 'status=%E5%95%A6%E5%95%A6')
264
+ self.assertIn('oauth_signature="yrtSqp88m%2Fc5UDaucI8BXK4oEtk%3D"', h['Authorization'])
265
+ _, h, b = client.sign('http://i.b/path', http_method='POST',
266
+ body='status=%C3%A6%C3%A5%C3%B8',
267
+ headers={'Content-Type': 'application/x-www-form-urlencoded'})
268
+ self.assertEqual(b, 'status=%C3%A6%C3%A5%C3%B8')
269
+ self.assertIn('oauth_signature="oG5t3Eg%2FXO5FfQgUUlTtUeeZzvk%3D"', h['Authorization'])
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/test_parameters.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from oauthlib.common import urlencode
3
+ from oauthlib.oauth1.rfc5849.parameters import (
4
+ _append_params, prepare_form_encoded_body, prepare_headers,
5
+ prepare_request_uri_query,
6
+ )
7
+
8
+ from tests.unittest import TestCase
9
+
10
+
11
+ class ParameterTests(TestCase):
12
+ auth_only_params = [
13
+ ('oauth_consumer_key', "9djdj82h48djs9d2"),
14
+ ('oauth_token', "kkk9d7dh3k39sjv7"),
15
+ ('oauth_signature_method', "HMAC-SHA1"),
16
+ ('oauth_timestamp', "137131201"),
17
+ ('oauth_nonce', "7d8f3e4a"),
18
+ ('oauth_signature', "bYT5CMsGcbgUdFHObYMEfcx6bsw=")
19
+ ]
20
+ auth_and_data = list(auth_only_params)
21
+ auth_and_data.append(('data_param_foo', 'foo'))
22
+ auth_and_data.append(('data_param_1', '1'))
23
+ realm = 'testrealm'
24
+ norealm_authorization_header = ' '.join((
25
+ 'OAuth',
26
+ 'oauth_consumer_key="9djdj82h48djs9d2",',
27
+ 'oauth_token="kkk9d7dh3k39sjv7",',
28
+ 'oauth_signature_method="HMAC-SHA1",',
29
+ 'oauth_timestamp="137131201",',
30
+ 'oauth_nonce="7d8f3e4a",',
31
+ 'oauth_signature="bYT5CMsGcbgUdFHObYMEfcx6bsw%3D"',
32
+ ))
33
+ withrealm_authorization_header = ' '.join((
34
+ 'OAuth',
35
+ 'realm="testrealm",',
36
+ 'oauth_consumer_key="9djdj82h48djs9d2",',
37
+ 'oauth_token="kkk9d7dh3k39sjv7",',
38
+ 'oauth_signature_method="HMAC-SHA1",',
39
+ 'oauth_timestamp="137131201",',
40
+ 'oauth_nonce="7d8f3e4a",',
41
+ 'oauth_signature="bYT5CMsGcbgUdFHObYMEfcx6bsw%3D"',
42
+ ))
43
+
44
+ def test_append_params(self):
45
+ unordered_1 = [
46
+ ('oauth_foo', 'foo'),
47
+ ('lala', 123),
48
+ ('oauth_baz', 'baz'),
49
+ ('oauth_bar', 'bar'), ]
50
+ unordered_2 = [
51
+ ('teehee', 456),
52
+ ('oauth_quux', 'quux'), ]
53
+ expected = [
54
+ ('teehee', 456),
55
+ ('lala', 123),
56
+ ('oauth_quux', 'quux'),
57
+ ('oauth_foo', 'foo'),
58
+ ('oauth_baz', 'baz'),
59
+ ('oauth_bar', 'bar'), ]
60
+ self.assertEqual(_append_params(unordered_1, unordered_2), expected)
61
+
62
+ def test_prepare_headers(self):
63
+ self.assertEqual(
64
+ prepare_headers(self.auth_only_params, {}),
65
+ {'Authorization': self.norealm_authorization_header})
66
+ self.assertEqual(
67
+ prepare_headers(self.auth_only_params, {}, realm=self.realm),
68
+ {'Authorization': self.withrealm_authorization_header})
69
+
70
+ def test_prepare_headers_ignore_data(self):
71
+ self.assertEqual(
72
+ prepare_headers(self.auth_and_data, {}),
73
+ {'Authorization': self.norealm_authorization_header})
74
+ self.assertEqual(
75
+ prepare_headers(self.auth_and_data, {}, realm=self.realm),
76
+ {'Authorization': self.withrealm_authorization_header})
77
+
78
+ def test_prepare_form_encoded_body(self):
79
+ existing_body = ''
80
+ form_encoded_body = 'data_param_foo=foo&data_param_1=1&oauth_consumer_key=9djdj82h48djs9d2&oauth_token=kkk9d7dh3k39sjv7&oauth_signature_method=HMAC-SHA1&oauth_timestamp=137131201&oauth_nonce=7d8f3e4a&oauth_signature=bYT5CMsGcbgUdFHObYMEfcx6bsw%3D'
81
+ self.assertEqual(
82
+ urlencode(prepare_form_encoded_body(self.auth_and_data, existing_body)),
83
+ form_encoded_body)
84
+
85
+ def test_prepare_request_uri_query(self):
86
+ url = 'http://notarealdomain.com/foo/bar/baz?some=args&go=here'
87
+ request_uri_query = 'http://notarealdomain.com/foo/bar/baz?some=args&go=here&data_param_foo=foo&data_param_1=1&oauth_consumer_key=9djdj82h48djs9d2&oauth_token=kkk9d7dh3k39sjv7&oauth_signature_method=HMAC-SHA1&oauth_timestamp=137131201&oauth_nonce=7d8f3e4a&oauth_signature=bYT5CMsGcbgUdFHObYMEfcx6bsw%3D'
88
+ self.assertEqual(
89
+ prepare_request_uri_query(self.auth_and_data, url),
90
+ request_uri_query)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/test_request_validator.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from oauthlib.oauth1 import RequestValidator
3
+
4
+ from tests.unittest import TestCase
5
+
6
+
7
+ class RequestValidatorTests(TestCase):
8
+
9
+ def test_not_implemented(self):
10
+ v = RequestValidator()
11
+ self.assertRaises(NotImplementedError, v.get_client_secret, None, None)
12
+ self.assertRaises(NotImplementedError, v.get_request_token_secret,
13
+ None, None, None)
14
+ self.assertRaises(NotImplementedError, v.get_access_token_secret,
15
+ None, None, None)
16
+ self.assertRaises(NotImplementedError, lambda: v.dummy_client)
17
+ self.assertRaises(NotImplementedError, lambda: v.dummy_request_token)
18
+ self.assertRaises(NotImplementedError, lambda: v.dummy_access_token)
19
+ self.assertRaises(NotImplementedError, v.get_rsa_key, None, None)
20
+ self.assertRaises(NotImplementedError, v.get_default_realms, None, None)
21
+ self.assertRaises(NotImplementedError, v.get_realms, None, None)
22
+ self.assertRaises(NotImplementedError, v.get_redirect_uri, None, None)
23
+ self.assertRaises(NotImplementedError, v.validate_client_key, None, None)
24
+ self.assertRaises(NotImplementedError, v.validate_access_token,
25
+ None, None, None)
26
+ self.assertRaises(NotImplementedError, v.validate_request_token,
27
+ None, None, None)
28
+ self.assertRaises(NotImplementedError, v.verify_request_token,
29
+ None, None)
30
+ self.assertRaises(NotImplementedError, v.verify_realms,
31
+ None, None, None)
32
+ self.assertRaises(NotImplementedError, v.validate_timestamp_and_nonce,
33
+ None, None, None, None)
34
+ self.assertRaises(NotImplementedError, v.validate_redirect_uri,
35
+ None, None, None)
36
+ self.assertRaises(NotImplementedError, v.validate_realms,
37
+ None, None, None, None, None)
38
+ self.assertRaises(NotImplementedError, v.validate_requested_realms,
39
+ None, None, None)
40
+ self.assertRaises(NotImplementedError, v.validate_verifier,
41
+ None, None, None, None)
42
+ self.assertRaises(NotImplementedError, v.save_access_token, None, None)
43
+ self.assertRaises(NotImplementedError, v.save_request_token, None, None)
44
+ self.assertRaises(NotImplementedError, v.save_verifier,
45
+ None, None, None)
46
+
47
+ def test_check_length(self):
48
+ v = RequestValidator()
49
+
50
+ for method in (v.check_client_key, v.check_request_token,
51
+ v.check_access_token, v.check_nonce, v.check_verifier):
52
+ for not_valid in ('tooshort', 'invalid?characters!',
53
+ 'thisclientkeyisalittlebittoolong'):
54
+ self.assertFalse(method(not_valid))
55
+ for valid in ('itsjustaboutlongenough',):
56
+ self.assertTrue(method(valid))
57
+
58
+ def test_check_realms(self):
59
+ v = RequestValidator()
60
+ self.assertFalse(v.check_realms(['foo']))
61
+
62
+ class FooRealmValidator(RequestValidator):
63
+ @property
64
+ def realms(self):
65
+ return ['foo']
66
+
67
+ v = FooRealmValidator()
68
+ self.assertTrue(v.check_realms(['foo']))
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/test_signatures.py ADDED
@@ -0,0 +1,903 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from jwt import InvalidKeyError
3
+ from oauthlib.oauth1.rfc5849.signature import (
4
+ base_string_uri, collect_parameters, normalize_parameters,
5
+ sign_hmac_sha1_with_client, sign_hmac_sha256_with_client,
6
+ sign_hmac_sha512_with_client, sign_plaintext_with_client,
7
+ sign_rsa_sha1_with_client, sign_rsa_sha256_with_client,
8
+ sign_rsa_sha512_with_client, signature_base_string, verify_hmac_sha1,
9
+ verify_hmac_sha256, verify_hmac_sha512, verify_plaintext, verify_rsa_sha1,
10
+ verify_rsa_sha256, verify_rsa_sha512,
11
+ )
12
+
13
+ from tests.unittest import TestCase
14
+
15
+ # ################################################################
16
+
17
+ class MockRequest:
18
+ """
19
+ Mock of a request used by the verify_* functions.
20
+ """
21
+
22
+ def __init__(self,
23
+ method: str,
24
+ uri_str: str,
25
+ params: list,
26
+ signature: str):
27
+ """
28
+ The params is a list of (name, value) tuples. It is not a dictionary,
29
+ because there can be multiple parameters with the same name.
30
+ """
31
+ self.uri = uri_str
32
+ self.http_method = method
33
+ self.params = params
34
+ self.signature = signature
35
+
36
+
37
+ # ################################################################
38
+
39
+ class MockClient:
40
+ """
41
+ Mock of client credentials used by the sign_*_with_client functions.
42
+
43
+ For HMAC, set the client_secret and resource_owner_secret.
44
+
45
+ For RSA, set the rsa_key to either a PEM formatted PKCS #1 public key or
46
+ PEM formatted PKCS #1 private key.
47
+ """
48
+ def __init__(self,
49
+ client_secret: str = None,
50
+ resource_owner_secret: str = None,
51
+ rsa_key: str = None):
52
+ self.client_secret = client_secret
53
+ self.resource_owner_secret = resource_owner_secret
54
+ self.rsa_key = rsa_key # used for private or public key: a poor design!
55
+
56
+
57
+ # ################################################################
58
+
59
+ class SignatureTests(TestCase):
60
+ """
61
+ Unit tests for the oauthlib/oauth1/rfc5849/signature.py module.
62
+
63
+ The tests in this class are organised into sections, to test the
64
+ functions relating to:
65
+
66
+ - Signature base string calculation
67
+ - HMAC-based signature methods
68
+ - RSA-based signature methods
69
+ - PLAINTEXT signature method
70
+
71
+ Each section is separated by a comment beginning with "====".
72
+
73
+ Those comments have been formatted to remain visible when the code is
74
+ collapsed using PyCharm's code folding feature. That is, those section
75
+ heading comments do not have any other comment lines around it, so they
76
+ don't get collapsed when the contents of the class is collapsed. While
77
+ there is a "Sequential comments" option in the code folding configuration,
78
+ by default they are folded.
79
+
80
+ They all use some/all of the example test vector, defined in the first
81
+ section below.
82
+ """
83
+
84
+ # ==== Example test vector =======================================
85
+
86
+ eg_signature_base_string = (
87
+ 'POST&http%3A%2F%2Fexample.com%2Frequest&a2%3Dr%2520b%26a3%3D2%2520q'
88
+ '%26a3%3Da%26b5%3D%253D%25253D%26c%2540%3D%26c2%3D%26oauth_consumer_'
89
+ 'key%3D9djdj82h48djs9d2%26oauth_nonce%3D7d8f3e4a%26oauth_signature_m'
90
+ 'ethod%3DHMAC-SHA1%26oauth_timestamp%3D137131201%26oauth_token%3Dkkk'
91
+ '9d7dh3k39sjv7'
92
+ )
93
+
94
+ # The _signature base string_ above is copied from the end of
95
+ # RFC 5849 section 3.4.1.1.
96
+ #
97
+ # It corresponds to the three values below.
98
+ #
99
+ # The _normalized parameters_ below is copied from the end of
100
+ # RFC 5849 section 3.4.1.3.2.
101
+
102
+ eg_http_method = 'POST'
103
+
104
+ eg_base_string_uri = 'http://example.com/request'
105
+
106
+ eg_normalized_parameters = (
107
+ 'a2=r%20b&a3=2%20q&a3=a&b5=%3D%253D&c%40=&c2=&oauth_consumer_key=9dj'
108
+ 'dj82h48djs9d2&oauth_nonce=7d8f3e4a&oauth_signature_method=HMAC-SHA1'
109
+ '&oauth_timestamp=137131201&oauth_token=kkk9d7dh3k39sjv7'
110
+ )
111
+ # The above _normalized parameters_ corresponds to the parameters below.
112
+ #
113
+ # The parameters below is copied from the table at the end of
114
+ # RFC 5849 section 3.4.1.3.1.
115
+
116
+ eg_params = [
117
+ ('b5', '=%3D'),
118
+ ('a3', 'a'),
119
+ ('c@', ''),
120
+ ('a2', 'r b'),
121
+ ('oauth_consumer_key', '9djdj82h48djs9d2'),
122
+ ('oauth_token', 'kkk9d7dh3k39sjv7'),
123
+ ('oauth_signature_method', 'HMAC-SHA1'),
124
+ ('oauth_timestamp', '137131201'),
125
+ ('oauth_nonce', '7d8f3e4a'),
126
+ ('c2', ''),
127
+ ('a3', '2 q'),
128
+ ]
129
+
130
+ # The above parameters correspond to parameters from the three values below.
131
+ #
132
+ # These come from RFC 5849 section 3.4.1.3.1.
133
+
134
+ eg_uri_query = 'b5=%3D%253D&a3=a&c%40=&a2=r%20b'
135
+
136
+ eg_body = 'c2&a3=2+q'
137
+
138
+ eg_authorization_header = (
139
+ 'OAuth realm="Example", oauth_consumer_key="9djdj82h48djs9d2",'
140
+ ' oauth_token="kkk9d7dh3k39sjv7", oauth_signature_method="HMAC-SHA1",'
141
+ ' oauth_timestamp="137131201", oauth_nonce="7d8f3e4a",'
142
+ ' oauth_signature="djosJKDKJSD8743243%2Fjdk33klY%3D"'
143
+ )
144
+ # ==== Signature base string calculating function tests ==========
145
+
146
+ def test_signature_base_string(self):
147
+ """
148
+ Test the ``signature_base_string`` function.
149
+ """
150
+
151
+ # Example from RFC 5849
152
+
153
+ self.assertEqual(
154
+ self.eg_signature_base_string,
155
+ signature_base_string(
156
+ self.eg_http_method,
157
+ self.eg_base_string_uri,
158
+ self.eg_normalized_parameters))
159
+
160
+ # Test method is always uppercase in the signature base string
161
+
162
+ for test_method in ['POST', 'Post', 'pOST', 'poST', 'posT', 'post']:
163
+ self.assertEqual(
164
+ self.eg_signature_base_string,
165
+ signature_base_string(
166
+ test_method,
167
+ self.eg_base_string_uri,
168
+ self.eg_normalized_parameters))
169
+
170
+ def test_base_string_uri(self):
171
+ """
172
+ Test the ``base_string_uri`` function.
173
+ """
174
+
175
+ # ----------------
176
+ # Examples from the OAuth 1.0a specification: RFC 5849.
177
+
178
+ # First example from RFC 5849 section 3.4.1.2.
179
+ #
180
+ # GET /r%20v/X?id=123 HTTP/1.1
181
+ # Host: EXAMPLE.COM:80
182
+ #
183
+ # Note: there is a space between "r" and "v"
184
+
185
+ self.assertEqual(
186
+ 'http://example.com/r%20v/X',
187
+ base_string_uri('http://EXAMPLE.COM:80/r v/X?id=123'))
188
+
189
+ # Second example from RFC 5849 section 3.4.1.2.
190
+ #
191
+ # GET /?q=1 HTTP/1.1
192
+ # Host: www.example.net:8080
193
+
194
+ self.assertEqual(
195
+ 'https://www.example.net:8080/',
196
+ base_string_uri('https://www.example.net:8080/?q=1'))
197
+
198
+ # ----------------
199
+ # Scheme: will always be in lowercase
200
+
201
+ for uri in [
202
+ 'foobar://www.example.com',
203
+ 'FOOBAR://www.example.com',
204
+ 'Foobar://www.example.com',
205
+ 'FooBar://www.example.com',
206
+ 'fOObAR://www.example.com',
207
+ ]:
208
+ self.assertEqual('foobar://www.example.com/', base_string_uri(uri))
209
+
210
+ # ----------------
211
+ # Host: will always be in lowercase
212
+
213
+ for uri in [
214
+ 'http://www.example.com',
215
+ 'http://WWW.EXAMPLE.COM',
216
+ 'http://www.EXAMPLE.com',
217
+ 'http://wWW.eXAMPLE.cOM',
218
+ ]:
219
+ self.assertEqual('http://www.example.com/', base_string_uri(uri))
220
+
221
+ # base_string_uri has an optional host parameter that can be used to
222
+ # override the URI's netloc (or used as the host if there is no netloc)
223
+ # The "netloc" refers to the "hostname[:port]" part of the URI.
224
+
225
+ self.assertEqual(
226
+ 'http://actual.example.com/',
227
+ base_string_uri('http://IGNORE.example.com', 'ACTUAL.example.com'))
228
+
229
+ self.assertEqual(
230
+ 'http://override.example.com/path',
231
+ base_string_uri('http:///path', 'OVERRIDE.example.com'))
232
+
233
+ # ----------------
234
+ # Host: valid host allows for IPv4 and IPv6
235
+
236
+ self.assertEqual(
237
+ 'https://192.168.0.1/',
238
+ base_string_uri('https://192.168.0.1')
239
+ )
240
+ self.assertEqual(
241
+ 'https://192.168.0.1:13000/',
242
+ base_string_uri('https://192.168.0.1:13000')
243
+ )
244
+ self.assertEqual(
245
+ 'https://[123:db8:fd00:1000::5]:13000/',
246
+ base_string_uri('https://[123:db8:fd00:1000::5]:13000')
247
+ )
248
+ self.assertEqual(
249
+ 'https://[123:db8:fd00:1000::5]/',
250
+ base_string_uri('https://[123:db8:fd00:1000::5]')
251
+ )
252
+
253
+ # ----------------
254
+ # Port: default ports always excluded; non-default ports always included
255
+
256
+ self.assertEqual(
257
+ "http://www.example.com/",
258
+ base_string_uri("http://www.example.com:80/")) # default port
259
+
260
+ self.assertEqual(
261
+ "https://www.example.com/",
262
+ base_string_uri("https://www.example.com:443/")) # default port
263
+
264
+ self.assertEqual(
265
+ "https://www.example.com:999/",
266
+ base_string_uri("https://www.example.com:999/")) # non-default port
267
+
268
+ self.assertEqual(
269
+ "http://www.example.com:443/",
270
+ base_string_uri("HTTP://www.example.com:443/")) # non-default port
271
+
272
+ self.assertEqual(
273
+ "https://www.example.com:80/",
274
+ base_string_uri("HTTPS://www.example.com:80/")) # non-default port
275
+
276
+ self.assertEqual(
277
+ "http://www.example.com/",
278
+ base_string_uri("http://www.example.com:/")) # colon but no number
279
+
280
+ # ----------------
281
+ # Paths
282
+
283
+ self.assertEqual(
284
+ 'http://www.example.com/',
285
+ base_string_uri('http://www.example.com')) # no slash
286
+
287
+ self.assertEqual(
288
+ 'http://www.example.com/',
289
+ base_string_uri('http://www.example.com/')) # with slash
290
+
291
+ self.assertEqual(
292
+ 'http://www.example.com:8080/',
293
+ base_string_uri('http://www.example.com:8080')) # no slash
294
+
295
+ self.assertEqual(
296
+ 'http://www.example.com:8080/',
297
+ base_string_uri('http://www.example.com:8080/')) # with slash
298
+
299
+ self.assertEqual(
300
+ 'http://www.example.com/foo/bar',
301
+ base_string_uri('http://www.example.com/foo/bar')) # no slash
302
+ self.assertEqual(
303
+ 'http://www.example.com/foo/bar/',
304
+ base_string_uri('http://www.example.com/foo/bar/')) # with slash
305
+
306
+ # ----------------
307
+ # Query parameters & fragment IDs do not appear in the base string URI
308
+
309
+ self.assertEqual(
310
+ 'https://www.example.com/path',
311
+ base_string_uri('https://www.example.com/path?foo=bar'))
312
+
313
+ self.assertEqual(
314
+ 'https://www.example.com/path',
315
+ base_string_uri('https://www.example.com/path#fragment'))
316
+
317
+ # ----------------
318
+ # Percent encoding
319
+ #
320
+ # RFC 5849 does not specify what characters are percent encoded, but in
321
+ # one of its examples it shows spaces being percent encoded.
322
+ # So it is assumed that spaces must be encoded, but we don't know what
323
+ # other characters are encoded or not.
324
+
325
+ self.assertEqual(
326
+ 'https://www.example.com/hello%20world',
327
+ base_string_uri('https://www.example.com/hello world'))
328
+
329
+ self.assertEqual(
330
+ 'https://www.hello%20world.com/',
331
+ base_string_uri('https://www.hello world.com/'))
332
+
333
+ # ----------------
334
+ # Errors detected
335
+
336
+ # base_string_uri expects a string
337
+ self.assertRaises(ValueError, base_string_uri, None)
338
+ self.assertRaises(ValueError, base_string_uri, 42)
339
+ self.assertRaises(ValueError, base_string_uri, b'http://example.com')
340
+
341
+ # Missing scheme is an error
342
+ self.assertRaises(ValueError, base_string_uri, '')
343
+ self.assertRaises(ValueError, base_string_uri, ' ') # single space
344
+ self.assertRaises(ValueError, base_string_uri, 'http')
345
+ self.assertRaises(ValueError, base_string_uri, 'example.com')
346
+
347
+ # Missing host is an error
348
+ self.assertRaises(ValueError, base_string_uri, 'http:')
349
+ self.assertRaises(ValueError, base_string_uri, 'http://')
350
+ self.assertRaises(ValueError, base_string_uri, 'http://:8080')
351
+
352
+ # Port is not a valid TCP/IP port number
353
+ self.assertRaises(ValueError, base_string_uri, 'http://eg.com:0')
354
+ self.assertRaises(ValueError, base_string_uri, 'http://eg.com:-1')
355
+ self.assertRaises(ValueError, base_string_uri, 'http://eg.com:65536')
356
+ self.assertRaises(ValueError, base_string_uri, 'http://eg.com:3.14')
357
+ self.assertRaises(ValueError, base_string_uri, 'http://eg.com:BAD')
358
+ self.assertRaises(ValueError, base_string_uri, 'http://eg.com:NaN')
359
+ self.assertRaises(ValueError, base_string_uri, 'http://eg.com: ')
360
+ self.assertRaises(ValueError, base_string_uri, 'http://eg.com:42:42')
361
+
362
+ def test_collect_parameters(self):
363
+ """
364
+ Test the ``collect_parameters`` function.
365
+ """
366
+
367
+ # ----------------
368
+ # Examples from the OAuth 1.0a specification: RFC 5849.
369
+
370
+ params = collect_parameters(
371
+ self.eg_uri_query,
372
+ self.eg_body,
373
+ {'Authorization': self.eg_authorization_header})
374
+
375
+ # Check params contains the same pairs as control_params, ignoring order
376
+ self.assertEqual(sorted(self.eg_params), sorted(params))
377
+
378
+ # ----------------
379
+ # Examples with no parameters
380
+
381
+ self.assertEqual([], collect_parameters('', '', {}))
382
+
383
+ self.assertEqual([], collect_parameters(None, None, None))
384
+
385
+ self.assertEqual([], collect_parameters())
386
+
387
+ self.assertEqual([], collect_parameters(headers={'foo': 'bar'}))
388
+
389
+ # ----------------
390
+ # Test effect of exclude_oauth_signature"
391
+
392
+ no_sig = collect_parameters(
393
+ headers={'authorization': self.eg_authorization_header})
394
+ with_sig = collect_parameters(
395
+ headers={'authorization': self.eg_authorization_header},
396
+ exclude_oauth_signature=False)
397
+
398
+ self.assertEqual(sorted(no_sig + [('oauth_signature',
399
+ 'djosJKDKJSD8743243/jdk33klY=')]),
400
+ sorted(with_sig))
401
+
402
+ # ----------------
403
+ # Test effect of "with_realm" as well as header name case insensitivity
404
+
405
+ no_realm = collect_parameters(
406
+ headers={'authorization': self.eg_authorization_header},
407
+ with_realm=False)
408
+ with_realm = collect_parameters(
409
+ headers={'AUTHORIZATION': self.eg_authorization_header},
410
+ with_realm=True)
411
+
412
+ self.assertEqual(sorted(no_realm + [('realm', 'Example')]),
413
+ sorted(with_realm))
414
+
415
+ def test_normalize_parameters(self):
416
+ """
417
+ Test the ``normalize_parameters`` function.
418
+ """
419
+
420
+ # headers = {'Authorization': self.authorization_header}
421
+ # parameters = collect_parameters(
422
+ # uri_query=self.uri_query, body=self.body, headers=headers)
423
+ # normalized = normalize_parameters(parameters)
424
+ #
425
+ # # Unicode everywhere and always
426
+ # self.assertIsInstance(normalized, str)
427
+ #
428
+ # # Lets see if things are in order
429
+ # # check to see that querystring keys come in alphanumeric order:
430
+ # querystring_keys = ['a2', 'a3', 'b5', 'oauth_consumer_key',
431
+ # 'oauth_nonce', 'oauth_signature_method',
432
+ # 'oauth_timestamp', 'oauth_token']
433
+ # index = -1 # start at -1 because the 'a2' key starts at index 0
434
+ # for key in querystring_keys:
435
+ # self.assertGreater(normalized.index(key), index)
436
+ # index = normalized.index(key)
437
+
438
+ # ----------------
439
+ # Example from the OAuth 1.0a specification: RFC 5849.
440
+ # Params from end of section 3.4.1.3.1. and the expected
441
+ # normalized parameters from the end of section 3.4.1.3.2.
442
+
443
+ self.assertEqual(self.eg_normalized_parameters,
444
+ normalize_parameters(self.eg_params))
445
+
446
+ # ==== HMAC-based signature method tests =========================
447
+
448
+ hmac_client = MockClient(
449
+ client_secret='ECrDNoq1VYzzzzzzzzzyAK7TwZNtPnkqatqZZZZ',
450
+ resource_owner_secret='just-a-string asdasd')
451
+
452
+ # The following expected signatures were calculated by putting the value of
453
+ # the eg_signature_base_string in a file ("base-str.txt") and running:
454
+ #
455
+ # echo -n `cat base-str.txt` | openssl dgst -hmac KEY -sha1 -binary| base64
456
+ #
457
+ # Where the KEY is the concatenation of the client_secret, an ampersand and
458
+ # the resource_owner_secret. But those values need to be encoded properly,
459
+ # so the spaces in the resource_owner_secret must be represented as '%20'.
460
+ #
461
+ # Note: the "echo -n" is needed to remove the last newline character, which
462
+ # most text editors will add.
463
+
464
+ expected_signature_hmac_sha1 = \
465
+ 'wsdNmjGB7lvis0UJuPAmjvX/PXw='
466
+
467
+ expected_signature_hmac_sha256 = \
468
+ 'wdfdHUKXHbOnOGZP8WFAWMSAmWzN3EVBWWgXGlC/Eo4='
469
+
470
+ expected_signature_hmac_sha512 = (
471
+ 'u/vlyZFDxOWOZ9UUXwRBJHvq8/T4jCA74ocRmn2ECnjUBTAeJiZIRU8hDTjS88Tz'
472
+ '1fGONffMpdZxUkUTW3k1kg=='
473
+ )
474
+ def test_sign_hmac_sha1_with_client(self):
475
+ """
476
+ Test sign and verify with HMAC-SHA1.
477
+ """
478
+ self.assertEqual(
479
+ self.expected_signature_hmac_sha1,
480
+ sign_hmac_sha1_with_client(self.eg_signature_base_string,
481
+ self.hmac_client))
482
+ self.assertTrue(verify_hmac_sha1(
483
+ MockRequest('POST',
484
+ 'http://example.com/request',
485
+ self.eg_params,
486
+ self.expected_signature_hmac_sha1),
487
+ self.hmac_client.client_secret,
488
+ self.hmac_client.resource_owner_secret))
489
+
490
+ def test_sign_hmac_sha256_with_client(self):
491
+ """
492
+ Test sign and verify with HMAC-SHA256.
493
+ """
494
+ self.assertEqual(
495
+ self.expected_signature_hmac_sha256,
496
+ sign_hmac_sha256_with_client(self.eg_signature_base_string,
497
+ self.hmac_client))
498
+ self.assertTrue(verify_hmac_sha256(
499
+ MockRequest('POST',
500
+ 'http://example.com/request',
501
+ self.eg_params,
502
+ self.expected_signature_hmac_sha256),
503
+ self.hmac_client.client_secret,
504
+ self.hmac_client.resource_owner_secret))
505
+
506
+ def test_sign_hmac_sha512_with_client(self):
507
+ """
508
+ Test sign and verify with HMAC-SHA512.
509
+ """
510
+ self.assertEqual(
511
+ self.expected_signature_hmac_sha512,
512
+ sign_hmac_sha512_with_client(self.eg_signature_base_string,
513
+ self.hmac_client))
514
+ self.assertTrue(verify_hmac_sha512(
515
+ MockRequest('POST',
516
+ 'http://example.com/request',
517
+ self.eg_params,
518
+ self.expected_signature_hmac_sha512),
519
+ self.hmac_client.client_secret,
520
+ self.hmac_client.resource_owner_secret))
521
+
522
+ def test_hmac_false_positives(self):
523
+ """
524
+ Test verify_hmac-* functions will correctly detect invalid signatures.
525
+ """
526
+
527
+ _ros = self.hmac_client.resource_owner_secret
528
+
529
+ for functions in [
530
+ (sign_hmac_sha1_with_client, verify_hmac_sha1),
531
+ (sign_hmac_sha256_with_client, verify_hmac_sha256),
532
+ (sign_hmac_sha512_with_client, verify_hmac_sha512),
533
+ ]:
534
+ signing_function = functions[0]
535
+ verify_function = functions[1]
536
+
537
+ good_signature = \
538
+ signing_function(
539
+ self.eg_signature_base_string,
540
+ self.hmac_client)
541
+
542
+ bad_signature_on_different_value = \
543
+ signing_function(
544
+ 'not the signature base string',
545
+ self.hmac_client)
546
+
547
+ bad_signature_produced_by_different_client_secret = \
548
+ signing_function(
549
+ self.eg_signature_base_string,
550
+ MockClient(client_secret='wrong-secret',
551
+ resource_owner_secret=_ros))
552
+ bad_signature_produced_by_different_resource_owner_secret = \
553
+ signing_function(
554
+ self.eg_signature_base_string,
555
+ MockClient(client_secret=self.hmac_client.client_secret,
556
+ resource_owner_secret='wrong-secret'))
557
+
558
+ bad_signature_produced_with_no_resource_owner_secret = \
559
+ signing_function(
560
+ self.eg_signature_base_string,
561
+ MockClient(client_secret=self.hmac_client.client_secret))
562
+ bad_signature_produced_with_no_client_secret = \
563
+ signing_function(
564
+ self.eg_signature_base_string,
565
+ MockClient(resource_owner_secret=_ros))
566
+
567
+ self.assertTrue(verify_function(
568
+ MockRequest('POST',
569
+ 'http://example.com/request',
570
+ self.eg_params,
571
+ good_signature),
572
+ self.hmac_client.client_secret,
573
+ self.hmac_client.resource_owner_secret))
574
+
575
+ for bad_signature in [
576
+ '',
577
+ 'ZG9uJ3QgdHJ1c3QgbWUK', # random base64 encoded value
578
+ 'altérer', # value with a non-ASCII character in it
579
+ bad_signature_on_different_value,
580
+ bad_signature_produced_by_different_client_secret,
581
+ bad_signature_produced_by_different_resource_owner_secret,
582
+ bad_signature_produced_with_no_resource_owner_secret,
583
+ bad_signature_produced_with_no_client_secret,
584
+ ]:
585
+ self.assertFalse(verify_function(
586
+ MockRequest('POST',
587
+ 'http://example.com/request',
588
+ self.eg_params,
589
+ bad_signature),
590
+ self.hmac_client.client_secret,
591
+ self.hmac_client.resource_owner_secret))
592
+
593
+ # ==== RSA-based signature methods tests =========================
594
+
595
+ rsa_private_client = MockClient(rsa_key='''
596
+ -----BEGIN RSA PRIVATE KEY-----
597
+ MIICXgIBAAKBgQDk1/bxyS8Q8jiheHeYYp/4rEKJopeQRRKKpZI4s5i+UPwVpupG
598
+ AlwXWfzXwSMaKPAoKJNdu7tqKRniqst5uoHXw98gj0x7zamu0Ck1LtQ4c7pFMVah
599
+ 5IYGhBi2E9ycNS329W27nJPWNCbESTu7snVlG8V8mfvGGg3xNjTMO7IdrwIDAQAB
600
+ AoGBAOQ2KuH8S5+OrsL4K+wfjoCi6MfxCUyqVU9GxocdM1m30WyWRFMEz2nKJ8fR
601
+ p3vTD4w8yplTOhcoXdQZl0kRoaDzrcYkm2VvJtQRrX7dKFT8dR8D/Tr7dNQLOXfC
602
+ DY6xveQczE7qt7Vk7lp4FqmxBsaaEuokt78pOOjywZoInjZhAkEA9wz3zoZNT0/i
603
+ rf6qv2qTIeieUB035N3dyw6f1BGSWYaXSuerDCD/J1qZbAPKKhyHZbVawFt3UMhe
604
+ 542UftBaxQJBAO0iJy1I8GQjGnS7B3yvyH3CcLYGy296+XO/2xKp/d/ty1OIeovx
605
+ C60pLNwuFNF3z9d2GVQAdoQ89hUkOtjZLeMCQQD0JO6oPHUeUjYT+T7ImAv7UKVT
606
+ Suy30sKjLzqoGw1kR+wv7C5PeDRvscs4wa4CW9s6mjSrMDkDrmCLuJDtmf55AkEA
607
+ kmaMg2PNrjUR51F0zOEFycaaqXbGcFwe1/xx9zLmHzMDXd4bsnwt9kk+fe0hQzVS
608
+ JzatanQit3+feev1PN3QewJAWv4RZeavEUhKv+kLe95Yd0su7lTLVduVgh4v5yLT
609
+ Ga6FHdjGPcfajt+nrpB1n8UQBEH9ZxniokR/IPvdMlxqXA==
610
+ -----END RSA PRIVATE KEY-----
611
+ ''')
612
+
613
+ rsa_public_client = MockClient(rsa_key='''
614
+ -----BEGIN RSA PUBLIC KEY-----
615
+ MIGJAoGBAOTX9vHJLxDyOKF4d5hin/isQomil5BFEoqlkjizmL5Q/BWm6kYCXBdZ
616
+ /NfBIxoo8Cgok127u2opGeKqy3m6gdfD3yCPTHvNqa7QKTUu1DhzukUxVqHkhgaE
617
+ GLYT3Jw1Lfb1bbuck9Y0JsRJO7uydWUbxXyZ+8YaDfE2NMw7sh2vAgMBAAE=
618
+ -----END RSA PUBLIC KEY-----
619
+ ''')
620
+
621
+ # The above private key was generated using:
622
+ # $ openssl genrsa -out example.pvt 1024
623
+ # $ chmod 600 example.pvt
624
+ # Public key was extract from it using:
625
+ # $ ssh-keygen -e -m pem -f example.pvt
626
+ # PEM encoding requires the key to be concatenated with linebreaks.
627
+
628
+ # The following expected signatures were calculated by putting the private
629
+ # key in a file (test.pvt) and the value of sig_base_str_rsa in another file
630
+ # ("base-str.txt") and running:
631
+ #
632
+ # echo -n `cat base-str.txt` | openssl dgst -sha1 -sign test.pvt| base64
633
+ #
634
+ # Note: the "echo -n" is needed to remove the last newline character, which
635
+ # most text editors will add.
636
+
637
+ expected_signature_rsa_sha1 = (
638
+ 'mFY2KOEnlYWsTvUA+5kxuBIcvBYXu+ljw9ttVJQxKduMueGSVPCB1tK1PlqVLK738'
639
+ 'HK0t19ecBJfb6rMxUwrriw+MlBO+jpojkZIWccw1J4cAb4qu4M81DbpUAq4j/1w/Q'
640
+ 'yTR4TWCODlEfN7Zfgy8+pf+TjiXfIwRC1jEWbuL1E='
641
+ )
642
+ expected_signature_rsa_sha256 = (
643
+ 'jqKl6m0WS69tiVJV8ZQ6aQEfJqISoZkiPBXRv6Al2+iFSaDpfeXjYm+Hbx6m1azR'
644
+ 'drZ/35PM3cvuid3LwW/siAkzb0xQcGnTyAPH8YcGWzmnKGY7LsB7fkqThchNxvRK'
645
+ '/N7s9M1WMnfZZ+1dQbbwtTs1TG1+iexUcV7r3M7Heec='
646
+ )
647
+ expected_signature_rsa_sha512 = (
648
+ 'jL1CnjlsNd25qoZVHZ2oJft47IRYTjpF5CvCUjL3LY0NTnbEeVhE4amWXUFBe9GL'
649
+ 'DWdUh/79ZWNOrCirBFIP26cHLApjYdt4ZG7EVK0/GubS2v8wT1QPRsog8zyiMZkm'
650
+ 'g4JXdWCGXG8YRvRJTg+QKhXuXwS6TcMNakrgzgFIVhA='
651
+ )
652
+ def test_sign_rsa_sha1_with_client(self):
653
+ """
654
+ Test sign and verify with RSA-SHA1.
655
+ """
656
+ self.assertEqual(
657
+ self.expected_signature_rsa_sha1,
658
+ sign_rsa_sha1_with_client(self.eg_signature_base_string,
659
+ self.rsa_private_client))
660
+ self.assertTrue(verify_rsa_sha1(
661
+ MockRequest('POST',
662
+ 'http://example.com/request',
663
+ self.eg_params,
664
+ self.expected_signature_rsa_sha1),
665
+ self.rsa_public_client.rsa_key))
666
+
667
+ def test_sign_rsa_sha256_with_client(self):
668
+ """
669
+ Test sign and verify with RSA-SHA256.
670
+ """
671
+ self.assertEqual(
672
+ self.expected_signature_rsa_sha256,
673
+ sign_rsa_sha256_with_client(self.eg_signature_base_string,
674
+ self.rsa_private_client))
675
+ self.assertTrue(verify_rsa_sha256(
676
+ MockRequest('POST',
677
+ 'http://example.com/request',
678
+ self.eg_params,
679
+ self.expected_signature_rsa_sha256),
680
+ self.rsa_public_client.rsa_key))
681
+
682
+ def test_sign_rsa_sha512_with_client(self):
683
+ """
684
+ Test sign and verify with RSA-SHA512.
685
+ """
686
+ self.assertEqual(
687
+ self.expected_signature_rsa_sha512,
688
+ sign_rsa_sha512_with_client(self.eg_signature_base_string,
689
+ self.rsa_private_client))
690
+ self.assertTrue(verify_rsa_sha512(
691
+ MockRequest('POST',
692
+ 'http://example.com/request',
693
+ self.eg_params,
694
+ self.expected_signature_rsa_sha512),
695
+ self.rsa_public_client.rsa_key))
696
+
697
+ def test_rsa_false_positives(self):
698
+ """
699
+ Test verify_rsa-* functions will correctly detect invalid signatures.
700
+ """
701
+
702
+ another_client = MockClient(rsa_key='''
703
+ -----BEGIN RSA PRIVATE KEY-----
704
+ MIICXQIBAAKBgQDZcD/1OZNJJ6Y3QZM16Z+O7fkD9kTIQuT2BfpAOUvDfxzYhVC9
705
+ TNmSDHCQhr+ClutyolBk5jTE1/FXFUuHoPsTrkI7KQFXPP834D4gnSY9jrAiUJHe
706
+ DVF6wXNuS7H4Ueh16YPjUxgLLRh/nn/JSEj98gsw+7DP01OWMfWS99S7eQIDAQAB
707
+ AoGBALsQZRXVyK7BG7CiC8HwEcNnXDpaXmZjlpNKJTenk1THQMvONd4GBZAuf5D3
708
+ PD9fE4R1u/ByVKecmBaxTV+L0TRQfD8K/nbQe0SKRQIkLI2ymLJKC/eyw5iTKT0E
709
+ +BS6wYpVd+mfcqgvpHOYpUmz9X8k/eOa7uslFmvt+sDb5ZcBAkEA+++SRqqUxFEG
710
+ s/ZWAKw9p5YgkeVUOYVUwyAeZ97heySrjVzg1nZ6v6kv7iOPi9KOEpaIGPW7x1K/
711
+ uQuSt4YEqQJBANzyNqZTTPpv7b/R8ABFy0YMwPVNt3b1GOU1Xxl6iuhH2WcHuueo
712
+ UB13JHoZCMZ7hsEqieEz6uteUjdRzRPKclECQFNhVK4iop3emzNQYeJTHwyp+RmQ
713
+ JrHq2MTDioyiDUouNsDQbnFMQQ/RtNVB265Q/0hTnbN1ELLFRkK9+87VghECQQC9
714
+ hacLFPk6+TffCp3sHfI3rEj4Iin1iFhKhHWGzW7JwJfjoOXaQK44GDLZ6Q918g+t
715
+ MmgDHR2tt8KeYTSgfU+BAkBcaVF91EQ7VXhvyABNYjeYP7lU7orOgdWMa/zbLXSU
716
+ 4vLsK1WOmwPY9zsXpPkilqszqcru4gzlG462cSbEdAW9
717
+ -----END RSA PRIVATE KEY-----
718
+ ''')
719
+
720
+ for functions in [
721
+ (sign_rsa_sha1_with_client, verify_rsa_sha1),
722
+ (sign_rsa_sha256_with_client, verify_rsa_sha256),
723
+ (sign_rsa_sha512_with_client, verify_rsa_sha512),
724
+ ]:
725
+ signing_function = functions[0]
726
+ verify_function = functions[1]
727
+
728
+ good_signature = \
729
+ signing_function(self.eg_signature_base_string,
730
+ self.rsa_private_client)
731
+
732
+ bad_signature_on_different_value = \
733
+ signing_function('wrong value signed', self.rsa_private_client)
734
+
735
+ bad_signature_produced_by_different_private_key = \
736
+ signing_function(self.eg_signature_base_string, another_client)
737
+
738
+ self.assertTrue(verify_function(
739
+ MockRequest('POST',
740
+ 'http://example.com/request',
741
+ self.eg_params,
742
+ good_signature),
743
+ self.rsa_public_client.rsa_key))
744
+
745
+ for bad_signature in [
746
+ '',
747
+ 'ZG9uJ3QgdHJ1c3QgbWUK', # random base64 encoded value
748
+ 'altérer', # value with a non-ASCII character in it
749
+ bad_signature_on_different_value,
750
+ bad_signature_produced_by_different_private_key,
751
+ ]:
752
+ self.assertFalse(verify_function(
753
+ MockRequest('POST',
754
+ 'http://example.com/request',
755
+ self.eg_params,
756
+ bad_signature),
757
+ self.rsa_public_client.rsa_key))
758
+
759
+ def test_rsa_bad_keys(self):
760
+ """
761
+ Testing RSA sign and verify with bad key values produces errors.
762
+
763
+ This test is useful for coverage tests, since it runs the code branches
764
+ that deal with error situations.
765
+ """
766
+
767
+ # Signing needs a private key
768
+
769
+ for bad_value in [None, '']:
770
+ self.assertRaises(ValueError,
771
+ sign_rsa_sha1_with_client,
772
+ self.eg_signature_base_string,
773
+ MockClient(rsa_key=bad_value))
774
+
775
+ self.assertRaises(InvalidKeyError,
776
+ sign_rsa_sha1_with_client,
777
+ self.eg_signature_base_string,
778
+ MockClient(rsa_key='foobar'))
779
+
780
+ self.assertRaises(AttributeError,
781
+ sign_rsa_sha1_with_client,
782
+ self.eg_signature_base_string,
783
+ self.rsa_public_client) # public key doesn't sign
784
+
785
+ # Verify needs a public key
786
+
787
+ for bad_value in [None, '', 'foobar', self.rsa_private_client.rsa_key]:
788
+ self.assertRaises(TypeError,
789
+ verify_rsa_sha1,
790
+ MockRequest('POST',
791
+ 'http://example.com/request',
792
+ self.eg_params,
793
+ self.expected_signature_rsa_sha1),
794
+ MockClient(rsa_key=bad_value))
795
+
796
+ # For completeness, this text could repeat the above for RSA-SHA256 and
797
+ # RSA-SHA512 signing and verification functions.
798
+
799
+ def test_rsa_jwt_algorithm_cache(self):
800
+ # Tests cache of RSAAlgorithm objects is implemented correctly.
801
+
802
+ # This is difficult to test, since the cache is internal.
803
+ #
804
+ # Running this test with coverage will show the cache-hit branch of code
805
+ # being executed by two signing operations with the same hash algorithm.
806
+
807
+ self.test_sign_rsa_sha1_with_client() # creates cache entry
808
+ self.test_sign_rsa_sha1_with_client() # reuses cache entry
809
+
810
+ # Some possible bugs will be detected if multiple signing operations
811
+ # with different hash algorithms produce the wrong results (e.g. if the
812
+ # cache incorrectly returned the previously used algorithm, instead
813
+ # of the one that is needed).
814
+
815
+ self.test_sign_rsa_sha256_with_client()
816
+ self.test_sign_rsa_sha256_with_client()
817
+ self.test_sign_rsa_sha1_with_client()
818
+ self.test_sign_rsa_sha256_with_client()
819
+ self.test_sign_rsa_sha512_with_client()
820
+
821
+ # ==== PLAINTEXT signature method tests ==========================
822
+
823
+ plaintext_client = hmac_client # for convenience, use the same HMAC secrets
824
+
825
+ expected_signature_plaintext = (
826
+ 'ECrDNoq1VYzzzzzzzzzyAK7TwZNtPnkqatqZZZZ'
827
+ '&'
828
+ 'just-a-string%20%20%20%20asdasd')
829
+
830
+ def test_sign_plaintext_with_client(self):
831
+ # With PLAINTEXT, the "signature" is always the same: regardless of the
832
+ # contents of the request. It is the concatenation of the encoded
833
+ # client_secret, an ampersand, and the encoded resource_owner_secret.
834
+ #
835
+ # That is why the spaces in the resource owner secret are "%20".
836
+
837
+ self.assertEqual(self.expected_signature_plaintext,
838
+ sign_plaintext_with_client(None, # request is ignored
839
+ self.plaintext_client))
840
+ self.assertTrue(verify_plaintext(
841
+ MockRequest('PUT',
842
+ 'http://example.com/some-other-path',
843
+ [('description', 'request is ignored in PLAINTEXT')],
844
+ self.expected_signature_plaintext),
845
+ self.plaintext_client.client_secret,
846
+ self.plaintext_client.resource_owner_secret))
847
+
848
+ def test_plaintext_false_positives(self):
849
+ """
850
+ Test verify_plaintext function will correctly detect invalid signatures.
851
+ """
852
+
853
+ _ros = self.plaintext_client.resource_owner_secret
854
+
855
+ good_signature = \
856
+ sign_plaintext_with_client(
857
+ self.eg_signature_base_string,
858
+ self.plaintext_client)
859
+
860
+ bad_signature_produced_by_different_client_secret = \
861
+ sign_plaintext_with_client(
862
+ self.eg_signature_base_string,
863
+ MockClient(client_secret='wrong-secret',
864
+ resource_owner_secret=_ros))
865
+ bad_signature_produced_by_different_resource_owner_secret = \
866
+ sign_plaintext_with_client(
867
+ self.eg_signature_base_string,
868
+ MockClient(client_secret=self.plaintext_client.client_secret,
869
+ resource_owner_secret='wrong-secret'))
870
+
871
+ bad_signature_produced_with_no_resource_owner_secret = \
872
+ sign_plaintext_with_client(
873
+ self.eg_signature_base_string,
874
+ MockClient(client_secret=self.plaintext_client.client_secret))
875
+ bad_signature_produced_with_no_client_secret = \
876
+ sign_plaintext_with_client(
877
+ self.eg_signature_base_string,
878
+ MockClient(resource_owner_secret=_ros))
879
+
880
+ self.assertTrue(verify_plaintext(
881
+ MockRequest('POST',
882
+ 'http://example.com/request',
883
+ self.eg_params,
884
+ good_signature),
885
+ self.plaintext_client.client_secret,
886
+ self.plaintext_client.resource_owner_secret))
887
+
888
+ for bad_signature in [
889
+ '',
890
+ 'ZG9uJ3QgdHJ1c3QgbWUK', # random base64 encoded value
891
+ 'altérer', # value with a non-ASCII character in it
892
+ bad_signature_produced_by_different_client_secret,
893
+ bad_signature_produced_by_different_resource_owner_secret,
894
+ bad_signature_produced_with_no_resource_owner_secret,
895
+ bad_signature_produced_with_no_client_secret,
896
+ ]:
897
+ self.assertFalse(verify_plaintext(
898
+ MockRequest('POST',
899
+ 'http://example.com/request',
900
+ self.eg_params,
901
+ bad_signature),
902
+ self.plaintext_client.client_secret,
903
+ self.plaintext_client.resource_owner_secret))
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth1/rfc5849/test_utils.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from oauthlib.oauth1.rfc5849.utils import *
3
+
4
+ from tests.unittest import TestCase
5
+
6
+
7
+ class UtilsTests(TestCase):
8
+
9
+ sample_params_list = [
10
+ ("notoauth", "shouldnotbehere"),
11
+ ("oauth_consumer_key", "9djdj82h48djs9d2"),
12
+ ("oauth_token", "kkk9d7dh3k39sjv7"),
13
+ ("notoautheither", "shouldnotbehere")
14
+ ]
15
+
16
+ sample_params_dict = {
17
+ "notoauth": "shouldnotbehere",
18
+ "oauth_consumer_key": "9djdj82h48djs9d2",
19
+ "oauth_token": "kkk9d7dh3k39sjv7",
20
+ "notoautheither": "shouldnotbehere"
21
+ }
22
+
23
+ sample_params_unicode_list = [
24
+ ("notoauth", "shouldnotbehere"),
25
+ ("oauth_consumer_key", "9djdj82h48djs9d2"),
26
+ ("oauth_token", "kkk9d7dh3k39sjv7"),
27
+ ("notoautheither", "shouldnotbehere")
28
+ ]
29
+
30
+ sample_params_unicode_dict = {
31
+ "notoauth": "shouldnotbehere",
32
+ "oauth_consumer_key": "9djdj82h48djs9d2",
33
+ "oauth_token": "kkk9d7dh3k39sjv7",
34
+ "notoautheither": "shouldnotbehere"
35
+ }
36
+
37
+ authorization_header = """OAuth realm="Example",
38
+ oauth_consumer_key="9djdj82h48djs9d2",
39
+ oauth_token="kkk9d7dh3k39sjv7",
40
+ oauth_signature_method="HMAC-SHA1",
41
+ oauth_timestamp="137131201",
42
+ oauth_nonce="7d8f3e4a",
43
+ oauth_signature="djosJKDKJSD8743243%2Fjdk33klY%3D" """.strip()
44
+ bad_authorization_headers = (
45
+ "OAuth",
46
+ "OAuth oauth_nonce=",
47
+ "Negotiate b2F1dGhsaWI=",
48
+ "OA",
49
+ )
50
+
51
+ def test_filter_params(self):
52
+
53
+ # The following is an isolated test function used to test the filter_params decorator.
54
+ @filter_params
55
+ def special_test_function(params, realm=None):
56
+ """I am a special test function"""
57
+ return 'OAuth ' + ','.join(['='.join([k, v]) for k, v in params])
58
+
59
+ # check that the docstring got through
60
+ self.assertEqual(special_test_function.__doc__, "I am a special test function")
61
+
62
+ # Check that the decorator filtering works as per design.
63
+ # Any param that does not start with 'oauth'
64
+ # should not be present in the filtered params
65
+ filtered_params = special_test_function(self.sample_params_list)
66
+ self.assertNotIn("notoauth", filtered_params)
67
+ self.assertIn("oauth_consumer_key", filtered_params)
68
+ self.assertIn("oauth_token", filtered_params)
69
+ self.assertNotIn("notoautheither", filtered_params)
70
+
71
+ def test_filter_oauth_params(self):
72
+
73
+ # try with list
74
+ # try with list
75
+ # try with list
76
+ self.assertEqual(len(self.sample_params_list), 4)
77
+
78
+ # Any param that does not start with 'oauth'
79
+ # should not be present in the filtered params
80
+ filtered_params = filter_oauth_params(self.sample_params_list)
81
+ self.assertEqual(len(filtered_params), 2)
82
+
83
+ self.assertTrue(filtered_params[0][0].startswith('oauth'))
84
+ self.assertTrue(filtered_params[1][0].startswith('oauth'))
85
+
86
+ # try with dict
87
+ # try with dict
88
+ # try with dict
89
+ self.assertEqual(len(self.sample_params_dict), 4)
90
+
91
+ # Any param that does not start with 'oauth'
92
+ # should not be present in the filtered params
93
+ filtered_params = filter_oauth_params(self.sample_params_dict)
94
+ self.assertEqual(len(filtered_params), 2)
95
+
96
+ self.assertTrue(filtered_params[0][0].startswith('oauth'))
97
+ self.assertTrue(filtered_params[1][0].startswith('oauth'))
98
+
99
+ def test_escape(self):
100
+ self.assertRaises(ValueError, escape, b"I am a string type. Not a unicode type.")
101
+ self.assertEqual(escape("I am a unicode type."), "I%20am%20a%20unicode%20type.")
102
+ self.assertIsInstance(escape("I am a unicode type."), str)
103
+
104
+ def test_unescape(self):
105
+ self.assertRaises(ValueError, unescape, b"I am a string type. Not a unicode type.")
106
+ self.assertEqual(unescape("I%20am%20a%20unicode%20type."), 'I am a unicode type.')
107
+ self.assertIsInstance(unescape("I%20am%20a%20unicode%20type."), str)
108
+
109
+ def test_parse_authorization_header(self):
110
+ # make us some headers
111
+ authorization_headers = parse_authorization_header(self.authorization_header)
112
+
113
+ # is it a list?
114
+ self.assertIsInstance(authorization_headers, list)
115
+
116
+ # are the internal items tuples?
117
+ for header in authorization_headers:
118
+ self.assertIsInstance(header, tuple)
119
+
120
+ # are the internal components of each tuple unicode?
121
+ for k, v in authorization_headers:
122
+ self.assertIsInstance(k, str)
123
+ self.assertIsInstance(v, str)
124
+
125
+ # let's check the parsed headers created
126
+ correct_headers = [
127
+ ("oauth_nonce", "7d8f3e4a"),
128
+ ("oauth_timestamp", "137131201"),
129
+ ("oauth_consumer_key", "9djdj82h48djs9d2"),
130
+ ('oauth_signature', 'djosJKDKJSD8743243%2Fjdk33klY%3D'),
131
+ ('oauth_signature_method', 'HMAC-SHA1'),
132
+ ('oauth_token', 'kkk9d7dh3k39sjv7'),
133
+ ('realm', 'Example')]
134
+ self.assertEqual(sorted(authorization_headers), sorted(correct_headers))
135
+
136
+ # Check against malformed headers.
137
+ for header in self.bad_authorization_headers:
138
+ self.assertRaises(ValueError, parse_authorization_header, header)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/__init__.py ADDED
File without changes
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/__init__.py ADDED
File without changes
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/__init__.py ADDED
File without changes
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/test_backend_application.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ from unittest.mock import patch
4
+
5
+ from oauthlib import signals
6
+ from oauthlib.oauth2 import BackendApplicationClient
7
+
8
+ from tests.unittest import TestCase
9
+
10
+
11
+ @patch('time.time', new=lambda: 1000)
12
+ class BackendApplicationClientTest(TestCase):
13
+
14
+ client_id = "someclientid"
15
+ client_secret = 'someclientsecret'
16
+ scope = ["/profile"]
17
+ kwargs = {
18
+ "some": "providers",
19
+ "require": "extra arguments"
20
+ }
21
+
22
+ body = "not=empty"
23
+
24
+ body_up = "not=empty&grant_type=client_credentials"
25
+ body_kwargs = body_up + "&some=providers&require=extra+arguments"
26
+
27
+ token_json = ('{ "access_token":"2YotnFZFEjr1zCsicMWpAA",'
28
+ ' "token_type":"example",'
29
+ ' "expires_in":3600,'
30
+ ' "scope":"/profile",'
31
+ ' "example_parameter":"example_value"}')
32
+ token = {
33
+ "access_token": "2YotnFZFEjr1zCsicMWpAA",
34
+ "token_type": "example",
35
+ "expires_in": 3600,
36
+ "expires_at": 4600,
37
+ "scope": ["/profile"],
38
+ "example_parameter": "example_value"
39
+ }
40
+
41
+ def test_request_body(self):
42
+ client = BackendApplicationClient(self.client_id)
43
+
44
+ # Basic, no extra arguments
45
+ body = client.prepare_request_body(body=self.body)
46
+ self.assertFormBodyEqual(body, self.body_up)
47
+
48
+ rclient = BackendApplicationClient(self.client_id)
49
+ body = rclient.prepare_request_body(body=self.body)
50
+ self.assertFormBodyEqual(body, self.body_up)
51
+
52
+ # With extra parameters
53
+ body = client.prepare_request_body(body=self.body, **self.kwargs)
54
+ self.assertFormBodyEqual(body, self.body_kwargs)
55
+
56
+ def test_parse_token_response(self):
57
+ client = BackendApplicationClient(self.client_id)
58
+
59
+ # Parse code and state
60
+ response = client.parse_request_body_response(self.token_json, scope=self.scope)
61
+ self.assertEqual(response, self.token)
62
+ self.assertEqual(client.access_token, response.get("access_token"))
63
+ self.assertEqual(client.refresh_token, response.get("refresh_token"))
64
+ self.assertEqual(client.token_type, response.get("token_type"))
65
+
66
+ # Mismatching state
67
+ self.assertRaises(Warning, client.parse_request_body_response, self.token_json, scope="invalid")
68
+ os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '3'
69
+ token = client.parse_request_body_response(self.token_json, scope="invalid")
70
+ self.assertTrue(token.scope_changed)
71
+
72
+ scope_changes_recorded = []
73
+ def record_scope_change(sender, message, old, new):
74
+ scope_changes_recorded.append((message, old, new))
75
+
76
+ signals.scope_changed.connect(record_scope_change)
77
+ try:
78
+ client.parse_request_body_response(self.token_json, scope="invalid")
79
+ self.assertEqual(len(scope_changes_recorded), 1)
80
+ message, old, new = scope_changes_recorded[0]
81
+ self.assertEqual(message, 'Scope has changed from "invalid" to "/profile".')
82
+ self.assertEqual(old, ['invalid'])
83
+ self.assertEqual(new, ['/profile'])
84
+ finally:
85
+ signals.scope_changed.disconnect(record_scope_change)
86
+ del os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE']
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/test_base.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import datetime
3
+ from unittest.mock import patch
4
+
5
+ from oauthlib import common
6
+ from oauthlib.oauth2 import Client, InsecureTransportError, TokenExpiredError
7
+ from oauthlib.oauth2.rfc6749 import utils
8
+ from oauthlib.oauth2.rfc6749.clients import AUTH_HEADER, BODY, URI_QUERY
9
+
10
+ from tests.unittest import TestCase
11
+
12
+
13
+ class ClientTest(TestCase):
14
+
15
+ client_id = "someclientid"
16
+ uri = "https://example.com/path?query=world"
17
+ body = "not=empty"
18
+ headers = {}
19
+ access_token = "token"
20
+ mac_key = "secret"
21
+
22
+ bearer_query = uri + "&access_token=" + access_token
23
+ bearer_header = {
24
+ "Authorization": "Bearer " + access_token
25
+ }
26
+ bearer_body = body + "&access_token=" + access_token
27
+
28
+ mac_00_header = {
29
+ "Authorization": 'MAC id="' + access_token + '", nonce="0:abc123",' +
30
+ ' bodyhash="Yqyso8r3hR5Nm1ZFv+6AvNHrxjE=",' +
31
+ ' mac="0X6aACoBY0G6xgGZVJ1IeE8dF9k="'
32
+ }
33
+ mac_01_header = {
34
+ "Authorization": 'MAC id="' + access_token + '", ts="123456789",' +
35
+ ' nonce="abc123", mac="Xuk+9oqaaKyhitkgh1CD0xrI6+s="'
36
+ }
37
+
38
+ def test_add_bearer_token(self):
39
+ """Test a number of bearer token placements"""
40
+
41
+ # Invalid token type
42
+ client = Client(self.client_id, token_type="invalid")
43
+ self.assertRaises(ValueError, client.add_token, self.uri)
44
+
45
+ # Case-insensitive token type
46
+ client = Client(self.client_id, access_token=self.access_token, token_type="bEAreR")
47
+ uri, headers, body = client.add_token(self.uri, body=self.body,
48
+ headers=self.headers)
49
+ self.assertURLEqual(uri, self.uri)
50
+ self.assertFormBodyEqual(body, self.body)
51
+ self.assertEqual(headers, self.bearer_header)
52
+
53
+ # Non-HTTPS
54
+ insecure_uri = 'http://example.com/path?query=world'
55
+ client = Client(self.client_id, access_token=self.access_token, token_type="Bearer")
56
+ self.assertRaises(InsecureTransportError, client.add_token, insecure_uri,
57
+ body=self.body,
58
+ headers=self.headers)
59
+
60
+ # Missing access token
61
+ client = Client(self.client_id)
62
+ self.assertRaises(ValueError, client.add_token, self.uri)
63
+
64
+ # Expired token
65
+ expired = 523549800
66
+ expired_token = {
67
+ 'expires_at': expired,
68
+ }
69
+ client = Client(self.client_id, token=expired_token, access_token=self.access_token, token_type="Bearer")
70
+ self.assertRaises(TokenExpiredError, client.add_token, self.uri,
71
+ body=self.body, headers=self.headers)
72
+
73
+ # The default token placement, bearer in auth header
74
+ client = Client(self.client_id, access_token=self.access_token)
75
+ uri, headers, body = client.add_token(self.uri, body=self.body,
76
+ headers=self.headers)
77
+ self.assertURLEqual(uri, self.uri)
78
+ self.assertFormBodyEqual(body, self.body)
79
+ self.assertEqual(headers, self.bearer_header)
80
+
81
+ # Setting default placements of tokens
82
+ client = Client(self.client_id, access_token=self.access_token,
83
+ default_token_placement=AUTH_HEADER)
84
+ uri, headers, body = client.add_token(self.uri, body=self.body,
85
+ headers=self.headers)
86
+ self.assertURLEqual(uri, self.uri)
87
+ self.assertFormBodyEqual(body, self.body)
88
+ self.assertEqual(headers, self.bearer_header)
89
+
90
+ client = Client(self.client_id, access_token=self.access_token,
91
+ default_token_placement=URI_QUERY)
92
+ uri, headers, body = client.add_token(self.uri, body=self.body,
93
+ headers=self.headers)
94
+ self.assertURLEqual(uri, self.bearer_query)
95
+ self.assertFormBodyEqual(body, self.body)
96
+ self.assertEqual(headers, self.headers)
97
+
98
+ client = Client(self.client_id, access_token=self.access_token,
99
+ default_token_placement=BODY)
100
+ uri, headers, body = client.add_token(self.uri, body=self.body,
101
+ headers=self.headers)
102
+ self.assertURLEqual(uri, self.uri)
103
+ self.assertFormBodyEqual(body, self.bearer_body)
104
+ self.assertEqual(headers, self.headers)
105
+
106
+ # Asking for specific placement in the add_token method
107
+ client = Client(self.client_id, access_token=self.access_token)
108
+ uri, headers, body = client.add_token(self.uri, body=self.body,
109
+ headers=self.headers, token_placement=AUTH_HEADER)
110
+ self.assertURLEqual(uri, self.uri)
111
+ self.assertFormBodyEqual(body, self.body)
112
+ self.assertEqual(headers, self.bearer_header)
113
+
114
+ client = Client(self.client_id, access_token=self.access_token)
115
+ uri, headers, body = client.add_token(self.uri, body=self.body,
116
+ headers=self.headers, token_placement=URI_QUERY)
117
+ self.assertURLEqual(uri, self.bearer_query)
118
+ self.assertFormBodyEqual(body, self.body)
119
+ self.assertEqual(headers, self.headers)
120
+
121
+ client = Client(self.client_id, access_token=self.access_token)
122
+ uri, headers, body = client.add_token(self.uri, body=self.body,
123
+ headers=self.headers, token_placement=BODY)
124
+ self.assertURLEqual(uri, self.uri)
125
+ self.assertFormBodyEqual(body, self.bearer_body)
126
+ self.assertEqual(headers, self.headers)
127
+
128
+ # Invalid token placement
129
+ client = Client(self.client_id, access_token=self.access_token)
130
+ self.assertRaises(ValueError, client.add_token, self.uri, body=self.body,
131
+ headers=self.headers, token_placement="invalid")
132
+
133
+ client = Client(self.client_id, access_token=self.access_token,
134
+ default_token_placement="invalid")
135
+ self.assertRaises(ValueError, client.add_token, self.uri, body=self.body,
136
+ headers=self.headers)
137
+
138
+ def test_add_mac_token(self):
139
+ # Missing access token
140
+ client = Client(self.client_id, token_type="MAC")
141
+ self.assertRaises(ValueError, client.add_token, self.uri)
142
+
143
+ # Invalid hash algorithm
144
+ client = Client(self.client_id, token_type="MAC",
145
+ access_token=self.access_token, mac_key=self.mac_key,
146
+ mac_algorithm="hmac-sha-2")
147
+ self.assertRaises(ValueError, client.add_token, self.uri)
148
+
149
+ orig_generate_timestamp = common.generate_timestamp
150
+ orig_generate_nonce = common.generate_nonce
151
+ orig_generate_age = utils.generate_age
152
+ self.addCleanup(setattr, common, 'generage_timestamp', orig_generate_timestamp)
153
+ self.addCleanup(setattr, common, 'generage_nonce', orig_generate_nonce)
154
+ self.addCleanup(setattr, utils, 'generate_age', orig_generate_age)
155
+ common.generate_timestamp = lambda: '123456789'
156
+ common.generate_nonce = lambda: 'abc123'
157
+ utils.generate_age = lambda *args: 0
158
+
159
+ # Add the Authorization header (draft 00)
160
+ client = Client(self.client_id, token_type="MAC",
161
+ access_token=self.access_token, mac_key=self.mac_key,
162
+ mac_algorithm="hmac-sha-1")
163
+ uri, headers, body = client.add_token(self.uri, body=self.body,
164
+ headers=self.headers, issue_time=datetime.datetime.now())
165
+ self.assertEqual(uri, self.uri)
166
+ self.assertEqual(body, self.body)
167
+ self.assertEqual(headers, self.mac_00_header)
168
+ # Non-HTTPS
169
+ insecure_uri = 'http://example.com/path?query=world'
170
+ self.assertRaises(InsecureTransportError, client.add_token, insecure_uri,
171
+ body=self.body,
172
+ headers=self.headers,
173
+ issue_time=datetime.datetime.now())
174
+ # Expired Token
175
+ expired = 523549800
176
+ expired_token = {
177
+ 'expires_at': expired,
178
+ }
179
+ client = Client(self.client_id, token=expired_token, token_type="MAC",
180
+ access_token=self.access_token, mac_key=self.mac_key,
181
+ mac_algorithm="hmac-sha-1")
182
+ self.assertRaises(TokenExpiredError, client.add_token, self.uri,
183
+ body=self.body,
184
+ headers=self.headers,
185
+ issue_time=datetime.datetime.now())
186
+
187
+ # Add the Authorization header (draft 01)
188
+ client = Client(self.client_id, token_type="MAC",
189
+ access_token=self.access_token, mac_key=self.mac_key,
190
+ mac_algorithm="hmac-sha-1")
191
+ uri, headers, body = client.add_token(self.uri, body=self.body,
192
+ headers=self.headers, draft=1)
193
+ self.assertEqual(uri, self.uri)
194
+ self.assertEqual(body, self.body)
195
+ self.assertEqual(headers, self.mac_01_header)
196
+ # Non-HTTPS
197
+ insecure_uri = 'http://example.com/path?query=world'
198
+ self.assertRaises(InsecureTransportError, client.add_token, insecure_uri,
199
+ body=self.body,
200
+ headers=self.headers,
201
+ draft=1)
202
+ # Expired Token
203
+ expired = 523549800
204
+ expired_token = {
205
+ 'expires_at': expired,
206
+ }
207
+ client = Client(self.client_id, token=expired_token, token_type="MAC",
208
+ access_token=self.access_token, mac_key=self.mac_key,
209
+ mac_algorithm="hmac-sha-1")
210
+ self.assertRaises(TokenExpiredError, client.add_token, self.uri,
211
+ body=self.body,
212
+ headers=self.headers,
213
+ draft=1)
214
+
215
+ def test_revocation_request(self):
216
+ client = Client(self.client_id)
217
+
218
+ url = 'https://example.com/revoke'
219
+ token = 'foobar'
220
+
221
+ # Valid request
222
+ u, h, b = client.prepare_token_revocation_request(url, token)
223
+ self.assertEqual(u, url)
224
+ self.assertEqual(h, {'Content-Type': 'application/x-www-form-urlencoded'})
225
+ self.assertEqual(b, 'token=%s&token_type_hint=access_token' % token)
226
+
227
+ # Non-HTTPS revocation endpoint
228
+ self.assertRaises(InsecureTransportError,
229
+ client.prepare_token_revocation_request,
230
+ 'http://example.com/revoke', token)
231
+
232
+
233
+ u, h, b = client.prepare_token_revocation_request(
234
+ url, token, token_type_hint='refresh_token')
235
+ self.assertEqual(u, url)
236
+ self.assertEqual(h, {'Content-Type': 'application/x-www-form-urlencoded'})
237
+ self.assertEqual(b, 'token=%s&token_type_hint=refresh_token' % token)
238
+
239
+ # JSONP
240
+ u, h, b = client.prepare_token_revocation_request(
241
+ url, token, callback='hello.world')
242
+ self.assertURLEqual(u, url + '?callback=hello.world&token=%s&token_type_hint=access_token' % token)
243
+ self.assertEqual(h, {'Content-Type': 'application/x-www-form-urlencoded'})
244
+ self.assertEqual(b, '')
245
+
246
+ def test_prepare_authorization_request(self):
247
+ redirect_url = 'https://example.com/callback/'
248
+ scopes = 'read'
249
+ auth_url = 'https://example.com/authorize/'
250
+ state = 'fake_state'
251
+
252
+ client = Client(self.client_id, redirect_url=redirect_url, scope=scopes, state=state)
253
+
254
+ # Non-HTTPS
255
+ self.assertRaises(InsecureTransportError,
256
+ client.prepare_authorization_request, 'http://example.com/authorize/')
257
+
258
+ # NotImplementedError
259
+ self.assertRaises(NotImplementedError, client.prepare_authorization_request, auth_url)
260
+
261
+ def test_prepare_token_request(self):
262
+ redirect_url = 'https://example.com/callback/'
263
+ scopes = 'read'
264
+ token_url = 'https://example.com/token/'
265
+ state = 'fake_state'
266
+
267
+ client = Client(self.client_id, scope=scopes, state=state)
268
+
269
+ # Non-HTTPS
270
+ self.assertRaises(InsecureTransportError,
271
+ client.prepare_token_request, 'http://example.com/token/')
272
+
273
+ # NotImplementedError
274
+ self.assertRaises(NotImplementedError, client.prepare_token_request, token_url)
275
+
276
+ def test_prepare_refresh_token_request(self):
277
+ client = Client(self.client_id)
278
+
279
+ url = 'https://example.com/revoke'
280
+ token = 'foobar'
281
+ scope = 'extra_scope'
282
+
283
+ u, h, b = client.prepare_refresh_token_request(url, token)
284
+ self.assertEqual(u, url)
285
+ self.assertEqual(h, {'Content-Type': 'application/x-www-form-urlencoded'})
286
+ self.assertFormBodyEqual(b, 'grant_type=refresh_token&refresh_token=%s' % token)
287
+
288
+ # Non-HTTPS revocation endpoint
289
+ self.assertRaises(InsecureTransportError,
290
+ client.prepare_refresh_token_request,
291
+ 'http://example.com/revoke', token)
292
+
293
+ # provide extra scope
294
+ u, h, b = client.prepare_refresh_token_request(url, token, scope=scope)
295
+ self.assertEqual(u, url)
296
+ self.assertEqual(h, {'Content-Type': 'application/x-www-form-urlencoded'})
297
+ self.assertFormBodyEqual(b, 'grant_type=refresh_token&scope={}&refresh_token={}'.format(scope, token))
298
+
299
+ # provide scope while init
300
+ client = Client(self.client_id, scope=scope)
301
+ u, h, b = client.prepare_refresh_token_request(url, token, scope=scope)
302
+ self.assertEqual(u, url)
303
+ self.assertEqual(h, {'Content-Type': 'application/x-www-form-urlencoded'})
304
+ self.assertFormBodyEqual(b, 'grant_type=refresh_token&scope={}&refresh_token={}'.format(scope, token))
305
+
306
+ def test_parse_token_response_invalid_expires_at(self):
307
+ token_json = ('{ "access_token":"2YotnFZFEjr1zCsicMWpAA",'
308
+ ' "token_type":"example",'
309
+ ' "expires_at":"2006-01-02T15:04:05Z",'
310
+ ' "scope":"/profile",'
311
+ ' "example_parameter":"example_value"}')
312
+ token = {
313
+ "access_token": "2YotnFZFEjr1zCsicMWpAA",
314
+ "token_type": "example",
315
+ "expires_at": "2006-01-02T15:04:05Z",
316
+ "scope": ["/profile"],
317
+ "example_parameter": "example_value"
318
+ }
319
+
320
+ client = Client(self.client_id)
321
+
322
+ # Parse code and state
323
+ response = client.parse_request_body_response(token_json, scope=["/profile"])
324
+ self.assertEqual(response, token)
325
+ self.assertEqual(None, client._expires_at)
326
+ self.assertEqual(client.access_token, response.get("access_token"))
327
+ self.assertEqual(client.refresh_token, response.get("refresh_token"))
328
+ self.assertEqual(client.token_type, response.get("token_type"))
329
+
330
+
331
+ def test_create_code_verifier_min_length(self):
332
+ client = Client(self.client_id)
333
+ length = 43
334
+ code_verifier = client.create_code_verifier(length=length)
335
+ self.assertEqual(client.code_verifier, code_verifier)
336
+
337
+ def test_create_code_verifier_max_length(self):
338
+ client = Client(self.client_id)
339
+ length = 128
340
+ code_verifier = client.create_code_verifier(length=length)
341
+ self.assertEqual(client.code_verifier, code_verifier)
342
+
343
+ def test_create_code_verifier_length(self):
344
+ client = Client(self.client_id)
345
+ length = 96
346
+ code_verifier = client.create_code_verifier(length=length)
347
+ self.assertEqual(len(code_verifier), length)
348
+
349
+ def test_create_code_challenge_plain(self):
350
+ client = Client(self.client_id)
351
+ code_verifier = client.create_code_verifier(length=128)
352
+ code_challenge_plain = client.create_code_challenge(code_verifier=code_verifier)
353
+
354
+ # if no code_challenge_method specified, code_challenge = code_verifier
355
+ self.assertEqual(code_challenge_plain, client.code_verifier)
356
+ self.assertEqual(client.code_challenge_method, "plain")
357
+
358
+ def test_create_code_challenge_s256(self):
359
+ client = Client(self.client_id)
360
+ code_verifier = client.create_code_verifier(length=128)
361
+ code_challenge_s256 = client.create_code_challenge(code_verifier=code_verifier, code_challenge_method='S256')
362
+ self.assertEqual(code_challenge_s256, client.code_challenge)
363
+
364
+ def test_parse_token_response_expires_at_is_int(self):
365
+ expected_expires_at = 1661185149
366
+ token_json = ('{ "access_token":"2YotnFZFEjr1zCsicMWpAA",'
367
+ ' "token_type":"example",'
368
+ ' "expires_at":1661185148.6437678,'
369
+ ' "scope":"/profile",'
370
+ ' "example_parameter":"example_value"}')
371
+
372
+ client = Client(self.client_id)
373
+
374
+ response = client.parse_request_body_response(token_json, scope=["/profile"])
375
+
376
+ self.assertEqual(response['expires_at'], expected_expires_at)
377
+ self.assertEqual(client._expires_at, expected_expires_at)
378
+
379
+ @patch('time.time')
380
+ def test_parse_token_response_generated_expires_at_is_int(self, t):
381
+ t.return_value = 1661185148.6437678
382
+ expected_expires_at = round(t.return_value) + 3600
383
+ token_json = ('{ "access_token":"2YotnFZFEjr1zCsicMWpAA",'
384
+ ' "token_type":"example",'
385
+ ' "expires_in":3600,'
386
+ ' "scope":"/profile",'
387
+ ' "example_parameter":"example_value"}')
388
+
389
+ client = Client(self.client_id)
390
+
391
+ response = client.parse_request_body_response(token_json, scope=["/profile"])
392
+
393
+ self.assertEqual(response['expires_at'], expected_expires_at)
394
+ self.assertEqual(client._expires_at, expected_expires_at)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/test_legacy_application.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import urllib.parse as urlparse
4
+ from unittest.mock import patch
5
+
6
+ from oauthlib import signals
7
+ from oauthlib.oauth2 import LegacyApplicationClient
8
+
9
+ from tests.unittest import TestCase
10
+
11
+
12
+ @patch('time.time', new=lambda: 1000)
13
+ class LegacyApplicationClientTest(TestCase):
14
+
15
+ client_id = "someclientid"
16
+ client_secret = 'someclientsecret'
17
+ scope = ["/profile"]
18
+ kwargs = {
19
+ "some": "providers",
20
+ "require": "extra arguments"
21
+ }
22
+
23
+ username = "user_username"
24
+ password = "user_password"
25
+ body = "not=empty"
26
+
27
+ body_up = "not=empty&grant_type=password&username={}&password={}".format(username, password)
28
+ body_kwargs = body_up + "&some=providers&require=extra+arguments"
29
+
30
+ token_json = ('{ "access_token":"2YotnFZFEjr1zCsicMWpAA",'
31
+ ' "token_type":"example",'
32
+ ' "expires_in":3600,'
33
+ ' "scope":"/profile",'
34
+ ' "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",'
35
+ ' "example_parameter":"example_value"}')
36
+ token = {
37
+ "access_token": "2YotnFZFEjr1zCsicMWpAA",
38
+ "token_type": "example",
39
+ "expires_in": 3600,
40
+ "expires_at": 4600,
41
+ "scope": scope,
42
+ "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
43
+ "example_parameter": "example_value"
44
+ }
45
+
46
+ def test_request_body(self):
47
+ client = LegacyApplicationClient(self.client_id)
48
+
49
+ # Basic, no extra arguments
50
+ body = client.prepare_request_body(self.username, self.password,
51
+ body=self.body)
52
+ self.assertFormBodyEqual(body, self.body_up)
53
+
54
+ # With extra parameters
55
+ body = client.prepare_request_body(self.username, self.password,
56
+ body=self.body, **self.kwargs)
57
+ self.assertFormBodyEqual(body, self.body_kwargs)
58
+
59
+ def test_parse_token_response(self):
60
+ client = LegacyApplicationClient(self.client_id)
61
+
62
+ # Parse code and state
63
+ response = client.parse_request_body_response(self.token_json, scope=self.scope)
64
+ self.assertEqual(response, self.token)
65
+ self.assertEqual(client.access_token, response.get("access_token"))
66
+ self.assertEqual(client.refresh_token, response.get("refresh_token"))
67
+ self.assertEqual(client.token_type, response.get("token_type"))
68
+
69
+ # Mismatching state
70
+ self.assertRaises(Warning, client.parse_request_body_response, self.token_json, scope="invalid")
71
+ os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '5'
72
+ token = client.parse_request_body_response(self.token_json, scope="invalid")
73
+ self.assertTrue(token.scope_changed)
74
+
75
+ scope_changes_recorded = []
76
+ def record_scope_change(sender, message, old, new):
77
+ scope_changes_recorded.append((message, old, new))
78
+
79
+ signals.scope_changed.connect(record_scope_change)
80
+ try:
81
+ client.parse_request_body_response(self.token_json, scope="invalid")
82
+ self.assertEqual(len(scope_changes_recorded), 1)
83
+ message, old, new = scope_changes_recorded[0]
84
+ self.assertEqual(message, 'Scope has changed from "invalid" to "/profile".')
85
+ self.assertEqual(old, ['invalid'])
86
+ self.assertEqual(new, ['/profile'])
87
+ finally:
88
+ signals.scope_changed.disconnect(record_scope_change)
89
+ del os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE']
90
+
91
+ def test_prepare_request_body(self):
92
+ """
93
+ see issue #585
94
+ https://github.com/oauthlib/oauthlib/issues/585
95
+ """
96
+ client = LegacyApplicationClient(self.client_id)
97
+
98
+ # scenario 1, default behavior to not include `client_id`
99
+ r1 = client.prepare_request_body(username=self.username, password=self.password)
100
+ self.assertIn(r1, ('grant_type=password&username={}&password={}'.format(self.username, self.password),
101
+ 'grant_type=password&password={}&username={}'.format(self.password, self.username),
102
+ ))
103
+
104
+ # scenario 2, include `client_id` in the body
105
+ r2 = client.prepare_request_body(username=self.username, password=self.password, include_client_id=True)
106
+ r2_params = dict(urlparse.parse_qsl(r2, keep_blank_values=True))
107
+ self.assertEqual(len(r2_params.keys()), 4)
108
+ self.assertEqual(r2_params['grant_type'], 'password')
109
+ self.assertEqual(r2_params['username'], self.username)
110
+ self.assertEqual(r2_params['password'], self.password)
111
+ self.assertEqual(r2_params['client_id'], self.client_id)
112
+
113
+ # scenario 3, include `client_id` + `client_secret` in the body
114
+ r3 = client.prepare_request_body(username=self.username, password=self.password, include_client_id=True, client_secret=self.client_secret)
115
+ r3_params = dict(urlparse.parse_qsl(r3, keep_blank_values=True))
116
+ self.assertEqual(len(r3_params.keys()), 5)
117
+ self.assertEqual(r3_params['grant_type'], 'password')
118
+ self.assertEqual(r3_params['username'], self.username)
119
+ self.assertEqual(r3_params['password'], self.password)
120
+ self.assertEqual(r3_params['client_id'], self.client_id)
121
+ self.assertEqual(r3_params['client_secret'], self.client_secret)
122
+
123
+ # scenario 4, `client_secret` is an empty string
124
+ r4 = client.prepare_request_body(username=self.username, password=self.password, include_client_id=True, client_secret='')
125
+ r4_params = dict(urlparse.parse_qsl(r4, keep_blank_values=True))
126
+ self.assertEqual(len(r4_params.keys()), 5)
127
+ self.assertEqual(r4_params['grant_type'], 'password')
128
+ self.assertEqual(r4_params['username'], self.username)
129
+ self.assertEqual(r4_params['password'], self.password)
130
+ self.assertEqual(r4_params['client_id'], self.client_id)
131
+ self.assertEqual(r4_params['client_secret'], '')
132
+
133
+ # scenario 4b`,` client_secret is `None`
134
+ r4b = client.prepare_request_body(username=self.username, password=self.password, include_client_id=True, client_secret=None)
135
+ r4b_params = dict(urlparse.parse_qsl(r4b, keep_blank_values=True))
136
+ self.assertEqual(len(r4b_params.keys()), 4)
137
+ self.assertEqual(r4b_params['grant_type'], 'password')
138
+ self.assertEqual(r4b_params['username'], self.username)
139
+ self.assertEqual(r4b_params['password'], self.password)
140
+ self.assertEqual(r4b_params['client_id'], self.client_id)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/test_mobile_application.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ from unittest.mock import patch
4
+
5
+ from oauthlib import signals
6
+ from oauthlib.oauth2 import MobileApplicationClient
7
+
8
+ from tests.unittest import TestCase
9
+
10
+
11
+ @patch('time.time', new=lambda: 1000)
12
+ class MobileApplicationClientTest(TestCase):
13
+
14
+ client_id = "someclientid"
15
+ uri = "https://example.com/path?query=world"
16
+ uri_id = uri + "&response_type=token&client_id=" + client_id
17
+ uri_redirect = uri_id + "&redirect_uri=http%3A%2F%2Fmy.page.com%2Fcallback"
18
+ redirect_uri = "http://my.page.com/callback"
19
+ scope = ["/profile"]
20
+ state = "xyz"
21
+ uri_scope = uri_id + "&scope=%2Fprofile"
22
+ uri_state = uri_id + "&state=" + state
23
+ kwargs = {
24
+ "some": "providers",
25
+ "require": "extra arguments"
26
+ }
27
+ uri_kwargs = uri_id + "&some=providers&require=extra+arguments"
28
+
29
+ code = "zzzzaaaa"
30
+
31
+ response_uri = ('https://client.example.com/cb?#'
32
+ 'access_token=2YotnFZFEjr1zCsicMWpAA&'
33
+ 'token_type=example&'
34
+ 'expires_in=3600&'
35
+ 'scope=%2Fprofile&'
36
+ 'example_parameter=example_value')
37
+ token = {
38
+ "access_token": "2YotnFZFEjr1zCsicMWpAA",
39
+ "token_type": "example",
40
+ "expires_in": 3600,
41
+ "expires_at": 4600,
42
+ "scope": scope,
43
+ "example_parameter": "example_value"
44
+ }
45
+
46
+ def test_implicit_token_uri(self):
47
+ client = MobileApplicationClient(self.client_id)
48
+
49
+ # Basic, no extra arguments
50
+ uri = client.prepare_request_uri(self.uri)
51
+ self.assertURLEqual(uri, self.uri_id)
52
+
53
+ # With redirection uri
54
+ uri = client.prepare_request_uri(self.uri, redirect_uri=self.redirect_uri)
55
+ self.assertURLEqual(uri, self.uri_redirect)
56
+
57
+ # With scope
58
+ uri = client.prepare_request_uri(self.uri, scope=self.scope)
59
+ self.assertURLEqual(uri, self.uri_scope)
60
+
61
+ # With state
62
+ uri = client.prepare_request_uri(self.uri, state=self.state)
63
+ self.assertURLEqual(uri, self.uri_state)
64
+
65
+ # With extra parameters through kwargs
66
+ uri = client.prepare_request_uri(self.uri, **self.kwargs)
67
+ self.assertURLEqual(uri, self.uri_kwargs)
68
+
69
+ def test_populate_attributes(self):
70
+
71
+ client = MobileApplicationClient(self.client_id)
72
+
73
+ response_uri = (self.response_uri + "&code=EVIL-CODE")
74
+
75
+ client.parse_request_uri_response(response_uri, scope=self.scope)
76
+
77
+ # We must not accidentally pick up any further security
78
+ # credentials at this point.
79
+ self.assertIsNone(client.code)
80
+
81
+ def test_parse_token_response(self):
82
+ client = MobileApplicationClient(self.client_id)
83
+
84
+ # Parse code and state
85
+ response = client.parse_request_uri_response(self.response_uri, scope=self.scope)
86
+ self.assertEqual(response, self.token)
87
+ self.assertEqual(client.access_token, response.get("access_token"))
88
+ self.assertEqual(client.refresh_token, response.get("refresh_token"))
89
+ self.assertEqual(client.token_type, response.get("token_type"))
90
+
91
+ # Mismatching scope
92
+ self.assertRaises(Warning, client.parse_request_uri_response, self.response_uri, scope="invalid")
93
+ os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '4'
94
+ token = client.parse_request_uri_response(self.response_uri, scope='invalid')
95
+ self.assertTrue(token.scope_changed)
96
+
97
+ scope_changes_recorded = []
98
+ def record_scope_change(sender, message, old, new):
99
+ scope_changes_recorded.append((message, old, new))
100
+
101
+ signals.scope_changed.connect(record_scope_change)
102
+ try:
103
+ client.parse_request_uri_response(self.response_uri, scope="invalid")
104
+ self.assertEqual(len(scope_changes_recorded), 1)
105
+ message, old, new = scope_changes_recorded[0]
106
+ self.assertEqual(message, 'Scope has changed from "invalid" to "/profile".')
107
+ self.assertEqual(old, ['invalid'])
108
+ self.assertEqual(new, ['/profile'])
109
+ finally:
110
+ signals.scope_changed.disconnect(record_scope_change)
111
+ del os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE']
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/test_service_application.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ from time import time
4
+ from unittest.mock import patch
5
+
6
+ import jwt
7
+
8
+ from oauthlib.common import Request
9
+ from oauthlib.oauth2 import ServiceApplicationClient
10
+
11
+ from tests.unittest import TestCase
12
+
13
+
14
+ class ServiceApplicationClientTest(TestCase):
15
+
16
+ gt = ServiceApplicationClient.grant_type
17
+
18
+ private_key = """
19
+ -----BEGIN RSA PRIVATE KEY-----
20
+ MIICXgIBAAKBgQDk1/bxyS8Q8jiheHeYYp/4rEKJopeQRRKKpZI4s5i+UPwVpupG
21
+ AlwXWfzXwSMaKPAoKJNdu7tqKRniqst5uoHXw98gj0x7zamu0Ck1LtQ4c7pFMVah
22
+ 5IYGhBi2E9ycNS329W27nJPWNCbESTu7snVlG8V8mfvGGg3xNjTMO7IdrwIDAQAB
23
+ AoGBAOQ2KuH8S5+OrsL4K+wfjoCi6MfxCUyqVU9GxocdM1m30WyWRFMEz2nKJ8fR
24
+ p3vTD4w8yplTOhcoXdQZl0kRoaDzrcYkm2VvJtQRrX7dKFT8dR8D/Tr7dNQLOXfC
25
+ DY6xveQczE7qt7Vk7lp4FqmxBsaaEuokt78pOOjywZoInjZhAkEA9wz3zoZNT0/i
26
+ rf6qv2qTIeieUB035N3dyw6f1BGSWYaXSuerDCD/J1qZbAPKKhyHZbVawFt3UMhe
27
+ 542UftBaxQJBAO0iJy1I8GQjGnS7B3yvyH3CcLYGy296+XO/2xKp/d/ty1OIeovx
28
+ C60pLNwuFNF3z9d2GVQAdoQ89hUkOtjZLeMCQQD0JO6oPHUeUjYT+T7ImAv7UKVT
29
+ Suy30sKjLzqoGw1kR+wv7C5PeDRvscs4wa4CW9s6mjSrMDkDrmCLuJDtmf55AkEA
30
+ kmaMg2PNrjUR51F0zOEFycaaqXbGcFwe1/xx9zLmHzMDXd4bsnwt9kk+fe0hQzVS
31
+ JzatanQit3+feev1PN3QewJAWv4RZeavEUhKv+kLe95Yd0su7lTLVduVgh4v5yLT
32
+ Ga6FHdjGPcfajt+nrpB1n8UQBEH9ZxniokR/IPvdMlxqXA==
33
+ -----END RSA PRIVATE KEY-----
34
+ """
35
+
36
+ public_key = """
37
+ -----BEGIN PUBLIC KEY-----
38
+ MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDk1/bxyS8Q8jiheHeYYp/4rEKJ
39
+ opeQRRKKpZI4s5i+UPwVpupGAlwXWfzXwSMaKPAoKJNdu7tqKRniqst5uoHXw98g
40
+ j0x7zamu0Ck1LtQ4c7pFMVah5IYGhBi2E9ycNS329W27nJPWNCbESTu7snVlG8V8
41
+ mfvGGg3xNjTMO7IdrwIDAQAB
42
+ -----END PUBLIC KEY-----
43
+ """
44
+
45
+ subject = 'resource-owner@provider.com'
46
+
47
+ issuer = 'the-client@provider.com'
48
+
49
+ audience = 'https://provider.com/token'
50
+
51
+ client_id = "someclientid"
52
+ scope = ["/profile"]
53
+ kwargs = {
54
+ "some": "providers",
55
+ "require": "extra arguments"
56
+ }
57
+
58
+ body = "isnot=empty"
59
+
60
+ body_up = "not=empty&grant_type=%s" % gt
61
+ body_kwargs = body_up + "&some=providers&require=extra+arguments"
62
+
63
+ token_json = ('{ "access_token":"2YotnFZFEjr1zCsicMWpAA",'
64
+ ' "token_type":"example",'
65
+ ' "expires_in":3600,'
66
+ ' "scope":"/profile",'
67
+ ' "example_parameter":"example_value"}')
68
+ token = {
69
+ "access_token": "2YotnFZFEjr1zCsicMWpAA",
70
+ "token_type": "example",
71
+ "expires_in": 3600,
72
+ "scope": ["/profile"],
73
+ "example_parameter": "example_value"
74
+ }
75
+
76
+ @patch('time.time')
77
+ def test_request_body(self, t):
78
+ t.return_value = time()
79
+ self.token['expires_at'] = self.token['expires_in'] + t.return_value
80
+
81
+ client = ServiceApplicationClient(
82
+ self.client_id, private_key=self.private_key)
83
+
84
+ # Basic with min required params
85
+ body = client.prepare_request_body(issuer=self.issuer,
86
+ subject=self.subject,
87
+ audience=self.audience,
88
+ body=self.body)
89
+ r = Request('https://a.b', body=body)
90
+ self.assertEqual(r.isnot, 'empty')
91
+ self.assertEqual(r.grant_type, ServiceApplicationClient.grant_type)
92
+
93
+ claim = jwt.decode(r.assertion, self.public_key, audience=self.audience, algorithms=['RS256'])
94
+
95
+ self.assertEqual(claim['iss'], self.issuer)
96
+ # audience verification is handled during decode now
97
+ self.assertEqual(claim['sub'], self.subject)
98
+ self.assertEqual(claim['iat'], int(t.return_value))
99
+ self.assertNotIn('nbf', claim)
100
+ self.assertNotIn('jti', claim)
101
+
102
+ # Missing issuer parameter
103
+ self.assertRaises(ValueError, client.prepare_request_body,
104
+ issuer=None, subject=self.subject, audience=self.audience, body=self.body)
105
+
106
+ # Missing subject parameter
107
+ self.assertRaises(ValueError, client.prepare_request_body,
108
+ issuer=self.issuer, subject=None, audience=self.audience, body=self.body)
109
+
110
+ # Missing audience parameter
111
+ self.assertRaises(ValueError, client.prepare_request_body,
112
+ issuer=self.issuer, subject=self.subject, audience=None, body=self.body)
113
+
114
+ # Optional kwargs
115
+ not_before = time() - 3600
116
+ jwt_id = '8zd15df4s35f43sd'
117
+ body = client.prepare_request_body(issuer=self.issuer,
118
+ subject=self.subject,
119
+ audience=self.audience,
120
+ body=self.body,
121
+ not_before=not_before,
122
+ jwt_id=jwt_id)
123
+
124
+ r = Request('https://a.b', body=body)
125
+ self.assertEqual(r.isnot, 'empty')
126
+ self.assertEqual(r.grant_type, ServiceApplicationClient.grant_type)
127
+
128
+ claim = jwt.decode(r.assertion, self.public_key, audience=self.audience, algorithms=['RS256'])
129
+
130
+ self.assertEqual(claim['iss'], self.issuer)
131
+ # audience verification is handled during decode now
132
+ self.assertEqual(claim['sub'], self.subject)
133
+ self.assertEqual(claim['iat'], int(t.return_value))
134
+ self.assertEqual(claim['nbf'], not_before)
135
+ self.assertEqual(claim['jti'], jwt_id)
136
+
137
+ @patch('time.time')
138
+ def test_request_body_no_initial_private_key(self, t):
139
+ t.return_value = time()
140
+ self.token['expires_at'] = self.token['expires_in'] + t.return_value
141
+
142
+ client = ServiceApplicationClient(
143
+ self.client_id, private_key=None)
144
+
145
+ # Basic with private key provided
146
+ body = client.prepare_request_body(issuer=self.issuer,
147
+ subject=self.subject,
148
+ audience=self.audience,
149
+ body=self.body,
150
+ private_key=self.private_key)
151
+ r = Request('https://a.b', body=body)
152
+ self.assertEqual(r.isnot, 'empty')
153
+ self.assertEqual(r.grant_type, ServiceApplicationClient.grant_type)
154
+
155
+ claim = jwt.decode(r.assertion, self.public_key, audience=self.audience, algorithms=['RS256'])
156
+
157
+ self.assertEqual(claim['iss'], self.issuer)
158
+ # audience verification is handled during decode now
159
+ self.assertEqual(claim['sub'], self.subject)
160
+ self.assertEqual(claim['iat'], int(t.return_value))
161
+
162
+ # No private key provided
163
+ self.assertRaises(ValueError, client.prepare_request_body,
164
+ issuer=self.issuer, subject=self.subject, audience=self.audience, body=self.body)
165
+
166
+ @patch('time.time')
167
+ def test_parse_token_response(self, t):
168
+ t.return_value = time()
169
+ self.token['expires_at'] = self.token['expires_in'] + round(t.return_value)
170
+
171
+ client = ServiceApplicationClient(self.client_id)
172
+
173
+ # Parse code and state
174
+ response = client.parse_request_body_response(self.token_json, scope=self.scope)
175
+ self.assertEqual(response, self.token)
176
+ self.assertEqual(client.access_token, response.get("access_token"))
177
+ self.assertEqual(client.refresh_token, response.get("refresh_token"))
178
+ self.assertEqual(client.token_type, response.get("token_type"))
179
+
180
+ # Mismatching state
181
+ self.assertRaises(Warning, client.parse_request_body_response, self.token_json, scope="invalid")
182
+ os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '2'
183
+ token = client.parse_request_body_response(self.token_json, scope="invalid")
184
+ self.assertTrue(token.scope_changed)
185
+ del os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE']
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/clients/test_web_application.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import urllib.parse as urlparse
4
+ import warnings
5
+ from unittest.mock import patch
6
+
7
+ from oauthlib import common, signals
8
+ from oauthlib.oauth2 import (
9
+ BackendApplicationClient, Client, LegacyApplicationClient,
10
+ MobileApplicationClient, WebApplicationClient,
11
+ )
12
+ from oauthlib.oauth2.rfc6749 import errors, utils
13
+ from oauthlib.oauth2.rfc6749.clients import AUTH_HEADER, BODY, URI_QUERY
14
+
15
+ from tests.unittest import TestCase
16
+
17
+
18
+ @patch('time.time', new=lambda: 1000)
19
+ class WebApplicationClientTest(TestCase):
20
+
21
+ client_id = "someclientid"
22
+ client_secret = 'someclientsecret'
23
+ uri = "https://example.com/path?query=world"
24
+ uri_id = uri + "&response_type=code&client_id=" + client_id
25
+ uri_redirect = uri_id + "&redirect_uri=http%3A%2F%2Fmy.page.com%2Fcallback"
26
+ redirect_uri = "http://my.page.com/callback"
27
+ code_verifier = "code_verifier"
28
+ scope = ["/profile"]
29
+ state = "xyz"
30
+ code_challenge = "code_challenge"
31
+ code_challenge_method = "S256"
32
+ uri_scope = uri_id + "&scope=%2Fprofile"
33
+ uri_state = uri_id + "&state=" + state
34
+ uri_code_challenge = uri_id + "&code_challenge=" + code_challenge + "&code_challenge_method=" + code_challenge_method
35
+ uri_code_challenge_method = uri_id + "&code_challenge=" + code_challenge + "&code_challenge_method=plain"
36
+ kwargs = {
37
+ "some": "providers",
38
+ "require": "extra arguments"
39
+ }
40
+ uri_kwargs = uri_id + "&some=providers&require=extra+arguments"
41
+ uri_authorize_code = uri_redirect + "&scope=%2Fprofile&state=" + state
42
+
43
+ code = "zzzzaaaa"
44
+ body = "not=empty"
45
+
46
+ body_code = "not=empty&grant_type=authorization_code&code={}&client_id={}".format(code, client_id)
47
+ body_redirect = body_code + "&redirect_uri=http%3A%2F%2Fmy.page.com%2Fcallback"
48
+ body_code_verifier = body_code + "&code_verifier=code_verifier"
49
+ body_kwargs = body_code + "&some=providers&require=extra+arguments"
50
+
51
+ response_uri = "https://client.example.com/cb?code=zzzzaaaa&state=xyz"
52
+ response = {"code": "zzzzaaaa", "state": "xyz"}
53
+
54
+ token_json = ('{ "access_token":"2YotnFZFEjr1zCsicMWpAA",'
55
+ ' "token_type":"example",'
56
+ ' "expires_in":3600,'
57
+ ' "scope":"/profile",'
58
+ ' "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",'
59
+ ' "example_parameter":"example_value"}')
60
+ token = {
61
+ "access_token": "2YotnFZFEjr1zCsicMWpAA",
62
+ "token_type": "example",
63
+ "expires_in": 3600,
64
+ "expires_at": 4600,
65
+ "scope": scope,
66
+ "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
67
+ "example_parameter": "example_value"
68
+ }
69
+
70
+ def test_auth_grant_uri(self):
71
+ client = WebApplicationClient(self.client_id)
72
+
73
+ # Basic, no extra arguments
74
+ uri = client.prepare_request_uri(self.uri)
75
+ self.assertURLEqual(uri, self.uri_id)
76
+
77
+ # With redirection uri
78
+ uri = client.prepare_request_uri(self.uri, redirect_uri=self.redirect_uri)
79
+ self.assertURLEqual(uri, self.uri_redirect)
80
+
81
+ # With scope
82
+ uri = client.prepare_request_uri(self.uri, scope=self.scope)
83
+ self.assertURLEqual(uri, self.uri_scope)
84
+
85
+ # With state
86
+ uri = client.prepare_request_uri(self.uri, state=self.state)
87
+ self.assertURLEqual(uri, self.uri_state)
88
+
89
+ # with code_challenge and code_challenge_method
90
+ uri = client.prepare_request_uri(self.uri, code_challenge=self.code_challenge, code_challenge_method=self.code_challenge_method)
91
+ self.assertURLEqual(uri, self.uri_code_challenge)
92
+
93
+ # with no code_challenge_method
94
+ uri = client.prepare_request_uri(self.uri, code_challenge=self.code_challenge)
95
+ self.assertURLEqual(uri, self.uri_code_challenge_method)
96
+
97
+ # With extra parameters through kwargs
98
+ uri = client.prepare_request_uri(self.uri, **self.kwargs)
99
+ self.assertURLEqual(uri, self.uri_kwargs)
100
+
101
+ def test_request_body(self):
102
+ client = WebApplicationClient(self.client_id, code=self.code)
103
+
104
+ # Basic, no extra arguments
105
+ body = client.prepare_request_body(body=self.body)
106
+ self.assertFormBodyEqual(body, self.body_code)
107
+
108
+ rclient = WebApplicationClient(self.client_id)
109
+ body = rclient.prepare_request_body(code=self.code, body=self.body)
110
+ self.assertFormBodyEqual(body, self.body_code)
111
+
112
+ # With redirection uri
113
+ body = client.prepare_request_body(body=self.body, redirect_uri=self.redirect_uri)
114
+ self.assertFormBodyEqual(body, self.body_redirect)
115
+
116
+ # With code verifier
117
+ body = client.prepare_request_body(body=self.body, code_verifier=self.code_verifier)
118
+ self.assertFormBodyEqual(body, self.body_code_verifier)
119
+
120
+ # With extra parameters
121
+ body = client.prepare_request_body(body=self.body, **self.kwargs)
122
+ self.assertFormBodyEqual(body, self.body_kwargs)
123
+
124
+ def test_parse_grant_uri_response(self):
125
+ client = WebApplicationClient(self.client_id)
126
+
127
+ # Parse code and state
128
+ response = client.parse_request_uri_response(self.response_uri, state=self.state)
129
+ self.assertEqual(response, self.response)
130
+ self.assertEqual(client.code, self.code)
131
+
132
+ # Mismatching state
133
+ self.assertRaises(errors.MismatchingStateError,
134
+ client.parse_request_uri_response,
135
+ self.response_uri,
136
+ state="invalid")
137
+
138
+ def test_populate_attributes(self):
139
+
140
+ client = WebApplicationClient(self.client_id)
141
+
142
+ response_uri = (self.response_uri +
143
+ "&access_token=EVIL-TOKEN"
144
+ "&refresh_token=EVIL-TOKEN"
145
+ "&mac_key=EVIL-KEY")
146
+
147
+ client.parse_request_uri_response(response_uri, self.state)
148
+
149
+ self.assertEqual(client.code, self.code)
150
+
151
+ # We must not accidentally pick up any further security
152
+ # credentials at this point.
153
+ self.assertIsNone(client.access_token)
154
+ self.assertIsNone(client.refresh_token)
155
+ self.assertIsNone(client.mac_key)
156
+
157
+ def test_parse_token_response(self):
158
+ client = WebApplicationClient(self.client_id)
159
+
160
+ # Parse code and state
161
+ response = client.parse_request_body_response(self.token_json, scope=self.scope)
162
+ self.assertEqual(response, self.token)
163
+ self.assertEqual(client.access_token, response.get("access_token"))
164
+ self.assertEqual(client.refresh_token, response.get("refresh_token"))
165
+ self.assertEqual(client.token_type, response.get("token_type"))
166
+
167
+ # Mismatching state
168
+ self.assertRaises(Warning, client.parse_request_body_response, self.token_json, scope="invalid")
169
+ os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
170
+ token = client.parse_request_body_response(self.token_json, scope="invalid")
171
+ self.assertTrue(token.scope_changed)
172
+
173
+ scope_changes_recorded = []
174
+ def record_scope_change(sender, message, old, new):
175
+ scope_changes_recorded.append((message, old, new))
176
+
177
+ signals.scope_changed.connect(record_scope_change)
178
+ try:
179
+ client.parse_request_body_response(self.token_json, scope="invalid")
180
+ self.assertEqual(len(scope_changes_recorded), 1)
181
+ message, old, new = scope_changes_recorded[0]
182
+ self.assertEqual(message, 'Scope has changed from "invalid" to "/profile".')
183
+ self.assertEqual(old, ['invalid'])
184
+ self.assertEqual(new, ['/profile'])
185
+ finally:
186
+ signals.scope_changed.disconnect(record_scope_change)
187
+ del os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE']
188
+
189
+ def test_prepare_authorization_requeset(self):
190
+ client = WebApplicationClient(self.client_id)
191
+
192
+ url, header, body = client.prepare_authorization_request(
193
+ self.uri, redirect_url=self.redirect_uri, state=self.state, scope=self.scope)
194
+ self.assertURLEqual(url, self.uri_authorize_code)
195
+ # verify default header and body only
196
+ self.assertEqual(header, {'Content-Type': 'application/x-www-form-urlencoded'})
197
+ self.assertEqual(body, '')
198
+
199
+ def test_prepare_request_body(self):
200
+ """
201
+ see issue #585
202
+ https://github.com/oauthlib/oauthlib/issues/585
203
+
204
+ `prepare_request_body` should support the following scenarios:
205
+ 1. Include client_id alone in the body (default)
206
+ 2. Include client_id and client_secret in auth and not include them in the body (RFC preferred solution)
207
+ 3. Include client_id and client_secret in the body (RFC alternative solution)
208
+ 4. Include client_id in the body and an empty string for client_secret.
209
+ """
210
+ client = WebApplicationClient(self.client_id)
211
+
212
+ # scenario 1, default behavior to include `client_id`
213
+ r1 = client.prepare_request_body()
214
+ self.assertEqual(r1, 'grant_type=authorization_code&client_id=%s' % self.client_id)
215
+
216
+ r1b = client.prepare_request_body(include_client_id=True)
217
+ self.assertEqual(r1b, 'grant_type=authorization_code&client_id=%s' % self.client_id)
218
+
219
+ # scenario 2, do not include `client_id` in the body, so it can be sent in auth.
220
+ r2 = client.prepare_request_body(include_client_id=False)
221
+ self.assertEqual(r2, 'grant_type=authorization_code')
222
+
223
+ # scenario 3, Include client_id and client_secret in the body (RFC alternative solution)
224
+ # the order of kwargs being appended is not guaranteed. for brevity, check the 2 permutations instead of sorting
225
+ r3 = client.prepare_request_body(client_secret=self.client_secret)
226
+ r3_params = dict(urlparse.parse_qsl(r3, keep_blank_values=True))
227
+ self.assertEqual(len(r3_params.keys()), 3)
228
+ self.assertEqual(r3_params['grant_type'], 'authorization_code')
229
+ self.assertEqual(r3_params['client_id'], self.client_id)
230
+ self.assertEqual(r3_params['client_secret'], self.client_secret)
231
+
232
+ r3b = client.prepare_request_body(include_client_id=True, client_secret=self.client_secret)
233
+ r3b_params = dict(urlparse.parse_qsl(r3b, keep_blank_values=True))
234
+ self.assertEqual(len(r3b_params.keys()), 3)
235
+ self.assertEqual(r3b_params['grant_type'], 'authorization_code')
236
+ self.assertEqual(r3b_params['client_id'], self.client_id)
237
+ self.assertEqual(r3b_params['client_secret'], self.client_secret)
238
+
239
+ # scenario 4, `client_secret` is an empty string
240
+ r4 = client.prepare_request_body(include_client_id=True, client_secret='')
241
+ r4_params = dict(urlparse.parse_qsl(r4, keep_blank_values=True))
242
+ self.assertEqual(len(r4_params.keys()), 3)
243
+ self.assertEqual(r4_params['grant_type'], 'authorization_code')
244
+ self.assertEqual(r4_params['client_id'], self.client_id)
245
+ self.assertEqual(r4_params['client_secret'], '')
246
+
247
+ # scenario 4b, `client_secret` is `None`
248
+ r4b = client.prepare_request_body(include_client_id=True, client_secret=None)
249
+ r4b_params = dict(urlparse.parse_qsl(r4b, keep_blank_values=True))
250
+ self.assertEqual(len(r4b_params.keys()), 2)
251
+ self.assertEqual(r4b_params['grant_type'], 'authorization_code')
252
+ self.assertEqual(r4b_params['client_id'], self.client_id)
253
+
254
+ # scenario Warnings
255
+ # warning1 - raise a DeprecationWarning if a `client_id` is submitted
256
+ with self.assertWarns(DeprecationWarning):
257
+ client.prepare_request_body(client_id=self.client_id)
258
+ # testing the exact warning message in Python2&Python3 is a pain
259
+
260
+ # scenario Exceptions
261
+ # exception1 - raise a ValueError if the a different `client_id` is submitted
262
+ with self.assertWarns(DeprecationWarning), self.assertRaises(ValueError):
263
+ client.prepare_request_body(client_id='different_client_id')
264
+ # testing the exact exception message in Python2&Python3 is a pain
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/__init__.py ADDED
File without changes
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_base_endpoint.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from oauthlib.oauth2 import (
3
+ FatalClientError, OAuth2Error, RequestValidator, Server,
4
+ )
5
+ from oauthlib.oauth2.rfc6749 import (
6
+ BaseEndpoint, catch_errors_and_unavailability,
7
+ )
8
+
9
+ from tests.unittest import TestCase
10
+
11
+
12
+ class BaseEndpointTest(TestCase):
13
+
14
+ def test_default_config(self):
15
+ endpoint = BaseEndpoint()
16
+ self.assertFalse(endpoint.catch_errors)
17
+ self.assertTrue(endpoint.available)
18
+ endpoint.catch_errors = True
19
+ self.assertTrue(endpoint.catch_errors)
20
+ endpoint.available = False
21
+ self.assertFalse(endpoint.available)
22
+
23
+ def test_error_catching(self):
24
+ validator = RequestValidator()
25
+ server = Server(validator)
26
+ server.catch_errors = True
27
+ h, b, s = server.create_token_response(
28
+ 'https://example.com', body='grant_type=authorization_code&code=abc'
29
+ )
30
+ self.assertIn("server_error", b)
31
+ self.assertEqual(s, 500)
32
+
33
+ def test_unavailability(self):
34
+ validator = RequestValidator()
35
+ server = Server(validator)
36
+ server.available = False
37
+ h, b, s = server.create_authorization_response('https://example.com')
38
+ self.assertIn("temporarily_unavailable", b)
39
+ self.assertEqual(s, 503)
40
+
41
+ def test_wrapper(self):
42
+
43
+ class TestServer(Server):
44
+
45
+ @catch_errors_and_unavailability
46
+ def throw_error(self, uri):
47
+ raise ValueError()
48
+
49
+ @catch_errors_and_unavailability
50
+ def throw_oauth_error(self, uri):
51
+ raise OAuth2Error()
52
+
53
+ @catch_errors_and_unavailability
54
+ def throw_fatal_oauth_error(self, uri):
55
+ raise FatalClientError()
56
+
57
+ validator = RequestValidator()
58
+ server = TestServer(validator)
59
+
60
+ server.catch_errors = True
61
+ h, b, s = server.throw_error('a')
62
+ self.assertIn("server_error", b)
63
+ self.assertEqual(s, 500)
64
+
65
+ server.available = False
66
+ h, b, s = server.throw_error('a')
67
+ self.assertIn("temporarily_unavailable", b)
68
+ self.assertEqual(s, 503)
69
+
70
+ server.available = True
71
+ self.assertRaises(OAuth2Error, server.throw_oauth_error, 'a')
72
+ self.assertRaises(FatalClientError, server.throw_fatal_oauth_error, 'a')
73
+ server.catch_errors = False
74
+ self.assertRaises(OAuth2Error, server.throw_oauth_error, 'a')
75
+ self.assertRaises(FatalClientError, server.throw_fatal_oauth_error, 'a')
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_client_authentication.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Client authentication tests across all endpoints.
2
+
3
+ Client authentication in OAuth2 serve two purposes, to authenticate
4
+ confidential clients and to ensure public clients are in fact public. The
5
+ latter is achieved with authenticate_client_id and the former with
6
+ authenticate_client.
7
+
8
+ We make sure authentication is done by requiring a client object to be set
9
+ on the request object with a client_id parameter. The client_id attribute
10
+ prevents this check from being circumvented with a client form parameter.
11
+ """
12
+ import json
13
+ from unittest import mock
14
+
15
+ from oauthlib.oauth2 import (
16
+ BackendApplicationServer, LegacyApplicationServer, MobileApplicationServer,
17
+ RequestValidator, WebApplicationServer,
18
+ )
19
+
20
+ from tests.unittest import TestCase
21
+
22
+ from .test_utils import get_fragment_credentials
23
+
24
+
25
+ class ClientAuthenticationTest(TestCase):
26
+
27
+ def inspect_client(self, request, refresh_token=False):
28
+ if not request.client or not request.client.client_id:
29
+ raise ValueError()
30
+ return 'abc'
31
+
32
+ def setUp(self):
33
+ self.validator = mock.MagicMock(spec=RequestValidator)
34
+ self.validator.is_pkce_required.return_value = False
35
+ self.validator.get_code_challenge.return_value = None
36
+ self.validator.get_default_redirect_uri.return_value = 'http://i.b./path'
37
+ self.web = WebApplicationServer(self.validator,
38
+ token_generator=self.inspect_client)
39
+ self.mobile = MobileApplicationServer(self.validator,
40
+ token_generator=self.inspect_client)
41
+ self.legacy = LegacyApplicationServer(self.validator,
42
+ token_generator=self.inspect_client)
43
+ self.backend = BackendApplicationServer(self.validator,
44
+ token_generator=self.inspect_client)
45
+ self.token_uri = 'http://example.com/path'
46
+ self.auth_uri = 'http://example.com/path?client_id=abc&response_type=token'
47
+ # should be base64 but no added value in this unittest
48
+ self.basicauth_client_creds = {"Authorization": "john:doe"}
49
+ self.basicauth_client_id = {"Authorization": "john:"}
50
+
51
+ def set_client(self, request):
52
+ request.client = mock.MagicMock()
53
+ request.client.client_id = 'mocked'
54
+ return True
55
+
56
+ def set_client_id(self, client_id, request):
57
+ request.client = mock.MagicMock()
58
+ request.client.client_id = 'mocked'
59
+ return True
60
+
61
+ def basicauth_authenticate_client(self, request):
62
+ assert "Authorization" in request.headers
63
+ assert "john:doe" in request.headers["Authorization"]
64
+ request.client = mock.MagicMock()
65
+ request.client.client_id = 'mocked'
66
+ return True
67
+
68
+ def test_client_id_authentication(self):
69
+ token_uri = 'http://example.com/path'
70
+
71
+ # authorization code grant
72
+ self.validator.authenticate_client.return_value = False
73
+ self.validator.authenticate_client_id.return_value = False
74
+ _, body, _ = self.web.create_token_response(token_uri,
75
+ body='grant_type=authorization_code&code=mock')
76
+ self.assertEqual(json.loads(body)['error'], 'invalid_client')
77
+
78
+ self.validator.authenticate_client_id.return_value = True
79
+ self.validator.authenticate_client.side_effect = self.set_client
80
+ _, body, _ = self.web.create_token_response(token_uri,
81
+ body='grant_type=authorization_code&code=mock')
82
+ self.assertIn('access_token', json.loads(body))
83
+
84
+ # implicit grant
85
+ auth_uri = 'http://example.com/path?client_id=abc&response_type=token'
86
+ self.assertRaises(ValueError, self.mobile.create_authorization_response,
87
+ auth_uri, scopes=['random'])
88
+
89
+ self.validator.validate_client_id.side_effect = self.set_client_id
90
+ h, _, s = self.mobile.create_authorization_response(auth_uri, scopes=['random'])
91
+ self.assertEqual(302, s)
92
+ self.assertIn('Location', h)
93
+ self.assertIn('access_token', get_fragment_credentials(h['Location']))
94
+
95
+ def test_basicauth_web(self):
96
+ self.validator.authenticate_client.side_effect = self.basicauth_authenticate_client
97
+ _, body, _ = self.web.create_token_response(
98
+ self.token_uri,
99
+ body='grant_type=authorization_code&code=mock',
100
+ headers=self.basicauth_client_creds
101
+ )
102
+ self.assertIn('access_token', json.loads(body))
103
+
104
+ def test_basicauth_legacy(self):
105
+ self.validator.authenticate_client.side_effect = self.basicauth_authenticate_client
106
+ _, body, _ = self.legacy.create_token_response(
107
+ self.token_uri,
108
+ body='grant_type=password&username=abc&password=secret',
109
+ headers=self.basicauth_client_creds
110
+ )
111
+ self.assertIn('access_token', json.loads(body))
112
+
113
+ def test_basicauth_backend(self):
114
+ self.validator.authenticate_client.side_effect = self.basicauth_authenticate_client
115
+ _, body, _ = self.backend.create_token_response(
116
+ self.token_uri,
117
+ body='grant_type=client_credentials',
118
+ headers=self.basicauth_client_creds
119
+ )
120
+ self.assertIn('access_token', json.loads(body))
121
+
122
+ def test_basicauth_revoke(self):
123
+ self.validator.authenticate_client.side_effect = self.basicauth_authenticate_client
124
+
125
+ # legacy or any other uses the same RevocationEndpoint
126
+ _, body, status = self.legacy.create_revocation_response(
127
+ self.token_uri,
128
+ body='token=foobar',
129
+ headers=self.basicauth_client_creds
130
+ )
131
+ self.assertEqual(status, 200, body)
132
+
133
+ def test_basicauth_introspect(self):
134
+ self.validator.authenticate_client.side_effect = self.basicauth_authenticate_client
135
+
136
+ # legacy or any other uses the same IntrospectEndpoint
137
+ _, body, status = self.legacy.create_introspect_response(
138
+ self.token_uri,
139
+ body='token=foobar',
140
+ headers=self.basicauth_client_creds
141
+ )
142
+ self.assertEqual(status, 200, body)
143
+
144
+ def test_custom_authentication(self):
145
+ token_uri = 'http://example.com/path'
146
+
147
+ # authorization code grant
148
+ self.assertRaises(NotImplementedError,
149
+ self.web.create_token_response, token_uri,
150
+ body='grant_type=authorization_code&code=mock')
151
+
152
+ # password grant
153
+ self.validator.authenticate_client.return_value = True
154
+ self.assertRaises(NotImplementedError,
155
+ self.legacy.create_token_response, token_uri,
156
+ body='grant_type=password&username=abc&password=secret')
157
+
158
+ # client credentials grant
159
+ self.validator.authenticate_client.return_value = True
160
+ self.assertRaises(NotImplementedError,
161
+ self.backend.create_token_response, token_uri,
162
+ body='grant_type=client_credentials')
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_credentials_preservation.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ensure credentials are preserved through the authorization.
2
+
3
+ The Authorization Code Grant will need to preserve state as well as redirect
4
+ uri and the Implicit Grant will need to preserve state.
5
+ """
6
+ import json
7
+ from unittest import mock
8
+
9
+ from oauthlib.oauth2 import (
10
+ MobileApplicationServer, RequestValidator, WebApplicationServer,
11
+ )
12
+ from oauthlib.oauth2.rfc6749 import errors
13
+
14
+ from tests.unittest import TestCase
15
+
16
+ from .test_utils import get_fragment_credentials, get_query_credentials
17
+
18
+
19
+ class PreservationTest(TestCase):
20
+
21
+ DEFAULT_REDIRECT_URI = 'http://i.b./path'
22
+
23
+ def setUp(self):
24
+ self.validator = mock.MagicMock(spec=RequestValidator)
25
+ self.validator.get_default_redirect_uri.return_value = self.DEFAULT_REDIRECT_URI
26
+ self.validator.get_code_challenge.return_value = None
27
+ self.validator.authenticate_client.side_effect = self.set_client
28
+ self.web = WebApplicationServer(self.validator)
29
+ self.mobile = MobileApplicationServer(self.validator)
30
+
31
+ def set_client(self, request):
32
+ request.client = mock.MagicMock()
33
+ request.client.client_id = 'mocked'
34
+ return True
35
+
36
+ def test_state_preservation(self):
37
+ auth_uri = 'http://example.com/path?state=xyz&client_id=abc&response_type='
38
+
39
+ # authorization grant
40
+ h, _, s = self.web.create_authorization_response(
41
+ auth_uri + 'code', scopes=['random'])
42
+ self.assertEqual(s, 302)
43
+ self.assertIn('Location', h)
44
+ self.assertEqual(get_query_credentials(h['Location'])['state'][0], 'xyz')
45
+
46
+ # implicit grant
47
+ h, _, s = self.mobile.create_authorization_response(
48
+ auth_uri + 'token', scopes=['random'])
49
+ self.assertEqual(s, 302)
50
+ self.assertIn('Location', h)
51
+ self.assertEqual(get_fragment_credentials(h['Location'])['state'][0], 'xyz')
52
+
53
+ def test_redirect_uri_preservation(self):
54
+ auth_uri = 'http://example.com/path?redirect_uri=http%3A%2F%2Fi.b%2Fpath&client_id=abc'
55
+ redirect_uri = 'http://i.b/path'
56
+ token_uri = 'http://example.com/path'
57
+
58
+ # authorization grant
59
+ h, _, s = self.web.create_authorization_response(
60
+ auth_uri + '&response_type=code', scopes=['random'])
61
+ self.assertEqual(s, 302)
62
+ self.assertIn('Location', h)
63
+ self.assertTrue(h['Location'].startswith(redirect_uri))
64
+
65
+ # confirm_redirect_uri should return false if the redirect uri
66
+ # was given in the authorization but not in the token request.
67
+ self.validator.confirm_redirect_uri.return_value = False
68
+ code = get_query_credentials(h['Location'])['code'][0]
69
+ _, body, _ = self.web.create_token_response(token_uri,
70
+ body='grant_type=authorization_code&code=%s' % code)
71
+ self.assertEqual(json.loads(body)['error'], 'invalid_request')
72
+
73
+ # implicit grant
74
+ h, _, s = self.mobile.create_authorization_response(
75
+ auth_uri + '&response_type=token', scopes=['random'])
76
+ self.assertEqual(s, 302)
77
+ self.assertIn('Location', h)
78
+ self.assertTrue(h['Location'].startswith(redirect_uri))
79
+
80
+ def test_invalid_redirect_uri(self):
81
+ auth_uri = 'http://example.com/path?redirect_uri=http%3A%2F%2Fi.b%2Fpath&client_id=abc'
82
+ self.validator.validate_redirect_uri.return_value = False
83
+
84
+ # authorization grant
85
+ self.assertRaises(errors.MismatchingRedirectURIError,
86
+ self.web.create_authorization_response,
87
+ auth_uri + '&response_type=code', scopes=['random'])
88
+
89
+ # implicit grant
90
+ self.assertRaises(errors.MismatchingRedirectURIError,
91
+ self.mobile.create_authorization_response,
92
+ auth_uri + '&response_type=token', scopes=['random'])
93
+
94
+ def test_default_uri(self):
95
+ auth_uri = 'http://example.com/path?state=xyz&client_id=abc'
96
+
97
+ self.validator.get_default_redirect_uri.return_value = None
98
+
99
+ # authorization grant
100
+ self.assertRaises(errors.MissingRedirectURIError,
101
+ self.web.create_authorization_response,
102
+ auth_uri + '&response_type=code', scopes=['random'])
103
+
104
+ # implicit grant
105
+ self.assertRaises(errors.MissingRedirectURIError,
106
+ self.mobile.create_authorization_response,
107
+ auth_uri + '&response_type=token', scopes=['random'])
108
+
109
+ def test_default_uri_in_token(self):
110
+ auth_uri = 'http://example.com/path?state=xyz&client_id=abc'
111
+ token_uri = 'http://example.com/path'
112
+
113
+ # authorization grant
114
+ h, _, s = self.web.create_authorization_response(
115
+ auth_uri + '&response_type=code', scopes=['random'])
116
+ self.assertEqual(s, 302)
117
+ self.assertIn('Location', h)
118
+ self.assertTrue(h['Location'].startswith(self.DEFAULT_REDIRECT_URI))
119
+
120
+ # confirm_redirect_uri should return true if the redirect uri
121
+ # was not given in the authorization AND not in the token request.
122
+ self.validator.confirm_redirect_uri.return_value = True
123
+ code = get_query_credentials(h['Location'])['code'][0]
124
+ self.validator.validate_code.return_value = True
125
+ _, body, s = self.web.create_token_response(token_uri,
126
+ body='grant_type=authorization_code&code=%s' % code)
127
+ self.assertEqual(s, 200)
128
+ self.assertEqual(self.validator.confirm_redirect_uri.call_args[0][2], self.DEFAULT_REDIRECT_URI)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_error_responses.py ADDED
@@ -0,0 +1,491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ensure the correct error responses are returned for all defined error types.
2
+ """
3
+ import json
4
+ from unittest import mock
5
+
6
+ from oauthlib.common import urlencode
7
+ from oauthlib.oauth2 import (
8
+ BackendApplicationServer, LegacyApplicationServer, MobileApplicationServer,
9
+ RequestValidator, WebApplicationServer,
10
+ )
11
+ from oauthlib.oauth2.rfc6749 import errors
12
+
13
+ from tests.unittest import TestCase
14
+
15
+
16
+ class ErrorResponseTest(TestCase):
17
+
18
+ def set_client(self, request):
19
+ request.client = mock.MagicMock()
20
+ request.client.client_id = 'mocked'
21
+ return True
22
+
23
+ def setUp(self):
24
+ self.validator = mock.MagicMock(spec=RequestValidator)
25
+ self.validator.get_default_redirect_uri.return_value = None
26
+ self.validator.get_code_challenge.return_value = None
27
+ self.web = WebApplicationServer(self.validator)
28
+ self.mobile = MobileApplicationServer(self.validator)
29
+ self.legacy = LegacyApplicationServer(self.validator)
30
+ self.backend = BackendApplicationServer(self.validator)
31
+
32
+ def test_invalid_redirect_uri(self):
33
+ uri = 'https://example.com/authorize?response_type={0}&client_id=foo&redirect_uri=wrong'
34
+
35
+ # Authorization code grant
36
+ self.assertRaises(errors.InvalidRedirectURIError,
37
+ self.web.validate_authorization_request, uri.format('code'))
38
+ self.assertRaises(errors.InvalidRedirectURIError,
39
+ self.web.create_authorization_response, uri.format('code'), scopes=['foo'])
40
+
41
+ # Implicit grant
42
+ self.assertRaises(errors.InvalidRedirectURIError,
43
+ self.mobile.validate_authorization_request, uri.format('token'))
44
+ self.assertRaises(errors.InvalidRedirectURIError,
45
+ self.mobile.create_authorization_response, uri.format('token'), scopes=['foo'])
46
+
47
+ def test_invalid_default_redirect_uri(self):
48
+ uri = 'https://example.com/authorize?response_type={0}&client_id=foo'
49
+ self.validator.get_default_redirect_uri.return_value = "wrong"
50
+
51
+ # Authorization code grant
52
+ self.assertRaises(errors.InvalidRedirectURIError,
53
+ self.web.validate_authorization_request, uri.format('code'))
54
+ self.assertRaises(errors.InvalidRedirectURIError,
55
+ self.web.create_authorization_response, uri.format('code'), scopes=['foo'])
56
+
57
+ # Implicit grant
58
+ self.assertRaises(errors.InvalidRedirectURIError,
59
+ self.mobile.validate_authorization_request, uri.format('token'))
60
+ self.assertRaises(errors.InvalidRedirectURIError,
61
+ self.mobile.create_authorization_response, uri.format('token'), scopes=['foo'])
62
+
63
+ def test_missing_redirect_uri(self):
64
+ uri = 'https://example.com/authorize?response_type={0}&client_id=foo'
65
+
66
+ # Authorization code grant
67
+ self.assertRaises(errors.MissingRedirectURIError,
68
+ self.web.validate_authorization_request, uri.format('code'))
69
+ self.assertRaises(errors.MissingRedirectURIError,
70
+ self.web.create_authorization_response, uri.format('code'), scopes=['foo'])
71
+
72
+ # Implicit grant
73
+ self.assertRaises(errors.MissingRedirectURIError,
74
+ self.mobile.validate_authorization_request, uri.format('token'))
75
+ self.assertRaises(errors.MissingRedirectURIError,
76
+ self.mobile.create_authorization_response, uri.format('token'), scopes=['foo'])
77
+
78
+ def test_mismatching_redirect_uri(self):
79
+ uri = 'https://example.com/authorize?response_type={0}&client_id=foo&redirect_uri=https%3A%2F%2Fi.b%2Fback'
80
+
81
+ # Authorization code grant
82
+ self.validator.validate_redirect_uri.return_value = False
83
+ self.assertRaises(errors.MismatchingRedirectURIError,
84
+ self.web.validate_authorization_request, uri.format('code'))
85
+ self.assertRaises(errors.MismatchingRedirectURIError,
86
+ self.web.create_authorization_response, uri.format('code'), scopes=['foo'])
87
+
88
+ # Implicit grant
89
+ self.assertRaises(errors.MismatchingRedirectURIError,
90
+ self.mobile.validate_authorization_request, uri.format('token'))
91
+ self.assertRaises(errors.MismatchingRedirectURIError,
92
+ self.mobile.create_authorization_response, uri.format('token'), scopes=['foo'])
93
+
94
+ def test_missing_client_id(self):
95
+ uri = 'https://example.com/authorize?response_type={0}&redirect_uri=https%3A%2F%2Fi.b%2Fback'
96
+
97
+ # Authorization code grant
98
+ self.validator.validate_redirect_uri.return_value = False
99
+ self.assertRaises(errors.MissingClientIdError,
100
+ self.web.validate_authorization_request, uri.format('code'))
101
+ self.assertRaises(errors.MissingClientIdError,
102
+ self.web.create_authorization_response, uri.format('code'), scopes=['foo'])
103
+
104
+ # Implicit grant
105
+ self.assertRaises(errors.MissingClientIdError,
106
+ self.mobile.validate_authorization_request, uri.format('token'))
107
+ self.assertRaises(errors.MissingClientIdError,
108
+ self.mobile.create_authorization_response, uri.format('token'), scopes=['foo'])
109
+
110
+ def test_invalid_client_id(self):
111
+ uri = 'https://example.com/authorize?response_type={0}&client_id=foo&redirect_uri=https%3A%2F%2Fi.b%2Fback'
112
+
113
+ # Authorization code grant
114
+ self.validator.validate_client_id.return_value = False
115
+ self.assertRaises(errors.InvalidClientIdError,
116
+ self.web.validate_authorization_request, uri.format('code'))
117
+ self.assertRaises(errors.InvalidClientIdError,
118
+ self.web.create_authorization_response, uri.format('code'), scopes=['foo'])
119
+
120
+ # Implicit grant
121
+ self.assertRaises(errors.InvalidClientIdError,
122
+ self.mobile.validate_authorization_request, uri.format('token'))
123
+ self.assertRaises(errors.InvalidClientIdError,
124
+ self.mobile.create_authorization_response, uri.format('token'), scopes=['foo'])
125
+
126
+ def test_empty_parameter(self):
127
+ uri = 'https://example.com/authorize?client_id=foo&redirect_uri=https%3A%2F%2Fi.b%2Fback&response_type=code&'
128
+
129
+ # Authorization code grant
130
+ self.assertRaises(errors.InvalidRequestFatalError,
131
+ self.web.validate_authorization_request, uri)
132
+
133
+ # Implicit grant
134
+ self.assertRaises(errors.InvalidRequestFatalError,
135
+ self.mobile.validate_authorization_request, uri)
136
+
137
+ def test_invalid_request(self):
138
+ self.validator.get_default_redirect_uri.return_value = 'https://i.b/cb'
139
+ token_uri = 'https://i.b/token'
140
+
141
+ invalid_bodies = [
142
+ # duplicate params
143
+ 'grant_type=authorization_code&client_id=nope&client_id=nope&code=foo'
144
+ ]
145
+ for body in invalid_bodies:
146
+ _, body, _ = self.web.create_token_response(token_uri,
147
+ body=body)
148
+ self.assertEqual('invalid_request', json.loads(body)['error'])
149
+
150
+ # Password credentials grant
151
+ invalid_bodies = [
152
+ # duplicate params
153
+ 'grant_type=password&username=foo&username=bar&password=baz'
154
+ # missing username
155
+ 'grant_type=password&password=baz'
156
+ # missing password
157
+ 'grant_type=password&username=foo'
158
+ ]
159
+ self.validator.authenticate_client.side_effect = self.set_client
160
+ for body in invalid_bodies:
161
+ _, body, _ = self.legacy.create_token_response(token_uri,
162
+ body=body)
163
+ self.assertEqual('invalid_request', json.loads(body)['error'])
164
+
165
+ # Client credentials grant
166
+ invalid_bodies = [
167
+ # duplicate params
168
+ 'grant_type=client_credentials&scope=foo&scope=bar'
169
+ ]
170
+ for body in invalid_bodies:
171
+ _, body, _ = self.backend.create_token_response(token_uri,
172
+ body=body)
173
+ self.assertEqual('invalid_request', json.loads(body)['error'])
174
+
175
+ def test_invalid_request_duplicate_params(self):
176
+ self.validator.get_default_redirect_uri.return_value = 'https://i.b/cb'
177
+ uri = 'https://i.b/auth?client_id=foo&client_id=bar&response_type={0}'
178
+ description = 'Duplicate client_id parameter.'
179
+
180
+ # Authorization code
181
+ self.assertRaisesRegex(errors.InvalidRequestFatalError,
182
+ description,
183
+ self.web.validate_authorization_request,
184
+ uri.format('code'))
185
+ self.assertRaisesRegex(errors.InvalidRequestFatalError,
186
+ description,
187
+ self.web.create_authorization_response,
188
+ uri.format('code'), scopes=['foo'])
189
+
190
+ # Implicit grant
191
+ self.assertRaisesRegex(errors.InvalidRequestFatalError,
192
+ description,
193
+ self.mobile.validate_authorization_request,
194
+ uri.format('token'))
195
+ self.assertRaisesRegex(errors.InvalidRequestFatalError,
196
+ description,
197
+ self.mobile.create_authorization_response,
198
+ uri.format('token'), scopes=['foo'])
199
+
200
+ def test_invalid_request_missing_response_type(self):
201
+
202
+ self.validator.get_default_redirect_uri.return_value = 'https://i.b/cb'
203
+
204
+ uri = 'https://i.b/auth?client_id=foo'
205
+
206
+ # Authorization code
207
+ self.assertRaises(errors.MissingResponseTypeError,
208
+ self.web.validate_authorization_request,
209
+ uri.format('code'))
210
+ h, _, s = self.web.create_authorization_response(uri, scopes=['foo'])
211
+ self.assertEqual(s, 302)
212
+ self.assertIn('Location', h)
213
+ self.assertIn('error=invalid_request', h['Location'])
214
+
215
+ # Implicit grant
216
+ self.assertRaises(errors.MissingResponseTypeError,
217
+ self.mobile.validate_authorization_request,
218
+ uri.format('token'))
219
+ h, _, s = self.mobile.create_authorization_response(uri, scopes=['foo'])
220
+ self.assertEqual(s, 302)
221
+ self.assertIn('Location', h)
222
+ self.assertIn('error=invalid_request', h['Location'])
223
+
224
+ def test_unauthorized_client(self):
225
+ self.validator.get_default_redirect_uri.return_value = 'https://i.b/cb'
226
+ self.validator.validate_grant_type.return_value = False
227
+ self.validator.validate_response_type.return_value = False
228
+ self.validator.authenticate_client.side_effect = self.set_client
229
+ token_uri = 'https://i.b/token'
230
+
231
+ # Authorization code grant
232
+ self.assertRaises(errors.UnauthorizedClientError,
233
+ self.web.validate_authorization_request,
234
+ 'https://i.b/auth?response_type=code&client_id=foo')
235
+ _, body, _ = self.web.create_token_response(token_uri,
236
+ body='grant_type=authorization_code&code=foo')
237
+ self.assertEqual('unauthorized_client', json.loads(body)['error'])
238
+
239
+ # Implicit grant
240
+ self.assertRaises(errors.UnauthorizedClientError,
241
+ self.mobile.validate_authorization_request,
242
+ 'https://i.b/auth?response_type=token&client_id=foo')
243
+
244
+ # Password credentials grant
245
+ _, body, _ = self.legacy.create_token_response(token_uri,
246
+ body='grant_type=password&username=foo&password=bar')
247
+ self.assertEqual('unauthorized_client', json.loads(body)['error'])
248
+
249
+ # Client credentials grant
250
+ _, body, _ = self.backend.create_token_response(token_uri,
251
+ body='grant_type=client_credentials')
252
+ self.assertEqual('unauthorized_client', json.loads(body)['error'])
253
+
254
+ def test_access_denied(self):
255
+ self.validator.authenticate_client.side_effect = self.set_client
256
+ self.validator.get_default_redirect_uri.return_value = 'https://i.b/cb'
257
+ self.validator.confirm_redirect_uri.return_value = False
258
+ token_uri = 'https://i.b/token'
259
+ # Authorization code grant
260
+ _, body, _ = self.web.create_token_response(token_uri,
261
+ body='grant_type=authorization_code&code=foo')
262
+ self.assertEqual('invalid_request', json.loads(body)['error'])
263
+
264
+ def test_access_denied_no_default_redirecturi(self):
265
+ self.validator.authenticate_client.side_effect = self.set_client
266
+ self.validator.get_default_redirect_uri.return_value = None
267
+ token_uri = 'https://i.b/token'
268
+ # Authorization code grant
269
+ _, body, _ = self.web.create_token_response(token_uri,
270
+ body='grant_type=authorization_code&code=foo')
271
+ self.assertEqual('invalid_request', json.loads(body)['error'])
272
+
273
+ def test_unsupported_response_type(self):
274
+ self.validator.get_default_redirect_uri.return_value = 'https://i.b/cb'
275
+
276
+ # Authorization code grant
277
+ self.assertRaises(errors.UnsupportedResponseTypeError,
278
+ self.web.validate_authorization_request,
279
+ 'https://i.b/auth?response_type=foo&client_id=foo')
280
+
281
+ # Implicit grant
282
+ self.assertRaises(errors.UnsupportedResponseTypeError,
283
+ self.mobile.validate_authorization_request,
284
+ 'https://i.b/auth?response_type=foo&client_id=foo')
285
+
286
+ def test_invalid_scope(self):
287
+ self.validator.get_default_redirect_uri.return_value = 'https://i.b/cb'
288
+ self.validator.validate_scopes.return_value = False
289
+ self.validator.authenticate_client.side_effect = self.set_client
290
+
291
+ # Authorization code grant
292
+ self.assertRaises(errors.InvalidScopeError,
293
+ self.web.validate_authorization_request,
294
+ 'https://i.b/auth?response_type=code&client_id=foo')
295
+
296
+ # Implicit grant
297
+ self.assertRaises(errors.InvalidScopeError,
298
+ self.mobile.validate_authorization_request,
299
+ 'https://i.b/auth?response_type=token&client_id=foo')
300
+
301
+ # Password credentials grant
302
+ _, body, _ = self.legacy.create_token_response(
303
+ 'https://i.b/token',
304
+ body='grant_type=password&username=foo&password=bar')
305
+ self.assertEqual('invalid_scope', json.loads(body)['error'])
306
+
307
+ # Client credentials grant
308
+ _, body, _ = self.backend.create_token_response(
309
+ 'https://i.b/token',
310
+ body='grant_type=client_credentials')
311
+ self.assertEqual('invalid_scope', json.loads(body)['error'])
312
+
313
+ def test_server_error(self):
314
+ def raise_error(*args, **kwargs):
315
+ raise ValueError()
316
+
317
+ self.validator.validate_client_id.side_effect = raise_error
318
+ self.validator.authenticate_client.side_effect = raise_error
319
+ self.validator.get_default_redirect_uri.return_value = 'https://i.b/cb'
320
+
321
+ # Authorization code grant
322
+ self.web.catch_errors = True
323
+ _, _, s = self.web.create_authorization_response(
324
+ 'https://i.b/auth?client_id=foo&response_type=code',
325
+ scopes=['foo'])
326
+ self.assertEqual(s, 500)
327
+ _, _, s = self.web.create_token_response(
328
+ 'https://i.b/token',
329
+ body='grant_type=authorization_code&code=foo',
330
+ scopes=['foo'])
331
+ self.assertEqual(s, 500)
332
+
333
+ # Implicit grant
334
+ self.mobile.catch_errors = True
335
+ _, _, s = self.mobile.create_authorization_response(
336
+ 'https://i.b/auth?client_id=foo&response_type=token',
337
+ scopes=['foo'])
338
+ self.assertEqual(s, 500)
339
+
340
+ # Password credentials grant
341
+ self.legacy.catch_errors = True
342
+ _, _, s = self.legacy.create_token_response(
343
+ 'https://i.b/token',
344
+ body='grant_type=password&username=foo&password=foo')
345
+ self.assertEqual(s, 500)
346
+
347
+ # Client credentials grant
348
+ self.backend.catch_errors = True
349
+ _, _, s = self.backend.create_token_response(
350
+ 'https://i.b/token',
351
+ body='grant_type=client_credentials')
352
+ self.assertEqual(s, 500)
353
+
354
+ def test_temporarily_unavailable(self):
355
+ # Authorization code grant
356
+ self.web.available = False
357
+ _, _, s = self.web.create_authorization_response(
358
+ 'https://i.b/auth?client_id=foo&response_type=code',
359
+ scopes=['foo'])
360
+ self.assertEqual(s, 503)
361
+ _, _, s = self.web.create_token_response(
362
+ 'https://i.b/token',
363
+ body='grant_type=authorization_code&code=foo',
364
+ scopes=['foo'])
365
+ self.assertEqual(s, 503)
366
+
367
+ # Implicit grant
368
+ self.mobile.available = False
369
+ _, _, s = self.mobile.create_authorization_response(
370
+ 'https://i.b/auth?client_id=foo&response_type=token',
371
+ scopes=['foo'])
372
+ self.assertEqual(s, 503)
373
+
374
+ # Password credentials grant
375
+ self.legacy.available = False
376
+ _, _, s = self.legacy.create_token_response(
377
+ 'https://i.b/token',
378
+ body='grant_type=password&username=foo&password=foo')
379
+ self.assertEqual(s, 503)
380
+
381
+ # Client credentials grant
382
+ self.backend.available = False
383
+ _, _, s = self.backend.create_token_response(
384
+ 'https://i.b/token',
385
+ body='grant_type=client_credentials')
386
+ self.assertEqual(s, 503)
387
+
388
+ def test_invalid_client(self):
389
+ self.validator.authenticate_client.return_value = False
390
+ self.validator.authenticate_client_id.return_value = False
391
+
392
+ # Authorization code grant
393
+ _, body, _ = self.web.create_token_response('https://i.b/token',
394
+ body='grant_type=authorization_code&code=foo')
395
+ self.assertEqual('invalid_client', json.loads(body)['error'])
396
+
397
+ # Password credentials grant
398
+ _, body, _ = self.legacy.create_token_response('https://i.b/token',
399
+ body='grant_type=password&username=foo&password=bar')
400
+ self.assertEqual('invalid_client', json.loads(body)['error'])
401
+
402
+ # Client credentials grant
403
+ _, body, _ = self.legacy.create_token_response('https://i.b/token',
404
+ body='grant_type=client_credentials')
405
+ self.assertEqual('invalid_client', json.loads(body)['error'])
406
+
407
+ def test_invalid_grant(self):
408
+ self.validator.authenticate_client.side_effect = self.set_client
409
+
410
+ # Authorization code grant
411
+ self.validator.validate_code.return_value = False
412
+ _, body, _ = self.web.create_token_response('https://i.b/token',
413
+ body='grant_type=authorization_code&code=foo')
414
+ self.assertEqual('invalid_grant', json.loads(body)['error'])
415
+
416
+ # Password credentials grant
417
+ self.validator.validate_user.return_value = False
418
+ _, body, _ = self.legacy.create_token_response('https://i.b/token',
419
+ body='grant_type=password&username=foo&password=bar')
420
+ self.assertEqual('invalid_grant', json.loads(body)['error'])
421
+
422
+ def test_unsupported_grant_type(self):
423
+ self.validator.authenticate_client.side_effect = self.set_client
424
+
425
+ # Authorization code grant
426
+ _, body, _ = self.web.create_token_response('https://i.b/token',
427
+ body='grant_type=bar&code=foo')
428
+ self.assertEqual('unsupported_grant_type', json.loads(body)['error'])
429
+
430
+ # Password credentials grant
431
+ _, body, _ = self.legacy.create_token_response('https://i.b/token',
432
+ body='grant_type=bar&username=foo&password=bar')
433
+ self.assertEqual('unsupported_grant_type', json.loads(body)['error'])
434
+
435
+ # Client credentials grant
436
+ _, body, _ = self.backend.create_token_response('https://i.b/token',
437
+ body='grant_type=bar')
438
+ self.assertEqual('unsupported_grant_type', json.loads(body)['error'])
439
+
440
+ def test_invalid_request_method(self):
441
+ test_methods = ['GET', 'pUt', 'dEleTe', 'paTcH']
442
+ test_methods = test_methods + [x.lower() for x in test_methods] + [x.upper() for x in test_methods]
443
+ for method in test_methods:
444
+ self.validator.authenticate_client.side_effect = self.set_client
445
+
446
+ uri = "http://i/b/token/"
447
+ try:
448
+ _, body, s = self.web.create_token_response(uri,
449
+ body='grant_type=access_token&code=123', http_method=method)
450
+ self.fail('This should have failed with InvalidRequestError')
451
+ except errors.InvalidRequestError as ire:
452
+ self.assertIn('Unsupported request method', ire.description)
453
+
454
+ try:
455
+ _, body, s = self.legacy.create_token_response(uri,
456
+ body='grant_type=access_token&code=123', http_method=method)
457
+ self.fail('This should have failed with InvalidRequestError')
458
+ except errors.InvalidRequestError as ire:
459
+ self.assertIn('Unsupported request method', ire.description)
460
+
461
+ try:
462
+ _, body, s = self.backend.create_token_response(uri,
463
+ body='grant_type=access_token&code=123', http_method=method)
464
+ self.fail('This should have failed with InvalidRequestError')
465
+ except errors.InvalidRequestError as ire:
466
+ self.assertIn('Unsupported request method', ire.description)
467
+
468
+ def test_invalid_post_request(self):
469
+ self.validator.authenticate_client.side_effect = self.set_client
470
+ for param in ['token', 'secret', 'code', 'foo']:
471
+ uri = 'https://i/b/token?' + urlencode([(param, 'secret')])
472
+ try:
473
+ _, body, s = self.web.create_token_response(uri,
474
+ body='grant_type=access_token&code=123')
475
+ self.fail('This should have failed with InvalidRequestError')
476
+ except errors.InvalidRequestError as ire:
477
+ self.assertIn('URL query parameters are not allowed', ire.description)
478
+
479
+ try:
480
+ _, body, s = self.legacy.create_token_response(uri,
481
+ body='grant_type=access_token&code=123')
482
+ self.fail('This should have failed with InvalidRequestError')
483
+ except errors.InvalidRequestError as ire:
484
+ self.assertIn('URL query parameters are not allowed', ire.description)
485
+
486
+ try:
487
+ _, body, s = self.backend.create_token_response(uri,
488
+ body='grant_type=access_token&code=123')
489
+ self.fail('This should have failed with InvalidRequestError')
490
+ except errors.InvalidRequestError as ire:
491
+ self.assertIn('URL query parameters are not allowed', ire.description)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_extra_credentials.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ensure extra credentials can be supplied for inclusion in tokens.
2
+ """
3
+ from unittest import mock
4
+
5
+ from oauthlib.oauth2 import (
6
+ BackendApplicationServer, LegacyApplicationServer, MobileApplicationServer,
7
+ RequestValidator, WebApplicationServer,
8
+ )
9
+
10
+ from tests.unittest import TestCase
11
+
12
+
13
+ class ExtraCredentialsTest(TestCase):
14
+
15
+ def set_client(self, request):
16
+ request.client = mock.MagicMock()
17
+ request.client.client_id = 'mocked'
18
+ return True
19
+
20
+ def setUp(self):
21
+ self.validator = mock.MagicMock(spec=RequestValidator)
22
+ self.validator.get_default_redirect_uri.return_value = 'https://i.b/cb'
23
+ self.web = WebApplicationServer(self.validator)
24
+ self.mobile = MobileApplicationServer(self.validator)
25
+ self.legacy = LegacyApplicationServer(self.validator)
26
+ self.backend = BackendApplicationServer(self.validator)
27
+
28
+ def test_post_authorization_request(self):
29
+ def save_code(client_id, token, request):
30
+ self.assertEqual('creds', request.extra)
31
+
32
+ def save_token(token, request):
33
+ self.assertEqual('creds', request.extra)
34
+
35
+ # Authorization code grant
36
+ self.validator.save_authorization_code.side_effect = save_code
37
+ self.web.create_authorization_response(
38
+ 'https://i.b/auth?client_id=foo&response_type=code',
39
+ scopes=['foo'],
40
+ credentials={'extra': 'creds'})
41
+
42
+ # Implicit grant
43
+ self.validator.save_bearer_token.side_effect = save_token
44
+ self.mobile.create_authorization_response(
45
+ 'https://i.b/auth?client_id=foo&response_type=token',
46
+ scopes=['foo'],
47
+ credentials={'extra': 'creds'})
48
+
49
+ def test_token_request(self):
50
+ def save_token(token, request):
51
+ self.assertIn('extra', token)
52
+
53
+ self.validator.save_bearer_token.side_effect = save_token
54
+ self.validator.authenticate_client.side_effect = self.set_client
55
+
56
+ # Authorization code grant
57
+ self.web.create_token_response('https://i.b/token',
58
+ body='grant_type=authorization_code&code=foo',
59
+ credentials={'extra': 'creds'})
60
+
61
+ # Password credentials grant
62
+ self.legacy.create_token_response('https://i.b/token',
63
+ body='grant_type=password&username=foo&password=bar',
64
+ credentials={'extra': 'creds'})
65
+
66
+ # Client credentials grant
67
+ self.backend.create_token_response('https://i.b/token',
68
+ body='grant_type=client_credentials',
69
+ credentials={'extra': 'creds'})
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_introspect_endpoint.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from json import loads
3
+ from unittest.mock import MagicMock
4
+
5
+ from oauthlib.common import urlencode
6
+ from oauthlib.oauth2 import IntrospectEndpoint, RequestValidator
7
+
8
+ from tests.unittest import TestCase
9
+
10
+
11
+ class IntrospectEndpointTest(TestCase):
12
+
13
+ def setUp(self):
14
+ self.validator = MagicMock(wraps=RequestValidator())
15
+ self.validator.client_authentication_required.return_value = True
16
+ self.validator.authenticate_client.return_value = True
17
+ self.validator.validate_bearer_token.return_value = True
18
+ self.validator.introspect_token.return_value = {}
19
+ self.endpoint = IntrospectEndpoint(self.validator)
20
+
21
+ self.uri = 'should_not_matter'
22
+ self.headers = {
23
+ 'Content-Type': 'application/x-www-form-urlencoded',
24
+ }
25
+ self.resp_h = {
26
+ 'Cache-Control': 'no-store',
27
+ 'Content-Type': 'application/json',
28
+ 'Pragma': 'no-cache'
29
+ }
30
+ self.resp_b = {
31
+ "active": True
32
+ }
33
+
34
+ def test_introspect_token(self):
35
+ for token_type in ('access_token', 'refresh_token', 'invalid'):
36
+ body = urlencode([('token', 'foo'),
37
+ ('token_type_hint', token_type)])
38
+ h, b, s = self.endpoint.create_introspect_response(self.uri,
39
+ headers=self.headers, body=body)
40
+ self.assertEqual(h, self.resp_h)
41
+ self.assertEqual(loads(b), self.resp_b)
42
+ self.assertEqual(s, 200)
43
+
44
+ def test_introspect_token_nohint(self):
45
+ # don't specify token_type_hint
46
+ body = urlencode([('token', 'foo')])
47
+ h, b, s = self.endpoint.create_introspect_response(self.uri,
48
+ headers=self.headers, body=body)
49
+ self.assertEqual(h, self.resp_h)
50
+ self.assertEqual(loads(b), self.resp_b)
51
+ self.assertEqual(s, 200)
52
+
53
+ def test_introspect_token_false(self):
54
+ self.validator.introspect_token.return_value = None
55
+ body = urlencode([('token', 'foo')])
56
+ h, b, s = self.endpoint.create_introspect_response(self.uri,
57
+ headers=self.headers, body=body)
58
+ self.assertEqual(h, self.resp_h)
59
+ self.assertEqual(loads(b), {"active": False})
60
+ self.assertEqual(s, 200)
61
+
62
+ def test_introspect_token_claims(self):
63
+ self.validator.introspect_token.return_value = {"foo": "bar"}
64
+ body = urlencode([('token', 'foo')])
65
+ h, b, s = self.endpoint.create_introspect_response(self.uri,
66
+ headers=self.headers, body=body)
67
+ self.assertEqual(h, self.resp_h)
68
+ self.assertEqual(loads(b), {"active": True, "foo": "bar"})
69
+ self.assertEqual(s, 200)
70
+
71
+ def test_introspect_token_claims_spoof_active(self):
72
+ self.validator.introspect_token.return_value = {"foo": "bar", "active": False}
73
+ body = urlencode([('token', 'foo')])
74
+ h, b, s = self.endpoint.create_introspect_response(self.uri,
75
+ headers=self.headers, body=body)
76
+ self.assertEqual(h, self.resp_h)
77
+ self.assertEqual(loads(b), {"active": True, "foo": "bar"})
78
+ self.assertEqual(s, 200)
79
+
80
+ def test_introspect_token_client_authentication_failed(self):
81
+ self.validator.authenticate_client.return_value = False
82
+ body = urlencode([('token', 'foo'),
83
+ ('token_type_hint', 'access_token')])
84
+ h, b, s = self.endpoint.create_introspect_response(self.uri,
85
+ headers=self.headers, body=body)
86
+ self.assertEqual(h, {
87
+ 'Content-Type': 'application/json',
88
+ 'Cache-Control': 'no-store',
89
+ 'Pragma': 'no-cache',
90
+ "WWW-Authenticate": 'Bearer error="invalid_client"'
91
+ })
92
+ self.assertEqual(loads(b)['error'], 'invalid_client')
93
+ self.assertEqual(s, 401)
94
+
95
+ def test_introspect_token_public_client_authentication(self):
96
+ self.validator.client_authentication_required.return_value = False
97
+ self.validator.authenticate_client_id.return_value = True
98
+ for token_type in ('access_token', 'refresh_token', 'invalid'):
99
+ body = urlencode([('token', 'foo'),
100
+ ('token_type_hint', token_type)])
101
+ h, b, s = self.endpoint.create_introspect_response(self.uri,
102
+ headers=self.headers, body=body)
103
+ self.assertEqual(h, self.resp_h)
104
+ self.assertEqual(loads(b), self.resp_b)
105
+ self.assertEqual(s, 200)
106
+
107
+ def test_introspect_token_public_client_authentication_failed(self):
108
+ self.validator.client_authentication_required.return_value = False
109
+ self.validator.authenticate_client_id.return_value = False
110
+ body = urlencode([('token', 'foo'),
111
+ ('token_type_hint', 'access_token')])
112
+ h, b, s = self.endpoint.create_introspect_response(self.uri,
113
+ headers=self.headers, body=body)
114
+ self.assertEqual(h, {
115
+ 'Content-Type': 'application/json',
116
+ 'Cache-Control': 'no-store',
117
+ 'Pragma': 'no-cache',
118
+ "WWW-Authenticate": 'Bearer error="invalid_client"'
119
+ })
120
+ self.assertEqual(loads(b)['error'], 'invalid_client')
121
+ self.assertEqual(s, 401)
122
+
123
+ def test_introspect_unsupported_token(self):
124
+ endpoint = IntrospectEndpoint(self.validator,
125
+ supported_token_types=['access_token'])
126
+ body = urlencode([('token', 'foo'),
127
+ ('token_type_hint', 'refresh_token')])
128
+ h, b, s = endpoint.create_introspect_response(self.uri,
129
+ headers=self.headers, body=body)
130
+ self.assertEqual(h, self.resp_h)
131
+ self.assertEqual(loads(b)['error'], 'unsupported_token_type')
132
+ self.assertEqual(s, 400)
133
+
134
+ h, b, s = endpoint.create_introspect_response(self.uri,
135
+ headers=self.headers, body='')
136
+ self.assertEqual(h, self.resp_h)
137
+ self.assertEqual(loads(b)['error'], 'invalid_request')
138
+ self.assertEqual(s, 400)
139
+
140
+ def test_introspect_invalid_request_method(self):
141
+ endpoint = IntrospectEndpoint(self.validator,
142
+ supported_token_types=['access_token'])
143
+ test_methods = ['GET', 'pUt', 'dEleTe', 'paTcH']
144
+ test_methods = test_methods + [x.lower() for x in test_methods] + [x.upper() for x in test_methods]
145
+ for method in test_methods:
146
+ body = urlencode([('token', 'foo'),
147
+ ('token_type_hint', 'refresh_token')])
148
+ h, b, s = endpoint.create_introspect_response(self.uri,
149
+ http_method = method, headers=self.headers, body=body)
150
+ self.assertEqual(h, self.resp_h)
151
+ self.assertEqual(loads(b)['error'], 'invalid_request')
152
+ self.assertIn('Unsupported request method', loads(b)['error_description'])
153
+ self.assertEqual(s, 400)
154
+
155
+ def test_introspect_bad_post_request(self):
156
+ endpoint = IntrospectEndpoint(self.validator,
157
+ supported_token_types=['access_token'])
158
+ for param in ['token', 'secret', 'code', 'foo']:
159
+ uri = 'http://some.endpoint?' + urlencode([(param, 'secret')])
160
+ body = urlencode([('token', 'foo'),
161
+ ('token_type_hint', 'access_token')])
162
+ h, b, s = endpoint.create_introspect_response(
163
+ uri,
164
+ headers=self.headers, body=body)
165
+ self.assertEqual(h, self.resp_h)
166
+ self.assertEqual(loads(b)['error'], 'invalid_request')
167
+ self.assertIn('query parameters are not allowed', loads(b)['error_description'])
168
+ self.assertEqual(s, 400)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_metadata.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import json
3
+
4
+ from oauthlib.oauth2 import MetadataEndpoint, Server, TokenEndpoint
5
+
6
+ from tests.unittest import TestCase
7
+
8
+
9
+ class MetadataEndpointTest(TestCase):
10
+ def setUp(self):
11
+ self.metadata = {
12
+ "issuer": 'https://foo.bar'
13
+ }
14
+
15
+ def test_openid_oauth2_preconfigured(self):
16
+ default_claims = {
17
+ "issuer": 'https://foo.bar',
18
+ "authorization_endpoint": "https://foo.bar/authorize",
19
+ "revocation_endpoint": "https://foo.bar/revoke",
20
+ "introspection_endpoint": "https://foo.bar/introspect",
21
+ "token_endpoint": "https://foo.bar/token"
22
+ }
23
+ from oauthlib.oauth2 import Server as OAuth2Server
24
+ from oauthlib.openid import Server as OpenIDServer
25
+
26
+ endpoint = OAuth2Server(None)
27
+ metadata = MetadataEndpoint([endpoint], default_claims)
28
+ oauth2_claims = metadata.claims
29
+
30
+ endpoint = OpenIDServer(None)
31
+ metadata = MetadataEndpoint([endpoint], default_claims)
32
+ openid_claims = metadata.claims
33
+
34
+ # Pure OAuth2 Authorization Metadata are similar with OpenID but
35
+ # response_type not! (OIDC contains "id_token" and hybrid flows)
36
+ del oauth2_claims['response_types_supported']
37
+ del openid_claims['response_types_supported']
38
+
39
+ self.maxDiff = None
40
+ self.assertEqual(openid_claims, oauth2_claims)
41
+
42
+ def test_create_metadata_response(self):
43
+ endpoint = TokenEndpoint(None, None, grant_types={"password": None})
44
+ metadata = MetadataEndpoint([endpoint], {
45
+ "issuer": 'https://foo.bar',
46
+ "token_endpoint": "https://foo.bar/token"
47
+ })
48
+ headers, body, status = metadata.create_metadata_response('/', 'GET')
49
+ assert headers == {
50
+ 'Content-Type': 'application/json',
51
+ 'Access-Control-Allow-Origin': '*',
52
+ }
53
+ claims = json.loads(body)
54
+ assert claims['issuer'] == 'https://foo.bar'
55
+
56
+ def test_token_endpoint(self):
57
+ endpoint = TokenEndpoint(None, None, grant_types={"password": None})
58
+ metadata = MetadataEndpoint([endpoint], {
59
+ "issuer": 'https://foo.bar',
60
+ "token_endpoint": "https://foo.bar/token"
61
+ })
62
+ self.assertIn("grant_types_supported", metadata.claims)
63
+ self.assertEqual(metadata.claims["grant_types_supported"], ["password"])
64
+
65
+ def test_token_endpoint_overridden(self):
66
+ endpoint = TokenEndpoint(None, None, grant_types={"password": None})
67
+ metadata = MetadataEndpoint([endpoint], {
68
+ "issuer": 'https://foo.bar',
69
+ "token_endpoint": "https://foo.bar/token",
70
+ "grant_types_supported": ["pass_word_special_provider"]
71
+ })
72
+ self.assertIn("grant_types_supported", metadata.claims)
73
+ self.assertEqual(metadata.claims["grant_types_supported"], ["pass_word_special_provider"])
74
+
75
+ def test_mandatory_fields(self):
76
+ metadata = MetadataEndpoint([], self.metadata)
77
+ self.assertIn("issuer", metadata.claims)
78
+ self.assertEqual(metadata.claims["issuer"], 'https://foo.bar')
79
+
80
+ def test_server_metadata(self):
81
+ endpoint = Server(None)
82
+ metadata = MetadataEndpoint([endpoint], {
83
+ "issuer": 'https://foo.bar',
84
+ "authorization_endpoint": "https://foo.bar/authorize",
85
+ "introspection_endpoint": "https://foo.bar/introspect",
86
+ "revocation_endpoint": "https://foo.bar/revoke",
87
+ "token_endpoint": "https://foo.bar/token",
88
+ "jwks_uri": "https://foo.bar/certs",
89
+ "scopes_supported": ["email", "profile"]
90
+ })
91
+ expected_claims = {
92
+ "issuer": "https://foo.bar",
93
+ "authorization_endpoint": "https://foo.bar/authorize",
94
+ "introspection_endpoint": "https://foo.bar/introspect",
95
+ "revocation_endpoint": "https://foo.bar/revoke",
96
+ "token_endpoint": "https://foo.bar/token",
97
+ "jwks_uri": "https://foo.bar/certs",
98
+ "scopes_supported": ["email", "profile"],
99
+ "grant_types_supported": [
100
+ "authorization_code",
101
+ "password",
102
+ "client_credentials",
103
+ "refresh_token",
104
+ "implicit"
105
+ ],
106
+ "token_endpoint_auth_methods_supported": [
107
+ "client_secret_post",
108
+ "client_secret_basic"
109
+ ],
110
+ "response_types_supported": [
111
+ "code",
112
+ "token"
113
+ ],
114
+ "response_modes_supported": [
115
+ "query",
116
+ "fragment"
117
+ ],
118
+ "code_challenge_methods_supported": [
119
+ "plain",
120
+ "S256"
121
+ ],
122
+ "revocation_endpoint_auth_methods_supported": [
123
+ "client_secret_post",
124
+ "client_secret_basic"
125
+ ],
126
+ "introspection_endpoint_auth_methods_supported": [
127
+ "client_secret_post",
128
+ "client_secret_basic"
129
+ ]
130
+ }
131
+
132
+ def sort_list(claims):
133
+ for key, value in claims.items():
134
+ claims[key] = sorted(value)
135
+
136
+ sort_list(metadata.claims)
137
+ sort_list(expected_claims)
138
+ self.assertEqual(sorted(metadata.claims.items()), sorted(expected_claims.items()))
139
+
140
+ def test_metadata_validate_issuer(self):
141
+ with self.assertRaises(ValueError):
142
+ endpoint = TokenEndpoint(
143
+ None, None, grant_types={"password": None},
144
+ )
145
+ metadata = MetadataEndpoint([endpoint], {
146
+ "issuer": 'http://foo.bar',
147
+ "token_endpoint": "https://foo.bar/token",
148
+ })
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_resource_owner_association.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ensure all tokens are associated with a resource owner.
2
+ """
3
+ import json
4
+ from unittest import mock
5
+
6
+ from oauthlib.oauth2 import (
7
+ BackendApplicationServer, LegacyApplicationServer, MobileApplicationServer,
8
+ RequestValidator, WebApplicationServer,
9
+ )
10
+
11
+ from tests.unittest import TestCase
12
+
13
+ from .test_utils import get_fragment_credentials, get_query_credentials
14
+
15
+
16
+ class ResourceOwnerAssociationTest(TestCase):
17
+
18
+ auth_uri = 'http://example.com/path?client_id=abc'
19
+ token_uri = 'http://example.com/path'
20
+
21
+ def set_client(self, request):
22
+ request.client = mock.MagicMock()
23
+ request.client.client_id = 'mocked'
24
+ return True
25
+
26
+ def set_user(self, client_id, code, client, request):
27
+ request.user = 'test'
28
+ return True
29
+
30
+ def set_user_from_username(self, username, password, client, request):
31
+ request.user = 'test'
32
+ return True
33
+
34
+ def set_user_from_credentials(self, request):
35
+ request.user = 'test'
36
+ request.client = mock.MagicMock()
37
+ request.client.client_id = 'mocked'
38
+ return True
39
+
40
+ def inspect_client(self, request, refresh_token=False):
41
+ if not request.user:
42
+ raise ValueError()
43
+ return 'abc'
44
+
45
+ def setUp(self):
46
+ self.validator = mock.MagicMock(spec=RequestValidator)
47
+ self.validator.get_default_redirect_uri.return_value = 'http://i.b./path'
48
+ self.validator.get_code_challenge.return_value = None
49
+ self.validator.authenticate_client.side_effect = self.set_client
50
+ self.web = WebApplicationServer(self.validator,
51
+ token_generator=self.inspect_client)
52
+ self.mobile = MobileApplicationServer(self.validator,
53
+ token_generator=self.inspect_client)
54
+ self.legacy = LegacyApplicationServer(self.validator,
55
+ token_generator=self.inspect_client)
56
+ self.backend = BackendApplicationServer(self.validator,
57
+ token_generator=self.inspect_client)
58
+
59
+ def test_web_application(self):
60
+ # TODO: code generator + intercept test
61
+ h, _, s = self.web.create_authorization_response(
62
+ self.auth_uri + '&response_type=code',
63
+ credentials={'user': 'test'}, scopes=['random'])
64
+ self.assertEqual(s, 302)
65
+ self.assertIn('Location', h)
66
+ code = get_query_credentials(h['Location'])['code'][0]
67
+ self.assertRaises(ValueError,
68
+ self.web.create_token_response, self.token_uri,
69
+ body='grant_type=authorization_code&code=%s' % code)
70
+
71
+ self.validator.validate_code.side_effect = self.set_user
72
+ _, body, _ = self.web.create_token_response(self.token_uri,
73
+ body='grant_type=authorization_code&code=%s' % code)
74
+ self.assertEqual(json.loads(body)['access_token'], 'abc')
75
+
76
+ def test_mobile_application(self):
77
+ self.assertRaises(ValueError,
78
+ self.mobile.create_authorization_response,
79
+ self.auth_uri + '&response_type=token')
80
+
81
+ h, _, s = self.mobile.create_authorization_response(
82
+ self.auth_uri + '&response_type=token',
83
+ credentials={'user': 'test'}, scopes=['random'])
84
+ self.assertEqual(s, 302)
85
+ self.assertIn('Location', h)
86
+ self.assertEqual(get_fragment_credentials(h['Location'])['access_token'][0], 'abc')
87
+
88
+ def test_legacy_application(self):
89
+ body = 'grant_type=password&username=abc&password=secret'
90
+ self.assertRaises(ValueError,
91
+ self.legacy.create_token_response,
92
+ self.token_uri, body=body)
93
+
94
+ self.validator.validate_user.side_effect = self.set_user_from_username
95
+ _, body, _ = self.legacy.create_token_response(
96
+ self.token_uri, body=body)
97
+ self.assertEqual(json.loads(body)['access_token'], 'abc')
98
+
99
+ def test_backend_application(self):
100
+ body = 'grant_type=client_credentials'
101
+ self.assertRaises(ValueError,
102
+ self.backend.create_token_response,
103
+ self.token_uri, body=body)
104
+
105
+ self.validator.authenticate_client.side_effect = self.set_user_from_credentials
106
+ _, body, _ = self.backend.create_token_response(
107
+ self.token_uri, body=body)
108
+ self.assertEqual(json.loads(body)['access_token'], 'abc')
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_revocation_endpoint.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from json import loads
3
+ from unittest.mock import MagicMock
4
+
5
+ from oauthlib.common import urlencode
6
+ from oauthlib.oauth2 import RequestValidator, RevocationEndpoint
7
+
8
+ from tests.unittest import TestCase
9
+
10
+
11
+ class RevocationEndpointTest(TestCase):
12
+
13
+ def setUp(self):
14
+ self.validator = MagicMock(wraps=RequestValidator())
15
+ self.validator.client_authentication_required.return_value = True
16
+ self.validator.authenticate_client.return_value = True
17
+ self.validator.revoke_token.return_value = True
18
+ self.endpoint = RevocationEndpoint(self.validator)
19
+
20
+ self.uri = 'https://example.com/revoke_token'
21
+ self.headers = {
22
+ 'Content-Type': 'application/x-www-form-urlencoded',
23
+ }
24
+ self.resp_h = {
25
+ 'Cache-Control': 'no-store',
26
+ 'Content-Type': 'application/json',
27
+ 'Pragma': 'no-cache'
28
+ }
29
+
30
+ def test_revoke_token(self):
31
+ for token_type in ('access_token', 'refresh_token', 'invalid'):
32
+ body = urlencode([('token', 'foo'),
33
+ ('token_type_hint', token_type)])
34
+ h, b, s = self.endpoint.create_revocation_response(self.uri,
35
+ headers=self.headers, body=body)
36
+ self.assertEqual(h, {})
37
+ self.assertEqual(b, '')
38
+ self.assertEqual(s, 200)
39
+
40
+ # don't specify token_type_hint
41
+ body = urlencode([('token', 'foo')])
42
+ h, b, s = self.endpoint.create_revocation_response(self.uri,
43
+ headers=self.headers, body=body)
44
+ self.assertEqual(h, {})
45
+ self.assertEqual(b, '')
46
+ self.assertEqual(s, 200)
47
+
48
+ def test_revoke_token_client_authentication_failed(self):
49
+ self.validator.authenticate_client.return_value = False
50
+ body = urlencode([('token', 'foo'),
51
+ ('token_type_hint', 'access_token')])
52
+ h, b, s = self.endpoint.create_revocation_response(self.uri,
53
+ headers=self.headers, body=body)
54
+ self.assertEqual(h, {
55
+ 'Content-Type': 'application/json',
56
+ 'Cache-Control': 'no-store',
57
+ 'Pragma': 'no-cache',
58
+ "WWW-Authenticate": 'Bearer error="invalid_client"'
59
+ })
60
+ self.assertEqual(loads(b)['error'], 'invalid_client')
61
+ self.assertEqual(s, 401)
62
+
63
+ def test_revoke_token_public_client_authentication(self):
64
+ self.validator.client_authentication_required.return_value = False
65
+ self.validator.authenticate_client_id.return_value = True
66
+ for token_type in ('access_token', 'refresh_token', 'invalid'):
67
+ body = urlencode([('token', 'foo'),
68
+ ('token_type_hint', token_type)])
69
+ h, b, s = self.endpoint.create_revocation_response(self.uri,
70
+ headers=self.headers, body=body)
71
+ self.assertEqual(h, {})
72
+ self.assertEqual(b, '')
73
+ self.assertEqual(s, 200)
74
+
75
+ def test_revoke_token_public_client_authentication_failed(self):
76
+ self.validator.client_authentication_required.return_value = False
77
+ self.validator.authenticate_client_id.return_value = False
78
+ body = urlencode([('token', 'foo'),
79
+ ('token_type_hint', 'access_token')])
80
+ h, b, s = self.endpoint.create_revocation_response(self.uri,
81
+ headers=self.headers, body=body)
82
+ self.assertEqual(h, {
83
+ 'Content-Type': 'application/json',
84
+ 'Cache-Control': 'no-store',
85
+ 'Pragma': 'no-cache',
86
+ "WWW-Authenticate": 'Bearer error="invalid_client"'
87
+ })
88
+ self.assertEqual(loads(b)['error'], 'invalid_client')
89
+ self.assertEqual(s, 401)
90
+
91
+ def test_revoke_with_callback(self):
92
+ endpoint = RevocationEndpoint(self.validator, enable_jsonp=True)
93
+ callback = 'package.hello_world'
94
+ for token_type in ('access_token', 'refresh_token', 'invalid'):
95
+ body = urlencode([('token', 'foo'),
96
+ ('token_type_hint', token_type),
97
+ ('callback', callback)])
98
+ h, b, s = endpoint.create_revocation_response(self.uri,
99
+ headers=self.headers, body=body)
100
+ self.assertEqual(h, {})
101
+ self.assertEqual(b, callback + '();')
102
+ self.assertEqual(s, 200)
103
+
104
+ def test_revoke_unsupported_token(self):
105
+ endpoint = RevocationEndpoint(self.validator,
106
+ supported_token_types=['access_token'])
107
+ body = urlencode([('token', 'foo'),
108
+ ('token_type_hint', 'refresh_token')])
109
+ h, b, s = endpoint.create_revocation_response(self.uri,
110
+ headers=self.headers, body=body)
111
+ self.assertEqual(h, self.resp_h)
112
+ self.assertEqual(loads(b)['error'], 'unsupported_token_type')
113
+ self.assertEqual(s, 400)
114
+
115
+ h, b, s = endpoint.create_revocation_response(self.uri,
116
+ headers=self.headers, body='')
117
+ self.assertEqual(h, self.resp_h)
118
+ self.assertEqual(loads(b)['error'], 'invalid_request')
119
+ self.assertEqual(s, 400)
120
+
121
+ def test_revoke_invalid_request_method(self):
122
+ endpoint = RevocationEndpoint(self.validator,
123
+ supported_token_types=['access_token'])
124
+ test_methods = ['GET', 'pUt', 'dEleTe', 'paTcH']
125
+ test_methods = test_methods + [x.lower() for x in test_methods] + [x.upper() for x in test_methods]
126
+ for method in test_methods:
127
+ body = urlencode([('token', 'foo'),
128
+ ('token_type_hint', 'refresh_token')])
129
+ h, b, s = endpoint.create_revocation_response(self.uri,
130
+ http_method = method, headers=self.headers, body=body)
131
+ self.assertEqual(h, self.resp_h)
132
+ self.assertEqual(loads(b)['error'], 'invalid_request')
133
+ self.assertIn('Unsupported request method', loads(b)['error_description'])
134
+ self.assertEqual(s, 400)
135
+
136
+ def test_revoke_bad_post_request(self):
137
+ endpoint = RevocationEndpoint(self.validator,
138
+ supported_token_types=['access_token'])
139
+ for param in ['token', 'secret', 'code', 'foo']:
140
+ uri = 'http://some.endpoint?' + urlencode([(param, 'secret')])
141
+ body = urlencode([('token', 'foo'),
142
+ ('token_type_hint', 'access_token')])
143
+ h, b, s = endpoint.create_revocation_response(uri,
144
+ headers=self.headers, body=body)
145
+ self.assertEqual(h, self.resp_h)
146
+ self.assertEqual(loads(b)['error'], 'invalid_request')
147
+ self.assertIn('query parameters are not allowed', loads(b)['error_description'])
148
+ self.assertEqual(s, 400)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_scope_handling.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ensure scope is preserved across authorization.
2
+
3
+ Fairly trivial in all grants except the Authorization Code Grant where scope
4
+ need to be persisted temporarily in an authorization code.
5
+ """
6
+ import json
7
+ from unittest import mock
8
+
9
+ from oauthlib.oauth2 import (
10
+ BackendApplicationServer, LegacyApplicationServer, MobileApplicationServer,
11
+ RequestValidator, Server, WebApplicationServer,
12
+ )
13
+
14
+ from tests.unittest import TestCase
15
+
16
+ from .test_utils import get_fragment_credentials, get_query_credentials
17
+
18
+
19
+ class TestScopeHandling(TestCase):
20
+
21
+ DEFAULT_REDIRECT_URI = 'http://i.b./path'
22
+
23
+ def set_scopes(self, scopes):
24
+ def set_request_scopes(client_id, code, client, request):
25
+ request.scopes = scopes
26
+ return True
27
+ return set_request_scopes
28
+
29
+ def set_user(self, request):
30
+ request.user = 'foo'
31
+ request.client_id = 'bar'
32
+ request.client = mock.MagicMock()
33
+ request.client.client_id = 'mocked'
34
+ return True
35
+
36
+ def set_client(self, request):
37
+ request.client = mock.MagicMock()
38
+ request.client.client_id = 'mocked'
39
+ return True
40
+
41
+ def setUp(self):
42
+ self.validator = mock.MagicMock(spec=RequestValidator)
43
+ self.validator.get_default_redirect_uri.return_value = TestScopeHandling.DEFAULT_REDIRECT_URI
44
+ self.validator.get_code_challenge.return_value = None
45
+ self.validator.authenticate_client.side_effect = self.set_client
46
+ self.server = Server(self.validator)
47
+ self.web = WebApplicationServer(self.validator)
48
+ self.mobile = MobileApplicationServer(self.validator)
49
+ self.legacy = LegacyApplicationServer(self.validator)
50
+ self.backend = BackendApplicationServer(self.validator)
51
+
52
+ def test_scope_extraction(self):
53
+ scopes = (
54
+ ('images', ['images']),
55
+ ('images+videos', ['images', 'videos']),
56
+ ('images+videos+openid', ['images', 'videos', 'openid']),
57
+ ('http%3A%2f%2fa.b%2fvideos', ['http://a.b/videos']),
58
+ ('http%3A%2f%2fa.b%2fvideos+pics', ['http://a.b/videos', 'pics']),
59
+ ('pics+http%3A%2f%2fa.b%2fvideos', ['pics', 'http://a.b/videos']),
60
+ ('http%3A%2f%2fa.b%2fvideos+https%3A%2f%2fc.d%2Fsecret', ['http://a.b/videos', 'https://c.d/secret']),
61
+ )
62
+
63
+ uri = 'http://example.com/path?client_id=abc&scope=%s&response_type=%s'
64
+ for scope, correct_scopes in scopes:
65
+ scopes, _ = self.web.validate_authorization_request(
66
+ uri % (scope, 'code'))
67
+ self.assertCountEqual(scopes, correct_scopes)
68
+ scopes, _ = self.mobile.validate_authorization_request(
69
+ uri % (scope, 'token'))
70
+ self.assertCountEqual(scopes, correct_scopes)
71
+ scopes, _ = self.server.validate_authorization_request(
72
+ uri % (scope, 'code'))
73
+ self.assertCountEqual(scopes, correct_scopes)
74
+
75
+ def test_scope_preservation(self):
76
+ scope = 'pics+http%3A%2f%2fa.b%2fvideos'
77
+ decoded_scope = 'pics http://a.b/videos'
78
+ auth_uri = 'http://example.com/path?client_id=abc&response_type='
79
+ token_uri = 'http://example.com/path'
80
+
81
+ # authorization grant
82
+ for backend_server_type in ['web', 'server']:
83
+ h, _, s = getattr(self, backend_server_type).create_authorization_response(
84
+ auth_uri + 'code', scopes=decoded_scope.split(' '))
85
+ self.validator.validate_code.side_effect = self.set_scopes(decoded_scope.split(' '))
86
+ self.assertEqual(s, 302)
87
+ self.assertIn('Location', h)
88
+ code = get_query_credentials(h['Location'])['code'][0]
89
+ _, body, _ = getattr(self, backend_server_type).create_token_response(token_uri,
90
+ body='client_id=me&redirect_uri=http://back.to/me&grant_type=authorization_code&code=%s' % code)
91
+ self.assertEqual(json.loads(body)['scope'], decoded_scope)
92
+
93
+ # implicit grant
94
+ for backend_server_type in ['mobile', 'server']:
95
+ h, _, s = getattr(self, backend_server_type).create_authorization_response(
96
+ auth_uri + 'token', scopes=decoded_scope.split(' '))
97
+ self.assertEqual(s, 302)
98
+ self.assertIn('Location', h)
99
+ self.assertEqual(get_fragment_credentials(h['Location'])['scope'][0], decoded_scope)
100
+
101
+ # resource owner password credentials grant
102
+ for backend_server_type in ['legacy', 'server']:
103
+ body = 'grant_type=password&username=abc&password=secret&scope=%s'
104
+
105
+ _, body, _ = getattr(self, backend_server_type).create_token_response(token_uri,
106
+ body=body % scope)
107
+ self.assertEqual(json.loads(body)['scope'], decoded_scope)
108
+
109
+ # client credentials grant
110
+ for backend_server_type in ['backend', 'server']:
111
+ body = 'grant_type=client_credentials&scope=%s'
112
+ self.validator.authenticate_client.side_effect = self.set_user
113
+ _, body, _ = getattr(self, backend_server_type).create_token_response(token_uri,
114
+ body=body % scope)
115
+ self.assertEqual(json.loads(body)['scope'], decoded_scope)
116
+
117
+ def test_scope_changed(self):
118
+ scope = 'pics+http%3A%2f%2fa.b%2fvideos'
119
+ scopes = ['images', 'http://a.b/videos']
120
+ decoded_scope = 'images http://a.b/videos'
121
+ auth_uri = 'http://example.com/path?client_id=abc&response_type='
122
+ token_uri = 'http://example.com/path'
123
+
124
+ # authorization grant
125
+ h, _, s = self.web.create_authorization_response(
126
+ auth_uri + 'code', scopes=scopes)
127
+ self.assertEqual(s, 302)
128
+ self.assertIn('Location', h)
129
+ code = get_query_credentials(h['Location'])['code'][0]
130
+ self.validator.validate_code.side_effect = self.set_scopes(scopes)
131
+ _, body, _ = self.web.create_token_response(token_uri,
132
+ body='grant_type=authorization_code&code=%s' % code)
133
+ self.assertEqual(json.loads(body)['scope'], decoded_scope)
134
+
135
+ # implicit grant
136
+ self.validator.validate_scopes.side_effect = self.set_scopes(scopes)
137
+ h, _, s = self.mobile.create_authorization_response(
138
+ auth_uri + 'token', scopes=scopes)
139
+ self.assertEqual(s, 302)
140
+ self.assertIn('Location', h)
141
+ self.assertEqual(get_fragment_credentials(h['Location'])['scope'][0], decoded_scope)
142
+
143
+ # resource owner password credentials grant
144
+ self.validator.validate_scopes.side_effect = self.set_scopes(scopes)
145
+ body = 'grant_type=password&username=abc&password=secret&scope=%s'
146
+ _, body, _ = self.legacy.create_token_response(token_uri,
147
+ body=body % scope)
148
+ self.assertEqual(json.loads(body)['scope'], decoded_scope)
149
+
150
+ # client credentials grant
151
+ self.validator.validate_scopes.side_effect = self.set_scopes(scopes)
152
+ self.validator.authenticate_client.side_effect = self.set_user
153
+ body = 'grant_type=client_credentials&scope=%s'
154
+ _, body, _ = self.backend.create_token_response(token_uri,
155
+ body=body % scope)
156
+
157
+ self.assertEqual(json.loads(body)['scope'], decoded_scope)
158
+
159
+ def test_invalid_scope(self):
160
+ scope = 'pics+http%3A%2f%2fa.b%2fvideos'
161
+ auth_uri = 'http://example.com/path?client_id=abc&response_type='
162
+ token_uri = 'http://example.com/path'
163
+
164
+ self.validator.validate_scopes.return_value = False
165
+
166
+ # authorization grant
167
+ h, _, s = self.web.create_authorization_response(
168
+ auth_uri + 'code', scopes=['invalid'])
169
+ self.assertEqual(s, 302)
170
+ self.assertIn('Location', h)
171
+ error = get_query_credentials(h['Location'])['error'][0]
172
+ self.assertEqual(error, 'invalid_scope')
173
+
174
+ # implicit grant
175
+ h, _, s = self.mobile.create_authorization_response(
176
+ auth_uri + 'token', scopes=['invalid'])
177
+ self.assertEqual(s, 302)
178
+ self.assertIn('Location', h)
179
+ error = get_fragment_credentials(h['Location'])['error'][0]
180
+ self.assertEqual(error, 'invalid_scope')
181
+
182
+ # resource owner password credentials grant
183
+ body = 'grant_type=password&username=abc&password=secret&scope=%s'
184
+ _, body, _ = self.legacy.create_token_response(token_uri,
185
+ body=body % scope)
186
+ self.assertEqual(json.loads(body)['error'], 'invalid_scope')
187
+
188
+ # client credentials grant
189
+ self.validator.authenticate_client.side_effect = self.set_user
190
+ body = 'grant_type=client_credentials&scope=%s'
191
+ _, body, _ = self.backend.create_token_response(token_uri,
192
+ body=body % scope)
193
+ self.assertEqual(json.loads(body)['error'], 'invalid_scope')
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/endpoints/test_utils.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import urllib.parse as urlparse
2
+
3
+
4
+ def get_query_credentials(uri):
5
+ return urlparse.parse_qs(urlparse.urlparse(uri).query,
6
+ keep_blank_values=True)
7
+
8
+
9
+ def get_fragment_credentials(uri):
10
+ return urlparse.parse_qs(urlparse.urlparse(uri).fragment,
11
+ keep_blank_values=True)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/grant_types/__init__.py ADDED
File without changes
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/grant_types/test_authorization_code.py ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import json
3
+ from unittest import mock
4
+
5
+ from oauthlib.common import Request
6
+ from oauthlib.oauth2.rfc6749 import errors
7
+ from oauthlib.oauth2.rfc6749.grant_types import (
8
+ AuthorizationCodeGrant, authorization_code,
9
+ )
10
+ from oauthlib.oauth2.rfc6749.tokens import BearerToken
11
+
12
+ from tests.unittest import TestCase
13
+
14
+
15
+ class AuthorizationCodeGrantTest(TestCase):
16
+
17
+ def setUp(self):
18
+ self.request = Request('http://a.b/path')
19
+ self.request.scopes = ('hello', 'world')
20
+ self.request.expires_in = 1800
21
+ self.request.client = 'batman'
22
+ self.request.client_id = 'abcdef'
23
+ self.request.code = '1234'
24
+ self.request.response_type = 'code'
25
+ self.request.grant_type = 'authorization_code'
26
+ self.request.redirect_uri = 'https://a.b/cb'
27
+
28
+ self.mock_validator = mock.MagicMock()
29
+ self.mock_validator.is_pkce_required.return_value = False
30
+ self.mock_validator.get_code_challenge.return_value = None
31
+ self.mock_validator.is_origin_allowed.return_value = False
32
+ self.mock_validator.authenticate_client.side_effect = self.set_client
33
+ self.auth = AuthorizationCodeGrant(request_validator=self.mock_validator)
34
+
35
+ def set_client(self, request):
36
+ request.client = mock.MagicMock()
37
+ request.client.client_id = 'mocked'
38
+ return True
39
+
40
+ def setup_validators(self):
41
+ self.authval1, self.authval2 = mock.Mock(), mock.Mock()
42
+ self.authval1.return_value = {}
43
+ self.authval2.return_value = {}
44
+ self.tknval1, self.tknval2 = mock.Mock(), mock.Mock()
45
+ self.tknval1.return_value = None
46
+ self.tknval2.return_value = None
47
+ self.auth.custom_validators.pre_token.append(self.tknval1)
48
+ self.auth.custom_validators.post_token.append(self.tknval2)
49
+ self.auth.custom_validators.pre_auth.append(self.authval1)
50
+ self.auth.custom_validators.post_auth.append(self.authval2)
51
+
52
+ def test_custom_auth_validators(self):
53
+ self.setup_validators()
54
+
55
+ bearer = BearerToken(self.mock_validator)
56
+ self.auth.create_authorization_response(self.request, bearer)
57
+ self.assertTrue(self.authval1.called)
58
+ self.assertTrue(self.authval2.called)
59
+ self.assertFalse(self.tknval1.called)
60
+ self.assertFalse(self.tknval2.called)
61
+
62
+ def test_custom_token_validators(self):
63
+ self.setup_validators()
64
+
65
+ bearer = BearerToken(self.mock_validator)
66
+ self.auth.create_token_response(self.request, bearer)
67
+ self.assertTrue(self.tknval1.called)
68
+ self.assertTrue(self.tknval2.called)
69
+ self.assertFalse(self.authval1.called)
70
+ self.assertFalse(self.authval2.called)
71
+
72
+ def test_create_authorization_grant(self):
73
+ bearer = BearerToken(self.mock_validator)
74
+ self.request.response_mode = 'query'
75
+ h, b, s = self.auth.create_authorization_response(self.request, bearer)
76
+ grant = dict(Request(h['Location']).uri_query_params)
77
+ self.assertIn('code', grant)
78
+ self.assertTrue(self.mock_validator.validate_redirect_uri.called)
79
+ self.assertTrue(self.mock_validator.validate_response_type.called)
80
+ self.assertTrue(self.mock_validator.validate_scopes.called)
81
+
82
+ def test_create_authorization_grant_no_scopes(self):
83
+ bearer = BearerToken(self.mock_validator)
84
+ self.request.response_mode = 'query'
85
+ self.request.scopes = []
86
+ self.auth.create_authorization_response(self.request, bearer)
87
+
88
+ def test_create_authorization_grant_state(self):
89
+ self.request.state = 'abc'
90
+ self.request.redirect_uri = None
91
+ self.request.response_mode = 'query'
92
+ self.mock_validator.get_default_redirect_uri.return_value = 'https://a.b/cb'
93
+ bearer = BearerToken(self.mock_validator)
94
+ h, b, s = self.auth.create_authorization_response(self.request, bearer)
95
+ grant = dict(Request(h['Location']).uri_query_params)
96
+ self.assertIn('code', grant)
97
+ self.assertIn('state', grant)
98
+ self.assertFalse(self.mock_validator.validate_redirect_uri.called)
99
+ self.assertTrue(self.mock_validator.get_default_redirect_uri.called)
100
+ self.assertTrue(self.mock_validator.validate_response_type.called)
101
+ self.assertTrue(self.mock_validator.validate_scopes.called)
102
+
103
+ @mock.patch('oauthlib.common.generate_token')
104
+ def test_create_authorization_response(self, generate_token):
105
+ generate_token.return_value = 'abc'
106
+ bearer = BearerToken(self.mock_validator)
107
+ self.request.response_mode = 'query'
108
+ h, b, s = self.auth.create_authorization_response(self.request, bearer)
109
+ self.assertURLEqual(h['Location'], 'https://a.b/cb?code=abc')
110
+ self.request.response_mode = 'fragment'
111
+ h, b, s = self.auth.create_authorization_response(self.request, bearer)
112
+ self.assertURLEqual(h['Location'], 'https://a.b/cb#code=abc')
113
+
114
+ def test_create_token_response(self):
115
+ bearer = BearerToken(self.mock_validator)
116
+
117
+ h, token, s = self.auth.create_token_response(self.request, bearer)
118
+ token = json.loads(token)
119
+ self.assertEqual(self.mock_validator.save_token.call_count, 1)
120
+ self.assertIn('access_token', token)
121
+ self.assertIn('refresh_token', token)
122
+ self.assertIn('expires_in', token)
123
+ self.assertIn('scope', token)
124
+ self.assertTrue(self.mock_validator.client_authentication_required.called)
125
+ self.assertTrue(self.mock_validator.authenticate_client.called)
126
+ self.assertTrue(self.mock_validator.validate_code.called)
127
+ self.assertTrue(self.mock_validator.confirm_redirect_uri.called)
128
+ self.assertTrue(self.mock_validator.validate_grant_type.called)
129
+ self.assertTrue(self.mock_validator.invalidate_authorization_code.called)
130
+
131
+ def test_create_token_response_without_refresh_token(self):
132
+ self.auth.refresh_token = False # Not to issue refresh token.
133
+
134
+ bearer = BearerToken(self.mock_validator)
135
+ h, token, s = self.auth.create_token_response(self.request, bearer)
136
+ token = json.loads(token)
137
+ self.assertEqual(self.mock_validator.save_token.call_count, 1)
138
+ self.assertIn('access_token', token)
139
+ self.assertNotIn('refresh_token', token)
140
+ self.assertIn('expires_in', token)
141
+ self.assertIn('scope', token)
142
+ self.assertTrue(self.mock_validator.client_authentication_required.called)
143
+ self.assertTrue(self.mock_validator.authenticate_client.called)
144
+ self.assertTrue(self.mock_validator.validate_code.called)
145
+ self.assertTrue(self.mock_validator.confirm_redirect_uri.called)
146
+ self.assertTrue(self.mock_validator.validate_grant_type.called)
147
+ self.assertTrue(self.mock_validator.invalidate_authorization_code.called)
148
+
149
+ def test_invalid_request(self):
150
+ del self.request.code
151
+ self.assertRaises(errors.InvalidRequestError, self.auth.validate_token_request,
152
+ self.request)
153
+
154
+ def test_invalid_request_duplicates(self):
155
+ request = mock.MagicMock(wraps=self.request)
156
+ request.grant_type = 'authorization_code'
157
+ request.duplicate_params = ['client_id']
158
+ self.assertRaises(errors.InvalidRequestError, self.auth.validate_token_request,
159
+ request)
160
+
161
+ def test_authentication_required(self):
162
+ """
163
+ ensure client_authentication_required() is properly called
164
+ """
165
+ self.auth.validate_token_request(self.request)
166
+ self.mock_validator.client_authentication_required.assert_called_once_with(self.request)
167
+
168
+ def test_authenticate_client(self):
169
+ self.mock_validator.authenticate_client.side_effect = None
170
+ self.mock_validator.authenticate_client.return_value = False
171
+ self.assertRaises(errors.InvalidClientError, self.auth.validate_token_request,
172
+ self.request)
173
+
174
+ def test_client_id_missing(self):
175
+ self.mock_validator.authenticate_client.side_effect = None
176
+ request = mock.MagicMock(wraps=self.request)
177
+ request.grant_type = 'authorization_code'
178
+ del request.client.client_id
179
+ self.assertRaises(NotImplementedError, self.auth.validate_token_request,
180
+ request)
181
+
182
+ def test_invalid_grant(self):
183
+ self.request.client = 'batman'
184
+ self.mock_validator.authenticate_client = self.set_client
185
+ self.mock_validator.validate_code.return_value = False
186
+ self.assertRaises(errors.InvalidGrantError,
187
+ self.auth.validate_token_request, self.request)
188
+
189
+ def test_invalid_grant_type(self):
190
+ self.request.grant_type = 'foo'
191
+ self.assertRaises(errors.UnsupportedGrantTypeError,
192
+ self.auth.validate_token_request, self.request)
193
+
194
+ def test_authenticate_client_id(self):
195
+ self.mock_validator.client_authentication_required.return_value = False
196
+ self.mock_validator.authenticate_client_id.return_value = False
197
+ self.request.state = 'abc'
198
+ self.assertRaises(errors.InvalidClientError,
199
+ self.auth.validate_token_request, self.request)
200
+
201
+ def test_invalid_redirect_uri(self):
202
+ self.mock_validator.confirm_redirect_uri.return_value = False
203
+ self.assertRaises(errors.MismatchingRedirectURIError,
204
+ self.auth.validate_token_request, self.request)
205
+
206
+ # PKCE validate_authorization_request
207
+ def test_pkce_challenge_missing(self):
208
+ self.mock_validator.is_pkce_required.return_value = True
209
+ self.assertRaises(errors.MissingCodeChallengeError,
210
+ self.auth.validate_authorization_request, self.request)
211
+
212
+ def test_pkce_default_method(self):
213
+ for required in [True, False]:
214
+ self.mock_validator.is_pkce_required.return_value = required
215
+ self.request.code_challenge = "present"
216
+ _, ri = self.auth.validate_authorization_request(self.request)
217
+ self.assertIn("code_challenge", ri)
218
+ self.assertIn("code_challenge_method", ri)
219
+ self.assertEqual(ri["code_challenge"], "present")
220
+ self.assertEqual(ri["code_challenge_method"], "plain")
221
+
222
+ def test_pkce_wrong_method(self):
223
+ for required in [True, False]:
224
+ self.mock_validator.is_pkce_required.return_value = required
225
+ self.request.code_challenge = "present"
226
+ self.request.code_challenge_method = "foobar"
227
+ self.assertRaises(errors.UnsupportedCodeChallengeMethodError,
228
+ self.auth.validate_authorization_request, self.request)
229
+
230
+ # PKCE validate_token_request
231
+ def test_pkce_verifier_missing(self):
232
+ self.mock_validator.is_pkce_required.return_value = True
233
+ self.assertRaises(errors.MissingCodeVerifierError,
234
+ self.auth.validate_token_request, self.request)
235
+
236
+ # PKCE validate_token_request
237
+ def test_pkce_required_verifier_missing_challenge_missing(self):
238
+ self.mock_validator.is_pkce_required.return_value = True
239
+ self.request.code_verifier = None
240
+ self.mock_validator.get_code_challenge.return_value = None
241
+ self.assertRaises(errors.MissingCodeVerifierError,
242
+ self.auth.validate_token_request, self.request)
243
+
244
+ def test_pkce_required_verifier_missing_challenge_valid(self):
245
+ self.mock_validator.is_pkce_required.return_value = True
246
+ self.request.code_verifier = None
247
+ self.mock_validator.get_code_challenge.return_value = "foo"
248
+ self.assertRaises(errors.MissingCodeVerifierError,
249
+ self.auth.validate_token_request, self.request)
250
+
251
+ def test_pkce_required_verifier_valid_challenge_missing(self):
252
+ self.mock_validator.is_pkce_required.return_value = True
253
+ self.request.code_verifier = "foobar"
254
+ self.mock_validator.get_code_challenge.return_value = None
255
+ self.assertRaises(errors.InvalidGrantError,
256
+ self.auth.validate_token_request, self.request)
257
+
258
+ def test_pkce_required_verifier_valid_challenge_valid_method_valid(self):
259
+ self.mock_validator.is_pkce_required.return_value = True
260
+ self.request.code_verifier = "foobar"
261
+ self.mock_validator.get_code_challenge.return_value = "foobar"
262
+ self.mock_validator.get_code_challenge_method.return_value = "plain"
263
+ self.auth.validate_token_request(self.request)
264
+
265
+ def test_pkce_required_verifier_invalid_challenge_valid_method_valid(self):
266
+ self.mock_validator.is_pkce_required.return_value = True
267
+ self.request.code_verifier = "foobar"
268
+ self.mock_validator.get_code_challenge.return_value = "raboof"
269
+ self.mock_validator.get_code_challenge_method.return_value = "plain"
270
+ self.assertRaises(errors.InvalidGrantError,
271
+ self.auth.validate_token_request, self.request)
272
+
273
+ def test_pkce_required_verifier_valid_challenge_valid_method_wrong(self):
274
+ self.mock_validator.is_pkce_required.return_value = True
275
+ self.request.code_verifier = "present"
276
+ self.mock_validator.get_code_challenge.return_value = "foobar"
277
+ self.mock_validator.get_code_challenge_method.return_value = "cryptic_method"
278
+ self.assertRaises(errors.ServerError,
279
+ self.auth.validate_token_request, self.request)
280
+
281
+ def test_pkce_verifier_valid_challenge_valid_method_missing(self):
282
+ self.mock_validator.is_pkce_required.return_value = True
283
+ self.request.code_verifier = "present"
284
+ self.mock_validator.get_code_challenge.return_value = "foobar"
285
+ self.mock_validator.get_code_challenge_method.return_value = None
286
+ self.assertRaises(errors.InvalidGrantError,
287
+ self.auth.validate_token_request, self.request)
288
+
289
+ def test_pkce_optional_verifier_valid_challenge_missing(self):
290
+ self.mock_validator.is_pkce_required.return_value = False
291
+ self.request.code_verifier = "present"
292
+ self.mock_validator.get_code_challenge.return_value = None
293
+ self.auth.validate_token_request(self.request)
294
+
295
+ def test_pkce_optional_verifier_missing_challenge_valid(self):
296
+ self.mock_validator.is_pkce_required.return_value = False
297
+ self.request.code_verifier = None
298
+ self.mock_validator.get_code_challenge.return_value = "foobar"
299
+ self.assertRaises(errors.MissingCodeVerifierError,
300
+ self.auth.validate_token_request, self.request)
301
+
302
+ # PKCE functions
303
+ def test_wrong_code_challenge_method_plain(self):
304
+ self.assertFalse(authorization_code.code_challenge_method_plain("foo", "bar"))
305
+
306
+ def test_correct_code_challenge_method_plain(self):
307
+ self.assertTrue(authorization_code.code_challenge_method_plain("foo", "foo"))
308
+
309
+ def test_wrong_code_challenge_method_s256(self):
310
+ self.assertFalse(authorization_code.code_challenge_method_s256("foo", "bar"))
311
+
312
+ def test_correct_code_challenge_method_s256(self):
313
+ # "abcd" as verifier gives a '+' to base64
314
+ self.assertTrue(
315
+ authorization_code.code_challenge_method_s256("abcd",
316
+ "iNQmb9TmM40TuEX88olXnSCciXgjuSF9o-Fhk28DFYk")
317
+ )
318
+ # "/" as verifier gives a '/' and '+' to base64
319
+ self.assertTrue(
320
+ authorization_code.code_challenge_method_s256("/",
321
+ "il7asoJjJEMhngUeSt4tHVu8Zxx4EFG_FDeJfL3-oPE")
322
+ )
323
+ # Example from PKCE RFCE
324
+ self.assertTrue(
325
+ authorization_code.code_challenge_method_s256("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",
326
+ "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM")
327
+ )
328
+
329
+ def test_code_modifier_called(self):
330
+ bearer = BearerToken(self.mock_validator)
331
+ code_modifier = mock.MagicMock(wraps=lambda grant, *a: grant)
332
+ self.auth.register_code_modifier(code_modifier)
333
+ self.auth.create_authorization_response(self.request, bearer)
334
+ code_modifier.assert_called_once()
335
+
336
+ def test_hybrid_token_save(self):
337
+ bearer = BearerToken(self.mock_validator)
338
+ self.auth.register_code_modifier(
339
+ lambda grant, *a: dict(list(grant.items()) + [('access_token', 1)])
340
+ )
341
+ self.auth.create_authorization_response(self.request, bearer)
342
+ self.mock_validator.save_token.assert_called_once()
343
+
344
+ # CORS
345
+
346
+ def test_create_cors_headers(self):
347
+ bearer = BearerToken(self.mock_validator)
348
+ self.request.headers['origin'] = 'https://foo.bar'
349
+ self.mock_validator.is_origin_allowed.return_value = True
350
+
351
+ headers = self.auth.create_token_response(self.request, bearer)[0]
352
+ self.assertEqual(
353
+ headers['Access-Control-Allow-Origin'], 'https://foo.bar'
354
+ )
355
+ self.mock_validator.is_origin_allowed.assert_called_once_with(
356
+ 'abcdef', 'https://foo.bar', self.request
357
+ )
358
+
359
+ def test_create_cors_headers_no_origin(self):
360
+ bearer = BearerToken(self.mock_validator)
361
+ headers = self.auth.create_token_response(self.request, bearer)[0]
362
+ self.assertNotIn('Access-Control-Allow-Origin', headers)
363
+ self.mock_validator.is_origin_allowed.assert_not_called()
364
+
365
+ def test_create_cors_headers_insecure_origin(self):
366
+ bearer = BearerToken(self.mock_validator)
367
+ self.request.headers['origin'] = 'http://foo.bar'
368
+
369
+ headers = self.auth.create_token_response(self.request, bearer)[0]
370
+ self.assertNotIn('Access-Control-Allow-Origin', headers)
371
+ self.mock_validator.is_origin_allowed.assert_not_called()
372
+
373
+ def test_create_cors_headers_invalid_origin(self):
374
+ bearer = BearerToken(self.mock_validator)
375
+ self.request.headers['origin'] = 'https://foo.bar'
376
+ self.mock_validator.is_origin_allowed.return_value = False
377
+
378
+ headers = self.auth.create_token_response(self.request, bearer)[0]
379
+ self.assertNotIn('Access-Control-Allow-Origin', headers)
380
+ self.mock_validator.is_origin_allowed.assert_called_once_with(
381
+ 'abcdef', 'https://foo.bar', self.request
382
+ )
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/grant_types/test_client_credentials.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import json
3
+ from unittest import mock
4
+
5
+ from oauthlib.common import Request
6
+ from oauthlib.oauth2.rfc6749.grant_types import ClientCredentialsGrant
7
+ from oauthlib.oauth2.rfc6749.tokens import BearerToken
8
+
9
+ from tests.unittest import TestCase
10
+
11
+
12
+ class ClientCredentialsGrantTest(TestCase):
13
+
14
+ def setUp(self):
15
+ mock_client = mock.MagicMock()
16
+ mock_client.user.return_value = 'mocked user'
17
+ self.request = Request('http://a.b/path')
18
+ self.request.grant_type = 'client_credentials'
19
+ self.request.client = mock_client
20
+ self.request.scopes = ('mocked', 'scopes')
21
+ self.mock_validator = mock.MagicMock()
22
+ self.auth = ClientCredentialsGrant(
23
+ request_validator=self.mock_validator)
24
+
25
+ def test_custom_auth_validators_unsupported(self):
26
+ authval1, authval2 = mock.Mock(), mock.Mock()
27
+ expected = ('ClientCredentialsGrant does not support authorization '
28
+ 'validators. Use token validators instead.')
29
+ with self.assertRaises(ValueError) as caught:
30
+ ClientCredentialsGrant(self.mock_validator, pre_auth=[authval1])
31
+ self.assertEqual(caught.exception.args[0], expected)
32
+ with self.assertRaises(ValueError) as caught:
33
+ ClientCredentialsGrant(self.mock_validator, post_auth=[authval2])
34
+ self.assertEqual(caught.exception.args[0], expected)
35
+ with self.assertRaises(AttributeError):
36
+ self.auth.custom_validators.pre_auth.append(authval1)
37
+ with self.assertRaises(AttributeError):
38
+ self.auth.custom_validators.pre_auth.append(authval2)
39
+
40
+ def test_custom_token_validators(self):
41
+ tknval1, tknval2 = mock.Mock(), mock.Mock()
42
+ self.auth.custom_validators.pre_token.append(tknval1)
43
+ self.auth.custom_validators.post_token.append(tknval2)
44
+
45
+ bearer = BearerToken(self.mock_validator)
46
+ self.auth.create_token_response(self.request, bearer)
47
+ self.assertTrue(tknval1.called)
48
+ self.assertTrue(tknval2.called)
49
+
50
+ def test_create_token_response(self):
51
+ bearer = BearerToken(self.mock_validator)
52
+ headers, body, status_code = self.auth.create_token_response(
53
+ self.request, bearer)
54
+ token = json.loads(body)
55
+ self.assertEqual(self.mock_validator.save_token.call_count, 1)
56
+ self.assertIn('access_token', token)
57
+ self.assertIn('token_type', token)
58
+ self.assertIn('expires_in', token)
59
+ self.assertIn('Content-Type', headers)
60
+ self.assertEqual(headers['Content-Type'], 'application/json')
61
+
62
+ def test_error_response(self):
63
+ bearer = BearerToken(self.mock_validator)
64
+ self.mock_validator.authenticate_client.return_value = False
65
+ headers, body, status_code = self.auth.create_token_response(
66
+ self.request, bearer)
67
+ self.assertEqual(self.mock_validator.save_token.call_count, 0)
68
+ error_msg = json.loads(body)
69
+ self.assertIn('error', error_msg)
70
+ self.assertEqual(error_msg['error'], 'invalid_client')
71
+ self.assertIn('Content-Type', headers)
72
+ self.assertEqual(headers['Content-Type'], 'application/json')
73
+
74
+ def test_validate_token_response(self):
75
+ # wrong grant type, scope
76
+ pass
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/grant_types/test_implicit.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from unittest import mock
3
+
4
+ from oauthlib.common import Request
5
+ from oauthlib.oauth2.rfc6749.grant_types import ImplicitGrant
6
+ from oauthlib.oauth2.rfc6749.tokens import BearerToken
7
+
8
+ from tests.unittest import TestCase
9
+
10
+
11
+ class ImplicitGrantTest(TestCase):
12
+
13
+ def setUp(self):
14
+ mock_client = mock.MagicMock()
15
+ mock_client.user.return_value = 'mocked user'
16
+ self.request = Request('http://a.b/path')
17
+ self.request.scopes = ('hello', 'world')
18
+ self.request.client = mock_client
19
+ self.request.client_id = 'abcdef'
20
+ self.request.response_type = 'token'
21
+ self.request.state = 'xyz'
22
+ self.request.redirect_uri = 'https://b.c/p'
23
+
24
+ self.mock_validator = mock.MagicMock()
25
+ self.auth = ImplicitGrant(request_validator=self.mock_validator)
26
+
27
+ @mock.patch('oauthlib.common.generate_token')
28
+ def test_create_token_response(self, generate_token):
29
+ generate_token.return_value = '1234'
30
+ bearer = BearerToken(self.mock_validator, expires_in=1800)
31
+ h, b, s = self.auth.create_token_response(self.request, bearer)
32
+ correct_uri = 'https://b.c/p#access_token=1234&token_type=Bearer&expires_in=1800&state=xyz&scope=hello+world'
33
+ self.assertEqual(s, 302)
34
+ self.assertURLEqual(h['Location'], correct_uri, parse_fragment=True)
35
+ self.assertEqual(self.mock_validator.save_token.call_count, 1)
36
+
37
+ correct_uri = 'https://b.c/p?access_token=1234&token_type=Bearer&expires_in=1800&state=xyz&scope=hello+world'
38
+ self.request.response_mode = 'query'
39
+ h, b, s = self.auth.create_token_response(self.request, bearer)
40
+ self.assertURLEqual(h['Location'], correct_uri)
41
+
42
+ def test_custom_validators(self):
43
+ self.authval1, self.authval2 = mock.Mock(), mock.Mock()
44
+ self.tknval1, self.tknval2 = mock.Mock(), mock.Mock()
45
+ for val in (self.authval1, self.authval2):
46
+ val.return_value = {}
47
+ for val in (self.tknval1, self.tknval2):
48
+ val.return_value = None
49
+ self.auth.custom_validators.pre_token.append(self.tknval1)
50
+ self.auth.custom_validators.post_token.append(self.tknval2)
51
+ self.auth.custom_validators.pre_auth.append(self.authval1)
52
+ self.auth.custom_validators.post_auth.append(self.authval2)
53
+
54
+ bearer = BearerToken(self.mock_validator)
55
+ self.auth.create_token_response(self.request, bearer)
56
+ self.assertTrue(self.tknval1.called)
57
+ self.assertTrue(self.tknval2.called)
58
+ self.assertTrue(self.authval1.called)
59
+ self.assertTrue(self.authval2.called)
60
+
61
+ def test_error_response(self):
62
+ pass
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/grant_types/test_refresh_token.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import json
3
+ from unittest import mock
4
+
5
+ from oauthlib.common import Request
6
+ from oauthlib.oauth2.rfc6749 import errors
7
+ from oauthlib.oauth2.rfc6749.grant_types import RefreshTokenGrant
8
+ from oauthlib.oauth2.rfc6749.tokens import BearerToken
9
+
10
+ from tests.unittest import TestCase
11
+
12
+
13
+ class RefreshTokenGrantTest(TestCase):
14
+
15
+ def setUp(self):
16
+ mock_client = mock.MagicMock()
17
+ mock_client.user.return_value = 'mocked user'
18
+ self.request = Request('http://a.b/path')
19
+ self.request.grant_type = 'refresh_token'
20
+ self.request.refresh_token = 'lsdkfhj230'
21
+ self.request.client_id = 'abcdef'
22
+ self.request.client = mock_client
23
+ self.request.scope = 'foo'
24
+ self.mock_validator = mock.MagicMock()
25
+ self.auth = RefreshTokenGrant(
26
+ request_validator=self.mock_validator)
27
+
28
+ def test_create_token_response(self):
29
+ self.mock_validator.get_original_scopes.return_value = ['foo', 'bar']
30
+ bearer = BearerToken(self.mock_validator)
31
+ headers, body, status_code = self.auth.create_token_response(
32
+ self.request, bearer)
33
+ token = json.loads(body)
34
+ self.assertEqual(self.mock_validator.save_token.call_count, 1)
35
+ self.assertIn('access_token', token)
36
+ self.assertIn('token_type', token)
37
+ self.assertIn('expires_in', token)
38
+ self.assertEqual(token['scope'], 'foo')
39
+
40
+ def test_custom_auth_validators_unsupported(self):
41
+ authval1, authval2 = mock.Mock(), mock.Mock()
42
+ expected = ('RefreshTokenGrant does not support authorization '
43
+ 'validators. Use token validators instead.')
44
+ with self.assertRaises(ValueError) as caught:
45
+ RefreshTokenGrant(self.mock_validator, pre_auth=[authval1])
46
+ self.assertEqual(caught.exception.args[0], expected)
47
+ with self.assertRaises(ValueError) as caught:
48
+ RefreshTokenGrant(self.mock_validator, post_auth=[authval2])
49
+ self.assertEqual(caught.exception.args[0], expected)
50
+ with self.assertRaises(AttributeError):
51
+ self.auth.custom_validators.pre_auth.append(authval1)
52
+ with self.assertRaises(AttributeError):
53
+ self.auth.custom_validators.pre_auth.append(authval2)
54
+
55
+ def test_custom_token_validators(self):
56
+ tknval1, tknval2 = mock.Mock(), mock.Mock()
57
+ self.auth.custom_validators.pre_token.append(tknval1)
58
+ self.auth.custom_validators.post_token.append(tknval2)
59
+
60
+ bearer = BearerToken(self.mock_validator)
61
+ self.auth.create_token_response(self.request, bearer)
62
+ self.assertTrue(tknval1.called)
63
+ self.assertTrue(tknval2.called)
64
+
65
+ def test_create_token_inherit_scope(self):
66
+ self.request.scope = None
67
+ self.mock_validator.get_original_scopes.return_value = ['foo', 'bar']
68
+ bearer = BearerToken(self.mock_validator)
69
+ headers, body, status_code = self.auth.create_token_response(
70
+ self.request, bearer)
71
+ token = json.loads(body)
72
+ self.assertEqual(self.mock_validator.save_token.call_count, 1)
73
+ self.assertIn('access_token', token)
74
+ self.assertIn('token_type', token)
75
+ self.assertIn('expires_in', token)
76
+ self.assertEqual(token['scope'], 'foo bar')
77
+
78
+ def test_create_token_within_original_scope(self):
79
+ self.mock_validator.get_original_scopes.return_value = ['baz']
80
+ self.mock_validator.is_within_original_scope.return_value = True
81
+ bearer = BearerToken(self.mock_validator)
82
+ headers, body, status_code = self.auth.create_token_response(
83
+ self.request, bearer)
84
+ token = json.loads(body)
85
+ self.assertEqual(self.mock_validator.save_token.call_count, 1)
86
+ self.assertIn('access_token', token)
87
+ self.assertIn('token_type', token)
88
+ self.assertIn('expires_in', token)
89
+ self.assertEqual(token['scope'], 'foo')
90
+
91
+ def test_invalid_scope(self):
92
+ self.mock_validator.get_original_scopes.return_value = ['baz']
93
+ self.mock_validator.is_within_original_scope.return_value = False
94
+ bearer = BearerToken(self.mock_validator)
95
+ headers, body, status_code = self.auth.create_token_response(
96
+ self.request, bearer)
97
+ token = json.loads(body)
98
+ self.assertEqual(self.mock_validator.save_token.call_count, 0)
99
+ self.assertEqual(token['error'], 'invalid_scope')
100
+ self.assertEqual(status_code, 400)
101
+
102
+ def test_invalid_token(self):
103
+ self.mock_validator.validate_refresh_token.return_value = False
104
+ bearer = BearerToken(self.mock_validator)
105
+ headers, body, status_code = self.auth.create_token_response(
106
+ self.request, bearer)
107
+ token = json.loads(body)
108
+ self.assertEqual(self.mock_validator.save_token.call_count, 0)
109
+ self.assertEqual(token['error'], 'invalid_grant')
110
+ self.assertEqual(status_code, 400)
111
+
112
+ def test_invalid_client(self):
113
+ self.mock_validator.authenticate_client.return_value = False
114
+ bearer = BearerToken(self.mock_validator)
115
+ headers, body, status_code = self.auth.create_token_response(
116
+ self.request, bearer)
117
+ token = json.loads(body)
118
+ self.assertEqual(self.mock_validator.save_token.call_count, 0)
119
+ self.assertEqual(token['error'], 'invalid_client')
120
+ self.assertEqual(status_code, 401)
121
+
122
+ def test_authentication_required(self):
123
+ """
124
+ ensure client_authentication_required() is properly called
125
+ """
126
+ self.mock_validator.authenticate_client.return_value = False
127
+ self.mock_validator.authenticate_client_id.return_value = False
128
+ self.request.code = 'waffles'
129
+ self.assertRaises(errors.InvalidClientError, self.auth.validate_token_request,
130
+ self.request)
131
+ self.mock_validator.client_authentication_required.assert_called_once_with(self.request)
132
+
133
+
134
+ def test_authentication_required_populate_client_id(self):
135
+ """
136
+ Make sure that request.client_id is populated from
137
+ request.client.client_id if None.
138
+
139
+ """
140
+ self.mock_validator.client_authentication_required.return_value = True
141
+ self.mock_validator.authenticate_client.return_value = True
142
+ # self.mock_validator.authenticate_client_id.return_value = False
143
+ # self.request.code = 'waffles'
144
+ self.request.client_id = None
145
+ self.request.client.client_id = 'foobar'
146
+ self.auth.validate_token_request(self.request)
147
+ self.request.client_id = 'foobar'
148
+
149
+ def test_invalid_grant_type(self):
150
+ self.request.grant_type = 'wrong_type'
151
+ self.assertRaises(errors.UnsupportedGrantTypeError,
152
+ self.auth.validate_token_request, self.request)
153
+
154
+ def test_authenticate_client_id(self):
155
+ self.mock_validator.client_authentication_required.return_value = False
156
+ self.request.refresh_token = mock.MagicMock()
157
+ self.mock_validator.authenticate_client_id.return_value = False
158
+ self.assertRaises(errors.InvalidClientError,
159
+ self.auth.validate_token_request, self.request)
160
+
161
+ def test_invalid_refresh_token(self):
162
+ # invalid refresh token
163
+ self.mock_validator.authenticate_client_id.return_value = True
164
+ self.mock_validator.validate_refresh_token.return_value = False
165
+ self.assertRaises(errors.InvalidGrantError,
166
+ self.auth.validate_token_request, self.request)
167
+ # no token provided
168
+ del self.request.refresh_token
169
+ self.assertRaises(errors.InvalidRequestError,
170
+ self.auth.validate_token_request, self.request)
171
+
172
+ def test_invalid_scope_original_scopes_empty(self):
173
+ self.mock_validator.validate_refresh_token.return_value = True
174
+ self.mock_validator.is_within_original_scope.return_value = False
175
+ self.assertRaises(errors.InvalidScopeError,
176
+ self.auth.validate_token_request, self.request)
177
+
178
+ def test_valid_token_request(self):
179
+ self.request.scope = 'foo bar'
180
+ self.mock_validator.get_original_scopes = mock.Mock()
181
+ self.mock_validator.get_original_scopes.return_value = 'foo bar baz'
182
+ self.auth.validate_token_request(self.request)
183
+ self.assertEqual(self.request.scopes, self.request.scope.split())
184
+ # all ok but without request.scope
185
+ del self.request.scope
186
+ self.auth.validate_token_request(self.request)
187
+ self.assertEqual(self.request.scopes, 'foo bar baz'.split())
188
+
189
+ # CORS
190
+
191
+ def test_create_cors_headers(self):
192
+ bearer = BearerToken(self.mock_validator)
193
+ self.request.headers['origin'] = 'https://foo.bar'
194
+ self.mock_validator.is_origin_allowed.return_value = True
195
+
196
+ headers = self.auth.create_token_response(self.request, bearer)[0]
197
+ self.assertEqual(
198
+ headers['Access-Control-Allow-Origin'], 'https://foo.bar'
199
+ )
200
+ self.mock_validator.is_origin_allowed.assert_called_once_with(
201
+ 'abcdef', 'https://foo.bar', self.request
202
+ )
203
+
204
+ def test_create_cors_headers_no_origin(self):
205
+ bearer = BearerToken(self.mock_validator)
206
+ headers = self.auth.create_token_response(self.request, bearer)[0]
207
+ self.assertNotIn('Access-Control-Allow-Origin', headers)
208
+ self.mock_validator.is_origin_allowed.assert_not_called()
209
+
210
+ def test_create_cors_headers_insecure_origin(self):
211
+ bearer = BearerToken(self.mock_validator)
212
+ self.request.headers['origin'] = 'http://foo.bar'
213
+
214
+ headers = self.auth.create_token_response(self.request, bearer)[0]
215
+ self.assertNotIn('Access-Control-Allow-Origin', headers)
216
+ self.mock_validator.is_origin_allowed.assert_not_called()
217
+
218
+ def test_create_cors_headers_invalid_origin(self):
219
+ bearer = BearerToken(self.mock_validator)
220
+ self.request.headers['origin'] = 'https://foo.bar'
221
+ self.mock_validator.is_origin_allowed.return_value = False
222
+
223
+ headers = self.auth.create_token_response(self.request, bearer)[0]
224
+ self.assertNotIn('Access-Control-Allow-Origin', headers)
225
+ self.mock_validator.is_origin_allowed.assert_called_once_with(
226
+ 'abcdef', 'https://foo.bar', self.request
227
+ )
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/grant_types/test_resource_owner_password.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import json
3
+ from unittest import mock
4
+
5
+ from oauthlib.common import Request
6
+ from oauthlib.oauth2.rfc6749 import errors
7
+ from oauthlib.oauth2.rfc6749.grant_types import (
8
+ ResourceOwnerPasswordCredentialsGrant,
9
+ )
10
+ from oauthlib.oauth2.rfc6749.tokens import BearerToken
11
+
12
+ from tests.unittest import TestCase
13
+
14
+
15
+ class ResourceOwnerPasswordCredentialsGrantTest(TestCase):
16
+
17
+ def setUp(self):
18
+ mock_client = mock.MagicMock()
19
+ mock_client.user.return_value = 'mocked user'
20
+ self.request = Request('http://a.b/path')
21
+ self.request.grant_type = 'password'
22
+ self.request.username = 'john'
23
+ self.request.password = 'doe'
24
+ self.request.client = mock_client
25
+ self.request.scopes = ('mocked', 'scopes')
26
+ self.mock_validator = mock.MagicMock()
27
+ self.auth = ResourceOwnerPasswordCredentialsGrant(
28
+ request_validator=self.mock_validator)
29
+
30
+ def set_client(self, request, *args, **kwargs):
31
+ request.client = mock.MagicMock()
32
+ request.client.client_id = 'mocked'
33
+ return True
34
+
35
+ def test_create_token_response(self):
36
+ bearer = BearerToken(self.mock_validator)
37
+ headers, body, status_code = self.auth.create_token_response(
38
+ self.request, bearer)
39
+ token = json.loads(body)
40
+ self.assertEqual(self.mock_validator.save_token.call_count, 1)
41
+ self.assertIn('access_token', token)
42
+ self.assertIn('token_type', token)
43
+ self.assertIn('expires_in', token)
44
+ self.assertIn('refresh_token', token)
45
+ # ensure client_authentication_required() is properly called
46
+ self.mock_validator.client_authentication_required.assert_called_once_with(self.request)
47
+ # fail client authentication
48
+ self.mock_validator.reset_mock()
49
+ self.mock_validator.validate_user.return_value = True
50
+ self.mock_validator.authenticate_client.return_value = False
51
+ status_code = self.auth.create_token_response(self.request, bearer)[2]
52
+ self.assertEqual(status_code, 401)
53
+ self.assertEqual(self.mock_validator.save_token.call_count, 0)
54
+
55
+ # mock client_authentication_required() returning False then fail
56
+ self.mock_validator.reset_mock()
57
+ self.mock_validator.client_authentication_required.return_value = False
58
+ self.mock_validator.authenticate_client_id.return_value = False
59
+ status_code = self.auth.create_token_response(self.request, bearer)[2]
60
+ self.assertEqual(status_code, 401)
61
+ self.assertEqual(self.mock_validator.save_token.call_count, 0)
62
+
63
+ def test_create_token_response_without_refresh_token(self):
64
+ # self.auth.refresh_token = False so we don't generate a refresh token
65
+ self.auth = ResourceOwnerPasswordCredentialsGrant(
66
+ request_validator=self.mock_validator, refresh_token=False)
67
+ bearer = BearerToken(self.mock_validator)
68
+ headers, body, status_code = self.auth.create_token_response(
69
+ self.request, bearer)
70
+ token = json.loads(body)
71
+ self.assertEqual(self.mock_validator.save_token.call_count, 1)
72
+ self.assertIn('access_token', token)
73
+ self.assertIn('token_type', token)
74
+ self.assertIn('expires_in', token)
75
+ # ensure no refresh token is generated
76
+ self.assertNotIn('refresh_token', token)
77
+ # ensure client_authentication_required() is properly called
78
+ self.mock_validator.client_authentication_required.assert_called_once_with(self.request)
79
+ # fail client authentication
80
+ self.mock_validator.reset_mock()
81
+ self.mock_validator.validate_user.return_value = True
82
+ self.mock_validator.authenticate_client.return_value = False
83
+ status_code = self.auth.create_token_response(self.request, bearer)[2]
84
+ self.assertEqual(status_code, 401)
85
+ self.assertEqual(self.mock_validator.save_token.call_count, 0)
86
+ # mock client_authentication_required() returning False then fail
87
+ self.mock_validator.reset_mock()
88
+ self.mock_validator.client_authentication_required.return_value = False
89
+ self.mock_validator.authenticate_client_id.return_value = False
90
+ status_code = self.auth.create_token_response(self.request, bearer)[2]
91
+ self.assertEqual(status_code, 401)
92
+ self.assertEqual(self.mock_validator.save_token.call_count, 0)
93
+
94
+ def test_custom_auth_validators_unsupported(self):
95
+ authval1, authval2 = mock.Mock(), mock.Mock()
96
+ expected = ('ResourceOwnerPasswordCredentialsGrant does not '
97
+ 'support authorization validators. Use token '
98
+ 'validators instead.')
99
+ with self.assertRaises(ValueError) as caught:
100
+ ResourceOwnerPasswordCredentialsGrant(self.mock_validator,
101
+ pre_auth=[authval1])
102
+ self.assertEqual(caught.exception.args[0], expected)
103
+ with self.assertRaises(ValueError) as caught:
104
+ ResourceOwnerPasswordCredentialsGrant(self.mock_validator,
105
+ post_auth=[authval2])
106
+ self.assertEqual(caught.exception.args[0], expected)
107
+ with self.assertRaises(AttributeError):
108
+ self.auth.custom_validators.pre_auth.append(authval1)
109
+ with self.assertRaises(AttributeError):
110
+ self.auth.custom_validators.pre_auth.append(authval2)
111
+
112
+ def test_custom_token_validators(self):
113
+ tknval1, tknval2 = mock.Mock(), mock.Mock()
114
+ self.auth.custom_validators.pre_token.append(tknval1)
115
+ self.auth.custom_validators.post_token.append(tknval2)
116
+
117
+ bearer = BearerToken(self.mock_validator)
118
+ self.auth.create_token_response(self.request, bearer)
119
+ self.assertTrue(tknval1.called)
120
+ self.assertTrue(tknval2.called)
121
+
122
+ def test_error_response(self):
123
+ pass
124
+
125
+ def test_scopes(self):
126
+ pass
127
+
128
+ def test_invalid_request_missing_params(self):
129
+ del self.request.grant_type
130
+ self.assertRaises(errors.InvalidRequestError, self.auth.validate_token_request,
131
+ self.request)
132
+
133
+ def test_invalid_request_duplicates(self):
134
+ request = mock.MagicMock(wraps=self.request)
135
+ request.duplicate_params = ['scope']
136
+ self.assertRaises(errors.InvalidRequestError, self.auth.validate_token_request,
137
+ request)
138
+
139
+ def test_invalid_grant_type(self):
140
+ self.request.grant_type = 'foo'
141
+ self.assertRaises(errors.UnsupportedGrantTypeError,
142
+ self.auth.validate_token_request, self.request)
143
+
144
+ def test_invalid_user(self):
145
+ self.mock_validator.validate_user.return_value = False
146
+ self.assertRaises(errors.InvalidGrantError, self.auth.validate_token_request,
147
+ self.request)
148
+
149
+ def test_client_id_missing(self):
150
+ del self.request.client.client_id
151
+ self.assertRaises(NotImplementedError, self.auth.validate_token_request,
152
+ self.request)
153
+
154
+ def test_valid_token_request(self):
155
+ self.mock_validator.validate_grant_type.return_value = True
156
+ self.auth.validate_token_request(self.request)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/test_parameters.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unittest.mock import patch
2
+
3
+ from oauthlib import signals
4
+ from oauthlib.oauth2.rfc6749.errors import *
5
+ from oauthlib.oauth2.rfc6749.parameters import *
6
+
7
+ from tests.unittest import TestCase
8
+
9
+
10
+ @patch('time.time', new=lambda: 1000)
11
+ class ParameterTests(TestCase):
12
+
13
+ state = 'xyz'
14
+ auth_base = {
15
+ 'uri': 'https://server.example.com/authorize',
16
+ 'client_id': 's6BhdRkqt3',
17
+ 'redirect_uri': 'https://client.example.com/cb',
18
+ 'state': state,
19
+ 'scope': 'photos'
20
+ }
21
+ list_scope = ['list', 'of', 'scopes']
22
+
23
+ auth_grant = {'response_type': 'code'}
24
+ auth_grant_pkce = {'response_type': 'code', 'code_challenge': "code_challenge",
25
+ 'code_challenge_method': 'code_challenge_method'}
26
+ auth_grant_list_scope = {}
27
+ auth_implicit = {'response_type': 'token', 'extra': 'extra'}
28
+ auth_implicit_list_scope = {}
29
+
30
+ def setUp(self):
31
+ self.auth_grant.update(self.auth_base)
32
+ self.auth_grant_pkce.update(self.auth_base)
33
+ self.auth_implicit.update(self.auth_base)
34
+ self.auth_grant_list_scope.update(self.auth_grant)
35
+ self.auth_grant_list_scope['scope'] = self.list_scope
36
+ self.auth_implicit_list_scope.update(self.auth_implicit)
37
+ self.auth_implicit_list_scope['scope'] = self.list_scope
38
+
39
+ auth_base_uri = ('https://server.example.com/authorize?response_type={0}'
40
+ '&client_id=s6BhdRkqt3&redirect_uri=https%3A%2F%2F'
41
+ 'client.example.com%2Fcb&scope={1}&state={2}{3}')
42
+
43
+ auth_base_uri_pkce = ('https://server.example.com/authorize?response_type={0}'
44
+ '&client_id=s6BhdRkqt3&redirect_uri=https%3A%2F%2F'
45
+ 'client.example.com%2Fcb&scope={1}&state={2}{3}&code_challenge={4}'
46
+ '&code_challenge_method={5}')
47
+
48
+ auth_grant_uri = auth_base_uri.format('code', 'photos', state, '')
49
+ auth_grant_uri_pkce = auth_base_uri_pkce.format('code', 'photos', state, '', 'code_challenge',
50
+ 'code_challenge_method')
51
+ auth_grant_uri_list_scope = auth_base_uri.format('code', 'list+of+scopes', state, '')
52
+ auth_implicit_uri = auth_base_uri.format('token', 'photos', state, '&extra=extra')
53
+ auth_implicit_uri_list_scope = auth_base_uri.format('token', 'list+of+scopes', state, '&extra=extra')
54
+
55
+ grant_body = {
56
+ 'grant_type': 'authorization_code',
57
+ 'code': 'SplxlOBeZQQYbYS6WxSbIA',
58
+ 'redirect_uri': 'https://client.example.com/cb'
59
+ }
60
+ grant_body_pkce = {
61
+ 'grant_type': 'authorization_code',
62
+ 'code': 'SplxlOBeZQQYbYS6WxSbIA',
63
+ 'redirect_uri': 'https://client.example.com/cb',
64
+ 'code_verifier': 'code_verifier'
65
+ }
66
+ grant_body_scope = {'scope': 'photos'}
67
+ grant_body_list_scope = {'scope': list_scope}
68
+ auth_grant_body = ('grant_type=authorization_code&'
69
+ 'code=SplxlOBeZQQYbYS6WxSbIA&'
70
+ 'redirect_uri=https%3A%2F%2Fclient.example.com%2Fcb')
71
+ auth_grant_body_pkce = ('grant_type=authorization_code&'
72
+ 'code=SplxlOBeZQQYbYS6WxSbIA&'
73
+ 'redirect_uri=https%3A%2F%2Fclient.example.com%2Fcb'
74
+ '&code_verifier=code_verifier')
75
+ auth_grant_body_scope = auth_grant_body + '&scope=photos'
76
+ auth_grant_body_list_scope = auth_grant_body + '&scope=list+of+scopes'
77
+
78
+ pwd_body = {
79
+ 'grant_type': 'password',
80
+ 'username': 'johndoe',
81
+ 'password': 'A3ddj3w'
82
+ }
83
+ password_body = 'grant_type=password&username=johndoe&password=A3ddj3w'
84
+
85
+ cred_grant = {'grant_type': 'client_credentials'}
86
+ cred_body = 'grant_type=client_credentials'
87
+
88
+ grant_response = 'https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=xyz'
89
+ grant_dict = {'code': 'SplxlOBeZQQYbYS6WxSbIA', 'state': state}
90
+
91
+ error_nocode = 'https://client.example.com/cb?state=xyz'
92
+ error_nostate = 'https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA'
93
+ error_wrongstate = 'https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=abc'
94
+ error_denied = 'https://client.example.com/cb?error=access_denied&state=xyz'
95
+ error_invalid = 'https://client.example.com/cb?error=invalid_request&state=xyz'
96
+
97
+ implicit_base = 'https://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA&scope=abc&'
98
+ implicit_response = implicit_base + 'state={}&token_type=example&expires_in=3600'.format(state)
99
+ implicit_notype = implicit_base + 'state={}&expires_in=3600'.format(state)
100
+ implicit_wrongstate = implicit_base + 'state={}&token_type=exampleexpires_in=3600'.format('invalid')
101
+ implicit_nostate = implicit_base + 'token_type=example&expires_in=3600'
102
+ implicit_notoken = 'https://example.com/cb#state=xyz&token_type=example&expires_in=3600'
103
+
104
+ implicit_dict = {
105
+ 'access_token': '2YotnFZFEjr1zCsicMWpAA',
106
+ 'state': state,
107
+ 'token_type': 'example',
108
+ 'expires_in': 3600,
109
+ 'expires_at': 4600,
110
+ 'scope': ['abc']
111
+ }
112
+
113
+ json_response = ('{ "access_token": "2YotnFZFEjr1zCsicMWpAA",'
114
+ ' "token_type": "example",'
115
+ ' "expires_in": 3600,'
116
+ ' "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",'
117
+ ' "example_parameter": "example_value",'
118
+ ' "scope":"abc def"}')
119
+ json_response_noscope = ('{ "access_token": "2YotnFZFEjr1zCsicMWpAA",'
120
+ ' "token_type": "example",'
121
+ ' "expires_in": 3600,'
122
+ ' "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",'
123
+ ' "example_parameter": "example_value" }')
124
+ json_response_noexpire = ('{ "access_token": "2YotnFZFEjr1zCsicMWpAA",'
125
+ ' "token_type": "example",'
126
+ ' "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",'
127
+ ' "example_parameter": "example_value"}')
128
+ json_response_expirenull = ('{ "access_token": "2YotnFZFEjr1zCsicMWpAA",'
129
+ ' "token_type": "example",'
130
+ ' "expires_in": null,'
131
+ ' "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",'
132
+ ' "example_parameter": "example_value"}')
133
+
134
+ json_custom_error = '{ "error": "incorrect_client_credentials" }'
135
+ json_error = '{ "error": "access_denied" }'
136
+
137
+ json_notoken = ('{ "token_type": "example",'
138
+ ' "expires_in": 3600,'
139
+ ' "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",'
140
+ ' "example_parameter": "example_value" }')
141
+
142
+ json_notype = ('{ "access_token": "2YotnFZFEjr1zCsicMWpAA",'
143
+ ' "expires_in": 3600,'
144
+ ' "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",'
145
+ ' "example_parameter": "example_value" }')
146
+
147
+ json_dict = {
148
+ 'access_token': '2YotnFZFEjr1zCsicMWpAA',
149
+ 'token_type': 'example',
150
+ 'expires_in': 3600,
151
+ 'expires_at': 4600,
152
+ 'refresh_token': 'tGzv3JOkF0XG5Qx2TlKWIA',
153
+ 'example_parameter': 'example_value',
154
+ 'scope': ['abc', 'def']
155
+ }
156
+
157
+ json_noscope_dict = {
158
+ 'access_token': '2YotnFZFEjr1zCsicMWpAA',
159
+ 'token_type': 'example',
160
+ 'expires_in': 3600,
161
+ 'expires_at': 4600,
162
+ 'refresh_token': 'tGzv3JOkF0XG5Qx2TlKWIA',
163
+ 'example_parameter': 'example_value'
164
+ }
165
+
166
+ json_noexpire_dict = {
167
+ 'access_token': '2YotnFZFEjr1zCsicMWpAA',
168
+ 'token_type': 'example',
169
+ 'refresh_token': 'tGzv3JOkF0XG5Qx2TlKWIA',
170
+ 'example_parameter': 'example_value'
171
+ }
172
+
173
+ json_notype_dict = {
174
+ 'access_token': '2YotnFZFEjr1zCsicMWpAA',
175
+ 'expires_in': 3600,
176
+ 'expires_at': 4600,
177
+ 'refresh_token': 'tGzv3JOkF0XG5Qx2TlKWIA',
178
+ 'example_parameter': 'example_value',
179
+ }
180
+
181
+ url_encoded_response = ('access_token=2YotnFZFEjr1zCsicMWpAA'
182
+ '&token_type=example'
183
+ '&expires_in=3600'
184
+ '&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA'
185
+ '&example_parameter=example_value'
186
+ '&scope=abc def')
187
+
188
+ url_encoded_error = 'error=access_denied'
189
+
190
+ url_encoded_notoken = ('token_type=example'
191
+ '&expires_in=3600'
192
+ '&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA'
193
+ '&example_parameter=example_value')
194
+
195
+
196
+ def test_prepare_grant_uri(self):
197
+ """Verify correct authorization URI construction."""
198
+ self.assertURLEqual(prepare_grant_uri(**self.auth_grant), self.auth_grant_uri)
199
+ self.assertURLEqual(prepare_grant_uri(**self.auth_grant_list_scope), self.auth_grant_uri_list_scope)
200
+ self.assertURLEqual(prepare_grant_uri(**self.auth_implicit), self.auth_implicit_uri)
201
+ self.assertURLEqual(prepare_grant_uri(**self.auth_implicit_list_scope), self.auth_implicit_uri_list_scope)
202
+ self.assertURLEqual(prepare_grant_uri(**self.auth_grant_pkce), self.auth_grant_uri_pkce)
203
+
204
+ def test_prepare_token_request(self):
205
+ """Verify correct access token request body construction."""
206
+ self.assertFormBodyEqual(prepare_token_request(**self.grant_body), self.auth_grant_body)
207
+ self.assertFormBodyEqual(prepare_token_request(**self.pwd_body), self.password_body)
208
+ self.assertFormBodyEqual(prepare_token_request(**self.cred_grant), self.cred_body)
209
+ self.assertFormBodyEqual(prepare_token_request(**self.grant_body_pkce), self.auth_grant_body_pkce)
210
+
211
+ def test_grant_response(self):
212
+ """Verify correct parameter parsing and validation for auth code responses."""
213
+ params = parse_authorization_code_response(self.grant_response)
214
+ self.assertEqual(params, self.grant_dict)
215
+ params = parse_authorization_code_response(self.grant_response, state=self.state)
216
+ self.assertEqual(params, self.grant_dict)
217
+
218
+ self.assertRaises(MissingCodeError, parse_authorization_code_response,
219
+ self.error_nocode)
220
+ self.assertRaises(AccessDeniedError, parse_authorization_code_response,
221
+ self.error_denied)
222
+ self.assertRaises(InvalidRequestFatalError, parse_authorization_code_response,
223
+ self.error_invalid)
224
+ self.assertRaises(MismatchingStateError, parse_authorization_code_response,
225
+ self.error_nostate, state=self.state)
226
+ self.assertRaises(MismatchingStateError, parse_authorization_code_response,
227
+ self.error_wrongstate, state=self.state)
228
+
229
+ def test_implicit_token_response(self):
230
+ """Verify correct parameter parsing and validation for implicit responses."""
231
+ self.assertEqual(parse_implicit_response(self.implicit_response),
232
+ self.implicit_dict)
233
+ self.assertRaises(MissingTokenError, parse_implicit_response,
234
+ self.implicit_notoken)
235
+ self.assertRaises(ValueError, parse_implicit_response,
236
+ self.implicit_nostate, state=self.state)
237
+ self.assertRaises(ValueError, parse_implicit_response,
238
+ self.implicit_wrongstate, state=self.state)
239
+
240
+ def test_custom_json_error(self):
241
+ self.assertRaises(CustomOAuth2Error, parse_token_response, self.json_custom_error)
242
+
243
+ def test_json_token_response(self):
244
+ """Verify correct parameter parsing and validation for token responses. """
245
+ self.assertEqual(parse_token_response(self.json_response), self.json_dict)
246
+ self.assertRaises(AccessDeniedError, parse_token_response, self.json_error)
247
+ self.assertRaises(MissingTokenError, parse_token_response, self.json_notoken)
248
+
249
+ self.assertEqual(parse_token_response(self.json_response_noscope,
250
+ scope=['all', 'the', 'scopes']), self.json_noscope_dict)
251
+ self.assertEqual(parse_token_response(self.json_response_noexpire), self.json_noexpire_dict)
252
+ self.assertEqual(parse_token_response(self.json_response_expirenull), self.json_noexpire_dict)
253
+
254
+ scope_changes_recorded = []
255
+ def record_scope_change(sender, message, old, new):
256
+ scope_changes_recorded.append((message, old, new))
257
+
258
+ os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
259
+ signals.scope_changed.connect(record_scope_change)
260
+ try:
261
+ parse_token_response(self.json_response, scope='aaa')
262
+ self.assertEqual(len(scope_changes_recorded), 1)
263
+ message, old, new = scope_changes_recorded[0]
264
+ for scope in new + old:
265
+ self.assertIn(scope, message)
266
+ self.assertEqual(old, ['aaa'])
267
+ self.assertEqual(set(new), {'abc', 'def'})
268
+ finally:
269
+ signals.scope_changed.disconnect(record_scope_change)
270
+ del os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE']
271
+
272
+
273
+ def test_json_token_notype(self):
274
+ """Verify strict token type parsing only when configured. """
275
+ self.assertEqual(parse_token_response(self.json_notype), self.json_notype_dict)
276
+ try:
277
+ os.environ['OAUTHLIB_STRICT_TOKEN_TYPE'] = '1'
278
+ self.assertRaises(MissingTokenTypeError, parse_token_response, self.json_notype)
279
+ finally:
280
+ del os.environ['OAUTHLIB_STRICT_TOKEN_TYPE']
281
+
282
+ def test_url_encoded_token_response(self):
283
+ """Verify fallback parameter parsing and validation for token responses. """
284
+ self.assertEqual(parse_token_response(self.url_encoded_response), self.json_dict)
285
+ self.assertRaises(AccessDeniedError, parse_token_response, self.url_encoded_error)
286
+ self.assertRaises(MissingTokenError, parse_token_response, self.url_encoded_notoken)
287
+
288
+ scope_changes_recorded = []
289
+ def record_scope_change(sender, message, old, new):
290
+ scope_changes_recorded.append((message, old, new))
291
+
292
+ os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
293
+ signals.scope_changed.connect(record_scope_change)
294
+ try:
295
+ token = parse_token_response(self.url_encoded_response, scope='aaa')
296
+ self.assertEqual(len(scope_changes_recorded), 1)
297
+ message, old, new = scope_changes_recorded[0]
298
+ for scope in new + old:
299
+ self.assertIn(scope, message)
300
+ self.assertEqual(old, ['aaa'])
301
+ self.assertEqual(set(new), {'abc', 'def'})
302
+ finally:
303
+ signals.scope_changed.disconnect(record_scope_change)
304
+ del os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE']
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/test_request_validator.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from oauthlib.oauth2 import RequestValidator
3
+
4
+ from tests.unittest import TestCase
5
+
6
+
7
+ class RequestValidatorTest(TestCase):
8
+
9
+ def test_method_contracts(self):
10
+ v = RequestValidator()
11
+ self.assertRaises(NotImplementedError, v.authenticate_client, 'r')
12
+ self.assertRaises(NotImplementedError, v.authenticate_client_id,
13
+ 'client_id', 'r')
14
+ self.assertRaises(NotImplementedError, v.confirm_redirect_uri,
15
+ 'client_id', 'code', 'redirect_uri', 'client', 'request')
16
+ self.assertRaises(NotImplementedError, v.get_default_redirect_uri,
17
+ 'client_id', 'request')
18
+ self.assertRaises(NotImplementedError, v.get_default_scopes,
19
+ 'client_id', 'request')
20
+ self.assertRaises(NotImplementedError, v.get_original_scopes,
21
+ 'refresh_token', 'request')
22
+ self.assertFalse(v.is_within_original_scope(
23
+ ['scope'], 'refresh_token', 'request'))
24
+ self.assertRaises(NotImplementedError, v.invalidate_authorization_code,
25
+ 'client_id', 'code', 'request')
26
+ self.assertRaises(NotImplementedError, v.save_authorization_code,
27
+ 'client_id', 'code', 'request')
28
+ self.assertRaises(NotImplementedError, v.save_bearer_token,
29
+ 'token', 'request')
30
+ self.assertRaises(NotImplementedError, v.validate_bearer_token,
31
+ 'token', 'scopes', 'request')
32
+ self.assertRaises(NotImplementedError, v.validate_client_id,
33
+ 'client_id', 'request')
34
+ self.assertRaises(NotImplementedError, v.validate_code,
35
+ 'client_id', 'code', 'client', 'request')
36
+ self.assertRaises(NotImplementedError, v.validate_grant_type,
37
+ 'client_id', 'grant_type', 'client', 'request')
38
+ self.assertRaises(NotImplementedError, v.validate_redirect_uri,
39
+ 'client_id', 'redirect_uri', 'request')
40
+ self.assertRaises(NotImplementedError, v.validate_refresh_token,
41
+ 'refresh_token', 'client', 'request')
42
+ self.assertRaises(NotImplementedError, v.validate_response_type,
43
+ 'client_id', 'response_type', 'client', 'request')
44
+ self.assertRaises(NotImplementedError, v.validate_scopes,
45
+ 'client_id', 'scopes', 'client', 'request')
46
+ self.assertRaises(NotImplementedError, v.validate_user,
47
+ 'username', 'password', 'client', 'request')
48
+ self.assertTrue(v.client_authentication_required('r'))
49
+ self.assertFalse(
50
+ v.is_origin_allowed('client_id', 'https://foo.bar', 'r')
51
+ )
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/test_server.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import json
3
+ from unittest import mock
4
+
5
+ from oauthlib import common
6
+ from oauthlib.oauth2.rfc6749 import errors, tokens
7
+ from oauthlib.oauth2.rfc6749.endpoints import Server
8
+ from oauthlib.oauth2.rfc6749.endpoints.authorization import (
9
+ AuthorizationEndpoint,
10
+ )
11
+ from oauthlib.oauth2.rfc6749.endpoints.resource import ResourceEndpoint
12
+ from oauthlib.oauth2.rfc6749.endpoints.token import TokenEndpoint
13
+ from oauthlib.oauth2.rfc6749.grant_types import (
14
+ AuthorizationCodeGrant, ClientCredentialsGrant, ImplicitGrant,
15
+ ResourceOwnerPasswordCredentialsGrant,
16
+ )
17
+
18
+ from tests.unittest import TestCase
19
+
20
+
21
+ class AuthorizationEndpointTest(TestCase):
22
+
23
+ def setUp(self):
24
+ self.mock_validator = mock.MagicMock()
25
+ self.mock_validator.get_code_challenge.return_value = None
26
+ self.addCleanup(setattr, self, 'mock_validator', mock.MagicMock())
27
+ auth_code = AuthorizationCodeGrant(
28
+ request_validator=self.mock_validator)
29
+ auth_code.save_authorization_code = mock.MagicMock()
30
+ implicit = ImplicitGrant(
31
+ request_validator=self.mock_validator)
32
+ implicit.save_token = mock.MagicMock()
33
+
34
+ response_types = {
35
+ 'code': auth_code,
36
+ 'token': implicit,
37
+ 'none': auth_code
38
+ }
39
+ self.expires_in = 1800
40
+ token = tokens.BearerToken(
41
+ self.mock_validator,
42
+ expires_in=self.expires_in
43
+ )
44
+ self.endpoint = AuthorizationEndpoint(
45
+ default_response_type='code',
46
+ default_token_type=token,
47
+ response_types=response_types
48
+ )
49
+
50
+ @mock.patch('oauthlib.common.generate_token', new=lambda: 'abc')
51
+ def test_authorization_grant(self):
52
+ uri = 'http://i.b/l?response_type=code&client_id=me&scope=all+of+them&state=xyz'
53
+ uri += '&redirect_uri=http%3A%2F%2Fback.to%2Fme'
54
+ headers, body, status_code = self.endpoint.create_authorization_response(
55
+ uri, scopes=['all', 'of', 'them'])
56
+ self.assertIn('Location', headers)
57
+ self.assertURLEqual(headers['Location'], 'http://back.to/me?code=abc&state=xyz')
58
+
59
+ @mock.patch('oauthlib.common.generate_token', new=lambda: 'abc')
60
+ def test_implicit_grant(self):
61
+ uri = 'http://i.b/l?response_type=token&client_id=me&scope=all+of+them&state=xyz'
62
+ uri += '&redirect_uri=http%3A%2F%2Fback.to%2Fme'
63
+ headers, body, status_code = self.endpoint.create_authorization_response(
64
+ uri, scopes=['all', 'of', 'them'])
65
+ self.assertIn('Location', headers)
66
+ self.assertURLEqual(headers['Location'], 'http://back.to/me#access_token=abc&expires_in=' + str(self.expires_in) + '&token_type=Bearer&state=xyz&scope=all+of+them', parse_fragment=True)
67
+
68
+ def test_none_grant(self):
69
+ uri = 'http://i.b/l?response_type=none&client_id=me&scope=all+of+them&state=xyz'
70
+ uri += '&redirect_uri=http%3A%2F%2Fback.to%2Fme'
71
+ headers, body, status_code = self.endpoint.create_authorization_response(
72
+ uri, scopes=['all', 'of', 'them'])
73
+ self.assertIn('Location', headers)
74
+ self.assertURLEqual(headers['Location'], 'http://back.to/me?state=xyz', parse_fragment=True)
75
+ self.assertIsNone(body)
76
+ self.assertEqual(status_code, 302)
77
+
78
+ # and without the state parameter
79
+ uri = 'http://i.b/l?response_type=none&client_id=me&scope=all+of+them'
80
+ uri += '&redirect_uri=http%3A%2F%2Fback.to%2Fme'
81
+ headers, body, status_code = self.endpoint.create_authorization_response(
82
+ uri, scopes=['all', 'of', 'them'])
83
+ self.assertIn('Location', headers)
84
+ self.assertURLEqual(headers['Location'], 'http://back.to/me', parse_fragment=True)
85
+ self.assertIsNone(body)
86
+ self.assertEqual(status_code, 302)
87
+
88
+ def test_missing_type(self):
89
+ uri = 'http://i.b/l?client_id=me&scope=all+of+them'
90
+ uri += '&redirect_uri=http%3A%2F%2Fback.to%2Fme'
91
+ self.mock_validator.validate_request = mock.MagicMock(
92
+ side_effect=errors.InvalidRequestError())
93
+ headers, body, status_code = self.endpoint.create_authorization_response(
94
+ uri, scopes=['all', 'of', 'them'])
95
+ self.assertIn('Location', headers)
96
+ self.assertURLEqual(headers['Location'], 'http://back.to/me?error=invalid_request&error_description=Missing+response_type+parameter.')
97
+
98
+ def test_invalid_type(self):
99
+ uri = 'http://i.b/l?response_type=invalid&client_id=me&scope=all+of+them'
100
+ uri += '&redirect_uri=http%3A%2F%2Fback.to%2Fme'
101
+ self.mock_validator.validate_request = mock.MagicMock(
102
+ side_effect=errors.UnsupportedResponseTypeError())
103
+ headers, body, status_code = self.endpoint.create_authorization_response(
104
+ uri, scopes=['all', 'of', 'them'])
105
+ self.assertIn('Location', headers)
106
+ self.assertURLEqual(headers['Location'], 'http://back.to/me?error=unsupported_response_type')
107
+
108
+
109
+ class TokenEndpointTest(TestCase):
110
+
111
+ def setUp(self):
112
+ def set_user(request):
113
+ request.user = mock.MagicMock()
114
+ request.client = mock.MagicMock()
115
+ request.client.client_id = 'mocked_client_id'
116
+ return True
117
+
118
+ self.mock_validator = mock.MagicMock()
119
+ self.mock_validator.authenticate_client.side_effect = set_user
120
+ self.mock_validator.get_code_challenge.return_value = None
121
+ self.addCleanup(setattr, self, 'mock_validator', mock.MagicMock())
122
+ auth_code = AuthorizationCodeGrant(
123
+ request_validator=self.mock_validator)
124
+ password = ResourceOwnerPasswordCredentialsGrant(
125
+ request_validator=self.mock_validator)
126
+ client = ClientCredentialsGrant(
127
+ request_validator=self.mock_validator)
128
+ supported_types = {
129
+ 'authorization_code': auth_code,
130
+ 'password': password,
131
+ 'client_credentials': client,
132
+ }
133
+ self.expires_in = 1800
134
+ token = tokens.BearerToken(
135
+ self.mock_validator,
136
+ expires_in=self.expires_in
137
+ )
138
+ self.endpoint = TokenEndpoint(
139
+ 'authorization_code',
140
+ default_token_type=token,
141
+ grant_types=supported_types
142
+ )
143
+
144
+ @mock.patch('oauthlib.common.generate_token', new=lambda: 'abc')
145
+ def test_authorization_grant(self):
146
+ body = 'grant_type=authorization_code&code=abc&scope=all+of+them'
147
+ headers, body, status_code = self.endpoint.create_token_response(
148
+ '', body=body)
149
+ token = {
150
+ 'token_type': 'Bearer',
151
+ 'expires_in': self.expires_in,
152
+ 'access_token': 'abc',
153
+ 'refresh_token': 'abc',
154
+ 'scope': 'all of them'
155
+ }
156
+ self.assertEqual(json.loads(body), token)
157
+
158
+ body = 'grant_type=authorization_code&code=abc'
159
+ headers, body, status_code = self.endpoint.create_token_response(
160
+ '', body=body)
161
+ token = {
162
+ 'token_type': 'Bearer',
163
+ 'expires_in': self.expires_in,
164
+ 'access_token': 'abc',
165
+ 'refresh_token': 'abc'
166
+ }
167
+ self.assertEqual(json.loads(body), token)
168
+
169
+ # try with additional custom variables
170
+ body = 'grant_type=authorization_code&code=abc&state=foobar'
171
+ headers, body, status_code = self.endpoint.create_token_response(
172
+ '', body=body)
173
+ self.assertEqual(json.loads(body), token)
174
+
175
+ @mock.patch('oauthlib.common.generate_token', new=lambda: 'abc')
176
+ def test_password_grant(self):
177
+ body = 'grant_type=password&username=a&password=hello&scope=all+of+them'
178
+ headers, body, status_code = self.endpoint.create_token_response(
179
+ '', body=body)
180
+ token = {
181
+ 'token_type': 'Bearer',
182
+ 'expires_in': self.expires_in,
183
+ 'access_token': 'abc',
184
+ 'refresh_token': 'abc',
185
+ 'scope': 'all of them',
186
+ }
187
+ self.assertEqual(json.loads(body), token)
188
+
189
+ @mock.patch('oauthlib.common.generate_token', new=lambda: 'abc')
190
+ def test_client_grant(self):
191
+ body = 'grant_type=client_credentials&scope=all+of+them'
192
+ headers, body, status_code = self.endpoint.create_token_response(
193
+ '', body=body)
194
+ token = {
195
+ 'token_type': 'Bearer',
196
+ 'expires_in': self.expires_in,
197
+ 'access_token': 'abc',
198
+ 'scope': 'all of them',
199
+ }
200
+ self.assertEqual(json.loads(body), token)
201
+
202
+ def test_missing_type(self):
203
+ _, body, _ = self.endpoint.create_token_response('', body='')
204
+ token = {'error': 'unsupported_grant_type'}
205
+ self.assertEqual(json.loads(body), token)
206
+
207
+ def test_invalid_type(self):
208
+ body = 'grant_type=invalid'
209
+ _, body, _ = self.endpoint.create_token_response('', body=body)
210
+ token = {'error': 'unsupported_grant_type'}
211
+ self.assertEqual(json.loads(body), token)
212
+
213
+
214
+ class SignedTokenEndpointTest(TestCase):
215
+
216
+ def setUp(self):
217
+ self.expires_in = 1800
218
+
219
+ def set_user(request):
220
+ request.user = mock.MagicMock()
221
+ request.client = mock.MagicMock()
222
+ request.client.client_id = 'mocked_client_id'
223
+ return True
224
+
225
+ self.mock_validator = mock.MagicMock()
226
+ self.mock_validator.get_code_challenge.return_value = None
227
+ self.mock_validator.authenticate_client.side_effect = set_user
228
+ self.addCleanup(setattr, self, 'mock_validator', mock.MagicMock())
229
+
230
+ self.private_pem = """
231
+ -----BEGIN RSA PRIVATE KEY-----
232
+ MIIEpAIBAAKCAQEA6TtDhWGwzEOWZP6m/zHoZnAPLABfetvoMPmxPGjFjtDuMRPv
233
+ EvI1sbixZBjBtdnc5rTtHUUQ25Am3JzwPRGo5laMGbj1pPyCPxlVi9LK82HQNX0B
234
+ YK7tZtVfDHElQA7F4v3j9d3rad4O9/n+lyGIQ0tT7yQcBm2A8FEaP0bZYCLMjwMN
235
+ WfaVLE8eXHyv+MfpNNLI9wttLxygKYM48I3NwsFuJgOa/KuodXaAmf8pJnx8t1Wn
236
+ nxvaYXFiUn/TxmhM/qhemPa6+0nqq+aWV5eT7xn4K/ghLgNs09v6Yge0pmPl9Oz+
237
+ +bjJ+aKRnAmwCOY8/5U5EilAiUOeBoO9+8OXtwIDAQABAoIBAGFTTbXXMkPK4HN8
238
+ oItVdDlrAanG7hECuz3UtFUVE3upS/xG6TjqweVLwRqYCh2ssDXFwjy4mXRGDzF4
239
+ e/e/6s9Txlrlh/w1MtTJ6ZzTdcViR9RKOczysjZ7S5KRlI3KnGFAuWPcG2SuOWjZ
240
+ dZfzcj1Crd/ZHajBAVFHRsCo/ATVNKbTRprFfb27xKpQ2BwH/GG781sLE3ZVNIhs
241
+ aRRaED4622kI1E/WXws2qQMqbFKzo0m1tPbLb3Z89WgZJ/tRQwuDype1Vfm7k6oX
242
+ xfbp3948qSe/yWKRlMoPkleji/WxPkSIalzWSAi9ziN/0Uzhe65FURgrfHL3XR1A
243
+ B8UR+aECgYEA7NPQZV4cAikk02Hv65JgISofqV49P8MbLXk8sdnI1n7Mj10TgzU3
244
+ lyQGDEX4hqvT0bTXe4KAOxQZx9wumu05ejfzhdtSsEm6ptGHyCdmYDQeV0C/pxDX
245
+ JNCK8XgMku2370XG0AnyBCT7NGlgtDcNCQufcesF2gEuoKiXg6Zjo7sCgYEA/Bzs
246
+ 9fWGZZnSsMSBSW2OYbFuhF3Fne0HcxXQHipl0Rujc/9g0nccwqKGizn4fGOE7a8F
247
+ usQgJoeGcinL7E9OEP/uQ9VX1C9RNVjIxP1O5/Guw1zjxQQYetOvbPhN2QhD1Ye7
248
+ 0TRKrW1BapcjwLpFQlVg1ZeTPOi5lv24W/wX9jUCgYEAkrMSX/hPuTbrTNVZ3L6r
249
+ NV/2hN+PaTPeXei/pBuXwOaCqDurnpcUfFcgN/IP5LwDVd+Dq0pHTFFDNv45EFbq
250
+ R77o5n3ZVsIVEMiyJ1XgoK8oLDw7e61+15smtjT69Piz+09pu+ytMcwGn4y3Dmsb
251
+ dALzHYnL8iLRU0ubrz0ec4kCgYAJiVKRTzNBPptQom49h85d9ac3jJCAE8o3WTjh
252
+ Gzt0uHXrWlqgO280EY/DTnMOyXjqwLcXxHlu26uDP/99tdY/IF8z46sJ1KxetzgI
253
+ 84f7kBHLRAU9m5UNeFpnZdEUB5MBTbwWAsNcYgiabpMkpCcghjg+fBhOsoLqqjhC
254
+ CnwhjQKBgQDkv0QTdyBU84TE8J0XY3eLQwXbrvG2yD5A2ntN3PyxGEneX5WTJGMZ
255
+ xJxwaFYQiDS3b9E7b8Q5dg8qa5Y1+epdhx3cuQAWPm+AoHKshDfbRve4txBDQAqh
256
+ c6MxSWgsa+2Ld5SWSNbGtpPcmEM3Fl5ttMCNCKtNc0UE16oHwaPAIw==
257
+ -----END RSA PRIVATE KEY-----
258
+ """
259
+
260
+ self.public_pem = """
261
+ -----BEGIN PUBLIC KEY-----
262
+ MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6TtDhWGwzEOWZP6m/zHo
263
+ ZnAPLABfetvoMPmxPGjFjtDuMRPvEvI1sbixZBjBtdnc5rTtHUUQ25Am3JzwPRGo
264
+ 5laMGbj1pPyCPxlVi9LK82HQNX0BYK7tZtVfDHElQA7F4v3j9d3rad4O9/n+lyGI
265
+ Q0tT7yQcBm2A8FEaP0bZYCLMjwMNWfaVLE8eXHyv+MfpNNLI9wttLxygKYM48I3N
266
+ wsFuJgOa/KuodXaAmf8pJnx8t1WnnxvaYXFiUn/TxmhM/qhemPa6+0nqq+aWV5eT
267
+ 7xn4K/ghLgNs09v6Yge0pmPl9Oz++bjJ+aKRnAmwCOY8/5U5EilAiUOeBoO9+8OX
268
+ twIDAQAB
269
+ -----END PUBLIC KEY-----
270
+ """
271
+
272
+ signed_token = tokens.signed_token_generator(self.private_pem,
273
+ user_id=123)
274
+ self.endpoint = Server(
275
+ self.mock_validator,
276
+ token_expires_in=self.expires_in,
277
+ token_generator=signed_token,
278
+ refresh_token_generator=tokens.random_token_generator
279
+ )
280
+
281
+ @mock.patch('oauthlib.common.generate_token', new=lambda: 'abc')
282
+ def test_authorization_grant(self):
283
+ body = 'client_id=me&redirect_uri=http%3A%2F%2Fback.to%2Fme&grant_type=authorization_code&code=abc&scope=all+of+them'
284
+ headers, body, status_code = self.endpoint.create_token_response(
285
+ '', body=body)
286
+ body = json.loads(body)
287
+ token = {
288
+ 'token_type': 'Bearer',
289
+ 'expires_in': self.expires_in,
290
+ 'access_token': body['access_token'],
291
+ 'refresh_token': 'abc',
292
+ 'scope': 'all of them'
293
+ }
294
+ self.assertEqual(body, token)
295
+
296
+ body = 'client_id=me&redirect_uri=http%3A%2F%2Fback.to%2Fme&grant_type=authorization_code&code=abc'
297
+ headers, body, status_code = self.endpoint.create_token_response(
298
+ '', body=body)
299
+ body = json.loads(body)
300
+ token = {
301
+ 'token_type': 'Bearer',
302
+ 'expires_in': self.expires_in,
303
+ 'access_token': body['access_token'],
304
+ 'refresh_token': 'abc'
305
+ }
306
+ self.assertEqual(body, token)
307
+
308
+ # try with additional custom variables
309
+ body = 'client_id=me&redirect_uri=http%3A%2F%2Fback.to%2Fme&grant_type=authorization_code&code=abc&state=foobar'
310
+ headers, body, status_code = self.endpoint.create_token_response(
311
+ '', body=body)
312
+ body = json.loads(body)
313
+ token = {
314
+ 'token_type': 'Bearer',
315
+ 'expires_in': self.expires_in,
316
+ 'access_token': body['access_token'],
317
+ 'refresh_token': 'abc'
318
+ }
319
+ self.assertEqual(body, token)
320
+
321
+ @mock.patch('oauthlib.common.generate_token', new=lambda: 'abc')
322
+ def test_password_grant(self):
323
+ body = 'grant_type=password&username=a&password=hello&scope=all+of+them'
324
+ headers, body, status_code = self.endpoint.create_token_response(
325
+ '', body=body)
326
+ body = json.loads(body)
327
+ token = {
328
+ 'token_type': 'Bearer',
329
+ 'expires_in': self.expires_in,
330
+ 'access_token': body['access_token'],
331
+ 'refresh_token': 'abc',
332
+ 'scope': 'all of them',
333
+ }
334
+ self.assertEqual(body, token)
335
+
336
+ @mock.patch('oauthlib.common.generate_token', new=lambda: 'abc')
337
+ def test_scopes_and_user_id_stored_in_access_token(self):
338
+ body = 'grant_type=password&username=a&password=hello&scope=all+of+them'
339
+ headers, body, status_code = self.endpoint.create_token_response(
340
+ '', body=body)
341
+
342
+ access_token = json.loads(body)['access_token']
343
+
344
+ claims = common.verify_signed_token(self.public_pem, access_token)
345
+
346
+ self.assertEqual(claims['scope'], 'all of them')
347
+ self.assertEqual(claims['user_id'], 123)
348
+
349
+ @mock.patch('oauthlib.common.generate_token', new=lambda: 'abc')
350
+ def test_client_grant(self):
351
+ body = 'grant_type=client_credentials&scope=all+of+them'
352
+ headers, body, status_code = self.endpoint.create_token_response(
353
+ '', body=body)
354
+ body = json.loads(body)
355
+ token = {
356
+ 'token_type': 'Bearer',
357
+ 'expires_in': self.expires_in,
358
+ 'access_token': body['access_token'],
359
+ 'scope': 'all of them',
360
+ }
361
+ self.assertEqual(body, token)
362
+
363
+ def test_missing_type(self):
364
+ _, body, _ = self.endpoint.create_token_response('', body='client_id=me&redirect_uri=http%3A%2F%2Fback.to%2Fme&code=abc')
365
+ token = {'error': 'unsupported_grant_type'}
366
+ self.assertEqual(json.loads(body), token)
367
+
368
+ def test_invalid_type(self):
369
+ body = 'client_id=me&redirect_uri=http%3A%2F%2Fback.to%2Fme&grant_type=invalid&code=abc'
370
+ _, body, _ = self.endpoint.create_token_response('', body=body)
371
+ token = {'error': 'unsupported_grant_type'}
372
+ self.assertEqual(json.loads(body), token)
373
+
374
+
375
+ class ResourceEndpointTest(TestCase):
376
+
377
+ def setUp(self):
378
+ self.mock_validator = mock.MagicMock()
379
+ self.addCleanup(setattr, self, 'mock_validator', mock.MagicMock())
380
+ token = tokens.BearerToken(request_validator=self.mock_validator)
381
+ self.endpoint = ResourceEndpoint(
382
+ default_token='Bearer',
383
+ token_types={'Bearer': token}
384
+ )
385
+
386
+ def test_defaults(self):
387
+ uri = 'http://a.b/path?some=query'
388
+ self.mock_validator.validate_bearer_token.return_value = False
389
+ valid, request = self.endpoint.verify_request(uri)
390
+ self.assertFalse(valid)
391
+ self.assertEqual(request.token_type, 'Bearer')
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/test_tokens.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unittest import mock
2
+
3
+ from oauthlib.common import Request
4
+ from oauthlib.oauth2.rfc6749.tokens import (
5
+ BearerToken, prepare_bearer_body, prepare_bearer_headers,
6
+ prepare_bearer_uri, prepare_mac_header,
7
+ )
8
+
9
+ from tests.unittest import TestCase
10
+
11
+
12
+ class TokenTest(TestCase):
13
+
14
+ # MAC without body/payload or extension
15
+ mac_plain = {
16
+ 'token': 'h480djs93hd8',
17
+ 'uri': 'http://example.com/resource/1?b=1&a=2',
18
+ 'key': '489dks293j39',
19
+ 'http_method': 'GET',
20
+ 'nonce': '264095:dj83hs9s',
21
+ 'hash_algorithm': 'hmac-sha-1'
22
+ }
23
+ auth_plain = {
24
+ 'Authorization': 'MAC id="h480djs93hd8", nonce="264095:dj83hs9s",'
25
+ ' mac="SLDJd4mg43cjQfElUs3Qub4L6xE="'
26
+ }
27
+
28
+ # MAC with body/payload, no extension
29
+ mac_body = {
30
+ 'token': 'jd93dh9dh39D',
31
+ 'uri': 'http://example.com/request',
32
+ 'key': '8yfrufh348h',
33
+ 'http_method': 'POST',
34
+ 'nonce': '273156:di3hvdf8',
35
+ 'hash_algorithm': 'hmac-sha-1',
36
+ 'body': 'hello=world%21'
37
+ }
38
+ auth_body = {
39
+ 'Authorization': 'MAC id="jd93dh9dh39D", nonce="273156:di3hvdf8",'
40
+ ' bodyhash="k9kbtCIy0CkI3/FEfpS/oIDjk6k=", mac="W7bdMZbv9UWOTadASIQHagZyirA="'
41
+ }
42
+
43
+ # MAC with body/payload and extension
44
+ mac_both = {
45
+ 'token': 'h480djs93hd8',
46
+ 'uri': 'http://example.com/request?b5=%3D%253D&a3=a&c%40=&a2=r%20b&c2&a3=2+q',
47
+ 'key': '489dks293j39',
48
+ 'http_method': 'GET',
49
+ 'nonce': '264095:7d8f3e4a',
50
+ 'hash_algorithm': 'hmac-sha-1',
51
+ 'body': 'Hello World!',
52
+ 'ext': 'a,b,c'
53
+ }
54
+ auth_both = {
55
+ 'Authorization': 'MAC id="h480djs93hd8", nonce="264095:7d8f3e4a",'
56
+ ' bodyhash="Lve95gjOVATpfV8EL5X4nxwjKHE=", ext="a,b,c",'
57
+ ' mac="Z3C2DojEopRDIC88/imW8Ez853g="'
58
+ }
59
+
60
+ # Bearer
61
+ token = 'vF9dft4qmT'
62
+ uri = 'http://server.example.com/resource'
63
+ bearer_headers = {
64
+ 'Authorization': 'Bearer vF9dft4qmT'
65
+ }
66
+ valid_bearer_header_lowercase = {"Authorization": "bearer vF9dft4qmT"}
67
+ fake_bearer_headers = [
68
+ {'Authorization': 'Beaver vF9dft4qmT'},
69
+ {'Authorization': 'BeavervF9dft4qmT'},
70
+ {'Authorization': 'Beaver vF9dft4qmT'},
71
+ {'Authorization': 'BearerF9dft4qmT'},
72
+ {'Authorization': 'Bearer vF9d ft4qmT'},
73
+ ]
74
+ valid_header_with_multiple_spaces = {'Authorization': 'Bearer vF9dft4qmT'}
75
+ bearer_body = 'access_token=vF9dft4qmT'
76
+ bearer_uri = 'http://server.example.com/resource?access_token=vF9dft4qmT'
77
+
78
+ def _mocked_validate_bearer_token(self, token, scopes, request):
79
+ if not token: # noqa: SIM103
80
+ return False
81
+ return True
82
+
83
+ def test_prepare_mac_header(self):
84
+ """Verify mac signatures correctness
85
+
86
+ TODO: verify hmac-sha-256
87
+ """
88
+ self.assertEqual(prepare_mac_header(**self.mac_plain), self.auth_plain)
89
+ self.assertEqual(prepare_mac_header(**self.mac_body), self.auth_body)
90
+ self.assertEqual(prepare_mac_header(**self.mac_both), self.auth_both)
91
+
92
+ def test_prepare_bearer_request(self):
93
+ """Verify proper addition of bearer tokens to requests.
94
+
95
+ They may be represented as query components in body or URI or
96
+ in a Bearer authorization header.
97
+ """
98
+ self.assertEqual(prepare_bearer_headers(self.token), self.bearer_headers)
99
+ self.assertEqual(prepare_bearer_body(self.token), self.bearer_body)
100
+ self.assertEqual(prepare_bearer_uri(self.token, uri=self.uri), self.bearer_uri)
101
+
102
+ def test_valid_bearer_is_validated(self):
103
+ request_validator = mock.MagicMock()
104
+ request_validator.validate_bearer_token = self._mocked_validate_bearer_token
105
+
106
+ request = Request("/", headers=self.bearer_headers)
107
+ result = BearerToken(request_validator=request_validator).validate_request(
108
+ request
109
+ )
110
+ self.assertTrue(result)
111
+
112
+ def test_lowercase_bearer_is_validated(self):
113
+ request_validator = mock.MagicMock()
114
+ request_validator.validate_bearer_token = self._mocked_validate_bearer_token
115
+
116
+ request = Request("/", headers=self.valid_bearer_header_lowercase)
117
+ result = BearerToken(request_validator=request_validator).validate_request(
118
+ request
119
+ )
120
+ self.assertTrue(result)
121
+
122
+ def test_fake_bearer_is_not_validated(self):
123
+ request_validator = mock.MagicMock()
124
+ request_validator.validate_bearer_token = self._mocked_validate_bearer_token
125
+
126
+ for fake_header in self.fake_bearer_headers:
127
+ request = Request("/", headers=fake_header)
128
+ result = BearerToken(request_validator=request_validator).validate_request(
129
+ request
130
+ )
131
+
132
+ self.assertFalse(result)
133
+
134
+ def test_header_with_multispaces_is_validated(self):
135
+ request_validator = mock.MagicMock()
136
+ request_validator.validate_bearer_token = self._mocked_validate_bearer_token
137
+
138
+ request = Request("/", headers=self.valid_header_with_multiple_spaces)
139
+ result = BearerToken(request_validator=request_validator).validate_request(
140
+ request
141
+ )
142
+
143
+ self.assertTrue(result)
144
+
145
+ def test_estimate_type(self):
146
+ request_validator = mock.MagicMock()
147
+ request_validator.validate_bearer_token = self._mocked_validate_bearer_token
148
+ request = Request("/", headers=self.bearer_headers)
149
+ result = BearerToken(request_validator=request_validator).estimate_type(request)
150
+ self.assertEqual(result, 9)
151
+
152
+ def test_estimate_type_with_fake_header_returns_type_0(self):
153
+ request_validator = mock.MagicMock()
154
+ request_validator.validate_bearer_token = self._mocked_validate_bearer_token
155
+
156
+ for fake_header in self.fake_bearer_headers:
157
+ request = Request("/", headers=fake_header)
158
+ result = BearerToken(request_validator=request_validator).estimate_type(
159
+ request
160
+ )
161
+
162
+ if (
163
+ fake_header["Authorization"].count(" ") == 2
164
+ and fake_header["Authorization"].split()[0] == "Bearer"
165
+ ):
166
+ # If we're dealing with the header containing 2 spaces, it will be recognized
167
+ # as a Bearer valid header, the token itself will be invalid by the way.
168
+ self.assertEqual(result, 9)
169
+ else:
170
+ self.assertEqual(result, 0)
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc6749/test_utils.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import os
3
+
4
+ from oauthlib.oauth2.rfc6749.utils import (
5
+ escape, generate_age, host_from_uri, is_secure_transport, list_to_scope,
6
+ params_from_uri, scope_to_list,
7
+ )
8
+
9
+ from tests.unittest import TestCase
10
+
11
+
12
+ class ScopeObject:
13
+ """
14
+ Fixture for testing list_to_scope()/scope_to_list() with objects other
15
+ than regular strings.
16
+ """
17
+ def __init__(self, scope):
18
+ self.scope = scope
19
+
20
+ def __str__(self):
21
+ return self.scope
22
+
23
+
24
+ class UtilsTests(TestCase):
25
+
26
+ def test_escape(self):
27
+ """Assert that we are only escaping unicode"""
28
+ self.assertRaises(ValueError, escape, b"I am a string type. Not a unicode type.")
29
+ self.assertEqual(escape("I am a unicode type."), "I%20am%20a%20unicode%20type.")
30
+
31
+ def test_host_from_uri(self):
32
+ """Test if hosts and ports are properly extracted from URIs.
33
+
34
+ This should be done according to the MAC Authentication spec.
35
+ Defaults ports should be provided when none is present in the URI.
36
+ """
37
+ self.assertEqual(host_from_uri('http://a.b-c.com:8080'), ('a.b-c.com', '8080'))
38
+ self.assertEqual(host_from_uri('https://a.b.com:8080'), ('a.b.com', '8080'))
39
+ self.assertEqual(host_from_uri('http://www.example.com'), ('www.example.com', '80'))
40
+ self.assertEqual(host_from_uri('https://www.example.com'), ('www.example.com', '443'))
41
+
42
+ def test_is_secure_transport(self):
43
+ """Test check secure uri."""
44
+ if 'OAUTHLIB_INSECURE_TRANSPORT' in os.environ:
45
+ del os.environ['OAUTHLIB_INSECURE_TRANSPORT']
46
+
47
+ self.assertTrue(is_secure_transport('https://example.com'))
48
+ self.assertFalse(is_secure_transport('http://example.com'))
49
+
50
+ os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
51
+ self.assertTrue(is_secure_transport('http://example.com'))
52
+ del os.environ['OAUTHLIB_INSECURE_TRANSPORT']
53
+
54
+ def test_params_from_uri(self):
55
+ self.assertEqual(params_from_uri('http://i.b/?foo=bar&g&scope=a+d'),
56
+ {'foo': 'bar', 'g': '', 'scope': ['a', 'd']})
57
+
58
+ def test_generate_age(self):
59
+ issue_time = datetime.datetime.now() - datetime.timedelta(
60
+ days=3, minutes=1, seconds=4)
61
+ self.assertGreater(float(generate_age(issue_time)), 259263.0)
62
+
63
+ def test_list_to_scope(self):
64
+ expected = 'foo bar baz'
65
+
66
+ string_list = ['foo', 'bar', 'baz']
67
+ self.assertEqual(list_to_scope(string_list), expected)
68
+
69
+ string_tuple = ('foo', 'bar', 'baz')
70
+ self.assertEqual(list_to_scope(string_tuple), expected)
71
+
72
+ obj_list = [ScopeObject('foo'), ScopeObject('bar'), ScopeObject('baz')]
73
+ self.assertEqual(list_to_scope(obj_list), expected)
74
+
75
+ set_list = set(string_list)
76
+ set_scope = list_to_scope(set_list)
77
+ assert len(set_scope.split(' ')) == 3
78
+ for x in string_list:
79
+ assert x in set_scope
80
+
81
+ self.assertRaises(ValueError, list_to_scope, object())
82
+
83
+ def test_scope_to_list(self):
84
+ expected = ['foo', 'bar', 'baz']
85
+
86
+ string_scopes = 'foo bar baz '
87
+ self.assertEqual(scope_to_list(string_scopes), expected)
88
+
89
+ string_list_scopes = ['foo', 'bar', 'baz']
90
+ self.assertEqual(scope_to_list(string_list_scopes), expected)
91
+
92
+ tuple_list_scopes = ('foo', 'bar', 'baz')
93
+ self.assertEqual(scope_to_list(tuple_list_scopes), expected)
94
+
95
+ obj_list_scopes = [ScopeObject('foo'), ScopeObject('bar'), ScopeObject('baz')]
96
+ self.assertEqual(scope_to_list(obj_list_scopes), expected)
97
+
98
+ set_list_scopes = set(string_list_scopes)
99
+ set_list = scope_to_list(set_list_scopes)
100
+ self.assertEqual(sorted(set_list), sorted(string_list_scopes))
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc8628/__init__.py ADDED
File without changes
tasks/oauthlib__oauthlib.1fd52536.combine_file__1utlssis/tests/trusted/tests/oauth2/rfc8628/clients/__init__.py ADDED
File without changes