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
def test_token_auth(): """Test TokenAuth generates proper request header.""" token = uuid4() header_format = uuid4() auth = api.TokenAuth(token, header_format) request = Mock() request.headers = {} changed_request = auth(request) assert changed_request is request assert 'Authorization' in request.headers assert request.headers['Authorization'] == f'{header_format} {token}'
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.'
def test_login_logout(): """Test that we can login, make requests and logout to the server. :id: 2eb55229-4e1e-4d35-ac4a-4f2424d37cf6 :description: Test that we can login, make requests and logout to the server. :steps: 1) Send POST with username and password to the token endpoint. 2) Send a GET request to /auth/me/ with the authorization token from previous step in the headers. 3) Send a POST request to /auth/token/destroy/. 4) Try to access /auth/me/ again with the authorization token from step 1. :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, including being flagged as a non-super user 3) Assert a 204 response is returned 4) Assert a 401 response is returned and the detailed message states the authentication token is now invalid. """ user = create_user_account() client = api.Client(authenticate=False) response = client.post(urls.AUTH_TOKEN_CREATE, user) assert response.status_code == 200 json_response = response.json() assert 'auth_token' in json_response assert not json_response['is_superuser'] auth = api.TokenAuth(json_response['auth_token']) response = client.get(urls.AUTH_ME, auth=auth) assert response.status_code == 200 json_response = response.json() assert json_response['email'] == user['email'] assert json_response['username'] == user['username'] response = client.post(urls.AUTH_TOKEN_DESTROY, {}, auth=auth) assert response.status_code == 204 client.response_handler = api.echo_handler response = client.get(urls.AUTH_ME, auth=auth) assert response.status_code == 401 json_response = response.json() assert json_response['detail'] == 'Invalid token.'
def test_token_negative(endpoint): """Given that we have an invalid token, we cannot make requests. :id: a87f7069-3ee9-4435-a953-fd8664199419 :description: Test that if we have a bad token, we cannot use it to make requests to any of the /api/v1/* endpoints :steps: 1) Send a GET request with a invalid authorization token in the header to all /api/v1/* endpoints. 2) Assert that we get a 401 response for all requests. :expectedresults: The server rejects our invalid token for all /api/v1/* endpoints. """ client = api.Client(response_handler=api.echo_handler) auth = api.TokenAuth(uuid4()) response = client.get(f'/api/v1/{endpoint}', auth=auth) assert response.status_code == 401 assert response.json() == {'detail': 'Invalid token.'}
def get_auth(user=None): """Get authentication for given user to use with requests. For example:: usr = create_user_account({ 'email': '', 'password': gen_password(), 'username': uuid4(), }) auth = get_auth(username, pwd) client = api.Client(authenticate=False) client.get(urls.AUTH_ME, auth=auth) If no user is provided, a new user is created. This is useful when you need to make authenticated requests as a regular user, but never need to use the user information for anything else. Example:: from integrade.tests import urls client = api.client(authenticate=False) auth1 = get_auth() client.get(urls.CLOUD_ACCOUNT, auth=auth1) :returns: instance of api.TokenAuth """ if not user: email = f'{uuid4()}@example.com' password = gen_password() user = create_user_account({ 'email': email, 'password': password, 'username': email, }) print(f'USER {email} {password}') client = api.Client(authenticate=False) response = client.post(urls.AUTH_TOKEN_CREATE, user) assert response.status_code == 200 json_response = response.json() assert 'auth_token' in json_response return api.TokenAuth(json_response['auth_token'])
def test_challenge_image(superuser, method): """Test if a challenge flags for RHEL and OS can be changed. :id: ec5fe0b6-9852-48db-a2ba-98d01aeaac28 :description: Try to change challenge flags on an image and ensure that change is reflected afterwards. :steps: 1. Create an image in a known account and make sure the challenge flags are false by default. 2. Use both PUT and PATCH forms of the image endpoint to set a flag to true :expectedresults: The image data now reflects this change. """ cfg = config.get_config() user = utils.create_user_account() auth = utils.get_auth(user) client = api.Client(authenticate=False) account = inject_aws_cloud_account( user['id'], name=uuid4(), ) image_type = '' ec2_ami_id = str(random.randint(100000, 999999999999)) image_id = inject_instance_data( account['id'], image_type, [random.randint(0, 20)], ec2_ami_id=ec2_ami_id, )['image_id'] if superuser: auth = api.TokenAuth(cfg.get('superuser_token')) image_url = urljoin(urls.IMAGE, str(image_id)) + '/' # Ensure the image owner can fetch it response = client.get(image_url, auth=auth).json() assert response['rhel_challenged'] is False assert response['openshift_challenged'] is False for tag in ('rhel', 'openshift'): if method == 'put': response[f'{tag}_challenged'] = True response = client.put(image_url, response, auth=auth).json() elif method == 'patch': data = { 'resourcetype': 'AwsMachineImage', f'{tag}_challenged': True, } response = client.patch(image_url, data, auth=auth).json() else: pytest.fail(f'Unknown method "{method}"') assert response[f'{tag}_challenged'] is True # Make sure the change is reflected in new responses response = client.get(image_url, auth=auth).json() response[f'{tag}_challenged'] = True # Ensure any other user can't fetch it response = client.get(image_url, auth=auth) assert response.status_code == 200 assert response.json()[f'{tag}_challenged']