Ejemplo n.º 1
0
def test_negative_super_user_creation_fails():
    """Test that if super user creation fails, we get the right exception.

    If no super user token is provided, then config.get_config will call
    injector.make_super_user. If this fails, we want config.get_config
    to bail out with as informative of a message as possible, so tests
    can fail more gracefully and we can know what happened.

    This test ensures that if injector.make_super_user throws a RuntimeError,
    that config.get_config raises an exceptions.MissingConfigurationError so
    so that integrade.tests.conftest.check_superuser can catch that and let
    the user know what happened.
    """
    with mock.patch.object(config, '_CONFIG', None):
        with mock.patch.dict(os.environ, {}, clear=True):
            account_number = int(time.time())
            os.environ['CLOUDIGRADE_USER'] = '******'
            os.environ['CLOUDIGRADE_PASSWORD'] = '******'
            os.environ['CLOUDIGRADE_BASE_URL'] = 'example.com'
            os.environ['CLOUDIGRADE_ROLE_CUSTOMER1'] = '{}:{}:{}'.format(
                utils.uuid4(), account_number, utils.uuid4())
            os.environ['AWS_ACCESS_KEY_ID_CUSTOMER1'] = utils.uuid4()
            with mock.patch.object(injector,
                                   'make_super_user') as make_super_user:
                make_super_user.side_effect = RuntimeError()
                with pytest.raises(exceptions.MissingConfigurationError):
                    config.get_config()
Ejemplo n.º 2
0
def needed_aws_profiles_present(num_profiles=1):
    """Return True if the number of profiles indicated are present.

    See the README for how aws profiles for customers are defined.
    """
    return False if not config.get_config().get('aws_profiles') else len(
        config.get_config().get('aws_profiles', [])) > num_profiles
Ejemplo n.º 3
0
def check_superuser():
    """Ensure that we have a valid superuser for the test run."""
    try:
        config.get_config()
        client = api.Client(response_handler=api.echo_handler)
        response = client.get(urls.AUTH_ME)
        assert response.status_code == 200, response.url
    except (AssertionError, exceptions.MissingConfigurationError) as e:
        pytest.fail('Super user creation must have failed. '
                    f'Error: {repr(e)}')
Ejemplo n.º 4
0
def test_negative_get_config_missing():
    """If a base url is specified in the environment, we use it."""
    with mock.patch.object(config, '_CONFIG', None):
        with mock.patch.dict(os.environ, {}, clear=True):
            with mock.patch.object(injector,
                                   'make_super_user') as make_super_user:
                make_super_user.return_value = utils.uuid4()
                os.environ['CLOUDIGRADE_ROLE_CUSTOMER1'] = '{}:{}:{}'.format(
                    utils.uuid4(), '1234', utils.uuid4())
                try:
                    config.get_config()
                except exceptions.MissingConfigurationError as e:
                    msg = str(e)
                    msg.replace('\n', ' ')
                    assert 'AWS access key id' in msg
Ejemplo n.º 5
0
def test_cloudi_create_account():
    """Ensure that Cloudigrade responds appropriately to Sources trigger.

    :id: 8DA8D12F-A6FE-426E-BF87-33DFBE2E65D0
    :description: Ensure that Cloudigrade recognizes when a user initiates
        an event via Sources.
    :steps:
        1) Add a source with AWS credentials.
        2) Watch Cloudigrade to see that a new cloud account with the
        appropriate arn is created.
    :expectedresults:
        1) Account is created in Cloudigrade with a name matching the pattern
        'aws-account-<ACCOUNT_NUMBER_OF_TEMP_AWS_ACCOUNT>'.
        2) Said account has expected arn for same temp account in AWS.
    """
    client = api.ClientV2()
    arn = 'arn:aws:iam::439727791560:role/cloudigrade-role-for-743187646576'
    # Make sure that there isn't already an account using this arn.
    aws_profile = config.get_config()['aws_profiles'][0]
    delete_preexisting_accounts(aws_profile)
    # delete_current_cloud_accounts(arn)
    # Trigger Sources authentication
    create_auth_obj_in_sources()
    time = 30
    params = ('get', 'accounts/')
    cloudi_response = wait_for_response_with_timeout(client, params, arn, time)
    assert cloudi_response['name'] == 'aws-account-439727791560'
    assert cloudi_response['content_object']['account_arn'] == arn
