예제 #1
0
    def _test_args_object(self, tenant_users, events):
        alogs = ApiClient(auditlogs.URL_MGMT)

        expected = events[0]

        # id filter
        resp = alogs.with_auth(tenant_users.users[0].token).call(
            "GET",
            auditlogs.URL_LOGS + "?object_id=" + expected["object"]["id"])

        resp = resp.json()
        assert len(resp) == 1

        for i in range(len(resp)):
            check_log(resp[0], expected)

        # type filter
        for obj_type in ["deployment"]:
            expected = [e for e in events if e["object"]["type"] == obj_type]
            resp = alogs.with_auth(tenant_users.users[0].token).call(
                "GET", auditlogs.URL_LOGS + "?object_type=" + obj_type)

            resp = resp.json()
            assert len(resp) == len(expected)

            for i in range(len(resp)):
                check_log(resp[i], expected[i])
예제 #2
0
def create_tenant(name, docker_prefix=None):
    """ Create a tenant via cli, record its id and token for further use.  """
    cli = CliTenantadm(docker_prefix)
    api = ApiClient(tenantadm.URL_INTERNAL)

    id = cli.create_tenant(name)

    page = 0
    per_page = 20
    qs_params = {}
    found = None
    while True:
        page = page + 1
        qs_params['page'] = page
        qs_params['per_page'] = per_page
        r = api.call('GET', tenantadm.URL_INTERNAL_TENANTS, qs_params=qs_params)
        assert r.status_code == 200
        api_tenants = r.json()

        found = [at for at in api_tenants if at['id'] == id]
        if len(found) > 0:
            break

        if len(api_tenants) == 0:
            break

    assert len(found) == 1
    token = found[0]['tenant_token']

    return Tenant(name, id, token)
    def test_authenticated_user_is_rejected(self, tenants):
        tc = ApiClient(tenantadm.URL_INTERNAL,
                       host=tenantadm.HOST,
                       schema="http://")
        uc = ApiClient(useradm.URL_MGMT)
        dc = ApiClient(deviceauth.URL_MGMT)

        u = tenants[0].users[0]

        # log in
        r = uc.call("POST", useradm.URL_LOGIN, auth=(u.name, u.pwd))
        assert r.status_code == 200

        token = r.text

        # check can access an api
        r = dc.with_auth(token).call("GET", deviceauth.URL_MGMT_DEVICES)
        assert r.status_code == 200

        # suspend tenant
        r = tc.call(
            "PUT",
            tenantadm.URL_INTERNAL_SUSPEND,
            tenantadm.req_status("suspended"),
            path_params={"tid": tenants[0].id},
        )
        assert r.status_code == 200

        time.sleep(10)

        # check token is rejected
        r = dc.with_auth(token).call("GET", deviceauth.URL_MGMT_DEVICES)
        assert r.status_code == 401
예제 #4
0
    def _test_args_paging(self, tenant_users, events):
        alogs = ApiClient(auditlogs.URL_MGMT)

        cases = [
            # default
            {"expected": events[:10]},
            # default, but specified
            {"page": "1", "per_page": "20", "expected": events},
            # past bounds
            {"page": "10", "expected": []},
            # >1 page, custom number
            {"page": "2", "per_page": "3", "expected": events[3:6]},
        ]

        for case in cases:
            arg = "?"
            if "page" in case:
                arg += "page=" + case["page"]
            if "per_page" in case:
                arg += "&per_page=" + case["per_page"]

            resp = alogs.with_auth(tenant_users.users[0].token).call(
                "GET", auditlogs.URL_LOGS + arg
            )

            assert resp.status_code == 200
            resp = resp.json()

            assert len(resp) == len(case["expected"])

            for i in range(len(resp)):
                check_log(resp[i], case["expected"][i])
