Commit 7f9e56cf authored by Vincent Pelletier's avatar Vincent Pelletier Committed by Vincent Pelletier

all: Reduce differences with python3.

Using only 2to3 conversions which are python2-compatible.
parent 719959e0
......@@ -625,7 +625,7 @@ class CertificateAuthority(object):
self._renewCAIfNeeded()
result = []
iter_key_pair = iter(self._ca_key_pairs_list)
first_key_pair = iter_key_pair.next()
first_key_pair = next(iter_key_pair)
previous_crt_pem = utils.dump_certificate(first_key_pair['crt'])
previous_key = first_key_pair['key']
for key_pair in iter_key_pair:
......
......@@ -18,7 +18,7 @@
"""
Caucase - Certificate Authority for Users, Certificate Authority for SErvices
"""
from __future__ import absolute_import
from __future__ import absolute_import, print_function
import argparse
import datetime
import httplib
......@@ -63,7 +63,7 @@ class RetryingCaucaseClient(CaucaseClient):
httplib.IncompleteRead,
):
connection.close() # Resets HTTPConnection state machine.
print 'Got a network error, retrying in a bit...'
print('Got a network error, retrying in a bit...')
traceback.print_exc()
self._until(datetime.datetime.now() + datetime.timedelta(0, 10))
......@@ -94,7 +94,7 @@ class CLICaucaseClient(object):
csr_pem = utils.getCertRequest(csr_path)
# Quick sanity check
utils.load_certificate_request(csr_pem)
print self._client.createCertificateSigningRequest(csr_pem), csr_path
print(self._client.createCertificateSigningRequest(csr_pem), csr_path)
def getCSR(self, csr_id_path_list):
"""
......@@ -113,45 +113,47 @@ class CLICaucaseClient(object):
crt_id = int(crt_id)
try:
crt_pem = self._client.getCertificate(crt_id)
except CaucaseError, e:
except CaucaseError as e:
if e.args[0] != httplib.NOT_FOUND:
raise
try:
self._client.getCertificateSigningRequest(crt_id)
except CaucaseError, e:
except CaucaseError as e:
if e.args[0] != httplib.NOT_FOUND:
raise
print crt_id, 'not found - maybe CSR was rejected ?'
print(crt_id, 'not found - maybe CSR was rejected ?')
error = True
else:
print crt_id, 'CSR still pending'
print(crt_id, 'CSR still pending')
warning = True
else:
print crt_id,
print(crt_id, end=' ')
if utils.isCertificateAutoSigned(utils.load_certificate(
crt_pem,
ca_list,
None,
)):
print 'was (originally) automatically approved'
print('was (originally) automatically approved')
else:
print 'was (originally) manually approved'
print('was (originally) manually approved')
if os.path.exists(crt_path):
try:
key_pem = utils.getKey(crt_path)
except ValueError:
print >>sys.stderr, (
print(
'Expected to find exactly one privatekey key in %s, skipping' % (
crt_path,
)
),
file=sys.stderr,
)
error = True
continue
try:
utils.validateCertAndKey(crt_pem, key_pem)
except ValueError:
print >>sys.stderr, (
'Key in %s does not match retrieved certificate, skipping'
print(
'Key in %s does not match retrieved certificate, skipping',
file=sys.stderr,
)
error = True
continue
......@@ -167,10 +169,11 @@ class CLICaucaseClient(object):
try:
crt, key, _ = utils.getKeyPair(crt_path, key_path)
except ValueError:
print >>sys.stderr, (
print(
'Could not find (exactly) one matching key pair in %s, skipping' % (
[x for x in set((crt_path, key_path)) if x]
)
[x for x in set((crt_path, key_path)) if x],
),
file=sys.stderr,
)
error = True
continue
......@@ -196,10 +199,11 @@ class CLICaucaseClient(object):
key_path,
)
except ValueError:
print >>sys.stderr, (
print(
'Could not find (exactly) one matching key pair in %s, skipping' % (
[x for x in set((crt_path, key_path)) if x]
)
[x for x in set((crt_path, key_path)) if x],
),
file=sys.stderr,
)
error = True
continue
......@@ -210,12 +214,13 @@ class CLICaucaseClient(object):
None,
)
except exceptions.CertificateVerificationError:
print crt_path, (
'was not signed by this CA, revoked or otherwise invalid, skipping'
print(
crt_path,
'was not signed by this CA, revoked or otherwise invalid, skipping',
)
continue
if renewal_deadline < old_crt.not_valid_after:
print crt_path, 'did not reach renew threshold, not renewing'
print(crt_path, 'did not reach renew threshold, not renewing')
continue
new_key_pem, new_crt_pem = self._client.renewCertificate(
old_crt=old_crt,
......@@ -237,18 +242,22 @@ class CLICaucaseClient(object):
"""
--list-csr
"""
print '-- pending', mode, 'CSRs --'
print '%20s | %s' % (
'csr_id',
'subject preview (fetch csr and check full content !)',
print('-- pending', mode, 'CSRs --')
print(
'%20s | %s' % (
'csr_id',
'subject preview (fetch csr and check full content !)',
),
)
for entry in self._client.getPendingCertificateRequestList():
csr = utils.load_certificate_request(entry['csr'])
print '%20s | %r' % (
entry['id'],
csr.subject,
print(
'%20s | %r' % (
entry['id'],
csr.subject,
),
)
print '-- end of pending', mode, 'CSRs --'
print('-- end of pending', mode, 'CSRs --')
def signCSR(self, csr_id_list):
"""
......@@ -291,10 +300,11 @@ class CLICaucaseClient(object):
# authenticated revocations).
crt_pem = utils.getCert(crt_path)
except ValueError:
print >>sys.stderr, (
print(
'Could not load a single certificate in %s, skipping' % (
crt_path,
)
),
file=sys.stderr,
)
self._client.revokeCertificate(crt_pem)
return error
......@@ -506,9 +516,10 @@ def main(argv=None):
sign_with_csr_id_set.intersection(args.reject_csr) or
sign_csr_id_set.intersection(sign_with_csr_id_set)
):
print >>sys.stderr, (
print(
'A given CSR_ID cannot be in more than one of --sign-csr, '
'--sign-csr-with and --reject-csr'
'--sign-csr-with and --reject-csr',
file=sys.stderr,
)
raise SystemExit(STATUS_ERROR)
......@@ -733,16 +744,16 @@ def updater(argv=None, until=utils.until):
ca_crt_pem_list=utils.getCertList(args.cas_ca)
)
if args.crt and not utils.hasOneCert(args.crt):
print 'Bootstraping...'
print('Bootstraping...')
csr_pem = utils.getCertRequest(args.csr)
# Quick sanity check before bothering server
utils.load_certificate_request(csr_pem)
csr_id = client.createCertificateSigningRequest(csr_pem)
print 'Waiting for signature of', csr_id
print('Waiting for signature of', csr_id)
while True:
try:
crt_pem = client.getCertificate(csr_id)
except CaucaseError, e:
except CaucaseError as e:
if e.args[0] != httplib.NOT_FOUND:
raise
# If server does not know our CSR anymore, getCSR will raise.
......@@ -756,11 +767,12 @@ def updater(argv=None, until=utils.until):
crt_file.write(crt_pem)
updated = True
break
print 'Bootstrap done'
print('Bootstrap done')
next_deadline = datetime.datetime.utcnow()
while True:
print 'Next wake-up at', next_deadline.strftime(
'%Y-%m-%d %H:%M:%S +0000'
print(
'Next wake-up at',
next_deadline.strftime('%Y-%m-%d %H:%M:%S +0000'),
)
now = until(next_deadline)
next_deadline = now + max_sleep
......@@ -773,7 +785,7 @@ def updater(argv=None, until=utils.until):
ca_crt_pem_list=utils.getCertList(args.cas_ca)
)
if RetryingCaucaseClient.updateCAFile(ca_url, args.ca):
print 'Got new CA'
print('Got new CA')
updated = True
# Note: CRL expiration should happen several time during CA renewal
# period, so it should not be needed to keep track of CA expiration
......@@ -783,7 +795,7 @@ def updater(argv=None, until=utils.until):
for x in utils.getCertList(args.ca)
]
if RetryingCaucaseClient.updateCRLFile(ca_url, args.crl, ca_crt_list):
print 'Got new CRL'
print('Got new CRL')
updated = True
next_deadline = min(
next_deadline,
......@@ -793,7 +805,7 @@ def updater(argv=None, until=utils.until):
crt_pem, key_pem, key_path = utils.getKeyPair(args.crt, args.key)
crt = utils.load_certificate(crt_pem, ca_crt_list, None)
if crt.not_valid_after - threshold <= now:
print 'Renewing', args.crt
print('Renewing', args.crt)
new_key_pem, new_crt_pem = client.renewCertificate(
old_crt=crt,
old_key=utils.load_privatekey(key_pem),
......@@ -823,7 +835,7 @@ def updater(argv=None, until=utils.until):
if args.on_renew is not None:
status = os.system(args.on_renew)
if status:
print >>sys.stderr, 'Renewal hook exited with status:', status
print('Renewal hook exited with status:', status, file=sys.stderr)
raise SystemExit(STATUS_ERROR)
updated = False
except (utils.SleepInterrupt, SystemExit):
......@@ -880,7 +892,7 @@ def rerequest(argv=None):
),
)
key_pem = utils.dump_privatekey(key)
orig_umask = os.umask(0177)
orig_umask = os.umask(0o177)
try:
with open(args.key, 'w') as key_file:
key_file.write(key_pem)
......@@ -914,11 +926,14 @@ def key_id(argv=None):
)
args = parser.parse_args(argv)
for key_path in args.private_key:
print key_path, x509.SubjectKeyIdentifier.from_public_key(
utils.load_privatekey(open(key_path).read()).public_key(),
).digest.encode('hex')
print(
key_path,
x509.SubjectKeyIdentifier.from_public_key(
utils.load_privatekey(open(key_path).read()).public_key(),
).digest.encode('hex'),
)
for backup_path in args.backup:
print backup_path
print(backup_path)
with open(backup_path) as backup_file:
magic = backup_file.read(8)
if magic != 'caucase\0':
......@@ -928,4 +943,4 @@ def key_id(argv=None):
backup_file.read(struct.calcsize('<I')),
)
for key_entry in json.loads(backup_file.read(header_len))['key_list']:
print ' ', key_entry['id']
print(' ', key_entry['id'])
......@@ -107,7 +107,7 @@ def canConnect(address): # pragma: no cover
"""
try:
socket.create_connection(address)
except socket.error, e:
except socket.error as e:
if e.errno == errno.ECONNREFUSED:
return False
raise
......@@ -334,7 +334,7 @@ class CaucaseTest(unittest.TestCase):
new_key_path,
),
)
except SystemExit, e:
except SystemExit as e:
return e.code # pragma: no cover
except: # pylint: disable=bare-except
return 1
......@@ -896,7 +896,7 @@ class CaucaseTest(unittest.TestCase):
client = CaucaseClient(self._caucase_url + '/cas')
try:
client.createCertificateSigningRequest('Not actually a CSR')
except CaucaseError, e:
except CaucaseError as e:
self.assertEqual(e.args[0], 400, e)
else: # pragma: no cover
raise AssertionError('Did not raise CaucaseError(400, ...)')
......
......@@ -264,7 +264,7 @@ def _verifyCertificateChain(cert, trusted_cert_list, crl):
except (
crypto.X509StoreContextError,
crypto.Error,
), e:
) as e:
raise CertificateVerificationError(
'Certificate verification error: %s' % str(e),
)
......
......@@ -572,13 +572,13 @@ class Application(object):
raise InsufficientStorage
except exceptions.NotJSON:
raise BadRequest('Invalid json payload')
except exceptions.CertificateAuthorityException, e:
except exceptions.CertificateAuthorityException as e:
raise BadRequest(str(e))
except Exception:
environ['wsgi.errors'].write('Unhandled exception\n')
traceback.print_exc(file=environ['wsgi.errors'])
raise ApplicationError
except ApplicationError, e:
except ApplicationError as e:
status = e.status
header_list = e.response_headers
result = [str(x) for x in e.args]
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment