diff options
Diffstat (limited to 'tests/unit/auth')
20 files changed, 1452 insertions, 377 deletions
diff --git a/tests/unit/auth/conftest.py b/tests/unit/auth/conftest.py index 7f9d42d..fa86a4c 100644 --- a/tests/unit/auth/conftest.py +++ b/tests/unit/auth/conftest.py @@ -4,19 +4,41 @@ import datetime from contextlib import contextmanager from gn_auth.auth.authentication.oauth2.models.oauth2token import OAuth2Token +from gn_auth.auth.authentication.oauth2.grants.jwt_bearer_grant import JWTBearerTokenGenerator from .fixtures import * # pylint: disable=[wildcard-import,unused-wildcard-import] -def get_tokeniser(user): +SECRET_KEY = "this is the test secret key" +SCOPE = "profile group role resource register-client" + +def _tokengenerator(user, client): + """Generate a JWT token for tests""" + _generator = JWTBearerTokenGenerator( + secret_key=SECRET_KEY, + alg="HS256") + return _generator( + grant_type="urn:ietf:params:oauth:grant-type:jwt-bearer", + client=client, + user=user, + scope=SCOPE, + expires_in=3600, + include_refresh_token=False) + +def get_tokeniser(user, client): """Get contextmanager for mocking token acquisition.""" @contextmanager def __token__(*args, **kwargs):# pylint: disable=[unused-argument] yield { usr.user_id: OAuth2Token( token_id=uuid.UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"), - client=None, token_type="Bearer", access_token="123456ABCDE", - refresh_token=None, revoked=False, expires_in=864000, - user=usr, issued_at=int(datetime.datetime.now().timestamp()), + client=client, + token_type="Bearer", + access_token=_tokengenerator(user, client), + refresh_token=None, + revoked=False, + expires_in=864000, + user=usr, + issued_at=int(datetime.datetime.now().timestamp()), scope="profile group role resource register-client") for usr in TEST_USERS }[user.user_id] diff --git a/tests/unit/auth/fixtures/group_fixtures.py b/tests/unit/auth/fixtures/group_fixtures.py index 79683c0..da1c4cd 100644 --- a/tests/unit/auth/fixtures/group_fixtures.py +++ b/tests/unit/auth/fixtures/group_fixtures.py @@ -1,13 +1,18 @@ """Fixtures and utilities for group-related tests""" import uuid +import datetime import pytest from gn_auth.auth.db import sqlite3 as db -from gn_auth.auth.authorisation.resources.groups import Group, GroupRole +from gn_auth.auth.authorisation.resources.groups import Group from gn_auth.auth.authorisation.resources import Resource, ResourceCategory -from .role_fixtures import RESOURCE_EDITOR_ROLE, RESOURCE_READER_ROLE +from .user_fixtures import TEST_USERS +from .resource_fixtures import TEST_RESOURCES + + +_created_ = datetime.datetime.now() TEST_GROUP_01 = Group(uuid.UUID("9988c21d-f02f-4d45-8966-22c968ac2fbf"), "TheTestGroup", {}) @@ -15,16 +20,6 @@ TEST_GROUP_02 = Group(uuid.UUID("e37d59d7-c05e-4d67-b479-81e627d8d634"), "AnotherTestGroup", {}) TEST_GROUPS = (TEST_GROUP_01, TEST_GROUP_02) -SYSTEM_CATEGORY = ResourceCategory( - uuid.UUID("aa3d787f-af6a-44fa-9b0b-c82d40e54ad2"), - "system", - "The overall system.") -SYSTEM_RESOURCE = Resource( - uuid.UUID("0248b289-b277-4eaa-8c94-88a434d14b6e"), - "GeneNetwork System", - SYSTEM_CATEGORY, - True) - GROUP_CATEGORY = ResourceCategory( uuid.UUID("1e0f70ee-add5-4358-8c6c-43de77fa4cce"), "group", @@ -34,56 +29,33 @@ GROUPS_AS_RESOURCES = tuple({ "resource_id": res_id, "resource_name": group.group_name, "category_id": str(GROUP_CATEGORY.resource_category_id), - "public": "0" + "public": "0", + "created_by": str(TEST_USERS[0].user_id), + "created_at": _created_.timestamp() } for res_id, group in zip( ("38d1807d-105f-44a7-8327-7e2d973b6d8d", "89458ef6-e090-4b53-8c2c-59eaf2785f11"), TEST_GROUPS)) GROUP_RESOURCES = tuple( - Resource(uuid.UUID(row["resource_id"]), - row["resource_name"], + Resource(uuid.UUID(row["resource_id"]),# type: ignore[arg-type] + row["resource_name"],# type: ignore[arg-type] GROUP_CATEGORY, - False) + False, + created_by=TEST_USERS[0], + created_at=_created_) for row in GROUPS_AS_RESOURCES) -TEST_RESOURCES_GROUP_01 = ( - Resource(uuid.UUID("26ad1668-29f5-439d-b905-84d551f85955"), - "ResourceG01R01", - ResourceCategory(uuid.UUID("48056f84-a2a6-41ac-8319-0e1e212cba2a"), - "genotype", "Genotype Dataset"), - True), - Resource(uuid.UUID("2130aec0-fefd-434d-92fd-9ca342348b2d"), - "ResourceG01R02", - ResourceCategory(uuid.UUID("548d684b-d4d1-46fb-a6d3-51a56b7da1b3"), - "phenotype", "Phenotype (Publish) Dataset"), - False), - Resource(uuid.UUID("e9a1184a-e8b4-49fb-b713-8d9cbeea5b83"), - "ResourceG01R03", - ResourceCategory(uuid.UUID("fad071a3-2fc8-40b8-992b-cdefe7dcac79"), - "mrna", "mRNA Dataset"), - False)) - -TEST_RESOURCES_GROUP_02 = ( - Resource(uuid.UUID("14496a1c-c234-49a2-978c-8859ea274054"), - "ResourceG02R01", - ResourceCategory(uuid.UUID("48056f84-a2a6-41ac-8319-0e1e212cba2a"), - "genotype", "Genotype Dataset"), - False), - Resource(uuid.UUID("04ad9e09-94ea-4390-8a02-11f92999806b"), - "ResourceG02R02", - ResourceCategory(uuid.UUID("fad071a3-2fc8-40b8-992b-cdefe7dcac79"), - "mrna", "mRNA Dataset"), - True)) - -TEST_RESOURCES = TEST_RESOURCES_GROUP_01 + TEST_RESOURCES_GROUP_02 -TEST_RESOURCES_PUBLIC = ( - SYSTEM_RESOURCE, TEST_RESOURCES_GROUP_01[0], TEST_RESOURCES_GROUP_02[1]) + +TEST_RESOURCES_GROUP_01 = TEST_RESOURCES[0:3] +TEST_RESOURCES_GROUP_02 = TEST_RESOURCES[3:5] + + def __gtuple__(cursor): return tuple(dict(row) for row in cursor.fetchall()) @pytest.fixture(scope="function") -def fxtr_group(conn_after_auth_migrations):# pylint: disable=[redefined-outer-name] +def fxtr_group(conn_after_auth_migrations, fxtr_users):# pylint: disable=[redefined-outer-name, unused-argument] """Fixture: setup a test group.""" with db.cursor(conn_after_auth_migrations) as cursor: cursor.executemany( @@ -94,7 +66,7 @@ def fxtr_group(conn_after_auth_migrations):# pylint: disable=[redefined-outer-na cursor.executemany( "INSERT INTO resources " - "VALUES(:resource_id, :resource_name, :category_id, :public)", + "VALUES(:resource_id, :resource_name, :category_id, :public, :created_by, :created_at)", GROUPS_AS_RESOURCES) cursor.executemany( @@ -115,6 +87,37 @@ def fxtr_group(conn_after_auth_migrations):# pylint: disable=[redefined-outer-na "DELETE FROM groups WHERE group_id=?", ((str(group.group_id),) for group in TEST_GROUPS)) + +@pytest.fixture(scope="function") +def fxtr_resource_ownership(# pylint: disable=[redefined-outer-name] + fxtr_resources, fxtr_group +): + """fixture: Set up group ownership of resources.""" + _conn, resources = fxtr_resources + conn, groups = fxtr_group + ownership = tuple({ + "group_id": str(TEST_GROUP_01.group_id), + "resource_id": str(res.resource_id) + } for res in TEST_RESOURCES_GROUP_01) + tuple({ + "group_id": str(TEST_GROUP_02.group_id), + "resource_id": str(res.resource_id) + } for res in TEST_RESOURCES_GROUP_02) + + with db.cursor(conn) as cursor: + cursor.executemany( + "INSERT INTO resource_ownership(group_id, resource_id) " + "VALUES (:group_id, :resource_id)", + ownership) + + yield conn, resources, groups, ownership + + with db.cursor(conn) as cursor: + cursor.executemany( + "DELETE FROM resource_ownership " + "WHERE group_id=:group_id AND resource_id=:resource_id", + ownership) + + @pytest.fixture(scope="function") def fxtr_users_in_group(fxtr_group, fxtr_users):# pylint: disable=[redefined-outer-name, unused-argument] """Link the users to the groups.""" @@ -134,60 +137,3 @@ def fxtr_users_in_group(fxtr_group, fxtr_users):# pylint: disable=[redefined-out cursor.executemany( "DELETE FROM group_users WHERE group_id=? AND user_id=?", query_params) - -@pytest.fixture(scope="function") -def fxtr_group_roles(fxtr_group, fxtr_roles):# pylint: disable=[redefined-outer-name,unused-argument] - """Link roles to group""" - group_roles = ( - GroupRole(uuid.UUID("9c25efb2-b477-4918-a95c-9914770cbf4d"), - TEST_GROUP_01, RESOURCE_EDITOR_ROLE), - GroupRole(uuid.UUID("82aed039-fe2f-408c-ab1e-81cd1ba96630"), - TEST_GROUP_02, RESOURCE_READER_ROLE)) - conn, groups = fxtr_group - with db.cursor(conn) as cursor: - cursor.executemany( - "INSERT INTO group_roles VALUES (?, ?, ?)", - ((str(role.group_role_id), str(role.group.group_id), - str(role.role.role_id)) - for role in group_roles)) - - yield conn, groups, group_roles - - with db.cursor(conn) as cursor: - cursor.executemany( - ("DELETE FROM group_roles " - "WHERE group_role_id=? AND group_id=? AND role_id=?"), - ((str(role.group_role_id), str(role.group.group_id), - str(role.role.role_id)) - for role in group_roles)) - -@pytest.fixture(scope="function") -def fxtr_group_user_roles(fxtr_resources, fxtr_group_roles, fxtr_users_in_group):#pylint: disable=[redefined-outer-name,unused-argument] - """Assign roles to users.""" - conn, _groups, group_roles = fxtr_group_roles - _conn, group_resources = fxtr_resources - _conn, _group, group_users = fxtr_users_in_group - users = tuple(user for user in group_users if user.email - not in ("unaff@iliated.user", "group@lead.er")) - users_roles_resources = ( - (user, RESOURCE_EDITOR_ROLE, TEST_RESOURCES_GROUP_01[1]) - for user in users if user.email == "group@mem.ber01") - with db.cursor(conn) as cursor: - params = tuple({ - "user_id": str(user.user_id), - "role_id": str(role.role_id), - "resource_id": str(resource.resource_id) - } for user, role, resource in users_roles_resources) - cursor.executemany( - ("INSERT INTO user_roles " - "VALUES (:user_id, :role_id, :resource_id)"), - params) - - yield conn, group_users, group_roles, group_resources - - with db.cursor(conn) as cursor: - cursor.executemany( - ("DELETE FROM user_roles WHERE " - "user_id=:user_id AND role_id=:role_id AND " - "resource_id=:resource_id"), - params) diff --git a/tests/unit/auth/fixtures/migration_fixtures.py b/tests/unit/auth/fixtures/migration_fixtures.py index 954b5a9..fe0ec1e 100644 --- a/tests/unit/auth/fixtures/migration_fixtures.py +++ b/tests/unit/auth/fixtures/migration_fixtures.py @@ -7,15 +7,15 @@ from yoyo.migrations import Migration, MigrationList from gn_auth.auth.db import sqlite3 as db from gn_auth.migrations import apply_migrations, rollback_migrations -@pytest.fixture(scope="session") -def auth_testdb_path(fxtr_app_config): # pylint: disable=redefined-outer-name +@pytest.fixture(scope="function") +def auth_testdb_path(fxtr_startup_configs): # pylint: disable=redefined-outer-name """Get the test application's auth database file""" - return fxtr_app_config["AUTH_DB"] + return fxtr_startup_configs["AUTH_DB"] -@pytest.fixture(scope="session") -def auth_migrations_dir(fxtr_app_config): # pylint: disable=redefined-outer-name +@pytest.fixture(scope="function") +def auth_migrations_dir(fxtr_startup_configs): # pylint: disable=redefined-outer-name """Get the test application's auth database file""" - return fxtr_app_config["AUTH_MIGRATIONS"] + return fxtr_startup_configs["AUTH_MIGRATIONS"] def apply_single_migration(backend: DatabaseBackend, migration: Migration):# pylint: disable=[redefined-outer-name] """Utility to apply a single migration""" @@ -25,16 +25,26 @@ def rollback_single_migration(backend: DatabaseBackend, migration: Migration):# """Utility to rollback a single migration""" rollback_migrations(backend, MigrationList([migration])) -@pytest.fixture(scope="session") +@pytest.fixture(scope="function") def backend(auth_testdb_path):# pylint: disable=redefined-outer-name """Fixture: retrieve yoyo backend for auth database""" return get_backend(f"sqlite:///{auth_testdb_path}") -@pytest.fixture(scope="session") +@pytest.fixture(scope="function") def all_migrations(auth_migrations_dir): # pylint: disable=redefined-outer-name """Retrieve all the migrations""" return read_migrations(auth_migrations_dir) + +@pytest.fixture(scope="function") +def fxtr_apply_all_migrations(backend, all_migrations): + """Apply all the migrations. + + Cannot use the `conn_after_auth_migrations` below due to scope mismatch. + """ + apply_migrations(backend, all_migrations) + + @pytest.fixture(scope="function") def conn_after_auth_migrations(backend, auth_testdb_path, all_migrations): # pylint: disable=redefined-outer-name """Run all migrations and return a connection to the database after""" diff --git a/tests/unit/auth/fixtures/resource_fixtures.py b/tests/unit/auth/fixtures/resource_fixtures.py index 7f3c383..b570a49 100644 --- a/tests/unit/auth/fixtures/resource_fixtures.py +++ b/tests/unit/auth/fixtures/resource_fixtures.py @@ -1,45 +1,95 @@ """Fixtures and utilities for resource-related tests""" +import uuid +import datetime + import pytest from gn_auth.auth.db import sqlite3 as db +from gn_auth.auth.authorisation.resources import Resource, ResourceCategory + +from .user_fixtures import TEST_USERS + +_created_ = datetime.datetime.now() + +SYSTEM_CATEGORY = ResourceCategory( + uuid.UUID("aa3d787f-af6a-44fa-9b0b-c82d40e54ad2"), + "system", + "The overall system.") +SYSTEM_RESOURCE = Resource( + uuid.UUID("0248b289-b277-4eaa-8c94-88a434d14b6e"), + "GeneNetwork System", + SYSTEM_CATEGORY, + True, + resource_data=tuple(), + created_by=TEST_USERS[4], + created_at=_created_) + +TEST_RESOURCES = ( + Resource(uuid.UUID("26ad1668-29f5-439d-b905-84d551f85955"), + "ResourceG01R01", + ResourceCategory(uuid.UUID("48056f84-a2a6-41ac-8319-0e1e212cba2a"), + "genotype", "Genotype Dataset"), + True, + resource_data=tuple(), + created_by=TEST_USERS[0], + created_at=_created_), + Resource(uuid.UUID("2130aec0-fefd-434d-92fd-9ca342348b2d"), + "ResourceG01R02", + ResourceCategory(uuid.UUID("548d684b-d4d1-46fb-a6d3-51a56b7da1b3"), + "phenotype", "Phenotype (Publish) Dataset"), + False, + resource_data=tuple(), + created_by=TEST_USERS[0], + created_at=_created_), + Resource(uuid.UUID("e9a1184a-e8b4-49fb-b713-8d9cbeea5b83"), + "ResourceG01R03", + ResourceCategory(uuid.UUID("fad071a3-2fc8-40b8-992b-cdefe7dcac79"), + "mrna", "mRNA Dataset"), + False, + resource_data=tuple(), + created_by=TEST_USERS[0], + created_at=_created_), + Resource(uuid.UUID("14496a1c-c234-49a2-978c-8859ea274054"), + "ResourceG02R01", + ResourceCategory(uuid.UUID("48056f84-a2a6-41ac-8319-0e1e212cba2a"), + "genotype", "Genotype Dataset"), + False, + resource_data=tuple(), + created_by=TEST_USERS[0], + created_at=_created_), + Resource(uuid.UUID("04ad9e09-94ea-4390-8a02-11f92999806b"), + "ResourceG02R02", + ResourceCategory(uuid.UUID("fad071a3-2fc8-40b8-992b-cdefe7dcac79"), + "mrna", "mRNA Dataset"), + True, + resource_data=tuple(), + created_by=TEST_USERS[0], + created_at=_created_)) + +TEST_RESOURCES_PUBLIC = (SYSTEM_RESOURCE, TEST_RESOURCES[0], TEST_RESOURCES[4]) -from .group_fixtures import ( - TEST_RESOURCES, - TEST_GROUP_01, - TEST_GROUP_02, - TEST_RESOURCES_GROUP_01, - TEST_RESOURCES_GROUP_02) @pytest.fixture(scope="function") -def fxtr_resources(fxtr_group):# pylint: disable=[redefined-outer-name] +def fxtr_resources(conn_after_auth_migrations, fxtr_users):# pylint: disable=[unused-argument] """fixture: setup test resources in the database""" - conn, _group = fxtr_group - ownership = tuple({ - "group_id": str(TEST_GROUP_01.group_id), - "resource_id": str(res.resource_id) - } for res in TEST_RESOURCES_GROUP_01) + tuple({ - "group_id": str(TEST_GROUP_02.group_id), - "resource_id": str(res.resource_id) - } for res in TEST_RESOURCES_GROUP_02) - + conn = conn_after_auth_migrations with db.cursor(conn) as cursor: cursor.executemany( - "INSERT INTO resources VALUES (?,?,?,?)", - ((str(res.resource_id), res.resource_name, - str(res.resource_category.resource_category_id), - 1 if res.public else 0) for res in TEST_RESOURCES)) - cursor.executemany( - "INSERT INTO resource_ownership(group_id, resource_id) " - "VALUES (:group_id, :resource_id)", - ownership) + "INSERT INTO resources VALUES (?,?,?,?,?,?)", + ((str(res.resource_id), res.resource_name, + str(res.resource_category.resource_category_id), + 1 if res.public else 0, + str(res.created_by.user_id), + res.created_at.timestamp()) for res in TEST_RESOURCES)) + cursor.execute( + "UPDATE resources SET created_by=?, created_at=? " + "WHERE resource_id=?", + (str(SYSTEM_RESOURCE.created_by.user_id), + SYSTEM_RESOURCE.created_at.timestamp(), + str(SYSTEM_RESOURCE.resource_id))) yield (conn, TEST_RESOURCES) with db.cursor(conn) as cursor: - cursor.executemany( - "DELETE FROM resource_ownership " - "WHERE group_id=:group_id AND resource_id=:resource_id", - ownership) cursor.executemany("DELETE FROM resources WHERE resource_id=?", - ((str(res.resource_id),) - for res in TEST_RESOURCES)) + ((str(res.resource_id),) for res in TEST_RESOURCES)) diff --git a/tests/unit/auth/fixtures/role_fixtures.py b/tests/unit/auth/fixtures/role_fixtures.py index ddcbba5..24e8e9f 100644 --- a/tests/unit/auth/fixtures/role_fixtures.py +++ b/tests/unit/auth/fixtures/role_fixtures.py @@ -7,18 +7,41 @@ from gn_auth.auth.db import sqlite3 as db from gn_auth.auth.authorisation.roles import Role from gn_auth.auth.authorisation.privileges import Privilege +from .user_fixtures import TEST_USERS +from .resource_fixtures import SYSTEM_RESOURCE, TEST_RESOURCES_PUBLIC +from .group_fixtures import ( + TEST_GROUP_01, + TEST_RESOURCES_GROUP_01, + TEST_RESOURCES_GROUP_02) + +PUBLIC_VIEW_ROLE = Role( + uuid.UUID("fd88bfed-d869-4969-87f2-67c4e8446ecb"), + "public-view", + False, + (Privilege("group:resource:view-resource", + "view a resource and use it in computations"),)) + RESOURCE_READER_ROLE = Role( - uuid.UUID("c3ca2507-ee24-4835-9b31-8c21e1c072d3"), "resource_reader", True, + uuid.UUID("c3ca2507-ee24-4835-9b31-8c21e1c072d3"), "resource_reader", + True, (Privilege("group:resource:view-resource", "view a resource and use it in computations"),)) RESOURCE_EDITOR_ROLE = Role( - uuid.UUID("89819f84-6346-488b-8955-86062e9eedb7"), "resource_editor", True, + uuid.UUID("89819f84-6346-488b-8955-86062e9eedb7"), + "resource_editor", + True, ( Privilege("group:resource:view-resource", "view a resource and use it in computations"), Privilege("group:resource:edit-resource", "edit/update a resource"))) +CREATE_GROUP_ROLE = Role( + uuid.UUID("ade7e6b0-ba9c-4b51-87d0-2af7fe39a347"), + "group-creator", + False, + (Privilege("system:group:create-group", "Create a group"),)) + TEST_ROLES = (RESOURCE_READER_ROLE, RESOURCE_EDITOR_ROLE) @pytest.fixture(scope="function") @@ -43,3 +66,145 @@ def fxtr_roles(conn_after_auth_migrations): cursor.executemany( ("DELETE FROM roles WHERE role_id=?"), ((str(role.role_id),) for role in TEST_ROLES)) + + +@pytest.fixture(scope="function") +def fxtr_resource_roles(fxtr_resources, fxtr_roles):# pylint: disable=[redefined-outer-name,unused-argument] + """Link roles to resources.""" + resource_roles = ({ + "resource_id": str(TEST_RESOURCES_GROUP_01[0].resource_id), + "role_created_by": "ecb52977-3004-469e-9428-2a1856725c7f", + "role_id": str(RESOURCE_EDITOR_ROLE.role_id) + },{ + "resource_id": str(TEST_RESOURCES_GROUP_01[0].resource_id), + "role_created_by": "ecb52977-3004-469e-9428-2a1856725c7f", + "role_id": str(RESOURCE_READER_ROLE.role_id) + }, { + "resource_id": str(TEST_RESOURCES_GROUP_02[1].resource_id), + "role_created_by": "ecb52977-3004-469e-9428-2a1856725c7f", + "role_id": str(RESOURCE_EDITOR_ROLE.role_id) + },{ + "resource_id": str(TEST_RESOURCES_GROUP_02[1].resource_id), + "role_created_by": "ecb52977-3004-469e-9428-2a1856725c7f", + "role_id": str(RESOURCE_READER_ROLE.role_id) + }) + + conn, resources = fxtr_resources + with db.cursor(conn) as cursor: + cursor.executemany( + "INSERT INTO resource_roles(resource_id, role_created_by, role_id) " + "VALUES (:resource_id, :role_created_by, :role_id)", + resource_roles) + + yield conn, resources, resource_roles + + with db.cursor(conn) as cursor: + cursor.executemany( + ("DELETE FROM resource_roles " + "WHERE resource_id=:resource_id " + "AND role_created_by=:role_created_by " + "AND role_id=:role_id"), + resource_roles) + + +@pytest.fixture(scope="function") +def fxtr_setup_group_leaders(fxtr_users, fxtr_group):# pylint: disable=[unused-argument] + """Define what roles users have that target resources of type 'Group'.""" + conn, users = fxtr_users + with db.cursor(conn) as cursor: + cursor.execute("SELECT * FROM group_resources") + g01res_id = { + row["group_id"]: row["resource_id"] + for row in cursor.fetchall() + }[str(TEST_GROUP_01.group_id)] + test_user_roles = ({ + "user_id": "ecb52977-3004-469e-9428-2a1856725c7f", + "role_id": "a0e67630-d502-4b9f-b23f-6805d0f30e30",# group-leader + "resource_id": g01res_id + },) + cursor.executemany( + "INSERT INTO user_roles(user_id, role_id, resource_id) " + "VALUES (:user_id, :role_id, :resource_id)", + test_user_roles) + + yield conn, users + + with db.cursor(conn) as cursor: + cursor.executemany( + "DELETE FROM user_roles WHERE user_id=:user_id " + "AND role_id=:role_id AND resource_id=:resource_id", + test_user_roles) + + +@pytest.fixture(scope="function") +def fxtr_system_roles(fxtr_users): + """Define what roles users have that target resources of type 'Group'.""" + conn, users = fxtr_users + with db.cursor(conn) as cursor: + cursor.execute("SELECT * FROM resources WHERE resource_name='GeneNetwork System'") + sysres_id = cursor.fetchone()["resource_id"] + test_user_roles = tuple({ + "user_id": str(user.user_id), + "role_id": str(PUBLIC_VIEW_ROLE.role_id), + "resource_id": sysres_id + } for user in TEST_USERS) + cursor.executemany( + "INSERT INTO user_roles(user_id, role_id, resource_id) " + "VALUES (:user_id, :role_id, :resource_id)", + test_user_roles) + + yield conn, users + + with db.cursor(conn) as cursor: + cursor.executemany( + "DELETE FROM user_roles WHERE user_id=:user_id " + "AND role_id=:role_id AND resource_id=:resource_id", + test_user_roles) + + +@pytest.fixture(scope="function") +def fxtr_resource_user_roles(# pylint: disable=[too-many-arguments, too-many-locals, too-many-positional-arguments] + fxtr_resources, + fxtr_users_in_group, + fxtr_resource_ownership, + fxtr_resource_roles, + fxtr_setup_group_leaders, + fxtr_system_roles +):#pylint: disable=[redefined-outer-name,unused-argument] + """Assign roles to users.""" + _conn, group_resources = fxtr_resources + _conn, _resources, _groups, group_resources = fxtr_resource_ownership + _conn, _group, group_users = fxtr_users_in_group + conn, _groups, resource_roles = fxtr_resource_roles + + users_roles_resources = ( + # Give access to group leader to all resources in their group + tuple((TEST_USERS[0], RESOURCE_EDITOR_ROLE, resource) + for resource in TEST_RESOURCES_GROUP_01) + # Set group member as resource editor + + ((TEST_USERS[1], RESOURCE_EDITOR_ROLE, TEST_RESOURCES_GROUP_01[1]),) + # Set group-creator role on the unaffiliated user + + ((TEST_USERS[3], CREATE_GROUP_ROLE, SYSTEM_RESOURCE),) + # Set roles for public resources + + tuple( + (user, PUBLIC_VIEW_ROLE, resource) + for user in TEST_USERS for resource in TEST_RESOURCES_PUBLIC[1:])) + with db.cursor(conn) as cursor: + params = tuple({ + "user_id": str(user.user_id), + "role_id": str(role.role_id), + "resource_id": str(resource.resource_id) + } for user, role, resource in users_roles_resources) + cursor.executemany( + ("INSERT INTO user_roles " + "VALUES (:user_id, :role_id, :resource_id)"), + params) + + yield conn, group_users, resource_roles, group_resources + + with db.cursor(conn) as cursor: + cursor.executemany( + ("DELETE FROM user_roles WHERE " + "user_id=:user_id AND role_id=:role_id AND " + "resource_id=:resource_id"), + params) diff --git a/tests/unit/auth/fixtures/user_fixtures.py b/tests/unit/auth/fixtures/user_fixtures.py index b88d78a..dfb37ef 100644 --- a/tests/unit/auth/fixtures/user_fixtures.py +++ b/tests/unit/auth/fixtures/user_fixtures.py @@ -1,53 +1,62 @@ """Fixtures and utilities for user-related tests""" import uuid +import datetime import pytest from gn_auth.auth.db import sqlite3 as db from gn_auth.auth.authentication.users import User, hash_password -from .group_fixtures import TEST_GROUP_01 +_created_ = datetime.datetime.now() TEST_USERS = ( User(uuid.UUID("ecb52977-3004-469e-9428-2a1856725c7f"), "group@lead.er", - "Group Leader"), + "Group Leader", created=_created_), User(uuid.UUID("21351b66-8aad-475b-84ac-53ce528451e3"), - "group@mem.ber01", "Group Member 01"), + "group@mem.ber01", "Group Member 01", created=_created_), User(uuid.UUID("ae9c6245-0966-41a5-9a5e-20885a96bea7"), - "group@mem.ber02", "Group Member 02"), + "group@mem.ber02", "Group Member 02", created=_created_), User(uuid.UUID("9a0c7ce5-2f40-4e78-979e-bf3527a59579"), - "unaff@iliated.user", "Unaffiliated User")) + "unaff@iliated.user", "Unaffiliated User", created=_created_), + User(uuid.UUID("60faf8a7-832b-471e-b6a0-bd4013f1fa0e"), + "sys@admin.user", "System Admin User", created=_created_)) @pytest.fixture(scope="function") -def fxtr_users(conn_after_auth_migrations, fxtr_group):# pylint: disable=[redefined-outer-name, unused-argument] +def fxtr_basic_setup(auth_testdb_path, fxtr_apply_all_migrations):# pylint: disable=[redefined-outer-name, unused-argument] + admin = User(uuid.UUID("0cb7b0b5-bac4-4359-9ef1-e79c33e5be2a"), + "default@system.admin", "Default System Administrator", + datetime.datetime.fromtimestamp(1691130509.0)) + with (db.connection(auth_testdb_path) as conn, db.cursor(conn) as cursor): + cursor.execute("SELECT resource_id FROM resources " + "WHERE resource_name='GeneNetwork System'") + resource_id = cursor.fetchone()[0] + cursor.execute( + "SELECT role_id FROM roles WHERE role_name='system-administrator'") + role_id = cursor.fetchone()[0] + + cursor.execute("INSERT INTO users VALUES (?, ?, ?, ?, ?)", + (str(admin.user_id), + admin.email, + admin.name, + admin.created.timestamp(), + 1)) + cursor.execute("UPDATE resources SET created_by=?", + (str(admin.user_id),)) + cursor.execute("INSERT INTO user_roles VALUES (?,?,?)", + (str(admin.user_id), role_id, resource_id)) + + yield (admin,) + + +@pytest.fixture(scope="function") +def fxtr_users(conn_after_auth_migrations):# pylint: disable=[redefined-outer-name, unused-argument] """Fixture: setup test users.""" - query = "INSERT INTO users(user_id, email, name) VALUES (?, ?, ?)" + query = ( + "INSERT INTO users(user_id, email, name, created) VALUES (?, ?, ?, ?)") with db.cursor(conn_after_auth_migrations) as cursor: cursor.executemany(query, ( - (str(user.user_id), user.email, user.name) for user in TEST_USERS)) - # setup user roles - cursor.execute("SELECT * FROM group_resources") - g01res_id = { - row["group_id"]: row["resource_id"] - for row in cursor.fetchall() - }[str(TEST_GROUP_01.group_id)] - cursor.execute("SELECT * FROM resources WHERE resource_name='GeneNetwork System'") - sysres_id = cursor.fetchone()["resource_id"] - test_user_roles = ( - { - "user_id": "ecb52977-3004-469e-9428-2a1856725c7f", - "role_id": "a0e67630-d502-4b9f-b23f-6805d0f30e30",# group-leader - "resource_id": g01res_id - }, - { - "user_id": "ecb52977-3004-469e-9428-2a1856725c7f", - "role_id": "ade7e6b0-ba9c-4b51-87d0-2af7fe39a347",# group-creator - "resource_id": sysres_id - }) - cursor.executemany( - "INSERT INTO user_roles(user_id, role_id, resource_id) " - "VALUES (:user_id, :role_id, :resource_id)", - test_user_roles) + (str(user.user_id), user.email, user.name, user.created.timestamp()) + for user in TEST_USERS)) yield (conn_after_auth_migrations, TEST_USERS) diff --git a/tests/unit/auth/test_admin_user_roles.py b/tests/unit/auth/test_admin_user_roles.py new file mode 100644 index 0000000..1fc4e14 --- /dev/null +++ b/tests/unit/auth/test_admin_user_roles.py @@ -0,0 +1,254 @@ +"""Tests for admin role-assignment HTTP endpoints.""" +import pytest + +from gn_auth.auth.db import sqlite3 as db +from gn_auth.auth.authorisation.roles.models import assign_user_role_by_name + +from tests.unit.auth import conftest +from tests.unit.auth.fixtures.resource_fixtures import SYSTEM_RESOURCE + +# Body used in all role-assign tests — assigning system-administrator on the +# system resource is a real, migrations-seeded combination. +_ASSIGN_BODY = { + "role_name": "system-administrator", + "resource_id": str(SYSTEM_RESOURCE.resource_id) +} + +# Target user for assignment: unaff@iliated.user (no roles initially) +_TARGET_USER = conftest.TEST_USERS[3] + + +def _setup_admin_mock(conn, clients, mocker): + """Grant resource-owner role on SYSTEM_RESOURCE and mock the token. + + resource-owner carries resource:user:assign-role, which is what the + endpoint checks. In production the caller would masquerade as the + resource owner; here we grant the role directly for test setup. + """ + admin = conftest.TEST_USERS[4] + with db.cursor(conn) as cursor: + assign_user_role_by_name( + cursor, admin, SYSTEM_RESOURCE.resource_id, "resource-owner") + mocker.patch( + "gn_auth.auth.authorisation.users.views.require_oauth.acquire", + conftest.get_tokeniser( + admin, + tuple(c for c in clients if c.user == admin)[0])) + return admin + + +@pytest.mark.unit_test +def test_assign_role_no_token_returns_401(client): + """ + GIVEN: no Authorization header + WHEN: POST /auth/user/<uid>/roles/assign + THEN: 401 is returned + """ + res = client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/assign", + json=_ASSIGN_BODY) + assert res.status_code == 401 + + +@pytest.mark.unit_test +def test_assign_role_non_admin_returns_403(client, mocker, fxtr_oauth2_clients): + """ + GIVEN: a valid token belonging to a non-admin user + WHEN: POST /auth/user/<uid>/roles/assign + THEN: 403 is returned + """ + _conn, clients = fxtr_oauth2_clients + user = conftest.TEST_USERS[3] # unaff@iliated.user — no privileges + mocker.patch( + "gn_auth.auth.authorisation.users.views.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(c for c in clients if c.user == user)[0])) + res = client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/assign", + json=_ASSIGN_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) + assert res.status_code == 403 + + +def _revoke_assigned_role(conn): + """Remove the role row written by the success tests. + + Keeps the DB in the state the fixtures expect — no user_roles entry for + _TARGET_USER — so teardown and any subsequent queries are not surprised. + """ + with db.cursor(conn) as cursor: + cursor.execute( + "DELETE FROM user_roles " + "WHERE user_id=? " + "AND role_id=(SELECT role_id FROM roles WHERE role_name=?) " + "AND resource_id=?", + (str(_TARGET_USER.user_id), + _ASSIGN_BODY["role_name"], + _ASSIGN_BODY["resource_id"])) + + +@pytest.mark.unit_test +def test_assign_role_admin_returns_200(client, mocker, fxtr_oauth2_clients): + """ + GIVEN: a valid system-admin token and a valid role/resource body + WHEN: POST /auth/user/<uid>/roles/assign + THEN: 200 is returned + """ + conn, clients = fxtr_oauth2_clients + _setup_admin_mock(conn, clients, mocker) + try: + res = client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/assign", + json=_ASSIGN_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) + assert res.status_code == 200 + finally: + _revoke_assigned_role(conn) + + +def _assign_target_role(conn): + """Pre-assign system-administrator to _TARGET_USER on SYSTEM_RESOURCE. + + Required setup for revoke tests: the endpoint can only revoke what exists. + """ + with db.cursor(conn) as cursor: + assign_user_role_by_name( + cursor, _TARGET_USER, SYSTEM_RESOURCE.resource_id, + _ASSIGN_BODY["role_name"]) + + +def _cleanup_target_role(conn): + """Remove _TARGET_USER's system-administrator row if still present. + + No-op when the revoke endpoint already deleted it; guards against + test failures that leave the DB dirty. + """ + with db.cursor(conn) as cursor: + cursor.execute( + "DELETE FROM user_roles " + "WHERE user_id=? " + "AND role_id=(SELECT role_id FROM roles WHERE role_name=?) " + "AND resource_id=?", + (str(_TARGET_USER.user_id), + _ASSIGN_BODY["role_name"], + _ASSIGN_BODY["resource_id"])) + + +@pytest.mark.unit_test +def test_assign_role_persists_to_db(client, mocker, fxtr_oauth2_clients): + """ + GIVEN: a valid system-admin token and a valid role/resource body + WHEN: POST /auth/user/<uid>/roles/assign + THEN: the user_roles row is present in the DB for that user/role/resource + """ + conn, clients = fxtr_oauth2_clients + _setup_admin_mock(conn, clients, mocker) + try: + client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/assign", + json=_ASSIGN_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) + with db.cursor(conn) as cursor: + cursor.execute( + "SELECT COUNT(*) AS cnt FROM user_roles " + "INNER JOIN roles ON user_roles.role_id=roles.role_id " + "WHERE user_roles.user_id=? " + "AND roles.role_name=? " + "AND user_roles.resource_id=?", + (str(_TARGET_USER.user_id), + _ASSIGN_BODY["role_name"], + _ASSIGN_BODY["resource_id"])) + assert cursor.fetchone()["cnt"] == 1 + finally: + _revoke_assigned_role(conn) + + +# --------------------------------------------------------------------------- +# HTTP endpoint tests: POST /auth/user/<uid>/roles/revoke +# --------------------------------------------------------------------------- + +@pytest.mark.unit_test +def test_revoke_role_no_token_returns_401(client): + """ + GIVEN: no Authorization header + WHEN: POST /auth/user/<uid>/roles/revoke + THEN: 401 is returned + """ + res = client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/revoke", + json=_ASSIGN_BODY) + assert res.status_code == 401 + + +@pytest.mark.unit_test +def test_revoke_role_non_admin_returns_403(client, mocker, fxtr_oauth2_clients): + """ + GIVEN: a valid token belonging to a non-admin user + WHEN: POST /auth/user/<uid>/roles/revoke + THEN: 403 is returned + """ + _conn, clients = fxtr_oauth2_clients + user = conftest.TEST_USERS[3] # unaff@iliated.user — no privileges + mocker.patch( + "gn_auth.auth.authorisation.users.views.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(c for c in clients if c.user == user)[0])) + res = client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/revoke", + json=_ASSIGN_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) + assert res.status_code == 403 + + +@pytest.mark.unit_test +def test_revoke_role_admin_returns_200(mocker, client, fxtr_oauth2_clients): + """ + GIVEN: a valid token with resource:user:assign-role and the target user + holds the role on the resource + WHEN: POST /auth/user/<uid>/roles/revoke + THEN: 200 is returned + """ + conn, clients = fxtr_oauth2_clients + _setup_admin_mock(conn, clients, mocker) + _assign_target_role(conn) + try: + res = client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/revoke", + json=_ASSIGN_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) + assert res.status_code == 200 + finally: + _cleanup_target_role(conn) + + +@pytest.mark.unit_test +def test_revoke_role_removes_from_db(client, mocker, fxtr_oauth2_clients): + """ + GIVEN: a valid token with resource:user:assign-role and the target user + holds the role on the resource + WHEN: POST /auth/user/<uid>/roles/revoke + THEN: the user_roles row is absent from the DB + """ + conn, clients = fxtr_oauth2_clients + _setup_admin_mock(conn, clients, mocker) + _assign_target_role(conn) + try: + client.post( + f"/auth/user/{_TARGET_USER.user_id}/roles/revoke", + json=_ASSIGN_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) + with db.cursor(conn) as cursor: + cursor.execute( + "SELECT COUNT(*) AS cnt FROM user_roles " + "INNER JOIN roles ON user_roles.role_id=roles.role_id " + "WHERE user_roles.user_id=? " + "AND roles.role_name=? " + "AND user_roles.resource_id=?", + (str(_TARGET_USER.user_id), + _ASSIGN_BODY["role_name"], + _ASSIGN_BODY["resource_id"])) + assert cursor.fetchone()["cnt"] == 0 + finally: + _cleanup_target_role(conn) diff --git a/tests/unit/auth/test_admin_users.py b/tests/unit/auth/test_admin_users.py new file mode 100644 index 0000000..eaa5bcd --- /dev/null +++ b/tests/unit/auth/test_admin_users.py @@ -0,0 +1,190 @@ +"""Tests for admin user-management: model functions and HTTP endpoints.""" +import pytest + +from gn_auth.auth.db import sqlite3 as db +from gn_auth.auth.authorisation.users.admin.models import ( + create_verified_user, + grant_sysadmin_role) + +from tests.unit.auth import conftest + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _credential_count(conn, user_id: str) -> int: + with db.cursor(conn) as cursor: + cursor.execute( + "SELECT COUNT(*) AS cnt FROM user_credentials WHERE user_id=?", + (user_id,)) + return cursor.fetchone()["cnt"] + + +@pytest.mark.unit_test +def test_create_verified_user_sets_verified_flag(conn_after_auth_migrations): + """ + GIVEN: a database with migrations applied + WHEN: create_verified_user is called with valid email, name and password + THEN: the returned user has verified=True and the flag is persisted in the DB + """ + conn = conn_after_auth_migrations + user = create_verified_user(conn, "new@example.org", "New User", "s3cr3t") + assert user.verified is True + with db.cursor(conn) as cursor: + cursor.execute( + "SELECT verified FROM users WHERE user_id=?", (str(user.user_id),)) + row = cursor.fetchone() + assert row is not None + assert bool(row["verified"]) is True + + +@pytest.mark.unit_test +def test_create_verified_user_has_no_roles(conn_after_auth_migrations): + """ + GIVEN: a database with migrations applied + WHEN: create_verified_user is called with valid email, name and password + THEN: the new user is assigned no roles + """ + conn = conn_after_auth_migrations + user = create_verified_user(conn, "noroles@example.org", "No Roles User", "s3cr3t") + with db.cursor(conn) as cursor: + cursor.execute( + "SELECT COUNT(*) AS cnt FROM user_roles WHERE user_id=?", + (str(user.user_id),)) + row = cursor.fetchone() + assert row["cnt"] == 0 + + +@pytest.mark.unit_test +def test_create_verified_user_stores_credentials(conn_after_auth_migrations): + """ + GIVEN: a database with migrations applied + WHEN: create_verified_user is called with valid email, name and password + THEN: a password credential row is stored for the new user + """ + conn = conn_after_auth_migrations + user = create_verified_user(conn, "creds@example.org", "Creds User", "s3cr3t") + assert _credential_count(conn, str(user.user_id)) == 1 + + +@pytest.mark.unit_test +def test_create_verified_user_raises_on_duplicate_email(conn_after_auth_migrations): + """ + GIVEN: a user already exists with a given email + WHEN: create_verified_user is called with the same email + THEN: an exception is raised + """ + conn = conn_after_auth_migrations + create_verified_user(conn, "dupe@example.org", "First User", "s3cr3t") + with pytest.raises(Exception): + create_verified_user(conn, "dupe@example.org", "Second User", "s3cr3t") + + +# --------------------------------------------------------------------------- +# HTTP endpoint tests: POST /auth/system/administration/users/create +# --------------------------------------------------------------------------- + +_NEW_USER_BODY = {"email": "newbie@example.org", "name": "Newbie", "password": "s3cr3t"} +_CREATE_URL = "/auth/system/administration/users/create" + + +@pytest.mark.unit_test +def test_create_user_endpoint_no_token_returns_401(fxtr_app): + """ + GIVEN: no Authorization header + WHEN: POST /auth/system/administration/users/create + THEN: 401 is returned + """ + with fxtr_app.test_client() as http: + res = http.post(_CREATE_URL, json=_NEW_USER_BODY) + assert res.status_code == 401 + + +@pytest.mark.unit_test +def test_create_user_endpoint_non_admin_returns_403(fxtr_app, mocker, fxtr_oauth2_clients): + """ + GIVEN: a valid token belonging to a non-admin user + WHEN: POST /auth/system/administration/users/create + THEN: 403 is returned + """ + _conn, clients = fxtr_oauth2_clients + user = conftest.TEST_USERS[3] # unaff@iliated.user — no privileges + mocker.patch( + "gn_auth.auth.system.admin.users.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(c for c in clients if c.user == user)[0])) + with fxtr_app.test_client() as http: + res = http.post( + _CREATE_URL, + json=_NEW_USER_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) + assert res.status_code == 403 + + +def _setup_admin_mock(conn, clients, mocker): + """Grant sysadmin role and mock the token for sys@admin.user.""" + admin = conftest.TEST_USERS[4] + with db.cursor(conn) as cursor: + grant_sysadmin_role(cursor, admin) + mocker.patch( + "gn_auth.auth.system.admin.users.require_oauth.acquire", + conftest.get_tokeniser( + admin, + tuple(c for c in clients if c.user == admin)[0])) + return admin + + +@pytest.mark.unit_test +def test_create_user_endpoint_admin_returns_201(fxtr_app, mocker, fxtr_oauth2_clients): + """ + GIVEN: a valid system-admin token and a valid request body + WHEN: POST /auth/system/administration/users/create + THEN: 201 is returned + """ + conn, clients = fxtr_oauth2_clients + _setup_admin_mock(conn, clients, mocker) + with fxtr_app.test_client() as http: + res = http.post( + _CREATE_URL, + json={**_NEW_USER_BODY, "password": "s3cr3tP4ssw0rd"}, + headers={"Authorization": "Bearer some-mocked-token"}) + assert res.status_code == 201 + + +@pytest.mark.unit_test +def test_create_user_endpoint_admin_returns_new_user(fxtr_app, mocker, fxtr_oauth2_clients): + """ + GIVEN: a valid system-admin token and a valid request body + WHEN: POST /auth/system/administration/users/create + THEN: the response body contains the new user's email and name + """ + conn, clients = fxtr_oauth2_clients + _setup_admin_mock(conn, clients, mocker) + with fxtr_app.test_client() as http: + res = http.post( + _CREATE_URL, + json={**_NEW_USER_BODY, "password": "s3cr3tP4ssw0rd"}, + headers={"Authorization": "Bearer some-mocked-token"}) + data = res.get_json() + assert data.get("email") == _NEW_USER_BODY["email"] + assert data.get("name") == _NEW_USER_BODY["name"] + assert res.status_code == 201 + + +@pytest.mark.unit_test +def test_create_user_endpoint_short_password_returns_400( + fxtr_app, mocker, fxtr_oauth2_clients): + """ + GIVEN: a valid system-admin token and a request body with a short password + WHEN: POST /auth/system/administration/users/create + THEN: 400 is returned (password must be at least 8 characters) + """ + conn, clients = fxtr_oauth2_clients + _setup_admin_mock(conn, clients, mocker) + with fxtr_app.test_client() as http: + res = http.post( + _CREATE_URL, + json={**_NEW_USER_BODY, "password": "short"}, + headers={"Authorization": "Bearer some-mocked-token"}) + assert res.status_code == 400 diff --git a/tests/unit/auth/test_groups.py b/tests/unit/auth/test_groups.py index c9d8b19..93c5af3 100644 --- a/tests/unit/auth/test_groups.py +++ b/tests/unit/auth/test_groups.py @@ -6,11 +6,9 @@ from pymonad.maybe import Nothing from gn_auth.auth.db import sqlite3 as db from gn_auth.auth.errors import AuthorisationError -from gn_auth.auth.authentication.users import User -from gn_auth.auth.authorisation.roles import Role from gn_auth.auth.authorisation.privileges import Privilege from gn_auth.auth.authorisation.resources.groups.models import ( - Group, GroupRole, user_group, create_group, create_group_role) + Group, user_group, create_group, create_group_role) from tests.unit.auth import conftest @@ -27,41 +25,100 @@ PRIVILEGES = ( "view a resource and use it in computations"), Privilege("group:resource:edit-resource", "edit/update a resource")) + +@pytest.mark.unit_test +@pytest.mark.parametrize("user", tuple(conftest.TEST_USERS[0:3])) +def test_create_group_fails(# pylint: disable=[too-many-arguments too-many-positional-arguments] + client, auth_testdb_path, mocker, fxtr_resource_user_roles, fxtr_oauth2_clients, user):# pylint: disable=[unused-argument] + """ + GIVEN: an authenticated user + WHEN: the user attempts to create a group + THEN: verify they are only able to create the group if they have the + appropriate privileges + """ + _conn, clients = fxtr_oauth2_clients + mocker.patch("gn_auth.auth.authorisation.resources.groups.models.uuid4", conftest.uuid_fn) + mocker.patch( + "gn_auth.auth.authorisation.checks.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(client for client in clients if client.user == user)[0])) + with db.connection(auth_testdb_path) as conn: + with pytest.raises(AuthorisationError): + create_group(conn, "a_test_group", user, "A test group") + + +def __cleanup_create_group__(conn, user, group): + """Cleanup creating a group...""" + # cleanup: This should probably go into a 'delete_group(…) function' + with db.cursor(conn) as cursor: + cursor.execute("DELETE FROM group_users WHERE group_id=? AND user_id=?", + (str(group.group_id), str(user.user_id))) + cursor.execute("SELECT * FROM group_resources WHERE group_id=?", + (str(group.group_id),)) + grp_rsc = cursor.fetchone() + cursor.execute( + "DELETE FROM user_roles WHERE user_id=? AND resource_id=?", + (str(user.user_id), str(grp_rsc["resource_id"]))) + cursor.execute("DELETE FROM group_resources WHERE group_id=?", + (str(group.group_id),)) + cursor.execute("DELETE FROM resources WHERE resource_id=?", + (grp_rsc["resource_id"],)) + cursor.execute("DELETE FROM groups WHERE group_id=?", + (str(group.group_id),)) + + @pytest.mark.unit_test @pytest.mark.parametrize( - "user,expected", tuple(zip(conftest.TEST_USERS[0:1], ( - Group( - UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"), "a_test_group", - {"group_description": "A test group"}), - create_group_failure, create_group_failure, create_group_failure, - create_group_failure)))) -def test_create_group(# pylint: disable=[too-many-arguments] - fxtr_app, auth_testdb_path, mocker, fxtr_users, user, expected):# pylint: disable=[unused-argument] + "user,expected", + ((conftest.TEST_USERS[3], Group( + UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"), "a_test_group", + {"group_description": "A test group"})),)) +def test_create_group_succeeds(# pylint: disable=[too-many-arguments too-many-positional-arguments, unused-argument] + client, + auth_testdb_path, + mocker, + fxtr_resource_user_roles, + fxtr_oauth2_clients, + user, + expected +): """ GIVEN: an authenticated user WHEN: the user attempts to create a group THEN: verify they are only able to create the group if they have the appropriate privileges """ + _conn, clients = fxtr_oauth2_clients mocker.patch("gn_auth.auth.authorisation.resources.groups.models.uuid4", conftest.uuid_fn) - mocker.patch("gn_auth.auth.authorisation.checks.require_oauth.acquire", - conftest.get_tokeniser(user)) + mocker.patch( + "gn_auth.auth.authorisation.checks.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(client for client in clients if client.user == user)[0])) with db.connection(auth_testdb_path) as conn: - assert create_group( - conn, "a_test_group", user, "A test group") == expected + created_group = create_group( + conn, "a_test_group", user, "A test group") + assert created_group == expected + __cleanup_create_group__(conn, user, created_group) + @pytest.mark.unit_test @pytest.mark.parametrize("user", conftest.TEST_USERS[1:]) -def test_create_group_raises_exception_with_non_privileged_user(# pylint: disable=[too-many-arguments] - fxtr_app, auth_testdb_path, mocker, fxtr_users, user):# pylint: disable=[unused-argument] +def test_create_group_raises_exception_with_non_privileged_user(# pylint: disable=[too-many-arguments too-many-positional-arguments] + client, auth_testdb_path, mocker, fxtr_users, fxtr_oauth2_clients, user):# pylint: disable=[unused-argument] """ GIVEN: an authenticated user, without appropriate privileges WHEN: the user attempts to create a group THEN: verify the system raises an exception """ + _conn, clients = fxtr_oauth2_clients mocker.patch("gn_auth.auth.authorisation.resources.groups.models.uuid4", conftest.uuid_fn) - mocker.patch("gn_auth.auth.authorisation.checks.require_oauth.acquire", - conftest.get_tokeniser(user)) + mocker.patch( + "gn_auth.auth.authorisation.checks.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(client for client in clients if client.user == user)[0])) with db.connection(auth_testdb_path) as conn: with pytest.raises(AuthorisationError): assert create_group(conn, "a_test_group", user, "A test group") @@ -71,58 +128,35 @@ create_role_failure = { "message": "Unauthorised: Could not create the group role" } -@pytest.mark.unit_test -@pytest.mark.parametrize( - "user,expected", tuple(zip(conftest.TEST_USERS[0:1], ( - GroupRole( - UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"), - GROUP, - Role(UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"), - "ResourceEditor", True, PRIVILEGES)),)))) -def test_create_group_role(mocker, fxtr_users_in_group, user, expected): - """ - GIVEN: an authenticated user - WHEN: the user attempts to create a role, attached to a group - THEN: verify they are only able to create the role if they have the - appropriate privileges and that the role is attached to the given group - """ - mocker.patch("gn_auth.auth.authorisation.resources.groups.models.uuid4", conftest.uuid_fn) - mocker.patch("gn_auth.auth.authorisation.roles.models.uuid4", conftest.uuid_fn) - mocker.patch("gn_auth.auth.authorisation.checks.require_oauth.acquire", - conftest.get_tokeniser(user)) - conn, _group, _users = fxtr_users_in_group - with db.cursor(conn) as cursor: - assert create_group_role( - conn, GROUP, "ResourceEditor", PRIVILEGES) == expected - # cleanup - cursor.execute( - ("DELETE FROM group_roles " - "WHERE group_role_id=? AND group_id=? AND role_id=?"), - (str(conftest.uuid_fn()), str(GROUP.group_id), str(conftest.uuid_fn()))) @pytest.mark.unit_test @pytest.mark.parametrize( "user,expected", tuple(zip(conftest.TEST_USERS[1:], ( create_role_failure, create_role_failure, create_role_failure)))) def test_create_group_role_raises_exception_with_unauthorised_users( - mocker, fxtr_users_in_group, user, expected): + mocker, client, fxtr_users_in_group, fxtr_oauth2_clients, user, expected): """ GIVEN: an authenticated user WHEN: the user attempts to create a role, attached to a group THEN: verify they are only able to create the role if they have the appropriate privileges and that the role is attached to the given group """ + _conn, clients = fxtr_oauth2_clients mocker.patch("gn_auth.auth.authorisation.resources.groups.models.uuid4", conftest.uuid_fn) mocker.patch("gn_auth.auth.authorisation.roles.models.uuid4", conftest.uuid_fn) - mocker.patch("gn_auth.auth.authorisation.checks.require_oauth.acquire", - conftest.get_tokeniser(user)) + mocker.patch( + "gn_auth.auth.authorisation.checks.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(client for client in clients if client.user == user)[0])) conn, _group, _users = fxtr_users_in_group with pytest.raises(AuthorisationError): assert create_group_role( conn, GROUP, "ResourceEditor", PRIVILEGES) == expected + @pytest.mark.unit_test -def test_create_multiple_groups(mocker, fxtr_users): +def test_create_multiple_groups(mocker, client, fxtr_resource_user_roles, fxtr_oauth2_clients): """ GIVEN: An authenticated user with appropriate authorisation WHEN: The user attempts to create a new group, while being a member of an @@ -130,21 +164,27 @@ def test_create_multiple_groups(mocker, fxtr_users): THEN: The system should prevent that, and respond with an appropriate error message """ + _conn, clients = fxtr_oauth2_clients mocker.patch("gn_auth.auth.authorisation.resources.groups.models.uuid4", conftest.uuid_fn) - user = User( - UUID("ecb52977-3004-469e-9428-2a1856725c7f"), "group@lead.er", - "Group Leader") - mocker.patch("gn_auth.auth.authorisation.checks.require_oauth.acquire", - conftest.get_tokeniser(user)) - conn, _test_users = fxtr_users + user = conftest.TEST_USERS[3] + mocker.patch( + "gn_auth.auth.authorisation.checks.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(client for client in clients if client.user == user)[0])) + conn, *_test_users = fxtr_resource_user_roles # First time, successfully creates the group - assert create_group(conn, "a_test_group", user) == Group( + created_group = create_group(conn, "a_test_group", user) + assert created_group == Group( UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"), "a_test_group", {}) # subsequent attempts should fail with pytest.raises(AuthorisationError): create_group(conn, "another_test_group", user) + __cleanup_create_group__(conn, user, created_group) + + @pytest.mark.unit_test @pytest.mark.parametrize( "user,expected", diff --git a/tests/unit/auth/test_migrations_add_data_to_table.py b/tests/unit/auth/test_migrations_add_data_to_table.py index d9e2ca4..0945a20 100644 --- a/tests/unit/auth/test_migrations_add_data_to_table.py +++ b/tests/unit/auth/test_migrations_add_data_to_table.py @@ -40,7 +40,7 @@ test_params = ( @pytest.mark.unit_test @pytest.mark.parametrize("migration_file,query,query_params,data", test_params) -def test_apply_insert(# pylint: disable=[too-many-arguments] +def test_apply_insert(# pylint: disable=[too-many-arguments, too-many-positional-arguments] auth_migrations_dir, backend, auth_testdb_path, migration_file, query, query_params, data): """ @@ -65,7 +65,7 @@ def test_apply_insert(# pylint: disable=[too-many-arguments] @pytest.mark.unit_test @pytest.mark.parametrize("migration_file,query,query_params,data", test_params) -def test_rollback_insert(# pylint: disable=[too-many-arguments] +def test_rollback_insert(# pylint: disable=[too-many-arguments, too-many-positional-arguments] auth_migrations_dir, backend, auth_testdb_path, migration_file, query, query_params, data): """ diff --git a/tests/unit/auth/test_migrations_add_remove_columns.py b/tests/unit/auth/test_migrations_add_remove_columns.py index af85652..15dc3a2 100644 --- a/tests/unit/auth/test_migrations_add_remove_columns.py +++ b/tests/unit/auth/test_migrations_add_remove_columns.py @@ -51,7 +51,7 @@ def rolled_back_successfully(adding: bool, result_str: str, column: str) -> bool @pytest.mark.unit_test @pytest.mark.parametrize( "migration_file,the_table,the_column,adding", TEST_PARAMS) -def test_apply_add_remove_column(# pylint: disable=[too-many-arguments] +def test_apply_add_remove_column(# pylint: disable=[too-many-arguments too-many-positional-arguments] auth_migrations_dir, auth_testdb_path, backend, migration_file, the_table, the_column, adding): """ @@ -84,7 +84,7 @@ def test_apply_add_remove_column(# pylint: disable=[too-many-arguments] @pytest.mark.unit_test @pytest.mark.parametrize( "migration_file,the_table,the_column,adding", TEST_PARAMS) -def test_rollback_add_remove_column(# pylint: disable=[too-many-arguments] +def test_rollback_add_remove_column(# pylint: disable=[too-many-arguments too-many-positional-arguments] auth_migrations_dir, auth_testdb_path, backend, migration_file, the_table, the_column, adding): """ diff --git a/tests/unit/auth/test_migrations_indexes.py b/tests/unit/auth/test_migrations_indexes.py index 1c543c4..2d0997f 100644 --- a/tests/unit/auth/test_migrations_indexes.py +++ b/tests/unit/auth/test_migrations_indexes.py @@ -30,7 +30,7 @@ migrations_tables_and_indexes = ( @pytest.mark.unit_test @pytest.mark.parametrize( "migration_file,the_table,the_index", migrations_tables_and_indexes) -def test_index_created(# pylint: disable=[too-many-arguments] +def test_index_created(# pylint: disable=[too-many-arguments too-many-positional-arguments] auth_testdb_path, auth_migrations_dir, backend, migration_file, the_table, the_index): """ @@ -61,7 +61,7 @@ def test_index_created(# pylint: disable=[too-many-arguments] @pytest.mark.unit_test @pytest.mark.parametrize( "migration_file,the_table,the_index", migrations_tables_and_indexes) -def test_index_dropped(# pylint: disable=[too-many-arguments] +def test_index_dropped(# pylint: disable=[too-many-arguments too-many-positional-arguments] auth_testdb_path, auth_migrations_dir, backend, migration_file, the_table, the_index): """ diff --git a/tests/unit/auth/test_migrations_init_data_in_resource_categories_table.py b/tests/unit/auth/test_migrations_init_data_in_resource_categories_table.py index c34a549..06f7cf3 100644 --- a/tests/unit/auth/test_migrations_init_data_in_resource_categories_table.py +++ b/tests/unit/auth/test_migrations_init_data_in_resource_categories_table.py @@ -8,7 +8,7 @@ from gn_auth.migrations import get_migration, apply_migrations, rollback_migrati from tests.unit.auth.conftest import ( apply_single_migration, rollback_single_migration, migrations_up_to) -MIGRATION_PATH = "migrations/auth/20221108_04_CKcSL-init-data-in-resource-categories-table.py" +MIGRATION_FILE = "20221108_04_CKcSL-init-data-in-resource-categories-table.py" @pytest.mark.unit_test def test_apply_init_data(auth_testdb_path, auth_migrations_dir, backend): @@ -17,8 +17,9 @@ def test_apply_init_data(auth_testdb_path, auth_migrations_dir, backend): WHEN: The migration is applied THEN: Verify that the expected data exists in the table """ - older_migrations = migrations_up_to(MIGRATION_PATH, auth_migrations_dir) - the_migration = get_migration(MIGRATION_PATH) + migration_path = f"{auth_migrations_dir}/{MIGRATION_FILE}" + older_migrations = migrations_up_to(migration_path, auth_migrations_dir) + the_migration = get_migration(migration_path) apply_migrations(backend, older_migrations) with db.connection(auth_testdb_path, None) as conn, db.cursor(conn) as cursor: cursor.execute("SELECT * FROM resource_categories") @@ -36,6 +37,7 @@ def test_apply_init_data(auth_testdb_path, auth_migrations_dir, backend): rollback_migrations(backend, older_migrations + [the_migration]) + @pytest.mark.unit_test def test_rollback_init_data(auth_testdb_path, auth_migrations_dir, backend): """ @@ -43,8 +45,9 @@ def test_rollback_init_data(auth_testdb_path, auth_migrations_dir, backend): WHEN: The migration is rolled back THEN: Verify that the table is empty """ - older_migrations = migrations_up_to(MIGRATION_PATH, auth_migrations_dir) - the_migration = get_migration(MIGRATION_PATH) + migration_path = f"{auth_migrations_dir}/{MIGRATION_FILE}" + older_migrations = migrations_up_to(migration_path, auth_migrations_dir) + the_migration = get_migration(migration_path) apply_migrations(backend, older_migrations) with db.connection(auth_testdb_path, None) as conn, db.cursor(conn) as cursor: cursor.execute("SELECT * FROM resource_categories") diff --git a/tests/unit/auth/test_migrations_insert_data_into_empty_table.py b/tests/unit/auth/test_migrations_insert_data_into_empty_table.py index 0cf9a1f..c699e81 100644 --- a/tests/unit/auth/test_migrations_insert_data_into_empty_table.py +++ b/tests/unit/auth/test_migrations_insert_data_into_empty_table.py @@ -16,7 +16,7 @@ test_params = ( @pytest.mark.unit_test @pytest.mark.parametrize( "migration_file,table,row_count", test_params) -def test_apply_insert(# pylint: disable=[too-many-arguments] +def test_apply_insert(# pylint: disable=[too-many-arguments, too-many-positional-arguments] auth_testdb_path, auth_migrations_dir, backend, migration_file, table, row_count): """ @@ -45,7 +45,7 @@ def test_apply_insert(# pylint: disable=[too-many-arguments] @pytest.mark.unit_test @pytest.mark.parametrize( "migration_file,table,row_count", test_params) -def test_rollback_insert(# pylint: disable=[too-many-arguments] +def test_rollback_insert(# pylint: disable=[too-many-arguments, too-many-positional-arguments] auth_testdb_path, auth_migrations_dir, backend, migration_file, table, row_count): """ diff --git a/tests/unit/auth/test_privileges.py b/tests/unit/auth/test_privileges.py index 0b5f120..41dae7f 100644 --- a/tests/unit/auth/test_privileges.py +++ b/tests/unit/auth/test_privileges.py @@ -11,8 +11,7 @@ def sort_key_privileges(priv): return priv.privilege_id PRIVILEGES = sorted( - (Privilege("system:group:create-group", "Create a group"), - Privilege("system:group:view-group", "View the details of a group"), + (Privilege("system:group:view-group", "View the details of a group"), Privilege("system:group:edit-group", "Edit the details of a group"), Privilege("system:user:list", "List users in the system"), Privilege("system:group:delete-group", "Delete a group"), @@ -27,17 +26,23 @@ PRIVILEGES = sorted( Privilege("group:resource:edit-resource", "edit/update a resource"), Privilege("group:resource:delete-resource", "Delete a resource"), - Privilege("group:role:create-role", "Create a new role"), - Privilege("group:role:edit-role", "edit/update an existing role"), - Privilege("group:user:assign-role", "Assign a role to an existing user"), - Privilege("group:role:delete-role", "Delete an existing role")), + Privilege("group:data:link-to-group", + "Allow linking data to only one specific group."), + + # Role-management privileges + Privilege("resource:role:create-role", + "Create a new role on a specific resource"), + Privilege("resource:role:delete-role", + "Delete an existing role from a specific resource"), + Privilege("resource:role:edit-role", + "Edit an existing role on a specific resource")), key=sort_key_privileges) @pytest.mark.unit_test @pytest.mark.parametrize( "user,expected", tuple(zip( conftest.TEST_USERS, (PRIVILEGES, [], [], [], [])))) -def test_user_privileges(auth_testdb_path, fxtr_users, user, expected):# pylint: disable=[unused-argument] +def test_user_privileges(auth_testdb_path, fxtr_setup_group_leaders, user, expected):# pylint: disable=[unused-argument] """ GIVEN: A user WHEN: An attempt is made to fetch the user's privileges diff --git a/tests/unit/auth/test_resources.py b/tests/unit/auth/test_resources.py index 85641be..23afcef 100644 --- a/tests/unit/auth/test_resources.py +++ b/tests/unit/auth/test_resources.py @@ -1,5 +1,6 @@ """Test resource-management functions""" import uuid +from datetime import datetime import pytest @@ -29,18 +30,32 @@ create_resource_failure = { conftest.TEST_USERS[0:1], (Resource( uuid.UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"), - "test_resource", resource_category, False),)))) -def test_create_resource(mocker, fxtr_users_in_group, user, expected): + "test_resource", resource_category, False, + conftest.TEST_USERS[0]),)))) +def test_create_resource(# pylint: disable=[too-many-arguments, too-many-positional-arguments, unused-argument] + mocker, + client, + fxtr_users_in_group, + fxtr_resource_user_roles, + fxtr_oauth2_clients, + user, + expected +): """Test that resource creation works as expected.""" mocker.patch("gn_auth.auth.authorisation.resources.models.uuid4", conftest.uuid_fn) - mocker.patch("gn_auth.auth.authorisation.checks.require_oauth.acquire", - conftest.get_tokeniser(user)) + _conn, clients = fxtr_oauth2_clients + mocker.patch( + "gn_auth.auth.authorisation.checks.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(client for client in clients if client.user == user)[0])) conn, _group, _users = fxtr_users_in_group - resource = create_resource( - conn, "test_resource", resource_category, user, False) - assert resource == expected with db.cursor(conn) as cursor: + resource = create_resource( + conn, "test_resource", resource_category, user, _group, False, + datetime(1970, 1, 1, 0, 0, 0)) + assert resource == expected # Cleanup cursor.execute( "DELETE FROM user_roles WHERE resource_id=?", @@ -49,9 +64,6 @@ def test_create_resource(mocker, fxtr_users_in_group, user, expected): "DELETE FROM resource_ownership WHERE resource_id=?", (str(resource.resource_id),)) cursor.execute( - "DELETE FROM group_roles WHERE group_id=?", - (str(group.group_id),)) - cursor.execute( "DELETE FROM resources WHERE resource_id=?", (str(resource.resource_id),)) @@ -63,15 +75,31 @@ def test_create_resource(mocker, fxtr_users_in_group, user, expected): (create_resource_failure, create_resource_failure, create_resource_failure)))) def test_create_resource_raises_for_unauthorised_users( - mocker, fxtr_users_in_group, user, expected): + mocker, + client, + fxtr_users_in_group, + fxtr_oauth2_clients, + user, + expected +): """Test that resource creation works as expected.""" mocker.patch("gn_auth.auth.authorisation.resources.models.uuid4", conftest.uuid_fn) - mocker.patch("gn_auth.auth.authorisation.checks.require_oauth.acquire", - conftest.get_tokeniser(user)) + _conn, clients = fxtr_oauth2_clients + mocker.patch( + "gn_auth.auth.authorisation.checks.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(client for client in clients if client.user == user)[0])) conn, _group, _users = fxtr_users_in_group with pytest.raises(AuthorisationError): assert create_resource( - conn, "test_resource", resource_category, user, False) == expected + conn, + "test_resource", + resource_category, + user, + _group, + False + ) == expected def sort_key_resources(resource): """Sort-key for resources.""" @@ -96,26 +124,30 @@ def test_public_resources(fxtr_resources): "user,expected", tuple(zip( conftest.TEST_USERS, - (sorted( + ((sorted( {res.resource_id: res for res in ((conftest.GROUP_RESOURCES[0],) + conftest.TEST_RESOURCES_GROUP_01 + conftest.TEST_RESOURCES_PUBLIC)}.values(), - key=sort_key_resources), - sorted( + key=sort_key_resources), 6), + (sorted( {res.resource_id: res for res in ((conftest.TEST_RESOURCES_GROUP_01[1],) + conftest.TEST_RESOURCES_PUBLIC)}.values() , - key=sort_key_resources), - PUBLIC_RESOURCES, PUBLIC_RESOURCES)))) -def test_user_resources(fxtr_group_user_roles, user, expected): + key=sort_key_resources), 4), + (PUBLIC_RESOURCES, 3), (PUBLIC_RESOURCES, 3))))) +def test_user_resources(fxtr_resource_user_roles, user, expected): """ GIVEN: some resources in the database WHEN: a particular user's resources are requested THEN: list only the resources for which the user can access """ - conn, *_others = fxtr_group_user_roles + conn, *_others = fxtr_resource_user_roles + uresources, count = user_resources(conn, user) + eresources, ecount = expected + assert count == ecount assert sorted( - {res.resource_id: res for res in user_resources(conn, user) - }.values(), key=sort_key_resources) == expected + {res.resource_id: res for res in uresources}.values(), + key=sort_key_resources + ) == eresources diff --git a/tests/unit/auth/test_resources_roles.py b/tests/unit/auth/test_resources_roles.py new file mode 100644 index 0000000..e43f25c --- /dev/null +++ b/tests/unit/auth/test_resources_roles.py @@ -0,0 +1,90 @@ +"""Tests for roles for a specific resource.""" +from uuid import UUID + +import pytest + +from gn_auth.auth.db import sqlite3 as db +from gn_auth.auth.authorisation.privileges import Privilege +from gn_auth.auth.authorisation.roles.models import Role, create_role +from gn_auth.auth.authorisation.resources.groups.models import ( + GroupRole, + create_group_role) + +from tests.unit.auth import conftest + + +GROUP = conftest.TEST_GROUP_01 +PRIVILEGES = ( + Privilege("group:resource:view-resource", + "view a resource and use it in computations"), + Privilege("group:resource:edit-resource", "edit/update a resource")) + + +@pytest.mark.skip("Keep as placeholder until we implement test for creating " + "a resource role.") +@pytest.mark.unit_test +@pytest.mark.parametrize( + "user,expected", tuple(zip(conftest.TEST_USERS[0:1], ( + GroupRole( + UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"), + GROUP, + Role(UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"), + "ResourceEditor", True, PRIVILEGES)),)))) +def test_create_group_role(mocker, fxtr_users_in_group, fxtr_oauth2_clients, user, expected): + """ + GIVEN: an authenticated user + WHEN: the user attempts to create a role, attached to a group + THEN: verify they are only able to create the role if they have the + appropriate privileges and that the role is attached to the given group + """ + _conn, clients = fxtr_oauth2_clients + mocker.patch("gn_auth.auth.authorisation.resources.groups.models.uuid4", conftest.uuid_fn) + mocker.patch("gn_auth.auth.authorisation.roles.models.uuid4", conftest.uuid_fn) + mocker.patch( + "gn_auth.auth.authorisation.checks.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(client for client in clients if client.user == user)[0])) + conn, _group, _users = fxtr_users_in_group + with db.cursor(conn) as cursor: + assert create_group_role( + conn, GROUP, "ResourceEditor", PRIVILEGES) == expected + # cleanup + cursor.execute( + ("DELETE FROM group_roles " + "WHERE group_role_id=? AND group_id=? AND role_id=?"), + (str(conftest.uuid_fn()), str(GROUP.group_id), str(conftest.uuid_fn()))) + + +@pytest.mark.skip( + "This needs to be replaced by tests for creation of resource roles.") +@pytest.mark.unit_test +@pytest.mark.parametrize( + "user,expected", tuple(zip(conftest.TEST_USERS[0:1], ( + Role(UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"), "a_test_role", + True, PRIVILEGES),)))) +def test_create_role(# pylint: disable=[too-many-arguments, too-many-positional-arguments, unused-argument] + fxtr_app, + auth_testdb_path, + mocker, + fxtr_users, + fxtr_oauth2_clients, + user, + expected +): + """ + GIVEN: an authenticated user + WHEN: the user attempts to create a role + THEN: verify they are only able to create the role if they have the + appropriate privileges + """ + _conn, clients = fxtr_oauth2_clients + mocker.patch("gn_auth.auth.authorisation.roles.models.uuid4", conftest.uuid_fn) + mocker.patch( + "gn_auth.auth.authorisation.checks.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(client for client in clients if client.user == user)[0])) + with db.connection(auth_testdb_path) as conn, db.cursor(conn) as cursor: + the_role = create_role(cursor, "a_test_role", PRIVILEGES) + assert the_role == expected diff --git a/tests/unit/auth/test_roles.py b/tests/unit/auth/test_roles.py index 00148a0..6f658ac 100644 --- a/tests/unit/auth/test_roles.py +++ b/tests/unit/auth/test_roles.py @@ -1,5 +1,5 @@ """Test functions dealing with group management.""" -import uuid +from uuid import UUID import pytest @@ -21,136 +21,297 @@ PRIVILEGES = ( "view a resource and use it in computations"), Privilege("group:resource:edit-resource", "edit/update a resource")) -@pytest.mark.unit_test -@pytest.mark.parametrize( - "user,expected", tuple(zip(conftest.TEST_USERS[0:1], ( - Role(uuid.UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"), "a_test_role", - True, PRIVILEGES),)))) -def test_create_role(# pylint: disable=[too-many-arguments] - fxtr_app, auth_testdb_path, mocker, fxtr_users, user, expected):# pylint: disable=[unused-argument] - """ - GIVEN: an authenticated user - WHEN: the user attempts to create a role - THEN: verify they are only able to create the role if they have the - appropriate privileges - """ - mocker.patch("gn_auth.auth.authorisation.roles.models.uuid4", conftest.uuid_fn) - mocker.patch("gn_auth.auth.authorisation.checks.require_oauth.acquire", - conftest.get_tokeniser(user)) - with db.connection(auth_testdb_path) as conn, db.cursor(conn) as cursor: - the_role = create_role(cursor, "a_test_role", PRIVILEGES) - assert the_role == expected @pytest.mark.unit_test @pytest.mark.parametrize( "user,expected", tuple(zip(conftest.TEST_USERS[1:], ( create_role_failure, create_role_failure, create_role_failure)))) -def test_create_role_raises_exception_for_unauthorised_users(# pylint: disable=[too-many-arguments] - fxtr_app, auth_testdb_path, mocker, fxtr_users, user, expected):# pylint: disable=[unused-argument] +def test_create_role_raises_exception_for_unauthorised_users(# pylint: disable=[too-many-arguments, unused-argument, too-many-positional-arguments] + client, + auth_testdb_path, + mocker, + fxtr_users, + fxtr_oauth2_clients, + user, + expected +): """ GIVEN: an authenticated user WHEN: the user attempts to create a role THEN: verify they are only able to create the role if they have the appropriate privileges """ + _conn, clients = fxtr_oauth2_clients mocker.patch("gn_auth.auth.authorisation.roles.models.uuid4", conftest.uuid_fn) - mocker.patch("gn_auth.auth.authorisation.checks.require_oauth.acquire", - conftest.get_tokeniser(user)) + mocker.patch( + "gn_auth.auth.authorisation.checks.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(client for client in clients if client.user == user)[0])) with db.connection(auth_testdb_path) as conn, db.cursor(conn) as cursor: with pytest.raises(AuthorisationError): create_role(cursor, "a_test_role", PRIVILEGES) + +# This might still be incomplete, especially regarding resource roles. @pytest.mark.unit_test @pytest.mark.parametrize( "user,expected", (zip(TEST_USERS, - (({"resource_id": uuid.UUID("38d1807d-105f-44a7-8327-7e2d973b6d8d"), - "user_id": uuid.UUID("ecb52977-3004-469e-9428-2a1856725c7f"), + (({"resource_id": UUID("2130aec0-fefd-434d-92fd-9ca342348b2d"), + "user_id": UUID("ecb52977-3004-469e-9428-2a1856725c7f"), "roles": (Role( - role_id=uuid.UUID('a0e67630-d502-4b9f-b23f-6805d0f30e30'), - role_name='group-leader', user_editable=False, + role_id=UUID("89819f84-6346-488b-8955-86062e9eedb7"), + role_name="resource_editor", + user_editable=True, privileges=( Privilege( - privilege_id='group:resource:create-resource', - privilege_description='Create a resource object'), + privilege_id="group:resource:edit-resource", + privilege_description="edit/update a resource"), Privilege( - privilege_id='group:resource:delete-resource', - privilege_description='Delete a resource'), + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"))),)}, + {"resource_id": UUID("26ad1668-29f5-439d-b905-84d551f85955"), + "user_id": UUID("ecb52977-3004-469e-9428-2a1856725c7f"), + "roles": ( + Role( + role_id=UUID("89819f84-6346-488b-8955-86062e9eedb7"), + role_name="resource_editor", + user_editable=True, + privileges=( + Privilege( + privilege_id="group:resource:edit-resource", + privilege_description="edit/update a resource"), + Privilege( + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"))), + Role( + role_id=UUID("fd88bfed-d869-4969-87f2-67c4e8446ecb"), + role_name="public-view", + user_editable=False, + privileges=( + Privilege( + privilege_id="group:resource:view-resource", + privilege_description=( + "view a resource and use it in computations")),)))}, + {"resource_id": UUID("e9a1184a-e8b4-49fb-b713-8d9cbeea5b83"), + "user_id": UUID("ecb52977-3004-469e-9428-2a1856725c7f"), + "roles": (Role( + role_id=UUID("89819f84-6346-488b-8955-86062e9eedb7"), + role_name="resource_editor", + user_editable=True, + privileges=( Privilege( - privilege_id='group:resource:edit-resource', - privilege_description='edit/update a resource'), + privilege_id="group:resource:edit-resource", + privilege_description="edit/update a resource"), Privilege( - privilege_id='group:resource:view-resource', - privilege_description=( - 'view a resource and use it in computations')), + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"))),)}, + {"resource_id": UUID("38d1807d-105f-44a7-8327-7e2d973b6d8d"), + "user_id": UUID("ecb52977-3004-469e-9428-2a1856725c7f"), + "roles": (Role( + role_id=UUID("a0e67630-d502-4b9f-b23f-6805d0f30e30"), + role_name="group-leader", + user_editable=False, + privileges=( Privilege( - privilege_id='group:role:create-role', - privilege_description='Create a new role'), + "group:data:link-to-group", + "Allow linking data to only one specific group."), + Privilege( - privilege_id='group:role:delete-role', - privilege_description='Delete an existing role'), + privilege_id="group:resource:create-resource", + privilege_description="Create a resource object"), Privilege( - privilege_id='group:role:edit-role', - privilege_description='edit/update an existing role'), + privilege_id="group:resource:delete-resource", + privilege_description="Delete a resource"), Privilege( - privilege_id='group:user:add-group-member', - privilege_description='Add a user to a group'), + privilege_id="group:resource:edit-resource", + privilege_description="edit/update a resource"), Privilege( - privilege_id='group:user:assign-role', - privilege_description=( - 'Assign a role to an existing user')), + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"), + Privilege( + privilege_id="group:user:add-group-member", + privilege_description="Add a user to a group"), + Privilege( + privilege_id="group:user:remove-group-member", + privilege_description="Remove a user from a group"), + Privilege( + privilege_id="resource:role:create-role", + privilege_description="Create a new role on a specific resource"), + Privilege( + privilege_id="resource:role:delete-role", + privilege_description="Delete an existing role from a specific resource"), Privilege( - privilege_id='group:user:remove-group-member', - privilege_description='Remove a user from a group'), + privilege_id="resource:role:edit-role", + privilege_description="Edit an existing role on a specific resource"), Privilege( - privilege_id='system:group:delete-group', - privilege_description='Delete a group'), + privilege_id="system:group:delete-group", + privilege_description="Delete a group"), Privilege( - privilege_id='system:group:edit-group', - privilege_description='Edit the details of a group'), + privilege_id="system:group:edit-group", + privilege_description="Edit the details of a group"), Privilege( - privilege_id='system:group:transfer-group-leader', + privilege_id="system:group:transfer-group-leader", privilege_description=( - 'Transfer leadership of the group to some other ' - 'member')), + "Transfer leadership of the group to some other member")), Privilege( - privilege_id='system:group:view-group', - privilege_description='View the details of a group'), + privilege_id="system:group:view-group", + privilege_description="View the details of a group"), Privilege( - privilege_id='system:user:list', - privilege_description='List users in the system'))),) - }, - { - "resource_id": uuid.UUID("0248b289-b277-4eaa-8c94-88a434d14b6e"), - "user_id": uuid.UUID("ecb52977-3004-469e-9428-2a1856725c7f"), - "roles": (Role( - role_id=uuid.UUID("ade7e6b0-ba9c-4b51-87d0-2af7fe39a347"), - role_name="group-creator", - user_editable=False, - privileges=( - Privilege( - privilege_id="system:group:create-group", - privilege_description="Create a group"),)),)}), - ({"resource_id": uuid.UUID("2130aec0-fefd-434d-92fd-9ca342348b2d"), - "user_id": uuid.UUID("21351b66-8aad-475b-84ac-53ce528451e3"), + privilege_id="system:user:list", + privilege_description="List users in the system"))),)}, + {"resource_id": UUID("0248b289-b277-4eaa-8c94-88a434d14b6e"), + "user_id": UUID("ecb52977-3004-469e-9428-2a1856725c7f"), + "roles": (Role( + role_id=UUID("fd88bfed-d869-4969-87f2-67c4e8446ecb"), + role_name="public-view", + user_editable=False, + privileges=( + Privilege( + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"),)),)}, + {"resource_id": UUID("04ad9e09-94ea-4390-8a02-11f92999806b"), + "user_id": UUID("ecb52977-3004-469e-9428-2a1856725c7f"), "roles": (Role( - role_id=uuid.UUID('89819f84-6346-488b-8955-86062e9eedb7'), - role_name='resource_editor', + role_id=UUID("fd88bfed-d869-4969-87f2-67c4e8446ecb"), + role_name="public-view", + user_editable=False, + privileges=( + Privilege( + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"),)),)}), + ({"resource_id": UUID("2130aec0-fefd-434d-92fd-9ca342348b2d"), + "user_id": UUID("21351b66-8aad-475b-84ac-53ce528451e3"), + "roles": (Role( + role_id=UUID("89819f84-6346-488b-8955-86062e9eedb7"), + role_name="resource_editor", user_editable=True, privileges=( Privilege( - privilege_id='group:resource:edit-resource', - privilege_description='edit/update a resource'), + privilege_id="group:resource:edit-resource", + privilege_description="edit/update a resource"), Privilege( - privilege_id='group:resource:view-resource', - privilege_description='view a resource and use it in computations'))),)},), - tuple(), - tuple())))) -def test_user_roles(fxtr_group_user_roles, user, expected): + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"))),) + }, + {"resource_id": UUID("0248b289-b277-4eaa-8c94-88a434d14b6e"), + "user_id": UUID("21351b66-8aad-475b-84ac-53ce528451e3"), + "roles": (Role( + role_id=UUID("fd88bfed-d869-4969-87f2-67c4e8446ecb"), + role_name="public-view", + user_editable=False, + privileges=( + Privilege( + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"),)),) + }, + {"resource_id": UUID("04ad9e09-94ea-4390-8a02-11f92999806b"), + "user_id": UUID("21351b66-8aad-475b-84ac-53ce528451e3"), + "roles": (Role( + role_id=UUID("fd88bfed-d869-4969-87f2-67c4e8446ecb"), + role_name="public-view", + user_editable=False, + privileges=( + Privilege( + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"),)),) + }, + {"resource_id": UUID("26ad1668-29f5-439d-b905-84d551f85955"), + "user_id": UUID("21351b66-8aad-475b-84ac-53ce528451e3"), + "roles": (Role( + role_id=UUID("fd88bfed-d869-4969-87f2-67c4e8446ecb"), + role_name="public-view", + user_editable=False, + privileges=( + Privilege( + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"),)),) + }), + ({"resource_id": UUID("0248b289-b277-4eaa-8c94-88a434d14b6e"), + "user_id": UUID("ae9c6245-0966-41a5-9a5e-20885a96bea7"), + "roles": (Role( + role_id=UUID("fd88bfed-d869-4969-87f2-67c4e8446ecb"), + role_name="public-view", + user_editable=False, + privileges=( + Privilege( + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"),)),) + }, + {"resource_id": UUID("04ad9e09-94ea-4390-8a02-11f92999806b"), + "user_id": UUID("ae9c6245-0966-41a5-9a5e-20885a96bea7"), + "roles": (Role( + role_id=UUID("fd88bfed-d869-4969-87f2-67c4e8446ecb"), + role_name="public-view", + user_editable=False, + privileges=( + Privilege( + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"),)),) + }, + {"resource_id": UUID("26ad1668-29f5-439d-b905-84d551f85955"), + "user_id": UUID("ae9c6245-0966-41a5-9a5e-20885a96bea7"), + "roles": (Role( + role_id=UUID("fd88bfed-d869-4969-87f2-67c4e8446ecb"), + role_name="public-view", + user_editable=False, + privileges=( + Privilege( + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"),)),) + }), + ({"resource_id": UUID("0248b289-b277-4eaa-8c94-88a434d14b6e"), + "user_id": UUID("9a0c7ce5-2f40-4e78-979e-bf3527a59579"), + "roles": ( + Role( + role_id=UUID("ade7e6b0-ba9c-4b51-87d0-2af7fe39a347"), + role_name="group-creator", + user_editable=False, + privileges=( + Privilege( + privilege_id="system:group:create-group", + privilege_description="Create a group"),)), + Role( + role_id=UUID("fd88bfed-d869-4969-87f2-67c4e8446ecb"), + role_name="public-view", + user_editable=False, + privileges=( + Privilege( + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"),))) + }, + {"resource_id": UUID("04ad9e09-94ea-4390-8a02-11f92999806b"), + "user_id": UUID("9a0c7ce5-2f40-4e78-979e-bf3527a59579"), + "roles": (Role( + role_id=UUID("fd88bfed-d869-4969-87f2-67c4e8446ecb"), + role_name="public-view", + user_editable=False, + privileges=( + Privilege( + privilege_id="group:resource:view-resource", + privilege_description="view a resource and use it in computations"),)),) + }, + {"resource_id": UUID("26ad1668-29f5-439d-b905-84d551f85955"), + "user_id": UUID("9a0c7ce5-2f40-4e78-979e-bf3527a59579"), + "roles": (Role( + role_id=UUID("fd88bfed-d869-4969-87f2-67c4e8446ecb"), + role_name="public-view", + user_editable=False, + privileges=( + Privilege( + privilege_id="group:resource:view-resource", + privilege_description=( + "view a resource and use it in computations")),)),)}))))) +def test_user_roles( + fxtr_resource_user_roles, + user, + expected +): """ GIVEN: an authenticated user WHEN: we request the user's privileges THEN: return **ALL** the privileges attached to the user """ - conn, *_others = fxtr_group_user_roles + conn, *_others = fxtr_resource_user_roles assert user_roles(conn, user) == expected diff --git a/tests/unit/auth/test_system_admin_resources.py b/tests/unit/auth/test_system_admin_resources.py new file mode 100644 index 0000000..76f3ca3 --- /dev/null +++ b/tests/unit/auth/test_system_admin_resources.py @@ -0,0 +1,94 @@ +"""Tests for system admin resource-ownership endpoints. + +Covers POST /auth/system/administration/resources/<id>/assign-owner + and POST /auth/system/administration/resources/<id>/revoke-owner. +""" +import pytest + +from tests.unit.auth import conftest +from tests.unit.auth.fixtures.resource_fixtures import TEST_RESOURCES + +# Arbitrary target resource for the endpoint path — the privilege check fires +# before any resource lookup, so the resource need not exist for 401/403 tests. +_TARGET_RESOURCE = str(TEST_RESOURCES[0].resource_id) + +# Minimal body for both endpoints (the target user for ownership change). +_BODY = {"user_id": str(conftest.TEST_USERS[3].user_id)} + +_ASSIGN_URL = f"/auth/system/administration/resources/{_TARGET_RESOURCE}/assign-owner" +_REVOKE_URL = f"/auth/system/administration/resources/{_TARGET_RESOURCE}/revoke-owner" + +_NON_SYSADMIN = conftest.TEST_USERS[3] # unaff@iliated.user — no roles at all + + +def _mock_token(mocker, user, clients): + """Patch require_oauth.acquire in the admin resources module.""" + mocker.patch( + "gn_auth.auth.system.admin.resources.require_oauth.acquire", + conftest.get_tokeniser( + user, + tuple(c for c in clients if c.user == user)[0])) + + +# --------------------------------------------------------------------------- +# No-token tests (401) +# --------------------------------------------------------------------------- + +@pytest.mark.unit_test +def test_assign_owner_no_token_returns_401(fxtr_app): + """ + GIVEN: no Authorization header + WHEN: POST .../assign-owner + THEN: 401 is returned + """ + with fxtr_app.test_client() as http: + res = http.post(_ASSIGN_URL, json=_BODY) + assert res.status_code == 401 + + +@pytest.mark.unit_test +def test_revoke_owner_no_token_returns_401(fxtr_app): + """ + GIVEN: no Authorization header + WHEN: POST .../revoke-owner + THEN: 401 is returned + """ + with fxtr_app.test_client() as http: + res = http.post(_REVOKE_URL, json=_BODY) + assert res.status_code == 401 + + +# --------------------------------------------------------------------------- +# Non-sysadmin tests (403) +# --------------------------------------------------------------------------- + +@pytest.mark.unit_test +def test_assign_owner_non_sysadmin_returns_403(fxtr_app, mocker, fxtr_oauth2_clients): + """ + GIVEN: a valid token for a user without system:resource:assign-owner + WHEN: POST .../assign-owner + THEN: 403 is returned + """ + _conn, clients = fxtr_oauth2_clients + _mock_token(mocker, _NON_SYSADMIN, clients) + with fxtr_app.test_client() as http: + res = http.post( + _ASSIGN_URL, json=_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) + assert res.status_code == 403 + + +@pytest.mark.unit_test +def test_revoke_owner_non_sysadmin_returns_403(fxtr_app, mocker, fxtr_oauth2_clients): + """ + GIVEN: a valid token for a user without system:resource:assign-owner + WHEN: POST .../revoke-owner + THEN: 403 is returned + """ + _conn, clients = fxtr_oauth2_clients + _mock_token(mocker, _NON_SYSADMIN, clients) + with fxtr_app.test_client() as http: + res = http.post( + _REVOKE_URL, json=_BODY, + headers={"Authorization": "Bearer some-mocked-token"}) + assert res.status_code == 403 diff --git a/tests/unit/auth/test_token.py b/tests/unit/auth/test_token.py index 60d19ad..865638f 100644 --- a/tests/unit/auth/test_token.py +++ b/tests/unit/auth/test_token.py @@ -1,4 +1,5 @@ """Test the OAuth2 authorisation""" +import warnings import pytest @@ -7,8 +8,8 @@ from gn_auth.auth.db import sqlite3 as db SUCCESS_RESULT = { "status_code": 200, "result": { - "access_token": "123456ABCDE", - "expires_in": 864000, + # "access_token": "123456ABCDE", # T0DO: Generate valid JWT for these: + # "expires_in": 864000, # T0DO: Check this in the JWT access_token itself "scope": "profile", "token_type": "Bearer"}} @@ -23,10 +24,6 @@ def gen_token(client, grant_type, user, scope): # pylint: disable=[unused-argume return "123456ABCDE" -@pytest.mark.skip( - "Use of JWTs means the password grant is broken. We should probably drop " - "support for the password grant in the code, since it is actually a " - "deprecated type of grant anyway.") @pytest.mark.unit_test @pytest.mark.parametrize( "test_data,expected", @@ -39,7 +36,7 @@ def gen_token(client, grant_type, user, scope): # pylint: disable=[unused-argume (("papa", "yada", 2), USERNAME_PASSWORD_FAIL_RESULT), # (("unaff@iliated.user", "password_for_user_004", 1), USERNAME_PASSWORD_FAIL_RESULT) )) -def test_token(fxtr_app, fxtr_oauth2_clients, test_data, expected): +def test_token(client, fxtr_oauth2_clients, test_data, expected): """ GIVEN: a registered oauth2 client, a user WHEN: a token is requested via the 'password' grant @@ -52,16 +49,23 @@ def test_token(fxtr_app, fxtr_oauth2_clients, test_data, expected): conn, oa2clients = fxtr_oauth2_clients email, password, client_idx = test_data data = { - "grant_type": "password", "scope": "profile nonexistent-scope", + "grant_type": "password", "scope": "profile", "client_id": oa2clients[client_idx].client_id, "client_secret": oa2clients[client_idx].client_secret, "username": email, "password": password} - with fxtr_app.test_client() as client, db.cursor(conn) as cursor: + with db.cursor(conn) as cursor: res = client.post("/auth/token", data=data) # cleanup db cursor.execute("DELETE FROM oauth2_tokens WHERE access_token=?", (gen_token(None, None, None, None),)) + + warnings.warn( + "The `test_token.py` tests are incomplete:\nTODO:\n" + "\t- [ ] mock the token generation function(s).\n" + "\t- [ ] Check 'access_token' value.\n" + "\t- [ ] Check 'expires_in' value inside the 'access_token' value.", + RuntimeWarning) assert res.status_code == expected["status_code"] for key in expected["result"]: assert res.json[key] == expected["result"][key] |
