Skip to content

Commit

Permalink
Merge pull request #30 from kevgliss/py3
Browse files Browse the repository at this point in the history
Making Lemur py3 compatible
  • Loading branch information
kevgliss committed Aug 4, 2015
2 parents 51cb821 + 63b1bab commit 3ebbbd2
Show file tree
Hide file tree
Showing 16 changed files with 81 additions and 87 deletions.
19 changes: 16 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,23 +1,36 @@
sudo: false

language: python

addons:
postgresql: "9.4"
python:
- "2.7"

matrix:
include:
- python: "2.7"
env: TOXENV=py27
- python: "3.3"
env: TOXENV=py33
- python: "3.4"
env: TOXENV=py34

cache:
directories:
- node_modules
- .pip_download_cache
- "$HOME/virtualenv/python2.7.9"

env:
global:
- PIP_DOWNLOAD_CACHE=".pip_download_cache"

install:
- make dev-postgres

before_script:
- psql -c "create database lemur;" -U postgres
- psql -c "create user lemur with password 'lemur;'" -U postgres
- npm install -g bower

script:
- make test

Expand Down
16 changes: 8 additions & 8 deletions lemur/auth/permissions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
.. module: permissions
.. module: lemur.auth.permissions
:platform: Unix
:synopsis: This module defines all the permission used within Lemur
:copyright: (c) 2015 by Netflix Inc., see AUTHORS for more
Expand All @@ -24,15 +24,15 @@

class ViewKeyPermission(Permission):
def __init__(self, role_id, certificate_id):
c_need = CertificateCreatorNeed(unicode(certificate_id))
o_need = CertificateOwnerNeed(unicode(role_id))
c_need = CertificateCreatorNeed(str(certificate_id))
o_need = CertificateOwnerNeed(str(role_id))
super(ViewKeyPermission, self).__init__(o_need, c_need, RoleNeed('admin'))


class UpdateCertificatePermission(Permission):
def __init__(self, role_id, certificate_id):
c_need = CertificateCreatorNeed(unicode(certificate_id))
o_need = CertificateOwnerNeed(unicode(role_id))
c_need = CertificateCreatorNeed(str(certificate_id))
o_need = CertificateOwnerNeed(str(role_id))
super(UpdateCertificatePermission, self).__init__(o_need, c_need, RoleNeed('admin'))


Expand All @@ -42,7 +42,7 @@ def __init__(self, role_id, certificate_id):

class ViewRoleCredentialsPermission(Permission):
def __init__(self, role_id):
need = ViewRoleCredentialsNeed(unicode(role_id))
need = ViewRoleCredentialsNeed(str(role_id))
super(ViewRoleCredentialsPermission, self).__init__(need, RoleNeed('admin'))


Expand All @@ -55,8 +55,8 @@ def __init__(self, role_id):

class AuthorityPermission(Permission):
def __init__(self, authority_id, roles):
needs = [RoleNeed('admin'), AuthorityCreatorNeed(unicode(authority_id))]
needs = [RoleNeed('admin'), AuthorityCreatorNeed(str(authority_id))]
for r in roles:
needs.append(AuthorityOwnerNeed(unicode(r)))
needs.append(AuthorityOwnerNeed(str(r)))

super(AuthorityPermission, self).__init__(*needs)
16 changes: 10 additions & 6 deletions lemur/auth/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import json
import base64
import binascii
from builtins import str

from functools import wraps
from datetime import datetime, timedelta

Expand All @@ -32,7 +34,7 @@


def base64url_decode(data):
if isinstance(data, unicode):
if isinstance(data, str):
data = str(data)

rem = len(data) % 4
Expand Down Expand Up @@ -139,7 +141,9 @@ def fetch_token_header(token):

try:
return json.loads(base64url_decode(header_segment))
except TypeError, binascii.Error:
except TypeError:
raise jwt.DecodeError('Invalid header padding')
except binascii.Error:
raise jwt.DecodeError('Invalid header padding')


