bug 1413336 - (6/7) replace setComponentByName with direct property setters r?Cykesiopka draft
authorDavid Keeler <dkeeler@mozilla.com>
Tue, 14 Nov 2017 13:35:10 -0800
changeset 699150 efd024fefd93bb6a5f57f002afe8e250df601d34
parent 699149 f66b0bfc9e210879cb44cf33e2c3470fa4ec2388
child 699151 698ec9397daac42d48c522969202aee380505a35
push id89479
push userbmo:dkeeler@mozilla.com
push dateThu, 16 Nov 2017 18:28:32 +0000
reviewersCykesiopka
bugs1413336
milestone59.0a1
bug 1413336 - (6/7) replace setComponentByName with direct property setters r?Cykesiopka MozReview-Commit-ID: EIIzP04YHo9
security/manager/ssl/tests/unit/pycert.py
security/manager/ssl/tests/unit/pykey.py
--- a/security/manager/ssl/tests/unit/pycert.py
+++ b/security/manager/ssl/tests/unit/pycert.py
@@ -223,17 +223,17 @@ def getASN1Tag(asn1Type):
     return asn1Type.tagSet.baseTag.tagId
 
 def stringToAccessDescription(string):
     """Helper function that takes a string representing a URI
     presumably identifying an OCSP authority information access
     location. Returns an AccessDescription usable by pyasn1."""
     accessMethod = rfc2459.id_ad_ocsp
     accessLocation = rfc2459.GeneralName()
