Black lint all the things
This commit is contained in:
@ -7,7 +7,17 @@
|
||||
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
|
||||
"""
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy import Column, Integer, String, Text, func, ForeignKey, DateTime, PassiveDefault, Boolean
|
||||
from sqlalchemy import (
|
||||
Column,
|
||||
Integer,
|
||||
String,
|
||||
Text,
|
||||
func,
|
||||
ForeignKey,
|
||||
DateTime,
|
||||
PassiveDefault,
|
||||
Boolean,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSON
|
||||
|
||||
from lemur.database import db
|
||||
@ -16,7 +26,7 @@ from lemur.models import roles_authorities
|
||||
|
||||
|
||||
class Authority(db.Model):
|
||||
__tablename__ = 'authorities'
|
||||
__tablename__ = "authorities"
|
||||
id = Column(Integer, primary_key=True)
|
||||
owner = Column(String(128), nullable=False)
|
||||
name = Column(String(128), unique=True)
|
||||
@ -27,22 +37,44 @@ class Authority(db.Model):
|
||||
description = Column(Text)
|
||||
options = Column(JSON)
|
||||
date_created = Column(DateTime, PassiveDefault(func.now()), nullable=False)
|
||||
roles = relationship('Role', secondary=roles_authorities, passive_deletes=True, backref=db.backref('authority'), lazy='dynamic')
|
||||
user_id = Column(Integer, ForeignKey('users.id'))
|
||||
authority_certificate = relationship("Certificate", backref='root_authority', uselist=False, foreign_keys='Certificate.root_authority_id')
|
||||
certificates = relationship("Certificate", backref='authority', foreign_keys='Certificate.authority_id')
|
||||
roles = relationship(
|
||||
"Role",
|
||||
secondary=roles_authorities,
|
||||
passive_deletes=True,
|
||||
backref=db.backref("authority"),
|
||||
lazy="dynamic",
|
||||
)
|
||||
user_id = Column(Integer, ForeignKey("users.id"))
|
||||
authority_certificate = relationship(
|
||||
"Certificate",
|
||||
backref="root_authority",
|
||||
uselist=False,
|
||||
foreign_keys="Certificate.root_authority_id",
|
||||
)
|
||||
certificates = relationship(
|
||||
"Certificate", backref="authority", foreign_keys="Certificate.authority_id"
|
||||
)
|
||||
|
||||
authority_pending_certificate = relationship("PendingCertificate", backref='root_authority', uselist=False, foreign_keys='PendingCertificate.root_authority_id')
|
||||
pending_certificates = relationship('PendingCertificate', backref='authority', foreign_keys='PendingCertificate.authority_id')
|
||||
authority_pending_certificate = relationship(
|
||||
"PendingCertificate",
|
||||
backref="root_authority",
|
||||
uselist=False,
|
||||
foreign_keys="PendingCertificate.root_authority_id",
|
||||
)
|
||||
pending_certificates = relationship(
|
||||
"PendingCertificate",
|
||||
backref="authority",
|
||||
foreign_keys="PendingCertificate.authority_id",
|
||||
)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
self.owner = kwargs['owner']
|
||||
self.roles = kwargs.get('roles', [])
|
||||
self.name = kwargs.get('name')
|
||||
self.description = kwargs.get('description')
|
||||
self.authority_certificate = kwargs['authority_certificate']
|
||||
self.plugin_name = kwargs['plugin']['slug']
|
||||
self.options = kwargs.get('options')
|
||||
self.owner = kwargs["owner"]
|
||||
self.roles = kwargs.get("roles", [])
|
||||
self.name = kwargs.get("name")
|
||||
self.description = kwargs.get("description")
|
||||
self.authority_certificate = kwargs["authority_certificate"]
|
||||
self.plugin_name = kwargs["plugin"]["slug"]
|
||||
self.options = kwargs.get("options")
|
||||
|
||||
@property
|
||||
def plugin(self):
|
||||
|
@ -11,7 +11,13 @@ from marshmallow import fields, validates_schema, pre_load
|
||||
from marshmallow import validate
|
||||
from marshmallow.exceptions import ValidationError
|
||||
|
||||
from lemur.schemas import PluginInputSchema, PluginOutputSchema, ExtensionSchema, AssociatedAuthoritySchema, AssociatedRoleSchema
|
||||
from lemur.schemas import (
|
||||
PluginInputSchema,
|
||||
PluginOutputSchema,
|
||||
ExtensionSchema,
|
||||
AssociatedAuthoritySchema,
|
||||
AssociatedRoleSchema,
|
||||
)
|
||||
from lemur.users.schemas import UserNestedOutputSchema
|
||||
from lemur.common.schema import LemurInputSchema, LemurOutputSchema
|
||||
from lemur.common import validators, missing
|
||||
@ -30,21 +36,36 @@ class AuthorityInputSchema(LemurInputSchema):
|
||||
validity_years = fields.Integer()
|
||||
|
||||
# certificate body fields
|
||||
organizational_unit = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_ORGANIZATIONAL_UNIT'))
|
||||
organization = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_ORGANIZATION'))
|
||||
location = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_LOCATION'))
|
||||
country = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_COUNTRY'))
|
||||
state = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_STATE'))
|
||||
organizational_unit = fields.String(
|
||||
missing=lambda: current_app.config.get("LEMUR_DEFAULT_ORGANIZATIONAL_UNIT")
|
||||
)
|
||||
organization = fields.String(
|
||||
missing=lambda: current_app.config.get("LEMUR_DEFAULT_ORGANIZATION")
|
||||
)
|
||||
location = fields.String(
|
||||
missing=lambda: current_app.config.get("LEMUR_DEFAULT_LOCATION")
|
||||
)
|
||||
country = fields.String(
|
||||
missing=lambda: current_app.config.get("LEMUR_DEFAULT_COUNTRY")
|
||||
)
|
||||
state = fields.String(missing=lambda: current_app.config.get("LEMUR_DEFAULT_STATE"))
|
||||
|
||||
plugin = fields.Nested(PluginInputSchema)
|
||||
|
||||
# signing related options
|
||||
type = fields.String(validate=validate.OneOf(['root', 'subca']), missing='root')
|
||||
type = fields.String(validate=validate.OneOf(["root", "subca"]), missing="root")
|
||||
parent = fields.Nested(AssociatedAuthoritySchema)
|
||||
signing_algorithm = fields.String(validate=validate.OneOf(['sha256WithRSA', 'sha1WithRSA']), missing='sha256WithRSA')
|
||||
key_type = fields.String(validate=validate.OneOf(['RSA2048', 'RSA4096']), missing='RSA2048')
|
||||
signing_algorithm = fields.String(
|
||||
validate=validate.OneOf(["sha256WithRSA", "sha1WithRSA"]),
|
||||
missing="sha256WithRSA",
|
||||
)
|
||||
key_type = fields.String(
|
||||
validate=validate.OneOf(["RSA2048", "RSA4096"]), missing="RSA2048"
|
||||
)
|
||||
key_name = fields.String()
|
||||
sensitivity = fields.String(validate=validate.OneOf(['medium', 'high']), missing='medium')
|
||||
sensitivity = fields.String(
|
||||
validate=validate.OneOf(["medium", "high"]), missing="medium"
|
||||
)
|
||||
serial_number = fields.Integer()
|
||||
first_serial = fields.Integer(missing=1)
|
||||
|
||||
@ -58,9 +79,11 @@ class AuthorityInputSchema(LemurInputSchema):
|
||||
|
||||
@validates_schema
|
||||
def validate_subca(self, data):
|
||||
if data['type'] == 'subca':
|
||||
if not data.get('parent'):
|
||||
raise ValidationError("If generating a subca, parent 'authority' must be specified.")
|
||||
if data["type"] == "subca":
|
||||
if not data.get("parent"):
|
||||
raise ValidationError(
|
||||
"If generating a subca, parent 'authority' must be specified."
|
||||
)
|
||||
|
||||
@pre_load
|
||||
def ensure_dates(self, data):
|
||||
|
@ -43,7 +43,7 @@ def mint(**kwargs):
|
||||
"""
|
||||
Creates the authority based on the plugin provided.
|
||||
"""
|
||||
issuer = kwargs['plugin']['plugin_object']
|
||||
issuer = kwargs["plugin"]["plugin_object"]
|
||||
values = issuer.create_authority(kwargs)
|
||||
|
||||
# support older plugins
|
||||
@ -53,7 +53,12 @@ def mint(**kwargs):
|
||||
elif len(values) == 4:
|
||||
body, private_key, chain, roles = values
|
||||
|
||||
roles = create_authority_roles(roles, kwargs['owner'], kwargs['plugin']['plugin_object'].title, kwargs['creator'])
|
||||
roles = create_authority_roles(
|
||||
roles,
|
||||
kwargs["owner"],
|
||||
kwargs["plugin"]["plugin_object"].title,
|
||||
kwargs["creator"],
|
||||
)
|
||||
return body, private_key, chain, roles
|
||||
|
||||
|
||||
@ -66,16 +71,17 @@ def create_authority_roles(roles, owner, plugin_title, creator):
|
||||
"""
|
||||
role_objs = []
|
||||
for r in roles:
|
||||
role = role_service.get_by_name(r['name'])
|
||||
role = role_service.get_by_name(r["name"])
|
||||
if not role:
|
||||
role = role_service.create(
|
||||
r['name'],
|
||||
password=r['password'],
|
||||
r["name"],
|
||||
password=r["password"],
|
||||
description="Auto generated role for {0}".format(plugin_title),
|
||||
username=r['username'])
|
||||
username=r["username"],
|
||||
)
|
||||
|
||||
# the user creating the authority should be able to administer it
|
||||
if role.username == 'admin':
|
||||
if role.username == "admin":
|
||||
creator.roles.append(role)
|
||||
|
||||
role_objs.append(role)
|
||||
@ -84,8 +90,7 @@ def create_authority_roles(roles, owner, plugin_title, creator):
|
||||
owner_role = role_service.get_by_name(owner)
|
||||
if not owner_role:
|
||||
owner_role = role_service.create(
|
||||
owner,
|
||||
description="Auto generated role based on owner: {0}".format(owner)
|
||||
owner, description="Auto generated role based on owner: {0}".format(owner)
|
||||
)
|
||||
|
||||
role_objs.append(owner_role)
|
||||
@ -98,27 +103,29 @@ def create(**kwargs):
|
||||
"""
|
||||
body, private_key, chain, roles = mint(**kwargs)
|
||||
|
||||
kwargs['creator'].roles = list(set(list(kwargs['creator'].roles) + roles))
|
||||
kwargs["creator"].roles = list(set(list(kwargs["creator"].roles) + roles))
|
||||
|
||||
kwargs['body'] = body
|
||||
kwargs['private_key'] = private_key
|
||||
kwargs['chain'] = chain
|
||||
kwargs["body"] = body
|
||||
kwargs["private_key"] = private_key
|
||||
kwargs["chain"] = chain
|
||||
|
||||
if kwargs.get('roles'):
|
||||
kwargs['roles'] += roles
|
||||
if kwargs.get("roles"):
|
||||
kwargs["roles"] += roles
|
||||
else:
|
||||
kwargs['roles'] = roles
|
||||
kwargs["roles"] = roles
|
||||
|
||||
cert = upload(**kwargs)
|
||||
kwargs['authority_certificate'] = cert
|
||||
if kwargs.get('plugin', {}).get('plugin_options', []):
|
||||
kwargs['options'] = json.dumps(kwargs['plugin']['plugin_options'])
|
||||
kwargs["authority_certificate"] = cert
|
||||
if kwargs.get("plugin", {}).get("plugin_options", []):
|
||||
kwargs["options"] = json.dumps(kwargs["plugin"]["plugin_options"])
|
||||
|
||||
authority = Authority(**kwargs)
|
||||
authority = database.create(authority)
|
||||
kwargs['creator'].authorities.append(authority)
|
||||
kwargs["creator"].authorities.append(authority)
|
||||
|
||||
metrics.send('authority_created', 'counter', 1, metric_tags=dict(owner=authority.owner))
|
||||
metrics.send(
|
||||
"authority_created", "counter", 1, metric_tags=dict(owner=authority.owner)
|
||||
)
|
||||
return authority
|
||||
|
||||
|
||||
@ -150,7 +157,7 @@ def get_by_name(authority_name):
|
||||
:param authority_name:
|
||||
:return:
|
||||
"""
|
||||
return database.get(Authority, authority_name, field='name')
|
||||
return database.get(Authority, authority_name, field="name")
|
||||
|
||||
|
||||
def get_authority_role(ca_name, creator=None):
|
||||
@ -173,29 +180,31 @@ def render(args):
|
||||
:return:
|
||||
"""
|
||||
query = database.session_query(Authority)
|
||||
filt = args.pop('filter')
|
||||
filt = args.pop("filter")
|
||||
|
||||
if filt:
|
||||
terms = filt.split(';')
|
||||
if 'active' in filt:
|
||||
terms = filt.split(";")
|
||||
if "active" in filt:
|
||||
query = query.filter(Authority.active == truthiness(terms[1]))
|
||||
elif 'cn' in filt:
|
||||
term = '%{0}%'.format(terms[1])
|
||||
sub_query = database.session_query(Certificate.root_authority_id) \
|
||||
.filter(Certificate.cn.ilike(term)) \
|
||||
elif "cn" in filt:
|
||||
term = "%{0}%".format(terms[1])
|
||||
sub_query = (
|
||||
database.session_query(Certificate.root_authority_id)
|
||||
.filter(Certificate.cn.ilike(term))
|
||||
.subquery()
|
||||
)
|
||||
|
||||
query = query.filter(Authority.id.in_(sub_query))
|
||||
else:
|
||||
query = database.filter(query, Authority, terms)
|
||||
|
||||
# we make sure that a user can only use an authority they either own are a member of - admins can see all
|
||||
if not args['user'].is_admin:
|
||||
if not args["user"].is_admin:
|
||||
authority_ids = []
|
||||
for authority in args['user'].authorities:
|
||||
for authority in args["user"].authorities:
|
||||
authority_ids.append(authority.id)
|
||||
|
||||
for role in args['user'].roles:
|
||||
for role in args["user"].roles:
|
||||
for authority in role.authorities:
|
||||
authority_ids.append(authority.id)
|
||||
query = query.filter(Authority.id.in_(authority_ids))
|
||||
|
@ -16,15 +16,21 @@ from lemur.auth.permissions import AuthorityPermission
|
||||
from lemur.certificates import service as certificate_service
|
||||
|
||||
from lemur.authorities import service
|
||||
from lemur.authorities.schemas import authority_input_schema, authority_output_schema, authorities_output_schema, authority_update_schema
|
||||
from lemur.authorities.schemas import (
|
||||
authority_input_schema,
|
||||
authority_output_schema,
|
||||
authorities_output_schema,
|
||||
authority_update_schema,
|
||||
)
|
||||
|
||||
|
||||
mod = Blueprint('authorities', __name__)
|
||||
mod = Blueprint("authorities", __name__)
|
||||
api = Api(mod)
|
||||
|
||||
|
||||
class AuthoritiesList(AuthenticatedResource):
|
||||
""" Defines the 'authorities' endpoint """
|
||||
|
||||
def __init__(self):
|
||||
self.reqparse = reqparse.RequestParser()
|
||||
super(AuthoritiesList, self).__init__()
|
||||
@ -107,7 +113,7 @@ class AuthoritiesList(AuthenticatedResource):
|
||||
"""
|
||||
parser = paginated_parser.copy()
|
||||
args = parser.parse_args()
|
||||
args['user'] = g.current_user
|
||||
args["user"] = g.current_user
|
||||
return service.render(args)
|
||||
|
||||
@validate_schema(authority_input_schema, authority_output_schema)
|
||||
@ -220,7 +226,7 @@ class AuthoritiesList(AuthenticatedResource):
|
||||
:statuscode 403: unauthenticated
|
||||
:statuscode 200: no error
|
||||
"""
|
||||
data['creator'] = g.current_user
|
||||
data["creator"] = g.current_user
|
||||
return service.create(**data)
|
||||
|
||||
|
||||
@ -388,7 +394,7 @@ class Authorities(AuthenticatedResource):
|
||||
authority = service.get(authority_id)
|
||||
|
||||
if not authority:
|
||||
return dict(message='Not Found'), 404
|
||||
return dict(message="Not Found"), 404
|
||||
|
||||
# all the authority role members should be allowed
|
||||
roles = [x.name for x in authority.roles]
|
||||
@ -397,10 +403,10 @@ class Authorities(AuthenticatedResource):
|
||||
if permission.can():
|
||||
return service.update(
|
||||
authority_id,
|
||||
owner=data['owner'],
|
||||
description=data['description'],
|
||||
active=data['active'],
|
||||
roles=data['roles']
|
||||
owner=data["owner"],
|
||||
description=data["description"],
|
||||
active=data["active"],
|
||||
roles=data["roles"],
|
||||
)
|
||||
|
||||
return dict(message="You are not authorized to update this authority."), 403
|
||||
@ -505,10 +511,21 @@ class AuthorityVisualizations(AuthenticatedResource):
|
||||
]}
|
||||
"""
|
||||
authority = service.get(authority_id)
|
||||
return dict(name=authority.name, children=[{"name": c.name} for c in authority.certificates])
|
||||
return dict(
|
||||
name=authority.name,
|
||||
children=[{"name": c.name} for c in authority.certificates],
|
||||
)
|
||||
|
||||
|
||||
api.add_resource(AuthoritiesList, '/authorities', endpoint='authorities')
|
||||
api.add_resource(Authorities, '/authorities/<int:authority_id>', endpoint='authority')
|
||||
api.add_resource(AuthorityVisualizations, '/authorities/<int:authority_id>/visualize', endpoint='authority_visualizations')
|
||||
api.add_resource(CertificateAuthority, '/certificates/<int:certificate_id>/authority', endpoint='certificateAuthority')
|
||||
api.add_resource(AuthoritiesList, "/authorities", endpoint="authorities")
|
||||
api.add_resource(Authorities, "/authorities/<int:authority_id>", endpoint="authority")
|
||||
api.add_resource(
|
||||
AuthorityVisualizations,
|
||||
"/authorities/<int:authority_id>/visualize",
|
||||
endpoint="authority_visualizations",
|
||||
)
|
||||
api.add_resource(
|
||||
CertificateAuthority,
|
||||
"/certificates/<int:certificate_id>/authority",
|
||||
endpoint="certificateAuthority",
|
||||
)
|
||||
|
Reference in New Issue
Block a user