Collapse Configuration classes, adjust middleware certificate validation

pull/447/head
Kieran Prasch 2018-09-22 21:04:40 -07:00
parent 5e10e48f54
commit 6b0d7c956c
7 changed files with 54 additions and 51 deletions

View File

@ -515,11 +515,11 @@ class Character(Learner):
try:
# TODO: Streamline path generation
certificate_path = os.path.join(self.known_certificates_dir, current_teacher.certificate_filename)
certificate_filepath = os.path.join(self.known_certificates_dir, current_teacher.certificate_filename)
response = self.network_middleware.get_nodes_via_rest(url=rest_url,
nodes_i_need=self._node_ids_to_learn_about_immediately,
announce_nodes=announce_nodes,
certificate_path=certificate_path)
certificate_filepath=certificate_filepath)
except requests.exceptions.ConnectionError as e:
unresponsive_nodes.add(current_teacher)
teacher_rest_info = current_teacher.rest_information()[0]

View File

@ -1,28 +1,27 @@
import binascii
import os
import random
from collections import OrderedDict
from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurve
from functools import partial
from typing import Iterable
from typing import List
import maya
import time
from bytestring_splitter import BytestringSplitter, VariableLengthBytestring
from constant_sorrow import constants
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurve
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.x509 import load_pem_x509_certificate, Certificate
from eth_utils import to_checksum_address
from functools import partial
from twisted.internet import threads
from typing import Iterable
from typing import List
from umbral.keys import UmbralPublicKey
from umbral.signing import Signature
from nucypher.blockchain.eth.actors import PolicyAuthor, Miner, only_me
from nucypher.blockchain.eth.agents import MinerAgent
from nucypher.blockchain.eth.constants import datetime_to_period
from nucypher.characters.base import Character
from nucypher.characters.base import Character, Learner
from nucypher.config.parsers import parse_character_config
from nucypher.crypto.api import keccak_digest
from nucypher.crypto.constants import PUBLIC_ADDRESS_LENGTH, PUBLIC_KEY_LENGTH

View File

@ -5,7 +5,7 @@ from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurve
from cryptography.x509 import Certificate
from nucypher.blockchain.eth.agents import EthereumContractAgent
from nucypher.blockchain.eth.agents import EthereumContractAgent, PolicyAgent
from nucypher.config.constants import DEFAULT_CONFIG_FILE_LOCATION
from nucypher.config.node import NodeConfiguration
from nucypher.crypto.powers import CryptoPower
@ -132,35 +132,24 @@ class UrsulaConfiguration(NodeConfiguration):
class AliceConfiguration(NodeConfiguration):
from nucypher.characters.lawful import Alice
from nucypher.config.parsers import parse_alice_config
def __init__(self,
policy_agent: EthereumContractAgent = None,
*args, **kwargs
) -> None:
super().__init__(*args, **kwargs)
_Character = Alice
_parser = parse_alice_config
def __init__(self, policy_agent: EthereumContractAgent = None, *args, **kwargs) -> None:
self.policy_agent = policy_agent
super().__init__(*args, **kwargs)
@property
def payload(self) -> dict:
alice_payload = dict(
policy_agent=self.policy_agent
)
alice_payload = dict(policy_agent=self.policy_agent)
base_payload = super().payload
alice_payload.update(base_payload)
return base_payload
def produce(self, **overrides):
merged_parameters = {**self.payload, **overrides}
from nucypher.characters.lawful import Alice
alice = Alice(**merged_parameters)
return alice
@classmethod
def from_configuration_file(cls, filepath=None) -> 'AliceConfiguration':
from nucypher.config.parsers import parse_alice_config
filepath = filepath if filepath is None else DEFAULT_CONFIG_FILE_LOCATION
payload = parse_alice_config(filepath=filepath)
instance = cls(**payload)
return instance
class BobConfiguration(NodeConfiguration):
from nucypher.characters.lawful import Bob
_Character = Bob

View File

@ -7,12 +7,16 @@ from tempfile import TemporaryDirectory
from constant_sorrow import constants
from itertools import islice
from nucypher.characters.base import Character
from nucypher.config.constants import DEFAULT_CONFIG_ROOT, DEFAULT_CONFIG_FILE_LOCATION, TEMPLATE_CONFIG_FILE_LOCATION
from nucypher.network.middleware import RestMiddleware
class NodeConfiguration:
_Character = NotImplemented
_parser = NotImplemented
DEFAULT_OPERATING_MODE = 'decentralized'
__TEMP_CONFIGURATION_DIR_PREFIX = "nucypher-tmp-cli-"
__REGISTRY_NAME = 'contract_registry.json'
@ -106,6 +110,12 @@ class NodeConfiguration:
if load_metadata:
self.load_known_nodes(known_metadata_dir=known_metadata_dir)
@classmethod
def from_configuration_file(cls, filepath=None) -> 'NodeConfiguration':
filepath = filepath if filepath is None else DEFAULT_CONFIG_FILE_LOCATION
payload = cls._parser(filepath=filepath)
return cls(**payload)
@property
def payload(self):
"""Exported configuration values for initializing Ursula"""
@ -232,10 +242,11 @@ class NodeConfiguration:
for line in islice(template_file, 12, None): # chop the warning header
new_file.writelines(line.lstrip(';')) # TODO Copy Default Sections, Perhaps interactively
def cleanup(self):
def cleanup(self) -> None:
if self.temp:
self.__temp_dir.cleanup()
@classmethod
def from_configuration_file(cls, filepath: str):
raise NotImplementedError
def produce(self, **overrides) -> Character:
"""Initialize a new character instance and return it"""
merged_parameters = {**self.payload, **overrides}
return self._Character(**merged_parameters)

