fix(instances): изоляция по владельцу для живых ресурсов Proxmox
Some checks failed
Deploy to Production / Trigger production update (push) Has been cancelled
Backend Tests / pytest (Python 3.12) (push) Has been cancelled

Список инстансов (/api/virtual-machines) уже фильтровался по owner_id, но
эндпоинты живых ресурсов Proxmox — /api/resources/all (дашборд) и
/api/{server_id}/resources (страница ноды/сервера) — отдавали все VM/LXC без
фильтра. Обычный пользователь (proxmox.view) через страницу ноды видел чужие
инстансы.

- _helpers: get_owned_vmids() — VMID, которыми владеет пользователь
- servers: get_server_resources / get_all_resources фильтруют VM/LXC по
  владельцу для не-привилегированных (сверка vmid с кэшем vm_instances);
  админы и роли с vm:manage видят всё
- assign_instances_owner.py: скрипт массового назначения владельца
  существующим инстансам (owner_id синхронизированных из Proxmox = NULL)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
markmorado
2026-07-22 04:56:17 +05:00
parent 25899866bc
commit 42c6acd52e
4 changed files with 154 additions and 5 deletions

View File

@@ -73,6 +73,24 @@ def require_vm_access(db: Session, current_user: User, server_id: int, vmid: int
)
def get_owned_vmids(db: Session, current_user: User, server_id: Optional[int] = None) -> set:
"""
Set of VMIDs the user owns (optionally scoped to a single Proxmox server).
Used to filter live Proxmox resource listings (which carry no owner
information) down to instances the tenant actually owns. Only meaningful for
non-privileged users — callers should skip filtering when
``can_view_all_instances`` is True.
"""
query = db.query(VMInstance.vmid).filter(
VMInstance.owner_id == current_user.id,
VMInstance.deleted_at.is_(None),
)
if server_id is not None:
query = query.filter(VMInstance.server_id == server_id)
return {row[0] for row in query.all()}
def _get_proxmox_client(server: ProxmoxServer) -> ProxmoxClient:
"""Build a ProxmoxClient from a ProxmoxServer model (password or token auth).

View File

@@ -18,7 +18,8 @@ from ...logging_service import LoggingService
from ...ipam_service import IPAMService
from ._helpers import (check_vm_access, require_vm_access, _get_proxmox_client,
get_next_vmid, archive_and_delete_snapshots,
save_vm_instance, get_vm_instance, soft_delete_vm_instance)
save_vm_instance, get_vm_instance, soft_delete_vm_instance,
can_view_all_instances, get_owned_vmids)
router = APIRouter()
@@ -510,7 +511,15 @@ def get_server_resources(
# Фильтруем шаблоны - они не должны считаться как VM
vms = [vm for vm in resources.get('vms', []) if not vm.get('template', 0)]
containers = [ct for ct in resources.get('containers', []) if not ct.get('template', 0)]
# Изоляция по владельцу: обычный пользователь видит на ноде только свои
# инстансы. Живые данные Proxmox не содержат owner_id, поэтому сверяемся
# с локальным кэшем vm_instances по vmid.
if not can_view_all_instances(current_user):
owned = get_owned_vmids(db, current_user, server_id)
vms = [vm for vm in vms if vm.get('vmid') in owned]
containers = [ct for ct in containers if ct.get('vmid') in owned]
# Получаем uptime ноды
node_uptime = None
try:
@@ -550,13 +559,16 @@ def get_all_resources(
):
"""API для получения всех ресурсов со всех Proxmox серверов"""
proxmox_servers = db.query(ProxmoxServer).all()
# Обычный пользователь видит только свои инстансы во всех агрегатах.
is_privileged = can_view_all_instances(current_user)
all_resources = {
"servers": [],
"total_vms": 0,
"total_containers": 0
}
for server in proxmox_servers:
try:
logger.info(f"Getting resources from server {server.name}, use_password={server.use_password}")
@@ -580,7 +592,13 @@ def get_all_resources(
vms = resources.get('vms', [])
containers = resources.get('containers', [])
# Изоляция по владельцу (живые данные Proxmox не содержат owner_id).
if not is_privileged:
owned = get_owned_vmids(db, current_user, server.id)
vms = [vm for vm in vms if vm.get('vmid') in owned]
containers = [ct for ct in containers if ct.get('vmid') in owned]
logger.info(f"Got {len(vms)} VMs and {len(containers)} containers from {server.name}")
server.update_status(True)