Ejemplo n.º 6
0
def test_superuser_login():
    """Test that we can login as a super user and identify we are super.

    :id: 0815070f-5042-45ba-a6bb-f2596f764c7e
    :description: Test that we can login with a super user's credentials and
        that the token response includes a flag indicating super user status.
    :steps:
        1) Send POST with username and password to the token endpoint.
    :expectedresults:
        1) Receive an authorization token that can then be used to build
           authentication headers and make authenticated requests.
        2) Assert a 200 response is returned and the information about the
           logged in user are correct
        3) Assert the response includes the `is_superuser` field set to True
    """
    config = get_config()
    client = api.Client(authenticate=False)
    user = {
        'username': config['super_user_name'],
        'password': config['super_user_password'],
    }
    response = client.post(urls.AUTH_TOKEN_CREATE, user)
    assert response.status_code == 200
    json_response = response.json()
    assert 'auth_token' in json_response
    assert json_response['is_superuser']
Ejemplo n.º 7
0
def test_get_config(ssl, protocol):
    """If a base url is specified in the environment, we use it."""
    with mock.patch.object(config, '_CONFIG', None):
        with mock.patch.dict(os.environ, {}, clear=True):
            token = utils.uuid4()
            use_https = 'True' if protocol == 'https' else 'False'
            account_number = int(time.time())
            cloudtrail_prefix = random.choice([
                'aardvark',
                'aardvark-',
                'flying-aardvark-',
                '42',
                utils.uuid4(),
            ])
            bucket_name = 'flying-aardvark-s3'
            os.environ['CLOUDIGRADE_TOKEN'] = token
            os.environ['CLOUDIGRADE_BASE_URL'] = 'example.com'
            os.environ['AWS_S3_BUCKET_NAME'] = bucket_name
            os.environ['CLOUDIGRADE_ROLE_CUSTOMER1'] = '{}:{}:{}'.format(
                utils.uuid4(), account_number, utils.uuid4())
            os.environ['CLOUDTRAIL_PREFIX'] = cloudtrail_prefix
            os.environ['AWS_ACCESS_KEY_ID_CUSTOMER1'] = utils.uuid4()
            os.environ['USE_HTTPS'] = use_https
            os.environ['SSL_VERIFY'] = 'True' if ssl else 'False'
            cfg = config.get_config()
            assert cfg['superuser_token'] == token
            assert cfg['base_url'] == 'example.com'
            assert cfg['scheme'] == protocol
            assert cfg['ssl-verify'] == ssl
            assert cfg['api_version'] == 'v1'
            assert len(cfg['aws_profiles']) == 1
            assert cfg['aws_profiles'][0]['name'] == 'CUSTOMER1'
            assert cfg['aws_profiles'][0]['cloudtrail_name'] == (
                f'{cloudtrail_prefix}{account_number}')
            assert cfg['cloudigrade_s3_bucket'] == bucket_name
Ejemplo n.º 8
0
def test_superuser_instances_report(instances_report_data):
    """Test that a superuser can retrieves a regular user's instances report.

    :id: d222617b-9304-4081-9b95-f1a193412b6e
    :description: Test that a superuser can retrieve a regular user's instances
        report.
    :steps:
        1) Add a cloud account for a regular user
        2) Add some instance usage data for the following images: blank, RHEL,
           OpenShift and RHEL + OpenShift
        3) As a superuser, generate an instances report for a given period
           providing a regular user ID.
        4) Ensure the report only shows information about the usage on the
           given period.
    :expectedresults:
        An instances report can be generated by a superuser impersonating a
        regular user and the information provided is accurate.
    """
    user1, user2, auth1, auth2, accounts1 = instances_report_data
    cfg = config.get_config()
    superuser_auth = api.TokenAuth(cfg.get('superuser_token'))
    client = api.Client(response_handler=api.json_handler)

    response = client.get(
        urls.REPORT_INSTANCES,
        params={
            'start': REPORT_START_DATE,
            'end': REPORT_END_DATE,
            'user_id': user1['id'],
        },
        auth=superuser_auth
    )

    assert response == EXPECTED_REPORT_DATA, response
