mirror of https://github.com/GNS3/gns3-server
commit
4dd3bc6a98
@ -0,0 +1,117 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
#
|
||||||
|
# Copyright (C) 2021 GNS3 Technologies Inc.
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU General Public License as published by
|
||||||
|
# the Free Software Foundation, either version 3 of the License, or
|
||||||
|
# (at your option) any later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU General Public License for more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
"""
|
||||||
|
API routes for permissions.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, status
|
||||||
|
from uuid import UUID
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from gns3server import schemas
|
||||||
|
from gns3server.controller.controller_error import (
|
||||||
|
ControllerBadRequestError,
|
||||||
|
ControllerNotFoundError,
|
||||||
|
ControllerForbiddenError,
|
||||||
|
)
|
||||||
|
|
||||||
|
from gns3server.db.repositories.rbac import RbacRepository
|
||||||
|
from .dependencies.database import get_repository
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=List[schemas.Permission])
|
||||||
|
async def get_permissions(
|
||||||
|
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository))
|
||||||
|
) -> List[schemas.Permission]:
|
||||||
|
"""
|
||||||
|
Get all permissions.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return await rbac_repo.get_permissions()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=schemas.Permission, status_code=status.HTTP_201_CREATED)
|
||||||
|
async def create_permission(
|
||||||
|
permission_create: schemas.PermissionCreate,
|
||||||
|
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository))
|
||||||
|
) -> schemas.Permission:
|
||||||
|
"""
|
||||||
|
Create a new permission.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if await rbac_repo.check_permission_exists(permission_create):
|
||||||
|
raise ControllerBadRequestError(f"Permission '{permission_create.methods} {permission_create.path} "
|
||||||
|
f"{permission_create.action}' already exists")
|
||||||
|
|
||||||
|
return await rbac_repo.create_permission(permission_create)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{permission_id}", response_model=schemas.Permission)
|
||||||
|
async def get_permission(
|
||||||
|
permission_id: UUID,
|
||||||
|
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository)),
|
||||||
|
) -> schemas.Permission:
|
||||||
|
"""
|
||||||
|
Get a permission.
|
||||||
|
"""
|
||||||
|
|
||||||
|
permission = await rbac_repo.get_permission(permission_id)
|
||||||
|
if not permission:
|
||||||
|
raise ControllerNotFoundError(f"Permission '{permission_id}' not found")
|
||||||
|
return permission
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{permission_id}", response_model=schemas.Permission)
|
||||||
|
async def update_permission(
|
||||||
|
permission_id: UUID,
|
||||||
|
permission_update: schemas.PermissionUpdate,
|
||||||
|
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository))
|
||||||
|
) -> schemas.Permission:
|
||||||
|
"""
|
||||||
|
Update a permission.
|
||||||
|
"""
|
||||||
|
|
||||||
|
permission = await rbac_repo.get_permission(permission_id)
|
||||||
|
if not permission:
|
||||||
|
raise ControllerNotFoundError(f"Permission '{permission_id}' not found")
|
||||||
|
|
||||||
|
return await rbac_repo.update_permission(permission_id, permission_update)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{permission_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
async def delete_permission(
|
||||||
|
permission_id: UUID,
|
||||||
|
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository)),
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Delete a permission.
|
||||||
|
"""
|
||||||
|
|
||||||
|
permission = await rbac_repo.get_permission(permission_id)
|
||||||
|
if not permission:
|
||||||
|
raise ControllerNotFoundError(f"Permission '{permission_id}' not found")
|
||||||
|
|
||||||
|
success = await rbac_repo.delete_permission(permission_id)
|
||||||
|
if not success:
|
||||||
|
raise ControllerNotFoundError(f"Permission '{permission_id}' could not be deleted")
|
@ -0,0 +1,178 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
#
|
||||||
|
# Copyright (C) 2021 GNS3 Technologies Inc.
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU General Public License as published by
|
||||||
|
# the Free Software Foundation, either version 3 of the License, or
|
||||||
|
# (at your option) any later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU General Public License for more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
"""
|
||||||
|
API routes for roles.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, status
|
||||||
|
from uuid import UUID
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from gns3server import schemas
|
||||||
|
from gns3server.controller.controller_error import (
|
||||||
|
ControllerBadRequestError,
|
||||||
|
ControllerNotFoundError,
|
||||||
|
ControllerForbiddenError,
|
||||||
|
)
|
||||||
|
|
||||||
|
from gns3server.db.repositories.rbac import RbacRepository
|
||||||
|
from .dependencies.database import get_repository
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=List[schemas.Role])
|
||||||
|
async def get_roles(
|
||||||
|
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository))
|
||||||
|
) -> List[schemas.Role]:
|
||||||
|
"""
|
||||||
|
Get all roles.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return await rbac_repo.get_roles()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=schemas.Role, status_code=status.HTTP_201_CREATED)
|
||||||
|
async def create_role(
|
||||||
|
role_create: schemas.RoleCreate,
|
||||||
|
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository))
|
||||||
|
) -> schemas.Role:
|
||||||
|
"""
|
||||||
|
Create a new role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if await rbac_repo.get_role_by_name(role_create.name):
|
||||||
|
raise ControllerBadRequestError(f"Role '{role_create.name}' already exists")
|
||||||
|
|
||||||
|
return await rbac_repo.create_role(role_create)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{role_id}", response_model=schemas.Role)
|
||||||
|
async def get_role(
|
||||||
|
role_id: UUID,
|
||||||
|
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository)),
|
||||||
|
) -> schemas.Role:
|
||||||
|
"""
|
||||||
|
Get a role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
role = await rbac_repo.get_role(role_id)
|
||||||
|
if not role:
|
||||||
|
raise ControllerNotFoundError(f"Role '{role_id}' not found")
|
||||||
|
return role
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{role_id}", response_model=schemas.Role)
|
||||||
|
async def update_role(
|
||||||
|
role_id: UUID,
|
||||||
|
role_update: schemas.RoleUpdate,
|
||||||
|
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository))
|
||||||
|
) -> schemas.Role:
|
||||||
|
"""
|
||||||
|
Update a role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
role = await rbac_repo.get_role(role_id)
|
||||||
|
if not role:
|
||||||
|
raise ControllerNotFoundError(f"Role '{role_id}' not found")
|
||||||
|
|
||||||
|
if role.builtin:
|
||||||
|
raise ControllerForbiddenError(f"Built-in role '{role_id}' cannot be updated")
|
||||||
|
|
||||||
|
return await rbac_repo.update_role(role_id, role_update)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{role_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
async def delete_role(
|
||||||
|
role_id: UUID,
|
||||||
|
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository)),
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Delete a role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
role = await rbac_repo.get_role(role_id)
|
||||||
|
if not role:
|
||||||
|
raise ControllerNotFoundError(f"Role '{role_id}' not found")
|
||||||
|
|
||||||
|
if role.builtin:
|
||||||
|
raise ControllerForbiddenError(f"Built-in role '{role_id}' cannot be deleted")
|
||||||
|
|
||||||
|
success = await rbac_repo.delete_role(role_id)
|
||||||
|
if not success:
|
||||||
|
raise ControllerNotFoundError(f"Role '{role_id}' could not be deleted")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{role_id}/permissions", response_model=List[schemas.Permission])
|
||||||
|
async def get_role_permissions(
|
||||||
|
role_id: UUID,
|
||||||
|
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository))
|
||||||
|
) -> List[schemas.Permission]:
|
||||||
|
"""
|
||||||
|
Get all role permissions.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return await rbac_repo.get_role_permissions(role_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put(
|
||||||
|
"/{role_id}/permissions/{permission_id}",
|
||||||
|
status_code=status.HTTP_204_NO_CONTENT
|
||||||
|
)
|
||||||
|
async def add_permission_to_role(
|
||||||
|
role_id: UUID,
|
||||||
|
permission_id: UUID,
|
||||||
|
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository))
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Add a permission to a role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
permission = await rbac_repo.get_permission(permission_id)
|
||||||
|
if not permission:
|
||||||
|
raise ControllerNotFoundError(f"Permission '{permission_id}' not found")
|
||||||
|
|
||||||
|
role = await rbac_repo.add_permission_to_role(role_id, permission)
|
||||||
|
if not role:
|
||||||
|
raise ControllerNotFoundError(f"Role '{role_id}' not found")
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete(
|
||||||
|
"/{role_id}/permissions/{permission_id}",
|
||||||
|
status_code=status.HTTP_204_NO_CONTENT
|
||||||
|
)
|
||||||
|
async def remove_permission_from_role(
|
||||||
|
role_id: UUID,
|
||||||
|
permission_id: UUID,
|
||||||
|
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository)),
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Remove member from an user group.
|
||||||
|
"""
|
||||||
|
|
||||||
|
permission = await rbac_repo.get_permission(permission_id)
|
||||||
|
if not permission:
|
||||||
|
raise ControllerNotFoundError(f"Permission '{permission_id}' not found")
|
||||||
|
|
||||||
|
role = await rbac_repo.remove_permission_from_role(role_id, permission)
|
||||||
|
if not role:
|
||||||
|
raise ControllerNotFoundError(f"Role '{role_id}' not found")
|
@ -0,0 +1,122 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
#
|
||||||
|
# Copyright (C) 2021 GNS3 Technologies Inc.
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU General Public License as published by
|
||||||
|
# the Free Software Foundation, either version 3 of the License, or
|
||||||
|
# (at your option) any later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU General Public License for more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
from sqlalchemy import Table, Column, String, ForeignKey, event
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from .base import Base, BaseTable, generate_uuid, GUID, ListType
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
permission_role_link = Table(
|
||||||
|
"permissions_roles_link",
|
||||||
|
Base.metadata,
|
||||||
|
Column("permission_id", GUID, ForeignKey("permissions.permission_id", ondelete="CASCADE")),
|
||||||
|
Column("role_id", GUID, ForeignKey("roles.role_id", ondelete="CASCADE"))
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Permission(BaseTable):
|
||||||
|
|
||||||
|
__tablename__ = "permissions"
|
||||||
|
|
||||||
|
permission_id = Column(GUID, primary_key=True, default=generate_uuid)
|
||||||
|
description = Column(String)
|
||||||
|
methods = Column(ListType)
|
||||||
|
path = Column(String)
|
||||||
|
action = Column(String)
|
||||||
|
user_id = Column(GUID, ForeignKey('users.user_id', ondelete="CASCADE"))
|
||||||
|
roles = relationship("Role", secondary=permission_role_link, back_populates="permissions")
|
||||||
|
|
||||||
|
|
||||||
|
@event.listens_for(Permission.__table__, 'after_create')
|
||||||
|
def create_default_roles(target, connection, **kw):
|
||||||
|
|
||||||
|
default_permissions = [
|
||||||
|
{
|
||||||
|
"description": "Allow access to all endpoints",
|
||||||
|
"methods": ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"],
|
||||||
|
"path": "/",
|
||||||
|
"action": "ALLOW"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Allow to create and list projects",
|
||||||
|
"methods": ["GET", "HEAD", "POST"],
|
||||||
|
"path": "/projects",
|
||||||
|
"action": "ALLOW"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Allow to create and list templates",
|
||||||
|
"methods": ["GET", "HEAD", "POST"],
|
||||||
|
"path": "/templates",
|
||||||
|
"action": "ALLOW"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Allow to list computes",
|
||||||
|
"methods": ["GET"],
|
||||||
|
"path": "/computes/*",
|
||||||
|
"action": "ALLOW"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Allow access to all symbol endpoints",
|
||||||
|
"methods": ["GET", "HEAD", "POST"],
|
||||||
|
"path": "/symbols/*",
|
||||||
|
"action": "ALLOW"
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
stmt = target.insert().values(default_permissions)
|
||||||
|
connection.execute(stmt)
|
||||||
|
connection.commit()
|
||||||
|
log.debug("The default permissions have been created in the database")
|
||||||
|
|
||||||
|
|
||||||
|
@event.listens_for(permission_role_link, 'after_create')
|
||||||
|
def add_permissions_to_role(target, connection, **kw):
|
||||||
|
|
||||||
|
from .roles import Role
|
||||||
|
roles_table = Role.__table__
|
||||||
|
stmt = roles_table.select().where(roles_table.c.name == "Administrator")
|
||||||
|
result = connection.execute(stmt)
|
||||||
|
role_id = result.first().role_id
|
||||||
|
|
||||||
|
permissions_table = Permission.__table__
|
||||||
|
stmt = permissions_table.select().where(permissions_table.c.path == "/")
|
||||||
|
result = connection.execute(stmt)
|
||||||
|
permission_id = result.first().permission_id
|
||||||
|
|
||||||
|
# add root path to the "Administrator" role
|
||||||
|
stmt = target.insert().values(permission_id=permission_id, role_id=role_id)
|
||||||
|
connection.execute(stmt)
|
||||||
|
|
||||||
|
stmt = roles_table.select().where(roles_table.c.name == "User")
|
||||||
|
result = connection.execute(stmt)
|
||||||
|
role_id = result.first().role_id
|
||||||
|
|
||||||
|
# add minimum required paths to the "User" role
|
||||||
|
for path in ("/projects", "/templates", "/computes/*", "/symbols/*"):
|
||||||
|
stmt = permissions_table.select().where(permissions_table.c.path == path)
|
||||||
|
result = connection.execute(stmt)
|
||||||
|
permission_id = result.first().permission_id
|
||||||
|
stmt = target.insert().values(permission_id=permission_id, role_id=role_id)
|
||||||
|
connection.execute(stmt)
|
||||||
|
|
||||||
|
connection.commit()
|
@ -0,0 +1,81 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
#
|
||||||
|
# Copyright (C) 2021 GNS3 Technologies Inc.
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU General Public License as published by
|
||||||
|
# the Free Software Foundation, either version 3 of the License, or
|
||||||
|
# (at your option) any later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU General Public License for more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
from sqlalchemy import Table, Column, String, Boolean, ForeignKey, event
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from .base import Base, BaseTable, generate_uuid, GUID
|
||||||
|
from .permissions import permission_role_link
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
role_group_link = Table(
|
||||||
|
"roles_groups_link",
|
||||||
|
Base.metadata,
|
||||||
|
Column("role_id", GUID, ForeignKey("roles.role_id", ondelete="CASCADE")),
|
||||||
|
Column("user_group_id", GUID, ForeignKey("user_groups.user_group_id", ondelete="CASCADE"))
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Role(BaseTable):
|
||||||
|
|
||||||
|
__tablename__ = "roles"
|
||||||
|
|
||||||
|
role_id = Column(GUID, primary_key=True, default=generate_uuid)
|
||||||
|
name = Column(String)
|
||||||
|
description = Column(String)
|
||||||
|
builtin = Column(Boolean, default=False)
|
||||||
|
permissions = relationship("Permission", secondary=permission_role_link, back_populates="roles")
|
||||||
|
groups = relationship("UserGroup", secondary=role_group_link, back_populates="roles")
|
||||||
|
|
||||||
|
|
||||||
|
@event.listens_for(Role.__table__, 'after_create')
|
||||||
|
def create_default_roles(target, connection, **kw):
|
||||||
|
|
||||||
|
default_roles = [
|
||||||
|
{"name": "Administrator", "description": "Administrator role", "builtin": True},
|
||||||
|
{"name": "User", "description": "User role", "builtin": True},
|
||||||
|
]
|
||||||
|
|
||||||
|
stmt = target.insert().values(default_roles)
|
||||||
|
connection.execute(stmt)
|
||||||
|
connection.commit()
|
||||||
|
log.debug("The default roles have been created in the database")
|
||||||
|
|
||||||
|
|
||||||
|
@event.listens_for(role_group_link, 'after_create')
|
||||||
|
def add_admin_to_group(target, connection, **kw):
|
||||||
|
|
||||||
|
from .users import UserGroup
|
||||||
|
user_groups_table = UserGroup.__table__
|
||||||
|
roles_table = Role.__table__
|
||||||
|
|
||||||
|
# Add roles to built-in user groups
|
||||||
|
groups_to_roles = {"Administrators": "Administrator", "Users": "User"}
|
||||||
|
for user_group, role in groups_to_roles.items():
|
||||||
|
stmt = user_groups_table.select().where(user_groups_table.c.name == user_group)
|
||||||
|
result = connection.execute(stmt)
|
||||||
|
user_group_id = result.first().user_group_id
|
||||||
|
stmt = roles_table.select().where(roles_table.c.name == role)
|
||||||
|
result = connection.execute(stmt)
|
||||||
|
role_id = result.first().role_id
|
||||||
|
stmt = target.insert().values(role_id=role_id, user_group_id=user_group_id)
|
||||||
|
connection.execute(stmt)
|
||||||
|
|
||||||
|
connection.commit()
|
@ -0,0 +1,409 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
#
|
||||||
|
# Copyright (C) 2020 GNS3 Technologies Inc.
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU General Public License as published by
|
||||||
|
# the Free Software Foundation, either version 3 of the License, or
|
||||||
|
# (at your option) any later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU General Public License for more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
from uuid import UUID
|
||||||
|
from typing import Optional, List, Union
|
||||||
|
from sqlalchemy import select, update, delete
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from sqlalchemy.orm import selectinload
|
||||||
|
|
||||||
|
from .base import BaseRepository
|
||||||
|
|
||||||
|
import gns3server.db.models as models
|
||||||
|
from gns3server.schemas.controller.rbac import HTTPMethods, PermissionAction
|
||||||
|
from gns3server import schemas
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class RbacRepository(BaseRepository):
|
||||||
|
|
||||||
|
def __init__(self, db_session: AsyncSession) -> None:
|
||||||
|
|
||||||
|
super().__init__(db_session)
|
||||||
|
|
||||||
|
async def get_role(self, role_id: UUID) -> Optional[models.Role]:
|
||||||
|
"""
|
||||||
|
Get a role by its ID.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.Role).\
|
||||||
|
options(selectinload(models.Role.permissions)).\
|
||||||
|
where(models.Role.role_id == role_id)
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
return result.scalars().first()
|
||||||
|
|
||||||
|
async def get_role_by_name(self, name: str) -> Optional[models.Role]:
|
||||||
|
"""
|
||||||
|
Get a role by its name.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.Role).\
|
||||||
|
options(selectinload(models.Role.permissions)).\
|
||||||
|
where(models.Role.name == name)
|
||||||
|
#query = select(models.Role).where(models.Role.name == name)
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
return result.scalars().first()
|
||||||
|
|
||||||
|
async def get_roles(self) -> List[models.Role]:
|
||||||
|
"""
|
||||||
|
Get all roles.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.Role).options(selectinload(models.Role.permissions))
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
return result.scalars().all()
|
||||||
|
|
||||||
|
async def create_role(self, role_create: schemas.RoleCreate) -> models.Role:
|
||||||
|
"""
|
||||||
|
Create a new role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
db_role = models.Role(
|
||||||
|
name=role_create.name,
|
||||||
|
description=role_create.description,
|
||||||
|
)
|
||||||
|
self._db_session.add(db_role)
|
||||||
|
await self._db_session.commit()
|
||||||
|
#await self._db_session.refresh(db_role)
|
||||||
|
return await self.get_role(db_role.role_id)
|
||||||
|
|
||||||
|
async def update_role(
|
||||||
|
self,
|
||||||
|
role_id: UUID,
|
||||||
|
role_update: schemas.RoleUpdate
|
||||||
|
) -> Optional[models.Role]:
|
||||||
|
"""
|
||||||
|
Update a role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
update_values = role_update.dict(exclude_unset=True)
|
||||||
|
query = update(models.Role).\
|
||||||
|
where(models.Role.role_id == role_id).\
|
||||||
|
values(update_values)
|
||||||
|
|
||||||
|
await self._db_session.execute(query)
|
||||||
|
await self._db_session.commit()
|
||||||
|
role_db = await self.get_role(role_id)
|
||||||
|
if role_db:
|
||||||
|
await self._db_session.refresh(role_db) # force refresh of updated_at value
|
||||||
|
return role_db
|
||||||
|
|
||||||
|
async def delete_role(self, role_id: UUID) -> bool:
|
||||||
|
"""
|
||||||
|
Delete a role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = delete(models.Role).where(models.Role.role_id == role_id)
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
await self._db_session.commit()
|
||||||
|
return result.rowcount > 0
|
||||||
|
|
||||||
|
async def add_permission_to_role(
|
||||||
|
self,
|
||||||
|
role_id: UUID,
|
||||||
|
permission: models.Permission
|
||||||
|
) -> Union[None, models.Role]:
|
||||||
|
"""
|
||||||
|
Add a permission to a role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.Role).\
|
||||||
|
options(selectinload(models.Role.permissions)).\
|
||||||
|
where(models.Role.role_id == role_id)
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
role_db = result.scalars().first()
|
||||||
|
if not role_db:
|
||||||
|
return None
|
||||||
|
|
||||||
|
role_db.permissions.append(permission)
|
||||||
|
await self._db_session.commit()
|
||||||
|
await self._db_session.refresh(role_db)
|
||||||
|
return role_db
|
||||||
|
|
||||||
|
async def remove_permission_from_role(
|
||||||
|
self,
|
||||||
|
role_id: UUID,
|
||||||
|
permission: models.Permission
|
||||||
|
) -> Union[None, models.Role]:
|
||||||
|
"""
|
||||||
|
Remove a permission from a role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.Role).\
|
||||||
|
options(selectinload(models.Role.permissions)).\
|
||||||
|
where(models.Role.role_id == role_id)
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
role_db = result.scalars().first()
|
||||||
|
if not role_db:
|
||||||
|
return None
|
||||||
|
|
||||||
|
role_db.permissions.remove(permission)
|
||||||
|
await self._db_session.commit()
|
||||||
|
await self._db_session.refresh(role_db)
|
||||||
|
return role_db
|
||||||
|
|
||||||
|
async def get_role_permissions(self, role_id: UUID) -> List[models.Permission]:
|
||||||
|
"""
|
||||||
|
Get all the role permissions.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.Permission).\
|
||||||
|
join(models.Permission.roles).\
|
||||||
|
filter(models.Role.role_id == role_id)
|
||||||
|
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
return result.scalars().all()
|
||||||
|
|
||||||
|
async def get_permission(self, permission_id: UUID) -> Optional[models.Permission]:
|
||||||
|
"""
|
||||||
|
Get a permission by its ID.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.Permission).where(models.Permission.permission_id == permission_id)
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
return result.scalars().first()
|
||||||
|
|
||||||
|
async def get_permission_by_path(self, path: str) -> Optional[models.Permission]:
|
||||||
|
"""
|
||||||
|
Get a permission by its path.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.Permission).where(models.Permission.path == path)
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
return result.scalars().first()
|
||||||
|
|
||||||
|
async def get_permissions(self) -> List[models.Permission]:
|
||||||
|
"""
|
||||||
|
Get all permissions.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.Permission)
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
return result.scalars().all()
|
||||||
|
|
||||||
|
async def check_permission_exists(self, permission_create: schemas.PermissionCreate) -> bool:
|
||||||
|
"""
|
||||||
|
Check if a permission exists.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.Permission).\
|
||||||
|
where(models.Permission.methods == permission_create.methods,
|
||||||
|
models.Permission.path == permission_create.path,
|
||||||
|
models.Permission.action == permission_create.action)
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
return result.scalars().first() is not None
|
||||||
|
|
||||||
|
async def create_permission(self, permission_create: schemas.PermissionCreate) -> models.Permission:
|
||||||
|
"""
|
||||||
|
Create a new permission.
|
||||||
|
"""
|
||||||
|
|
||||||
|
db_permission = models.Permission(
|
||||||
|
description=permission_create.description,
|
||||||
|
methods=permission_create.methods,
|
||||||
|
path=permission_create.path,
|
||||||
|
action=permission_create.action,
|
||||||
|
)
|
||||||
|
self._db_session.add(db_permission)
|
||||||
|
await self._db_session.commit()
|
||||||
|
await self._db_session.refresh(db_permission)
|
||||||
|
return db_permission
|
||||||
|
|
||||||
|
async def update_permission(
|
||||||
|
self,
|
||||||
|
permission_id: UUID,
|
||||||
|
permission_update: schemas.PermissionUpdate
|
||||||
|
) -> Optional[models.Permission]:
|
||||||
|
"""
|
||||||
|
Update a permission.
|
||||||
|
"""
|
||||||
|
|
||||||
|
update_values = permission_update.dict(exclude_unset=True)
|
||||||
|
query = update(models.Permission).\
|
||||||
|
where(models.Permission.permission_id == permission_id).\
|
||||||
|
values(update_values)
|
||||||
|
|
||||||
|
await self._db_session.execute(query)
|
||||||
|
await self._db_session.commit()
|
||||||
|
permission_db = await self.get_permission(permission_id)
|
||||||
|
if permission_db:
|
||||||
|
await self._db_session.refresh(permission_db) # force refresh of updated_at value
|
||||||
|
return permission_db
|
||||||
|
|
||||||
|
async def delete_permission(self, permission_id: UUID) -> bool:
|
||||||
|
"""
|
||||||
|
Delete a permission.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = delete(models.Permission).where(models.Permission.permission_id == permission_id)
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
await self._db_session.commit()
|
||||||
|
return result.rowcount > 0
|
||||||
|
|
||||||
|
def _match_permission(
|
||||||
|
self,
|
||||||
|
permissions: List[models.Permission],
|
||||||
|
method: str,
|
||||||
|
path: str
|
||||||
|
) -> Union[None, models.Permission]:
|
||||||
|
"""
|
||||||
|
Match the methods and path with a permission.
|
||||||
|
"""
|
||||||
|
|
||||||
|
for permission in permissions:
|
||||||
|
log.debug(f"RBAC: checking permission {permission.methods} {permission.path} {permission.action}")
|
||||||
|
if method not in permission.methods:
|
||||||
|
continue
|
||||||
|
if permission.path.endswith("/*") and path.startswith(permission.path[:-2]):
|
||||||
|
return permission
|
||||||
|
elif permission.path == path:
|
||||||
|
return permission
|
||||||
|
|
||||||
|
async def get_user_permissions(self, user_id: UUID):
|
||||||
|
"""
|
||||||
|
Get all permissions from an user.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.Permission).\
|
||||||
|
join(models.User.permissions). \
|
||||||
|
filter(models.User.user_id == user_id).\
|
||||||
|
order_by(models.Permission.path)
|
||||||
|
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
return result.scalars().all()
|
||||||
|
|
||||||
|
async def add_permission_to_user(
|
||||||
|
self,
|
||||||
|
user_id: UUID,
|
||||||
|
permission: models.Permission
|
||||||
|
) -> Union[None, models.User]:
|
||||||
|
"""
|
||||||
|
Add a permission to an user.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.User).\
|
||||||
|
options(selectinload(models.User.permissions)).\
|
||||||
|
where(models.User.user_id == user_id)
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
user_db = result.scalars().first()
|
||||||
|
if not user_db:
|
||||||
|
return None
|
||||||
|
|
||||||
|
user_db.permissions.append(permission)
|
||||||
|
await self._db_session.commit()
|
||||||
|
await self._db_session.refresh(user_db)
|
||||||
|
return user_db
|
||||||
|
|
||||||
|
async def remove_permission_from_user(
|
||||||
|
self,
|
||||||
|
user_id: UUID,
|
||||||
|
permission: models.Permission
|
||||||
|
) -> Union[None, models.User]:
|
||||||
|
"""
|
||||||
|
Remove a permission from a role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.User).\
|
||||||
|
options(selectinload(models.User.permissions)).\
|
||||||
|
where(models.User.user_id == user_id)
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
user_db = result.scalars().first()
|
||||||
|
if not user_db:
|
||||||
|
return None
|
||||||
|
|
||||||
|
user_db.permissions.remove(permission)
|
||||||
|
await self._db_session.commit()
|
||||||
|
await self._db_session.refresh(user_db)
|
||||||
|
return user_db
|
||||||
|
|
||||||
|
async def add_permission_to_user_with_path(self, user_id: UUID, path: str) -> Union[None, models.User]:
|
||||||
|
"""
|
||||||
|
Add a permission to an user.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Create a new permission with full rights on path
|
||||||
|
new_permission = schemas.PermissionCreate(
|
||||||
|
description=f"Allow access to {path}",
|
||||||
|
methods=[HTTPMethods.get, HTTPMethods.head, HTTPMethods.post, HTTPMethods.put, HTTPMethods.delete],
|
||||||
|
path=path,
|
||||||
|
action=PermissionAction.allow
|
||||||
|
)
|
||||||
|
permission_db = await self.create_permission(new_permission)
|
||||||
|
|
||||||
|
# Add the permission to the user
|
||||||
|
query = select(models.User).\
|
||||||
|
options(selectinload(models.User.permissions)).\
|
||||||
|
where(models.User.user_id == user_id)
|
||||||
|
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
user_db = result.scalars().first()
|
||||||
|
if not user_db:
|
||||||
|
return None
|
||||||
|
|
||||||
|
user_db.permissions.append(permission_db)
|
||||||
|
await self._db_session.commit()
|
||||||
|
await self._db_session.refresh(user_db)
|
||||||
|
return user_db
|
||||||
|
|
||||||
|
async def delete_all_permissions_with_path(self, path: str) -> None:
|
||||||
|
"""
|
||||||
|
Delete all permissions with path.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = delete(models.Permission).\
|
||||||
|
where(models.Permission.path.startswith(path)).\
|
||||||
|
execution_options(synchronize_session=False)
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
log.debug(f"{result.rowcount} permission(s) have been deleted")
|
||||||
|
|
||||||
|
async def check_user_is_authorized(self, user_id: UUID, method: str, path: str) -> bool:
|
||||||
|
"""
|
||||||
|
Check if an user is authorized to access a resource.
|
||||||
|
"""
|
||||||
|
|
||||||
|
query = select(models.Permission).\
|
||||||
|
join(models.Permission.roles). \
|
||||||
|
join(models.Role.groups). \
|
||||||
|
join(models.UserGroup.users). \
|
||||||
|
filter(models.User.user_id == user_id).\
|
||||||
|
order_by(models.Permission.path)
|
||||||
|
|
||||||
|
result = await self._db_session.execute(query)
|
||||||
|
permissions = result.scalars().all()
|
||||||
|
log.debug(f"RBAC: checking authorization for user '{user_id}' on {method} '{path}'")
|
||||||
|
matched_permission = self._match_permission(permissions, method, path)
|
||||||
|
if matched_permission:
|
||||||
|
log.debug(f"RBAC: matched role permission {matched_permission.methods} "
|
||||||
|
f"{matched_permission.path} {matched_permission.action}")
|
||||||
|
if matched_permission.action == "DENY":
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
log.debug(f"RBAC: could not find a role permission, checking user permissions...")
|
||||||
|
permissions = await self.get_user_permissions(user_id)
|
||||||
|
matched_permission = self._match_permission(permissions, method, path)
|
||||||
|
if matched_permission:
|
||||||
|
log.debug(f"RBAC: matched user permission {matched_permission.methods} "
|
||||||
|
f"{matched_permission.path} {matched_permission.action}")
|
||||||
|
if matched_permission.action == "DENY":
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
@ -0,0 +1,121 @@
|
|||||||
|
#
|
||||||
|
# Copyright (C) 2020 GNS3 Technologies Inc.
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU General Public License as published by
|
||||||
|
# the Free Software Foundation, either version 3 of the License, or
|
||||||
|
# (at your option) any later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU General Public License for more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
from typing import Optional, List
|
||||||
|
from pydantic import BaseModel, validator
|
||||||
|
from uuid import UUID
|
||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
from .base import DateTimeModelMixin
|
||||||
|
|
||||||
|
|
||||||
|
class HTTPMethods(str, Enum):
|
||||||
|
"""
|
||||||
|
HTTP method type.
|
||||||
|
"""
|
||||||
|
|
||||||
|
get = "GET"
|
||||||
|
head = "HEAD"
|
||||||
|
post = "POST"
|
||||||
|
patch = "PATCH"
|
||||||
|
put = "PUT"
|
||||||
|
delete = "DELETE"
|
||||||
|
|
||||||
|
|
||||||
|
class PermissionAction(str, Enum):
|
||||||
|
"""
|
||||||
|
Action to perform when permission is matched.
|
||||||
|
"""
|
||||||
|
|
||||||
|
allow = "ALLOW"
|
||||||
|
deny = "DENY"
|
||||||
|
|
||||||
|
|
||||||
|
class PermissionBase(BaseModel):
|
||||||
|
"""
|
||||||
|
Common permission properties.
|
||||||
|
"""
|
||||||
|
|
||||||
|
methods: List[HTTPMethods]
|
||||||
|
path: str
|
||||||
|
action: PermissionAction
|
||||||
|
description: Optional[str] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
use_enum_values = True
|
||||||
|
|
||||||
|
@validator("action", pre=True)
|
||||||
|
def action_uppercase(cls, v):
|
||||||
|
return v.upper()
|
||||||
|
|
||||||
|
|
||||||
|
class PermissionCreate(PermissionBase):
|
||||||
|
"""
|
||||||
|
Properties to create a permission.
|
||||||
|
"""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class PermissionUpdate(PermissionBase):
|
||||||
|
"""
|
||||||
|
Properties to update a role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Permission(DateTimeModelMixin, PermissionBase):
|
||||||
|
|
||||||
|
permission_id: UUID
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
orm_mode = True
|
||||||
|
|
||||||
|
|
||||||
|
class RoleBase(BaseModel):
|
||||||
|
"""
|
||||||
|
Common role properties.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class RoleCreate(RoleBase):
|
||||||
|
"""
|
||||||
|
Properties to create a role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
|
||||||
|
|
||||||
|
class RoleUpdate(RoleBase):
|
||||||
|
"""
|
||||||
|
Properties to update a role.
|
||||||
|
"""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Role(DateTimeModelMixin, RoleBase):
|
||||||
|
|
||||||
|
role_id: UUID
|
||||||
|
builtin: bool
|
||||||
|
permissions: List[Permission]
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
orm_mode = True
|
@ -0,0 +1,83 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
#
|
||||||
|
# Copyright (C) 2021 GNS3 Technologies Inc.
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU General Public License as published by
|
||||||
|
# the Free Software Foundation, either version 3 of the License, or
|
||||||
|
# (at your option) any later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU General Public License for more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from fastapi import FastAPI, status
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from gns3server.db.repositories.rbac import RbacRepository
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.asyncio
|
||||||
|
|
||||||
|
|
||||||
|
class TestPermissionRoutes:
|
||||||
|
|
||||||
|
async def test_create_permission(self, app: FastAPI, client: AsyncClient) -> None:
|
||||||
|
|
||||||
|
new_permission = {
|
||||||
|
"methods": ["GET"],
|
||||||
|
"path": "/templates",
|
||||||
|
"action": "ALLOW"
|
||||||
|
}
|
||||||
|
response = await client.post(app.url_path_for("create_permission"), json=new_permission)
|
||||||
|
assert response.status_code == status.HTTP_201_CREATED
|
||||||
|
|
||||||
|
async def test_get_permission(self, app: FastAPI, client: AsyncClient, db_session: AsyncSession) -> None:
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
permission_in_db = await rbac_repo.get_permission_by_path("/templates")
|
||||||
|
response = await client.get(app.url_path_for("get_permission", permission_id=permission_in_db.permission_id))
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
assert response.json()["permission_id"] == str(permission_in_db.permission_id)
|
||||||
|
|
||||||
|
async def test_list_permissions(self, app: FastAPI, client: AsyncClient) -> None:
|
||||||
|
|
||||||
|
response = await client.get(app.url_path_for("get_permissions"))
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
assert len(response.json()) == 6 # 5 default permissions + 1 custom permission
|
||||||
|
|
||||||
|
async def test_update_permission(self, app: FastAPI, client: AsyncClient, db_session: AsyncSession) -> None:
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
permission_in_db = await rbac_repo.get_permission_by_path("/templates")
|
||||||
|
|
||||||
|
update_permission = {
|
||||||
|
"methods": ["GET"],
|
||||||
|
"path": "/appliances",
|
||||||
|
"action": "ALLOW"
|
||||||
|
}
|
||||||
|
response = await client.put(
|
||||||
|
app.url_path_for("update_permission", permission_id=permission_in_db.permission_id),
|
||||||
|
json=update_permission
|
||||||
|
)
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
updated_permission_in_db = await rbac_repo.get_permission(permission_in_db.permission_id)
|
||||||
|
assert updated_permission_in_db.path == "/appliances"
|
||||||
|
|
||||||
|
async def test_delete_permission(
|
||||||
|
self,
|
||||||
|
app: FastAPI,
|
||||||
|
client: AsyncClient,
|
||||||
|
db_session: AsyncSession
|
||||||
|
) -> None:
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
permission_in_db = await rbac_repo.get_permission_by_path("/appliances")
|
||||||
|
response = await client.delete(app.url_path_for("delete_permission", permission_id=permission_in_db.permission_id))
|
||||||
|
assert response.status_code == status.HTTP_204_NO_CONTENT
|
@ -0,0 +1,185 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
#
|
||||||
|
# Copyright (C) 2021 GNS3 Technologies Inc.
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU General Public License as published by
|
||||||
|
# the Free Software Foundation, either version 3 of the License, or
|
||||||
|
# (at your option) any later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU General Public License for more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from fastapi import FastAPI, status
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from gns3server.db.repositories.rbac import RbacRepository
|
||||||
|
from gns3server.schemas.controller.rbac import Permission, HTTPMethods, PermissionAction
|
||||||
|
from gns3server import schemas
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.asyncio
|
||||||
|
|
||||||
|
|
||||||
|
class TestRolesRoutes:
|
||||||
|
|
||||||
|
async def test_create_role(self, app: FastAPI, client: AsyncClient) -> None:
|
||||||
|
|
||||||
|
new_role = {"name": "role1"}
|
||||||
|
response = await client.post(app.url_path_for("create_role"), json=new_role)
|
||||||
|
assert response.status_code == status.HTTP_201_CREATED
|
||||||
|
|
||||||
|
async def test_get_role(self, app: FastAPI, client: AsyncClient, db_session: AsyncSession) -> None:
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
role_in_db = await rbac_repo.get_role_by_name("role1")
|
||||||
|
response = await client.get(app.url_path_for("get_role", role_id=role_in_db.role_id))
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
assert response.json()["role_id"] == str(role_in_db.role_id)
|
||||||
|
|
||||||
|
async def test_list_roles(self, app: FastAPI, client: AsyncClient) -> None:
|
||||||
|
|
||||||
|
response = await client.get(app.url_path_for("get_roles"))
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
assert len(response.json()) == 3 # 2 default roles + role1
|
||||||
|
|
||||||
|
async def test_update_role(self, app: FastAPI, client: AsyncClient, db_session: AsyncSession) -> None:
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
role_in_db = await rbac_repo.get_role_by_name("role1")
|
||||||
|
|
||||||
|
update_role = {"name": "role42"}
|
||||||
|
response = await client.put(
|
||||||
|
app.url_path_for("update_role", role_id=role_in_db.role_id),
|
||||||
|
json=update_role
|
||||||
|
)
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
updated_role_in_db = await rbac_repo.get_role(role_in_db.role_id)
|
||||||
|
assert updated_role_in_db.name == "role42"
|
||||||
|
|
||||||
|
async def test_cannot_update_builtin_user_role(
|
||||||
|
self,
|
||||||
|
app: FastAPI,
|
||||||
|
client: AsyncClient,
|
||||||
|
db_session: AsyncSession
|
||||||
|
) -> None:
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
role_in_db = await rbac_repo.get_role_by_name("User")
|
||||||
|
update_role = {"name": "Hackers"}
|
||||||
|
response = await client.put(
|
||||||
|
app.url_path_for("update_role", role_id=role_in_db.role_id),
|
||||||
|
json=update_role
|
||||||
|
)
|
||||||
|
assert response.status_code == status.HTTP_403_FORBIDDEN
|
||||||
|
|
||||||
|
async def test_delete_role(
|
||||||
|
self,
|
||||||
|
app: FastAPI,
|
||||||
|
client: AsyncClient,
|
||||||
|
db_session: AsyncSession
|
||||||
|
) -> None:
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
role_in_db = await rbac_repo.get_role_by_name("role42")
|
||||||
|
response = await client.delete(app.url_path_for("delete_role", role_id=role_in_db.role_id))
|
||||||
|
assert response.status_code == status.HTTP_204_NO_CONTENT
|
||||||
|
|
||||||
|
async def test_cannot_delete_builtin_administrator_role(
|
||||||
|
self,
|
||||||
|
app: FastAPI,
|
||||||
|
client: AsyncClient,
|
||||||
|
db_session: AsyncSession
|
||||||
|
) -> None:
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
role_in_db = await rbac_repo.get_role_by_name("Administrator")
|
||||||
|
response = await client.delete(app.url_path_for("delete_role", role_id=role_in_db.role_id))
|
||||||
|
assert response.status_code == status.HTTP_403_FORBIDDEN
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
async def test_permission(db_session: AsyncSession) -> Permission:
|
||||||
|
|
||||||
|
new_permission = schemas.PermissionCreate(
|
||||||
|
methods=[HTTPMethods.get],
|
||||||
|
path="/statistics",
|
||||||
|
action=PermissionAction.allow
|
||||||
|
)
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
existing_permission = await rbac_repo.get_permission_by_path("/statistics")
|
||||||
|
if existing_permission:
|
||||||
|
return existing_permission
|
||||||
|
return await rbac_repo.create_permission(new_permission)
|
||||||
|
|
||||||
|
|
||||||
|
class TestRolesPermissionsRoutes:
|
||||||
|
|
||||||
|
async def test_add_permission_to_role(
|
||||||
|
self,
|
||||||
|
app: FastAPI,
|
||||||
|
client: AsyncClient,
|
||||||
|
test_permission: Permission,
|
||||||
|
db_session: AsyncSession
|
||||||
|
) -> None:
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
role_in_db = await rbac_repo.get_role_by_name("User")
|
||||||
|
|
||||||
|
response = await client.put(
|
||||||
|
app.url_path_for(
|
||||||
|
"add_permission_to_role",
|
||||||
|
role_id=role_in_db.role_id,
|
||||||
|
permission_id=str(test_permission.permission_id)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert response.status_code == status.HTTP_204_NO_CONTENT
|
||||||
|
permissions = await rbac_repo.get_role_permissions(role_in_db.role_id)
|
||||||
|
assert len(permissions) == 5 # 4 default permissions + 1 custom permission
|
||||||
|
|
||||||
|
async def test_get_role_permissions(
|
||||||
|
self,
|
||||||
|
app: FastAPI,
|
||||||
|
client: AsyncClient,
|
||||||
|
db_session: AsyncSession
|
||||||
|
) -> None:
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
role_in_db = await rbac_repo.get_role_by_name("User")
|
||||||
|
|
||||||
|
response = await client.get(
|
||||||
|
app.url_path_for(
|
||||||
|
"get_role_permissions",
|
||||||
|
role_id=role_in_db.role_id)
|
||||||
|
)
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
assert len(response.json()) == 5 # 4 default permissions + 1 custom permission
|
||||||
|
|
||||||
|
async def test_remove_role_from_group(
|
||||||
|
self,
|
||||||
|
app: FastAPI,
|
||||||
|
client: AsyncClient,
|
||||||
|
test_permission: Permission,
|
||||||
|
db_session: AsyncSession
|
||||||
|
) -> None:
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
role_in_db = await rbac_repo.get_role_by_name("User")
|
||||||
|
|
||||||
|
response = await client.delete(
|
||||||
|
app.url_path_for(
|
||||||
|
"remove_permission_from_role",
|
||||||
|
role_id=role_in_db.role_id,
|
||||||
|
permission_id=str(test_permission.permission_id)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assert response.status_code == status.HTTP_204_NO_CONTENT
|
||||||
|
permissions = await rbac_repo.get_role_permissions(role_in_db.role_id)
|
||||||
|
assert len(permissions) == 4 # 4 default permissions
|
@ -0,0 +1,203 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
#
|
||||||
|
# Copyright (C) 2021 GNS3 Technologies Inc.
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU General Public License as published by
|
||||||
|
# the Free Software Foundation, either version 3 of the License, or
|
||||||
|
# (at your option) any later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU General Public License for more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from fastapi import FastAPI, status
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from gns3server.db.repositories.rbac import RbacRepository
|
||||||
|
from gns3server.db.models import User
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.asyncio
|
||||||
|
|
||||||
|
|
||||||
|
class TestPermissions:
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"method, path, result",
|
||||||
|
(
|
||||||
|
("GET", "/users", False),
|
||||||
|
("GET", "/projects", True),
|
||||||
|
("GET", "/projects/e451ad73-2519-4f83-87fe-a8e821792d44", False),
|
||||||
|
("POST", "/projects", True),
|
||||||
|
("GET", "/templates", True),
|
||||||
|
("GET", "/templates/62e92cf1-244a-4486-8dae-b95439b54da9", False),
|
||||||
|
("POST", "/templates", True),
|
||||||
|
("GET", "/computes", True),
|
||||||
|
("GET", "/computes/local", True),
|
||||||
|
("GET", "/symbols", True),
|
||||||
|
("GET", "/symbols/default_symbols", True),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
async def test_default_permissions_user_group(
|
||||||
|
self,
|
||||||
|
app: FastAPI,
|
||||||
|
authorized_client: AsyncClient,
|
||||||
|
test_user: User,
|
||||||
|
db_session: AsyncSession,
|
||||||
|
method: str,
|
||||||
|
path: str,
|
||||||
|
result: bool
|
||||||
|
) -> None:
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
authorized = await rbac_repo.check_user_is_authorized(test_user.user_id, method, path)
|
||||||
|
assert authorized == result
|
||||||
|
|
||||||
|
|
||||||
|
class TestProjectsWithRbac:
|
||||||
|
|
||||||
|
async def test_admin_create_project(self, app: FastAPI, client: AsyncClient):
|
||||||
|
|
||||||
|
params = {"name": "Admin project"}
|
||||||
|
response = await client.post(app.url_path_for("create_project"), json=params)
|
||||||
|
assert response.status_code == status.HTTP_201_CREATED
|
||||||
|
|
||||||
|
async def test_user_only_access_own_projects(
|
||||||
|
self,
|
||||||
|
app: FastAPI,
|
||||||
|
authorized_client: AsyncClient,
|
||||||
|
test_user: User,
|
||||||
|
db_session: AsyncSession
|
||||||
|
) -> None:
|
||||||
|
|
||||||
|
params = {"name": "User project"}
|
||||||
|
response = await authorized_client.post(app.url_path_for("create_project"), json=params)
|
||||||
|
assert response.status_code == status.HTTP_201_CREATED
|
||||||
|
project_id = response.json()["project_id"]
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
permissions_in_db = await rbac_repo.get_user_permissions(test_user.user_id)
|
||||||
|
assert len(permissions_in_db) == 1
|
||||||
|
assert permissions_in_db[0].path == f"/projects/{project_id}/*"
|
||||||
|
|
||||||
|
response = await authorized_client.get(app.url_path_for("get_projects"))
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
projects = response.json()
|
||||||
|
assert len(projects) == 1
|
||||||
|
|
||||||
|
async def test_admin_access_all_projects(self, app: FastAPI, client: AsyncClient):
|
||||||
|
|
||||||
|
response = await client.get(app.url_path_for("get_projects"))
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
projects = response.json()
|
||||||
|
assert len(projects) == 2
|
||||||
|
|
||||||
|
async def test_admin_user_give_permission_on_project(
|
||||||
|
self,
|
||||||
|
app: FastAPI,
|
||||||
|
client: AsyncClient,
|
||||||
|
test_user: User
|
||||||
|
):
|
||||||
|
|
||||||
|
response = await client.get(app.url_path_for("get_projects"))
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
projects = response.json()
|
||||||
|
project_id = None
|
||||||
|
for project in projects:
|
||||||
|
if project["name"] == "Admin project":
|
||||||
|
project_id = project["project_id"]
|
||||||
|
break
|
||||||
|
|
||||||
|
new_permission = {
|
||||||
|
"methods": ["GET"],
|
||||||
|
"path": f"/projects/{project_id}",
|
||||||
|
"action": "ALLOW"
|
||||||
|
}
|
||||||
|
response = await client.post(app.url_path_for("create_permission"), json=new_permission)
|
||||||
|
assert response.status_code == status.HTTP_201_CREATED
|
||||||
|
permission_id = response.json()["permission_id"]
|
||||||
|
|
||||||
|
response = await client.put(
|
||||||
|
app.url_path_for(
|
||||||
|
"add_permission_to_user",
|
||||||
|
user_id=test_user.user_id,
|
||||||
|
permission_id=permission_id
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert response.status_code == status.HTTP_204_NO_CONTENT
|
||||||
|
|
||||||
|
async def test_user_access_admin_project(
|
||||||
|
self,
|
||||||
|
app: FastAPI,
|
||||||
|
authorized_client: AsyncClient,
|
||||||
|
test_user: User,
|
||||||
|
db_session: AsyncSession
|
||||||
|
) -> None:
|
||||||
|
|
||||||
|
response = await authorized_client.get(app.url_path_for("get_projects"))
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
projects = response.json()
|
||||||
|
assert len(projects) == 2
|
||||||
|
|
||||||
|
|
||||||
|
class TestTemplatesWithRbac:
|
||||||
|
|
||||||
|
async def test_admin_create_template(self, app: FastAPI, client: AsyncClient):
|
||||||
|
|
||||||
|
new_template = {"base_script_file": "vpcs_base_config.txt",
|
||||||
|
"category": "guest",
|
||||||
|
"console_auto_start": False,
|
||||||
|
"console_type": "telnet",
|
||||||
|
"default_name_format": "PC{0}",
|
||||||
|
"name": "ADMIN_VPCS_TEMPLATE",
|
||||||
|
"compute_id": "local",
|
||||||
|
"symbol": ":/symbols/vpcs_guest.svg",
|
||||||
|
"template_type": "vpcs"}
|
||||||
|
|
||||||
|
response = await client.post(app.url_path_for("create_template"), json=new_template)
|
||||||
|
assert response.status_code == status.HTTP_201_CREATED
|
||||||
|
|
||||||
|
async def test_user_only_access_own_templates(
|
||||||
|
self, app: FastAPI,
|
||||||
|
authorized_client: AsyncClient,
|
||||||
|
test_user: User,
|
||||||
|
db_session: AsyncSession
|
||||||
|
) -> None:
|
||||||
|
|
||||||
|
new_template = {"base_script_file": "vpcs_base_config.txt",
|
||||||
|
"category": "guest",
|
||||||
|
"console_auto_start": False,
|
||||||
|
"console_type": "telnet",
|
||||||
|
"default_name_format": "PC{0}",
|
||||||
|
"name": "USER_VPCS_TEMPLATE",
|
||||||
|
"compute_id": "local",
|
||||||
|
"symbol": ":/symbols/vpcs_guest.svg",
|
||||||
|
"template_type": "vpcs"}
|
||||||
|
|
||||||
|
response = await authorized_client.post(app.url_path_for("create_template"), json=new_template)
|
||||||
|
assert response.status_code == status.HTTP_201_CREATED
|
||||||
|
template_id = response.json()["template_id"]
|
||||||
|
|
||||||
|
rbac_repo = RbacRepository(db_session)
|
||||||
|
permissions_in_db = await rbac_repo.get_user_permissions(test_user.user_id)
|
||||||
|
assert len(permissions_in_db) == 1
|
||||||
|
assert permissions_in_db[0].path == f"/templates/{template_id}/*"
|
||||||
|
|
||||||
|
response = await authorized_client.get(app.url_path_for("get_templates"))
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
templates = [template for template in response.json() if template["builtin"] is False]
|
||||||
|
assert len(templates) == 1
|
||||||
|
|
||||||
|
async def test_admin_access_all_templates(self, app: FastAPI, client: AsyncClient):
|
||||||
|
|
||||||
|
response = await client.get(app.url_path_for("get_templates"))
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
templates = [template for template in response.json() if template["builtin"] is False]
|
||||||
|
assert len(templates) == 2
|
Loading…
Reference in new issue