Compare commits

...

14 Commits

Author SHA1 Message Date
Meng Meng a28ae727f3 Merge pull request #37 from LusineStar/fix/windows-firstlogon-drive-scan
fix(kvm): Windows 首启脚本盘符扫描的批处理语法错误,导致 RDP/入站端口全被丢弃
2026-07-26 21:47:11 +08:00
LusineStar 57d6b19c05 fix(kvm): correct Windows FirstLogon drive-scan batch syntax
The unattend FirstLogonCommands runs via 'cmd.exe /c' (command-line context),
where a FOR loop variable must be %d, not the batch-file form %%d. The %%d
form raised '%%d was unexpected at this time', so the else branch that locates
and runs FirstLogon.ps1 from the unattend ISO never executed.

Combined with $OEM$ not being processed from a separate ISO (so
C:\CLICD\FirstLogon.ps1 is never staged), the entire Windows post-install
init was skipped: RDP was never enabled, the firewall was never opened, and
the network profile stayed Public, so the guest dropped all inbound traffic.
The host NAT DNAT for 3389 was correct, but the guest silently dropped it,
making the mapping appear to have no effect.
2026-07-26 21:42:06 +08:00
Meng Meng bae028ade4 Merge pull request #36 from MengMengCode/copilot/fix-code-scanning-alerts-146
Triage CodeQL alert #146 as false positive (go/request-forgery)
2026-07-26 04:49:15 +08:00
copilot-swe-agent[bot] 2188bddb93 Initial plan 2026-07-25 20:46:03 +00:00
MengMengCode 79de3d5552 Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-07-26 04:39:02 +08:00
MengMengCode 70679b6fbb feat: upgrade Node.js version and update dependencies for frontend and docs 2026-07-26 04:38:56 +08:00
Meng Meng d739dcbaa4 Merge pull request #35 from MengMengCode/dependabot/npm_and_yarn/docs/postcss-8.5.23
build(deps-dev): bump postcss from 8.5.15 to 8.5.23 in /docs
2026-07-26 04:25:22 +08:00
dependabot[bot] 9eaf5002df build(deps-dev): bump postcss from 8.5.15 to 8.5.23 in /docs
Bumps [postcss](https://github.com/postcss/postcss) from 8.5.15 to 8.5.23.
- [Release notes](https://github.com/postcss/postcss/releases)
- [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss/compare/8.5.15...8.5.23)

---
updated-dependencies:
- dependency-name: postcss
  dependency-version: 8.5.23
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-25 20:23:42 +00:00
MengMengCode 73433c035d release: v1.1.28 2026-07-26 04:22:32 +08:00
MengMengCode 5474991a6d feat: implement safe HTTP client and URL validation for secure downloads 2026-07-26 04:19:38 +08:00
MengMengCode 37b16b83a5 Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-07-26 04:04:52 +08:00
MengMengCode 38debab1aa Add custom image handling and access policy management
- Implement tests for custom KVM and LXC image creation, ensuring invalid sources and architecture mismatches are rejected.
- Introduce access policy management in CLI, allowing configuration of allowed sources and trusted proxies.
- Add NAT network configuration with validation for RFC1918 compliance and subnet parsing.
- Create panel access policy management, including normalization and evaluation of access decisions based on client IPs and forwarded headers.
- Develop middleware for enforcing access policies in the server, returning appropriate responses for allowed and denied requests.
- Enhance custom image downloading and validation, ensuring integrity and security of downloaded root filesystem archives.
- Include comprehensive tests for all new functionalities to ensure reliability and correctness.
2026-07-26 04:04:45 +08:00
Meng Meng 24204609a1 Merge pull request #34 from MengMengCode/dependabot/npm_and_yarn/frontend/multi-92d8ff70db
build(deps): bump react-router and react-router-dom in /frontend
2026-07-24 19:21:40 +08:00
dependabot[bot] deedf86c22 build(deps): bump react-router and react-router-dom in /frontend
Bumps [react-router](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router) to 7.18.1 and updates ancestor dependency [react-router-dom](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router-dom). These dependencies need to be updated together.


Updates `react-router` from 6.30.4 to 7.18.1
- [Release notes](https://github.com/remix-run/react-router/releases)
- [Changelog](https://github.com/remix-run/react-router/blob/react-router@7.18.1/packages/react-router/CHANGELOG.md)
- [Commits](https://github.com/remix-run/react-router/commits/react-router@7.18.1/packages/react-router)

Updates `react-router-dom` from 6.30.4 to 7.18.1
- [Release notes](https://github.com/remix-run/react-router/releases)
- [Changelog](https://github.com/remix-run/react-router/blob/react-router-dom@7.18.1/packages/react-router-dom/CHANGELOG.md)
- [Commits](https://github.com/remix-run/react-router/commits/react-router-dom@7.18.1/packages/react-router-dom)

---
updated-dependencies:
- dependency-name: react-router
  dependency-version: 7.18.1
  dependency-type: indirect
- dependency-name: react-router-dom
  dependency-version: 7.18.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-24 11:03:57 +00:00
68 changed files with 4974 additions and 429 deletions
+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
node-version: "22.22.0"
cache: npm
cache-dependency-path: |
frontend/package-lock.json
+1 -1
View File
@@ -30,7 +30,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
node-version: "22.22.0"
cache: npm
cache-dependency-path: docs/package-lock.json
+1
View File
@@ -72,3 +72,4 @@ backend/clicd
api.md
deploy-arm.ps1
deploy-dhcp.ps1
deploy-pve-windows.ps1
+94
View File
@@ -0,0 +1,94 @@
package api
import (
"encoding/json"
"net/http"
"strings"
"clicd/internal/config"
)
type panelAccessPolicyResponse struct {
Enabled bool `json:"enabled"`
AllowedSources []string `json:"allowed_sources"`
TrustedProxies []string `json:"trusted_proxies"`
CurrentSource string `json:"current_source"`
DirectSource string `json:"direct_source"`
UsingForwarded bool `json:"using_forwarded"`
}
func HandlePanelAccessPolicy(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: panelAccessPolicyStatus(r, config.AppConfig.PanelAccessPolicy)})
case http.MethodPut:
updatePanelAccessPolicy(w, r)
default:
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
}
}
func updatePanelAccessPolicy(w http.ResponseWriter, r *http.Request) {
var requested config.PanelAccessPolicy
if err := json.NewDecoder(r.Body).Decode(&requested); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
normalized, err := config.NormalizePanelAccessPolicy(requested)
if err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
decision := evaluatePanelRequest(r, normalized)
if normalized.Enabled && !decision.Allowed {
jsonResponse(w, http.StatusBadRequest, APIResponse{
Success: false,
Message: "The new access policy does not allow your current source address " + decision.CurrentSource,
})
return
}
previous := config.AppConfig.PanelAccessPolicy
config.AppConfig.PanelAccessPolicy = normalized
if err := config.SaveConfig(); err != nil {
config.AppConfig.PanelAccessPolicy = previous
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to save panel access policy"})
return
}
detail := "enabled=" + strings.ToLower(strings.TrimSpace(boolText(normalized.Enabled))) +
",allowed=" + strings.Join(normalized.AllowedSources, ",") +
",trusted_proxies=" + strings.Join(normalized.TrustedProxies, ",")
auditRequest(r, "settings.panel_access", "Panel access policy", detail, true, "")
jsonResponse(w, http.StatusOK, APIResponse{
Success: true,
Message: "Panel access policy saved",
Data: panelAccessPolicyStatus(r, normalized),
})
}
func panelAccessPolicyStatus(r *http.Request, policy config.PanelAccessPolicy) panelAccessPolicyResponse {
decision := evaluatePanelRequest(r, policy)
return panelAccessPolicyResponse{
Enabled: policy.Enabled,
AllowedSources: append([]string(nil), policy.AllowedSources...),
TrustedProxies: append([]string(nil), policy.TrustedProxies...),
CurrentSource: decision.CurrentSource,
DirectSource: decision.DirectSource,
UsingForwarded: decision.UsedForwarded,
}
}
func evaluatePanelRequest(r *http.Request, policy config.PanelAccessPolicy) config.PanelAccessDecision {
return config.EvaluatePanelAccess(policy, r.RemoteAddr, config.ForwardedClientHeaders{
ForwardedFor: r.Header.Get("X-Forwarded-For"),
RealIP: r.Header.Get("X-Real-IP"),
CFConnectingIP: r.Header.Get("CF-Connecting-IP"),
})
}
func boolText(value bool) string {
if value {
return "true"
}
return "false"
}
+374 -39
View File
@@ -2,12 +2,15 @@ package api
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
@@ -16,6 +19,7 @@ import (
"clicd/internal/config"
"clicd/internal/kvm"
"clicd/internal/lxc"
"clicd/internal/safehttp"
)
// ImageInfo represents a template image with its download/enable status.
@@ -38,8 +42,14 @@ type ImageInfo struct {
SizeBytes int64 `json:"size_bytes"`
ManualPath string `json:"manual_path,omitempty"`
Desktop string `json:"desktop,omitempty"`
Provisioner string `json:"provisioner,omitempty"`
Custom bool `json:"custom,omitempty"`
SHA256 string `json:"sha256,omitempty"`
}
var customImageFieldPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
var sha256Pattern = regexp.MustCompile(`^[a-fA-F0-9]{64}$`)
var imageDownloadsMu sync.Mutex
var imageDownloads = map[string]*imageDownloadStatus{}
var lxcImageCacheMu sync.Mutex
@@ -177,46 +187,68 @@ func cleanupOldImageDownloadErrors() {
}
}
// isImageDownloaded checks if the LXC download cache exists for a template.
func isImageDownloaded(distro, release, arch string) bool {
downloaded, _ := imageDownloadedInfo(distro, release, arch)
return downloaded
}
// imageDownloadedInfo returns whether the image is downloaded and its total size in bytes.
func imageDownloadedInfo(distro, release, arch string) (bool, int64) {
cachePath := filepath.Join("/var/cache/lxc/download", distro, release, arch)
func imageDownloadedInfo(templateID string) (bool, int64) {
cachePath, ok := officialLXCImageCachePath(templateID)
if !ok {
return false, 0
}
info, err := os.Stat(cachePath)
if err != nil || !info.IsDir() {
return false, 0
}
// Check directly for rootfs.tar.xz (some LXC versions store it here)
if fi, err := os.Stat(filepath.Join(cachePath, "rootfs.tar.xz")); err == nil {
return true, fi.Size()
}
if fi, err := os.Stat(filepath.Join(cachePath, "meta.tar.xz")); err == nil {
return true, fi.Size()
}
// Check one level deeper (LXC uses variant subdirectories like "default")
entries, err := os.ReadDir(cachePath)
if err != nil {
return false, 0
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
subPath := filepath.Join(cachePath, entry.Name())
if fi, err := os.Stat(filepath.Join(subPath, "rootfs.tar.xz")); err == nil {
return true, fi.Size()
}
if fi, err := os.Stat(filepath.Join(subPath, "meta.tar.xz")); err == nil {
return true, fi.Size()
for _, candidate := range []string{
filepath.Join(cachePath, "rootfs.tar.xz"),
filepath.Join(cachePath, "meta.tar.xz"),
filepath.Join(cachePath, "default", "rootfs.tar.xz"),
filepath.Join(cachePath, "default", "meta.tar.xz"),
} {
if fileInfo, err := os.Stat(candidate); err == nil && !fileInfo.IsDir() {
return true, fileInfo.Size()
}
}
return false, 0
}
func officialLXCImageCachePath(templateID string) (string, bool) {
arch := "amd64"
if runtime.GOARCH == "arm64" {
arch = "arm64"
}
base := "/var/cache/lxc/download"
switch templateID {
case "ubuntu-noble":
return filepath.Join(base, "ubuntu", "noble", arch), true
case "ubuntu-jammy":
return filepath.Join(base, "ubuntu", "jammy", arch), true
case "debian-trixie":
return filepath.Join(base, "debian", "trixie", arch), true
case "debian-bookworm":
return filepath.Join(base, "debian", "bookworm", arch), true
case "debian-bullseye":
return filepath.Join(base, "debian", "bullseye", arch), true
case "alpine-3.21":
return filepath.Join(base, "alpine", "3.21", arch), true
case "centos-9-stream":
return filepath.Join(base, "centos", "9-Stream", arch), true
case "archlinux-current":
return filepath.Join(base, "archlinux", "current", arch), true
case "fedora-44":
return filepath.Join(base, "fedora", "44", arch), true
case "rockylinux-10":
return filepath.Join(base, "rockylinux", "10", arch), true
default:
return "", false
}
}
func lxcTemplateDownloadedInfo(template lxc.Template) (bool, int64) {
if template.Custom {
return lxc.CustomImageDownloadedInfo(template.ID)
}
return imageDownloadedInfo(template.ID)
}
// getEnabledImageSet returns the set of enabled image IDs.
// If none have been explicitly set, all templates are enabled by default.
func getEnabledImageSet() map[string]bool {
@@ -255,10 +287,10 @@ func HandleImages(w http.ResponseWriter, r *http.Request) {
if kvmAvailable {
kvmImages = kvm.GetImages()
}
images := make([]ImageInfo, 0, len(templates)+len(kvmImages))
images := make([]ImageInfo, 0, len(templates))
for _, t := range templates {
dl := imageDownloadInfo(t.ID)
downloaded, size := imageDownloadedInfo(t.Distro, t.Release, t.Arch)
downloaded, size := lxcTemplateDownloadedInfo(t)
images = append(images, ImageInfo{
ID: t.ID,
Name: t.Name,
@@ -276,13 +308,15 @@ func HandleImages(w http.ResponseWriter, r *http.Request) {
Stage: dl.Stage,
Error: dl.Error,
SizeBytes: size,
Custom: t.Custom,
SHA256: t.SHA256,
})
}
for _, t := range kvmImages {
dl := imageDownloadInfo(t.ID)
downloaded, size := kvm.ImageDownloadedInfo(t.ID)
manualPath := ""
if t.Distro == "windows" {
if t.IsWindows() {
manualPath = kvm.ImagePath(t.ID)
}
images = append(images, ImageInfo{
@@ -304,12 +338,260 @@ func HandleImages(w http.ResponseWriter, r *http.Request) {
SizeBytes: size,
ManualPath: manualPath,
Desktop: t.Desktop,
Provisioner: t.Provisioner,
Custom: t.Custom,
SHA256: t.SHA256,
})
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: images})
}
// HandleCustomKVMImages creates or removes administrator-defined LXC/KVM image sources.
func HandleCustomKVMImages(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
if !requireScope(w, r, "image:download") {
return
}
handleCustomKVMImageCreate(w, r)
case http.MethodDelete:
if !requireScope(w, r, "image:delete") {
return
}
handleCustomKVMImageDelete(w, r)
default:
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
}
}
func handleCustomKVMImageCreate(w http.ResponseWriter, r *http.Request) {
var req struct {
Type string `json:"type"`
Name string `json:"name"`
Description string `json:"description"`
Distro string `json:"distro"`
Release string `json:"release"`
Arch string `json:"arch"`
URL string `json:"url"`
Provisioner string `json:"provisioner"`
SHA256 string `json:"sha256"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
req.Name = strings.TrimSpace(req.Name)
req.Type = strings.ToLower(strings.TrimSpace(req.Type))
if req.Type == "" {
req.Type = config.VirtualizationKVM
}
req.Description = strings.TrimSpace(req.Description)
req.Distro = strings.ToLower(strings.TrimSpace(req.Distro))
req.Release = strings.ToLower(strings.TrimSpace(req.Release))
req.Arch = strings.ToLower(strings.TrimSpace(req.Arch))
req.URL = strings.TrimSpace(req.URL)
req.Provisioner = strings.ToLower(strings.TrimSpace(req.Provisioner))
req.SHA256 = strings.ToLower(strings.TrimSpace(req.SHA256))
if req.Name == "" || len(req.Name) > 100 {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "name must be between 1 and 100 characters"})
return
}
if len(req.Description) > 500 {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "description must not exceed 500 characters"})
return
}
if req.Arch != runtime.GOARCH || (req.Arch != "amd64" && req.Arch != "arm64") {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "image architecture must match the host architecture"})
return
}
if req.Type == config.VirtualizationLXC {
if !customImageFieldPattern.MatchString(req.Distro) {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "distro contains unsupported characters"})
return
}
if !customImageFieldPattern.MatchString(req.Release) {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "release contains unsupported characters"})
return
}
} else if req.Type == config.VirtualizationKVM {
switch req.Provisioner {
case config.KVMProvisionerLinuxCloudInit:
if !customImageFieldPattern.MatchString(req.Distro) {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "distro contains unsupported characters"})
return
}
if !customImageFieldPattern.MatchString(req.Release) {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "release contains unsupported characters"})
return
}
case config.KVMProvisionerWindows10:
if req.Arch != "amd64" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Windows unattended installation currently requires an amd64 host"})
return
}
req.Distro = "windows"
req.Release = "10"
case config.KVMProvisionerWindows11:
if req.Arch != "amd64" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Windows unattended installation currently requires an amd64 host"})
return
}
req.Distro = "windows"
req.Release = "11"
default:
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "unsupported unattended installation template"})
return
}
} else {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "type must be lxc or kvm"})
return
}
if len(req.URL) > 4096 {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "url must not exceed 4096 characters"})
return
}
if _, err := safehttp.ValidateURL(req.URL); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
if req.SHA256 != "" && !sha256Pattern.MatchString(req.SHA256) {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "sha256 must contain exactly 64 hexadecimal characters"})
return
}
if req.Type == config.VirtualizationLXC {
for _, existing := range lxc.GetTemplates() {
if strings.EqualFold(existing.Name, req.Name) {
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "an image with this name already exists"})
return
}
if existing.Custom && existing.URL == req.URL {
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "this image URL is already registered"})
return
}
}
} else {
for _, existing := range kvm.GetImages() {
if strings.EqualFold(existing.Name, req.Name) {
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "an image with this name already exists"})
return
}
if existing.Custom && existing.URL == req.URL {
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "this image URL is already registered"})
return
}
}
}
random := make([]byte, 5)
if _, err := rand.Read(random); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "failed to generate image ID"})
return
}
createdAt := time.Now().Format("2006-01-02 15:04:05")
if req.Type == config.VirtualizationLXC {
image := config.CustomLXCImage{
ID: "custom-lxc-" + hex.EncodeToString(random),
Name: req.Name,
Description: req.Description,
Distro: req.Distro,
Release: req.Release,
Arch: req.Arch,
URL: req.URL,
SHA256: req.SHA256,
CreatedAt: createdAt,
}
if err := config.AddCustomLXCImage(image); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "failed to save custom image: " + err.Error()})
return
}
jsonResponse(w, http.StatusCreated, APIResponse{Success: true, Message: "Custom image added", Data: image})
return
}
image := config.CustomKVMImage{
ID: "custom-kvm-" + hex.EncodeToString(random), Name: req.Name, Description: req.Description,
Distro: req.Distro, Release: req.Release, Arch: req.Arch, URL: req.URL,
Provisioner: req.Provisioner, SHA256: req.SHA256, CreatedAt: createdAt,
}
if err := config.AddCustomKVMImage(image); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "failed to save custom image: " + err.Error()})
return
}
jsonResponse(w, http.StatusCreated, APIResponse{Success: true, Message: "Custom image added", Data: image})
}
func handleCustomKVMImageDelete(w http.ResponseWriter, r *http.Request) {
var req struct {
ID string `json:"id"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.ID) == "" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "id required"})
return
}
req.ID = strings.TrimSpace(req.ID)
kvmImage := kvm.FindImage(req.ID)
lxcImage := lxc.FindTemplate(req.ID)
isCustomKVM := kvmImage != nil && kvmImage.Custom
isCustomLXC := lxcImage != nil && lxcImage.Custom
if !isCustomKVM && !isCustomLXC {
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Custom image not found"})
return
}
if isImageDownloadActive(req.ID) {
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "Image is downloading; cancel it before removing the source"})
return
}
for i := range config.AppConfig.Containers {
if config.AppConfig.Containers[i].Template == req.ID {
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "This image is still used by a container"})
return
}
}
for i := range config.AppConfig.Tasks {
task := &config.AppConfig.Tasks[i]
if task.Status != "pending" && task.Status != "running" {
continue
}
var taskConfig struct {
TemplateID string `json:"template_id"`
}
_ = json.Unmarshal([]byte(task.Config), &taskConfig)
if task.TemplateID == req.ID || taskConfig.TemplateID == req.ID {
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "This image is still referenced by an active task"})
return
}
}
var deleteErr error
if isCustomLXC {
deleteErr = lxc.DeleteCustomImage(req.ID)
} else {
deleteErr = kvm.DeleteImage(req.ID)
}
if deleteErr != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to delete image cache: " + deleteErr.Error()})
return
}
removeImageEnabled(req.ID)
var removed bool
var err error
if isCustomLXC {
removed, err = config.RemoveCustomLXCImage(req.ID)
} else {
removed, err = config.RemoveCustomKVMImage(req.ID)
}
if err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to remove custom image: " + err.Error()})
return
}
if !removed {
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Custom image not found"})
return
}
clearImageDownload(req.ID)
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Custom image removed"})
}
// HandleImageDownload starts a template image download in the background.
func HandleImageDownload(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
@@ -407,19 +689,52 @@ func HandleImageDownload(w http.ResponseWriter, r *http.Request) {
}
// Already downloaded? Just enable if needed.
if isImageDownloaded(tmpl.Distro, tmpl.Release, tmpl.Arch) {
if downloaded, _ := lxcTemplateDownloadedInfo(*tmpl); downloaded {
ensureImageEnabled(tmpl.ID)
clearImageDownload(tmpl.ID)
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Already downloaded"})
return
}
ctx, ok := startImageDownload(tmpl.ID, "lxc-create")
startStage := "lxc-create"
if tmpl.Custom {
startStage = "downloading"
}
ctx, ok := startImageDownload(tmpl.ID, startStage)
if !ok {
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "Already downloading"})
return
}
if tmpl.Custom {
go func(tmpl lxc.Template) {
defer endLXCImageDownload()
err := lxc.DownloadCustomImageWithProgress(ctx, tmpl, func(progress lxc.CustomImageDownloadProgress) {
updateImageDownload(tmpl.ID, func(status *imageDownloadStatus) {
status.Stage = progress.Stage
status.DownloadedBytes = progress.DownloadedBytes
status.TotalBytes = progress.TotalBytes
status.Progress = progress.Percent
})
})
if err != nil {
if ctx.Err() != nil {
_ = os.Remove(lxc.CustomImagePath(tmpl.ID) + ".tmp")
_ = os.Remove(lxc.CustomImagePath(tmpl.ID))
finishImageDownload(tmpl.ID, nil)
return
}
finishImageDownload(tmpl.ID, err)
return
}
ensureImageEnabled(tmpl.ID)
finishImageDownload(tmpl.ID, nil)
}(*tmpl)
lxcDownloadHandedOff = true
jsonResponse(w, http.StatusAccepted, APIResponse{Success: true, Message: "Download started"})
return
}
go func(tmpl lxc.Template) {
defer endLXCImageDownload()
// Download via lxc-create with a temp container, then destroy it.
@@ -633,8 +948,13 @@ func HandleImageCancel(w http.ResponseWriter, r *http.Request) {
os.Remove(kvm.ImagePath(image.ID))
}
if tmpl := lxc.FindTemplate(req.TemplateID); tmpl != nil {
if tmpl.Custom {
_ = os.Remove(lxc.CustomImagePath(tmpl.ID) + ".tmp")
_ = os.Remove(lxc.CustomImagePath(tmpl.ID))
} else {
go cleanupLXCImageDownloadTemp(tmpl.ID)
}
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Cancel requested"})
}
@@ -674,9 +994,22 @@ func HandleImageDelete(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Template not found"})
return
}
if tmpl.Custom {
if err := lxc.DeleteCustomImage(tmpl.ID); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to delete image cache: " + err.Error()})
return
}
removeImageEnabled(tmpl.ID)
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Deleted"})
return
}
// Remove cache directory
cachePath := filepath.Join("/var/cache/lxc/download", tmpl.Distro, tmpl.Release, tmpl.Arch)
cachePath, ok := officialLXCImageCachePath(tmpl.ID)
if !ok {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Template cache path is not managed by CLICD"})
return
}
if err := os.RemoveAll(cachePath); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{
Success: false,
@@ -773,7 +1106,7 @@ func HandleEnabledImages(w http.ResponseWriter, r *http.Request) {
if subUser != nil && !isImageAllowedForSubUser(subUser, targetContainer, t.ID) {
continue
}
if downloaded := isImageDownloaded(t.Distro, t.Release, t.Arch); downloaded && (enabledSet[t.ID] || currentImageIDs[t.ID]) {
if downloaded, _ := lxcTemplateDownloadedInfo(t); downloaded && (enabledSet[t.ID] || currentImageIDs[t.ID]) {
result = append(result, map[string]string{
"id": t.ID, "name": t.Name, "distro": t.Distro, "release": t.Release, "arch": t.Arch,
"variant": t.Variant, "description": t.Description, "type": config.VirtualizationLXC,
@@ -810,7 +1143,8 @@ func isImageDownloadedForRuntime(templateID string, runtime string) bool {
if tmpl == nil {
return false
}
return isImageDownloaded(tmpl.Distro, tmpl.Release, tmpl.Arch)
downloaded, _ := lxcTemplateDownloadedInfo(*tmpl)
return downloaded
}
func isTemplateAvailableForRequest(r *http.Request, c *config.Container, templateID string, runtime string) bool {
@@ -844,7 +1178,8 @@ func isImageEnabledAndDownloaded(templateID string, runtime string) bool {
return false
}
enabledSet := getEnabledImageSet()
return enabledSet[tmpl.ID] && isImageDownloaded(tmpl.Distro, tmpl.Release, tmpl.Arch)
downloaded, _ := lxcTemplateDownloadedInfo(*tmpl)
return enabledSet[tmpl.ID] && downloaded
}
func hostKVMAvailable() bool {
+133
View File
@@ -0,0 +1,133 @@
package api
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"runtime"
"strings"
"testing"
)
func TestCustomKVMImageCreateRejectsInvalidSource(t *testing.T) {
payload := map[string]string{
"name": "Invalid Source",
"distro": "ubuntu",
"release": "noble",
"arch": runtime.GOARCH,
"url": "file:///etc/passwd",
"provisioner": "linux-cloud-init",
}
body, err := json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodPost, "/api/images/custom", bytes.NewReader(body))
response := httptest.NewRecorder()
HandleCustomKVMImages(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d; body=%s", response.Code, http.StatusBadRequest, response.Body.String())
}
}
func TestCustomKVMImageCreateRejectsArchitectureMismatch(t *testing.T) {
otherArch := "arm64"
if runtime.GOARCH == otherArch {
otherArch = "amd64"
}
payload := map[string]string{
"name": "Wrong Architecture",
"distro": "ubuntu",
"release": "noble",
"arch": otherArch,
"url": "https://example.test/image.qcow2",
"provisioner": "linux-cloud-init",
}
body, err := json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodPost, "/api/images/custom", bytes.NewReader(body))
response := httptest.NewRecorder()
HandleCustomKVMImages(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d; body=%s", response.Code, http.StatusBadRequest, response.Body.String())
}
}
func TestCustomLXCImageCreateRejectsInvalidSource(t *testing.T) {
payload := map[string]string{
"type": "lxc",
"name": "Invalid LXC Source",
"distro": "alpine",
"release": "3.21",
"arch": runtime.GOARCH,
"url": "file:///tmp/rootfs.tar.xz",
}
body, err := json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodPost, "/api/images/custom", bytes.NewReader(body))
response := httptest.NewRecorder()
HandleCustomKVMImages(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d; body=%s", response.Code, http.StatusBadRequest, response.Body.String())
}
}
func TestCustomImageCreateRejectsPrivateNetworkSource(t *testing.T) {
for _, imageType := range []string{"lxc", "kvm"} {
t.Run(imageType, func(t *testing.T) {
payload := map[string]string{
"type": imageType,
"name": "Private Network Source",
"distro": "ubuntu",
"release": "noble",
"arch": runtime.GOARCH,
"url": "http://169.254.169.254/latest/meta-data",
"provisioner": "linux-cloud-init",
}
body, err := json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodPost, "/api/images/custom", bytes.NewReader(body))
response := httptest.NewRecorder()
HandleCustomKVMImages(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d; body=%s", response.Code, http.StatusBadRequest, response.Body.String())
}
})
}
}
func TestOfficialLXCImageCachePathUsesAllowlist(t *testing.T) {
cachePath, ok := officialLXCImageCachePath("debian-trixie")
if !ok {
t.Fatal("known template cache path was rejected")
}
normalized := filepath.ToSlash(cachePath)
if !strings.Contains(normalized, "/debian/trixie/") {
t.Fatalf("cache path = %q, want Debian trixie path", cachePath)
}
for _, templateID := range []string{
"../../../etc",
"custom-lxc-attacker",
"debian-trixie/../../etc",
} {
if cachePath, ok := officialLXCImageCachePath(templateID); ok || cachePath != "" {
t.Fatalf("officialLXCImageCachePath(%q) = %q, %v; want rejection", templateID, cachePath, ok)
}
}
}
+13
View File
@@ -22,6 +22,11 @@ type nat4PortRange struct {
End int `json:"end"`
}
type nat4Networks struct {
LXC config.NATNetwork `json:"lxc"`
KVM config.NATNetwork `json:"kvm"`
}
type nat4Route struct {
ContainerID int `json:"container_id"`
ContainerName string `json:"container_name"`
@@ -72,6 +77,8 @@ type ipv6Route struct {
type routingResponse struct {
NAT4 routeCapacity `json:"nat4"`
NAT4PortRange nat4PortRange `json:"nat4_port_range"`
NAT4NextPort int `json:"nat4_next_port"`
NAT4Networks nat4Networks `json:"nat4_networks"`
IPv4 routeCapacity `json:"ipv4"`
LANDHCP routeCapacity `json:"lan_dhcp"`
IPv6 routeCapacity `json:"ipv6"`
@@ -237,6 +244,7 @@ func handleRoutingGet(w http.ResponseWriter, r *http.Request) {
if nat4Remaining < 0 {
nat4Remaining = 0
}
nat4NextPort, _ := config.PreviewSSHPortExcluding(nil)
prefixes := lxc.DetectPublicIPv6Prefixes()
hostPublicIPv4 := lxc.DetectPublicIPv4()
@@ -262,6 +270,11 @@ func handleRoutingGet(w http.ResponseWriter, r *http.Request) {
Start: nat4StartPort,
End: nat4EndPort,
},
NAT4NextPort: nat4NextPort,
NAT4Networks: nat4Networks{
LXC: config.LXCNATNetwork(),
KVM: config.KVMNATNetwork(),
},
IPv4: routeCapacity{
Used: ipv4Used,
Remaining: strconv.Itoa(ipv4Remaining),
+42
View File
@@ -1,6 +1,7 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
@@ -24,3 +25,44 @@ func TestHandleRoutingGetAllowsRoutingWriteScope(t *testing.T) {
t.Fatal("routing:write scope should be able to receive the routing response after updates")
}
}
func TestHandleRoutingGetReturnsConfiguredNextNATPort(t *testing.T) {
previous := config.AppConfig
t.Cleanup(func() { config.AppConfig = previous })
config.AppConfig = &config.ClicdConfig{
NATPortStart: 30000,
NATPortEnd: 35000,
NextSSHPort: 30000,
Containers: []config.Container{{
PortMappings: []config.PortMapping{{HostPort: 30000}},
}},
}
req := httptest.NewRequest(http.MethodGet, "/api/v1/routing", nil)
req = withAuthContext(req, AuthContext{
Type: authTypeAPIKey,
Scopes: []string{"routing:read"},
})
rec := httptest.NewRecorder()
handleRoutingGet(rec, req)
var response struct {
Success bool `json:"success"`
Data struct {
NAT4PortRange nat4PortRange `json:"nat4_port_range"`
NAT4NextPort int `json:"nat4_next_port"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if !response.Success {
t.Fatalf("routing response was unsuccessful: %s", rec.Body.String())
}
if response.Data.NAT4PortRange.Start != 30000 || response.Data.NAT4PortRange.End != 35000 {
t.Fatalf("NAT range = %+v", response.Data.NAT4PortRange)
}
if response.Data.NAT4NextPort != 30001 {
t.Fatalf("next NAT port = %d, want 30001", response.Data.NAT4NextPort)
}
}
+13 -2
View File
@@ -462,6 +462,8 @@ func (q *TaskQueue) runCreateTask(task *Task) {
q.finishTask(task, "failed", err)
return
}
} else {
lxc.ReleaseQueuedCreateNATPorts(cfg.Name)
}
q.mu.Lock()
@@ -866,7 +868,12 @@ func HandleBatchCreate(w http.ResponseWriter, r *http.Request) {
}
requestNames[name] = true
}
ids := globalQueue.EnqueueBatchCreateWithAudit(req.Containers, requestActor(r), clientIP(r), r.UserAgent())
planned, err := lxc.ReserveBatchCreateNATPorts(req.Containers)
if err != nil {
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: err.Error()})
return
}
ids := globalQueue.EnqueueBatchCreateWithAudit(planned, requestActor(r), clientIP(r), r.UserAgent())
jsonResponse(w, http.StatusAccepted, APIResponse{Success: true, Data: ids})
}
@@ -988,7 +995,8 @@ func HandleTaskDelete(w http.ResponseWriter, r *http.Request) {
return
}
globalQueue.mu.Lock()
if task := globalQueue.tasks[taskID]; task != nil && !isTaskAllowedForRequest(r, task) {
task := globalQueue.tasks[taskID]
if task != nil && !isTaskAllowedForRequest(r, task) {
globalQueue.mu.Unlock()
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Access denied to this task"})
return
@@ -1011,6 +1019,9 @@ func HandleTaskDelete(w http.ResponseWriter, r *http.Request) {
globalQueue.opQueue = newOp
globalQueue.persistTasks()
globalQueue.mu.Unlock()
if task != nil && task.Type == TaskCreate {
lxc.ReleaseQueuedCreateNATPorts(task.Config.Name)
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Task deleted"})
}
+86
View File
@@ -0,0 +1,86 @@
package cli
import (
"flag"
"fmt"
"strings"
"clicd/internal/config"
)
// RunAccessPolicyCommand manages the panel source policy without requiring the
// interactive menu. It is intended to remain usable over SSH as a recovery path.
func RunAccessPolicyCommand(args []string) error {
action := "show"
if len(args) > 0 {
action = strings.ToLower(strings.TrimSpace(args[0]))
args = args[1:]
}
switch action {
case "show":
printPanelAccessPolicy(config.AppConfig.PanelAccessPolicy)
return nil
case "disable", "off":
next := config.AppConfig.PanelAccessPolicy
next.Enabled = false
if err := savePanelAccessPolicy(next); err != nil {
return err
}
fmt.Println("Panel access allowlist disabled.")
return reloadPanelAfterAccessPolicyCommand()
case "set", "enable":
flags := flag.NewFlagSet("clicd access-policy set", flag.ContinueOnError)
flags.SetOutput(new(strings.Builder))
var allowed string
var trusted string
flags.StringVar(&allowed, "allow", "", "comma-separated allowed IP/CIDR values")
flags.StringVar(&trusted, "trusted-proxy", "", "comma-separated trusted proxy IP/CIDR values")
if err := flags.Parse(args); err != nil {
return fmt.Errorf("invalid access-policy arguments: %w", err)
}
next := config.PanelAccessPolicy{
Enabled: true,
AllowedSources: splitPanelAccessEntries(allowed),
TrustedProxies: splitPanelAccessEntries(trusted),
}
if err := savePanelAccessPolicy(next); err != nil {
return err
}
fmt.Println("Panel access allowlist saved.")
printPanelAccessPolicy(config.AppConfig.PanelAccessPolicy)
return reloadPanelAfterAccessPolicyCommand()
default:
return fmt.Errorf("unknown access-policy action %q; use show, set, or disable", action)
}
}
func savePanelAccessPolicy(policy config.PanelAccessPolicy) error {
normalized, err := config.NormalizePanelAccessPolicy(policy)
if err != nil {
return err
}
previous := config.AppConfig.PanelAccessPolicy
config.AppConfig.PanelAccessPolicy = normalized
if err := config.SaveConfig(); err != nil {
config.AppConfig.PanelAccessPolicy = previous
return fmt.Errorf("save panel access policy: %w", err)
}
return nil
}
func reloadPanelAfterAccessPolicyCommand() error {
if !isWebPanelRunning() {
return nil
}
if err := restartService("clicd"); err != nil {
return fmt.Errorf("policy was saved but clicd service restart failed: %w", err)
}
return nil
}
func printPanelAccessPolicy(policy config.PanelAccessPolicy) {
fmt.Printf("Enabled: %t\n", policy.Enabled)
fmt.Printf("Allowed sources: %s\n", strings.Join(policy.AllowedSources, ", "))
fmt.Printf("Trusted proxies: %s\n", strings.Join(policy.TrustedProxies, ", "))
}
+93 -3
View File
@@ -54,6 +54,7 @@ var cliTranslations = map[string]string{
"导入现有 LXC 容器": "Import existing LXC containers",
"检查并升级 CLICD": "Check and upgrade CLICD",
"卸载 CLICD": "Uninstall CLICD",
"面板访问白名单": "Panel access allowlist",
"系统信息": "System info",
"退出": "Exit",
"获取容器列表失败": "Failed to get container list",
@@ -175,6 +176,22 @@ var cliTranslations = map[string]string{
"LXC 版本": "LXC version",
"暂无可用容器": "No available containers",
"忽略无效端口": "Ignoring invalid port",
"面板访问来源策略": "Panel access source policy",
"当前状态": "Current status",
"已启用": "enabled",
"已关闭": "disabled",
"允许来源": "Allowed sources",
"可信代理": "Trusted proxies",
"启用或修改白名单": "Enable or update allowlist",
"关闭白名单限制": "Disable allowlist",
"取消": "Cancel",
"允许的 IP/CIDR,多个用逗号分隔": "Allowed IP/CIDR values, comma-separated",
"可信代理 IP/CIDR,多个用逗号分隔,可留空": "Trusted proxy IP/CIDR values, comma-separated; optional",
"白名单配置无效": "Invalid allowlist configuration",
"保存访问来源策略失败": "Failed to save access source policy",
"面板访问白名单已保存。": "Panel access allowlist saved.",
"面板访问白名单已关闭。": "Panel access allowlist disabled.",
"至少填写一个允许的 IP 或网段。": "Enter at least one allowed IP address or network.",
"": "? ",
"。": ". ",
"": ", ",
@@ -193,7 +210,7 @@ func Run() {
refreshCLILanguage()
clearScreen()
printMenu()
cliPrint("\n请选择操作 [1-12,l,0/q]: ")
cliPrint("\n请选择操作 [1-13,l,0/q]: ")
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
@@ -246,6 +263,10 @@ func Run() {
clearScreen()
cliUninstall(reader)
return
case "13":
clearScreen()
cliConfigurePanelAccess(reader)
waitEnter(reader)
case "0":
clearScreen()
cliShowInfo()
@@ -293,11 +314,80 @@ func printMenu() {
cliPrintln(" 10. 导入现有 LXC 容器")
cliPrintln(" 11. 检查并升级 CLICD")
cliPrintln(" 12. 卸载 CLICD")
cliPrintln(" 13. 面板访问白名单")
cliPrintln(" 0. 系统信息")
cliPrintln(" l. 切换语言")
cliPrintln(" q. 退出")
}
func cliConfigurePanelAccess(reader *bufio.Reader) {
cliPrintf("\n--- %s ---\n", cliT("面板访问来源策略"))
policy := config.AppConfig.PanelAccessPolicy
status := cliT("已关闭")
if policy.Enabled {
status = cliT("已启用")
}
cliPrintf("%s: %s\n", cliT("当前状态"), status)
cliPrintf("%s: %s\n", cliT("允许来源"), strings.Join(policy.AllowedSources, ", "))
cliPrintf("%s: %s\n", cliT("可信代理"), strings.Join(policy.TrustedProxies, ", "))
cliPrintf("\n 1. %s\n", cliT("启用或修改白名单"))
cliPrintf(" 2. %s\n", cliT("关闭白名单限制"))
cliPrintf(" 0. %s\n", cliT("取消"))
choice := promptString(reader, "请选择操作", "0")
next := policy
switch strings.TrimSpace(choice) {
case "1":
allowed := promptString(reader, "允许的 IP/CIDR,多个用逗号分隔", strings.Join(policy.AllowedSources, ","))
allowedSources := splitPanelAccessEntries(allowed)
if len(allowedSources) == 0 {
cliPrintln("至少填写一个允许的 IP 或网段。")
return
}
trusted := promptString(reader, "可信代理 IP/CIDR,多个用逗号分隔,可留空", strings.Join(policy.TrustedProxies, ","))
next = config.PanelAccessPolicy{
Enabled: true,
AllowedSources: allowedSources,
TrustedProxies: splitPanelAccessEntries(trusted),
}
case "2":
next.Enabled = false
case "0", "":
cliPrintln("已取消")
return
default:
cliPrintln("无效选择")
return
}
normalized, err := config.NormalizePanelAccessPolicy(next)
if err != nil {
cliPrintf("%s: %v\n", cliT("白名单配置无效"), err)
return
}
previous := config.AppConfig.PanelAccessPolicy
config.AppConfig.PanelAccessPolicy = normalized
if err := config.SaveConfig(); err != nil {
config.AppConfig.PanelAccessPolicy = previous
cliPrintf("%s: %v\n", cliT("保存访问来源策略失败"), err)
return
}
if normalized.Enabled {
cliPrintln("面板访问白名单已保存。")
} else {
cliPrintln("面板访问白名单已关闭。")
}
if isWebPanelRunning() {
restartWebPanelForConfigChange()
}
}
func splitPanelAccessEntries(value string) []string {
return strings.FieldsFunc(value, func(r rune) bool {
return r == ',' || r == ';' || r == '\n' || r == '\r' || r == '\t' || r == ' '
})
}
func cliSwitchLanguage(reader *bufio.Reader) {
cliPrintf("\n--- %s ---\n", cliT("切换语言"))
cliPrintf("%s: %s\n", cliT("当前语言"), cliLanguageLabel(config.NormalizeLanguage(config.AppConfig.Language)))
@@ -1244,8 +1334,8 @@ func removeCLICDNATRules() {
break
}
}
deleteNATRule("POSTROUTING", "-s", "10.0.3.0/24", "-o", "eth+", "-j", "MASQUERADE")
deleteNATRule("POSTROUTING", "-s", "192.168.122.0/24", "-o", "eth+", "-j", "MASQUERADE")
deleteNATRule("POSTROUTING", "-s", config.LXCNATNetwork().Subnet, "-o", "eth+", "-j", "MASQUERADE")
deleteNATRule("POSTROUTING", "-s", config.KVMNATNetwork().Subnet, "-o", "eth+", "-j", "MASQUERADE")
}
}
+188 -6
View File
@@ -583,7 +583,7 @@ func (c *Container) NormalizeNetworkAssignments() bool {
c.PublicIPv4s = filteredIPv4
seenIPv6 := map[string]bool{}
filteredIPv6 := make([]IPv6Assignment, 0, len(c.IPv6Addresses)+1)
filteredIPv6 := make([]IPv6Assignment, 0, len(c.IPv6Addresses))
for _, item := range c.IPv6Addresses {
item.Address = strings.TrimSpace(item.Address)
item.Interface = strings.TrimSpace(item.Interface)
@@ -794,6 +794,8 @@ type ClicdConfig struct {
NextSSHPort int `json:"next_ssh_port"`
NATPortStart int `json:"nat_port_start"`
NATPortEnd int `json:"nat_port_end"`
LXCNATSubnet string `json:"lxc_nat_subnet"`
KVMNATSubnet string `json:"kvm_nat_subnet"`
SetupComplete bool `json:"setup_complete"`
SubUsers []SubUser `json:"sub_users"`
ApiKeys []ApiKeyConfig `json:"api_keys"`
@@ -801,10 +803,13 @@ type ClicdConfig struct {
Tasks []SavedTask `json:"tasks"`
LoginLogs []SavedLoginLog `json:"login_logs"`
EnabledImages []string `json:"enabled_images"`
CustomKVMImages []CustomKVMImage `json:"custom_kvm_images"`
CustomLXCImages []CustomLXCImage `json:"custom_lxc_images"`
Snapshots []Snapshot `json:"snapshots"`
PublicIPv4Pool []PublicIPv4Assignment `json:"public_ipv4_pool"`
PublicIPv6Prefixes []PublicIPv6Prefix `json:"public_ipv6_prefixes"`
WebSSHAllowedOrigins []string `json:"webssh_allowed_origins"`
PanelAccessPolicy PanelAccessPolicy `json:"panel_access_policy"`
SecurityAutoShutdown bool `json:"security_auto_shutdown"`
TaskConcurrency int `json:"task_concurrency"`
Language string `json:"language"`
@@ -813,6 +818,39 @@ type ClicdConfig struct {
StoragePools []StoragePool `json:"storage_pools"`
}
const (
KVMProvisionerLinuxCloudInit = "linux-cloud-init"
KVMProvisionerWindows10 = "windows-10"
KVMProvisionerWindows11 = "windows-11"
)
// CustomKVMImage is an administrator-defined KVM image source.
type CustomKVMImage struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Distro string `json:"distro"`
Release string `json:"release"`
Arch string `json:"arch"`
URL string `json:"url"`
Provisioner string `json:"provisioner"`
SHA256 string `json:"sha256,omitempty"`
CreatedAt string `json:"created_at"`
}
// CustomLXCImage is an administrator-defined LXC rootfs archive source.
type CustomLXCImage struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Distro string `json:"distro"`
Release string `json:"release"`
Arch string `json:"arch"`
URL string `json:"url"`
SHA256 string `json:"sha256,omitempty"`
CreatedAt string `json:"created_at"`
}
var configPath string
var AppConfig *ClicdConfig
var allocationMu sync.Mutex
@@ -946,6 +984,8 @@ func InitConfig() (*ClicdConfig, error) {
NextSSHPort: 22000,
NATPortStart: DefaultNATPortStart,
NATPortEnd: DefaultNATPortEnd,
LXCNATSubnet: configuredSubnetValue("", "CLICD_LXC_SUBNET", DefaultLXCNATSubnet),
KVMNATSubnet: configuredSubnetValue("", "CLICD_KVM_SUBNET", DefaultKVMNATSubnet),
SetupComplete: false,
SubUsers: []SubUser{},
AuditLogs: []AuditLog{},
@@ -955,6 +995,10 @@ func InitConfig() (*ClicdConfig, error) {
PublicIPv4Pool: []PublicIPv4Assignment{},
PublicIPv6Prefixes: []PublicIPv6Prefix{},
WebSSHAllowedOrigins: []string{},
PanelAccessPolicy: PanelAccessPolicy{
AllowedSources: []string{},
TrustedProxies: []string{},
},
TaskConcurrency: DefaultTaskConcurrency,
StoragePools: []StoragePool{defaultPrimaryStoragePool()},
}
@@ -994,6 +1038,9 @@ func normalizeConfigDefaults(dataDir string) bool {
if normalizeNATPortRangeDefaults() {
changed = true
}
if normalizeNATNetworkDefaults() {
changed = true
}
if AppConfig.NextContainerID == 0 {
AppConfig.NextContainerID = 1
changed = true
@@ -1029,6 +1076,18 @@ func normalizeConfigDefaults(dataDir string) bool {
AppConfig.WebSSHAllowedOrigins = normalized
changed = true
}
if normalized, err := NormalizePanelAccessPolicy(AppConfig.PanelAccessPolicy); err == nil {
if !panelAccessPoliciesEqual(AppConfig.PanelAccessPolicy, normalized) {
AppConfig.PanelAccessPolicy = normalized
changed = true
}
} else {
AppConfig.PanelAccessPolicy = PanelAccessPolicy{
AllowedSources: []string{},
TrustedProxies: []string{},
}
changed = true
}
if len(AppConfig.StoragePools) == 0 {
AppConfig.StoragePools = []StoragePool{defaultPrimaryStoragePool()}
changed = true
@@ -1067,6 +1126,14 @@ func normalizeConfigDefaults(dataDir string) bool {
AppConfig.EnabledImages = make([]string, 0)
changed = true
}
if AppConfig.CustomKVMImages == nil {
AppConfig.CustomKVMImages = make([]CustomKVMImage, 0)
changed = true
}
if AppConfig.CustomLXCImages == nil {
AppConfig.CustomLXCImages = make([]CustomLXCImage, 0)
changed = true
}
if AppConfig.Language == "" {
AppConfig.Language = "zh"
changed = true
@@ -1435,6 +1502,104 @@ func SaveConfig() error {
return saveConfigToDB()
}
func ListCustomKVMImages() []CustomKVMImage {
allocationMu.Lock()
defer allocationMu.Unlock()
if AppConfig == nil {
return nil
}
return append([]CustomKVMImage(nil), AppConfig.CustomKVMImages...)
}
func AddCustomKVMImage(image CustomKVMImage) error {
allocationMu.Lock()
defer allocationMu.Unlock()
for _, existing := range AppConfig.CustomKVMImages {
if existing.ID == image.ID {
return fmt.Errorf("custom KVM image %q already exists", image.ID)
}
}
AppConfig.CustomKVMImages = append(AppConfig.CustomKVMImages, image)
if err := SaveConfig(); err != nil {
AppConfig.CustomKVMImages = AppConfig.CustomKVMImages[:len(AppConfig.CustomKVMImages)-1]
return err
}
return nil
}
func RemoveCustomKVMImage(id string) (bool, error) {
allocationMu.Lock()
defer allocationMu.Unlock()
filtered := make([]CustomKVMImage, 0, len(AppConfig.CustomKVMImages))
found := false
for _, image := range AppConfig.CustomKVMImages {
if image.ID == id {
found = true
continue
}
filtered = append(filtered, image)
}
if !found {
return false, nil
}
previous := AppConfig.CustomKVMImages
AppConfig.CustomKVMImages = filtered
if err := SaveConfig(); err != nil {
AppConfig.CustomKVMImages = previous
return false, err
}
return true, nil
}
func ListCustomLXCImages() []CustomLXCImage {
allocationMu.Lock()
defer allocationMu.Unlock()
if AppConfig == nil {
return nil
}
return append([]CustomLXCImage(nil), AppConfig.CustomLXCImages...)
}
func AddCustomLXCImage(image CustomLXCImage) error {
allocationMu.Lock()
defer allocationMu.Unlock()
for _, existing := range AppConfig.CustomLXCImages {
if existing.ID == image.ID {
return fmt.Errorf("custom LXC image %q already exists", image.ID)
}
}
AppConfig.CustomLXCImages = append(AppConfig.CustomLXCImages, image)
if err := SaveConfig(); err != nil {
AppConfig.CustomLXCImages = AppConfig.CustomLXCImages[:len(AppConfig.CustomLXCImages)-1]
return err
}
return nil
}
func RemoveCustomLXCImage(id string) (bool, error) {
allocationMu.Lock()
defer allocationMu.Unlock()
filtered := make([]CustomLXCImage, 0, len(AppConfig.CustomLXCImages))
found := false
for _, image := range AppConfig.CustomLXCImages {
if image.ID == id {
found = true
continue
}
filtered = append(filtered, image)
}
if !found {
return false, nil
}
previous := AppConfig.CustomLXCImages
AppConfig.CustomLXCImages = filtered
if err := SaveConfig(); err != nil {
AppConfig.CustomLXCImages = previous
return false, err
}
return true, nil
}
// AddContainer adds a container to the config
func AddContainer(c Container) {
allocationMu.Lock()
@@ -1736,6 +1901,28 @@ func AllocateSSHPort() (int, error) {
func AllocateSSHPortExcluding(excluded []int) (int, error) {
allocationMu.Lock()
defer allocationMu.Unlock()
candidate, err := previewSSHPortExcluding(excluded)
if err != nil {
return 0, err
}
start, end := NATPortRange()
AppConfig.NextSSHPort = candidate + 1
if AppConfig.NextSSHPort > end {
AppConfig.NextSSHPort = start
}
SaveConfig()
return candidate, nil
}
// PreviewSSHPortExcluding returns the management port that the allocator would
// choose without advancing or persisting the allocation cursor.
func PreviewSSHPortExcluding(excluded []int) (int, error) {
allocationMu.Lock()
defer allocationMu.Unlock()
return previewSSHPortExcluding(excluded)
}
func previewSSHPortExcluding(excluded []int) (int, error) {
used := collectAllHostPorts()
for _, port := range excluded {
if port > 0 {
@@ -1753,11 +1940,6 @@ func AllocateSSHPortExcluding(excluded []int) (int, error) {
if used[candidate] {
continue
}
AppConfig.NextSSHPort = candidate + 1
if AppConfig.NextSSHPort > end {
AppConfig.NextSSHPort = start
}
SaveConfig()
return candidate, nil
}
return 0, fmt.Errorf("no free NAT4 host port in configured range %d-%d", start, end)
+144
View File
@@ -0,0 +1,144 @@
package config
import (
"encoding/binary"
"fmt"
"net/netip"
"os"
"strings"
)
const (
DefaultLXCNATSubnet = "10.0.3.0/24"
DefaultKVMNATSubnet = "192.168.122.0/24"
)
type NATNetwork struct {
Subnet string `json:"subnet"`
Gateway string `json:"gateway"`
Netmask string `json:"netmask"`
DHCPStart string `json:"dhcp_start"`
DHCPEnd string `json:"dhcp_end"`
DHCPMax int `json:"dhcp_max"`
PrefixBits int `json:"prefix_bits"`
}
func ParseNATNetwork(raw string) (NATNetwork, error) {
prefix, err := netip.ParsePrefix(strings.TrimSpace(raw))
if err != nil || !prefix.Addr().Is4() {
return NATNetwork{}, fmt.Errorf("NAT subnet must be a valid IPv4 CIDR")
}
prefix = prefix.Masked()
if prefix.Bits() < 16 || prefix.Bits() > 28 {
return NATNetwork{}, fmt.Errorf("NAT subnet prefix must be between /16 and /28")
}
if !isRFC1918Prefix(prefix) {
return NATNetwork{}, fmt.Errorf("NAT subnet must use an RFC1918 private IPv4 range")
}
network := ipv4Uint32(prefix.Addr())
hostBits := 32 - prefix.Bits()
broadcast := network | uint32((uint64(1)<<hostBits)-1)
gateway := uint32IPv4(network + 1)
dhcpStart := uint32IPv4(network + 2)
dhcpEnd := uint32IPv4(broadcast - 1)
return NATNetwork{
Subnet: prefix.String(),
Gateway: gateway.String(),
Netmask: netmaskString(prefix.Bits()),
DHCPStart: dhcpStart.String(),
DHCPEnd: dhcpEnd.String(),
DHCPMax: int(broadcast - network - 2),
PrefixBits: prefix.Bits(),
}, nil
}
func LXCNATNetwork() NATNetwork {
return configuredNATNetwork(false)
}
func KVMNATNetwork() NATNetwork {
return configuredNATNetwork(true)
}
func normalizeNATNetworkDefaults() bool {
changed := false
lxcSubnet := configuredSubnetValue(AppConfig.LXCNATSubnet, "CLICD_LXC_SUBNET", DefaultLXCNATSubnet)
kvmSubnet := configuredSubnetValue(AppConfig.KVMNATSubnet, "CLICD_KVM_SUBNET", DefaultKVMNATSubnet)
if AppConfig.LXCNATSubnet != lxcSubnet {
AppConfig.LXCNATSubnet = lxcSubnet
changed = true
}
if AppConfig.KVMNATSubnet != kvmSubnet {
AppConfig.KVMNATSubnet = kvmSubnet
changed = true
}
return changed
}
func configuredNATNetwork(kvm bool) NATNetwork {
raw := DefaultLXCNATSubnet
if kvm {
raw = DefaultKVMNATSubnet
}
if AppConfig != nil {
if kvm && AppConfig.KVMNATSubnet != "" {
raw = AppConfig.KVMNATSubnet
}
if !kvm && AppConfig.LXCNATSubnet != "" {
raw = AppConfig.LXCNATSubnet
}
}
network, err := ParseNATNetwork(raw)
if err == nil {
return network
}
network, _ = ParseNATNetwork(map[bool]string{false: DefaultLXCNATSubnet, true: DefaultKVMNATSubnet}[kvm])
return network
}
func configuredSubnetValue(current, envName, fallback string) string {
raw := strings.TrimSpace(current)
if envValue := strings.TrimSpace(os.Getenv(envName)); envValue != "" {
raw = envValue
}
if network, err := ParseNATNetwork(raw); err == nil {
return network.Subnet
}
network, _ := ParseNATNetwork(fallback)
return network.Subnet
}
func isRFC1918Prefix(prefix netip.Prefix) bool {
privateRanges := []netip.Prefix{
netip.MustParsePrefix("10.0.0.0/8"),
netip.MustParsePrefix("172.16.0.0/12"),
netip.MustParsePrefix("192.168.0.0/16"),
}
for _, privateRange := range privateRanges {
if privateRange.Contains(prefix.Addr()) {
last := uint32IPv4(ipv4Uint32(prefix.Addr()) | uint32((uint64(1)<<(32-prefix.Bits()))-1))
return privateRange.Contains(last)
}
}
return false
}
func ipv4Uint32(addr netip.Addr) uint32 {
bytes := addr.As4()
return binary.BigEndian.Uint32(bytes[:])
}
func uint32IPv4(value uint32) netip.Addr {
var bytes [4]byte
binary.BigEndian.PutUint32(bytes[:], value)
return netip.AddrFrom4(bytes)
}
func netmaskString(bits int) string {
mask := uint32(0)
if bits > 0 {
mask = ^uint32(0) << (32 - bits)
}
return uint32IPv4(mask).String()
}
@@ -0,0 +1,56 @@
package config
import "testing"
func TestParseNATNetwork(t *testing.T) {
network, err := ParseNATNetwork("172.28.40.0/24")
if err != nil {
t.Fatalf("ParseNATNetwork returned error: %v", err)
}
if network.Subnet != "172.28.40.0/24" ||
network.Gateway != "172.28.40.1" ||
network.Netmask != "255.255.255.0" ||
network.DHCPStart != "172.28.40.2" ||
network.DHCPEnd != "172.28.40.254" ||
network.DHCPMax != 253 {
t.Fatalf("unexpected network values: %+v", network)
}
}
func TestParseNATNetworkMasksHostBits(t *testing.T) {
network, err := ParseNATNetwork("10.44.8.99/20")
if err != nil {
t.Fatalf("ParseNATNetwork returned error: %v", err)
}
if network.Subnet != "10.44.0.0/20" || network.Gateway != "10.44.0.1" || network.DHCPEnd != "10.44.15.254" {
t.Fatalf("unexpected masked network values: %+v", network)
}
}
func TestParseNATNetworkRejectsUnsafeRanges(t *testing.T) {
for _, raw := range []string{
"203.0.113.0/24",
"10.0.0.0/15",
"10.0.0.0/29",
"not-a-subnet",
} {
if _, err := ParseNATNetwork(raw); err == nil {
t.Fatalf("ParseNATNetwork(%q) unexpectedly succeeded", raw)
}
}
}
func TestNormalizeNATNetworkDefaultsUsesEnvironment(t *testing.T) {
t.Setenv("CLICD_LXC_SUBNET", "172.30.8.0/24")
t.Setenv("CLICD_KVM_SUBNET", "10.230.0.0/20")
previous := AppConfig
AppConfig = &ClicdConfig{}
t.Cleanup(func() { AppConfig = previous })
if !normalizeNATNetworkDefaults() {
t.Fatal("expected defaults to change")
}
if AppConfig.LXCNATSubnet != "172.30.8.0/24" || AppConfig.KVMNATSubnet != "10.230.0.0/20" {
t.Fatalf("unexpected configured subnets: LXC=%s KVM=%s", AppConfig.LXCNATSubnet, AppConfig.KVMNATSubnet)
}
}
+24
View File
@@ -62,3 +62,27 @@ func TestAllocateSSHPortExcludingRequestedMappings(t *testing.T) {
t.Fatalf("allocated port = %d, want 32002", port)
}
}
func TestPreviewSSHPortUsesRangeWithoutAdvancingCursor(t *testing.T) {
previous := AppConfig
t.Cleanup(func() { AppConfig = previous })
AppConfig = &ClicdConfig{
NATPortStart: 30000,
NATPortEnd: 35000,
NextSSHPort: 30000,
Containers: []Container{{
PortMappings: []PortMapping{{HostPort: 30000}},
}},
}
port, err := PreviewSSHPortExcluding([]int{30001})
if err != nil {
t.Fatal(err)
}
if port != 30002 {
t.Fatalf("preview port = %d, want 30002", port)
}
if AppConfig.NextSSHPort != 30000 {
t.Fatalf("preview advanced cursor to %d", AppConfig.NextSSHPort)
}
}
+198
View File
@@ -0,0 +1,198 @@
package config
import (
"fmt"
"net"
"net/netip"
"strings"
)
// PanelAccessPolicy limits access to the complete web panel and API surface.
type PanelAccessPolicy struct {
Enabled bool `json:"enabled"`
AllowedSources []string `json:"allowed_sources"`
TrustedProxies []string `json:"trusted_proxies"`
}
// ForwardedClientHeaders contains proxy-provided client address headers.
type ForwardedClientHeaders struct {
ForwardedFor string
RealIP string
CFConnectingIP string
}
// PanelAccessDecision describes the address used by the access policy.
type PanelAccessDecision struct {
Allowed bool
DirectSource string
CurrentSource string
UsedForwarded bool
}
func NormalizePanelAccessPolicy(policy PanelAccessPolicy) (PanelAccessPolicy, error) {
allowed, err := normalizeIPRanges(policy.AllowedSources, "allowed source")
if err != nil {
return PanelAccessPolicy{}, err
}
trusted, err := normalizeIPRanges(policy.TrustedProxies, "trusted proxy")
if err != nil {
return PanelAccessPolicy{}, err
}
if policy.Enabled && len(allowed) == 0 {
return PanelAccessPolicy{}, fmt.Errorf("at least one allowed IP address or CIDR is required")
}
return PanelAccessPolicy{
Enabled: policy.Enabled,
AllowedSources: allowed,
TrustedProxies: trusted,
}, nil
}
func normalizeIPRanges(values []string, label string) ([]string, error) {
result := make([]string, 0, len(values))
seen := make(map[string]struct{}, len(values))
for _, raw := range values {
value := strings.TrimSpace(raw)
if value == "" {
continue
}
normalized, err := normalizeIPRange(value)
if err != nil {
return nil, fmt.Errorf("invalid %s %q: %w", label, value, err)
}
if _, exists := seen[normalized]; exists {
continue
}
seen[normalized] = struct{}{}
result = append(result, normalized)
}
return result, nil
}
func normalizeIPRange(value string) (string, error) {
if strings.Contains(value, "/") {
prefix, err := netip.ParsePrefix(value)
if err != nil {
return "", err
}
if prefix.Addr().Zone() != "" {
return "", fmt.Errorf("IPv6 zones are not supported")
}
return prefix.Masked().String(), nil
}
addr, err := netip.ParseAddr(value)
if err != nil {
return "", err
}
if addr.Zone() != "" {
return "", fmt.Errorf("IPv6 zones are not supported")
}
return addr.Unmap().String(), nil
}
func panelAccessPoliciesEqual(a, b PanelAccessPolicy) bool {
return a.Enabled == b.Enabled &&
stringSlicesEqual(a.AllowedSources, b.AllowedSources) &&
stringSlicesEqual(a.TrustedProxies, b.TrustedProxies)
}
func stringSlicesEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// EvaluatePanelAccess resolves the effective client address and applies policy.
// Forwarded headers are only considered when the TCP peer is trusted.
func EvaluatePanelAccess(policy PanelAccessPolicy, remoteAddr string, headers ForwardedClientHeaders) PanelAccessDecision {
direct, ok := parseRemoteIP(remoteAddr)
decision := PanelAccessDecision{}
if ok {
decision.DirectSource = direct.String()
decision.CurrentSource = direct.String()
}
if !policy.Enabled {
decision.Allowed = true
return decision
}
if !ok {
return decision
}
current := direct
if ipInRanges(direct, policy.TrustedProxies) {
if forwarded, forwardedOK := resolveForwardedIP(direct, policy.TrustedProxies, headers); forwardedOK {
current = forwarded
decision.CurrentSource = forwarded.String()
decision.UsedForwarded = true
}
}
// A direct local connection remains an emergency recovery path. When a
// trusted local reverse proxy forwards a client address, that client is
// still checked normally.
if current.IsLoopback() && !decision.UsedForwarded {
decision.Allowed = true
return decision
}
decision.Allowed = ipInRanges(current, policy.AllowedSources)
return decision
}
func parseRemoteIP(value string) (netip.Addr, bool) {
value = strings.TrimSpace(value)
if host, _, err := net.SplitHostPort(value); err == nil {
value = host
}
value = strings.TrimPrefix(strings.TrimSuffix(value, "]"), "[")
addr, err := netip.ParseAddr(value)
if err != nil {
return netip.Addr{}, false
}
return addr.Unmap(), true
}
func resolveForwardedIP(direct netip.Addr, trusted []string, headers ForwardedClientHeaders) (netip.Addr, bool) {
for _, raw := range []string{headers.CFConnectingIP, headers.RealIP} {
if addr, ok := parseRemoteIP(strings.TrimSpace(strings.Split(raw, ",")[0])); ok {
return addr, true
}
}
parts := strings.Split(headers.ForwardedFor, ",")
current := direct
found := false
for i := len(parts) - 1; i >= 0 && ipInRanges(current, trusted); i-- {
addr, ok := parseRemoteIP(strings.TrimSpace(parts[i]))
if !ok {
continue
}
current = addr
found = true
}
return current, found
}
func ipInRanges(addr netip.Addr, ranges []string) bool {
addr = addr.Unmap()
for _, raw := range ranges {
if strings.Contains(raw, "/") {
prefix, err := netip.ParsePrefix(raw)
if err == nil && prefix.Contains(addr) {
return true
}
continue
}
candidate, err := netip.ParseAddr(raw)
if err == nil && candidate.Unmap() == addr {
return true
}
}
return false
}
@@ -0,0 +1,146 @@
package config
import (
"reflect"
"testing"
)
func TestNormalizePanelAccessPolicy(t *testing.T) {
policy, err := NormalizePanelAccessPolicy(PanelAccessPolicy{
Enabled: true,
AllowedSources: []string{" 192.0.2.8 ", "10.20.30.44/24", "192.0.2.8", "2001:db8::1"},
TrustedProxies: []string{"127.0.0.1", "2001:db8:1::/64"},
})
if err != nil {
t.Fatalf("NormalizePanelAccessPolicy() error = %v", err)
}
if want := []string{"192.0.2.8", "10.20.30.0/24", "2001:db8::1"}; !reflect.DeepEqual(policy.AllowedSources, want) {
t.Fatalf("AllowedSources = %#v, want %#v", policy.AllowedSources, want)
}
if want := []string{"127.0.0.1", "2001:db8:1::/64"}; !reflect.DeepEqual(policy.TrustedProxies, want) {
t.Fatalf("TrustedProxies = %#v, want %#v", policy.TrustedProxies, want)
}
}
func TestNormalizePanelAccessPolicyRejectsEmptyEnabledPolicy(t *testing.T) {
if _, err := NormalizePanelAccessPolicy(PanelAccessPolicy{Enabled: true}); err == nil {
t.Fatal("expected enabled empty policy to fail")
}
}
func TestEvaluatePanelAccess(t *testing.T) {
base := PanelAccessPolicy{
Enabled: true,
AllowedSources: []string{"192.0.2.0/24", "2001:db8::/32"},
TrustedProxies: []string{"10.0.0.1", "127.0.0.1"},
}
tests := []struct {
name string
policy PanelAccessPolicy
remote string
headers ForwardedClientHeaders
allowed bool
current string
usedForwarded bool
}{
{
name: "disabled",
policy: PanelAccessPolicy{},
remote: "198.51.100.9:44321",
allowed: true,
current: "198.51.100.9",
},
{
name: "direct CIDR match",
policy: base,
remote: "192.0.2.25:44321",
allowed: true,
current: "192.0.2.25",
},
{
name: "direct denied",
policy: base,
remote: "198.51.100.9:44321",
allowed: false,
current: "198.51.100.9",
},
{
name: "spoofed forwarding header ignored",
policy: base,
remote: "198.51.100.9:44321",
headers: ForwardedClientHeaders{
ForwardedFor: "192.0.2.10",
},
allowed: false,
current: "198.51.100.9",
},
{
name: "trusted proxy forwards allowed source",
policy: base,
remote: "10.0.0.1:44321",
headers: ForwardedClientHeaders{
ForwardedFor: "192.0.2.10",
},
allowed: true,
current: "192.0.2.10",
usedForwarded: true,
},
{
name: "trusted proxy forwards denied source",
policy: base,
remote: "10.0.0.1:44321",
headers: ForwardedClientHeaders{
RealIP: "198.51.100.20",
},
allowed: false,
current: "198.51.100.20",
usedForwarded: true,
},
{
name: "direct loopback recovery",
policy: base,
remote: "127.0.0.1:44321",
allowed: true,
current: "127.0.0.1",
usedForwarded: false,
},
{
name: "trusted loopback proxy is enforced",
policy: base,
remote: "127.0.0.1:44321",
headers: ForwardedClientHeaders{
ForwardedFor: "198.51.100.20",
},
allowed: false,
current: "198.51.100.20",
usedForwarded: true,
},
{
name: "IPv6 source",
policy: base,
remote: "[2001:db8::88]:44321",
allowed: true,
current: "2001:db8::88",
},
{
name: "trusted proxy chain",
policy: base,
remote: "10.0.0.1:44321",
headers: ForwardedClientHeaders{
ForwardedFor: "192.0.2.70, 10.0.0.1",
},
allowed: true,
current: "192.0.2.70",
usedForwarded: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := EvaluatePanelAccess(tt.policy, tt.remote, tt.headers)
if got.Allowed != tt.allowed || got.CurrentSource != tt.current || got.UsedForwarded != tt.usedForwarded {
t.Fatalf("EvaluatePanelAccess() = %#v", got)
}
})
}
}
+19
View File
@@ -606,6 +606,8 @@ func loadConfigFromDB() (*ClicdConfig, bool, error) {
NextSSHPort: atoi(meta["next_ssh_port"]),
NATPortStart: atoi(meta["nat_port_start"]),
NATPortEnd: atoi(meta["nat_port_end"]),
LXCNATSubnet: meta["lxc_nat_subnet"],
KVMNATSubnet: meta["kvm_nat_subnet"],
SetupComplete: atob(meta["setup_complete"]),
SecurityAutoShutdown: atob(meta["security_auto_shutdown"]),
TaskConcurrency: atoi(meta["task_concurrency"]),
@@ -626,9 +628,18 @@ func loadConfigFromDB() (*ClicdConfig, bool, error) {
if raw := strings.TrimSpace(meta["webssh_allowed_origins"]); raw != "" {
_ = json.Unmarshal([]byte(raw), &cfg.WebSSHAllowedOrigins)
}
if raw := strings.TrimSpace(meta["panel_access_policy"]); raw != "" {
_ = json.Unmarshal([]byte(raw), &cfg.PanelAccessPolicy)
}
if raw := strings.TrimSpace(meta["storage_pools"]); raw != "" {
_ = json.Unmarshal([]byte(raw), &cfg.StoragePools)
}
if raw := strings.TrimSpace(meta["custom_kvm_images"]); raw != "" {
_ = json.Unmarshal([]byte(raw), &cfg.CustomKVMImages)
}
if raw := strings.TrimSpace(meta["custom_lxc_images"]); raw != "" {
_ = json.Unmarshal([]byte(raw), &cfg.CustomLXCImages)
}
if cfg.Containers, err = loadContainers(); err != nil {
return nil, false, err
@@ -729,7 +740,10 @@ func saveMeta(tx *sql.Tx) error {
publicIPv4PoolJSON, _ := json.Marshal(AppConfig.PublicIPv4Pool)
publicIPv6PrefixesJSON, _ := json.Marshal(AppConfig.PublicIPv6Prefixes)
webSSHAllowedOriginsJSON, _ := json.Marshal(AppConfig.WebSSHAllowedOrigins)
panelAccessPolicyJSON, _ := json.Marshal(AppConfig.PanelAccessPolicy)
storagePoolsJSON, _ := json.Marshal(AppConfig.StoragePools)
customKVMImagesJSON, _ := json.Marshal(AppConfig.CustomKVMImages)
customLXCImagesJSON, _ := json.Marshal(AppConfig.CustomLXCImages)
values := map[string]string{
"admin_user": AppConfig.AdminUser,
"admin_pass_hash": AppConfig.AdminPassHash,
@@ -741,6 +755,8 @@ func saveMeta(tx *sql.Tx) error {
"next_ssh_port": strconv.Itoa(AppConfig.NextSSHPort),
"nat_port_start": strconv.Itoa(AppConfig.NATPortStart),
"nat_port_end": strconv.Itoa(AppConfig.NATPortEnd),
"lxc_nat_subnet": AppConfig.LXCNATSubnet,
"kvm_nat_subnet": AppConfig.KVMNATSubnet,
"setup_complete": btoa(AppConfig.SetupComplete),
"security_auto_shutdown": btoa(AppConfig.SecurityAutoShutdown),
"task_concurrency": strconv.Itoa(AppConfig.TaskConcurrency),
@@ -750,7 +766,10 @@ func saveMeta(tx *sql.Tx) error {
"public_ipv4_pool": string(publicIPv4PoolJSON),
"public_ipv6_prefixes": string(publicIPv6PrefixesJSON),
"webssh_allowed_origins": string(webSSHAllowedOriginsJSON),
"panel_access_policy": string(panelAccessPolicyJSON),
"storage_pools": string(storagePoolsJSON),
"custom_kvm_images": string(customKVMImagesJSON),
"custom_lxc_images": string(customLXCImagesJSON),
"schema_version": "1",
"updated_at": time.Now().Format("2006-01-02 15:04:05"),
}
@@ -66,6 +66,34 @@ func TestSQLiteConfigMigratesLegacyJSONAndPersists(t *testing.T) {
Config: `{"name":"ct2","template_id":"debian-12","vcpu":1,"ram_mb":512,"disk_gb":5,"extra_ports":[80,443],"nat_port_mappings":[{"host_port":30080,"container_port":80,"protocol":"tcp","description":"HTTP"}],"management_port":30022,"assign_ipv6":true}`,
}},
EnabledImages: []string{"debian-12"},
CustomKVMImages: []CustomKVMImage{{
ID: "custom-kvm-test",
Name: "Test Cloud Image",
Description: "third-party image",
Distro: "ubuntu",
Release: "noble",
Arch: "amd64",
URL: "https://images.example.test/ubuntu.qcow2",
Provisioner: KVMProvisionerLinuxCloudInit,
SHA256: strings.Repeat("a", 64),
CreatedAt: "2026-07-26 10:00:00",
}},
CustomLXCImages: []CustomLXCImage{{
ID: "custom-lxc-test",
Name: "Test Rootfs",
Description: "third-party LXC image",
Distro: "alpine",
Release: "3.21",
Arch: "amd64",
URL: "https://images.example.test/alpine-rootfs.tar.xz",
SHA256: strings.Repeat("b", 64),
CreatedAt: "2026-07-26 10:00:00",
}},
PanelAccessPolicy: PanelAccessPolicy{
Enabled: true,
AllowedSources: []string{"192.0.2.0/24"},
TrustedProxies: []string{"127.0.0.1"},
},
Snapshots: []Snapshot{{
ID: "snap-1",
ContainerID: 1,
@@ -102,6 +130,15 @@ func TestSQLiteConfigMigratesLegacyJSONAndPersists(t *testing.T) {
if cfg.TaskConcurrency != DefaultTaskConcurrency {
t.Fatalf("legacy task concurrency = %d, want default %d", cfg.TaskConcurrency, DefaultTaskConcurrency)
}
if !cfg.PanelAccessPolicy.Enabled || len(cfg.PanelAccessPolicy.AllowedSources) != 1 {
t.Fatalf("legacy panel access policy was not migrated: %+v", cfg.PanelAccessPolicy)
}
if len(cfg.CustomKVMImages) != 1 || cfg.CustomKVMImages[0].ID != "custom-kvm-test" {
t.Fatalf("legacy custom KVM images were not migrated: %+v", cfg.CustomKVMImages)
}
if len(cfg.CustomLXCImages) != 1 || cfg.CustomLXCImages[0].ID != "custom-lxc-test" {
t.Fatalf("legacy custom LXC images were not migrated: %+v", cfg.CustomLXCImages)
}
if _, err := os.Stat(filepath.Join(dir, "config.db")); err != nil {
t.Fatalf("sqlite database was not created: %v", err)
}
@@ -124,6 +161,15 @@ func TestSQLiteConfigMigratesLegacyJSONAndPersists(t *testing.T) {
if got := cfg.TaskConcurrency; got != 6 {
t.Fatalf("persisted task concurrency = %d, want 6", got)
}
if !cfg.PanelAccessPolicy.Enabled || cfg.PanelAccessPolicy.AllowedSources[0] != "192.0.2.0/24" {
t.Fatalf("persisted panel access policy = %+v", cfg.PanelAccessPolicy)
}
if len(cfg.CustomKVMImages) != 1 || cfg.CustomKVMImages[0].SHA256 != strings.Repeat("a", 64) {
t.Fatalf("persisted custom KVM images = %+v", cfg.CustomKVMImages)
}
if len(cfg.CustomLXCImages) != 1 || cfg.CustomLXCImages[0].SHA256 != strings.Repeat("b", 64) {
t.Fatalf("persisted custom LXC images = %+v", cfg.CustomLXCImages)
}
}
func resetConfigStoreForTest(t *testing.T) {
+66 -39
View File
@@ -29,6 +29,7 @@ import (
"clicd/internal/config"
"clicd/internal/lxc"
"clicd/internal/safehttp"
"golang.org/x/crypto/ssh"
)
@@ -166,7 +167,7 @@ func DownloadImageWithProgress(ctx context.Context, image Image, progress Downlo
return err
}
ext := ".qcow2"
if image.Distro == "windows" {
if image.IsWindows() {
ext = ".iso"
}
target := filepath.Join(cacheDir, image.ID+ext)
@@ -184,7 +185,7 @@ func DownloadImageWithProgress(ctx context.Context, image Image, progress Downlo
}
tmp := target + ".tmp"
_ = os.Remove(tmp)
if image.Distro == "windows" {
if image.IsWindows() {
if err := downloadFileWithValidator(ctx, image.URL, tmp, validateWindowsISOResponse(target), progress); err != nil {
_ = os.Remove(tmp)
return err
@@ -197,7 +198,13 @@ func DownloadImageWithProgress(ctx context.Context, image Image, progress Downlo
_ = os.Remove(tmp)
return err
}
if image.Distro == "windows" {
if image.SHA256 != "" {
if err := verifyFileSHA256(tmp, image.SHA256); err != nil {
_ = os.Remove(tmp)
return err
}
}
if image.IsWindows() {
if err := validateWindowsISO(tmp, target); err != nil {
_ = os.Remove(tmp)
return err
@@ -221,6 +228,23 @@ func DownloadImageWithProgress(ctx context.Context, image Image, progress Downlo
return nil
}
func verifyFileSHA256(path, expected string) error {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return err
}
actual := hex.EncodeToString(hash.Sum(nil))
if !strings.EqualFold(actual, strings.TrimSpace(expected)) {
return fmt.Errorf("SHA-256 mismatch: expected %s, got %s", expected, actual)
}
return nil
}
func DeleteImage(id string) error {
return os.RemoveAll(ImagePath(id))
}
@@ -232,26 +256,8 @@ func downloadFile(ctx context.Context, url, target string, progress DownloadProg
}
func downloadFileWithValidator(ctx context.Context, url, target string, validate downloadResponseValidator, progress DownloadProgressFunc) error {
client := http.Client{
Timeout: 30 * time.Minute,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return fmt.Errorf("too many redirects")
}
// Copy User-Agent on redirect
if ua := via[0].Header.Get("User-Agent"); ua != "" {
req.Header.Set("User-Agent", ua)
}
return nil
},
}
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return err
}
// Windows UA needed for Microsoft download servers
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
resp, err := client.Do(req)
const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
resp, err := safehttp.Get(ctx, url, userAgent, 30*time.Minute)
if err != nil {
return err
}
@@ -500,11 +506,15 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig
var xml string
winAdminPassword := ""
if IsWindowsImage(image.ID) {
if cfg.RAMMB < 2048 {
cfg.RAMMB = 2048
minVCPU, minRAMMB, minDiskGB := windowsMinimumResources(image.ID)
if cfg.VCPU < minVCPU {
cfg.VCPU = minVCPU
}
if cfg.DiskGB < 30 {
cfg.DiskGB = 30
if cfg.RAMMB < minRAMMB {
cfg.RAMMB = minRAMMB
}
if cfg.DiskGB < minDiskGB {
cfg.DiskGB = minDiskGB
}
cfg.ReportProgress("disk", "创建 Windows 虚拟磁盘")
if err := createEmptyDisk(diskPath, cfg.DiskGB); err != nil {
@@ -516,7 +526,7 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig
winAdminPassword = generateWindowsPassword()
unattendPath := filepath.Join(m.instanceDir(vmName), "unattend.iso")
cfg.ReportProgress("cloud_init", "生成 Windows 自动应答配置")
if err := createWindowsUnattendISO(unattendPath, cfg.Name, winAdminPassword, mac, ipv6List, ipv4List); err != nil {
if err := createWindowsUnattendISO(unattendPath, cfg.Name, winAdminPassword, mac, ipv6List, ipv4List, IsWindows11Image(image.ID)); err != nil {
return nil, err
}
xml = windowsDomainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, ImagePath(image.ID), unattendPath, mac, cfg.IOReadMBps, cfg.IOWriteMBps, cfg.NetworkDownMbps, cfg.NetworkUpMbps)
@@ -1724,16 +1734,17 @@ func ensureDefaultNetwork() error {
// Ensure default network is defined
if virshCLocaleCommand("net-info", "default").Run() != nil {
// Default network may not be defined; try to define it
netXML := `<network>
network := config.KVMNATNetwork()
netXML := fmt.Sprintf(`<network>
<name>default</name>
<bridge name='virbr0'/>
<forward mode='nat'/>
<ip address='192.168.122.1' netmask='255.255.255.0'>
<ip address='%s' netmask='%s'>
<dhcp>
<range start='192.168.122.2' end='192.168.122.254'/>
<range start='%s' end='%s'/>
</dhcp>
</ip>
</network>`
</network>`, network.Gateway, network.Netmask, network.DHCPStart, network.DHCPEnd)
tmpFile := filepath.Join(os.TempDir(), "clicd-default-net.xml")
if err := os.WriteFile(tmpFile, []byte(netXML), 0644); err != nil {
return fmt.Errorf("failed to write default network XML: %v", err)
@@ -1832,7 +1843,7 @@ func createEmptyDisk(target string, diskGB int) error {
return nil
}
func createWindowsUnattendISO(target, hostname, adminPassword, mac string, ipv6s []string, ipv4s []string) error {
func createWindowsUnattendISO(target, hostname, adminPassword, mac string, ipv6s []string, ipv4s []string, windows11 bool) error {
tool := firstAvailableCommand("genisoimage", "mkisofs", "xorriso")
if tool == "" {
return fmt.Errorf("one of genisoimage, mkisofs, xorriso is required for Windows unattended setup")
@@ -1852,7 +1863,7 @@ func createWindowsUnattendISO(target, hostname, adminPassword, mac string, ipv6s
return err
}
}
if err := os.WriteFile(answerPath, []byte(windowsAutounattendXML(hostname, adminPassword)), 0600); err != nil {
if err := os.WriteFile(answerPath, []byte(windowsAutounattendXML(hostname, adminPassword, windows11)), 0600); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(setupScriptsDir, "SetupComplete.cmd"), []byte(windowsSetupCompleteCMD()), 0600); err != nil {
@@ -1890,12 +1901,21 @@ func firstAvailableCommand(names ...string) string {
return ""
}
func windowsAutounattendXML(hostname, adminPassword string) string {
func windowsAutounattendXML(hostname, adminPassword string, windows11 bool) string {
if strings.TrimSpace(hostname) == "" {
hostname = "clicd-win"
}
hostname = sanitizeWindowsComputerName(hostname)
setupCommand := `cmd.exe /c if exist C:\CLICD\FirstLogon.ps1 (powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\CLICD\FirstLogon.ps1) else (for %%d in (D E F G H I J K L M N O P Q R S T U V W X Y Z) do @if exist %%d:\FirstLogon.ps1 powershell.exe -NoProfile -ExecutionPolicy Bypass -File %%d:\FirstLogon.ps1)`
setupCommand := `cmd.exe /c if exist C:\CLICD\FirstLogon.ps1 (powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\CLICD\FirstLogon.ps1) else (for %d in (D E F G H I J K L M N O P Q R S T U V W X Y Z) do @if exist %d:\FirstLogon.ps1 powershell.exe -NoProfile -ExecutionPolicy Bypass -File %d:\FirstLogon.ps1)`
compatibilityCommands := ""
if windows11 {
compatibilityCommands = `
<RunSynchronous>
<RunSynchronousCommand wcm:action="add"><Order>1</Order><Description>Allow virtual TPM compatibility</Description><Path>reg.exe add HKLM\SYSTEM\Setup\LabConfig /v BypassTPMCheck /t REG_DWORD /d 1 /f</Path></RunSynchronousCommand>
<RunSynchronousCommand wcm:action="add"><Order>2</Order><Description>Allow virtual Secure Boot compatibility</Description><Path>reg.exe add HKLM\SYSTEM\Setup\LabConfig /v BypassSecureBootCheck /t REG_DWORD /d 1 /f</Path></RunSynchronousCommand>
<RunSynchronousCommand wcm:action="add"><Order>3</Order><Description>Allow virtual CPU compatibility</Description><Path>reg.exe add HKLM\SYSTEM\Setup\LabConfig /v BypassCPUCheck /t REG_DWORD /d 1 /f</Path></RunSynchronousCommand>
</RunSynchronous>`
}
return fmt.Sprintf(`<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
<settings pass="windowsPE">
@@ -1924,7 +1944,7 @@ func windowsAutounattendXML(hostname, adminPassword string) string {
<AcceptEula>true</AcceptEula>
<FullName>CLICD</FullName>
<Organization>CLICD</Organization>
</UserData>
</UserData>%s
</component>
</settings>
<settings pass="specialize">
@@ -1945,7 +1965,14 @@ func windowsAutounattendXML(hostname, adminPassword string) string {
</component>
</settings>
</unattend>
`, xmlEscape(hostname), xmlEscape(adminPassword), xmlEscape(adminPassword), xmlEscape(setupCommand))
`, compatibilityCommands, xmlEscape(hostname), xmlEscape(adminPassword), xmlEscape(adminPassword), xmlEscape(setupCommand))
}
func windowsMinimumResources(imageID string) (float64, int, int) {
if IsWindows11Image(imageID) {
return 2, 4096, 64
}
return 1, 2048, 30
}
func sanitizeWindowsComputerName(name string) string {
@@ -2179,7 +2206,7 @@ runcmd:
// Build static address block (IPv4 + IPv6)
ipv4s = normalizeKVMIPv4List(ipv4s)
addressBlock := ""
addressLines := make([]string, 0, len(ipv4s)+len(ipv6s))
addressLines := make([]string, 0, len(ipv4s))
for _, ipv4 := range ipv4s {
addressLines = append(addressLines, fmt.Sprintf(" - %s/32", ipv4))
}
+122
View File
@@ -3,8 +3,14 @@ package kvm
import (
"crypto/ed25519"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/xml"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"clicd/internal/config"
@@ -24,6 +30,51 @@ func TestImagePathUsesAllowlistedImageID(t *testing.T) {
}
}
func TestWindows11ImageDefinition(t *testing.T) {
image := FindImage("kvm-windows-11")
if image == nil {
t.Fatal("Windows 11 image is missing from the amd64 image list")
}
if image.Distro != "windows" || image.Release != "11" || image.Arch != "amd64" {
t.Fatalf("Windows 11 image metadata = %+v", image)
}
if !strings.Contains(image.URL, "microsoft.com/fwlink/") {
t.Fatalf("Windows 11 image does not use an official Microsoft URL: %s", image.URL)
}
if got := filepath.Base(ImagePath(image.ID)); got != "kvm-windows-11.iso" {
t.Fatalf("Windows 11 image basename = %q", got)
}
}
func TestWindows11UnattendAddsCompatibilityChecksOnlyForWindows11(t *testing.T) {
windows11 := windowsAutounattendXML("win11-test", "Password123!", true)
windows10 := windowsAutounattendXML("win10-test", "Password123!", false)
for _, key := range []string{"BypassTPMCheck", "BypassSecureBootCheck", "BypassCPUCheck"} {
if !strings.Contains(windows11, key) {
t.Fatalf("Windows 11 unattend is missing %s", key)
}
if strings.Contains(windows10, key) {
t.Fatalf("Windows 10 unattend unexpectedly contains %s", key)
}
}
var document struct {
XMLName xml.Name
}
if err := xml.Unmarshal([]byte(windows11), &document); err != nil {
t.Fatalf("Windows 11 unattend XML is invalid: %v", err)
}
}
func TestWindowsMinimumResources(t *testing.T) {
if cpu, ram, disk := windowsMinimumResources("kvm-windows-11"); cpu != 2 || ram != 4096 || disk != 64 {
t.Fatalf("Windows 11 minimums = %v vCPU, %d MB, %d GB", cpu, ram, disk)
}
if cpu, ram, disk := windowsMinimumResources("kvm-windows-10"); cpu != 1 || ram != 2048 || disk != 30 {
t.Fatalf("Windows 10 minimums = %v vCPU, %d MB, %d GB", cpu, ram, disk)
}
}
func TestLibvirtNetworkActiveParsesCLocaleOutput(t *testing.T) {
tests := []struct {
name string
@@ -115,6 +166,77 @@ func TestVerifyKVMHostKeyCapturesAndRejectsMismatch(t *testing.T) {
}
}
func TestGetImagesIncludesHostArchitectureCustomImage(t *testing.T) {
previous := config.AppConfig
t.Cleanup(func() { config.AppConfig = previous })
config.AppConfig = &config.ClicdConfig{
CustomKVMImages: []config.CustomKVMImage{
{
ID: "custom-kvm-linux",
Name: "Custom Linux",
Distro: "ubuntu",
Release: "noble",
Arch: runtime.GOARCH,
URL: "https://example.test/linux.qcow2",
Provisioner: config.KVMProvisionerLinuxCloudInit,
},
{
ID: "custom-kvm-other-arch",
Name: "Other Architecture",
Distro: "ubuntu",
Release: "noble",
Arch: "not-" + runtime.GOARCH,
URL: "https://example.test/other.qcow2",
Provisioner: config.KVMProvisionerLinuxCloudInit,
},
},
}
image := FindImage("custom-kvm-linux")
if image == nil || !image.Custom || image.Provisioner != config.KVMProvisionerLinuxCloudInit {
t.Fatalf("custom image was not exposed correctly: %+v", image)
}
if FindImage("custom-kvm-other-arch") != nil {
t.Fatal("custom image for another architecture was exposed")
}
}
func TestCustomWindowsProvisionerControlsImageType(t *testing.T) {
previous := config.AppConfig
t.Cleanup(func() { config.AppConfig = previous })
config.AppConfig = &config.ClicdConfig{CustomKVMImages: []config.CustomKVMImage{{
ID: "custom-kvm-windows",
Name: "Custom Windows",
Distro: "windows",
Release: "11",
Arch: runtime.GOARCH,
URL: "https://example.test/windows.iso",
Provisioner: config.KVMProvisionerWindows11,
}}}
if !IsWindowsImage("custom-kvm-windows") || !IsWindows11Image("custom-kvm-windows") {
t.Fatal("custom Windows 11 provisioner was not recognized")
}
if ext := filepath.Ext(ImagePath("custom-kvm-windows")); ext != ".iso" {
t.Fatalf("custom Windows image extension = %q, want .iso", ext)
}
}
func TestVerifyFileSHA256(t *testing.T) {
path := filepath.Join(t.TempDir(), "image")
content := []byte("clicd custom image")
if err := os.WriteFile(path, content, 0600); err != nil {
t.Fatal(err)
}
sum := sha256.Sum256(content)
if err := verifyFileSHA256(path, hex.EncodeToString(sum[:])); err != nil {
t.Fatalf("valid checksum failed: %v", err)
}
if err := verifyFileSHA256(path, strings.Repeat("0", 64)); err == nil {
t.Fatal("invalid checksum unexpectedly passed")
}
}
func testSSHPublicKey(t *testing.T) ssh.PublicKey {
t.Helper()
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
+49 -5
View File
@@ -17,15 +17,37 @@ type Image struct {
Description string `json:"description"`
URL string `json:"url"`
Desktop string `json:"desktop,omitempty"`
Provisioner string `json:"provisioner,omitempty"`
SHA256 string `json:"sha256,omitempty"`
Custom bool `json:"custom,omitempty"`
}
func GetImages() []Image {
var images []Image
switch runtime.GOARCH {
case "arm64":
return arm64Images()
images = arm64Images()
default:
return amd64Images()
images = amd64Images()
}
for _, custom := range config.ListCustomKVMImages() {
if custom.Arch != runtime.GOARCH {
continue
}
images = append(images, Image{
ID: custom.ID,
Name: custom.Name,
Distro: custom.Distro,
Release: custom.Release,
Arch: custom.Arch,
Description: custom.Description,
URL: custom.URL,
Provisioner: custom.Provisioner,
SHA256: custom.SHA256,
Custom: true,
})
}
return images
}
func amd64Images() []Image {
@@ -111,6 +133,12 @@ func amd64Images() []Image {
Description: "Rocky Linux 9 GenericCloud image for KVM",
URL: "https://dl.rockylinux.org/pub/rocky/9/images/x86_64/Rocky-9-GenericCloud-Base.latest.x86_64.qcow2",
},
{
ID: "kvm-windows-11", Name: "Windows 11 KVM",
Distro: "windows", Release: "11", Arch: "amd64",
Description: "Windows 11 Enterprise LTSC 2024 Evaluation",
URL: "https://go.microsoft.com/fwlink/?clcid=0x409&country=us&culture=en-us&linkid=2289029",
},
{
ID: "kvm-windows-10", Name: "Windows 10 KVM",
Distro: "windows", Release: "10", Arch: "amd64",
@@ -196,7 +224,7 @@ func ImagePath(id string) string {
if img != nil {
safeID = img.ID
}
if img != nil && img.Distro == "windows" {
if img != nil && img.IsWindows() {
ext = ".iso"
}
fileName := safeID + ext
@@ -213,10 +241,26 @@ func ImagePath(id string) string {
return filepath.Join(CacheDir(), fileName)
}
// IsWindowsImage returns true if the image distro is "windows".
func (image Image) IsWindows() bool {
return image.Provisioner == config.KVMProvisionerWindows10 ||
image.Provisioner == config.KVMProvisionerWindows11 ||
(image.Provisioner == "" && image.Distro == "windows")
}
func (image Image) IsWindows11() bool {
return image.Provisioner == config.KVMProvisionerWindows11 ||
(image.Provisioner == "" && image.Distro == "windows" && image.Release == "11")
}
// IsWindowsImage returns true if the image uses Windows unattended installation.
func IsWindowsImage(id string) bool {
img := FindImage(id)
return img != nil && img.Distro == "windows"
return img != nil && img.IsWindows()
}
func IsWindows11Image(id string) bool {
img := FindImage(id)
return img != nil && img.IsWindows11()
}
func virtioWinISOPath() string {
+297
View File
@@ -0,0 +1,297 @@
package lxc
import (
"bufio"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"time"
"clicd/internal/safehttp"
)
type CustomImageDownloadProgress struct {
Stage string
DownloadedBytes int64
TotalBytes int64
Percent int
}
type CustomImageDownloadProgressFunc func(CustomImageDownloadProgress)
func CustomImagePath(id string) string {
template := FindTemplate(id)
if template == nil || !template.Custom {
return filepath.Join("/var/cache/lxc/download/custom", "__invalid_image_id__", "rootfs.tar")
}
return filepath.Join("/var/cache/lxc/download/custom", template.ID, "rootfs.tar")
}
func CustomImageDownloadedInfo(id string) (bool, int64) {
info, err := os.Stat(CustomImagePath(id))
if err != nil || info.IsDir() {
return false, 0
}
return true, info.Size()
}
func DeleteCustomImage(id string) error {
template := FindTemplate(id)
if template == nil || !template.Custom {
return fmt.Errorf("custom LXC image not found")
}
return os.RemoveAll(filepath.Dir(CustomImagePath(id)))
}
func DownloadCustomImageWithProgress(ctx context.Context, template Template, progress CustomImageDownloadProgressFunc) error {
if !template.Custom {
return fmt.Errorf("template is not a custom LXC image")
}
target := CustomImagePath(template.ID)
if ok, _ := CustomImageDownloadedInfo(template.ID); ok {
return nil
}
if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil {
return err
}
tmp := target + ".tmp"
_ = os.Remove(tmp)
if err := downloadCustomRootfs(ctx, template.URL, tmp, progress); err != nil {
_ = os.Remove(tmp)
return err
}
if err := ctx.Err(); err != nil {
_ = os.Remove(tmp)
return err
}
if template.SHA256 != "" {
if err := verifyCustomRootfsSHA256(tmp, template.SHA256); err != nil {
_ = os.Remove(tmp)
return err
}
}
if progress != nil {
progress(CustomImageDownloadProgress{Stage: "validating", Percent: 100})
}
if err := ValidateCustomRootfsArchive(tmp); err != nil {
_ = os.Remove(tmp)
return err
}
if err := os.Rename(tmp, target); err != nil {
_ = os.Remove(tmp)
return err
}
return os.Chmod(target, 0644)
}
func downloadCustomRootfs(ctx context.Context, sourceURL, target string, progress CustomImageDownloadProgressFunc) error {
response, err := safehttp.Get(ctx, sourceURL, "CLICD/1.0 LXC image downloader", 30*time.Minute)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode >= 300 {
return fmt.Errorf("download failed: %s", response.Status)
}
file, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer file.Close()
total := response.ContentLength
buffer := make([]byte, 128*1024)
var downloaded int64
for {
count, readErr := response.Body.Read(buffer)
if count > 0 {
if _, err := file.Write(buffer[:count]); err != nil {
return err
}
downloaded += int64(count)
if progress != nil {
percent := 0
if total > 0 {
percent = int(downloaded * 100 / total)
if percent > 100 {
percent = 100
}
}
progress(CustomImageDownloadProgress{
Stage: "downloading",
DownloadedBytes: downloaded,
TotalBytes: total,
Percent: percent,
})
}
}
if readErr == io.EOF {
break
}
if readErr != nil {
return readErr
}
}
return file.Sync()
}
func verifyCustomRootfsSHA256(filePath, expected string) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return err
}
actual := hex.EncodeToString(hash.Sum(nil))
if !strings.EqualFold(actual, strings.TrimSpace(expected)) {
return fmt.Errorf("SHA-256 mismatch: expected %s, got %s", expected, actual)
}
return nil
}
func ValidateCustomRootfsArchive(archivePath string) error {
command := exec.Command("tar", "-tf", archivePath)
stdout, err := command.StdoutPipe()
if err != nil {
return err
}
var stderr strings.Builder
command.Stderr = &stderr
if err := command.Start(); err != nil {
return fmt.Errorf("failed to inspect rootfs archive: %v", err)
}
scanner := bufio.NewScanner(stdout)
scanner.Buffer(make([]byte, 64*1024), 1024*1024)
entries := make([]string, 0, 4096)
for scanner.Scan() {
if len(entries) >= 2_000_000 {
_ = command.Process.Kill()
return fmt.Errorf("rootfs archive contains too many entries")
}
entries = append(entries, scanner.Text())
}
scanErr := scanner.Err()
waitErr := command.Wait()
if scanErr != nil {
return fmt.Errorf("failed to read rootfs archive: %v", scanErr)
}
if waitErr != nil {
return fmt.Errorf("invalid rootfs archive: %v, output: %s", waitErr, strings.TrimSpace(stderr.String()))
}
return validateCustomRootfsEntries(entries)
}
func validateCustomRootfsEntries(entries []string) error {
hasInit := false
for _, entry := range entries {
entry = strings.TrimSpace(strings.ReplaceAll(entry, "\\", "/"))
entry = strings.TrimPrefix(entry, "./")
if entry == "" || entry == "." {
continue
}
if strings.HasPrefix(entry, "/") {
return fmt.Errorf("rootfs archive contains an absolute path: %s", entry)
}
clean := path.Clean(entry)
if clean == ".." || strings.HasPrefix(clean, "../") {
return fmt.Errorf("rootfs archive contains path traversal: %s", entry)
}
switch strings.TrimSuffix(clean, "/") {
case "sbin/init", "usr/lib/systemd/systemd", "lib/systemd/systemd", "bin/busybox", "bin/sh":
hasInit = true
}
}
if len(entries) == 0 {
return fmt.Errorf("rootfs archive is empty")
}
if !hasInit {
return fmt.Errorf("rootfs archive does not contain a supported init")
}
return nil
}
func ExtractCustomRootfs(templateID, destination string) error {
template := FindTemplate(templateID)
if template == nil || !template.Custom {
return fmt.Errorf("custom LXC image not found: %s", templateID)
}
archive := CustomImagePath(template.ID)
if ok, _ := CustomImageDownloadedInfo(template.ID); !ok {
return fmt.Errorf("custom LXC image is not downloaded: %s", templateID)
}
if err := ValidateCustomRootfsArchive(archive); err != nil {
return err
}
if err := os.MkdirAll(destination, 0755); err != nil {
return err
}
output, err := exec.Command("tar", "-xpf", archive, "-C", destination).CombinedOutput()
if err != nil {
return fmt.Errorf("failed to extract custom LXC rootfs: %v, output: %s", err, strings.TrimSpace(string(output)))
}
if err := secureExtractedRootfs(destination); err != nil {
return err
}
if !rootfsHasInit(destination) {
return fmt.Errorf("extracted custom LXC rootfs is invalid: init not found")
}
return nil
}
func secureExtractedRootfs(root string) error {
root, err := filepath.Abs(root)
if err != nil {
return err
}
return filepath.WalkDir(root, func(filePath string, entry os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
info, err := entry.Info()
if err != nil {
return err
}
if info.Mode()&os.ModeSymlink == 0 {
return nil
}
target, err := os.Readlink(filePath)
if err != nil {
return err
}
var resolved string
if filepath.IsAbs(target) {
resolved = filepath.Join(root, strings.TrimLeft(filepath.ToSlash(target), "/"))
relative, err := filepath.Rel(filepath.Dir(filePath), resolved)
if err != nil {
return err
}
if err := os.Remove(filePath); err != nil {
return err
}
if err := os.Symlink(relative, filePath); err != nil {
return err
}
} else {
resolved = filepath.Join(filepath.Dir(filePath), target)
}
relativeToRoot, err := filepath.Rel(root, filepath.Clean(resolved))
if err != nil {
return err
}
if relativeToRoot == ".." || strings.HasPrefix(relativeToRoot, ".."+string(os.PathSeparator)) {
return fmt.Errorf("rootfs symlink escapes the archive root: %s -> %s", filePath, target)
}
return nil
})
}
@@ -0,0 +1,61 @@
package lxc
import (
"path/filepath"
"runtime"
"testing"
"clicd/internal/config"
)
func TestGetTemplatesIncludesHostArchitectureCustomLXCImage(t *testing.T) {
previous := config.AppConfig
t.Cleanup(func() { config.AppConfig = previous })
config.AppConfig = &config.ClicdConfig{CustomLXCImages: []config.CustomLXCImage{
{
ID: "custom-lxc-host", Name: "Host Rootfs", Distro: "alpine",
Release: "3.21", Arch: runtime.GOARCH, URL: "https://example.test/rootfs.tar.xz",
},
{
ID: "custom-lxc-other", Name: "Other Rootfs", Distro: "alpine",
Release: "3.21", Arch: "not-" + runtime.GOARCH, URL: "https://example.test/other.tar.xz",
},
}}
template := FindTemplate("custom-lxc-host")
if template == nil || !template.Custom || template.URL == "" {
t.Fatalf("custom LXC template was not exposed correctly: %+v", template)
}
if FindTemplate("custom-lxc-other") != nil {
t.Fatal("custom LXC template for another architecture was exposed")
}
}
func TestCustomImagePathUsesAllowlistedID(t *testing.T) {
previous := config.AppConfig
t.Cleanup(func() { config.AppConfig = previous })
config.AppConfig = &config.ClicdConfig{}
for _, id := range []string{"", ".", "..", "../../etc/passwd", "/absolute", "unknown"} {
got := filepath.ToSlash(CustomImagePath(id))
if filepath.Base(filepath.Dir(got)) != "__invalid_image_id__" {
t.Fatalf("CustomImagePath(%q) = %q", id, got)
}
}
}
func TestValidateCustomRootfsEntries(t *testing.T) {
if err := validateCustomRootfsEntries([]string{"./etc/", "./bin/", "./bin/sh"}); err != nil {
t.Fatalf("valid rootfs entries failed: %v", err)
}
for _, entries := range [][]string{
{},
{"etc/passwd"},
{"/etc/passwd", "bin/sh"},
{"../../etc/passwd", "bin/sh"},
} {
if err := validateCustomRootfsEntries(entries); err == nil {
t.Fatalf("unsafe rootfs entries unexpectedly passed: %#v", entries)
}
}
}
+1 -1
View File
@@ -1591,7 +1591,7 @@ func (m *Manager) applyIPv6Config(lxcName string, ipv6s ...string) error {
return fmt.Errorf("failed to read container config: %v", err)
}
lines := strings.Split(string(data), "\n")
next := make([]string, 0, len(lines)+4)
next := make([]string, 0, len(lines))
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.Contains(trimmed, "# clicd managed: public IPv6") ||
+67 -4
View File
@@ -410,7 +410,7 @@ func (cfg *ContainerConfig) NormalizeCreateNATMappings() error {
}
func (cfg ContainerConfig) RequestedNATHostPorts() []int {
ports := make([]int, 0, len(cfg.NATPortMappings)+1)
ports := make([]int, 0, len(cfg.NATPortMappings))
if cfg.ManagementPort > 0 {
ports = append(ports, cfg.ManagementPort)
}
@@ -503,6 +503,20 @@ func (m *Manager) CreateContainer(cfg ContainerConfig) error {
lxcName, id, tmpl.Distro, tmpl.Release, tmpl.Arch)
cfg.ReportProgress("rootfs", "下载模板并创建基础文件系统")
if tmpl.Custom {
output, err := exec.Command("lxc-create", "-n", lxcName, "-t", "none").CombinedOutput()
if err != nil {
return fmt.Errorf("lxc-create failed for custom rootfs: %v, output: %s", err, string(output))
}
if err := m.configureCustomLXCBase(lxcName, tmpl); err != nil {
_ = m.cleanupContainerStorage(lxcName)
return err
}
if err := ExtractCustomRootfs(tmpl.ID, filepath.Join(containerDir, "rootfs")); err != nil {
_ = m.cleanupContainerStorage(lxcName)
return err
}
} else {
args := []string{"-n", lxcName, "-t", "download", "--",
"-d", tmpl.Distro, "-r", tmpl.Release, "-a", tmpl.Arch}
if tmpl.Variant != "" {
@@ -513,6 +527,7 @@ func (m *Manager) CreateContainer(cfg ContainerConfig) error {
if err != nil {
return fmt.Errorf("lxc-create failed: %v, output: %s", err, string(output))
}
}
cfg.ReportProgress("storage", "复制容器数据到存储磁盘")
storagePoolID, storagePath, err := m.moveContainerToStoragePool(lxcName, cfg.StoragePoolID)
@@ -676,6 +691,41 @@ func (m *Manager) CreateContainer(cfg ContainerConfig) error {
return nil
}
func (m *Manager) configureCustomLXCBase(lxcName string, tmpl *Template) error {
rootfsPath, err := m.safeRootfsPath(filepath.Join(m.LxcPath, lxcName, "rootfs"))
if err != nil {
return fmt.Errorf("invalid custom LXC rootfs path: %v", err)
}
configFile := filepath.Join(filepath.Dir(rootfsPath), "config")
data, err := os.ReadFile(configFile)
if err != nil {
return fmt.Errorf("failed to read custom LXC base config: %v", err)
}
if _, err := os.Stat("/usr/share/lxc/config/common.conf"); err != nil {
return fmt.Errorf("LXC common configuration is unavailable: %v", err)
}
arch := "linux64"
switch strings.ToLower(strings.TrimSpace(tmpl.Arch)) {
case "amd64", "x86_64", "arm64", "aarch64":
default:
return fmt.Errorf("unsupported custom LXC architecture: %s", tmpl.Arch)
}
base := []string{
"# CLICD custom rootfs base configuration",
"lxc.include = /usr/share/lxc/config/common.conf",
"lxc.arch = " + arch,
"lxc.rootfs.path = dir:" + rootfsPath,
"lxc.uts.name = " + lxcName,
"",
}
if err := os.WriteFile(configFile, []byte(strings.Join(base, "\n")+string(data)), 0644); err != nil {
return fmt.Errorf("failed to write custom LXC base config: %v", err)
}
return nil
}
func (m *Manager) preconfigureNetwork(rootfsPath string, cfg ContainerConfig) {
templateID := cfg.TemplateID
osRelease := ""
@@ -1667,6 +1717,9 @@ func appArmorProfileForTemplate(templateID string) (string, error) {
func systemdTemplateNeedsUnconfinedAppArmor(templateID string) bool {
id := strings.ToLower(strings.TrimSpace(templateID))
if template := FindTemplate(templateID); template != nil {
id += " " + strings.ToLower(template.Distro+" "+template.Release)
}
if id == "" || strings.Contains(id, "alpine") {
return false
}
@@ -2564,7 +2617,7 @@ if [ -L /etc/resolv.conf ] 2>/dev/null; then
fi
# Also try resolvectl for systemd-resolved setups
if command -v resolvectl >/dev/null 2>&1; then
resolvectl dns eth0 10.0.3.1 2>/dev/null || true
resolvectl dns eth0 __CLICD_LXC_GATEWAY__ 2>/dev/null || true
resolvectl dns eth0 8.8.8.8 2>/dev/null || true
resolvectl domain eth0 '~.' 2>/dev/null || true
fi
@@ -2572,7 +2625,7 @@ fi
# Avoid the trap where systemd stub resolver puts "nameserver 127.0.0.53"
# but doesn't actually resolve anything.
if ! grep -q '^nameserver [1-9]' /etc/resolv.conf 2>/dev/null; then
echo "nameserver 10.0.3.1" > /etc/resolv.conf
echo "nameserver __CLICD_LXC_GATEWAY__" > /etc/resolv.conf
echo "nameserver 8.8.8.8" >> /etc/resolv.conf
fi
export DEBIAN_FRONTEND=noninteractive
@@ -2709,6 +2762,7 @@ ensure_sshd_runtime_dir
}
`
script = strings.ReplaceAll(script, "__CLICD_PUBKEY_AUTH__", pubkeyValue)
script = strings.ReplaceAll(script, "__CLICD_LXC_GATEWAY__", config.LXCNATNetwork().Gateway)
if !startService {
return script
}
@@ -3308,6 +3362,15 @@ func (m *Manager) replaceRootfsFromTemplate(lxcName string, tmpl *Template) erro
}
defer m.cleanupTemporaryContainer(tmpName)
tmpRootfs := filepath.Join(tmpDir, "rootfs")
if tmpl.Custom {
if err := os.MkdirAll(tmpRootfs, 0755); err != nil {
return err
}
if err := ExtractCustomRootfs(tmpl.ID, tmpRootfs); err != nil {
return err
}
} else {
args := []string{
"-n", tmpName,
"-t", "download",
@@ -3323,8 +3386,8 @@ func (m *Manager) replaceRootfsFromTemplate(lxcName string, tmpl *Template) erro
if err != nil {
return fmt.Errorf("failed to download replacement rootfs: %v, output: %s", err, string(output))
}
}
tmpRootfs := filepath.Join(tmpDir, "rootfs")
if !rootfsHasInit(tmpRootfs) {
return fmt.Errorf("downloaded replacement rootfs is invalid: init not found")
}
+177
View File
@@ -122,6 +122,78 @@ func TestNormalizeCreateNATMappingsRejectsManagementPortConflict(t *testing.T) {
}
}
func TestTaggedRuleLineNumbersReturnsMatchingRulesDescending(t *testing.T) {
output := []byte(`Chain PREROUTING (policy ACCEPT)
num target prot opt source destination
2 DNAT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:30080 /* clicd-c12-any-30080 */
7 DNAT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:30081 /* clicd-c13-any-30081 */
11 DNAT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:30082 /* clicd-c12-any-30082 */
`)
got := taggedRuleLineNumbers(output, "clicd-c12-")
want := []int{11, 2}
if !reflect.DeepEqual(got, want) {
t.Fatalf("taggedRuleLineNumbers() = %v, want %v", got, want)
}
}
func TestPortMappingConntrackDeleteArgs(t *testing.T) {
got := portMappingConntrackDeleteArgs(config.PortMapping{
HostIP: "203.0.113.10",
HostPort: 32022,
Protocol: "TCP",
})
want := []string{"-D", "-p", "tcp", "--dport", "32022", "--dst", "203.0.113.10"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("portMappingConntrackDeleteArgs() = %v, want %v", got, want)
}
if got := portMappingConntrackDeleteArgs(config.PortMapping{HostPort: 32022, Protocol: "icmp"}); got != nil {
t.Fatalf("unsupported protocol returned args: %v", got)
}
}
func TestUpdateSSHPortMappingKeepsIdentityAndSynchronizesSSHPort(t *testing.T) {
previous := config.AppConfig
t.Cleanup(func() { config.AppConfig = previous })
config.AppConfig = &config.ClicdConfig{
NATPortStart: 30000,
NATPortEnd: 65535,
Containers: []config.Container{{
ID: 12,
Name: "ct-test",
Status: "stopped",
SSHPort: 30022,
PortMappings: []config.PortMapping{{
HostPort: 30022,
ContainerPort: 22,
Protocol: "tcp",
Description: "SSH",
}},
}},
}
manager := NewManager()
mappings, err := manager.UpdatePortMapping(12, 0, config.PortMapping{
HostPort: 31022,
ContainerPort: 22,
Protocol: "tcp",
Description: "renamed",
})
if err != nil {
t.Fatal(err)
}
if len(mappings) != 1 || mappings[0].Description != "SSH" {
t.Fatalf("updated mappings = %+v", mappings)
}
container := config.FindContainer(12)
if container == nil || container.SSHPort != 31022 {
t.Fatalf("container after SSH update = %+v", container)
}
if _, err := manager.DeletePortMapping(12, 0); err == nil {
t.Fatal("updated SSH mapping became deletable")
}
}
func TestReserveCreateNATPortsProtectsConcurrentTasks(t *testing.T) {
previous := config.AppConfig
t.Cleanup(func() { config.AppConfig = previous })
@@ -133,10 +205,12 @@ func TestReserveCreateNATPortsProtectsConcurrentTasks(t *testing.T) {
createNATReservationMu.Lock()
createNATReservations = map[uint64][]config.PortMapping{}
queuedCreateNATReservations = map[string][]config.PortMapping{}
createNATReservationMu.Unlock()
t.Cleanup(func() {
createNATReservationMu.Lock()
createNATReservations = map[uint64][]config.PortMapping{}
queuedCreateNATReservations = map[string][]config.PortMapping{}
createNATReservationMu.Unlock()
})
@@ -181,6 +255,109 @@ func TestReserveCreateNATPortsProtectsConcurrentTasks(t *testing.T) {
}
}
func TestReserveBatchCreateNATPortsPlansAllAutomaticPorts(t *testing.T) {
previous := config.AppConfig
t.Cleanup(func() { config.AppConfig = previous })
config.AppConfig = &config.ClicdConfig{
NATPortStart: 30000,
NATPortEnd: 30010,
NextSSHPort: 30001,
}
createNATReservationMu.Lock()
createNATReservations = map[uint64][]config.PortMapping{}
queuedCreateNATReservations = map[string][]config.PortMapping{}
createNATReservationMu.Unlock()
t.Cleanup(func() {
createNATReservationMu.Lock()
createNATReservations = map[uint64][]config.PortMapping{}
queuedCreateNATReservations = map[string][]config.PortMapping{}
createNATReservationMu.Unlock()
})
configs := []ContainerConfig{
{Name: "batch-1", PortMappingCount: 2},
{Name: "batch-2", PortMappingCount: 2},
}
for i := range configs {
if err := configs[i].NormalizeCreateNATMappings(); err != nil {
t.Fatal(err)
}
}
planned, err := ReserveBatchCreateNATPorts(configs)
if err != nil {
t.Fatal(err)
}
used := map[int]string{}
for _, cfg := range planned {
if cfg.ManagementPort == 0 {
t.Fatalf("%s has no planned management port", cfg.Name)
}
if len(cfg.NATPortMappings) != 1 {
t.Fatalf("%s automatic mappings = %d, want 1", cfg.Name, len(cfg.NATPortMappings))
}
for _, port := range []int{cfg.ManagementPort, cfg.NATPortMappings[0].HostPort} {
if owner := used[port]; owner != "" {
t.Fatalf("planned port %d is shared by %s and %s", port, owner, cfg.Name)
}
used[port] = cfg.Name
}
}
for _, cfg := range planned {
port, release, err := ReserveCreateNATPorts(cfg)
if err != nil {
t.Fatalf("%s could not claim its queued reservation: %v", cfg.Name, err)
}
if port != cfg.ManagementPort {
t.Fatalf("%s claimed management port %d, want %d", cfg.Name, port, cfg.ManagementPort)
}
release()
}
if len(queuedCreateNATReservations) != 0 {
t.Fatalf("queued reservations remain after claim: %v", queuedCreateNATReservations)
}
}
func TestReserveBatchCreateNATPortsRejectsWholeConflictingBatch(t *testing.T) {
previous := config.AppConfig
t.Cleanup(func() { config.AppConfig = previous })
config.AppConfig = &config.ClicdConfig{
NATPortStart: 30000,
NATPortEnd: 30010,
NextSSHPort: 30001,
}
createNATReservationMu.Lock()
createNATReservations = map[uint64][]config.PortMapping{}
queuedCreateNATReservations = map[string][]config.PortMapping{}
createNATReservationMu.Unlock()
t.Cleanup(func() {
createNATReservationMu.Lock()
createNATReservations = map[uint64][]config.PortMapping{}
queuedCreateNATReservations = map[string][]config.PortMapping{}
createNATReservationMu.Unlock()
})
configs := []ContainerConfig{
{Name: "batch-1", NATPortMappings: []config.PortMapping{{HostPort: 30005, ContainerPort: 80, Protocol: "tcp"}}},
{Name: "batch-2", NATPortMappings: []config.PortMapping{{HostPort: 30005, ContainerPort: 8080, Protocol: "tcp"}}},
}
for i := range configs {
if err := configs[i].NormalizeCreateNATMappings(); err != nil {
t.Fatal(err)
}
}
if _, err := ReserveBatchCreateNATPorts(configs); err == nil {
t.Fatal("conflicting batch was accepted")
}
if len(queuedCreateNATReservations) != 0 {
t.Fatalf("conflicting batch left partial reservations: %v", queuedCreateNATReservations)
}
}
func TestRootfsCommandRejectsUnmanagedCommand(t *testing.T) {
base := t.TempDir()
rootfs := filepath.Join(base, "ct-1", "rootfs")
+372 -36
View File
@@ -1,9 +1,12 @@
package lxc
import (
"errors"
"fmt"
"net/netip"
"os/exec"
"regexp"
"sort"
"strconv"
"strings"
"sync"
@@ -15,6 +18,7 @@ var (
createNATReservationMu sync.Mutex
createNATReservationNextID uint64
createNATReservations = map[uint64][]config.PortMapping{}
queuedCreateNATReservations = map[string][]config.PortMapping{}
)
// ApplyPortMappings applies iptables DNAT rules for a container's port mappings
@@ -29,14 +33,16 @@ func (m *Manager) ApplyPortMappings(id int) error {
EnsureAssignedPublicIPv4s(c.PublicIPv4s)
tag := clicdTag(id)
bridge := "lxcbr0"
subnet := "10.0.3.0/24"
subnet := config.LXCNATNetwork().Subnet
if c.IsKVM() {
bridge = "virbr0"
subnet = "192.168.122.0/24"
subnet = config.KVMNATNetwork().Subnet
}
EnsureForwardRules(bridge)
m.CleanPortMappings(id)
if err := m.CleanPortMappings(id); err != nil {
return fmt.Errorf("clean existing port mappings for container %d: %w", id, err)
}
deleteBridgeMasquerade(subnet)
for _, pm := range c.PortMappings {
@@ -243,9 +249,13 @@ func clicdTag(id int) string { return "c" + strconv.Itoa(id) }
func EnsureAllRunningPortMappings() {
m := NewManager()
m.cleanOrphanedPortMappings()
for i := range config.AppConfig.Containers {
c := &config.AppConfig.Containers[i]
if c.Status != "running" || strings.TrimSpace(c.IP) == "" {
if err := m.CleanPortMappings(c.ID); err != nil {
fmt.Printf("Warning: failed to clean inactive port mappings for %s: %v\n", c.Name, err)
}
continue
}
if err := m.ApplyPortMappings(c.ID); err != nil {
@@ -254,6 +264,33 @@ func EnsureAllRunningPortMappings() {
}
}
var taggedContainerIDPattern = regexp.MustCompile(`clicd-c([0-9]+)-`)
func (m *Manager) cleanOrphanedPortMappings() {
output, err := exec.Command("iptables-save").Output()
if err != nil {
return
}
configured := make(map[int]bool, len(config.AppConfig.Containers))
for i := range config.AppConfig.Containers {
configured[config.AppConfig.Containers[i].ID] = true
}
seen := map[int]bool{}
for _, match := range taggedContainerIDPattern.FindAllSubmatch(output, -1) {
if len(match) < 2 {
continue
}
id, err := strconv.Atoi(string(match[1]))
if err != nil || configured[id] || seen[id] {
continue
}
seen[id] = true
if err := m.CleanPortMappings(id); err != nil {
fmt.Printf("Warning: failed to clean orphaned port mappings for container %d: %v\n", id, err)
}
}
}
// EnsureForwardRules makes sure iptables FORWARD chain allows bridge traffic.
func EnsureForwardRules(bridge string) {
if bridge == "" {
@@ -306,16 +343,108 @@ func ensureLibvirtForwardRules(bridge string) {
// CleanPortMappings removes all iptables rules for a container
func (m *Manager) CleanPortMappings(id int) error {
tag := clicdTag(id)
for _, chain := range []string{"PREROUTING", "POSTROUTING"} {
cmd := exec.Command("sh", "-c",
fmt.Sprintf("iptables -t nat -L %s -n --line-numbers 2>/dev/null | grep 'clicd-%s-' | awk '{print $1}' | sort -rn | while read num; do iptables -t nat -D %s $num; done", chain, tag, chain))
cmd.Run()
marker := "clicd-" + clicdTag(id) + "-"
var cleanupErrors []error
for _, target := range []struct {
table string
chain string
}{
{table: "nat", chain: "PREROUTING"},
{table: "nat", chain: "POSTROUTING"},
{chain: "FORWARD"},
} {
if err := deleteTaggedIPTablesRules(target.table, target.chain, marker); err != nil {
cleanupErrors = append(cleanupErrors, err)
}
cmd := exec.Command("sh", "-c",
fmt.Sprintf("iptables -S FORWARD 2>/dev/null | grep 'clicd-%s-' | sed 's/^-A /-D /' | while read rule; do iptables $rule; done", tag))
cmd.Run()
}
if c := config.FindContainer(id); c != nil {
for _, mapping := range c.PortMappings {
clearPortMappingConntrack(mapping)
}
}
return errors.Join(cleanupErrors...)
}
func deleteTaggedIPTablesRules(table, chain, marker string) error {
listArgs := []string{"-w", "5"}
if table != "" {
listArgs = append(listArgs, "-t", table)
}
listArgs = append(listArgs, "-L", chain, "-n", "--line-numbers")
output, err := exec.Command("iptables", listArgs...).CombinedOutput()
if err != nil {
return fmt.Errorf("list iptables %s/%s: %w: %s", tableName(table), chain, err, strings.TrimSpace(string(output)))
}
var deleteErrors []error
for _, lineNumber := range taggedRuleLineNumbers(output, marker) {
deleteArgs := []string{"-w", "5"}
if table != "" {
deleteArgs = append(deleteArgs, "-t", table)
}
deleteArgs = append(deleteArgs, "-D", chain, strconv.Itoa(lineNumber))
if output, err := exec.Command("iptables", deleteArgs...).CombinedOutput(); err != nil {
deleteErrors = append(deleteErrors, fmt.Errorf(
"delete iptables %s/%s rule %d: %w: %s",
tableName(table), chain, lineNumber, err, strings.TrimSpace(string(output)),
))
}
}
return errors.Join(deleteErrors...)
}
func taggedRuleLineNumbers(output []byte, marker string) []int {
lineNumbers := make([]int, 0)
for _, line := range strings.Split(string(output), "\n") {
if !strings.Contains(line, marker) {
continue
}
fields := strings.Fields(line)
if len(fields) == 0 {
continue
}
lineNumber, err := strconv.Atoi(fields[0])
if err == nil && lineNumber > 0 {
lineNumbers = append(lineNumbers, lineNumber)
}
}
sort.Sort(sort.Reverse(sort.IntSlice(lineNumbers)))
return lineNumbers
}
func tableName(table string) string {
if table == "" {
return "filter"
}
return table
}
func clearPortMappingConntrack(mapping config.PortMapping) {
args := portMappingConntrackDeleteArgs(mapping)
if len(args) == 0 {
return
}
// conntrack exits non-zero when no matching flow exists; that is already clean.
_ = exec.Command("conntrack", args...).Run()
}
func portMappingConntrackDeleteArgs(mapping config.PortMapping) []string {
protocol := strings.ToLower(strings.TrimSpace(mapping.Protocol))
if protocol != "tcp" && protocol != "udp" {
return nil
}
if mapping.HostPort < 1 || mapping.HostPort > 65535 {
return nil
}
args := []string{
"-D",
"-p", protocol,
"--dport", strconv.Itoa(mapping.HostPort),
}
if hostIP := strings.TrimSpace(mapping.HostIP); hostIP != "" {
args = append(args, "--dst", hostIP)
}
return args
}
// SetupDefaultPortMappings creates default port mappings
@@ -368,14 +497,19 @@ func (m *Manager) UpdatePortMapping(id int, index int, pm config.PortMapping) ([
if index < 0 || index >= len(c.PortMappings) {
return nil, fmt.Errorf("invalid port mapping index: %d", index)
}
existing := c.PortMappings[index]
normalized, err := normalizePortMapping(c, index, pm)
if err != nil {
return nil, err
}
if strings.EqualFold(existing.Description, "SSH") {
normalized.Description = "SSH"
}
c.PortMappings[index] = normalized
if err := persistAndReloadMappings(m, c); err != nil {
return nil, err
}
clearPortMappingConntrack(existing)
return c.PortMappings, nil
}
@@ -388,17 +522,20 @@ func (m *Manager) DeletePortMapping(id int, index int) ([]config.PortMapping, er
if index < 0 || index >= len(c.PortMappings) {
return nil, fmt.Errorf("invalid port mapping index: %d", index)
}
if c.PortMappings[index].Description == "SSH" {
removed := c.PortMappings[index]
if strings.EqualFold(removed.Description, "SSH") {
return nil, fmt.Errorf("SSH default mapping cannot be deleted")
}
c.PortMappings = append(c.PortMappings[:index], c.PortMappings[index+1:]...)
if err := persistAndReloadMappings(m, c); err != nil {
return nil, err
}
clearPortMappingConntrack(removed)
return c.PortMappings, nil
}
func persistAndReloadMappings(m *Manager, c *config.Container) error {
syncContainerSSHPort(c)
config.SaveConfig()
if c.Status == "running" && c.IP != "" {
return m.ApplyPortMappings(c.ID)
@@ -406,6 +543,18 @@ func persistAndReloadMappings(m *Manager, c *config.Container) error {
return nil
}
func syncContainerSSHPort(c *config.Container) {
if c == nil {
return
}
for _, mapping := range c.PortMappings {
if strings.EqualFold(mapping.Description, "SSH") {
c.SSHPort = mapping.HostPort
return
}
}
}
func (m *Manager) UpdatePublicIPv4Assignments(id int, requested []string, count int, auto bool) (*config.Container, error) {
c := config.FindContainer(id)
if c == nil {
@@ -553,32 +702,25 @@ func ReserveCreateNATPorts(cfg ContainerConfig) (int, func(), error) {
createNATReservationMu.Lock()
defer createNATReservationMu.Unlock()
owner := createNATReservationOwner(cfg.Name)
requestedReservations := createNATReservationMappings(cfg, cfg.ManagementPort)
if queued, ok := queuedCreateNATReservations[owner]; ok {
if !sameCreateNATReservations(queued, requestedReservations) {
return 0, nil, fmt.Errorf("queued NAT port plan for %s no longer matches the create task", cfg.Name)
}
delete(queuedCreateNATReservations, owner)
return activateCreateNATReservationLocked(cfg.ManagementPort, queued)
}
if err := ValidateCreateNATPortAvailability(cfg); err != nil {
return 0, nil, err
}
requestedReservations := append([]config.PortMapping(nil), cfg.NATPortMappings...)
if cfg.ManagementPort > 0 {
requestedReservations = append(requestedReservations, config.PortMapping{
HostPort: cfg.ManagementPort,
Protocol: "tcp",
})
}
for _, requested := range requestedReservations {
for _, reservations := range createNATReservations {
for _, reserved := range reservations {
if requested.HostPort == reserved.HostPort && protocolsOverlap(requested.Protocol, reserved.Protocol) {
return 0, nil, fmt.Errorf("NAT host port %d/%s is reserved by another create task", requested.HostPort, requested.Protocol)
}
}
}
if err := validateCreateNATReservationsAvailableLocked(requestedReservations, owner); err != nil {
return 0, nil, err
}
excluded := cfg.RequestedNATHostPorts()
for _, reservations := range createNATReservations {
for _, reserved := range reservations {
excluded = append(excluded, reserved.HostPort)
}
}
excluded = append(excluded, allReservedCreateNATHostPortsLocked(owner)...)
managementPort := cfg.ManagementPort
if managementPort == 0 {
var err error
@@ -588,12 +730,96 @@ func ReserveCreateNATPorts(cfg ContainerConfig) (int, func(), error) {
}
}
reservations := createNATReservationMappings(cfg, managementPort)
return activateCreateNATReservationLocked(managementPort, reservations)
}
// ReserveBatchCreateNATPorts resolves every automatic NAT port and reserves
// the complete batch before any create task is enqueued.
func ReserveBatchCreateNATPorts(configs []ContainerConfig) ([]ContainerConfig, error) {
createNATReservationMu.Lock()
defer createNATReservationMu.Unlock()
planned := append([]ContainerConfig(nil), configs...)
addedOwners := make([]string, 0, len(planned))
rollback := func() {
for _, owner := range addedOwners {
delete(queuedCreateNATReservations, owner)
}
}
for i := range planned {
cfg := &planned[i]
cfg.NATPortMappings = append([]config.PortMapping(nil), cfg.NATPortMappings...)
if !cfg.WantsNAT() {
continue
}
owner := createNATReservationOwner(cfg.Name)
if owner == "" {
rollback()
return nil, fmt.Errorf("container name is required for NAT port reservation")
}
if _, exists := queuedCreateNATReservations[owner]; exists {
rollback()
return nil, fmt.Errorf("container creation already has reserved NAT ports: %s", cfg.Name)
}
if err := ValidateCreateNATPortAvailability(*cfg); err != nil {
rollback()
return nil, fmt.Errorf("%s: %w", cfg.Name, err)
}
explicit := createNATReservationMappings(*cfg, cfg.ManagementPort)
if err := validateCreateNATReservationsAvailableLocked(explicit, owner); err != nil {
rollback()
return nil, fmt.Errorf("%s: %w", cfg.Name, err)
}
excluded := cfg.RequestedNATHostPorts()
excluded = append(excluded, allReservedCreateNATHostPortsLocked(owner)...)
if cfg.ManagementPort == 0 {
port, err := config.AllocateSSHPortExcluding(excluded)
if err != nil {
rollback()
return nil, fmt.Errorf("%s: %w", cfg.Name, err)
}
cfg.ManagementPort = port
}
if len(cfg.NATPortMappings) == 0 && cfg.PortMappingCount > 1 {
generated, err := planDefaultCreateNATMappingsLocked(*cfg, cfg.PortMappingCount-1, owner)
if err != nil {
rollback()
return nil, fmt.Errorf("%s: %w", cfg.Name, err)
}
cfg.NATPortMappings = generated
cfg.PortMappingCount = len(generated) + 1
}
reservations := createNATReservationMappings(*cfg, cfg.ManagementPort)
if err := validateCreateNATReservationsAvailableLocked(reservations, owner); err != nil {
rollback()
return nil, fmt.Errorf("%s: %w", cfg.Name, err)
}
queuedCreateNATReservations[owner] = reservations
addedOwners = append(addedOwners, owner)
}
return planned, nil
}
func ReleaseQueuedCreateNATPorts(name string) {
owner := createNATReservationOwner(name)
if owner == "" {
return
}
createNATReservationMu.Lock()
delete(queuedCreateNATReservations, owner)
createNATReservationMu.Unlock()
}
func activateCreateNATReservationLocked(managementPort int, reservations []config.PortMapping) (int, func(), error) {
createNATReservationNextID++
reservationID := createNATReservationNextID
reservations := make([]config.PortMapping, 0, len(cfg.NATPortMappings)+1)
reservations = append(reservations, config.PortMapping{HostPort: managementPort, Protocol: "tcp"})
reservations = append(reservations, cfg.NATPortMappings...)
createNATReservations[reservationID] = reservations
createNATReservations[reservationID] = append([]config.PortMapping(nil), reservations...)
var once sync.Once
release := func() {
@@ -606,6 +832,116 @@ func ReserveCreateNATPorts(cfg ContainerConfig) (int, func(), error) {
return managementPort, release, nil
}
func createNATReservationOwner(name string) string {
return strings.ToLower(strings.TrimSpace(name))
}
func createNATReservationMappings(cfg ContainerConfig, managementPort int) []config.PortMapping {
reservations := make([]config.PortMapping, 0, len(cfg.NATPortMappings))
if managementPort > 0 {
reservations = append(reservations, config.PortMapping{HostPort: managementPort, Protocol: "tcp"})
}
reservations = append(reservations, cfg.NATPortMappings...)
return reservations
}
func validateCreateNATReservationsAvailableLocked(requested []config.PortMapping, exceptOwner string) error {
for _, candidate := range requested {
for _, reservations := range createNATReservations {
if conflictingCreateNATReservation(candidate, reservations) {
return fmt.Errorf("NAT host port %d/%s is reserved by another create task", candidate.HostPort, candidate.Protocol)
}
}
for owner, reservations := range queuedCreateNATReservations {
if owner == exceptOwner {
continue
}
if conflictingCreateNATReservation(candidate, reservations) {
return fmt.Errorf("NAT host port %d/%s is reserved by queued create task %s", candidate.HostPort, candidate.Protocol, owner)
}
}
}
return nil
}
func conflictingCreateNATReservation(candidate config.PortMapping, reservations []config.PortMapping) bool {
for _, reserved := range reservations {
if candidate.HostPort == reserved.HostPort && protocolsOverlap(candidate.Protocol, reserved.Protocol) {
return true
}
}
return false
}
func allReservedCreateNATHostPortsLocked(exceptOwner string) []int {
ports := make([]int, 0)
for _, reservations := range createNATReservations {
for _, reserved := range reservations {
ports = append(ports, reserved.HostPort)
}
}
for owner, reservations := range queuedCreateNATReservations {
if owner == exceptOwner {
continue
}
for _, reserved := range reservations {
ports = append(ports, reserved.HostPort)
}
}
return ports
}
func planDefaultCreateNATMappingsLocked(cfg ContainerConfig, count int, owner string) ([]config.PortMapping, error) {
if count <= 0 {
return nil, nil
}
unavailable := map[int]bool{cfg.ManagementPort: true}
for _, port := range allReservedCreateNATHostPortsLocked(owner) {
unavailable[port] = true
}
for _, mapping := range cfg.NATPortMappings {
unavailable[mapping.HostPort] = true
}
candidate := &config.Container{ID: -1}
start, end := config.NATPortRange()
mappings := make([]config.PortMapping, 0, count)
for port := start; port <= end && len(mappings) < count; port++ {
if unavailable[port] || !HostPortAvailable(candidate, "", port, "tcp") {
continue
}
unavailable[port] = true
mappings = append(mappings, config.PortMapping{
HostPort: port,
ContainerPort: port,
Protocol: "tcp",
Description: fmt.Sprintf("Port-%d", port),
})
}
if len(mappings) != count {
return nil, fmt.Errorf("not enough free NAT4 host ports for %d automatic mappings", count)
}
return mappings, nil
}
func sameCreateNATReservations(left, right []config.PortMapping) bool {
if len(left) != len(right) {
return false
}
counts := make(map[string]int, len(left))
for _, mapping := range left {
counts[fmt.Sprintf("%d/%s", mapping.HostPort, strings.ToLower(mapping.Protocol))]++
}
for _, mapping := range right {
key := fmt.Sprintf("%d/%s", mapping.HostPort, strings.ToLower(mapping.Protocol))
if counts[key] == 0 {
return false
}
counts[key]--
}
return true
}
func allocateDefaultEqualPorts(c *config.Container, count int) []int {
if count <= 0 {
return nil
+26 -2
View File
@@ -1,6 +1,10 @@
package lxc
import "runtime"
import (
"runtime"
"clicd/internal/config"
)
// Template represents an LXC image template
type Template struct {
@@ -11,12 +15,15 @@ type Template struct {
Arch string `json:"arch"`
Variant string `json:"variant"`
Description string `json:"description"`
URL string `json:"url,omitempty"`
SHA256 string `json:"sha256,omitempty"`
Custom bool `json:"custom,omitempty"`
}
// GetTemplates returns available LXC image templates (only verified working ones)
func GetTemplates() []Template {
arch := defaultTemplateArch()
return []Template{
templates := []Template{
{
ID: "ubuntu-noble", Name: "Ubuntu 24.04",
Distro: "ubuntu", Release: "noble", Arch: arch,
@@ -68,6 +75,23 @@ func GetTemplates() []Template {
Description: "Rocky Linux 10",
},
}
for _, custom := range config.ListCustomLXCImages() {
if custom.Arch != arch {
continue
}
templates = append(templates, Template{
ID: custom.ID,
Name: custom.Name,
Distro: custom.Distro,
Release: custom.Release,
Arch: custom.Arch,
Description: custom.Description,
URL: custom.URL,
SHA256: custom.SHA256,
Custom: true,
})
}
return templates
}
func defaultTemplateArch() string {
+214
View File
@@ -0,0 +1,214 @@
package safehttp
import (
"context"
"fmt"
"net"
"net/http"
"net/netip"
"net/url"
"strconv"
"strings"
"time"
)
const maxRedirects = 10
var blockedPrefixes = []netip.Prefix{
netip.MustParsePrefix("0.0.0.0/8"),
netip.MustParsePrefix("10.0.0.0/8"),
netip.MustParsePrefix("100.64.0.0/10"),
netip.MustParsePrefix("127.0.0.0/8"),
netip.MustParsePrefix("169.254.0.0/16"),
netip.MustParsePrefix("172.16.0.0/12"),
netip.MustParsePrefix("192.0.0.0/24"),
netip.MustParsePrefix("192.0.2.0/24"),
netip.MustParsePrefix("192.88.99.0/24"),
netip.MustParsePrefix("192.168.0.0/16"),
netip.MustParsePrefix("198.18.0.0/15"),
netip.MustParsePrefix("198.51.100.0/24"),
netip.MustParsePrefix("203.0.113.0/24"),
netip.MustParsePrefix("224.0.0.0/4"),
netip.MustParsePrefix("240.0.0.0/4"),
netip.MustParsePrefix("::/128"),
netip.MustParsePrefix("::1/128"),
netip.MustParsePrefix("64:ff9b::/96"),
netip.MustParsePrefix("64:ff9b:1::/48"),
netip.MustParsePrefix("100::/64"),
netip.MustParsePrefix("2001::/32"),
netip.MustParsePrefix("2001:2::/48"),
netip.MustParsePrefix("2001:db8::/32"),
netip.MustParsePrefix("2001:20::/28"),
netip.MustParsePrefix("2002::/16"),
netip.MustParsePrefix("fc00::/7"),
netip.MustParsePrefix("fec0::/10"),
netip.MustParsePrefix("fe80::/10"),
netip.MustParsePrefix("ff00::/8"),
}
// ValidateURL performs the URL checks that do not require DNS. Host addresses
// are checked again after resolution and immediately before every connection.
func ValidateURL(rawURL string) (*url.URL, error) {
if len(rawURL) == 0 || len(rawURL) > 4096 {
return nil, fmt.Errorf("download URL must be between 1 and 4096 characters")
}
parsed, err := url.ParseRequestURI(rawURL)
if err != nil {
return nil, fmt.Errorf("invalid download URL: %v", err)
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return nil, fmt.Errorf("download URL must use HTTP or HTTPS")
}
if parsed.Host == "" || parsed.Hostname() == "" {
return nil, fmt.Errorf("download URL must include a host")
}
if parsed.User != nil {
return nil, fmt.Errorf("download URL must not include credentials")
}
if parsed.Fragment != "" {
return nil, fmt.Errorf("download URL must not include a fragment")
}
if port := parsed.Port(); port != "" {
value, err := strconv.Atoi(port)
if err != nil || value < 1 || value > 65535 {
return nil, fmt.Errorf("download URL contains an invalid port")
}
}
if addr, err := netip.ParseAddr(parsed.Hostname()); err == nil && !isPublicAddress(addr) {
return nil, fmt.Errorf("download URL resolves to a non-public address")
}
return parsed, nil
}
// Get retrieves a resource only when every resolved destination is public.
func Get(ctx context.Context, rawURL, userAgent string, timeout time.Duration) (*http.Response, error) {
parsed, err := ValidateURL(rawURL)
if err != nil {
return nil, err
}
if err := validateHost(ctx, net.DefaultResolver, parsed.Hostname()); err != nil {
return nil, err
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
if err != nil {
return nil, err
}
request.Header.Set("User-Agent", userAgent)
client := &http.Client{
Timeout: timeout,
Transport: publicTransport(net.DefaultResolver),
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= maxRedirects {
return fmt.Errorf("too many redirects")
}
redirect, err := ValidateURL(req.URL.String())
if err != nil {
return err
}
if err := validateHost(req.Context(), net.DefaultResolver, redirect.Hostname()); err != nil {
return err
}
if len(via) > 0 {
req.Header.Set("User-Agent", via[0].Header.Get("User-Agent"))
}
return nil
},
}
// All URL components, redirects, DNS answers and dial destinations are
// constrained above and in publicTransport.
// lgtm[go/request-forgery]
return client.Do(request)
}
func publicTransport(resolver *net.Resolver) *http.Transport {
dialer := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
return &http.Transport{
Proxy: nil,
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, fmt.Errorf("invalid download destination: %v", err)
}
addresses, err := resolvePublicHost(ctx, resolver, host)
if err != nil {
return nil, err
}
var lastErr error
for _, addr := range addresses {
conn, err := dialer.DialContext(ctx, network, net.JoinHostPort(addr.String(), port))
if err == nil {
return conn, nil
}
lastErr = err
}
if lastErr == nil {
lastErr = fmt.Errorf("host has no usable public addresses")
}
return nil, lastErr
},
ForceAttemptHTTP2: true,
TLSHandshakeTimeout: 30 * time.Second,
IdleConnTimeout: 90 * time.Second,
}
}
func validateHost(ctx context.Context, resolver *net.Resolver, host string) error {
_, err := resolvePublicHost(ctx, resolver, host)
return err
}
func resolvePublicHost(ctx context.Context, resolver *net.Resolver, host string) ([]netip.Addr, error) {
host = strings.TrimSpace(strings.TrimSuffix(host, "."))
if host == "" {
return nil, fmt.Errorf("download URL host is empty")
}
if strings.EqualFold(host, "localhost") || strings.HasSuffix(strings.ToLower(host), ".localhost") {
return nil, fmt.Errorf("download URL host is not public")
}
if addr, err := netip.ParseAddr(host); err == nil {
addr = addr.Unmap()
if !isPublicAddress(addr) {
return nil, fmt.Errorf("download URL resolves to a non-public address")
}
return []netip.Addr{addr}, nil
}
addresses, err := resolver.LookupNetIP(ctx, "ip", host)
if err != nil {
return nil, fmt.Errorf("failed to resolve download host: %v", err)
}
if len(addresses) == 0 {
return nil, fmt.Errorf("download host has no IP addresses")
}
result := make([]netip.Addr, 0, len(addresses))
for _, address := range addresses {
address = address.Unmap()
if !isPublicAddress(address) {
return nil, fmt.Errorf("download host resolves to a non-public address")
}
result = append(result, address)
}
return result, nil
}
func isPublicAddress(address netip.Addr) bool {
if !address.IsValid() || address.Zone() != "" || !address.IsGlobalUnicast() || address.IsPrivate() ||
address.IsLoopback() || address.IsLinkLocalUnicast() || address.IsLinkLocalMulticast() ||
address.IsMulticast() || address.IsUnspecified() {
return false
}
address = address.Unmap()
for _, prefix := range blockedPrefixes {
if prefix.Contains(address) {
return false
}
}
return true
}
@@ -0,0 +1,74 @@
package safehttp
import (
"context"
"net/netip"
"testing"
"time"
)
func TestValidateURLRejectsUnsafeDestinations(t *testing.T) {
t.Parallel()
for _, rawURL := range []string{
"file:///etc/passwd",
"http://user:pass@example.com/image",
"http://127.0.0.1/image",
"http://[::1]/image",
"http://169.254.169.254/latest/meta-data",
"http://10.0.0.1/image",
"http://192.168.1.10/image",
"http://100.64.0.1/image",
"http://example.com:99999/image",
} {
if _, err := ValidateURL(rawURL); err == nil {
t.Fatalf("ValidateURL(%q) succeeded, want rejection", rawURL)
}
}
}
func TestValidateURLAcceptsPublicHTTPURL(t *testing.T) {
t.Parallel()
parsed, err := ValidateURL("https://example.com/images/rootfs.tar.xz?variant=default")
if err != nil {
t.Fatalf("ValidateURL returned error: %v", err)
}
if parsed.Hostname() != "example.com" {
t.Fatalf("hostname = %q, want example.com", parsed.Hostname())
}
}
func TestIsPublicAddress(t *testing.T) {
t.Parallel()
tests := map[string]bool{
"8.8.8.8": true,
"1.1.1.1": true,
"2606:4700:4700::1111": true,
"127.0.0.1": false,
"10.0.0.1": false,
"100.64.0.1": false,
"169.254.169.254": false,
"192.0.2.1": false,
"198.18.0.1": false,
"::1": false,
"64:ff9b::127.0.0.1": false,
"2002:7f00:1::1": false,
"fc00::1": false,
"fec0::1": false,
"fe80::1": false,
"2001:db8::1": false,
}
for raw, expected := range tests {
if actual := isPublicAddress(netip.MustParseAddr(raw)); actual != expected {
t.Errorf("isPublicAddress(%s) = %v, want %v", raw, actual, expected)
}
}
}
func TestGetRejectsLoopbackBeforeRequest(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if _, err := Get(ctx, "http://127.0.0.1:1/image", "test", time.Second); err == nil {
t.Fatal("Get accepted a loopback destination")
}
}
+39
View File
@@ -0,0 +1,39 @@
package server
import (
"encoding/json"
"net/http"
"strings"
"clicd/internal/config"
)
func panelAccessMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
decision := config.EvaluatePanelAccess(
config.AppConfig.PanelAccessPolicy,
r.RemoteAddr,
config.ForwardedClientHeaders{
ForwardedFor: r.Header.Get("X-Forwarded-For"),
RealIP: r.Header.Get("X-Real-IP"),
CFConnectingIP: r.Header.Get("CF-Connecting-IP"),
},
)
if decision.Allowed {
next.ServeHTTP(w, r)
return
}
w.Header().Set("Cache-Control", "no-store")
if strings.HasPrefix(r.URL.Path, "/api/") {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
_ = json.NewEncoder(w).Encode(map[string]any{
"success": false,
"message": "Access denied by panel source policy",
})
return
}
http.Error(w, "Access denied by panel source policy", http.StatusForbidden)
})
}
@@ -0,0 +1,46 @@
package server
import (
"net/http"
"net/http/httptest"
"testing"
"clicd/internal/config"
)
func TestPanelAccessMiddleware(t *testing.T) {
previous := config.AppConfig
config.AppConfig = &config.ClicdConfig{
PanelAccessPolicy: config.PanelAccessPolicy{
Enabled: true,
AllowedSources: []string{"192.0.2.0/24"},
TrustedProxies: []string{"10.0.0.1"},
},
}
t.Cleanup(func() {
config.AppConfig = previous
})
handler := panelAccessMiddleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
}))
allowed := httptest.NewRequest(http.MethodGet, "/api/version", nil)
allowed.RemoteAddr = "192.0.2.8:50000"
allowedRecorder := httptest.NewRecorder()
handler.ServeHTTP(allowedRecorder, allowed)
if allowedRecorder.Code != http.StatusNoContent {
t.Fatalf("allowed status = %d", allowedRecorder.Code)
}
denied := httptest.NewRequest(http.MethodGet, "/api/version", nil)
denied.RemoteAddr = "198.51.100.8:50000"
deniedRecorder := httptest.NewRecorder()
handler.ServeHTTP(deniedRecorder, denied)
if deniedRecorder.Code != http.StatusForbidden {
t.Fatalf("denied status = %d", deniedRecorder.Code)
}
if got := deniedRecorder.Header().Get("Content-Type"); got != "application/json" {
t.Fatalf("denied content type = %q", got)
}
}
+5 -1
View File
@@ -49,11 +49,13 @@ func setupRoutes(mux *http.ServeMux) {
mux.HandleFunc("/api/login-logs", corsMiddleware(api.AdminMiddleware(api.HandleLoginLogs)))
mux.HandleFunc("/api/ssl", corsMiddleware(api.AdminMiddleware(api.HandleSSLSettings)))
mux.HandleFunc("/api/webssh-origins", corsMiddleware(api.AdminMiddleware(api.HandleWebSSHOriginSettings)))
mux.HandleFunc("/api/access-policy", corsMiddleware(api.AdminMiddleware(api.HandlePanelAccessPolicy)))
mux.HandleFunc("/api/containers", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleContainers))))
mux.HandleFunc("/api/containers/list", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleContainerListAlias))))
mux.HandleFunc("/api/containers/", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleSingleContainer))))
mux.HandleFunc("/api/templates", corsMiddleware(api.AuthMiddleware(api.HandleTemplates)))
mux.HandleFunc("/api/images", corsMiddleware(api.AdminMiddleware(api.HandleImages)))
mux.HandleFunc("/api/images/custom", corsMiddleware(api.AdminMiddleware(api.HandleCustomKVMImages)))
mux.HandleFunc("/api/images/download", corsMiddleware(api.AdminMiddleware(api.HandleImageDownload)))
mux.HandleFunc("/api/images/cancel", corsMiddleware(api.AdminMiddleware(api.HandleImageCancel)))
mux.HandleFunc("/api/images/delete", corsMiddleware(api.AdminMiddleware(api.HandleImageDelete)))
@@ -101,6 +103,7 @@ func setupRoutes(mux *http.ServeMux) {
mux.HandleFunc("/api/v1/containers/", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleSingleContainer))))
mux.HandleFunc("/api/v1/templates", corsMiddleware(api.AuthMiddleware(api.HandleTemplates)))
mux.HandleFunc("/api/v1/images", corsMiddleware(api.AuthMiddleware(api.HandleImages)))
mux.HandleFunc("/api/v1/images/custom", corsMiddleware(api.AuthMiddleware(api.HandleCustomKVMImages)))
mux.HandleFunc("/api/v1/images/download", corsMiddleware(api.AuthMiddleware(api.HandleImageDownload)))
mux.HandleFunc("/api/v1/images/cancel", corsMiddleware(api.AuthMiddleware(api.HandleImageCancel)))
mux.HandleFunc("/api/v1/images/delete", corsMiddleware(api.AuthMiddleware(api.HandleImageDelete)))
@@ -126,6 +129,7 @@ func setupRoutes(mux *http.ServeMux) {
mux.HandleFunc("/api/v1/login-logs", corsMiddleware(api.AuthMiddleware(api.HandleLoginLogs)))
mux.HandleFunc("/api/v1/ssl", corsMiddleware(api.AdminMiddleware(api.HandleSSLSettings)))
mux.HandleFunc("/api/v1/webssh-origins", corsMiddleware(api.AdminMiddleware(api.HandleWebSSHOriginSettings)))
mux.HandleFunc("/api/v1/access-policy", corsMiddleware(api.AdminMiddleware(api.HandlePanelAccessPolicy)))
mux.HandleFunc("/api/v1/security/alerts", corsMiddleware(api.AuthMiddleware(api.ScopeMiddleware("security:read", api.HandleSecurityAlerts))))
mux.HandleFunc("/api/v1/security/check", corsMiddleware(api.AuthMiddleware(api.ScopeMiddleware("security:check", api.HandleSecurityCheck))))
mux.HandleFunc("/api/v1/security/logs", corsMiddleware(api.AuthMiddleware(api.ScopeMiddleware("security:read", api.HandleSecurityLogs))))
@@ -192,7 +196,7 @@ func Run() error {
server := &http.Server{
Addr: addr,
Handler: mux,
Handler: panelAccessMiddleware(mux),
}
if sslEnabled() {
+1 -1
View File
@@ -1,7 +1,7 @@
package version
var (
Version = "1.1.27"
Version = "1.1.28"
Repo = "MengMengCode/CLICD"
)
+9
View File
@@ -27,6 +27,7 @@ func main() {
isServerMode := false
isCliMode := false
noWebAutostart := false
isAccessPolicyCommand := len(os.Args) > 1 && os.Args[1] == "access-policy"
for _, arg := range os.Args[1:] {
if arg == "server" || arg == "-s" || arg == "--server" {
isServerMode = true
@@ -48,6 +49,14 @@ func main() {
}
_ = cfg
if isAccessPolicyCommand {
if err := cli.RunAccessPolicyCommand(os.Args[2:]); err != nil {
fmt.Fprintf(os.Stderr, "Access policy error: %v\n", err)
os.Exit(1)
}
return
}
if isServerMode || (!isTerminal && !isCliMode) {
installShutdownStateCapture()
+22
View File
@@ -191,6 +191,26 @@ Update example:
| `disabled` | Whether this key is disabled. |
| `container_uuids` | Optional container allowlist that limits the key to specific containers. |
## Panel Access Source Policy
Use `GET /api/v1/access-policy` to read the panel source allowlist and `PUT /api/v1/access-policy` to update it. Both endpoints require `admin:access`. The policy covers panel pages, login endpoints, and every API.
```json
{
"enabled": true,
"allowed_sources": [
"203.0.113.10",
"192.168.1.0/24",
"2001:db8::/32"
],
"trusted_proxies": [
"127.0.0.1"
]
}
```
Both lists accept IPv4, IPv6, and CIDR values. The backend only uses `X-Forwarded-For`, `X-Real-IP`, or `CF-Connecting-IP` when the direct peer matches `trusted_proxies`, so untrusted clients cannot bypass the policy by spoofing those headers. An enabled policy requires at least one allowed source, and the API rejects changes that exclude the current administrator source. Direct loopback access remains available as a CLI/SSH recovery path.
## Python Example
Fetch containers:
@@ -302,6 +322,8 @@ print(resp.json())
| GET | `/api/v1/templates` | Template list |
| GET | `/api/v1/images` | Image management list |
| GET | `/api/v1/images/enabled` | Enabled and downloaded images; supports `type=lxc\|kvm` |
| POST | `/api/v1/images/custom` | Add a third-party LXC/KVM image source |
| DELETE | `/api/v1/images/custom` | Remove a third-party LXC/KVM image source and cache |
| POST | `/api/v1/images/download` | Download image |
| POST | `/api/v1/images/cancel` | Cancel image download |
| DELETE | `/api/v1/images/delete` | Delete image cache |
+17
View File
@@ -21,6 +21,23 @@ systemctl restart clicd
journalctl -u clicd -n 100 --no-pager
```
## Panel Access Allowlist CLI
```bash
# Show the current policy
clicd access-policy show
# Allow selected addresses and networks; add reverse proxies when needed
clicd access-policy set \
--allow "203.0.113.10,192.168.1.0/24,2001:db8::/32" \
--trusted-proxy "127.0.0.1"
# Disable source restrictions
clicd access-policy disable
```
The same controls are available from the "Panel access allowlist" item in `clicd cli`. Both paths persist the setting and restart the running panel service automatically.
## Security Recommendations
- Do not expose the web panel directly to untrusted networks.
+2
View File
@@ -17,6 +17,8 @@ CLICD provides a one-line installer. By default, it installs the latest version
curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh | sudo sh
```
The installer asks for separate LXC and KVM NAT private subnets. Press Enter to scan host routes, interfaces, bridges, and libvirt networks and select non-overlapping RFC1918 `/24` networks, or enter a CIDR such as `172.28.40.0/24`. For unattended installation, set `CLICD_LXC_SUBNET` and `CLICD_KVM_SUBNET`.
The script defaults to `CLICD_VERSION=latest` and downloads `clicd-linux-amd64.tar.gz` or `clicd-linux-arm64.tar.gz` from `releases/latest` according to the host architecture.
## Install a Specific Version
+22
View File
@@ -191,6 +191,26 @@ curl -H "Authorization: Bearer YOUR_API_KEY" https://panel.example.com/api/v1/da
| `disabled` | 是否禁用该 Key。 |
| `container_uuids` | 可选;限制该 Key 只能访问指定容器。 |
## 面板访问来源策略
`GET /api/v1/access-policy` 读取面板访问白名单,`PUT /api/v1/access-policy` 更新策略。两者均需要 `admin:access` 权限。策略覆盖面板页面、登录入口和全部 API。
```json
{
"enabled": true,
"allowed_sources": [
"203.0.113.10",
"192.168.1.0/24",
"2001:db8::/32"
],
"trusted_proxies": [
"127.0.0.1"
]
}
```
`allowed_sources``trusted_proxies` 均支持 IPv4、IPv6 及 CIDR。只有直接连接来源命中 `trusted_proxies` 时,后端才会使用 `X-Forwarded-For``X-Real-IP``CF-Connecting-IP`;其他客户端伪造这些请求头不会绕过白名单。启用策略时至少要配置一个允许来源,且接口会拒绝排除当前管理来源的配置。本机回环直连保留为 CLI/SSH 故障恢复通道。
## Python 示例
获取容器列表:
@@ -302,6 +322,8 @@ print(resp.json())
| GET | `/api/v1/templates` | 模板列表 |
| GET | `/api/v1/images` | 镜像管理列表 |
| GET | `/api/v1/images/enabled` | 已启用且已下载的镜像;支持 `type=lxc\|kvm` |
| POST | `/api/v1/images/custom` | 添加第三方 LXC/KVM 镜像源 |
| DELETE | `/api/v1/images/custom` | 移除第三方 LXC/KVM 镜像源及缓存 |
| POST | `/api/v1/images/download` | 下载镜像 |
| POST | `/api/v1/images/cancel` | 取消镜像下载 |
| DELETE | `/api/v1/images/delete` | 删除镜像缓存 |
+17
View File
@@ -21,6 +21,23 @@ systemctl restart clicd
journalctl -u clicd -n 100 --no-pager
```
## 面板访问白名单 CLI
```bash
# 查看当前策略
clicd access-policy show
# 仅允许指定 IP/网段;反向代理地址按需填写
clicd access-policy set \
--allow "203.0.113.10,192.168.1.0/24,2001:db8::/32" \
--trusted-proxy "127.0.0.1"
# 关闭白名单限制
clicd access-policy disable
```
也可以运行 `clicd cli`,在交互菜单中选择“面板访问白名单”。直接命令和交互菜单都会保存配置,并在服务运行时自动重启面板。
## 安全建议
- 不要把 Web 面板直接暴露给不可信来源。
+2
View File
@@ -17,6 +17,8 @@ CLICD 提供一键安装脚本。脚本默认安装 GitHub Releases 的最新版
curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh | sudo sh
```
安装器会分别询问 LXC 与 KVM 的 NAT 私网网段。直接回车时,脚本会扫描宿主机路由、网卡、网桥和 libvirt 网络,自动选择未冲突的 RFC1918 `/24` 网段;也可以输入 `172.28.40.0/24` 这类 CIDR。非交互安装可设置 `CLICD_LXC_SUBNET``CLICD_KVM_SUBNET`
脚本当前默认使用 `CLICD_VERSION=latest`,会按宿主架构下载 `releases/latest` 对应的 `clicd-linux-amd64.tar.gz``clicd-linux-arm64.tar.gz`
## 安装指定版本
+7 -7
View File
@@ -2065,9 +2065,9 @@
"license": "MIT"
},
"node_modules/nanoid": {
"version": "3.3.12",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
"integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
"version": "3.3.16",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
"dev": true,
"funding": [
{
@@ -2123,9 +2123,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.15",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
"integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",
"version": "8.5.23",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.23.tgz",
"integrity": "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==",
"dev": true,
"funding": [
{
@@ -2143,7 +2143,7 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.12",
"nanoid": "^3.3.16",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
+2 -1
View File
@@ -12,6 +12,7 @@
},
"overrides": {
"vite": "6.4.3",
"esbuild": "0.28.1"
"esbuild": "0.28.1",
"postcss": "8.5.23"
}
}
+52 -92
View File
@@ -1,28 +1,28 @@
{
"name": "clicd-frontend",
"version": "1.1.25",
"version": "1.1.28",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clicd-frontend",
"version": "1.1.25",
"version": "1.1.28",
"dependencies": {
"@novnc/novnc": "1.5.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"axios": "^1.18.0",
"lucide-react": "^0.454.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.28.0"
"react": "19.2.8",
"react-dom": "19.2.8",
"react-router": "8.3.0"
},
"devDependencies": {
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.2.0",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
"postcss": "^8.5.23",
"tailwindcss": "^3.4.15",
"typescript": "^5.6.3",
"vite": "^8.0.16"
@@ -480,15 +480,6 @@
"url": "https://github.com/sponsors/Boshen"
}
},
"node_modules/@remix-run/router": {
"version": "1.23.3",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.3.tgz",
"integrity": "sha512-4An71tdz9X8+3sI4Qqqd2LWd9vS39J7sqd9EU4Scw7TJE/qB10Flv/UuqbPVgfQV9XoK8Np6jNquZitnZq5i+Q==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.3.tgz",
@@ -809,32 +800,24 @@
"@babel/types": "^7.28.2"
}
},
"node_modules/@types/prop-types": {
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/react": {
"version": "18.3.30",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.30.tgz",
"integrity": "sha512-3ek6mwJL5/VBewBcY4S66cqlCtK3qi4WIq37Z0m/NHw1hjhI7274Mx1qz/+ggSzyBCOEf7eHjBN6INjPAWYfYw==",
"version": "19.2.17",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.2.2"
}
},
"node_modules/@types/react-dom": {
"version": "18.3.7",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"version": "19.2.3",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^18.0.0"
"@types/react": "^19.2.0"
}
},
"node_modules/@vitejs/plugin-react": {
@@ -1152,6 +1135,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/cookie-es": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-3.1.1.tgz",
"integrity": "sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg==",
"license": "MIT"
},
"node_modules/cssesc": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",
@@ -1625,6 +1614,7 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"dev": true,
"license": "MIT"
},
"node_modules/jsesc": {
@@ -1934,18 +1924,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
},
"bin": {
"loose-envify": "cli.js"
}
},
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
@@ -2038,9 +2016,9 @@
}
},
"node_modules/nanoid": {
"version": "3.3.12",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
"integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
"version": "3.3.16",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
"dev": true,
"funding": [
{
@@ -2144,9 +2122,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.15",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
"integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",
"version": "8.5.23",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.23.tgz",
"integrity": "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==",
"dev": true,
"funding": [
{
@@ -2164,7 +2142,7 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.12",
"nanoid": "^3.3.16",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -2337,28 +2315,24 @@
"license": "MIT"
},
"node_modules/react": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"version": "19.2.8",
"resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz",
"integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-dom": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"version": "19.2.8",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.8.tgz",
"integrity": "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
"scheduler": "^0.27.0"
},
"peerDependencies": {
"react": "^18.3.1"
"react": "^19.2.8"
}
},
"node_modules/react-refresh": {
@@ -2372,35 +2346,24 @@
}
},
"node_modules/react-router": {
"version": "6.30.4",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.4.tgz",
"integrity": "sha512-SVUsDe+DybHM/WmYKIVYhZh1o5Dcuf16yM6WjG02Q9XVFMZIJyHYhwrr6bFBXZkVP6z69kNkMyBCujt8FaFLJA==",
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-8.3.0.tgz",
"integrity": "sha512-qyPMvW83jGIct3yiieisxdk9M745anqhpIMKN5m1t6yBMfgVPpt77aHOqs5fUlEJRMCGffg9BaQLH9oPVOL7xQ==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.3"
"cookie-es": "^3.1.1"
},
"engines": {
"node": ">=14.0.0"
"node": ">=22.22.0"
},
"peerDependencies": {
"react": ">=16.8"
"react": ">=19.2.7",
"react-dom": ">=19.2.7"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
}
},
"node_modules/react-router-dom": {
"version": "6.30.4",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.4.tgz",
"integrity": "sha512-q4HvNl+mmDdkS0g+MqiBZNteQJCuimWoOyHMy4T/RQLAn9Z29+E91QXRaxOujeMl2HTzRSS0KFPd7lxX3PjV0Q==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.3",
"react-router": "6.30.4"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"react": ">=16.8",
"react-dom": ">=16.8"
}
},
"node_modules/read-cache": {
@@ -2525,13 +2488,10 @@
}
},
"node_modules/scheduler": {
"version": "0.23.2",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
}
"version": "0.27.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
"integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
"license": "MIT"
},
"node_modules/semver": {
"version": "6.3.1",
+7 -7
View File
@@ -1,7 +1,7 @@
{
"name": "clicd-frontend",
"private": true,
"version": "1.1.27",
"version": "1.1.28",
"type": "module",
"scripts": {
"dev": "vite",
@@ -14,16 +14,16 @@
"@xterm/xterm": "^6.0.0",
"axios": "^1.18.0",
"lucide-react": "^0.454.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.28.0"
"react": "19.2.8",
"react-dom": "19.2.8",
"react-router": "8.3.0"
},
"devDependencies": {
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.2.0",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
"postcss": "^8.5.23",
"tailwindcss": "^3.4.15",
"typescript": "^5.6.3",
"vite": "^8.0.16"
+1 -1
View File
@@ -1,4 +1,4 @@
import { Routes, Route, Navigate } from 'react-router-dom'
import { Routes, Route, Navigate } from 'react-router'
import { useAuth } from './contexts/AuthContext'
import Login from './pages/Login'
import Dashboard from './pages/Dashboard'
+1 -1
View File
@@ -1,5 +1,5 @@
import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import { useLocation } from 'react-router'
import { useLanguage } from '../contexts/LanguageContext'
import { shouldTranslateText, translateText } from '../utils/i18n'
+1 -1
View File
@@ -1,4 +1,4 @@
import { useNavigate } from 'react-router-dom'
import { useNavigate } from 'react-router'
import {
Server,
Cpu,
+351 -59
View File
@@ -1,7 +1,7 @@
import { useEffect, useMemo, useState, type ReactNode } from 'react'
import { ArrowRight, CalendarClock, Plus, RefreshCw, Trash2, X } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { batchCreate, getIPv6Status, getEnabledImages, getHostInfo, getHostReport, getStorageInfo, CreateContainerRequest, HostInfo, HostProbeReport, IPv6Status, PortMapping, StorageInfo, Template } from '../services/api'
import { ArrowLeft, ArrowRight, CalendarClock, Check, Plus, RefreshCw, Trash2, X } from 'lucide-react'
import { useNavigate } from 'react-router'
import { batchCreate, getIPv6Status, getEnabledImages, getHostInfo, getHostReport, getRoutingInfo, getStorageInfo, CreateContainerRequest, HostInfo, HostProbeReport, IPv6Status, PortMapping, RoutingInfo, StorageInfo, Template } from '../services/api'
import { useDialog } from './Dialog'
import { useLanguage, type Language } from '../contexts/LanguageContext'
import { generateSSHPassword, sshPasswordError, sshPublicKeyError, type SSHAuthMode } from '../utils/sshAuth'
@@ -60,8 +60,10 @@ const defaultForm: CreateContainerRequest = {
export default function CreateContainerModal({ isOpen, onClose, onSuccess, existingNames = [] }: CreateContainerModalProps) {
const navigate = useNavigate()
const dialog = useDialog()
const { language } = useLanguage()
const { language, t } = useLanguage()
const networkText = createNetworkText[language]
const wizardSteps = [t('基础信息'), t('镜像选择'), t('网络配置'), t('预览清单')]
const [currentStep, setCurrentStep] = useState(0)
const [templates, setTemplates] = useState<Template[]>([])
const [loading, setLoading] = useState(false)
const [batchCount, setBatchCount] = useState(1)
@@ -70,9 +72,14 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
const [hostReport, setHostReport] = useState<HostProbeReport | null>(null)
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null)
const [storageLoading, setStorageLoading] = useState(true)
const [routingInfo, setRoutingInfo] = useState<RoutingInfo | null>(null)
const [ipv6Status, setIPv6Status] = useState<IPv6Status | null>(null)
const [nameError, setNameError] = useState('')
useEffect(() => {
if (isOpen) setCurrentStep(0)
}, [isOpen])
useEffect(() => {
if (!isOpen) return
@@ -134,6 +141,19 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
return () => { active = false }
}, [isOpen])
useEffect(() => {
if (!isOpen) return
let active = true
getRoutingInfo()
.then((res) => {
if (active) setRoutingInfo(res.data.data || null)
})
.catch(() => {
if (active) setRoutingInfo(null)
})
return () => { active = false }
}, [isOpen])
const ipv6Available = !!ipv6Status?.available
const ipv6Prefixes = ipv6Status?.prefixes || []
const ipv6Prefix = ipv6Prefixes.length > 1 ? `${ipv6Prefixes.length} prefixes configured` : (ipv6Prefixes[0]?.prefix || '')
@@ -167,22 +187,34 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
: 0
const linuxTemplate = !isWindowsTemplate(form.template_id)
const sshAuthMode = (form.ssh_auth_mode || 'auto_password') as SSHAuthMode
const autoPortMappings = useMemo(() => {
if (!natEnabled) return []
const count = natPortCount
return Array.from({ length: count - 1 }, (_, index) => ({
host_port: 22002 + index,
container_port: 22002 + index,
protocol: 'tcp',
description: `Port-${22002 + index}`,
}))
}, [natEnabled, natPortCount])
const natPreviewMappings = customNATMappings.length > 0 ? customNATMappings : autoPortMappings
const managementPort = Math.round(Number(form.management_port) || 0)
// Automatic allocation starts around 22000; an explicit value is exact.
const sshPortPreview = managementPort || 22000
const natAllocationPreview = useMemo(
() => previewNATAllocation(
routingInfo,
customNATMappings,
managementPort,
natEnabled ? natPortCount - 1 : 0,
isWindowsTemplate(form.template_id) ? 3389 : 22
),
[routingInfo, customNATMappings, managementPort, natEnabled, natPortCount, form.template_id]
)
const autoPortMappings = natAllocationPreview.autoMappings
const natPreviewMappings = customNATMappings.length > 0 ? customNATMappings : autoPortMappings
const sshPortPreview = managementPort || natAllocationPreview.managementPort
const selectedTemplate = templates.find((template) => template.id === form.template_id)
const selectedStoragePool = storagePools.find((pool) => pool.id === form.storage_pool_id)
const selectedAllowedImages = templates.filter((template) => (form.allowed_image_ids || []).includes(template.id))
const networkSummary = form.assign_ipv4
? (manualIPv4s.length > 0
? `${networkText.publicIPv4}: ${manualIPv4s.join(', ')}`
: `${networkText.publicIPv4}: ${t('自动分配')} × ${form.ipv4_count || 1}`)
: lanIPv4Enabled
? `${t('局域网')}: ${lanStaticEnabled ? `${form.lan_ipv4_address}/${form.lan_ipv4_prefix_len}` : 'DHCP'}`
: natEnabled
? `${networkText.publicNAT}: ${natPortCount} ${t('个端口')}`
: form.assign_ipv6
? `${networkText.publicIPv6}: ${form.ipv6_count || 1}`
: t('未配置网络')
// Find next available batch index to avoid name conflicts
const batchStartIndex = useMemo(() => {
@@ -212,6 +244,57 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
}
}
const validateStep = (step: number) => {
if (step === 0) {
if (!form.name.trim() || nameError) {
dialog.alert(t('基础信息有误'), t('请填写有效且未被占用的容器名称'))
return false
}
if (Object.keys(resourceErrors).length > 0) {
dialog.alert(t('资源配置有误'), t('请按红色提示修改 vCPU、内存或磁盘配置'))
return false
}
if (!storageReady) {
dialog.alert(t('未配置存储'), `${t('请先在存储管理中为')} ${form.virtualization === 'kvm' ? t('KVM 磁盘') : t('LXC 容器')} ${t('开启至少一块存储磁盘')}`)
return false
}
const authError = validateSSHAuthInputs(form)
if (authError) {
dialog.alert(t('登录方式有误'), authError)
return false
}
}
if (step === 1 && !form.template_id) {
dialog.alert(t('请选择镜像'), t('请选择用于创建容器的系统镜像'))
return false
}
if (step === 2) {
if (!form.assign_ipv4 && !form.assign_ipv6 && form.assign_nat === false && form.lan_ipv4_mode !== 'dhcp' && form.lan_ipv4_mode !== 'static') {
dialog.alert(t('网络配置有误'), t('请至少启用一种网络连接方式'))
return false
}
if (form.lan_ipv4_mode === 'static' && (!isIPv4Address(form.lan_ipv4_address || '') || !isIPv4Address(form.lan_ipv4_gateway || '') || !form.lan_ipv4_prefix_len)) {
dialog.alert(t('局域网 IPv4 配置有误'), t('请填写有效的 IPv4 地址、子网掩码和网关'))
return false
}
const natMappingError = natEnabled
? validateBatchNATPortMappings(customNATMappings, managementPort, batchCount)
: ''
if (natMappingError) {
dialog.alert(t('NAT 端口配置有误'), natMappingError)
return false
}
}
return true
}
const handleNextStep = () => {
if (!validateStep(currentStep)) return
setCurrentStep((step) => Math.min(wizardSteps.length - 1, step + 1))
}
const handleSubmit = async () => {
if (!form.name || !form.template_id) {
dialog.alert('提示', '请填写容器名称并选择系统模板')
@@ -263,7 +346,7 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
for (let i = 0; i < batchCount; i++) {
const name = batchCount > 1 ? `${boundedForm.name}-${startIndex + i}` : boundedForm.name
const expandedNAT = wantsNAT
? expandBatchNATConfig(boundedForm.nat_port_mappings || [], boundedForm.management_port || 0, i, batchCount)
? expandBatchNATConfig(boundedForm.nat_port_mappings || [], boundedForm.management_port || 0, i)
: { mappings: [], managementPort: 0 }
const natPortMappings = expandedNAT.mappings
containers.push({
@@ -301,7 +384,7 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<div className="bg-white rounded-lg border border-gray-200 shadow-xl w-full max-w-3xl max-h-[92vh] overflow-y-auto">
<div className="flex max-h-[92vh] w-full max-w-5xl flex-col overflow-hidden rounded-lg border border-gray-200 bg-white shadow-xl">
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
<h2 className="text-lg font-semibold text-black"></h2>
<button onClick={onClose} className="p-1 hover:bg-gray-100 rounded text-gray-500" title="关闭">
@@ -309,7 +392,39 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
</button>
</div>
<div className="px-5 py-4 space-y-3">
<nav aria-label={t('创建步骤')} className="border-b border-gray-200 px-5 py-3">
<ol className="grid grid-cols-4 gap-2">
{wizardSteps.map((label, index) => {
const completed = index < currentStep
const active = index === currentStep
return (
<li key={label} className="min-w-0">
<button
type="button"
disabled={index > currentStep}
onClick={() => setCurrentStep(index)}
aria-current={active ? 'step' : undefined}
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors disabled:cursor-default ${
active ? 'bg-gray-100 text-black' : completed ? 'text-gray-700 hover:bg-gray-50' : 'text-gray-400'
}`}
>
<span className={`inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border text-xs font-semibold ${
active || completed ? 'border-black bg-black text-white' : 'border-gray-300 bg-white'
}`}>
{completed ? <Check className="h-3.5 w-3.5" /> : index + 1}
</span>
<span className="min-w-0 truncate text-xs font-medium sm:text-sm">{label}</span>
</button>
</li>
)
})}
</ol>
</nav>
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">
<div className="space-y-3">
{currentStep === 0 && (
<>
<div className="grid grid-cols-2 gap-3">
<Field label="容器名称">
<input
@@ -352,7 +467,11 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
</button>
</div>
</Field>
</>
)}
{currentStep === 1 && (
<>
<Field label="系统模板">
{templates.length === 0 ? (
<div className="text-sm text-amber-600 bg-amber-50 border border-amber-200 rounded-md px-3 py-2">
@@ -378,7 +497,10 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
)}
</Field>
</>
)}
{currentStep === 0 && (
<Field label="存储磁盘">
{storageLoading ? (
<div className="flex items-center gap-2 rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-sm text-gray-600">
@@ -411,8 +533,9 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
</div>
)}
</Field>
)}
{templates.length > 0 && (
{currentStep === 1 && templates.length > 0 && (
<Field label="子用户可用镜像">
<div className="rounded-md border border-gray-200 bg-gray-50 p-3">
<div className="mb-2 text-xs text-gray-500"></div>
@@ -444,7 +567,7 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
</Field>
)}
{linuxTemplate && (
{currentStep === 0 && linuxTemplate && (
<div className="rounded-md border border-gray-200 bg-white px-3 py-3 text-sm">
<div className="mb-2 font-medium text-gray-800"></div>
<div className="grid grid-cols-3 gap-2">
@@ -493,6 +616,7 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
</div>
)}
{currentStep === 2 && (
<div className="grid gap-3 lg:grid-cols-2">
<div className={`rounded-md border px-3 py-2 text-sm ${ipv4Available ? 'border-gray-200 bg-white' : 'border-gray-200 bg-gray-50 text-gray-400'}`}>
<label className="flex items-start gap-3">
@@ -751,6 +875,16 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
<span className="block font-medium text-gray-800">{networkText.publicNAT}</span>
<span className="block text-xs text-gray-500">
{natEnabled ? formatNATPortCount(natPortCount, language) : networkText.noNATPorts}
{natEnabled && routingInfo && (
<span className="mt-0.5 block font-mono">
{language === 'en' ? 'Range' : '范围'} {routingInfo.nat4_port_range.start}-{routingInfo.nat4_port_range.end}
{' · '}
{managementPort > 0
? (language === 'en' ? 'management' : '管理端口')
: (language === 'en' ? 'next' : '下一个')}
{' '}{sshPortPreview || '-'}
</span>
)}
</span>
</span>
</label>
@@ -817,10 +951,13 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
<input
type="radio"
checked={customNATMappings.length > 0}
disabled={!routingInfo}
onChange={() => {
const suggestedPort = autoPortMappings[0]?.host_port || natAllocationPreview.managementPort
if (!suggestedPort) return
const next = customNATMappings.length > 0
? customNATMappings
: [{ host_port: 22002, container_port: 22002, protocol: 'tcp', description: 'Port-22002' }]
: [{ host_port: suggestedPort, container_port: suggestedPort, protocol: 'tcp', description: `Port-${suggestedPort}` }]
setForm({ ...form, extra_ports: [], nat_port_mappings: next, port_mapping_count: next.length + 1, assign_nat: true })
}}
/>
@@ -918,15 +1055,15 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
{batchCount > 1 && (
<p className="text-[11px] text-gray-500">
{language === 'en'
? 'Batch mode shifts the public source-port group for each container; target ports stay unchanged.'
: '批量创建时,每台容器使用不重叠的公网端口,容器目标端口保持不变。'}
? 'Each later container starts after the previous highest public port; target ports stay unchanged.'
: '后续容器从上一台的最高公网端口之后开始,容器内部端口保持不变。'}
</p>
)}
</div>
)}
<div className="flex flex-wrap gap-1.5">
<span className="inline-flex px-2 py-1 bg-emerald-50 text-emerald-700 rounded text-xs font-mono">
{isWindowsTemplate(form.template_id) ? 'RDP' : 'SSH'}: {sshPortPreview} -&gt; {isWindowsTemplate(form.template_id) ? 3389 : 22}
{isWindowsTemplate(form.template_id) ? 'RDP' : 'SSH'}: {sshPortPreview || '--'} -&gt; {isWindowsTemplate(form.template_id) ? 3389 : 22}
{managementPort === 0 ? (language === 'en' ? ' (auto)' : '(自动)') : ''}
</span>
{natPreviewMappings.map((mapping, index) => (
@@ -939,7 +1076,9 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
)}
</div>
</div>
)}
{currentStep === 0 && (
<div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
<Field label="vCPU">
<NumberInput
@@ -1035,22 +1174,128 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
<p className="mt-1 text-[11px] leading-4 text-gray-400"></p>
</Field>
</div>
)}
{currentStep === 3 && (
<div className="space-y-5">
<section>
<h3 className="mb-2 text-sm font-semibold text-gray-900">{t('基础信息')}</h3>
<dl className="grid grid-cols-1 border-y border-gray-200 sm:grid-cols-2 lg:grid-cols-4">
<ReviewItem label={t('容器名称')} value={batchCount > 1 ? `${form.name}-${batchStartIndex}${form.name}-${batchStartIndex + batchCount - 1}` : form.name} />
<ReviewItem label={t('创建数量')} value={String(batchCount)} />
<ReviewItem label={t('虚拟化架构')} value={form.virtualization === 'kvm' ? 'KVM' : 'LXC'} />
<ReviewItem label={t('存储磁盘')} value={selectedStoragePool ? `${selectedStoragePool.name} · ${selectedStoragePool.mount_point || selectedStoragePool.path}` : t('自动选择')} />
<ReviewItem label="vCPU" value={String(form.vcpu)} />
<ReviewItem label={t('内存')} value={`${form.ram_mb} MB`} />
<ReviewItem label={t('磁盘')} value={`${form.disk_gb} GB`} />
<ReviewItem label={t('到期时间')} value={form.expires_at || t('长期有效')} />
</dl>
</section>
<section>
<h3 className="mb-2 text-sm font-semibold text-gray-900">{t('镜像与登录')}</h3>
<dl className="grid grid-cols-1 border-y border-gray-200 sm:grid-cols-3">
<ReviewItem label={t('系统镜像')} value={selectedTemplate?.name || '-'} />
<ReviewItem label={t('登录方式')} value={
!linuxTemplate
? t('镜像默认')
: sshAuthMode === 'key'
? 'SSH Key'
: sshAuthMode === 'password'
? t('自定义密码')
: t('自动生成密码')
} />
<ReviewItem label={t('子用户可用镜像')} value={`${selectedAllowedImages.length} ${t('个')}`} />
</dl>
{selectedAllowedImages.length > 0 && (
<div className="mt-2 flex flex-wrap gap-1.5">
{selectedAllowedImages.map((template) => (
<span key={template.id} className="rounded bg-gray-100 px-2 py-1 text-xs text-gray-700">
{template.name}
</span>
))}
</div>
)}
</section>
<section>
<h3 className="mb-2 text-sm font-semibold text-gray-900">{t('网络配置')}</h3>
<dl className="grid grid-cols-1 border-y border-gray-200 sm:grid-cols-2">
<ReviewItem label={t('主要网络')} value={networkSummary} />
<ReviewItem
label={networkText.publicIPv6}
value={form.assign_ipv6 ? `${form.ipv6_count || 1} ${t('个地址')}` : t('未启用')}
/>
</dl>
{natEnabled && (
<div className="mt-3">
<div className="mb-1.5 text-xs font-medium text-gray-500">{t('端口映射')}</div>
<div className="flex flex-wrap gap-1.5">
<span className="rounded bg-emerald-50 px-2 py-1 font-mono text-xs text-emerald-700">
{isWindowsTemplate(form.template_id) ? 'RDP' : 'SSH'}: {sshPortPreview || t('自动')} -&gt; {isWindowsTemplate(form.template_id) ? 3389 : 22}/TCP
</span>
{natPreviewMappings.map((mapping, index) => (
<span key={`${mapping.host_port}-${mapping.container_port}-${mapping.protocol}-${index}`} className="rounded bg-gray-100 px-2 py-1 font-mono text-xs text-gray-700">
{mapping.host_port || t('自动')} -&gt; {mapping.container_port}/{mapping.protocol.toUpperCase()}
</span>
))}
</div>
</div>
)}
</section>
</div>
)}
</div>
</div>
<div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200">
<div className="flex items-center justify-between gap-3 border-t border-gray-200 px-6 py-4">
<button onClick={onClose} className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-md transition-colors">
{t('取消')}
</button>
<div className="flex items-center gap-2">
{currentStep > 0 && (
<button
onClick={handleSubmit}
disabled={loading || storageLoading || !storageReady}
className="px-4 py-2 text-sm bg-black text-white rounded-md hover:bg-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
type="button"
onClick={() => setCurrentStep((step) => Math.max(0, step - 1))}
className="inline-flex items-center gap-2 rounded-md border border-gray-300 px-4 py-2 text-sm text-gray-700 transition-colors hover:bg-gray-50"
>
{loading ? '创建中...' : '创建容器'}
<ArrowLeft className="h-4 w-4" />
{t('上一步')}
</button>
)}
{currentStep < wizardSteps.length - 1 ? (
<button
type="button"
onClick={handleNextStep}
disabled={currentStep === 0 && storageLoading}
className="inline-flex items-center gap-2 rounded-md bg-black px-4 py-2 text-sm text-white transition-colors hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-50"
>
{t('下一步')}
<ArrowRight className="h-4 w-4" />
</button>
) : (
<button
type="button"
onClick={handleSubmit}
disabled={loading}
className="inline-flex items-center gap-2 rounded-md bg-black px-4 py-2 text-sm text-white transition-colors hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-50"
>
{loading ? t('创建中...') : t('确认创建')}
</button>
)}
</div>
</div>
</div>
</div>
)
}
function ReviewItem({ label, value }: { label: string; value: string }) {
return (
<div className="min-w-0 border-b border-gray-100 px-3 py-2.5 last:border-b-0 sm:border-b-0 sm:border-r sm:last:border-r-0">
<dt className="text-xs text-gray-500">{label}</dt>
<dd className="mt-1 break-words text-sm font-medium text-gray-800">{value || '-'}</dd>
</div>
)
}
@@ -1115,9 +1360,10 @@ function NumberInput({
function validateResourceInputs(form: CreateContainerRequest, maxVCPU: number, maxRAMMB?: number, maxDiskGB?: number) {
const errors: Partial<Record<'vcpu' | 'ram_mb' | 'disk_gb', string>> = {}
const windows = isWindowsTemplate(form.template_id)
const windows11 = form.template_id.toLowerCase().includes('windows-11')
const minVCPU = windows ? 2 : (form.virtualization === 'kvm' ? 1 : 0.25)
const minRAMMB = windows ? 2048 : 128
const minDiskGB = windows ? 30 : 1
const minRAMMB = windows11 ? 4096 : windows ? 2048 : 128
const minDiskGB = windows11 ? 64 : windows ? 30 : 1
if (!Number.isFinite(form.vcpu)) {
errors.vcpu = '请输入 vCPU'
@@ -1272,8 +1518,68 @@ function normalizeNATPortMappings(mappings: PortMapping[]) {
})
}
function expandBatchNATConfig(mappings: PortMapping[], managementPort: number, batchIndex: number, batchCount: number) {
const stride = batchNATPortStride(batchNATSourceMappings(mappings, managementPort), batchCount)
function previewNATAllocation(
routing: RoutingInfo | null,
customMappings: PortMapping[],
explicitManagementPort: number,
autoMappingCount: number,
managementTargetPort: number
) {
if (!routing) {
return { managementPort: explicitManagementPort, autoMappings: [] as PortMapping[] }
}
const { start, end } = routing.nat4_port_range
const used = new Set(
(routing.nat4_mappings || [])
.map((mapping) => Math.round(Number(mapping.host_port) || 0))
.filter((port) => port >= start && port <= end)
)
const excluded = new Set(
customMappings
.map((mapping) => Math.round(Number(mapping.host_port) || 0))
.filter((port) => port >= start && port <= end)
)
let managementPort = explicitManagementPort
if (managementPort === 0) {
const cursor = routing.nat4_next_port >= start && routing.nat4_next_port <= end
? routing.nat4_next_port
: start
managementPort = findAvailableNATPort(start, end, cursor, new Set([...used, ...excluded]))
}
const autoMappings: PortMapping[] = []
if (customMappings.length === 0 && autoMappingCount > 0) {
const unavailable = new Set(used)
if (managementPort > 0) unavailable.add(managementPort)
if (managementTargetPort >= start && managementTargetPort <= end) unavailable.add(managementTargetPort)
for (let port = start; port <= end && autoMappings.length < autoMappingCount; port++) {
if (unavailable.has(port)) continue
unavailable.add(port)
autoMappings.push({
host_port: port,
container_port: port,
protocol: 'tcp',
description: `Port-${port}`,
})
}
}
return { managementPort, autoMappings }
}
function findAvailableNATPort(start: number, end: number, cursor: number, unavailable: Set<number>) {
const capacity = end - start + 1
for (let offset = 0; offset < capacity; offset++) {
const candidate = start + ((cursor - start + offset) % capacity)
if (!unavailable.has(candidate)) return candidate
}
return 0
}
function expandBatchNATConfig(mappings: PortMapping[], managementPort: number, batchIndex: number) {
const stride = batchNATPortStride(batchNATSourceMappings(mappings, managementPort))
const offset = batchIndex * stride
return {
mappings: mappings.map((mapping) => ({
@@ -1297,26 +1603,12 @@ function batchNATSourceMappings(mappings: PortMapping[], managementPort: number)
]
}
function batchNATPortStride(mappings: PortMapping[], batchCount: number) {
if (mappings.length === 0 || batchCount <= 1) return 1
const invalid = new Set<number>()
for (let left = 0; left < mappings.length; left++) {
for (let right = left + 1; right < mappings.length; right++) {
const leftProtocol = (mappings[left].protocol || 'tcp').toLowerCase()
const rightProtocol = (mappings[right].protocol || 'tcp').toLowerCase()
if (leftProtocol !== rightProtocol) continue
const difference = Math.abs(
Math.round(Number(mappings[left].host_port) || 0)
- Math.round(Number(mappings[right].host_port) || 0)
)
for (let distance = 1; difference > 0 && distance < batchCount; distance++) {
if (difference % distance === 0) invalid.add(difference / distance)
}
}
}
let stride = 1
while (invalid.has(stride)) stride++
return stride
function batchNATPortStride(mappings: PortMapping[]) {
const sourcePorts = mappings
.map((mapping) => Math.round(Number(mapping.host_port) || 0))
.filter((port) => port > 0)
if (sourcePorts.length === 0) return 1
return Math.max(...sourcePorts) - Math.min(...sourcePorts) + 1
}
function validateBatchNATPortMappings(mappings: PortMapping[], managementPort: number, batchCount: number) {
@@ -1327,7 +1619,7 @@ function validateBatchNATPortMappings(mappings: PortMapping[], managementPort: n
if (mappings.length > 63) return '每个容器最多可配置 63 条自定义 NAT 映射'
const used = new Map<string, string>()
const stride = batchNATPortStride(batchNATSourceMappings(mappings, managementPort), batchCount)
const stride = batchNATPortStride(batchNATSourceMappings(mappings, managementPort))
for (let batchIndex = 0; batchIndex < batchCount; batchIndex++) {
if (managementPort > 0) {
const expandedManagementPort = managementPort + batchIndex * stride
+2 -2
View File
@@ -1,4 +1,4 @@
import { Outlet } from 'react-router-dom'
import { Outlet } from 'react-router'
import Sidebar from './Sidebar'
import { useState } from 'react'
import AutoTranslate from './AutoTranslate'
@@ -12,7 +12,7 @@ export default function Layout() {
<AutoTranslate />
<BrowserDialogTranslator />
<Sidebar collapsed={sidebarCollapsed} onToggle={() => setSidebarCollapsed(!sidebarCollapsed)} />
<main className={`flex-1 transition-all duration-300 ${sidebarCollapsed ? 'ml-16' : 'ml-60'}`}>
<main className={`min-w-0 flex-1 transition-all duration-300 ${sidebarCollapsed ? 'ml-16' : 'ml-60'}`}>
<div className="p-6">
<Outlet />
</div>
+1 -1
View File
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useLocation, useNavigate } from 'react-router'
import {
ChevronLeft,
ChevronRight,
+1 -1
View File
@@ -1,5 +1,5 @@
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { useNavigate } from 'react-router-dom'
import { useNavigate } from 'react-router'
import api, { login as apiLogin, checkAuth, LoginResponse } from '../services/api'
interface AuthContextType {
+3
View File
@@ -17,6 +17,7 @@ body {
/* Scrollbar */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
@@ -199,4 +200,6 @@ body {
.dark .peer-checked\:bg-black:checked ~ * { background-color: #f9fafb !important; }
.dark .peer-checked\:bg-black:checked + *,
.dark input.peer:checked + .peer-checked\:bg-black { background-color: #f9fafb !important; }
.dark .access-policy-switch .access-policy-switch-thumb { background-color: #e5e7eb !important; }
.dark .access-policy-switch[aria-checked="true"] .access-policy-switch-thumb { background-color: #111827 !important; }
+1 -1
View File
@@ -1,6 +1,6 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import { BrowserRouter } from 'react-router'
import App from './App'
import { AuthProvider } from './contexts/AuthContext'
import { ThemeProvider } from './contexts/ThemeContext'
+44 -2
View File
@@ -199,6 +199,8 @@ const endpointGroups: Array<{ title: string; endpoints: EndpointTuple[] }> = [
['GET', '/api/v1/templates', '模板列表'],
['GET', '/api/v1/images', '镜像管理列表'],
['GET', '/api/v1/images/enabled?type=lxc&container={id}', '可用于创建或重装的已启用镜像'],
['POST', '/api/v1/images/custom', '添加第三方 LXC/KVM 镜像源'],
['DELETE', '/api/v1/images/custom', '移除第三方 LXC/KVM 镜像源'],
['POST', '/api/v1/images/download', '下载镜像'],
['POST', '/api/v1/images/cancel', '取消镜像下载'],
['DELETE', '/api/v1/images/delete', '删除镜像缓存'],
@@ -228,6 +230,8 @@ const endpointGroups: Array<{ title: string; endpoints: EndpointTuple[] }> = [
['PUT', '/api/v1/ssl', '更新 SSL 配置'],
['GET', '/api/v1/webssh-origins', 'WebSSH/VNC Origin 白名单'],
['PUT', '/api/v1/webssh-origins', '更新 WebSSH/VNC Origin 白名单'],
['GET', '/api/v1/access-policy', '面板访问来源策略'],
['PUT', '/api/v1/access-policy', '更新面板访问来源策略'],
['GET', '/api/v1/language', '面板语言'],
['PUT', '/api/v1/language', '更新面板语言'],
],
@@ -845,6 +849,18 @@ const requestBodySamples: Record<string, Record<string, unknown>> = {
time: '03:00',
},
'PUT /api/v1/containers/{id}/snapshots/quota': { snapshot_limit: 2 },
'POST /api/v1/images/custom': {
type: 'kvm',
name: 'Custom Ubuntu Cloud',
description: 'Private mirror image',
distro: 'ubuntu',
release: 'noble',
arch: 'amd64',
url: 'https://images.example.com/ubuntu-noble.qcow2',
provisioner: 'linux-cloud-init',
sha256: '',
},
'DELETE /api/v1/images/custom': { id: 'custom-kvm-a1b2c3d4e5' },
'POST /api/v1/images/download': { template_id: 'debian-bookworm' },
'POST /api/v1/images/cancel': { template_id: 'debian-bookworm' },
'DELETE /api/v1/images/delete': { template_id: 'debian-bookworm' },
@@ -873,6 +889,11 @@ const requestBodySamples: Record<string, Record<string, unknown>> = {
'PUT /api/v1/webssh-origins': {
origins: ['https://panel.example.com'],
},
'PUT /api/v1/access-policy': {
enabled: true,
allowed_sources: ['203.0.113.10', '192.168.1.0/24', '2001:db8::/32'],
trusted_proxies: ['127.0.0.1'],
},
'PUT /api/v1/language': { language: 'zh' },
'PUT /api/v1/routing': {
items: [
@@ -1027,6 +1048,11 @@ const responseSamples: Record<string, unknown> = {
data: {
nat4: { used: 62, remaining: '45474', total: '45536' },
nat4_port_range: { start: 20000, end: 65535 },
nat4_next_port: 22005,
nat4_networks: {
lxc: { subnet: '10.0.3.0/24', gateway: '10.0.3.1', netmask: '255.255.255.0', dhcp_start: '10.0.3.2', dhcp_end: '10.0.3.254', dhcp_max: 253, prefix_bits: 24 },
kvm: { subnet: '192.168.122.0/24', gateway: '192.168.122.1', netmask: '255.255.255.0', dhcp_start: '192.168.122.2', dhcp_end: '192.168.122.254', dhcp_max: 253, prefix_bits: 24 },
},
ipv4: { used: 1, remaining: '3', total: '4' },
ipv6: { used: 31, remaining: 'large', total: 'large' },
public_ipv4_addresses: [{ address: '203.0.113.10', interface: 'eth0', prefix_len: 32, gateway: '203.0.113.1' }],
@@ -1042,6 +1068,11 @@ const responseSamples: Record<string, unknown> = {
data: {
nat4: { used: 62, remaining: '45474', total: '45536' },
nat4_port_range: { start: 20000, end: 65535 },
nat4_next_port: 22005,
nat4_networks: {
lxc: { subnet: '10.0.3.0/24', gateway: '10.0.3.1' },
kvm: { subnet: '192.168.122.0/24', gateway: '192.168.122.1' },
},
ipv4: { used: 1, remaining: '3', total: '4' },
public_ipv4_addresses: [{ address: '203.0.113.10', interface: 'eth0', prefix_len: 32, gateway: '203.0.113.1' }],
ipv6_prefixes: [{ interface: 'eth0', address: '2001:db8:100::2', prefix: '2001:db8:100::/64', prefix_len: 64, gateway: '2001:db8:100::1' }],
@@ -1234,6 +1265,12 @@ const responseSamples: Record<string, unknown> = {
{ id: 'debian-bookworm', name: 'Debian 12', distro: 'debian', release: 'bookworm', arch: 'amd64', type: 'lxc', downloaded: true, enabled: true },
],
},
'POST /api/v1/images/custom': {
success: true,
message: 'Custom image added',
data: { id: 'custom-kvm-a1b2c3d4e5', name: 'Custom Ubuntu Cloud' },
},
'DELETE /api/v1/images/custom': { success: true, message: 'Custom image removed' },
'POST /api/v1/images/download': { success: true, message: 'Already downloaded' },
'POST /api/v1/images/cancel': { success: true, message: 'Cancel requested' },
'DELETE /api/v1/images/delete': { success: true, message: 'Deleted' },
@@ -1277,6 +1314,8 @@ const responseSamples: Record<string, unknown> = {
'PUT /api/v1/ssl': { success: true, message: 'SSL settings saved', data: { enabled: true, mode: 'letsencrypt', target: 'panel.example.com', needs_restart: true } },
'GET /api/v1/webssh-origins': { success: true, data: { origins: ['https://panel.example.com'], current_origin: 'https://panel.example.com' } },
'PUT /api/v1/webssh-origins': { success: true, message: 'Origin allowlist saved', data: { origins: ['https://panel.example.com'], current_origin: 'https://panel.example.com' } },
'GET /api/v1/access-policy': { success: true, data: { enabled: true, allowed_sources: ['203.0.113.10', '192.168.1.0/24'], trusted_proxies: ['127.0.0.1'], current_source: '203.0.113.10', direct_source: '127.0.0.1', using_forwarded: true } },
'PUT /api/v1/access-policy': { success: true, message: 'Panel access policy saved', data: { enabled: true, allowed_sources: ['203.0.113.10', '192.168.1.0/24'], trusted_proxies: ['127.0.0.1'], current_source: '203.0.113.10', direct_source: '127.0.0.1', using_forwarded: true } },
'GET /api/v1/language': { success: true, data: { language: 'zh' } },
'PUT /api/v1/language': { success: true, data: { language: 'zh' } },
'GET /api/v1/security/alerts': { success: true, data: [] },
@@ -1367,7 +1406,7 @@ function endpointNoteFor(key: string) {
}
if (key === 'POST /api/v1/batch-create') {
notes.push('Each containers[] item in batch creation supports the same storage, network, image allowlist, and SSH authentication fields as POST /api/v1/containers.')
notes.push('Custom management_port and NAT host_port values must be unique across the batch. The panel shifts each source-port group for later containers while keeping target ports unchanged; direct API clients should submit the expanded values explicitly.')
notes.push('Custom management_port and NAT host_port values must be unique across the batch. The panel places each later source-port group after the previous container\'s highest public port while keeping every target container_port unchanged; direct API clients should submit the expanded values explicitly.')
}
if (key === 'PUT /api/v1/containers/{id}/resource-limit') {
notes.push('Supports independent download/upload bandwidth limits and read/write I/O limits. Omitted fields keep their current values, and explicitly passing 0 makes that direction unlimited. network_bw_mbps and io_speed_mbps are deprecated symmetric compatibility aliases.')
@@ -1399,9 +1438,12 @@ function endpointNoteFor(key: string) {
if (key === 'PUT /api/v1/storage') {
notes.push('Start from GET /api/v1/storage and submit mounted disks returned by the server. Paths and mount points are server-managed and custom paths are rejected. content_types enables a disk for each workload; only one pool may be the default for each type.')
}
if (key.includes('/api/v1/storage') || key.includes('/task-queue/settings') || key.includes('/api/v1/ssl') || key.includes('/webssh-origins')) {
if (key.includes('/api/v1/storage') || key.includes('/task-queue/settings') || key.includes('/api/v1/ssl') || key.includes('/webssh-origins') || key.includes('/access-policy')) {
notes.push('This endpoint requires an API key with admin:access.')
}
if (key === 'PUT /api/v1/access-policy') {
notes.push('allowed_sources and trusted_proxies accept IPv4, IPv6, or CIDR values. Forwarded client headers are ignored unless the direct peer matches trusted_proxies. The server rejects an enabled policy that excludes the current source.')
}
if (key === 'PUT /api/v1/task-queue/settings') {
notes.push('concurrency must be between 1 and 16. Tasks targeting the same container are still serialized.')
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback, useRef, type ReactNode } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { useParams, useNavigate } from 'react-router'
import {
ArrowLeft,
AlertTriangle,
+2 -1
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { useNavigate } from 'react-router-dom'
import { useNavigate } from 'react-router'
import {
ArrowDown,
ArrowUp,
@@ -991,6 +991,7 @@ function getTemplateName(id: string) {
'kvm-debian-bookworm': 'Debian 12',
'kvm-debian-bullseye': 'Debian 11',
'kvm-rockylinux-9': 'Rocky 9',
'kvm-windows-11': 'Windows 11',
'kvm-windows-10': 'Windows 10',
}
return map[id] || id
+2 -2
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useState, type ReactNode } from 'react'
import { Cpu, HardDrive, MemoryStick, Network, Server } from 'lucide-react'
import RingStats from '../components/RingStats'
import ResourceStatsPanel, {
@@ -171,7 +171,7 @@ function SummaryCard({
value,
muted = false,
}: {
icon?: JSX.Element
icon?: ReactNode
dot?: string
title: string
value: number
+282 -6
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useState, type ReactNode } from 'react'
import { useNavigate } from 'react-router-dom'
import { useNavigate } from 'react-router'
import {
Download,
Trash2,
@@ -11,12 +11,29 @@ import {
Loader2,
AlertCircle,
X,
Plus,
Unlink,
CloudDownload,
} from 'lucide-react'
import { getImages, getStorageInfo, downloadImage, cancelImageDownload, deleteImage, toggleImage, ImageInfo, StorageInfo } from '../services/api'
import {
getImages,
getStorageInfo,
downloadImage,
cancelImageDownload,
deleteImage,
toggleImage,
createCustomKVMImage,
removeCustomKVMImage,
ImageInfo,
StorageInfo,
CustomKVMImageInput,
} from '../services/api'
import { useDialog } from '../components/Dialog'
import { useLanguage } from '../contexts/LanguageContext'
export default function ImageManagement() {
const dialog = useDialog()
const { t } = useLanguage()
const navigate = useNavigate()
const [images, setImages] = useState<ImageInfo[]>([])
const [loading, setLoading] = useState(true)
@@ -24,6 +41,7 @@ export default function ImageManagement() {
const [error, setError] = useState('')
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null)
const [storageLoading, setStorageLoading] = useState(true)
const [customModalOpen, setCustomModalOpen] = useState<'lxc' | 'kvm' | null>(null)
const fetchImages = useCallback(async () => {
try {
@@ -115,6 +133,34 @@ export default function ImageManagement() {
}
}
const handleRemoveCustom = async (templateId: string) => {
if (!(await dialog.confirm('移除第三方镜像', '确定移除该镜像源和已下载的缓存吗?正在使用该镜像的虚拟机不会允许移除。'))) return
setActionLoading(templateId)
setError('')
try {
await removeCustomKVMImage(templateId)
await fetchImages()
dialog.alert('完成', '第三方镜像已移除')
} catch (err: unknown) {
dialog.alert('失败', apiErrorMessage(err, '移除第三方镜像失败'))
} finally {
setActionLoading(null)
}
}
const handleCustomCreated = async (payload: CustomKVMImageInput) => {
const response = await createCustomKVMImage(payload)
const image = response.data.data
if (!image) throw new Error('镜像源保存成功,但服务器没有返回镜像 ID')
try {
await downloadImage(image.id)
dialog.alert('完成', '第三方镜像已添加,下载任务已启动')
} catch (err: unknown) {
dialog.alert('提示', `镜像源已保存,但下载未启动:${apiErrorMessage(err, '请在列表中重试')}`)
}
await fetchImages()
}
const downloadedCount = images.filter((img) => img.downloaded).length
const lxcImages = images.filter((img) => img.type === 'lxc')
const kvmImages = images.filter((img) => img.type === 'kvm')
@@ -185,8 +231,21 @@ export default function ImageManagement() {
onCancelDownload={handleCancelDownload}
onDelete={handleDelete}
onToggle={handleToggle}
onRemoveCustom={handleRemoveCustom}
storageReady={imageStorageReady}
storageLoading={storageLoading}
headerAction={(
<button
type="button"
onClick={() => setCustomModalOpen('lxc')}
disabled={storageLoading || !imageStorageReady}
title={storageLoading ? t('正在检查存储配置...') : imageStorageReady ? t('下载第三方 LXC 镜像') : t('请先在存储管理中开启镜像缓存存储')}
className="inline-flex items-center gap-1.5 rounded-md bg-black px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white dark:text-black dark:hover:bg-gray-200"
>
<Plus className="h-3.5 w-3.5" />
{t('第三方镜像')}
</button>
)}
/>
{kvmImages.length > 0 && (
@@ -200,10 +259,206 @@ export default function ImageManagement() {
onCancelDownload={handleCancelDownload}
onDelete={handleDelete}
onToggle={handleToggle}
onRemoveCustom={handleRemoveCustom}
storageReady={imageStorageReady}
storageLoading={storageLoading}
headerAction={(
<button
type="button"
onClick={() => setCustomModalOpen('kvm')}
disabled={storageLoading || !imageStorageReady}
title={storageLoading ? t('正在检查存储配置...') : imageStorageReady ? t('下载第三方 KVM 镜像') : t('请先在存储管理中开启镜像缓存存储')}
className="inline-flex items-center gap-1.5 rounded-md bg-black px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white dark:text-black dark:hover:bg-gray-200"
>
<Plus className="h-3.5 w-3.5" />
{t('第三方镜像')}
</button>
)}
/>
)}
{customModalOpen !== null && (
<CustomKVMImageModal
virtualization={customModalOpen}
arch={(customModalOpen === 'lxc' ? lxcImages[0]?.arch : kvmImages[0]?.arch) || 'amd64'}
onClose={() => setCustomModalOpen(null)}
onSubmit={handleCustomCreated}
/>
)}
</div>
)
}
const emptyCustomImage = (arch: string, virtualization: 'lxc' | 'kvm'): CustomKVMImageInput => ({
type: virtualization,
name: '',
description: '',
distro: '',
release: '',
arch,
url: '',
provisioner: virtualization === 'lxc' ? 'lxc-rootfs' : 'linux-cloud-init',
sha256: '',
})
function CustomKVMImageModal({
virtualization,
arch,
onClose,
onSubmit,
}: {
virtualization: 'lxc' | 'kvm'
arch: string
onClose: () => void
onSubmit: (payload: CustomKVMImageInput) => Promise<void>
}) {
const { t } = useLanguage()
const [form, setForm] = useState<CustomKVMImageInput>(() => emptyCustomImage(arch, virtualization))
const [submitting, setSubmitting] = useState(false)
const [formError, setFormError] = useState('')
const windows = virtualization === 'kvm' && form.provisioner !== 'linux-cloud-init'
useEffect(() => {
const closeOnEscape = (event: KeyboardEvent) => {
if (event.key === 'Escape' && !submitting) onClose()
}
window.addEventListener('keydown', closeOnEscape)
return () => window.removeEventListener('keydown', closeOnEscape)
}, [onClose, submitting])
const updateProvisioner = (provisioner: 'linux-cloud-init' | 'windows-10' | 'windows-11') => {
setForm((current) => ({
...current,
provisioner,
distro: provisioner === 'linux-cloud-init' ? (current.distro === 'windows' ? '' : current.distro) : 'windows',
release: provisioner === 'windows-10' ? '10' : provisioner === 'windows-11' ? '11' : (current.distro === 'windows' ? '' : current.release),
}))
}
const submit = async () => {
if (!form.name.trim() || !form.distro.trim() || !form.release.trim() || !form.url.trim()) {
setFormError(t('请填写名称、发行版、版本和下载地址'))
return
}
if (form.sha256 && !/^[a-fA-F0-9]{64}$/.test(form.sha256.trim())) {
setFormError(t('SHA-256 必须是 64 位十六进制字符串'))
return
}
setSubmitting(true)
setFormError('')
try {
await onSubmit({
...form,
name: form.name.trim(),
description: form.description.trim(),
distro: form.distro.trim().toLowerCase(),
release: form.release.trim().toLowerCase(),
url: form.url.trim(),
sha256: form.sha256?.trim().toLowerCase(),
})
onClose()
} catch (err: unknown) {
setFormError(apiErrorMessage(err, t('添加第三方镜像失败')))
} finally {
setSubmitting(false)
}
}
const inputClass = 'mt-1.5 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-black outline-none focus:border-black focus:ring-2 focus:ring-black/10 dark:border-gray-700 dark:bg-gray-950 dark:text-white dark:focus:border-white dark:focus:ring-white/10'
return (
<div className="fixed inset-0 z-[90] flex items-center justify-center bg-black/55 p-4 dark:bg-black/75">
<div className="w-full max-w-2xl overflow-hidden rounded-lg border border-gray-200 bg-white shadow-xl dark:border-gray-700 dark:bg-gray-900">
<div className="flex items-center justify-between border-b border-gray-200 px-5 py-4 dark:border-gray-700">
<div>
<h3 className="text-base font-semibold text-gray-900 dark:text-white">{t(virtualization === 'lxc' ? '下载第三方 LXC 镜像' : '下载第三方 KVM 镜像')}</h3>
<p className="mt-0.5 text-xs text-gray-500 dark:text-gray-400">
{t(virtualization === 'lxc' ? '支持 tar、tar.gz、tar.xz、tar.zst 格式的 Linux rootfs' : '镜像格式必须与所选无人值守安装模板匹配')}
</p>
</div>
<button type="button" onClick={onClose} disabled={submitting} className="rounded p-1.5 text-gray-400 hover:bg-gray-100 hover:text-black disabled:opacity-50 dark:hover:bg-gray-800 dark:hover:text-white" title={t('关闭')}>
<X className="h-4 w-4" />
</button>
</div>
<div className="max-h-[72vh] space-y-5 overflow-y-auto px-5 py-4">
{virtualization === 'kvm' && <div>
<label className="text-sm font-medium text-gray-700 dark:text-gray-200">{t('无人值守安装模板')}</label>
<div className="mt-2 grid grid-cols-1 gap-2 sm:grid-cols-3">
{([
['linux-cloud-init', 'Linux cloud-init', 'QCOW2 / IMG'],
['windows-10', 'Windows 10', '安装 ISO'],
['windows-11', 'Windows 11', '安装 ISO'],
] as const).map(([value, label, hint]) => (
<button
key={value}
type="button"
onClick={() => updateProvisioner(value)}
disabled={arch !== 'amd64' && value !== 'linux-cloud-init'}
className={`rounded-md border px-3 py-2 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-40 ${
form.provisioner === value
? 'border-black bg-gray-50 dark:border-white dark:bg-gray-800'
: 'border-gray-200 hover:border-gray-400 dark:border-gray-700 dark:hover:border-gray-500'
}`}
>
<span className="block text-sm font-medium text-gray-900 dark:text-white">{label}</span>
<span className="mt-0.5 block text-xs text-gray-500 dark:text-gray-400">{t(hint)}</span>
</button>
))}
</div>
</div>}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<label className="text-sm text-gray-700 dark:text-gray-200">
{t('镜像名称')}
<input className={inputClass} value={form.name} maxLength={100} onChange={(event) => setForm({ ...form, name: event.target.value })} placeholder={virtualization === 'lxc' ? 'Alpine Custom Rootfs' : windows ? 'Windows 11 Custom' : 'Ubuntu Custom Cloud'} />
</label>
<label className="text-sm text-gray-700 dark:text-gray-200">
{t('架构')}
<select className={inputClass} value={form.arch} disabled>
<option value={arch}>{arch}</option>
</select>
</label>
<label className="text-sm text-gray-700 dark:text-gray-200">
{t('发行版')}
<input className={inputClass} value={form.distro} disabled={windows} maxLength={64} onChange={(event) => setForm({ ...form, distro: event.target.value })} placeholder="ubuntu" />
</label>
<label className="text-sm text-gray-700 dark:text-gray-200">
{t('版本 / 代号')}
<input className={inputClass} value={form.release} disabled={windows} maxLength={64} onChange={(event) => setForm({ ...form, release: event.target.value })} placeholder="noble" />
</label>
</div>
<label className="block text-sm text-gray-700 dark:text-gray-200">
{t('备注')}
<textarea className={`${inputClass} min-h-20 resize-y`} value={form.description} maxLength={500} onChange={(event) => setForm({ ...form, description: event.target.value })} placeholder={t('镜像来源、版本或用途')} />
</label>
<label className="block text-sm text-gray-700 dark:text-gray-200">
{t('镜像下载地址')}
<input className={`${inputClass} font-mono text-xs`} value={form.url} onChange={(event) => setForm({ ...form, url: event.target.value })} placeholder={virtualization === 'lxc' ? 'https://example.com/rootfs.tar.xz' : windows ? 'https://example.com/windows.iso' : 'https://example.com/image.qcow2'} />
</label>
<label className="block text-sm text-gray-700 dark:text-gray-200">
SHA-256 <span className="text-xs text-gray-400">({t('可选')})</span>
<input className={`${inputClass} font-mono text-xs`} value={form.sha256 || ''} maxLength={64} onChange={(event) => setForm({ ...form, sha256: event.target.value })} placeholder={t('用于校验下载文件完整性')} />
</label>
{formError && (
<div className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900 dark:bg-red-950 dark:text-red-300">
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
{formError}
</div>
)}
</div>
<div className="flex justify-end gap-2 border-t border-gray-200 bg-gray-50 px-5 py-3 dark:border-gray-700 dark:bg-gray-800">
<button type="button" onClick={onClose} disabled={submitting} className="rounded-md px-4 py-2 text-sm text-gray-700 hover:bg-gray-200 disabled:opacity-50 dark:text-gray-300 dark:hover:bg-gray-700">{t('取消')}</button>
<button type="button" onClick={submit} disabled={submitting} className="inline-flex items-center gap-2 rounded-md bg-black px-4 py-2 text-sm text-white hover:bg-gray-800 disabled:opacity-50 dark:bg-white dark:text-black dark:hover:bg-gray-200">
{submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : <CloudDownload className="h-4 w-4" />}
{submitting ? t('正在添加...') : t('添加并下载')}
</button>
</div>
</div>
</div>
)
}
@@ -218,8 +473,10 @@ function ImageTable({
onCancelDownload,
onDelete,
onToggle,
onRemoveCustom,
storageReady,
storageLoading,
headerAction,
}: {
title: string
images: ImageInfo[]
@@ -230,17 +487,22 @@ function ImageTable({
onCancelDownload: (id: string) => void
onDelete: (id: string) => void
onToggle: (id: string, enabled: boolean) => void
onRemoveCustom: (id: string) => void
storageReady: boolean
storageLoading: boolean
headerAction?: ReactNode
}) {
return (
<div className="space-y-3">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-3">
<h2 className="text-lg font-semibold text-gray-800">{title}</h2>
<h2 className="text-lg font-semibold text-gray-800 dark:text-gray-100">{title}</h2>
<span className="text-xs text-gray-400">
{downloadedCount}/{totalCount}
</span>
</div>
{headerAction}
</div>
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full">
@@ -274,10 +536,11 @@ function ImageTable({
<td className="px-4 py-3">
<div className="flex items-center gap-3">
<span className="w-8 h-8 flex items-center justify-center flex-shrink-0">
{getTemplateIcon(img.id)}
{getTemplateIcon(img.id, img.distro, img.custom)}
</span>
<div>
<span className="font-medium text-gray-900 text-sm">{img.name}</span>
<span className="font-medium text-gray-900 text-sm dark:text-gray-100">{img.name}</span>
{img.custom && <span className="ml-2 rounded bg-blue-50 px-1.5 py-0.5 text-[10px] font-medium text-blue-700 dark:bg-blue-950 dark:text-blue-300"></span>}
<p className="text-[11px] text-gray-400">{img.description}</p>
</div>
@@ -350,6 +613,16 @@ function ImageTable({
</button>
</>
)}
{img.custom && !img.downloading && (
<button
onClick={() => onRemoveCustom(img.id)}
disabled={isBusy}
className="inline-flex items-center rounded-md border border-gray-200 p-1.5 text-gray-500 hover:border-red-200 hover:bg-red-50 hover:text-red-600 disabled:opacity-50 dark:border-gray-700 dark:text-gray-400 dark:hover:border-red-900 dark:hover:bg-red-950 dark:hover:text-red-300"
title="移除第三方镜像源和缓存"
>
<Unlink className="h-3.5 w-3.5" />
</button>
)}
</div>
</td>
</tr>
@@ -425,6 +698,7 @@ function StatusBadge({ img }: { img: ImageInfo }) {
function downloadStatusLabel(img: ImageInfo) {
if (img.stage === 'canceling') return '取消中'
if (img.stage === 'converting') return '转换中'
if (img.stage === 'validating') return '校验中'
if (img.stage === 'lxc-create') return '下载中'
if (img.progress > 0) return `下载中 ${Math.min(100, img.progress)}%`
if (img.downloaded_bytes > 0) return `下载中 · ${formatSize(img.downloaded_bytes)}`
@@ -444,8 +718,9 @@ function isWindowsImage(img: ImageInfo) {
return img.distro === 'windows' || img.id.toLowerCase().includes('windows')
}
function getTemplateIcon(id: string): ReactNode {
function getTemplateIcon(id: string, distro = '', custom = false): ReactNode {
const size = 'w-5 h-5'
id = (custom && distro ? distro : id).toLowerCase()
id = id.startsWith('kvm-') ? id.slice(4) : id
if (id.startsWith('debian')) return <svg className={size} viewBox="0 0 1024 1024"><path d="M935.473 375.359a558.602 558.602 0 0 0-22.351-114.655l13.308 4.436c-35.66-81.385-90.086-163.623-153.556-199.282-8.701-5.118-35.147 4.948-26.616-12.113s-37.536-8.19-56.816-4.778c-26.275 4.266-30.028-29.175-75.071-35.83-25.593-3.582-32.247 18.427-44.702 13.309-23.545-9.384-20.816-27.64-57.669-9.384-18.427 9.042 11.602-26.105-49.138-4.607L457.744 0C349.23 41.63 318.69 76.266 288.15 79.337c-6.996 0-34.124 32.759-53.574 53.062-17.062 17.062-26.275 36.512-49.138 39.583l-17.062 70.636A136.494 136.494 0 0 0 119.41 339.7a66.711 66.711 0 0 1 4.436-52.892c-17.062 6.825-45.896 17.062-29.687 96.91 12.796 63.13-5.29 135.13 10.066 204.742 4.777 20.986 0 40.095 6.142 51.185 107.66 235.794 208.836 392.08 472.44 384.06l4.436-8.872c-28.152-6.825-55.11-17.062-111.584-30.711-18.597-4.436-23.033-34.124-40.265-44.19-9.384-5.46-28.323-4.095-37.195-9.896s4.266-21.668-19.962-14.332c-8.531 2.56-13.82-10.92-20.133-17.061s0-23.716-23.375-24.74-18.426-29.687-19.791-44.702c-12.114 1.536-1.195-1.535-13.308 4.436a63.64 63.64 0 0 1-23.887-31.735c-10.237-48.967-10.578-21.497-15.014-32.417a322.297 322.297 0 0 0-19.28-42.142l26.787 8.872h4.436l4.436-13.309-26.616-8.701h31.223c-7.678 13.99 2.047 5.29-13.479 8.872v13.308l22.35-8.872v-13.308c-20.644-10.237-28.663-13.308-49.137-22.01l9.043 8.872v4.436h-49.138c-22.01-14.843-13.99-31.734-17.915-53.062 17.062 0 9.213 6.655 17.062-13.137l-17.062 8.872 13.308-33.953-13.308 13.138c-29.176-38.73-16.209-97.764-11.943-152.02A180.684 180.684 0 0 1 211.2 372.97c8.872-10.067 5.119-25.251 5.46-37.195l31.223-26.445H265.8c7.678 17.061 4.777 5.46 0 22.01l8.872 4.435c7.166-8.701 6.142-5.971 8.872-22.01-10.066-10.578-6.995-9.895-26.616-13.308A119.432 119.432 0 0 1 368.51 243.13l4.436-13.308-17.915 9.043-4.436-13.138a109.536 109.536 0 0 1 76.095-27.128c6.313 0 6.996-17.062 12.797-19.45 161.574-60.57 309.33 9.383 371.093 147.413a324.173 324.173 0 0 1 8.19 34.123c17.061 56.987-7.167 121.48 9.725 155.604-7.849 36-36.683 13.82-40.266 30.881-8.531 41.29-14.844 59.717-40.778 78.826a196.38 196.38 0 0 1-30.711 22.35 84.285 84.285 0 0 0 22.35-39.753c-106.294 111.584-262.58 63.981-290.049-105.954a101.176 101.176 0 0 1 35.147-93.157c92.987-87.527 150.144-52.38 205.765-20.474l-8.872-30.711c-32.93-24.398-17.062-19.792-9.043-57.328v-4.436l-17.915-13.137c2.56 10.066 1.024 5.289 9.043 17.061-4.436 16.039 0 9.043-8.872 17.062-15.014 9.725-23.716 7.337-44.702 4.436l4.436-13.308-13.308-13.308c0 11.773-4.095 2.73 0 17.062-126.086 9.896-218.05 80.02-178.636 260.191a220.608 220.608 0 0 0 8.872 44.19l-8.872 8.702-4.436-26.446h-13.48l-4.435 13.308c-12.626-25.763-0.853 10.75 40.265 52.892a149.29 149.29 0 0 0 12.797 12.625c47.773 34.124 113.29 81.385 201.328 49.138h9.043v-4.436l-102.37-13.308-4.436-8.701c106.806 24.74 176.93-8.531 236.646-48.456 13.138-17.062 11.431-24.057 22.18-9.043 19.28-17.061 3.925-26.786 13.48-44.019 6.483-11.772 32.587-17.062 44.7-35.318l40.096-136.494h-17.062c3.071-14.332 22.522-34.123-4.436-48.455-2.559-1.536 9.043-1.365 8.872-4.266a145.537 145.537 0 0 0-22.18-66.37c33.1 21.669 36.342 68.247 53.574 105.783v8.872h4.436V375.36zM453.308 595.455l-9.555-26.446 62.446 57.328zM146.196 211.736l-23.204-4.436v39.754c16.72-10.578 18.939-10.407 22.35-35.318z m574.981 176.419a57.498 57.498 0 0 0-17.062 44.19l13.48 8.701a37.877 37.877 0 0 0 4.435-52.891zM868.42 555.872c26.275-11.602 54.598-58.01 35.83-97.081l-35.83 96.91z m-174.03-79.508c-15.697 11.773-19.791 13.308-22.35 39.754l13.307 8.872 17.915-8.872a60.228 60.228 0 0 0 4.436-48.455c-8.36 13.478-2.559 20.644-13.308 8.701z m-67.053 79.508c15.868-10.92 11.944-14.844 17.915-22.18v-4.778a292.097 292.097 0 0 1-62.446 0c-13.137-13.99-13.308-29.346-31.223-39.583 17.062 35.147 3.242 38.218 31.223 61.764a158.162 158.162 0 0 0 40.095 4.436c1.536 0-6.824-1.024 4.436 0zM207.79 520.554H194.31l-8.872 8.702c9.555 10.237 5.46 7.166 13.308-4.436L212.225 547l4.436-17.062-8.872-8.701z m17.062 57.328l4.436-8.873c-10.067-8.701 0-3.583-13.308 0l-13.309-17.061 4.436 17.061v8.873h17.062z" fill="#CE0C48"/></svg>
if (id.startsWith('ubuntu')) return <svg className={size} viewBox="0 0 1024 1024"><circle cx="512" cy="512" r="511" fill="#DD4814"/><path d="M164.532 442.532c-37.676 0-68.2 30.524-68.2 68.2 0 37.656 30.524 68.184 68.2 68.184 37.66 0 68.184-30.528 68.184-68.184 0-37.676-30.524-68.2-68.184-68.2z m486.86 309.912c-32.612 18.84-43.8 60.52-24.96 93.116 18.82 32.616 60.5 43.796 93.116 24.96 32.612-18.82 43.796-60.5 24.96-93.12-18.82-32.592-60.524-43.772-93.116-24.956z m-338.744-241.712c0-67.384 33.472-126.92 84.684-162.968L347.48 264.268c-59.656 39.88-104.048 100.816-122.496 172.188 21.528 17.56 35.304 44.3 35.304 74.272 0 29.956-13.776 56.696-35.304 74.26C243.408 656.376 287.8 717.32 347.48 757.2l49.852-83.52c-51.212-36.028-84.684-95.56-84.684-162.948z m199.168-199.188c104.052 0 189.42 79.776 198.38 181.52l97.16-1.432c-4.776-75.112-37.592-142.544-88.008-192.128-25.928 9.796-55.88 8.296-81.76-6.624-25.932-14.964-42.192-40.208-46.636-67.608a297.04 297.04 0 0 0-79.14-10.76 295.148 295.148 0 0 0-131.276 30.652l47.38 84.908a198.384 198.384 0 0 1 83.9-18.528z m0 398.36a198.404 198.404 0 0 1-83.896-18.528l-47.38 84.9a294.848 294.848 0 0 0 131.28 30.684 296.16 296.16 0 0 0 79.136-10.788c4.444-27.4 20.708-52.62 46.632-67.608 25.904-14.948 55.836-16.42 81.76-6.624 50.42-49.584 83.232-117.016 88.016-192.128l-97.188-1.432c-8.94 101.772-94.304 181.52-198.36 181.52z m139.552-440.924c32.616 18.832 74.3 7.68 93.116-24.936 18.84-32.616 7.68-74.3-24.936-93.14-32.616-18.816-74.296-7.64-93.14 24.976-18.812 32.6-7.632 74.28 24.96 93.1z" fill="#FFF"/></svg>
@@ -455,6 +730,7 @@ function getTemplateIcon(id: string): ReactNode {
if (id.startsWith('fedora')) return <svg className={size} viewBox="0 0 1024 1024"><path d="M512 0C229.344 0 0.224 229.024 0 511.648V907.84a116.384 116.384 0 0 0 116.384 116.128h395.808c282.656-0.128 511.776-229.28 511.776-512 0-282.752-229.248-512-512-512z m196.064 237.952c-16.16 0-22.016-3.104-45.728-3.104a126.848 126.848 0 0 0-126.848 126.624v110.208c0 9.888 8.032 17.92 17.92 17.92h83.328c31.072 0 56.16 24.736 56.16 55.904 0 31.328-25.344 55.968-56.736 55.968h-100.608v127.36a240.32 240.32 0 0 1-240.288 240.288h-1.248a190.944 190.944 0 0 1-53.216-7.52l1.344 0.32c-27.168-7.072-49.376-29.408-49.376-55.296 0-31.328 22.752-54.112 56.736-54.112 16.128 0 22.016 3.072 45.696 3.072a126.848 126.848 0 0 0 126.848-126.624v-110.208a17.92 17.92 0 0 0-17.92-17.888h-83.328a55.808 55.808 0 0 1-56.096-55.904c0-31.328 25.344-55.968 56.736-55.968h100.576v-127.36a240.32 240.32 0 0 1 240.288-240.288c20.128 0 34.432 2.272 53.088 7.136 27.168 7.136 49.408 29.44 49.408 55.296 0 31.36-22.752 54.144-56.736 54.144z" fill="#294172"/></svg>
if (id.startsWith('rockylinux')) return <svg className={size} viewBox="0 0 1024 1024"><path d="M995.498667 680.362667c18.474667-52.778667 28.501333-109.568 28.501333-168.704C1024 229.077333 794.752 0 512 0S0 229.077333 0 511.658667c0 139.818667 56.106667 266.496 147.114667 358.826666L666.453333 351.530667l128.213334 128.170666 200.832 200.704z m-93.525334 162.816l-235.52-235.349334-368.896 368.597334A510.506667 510.506667 0 0 0 512 1023.274667c156.16 0 296.106667-69.888 389.973333-180.053334h0.042667z" fill="#10B981"/></svg>
if (id.startsWith('windows')) return <svg className={size} viewBox="0 0 1024 1024"><path d="M56.888889 227.555556l398.222222-70.542223V512H56.888889V227.555556z m0 625.777777l398.222222 70.542223V568.888889H56.888889v284.444444zM512 147.342222L1024 56.888889v455.111111H512V147.342222z m0 786.204445L1024 1024v-455.111111H512v364.657778z" fill="#16C6FE"/></svg>
if (custom) return <CloudDownload className={`${size} text-blue-600 dark:text-blue-300`} />
return null
}
+11 -7
View File
@@ -40,8 +40,12 @@ export default function Login() {
await login(username, password)
}
} catch (err: unknown) {
const error = err as { response?: { data?: { message?: string } } }
const error = err as { response?: { status?: number; data?: { message?: string } } }
if (error.response?.status === 401) {
setError(t(isAccessCodeLogin ? '访问码或密码错误' : '用户名或密码错误'))
} else {
setError(error.response?.data?.message || t('登录失败,请检查用户名和密码'))
}
} finally {
setLoading(false)
}
@@ -79,7 +83,7 @@ export default function Login() {
{!isAccessCodeLogin && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1.5">
{t('用户名')}
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
@@ -90,7 +94,7 @@ export default function Login() {
value={username}
onChange={(event) => setUsername(event.target.value)}
className="block w-full pl-10 pr-3 py-2.5 border border-gray-300 rounded-md text-black bg-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-black focus:border-black text-sm"
placeholder="输入用户名"
placeholder={t('输入用户名')}
required
autoComplete="username"
/>
@@ -100,7 +104,7 @@ export default function Login() {
<div>
<label className="block text-sm font-medium text-gray-700 mb-1.5">
{t('密码')}
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
@@ -111,7 +115,7 @@ export default function Login() {
value={password}
onChange={(event) => setPassword(event.target.value)}
className="block w-full pl-10 pr-3 py-2.5 border border-gray-300 rounded-md text-black bg-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-black focus:border-black text-sm"
placeholder="输入密码"
placeholder={t('输入密码')}
required
autoComplete="current-password"
/>
@@ -123,12 +127,12 @@ export default function Login() {
disabled={loading}
className="w-full bg-black text-white py-2.5 rounded-md hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed text-sm font-medium"
>
{loading ? '登录中...' : '登录'}
{loading ? t('登录中...') : t('登录')}
</button>
</form>
</div>
<p className="text-center text-xs text-gray-400 mt-6">CLICD v1.1.27</p>
<p className="text-center text-xs text-gray-400 mt-6">CLICD v1.1.28</p>
</div>
</div>
)
+6 -2
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { Globe2, Network, Pencil, Plus, RefreshCw, Router, Save, Search, Server, Trash2, X } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { useNavigate } from 'react-router'
import { useLanguage, type Language } from '../contexts/LanguageContext'
import {
getRoutingInfo,
@@ -62,6 +62,7 @@ export default function Routing() {
const ipv6Prefixes = routing?.ipv6_prefixes || []
const ipv6Assignments = routing?.ipv6_assignments || []
const nat4Range = routing?.nat4_port_range || { start: 20000, end: 65535 }
const nat4Networks = routing?.nat4_networks
const defaultIPv4Interface = routing?.host_public_ipv4?.interface || publicIPv4s[0]?.interface || 'eth0'
const defaultIPv4Gateway = routing?.host_public_ipv4?.gateway || publicIPv4s[0]?.gateway || ''
const defaultIPv4PrefixLen = routing?.host_public_ipv4?.prefix_len || publicIPv4s[0]?.prefix_len || 32
@@ -287,7 +288,10 @@ export default function Routing() {
used={routing?.nat4.used || 0}
label={text.remainingTotal}
usedLabel={text.used}
detail={formatNATRange(nat4Range, language)}
detail={[
formatNATRange(nat4Range, language),
nat4Networks ? `LXC ${nat4Networks.lxc.subnet} · KVM ${nat4Networks.kvm.subnet}` : '',
].filter(Boolean).join(' · ')}
action={
<button onClick={startEditNAT4} className="rounded p-1.5 text-gray-500 hover:bg-gray-100 hover:text-black" title={text.editNAT4Range}>
<Pencil className="h-4 w-4" />
+178 -4
View File
@@ -1,17 +1,20 @@
import { Dispatch, SetStateAction, useCallback, useEffect, useState } from 'react'
import { Clock, Globe, ListTodo, Lock, LogIn, Minus, Monitor, Plus, RefreshCw, Save, ShieldCheck, Terminal, Upload, UserCog } from 'lucide-react'
import { Clock, Globe, ListTodo, Lock, LogIn, Minus, Monitor, Plus, RefreshCw, Save, Shield, ShieldCheck, Terminal, Upload, UserCog } from 'lucide-react'
import {
changePassword,
changeUsername,
getLoginLogs,
getPanelAccessPolicy,
getSSLSettings,
getTaskQueueSettings,
getWebSSHOriginSettings,
LoginLog,
PanelAccessPolicy,
SSLSettings,
TaskQueueSettings,
updateTaskQueueSettings,
updateSSLSettings,
updatePanelAccessPolicy,
updateWebSSHOriginSettings,
WebSSHOriginSettings,
} from '../services/api'
@@ -19,11 +22,12 @@ import { useDialog } from '../components/Dialog'
import { useAuth } from '../contexts/AuthContext'
import { useLanguage } from '../contexts/LanguageContext'
type SettingsSection = 'tasks' | 'account' | 'webssh' | 'ssl' | 'logs'
type SettingsSection = 'tasks' | 'account' | 'access' | 'webssh' | 'ssl' | 'logs'
const settingsSections = [
{ id: 'tasks', label: '任务队列', icon: ListTodo },
{ id: 'account', label: '账号设置', icon: UserCog },
{ id: 'access', label: '访问来源', icon: Shield },
{ id: 'webssh', label: 'WebSSH 访问', icon: Terminal },
{ id: 'ssl', label: 'SSL 证书', icon: ShieldCheck },
{ id: 'logs', label: '登录日志', icon: LogIn },
@@ -57,6 +61,11 @@ export default function Settings() {
const [taskQueue, setTaskQueue] = useState<TaskQueueSettings | null>(null)
const [taskConcurrency, setTaskConcurrency] = useState(2)
const [savingTaskQueue, setSavingTaskQueue] = useState(false)
const [accessPolicy, setAccessPolicy] = useState<PanelAccessPolicy | null>(null)
const [accessEnabled, setAccessEnabled] = useState(false)
const [allowedSourcesText, setAllowedSourcesText] = useState('')
const [trustedProxiesText, setTrustedProxiesText] = useState('')
const [savingAccessPolicy, setSavingAccessPolicy] = useState(false)
const [activeSection, setActiveSection] = useState<SettingsSection>('tasks')
const fetchLogs = useCallback(async () => {
@@ -109,18 +118,33 @@ export default function Settings() {
}
}, [])
const fetchAccessPolicy = useCallback(async () => {
try {
const res = await getPanelAccessPolicy()
const data = res.data.data
if (!data) return
setAccessPolicy(data)
setAccessEnabled(data.enabled)
setAllowedSourcesText((data.allowed_sources || []).join('\n'))
setTrustedProxiesText((data.trusted_proxies || []).join('\n'))
} catch (err) {
console.error(err)
}
}, [])
useEffect(() => {
fetchLogs()
fetchSSL()
fetchWebSSHOrigins()
fetchTaskQueue()
fetchAccessPolicy()
const logTimer = setInterval(fetchLogs, 15000)
const taskTimer = setInterval(fetchTaskQueue, 5000)
return () => {
clearInterval(logTimer)
clearInterval(taskTimer)
}
}, [fetchLogs, fetchSSL, fetchTaskQueue, fetchWebSSHOrigins])
}, [fetchAccessPolicy, fetchLogs, fetchSSL, fetchTaskQueue, fetchWebSSHOrigins])
const handleSaveTaskQueue = async () => {
const concurrency = Math.max(1, Math.min(16, Math.round(taskConcurrency || 1)))
@@ -194,6 +218,38 @@ export default function Settings() {
}
}
const handleAccessEnabledChange = (enabled: boolean) => {
setAccessEnabled(enabled)
if (enabled && !allowedSourcesText.trim() && accessPolicy?.current_source) {
setAllowedSourcesText(accessPolicy.current_source)
}
}
const handleSaveAccessPolicy = async () => {
const splitEntries = (value: string) => value.split(/[\s,;]+/).map(item => item.trim()).filter(Boolean)
setSavingAccessPolicy(true)
try {
const res = await updatePanelAccessPolicy({
enabled: accessEnabled,
allowed_sources: splitEntries(allowedSourcesText),
trusted_proxies: splitEntries(trustedProxiesText),
})
const data = res.data.data
if (data) {
setAccessPolicy(data)
setAccessEnabled(data.enabled)
setAllowedSourcesText((data.allowed_sources || []).join('\n'))
setTrustedProxiesText((data.trusted_proxies || []).join('\n'))
}
dialog.alert('完成', accessEnabled ? '面板访问来源策略已保存并立即生效' : '面板访问来源限制已关闭')
} catch (err: unknown) {
const e = err as { response?: { data?: { message?: string } } }
dialog.alert('失败', e.response?.data?.message || '面板访问来源策略保存失败')
} finally {
setSavingAccessPolicy(false)
}
}
const handleSaveAccount = async () => {
if (!oldPwd) {
dialog.alert('提示', '请输入当前密码以确认修改')
@@ -248,7 +304,7 @@ export default function Settings() {
<div className="space-y-5">
<div>
<h1 className="text-2xl font-bold text-black dark:text-white"></h1>
<p className="mt-1 text-sm text-gray-500 dark:text-gray-400">访</p>
<p className="mt-1 text-sm text-gray-500 dark:text-gray-400">访访</p>
</div>
<div className="grid items-start gap-4 lg:grid-cols-[210px_minmax(0,1fr)]">
@@ -324,6 +380,21 @@ export default function Settings() {
/>
)}
{activeSection === 'access' && (
<PanelAccessPolicyCard
policy={accessPolicy}
enabled={accessEnabled}
allowedSourcesText={allowedSourcesText}
trustedProxiesText={trustedProxiesText}
saving={savingAccessPolicy}
onEnabledChange={handleAccessEnabledChange}
onAllowedSourcesTextChange={setAllowedSourcesText}
onTrustedProxiesTextChange={setTrustedProxiesText}
onRefresh={fetchAccessPolicy}
onSave={handleSaveAccessPolicy}
/>
)}
{activeSection === 'ssl' && (
<SSLCard
ssl={ssl}
@@ -365,6 +436,109 @@ interface TaskQueueCardProps {
onSave: () => void
}
interface PanelAccessPolicyCardProps {
policy: PanelAccessPolicy | null
enabled: boolean
allowedSourcesText: string
trustedProxiesText: string
saving: boolean
onEnabledChange: (enabled: boolean) => void
onAllowedSourcesTextChange: (value: string) => void
onTrustedProxiesTextChange: (value: string) => void
onRefresh: () => void
onSave: () => void
}
function PanelAccessPolicyCard(props: PanelAccessPolicyCardProps) {
return (
<div className="rounded-lg border border-gray-200 bg-white p-5 dark:border-gray-700 dark:bg-gray-900">
<div className="mb-4 flex items-center justify-between gap-3">
<div>
<h2 className="flex items-center gap-2 text-sm font-semibold text-black dark:text-white">
<Shield className="h-4 w-4" />访
</h2>
<p className="mt-1 text-xs text-gray-500 dark:text-gray-400">访 API </p>
</div>
<button type="button" onClick={props.onRefresh} className="rounded-md border border-gray-200 p-1.5 text-gray-500 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800" title="刷新">
<RefreshCw className="h-4 w-4" />
</button>
</div>
<div className="flex items-center justify-between gap-4 border-y border-gray-100 py-3 dark:border-gray-800">
<div>
<div className="text-sm font-medium text-gray-800 dark:text-gray-200">访</div>
<div className="mt-0.5 text-xs text-gray-500 dark:text-gray-400">访</div>
</div>
<button
type="button"
role="switch"
aria-checked={props.enabled}
onClick={() => props.onEnabledChange(!props.enabled)}
className={`access-policy-switch relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full border transition-colors focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2 dark:focus:ring-white dark:focus:ring-offset-gray-900 ${
props.enabled
? 'border-black bg-black dark:border-white dark:bg-white'
: 'border-gray-300 bg-gray-300 dark:border-gray-600 dark:bg-gray-700'
}`}
title={props.enabled ? '关闭访问白名单' : '启用访问白名单'}
>
<span
aria-hidden="true"
className={`access-policy-switch-thumb pointer-events-none absolute left-0.5 top-0.5 h-5 w-5 rounded-full shadow-sm ring-1 ring-black/5 transition-[transform,background-color] duration-200 ${
props.enabled
? 'translate-x-5 bg-white dark:bg-gray-900'
: 'translate-x-0 bg-white dark:bg-gray-200'
}`}
/>
</button>
</div>
<div className="mt-4 grid gap-4 lg:grid-cols-2">
<div>
<label className="mb-1.5 block text-xs font-medium text-gray-600 dark:text-gray-300"> IP / CIDR</label>
<textarea
value={props.allowedSourcesText}
onChange={(event) => props.onAllowedSourcesTextChange(event.target.value)}
rows={6}
disabled={!props.enabled}
className="w-full rounded-md border border-gray-300 bg-white px-3 py-2 font-mono text-xs text-black outline-none focus:border-black focus:ring-1 focus:ring-black disabled:bg-gray-50 disabled:text-gray-400 dark:border-gray-700 dark:bg-gray-950 dark:text-white dark:focus:border-white dark:focus:ring-white dark:disabled:bg-gray-800 dark:disabled:text-gray-500"
placeholder={'203.0.113.10\n192.168.1.0/24\n2001:db8::/32'}
/>
</div>
<div>
<label className="mb-1.5 block text-xs font-medium text-gray-600 dark:text-gray-300"> IP / CIDR</label>
<textarea
value={props.trustedProxiesText}
onChange={(event) => props.onTrustedProxiesTextChange(event.target.value)}
rows={6}
disabled={!props.enabled}
className="w-full rounded-md border border-gray-300 bg-white px-3 py-2 font-mono text-xs text-black outline-none focus:border-black focus:ring-1 focus:ring-black disabled:bg-gray-50 disabled:text-gray-400 dark:border-gray-700 dark:bg-gray-950 dark:text-white dark:focus:border-white dark:focus:ring-white dark:disabled:bg-gray-800 dark:disabled:text-gray-500"
placeholder={'127.0.0.1\n10.0.0.0/8'}
/>
<p className="mt-1.5 text-xs text-gray-500 dark:text-gray-400">使</p>
</div>
</div>
<div className="mt-4 grid gap-2 rounded-md border border-gray-100 bg-gray-50 p-3 text-xs dark:border-gray-800 dark:bg-gray-950 sm:grid-cols-2">
<div>
<span className="text-gray-500 dark:text-gray-400"></span>
<div className="mt-0.5 break-all font-mono text-gray-800 dark:text-gray-200">{props.policy?.current_source || '-'}</div>
</div>
<div>
<span className="text-gray-500 dark:text-gray-400"></span>
<div className="mt-0.5 break-all font-mono text-gray-800 dark:text-gray-200">{props.policy?.direct_source || '-'}</div>
</div>
</div>
<div className="mt-4 flex justify-end">
<button type="button" onClick={props.onSave} disabled={props.saving} className="inline-flex items-center justify-center gap-2 rounded-md bg-black px-4 py-2 text-sm text-white hover:bg-gray-800 disabled:opacity-50 dark:bg-white dark:text-black dark:hover:bg-gray-200">
<Save className="h-4 w-4" />
{props.saving ? '保存中...' : '保存访问策略'}
</button>
</div>
</div>
)
}
function TaskQueueCard(props: TaskQueueCardProps) {
const setBounded = (value: number) => props.onConcurrencyChange(Math.max(1, Math.min(16, value)))
return (
+1 -1
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useState } from 'react'
import { Camera, RefreshCw, Server, Trash2 } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { useNavigate } from 'react-router'
import { deleteContainerSnapshot, getSnapshots, Snapshot } from '../services/api'
import { useDialog } from '../components/Dialog'
+42 -38
View File
@@ -136,13 +136,13 @@ export default function Storage() {
}
return (
<div className="space-y-5">
<div className="flex items-center justify-between gap-4">
<div className="min-w-0 space-y-5">
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl font-bold text-black dark:text-white">{t('存储管理')}</h1>
<p className="mt-1 text-sm text-gray-500 dark:text-gray-400">{t('只显示已挂载磁盘;勾选后,对应功能可以选择该磁盘保存数据。')}</p>
</div>
<div className="flex gap-2">
<div className="flex shrink-0 gap-2">
<button onClick={fetchData} className="inline-flex items-center gap-2 rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50">
<RefreshCw className="h-4 w-4" />{t('刷新')}
</button>
@@ -169,53 +169,57 @@ export default function Storage() {
</div>
)}
<div className="overflow-x-auto rounded-lg border border-gray-200 bg-white">
<table className="w-full min-w-[1240px] text-sm">
<thead className="border-b border-gray-200 bg-gray-50 text-xs text-gray-500">
<tr>
<th className="px-4 py-3 text-left font-medium">{t('磁盘')}</th>
<th className="px-4 py-3 text-left font-medium">{t('空间分布')}</th>
<th className="px-4 py-3 text-left font-medium">{t('用于存储')}</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
<div className="overflow-hidden rounded-lg border border-gray-200 bg-white text-sm">
<div className="hidden grid-cols-[minmax(170px,0.65fr)_minmax(320px,1.2fr)_minmax(480px,1.8fr)] gap-4 border-b border-gray-200 bg-gray-50 px-4 py-3 text-xs text-gray-500 2xl:grid">
<div className="font-medium">{t('磁盘')}</div>
<div className="font-medium">{t('空间分布')}</div>
<div className="font-medium">{t('用于存储')}</div>
</div>
{mountedDisks.length === 0 ? (
<tr><td colSpan={3} className="px-4 py-10 text-center text-gray-400">{t('未检测到已挂载磁盘')}</td></tr>
) : mountedDisks.map((disk) => {
<div className="px-4 py-10 text-center text-gray-400">{t('未检测到已挂载磁盘')}</div>
) : (
<div className="divide-y divide-gray-100">
{mountedDisks.map((disk) => {
const pool = pools.find((item) => poolForDisk(item, disk))
const contentUsage = contentUsageMap(pool?.content_usage || disk.content_usage || [])
const clicdUsed = pool?.clicd_used_bytes || disk.clicd_used_bytes || 0
return (
<tr key={`${disk.path}-${disk.mount_point}`} className="align-top hover:bg-gray-50/70">
<td className="px-4 py-4">
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-9 w-9 items-center justify-center rounded-md bg-gray-100 text-gray-600">
<section
key={`${disk.path}-${disk.mount_point}`}
className="grid min-w-0 grid-cols-1 gap-4 px-4 py-4 hover:bg-gray-50/70 2xl:grid-cols-[minmax(170px,0.65fr)_minmax(320px,1.2fr)_minmax(480px,1.8fr)]"
>
<div className="min-w-0">
<div className="mb-2 text-xs font-medium text-gray-500 2xl:hidden">{t('磁盘')}</div>
<div className="flex min-w-0 items-start gap-3">
<div className="mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-gray-100 text-gray-600">
<HardDrive className="h-5 w-5" />
</div>
<div>
<div className="font-mono text-xs font-medium text-gray-900">{disk.path || disk.name}</div>
<div className="mt-1 text-xs text-gray-500">{disk.model || disk.fstype || disk.type || '-'}</div>
<div className="mt-1 font-mono text-xs text-gray-400">{disk.mount_point}</div>
<div className="min-w-0">
<div className="truncate font-mono text-xs font-medium text-gray-900" title={disk.path || disk.name}>{disk.path || disk.name}</div>
<div className="mt-1 truncate text-xs text-gray-500" title={disk.model || disk.fstype || disk.type || '-'}>{disk.model || disk.fstype || disk.type || '-'}</div>
<div className="mt-1 truncate font-mono text-xs text-gray-400" title={disk.mount_point}>{disk.mount_point}</div>
</div>
</div>
</td>
<td className="px-4 py-4">
</div>
<div className="min-w-0">
<div className="mb-2 text-xs font-medium text-gray-500 2xl:hidden">{t('空间分布')}</div>
<DiskUsageBar disk={disk} contentUsage={contentUsage} clicdUsed={clicdUsed} />
</td>
<td className="px-4 py-4">
<div className="flex min-w-[620px] flex-nowrap items-start gap-2">
</div>
<div className="min-w-0">
<div className="mb-2 text-xs font-medium text-gray-500 2xl:hidden">{t('用于存储')}</div>
<div className="grid min-w-0 grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-5">
{contentOptions.map(([value, label]) => {
const checked = (pool?.content_types || []).includes(value)
const isDefault = (pool?.default_contents || []).includes(value)
return (
<div key={value} className={`w-[116px] shrink-0 rounded-md border px-2.5 py-2 ${checked ? 'border-gray-300 bg-white' : 'border-gray-200 bg-gray-50'}`}>
<div key={value} className={`min-w-0 rounded-md border px-2.5 py-2 ${checked ? 'border-gray-300 bg-white' : 'border-gray-200 bg-gray-50'}`}>
<label className="flex cursor-pointer items-center gap-2 text-xs text-gray-700">
<input type="checkbox" checked={checked} onChange={() => toggleContent(disk, value)} />
{t(label)}
<input className="shrink-0" type="checkbox" checked={checked} onChange={() => toggleContent(disk, value)} />
<span className="truncate" title={t(label)}>{t(label)}</span>
</label>
{checked && (
<div className="mt-1.5 flex items-center justify-between gap-2 border-t border-gray-100 pt-1.5">
<span className="text-[11px] text-gray-500">{t('默认盘')}</span>
<span className="truncate text-[11px] text-gray-500">{t('默认盘')}</span>
<button
type="button"
role="switch"
@@ -232,12 +236,12 @@ export default function Storage() {
)
})}
</div>
</td>
</tr>
</div>
</section>
)
})}
</tbody>
</table>
</div>
)}
</div>
</div>
)
@@ -279,8 +283,8 @@ function DiskUsageBar({
].filter((segment) => segment.size > 0)
return (
<div className="min-w-[420px] max-w-[620px]">
<div className="flex items-center justify-between gap-4 text-xs text-gray-600">
<div className="w-full min-w-0">
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1 text-xs text-gray-600">
<span>{t('已用')} {formatBytes(used)} / {formatBytes(total)}</span>
<span>{usagePct(used, total).toFixed(1)}% · {t('可用')} {formatBytes(free)}</span>
</div>
+62 -1
View File
@@ -21,11 +21,16 @@ api.interceptors.request.use((config) => {
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
const requestURL = String(error.config?.url || '')
const isLoginRequest = ['/login', '/sub-user/login', '/sub-user/access']
.some((path) => requestURL === path || requestURL.endsWith(path))
if (error.response?.status === 401 && !isLoginRequest) {
localStorage.removeItem('clicd_token')
localStorage.removeItem('clicd_username')
if (window.location.pathname !== '/login') {
window.location.href = '/login'
}
}
return Promise.reject(error)
}
)
@@ -548,6 +553,21 @@ export const getWebSSHOriginSettings = () =>
export const updateWebSSHOriginSettings = (origins: string[]) =>
api.put<APIResponse<WebSSHOriginSettings>>('/webssh-origins', { origins })
export interface PanelAccessPolicy {
enabled: boolean
allowed_sources: string[]
trusted_proxies: string[]
current_source: string
direct_source: string
using_forwarded: boolean
}
export const getPanelAccessPolicy = () =>
api.get<APIResponse<PanelAccessPolicy>>('/access-policy')
export const updatePanelAccessPolicy = (data: Pick<PanelAccessPolicy, 'enabled' | 'allowed_sources' | 'trusted_proxies'>) =>
api.put<APIResponse<PanelAccessPolicy>>('/access-policy', data)
// Containers
export const getContainers = () =>
api.get<APIResponse<Container[]>>('/containers')
@@ -717,6 +737,11 @@ export interface IPv6Route {
export interface RoutingInfo {
nat4: RouteCapacity
nat4_port_range: NAT4PortRange
nat4_next_port: number
nat4_networks: {
lxc: NATNetworkInfo
kvm: NATNetworkInfo
}
ipv4: RouteCapacity
lan_dhcp: RouteCapacity
ipv6: RouteCapacity
@@ -774,11 +799,37 @@ export interface ImageInfo {
size_bytes: number
manual_path?: string
desktop?: string
provisioner?: string
custom?: boolean
sha256?: string
}
export interface CustomKVMImageInput {
type: 'lxc' | 'kvm'
name: string
description: string
distro: string
release: string
arch: string
url: string
provisioner?: 'linux-cloud-init' | 'windows-10' | 'windows-11' | 'lxc-rootfs'
sha256?: string
}
export interface CustomKVMImage extends CustomKVMImageInput {
id: string
created_at: string
}
export const getImages = () =>
api.get<APIResponse<ImageInfo[]>>('/images')
export const createCustomKVMImage = (payload: CustomKVMImageInput) =>
api.post<APIResponse<CustomKVMImage>>('/images/custom', payload)
export const removeCustomKVMImage = (id: string) =>
api.delete<APIResponse>('/images/custom', { data: { id } })
export const downloadImage = (templateId: string) =>
api.post<APIResponse>('/images/download', { template_id: templateId })
@@ -923,6 +974,16 @@ export interface SubUser {
created_at: string
}
export interface NATNetworkInfo {
subnet: string
gateway: string
netmask: string
dhcp_start: string
dhcp_end: string
dhcp_max: number
prefix_bits: number
}
export const createSubUser = (containerId: ContainerIdentifier) =>
api.post<APIResponse<SubUser>>('/sub-user/create', { container_name: String(containerId) })
+73
View File
@@ -138,6 +138,8 @@ const exact: Record<string, string> = {
'输入密码': 'Enter password',
'登录': 'Log in',
'登录中...': 'Logging in...',
'用户名或密码错误': 'Incorrect username or password',
'访问码或密码错误': 'Incorrect access code or password',
'登录失败,请检查用户名和密码': 'Login failed. Check your username and password.',
'Authentication required': 'Authentication required',
'Administrator permission required': 'Administrator permission required',
@@ -193,6 +195,33 @@ const exact: Record<string, string> = {
'请按红色提示修改 vCPU、内存或磁盘配置': 'Fix the vCPU, memory, or disk fields marked in red',
'创建失败': 'Create failed',
'创建新容器': 'Create New Container',
'创建步骤': 'Creation steps',
'基础信息': 'Basics',
'镜像选择': 'Image',
'网络配置': 'Network',
'预览清单': 'Review',
'基础信息有误': 'Invalid basic information',
'请填写有效且未被占用的容器名称': 'Enter a valid, available container name',
'KVM 磁盘': 'KVM Disk',
'请选择镜像': 'Select an image',
'请选择用于创建容器的系统镜像': 'Select the system image used to create the container',
'网络配置有误': 'Invalid network configuration',
'请至少启用一种网络连接方式': 'Enable at least one network connection mode',
'NAT 端口配置有误': 'Invalid NAT port configuration',
'自动分配': 'Auto assign',
'个端口': 'ports',
'局域网': 'LAN',
'未配置网络': 'No network configured',
'创建数量': 'Count',
'自动选择': 'Automatic',
'镜像与登录': 'Image and Login',
'镜像默认': 'Image default',
'自动生成密码': 'Auto-generated password',
'子用户可用镜像': 'Sub-user Images',
'主要网络': 'Primary Network',
'上一步': 'Back',
'下一步': 'Next',
'确认创建': 'Create',
'批量创建数量': 'Batch Count',
'虚拟化架构': 'Virtualization',
'LXC 容器': 'LXC Container',
@@ -407,7 +436,25 @@ const exact: Record<string, string> = {
'存储配置已保存': 'Storage settings saved',
'保存存储配置失败': 'Failed to save storage settings',
'任务队列、账号、安全证书与访问记录': 'Task queue, account, certificates, and access records',
'任务队列、账号、访问控制、安全证书与访问记录': 'Task queue, account, access control, certificates, and access records',
'设置分类': 'Settings categories',
'访问来源': 'Access Sources',
'访问来源策略': 'Access Source Policy',
'限制可访问面板、登录和 API 的来源地址': 'Restrict source addresses that can access the panel, login, and APIs',
'启用访问白名单': 'Enable Access Allowlist',
'关闭后不限制访问来源': 'No source restrictions when disabled',
'关闭访问白名单': 'Disable Access Allowlist',
'允许的 IP / CIDR': 'Allowed IP / CIDR',
'可信代理 IP / CIDR': 'Trusted Proxy IP / CIDR',
'仅可信代理可提供真实客户端地址;未使用反向代理时留空': 'Only trusted proxies may supply the real client address. Leave empty without a reverse proxy.',
'当前识别来源': 'Detected Source',
'直接连接来源': 'Direct Connection Source',
'保存访问策略': 'Save Access Policy',
'面板访问来源策略已保存并立即生效': 'Panel access source policy saved and applied immediately',
'面板访问来源限制已关闭': 'Panel access source restriction disabled',
'面板访问来源策略保存失败': 'Failed to save panel access source policy',
'面板访问来源策略': 'Panel Access Source Policy',
'更新面板访问来源策略': 'Update Panel Access Source Policy',
'WebSSH 访问': 'WebSSH Access',
'账号设置': 'Account Settings',
'当前用户名': 'Current Username',
@@ -668,6 +715,32 @@ const exact: Record<string, string> = {
'快照配额': 'Snapshot Quota',
'模板列表': 'Template List',
'镜像管理列表': 'Image Management List',
'第三方镜像': 'Third-party Image',
'下载第三方 KVM 镜像': 'Download Third-party KVM Image',
'下载第三方 LXC 镜像': 'Download Third-party LXC Image',
'支持 tar、tar.gz、tar.xz、tar.zst 格式的 Linux rootfs': 'Supports Linux rootfs archives in tar, tar.gz, tar.xz, and tar.zst formats',
'移除第三方镜像': 'Remove Third-party Image',
'第三方镜像已移除': 'Third-party image removed',
'移除第三方镜像失败': 'Failed to remove third-party image',
'第三方镜像已添加,下载任务已启动': 'Third-party image added and download started',
'镜像格式必须与所选无人值守安装模板匹配': 'The image format must match the selected unattended installation template',
'无人值守安装模板': 'Unattended Installation Template',
'镜像名称': 'Image Name',
'版本 / 代号': 'Version / Codename',
'镜像下载地址': 'Image Download URL',
'镜像来源、版本或用途': 'Image source, version, or purpose',
'用于校验下载文件完整性': 'Used to verify download integrity',
'添加并下载': 'Add and Download',
'正在添加...': 'Adding...',
'添加第三方镜像失败': 'Failed to add third-party image',
'添加第三方 KVM 镜像源': 'Add Third-party KVM Image Source',
'移除第三方 KVM 镜像源': 'Remove Third-party KVM Image Source',
'添加第三方 LXC/KVM 镜像源': 'Add Third-party LXC/KVM Image Source',
'移除第三方 LXC/KVM 镜像源': 'Remove Third-party LXC/KVM Image Source',
'请填写名称、发行版、版本和下载地址': 'Enter the name, distribution, version, and download URL',
'SHA-256 必须是 64 位十六进制字符串': 'SHA-256 must be a 64-character hexadecimal string',
'安装 ISO': 'Installation ISO',
'校验中': 'Validating',
'取消镜像下载': 'Cancel Image Download',
'启用/禁用镜像': 'Enable / Disable Image',
'安全连接日志': 'Security Connection Logs',
+416 -5
View File
@@ -9,6 +9,7 @@ ISSUE_URL="https://github.com/${REPO}/issues"
LOG_FILE="${CLICD_LOG_FILE:-/var/log/clicd-install.log}"
INSTALL_DOWNLOAD_MARKER="${CLICD_INSTALL_DOWNLOAD_MARKER:-/tmp/clicd-install-dir.$$}"
LIBVIRT_DEFAULT_MARKER="/var/lib/clicd/kvm/default-network.created"
CLICD_NETWORK_ENV="/etc/clicd/network.env"
normalize_clicd_arch() {
arch="$1"
@@ -207,6 +208,7 @@ tr_msg() {
-e 's/存储环境检查/Storage environment check/g' \
-e 's/安装系统依赖/Install system dependencies/g' \
-e 's/配置内核网络参数/Configure kernel networking/g' \
-e 's/配置 LXC NAT 网络/Configure LXC NAT network/g' \
-e 's/配置运行时服务/Configure runtime services/g' \
-e 's/配置 libvirt default NAT 网络/Configure libvirt default NAT network/g' \
-e 's/配置 UID\/GID 映射/Configure UID\/GID mapping/g' \
@@ -417,6 +419,8 @@ Environment variables:
CLICD_REPO=owner/repo Default: ${REPO}
CLICD_VERSION=latest|v1.0.0 Default: latest
CLICD_LANG=en|zh Default: auto
CLICD_LXC_SUBNET=10.0.3.0/24 Default: auto-detect an available private subnet
CLICD_KVM_SUBNET=192.168.122.0/24
CLICD_LOG_FILE=/path/file.log Default: ${LOG_FILE}
Examples:
@@ -438,6 +442,8 @@ EOF
CLICD_REPO=owner/repo 默认:${REPO}
CLICD_VERSION=latest|v1.0.0 默认:latest
CLICD_LANG=en|zh 默认:自动检测
CLICD_LXC_SUBNET=10.0.3.0/24 默认:自动检测可用私网网段
CLICD_KVM_SUBNET=192.168.122.0/24
CLICD_LOG_FILE=/path/file.log 默认:${LOG_FILE}
示例:
@@ -844,8 +850,15 @@ delete_ip6tables_bridge_rules() {
cleanup_clicd_networking() {
log "正在清理 CLICD 防火墙和网桥规则..."
delete_iptables_lines nat PREROUTING 'clicd-'
delete_iptables_rule nat POSTROUTING -s 10.0.3.0/24 -o eth+ -j MASQUERADE
delete_iptables_rule nat POSTROUTING -s 192.168.122.0/24 -o eth+ -j MASQUERADE
delete_iptables_lines nat POSTROUTING 'clicd-'
configured_lxc_subnet="$(sed -n 's/^CLICD_LXC_SUBNET=//p' "$CLICD_NETWORK_ENV" 2>/dev/null | tail -n 1)"
configured_kvm_subnet="$(sed -n 's/^CLICD_KVM_SUBNET=//p' "$CLICD_NETWORK_ENV" 2>/dev/null | tail -n 1)"
[ -n "$configured_lxc_subnet" ] || configured_lxc_subnet="$(ip -4 route show dev lxcbr0 proto kernel scope link 2>/dev/null | awk '$1 ~ /\// {print $1; exit}' || true)"
[ -n "$configured_kvm_subnet" ] || configured_kvm_subnet="$(ip -4 route show dev virbr0 proto kernel scope link 2>/dev/null | awk '$1 ~ /\// {print $1; exit}' || true)"
for subnet in 10.0.3.0/24 192.168.122.0/24 "$configured_lxc_subnet" "$configured_kvm_subnet"; do
[ -n "$subnet" ] || continue
delete_iptables_rule nat POSTROUTING -s "$subnet" -o eth+ -j MASQUERADE
done
cleanup_clicd_ipv6_from_config
cleanup_clicd_ipv6_bridge_routes
@@ -857,6 +870,21 @@ cleanup_clicd_networking() {
delete_ip6tables_bridge_rules
}
restore_lxc_network_configs() {
for path in /etc/default/lxc-net /etc/sysconfig/lxc-net /etc/conf.d/lxc-net /etc/conf.d/lxc-bridge; do
backup="${path}.clicd-backup"
if [ -f "$backup" ]; then
mv -f "$backup" "$path"
log "已恢复 $path"
elif [ -f "${path}.clicd-created" ]; then
remove_path "$path"
fi
rm -f "${path}.clicd-created"
done
remove_path "$CLICD_NETWORK_ENV"
rmdir /etc/clicd >/dev/null 2>&1 || true
}
remove_clicd_host_hooks() {
if has_cmd systemctl; then
systemctl stop clicd-kvm-ipv6.service >/dev/null 2>&1 || true
@@ -954,6 +982,7 @@ uninstall_clicd() {
destroy_clicd_kvm_domains
remove_clicd_libvirt_default_network
cleanup_clicd_networking
restore_lxc_network_configs
remove_clicd_host_hooks
remove_clicd_quota_records
@@ -1019,6 +1048,7 @@ install_apk() {
tar \
gzip \
xz \
python3 \
lxc \
lxc-download \
lxc-openrc \
@@ -1058,6 +1088,7 @@ install_apt() {
tar \
gzip \
xz-utils \
python3 \
lxc \
lxc-templates \
lxcfs \
@@ -1127,6 +1158,7 @@ install_dnf() {
tar \
gzip \
xz \
python3 \
lxc \
lxc-templates \
bridge-utils \
@@ -1169,6 +1201,7 @@ install_yum() {
tar \
gzip \
xz \
python3 \
lxc \
lxc-templates \
bridge-utils \
@@ -1252,6 +1285,328 @@ install_dependencies() {
fi
}
network_prompt_available() {
[ -r /dev/tty ] && [ -w /dev/tty ] && { printf '' > /dev/tty; } 2>/dev/null
}
current_bridge_subnet() {
bridge="$1"
subnet="$(ip -4 route show dev "$bridge" proto kernel scope link 2>/dev/null | awk '$1 ~ /\// {print $1; exit}' || true)"
if [ -z "$subnet" ]; then
subnet="$(ip -4 route show dev "$bridge" 2>/dev/null | awk '$1 ~ /\// {print $1; exit}' || true)"
fi
printf '%s' "$subnet"
}
saved_nat_subnet() {
key="$1"
bridge="$2"
saved=""
if [ -f "$CLICD_NETWORK_ENV" ]; then
saved="$(sed -n "s/^${key}=//p" "$CLICD_NETWORK_ENV" 2>/dev/null | tail -n 1)"
fi
if [ -z "$saved" ]; then
saved="$(current_bridge_subnet "$bridge")"
fi
if [ -z "$saved" ] && [ "$key" = "CLICD_LXC_SUBNET" ]; then
for path in /etc/default/lxc-net /etc/sysconfig/lxc-net /etc/conf.d/lxc-net /etc/conf.d/lxc-bridge; do
[ -f "$path" ] || continue
saved="$(sed -n 's/^[[:space:]]*LXC_NETWORK=["'\'']*\([^"'\'']*\)["'\'']*[[:space:]]*$/\1/p' "$path" | tail -n 1)"
[ -n "$saved" ] && break
done
fi
printf '%s' "$saved"
}
resolve_nat_network() {
role="$1"
requested="$2"
hint="$3"
exclude_bridge="$4"
extra_blocked="$5"
CLICD_NET_ROLE="$role" \
CLICD_NET_REQUESTED="$requested" \
CLICD_NET_HINT="$hint" \
CLICD_NET_EXCLUDE_BRIDGE="$exclude_bridge" \
CLICD_NET_EXTRA_BLOCKED="$extra_blocked" \
python3 - <<'PY'
import ipaddress
import os
import subprocess
import sys
import xml.etree.ElementTree as ET
def clean_excepthook(exc_type, value, traceback):
if issubclass(exc_type, ValueError):
print(value, file=sys.stderr)
return
sys.__excepthook__(exc_type, value, traceback)
sys.excepthook = clean_excepthook
role = os.environ.get("CLICD_NET_ROLE", "lxc")
requested = os.environ.get("CLICD_NET_REQUESTED", "").strip()
hint = os.environ.get("CLICD_NET_HINT", "").strip()
exclude_bridge = os.environ.get("CLICD_NET_EXCLUDE_BRIDGE", "").strip()
extra_blocked = os.environ.get("CLICD_NET_EXTRA_BLOCKED", "").strip()
private_ranges = tuple(
ipaddress.ip_network(item)
for item in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")
)
def parse_private(value):
try:
network = ipaddress.ip_network(value, strict=False)
except ValueError as exc:
raise ValueError("请输入有效的 IPv4 CIDR,例如 172.28.40.0/24") from exc
if network.version != 4:
raise ValueError("NAT 网段必须是 IPv4 CIDR")
if network.prefixlen < 16 or network.prefixlen > 28:
raise ValueError("NAT 网段前缀长度必须在 /16 到 /28 之间")
if not any(network.subnet_of(private) for private in private_ranges):
raise ValueError("NAT 网段必须使用 RFC1918 私网地址")
return network
def run(*args):
try:
return subprocess.run(args, check=False, text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout
except OSError:
return ""
blocked = []
route_types = {"broadcast", "local", "unreachable", "blackhole", "throw", "prohibit"}
for line in run("ip", "-4", "route", "show", "table", "all").splitlines():
fields = line.split()
if not fields:
continue
index = 1 if fields[0] in route_types else 0
if index >= len(fields) or fields[index] == "default":
continue
if "dev" in fields:
dev_index = fields.index("dev")
if dev_index + 1 < len(fields) and fields[dev_index + 1] == exclude_bridge:
continue
try:
blocked.append(ipaddress.ip_network(fields[index], strict=False))
except ValueError:
continue
for name in run("virsh", "net-list", "--all", "--name").splitlines():
name = name.strip()
if not name or (role == "kvm" and name == "default"):
continue
xml = run("virsh", "net-dumpxml", name)
if not xml:
continue
try:
root = ET.fromstring(xml)
except ET.ParseError:
continue
for item in root.findall("ip"):
address = item.get("address", "")
netmask = item.get("netmask", "")
prefix = item.get("prefix", "")
if not address:
continue
try:
blocked.append(ipaddress.ip_network(f"{address}/{prefix or netmask}", strict=False))
except ValueError:
continue
if extra_blocked:
try:
blocked.append(ipaddress.ip_network(extra_blocked, strict=False))
except ValueError:
pass
def conflicts(network):
return [item for item in blocked if network.overlaps(item)]
selected = None
if requested and requested.lower() != "auto":
selected = parse_private(requested)
overlaps = conflicts(selected)
if overlaps:
joined = ", ".join(str(item) for item in overlaps[:5])
raise ValueError(f"网段 {selected} 与宿主机现有网络冲突:{joined}")
else:
if hint:
try:
candidate = parse_private(hint)
if not conflicts(candidate):
selected = candidate
except ValueError:
pass
defaults = ["10.0.3.0/24"] if role == "lxc" else ["192.168.122.0/24"]
base_octet = 240 if role == "lxc" else 241
ten_candidates = [
f"10.{base_octet + offset // 256}.{offset % 256}.0/24"
for offset in range(0, 1024)
if base_octet + offset // 256 <= 250
]
seventeen_candidates = [
f"172.{second}.{third}.0/24"
for second in range(31, 15, -1)
for third in range(0, 256)
]
one_ninety_two_candidates = [
f"192.168.{third}.0/24"
for third in range(240, -1, -1)
]
candidates = defaults + ten_candidates + seventeen_candidates + one_ninety_two_candidates
if selected is None:
for raw in candidates:
candidate = ipaddress.ip_network(raw)
if not conflicts(candidate):
selected = candidate
break
if selected is None:
raise ValueError("没有找到可用的私网网段,请通过 CLICD_LXC_SUBNET/CLICD_KVM_SUBNET 手动指定")
hosts = selected.num_addresses
gateway = selected.network_address + 1
dhcp_start = selected.network_address + 2
dhcp_end = selected.broadcast_address - 1
dhcp_max = hosts - 3
print("|".join((
str(selected),
str(gateway),
str(selected.netmask),
str(dhcp_start),
str(dhcp_end),
str(dhcp_max),
)))
PY
}
prompt_nat_network() {
role="$1"
label_zh="$2"
label_en="$3"
env_value="$4"
hint="$5"
bridge="$6"
extra_blocked="$7"
requested="$env_value"
while :; do
if [ -z "$requested" ] && network_prompt_available; then
if [ "$CLICD_LANG_DETECTED" = "en" ]; then
printf " %s (IPv4 CIDR, press Enter to auto-detect): " "$label_en" > /dev/tty
else
printf " %sIPv4 CIDR,回车自动检测可用网段): " "$label_zh" > /dev/tty
fi
IFS= read -r requested < /dev/tty || requested=""
fi
[ -n "$requested" ] || requested="auto"
error_file="/tmp/clicd-network-error.$$"
if values="$(resolve_nat_network "$role" "$requested" "$hint" "$bridge" "$extra_blocked" 2>"$error_file")"; then
rm -f "$error_file"
printf '%s' "$values"
return
fi
error_message="$(cat "$error_file" 2>/dev/null || true)"
rm -f "$error_file"
if ! network_prompt_available || [ -n "$env_value" ]; then
die "${error_message:-NAT 网段配置无效。}"
fi
warn "${error_message:-NAT 网段配置无效,请重新输入。}"
requested=""
done
}
choose_nat_networks() {
lxc_hint="$(saved_nat_subnet CLICD_LXC_SUBNET lxcbr0)"
kvm_hint="$(saved_nat_subnet CLICD_KVM_SUBNET virbr0)"
lxc_values="$(prompt_nat_network lxc "LXC NAT 网段" "LXC NAT subnet" "${CLICD_LXC_SUBNET:-}" "$lxc_hint" lxcbr0 "")"
old_ifs="$IFS"
IFS='|'
set -- $lxc_values
IFS="$old_ifs"
LXC_NAT_SUBNET="$1"
LXC_NAT_GATEWAY="$2"
LXC_NAT_NETMASK="$3"
LXC_NAT_DHCP_START="$4"
LXC_NAT_DHCP_END="$5"
LXC_NAT_DHCP_MAX="$6"
kvm_values="$(prompt_nat_network kvm "KVM NAT 网段" "KVM NAT subnet" "${CLICD_KVM_SUBNET:-}" "$kvm_hint" virbr0 "$LXC_NAT_SUBNET")"
IFS='|'
set -- $kvm_values
IFS="$old_ifs"
KVM_NAT_SUBNET="$1"
KVM_NAT_GATEWAY="$2"
KVM_NAT_NETMASK="$3"
KVM_NAT_DHCP_START="$4"
KVM_NAT_DHCP_END="$5"
KVM_NAT_DHCP_MAX="$6"
export CLICD_LXC_SUBNET="$LXC_NAT_SUBNET"
export CLICD_KVM_SUBNET="$KVM_NAT_SUBNET"
log "NAT 网络:LXC=${LXC_NAT_SUBNET} gateway=${LXC_NAT_GATEWAY}KVM=${KVM_NAT_SUBNET} gateway=${KVM_NAT_GATEWAY}"
}
write_lxc_network_config() {
path="$1"
mkdir -p "$(dirname "$path")"
if [ -f "${path}.clicd-created" ]; then
:
elif [ -f "$path" ] && [ ! -f "${path}.clicd-backup" ]; then
cp -p "$path" "${path}.clicd-backup"
elif [ ! -f "$path" ]; then
touch "${path}.clicd-created"
fi
cat > "$path" << EOF
USE_LXC_BRIDGE="true"
LXC_BRIDGE="lxcbr0"
LXC_ADDR="${LXC_NAT_GATEWAY}"
LXC_NETMASK="${LXC_NAT_NETMASK}"
LXC_NETWORK="${LXC_NAT_SUBNET}"
LXC_DHCP_RANGE="${LXC_NAT_DHCP_START},${LXC_NAT_DHCP_END}"
LXC_DHCP_MAX="${LXC_NAT_DHCP_MAX}"
LXC_DHCP_CONFILE=""
LXC_DOMAIN=""
EOF
}
configure_lxc_nat_network() {
previous="$(current_bridge_subnet lxcbr0)"
if [ -n "$previous" ] && [ "$previous" != "$LXC_NAT_SUBNET" ]; then
active="$(lxc-ls --active 2>/dev/null | tr '\n' ' ' | sed 's/[[:space:]]*$//' || true)"
if [ -n "$active" ] && [ "${CLICD_FORCE_NAT_RECONFIGURE:-0}" != "1" ]; then
die "LXC NAT 网段将从 ${previous} 修改为 ${LXC_NAT_SUBNET},但仍有运行中的 LXC${active}。请先关机,或设置 CLICD_FORCE_NAT_RECONFIGURE=1。"
fi
if is_systemd; then
systemctl stop lxc-net.service >/dev/null 2>&1 || true
elif is_openrc; then
rc-service lxc-net stop >/dev/null 2>&1 || rc-service lxc-bridge stop >/dev/null 2>&1 || true
fi
ip link delete lxcbr0 >/dev/null 2>&1 || true
fi
write_lxc_network_config /etc/default/lxc-net
case "$OS_ID" in
alpine)
write_lxc_network_config /etc/conf.d/lxc-net
write_lxc_network_config /etc/conf.d/lxc-bridge
;;
centos|rhel|rocky|almalinux|fedora)
write_lxc_network_config /etc/sysconfig/lxc-net
;;
esac
mkdir -p "$(dirname "$CLICD_NETWORK_ENV")"
cat > "$CLICD_NETWORK_ENV" << EOF
CLICD_LXC_SUBNET=${LXC_NAT_SUBNET}
CLICD_KVM_SUBNET=${KVM_NAT_SUBNET}
EOF
chmod 0644 "$CLICD_NETWORK_ENV"
}
configure_kernel_networking() {
log "正在启用内核转发配置..."
cat > /etc/sysctl.d/99-clicd.conf << 'EOF'
@@ -1308,6 +1663,13 @@ setup_runtime_services() {
if is_openrc; then
rc-update add cgroups default >/dev/null 2>&1 || true
rc-service cgroups start >/dev/null 2>&1 || true
if rc-service -e lxc-net >/dev/null 2>&1; then
rc-update add lxc-net default >/dev/null 2>&1 || true
rc-service lxc-net restart >/dev/null 2>&1 || true
elif rc-service -e lxc-bridge >/dev/null 2>&1; then
rc-update add lxc-bridge default >/dev/null 2>&1 || true
rc-service lxc-bridge restart >/dev/null 2>&1 || true
fi
rc-update add lxc default >/dev/null 2>&1 || true
rc-service lxc start >/dev/null 2>&1 || true
rc-update add lxcfs default >/dev/null 2>&1 || true
@@ -1331,22 +1693,60 @@ libvirt_network_active() {
| grep -qx yes
}
libvirt_default_subnet() {
LC_ALL=C LANG=C virsh net-dumpxml default 2>/dev/null |
python3 -c '
import ipaddress
import sys
import xml.etree.ElementTree as ET
try:
root = ET.parse(sys.stdin).getroot()
item = root.find("ip")
address = item.get("address", "")
mask = item.get("prefix", "") or item.get("netmask", "")
print(ipaddress.ip_network(f"{address}/{mask}", strict=False))
except Exception:
pass
' 2>/dev/null || true
}
libvirt_default_in_use() {
LC_ALL=C LANG=C virsh list --all --name 2>/dev/null | while IFS= read -r domain; do
[ -n "$domain" ] || continue
if LC_ALL=C LANG=C virsh domiflist "$domain" 2>/dev/null |
awk '($2 == "network" && $3 == "default") || ($2 == "bridge" && $3 == "virbr0") {found=1} END {exit !found}'; then
printf '%s\n' "$domain"
fi
done
}
setup_default_libvirt_network() {
if ! has_cmd virsh; then
warn "未找到 virsh,跳过 libvirt default NAT 网络检查。"
return
fi
log "正在检查 libvirt default NAT 网络..."
current_subnet="$(libvirt_default_subnet)"
if [ -n "$current_subnet" ] && [ "$current_subnet" != "$KVM_NAT_SUBNET" ]; then
domains="$(libvirt_default_in_use | tr '\n' ' ' | sed 's/[[:space:]]*$//')"
if [ -n "$domains" ] && [ "${CLICD_FORCE_NAT_RECONFIGURE:-0}" != "1" ]; then
die "KVM NAT 网段将从 ${current_subnet} 修改为 ${KVM_NAT_SUBNET},但 libvirt default 网络仍被虚拟机使用:${domains}。请先关机,或设置 CLICD_FORCE_NAT_RECONFIGURE=1。"
fi
if libvirt_network_active; then
LC_ALL=C LANG=C virsh net-destroy default >/dev/null
fi
LC_ALL=C LANG=C virsh net-undefine default >/dev/null
fi
if ! virsh net-info default >/dev/null 2>&1; then
net_xml="$(mktemp /tmp/clicd-default-net.XXXXXX.xml)"
cat > "$net_xml" << 'EOF'
cat > "$net_xml" << EOF
<network>
<name>default</name>
<bridge name='virbr0'/>
<forward mode='nat'/>
<ip address='192.168.122.1' netmask='255.255.255.0'>
<ip address='${KVM_NAT_GATEWAY}' netmask='${KVM_NAT_NETMASK}'>
<dhcp>
<range start='192.168.122.2' end='192.168.122.254'/>
<range start='${KVM_NAT_DHCP_START}' end='${KVM_NAT_DHCP_END}'/>
</dhcp>
</ip>
</network>
@@ -1605,6 +2005,7 @@ Restart=always
RestartSec=5
LimitNOFILE=1048576
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
EnvironmentFile=-${CLICD_NETWORK_ENV}
[Install]
WantedBy=multi-user.target
@@ -1628,6 +2029,12 @@ pidfile="/run/clicd.pid"
output_log="/var/log/clicd.log"
error_log="/var/log/clicd.err"
if [ -r /etc/clicd/network.env ]; then
set -a
. /etc/clicd/network.env
set +a
fi
depend() {
need net
after lxc libvirtd
@@ -1708,6 +2115,8 @@ print_summary() {
echo "====================================="
echo " $(tr_msg "Web 面板:")http://YOUR_SERVER_IP:8999"
echo " $(tr_msg "二进制:")/usr/local/bin/clicd"
echo " LXC NAT: ${LXC_NAT_SUBNET} (gateway ${LXC_NAT_GATEWAY})"
echo " KVM NAT: ${KVM_NAT_SUBNET} (gateway ${KVM_NAT_GATEWAY})"
echo " $(tr_msg "安装日志:")$LOG_FILE"
echo " $(tr_msg "问题反馈:")$ISSUE_URL"
if is_systemd; then
@@ -1733,7 +2142,9 @@ print_summary() {
run_step "兼容性检查" check_os_compatibility
run_step "存储环境检查" check_storage_compatibility
run_step "安装系统依赖" install_dependencies
choose_nat_networks
run_step "配置内核网络参数" configure_kernel_networking
run_step "配置 LXC NAT 网络" configure_lxc_nat_network
run_step "配置运行时服务" setup_runtime_services
run_step "配置 libvirt default NAT 网络" setup_default_libvirt_network
run_step "配置 UID/GID 映射" setup_subids