Ejemplo n.º 9
0
def test_negative_create_cloud_account_missing(drop_account_data,
                                               field_to_delete):
    """Ensure attempts to create cloud accounts missing data are rejected.

    :id: a93821ba-4181-47e7-b685-dbe642c1441e
    :description: Ensure an user cannot register a cloud account missing data.
    :steps: 1) Create a user and authenticate with their password
        2) Send a POST with the incomplete cloud account information to
            'api/v1/account/'
    :expectedresults: The server rejects the incomplete request.
    """
    auth = get_auth()
    client = api.Client(authenticate=False, response_handler=api.echo_handler)
    cfg = config.get_config()
    aws_profile = cfg['aws_profiles'][0]
    profile_name = aws_profile['name']
    acct_arn = aws_profile['arn']

    cloud_account = {
        'account_arn': acct_arn,
        'resourcetype': 'AwsAccount',
        'name': profile_name,
    }
    # remove one field
    cloud_account.pop(field_to_delete)
    create_response = client.post(urls.CLOUD_ACCOUNT,
                                  payload=cloud_account,
                                  auth=auth)
    missing_fields = create_response.json().keys()
    assert create_response.status_code == 400, create_response.json()
    assert field_to_delete in missing_fields, create_response.json()
Ejemplo n.º 10
0
def test_create_no_config():
    """If a base url is specified we use it."""
    with patch.object(config, '_CONFIG', {}):
        assert config.get_config() == {}
        other_host = 'http://hostname.com'
        client = api.Client(url=other_host, authenticate=False)
        assert 'http://example.com/api/v1/' != client.url
        assert other_host == client.url
Ejemplo n.º 11
0
def test_create_override_config():
    """If a base url is specified, we use that instead of config file."""
    with patch.object(config, '_CONFIG', VALID_CONFIG):
        other_host = 'http://hostname.com'
        client = api.Client(url=other_host, authenticate=False)
        cfg_host = config.get_config()['base_url']
        assert cfg_host != client.url
        assert other_host == client.url
def get_s3_bucket_name():
    """Get the cloudigrade bucket name and raise an exception if not found."""
    bucket_name = config.get_config()['cloudigrade_s3_bucket']
    if not bucket_name:
        raise MissingConfigurationError(
            'Need to know the name of cloudigrade\'s s3'
            ' bucket to mock events!')
    return bucket_name
def all_the_images():
    """Provide a list of all available images to test."""
    aws_profile = config.get_config()['aws_profiles'][0]
    all_images = []
    image_types = aws_profile['images'].keys()
    for image_type in image_types:
        for image in aws_profile['images'][image_type]:
            all_images.append((image_type, image['name'], 'inspected'))
    return all_images
Ejemplo n.º 14
0
def test_list_specific_image(images_data):
    """Test if a specific image can be fetched.

    :id: 99aaec58-6053-476d-9674-ee650ffa33a9
    :description: Check if a regular user can fetch one of its images. Check if
        a superuser can fetch all images. Check if a regular user can't fetch
        an image that belongs to another user.
    :steps:
        1. Fetch all images
        2. For each image, check if its owner and a superuser can fetch each.
           Also check if another user can't fetch it.
    :expectedresults:
        A regular user can only fetch its images and a superuser can fetch all
        images.
    """
    user1, user2, auth1, auth2, images1, images2 = images_data
    cfg = config.get_config()
    superuser_auth = api.TokenAuth(cfg.get('superuser_token'))
    client = api.Client(authenticate=False)
    start, end = utils.get_time_range()

    response = client.get(urls.IMAGE, auth=superuser_auth).json()
    assert response['count'] == len(images1) + len(images2), response
    all_images = response['results']
    ec2_ami_ids1 = [image['ec2_ami_id'] for image in images1]
    ec2_ami_ids2 = [image['ec2_ami_id'] for image in images2]

    for image in all_images:
        if image['ec2_ami_id'] in ec2_ami_ids1:
            auth = auth1
            other_auth = auth2
        elif image['ec2_ami_id'] in ec2_ami_ids2:
            auth = auth2
            other_auth = auth1
        else:
            raise ValueError(
                f'{image} not in {ec2_ami_ids1} or {ec2_ami_ids2}')
        image_url = urljoin(urls.IMAGE, str(image['id']))

        # Ensure superuser can fetch it
        response = client.get(image_url, auth=superuser_auth).json()
        assert response == image

        # Ensure the image owner can fetch it
        response = client.get(image_url, auth=auth).json()
        assert response == image

        # Ensure any other user can't fetch it
        old_handler = client.response_handler
        client.response_handler = api.echo_handler
        response = client.get(image_url, auth=other_auth)
        client.response_handler = old_handler
        assert response.status_code == 404
        assert response.json()['detail'] == 'Not found.'