Expand All @@ -161,19 +165,19 @@ def on_identity_loaded(sender, identity):
# identity with the roles that the user provides
if hasattr(user, 'roles'):
for role in user.roles:
identity.provides.add(CertificateOwnerNeed(unicode(role.id)))
identity.provides.add(ViewRoleCredentialsNeed(unicode(role.id)))
identity.provides.add(CertificateOwnerNeed(role.id))
identity.provides.add(ViewRoleCredentialsNeed(role.id))
identity.provides.add(RoleNeed(role.name))

# apply ownership for authorities
if hasattr(user, 'authorities'):
for authority in user.authorities:
identity.provides.add(AuthorityCreatorNeed(unicode(authority.id)))
identity.provides.add(AuthorityCreatorNeed(authority.id))

# apply ownership of certificates
if hasattr(user, 'certificates'):
for certificate in user.certificates:
identity.provides.add(CertificateCreatorNeed(unicode(certificate.id)))
identity.provides.add(CertificateCreatorNeed(certificate.id))

g.user = user

Expand Down
10 changes: 8 additions & 2 deletions lemur/certificates/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"""
import os
import datetime

from cryptography import x509
from cryptography.hazmat.backends import default_backend

Expand Down Expand Up @@ -56,7 +57,10 @@ def create_name(issuer, not_before, not_after, subject, san):
disallowed_chars = disallowed_chars.replace("-", "")
disallowed_chars = disallowed_chars.replace(".", "")
temp = temp.replace('*', "WILDCARD")
temp = temp.translate(None, disallowed_chars)

for c in disallowed_chars:
temp = temp.replace(c, "")

# white space is silly too
return temp.replace(" ", "-")

Expand Down Expand Up @@ -151,7 +155,9 @@ def cert_get_issuer(cert):
delchars = ''.join(c for c in map(chr, range(256)) if not c.isalnum())
try:
issuer = str(cert.issuer.get_attributes_for_oid(x509.OID_ORGANIZATION_NAME)[0].value)
return issuer.translate(None, delchars)
for c in delchars:
issuer = issuer.replace(c, "")
return issuer
except Exception as e:
current_app.logger.error("Unable to get issuer! {0}".format(e))

Expand Down
14 changes: 7 additions & 7 deletions lemur/certificates/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,15 +304,15 @@ def create_csr(csr_config):
backend=default_backend()
)

# TODO When we figure out a better way to validate these options they should be parsed as unicode
# TODO When we figure out a better way to validate these options they should be parsed as str
builder = x509.CertificateSigningRequestBuilder()
builder = builder.subject_name(x509.Name([
x509.NameAttribute(x509.OID_COMMON_NAME, unicode(csr_config['commonName'])),
x509.NameAttribute(x509.OID_ORGANIZATION_NAME, unicode(csr_config['organization'])),
x509.NameAttribute(x509.OID_ORGANIZATIONAL_UNIT_NAME, unicode(csr_config['organizationalUnit'])),
x509.NameAttribute(x509.OID_COUNTRY_NAME, unicode(csr_config['country'])),
x509.NameAttribute(x509.OID_STATE_OR_PROVINCE_NAME, unicode(csr_config['state'])),
x509.NameAttribute(x509.OID_LOCALITY_NAME, unicode(csr_config['location'])),
x509.NameAttribute(x509.OID_COMMON_NAME, csr_config['commonName']),
x509.NameAttribute(x509.OID_ORGANIZATION_NAME, csr_config['organization']),
x509.NameAttribute(x509.OID_ORGANIZATIONAL_UNIT_NAME, csr_config['organizationalUnit']),
x509.NameAttribute(x509.OID_COUNTRY_NAME, csr_config['country']),
x509.NameAttribute(x509.OID_STATE_OR_PROVINCE_NAME, csr_config['state']),
x509.NameAttribute(x509.OID_LOCALITY_NAME, csr_config['location']),
]))

builder = builder.add_extension(
Expand Down
6 changes: 4 additions & 2 deletions lemur/certificates/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from builtins import str

from flask import Blueprint, make_response, jsonify
from flask.ext.restful import reqparse, Api, fields

Expand Down Expand Up @@ -75,7 +77,7 @@ def pem_str(value, name):
:return: :raise ValueError:
"""
try:
x509.load_pem_x509_certificate(str(value), default_backend())
x509.load_pem_x509_certificate(bytes(value), default_backend())
except Exception:
raise ValueError("The parameter '{0}' needs to be a valid PEM string".format(name))
return value
Expand All @@ -90,7 +92,7 @@ def private_key_str(value, name):
:return: :raise ValueError:
"""
try:
serialization.load_pem_private_key(str(value), None, backend=default_backend())
serialization.load_pem_private_key(bytes(value), None, backend=default_backend())
except Exception:
raise ValueError("The parameter '{0}' needs to be a valid RSA private key".format(name))
return value
Expand Down
2 changes: 1 addition & 1 deletion lemur/common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def wrapper(*args, **kwargs):
else:
return {'message': 'unknown'}, 400
else:
return {'message': e.message}, 400
return {'message': str(e)}, 400
return wrapper


Expand Down
6 changes: 4 additions & 2 deletions lemur/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
:copyright: (c) 2015 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
"""
from builtins import str

