Skip to content

Commit

Permalink
[models] Coerce x509 subject fields to strings
Browse files Browse the repository at this point in the history
This change allows subclasses to redefine the following
fields as foreign keys without losing compatibility:
- country_code
- state
- city
- organization
- email
- common_name
  • Loading branch information
nemesifier committed Jan 4, 2017
1 parent c17992a commit 34bb2dc
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
5 changes: 5 additions & 0 deletions django_x509/base/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from jsonfield import JSONField
from model_utils.fields import AutoCreatedField, AutoLastModifiedField
from OpenSSL import crypto
from six import string_types

from .. import settings as app_settings
from ..utils import bytes_compat
Expand Down Expand Up @@ -220,6 +221,10 @@ def _fill_subject(self, subject):
for model_attr, subject_attr in attr_map.items():
value = getattr(self, model_attr)
if value:
# coerce value to string, allow these fields to be redefined
# as foreign keys by subclasses without losing compatibility
if not isinstance(value, string_types):
value = str(value)
setattr(subject, subject_attr, value)
return subject

Expand Down
13 changes: 10 additions & 3 deletions django_x509/tests/test_ca.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ class TestCa(TestCase):
"""
tests for Ca model
"""
def _create_ca(self, ext=[]):
ca = Ca(name='newcert',
def _create_ca(self, organization='OpenWISP', ext=[]):
ca = Ca(name='Test CA',
key_length='2048',
digest='sha256',
country_code='IT',
state='RM',
city='Rome',
organization='OpenWISP',
organization=organization,
email='test@test.com',
common_name='openwisp.org',
extensions=ext)
Expand Down Expand Up @@ -413,3 +413,10 @@ def test_x509_import_exception_fixed(self):
ca.full_clean()
ca.save()
self.assertEqual(ca.email, '')

def test_fill_subject_non_strings(self):
ca1 = self._create_ca()
ca2 = Ca(name='ca', organization=ca1)
x509 = crypto.X509()
subject = ca2._fill_subject(x509.get_subject())
self.assertEqual(subject.organizationName, 'Test CA')

0 comments on commit 34bb2dc

Please sign in to comment.