Ejemplo n.º 15
0
    def _():
        selenium.get(base_url(get_config()))
        assert selenium.title == 'Cloud Meter', selenium.page_source

        browser = Browser(selenium)
        login = LoginView(browser)

        # User is directed to the login page, not the dashboard
        wait = WebDriverWait(selenium, 30)
        wait.until(wait_for_page_text('Log In to Your Account'))

        return browser, login
Ejemplo n.º 16
0
def aws_instance_instigator():
    """Run instances in an aws account for testing purposes."""
    cfg = config.get_config()
    profile = cfg['aws_profiles'][0]
    profile_name = profile['name']
    image_type = 'owned'
    image_name = 'rhel-extra-detection-methods'

    instance_ids = aws_utils.run_instances_by_name(profile_name,
                                                   image_type,
                                                   image_name,
                                                   count=2)
    print(instance_ids)
Ejemplo n.º 17
0
def test_response_handlers(good_response, handler):
    """Test that when we get a good 2xx response, it is returned."""
    with patch.object(config, '_CONFIG', VALID_CONFIG):
        assert config.get_config() == VALID_CONFIG
        client = api.Client(
            authenticate=False,
            response_handler=handler
        )
        r = client.response_handler(good_response)
        if handler == api.json_handler:
            assert r == good_response.json()
        else:
            assert r == good_response
Ejemplo n.º 18
0
    def __init__(self, response_handler=None, url=None, authenticate=True,
                 token=None):
        """Initialize this object, collecting base URL from config file.

        If no response handler is specified, use the `code_handler` which will
        raise an exception for 'bad' return codes.

        If no URL is specified, then the url will be built from the
        environment variables $CLOUDIGRADE_BASE_URL and $USE_HTTPS values (see
        integrade/config.py).
        """
        self.token = token
        self.url = url
        cfg = config.get_config()
        self.verify = cfg.get('ssl-verify', False)

        if not self.url:
            hostname = cfg.get('base_url')

            if not hostname:
                raise exceptions.BaseUrlNotFound(
                    'Make sure you have $CLOUDIGRADE_BASE_URL set in in'
                    ' your environment.'
                )

            scheme = cfg.get('scheme')
            self.url = urlunparse(
                (
                    scheme,
                    hostname,
                    'api/{}/'.format(cfg.get('api_version')),
                    '', '', ''
                ))

        if response_handler is None:
            self.response_handler = code_handler
        else:
            self.response_handler = response_handler

        if authenticate:
            if not self.token:
                self.token = cfg.get('superuser_token')
            if not self.token:
                raise exceptions.TokenNotFound(
                    'No token was found to authenticate with the server. Make '
                    'sure you have $CLOUDIGRADE_TOKEN set in in your '
                    'environment.'
                )
Ejemplo n.º 19
0
def run_remote_python(script, **kwargs):
    """Run Python code inside the remote OpenShift pod."""
    script = dedent(script).strip()

    openshift_prefix = config.get_config()['openshift_prefix']
    if openshift_prefix:
        container_name = f'{openshift_prefix}a'
    else:
        raise RuntimeError('Unable to determine openshift prefix!')

    data = pickle.dumps(kwargs)
    wrap_start = 'import pickle as _pickle;import sys as _sys;\n' \
        f'globals().update(_pickle.loads({repr(data)}))\n' \
        'def _codewrapper():\n'
    wrap_end = '\n_retval = _codewrapper()\n' \
        '_sys.stdout.buffer.write(_pickle.dumps(_retval))\n'
    script = wrap_start + indent(script, '  ') + wrap_end
    script = script.encode('utf8')

    if which('oc'):
        result = subprocess.run(['sh',
                                 '-c',
                                 f'oc rsh -c {container_name} $(oc get pods'
                                 ' -o jsonpath="{.items[*].metadata.name}" -l'
                                 f' name={container_name})'
                                 ' scl enable rh-python36'
                                 ' -- python -W ignore manage.py shell'],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                input=script,
                                timeout=60
                                )
        if result.returncode != 0:
            for line in result.stdout:
                print(line)
            raise RuntimeError(
                f'Remote script failed (container_name="{container_name}"'
            )
        elif result.stdout:
            return pickle.loads(result.stdout)
    else:
        raise EnvironmentError(
            'Must have access to the cloudigrade openshift pod via the "oc"'
            'client to run remote commands in the Django manage.py shell. Make'
            'sure the "oc" client is in your path and the $OPENSHIFT_PREFIX'
            'used in the deploy is in your environment.'
        )