예제 #5
0
    def test_accepted_dev_cant_authenticate(self, tenants_users_devices):
        dacd = ApiClient(deviceauth.URL_DEVICES)
        devauthm = ApiClient(deviceauth_v2.URL_MGMT)
        uc = ApiClient(useradm.URL_MGMT)
        tc = ApiClient(tenantadm.URL_INTERNAL)

        # accept a dev
        device = tenants_users_devices[0].devices[0]
        user = tenants_users_devices[0].users[0]

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

        aset = device.authsets[0]
        change_authset_status(devauthm, aset.did, aset.id, 'accepted', utoken)

        # suspend
        r = tc.call('PUT',
                    tenantadm.URL_INTERNAL_SUSPEND,
                    tenantadm.req_status('suspended'),
                    path_params={'tid': tenants_users_devices[0].id})
        assert r.status_code == 200

        time.sleep(10)

        # try requesting auth
        body, sighdr = deviceauth.auth_req(
            aset.id_data, aset.pubkey, aset.privkey,
            tenants_users_devices[0].tenant_token)

        r = dacd.call('POST', deviceauth.URL_AUTH_REQS, body, headers=sighdr)

        assert r.status_code == 401
        assert r.json()['error'] == 'Account suspended'
def try_update(device,
               expected_status_code=200,
               artifact_name="bugs-bunny"):
    """
    Try to make an update with a device
    :param devices:              list of devices
    :param expected_status_code: expected status code
    :param artifact_name:        artifact name used in the request
    """
    api_dev_deploy = ApiClient(deployments.URL_DEVICES)
    # Try to retrieve next update and assert expected status code
    resp = api_dev_deploy.with_auth(device.token).call(
        'GET',
        deployments.URL_NEXT,
        qs_params={"artifact_name": artifact_name,
                   "device_type"  : "qemux86-64"}
    )
    assert resp.status_code == expected_status_code
    if resp.status_code == 200:
        # Update device status upon successful request
        api_dev_deploy.with_auth(device.token).call(
            "PUT",
            deployments.URL_STATUS.format(id=resp.json()["id"]),
            body={"status": "success"}
        )
예제 #7
0
    def check_access_file_transfer(self, auth, devid, forbid=False):
        devconn = ApiClient(
            host=get_container_manager().get_mender_gateway(),
            base_url=deviceconnect.URL_MGMT,
        )
        res = devconn.call(
            "GET",
            deviceconnect.URL_MGMT_FDOWNLOAD,
            headers=auth.get_auth_token(),
            path_params={"id": devid},
            qs_params={"path": "/etc/mender/mender.conf"},
        )

        if forbid:
            assert res.status_code == 403
        else:
            assert res.ok

        res = devconn.call(
            "PUT",
            deviceconnect.URL_MGMT_FUPLOAD,
            headers=auth.get_auth_token(),
            path_params={"id": devid},
            qs_params={"path": "/etc/mender/mender.conf"},
        )

        if forbid:
            assert res.status_code == 403
        else:
            assert res.status_code != 403
def create_tenant_test_setup(user_name, tenant_name, nr_deployments=3, nr_devices=100):
    """
    Creates a tenant, and a user belonging to the tenant belonging to the user
    with 'nr_deployments', and 'nr_devices'
    """
    api_mgmt_deploy = ApiClient(deployments.URL_MGMT)
    tenant = create_tenant(tenant_name)
    user = create_tenant_user(user_name, tenant)
    r = ApiClient(useradm.URL_MGMT).call(
        'POST', useradm.URL_LOGIN, auth=(user.name, user.pwd))
    assert r.status_code == 200
    user.utoken = r.text
    tenant.users = [user]
    upload_image("/tests/test-artifact.mender", user.utoken)
    # Create three deployments for the user
    for i in range(nr_deployments):
        request_body = {
            "name": str(i) + "st-dummy-deployment",
            "artifact_name": "deployments-phase-testing",
            "devices": ["uuid not needed" + str(i) for i in range(nr_devices)],
        }
        resp = api_mgmt_deploy.with_auth(user.utoken).call(
            'POST',
            '/deployments',
            body=request_body,
        )
        assert resp.status_code == 201
    # Verify that the 'nr_deployments' expected deployments have been created
    resp = api_mgmt_deploy.with_auth(user.utoken).call('GET', '/deployments')
    assert resp.status_code == 200
    assert len(resp.json()) == nr_deployments
    return tenant
    def test_authenticated_user_is_rejected(self, tenants):
        tc = ApiClient(tenantadm.URL_INTERNAL)
        uc = ApiClient(useradm.URL_MGMT)
        dc = ApiClient(deviceauth_v2.URL_MGMT)

        u = tenants[0].users[0]

        # log in
        r = uc.call('POST',
                     useradm.URL_LOGIN,
                     auth=(u.name, u.pwd))
        assert r.status_code == 200

        token = r.text

        # check can access an api
        r = dc.with_auth(token).call('GET', deviceauth_v2.URL_DEVICES)
        assert r.status_code == 200

        # suspend tenant
        r = tc.call('PUT',
                tenantadm.URL_INTERNAL_SUSPEND,
                tenantadm.req_status('suspended'),
                path_params={'tid': tenants[0].id})
        assert r.status_code == 200

        time.sleep(10)

        # check token is rejected
        r = dc.with_auth(token).call('GET', deviceauth_v2.URL_DEVICES)
        assert r.status_code == 401
