internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: Netflix/lemur

Issue:
SubCA autogenerated descriptions for their certs are incorrect
If you create a root CA, and look up the certificate for that CA its description is: 
This is the ROOT certificate for the $CN certificate authority.
If you create a subCA off of that rootCA, and look up the certificate for that SubCA its description is: 
This is the ROOT certificate for the $CN certificate authority



Discussion:

Resolving patch:
diff --git a/lemur/authorities/service.py b/lemur/authorities/service.py
--- a/lemur/authorities/service.py
+++ b/lemur/authorities/service.py
@@ -58,7 +58,15 @@ def create(kwargs):
 
     cert = Certificate(cert_body, chain=intermediate)
     cert.owner = kwargs['ownerEmail']
-    cert.description = "This is the ROOT certificate for the {0} certificate authority".format(kwargs.get('caName'))
+
+    if kwargs['caType'] == 'subca':
+        cert.description = "This is the ROOT certificate for the {0} sub certificate authority the parent \
+                                authority is {1}.".format(kwargs.get('caName'), kwargs.get('caParent'))
+    else:
+        cert.description = "This is the ROOT certificate for the {0} certificate authority.".format(
+            kwargs.get('caName')
+        )
+
     cert.user = g.current_user
 
     cert.notifications = notification_service.create_default_expiration_notifications(


Test patch:
Repository: Netflix/lemur

Issue:
Error messages not displaying long enough
Currently error messages are displayed for only a period of time. They should be displayed until the user acknowledges the error. 



Discussion:

Resolving patch:
diff --git a/lemur/common/utils.py b/lemur/common/utils.py
--- a/lemur/common/utils.py
+++ b/lemur/common/utils.py
@@ -63,9 +63,9 @@ def wrapper(*args, **kwargs):
                     if hasattr(e, 'data'):
                         return {'message': e.data['message']}, 400
                     else:
-                        return {'message': 'unknown'}, 400
+                        return {'message': {'exception': 'unknown'}}, 400
                 else:
-                    return {'message': str(e)}, 400
+                    return {'message': {'exception': str(e)}}, 400
         return wrapper
 
 


Test patch:
Repository: Netflix/lemur

Issue:
Should be able to search certificates by domains covered, included wildcards



Discussion:

Resolving patch:
diff --git a/lemur/certificates/service.py b/lemur/certificates/service.py
--- a/lemur/certificates/service.py
+++ b/lemur/certificates/service.py
@@ -17,6 +17,7 @@
 from lemur.destinations.models import Destination
 from lemur.notifications.models import Notification
 from lemur.authorities.models import Authority
+from lemur.domains.models import Domain
 
 from lemur.roles.models import Role
 
@@ -271,6 +272,7 @@ def render(args):
 
     if filt:
         terms = filt.split(';')
+
         if 'issuer' in terms:
             # we can't rely on issuer being correct in the cert directly so we combine queries
             sub_query = database.session_query(Authority.id)\
@@ -285,10 +287,17 @@ def render(args):
             )
             return database.sort_and_page(query, Certificate, args)
 
-        if 'destination' in terms:
+        elif 'destination' in terms:
             query = query.filter(Certificate.destinations.any(Destination.id == terms[1]))
         elif 'active' in filt:  # this is really weird but strcmp seems to not work here??
             query = query.filter(Certificate.active == terms[1])
+        elif 'cn' in terms:
+            query = query.filter(
+                or_(
+                    Certificate.cn.ilike('%{0}%'.format(terms[1])),
+                    Certificate.domains.any(Domain.name.ilike('%{0}%'.format(terms[1])))
+                )
+            )
         else:
             query = database.filter(query, Certificate, terms)
 


Test patch:
Repository: Netflix/lemur

Issue:
Add ability to submit a CSR to Lemur
There are use cases where a third party may issue a CSR on your behalf (retaining the private key). It would be helpful to allow Lemur to be able to act as a 'pass through' and issue this certificate directly. This would also be helpful in the case the UI does not support a particular option or extension and could be generated manually.



Discussion:

Resolving patch:
diff --git a/lemur/certificates/service.py b/lemur/certificates/service.py
--- a/lemur/certificates/service.py
+++ b/lemur/certificates/service.py
@@ -140,7 +140,12 @@ def mint(issuer_options):
 
     issuer = plugins.get(authority.plugin_name)
 