Ejemplo n.º 20
0
def test_response_handler_raises(
    bad_response_valid_json,
    handler
):
    """Test that when we get a 4xx or 5xx response, an error is raised."""
    with patch.object(config, '_CONFIG', VALID_CONFIG):
        assert config.get_config() == VALID_CONFIG
        bad_response = bad_response_valid_json
        client = api.Client(
            authenticate=False,
            response_handler=handler
        )
        if handler != api.echo_handler:
            with pytest.raises(requests.exceptions.HTTPError):
                client.response_handler(bad_response)
        else:
            # no error should be raised with the echo handler
            client.response_handler(bad_response)
Ejemplo n.º 21
0
def test_user_list(drop_account_data):
    """Super users can request lists of created user accounts.

    :id: 52567e92-2b6a-43b0-bdc0-5a347b9dd4bc
    :description: Super users, and only super users, are able to request a user
        list.
    :steps:
        1) Authenticate with a super user account and request the user list
            end point contains yourself and a created non-super user account.
        2) Authenticate with a non-super user account and request the user list
            to verify a 4xx error
    :expectedresults: The super user can get the list, but not the regular user
        account.
    """
    client = api.Client()
    response = client.get(urls.USER_LIST)
    pre_user_list = response.json()
    usernames = [user['username'] for user in pre_user_list]
    assert get_config()['super_user_name'] in usernames

    new_user = create_user_account()
    account_number = random.randint(2, 5)
    for _ in range(account_number):
        inject_aws_cloud_account(new_user['id'])
    response = client.get(urls.USER_LIST).json()

    for user in response:
        assert 'accounts' in user, user
        assert 'challenged_images' in user, user

        if user['id'] == new_user['id']:
            assert user['accounts'] == account_number
            assert user['challenged_images'] == 0

    new_user_list = [user for user in response if user not in pre_user_list]
    new_user_ids = [user['id'] for user in new_user_list]

    assert new_user['id'] in new_user_ids

    auth = get_auth(new_user)
    client = api.Client(authenticate=False, response_handler=api.echo_handler)
    response = client.get(urls.USER_LIST, auth=auth)
    assert response.status_code == 403
Ejemplo n.º 22
0
def test_create_cloud_account_duplicate_names_different_users(
        cloudtrails_to_delete):
    """Ensure cloud accounts can be registered to a user.

    :id: 7bf483b7-f0d0-40db-9c18-396dc4a58792
    :description: Ensure an user can register a cloud account by specifying
        the role ARN.
    :steps: 1) Create a user and authenticate with their password
        2) Send a POST with the cloud account information to 'api/v1/account/'
        3) Send a GET to 'api/v1/account/' to get a list of the cloud accounts
        4) Attempt to create a duplicate and expect it to be rejected
        5) Attempt to delete the account and expect to be rejected
    :expectedresults:
        1) The server returns a 201 response with the information
            of the created account.
        2) The account cannot be duplicated, and attempts to do so receive a
            400 status code.
        3) The account cannot be deleted and attempts to do so receive a 405
            response.
    """
    # TODO: refactor inject_aws_cloud_account to use seed data
    user = ''  # create_user_account()
    auth = get_auth(user)
    client = api.Client(authenticate=False, response_handler=api.echo_handler)
    cfg = config.get_config()
    aws_profile = cfg['aws_profiles'][0]
    # TODO: refactor inject_aws_cloud_account to use seed data
    profile_name = ''  # aws_profile['name']
    # inject_aws_cloud_account(user['id'], name=profile_name)

    # Now try to reuse the name
    auth = get_auth()
    aws_profile = cfg['aws_profiles'][1]
    acct_arn = aws_profile['arn']
    cloud_account = {
        'account_arn': acct_arn,
        'name': profile_name,
        'resourcetype': 'AwsAccount'
    }
    create_response = client.post(urls.CLOUD_ACCOUNT,
                                  payload=cloud_account,
                                  auth=auth)
    assert create_response.status_code == 201, create_response.json()
