Exemple #1
0
def add_devices_to_user(user, dev_inventories):
    try:
        user.devices
    except AttributeError:
        user.devices = []

    useradmm = ApiClient(useradm.URL_MGMT)
    devauthd = ApiClient(deviceauth.URL_DEVICES)
    devauthm = ApiClient(deviceauth.URL_MGMT)
    invd = ApiClient(inventory.URL_DEV)

    utoken = useradmm.call("POST", useradm.URL_LOGIN, auth=(user.name, user.pwd)).text
    assert utoken != ""
    user.api_token = utoken

    for inv in dev_inventories:
        device = make_accepted_device(devauthd, devauthm, utoken)
        user.devices.append(device)

        attrs = dict_to_inventoryattrs(inv)
        rsp = invd.with_auth(device.token).call(
            "PATCH", inventory.URL_DEVICE_ATTRIBUTES, body=attrs
        )
        assert rsp.status_code == 200
        device.inventory = inv

    return user
def initialize_os_setup(env):
    """ Seed the OS setup with all operational data - users and devices.
        Return {"os_devs": [...], "os_users": [...]}
    """
    uadmm = ApiClient(useradm.URL_MGMT, host=env.get_mender_gateway())
    dauthd = ApiClient(deviceauth.URL_DEVICES, host=env.get_mender_gateway())
    dauthm = ApiClient(deviceauth.URL_MGMT, host=env.get_mender_gateway())

    users = [
        create_user("*****@*****.**", "correcthorse", containers_namespace=env.name),
        create_user("*****@*****.**", "correcthorse", containers_namespace=env.name),
    ]

    r = uadmm.call("POST", useradm.URL_LOGIN, auth=(users[0].name, users[0].pwd))

    assert r.status_code == 200
    utoken = r.text

    # create and accept some devs; save tokens
    devs = []
    for _ in range(10):
        devs.append(make_accepted_device(dauthd, dauthm, utoken))

    # get tokens for all
    for d in devs:
        body, sighdr = deviceauth.auth_req(
            d.id_data, d.authsets[0].pubkey, d.authsets[0].privkey
        )

        r = dauthd.call("POST", deviceauth.URL_AUTH_REQS, body, headers=sighdr)

        assert r.status_code == 200
        d.token = r.text

    return {"os_devs": devs, "os_users": users}
    def setup_upload_artifact_selection(self, plan, artifacts=()):
        tenant, username, password = self.get_tenant_username_and_password(
            plan=plan)
        auth_token = self.get_auth_token(username, password)

        api_client = ApiClient(deployments.URL_MGMT)
        api_client.headers = {}  # avoid default Content-Type: application/json
        api_client.with_auth(auth_token)

        # create and upload the mender artifact
        for artifact_kw in artifacts:
            artifact_kw.setdefault("artifact_name", "test")
            artifact_kw.setdefault("device_types", ["arm1"])
            with get_mender_artifact(**artifact_kw) as artifact:
                r = api_client.with_auth(auth_token).call(
                    "POST",
                    deployments.URL_DEPLOYMENTS_ARTIFACTS,
                    files=(
                        ("description", (None, "description")),
                        ("size", (None, str(os.path.getsize(artifact)))),
                        (
                            "artifact",
                            (
                                artifact,
                                open(artifact, "rb"),
                                "application/octet-stream",
                            ),
                        ),
                    ),
                )
            assert r.status_code == 201

        # create a new accepted device
        devauthd = ApiClient(deviceauth.URL_DEVICES)
        devauthm = ApiClient(deviceauth.URL_MGMT)
        dev = make_accepted_device(
            devauthd,
            devauthm,
            auth_token,
            tenant.tenant_token if tenant is not None else "",
        )
        assert dev is not None

        # create a deployment
        resp = api_client.with_auth(auth_token).call(
            "POST",
            deployments.URL_DEPLOYMENTS,
            body={
                "name": "deployment-1",
                "artifact_name": "test",
                "devices": [dev.id],
            },
        )
        assert resp.status_code == 201

        return dev
