diff --git a/backend/app/api/proxmox/iso_vm.py b/backend/app/api/proxmox/iso_vm.py index c3c054f..81f3a5b 100644 --- a/backend/app/api/proxmox/iso_vm.py +++ b/backend/app/api/proxmox/iso_vm.py @@ -316,6 +316,11 @@ async def create_vm_from_iso( raise HTTPException(status_code=404, detail="Proxmox сервер не найден") if not req.name.strip(): raise HTTPException(status_code=400, detail="Укажите имя ВМ") + from ...schemas import validate_instance_name + try: + req.name = validate_instance_name(req.name) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) if not req.node: raise HTTPException(status_code=400, detail="Укажите ноду для размещения ВМ") if not req.iso: diff --git a/backend/app/api/proxmox/lxc.py b/backend/app/api/proxmox/lxc.py index fd5544e..a041b7d 100644 --- a/backend/app/api/proxmox/lxc.py +++ b/backend/app/api/proxmox/lxc.py @@ -447,6 +447,11 @@ async def deploy_lxc_from_template( raise HTTPException(status_code=400, detail="Необходимо указать ostemplate") if not req.name or len(req.name) < 1: raise HTTPException(status_code=400, detail="Укажите имя контейнера") + from ...schemas import validate_instance_name + try: + req.name = validate_instance_name(req.name) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) # Resolve owner / SSH keys is_admin = current_user.has_permission("user:manage") or current_user.is_admin diff --git a/backend/app/api/templates.py b/backend/app/api/templates.py index 909662f..fac1aec 100644 --- a/backend/app/api/templates.py +++ b/backend/app/api/templates.py @@ -1072,6 +1072,12 @@ async def deploy_vm_from_template( raise HTTPException(status_code=404, detail="Owner user not found") instance_owner_id = owner.id + from ..schemas import validate_instance_name + try: + deploy_data.name = validate_instance_name(deploy_data.name) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + # Enforce per-user resource quota (no-op if owner has no quota set) from ..services.quota_service import check_quota check_quota(db, instance_owner_id, add_cores=cores, add_memory_mb=memory, add_disk_gb=disk) diff --git a/backend/app/schemas.py b/backend/app/schemas.py index 39665db..e7cabed 100644 --- a/backend/app/schemas.py +++ b/backend/app/schemas.py @@ -8,6 +8,30 @@ from pydantic import BaseModel, Field, field_validator, model_validator, EmailSt _HOSTNAME_LABEL_RE = re.compile(r'^(?!-)[A-Za-z0-9-]{1,63}(? str: + """Validate that an instance name is a valid DNS label (RFC 952 / RFC 1123). + + Proxmox requires VM/CT names to be valid DNS names: start with a letter, + contain only letters, digits and hyphens, end with a letter or digit, + max 63 characters. Underscores, spaces and other special characters are + rejected. + """ + name = name.strip() + if not name: + raise ValueError("Имя не может быть пустым") + if len(name) > 63: + raise ValueError("Имя не может быть длиннее 63 символов") + if not _DNS_NAME_RE.match(name): + raise ValueError( + "Имя должно быть валидным DNS-именем: начинаться с буквы, " + "содержать только латинские буквы, цифры и дефис, " + "заканчиваться буквой или цифрой" + ) + return name + def validate_host(v: str) -> str: """Validate that value is a valid IP address or hostname/FQDN.""" diff --git a/frontend/src/features/instances/CreateInstanceWizard.tsx b/frontend/src/features/instances/CreateInstanceWizard.tsx index 3dc45bd..5cd2c79 100644 --- a/frontend/src/features/instances/CreateInstanceWizard.tsx +++ b/frontend/src/features/instances/CreateInstanceWizard.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useState, useRef } from 'react'; import { useNavigate } from 'react-router'; import { useTranslation } from 'react-i18next'; import { useMutation } from '@tanstack/react-query'; @@ -32,6 +32,39 @@ import { import { toast } from 'sonner'; type InstanceKind = 'vm' | 'lxc' | 'iso'; + +const DNS_NAME_RE = /^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/; +function isValidDnsName(name: string): boolean { + return name.length > 0 && name.length <= 63 && DNS_NAME_RE.test(name); +} + +function NumericInput({ value, onChange, ...props }: Omit, 'value' | 'onChange'> & { + value: number; + onChange: (n: number) => void; +}) { + const [raw, setRaw] = useState(String(value)); + const committed = useRef(value); + if (value !== committed.current) { + committed.current = value; + setRaw(String(value)); + } + return ( + { + setRaw(e.target.value); + const n = e.target.value === '' ? 0 : Number(e.target.value); + if (!Number.isNaN(n)) { + committed.current = n; + onChange(n); + } + }} + /> + ); +} + const STEPS = ['server', 'type', 'template', 'config', 'confirm'] as const; type Step = (typeof STEPS)[number]; @@ -235,9 +268,9 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void return !!selectedLXCTemplate; } if (step === 'config') { - if (kind === 'vm') return config.name.length >= 2; - if (kind === 'iso') return isoConfig.name.length >= 2; - return lxcConfig.name.length >= 2; + if (kind === 'vm') return isValidDnsName(config.name) && !!config.cloud_init_user.trim() && !!config.cloud_init_password.trim(); + if (kind === 'iso') return isValidDnsName(isoConfig.name); + return isValidDnsName(lxcConfig.name); } return true; }; @@ -689,6 +722,9 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void
setConfig(p => ({ ...p, name: e.target.value }))} placeholder={t('common.placeholder_vm_name')} /> + {config.name && !isValidDnsName(config.name) && ( +

{t('wizard.invalid_name')}

+ )}
@@ -719,30 +755,27 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void
- setConfig(p => ({ ...p, cores: Number(e.target.value) }))} + onChange={v => setConfig(p => ({ ...p, cores: v }))} />
- setConfig(p => ({ ...p, memory: Number(e.target.value) }))} + onChange={v => setConfig(p => ({ ...p, memory: v }))} />
- setConfig(p => ({ ...p, disk: Number(e.target.value) }))} + onChange={v => setConfig(p => ({ ...p, disk: v }))} />
@@ -799,12 +832,22 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void Cloud-Init
- - setConfig(p => ({ ...p, cloud_init_user: e.target.value }))} placeholder={t('common.placeholder_ubuntu')} /> + + setConfig(p => ({ ...p, cloud_init_user: e.target.value }))} + placeholder={t('common.placeholder_ubuntu')} + className={!config.cloud_init_user.trim() ? 'border-destructive' : ''} + />
- - setConfig(p => ({ ...p, cloud_init_password: e.target.value }))} /> + + setConfig(p => ({ ...p, cloud_init_password: e.target.value }))} + className={!config.cloud_init_password.trim() ? 'border-destructive' : ''} + />
{isAdmin && ( void
setIsoConfig(p => ({ ...p, name: e.target.value }))} placeholder={t('common.placeholder_vm_name')} /> + {isoConfig.name && !isValidDnsName(isoConfig.name) && ( +

{t('wizard.invalid_name')}

+ )}
@@ -887,15 +933,15 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void
- setIsoConfig(p => ({ ...p, cores: Number(e.target.value) }))} /> + setIsoConfig(p => ({ ...p, cores: v }))} />
- setIsoConfig(p => ({ ...p, memory: Number(e.target.value) }))} /> + setIsoConfig(p => ({ ...p, memory: v }))} />
- setIsoConfig(p => ({ ...p, disk: Number(e.target.value) }))} /> + setIsoConfig(p => ({ ...p, disk: v }))} />
@@ -1018,6 +1064,9 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void onChange={e => setLxcConfig(p => ({ ...p, name: e.target.value }))} placeholder={t('common.placeholder_vm_name')} /> + {lxcConfig.name && !isValidDnsName(lxcConfig.name) && ( +

{t('wizard.invalid_name')}

+ )}
@@ -1056,19 +1105,19 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void
- setLxcConfig(p => ({ ...p, cores: Number(e.target.value) }))} /> + setLxcConfig(p => ({ ...p, cores: v }))} />
- setLxcConfig(p => ({ ...p, memory: Number(e.target.value) }))} /> + setLxcConfig(p => ({ ...p, memory: v }))} />
- setLxcConfig(p => ({ ...p, swap: Number(e.target.value) }))} /> + setLxcConfig(p => ({ ...p, swap: v }))} />
- setLxcConfig(p => ({ ...p, disk: Number(e.target.value) }))} /> + setLxcConfig(p => ({ ...p, disk: v }))} />
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json index de8129f..75edc2e 100644 --- a/frontend/src/locales/en.json +++ b/frontend/src/locales/en.json @@ -755,7 +755,8 @@ "quota_exceeded_hint": "Reduce the resources above to continue.", "quota_used_of": "{{used}} of {{limit}}", "quota_projection_note": "Including the instance being created.", - "ip_cidr_placeholder": "10.10.10.5/24 or dhcp" + "ip_cidr_placeholder": "10.10.10.5/24 or dhcp", + "invalid_name": "Name must be a valid DNS name: start with a letter, contain only letters, digits and hyphens, end with a letter or digit (e.g. my-app-01)" }, "nodes": { "title": "Servers", diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json index b39f6b7..4fdd6e3 100644 --- a/frontend/src/locales/ru.json +++ b/frontend/src/locales/ru.json @@ -754,7 +754,8 @@ "quota_exceeded_hint": "Уменьшите ресурсы выше, чтобы продолжить.", "quota_used_of": "{{used}} из {{limit}}", "quota_projection_note": "С учётом создаваемого инстанса.", - "ip_cidr_placeholder": "10.10.10.5/24 или dhcp" + "ip_cidr_placeholder": "10.10.10.5/24 или dhcp", + "invalid_name": "Имя должно быть валидным DNS-именем: начинаться с буквы, содержать только латинские буквы, цифры и дефис, заканчиваться буквой или цифрой (например, my-app-01)" }, "nodes": { "title": "Серверы",