from datetime import timedelta
from flask import make_response, request, current_app

Expand All @@ -16,10 +18,10 @@ def crossdomain(origin=None, methods=None, headers=None,
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))

if headers is not None and not isinstance(headers, basestring):
if headers is not None and not isinstance(headers, str):
headers = ', '.join(x.upper() for x in headers)

if not isinstance(origin, basestring):
if not isinstance(origin, str):
origin = ', '.join(origin)

if isinstance(max_age, timedelta):
Expand Down
2 changes: 1 addition & 1 deletion lemur/plugins/lemur_aws/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
try:
VERSION = __import__('pkg_resources') \
.get_distribution(__name__).version
except Exception, e:
except Exception as e:
VERSION = 'unknown'
2 changes: 1 addition & 1 deletion lemur/plugins/lemur_cloudca/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
try:
VERSION = __import__('pkg_resources') \
.get_distribution(__name__).version
except Exception, e:
except Exception as e:
VERSION = 'unknown'
2 changes: 1 addition & 1 deletion lemur/plugins/lemur_email/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
try:
VERSION = __import__('pkg_resources') \
.get_distribution(__name__).version
except Exception, e:
except Exception as e:
VERSION = 'unknown'
2 changes: 1 addition & 1 deletion lemur/plugins/lemur_verisign/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
try:
VERSION = __import__('pkg_resources') \
.get_distribution(__name__).version
except Exception, e:
except Exception as e:
VERSION = 'unknown'
50 changes: 6 additions & 44 deletions lemur/tests/certs.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from cryptography import x509
from cryptography.hazmat.backends import default_backend

INTERNAL_VALID_LONG_STR = """
INTERNAL_VALID_LONG_STR = b"""
-----BEGIN CERTIFICATE-----
MIID1zCCAr+gAwIBAgIBATANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UEBhMCVVMx
CzAJBgNVBAgMAkNBMRAwDgYDVQQHDAdBIHBsYWNlMRcwFQYDVQQDDA5sb25nLmxp
Expand Down Expand Up @@ -29,7 +29,7 @@
INTERNAL_VALID_LONG_CERT = x509.load_pem_x509_certificate(INTERNAL_VALID_LONG_STR, default_backend())


INTERNAL_INVALID_STR = """
INTERNAL_INVALID_STR = b"""
-----BEGIN CERTIFICATE-----
MIIEFTCCAv2gAwIBAgICA+gwDQYJKoZIhvcNAQELBQAwgYwxCzAJBgNVBAYTAlVT
MQswCQYDVQQIDAJDQTEQMA4GA1UEBwwHQSBwbGFjZTEXMBUGA1UEAwwObG9uZy5s
Expand Down Expand Up @@ -58,7 +58,7 @@
INTERNAL_INVALID_CERT = x509.load_pem_x509_certificate(INTERNAL_INVALID_STR, default_backend())