Exemple #4
0
    def _prepare_device(
        self,
        azure_user: User,
        httpserver: HTTPServer,
        httpserver_ssl_context: ssl.SSLContext,
    ) -> Device:
        """Create accepted device in Mender and make sure it has been successfully added in Azure IoT Hub."""
        if self.azure_iot_hub_mock:
            httpserver.expect_oneshot_request(
                re.compile("^/devices"),
                method="PUT",
                query_string="api-version=2021-04-12",
            ).respond_with_json(self._prepare_iot_hub_upsert_device_response())
            httpserver.expect_oneshot_request(
                re.compile("^/devices"),
                method="GET",
                query_string="api-version=2021-04-12",
            ).respond_with_data(status=200)
            httpserver.expect_oneshot_request(
                re.compile("^/devices"),
                method="PUT",
                query_string="api-version=2021-04-12",
            ).respond_with_data(status=200)
            httpserver.expect_oneshot_request(
                re.compile("^/twins"),
                method="PATCH",
                query_string="api-version=2021-04-12",
            ).respond_with_data(status=200)

        tenant_token = getattr(getattr(azure_user, "tenant", {}),
                               "tenant_token", "")
        dev = make_accepted_device(
            self.api_devauth_devices,
            self.api_devauth_mgmt,
            azure_user.token,
            tenant_token=tenant_token,
            test_type="azure",
        )
        self.devices.append(dev.id)
        for _ in retrier(attempts=5, sleeptime=1):
            if self.azure_iot_hub_mock:
                httpserver.expect_oneshot_request(
                    re.compile("^/twins"),
                    method="GET",
                    query_string="api-version=2021-04-12",
                ).respond_with_json(
                    self._prepare_iot_hub_upsert_device_response())
            rsp = self.api_azure.with_auth(azure_user.token).call(
                "GET", iot.URL_DEVICE(dev.id))
            if rsp.status_code == 200:
                break
        return dev
Exemple #5
0
def devices(user):
    uc = ApiClient(useradm.URL_MGMT)
    devauthm = ApiClient(deviceauth.URL_MGMT)
    devauthd = ApiClient(deviceauth.URL_DEVICES)

    r = uc.call("POST", useradm.URL_LOGIN, auth=(user.name, user.pwd))
    assert r.status_code == 200
    utoken = r.text

    devices = []

    for _ in range(5):
        dev = make_accepted_device(devauthd, devauthm, utoken)
        devices.append(dev)

    yield devices
Exemple #6
0
def tenants_users_devices(tenants_users):
    uc = ApiClient(useradm.URL_MGMT)
    devauthm = ApiClient(deviceauth.URL_MGMT)
    devauthd = ApiClient(deviceauth.URL_DEVICES)

    for t in tenants_users:
        user = t.users[0]
        r = uc.call("POST", useradm.URL_LOGIN, auth=(user.name, user.pwd))
        assert r.status_code == 200
        utoken = r.text

        for _ in range(5):
            dev = make_accepted_device(devauthd, devauthm, utoken,
                                       t.tenant_token)
            t.devices.append(dev)

    yield tenants_users