View File

@ -6,7 +6,6 @@ from eth_utils import keccak
from umbral import pre
from umbral.keys import UmbralPublicKey, UmbralPrivateKey, UmbralKeyingMaterial
from nucypher.blockchain.eth.chains import Blockchain
from nucypher.keystore import keypairs
from nucypher.keystore.keypairs import SigningKeypair, EncryptingKeypair, HostingKeypair

View File

@ -9,8 +9,10 @@ class RestMiddleware:
def consider_arrangement(self, arrangement, certificate_filepath):
node = arrangement.ursula
response = requests.post("https://{}/consider_arrangement".format(node.rest_interface), bytes(arrangement),
response = requests.post("https://{}/consider_arrangement".format(node.rest_interface),
bytes(arrangement),
verify=certificate_filepath)
if not response.status_code == 200:
raise RuntimeError("Bad response: {}".format(response.content))
return response
@ -47,13 +49,13 @@ class RestMiddleware:
endpoint = 'https://{}/kFrag/{}/reencrypt'.format(work_order.ursula.rest_interface, id_as_hex)
return requests.post(endpoint, payload, verify=work_order.ursula.certificate_filepath)
def node_information(self, host, port, certificate_path=None):
def node_information(self, host, port, certificate_filepath=None):
endpoint = "https://{}:{}/public_information".format(host, port)
return requests.get(endpoint, verify=False)
def get_nodes_via_rest(self,
url,
certificate_path,
certificate_filepath,
announce_nodes=None,
nodes_i_need=None):
if nodes_i_need:
@ -65,9 +67,9 @@ class RestMiddleware:
if announce_nodes:
payload = bytes().join(bytes(n) for n in announce_nodes)
response = requests.post("https://{}/node_metadata".format(url),
verify=certificate_path,
verify=certificate_filepath,
data=payload)
else:
response = requests.get("https://{}/node_metadata".format(url),
verify=certificate_path)
verify=certificate_filepath)
return response

View File

@ -21,7 +21,7 @@ class MockRestMiddleware(RestMiddleware):
port = int(url.split(":")[1])
return self._get_mock_client_by_port(port)
def _get_mock_client_by_port(self, port): # TODO
def _get_mock_client_by_port(self, port):
try:
ursula = TEST_KNOWN_URSULAS_CACHE[port]
rest_app = ursula.rest_app
@ -31,7 +31,8 @@ class MockRestMiddleware(RestMiddleware):
"Can't find an Ursula with port {} - did you spin up the right test ursulas?".format(port))
return mock_client
def consider_arrangement(self, arrangement=None):
def consider_arrangement(self, arrangement, certificate_filepath):
# assert os.path.isfile(certificate_filepath)
mock_client = self._get_mock_client_by_ursula(arrangement.ursula)
response = mock_client.post("http://localhost/consider_arrangement", bytes(arrangement))
assert response.status_code == 200
@ -53,12 +54,12 @@ class MockRestMiddleware(RestMiddleware):
mock_client = self._get_mock_client_by_ursula(node)
return mock_client.get("http://localhost/treasure_map/{}".format(map_id))
def node_information(self, host, port):
def node_information(self, host, port, certificate_filepath=None):
mock_client = self._get_mock_client_by_port(port)
response = mock_client.get("http://localhost/public_information")
return response
def get_nodes_via_rest(self, url, certificate_path, announce_nodes=None, nodes_i_need=None):
def get_nodes_via_rest(self, url, certificate_filepath, announce_nodes=None, nodes_i_need=None):
mock_client = self._get_mock_client_by_url(url)
@ -70,17 +71,19 @@ class MockRestMiddleware(RestMiddleware):
if announce_nodes:
response = mock_client.post("https://{}/node_metadata".format(url),
verify=False,
data=bytes().join(bytes(n) for n in announce_nodes)) # TODO: TLS-only.
verify=certificate_filepath,
data=bytes().join(bytes(n) for n in announce_nodes))
else:
response = mock_client.get("https://{}/node_metadata".format(url),
verify=False) # TODO: TLS-only.
verify=certificate_filepath)
return response
def put_treasure_map_on_node(self, node, map_id, map_payload):
mock_client = self._get_mock_client_by_ursula(node)
certificate_filepath = node.certificate_filepath
response = mock_client.post("http://localhost/treasure_map/{}".format(map_id),
data=map_payload, verify=False)
data=map_payload, verify=certificate_filepath)
return response
@ -96,4 +99,4 @@ class EvilMiddleWare(MockRestMiddleware):
response = mock_client.post("http://localhost/node_metadata".format(mock_client),
verify=False,
data=bytes(shitty_interface_id))
return response
return response