Ejemplo n.º 23
0
def test_cancel(browser_session, ui_addacct_page3, u1_user):
    """The user can add a new account using a valid current ARN.

    :id: fa01c0a2-86da-11e8-af5f-8c1645548902
    :description: The user can create and name a new cloud account.
    :steps:
        1) Open the dashboard and click the "Add Account"
        2) Enter a name for the account
        3) Proceed to page 3
        4) Enter an ARN which is valid ARN for a resource we are granted
           permission to
        5) Click the "Cancel" button to cancel attempt to create the account
    :expectedresults: The Account is not created and can't be fetched by the
        account list API for verification with the given name and ARN.
    """
    selenium = browser_session
    if find_element_by_text(selenium, 'Different Name', timeout=0.5):
        clean_slate(selenium)
        back_to_addacct_wizard(selenium)
    else:
        back_to_addacct_wizard(selenium)
    acct_arn = config.get_config()['aws_profiles'][0]['arn']
    dialog = selenium.find_element_by_xpath('//div[@role="dialog"]')
    fill_input_by_label(selenium, dialog, 'Account Name', 'My Account')
    find_element_by_text(selenium, 'Next').click()
    find_element_by_text(selenium, 'Next').click()

    fill_input_by_label(selenium, dialog, 'ARN', acct_arn)
    find_element_by_text(dialog, 'Cancel').click()
    find_element_by_text(selenium, 'Yes').click()

    pytest.raises(
        NoSuchElementException,
        selenium.find_element_by_tag_name,
        'dialog',
    )

    client = api.Client(authenticate=False)
    auth = get_auth(user=u1_user)
    sleep(0.25)
    response = client.get(urls.CLOUD_ACCOUNT, auth=auth)
    res = response.json()['results']
    assert res[0]['account_arn'] != acct_arn
Ejemplo n.º 24
0
def create_cloud_account(auth, n, cloudtrails_to_delete=None, name=_SENTINEL):
    """Create a cloud account based on configured AWS customer info."""
    client = api.Client(authenticate=False)
    cfg = config.get_config()
    aws_profile = cfg['aws_profiles'][n]
    acct_arn = aws_profile['arn']
    cloud_account = {
        'account_arn': acct_arn,
        'name': uuid4() if name is _SENTINEL else name,
        'resourcetype': 'AwsAccount'
    }
    create_response = client.post(urls.CLOUD_ACCOUNT,
                                  payload=cloud_account,
                                  auth=auth)
    assert create_response.status_code == 201

    if isinstance(cloudtrails_to_delete, list):
        cloudtrails_to_delete.append(
            (aws_profile['name'], aws_profile['cloudtrail_name']))
    return create_response.json()
Ejemplo n.º 25
0
 def __init__(self, url=None, response_handler=None, auth=None,
              env=None, branch=None):
     """Initialize this object, collecting base URL."""
     self.url = url
     cfg = config.get_config()
     self.verify = cfg.get('ssl-verify', False)
     self.auth = auth if auth is not None else get_credentials()
     self.env = env
     if branch is None:
         self.branch = os.environ.get('BRANCH_NAME')
     else:
         self.branch = branch
     if not self.branch:
         raise MissingConfigurationError(
             'BRANCH_NAME is missing.'
         )
     if response_handler is None:
         self.response_handler = code_handler
     else:
         self.response_handler = response_handler
     self._guess_v2_environment()
Ejemplo n.º 26
0
def test_create_multiple_cloud_accounts(drop_account_data,
                                        cloudtrails_to_delete):
    """Ensure cloud accounts can be registered to a user.

    :id: f1db2617-fd15-4270-b9d3-595db001e1e7
    :description: Ensure an user can register multiple cloud accounts as long
        as each ARN is associated with unique cloud accounts.
    :steps: 1) Create a user and authenticate with their password
        2) Send POSTS with each of the cloud account's information to
            'api/v1/account/'
        3) Send a GET to 'api/v1/account/' to get a list of the cloud accounts
    :expectedresults: The server returns a 201 response with the information of
        the created accounts.
    """
    client = api.Client(authenticate=False)
    auth = get_auth()
    cfg = config.get_config()
    accts = []
    for profile in cfg['aws_profiles']:
        arn = profile['arn']
        cloud_account = {
            'account_arn': arn,
            'name': uuid4(),
            'resourcetype': 'AwsAccount'
        }
        create_response = client.post(urls.CLOUD_ACCOUNT,
                                      payload=cloud_account,
                                      auth=auth)
        assert create_response.status_code == 201
        cloudtrails_to_delete.append(
            (profile['name'], profile['cloudtrail_name']))

        accts.append(create_response.json())

    # list cloud accounts associated with this user
    list_response = client.get(urls.CLOUD_ACCOUNT, auth=auth)
    for acct in accts:
        assert acct in list_response.json()['results']
