fix: validate instance name as DNS label and improve wizard UX
Some checks failed
Backend Tests / pytest (Python 3.12) (push) Failing after 1m23s
Deploy to Production / Trigger production update (push) Failing after 10s

Add DNS name validation (RFC 952/1123) for VM, LXC and ISO instance
names on both backend and frontend. Proxmox rejects names with
underscores or special characters but the error was only surfaced as
a raw 400 from the API.

Also require Cloud-Init user and password fields for VM deploys
(highlighted when empty, Next button blocked), and fix numeric input
fields that showed "0" on clear and concatenated values like "04096".
This commit is contained in:
2026-08-17 16:24:55 +05:00
parent 0220f338db
commit 8cbba05dac
7 changed files with 117 additions and 26 deletions

View File

@@ -316,6 +316,11 @@ async def create_vm_from_iso(
raise HTTPException(status_code=404, detail="Proxmox сервер не найден") raise HTTPException(status_code=404, detail="Proxmox сервер не найден")
if not req.name.strip(): if not req.name.strip():
raise HTTPException(status_code=400, detail="Укажите имя ВМ") 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: if not req.node:
raise HTTPException(status_code=400, detail="Укажите ноду для размещения ВМ") raise HTTPException(status_code=400, detail="Укажите ноду для размещения ВМ")
if not req.iso: if not req.iso:

View File

@@ -447,6 +447,11 @@ async def deploy_lxc_from_template(
raise HTTPException(status_code=400, detail="Необходимо указать ostemplate") raise HTTPException(status_code=400, detail="Необходимо указать ostemplate")
if not req.name or len(req.name) < 1: if not req.name or len(req.name) < 1:
raise HTTPException(status_code=400, detail="Укажите имя контейнера") 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 # Resolve owner / SSH keys
is_admin = current_user.has_permission("user:manage") or current_user.is_admin is_admin = current_user.has_permission("user:manage") or current_user.is_admin

View File

@@ -1072,6 +1072,12 @@ async def deploy_vm_from_template(
raise HTTPException(status_code=404, detail="Owner user not found") raise HTTPException(status_code=404, detail="Owner user not found")
instance_owner_id = owner.id 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) # Enforce per-user resource quota (no-op if owner has no quota set)
from ..services.quota_service import check_quota from ..services.quota_service import check_quota
check_quota(db, instance_owner_id, add_cores=cores, add_memory_mb=memory, add_disk_gb=disk) check_quota(db, instance_owner_id, add_cores=cores, add_memory_mb=memory, add_disk_gb=disk)

View File

@@ -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}(?<!-)$') _HOSTNAME_LABEL_RE = re.compile(r'^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$')
_DNS_NAME_RE = re.compile(r'^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$')
def validate_instance_name(name: str) -> 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: def validate_host(v: str) -> str:
"""Validate that value is a valid IP address or hostname/FQDN.""" """Validate that value is a valid IP address or hostname/FQDN."""

View File

@@ -1,4 +1,4 @@
import { useState } from 'react'; import { useState, useRef } from 'react';
import { useNavigate } from 'react-router'; import { useNavigate } from 'react-router';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useMutation } from '@tanstack/react-query'; import { useMutation } from '@tanstack/react-query';
@@ -32,6 +32,39 @@ import {
import { toast } from 'sonner'; import { toast } from 'sonner';
type InstanceKind = 'vm' | 'lxc' | 'iso'; 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<React.ComponentProps<typeof Input>, '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 (
<Input
{...props}
type="number"
value={raw}
onChange={e => {
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; const STEPS = ['server', 'type', 'template', 'config', 'confirm'] as const;
type Step = (typeof STEPS)[number]; type Step = (typeof STEPS)[number];
@@ -235,9 +268,9 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void
return !!selectedLXCTemplate; return !!selectedLXCTemplate;
} }
if (step === 'config') { if (step === 'config') {
if (kind === 'vm') return config.name.length >= 2; if (kind === 'vm') return isValidDnsName(config.name) && !!config.cloud_init_user.trim() && !!config.cloud_init_password.trim();
if (kind === 'iso') return isoConfig.name.length >= 2; if (kind === 'iso') return isValidDnsName(isoConfig.name);
return lxcConfig.name.length >= 2; return isValidDnsName(lxcConfig.name);
} }
return true; return true;
}; };
@@ -689,6 +722,9 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void
<div> <div>
<Label>{t('common.name')}</Label> <Label>{t('common.name')}</Label>
<Input value={config.name} onChange={e => setConfig(p => ({ ...p, name: e.target.value }))} placeholder={t('common.placeholder_vm_name')} /> <Input value={config.name} onChange={e => setConfig(p => ({ ...p, name: e.target.value }))} placeholder={t('common.placeholder_vm_name')} />
{config.name && !isValidDnsName(config.name) && (
<p className="mt-1 text-xs text-destructive">{t('wizard.invalid_name')}</p>
)}
</div> </div>
<div> <div>
<Label>{t('wizard.target_node')}</Label> <Label>{t('wizard.target_node')}</Label>
@@ -719,30 +755,27 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void
<CardContent className="space-y-3"> <CardContent className="space-y-3">
<div> <div>
<Label>vCPU</Label> <Label>vCPU</Label>
<Input <NumericInput
type="number"
min={selectedTemplate?.min_cores || 1} min={selectedTemplate?.min_cores || 1}
value={config.cores} value={config.cores}
onChange={e => setConfig(p => ({ ...p, cores: Number(e.target.value) }))} onChange={v => setConfig(p => ({ ...p, cores: v }))}
/> />
</div> </div>
<div> <div>
<Label>{t('wizard.memory_mb')}</Label> <Label>{t('wizard.memory_mb')}</Label>
<Input <NumericInput
type="number"
min={selectedTemplate?.min_memory || 256} min={selectedTemplate?.min_memory || 256}
step={256} step={256}
value={config.memory} value={config.memory}
onChange={e => setConfig(p => ({ ...p, memory: Number(e.target.value) }))} onChange={v => setConfig(p => ({ ...p, memory: v }))}
/> />
</div> </div>
<div> <div>
<Label>{t('wizard.disk_gb')}</Label> <Label>{t('wizard.disk_gb')}</Label>
<Input <NumericInput
type="number"
min={selectedTemplate?.min_disk || 5} min={selectedTemplate?.min_disk || 5}
value={config.disk} value={config.disk}
onChange={e => setConfig(p => ({ ...p, disk: Number(e.target.value) }))} onChange={v => setConfig(p => ({ ...p, disk: v }))}
/> />
</div> </div>
<div> <div>
@@ -799,12 +832,22 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void
<CardHeader className="pb-3"><CardTitle className="text-sm">Cloud-Init</CardTitle></CardHeader> <CardHeader className="pb-3"><CardTitle className="text-sm">Cloud-Init</CardTitle></CardHeader>
<CardContent className="space-y-3"> <CardContent className="space-y-3">
<div> <div>
<Label>{t('wizard.ci_user')}</Label> <Label>{t('wizard.ci_user')} <span className="text-destructive">*</span></Label>
<Input value={config.cloud_init_user} onChange={e => setConfig(p => ({ ...p, cloud_init_user: e.target.value }))} placeholder={t('common.placeholder_ubuntu')} /> <Input
value={config.cloud_init_user}
onChange={e => setConfig(p => ({ ...p, cloud_init_user: e.target.value }))}
placeholder={t('common.placeholder_ubuntu')}
className={!config.cloud_init_user.trim() ? 'border-destructive' : ''}
/>
</div> </div>
<div> <div>
<Label>{t('wizard.ci_password')}</Label> <Label>{t('wizard.ci_password')} <span className="text-destructive">*</span></Label>
<Input type="password" value={config.cloud_init_password} onChange={e => setConfig(p => ({ ...p, cloud_init_password: e.target.value }))} /> <Input
type="password"
value={config.cloud_init_password}
onChange={e => setConfig(p => ({ ...p, cloud_init_password: e.target.value }))}
className={!config.cloud_init_password.trim() ? 'border-destructive' : ''}
/>
</div> </div>
{isAdmin && ( {isAdmin && (
<SSHOwnerSelector <SSHOwnerSelector
@@ -844,6 +887,9 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void
<div> <div>
<Label>{t('common.name')}</Label> <Label>{t('common.name')}</Label>
<Input value={isoConfig.name} onChange={e => setIsoConfig(p => ({ ...p, name: e.target.value }))} placeholder={t('common.placeholder_vm_name')} /> <Input value={isoConfig.name} onChange={e => setIsoConfig(p => ({ ...p, name: e.target.value }))} placeholder={t('common.placeholder_vm_name')} />
{isoConfig.name && !isValidDnsName(isoConfig.name) && (
<p className="mt-1 text-xs text-destructive">{t('wizard.invalid_name')}</p>
)}
</div> </div>
<div> <div>
<Label>{t('wizard.os_type')}</Label> <Label>{t('wizard.os_type')}</Label>
@@ -887,15 +933,15 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void
<CardContent className="space-y-3"> <CardContent className="space-y-3">
<div> <div>
<Label>vCPU</Label> <Label>vCPU</Label>
<Input type="number" min={1} value={isoConfig.cores} onChange={e => setIsoConfig(p => ({ ...p, cores: Number(e.target.value) }))} /> <NumericInput min={1} value={isoConfig.cores} onChange={v => setIsoConfig(p => ({ ...p, cores: v }))} />
</div> </div>
<div> <div>
<Label>{t('wizard.memory_mb')}</Label> <Label>{t('wizard.memory_mb')}</Label>
<Input type="number" min={256} step={256} value={isoConfig.memory} onChange={e => setIsoConfig(p => ({ ...p, memory: Number(e.target.value) }))} /> <NumericInput min={256} step={256} value={isoConfig.memory} onChange={v => setIsoConfig(p => ({ ...p, memory: v }))} />
</div> </div>
<div> <div>
<Label>{t('wizard.disk_gb')}</Label> <Label>{t('wizard.disk_gb')}</Label>
<Input type="number" min={1} value={isoConfig.disk} onChange={e => setIsoConfig(p => ({ ...p, disk: Number(e.target.value) }))} /> <NumericInput min={1} value={isoConfig.disk} onChange={v => setIsoConfig(p => ({ ...p, disk: v }))} />
</div> </div>
<div> <div>
<Label>{t('wizard.storage')}</Label> <Label>{t('wizard.storage')}</Label>
@@ -1018,6 +1064,9 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void
onChange={e => setLxcConfig(p => ({ ...p, name: e.target.value }))} onChange={e => setLxcConfig(p => ({ ...p, name: e.target.value }))}
placeholder={t('common.placeholder_vm_name')} placeholder={t('common.placeholder_vm_name')}
/> />
{lxcConfig.name && !isValidDnsName(lxcConfig.name) && (
<p className="mt-1 text-xs text-destructive">{t('wizard.invalid_name')}</p>
)}
</div> </div>
<div> <div>
<Label>{t('wizard.storage')}</Label> <Label>{t('wizard.storage')}</Label>
@@ -1056,19 +1105,19 @@ export default function CreateInstanceWizard({ onClose }: { onClose?: () => void
<CardContent className="space-y-3"> <CardContent className="space-y-3">
<div> <div>
<Label>vCPU</Label> <Label>vCPU</Label>
<Input type="number" min={1} value={lxcConfig.cores} onChange={e => setLxcConfig(p => ({ ...p, cores: Number(e.target.value) }))} /> <NumericInput min={1} value={lxcConfig.cores} onChange={v => setLxcConfig(p => ({ ...p, cores: v }))} />
</div> </div>
<div> <div>
<Label>{t('wizard.memory_mb')}</Label> <Label>{t('wizard.memory_mb')}</Label>
<Input type="number" min={64} step={128} value={lxcConfig.memory} onChange={e => setLxcConfig(p => ({ ...p, memory: Number(e.target.value) }))} /> <NumericInput min={64} step={128} value={lxcConfig.memory} onChange={v => setLxcConfig(p => ({ ...p, memory: v }))} />
</div> </div>
<div> <div>
<Label>{t('wizard.swap_mb')}</Label> <Label>{t('wizard.swap_mb')}</Label>
<Input type="number" min={0} step={128} value={lxcConfig.swap} onChange={e => setLxcConfig(p => ({ ...p, swap: Number(e.target.value) }))} /> <NumericInput min={0} step={128} value={lxcConfig.swap} onChange={v => setLxcConfig(p => ({ ...p, swap: v }))} />
</div> </div>
<div> <div>
<Label>{t('wizard.disk_gb')}</Label> <Label>{t('wizard.disk_gb')}</Label>
<Input type="number" min={1} value={lxcConfig.disk} onChange={e => setLxcConfig(p => ({ ...p, disk: Number(e.target.value) }))} /> <NumericInput min={1} value={lxcConfig.disk} onChange={v => setLxcConfig(p => ({ ...p, disk: v }))} />
</div> </div>
</CardContent> </CardContent>
</Card> </Card>

View File

@@ -755,7 +755,8 @@
"quota_exceeded_hint": "Reduce the resources above to continue.", "quota_exceeded_hint": "Reduce the resources above to continue.",
"quota_used_of": "{{used}} of {{limit}}", "quota_used_of": "{{used}} of {{limit}}",
"quota_projection_note": "Including the instance being created.", "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": { "nodes": {
"title": "Servers", "title": "Servers",

View File

@@ -754,7 +754,8 @@
"quota_exceeded_hint": "Уменьшите ресурсы выше, чтобы продолжить.", "quota_exceeded_hint": "Уменьшите ресурсы выше, чтобы продолжить.",
"quota_used_of": "{{used}} из {{limit}}", "quota_used_of": "{{used}} из {{limit}}",
"quota_projection_note": "С учётом создаваемого инстанса.", "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": { "nodes": {
"title": "Серверы", "title": "Серверы",