예제 #10
0
 def test_reporting_search(self, user_reporting, test_case):
     reporting_client = ApiClient(reporting.URL_MGMT)
     rsp = reporting_client.with_auth(user_reporting.api_token).call(
         "POST", reporting.URL_MGMT_DEVICES_SEARCH, test_case["request"]
     )
     assert rsp.status_code == test_case["status_code"], (
         "Unexpected status code (%d) from /devices/search response: %s"
         % (rsp.status_code, rsp.text)
     )
     if rsp.status_code == 200 and "response" in test_case:
         body = rsp.json()
         if body is None:
             body = []
         test_case_response = test_case["response"](user_reporting)
         self.logger.info("expected: %r", test_case_response)
         self.logger.info("received: %r", body)
         assert len(body) == len(test_case_response), (
             "Unexpected number of results: %s != %s"
             % (
                 [dev["id"] for dev in test_case_response],
                 [dev["id"] for dev in body],
             )
         )
         if len(test_case_response) > 0:
             if "sort" not in test_case["request"]:
                 body = sorted(body, key=lambda dev: dev["id"])
                 test_case_response = sorted(
                     test_case_response, key=lambda dev: dev["id"]
                 )
             for i, dev in enumerate(test_case_response):
                 assert dev["id"] == body[i]["id"], "Unexpected device in response"
                 assert_device_attributes(dev, body[i])
예제 #11
0
def create_org(name, username, password, plan="os"):
    cli = CliTenantadm()
    user_id = None
    tenant_id = cli.create_org(name, username, password, plan=plan)
    tenant_token = json.loads(cli.get_tenant(tenant_id))["tenant_token"]
    api = ApiClient(useradm.URL_MGMT)
    # Try log in every second for 3 minutes.
    # - There usually is a slight delay (in order of ms) for propagating
    #   the created user to the db.
    for i in range(3 * 60):
        rsp = api.call("POST", useradm.URL_LOGIN, auth=(username, password))
        if rsp.status_code == 200:
            break
        time.sleep(1)

    if rsp.status_code != 200:
        raise ValueError(
            "User could not log in within three minutes after organization has been created."
        )

    user_token = rsp.text
    rsp = api.with_auth(user_token).call("GET", useradm.URL_USERS)
    users = json.loads(rsp.text)
    for user in users:
        if user["email"] == username:
            user_id = user["id"]
            break
    if user_id == None:
        raise ValueError("Error retrieving user id.")

    tenant = Tenant(name, tenant_id, tenant_token)
    user = User(user_id, username, password)
    tenant.users.append(user)
    return tenant
예제 #12
0
    def test_duplicate_email(self, clean_migrated_mongo):
        tc = ApiClient(tenantadm.URL_MGMT,
                       host=tenantadm.HOST,
                       schema="http://")

        uuidv4 = str(uuid.uuid4())
        tenant = "test.mender.io-" + uuidv4
        email = "some.user@{}.com".format(tenant)

        payload = {
            "request_id": "123456",
            "organization": tenant,
            "email": email,
            "password": "******",
            "g-recaptcha-response": "foobar",
            "token": "tok_visa",
        }
        rsp = tc.post(tenantadm.URL_MGMT_TENANTS, data=payload)
        assert rsp.status_code == 202

        uuidv4 = str(uuid.uuid4())
        tenant = "test.mender.io-" + uuidv4

        payload = {
            "request_id": "123457",
            "organization": tenant,
            "email": email,
            "password": "******",
            "g-recaptcha-response": "foobar",
            "token": "tok_visa",
        }
        rsp = tc.post(tenantadm.URL_MGMT_TENANTS, data=payload)
        assert rsp.status_code == 409

        self._cleanup_stripe(email)