-    accessLocation.setComponentByName('uniformResourceIdentifier', string)
+    accessLocation['uniformResourceIdentifier'] = string
     sequence = univ.Sequence()
     sequence.setComponentByPosition(0, accessMethod)
     sequence.setComponentByPosition(1, accessLocation)
     return sequence
 
 def stringToDN(string, tag=None):
     """Takes a string representing a distinguished name or directory
     name and returns a Name for use by pyasn1. See the documentation
@@ -248,44 +248,44 @@ def stringToDN(string, tag=None):
     # split should now be [[encoding], <type>, <value>, <type>, <value>, ...]
     if split[0]:
         encoding = split[0]
     else:
         encoding = 'utf8String'
     for pos, (nameType, value) in enumerate(zip(split[1::2], split[2::2])):
         ava = rfc2459.AttributeTypeAndValue()
         if nameType == 'C':
-            ava.setComponentByName('type', rfc2459.id_at_countryName)
+            ava['type'] = rfc2459.id_at_countryName
             nameComponent = rfc2459.X520countryName(value)
         elif nameType == 'ST':
-            ava.setComponentByName('type', rfc2459.id_at_stateOrProvinceName)
+            ava['type'] = rfc2459.id_at_stateOrProvinceName
             nameComponent = rfc2459.X520StateOrProvinceName()
         elif nameType == 'L':
-            ava.setComponentByName('type', rfc2459.id_at_localityName)
+            ava['type'] = rfc2459.id_at_localityName
             nameComponent = rfc2459.X520LocalityName()
         elif nameType == 'O':
-            ava.setComponentByName('type', rfc2459.id_at_organizationName)
+            ava['type'] = rfc2459.id_at_organizationName
             nameComponent = rfc2459.X520OrganizationName()
         elif nameType == 'OU':
-            ava.setComponentByName('type', rfc2459.id_at_organizationalUnitName)
+            ava['type'] = rfc2459.id_at_organizationalUnitName
             nameComponent = rfc2459.X520OrganizationalUnitName()
         elif nameType == 'CN':
-            ava.setComponentByName('type', rfc2459.id_at_commonName)
+            ava['type'] = rfc2459.id_at_commonName
             nameComponent = rfc2459.X520CommonName()
         elif nameType == 'emailAddress':
-            ava.setComponentByName('type', rfc2459.emailAddress)
+            ava['type'] = rfc2459.emailAddress
             nameComponent = rfc2459.Pkcs9email(value)
         else:
             raise UnknownDNTypeError(nameType)
         if not nameType == 'C' and not nameType == 'emailAddress':
             # The value may have things like '\0' (i.e. a slash followed by
             # the number zero) that have to be decoded into the resulting
             # '\x00' (i.e. a byte with value zero).
-            nameComponent.setComponentByName(encoding, value.decode(encoding='string_escape'))
-        ava.setComponentByName('value', nameComponent)
+            nameComponent[encoding] = value.decode(encoding='string_escape')
+        ava['value'] = nameComponent
         rdn = rfc2459.RelativeDistinguishedName()
         rdn.setComponentByPosition(0, ava)
         rdns.setComponentByPosition(pos, rdn)
     if tag:
         name = rfc2459.Name().subtype(implicitTag=tag)
     else:
         name = rfc2459.Name()
     name.setComponentByPosition(0, rdns)
@@ -329,17 +329,17 @@ def stringToAlgorithmIdentifiers(string)
         nullEncapsulated = encoder.encode(univ.Null())
         algorithmIdentifier['parameters'] = univ.Any(nullEncapsulated)
     return (algorithmIdentifier, algorithmType)
 
 def datetimeToTime(dt):
     """Takes a datetime object and returns an rfc2459.Time object with
     that time as its value as a GeneralizedTime"""
     time = rfc2459.Time()
-    time.setComponentByName('generalTime', useful.GeneralizedTime(dt.strftime('%Y%m%d%H%M%SZ')))
+    time['generalTime'] = useful.GeneralizedTime(dt.strftime('%Y%m%d%H%M%SZ'))
     return time
 
 def serialBytesToString(serialBytes):
     """Takes a list of integers in the interval [0, 255] and returns
     the corresponding serial number string."""
     serialBytesLen = len(serialBytes)
     if serialBytesLen > 127:
         raise InvalidSerialNumber("{} bytes is too long".format(serialBytesLen))
@@ -510,35 +510,34 @@ class Certificate(object):
         else:
             raise UnknownKeyTargetError(subjectOrIssuer)
 
     def addExtension(self, extensionType, extensionValue, critical):
         if not self.extensions:
             self.extensions = []
         encapsulated = univ.OctetString(encoder.encode(extensionValue))
         extension = rfc2459.Extension()
-        extension.setComponentByName('extnID', extensionType)
+        extension['extnID'] = extensionType
         # critical is either the string '[critical]' or None.
         # We only care whether or not it is truthy.
         if critical:
-            extension.setComponentByName('critical', True)
-        extension.setComponentByName('extnValue', encapsulated)
+            extension['critical'] = True
+        extension['extnValue'] = encapsulated
         self.extensions.append(extension)
 
     def addBasicConstraints(self, basicConstraints, critical):
         cA = basicConstraints.split(',')[0]
         pathLenConstraint = basicConstraints.split(',')[1]
         basicConstraintsExtension = rfc2459.BasicConstraints()
-        basicConstraintsExtension.setComponentByName('cA', cA == 'cA')
+        basicConstraintsExtension['cA'] = cA == 'cA'
         if pathLenConstraint:
             pathLenConstraintValue = \
                 univ.Integer(int(pathLenConstraint)).subtype(
                     subtypeSpec=constraint.ValueRangeConstraint(0, float('inf')))
-            basicConstraintsExtension.setComponentByName('pathLenConstraint',
-                                                         pathLenConstraintValue)
+            basicConstraintsExtension['pathLenConstraint'] = pathLenConstraintValue
         self.addExtension(rfc2459.id_ce_basicConstraints, basicConstraintsExtension, critical)
 
     def addKeyUsage(self, keyUsage, critical):
         keyUsageExtension = rfc2459.KeyUsage(keyUsage)
         self.addExtension(rfc2459.id_ce_keyUsage, keyUsageExtension, critical)
 
     def keyPurposeToOID(self, keyPurpose):
         if keyPurpose == 'serverAuth':
@@ -565,39 +564,39 @@ class Certificate(object):
 
     def addSubjectAlternativeName(self, names, critical):
         subjectAlternativeName = rfc2459.SubjectAltName()
         for count, name in enumerate(names.split(',')):
             generalName = rfc2459.GeneralName()
             if '/' in name:
                 directoryName = stringToDN(name,
                                            tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 4))
-                generalName.setComponentByName('directoryName', directoryName)
+                generalName['directoryName'] = directoryName
             else:
                 # The string may have things like '\0' (i.e. a slash
                 # followed by the number zero) that have to be decoded into
                 # the resulting '\x00' (i.e. a byte with value zero).
-                generalName.setComponentByName('dNSName', name.decode(encoding='string_escape'))
+                generalName['dNSName'] = name.decode(encoding='string_escape')
             subjectAlternativeName.setComponentByPosition(count, generalName)
         self.addExtension(rfc2459.id_ce_subjectAltName, subjectAlternativeName, critical)
 
     def addAuthorityInformationAccess(self, ocspURI, critical):
         sequence = univ.Sequence()
         accessDescription = stringToAccessDescription(ocspURI)
         sequence.setComponentByPosition(0, accessDescription)
         self.addExtension(rfc2459.id_pe_authorityInfoAccess, sequence, critical)
 
     def addCertificatePolicies(self, policyOIDs, critical):
         policies = rfc2459.CertificatePolicies()
         for pos, policyOID in enumerate(policyOIDs.split(',')):
             if policyOID == 'any':
                 policyOID = '2.5.29.32.0'
             policy = rfc2459.PolicyInformation()
             policyIdentifier = rfc2459.CertPolicyId(policyOID)
-            policy.setComponentByName('policyIdentifier', policyIdentifier)
+            policy['policyIdentifier'] = policyIdentifier
             policies.setComponentByPosition(pos, policy)
         self.addExtension(rfc2459.id_ce_certificatePolicies, policies, critical)
 
     def addNameConstraints(self, constraints, critical):
         nameConstraints = rfc2459.NameConstraints()
         if constraints.startswith('permitted:'):
             (subtreesType, subtreesTag) = ('permittedSubtrees', 0)
         elif constraints.startswith('excluded:'):
@@ -607,23 +606,23 @@ class Certificate(object):
         generalSubtrees = rfc2459.GeneralSubtrees().subtype(
             implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, subtreesTag))
         subtrees = constraints[(constraints.find(':') + 1):]
         for pos, name in enumerate(subtrees.split(',')):
             generalName = rfc2459.GeneralName()
             if '/' in name:
                 directoryName = stringToDN(name,
                                            tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 4))
-                generalName.setComponentByName('directoryName', directoryName)
+                generalName['directoryName'] = directoryName
             else:
-                generalName.setComponentByName('dNSName', name)
+                generalName['dNSName'] = name
             generalSubtree = rfc2459.GeneralSubtree()
-            generalSubtree.setComponentByName('base', generalName)
+            generalSubtree['base'] = generalName
             generalSubtrees.setComponentByPosition(pos, generalSubtree)
-        nameConstraints.setComponentByName(subtreesType, generalSubtrees)
+        nameConstraints[subtreesType] = generalSubtrees
         self.addExtension(rfc2459.id_ce_nameConstraints, nameConstraints, critical)
 
     def addNSCertType(self, certType, critical):
         if certType != 'sslServer':
             raise UnknownNSCertTypeError(certType)
         self.addExtension(univ.ObjectIdentifier('2.16.840.1.113730.1.1'), univ.BitString("'01'B"),
                           critical)
 
@@ -674,56 +673,55 @@ class Certificate(object):
     def getSerialNumber(self):
         return decoder.decode(self.serialNumber)[0]
 
     def getIssuer(self):
         return stringToDN(self.issuer)
 
     def getValidity(self):
         validity = rfc2459.Validity()
-        validity.setComponentByName('notBefore', self.getNotBefore())
-        validity.setComponentByName('notAfter', self.getNotAfter())
+        validity['notBefore'] = self.getNotBefore()
+        validity['notAfter'] = self.getNotAfter()
         return validity
 
     def getNotBefore(self):
         return datetimeToTime(self.notBefore)
 
     def getNotAfter(self):
         return datetimeToTime(self.notAfter)
 
     def getSubject(self):
         return stringToDN(self.subject)
 
     def getTBSCertificate(self):
         (signatureOID, _) = stringToAlgorithmIdentifiers(self.signature)
         tbsCertificate = rfc2459.TBSCertificate()
-        tbsCertificate.setComponentByName('version', self.getVersion())
-        tbsCertificate.setComponentByName('serialNumber', self.getSerialNumber())
-        tbsCertificate.setComponentByName('signature', signatureOID)
-        tbsCertificate.setComponentByName('issuer', self.getIssuer())
-        tbsCertificate.setComponentByName('validity', self.getValidity())
-        tbsCertificate.setComponentByName('subject', self.getSubject())
-        tbsCertificate.setComponentByName('subjectPublicKeyInfo',
-                                          self.subjectKey.asSubjectPublicKeyInfo())
+        tbsCertificate['version'] = self.getVersion()
+        tbsCertificate['serialNumber'] = self.getSerialNumber()
+        tbsCertificate['signature'] = signatureOID
+        tbsCertificate['issuer'] = self.getIssuer()
+        tbsCertificate['validity'] = self.getValidity()
+        tbsCertificate['subject'] = self.getSubject()
+        tbsCertificate['subjectPublicKeyInfo'] = self.subjectKey.asSubjectPublicKeyInfo()
         if self.extensions:
             extensions = rfc2459.Extensions().subtype(
                 explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3))
             for count, extension in enumerate(self.extensions):
                 extensions.setComponentByPosition(count, extension)
-            tbsCertificate.setComponentByName('extensions', extensions)
+            tbsCertificate['extensions'] = extensions
         return tbsCertificate
 
     def toDER(self):
         (signatureOID, hashAlgorithm) = stringToAlgorithmIdentifiers(self.signature)
         certificate = rfc2459.Certificate()
         tbsCertificate = self.getTBSCertificate()
-        certificate.setComponentByName('tbsCertificate', tbsCertificate)
-        certificate.setComponentByName('signatureAlgorithm', signatureOID)
+        certificate['tbsCertificate'] = tbsCertificate
+        certificate['signatureAlgorithm'] = signatureOID
         tbsDER = encoder.encode(tbsCertificate)
-        certificate.setComponentByName('signatureValue', self.issuerKey.sign(tbsDER, hashAlgorithm))
+        certificate['signatureValue'] = self.issuerKey.sign(tbsDER, hashAlgorithm)
         return encoder.encode(certificate)
 
     def toPEM(self):
         output = '-----BEGIN CERTIFICATE-----'
         der = self.toDER()
         b64 = base64.b64encode(der)
         while b64:
             output += '\n' + b64[:64]
--- a/security/manager/ssl/tests/unit/pykey.py
+++ b/security/manager/ssl/tests/unit/pykey.py
@@ -530,62 +530,62 @@ class RSAKey(object):
             self.RSA_exp1 = self.rsa1016_exp1
             self.RSA_exp2 = self.rsa1016_exp2
             self.RSA_coef = self.rsa1016_coef
         else:
             raise UnknownKeySpecificationError(specification)
 
     def toDER(self):
         privateKeyInfo = PrivateKeyInfo()
-        privateKeyInfo.setComponentByName('version', 0)
+        privateKeyInfo['version'] = 0
         algorithmIdentifier = rfc2459.AlgorithmIdentifier()
-        algorithmIdentifier.setComponentByName('algorithm', rfc2459.rsaEncryption)
+        algorithmIdentifier['algorithm'] = rfc2459.rsaEncryption
         # Directly setting parameters to univ.Null doesn't currently work.
         nullEncapsulated = encoder.encode(univ.Null())
         algorithmIdentifier['parameters'] = univ.Any(nullEncapsulated)
-        privateKeyInfo.setComponentByName('privateKeyAlgorithm', algorithmIdentifier)
+        privateKeyInfo['privateKeyAlgorithm'] = algorithmIdentifier
         rsaPrivateKey = RSAPrivateKey()
-        rsaPrivateKey.setComponentByName('version', 0)
-        rsaPrivateKey.setComponentByName('modulus', self.RSA_N)
-        rsaPrivateKey.setComponentByName('publicExponent', self.RSA_E)
-        rsaPrivateKey.setComponentByName('privateExponent', self.RSA_D)
-        rsaPrivateKey.setComponentByName('prime1', self.RSA_P)
-        rsaPrivateKey.setComponentByName('prime2', self.RSA_Q)
-        rsaPrivateKey.setComponentByName('exponent1', self.RSA_exp1)
-        rsaPrivateKey.setComponentByName('exponent2', self.RSA_exp2)
-        rsaPrivateKey.setComponentByName('coefficient', self.RSA_coef)
+        rsaPrivateKey['version'] = 0
+        rsaPrivateKey['modulus'] = self.RSA_N
+        rsaPrivateKey['publicExponent'] = self.RSA_E
+        rsaPrivateKey['privateExponent'] = self.RSA_D
+        rsaPrivateKey['prime1'] = self.RSA_P
+        rsaPrivateKey['prime2'] = self.RSA_Q
+        rsaPrivateKey['exponent1'] = self.RSA_exp1
+        rsaPrivateKey['exponent2'] = self.RSA_exp2
+        rsaPrivateKey['coefficient'] = self.RSA_coef
         rsaPrivateKeyEncoded = encoder.encode(rsaPrivateKey)
-        privateKeyInfo.setComponentByName('privateKey', univ.OctetString(rsaPrivateKeyEncoded))
+        privateKeyInfo['privateKey'] = univ.OctetString(rsaPrivateKeyEncoded)
         return encoder.encode(privateKeyInfo)
 
     def toPEM(self):
         output = '-----BEGIN PRIVATE KEY-----'
         der = self.toDER()
         b64 = base64.b64encode(der)
         while b64:
             output += '\n' + b64[:64]
             b64 = b64[64:]
         output += '\n-----END PRIVATE KEY-----\n'
         return output
 
     def asSubjectPublicKeyInfo(self):
         """Returns a subject public key info representing
         this key for use by pyasn1."""
         algorithmIdentifier = rfc2459.AlgorithmIdentifier()
-        algorithmIdentifier.setComponentByName('algorithm', rfc2459.rsaEncryption)
+        algorithmIdentifier['algorithm'] = rfc2459.rsaEncryption
         # Directly setting parameters to univ.Null doesn't currently work.
         nullEncapsulated = encoder.encode(univ.Null())
         algorithmIdentifier['parameters'] = univ.Any(nullEncapsulated)
         spki = rfc2459.SubjectPublicKeyInfo()
-        spki.setComponentByName('algorithm', algorithmIdentifier)
+        spki['algorithm'] = algorithmIdentifier
         rsaKey = RSAPublicKey()
-        rsaKey.setComponentByName('N', univ.Integer(self.RSA_N))
-        rsaKey.setComponentByName('E', univ.Integer(self.RSA_E))
+        rsaKey['N'] = univ.Integer(self.RSA_N)
+        rsaKey['E'] = univ.Integer(self.RSA_E)
         subjectPublicKey = univ.BitString(byteStringToHexifiedBitString(encoder.encode(rsaKey)))
-        spki.setComponentByName('subjectPublicKey', subjectPublicKey)
+        spki['subjectPublicKey'] = subjectPublicKey
         return spki
 
     def sign(self, data, hashAlgorithm):
         """Returns a hexified bit string representing a
         signature by this key over the specified data.
         Intended for use with pyasn1.type.univ.BitString"""
         hashAlgorithmName = None
         if hashAlgorithm == HASH_MD5:
@@ -683,33 +683,33 @@ class ECCKey(object):
             self.keyOID = secp521r1
         else:
             raise UnknownKeySpecificationError(specification)
 
     def asSubjectPublicKeyInfo(self):
         """Returns a subject public key info representing
         this key for use by pyasn1."""
         algorithmIdentifier = rfc2459.AlgorithmIdentifier()
-        algorithmIdentifier.setComponentByName('algorithm', ecPublicKey)
-        algorithmIdentifier.setComponentByName('parameters', self.keyOID)
+        algorithmIdentifier['algorithm'] = ecPublicKey
+        algorithmIdentifier['parameters'] = self.keyOID
         spki = rfc2459.SubjectPublicKeyInfo()
-        spki.setComponentByName('algorithm', algorithmIdentifier)
+        spki['algorithm'] = algorithmIdentifier
         # We need to extract the point that represents this key.
         # The library encoding of the key is an 8-byte id, followed by 2
         # bytes for the key length in bits, followed by the point on the
         # curve (represented by two python longs). There appear to also
         # be 2 bytes indicating the length of the point as encoded, but
         # Decoder takes care of that.
         encoded = self.key.encode()
         _, _, points = encoding.Decoder(encoded).int(8).int(2).point(2).out()
         # '04' indicates that the points are in uncompressed form.
         hexifiedBitString = "'%s%s%s'H" % ('04', longToEvenLengthHexString(points[0]),
                                            longToEvenLengthHexString(points[1]))
         subjectPublicKey = univ.BitString(hexifiedBitString)
-        spki.setComponentByName('subjectPublicKey', subjectPublicKey)
+        spki['subjectPublicKey'] = subjectPublicKey
         return spki
 
     def sign(self, data, hashAlgorithm):
         """Returns a hexified bit string representing a
         signature by this key over the specified data.
         Intended for use with pyasn1.type.univ.BitString"""
         # There is some non-determinism in ECDSA signatures. Work around
         # this by patching ecc.ecdsa.urandom to not be random.
@@ -719,18 +719,18 @@ class ECCKey(object):
             # of a SEQUENCE of two INTEGERs.
             # Also patch in secp256k1 if applicable.
             if self.keyOID == secp256k1:
                 with mock.patch('ecc.curves.DOMAINS', {256: secp256k1Params}):
                     x, y = encoding.dec_point(self.key.sign(data, hashAlgorithm.split(':')[-1]))
             else:
                 x, y = encoding.dec_point(self.key.sign(data, hashAlgorithm.split(':')[-1]))
             point = ECPoint()
-            point.setComponentByName('x', x)
-            point.setComponentByName('y', y)
+            point['x'] = x
+            point['y'] = y
             return byteStringToHexifiedBitString(encoder.encode(point))
 
 
 def keyFromSpecification(specification):
     """Pass in a specification, get the appropriate key back."""
     if specification.startswith('secp'):
         return ECCKey(specification)
     else: