Compare commits

..

177 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
MengMengCode 8283b88ded release: v1.1.27 2026-07-24 19:00:12 +08:00
MengMengCode 6c9f24bb24 FIX port setting 2026-07-24 18:51:52 +08:00
MengMengCode f2fa2449e9 release: v1.1.26 2026-07-22 17:02:23 +08:00
MengMengCode 53d56be8f9 fix #33 2026-07-22 16:57:44 +08:00
MengMengCode ec38ab9136 Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-07-21 21:26:09 +08:00
MengMengCode fdcd7df9e9 Update API endpoint. 2026-07-21 21:26:04 +08:00
Meng Meng d6d46296fe Merge pull request #32 from MengMengCode/dependabot/npm_and_yarn/frontend/axios-1.18.0
build(deps): bump axios from 1.17.0 to 1.18.0 in /frontend
2026-07-21 15:13:02 +08:00
dependabot[bot] 3f44c7565f build(deps): bump axios from 1.17.0 to 1.18.0 in /frontend
Bumps [axios](https://github.com/axios/axios) from 1.17.0 to 1.18.0.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.17.0...v1.18.0)

---
updated-dependencies:
- dependency-name: axios
  dependency-version: 1.18.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-20 20:30:35 +00:00
Meng Meng 61d842d94c Fix star history image link in README.md
Updated the star history image link in the README.
2026-07-20 12:52:40 +08:00
Meng Meng ca303d33f6 Replace star history section with new embed link 2026-07-19 20:08:13 +08:00
MengMengCode 6bdeafccf2 修复剩余 CodeQL 高危告警 2026-07-18 21:31:31 +08:00
MengMengCode 04cefe0cf1 release: v1.1.25 2026-07-18 21:18:54 +08:00
MengMengCode f28117bc5e 修复了一些已知问题 2026-07-18 21:16:29 +08:00
MengMengCode 2324494dd7 优化了机器创建流程 2026-07-18 20:45:23 +08:00
MengMengCode ebba97f1d6 · 修复了一些已知问题
· 增加了局域网DHCP IP分配适配
· 完善了多盘兼容支持 #17
2026-07-18 19:44:32 +08:00
MengMengCode 3dabd93d2f Fix some problem. 2026-07-17 00:44:47 +08:00
MengMengCode 8bad52bd9e FIX ##30 2026-07-17 00:27:31 +08:00
MengMengCode d05ca8cc4c release: v1.1.24 2026-07-16 23:28:28 +08:00
MengMengCode 48fa14f8a7 FIX #18 2026-07-16 23:27:26 +08:00
MengMengCode 5c6d6eafc9 Support Debian 13.
#29
and fix useage chart data display problem, storage on database instead of localstorage.
2026-07-16 21:24:28 +08:00
MengMengCode 2ecdb5c26f fix Dependabot alerts 2026-07-16 21:01:27 +08:00
MengMengCode ae02241370 KVM的端口转发_ 失效修复 2026-07-16 20:57:07 +08:00
MengMengCode fdd83977fc 支持限制用户可选择的系统 2026-07-16 20:47:26 +08:00
MengMengCode 58d86b5d08 release: v1.1.23 2026-07-16 18:57:49 +08:00
MengMengCode 7307255130 FIX #28 2026-07-16 18:57:15 +08:00
MengMengCode 0e3c059236 ci: fix release workflow checkout 2026-07-16 16:58:19 +08:00
MengMengCode 61137b837d release: v1.1.22 2026-07-16 16:58:19 +08:00
Meng Meng 596bf86477 Merge pull request #27 from MengMengCode/dependabot/go_modules/backend/golang.org/x/crypto-0.52.0
build(deps): bump golang.org/x/crypto from 0.45.0 to 0.52.0 in /backend
2026-07-16 15:15:39 +08:00
MengMengCode 47a09aa177 release: v1.1.21 2026-07-16 15:13:53 +08:00
MengMengCode 2456b65ce2 Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-07-16 15:13:40 +08:00
MengMengCode 292686a19a Fix some problems. 2026-07-16 15:13:35 +08:00
dependabot[bot] 9eb7c322cf build(deps): bump golang.org/x/crypto from 0.45.0 to 0.52.0 in /backend
Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.45.0 to 0.52.0.
- [Commits](https://github.com/golang/crypto/compare/v0.45.0...v0.52.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-version: 0.52.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-10 11:56:11 +00:00
Meng Meng 5ec62ca732 Merge pull request #26 from StarVM-OpenSource/main
从UTF8-BOM转UTF8以修复魔方财务使用此模块后无法正常被下游拉取信息的问题
2026-06-29 09:06:10 +08:00
a79df0d2dd Merge branch 'MengMengCode:main' into main 2026-06-26 22:20:52 +08:00
cc8fdbfede 从UTF8-BOM转UTF8以修复魔方财务使用此模块后无法正常被下游拉取信息的问题 2026-06-26 20:44:29 +08:00
MengMengCode 702d6975e5 release: v1.1.20 2026-06-17 21:08:13 +08:00
MengMengCode 84d98e40c6 FIX #16 2026-06-17 21:06:58 +08:00
MengMengCode fd974d95b9 Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-06-17 20:41:14 +08:00
MengMengCode cd258fd6ac FIX #20 2026-06-17 20:41:11 +08:00
Meng Meng 0c2dd457d4 Merge pull request #22 from MengMengCode/dependabot/npm_and_yarn/frontend/form-data-4.0.6
build(deps): bump form-data from 4.0.5 to 4.0.6 in /frontend
2026-06-17 20:03:18 +08:00
MengMengCode 92e846eecc IPV6 fix 2026-06-17 19:56:09 +08:00
dependabot[bot] a1d9ce8b1c build(deps): bump form-data from 4.0.5 to 4.0.6 in /frontend
Bumps [form-data](https://github.com/form-data/form-data) from 4.0.5 to 4.0.6.
- [Release notes](https://github.com/form-data/form-data/releases)
- [Changelog](https://github.com/form-data/form-data/blob/master/CHANGELOG.md)
- [Commits](https://github.com/form-data/form-data/compare/v4.0.5...v4.0.6)

---
updated-dependencies:
- dependency-name: form-data
  dependency-version: 4.0.6
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-17 11:22:14 +00:00
MengMengCode 49d8093f45 网络流量、磁盘 IO 图表显示优化 2026-06-17 19:16:28 +08:00
MengMengCode 98ed716225 Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-06-17 18:42:19 +08:00
MengMengCode 78276d303b chore(docs): 升级 esbuild 至 0.28.1 并更新忽略规则 2026-06-17 18:42:12 +08:00
Meng Meng 30d2a4f4da Merge pull request #15 from StarVM-OpenSource/main
更新一键安装certbot脚本+增加更完整的webssh逻辑
2026-06-14 12:51:18 +08:00
a54e03b924 更新一键安装certbot脚本+增加更完整的webssh逻辑 2026-06-14 03:15:02 +08:00
Meng Meng 4cdc6e68ba Merge pull request #14 from MengMengCode/alert-autofix-29
Potential fix for code scanning alert no. 29: DOM text reinterpreted as HTML
2026-06-13 21:04:48 +08:00
Meng Meng 2ed42992ed Potential fix for code scanning alert no. 29: DOM text reinterpreted as HTML
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-06-13 21:04:10 +08:00
Meng Meng 4dfd7c0885 Merge pull request #13 from StarVM-OpenSource/main
修复防火墙无法创建 获取规则问题 优化防火墙创建规则UI
2026-06-13 12:01:43 +08:00
5ed5b4509d Merge branch 'main' of https://github.com/StarVM-OpenSource/CLICD-MoFang 2026-06-13 02:52:47 +08:00
18f297b988 修复防火墙功能 2026-06-13 02:49:23 +08:00
d5a236943b 修复防火墙至不支持的方法 等待Claude修复 2026-06-13 00:52:19 +08:00
MengMengCode c54f92f892 Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-06-12 21:55:17 +08:00
MengMengCode 86f0d079ab update docs 2026-06-12 21:55:15 +08:00
Meng Meng 3a65d5d24a Remove version number from README title
Removed version number from the title in README.md
2026-06-12 16:03:38 +08:00
MengMengCode cbe9339316 release: v1.1.19 2026-06-12 16:01:52 +08:00
Meng Meng 79d6dad684 Merge pull request #12 from MengMengCode/chore/update-version-badge
chore: add version badge to README
2026-06-12 15:59:47 +08:00
MengMengCode 55c7a9796c chore: add version badge to README 2026-06-12 15:59:24 +08:00
Meng Meng f4a15a0d90 Merge pull request #11 from MengMengCode/feature/split-rate-limits
feat: split rate limits with configurable per-endpoint controls
2026-06-12 15:57:35 +08:00
MengMengCode c7742319b2 feat: split rate limits with configurable per-endpoint controls 2026-06-12 15:53:31 +08:00
Meng Meng 01c14ecba6 chore: update firewall i18n strings
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 13:42:22 +08:00
MengMengCode 989e1b6645 chore: update firewall i18n strings
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 13:40:59 +08:00
MengMengCode da5eea5193 release: v1.1.18 2026-06-12 13:19:07 +08:00
MengMengCode 4de86c458f 修复了一些已知问题 2026-06-12 13:18:54 +08:00
Meng Meng baf213e769 Potential fix for code scanning alert no. 28: DOM text reinterpreted as HTML
Patch

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-06-12 12:00:38 +08:00
Meng Meng 819a79e00d Merge pull request #8 from StarVM-OpenSource/main
魔方财务模块:支持独立IPv4 初步兼容防火墙
2026-06-12 11:54:46 +08:00
18bee369c1 Merge branch 'main' of https://github.com/StarVM-OpenSource/CLICD-MoFang 2026-06-12 10:20:59 +08:00
2463715e32 兼容独立IPv4 初步兼容防火墙 2026-06-12 10:19:51 +08:00
MengMengCode fbc539ea47 release: v1.1.17 2026-06-12 01:35:17 +08:00
MengMengCode 875cd4716b 增加了服务器防火墙功能 2026-06-12 01:35:04 +08:00
MengMengCode 6194b6e364 修复了一些已知问题 2026-06-11 23:29:22 +08:00
MengMengCode 30d6b2d9f7 release: v1.1.16 2026-06-11 23:09:49 +08:00
MengMengCode 2f94498df2 修复了一些已知问题 2026-06-11 23:09:04 +08:00
MengMengCode c303fe6d17 release: v1.1.15 2026-06-10 14:52:30 +08:00
MengMengCode eedb2d7fb0 修复了一些已知问题 2026-06-10 14:51:22 +08:00
MengMengCode bfc98d043b feat(security): 快照并持久化告警时的连接跟踪数据 2026-06-10 13:28:46 +08:00
MengMengCode 0a4cf5c0bd release: v1.1.14 2026-06-10 11:12:43 +08:00
MengMengCode 54a608c19d Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-06-10 11:12:32 +08:00
MengMengCode 73bd6934f9 修复预设密码以及KEY问题 2026-06-10 11:12:27 +08:00
Meng Meng a35595edcf Update README.md 2026-06-10 11:04:58 +08:00
MengMengCode b605df613e Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-06-10 10:35:13 +08:00
MengMengCode 3cc8f7df7f 修复了一些已知问题 2026-06-10 10:35:08 +08:00
Meng Meng 744246c0a8 Update thanks section formatting in README.md 2026-06-10 09:33:31 +08:00
MengMengCode aed512cb09 patch 2026-06-10 02:39:58 +08:00
MengMengCode b6f48acc4c Refactor code structure for improved readability and maintainability 2026-06-10 02:33:18 +08:00
MengMengCode d83a5e3473 release: v1.1.13 2026-06-10 01:27:21 +08:00
MengMengCode 18c9d75a05 Merge pull request #5 from StarVM-OpenSource/main
Add Mofang finance module sources without packaged zip.
2026-06-10 01:22:45 +08:00
MengMengCode b80e4817ef ci: package mofang module artifacts 2026-06-10 01:21:57 +08:00
MengMengCode 0b052f2217 优化UI 2026-06-10 01:14:51 +08:00
80386d35ba 已测试LXC功能基本正常 KVM功能暂未进行测试 2026-06-10 01:01:39 +08:00
MengMengCode a45e063fc2 Add comprehensive documentation for CLICD features and operations
- Introduced Container Management documentation covering lifecycle operations, resource management, and console access.
- Added Dashboard documentation detailing metrics and related APIs.
- Created Host Report documentation summarizing host environment and resource status.
- Included Image Management documentation for template handling and management actions.
- Documented Networking and Routing features including NAT4 and IPv6 management.
- Added Security Alerts documentation outlining alert scenarios and API usage.
- Created Snapshot Management documentation for snapshot operations and scheduling.
- Documented Sub-user management for granting access to specific containers.
- Added Configuration guide detailing runtime settings and security recommendations.
- Created Installation guide for setting up CLICD with requirements and steps.
- Added Introduction and Quick Start guides for new users.
- Documented Upgrade process with version checking and pre-upgrade checklist.
- Created Deployment guide for service exposure and firewall recommendations.
- Added FAQ section addressing common questions and concerns.
- Documented Troubleshooting steps for common issues encountered.
2026-06-10 00:42:06 +08:00
MengMengCode e71adf6830 修复了一些已知问题 2026-06-09 23:34:09 +08:00
MengMengCode bb0c4f999d release: v1.1.12 2026-06-09 23:25:29 +08:00
MengMengCode 0c9f420474 添加新建虚拟机/重装系统 预设SSH密码以及KEY Auth功能 2026-06-09 23:25:19 +08:00
MengMengCode 9a826add87 release: v1.1.11 2026-06-09 22:48:20 +08:00
MengMengCode 63611dc932 Support webSSH Origin Allowlist 2026-06-09 22:48:09 +08:00
MengMengCode e6551bf4ae release: v1.1.10 2026-06-09 22:25:42 +08:00
MengMengCode 5bf2b6534a Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-06-09 22:22:42 +08:00
MengMengCode 917afc3157 支持公网IPV4分配,单独IPV6分配,以及混合网络分配。 2026-06-09 22:22:40 +08:00
Meng Meng c8081edbac Update README.md 2026-06-09 16:50:19 +08:00
Meng Meng 95eb00a31d Update Buy Me a Coffee username in FUNDING.yml 2026-06-09 15:56:08 +08:00
MengMengCode f4edf94800 release: v1.1.9 2026-06-09 15:34:06 +08:00
MengMengCode 82b42e7961 Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-06-09 15:33:19 +08:00
MengMengCode e971d99070 Refactor code structure for improved readability and maintainability 2026-06-09 15:33:17 +08:00
Meng Meng 8dd09ff009 Revise badges and add support indicators in README
Updated badge descriptions and added new badges for supported features.
2026-06-09 15:33:13 +08:00
Meng Meng 7f4755788a Enhance README with features and tech stack
Added detailed features and technology stack information to README.
2026-06-09 15:26:55 +08:00
Meng Meng c24df1d42f Add Let's Encrypt badge to README 2026-06-09 15:16:40 +08:00
MengMengCode cf00d0d03d 加入了certbot检测 2026-06-09 13:49:09 +08:00
MengMengCode 79be2d5cbd 修复了一些已知问题 2026-06-09 13:35:08 +08:00
MengMengCode e66327db29 release: v1.1.8 2026-06-09 13:14:08 +08:00
MengMengCode 2b4fe4f5bc 修复webvnc 2026-06-09 13:13:51 +08:00
MengMengCode a923daa7a2 release: v1.1.7 2026-06-09 13:06:46 +08:00
MengMengCode c46f84c66e 增加SSL支持HTTPS/WSS 2026-06-09 13:06:26 +08:00
MengMengCode 835bb51c6e 修改 2026-06-09 02:00:04 +08:00
MengMengCode 7aed51e86b gitignore优化 2026-06-09 01:59:54 +08:00
MengMengCode e364807fb9 docs 2026-06-09 00:49:53 +08:00
MengMengCode c63ce02709 docs 2026-06-09 00:44:00 +08:00
MengMengCode 54f9ed7f7d Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-06-09 00:25:06 +08:00
MengMengCode b01f9fe301 修复UI 2026-06-09 00:25:04 +08:00
Meng Meng d03e2c4c0c Create LICENSE 2026-06-09 00:23:55 +08:00
MengMengCode 33603f5776 release: v1.1.6 2026-06-09 00:12:19 +08:00
MengMengCode 9ad7bcc97a 完善API文档 2026-06-09 00:10:45 +08:00
MengMengCode f3a1687a18 修复了一些已知问题 2026-06-08 21:18:17 +08:00
MengMengCode 49b13af91c release: v1.1.5 2026-06-08 20:10:34 +08:00
MengMengCode e79609281f 增强API集成能力,划分KEY功能权限 2026-06-08 19:25:55 +08:00
MengMengCode 2fa130a2b6 标记并清理 CLICD 创建的 libvirt default 网络 2026-06-08 16:21:23 +08:00
MengMengCode 14d2192b05 完善卸载网络规则清理 2026-06-08 16:18:24 +08:00
MengMengCode 9f5ad94a83 清理卸载时的 LXC 镜像缓存 2026-06-08 16:10:55 +08:00
MengMengCode ac6587f2bc 增强安装脚本发行版下载回退 2026-06-08 16:03:32 +08:00
MengMengCode 6fad37b844 修复安装脚本下载失败处理 2026-06-08 15:55:17 +08:00
MengMengCode d0eb92eaab 修复 2026-06-08 15:49:42 +08:00
MengMengCode 5207082cd1 release: v1.1.4 2026-06-08 15:44:58 +08:00
MengMengCode 608b50f18a 修复了一些功能 2026-06-08 15:44:35 +08:00
MengMengCode b58a6b1030 release: v1.1.3 2026-06-08 14:41:51 +08:00
MengMengCode 366f889a8c 优化安装脚本执行逻辑 2026-06-08 14:40:06 +08:00
MengMengCode 814441e9a0 release: v1.1.2 2026-06-08 02:24:04 +08:00
MengMengCode aed11af105 修复了一些已知问题 2026-06-08 02:23:48 +08:00
MengMengCode 3d95bb33c1 Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-06-08 01:21:12 +08:00
MengMengCode ade1c6c093 优化功能体验 2026-06-08 01:21:10 +08:00
Meng Meng 5c4cc1cab3 Merge pull request #4 from MengMengCode/dependabot/npm_and_yarn/frontend/vite-8.0.16
build(deps-dev): bump vite from 5.4.21 to 8.0.16 in /frontend
2026-06-07 23:42:42 +08:00
copilot-swe-agent[bot] 109e47170f fix: resolve frontend dependency conflicts for Vite 8 build 2026-06-07 15:40:09 +00:00
dependabot[bot] 34637cc79d build(deps-dev): bump vite from 5.4.21 to 8.0.16 in /frontend
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 5.4.21 to 8.0.16.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v8.0.16/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 8.0.16
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-07 15:31:31 +00:00
MengMengCode 7d48889eea release: v1.1.1 2026-06-07 23:29:06 +08:00
MengMengCode 2bcdb9e095 Merge branch 'main' of https://github.com/MengMengCode/CLICD 2026-06-07 23:10:21 +08:00
MengMengCode 2ab42e7f57 支持部署KVM XFCE桌面系统 2026-06-07 23:10:19 +08:00
Meng Meng 3257cbb2a3 Merge pull request #2 from MengMengCode/dependabot/go_modules/backend/golang.org/x/crypto-0.45.0
build(deps): bump golang.org/x/crypto from 0.28.0 to 0.45.0 in /backend
2026-06-07 22:06:55 +08:00
dependabot[bot] 1ff5d7a85e build(deps): bump golang.org/x/crypto from 0.28.0 to 0.45.0 in /backend
Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.28.0 to 0.45.0.
- [Commits](https://github.com/golang/crypto/compare/v0.28.0...v0.45.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-version: 0.45.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-07 13:29:47 +00:00
Meng Meng a99781d418 Merge pull request #1 from MengMengCode/dependabot/go_modules/backend/github.com/golang-jwt/jwt/v5-5.2.2
Bump github.com/golang-jwt/jwt/v5 from 5.2.1 to 5.2.2 in /backend
2026-06-07 21:27:51 +08:00
MengMengCode b993e57d05 fix: repair login page encoding 2026-06-07 21:19:24 +08:00
MengMengCode 7ae0c91813 release: v1.1.0 2026-06-07 21:14:31 +08:00
MengMengCode aab58aca6e release: v1.1.0 2026-06-07 21:11:53 +08:00
MengMengCode 0b27604f95 FIX 2026-06-07 21:11:29 +08:00
dependabot[bot] 460614e274 Bump github.com/golang-jwt/jwt/v5 from 5.2.1 to 5.2.2 in /backend
Bumps [github.com/golang-jwt/jwt/v5](https://github.com/golang-jwt/jwt) from 5.2.1 to 5.2.2.
- [Release notes](https://github.com/golang-jwt/jwt/releases)
- [Commits](https://github.com/golang-jwt/jwt/compare/v5.2.1...v5.2.2)

---
updated-dependencies:
- dependency-name: github.com/golang-jwt/jwt/v5
  dependency-version: 5.2.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-07 13:11:00 +00:00
MengMengCode 007811ab41 release: v1.1.0 2026-06-07 21:09:37 +08:00
MengMengCode 95af3e44f2 优化了一些功能 2026-06-07 21:08:51 +08:00
MengMengCode 2ad17fa520 修复了一些已知问题 2026-06-07 20:16:00 +08:00
MengMengCode 08a1a057e7 Update Disclaimer 2026-06-07 19:09:23 +08:00
MengMengCode e9f657ab17 release: v1.0.13 2026-06-07 18:58:10 +08:00
MengMengCode 7e5da67de4 兼容KVM大多数功能 2026-06-07 18:57:55 +08:00
MengMengCode c99f3f6d55 release: v1.0.12 2026-06-07 13:16:39 +08:00
MengMengCode 2df92be501 修复了一些已知问题 2026-06-07 13:15:59 +08:00
MengMengCode f8d16ca792 添加标签 2026-06-07 10:55:52 +08:00
177 changed files with 46471 additions and 3756 deletions
Submodule .claude/worktrees/agent-ae3871aebda20eb86 deleted from 422e48b524
+15
View File
@@ -0,0 +1,15 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: mengmengcode
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+79 -23
View File
@@ -6,7 +6,7 @@ on:
- main
- master
tags:
- "v*"
- 'v*'
pull_request:
workflow_dispatch:
@@ -14,9 +14,15 @@ permissions:
contents: write
jobs:
linux-amd64:
name: Linux amd64
linux:
name: Linux ${{ matrix.goarch }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
goarch:
- amd64
- arm64
steps:
- name: Checkout
@@ -25,51 +31,101 @@ 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
cache-dependency-path: |
frontend/package-lock.json
docs/package-lock.json
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: "1.22.x"
go-version: '1.24.5'
cache-dependency-path: backend/go.sum
- name: Install frontend dependencies
run: npm ci --prefix frontend
- name: Install docs dependencies
run: npm ci --prefix docs
- name: Build docs
run: npm run build --prefix docs
- name: Set version from tag
shell: bash
run: |
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
echo "CLICD_VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV
echo "CLICD_VERSION=${GITHUB_REF#refs/tags/v}" >> "$GITHUB_ENV"
else
echo "CLICD_VERSION=dev" >> $GITHUB_ENV
echo "CLICD_VERSION=dev" >> "$GITHUB_ENV"
fi
- name: Build
shell: bash
- name: Build CLICD
env:
CLICD_GOARCH: ${{ matrix.goarch }}
run: bash build.sh
- name: Package
shell: bash
- name: Package CLICD
env:
CLICD_GOARCH: ${{ matrix.goarch }}
run: |
mkdir -p dist package/clicd-linux-amd64
cp build/clicd package/clicd-linux-amd64/clicd
cp build/install.sh package/clicd-linux-amd64/install.sh
chmod +x package/clicd-linux-amd64/clicd package/clicd-linux-amd64/install.sh
tar -C package -czf dist/clicd-linux-amd64.tar.gz clicd-linux-amd64
cp build/clicd dist/clicd-linux-amd64
sha256sum dist/* > dist/SHA256SUMS
asset_dir="clicd-linux-${CLICD_GOARCH}"
mkdir -p "dist" "package/${asset_dir}"
cp build/clicd "package/${asset_dir}/clicd"
cp build/install.sh "package/${asset_dir}/install.sh"
chmod +x "package/${asset_dir}/clicd" "package/${asset_dir}/install.sh"
tar -C package -czf "dist/${asset_dir}.tar.gz" "${asset_dir}"
cp build/clicd "dist/${asset_dir}"
- name: Package Mofang module
run: |
if [ ! -f Mofang/clicd.php ]; then
echo "Mofang module not present; skipping package."
exit 0
fi
if ! command -v zip >/dev/null 2>&1; then
sudo apt-get update
sudo apt-get install -y zip
fi
cd Mofang
zip -r ../dist/clicd-mofang.zip clicd.php handlers templates -x '*.DS_Store' -x '*/.DS_Store'
- name: Generate checksums
run: sha256sum dist/* > dist/SHA256SUMS
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: clicd-linux-amd64
name: clicd-linux-${{ matrix.goarch }}
path: dist/*
release:
name: Publish GitHub Release
needs: linux
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/v')
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Download artifacts
uses: actions/download-artifact@v4
with:
path: dist-artifacts
- name: Prepare release assets
run: |
mkdir -p dist
find dist-artifacts -maxdepth 2 -type f ! -name SHA256SUMS -print -exec cp -f {} dist/ \;
sha256sum dist/* > dist/SHA256SUMS
- name: Publish GitHub Release
if: startsWith(github.ref, 'refs/tags/v')
env:
GH_TOKEN: ${{ github.token }}
shell: bash
GH_REPO: ${{ github.repository }}
run: |
gh release create "$GITHUB_REF_NAME" dist/* --generate-notes || \
gh release upload "$GITHUB_REF_NAME" dist/* --clobber
+65
View File
@@ -0,0 +1,65 @@
name: Deploy Docs
on:
push:
branches:
- main
- master
paths:
- "docs/**"
- ".github/workflows/pages.yml"
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: github-pages
cancel-in-progress: false
jobs:
build:
name: Build VitePress
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "22.22.0"
cache: npm
cache-dependency-path: docs/package-lock.json
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Install dependencies
working-directory: docs
run: npm ci
- name: Build docs
working-directory: docs
env:
VITEPRESS_BASE: /
run: npm run build
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: docs/.vitepress/dist
deploy:
name: Deploy GitHub Pages
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
+9
View File
@@ -13,6 +13,8 @@ backend/internal/server/web/*
# Build artifacts
/build/
/dist/
Mofang/*.zip
*.exe
*.dll
*.so
@@ -58,9 +60,16 @@ backend/tmp/
*.swp
*.swo
*~
.claude/
# OS
.DS_Store
Thumbs.db
linux.txt
push-release.ps1
deploy.ps1
backend/clicd
api.md
deploy-arm.ps1
deploy-dhcp.ps1
deploy-pve-windows.ps1
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+549
View File
@@ -0,0 +1,549 @@
# CLICD 魔方财务对接模块
这是用于智简魔方 / IDCSMART 的 CLICD 服务器模块。模块通过 CLICD API 完成实例开通、删除、开关机、重启、重装、改密、资源变更、流量重置、NAT 端口映射管理、实例信息展示和 WebSSH 入口。
## 文件结构
```text
clicd.php
README.md
handlers/
webssh.php
templates/
firewall.html
info.html
nat.html
```
安装时请保持目录结构不变,将整个 `clicd` 目录放入魔方服务器模块目录:
```text
public/plugins/servers/clicd/
```
## 服务器配置
在魔方后台添加服务器时,模块名称选择 `clicd`
CLICD 面板地址建议使用 HTTPS
```text
主机名 = https://0.0.0.0:8999
```
也可以拆分填写:
```text
IP地址 = 0.0.0.0
端口 = 8999
secure = 开启
```
API Key 可以填写在以下任意一个字段中:
```text
Hash
密码
```
模块请求 CLICD 时会同时携带:
```text
X-API-Key: clicd_sk_xxxx
Authorization: Bearer clicd_sk_xxxx
Content-Type: application/json
```
## 产品配置项
| 字段 | 说明 |
| --- | --- |
| `virtualization` | 虚拟化类型,`lxc``kvm` |
| `template_id` | CLICD 模板 / 镜像 ID |
| `vcpu` | CPU 核心数 |
| `cpu_percent` | CPU 使用率限制,`0` 表示不额外限制 |
| `ram_mb` | 内存,单位 MB |
| `disk_gb` | 系统盘,单位 GB |
| `network_bw_mbps` | 带宽,单位 Mbps |
| `traffic_mode` | `total` 总流量,或 `in_out` 入 / 出分开 |
| `monthly_traffic_gb` | 月流量 GB |
| `traffic_in_gb` | 入站流量 GB`in_out` 模式使用 |
| `traffic_out_gb` | 出站流量 GB`in_out` 模式使用 |
| `io_speed_mbps` | 磁盘 IO 限制,`0` 表示不限制 |
| `port_mapping_count` | 开通时分配的 NAT 端口数量,最小 2 |
| `snapshot_limit` | 快照配额 |
| `extra_ports` | 额外映射的容器端口,逗号分隔,例如 `80,443` |
| `assign_ipv6` | 开通时是否自动分配 IPv6 |
| `sync_expiry` | 是否同步魔方到期时间到 CLICD |
客户产品的 `domain` 会作为 CLICD 容器名称。模块会自动把不适合作为容器名的字符替换为 `-`
## 开通后字段同步
开通、同步、重装、改密后,模块会从 CLICD 容器详情拉取最新信息并写回魔方主机表:
| 魔方字段 | 写入内容 |
| --- | --- |
| `dedicatedip` | NAT 外网 IP,优先使用 API 返回的公网字段,否则使用服务器 IP |
| `username` | 固定写入 `root` |
| `password` | CLICD 返回的 SSH 密码,兼容魔方 `cmf_encrypt()` |
| `port` | CLICD 返回的 `ssh_port` |
| `domainstatus` | CLICD 状态为 `running` 时写 `Active`,否则写 `Suspended` |
如果接口返回的密码是 `***` 这类脱敏值,模块不会覆盖魔方里已有密码。
## 客户区页面
模块提供三个客户区选项卡:
```text
实例信息
NAT转发
防火墙
```
客户区按钮提供:
```text
WebSSH
```
## 实例信息
实例信息页展示:
- 实例名称、运行状态、SSH 地址、IPv6
- CPU、内存、负载、磁盘圆环状态
- 月流量进度
- CPU 使用率、内存使用、网络流量、磁盘 IO 图表
- IPv4、SSH 端口、SSH 密码、资源配置、到期时间
图表数据通过客户区懒加载接口获取,不会强制刷新整个魔方页面。页面首次打开会加载一次数据,之后由用户选择是否自动刷新:
```text
不刷新
10 秒
1 分钟
5 分钟
10 分钟
```
也可以点击“立即刷新”手动刷新一次。当前 CLICD 用量接口返回的是实时值,不是历史数组;图表曲线由客户区前端持续采样生成。若需要打开页面立即显示历史曲线,需要 CLICD 额外提供历史指标接口。
流量显示支持智能单位,小流量会显示 B / KB / MB,大流量显示 GB,例如:
```text
370.5 KB / 100 GB
```
模块会优先调用:
```text
GET /api/v1/containers/{name}/usage
GET /api/v1/containers/{name}/traffic
```
如果 `/api/v1/containers/{name}/usage` 不可用,模块会在容器详情存在 `uuid` 时尝试兼容:
```text
GET /api/containers/{uuid}/usage
```
已兼容的常见用量字段包括:
```text
cpu_usage_pct
memory_usage_bytes
disk_usage_bytes
network_rx_bps
network_tx_bps
disk_read_bps
disk_write_bps
rx_used_bytes
tx_used_bytes
total_used_bytes
limit_gb
used_pct
```
## NAT 转发
NAT 转发是独立页面,支持:
- 查看端口映射
- 获取随机可用端口
- 添加端口映射
- 修改端口映射
- 删除端口映射
删除端口映射时使用页面内确认弹窗,不使用浏览器自带确认框。
使用的 CLICD API
```text
GET /api/v1/containers/{id|uuid|name}
GET /api/v1/containers/{id}/random-port
POST /api/v1/containers/{id}/port-mappings
PUT /api/v1/containers/{id}/port-mappings/{index}
DELETE /api/v1/containers/{id}/port-mappings/{index}
```
添加 / 修改 NAT 映射时必须使用 JSON 请求体,例如:
```json
{
"container_port": 8080,
"host_port": 61320,
"protocol": "tcp",
"description": "HTTP"
}
```
## 防火墙
防火墙是独立客户区页面,支持:
- 查看防火墙启用状态、默认动作和规则列表
- 启用 / 停用防火墙
- 设置默认动作:未匹配拒绝或未匹配放行
- 添加规则
- 编辑规则
- 删除规则
- 单独启用 / 停用某条规则
页面会先在前端修改规则列表和开关状态,点击“保存设置”后才统一同步到 CLICD。这样可以避免每次切换开关、修改默认动作或编辑规则时都立即请求后端,减少客户区卡顿。
注意:防火墙关闭时也可以保存规则;关闭只表示暂时不接管该容器流量,不代表规则必须清空。
使用的 CLICD API
```text
GET /api/v1/containers/{id}/firewall
PUT /api/v1/containers/{id}/firewall
```
更新防火墙时必须使用 JSON 请求体,例如:
```json
{
"enabled": true,
"default_action": "ACCEPT",
"rules": [
{
"id": "",
"network": "ipv4",
"direction": "in",
"protocol": "tcp",
"port": "22",
"source_ip": "",
"action": "ACCEPT",
"description": "Allow SSH",
"enabled": true
}
]
}
```
规则字段说明:
| 字段 | 说明 |
| --- | --- |
| `network` | 网络范围,常用 `ipv4`,也支持 `ipv6` / `all` |
| `direction` | 方向,`in` 入站,`out` 出站 |
| `protocol` | 协议,`tcp``udp` |
| `port` | 端口,可填写单端口、逗号分隔端口或端口段,例如 `22``80,443``8000-9000` |
| `source_ip` | 来源 IP / CIDR,留空表示任意来源 |
| `action` | 动作,`ACCEPT` 放行,`DROP` 拒绝 |
| `description` | 规则描述 |
| `enabled` | 是否启用该规则 |
IPv4 NAT 入站规则的端口按容器内部端口匹配,不是宿主机公网端口。例如公网 `22023 -> 容器 22`,防火墙规则端口应填写 `22`
## WebSSH
WebSSH 按钮会调用:
```text
POST /api/v1/ssh-ticket
```
请求体:
```json
{
"container_name": "example-vm"
}
```
接口返回 60 秒有效票据后,模块会打开本地 handler:
```text
/plugins/servers/clicd/handlers/webssh.php
```
浏览器会从该页面直连 CLICD
```text
wss://0.0.0.0:8999/api/ssh?container=example-vm
Sec-WebSocket-Protocol: clicd-ticket.xxxxx
```
注意:WebSSH 受浏览器安全策略和 CLICD 后端 Origin 校验影响。魔方客户区通常是 HTTPS,因此 CLICD 面板也必须启用 HTTPS/WSS。请把魔方服务器配置里的 `主机名` 改为 `https://0.0.0.0:8999`,或把 `secure` 设为 `开启`
新版 CLICD 已支持 WebSSH Origin 放行。部署时需要在 CLICD 后端把魔方财务客户区域名加入 WebSSH Origin 白名单,例如:
```text
https://www.example.com
```
如果 WebSSH 页面显示 `WebSocket error``Disconnected code=1006`,但直接以 CLICD 自身 Origin 测试能返回 `101 Switching Protocols`,通常说明 CLICD 后端未放行魔方客户区域名的 WebSocket Origin。此时请检查 CLICD 的 WebSSH Origin 白名单配置;前端页面无法伪造浏览器 Origin。
## 支持的魔方操作
| 魔方操作 | CLICD API |
| --- | --- |
| 连接测试 | `GET /api/v1/dashboard` |
| 开通 | `POST /api/v1/containers` |
| 删除 | `DELETE /api/v1/containers/{name}/delete` |
| 开机 | `POST /api/v1/containers/{name}/start` |
| 关机 | `POST /api/v1/containers/{name}/stop` |
| 重启 | `POST /api/v1/containers/{name}/restart` |
| 重装 | `POST /api/v1/containers/{name}/reinstall` |
| 改密 | `POST /api/v1/containers/{name}/reset-password` |
| 重置流量 | `POST /api/v1/containers/{name}/traffic-reset` |
| 变更资源 | `PUT /api/v1/containers/{name}/resource-limit` |
| 变更流量 | `PUT /api/v1/containers/{name}/traffic-limit` |
| 同步到期 | `PUT /api/v1/containers/{name}/expiry` |
| 查询防火墙 | `GET /api/v1/containers/{id}/firewall` |
| 更新防火墙 | `PUT /api/v1/containers/{id}/firewall` |
| WebSSH | `POST /api/v1/ssh-ticket` |
## 建议 API 权限
API Key 至少需要以下权限,具体名称以 CLICD 后端实际权限系统为准:
```text
dashboard:read
container:read
container:create
container:power
container:delete
container:reinstall
container:password
container:traffic
container:resize
container:port
container:firewall
task:read
ssh-ticket:create
```
如果 API Key 使用 `*``admin:*`,通常可以覆盖上述权限。
## 建议先测试的 curl
连接测试:
```bash
curl -H "X-API-Key: clicd_sk_xxxx" \
https://0.0.0.0:8999/api/v1/dashboard
```
容器详情:
```bash
curl -H "X-API-Key: clicd_sk_xxxx" \
https://0.0.0.0:8999/api/v1/containers/example-vm
```
资源用量:
```bash
curl -H "X-API-Key: clicd_sk_xxxx" \
https://0.0.0.0:8999/api/v1/containers/example-vm/usage
```
流量统计:
```bash
curl -H "X-API-Key: clicd_sk_xxxx" \
https://0.0.0.0:8999/api/v1/containers/example-vm/traffic
```
修改 NAT
```bash
curl --location --request PUT \
"https://0.0.0.0:8999/api/v1/containers/10/port-mappings/1" \
--header "X-API-Key: clicd_sk_xxxx" \
--header "Authorization: Bearer clicd_sk_xxxx" \
--header "Content-Type: application/json" \
--data-raw '{"container_port":8081,"host_port":61320,"protocol":"tcp","description":"HTTP"}'
```
查询防火墙:
```bash
curl -H "X-API-Key: clicd_sk_xxxx" \
https://0.0.0.0:8999/api/v1/containers/10/firewall
```
更新防火墙:
```bash
curl --location --request PUT \
"https://0.0.0.0:8999/api/v1/containers/10/firewall" \
--header "X-API-Key: clicd_sk_xxxx" \
--header "Content-Type: application/json" \
--data-raw '{"enabled":true,"default_action":"ACCEPT","rules":[{"id":"","network":"ipv4","direction":"in","protocol":"tcp","port":"22","source_ip":"","action":"ACCEPT","description":"Allow SSH","enabled":true}]}'
```
创建 WebSSH 票据:
```bash
curl --location --request POST \
"https://0.0.0.0:8999/api/v1/ssh-ticket" \
--header "X-API-Key: clicd_sk_xxxx" \
--header "Content-Type: application/json" \
--data-raw '{"container_name":"example-vm"}'
```
## 常见问题
### NAT 修改不生效
确认请求体必须是 JSON,不要使用 `multipart/form-data`。正确请求头:
```text
Content-Type: application/json
```
### 防火墙获取提示“不支持的方法”
请确认模块版本已经包含防火墙页签修复。客户区防火墙列表应通过模块公开的 `firewallList` 调用,再由模块向 CLICD 发起:
```text
GET /api/v1/containers/{id}/firewall
```
如果页面或二开代码直接把读取请求改成 `POST /api/v1/containers/{id}/firewall`,CLICD 会返回“不支持的方法”。
### 防火墙保存后规则为空
请确认更新接口最终发往 CLICD 的请求体是 JSON,并且包含 `rules` 数组。防火墙关闭时也可以保存规则,`enabled: false` 不应自动清空 `rules`
正确请求体示例:
```json
{
"enabled": false,
"default_action": "ACCEPT",
"rules": [
{
"id": "",
"network": "ipv4",
"direction": "in",
"protocol": "tcp",
"port": "22",
"source_ip": "",
"action": "ACCEPT",
"description": "Allow SSH",
"enabled": true
}
]
}
```
### 图表刚打开只有一条横线
CLICD 当前用量接口返回的是实时值,不是历史序列。页面刚打开时只有一个采样点,所以会显示当前值横线。选择 `10 秒` 自动刷新或点击“立即刷新”多采样几次后,会逐步形成折线。
### 流量显示为 0
旧版本只显示 GB,小流量换算后会被四舍五入成 `0 GB`。当前版本已改为智能单位,会显示 B / KB / MB / GB。
### 防火墙
防火墙是独立客户区页面,支持:
- 查看防火墙启用状态、默认动作和规则列表
- 启用 / 停用防火墙
- 设置默认动作:未匹配拒绝或未匹配放行
- 添加规则
- 编辑规则
- 删除规则
- 单独启用 / 停用某条规则
页面会先在前端修改规则列表和开关状态,点击“保存设置”后才统一同步到 CLICD。这样可以避免每次切换开关、修改默认动作或编辑规则时都立即请求后端,减少客户区卡顿。
注意:防火墙关闭时也可以保存规则;关闭只表示暂时不接管该容器流量,不代表规则必须清空。
使用的 CLICD API
```text
GET /api/v1/containers/{id}/firewall
PUT /api/v1/containers/{id}/firewall
```
更新防火墙时必须使用 JSON 请求体,例如:
```json
{
"enabled": true,
"default_action": "ACCEPT",
"rules": [
{
"id": "",
"network": "ipv4",
"direction": "in",
"protocol": "tcp",
"port": "22",
"source_ip": "",
"action": "ACCEPT",
"description": "Allow SSH",
"enabled": true
}
]
}
```
规则字段说明:
| 字段 | 说明 |
| --- | --- |
| `network` | 网络范围,常用 `ipv4`,也支持 `ipv6` / `all` |
| `direction` | 方向,`in` 入站,`out` 出站 |
| `protocol` | 协议,`tcp``udp` |
| `port` | 端口,可填写单端口、逗号分隔端口或端口段,例如 `22``80,443``8000-9000` |
| `source_ip` | 来源 IP / CIDR,留空表示任意来源 |
| `action` | 动作,`ACCEPT` 放行,`DROP` 拒绝 |
| `description` | 规则描述 |
| `enabled` | 是否启用该规则 |
IPv4 NAT 入站规则的端口按容器内部端口匹配,不是宿主机公网端口。例如公网 `22023 -> 容器 22`,防火墙规则端口应填写 `22`
## WebSSH 打不开或提示不安全 WebSocket
请确认 CLICD 面板已经启用 HTTPS/WSS,并且魔方服务器配置使用 HTTPS:
```text
server_host = https://0.0.0.0:8999
```
如果仍然使用 `http://`,模块会生成 `ws://` 地址,HTTPS 客户区页面会被浏览器拦截。
如果 WSS 证书正常但仍返回 `Forbidden` 或浏览器显示 `code=1006`,请检查 CLICD 的 WebSSH Origin 白名单。新版 CLICD 已支持放行魔方财务域名,需要把魔方客户区访问域名完整加入白名单,例如:
```text
https://www.example.com
```
注意需要填写浏览器实际访问魔方客户区时的协议和域名,`http` / `https`、带不带 `www` 都要与实际访问地址一致。
### 开通后魔方里的 IP、端口、密码不对
执行“同步状态”或重装 / 改密后,模块会重新拉取容器详情。请确认 CLICD 容器详情接口能返回:
```text
ssh_port
ssh_password
status
```
公网 IP 优先使用 `nat_public_ip/public_ip/host_ip/external_ip/node_ip/nat_host` 等字段;如果接口没有返回,则使用魔方服务器配置的 IP。
+1716
View File
File diff suppressed because it is too large Load Diff
+399
View File
@@ -0,0 +1,399 @@
<?php
$ws = isset($_GET['ws']) ? (string)$_GET['ws'] : (isset($_GET['amp;ws']) ? (string)$_GET['amp;ws'] : '');
$protocol = isset($_GET['protocol']) ? (string)$_GET['protocol'] : (isset($_GET['amp;protocol']) ? (string)$_GET['amp;protocol'] : '');
$container = isset($_GET['container']) ? (string)$_GET['container'] : (isset($_GET['amp;container']) ? (string)$_GET['amp;container'] : '');
$ticket = isset($_GET['ticket']) ? (string)$_GET['ticket'] : (isset($_GET['amp;ticket']) ? (string)$_GET['amp;ticket'] : '');
if ($protocol === '' && $ticket !== '') {
$protocol = 'clicd-ticket.' . $ticket;
}
if ($ws === '') {
http_response_code(400);
header('Content-Type: text/plain; charset=utf-8');
echo "Missing WebSSH parameters\n";
echo "Received query: " . ($_SERVER['QUERY_STRING'] ?? '') . "\n";
exit;
}
?>
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WebSSH</title>
<style>
html,body{height:100%;margin:0;background:#0b1020;color:#e5e7eb;font-family:Consolas,Menlo,monospace}
body{cursor:text}
.bar{height:44px;display:flex;align-items:center;gap:12px;padding:0 14px;background:#111827;border-bottom:1px solid #243047}
.dot{width:9px;height:9px;border-radius:50%;background:#f59e0b}
.dot.ok{background:#22c55e}.dot.err{background:#ef4444}
.title{font-size:14px;color:#cbd5e1;flex:1}
.tools{display:flex;align-items:center;gap:8px;font-size:12px;color:#94a3b8;flex-wrap:wrap;justify-content:flex-end}
.tools select{height:26px;background:#0f172a;color:#cbd5e1;border:1px solid #334155;border-radius:4px}
.tools button{height:26px;border:1px solid #334155;background:#0f172a;color:#cbd5e1;border-radius:4px;padding:0 8px;cursor:pointer}
#keyhint{min-width:44px;text-align:right}
#iostat{min-width:120px;text-align:right}
#term{height:calc(100% - 89px);box-sizing:border-box;padding:14px;overflow:auto;white-space:pre-wrap;word-break:break-word;font-size:14px;line-height:1.45;outline:none}
.inputbar{height:44px;display:flex;align-items:center;gap:8px;padding:6px 10px;box-sizing:border-box;background:#111827;border-top:1px solid #243047}
#cmd{flex:1;height:30px;background:#020617;color:#e5e7eb;border:1px solid #334155;border-radius:4px;padding:0 8px;font:14px Consolas,Menlo,monospace;outline:none}
#sendcmd{height:30px;border:1px solid #2563eb;background:#2563eb;color:#fff;border-radius:4px;padding:0 12px;cursor:pointer}
.hint{color:#94a3b8}
.meta{color:#94a3b8}
</style>
</head>
<body>
<div class="bar">
<span id="state" class="dot"></span>
<span class="title">WebSSH <?php echo htmlspecialchars($container, ENT_QUOTES, 'UTF-8'); ?></span>
<span class="tools">
<span>发送模式</span>
<select id="send-mode">
<option value="raw" selected>raw</option>
<option value="binary">binary</option>
<option value="json-input">json input</option>
<option value="json-data">json data</option>
<option value="json-stdin">json stdin</option>
</select>
<button id="send-enter" type="button">回车</button>
<span id="iostat">S0 R0</span>
<span id="keyhint"></span>
</span>
</div>
<div id="term" tabindex="0"><span class="hint">正在连接...</span></div>
<div class="inputbar">
<input id="cmd" type="text" autocomplete="off" spellcheck="false" placeholder="在这里输入命令,例如 ls -la">
<button id="sendcmd" type="button">发送</button>
</div>
<script>
(function(){
var wsUrl = <?php echo json_encode($ws, JSON_UNESCAPED_SLASHES); ?>;
var protocol = <?php echo json_encode($protocol, JSON_UNESCAPED_SLASHES); ?>;
var ticket = <?php echo json_encode($ticket, JSON_UNESCAPED_SLASHES); ?>;
var term = document.getElementById('term');
var state = document.getElementById('state');
var modeSelect = document.getElementById('send-mode');
var keyhint = document.getElementById('keyhint');
var iostat = document.getElementById('iostat');
var sendEnter = document.getElementById('send-enter');
var cmd = document.getElementById('cmd');
var sendcmd = document.getElementById('sendcmd');
var socket;
var hintTimer;
var sentCount = 0;
var recvCount = 0;
var decoder = window.TextDecoder ? new TextDecoder('utf-8') : null;
var termLines = [''];
var cursorRow = 0;
var cursorCol = 0;
var maxLines = 2000;
function append(text) {
writeTerminal(stripTerminalControls(String(text || '')));
renderTerminal();
}
function clearTerminal() {
termLines = [''];
cursorRow = 0;
cursorCol = 0;
renderTerminal();
}
function stripTerminalControls(text) {
return text
.replace(/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g, '')
.replace(/\x1b\[(?:2J|H)/g, '\f')
.replace(/\x1b\[[0-?]*[ -/]*K/g, '\v')
.replace(/\ufffd\[[0-?]*[ -/]*K/g, '\v')
.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
.replace(/\ufffd\[[0-?]*[ -/]*[@-~]/g, '')
.replace(/\x1b[()][A-Za-z0-9]/g, '')
.replace(/\x1b[@-Z\\-_]/g, '')
.replace(/[\x00-\x08\x0e-\x1f\x7f]/g, '');
}
function ensureLine() {
while (cursorRow >= termLines.length) {
termLines.push('');
}
}
function trimTerminal() {
if (termLines.length <= maxLines) {
return;
}
var overflow = termLines.length - maxLines;
termLines.splice(0, overflow);
cursorRow = Math.max(0, cursorRow - overflow);
}
function writeTerminal(text) {
for (var i = 0; i < text.length; i++) {
var ch = text.charAt(i);
if (ch === '\f') {
termLines = [''];
cursorRow = 0;
cursorCol = 0;
continue;
}
if (ch === '\v') {
ensureLine();
termLines[cursorRow] = termLines[cursorRow].slice(0, cursorCol);
continue;
}
if (ch === '\r') {
cursorCol = 0;
continue;
}
if (ch === '\n') {
cursorRow++;
cursorCol = 0;
ensureLine();
trimTerminal();
continue;
}
if (ch === '\b') {
cursorCol = Math.max(0, cursorCol - 1);
continue;
}
if (ch === '\t') {
var spaces = 4 - (cursorCol % 4);
for (var s = 0; s < spaces; s++) {
writePrintable(' ');
}
continue;
}
writePrintable(ch);
}
trimTerminal();
}
function writePrintable(ch) {
ensureLine();
var line = termLines[cursorRow];
if (cursorCol > line.length) {
line += new Array(cursorCol - line.length + 1).join(' ');
}
termLines[cursorRow] = line.slice(0, cursorCol) + ch + line.slice(cursorCol + 1);
cursorCol++;
}
function renderTerminal() {
term.textContent = termLines.join('\n');
term.scrollTop = term.scrollHeight;
}
function setState(cls, text) {
state.className = 'dot ' + cls;
append(text);
}
function updateIoStatus() {
if (!iostat) return;
var stateText = socket ? ['CONNECTING','OPEN','CLOSING','CLOSED'][socket.readyState] : '-';
iostat.textContent = 'S' + sentCount + ' R' + recvCount + ' ' + stateText;
}
function websocketProtocolValue(value) {
value = String(value || '');
return /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(value) ? value : '';
}
try {
var protocolValue = websocketProtocolValue(protocol);
if (!protocolValue && ticket) {
append('[WebSSH] 票据已通过 URL 参数传递,当前浏览器不会发送子协议。\n');
}
socket = protocolValue ? new WebSocket(wsUrl, protocolValue) : new WebSocket(wsUrl);
socket.binaryType = 'arraybuffer';
} catch (e) {
setState('err', '\nWebSocket 创建失败:' + e.message + '\n');
return;
}
socket.onopen = function(){
clearTerminal();
setState('ok', '已连接。\r\n');
updateIoStatus();
if (cmd) cmd.focus();
};
socket.onmessage = function(event){
recvCount++;
updateIoStatus();
if (typeof event.data === 'string') {
handleIncomingText(event.data);
return;
}
if (event.data instanceof ArrayBuffer) {
handleIncomingText(decodeIncoming(event.data));
return;
}
if (window.Blob && event.data instanceof Blob) {
event.data.arrayBuffer().then(function(buffer){
handleIncomingText(decodeIncoming(buffer));
}).catch(function(){
append('\n[WebSSH] 无法解码服务端返回内容。\n');
});
}
};
socket.onerror = function(){
setState('err', '\nWebSocket 连接错误,请检查 HTTPS 证书、WSS 服务、Origin 策略和票据有效期。\n');
};
socket.onclose = function(event){
updateIoStatus();
setState('err', '\n连接已断开。code=' + event.code + ' reason=' + (event.reason || '-') + ' clean=' + event.wasClean + '\n');
};
function flashKey(text) {
if (!keyhint) return;
keyhint.textContent = text;
window.clearTimeout(hintTimer);
hintTimer = window.setTimeout(function(){ keyhint.textContent = ''; }, 500);
}
function decodeIncoming(buffer) {
if (decoder) {
return decoder.decode(new Uint8Array(buffer));
}
var bytes = new Uint8Array(buffer);
var text = '';
for (var i = 0; i < bytes.length; i++) {
text += String.fromCharCode(bytes[i]);
}
try {
return decodeURIComponent(escape(text));
} catch (e) {
return text;
}
}
function handleIncomingText(text) {
append(text);
if (text.indexOf('SSH shell ready') !== -1) {
window.setTimeout(function(){ send('\r'); }, 250);
}
}
function wsPayload(data) {
var mode = modeSelect ? modeSelect.value : 'raw';
if (mode === 'raw') {
return data;
}
if (mode === 'binary') {
return new TextEncoder().encode(data);
}
if (mode === 'json-data') {
return JSON.stringify({type:'data', data:data});
}
if (mode === 'json-stdin') {
return JSON.stringify({type:'stdin', data:data});
}
return JSON.stringify({type:'input', data:data});
}
function send(data) {
if (!socket || socket.readyState !== WebSocket.OPEN) {
return false;
}
socket.send(wsPayload(data));
sentCount++;
updateIoStatus();
flashKey(data === '\r' ? '回车' : data === '\x7f' ? '退格' : data.length > 1 ? data.length + ' 字符' : data);
return true;
}
function keyToData(e) {
if (e.ctrlKey && !e.altKey && !e.metaKey && e.key.length === 1) {
var code = e.key.toUpperCase().charCodeAt(0);
if (code >= 64 && code <= 95) {
return String.fromCharCode(code - 64);
}
}
var map = {
Enter: '\r',
Backspace: '\x7f',
Tab: '\t',
Escape: '\x1b',
ArrowUp: '\x1b[A',
ArrowDown: '\x1b[B',
ArrowRight: '\x1b[C',
ArrowLeft: '\x1b[D',
Delete: '\x1b[3~',
Home: '\x1b[H',
End: '\x1b[F',
PageUp: '\x1b[5~',
PageDown: '\x1b[6~'
};
if (map[e.key]) {
return map[e.key];
}
if (!e.ctrlKey && !e.altKey && !e.metaKey && e.key.length === 1) {
return e.key;
}
return null;
}
document.addEventListener('keydown', function(e){
if (e.target === cmd) {
return;
}
var data = keyToData(e);
if (data !== null && send(data)) {
e.preventDefault();
}
});
document.addEventListener('paste', function(e){
if (e.target === cmd) {
return;
}
var text = e.clipboardData ? e.clipboardData.getData('text/plain') : '';
if (text && send(text)) {
e.preventDefault();
}
});
document.addEventListener('mousedown', function(){
if (cmd) cmd.focus();
});
function sendCommandLine() {
if (!cmd) return;
var value = cmd.value;
if (value === '') {
send('\r');
return;
}
if (send(value + '\r')) {
cmd.value = '';
}
}
if (sendcmd) {
sendcmd.addEventListener('click', sendCommandLine);
}
if (sendEnter) {
sendEnter.addEventListener('click', function(){
send('\r');
if (cmd) cmd.focus();
});
}
if (cmd) {
cmd.addEventListener('keydown', function(e){
if (e.key === 'Enter') {
sendCommandLine();
e.preventDefault();
return;
}
if (e.ctrlKey && e.key.toLowerCase() === 'c') {
send('\x03');
e.preventDefault();
}
});
}
window.setInterval(updateIoStatus, 1000);
})();
</script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+378
View File
@@ -0,0 +1,378 @@
<style>
.clicd-info{font-size:14px;color:#1f2937;background:#f6f8fb;padding:14px;border-radius:6px;max-width:100%;overflow:hidden}
.clicd-info *{box-sizing:border-box}
.clicd-head{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px;margin-bottom:12px}
.clicd-mini{background:#fff;border:1px solid #e5e7eb;border-radius:6px;padding:10px}
.clicd-mini-label{font-size:12px;color:#6b7280;margin-bottom:4px}
.clicd-mini-value{font-size:16px;font-weight:600;color:#111827;word-break:break-all}
.clicd-section{background:#fff;border:1px solid #e5e7eb;border-radius:6px;margin-top:12px;padding:14px}
.clicd-section-title{display:flex;align-items:center;justify-content:space-between;gap:10px;font-size:15px;font-weight:700;margin-bottom:12px;color:#111827;min-width:0;flex-wrap:wrap}
.clicd-section-title>span:first-child{min-width:0}
.clicd-refresh{display:flex;align-items:center;justify-content:flex-end;gap:8px;font-size:12px;color:#6b7280;font-weight:400;flex-wrap:wrap;min-width:0;max-width:100%}
.clicd-refresh label{display:inline-flex;align-items:center;gap:4px;min-width:0;white-space:nowrap}
.clicd-refresh-select{height:28px;border:1px solid #d1d5db;border-radius:4px;background:#fff;color:#374151;padding:3px 6px;font-size:12px}
.clicd-refresh-btn{height:28px;border:1px solid #2563eb;background:#2563eb;color:#fff;border-radius:4px;padding:3px 8px;font-size:12px;cursor:pointer;white-space:nowrap;max-width:96px;overflow:hidden;text-overflow:ellipsis}
.clicd-refresh-btn[disabled]{opacity:.6;cursor:not-allowed}
.clicd-gauges{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px}
.clicd-gauge{display:flex;align-items:center;gap:12px;min-height:92px}
.clicd-ring{--p:0%;width:78px;height:78px;border-radius:50%;background:conic-gradient(#2f80ed var(--p),#e5e7eb 0);display:grid;place-items:center;flex:0 0 auto;position:relative}
.clicd-ring:before{content:"";width:66px;height:66px;border-radius:50%;background:#fff;position:absolute}
.clicd-ring span{position:relative;display:inline-flex;align-items:center;justify-content:center;max-width:62px;min-width:0;font-size:17px;font-weight:700;line-height:1;color:#111827;white-space:nowrap;text-align:center;background:#fff;border-radius:3px;padding:0 1px}
.clicd-ring[data-tight="1"] span{font-size:15px}
.clicd-ring[data-tight="2"] span{font-size:14px}
.clicd-gauge-title{font-weight:700;color:#111827;margin-bottom:4px}
.clicd-gauge-sub{font-size:12px;color:#6b7280;line-height:1.45}
.clicd-progress{height:12px;background:#e5e7eb;border-radius:999px;overflow:hidden}
.clicd-progress span{display:block;height:100%;width:0;background:linear-gradient(90deg,#2f80ed,#10b981);transition:width .25s ease}
.clicd-traffic-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:center;margin-top:8px;color:#374151;min-width:0}
.clicd-traffic-row>div{min-width:0;word-break:break-word}
.clicd-charts{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px}
.clicd-chart{border:1px solid #e5e7eb;border-radius:6px;padding:12px;background:#fff;min-height:190px;min-width:0;overflow:hidden}
.clicd-chart-title{display:flex;justify-content:space-between;gap:8px;align-items:center;font-weight:700;margin-bottom:8px;color:#111827;min-width:0;flex-wrap:wrap}
.clicd-chart-value{font-size:12px;color:#6b7280;font-weight:400;white-space:normal;overflow-wrap:anywhere;text-align:right}
.clicd-chart canvas{width:100%;height:132px;display:block}
.clicd-table{width:100%;border-collapse:collapse;background:#fff}
.clicd-table th,.clicd-table td{border:1px solid #e5e7eb;padding:8px;text-align:left}
.clicd-table th{width:16%;background:#f9fafb;color:#374151;font-weight:600}
.clicd-debug{display:none;margin-top:10px;padding:8px;background:#fff7ed;border:1px solid #fed7aa;color:#9a3412;border-radius:6px;font-size:12px}
@media (max-width:640px){
.clicd-info{padding:10px}
.clicd-section-title{align-items:flex-start}
.clicd-refresh{justify-content:flex-start;width:100%}
.clicd-charts{grid-template-columns:1fr}
.clicd-table th,.clicd-table td{display:block;width:100%}
.clicd-ring{width:70px;height:70px}
.clicd-ring:before{width:60px;height:60px}
.clicd-ring span{max-width:56px;font-size:15px}
}
</style>
<div class="clicd-info" data-clicd-info-root="1">
<div class="clicd-head">
<div class="clicd-mini">
<div class="clicd-mini-label">&#23454;&#20363;&#21517;&#31216;</div>
<div class="clicd-mini-value">{$container.name|default='-'}</div>
</div>
<div class="clicd-mini">
<div class="clicd-mini-label">&#36816;&#34892;&#29366;&#24577;</div>
<div class="clicd-mini-value">{$status_text|default='-'}</div>
</div>
<div class="clicd-mini">
<div class="clicd-mini-label">SSH &#22320;&#22336;</div>
<div class="clicd-mini-value">{$ssh_host|default='-'}:{$ssh_port|default='-'}</div>
</div>
<div class="clicd-mini">
<div class="clicd-mini-label">IPv6</div>
<div class="clicd-mini-value">{$ipv6|default='-'}</div>
</div>
</div>
<div class="clicd-section">
<div class="clicd-section-title">
<span>&#29366;&#24577;</span>
<span class="clicd-refresh">
<span>&#26356;&#26032;&#20110; <span data-clicd-info="chart_time">-</span></span>
<label>
&#33258;&#21160;&#21047;&#26032;
<select class="clicd-refresh-select" id="clicd-info-refresh">
<option value="0" selected>&#19981;&#21047;&#26032;</option>
<option value="10000">10 &#31186;</option>
<option value="60000">1 &#20998;&#38047;</option>
<option value="300000">5 &#20998;&#38047;</option>
<option value="600000">10 &#20998;&#38047;</option>
</select>
</label>
<button class="clicd-refresh-btn" type="button" id="clicd-info-refresh-now">&#31435;&#21363;&#21047;&#26032;</button>
</span>
</div>
<div class="clicd-gauges">
<div class="clicd-gauge">
<div class="clicd-ring" data-gauge="cpu_percent"><span><span data-clicd-info="cpu_percent">0</span>%</span></div>
<div>
<div class="clicd-gauge-title">CPU</div>
<div class="clicd-gauge-sub" data-clicd-info="cpu_detail">-</div>
</div>
</div>
<div class="clicd-gauge">
<div class="clicd-ring" data-gauge="mem_percent"><span><span data-clicd-info="mem_percent">0</span>%</span></div>
<div>
<div class="clicd-gauge-title">&#20869;&#23384;</div>
<div class="clicd-gauge-sub" data-clicd-info="mem_detail">-</div>
</div>
</div>
<div class="clicd-gauge">
<div class="clicd-ring" data-gauge="load_percent"><span><span data-clicd-info="load_percent">0</span>%</span></div>
<div>
<div class="clicd-gauge-title">&#36127;&#36733;</div>
<div class="clicd-gauge-sub" data-clicd-info="load_detail">-</div>
</div>
</div>
<div class="clicd-gauge">
<div class="clicd-ring" data-gauge="disk_percent"><span><span data-clicd-info="disk_percent">0</span>%</span></div>
<div>
<div class="clicd-gauge-title">&#30913;&#30424;</div>
<div class="clicd-gauge-sub" data-clicd-info="disk_detail">-</div>
</div>
</div>
</div>
<div style="margin-top:14px">
<div class="clicd-traffic-row">
<div>&#26376;&#27969;&#37327;</div>
<div><span data-clicd-info="traffic_used_text">{$traffic_used_text|default='-'}</span> / <span data-clicd-info="traffic_limit_text">{$traffic_limit_text|default='-'}</span></div>
</div>
<div class="clicd-progress"><span data-progress="traffic_percent"></span></div>
<div class="clicd-traffic-row" style="font-size:12px;color:#6b7280">
<div>&#20837;&#31449; <span data-clicd-info="traffic_in_text">{$traffic_in_text|default='-'}</span></div>
<div>&#20986;&#31449; <span data-clicd-info="traffic_out_text">{$traffic_out_text|default='-'}</span></div>
</div>
</div>
</div>
<div class="clicd-section">
<div class="clicd-section-title"><span>&#32479;&#35745;&#20449;&#24687;</span></div>
<div class="clicd-charts">
<div class="clicd-chart">
<div class="clicd-chart-title">CPU &#20351;&#29992;&#29575; <span class="clicd-chart-value" data-clicd-info="cpu_detail">-</span></div>
<canvas data-chart="cpu_percent"></canvas>
</div>
<div class="clicd-chart">
<div class="clicd-chart-title">&#20869;&#23384;&#20351;&#29992; <span class="clicd-chart-value" data-clicd-info="mem_detail">-</span></div>
<canvas data-chart="mem_percent"></canvas>
</div>
<div class="clicd-chart">
<div class="clicd-chart-title">&#32593;&#32476;&#27969;&#37327; <span class="clicd-chart-value"><span data-clicd-info="net_in_rate">0 B/s</span> / <span data-clicd-info="net_out_rate">0 B/s</span></span></div>
<canvas data-chart="network"></canvas>
</div>
<div class="clicd-chart">
<div class="clicd-chart-title">&#30913;&#30424; IO <span class="clicd-chart-value"><span data-clicd-info="disk_read_rate">0 B/s</span> / <span data-clicd-info="disk_write_rate">0 B/s</span></span></div>
<canvas data-chart="diskio"></canvas>
</div>
</div>
</div>
<div class="clicd-section">
<div class="clicd-section-title"><span>&#23454;&#20363;&#20449;&#24687;</span></div>
<table class="clicd-table">
<tbody>
<tr>
<th>IPv4</th><td>{$ipv4|default='-'}</td>
<th>&#29992;&#25143;&#21517;</th><td>root</td>
</tr>
<tr>
<th>SSH &#31471;&#21475;</th><td>{$ssh_port|default='-'}</td>
<th>SSH &#23494;&#30721;</th><td>{$ssh_password|default='-'}</td>
</tr>
<tr>
<th>CPU</th><td>{$vcpu|default='-'} &#26680;</td>
<th>&#20869;&#23384;</th><td>{$ram_mb|default='-'} MB</td>
</tr>
<tr>
<th>&#30828;&#30424;</th><td>{$disk_gb|default='-'} GB</td>
<th>&#24102;&#23485;</th><td>{$bandwidth|default='-'} Mbps</td>
</tr>
<tr>
<th>&#21040;&#26399;&#26102;&#38388;</th><td colspan="3">{$expires_at|default='-'}</td>
</tr>
</tbody>
</table>
</div>
<div class="clicd-debug" id="clicd-info-debug"></div>
</div>
<script>
(function(){
var root = document.querySelector('[data-clicd-info-root="1"]:not([data-info-bound="1"])');
if (!root) return;
root.setAttribute('data-info-bound', '1');
var history = {
cpu_percent: [],
mem_percent: [],
network_in: [],
network_out: [],
disk_read: [],
disk_write: []
};
var maxPoints = 18;
var refreshTimer = null;
function endpoint() {
return "{$MODULE_CUSTOM_API}";
}
function number(value) {
var n = parseFloat(value);
return isFinite(n) ? n : 0;
}
function push(name, value) {
history[name].push(number(value));
if (history[name].length > maxPoints) history[name].shift();
}
function setText(key, value) {
root.querySelectorAll('[data-clicd-info="' + key + '"]').forEach(function(node){
if (typeof value !== 'object') node.textContent = value;
});
}
function setGauge(key, value) {
var pct = Math.max(0, Math.min(100, number(value)));
root.querySelectorAll('[data-gauge="' + key + '"]').forEach(function(node){
node.style.setProperty('--p', pct + '%');
});
}
function fitGaugeText() {
root.querySelectorAll('.clicd-ring').forEach(function(ring){
var label = ring.querySelector('span');
if (!label) return;
ring.removeAttribute('data-tight');
if (label.scrollWidth > label.clientWidth) {
ring.setAttribute('data-tight', '1');
}
if (label.scrollWidth > label.clientWidth) {
ring.setAttribute('data-tight', '2');
}
});
}
function setProgress(key, value) {
var pct = Math.max(0, Math.min(100, number(value)));
root.querySelectorAll('[data-progress="' + key + '"]').forEach(function(node){
node.style.width = pct + '%';
});
}
function draw(canvas, series, colors, maxValue) {
if (!canvas || !canvas.getContext) return;
var rect = canvas.getBoundingClientRect();
var ratio = window.devicePixelRatio || 1;
var width = Math.max(220, Math.floor(rect.width || canvas.clientWidth || 220));
var height = Math.max(120, Math.floor(rect.height || canvas.clientHeight || 132));
if (canvas.width !== width * ratio || canvas.height !== height * ratio) {
canvas.width = width * ratio;
canvas.height = height * ratio;
}
var ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
ctx.clearRect(0, 0, width, height);
ctx.strokeStyle = '#e5e7eb';
ctx.lineWidth = 1;
for (var i = 1; i < 4; i++) {
var y = Math.round((height / 4) * i);
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(width, y);
ctx.stroke();
}
series.forEach(function(values, idx){
if (!values.length) return;
var color = colors[idx] || '#2f80ed';
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.beginPath();
if (values.length === 1) {
var singleY = height - (Math.max(0, Math.min(maxValue, number(values[0]))) / maxValue) * (height - 6) - 3;
ctx.moveTo(0, singleY);
ctx.lineTo(width, singleY);
ctx.stroke();
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(width - 8, singleY, 3, 0, Math.PI * 2);
ctx.fill();
return;
}
values.forEach(function(value, i){
var x = values.length <= 1 ? width : (i / (values.length - 1)) * width;
var y = height - (Math.max(0, Math.min(maxValue, number(value))) / maxValue) * (height - 6) - 3;
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
});
ctx.stroke();
});
}
function redraw() {
draw(root.querySelector('[data-chart="cpu_percent"]'), [history.cpu_percent], ['#2f80ed'], 100);
draw(root.querySelector('[data-chart="mem_percent"]'), [history.mem_percent], ['#10b981'], 100);
var netMax = Math.max(1, Math.max.apply(null, history.network_in.concat(history.network_out, [1])));
draw(root.querySelector('[data-chart="network"]'), [history.network_in, history.network_out], ['#2f80ed', '#f59e0b'], netMax);
var ioMax = Math.max(1, Math.max.apply(null, history.disk_read.concat(history.disk_write, [1])));
draw(root.querySelector('[data-chart="diskio"]'), [history.disk_read, history.disk_write], ['#10b981', '#ef4444'], ioMax);
}
function showInfoError(text) {
var debug = document.getElementById('clicd-info-debug');
if (debug) {
debug.style.display = 'block';
debug.textContent = text || 'info load failed';
}
}
function loadInfo() {
var refreshNow = document.getElementById('clicd-info-refresh-now');
if (refreshNow) refreshNow.disabled = true;
var body = new URLSearchParams();
body.set('id', '{$service_id}');
body.set('func', 'infoData');
fetch(endpoint(), {
method:'POST',
headers:{
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
'Authorization':'JWT {$Think.get.jwt}'
},
credentials:'same-origin',
body: body.toString()
})
.then(function(res){ return res.json(); })
.then(function(json){
if (!json || (json.status !== 200 && json.status !== 'success') || !json.data) {
showInfoError(json && json.msg ? json.msg : 'info load failed');
return;
}
var data = json.data;
Object.keys(data).forEach(function(key){ setText(key, data[key]); });
['cpu_percent','mem_percent','load_percent','disk_percent'].forEach(function(key){ setGauge(key, data[key]); });
fitGaugeText();
setProgress('traffic_percent', data.traffic_percent);
push('cpu_percent', data.cpu_percent);
push('mem_percent', data.mem_percent);
push('network_in', data.net_in_bps);
push('network_out', data.net_out_bps);
push('disk_read', data.disk_read_bps);
push('disk_write', data.disk_write_bps);
redraw();
})
.catch(function(error){
showInfoError(error && error.message ? error.message : 'info request failed');
})
.finally(function(){
if (refreshNow) refreshNow.disabled = false;
});
}
loadInfo();
var refreshSelect = document.getElementById('clicd-info-refresh');
var refreshNow = document.getElementById('clicd-info-refresh-now');
if (refreshNow) {
refreshNow.addEventListener('click', loadInfo);
}
if (refreshSelect) {
refreshSelect.addEventListener('change', function(){
if (refreshTimer) {
window.clearInterval(refreshTimer);
refreshTimer = null;
}
var ms = number(refreshSelect.value);
if (ms > 0) {
loadInfo();
refreshTimer = window.setInterval(loadInfo, ms);
}
});
}
window.addEventListener('resize', function(){ window.setTimeout(function(){ fitGaugeText(); redraw(); }, 50); });
})();
</script>
+328
View File
@@ -0,0 +1,328 @@
<style>
.clicd-nat-panel{font-size:14px;color:#1f2937}
.clicd-nat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-bottom:16px}
.clicd-nat-card{border:1px solid #e5e7eb;border-radius:6px;padding:12px;background:#fff}
.clicd-nat-label{color:#6b7280;font-size:12px;margin-bottom:4px}
.clicd-nat-value{font-size:18px;font-weight:600;word-break:break-all}
.clicd-nat-title{font-weight:600;margin:18px 0 8px}
.clicd-nat-muted{color:#6b7280}
.clicd-nat-form{border:1px solid #e5e7eb;border-radius:6px;background:#fff;padding:12px;margin-top:8px}
.clicd-nat-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;align-items:end}
.clicd-nat-field label{display:block;color:#6b7280;font-size:12px;margin-bottom:4px}
.clicd-nat-input,.clicd-nat-select{width:100%;height:34px;border:1px solid #d1d5db;border-radius:4px;padding:6px 8px;box-sizing:border-box}
.clicd-nat-actions{display:flex;gap:8px;flex-wrap:wrap}
.clicd-nat-btn{height:34px;border:1px solid #2563eb;background:#2563eb;color:#fff;border-radius:4px;padding:0 12px;cursor:pointer}
.clicd-nat-btn[disabled]{opacity:.6;cursor:not-allowed}
.clicd-nat-btn-secondary{border-color:#d1d5db;background:#fff;color:#374151}
.clicd-nat-btn-danger{border-color:#dc2626;background:#dc2626;color:#fff}
.clicd-nat-list{display:flex;flex-direction:column;gap:10px;margin-top:8px}
.clicd-nat-item{border:1px solid #e5e7eb;border-radius:6px;background:#fff;padding:12px}
.clicd-nat-message{border:1px solid #bfdbfe;background:#eff6ff;color:#1d4ed8;border-radius:6px;padding:10px 12px;margin-bottom:12px;display:none}
.clicd-nat-message.error{border-color:#fecaca;background:#fef2f2;color:#b91c1c}
.clicd-nat-debug{margin-top:12px;border:1px dashed #d1d5db;border-radius:6px;background:#f9fafb;padding:10px;color:#374151;white-space:pre-wrap;font-size:12px;display:none}
.clicd-nat-modal-mask{position:fixed;inset:0;background:rgba(15,23,42,.42);display:none;align-items:center;justify-content:center;z-index:9999;padding:16px}
.clicd-nat-modal{width:min(420px,100%);background:#fff;border-radius:6px;border:1px solid #e5e7eb;box-shadow:0 18px 48px rgba(15,23,42,.22);padding:16px}
.clicd-nat-modal-title{font-size:16px;font-weight:700;color:#111827;margin-bottom:8px}
.clicd-nat-modal-body{font-size:14px;color:#4b5563;line-height:1.6;margin-bottom:14px}
.clicd-nat-modal-actions{display:flex;justify-content:flex-end;gap:8px}
</style>
<div class="clicd-nat-panel" id="clicd-nat-panel" data-service-id="{$service_id}" data-area-key="{$area_key}">
<div class="clicd-nat-message" id="clicd-nat-message"></div>
<div class="clicd-nat-grid">
<div class="clicd-nat-card">
<div class="clicd-nat-label">&#23454;&#20363;&#21517;&#31216;</div>
<div class="clicd-nat-value">{$container_name}</div>
</div>
<div class="clicd-nat-card">
<div class="clicd-nat-label">&#20844;&#32593;&#22320;&#22336;</div>
<div class="clicd-nat-value">{$nat_host}</div>
</div>
<div class="clicd-nat-card">
<div class="clicd-nat-label">SSH &#31471;&#21475;</div>
<div class="clicd-nat-value">{$ssh_port}</div>
</div>
</div>
<div class="clicd-nat-title">&#28155;&#21152;&#31471;&#21475;&#26144;&#23556;</div>
<div class="clicd-nat-form">
<div class="clicd-nat-row">
<div class="clicd-nat-field">
<label>&#20844;&#32593;&#31471;&#21475;</label>
<input class="clicd-nat-input" id="clicd-add-host-port" type="number" min="1" max="65535" placeholder="61320">
</div>
<div class="clicd-nat-field">
<label>&#23481;&#22120;&#31471;&#21475;</label>
<input class="clicd-nat-input" id="clicd-add-container-port" type="number" min="1" max="65535" placeholder="8080">
</div>
<div class="clicd-nat-field">
<label>&#21327;&#35758;</label>
<select class="clicd-nat-select" id="clicd-add-protocol">
<option value="tcp">TCP</option>
<option value="udp">UDP</option>
</select>
</div>
<div class="clicd-nat-field">
<label>&#35828;&#26126;</label>
<input class="clicd-nat-input" id="clicd-add-description" type="text" placeholder="HTTP">
</div>
<div class="clicd-nat-actions">
<button class="clicd-nat-btn" type="button" data-clicd-action="add">&#28155;&#21152;</button>
<button class="clicd-nat-btn clicd-nat-btn-secondary" type="button" data-clicd-action="random-port">&#33719;&#21462;&#38543;&#26426;&#31471;&#21475;</button>
</div>
</div>
</div>
<div class="clicd-nat-title">&#29616;&#26377;&#31471;&#21475;&#26144;&#23556;</div>
<div id="clicd-nat-list" class="clicd-nat-list">
{if condition="empty($port_mappings)"}
<div class="clicd-nat-form clicd-nat-muted">&#26242;&#26080;&#31471;&#21475;&#26144;&#23556;</div>
{else/}
{foreach name="port_mappings" item="mapping"}
<div class="clicd-nat-item" data-index="{$mapping.index}">
<div class="clicd-nat-row">
<div class="clicd-nat-field">
<label>&#32034;&#24341;</label>
<div class="clicd-nat-value">{$mapping.index}</div>
</div>
<div class="clicd-nat-field">
<label>&#20844;&#32593;&#35775;&#38382;</label>
<div class="clicd-nat-value">{$nat_host}:{$mapping.host_port}</div>
</div>
<div class="clicd-nat-field">
<label>&#20844;&#32593;&#31471;&#21475;</label>
<input class="clicd-nat-input" data-field="host_port" type="number" min="1" max="65535" value="{$mapping.host_port}">
</div>
<div class="clicd-nat-field">
<label>&#23481;&#22120;&#31471;&#21475;</label>
<input class="clicd-nat-input" data-field="container_port" type="number" min="1" max="65535" value="{$mapping.container_port}">
</div>
<div class="clicd-nat-field">
<label>&#21327;&#35758;</label>
<select class="clicd-nat-select" data-field="protocol">
<option value="tcp" {$mapping.tcp_selected}>TCP</option>
<option value="udp" {$mapping.udp_selected}>UDP</option>
</select>
</div>
<div class="clicd-nat-field">
<label>&#35828;&#26126;</label>
<input class="clicd-nat-input" data-field="description" type="text" value="{$mapping.description}">
</div>
<div class="clicd-nat-actions">
<button class="clicd-nat-btn clicd-nat-btn-secondary" type="button" data-clicd-action="update">&#20445;&#23384;</button>
<button class="clicd-nat-btn clicd-nat-btn-danger" type="button" data-clicd-action="delete">&#21024;&#38500;</button>
</div>
</div>
</div>
{/foreach}
{/if}
</div>
<pre class="clicd-nat-debug" id="clicd-nat-debug"></pre>
<div class="clicd-nat-modal-mask" id="clicd-nat-delete-modal">
<div class="clicd-nat-modal">
<div class="clicd-nat-modal-title">&#30830;&#35748;&#21024;&#38500;</div>
<div class="clicd-nat-modal-body" id="clicd-nat-delete-text">&#30830;&#35748;&#21024;&#38500;&#35813;&#31471;&#21475;&#26144;&#23556;&#65311;</div>
<div class="clicd-nat-modal-actions">
<button class="clicd-nat-btn clicd-nat-btn-secondary" type="button" id="clicd-nat-delete-cancel">&#21462;&#28040;</button>
<button class="clicd-nat-btn clicd-nat-btn-danger" type="button" id="clicd-nat-delete-confirm">&#21024;&#38500;</button>
</div>
</div>
</div>
</div>
<script>
(function(){
var panel = document.getElementById('clicd-nat-panel');
if (!panel || panel.getAttribute('data-bound') === '1') return;
panel.setAttribute('data-bound', '1');
var message = document.getElementById('clicd-nat-message');
var debugBox = document.getElementById('clicd-nat-debug');
var list = document.getElementById('clicd-nat-list');
var natHost = '{$nat_host}';
var deleteModal = document.getElementById('clicd-nat-delete-modal');
var deleteText = document.getElementById('clicd-nat-delete-text');
var deleteCancel = document.getElementById('clicd-nat-delete-cancel');
var deleteConfirm = document.getElementById('clicd-nat-delete-confirm');
var pendingDeletePayload = null;
function showMessage(type, text) {
message.className = 'clicd-nat-message' + (type === 'error' ? ' error' : '');
message.style.display = 'block';
message.textContent = text || '';
}
function showDebug(data) {
debugBox.style.display = 'block';
debugBox.textContent = JSON.stringify(data || {}, null, 2);
}
function endpoint() {
return "{$MODULE_CUSTOM_API}";
}
function field(item, name) {
return item.querySelector('[data-field="' + name + '"]');
}
function setBusy(busy) {
panel.querySelectorAll('button').forEach(function(btn){ btn.disabled = !!busy; });
}
function renderList(items) {
if (!Array.isArray(items) || items.length === 0) {
list.innerHTML = '<div class="clicd-nat-form clicd-nat-muted">&#26242;&#26080;&#31471;&#21475;&#26144;&#23556;</div>';
return;
}
list.innerHTML = items.map(function(item) {
var protocol = (item.protocol || 'tcp').toLowerCase();
var desc = escapeHtml(item.description || '');
var index = escapeHtml(String(item.index));
var hostPort = escapeHtml(String(item.host_port || ''));
var containerPort = escapeHtml(String(item.container_port || ''));
return '<div class="clicd-nat-item" data-index="' + index + '">' +
'<div class="clicd-nat-row">' +
'<div class="clicd-nat-field"><label>&#32034;&#24341;</label><div class="clicd-nat-value">' + index + '</div></div>' +
'<div class="clicd-nat-field"><label>&#20844;&#32593;&#35775;&#38382;</label><div class="clicd-nat-value">' + escapeHtml(natHost) + ':' + hostPort + '</div></div>' +
'<div class="clicd-nat-field"><label>&#20844;&#32593;&#31471;&#21475;</label><input class="clicd-nat-input" data-field="host_port" type="number" min="1" max="65535" value="' + hostPort + '"></div>' +
'<div class="clicd-nat-field"><label>&#23481;&#22120;&#31471;&#21475;</label><input class="clicd-nat-input" data-field="container_port" type="number" min="1" max="65535" value="' + containerPort + '"></div>' +
'<div class="clicd-nat-field"><label>&#21327;&#35758;</label><select class="clicd-nat-select" data-field="protocol">' +
'<option value="tcp"' + (protocol === 'tcp' ? ' selected' : '') + '>TCP</option>' +
'<option value="udp"' + (protocol === 'udp' ? ' selected' : '') + '>UDP</option>' +
'</select></div>' +
'<div class="clicd-nat-field"><label>&#35828;&#26126;</label><input class="clicd-nat-input" data-field="description" type="text" value="' + desc + '"></div>' +
'<div class="clicd-nat-actions"><button class="clicd-nat-btn clicd-nat-btn-secondary" type="button" data-clicd-action="update">&#20445;&#23384;</button>' +
'<button class="clicd-nat-btn clicd-nat-btn-danger" type="button" data-clicd-action="delete">&#21024;&#38500;</button></div>' +
'</div></div>';
}).join('');
}
function escapeHtml(value) {
return String(value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
async function request(action, payload, silent) {
setBusy(true);
try {
var funcMap = {
'random-port': 'randomPort',
'add': 'addNat',
'update': 'updateNat',
'delete': 'deleteNat',
'list': 'natList'
};
var body = new URLSearchParams();
body.set('id', panel.getAttribute('data-service-id') || '');
body.set('func', funcMap[action] || action);
Object.keys(payload || {}).forEach(function(key){ body.set(key, payload[key]); });
var res = await fetch(endpoint(), {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Authorization': 'JWT {$Think.get.jwt}'
},
credentials: 'same-origin',
body: body.toString()
});
var text = await res.text();
var data;
try { data = JSON.parse(text); } catch (e) { data = {status:'error', msg:'\u975e JSON \u54cd\u5e94: ' + text}; }
showDebug((data.data && data.data.debug) || data.debug || data);
if (data.status === 200 || data.status === 'success') {
if (!silent) {
showMessage('success', data.msg || '\u64cd\u4f5c\u6210\u529f');
}
if (data.data && data.data.port) {
document.getElementById('clicd-add-host-port').value = data.data.port;
}
if (data.data && Array.isArray(data.data.port_mappings)) {
renderList(data.data.port_mappings);
} else if (action !== 'random-port') {
request('list', {}, true);
}
} else {
showMessage('error', data.msg || '\u64cd\u4f5c\u5931\u8d25');
}
} catch (e) {
showMessage('error', e.message || '\u8bf7\u6c42\u5931\u8d25');
showDebug({error: String(e)});
} finally {
setBusy(false);
}
}
function openDeleteModal(payload) {
pendingDeletePayload = payload;
if (deleteText) {
deleteText.textContent = '\u786e\u8ba4\u5220\u9664\u7aef\u53e3\u6620\u5c04 ' + natHost + ':' + (payload.host_port || '-') + ' -> ' + (payload.container_port || '-') + '/' + (payload.protocol || 'tcp') + ' \u5417\uff1f';
}
if (deleteModal) {
deleteModal.style.display = 'flex';
}
}
function closeDeleteModal() {
pendingDeletePayload = null;
if (deleteModal) {
deleteModal.style.display = 'none';
}
}
panel.addEventListener('click', function(event) {
var button = event.target.closest('[data-clicd-action]');
if (!button) return;
var action = button.getAttribute('data-clicd-action');
if (action === 'random-port') {
request('random-port', {});
return;
}
if (action === 'add') {
request('add', {
host_port: document.getElementById('clicd-add-host-port').value,
container_port: document.getElementById('clicd-add-container-port').value,
protocol: document.getElementById('clicd-add-protocol').value,
description: document.getElementById('clicd-add-description').value
});
return;
}
var item = button.closest('.clicd-nat-item');
if (!item) return;
var payload = {
index: item.getAttribute('data-index'),
host_port: field(item, 'host_port') ? field(item, 'host_port').value : '',
container_port: field(item, 'container_port') ? field(item, 'container_port').value : '',
protocol: field(item, 'protocol') ? field(item, 'protocol').value : 'tcp',
description: field(item, 'description') ? field(item, 'description').value : ''
};
if (action === 'delete') {
openDeleteModal(payload);
return;
}
request(action, payload);
});
if (deleteCancel) {
deleteCancel.addEventListener('click', closeDeleteModal);
}
if (deleteModal) {
deleteModal.addEventListener('click', function(event){
if (event.target === deleteModal) closeDeleteModal();
});
}
if (deleteConfirm) {
deleteConfirm.addEventListener('click', function(){
if (!pendingDeletePayload) return;
var payload = pendingDeletePayload;
closeDeleteModal();
request('delete', payload);
});
}
})();
</script>
+91 -36
View File
@@ -2,66 +2,121 @@
<img src="frontend/public/favicon.svg" width="96" alt="CLICD">
</p>
<h1 align="center">CLICD</h1>
<h1 align="center">CLICD <sub></sub></h1>
<p align="center">
<img alt="Go" src="https://img.shields.io/badge/Go-1.22-00ADD8?style=flat-square&logo=go&logoColor=white">
<img alt="Go" src="https://img.shields.io/badge/Go-1.24-00ADD8?style=flat-square&logo=go&logoColor=white">
<img alt="React" src="https://img.shields.io/badge/React-18-61DAFB?style=flat-square&logo=react&logoColor=111111">
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-5-3178C6?style=flat-square&logo=typescript&logoColor=white">
<img alt="Vite" src="https://img.shields.io/badge/Vite-5-646CFF?style=flat-square&logo=vite&logoColor=white">
<img alt="Tailwind CSS" src="https://img.shields.io/badge/Tailwind_CSS-3-06B6D4?style=flat-square&logo=tailwindcss&logoColor=white">
<img alt="LXC" src="https://img.shields.io/badge/LXC-container-111111?style=flat-square">
<img alt="LXC" src="https://img.shields.io/badge/LXC-Supported-111111?style=flat-square">
<img alt="KVM" src="https://img.shields.io/badge/KVM-Supported-EE0000?style=flat-square">
</p>
CLICD 是一个面向 LXC 的轻量容器管理面板,提供 Web 控制台、CLI、批量任务、镜像管理、NAT 端口、IPv6 分配、WebSSH、资源限制、流量限制和安全告警能力。它适合用来管理小型 VPS 上的 LXC 容器,也适合需要批量创建和分发子用户管理链接的场景。
<p align="center">
<img alt="WebSSH" src="https://img.shields.io/badge/WebSSH-Built--in-009688?style=flat-square">
<img alt="VNC" src="https://img.shields.io/badge/VNC-Supported-7B1FA2?style=flat-square">
<img alt="IPv6" src="https://img.shields.io/badge/IPv6-Native-1976D2?style=flat-square">
<img alt="NAT" src="https://img.shields.io/badge/NAT-Port_Forwarding-FF9800?style=flat-square">
<img alt="REST API" src="https://img.shields.io/badge/API-REST-4CAF50?style=flat-square">
<img alt="Multi User" src="https://img.shields.io/badge/Multi_User-Supported-8E24AA?style=flat-square">
<img alt="Traffic Control" src="https://img.shields.io/badge/Traffic-Control-795548?style=flat-square">
<img alt="Security Alert" src="https://img.shields.io/badge/Security-Alert-orange?style=flat-square">
<img alt="CLI" src="https://img.shields.io/badge/CLI-Mode-424242?style=flat-square">
<img alt="TLS" src="https://img.shields.io/badge/TLS-Let's_Encrypt-003A70?style=flat-square&logo=letsencrypt&logoColor=white">
</p>
## 功能介绍
CLICD is a lightweight virtualization management panel for LXC and KVM. It combines a web console, CLI tools, REST API, NAT/IPv6 networking, WebSSH/WebVNC access, resource quotas, traffic limits, snapshots, delegated sub-user access, and security alerts into a single deployable service.
1. 支持 Ubuntu、Debian、Alpine、CentOS、Arch Linux、Fedora、Rocky Linux 等系统镜像。镜像可以在镜像管理中按需下载;如果宿主机资源比较小,建议优先选择 Alpine 这类轻量镜像
2. 支持 WebSSH 管理,可以在浏览器里一键进入容器终端,不需要手动复制 SSH 密码。
3. 支持设置 NAT4 端口数量、NAT 端口映射和协议限制,并支持分配公网 IPv6。IPv6 分配要求宿主机本身拥有可路由的 IPv6 地址段。
4. 支持单向和双向网络流量限制。达到限制后容器会自动关机,避免流量超额。
5. 支持设置容器有效期。到期后容器会自动关机,子用户无法继续操作,只有管理员重新设置延期日期后才能恢复使用。
6. 内置基于 conntrack 的轻量安全告警。系统不会保存完整正常连接日志,但会对端口扫描、横向扫描、爆破倾向、SMTP 滥用、UDP 反射、挖矿端口、代理/VPN/Tor 等可疑行为生成告警并写入审计日志。
7. 支持子用户管理链接,管理员可以把指定容器分发给拼车用户,子用户只能管理自己被授权的容器。
8. 支持 API 接入,可以通过 API 完成容器、任务、镜像、端口、流量、安全告警等功能的自动化控制。
9. 支持仅使用 CLI 管理。需要关闭 Web 控制台时,可以停止并禁用 systemd 服务,然后使用 `clicd cli --no-web` 进入命令行模式。
CLICD 是一个面向 LXC/KVM 的轻量虚拟化管理面板,集成 Web 控制台、CLI、REST API、NAT/IPv6 网络、WebSSH/WebVNC、资源配额、流量限制、快照、子用户授权和安全告警能力,适合 VPS 商家、实验室、开发者自建虚拟化节点以及需要批量开通容器的场景
## 技术栈
![alt text](/img/image-1.png)
- Backend: Go, net/http, LXC, cgroup v2, iptables, conntrack
- Frontend: React, TypeScript, Vite, Tailwind CSS, lucide-react, xterm.js
- Runtime: Linux, systemd, LXC
- Build: GitHub Actions, Node.js 20, Go 1.22
## Installation / 安装
## 安装
一键安装:
One-click Install / 一键安装:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh | sudo sh
```
一键卸载:
One-click Uninstall / 一键卸载:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh | sudo sh -s -- uninstall
```
![alt text](/img/image.png)
![alt text](/img/image-1.png)
## Features / 功能介绍
### English
| Area | What CLICD provides |
| --- | --- |
| Virtualization | Manage LXC containers and KVM virtual machines from one panel, including create, reinstall, start, stop, restart, delete, password reset, expiry control, and batch actions. |
| Images and templates | Built-in template and image management for Ubuntu, Debian, Alpine, CentOS, Arch Linux, Fedora, Rocky Linux, and other common distributions. Images can be enabled, disabled, downloaded, cancelled, or removed from cache. |
| Networking | NAT4 port quotas, random available port allocation, TCP/UDP port mappings, public IPv4 pool management, IPv6 prefix detection, IPv6 status checks, and per-container IPv6 assignment. |
| Resource control | CPU, memory, disk, swap, bandwidth usage, traffic reset, traffic limit, and resource limit management, with automatic shutdown behavior for expired or over-quota containers. |
| Console access | Browser-based WebSSH and WebVNC ticket access, so users can open terminals or consoles without manually exchanging credentials. |
| Snapshots | Snapshot overview, per-container snapshots, create/delete/restore operations, scheduled snapshots, and quota controls. |
| Security | Conntrack-based security alerts for port scans, lateral scans, brute-force behavior, SMTP abuse, UDP reflection, mining ports, proxy/VPN/Tor usage, plus security logs, summaries, and configurable settings. |
| Accounts and audit | Delegated sub-user links, sub-user password rotation, per-user container permissions, audit logs, login logs, and API key management. |
| Automation | Versioned REST API under `/api/v1`, task queue endpoints, batch create/action endpoints, and a Mofang finance integration module packaged automatically by GitHub Actions. |
| Operations | Dashboard statistics, host resource overview, routing overview, swap management, CLI-only mode, and release artifacts generated by GitHub Actions. |
### 中文
| 模块 | CLICD 提供的能力 |
| --- | --- |
| 虚拟化管理 | 在同一个面板里管理 LXC 容器和 KVM 虚拟机,支持创建、重装、开机、关机、重启、删除、重置密码、到期时间和批量操作。 |
| 镜像与模板 | 内置模板和镜像管理,支持 Ubuntu、Debian、Alpine、CentOS、Arch Linux、Fedora、Rocky Linux 等常见发行版,镜像可按需下载、取消、启用、禁用和清理缓存。 |
| 网络能力 | 支持 NAT4 端口配额、随机可用端口、TCP/UDP 端口映射、公网 IPv4 池管理、IPv6 前缀检测、IPv6 状态检查和容器级 IPv6 分配。 |
| 资源限制 | 支持 CPU、内存、磁盘、Swap、独立上行/下行带宽、读/写 I/O 限速、流量重置、流量限制和资源限制管理;容器到期或超额后可自动关机,避免资源和流量失控。 |
| 远程控制 | 内置 WebSSH 和 WebVNC 票据访问,用户可以直接在浏览器打开终端或控制台,不需要手动复制连接信息。 |
| 快照能力 | 支持快照总览、容器快照、创建快照、删除快照、恢复快照、计划快照和快照配额。 |
| 安全告警 | 基于 conntrack 做轻量安全检测,可识别端口扫描、横向扫描、爆破倾向、SMTP 滥用、UDP 反射、挖矿端口、代理/VPN/Tor 等风险,并提供安全日志、汇总和设置项。 |
| 账号与审计 | 支持子用户管理链接、子用户密码轮换、按容器授权、操作日志、登录日志和 API Key 管理,适合分发给下游用户或拼车用户。 |
| 自动化接入 | 全量接口统一使用 `/api/v1`,覆盖任务队列、容器、镜像、网络、流量、安全、批量创建和批量操作;同时提供魔方财务对接模块,并由 GitHub Actions 自动打包发布。 |
| 运维入口 | 提供总览统计、主机资源、路由概览、Swap 管理、CLI-only 模式和 GitHub Actions 自动发布产物,便于在小型节点上长期维护。 |
## Technology Stack / 技术栈
- Backend: Go, net/http, LXC, KVM/libvirt, cgroup v2, iptables, conntrack
- Frontend: React, TypeScript, Vite, Tailwind CSS, lucide-react, xterm.js
- Runtime: Linux, systemd, LXC, KVM/QEMU
- Build: GitHub Actions, Node.js 20, Go 1.24
## Preview / 预览
![alt text](/img/image-2.png)
![alt text](/img/image-3.png)
![alt text](/img/image-4.png)
![alt text](/img/image-5.png)
## Disclaimer/免责声明
This open-source software does not distribute Windows system images, nor does it provide any means to bypass or circumvent Windows activation mechanisms.
All download links provided within the software point to resources officially supplied by Microsoft. Users of this software are responsible for obtaining the appropriate licenses from Microsoft before using any Windows operating system downloaded through these links. This project does not bypass activation requirements for installed systems, nor does it assume any responsibility for the consequences of users' actions when using this software.
This open-source software is intended solely for educational purposes, specifically for learning the principles of LXC and KVM. The copyright for the Windows logo and related icons belongs to Microsoft/Windows.
本开源软件不提供任何 Windows 操作系统镜像的分发服务,也不包含任何绕过、破解或免除 Windows 激活机制的功能。
软件内涉及的 Windows 系统下载链接均由微软官方提供。使用者在下载、安装和使用相关 Windows 系统时,应自行向微软或其授权渠道购买并获得相应的软件许可。本项目不会对安装后的 Windows 系统进行任何形式的激活绕过、破解或免激活处理。
对于使用者因使用本软件而产生的任何行为及其后果,包括但不限于软件许可、系统使用、数据丢失、法律责任或其他相关问题,本项目及其开发者不承担任何责任。
本开源软件仅供学习和研究 LXC、KVM 等虚拟化技术原理之目的使用,不得用于任何违反适用法律法规、软件许可协议或第三方权益的行为。
本软件中涉及的 Windows 名称、标识、图标及相关知识产权均归 Microsoft Corporation 及其权利人所有。本项目与微软公司不存在任何关联、授权或合作关系。
## Thanks / 鸣谢
- [Nodeseek.com](https://www.nodeseek.com) — 一个专注于服务器的社区
- [Linux.do](https://linux.do) — 一个充满灵感的科技社区
## Star History
<a href="https://www.star-history.com/?repos=MengMengCode%2FCLICD&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=MengMengCode/CLICD&type=date&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=MengMengCode/CLICD&type=date&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=MengMengCode/CLICD&type=date&legend=top-left" />
</picture>
</a>
## 鸣谢
- [Linux.do](https://linux.do) — 一个充满灵感的科技社区
[![MengMengCode/CLICD Star History](http://mengmeng.meteor-history.com/api/embed/MengMengCode/CLICD.svg?sig=YT8i1bxihL6_GcFAa0CWRbQb35-B0XXyh-ZAxIsmV0U&theme=light&style=xkcd&color=dd4528&background=ffffff&textColor=000000&width=900&height=600&lineWidth=3&showTitle=true&showLegend=true&showDots=false&v=3)](https://meteor-history.com)
+24 -5
View File
@@ -1,12 +1,31 @@
module clicd
go 1.22.0
go 1.25.0
require (
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/golang-jwt/jwt/v5 v5.2.2
github.com/gorilla/websocket v1.5.3
golang.org/x/crypto v0.28.0
golang.org/x/term v0.28.0
golang.org/x/crypto v0.52.0
golang.org/x/term v0.43.0
)
require golang.org/x/sys v0.29.0 // indirect
require (
golang.org/x/sys v0.45.0
modernc.org/sqlite v1.29.10
)
require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 // indirect
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
modernc.org/libc v1.61.13 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.8.2 // indirect
modernc.org/strutil v1.2.1 // indirect
modernc.org/token v1.1.0 // indirect
)
+59 -8
View File
@@ -1,10 +1,61 @@
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw=
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg=
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 h1:mchzmB1XO2pMaKFRqk/+MV3mgGG96aqaPXaMifQU47w=
golang.org/x/exp v0.0.0-20231108232855-2478ac86f678/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE=
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg=
golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
modernc.org/cc/v4 v4.24.4 h1:TFkx1s6dCkQpd6dKurBNmpo+G8Zl4Sq/ztJ+2+DEsh0=
modernc.org/cc/v4 v4.24.4/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/ccgo/v4 v4.23.16 h1:Z2N+kk38b7SfySC1ZkpGLN2vthNJP1+ZzGZIlH7uBxo=
modernc.org/ccgo/v4 v4.23.16/go.mod h1:nNma8goMTY7aQZQNTyN9AIoJfxav4nvTnvKThAeMDdo=
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
modernc.org/gc/v2 v2.6.3 h1:aJVhcqAte49LF+mGveZ5KPlsp4tdGdAOT4sipJXADjw=
modernc.org/gc/v2 v2.6.3/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI=
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=
modernc.org/libc v1.61.13 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8=
modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.8.2 h1:cL9L4bcoAObu4NkxOlKWBWtNHIsnnACGF/TbqQ6sbcI=
modernc.org/memory v1.8.2/go.mod h1:ZbjSvMO5NQ1A2i3bWeDiVMxIorXwdClKE/0SZ+BMotU=
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.29.10 h1:3u93dz83myFnMilBGCOLbr+HjklS6+5rJLx4q86RDAg=
modernc.org/sqlite v1.29.10/go.mod h1:ItX2a1OVGgNsFh6Dv60JQvGfJfTPHPVpV6DF59akYOA=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
+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"
}
+363 -124
View File
@@ -2,122 +2,293 @@ package api
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"time"
"clicd/internal/config"
"golang.org/x/crypto/argon2"
)
type ApiKey struct {
ID string `json:"id"`
Name string `json:"name"`
Key string `json:"key,omitempty"`
Prefix string `json:"prefix"`
IPWhitelist string `json:"ip_whitelist"`
CreatedAt string `json:"created_at"`
LastUsed string `json:"last_used"`
ID string `json:"id"`
Name string `json:"name"`
Key string `json:"key,omitempty"`
Prefix string `json:"prefix"`
IPWhitelist string `json:"ip_whitelist"`
CreatedAt string `json:"created_at"`
LastUsed string `json:"last_used"`
Scopes []string `json:"scopes,omitempty"`
ExpiresAt string `json:"expires_at,omitempty"`
Disabled bool `json:"disabled,omitempty"`
ContainerUUIDs []string `json:"container_uuids,omitempty"`
LastUsedIP string `json:"last_used_ip,omitempty"`
}
type apiKeyRequest struct {
Name string `json:"name"`
IPWhitelist string `json:"ip_whitelist"`
Scopes []string `json:"scopes"`
ExpiresAt string `json:"expires_at"`
Disabled bool `json:"disabled"`
ContainerUUIDs []string `json:"container_uuids"`
}
var defaultApiKeyScopes = []string{
"dashboard:read",
"container:read",
"task:read",
"image:read",
"snapshot:read",
"routing:read",
"ipv6:read",
"host:read",
}
// HandleApiKeys handles GET (list) and POST (create) for API keys
func HandleApiKeys(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
if !requireScope(w, r, "apikey:read") {
return
}
listApiKeys(w, r)
case http.MethodPost:
if !requireScope(w, r, "apikey:create") {
return
}
createApiKey(w, r)
default:
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
}
}
// HandleApiKeyDelete handles DELETE for a specific API key
// HandleApiKeyDelete handles PATCH and DELETE for a specific API key
func HandleApiKeyDelete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
switch r.Method {
case http.MethodPatch:
if !requireScope(w, r, "apikey:update") {
return
}
updateApiKey(w, r)
case http.MethodDelete:
if !requireScope(w, r, "apikey:delete") {
return
}
deleteApiKey(w, r)
default:
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
keyID := strings.TrimPrefix(r.URL.Path, "/api/api-keys/")
if keyID == "" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Key ID required"})
return
}
config.DeleteApiKey(keyID)
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "API key deleted"})
}
func apiKeyIDFromPath(path string) string {
path = strings.TrimPrefix(path, "/api/api-keys/")
path = strings.TrimPrefix(path, "/api/v1/api-keys/")
return strings.Trim(path, "/")
}
func listApiKeys(w http.ResponseWriter, r *http.Request) {
keys := make([]ApiKey, 0)
for _, k := range config.AppConfig.ApiKeys {
keys = append(keys, ApiKey{
ID: k.ID,
Name: k.Name,
Prefix: k.Prefix,
IPWhitelist: k.IPWhitelist,
CreatedAt: k.CreatedAt,
LastUsed: k.LastUsed,
})
keys = append(keys, apiKeyResponse(k))
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: keys})
}
func createApiKey(w http.ResponseWriter, r *http.Request) {
var req struct {
Name string `json:"name"`
IPWhitelist string `json:"ip_whitelist"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Name == "" {
var req apiKeyRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Name) == "" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Name is required"})
return
}
if req.ExpiresAt != "" && !validApiKeyTime(req.ExpiresAt) {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid expiration date"})
return
}
// Generate key: clicd_sk_ + 32 hex chars
rawBytes := make([]byte, 16)
rand.Read(rawBytes)
if _, err := rand.Read(rawBytes); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to generate API key"})
return
}
rawKey := "clicd_sk_" + hex.EncodeToString(rawBytes)
keyHash, err := hashAPIKey(rawKey)
if err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to store API key"})
return
}
now := time.Now().Format("2006-01-02 15:04:05")
scopes := normalizeRequestedScopes(req.Scopes, defaultApiKeyScopes)
key := config.ApiKeyConfig{
ID: generateShortID(),
Name: req.Name,
KeyHash: hashKey(rawKey),
Prefix: rawKey[:13] + "...",
IPWhitelist: strings.TrimSpace(req.IPWhitelist),
CreatedAt: now,
ID: generateShortID(),
Name: strings.TrimSpace(req.Name),
KeyHash: keyHash,
Prefix: rawKey[:13] + "...",
IPWhitelist: strings.TrimSpace(req.IPWhitelist),
CreatedAt: now,
Scopes: scopes,
ExpiresAt: strings.TrimSpace(req.ExpiresAt),
Disabled: req.Disabled,
ContainerUUIDs: normalizeStringSlice(req.ContainerUUIDs),
}
config.AppConfig.ApiKeys = append(config.AppConfig.ApiKeys, key)
config.SaveConfig()
if err := config.SaveConfig(); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to save API key"})
return
}
auditRequest(r, "apikey.create", key.Name, "scopes="+strings.Join(key.Scopes, ","), true, "")
resp := apiKeyResponse(key)
resp.Key = rawKey
jsonResponse(w, http.StatusCreated, APIResponse{
Success: true,
Message: "API key created. Save this key now - it won't be shown again.",
Data: ApiKey{
ID: key.ID,
Name: key.Name,
Key: rawKey,
Prefix: key.Prefix,
IPWhitelist: key.IPWhitelist,
CreatedAt: key.CreatedAt,
},
Data: resp,
})
}
func updateApiKey(w http.ResponseWriter, r *http.Request) {
keyID := apiKeyIDFromPath(r.URL.Path)
if keyID == "" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Key ID required"})
return
}
var req apiKeyRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
if req.ExpiresAt != "" && !validApiKeyTime(req.ExpiresAt) {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid expiration date"})
return
}
for i := range config.AppConfig.ApiKeys {
if config.AppConfig.ApiKeys[i].ID != keyID {
continue
}
if strings.TrimSpace(req.Name) != "" {
config.AppConfig.ApiKeys[i].Name = strings.TrimSpace(req.Name)
}
config.AppConfig.ApiKeys[i].IPWhitelist = strings.TrimSpace(req.IPWhitelist)
if len(req.Scopes) > 0 {
config.AppConfig.ApiKeys[i].Scopes = normalizeStringSlice(req.Scopes)
}
config.AppConfig.ApiKeys[i].ExpiresAt = strings.TrimSpace(req.ExpiresAt)
config.AppConfig.ApiKeys[i].Disabled = req.Disabled
config.AppConfig.ApiKeys[i].ContainerUUIDs = normalizeStringSlice(req.ContainerUUIDs)
if err := config.SaveConfig(); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to save API key"})
return
}
auditRequest(r, "apikey.update", config.AppConfig.ApiKeys[i].Name, "scopes="+strings.Join(config.AppConfig.ApiKeys[i].Scopes, ","), true, "")
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: apiKeyResponse(config.AppConfig.ApiKeys[i])})
return
}
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "API key not found"})
}
func deleteApiKey(w http.ResponseWriter, r *http.Request) {
keyID := apiKeyIDFromPath(r.URL.Path)
if keyID == "" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Key ID required"})
return
}
name := keyID
for _, k := range config.AppConfig.ApiKeys {
if k.ID == keyID {
name = k.Name
break
}
}
config.DeleteApiKey(keyID)
auditRequest(r, "apikey.delete", name, "", true, "")
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "API key deleted"})
}
func apiKeyResponse(k config.ApiKeyConfig) ApiKey {
return ApiKey{
ID: k.ID,
Name: k.Name,
Prefix: k.Prefix,
IPWhitelist: k.IPWhitelist,
CreatedAt: k.CreatedAt,
LastUsed: k.LastUsed,
Scopes: normalizeApiKeyScopes(k.Scopes),
ExpiresAt: k.ExpiresAt,
Disabled: k.Disabled,
ContainerUUIDs: k.ContainerUUIDs,
LastUsedIP: k.LastUsedIP,
}
}
func generateShortID() string {
b := make([]byte, 4)
rand.Read(b)
return hex.EncodeToString(b)
}
// hashKey creates a simple hash for storage (not reversible)
func hashKey(key string) string {
sum := sha256.Sum256([]byte(key))
return hex.EncodeToString(sum[:])
const (
apiKeyHashPrefix = "argon2id"
apiKeyHashTime = uint32(3)
apiKeyHashMemory = uint32(64 * 1024)
apiKeyHashThreads = uint8(1)
apiKeyHashSaltLength = 16
apiKeyHashKeyLength = uint32(32)
)
// hashAPIKey stores API keys using a salted slow password-hash style function.
func hashAPIKey(key string) (string, error) {
salt := make([]byte, apiKeyHashSaltLength)
if _, err := rand.Read(salt); err != nil {
return "", err
}
return hashAPIKeyWithSalt(key, salt), nil
}
func hashAPIKeyWithSalt(key string, salt []byte) string {
digest := argon2.IDKey([]byte(key), salt, apiKeyHashTime, apiKeyHashMemory, apiKeyHashThreads, apiKeyHashKeyLength)
return fmt.Sprintf("%s$v=19$m=%d,t=%d,p=%d$%s$%s",
apiKeyHashPrefix,
apiKeyHashMemory,
apiKeyHashTime,
apiKeyHashThreads,
hex.EncodeToString(salt),
hex.EncodeToString(digest),
)
}
func verifyAPIKeyHash(rawKey, storedHash string) bool {
parts := strings.Split(storedHash, "$")
if len(parts) != 5 || parts[0] != apiKeyHashPrefix || parts[1] != "v=19" {
return false
}
var memory, iterations uint32
var threads uint8
if _, err := fmt.Sscanf(parts[2], "m=%d,t=%d,p=%d", &memory, &iterations, &threads); err != nil {
return false
}
if memory != apiKeyHashMemory || iterations != apiKeyHashTime || threads != apiKeyHashThreads {
return false
}
salt, err := hex.DecodeString(parts[3])
if err != nil || len(salt) == 0 {
return false
}
expected, err := hex.DecodeString(parts[4])
if err != nil || len(expected) == 0 {
return false
}
digest := argon2.IDKey([]byte(rawKey), salt, iterations, memory, threads, uint32(len(expected)))
return subtle.ConstantTimeCompare(digest, expected) == 1
}
func legacyHashKey(key string) string {
@@ -128,20 +299,75 @@ func legacyHashKey(key string) string {
return hex.EncodeToString(b)
}
// validateApiKey checks if the given key is valid and IP is allowed
func validateApiKey(rawKey, clientIP string) bool {
hashed := hashKey(rawKey)
func matchApiKey(rawKey string) (idx int, needsRehash bool) {
legacyHashed := legacyHashKey(rawKey)
for _, k := range config.AppConfig.ApiKeys {
if subtle.ConstantTimeCompare([]byte(k.KeyHash), []byte(hashed)) == 1 ||
subtle.ConstantTimeCompare([]byte(k.KeyHash), []byte(legacyHashed)) == 1 {
if k.IPWhitelist == "" {
return true
}
return isIPAllowed(clientIP, k.IPWhitelist)
for i, k := range config.AppConfig.ApiKeys {
if verifyAPIKeyHash(rawKey, k.KeyHash) {
return i, false
}
if subtle.ConstantTimeCompare([]byte(k.KeyHash), []byte(legacyHashed)) == 1 {
return i, true
}
}
return false
return -1, false
}
// validateApiKey checks if the given key is valid and IP is allowed.
func validateApiKey(rawKey, clientIP string) bool {
_, ok := validateApiKeyDetails(rawKey, clientIP)
return ok
}
func validateApiKeyDetails(rawKey, clientIP string) (*config.ApiKeyConfig, bool) {
idx, needsRehash := matchApiKey(rawKey)
if idx < 0 {
return nil, false
}
k := &config.AppConfig.ApiKeys[idx]
if k.Disabled || apiKeyExpired(k.ExpiresAt) {
return nil, false
}
if clientIP != "" && k.IPWhitelist != "" && !isIPAllowed(clientIP, k.IPWhitelist) {
return nil, false
}
if needsRehash {
if newHash, err := hashAPIKey(rawKey); err == nil {
config.AppConfig.ApiKeys[idx].KeyHash = newHash
config.SaveConfig()
}
}
if len(k.Scopes) == 0 {
k.Scopes = []string{"*"}
}
return k, true
}
func validateApiKeyRequest(r *http.Request) (*config.ApiKeyConfig, bool) {
apiKey := apiKeyFromRequest(r)
if apiKey == "" {
return nil, false
}
key, ok := validateApiKeyDetails(apiKey, clientIP(r))
if !ok {
return nil, false
}
updateApiKeyLastUsedForKey(key, clientIP(r))
return key, true
}
func authContextFromAPIKey(key *config.ApiKeyConfig) AuthContext {
actor := "api:" + key.ID
if key.Name != "" {
actor = "api:" + key.Name
}
return AuthContext{
Type: authTypeAPIKey,
ApiKeyID: key.ID,
ApiKeyName: key.Name,
Actor: actor,
Scopes: normalizeApiKeyScopes(key.Scopes),
ContainerUUIDs: key.ContainerUUIDs,
}
}
func apiKeyFromRequest(r *http.Request) string {
@@ -156,23 +382,16 @@ func apiKeyFromRequest(r *http.Request) string {
}
func isValidApiKeyRequest(r *http.Request) bool {
apiKey := apiKeyFromRequest(r)
if apiKey == "" {
return false
}
if !validateApiKey(apiKey, clientIP(r)) {
return false
}
updateApiKeyLastUsed(apiKey)
return true
_, ok := validateApiKeyRequest(r)
return ok
}
// isIPAllowed checks if clientIP matches any entry in the whitelist
func isIPAllowed(clientIP, whitelist string) bool {
clientIP = strings.TrimSpace(clientIP)
// Strip port if present
if idx := strings.LastIndex(clientIP, ":"); idx > strings.LastIndex(clientIP, "]") {
clientIP = clientIP[:idx]
clientIP = normalizeIPString(clientIP)
client := net.ParseIP(clientIP)
if client == nil {
return false
}
for _, entry := range strings.Split(whitelist, "\n") {
entry = strings.TrimSpace(entry)
@@ -180,77 +399,97 @@ func isIPAllowed(clientIP, whitelist string) bool {
continue
}
if strings.Contains(entry, "/") {
// CIDR match
if ipInCIDR(clientIP, entry) {
_, network, err := net.ParseCIDR(entry)
if err == nil && network.Contains(client) {
return true
}
} else if entry == clientIP {
continue
}
if allowed := net.ParseIP(normalizeIPString(entry)); allowed != nil && allowed.Equal(client) {
return true
}
}
return false
}
func ipInCIDR(ipStr, cidr string) bool {
parts := strings.Split(cidr, "/")
if len(parts) != 2 {
return false
}
// Simple prefix match for IPv4
ip := netParseIP(ipStr)
cidrIP := netParseIP(parts[0])
if ip == nil || cidrIP == nil {
return false
}
bits, err := strconv.Atoi(parts[1])
if err != nil || bits < 0 || bits > 32 {
return false
}
mask := uint32(0xFFFFFFFF) << (32 - bits)
ipVal := ip4ToUint32(ip)
cidrVal := ip4ToUint32(cidrIP)
return (ipVal & mask) == (cidrVal & mask)
}
func netParseIP(s string) net.IP {
func normalizeIPString(s string) string {
s = strings.TrimSpace(s)
if idx := strings.LastIndex(s, ":"); idx > strings.LastIndex(s, "]") {
s = s[:idx]
if host, _, err := net.SplitHostPort(s); err == nil {
return strings.Trim(host, "[]")
}
return net.ParseIP(s)
return strings.Trim(s, "[]")
}
func ip4ToUint32(ip net.IP) uint32 {
ip = ip.To4()
if ip == nil {
return 0
}
return uint32(ip[0])<<24 | uint32(ip[1])<<16 | uint32(ip[2])<<8 | uint32(ip[3])
func ipInCIDR(ipStr, cidr string) bool {
ip := net.ParseIP(normalizeIPString(ipStr))
_, network, err := net.ParseCIDR(cidr)
return err == nil && ip != nil && network.Contains(ip)
}
// updateApiKeyLastUsed marks the key as recently used
// updateApiKeyLastUsed marks the key as recently used.
func updateApiKeyLastUsed(rawKey string) {
hashed := hashKey(rawKey)
now := time.Now().Format("2006-01-02 15:04:05")
for i := range config.AppConfig.ApiKeys {
if config.AppConfig.ApiKeys[i].KeyHash == hashed {
config.AppConfig.ApiKeys[i].LastUsed = now
config.SaveConfig()
return
}
key, ok := validateApiKeyDetails(rawKey, "")
if !ok {
return
}
updateApiKeyLastUsedForKey(key, "")
}
func updateApiKeyLastUsedForKey(key *config.ApiKeyConfig, ip string) {
key.LastUsed = time.Now().Format("2006-01-02 15:04:05")
if ip != "" {
key.LastUsedIP = ip
}
config.SaveConfig()
}
// ApiKeyMiddleware authenticates requests via X-API-Key header or Authorization bearer.
func ApiKeyMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
apiKey := apiKeyFromRequest(r)
if apiKey == "" || !validateApiKey(apiKey, clientIP(r)) {
key, ok := validateApiKeyRequest(r)
if !ok {
jsonResponse(w, http.StatusUnauthorized, APIResponse{Success: false, Message: "Invalid API key or IP not in whitelist"})
return
}
updateApiKeyLastUsed(apiKey)
next(w, r)
next(w, withAuthContext(r, authContextFromAPIKey(key)))
}
}
func normalizeApiKeyScopes(scopes []string) []string {
return normalizeRequestedScopes(scopes, []string{"*"})
}
func normalizeRequestedScopes(scopes []string, fallback []string) []string {
result := normalizeStringSlice(scopes)
if len(result) == 0 {
return append([]string(nil), fallback...)
}
return result
}
func normalizeStringSlice(values []string) []string {
seen := map[string]bool{}
result := make([]string, 0, len(values))
for _, value := range values {
value = strings.TrimSpace(value)
if value == "" || seen[value] {
continue
}
seen[value] = true
result = append(result, value)
}
return result
}
func validApiKeyTime(value string) bool {
_, err := time.ParseInLocation("2006-01-02 15:04:05", value, time.Local)
return err == nil
}
func apiKeyExpired(value string) bool {
if strings.TrimSpace(value) == "" {
return false
}
expiresAt, err := time.ParseInLocation("2006-01-02 15:04:05", value, time.Local)
return err == nil && !time.Now().Before(expiresAt)
}
+102
View File
@@ -0,0 +1,102 @@
package api
import (
"strings"
"testing"
"clicd/internal/config"
)
func TestHashAPIKeyUsesSaltedArgon2idHash(t *testing.T) {
raw := "clicd_sk_0123456789abcdef0123456789abcdef"
h1, err := hashAPIKey(raw)
if err != nil {
t.Fatal(err)
}
h2, err := hashAPIKey(raw)
if err != nil {
t.Fatal(err)
}
if h1 == h2 {
t.Fatal("expected salted hashes to differ")
}
if !strings.HasPrefix(h1, apiKeyHashPrefix+"$") || !strings.HasPrefix(h2, apiKeyHashPrefix+"$") {
t.Fatalf("expected argon2id hashes, got %q and %q", h1, h2)
}
if !verifyAPIKeyHash(raw, h1) || !verifyAPIKeyHash(raw, h2) {
t.Fatal("argon2id hashes did not verify")
}
if verifyAPIKeyHash(raw+"x", h1) {
t.Fatal("argon2id hash verified wrong key")
}
}
func TestValidateApiKeyAllowsArgon2idAndUpdatesLastUsed(t *testing.T) {
raw := "clicd_sk_0123456789abcdef0123456789abcdef"
hash, err := hashAPIKey(raw)
if err != nil {
t.Fatal(err)
}
config.AppConfig = &config.ClicdConfig{
ApiKeys: []config.ApiKeyConfig{{
ID: "key1",
Name: "test",
KeyHash: hash,
}},
}
if !validateApiKey(raw, "127.0.0.1") {
t.Fatal("validateApiKey rejected valid argon2id key")
}
updateApiKeyLastUsed(raw)
if config.AppConfig.ApiKeys[0].LastUsed == "" {
t.Fatal("LastUsed was not updated")
}
}
func TestValidateApiKeyMigratesLegacyHash(t *testing.T) {
raw := "clicd_sk_0123456789abcdef0123456789abcdef"
config.AppConfig = &config.ClicdConfig{
ApiKeys: []config.ApiKeyConfig{{
ID: "legacy",
Name: "legacy",
KeyHash: legacyHashKey(raw),
}},
}
if !validateApiKey(raw, "127.0.0.1") {
t.Fatal("validateApiKey rejected valid legacy key")
}
migrated := config.AppConfig.ApiKeys[0].KeyHash
if migrated == legacyHashKey(raw) {
t.Fatal("legacy key hash was not migrated")
}
if !verifyAPIKeyHash(raw, migrated) {
t.Fatal("migrated key hash does not verify")
}
}
func TestValidateApiKeyAppliesIPWhitelist(t *testing.T) {
raw := "clicd_sk_0123456789abcdef0123456789abcdef"
hash, err := hashAPIKey(raw)
if err != nil {
t.Fatal(err)
}
config.AppConfig = &config.ClicdConfig{
ApiKeys: []config.ApiKeyConfig{{
ID: "key1",
Name: "test",
KeyHash: hash,
IPWhitelist: "192.0.2.10",
}},
}
if validateApiKey(raw, "198.51.100.10") {
t.Fatal("validateApiKey allowed disallowed IP")
}
if !validateApiKey(raw, "192.0.2.10") {
t.Fatal("validateApiKey rejected allowed IP")
}
}
+165 -4
View File
@@ -1,6 +1,7 @@
package api
import (
"context"
"encoding/json"
"net/http"
"strings"
@@ -28,6 +29,132 @@ type APIResponse struct {
Data interface{} `json:"data,omitempty"`
}
type authContextKey struct{}
type AuthContext struct {
Type string
Username string
ApiKeyID string
ApiKeyName string
Actor string
Scopes []string
ContainerUUIDs []string
}
const (
authTypeAdmin = "admin"
authTypeSubUser = "sub_user"
authTypeAPIKey = "api_key"
)
func withAuthContext(r *http.Request, auth AuthContext) *http.Request {
return r.WithContext(context.WithValue(r.Context(), authContextKey{}, auth))
}
func authContextFromRequest(r *http.Request) (AuthContext, bool) {
ctx, ok := r.Context().Value(authContextKey{}).(AuthContext)
return ctx, ok
}
func requestActor(r *http.Request) string {
if ctx, ok := authContextFromRequest(r); ok && ctx.Actor != "" {
return ctx.Actor
}
if claims, ok := claimsFromRequest(r); ok {
if subUser, _ := claims["sub_user"].(string); subUser != "" {
return "user:" + subUser
}
if username, _ := claims["username"].(string); username != "" {
return username
}
}
return "admin"
}
func hasScope(r *http.Request, scope string) bool {
ctx, ok := authContextFromRequest(r)
if !ok {
return true
}
switch ctx.Type {
case authTypeAdmin:
return true
case authTypeSubUser:
return subUserScopeAllowed(scope)
case authTypeAPIKey:
return scopeAllowed(ctx.Scopes, scope)
default:
return false
}
}
func subUserScopeAllowed(scope string) bool {
switch scope {
case "container:read", "container:power", "container:reinstall", "container:password", "container:network",
"dashboard:read", "image:read", "task:read", "snapshot:read", "snapshot:create", "snapshot:delete", "snapshot:restore", "snapshot:schedule",
"terminal:ssh", "terminal:vnc":
return true
default:
return false
}
}
func hasAnyScope(r *http.Request, scopes ...string) bool {
for _, scope := range scopes {
if hasScope(r, scope) {
return true
}
}
return false
}
func scopeAllowed(scopes []string, required string) bool {
for _, scope := range scopes {
scope = strings.TrimSpace(scope)
if scope == "*" || scope == "admin:*" || scope == required {
return true
}
if strings.HasSuffix(scope, ":*") {
prefix := strings.TrimSuffix(scope, "*")
if strings.HasPrefix(required, prefix) {
return true
}
}
}
return false
}
func requireScope(w http.ResponseWriter, r *http.Request, scope string) bool {
if hasScope(r, scope) {
return true
}
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Insufficient API key scope"})
return false
}
func ScopeMiddleware(scope string, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !requireScope(w, r, scope) {
return
}
next(w, r)
}
}
func AnyScopeMiddleware(scopes []string, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if hasAnyScope(r, scopes...) {
next(w, r)
return
}
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Insufficient API key scope"})
}
}
func auditRequest(r *http.Request, action, target, detail string, success bool, errMsg string) {
config.AddAuditLogFull(action, target, detail, requestActor(r), clientIP(r), r.UserAgent(), success, errMsg)
}
func jsonResponse(w http.ResponseWriter, status int, resp APIResponse) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
@@ -75,8 +202,10 @@ func claimsFromToken(tokenString string) (jwt.MapClaims, bool) {
if subUser, _ := claims["sub_user"].(string); subUser != "" {
tokenVersionFloat, hasVersion := claims["token_version"].(float64)
tokenVersion := int(tokenVersionFloat)
foundSubUser := false
for i := range config.AppConfig.SubUsers {
if config.AppConfig.SubUsers[i].Username == subUser {
foundSubUser = true
stored := config.AppConfig.SubUsers[i].TokenVersion
// If stored version > 0, require token_version to match exactly.
// This also rejects legacy tokens that lack token_version entirely.
@@ -86,6 +215,9 @@ func claimsFromToken(tokenString string) (jwt.MapClaims, bool) {
break
}
}
if !foundSubUser {
return nil, false
}
}
return claims, ok
@@ -96,6 +228,9 @@ func claimsFromRequest(r *http.Request) (jwt.MapClaims, bool) {
}
func isSubUserRequest(r *http.Request) bool {
if ctx, ok := authContextFromRequest(r); ok {
return ctx.Type == authTypeSubUser
}
claims, ok := claimsFromRequest(r)
if !ok {
return false
@@ -210,19 +345,45 @@ func HandleCheckAuth(w http.ResponseWriter, r *http.Request) {
func AuthMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tokenString := tokenFromRequest(r)
if !isValidToken(tokenString) && !isValidApiKeyRequest(r) {
jsonResponse(w, http.StatusUnauthorized, APIResponse{Success: false, Message: "Authentication required"})
if claims, ok := claimsFromToken(tokenString); ok {
if subUser, _ := claims["sub_user"].(string); subUser != "" {
auth := AuthContext{Type: authTypeSubUser, Username: subUser, Actor: "user:" + subUser}
if values, ok := claims["container_uuids"].([]interface{}); ok {
for _, value := range values {
if uuid, ok := value.(string); ok {
auth.ContainerUUIDs = append(auth.ContainerUUIDs, uuid)
}
}
}
next(w, withAuthContext(r, auth))
return
}
username, _ := claims["username"].(string)
if username == "" {
username = config.AppConfig.AdminUser
}
next(w, withAuthContext(r, AuthContext{Type: authTypeAdmin, Username: username, Actor: username}))
return
}
next(w, r)
if key, ok := validateApiKeyRequest(r); ok {
next(w, withAuthContext(r, authContextFromAPIKey(key)))
return
}
jsonResponse(w, http.StatusUnauthorized, APIResponse{Success: false, Message: "Authentication required"})
}
}
// AdminMiddleware requires a valid administrator token and rejects sub-user tokens.
func AdminMiddleware(next http.HandlerFunc) http.HandlerFunc {
return AuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
if isSubUserRequest(r) {
ctx, _ := authContextFromRequest(r)
if ctx.Type == authTypeSubUser {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Administrator permission required"})
return
}
if ctx.Type == authTypeAPIKey && !scopeAllowed(ctx.Scopes, "admin:access") {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Administrator permission required"})
return
}
+242
View File
@@ -0,0 +1,242 @@
package api
import (
"encoding/json"
"fmt"
"math"
"strconv"
"sync"
"time"
"clicd/internal/config"
)
type ContainerMetricPoint struct {
TS int64 `json:"ts"`
CPU float64 `json:"cpu"`
Memory float64 `json:"memory"`
Network float64 `json:"network"`
NetworkRx float64 `json:"network_rx"`
NetworkTx float64 `json:"network_tx"`
DiskIO float64 `json:"disk_io"`
DiskRead float64 `json:"disk_read"`
DiskWrite float64 `json:"disk_write"`
}
var containerMetricSamplerOnce sync.Once
var containerMetricMu sync.RWMutex
var containerMetricHistory = map[string][]ContainerMetricPoint{}
var containerMetricInFlight sync.Map
const (
containerMetricSampleInterval = 30 * time.Second
containerMetricSampleTimeout = 20 * time.Second
containerMetricConcurrency = 4
)
func StartContainerMetricSampler() {
containerMetricSamplerOnce.Do(func() {
go func() {
sampleAllContainerMetrics()
ticker := time.NewTicker(containerMetricSampleInterval)
defer ticker.Stop()
for range ticker.C {
sampleAllContainerMetrics()
}
}()
})
}
func sampleAllContainerMetrics() {
containers, _ := listByRuntime()
sem := make(chan struct{}, containerMetricConcurrency)
var wg sync.WaitGroup
for _, c := range containers {
c := c
if c.Status != "running" {
continue
}
sem <- struct{}{}
wg.Add(1)
go func() {
defer wg.Done()
defer func() { <-sem }()
sampleContainerMetricWithTimeout(c)
}()
}
wg.Wait()
pruneContainerMetricHistory()
}
func sampleContainerMetricWithTimeout(c config.Container) {
key := containerMetricKey(c)
if key == "" {
return
}
if _, loaded := containerMetricInFlight.LoadOrStore(key, struct{}{}); loaded {
return
}
done := make(chan struct{}, 1)
go func() {
defer containerMetricInFlight.Delete(key)
if usage, err := usageByRuntime(c.ID); err == nil {
appendContainerMetricPoint(c, usage)
}
done <- struct{}{}
}()
select {
case <-done:
case <-time.After(containerMetricSampleTimeout):
}
}
func appendContainerMetricPoint(c config.Container, usage map[string]interface{}) {
key := containerMetricKey(c)
if key == "" {
return
}
memoryTotal := numberFromUsage(usage, "memory_total_bytes")
if memoryTotal <= 0 {
memoryTotal = float64(c.RAMMB) * 1024 * 1024
}
memoryPct := 0.0
if memoryTotal > 0 {
memoryPct = clampPercent(numberFromUsage(usage, "memory_usage_bytes") / memoryTotal * 100)
}
vcpu := c.VCPU
if vcpu <= 0 {
vcpu = 1
}
cpuPct := clampPercent(numberFromUsage(usage, "cpu_usage_pct") / vcpu)
networkRx := positiveNumberFromUsage(usage, "network_rx_bps")
networkTx := positiveNumberFromUsage(usage, "network_tx_bps")
diskRead := positiveNumberFromUsage(usage, "disk_read_bps")
diskWrite := positiveNumberFromUsage(usage, "disk_write_bps")
point := ContainerMetricPoint{
TS: time.Now().UnixMilli(),
CPU: cpuPct,
Memory: memoryPct,
NetworkRx: networkRx,
NetworkTx: networkTx,
Network: networkRx + networkTx,
DiskRead: diskRead,
DiskWrite: diskWrite,
DiskIO: diskRead + diskWrite,
}
cutoff := time.Now().Add(-hostMetricRetention).UnixMilli()
containerMetricMu.Lock()
defer containerMetricMu.Unlock()
history := containerMetricHistory[key]
keepFrom := 0
for keepFrom < len(history) && history[keepFrom].TS < cutoff {
keepFrom++
}
if keepFrom > 0 {
copy(history, history[keepFrom:])
history = history[:len(history)-keepFrom]
}
containerMetricHistory[key] = append(history, point)
}
func getContainerMetricHistory(c *config.Container) []ContainerMetricPoint {
if c == nil {
return nil
}
key := containerMetricKey(*c)
containerMetricMu.RLock()
defer containerMetricMu.RUnlock()
history := containerMetricHistory[key]
result := make([]ContainerMetricPoint, len(history))
copy(result, history)
return result
}
func pruneContainerMetricHistory() {
cutoff := time.Now().Add(-hostMetricRetention).UnixMilli()
valid := map[string]bool{}
if config.AppConfig != nil {
for _, c := range config.AppConfig.Containers {
valid[containerMetricKey(c)] = true
}
}
containerMetricMu.Lock()
defer containerMetricMu.Unlock()
for key, history := range containerMetricHistory {
if !valid[key] {
delete(containerMetricHistory, key)
continue
}
keepFrom := 0
for keepFrom < len(history) && history[keepFrom].TS < cutoff {
keepFrom++
}
if keepFrom > 0 {
copy(history, history[keepFrom:])
containerMetricHistory[key] = history[:len(history)-keepFrom]
}
}
}
func containerMetricKey(c config.Container) string {
if c.UUID != "" {
return "uuid:" + c.UUID
}
if c.ID > 0 {
return fmt.Sprintf("id:%d", c.ID)
}
if c.Name != "" {
return "name:" + c.Name
}
return ""
}
func numberFromUsage(usage map[string]interface{}, key string) float64 {
value, ok := usage[key]
if !ok || value == nil {
return 0
}
switch v := value.(type) {
case float64:
if math.IsNaN(v) || math.IsInf(v, 0) {
return 0
}
return v
case float32:
return float64(v)
case int:
return float64(v)
case int64:
return float64(v)
case int32:
return float64(v)
case uint:
return float64(v)
case uint64:
return float64(v)
case uint32:
return float64(v)
case json.Number:
n, _ := v.Float64()
return n
case string:
n, _ := strconv.ParseFloat(v, 64)
return n
default:
return 0
}
}
func positiveNumberFromUsage(usage map[string]interface{}, key string) float64 {
value := numberFromUsage(usage, key)
if value < 0 {
return 0
}
return value
}
@@ -0,0 +1,7 @@
//go:build !linux
package api
func getRootDiskInfo() (DiskInfo, bool) {
return DiskInfo{}, false
}
+21
View File
@@ -0,0 +1,21 @@
//go:build linux
package api
import "golang.org/x/sys/unix"
func getRootDiskInfo() (DiskInfo, bool) {
var stat unix.Statfs_t
if err := unix.Statfs("/", &stat); err != nil {
return DiskInfo{}, false
}
total := float64(int64(stat.Blocks)*int64(stat.Bsize)) / (1024 * 1024 * 1024)
free := float64(int64(stat.Bavail)*int64(stat.Bsize)) / (1024 * 1024 * 1024)
return DiskInfo{
TotalGB: total,
UsedGB: total - free,
FreeGB: free,
}, true
}
+257
View File
@@ -0,0 +1,257 @@
package api
import (
"encoding/json"
"math/rand"
"net/http"
"net/netip"
"strconv"
"strings"
"clicd/internal/config"
"clicd/internal/lxc"
)
func generateFirewallRuleID() string {
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
b := make([]byte, 8)
for i := range b {
b[i] = chars[rand.Intn(len(chars))]
}
return string(b)
}
func getFirewall(w http.ResponseWriter, r *http.Request, id int) {
c := config.FindContainer(id)
if c == nil {
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"})
return
}
jsonResponse(w, http.StatusOK, APIResponse{
Success: true,
Data: map[string]interface{}{
"enabled": c.FirewallEnabled,
"default_action": normalizeFirewallDefaultAction(c.FirewallDefaultAction),
"rules": c.FirewallRules,
},
})
}
func updateFirewall(w http.ResponseWriter, r *http.Request, id int) {
c := config.FindContainer(id)
if c == nil {
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"})
return
}
var req struct {
Enabled *bool `json:"enabled"`
DefaultAction *string `json:"default_action"`
Rules *[]config.FirewallRule `json:"rules"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
oldEnabled := c.FirewallEnabled
oldDefaultAction := c.FirewallDefaultAction
oldRules := append([]config.FirewallRule(nil), c.FirewallRules...)
if req.Enabled != nil {
c.FirewallEnabled = *req.Enabled
}
if req.DefaultAction != nil {
action := normalizeFirewallDefaultAction(*req.DefaultAction)
if action == "" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid default action"})
return
}
c.FirewallDefaultAction = action
} else if strings.TrimSpace(c.FirewallDefaultAction) == "" {
c.FirewallDefaultAction = "DROP"
}
if req.Rules != nil {
// Validate and assign IDs to new rules
rules := *req.Rules
for i := range rules {
rules[i].Direction = strings.ToLower(strings.TrimSpace(rules[i].Direction))
rules[i].Protocol = strings.ToLower(strings.TrimSpace(rules[i].Protocol))
rules[i].Action = strings.ToUpper(strings.TrimSpace(rules[i].Action))
rules[i].Network = normalizeFirewallNetwork(rules[i].Network)
rules[i].SourceIP = strings.TrimSpace(rules[i].SourceIP)
rules[i].Port = strings.TrimSpace(rules[i].Port)
if rules[i].Network == "" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid network"})
return
}
if rules[i].Direction != "in" && rules[i].Direction != "out" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid direction: " + rules[i].Direction})
return
}
if rules[i].Protocol != "tcp" && rules[i].Protocol != "udp" && rules[i].Protocol != "icmp" && rules[i].Protocol != "all" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid protocol: " + rules[i].Protocol})
return
}
if rules[i].Action != "ACCEPT" && rules[i].Action != "DROP" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid action: " + rules[i].Action})
return
}
if rules[i].SourceIP != "" {
if err := validateFirewallIPSpec(rules[i].SourceIP, rules[i].Network); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid IP: " + err.Error()})
return
}
}
if rules[i].ID == "" || strings.HasPrefix(rules[i].ID, "tmp-") {
rules[i].ID = generateFirewallRuleID()
}
// Validate port spec
if rules[i].Port != "" {
if rules[i].Protocol != "tcp" && rules[i].Protocol != "udp" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Ports are only supported for TCP and UDP rules"})
return
}
if err := validatePortSpec(rules[i].Port); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid port: " + err.Error()})
return
}
}
}
c.FirewallRules = rules
}
// Apply firewall rules to iptables if container is running
if c.Status == "running" {
if err := lxc.ApplyFirewallRules(id); err != nil {
c.FirewallEnabled = oldEnabled
c.FirewallDefaultAction = oldDefaultAction
c.FirewallRules = oldRules
_ = lxc.ApplyFirewallRules(id)
config.SaveConfig()
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to apply firewall rules: " + err.Error()})
return
}
} else if !c.FirewallEnabled {
// If disabled and not running, clean any lingering rules
lxc.CleanFirewallRules(id)
}
config.SaveConfig()
jsonResponse(w, http.StatusOK, APIResponse{
Success: true,
Message: "Firewall updated",
Data: map[string]interface{}{
"enabled": c.FirewallEnabled,
"default_action": normalizeFirewallDefaultAction(c.FirewallDefaultAction),
"rules": c.FirewallRules,
},
})
}
func normalizeFirewallDefaultAction(action string) string {
action = strings.ToUpper(strings.TrimSpace(action))
if action == "ACCEPT" || action == "DROP" {
return action
}
return ""
}
func normalizeFirewallNetwork(network string) string {
network = strings.ToLower(strings.TrimSpace(network))
switch network {
case "", "ipv4", "nat4":
return "ipv4"
case "ipv6":
return "ipv6"
case "all", "both":
return "all"
default:
return ""
}
}
func validatePortSpec(port string) error {
port = strings.TrimSpace(port)
if port == "" {
return nil
}
// Support: "22", "80,443", "8000-9000", "80,443,8000-9000"
partCount := 0
for _, part := range strings.Split(port, ",") {
part = strings.TrimSpace(part)
if part == "" {
return &portValidationError{port}
}
partCount++
if strings.Contains(part, "-") {
// Range
bounds := strings.SplitN(part, "-", 2)
lo, err := strconv.Atoi(strings.TrimSpace(bounds[0]))
if err != nil || lo < 1 || lo > 65535 {
return &portValidationError{part}
}
hi, err := strconv.Atoi(strings.TrimSpace(bounds[1]))
if err != nil || hi < 1 || hi > 65535 {
return &portValidationError{part}
}
if hi < lo {
return &portValidationError{part}
}
} else {
p, err := strconv.Atoi(part)
if err != nil || p < 1 || p > 65535 {
return &portValidationError{part}
}
}
}
if partCount > 15 {
return &portValidationError{"too many ports; maximum 15 items per rule"}
}
return nil
}
func validateFirewallIPSpec(value string, network string) error {
var addr netip.Addr
if strings.Contains(value, "/") {
prefix, err := netip.ParsePrefix(value)
if err != nil {
return err
}
addr = prefix.Addr()
} else {
parsed, err := netip.ParseAddr(value)
if err != nil {
return err
}
addr = parsed
}
switch network {
case "ipv4":
if !addr.Is4() {
return &ipValidationError{"IPv4 rule requires an IPv4 address or CIDR: " + value}
}
case "ipv6":
if !addr.Is6() || addr.Is4In6() {
return &ipValidationError{"IPv6 rule requires an IPv6 address or CIDR: " + value}
}
}
return nil
}
type ipValidationError struct {
value string
}
func (e *ipValidationError) Error() string {
return e.value
}
type portValidationError struct {
port string
}
func (e *portValidationError) Error() string {
return "invalid port value: " + e.port
}
+377 -42
View File
@@ -2,6 +2,8 @@ package api
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
@@ -18,17 +20,41 @@ var lxcManager = lxc.NewManager()
func HandleContainers(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
if !requireScope(w, r, "container:read") {
return
}
listContainers(w, r)
case http.MethodPost:
if !requireScope(w, r, "container:create") {
return
}
if isAccessRestrictedRequest(r) {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Container-bound API keys cannot create containers"})
return
}
createContainer(w, r)
default:
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
}
}
// HandleContainerListAlias supports legacy integrations that call
// /api/containers/list or /api/v1/containers/list.
func HandleContainerListAlias(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodPost {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "container:read") {
return
}
listContainers(w, r)
}
// HandleSingleContainer handles individual container operations by ID or name: /api/containers/{id-or-name}/...
func HandleSingleContainer(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/api/containers/")
path := strings.TrimPrefix(r.URL.Path, "/api/v1/containers/")
path = strings.TrimPrefix(path, "/api/containers/")
parts := strings.SplitN(path, "/", 2)
c := containerByIdentifier(parts[0])
id := 0
@@ -48,6 +74,10 @@ func HandleSingleContainer(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"})
return
}
if !isSnapshotAction && !isContainerAllowedForRequest(r, parts[0]) {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Access denied to this container"})
return
}
if isSnapshotAction && id == 0 {
// For orphaned snapshots, resolve containerID from the snapshot itself
snapshotID := strings.TrimPrefix(action, "snapshots/")
@@ -59,45 +89,130 @@ func HandleSingleContainer(w http.ResponseWriter, r *http.Request) {
}
id = snapshot.ContainerID
}
if isSnapshotAction {
if c := config.FindContainer(id); c != nil && !isContainerAllowedForRequest(r, c.UUID) {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Access denied to this container"})
return
}
}
switch {
case action == "start" && r.Method == http.MethodPost:
if !requireScope(w, r, "container:power") {
return
}
HandleSingleTaskAction(w, r, id, "start")
case action == "stop" && r.Method == http.MethodPost:
if !requireScope(w, r, "container:power") {
return
}
HandleSingleTaskAction(w, r, id, "stop")
case action == "restart" && r.Method == http.MethodPost:
if !requireScope(w, r, "container:power") {
return
}
HandleSingleTaskAction(w, r, id, "restart")
case action == "reinstall" && r.Method == http.MethodPost:
if !requireScope(w, r, "container:reinstall") {
return
}
HandleSingleTaskAction(w, r, id, "reinstall")
case action == "delete" && r.Method == http.MethodDelete:
if !requireScope(w, r, "container:delete") {
return
}
HandleSingleTaskAction(w, r, id, "delete")
case action == "reset-password" && r.Method == http.MethodPost:
if !requireScope(w, r, "container:password") {
return
}
resetSSHPassword(w, r, id)
case action == "usage" && r.Method == http.MethodGet:
if !requireScope(w, r, "container:read") {
return
}
getUsage(w, r, id)
case action == "history" && r.Method == http.MethodGet:
if !requireScope(w, r, "container:read") {
return
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: getContainerMetricHistory(c)})
case action == "traffic" && r.Method == http.MethodGet:
if !requireScope(w, r, "container:read") {
return
}
getTraffic(w, r, id)
case action == "traffic-reset" && r.Method == http.MethodPost:
if !requireScope(w, r, "container:traffic") {
return
}
resetTraffic(w, r, id)
case action == "traffic-limit" && r.Method == http.MethodPut:
if !requireScope(w, r, "container:traffic") {
return
}
updateTrafficLimit(w, r, id)
case action == "resource-limit" && r.Method == http.MethodPut:
if !requireScope(w, r, "container:resize") {
return
}
updateResourceLimit(w, r, id)
case action == "random-port" && r.Method == http.MethodGet:
if !requireScope(w, r, "container:network") {
return
}
getRandomPort(w, r, id)
case action == "expiry" && r.Method == http.MethodPut:
if !requireScope(w, r, "container:resize") {
return
}
updateExpiry(w, r, id)
case action == "ipv6" && r.Method == http.MethodPost:
if !requireScope(w, r, "ipv6:assign") {
return
}
assignIPv6(w, r, id)
case action == "public-ipv4" && r.Method == http.MethodPut:
if !requireScope(w, r, "container:network") {
return
}
updatePublicIPv4(w, r, id)
case action == "ipv6-addresses" && r.Method == http.MethodPut:
if !requireScope(w, r, "ipv6:assign") {
return
}
updateIPv6Addresses(w, r, id)
case action == "snapshots" || strings.HasPrefix(action, "snapshots/"):
handleContainerSnapshots(w, r, id, action)
case action == "port-mappings" && r.Method == http.MethodPost:
if !requireScope(w, r, "container:network") {
return
}
addPortMapping(w, r, id)
case strings.HasPrefix(action, "port-mappings/") && r.Method == http.MethodPut:
if !requireScope(w, r, "container:network") {
return
}
updatePortMapping(w, r, id, strings.TrimPrefix(action, "port-mappings/"))
case strings.HasPrefix(action, "port-mappings/") && r.Method == http.MethodDelete:
if !requireScope(w, r, "container:network") {
return
}
deletePortMapping(w, r, id, strings.TrimPrefix(action, "port-mappings/"))
case action == "firewall" && r.Method == http.MethodGet:
if !requireScope(w, r, "container:network") {
return
}
getFirewall(w, r, id)
case action == "firewall" && r.Method == http.MethodPut:
if !requireScope(w, r, "container:network") {
return
}
updateFirewall(w, r, id)
case r.Method == http.MethodGet:
if !requireScope(w, r, "container:read") {
return
}
getContainer(w, r, id)
default:
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Action not found"})
@@ -112,10 +227,21 @@ func listContainers(w http.ResponseWriter, r *http.Request) {
func createContainer(w http.ResponseWriter, r *http.Request) {
var cfg lxc.ContainerConfig
if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
body, err := io.ReadAll(r.Body)
if err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
var fields map[string]json.RawMessage
if err := json.Unmarshal(body, &cfg); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
_ = json.Unmarshal(body, &fields)
if err := normalizeCreateResourceLimits(&cfg, fields); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
if cfg.Name == "" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Container name is required"})
return
@@ -129,6 +255,12 @@ func createContainer(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Template is not enabled or downloaded"})
return
}
if ids, err := normalizeAllowedImageIDs(cfg.AllowedImageIDs); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
} else {
cfg.AllowedImageIDs = ids
}
if cfg.VCPU <= 0 {
cfg.VCPU = 1
}
@@ -138,13 +270,40 @@ func createContainer(w http.ResponseWriter, r *http.Request) {
if cfg.DiskGB < 1 {
cfg.DiskGB = 5
}
if cfg.PortMappingCount < 2 {
cfg.PortMappingCount = 2
if cfg.PortMappingCount < 0 {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Port mapping count cannot be negative"})
return
}
if err := cfg.NormalizeCreateNATMappings(); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
if err := lxc.ValidateCreateNATPortAvailability(cfg); err != nil {
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: err.Error()})
return
}
if cfg.PortMappingCount > 64 {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Port mapping count cannot exceed 64"})
return
}
if cfg.IPv4Count < 0 || cfg.IPv6Count < 0 {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "IP address count cannot be negative"})
return
}
if cfg.IPv4Count > 64 || cfg.IPv6Count > 64 {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "IP address count cannot exceed 64"})
return
}
if !cfg.AssignIPv4 && len(cfg.PublicIPv4s) == 0 {
cfg.IPv4Count = 0
}
if !cfg.AssignIPv6 && len(cfg.IPv6Addresses) == 0 {
cfg.IPv6Count = 0
}
if !hasRequestedNetwork(cfg) {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: noNetworkSelectedMessage})
return
}
if cfg.SnapshotLimit <= 0 {
cfg.SnapshotLimit = config.DefaultSnapshotLimit
}
@@ -152,6 +311,14 @@ func createContainer(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
if err := validateCreateStoragePool(&cfg); err != nil {
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: err.Error()})
return
}
if err := validateCreateSSHAuth(cfg); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
if cfg.ExpiresAt != "" {
expiresAt, ok := lxc.ParseExpiration(cfg.ExpiresAt)
if !ok {
@@ -177,6 +344,10 @@ func getContainer(w http.ResponseWriter, r *http.Request, id int) {
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"})
return
}
if c.IsKVM() && c.Status == "running" {
_, _ = kvmManager.RefreshVNCPort(c.ID)
_, _ = kvmManager.RefreshNetwork(c.ID)
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: c})
}
@@ -255,10 +426,14 @@ func updateTrafficLimit(w http.ResponseWriter, r *http.Request, id int) {
func updateResourceLimit(w http.ResponseWriter, r *http.Request, id int) {
var req struct {
VCPU float64 `json:"vcpu"`
RAMMB int `json:"ram_mb"`
IOMBps int `json:"io_speed_mbps"`
BWMbps int `json:"network_bw_mbps"`
VCPU *float64 `json:"vcpu"`
RAMMB *int `json:"ram_mb"`
IOMBps *int `json:"io_speed_mbps"`
IOReadMBps *int `json:"io_read_mbps"`
IOWriteMBps *int `json:"io_write_mbps"`
BWMbps *int `json:"network_bw_mbps"`
NetworkDownMbps *int `json:"network_down_mbps"`
NetworkUpMbps *int `json:"network_up_mbps"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request"})
@@ -273,32 +448,157 @@ func updateResourceLimit(w http.ResponseWriter, r *http.Request, id int) {
// Update config
nextVCPU := c.VCPU
nextRAMMB := c.RAMMB
if req.VCPU > 0 {
nextVCPU = req.VCPU
if req.VCPU != nil {
nextVCPU = *req.VCPU
}
if req.RAMMB > 0 {
nextRAMMB = req.RAMMB
if req.RAMMB != nil {
nextRAMMB = *req.RAMMB
}
if err := validateRuntimeResourceRequest(c.Runtime(), nextVCPU, nextRAMMB, c.DiskGB); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
c.VCPU = nextVCPU
c.RAMMB = nextRAMMB
c.IOSpeedMBps = req.IOMBps
c.NetworkBWMbps = req.BWMbps
config.SaveConfig()
// Re-apply resource limits to running container
if c.Status == "running" {
if err := applyLimitsByRuntime(c); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: err.Error()})
for name, value := range map[string]*int{
"network_bw_mbps": req.BWMbps,
"network_down_mbps": req.NetworkDownMbps,
"network_up_mbps": req.NetworkUpMbps,
"io_speed_mbps": req.IOMBps,
"io_read_mbps": req.IOReadMBps,
"io_write_mbps": req.IOWriteMBps,
} {
if err := rejectNegativeLimit(name, value); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Resource limits updated"})
c.VCPU = nextVCPU
c.RAMMB = nextRAMMB
applyNetworkLimitPatch(c, req.BWMbps, req.NetworkDownMbps, req.NetworkUpMbps)
applyIOLimitPatch(c, req.IOMBps, req.IOReadMBps, req.IOWriteMBps)
config.NormalizeContainerResourceAliases(c)
config.SaveConfig()
// Re-apply persisted/runtime limits. LXC also uses this path to migrate
// old managed config lines such as lxc.prlimit.nproc.
if err := applyLimitsByRuntime(c); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: err.Error()})
return
}
msg := "Resource limits updated"
if c.IsKVM() && c.Status == "running" {
msg = "资源已保存,请关机重启虚拟机后生效"
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: msg})
}
func normalizeCreateResourceLimits(cfg *lxc.ContainerConfig, fields map[string]json.RawMessage) error {
if cfg == nil {
return nil
}
if err := rejectNegativeCreateLimits(*cfg); err != nil {
return err
}
bwSet := hasJSONField(fields, "network_bw_mbps")
downSet := hasJSONField(fields, "network_down_mbps")
upSet := hasJSONField(fields, "network_up_mbps")
if bwSet {
if !downSet {
cfg.NetworkDownMbps = cfg.NetworkBWMbps
}
if !upSet {
cfg.NetworkUpMbps = cfg.NetworkBWMbps
}
}
ioSet := hasJSONField(fields, "io_speed_mbps")
readSet := hasJSONField(fields, "io_read_mbps")
writeSet := hasJSONField(fields, "io_write_mbps")
if ioSet {
if !readSet {
cfg.IOReadMBps = cfg.IOSpeedMBps
}
if !writeSet {
cfg.IOWriteMBps = cfg.IOSpeedMBps
}
}
cfg.NormalizeResourceAliases()
return nil
}
func rejectNegativeCreateLimits(cfg lxc.ContainerConfig) error {
for name, value := range map[string]int{
"network_bw_mbps": cfg.NetworkBWMbps,
"network_down_mbps": cfg.NetworkDownMbps,
"network_up_mbps": cfg.NetworkUpMbps,
"io_speed_mbps": cfg.IOSpeedMBps,
"io_read_mbps": cfg.IOReadMBps,
"io_write_mbps": cfg.IOWriteMBps,
} {
if value < 0 {
return fmt.Errorf("%s cannot be negative", name)
}
}
return nil
}
func hasJSONField(fields map[string]json.RawMessage, name string) bool {
if fields == nil {
return false
}
_, ok := fields[name]
return ok
}
func rejectNegativeLimit(name string, value *int) error {
if value != nil && *value < 0 {
return fmt.Errorf("%s cannot be negative", name)
}
return nil
}
func applyNetworkLimitPatch(c *config.Container, legacy *int, down *int, up *int) {
if c == nil {
return
}
config.NormalizeContainerResourceAliases(c)
nextDown := c.NetworkDownMbps
nextUp := c.NetworkUpMbps
if legacy != nil {
nextDown = *legacy
nextUp = *legacy
}
if down != nil {
nextDown = *down
}
if up != nil {
nextUp = *up
}
c.NetworkDownMbps = nextDown
c.NetworkUpMbps = nextUp
c.NetworkBWMbps = config.LegacySymmetricLimit(nextDown, nextUp)
}
func applyIOLimitPatch(c *config.Container, legacy *int, read *int, write *int) {
if c == nil {
return
}
config.NormalizeContainerResourceAliases(c)
nextRead := c.IOReadMBps
nextWrite := c.IOWriteMBps
if legacy != nil {
nextRead = *legacy
nextWrite = *legacy
}
if read != nil {
nextRead = *read
}
if write != nil {
nextWrite = *write
}
c.IOReadMBps = nextRead
c.IOWriteMBps = nextWrite
c.IOSpeedMBps = config.LegacySymmetricLimit(nextRead, nextWrite)
}
func getRandomPort(w http.ResponseWriter, r *http.Request, id int) {
@@ -307,24 +607,16 @@ func getRandomPort(w http.ResponseWriter, r *http.Request, id int) {
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"})
return
}
// Find a random unused port between 10000-65535
used := map[int]bool{}
for _, pm := range c.PortMappings {
used[pm.HostPort] = true
hostIP := strings.TrimSpace(r.URL.Query().Get("host_ip"))
start, end := config.NATPortRange()
capacity := end - start + 1
offset := 0
if capacity > 0 {
offset = int(time.Now().UnixNano() % int64(capacity))
}
// Also check all containers
for _, oc := range config.AppConfig.Containers {
if oc.ID == id {
continue
}
for _, pm := range oc.PortMappings {
used[pm.HostPort] = true
}
}
// Try random ports
for tries := 0; tries < 100; tries++ {
port := 10000 + (int(time.Now().UnixNano()) % 55535)
if !used[port] {
for tries := 0; tries < capacity; tries++ {
port := start + ((offset + tries) % capacity)
if lxc.HostPortAvailable(c, hostIP, port, "tcp") {
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: map[string]int{"port": port}})
return
}
@@ -338,6 +630,9 @@ func HandleTemplates(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "image:read") {
return
}
if isSubUserRequest(r) {
HandleEnabledImages(w, r)
return
@@ -352,7 +647,11 @@ func HandleDashboard(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "dashboard:read") {
return
}
containers, _ := listByRuntime()
containers = filterContainersForRequest(r, containers)
running := 0
stopped := 0
for _, c := range containers {
@@ -376,17 +675,49 @@ func HandleHostInfo(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "host:read") {
return
}
info := getHostInfo()
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: info})
}
// HandleHostHistory returns host resource samples collected by the server.
func HandleHostHistory(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "host:read") {
return
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: getHostMetricHistory()})
}
func resetSSHPassword(w http.ResponseWriter, r *http.Request, id int) {
c := config.FindContainer(id)
if c != nil && lxc.IsExpired(*c) {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "容器已到期,不允许此操作"})
return
}
newPassword, err := resetPasswordByRuntime(id)
var req struct {
Password string `json:"password"`
}
if r.Body != nil {
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&req); err != nil && err.Error() != "EOF" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
}
password := strings.TrimSpace(req.Password)
if password != "" {
if err := validateSSHPassword(password); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
}
newPassword, err := resetPasswordByRuntime(id, password)
if err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: err.Error()})
return
@@ -398,6 +729,10 @@ func resetSSHPassword(w http.ResponseWriter, r *http.Request, id int) {
})
}
func validateSSHPassword(password string) error {
return lxc.ValidateCustomSSHPassword(password)
}
func addPortMapping(w http.ResponseWriter, r *http.Request, id int) {
var pm config.PortMapping
if err := json.NewDecoder(r.Body).Decode(&pm); err != nil {
File diff suppressed because it is too large Load Diff
+77
View File
@@ -0,0 +1,77 @@
package api
import "testing"
func TestExtractCertbotVersion(t *testing.T) {
tests := []struct {
output string
want string
}{
{"certbot 5.4.0", "5.4.0"},
{"certbot v5.10.1", "5.10.1"},
{"certbot, version 4.9", "4.9"},
{"installed", ""},
}
for _, tt := range tests {
if got := extractCertbotVersion(tt.output); got != tt.want {
t.Fatalf("extractCertbotVersion(%q) = %q, want %q", tt.output, got, tt.want)
}
}
}
func TestCertbotVersionAtLeast54(t *testing.T) {
tests := []struct {
version string
want bool
}{
{"5.4", true},
{"5.4.0", true},
{"5.10", true},
{"6.0.0", true},
{"5.3.9", false},
{"4.99", false},
{"5", false},
{"", false},
}
for _, tt := range tests {
if got := certbotVersionAtLeast(tt.version, 5, 4); got != tt.want {
t.Fatalf("certbotVersionAtLeast(%q, 5, 4) = %v, want %v", tt.version, got, tt.want)
}
}
}
func TestARMCPUModelName(t *testing.T) {
if got := armCPUModelName("0x41", "0xd0c"); got != "ARM Neoverse N1" {
t.Fatalf("armCPUModelName() = %q, want ARM Neoverse N1", got)
}
if got := armCPUModelName("41", "d0c"); got != "ARM Neoverse N1" {
t.Fatalf("armCPUModelName() without hex prefix = %q, want ARM Neoverse N1", got)
}
}
func TestMeaningfulCPUModel(t *testing.T) {
if meaningfulCPUModel("0") {
t.Fatal("numeric ARM processor index should not be treated as a CPU model")
}
if !meaningfulCPUModel("Neoverse-N1") {
t.Fatal("expected Neoverse-N1 to be treated as a CPU model")
}
}
func TestHostTrafficInterfaceFilter(t *testing.T) {
accepted := []string{"eth0", "ens3", "enp0s6", "bond0", "wg0"}
for _, name := range accepted {
if !isHostTrafficInterface(name) {
t.Fatalf("expected %s to be accepted as a host traffic interface", name)
}
}
rejected := []string{"", "lo", "docker0", "br-3024b78640ee", "lxcbr0", "virbr0", "vethaaa9e44", "cni0"}
for _, name := range rejected {
if isHostTrafficInterface(name) {
t.Fatalf("expected %s to be rejected as an internal/container interface", name)
}
}
}
File diff suppressed because it is too large Load Diff
+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)
}
}
}
+58 -1
View File
@@ -1,12 +1,18 @@
package api
import "net/http"
import (
"encoding/json"
"net/http"
)
func HandleIPv6Status(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "ipv6:read") {
return
}
status := lxcManager.DetectIPv6Status()
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: status})
}
@@ -19,3 +25,54 @@ func assignIPv6(w http.ResponseWriter, r *http.Request, id int) {
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "IPv6 assigned", Data: c})
}
type ipAssignmentRequest struct {
Mode string `json:"mode"`
Auto *bool `json:"auto,omitempty"`
Count int `json:"count,omitempty"`
Addresses []string `json:"addresses,omitempty"`
}
func (req ipAssignmentRequest) allocation() ([]string, int, bool) {
auto := req.Mode == "random" || req.Mode == "auto"
if req.Mode == "custom" {
auto = false
}
if req.Mode == "clear" || req.Mode == "none" {
return nil, 0, false
}
if req.Auto != nil {
auto = *req.Auto
}
return req.Addresses, req.Count, auto
}
func updatePublicIPv4(w http.ResponseWriter, r *http.Request, id int) {
var req ipAssignmentRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
addresses, count, auto := req.allocation()
c, err := updatePublicIPv4ByRuntime(id, addresses, count, auto)
if err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Public IPv4 assignments updated", Data: c})
}
func updateIPv6Addresses(w http.ResponseWriter, r *http.Request, id int) {
var req ipAssignmentRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
addresses, count, auto := req.allocation()
c, err := updateIPv6ByRuntime(id, addresses, count, auto)
if err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "IPv6 assignments updated", Data: c})
}
+80
View File
@@ -0,0 +1,80 @@
package api
import (
"encoding/json"
"net/http"
"strings"
"clicd/internal/config"
)
type webSSHOriginSettingsRequest struct {
Origins []string `json:"origins"`
WebSSHAllowedOrigins []string `json:"webssh_allowed_origins"`
}
type webSSHOriginSettingsResponse struct {
Origins []string `json:"origins"`
CurrentOrigin string `json:"current_origin,omitempty"`
}
func HandleWebSSHOriginSettings(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: webSSHOriginSettingsStatus(r)})
case http.MethodPut:
updateWebSSHOriginSettings(w, r)
default:
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
}
}
func updateWebSSHOriginSettings(w http.ResponseWriter, r *http.Request) {
var req webSSHOriginSettingsRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
origins := req.Origins
if len(origins) == 0 && len(req.WebSSHAllowedOrigins) > 0 {
origins = req.WebSSHAllowedOrigins
}
normalized, err := config.NormalizeAllowedOrigins(origins)
if err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
config.AppConfig.WebSSHAllowedOrigins = normalized
if err := config.SaveConfig(); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Save Origin allowlist failed"})
return
}
auditRequest(r, "settings.webssh_origins", "WebSSH Origin", "origins="+strings.Join(normalized, ","), true, "")
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Origin allowlist saved", Data: webSSHOriginSettingsStatus(r)})
}
func webSSHOriginSettingsStatus(r *http.Request) webSSHOriginSettingsResponse {
origins := config.AppConfig.WebSSHAllowedOrigins
if origins == nil {
origins = []string{}
}
return webSSHOriginSettingsResponse{
Origins: origins,
CurrentOrigin: requestOrigin(r),
}
}
func requestOrigin(r *http.Request) string {
host := strings.TrimSpace(r.Host)
if host == "" {
return ""
}
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
if forwarded := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")); forwarded != "" {
scheme = strings.ToLower(strings.Split(forwarded, ",")[0])
}
return scheme + "://" + host
}
+104
View File
@@ -0,0 +1,104 @@
package api
import (
"fmt"
"time"
"clicd/internal/config"
"clicd/internal/kvm"
"clicd/internal/lxc"
)
// CaptureRuntimeRestoreState records which managed workloads are actually
// running before the CLICD service exits. On the next host boot, only those
// workloads are started again.
func CaptureRuntimeRestoreState() {
if config.AppConfig == nil {
return
}
lxcManager := lxc.NewManager()
kvmManager := kvm.NewManager()
changed := false
for i := range config.AppConfig.Containers {
c := &config.AppConfig.Containers[i]
status, err := runtimeStatus(*c, lxcManager, kvmManager)
if err != nil {
fmt.Printf("Warning: failed to capture runtime state for %s: %v\n", c.Name, err)
continue
}
restore := status == "running"
if c.RestoreOnHostBoot != restore {
c.RestoreOnHostBoot = restore
changed = true
}
if status != "" && c.Status != status {
c.Status = status
changed = true
}
}
if changed {
if err := config.SaveConfig(); err != nil {
fmt.Printf("Warning: failed to save host boot restore state: %v\n", err)
}
}
}
func StartHostBootRestore() {
go RestoreHostBootState()
}
func RestoreHostBootState() {
if config.AppConfig == nil {
return
}
time.Sleep(2 * time.Second)
lxcManager := lxc.NewManager()
kvmManager := kvm.NewManager()
containers := append([]config.Container(nil), config.AppConfig.Containers...)
for _, c := range containers {
if !c.RestoreOnHostBoot {
continue
}
if c.PolicyBlocked {
fmt.Printf("Skipping host boot restore for %s: policy blocked\n", c.Name)
continue
}
if lxc.IsExpired(c) {
fmt.Printf("Skipping host boot restore for %s: expired at %s\n", c.Name, c.ExpiresAt)
continue
}
status, err := runtimeStatus(c, lxcManager, kvmManager)
if err == nil && status == "running" {
config.UpdateContainerStatusAndRestore(c.ID, "running", true)
if !c.IsKVM() {
_ = lxcManager.ApplyPortMappings(c.ID)
} else {
_ = lxc.NewManager().ApplyPortMappings(c.ID)
}
continue
}
fmt.Printf("Restoring workload after host boot: %s (ID=%d)\n", c.Name, c.ID)
if c.IsKVM() {
if err := kvmManager.StartContainer(c.ID); err != nil {
fmt.Printf("Warning: failed to restore KVM %s: %v\n", c.Name, err)
}
continue
}
if err := lxcManager.StartContainer(c.ID); err != nil {
fmt.Printf("Warning: failed to restore LXC %s: %v\n", c.Name, err)
}
}
lxc.EnsureAllRunningPortMappings()
}
func runtimeStatus(c config.Container, lxcManager *lxc.Manager, kvmManager *kvm.Manager) (string, error) {
if c.IsKVM() {
return kvmManager.GetContainerStatus(c.VirshName())
}
return lxcManager.GetContainerStatus(c.LxcName())
}
+322 -23
View File
@@ -1,7 +1,9 @@
package api
import (
"encoding/json"
"net/http"
"net/netip"
"sort"
"strconv"
@@ -15,18 +17,53 @@ type routeCapacity struct {
Total string `json:"total"`
}
type nat4PortRange struct {
Start int `json:"start"`
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"`
LXCName string `json:"lxc_name"`
Status string `json:"status"`
IP string `json:"ip"`
HostIP string `json:"host_ip"`
HostPort int `json:"host_port"`
ContainerPort int `json:"container_port"`
Protocol string `json:"protocol"`
Description string `json:"description"`
}
type ipv4Route struct {
ContainerID int `json:"container_id"`
ContainerName string `json:"container_name"`
LXCName string `json:"lxc_name"`
Status string `json:"status"`
Address string `json:"address"`
Interface string `json:"interface"`
PrefixLen int `json:"prefix_len,omitempty"`
Gateway string `json:"gateway,omitempty"`
}
type lanDHCPRoute struct {
ContainerID int `json:"container_id"`
ContainerName string `json:"container_name"`
LXCName string `json:"lxc_name"`
Status string `json:"status"`
Address string `json:"address"`
Interface string `json:"interface"`
PrefixLen int `json:"prefix_len,omitempty"`
Gateway string `json:"gateway,omitempty"`
MACAddress string `json:"mac_address,omitempty"`
Mode string `json:"mode"`
}
type ipv6Route struct {
ContainerID int `json:"container_id"`
ContainerName string `json:"container_name"`
@@ -38,29 +75,87 @@ type ipv6Route struct {
}
type routingResponse struct {
NAT4 routeCapacity `json:"nat4"`
IPv6 routeCapacity `json:"ipv6"`
NAT4Mappings []nat4Route `json:"nat4_mappings"`
IPv6Assignments []ipv6Route `json:"ipv6_assignments"`
IPv6Prefixes []lxc.IPv6PrefixInfo `json:"ipv6_prefixes"`
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"`
HostPublicIPv4 lxc.PublicIPInfo `json:"host_public_ipv4"`
PublicIPv4Addresses []lxc.PublicIPInfo `json:"public_ipv4_addresses"`
IPv4Assignments []ipv4Route `json:"ipv4_assignments"`
LANDHCPAssignments []lanDHCPRoute `json:"lan_dhcp_assignments"`
NAT4Mappings []nat4Route `json:"nat4_mappings"`
IPv6Assignments []ipv6Route `json:"ipv6_assignments"`
IPv6Prefixes []lxc.IPv6PrefixInfo `json:"ipv6_prefixes"`
}
type routingPoolsRequest struct {
Addresses *[]string `json:"addresses"`
Items *[]config.PublicIPv4Assignment `json:"items"`
IPv6Prefixes *[]config.PublicIPv6Prefix `json:"ipv6_prefixes"`
NAT4PortRange *nat4PortRange `json:"nat4_port_range"`
}
type publicIPv4ScanRequest struct {
CIDR string `json:"cidr"`
Interface string `json:"interface"`
Gateway string `json:"gateway"`
Verify bool `json:"verify"`
Limit int `json:"limit"`
}
func HandleRouting(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
switch r.Method {
case http.MethodGet:
handleRoutingGet(w, r)
case http.MethodPut:
handleRoutingPoolsUpdate(w, r)
default:
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
}
}
func HandleRoutingIPv4Scan(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "routing:write") {
return
}
var req publicIPv4ScanRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
results, err := lxc.ScanPublicIPv4Segment(req.CIDR, req.Interface, req.Gateway, req.Verify, req.Limit)
if err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: results})
}
func handleRoutingGet(w http.ResponseWriter, r *http.Request) {
if !hasAnyScope(r, "routing:read", "routing:write") {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Insufficient API key scope"})
return
}
nat4Mappings := make([]nat4Route, 0)
usedPorts := map[int]bool{}
ipv4Assignments := make([]ipv4Route, 0)
lanDHCPAssignments := make([]lanDHCPRoute, 0)
ipv6Assignments := make([]ipv6Route, 0)
const nat4StartPort = 20000
const nat4EndPort = 65535
nat4StartPort, nat4EndPort := config.NATPortRange()
for _, c := range config.AppConfig.Containers {
for i := range config.AppConfig.Containers {
c := &config.AppConfig.Containers[i]
for _, pm := range c.PortMappings {
if pm.HostPort >= nat4StartPort && pm.HostPort <= nat4EndPort {
if config.NATPortInRange(pm.HostPort) {
usedPorts[pm.HostPort] = true
}
nat4Mappings = append(nat4Mappings, nat4Route{
@@ -69,48 +164,99 @@ func HandleRouting(w http.ResponseWriter, r *http.Request) {
LXCName: c.LxcName(),
Status: c.Status,
IP: c.IP,
HostIP: pm.HostIP,
HostPort: pm.HostPort,
ContainerPort: pm.ContainerPort,
Protocol: pm.Protocol,
Description: pm.Description,
})
}
if c.IPv6 != "" {
for _, ip := range c.PublicIPv4s {
if ip.Address == "" {
continue
}
ipv4Assignments = append(ipv4Assignments, ipv4Route{
ContainerID: c.ID,
ContainerName: c.Name,
LXCName: c.LxcName(),
Status: c.Status,
Address: ip.Address,
Interface: ip.Interface,
PrefixLen: ip.PrefixLen,
Gateway: ip.Gateway,
})
}
c.NormalizeNetworkAssignments()
if c.UsesLANIPv4() {
lanDHCPAssignments = append(lanDHCPAssignments, lanDHCPRoute{
ContainerID: c.ID,
ContainerName: c.Name,
LXCName: c.LxcName(),
Status: c.Status,
Address: c.IP,
Interface: c.LANInterface,
PrefixLen: c.LANIPv4PrefixLen,
Gateway: c.LANIPv4Gateway,
MACAddress: c.MACAddress,
Mode: c.LANIPv4Mode,
})
}
for _, ip := range c.IPv6Addresses {
if ip.Address == "" {
continue
}
ipv6Assignments = append(ipv6Assignments, ipv6Route{
ContainerID: c.ID,
ContainerName: c.Name,
LXCName: c.LxcName(),
Status: c.Status,
Address: c.IPv6,
PrefixLen: c.IPv6PrefixLen,
Interface: c.IPv6Interface,
Address: ip.Address,
PrefixLen: ip.PrefixLen,
Interface: ip.Interface,
})
}
}
sort.SliceStable(nat4Mappings, func(i, j int) bool {
if nat4Mappings[i].HostPort == nat4Mappings[j].HostPort {
if nat4Mappings[i].HostIP != nat4Mappings[j].HostIP {
return nat4Mappings[i].HostIP < nat4Mappings[j].HostIP
}
return nat4Mappings[i].ContainerName < nat4Mappings[j].ContainerName
}
return nat4Mappings[i].HostPort < nat4Mappings[j].HostPort
})
sort.SliceStable(ipv4Assignments, func(i, j int) bool {
return ipv4Assignments[i].Address < ipv4Assignments[j].Address
})
sort.SliceStable(lanDHCPAssignments, func(i, j int) bool {
if lanDHCPAssignments[i].Interface == lanDHCPAssignments[j].Interface {
return lanDHCPAssignments[i].ContainerName < lanDHCPAssignments[j].ContainerName
}
return lanDHCPAssignments[i].Interface < lanDHCPAssignments[j].Interface
})
sort.SliceStable(ipv6Assignments, func(i, j int) bool {
return ipv6Assignments[i].Address < ipv6Assignments[j].Address
})
const totalNAT4Ports = nat4EndPort - nat4StartPort + 1
totalNAT4Ports := config.NATPortCapacity()
nat4Used := len(usedPorts)
nat4Remaining := totalNAT4Ports - nat4Used
if nat4Remaining < 0 {
nat4Remaining = 0
}
nat4NextPort, _ := config.PreviewSSHPortExcluding(nil)
prefixes := lxc.DetectPublicIPv6Prefixes()
ipv6Total := "0"
ipv6Remaining := "0"
if len(prefixes) > 0 {
ipv6Total = lxc.IPv6PrefixCapacity(prefixes[0].PrefixLen)
ipv6Remaining = subtractCapacity(ipv6Total, len(ipv6Assignments))
hostPublicIPv4 := lxc.DetectPublicIPv4()
publicIPv4s := lxc.DetectPublicIPv4Candidates()
ipv4Total := len(publicIPv4s)
ipv4Used := len(ipv4Assignments)
ipv4Remaining := ipv4Total - ipv4Used
if ipv4Remaining < 0 {
ipv4Remaining = 0
}
ipv6Total := totalIPv6Capacity(prefixes)
ipv6Remaining := subtractCapacity(ipv6Total, len(ipv6Assignments))
jsonResponse(w, http.StatusOK, APIResponse{
Success: true,
@@ -120,18 +266,171 @@ func HandleRouting(w http.ResponseWriter, r *http.Request) {
Remaining: strconv.Itoa(nat4Remaining),
Total: strconv.Itoa(totalNAT4Ports),
},
NAT4PortRange: nat4PortRange{
Start: nat4StartPort,
End: nat4EndPort,
},
NAT4NextPort: nat4NextPort,
NAT4Networks: nat4Networks{
LXC: config.LXCNATNetwork(),
KVM: config.KVMNATNetwork(),
},
IPv4: routeCapacity{
Used: ipv4Used,
Remaining: strconv.Itoa(ipv4Remaining),
Total: strconv.Itoa(ipv4Total),
},
LANDHCP: routeCapacity{
Used: len(lanDHCPAssignments),
Remaining: "DHCP",
Total: "DHCP",
},
IPv6: routeCapacity{
Used: len(ipv6Assignments),
Remaining: ipv6Remaining,
Total: ipv6Total,
},
NAT4Mappings: nat4Mappings,
IPv6Assignments: ipv6Assignments,
IPv6Prefixes: prefixes,
HostPublicIPv4: hostPublicIPv4,
PublicIPv4Addresses: publicIPv4s,
IPv4Assignments: ipv4Assignments,
LANDHCPAssignments: lanDHCPAssignments,
NAT4Mappings: nat4Mappings,
IPv6Assignments: ipv6Assignments,
IPv6Prefixes: prefixes,
},
})
}
func handleRoutingPoolsUpdate(w http.ResponseWriter, r *http.Request) {
if !requireScope(w, r, "routing:write") {
return
}
var req routingPoolsRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
if req.NAT4PortRange != nil {
start, end, err := config.NormalizeNATPortRange(req.NAT4PortRange.Start, req.NAT4PortRange.End)
if err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
config.AppConfig.NATPortStart = start
config.AppConfig.NATPortEnd = end
if config.AppConfig.NextSSHPort < start || config.AppConfig.NextSSHPort > end {
config.AppConfig.NextSSHPort = start
}
}
if req.Items != nil || req.Addresses != nil {
items := []config.PublicIPv4Assignment{}
if req.Items != nil {
items = *req.Items
} else if req.Addresses != nil {
items = make([]config.PublicIPv4Assignment, 0, len(*req.Addresses))
for _, address := range *req.Addresses {
items = append(items, config.PublicIPv4Assignment{Address: address})
}
}
normalized, err := lxc.NormalizePublicIPv4Pool(items)
if err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
allowed := map[string]bool{}
for _, item := range normalized {
allowed[item.Address] = true
}
for _, c := range config.AppConfig.Containers {
for _, item := range c.PublicIPv4s {
if item.Address != "" && !allowed[item.Address] {
jsonResponse(w, http.StatusBadRequest, APIResponse{
Success: false,
Message: "IPv4 " + item.Address + " is assigned to container " + c.Name + " and cannot be removed from the pool",
})
return
}
}
}
config.AppConfig.PublicIPv4Pool = normalized
}
if req.IPv6Prefixes != nil {
normalized, err := lxc.NormalizePublicIPv6Prefixes(*req.IPv6Prefixes)
if err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
parsedPrefixes := make([]netip.Prefix, 0, len(normalized))
for _, item := range normalized {
prefix, err := netip.ParsePrefix(item.Prefix)
if err == nil {
parsedPrefixes = append(parsedPrefixes, prefix)
}
}
for _, c := range config.AppConfig.Containers {
c.NormalizeNetworkAssignments()
for _, item := range c.IPv6Addresses {
if item.Address == "" {
continue
}
addr, err := netip.ParseAddr(item.Address)
if err != nil {
continue
}
contained := false
for _, prefix := range parsedPrefixes {
if prefix.Contains(addr) {
contained = true
break
}
}
if !contained {
jsonResponse(w, http.StatusBadRequest, APIResponse{
Success: false,
Message: "IPv6 " + item.Address + " is assigned to container " + c.Name + " and cannot be removed from the pool",
})
return
}
}
}
config.AppConfig.PublicIPv6Prefixes = normalized
}
if err := config.SaveConfig(); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to save configuration"})
return
}
handleRoutingGet(w, r)
}
func totalIPv6Capacity(prefixes []lxc.IPv6PrefixInfo) string {
if len(prefixes) == 0 {
return "0"
}
var total uint64
for _, prefix := range prefixes {
capacity := lxc.IPv6PrefixCapacity(prefix.PrefixLen)
if capacity == "large" {
return "large"
}
parsed, err := strconv.ParseUint(capacity, 10, 64)
if err != nil {
continue
}
if ^uint64(0)-total < parsed {
return "large"
}
total += parsed
}
if total == 0 {
return "0"
}
return strconv.FormatUint(total, 10)
}
func subtractCapacity(total string, used int) string {
if total == "" || total == "0" {
return "0"
+68
View File
@@ -0,0 +1,68 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"clicd/internal/config"
)
func TestHandleRoutingGetAllowsRoutingWriteScope(t *testing.T) {
config.AppConfig = &config.ClicdConfig{}
req := httptest.NewRequest(http.MethodGet, "/api/v1/routing", nil)
req = withAuthContext(req, AuthContext{
Type: authTypeAPIKey,
Scopes: []string{"routing:write"},
})
rec := httptest.NewRecorder()
handleRoutingGet(rec, req)
if rec.Code == http.StatusForbidden {
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)
}
}
+52 -9
View File
@@ -13,10 +13,16 @@ import (
var kvmManager = kvm.NewManager()
const noNetworkSelectedMessage = "请勾选任意一个可用网络"
func runtimeFromRequest(value string) string {
return config.NormalizeVirtualization(value)
}
func hasRequestedNetwork(cfg lxc.ContainerConfig) bool {
return cfg.WantsNAT() || cfg.WantsLANIPv4() || cfg.AssignIPv4 || len(cfg.PublicIPv4s) > 0 || cfg.AssignIPv6 || len(cfg.IPv6Addresses) > 0
}
func runtimeFromTemplateID(templateID string) string {
if kvm.FindImage(templateID) != nil {
return config.VirtualizationKVM
@@ -26,12 +32,33 @@ func runtimeFromTemplateID(templateID string) string {
func createByRuntime(cfg lxc.ContainerConfig) error {
cfg.Virtualization = runtimeFromRequest(cfg.Virtualization)
cfg.NormalizeResourceAliases()
if cfg.Virtualization == config.VirtualizationKVM {
return kvmManager.CreateContainer(cfg)
}
return lxcManager.CreateContainer(cfg)
}
func validateCreateSSHAuth(cfg lxc.ContainerConfig) error {
if cfg.Virtualization == config.VirtualizationKVM && kvm.IsWindowsImage(cfg.TemplateID) {
return nil
}
_, err := lxc.ResolveCreateSSHAccess(cfg)
return err
}
func validateReinstallSSHAuth(c *config.Container, templateID string, cfg lxc.ContainerConfig) error {
if c != nil && c.IsKVM() && kvm.IsWindowsImage(templateID) {
return nil
}
currentPassword := ""
if c != nil {
currentPassword = c.SSHPassword
}
_, err := lxc.ResolveReinstallSSHAccess(currentPassword, cfg)
return err
}
func startByRuntime(id int) error {
c := config.FindContainer(id)
if c != nil && c.IsKVM() {
@@ -64,20 +91,20 @@ func destroyByRuntime(id int) error {
return lxcManager.DestroyContainer(id)
}
func reinstallByRuntime(id int, templateID string) error {
func reinstallByRuntime(id int, templateID string, authConfig ...lxc.ContainerConfig) error {
c := config.FindContainer(id)
if c != nil && c.IsKVM() {
return kvmManager.ReinstallContainer(id, templateID)
return kvmManager.ReinstallContainer(id, templateID, authConfig...)
}
return lxcManager.ReinstallContainer(id, templateID)
return lxcManager.ReinstallContainer(id, templateID, authConfig...)
}
func resetPasswordByRuntime(id int) (string, error) {
func resetPasswordByRuntime(id int, password string) (string, error) {
c := config.FindContainer(id)
if c != nil && c.IsKVM() {
return kvmManager.ResetSSHPassword(id)
return kvmManager.ResetSSHPassword(id, password)
}
return lxcManager.ResetSSHPassword(id)
return lxcManager.ResetSSHPassword(id, password)
}
func assignIPv6ByRuntime(id int) (*config.Container, error) {
@@ -88,6 +115,22 @@ func assignIPv6ByRuntime(id int) (*config.Container, error) {
return lxcManager.AssignIPv6(id)
}
func updatePublicIPv4ByRuntime(id int, requested []string, count int, auto bool) (*config.Container, error) {
c := config.FindContainer(id)
if c != nil && c.IsKVM() {
return kvmManager.UpdatePublicIPv4Assignments(id, requested, count, auto)
}
return lxcManager.UpdatePublicIPv4Assignments(id, requested, count, auto)
}
func updateIPv6ByRuntime(id int, requested []string, count int, auto bool) (*config.Container, error) {
c := config.FindContainer(id)
if c != nil && c.IsKVM() {
return kvmManager.UpdateIPv6Assignments(id, requested, count, auto)
}
return lxcManager.UpdateIPv6Assignments(id, requested, count, auto)
}
func usageByRuntime(id int) (map[string]interface{}, error) {
c := config.FindContainer(id)
if c != nil && c.IsKVM() {
@@ -104,12 +147,12 @@ func trafficByRuntime(id int) map[string]interface{} {
return lxcManager.GetTrafficInfo(id)
}
func createSnapshotByRuntime(id int, createdBy string, scheduled bool, rotateLimit int) (config.Snapshot, error) {
func createSnapshotByRuntime(id int, createdBy string, scheduled bool, rotateLimit int, storagePoolID ...string) (config.Snapshot, error) {
c := config.FindContainer(id)
if c != nil && c.IsKVM() {
return kvmManager.CreateSnapshot(id, createdBy, scheduled, rotateLimit)
return kvmManager.CreateSnapshot(id, createdBy, scheduled, rotateLimit, storagePoolID...)
}
return lxcManager.CreateSnapshot(id, createdBy, scheduled, rotateLimit)
return lxcManager.CreateSnapshot(id, createdBy, scheduled, rotateLimit, storagePoolID...)
}
func deleteSnapshotByRuntime(snapshotID string) error {
+378 -69
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"os"
"os/exec"
"sort"
"strconv"
"strings"
"sync"
@@ -48,15 +49,19 @@ type connEntry struct {
}
type trafficStats struct {
total int
totalSynSent int
destCounts map[string]int
destPorts map[string]map[int]int
portDestCounts map[int]map[string]int
portTotalCounts map[int]int
udpDestCounts map[int]map[string]int
udpTotalCounts map[int]int
synSentByDst map[string]int
total int
totalSynSent int
destCounts map[string]int
destPorts map[string]map[int]int
portDestCounts map[int]map[string]int
portTotalCounts map[int]int
udpDestCounts map[int]map[string]int
udpTotalCounts map[int]int
udpDestTotalCounts map[string]int
synSentByDst map[string]int
tcpSynDestPorts map[string]map[int]int
tcpSynPortDestCounts map[int]map[string]int
tcpSynPortTotalCounts map[int]int
}
var scanner *SecurityScanner
@@ -179,6 +184,12 @@ func (ss *SecurityScanner) monitorLoop() {
}
}
func (ss *SecurityScanner) alertCount() int {
ss.mu.Lock()
defer ss.mu.Unlock()
return len(ss.alerts)
}
func (ss *SecurityScanner) checkAllContainers() {
for _, c := range config.AppConfig.Containers {
if c.Status != "running" || c.IP == "" {
@@ -207,6 +218,7 @@ func (ss *SecurityScanner) checkContainer(name, ip string) {
return
}
alertBefore := ss.alertCount()
ss.detectPortScans(name, ip, stats)
ss.detectBruteForce(name, ip, stats)
ss.detectSpam(name, ip, stats)
@@ -215,17 +227,26 @@ func (ss *SecurityScanner) checkContainer(name, ip string) {
ss.detectMining(name, ip, stats)
ss.detectProxyAndTor(name, ip, stats)
ss.detectMalware(name, ip, stats)
// If new alerts were generated, snapshot the conntrack data for later retrieval.
if ss.alertCount() > alertBefore {
config.SaveConntrackSnapshot(ip, lines)
}
}
func newTrafficStats() *trafficStats {
return &trafficStats{
destCounts: make(map[string]int),
destPorts: make(map[string]map[int]int),
portDestCounts: make(map[int]map[string]int),
portTotalCounts: make(map[int]int),
udpDestCounts: make(map[int]map[string]int),
udpTotalCounts: make(map[int]int),
synSentByDst: make(map[string]int),
destCounts: make(map[string]int),
destPorts: make(map[string]map[int]int),
portDestCounts: make(map[int]map[string]int),
portTotalCounts: make(map[int]int),
udpDestCounts: make(map[int]map[string]int),
udpTotalCounts: make(map[int]int),
synSentByDst: make(map[string]int),
udpDestTotalCounts: make(map[string]int),
tcpSynDestPorts: make(map[string]map[int]int),
tcpSynPortDestCounts: make(map[int]map[string]int),
tcpSynPortTotalCounts: make(map[int]int),
}
}
@@ -251,52 +272,64 @@ func (ts *trafficStats) add(conn connEntry) {
}
ts.udpDestCounts[conn.dstPort][conn.dstIP]++
ts.udpTotalCounts[conn.dstPort]++
ts.udpDestTotalCounts[conn.dstIP]++
}
}
if conn.state == "SYN_SENT" {
if conn.proto == "tcp" && conn.state == "SYN_SENT" {
ts.totalSynSent++
ts.synSentByDst[conn.dstIP]++
if conn.dstPort > 0 {
if ts.tcpSynDestPorts[conn.dstIP] == nil {
ts.tcpSynDestPorts[conn.dstIP] = make(map[int]int)
}
ts.tcpSynDestPorts[conn.dstIP][conn.dstPort]++
if ts.tcpSynPortDestCounts[conn.dstPort] == nil {
ts.tcpSynPortDestCounts[conn.dstPort] = make(map[string]int)
}
ts.tcpSynPortDestCounts[conn.dstPort][conn.dstIP]++
ts.tcpSynPortTotalCounts[conn.dstPort]++
}
}
}
func (ss *SecurityScanner) detectPortScans(name, ip string, stats *trafficStats) {
for dstIP, portCounts := range stats.destPorts {
for dstIP, portCounts := range stats.tcpSynDestPorts {
uniquePorts := len(portCounts)
switch {
case uniquePorts >= 20:
case uniquePorts >= 25:
ss.addAlert(name, "port_scan", "high", ip, dstIP, 0,
fmt.Sprintf("端口扫描: 同一目标 %s 出现 %d 个不同目标端口", dstIP, uniquePorts),
fmt.Sprintf("端口扫描: 同一目标 %s 出现 %d 个不同 TCP 半开目标端口", dstIP, uniquePorts),
"")
case uniquePorts >= 8:
case uniquePorts >= 12:
ss.addAlert(name, "port_scan", "medium", ip, dstIP, 0,
fmt.Sprintf("可疑端口探测: 同一目标 %s 出现 %d 个不同目标端口", dstIP, uniquePorts),
fmt.Sprintf("可疑端口探测: 同一目标 %s 出现 %d 个不同 TCP 半开目标端口", dstIP, uniquePorts),
"")
}
}
for port, targets := range stats.portDestCounts {
for port, targets := range stats.tcpSynPortDestCounts {
uniqueTargets := len(targets)
if service, ok := bruteForcePorts[port]; ok {
if uniqueTargets >= 30 {
ss.addAlert(name, "brute_force", "critical", ip, "*", port,
fmt.Sprintf("横向爆破: 目标服务 %s(%d) 覆盖 %d 个不同 IP", service, port, uniqueTargets),
fmt.Sprintf("横向爆破: 目标服务 %s(%d) 出现 TCP 半开连接并覆盖 %d 个不同 IP", service, port, uniqueTargets),
"")
} else if uniqueTargets >= 10 {
} else if uniqueTargets >= 12 {
ss.addAlert(name, "brute_force", "high", ip, "*", port,
fmt.Sprintf("疑似横向爆破: 目标服务 %s(%d) 覆盖 %d 个不同 IP", service, port, uniqueTargets),
fmt.Sprintf("疑似横向爆破: 目标服务 %s(%d) 出现 TCP 半开连接并覆盖 %d 个不同 IP", service, port, uniqueTargets),
"")
}
continue
}
if uniqueTargets >= 40 {
if uniqueTargets >= 50 {
ss.addAlert(name, "horizontal_scan", "high", ip, "*", port,
fmt.Sprintf("横向扫描: 同一端口 %d 覆盖 %d 个不同目标", port, uniqueTargets),
fmt.Sprintf("横向扫描: 同一 TCP 端口 %d 出现半开连接并覆盖 %d 个不同目标", port, uniqueTargets),
"")
} else if uniqueTargets >= 15 {
} else if uniqueTargets >= 20 {
ss.addAlert(name, "horizontal_scan", "medium", ip, "*", port,
fmt.Sprintf("可疑横向探测: 同一端口 %d 覆盖 %d 个不同目标", port, uniqueTargets),
fmt.Sprintf("可疑横向探测: 同一 TCP 端口 %d 出现半开连接并覆盖 %d 个不同目标", port, uniqueTargets),
"")
}
}
@@ -310,13 +343,25 @@ func (ss *SecurityScanner) detectBruteForce(name, ip string, stats *trafficStats
continue
}
if count >= 20 {
synCount := 0
if ports := stats.tcpSynDestPorts[dstIP]; ports != nil {
synCount = ports[port]
}
if synCount >= 25 {
ss.addAlert(name, "brute_force", "critical", ip, dstIP, port,
fmt.Sprintf("暴力破解: %s(%d) 当前连接 %d", service, port, count),
fmt.Sprintf("暴力破解: %s(%d) 当前 TCP 半开连接 %d", service, port, synCount),
"")
} else if count >= 10 {
} else if synCount >= 12 {
ss.addAlert(name, "brute_force", "high", ip, dstIP, port,
fmt.Sprintf("疑似暴力破解: %s(%d) 当前连接 %d", service, port, count),
fmt.Sprintf("疑似暴力破解: %s(%d) 当前 TCP 半开连接 %d", service, port, synCount),
"")
} else if count >= 60 {
ss.addAlert(name, "brute_force", "critical", ip, dstIP, port,
fmt.Sprintf("暴力破解: %s(%d) 当前连接数 %d 条", service, port, count),
"")
} else if count >= 30 {
ss.addAlert(name, "brute_force", "high", ip, dstIP, port,
fmt.Sprintf("疑似暴力破解: %s(%d) 当前连接数 %d 条", service, port, count),
"")
}
}
@@ -343,30 +388,41 @@ func (ss *SecurityScanner) detectSpam(name, ip string, stats *trafficStats) {
func (ss *SecurityScanner) detectMassAbuse(name, ip string, stats *trafficStats) {
targets := len(stats.destCounts)
switch {
case targets >= 100:
case targets >= 120 && stats.total >= 600:
ss.addAlert(name, "ddos", "critical", ip, "*", 0,
fmt.Sprintf("大规模对外连接: 当前覆盖 %d 个不同目标", targets),
fmt.Sprintf("大规模对外连接: 当前 conntrack 出站记录 %d 条,覆盖 %d 个不同目标", stats.total, targets),
"")
case targets >= 35:
case targets >= 60 && stats.total >= 300:
ss.addAlert(name, "ddos", "high", ip, "*", 0,
fmt.Sprintf("大量对外连接: 当前覆盖 %d 个不同目标", targets),
fmt.Sprintf("大量对外连接: 当前 conntrack 出站记录 %d 条,覆盖 %d 个不同目标", stats.total, targets),
"")
}
synTargets := len(stats.synSentByDst)
switch {
case stats.total >= 500:
case stats.totalSynSent >= 250 || (synTargets >= 80 && stats.totalSynSent >= 160):
ss.addAlert(name, "ddos", "critical", ip, "*", 0,
fmt.Sprintf("异常大量连接: 当前 conntrack 出站记录 %d 条", stats.total),
fmt.Sprintf("大量半开连接: 当前 TCP SYN_SENT %d 条,覆盖 %d 个不同目标", stats.totalSynSent, synTargets),
"")
case stats.total >= 200:
case stats.totalSynSent >= 100 || (synTargets >= 35 && stats.totalSynSent >= 70):
ss.addAlert(name, "ddos", "high", ip, "*", 0,
fmt.Sprintf("连接: 当前 conntrack 出站记录 %d 条", stats.total),
fmt.Sprintf("可疑大量半开连接: 当前 TCP SYN_SENT %d 条,覆盖 %d 个不同目标", stats.totalSynSent, synTargets),
"")
}
if stats.totalSynSent >= 100 {
udpTargets := len(stats.udpDestTotalCounts)
udpTotal := 0
for _, count := range stats.udpTotalCounts {
udpTotal += count
}
switch {
case udpTargets >= 120 && udpTotal >= 300:
ss.addAlert(name, "ddos", "critical", ip, "*", 0,
fmt.Sprintf("大量半开连接: 当前 SYN_SENT %d 条", stats.totalSynSent),
fmt.Sprintf("UDP 大规模外发: 当前 UDP 连接 %d 条,覆盖 %d 个不同目标", udpTotal, udpTargets),
"")
case udpTargets >= 50 && udpTotal >= 120:
ss.addAlert(name, "ddos", "high", ip, "*", 0,
fmt.Sprintf("可疑 UDP 大规模外发: 当前 UDP 连接 %d 条,覆盖 %d 个不同目标", udpTotal, udpTargets),
"")
}
@@ -391,11 +447,18 @@ func (ss *SecurityScanner) detectReflectionAbuse(name, ip string, stats *traffic
continue
}
if targets >= 30 || total >= 100 {
criticalTargets, criticalTotal := 40, 120
highTargets, highTotal := 15, 45
if port == 53 {
criticalTargets, criticalTotal = 75, 300
highTargets, highTotal = 25, 100
}
if targets >= criticalTargets && total >= criticalTotal {
ss.addAlert(name, "reflection", "critical", ip, "*", port,
fmt.Sprintf("UDP 反射放大: %s(%d) 当前 UDP 连接 %d 条,覆盖 %d 个目标", service, port, total, targets),
"")
} else if targets >= 10 || total >= 30 {
} else if targets >= highTargets && total >= highTotal {
ss.addAlert(name, "reflection", "high", ip, "*", port,
fmt.Sprintf("疑似 UDP 反射放大: %s(%d) 当前 UDP 连接 %d 条,覆盖 %d 个目标", service, port, total, targets),
"")
@@ -557,10 +620,10 @@ func countPorts(totalCounts map[int]int, destCounts map[int]map[string]int, port
func (ss *SecurityScanner) addAlert(name, alertType, severity, srcIP, dstIP string, port int, detail, logLine string) {
ss.mu.Lock()
defer ss.mu.Unlock()
now := time.Now()
cutoff := now.Add(-5 * time.Minute)
shouldShutdown := false
for i := range ss.alerts {
a := &ss.alerts[i]
@@ -579,6 +642,11 @@ func (ss *SecurityScanner) addAlert(name, alertType, severity, srcIP, dstIP stri
if severityRank(severity) > severityRank(a.Severity) {
a.Severity = severity
}
shouldShutdown = config.AppConfig.SecurityAutoShutdown
ss.mu.Unlock()
if shouldShutdown {
autoShutdownAlertContainer(name, alertType, severity)
}
return
}
@@ -599,10 +667,16 @@ func (ss *SecurityScanner) addAlert(name, alertType, severity, srcIP, dstIP stri
ss.alerts = append(ss.alerts, alert)
config.AddAuditLog("security_"+alertType, name, fmt.Sprintf("[%s] %s", severity, detail), "system")
shouldShutdown = config.AppConfig.SecurityAutoShutdown
if len(ss.alerts) > 200 {
ss.alerts = ss.alerts[len(ss.alerts)-200:]
}
ss.mu.Unlock()
if shouldShutdown {
autoShutdownAlertContainer(name, alertType, severity)
}
}
func severityRank(severity string) int {
@@ -620,26 +694,97 @@ func severityRank(severity string) int {
}
}
func autoShutdownAlertContainer(containerName, alertType, severity string) {
if !config.AppConfig.SecurityAutoShutdown {
return
}
c := config.FindContainerByName(containerName)
if c == nil || c.Status != "running" {
return
}
reason := fmt.Sprintf("%s 告警触发策略临时封禁", alertType)
if severity != "" {
reason = fmt.Sprintf("[%s] %s", severity, reason)
}
config.SetContainerPolicyBlock(c.ID, true, reason)
taskID, queued := globalQueue.EnqueueSecurityStop(c.ID, c.Name)
if queued {
config.AddAuditLog("security_auto_shutdown", c.Name, fmt.Sprintf("[%s] %s 告警触发自动关机任务 %s", severity, alertType, taskID), "system")
}
}
func clearSecurityPolicyBlocks() int {
cleared := 0
for i := range config.AppConfig.Containers {
c := &config.AppConfig.Containers[i]
if !c.PolicyBlocked || !isSecurityPolicyBlockReason(c.PolicyBlockedReason) {
continue
}
config.SetContainerPolicyBlock(c.ID, false, "")
config.AddAuditLog("security_policy_unblock", c.Name, "关闭安全告警自动关机后解除策略临时封禁", "system")
cleared++
}
return cleared
}
func isSecurityPolicyBlockReason(reason string) bool {
return strings.Contains(reason, "告警触发策略临时封禁")
}
// HandleSecurityAlerts returns all security alerts.
func HandleSecurityAlerts(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
ss := ensureScanner()
ss.mu.Lock()
reversed := make([]SecurityAlert, len(ss.alerts))
for i, a := range ss.alerts {
reversed[len(ss.alerts)-1-i] = a
}
ss.mu.Unlock()
if reversed == nil {
reversed = []SecurityAlert{}
if !requireScope(w, r, "security:read") {
return
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: reversed})
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: filterSecurityAlertsForRequest(r, mergedSecurityAlerts())})
}
// HandleSecuritySettings returns or updates security automation settings.
func HandleSecuritySettings(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
if !requireScope(w, r, "security:read") {
return
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: map[string]bool{
"auto_shutdown": config.AppConfig.SecurityAutoShutdown,
}})
case http.MethodPut:
if !requireScope(w, r, "security:settings") {
return
}
var req struct {
AutoShutdown bool `json:"auto_shutdown"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
config.AppConfig.SecurityAutoShutdown = req.AutoShutdown
if err := config.SaveConfig(); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: err.Error()})
return
}
cancelledTasks := 0
clearedBlocks := 0
if !req.AutoShutdown {
cancelledTasks = globalQueue.CancelPendingSecurityStops()
clearedBlocks = clearSecurityPolicyBlocks()
}
auditRequest(r, "security.settings", "auto_shutdown", fmt.Sprintf("auto_shutdown=%v", req.AutoShutdown), true, "")
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: map[string]interface{}{
"auto_shutdown": config.AppConfig.SecurityAutoShutdown,
"cancelled_tasks": cancelledTasks,
"cleared_blocks": clearedBlocks,
}})
default:
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
}
}
// HandleSecurityCheck triggers immediate security check for a container.
@@ -648,6 +793,9 @@ func HandleSecurityCheck(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "security:check") {
return
}
var req struct {
ContainerName string `json:"container_name"`
@@ -662,6 +810,10 @@ func HandleSecurityCheck(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found or not running"})
return
}
if !isContainerAllowedForRequest(r, c.UUID) {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Access denied to this container"})
return
}
ensureScanner().checkContainer(c.Name, c.IP)
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Security check completed"})
@@ -673,6 +825,9 @@ func HandleSecurityLogs(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "security:read") {
return
}
containerName := r.URL.Query().Get("container")
if containerName == "" {
@@ -685,34 +840,59 @@ func HandleSecurityLogs(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: []map[string]interface{}{}})
return
}
if !isContainerAllowedForRequest(r, c.UUID) {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Access denied to this container"})
return
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: getConnectionLogs(c.IP)})
}
func getConnectionLogs(ip string) []map[string]interface{} {
logs := make([]map[string]interface{}, 0)
seen := map[string]bool{}
for _, line := range readConntrackLines(ip) {
parseLine := func(line string) map[string]interface{} {
srcIP := extractField(line, "src=")
dstIP := extractField(line, "dst=")
srcPort := extractField(line, "sport=")
dstPort := extractField(line, "dport=")
sPort, _ := strconv.Atoi(srcPort)
dPort, _ := strconv.Atoi(dstPort)
logs = append(logs, map[string]interface{}{
return map[string]interface{}{
"src_ip": srcIP,
"dst_ip": dstIP,
"src_port": sPort,
"dst_port": dPort,
"protocol": extractProtocol(line),
"state": extractConnState(line),
})
}
}
// First, load stored snapshots from database (persisted at alert time).
for _, line := range config.GetConntrackSnapshotLines(ip) {
if len(logs) >= 100 {
break
}
key := strings.TrimSpace(line)
if key == "" || seen[key] {
continue
}
seen[key] = true
logs = append(logs, parseLine(line))
}
// Then, merge live conntrack data (deduplicated).
for _, line := range readConntrackLines(ip) {
if len(logs) >= 100 {
break
}
key := strings.TrimSpace(line)
if key == "" || seen[key] {
continue
}
seen[key] = true
logs = append(logs, parseLine(line))
}
return logs
@@ -737,14 +917,16 @@ func HandleContainerSecuritySummary(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "security:read") {
return
}
ss := ensureScanner()
ss.mu.Lock()
critical := 0
high := 0
medium := 0
low := 0
for _, a := range ss.alerts {
alerts := filterSecurityAlertsForRequest(r, mergedSecurityAlerts())
for _, a := range alerts {
switch a.Severity {
case "critical":
critical++
@@ -756,8 +938,7 @@ func HandleContainerSecuritySummary(w http.ResponseWriter, r *http.Request) {
low++
}
}
total := len(ss.alerts)
ss.mu.Unlock()
total := len(alerts)
summary := map[string]interface{}{
"total_alerts": total,
@@ -769,3 +950,131 @@ func HandleContainerSecuritySummary(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: summary})
}
func filterSecurityAlertsForRequest(r *http.Request, alerts []SecurityAlert) []SecurityAlert {
allowed, restricted := requestAllowedContainers(r)
if !restricted {
return alerts
}
filtered := make([]SecurityAlert, 0, len(alerts))
for _, alert := range alerts {
if c := config.FindContainerByName(alert.ContainerName); c != nil && isContainerAllowed(allowed, c) {
filtered = append(filtered, alert)
}
}
return filtered
}
func mergedSecurityAlerts() []SecurityAlert {
ss := ensureScanner()
ss.mu.Lock()
alerts := make([]SecurityAlert, len(ss.alerts))
copy(alerts, ss.alerts)
ss.mu.Unlock()
seen := make(map[string]bool)
for _, alert := range alerts {
seen[securityAlertKey(alert)] = true
}
for i, log := range config.AppConfig.AuditLogs {
alert, ok := alertFromSecurityAuditLog(log, i)
if !ok {
continue
}
key := securityAlertKey(alert)
if seen[key] {
continue
}
seen[key] = true
alerts = append(alerts, alert)
}
sort.SliceStable(alerts, func(i, j int) bool {
ti, errI := time.Parse("2006-01-02 15:04:05", alerts[i].Timestamp)
tj, errJ := time.Parse("2006-01-02 15:04:05", alerts[j].Timestamp)
if errI == nil && errJ == nil && !ti.Equal(tj) {
return ti.After(tj)
}
return alerts[i].Timestamp > alerts[j].Timestamp
})
if len(alerts) > 200 {
alerts = alerts[:200]
}
if alerts == nil {
return []SecurityAlert{}
}
return alerts
}
func securityAlertKey(alert SecurityAlert) string {
return strings.Join([]string{
alert.Timestamp,
alert.ContainerName,
alert.Type,
alert.Detail,
strconv.Itoa(alert.TargetPort),
}, "\x1f")
}
func alertFromSecurityAuditLog(log config.AuditLog, index int) (SecurityAlert, bool) {
if !strings.HasPrefix(log.Action, "security_") || log.Action == "security_auto_shutdown" || log.Action == "security_policy_unblock" {
return SecurityAlert{}, false
}
alertType := strings.TrimPrefix(log.Action, "security_")
severity, detail := parseSecurityAuditDetail(log.Detail)
targetPort := parseDetailPort(detail)
targetIP := ""
if targetPort > 0 || alertType == "horizontal_scan" || alertType == "brute_force" {
targetIP = "*"
}
return SecurityAlert{
ID: fmt.Sprintf("audit-security-%d", index),
ContainerName: log.Target,
Type: alertType,
Severity: severity,
SourceIP: "",
TargetIP: targetIP,
TargetPort: targetPort,
Detail: detail,
LogLine: "",
Timestamp: log.Time,
Count: 1,
}, true
}
func parseSecurityAuditDetail(detail string) (string, string) {
severity := "medium"
if strings.HasPrefix(detail, "[") {
if end := strings.Index(detail, "]"); end > 1 {
severity = detail[1:end]
detail = strings.TrimSpace(detail[end+1:])
}
}
return severity, detail
}
func parseDetailPort(detail string) int {
for _, marker := range []string{"端口 ", "端口"} {
idx := strings.Index(detail, marker)
if idx == -1 {
continue
}
start := idx + len(marker)
for start < len(detail) && (detail[start] == ' ' || detail[start] == ':' || detail[start] == '(') {
start++
}
end := start
for end < len(detail) && detail[end] >= '0' && detail[end] <= '9' {
end++
}
if end > start {
port, _ := strconv.Atoi(detail[start:end])
return port
}
}
return 0
}
+148
View File
@@ -0,0 +1,148 @@
package api
import (
"fmt"
"testing"
"clicd/internal/config"
)
func TestDetectReflectionAbuseIgnoresSingleDNSResolver(t *testing.T) {
resetSecurityTestConfig()
stats := newTrafficStats()
for i := 0; i < 180; i++ {
stats.add(connEntry{
dstIP: "1.1.1.1",
dstPort: 53,
proto: "udp",
state: "UNREPLIED",
})
}
ss := newSecurityScanner()
ss.detectReflectionAbuse("ct-dns", "10.0.0.2", stats)
if len(ss.alerts) != 0 {
t.Fatalf("normal DNS queries to one resolver should not trigger reflection alert: %+v", ss.alerts)
}
}
func TestDetectReflectionAbuseFlagsWideDNSFanout(t *testing.T) {
resetSecurityTestConfig()
stats := newTrafficStats()
for i := 0; i < 120; i++ {
stats.add(connEntry{
dstIP: fmt.Sprintf("203.0.113.%d", i),
dstPort: 53,
proto: "udp",
state: "UNREPLIED",
})
}
ss := newSecurityScanner()
ss.detectReflectionAbuse("ct-dns", "10.0.0.2", stats)
if len(ss.alerts) != 1 {
t.Fatalf("expected one reflection alert, got %+v", ss.alerts)
}
if got := ss.alerts[0].Type; got != "reflection" {
t.Fatalf("expected reflection alert, got %q", got)
}
}
func TestDetectPortScansUsesHalfOpenConnections(t *testing.T) {
resetSecurityTestConfig()
established := newTrafficStats()
for port := 8000; port < 8020; port++ {
established.add(connEntry{
dstIP: "198.51.100.10",
dstPort: port,
proto: "tcp",
state: "ESTABLISHED",
})
}
ss := newSecurityScanner()
ss.detectPortScans("ct-web", "10.0.0.3", established)
if len(ss.alerts) != 0 {
t.Fatalf("established multi-port connections should not trigger port scan alert: %+v", ss.alerts)
}
halfOpen := newTrafficStats()
for port := 8000; port < 8012; port++ {
halfOpen.add(connEntry{
dstIP: "198.51.100.10",
dstPort: port,
proto: "tcp",
state: "SYN_SENT",
})
}
ss.detectPortScans("ct-web", "10.0.0.3", halfOpen)
if len(ss.alerts) != 1 {
t.Fatalf("expected one port scan alert, got %+v", ss.alerts)
}
if got := ss.alerts[0].Type; got != "port_scan" {
t.Fatalf("expected port_scan alert, got %q", got)
}
}
func TestCancelPendingSecurityStops(t *testing.T) {
resetSecurityTestConfig()
q := &TaskQueue{
tasks: map[string]*Task{},
}
securityTask := &Task{
ID: "task-1",
Type: TaskStop,
ContainerID: 1,
Status: "pending",
User: "system:security",
}
userTask := &Task{
ID: "task-2",
Type: TaskStop,
ContainerID: 2,
Status: "pending",
User: "admin",
}
runningSecurityTask := &Task{
ID: "task-3",
Type: TaskStop,
ContainerID: 3,
Status: "running",
User: "system:security",
}
q.tasks[securityTask.ID] = securityTask
q.tasks[userTask.ID] = userTask
q.tasks[runningSecurityTask.ID] = runningSecurityTask
q.opQueue = []*Task{securityTask, userTask, runningSecurityTask}
if got := q.CancelPendingSecurityStops(); got != 1 {
t.Fatalf("expected one pending security stop to be cancelled, got %d", got)
}
if _, ok := q.tasks[securityTask.ID]; ok {
t.Fatal("pending security stop task was not removed")
}
if _, ok := q.tasks[userTask.ID]; !ok {
t.Fatal("user stop task should not be removed")
}
if _, ok := q.tasks[runningSecurityTask.ID]; !ok {
t.Fatal("running security stop task should be left for worker-side skip")
}
if len(q.opQueue) != 2 {
t.Fatalf("expected op queue to keep two tasks, got %d", len(q.opQueue))
}
}
func resetSecurityTestConfig() {
config.AppConfig = &config.ClicdConfig{
Containers: []config.Container{},
AuditLogs: []config.AuditLog{},
Tasks: []config.SavedTask{},
}
}
+64
View File
@@ -2,6 +2,7 @@ package api
import (
"encoding/json"
"fmt"
"net/http"
"time"
@@ -20,6 +21,66 @@ type LoginLog struct {
var loginLogs = make([]LoginLog, 0)
// HandleLanguage returns or updates the global panel language.
func HandleLanguage(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: map[string]string{
"language": config.NormalizeLanguage(config.AppConfig.Language),
}})
case http.MethodPost, http.MethodPut:
var req struct {
Language string `json:"language"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
config.AppConfig.Language = config.NormalizeLanguage(req.Language)
if err := config.SaveConfig(); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to save language"})
return
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: map[string]string{
"language": config.AppConfig.Language,
}})
default:
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
}
}
// HandleTaskQueueSettings returns or updates the global task concurrency limit.
func HandleTaskQueueSettings(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: globalQueue.Settings()})
case http.MethodPut, http.MethodPost:
var req struct {
Concurrency int `json:"concurrency"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
if req.Concurrency < 1 || req.Concurrency > config.MaxTaskConcurrency {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "任务并发数必须在 1 到 16 之间"})
return
}
previous := config.AppConfig.TaskConcurrency
config.AppConfig.TaskConcurrency = req.Concurrency
if err := config.SaveConfig(); err != nil {
config.AppConfig.TaskConcurrency = previous
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "保存任务队列设置失败"})
return
}
globalQueue.SetConcurrency(req.Concurrency)
auditRequest(r, "settings.task_queue", "task_concurrency", fmt.Sprintf("concurrency=%d", req.Concurrency), true, "")
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "任务队列设置已保存", Data: globalQueue.Settings()})
default:
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
}
}
// RecordLoginLog adds a login attempt to the log (persisted to config)
func RecordLoginLog(username, ip, userAgent string, success bool) {
config.AddLoginLog(username, ip, userAgent, success)
@@ -56,6 +117,9 @@ func HandleLoginLogs(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "loginlog:read") {
return
}
// Return in reverse (newest first)
reversed := make([]LoginLog, len(loginLogs))
+59 -10
View File
@@ -2,6 +2,7 @@ package api
import (
"encoding/json"
"io"
"net/http"
"sort"
"strconv"
@@ -16,7 +17,11 @@ func HandleSnapshots(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "snapshot:read") {
return
}
snapshots := append([]config.Snapshot(nil), config.AppConfig.Snapshots...)
snapshots = filterSnapshotsForRequest(r, snapshots)
sortSnapshotsNewestFirst(snapshots)
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: snapshots})
}
@@ -24,17 +29,35 @@ func HandleSnapshots(w http.ResponseWriter, r *http.Request) {
func handleContainerSnapshots(w http.ResponseWriter, r *http.Request, containerID int, action string) {
switch {
case action == "snapshots" && r.Method == http.MethodGet:
if !requireScope(w, r, "snapshot:read") {
return
}
listContainerSnapshots(w, r, containerID)
case action == "snapshots" && r.Method == http.MethodPost:
if !requireScope(w, r, "snapshot:create") {
return
}
createContainerSnapshot(w, r, containerID)
case action == "snapshots/schedule" && r.Method == http.MethodPost:
if !requireScope(w, r, "snapshot:schedule") {
return
}
updateSnapshotSchedule(w, r, containerID)
case action == "snapshots/quota" && r.Method == http.MethodPut:
if !requireScope(w, r, "snapshot:schedule") {
return
}
updateSnapshotQuota(w, r, containerID)
case strings.HasPrefix(action, "snapshots/") && strings.HasSuffix(action, "/restore") && r.Method == http.MethodPost:
if !requireScope(w, r, "snapshot:restore") {
return
}
snapshotID := strings.TrimSuffix(strings.TrimPrefix(action, "snapshots/"), "/restore")
restoreContainerSnapshot(w, r, containerID, snapshotID)
case strings.HasPrefix(action, "snapshots/") && r.Method == http.MethodDelete:
if !requireScope(w, r, "snapshot:delete") {
return
}
snapshotID := strings.TrimPrefix(action, "snapshots/")
deleteContainerSnapshot(w, r, containerID, snapshotID)
default:
@@ -66,6 +89,20 @@ func listContainerSnapshots(w http.ResponseWriter, r *http.Request, containerID
func createContainerSnapshot(w http.ResponseWriter, r *http.Request, containerID int) {
user := requestUser(r)
var req struct {
StoragePoolID string `json:"storage_pool_id"`
}
if r.Body != nil {
if err := json.NewDecoder(r.Body).Decode(&req); err != nil && err != io.EOF {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
}
req.StoragePoolID = strings.TrimSpace(req.StoragePoolID)
if _, err := config.SelectStoragePoolForContent(config.StorageContentSnapshots, req.StoragePoolID, 0); err != nil {
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: err.Error()})
return
}
if isSubUserRequest(r) {
c := config.FindContainer(containerID)
limit := config.ContainerSnapshotLimit(c)
@@ -74,7 +111,7 @@ func createContainerSnapshot(w http.ResponseWriter, r *http.Request, containerID
return
}
}
snapshot, err := createSnapshotByRuntime(containerID, user, false, 0)
snapshot, err := createSnapshotByRuntime(containerID, user, false, 0, req.StoragePoolID)
if err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: err.Error()})
return
@@ -137,6 +174,12 @@ func updateSnapshotSchedule(w http.ResponseWriter, r *http.Request, containerID
if req.Time == "" {
req.Time = "03:00"
}
if req.Enabled {
if _, err := config.SelectStoragePoolForContent(config.StorageContentSnapshots, "", 0); err != nil {
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: err.Error()})
return
}
}
user := requestUser(r)
c, err := setSnapshotScheduleByRuntime(containerID, req.Enabled, req.IntervalHours, req.Time, user)
if err != nil {
@@ -186,15 +229,7 @@ func restoreContainerSnapshot(w http.ResponseWriter, r *http.Request, containerI
}
func requestUser(r *http.Request) string {
if claims, ok := claimsFromRequest(r); ok {
if subUser, _ := claims["sub_user"].(string); subUser != "" {
return "user:" + subUser
}
if username, _ := claims["username"].(string); username != "" {
return username
}
}
return "admin"
return requestActor(r)
}
func sortSnapshotsNewestFirst(snapshots []config.Snapshot) {
@@ -204,3 +239,17 @@ func sortSnapshotsNewestFirst(snapshots []config.Snapshot) {
return tj.Before(ti)
})
}
func filterSnapshotsForRequest(r *http.Request, snapshots []config.Snapshot) []config.Snapshot {
allowed, restricted := requestAllowedContainers(r)
if !restricted {
return snapshots
}
filtered := make([]config.Snapshot, 0, len(snapshots))
for _, snapshot := range snapshots {
if c := config.FindContainer(snapshot.ContainerID); c != nil && isContainerAllowed(allowed, c) {
filtered = append(filtered, snapshot)
}
}
return filtered
}
+20 -5
View File
@@ -27,6 +27,7 @@ type terminalResizeMessage struct {
type webSSHTicket struct {
ContainerName string
SubUser bool
ExpiresAt time.Time
}
@@ -41,6 +42,9 @@ func HandleWebSSHTicket(w http.ResponseWriter, r *http.Request) {
return
}
if !requireScope(w, r, "terminal:ssh") {
return
}
var req struct {
ContainerName string `json:"container_name"`
}
@@ -52,16 +56,22 @@ func HandleWebSSHTicket(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Access denied to this container"})
return
}
if config.FindContainerByName(req.ContainerName) == nil {
c := config.FindContainerByName(req.ContainerName)
if c == nil {
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"})
return
}
if isSubUserRequest(r) && c.PolicyBlocked {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: policyBlockedMessage(c)})
return
}
ticket := randomHex(32)
webSSHTickets.Lock()
cleanupExpiredWebSSHTicketsLocked(time.Now())
webSSHTickets.items[ticket] = webSSHTicket{
ContainerName: req.ContainerName,
SubUser: isSubUserRequest(r),
ExpiresAt: time.Now().Add(60 * time.Second),
}
webSSHTickets.Unlock()
@@ -86,7 +96,8 @@ func HandleWebSSH(w http.ResponseWriter, r *http.Request) {
return
}
if !consumeWebSSHTicket(ticket, containerName) {
item, ok := consumeWebSSHTicket(ticket, containerName)
if !ok {
http.Error(w, "invalid or expired ticket", http.StatusUnauthorized)
return
}
@@ -96,6 +107,10 @@ func HandleWebSSH(w http.ResponseWriter, r *http.Request) {
http.Error(w, "container not found", http.StatusNotFound)
return
}
if item.SubUser && c.PolicyBlocked {
http.Error(w, "虚拟机被策略临时封禁", http.StatusForbidden)
return
}
if c.Status != "running" {
http.Error(w, "container is not running", http.StatusBadRequest)
return
@@ -359,17 +374,17 @@ func writeWebSocketText(ws *websocket.Conn, writeMu *sync.Mutex, msg string) {
_ = ws.WriteMessage(websocket.TextMessage, []byte(msg))
}
func consumeWebSSHTicket(ticket, containerName string) bool {
func consumeWebSSHTicket(ticket, containerName string) (webSSHTicket, bool) {
now := time.Now()
webSSHTickets.Lock()
defer webSSHTickets.Unlock()
cleanupExpiredWebSSHTicketsLocked(now)
item, ok := webSSHTickets.items[ticket]
if !ok {
return false
return webSSHTicket{}, false
}
delete(webSSHTickets.items, ticket)
return item.ContainerName == containerName && now.Before(item.ExpiresAt)
return item, item.ContainerName == containerName && now.Before(item.ExpiresAt)
}
func cleanupExpiredWebSSHTicketsLocked(now time.Time) {
+587
View File
@@ -0,0 +1,587 @@
package api
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"math/big"
"net"
"net/http"
"os"
"os/exec"
"strings"
"time"
"clicd/internal/config"
)
type sslSettingsRequest struct {
Enabled bool `json:"enabled"`
Mode string `json:"mode"`
Target string `json:"target"`
Email string `json:"email"`
CertPEM string `json:"cert_pem"`
KeyPEM string `json:"key_pem"`
ApplyNow bool `json:"apply_now"`
}
type sslCertificateInfo struct {
Subject string `json:"subject"`
Issuer string `json:"issuer"`
DNSNames []string `json:"dns_names"`
IPNames []string `json:"ip_names"`
NotBefore string `json:"not_before"`
NotAfter string `json:"not_after"`
Valid bool `json:"valid"`
}
type sslSavedCertificateStatus struct {
config.SSLConfig
Certificate *sslCertificateInfo `json:"certificate,omitempty"`
}
type sslSettingsResponse struct {
config.SSLConfig
DetectedHost string `json:"detected_host"`
Certificate *sslCertificateInfo `json:"certificate,omitempty"`
ModeCertificates map[string]sslSavedCertificateStatus `json:"mode_certificates"`
NeedsRestart bool `json:"needs_restart,omitempty"`
}
func HandleSSLSettings(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: sslSettingsStatus(r, false)})
case http.MethodPut:
updateSSLSettings(w, r)
default:
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
}
}
func updateSSLSettings(w http.ResponseWriter, r *http.Request) {
var req sslSettingsRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
mode := config.NormalizeSSLMode(req.Mode)
if !req.Enabled || mode == config.SSLModeDisabled {
saveCurrentSSLSlot()
config.AppConfig.SSL = config.SSLConfig{Enabled: false, Mode: config.SSLModeDisabled}
if err := config.SaveConfig(); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Save SSL settings failed"})
return
}
restartIfRequested(req.ApplyNow)
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "SSL disabled", Data: sslSettingsStatus(r, true)})
return
}
target := strings.TrimSpace(req.Target)
if target == "" {
target = detectedRequestHost(r)
}
normalizedTarget, err := config.NormalizeSSLCertificateTarget(target)
if err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
target = normalizedTarget
next, err := resolveSSLModeCertificate(mode, target, strings.TrimSpace(req.Email), req.CertPEM, req.KeyPEM)
if err != nil {
_ = config.SaveConfig()
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error(), Data: sslSettingsStatus(r, false)})
return
}
if err := validateCertificatePair(next.CertPath, next.KeyPath); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
next.LastIssuedAt = time.Now().Format(time.RFC3339)
next.Enabled = true
config.AppConfig.SSL = next
saveSSLSlot(next)
if err := config.SaveConfig(); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Save SSL settings failed"})
return
}
restartIfRequested(req.ApplyNow)
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "SSL settings saved", Data: sslSettingsStatus(r, true)})
}
func sslSettingsStatus(r *http.Request, needsRestart bool) sslSettingsResponse {
cfg := config.AppConfig.SSL
cfg.KeyPath = maskExistingPath(cfg.KeyPath)
resp := sslSettingsResponse{
SSLConfig: cfg,
DetectedHost: detectedRequestHost(r),
ModeCertificates: sslModeCertificatesStatus(),
NeedsRestart: needsRestart,
}
if cert, err := readCertificateInfo(config.AppConfig.SSL.CertPath); err == nil {
resp.Certificate = cert
}
return resp
}
func resolveSSLModeCertificate(mode, target, email, certPEM, keyPEM string) (config.SSLConfig, error) {
if config.AppConfig.SSLCertificates == nil {
config.AppConfig.SSLCertificates = map[string]config.SSLConfig{}
}
next := config.AppConfig.SSLCertificates[mode]
next.Mode = mode
next.Target = target
if email != "" || next.Email == "" {
next.Email = email
}
var err error
switch mode {
case config.SSLModeUploaded:
if strings.TrimSpace(certPEM) != "" || strings.TrimSpace(keyPEM) != "" {
next.CertPath, next.KeyPath, err = saveUploadedCertificate(certPEM, keyPEM)
} else if next.CertPath == "" || next.KeyPath == "" {
err = fmt.Errorf("certificate and private key are required")
} else if !certificateUsable(next.CertPath, next.KeyPath, target) {
err = fmt.Errorf("uploaded certificate is expired, invalid, or does not match the target")
}
case config.SSLModeSelfSigned:
if !certificateUsable(next.CertPath, next.KeyPath, target) {
next.CertPath, next.KeyPath, err = generateSelfSignedCertificate(target)
}
case config.SSLModeLetsEncrypt:
if !certificateUsable(next.CertPath, next.KeyPath, target) {
next.CertPath, next.KeyPath, err = requestLetsEncryptCertificate(target, next.Email)
}
default:
err = fmt.Errorf("unsupported SSL mode")
}
if err != nil {
next.LastError = err.Error()
saveSSLSlot(next)
return next, err
}
next.LastError = ""
return next, nil
}
func sslModeCertificatesStatus() map[string]sslSavedCertificateStatus {
result := map[string]sslSavedCertificateStatus{}
for _, mode := range []string{config.SSLModeLetsEncrypt, config.SSLModeSelfSigned, config.SSLModeUploaded} {
cfg := config.AppConfig.SSLCertificates[mode]
cfg.KeyPath = maskExistingPath(cfg.KeyPath)
status := sslSavedCertificateStatus{SSLConfig: cfg}
if cert, err := readCertificateInfo(config.AppConfig.SSLCertificates[mode].CertPath); err == nil {
status.Certificate = cert
}
result[mode] = status
}
return result
}
func saveCurrentSSLSlot() {
if config.AppConfig.SSL.Mode == config.SSLModeDisabled || config.AppConfig.SSL.CertPath == "" {
return
}
saveSSLSlot(config.AppConfig.SSL)
}
func saveSSLSlot(ssl config.SSLConfig) {
mode := config.NormalizeSSLMode(ssl.Mode)
if mode == config.SSLModeDisabled {
return
}
if config.AppConfig.SSLCertificates == nil {
config.AppConfig.SSLCertificates = map[string]config.SSLConfig{}
}
ssl.Mode = mode
ssl.Enabled = false
config.AppConfig.SSLCertificates[mode] = ssl
}
func saveUploadedCertificate(certPEM, keyPEM string) (string, string, error) {
certPEM = strings.TrimSpace(certPEM)
keyPEM = strings.TrimSpace(keyPEM)
if certPEM == "" || keyPEM == "" {
return "", "", fmt.Errorf("certificate and private key are required")
}
if _, err := tls.X509KeyPair([]byte(certPEM), []byte(keyPEM)); err != nil {
return "", "", fmt.Errorf("certificate/private key mismatch: %v", err)
}
certPath, keyPath, err := config.UploadedSSLPaths()
if err != nil {
return "", "", err
}
if err := os.WriteFile(certPath, []byte(certPEM+"\n"), 0600); err != nil {
return "", "", err
}
if err := os.WriteFile(keyPath, []byte(keyPEM+"\n"), 0600); err != nil {
return "", "", err
}
return certPath, keyPath, nil
}
func generateSelfSignedCertificate(target string) (string, string, error) {
target = strings.TrimSpace(target)
normalizedTarget, err := config.NormalizeSSLCertificateTarget(target)
if err != nil {
return "", "", err
}
target = normalizedTarget
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return "", "", err
}
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
return "", "", err
}
now := time.Now()
tpl := x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{
CommonName: target,
},
NotBefore: now.Add(-time.Hour),
NotAfter: now.AddDate(1, 0, 0),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
if ip := net.ParseIP(target); ip != nil {
tpl.IPAddresses = []net.IP{ip}
} else {
tpl.DNSNames = []string{target}
}
der, err := x509.CreateCertificate(rand.Reader, &tpl, &tpl, &key.PublicKey, key)
if err != nil {
return "", "", err
}
keyDER, err := x509.MarshalECPrivateKey(key)
if err != nil {
return "", "", err
}
certPath, keyPath, err := config.SelfSignedSSLPaths()
if err != nil {
return "", "", err
}
certOut := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
keyOut := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
if err := os.WriteFile(certPath, certOut, 0600); err != nil {
return "", "", err
}
if err := os.WriteFile(keyPath, keyOut, 0600); err != nil {
return "", "", err
}
return certPath, keyPath, nil
}
func requestLetsEncryptCertificate(target, email string) (string, string, error) {
if _, err := exec.LookPath("certbot"); err != nil {
return "", "", fmt.Errorf("certbot is not installed on this server")
}
target = strings.TrimSpace(target)
normalizedTarget, err := config.NormalizeSSLCertificateTarget(target)
if err != nil {
return "", "", err
}
target = normalizedTarget
args := []string{"certonly", "--non-interactive", "--agree-tos", "--standalone"}
if email != "" {
args = append(args, "--email", email)
} else {
args = append(args, "--register-unsafely-without-email")
}
if net.ParseIP(target) != nil {
if err := ensureCertbotSupportsIPCertificates(); err != nil {
return "", "", err
}
args = append(args, "--preferred-profile", "shortlived", "--ip-address", target)
} else {
args = append(args, "-d", target)
}
cmd := exec.Command("certbot", args...)
output, err := cmd.CombinedOutput()
if err != nil {
return "", "", fmt.Errorf("Let's Encrypt request failed: %s", strings.TrimSpace(string(output)))
}
certPath, keyPath, err := config.LetsEncryptSSLPaths(target)
if err != nil {
return "", "", err
}
if _, err := config.ReadableFileStat(certPath); err != nil {
return "", "", fmt.Errorf("Let's Encrypt certificate file not found after issuance: %s", certPath)
}
if _, err := config.ReadableFileStat(keyPath); err != nil {
return "", "", fmt.Errorf("Let's Encrypt private key file not found after issuance: %s", keyPath)
}
return certPath, keyPath, nil
}
func ensureCertbotSupportsIPCertificates() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "certbot", "--help", "all")
output, err := cmd.CombinedOutput()
if ctx.Err() == context.DeadlineExceeded {
return fmt.Errorf("certbot check timed out")
}
if err != nil {
return fmt.Errorf("certbot capability check failed: %s", strings.TrimSpace(string(output)))
}
help := string(output)
if !strings.Contains(help, "--ip-address") || !strings.Contains(help, "--preferred-profile") {
return fmt.Errorf("current certbot does not support IP certificates; install Certbot 5.4+ from snap or another current source")
}
return nil
}
func validateCertificatePair(certPath, keyPath string) error {
safeCertPath, err := config.ResolveSSLPath(certPath)
if err != nil {
return err
}
safeKeyPath, err := config.ResolveSSLPath(keyPath)
if err != nil {
return err
}
certPEM, err := os.ReadFile(safeCertPath)
if err != nil {
return err
}
keyPEM, err := os.ReadFile(safeKeyPath)
if err != nil {
return err
}
if _, err := tls.X509KeyPair(certPEM, keyPEM); err != nil {
return fmt.Errorf("certificate/private key mismatch: %v", err)
}
return nil
}
func certificateUsable(certPath, keyPath, target string) bool {
if certPath == "" || keyPath == "" {
return false
}
if err := validateCertificatePair(certPath, keyPath); err != nil {
return false
}
cert, err := readLeafCertificate(certPath)
if err != nil {
return false
}
now := time.Now()
if now.Before(cert.NotBefore) || !now.Before(cert.NotAfter) {
return false
}
return certificateMatchesTarget(cert, target)
}
func certificateNeedsRenewal(certPath, keyPath, target string, renewBefore time.Duration) bool {
if certPath == "" || keyPath == "" {
return true
}
if err := validateCertificatePair(certPath, keyPath); err != nil {
return true
}
cert, err := readLeafCertificate(certPath)
if err != nil {
return true
}
now := time.Now()
if now.Before(cert.NotBefore) || !now.Before(cert.NotAfter) {
return true
}
if !certificateMatchesTarget(cert, target) {
return true
}
return cert.NotAfter.Sub(now) <= renewBefore
}
func certificateMatchesTarget(cert *x509.Certificate, target string) bool {
target = strings.TrimSpace(strings.Trim(target, "[]"))
if target == "" {
return true
}
if ip := net.ParseIP(target); ip != nil {
for _, certIP := range cert.IPAddresses {
if certIP.Equal(ip) {
return true
}
}
return false
}
if err := cert.VerifyHostname(target); err != nil {
return false
}
return true
}
func readCertificateInfo(certPath string) (*sslCertificateInfo, error) {
cert, err := readLeafCertificate(certPath)
if err != nil {
return nil, err
}
ipNames := make([]string, 0, len(cert.IPAddresses))
for _, ip := range cert.IPAddresses {
ipNames = append(ipNames, ip.String())
}
return &sslCertificateInfo{
Subject: cert.Subject.String(),
Issuer: cert.Issuer.String(),
DNSNames: cert.DNSNames,
IPNames: ipNames,
NotBefore: cert.NotBefore.Format(time.RFC3339),
NotAfter: cert.NotAfter.Format(time.RFC3339),
Valid: time.Now().After(cert.NotBefore) && time.Now().Before(cert.NotAfter),
}, nil
}
func readLeafCertificate(certPath string) (*x509.Certificate, error) {
if certPath == "" {
return nil, errors.New("certificate path is empty")
}
safeCertPath, err := config.ResolveSSLPath(certPath)
if err != nil {
return nil, err
}
data, err := os.ReadFile(safeCertPath)
if err != nil {
return nil, err
}
block, _ := pem.Decode(data)
if block == nil {
return nil, errors.New("certificate PEM is invalid")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
return cert, nil
}
func detectedRequestHost(r *http.Request) string {
host := strings.TrimSpace(r.Host)
if host == "" {
return firstPublicInterfaceIP()
}
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
host = strings.Trim(host, "[]")
if host == "localhost" || net.ParseIP(host).IsLoopback() {
if ip := firstPublicInterfaceIP(); ip != "" {
return ip
}
}
return host
}
func firstPublicInterfaceIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if !ok {
continue
}
ip := ipNet.IP.To4()
if ip == nil || ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() {
continue
}
return ip.String()
}
return ""
}
func maskExistingPath(path string) string {
if path == "" {
return ""
}
return path
}
func restartIfRequested(applyNow bool) {
if !applyNow {
return
}
go func() {
time.Sleep(500 * time.Millisecond)
_ = exec.Command("systemctl", "restart", "clicd").Start()
}()
}
func StartSSLRenewalMonitor() {
go func() {
time.Sleep(30 * time.Second)
renewSavedSSLCertificates()
ticker := time.NewTicker(6 * time.Hour)
defer ticker.Stop()
for range ticker.C {
renewSavedSSLCertificates()
}
}()
}
func renewSavedSSLCertificates() {
if config.AppConfig == nil || len(config.AppConfig.SSLCertificates) == 0 {
return
}
changed := false
for mode, cert := range config.AppConfig.SSLCertificates {
mode = config.NormalizeSSLMode(mode)
if cert.Target == "" || mode == config.SSLModeDisabled || mode == config.SSLModeUploaded {
continue
}
var certPath, keyPath string
var err error
switch mode {
case config.SSLModeLetsEncrypt:
if !certificateNeedsRenewal(cert.CertPath, cert.KeyPath, cert.Target, 48*time.Hour) {
continue
}
certPath, keyPath, err = requestLetsEncryptCertificate(cert.Target, cert.Email)
case config.SSLModeSelfSigned:
if !certificateNeedsRenewal(cert.CertPath, cert.KeyPath, cert.Target, 30*24*time.Hour) {
continue
}
certPath, keyPath, err = generateSelfSignedCertificate(cert.Target)
}
if err != nil {
cert.LastError = err.Error()
config.AppConfig.SSLCertificates[mode] = cert
changed = true
continue
}
cert.CertPath = certPath
cert.KeyPath = keyPath
cert.LastIssuedAt = time.Now().Format(time.RFC3339)
cert.LastError = ""
config.AppConfig.SSLCertificates[mode] = cert
if config.AppConfig.SSL.Enabled && config.AppConfig.SSL.Mode == mode {
active := cert
active.Enabled = true
config.AppConfig.SSL = active
}
changed = true
}
if changed {
_ = config.SaveConfig()
}
}
+498
View File
@@ -0,0 +1,498 @@
package api
import (
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
pathpkg "path"
"path/filepath"
"strings"
"clicd/internal/config"
)
type storageInfoResponse struct {
Pools []storagePoolInfo `json:"pools"`
Disks []storageDiskInfo `json:"disks"`
ContentTypes []string `json:"content_types"`
}
type storagePoolInfo struct {
config.StoragePool
Available bool `json:"available"`
Exists bool `json:"exists"`
SizeBytes int64 `json:"size_bytes"`
UsedBytes int64 `json:"used_bytes"`
FreeBytes int64 `json:"free_bytes"`
ClicdUsedBytes int64 `json:"clicd_used_bytes"`
ContentUsage []storageContentUsage `json:"content_usage"`
Error string `json:"error,omitempty"`
}
type storageContentUsage struct {
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
}
type storageDiskInfo struct {
Name string `json:"name"`
Path string `json:"path"`
Type string `json:"type"`
FSType string `json:"fstype"`
MountPoint string `json:"mount_point"`
Model string `json:"model"`
SizeBytes int64 `json:"size_bytes"`
UsedBytes int64 `json:"used_bytes"`
FreeBytes int64 `json:"free_bytes"`
StoragePoolID string `json:"storage_pool_id,omitempty"`
StoragePath string `json:"storage_path,omitempty"`
ClicdUsedBytes int64 `json:"clicd_used_bytes"`
ContentUsage []storageContentUsage `json:"content_usage"`
}
func HandleStorage(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: buildStorageInfo()})
case http.MethodPut:
var req struct {
Pools []config.StoragePool `json:"pools"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
pools, err := normalizeStoragePoolsRequest(req.Pools)
if err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
for _, pool := range pools {
if err := os.MkdirAll(pool.Path, 0755); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: fmt.Sprintf("Failed to create %s: %v", pool.Path, err)})
return
}
}
config.AppConfig.StoragePools = pools
if err := config.SaveConfig(); err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to save storage pools"})
return
}
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: buildStorageInfo()})
default:
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
}
}
func buildStorageInfo() storageInfoResponse {
disks := detectStorageDisks()
pools := make([]storagePoolInfo, 0, len(config.AppConfig.StoragePools))
for _, pool := range config.AppConfig.StoragePools {
info := storagePoolInfo{StoragePool: pool}
if filepath.Clean(pool.MountPoint) == string(os.PathSeparator) {
_ = os.MkdirAll(pool.Path, 0755)
}
if st, err := os.Stat(pool.Path); err == nil && st.IsDir() {
info.Exists = true
} else if err != nil {
info.Error = err.Error()
}
detectedMountPoint := bestMountPointForPath(pool.Path, disks)
if info.MountPoint == "" {
info.MountPoint = detectedMountPoint
}
if detectedMountPoint != "" && filepath.Clean(info.MountPoint) == filepath.Clean(detectedMountPoint) {
info.Available = info.Exists
info.SizeBytes, info.UsedBytes, info.FreeBytes = dfPath(pool.Path)
info.ContentUsage, info.ClicdUsedBytes = contentUsageForPool(pool.Path)
} else if info.Error == "" {
info.Error = "storage disk is not mounted"
}
pools = append(pools, info)
}
for i := range disks {
for _, pool := range pools {
if pool.MountPoint != disks[i].MountPoint {
continue
}
disks[i].ClicdUsedBytes += pool.ClicdUsedBytes
disks[i].ContentUsage = mergeContentUsage(disks[i].ContentUsage, pool.ContentUsage)
if disks[i].StoragePoolID == "" {
disks[i].StoragePoolID = pool.ID
disks[i].StoragePath = pool.Path
}
}
}
return storageInfoResponse{
Pools: pools,
Disks: disks,
ContentTypes: []string{
config.StorageContentLXC,
config.StorageContentKVM,
config.StorageContentImages,
config.StorageContentSnapshots,
config.StorageContentBackups,
},
}
}
func normalizeStoragePoolsRequest(items []config.StoragePool) ([]config.StoragePool, error) {
return normalizeStoragePoolsRequestWithDisks(items, detectStorageDisks())
}
func normalizeStoragePoolsRequestWithDisks(items []config.StoragePool, disks []storageDiskInfo) ([]config.StoragePool, error) {
if len(items) == 0 {
return nil, fmt.Errorf("at least one mounted storage disk configuration must be retained")
}
result := make([]config.StoragePool, 0, len(items))
seen := map[string]bool{}
defaultSeen := map[string]bool{}
for _, item := range items {
disk, managedPath, err := storageDiskForPoolRequest(item, disks)
if err != nil {
return nil, err
}
id, name := storagePoolIdentity(disk)
if seen[id] {
return nil, fmt.Errorf("duplicate storage disk: %s", disk.MountPoint)
}
seen[id] = true
contentTypes := normalizeStorageContentTypes(item.ContentTypes)
defaultContents := normalizeStorageContentTypes(item.DefaultContents)
allowed := map[string]bool{}
for _, content := range contentTypes {
allowed[content] = true
}
defaults := make([]string, 0, len(defaultContents))
for _, content := range defaultContents {
if !allowed[content] {
continue
}
if defaultSeen[content] {
return nil, fmt.Errorf("only one default storage disk is allowed for %s", content)
}
defaultSeen[content] = true
defaults = append(defaults, content)
}
result = append(result, config.StoragePool{
ID: id,
Name: name,
Path: managedPath,
MountPoint: disk.MountPoint,
ContentTypes: contentTypes,
DefaultContents: defaults,
Enabled: item.Enabled,
})
}
return result, nil
}
func storageDiskForPoolRequest(item config.StoragePool, disks []storageDiskInfo) (storageDiskInfo, string, error) {
requestedMount := filepath.Clean(strings.TrimSpace(item.MountPoint))
if requestedMount == "." {
requestedMount = ""
}
requestedPath := filepath.Clean(strings.TrimSpace(item.Path))
if requestedPath == "." {
requestedPath = ""
}
for _, disk := range disks {
mountPoint := filepath.Clean(disk.MountPoint)
managedPath := managedStoragePath(mountPoint)
mountMatches := requestedMount != "" && requestedMount == mountPoint
pathMatches := requestedPath != "" && requestedPath == managedPath
if !mountMatches && !pathMatches {
continue
}
if requestedMount != "" && !mountMatches {
return storageDiskInfo{}, "", fmt.Errorf("storage disk mount point has changed; refresh and try again")
}
if requestedPath != "" && !pathMatches {
return storageDiskInfo{}, "", fmt.Errorf("custom storage paths are not allowed; refresh and try again")
}
return disk, managedPath, nil
}
return storageDiskInfo{}, "", fmt.Errorf("storage disk is not mounted or is no longer available")
}
func storagePoolIdentity(disk storageDiskInfo) (string, string) {
mountPoint := filepath.Clean(disk.MountPoint)
if mountPoint == string(os.PathSeparator) {
return "disk-root", "system (/)"
}
baseName := filepath.Base(mountPoint)
if baseName == "" || baseName == "." || baseName == string(os.PathSeparator) {
baseName = strings.TrimSpace(disk.Name)
}
if baseName == "" {
baseName = "storage"
}
devicePath := strings.TrimSpace(disk.Path)
if devicePath == "" {
devicePath = strings.TrimSpace(disk.Name)
}
return "disk-" + storageID(baseName), fmt.Sprintf("%s (%s)", baseName, devicePath)
}
func managedStoragePath(mountPoint string) string {
if filepath.Clean(mountPoint) == string(os.PathSeparator) {
return filepath.Join(string(os.PathSeparator), "var", "lib", "clicd")
}
return filepath.Join(filepath.Clean(mountPoint), "clicd")
}
func normalizeStorageContentTypes(values []string) []string {
seen := map[string]bool{}
result := []string{}
for _, value := range values {
var next string
switch strings.ToLower(strings.TrimSpace(value)) {
case config.StorageContentLXC:
next = config.StorageContentLXC
case config.StorageContentKVM:
next = config.StorageContentKVM
case config.StorageContentImages:
next = config.StorageContentImages
case config.StorageContentSnapshots:
next = config.StorageContentSnapshots
case config.StorageContentBackups:
next = config.StorageContentBackups
default:
continue
}
if seen[next] {
continue
}
seen[next] = true
result = append(result, next)
}
return result
}
func storageID(name string) string {
id := strings.ToLower(strings.TrimSpace(name))
id = strings.NewReplacer(" ", "-", "_", "-", ".", "-", "/", "-").Replace(id)
id = strings.Trim(id, "-")
if id == "" {
return "storage"
}
return id
}
func detectStorageDisks() []storageDiskInfo {
type lsblkDevice struct {
Name string `json:"name"`
Path string `json:"path"`
Type string `json:"type"`
FSType string `json:"fstype"`
MountPoint string `json:"mountpoint"`
Model string `json:"model"`
Size int64 `json:"size"`
ReadOnly bool `json:"ro"`
Children []lsblkDevice `json:"children"`
}
var payload struct {
BlockDevices []lsblkDevice `json:"blockdevices"`
}
out, err := exec.Command("lsblk", "-J", "-b", "-o", "NAME,PATH,SIZE,TYPE,FSTYPE,MOUNTPOINT,MODEL,RO").Output()
if err != nil {
return nil
}
if err := json.Unmarshal(out, &payload); err != nil {
return nil
}
result := []storageDiskInfo{}
var walk func(lsblkDevice)
walk = func(dev lsblkDevice) {
info := storageDiskInfo{
Name: dev.Name,
Path: dev.Path,
Type: dev.Type,
FSType: dev.FSType,
MountPoint: dev.MountPoint,
Model: strings.TrimSpace(dev.Model),
SizeBytes: dev.Size,
}
if isUsableStorageMount(dev.Type, dev.FSType, dev.Path, dev.MountPoint, dev.ReadOnly) && !mountIsReadOnly(dev.MountPoint) {
info.SizeBytes, info.UsedBytes, info.FreeBytes = dfPath(dev.MountPoint)
result = append(result, info)
}
for _, child := range dev.Children {
walk(child)
}
}
for _, dev := range payload.BlockDevices {
walk(dev)
}
return result
}
func isUsableStorageMount(deviceType, fsType, devicePath, mountPoint string, readOnly bool) bool {
if readOnly || strings.TrimSpace(mountPoint) == "" || !strings.HasPrefix(mountPoint, "/") {
return false
}
deviceType = strings.ToLower(strings.TrimSpace(deviceType))
devicePath = strings.ToLower(strings.TrimSpace(devicePath))
if deviceType == "loop" || deviceType == "rom" || deviceType == "zram" || strings.HasPrefix(devicePath, "/dev/loop") {
return false
}
fsType = strings.ToLower(strings.TrimSpace(fsType))
unsupportedFileSystems := map[string]bool{
"": true,
"squashfs": true,
"iso9660": true,
"udf": true,
"swap": true,
"tmpfs": true,
"devtmpfs": true,
"overlay": true,
"proc": true,
"sysfs": true,
"cgroup": true,
"cgroup2": true,
"efivarfs": true,
"securityfs": true,
}
if unsupportedFileSystems[fsType] {
return false
}
mountPoint = pathpkg.Clean(mountPoint)
for _, reserved := range []string{"/snap", "/boot"} {
if mountPoint == reserved || strings.HasPrefix(mountPoint, reserved+"/") {
return false
}
}
return true
}
func mountIsReadOnly(mountPoint string) bool {
out, err := exec.Command("findmnt", "-n", "-o", "OPTIONS", "--target", mountPoint).Output()
if err != nil {
return false
}
for _, option := range strings.Split(strings.TrimSpace(string(out)), ",") {
if strings.TrimSpace(option) == "ro" {
return true
}
}
return false
}
func contentUsageForPool(poolPath string) ([]storageContentUsage, int64) {
mapping := map[string]string{
config.StorageContentLXC: "lxc",
config.StorageContentKVM: "kvm",
config.StorageContentImages: "images",
config.StorageContentSnapshots: "snapshots",
config.StorageContentBackups: "backups",
}
result := make([]storageContentUsage, 0, len(mapping))
var total int64
for _, content := range []string{
config.StorageContentLXC,
config.StorageContentKVM,
config.StorageContentImages,
config.StorageContentSnapshots,
config.StorageContentBackups,
} {
size := dirSizeBytes(filepath.Join(poolPath, mapping[content]))
result = append(result, storageContentUsage{ContentType: content, SizeBytes: size})
total += size
}
return result, total
}
func mergeContentUsage(current []storageContentUsage, next []storageContentUsage) []storageContentUsage {
sizes := map[string]int64{}
order := []string{}
for _, item := range append(current, next...) {
if _, ok := sizes[item.ContentType]; !ok {
order = append(order, item.ContentType)
}
sizes[item.ContentType] += item.SizeBytes
}
result := make([]storageContentUsage, 0, len(order))
for _, content := range order {
result = append(result, storageContentUsage{ContentType: content, SizeBytes: sizes[content]})
}
return result
}
func dirSizeBytes(path string) int64 {
if resolved, err := filepath.EvalSymlinks(path); err == nil {
path = resolved
}
// Count allocated blocks on this filesystem only. LXC rootfs directories can
// contain active mounts such as proc/sys; traversing them is slow and reports
// enormous virtual sizes that are not actually occupied by CLICD data.
out, err := exec.Command("du", "-skx", path).Output()
if err == nil {
fields := strings.Fields(string(out))
if len(fields) > 0 {
var sizeKB int64
if _, scanErr := fmt.Sscanf(fields[0], "%d", &sizeKB); scanErr == nil && sizeKB <= (1<<63-1)/1024 {
return sizeKB * 1024
}
}
}
var size int64
_ = filepath.WalkDir(path, func(_ string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() {
return nil
}
if info, statErr := d.Info(); statErr == nil {
size += info.Size()
}
return nil
})
return size
}
func dfPath(path string) (size int64, used int64, free int64) {
out, err := exec.Command("df", "-B1", "-P", path).Output()
if err != nil {
return 0, 0, 0
}
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
if len(lines) < 2 {
return 0, 0, 0
}
fields := strings.Fields(lines[len(lines)-1])
if len(fields) < 6 {
return 0, 0, 0
}
fmt.Sscanf(fields[1], "%d", &size)
fmt.Sscanf(fields[2], "%d", &used)
fmt.Sscanf(fields[3], "%d", &free)
return size, used, free
}
func bestMountPointForPath(path string, disks []storageDiskInfo) string {
path = strings.ReplaceAll(path, "\\", "/")
path = pathpkg.Clean(path)
best := ""
for _, disk := range disks {
mp := pathpkg.Clean(strings.ReplaceAll(disk.MountPoint, "\\", "/"))
if disk.MountPoint == "" || mp == "." {
continue
}
matches := path == mp
if mp == "/" {
matches = pathpkg.IsAbs(path)
} else if strings.HasPrefix(path, mp+"/") {
matches = true
}
if matches {
if len(mp) > len(best) {
best = mp
}
}
}
return best
}
+121
View File
@@ -0,0 +1,121 @@
package api
import (
"os"
"path/filepath"
"runtime"
"testing"
"clicd/internal/config"
)
func TestIsUsableStorageMount(t *testing.T) {
tests := []struct {
name string
deviceType string
fsType string
devicePath string
mountPoint string
readOnly bool
wantUsable bool
}{
{name: "root partition", deviceType: "part", fsType: "ext4", devicePath: "/dev/sda2", mountPoint: "/", wantUsable: true},
{name: "mounted data disk", deviceType: "disk", fsType: "xfs", devicePath: "/dev/sdb", mountPoint: "/data", wantUsable: true},
{name: "snap loop", deviceType: "loop", fsType: "squashfs", devicePath: "/dev/loop0", mountPoint: "/snap/core20/2105", readOnly: true},
{name: "loop without ro flag", deviceType: "loop", fsType: "ext4", devicePath: "/dev/loop7", mountPoint: "/mnt/loop"},
{name: "read only disk", deviceType: "part", fsType: "ext4", devicePath: "/dev/sdc1", mountPoint: "/archive", readOnly: true},
{name: "optical image", deviceType: "rom", fsType: "iso9660", devicePath: "/dev/sr0", mountPoint: "/media/cdrom"},
{name: "efi partition", deviceType: "part", fsType: "vfat", devicePath: "/dev/sda1", mountPoint: "/boot/efi"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := isUsableStorageMount(tt.deviceType, tt.fsType, tt.devicePath, tt.mountPoint, tt.readOnly)
if got != tt.wantUsable {
t.Fatalf("isUsableStorageMount() = %v, want %v", got, tt.wantUsable)
}
})
}
}
func TestBestMountPointForPath(t *testing.T) {
disks := []storageDiskInfo{
{Path: "/dev/sda2", MountPoint: "/"},
{Path: "/dev/sdb1", MountPoint: "/mnt/clicd-data"},
}
tests := []struct {
path string
want string
}{
{path: "/var/lib/clicd", want: "/"},
{path: "/mnt/clicd-data/clicd", want: "/mnt/clicd-data"},
{path: "/mnt/clicd-data", want: "/mnt/clicd-data"},
}
for _, tt := range tests {
if got := bestMountPointForPath(tt.path, disks); got != tt.want {
t.Fatalf("bestMountPointForPath(%q) = %q, want %q", tt.path, got, tt.want)
}
}
}
func TestNormalizeStoragePoolsUsesServerManagedPath(t *testing.T) {
disks := []storageDiskInfo{
{Path: "/dev/sda2", MountPoint: "/"},
{Path: "/dev/sdb1", MountPoint: "/mnt/data"},
}
items := []config.StoragePool{{
ID: "disk-data",
Name: "data",
Path: "/mnt/data/clicd",
MountPoint: "/mnt/data",
ContentTypes: []string{config.StorageContentLXC},
DefaultContents: []string{config.StorageContentLXC},
Enabled: true,
}}
pools, err := normalizeStoragePoolsRequestWithDisks(items, disks)
if err != nil {
t.Fatal(err)
}
wantPath := filepath.Join(filepath.Clean("/mnt/data"), "clicd")
if len(pools) != 1 || pools[0].ID != "disk-data" || pools[0].Name != "data (/dev/sdb1)" || pools[0].Path != wantPath || pools[0].MountPoint != "/mnt/data" {
t.Fatalf("unexpected normalized pools: %#v", pools)
}
}
func TestNormalizeStoragePoolsRejectsUncontrolledPath(t *testing.T) {
disks := []storageDiskInfo{{Path: "/dev/sdb1", MountPoint: "/mnt/data"}}
for _, path := range []string{"/etc", "/mnt/data/clicd/../../etc", "/mnt/data/other"} {
_, err := normalizeStoragePoolsRequestWithDisks([]config.StoragePool{{
ID: "disk-data",
Name: "data",
Path: path,
MountPoint: "/mnt/data",
Enabled: true,
}}, disks)
if err == nil {
t.Fatalf("path %q was accepted", path)
}
}
}
func TestDirSizeBytesUsesAllocatedBlocks(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("allocated-block behavior is provided by the Linux du command")
}
dir := t.TempDir()
file, err := os.Create(filepath.Join(dir, "sparse.img"))
if err != nil {
t.Fatal(err)
}
if err := file.Truncate(1 << 30); err != nil {
file.Close()
t.Fatal(err)
}
if err := file.Close(); err != nil {
t.Fatal(err)
}
if got := dirSizeBytes(dir); got >= 128<<20 {
t.Fatalf("dirSizeBytes() = %d, expected allocated size instead of 1 GiB apparent size", got)
}
}
+360 -71
View File
@@ -22,24 +22,30 @@ func generateRandomStr(length int) string {
}
type subUserResponse struct {
ID string `json:"id"`
Username string `json:"username"`
Password string `json:"password,omitempty"`
ContainerNames []string `json:"container_names"`
ContainerUUIDs []string `json:"container_uuids,omitempty"`
AccessCode string `json:"access_code"`
CreatedAt string `json:"created_at"`
ID string `json:"id"`
Username string `json:"username"`
Password string `json:"password,omitempty"`
ContainerNames []string `json:"container_names"`
ContainerUUIDs []string `json:"container_uuids,omitempty"`
AllowedImageIDs []string `json:"allowed_image_ids,omitempty"`
ImageLimitConfigured bool `json:"image_limit_configured,omitempty"`
CurrentImageIDs []string `json:"current_image_ids,omitempty"`
AccessCode string `json:"access_code"`
CreatedAt string `json:"created_at"`
}
func newSubUserResponse(su config.SubUser, password string) subUserResponse {
return subUserResponse{
ID: su.ID,
Username: su.Username,
Password: password,
ContainerNames: su.ContainerNames,
ContainerUUIDs: su.ContainerUUIDs,
AccessCode: su.AccessCode,
CreatedAt: su.CreatedAt,
ID: su.ID,
Username: su.Username,
Password: password,
ContainerNames: su.ContainerNames,
ContainerUUIDs: su.ContainerUUIDs,
AllowedImageIDs: effectiveSubUserAllowedImageIDs(&su),
ImageLimitConfigured: su.ImageLimitConfigured,
CurrentImageIDs: subUserCurrentImageIDs(&su),
AccessCode: su.AccessCode,
CreatedAt: su.CreatedAt,
}
}
@@ -49,6 +55,9 @@ func HandleSubUserCreate(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "subuser:create") {
return
}
var req struct {
ContainerName string `json:"container_name"`
@@ -91,6 +100,10 @@ func HandleSubUserCreate(w http.ResponseWriter, r *http.Request) {
}
su.ContainerNames = appendUniqueString(su.ContainerNames, containerName)
su.ContainerUUIDs = appendUniqueString(su.ContainerUUIDs, c.UUID)
if !su.ImageLimitConfigured && len(su.AllowedImageIDs) == 0 {
su.AllowedImageIDs = effectiveContainerAllowedImageIDs(c)
su.ImageLimitConfigured = true
}
config.SaveConfig()
jsonResponse(w, http.StatusOK, APIResponse{
Success: true,
@@ -111,14 +124,16 @@ func HandleSubUserCreate(w http.ResponseWriter, r *http.Request) {
accessCode := generateRandomStr(8)
subUser := config.SubUser{
ID: "sub-" + generateRandomStr(8),
Username: username,
Password: password,
PassHash: string(hash),
ContainerNames: []string{containerName},
ContainerUUIDs: []string{c.UUID},
AccessCode: accessCode,
CreatedAt: time.Now().Format("2006-01-02 15:04:05"),
ID: "sub-" + generateRandomStr(8),
Username: username,
Password: password,
PassHash: string(hash),
ContainerNames: []string{containerName},
ContainerUUIDs: []string{c.UUID},
AllowedImageIDs: effectiveContainerAllowedImageIDs(c),
ImageLimitConfigured: true,
AccessCode: accessCode,
CreatedAt: time.Now().Format("2006-01-02 15:04:05"),
}
config.AppConfig.SubUsers = append(config.AppConfig.SubUsers, subUser)
@@ -281,13 +296,189 @@ func subUserAllowedContainers(r *http.Request) (subUserAccess, bool) {
return allowed, true
}
func requestAllowedContainers(r *http.Request) (subUserAccess, bool) {
if ctx, ok := authContextFromRequest(r); ok {
if ctx.Type == authTypeAPIKey && len(ctx.ContainerUUIDs) == 0 {
return subUserAccess{}, false
}
if ctx.Type == authTypeSubUser || ctx.Type == authTypeAPIKey {
allowed := subUserAccess{names: make(map[string]bool), uuids: make(map[string]bool)}
for _, uuid := range ctx.ContainerUUIDs {
allowed.uuids[uuid] = true
}
if ctx.Type == authTypeSubUser && len(ctx.ContainerUUIDs) == 0 {
legacy, ok := subUserAllowedContainers(r)
if ok {
return legacy, true
}
}
return allowed, true
}
}
return subUserAllowedContainers(r)
}
func subUserFromRequest(r *http.Request) *config.SubUser {
username := ""
if ctx, ok := authContextFromRequest(r); ok && ctx.Type == authTypeSubUser {
username = ctx.Username
}
if username == "" {
if claims, ok := claimsFromRequest(r); ok {
username, _ = claims["sub_user"].(string)
}
}
if username == "" {
return nil
}
for i := range config.AppConfig.SubUsers {
if config.AppConfig.SubUsers[i].Username == username {
return &config.AppConfig.SubUsers[i]
}
}
return nil
}
func normalizeAllowedImageIDs(ids []string) ([]string, error) {
seen := map[string]bool{}
result := make([]string, 0, len(ids))
for _, id := range ids {
id = strings.TrimSpace(id)
if id == "" || seen[id] {
continue
}
if !imageTemplateExists(id) {
return nil, fmt.Errorf("unknown image template: %s", id)
}
seen[id] = true
result = append(result, id)
}
return result, nil
}
func isTemplateAllowedForRequest(r *http.Request, c *config.Container, templateID string) bool {
if !isSubUserRequest(r) {
return true
}
return isImageAllowedForSubUser(subUserFromRequest(r), c, templateID)
}
func isImageAllowedForSubUser(su *config.SubUser, c *config.Container, templateID string) bool {
if su == nil || strings.TrimSpace(templateID) == "" {
return false
}
for _, id := range effectiveSubUserAllowedImageIDs(su) {
if id == templateID {
return true
}
}
return false
}
func effectiveContainerAllowedImageIDs(c *config.Container) []string {
if c == nil {
return nil
}
if c.ImageLimitConfigured || len(c.AllowedImageIDs) > 0 {
return cleanImageIDList(c.AllowedImageIDs)
}
if c.Template != "" {
return []string{c.Template}
}
return nil
}
func effectiveSubUserAllowedImageIDs(su *config.SubUser) []string {
if su == nil {
return nil
}
if su.ImageLimitConfigured || len(su.AllowedImageIDs) > 0 {
return cleanImageIDList(su.AllowedImageIDs)
}
result := []string{}
seen := map[string]bool{}
for _, c := range subUserAssignedContainers(su) {
for _, id := range effectiveContainerAllowedImageIDs(c) {
if id != "" && !seen[id] {
seen[id] = true
result = append(result, id)
}
}
}
return result
}
func cleanImageIDList(ids []string) []string {
result := make([]string, 0, len(ids))
seen := map[string]bool{}
for _, id := range ids {
id = strings.TrimSpace(id)
if id == "" || seen[id] {
continue
}
seen[id] = true
result = append(result, id)
}
return result
}
func subUserCurrentImageIDs(su *config.SubUser) []string {
seen := map[string]bool{}
result := []string{}
for _, c := range subUserAssignedContainers(su) {
if c.Template != "" && !seen[c.Template] {
seen[c.Template] = true
result = append(result, c.Template)
}
}
return result
}
func subUserAssignedContainers(su *config.SubUser) []*config.Container {
if su == nil {
return nil
}
result := []*config.Container{}
seen := map[string]bool{}
for _, uuid := range su.ContainerUUIDs {
if c := config.FindContainerByUUID(uuid); c != nil {
key := c.UUID
if key == "" {
key = c.Name
}
if !seen[key] {
seen[key] = true
result = append(result, c)
}
}
}
for _, name := range su.ContainerNames {
if c := config.FindContainerByName(name); c != nil {
key := c.UUID
if key == "" {
key = c.Name
}
if !seen[key] {
seen[key] = true
result = append(result, c)
}
}
}
return result
}
func isAccessRestrictedRequest(r *http.Request) bool {
_, restricted := requestAllowedContainers(r)
return restricted
}
func containerByIdentifier(identifier string) *config.Container {
return config.FindContainerByIdentifier(identifier)
}
func isContainerAllowedForRequest(r *http.Request, identifier string) bool {
allowed, isSubUser := subUserAllowedContainers(r)
if !isSubUser {
allowed, restricted := requestAllowedContainers(r)
if !restricted {
return true
}
c := containerByIdentifier(identifier)
@@ -303,6 +494,9 @@ func HandleAuditLogs(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "audit:read") {
return
}
logs := config.AppConfig.AuditLogs
if logs == nil {
@@ -327,12 +521,29 @@ func SubUserMiddleware(next http.HandlerFunc) http.HandlerFunc {
}
path := r.URL.Path
if path == "/api/tasks" && r.Method == http.MethodGet {
containerPrefix := "/api/containers/"
containerListPath := "/api/containers"
tasksPath := "/api/tasks"
if strings.HasPrefix(path, "/api/v1/") {
containerPrefix = "/api/v1/containers/"
containerListPath = "/api/v1/containers"
tasksPath = "/api/v1/tasks"
}
if path == tasksPath && r.Method == http.MethodGet {
next(w, r)
return
}
if path == "/api/containers" {
imagesEnabledPath := "/api/images/enabled"
if strings.HasPrefix(path, "/api/v1/") {
imagesEnabledPath = "/api/v1/images/enabled"
}
if path == imagesEnabledPath && r.Method == http.MethodGet {
next(w, r)
return
}
if path == containerListPath {
if r.Method != http.MethodGet {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Sub-users cannot create containers"})
return
@@ -341,8 +552,8 @@ func SubUserMiddleware(next http.HandlerFunc) http.HandlerFunc {
return
}
if len(path) > len("/api/containers/") {
rest := path[len("/api/containers/"):]
if strings.HasPrefix(path, containerPrefix) {
rest := path[len(containerPrefix):]
parts := splitPath(rest)
if len(parts) > 0 && parts[0] != "" {
c := containerByIdentifier(parts[0])
@@ -352,7 +563,11 @@ func SubUserMiddleware(next http.HandlerFunc) http.HandlerFunc {
}
action := ""
if len(parts) > 1 {
action = parts[1]
action = strings.Join(parts[1:], "/")
}
if c.PolicyBlocked && isSubUserBlockedAction(action, r.Method) {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: policyBlockedMessage(c)})
return
}
if !isSubUserContainerActionAllowed(action, r.Method) {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Action is not allowed for this link"})
@@ -369,8 +584,8 @@ func SubUserMiddleware(next http.HandlerFunc) http.HandlerFunc {
}
func filterContainersForRequest(r *http.Request, containers []config.Container) []config.Container {
allowed, isSubUser := subUserAllowedContainers(r)
if !isSubUser {
allowed, restricted := requestAllowedContainers(r)
if !restricted {
return containers
}
filtered := make([]config.Container, 0, len(containers))
@@ -383,33 +598,66 @@ func filterContainersForRequest(r *http.Request, containers []config.Container)
}
func filterTasksForRequest(r *http.Request, tasks []*Task) []*Task {
allowed, isSubUser := subUserAllowedContainers(r)
if !isSubUser {
return tasks
}
filtered := make([]*Task, 0, len(tasks))
for _, task := range tasks {
if c := config.FindContainer(task.ContainerID); c != nil && isContainerAllowed(allowed, c) {
if isTaskAllowedForRequest(r, task) {
filtered = append(filtered, task)
continue
}
if task.ContainerName != "" {
if c := config.FindContainerByName(task.ContainerName); c != nil && isContainerAllowed(allowed, c) {
filtered = append(filtered, task)
continue
}
}
if task.Config.Name != "" {
if c := config.FindContainerByName(task.Config.Name); c != nil && isContainerAllowed(allowed, c) {
filtered = append(filtered, task)
}
}
}
return filtered
}
func isTaskAllowedForRequest(r *http.Request, task *Task) bool {
allowed, restricted := requestAllowedContainers(r)
if !restricted {
return true
}
if task == nil {
return false
}
if c := config.FindContainer(task.ContainerID); c != nil && isContainerAllowed(allowed, c) {
return true
}
if task.ContainerName != "" {
if c := config.FindContainerByName(task.ContainerName); c != nil && isContainerAllowed(allowed, c) {
return true
}
}
if task.Config.Name != "" {
if c := config.FindContainerByName(task.Config.Name); c != nil && isContainerAllowed(allowed, c) {
return true
}
}
return false
}
func isContainerAllowed(allowed subUserAccess, c *config.Container) bool {
return c != nil && c.UUID != "" && allowed.uuids[c.UUID]
if c == nil {
return false
}
if c.UUID != "" && allowed.uuids[c.UUID] {
return true
}
return c.Name != "" && allowed.names[c.Name]
}
func isSubUserBlockedAction(action string, method string) bool {
if action == "" {
return method != http.MethodGet
}
switch action {
case "usage", "traffic", "history":
return method != http.MethodGet
default:
return true
}
}
func policyBlockedMessage(c *config.Container) string {
if c != nil && c.PolicyBlockedReason != "" {
return "虚拟机被策略临时封禁:" + c.PolicyBlockedReason
}
return "虚拟机被策略临时封禁"
}
func isSubUserContainerActionAllowed(action string, method string) bool {
@@ -417,7 +665,7 @@ func isSubUserContainerActionAllowed(action string, method string) bool {
return method == http.MethodGet
}
switch {
case action == "usage" || action == "traffic" || action == "random-port":
case action == "usage" || action == "traffic" || action == "history" || action == "random-port":
return method == http.MethodGet
case action == "snapshots":
return method == http.MethodGet || method == http.MethodPost
@@ -425,7 +673,7 @@ func isSubUserContainerActionAllowed(action string, method string) bool {
return method == http.MethodPost
case strings.HasPrefix(action, "snapshots/"):
return method == http.MethodDelete || method == http.MethodPost
case action == "start" || action == "stop" || action == "restart" || action == "reinstall":
case action == "start" || action == "stop" || action == "restart" || action == "reinstall" || action == "reset-password":
return method == http.MethodPost
case strings.HasPrefix(action, "port-mappings/"):
return method == http.MethodPut
@@ -493,18 +741,21 @@ func splitBy(s, sep string) []string {
// SubUserListItem is the enriched sub-user info returned by the list API
type SubUserListItem struct {
ID string `json:"id"`
Username string `json:"username"`
ContainerNames []string `json:"container_names"`
ContainerUUIDs []string `json:"container_uuids"`
ContainerName string `json:"container_name"`
ContainerUUID string `json:"container_uuid"`
AccessCode string `json:"access_code"`
Password string `json:"password,omitempty"`
CreatedAt string `json:"created_at"`
LastLogin string `json:"last_login"`
LastLoginIP string `json:"last_login_ip"`
LastLoginUA string `json:"last_login_ua"`
ID string `json:"id"`
Username string `json:"username"`
ContainerNames []string `json:"container_names"`
ContainerUUIDs []string `json:"container_uuids"`
AllowedImageIDs []string `json:"allowed_image_ids"`
ImageLimitConfigured bool `json:"image_limit_configured"`
CurrentImageIDs []string `json:"current_image_ids"`
ContainerName string `json:"container_name"`
ContainerUUID string `json:"container_uuid"`
AccessCode string `json:"access_code"`
Password string `json:"password,omitempty"`
CreatedAt string `json:"created_at"`
LastLogin string `json:"last_login"`
LastLoginIP string `json:"last_login_ip"`
LastLoginUA string `json:"last_login_ua"`
}
// HandleSubUserList returns the list of all sub-users with container info
@@ -513,17 +764,23 @@ func HandleSubUserList(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "subuser:read") {
return
}
result := make([]SubUserListItem, 0, len(config.AppConfig.SubUsers))
for _, su := range config.AppConfig.SubUsers {
item := SubUserListItem{
ID: su.ID,
Username: su.Username,
ContainerNames: su.ContainerNames,
ContainerUUIDs: su.ContainerUUIDs,
AccessCode: su.AccessCode,
Password: su.Password,
CreatedAt: su.CreatedAt,
ID: su.ID,
Username: su.Username,
ContainerNames: su.ContainerNames,
ContainerUUIDs: su.ContainerUUIDs,
AllowedImageIDs: effectiveSubUserAllowedImageIDs(&su),
ImageLimitConfigured: su.ImageLimitConfigured,
CurrentImageIDs: subUserCurrentImageIDs(&su),
AccessCode: su.AccessCode,
Password: su.Password,
CreatedAt: su.CreatedAt,
}
// Resolve container name from first active UUID
@@ -562,7 +819,8 @@ func HandleSubUserList(w http.ResponseWriter, r *http.Request) {
// HandleSubUserAction handles actions on a specific sub-user
func HandleSubUserAction(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/api/sub-users/")
path := strings.TrimPrefix(r.URL.Path, "/api/v1/sub-users/")
path = strings.TrimPrefix(path, "/api/sub-users/")
parts := strings.SplitN(path, "/", 2)
subUserID := parts[0]
action := ""
@@ -585,6 +843,9 @@ func HandleSubUserAction(w http.ResponseWriter, r *http.Request) {
switch {
case action == "rotate-password" && r.Method == http.MethodPost:
if !requireScope(w, r, "subuser:update") {
return
}
password := generateRandomStr(16)
if hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost); err == nil {
target.PassHash = string(hash)
@@ -602,15 +863,43 @@ func HandleSubUserAction(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to generate password"})
case action == "audit-logs" && r.Method == http.MethodGet:
if !requireScope(w, r, "audit:read") {
return
}
// Filter audit logs for this sub-user
logs := filterSubUserAuditLogs(target.Username)
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: logs})
case action == "login-logs" && r.Method == http.MethodGet:
if !requireScope(w, r, "loginlog:read") {
return
}
// Filter login logs for this sub-user
logs := filterSubUserLoginLogs(target.Username)
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: logs})
case action == "images" && r.Method == http.MethodPut:
if !requireScope(w, r, "subuser:update") {
return
}
var req struct {
AllowedImageIDs []string `json:"allowed_image_ids"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
ids, err := normalizeAllowedImageIDs(req.AllowedImageIDs)
if err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
target.AllowedImageIDs = ids
target.ImageLimitConfigured = true
target.TokenVersion++
config.SaveConfig()
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: newSubUserResponse(*target, target.Password)})
default:
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Action not found"})
}
+50 -27
View File
@@ -11,19 +11,27 @@ import (
)
type SwapInfo struct {
TotalMB int64 `json:"total_mb"`
UsedMB int64 `json:"used_mb"`
FreeMB int64 `json:"free_mb"`
Enabled bool `json:"enabled"`
SwapFile string `json:"swap_file"`
TotalMB int64 `json:"total_mb"`
UsedMB int64 `json:"used_mb"`
FreeMB int64 `json:"free_mb"`
Enabled bool `json:"enabled"`
SwapFile string `json:"swap_file"`
}
const (
minSwapSizeMB = 128
maxSwapSizeMB = 262144
)
// HandleSwapInfo returns current swap status
func HandleSwapInfo(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "swap:read") {
return
}
info := getSwapInfo()
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: info})
@@ -35,9 +43,12 @@ func HandleSwapManage(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "swap:manage") {
return
}
var req struct {
Action string `json:"action"` // create, enable, disable, resize
Action string `json:"action"` // create, enable, disable, resize
SizeMB int `json:"size_mb"` // for create/resize
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -46,54 +57,63 @@ func HandleSwapManage(w http.ResponseWriter, r *http.Request) {
}
var msg string
var err error
switch req.Action {
case "create":
if req.SizeMB <= 0 {
req.SizeMB = 2048
}
err := createSwap(req.SizeMB)
if err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: err.Error()})
return
if err = validateSwapSize(req.SizeMB); err == nil {
err = createSwap(req.SizeMB)
}
msg = fmt.Sprintf("已创建 %d MB SWAP", req.SizeMB)
case "enable":
err := enableSwap()
if err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: err.Error()})
return
}
err = enableSwap()
msg = "SWAP 已启用"
case "disable":
err := disableSwap()
if err != nil {
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: err.Error()})
return
}
err = disableSwap()
msg = "SWAP 已禁用"
case "resize":
if req.SizeMB <= 0 {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid size"})
return
if err = validateSwapSize(req.SizeMB); err == nil {
err = disableSwap()
}
if err == nil {
err = createSwap(req.SizeMB)
}
if err == nil {
err = enableSwap()
}
disableSwap()
createSwap(req.SizeMB)
enableSwap()
msg = fmt.Sprintf("SWAP 已调整为 %d MB", req.SizeMB)
default:
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid action: " + req.Action})
return
}
if err != nil {
auditRequest(r, "swap."+req.Action, "/swapfile", fmt.Sprintf("size_mb=%d", req.SizeMB), false, err.Error())
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: err.Error()})
return
}
info := getSwapInfo()
auditRequest(r, "swap."+req.Action, "/swapfile", fmt.Sprintf("size_mb=%d", req.SizeMB), true, "")
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: msg, Data: info})
}
func validateSwapSize(sizeMB int) error {
if sizeMB < minSwapSizeMB {
return fmt.Errorf("swap size must be at least %d MB", minSwapSizeMB)
}
if sizeMB > maxSwapSizeMB {
return fmt.Errorf("swap size cannot exceed %d MB", maxSwapSizeMB)
}
return nil
}
func getSwapInfo() SwapInfo {
info := SwapInfo{SwapFile: "/swapfile"}
@@ -160,6 +180,9 @@ func createSwap(sizeMB int) error {
func enableSwap() error {
swapFile := "/swapfile"
if _, err := os.Stat(swapFile); os.IsNotExist(err) {
if getSwapInfo().Enabled {
return nil
}
return fmt.Errorf("swap 文件不存在,请先创建")
}
@@ -180,7 +203,7 @@ func disableSwap() error {
cmd := exec.Command("swapoff", swapFile)
output, err := cmd.CombinedOutput()
if err != nil {
if strings.Contains(string(output), "No such") {
if strings.Contains(string(output), "No such") || strings.Contains(string(output), "Invalid argument") {
return nil
}
return fmt.Errorf("禁用 swap 失败: %v, %s", err, string(output))
File diff suppressed because it is too large Load Diff
+56
View File
@@ -0,0 +1,56 @@
package api
import (
"testing"
"clicd/internal/config"
"clicd/internal/lxc"
)
func TestRunnableTaskIndexSkipsActiveContainer(t *testing.T) {
queue := []*Task{
{ID: "task-1", Type: TaskStop, ContainerID: 1, ContainerName: "alpha"},
{ID: "task-2", Type: TaskStart, ContainerID: 1, ContainerName: "alpha"},
{ID: "task-3", Type: TaskStart, ContainerID: 2, ContainerName: "beta"},
}
active := map[string]bool{taskConcurrencyKey(queue[0]): true}
if got := runnableTaskIndex(queue[1:], active); got != 1 {
t.Fatalf("runnableTaskIndex() = %d, want 1 for the other container", got)
}
}
func TestTaskConcurrencyKeyUsesContainerName(t *testing.T) {
create := &Task{ID: "task-1", Type: TaskCreate, Config: lxcConfigWithName("Example")}
operation := &Task{ID: "task-2", Type: TaskDelete, ContainerID: 9, ContainerName: "example"}
if taskConcurrencyKey(create) != taskConcurrencyKey(operation) {
t.Fatalf("same container received different concurrency keys: %q and %q", taskConcurrencyKey(create), taskConcurrencyKey(operation))
}
}
func TestTaskQueueSetConcurrencyNormalizesAndReports(t *testing.T) {
q := newTaskQueue(config.DefaultTaskConcurrency)
q.SetConcurrency(config.MaxTaskConcurrency + 10)
if got := q.Settings().Concurrency; got != config.MaxTaskConcurrency {
t.Fatalf("concurrency = %d, want %d", got, config.MaxTaskConcurrency)
}
q.SetConcurrency(0)
if got := q.Settings().Concurrency; got != config.DefaultTaskConcurrency {
t.Fatalf("concurrency = %d, want default %d", got, config.DefaultTaskConcurrency)
}
}
func TestTaskQueueUpdateTaskStage(t *testing.T) {
q := newTaskQueue(config.DefaultTaskConcurrency)
task := &Task{ID: "task-1", Type: TaskCreate, Status: "running"}
q.updateTaskStage(task, "rootfs", "下载模板并创建基础文件系统")
if task.Stage != "rootfs" || task.StageDetail != "下载模板并创建基础文件系统" {
t.Fatalf("unexpected task stage: %q %q", task.Stage, task.StageDetail)
}
}
func lxcConfigWithName(name string) lxc.ContainerConfig {
return lxc.ContainerConfig{Name: name}
}
+275
View File
@@ -0,0 +1,275 @@
package api
import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"sync"
"time"
"clicd/internal/config"
"github.com/gorilla/websocket"
)
type webVNCTicket struct {
ContainerName string
ContainerUUID string
Username string
SubUser bool
ClientIP string
UserAgent string
ExpiresAt time.Time
}
var webVNCTickets = struct {
sync.Mutex
items map[string]webVNCTicket
}{items: map[string]webVNCTicket{}}
func HandleVNCTicket(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
return
}
if !requireScope(w, r, "terminal:vnc") {
return
}
var req struct {
ContainerName string `json:"container_name"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.ContainerName == "" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Container name required"})
return
}
if !isContainerAllowedForRequest(r, req.ContainerName) {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Access denied to this container"})
return
}
c := config.FindContainerByName(req.ContainerName)
if c == nil {
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"})
return
}
if isSubUserRequest(r) && c.PolicyBlocked {
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: policyBlockedMessage(c)})
return
}
if !c.IsKVM() {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "VNC console is only available for KVM VMs"})
return
}
username, isSubUser := vncRequesterIdentity(r)
ticket := randomHex(32)
webVNCTickets.Lock()
cleanupExpiredWebVNCTicketsLocked(time.Now())
webVNCTickets.items[ticket] = webVNCTicket{
ContainerName: c.Name,
ContainerUUID: c.UUID,
Username: username,
SubUser: isSubUser,
ClientIP: clientIP(r),
UserAgent: r.UserAgent(),
ExpiresAt: time.Now().Add(60 * time.Second),
}
webVNCTickets.Unlock()
jsonResponse(w, http.StatusOK, APIResponse{
Success: true,
Data: map[string]string{"ticket": ticket},
})
}
// HandleVNCProxy proxies a KVM VM's local libvirt VNC socket to the browser.
func HandleVNCProxy(w http.ResponseWriter, r *http.Request) {
ticket := webVNCTicketFromRequest(r)
if ticket == "" {
http.Error(w, "ticket required", http.StatusUnauthorized)
return
}
containerName := r.URL.Query().Get("container")
if containerName == "" {
http.Error(w, "container name required", http.StatusBadRequest)
return
}
item, ok := consumeWebVNCTicket(ticket, containerName, r)
if !ok {
http.Error(w, "invalid or expired ticket", http.StatusUnauthorized)
return
}
c := config.FindContainerByName(containerName)
if c == nil || c.UUID != item.ContainerUUID {
http.Error(w, "container not found", http.StatusNotFound)
return
}
if item.SubUser && c.PolicyBlocked {
http.Error(w, "虚拟机被策略临时封禁", http.StatusForbidden)
return
}
if !c.IsKVM() {
http.Error(w, "VNC console is only available for KVM VMs", http.StatusBadRequest)
return
}
if c.Status != "running" {
http.Error(w, "container is not running", http.StatusBadRequest)
return
}
vncPort, err := kvmManager.RefreshVNCPort(c.ID)
if err != nil {
http.Error(w, fmt.Sprintf("VNC display is not available: %v", err), http.StatusBadRequest)
return
}
vncConn, err := net.DialTimeout("tcp", net.JoinHostPort("127.0.0.1", fmt.Sprintf("%d", vncPort)), 5*time.Second)
if err != nil {
http.Error(w, fmt.Sprintf("VNC connection failed: %v", err), http.StatusBadRequest)
return
}
defer vncConn.Close()
responseHeader := http.Header{}
if protocol := webVNCResponseProtocol(r); protocol != "" {
responseHeader.Set("Sec-WebSocket-Protocol", protocol)
}
ws, err := upgrader.Upgrade(w, r, responseHeader)
if err != nil {
log.Printf("WebVNC upgrade failed: %v", err)
return
}
defer ws.Close()
log.Printf("WebVNC connected for container %s as %s (sub_user=%t) -> 127.0.0.1:%d", containerName, item.Username, item.SubUser, vncPort)
done := make(chan string, 2)
var writeMu sync.Mutex
go streamVNCToWebSocket(ws, &writeMu, vncConn, done)
go streamWebSocketToVNC(ws, vncConn, done)
reason := <-done
_ = vncConn.Close()
_ = ws.Close()
log.Printf("WebVNC disconnected for container %s as %s: %s", containerName, item.Username, reason)
}
func vncRequesterIdentity(r *http.Request) (string, bool) {
if ctx, ok := authContextFromRequest(r); ok {
switch ctx.Type {
case authTypeSubUser:
return ctx.Username, true
case authTypeAPIKey:
return ctx.Actor, false
case authTypeAdmin:
return ctx.Username, false
}
}
claims, ok := claimsFromRequest(r)
if !ok {
return "api-key", false
}
if subUser, ok := claims["sub_user"].(string); ok && subUser != "" {
return subUser, true
}
if username, ok := claims["username"].(string); ok && username != "" {
return username, false
}
return "unknown", false
}
func webVNCTicketFromRequest(r *http.Request) string {
for _, protocol := range websocket.Subprotocols(r) {
const prefix = "clicd-vnc-ticket."
if len(protocol) > len(prefix) && protocol[:len(prefix)] == prefix {
return protocol[len(prefix):]
}
}
return r.URL.Query().Get("ticket")
}
func webVNCResponseProtocol(r *http.Request) string {
for _, protocol := range websocket.Subprotocols(r) {
if protocol == "binary" {
return protocol
}
}
for _, protocol := range websocket.Subprotocols(r) {
const prefix = "clicd-vnc-ticket."
if len(protocol) > len(prefix) && protocol[:len(prefix)] == prefix {
return protocol
}
}
return ""
}
func consumeWebVNCTicket(ticket, containerName string, r *http.Request) (webVNCTicket, bool) {
now := time.Now()
webVNCTickets.Lock()
defer webVNCTickets.Unlock()
cleanupExpiredWebVNCTicketsLocked(now)
item, ok := webVNCTickets.items[ticket]
if !ok {
return webVNCTicket{}, false
}
delete(webVNCTickets.items, ticket)
return item, item.ContainerName == containerName &&
item.ClientIP == clientIP(r) &&
item.UserAgent == r.UserAgent() &&
now.Before(item.ExpiresAt)
}
func cleanupExpiredWebVNCTicketsLocked(now time.Time) {
for ticket, item := range webVNCTickets.items {
if !now.Before(item.ExpiresAt) {
delete(webVNCTickets.items, ticket)
}
}
}
func streamVNCToWebSocket(ws *websocket.Conn, writeMu *sync.Mutex, src io.Reader, done chan<- string) {
buf := make([]byte, 32*1024)
for {
n, err := src.Read(buf)
if n > 0 {
writeMu.Lock()
writeErr := ws.WriteMessage(websocket.BinaryMessage, buf[:n])
writeMu.Unlock()
if writeErr != nil {
done <- fmt.Sprintf("browser websocket write failed: %v", writeErr)
return
}
}
if err != nil {
if err == io.EOF {
done <- "VNC server closed connection"
} else {
done <- fmt.Sprintf("VNC server read failed: %v", err)
}
return
}
}
}
func streamWebSocketToVNC(ws *websocket.Conn, dst net.Conn, done chan<- string) {
for {
messageType, msg, err := ws.ReadMessage()
if err != nil {
done <- fmt.Sprintf("browser websocket read failed: %v", err)
return
}
if messageType != websocket.BinaryMessage && messageType != websocket.TextMessage {
continue
}
if _, err := dst.Write(msg); err != nil {
done <- fmt.Sprintf("VNC server write failed: %v", err)
return
}
}
}
+3 -17
View File
@@ -1,10 +1,9 @@
package api
import (
"net"
"net/http"
"net/url"
"strings"
"clicd/internal/config"
"github.com/gorilla/websocket"
)
@@ -17,19 +16,6 @@ var upgrader = websocket.Upgrader{
if origin == "" {
return true
}
originURL, err := url.Parse(origin)
if err != nil {
return false
}
originHost := strings.ToLower(stripPort(originURL.Host))
requestHost := strings.ToLower(stripPort(r.Host))
return originHost != "" && originHost == requestHost
return config.IsOriginAllowed(origin, r.Host)
},
}
func stripPort(host string) string {
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
return parsedHost
}
return strings.Trim(host, "[]")
}
+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, ", "))
}
File diff suppressed because it is too large Load Diff
+74
View File
@@ -0,0 +1,74 @@
package cli
import (
"strings"
"testing"
)
func TestSafeReleaseBackupComponent(t *testing.T) {
tests := map[string]string{
"v1.2.3": "1.2.3",
" release/candidate ": "release_candidate",
"../../etc/passwd": "etc_passwd",
"": "unknown",
}
for input, want := range tests {
if got := safeReleaseBackupComponent(input); got != want {
t.Fatalf("safeReleaseBackupComponent(%q) = %q, want %q", input, got, want)
}
}
}
func TestReleaseArchiveAssetName(t *testing.T) {
tests := map[string]string{
"amd64": "clicd-linux-amd64.tar.gz",
"arm64": "clicd-linux-arm64.tar.gz",
}
for goarch, want := range tests {
got, err := releaseArchiveAssetName(goarch)
if err != nil {
t.Fatalf("releaseArchiveAssetName(%q) error = %v", goarch, err)
}
if got != want {
t.Fatalf("releaseArchiveAssetName(%q) = %q, want %q", goarch, got, want)
}
}
if _, err := releaseArchiveAssetName("386"); err == nil {
t.Fatal("releaseArchiveAssetName(386) error = nil, want unsupported architecture")
}
}
func TestCopyFileToBackupRejectsUnsafeFileName(t *testing.T) {
unsafeNames := []string{
"../clicd",
"..\\clicd",
"subdir/clicd",
"",
}
for _, name := range unsafeNames {
if _, err := copyFileToBackup("missing-source", name, 0755); err == nil || !strings.Contains(err.Error(), "unsafe backup file name") {
t.Fatalf("copyFileToBackup(%q) error = %v, want unsafe backup file name", name, err)
}
}
}
func TestFormatSSHAccessDoesNotExposePassword(t *testing.T) {
out := formatSSHAccess(2222)
if strings.Contains(out, "/") {
t.Fatalf("formatSSHAccess output contains credential separator: %q", out)
}
if strings.Contains(strings.ToLower(out), "password123") {
t.Fatalf("formatSSHAccess output exposed password: %q", out)
}
if !strings.Contains(out, "2222 -> 22") {
t.Fatalf("formatSSHAccess output = %q, want SSH port mapping", out)
}
}
func TestFormatSSHAccessHandlesMissingPort(t *testing.T) {
out := formatSSHAccess(0)
if !strings.Contains(out, "端口未分配") {
t.Fatalf("formatSSHAccess output = %q, want missing port message", out)
}
}
File diff suppressed because it is too large Load Diff
+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)
}
}
+88
View File
@@ -0,0 +1,88 @@
package config
import "testing"
func TestAllocateSSHPortUsesConfiguredNATRange(t *testing.T) {
AppConfig = &ClicdConfig{
NATPortStart: 30000,
NATPortEnd: 30002,
NextSSHPort: 22000,
Containers: []Container{{
PortMappings: []PortMapping{
{HostPort: 30000},
{HostPort: 30001},
},
}},
}
port, err := AllocateSSHPort()
if err != nil {
t.Fatal(err)
}
if port != 30002 {
t.Fatalf("expected port 30002, got %d", port)
}
if AppConfig.NextSSHPort != 30000 {
t.Fatalf("expected next port to wrap to 30000, got %d", AppConfig.NextSSHPort)
}
}
func TestAllocateSSHPortErrorsWhenConfiguredRangeIsFull(t *testing.T) {
AppConfig = &ClicdConfig{
NATPortStart: 31000,
NATPortEnd: 31001,
NextSSHPort: 31000,
Containers: []Container{{
PortMappings: []PortMapping{
{HostPort: 31000},
{HostPort: 31001},
},
}},
}
if port, err := AllocateSSHPort(); err == nil {
t.Fatalf("expected exhausted NAT range error, got port %d", port)
}
}
func TestAllocateSSHPortExcludingRequestedMappings(t *testing.T) {
previous := AppConfig
t.Cleanup(func() { AppConfig = previous })
AppConfig = &ClicdConfig{
NATPortStart: 32000,
NATPortEnd: 32002,
NextSSHPort: 32000,
}
port, err := AllocateSSHPortExcluding([]int{32000, 32001})
if err != nil {
t.Fatal(err)
}
if port != 32002 {
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)
}
}
+136
View File
@@ -0,0 +1,136 @@
package config
import (
"fmt"
"net"
"net/url"
"strings"
)
// NormalizeAllowedOrigin accepts a browser Origin value such as
// https://www.example.com and returns a canonical form for exact matching.
func NormalizeAllowedOrigin(value string) (string, error) {
value = strings.TrimSpace(value)
if value == "" {
return "", nil
}
u, err := url.Parse(value)
if err != nil || u.Scheme == "" || u.Host == "" {
return "", fmt.Errorf("Origin must include scheme and host: %s", value)
}
scheme := strings.ToLower(u.Scheme)
if scheme != "http" && scheme != "https" {
return "", fmt.Errorf("Origin scheme must be http or https: %s", value)
}
if (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" {
return "", fmt.Errorf("Origin must not include path, query, or fragment: %s", value)
}
host := normalizeOriginHostPort(u.Host, scheme)
if host == "" {
return "", fmt.Errorf("Origin host is required: %s", value)
}
return scheme + "://" + host, nil
}
func NormalizeAllowedOrigins(values []string) ([]string, error) {
result := make([]string, 0, len(values))
seen := map[string]bool{}
for _, value := range values {
origin, err := NormalizeAllowedOrigin(value)
if err != nil {
return nil, err
}
if origin == "" || seen[origin] {
continue
}
seen[origin] = true
result = append(result, origin)
}
return result, nil
}
func IsOriginAllowed(origin string, requestHost string) bool {
origin = strings.TrimSpace(origin)
if origin == "" {
return true
}
if isSameRequestOrigin(origin, requestHost) {
return true
}
normalized, err := NormalizeAllowedOrigin(origin)
if err != nil {
return false
}
if AppConfig == nil {
return false
}
for _, allowed := range AppConfig.WebSSHAllowedOrigins {
allowed, err := NormalizeAllowedOrigin(allowed)
if err == nil && normalized == allowed {
return true
}
}
return false
}
func isSameRequestOrigin(origin string, requestHost string) bool {
u, err := url.Parse(origin)
if err != nil || u.Host == "" {
return false
}
originHost := normalizeHostOnly(u.Hostname())
host := normalizeHostOnly(requestHost)
if originHost == "" || host == "" {
return false
}
if originHost == host {
return true
}
return isLoopbackHost(originHost) && isLoopbackHost(host)
}
func normalizeOriginHostPort(raw string, scheme string) string {
host := raw
port := ""
if h, p, err := net.SplitHostPort(raw); err == nil {
host = h
port = p
}
host = normalizeHostOnly(host)
if host == "" {
return ""
}
if (scheme == "https" && port == "443") || (scheme == "http" && port == "80") {
port = ""
}
if port != "" {
return net.JoinHostPort(host, port)
}
if strings.Contains(host, ":") && net.ParseIP(host) != nil {
return "[" + host + "]"
}
return host
}
func normalizeHostOnly(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return ""
}
if h, _, err := net.SplitHostPort(raw); err == nil {
raw = h
}
raw = strings.Trim(raw, "[]")
if ip := net.ParseIP(raw); ip != nil {
return strings.ToLower(ip.String())
}
return strings.TrimSuffix(strings.ToLower(raw), ".")
}
func isLoopbackHost(host string) bool {
if host == "localhost" {
return true
}
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
+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)
}
})
}
}
+175
View File
@@ -0,0 +1,175 @@
package config
import (
"fmt"
"net"
"os"
"path/filepath"
"regexp"
"strings"
)
const letsEncryptLiveDir = "/etc/letsencrypt/live"
var dnsNamePattern = regexp.MustCompile(`^[A-Za-z0-9.-]+$`)
func SSLStorageDir() string {
dataDir := ""
if AppConfig != nil {
dataDir = AppConfig.DataDir
}
if dataDir == "" {
dataDir = getDataDir()
}
return filepath.Join(dataDir, "ssl")
}
func UploadedSSLPaths() (string, string, error) {
dir, err := safeSSLStorageDir()
if err != nil {
return "", "", err
}
return filepath.Join(dir, "uploaded-fullchain.pem"), filepath.Join(dir, "uploaded-privkey.pem"), nil
}
func SelfSignedSSLPaths() (string, string, error) {
dir, err := safeSSLStorageDir()
if err != nil {
return "", "", err
}
return filepath.Join(dir, "self-signed-fullchain.pem"), filepath.Join(dir, "self-signed-privkey.pem"), nil
}
func LetsEncryptSSLPaths(target string) (string, string, error) {
name, err := NormalizeSSLCertificateTarget(target)
if err != nil {
return "", "", err
}
base := filepath.Join(letsEncryptLiveDir, name)
return filepath.Join(base, "fullchain.pem"), filepath.Join(base, "privkey.pem"), nil
}
func ResolveSSLConfigPaths(ssl SSLConfig) (string, string, error) {
mode := NormalizeSSLMode(ssl.Mode)
switch mode {
case SSLModeUploaded:
if ssl.CertPath != "" && ssl.KeyPath != "" {
return ResolveSSLPathPair(ssl.CertPath, ssl.KeyPath)
}
return UploadedSSLPaths()
case SSLModeSelfSigned:
if ssl.CertPath != "" && ssl.KeyPath != "" {
return ResolveSSLPathPair(ssl.CertPath, ssl.KeyPath)
}
return SelfSignedSSLPaths()
case SSLModeLetsEncrypt:
if strings.TrimSpace(ssl.Target) == "" && ssl.CertPath != "" && ssl.KeyPath != "" {
return ResolveSSLPathPair(ssl.CertPath, ssl.KeyPath)
}
return LetsEncryptSSLPaths(ssl.Target)
default:
return "", "", fmt.Errorf("SSL is disabled")
}
}
func ResolveSSLPathPair(certPath, keyPath string) (string, string, error) {
safeCertPath, err := ResolveSSLPath(certPath)
if err != nil {
return "", "", err
}
safeKeyPath, err := ResolveSSLPath(keyPath)
if err != nil {
return "", "", err
}
return safeCertPath, safeKeyPath, nil
}
func ResolveSSLPath(path string) (string, error) {
cleaned, err := cleanAbsolutePath(path)
if err != nil {
return "", err
}
if isPathUnder(cleaned, SSLStorageDir()) || isPathUnder(cleaned, letsEncryptLiveDir) || isPathUnder(cleaned, "/etc/letsencrypt/archive") {
return cleaned, nil
}
return "", fmt.Errorf("SSL path is outside allowed certificate directories")
}
func ReadableFileStat(path string) (os.FileInfo, error) {
safePath, err := ResolveSSLPath(path)
if err != nil {
return nil, err
}
return os.Stat(safePath)
}
func NormalizeSSLCertificateTarget(target string) (string, error) {
target = strings.TrimSpace(strings.Trim(target, "[]"))
if target == "" {
return "", fmt.Errorf("SSL target is required")
}
if strings.Contains(target, "/") || strings.Contains(target, "\\") || strings.Contains(target, "..") {
return "", fmt.Errorf("SSL target contains invalid path characters")
}
if ip := net.ParseIP(target); ip != nil {
return ip.String(), nil
}
if len(target) > 253 || !dnsNamePattern.MatchString(target) {
return "", fmt.Errorf("SSL target must be a valid IP address or DNS name")
}
labels := strings.Split(target, ".")
for _, label := range labels {
if label == "" || len(label) > 63 || strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") {
return "", fmt.Errorf("SSL target must be a valid IP address or DNS name")
}
}
return strings.ToLower(target), nil
}
func safeSSLStorageDir() (string, error) {
dir, err := cleanAbsolutePath(SSLStorageDir())
if err != nil {
return "", err
}
dataDir := ""
if AppConfig != nil {
dataDir = AppConfig.DataDir
}
if dataDir == "" {
dataDir = getDataDir()
}
if !isPathUnder(dir, dataDir) {
return "", fmt.Errorf("SSL storage directory is outside the data directory")
}
if err := os.MkdirAll(dir, 0700); err != nil {
return "", err
}
return dir, nil
}
func cleanAbsolutePath(path string) (string, error) {
if strings.TrimSpace(path) == "" {
return "", fmt.Errorf("path is empty")
}
abs, err := filepath.Abs(path)
if err != nil {
return "", err
}
return filepath.Clean(abs), nil
}
func isPathUnder(path, root string) bool {
cleanPath, err := cleanAbsolutePath(path)
if err != nil {
return false
}
cleanRoot, err := cleanAbsolutePath(root)
if err != nil {
return false
}
rel, err := filepath.Rel(cleanRoot, cleanPath)
if err != nil {
return false
}
return rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)))
}
+114
View File
@@ -0,0 +1,114 @@
package config
import (
"path/filepath"
"testing"
)
func TestNormalizeStoragePoolsReplacesPersistedCustomPath(t *testing.T) {
previousConfig := AppConfig
t.Cleanup(func() { AppConfig = previousConfig })
mountPoint := filepath.Join(t.TempDir(), "data")
AppConfig = &ClicdConfig{StoragePools: []StoragePool{{
ID: "data",
Name: "data",
Path: filepath.Join(t.TempDir(), "uncontrolled"),
MountPoint: mountPoint,
Enabled: true,
}}}
if !normalizeStoragePools() {
t.Fatal("expected custom path normalization to report a change")
}
want := managedStoragePoolPath(mountPoint)
if got := AppConfig.StoragePools[0].Path; got != want {
t.Fatalf("normalized path = %q, want %q", got, want)
}
}
func TestSelectStoragePoolForContent(t *testing.T) {
previousConfig := AppConfig
previousProbe := probeStoragePoolFreeBytes
t.Cleanup(func() {
AppConfig = previousConfig
probeStoragePoolFreeBytes = previousProbe
})
AppConfig = &ClicdConfig{StoragePools: []StoragePool{
{
ID: "primary",
Path: "/primary",
ContentTypes: []string{StorageContentLXC},
DefaultContents: []string{StorageContentLXC},
Enabled: true,
},
{
ID: "large",
Path: "/large",
ContentTypes: []string{StorageContentLXC},
Enabled: true,
},
{
ID: "small",
Path: "/small",
ContentTypes: []string{StorageContentLXC},
Enabled: true,
},
}}
free := map[string]int64{
"primary": 20 * 1024 * 1024 * 1024,
"large": 50 * 1024 * 1024 * 1024,
"small": 10 * 1024 * 1024 * 1024,
}
probeStoragePoolFreeBytes = func(pool StoragePool) (int64, bool) {
value, ok := free[pool.ID]
return value, ok
}
pool, err := SelectStoragePoolForContent(StorageContentLXC, "", 5*1024*1024*1024)
if err != nil {
t.Fatal(err)
}
if pool.ID != "primary" {
t.Fatalf("selected %q, want configured default primary", pool.ID)
}
free["primary"] = 128 * 1024 * 1024
pool, err = SelectStoragePoolForContent(StorageContentLXC, "", 5*1024*1024*1024)
if err != nil {
t.Fatal(err)
}
if pool.ID != "large" {
t.Fatalf("selected %q, want largest fallback pool", pool.ID)
}
pool, err = SelectStoragePoolForContent(StorageContentLXC, "small", 5*1024*1024*1024)
if err != nil {
t.Fatal(err)
}
if pool.ID != "small" {
t.Fatalf("selected %q, want requested pool", pool.ID)
}
}
func TestSelectStoragePoolRequiresEnabledContent(t *testing.T) {
previousConfig := AppConfig
previousProbe := probeStoragePoolFreeBytes
t.Cleanup(func() {
AppConfig = previousConfig
probeStoragePoolFreeBytes = previousProbe
})
AppConfig = &ClicdConfig{StoragePools: []StoragePool{{
ID: "primary",
Path: "/primary",
ContentTypes: []string{StorageContentLXC},
Enabled: true,
}}}
probeStoragePoolFreeBytes = func(StoragePool) (int64, bool) { return 100 * 1024 * 1024 * 1024, true }
if _, err := SelectStoragePoolForContent(StorageContentSnapshots, "", 0); err == nil {
t.Fatal("expected snapshots selection to fail when no pool enables snapshots")
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,185 @@
package config
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
func TestSQLiteConfigMigratesLegacyJSONAndPersists(t *testing.T) {
resetConfigStoreForTest(t)
dir := t.TempDir()
t.Cleanup(func() {
resetConfigStoreForTest(t)
})
legacyPath := filepath.Join(dir, "config.json")
SetConfigPath(legacyPath)
legacy := ClicdConfig{
AdminUser: "admin",
AdminPassHash: "hash",
JWTSecret: "secret",
Port: 8999,
DataDir: dir,
NextContainerID: 2,
NextVNCPort: 5900,
NextSSHPort: 22000,
Containers: []Container{{
ID: 1,
UUID: "uuid-1",
Name: "ct1",
Virtualization: "lxc",
Template: "debian-12",
Status: "running",
PortMappingLimit: 2,
SnapshotLimit: 3,
PortMappings: []PortMapping{{
ContainerPort: 22,
HostPort: 22001,
Protocol: "tcp",
Description: "SSH",
}},
}},
AuditLogs: []AuditLog{{
Time: "2026-06-07 17:29:00",
Action: "security_horizontal_scan",
Target: "ct1",
Detail: "[medium] 可疑横向探测",
User: "system",
}},
LoginLogs: []SavedLoginLog{{
Time: "2026-06-07 17:29:01 CST",
Username: "admin",
IP: "127.0.0.1",
UserAgent: "test",
Success: true,
}},
Tasks: []SavedTask{{
ID: "task-1",
Type: "create",
ContainerName: "ct2",
Status: "pending",
CreatedAt: "2026-06-07 17:29:02",
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,
ContainerName: "ct1",
LXCName: "ct-1",
CreatedAt: "2026-06-07 17:30:00",
Path: filepath.Join(dir, "snap-1"),
}},
}
data, err := json.Marshal(legacy)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(legacyPath, data, 0600); err != nil {
t.Fatal(err)
}
cfg, err := InitConfig()
if err != nil {
t.Fatal(err)
}
if len(cfg.Containers) != 1 || len(cfg.Containers[0].PortMappings) != 1 {
t.Fatalf("legacy config was not migrated: %+v", cfg.Containers)
}
if len(cfg.Tasks) != 1 || !strings.Contains(cfg.Tasks[0].Config, `"extra_ports":[80,443]`) {
t.Fatalf("task config was not restored from sqlite columns: %+v", cfg.Tasks)
}
if !strings.Contains(cfg.Tasks[0].Config, `"nat_port_mappings":[{"host_port":30080,"container_port":80`) {
t.Fatalf("task NAT mappings were not restored from sqlite: %+v", cfg.Tasks)
}
if !strings.Contains(cfg.Tasks[0].Config, `"management_port":30022`) {
t.Fatalf("task management port was not restored from sqlite: %+v", cfg.Tasks)
}
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)
}
cfg.Containers[0].Status = "stopped"
cfg.TaskConcurrency = 6
if err := SaveConfig(); err != nil {
t.Fatal(err)
}
resetConfigStoreForTest(t)
SetConfigPath(legacyPath)
cfg, err = InitConfig()
if err != nil {
t.Fatal(err)
}
if got := cfg.Containers[0].Status; got != "stopped" {
t.Fatalf("expected sqlite value to win after migration, got %q", got)
}
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) {
t.Helper()
if db != nil {
if err := db.Close(); err != nil {
t.Fatal(err)
}
db = nil
}
AppConfig = nil
configPath = ""
}
+2140 -228
View File
File diff suppressed because it is too large Load Diff
+251
View File
@@ -0,0 +1,251 @@
package kvm
import (
"crypto/ed25519"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/xml"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"clicd/internal/config"
"golang.org/x/crypto/ssh"
)
func TestImagePathUsesAllowlistedImageID(t *testing.T) {
for _, id := range []string{"", ".", "..", "../../etc/passwd", `..\\..\\windows`, "/absolute", "unknown-image"} {
if got := filepath.Base(ImagePath(id)); got != "__invalid_image_id__.qcow2" {
t.Fatalf("ImagePath(%q) basename = %q", id, got)
}
}
validID := GetImages()[0].ID
if got := filepath.Base(ImagePath(validID)); got != validID+".qcow2" {
t.Fatalf("ImagePath(%q) basename = %q", validID, got)
}
}
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
info string
want bool
}{
{name: "active", info: "Name: default\nActive: yes\n", want: true},
{name: "spacing and case", info: " Active : YES \r\n", want: true},
{name: "inactive", info: "Name: default\nActive: no\n", want: false},
{name: "missing field", info: "Name: default\nAutostart: yes\n", want: false},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := libvirtNetworkActive(tc.info); got != tc.want {
t.Fatalf("libvirtNetworkActive(%q) = %v, want %v", tc.info, got, tc.want)
}
})
}
}
func TestChpasswdStdinPreservesShellMetacharacters(t *testing.T) {
password := `pa'";$(touch /tmp/pwned); echo #\\word`
got, err := chpasswdStdin("root", password)
if err != nil {
t.Fatalf("chpasswdStdin returned error: %v", err)
}
want := []byte("root:" + password + "\n")
if !reflect.DeepEqual(got, want) {
t.Fatalf("chpasswdStdin = %#v, want %#v", got, want)
}
}
func TestChpasswdStdinRejectsNewlines(t *testing.T) {
tests := []struct {
name string
username string
password string
}{
{name: "username newline", username: "root\nadmin", password: "safe"},
{name: "username colon", username: "root:admin", password: "safe"},
{name: "password newline", username: "root", password: "safe\nroot:evil"},
{name: "password carriage return", username: "root", password: "safe\rroot:evil"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if _, err := chpasswdStdin(tc.username, tc.password); err == nil {
t.Fatal("chpasswdStdin returned nil error")
}
})
}
}
func TestVerifyKVMHostKeyCapturesAndRejectsMismatch(t *testing.T) {
key1 := testSSHPublicKey(t)
key2 := testSSHPublicKey(t)
saves := 0
c := &config.Container{}
save := func() error {
saves++
return nil
}
if err := verifyKVMHostKey(c, key1, save); err != nil {
t.Fatalf("first host key verification returned error: %v", err)
}
if c.SSHHostKey == "" {
t.Fatal("first host key verification did not capture fingerprint")
}
if c.SSHHostKey != sshHostKeyFingerprint(key1) {
t.Fatalf("captured fingerprint = %q, want %q", c.SSHHostKey, sshHostKeyFingerprint(key1))
}
if saves != 1 {
t.Fatalf("save count = %d, want 1", saves)
}
if err := verifyKVMHostKey(c, key1, save); err != nil {
t.Fatalf("same host key verification returned error: %v", err)
}
if saves != 1 {
t.Fatalf("save count after same key = %d, want 1", saves)
}
if err := verifyKVMHostKey(c, key2, save); err == nil {
t.Fatal("mismatched host key verification returned nil error")
}
}
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)
if err != nil {
t.Fatal(err)
}
signer, err := ssh.NewSignerFromKey(privateKey)
if err != nil {
t.Fatal(err)
}
return signer.PublicKey()
}
+178 -1
View File
@@ -1,7 +1,11 @@
package kvm
import (
"os"
"path/filepath"
"runtime"
"clicd/internal/config"
)
type Image struct {
@@ -12,9 +16,41 @@ type Image struct {
Arch string `json:"arch"`
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":
images = arm64Images()
default:
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 {
return []Image{
{
ID: "kvm-ubuntu-noble", Name: "Ubuntu 24.04 KVM",
@@ -22,18 +58,45 @@ func GetImages() []Image {
Description: "Ubuntu 24.04 LTS cloud image for KVM",
URL: "https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img",
},
{
ID: "kvm-ubuntu-noble-xfce", Name: "Ubuntu 24.04 XFCE KVM",
Distro: "ubuntu", Release: "noble", Arch: "amd64",
Description: "Ubuntu 24.04 LTS cloud image with XFCE desktop provisioned via cloud-init",
URL: "https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img",
Desktop: "xfce",
},
{
ID: "kvm-ubuntu-jammy", Name: "Ubuntu 22.04 KVM",
Distro: "ubuntu", Release: "jammy", Arch: "amd64",
Description: "Ubuntu 22.04 LTS cloud image for KVM",
URL: "https://cloud-images.ubuntu.com/jammy/current/jammy-server-cloudimg-amd64.img",
},
{
ID: "kvm-debian-trixie", Name: "Debian 13 KVM",
Distro: "debian", Release: "trixie", Arch: "amd64",
Description: "Debian 13 generic cloud image for KVM",
URL: "https://cloud.debian.org/images/cloud/trixie/latest/debian-13-genericcloud-amd64.qcow2",
},
{
ID: "kvm-debian-bookworm", Name: "Debian 12 KVM",
Distro: "debian", Release: "bookworm", Arch: "amd64",
Description: "Debian 12 generic cloud image for KVM",
URL: "https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-genericcloud-amd64.qcow2",
},
{
ID: "kvm-debian-trixie-xfce", Name: "Debian 13 XFCE KVM",
Distro: "debian", Release: "trixie", Arch: "amd64",
Description: "Debian 13 generic cloud image with XFCE desktop provisioned via cloud-init",
URL: "https://cloud.debian.org/images/cloud/trixie/latest/debian-13-genericcloud-amd64.qcow2",
Desktop: "xfce",
},
{
ID: "kvm-debian-bookworm-xfce", Name: "Debian 12 XFCE KVM",
Distro: "debian", Release: "bookworm", Arch: "amd64",
Description: "Debian 12 generic cloud image with XFCE desktop provisioned via cloud-init",
URL: "https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-genericcloud-amd64.qcow2",
Desktop: "xfce",
},
{
ID: "kvm-debian-bullseye", Name: "Debian 11 KVM",
Distro: "debian", Release: "bullseye", Arch: "amd64",
@@ -70,6 +133,71 @@ func GetImages() []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",
Description: "Windows 10 Enterprise LTSC Evaluation",
URL: "https://go.microsoft.com/fwlink/?LinkID=2195404",
},
}
}
func arm64Images() []Image {
return []Image{
{
ID: "kvm-ubuntu-noble", Name: "Ubuntu 24.04 KVM",
Distro: "ubuntu", Release: "noble", Arch: "arm64",
Description: "Ubuntu 24.04 LTS cloud image for ARM64 KVM",
URL: "https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-arm64.img",
},
{
ID: "kvm-ubuntu-jammy", Name: "Ubuntu 22.04 KVM",
Distro: "ubuntu", Release: "jammy", Arch: "arm64",
Description: "Ubuntu 22.04 LTS cloud image for ARM64 KVM",
URL: "https://cloud-images.ubuntu.com/jammy/current/jammy-server-cloudimg-arm64.img",
},
{
ID: "kvm-debian-trixie", Name: "Debian 13 KVM",
Distro: "debian", Release: "trixie", Arch: "arm64",
Description: "Debian 13 generic cloud image for ARM64 KVM",
URL: "https://cloud.debian.org/images/cloud/trixie/latest/debian-13-genericcloud-arm64.qcow2",
},
{
ID: "kvm-debian-bookworm", Name: "Debian 12 KVM",
Distro: "debian", Release: "bookworm", Arch: "arm64",
Description: "Debian 12 generic cloud image for ARM64 KVM",
URL: "https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-genericcloud-arm64.qcow2",
},
{
ID: "kvm-debian-bullseye", Name: "Debian 11 KVM",
Distro: "debian", Release: "bullseye", Arch: "arm64",
Description: "Debian 11 generic cloud image for ARM64 KVM",
URL: "https://cloud.debian.org/images/cloud/bullseye/latest/debian-11-genericcloud-arm64.qcow2",
},
{
ID: "kvm-centos-9-stream", Name: "CentOS Stream 9 KVM",
Distro: "centos", Release: "9-stream", Arch: "arm64",
Description: "CentOS Stream 9 GenericCloud image for ARM64 KVM",
URL: "https://cloud.centos.org/centos/9-stream/aarch64/images/CentOS-Stream-GenericCloud-9-latest.aarch64.qcow2",
},
{
ID: "kvm-fedora-44", Name: "Fedora 44 KVM",
Distro: "fedora", Release: "44", Arch: "arm64",
Description: "Fedora 44 GenericCloud image for ARM64 KVM",
URL: "https://download.fedoraproject.org/pub/fedora/linux/releases/44/Cloud/aarch64/images/Fedora-Cloud-Base-Generic-44-1.7.aarch64.qcow2",
},
{
ID: "kvm-rockylinux-9", Name: "Rocky Linux 9 KVM",
Distro: "rockylinux", Release: "9", Arch: "arm64",
Description: "Rocky Linux 9 GenericCloud image for ARM64 KVM",
URL: "https://dl.rockylinux.org/pub/rocky/9/images/aarch64/Rocky-9-GenericCloud-Base.latest.aarch64.qcow2",
},
}
}
@@ -83,9 +211,58 @@ func FindImage(id string) *Image {
}
func CacheDir() string {
if pool := config.PreferredStoragePoolForContent(config.StorageContentImages); pool != nil {
return filepath.Join(pool.Path, "images", "kvm")
}
return filepath.Join(BaseDir(), "images")
}
func ImagePath(id string) string {
return filepath.Join(CacheDir(), id+".qcow2")
img := FindImage(id)
ext := ".qcow2"
safeID := "__invalid_image_id__"
if img != nil {
safeID = img.ID
}
if img != nil && img.IsWindows() {
ext = ".iso"
}
fileName := safeID + ext
for _, pool := range config.StoragePoolsForContent(config.StorageContentImages) {
candidate := filepath.Join(pool.Path, "images", "kvm", fileName)
if info, err := os.Stat(candidate); err == nil && !info.IsDir() {
return candidate
}
}
legacy := filepath.Join("/var/lib/clicd/kvm/images", fileName)
if info, err := os.Stat(legacy); err == nil && !info.IsDir() {
return legacy
}
return filepath.Join(CacheDir(), fileName)
}
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.IsWindows()
}
func IsWindows11Image(id string) bool {
img := FindImage(id)
return img != nil && img.IsWindows11()
}
func virtioWinISOPath() string {
return filepath.Join(CacheDir(), "virtio-win.iso")
}
+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)
}
}
}
File diff suppressed because it is too large Load Diff
+1601 -247
View File
File diff suppressed because it is too large Load Diff
+514
View File
@@ -0,0 +1,514 @@
package lxc
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"clicd/internal/config"
)
func TestRootfsCommandAddsSeparatorForAllowedCommand(t *testing.T) {
base := t.TempDir()
rootfs := filepath.Join(base, "ct-1", "rootfs")
if err := os.MkdirAll(rootfs, 0755); err != nil {
t.Fatal(err)
}
m := &Manager{LxcPath: base}
cmd, err := m.rootfsCommand(rootfs, "chpasswd")
if err != nil {
t.Fatalf("rootfsCommand returned error: %v", err)
}
want := []string{"chroot", "--", rootfs, "chpasswd"}
if !reflect.DeepEqual(cmd.Args, want) {
t.Fatalf("cmd.Args = %#v, want %#v", cmd.Args, want)
}
}
func TestNormalizeCreateNATMappingsSupportsDifferentHostAndContainerPorts(t *testing.T) {
previous := config.AppConfig
t.Cleanup(func() { config.AppConfig = previous })
config.AppConfig = &config.ClicdConfig{NATPortStart: 20000, NATPortEnd: 65535}
cfg := ContainerConfig{
PortMappingCount: 2,
NATPortMappings: []config.PortMapping{{
HostPort: 30080,
ContainerPort: 80,
Protocol: "TCP",
}},
}
if err := cfg.NormalizeCreateNATMappings(); err != nil {
t.Fatal(err)
}
if cfg.PortMappingCount != 2 || len(cfg.NATPortMappings) != 1 {
t.Fatalf("normalized config = %+v", cfg)
}
mapping := cfg.NATPortMappings[0]
if mapping.HostPort != 30080 || mapping.ContainerPort != 80 || mapping.Protocol != "tcp" {
t.Fatalf("normalized mapping = %+v", mapping)
}
container := &config.Container{
ID: -1,
PortMappings: []config.PortMapping{{
HostPort: 22000,
ContainerPort: 22,
Protocol: "tcp",
Description: "SSH",
}},
}
mappings, err := SetupCreatePortMappings(container, cfg)
if err != nil {
t.Fatal(err)
}
if len(mappings) != 2 || mappings[1].HostPort != 30080 || mappings[1].ContainerPort != 80 {
t.Fatalf("created mappings = %+v", mappings)
}
}
func TestNormalizeCreateNATMappingsKeepsLegacyExtraPortsCompatible(t *testing.T) {
previous := config.AppConfig
t.Cleanup(func() { config.AppConfig = previous })
config.AppConfig = &config.ClicdConfig{NATPortStart: 20000, NATPortEnd: 65535}
cfg := ContainerConfig{ExtraPorts: []int{30080, 30443}}
if err := cfg.NormalizeCreateNATMappings(); err != nil {
t.Fatal(err)
}
if len(cfg.ExtraPorts) != 0 || len(cfg.NATPortMappings) != 2 {
t.Fatalf("legacy ports were not converted: %+v", cfg)
}
for _, mapping := range cfg.NATPortMappings {
if mapping.HostPort != mapping.ContainerPort {
t.Fatalf("legacy mapping changed semantics: %+v", mapping)
}
}
}
func TestNormalizeCreateNATMappingsRejectsDuplicateHostPort(t *testing.T) {
previous := config.AppConfig
t.Cleanup(func() { config.AppConfig = previous })
config.AppConfig = &config.ClicdConfig{NATPortStart: 20000, NATPortEnd: 65535}
cfg := ContainerConfig{NATPortMappings: []config.PortMapping{
{HostPort: 30080, ContainerPort: 80, Protocol: "tcp"},
{HostPort: 30080, ContainerPort: 8080, Protocol: "tcp"},
}}
if err := cfg.NormalizeCreateNATMappings(); err == nil {
t.Fatal("duplicate host port was accepted")
}
}
func TestNormalizeCreateNATMappingsRejectsManagementPortConflict(t *testing.T) {
previous := config.AppConfig
t.Cleanup(func() { config.AppConfig = previous })
config.AppConfig = &config.ClicdConfig{NATPortStart: 20000, NATPortEnd: 65535}
cfg := ContainerConfig{
ManagementPort: 30022,
NATPortMappings: []config.PortMapping{{
HostPort: 30022,
ContainerPort: 8080,
Protocol: "tcp",
}},
}
if err := cfg.NormalizeCreateNATMappings(); err == nil || !strings.Contains(err.Error(), "management_port") {
t.Fatalf("management port conflict returned %v", err)
}
}
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 })
config.AppConfig = &config.ClicdConfig{
NATPortStart: 20000,
NATPortEnd: 65535,
NextSSHPort: 22000,
}
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()
})
cfg := ContainerConfig{NATPortMappings: []config.PortMapping{{
HostPort: 22000,
ContainerPort: 80,
Protocol: "tcp",
}}}
if err := cfg.NormalizeCreateNATMappings(); err != nil {
t.Fatal(err)
}
managementPort, release, err := ReserveCreateNATPorts(cfg)
if err != nil {
t.Fatal(err)
}
if managementPort == 22000 {
t.Fatal("management port collided with the requested custom host port")
}
if _, _, err := ReserveCreateNATPorts(cfg); err == nil {
t.Fatal("concurrent task reserved an already reserved custom host port")
}
release()
if _, releaseAgain, err := ReserveCreateNATPorts(cfg); err != nil {
t.Fatalf("released custom host port remained reserved: %v", err)
} else {
releaseAgain()
}
explicit := ContainerConfig{ManagementPort: 30022}
if err := explicit.NormalizeCreateNATMappings(); err != nil {
t.Fatal(err)
}
if port, releaseExplicit, err := ReserveCreateNATPorts(explicit); err != nil {
t.Fatal(err)
} else {
defer releaseExplicit()
if port != explicit.ManagementPort {
t.Fatalf("reserved management port = %d, want %d", port, explicit.ManagementPort)
}
}
}
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")
if err := os.MkdirAll(rootfs, 0755); err != nil {
t.Fatal(err)
}
m := &Manager{LxcPath: base}
if _, err := m.rootfsCommand(rootfs, "true"); err == nil {
t.Fatal("rootfsCommand allowed unmanaged command")
}
}
func TestRootfsCommandRejectsLeadingDashContainerName(t *testing.T) {
base := t.TempDir()
rootfs := filepath.Join(base, "-ct", "rootfs")
if err := os.MkdirAll(rootfs, 0755); err != nil {
t.Fatal(err)
}
m := &Manager{LxcPath: base}
if _, err := m.rootfsCommand(rootfs, "chpasswd"); err == nil {
t.Fatal("rootfsCommand allowed leading-dash container name")
}
}
func TestRootfsCommandRejectsUnsafeRootfsPaths(t *testing.T) {
base := t.TempDir()
outside := t.TempDir()
m := &Manager{LxcPath: base}
tests := []struct {
name string
path string
}{
{name: "outside base", path: filepath.Join(outside, "ct-1", "rootfs")},
{name: "base path", path: base},
{name: "not rootfs", path: filepath.Join(base, "ct-1", "not-rootfs")},
{name: "rootfs directly under base", path: filepath.Join(base, "rootfs")},
{name: "relative rootfs", path: filepath.Join("ct-1", "rootfs")},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if _, err := m.rootfsCommand(tc.path, "chpasswd"); err == nil {
t.Fatalf("rootfsCommand(%q) returned nil error", tc.path)
}
})
}
}
func TestSafeRootfsPathRejectsSiblingPrefix(t *testing.T) {
parent := t.TempDir()
base := filepath.Join(parent, "lxc")
siblingRootfs := filepath.Join(parent, "lxc-evil", "ct-1", "rootfs")
m := &Manager{LxcPath: base}
if _, err := m.safeRootfsPath(siblingRootfs); err == nil || !strings.Contains(err.Error(), "unsafe rootfs path") {
t.Fatalf("safeRootfsPath returned %v, want unsafe rootfs path error", err)
}
}
func TestIsLXCVDenylistSeccompProfile(t *testing.T) {
tests := []string{`
# base profile
2
denylist
[all]
open_by_handle_at errno 1
`, `
2
blacklist allow
[all]
open_by_handle_at errno 1
`}
for _, profile := range tests {
if !isLXCVDenylistSeccompProfile(profile) {
t.Fatalf("expected v2 denylist profile for\n%s", profile)
}
}
if isLXCVDenylistSeccompProfile("1\nallowlist\n1\n") {
t.Fatal("did not expect v1 allowlist profile")
}
}
func TestManagedPrlimitLinesDoNotSetNproc(t *testing.T) {
for _, line := range managedPrlimitLines() {
if strings.HasPrefix(strings.TrimSpace(line), "lxc.prlimit.nproc") {
t.Fatalf("managed prlimit lines must not set nproc: %q", line)
}
}
}
func TestRootfsHasSSHD(t *testing.T) {
rootfs := t.TempDir()
if rootfsHasSSHD(rootfs) {
t.Fatal("empty rootfs unexpectedly reports sshd")
}
sshd := filepath.Join(rootfs, "usr", "sbin", "sshd")
if err := os.MkdirAll(filepath.Dir(sshd), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(sshd, []byte("#!/bin/sh\n"), 0755); err != nil {
t.Fatal(err)
}
if !rootfsHasSSHD(rootfs) {
t.Fatal("executable sshd was not detected")
}
}
func TestSameFilesystemPathResolvesContainerStorageSymlink(t *testing.T) {
base := t.TempDir()
storageContainer := filepath.Join(base, "storage", "ct-1")
rootfs := filepath.Join(storageContainer, "rootfs")
if err := os.MkdirAll(rootfs, 0755); err != nil {
t.Fatal(err)
}
lxcPath := filepath.Join(base, "lxc")
if err := os.MkdirAll(lxcPath, 0755); err != nil {
t.Fatal(err)
}
containerLink := filepath.Join(lxcPath, "ct-1")
if err := os.Symlink(storageContainer, containerLink); err != nil {
t.Skipf("directory symlinks are unavailable: %v", err)
}
linkedRootfs := filepath.Join(containerLink, "rootfs")
if !sameFilesystemPath(rootfs, linkedRootfs) {
t.Fatalf("sameFilesystemPath(%q, %q) = false, want true", rootfs, linkedRootfs)
}
}
func TestAppendMissingSeccompRulesAddsFutexMitigationOnce(t *testing.T) {
base := "2\ndenylist\n[all]\nopen_by_handle_at errno 1\n"
once := appendMissingSeccompRules(base, cve202643499FutexSeccompRules)
twice := appendMissingSeccompRules(once, cve202643499FutexSeccompRules)
for _, want := range []string{
"futex errno 1 [1,0x6,SCMP_CMP_MASKED_EQ,0x7f]",
"futex errno 1 [1,0xb,SCMP_CMP_MASKED_EQ,0x7f]",
"futex errno 1 [1,0xc,SCMP_CMP_MASKED_EQ,0x7f]",
"futex errno 1 [1,0xd,SCMP_CMP_MASKED_EQ,0x7f]",
} {
if !strings.Contains(once, want) {
t.Fatalf("missing seccomp rule %q in\n%s", want, once)
}
if strings.Count(twice, want) != 1 {
t.Fatalf("rule %q duplicated in\n%s", want, twice)
}
}
}
File diff suppressed because it is too large Load Diff
+44 -6
View File
@@ -16,7 +16,7 @@ import (
var snapshotMu sync.Mutex
func (m *Manager) CreateSnapshot(id int, createdBy string, scheduled bool, rotateLimit int) (config.Snapshot, error) {
func (m *Manager) CreateSnapshot(id int, createdBy string, scheduled bool, rotateLimit int, storagePoolID ...string) (config.Snapshot, error) {
snapshotMu.Lock()
defer snapshotMu.Unlock()
@@ -42,12 +42,21 @@ func (m *Manager) CreateSnapshot(id int, createdBy string, scheduled bool, rotat
if _, err := os.Stat(containerDir); err != nil {
return config.Snapshot{}, fmt.Errorf("container storage not found: %v", err)
}
pool, err := config.SelectStoragePoolForContent(
config.StorageContentSnapshots,
firstString(storagePoolID),
dirSizeBytes(containerDir),
)
if err != nil {
return config.Snapshot{}, err
}
now := time.Now()
snapshotID := fmt.Sprintf("snap-%d-%s", id, now.Format("20060102150405-000000000"))
// Use container ID instead of lxcName to avoid collision when containers are recreated
snapshotDir := filepath.Join(snapshotBaseDir(), strconv.Itoa(id), snapshotID)
if err := safePathUnder(snapshotDir, snapshotBaseDir()); err != nil {
baseDir := filepath.Join(pool.Path, "snapshots")
snapshotDir := filepath.Join(baseDir, strconv.Itoa(id), snapshotID)
if err := safePathUnder(snapshotDir, baseDir); err != nil {
return config.Snapshot{}, err
}
if err := os.MkdirAll(snapshotDir, 0700); err != nil {
@@ -100,7 +109,7 @@ func (m *Manager) DeleteSnapshot(id string) error {
func (m *Manager) deleteSnapshotLocked(snapshot config.Snapshot) error {
if snapshot.Path != "" {
if err := safePathUnder(snapshot.Path, snapshotBaseDir()); err != nil {
if err := safeSnapshotPath(snapshot.Path); err != nil {
return err
}
if err := os.RemoveAll(snapshot.Path); err != nil {
@@ -122,7 +131,7 @@ func (m *Manager) RestoreSnapshot(id string) error {
if snapshot.Path == "" {
return fmt.Errorf("snapshot path is empty")
}
if err := safePathUnder(snapshot.Path, snapshotBaseDir()); err != nil {
if err := safeSnapshotPath(snapshot.Path); err != nil {
return err
}
if _, err := os.Stat(snapshot.Path); err != nil {
@@ -295,7 +304,33 @@ func (m *Manager) prepareContainerForColdCopy(id int, lxcName string, containerD
}
func snapshotBaseDir() string {
return filepath.Join(config.AppConfig.DataDir, "snapshots")
return snapshotBaseDirForPool("")
}
func snapshotBaseDirForPool(poolID string) string {
if pool, err := config.SelectStoragePoolForContent(config.StorageContentSnapshots, poolID, 0); err == nil {
return filepath.Join(pool.Path, "snapshots")
}
return ""
}
func safeSnapshotPath(path string) error {
if err := safePathUnder(path, filepath.Join(config.AppConfig.DataDir, "snapshots")); err == nil {
return nil
}
for _, pool := range config.StoragePoolsForContent(config.StorageContentSnapshots) {
if err := safePathUnder(path, filepath.Join(pool.Path, "snapshots")); err == nil {
return nil
}
}
return fmt.Errorf("unsafe snapshot path: %s", path)
}
func firstString(values []string) string {
if len(values) == 0 {
return ""
}
return strings.TrimSpace(values[0])
}
func copyTree(src string, dst string) error {
@@ -313,6 +348,9 @@ func copyTree(src string, dst string) error {
}
func dirSizeBytes(path string) int64 {
if resolved, err := filepath.EvalSymlinks(path); err == nil {
path = resolved
}
out, err := exec.Command("du", "-s", "-B1", path).Output()
if err != nil {
return 0
+221
View File
@@ -0,0 +1,221 @@
package lxc
import (
"fmt"
"strings"
"unicode"
"golang.org/x/crypto/ssh"
)
const (
SSHAuthAutoPassword = "auto_password"
SSHAuthPassword = "password"
SSHAuthKey = "key"
SSHAuthKeep = "keep"
)
type SSHAccess struct {
Mode string
Password string
PublicKey string
}
func HasSSHAuthOptions(cfg ContainerConfig) bool {
return strings.TrimSpace(cfg.SSHAuthMode) != "" ||
strings.TrimSpace(cfg.SSHPassword) != "" ||
strings.TrimSpace(cfg.SSHPublicKey) != ""
}
func ResolveCreateSSHAccess(cfg ContainerConfig) (SSHAccess, error) {
mode, err := resolveSSHAuthMode(cfg.SSHAuthMode, cfg.SSHPassword, cfg.SSHPublicKey, SSHAuthAutoPassword)
if err != nil {
return SSHAccess{}, err
}
if mode == SSHAuthKeep {
mode = SSHAuthAutoPassword
}
switch mode {
case SSHAuthAutoPassword:
return SSHAccess{Mode: mode, Password: generateRandomString(16)}, nil
case SSHAuthPassword:
password := strings.TrimSpace(cfg.SSHPassword)
if password == "" {
return SSHAccess{}, fmt.Errorf("请填写自定义 SSH 密码")
}
if err := ValidateCustomSSHPassword(password); err != nil {
return SSHAccess{}, err
}
return SSHAccess{Mode: mode, Password: password}, nil
case SSHAuthKey:
publicKey, err := NormalizeSSHPublicKey(cfg.SSHPublicKey)
if err != nil {
return SSHAccess{}, err
}
if publicKey == "" {
return SSHAccess{}, fmt.Errorf("请填写 SSH 公钥")
}
password := strings.TrimSpace(cfg.SSHPassword)
if password == "" {
password = generateRandomString(16)
} else if err := ValidateCustomSSHPassword(password); err != nil {
return SSHAccess{}, err
}
return SSHAccess{Mode: mode, Password: password, PublicKey: publicKey}, nil
default:
return SSHAccess{}, fmt.Errorf("不支持的 SSH 登录方式: %s", mode)
}
}
func ResolveReinstallSSHAccess(currentPassword string, cfg ContainerConfig) (SSHAccess, error) {
mode, err := resolveSSHAuthMode(cfg.SSHAuthMode, cfg.SSHPassword, cfg.SSHPublicKey, SSHAuthKeep)
if err != nil {
return SSHAccess{}, err
}
switch mode {
case SSHAuthKeep:
password := strings.TrimSpace(currentPassword)
if password == "" {
password = generateRandomString(16)
}
if err := validateRootPassword(password); err != nil {
return SSHAccess{}, err
}
return SSHAccess{Mode: mode, Password: password}, nil
case SSHAuthAutoPassword:
return SSHAccess{Mode: mode, Password: generateRandomString(16)}, nil
case SSHAuthPassword:
password := strings.TrimSpace(cfg.SSHPassword)
if password == "" {
return SSHAccess{}, fmt.Errorf("请填写自定义 SSH 密码")
}
if err := ValidateCustomSSHPassword(password); err != nil {
return SSHAccess{}, err
}
return SSHAccess{Mode: mode, Password: password}, nil
case SSHAuthKey:
publicKey, err := NormalizeSSHPublicKey(cfg.SSHPublicKey)
if err != nil {
return SSHAccess{}, err
}
if publicKey == "" {
return SSHAccess{}, fmt.Errorf("请填写 SSH 公钥")
}
password := strings.TrimSpace(cfg.SSHPassword)
if password != "" {
if err := ValidateCustomSSHPassword(password); err != nil {
return SSHAccess{}, err
}
} else {
password = strings.TrimSpace(currentPassword)
if password == "" {
password = generateRandomString(16)
}
}
if err := validateRootPassword(password); err != nil {
return SSHAccess{}, err
}
return SSHAccess{Mode: mode, Password: password, PublicKey: publicKey}, nil
default:
return SSHAccess{}, fmt.Errorf("不支持的 SSH 登录方式: %s", mode)
}
}
func ValidateCustomSSHPassword(password string) error {
if len(password) < 8 || len(password) > 64 {
return fmt.Errorf("密码长度必须为 8-64 位")
}
hasLetter := false
hasDigit := false
for _, r := range password {
if unicode.IsSpace(r) {
return fmt.Errorf("密码不能包含空白字符")
}
if unicode.IsLetter(r) {
hasLetter = true
}
if unicode.IsDigit(r) {
hasDigit = true
}
}
if !hasLetter || !hasDigit {
return fmt.Errorf("密码至少需要包含字母和数字")
}
return validateRootPassword(password)
}
func NormalizeSSHPublicKey(publicKey string) (string, error) {
key := strings.TrimSpace(publicKey)
if key == "" {
return "", nil
}
if len(key) > 8192 {
return "", fmt.Errorf("SSH 公钥长度不能超过 8192 字符")
}
if strings.ContainsAny(key, "\r\n") || strings.ContainsRune(key, '\x00') {
return "", fmt.Errorf("SSH 公钥只能填写一行")
}
fields := strings.Fields(key)
if len(fields) < 2 {
return "", fmt.Errorf("SSH 公钥格式不正确")
}
if !isSupportedSSHKeyType(fields[0]) {
return "", fmt.Errorf("不支持的 SSH 公钥类型: %s", fields[0])
}
parsed, _, _, rest, err := ssh.ParseAuthorizedKey([]byte(key))
if err != nil {
return "", fmt.Errorf("SSH 公钥格式不正确")
}
if strings.TrimSpace(string(rest)) != "" {
return "", fmt.Errorf("一次只能填写一个 SSH 公钥")
}
if !isSupportedSSHKeyType(parsed.Type()) {
return "", fmt.Errorf("不支持的 SSH 公钥类型: %s", parsed.Type())
}
return key, nil
}
func resolveSSHAuthMode(rawMode, password, publicKey, defaultMode string) (string, error) {
mode := strings.ToLower(strings.TrimSpace(rawMode))
mode = strings.ReplaceAll(mode, "-", "_")
if mode == "" {
if strings.TrimSpace(publicKey) != "" {
return SSHAuthKey, nil
}
if strings.TrimSpace(password) != "" {
return SSHAuthPassword, nil
}
return defaultMode, nil
}
switch mode {
case "auto", "auto_password", "generated", "generate":
return SSHAuthAutoPassword, nil
case "password", "custom_password":
return SSHAuthPassword, nil
case "key", "ssh_key", "public_key":
return SSHAuthKey, nil
case "keep", "retain", "keep_password":
return SSHAuthKeep, nil
default:
return "", fmt.Errorf("不支持的 SSH 登录方式: %s", rawMode)
}
}
func isSupportedSSHKeyType(keyType string) bool {
switch keyType {
case "ssh-ed25519",
"ssh-rsa",
"ecdsa-sha2-nistp256",
"ecdsa-sha2-nistp384",
"ecdsa-sha2-nistp521",
"sk-ssh-ed25519@openssh.com",
"sk-ecdsa-sha2-nistp256@openssh.com":
return true
default:
return false
}
}
+51 -10
View File
@@ -1,5 +1,11 @@
package lxc
import (
"runtime"
"clicd/internal/config"
)
// Template represents an LXC image template
type Template struct {
ID string `json:"id"`
@@ -9,57 +15,92 @@ 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 {
return []Template{
arch := defaultTemplateArch()
templates := []Template{
{
ID: "ubuntu-noble", Name: "Ubuntu 24.04",
Distro: "ubuntu", Release: "noble", Arch: "amd64",
Distro: "ubuntu", Release: "noble", Arch: arch,
Description: "Ubuntu 24.04 LTS",
},
{
ID: "ubuntu-jammy", Name: "Ubuntu 22.04",
Distro: "ubuntu", Release: "jammy", Arch: "amd64",
Distro: "ubuntu", Release: "jammy", Arch: arch,
Description: "Ubuntu 22.04 LTS",
},
{
ID: "debian-trixie", Name: "Debian 13",
Distro: "debian", Release: "trixie", Arch: arch,
Description: "Debian 13 (Trixie)",
},
{
ID: "debian-bookworm", Name: "Debian 12",
Distro: "debian", Release: "bookworm", Arch: "amd64",
Distro: "debian", Release: "bookworm", Arch: arch,
Description: "Debian 12 (Bookworm)",
},
{
ID: "debian-bullseye", Name: "Debian 11",
Distro: "debian", Release: "bullseye", Arch: "amd64",
Distro: "debian", Release: "bullseye", Arch: arch,
Description: "Debian 11 (Bullseye)",
},
{
ID: "alpine-3.21", Name: "Alpine 3.21",
Distro: "alpine", Release: "3.21", Arch: "amd64",
Distro: "alpine", Release: "3.21", Arch: arch,
Description: "Alpine Linux 3.21",
},
{
ID: "centos-9-stream", Name: "CentOS 9 Stream",
Distro: "centos", Release: "9-Stream", Arch: "amd64",
Distro: "centos", Release: "9-Stream", Arch: arch,
Description: "CentOS 9 Stream",
},
{
ID: "archlinux-current", Name: "Arch Linux",
Distro: "archlinux", Release: "current", Arch: "amd64", Variant: "cloud",
Distro: "archlinux", Release: "current", Arch: arch,
Description: "Arch Linux (Rolling)",
},
{
ID: "fedora-44", Name: "Fedora 44",
Distro: "fedora", Release: "44", Arch: "amd64", Variant: "cloud",
Distro: "fedora", Release: "44", Arch: arch,
Description: "Fedora 44",
},
{
ID: "rockylinux-10", Name: "Rocky Linux 10",
Distro: "rockylinux", Release: "10", Arch: "amd64", Variant: "cloud",
Distro: "rockylinux", Release: "10", Arch: arch,
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 {
switch runtime.GOARCH {
case "arm64":
return "arm64"
default:
return "amd64"
}
}
// FindTemplate finds a template by ID
+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)
}
}
+131 -34
View File
@@ -1,11 +1,10 @@
package server
import (
"crypto/tls"
"fmt"
"log"
"net"
"net/http"
"net/url"
"strings"
"clicd/internal/api"
@@ -18,16 +17,16 @@ var webFS http.FileSystem
// corsMiddleware adds CORS headers
func corsMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" && isAllowedOrigin(origin, r.Host) {
if origin := r.Header.Get("Origin"); origin != "" && config.IsOriginAllowed(origin, r.Host) {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Vary", "Origin")
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-API-Key")
if r.Method == http.MethodOptions {
if origin := r.Header.Get("Origin"); origin != "" && !isAllowedOrigin(origin, r.Host) {
if origin := r.Header.Get("Origin"); origin != "" && !config.IsOriginAllowed(origin, r.Host) {
w.WriteHeader(http.StatusForbidden)
return
}
@@ -39,57 +38,41 @@ func corsMiddleware(next http.HandlerFunc) http.HandlerFunc {
}
}
func isAllowedOrigin(origin string, requestHost string) bool {
u, err := url.Parse(origin)
if err != nil || u.Host == "" {
return false
}
originHost := normalizeHost(u.Host)
host := normalizeHost(requestHost)
if originHost == host {
return true
}
return isLoopbackHost(originHost) && isLoopbackHost(host)
}
func normalizeHost(host string) string {
if h, _, err := net.SplitHostPort(host); err == nil {
return strings.ToLower(h)
}
return strings.ToLower(host)
}
func isLoopbackHost(host string) bool {
if host == "localhost" {
return true
}
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
// setupRoutes configures API and static routes
func setupRoutes(mux *http.ServeMux) {
// API routes
mux.HandleFunc("/api/login", corsMiddleware(api.HandleLogin))
mux.HandleFunc("/api/language", corsMiddleware(api.HandleLanguage))
mux.HandleFunc("/api/check-auth", corsMiddleware(api.AuthMiddleware(api.HandleCheckAuth)))
mux.HandleFunc("/api/change-password", corsMiddleware(api.AdminMiddleware(api.HandleAdminPasswordChange)))
mux.HandleFunc("/api/change-username", corsMiddleware(api.AdminMiddleware(api.HandleAdminUsernameChange)))
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)))
mux.HandleFunc("/api/images/toggle", corsMiddleware(api.AdminMiddleware(api.HandleImageToggle)))
mux.HandleFunc("/api/images/enabled", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleEnabledImages))))
mux.HandleFunc("/api/dashboard", corsMiddleware(api.AdminMiddleware(api.HandleDashboard)))
mux.HandleFunc("/api/host-info", corsMiddleware(api.AdminMiddleware(api.HandleHostInfo)))
mux.HandleFunc("/api/host-history", corsMiddleware(api.AdminMiddleware(api.HandleHostHistory)))
mux.HandleFunc("/api/host-report", corsMiddleware(api.AdminMiddleware(api.HandleHostReport)))
mux.HandleFunc("/api/snapshots", corsMiddleware(api.AdminMiddleware(api.HandleSnapshots)))
mux.HandleFunc("/api/routing/ipv4-scan", corsMiddleware(api.AdminMiddleware(api.HandleRoutingIPv4Scan)))
mux.HandleFunc("/api/routing", corsMiddleware(api.AdminMiddleware(api.HandleRouting)))
mux.HandleFunc("/api/storage", corsMiddleware(api.AdminMiddleware(api.HandleStorage)))
mux.HandleFunc("/api/ipv6/status", corsMiddleware(api.AdminMiddleware(api.HandleIPv6Status)))
mux.HandleFunc("/api/tasks", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleTasks))))
mux.HandleFunc("/api/tasks/", corsMiddleware(api.AuthMiddleware(api.AdminMiddleware(api.HandleTaskDelete))))
mux.HandleFunc("/api/task-queue/settings", corsMiddleware(api.AdminMiddleware(api.HandleTaskQueueSettings)))
mux.HandleFunc("/api/batch-create", corsMiddleware(api.AdminMiddleware(api.HandleBatchCreate)))
mux.HandleFunc("/api/batch-action", corsMiddleware(api.AdminMiddleware(api.HandleBatchAction)))
mux.HandleFunc("/api/sub-user/create", corsMiddleware(api.AdminMiddleware(api.HandleSubUserCreate)))
@@ -102,13 +85,68 @@ func setupRoutes(mux *http.ServeMux) {
mux.HandleFunc("/api/security/check", corsMiddleware(api.AdminMiddleware(api.HandleSecurityCheck)))
mux.HandleFunc("/api/security/logs", corsMiddleware(api.AdminMiddleware(api.HandleSecurityLogs)))
mux.HandleFunc("/api/security/summary", corsMiddleware(api.AdminMiddleware(api.HandleContainerSecuritySummary)))
mux.HandleFunc("/api/security/settings", corsMiddleware(api.AdminMiddleware(api.HandleSecuritySettings)))
mux.HandleFunc("/api/ssh-ticket", corsMiddleware(api.AuthMiddleware(api.HandleWebSSHTicket)))
mux.HandleFunc("/api/ssh", api.HandleWebSSH) // WebSocket
mux.HandleFunc("/api/vnc-ticket", corsMiddleware(api.AuthMiddleware(api.HandleVNCTicket)))
mux.HandleFunc("/api/vnc", api.HandleVNCProxy) // WebSocket
// API Key management
mux.HandleFunc("/api/api-keys", corsMiddleware(api.AdminMiddleware(api.HandleApiKeys)))
mux.HandleFunc("/api/api-keys/", corsMiddleware(api.AdminMiddleware(api.HandleApiKeyDelete)))
// Versioned external API routes
mux.HandleFunc("/api/v1/dashboard", corsMiddleware(api.AuthMiddleware(api.HandleDashboard)))
mux.HandleFunc("/api/v1/language", corsMiddleware(api.HandleLanguage))
mux.HandleFunc("/api/v1/containers", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleContainers))))
mux.HandleFunc("/api/v1/containers/list", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleContainerListAlias))))
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)))
mux.HandleFunc("/api/v1/images/toggle", corsMiddleware(api.AuthMiddleware(api.HandleImageToggle)))
mux.HandleFunc("/api/v1/images/enabled", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleEnabledImages))))
mux.HandleFunc("/api/v1/host-info", corsMiddleware(api.AuthMiddleware(api.HandleHostInfo)))
mux.HandleFunc("/api/v1/host-history", corsMiddleware(api.AuthMiddleware(api.HandleHostHistory)))
mux.HandleFunc("/api/v1/host-report", corsMiddleware(api.AuthMiddleware(api.HandleHostReport)))
mux.HandleFunc("/api/v1/snapshots", corsMiddleware(api.AuthMiddleware(api.ScopeMiddleware("snapshot:read", api.HandleSnapshots))))
mux.HandleFunc("/api/v1/routing/ipv4-scan", corsMiddleware(api.AuthMiddleware(api.HandleRoutingIPv4Scan)))
mux.HandleFunc("/api/v1/routing", corsMiddleware(api.AuthMiddleware(api.HandleRouting)))
mux.HandleFunc("/api/v1/storage", corsMiddleware(api.AdminMiddleware(api.HandleStorage)))
mux.HandleFunc("/api/v1/ipv6/status", corsMiddleware(api.AuthMiddleware(api.HandleIPv6Status)))
mux.HandleFunc("/api/v1/tasks", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleTasks))))
mux.HandleFunc("/api/v1/tasks/", corsMiddleware(api.AuthMiddleware(api.HandleTaskDelete)))
mux.HandleFunc("/api/v1/task-queue/settings", corsMiddleware(api.AdminMiddleware(api.HandleTaskQueueSettings)))
mux.HandleFunc("/api/v1/batch-create", corsMiddleware(api.AuthMiddleware(api.HandleBatchCreate)))
mux.HandleFunc("/api/v1/batch-action", corsMiddleware(api.AuthMiddleware(api.HandleBatchAction)))
mux.HandleFunc("/api/v1/sub-user/create", corsMiddleware(api.AuthMiddleware(api.HandleSubUserCreate)))
mux.HandleFunc("/api/v1/sub-users", corsMiddleware(api.AuthMiddleware(api.HandleSubUserList)))
mux.HandleFunc("/api/v1/sub-users/", corsMiddleware(api.AuthMiddleware(api.HandleSubUserAction)))
mux.HandleFunc("/api/v1/audit-logs", corsMiddleware(api.AuthMiddleware(api.HandleAuditLogs)))
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))))
mux.HandleFunc("/api/v1/security/summary", corsMiddleware(api.AuthMiddleware(api.ScopeMiddleware("security:read", api.HandleContainerSecuritySummary))))
mux.HandleFunc("/api/v1/security/settings", corsMiddleware(api.AuthMiddleware(api.HandleSecuritySettings)))
mux.HandleFunc("/api/v1/ssh-ticket", corsMiddleware(api.AuthMiddleware(api.HandleWebSSHTicket)))
mux.HandleFunc("/api/v1/vnc-ticket", corsMiddleware(api.AuthMiddleware(api.HandleVNCTicket)))
mux.HandleFunc("/api/v1/api-keys", corsMiddleware(api.AuthMiddleware(api.HandleApiKeys)))
mux.HandleFunc("/api/v1/api-keys/", corsMiddleware(api.AuthMiddleware(api.HandleApiKeyDelete)))
mux.HandleFunc("/api/v1/swap", corsMiddleware(api.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
api.HandleSwapInfo(w, r)
return
}
api.HandleSwapManage(w, r)
})))
// Version (public)
mux.HandleFunc("/api/version", corsMiddleware(api.HandleVersion))
@@ -146,6 +184,8 @@ func setupRoutes(mux *http.ServeMux) {
func Run() error {
// Use embedded frontend files
webFS = GetEmbeddedFS()
api.StartHostMetricSampler()
api.StartContainerMetricSampler()
mux := http.NewServeMux()
setupRoutes(mux)
@@ -156,9 +196,66 @@ func Run() error {
server := &http.Server{
Addr: addr,
Handler: mux,
Handler: panelAccessMiddleware(mux),
}
if sslEnabled() {
certPath, keyPath, err := config.ResolveSSLConfigPaths(config.AppConfig.SSL)
if err != nil {
return err
}
server.TLSConfig = &tls.Config{
MinVersion: tls.VersionTLS12,
GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
safeCertPath, err := config.ResolveSSLPath(certPath)
if err != nil {
return nil, err
}
safeKeyPath, err := config.ResolveSSLPath(keyPath)
if err != nil {
return nil, err
}
cert, err := tls.LoadX509KeyPair(safeCertPath, safeKeyPath)
if err != nil {
return nil, err
}
return &cert, nil
},
}
log.Printf("CLICD Web Server SSL enabled on https://0.0.0.0:%d", config.AppConfig.Port)
return server.ListenAndServeTLS("", "")
}
return server.ListenAndServe()
}
func sslEnabled() bool {
ssl := config.AppConfig.SSL
if !ssl.Enabled {
return false
}
certPath, keyPath, err := config.ResolveSSLConfigPaths(ssl)
if err != nil {
log.Printf("SSL paths are invalid, falling back to HTTP: %v", err)
return false
}
safeCertPath, err := config.ResolveSSLPath(certPath)
if err != nil {
log.Printf("SSL certificate path is not allowed, falling back to HTTP: %v", err)
return false
}
safeKeyPath, err := config.ResolveSSLPath(keyPath)
if err != nil {
log.Printf("SSL private key path is not allowed, falling back to HTTP: %v", err)
return false
}
if _, err := config.ReadableFileStat(safeCertPath); err != nil {
log.Printf("SSL certificate is not readable, falling back to HTTP: %v", err)
return false
}
if _, err := config.ReadableFileStat(safeKeyPath); err != nil {
log.Printf("SSL private key is not readable, falling back to HTTP: %v", err)
return false
}
return true
}
+1
View File
@@ -0,0 +1 @@

+1 -7
View File
@@ -1,7 +1,7 @@
package version
var (
Version = "1.0.11"
Version = "1.1.28"
Repo = "MengMengCode/CLICD"
)
@@ -11,9 +11,3 @@ func Current() string {
}
return Version
}
+60 -2
View File
@@ -4,7 +4,10 @@ import (
"fmt"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
"syscall"
"clicd/internal/api"
"clicd/internal/cli"
@@ -16,12 +19,15 @@ import (
"golang.org/x/term"
)
var shutdownCaptureOnce sync.Once
func main() {
isTerminal := term.IsTerminal(int(os.Stdin.Fd()))
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
@@ -43,17 +49,30 @@ 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()
// Restore persisted state
api.ConfigureTaskQueue(cfg.TaskConcurrency)
api.RestoreTasks()
api.RestoreLoginLogs()
// Start security scanner
api.InitScanner()
api.StartSSLRenewalMonitor()
// Ensure iptables FORWARD rules allow managed bridge traffic.
lxc.EnsureForwardRules("lxcbr0")
lxc.EnsureForwardRules("virbr0")
lxc.EnsureAllAssignedPublicIPv4s()
// Start expiry scanners (stops expired/over-traffic workloads every 30s)
manager := lxc.NewManager()
@@ -64,6 +83,7 @@ func main() {
// Start usage monitors (computes CPU/network/disk rates every 5s)
manager.StartUsageMonitor()
kvmManager.StartUsageMonitor()
kvmManager.StartNetworkSyncMonitor()
kvmManager.StartIPv6Guard()
// Start scheduled snapshot scanners.
@@ -72,6 +92,8 @@ func main() {
// Clean up stale container configs (LXC dir was deleted but config remains)
config.CleanStaleContainers()
api.StartHostBootRestore()
lxc.EnsureAllRunningPortMappings()
// Pre-warm SSH for containers already running after host boot or service restart.
manager.StartSSHWarmupScanner()
@@ -93,6 +115,17 @@ func main() {
}
}
func installShutdownStateCapture() {
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-signals
fmt.Fprintf(os.Stderr, "Received %s, capturing workload restore state...\n", sig)
shutdownCaptureOnce.Do(api.CaptureRuntimeRestoreState)
os.Exit(0)
}()
}
func isWebPanelSystemdRunning() bool {
cmd := exec.Command("systemctl", "is-active", "clicd")
output, err := cmd.Output()
@@ -105,8 +138,33 @@ func isWebPanelSystemdRunning() bool {
func startWebPanelSystemd() {
cmd := exec.Command("systemctl", "start", "clicd")
if err := cmd.Run(); err != nil {
fmt.Fprintf(os.Stderr, "警告: 自动启动 Web 面板失败: %v\n", err)
fmt.Fprintf(os.Stderr, "%s: %v\n", mainT("警告: 自动启动 Web 面板失败"), err)
} else {
fmt.Println("Web 面板已自动启动")
fmt.Println(mainT("Web 面板已自动启动"))
}
}
func mainT(text string) string {
if !mainEnglish() {
return text
}
switch text {
case "警告: 自动启动 Web 面板失败":
return "Warning: failed to auto-start web panel"
case "Web 面板已自动启动":
return "Web panel auto-started"
default:
return text
}
}
func mainEnglish() bool {
lang := strings.ToLower(strings.TrimSpace(os.Getenv("CLICD_LANG")))
if lang == "en" || strings.HasPrefix(lang, "en_") || strings.HasPrefix(lang, "en-") {
return true
}
if lang == "zh" || strings.HasPrefix(lang, "zh_") || strings.HasPrefix(lang, "zh-") {
return false
}
return config.AppConfig != nil && config.NormalizeLanguage(config.AppConfig.Language) == "en"
}
+41 -3
View File
@@ -6,6 +6,7 @@ set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD_DIR="$SCRIPT_DIR/build"
DIST_DIR="$SCRIPT_DIR/dist"
FRONTEND_DIR="$SCRIPT_DIR/frontend"
BACKEND_DIR="$SCRIPT_DIR/backend"
WEB_DIR="$SCRIPT_DIR/web"
@@ -17,9 +18,11 @@ echo "====================================="
# Clean previous build
rm -rf "$BUILD_DIR"
rm -rf "$DIST_DIR"
rm -rf "$WEB_DIR"
rm -rf "$EMBED_WEB_DIR"
mkdir -p "$BUILD_DIR"
mkdir -p "$DIST_DIR"
mkdir -p "$WEB_DIR"
mkdir -p "$EMBED_WEB_DIR"
touch "$EMBED_WEB_DIR/.gitkeep"
@@ -51,9 +54,26 @@ cd "$BACKEND_DIR"
go mod tidy
go mod download
# Build for Linux amd64
BUILD_VERSION="${CLICD_VERSION:-dev}"
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags="-s -w -X clicd/internal/version.Version=${BUILD_VERSION}" -o "$BUILD_DIR/clicd" .
TARGET_GOOS="${CLICD_GOOS:-linux}"
TARGET_GOARCH="${CLICD_GOARCH:-amd64}"
case "$TARGET_GOARCH" in
all) TARGET_GOARCH_LIST="amd64 arm64" ;;
amd64|arm64) TARGET_GOARCH_LIST="$TARGET_GOARCH" ;;
*)
echo "Unsupported CLICD_GOARCH: $TARGET_GOARCH (expected amd64, arm64, or all)" >&2
exit 2
;;
esac
for arch in $TARGET_GOARCH_LIST; do
echo "Target: ${TARGET_GOOS}/${arch}"
GOOS="$TARGET_GOOS" GOARCH="$arch" CGO_ENABLED=0 go build -ldflags="-s -w -X clicd/internal/version.Version=${BUILD_VERSION}" -o "$BUILD_DIR/clicd-linux-${arch}" .
done
first_arch="${TARGET_GOARCH_LIST%% *}"
cp "$BUILD_DIR/clicd-linux-${first_arch}" "$BUILD_DIR/clicd"
echo "Go backend built successfully"
@@ -62,7 +82,20 @@ echo ""
echo "[3/3] Packaging..."
cp -r "$WEB_DIR" "$BUILD_DIR/web"
cp "$SCRIPT_DIR/install.sh" "$BUILD_DIR/install.sh" 2>/dev/null || true
chmod +x "$BUILD_DIR/clicd"
chmod +x "$BUILD_DIR"/clicd*
for arch in $TARGET_GOARCH_LIST; do
asset_dir="clicd-linux-${arch}"
package_root="$BUILD_DIR/package-${arch}"
rm -rf "$package_root"
mkdir -p "$package_root/$asset_dir"
cp "$BUILD_DIR/clicd-linux-${arch}" "$package_root/$asset_dir/clicd"
cp "$BUILD_DIR/install.sh" "$package_root/$asset_dir/install.sh" 2>/dev/null || true
chmod +x "$package_root/$asset_dir/clicd"
[ ! -f "$package_root/$asset_dir/install.sh" ] || chmod +x "$package_root/$asset_dir/install.sh"
tar -C "$package_root" -czf "$DIST_DIR/${asset_dir}.tar.gz" "$asset_dir"
cp "$BUILD_DIR/clicd-linux-${arch}" "$DIST_DIR/${asset_dir}"
done
echo ""
echo "====================================="
@@ -70,6 +103,11 @@ echo " Build Complete!"
echo "====================================="
echo " Output: $BUILD_DIR/clicd"
echo " Web: $BUILD_DIR/web/"
echo " Dist: $DIST_DIR/"
for arch in $TARGET_GOARCH_LIST; do
echo " dist/clicd-linux-${arch}"
echo " dist/clicd-linux-${arch}.tar.gz"
done
echo ""
echo " To deploy:"
echo " 1. Copy build/ directory to server"
+4
View File
@@ -0,0 +1,4 @@
node_modules/
.vitepress/cache/
.vitepress/dist/
.vitepress/.temp/
+170
View File
@@ -0,0 +1,170 @@
import { defineConfig } from 'vitepress'
const zhNav = [
{ text: '指南', link: '/guide/introduction' },
{ text: '功能', link: '/features/dashboard' },
{ text: '运维', link: '/operations/deployment' },
{ text: '开发', link: '/developer/architecture' },
]
const enNav = [
{ text: 'Guide', link: '/en/guide/introduction' },
{ text: 'Features', link: '/en/features/dashboard' },
{ text: 'Operations', link: '/en/operations/deployment' },
{ text: 'Developer', link: '/en/developer/architecture' },
]
const zhSidebar = [
{
text: '开始',
items: [
{ text: '项目介绍', link: '/guide/introduction' },
{ text: '安装', link: '/guide/installation' },
{ text: '升级', link: '/guide/upgrade' },
{ text: '快速上手', link: '/guide/quick-start' },
{ text: '配置说明', link: '/guide/configuration' },
],
},
{
text: '功能',
items: [
{ text: '控制面板', link: '/features/dashboard' },
{ text: '容器管理', link: '/features/containers' },
{ text: '镜像管理', link: '/features/images' },
{ text: '网络与路由', link: '/features/networking' },
{ text: '快照管理', link: '/features/snapshots' },
{ text: '安全告警', link: '/features/security' },
{ text: '子用户', link: '/features/sub-users' },
{ text: 'API 集成', link: '/features/api' },
{ text: '主机报告', link: '/features/host-report' },
],
},
{
text: '运维',
items: [
{ text: '部署建议', link: '/operations/deployment' },
{ text: '故障排查', link: '/operations/troubleshooting' },
{ text: '常见问题', link: '/operations/faq' },
],
},
{
text: '开发',
items: [
{ text: '系统架构', link: '/developer/architecture' },
{ text: '本地构建', link: '/developer/build' },
{ text: '发布流程', link: '/developer/release' },
],
},
]
const enSidebar = [
{
text: 'Get Started',
items: [
{ text: 'Introduction', link: '/en/guide/introduction' },
{ text: 'Installation', link: '/en/guide/installation' },
{ text: 'Upgrade', link: '/en/guide/upgrade' },
{ text: 'Quick Start', link: '/en/guide/quick-start' },
{ text: 'Configuration', link: '/en/guide/configuration' },
],
},
{
text: 'Features',
items: [
{ text: 'Dashboard', link: '/en/features/dashboard' },
{ text: 'Containers', link: '/en/features/containers' },
{ text: 'Images', link: '/en/features/images' },
{ text: 'Networking & Routing', link: '/en/features/networking' },
{ text: 'Snapshots', link: '/en/features/snapshots' },
{ text: 'Security Alerts', link: '/en/features/security' },
{ text: 'Sub-users', link: '/en/features/sub-users' },
{ text: 'API Integration', link: '/en/features/api' },
{ text: 'Host Report', link: '/en/features/host-report' },
],
},
{
text: 'Operations',
items: [
{ text: 'Deployment', link: '/en/operations/deployment' },
{ text: 'Troubleshooting', link: '/en/operations/troubleshooting' },
{ text: 'FAQ', link: '/en/operations/faq' },
],
},
{
text: 'Developer',
items: [
{ text: 'Architecture', link: '/en/developer/architecture' },
{ text: 'Local Build', link: '/en/developer/build' },
{ text: 'Release Process', link: '/en/developer/release' },
],
},
]
export default defineConfig({
title: 'CLICD',
description: '面向 LXC/KVM 的轻量虚拟化管理面板文档',
lang: 'zh-CN',
base: process.env.VITEPRESS_BASE || '/',
cleanUrls: true,
ignoreDeadLinks: true,
head: [
['link', { rel: 'icon', href: '/favicon.svg' }],
],
vite: {
esbuild: {
supported: {
destructuring: true,
},
},
},
locales: {
root: {
label: '简体中文',
lang: 'zh-CN',
description: '面向 LXC/KVM 的轻量虚拟化管理面板文档',
themeConfig: {
nav: zhNav,
sidebar: zhSidebar,
outline: {
label: '页面导航',
},
darkModeSwitchLabel: '外观',
sidebarMenuLabel: '菜单',
returnToTopLabel: '返回顶部',
},
},
en: {
label: 'English',
lang: 'en-US',
link: '/en/',
description: 'Documentation for the lightweight LXC/KVM virtualization management panel.',
themeConfig: {
nav: enNav,
sidebar: enSidebar,
outline: {
label: 'On This Page',
},
darkModeSwitchLabel: 'Appearance',
sidebarMenuLabel: 'Menu',
returnToTopLabel: 'Return to Top',
footer: {
message: 'CLICD documentation for deployment, usage, operations, and integration.',
copyright: 'Copyright © CLICD contributors',
},
},
},
},
themeConfig: {
logo: '/favicon.svg',
search: {
provider: 'local',
},
socialLinks: [
{ icon: 'github', link: 'https://github.com/MengMengCode/CLICD' },
],
footer: {
message: 'CLICD 文档面向部署、使用、运维和二次开发场景。',
copyright: 'Copyright © CLICD contributors',
},
},
})
+26
View File
@@ -0,0 +1,26 @@
:root {
--vp-c-brand-1: #0284c7;
--vp-c-brand-2: #0ea5e9;
--vp-c-brand-3: #7dd3fc;
--vp-c-brand-soft: rgba(14, 165, 233, 0.14);
--vp-home-hero-name-color: #0369a1;
--vp-home-hero-image-background-image: linear-gradient(135deg, #7dd3fc 0%, #38bdf8 46%, #86efac 100%);
--vp-home-hero-image-filter: blur(46px);
}
.dark {
--vp-c-brand-1: #7dd3fc;
--vp-c-brand-2: #38bdf8;
--vp-c-brand-3: #0ea5e9;
--vp-c-brand-soft: rgba(125, 211, 252, 0.16);
--vp-home-hero-name-color: #bae6fd;
}
.VPHomeHero .text {
max-width: 680px;
}
.vp-doc table {
display: table;
width: 100%;
}
+4
View File
@@ -0,0 +1,4 @@
import DefaultTheme from 'vitepress/theme'
import './custom.css'
export default DefaultTheme
+42
View File
@@ -0,0 +1,42 @@
# 系统架构
CLICD 由 Go 后端、React 前端和宿主机虚拟化能力组成。
## 后端
后端入口在 `backend/main.go`HTTP 服务路由集中在 `backend/internal/server/server.go`。主要模块:
- `internal/api`Web 面板和 `/api/v1` 的 HTTP 接口。
- `internal/config`:配置和 SQLite 存储。
- `internal/lxc`LXC 容器管理。
- `internal/kvm`KVM/libvirt 虚拟机管理。
- `internal/cli`:命令行管理入口。
- `internal/server`:静态前端嵌入和 HTTP 服务。
- `internal/version`:版本号。
## 前端
前端入口在 `frontend/src/main.tsx`,页面位于 `frontend/src/pages`,通用组件位于 `frontend/src/components`
主要页面:
- 控制面板:`Dashboard.tsx`
- 容器列表:`Containers.tsx`
- 容器详情:`ContainerDetail.tsx`
- 镜像管理:`ImageManagement.tsx`
- 安全告警:`Security.tsx`
- 快照管理:`Snapshots.tsx`
- 路由管理:`Routing.tsx`
- API 集成:`ApiIntegration.tsx`
- 主机报告:`HostReport.tsx`
- 子用户管理:`SubUserManagement.tsx`
## 前端嵌入
生产构建时,前端产物会放入 `backend/internal/server/web`,后端通过 Go embed 提供静态文件,并对非 API 路由返回 SPA 入口。
## 接口分层
- `/api/*`Web 面板和兼容接口。
- `/api/v1/*`:推荐给外部自动化系统使用的版本化接口。
- WebSSH 和 WebVNC 使用短期票据后建立 WebSocket 连接。
+61
View File
@@ -0,0 +1,61 @@
# 本地构建
## 前端构建
```bash
cd frontend
npm install
npm run build
```
构建输出位于 `frontend/dist`
## 后端构建
```bash
cd backend
go test ./...
go build -o ../build/clicd .
```
如果要打包嵌入式 Web 面板,需要先把前端构建产物同步到后端嵌入目录。
## 一键构建
项目根目录提供了构建脚本:
```bash
bash build.sh
```
该脚本用于串联前端构建、静态资源同步和 Go 二进制构建。
默认目标为 Linux amd64。需要构建 ARM64 包时可以指定:
```bash
CLICD_GOARCH=arm64 bash build.sh
```
需要同时构建 amd64 和 arm64 发布包时:
```bash
CLICD_GOARCH=all bash build.sh
```
构建完成后会生成:
- `dist/clicd-linux-amd64`
- `dist/clicd-linux-amd64.tar.gz`
- `dist/clicd-linux-arm64`
- `dist/clicd-linux-arm64.tar.gz`
## 文档站构建
```bash
cd docs
npm install
npm run dev
npm run build
```
`npm run dev` 用于本地预览,`npm run build` 用于生成静态文档。
+46
View File
@@ -0,0 +1,46 @@
# 发布流程
CLICD 的安装和升级依赖 GitHub Release 产物。发布时建议使用语义化版本标签,例如 `v1.1.6`
## 版本号
版本号需要同步检查:
- `backend/internal/version/version.go`
- `frontend/package.json`
- Release 标签。
## Release 产物
安装脚本会按宿主架构优先下载 Linux AMD64 或 ARM64 产物:
```text
clicd-linux-amd64.tar.gz
clicd-linux-arm64.tar.gz
```
在部分场景中也会尝试下载单独二进制:
```text
clicd-linux-amd64
clicd-linux-arm64
```
## 安装脚本行为
- `CLICD_VERSION=latest`:使用 GitHub `releases/latest`
- `CLICD_VERSION=vX.Y.Z`:下载指定标签的 Release 产物。
示例:
```bash
CLICD_VERSION=v1.1.6 sh install.sh
```
## 发布后验证
- 安装脚本可以下载新版本。
- `systemctl status clicd` 正常。
- `/api/version` 返回新版本。
- Web 面板可以加载前端资源。
- 容器列表、任务队列、API Key 页面可以正常打开。
+42
View File
@@ -0,0 +1,42 @@
# Architecture
CLICD consists of a Go backend, a React frontend, and host virtualization capabilities.
## Backend
The backend entry point is `backend/main.go`, and HTTP routes are centralized in `backend/internal/server/server.go`. Main modules:
- `internal/api`: HTTP APIs for the web panel and `/api/v1`.
- `internal/config`: configuration and SQLite storage.
- `internal/lxc`: LXC container management.
- `internal/kvm`: KVM/libvirt virtual machine management.
- `internal/cli`: command-line management entry point.
- `internal/server`: embedded frontend assets and HTTP service.
- `internal/version`: version number.
## Frontend
The frontend entry point is `frontend/src/main.tsx`. Pages live in `frontend/src/pages`, and shared components live in `frontend/src/components`.
Main pages:
- Dashboard: `Dashboard.tsx`
- Container list: `Containers.tsx`
- Container details: `ContainerDetail.tsx`
- Image Management: `ImageManagement.tsx`
- Security Alerts: `Security.tsx`
- Snapshot Management: `Snapshots.tsx`
- Routing Management: `Routing.tsx`
- API Integration: `ApiIntegration.tsx`
- Host Report: `HostReport.tsx`
- Sub-user Management: `SubUserManagement.tsx`
## Frontend Embedding
For production builds, frontend artifacts are placed in `backend/internal/server/web`. The backend serves them through Go embed and returns the SPA entry for non-API routes.
## API Layers
- `/api/*`: web panel and compatibility APIs.
- `/api/v1/*`: versioned APIs recommended for external automation.
- WebSSH and WebVNC use short-lived tickets before opening WebSocket connections.
+61
View File
@@ -0,0 +1,61 @@
# Local Build
## Frontend Build
```bash
cd frontend
npm install
npm run build
```
Build output is written to `frontend/dist`.
## Backend Build
```bash
cd backend
go test ./...
go build -o ../build/clicd .
```
To package the embedded web panel, sync the frontend build output into the backend embed directory first.
## One-command Build
The project root provides a build script:
```bash
bash build.sh
```
The script chains frontend build, static asset sync, and Go binary build.
The default target is Linux amd64. To build an ARM64 package, set:
```bash
CLICD_GOARCH=arm64 bash build.sh
```
To build both amd64 and arm64 release assets at once:
```bash
CLICD_GOARCH=all bash build.sh
```
The build writes:
- `dist/clicd-linux-amd64`
- `dist/clicd-linux-amd64.tar.gz`
- `dist/clicd-linux-arm64`
- `dist/clicd-linux-arm64.tar.gz`
## Docs Build
```bash
cd docs
npm install
npm run dev
npm run build
```
`npm run dev` starts a local preview, and `npm run build` generates static documentation.
+46
View File
@@ -0,0 +1,46 @@
# Release Process
CLICD installation and upgrade rely on GitHub Release artifacts. Use semantic version tags such as `v1.1.6`.
## Version Number
Check the version in:
- `backend/internal/version/version.go`
- `frontend/package.json`
- Release tag.
## Release Artifacts
The installer first tries to download the Linux AMD64 or ARM64 archive for the host architecture:
```text
clicd-linux-amd64.tar.gz
clicd-linux-arm64.tar.gz
```
In some cases, it may also try the standalone binary:
```text
clicd-linux-amd64
clicd-linux-arm64
```
## Installer Behavior
- `CLICD_VERSION=latest`: use GitHub `releases/latest`.
- `CLICD_VERSION=vX.Y.Z`: download artifacts from the specified release tag.
Example:
```bash
CLICD_VERSION=v1.1.6 sh install.sh
```
## Post-release Verification
- The installer can download the new version.
- `systemctl status clicd` is healthy.
- `/api/version` returns the new version.
- The web panel can load frontend assets.
- Container list, task queue, and API Key pages open correctly.
+880
View File
@@ -0,0 +1,880 @@
# API Integration
CLICD remains compatible with legacy `/api` endpoints, so existing integrations do not need to change. New integrations should use `/api/v1`; the list below is all v1, and the recommended container list endpoint is `GET /api/v1/containers`.
## Authentication
API keys can be created and managed from the API Integration page. Requests support either of these headers:
```bash
curl -H "X-API-Key: YOUR_API_KEY" https://panel.example.com/api/v1/containers
```
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" https://panel.example.com/api/v1/dashboard
```
## Response Shape
All APIs use the same response envelope:
```json
{
"success": true,
"message": "OK",
"data": {}
}
```
Integrations should read only the business fields they need. New capabilities are added as optional fields where possible, without requiring existing plugins to rename current fields.
## Creation and Reinstall
Container creation, batch creation, reinstall, and batch reinstall support mixed NAT, public IPv4, IPv6 networking, plus Linux SSH login configuration. Public IPv4/IPv6 pools can be viewed with `GET /api/v1/routing` and updated with `PUT /api/v1/routing`.
Create container example:
```json
{
"name": "demo-lxc-01",
"virtualization": "lxc",
"template_id": "debian-bookworm",
"vcpu": 1,
"ram_mb": 512,
"disk_gb": 10,
"assign_nat": true,
"port_mapping_count": 2,
"assign_ipv4": false,
"ipv4_count": 1,
"public_ipv4s": [],
"assign_ipv6": true,
"ipv6_count": 1,
"ipv6_addresses": [],
"ssh_auth_mode": "auto_password",
"ssh_password": "",
"ssh_public_key": "",
"expires_at": "",
"network_down_mbps": 100,
"network_up_mbps": 50,
"io_read_mbps": 120,
"io_write_mbps": 80
}
```
Field notes:
| Field | Description |
| --- | --- |
| `assign_nat` | Whether to allocate NAT port mappings. If omitted, default NAT behavior is preserved. |
| `assign_ipv4` | Whether to allocate public IPv4. |
| `ipv4_count` | Number of public IPv4 addresses to allocate automatically. |
| `public_ipv4s` | Explicit public IPv4 address list. |
| `assign_ipv6` | Whether to allocate IPv6. |
| `ipv6_count` | Number of IPv6 addresses to allocate automatically. |
| `ipv6_addresses` | Explicit IPv6 address list. |
| `ssh_auth_mode` | Linux creation supports `auto_password`, `password`, and `key`; reinstall also supports `keep`. |
| `ssh_password` | Custom password for `password` mode. It must be 8-64 characters, include letters and digits, and contain no whitespace. |
| `ssh_public_key` | One-line SSH public key for `key` mode. |
| `network_down_mbps` | Optional container download/downlink bandwidth limit in Mbps. `0` means unlimited. |
| `network_up_mbps` | Optional container upload/uplink bandwidth limit in Mbps. `0` means unlimited. |
| `io_read_mbps` | Optional disk read limit in MB/s. `0` means unlimited. |
| `io_write_mbps` | Optional disk write limit in MB/s. `0` means unlimited. |
| `network_bw_mbps` | Legacy-compatible field. Sets symmetric downlink/uplink bandwidth; new integrations should prefer the split fields. |
| `io_speed_mbps` | Legacy-compatible field. Sets symmetric read/write I/O limits; new integrations should prefer the split fields. |
Reinstall example:
```json
{
"template_id": "debian-bookworm",
"ssh_auth_mode": "keep",
"ssh_password": "",
"ssh_public_key": ""
}
```
`keep` is only for reinstall and keeps the current SSH password. Windows KVM images ignore Linux SSH public key fields.
## Resource and Traffic Limits
`PUT /api/v1/containers/{id}/resource-limit` supports partial updates. Fields omitted from the request remain unchanged.
```json
{
"vcpu": 2,
"ram_mb": 1024,
"network_down_mbps": 100,
"network_up_mbps": 50,
"io_read_mbps": 120,
"io_write_mbps": 80
}
```
Legacy `network_bw_mbps` and `io_speed_mbps` are still accepted. They mean symmetric downlink/uplink bandwidth and symmetric read/write I/O limits. New integrations should use the split fields to control download/upload and read/write independently.
`PUT /api/v1/containers/{id}/traffic-limit` request body:
```json
{
"traffic_mode": "total",
"monthly_traffic_gb": 1024,
"traffic_in_gb": 0,
"traffic_out_gb": 0
}
```
| Field | Description |
| --- | --- |
| `traffic_mode` | Traffic limit mode. Common values are `total` for a shared total limit and `split` for separate inbound/outbound limits. |
| `monthly_traffic_gb` | Monthly total traffic quota for `total` mode, in GB. `0` means unlimited. |
| `traffic_in_gb` | Monthly inbound quota for `split` mode, in GB. `0` means unlimited. |
| `traffic_out_gb` | Monthly outbound quota for `split` mode, in GB. `0` means unlimited. |
## Container Firewall
Read container firewall settings with `GET /api/v1/containers/{id}/firewall` and update them with `PUT /api/v1/containers/{id}/firewall`. Updates are applied immediately when the container is running.
Update example:
```json
{
"enabled": true,
"default_action": "DROP",
"rules": [
{
"direction": "in",
"protocol": "tcp",
"action": "ACCEPT",
"network": "ipv4",
"source_ip": "203.0.113.0/24",
"port": "22,80,443",
"description": "allow admin and web"
}
]
}
```
| Field | Description |
| --- | --- |
| `enabled` | Whether the container firewall is enabled. |
| `default_action` | Default action: `ACCEPT` or `DROP`. |
| `rules[].id` | Optional. Omit for new rules and the backend will generate one. |
| `rules[].direction` | Direction: `in` or `out`. |
| `rules[].protocol` | Protocol: `tcp`, `udp`, `icmp`, or `all`. |
| `rules[].action` | Action: `ACCEPT` or `DROP`. |
| `rules[].network` | Network type: `ipv4`, `ipv6`, or `all`. |
| `rules[].source_ip` | Optional source IP, CIDR, or address range. |
| `rules[].port` | Optional. Supported only for `tcp`/`udp`; examples: `22`, `80,443`, or `8000-9000`. |
| `rules[].description` | Optional note. |
## API Key Create and Update
`POST /api/v1/api-keys` and `PATCH /api/v1/api-keys/{id}` use the same field shape. `name` is required when creating a key; updates overwrite the fields you send.
```json
{
"name": "Automation",
"ip_whitelist": "198.51.100.23,203.0.113.0/24",
"scopes": ["dashboard:read", "container:read", "container:power"],
"expires_at": "2026-12-31 23:59:59",
"disabled": false,
"container_uuids": ["00000000-0000-4000-8000-000000000005"]
}
```
| Field | Description |
| --- | --- |
| `name` | API key name. Required when creating a key. |
| `ip_whitelist` | Optional allowed source IPs/CIDRs, comma-separated. Empty means no IP restriction. |
| `scopes` | Optional permission scopes. If omitted, the default read-only scopes are used. `*` grants all permissions. |
| `expires_at` | Optional expiration time. Empty means no expiration. |
| `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:
```python
import requests
BASE_URL = "https://panel.example.com"
API_KEY = "YOUR_API_KEY"
session = requests.Session()
session.headers.update({
"X-API-Key": API_KEY,
"Content-Type": "application/json",
})
resp = session.get(f"{BASE_URL}/api/v1/containers", timeout=15)
resp.raise_for_status()
print(resp.json())
```
Create a port mapping:
```python
import requests
BASE_URL = "https://panel.example.com"
API_KEY = "YOUR_API_KEY"
CONTAINER_ID = "example-vm"
payload = {
"protocol": "tcp",
"host_port": 18080,
"container_port": 80,
"description": "web",
}
resp = requests.post(
f"{BASE_URL}/api/v1/containers/{CONTAINER_ID}/port-mappings",
headers={"X-API-Key": API_KEY},
json=payload,
timeout=15,
)
resp.raise_for_status()
print(resp.json())
```
## Endpoint List
### Overview
| Method | Path | Description |
| --- | --- | --- |
| GET | `/api/v1/dashboard` | Dashboard statistics |
| GET | `/api/v1/host-info` | Host resources |
| GET | `/api/v1/host-report` | Host inspection report |
| GET | `/api/v1/routing` | NAT/IPv4/IPv6 routing |
| PUT | `/api/v1/routing` | Update public IPv4/IPv6 pools |
| POST | `/api/v1/routing/ipv4-scan` | Scan a public IPv4 segment |
| GET | `/api/v1/ipv6/status` | IPv6 status |
| GET | `/api/v1/tasks` | Task queue |
| DELETE | `/api/v1/tasks/{task_id}` | Delete a task |
### Containers
| Method | Path | Description |
| --- | --- | --- |
| GET | `/api/v1/containers` | Container list (recommended) |
| GET | `/api/v1/containers/list` | Compatible GET form for container list |
| POST | `/api/v1/containers/list` | Compatible POST form for container list |
| POST | `/api/v1/containers` | Create container |
| GET | `/api/v1/containers/{id\|uuid\|name}` | Container details |
| POST | `/api/v1/containers/{id}/start` | Start |
| POST | `/api/v1/containers/{id}/stop` | Stop |
| POST | `/api/v1/containers/{id}/restart` | Restart |
| POST | `/api/v1/containers/{id}/reinstall` | Reinstall |
| DELETE | `/api/v1/containers/{id}/delete` | Delete |
| GET | `/api/v1/containers/{id}/usage` | Resource usage |
| GET | `/api/v1/containers/{id}/traffic` | Traffic statistics |
| POST | `/api/v1/containers/{id}/traffic-reset` | Reset traffic |
| PUT | `/api/v1/containers/{id}/traffic-limit` | Update traffic limits |
| PUT | `/api/v1/containers/{id}/resource-limit` | Update resource limits |
| PUT | `/api/v1/containers/{id}/expiry` | Update expiration time |
| POST | `/api/v1/containers/{id}/reset-password` | Reset SSH password |
| POST | `/api/v1/containers/{id}/ipv6` | Assign IPv6 |
### Ports and Snapshots
| Method | Path | Description |
| --- | --- | --- |
| GET | `/api/v1/containers/{id}/random-port` | Random available port; accepts `host_ip` to check a specific host IP |
| POST | `/api/v1/containers/{id}/port-mappings` | Add port mapping |
| PUT | `/api/v1/containers/{id}/port-mappings/{index}` | Update port mapping |
| DELETE | `/api/v1/containers/{id}/port-mappings/{index}` | Delete port mapping |
| GET | `/api/v1/containers/{id}/firewall` | Get container firewall settings |
| PUT | `/api/v1/containers/{id}/firewall` | Update container firewall settings |
| GET | `/api/v1/snapshots` | Snapshot overview |
| GET | `/api/v1/containers/{id}/snapshots` | Container snapshots |
| POST | `/api/v1/containers/{id}/snapshots` | Create snapshot |
| DELETE | `/api/v1/containers/{id}/snapshots/{snapshot_id}` | Delete snapshot |
| POST | `/api/v1/containers/{id}/snapshots/{snapshot_id}/restore` | Restore snapshot |
| POST | `/api/v1/containers/{id}/snapshots/schedule` | Schedule snapshots |
| PUT | `/api/v1/containers/{id}/snapshots/quota` | Snapshot quota |
### Platform Management
| Method | Path | Description |
| --- | --- | --- |
| 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 |
| PUT | `/api/v1/images/toggle` | Enable or disable image |
| GET | `/api/v1/security/alerts` | Security alerts |
| POST | `/api/v1/security/check` | Run security check |
| GET | `/api/v1/security/logs?container={name}` | Security connection logs |
| GET | `/api/v1/security/summary` | Security summary |
| GET | `/api/v1/security/settings` | Security settings |
| PUT | `/api/v1/security/settings` | Update security settings |
| GET | `/api/v1/swap` | Swap information |
| POST | `/api/v1/swap` | Adjust Swap |
| GET | `/api/v1/language` | Current panel language |
| POST/PUT | `/api/v1/language` | Update panel language |
| GET | `/api/v1/ssl` | SSL settings (requires admin permission / `admin:access`) |
| PUT | `/api/v1/ssl` | Update SSL settings (requires admin permission / `admin:access`) |
| GET | `/api/v1/webssh-origins` | WebSSH Origin allowlist (requires admin permission / `admin:access`) |
| PUT | `/api/v1/webssh-origins` | Update WebSSH Origin allowlist (requires admin permission / `admin:access`) |
| POST | `/api/v1/batch-create` | Batch create containers |
| POST | `/api/v1/batch-action` | Batch power action, delete, or reinstall |
| POST | `/api/v1/ssh-ticket` | Create WebSSH ticket |
| POST | `/api/v1/vnc-ticket` | Create WebVNC ticket |
### Accounts and Logs
| Method | Path | Description |
| --- | --- | --- |
| POST | `/api/v1/sub-user/create` | Create sub-user link |
| GET | `/api/v1/sub-users` | Sub-user list |
| POST | `/api/v1/sub-users/{id}/rotate-password` | Rotate sub-user password |
| GET | `/api/v1/sub-users/{id}/audit-logs` | Sub-user audit logs |
| GET | `/api/v1/sub-users/{id}/login-logs` | Sub-user login logs |
| GET | `/api/v1/audit-logs` | Audit logs |
| GET | `/api/v1/login-logs` | Login logs |
| GET | `/api/v1/api-keys` | API key list |
| POST | `/api/v1/api-keys` | Create API key |
| PATCH | `/api/v1/api-keys/{id}` | Update API key |
| DELETE | `/api/v1/api-keys/{id}` | Delete API key |
## Response Samples
The samples below are grouped by endpoint path. Resource numbers, task IDs, container IDs, timestamps, IP addresses, and keys will differ in real environments. Passwords, tickets, and API keys are masked.
### Overview
```json
{
"GET /api/v1/dashboard": {
"success": true,
"data": {
"running": 31,
"stopped": 0,
"total_containers": 31
}
},
"GET /api/v1/host-info": {
"success": true,
"data": {
"cpu": { "cores": 8, "usage_pct": 1.16 },
"ram": { "total_mb": 31825, "used_mb": 1275, "free_mb": 30550 },
"disk": { "total_gb": 1750.49, "used_gb": 123.98, "free_gb": 1626.51 },
"network": {
"public_ipv4": "203.0.113.10",
"public_ipv4_interface": "eth0",
"public_ipv6": "2001:db8:100::2",
"public_ipv6_interface": "eth0"
},
"load": { "load1": 0.01, "load5": 0.03, "load15": 0.01 }
}
},
"GET /api/v1/host-report": {
"success": true,
"data": {
"generated_at": "2026-06-12 10:00:00",
"summary": { "status": "ok", "warnings": 0 },
"host": { "hostname": "node-1", "kernel": "6.8.0" },
"resources": { "cpu_cores": 8, "ram_total_mb": 31825, "disk_total_gb": 1750.49 },
"network": { "public_ipv4": "203.0.113.10", "public_ipv6": "2001:db8:100::2" }
}
},
"GET /api/v1/routing": {
"success": true,
"data": {
"nat4": { "used": 62, "remaining": "45474", "total": "45536" },
"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" }
],
"ipv4_assignments": [
{ "container_id": 5, "container_name": "example-vm", "address": "203.0.113.10", "interface": "eth0", "prefix_len": 32, "gateway": "203.0.113.1" }
],
"nat4_mappings": [
{ "container_id": 5, "container_name": "example-vm", "status": "running", "ip": "10.0.0.10", "host_port": 22004, "container_port": 22, "protocol": "tcp" }
],
"ipv6_assignments": [
{ "container_id": 5, "container_name": "example-vm", "address": "2001:db8:100::1005", "prefix_len": 64, "interface": "eth0" }
]
}
},
"PUT /api/v1/routing": {
"success": true,
"data": {
"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" }
]
}
},
"POST /api/v1/routing/ipv4-scan": {
"success": true,
"data": [
{ "address": "203.0.113.10", "interface": "eth0", "prefix_len": 32, "gateway": "203.0.113.1", "status": "available", "usable": true, "reason": "" }
]
},
"GET /api/v1/ipv6/status": {
"success": true,
"data": {
"available": true,
"reachable": true,
"reason": "usable public IPv6 prefix detected",
"prefixes": [
{ "interface": "eth0", "address": "2001:db8:100::2", "prefix": "2001:db8:100::/64", "prefix_len": 64, "gateway": "2001:db8:100::1" }
]
}
},
"GET /api/v1/tasks": {
"success": true,
"data": []
},
"DELETE /api/v1/tasks/{task_id}": {
"success": true,
"message": "Task deleted"
}
}
```
### Containers
```json
{
"GET /api/v1/containers": {
"success": true,
"data": [
{
"id": 5,
"uuid": "00000000-0000-4000-8000-000000000005",
"name": "example-vm",
"virtualization": "lxc",
"template": "debian-bullseye",
"vcpu": 1,
"ram_mb": 512,
"disk_gb": 10,
"network_down_mbps": 100,
"network_up_mbps": 50,
"io_read_mbps": 120,
"io_write_mbps": 80,
"status": "running",
"ip": "10.0.0.10",
"ipv6": "2001:db8:100::1005",
"ssh_port": 22004,
"ssh_password": "***",
"port_mappings": [
{ "container_port": 22, "host_port": 22004, "protocol": "tcp", "description": "SSH" },
{ "container_port": 20000, "host_port": 20000, "protocol": "tcp", "description": "Port-20000" }
]
}
]
},
"GET /api/v1/containers/list": {
"success": true,
"data": [
{ "id": 5, "uuid": "00000000-0000-4000-8000-000000000005", "name": "example-vm", "status": "running", "ip": "10.0.0.10" }
]
},
"POST /api/v1/containers/list": {
"success": true,
"data": [
{ "id": 5, "uuid": "00000000-0000-4000-8000-000000000005", "name": "example-vm", "status": "running", "ip": "10.0.0.10" }
]
},
"POST /api/v1/containers": {
"success": true,
"message": "Container created successfully"
},
"GET /api/v1/containers/{id|uuid|name}": {
"success": true,
"data": {
"id": 5,
"uuid": "00000000-0000-4000-8000-000000000005",
"name": "example-vm",
"status": "running",
"ip": "10.0.0.10",
"ipv6": "2001:db8:100::1005",
"ssh_port": 22004,
"ssh_password": "***",
"policy_blocked": false
}
},
"POST /api/v1/containers/{id}/start": {
"success": true,
"message": "Task queued",
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "start" }
},
"POST /api/v1/containers/{id}/stop": {
"success": true,
"message": "Task queued",
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "stop" }
},
"POST /api/v1/containers/{id}/restart": {
"success": true,
"message": "Task queued",
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "restart" }
},
"POST /api/v1/containers/{id}/reinstall": {
"success": true,
"message": "Task queued",
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "reinstall" }
},
"DELETE /api/v1/containers/{id}/delete": {
"success": true,
"message": "Task queued",
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "delete" }
},
"GET /api/v1/containers/{id}/usage": {
"success": true,
"data": {
"cpu_usage_pct": 0,
"cpu_usage_usec": 3908852,
"memory_usage_bytes": 29331456,
"disk_usage_bytes": 515100672,
"network_rx_bytes": 131232,
"network_tx_bytes": 16828,
"load1": 0.1,
"load5": 0.06,
"load15": 0.01
}
},
"GET /api/v1/containers/{id}/traffic": {
"success": true,
"data": {
"mode": "total",
"limit_gb": 1024,
"in_limit_gb": 0,
"out_limit_gb": 0,
"total_used_bytes": 142082,
"rx_used_bytes": 127212,
"tx_used_bytes": 14870,
"used_pct": 0,
"reset_date": "2026-06"
}
},
"POST /api/v1/containers/{id}/traffic-reset": {
"success": true,
"message": "Traffic reset"
},
"PUT /api/v1/containers/{id}/traffic-limit": {
"success": true,
"message": "Traffic limit updated"
},
"PUT /api/v1/containers/{id}/resource-limit": {
"success": true,
"message": "Resource limits updated"
},
"PUT /api/v1/containers/{id}/expiry": {
"success": true,
"message": "Expiry updated"
},
"POST /api/v1/containers/{id}/reset-password": {
"success": true,
"message": "SSH password reset successfully",
"data": { "password": "***" }
},
"POST /api/v1/containers/{id}/ipv6": {
"success": true,
"message": "IPv6 assigned",
"data": { "id": 5, "name": "example-vm", "ipv6": "2001:db8:100::1005" }
}
}
```
### Ports and Snapshots
```json
{
"GET /api/v1/containers/{id}/random-port?host_ip=203.0.113.10": {
"success": true,
"data": { "port": 61320 }
},
"POST /api/v1/containers/{id}/port-mappings": {
"success": true,
"data": [
{ "container_port": 22, "host_port": 22004, "protocol": "tcp", "description": "SSH" },
{ "container_port": 8080, "host_port": 61320, "protocol": "tcp", "description": "HTTP" }
]
},
"PUT /api/v1/containers/{id}/port-mappings/{index}": {
"success": true,
"data": [
{ "container_port": 8081, "host_port": 61320, "protocol": "tcp", "description": "HTTP" }
]
},
"DELETE /api/v1/containers/{id}/port-mappings/{index}": {
"success": true,
"data": []
},
"GET /api/v1/containers/{id}/firewall": {
"success": true,
"data": {
"enabled": true,
"default_action": "DROP",
"rules": [
{ "id": "a1b2c3d4", "direction": "in", "protocol": "tcp", "action": "ACCEPT", "network": "ipv4", "source_ip": "203.0.113.0/24", "port": "22,80,443", "description": "allow admin and web" }
]
}
},
"PUT /api/v1/containers/{id}/firewall": {
"success": true,
"message": "Firewall updated",
"data": { "enabled": true, "default_action": "DROP", "rules": [] }
},
"GET /api/v1/snapshots": {
"success": true,
"data": null
},
"GET /api/v1/containers/{id}/snapshots": {
"success": true,
"data": {
"quota": 1,
"schedule": { "enabled": false, "interval_hours": 0, "last_run": "", "next_run": "", "time": "", "created_by": "" },
"snapshots": []
}
},
"POST /api/v1/containers/{id}/snapshots": {
"success": true,
"data": {
"id": "snap-20260608-001",
"container_id": 5,
"container_name": "example-vm",
"created_at": "2026-06-08 16:00:00",
"created_by": "api:Automation",
"scheduled": false,
"size_bytes": 10485760
}
},
"DELETE /api/v1/containers/{id}/snapshots/{snapshot_id}": {
"success": true,
"message": "Snapshot deleted"
},
"POST /api/v1/containers/{id}/snapshots/{snapshot_id}/restore": {
"success": true,
"message": "Snapshot restored"
},
"POST /api/v1/containers/{id}/snapshots/schedule": {
"success": true,
"data": {
"container": { "id": 5, "name": "example-vm", "snapshot_schedule_enabled": true, "snapshot_schedule_interval_hours": 24, "snapshot_schedule_time": "03:00" }
}
},
"PUT /api/v1/containers/{id}/snapshots/quota": {
"success": true,
"data": {
"quota": 2,
"container": { "id": 5, "name": "example-vm", "snapshot_limit": 2 }
}
}
}
```
### Platform Management
```json
{
"GET /api/v1/templates": {
"success": true,
"data": [
{ "id": "ubuntu-noble", "name": "Ubuntu 24.04", "distro": "ubuntu", "release": "noble", "arch": "amd64", "description": "Ubuntu 24.04 LTS" },
{ "id": "debian-bookworm", "name": "Debian 12", "distro": "debian", "release": "bookworm", "arch": "amd64", "description": "Debian 12 (Bookworm)" }
]
},
"GET /api/v1/images": {
"success": true,
"data": [
{ "id": "ubuntu-noble", "name": "Ubuntu 24.04", "type": "lxc", "downloaded": true, "enabled": true, "downloading": false, "progress": 0, "size_bytes": 135005452 }
]
},
"GET /api/v1/images/enabled?type=lxc": {
"success": true,
"data": [
{ "id": "ubuntu-noble", "name": "Ubuntu 24.04", "distro": "ubuntu", "release": "noble", "arch": "amd64", "variant": "default", "description": "Ubuntu 24.04 LTS", "type": "lxc" }
]
},
"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"
},
"PUT /api/v1/images/toggle": {
"success": true,
"message": "OK"
},
"GET /api/v1/security/alerts": {
"success": true,
"data": []
},
"POST /api/v1/security/check": {
"success": true,
"message": "Security check completed"
},
"GET /api/v1/security/logs?container={name}": {
"success": true,
"data": []
},
"GET /api/v1/security/summary": {
"success": true,
"data": { "critical": 0, "high": 0, "medium": 0, "low": 0, "total_alerts": 0 }
},
"GET /api/v1/security/settings": {
"success": true,
"data": { "auto_shutdown": false }
},
"PUT /api/v1/security/settings": {
"success": true,
"data": { "auto_shutdown": false }
},
"GET /api/v1/swap": {
"success": true,
"data": { "total_mb": 16383, "used_mb": 0, "free_mb": 16383, "enabled": true, "swap_file": "/swapfile" }
},
"POST /api/v1/swap": {
"success": true,
"message": "SWAP adjusted to 16384 MB",
"data": { "total_mb": 16383, "used_mb": 0, "free_mb": 16383, "enabled": true, "swap_file": "/swapfile" }
},
"GET /api/v1/language": {
"success": true,
"data": { "language": "zh" }
},
"PUT /api/v1/language": {
"success": true,
"data": { "language": "en" }
},
"GET /api/v1/ssl": {
"success": true,
"data": { "enabled": true, "mode": "self-signed", "target": "panel.example.com", "detected_host": "panel.example.com", "needs_restart": false }
},
"PUT /api/v1/ssl": {
"success": true,
"message": "SSL settings saved",
"data": { "enabled": true, "mode": "self-signed", "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" }
},
"POST /api/v1/batch-create": {
"success": true,
"data": ["task-12"]
},
"POST /api/v1/batch-action": {
"success": true,
"data": ["task-13"]
},
"POST /api/v1/ssh-ticket": {
"success": true,
"data": { "ticket": "***60 seconds valid***" }
},
"POST /api/v1/vnc-ticket": {
"success": true,
"data": { "ticket": "***60 seconds valid***" }
}
}
```
### Accounts and Logs
```json
{
"POST /api/v1/sub-user/create": {
"success": true,
"message": "Sub-user created",
"data": {
"id": "sub-xxxxxxxx",
"username": "user-xxxxxxxx",
"password": "***",
"container_names": ["example-vm"],
"access_code": "********",
"created_at": "2026-06-08 16:00:00"
}
},
"GET /api/v1/sub-users": {
"success": true,
"data": []
},
"POST /api/v1/sub-users/{id}/rotate-password": {
"success": true,
"data": { "username": "user-xxxxxxxx", "password": "***", "access_code": "********" }
},
"GET /api/v1/sub-users/{id}/audit-logs": {
"success": true,
"data": []
},
"GET /api/v1/sub-users/{id}/login-logs": {
"success": true,
"data": []
},
"GET /api/v1/audit-logs": {
"success": true,
"data": [
{ "time": "2026-06-08 15:44:40", "action": "apikey.create", "target": "Test", "detail": "scopes=*", "user": "admin", "success": true }
]
},
"GET /api/v1/login-logs": {
"success": true,
"data": [
{ "time": "2026-06-08 08:24:00 UTC", "username": "admin", "ip": "198.51.100.23", "user_agent": "Mozilla/5.0 ...", "success": true }
]
},
"GET /api/v1/api-keys": {
"success": true,
"data": [
{ "id": "c271023f", "name": "Test", "prefix": "clicd_sk_dd9d...", "ip_whitelist": "", "created_at": "2026-06-08 15:44:40", "last_used": "2026-06-08 15:46:10", "scopes": ["*"], "expires_at": "", "disabled": false, "container_uuids": [], "last_used_ip": "198.51.100.23" }
]
},
"POST /api/v1/api-keys": {
"success": true,
"message": "API key created. Save this key now - it won't be shown again.",
"data": { "id": "a1b2c3d4", "name": "Automation", "key": "clicd_sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "prefix": "clicd_sk_xxxx...", "ip_whitelist": "198.51.100.23", "scopes": ["dashboard:read", "container:read"], "expires_at": "2026-12-31 23:59:59", "disabled": false, "container_uuids": ["00000000-0000-4000-8000-000000000005"] }
},
"PATCH /api/v1/api-keys/{id}": {
"success": true,
"data": { "id": "a1b2c3d4", "name": "Automation", "prefix": "clicd_sk_xxxx...", "scopes": ["dashboard:read", "container:read"], "expires_at": "2026-12-31 23:59:59", "disabled": false, "container_uuids": ["00000000-0000-4000-8000-000000000005"] }
},
"DELETE /api/v1/api-keys/{id}": {
"success": true,
"message": "API key deleted"
}
}
```
+83
View File
@@ -0,0 +1,83 @@
# Container Management
Container Management is the core CLICD module. It covers creation, lifecycle operations, resource limits, network mappings, traffic statistics, password resets, and console access.
## Container List
The list page scans container status. Administrators can view all containers. Sub-users only see containers within their authorization scope.
Common fields include:
- ID, UUID, and name.
- Virtualization type.
- Runtime status.
- IP and IPv6.
- CPU, memory, and disk limits.
- Traffic usage and traffic limits.
- Expiration time.
## Create Containers
Creation requires a template and resource quotas. Batch creation is available from the panel or API and is useful for issuing multiple containers at once.
```http
POST /api/v1/containers
POST /api/v1/batch-create
```
Linux containers and Linux KVM virtual machines support SSH login configuration during creation:
- `auto_password`: generate a root SSH password automatically.
- `password`: use a custom `ssh_password`.
- `key`: write a one-line `ssh_public_key`; a password is still kept for WebSSH.
Network allocation can combine NAT, public IPv4, and IPv6 as needed. API fields such as `assign_nat`, `assign_ipv4`, `public_ipv4s`, `assign_ipv6`, and `ipv6_addresses` are optional. If they are omitted, default behavior is preserved.
## Lifecycle Operations
```http
POST /api/v1/containers/{id}/start
POST /api/v1/containers/{id}/stop
POST /api/v1/containers/{id}/restart
POST /api/v1/containers/{id}/reinstall
DELETE /api/v1/containers/{id}/delete
```
Start, stop, reinstall, and delete actions enter the task queue. Call `GET /api/v1/tasks` afterwards to check execution status.
When reinstalling a Linux system, you may pass `ssh_auth_mode`, `ssh_password`, and `ssh_public_key`. `ssh_auth_mode=keep` keeps the current SSH password. If these fields are omitted, the old behavior is preserved.
## Resources and Traffic
The container details page supports resource usage, traffic limit changes, resource limit changes, and expiration changes.
```http
GET /api/v1/containers/{id}/usage
GET /api/v1/containers/{id}/traffic
POST /api/v1/containers/{id}/traffic-reset
PUT /api/v1/containers/{id}/traffic-limit
PUT /api/v1/containers/{id}/resource-limit
PUT /api/v1/containers/{id}/expiry
```
## NAT Port Management
The NAT port management section supports adding, editing, and deleting mappings. Add and edit actions use a dialog so name, protocol, external port, and internal port can be filled in together.
```http
GET /api/v1/containers/{id}/random-port
POST /api/v1/containers/{id}/port-mappings
PUT /api/v1/containers/{id}/port-mappings/{index}
DELETE /api/v1/containers/{id}/port-mappings/{index}
```
In sub-user mode, administrators can limit sub-users to changing only the internal port, preventing changes to the host-facing port and protocol.
## Remote Console
```http
POST /api/v1/ssh-ticket
POST /api/v1/vnc-ticket
```
Tickets are short-lived. Use them immediately for WebSSH or WebVNC and do not persist them.
+27
View File
@@ -0,0 +1,27 @@
# Dashboard
The dashboard shows the overall state of the host and virtualization resources.
## Metrics
- Total containers, running containers, and stopped containers.
- CPU, memory, disk, and Swap overview.
- Entry points for host network and routing status.
- Task queue status.
- Security alert summary.
## Related APIs
```http
GET /api/v1/dashboard
GET /api/v1/host-info
GET /api/v1/routing
GET /api/v1/ipv6/status
GET /api/v1/tasks
```
API requests must include an API key:
```bash
curl -H "X-API-Key: YOUR_API_KEY" https://panel.example.com/api/v1/dashboard
```
+21
View File
@@ -0,0 +1,21 @@
# Host Report
The host report summarizes the host runtime environment, resource status, and virtualization dependencies. It is useful for post-installation checks, troubleshooting, or sharing environment information with maintainers.
## Contents
- System version and kernel information.
- CPU, memory, disk, and Swap.
- Network status.
- LXC/KVM dependency status.
- CLICD service status.
## Related APIs
```http
GET /api/v1/host-report
GET /api/v1/host-info
GET /api/v1/swap
```
Before sending a report externally, check whether it contains public IPs, private networks, usernames, keys, tickets, or business domains.
+29
View File
@@ -0,0 +1,29 @@
# Image Management
Image Management maintains templates used to create containers or virtual machines.
## Supported Template Types
The project includes common Linux distribution templates such as Debian, Ubuntu, Alpine, CentOS, Fedora, Arch Linux, and Rocky Linux. KVM templates use the corresponding distribution cloud image resources.
## Management Actions
```http
GET /api/v1/templates
GET /api/v1/images
POST /api/v1/images/download
POST /api/v1/images/cancel
DELETE /api/v1/images/delete
PUT /api/v1/images/toggle
```
- `templates` returns available template definitions.
- `images` returns local image status.
- `download` downloads a specific template.
- `cancel` cancels a download task.
- `delete` removes the local image cache.
- `toggle` controls whether a template can be used during creation.
## Windows Images
This project does not distribute Windows system images and does not provide features to bypass or avoid Windows activation. Windows download links should point to official Microsoft resources, and users must obtain valid licenses themselves.
+61
View File
@@ -0,0 +1,61 @@
# Networking and Routing
CLICD provides NAT4 port mapping, random available ports, public IPv4 assignment, IPv6 status checks, and IPv6 assignment. During container creation, you can use NAT only, public IPv4 only, IPv6 only, or a mixed network setup.
## NAT4
NAT4 forwards host ports to container internal ports. Common uses include:
- Forwarding SSH.
- Exposing web services.
- Assigning fixed external ports to sub-users.
Port mappings include:
| Field | Description |
| --- | --- |
| Name | A purpose label such as `ssh` or `web`. |
| Protocol | `tcp` or `udp`. |
| External port | The host port exposed to the outside. |
| Internal port | The service port inside the container. |
## IPv6
IPv6 assignment requires the host to have a routable IPv6 prefix, plus correct routing, neighbor discovery, or proxy configuration.
```http
GET /api/v1/ipv6/status
POST /api/v1/containers/{id}/ipv6
```
If the host has no public IPv6 or the upstream network is not routing the prefix correctly, assigned addresses will not be reachable from the public internet.
## Public IPv4
Public IPv4 assignment selects from public IPv4 addresses detected on the host, or from `public_ipv4s` specified through the API. Creation fields include:
| Field | Description |
| --- | --- |
| `assign_nat` | Whether to enable NAT port mappings. |
| `assign_ipv4` | Whether to assign public IPv4. |
| `ipv4_count` | Number of public IPv4 addresses to allocate automatically. |
| `public_ipv4s` | Explicit public IPv4 address list. |
| `assign_ipv6` | Whether to assign IPv6. |
| `ipv6_count` | Number of IPv6 addresses to allocate automatically. |
| `ipv6_addresses` | Explicit IPv6 address list. |
Public address pool APIs:
```http
GET /api/v1/routing
PUT /api/v1/routing
POST /api/v1/routing/ipv4-scan
```
## Routing Status
```http
GET /api/v1/routing
```
This endpoint shows runtime status for NAT, IPv4, IPv6, and port capacity.
+31
View File
@@ -0,0 +1,31 @@
# Security Alerts
CLICD includes lightweight security alerts based on connection behavior. It does not keep full normal connection logs; it focuses on abnormal behavior and high-risk patterns.
## Covered Scenarios
- Port scanning.
- Lateral scanning.
- Brute-force tendencies.
- SMTP abuse.
- UDP reflection risk.
- Suspicious ports related to mining, proxies, VPNs, Tor, and similar services.
## APIs
```http
GET /api/v1/security/alerts
POST /api/v1/security/check
GET /api/v1/security/logs?container={name}
GET /api/v1/security/summary
GET /api/v1/security/settings
PUT /api/v1/security/settings
```
## Automatic Shutdown
Security settings can enable automatic shutdown after alerts. Before enabling it, observe for a while and make sure the rules do not affect normal services.
## Logging Advice
Security alerts are risk signals. They should not replace a professional firewall, intrusion detection, or centralized logging system. For public services, still combine them with security groups, firewall rules, Fail2ban, and similar tools.

Some files were not shown because too many files have changed in this diff Show More