예제 #13
0
    def test_duplicate_email(self, clean_migrated_mongo):
        tc = ApiClient(tenantadm.URL_MGMT)

        tenant = "tenant{}".format(randstr())
        email = "some.user@{}.com".format(tenant)

        payload = {
            "request_id": "123456",
            "organization": tenant,
            "email": email,
            "password": "******",
            "g-recaptcha-response": "foobar",
            "token": "tok_visa",
        }
        rsp = tc.post(tenantadm.URL_MGMT_TENANTS, data=payload)
        assert rsp.status_code == 202

        tenant = "tenant{}".format(randstr())

        payload = {
            "request_id": "123457",
            "organization": tenant,
            "email": email,
            "password": "******",
            "g-recaptcha-response": "foobar",
            "token": "tok_visa",
        }
        rsp = tc.post(tenantadm.URL_MGMT_TENANTS, data=payload)
        assert rsp.status_code == 409

        self._cleanup_stripe(email)
예제 #14
0
def try_update(device,
               default_artifact_name="bugs-bunny",
               default_device_type="qemux86-64"):
    """
    Try to make an update with a device
    :param devices:               list of devices
    :param expected_status_code:  expected status code
    :param default_artifact_name: default artifact name of the
                                  artifact used in the request

    NOTE: You can override the device type and artifact name 
          by creating a device_type/artifact_name member of the
          Device object.
    """
    api_dev_deploy = ApiClient(deployments.URL_DEVICES)
    # Try to retrieve next update and assert expected status code
    resp = api_dev_deploy.with_auth(device.token).call(
        'GET',
        deployments.URL_NEXT,
        qs_params={"artifact_name": getattr(
            device, "artifact_name", default_artifact_name),
            "device_type": getattr(
            device, "device_type", default_device_type)}
    )
    if resp.status_code == 200:
        # Update device status upon successful request
        api_dev_deploy.with_auth(device.token).call(
            "PUT",
            deployments.URL_STATUS.format(id=resp.json()["id"]),
            body={"status": "success"}
        )
    return resp.status_code
예제 #15
0
파일: common.py 프로젝트: kacf/integration
def make_device_with_inventory(attributes, utoken, tenant_token):
    devauthm = ApiClient(deviceauth.URL_MGMT)
    devauthd = ApiClient(deviceauth.URL_DEVICES)
    invm = ApiClient(inventory.URL_MGMT)

    d = make_accepted_device(devauthd, devauthm, utoken, tenant_token)
    """
    verify that the status of the device in inventory is "accepted"
    """
    accepted = False
    timeout = 10
    for i in range(timeout):
        r = invm.with_auth(utoken).call("GET",
                                        inventory.URL_DEVICE.format(id=d.id))
        if r.status_code == 200:
            dj = r.json()
            for attr in dj["attributes"]:
                if attr["name"] == "status" and attr["value"] == "accepted":
                    accepted = True
                    break
        if accepted:
            break
        time.sleep(1)
    if not accepted:
        raise ValueError(
            "status for device %s has not been propagated within %d seconds" %
            (d.id, timeout))

    submit_inventory(attributes, d.token)

    d.attributes = attributes

    return d
예제 #16
0
    def _test_args_actor(self, tenant_users, events):
        alogs = ApiClient(auditlogs.URL_MGMT)

        ids = [user.id for user in tenant_users.users]
        emails = [user.name for user in tenant_users.users]

        for id in ids:
            expected = [e for e in events if e["actor"]["id"] == id]

            resp = alogs.with_auth(tenant_users.users[0].token).call(
                "GET", auditlogs.URL_LOGS + "?actor_id=" + id)

            assert resp.status_code == 200
            resp = resp.json()

            assert len(resp) == len(expected)
            for i in range(len(resp)):
                check_log(resp[i], expected[i])

        for email in emails:
            expected = [e for e in events if e["actor"]["email"] == email]

            resp = alogs.with_auth(tenant_users.users[0].token).call(
                "GET", auditlogs.URL_LOGS + "?actor_email=" +
                urllib.parse.quote(email))

            assert resp.status_code == 200
            resp = resp.json()

            assert len(resp) == len(expected)
            for i in range(len(resp)):
                check_log(resp[i], expected[i])
