Skip to content
Permalink
Browse files

Fix: #154. Reformat code and make build green

  - Ignore lines too long in setup.cfg
  - Add a tox env to reformat code with autopep8 and isort
  - Add #noqa when delegating fixes to the actual team.
  • Loading branch information...
ioggstream committed Sep 18, 2018
1 parent 0e82f60 commit 907067f74624ccefaba59585ed193d4d968bee00
@@ -1,6 +1,9 @@
[flake8]
exclude = *.egg-info
max-line-length = 119
ignore =
E501 # Line too long


[isort]
line_length = 119
@@ -12,6 +12,7 @@


class ConfigValidator(object):

def __init__(self, confdata):
self._confdata = confdata
self._init_schema()
@@ -53,7 +54,8 @@ def check_https(data):
key_path = data.get('https_key_file')
cert_path = data.get('https_cert_file')
if https and not all([key_path, cert_path]):
raise Invalid('Errore modalità HTTPS: chiave e/o certificato assenti')
raise Invalid(
'Errore modalità HTTPS: chiave e/o certificato assenti')
return data

def check_endpoints(data):
@@ -90,6 +92,7 @@ def _validate(self):


class Config(object):

def __init__(self, confdata):
self._confdata = confdata
self._idp_key = self._load_idp_key()
@@ -99,7 +102,8 @@ def _load_idp_key(self):
try:
return self._read_file_bytes(self.idp_key_file_path)
except Exception:
self._fail('Impossibile ottenere la chiave privata dal file {}'.format(self.key_file_path))
self._fail('Impossibile ottenere la chiave privata dal file {}'.format(
self.key_file_path))

@staticmethod
def _read_file_bytes(path):
@@ -118,7 +122,8 @@ def _load_idp_certificate(self):
try:
return self._read_file_bytes(self.idp_certificate_file_path)
except Exception:
self._fail('Impossibile ottenere il certificato dal file {}'.format(self.cert_file_path))
self._fail('Impossibile ottenere il certificato dal file {}'.format(
self.cert_file_path))

@property
def idp_certificate_file_path(self):
@@ -233,6 +238,7 @@ def receivers(self, service):


class BaseConfigParser(object):

def __init__(self, path):
self._path = path
self._fp = None
@@ -241,9 +247,11 @@ def parse(self):
try:
return self._parse()
except OSError:
raise BadConfiguration('Impossibile accedere al file di configurazione: {}'.format(self._path))
raise BadConfiguration(
'Impossibile accedere al file di configurazione: {}'.format(self._path))
except Exception:
raise BadConfiguration('Errore di sintassi nel file di configurazione: {}'.format(self._path))
raise BadConfiguration(
'Errore di sintassi nel file di configurazione: {}'.format(self._path))

def _parse(self):
with open(self._path, 'r') as fp:
@@ -252,11 +260,13 @@ def _parse(self):


class YAMLConfigParser(BaseConfigParser):

def _deserialize(self):
return yaml.load(self._fp)


class JSONConfigParser(BaseConfigParser):

def _deserialize(self):
return json.load(self._fp.read())

@@ -56,6 +56,7 @@ def normalize_x509(cert):


class RSASigner(object):

def __init__(self, digest, key=None, padding=None):
self._key = key
self._digest = digest
@@ -68,6 +69,7 @@ def sign(self, unsigned_data, key=None):


class RSAVerifier(object):

def __init__(self, digest, padding=None):
self._digest = digest
self._padding = padding or PKCS1v15()
@@ -141,6 +143,7 @@ def sign_http_redirect(xmlstr, key, relay_state=None, req_type='SAMLResponse'):


class HTTPRedirectSignatureVerifier(object):

def __init__(self, certificate, request, verifiers=None):
self._cert = certificate
self._request = request
@@ -192,6 +195,7 @@ def _get_pubkey(self):


class HTTPPostSignatureVerifier(object):

def __init__(self, certificate, request, verifier=None):
self._cert = certificate
self._request = request
@@ -15,6 +15,7 @@ class RequestParserError(TestenvError):


class DeserializationError(TestenvError):

def __init__(self, initial_data, details):
super(DeserializationError, self).__init__()
self.initial_data = initial_data
@@ -58,6 +59,7 @@ class UnknownEntityIDError(TestenvError):


