File: test_oauth1_session.py

package info (click to toggle)
python-authlib 1.6.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,024 kB
  • sloc: python: 27,284; makefile: 53; sh: 14
file content (286 lines) | stat: -rw-r--r-- 10,139 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
from io import StringIO
from unittest import mock

import pytest
import requests

from authlib.common.encoding import to_unicode
from authlib.integrations.requests_client import OAuth1Session
from authlib.integrations.requests_client import OAuthError
from authlib.oauth1 import SIGNATURE_PLAINTEXT
from authlib.oauth1 import SIGNATURE_RSA_SHA1
from authlib.oauth1 import SIGNATURE_TYPE_BODY
from authlib.oauth1 import SIGNATURE_TYPE_QUERY
from authlib.oauth1.rfc5849.util import escape

from ..util import mock_text_response
from ..util import read_key_file

TEST_RSA_OAUTH_SIGNATURE = (
    "Pko%2BFb4T1XGDE5DlLjuEMthVXjczqGi8qyfQ%2FSE405bBLEywint1tYNGN1me8h"
    "JoXZMqyXy%2F%2FAzJ0ViRYRc7rDTaTYyjB%2Fct%2FFt8f4lb3e9LfGhgkwih%2FsH2w%3D%3D"
)


def test_no_client_id():
    with pytest.raises(ValueError):
        OAuth1Session(None)


def test_signature_types():
    def verify_signature(getter):
        def fake_send(r, **kwargs):
            signature = to_unicode(getter(r))
            assert "oauth_signature" in signature
            resp = mock.MagicMock(spec=requests.Response)
            resp.cookies = []
            return resp

        return fake_send

    header = OAuth1Session("foo")
    header.send = verify_signature(lambda r: r.headers["Authorization"])
    header.post("https://provider.test")

    query = OAuth1Session("foo", signature_type=SIGNATURE_TYPE_QUERY)
    query.send = verify_signature(lambda r: r.url)
    query.post("https://provider.test")

    body = OAuth1Session("foo", signature_type=SIGNATURE_TYPE_BODY)
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    body.send = verify_signature(lambda r: r.body)
    body.post("https://provider.test", headers=headers, data="")


@mock.patch("authlib.oauth1.rfc5849.client_auth.generate_timestamp")
@mock.patch("authlib.oauth1.rfc5849.client_auth.generate_nonce")
def test_signature_methods(generate_nonce, generate_timestamp):
    generate_nonce.return_value = "abc"
    generate_timestamp.return_value = "123"

    signature = ", ".join(
        [
            'OAuth oauth_nonce="abc"',
            'oauth_timestamp="123"',
            'oauth_version="1.0"',
            'oauth_signature_method="HMAC-SHA1"',
            'oauth_consumer_key="foo"',
            'oauth_signature="GuqiSr5%2FHajrrmc%2FFprUV4cCGbw%3D"',
        ]
    )
    auth = OAuth1Session("foo")
    auth.send = verify_signature(signature)
    auth.post("https://provider.test")

    signature = (
        "OAuth "
        'oauth_nonce="abc", oauth_timestamp="123", oauth_version="1.0", '
        'oauth_signature_method="PLAINTEXT", oauth_consumer_key="foo", '
        'oauth_signature="%26"'
    )
    auth = OAuth1Session("foo", signature_method=SIGNATURE_PLAINTEXT)
    auth.send = verify_signature(signature)
    auth.post("https://provider.test")

    signature = (
        "OAuth "
        'oauth_nonce="abc", oauth_timestamp="123", oauth_version="1.0", '
        'oauth_signature_method="RSA-SHA1", oauth_consumer_key="foo", '
        f'oauth_signature="{TEST_RSA_OAUTH_SIGNATURE}"'
    )

    rsa_key = read_key_file("rsa_private.pem")
    auth = OAuth1Session("foo", signature_method=SIGNATURE_RSA_SHA1, rsa_key=rsa_key)
    auth.send = verify_signature(signature)
    auth.post("https://provider.test")


@mock.patch("authlib.oauth1.rfc5849.client_auth.generate_timestamp")
@mock.patch("authlib.oauth1.rfc5849.client_auth.generate_nonce")
def test_binary_upload(generate_nonce, generate_timestamp):
    generate_nonce.return_value = "abc"
    generate_timestamp.return_value = "123"
    fake_xml = StringIO("hello world")
    headers = {"Content-Type": "application/xml"}

    def fake_send(r, **kwargs):
        auth_header = r.headers["Authorization"]
        assert "oauth_body_hash" in auth_header

    auth = OAuth1Session("foo", force_include_body=True)
    auth.send = fake_send
    auth.post("https://provider.test", headers=headers, files=[("fake", fake_xml)])


@mock.patch("authlib.oauth1.rfc5849.client_auth.generate_timestamp")
@mock.patch("authlib.oauth1.rfc5849.client_auth.generate_nonce")
def test_nonascii(generate_nonce, generate_timestamp):
    generate_nonce.return_value = "abc"
    generate_timestamp.return_value = "123"
    signature = (
        'OAuth oauth_nonce="abc", oauth_timestamp="123", oauth_version="1.0", '
        'oauth_signature_method="HMAC-SHA1", oauth_consumer_key="foo", '
        'oauth_signature="USkqQvV76SCKBewYI9cut6FfYcI%3D"'
    )
    auth = OAuth1Session("foo")
    auth.send = verify_signature(signature)
    auth.post("https://provider.test?cjk=%E5%95%A6%E5%95%A6")


