We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[Web-UI] Active button for authority is not working
I have list of authorities created on the lemur. I want to disable creation of new certificates using one of the authority. Clicking on **active** button against that authority should make that authority inactive which is not the case.

Even the PUT call to the `http://example.com/api/1/authorities/5` with active key's value set to false returns true in response. Please find the request and response for the API in the file given below.
[active.txt](https://github.com/Netflix/lemur/files/878813/active.txt)


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `lemur/authorities/service.py`
Content:
```
1 """
2 .. module: lemur.authorities.service
3     :platform: Unix
4     :synopsis: This module contains all of the services level functions used to
5     administer authorities in Lemur
6     :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more
7     :license: Apache, see LICENSE for more details.
8 .. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
9 
10 """
11 from lemur import database
12 from lemur.extensions import metrics
13 from lemur.authorities.models import Authority
14 from lemur.roles import service as role_service
15 
16 from lemur.certificates.service import upload
17 
18 
19 def update(authority_id, description=None, owner=None, active=None, roles=None):
20     """
21     Update an authority with new values.
22 
23     :param authority_id:
24     :param roles: roles that are allowed to use this authority
25     :return:
26     """
27     authority = get(authority_id)
28 
29     if roles:
30         authority.roles = roles
31 
32     if active:
33         authority.active = active
34 
35     authority.description = description
36     authority.owner = owner
37     return database.update(authority)
38 
39 
40 def mint(**kwargs):
41     """
42     Creates the authority based on the plugin provided.
43     """
44     issuer = kwargs['plugin']['plugin_object']
45     values = issuer.create_authority(kwargs)
46 
47     # support older plugins
48     if len(values) == 3:
49         body, chain, roles = values
50         private_key = None
51     elif len(values) == 4:
52         body, private_key, chain, roles = values
53 
54     roles = create_authority_roles(roles, kwargs['owner'], kwargs['plugin']['plugin_object'].title, kwargs['creator'])
55     return body, private_key, chain, roles
56 
57 
58 def create_authority_roles(roles, owner, plugin_title, creator):
59     """
60     Creates all of the necessary authority roles.
61     :param creator:
62     :param roles:
63     :return:
64     """
65     role_objs = []
66     for r in roles:
67         role = role_service.get_by_name(r['name'])
68         if not role:
69             role = role_service.create(
70                 r['name'],
71                 password=r['password'],
72                 description="Auto generated role for {0}".format(plugin_title),
73                 username=r['username'])
74 
75         # the user creating the authority should be able to administer it
76         if role.username == 'admin':
77             creator.roles.append(role)
78 
79         role_objs.append(role)
80 
81     # create an role for the owner and assign it
82     owner_role = role_service.get_by_name(owner)
83     if not owner_role:
84         owner_role = role_service.create(
85             owner,
86             description="Auto generated role based on owner: {0}".format(owner)
87         )
88 
89     role_objs.append(owner_role)
90     return role_objs
91 
92 
93 def create(**kwargs):
94     """
95     Creates a new authority.
96     """
97     body, private_key, chain, roles = mint(**kwargs)
98 
99     kwargs['creator'].roles = list(set(list(kwargs['creator'].roles) + roles))
100 
101     kwargs['body'] = body
102     kwargs['private_key'] = private_key
103     kwargs['chain'] = chain
104 
105     if kwargs.get('roles'):
106         kwargs['roles'] += roles
107     else:
108         kwargs['roles'] = roles
109 
110     cert = upload(**kwargs)
111     kwargs['authority_certificate'] = cert
112 
113     authority = Authority(**kwargs)
114     authority = database.create(authority)
115     kwargs['creator'].authorities.append(authority)
116 
117     metrics.send('authority_created', 'counter', 1, metric_tags=dict(owner=authority.owner))
118     return authority
119 
120 
121 def get_all():
122     """
123     Get all authorities that are currently in Lemur.
124 
125     :rtype : List
126     :return:
127     """
128     query = database.session_query(Authority)
129     return database.find_all(query, Authority, {}).all()
130 
131 
132 def get(authority_id):
133     """
134     Retrieves an authority given it's ID
135 
136     :param authority_id:
137     :return:
138     """
139     return database.get(Authority, authority_id)
140 
141 
142 def get_by_name(authority_name):
143     """
144     Retrieves an authority given it's name.
145 
146     :param authority_name:
147     :return:
148     """
149     return database.get(Authority, authority_name, field='name')
150 
151 
152 def get_authority_role(ca_name, creator=None):
153     """
154     Attempts to get the authority role for a given ca uses current_user
155     as a basis for accomplishing that.
156 
157     :param ca_name:
158     """
159     if creator:
160         if creator.is_admin:
161             return role_service.get_by_name("{0}_admin".format(ca_name))
162     return role_service.get_by_name("{0}_operator".format(ca_name))
163 
164 
165 def render(args):
166     """
167     Helper that helps us render the REST Api responses.
168     :param args:
169     :return:
170     """
171     query = database.session_query(Authority)
172     filt = args.pop('filter')
173 
174     if filt:
175         terms = filt.split(';')
176         if 'active' in filt:  # this is really weird but strcmp seems to not work here??
177             query = query.filter(Authority.active == terms[1])
178         else:
179             query = database.filter(query, Authority, terms)
180 
181     # we make sure that a user can only use an authority they either own are a member of - admins can see all
182     if not args['user'].is_admin:
183         authority_ids = []
184         for authority in args['user'].authorities:
185             authority_ids.append(authority.id)
186 
187         for role in args['user'].roles:
188             for authority in role.authorities:
189                 authority_ids.append(authority.id)
190         query = query.filter(Authority.id.in_(authority_ids))
191 
192     return database.sort_and_page(query, Authority, args)
193
```

Path: `lemur/authorities/schemas.py`
Content:
```
1 """
2 .. module: lemur.authorities.schemas
3     :platform: unix
4     :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more
5     :license: Apache, see LICENSE for more details.
6 .. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
7 """
8 from flask import current_app
9 
10 from marshmallow import fields, validates_schema, pre_load
11 from marshmallow import validate
12 from marshmallow.exceptions import ValidationError
13 
14 from lemur.schemas import PluginInputSchema, PluginOutputSchema, ExtensionSchema, AssociatedAuthoritySchema, AssociatedRoleSchema
15 from lemur.users.schemas import UserNestedOutputSchema
16 from lemur.common.schema import LemurInputSchema, LemurOutputSchema
17 from lemur.common import validators, missing
18 
19 from lemur.common.fields import ArrowDateTime
20 
21 
22 class AuthorityInputSchema(LemurInputSchema):
23     name = fields.String(required=True)
24     owner = fields.Email(required=True)
25     description = fields.String()
26     common_name = fields.String(required=True, validate=validators.sensitive_domain)
27 
28     validity_start = ArrowDateTime()
29     validity_end = ArrowDateTime()
30     validity_years = fields.Integer()
31 
32     # certificate body fields
33     organizational_unit = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_ORGANIZATIONAL_UNIT'))
34     organization = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_ORGANIZATION'))
35     location = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_LOCATION'))
36     country = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_COUNTRY'))
37     state = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_STATE'))
38 
39     plugin = fields.Nested(PluginInputSchema)
40 
41     # signing related options
42     type = fields.String(validate=validate.OneOf(['root', 'subca']), missing='root')
43     parent = fields.Nested(AssociatedAuthoritySchema)
44     signing_algorithm = fields.String(validate=validate.OneOf(['sha256WithRSA', 'sha1WithRSA']), missing='sha256WithRSA')
45     key_type = fields.String(validate=validate.OneOf(['RSA2048', 'RSA4096']), missing='RSA2048')
46     key_name = fields.String()
47     sensitivity = fields.String(validate=validate.OneOf(['medium', 'high']), missing='medium')
48     serial_number = fields.Integer()
49     first_serial = fields.Integer(missing=1)
50 
51     extensions = fields.Nested(ExtensionSchema)
52 
53     roles = fields.Nested(AssociatedRoleSchema(many=True))
54 
55     @validates_schema
56     def validate_dates(self, data):
57         validators.dates(data)
58 
59     @validates_schema
60     def validate_subca(self, data):
61         if data['type'] == 'subca':
62             if not data.get('parent'):
63                 raise ValidationError("If generating a subca, parent 'authority' must be specified.")
64 
65     @pre_load
66     def ensure_dates(self, data):
67         return missing.convert_validity_years(data)
68 
69 
70 class AuthorityUpdateSchema(LemurInputSchema):
71     owner = fields.Email(required=True)
72     description = fields.String()
73     active = fields.Boolean()
74     roles = fields.Nested(AssociatedRoleSchema(many=True))
75 
76 
77 class RootAuthorityCertificateOutputSchema(LemurOutputSchema):
78     __envelope__ = False
79     id = fields.Integer()
80     active = fields.Boolean()
81     bits = fields.Integer()
82     body = fields.String()
83     chain = fields.String()
84     description = fields.String()
85     name = fields.String()
86     cn = fields.String()
87     not_after = fields.DateTime()
88     not_before = fields.DateTime()
89     owner = fields.Email()
90     status = fields.Boolean()
91     user = fields.Nested(UserNestedOutputSchema)
92 
93 
94 class AuthorityOutputSchema(LemurOutputSchema):
95     id = fields.Integer()
96     description = fields.String()
97     name = fields.String()
98     owner = fields.Email()
99     plugin = fields.Nested(PluginOutputSchema)
100     active = fields.Boolean()
101     options = fields.Dict()
102     roles = fields.List(fields.Nested(AssociatedRoleSchema))
103     authority_certificate = fields.Nested(RootAuthorityCertificateOutputSchema)
104 
105 
106 class AuthorityNestedOutputSchema(LemurOutputSchema):
107     __envelope__ = False
108     id = fields.Integer()
109     description = fields.String()
110     name = fields.String()
111     owner = fields.Email()
112     plugin = fields.Nested(PluginOutputSchema)
113     active = fields.Boolean()
114 
115 
116 authority_update_schema = AuthorityUpdateSchema()
117 authority_input_schema = AuthorityInputSchema()
118 authority_output_schema = AuthorityOutputSchema()
119 authorities_output_schema = AuthorityOutputSchema(many=True)
120
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/lemur/authorities/schemas.py b/lemur/authorities/schemas.py
--- a/lemur/authorities/schemas.py
+++ b/lemur/authorities/schemas.py
@@ -70,7 +70,7 @@
 class AuthorityUpdateSchema(LemurInputSchema):
     owner = fields.Email(required=True)
     description = fields.String()
-    active = fields.Boolean()
+    active = fields.Boolean(missing=True)
     roles = fields.Nested(AssociatedRoleSchema(many=True))
 
 
diff --git a/lemur/authorities/service.py b/lemur/authorities/service.py
--- a/lemur/authorities/service.py
+++ b/lemur/authorities/service.py
@@ -29,9 +29,7 @@
     if roles:
         authority.roles = roles
 
-    if active:
-        authority.active = active
-
+    authority.active = active
     authority.description = description
     authority.owner = owner
     return database.update(authority)

{"golden_diff": "diff --git a/lemur/authorities/schemas.py b/lemur/authorities/schemas.py\n--- a/lemur/authorities/schemas.py\n+++ b/lemur/authorities/schemas.py\n@@ -70,7 +70,7 @@\n class AuthorityUpdateSchema(LemurInputSchema):\n     owner = fields.Email(required=True)\n     description = fields.String()\n-    active = fields.Boolean()\n+    active = fields.Boolean(missing=True)\n     roles = fields.Nested(AssociatedRoleSchema(many=True))\n \n \ndiff --git a/lemur/authorities/service.py b/lemur/authorities/service.py\n--- a/lemur/authorities/service.py\n+++ b/lemur/authorities/service.py\n@@ -29,9 +29,7 @@\n     if roles:\n         authority.roles = roles\n \n-    if active:\n-        authority.active = active\n-\n+    authority.active = active\n     authority.description = description\n     authority.owner = owner\n     return database.update(authority)\n", "issue": "[Web-UI] Active button for authority is not working\nI have list of authorities created on the lemur. I want to disable creation of new certificates using one of the authority. Clicking on **active** button against that authority should make that authority inactive which is not the case.\r\n\r\nEven the PUT call to the `http://example.com/api/1/authorities/5` with active key's value set to false returns true in response. Please find the request and response for the API in the file given below.\r\n[active.txt](https://github.com/Netflix/lemur/files/878813/active.txt)\r\n\n", "before_files": [{"content": "\"\"\"\n.. module: lemur.authorities.service\n    :platform: Unix\n    :synopsis: This module contains all of the services level functions used to\n    administer authorities in Lemur\n    :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more\n    :license: Apache, see LICENSE for more details.\n.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>\n\n\"\"\"\nfrom lemur import database\nfrom lemur.extensions import metrics\nfrom lemur.authorities.models import Authority\nfrom lemur.roles import service as role_service\n\nfrom lemur.certificates.service import upload\n\n\ndef update(authority_id, description=None, owner=None, active=None, roles=None):\n    \"\"\"\n    Update an authority with new values.\n\n    :param authority_id:\n    :param roles: roles that are allowed to use this authority\n    :return:\n    \"\"\"\n    authority = get(authority_id)\n\n    if roles:\n        authority.roles = roles\n\n    if active:\n        authority.active = active\n\n    authority.description = description\n    authority.owner = owner\n    return database.update(authority)\n\n\ndef mint(**kwargs):\n    \"\"\"\n    Creates the authority based on the plugin provided.\n    \"\"\"\n    issuer = kwargs['plugin']['plugin_object']\n    values = issuer.create_authority(kwargs)\n\n    # support older plugins\n    if len(values) == 3:\n        body, chain, roles = values\n        private_key = None\n    elif len(values) == 4:\n        body, private_key, chain, roles = values\n\n    roles = create_authority_roles(roles, kwargs['owner'], kwargs['plugin']['plugin_object'].title, kwargs['creator'])\n    return body, private_key, chain, roles\n\n\ndef create_authority_roles(roles, owner, plugin_title, creator):\n    \"\"\"\n    Creates all of the necessary authority roles.\n    :param creator:\n    :param roles:\n    :return:\n    \"\"\"\n    role_objs = []\n    for r in roles:\n        role = role_service.get_by_name(r['name'])\n        if not role:\n            role = role_service.create(\n                r['name'],\n                password=r['password'],\n                description=\"Auto generated role for {0}\".format(plugin_title),\n                username=r['username'])\n\n        # the user creating the authority should be able to administer it\n        if role.username == 'admin':\n            creator.roles.append(role)\n\n        role_objs.append(role)\n\n    # create an role for the owner and assign it\n    owner_role = role_service.get_by_name(owner)\n    if not owner_role:\n        owner_role = role_service.create(\n            owner,\n            description=\"Auto generated role based on owner: {0}\".format(owner)\n        )\n\n    role_objs.append(owner_role)\n    return role_objs\n\n\ndef create(**kwargs):\n    \"\"\"\n    Creates a new authority.\n    \"\"\"\n    body, private_key, chain, roles = mint(**kwargs)\n\n    kwargs['creator'].roles = list(set(list(kwargs['creator'].roles) + roles))\n\n    kwargs['body'] = body\n    kwargs['private_key'] = private_key\n    kwargs['chain'] = chain\n\n    if kwargs.get('roles'):\n        kwargs['roles'] += roles\n    else:\n        kwargs['roles'] = roles\n\n    cert = upload(**kwargs)\n    kwargs['authority_certificate'] = cert\n\n    authority = Authority(**kwargs)\n    authority = database.create(authority)\n    kwargs['creator'].authorities.append(authority)\n\n    metrics.send('authority_created', 'counter', 1, metric_tags=dict(owner=authority.owner))\n    return authority\n\n\ndef get_all():\n    \"\"\"\n    Get all authorities that are currently in Lemur.\n\n    :rtype : List\n    :return:\n    \"\"\"\n    query = database.session_query(Authority)\n    return database.find_all(query, Authority, {}).all()\n\n\ndef get(authority_id):\n    \"\"\"\n    Retrieves an authority given it's ID\n\n    :param authority_id:\n    :return:\n    \"\"\"\n    return database.get(Authority, authority_id)\n\n\ndef get_by_name(authority_name):\n    \"\"\"\n    Retrieves an authority given it's name.\n\n    :param authority_name:\n    :return:\n    \"\"\"\n    return database.get(Authority, authority_name, field='name')\n\n\ndef get_authority_role(ca_name, creator=None):\n    \"\"\"\n    Attempts to get the authority role for a given ca uses current_user\n    as a basis for accomplishing that.\n\n    :param ca_name:\n    \"\"\"\n    if creator:\n        if creator.is_admin:\n            return role_service.get_by_name(\"{0}_admin\".format(ca_name))\n    return role_service.get_by_name(\"{0}_operator\".format(ca_name))\n\n\ndef render(args):\n    \"\"\"\n    Helper that helps us render the REST Api responses.\n    :param args:\n    :return:\n    \"\"\"\n    query = database.session_query(Authority)\n    filt = args.pop('filter')\n\n    if filt:\n        terms = filt.split(';')\n        if 'active' in filt:  # this is really weird but strcmp seems to not work here??\n            query = query.filter(Authority.active == terms[1])\n        else:\n            query = database.filter(query, Authority, terms)\n\n    # we make sure that a user can only use an authority they either own are a member of - admins can see all\n    if not args['user'].is_admin:\n        authority_ids = []\n        for authority in args['user'].authorities:\n            authority_ids.append(authority.id)\n\n        for role in args['user'].roles:\n            for authority in role.authorities:\n                authority_ids.append(authority.id)\n        query = query.filter(Authority.id.in_(authority_ids))\n\n    return database.sort_and_page(query, Authority, args)\n", "path": "lemur/authorities/service.py"}, {"content": "\"\"\"\n.. module: lemur.authorities.schemas\n    :platform: unix\n    :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more\n    :license: Apache, see LICENSE for more details.\n.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>\n\"\"\"\nfrom flask import current_app\n\nfrom marshmallow import fields, validates_schema, pre_load\nfrom marshmallow import validate\nfrom marshmallow.exceptions import ValidationError\n\nfrom lemur.schemas import PluginInputSchema, PluginOutputSchema, ExtensionSchema, AssociatedAuthoritySchema, AssociatedRoleSchema\nfrom lemur.users.schemas import UserNestedOutputSchema\nfrom lemur.common.schema import LemurInputSchema, LemurOutputSchema\nfrom lemur.common import validators, missing\n\nfrom lemur.common.fields import ArrowDateTime\n\n\nclass AuthorityInputSchema(LemurInputSchema):\n    name = fields.String(required=True)\n    owner = fields.Email(required=True)\n    description = fields.String()\n    common_name = fields.String(required=True, validate=validators.sensitive_domain)\n\n    validity_start = ArrowDateTime()\n    validity_end = ArrowDateTime()\n    validity_years = fields.Integer()\n\n    # certificate body fields\n    organizational_unit = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_ORGANIZATIONAL_UNIT'))\n    organization = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_ORGANIZATION'))\n    location = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_LOCATION'))\n    country = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_COUNTRY'))\n    state = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_STATE'))\n\n    plugin = fields.Nested(PluginInputSchema)\n\n    # signing related options\n    type = fields.String(validate=validate.OneOf(['root', 'subca']), missing='root')\n    parent = fields.Nested(AssociatedAuthoritySchema)\n    signing_algorithm = fields.String(validate=validate.OneOf(['sha256WithRSA', 'sha1WithRSA']), missing='sha256WithRSA')\n    key_type = fields.String(validate=validate.OneOf(['RSA2048', 'RSA4096']), missing='RSA2048')\n    key_name = fields.String()\n    sensitivity = fields.String(validate=validate.OneOf(['medium', 'high']), missing='medium')\n    serial_number = fields.Integer()\n    first_serial = fields.Integer(missing=1)\n\n    extensions = fields.Nested(ExtensionSchema)\n\n    roles = fields.Nested(AssociatedRoleSchema(many=True))\n\n    @validates_schema\n    def validate_dates(self, data):\n        validators.dates(data)\n\n    @validates_schema\n    def validate_subca(self, data):\n        if data['type'] == 'subca':\n            if not data.get('parent'):\n                raise ValidationError(\"If generating a subca, parent 'authority' must be specified.\")\n\n    @pre_load\n    def ensure_dates(self, data):\n        return missing.convert_validity_years(data)\n\n\nclass AuthorityUpdateSchema(LemurInputSchema):\n    owner = fields.Email(required=True)\n    description = fields.String()\n    active = fields.Boolean()\n    roles = fields.Nested(AssociatedRoleSchema(many=True))\n\n\nclass RootAuthorityCertificateOutputSchema(LemurOutputSchema):\n    __envelope__ = False\n    id = fields.Integer()\n    active = fields.Boolean()\n    bits = fields.Integer()\n    body = fields.String()\n    chain = fields.String()\n    description = fields.String()\n    name = fields.String()\n    cn = fields.String()\n    not_after = fields.DateTime()\n    not_before = fields.DateTime()\n    owner = fields.Email()\n    status = fields.Boolean()\n    user = fields.Nested(UserNestedOutputSchema)\n\n\nclass AuthorityOutputSchema(LemurOutputSchema):\n    id = fields.Integer()\n    description = fields.String()\n    name = fields.String()\n    owner = fields.Email()\n    plugin = fields.Nested(PluginOutputSchema)\n    active = fields.Boolean()\n    options = fields.Dict()\n    roles = fields.List(fields.Nested(AssociatedRoleSchema))\n    authority_certificate = fields.Nested(RootAuthorityCertificateOutputSchema)\n\n\nclass AuthorityNestedOutputSchema(LemurOutputSchema):\n    __envelope__ = False\n    id = fields.Integer()\n    description = fields.String()\n    name = fields.String()\n    owner = fields.Email()\n    plugin = fields.Nested(PluginOutputSchema)\n    active = fields.Boolean()\n\n\nauthority_update_schema = AuthorityUpdateSchema()\nauthority_input_schema = AuthorityInputSchema()\nauthority_output_schema = AuthorityOutputSchema()\nauthorities_output_schema = AuthorityOutputSchema(many=True)\n", "path": "lemur/authorities/schemas.py"}], "after_files": [{"content": "\"\"\"\n.. module: lemur.authorities.service\n    :platform: Unix\n    :synopsis: This module contains all of the services level functions used to\n    administer authorities in Lemur\n    :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more\n    :license: Apache, see LICENSE for more details.\n.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>\n\n\"\"\"\nfrom lemur import database\nfrom lemur.extensions import metrics\nfrom lemur.authorities.models import Authority\nfrom lemur.roles import service as role_service\n\nfrom lemur.certificates.service import upload\n\n\ndef update(authority_id, description=None, owner=None, active=None, roles=None):\n    \"\"\"\n    Update an authority with new values.\n\n    :param authority_id:\n    :param roles: roles that are allowed to use this authority\n    :return:\n    \"\"\"\n    authority = get(authority_id)\n\n    if roles:\n        authority.roles = roles\n\n    authority.active = active\n    authority.description = description\n    authority.owner = owner\n    return database.update(authority)\n\n\ndef mint(**kwargs):\n    \"\"\"\n    Creates the authority based on the plugin provided.\n    \"\"\"\n    issuer = kwargs['plugin']['plugin_object']\n    values = issuer.create_authority(kwargs)\n\n    # support older plugins\n    if len(values) == 3:\n        body, chain, roles = values\n        private_key = None\n    elif len(values) == 4:\n        body, private_key, chain, roles = values\n\n    roles = create_authority_roles(roles, kwargs['owner'], kwargs['plugin']['plugin_object'].title, kwargs['creator'])\n    return body, private_key, chain, roles\n\n\ndef create_authority_roles(roles, owner, plugin_title, creator):\n    \"\"\"\n    Creates all of the necessary authority roles.\n    :param creator:\n    :param roles:\n    :return:\n    \"\"\"\n    role_objs = []\n    for r in roles:\n        role = role_service.get_by_name(r['name'])\n        if not role:\n            role = role_service.create(\n                r['name'],\n                password=r['password'],\n                description=\"Auto generated role for {0}\".format(plugin_title),\n                username=r['username'])\n\n        # the user creating the authority should be able to administer it\n        if role.username == 'admin':\n            creator.roles.append(role)\n\n        role_objs.append(role)\n\n    # create an role for the owner and assign it\n    owner_role = role_service.get_by_name(owner)\n    if not owner_role:\n        owner_role = role_service.create(\n            owner,\n            description=\"Auto generated role based on owner: {0}\".format(owner)\n        )\n\n    role_objs.append(owner_role)\n    return role_objs\n\n\ndef create(**kwargs):\n    \"\"\"\n    Creates a new authority.\n    \"\"\"\n    body, private_key, chain, roles = mint(**kwargs)\n\n    kwargs['creator'].roles = list(set(list(kwargs['creator'].roles) + roles))\n\n    kwargs['body'] = body\n    kwargs['private_key'] = private_key\n    kwargs['chain'] = chain\n\n    if kwargs.get('roles'):\n        kwargs['roles'] += roles\n    else:\n        kwargs['roles'] = roles\n\n    cert = upload(**kwargs)\n    kwargs['authority_certificate'] = cert\n\n    authority = Authority(**kwargs)\n    authority = database.create(authority)\n    kwargs['creator'].authorities.append(authority)\n\n    metrics.send('authority_created', 'counter', 1, metric_tags=dict(owner=authority.owner))\n    return authority\n\n\ndef get_all():\n    \"\"\"\n    Get all authorities that are currently in Lemur.\n\n    :rtype : List\n    :return:\n    \"\"\"\n    query = database.session_query(Authority)\n    return database.find_all(query, Authority, {}).all()\n\n\ndef get(authority_id):\n    \"\"\"\n    Retrieves an authority given it's ID\n\n    :param authority_id:\n    :return:\n    \"\"\"\n    return database.get(Authority, authority_id)\n\n\ndef get_by_name(authority_name):\n    \"\"\"\n    Retrieves an authority given it's name.\n\n    :param authority_name:\n    :return:\n    \"\"\"\n    return database.get(Authority, authority_name, field='name')\n\n\ndef get_authority_role(ca_name, creator=None):\n    \"\"\"\n    Attempts to get the authority role for a given ca uses current_user\n    as a basis for accomplishing that.\n\n    :param ca_name:\n    \"\"\"\n    if creator:\n        if creator.is_admin:\n            return role_service.get_by_name(\"{0}_admin\".format(ca_name))\n    return role_service.get_by_name(\"{0}_operator\".format(ca_name))\n\n\ndef render(args):\n    \"\"\"\n    Helper that helps us render the REST Api responses.\n    :param args:\n    :return:\n    \"\"\"\n    query = database.session_query(Authority)\n    filt = args.pop('filter')\n\n    if filt:\n        terms = filt.split(';')\n        if 'active' in filt:  # this is really weird but strcmp seems to not work here??\n            query = query.filter(Authority.active == terms[1])\n        else:\n            query = database.filter(query, Authority, terms)\n\n    # we make sure that a user can only use an authority they either own are a member of - admins can see all\n    if not args['user'].is_admin:\n        authority_ids = []\n        for authority in args['user'].authorities:\n            authority_ids.append(authority.id)\n\n        for role in args['user'].roles:\n            for authority in role.authorities:\n                authority_ids.append(authority.id)\n        query = query.filter(Authority.id.in_(authority_ids))\n\n    return database.sort_and_page(query, Authority, args)\n", "path": "lemur/authorities/service.py"}, {"content": "\"\"\"\n.. module: lemur.authorities.schemas\n    :platform: unix\n    :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more\n    :license: Apache, see LICENSE for more details.\n.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>\n\"\"\"\nfrom flask import current_app\n\nfrom marshmallow import fields, validates_schema, pre_load\nfrom marshmallow import validate\nfrom marshmallow.exceptions import ValidationError\n\nfrom lemur.schemas import PluginInputSchema, PluginOutputSchema, ExtensionSchema, AssociatedAuthoritySchema, AssociatedRoleSchema\nfrom lemur.users.schemas import UserNestedOutputSchema\nfrom lemur.common.schema import LemurInputSchema, LemurOutputSchema\nfrom lemur.common import validators, missing\n\nfrom lemur.common.fields import ArrowDateTime\n\n\nclass AuthorityInputSchema(LemurInputSchema):\n    name = fields.String(required=True)\n    owner = fields.Email(required=True)\n    description = fields.String()\n    common_name = fields.String(required=True, validate=validators.sensitive_domain)\n\n    validity_start = ArrowDateTime()\n    validity_end = ArrowDateTime()\n    validity_years = fields.Integer()\n\n    # certificate body fields\n    organizational_unit = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_ORGANIZATIONAL_UNIT'))\n    organization = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_ORGANIZATION'))\n    location = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_LOCATION'))\n    country = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_COUNTRY'))\n    state = fields.String(missing=lambda: current_app.config.get('LEMUR_DEFAULT_STATE'))\n\n    plugin = fields.Nested(PluginInputSchema)\n\n    # signing related options\n    type = fields.String(validate=validate.OneOf(['root', 'subca']), missing='root')\n    parent = fields.Nested(AssociatedAuthoritySchema)\n    signing_algorithm = fields.String(validate=validate.OneOf(['sha256WithRSA', 'sha1WithRSA']), missing='sha256WithRSA')\n    key_type = fields.String(validate=validate.OneOf(['RSA2048', 'RSA4096']), missing='RSA2048')\n    key_name = fields.String()\n    sensitivity = fields.String(validate=validate.OneOf(['medium', 'high']), missing='medium')\n    serial_number = fields.Integer()\n    first_serial = fields.Integer(missing=1)\n\n    extensions = fields.Nested(ExtensionSchema)\n\n    roles = fields.Nested(AssociatedRoleSchema(many=True))\n\n    @validates_schema\n    def validate_dates(self, data):\n        validators.dates(data)\n\n    @validates_schema\n    def validate_subca(self, data):\n        if data['type'] == 'subca':\n            if not data.get('parent'):\n                raise ValidationError(\"If generating a subca, parent 'authority' must be specified.\")\n\n    @pre_load\n    def ensure_dates(self, data):\n        return missing.convert_validity_years(data)\n\n\nclass AuthorityUpdateSchema(LemurInputSchema):\n    owner = fields.Email(required=True)\n    description = fields.String()\n    active = fields.Boolean(missing=True)\n    roles = fields.Nested(AssociatedRoleSchema(many=True))\n\n\nclass RootAuthorityCertificateOutputSchema(LemurOutputSchema):\n    __envelope__ = False\n    id = fields.Integer()\n    active = fields.Boolean()\n    bits = fields.Integer()\n    body = fields.String()\n    chain = fields.String()\n    description = fields.String()\n    name = fields.String()\n    cn = fields.String()\n    not_after = fields.DateTime()\n    not_before = fields.DateTime()\n    owner = fields.Email()\n    status = fields.Boolean()\n    user = fields.Nested(UserNestedOutputSchema)\n\n\nclass AuthorityOutputSchema(LemurOutputSchema):\n    id = fields.Integer()\n    description = fields.String()\n    name = fields.String()\n    owner = fields.Email()\n    plugin = fields.Nested(PluginOutputSchema)\n    active = fields.Boolean()\n    options = fields.Dict()\n    roles = fields.List(fields.Nested(AssociatedRoleSchema))\n    authority_certificate = fields.Nested(RootAuthorityCertificateOutputSchema)\n\n\nclass AuthorityNestedOutputSchema(LemurOutputSchema):\n    __envelope__ = False\n    id = fields.Integer()\n    description = fields.String()\n    name = fields.String()\n    owner = fields.Email()\n    plugin = fields.Nested(PluginOutputSchema)\n    active = fields.Boolean()\n\n\nauthority_update_schema = AuthorityUpdateSchema()\nauthority_input_schema = AuthorityInputSchema()\nauthority_output_schema = AuthorityOutputSchema()\nauthorities_output_schema = AuthorityOutputSchema(many=True)\n", "path": "lemur/authorities/schemas.py"}]}