class MetadataNotFoundError(TestenvError):

def __init__(self, entity_id):
self.entity_id = entity_id

@@ -27,7 +27,8 @@
)


HTTPPostRequest = namedtuple('HTTPPostRequest', ['saml_request', 'relay_state'])
HTTPPostRequest = namedtuple(
'HTTPPostRequest', ['saml_request', 'relay_state'])


def _get_deserializer(request, action, binding):
@@ -49,6 +50,7 @@ def get_http_post_request_deserializer(request, action):


class HTTPRedirectRequestParser(object):

def __init__(self, querystring, request_class=None):
self._querystring = querystring
self._request_class = request_class or HTTPRedirectRequest
@@ -130,6 +132,7 @@ def _build_request(self):


class HTTPPostRequestParser(object):

def __init__(self, form, request_class=None):
self._form = form
self._request_class = request_class or HTTPPostRequest
@@ -177,6 +180,7 @@ def _build_request(self):


class HTTPRequestDeserializer(object):

def __init__(self, request, validator, saml_class=None):
self._request = request
self._validator = validator
@@ -201,6 +205,7 @@ def _deserialize(self):


class SAMLTree(object):

def __init__(self, xml_doc, multi_occur_tags=None):
self._xml_doc = xml_doc
self._multi_occur_tags = multi_occur_tags or MULTIPLE_OCCURRENCES_TAGS
@@ -276,7 +276,7 @@ def create_response(data, response_status, attributes={}):
InResponseTo=response_attrs.get('in_response_to')
)
)

# Setup issuer data
issuer_attrs = data.get('issuer').get('attrs')
issuer = Issuer(
@@ -286,7 +286,7 @@ def create_response(data, response_status, attributes={}):
text=data.get('issuer').get('text')
)
response.append(issuer)

# Setup status data
status = Status()
status_code_value = response_status.get('status_code')
@@ -297,7 +297,7 @@ def create_response(data, response_status, attributes={}):
)
status.append(status_code)
response.append(status)

