Skip to content

Commit

Permalink
Split tokeninfo scope if it is a string (#477)
Browse files Browse the repository at this point in the history
* Split tokeninfo scope if it is a string

* Add test for string and array scopes

* Fix isort lint error
  • Loading branch information
kislyuk authored and hjacobs committed Jul 8, 2017
1 parent d8019b3 commit ca862c4
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 4 deletions.
5 changes: 4 additions & 1 deletion connexion/decorators/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ def wrapper(request):
token_response=token_request
)
token_info = token_request.json() # type: dict
user_scopes = set(token_info['scope'])
if isinstance(token_info['scope'], list):
user_scopes = set(token_info['scope'])
else:
user_scopes = set(token_info['scope'].split())
logger.debug("... Scopes required: %s", allowed_scopes)
logger.debug("... User scopes: %s", user_scopes)
if not allowed_scopes <= user_scopes:
Expand Down
48 changes: 45 additions & 3 deletions tests/decorators/test_security.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import json

import requests

import pytest
from connexion.decorators.security import get_tokeninfo_url, verify_oauth
from connexion.exceptions import OAuthProblem
from connexion.exceptions import OAuthProblem, OAuthScopeProblem
from mock import MagicMock


Expand Down Expand Up @@ -31,5 +35,43 @@ def func():
app = MagicMock()
monkeypatch.setattr('flask.current_app', app)

with pytest.raises(OAuthProblem) as exc_info:
wrapped_func(MagicMock())
with pytest.raises(OAuthProblem):
wrapped_func(request)


def test_verify_oauth_scopes(monkeypatch):
tokeninfo = dict(uid="foo", scope="scope1 scope2")

def get_tokeninfo_response(*args, **kwargs):
tokeninfo_response = requests.Response()
tokeninfo_response.status_code = requests.codes.ok
tokeninfo_response._content = json.dumps(tokeninfo).encode()
return tokeninfo_response

def func(request):
pass

wrapped_func = verify_oauth('https://example.org/tokeninfo', set(['admin']), func)

request = MagicMock()
request.headers = {}
request.headers["Authorization"] = "Bearer 123"
app = MagicMock()
monkeypatch.setattr('flask.current_app', app)

session = MagicMock()
session.get = get_tokeninfo_response
monkeypatch.setattr('connexion.decorators.security.session', session)

with pytest.raises(OAuthScopeProblem, message="Provided token doesn't have the required scope"):
wrapped_func(request)

tokeninfo["scope"] += " admin"
wrapped_func(request)

tokeninfo["scope"] = ["foo", "bar"]
with pytest.raises(OAuthScopeProblem, message="Provided token doesn't have the required scope"):
wrapped_func(request)

tokeninfo["scope"].append("admin")
wrapped_func(request)

0 comments on commit ca862c4

Please sign in to comment.