def test_redirect_uri():
    sess = OAuth1Session("foo")
    assert sess.redirect_uri is None
    url = "https://provider.test"
    sess.redirect_uri = url
    assert sess.redirect_uri == url


def test_set_token():
    sess = OAuth1Session("foo")
    try:
        sess.token = {}
    except OAuthError as exc:
        assert exc.error == "missing_token"

    sess.token = {"oauth_token": "a", "oauth_token_secret": "b"}
    assert sess.token["oauth_verifier"] is None
    sess.token = {"oauth_token": "a", "oauth_verifier": "c"}
    assert sess.token["oauth_token_secret"] == "b"
    assert sess.token["oauth_verifier"] == "c"

    sess.token = None
    assert sess.token["oauth_token"] is None
    assert sess.token["oauth_token_secret"] is None
    assert sess.token["oauth_verifier"] is None


def test_create_authorization_url():
    auth = OAuth1Session("foo")
    url = "https://provider.test/authorize"
    token = "asluif023sf"
    auth_url = auth.create_authorization_url(url, request_token=token)
    assert auth_url == url + "?oauth_token=" + token
    redirect_uri = "https://client.test/callback"
    auth = OAuth1Session("foo", redirect_uri=redirect_uri)
    auth_url = auth.create_authorization_url(url, request_token=token)
    assert escape(redirect_uri) in auth_url


def test_parse_response_url():
    url = "https://provider.test/callback?oauth_token=foo&oauth_verifier=bar"
    auth = OAuth1Session("foo")
    resp = auth.parse_authorization_response(url)
    assert resp["oauth_token"] == "foo"
    assert resp["oauth_verifier"] == "bar"
    for k, v in resp.items():
        assert isinstance(k, str)
        assert isinstance(v, str)


def test_fetch_request_token():
    auth = OAuth1Session("foo", realm="A")
    auth.send = mock_text_response("oauth_token=foo")
    resp = auth.fetch_request_token("https://provider.test/token")
    assert resp["oauth_token"] == "foo"
    for k, v in resp.items():
        assert isinstance(k, str)
        assert isinstance(v, str)

    resp = auth.fetch_request_token("https://provider.test/token")
    assert resp["oauth_token"] == "foo"


def test_fetch_request_token_with_optional_arguments():
    auth = OAuth1Session("foo")
    auth.send = mock_text_response("oauth_token=foo")
    resp = auth.fetch_request_token(
        "https://provider.test/token", verify=False, stream=True
    )
    assert resp["oauth_token"] == "foo"
    for k, v in resp.items():
        assert isinstance(k, str)
        assert isinstance(v, str)


def test_fetch_access_token():
    auth = OAuth1Session("foo", verifier="bar")
    auth.send = mock_text_response("oauth_token=foo")
    resp = auth.fetch_access_token("https://provider.test/token")
    assert resp["oauth_token"] == "foo"
    for k, v in resp.items():
        assert isinstance(k, str)
        assert isinstance(v, str)

    auth = OAuth1Session("foo", verifier="bar")
    auth.send = mock_text_response('{"oauth_token":"foo"}')
    resp = auth.fetch_access_token("https://provider.test/token")
    assert resp["oauth_token"] == "foo"

    auth = OAuth1Session("foo")
    auth.send = mock_text_response("oauth_token=foo")
    resp = auth.fetch_access_token("https://provider.test/token", verifier="bar")
    assert resp["oauth_token"] == "foo"


def test_fetch_access_token_with_optional_arguments():
    auth = OAuth1Session("foo", verifier="bar")
    auth.send = mock_text_response("oauth_token=foo")
    resp = auth.fetch_access_token(
        "https://provider.test/token", verify=False, stream=True
    )
    assert resp["oauth_token"] == "foo"
    for k, v in resp.items():
        assert isinstance(k, str)
        assert isinstance(v, str)


def _test_fetch_access_token_raises_error(session):
    """Assert that an error is being raised whenever there's no verifier
    passed in to the client.
    """
    session.send = mock_text_response("oauth_token=foo")
    with pytest.raises(OAuthError, match="missing_verifier"):
        session.fetch_access_token("https://provider.test/token")


def test_fetch_token_invalid_response():
    auth = OAuth1Session("foo")
    auth.send = mock_text_response("not valid urlencoded response!")
    with pytest.raises(ValueError):
        auth.fetch_request_token("https://provider.test/token")

    for code in (400, 401, 403):
        auth.send = mock_text_response("valid=response", code)
        with pytest.raises(OAuthError, match="fetch_token_denied"):
            auth.fetch_request_token("https://provider.test/token")


def test_fetch_access_token_missing_verifier():
    _test_fetch_access_token_raises_error(OAuth1Session("foo"))


def test_fetch_access_token_has_verifier_is_none():
    session = OAuth1Session("foo")
    session.auth.verifier = None
    _test_fetch_access_token_raises_error(session)


def verify_signature(signature):
    def fake_send(r, **kwargs):
        auth_header = to_unicode(r.headers["Authorization"])
        # RSA signatures are non-deterministic, so we only check the prefix for RSA-SHA1
        if 'oauth_signature_method="RSA-SHA1"' in signature:
            signature_prefix = (
                signature.split('oauth_signature="')[0] + 'oauth_signature="'
            )
            auth_prefix = (
                auth_header.split('oauth_signature="')[0] + 'oauth_signature="'
            )
            assert auth_prefix == signature_prefix
        else:
            assert auth_header == signature
        resp = mock.MagicMock(spec=requests.Response)
        resp.cookies = []
        return resp

    return fake_send