예제 #17
0
 def test_upload_artifact_selection_match_depends_multiple_artifacts(
         self, mongo, clean_mongo):
     dev = self.setup_upload_artifact_selection(
         plan="enterprise",
         artifacts=(
             {
                 "artifact_name": "test",
                 "device_types": ["arm1"],
                 "depends": ("rootfs_image_checksum:checksum", ),
                 "provides": ("rootfs_image_checksum:provided", ),
             },
             {
                 "artifact_name": "test",
                 "device_types": ["arm1"],
                 "depends": ("rootfs_image_checksum:another-checksum", ),
                 "provides": ("rootfs_image_checksum:provided", ),
             },
         ),
     )
     deploymentsd = ApiClient(deployments.URL_DEVICES)
     r = deploymentsd.with_auth(dev.token).call(
         "POST",
         deployments.URL_NEXT,
         body={
             "device_type": "arm1",
             "artifact_name": "old-artifact",
             "rootfs_image_checksum": "another-checksum",
         },
     )
     assert r.status_code == 200
예제 #18
0
    def test_deploy_to_group(self, clean_mongo, test_case):
        """
        Tests adding group restrinction to roles and checking that users
        are not allowed to deploy to devices outside the restricted
        groups.
        """
        dplmnt_MGMT = ApiClient(deployments.URL_MGMT)

        i = 0
        self.logger.info("RUN: %s", test_case["name"])
        tenant = create_org("org%d" % i,
                            "*****@*****.**" % i,
                            "password",
                            plan="enterprise")
        test_user = create_user(tid=tenant.id, **test_case["user"])
        tenant.users.append(test_user)
        login_tenant_users(tenant)

        # Initialize tenant's devices
        grouped_devices = setup_tenant_devices(tenant,
                                               test_case["device_groups"])

        # Add user to deployment group
        role = UserRole("RBAC_DEVGRP", test_case["permissions"])
        add_user_to_role(test_user, tenant, role)

        # Upload a bogus artifact
        artifact = Artifact("tester", ["qemux86-64"], payload="bogus")
        rsp = dplmnt_MGMT.with_auth(test_user.token).call(
            "POST",
            deployments.URL_DEPLOYMENTS_ARTIFACTS,
            files=((
                "artifact",
                (
                    "artifact.mender",
                    artifact.make(),
                    "application/octet-stream",
                ),
            ), ),
        )
        assert rsp.status_code == 201, rsp.text

        # Attempt to create deployment with test user
        devices = []
        for group in test_case["deploy_groups"]:
            for device in grouped_devices[group]:
                devices.append(device.id)

        rsp = dplmnt_MGMT.with_auth(test_user.token).call(
            "POST",
            deployments.URL_DEPLOYMENTS,
            body={
                "artifact_name": "tester",
                "name": "dplmnt",
                "devices": devices
            },
        )
        assert rsp.status_code == test_case["status_code"], rsp.text
        self.logger.info("PASS: %s" % test_case["name"])
    def test_ok(self, user):
        useradmm = ApiClient(useradm.URL_MGMT)
        devauthd = ApiClient(deviceauth_v1.URL_DEVICES)
        invm = ApiClient(inventory.URL_MGMT)
        invd = ApiClient(inventory.URL_DEV)

        # log in user
        r = useradmm.call('POST',
                          useradm.URL_LOGIN,
                          auth=(user.name, user.pwd))
        assert r.status_code == 200
        utoken = r.text

        # prepare accepted devices
        devs = make_accepted_devices(utoken, devauthd, 3)

        # wait for devices to be provisioned
        time.sleep(3)

        for i, d in enumerate(devs):
            payload = [
                {
                    "name": "mac",
                    "value": "mac-new-" + str(d.id)
                },
                {
                    #empty value for existing
                    "name": "sn",
                    "value": "",
                },
                {
                    #empty value for new
                    "name": "new-empty",
                    "value": "",
                }
            ]
            r = invd.with_auth(d.token).call('PATCH',
                                             inventory.URL_DEVICE_ATTRIBUTES,
                                             payload)
            assert r.status_code == 200

        for d in devs:
            r = invm.with_auth(utoken).call('GET',
                                            inventory.URL_DEVICE,
                                            path_params={'id': d.id})
            assert r.status_code == 200

            api_dev = r.json()
            assert len(api_dev['attributes']) == 3

            for a in api_dev['attributes']:
                if a['name'] == 'mac':
                    assert a['value'] == 'mac-new-' + str(api_dev['id'])
                elif a['name'] == 'sn':
                    assert a['value'] == ''
                elif a['name'] == 'new-empty':
                    assert a['value'] == ''
                else:
                    assert False, 'unexpected attribute ' + a['name']