INTERNAL_VALID_SAN_STR = """
INTERNAL_VALID_SAN_STR = b"""
-----BEGIN CERTIFICATE-----
MIIESjCCAzKgAwIBAgICA+kwDQYJKoZIhvcNAQELBQAwgYwxCzAJBgNVBAYTAlVT
MQswCQYDVQQIDAJDQTEQMA4GA1UEBwwHQSBwbGFjZTEXMBUGA1UEAwwObG9uZy5s
Expand Down Expand Up @@ -88,7 +88,7 @@
INTERNAL_VALID_SAN_CERT = x509.load_pem_x509_certificate(INTERNAL_VALID_SAN_STR, default_backend())


INTERNAL_VALID_WILDCARD_STR = """
INTERNAL_VALID_WILDCARD_STR = b"""
-----BEGIN CERTIFICATE-----
MIIEHDCCAwSgAwIBAgICA+owDQYJKoZIhvcNAQELBQAwgYwxCzAJBgNVBAYTAlVT
MQswCQYDVQQIDAJDQTEQMA4GA1UEBwwHQSBwbGFjZTEXMBUGA1UEAwwObG9uZy5s
Expand Down Expand Up @@ -117,7 +117,7 @@
INTERNAL_VALID_WILDCARD_CERT = x509.load_pem_x509_certificate(INTERNAL_VALID_WILDCARD_STR, default_backend())


EXTERNAL_VALID_STR = """
EXTERNAL_VALID_STR = b"""
-----BEGIN CERTIFICATE-----
MIIFHzCCBAegAwIBAgIQGFWCciDWzbOej/TbAJN0WzANBgkqhkiG9w0BAQsFADCB
pDELMAkGA1UEBhMCVVMxHTAbBgNVBAoTFFN5bWFudGVjIENvcnBvcmF0aW9uMR8w
Expand Down Expand Up @@ -152,7 +152,7 @@
EXTERNAL_CERT = x509.load_pem_x509_certificate(EXTERNAL_VALID_STR, default_backend())


PRIVATE_KEY_STR = """
PRIVATE_KEY_STR = b"""
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAnEjM0cQevlDjT6mDMtTo8N1ovAyKbfVEp0ketCPC4hLkStms
q9ETIyyerARIMv4SEhKqS4E7HIg6ccGkwv1ja5E/b2jHMH4ht1dEXnfM2yh0Mwvk
Expand Down Expand Up @@ -181,41 +181,3 @@
XKxcRgm/Va4QMEAnec0qXfdTVJaJiAW0bdKwKRRrrbwcTdNRGibdng==
-----END RSA PRIVATE KEY-----
"""

CSR_CONFIG = """
# Configuration for standard CSR generation for Netflix
# Used for procuring VeriSign certificates
# Author: jbob
# Contact: security@example.com
[ req ]
# Use a 2048 bit private key
default_bits = 2048
default_keyfile = key.pem
prompt = no
encrypt_key = no
# base request
distinguished_name = req_distinguished_name
# extensions
# Uncomment the following line if you are requesting a SAN cert
#req_extensions = req_ext
# distinguished_name
[ req_distinguished_name ]
countryName = "US" # C=
stateOrProvinceName = "CALIFORNIA" # ST=
localityName = "A place" # L=
organizationName = "Example, Inc." # O=
organizationalUnitName = "Operations" # OU=
# This is the hostname/subject name on the certificate
commonName = "example.net" # CN=
[ req_ext ]
# Uncomment the following line if you are requesting a SAN cert
#subjectAltName = @alt_names
[alt_names]
# Put your SANs here
"""
Loading

0 comments on commit 3ebbbd2

Please sign in to comment.