-    csr, private_key = create_csr(issuer_options)
+    # allow the CSR to be specified by the user
+    if not issuer_options.get('csr'):
+        csr, private_key = create_csr(issuer_options)
+    else:
+        csr = issuer_options.get('csr')
+        private_key = None
 
     issuer_options['creator'] = g.user.email
     cert_body, cert_chain = issuer.create_certificate(csr, issuer_options)
diff --git a/lemur/certificates/views.py b/lemur/certificates/views.py
--- a/lemur/certificates/views.py
+++ b/lemur/certificates/views.py
@@ -192,6 +192,7 @@ def post(self):
                 "owner": "bob@example.com",
                 "description": "test",
                 "selectedAuthority": "timetest2",
+                "csr",
                 "authority": {
                     "body": "-----BEGIN...",
                     "name": "timetest2",
@@ -325,6 +326,7 @@ def post(self):
         self.reqparse.add_argument('organizationalUnit', type=str, location='json', required=True)
         self.reqparse.add_argument('owner', type=str, location='json', required=True)
         self.reqparse.add_argument('commonName', type=str, location='json', required=True)
+        self.reqparse.add_argument('csr', type=str, location='json')
 
         args = self.reqparse.parse_args()
 


Test patch:
Repository: Netflix/lemur

Issue:
Creating an authority does not allow others with the role to issue certificates
When creating an authority currently only the creator can see the authority, anyone with the owning role should be able to see and use the certificate.

Currently even when a valid role is assigned and the user can see the authority they cannot use it because the cannot access the authorities key.



Discussion:

Resolving patch:
diff --git a/lemur/authorities/service.py b/lemur/authorities/service.py
--- a/lemur/authorities/service.py
+++ b/lemur/authorities/service.py
@@ -101,6 +101,10 @@ def create(kwargs):
     database.update(cert)
     authority = database.create(authority)
 
+    # the owning dl or role should have this authority associated with it
+    owner_role = role_service.get_by_name(kwargs['ownerEmail'])
+    owner_role.authority = authority
+
     g.current_user.authorities.append(authority)
 
     return authority


Test patch:
Repository: Netflix/lemur

Issue:
Internal Server Error hitting auth/login API
Hitting the `/auth/login` API with a GET request returns an HTTP 500 error. The resource needs to be authenticated.



Discussion:
After looking at this I believe that route can just be removed. It is not called, /me is used instead.

See: https://github.com/Netflix/lemur/blob/master/lemur/users/views.py#L356


Resolving patch:
diff --git a/lemur/auth/views.py b/lemur/auth/views.py
--- a/lemur/auth/views.py
+++ b/lemur/auth/views.py
@@ -9,7 +9,7 @@
 import base64
 import requests
 
-from flask import g, Blueprint, current_app
+from flask import Blueprint, current_app
 
 from flask.ext.restful import reqparse, Resource, Api
 from flask.ext.principal import Identity, identity_changed
@@ -100,9 +100,6 @@ def post(self):
 
         return dict(message='The supplied credentials are invalid'), 401
 
-    def get(self):
-        return {'username': g.current_user.username, 'roles': [r.name for r in g.current_user.roles]}
-
 
 class Ping(Resource):
     """


Test patch:
Repository: Netflix/lemur

Issue:
Disabling and then re-enabling notifications causes notifications to go unsent
There is a bug in the way that a notification is 're-enabled' such that the interval value (number of days) becomes unset when the notification is marked as active again.



Discussion:

Resolving patch:
diff --git a/lemur/notifications/views.py b/lemur/notifications/views.py
--- a/lemur/notifications/views.py
+++ b/lemur/notifications/views.py
@@ -376,7 +376,7 @@ def put(self, notification_id):
            :statuscode 200: no error
         """
         self.reqparse.add_argument('label', type=str, location='json', required=True)
-        self.reqparse.add_argument('plugin', type=dict, location='json', required=True)
+        self.reqparse.add_argument('notificationOptions', type=list, location='json')
         self.reqparse.add_argument('active', type=bool, location='json')
         self.reqparse.add_argument('certificates', type=list, default=[], location='json')
         self.reqparse.add_argument('description', type=str, location='json')
@@ -385,7 +385,7 @@ def put(self, notification_id):
         return service.update(
             notification_id,
             args['label'],
-            args['plugin']['pluginOptions'],
+            args['notificationOptions'],
             args['description'],
             args['active'],
             args['certificates']


Test patch:
Repository: Netflix/lemur

Issue:
Create new roles for unknown owners
Currently when you create an authority with an unknown owner we get an error because we assumed that the owner is creating the authority.

This is not always the case as sometimes teams will create authorities on the behalf of other teams. We should just go ahead an create an owner_role if one does not exist.

```
2016-03-31 16:21:39,507 ERROR: 'NoneType' object has no attribute 'authority' [in /apps/lemur/lemur/common/utils.py:60]
Traceback (most recent call last):
  File "/apps/lemur/lemur/common/utils.py", line 46, in wrapper
    resp = f(*args, **kwargs)
  File "/apps/lemur/lemur/authorities/views.py", line 201, in post
    return service.create(args)
  File "/apps/lemur/lemur/authorities/service.py", line 106, in create
    owner_role.authority = authority
AttributeError: 'NoneType' object has no attribute 'authority'
```



Discussion:

Resolving patch:
diff --git a/lemur/authorities/service.py b/lemur/authorities/service.py
--- a/lemur/authorities/service.py
+++ b/lemur/authorities/service.py
@@ -103,6 +103,10 @@ def create(kwargs):
 
     # the owning dl or role should have this authority associated with it
     owner_role = role_service.get_by_name(kwargs['ownerEmail'])
+
+    if not owner_role:
+        owner_role = role_service.create(kwargs['ownerEmail'])
+
     owner_role.authority = authority
 
     g.current_user.authorities.append(authority)


Test patch:
Repository: Netflix/lemur

Issue:
Support validity period selection in years
Some CAs (DigiCert is one) only allow you to specify validity periods in integers (1, 2 or 3 years). There are no specific date selections allowed. Would be nice if there was a way in the GUI to quickly select one of these options. Implementation flexible.



Discussion:
Verisign/Symantec does something similar but they do allow for the ability to specify the end date. Does digicert disallow a given end date at all?

https://github.com/Netflix/lemur/blob/master/lemur/plugins/lemur_verisign/plugin.py#L100

So after reviewing the API they do support a specific end-date if you want to end it earlier that the standard 1,2,3 years. Suppose this is is more of a usability request. Right now we're having to select dates that fall into the 1/2 year bounds. Would be nice to be able to select an integer 1 or 2 or 3.

Got it. UI wise I think we could do a dropdown with 1, 2, 3 years and then an advanced box for users who want to specify an end date. 

That would be perfect!
On Thu, Dec 31, 2015 at 2:54 PM kevgliss notifications@github.com wrote:

> Got it. UI wise I think we could do a dropdown with 1, 2, 3 years and then
> an advanced box for users who want to specify an end date.
> 
> —
> Reply to this email directly or view it on GitHub
> https://github.com/Netflix/lemur/issues/195#issuecomment-168258235.


Resolving patch:
diff --git a/lemur/certificates/views.py b/lemur/certificates/views.py
--- a/lemur/certificates/views.py
+++ b/lemur/certificates/views.py
@@ -357,6 +357,7 @@ def post(self):
         self.reqparse.add_argument('replacements', type=list, default=[], location='json')
         self.reqparse.add_argument('validityStart', type=str, location='json')  # TODO validate
         self.reqparse.add_argument('validityEnd', type=str, location='json')  # TODO validate
+        self.reqparse.add_argument('validityYears', type=int, location='json')  # TODO validate
         self.reqparse.add_argument('authority', type=valid_authority, location='json', required=True)
         self.reqparse.add_argument('description', type=str, location='json')
         self.reqparse.add_argument('country', type=str, location='json', required=True)
diff --git a/lemur/plugins/lemur_verisign/plugin.py b/lemur/plugins/lemur_verisign/plugin.py
--- a/lemur/plugins/lemur_verisign/plugin.py
+++ b/lemur/plugins/lemur_verisign/plugin.py
@@ -82,6 +82,12 @@ def process_options(options):
         data['specificEndDate'] = str(end_date)
         data['validityPeriod'] = period
 
+    elif options.get('validityYears'):
+        if options['validityYears'] in [1, 2]:
+            data['validityPeriod'] = str(options['validityYears']) + 'Y'
+        else:
+            raise Exception("Verisign issued certificates cannot exceed two years in validity")
+
     return data
 
 


Test patch:
Repository: Netflix/lemur

Issue:
Document periodic tasks or jobs
There are a few pieces of functionality that are run periodically that should be called out in the documentation. Short list:

-notifiy 
-check_revoked
-sync_sources



Discussion:

Resolving patch:
diff --git a/lemur/manage.py b/lemur/manage.py
--- a/lemur/manage.py
+++ b/lemur/manage.py
@@ -30,7 +30,7 @@
 
 from lemur.plugins.lemur_aws import elb
 
-from lemur.sources.service import sync
+from lemur.sources.service import sync as source_sync
 
 from lemur import create_app
 
@@ -189,7 +189,7 @@ def generate_settings():
 
 
 @manager.option('-s', '--sources', dest='labels')
-def sync_sources(labels):
+def sync(labels):
     """
     Attempts to run several methods Certificate discovery. This is
     run on a periodic basis and updates the Lemur datastore with the
@@ -218,9 +218,9 @@ def sync_sources(labels):
                 labels = labels.split(",")
 
                 if labels[0] == 'all':
-                    sync()
+                    source_sync()
                 else:
-                    sync(labels=labels)
+                    source_sync(labels=labels)
 
                 sys.stdout.write(
                     "[+] Finished syncing sources. Run Time: {time}\n".format(


Test patch:
Repository: Netflix/lemur

Issue:
Chain Certificate is not exporting
Hi Team,

While extracting .p12 formatted file (which was exported from Lemur) we cannot find the Chain file on the same. Could you please let us know if we need to perform any additional step to download the .p12 along with the chain. 

Thanks,
Akash John



Discussion:
Verified this as a bug. Will look into a fix. 


Resolving patch:
diff --git a/lemur/plugins/lemur_openssl/plugin.py b/lemur/plugins/lemur_openssl/plugin.py
--- a/lemur/plugins/lemur_openssl/plugin.py
+++ b/lemur/plugins/lemur_openssl/plugin.py
@@ -33,11 +33,12 @@ def run_process(command):
         raise Exception(stderr)
 
 
-def create_pkcs12(cert, p12_tmp, key, alias, passphrase):
+def create_pkcs12(cert, chain, p12_tmp, key, alias, passphrase):
     """
     Creates a pkcs12 formated file.
     :param cert:
-    :param jks_tmp:
+    :param chain:
+    :param p12_tmp:
     :param key:
     :param alias:
     :param passphrase:
@@ -49,7 +50,7 @@ def create_pkcs12(cert, p12_tmp, key, alias, passphrase):
         # Create PKCS12 keystore from private key and public certificate
         with mktempfile() as cert_tmp:
             with open(cert_tmp, 'w') as f:
-                f.write(cert)
+                f.writelines([cert + "\n", chain + "\n"])
 
             run_process([
                 "openssl",
@@ -119,7 +120,7 @@ def export(self, body, chain, key, options, **kwargs):
 
         with mktemppath() as output_tmp:
             if type == 'PKCS12 (.p12)':
-                create_pkcs12(body, output_tmp, key, alias, passphrase)
+                create_pkcs12(body, chain, output_tmp, key, alias, passphrase)
                 extension = "p12"
             else:
                 raise Exception("Unable to export, unsupported type: {0}".format(type))


Test patch:
Repository: Netflix/lemur

Issue:
Lemur should re-direct you to 'next' page after login.
Lemur should do the right thing and re-direct back to the correct page after a login prompt.



Discussion:

Resolving patch:
diff --git a/lemur/manage.py b/lemur/manage.py
--- a/lemur/manage.py
+++ b/lemur/manage.py
@@ -864,7 +864,7 @@ def run(self, window):
 
 def main():
     manager.add_command("start", LemurServer())
-    manager.add_command("runserver", Server(host='127.0.0.1'))
+    manager.add_command("runserver", Server(host='127.0.0.1', threaded=True))
     manager.add_command("clean", Clean())
     manager.add_command("show_urls", ShowUrls())
     manager.add_command("db", MigrateCommand)


Test patch:
Repository: Netflix/lemur

Issue:
A custom cert name with spaces causes AWS Upload failures
Creating a cert with a custom name that has spaces, such as: `My Certificate` will not properly get uploaded to AWS.

-- Potential Fixes:
1. Prevent spaces in custom names
2. Allow custom cert names to be editable
3. If spaces are allowed, the AWS uploader plugin needs to upload it in a way that can work properly.



Discussion:
I don't like having the AWS plugin dictate core Lemur functionality. That being said, I don't particularly like having whitespace in custom names either. How do we feel about replacing any whitespace found in a certificate's custom name with a `-`? This would align it better with the generated names as well.

+1 to remove whitespace.


Resolving patch:
diff --git a/lemur/certificates/models.py b/lemur/certificates/models.py
--- a/lemur/certificates/models.py
+++ b/lemur/certificates/models.py
@@ -27,6 +27,7 @@
 
 
 def get_or_increase_name(name):
+    name = '-'.join(name.strip().split(' '))
     count = Certificate.query.filter(Certificate.name.ilike('{0}%'.format(name))).count()
 
     if count >= 1:


Test patch:
Repository: Netflix/lemur

Issue:
Owner change does not modify notifications.
When a certificate changes ownership, we should try to also update the notifications by removing the old defaults owners and applying new defaults. 



Discussion:

Resolving patch:
diff --git a/lemur/certificates/schemas.py b/lemur/certificates/schemas.py
--- a/lemur/certificates/schemas.py
+++ b/lemur/certificates/schemas.py
@@ -77,11 +77,25 @@ def ensure_dates(self, data):
 
 class CertificateEditInputSchema(CertificateSchema):
     notify = fields.Boolean()
+    owner = fields.String()
     destinations = fields.Nested(AssociatedDestinationSchema, missing=[], many=True)
     notifications = fields.Nested(AssociatedNotificationSchema, missing=[], many=True)
     replacements = fields.Nested(AssociatedCertificateSchema, missing=[], many=True)
     roles = fields.Nested(AssociatedRoleSchema, missing=[], many=True)
 
+    @post_load
+    def enforce_notifications(self, data):
+        """
+        Ensures that when an owner changes, default notifications are added for the new owner.
+        Old owner notifications are retained unless explicitly removed.
+        :param data:
+        :return:
+        """
+        if data['owner']:
+            notification_name = "DEFAULT_{0}".format(data['owner'].split('@')[0].upper())
+            data['notifications'] += notification_service.create_default_expiration_notifications(notification_name, [data['owner']])
+        return data
+
 
 class CertificateNestedOutputSchema(LemurOutputSchema):
     __envelope__ = False


Test patch:
diff --git a/lemur/tests/test_certificates.py b/lemur/tests/test_certificates.py
--- a/lemur/tests/test_certificates.py
+++ b/lemur/tests/test_certificates.py
@@ -9,6 +9,14 @@
     INTERNAL_VALID_LONG_STR, INTERNAL_VALID_SAN_STR, PRIVATE_KEY_STR
 
 
+def test_certificate_edit_schema(session):
+    from lemur.certificates.schemas import CertificateEditInputSchema
+
+    input_data = {'owner': 'bob@example.com'}
+    data, errors = CertificateEditInputSchema().load(input_data)
+    assert len(data['notifications']) == 3
+
+
 def test_authority_identifier_schema():
     from lemur.schemas import AuthorityIdentifierSchema
     input_data = {'useAuthorityCert': True}
Repository: Netflix/lemur

Issue:
Add example requests
Add example requests for certificate creation. 


Discussion:

Resolving patch:
diff --git a/lemur/certificates/views.py b/lemur/certificates/views.py
--- a/lemur/certificates/views.py
+++ b/lemur/certificates/views.py
@@ -146,6 +146,38 @@ def post(self, data=None):
               Host: example.com
               Accept: application/json, text/javascript
 
+              {
+                  "owner": "secure@example.net",
+                  "commonName": "test.example.net",
+                  "country": "US",
+                  "extensions": {
+                    "subAltNames": {
+                      "names": [
+                        {
+                          "nameType": "DNSName",
+                          "value": "*.test.example.net"
+                        },
+                        {
+                          "nameType": "DNSName",
+                          "value": "www.test.example.net"
+                        }
+                      ]
+                    }
+                  },
+                  "replaces": [{
+                    "id": 1
+                  },
+                  "validityEnd": "2026-01-01T08:00:00.000Z",
+                  "authority": {
+                    "name": "verisign"
+                  },
+                  "organization": "Netflix, Inc.",
+                  "location": "Los Gatos",
+                  "state": "California",
+                  "validityStart": "2016-11-11T04:19:48.000Z",
+                  "organizationalUnit": "Operations"
+              }
+
 
            **Example response**:
 
@@ -193,7 +225,9 @@ def post(self, data=None):
                     "id": 1090,
                     "name": "*.test.example.net"
                 }],
-                "replaces": [],
+                "replaces": [{
+                    "id": 1
+                }],
                 "name": "WILDCARD.test.example.net-SymantecCorporation-20160603-20180112",
                 "roles": [{
                     "id": 464,


Test patch: