Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove admin user group #436

Merged
merged 3 commits into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 5 additions & 17 deletions api/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,19 @@

from .auth import Authentication
from .db import Database
from .models import UserGroup
from .user_models import User


async def setup_admin_group(db, admin_group):
group_obj = await db.find_one(UserGroup, name=admin_group)
if group_obj is None:
print(f"Creating {admin_group} group...")
group_obj = await db.create(UserGroup(name=admin_group))
return group_obj


async def setup_admin_user(db, username, email, admin_group):
async def setup_admin_user(db, username, email):

Check warning on line 23 in api/admin.py

View workflow job for this annotation

GitHub Actions / Lint

Argument name "db" doesn't conform to snake_case naming style
"""Create an admin user"""
user_obj = await db.find_one_by_attributes(User,
{'username': username})
if user_obj:
print(f"User {username} already exists, aborting.")
print(user_obj.json())
return None
password = getpass.getpass(f"Password for user '{args.username}': ")
retyped = getpass.getpass(f"Retype password for user '{args.username}': ")
password = getpass.getpass(f"Password for user '{username}': ")
retyped = getpass.getpass(f"Retype password for user '{username}': ")
if password != retyped:
print("Sorry, passwords do not match, aborting.")
return None
Expand All @@ -47,17 +39,15 @@
username=username,
hashed_password=hashed_password,
email=email,
groups=[admin_group],
is_superuser=1,
is_verified=1,
))


async def main(args):

Check warning on line 47 in api/admin.py

View workflow job for this annotation

GitHub Actions / Lint

Missing function or method docstring

Check warning on line 47 in api/admin.py

View workflow job for this annotation

GitHub Actions / Lint

Redefining name 'args' from outer scope (line 64)
db = Database(args.mongo, args.database)

Check warning on line 48 in api/admin.py

View workflow job for this annotation

GitHub Actions / Lint

Variable name "db" doesn't conform to snake_case naming style
await db.initialize_beanie()
group = await setup_admin_group(db, args.admin_group)
user = await setup_admin_user(db, args.username, args.email, group)
await setup_admin_user(db, args.username, args.email)
return True


Expand All @@ -67,8 +57,6 @@
help="Mongo server connection string")
parser.add_argument('--username', default='admin',
help="Admin username")
parser.add_argument('--admin-group', default='admin',
help="Admin group name")
parser.add_argument('--database', default='kernelci',
help="KernelCI database name")
parser.add_argument('--email', required=True,
Expand Down
6 changes: 1 addition & 5 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ async def update_me(request: Request, user: UserUpdate,
"""User update route

Custom user update router handler will only allow users to update
its own profile. Adding itself to 'admin' group is not allowed.
its own profile.
"""
if user.username and user.username != current_user.username:
existing_user = await db.find_one(User, username=user.username)
Expand All @@ -232,10 +232,6 @@ async def update_me(request: Request, user: UserUpdate,
groups = []
if user.groups:
for group_name in user.groups:
if group_name == "admin":
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Unauthorized to add user to 'admin' group")
group = await db.find_one(UserGroup, name=group_name)
if not group:
raise HTTPException(
Expand Down
2 changes: 1 addition & 1 deletion tests/e2e_tests/test_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
depends=[
'e2e_tests/test_subscribe_handler.py::test_subscribe_node_channel'],
scope='session')
@pytest.mark.order(5)
@pytest.mark.order(4)
r-c-n marked this conversation as resolved.
Show resolved Hide resolved
@pytest.mark.asyncio
async def test_node_pipeline(test_async_client):
"""
Expand All @@ -38,7 +38,7 @@

# Create Task to listen pubsub event on 'node' channel
task_listen = create_listen_task(test_async_client,
pytest.node_channel_subscription_id)

Check failure on line 41 in tests/e2e_tests/test_pipeline.py

View workflow job for this annotation

GitHub Actions / Lint

Module 'pytest' has no 'node_channel_subscription_id' member

# Create a node
node = {
Expand Down Expand Up @@ -71,7 +71,7 @@

# Create Task to listen 'updated' event on 'node' channel
task_listen = create_listen_task(test_async_client,
pytest.node_channel_subscription_id)

Check failure on line 74 in tests/e2e_tests/test_pipeline.py

View workflow job for this annotation

GitHub Actions / Lint

Module 'pytest' has no 'node_channel_subscription_id' member

# Update node.state
node.update({"state": "done"})
Expand Down
6 changes: 3 additions & 3 deletions tests/e2e_tests/test_subscribe_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
@pytest.mark.dependency(
depends=['e2e_tests/test_user_creation.py::test_create_regular_user'],
scope='session')
@pytest.mark.order(4)
@pytest.mark.order(3)
def test_subscribe_node_channel(test_client):
"""
Test Case : Test KernelCI API '/subscribe' endpoint with 'node' channel
Expand All @@ -23,7 +23,7 @@
response = test_client.post(
"subscribe/node",
headers={
"Authorization": f"Bearer {pytest.BEARER_TOKEN}"

Check failure on line 26 in tests/e2e_tests/test_subscribe_handler.py

View workflow job for this annotation

GitHub Actions / Lint

Module 'pytest' has no 'BEARER_TOKEN' member
},
)
pytest.node_channel_subscription_id = response.json()['id']
Expand All @@ -35,7 +35,7 @@
@pytest.mark.dependency(
depends=['e2e_tests/test_user_creation.py::test_create_regular_user'],
scope='session')
@pytest.mark.order(4)
@pytest.mark.order(3)
def test_subscribe_test_channel(test_client):
"""
Test Case : Test KernelCI API '/subscribe' endpoint with 'test_channel'
Expand All @@ -46,7 +46,7 @@
response = test_client.post(
"subscribe/test_channel",
headers={
"Authorization": f"Bearer {pytest.BEARER_TOKEN}"

Check failure on line 49 in tests/e2e_tests/test_subscribe_handler.py

View workflow job for this annotation

GitHub Actions / Lint

Module 'pytest' has no 'BEARER_TOKEN' member
},
)
pytest.test_channel_subscription_id = response.json()['id']
Expand All @@ -58,7 +58,7 @@
@pytest.mark.dependency(
depends=['e2e_tests/test_user_creation.py::test_create_regular_user'],
scope='session')
@pytest.mark.order(4)
@pytest.mark.order(3)
def test_subscribe_user_group_channel(test_client):
"""
Test Case : Test KernelCI API '/subscribe' endpoint with 'user_group'
Expand All @@ -70,7 +70,7 @@
response = test_client.post(
"subscribe/user_group",
headers={
"Authorization": f"Bearer {pytest.BEARER_TOKEN}"

Check failure on line 73 in tests/e2e_tests/test_subscribe_handler.py

View workflow job for this annotation

GitHub Actions / Lint

Module 'pytest' has no 'BEARER_TOKEN' member
},
)
pytest.user_group_channel_subscription_id = response.json()['id']
Expand Down
7 changes: 3 additions & 4 deletions tests/e2e_tests/test_user_creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
import json
import pytest

from e2e_tests.conftest import db_create

Check failure on line 11 in tests/e2e_tests/test_user_creation.py

View workflow job for this annotation

GitHub Actions / Lint

Unable to import 'e2e_tests.conftest'
from api.models import UserGroup
from api.user_models import User
from api.db import Database
from api.auth import Authentication
Expand All @@ -19,11 +18,11 @@
depends=["e2e_tests/test_user_group_handler.py::test_create_user_groups"],
scope="session")
@pytest.mark.dependency()
@pytest.mark.order(2)
@pytest.mark.order(1)
@pytest.mark.asyncio
async def test_create_admin_user(test_async_client):
"""
Test Case : Get hashed password using authentication method to create an admin

Check warning on line 25 in tests/e2e_tests/test_user_creation.py

View workflow job for this annotation

GitHub Actions / Lint

line too long (82 > 79 characters)
user. Create the admin user using database create method.
Request authentication token using '/user/login' endpoint for the user and
store it in pytest global variable 'ADMIN_BEARER_TOKEN'.
Expand All @@ -38,7 +37,7 @@
username=username,
hashed_password=hashed_password,
email='[email protected]',
groups=[UserGroup(name="admin")],
groups=[],
is_superuser=1,
is_verified=1
))
Expand All @@ -62,13 +61,13 @@


@pytest.mark.dependency(depends=["test_create_admin_user"])
@pytest.mark.order(3)
@pytest.mark.order(2)
@pytest.mark.asyncio
async def test_create_regular_user(test_async_client):
"""
Test Case : Test KernelCI API '/user/register' endpoint to create regular
user when requested with admin user's bearer token. Request '/user/login'
endpoint for the user and store it in pytest global variable 'BEARER_TOKEN'.

Check warning on line 70 in tests/e2e_tests/test_user_creation.py

View workflow job for this annotation

GitHub Actions / Lint

line too long (80 > 79 characters)
"""
username = 'test_user'
password = 'test'
Expand Down
43 changes: 0 additions & 43 deletions tests/e2e_tests/test_user_group_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,57 +7,14 @@

import pytest
from cloudevents.http import from_json
import json

Check warning on line 10 in tests/e2e_tests/test_user_group_handler.py

View workflow job for this annotation

GitHub Actions / Lint

standard import "import json" should be placed before "import pytest"

from api.models import UserGroup
from api.db import Database
from e2e_tests.conftest import db_create
from .listen_handler import create_listen_task


@pytest.mark.dependency()
@pytest.mark.order(1)
@pytest.mark.asyncio
async def test_create_user_groups():
"""
Test Case : Create default user groups
"""
default_user_groups = ['admin']
for group in default_user_groups:
obj = await db_create(
Database.COLLECTIONS[UserGroup],
UserGroup(name=group))
assert obj is not None


@pytest.mark.dependency(
depends=["test_create_user_groups"])
@pytest.mark.asyncio
async def test_get_user_group(test_async_client):
"""
Test Case : Get user groups
Expected Result :
HTTP Response Code 200 OK
Returns dictionary with UserGroup objects, total number of groups
returned along with limit and offset values
"""
response = await test_async_client.get(
"groups",
)
assert response.status_code == 200
assert response.json().keys() == {
'items',
'total',
'limit',
'offset',
}
assert response.json()['total'] == 1
assert response.json()['items'][0]['name'] == 'admin'


@pytest.mark.dependency(
depends=[
'e2e_tests/test_subscribe_handler.py::test_subscribe_user_group_channel'],

Check warning on line 17 in tests/e2e_tests/test_user_group_handler.py

View workflow job for this annotation

GitHub Actions / Lint

line too long (82 > 79 characters)
scope='session')
@pytest.mark.asyncio
async def test_create_and_get_user_group(test_async_client):
Expand All @@ -71,11 +28,11 @@
The GET '/group/{group_id}' will be sent using group id from event data
to get newly created user group object.
"""

Check warning on line 31 in tests/e2e_tests/test_user_group_handler.py

View workflow job for this annotation

GitHub Actions / Lint

Trailing whitespace
# Create Task to listen pubsub event on 'user_group' channel
task_listen = create_listen_task(test_async_client,
pytest.user_group_channel_subscription_id)

Check warning on line 35 in tests/e2e_tests/test_user_group_handler.py

View workflow job for this annotation

GitHub Actions / Lint

Trailing whitespace
# Create a user group
response = await test_async_client.post(
"group",
Expand Down
3 changes: 1 addition & 2 deletions tests/unit_tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
get_current_user,
get_current_superuser,
)
from api.models import UserGroup
from api.user_models import User
from api.pubsub import PubSub, Subscription

Expand Down Expand Up @@ -86,7 +85,7 @@ def mock_get_current_admin_user(request: Request):
hashed_password='$2b$12$CpJZx5ooxM11bCFXT76/z.o6HWs2sPJy4iP8.'
'xCZGmM8jWXUXJZ4K',
email='[email protected]',
groups=[UserGroup(name='admin')],
groups=[],
is_active=True,
is_superuser=True,
is_verified=True
Expand Down
2 changes: 1 addition & 1 deletion tests/unit_tests/test_user_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ async def test_create_admin_user(test_async_client, mock_db_find_one,
id='61bda8f2eb1a63d2b7152419',
username='test_admin',
email='[email protected]',
groups=[UserGroup(name='admin')],
groups=[],
is_active=True,
is_verified=False,
is_superuser=True
Expand Down
Loading