def test_create_api_with_env(self):
        api = ubirch.API(env='test')

        self.assertEqual(TEST_ENV_KEY_SERVICE.format("test"),
                         api.get_url(KEY_SERVICE))
        self.assertEqual(TEST_ENV_NIOMON_SERVICE.format("test"),
                         api.get_url(NIOMON_SERVICE))
        self.assertEqual(TEST_ENV_VERIFIER_SERVICE.format("test"),
                         api.get_url(VERIFICATION_SERVICE))
    def test_create_api_defaults(self):
        api = ubirch.API()

        self.assertEqual(TEST_LOCAL_KEY_SERVICE, api.get_url(KEY_SERVICE))
        self.assertEqual(TEST_LOCAL_AVATAR_SERVICE,
                         api.get_url(AVATAR_SERVICE))
        self.assertEqual(TEST_LOCAL_CHAIN_SERVICE, api.get_url(CHAIN_SERVICE))
        self.assertEqual(TEST_LOCAL_NOTARY_SERVICE,
                         api.get_url(NOTARY_SERVICE))
        self.assertDictEqual({}, api._auth)
    def test_create_api_with_auth(self):
        AUTH_TOKEN = "ABC:TOKEN:DEF"
        api = ubirch.API(auth=AUTH_TOKEN)

        self.assertEqual(TEST_LOCAL_KEY_SERVICE, api.get_url(KEY_SERVICE))
        self.assertEqual(TEST_LOCAL_AVATAR_SERVICE,
                         api.get_url(AVATAR_SERVICE))
        self.assertEqual(TEST_LOCAL_CHAIN_SERVICE, api.get_url(CHAIN_SERVICE))
        self.assertEqual(TEST_LOCAL_NOTARY_SERVICE,
                         api.get_url(NOTARY_SERVICE))
        self.assertDictEqual({'Authorization': AUTH_TOKEN}, api._auth)
    def test_create_api_with_env(self):
        api = ubirch.API(env='test')

        self.assertEqual(TEST_ENV_KEY_SERVICE.format("test"),
                         api.get_url(KEY_SERVICE))
        self.assertEqual(TEST_ENV_AVATAR_SERVICE.format("test"),
                         api.get_url(AVATAR_SERVICE))
        self.assertEqual(TEST_ENV_CHAIN_SERVICE.format("test"),
                         api.get_url(CHAIN_SERVICE))
        self.assertEqual(TEST_ENV_NOTARY_SERVICE.format("test"),
                         api.get_url(NOTARY_SERVICE))
    def test_create_api_with_debug(self):
        import http.client as http_client

        # prepare the logging level
        logger = logging.getLogger(ubirch.ubirch_api.__name__)
        orig_level = logger.level
        logger.setLevel(logging.DEBUG)

        ubirch.API(debug=True)
        self.assertEqual(http_client.HTTPConnection.debuglevel, 1)
        urllib_logger = logging.getLogger("requests.packages.urllib3")
        self.assertEqual(urllib_logger.level, logging.DEBUG)
        self.assertEqual(urllib_logger.propagate, True)

        # reset logging level
        logger.setLevel(orig_level)
Example #6
0
        # check if the device already has keys or generate a new pair
        if not keystore.exists_signing_key(uuid):
            keystore.create_ed25519_keypair(uuid)

    def _sign(self, uuid: UUID, message: bytes) -> bytes:
        return self.__ks.find_signing_key(uuid).sign(message)


# create a keystore
keystore = ubirch.KeyStore("demo-device.jks", "keystore")

# create an instance of the protocol
protocol = Proto(keystore, uuid)

# create an instance of the ubirch API and set the password
api = ubirch.API(env=env)
api.set_authentication(uuid, auth)

# register the public key at the UBIRCH key service
if not api.is_identity_registered(uuid):
    certificate = keystore.get_certificate(uuid)
    key_registration = protocol.message_signed(uuid, UBIRCH_PROTOCOL_TYPE_REG,
                                               certificate)
    r = api.register_identity(key_registration)
    print("key registration status code:", r.status_code)

# hash the test message
test_message_hash = hashlib.sha256(test_message.encode()).digest()
test_message_ascii = binascii.b2a_base64(test_message_hash,
                                         newline=False).decode()
print("message hash:", test_message_ascii)
logger.info("AUTH : {}".format(auth))
logger.info("ENV  : {}".format(env))
logger.info("DEBUG: {}".format(debug))