예제 #20
0
def login_tenant_users(tenant):
    useradm_MGMT = ApiClient(useradm.URL_MGMT)
    for user in tenant.users:
        rsp = useradm_MGMT.call("POST",
                                useradm.URL_LOGIN,
                                auth=(user.name, user.pwd))
        assert rsp.status_code == 200, "Failed to setup test environment"
        user.token = rsp.text
예제 #21
0
    def verify_dev_provisioned(self, dev, utoken):
        invm = ApiClient(inventory.URL_MGMT)

        r = invm.with_auth(utoken).call(
            "GET", inventory.URL_DEVICE, path_params={"id": dev.id}
        )
        assert r.status_code == 200

        api_dev = r.json()
예제 #22
0
class _TestMonitoringAlertsBase:
    useradm = ApiClient(useradm.URL_MGMT)
    devmond = ApiClient(devicemonitor.URL_DEVICES)
    invm = ApiClient(inventory.URL_MGMT)

    def test_alerting_email(self, test_case, user, devices, smtp_server):
        device = devices.pop(1)
        r = self.devmond.with_auth(device.token).call(
            "POST",
            devicemonitor.URL_ALERT,
            test_case["alerts"],
        )
        assert r.status_code < 300

        try:
            wait_start = datetime.now()
            smtp_server.await_messages(user.name, len(test_case["alerts"]),
                                       ONE_MINUTE_SEC)
            wait_time = datetime.now() - wait_start
            # Wait the same amount of time for which we expect
            # to see more messages incomming if there are any.
            time.sleep(wait_time.total_seconds())
        except TimeoutError:
            raise TimeoutError(
                "did not receive the expected number of emails in time (%.0f seconds)"
                % ONE_MINUTE_SEC)
        messages = smtp_server.filtered_messages(user.name)
        assert len(messages) == len(test_case["alerts"])

        regex = test_case.get("email_regex", [])
        if isinstance(regex, str):
            regex = [regex]

        for message in messages:
            data = message.data.decode("utf-8")
            assert device.id in data
            assert user.name in data
            for ex in regex:
                assert re.search(
                    ex, data), "email did not contain expected content"

        rsp = self.invm.with_auth(user.token).call(
            "GET", inventory.URL_DEVICE.format(id=device.id))
        assert rsp.status_code == 200
        alert_count_attrs = {
            x["name"]: x["value"]
            for x in filter(
                lambda x: x["scope"] == "monitor",
                rsp.json()["attributes"],
            )
        }
        assert len(alert_count_attrs) == 2
        assert alert_count_attrs["alert_count"] == test_case["alert_count"]
        if test_case["alert_count"] > 0:
            assert alert_count_attrs["alerts"] == True
        else:
            assert alert_count_attrs["alerts"] == False