Exemple #7
0
def initialize_os_setup():
    """ Seed the OS setup with all operational data - users and devices.
        Return {"os_devs": [...], "os_users": [...]}
    """
    uadmm = ApiClient('https://{}/api/management/v1/useradm'.format(
        get_mender_gateway()))
    dauthd = ApiClient('https://{}/api/devices/v1/authentication'.format(
        get_mender_gateway()))
    dauthm = ApiClient('https://{}/api/management/v2/devauth'.format(
        get_mender_gateway()))

    users = [
        create_user("*****@*****.**",
                    "correcthorse",
                    docker_prefix=docker_compose_instance),
        create_user("*****@*****.**",
                    "correcthorse",
                    docker_prefix=docker_compose_instance)
    ]

    r = uadmm.call('POST',
                   useradm.URL_LOGIN,
                   auth=(users[0].name, users[0].pwd))

    assert r.status_code == 200
    utoken = r.text

    # create and accept some devs; save tokens
    devs = []
    for i in range(10):
        devs.append(make_accepted_device(dauthd, dauthm, utoken))

    # get tokens for all
    for d in devs:
        body, sighdr = deviceauth_v1.auth_req(d.id_data, d.authsets[0].pubkey,
                                              d.authsets[0].privkey)

        r = dauthd.call('POST',
                        deviceauth_v1.URL_AUTH_REQS,
                        body,
                        headers=sighdr)

        assert r.status_code == 200
        d.token = r.text

    return {"os_devs": devs, "os_users": users}
Exemple #8
0
def setup_tenant_devices(tenant, device_groups):
    """
    setup_user_devices authenticates the user and creates devices
    attached to (static) groups given by the proportion map from
    the groups parameter.
    :param users:     Users to setup devices for (list).
    :param n_devices: Number of accepted devices created for each
                      user (int).
    :param groups:    Map of group names to device proportions, the
                      sum of proportion must be less than or equal
                      to 1 (dict[str] = float)
    :return: Dict mapping group_name -> list(devices)
    """
    devauth_DEV = ApiClient(deviceauth.URL_DEVICES)
    devauth_MGMT = ApiClient(deviceauth.URL_MGMT)
    invtry_MGMT = ApiClient(inventory.URL_MGMT)
    user = tenant.users[0]
    grouped_devices = {}
    group = None

    login_tenant_users(tenant)

    tenant.devices = []
    for group, dev_cnt in device_groups.items():
        grouped_devices[group] = []
        for i in range(dev_cnt):
            device = make_accepted_device(devauth_DEV, devauth_MGMT,
                                          user.token, tenant.tenant_token)
            if group is not None:
                rsp = invtry_MGMT.with_auth(user.token).call(
                    "PUT",
                    inventory.URL_DEVICE_GROUP.format(id=device.id),
                    body={"group": group},
                )
                assert rsp.status_code == 204

            device.group = group
            grouped_devices[group].append(device)
            tenant.devices.append(device)

    # sleep a few seconds waiting for the data propagation to the reporting service
    # and the Elasticsearch indexing to complete
    time.sleep(reporting.REPORTING_DATA_PROPAGATION_SLEEP_TIME_SECS)

    return grouped_devices
Exemple #9
0
def setup_tenant_devices(tenant, device_groups):
    """
    setup_user_devices authenticates the user and creates devices
    attached to (static) groups given by the proportion map from
    the groups parameter.
    :param users:     Users to setup devices for (list).
    :param n_devices: Number of accepted devices created for each
                      user (int).
    :param groups:    Map of group names to device proportions, the
                      sum of proportion must be less than or equal
                      to 1 (dict[str] = float)
    :return: Dict mapping group_name -> list(devices)
    """
    devauth_DEV = ApiClient(deviceauth.URL_DEVICES)
    devauth_MGMT = ApiClient(deviceauth_v2.URL_MGMT)
    invtry_MGMT = ApiClient(inventory.URL_MGMT)
    user = tenant.users[0]
    grouped_devices = {}
    group_cumulative = []
    group = None

    login_tenant_users(tenant)

    tenant.devices = []
    for group, dev_cnt in device_groups.items():
        grouped_devices[group] = []
        for i in range(dev_cnt):
            device = make_accepted_device(devauth_DEV, devauth_MGMT,
                                          user.token, tenant.tenant_token)
            if group is not None:
                rsp = invtry_MGMT.with_auth(user.token).call(
                    "PUT",
                    inventory.URL_DEVICE_GROUP.format(id=device.id),
                    body={"group": group},
                )
                assert rsp.status_code == 204

            device.group = group
            grouped_devices[group].append(device)
            tenant.devices.append(device)

    return grouped_devices