# create a new device uuid and a keystore for the device
keystore = ubirch.KeyStore(uuid.hex + ".jks", "test-keystore")

# check if the device already has keys or generate a new pair
if not keystore.exists_signing_key(uuid):
    keystore.create_ed25519_keypair(uuid)

# create new protocol
proto = Proto(keystore, uuid)

# use the ubirch API to create a new device and send data using the ubirch-protocol
api = ubirch.API(auth=auth, debug=debug, env=env)

# check if the device exists and delete if that is the case
if api.device_exists(uuid):
    logger.warning("device {} exists, deleting".format(str(uuid)))
    api.device_delete(uuid)
    time.sleep(2)

# create a new device on the backend
r = api.device_create({
    "deviceId":
    str(uuid),
    "deviceTypeKey":
    "genericSensor",
    "deviceName":
    str(uuid),
Example #8
0
        print("IMSI: " + imsi)
    except Exception as e:
        print("\tERROR setting up modem")
        error_handler.log(e, COLOR_MODEM_FAIL)
        while True:
            machine.idle()

    set_led(LED_TURQUOISE)

    # load configuration, blocks in case of failure
    print("++ loading config")
    try:
        cfg = load_config(sd_card_mounted=SD_CARD_MOUNTED)
        connection = get_connection(
            lte, cfg)  # initialize connection object depending on config
        api = ubirch.API(cfg)  # set up API for backend communication
    except Exception as e:
        print("\tERROR loading configuration")
        error_handler.log(e, COLOR_CONFIG_FAIL)
        while True:
            machine.idle()

    # get PIN from flash, or bootstrap from backend and then save PIN to flash
    pin_file = imsi + ".bin"
    pin = get_pin_from_flash(pin_file, imsi)
    if pin is None:
        try:
            connection.connect()
        except Exception as e:
            error_handler.log(e, COLOR_INET_FAIL, reset=True)
if UBIRCH_CLIENT and UBIRCH_CLIENT.strip():
    # create a sub-class of the ubirch API to use
    class ClientAPI(ubirch.API):
        def __init__(self,
                     client: str,
                     auth: str = None,
                     env: str = None,
                     debug: bool = False) -> None:
            super().__init__(auth, env, debug)
            self._services[AVATAR_SERVICE] = "https://ubirch.api.{}.{}.ubirch.com/api/avatarService/v1" \
                .format(client, env)

    # instantiate the sub class to include ubirch-client
    api = ClientAPI(client=UBIRCH_CLIENT, env=UBIRCH_ENV, auth=UBIRCH_AUTH)
else:
    api = ubirch.API(env=UBIRCH_ENV, auth=UBIRCH_AUTH)

proto = Proto(keystore)

# do an initial deepCheck test
services = [KEY_SERVICE, AVATAR_SERVICE]  # , NOTARY_SERVICE, CHAIN_SERVICE]
for service in services:
    try:
        logger.info(
            "DEEPCHECK: {}".format(api.get_url(service) + "/deepCheck"))
        r = requests.get(api.get_url(service) + "/deepCheck", timeout=1.0)
        try:
            response = r.json()
            if not response['status']:
                ERRORS += 1
                nagios(UBIRCH_CLIENT, UBIRCH_ENV, service + "-deepCheck",
 def test_is_identity_registered(self, mock):
     mock.register_uri(requests_mock.ANY,
                       requests_mock.ANY,
                       text='{"result":"OK"}')
     self.assertTrue(ubirch.API().is_identity_registered(uuid.uuid4()))
logger.info("UUID (user2) : {}".format(user2_uuid))
logger.info("UUID (user2.deviceB) : {}".format(user2_deviceB))
logger.info("ENV  : {}".format(env))

keystore = ubirch.KeyStore("test-web-of-trust.jks", "test-keystore")

if not keystore.exists_signing_key(user1_uuid):
    keystore.create_ed25519_keypair(user1_uuid)
if not keystore.exists_signing_key(user1_deviceA):
    keystore.create_ed25519_keypair(user1_deviceA)
if not keystore.exists_signing_key(user2_uuid):
    keystore.create_ed25519_keypair(user2_uuid)
if not keystore.exists_signing_key(user2_deviceB):
    keystore.create_ed25519_keypair(user2_deviceB)

api = ubirch.API(auth=auth, env=env)


def upload_public_key(uuid: UUID, info_text: str):
    proto = Proto(keystore, uuid)
    if not api.is_identity_registered(uuid):
        registration_message = proto.message_signed(uuid, UBIRCH_PROTOCOL_TYPE_REG, keystore.get_certificate(uuid))
        r = api.register_identity(registration_message)
        if r.status_code == requests.codes.ok:
            logger.info(
                "public key upload successful: '{}' ({}): {}: {}".format(info_text, uuid, r.status_code, r.content))
        else:
            logger.info("register of '{}' ({}) failed: {}: {}".format(info_text, uuid, r.status_code, r.content))
        logger.debug(r.content)
    else:
        logger.info("already registered '{}' ({})".format(info_text, uuid))
 def test_is_identity_registered_fails(self, mock):
     mock.register_uri(requests_mock.ANY, requests_mock.ANY, text='')
     try:
         self.assertFalse(ubirch.API().is_identity_registered(uuid.uuid4()))
     except JSONDecodeError as e:
         pass
 def test_anchor(self, mock):
     mock.register_uri(requests_mock.ANY,
                       requests_mock.ANY,
                       text='{"result":"OK"}')
     self.assertTrue(ubirch.API().anchor(b'This is a Test'))
 def test_send_msgpack(self, mock):
     mock.register_uri(requests_mock.ANY,
                       requests_mock.ANY,
                       text='{"result":"OK"}')
     self.assertTrue(ubirch.API().send(msgpack.packb([1, 2, 3])))
 def test_send_json(self, mock):
     mock.register_uri(requests_mock.ANY,
                       requests_mock.ANY,
                       text='{"result":"OK"}')
     self.assertTrue(ubirch.API().send(str.encode(json.dumps({}))))
 def test_device_create(self, mock):
     mock.register_uri(requests_mock.ANY,
                       requests_mock.ANY,
                       text='{"result":"OK"}')
     self.assertTrue(ubirch.API().device_create({}))
 def test_device_exists(self, mock):
     mock.register_uri(requests_mock.ANY,
                       requests_mock.ANY,
                       text='{"result":"OK"}')
     self.assertTrue(ubirch.API().device_exists(uuid.uuid4()))
Example #18
0
import requests
import ubirch
from requests import Response
from ubirch.ubirch_protocol import UBIRCH_PROTOCOL_TYPE_REG, UBIRCH_PROTOCOL_TYPE_BIN

from config import device_uuid, ub_env, ub_auth, device_type, device_name, device_hwid, validator_address, \
    show_username
from demo_logging import logger
from ubirch_proto import Proto
from util import ok, nok, step, abort, wait, shorten, make_sensitive_message

# region setting up the keystore, api and the protocol
keystore = ubirch.KeyStore(
    device_uuid.hex + ".jks",
    "demo-keystore")  # use a better password in production
api = ubirch.API(ub_auth, ub_env, logger.level == logging.DEBUG)

protocol = Proto(keystore, device_uuid)
# endregion

# region check the connection to ubirch api
logger.info(step + "Checking authorization")
# TODO: replace this with client api call when it's implemented
user_req = requests.get(
    "https://auth.{}.ubirch.com/api/authService/v1/userInfo".format(ub_env),
    headers=api._auth)
if user_req.ok:
    username = user_req.json()["displayName"]
    if show_username:
        logger.info(
            ok +
Example #19
0
    filter(None,
           config.get('device', 'groups', fallback="").split(",")))

logger.info("UUID : {}".format(uuid))
logger.info("AUTH : {}".format(auth))
logger.info("ENV  : {}".format(env))
logger.info("DEBUG: {}".format(debug))

# create a new device uuid and a keystore for the device
keystore = ubirch.KeyStore("demo-device.jks", "keystore")

# create new protocol
proto = Proto(keystore, uuid)

# use the ubirch API to create a new device and send data using the ubirch-protocol
api = ubirch.API(env=env, debug=debug)
api.set_authentication(uuid, auth)
# register the devices identity
if not api.is_identity_registered(uuid):
    registration_message = proto.message_signed(uuid, UBIRCH_PROTOCOL_TYPE_REG,
                                                keystore.get_certificate(uuid))
    r = api.register_identity(registration_message)
    if r.status_code == requests.codes.ok:
        logger.info("registered new identity: {}".format(uuid))
    else:
        logger.error("device registration failed: {}".format(uuid))
    logger.debug(r.content)

for i in range(3):
    # create a message like being sent to the customer backend
    # include an ID and timestamp in the data message to ensure a unique hash