예제 #23
0
    def test_deploy_to_devices(self, clean_mongo, test_case):
        """
        Tests adding group restrinction to roles and checking that users
        are not allowed to deploy to devices by providing list of device IDs.
        The only exception is single device deployment.
        """
        self.logger.info("RUN: %s", test_case["name"])

        uuidv4 = str(uuid.uuid4())
        tenant, username, password = (
            "test.mender.io-" + uuidv4,
            "some.user+" + uuidv4 + "@example.com",
            "secretsecret",
        )
        tenant = create_org(tenant, username, password, "enterprise")
        test_case["user"]["name"] = test_case["user"]["name"].replace("UUID", uuidv4)
        test_user = create_user(tid=tenant.id, **test_case["user"])
        tenant.users.append(test_user)
        login_tenant_users(tenant)

        # Initialize tenant's devices
        grouped_devices = setup_tenant_devices(tenant, test_case["device_groups"])

        # Add user to deployment group
        role = UserRole("RBAC_DEVGRP", test_case["permissions"])
        add_user_to_role(test_user, tenant, role)

        # Upload a bogus artifact
        artifact = Artifact("tester", ["qemux86-64"], payload="bogus")

        dplmnt_MGMT = ApiClient(deployments.URL_MGMT)
        rsp = dplmnt_MGMT.with_auth(test_user.token).call(
            "POST",
            deployments.URL_DEPLOYMENTS_ARTIFACTS,
            files=(
                (
                    "artifact",
                    ("artifact.mender", artifact.make(), "application/octet-stream"),
                ),
            ),
        )
        assert rsp.status_code == 201, rsp.text

        # Attempt to create deployment with test user
        devices = []
        for group in test_case["deploy_groups"]:
            for device in grouped_devices[group]:
                devices.append(device.id)

        rsp = dplmnt_MGMT.with_auth(test_user.token).call(
            "POST",
            deployments.URL_DEPLOYMENTS,
            body={"artifact_name": "tester", "name": "dplmnt", "devices": devices},
        )
        assert rsp.status_code == test_case["status_code"], rsp.text
        self.logger.info("PASS: %s" % test_case["name"])
예제 #24
0
    def test_user_cannot_log_in(self, tenants_users):
        tc = ApiClient(tenantadm.URL_INTERNAL)

        uc = ApiClient(useradm.URL_MGMT)

        for u in tenants_users[0].users:
            r = uc.call('POST', useradm.URL_LOGIN, auth=(u.name, u.pwd))
            assert r.status_code == 200

        # tenant's users can log in
        for u in tenants_users[0].users:
            r = uc.call('POST', useradm.URL_LOGIN, auth=(u.name, u.pwd))
            assert r.status_code == 200

        assert r.status_code == 200

        # suspend tenant
        r = tc.call('PUT',
                    tenantadm.URL_INTERNAL_SUSPEND,
                    tenantadm.req_status('suspended'),
                    path_params={'tid': tenants_users[0].id})
        assert r.status_code == 200

        time.sleep(10)

        # none of tenant's users can log in
        for u in tenants_users[0].users:
            r = uc.call('POST', useradm.URL_LOGIN, auth=(u.name, u.pwd))
            assert r.status_code == 401

        # but other users still can
        for u in tenants_users[1].users:
            r = uc.call('POST', useradm.URL_LOGIN, auth=(u.name, u.pwd))
            assert r.status_code == 200
예제 #25
0
    def test_set_and_deploy_configuration(self, clean_mongo, test_case):
        """
        Tests adding group restrinction to roles and checking that users
        are not allowed to set and deploy configuration to devices outside the restricted
        groups.
        """
        self.logger.info("RUN: %s", test_case["name"])

        uuidv4 = str(uuid.uuid4())
        tenant, username, password = (
            "test.mender.io-" + uuidv4,
            "some.user+" + uuidv4 + "@example.com",
            "secretsecret",
        )
        tenant = create_org(tenant, username, password, "enterprise")

        update_tenant(tenant.id, addons=["configure"])

        test_case["user"]["name"] = test_case["user"]["name"].replace(
            "UUID", uuidv4)
        test_user = create_user(tid=tenant.id, **test_case["user"])
        tenant.users.append(test_user)
        login_tenant_users(tenant)

        # Initialize tenant's devices
        grouped_devices = setup_tenant_devices(tenant,
                                               test_case["device_groups"])

        # Add user to deployment group
        role = UserRole("RBAC_DEVGRP", test_case["permissions"])
        add_user_to_role(test_user, tenant, role)

        deviceconf_MGMT = ApiClient(deviceconfig.URL_MGMT)

        device_id = grouped_devices[test_case["deploy_group"]][0].id

        # Attempt to set configuration
        rsp = deviceconf_MGMT.with_auth(test_user.token).call(
            "PUT",
            deviceconfig.URL_MGMT_DEVICE_CONFIGURATION.format(id=device_id),
            body={"foo": "bar"},
        )
        assert rsp.status_code == test_case[
            "set_configuration_status_code"], rsp.text

        # Attempt to deploy the configuration
        rsp = deviceconf_MGMT.with_auth(test_user.token).call(
            "POST",
            deviceconfig.URL_MGMT_DEVICE_CONFIGURATION_DEPLOY.format(
                id=device_id),
            body={"retries": 0},
        )
        assert (rsp.status_code ==
                test_case["deploy_configuration_status_code"]), rsp.text
        self.logger.info("PASS: %s" % test_case["name"])