Ejemplo n.º 27
0
def test_cancel(drop_account_data, browser_session, ui_addacct_page3, ui_user):
    """The user can add a new account using a valid current ARN.

    :id: fa01c0a2-86da-11e8-af5f-8c1645548902
    :description: The user can create and name a new cloud account.
    :steps:
        1) Open the dashboard and click the "Add Account"
        2) Enter a name for the account
        3) Proceed to page 3
        4) Enter an ARN which is valid ARN for a resource we are granted
           permission to
        5) Click the "Add" button to attempt to create the account
    :expectedresults: The Account is created and can be fetched by the account
        list API for verification with the given name and ARN.
    """
    selenium = browser_session
    dialog = ui_addacct_page3['dialog']

    assert ui_addacct_page3['dialog_add'].get_attribute('disabled')

    acct_arn = config.get_config()['aws_profiles'][0]['arn']
    fill_input_by_label(selenium, dialog, 'ARN', acct_arn)

    find_element_by_text(dialog, 'Cancel').click()
    find_element_by_text(selenium, 'Yes').click()

    pytest.raises(
        NoSuchElementException,
        selenium.find_element_by_tag_name,
        'dialog',
    )

    c = api.Client()
    r = c.get(urls.CLOUD_ACCOUNT).json()
    accounts = [a for a in r['results'] if a['user_id'] == ui_user['id']]
    assert accounts == []
Ejemplo n.º 28
0
def test_create_cloud_account_duplicate_names(drop_account_data,
                                              cloudtrails_to_delete):
    """Ensure cloud accounts can be registered to a user.

    :id: 47b6b382-092a-420f-a8b0-63e6578e4857
    :description: Ensure an user can register a cloud account by specifying
        the role ARN.
    :steps: 1) Create a user and authenticate with their password
        2) Send a POST with the cloud account information to 'api/v1/account/'
        3) Send a GET to 'api/v1/account/' to get a list of the cloud accounts
        4) Attempt to create a duplicate and expect it to be rejected
        5) Attempt to delete the account and expect to be rejected
    :expectedresults:
        1) The server returns a 201 response with the information
            of the created account.
        2) The account cannot be duplicated, and attempts to do so receive a
            400 status code.
        3) The account cannot be deleted and attempts to do so receive a 405
            response.
    """
    user = create_user_account()
    auth = get_auth(user)
    client = api.Client(authenticate=False, response_handler=api.echo_handler)
    cfg = config.get_config()
    inject_aws_cloud_account(user['id'], name=cfg['aws_profiles'][0]['name'])

    # Now try to reuse the name
    cloud_account = {
        'account_arn': cfg['aws_profiles'][0]['arn'],
        'name': cfg['aws_profiles'][0]['name'],
        'resourcetype': 'AwsAccount'
    }
    create_response = client.post(urls.CLOUD_ACCOUNT,
                                  payload=cloud_account,
                                  auth=auth)
    assert create_response.status_code == 400
Ejemplo n.º 29
0
def test_create_with_config():
    """If a base url is specified in the environment, we use it."""
    with patch.object(config, '_CONFIG', VALID_CONFIG):
        assert config.get_config() == VALID_CONFIG
        client = api.Client(authenticate=False)
        assert client.url == 'http://example.com/api/v1/'
Ejemplo n.º 30
0
def test_empty_default_headers():
    """Test when a token is not defined, default_headers is an empty dict."""
    with patch.object(config, '_CONFIG', VALID_CONFIG):
        assert config.get_config() == VALID_CONFIG
        client = api.Client(authenticate=False)
        assert client.default_headers() == {}