def stoken_upload(): """Upload the smime.p7m supplied from the DEP, ASM or ABM portals and decrypt it with a matching private key from our database, storing the result in the ``dep_configurations`` table. :reqheader Accept: application/vnd.api+json :reqheader Content-Type: multipart/form-data :statuscode 200: token decrypted ok :statuscode 400: token was unable to be decrypted. :statuscode 500: system error """ if 'file' not in request.files: abort(400, 'no file uploaded in request data') f = request.files['file'] try: certificate_model = db.session.query( DEPServerTokenCertificate).filter_by( x509_cn='COMMANDMENT-DEP').one() except sqlalchemy.orm.exc.NoResultFound: return abort( 400, "No DEP certificate generated, impossible to decrypt the DEP token" ) pk: RSAPrivateKey = certificate_model.rsa_private_key pk_crypto = pk.to_crypto() smime_data = f.read() payload = smime.decrypt(smime_data, pk_crypto) # dirty, dirty hacks for now. python email does not strip boundaries payload = payload.replace('-----BEGIN MESSAGE-----', '').replace('-----END MESSAGE-----', '') try: stoken = json.loads(payload) except json.decoder.JSONDecodeError: current_app.logger.debug(payload) return abort( 400, "Failed to decode token, could not parse JSON data inside S/MIME data" ) try: dep_account = db.session.query(DEPAccount).one() except sqlalchemy.orm.exc.NoResultFound: dep_account = DEPAccount() dep_account.certificate = certificate_model dep_account.consumer_key = stoken['consumer_key'] dep_account.consumer_secret = stoken['consumer_secret'] dep_account.access_token = stoken['access_token'] dep_account.access_secret = stoken['access_secret'] dep_account.access_token_expiry = dateutil.parser.parse( stoken['access_token_expiry']) dep_account.token_updated_at = datetime.datetime.utcnow() db.session.commit()
def test_decrypt(self): with open(DEP_TOKEN_SMIME_PATH, 'rb') as fd: message = fd.read() with open(DEP_TOKEN_KEY_PATH, 'rb') as fd: pem_key = fd.read() pk = serialization.load_pem_private_key( pem_key, backend=default_backend(), password=None, ) result = smime.decrypt(message, pk) print(result)
def test_load(self): result = smime.decrypt(DEP_TOKEN_SMIME_PATH)