예제 #26
0
    def test_provides_depends_ignored_in_lower_plans(self, mongo, clean_mongo,
                                                     plan):
        dev = self.setup_upload_artifact_selection(
            plan=plan,
            artifacts=(
                {
                    "artifact_name": "test",
                    "device_types": ["arm1"],
                    "size": 256,
                },
                {
                    "artifact_name": "test",
                    "device_types": ["arm1"],
                    "depends": (
                        "foo:fooval",
                        "bar:barval",
                    ),
                    "size": 1024,
                },
            ),
        )
        deploymentsd = ApiClient(deployments.URL_DEVICES)
        r = deploymentsd.with_auth(dev.token).call(
            "POST",
            deployments.URL_NEXT,
            body={
                "device_type": "arm1",
                "artifact_name": "old-artifact",
                "foo": "fooval",
                "bar": "barval",
            },
        )
        assert r.status_code == 200
        data = r.json()
        r = requests.get(data["artifact"]["source"]["uri"], verify=False)
        assert r.status_code == 200

        f = tempfile.NamedTemporaryFile(delete=False)
        try:
            f.write(r.content)
            f.close()
            #
            p = subprocess.Popen(["mender-artifact", "read", f.name],
                                 stdout=subprocess.PIPE)
            stdout = p.stdout.read().decode("utf-8")
            m_size = re.search(r".*size: *([0-9]+).*", stdout, re.M | re.I)
            assert m_size is not None
            size = int(m_size.group(1))

            # if provides/depends wasn't ignored - the matching, larger
            # artifact should have been selected
            # that's not the case, and we selected 'smallest of all'
            assert size == 256
        finally:
            os.unlink(f.name)
예제 #27
0
def upload_image(filename, auth_token, description="abc"):
    api_client = ApiClient(deployments.URL_MGMT)
    api_client.headers={}
    r = api_client.with_auth(auth_token).call(
        'POST',
        deployments.URL_DEPLOYMENTS_ARTIFACTS,
        files=(("description", (None, description)),
               ("size", (None, str(os.path.getsize(filename)))),
               ("artifact", (filename, open(filename, 'rb'),
                             "application/octet-stream"))))
    assert r.status_code == 201
예제 #28
0
    def check_access_auditlogs(self, auth, forbid=False):
        alogs = ApiClient(
            host=get_container_manager().get_mender_gateway(),
            base_url=auditlogs.URL_MGMT,
        )
        res = alogs.call("GET", auditlogs.URL_LOGS, headers=auth.get_auth_token(),)

        if forbid:
            assert res.status_code == 403
        else:
            assert res.ok
예제 #29
0
    def check_access_rbac(self, auth, forbid=False):
        uadm = ApiClient(
            host=get_container_manager().get_mender_gateway(),
            base_url=useradm.URL_MGMT,
        )
        res = uadm.call("GET", useradm.URL_ROLES, headers=auth.get_auth_token(),)

        if forbid:
            assert res.status_code == 403
        else:
            assert res.ok
예제 #30
0
    def setup_class(cls):
        cls.azure_iot_hub_mock = os.environ.get("AZURE_IOTHUB_MOCK")
        cls.azure_client = get_azure_client()

        cls.api_devauth_devices = ApiClient(base_url=deviceauth.URL_DEVICES)
        cls.api_devauth_mgmt = ApiClient(base_url=deviceauth.URL_MGMT)
        cls.api_azure = ApiClient(base_url=iot.URL_MGMT)
        cls.api_deviceconfig = ApiClient(base_url=deviceconfig.URL_MGMT)

        cls.devices = list()
        cls.logger = logging.getLogger(cls.__class__.__name__)