Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mypy #612

Merged
merged 4 commits into from
Feb 18, 2019
Merged

Mypy #612

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ install:
- pip install tox

env:
- TOXENV=py34
- TOXENV=py36
- TOXENV=quality
- TOXENV=docs
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ The format is based on the [KeepAChangeLog] project.

### Changed
- [#578] Dropped python 2.7 support
- [#612] Dropped python 3.4 support
- [#588] Switch to defusedxml for XML parsing
- [#605] Message.c_param dictionary values have to be a ParamDefinition namedtuple type

Expand All @@ -28,6 +29,7 @@ The format is based on the [KeepAChangeLog] project.
[#605]: https://github.com/OpenIDC/pyoidc/pull/605
[#605]: https://github.com/OpenIDC/pyoidc/issues/607
[#441]: https://github.com/OpenIDC/pyoidc/issues/441
[#612]: https://github.com/OpenIDC/pyoidc/pull/612

## 0.15.1 [2019-01-31]

Expand Down
2 changes: 0 additions & 2 deletions appveyor.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
environment:
matrix:
- PYTHON: "C:\\Python34-x64"
PYTHON_ARCH: "64"
- PYTHON: "C:\\Python35-x64"
PYTHON_ARCH: "64"
- PYTHON: "C:\\Python36-x64"
Expand Down
2 changes: 2 additions & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[mypy]
ignore_missing_imports = True
5 changes: 2 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,16 @@ def run_tests(self):
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: Software Development :: Libraries :: Python Modules"],
python_requires='~=3.4',
python_requires='~=3.5',
extras_require={
'develop': ["cherrypy==3.2.4", "pyOpenSSL"],
'testing': tests_requires,
'docs': ['Sphinx', 'sphinx-autobuild', 'alabaster'],
'quality': ['pylama', 'isort', 'eradicate'],
'quality': ['pylama', 'isort', 'eradicate', 'mypy'],
'ldap_authn': ['pyldap'],
},
install_requires=[
Expand Down
2 changes: 1 addition & 1 deletion src/oic/extension/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import traceback
from functools import cmp_to_key
from urllib.parse import parse_qs
from urllib.parse import splitquery
from urllib.parse import splitquery # type: ignore

from jwkest import b64e
from jwkest import jws
Expand Down
3 changes: 2 additions & 1 deletion src/oic/extension/sts.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from oic.oauth2.message import SINGLE_OPTIONAL_STRING
from oic.oauth2.message import SINGLE_REQUIRED_STRING
from oic.oauth2.message import Message
from oic.oauth2.message import ParamDefinition
from oic.oic.message import SINGLE_REQUIRED_INT
from oic.oic.message import msg_ser

Expand Down Expand Up @@ -64,7 +65,7 @@ def sts_deser(val, sformat="json"):
return STS().deserialize(val, sformat)


SINGLE_OPTIONAL_STS = (Message, False, msg_ser, sts_deser, False)
SINGLE_OPTIONAL_STS = ParamDefinition(Message, False, msg_ser, sts_deser, False)


class STS(Message):
Expand Down
8 changes: 5 additions & 3 deletions src/oic/oauth2/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import logging
from collections import MutableMapping
from collections import namedtuple
from typing import Any # noqa - This is used for MyPy
from typing import Mapping # noqa - This is used for MyPy
from urllib.parse import parse_qs
from urllib.parse import urlencode

Expand Down Expand Up @@ -126,9 +128,9 @@ def jwt_header(txt):


class Message(MutableMapping):
c_param = {}
c_default = {}
c_allowed_values = {}
c_param = {} # type: Mapping[str, ParamDefinition]
c_default = {} # type: Mapping[str, Any]
c_allowed_values = {} # type: ignore

def __init__(self, **kwargs):
self._dict = self.c_default.copy()
Expand Down
16 changes: 8 additions & 8 deletions src/oic/oauth2/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import traceback
import warnings
from urllib.parse import parse_qs
from urllib.parse import splitquery
from urllib.parse import splitquery # type: ignore
from urllib.parse import unquote
from urllib.parse import urljoin
from urllib.parse import urlparse
Expand Down Expand Up @@ -786,8 +786,8 @@ def token_endpoint(self, authn="", **kwargs):
logger.debug("AccessTokenRequest: %s" % sanitize(areq))

if areq["grant_type"] != "authorization_code":
err = TokenErrorResponse(error="invalid_request", error_description="Wrong grant type")
return Response(err.to_json(), content="application/json", status="401 Unauthorized")
error = TokenErrorResponse(error="invalid_request", error_description="Wrong grant type")
return Response(error.to_json(), content="application/json", status="401 Unauthorized")

# assert that the code is valid
_info = _sdb[areq["code"]]
Expand All @@ -800,15 +800,15 @@ def token_endpoint(self, authn="", **kwargs):
# verify that the one given here is the correct one.
if "redirect_uri" in _info and areq["redirect_uri"] != _info["redirect_uri"]:
logger.error('Redirect_uri mismatch')
err = TokenErrorResponse(error="unauthorized_client")
return Unauthorized(err.to_json(), content="application/json")
error = TokenErrorResponse(error="unauthorized_client")
return Unauthorized(error.to_json(), content="application/json")

try:
_tinfo = _sdb.upgrade_to_token(areq["code"], issue_refresh=True)
except AccessCodeUsed:
err = TokenErrorResponse(error="invalid_grant",
error_description="Access grant used")
return Response(err.to_json(), content="application/json",
error = TokenErrorResponse(error="invalid_grant",
error_description="Access grant used")
return Response(error.to_json(), content="application/json",
status="401 Unauthorized")

logger.debug("_tinfo: %s" % sanitize(_tinfo))
Expand Down
2 changes: 1 addition & 1 deletion src/oic/oauth2/util.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging
from http import cookiejar as http_cookiejar
from http.cookiejar import http2time
from http.cookiejar import http2time # type: ignore
from urllib.parse import parse_qs
from urllib.parse import urlsplit
from urllib.parse import urlunsplit
Expand Down
14 changes: 3 additions & 11 deletions src/oic/oic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,7 @@
from base64 import b64encode
from urllib.parse import urlparse
from urllib.parse import parse_qs


from oic.utils.http_util import Response

try:
from json import JSONDecodeError
except ImportError: # Only works for >= 3.5
_decode_err = ValueError
else:
_decode_err = JSONDecodeError
from json import JSONDecodeError

from jwkest.jwe import JWE
from jwkest import jws, as_bytes
Expand Down Expand Up @@ -70,6 +61,7 @@
from oic.exception import RegistrationError
from oic.exception import RequestError
from oic.utils import time_util
from oic.utils.http_util import Response
from oic.utils.keyio import KeyJar
from oic.utils.sanitize import sanitize
from oic.utils.webfinger import OIC_ISSUER
Expand Down Expand Up @@ -1243,7 +1235,7 @@ def handle_registration_info(self, response):
elif 400 <= response.status_code <= 499:
try:
resp = ErrorResponse().deserialize(response.text, "json")
except _decode_err:
except JSONDecodeError:
logger.error(unk_msg.format(sanitize(response.text)))
raise RegistrationError(response.text)

Expand Down
15 changes: 8 additions & 7 deletions src/oic/oic/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@
import sys
import time
import traceback
import warnings
from functools import cmp_to_key
from urllib.parse import parse_qs
from urllib.parse import splitquery
from urllib.parse import splitquery # type: ignore
from urllib.parse import unquote
from urllib.parse import urlencode
from urllib.parse import urljoin
Expand Down Expand Up @@ -247,9 +248,12 @@ def __init__(self, name, sdb, cdb, authn_broker, userinfo, authz,
self.extra_claims = extra_claims
self.extra_scope_dict = extra_scope_dict

self.register_endpoint = None
for endp in self.endp:
if endp.etype == 'registration':
endpoint = urljoin(self.baseurl, endp.url)
warnings.warn("Using `register_endpoint` is deprecated, please use `registration_endpoint` instead.",
DeprecationWarning)
self.register_endpoint = endpoint
break

Expand Down Expand Up @@ -1106,9 +1110,9 @@ def token_endpoint(self, request="", authn=None, dtype='urlencoded',

if not client_id:
logger.error('No client_id, authentication failed')
err = TokenErrorResponse(error="unauthorized_client",
error_description=msg)
return Unauthorized(err.to_json(), content="application/json")
error = TokenErrorResponse(error="unauthorized_client",
error_description=msg)
return Unauthorized(error.to_json(), content="application/json")

if "client_id" not in req: # Optional for access token request
req["client_id"] = client_id
Expand Down Expand Up @@ -2025,9 +2029,6 @@ def key_setup(self, local_path, vault="keys", sig=None, enc=None):
self.jwks_uri = key_export(self.baseurl, local_path, vault, self.keyjar,
fqdn=self.hostname, sig=sig, enc=enc)

def register_endpoint(self, request="", **kwargs):
pass

def endsession_endpoint(self, request="", **kwargs):
"""

Expand Down
2 changes: 1 addition & 1 deletion src/oic/utils/client_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import sys
from builtins import input
from urllib.parse import parse_qs
from urllib.parse import splitquery
from urllib.parse import splitquery # type: ignore
from urllib.parse import urlparse

from oic import rndstr
Expand Down
12 changes: 6 additions & 6 deletions src/oic/utils/http_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@


class Response(object):
_template = None
_template = ''
_status_code = 200
_content_type = 'text/html'
_mako_template = None
Expand Down Expand Up @@ -546,16 +546,16 @@ def wsgi_wrapper(environ, start_response, func, **kwargs):


class CookieDealer(object):
def getServer(self):

@property
def srv(self):
return self._srv

def setServer(self, server):
@srv.setter
def srv(self, server):
self._srv = server

srv = property(getServer, setServer)

def __init__(self, srv, ttl=5, secure=True, httponly=True):
self.srv = None
self.init_srv(srv)
# minutes before the interaction should be completed
self.cookie_ttl = ttl # N minutes
Expand Down
2 changes: 1 addition & 1 deletion src/oic/utils/userinfo/aa_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
class AaUserInfo(UserInfo):
pass
else:
class AaUserInfo(UserInfo):
class AaUserInfo(UserInfo): # type: ignore
def __init__(self, spconf, url, db=None):
UserInfo.__init__(self, db)

Expand Down
4 changes: 3 additions & 1 deletion src/oic/utils/webfinger.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import json
import logging
import re
from typing import Any # noqa - Used for MyPy
from typing import Mapping # noqa - Used for MyPy
from urllib.parse import urlencode
from urllib.parse import urlparse

Expand All @@ -22,7 +24,7 @@ class WebFingerError(PyoidcError):


class Base(object):
c_param = {}
c_param = {} # type: Mapping[str, Mapping[str, Any]]

def __init__(self, dic=None):
self._ava = {}
Expand Down
6 changes: 3 additions & 3 deletions tests/test_authn_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@

try:
from oic.utils.authn.ldap_member import UserLDAPMemberValidation
SKIP_LDAP = False
except ImportError:
UserLDAPMemberValidation = None
SKIP_LDAP = True


class TestAuthnBroker(object):
@pytest.mark.skipif("UserLDAPMemberValidation is None",
reason="LDAP support missing")
@pytest.mark.skipif(SKIP_LDAP, reason="LDAP support missing")
def test(self):
ac = AuthnBroker()
issuer = "https://example.com/op"
Expand Down
2 changes: 1 addition & 1 deletion tests/test_util.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from http.cookiejar import FileCookieJar
from http.cookiejar import http2time
from http.cookiejar import http2time # type: ignore
from http.cookies import SimpleCookie
from urllib.parse import parse_qs
from urllib.parse import urlparse
Expand Down
1 change: 1 addition & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ extras = quality
commands =
isort --recursive --diff --check-only src/ tests/
pylama src/ tests/
mypy --config-file mypy.ini src/ tests/

[pep8]
max-line-length=100
Expand Down