# Create and setup the assertion
assertion = Assertion(
attrib=dict(
@@ -316,7 +316,8 @@ def create_response(data, response_status, attributes={}):
)
subject.append(name_id)
subject_confirmation = SubjectConfirmation()
subject_confirmation_data_attrs = data.get('subject_confirmation_data').get('attrs')
subject_confirmation_data_attrs = data.get(
'subject_confirmation_data').get('attrs')
subject_confirmation_data = SubjectConfirmationData(
attrib=dict(
Recipient=subject_confirmation_data_attrs.get('recipient'),
@@ -491,7 +492,6 @@ class RequestedAttribute(SamlMixin):
saml_type = 'md'



def create_idp_metadata(
entity_id,
want_authn_requests_signed,
@@ -127,7 +127,8 @@ def _verify_spid(self, level, verify=False, **kwargs):
:param kwargs: dictionary, extra arguments
"""
level = self._spid_levels.index(level)
self.app.logger.debug('spid level {} - verifica ({})'.format(level, verify))
self.app.logger.debug(
'spid level {} - verifica ({})'.format(level, verify))
if verify:
# Verify the challenge
if level == 2:
@@ -156,9 +157,9 @@ def _verify_spid(self, level, verify=False, **kwargs):
otp = ''.join(random.choice(string.digits) for _ in range(6))
self.challenges[key] = [otp, datetime.now()]
extra_challenge = '<span>Otp ({})</span>'\
'<input type="text" name="otp" />'.format(
otp
)
'<input type="text" name="otp" />'.format(
otp
)
else:
extra_challenge = ''
return extra_challenge
@@ -179,7 +180,7 @@ def _raise_error(self, msg, extra=None):

abort(
Response(
render_template(
render_template(
"error.html",
**{'msg': msg, 'extra': extra or ""}
), 200
@@ -206,8 +207,8 @@ def _handle_errors(self, xmlstr, errors=None):
**{
'lines': xmlstr.splitlines(),
'errors': errors
}
)
}
)
return rendered_error_response

def _parse_message(self, action):
@@ -236,7 +237,8 @@ def _handle_http_redirect(self, action):
# about request parsing *at all*.
saml_msg = self.unpack_args(request.args)
request_data = HTTPRedirectRequestParser(saml_msg).parse()
deserializer = get_http_redirect_request_deserializer(request_data, action)
deserializer = get_http_redirect_request_deserializer(
request_data, action)
saml_tree = deserializer.deserialize()
certs = self._get_certificates_by_issuer(saml_tree.issuer.text)
if not certs:
@@ -267,12 +269,12 @@ def _get_certificates_by_issuer(self, issuer):
return self._registry.get(issuer).certs()
except KeyError:
self._raise_error(
'entity ID {} non registrato, impossibile ricavare'\
'entity ID {} non registrato, impossibile ricavare'
' un certificato valido.'.format(issuer)
)
except NoCertificateError:
self._raise_error(
'Errore, il metadata associato al Service provider non'\
'Errore, il metadata associato al Service provider non'
' non è provvisto di certificati validi'.format(issuer)
)

@@ -357,7 +359,8 @@ def users(self):
if spid_value:
extra[spid_field] = spid_value
if 'fiscalNumber' in extra:
extra['fiscalNumber'] = 'TINIT-{}'.format(extra['fiscalNumber'])
extra[
'fiscalNumber'] = 'TINIT-{}'.format(extra['fiscalNumber'])
self.user_manager.add(username, password, sp, extra.copy())
return redirect(url_for('users'))

@@ -379,7 +382,8 @@ def get_destination(self, req, sp_id):
acs_index = getattr(req, 'assertion_consumer_service_index', None)
protocol_binding = getattr(req, 'protocol_binding', None)
if acs_index is not None:
acss = self._registry.get(sp_id).assertion_consumer_service(index=acs_index)
acss = self._registry.get(
sp_id).assertion_consumer_service(index=acs_index)
if acss:
destination = acss[0].get('Location')
self.app.logger.debug(
@@ -420,7 +424,8 @@ def login(self):
spid_level = authn_context.authn_context_class_ref.text
if request.method == 'GET':
# inject extra data in form login based on spid level
extra_challenge = self._verify_spid(level=spid_level, **{'key': key})
extra_challenge = self._verify_spid(
level=spid_level, **{'key': key})
rendered_form = render_template(
'login.html',
**{
@@ -453,7 +458,8 @@ def login(self):
self.app.logger.debug(
'Unfiltered data: {}'.format(identity)
)
atcs_idx = getattr(authn_request, 'attribute_consuming_service_index', None)
atcs_idx = getattr(
authn_request, 'attribute_consuming_service_index', None)
self.app.logger.debug(
'AttributeConsumingServiceIndex: {}'.format(
atcs_idx
@@ -477,12 +483,14 @@ def login(self):
try:
_identity[_key] = identity[_key]
except KeyError:
_identity[_key] = ('', self._attribute_type(_key))
_identity[_key] = (
'', self._attribute_type(_key))
for _key in optional:
try:
_identity[_key] = identity[_key]
except KeyError:
_identity[_key] = ('', self._attribute_type(_key))
_identity[_key] = (
'', self._attribute_type(_key))

self.app.logger.debug(
'Filtered data: {}'.format(_identity)
@@ -615,8 +623,8 @@ def continue_response(self):
auth_req, auth_req.issuer.text
)
error_info = get_spid_error(
AUTH_NO_CONSENT
)
AUTH_NO_CONSENT
)
response = create_error_response(
{
'response': {
@@ -661,7 +669,8 @@ def _sp_single_logout_service(self, issuer_name):
_slo = None
for binding in [BINDING_HTTP_POST, BINDING_HTTP_REDIRECT]:
try:
_slo = self._registry.get(issuer_name).single_logout_services[0]
_slo = self._registry.get(
issuer_name).single_logout_services[0]
except Exception:
pass
return _slo
@@ -678,7 +687,7 @@ def single_logout_service(self):
_slo = self._sp_single_logout_service(issuer_name)
if _slo is None:
self._raise_error(
'Impossibile trovare un servizio di'\
'Impossibile trovare un servizio di'
' Single Logout per il service provider {}'.format(
issuer_name
)
Oops, something went wrong.

0 comments on commit 907067f

Please sign in to comment.
You can’t perform that action at this time.