Compare commits
366 Commits
b1937d42a2
...
20250409
| Author | SHA1 | Date | |
|---|---|---|---|
| 3c636406af | |||
| 578f1432a0 | |||
| f403c85f0a | |||
| db25c7e426 | |||
| 98b67534cb | |||
| 09d3cf08f3 | |||
| 9b3d32811f | |||
| 26d391ea96 | |||
| c044996014 | |||
| 34b04968b2 | |||
| c44a3f2673 | |||
| e46adcd1da | |||
| d1506f26ab | |||
| 23194d13d2 | |||
| 131dec892d | |||
| c2e6105aff | |||
| f5202f596d | |||
| 3bf8859ff9 | |||
| 9a905e83f7 | |||
| 4b9df95721 | |||
| e14f51ef7e | |||
| 5d49ce17a6 | |||
| e5753d2b26 | |||
| e9e3103938 | |||
| 44188975ca | |||
| 3f8d4e78d8 | |||
| 1c01a3b1ac | |||
| a5c40255c7 | |||
| 6080bd83b5 | |||
| 8cb9d8bb32 | |||
| 3c613e40bf | |||
| 7fed9e2324 | |||
| afe7aab751 | |||
| accd4776cb | |||
| 6aabab866c | |||
| 4981a41a0a | |||
| 9daced06e4 | |||
| 8299065eb2 | |||
| 67549d54a3 | |||
| c0690d888e | |||
| ed9fd097e9 | |||
| 3c8de8279b | |||
| 6d8ce34e4a | |||
| 7c7df3bdde | |||
| d9767d1011 | |||
| 136dfbbea0 | |||
| 7c8a1e06af | |||
| 296e7da865 | |||
| 0f84db322a | |||
| 70ca59d96f | |||
| 0669493d9b | |||
| ef38125277 | |||
| 4107e7f77c | |||
| f3c6b85827 | |||
| cf31ab6ecd | |||
| 76a4506a62 | |||
| c16f805df6 | |||
| 7ad8b42609 | |||
| b139dfdfee | |||
| 72c559bf10 | |||
| 9b6a813c6f | |||
| 0830d81b3d | |||
| 3ed64003d3 | |||
| 6f1e707c2f | |||
| 300efe5367 | |||
| 375ce6ca7e | |||
| 8eff09a607 | |||
| 0885def533 | |||
| 48b1bc3185 | |||
| 99533fabf4 | |||
| 88a1c7a96a | |||
| 38ac6e575b | |||
| 51010fdea3 | |||
| 9b6704c39b | |||
| 8de0718650 | |||
| 10b1355c2c | |||
| ec56af6a8e | |||
| 0549eb04d7 | |||
| dd49c692b1 | |||
| 024360ac65 | |||
| c2f04e41f3 | |||
| b8d2c6ef5a | |||
| a7b4a132cd | |||
| 94c9057a12 | |||
| e7bc32d38f | |||
| a8d0520ec5 | |||
| 63d13f4c27 | |||
| 0c8d37033a | |||
| fd604e2869 | |||
| 990057be0d | |||
| d65ebdcb0f | |||
| cd7252b864 | |||
| 284f9d3a94 | |||
| 98f26c2bf7 | |||
| d7db6a56d3 | |||
| 8389c026fa | |||
| 6cb5b37c23 | |||
| 058c2a4abb | |||
| 839a7d271b | |||
| d53c5d45cf | |||
| be4fa6f0d7 | |||
| deced2492f | |||
| 0eb6567eb8 | |||
| 2c40d50435 | |||
| 5c5c54bbd7 | |||
| 772e14cc3d | |||
| a2802647f2 | |||
| 79b2db0987 | |||
| 9cbbcc3bea | |||
| f4571af3c5 | |||
| 5808589cf8 | |||
| 48e4d9a84d | |||
| 5ee1abde46 | |||
| aca1c69f32 | |||
| 19f71e7d68 | |||
| 7583b547c2 | |||
| f67201eaa9 | |||
| ba7129b67f | |||
| 0642e2910e | |||
| e5968f2444 | |||
| 1bbdbcbbaf | |||
| 5a85e9a91f | |||
| 20342a5cc9 | |||
| 4259327fbf | |||
| 9cdd0920a4 | |||
| feb52889c1 | |||
| 70ef1a3717 | |||
| b13712a430 | |||
| 8e350d4c60 | |||
| 824d9ba4ff | |||
| 5da98d3d12 | |||
| a77faafdf7 | |||
| 61f4dab638 | |||
| 66fd3954c7 | |||
| 772e2270c4 | |||
| 2955dfa5c0 | |||
| 48e9c1d42f | |||
| 044b7d0de4 | |||
| a969248744 | |||
| 7d046e607d | |||
| ee77bd11c9 | |||
| 821021e66f | |||
| 68bd5a6c67 | |||
| e49e69de88 | |||
| a3f9ad17c0 | |||
| b943691d18 | |||
| bc051ee678 | |||
| c7a2d1af23 | |||
| 93fbb31273 | |||
| b4eb6f7ea4 | |||
| 00ff6f0b50 | |||
| 324042f956 | |||
| e466d03ec5 | |||
| 89ba09f872 | |||
| a322c46ca4 | |||
| 0915a3e2d9 | |||
| 07eceaf72f | |||
| 0e1396e177 | |||
| e59f21984f | |||
| 8c508acd32 | |||
| 26e7af7675 | |||
| 2fadf53dea | |||
| 2b58ce4d5e | |||
| 9755bacc55 | |||
| 8b16ce0c5d | |||
| 20e6d7931e | |||
| c908d00c62 | |||
| 55b49699eb | |||
| 91fe291341 | |||
| eec6bbb598 | |||
| d2243fa1c2 | |||
| 6e7dd7c1c4 | |||
| e40e15287b | |||
| 800969b9cc | |||
| 5917068add | |||
| 9b14d62830 | |||
| 25503a688b | |||
| 868adc6cee | |||
| 528e30f3dc | |||
| cc42d20e67 | |||
| d189470539 | |||
| 6fdd9f91fa | |||
| 69c2d12fcd | |||
| 174e4a2c79 | |||
| 847ab20a63 | |||
| 09c32a5555 | |||
| 220c943642 | |||
| e5d709c34f | |||
| 1e359a3b8e | |||
| dbff6358db | |||
| d5c05a0cdd | |||
| 1d24d2a84c | |||
| d35dac2de8 | |||
| 01141f77e2 | |||
| 56f765a15a | |||
| 639b7f4b38 | |||
| babda3acd1 | |||
| 197b72cad0 | |||
| 1910c7081b | |||
| eda0fc80b0 | |||
| f6e5356109 | |||
| 11da25b4c0 | |||
| 2599032581 | |||
| ed58d60e84 | |||
| a126e76eef | |||
| c472dfe807 | |||
| c883f13bf8 | |||
| b320f0b326 | |||
| 9812120ed6 | |||
| 9ebd3b0315 | |||
| 24afa12be2 | |||
| 310689312c | |||
| e7f4bc44e7 | |||
| 165937f88b | |||
| a5d81de62b | |||
| ba2b3494cf | |||
| 1944415371 | |||
| 4130fdda1c | |||
| e4ef4c43bd | |||
| afdf639d9b | |||
| f2d6b9a5dd | |||
| e3b61baf11 | |||
| 20732860cf | |||
| 7f14ab8a54 | |||
| 87d4c5b0fd | |||
| 0f58f82e52 | |||
| 16b73a2030 | |||
| a32954785d | |||
| 2789fc299f | |||
| 0257ecba0b | |||
| 17fc64b1fe | |||
| fbc818b5f3 | |||
| a4292795d1 | |||
| 529e16c0c7 | |||
| e1adc1456f | |||
| f1f4a88ae3 | |||
| 8fdbb0f442 | |||
| 9efb1b29df | |||
| 2c07f5f121 | |||
| 953f6fdcf2 | |||
| d66e384137 | |||
| 80bf70502f | |||
| 7f6cf26617 | |||
| c9cf39bb76 | |||
| 93afb646ca | |||
| 4b358acbde | |||
| b97dbc8149 | |||
| e1292ae922 | |||
| 3e812b5530 | |||
| b1e268bf63 | |||
| 887c4608b4 | |||
| 49e33cfd57 | |||
| 842733caa3 | |||
| b6b56fdba8 | |||
| 8163d5e52f | |||
| 7aca0aee13 | |||
| 39fc34ef26 | |||
| be06339bd7 | |||
| 00c1047734 | |||
| a6c54ada50 | |||
| 8803c6755b | |||
| cdab9df5c1 | |||
| 75b8c1d9e9 | |||
| 557fb7d97b | |||
| bb85e58008 | |||
| b8c1375f4f | |||
| a96f6f33df | |||
| a55061a2cd | |||
| e6d3dd926c | |||
| 95dc089943 | |||
| dafef923f0 | |||
| 5095a701eb | |||
| a157484105 | |||
| 0e4bf4414c | |||
| 0a2a9d66e1 | |||
| c4ff5d0621 | |||
| ff1391694d | |||
| 368ae4e89d | |||
| a539c092f5 | |||
| dbf44e6204 | |||
| 448b029c17 | |||
| f06082ce82 | |||
| 272763bdc3 | |||
| 1dd2dfc684 | |||
| b5cb76cd7d | |||
| 4f7161ae9e | |||
| f3d184e06d | |||
| 12404cc9a0 | |||
| 0eabdec559 | |||
| 8646837035 | |||
| a164c6adb5 | |||
| 7de2c01418 | |||
| 7f11076f45 | |||
| 3f32aab8bd | |||
| 275e706ee5 | |||
| 7608a7cb18 | |||
| e6293e3015 | |||
| a44bc0a4fc | |||
| a2221b0903 | |||
| 6ab4111182 | |||
| 8fb044b61d | |||
| 06ec35e1e7 | |||
| e94b08827c | |||
| 5d1ab3be67 | |||
| 383b29ce21 | |||
| 85c9e0f4c6 | |||
| 7e3c105d78 | |||
| 6a3f1f40f9 | |||
| b33c660c3e | |||
| cd04e04d34 | |||
| 7dfbed0186 | |||
| 3dbefc8d84 | |||
| 077b385c0f | |||
| 3f203966d4 | |||
| 0ab8b23de4 | |||
| a18787efcb | |||
| 68465270bf | |||
| b88eb08ec2 | |||
| 8995b5e874 | |||
| 9fe4c67aa0 | |||
| d6e2a10e59 | |||
| 03c7dbc357 | |||
| 27f33038a9 | |||
| 57b0957d3e | |||
| 2174ececd1 | |||
| a61b38b4d3 | |||
| ea84ebdda7 | |||
| a972ea51aa | |||
| f89a4f4481 | |||
| 0e07ca6bd3 | |||
| aaba9f2f80 | |||
| 0ba70330db | |||
| bb55ec4cfe | |||
| 90f8b46c84 | |||
| 51b34131d2 | |||
| 06374dc5ea | |||
| 151c1fc157 | |||
| 696b09f508 | |||
| 270fe60c1d | |||
| 50a224c9f6 | |||
| 2efe5877a4 | |||
| c1de6d9621 | |||
| 2ae2717a5b | |||
| 0a25dc5730 | |||
| 1d6d6e6796 | |||
| 4e8b79deca | |||
| 0ddc4362a0 | |||
| 9d423e3443 | |||
| 1c3d3d57a4 | |||
| edbfe53d1a | |||
| 81c1044bae | |||
| 3777d73c50 | |||
| 9365e9afdf | |||
| 9d738285ab | |||
| c7de64cc02 | |||
| 149e3f4d72 | |||
| f1ba3bc5ab | |||
| cea123f5b0 | |||
| 927414dbaf | |||
| 2ac16fd1cb | |||
| 59c64e4633 | |||
| 74924cff88 | |||
| f0328a8912 | |||
| afc1b5cca6 | |||
| b0ca64b2ff | |||
| d8e5aa17f3 |
28
.drone.yml
28
.drone.yml
@@ -5,13 +5,14 @@ name: default
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: web_build
|
- name: web_build
|
||||||
image: node:21
|
image: node:23
|
||||||
volumes:
|
volumes:
|
||||||
- name: web_app
|
- name: web_app
|
||||||
path: /tmp/web_build
|
path: /tmp/web_build
|
||||||
commands:
|
commands:
|
||||||
- cd virtweb_frontend
|
- cd virtweb_frontend
|
||||||
- npm install
|
- npm install --legacy-peer-deps # TODO : remove when mui-file-input is updated
|
||||||
|
- npm run lint
|
||||||
- npm run build
|
- npm run build
|
||||||
- mv dist /tmp/web_build
|
- mv dist /tmp/web_build
|
||||||
|
|
||||||
@@ -25,6 +26,7 @@ steps:
|
|||||||
- rustup component add clippy
|
- rustup component add clippy
|
||||||
- cd virtweb_backend
|
- cd virtweb_backend
|
||||||
- cargo clippy -- -D warnings
|
- cargo clippy -- -D warnings
|
||||||
|
- cargo clippy --examples -- -D warnings
|
||||||
- cargo test
|
- cargo test
|
||||||
|
|
||||||
- name: backend_compile
|
- name: backend_compile
|
||||||
@@ -34,6 +36,8 @@ steps:
|
|||||||
path: /usr/local/cargo/registry
|
path: /usr/local/cargo/registry
|
||||||
- name: web_app
|
- name: web_app
|
||||||
path: /tmp/web_build
|
path: /tmp/web_build
|
||||||
|
- name: release
|
||||||
|
path: /tmp/release
|
||||||
depends_on:
|
depends_on:
|
||||||
- backend_check
|
- backend_check
|
||||||
- web_build
|
- web_build
|
||||||
@@ -43,10 +47,30 @@ steps:
|
|||||||
- mv /tmp/web_build/dist static
|
- mv /tmp/web_build/dist static
|
||||||
- cargo build --release
|
- cargo build --release
|
||||||
- ls -lah target/release/virtweb_backend
|
- ls -lah target/release/virtweb_backend
|
||||||
|
- cp target/release/virtweb_backend /tmp/release
|
||||||
|
|
||||||
|
- name: gitea_release
|
||||||
|
image: plugins/gitea-release
|
||||||
|
depends_on:
|
||||||
|
- backend_compile
|
||||||
|
when:
|
||||||
|
event:
|
||||||
|
- tag
|
||||||
|
volumes:
|
||||||
|
- name: release
|
||||||
|
path: /tmp/release
|
||||||
|
environment:
|
||||||
|
PLUGIN_API_KEY:
|
||||||
|
from_secret: API_KEY
|
||||||
|
settings:
|
||||||
|
base_url: https://gitea.communiquons.org
|
||||||
|
files: /tmp/release/*
|
||||||
|
checksum: sha512
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
- name: rust_registry
|
- name: rust_registry
|
||||||
temp: {}
|
temp: {}
|
||||||
- name: web_app
|
- name: web_app
|
||||||
temp: {}
|
temp: {}
|
||||||
|
- name: release
|
||||||
|
temp: {}
|
||||||
|
|||||||
15
README.md
15
README.md
@@ -6,3 +6,18 @@ Please refer to this guide: [virtweb_docs/SETUP_DEV.md](virtweb_docs/SETUP_DEV.m
|
|||||||
|
|
||||||
## Production requirements
|
## Production requirements
|
||||||
Please refer to this guide: [virtweb_docs/SETUP_PROD.md](virtweb_docs/SETUP_PROD.md)
|
Please refer to this guide: [virtweb_docs/SETUP_PROD.md](virtweb_docs/SETUP_PROD.md)
|
||||||
|
|
||||||
|
## Features
|
||||||
|
* Only Qemu / KVM is supported!
|
||||||
|
* Basic auth / OpenID auth
|
||||||
|
* Create, update & delete VM
|
||||||
|
* noVNC control of VMs
|
||||||
|
* Start, stop, suspend, resume, reset & kill VMs
|
||||||
|
* Create, update & delete networks
|
||||||
|
* Start & stop networks
|
||||||
|
* Create, update & delete network filters
|
||||||
|
* Upload ISO for easy VM installation
|
||||||
|
* API tokens for system interconnection
|
||||||
|
|
||||||
|
## Screenshot
|
||||||
|

|
||||||
|
|||||||
@@ -1,9 +1,3 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
"extends": ["local>renovate/presets"]
|
||||||
"packageRules": [
|
|
||||||
{
|
|
||||||
"matchUpdateTypes": ["major", "minor", "patch"],
|
|
||||||
"automerge": true
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
2268
virtweb_backend/Cargo.lock
generated
2268
virtweb_backend/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,47 +1,48 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "virtweb_backend"
|
name = "virtweb_backend"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2024"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
log = "0.4.21"
|
log = "0.4.27"
|
||||||
env_logger = "0.11.3"
|
env_logger = "0.11.7"
|
||||||
clap = { version = "4.5.4", features = ["derive", "env"] }
|
clap = { version = "4.5.34", features = ["derive", "env"] }
|
||||||
light-openid = { version = "1.0.2", features = ["crypto-wrapper"] }
|
light-openid = { version = "1.0.4", features = ["crypto-wrapper"] }
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.5.0"
|
||||||
actix = "0.13.3"
|
actix = "0.13.5"
|
||||||
actix-web = "4.5.1"
|
actix-web = "4.10.2"
|
||||||
actix-remote-ip = "0.1.0"
|
actix-remote-ip = "0.1.0"
|
||||||
actix-session = { version = "0.9.0", features = ["cookie-session"] }
|
actix-session = { version = "0.10.1", features = ["cookie-session"] }
|
||||||
actix-identity = "0.7.1"
|
actix-identity = "0.8.0"
|
||||||
actix-cors = "0.7.0"
|
actix-cors = "0.7.1"
|
||||||
actix-files = "0.6.5"
|
actix-files = "0.6.6"
|
||||||
actix-web-actors = "4.3.0"
|
actix-ws = "0.3.0"
|
||||||
actix-http = "3.6.0"
|
actix-http = "3.10.0"
|
||||||
serde = { version = "1.0.197", features = ["derive"] }
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
serde_json = "1.0.115"
|
serde_json = "1.0.140"
|
||||||
quick-xml = { version = "0.31.0", features = ["serialize", "overlapped-lists"] }
|
quick-xml = { version = "0.37.3", features = ["serialize", "overlapped-lists"] }
|
||||||
futures-util = "0.3.30"
|
futures-util = "0.3.31"
|
||||||
anyhow = "1.0.81"
|
anyhow = "1.0.97"
|
||||||
actix-multipart = "0.6.1"
|
actix-multipart = "0.7.2"
|
||||||
tempfile = "3.10.1"
|
tempfile = "3.19.1"
|
||||||
reqwest = { version = "0.12.3", features = ["stream"] }
|
reqwest = { version = "0.12.15", features = ["stream"] }
|
||||||
url = "2.5.0"
|
url = "2.5.4"
|
||||||
virt = "0.3.1"
|
virt = "0.4.2"
|
||||||
sysinfo = { version = "0.30.9", features = ["serde"] }
|
sysinfo = { version = "0.34.2", features = ["serde"] }
|
||||||
uuid = { version = "1.8.0", features = ["v4", "serde"] }
|
uuid = { version = "1.16.0", features = ["v4", "serde"] }
|
||||||
lazy-regex = "3.1.0"
|
lazy-regex = "3.4.1"
|
||||||
thiserror = "1.0.58"
|
thiserror = "2.0.12"
|
||||||
image = "0.25.1"
|
image = "0.25.6"
|
||||||
rand = "0.8.5"
|
rand = "0.9.0"
|
||||||
bytes = "1.6.0"
|
bytes = "1.10.1"
|
||||||
tokio = "1.37.0"
|
tokio = { version = "1.44.1", features = ["rt", "time", "macros"] }
|
||||||
futures = "0.3.30"
|
futures = "0.3.31"
|
||||||
ipnetwork = "0.20.0"
|
ipnetwork = { version = "0.21.1", features = ["serde"] }
|
||||||
num = "0.4.1"
|
num = "0.4.3"
|
||||||
rust-embed = { version = "8.3.0" }
|
rust-embed = { version = "8.6.0" }
|
||||||
mime_guess = "2.0.4"
|
mime_guess = "2.0.5"
|
||||||
dotenvy = "0.15.7"
|
dotenvy = "0.15.7"
|
||||||
nix = { version = "0.28.0", features = ["net"] }
|
nix = { version = "0.29.0", features = ["net"] }
|
||||||
|
basic-jwt = "0.3.0"
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
services:
|
services:
|
||||||
oidc:
|
oidc:
|
||||||
image: qlik/simple-oidc-provider
|
image: dexidp/dex
|
||||||
environment:
|
|
||||||
- REDIRECTS=http://localhost:3000/oidc_cb
|
|
||||||
- PORT=9001
|
|
||||||
ports:
|
ports:
|
||||||
- 9001:9001
|
- 9001:9001
|
||||||
|
volumes:
|
||||||
|
- ./docker/dex:/conf:ro
|
||||||
|
command: [ "dex", "serve", "/conf/dex.config.yaml" ]
|
||||||
27
virtweb_backend/docker/dex/dex.config.yaml
Normal file
27
virtweb_backend/docker/dex/dex.config.yaml
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
issuer: http://127.0.0.1:9001/dex
|
||||||
|
|
||||||
|
storage:
|
||||||
|
type: memory
|
||||||
|
|
||||||
|
web:
|
||||||
|
http: 0.0.0.0:9001
|
||||||
|
|
||||||
|
oauth2:
|
||||||
|
# Automate some clicking
|
||||||
|
# Note: this might actually make some tests pass that otherwise wouldn't.
|
||||||
|
skipApprovalScreen: false
|
||||||
|
|
||||||
|
connectors:
|
||||||
|
# Note: this might actually make some tests pass that otherwise wouldn't.
|
||||||
|
- type: mockCallback
|
||||||
|
id: mock
|
||||||
|
name: Example
|
||||||
|
|
||||||
|
# Basic OP test suite requires two clients.
|
||||||
|
staticClients:
|
||||||
|
- id: foo
|
||||||
|
secret: bar
|
||||||
|
redirectURIs:
|
||||||
|
- http://localhost:3000/oidc_cb
|
||||||
|
- http://localhost:5173/oidc_cb
|
||||||
|
name: Project
|
||||||
67
virtweb_backend/examples/api_curl.rs
Normal file
67
virtweb_backend/examples/api_curl.rs
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
use basic_jwt::JWTPrivateKey;
|
||||||
|
use clap::Parser;
|
||||||
|
use std::os::unix::prelude::CommandExt;
|
||||||
|
use std::process::Command;
|
||||||
|
use std::str::FromStr;
|
||||||
|
use virtweb_backend::api_tokens::TokenVerb;
|
||||||
|
use virtweb_backend::extractors::api_auth_extractor::TokenClaims;
|
||||||
|
use virtweb_backend::utils::time_utils::time;
|
||||||
|
|
||||||
|
/// cURL wrapper to query Virtweb backend API
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(version, about, long_about = None)]
|
||||||
|
struct Args {
|
||||||
|
/// URL of VirtWeb
|
||||||
|
#[arg(short('u'), long, env, default_value = "http://localhost:8000")]
|
||||||
|
virtweb_url: String,
|
||||||
|
|
||||||
|
/// Token ID
|
||||||
|
#[arg(short('i'), long, env)]
|
||||||
|
token_id: String,
|
||||||
|
|
||||||
|
/// Token private key
|
||||||
|
#[arg(short('t'), long, env)]
|
||||||
|
token_key: String,
|
||||||
|
|
||||||
|
/// Request verb
|
||||||
|
#[arg(short('X'), long, default_value = "GET")]
|
||||||
|
verb: String,
|
||||||
|
|
||||||
|
/// Request URI
|
||||||
|
uri: String,
|
||||||
|
|
||||||
|
/// Command line arguments to pass to cURL
|
||||||
|
#[clap(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||||
|
run: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let full_url = format!("{}{}", args.virtweb_url, args.uri);
|
||||||
|
log::debug!("Full URL: {full_url}");
|
||||||
|
|
||||||
|
let key = JWTPrivateKey::ES384 {
|
||||||
|
r#priv: args.token_key,
|
||||||
|
};
|
||||||
|
let claims = TokenClaims {
|
||||||
|
sub: args.token_id.to_string(),
|
||||||
|
iat: time() as usize,
|
||||||
|
exp: time() as usize + 50,
|
||||||
|
verb: TokenVerb::from_str(&args.verb).expect("Invalid request verb!"),
|
||||||
|
path: args.uri,
|
||||||
|
nonce: uuid::Uuid::new_v4().to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let jwt = key.sign_jwt(&claims).expect("Failed to sign JWT!");
|
||||||
|
|
||||||
|
let err = Command::new("curl")
|
||||||
|
.args(["-X", &args.verb])
|
||||||
|
.args(["-H", &format!("x-token-id: {}", args.token_id)])
|
||||||
|
.args(["-H", &format!("x-token-content: {jwt}")])
|
||||||
|
.args(args.run)
|
||||||
|
.arg(full_url)
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
panic!("Failed to run cURL! {err}")
|
||||||
|
}
|
||||||
@@ -31,7 +31,7 @@ impl LibVirtActor {
|
|||||||
"Will connect to hypvervisor at address '{}'",
|
"Will connect to hypvervisor at address '{}'",
|
||||||
hypervisor_uri
|
hypervisor_uri
|
||||||
);
|
);
|
||||||
let conn = Connect::open(hypervisor_uri)?;
|
let conn = Connect::open(Some(hypervisor_uri))?;
|
||||||
|
|
||||||
Ok(Self { m: conn })
|
Ok(Self { m: conn })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
pub mod libvirt_actor;
|
pub mod libvirt_actor;
|
||||||
pub mod vnc_actor;
|
pub mod vnc_handler;
|
||||||
pub mod vnc_tokens_actor;
|
pub mod vnc_tokens_actor;
|
||||||
|
|||||||
@@ -1,209 +0,0 @@
|
|||||||
use actix::{Actor, ActorContext, AsyncContext, Handler, StreamHandler};
|
|
||||||
use actix_http::ws::Item;
|
|
||||||
use actix_web_actors::ws;
|
|
||||||
use actix_web_actors::ws::Message;
|
|
||||||
use bytes::Bytes;
|
|
||||||
use image::EncodableLayout;
|
|
||||||
use std::path::Path;
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
|
||||||
use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf};
|
|
||||||
use tokio::net::UnixStream;
|
|
||||||
|
|
||||||
/// How often heartbeat pings are sent
|
|
||||||
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
|
|
||||||
|
|
||||||
/// How long before lack of client response causes a timeout
|
|
||||||
const CLIENT_TIMEOUT: Duration = Duration::from_secs(20);
|
|
||||||
|
|
||||||
#[derive(thiserror::Error, Debug)]
|
|
||||||
enum VNCError {
|
|
||||||
#[error("Socket file does not exists!")]
|
|
||||||
SocketDoesNotExists,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct VNCActor {
|
|
||||||
/// Qemu -> WS
|
|
||||||
read_half: Option<OwnedReadHalf>,
|
|
||||||
|
|
||||||
/// WS -> Qemu
|
|
||||||
write_half: OwnedWriteHalf,
|
|
||||||
|
|
||||||
// Client must respond to ping at a specific interval, otherwise we drop connection
|
|
||||||
hb: Instant,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl VNCActor {
|
|
||||||
pub async fn new(socket_path: &str) -> anyhow::Result<Self> {
|
|
||||||
let socket_path = Path::new(socket_path);
|
|
||||||
|
|
||||||
if !socket_path.exists() {
|
|
||||||
return Err(VNCError::SocketDoesNotExists.into());
|
|
||||||
}
|
|
||||||
|
|
||||||
let socket = UnixStream::connect(socket_path).await?;
|
|
||||||
let (read_half, write_half) = socket.into_split();
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
read_half: Some(read_half),
|
|
||||||
write_half,
|
|
||||||
hb: Instant::now(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// helper method that sends ping to client every second.
|
|
||||||
///
|
|
||||||
/// also this method checks heartbeats from client
|
|
||||||
fn hb(&self, ctx: &mut ws::WebsocketContext<Self>) {
|
|
||||||
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
|
|
||||||
// check client heartbeats
|
|
||||||
if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
|
|
||||||
// heartbeat timed out
|
|
||||||
log::warn!("WebSocket Client heartbeat failed, disconnecting!");
|
|
||||||
ctx.stop();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.ping(b"");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn send_to_socket(&mut self, bytes: Bytes, ctx: &mut ws::WebsocketContext<Self>) {
|
|
||||||
log::trace!("Received {} bytes for VNC socket", bytes.len());
|
|
||||||
|
|
||||||
if let Err(e) = futures::executor::block_on(self.write_half.write(bytes.as_bytes())) {
|
|
||||||
log::error!("Failed to relay bytes to VNC socket {e}");
|
|
||||||
ctx.close(None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn start_qemu_to_ws_end(&mut self, ctx: &mut ws::WebsocketContext<Self>) {
|
|
||||||
let mut read_half = self.read_half.take().unwrap();
|
|
||||||
let addr = ctx.address();
|
|
||||||
let future = async move {
|
|
||||||
let mut buff: [u8; 5000] = [0; 5000];
|
|
||||||
loop {
|
|
||||||
match read_half.read(&mut buff).await {
|
|
||||||
Ok(mut l) => {
|
|
||||||
if l == 0 {
|
|
||||||
log::warn!("Got empty read!");
|
|
||||||
|
|
||||||
// Ugly hack made to wait for next byte
|
|
||||||
let mut one_byte_buff: [u8; 1] = [0; 1];
|
|
||||||
match read_half.read_exact(&mut one_byte_buff).await {
|
|
||||||
Ok(b) => {
|
|
||||||
if b == 0 {
|
|
||||||
log::error!("Did not get a byte !");
|
|
||||||
let _ = addr.send(CloseWebSocketReq).await;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
buff[0] = one_byte_buff[0];
|
|
||||||
l = 1;
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to read 1 BYTE from remote socket. Stopping now... {:?}", e);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let to_send = SendBytesReq(Vec::from(&buff[0..l]));
|
|
||||||
if let Err(e) = addr.send(to_send).await {
|
|
||||||
log::error!("Failed to send to websocket. Stopping now... {:?}", e);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to read from remote socket. Stopping now... {:?}", e);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
log::info!("Exited read loop");
|
|
||||||
};
|
|
||||||
|
|
||||||
tokio::spawn(future);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Actor for VNCActor {
|
|
||||||
type Context = ws::WebsocketContext<Self>;
|
|
||||||
|
|
||||||
fn started(&mut self, ctx: &mut Self::Context) {
|
|
||||||
self.hb(ctx);
|
|
||||||
self.start_qemu_to_ws_end(ctx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StreamHandler<Result<Message, ws::ProtocolError>> for VNCActor {
|
|
||||||
fn handle(&mut self, msg: Result<Message, ws::ProtocolError>, ctx: &mut Self::Context) {
|
|
||||||
match msg {
|
|
||||||
Ok(Message::Ping(msg)) => ctx.pong(&msg),
|
|
||||||
|
|
||||||
Ok(Message::Text(_text)) => {
|
|
||||||
log::error!("Received unexpected text on VNC WebSocket!");
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Message::Binary(bin)) => {
|
|
||||||
log::info!("Forward {} bytes to VNC server", bin.len());
|
|
||||||
self.send_to_socket(bin, ctx);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Message::Continuation(msg)) => match msg {
|
|
||||||
Item::FirstText(_) => {
|
|
||||||
log::error!("Received unexpected split text!");
|
|
||||||
ctx.close(None);
|
|
||||||
}
|
|
||||||
Item::FirstBinary(bin) | Item::Continue(bin) | Item::Last(bin) => {
|
|
||||||
self.send_to_socket(bin, ctx);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
Ok(Message::Pong(_)) => {
|
|
||||||
log::trace!("Received PONG message");
|
|
||||||
self.hb = Instant::now();
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Message::Close(r)) => {
|
|
||||||
log::info!("WebSocket closed. Reason={r:?}");
|
|
||||||
ctx.close(r);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Message::Nop) => {
|
|
||||||
log::debug!("Received Nop message")
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("WebSocket protocol error! {e}");
|
|
||||||
ctx.close(None)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(actix::Message)]
|
|
||||||
#[rtype(result = "()")]
|
|
||||||
pub struct SendBytesReq(Vec<u8>);
|
|
||||||
|
|
||||||
impl Handler<SendBytesReq> for VNCActor {
|
|
||||||
type Result = ();
|
|
||||||
|
|
||||||
fn handle(&mut self, msg: SendBytesReq, ctx: &mut Self::Context) -> Self::Result {
|
|
||||||
log::trace!("Send {} bytes to WS", msg.0.len());
|
|
||||||
ctx.binary(msg.0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(actix::Message)]
|
|
||||||
#[rtype(result = "()")]
|
|
||||||
pub struct CloseWebSocketReq;
|
|
||||||
|
|
||||||
impl Handler<CloseWebSocketReq> for VNCActor {
|
|
||||||
type Result = ();
|
|
||||||
|
|
||||||
fn handle(&mut self, _msg: CloseWebSocketReq, ctx: &mut Self::Context) -> Self::Result {
|
|
||||||
log::trace!("Close websocket, because VNC socket has terminated");
|
|
||||||
ctx.close(None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
129
virtweb_backend/src/actors/vnc_handler.rs
Normal file
129
virtweb_backend/src/actors/vnc_handler.rs
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
use actix_http::ws::Message;
|
||||||
|
use futures_util::StreamExt as _;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
use tokio::net::UnixStream;
|
||||||
|
use tokio::select;
|
||||||
|
use tokio::time::interval;
|
||||||
|
|
||||||
|
/// How often heartbeat pings are sent
|
||||||
|
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
|
/// How long before lack of client response causes a timeout
|
||||||
|
const CLIENT_TIMEOUT: Duration = Duration::from_secs(20);
|
||||||
|
|
||||||
|
/// Broadcast text & binary messages received from a client, respond to ping messages, and monitor
|
||||||
|
/// connection health to detect network issues and free up resources.
|
||||||
|
pub async fn handle(
|
||||||
|
mut session: actix_ws::Session,
|
||||||
|
mut msg_stream: actix_ws::MessageStream,
|
||||||
|
mut socket: UnixStream,
|
||||||
|
) {
|
||||||
|
log::info!("Connected to websocket");
|
||||||
|
|
||||||
|
let mut last_heartbeat = Instant::now();
|
||||||
|
let mut interval = interval(HEARTBEAT_INTERVAL);
|
||||||
|
|
||||||
|
let mut buf_socket = [0u8; 1024];
|
||||||
|
|
||||||
|
let reason = loop {
|
||||||
|
// waits for either `msg_stream` to receive a message from the client, the broadcast channel
|
||||||
|
// to send a message, or the heartbeat interval timer to tick, yielding the value of
|
||||||
|
// whichever one is ready first
|
||||||
|
select! {
|
||||||
|
|
||||||
|
// heartbeat interval ticked
|
||||||
|
_tick = interval.tick() => {
|
||||||
|
// if no heartbeat ping/pong received recently, close the connection
|
||||||
|
if Instant::now().duration_since(last_heartbeat) > CLIENT_TIMEOUT {
|
||||||
|
log::info!(
|
||||||
|
"client has not sent heartbeat in over {CLIENT_TIMEOUT:?}; disconnecting"
|
||||||
|
);
|
||||||
|
|
||||||
|
break None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// send heartbeat ping
|
||||||
|
let _ = session.ping(b"").await;
|
||||||
|
}
|
||||||
|
|
||||||
|
msg = msg_stream.next() => {
|
||||||
|
let msg = match msg {
|
||||||
|
// received message from WebSocket client
|
||||||
|
Some(Ok(msg)) => msg,
|
||||||
|
|
||||||
|
// client WebSocket stream error
|
||||||
|
Some(Err(err)) => {
|
||||||
|
log::error!("{err}");
|
||||||
|
break None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// client WebSocket stream ended
|
||||||
|
None => break None
|
||||||
|
};
|
||||||
|
|
||||||
|
log::debug!("msg: {msg:?}");
|
||||||
|
|
||||||
|
match msg {
|
||||||
|
Message::Text(_) => {
|
||||||
|
log::error!("Received unexpected text on VNC WebSocket!");
|
||||||
|
}
|
||||||
|
|
||||||
|
Message::Binary(bin) => {
|
||||||
|
log::info!("Forward {} bytes to VNC server", bin.len());
|
||||||
|
if let Err(e) = socket.write(&bin).await {
|
||||||
|
log::error!("Failed to relay bytes to VNC socket {e}");
|
||||||
|
break None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Message::Close(reason) => {
|
||||||
|
break reason;
|
||||||
|
}
|
||||||
|
|
||||||
|
Message::Ping(bytes) => {
|
||||||
|
last_heartbeat = Instant::now();
|
||||||
|
let _ = session.pong(&bytes).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
Message::Pong(_) => {
|
||||||
|
last_heartbeat = Instant::now();
|
||||||
|
}
|
||||||
|
|
||||||
|
Message::Continuation(_) => {
|
||||||
|
log::warn!("no support for continuation frames");
|
||||||
|
}
|
||||||
|
|
||||||
|
// no-op; ignore
|
||||||
|
Message::Nop => {}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Forward socket packet to WS client
|
||||||
|
count = socket.read(&mut buf_socket) => {
|
||||||
|
let count = match count {
|
||||||
|
Ok(count) => count,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("[VNC] Failed to read from upstream! {e}");
|
||||||
|
break None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if count == 0 {
|
||||||
|
log::warn!("[VNC] infinite loop (upstream), closing connection");
|
||||||
|
break None;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Err(e)=session.binary(buf_socket[0..count].to_vec()).await{
|
||||||
|
log::error!("[VNC] Failed to forward messages to upstream, will close connection! {e}");
|
||||||
|
break None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// attempt to close connection gracefully
|
||||||
|
let _ = session.close(reason).await;
|
||||||
|
|
||||||
|
log::info!("Disconnected from websocket");
|
||||||
|
}
|
||||||
299
virtweb_backend/src/api_tokens.rs
Normal file
299
virtweb_backend/src/api_tokens.rs
Normal file
@@ -0,0 +1,299 @@
|
|||||||
|
//! # API tokens management
|
||||||
|
|
||||||
|
use crate::app_config::AppConfig;
|
||||||
|
use crate::constants;
|
||||||
|
use crate::utils::time_utils::time;
|
||||||
|
use actix_http::Method;
|
||||||
|
use basic_jwt::{JWTPrivateKey, JWTPublicKey};
|
||||||
|
use std::path::Path;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug)]
|
||||||
|
pub struct TokenID(pub uuid::Uuid);
|
||||||
|
|
||||||
|
impl TokenID {
|
||||||
|
/// Parse a string as a token id
|
||||||
|
pub fn parse(t: &str) -> anyhow::Result<Self> {
|
||||||
|
Ok(Self(uuid::Uuid::parse_str(t)?))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)]
|
||||||
|
pub struct TokenRight {
|
||||||
|
verb: TokenVerb,
|
||||||
|
path: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||||
|
pub struct TokenRights(Vec<TokenRight>);
|
||||||
|
|
||||||
|
impl TokenRights {
|
||||||
|
pub fn check_error(&self) -> Option<&'static str> {
|
||||||
|
for r in &self.0 {
|
||||||
|
if !r.path.starts_with("/api/") {
|
||||||
|
return Some("All API rights shall start with /api/");
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.path.len() > constants::API_TOKEN_RIGHT_PATH_MAX_LENGTH {
|
||||||
|
return Some("An API path shall not exceed maximum URL size!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contains(&self, verb: TokenVerb, path: &str) -> bool {
|
||||||
|
let req_path_split = path.split('/').collect::<Vec<_>>();
|
||||||
|
|
||||||
|
'root: for r in &self.0 {
|
||||||
|
if r.verb != verb {
|
||||||
|
continue 'root;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut last_idx = 0;
|
||||||
|
for (idx, part) in r.path.split('/').enumerate() {
|
||||||
|
if idx >= req_path_split.len() {
|
||||||
|
continue 'root;
|
||||||
|
}
|
||||||
|
|
||||||
|
if part != "*" && part != req_path_split[idx] {
|
||||||
|
continue 'root;
|
||||||
|
}
|
||||||
|
|
||||||
|
last_idx = idx;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check we visited the whole path
|
||||||
|
if last_idx + 1 == req_path_split.len() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||||
|
pub struct Token {
|
||||||
|
pub id: TokenID,
|
||||||
|
pub name: String,
|
||||||
|
pub description: String,
|
||||||
|
created: u64,
|
||||||
|
updated: u64,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub pub_key: Option<JWTPublicKey>,
|
||||||
|
pub rights: TokenRights,
|
||||||
|
pub last_used: u64,
|
||||||
|
pub ip_restriction: Option<ipnetwork::IpNetwork>,
|
||||||
|
pub max_inactivity: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Token {
|
||||||
|
/// Turn the token into a JSON string
|
||||||
|
fn save(&self) -> anyhow::Result<()> {
|
||||||
|
let json = serde_json::to_string(self)?;
|
||||||
|
|
||||||
|
std::fs::write(AppConfig::get().api_token_definition_path(self.id), json)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load token information from a file
|
||||||
|
fn load_from_file(path: &Path) -> anyhow::Result<Self> {
|
||||||
|
Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check whether a token is expired or not
|
||||||
|
pub fn is_expired(&self) -> bool {
|
||||||
|
if let Some(max_inactivity) = self.max_inactivity {
|
||||||
|
if max_inactivity + self.last_used < time() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check whether last_used shall be updated or not
|
||||||
|
pub fn should_update_last_activity(&self) -> bool {
|
||||||
|
self.last_used + 3600 < time()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, Eq, PartialEq)]
|
||||||
|
pub enum TokenVerb {
|
||||||
|
GET,
|
||||||
|
POST,
|
||||||
|
PUT,
|
||||||
|
PATCH,
|
||||||
|
DELETE,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TokenVerb {
|
||||||
|
pub fn as_method(&self) -> Method {
|
||||||
|
match self {
|
||||||
|
TokenVerb::GET => Method::GET,
|
||||||
|
TokenVerb::POST => Method::POST,
|
||||||
|
TokenVerb::PUT => Method::PUT,
|
||||||
|
TokenVerb::PATCH => Method::PATCH,
|
||||||
|
TokenVerb::DELETE => Method::DELETE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromStr for TokenVerb {
|
||||||
|
type Err = ();
|
||||||
|
|
||||||
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
|
match s {
|
||||||
|
"GET" => Ok(TokenVerb::GET),
|
||||||
|
"POST" => Ok(TokenVerb::POST),
|
||||||
|
"PUT" => Ok(TokenVerb::PUT),
|
||||||
|
"PATCH" => Ok(TokenVerb::PATCH),
|
||||||
|
"DELETE" => Ok(TokenVerb::DELETE),
|
||||||
|
_ => Err(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Structure used to create a token
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||||
|
pub struct NewToken {
|
||||||
|
pub name: String,
|
||||||
|
pub description: String,
|
||||||
|
pub rights: TokenRights,
|
||||||
|
pub ip_restriction: Option<ipnetwork::IpNetwork>,
|
||||||
|
pub max_inactivity: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NewToken {
|
||||||
|
/// Check for error in token
|
||||||
|
pub fn check_error(&self) -> Option<&'static str> {
|
||||||
|
if self.name.len() < constants::API_TOKEN_NAME_MIN_LENGTH {
|
||||||
|
return Some("Name is too short!");
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.name.len() > constants::API_TOKEN_NAME_MAX_LENGTH {
|
||||||
|
return Some("Name is too long!");
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.description.len() < constants::API_TOKEN_DESCRIPTION_MIN_LENGTH {
|
||||||
|
return Some("Description is too short!");
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.description.len() > constants::API_TOKEN_DESCRIPTION_MAX_LENGTH {
|
||||||
|
return Some("Description is too long!");
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(err) = self.rights.check_error() {
|
||||||
|
return Some(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(t) = self.max_inactivity {
|
||||||
|
if t < 3600 {
|
||||||
|
return Some("API tokens shall be valid for at least 1 hour!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new Token
|
||||||
|
pub async fn create(t: &NewToken) -> anyhow::Result<(Token, JWTPrivateKey)> {
|
||||||
|
let priv_key = JWTPrivateKey::generate_ec384_signing_key()?;
|
||||||
|
let pub_key = priv_key.to_public_key()?;
|
||||||
|
|
||||||
|
let token = Token {
|
||||||
|
name: t.name.to_string(),
|
||||||
|
description: t.description.to_string(),
|
||||||
|
id: TokenID(uuid::Uuid::new_v4()),
|
||||||
|
created: time(),
|
||||||
|
updated: time(),
|
||||||
|
pub_key: Some(pub_key),
|
||||||
|
rights: t.rights.clone(),
|
||||||
|
last_used: time(),
|
||||||
|
ip_restriction: t.ip_restriction,
|
||||||
|
max_inactivity: t.max_inactivity,
|
||||||
|
};
|
||||||
|
|
||||||
|
token.save()?;
|
||||||
|
|
||||||
|
Ok((token, priv_key))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the entire list of api tokens
|
||||||
|
pub async fn full_list() -> anyhow::Result<Vec<Token>> {
|
||||||
|
let mut list = Vec::new();
|
||||||
|
for f in std::fs::read_dir(AppConfig::get().api_tokens_path())? {
|
||||||
|
list.push(Token::load_from_file(&f?.path())?);
|
||||||
|
}
|
||||||
|
Ok(list)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the information about a single token
|
||||||
|
pub async fn get_single(id: TokenID) -> anyhow::Result<Token> {
|
||||||
|
Token::load_from_file(&AppConfig::get().api_token_definition_path(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update API tokens rights
|
||||||
|
pub async fn update_rights(id: TokenID, rights: TokenRights) -> anyhow::Result<()> {
|
||||||
|
let mut token = get_single(id).await?;
|
||||||
|
token.rights = rights;
|
||||||
|
token.updated = time();
|
||||||
|
token.save()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set last_used value of token
|
||||||
|
pub async fn refresh_last_used(id: TokenID) -> anyhow::Result<()> {
|
||||||
|
let mut token = get_single(id).await?;
|
||||||
|
token.last_used = time();
|
||||||
|
token.save()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete an API token
|
||||||
|
pub async fn delete(id: TokenID) -> anyhow::Result<()> {
|
||||||
|
let path = AppConfig::get().api_token_definition_path(id);
|
||||||
|
if path.exists() {
|
||||||
|
std::fs::remove_file(path)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use crate::api_tokens::{TokenRight, TokenRights, TokenVerb};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_rights_patch() {
|
||||||
|
let rights = TokenRights(vec![
|
||||||
|
TokenRight {
|
||||||
|
path: "/api/vm/*".to_string(),
|
||||||
|
verb: TokenVerb::GET,
|
||||||
|
},
|
||||||
|
TokenRight {
|
||||||
|
path: "/api/vm/a".to_string(),
|
||||||
|
verb: TokenVerb::PUT,
|
||||||
|
},
|
||||||
|
TokenRight {
|
||||||
|
path: "/api/vm/a/other".to_string(),
|
||||||
|
verb: TokenVerb::DELETE,
|
||||||
|
},
|
||||||
|
TokenRight {
|
||||||
|
path: "/api/net/create".to_string(),
|
||||||
|
verb: TokenVerb::POST,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert!(rights.contains(TokenVerb::GET, "/api/vm/ab"));
|
||||||
|
assert!(!rights.contains(TokenVerb::GET, "/api/vm"));
|
||||||
|
assert!(!rights.contains(TokenVerb::GET, "/api/vm/ab/c"));
|
||||||
|
assert!(rights.contains(TokenVerb::PUT, "/api/vm/a"));
|
||||||
|
assert!(!rights.contains(TokenVerb::PUT, "/api/vm/other"));
|
||||||
|
assert!(rights.contains(TokenVerb::POST, "/api/net/create"));
|
||||||
|
assert!(!rights.contains(TokenVerb::GET, "/api/net/create"));
|
||||||
|
assert!(!rights.contains(TokenVerb::POST, "/api/net/b"));
|
||||||
|
assert!(!rights.contains(TokenVerb::POST, "/api/net/create/b"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use crate::api_tokens::TokenID;
|
||||||
use crate::constants;
|
use crate::constants;
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
use crate::libvirt_rest_structures::net::NetworkName;
|
use crate::libvirt_rest_structures::net::NetworkName;
|
||||||
@@ -67,7 +68,7 @@ pub struct AppConfig {
|
|||||||
#[arg(
|
#[arg(
|
||||||
long,
|
long,
|
||||||
env,
|
env,
|
||||||
default_value = "http://localhost:9001/.well-known/openid-configuration"
|
default_value = "http://localhost:9001/dex/.well-known/openid-configuration"
|
||||||
)]
|
)]
|
||||||
pub oidc_configuration_url: String,
|
pub oidc_configuration_url: String,
|
||||||
|
|
||||||
@@ -102,10 +103,15 @@ pub struct AppConfig {
|
|||||||
#[arg(short = 'H', long, env)]
|
#[arg(short = 'H', long, env)]
|
||||||
pub hypervisor_uri: Option<String>,
|
pub hypervisor_uri: Option<String>,
|
||||||
|
|
||||||
/// Trusted network. If set, a client from a different will not be able to perform request other
|
/// Trusted network. If set, a client (user) from a different network will not be able to perform
|
||||||
/// than those with GET verb (aside for login)
|
/// request other than those with GET verb (aside for login)
|
||||||
#[arg(short = 'T', long, env)]
|
#[arg(short = 'T', long, env)]
|
||||||
pub trusted_network: Vec<String>,
|
pub trusted_network: Vec<String>,
|
||||||
|
|
||||||
|
/// Comma-separated list of allowed networks. If set, a client (user or API token) from a
|
||||||
|
/// different network will not be able to access VirtWeb
|
||||||
|
#[arg(short = 'A', long, env)]
|
||||||
|
pub allowed_networks: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
lazy_static::lazy_static! {
|
lazy_static::lazy_static! {
|
||||||
@@ -189,6 +195,25 @@ impl AppConfig {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Check if an IP belongs to an allowed network or not
|
||||||
|
pub fn is_allowed_ip(&self, ip: IpAddr) -> bool {
|
||||||
|
if self.allowed_networks.is_empty() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
for i in &self.allowed_networks {
|
||||||
|
for sub_i in i.split(',') {
|
||||||
|
let net =
|
||||||
|
ipnetwork::IpNetwork::from_str(sub_i).expect("Allowed network is invalid!");
|
||||||
|
if net.contains(ip) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
/// Get OpenID providers configuration
|
/// Get OpenID providers configuration
|
||||||
pub fn openid_provider(&self) -> Option<OIDCProvider<'_>> {
|
pub fn openid_provider(&self) -> Option<OIDCProvider<'_>> {
|
||||||
if self.disable_oidc {
|
if self.disable_oidc {
|
||||||
@@ -268,6 +293,14 @@ impl AppConfig {
|
|||||||
self.definitions_path()
|
self.definitions_path()
|
||||||
.join(format!("nwfilter-{}.json", name.0))
|
.join(format!("nwfilter-{}.json", name.0))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn api_tokens_path(&self) -> PathBuf {
|
||||||
|
self.storage_path().join(constants::STORAGE_TOKENS_DIR)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn api_token_definition_path(&self, id: TokenID) -> PathBuf {
|
||||||
|
self.api_tokens_path().join(format!("{}.json", id.0))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, serde::Serialize)]
|
#[derive(Debug, Clone, serde::Serialize)]
|
||||||
|
|||||||
@@ -17,10 +17,11 @@ pub const ROUTES_WITHOUT_AUTH: [&str; 5] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
/// Allowed ISO mimetypes
|
/// Allowed ISO mimetypes
|
||||||
pub const ALLOWED_ISO_MIME_TYPES: [&str; 3] = [
|
pub const ALLOWED_ISO_MIME_TYPES: [&str; 4] = [
|
||||||
"application/x-cd-image",
|
"application/x-cd-image",
|
||||||
"application/x-iso9660-image",
|
"application/x-iso9660-image",
|
||||||
"application/octet-stream",
|
"application/octet-stream",
|
||||||
|
"application/vnd.efi.iso",
|
||||||
];
|
];
|
||||||
|
|
||||||
/// ISO max size
|
/// ISO max size
|
||||||
@@ -89,3 +90,21 @@ pub const NAT_MODE_ENV_VAR_NAME: &str = "NAT_MODE";
|
|||||||
|
|
||||||
/// Nat hook file path
|
/// Nat hook file path
|
||||||
pub const NAT_HOOK_PATH: &str = "/etc/libvirt/hooks/network";
|
pub const NAT_HOOK_PATH: &str = "/etc/libvirt/hooks/network";
|
||||||
|
|
||||||
|
/// Directory where API tokens are stored, inside storage directory
|
||||||
|
pub const STORAGE_TOKENS_DIR: &str = "tokens";
|
||||||
|
|
||||||
|
/// API token name min length
|
||||||
|
pub const API_TOKEN_NAME_MIN_LENGTH: usize = 3;
|
||||||
|
|
||||||
|
/// API token name max length
|
||||||
|
pub const API_TOKEN_NAME_MAX_LENGTH: usize = 30;
|
||||||
|
|
||||||
|
/// API token description min length
|
||||||
|
pub const API_TOKEN_DESCRIPTION_MIN_LENGTH: usize = 5;
|
||||||
|
|
||||||
|
/// API token description max length
|
||||||
|
pub const API_TOKEN_DESCRIPTION_MAX_LENGTH: usize = 30;
|
||||||
|
|
||||||
|
/// API token right path max length
|
||||||
|
pub const API_TOKEN_RIGHT_PATH_MAX_LENGTH: usize = 255;
|
||||||
|
|||||||
100
virtweb_backend/src/controllers/api_tokens_controller.rs
Normal file
100
virtweb_backend/src/controllers/api_tokens_controller.rs
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
//! # API tokens management
|
||||||
|
|
||||||
|
use crate::api_tokens;
|
||||||
|
use crate::api_tokens::{NewToken, TokenID, TokenRights};
|
||||||
|
use crate::controllers::HttpResult;
|
||||||
|
use crate::controllers::api_tokens_controller::rest_token::RestToken;
|
||||||
|
use actix_web::{HttpResponse, web};
|
||||||
|
use basic_jwt::JWTPrivateKey;
|
||||||
|
|
||||||
|
/// Create a special module for REST token to enforce usage of constructor function
|
||||||
|
mod rest_token {
|
||||||
|
use crate::api_tokens::Token;
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
pub struct RestToken {
|
||||||
|
#[serde(flatten)]
|
||||||
|
token: Token,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RestToken {
|
||||||
|
pub fn new(mut token: Token) -> Self {
|
||||||
|
token.pub_key = None;
|
||||||
|
Self { token }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct CreateTokenResult {
|
||||||
|
token: RestToken,
|
||||||
|
priv_key: JWTPrivateKey,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new API token
|
||||||
|
pub async fn create(new_token: web::Json<NewToken>) -> HttpResult {
|
||||||
|
if let Some(err) = new_token.check_error() {
|
||||||
|
log::error!("Failed to validate new API token information! {err}");
|
||||||
|
return Ok(HttpResponse::BadRequest().json(format!(
|
||||||
|
"Failed to validate new API token information! {err}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let (token, priv_key) = api_tokens::create(&new_token).await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(CreateTokenResult {
|
||||||
|
token: RestToken::new(token),
|
||||||
|
priv_key,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the list of API tokens
|
||||||
|
pub async fn list() -> HttpResult {
|
||||||
|
let list = api_tokens::full_list()
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.map(RestToken::new)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(list))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
pub struct TokenIDInPath {
|
||||||
|
uid: TokenID,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the information about a single token
|
||||||
|
pub async fn get_single(path: web::Path<TokenIDInPath>) -> HttpResult {
|
||||||
|
let token = api_tokens::get_single(path.uid).await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(RestToken::new(token)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
pub struct UpdateTokenBody {
|
||||||
|
rights: TokenRights,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update a token
|
||||||
|
pub async fn update(
|
||||||
|
path: web::Path<TokenIDInPath>,
|
||||||
|
body: web::Json<UpdateTokenBody>,
|
||||||
|
) -> HttpResult {
|
||||||
|
if let Some(err) = body.rights.check_error() {
|
||||||
|
log::error!("Failed to validate updated API token information! {err}");
|
||||||
|
return Ok(HttpResponse::BadRequest()
|
||||||
|
.json(format!("Failed to validate API token information! {err}")));
|
||||||
|
}
|
||||||
|
|
||||||
|
api_tokens::update_rights(path.uid, body.0.rights).await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Accepted().finish())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete a token
|
||||||
|
pub async fn delete(path: web::Path<TokenIDInPath>) -> HttpResult {
|
||||||
|
api_tokens::delete(path.uid).await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Accepted().finish())
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
use actix_remote_ip::RemoteIP;
|
use actix_remote_ip::RemoteIP;
|
||||||
use actix_web::web::Data;
|
use actix_web::web::Data;
|
||||||
use actix_web::{web, HttpResponse, Responder};
|
use actix_web::{HttpResponse, Responder, web};
|
||||||
use light_openid::basic_state_manager::BasicStateManager;
|
use light_openid::basic_state_manager::BasicStateManager;
|
||||||
|
|
||||||
use crate::app_config::AppConfig;
|
use crate::app_config::AppConfig;
|
||||||
|
|||||||
148
virtweb_backend/src/controllers/groups_controller.rs
Normal file
148
virtweb_backend/src/controllers/groups_controller.rs
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
use crate::controllers::{HttpResult, LibVirtReq};
|
||||||
|
use crate::extractors::group_vm_id_extractor::GroupVmIdExtractor;
|
||||||
|
use crate::libvirt_rest_structures::vm::VMInfo;
|
||||||
|
use actix_web::HttpResponse;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
/// Get the list of groups
|
||||||
|
pub async fn list(client: LibVirtReq) -> HttpResult {
|
||||||
|
let groups = match client.get_full_groups_list().await {
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to get the list of groups! {e}");
|
||||||
|
return Ok(HttpResponse::InternalServerError()
|
||||||
|
.json(format!("Failed to get the list of groups! {e}")));
|
||||||
|
}
|
||||||
|
Ok(l) => l,
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(groups))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get information about the VMs of a group
|
||||||
|
pub async fn vm_info(vms_xml: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut vms = Vec::new();
|
||||||
|
for vm in vms_xml.0 {
|
||||||
|
vms.push(VMInfo::from_domain(vm)?)
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(vms))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, serde::Serialize)]
|
||||||
|
pub struct TreatmentResult {
|
||||||
|
ok: usize,
|
||||||
|
failed: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the VMs of a group
|
||||||
|
pub async fn vm_start(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut res = TreatmentResult::default();
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
match client.start_domain(uuid).await {
|
||||||
|
Ok(_) => res.ok += 1,
|
||||||
|
Err(_) => res.failed += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shutdown the VMs of a group
|
||||||
|
pub async fn vm_shutdown(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut res = TreatmentResult::default();
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
match client.shutdown_domain(uuid).await {
|
||||||
|
Ok(_) => res.ok += 1,
|
||||||
|
Err(_) => res.failed += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Suspend the VMs of a group
|
||||||
|
pub async fn vm_suspend(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut res = TreatmentResult::default();
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
match client.suspend_domain(uuid).await {
|
||||||
|
Ok(_) => res.ok += 1,
|
||||||
|
Err(_) => res.failed += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resume the VMs of a group
|
||||||
|
pub async fn vm_resume(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut res = TreatmentResult::default();
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
match client.resume_domain(uuid).await {
|
||||||
|
Ok(_) => res.ok += 1,
|
||||||
|
Err(_) => res.failed += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Kill the VMs of a group
|
||||||
|
pub async fn vm_kill(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut res = TreatmentResult::default();
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
match client.kill_domain(uuid).await {
|
||||||
|
Ok(_) => res.ok += 1,
|
||||||
|
Err(_) => res.failed += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reset the VMs of a group
|
||||||
|
pub async fn vm_reset(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut res = TreatmentResult::default();
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
match client.reset_domain(uuid).await {
|
||||||
|
Ok(_) => res.ok += 1,
|
||||||
|
Err(_) => res.failed += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(HttpResponse::Ok().json(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the screenshot of the VMs of a group
|
||||||
|
pub async fn vm_screenshot(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
if vms.0.is_empty() {
|
||||||
|
return Ok(HttpResponse::NoContent().finish());
|
||||||
|
}
|
||||||
|
|
||||||
|
let image = if vms.0.len() == 1 {
|
||||||
|
client.screenshot_domain(vms.0[0].uuid.unwrap()).await?
|
||||||
|
} else {
|
||||||
|
return Ok(
|
||||||
|
HttpResponse::UnprocessableEntity().json("Cannot return multiple VM screenshots!!")
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().content_type("image/png").body(image))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the state of the VMs
|
||||||
|
pub async fn vm_state(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
|
||||||
|
let mut states = HashMap::new();
|
||||||
|
|
||||||
|
for vm in vms.0 {
|
||||||
|
if let Some(uuid) = vm.uuid {
|
||||||
|
states.insert(uuid, client.get_domain_state(uuid).await?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(states))
|
||||||
|
}
|
||||||
@@ -3,9 +3,9 @@ use crate::constants;
|
|||||||
use crate::controllers::HttpResult;
|
use crate::controllers::HttpResult;
|
||||||
use crate::utils::files_utils;
|
use crate::utils::files_utils;
|
||||||
use actix_files::NamedFile;
|
use actix_files::NamedFile;
|
||||||
use actix_multipart::form::tempfile::TempFile;
|
|
||||||
use actix_multipart::form::MultipartForm;
|
use actix_multipart::form::MultipartForm;
|
||||||
use actix_web::{web, HttpRequest, HttpResponse};
|
use actix_multipart::form::tempfile::TempFile;
|
||||||
|
use actix_web::{HttpRequest, HttpResponse, web};
|
||||||
use futures_util::StreamExt;
|
use futures_util::StreamExt;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
use crate::libvirt_client::LibVirtClient;
|
use crate::libvirt_client::LibVirtClient;
|
||||||
use actix_http::StatusCode;
|
use actix_http::StatusCode;
|
||||||
use actix_web::body::BoxBody;
|
use actix_web::body::BoxBody;
|
||||||
use actix_web::{web, HttpResponse};
|
use actix_web::{HttpResponse, web};
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt::{Display, Formatter};
|
use std::fmt::{Display, Formatter};
|
||||||
use std::io::ErrorKind;
|
use std::io::ErrorKind;
|
||||||
|
|
||||||
|
pub mod api_tokens_controller;
|
||||||
pub mod auth_controller;
|
pub mod auth_controller;
|
||||||
|
pub mod groups_controller;
|
||||||
pub mod iso_controller;
|
pub mod iso_controller;
|
||||||
pub mod network_controller;
|
pub mod network_controller;
|
||||||
pub mod nwfilter_controller;
|
pub mod nwfilter_controller;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use crate::controllers::{HttpResult, LibVirtReq};
|
use crate::controllers::{HttpResult, LibVirtReq};
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
use crate::libvirt_rest_structures::net::NetworkInfo;
|
use crate::libvirt_rest_structures::net::NetworkInfo;
|
||||||
use actix_web::{web, HttpResponse};
|
use actix_web::{HttpResponse, web};
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
pub struct NetworkID {
|
pub struct NetworkID {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use crate::constants;
|
|||||||
use crate::controllers::{HttpResult, LibVirtReq};
|
use crate::controllers::{HttpResult, LibVirtReq};
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
use crate::libvirt_rest_structures::nw_filter::NetworkFilter;
|
use crate::libvirt_rest_structures::nw_filter::NetworkFilter;
|
||||||
use actix_web::{web, HttpResponse};
|
use actix_web::{HttpResponse, web};
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
pub struct NetworkFilterID {
|
pub struct NetworkFilterID {
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ struct ServerConstraints {
|
|||||||
vnc_token_duration: u64,
|
vnc_token_duration: u64,
|
||||||
vm_name_size: LenConstraints,
|
vm_name_size: LenConstraints,
|
||||||
vm_title_size: LenConstraints,
|
vm_title_size: LenConstraints,
|
||||||
|
group_id_size: LenConstraints,
|
||||||
memory_size: LenConstraints,
|
memory_size: LenConstraints,
|
||||||
disk_name_size: LenConstraints,
|
disk_name_size: LenConstraints,
|
||||||
disk_size: LenConstraints,
|
disk_size: LenConstraints,
|
||||||
@@ -51,6 +52,9 @@ struct ServerConstraints {
|
|||||||
nwfilter_comment_size: LenConstraints,
|
nwfilter_comment_size: LenConstraints,
|
||||||
nwfilter_priority: SLenConstraints,
|
nwfilter_priority: SLenConstraints,
|
||||||
nwfilter_selectors_count: LenConstraints,
|
nwfilter_selectors_count: LenConstraints,
|
||||||
|
api_token_name_size: LenConstraints,
|
||||||
|
api_token_description_size: LenConstraints,
|
||||||
|
api_token_right_path_size: LenConstraints,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
|
pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
|
||||||
@@ -69,6 +73,7 @@ pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
|
|||||||
|
|
||||||
vm_name_size: LenConstraints { min: 2, max: 50 },
|
vm_name_size: LenConstraints { min: 2, max: 50 },
|
||||||
vm_title_size: LenConstraints { min: 0, max: 50 },
|
vm_title_size: LenConstraints { min: 0, max: 50 },
|
||||||
|
group_id_size: LenConstraints { min: 3, max: 50 },
|
||||||
memory_size: LenConstraints {
|
memory_size: LenConstraints {
|
||||||
min: constants::MIN_VM_MEMORY,
|
min: constants::MIN_VM_MEMORY,
|
||||||
max: constants::MAX_VM_MEMORY,
|
max: constants::MAX_VM_MEMORY,
|
||||||
@@ -98,6 +103,21 @@ pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
|
|||||||
max: 1000,
|
max: 1000,
|
||||||
},
|
},
|
||||||
nwfilter_selectors_count: LenConstraints { min: 0, max: 1 },
|
nwfilter_selectors_count: LenConstraints { min: 0, max: 1 },
|
||||||
|
|
||||||
|
api_token_name_size: LenConstraints {
|
||||||
|
min: constants::API_TOKEN_NAME_MIN_LENGTH,
|
||||||
|
max: constants::API_TOKEN_NAME_MAX_LENGTH,
|
||||||
|
},
|
||||||
|
|
||||||
|
api_token_description_size: LenConstraints {
|
||||||
|
min: constants::API_TOKEN_DESCRIPTION_MIN_LENGTH,
|
||||||
|
max: constants::API_TOKEN_DESCRIPTION_MAX_LENGTH,
|
||||||
|
},
|
||||||
|
|
||||||
|
api_token_right_path_size: LenConstraints {
|
||||||
|
min: 0,
|
||||||
|
max: constants::API_TOKEN_RIGHT_PATH_MAX_LENGTH,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -116,16 +136,13 @@ pub async fn server_info(client: LibVirtReq) -> HttpResult {
|
|||||||
system.refresh_all();
|
system.refresh_all();
|
||||||
|
|
||||||
let mut components = Components::new();
|
let mut components = Components::new();
|
||||||
components.refresh_list();
|
components.refresh(true);
|
||||||
components.refresh();
|
|
||||||
|
|
||||||
let mut disks = Disks::new();
|
let mut disks = Disks::new();
|
||||||
disks.refresh_list();
|
disks.refresh(true);
|
||||||
disks.refresh();
|
|
||||||
|
|
||||||
let mut networks = Networks::new();
|
let mut networks = Networks::new();
|
||||||
networks.refresh_list();
|
networks.refresh(true);
|
||||||
networks.refresh();
|
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(ServerInfo {
|
Ok(HttpResponse::Ok().json(ServerInfo {
|
||||||
hypervisor: client.get_info().await?,
|
hypervisor: client.get_info().await?,
|
||||||
@@ -153,7 +170,7 @@ pub async fn network_hook_status() -> HttpResult {
|
|||||||
|
|
||||||
pub async fn number_vcpus() -> HttpResult {
|
pub async fn number_vcpus() -> HttpResult {
|
||||||
let mut system = System::new();
|
let mut system = System::new();
|
||||||
system.refresh_cpu();
|
system.refresh_cpu_all();
|
||||||
let number_cpus = system.cpus().len();
|
let number_cpus = system.cpus().len();
|
||||||
assert_ne!(number_cpus, 0, "Got invlid number of CPU!");
|
assert_ne!(number_cpus, 0, "Got invlid number of CPU!");
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ mod serve_static_debug {
|
|||||||
|
|
||||||
#[cfg(not(debug_assertions))]
|
#[cfg(not(debug_assertions))]
|
||||||
mod serve_static_release {
|
mod serve_static_release {
|
||||||
use actix_web::{web, HttpResponse, Responder};
|
use actix_web::{HttpResponse, Responder, web};
|
||||||
use rust_embed::RustEmbed;
|
use rust_embed::RustEmbed;
|
||||||
|
|
||||||
#[derive(RustEmbed)]
|
#[derive(RustEmbed)]
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
use crate::actors::vnc_actor::VNCActor;
|
use crate::actors::vnc_handler;
|
||||||
use crate::actors::vnc_tokens_actor::VNCTokensManager;
|
use crate::actors::vnc_tokens_actor::VNCTokensManager;
|
||||||
use crate::controllers::{HttpResult, LibVirtReq};
|
use crate::controllers::{HttpResult, LibVirtReq};
|
||||||
use crate::libvirt_lib_structures::domain::DomainState;
|
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
|
use crate::libvirt_lib_structures::domain::DomainState;
|
||||||
use crate::libvirt_rest_structures::vm::VMInfo;
|
use crate::libvirt_rest_structures::vm::VMInfo;
|
||||||
use actix_web::{web, HttpRequest, HttpResponse};
|
use actix_web::{HttpRequest, HttpResponse, rt, web};
|
||||||
use actix_web_actors::ws;
|
use std::path::Path;
|
||||||
|
use tokio::net::UnixStream;
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
#[derive(serde::Serialize)]
|
||||||
struct VMInfoAndState {
|
struct VMInfoAndState {
|
||||||
@@ -21,7 +22,7 @@ struct VMUuid {
|
|||||||
|
|
||||||
/// Create a new VM
|
/// Create a new VM
|
||||||
pub async fn create(client: LibVirtReq, req: web::Json<VMInfo>) -> HttpResult {
|
pub async fn create(client: LibVirtReq, req: web::Json<VMInfo>) -> HttpResult {
|
||||||
let domain = match req.0.as_tomain() {
|
let domain = match req.0.as_domain() {
|
||||||
Ok(d) => d,
|
Ok(d) => d,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
log::error!("Failed to extract domain info! {e}");
|
log::error!("Failed to extract domain info! {e}");
|
||||||
@@ -83,6 +84,8 @@ pub async fn get_single(client: LibVirtReq, id: web::Path<SingleVMUUidReq>) -> H
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
log::debug!("INFO={info:#?}");
|
||||||
|
|
||||||
let state = client.get_domain_state(id.uid).await?;
|
let state = client.get_domain_state(id.uid).await?;
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(VMInfoAndState {
|
Ok(HttpResponse::Ok().json(VMInfoAndState {
|
||||||
@@ -112,7 +115,7 @@ pub async fn update(
|
|||||||
id: web::Path<SingleVMUUidReq>,
|
id: web::Path<SingleVMUUidReq>,
|
||||||
req: web::Json<VMInfo>,
|
req: web::Json<VMInfo>,
|
||||||
) -> HttpResult {
|
) -> HttpResult {
|
||||||
let mut domain = match req.0.as_tomain() {
|
let mut domain = match req.0.as_domain() {
|
||||||
Ok(d) => d,
|
Ok(d) => d,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
log::error!("Failed to extract domain info! {e}");
|
log::error!("Failed to extract domain info! {e}");
|
||||||
@@ -322,5 +325,19 @@ pub async fn vnc(
|
|||||||
};
|
};
|
||||||
|
|
||||||
log::info!("Start VNC connection on socket {socket_path}");
|
log::info!("Start VNC connection on socket {socket_path}");
|
||||||
Ok(ws::start(VNCActor::new(&socket_path).await?, &req, stream)?)
|
|
||||||
|
let socket_path = Path::new(&socket_path);
|
||||||
|
if !socket_path.exists() {
|
||||||
|
log::error!("VNC socket path {socket_path:?} does not exist!");
|
||||||
|
return Ok(HttpResponse::ServiceUnavailable().json("VNC socket path does not exists!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let socket = UnixStream::connect(socket_path).await?;
|
||||||
|
|
||||||
|
let (res, session, msg_stream) = actix_ws::handle(&req, stream)?;
|
||||||
|
|
||||||
|
// spawn websocket handler (and don't await it) so that the response is returned immediately
|
||||||
|
rt::spawn(vnc_handler::handle(session, msg_stream, socket));
|
||||||
|
|
||||||
|
Ok(res)
|
||||||
}
|
}
|
||||||
|
|||||||
151
virtweb_backend/src/extractors/api_auth_extractor.rs
Normal file
151
virtweb_backend/src/extractors/api_auth_extractor.rs
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
use crate::api_tokens::{Token, TokenID, TokenVerb};
|
||||||
|
|
||||||
|
use crate::api_tokens;
|
||||||
|
use crate::utils::time_utils::time;
|
||||||
|
use actix_remote_ip::RemoteIP;
|
||||||
|
use actix_web::dev::Payload;
|
||||||
|
use actix_web::error::{ErrorBadRequest, ErrorUnauthorized};
|
||||||
|
use actix_web::{Error, FromRequest, HttpRequest};
|
||||||
|
use std::future::Future;
|
||||||
|
use std::pin::Pin;
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug)]
|
||||||
|
pub struct TokenClaims {
|
||||||
|
pub sub: String,
|
||||||
|
pub iat: usize,
|
||||||
|
pub exp: usize,
|
||||||
|
pub verb: TokenVerb,
|
||||||
|
pub path: String,
|
||||||
|
pub nonce: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ApiAuthExtractor {
|
||||||
|
pub token: Token,
|
||||||
|
pub claims: TokenClaims,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRequest for ApiAuthExtractor {
|
||||||
|
type Error = Error;
|
||||||
|
type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;
|
||||||
|
|
||||||
|
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||||
|
let req = req.clone();
|
||||||
|
|
||||||
|
let remote_ip = match RemoteIP::from_request(&req, payload).into_inner() {
|
||||||
|
Ok(ip) => ip,
|
||||||
|
Err(e) => return Box::pin(async { Err(e) }),
|
||||||
|
};
|
||||||
|
|
||||||
|
Box::pin(async move {
|
||||||
|
let (token_id, token_jwt) = match (
|
||||||
|
req.headers().get("x-token-id"),
|
||||||
|
req.headers().get("x-token-content"),
|
||||||
|
) {
|
||||||
|
(Some(id), Some(jwt)) => (
|
||||||
|
id.to_str().unwrap_or("").to_string(),
|
||||||
|
jwt.to_str().unwrap_or("").to_string(),
|
||||||
|
),
|
||||||
|
(_, _) => {
|
||||||
|
return Err(ErrorBadRequest("API auth headers were not all specified!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let token_id = match TokenID::parse(&token_id) {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to parse token id! {e}");
|
||||||
|
return Err(ErrorBadRequest("Unable to validate token ID!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let token = match api_tokens::get_single(token_id).await {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to retrieve token: {e}");
|
||||||
|
return Err(ErrorBadRequest("Unable to validate token!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if token.is_expired() {
|
||||||
|
log::error!("Token has expired (not been used for too long)!");
|
||||||
|
return Err(ErrorBadRequest("Unable to validate token!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let claims = match token
|
||||||
|
.pub_key
|
||||||
|
.as_ref()
|
||||||
|
.expect("All tokens shall have public key!")
|
||||||
|
.validate_jwt::<TokenClaims>(&token_jwt)
|
||||||
|
{
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to validate JWT: {e}");
|
||||||
|
return Err(ErrorBadRequest("Unable to validate token!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if claims.sub != token.id.0.to_string() {
|
||||||
|
log::error!("JWT sub mismatch (should equal to token id)!");
|
||||||
|
return Err(ErrorBadRequest(
|
||||||
|
"JWT sub mismatch (should equal to token id)!",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if time() + 60 * 15 < claims.iat as u64 {
|
||||||
|
log::error!("iat is in the future!");
|
||||||
|
return Err(ErrorBadRequest("iat is in the future!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if claims.exp < claims.iat {
|
||||||
|
log::error!("exp shall not be smaller than iat!");
|
||||||
|
return Err(ErrorBadRequest("exp shall not be smaller than iat!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if claims.exp - claims.iat > 1800 {
|
||||||
|
log::error!("JWT shall not be valid more than 30 minutes!");
|
||||||
|
return Err(ErrorBadRequest(
|
||||||
|
"JWT shall not be valid more than 30 minutes!",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if claims.path != req.path() {
|
||||||
|
log::error!("JWT path mismatch!");
|
||||||
|
return Err(ErrorBadRequest("JWT path mismatch!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if claims.verb.as_method() != req.method() {
|
||||||
|
log::error!("JWT method mismatch!");
|
||||||
|
return Err(ErrorBadRequest("JWT method mismatch!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if !token.rights.contains(claims.verb, req.path()) {
|
||||||
|
log::error!(
|
||||||
|
"Attempt to use a token for an unauthorized route! (token_id={})",
|
||||||
|
token.id.0
|
||||||
|
);
|
||||||
|
return Err(ErrorUnauthorized(
|
||||||
|
"Token cannot be used to query this route!",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(ip) = token.ip_restriction {
|
||||||
|
if !ip.contains(remote_ip.0) {
|
||||||
|
log::error!(
|
||||||
|
"Attempt to use a token for an unauthorized IP! {remote_ip:?} token_id={}",
|
||||||
|
token.id.0
|
||||||
|
);
|
||||||
|
return Err(ErrorUnauthorized("Token cannot be used from this IP!"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if token.should_update_last_activity() {
|
||||||
|
if let Err(e) = api_tokens::refresh_last_used(token.id).await {
|
||||||
|
log::error!("Could not update token last activity! {e}");
|
||||||
|
return Err(ErrorBadRequest("Couldn't refresh token last activity!"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(ApiAuthExtractor { token, claims })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
use actix_identity::Identity;
|
use actix_identity::Identity;
|
||||||
use actix_web::dev::Payload;
|
use actix_web::dev::Payload;
|
||||||
use actix_web::{Error, FromRequest, HttpMessage, HttpRequest};
|
use actix_web::{Error, FromRequest, HttpMessage, HttpRequest};
|
||||||
use futures_util::future::{ready, Ready};
|
use futures_util::future::{Ready, ready};
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
|
|
||||||
pub struct AuthExtractor {
|
pub struct AuthExtractor {
|
||||||
|
|||||||
66
virtweb_backend/src/extractors/group_vm_id_extractor.rs
Normal file
66
virtweb_backend/src/extractors/group_vm_id_extractor.rs
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
use crate::controllers::LibVirtReq;
|
||||||
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
|
use crate::libvirt_lib_structures::domain::DomainXML;
|
||||||
|
use crate::libvirt_rest_structures::vm::VMGroupId;
|
||||||
|
use actix_http::Payload;
|
||||||
|
use actix_web::error::ErrorBadRequest;
|
||||||
|
use actix_web::web::Query;
|
||||||
|
use actix_web::{Error, FromRequest, HttpRequest, web};
|
||||||
|
use std::future::Future;
|
||||||
|
use std::pin::Pin;
|
||||||
|
|
||||||
|
pub struct GroupVmIdExtractor(pub Vec<DomainXML>);
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct GroupIDInPath {
|
||||||
|
gid: VMGroupId,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct FilterVM {
|
||||||
|
vm_id: Option<XMLUuid>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRequest for GroupVmIdExtractor {
|
||||||
|
type Error = Error;
|
||||||
|
type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;
|
||||||
|
|
||||||
|
fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
|
||||||
|
let req = req.clone();
|
||||||
|
|
||||||
|
Box::pin(async move {
|
||||||
|
let Ok(group_id) =
|
||||||
|
web::Path::<GroupIDInPath>::from_request(&req, &mut Payload::None).await
|
||||||
|
else {
|
||||||
|
return Err(ErrorBadRequest("Group ID not specified in path!"));
|
||||||
|
};
|
||||||
|
let group_id = group_id.into_inner().gid;
|
||||||
|
|
||||||
|
let filter_vm = match Query::<FilterVM>::from_request(&req, &mut Payload::None).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to extract VM id from request! {e}");
|
||||||
|
return Err(ErrorBadRequest("Failed to extract VM id from request!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let Ok(client) = LibVirtReq::from_request(&req, &mut Payload::None).await else {
|
||||||
|
return Err(ErrorBadRequest("Failed to extract client handle!"));
|
||||||
|
};
|
||||||
|
|
||||||
|
let vms = match client.get_full_group_vm_list(&group_id).await {
|
||||||
|
Ok(vms) => vms,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to get the VMs of the group {group_id:?}: {e}");
|
||||||
|
return Err(ErrorBadRequest("Failed to get the VMs of the group!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Filter (if requested by the user)
|
||||||
|
Ok(GroupVmIdExtractor(match filter_vm.vm_id {
|
||||||
|
None => vms,
|
||||||
|
Some(id) => vms.into_iter().filter(|vms| vms.uuid == Some(id)).collect(),
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
use crate::app_config::AppConfig;
|
use crate::app_config::AppConfig;
|
||||||
use actix_web::dev::Payload;
|
use actix_web::dev::Payload;
|
||||||
use actix_web::{Error, FromRequest, HttpRequest};
|
use actix_web::{Error, FromRequest, HttpRequest};
|
||||||
use futures_util::future::{ready, Ready};
|
use futures_util::future::{Ready, ready};
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||||
|
|||||||
@@ -1,2 +1,4 @@
|
|||||||
|
pub mod api_auth_extractor;
|
||||||
pub mod auth_extractor;
|
pub mod auth_extractor;
|
||||||
|
pub mod group_vm_id_extractor;
|
||||||
pub mod local_auth_extractor;
|
pub mod local_auth_extractor;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
pub mod actors;
|
pub mod actors;
|
||||||
|
pub mod api_tokens;
|
||||||
pub mod app_config;
|
pub mod app_config;
|
||||||
pub mod constants;
|
pub mod constants;
|
||||||
pub mod controllers;
|
pub mod controllers;
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
use crate::actors::libvirt_actor;
|
use crate::actors::libvirt_actor;
|
||||||
use crate::actors::libvirt_actor::LibVirtActor;
|
use crate::actors::libvirt_actor::LibVirtActor;
|
||||||
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
use crate::libvirt_lib_structures::domain::{DomainState, DomainXML};
|
use crate::libvirt_lib_structures::domain::{DomainState, DomainXML};
|
||||||
use crate::libvirt_lib_structures::network::NetworkXML;
|
use crate::libvirt_lib_structures::network::NetworkXML;
|
||||||
use crate::libvirt_lib_structures::nwfilter::NetworkFilterXML;
|
use crate::libvirt_lib_structures::nwfilter::NetworkFilterXML;
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
|
||||||
use crate::libvirt_rest_structures::hypervisor::HypervisorInfo;
|
use crate::libvirt_rest_structures::hypervisor::HypervisorInfo;
|
||||||
use crate::libvirt_rest_structures::net::NetworkInfo;
|
use crate::libvirt_rest_structures::net::NetworkInfo;
|
||||||
use crate::libvirt_rest_structures::nw_filter::NetworkFilter;
|
use crate::libvirt_rest_structures::nw_filter::NetworkFilter;
|
||||||
use crate::libvirt_rest_structures::vm::VMInfo;
|
use crate::libvirt_rest_structures::vm::{VMGroupId, VMInfo};
|
||||||
use actix::Addr;
|
use actix::Addr;
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct LibVirtClient(pub Addr<LibVirtActor>);
|
pub struct LibVirtClient(pub Addr<LibVirtActor>);
|
||||||
@@ -107,6 +108,35 @@ impl LibVirtClient {
|
|||||||
.await?
|
.await?
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the full list of groups
|
||||||
|
pub async fn get_full_groups_list(&self) -> anyhow::Result<Vec<VMGroupId>> {
|
||||||
|
let domains = self.get_full_domains_list().await?;
|
||||||
|
let mut out = HashSet::new();
|
||||||
|
for d in domains {
|
||||||
|
if let Some(g) = VMInfo::from_domain(d)?.group {
|
||||||
|
out.insert(g);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out: Vec<_> = out.into_iter().collect();
|
||||||
|
out.sort();
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the full list of VMs of a given group
|
||||||
|
pub async fn get_full_group_vm_list(
|
||||||
|
&self,
|
||||||
|
group: &VMGroupId,
|
||||||
|
) -> anyhow::Result<Vec<DomainXML>> {
|
||||||
|
let vms = self.get_full_domains_list().await?;
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for vm in vms {
|
||||||
|
if VMInfo::from_domain(vm.clone())?.group == Some(group.clone()) {
|
||||||
|
out.push(vm);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
/// Update a network configuration
|
/// Update a network configuration
|
||||||
pub async fn update_network(
|
pub async fn update_network(
|
||||||
&self,
|
&self,
|
||||||
|
|||||||
@@ -1,7 +1,25 @@
|
|||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
|
|
||||||
|
/// VirtWeb specific metadata
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)]
|
||||||
|
#[serde(rename = "virtweb", default)]
|
||||||
|
pub struct DomainMetadataVirtWebXML {
|
||||||
|
#[serde(rename = "@xmlns:virtweb", default)]
|
||||||
|
pub ns: String,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub group: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Domain metadata
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)]
|
||||||
|
#[serde(rename = "metadata")]
|
||||||
|
pub struct DomainMetadataXML {
|
||||||
|
#[serde(rename = "virtweb:metadata", default)]
|
||||||
|
pub virtweb: DomainMetadataVirtWebXML,
|
||||||
|
}
|
||||||
|
|
||||||
/// OS information
|
/// OS information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "os")]
|
#[serde(rename = "os")]
|
||||||
pub struct OSXML {
|
pub struct OSXML {
|
||||||
#[serde(rename = "@firmware", default)]
|
#[serde(rename = "@firmware", default)]
|
||||||
@@ -11,7 +29,7 @@ pub struct OSXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// OS Type information
|
/// OS Type information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "os")]
|
#[serde(rename = "os")]
|
||||||
pub struct OSTypeXML {
|
pub struct OSTypeXML {
|
||||||
#[serde(rename = "@arch")]
|
#[serde(rename = "@arch")]
|
||||||
@@ -23,7 +41,7 @@ pub struct OSTypeXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// OS Loader information
|
/// OS Loader information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "loader")]
|
#[serde(rename = "loader")]
|
||||||
pub struct OSLoaderXML {
|
pub struct OSLoaderXML {
|
||||||
#[serde(rename = "@secure")]
|
#[serde(rename = "@secure")]
|
||||||
@@ -31,39 +49,39 @@ pub struct OSLoaderXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Hypervisor features
|
/// Hypervisor features
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Default)]
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Default, Debug)]
|
||||||
#[serde(rename = "features")]
|
#[serde(rename = "features")]
|
||||||
pub struct FeaturesXML {
|
pub struct FeaturesXML {
|
||||||
pub acpi: ACPIXML,
|
pub acpi: ACPIXML,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// ACPI feature
|
/// ACPI feature
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Default)]
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Default, Debug)]
|
||||||
#[serde(rename = "acpi")]
|
#[serde(rename = "acpi")]
|
||||||
pub struct ACPIXML {}
|
pub struct ACPIXML {}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "mac")]
|
#[serde(rename = "mac")]
|
||||||
pub struct NetMacAddress {
|
pub struct NetMacAddress {
|
||||||
#[serde(rename = "@address")]
|
#[serde(rename = "@address")]
|
||||||
pub address: String,
|
pub address: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "source")]
|
#[serde(rename = "source")]
|
||||||
pub struct NetIntSourceXML {
|
pub struct NetIntSourceXML {
|
||||||
#[serde(rename = "@network")]
|
#[serde(rename = "@network")]
|
||||||
pub network: String,
|
pub network: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "model")]
|
#[serde(rename = "model")]
|
||||||
pub struct NetIntModelXML {
|
pub struct NetIntModelXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
pub r#type: String,
|
pub r#type: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "filterref")]
|
#[serde(rename = "filterref")]
|
||||||
pub struct NetIntFilterParameterXML {
|
pub struct NetIntFilterParameterXML {
|
||||||
#[serde(rename = "@name")]
|
#[serde(rename = "@name")]
|
||||||
@@ -72,7 +90,7 @@ pub struct NetIntFilterParameterXML {
|
|||||||
pub value: String,
|
pub value: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "filterref")]
|
#[serde(rename = "filterref")]
|
||||||
pub struct NetIntfilterRefXML {
|
pub struct NetIntfilterRefXML {
|
||||||
#[serde(rename = "@filter")]
|
#[serde(rename = "@filter")]
|
||||||
@@ -81,7 +99,7 @@ pub struct NetIntfilterRefXML {
|
|||||||
pub parameters: Vec<NetIntFilterParameterXML>,
|
pub parameters: Vec<NetIntFilterParameterXML>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "interface")]
|
#[serde(rename = "interface")]
|
||||||
pub struct DomainNetInterfaceXML {
|
pub struct DomainNetInterfaceXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
@@ -95,14 +113,14 @@ pub struct DomainNetInterfaceXML {
|
|||||||
pub filterref: Option<NetIntfilterRefXML>,
|
pub filterref: Option<NetIntfilterRefXML>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "input")]
|
#[serde(rename = "input")]
|
||||||
pub struct DomainInputXML {
|
pub struct DomainInputXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
pub r#type: String,
|
pub r#type: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "backend")]
|
#[serde(rename = "backend")]
|
||||||
pub struct TPMBackendXML {
|
pub struct TPMBackendXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
@@ -112,7 +130,7 @@ pub struct TPMBackendXML {
|
|||||||
pub r#version: String,
|
pub r#version: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "tpm")]
|
#[serde(rename = "tpm")]
|
||||||
pub struct TPMDeviceXML {
|
pub struct TPMDeviceXML {
|
||||||
#[serde(rename = "@model")]
|
#[serde(rename = "@model")]
|
||||||
@@ -121,7 +139,7 @@ pub struct TPMDeviceXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Devices information
|
/// Devices information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "devices")]
|
#[serde(rename = "devices")]
|
||||||
pub struct DevicesXML {
|
pub struct DevicesXML {
|
||||||
/// Graphics (used for VNC)
|
/// Graphics (used for VNC)
|
||||||
@@ -150,7 +168,7 @@ pub struct DevicesXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Graphics information
|
/// Graphics information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "graphics")]
|
#[serde(rename = "graphics")]
|
||||||
pub struct GraphicsXML {
|
pub struct GraphicsXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
@@ -160,14 +178,14 @@ pub struct GraphicsXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Video device information
|
/// Video device information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "video")]
|
#[serde(rename = "video")]
|
||||||
pub struct VideoXML {
|
pub struct VideoXML {
|
||||||
pub model: VideoModelXML,
|
pub model: VideoModelXML,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Video model device information
|
/// Video model device information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "model")]
|
#[serde(rename = "model")]
|
||||||
pub struct VideoModelXML {
|
pub struct VideoModelXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
@@ -175,7 +193,7 @@ pub struct VideoModelXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Disk information
|
/// Disk information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "disk")]
|
#[serde(rename = "disk")]
|
||||||
pub struct DiskXML {
|
pub struct DiskXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
@@ -193,7 +211,7 @@ pub struct DiskXML {
|
|||||||
pub address: Option<DiskAddressXML>,
|
pub address: Option<DiskAddressXML>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "driver")]
|
#[serde(rename = "driver")]
|
||||||
pub struct DiskDriverXML {
|
pub struct DiskDriverXML {
|
||||||
#[serde(rename = "@name")]
|
#[serde(rename = "@name")]
|
||||||
@@ -204,14 +222,14 @@ pub struct DiskDriverXML {
|
|||||||
pub r#cache: String,
|
pub r#cache: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "source")]
|
#[serde(rename = "source")]
|
||||||
pub struct DiskSourceXML {
|
pub struct DiskSourceXML {
|
||||||
#[serde(rename = "@file")]
|
#[serde(rename = "@file")]
|
||||||
pub file: String,
|
pub file: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "target")]
|
#[serde(rename = "target")]
|
||||||
pub struct DiskTargetXML {
|
pub struct DiskTargetXML {
|
||||||
#[serde(rename = "@dev")]
|
#[serde(rename = "@dev")]
|
||||||
@@ -220,18 +238,18 @@ pub struct DiskTargetXML {
|
|||||||
pub bus: String,
|
pub bus: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "readonly")]
|
#[serde(rename = "readonly")]
|
||||||
pub struct DiskReadOnlyXML {}
|
pub struct DiskReadOnlyXML {}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "boot")]
|
#[serde(rename = "boot")]
|
||||||
pub struct DiskBootXML {
|
pub struct DiskBootXML {
|
||||||
#[serde(rename = "@order")]
|
#[serde(rename = "@order")]
|
||||||
pub order: String,
|
pub order: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "address")]
|
#[serde(rename = "address")]
|
||||||
pub struct DiskAddressXML {
|
pub struct DiskAddressXML {
|
||||||
#[serde(rename = "@type")]
|
#[serde(rename = "@type")]
|
||||||
@@ -251,7 +269,7 @@ pub struct DiskAddressXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Domain RAM information
|
/// Domain RAM information
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "memory")]
|
#[serde(rename = "memory")]
|
||||||
pub struct DomainMemoryXML {
|
pub struct DomainMemoryXML {
|
||||||
#[serde(rename = "@unit")]
|
#[serde(rename = "@unit")]
|
||||||
@@ -261,7 +279,7 @@ pub struct DomainMemoryXML {
|
|||||||
pub memory: usize,
|
pub memory: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "topology")]
|
#[serde(rename = "topology")]
|
||||||
pub struct DomainCPUTopology {
|
pub struct DomainCPUTopology {
|
||||||
#[serde(rename = "@sockets")]
|
#[serde(rename = "@sockets")]
|
||||||
@@ -272,14 +290,14 @@ pub struct DomainCPUTopology {
|
|||||||
pub threads: usize,
|
pub threads: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "cpu")]
|
#[serde(rename = "cpu")]
|
||||||
pub struct DomainVCPUXML {
|
pub struct DomainVCPUXML {
|
||||||
#[serde(rename = "$value")]
|
#[serde(rename = "$value")]
|
||||||
pub body: usize,
|
pub body: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "cpu")]
|
#[serde(rename = "cpu")]
|
||||||
pub struct DomainCPUXML {
|
pub struct DomainCPUXML {
|
||||||
#[serde(rename = "@mode")]
|
#[serde(rename = "@mode")]
|
||||||
@@ -288,7 +306,7 @@ pub struct DomainCPUXML {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Domain information, see https://libvirt.org/formatdomain.html
|
/// Domain information, see https://libvirt.org/formatdomain.html
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename = "domain")]
|
#[serde(rename = "domain")]
|
||||||
pub struct DomainXML {
|
pub struct DomainXML {
|
||||||
/// Domain type (kvm)
|
/// Domain type (kvm)
|
||||||
@@ -300,6 +318,9 @@ pub struct DomainXML {
|
|||||||
pub genid: Option<uuid::Uuid>,
|
pub genid: Option<uuid::Uuid>,
|
||||||
pub title: Option<String>,
|
pub title: Option<String>,
|
||||||
pub description: Option<String>,
|
pub description: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub metadata: Option<DomainMetadataXML>,
|
||||||
|
|
||||||
pub os: OSXML,
|
pub os: OSXML,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub features: FeaturesXML,
|
pub features: FeaturesXML,
|
||||||
@@ -319,10 +340,32 @@ pub struct DomainXML {
|
|||||||
pub on_crash: String,
|
pub on_crash: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const METADATA_START_MARKER: &str =
|
||||||
|
"<virtweb:metadata xmlns:virtweb=\"https://virtweb.communiquons.org\">";
|
||||||
|
const METADATA_END_MARKER: &str = "</virtweb:metadata>";
|
||||||
|
|
||||||
impl DomainXML {
|
impl DomainXML {
|
||||||
/// Decode Domain structure from XML definition
|
/// Decode Domain structure from XML definition
|
||||||
pub fn parse_xml(xml: &str) -> anyhow::Result<Self> {
|
pub fn parse_xml(xml: &str) -> anyhow::Result<Self> {
|
||||||
Ok(quick_xml::de::from_str(xml)?)
|
let mut res: Self = quick_xml::de::from_str(xml)?;
|
||||||
|
|
||||||
|
// Handle custom metadata parsing issue
|
||||||
|
//
|
||||||
|
// https://github.com/tafia/quick-xml/pull/797
|
||||||
|
if xml.contains(METADATA_START_MARKER) && xml.contains(METADATA_END_MARKER) {
|
||||||
|
let s = xml
|
||||||
|
.split_once(METADATA_START_MARKER)
|
||||||
|
.unwrap()
|
||||||
|
.1
|
||||||
|
.split_once(METADATA_END_MARKER)
|
||||||
|
.unwrap()
|
||||||
|
.0;
|
||||||
|
let s = format!("<virtweb>{s}</virtweb>");
|
||||||
|
let metadata: DomainMetadataVirtWebXML = quick_xml::de::from_str(&s)?;
|
||||||
|
res.metadata = Some(DomainMetadataXML { virtweb: metadata });
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(res)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Turn this domain into its XML definition
|
/// Turn this domain into its XML definition
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug)]
|
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, Eq, PartialEq, Hash)]
|
||||||
pub struct XMLUuid(pub uuid::Uuid);
|
pub struct XMLUuid(pub uuid::Uuid);
|
||||||
|
|
||||||
impl XMLUuid {
|
impl XMLUuid {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use crate::libvirt_lib_structures::network::*;
|
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
|
use crate::libvirt_lib_structures::network::*;
|
||||||
use crate::libvirt_rest_structures::LibVirtStructError::StructureExtraction;
|
use crate::libvirt_rest_structures::LibVirtStructError::StructureExtraction;
|
||||||
use crate::nat::nat_definition::Nat;
|
use crate::nat::nat_definition::Nat;
|
||||||
use crate::nat::nat_lib;
|
use crate::nat::nat_lib;
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
use crate::libvirt_lib_structures::nwfilter::{
|
use crate::libvirt_lib_structures::nwfilter::{
|
||||||
NetworkFilterRefXML, NetworkFilterRuleProtocolAllXML, NetworkFilterRuleProtocolArpXML,
|
NetworkFilterRefXML, NetworkFilterRuleProtocolAllXML, NetworkFilterRuleProtocolArpXML,
|
||||||
NetworkFilterRuleProtocolIpvx, NetworkFilterRuleProtocolLayer4, NetworkFilterRuleProtocolMac,
|
NetworkFilterRuleProtocolIpvx, NetworkFilterRuleProtocolLayer4, NetworkFilterRuleProtocolMac,
|
||||||
NetworkFilterRuleXML, NetworkFilterXML,
|
NetworkFilterRuleXML, NetworkFilterXML,
|
||||||
};
|
};
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
|
||||||
use crate::libvirt_rest_structures::LibVirtStructError;
|
use crate::libvirt_rest_structures::LibVirtStructError;
|
||||||
use crate::libvirt_rest_structures::LibVirtStructError::{
|
use crate::libvirt_rest_structures::LibVirtStructError::{
|
||||||
NetworkFilterExtraction, StructureExtraction,
|
NetworkFilterExtraction, StructureExtraction,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use crate::app_config::AppConfig;
|
use crate::app_config::AppConfig;
|
||||||
use crate::constants;
|
use crate::constants;
|
||||||
use crate::libvirt_lib_structures::domain::*;
|
|
||||||
use crate::libvirt_lib_structures::XMLUuid;
|
use crate::libvirt_lib_structures::XMLUuid;
|
||||||
|
use crate::libvirt_lib_structures::domain::*;
|
||||||
use crate::libvirt_rest_structures::LibVirtStructError;
|
use crate::libvirt_rest_structures::LibVirtStructError;
|
||||||
use crate::libvirt_rest_structures::LibVirtStructError::StructureExtraction;
|
use crate::libvirt_rest_structures::LibVirtStructError::StructureExtraction;
|
||||||
use crate::utils::disks_utils::Disk;
|
use crate::utils::disks_utils::Disk;
|
||||||
@@ -10,6 +10,11 @@ use crate::utils::files_utils::convert_size_unit_to_mb;
|
|||||||
use lazy_regex::regex;
|
use lazy_regex::regex;
|
||||||
use num::Integer;
|
use num::Integer;
|
||||||
|
|
||||||
|
#[derive(
|
||||||
|
Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, Ord, PartialOrd,
|
||||||
|
)]
|
||||||
|
pub struct VMGroupId(pub String);
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
pub enum BootType {
|
pub enum BootType {
|
||||||
UEFI,
|
UEFI,
|
||||||
@@ -59,6 +64,9 @@ pub struct VMInfo {
|
|||||||
pub genid: Option<XMLUuid>,
|
pub genid: Option<XMLUuid>,
|
||||||
pub title: Option<String>,
|
pub title: Option<String>,
|
||||||
pub description: Option<String>,
|
pub description: Option<String>,
|
||||||
|
/// Group associated with the VM (VirtWeb specific field)
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub group: Option<VMGroupId>,
|
||||||
pub boot_type: BootType,
|
pub boot_type: BootType,
|
||||||
pub architecture: VMArchitecture,
|
pub architecture: VMArchitecture,
|
||||||
/// VM allocated memory, in megabytes
|
/// VM allocated memory, in megabytes
|
||||||
@@ -79,7 +87,7 @@ pub struct VMInfo {
|
|||||||
|
|
||||||
impl VMInfo {
|
impl VMInfo {
|
||||||
/// Turn this VM into a domain
|
/// Turn this VM into a domain
|
||||||
pub fn as_tomain(&self) -> anyhow::Result<DomainXML> {
|
pub fn as_domain(&self) -> anyhow::Result<DomainXML> {
|
||||||
if !regex!("^[a-zA-Z0-9]+$").is_match(&self.name) {
|
if !regex!("^[a-zA-Z0-9]+$").is_match(&self.name) {
|
||||||
return Err(StructureExtraction("VM name is invalid!").into());
|
return Err(StructureExtraction("VM name is invalid!").into());
|
||||||
}
|
}
|
||||||
@@ -105,6 +113,12 @@ impl VMInfo {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(group) = &self.group {
|
||||||
|
if !regex!("^[a-zA-Z0-9]+$").is_match(&group.0) {
|
||||||
|
return Err(StructureExtraction("VM group name is invalid!").into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if self.memory < constants::MIN_VM_MEMORY || self.memory > constants::MAX_VM_MEMORY {
|
if self.memory < constants::MIN_VM_MEMORY || self.memory > constants::MAX_VM_MEMORY {
|
||||||
return Err(StructureExtraction("VM memory is invalid!").into());
|
return Err(StructureExtraction("VM memory is invalid!").into());
|
||||||
}
|
}
|
||||||
@@ -282,6 +296,12 @@ impl VMInfo {
|
|||||||
title: self.title.clone(),
|
title: self.title.clone(),
|
||||||
description: self.description.clone(),
|
description: self.description.clone(),
|
||||||
|
|
||||||
|
metadata: Some(DomainMetadataXML {
|
||||||
|
virtweb: DomainMetadataVirtWebXML {
|
||||||
|
ns: "https://virtweb.communiquons.org".to_string(),
|
||||||
|
group: self.group.clone().map(|g| g.0),
|
||||||
|
},
|
||||||
|
}),
|
||||||
os: OSXML {
|
os: OSXML {
|
||||||
r#type: OSTypeXML {
|
r#type: OSTypeXML {
|
||||||
arch: match self.architecture {
|
arch: match self.architecture {
|
||||||
@@ -369,6 +389,13 @@ impl VMInfo {
|
|||||||
genid: domain.genid.map(XMLUuid),
|
genid: domain.genid.map(XMLUuid),
|
||||||
title: domain.title,
|
title: domain.title,
|
||||||
description: domain.description,
|
description: domain.description,
|
||||||
|
group: domain
|
||||||
|
.metadata
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.virtweb
|
||||||
|
.group
|
||||||
|
.map(VMGroupId),
|
||||||
boot_type: match domain.os.loader {
|
boot_type: match domain.os.loader {
|
||||||
None => BootType::UEFI,
|
None => BootType::UEFI,
|
||||||
Some(l) => match l.secure.as_str() {
|
Some(l) => match l.secure.as_str() {
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
use actix::Actor;
|
use actix::Actor;
|
||||||
use actix_cors::Cors;
|
use actix_cors::Cors;
|
||||||
use actix_identity::config::LogoutBehaviour;
|
|
||||||
use actix_identity::IdentityMiddleware;
|
use actix_identity::IdentityMiddleware;
|
||||||
use actix_multipart::form::tempfile::TempFileConfig;
|
use actix_identity::config::LogoutBehaviour;
|
||||||
use actix_multipart::form::MultipartFormConfig;
|
use actix_multipart::form::MultipartFormConfig;
|
||||||
|
use actix_multipart::form::tempfile::TempFileConfig;
|
||||||
use actix_remote_ip::RemoteIPConfig;
|
use actix_remote_ip::RemoteIPConfig;
|
||||||
use actix_session::storage::CookieSessionStore;
|
|
||||||
use actix_session::SessionMiddleware;
|
use actix_session::SessionMiddleware;
|
||||||
|
use actix_session::storage::CookieSessionStore;
|
||||||
use actix_web::cookie::{Key, SameSite};
|
use actix_web::cookie::{Key, SameSite};
|
||||||
use actix_web::http::header;
|
use actix_web::http::header;
|
||||||
use actix_web::middleware::Logger;
|
use actix_web::middleware::Logger;
|
||||||
use actix_web::web::Data;
|
use actix_web::web::Data;
|
||||||
use actix_web::{web, App, HttpServer};
|
use actix_web::{App, HttpServer, web};
|
||||||
use light_openid::basic_state_manager::BasicStateManager;
|
use light_openid::basic_state_manager::BasicStateManager;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use virtweb_backend::actors::libvirt_actor::LibVirtActor;
|
use virtweb_backend::actors::libvirt_actor::LibVirtActor;
|
||||||
@@ -22,8 +22,8 @@ use virtweb_backend::constants::{
|
|||||||
MAX_INACTIVITY_DURATION, MAX_SESSION_DURATION, SESSION_COOKIE_NAME,
|
MAX_INACTIVITY_DURATION, MAX_SESSION_DURATION, SESSION_COOKIE_NAME,
|
||||||
};
|
};
|
||||||
use virtweb_backend::controllers::{
|
use virtweb_backend::controllers::{
|
||||||
auth_controller, iso_controller, network_controller, nwfilter_controller, server_controller,
|
api_tokens_controller, auth_controller, groups_controller, iso_controller, network_controller,
|
||||||
static_controller, vm_controller,
|
nwfilter_controller, server_controller, static_controller, vm_controller,
|
||||||
};
|
};
|
||||||
use virtweb_backend::libvirt_client::LibVirtClient;
|
use virtweb_backend::libvirt_client::LibVirtClient;
|
||||||
use virtweb_backend::middlewares::auth_middleware::AuthChecker;
|
use virtweb_backend::middlewares::auth_middleware::AuthChecker;
|
||||||
@@ -50,6 +50,7 @@ async fn main() -> std::io::Result<()> {
|
|||||||
files_utils::create_directory_if_missing(AppConfig::get().disks_storage_path()).unwrap();
|
files_utils::create_directory_if_missing(AppConfig::get().disks_storage_path()).unwrap();
|
||||||
files_utils::create_directory_if_missing(AppConfig::get().nat_path()).unwrap();
|
files_utils::create_directory_if_missing(AppConfig::get().nat_path()).unwrap();
|
||||||
files_utils::create_directory_if_missing(AppConfig::get().definitions_path()).unwrap();
|
files_utils::create_directory_if_missing(AppConfig::get().definitions_path()).unwrap();
|
||||||
|
files_utils::create_directory_if_missing(AppConfig::get().api_tokens_path()).unwrap();
|
||||||
|
|
||||||
let conn = Data::new(LibVirtClient(
|
let conn = Data::new(LibVirtClient(
|
||||||
LibVirtActor::connect()
|
LibVirtActor::connect()
|
||||||
@@ -84,7 +85,7 @@ async fn main() -> std::io::Result<()> {
|
|||||||
|
|
||||||
let mut cors = Cors::default()
|
let mut cors = Cors::default()
|
||||||
.allowed_origin(&AppConfig::get().website_origin)
|
.allowed_origin(&AppConfig::get().website_origin)
|
||||||
.allowed_methods(vec!["GET", "POST", "DELETE", "PUT"])
|
.allowed_methods(vec!["GET", "POST", "DELETE", "PUT", "PATCH"])
|
||||||
.allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
|
.allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
|
||||||
.allowed_header(header::CONTENT_TYPE)
|
.allowed_header(header::CONTENT_TYPE)
|
||||||
.supports_credentials()
|
.supports_credentials()
|
||||||
@@ -209,6 +210,44 @@ async fn main() -> std::io::Result<()> {
|
|||||||
web::get().to(vm_controller::vnc_token),
|
web::get().to(vm_controller::vnc_token),
|
||||||
)
|
)
|
||||||
.route("/api/vnc", web::get().to(vm_controller::vnc))
|
.route("/api/vnc", web::get().to(vm_controller::vnc))
|
||||||
|
// Groups controller
|
||||||
|
.route("/api/group/list", web::get().to(groups_controller::list))
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/info",
|
||||||
|
web::get().to(groups_controller::vm_info),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/start",
|
||||||
|
web::get().to(groups_controller::vm_start),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/shutdown",
|
||||||
|
web::get().to(groups_controller::vm_shutdown),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/suspend",
|
||||||
|
web::get().to(groups_controller::vm_suspend),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/resume",
|
||||||
|
web::get().to(groups_controller::vm_resume),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/kill",
|
||||||
|
web::get().to(groups_controller::vm_kill),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/reset",
|
||||||
|
web::get().to(groups_controller::vm_reset),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/screenshot",
|
||||||
|
web::get().to(groups_controller::vm_screenshot),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/group/{gid}/vm/state",
|
||||||
|
web::get().to(groups_controller::vm_state),
|
||||||
|
)
|
||||||
// Network controller
|
// Network controller
|
||||||
.route(
|
.route(
|
||||||
"/api/network/create",
|
"/api/network/create",
|
||||||
@@ -276,6 +315,27 @@ async fn main() -> std::io::Result<()> {
|
|||||||
"/api/nwfilter/{uid}",
|
"/api/nwfilter/{uid}",
|
||||||
web::delete().to(nwfilter_controller::delete),
|
web::delete().to(nwfilter_controller::delete),
|
||||||
)
|
)
|
||||||
|
// API tokens controller
|
||||||
|
.route(
|
||||||
|
"/api/token/create",
|
||||||
|
web::post().to(api_tokens_controller::create),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/token/list",
|
||||||
|
web::get().to(api_tokens_controller::list),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/token/{uid}",
|
||||||
|
web::get().to(api_tokens_controller::get_single),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/token/{uid}",
|
||||||
|
web::patch().to(api_tokens_controller::update),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/token/{uid}",
|
||||||
|
web::delete().to(api_tokens_controller::delete),
|
||||||
|
)
|
||||||
// Static assets
|
// Static assets
|
||||||
.route("/", web::get().to(static_controller::root_index))
|
.route("/", web::get().to(static_controller::root_index))
|
||||||
.route(
|
.route(
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
use std::future::{ready, Ready};
|
use std::future::{Ready, ready};
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use crate::app_config::AppConfig;
|
use crate::app_config::AppConfig;
|
||||||
use crate::constants;
|
use crate::constants;
|
||||||
|
use crate::extractors::api_auth_extractor::ApiAuthExtractor;
|
||||||
use crate::extractors::auth_extractor::AuthExtractor;
|
use crate::extractors::auth_extractor::AuthExtractor;
|
||||||
use actix_web::body::EitherBody;
|
use actix_web::body::EitherBody;
|
||||||
use actix_web::dev::Payload;
|
use actix_web::dev::Payload;
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
|
|
||||||
Error, FromRequest, HttpResponse,
|
Error, FromRequest, HttpResponse,
|
||||||
|
dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready},
|
||||||
};
|
};
|
||||||
use futures_util::future::LocalBoxFuture;
|
use futures_util::future::LocalBoxFuture;
|
||||||
|
|
||||||
@@ -66,10 +67,43 @@ where
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
if !AppConfig::get().is_allowed_ip(remote_ip.0) {
|
||||||
|
log::error!(
|
||||||
|
"An attempt to access VirtWeb from an unauthorized network has been intercepted! {:?}",
|
||||||
|
remote_ip
|
||||||
|
);
|
||||||
|
return Ok(req
|
||||||
|
.into_response(
|
||||||
|
HttpResponse::MethodNotAllowed()
|
||||||
|
.json("I am sorry, but your IP is not allowed to access this service!"),
|
||||||
|
)
|
||||||
|
.map_into_right_body());
|
||||||
|
}
|
||||||
|
|
||||||
let auth_disabled = AppConfig::get().unsecure_disable_auth;
|
let auth_disabled = AppConfig::get().unsecure_disable_auth;
|
||||||
|
|
||||||
// Check authentication, if required
|
// Check API authentication
|
||||||
if !auth_disabled
|
if req.headers().get("x-token-id").is_some() {
|
||||||
|
let auth =
|
||||||
|
match ApiAuthExtractor::from_request(req.request(), &mut Payload::None).await {
|
||||||
|
Ok(auth) => auth,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(
|
||||||
|
"Failed to extract API authentication information from request! {e}"
|
||||||
|
);
|
||||||
|
return Ok(req
|
||||||
|
.into_response(HttpResponse::PreconditionFailed().finish())
|
||||||
|
.map_into_right_body());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
log::info!(
|
||||||
|
"Using API token '{}' to perform the request",
|
||||||
|
auth.token.name
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Check user authentication, if required
|
||||||
|
else if !auth_disabled
|
||||||
&& !constants::ROUTES_WITHOUT_AUTH.contains(&req.path())
|
&& !constants::ROUTES_WITHOUT_AUTH.contains(&req.path())
|
||||||
&& req.path().starts_with("/api/")
|
&& req.path().starts_with("/api/")
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -49,7 +49,9 @@ pub async fn sub_main() -> anyhow::Result<()> {
|
|||||||
let args = NatArgs::parse();
|
let args = NatArgs::parse();
|
||||||
|
|
||||||
if !args.network_file().exists() {
|
if !args.network_file().exists() {
|
||||||
log::warn!("Cannot do anything for the network, because the NAT configuration file does not exixsts!");
|
log::warn!(
|
||||||
|
"Cannot do anything for the network, because the NAT configuration file does not exixsts!"
|
||||||
|
);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,7 +186,9 @@ fn toggle_port_forwarding(
|
|||||||
false => "tcp",
|
false => "tcp",
|
||||||
};
|
};
|
||||||
|
|
||||||
log::info!("Forward (add={enable}) incoming {protocol} connections for {host_ip}:{host_port} to {guest_ip}:{guest_port} int {net_interface}");
|
log::info!(
|
||||||
|
"Forward (add={enable}) incoming {protocol} connections for {host_ip}:{host_port} to {guest_ip}:{guest_port} int {net_interface}"
|
||||||
|
);
|
||||||
|
|
||||||
// Rule 1
|
// Rule 1
|
||||||
let cmd = Command::new(program)
|
let cmd = Command::new(program)
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ pub fn is_net_interface_name_valid<D: AsRef<str>>(int: D) -> bool {
|
|||||||
/// Get the list of available network interfaces
|
/// Get the list of available network interfaces
|
||||||
pub fn net_list() -> Vec<String> {
|
pub fn net_list() -> Vec<String> {
|
||||||
let mut networks = Networks::new();
|
let mut networks = Networks::new();
|
||||||
networks.refresh_list();
|
networks.refresh(true);
|
||||||
|
|
||||||
networks
|
networks
|
||||||
.list()
|
.list()
|
||||||
|
|||||||
@@ -1,12 +1,6 @@
|
|||||||
use rand::distributions::Alphanumeric;
|
use rand::distr::{Alphanumeric, SampleString};
|
||||||
use rand::Rng;
|
|
||||||
|
|
||||||
/// Generate a random string
|
/// Generate a random string
|
||||||
pub fn rand_str(len: usize) -> String {
|
pub fn rand_str(len: usize) -> String {
|
||||||
let s: String = rand::thread_rng()
|
Alphanumeric.sample_string(&mut rand::rng(), len)
|
||||||
.sample_iter(&Alphanumeric)
|
|
||||||
.take(len)
|
|
||||||
.map(char::from)
|
|
||||||
.collect();
|
|
||||||
s
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ make
|
|||||||
|
|
||||||
The release file will be available in `virtweb_backend/target/release/virtweb_backend`.
|
The release file will be available in `virtweb_backend/target/release/virtweb_backend`.
|
||||||
|
|
||||||
This is the only artifcat that must be copied to the server. It is recommended to copy it to the `/usr/local/bin` directory.
|
This is the only artifact that must be copied to the server. It is recommended to copy it to the `/usr/local/bin` directory.
|
||||||
|
|
||||||
## Install requirements
|
## Install requirements
|
||||||
In order to work properly, VirtWeb relies on `libvirt`, `qemu` and `kvm`:
|
In order to work properly, VirtWeb relies on `libvirt`, `qemu` and `kvm`:
|
||||||
@@ -61,7 +61,7 @@ STORAGE=/home/virtweb/storage
|
|||||||
HYPERVISOR_URI=qemu:///system
|
HYPERVISOR_URI=qemu:///system
|
||||||
```
|
```
|
||||||
|
|
||||||
> Note: `HYPERVISOR_URI=qemu:///system` is used to sepcify that we want to use the main hypervisor.
|
> Note: `HYPERVISOR_URI=qemu:///system` is used to specify that we want to use the main hypervisor.
|
||||||
|
|
||||||
## Register Virtweb service
|
## Register Virtweb service
|
||||||
Before registering service, check that the configuration works correctly:
|
Before registering service, check that the configuration works correctly:
|
||||||
|
|||||||
@@ -1,46 +1,12 @@
|
|||||||
# Getting Started with Create React App
|
# Virtweb frontend
|
||||||
|
Built with Vite + React + TypeScript
|
||||||
|
|
||||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
## Get dependencies
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
## Available Scripts
|
# Run for developpment
|
||||||
|
```bash
|
||||||
In the project directory, you can run:
|
npm run dev
|
||||||
|
```
|
||||||
### `npm start`
|
|
||||||
|
|
||||||
Runs the app in the development mode.\
|
|
||||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
|
||||||
|
|
||||||
The page will reload if you make edits.\
|
|
||||||
You will also see any lint errors in the console.
|
|
||||||
|
|
||||||
### `npm test`
|
|
||||||
|
|
||||||
Launches the test runner in the interactive watch mode.\
|
|
||||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
|
||||||
|
|
||||||
### `npm run build`
|
|
||||||
|
|
||||||
Builds the app for production to the `build` folder.\
|
|
||||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
|
||||||
|
|
||||||
The build is minified and the filenames include the hashes.\
|
|
||||||
Your app is ready to be deployed!
|
|
||||||
|
|
||||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
|
||||||
|
|
||||||
### `npm run eject`
|
|
||||||
|
|
||||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
|
||||||
|
|
||||||
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
|
||||||
|
|
||||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
|
||||||
|
|
||||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
|
||||||
|
|
||||||
## Learn More
|
|
||||||
|
|
||||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
|
||||||
|
|
||||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
|
||||||
54
virtweb_frontend/eslint.config.js
Normal file
54
virtweb_frontend/eslint.config.js
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
import js from "@eslint/js";
|
||||||
|
import reactDom from "eslint-plugin-react-dom";
|
||||||
|
import reactHooks from "eslint-plugin-react-hooks";
|
||||||
|
import reactRefresh from "eslint-plugin-react-refresh";
|
||||||
|
import reactX from "eslint-plugin-react-x";
|
||||||
|
import globals from "globals";
|
||||||
|
import tseslint from "typescript-eslint";
|
||||||
|
|
||||||
|
export default tseslint.config(
|
||||||
|
{ ignores: ["dist"] },
|
||||||
|
{
|
||||||
|
extends: [
|
||||||
|
js.configs.recommended,
|
||||||
|
...tseslint.configs.strictTypeChecked,
|
||||||
|
...tseslint.configs.stylisticTypeChecked,
|
||||||
|
],
|
||||||
|
files: ["**/*.{ts,tsx}"],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
parserOptions: {
|
||||||
|
project: ["./tsconfig.node.json", "./tsconfig.app.json"],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
"react-hooks": reactHooks,
|
||||||
|
"react-refresh": reactRefresh,
|
||||||
|
"react-x": reactX,
|
||||||
|
"react-dom": reactDom,
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
...reactHooks.configs.recommended.rules,
|
||||||
|
"react-refresh/only-export-components": [
|
||||||
|
"warn",
|
||||||
|
{ allowConstantExport: true },
|
||||||
|
],
|
||||||
|
...reactX.configs["recommended-typescript"].rules,
|
||||||
|
...reactDom.configs.recommended.rules,
|
||||||
|
"@typescript-eslint/no-non-null-assertion": "off",
|
||||||
|
"@typescript-eslint/no-misused-promises": "off",
|
||||||
|
"@typescript-eslint/no-floating-promises": "off",
|
||||||
|
"@typescript-eslint/restrict-template-expressions": "off",
|
||||||
|
"@typescript-eslint/no-extraneous-class": "off",
|
||||||
|
"@typescript-eslint/no-explicit-any": "off",
|
||||||
|
"@typescript-eslint/no-unsafe-assignment": "off",
|
||||||
|
"@typescript-eslint/no-unsafe-return": "off",
|
||||||
|
"@typescript-eslint/no-unsafe-call": "off",
|
||||||
|
"@typescript-eslint/no-unsafe-member-access": "off",
|
||||||
|
"@typescript-eslint/no-unsafe-argument": "off",
|
||||||
|
"react-refresh/only-export-components": "off",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
22559
virtweb_frontend/package-lock.json
generated
22559
virtweb_frontend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -3,62 +3,51 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
|
||||||
"@emotion/react": "^11.11.1",
|
|
||||||
"@emotion/styled": "^11.11.0",
|
|
||||||
"@fontsource/roboto": "^5.0.8",
|
|
||||||
"@mdi/js": "^7.2.96",
|
|
||||||
"@mdi/react": "^1.6.1",
|
|
||||||
"@mui/icons-material": "^5.14.7",
|
|
||||||
"@mui/material": "^5.14.7",
|
|
||||||
"@mui/x-charts": "^7.1.1",
|
|
||||||
"@mui/x-data-grid": "^7.0.0",
|
|
||||||
"@testing-library/jest-dom": "^6.4.2",
|
|
||||||
"@testing-library/react": "^14.0.0",
|
|
||||||
"@testing-library/user-event": "^14.5.2",
|
|
||||||
"@types/humanize-duration": "^3.27.1",
|
|
||||||
"@types/jest": "^29.5.12",
|
|
||||||
"@types/react": "^18.2.21",
|
|
||||||
"@types/react-dom": "^18.2.7",
|
|
||||||
"@types/react-syntax-highlighter": "^15.5.11",
|
|
||||||
"@types/uuid": "^9.0.5",
|
|
||||||
"@vitejs/plugin-react": "^4.2.1",
|
|
||||||
"filesize": "^10.0.12",
|
|
||||||
"humanize-duration": "^3.29.0",
|
|
||||||
"mui-file-input": "^4.0.4",
|
|
||||||
"react": "^18.2.0",
|
|
||||||
"react-dom": "^18.2.0",
|
|
||||||
"react-router-dom": "^6.15.0",
|
|
||||||
"react-syntax-highlighter": "^15.5.0",
|
|
||||||
"react-vnc": "^1.0.0",
|
|
||||||
"typescript": "^5.0.0",
|
|
||||||
"uuid": "^9.0.1",
|
|
||||||
"vite": "^5.0.8",
|
|
||||||
"vite-tsconfig-paths": "^4.2.2",
|
|
||||||
"web-vitals": "^3.5.2",
|
|
||||||
"xml-formatter": "^3.6.0"
|
|
||||||
},
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc && vite build",
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"eslintConfig": {
|
"dependencies": {
|
||||||
"extends": [
|
"@emotion/react": "^11.14.0",
|
||||||
"react-app",
|
"@emotion/styled": "^11.14.0",
|
||||||
"react-app/jest"
|
"@fontsource/roboto": "^5.2.5",
|
||||||
]
|
"@mdi/js": "^7.2.96",
|
||||||
|
"@mdi/react": "^1.6.1",
|
||||||
|
"@mui/icons-material": "^7.0.0",
|
||||||
|
"@mui/material": "^7.0.0",
|
||||||
|
"@mui/x-charts": "^7.28.0",
|
||||||
|
"@mui/x-data-grid": "^7.28.1",
|
||||||
|
"date-and-time": "^3.6.0",
|
||||||
|
"filesize": "^10.1.6",
|
||||||
|
"humanize-duration": "^3.29.0",
|
||||||
|
"mui-file-input": "^7.0.0",
|
||||||
|
"react": "^19.0.0",
|
||||||
|
"react-dom": "^19.0.0",
|
||||||
|
"react-router-dom": "^7.4.0",
|
||||||
|
"react-syntax-highlighter": "^15.6.1",
|
||||||
|
"react-vnc": "^3.0.7",
|
||||||
|
"uuid": "^11.1.0",
|
||||||
|
"xml-formatter": "^3.6.0"
|
||||||
},
|
},
|
||||||
"browserslist": {
|
"devDependencies": {
|
||||||
"production": [
|
"@eslint/js": "^9.21.0",
|
||||||
">0.2%",
|
"@types/humanize-duration": "^3.27.1",
|
||||||
"not dead",
|
"@types/jest": "^29.5.14",
|
||||||
"not op_mini all"
|
"@types/react": "^19.0.12",
|
||||||
],
|
"@types/react-dom": "^19.0.4",
|
||||||
"development": [
|
"@types/react-syntax-highlighter": "^15.5.13",
|
||||||
"last 1 chrome version",
|
"@types/uuid": "^10.0.0",
|
||||||
"last 1 firefox version",
|
"@vitejs/plugin-react": "^4.3.4",
|
||||||
"last 1 safari version"
|
"eslint": "^9.21.0",
|
||||||
]
|
"eslint-plugin-react-dom": "^1.38.3",
|
||||||
|
"eslint-plugin-react-hooks": "^5.1.0",
|
||||||
|
"eslint-plugin-react-refresh": "^0.4.19",
|
||||||
|
"eslint-plugin-react-x": "^1.38.3",
|
||||||
|
"globals": "^15.15.0",
|
||||||
|
"typescript": "^5.8.2",
|
||||||
|
"typescript-eslint": "^8.24.1",
|
||||||
|
"vite": "^6.2.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,29 +9,35 @@ import "./App.css";
|
|||||||
import { AuthApi } from "./api/AuthApi";
|
import { AuthApi } from "./api/AuthApi";
|
||||||
import { ServerApi } from "./api/ServerApi";
|
import { ServerApi } from "./api/ServerApi";
|
||||||
import {
|
import {
|
||||||
CreateNetworkRoute,
|
CreateApiTokenRoute,
|
||||||
EditNetworkRoute,
|
EditApiTokenRoute,
|
||||||
} from "./routes/EditNetworkRoute";
|
} from "./routes/EditAPITokenRoute";
|
||||||
import { CreateVMRoute, EditVMRoute } from "./routes/EditVMRoute";
|
|
||||||
import { IsoFilesRoute } from "./routes/IsoFilesRoute";
|
|
||||||
import { NetworksListRoute } from "./routes/NetworksListRoute";
|
|
||||||
import { NotFoundRoute } from "./routes/NotFound";
|
|
||||||
import { SysInfoRoute } from "./routes/SysInfoRoute";
|
|
||||||
import { VMListRoute } from "./routes/VMListRoute";
|
|
||||||
import { VMRoute } from "./routes/VMRoute";
|
|
||||||
import { VNCRoute } from "./routes/VNCRoute";
|
|
||||||
import { LoginRoute } from "./routes/auth/LoginRoute";
|
|
||||||
import { OIDCCbRoute } from "./routes/auth/OIDCCbRoute";
|
|
||||||
import { BaseAuthenticatedPage } from "./widgets/BaseAuthenticatedPage";
|
|
||||||
import { BaseLoginPage } from "./widgets/BaseLoginPage";
|
|
||||||
import { ViewNetworkRoute } from "./routes/ViewNetworkRoute";
|
|
||||||
import { HomeRoute } from "./routes/HomeRoute";
|
|
||||||
import { NetworkFiltersListRoute } from "./routes/NetworkFiltersListRoute";
|
|
||||||
import { ViewNWFilterRoute } from "./routes/ViewNWFilterRoute";
|
|
||||||
import {
|
import {
|
||||||
CreateNWFilterRoute,
|
CreateNWFilterRoute,
|
||||||
EditNWFilterRoute,
|
EditNWFilterRoute,
|
||||||
} from "./routes/EditNWFilterRoute";
|
} from "./routes/EditNWFilterRoute";
|
||||||
|
import {
|
||||||
|
CreateNetworkRoute,
|
||||||
|
EditNetworkRoute,
|
||||||
|
} from "./routes/EditNetworkRoute";
|
||||||
|
import { CreateVMRoute, EditVMRoute } from "./routes/EditVMRoute";
|
||||||
|
import { HomeRoute } from "./routes/HomeRoute";
|
||||||
|
import { IsoFilesRoute } from "./routes/IsoFilesRoute";
|
||||||
|
import { NetworkFiltersListRoute } from "./routes/NetworkFiltersListRoute";
|
||||||
|
import { NetworksListRoute } from "./routes/NetworksListRoute";
|
||||||
|
import { NotFoundRoute } from "./routes/NotFound";
|
||||||
|
import { SysInfoRoute } from "./routes/SysInfoRoute";
|
||||||
|
import { TokensListRoute } from "./routes/TokensListRoute";
|
||||||
|
import { VMListRoute } from "./routes/VMListRoute";
|
||||||
|
import { VMRoute } from "./routes/VMRoute";
|
||||||
|
import { VNCRoute } from "./routes/VNCRoute";
|
||||||
|
import { ViewApiTokenRoute } from "./routes/ViewApiTokenRoute";
|
||||||
|
import { ViewNWFilterRoute } from "./routes/ViewNWFilterRoute";
|
||||||
|
import { ViewNetworkRoute } from "./routes/ViewNetworkRoute";
|
||||||
|
import { LoginRoute } from "./routes/auth/LoginRoute";
|
||||||
|
import { OIDCCbRoute } from "./routes/auth/OIDCCbRoute";
|
||||||
|
import { BaseAuthenticatedPage } from "./widgets/BaseAuthenticatedPage";
|
||||||
|
import { BaseLoginPage } from "./widgets/BaseLoginPage";
|
||||||
|
|
||||||
interface AuthContext {
|
interface AuthContext {
|
||||||
signedIn: boolean;
|
signedIn: boolean;
|
||||||
@@ -45,7 +51,10 @@ export function App() {
|
|||||||
|
|
||||||
const context: AuthContext = {
|
const context: AuthContext = {
|
||||||
signedIn: signedIn,
|
signedIn: signedIn,
|
||||||
setSignedIn: (s) => setSignedIn(s),
|
setSignedIn: (s) => {
|
||||||
|
setSignedIn(s);
|
||||||
|
location.reload();
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const router = createBrowserRouter(
|
const router = createBrowserRouter(
|
||||||
@@ -72,6 +81,11 @@ export function App() {
|
|||||||
<Route path="nwfilter/:uuid" element={<ViewNWFilterRoute />} />
|
<Route path="nwfilter/:uuid" element={<ViewNWFilterRoute />} />
|
||||||
<Route path="nwfilter/:uuid/edit" element={<EditNWFilterRoute />} />
|
<Route path="nwfilter/:uuid/edit" element={<EditNWFilterRoute />} />
|
||||||
|
|
||||||
|
<Route path="tokens" element={<TokensListRoute />} />
|
||||||
|
<Route path="token/new" element={<CreateApiTokenRoute />} />
|
||||||
|
<Route path="token/:id" element={<ViewApiTokenRoute />} />
|
||||||
|
<Route path="token/:id/edit" element={<EditApiTokenRoute />} />
|
||||||
|
|
||||||
<Route path="sysinfo" element={<SysInfoRoute />} />
|
<Route path="sysinfo" element={<SysInfoRoute />} />
|
||||||
<Route path="*" element={<NotFoundRoute />} />
|
<Route path="*" element={<NotFoundRoute />} />
|
||||||
</Route>
|
</Route>
|
||||||
@@ -86,12 +100,12 @@ export function App() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContextK.Provider value={context}>
|
<AuthContextK value={context}>
|
||||||
<RouterProvider router={router} />
|
<RouterProvider router={router} />
|
||||||
</AuthContextK.Provider>
|
</AuthContextK>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAuth(): AuthContext {
|
export function useAuth(): AuthContext {
|
||||||
return React.useContext(AuthContextK)!;
|
return React.use(AuthContextK)!;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ export class APIClient {
|
|||||||
* Get backend URL
|
* Get backend URL
|
||||||
*/
|
*/
|
||||||
static backendURL(): string {
|
static backendURL(): string {
|
||||||
const URL = import.meta.env.VITE_APP_BACKEND ?? "";
|
const URL = String(import.meta.env.VITE_APP_BACKEND ?? "");
|
||||||
if (URL.length === 0) throw new Error("Backend URL undefined!");
|
if (URL.length === 0) throw new Error("Backend URL undefined!");
|
||||||
return URL;
|
return URL;
|
||||||
}
|
}
|
||||||
@@ -44,7 +44,7 @@ export class APIClient {
|
|||||||
*/
|
*/
|
||||||
static async exec(args: RequestParams): Promise<APIResponse> {
|
static async exec(args: RequestParams): Promise<APIResponse> {
|
||||||
let body: string | undefined | FormData = undefined;
|
let body: string | undefined | FormData = undefined;
|
||||||
let headers: any = {};
|
const headers: any = {};
|
||||||
|
|
||||||
// JSON request
|
// JSON request
|
||||||
if (args.jsonData) {
|
if (args.jsonData) {
|
||||||
@@ -66,22 +66,25 @@ export class APIClient {
|
|||||||
if (args.upProgress) {
|
if (args.upProgress) {
|
||||||
const res: XMLHttpRequest = await new Promise((resolve, reject) => {
|
const res: XMLHttpRequest = await new Promise((resolve, reject) => {
|
||||||
const xhr = new XMLHttpRequest();
|
const xhr = new XMLHttpRequest();
|
||||||
xhr.upload.addEventListener("progress", (e) =>
|
xhr.upload.addEventListener("progress", (e) => {
|
||||||
args.upProgress!(e.loaded / e.total)
|
args.upProgress!(e.loaded / e.total);
|
||||||
);
|
});
|
||||||
xhr.addEventListener("load", () => resolve(xhr));
|
xhr.addEventListener("load", () => {
|
||||||
xhr.addEventListener("error", () =>
|
resolve(xhr);
|
||||||
reject(new Error("File upload failed"))
|
});
|
||||||
);
|
xhr.addEventListener("error", () => {
|
||||||
xhr.addEventListener("abort", () =>
|
reject(new Error("File upload failed"));
|
||||||
reject(new Error("File upload aborted"))
|
});
|
||||||
);
|
xhr.addEventListener("abort", () => {
|
||||||
xhr.addEventListener("timeout", () =>
|
reject(new Error("File upload aborted"));
|
||||||
reject(new Error("File upload timeout"))
|
});
|
||||||
);
|
xhr.addEventListener("timeout", () => {
|
||||||
|
reject(new Error("File upload timeout"));
|
||||||
|
});
|
||||||
xhr.open(args.method, url, true);
|
xhr.open(args.method, url, true);
|
||||||
xhr.withCredentials = true;
|
xhr.withCredentials = true;
|
||||||
for (const key in headers) {
|
for (const key in headers) {
|
||||||
|
// eslint-disable-next-line no-prototype-builtins
|
||||||
if (headers.hasOwnProperty(key))
|
if (headers.hasOwnProperty(key))
|
||||||
xhr.setRequestHeader(key, headers[key]);
|
xhr.setRequestHeader(key, headers[key]);
|
||||||
}
|
}
|
||||||
|
|||||||
15
virtweb_frontend/src/api/GroupApi.ts
Normal file
15
virtweb_frontend/src/api/GroupApi.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { APIClient } from "./ApiClient";
|
||||||
|
|
||||||
|
export class GroupApi {
|
||||||
|
/**
|
||||||
|
* Get the entire list of networks
|
||||||
|
*/
|
||||||
|
static async GetList(): Promise<string[]> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "GET",
|
||||||
|
uri: "/group/list",
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -140,7 +140,7 @@ export interface NWFilter {
|
|||||||
rules: NWFilterRule[];
|
rules: NWFilterRule[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function NWFilterURL(n: NWFilter, edit: boolean = false): string {
|
export function NWFilterURL(n: NWFilter, edit = false): string {
|
||||||
return `/nwfilter/${n.uuid}${edit ? "/edit" : ""}`;
|
return `/nwfilter/${n.uuid}${edit ? "/edit" : ""}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,7 +221,7 @@ export class NWFilterApi {
|
|||||||
static async Delete(n: NWFilter): Promise<void> {
|
static async Delete(n: NWFilter): Promise<void> {
|
||||||
await APIClient.exec({
|
await APIClient.exec({
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
uri: `/nwfilter/${n.uuid}`,
|
uri: `/nwfilter/${n.uuid!}`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ export interface NetworkInfo {
|
|||||||
|
|
||||||
export type NetworkStatus = "Started" | "Stopped";
|
export type NetworkStatus = "Started" | "Stopped";
|
||||||
|
|
||||||
export function NetworkURL(n: NetworkInfo, edit: boolean = false): string {
|
export function NetworkURL(n: NetworkInfo, edit = false): string {
|
||||||
return `/net/${n.uuid}${edit ? "/edit" : ""}`;
|
return `/net/${n.uuid}${edit ? "/edit" : ""}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ export interface ServerConstraints {
|
|||||||
vnc_token_duration: number;
|
vnc_token_duration: number;
|
||||||
vm_name_size: LenConstraint;
|
vm_name_size: LenConstraint;
|
||||||
vm_title_size: LenConstraint;
|
vm_title_size: LenConstraint;
|
||||||
|
group_id_size: LenConstraint;
|
||||||
memory_size: LenConstraint;
|
memory_size: LenConstraint;
|
||||||
disk_name_size: LenConstraint;
|
disk_name_size: LenConstraint;
|
||||||
disk_size: LenConstraint;
|
disk_size: LenConstraint;
|
||||||
@@ -27,6 +28,9 @@ export interface ServerConstraints {
|
|||||||
nwfilter_comment_size: LenConstraint;
|
nwfilter_comment_size: LenConstraint;
|
||||||
nwfilter_priority: LenConstraint;
|
nwfilter_priority: LenConstraint;
|
||||||
nwfilter_selectors_count: LenConstraint;
|
nwfilter_selectors_count: LenConstraint;
|
||||||
|
api_token_name_size: LenConstraint;
|
||||||
|
api_token_description_size: LenConstraint;
|
||||||
|
api_token_right_path_size: LenConstraint;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LenConstraint {
|
export interface LenConstraint {
|
||||||
@@ -70,7 +74,7 @@ interface SystemInfo {
|
|||||||
secs: number;
|
secs: number;
|
||||||
nanos: number;
|
nanos: number;
|
||||||
};
|
};
|
||||||
global_cpu_info: GlobalCPUInfo;
|
global_cpu_usage: number;
|
||||||
cpus: CpuCore[];
|
cpus: CpuCore[];
|
||||||
physical_core_count: number;
|
physical_core_count: number;
|
||||||
total_memory: number;
|
total_memory: number;
|
||||||
@@ -91,14 +95,6 @@ interface SystemInfo {
|
|||||||
host_name: string;
|
host_name: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface GlobalCPUInfo {
|
|
||||||
cpu_usage: number;
|
|
||||||
name: string;
|
|
||||||
vendor_id: string;
|
|
||||||
brand: string;
|
|
||||||
frequency: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CpuCore {
|
interface CpuCore {
|
||||||
cpu_usage: number;
|
cpu_usage: number;
|
||||||
name: string;
|
name: string;
|
||||||
|
|||||||
102
virtweb_frontend/src/api/TokensApi.ts
Normal file
102
virtweb_frontend/src/api/TokensApi.ts
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
import { time } from "../utils/DateUtils";
|
||||||
|
import { APIClient } from "./ApiClient";
|
||||||
|
|
||||||
|
export type RightVerb = "POST" | "GET" | "PUT" | "DELETE" | "PATCH";
|
||||||
|
|
||||||
|
export interface TokenRight {
|
||||||
|
verb: RightVerb;
|
||||||
|
path: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface APIToken {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
created: number;
|
||||||
|
updated: number;
|
||||||
|
rights: TokenRight[];
|
||||||
|
last_used: number;
|
||||||
|
ip_restriction?: string;
|
||||||
|
max_inactivity?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function APITokenURL(t: APIToken, edit = false): string {
|
||||||
|
return `/token/${t.id}${edit ? "/edit" : ""}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ExpiredAPIToken(t: APIToken): boolean {
|
||||||
|
if (!t.max_inactivity) return false;
|
||||||
|
return t.last_used + t.max_inactivity < time();
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface APITokenPrivateKey {
|
||||||
|
alg: string;
|
||||||
|
priv: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreatedAPIToken {
|
||||||
|
token: APIToken;
|
||||||
|
priv_key: APITokenPrivateKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TokensApi {
|
||||||
|
/**
|
||||||
|
* Create a new API token
|
||||||
|
*/
|
||||||
|
static async Create(n: APIToken): Promise<CreatedAPIToken> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "POST",
|
||||||
|
uri: "/token/create",
|
||||||
|
jsonData: n,
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the full list of tokens
|
||||||
|
*/
|
||||||
|
static async GetList(): Promise<APIToken[]> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "GET",
|
||||||
|
uri: "/token/list",
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the information about a single token
|
||||||
|
*/
|
||||||
|
static async GetSingle(uuid: string): Promise<APIToken> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "GET",
|
||||||
|
uri: `/token/${uuid}`,
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update an existing API token information
|
||||||
|
*/
|
||||||
|
static async Update(n: APIToken): Promise<void> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "PATCH",
|
||||||
|
uri: `/token/${n.id}`,
|
||||||
|
jsonData: n,
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete an API token
|
||||||
|
*/
|
||||||
|
static async Delete(n: APIToken): Promise<void> {
|
||||||
|
await APIClient.exec({
|
||||||
|
method: "DELETE",
|
||||||
|
uri: `/token/${n.id}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -63,6 +63,7 @@ interface VMInfoInterface {
|
|||||||
genid?: string;
|
genid?: string;
|
||||||
title?: string;
|
title?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
|
group?: string;
|
||||||
boot_type: "UEFI" | "UEFISecureBoot";
|
boot_type: "UEFI" | "UEFISecureBoot";
|
||||||
architecture: "i686" | "x86_64";
|
architecture: "i686" | "x86_64";
|
||||||
memory: number;
|
memory: number;
|
||||||
@@ -80,6 +81,7 @@ export class VMInfo implements VMInfoInterface {
|
|||||||
genid?: string;
|
genid?: string;
|
||||||
title?: string;
|
title?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
|
group?: string;
|
||||||
boot_type: "UEFI" | "UEFISecureBoot";
|
boot_type: "UEFI" | "UEFISecureBoot";
|
||||||
architecture: "i686" | "x86_64";
|
architecture: "i686" | "x86_64";
|
||||||
number_vcpu: number;
|
number_vcpu: number;
|
||||||
@@ -96,6 +98,7 @@ export class VMInfo implements VMInfoInterface {
|
|||||||
this.genid = int.genid;
|
this.genid = int.genid;
|
||||||
this.title = int.title;
|
this.title = int.title;
|
||||||
this.description = int.description;
|
this.description = int.description;
|
||||||
|
this.group = int.group;
|
||||||
this.boot_type = int.boot_type;
|
this.boot_type = int.boot_type;
|
||||||
this.architecture = int.architecture;
|
this.architecture = int.architecture;
|
||||||
this.number_vcpu = int.number_vcpu;
|
this.number_vcpu = int.number_vcpu;
|
||||||
|
|||||||
58
virtweb_frontend/src/dialogs/CreatedTokenDialog.tsx
Normal file
58
virtweb_frontend/src/dialogs/CreatedTokenDialog.tsx
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Dialog,
|
||||||
|
DialogActions,
|
||||||
|
DialogContent,
|
||||||
|
DialogTitle,
|
||||||
|
Typography,
|
||||||
|
} from "@mui/material";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { APITokenURL, CreatedAPIToken } from "../api/TokensApi";
|
||||||
|
import { CopyToClipboard } from "../widgets/CopyToClipboard";
|
||||||
|
import { InlineCode } from "../widgets/InlineCode";
|
||||||
|
|
||||||
|
export function CreatedTokenDialog(p: {
|
||||||
|
createdToken: CreatedAPIToken;
|
||||||
|
}): React.ReactElement {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const close = () => {
|
||||||
|
navigate(APITokenURL(p.createdToken.token));
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<Dialog open>
|
||||||
|
<DialogTitle>Token successfully created</DialogTitle>
|
||||||
|
<DialogContent>
|
||||||
|
<Typography>
|
||||||
|
Your token was successfully created. You need now to copy the private
|
||||||
|
key, as it will be technically impossible to recover it after closing
|
||||||
|
this dialog.
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<InfoBlock label="Token ID" value={p.createdToken.token.id} />
|
||||||
|
<InfoBlock label="Key algorithm" value={p.createdToken.priv_key.alg} />
|
||||||
|
<InfoBlock label="Private key" value={p.createdToken.priv_key.priv} />
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions>
|
||||||
|
<Button onClick={close} color="error">
|
||||||
|
I copied the key, close this dialog
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function InfoBlock(
|
||||||
|
p: React.PropsWithChildren<{ label: string; value: string }>
|
||||||
|
): React.ReactElement {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{ display: "flex", flexDirection: "column", margin: "20px 10px" }}
|
||||||
|
>
|
||||||
|
<Typography variant="overline">{p.label}</Typography>
|
||||||
|
<CopyToClipboard content={p.value}>
|
||||||
|
<InlineCode>{p.value}</InlineCode>
|
||||||
|
</CopyToClipboard>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -39,7 +39,7 @@ export function AlertDialogProvider(p: PropsWithChildren): React.ReactElement {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<AlertContextK.Provider value={hook}>{p.children}</AlertContextK.Provider>
|
<AlertContextK value={hook}>{p.children}</AlertContextK>
|
||||||
|
|
||||||
<Dialog
|
<Dialog
|
||||||
open={open}
|
open={open}
|
||||||
@@ -67,5 +67,5 @@ export function AlertDialogProvider(p: PropsWithChildren): React.ReactElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useAlert(): AlertContext {
|
export function useAlert(): AlertContext {
|
||||||
return React.useContext(AlertContextK)!;
|
return React.use(AlertContextK)!;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,13 +59,13 @@ export function ConfirmDialogProvider(
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<ConfirmContextK.Provider value={hook}>
|
<ConfirmContextK value={hook}>
|
||||||
{p.children}
|
{p.children}
|
||||||
</ConfirmContextK.Provider>
|
</ConfirmContextK>
|
||||||
|
|
||||||
<Dialog
|
<Dialog
|
||||||
open={open}
|
open={open}
|
||||||
onClose={() => handleClose(false)}
|
onClose={() => { handleClose(false); }}
|
||||||
aria-labelledby="alert-dialog-title"
|
aria-labelledby="alert-dialog-title"
|
||||||
aria-describedby="alert-dialog-description"
|
aria-describedby="alert-dialog-description"
|
||||||
>
|
>
|
||||||
@@ -76,10 +76,10 @@ export function ConfirmDialogProvider(
|
|||||||
</DialogContentText>
|
</DialogContentText>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
<DialogActions>
|
<DialogActions>
|
||||||
<Button onClick={() => handleClose(false)} autoFocus>
|
<Button onClick={() => { handleClose(false); }} autoFocus>
|
||||||
{cancelButton ?? "Cancel"}
|
{cancelButton ?? "Cancel"}
|
||||||
</Button>
|
</Button>
|
||||||
<Button onClick={() => handleClose(true)} color="error">
|
<Button onClick={() => { handleClose(true); }} color="error">
|
||||||
{confirmButton ?? "Confirm"}
|
{confirmButton ?? "Confirm"}
|
||||||
</Button>
|
</Button>
|
||||||
</DialogActions>
|
</DialogActions>
|
||||||
@@ -89,5 +89,5 @@ export function ConfirmDialogProvider(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useConfirm(): ConfirmContext {
|
export function useConfirm(): ConfirmContext {
|
||||||
return React.useContext(ConfirmContextK)!;
|
return React.use(ConfirmContextK)!;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,10 +6,10 @@ import {
|
|||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import React, { PropsWithChildren } from "react";
|
import React, { PropsWithChildren } from "react";
|
||||||
|
|
||||||
type LoadingMessageContext = {
|
interface LoadingMessageContext {
|
||||||
show: (message: string) => void;
|
show: (message: string) => void;
|
||||||
hide: () => void;
|
hide: () => void;
|
||||||
};
|
}
|
||||||
|
|
||||||
const LoadingMessageContextK =
|
const LoadingMessageContextK =
|
||||||
React.createContext<LoadingMessageContext | null>(null);
|
React.createContext<LoadingMessageContext | null>(null);
|
||||||
@@ -34,9 +34,9 @@ export function LoadingMessageProvider(
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<LoadingMessageContextK.Provider value={hook}>
|
<LoadingMessageContextK value={hook}>
|
||||||
{p.children}
|
{p.children}
|
||||||
</LoadingMessageContextK.Provider>
|
</LoadingMessageContextK>
|
||||||
|
|
||||||
<Dialog open={open}>
|
<Dialog open={open}>
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
@@ -60,5 +60,5 @@ export function LoadingMessageProvider(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useLoadingMessage(): LoadingMessageContext {
|
export function useLoadingMessage(): LoadingMessageContext {
|
||||||
return React.useContext(LoadingMessageContextK)!;
|
return React.use(LoadingMessageContextK)!;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,9 +24,9 @@ export function SnackbarProvider(p: PropsWithChildren): React.ReactElement {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SnackbarContextK.Provider value={hook}>
|
<SnackbarContextK value={hook}>
|
||||||
{p.children}
|
{p.children}
|
||||||
</SnackbarContextK.Provider>
|
</SnackbarContextK>
|
||||||
|
|
||||||
<Snackbar
|
<Snackbar
|
||||||
open={open}
|
open={open}
|
||||||
@@ -39,5 +39,5 @@ export function SnackbarProvider(p: PropsWithChildren): React.ReactElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useSnackbar(): SnackbarContext {
|
export function useSnackbar(): SnackbarContext {
|
||||||
return React.useContext(SnackbarContextK)!;
|
return React.use(SnackbarContextK)!;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import React from "react";
|
|||||||
import ReactDOM from "react-dom/client";
|
import ReactDOM from "react-dom/client";
|
||||||
import { App } from "./App";
|
import { App } from "./App";
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
import reportWebVitals from "./reportWebVitals";
|
|
||||||
import { LoadServerConfig } from "./widgets/LoadServerConfig";
|
import { LoadServerConfig } from "./widgets/LoadServerConfig";
|
||||||
import { ThemeProvider, createTheme } from "@mui/material";
|
import { ThemeProvider, createTheme } from "@mui/material";
|
||||||
import { LoadingMessageProvider } from "./hooks/providers/LoadingMessageProvider";
|
import { LoadingMessageProvider } from "./hooks/providers/LoadingMessageProvider";
|
||||||
@@ -22,7 +21,7 @@ const darkTheme = createTheme({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const root = ReactDOM.createRoot(
|
const root = ReactDOM.createRoot(
|
||||||
document.getElementById("root") as HTMLElement
|
document.getElementById("root")!
|
||||||
);
|
);
|
||||||
root.render(
|
root.render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
@@ -41,8 +40,3 @@ root.render(
|
|||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
</React.StrictMode>
|
</React.StrictMode>
|
||||||
);
|
);
|
||||||
|
|
||||||
// If you want to start measuring performance in your app, pass a function
|
|
||||||
// to log results (for example: reportWebVitals(console.log))
|
|
||||||
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
|
||||||
reportWebVitals();
|
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
import { ReportHandler } from 'web-vitals';
|
|
||||||
|
|
||||||
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
|
|
||||||
if (onPerfEntry && onPerfEntry instanceof Function) {
|
|
||||||
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
|
|
||||||
getCLS(onPerfEntry);
|
|
||||||
getFID(onPerfEntry);
|
|
||||||
getFCP(onPerfEntry);
|
|
||||||
getLCP(onPerfEntry);
|
|
||||||
getTTFB(onPerfEntry);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export default reportWebVitals;
|
|
||||||
161
virtweb_frontend/src/routes/EditAPITokenRoute.tsx
Normal file
161
virtweb_frontend/src/routes/EditAPITokenRoute.tsx
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
import { Button } from "@mui/material";
|
||||||
|
import React from "react";
|
||||||
|
import { useNavigate, useParams } from "react-router-dom";
|
||||||
|
import {
|
||||||
|
APIToken,
|
||||||
|
APITokenURL,
|
||||||
|
CreatedAPIToken,
|
||||||
|
TokensApi,
|
||||||
|
} from "../api/TokensApi";
|
||||||
|
import { CreatedTokenDialog } from "../dialogs/CreatedTokenDialog";
|
||||||
|
import { useAlert } from "../hooks/providers/AlertDialogProvider";
|
||||||
|
import { useLoadingMessage } from "../hooks/providers/LoadingMessageProvider";
|
||||||
|
import { useSnackbar } from "../hooks/providers/SnackbarProvider";
|
||||||
|
import { time } from "../utils/DateUtils";
|
||||||
|
import { AsyncWidget } from "../widgets/AsyncWidget";
|
||||||
|
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
||||||
|
import {
|
||||||
|
APITokenDetails,
|
||||||
|
TokenWidgetStatus,
|
||||||
|
} from "../widgets/tokens/APITokenDetails";
|
||||||
|
|
||||||
|
export function CreateApiTokenRoute(): React.ReactElement {
|
||||||
|
const alert = useAlert();
|
||||||
|
const snackbar = useSnackbar();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const [createdToken, setCreatedToken] = React.useState<
|
||||||
|
CreatedAPIToken | undefined
|
||||||
|
>();
|
||||||
|
|
||||||
|
const [token] = React.useState<APIToken>({
|
||||||
|
id: "",
|
||||||
|
name: "",
|
||||||
|
description: "",
|
||||||
|
created: time(),
|
||||||
|
updated: time(),
|
||||||
|
last_used: time(),
|
||||||
|
rights: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
const createApiToken = async (n: APIToken) => {
|
||||||
|
try {
|
||||||
|
const res = await TokensApi.Create(n);
|
||||||
|
snackbar("The api token was successfully created!");
|
||||||
|
setCreatedToken(res);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
alert(`Failed to create API token!\n${e}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{createdToken && <CreatedTokenDialog createdToken={createdToken} />}
|
||||||
|
|
||||||
|
<EditApiTokenRouteInner
|
||||||
|
token={token}
|
||||||
|
creating={true}
|
||||||
|
onCancel={() => navigate("/tokens")}
|
||||||
|
onSave={createApiToken}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EditApiTokenRoute(): React.ReactElement {
|
||||||
|
const alert = useAlert();
|
||||||
|
const snackbar = useSnackbar();
|
||||||
|
|
||||||
|
const { id } = useParams();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const [token, setToken] = React.useState<APIToken | undefined>();
|
||||||
|
|
||||||
|
const load = async () => {
|
||||||
|
setToken(await TokensApi.GetSingle(id!));
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateApiToken = async (n: APIToken) => {
|
||||||
|
try {
|
||||||
|
await TokensApi.Update(n);
|
||||||
|
snackbar("The token was successfully updated!");
|
||||||
|
navigate(APITokenURL(token!));
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
alert(`Failed to update token!\n${e}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AsyncWidget
|
||||||
|
loadKey={id}
|
||||||
|
ready={token !== undefined}
|
||||||
|
errMsg="Failed to fetch API token informations!"
|
||||||
|
load={load}
|
||||||
|
build={() => (
|
||||||
|
<EditApiTokenRouteInner
|
||||||
|
token={token!}
|
||||||
|
creating={false}
|
||||||
|
onCancel={() => navigate(`/token/${id}`)}
|
||||||
|
onSave={updateApiToken}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function EditApiTokenRouteInner(p: {
|
||||||
|
token: APIToken;
|
||||||
|
creating: boolean;
|
||||||
|
onCancel: () => void;
|
||||||
|
onSave: (token: APIToken) => Promise<void>;
|
||||||
|
}): React.ReactElement {
|
||||||
|
const loadingMessage = useLoadingMessage();
|
||||||
|
|
||||||
|
const [changed, setChanged] = React.useState(false);
|
||||||
|
|
||||||
|
const [, updateState] = React.useState<any>();
|
||||||
|
const forceUpdate = React.useCallback(() => { updateState({}); }, []);
|
||||||
|
|
||||||
|
const valueChanged = () => {
|
||||||
|
setChanged(true);
|
||||||
|
forceUpdate();
|
||||||
|
};
|
||||||
|
|
||||||
|
const save = async () => {
|
||||||
|
loadingMessage.show("Saving API token configuration...");
|
||||||
|
await p.onSave(p.token);
|
||||||
|
loadingMessage.hide();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<VirtWebRouteContainer
|
||||||
|
label={p.creating ? "Create an API Token" : "Edit API Token"}
|
||||||
|
actions={
|
||||||
|
<span>
|
||||||
|
{changed && (
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
onClick={save}
|
||||||
|
style={{ marginRight: "10px" }}
|
||||||
|
>
|
||||||
|
{p.creating ? "Create" : "Save"}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button onClick={p.onCancel} variant="outlined">
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<APITokenDetails
|
||||||
|
token={p.token}
|
||||||
|
status={
|
||||||
|
p.creating ? TokenWidgetStatus.Create : TokenWidgetStatus.Update
|
||||||
|
}
|
||||||
|
onChange={valueChanged}
|
||||||
|
/>
|
||||||
|
</VirtWebRouteContainer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -99,7 +99,7 @@ function EditNetworkFilterRouteInner(p: {
|
|||||||
const [changed, setChanged] = React.useState(false);
|
const [changed, setChanged] = React.useState(false);
|
||||||
|
|
||||||
const [, updateState] = React.useState<any>();
|
const [, updateState] = React.useState<any>();
|
||||||
const forceUpdate = React.useCallback(() => updateState({}), []);
|
const forceUpdate = React.useCallback(() => { updateState({}); }, []);
|
||||||
|
|
||||||
const valueChanged = () => {
|
const valueChanged = () => {
|
||||||
setChanged(true);
|
setChanged(true);
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ function EditNetworkRouteInner(p: {
|
|||||||
const [changed, setChanged] = React.useState(false);
|
const [changed, setChanged] = React.useState(false);
|
||||||
|
|
||||||
const [, updateState] = React.useState<any>();
|
const [, updateState] = React.useState<any>();
|
||||||
const forceUpdate = React.useCallback(() => updateState({}), []);
|
const forceUpdate = React.useCallback(() => { updateState({}); }, []);
|
||||||
|
|
||||||
const valueChanged = () => {
|
const valueChanged = () => {
|
||||||
setChanged(true);
|
setChanged(true);
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export function CreateVMRoute(): React.ReactElement {
|
|||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const [vm, setVM] = React.useState(VMInfo.NewEmpty);
|
const [vm, setVM] = React.useState(VMInfo.NewEmpty());
|
||||||
|
|
||||||
const create = async (v: VMInfo) => {
|
const create = async (v: VMInfo) => {
|
||||||
try {
|
try {
|
||||||
@@ -103,7 +103,9 @@ function EditVMInner(p: {
|
|||||||
const [changed, setChanged] = React.useState(false);
|
const [changed, setChanged] = React.useState(false);
|
||||||
|
|
||||||
const [, updateState] = React.useState<any>();
|
const [, updateState] = React.useState<any>();
|
||||||
const forceUpdate = React.useCallback(() => updateState({}), []);
|
const forceUpdate = React.useCallback(() => {
|
||||||
|
updateState({});
|
||||||
|
}, []);
|
||||||
|
|
||||||
const valueChanged = () => {
|
const valueChanged = () => {
|
||||||
setChanged(true);
|
setChanged(true);
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ function UploadIsoFileCard(p: {
|
|||||||
p.onFileUploaded();
|
p.onFileUploaded();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
await alert("Failed to perform file upload! " + e);
|
await alert(`Failed to perform file upload! ${e}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
setUploadProgress(null);
|
setUploadProgress(null);
|
||||||
@@ -120,7 +120,9 @@ function UploadIsoFileCard(p: {
|
|||||||
value={value}
|
value={value}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
style={{ flex: 1 }}
|
style={{ flex: 1 }}
|
||||||
inputProps={{ accept: ServerApi.Config.iso_mimetypes.join(",") }}
|
slotProps={{
|
||||||
|
htmlInput: { accept: ServerApi.Config.iso_mimetypes.join(",") },
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{value && <Button onClick={upload}>Upload file</Button>}
|
{value && <Button onClick={upload}>Upload file</Button>}
|
||||||
@@ -147,6 +149,8 @@ function UploadIsoFileFromUrlCard(p: {
|
|||||||
loadingMessage.show("Downloading file from URL...");
|
loadingMessage.show("Downloading file from URL...");
|
||||||
await IsoFilesApi.UploadFromURL(url, actualFileName);
|
await IsoFilesApi.UploadFromURL(url, actualFileName);
|
||||||
|
|
||||||
|
p.onFileUploaded();
|
||||||
|
|
||||||
setURL("");
|
setURL("");
|
||||||
setFilename(null);
|
setFilename(null);
|
||||||
snackbar("Successfully downloaded file!");
|
snackbar("Successfully downloaded file!");
|
||||||
@@ -164,14 +168,18 @@ function UploadIsoFileFromUrlCard(p: {
|
|||||||
label="URL"
|
label="URL"
|
||||||
value={url}
|
value={url}
|
||||||
style={{ flex: 3 }}
|
style={{ flex: 3 }}
|
||||||
onChange={(e) => setURL(e.target.value)}
|
onChange={(e) => {
|
||||||
|
setURL(e.target.value);
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
<span style={{ width: "10px" }}></span>
|
<span style={{ width: "10px" }}></span>
|
||||||
<TextField
|
<TextField
|
||||||
label="Filename"
|
label="Filename"
|
||||||
value={actualFileName}
|
value={actualFileName}
|
||||||
style={{ flex: 2 }}
|
style={{ flex: 2 }}
|
||||||
onChange={(e) => setFilename(e.target.value)}
|
onChange={(e) => {
|
||||||
|
setFilename(e.target.value);
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
{url !== "" && actualFileName !== "" && (
|
{url !== "" && actualFileName !== "" && (
|
||||||
<Button onClick={upload}>Upload file</Button>
|
<Button onClick={upload}>Upload file</Button>
|
||||||
@@ -198,7 +206,7 @@ function IsoFilesList(p: {
|
|||||||
try {
|
try {
|
||||||
const blob = await IsoFilesApi.Download(entry, setDlProgress);
|
const blob = await IsoFilesApi.Download(entry, setDlProgress);
|
||||||
|
|
||||||
await downloadBlob(blob, entry.filename);
|
downloadBlob(blob, entry.filename);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
alert("Failed to download iso file!");
|
alert("Failed to download iso file!");
|
||||||
@@ -236,7 +244,7 @@ function IsoFilesList(p: {
|
|||||||
</Typography>
|
</Typography>
|
||||||
);
|
);
|
||||||
|
|
||||||
const columns: GridColDef[] = [
|
const columns: GridColDef<IsoFile>[] = [
|
||||||
{ field: "filename", headerName: "File name", flex: 3 },
|
{ field: "filename", headerName: "File name", flex: 3 },
|
||||||
{
|
{
|
||||||
field: "size",
|
field: "size",
|
||||||
@@ -301,7 +309,6 @@ function IsoFilesList(p: {
|
|||||||
getRowId={(c) => c.filename}
|
getRowId={(c) => c.filename}
|
||||||
rows={p.list}
|
rows={p.list}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
autoHeight={true}
|
|
||||||
/>
|
/>
|
||||||
</VirtWebPaper>
|
</VirtWebPaper>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ function NetworkFiltersListRouteInner(p: {
|
|||||||
const onlyBuiltin = visibleFilters === VisibleFilters.Builtin;
|
const onlyBuiltin = visibleFilters === VisibleFilters.Builtin;
|
||||||
|
|
||||||
return p.list.filter((f) => NWFilterIsBuiltin(f) === onlyBuiltin);
|
return p.list.filter((f) => NWFilterIsBuiltin(f) === onlyBuiltin);
|
||||||
}, [visibleFilters]);
|
}, [visibleFilters, p.list]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<VirtWebRouteContainer
|
<VirtWebRouteContainer
|
||||||
@@ -78,7 +78,9 @@ function NetworkFiltersListRouteInner(p: {
|
|||||||
size="small"
|
size="small"
|
||||||
value={visibleFilters}
|
value={visibleFilters}
|
||||||
exclusive
|
exclusive
|
||||||
onChange={(_ev, v) => setVisibleFilters(v)}
|
onChange={(_ev, v) => {
|
||||||
|
setVisibleFilters(v);
|
||||||
|
}}
|
||||||
aria-label="visible filters"
|
aria-label="visible filters"
|
||||||
>
|
>
|
||||||
<ToggleButton value={VisibleFilters.All}>All</ToggleButton>
|
<ToggleButton value={VisibleFilters.All}>All</ToggleButton>
|
||||||
@@ -130,8 +132,8 @@ function NetworkFiltersListRouteInner(p: {
|
|||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<ul>
|
<ul>
|
||||||
{t.join_filters.map((f, n) => (
|
{t.join_filters.map((f) => (
|
||||||
<li key={n}>{f}</li>
|
<li key={f}>{f}</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import DeleteIcon from "@mui/icons-material/Delete";
|
|
||||||
import VisibilityIcon from "@mui/icons-material/Visibility";
|
import VisibilityIcon from "@mui/icons-material/Visibility";
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
@@ -13,13 +12,13 @@ import {
|
|||||||
Typography,
|
Typography,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
import { NetworkApi, NetworkInfo, NetworkURL } from "../api/NetworksApi";
|
import { NetworkApi, NetworkInfo, NetworkURL } from "../api/NetworksApi";
|
||||||
import { AsyncWidget } from "../widgets/AsyncWidget";
|
import { AsyncWidget } from "../widgets/AsyncWidget";
|
||||||
import { RouterLink } from "../widgets/RouterLink";
|
import { RouterLink } from "../widgets/RouterLink";
|
||||||
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
||||||
import { NetworkStatusWidget } from "../widgets/net/NetworkStatusWidget";
|
|
||||||
import { useNavigate } from "react-router-dom";
|
|
||||||
import { NetworkHookStatusWidget } from "../widgets/net/NetworkHookStatusWidget";
|
import { NetworkHookStatusWidget } from "../widgets/net/NetworkHookStatusWidget";
|
||||||
|
import { NetworkStatusWidget } from "../widgets/net/NetworkStatusWidget";
|
||||||
|
|
||||||
export function NetworksListRoute(): React.ReactElement {
|
export function NetworksListRoute(): React.ReactElement {
|
||||||
const [list, setList] = React.useState<NetworkInfo[] | undefined>();
|
const [list, setList] = React.useState<NetworkInfo[] | undefined>();
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable react-x/no-array-index-key */
|
||||||
import {
|
import {
|
||||||
mdiHarddisk,
|
mdiHarddisk,
|
||||||
mdiInformation,
|
mdiInformation,
|
||||||
@@ -8,7 +9,6 @@ import {
|
|||||||
import Icon from "@mdi/react";
|
import Icon from "@mdi/react";
|
||||||
import {
|
import {
|
||||||
Box,
|
Box,
|
||||||
Grid,
|
|
||||||
LinearProgress,
|
LinearProgress,
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
@@ -17,7 +17,10 @@ import {
|
|||||||
TableRow,
|
TableRow,
|
||||||
Typography,
|
Typography,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
|
import Grid from "@mui/material/Grid";
|
||||||
import { PieChart } from "@mui/x-charts";
|
import { PieChart } from "@mui/x-charts";
|
||||||
|
import { filesize } from "filesize";
|
||||||
|
import humanizeDuration from "humanize-duration";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import {
|
import {
|
||||||
DiskInfo,
|
DiskInfo,
|
||||||
@@ -28,8 +31,6 @@ import {
|
|||||||
import { AsyncWidget } from "../widgets/AsyncWidget";
|
import { AsyncWidget } from "../widgets/AsyncWidget";
|
||||||
import { VirtWebPaper } from "../widgets/VirtWebPaper";
|
import { VirtWebPaper } from "../widgets/VirtWebPaper";
|
||||||
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
||||||
import humanizeDuration from "humanize-duration";
|
|
||||||
import { filesize } from "filesize";
|
|
||||||
|
|
||||||
export function SysInfoRoute(): React.ReactElement {
|
export function SysInfoRoute(): React.ReactElement {
|
||||||
const [info, setInfo] = React.useState<ServerSystemInfo>();
|
const [info, setInfo] = React.useState<ServerSystemInfo>();
|
||||||
@@ -65,7 +66,7 @@ export function SysInfoRouteInner(p: {
|
|||||||
<VirtWebRouteContainer label="Sysinfo">
|
<VirtWebRouteContainer label="Sysinfo">
|
||||||
<Grid container spacing={2}>
|
<Grid container spacing={2}>
|
||||||
{/* Memory */}
|
{/* Memory */}
|
||||||
<Grid xs={4}>
|
<Grid size={{ xs: 4 }}>
|
||||||
<Box flexGrow={1}>
|
<Box flexGrow={1}>
|
||||||
<Typography style={{ textAlign: "center" }}>Memory</Typography>
|
<Typography style={{ textAlign: "center" }}>Memory</Typography>
|
||||||
<PieChart
|
<PieChart
|
||||||
@@ -97,7 +98,7 @@ export function SysInfoRouteInner(p: {
|
|||||||
</Grid>
|
</Grid>
|
||||||
|
|
||||||
{/* Disk usage */}
|
{/* Disk usage */}
|
||||||
<Grid xs={4}>
|
<Grid size={{ xs: 4 }}>
|
||||||
<Box flexGrow={1}>
|
<Box flexGrow={1}>
|
||||||
<Typography style={{ textAlign: "center" }}>Disk usage</Typography>
|
<Typography style={{ textAlign: "center" }}>Disk usage</Typography>
|
||||||
<PieChart
|
<PieChart
|
||||||
@@ -125,7 +126,7 @@ export function SysInfoRouteInner(p: {
|
|||||||
</Grid>
|
</Grid>
|
||||||
|
|
||||||
{/* CPU usage */}
|
{/* CPU usage */}
|
||||||
<Grid xs={4}>
|
<Grid size={{ xs: 4 }}>
|
||||||
<Box flexGrow={1}>
|
<Box flexGrow={1}>
|
||||||
<Typography style={{ textAlign: "center" }}>CPU usage</Typography>
|
<Typography style={{ textAlign: "center" }}>CPU usage</Typography>
|
||||||
<PieChart
|
<PieChart
|
||||||
@@ -134,13 +135,13 @@ export function SysInfoRouteInner(p: {
|
|||||||
data: [
|
data: [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
value: 100 - p.info.system.global_cpu_info.cpu_usage,
|
value: 100 - p.info.system.global_cpu_usage,
|
||||||
label: "Free",
|
label: "Free",
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
value: p.info.system.global_cpu_info.cpu_usage,
|
value: p.info.system.global_cpu_usage,
|
||||||
label: "Used",
|
label: "Used",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -180,18 +181,18 @@ export function SysInfoRouteInner(p: {
|
|||||||
label="CPU info"
|
label="CPU info"
|
||||||
icon={<Icon size={"1rem"} path={mdiMemory} />}
|
icon={<Icon size={"1rem"} path={mdiMemory} />}
|
||||||
entries={[
|
entries={[
|
||||||
{ label: "Brand", value: p.info.system.global_cpu_info.brand },
|
{ label: "Brand", value: p.info.system.cpus[0].brand },
|
||||||
{
|
{
|
||||||
label: "Vendor ID",
|
label: "Vendor ID",
|
||||||
value: p.info.system.global_cpu_info.vendor_id,
|
value: p.info.system.cpus[0].vendor_id,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "CPU usage",
|
label: "CPU usage",
|
||||||
value: p.info.system.global_cpu_info.cpu_usage,
|
value: p.info.system.cpus[0].cpu_usage,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "Name",
|
label: "Name",
|
||||||
value: p.info.system.global_cpu_info.name,
|
value: p.info.system.cpus[0].name,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "CPU model",
|
label: "CPU model",
|
||||||
@@ -236,7 +237,7 @@ export function SysInfoRouteInner(p: {
|
|||||||
function SysInfoDetailsTable(p: {
|
function SysInfoDetailsTable(p: {
|
||||||
label: string;
|
label: string;
|
||||||
icon: React.ReactElement;
|
icon: React.ReactElement;
|
||||||
entries: Array<{ label: string; value: string | number }>;
|
entries: { label: string; value: string | number }[];
|
||||||
}): React.ReactElement {
|
}): React.ReactElement {
|
||||||
return (
|
return (
|
||||||
<VirtWebPaper
|
<VirtWebPaper
|
||||||
|
|||||||
127
virtweb_frontend/src/routes/TokensListRoute.tsx
Normal file
127
virtweb_frontend/src/routes/TokensListRoute.tsx
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
/* eslint-disable react-x/no-array-index-key */
|
||||||
|
import VisibilityIcon from "@mui/icons-material/Visibility";
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
IconButton,
|
||||||
|
Paper,
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableContainer,
|
||||||
|
TableHead,
|
||||||
|
TableRow,
|
||||||
|
} from "@mui/material";
|
||||||
|
import React from "react";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import {
|
||||||
|
APIToken,
|
||||||
|
APITokenURL,
|
||||||
|
ExpiredAPIToken,
|
||||||
|
TokensApi,
|
||||||
|
} from "../api/TokensApi";
|
||||||
|
import { AsyncWidget } from "../widgets/AsyncWidget";
|
||||||
|
import { RouterLink } from "../widgets/RouterLink";
|
||||||
|
import { TimeWidget, timeDiff } from "../widgets/TimeWidget";
|
||||||
|
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
||||||
|
|
||||||
|
export function TokensListRoute(): React.ReactElement {
|
||||||
|
const [list, setList] = React.useState<APIToken[] | undefined>();
|
||||||
|
|
||||||
|
const [count] = React.useState(1);
|
||||||
|
|
||||||
|
const load = async () => {
|
||||||
|
setList(await TokensApi.GetList());
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AsyncWidget
|
||||||
|
loadKey={count}
|
||||||
|
load={load}
|
||||||
|
ready={list !== undefined}
|
||||||
|
errMsg="Failed to load the list of tokens!"
|
||||||
|
build={() => <TokensListRouteInner list={list!} />}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TokensListRouteInner(p: {
|
||||||
|
list: APIToken[];
|
||||||
|
}): React.ReactElement {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<VirtWebRouteContainer
|
||||||
|
label="API tokens"
|
||||||
|
actions={
|
||||||
|
<RouterLink to="/token/new">
|
||||||
|
<Button>New</Button>
|
||||||
|
</RouterLink>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<TableContainer component={Paper}>
|
||||||
|
<Table>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<TableCell>Name</TableCell>
|
||||||
|
<TableCell>Description</TableCell>
|
||||||
|
<TableCell>Created</TableCell>
|
||||||
|
<TableCell>Updated</TableCell>
|
||||||
|
<TableCell>Last used</TableCell>
|
||||||
|
<TableCell>IP restriction</TableCell>
|
||||||
|
<TableCell>Max inactivity</TableCell>
|
||||||
|
<TableCell>Rights</TableCell>
|
||||||
|
<TableCell>Actions</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{p.list.map((t) => {
|
||||||
|
return (
|
||||||
|
<TableRow
|
||||||
|
key={t.id}
|
||||||
|
hover
|
||||||
|
onDoubleClick={() => navigate(APITokenURL(t))}
|
||||||
|
style={{ backgroundColor: ExpiredAPIToken(t) ? "red" : "" }}
|
||||||
|
>
|
||||||
|
<TableCell>
|
||||||
|
{t.name} {ExpiredAPIToken(t) && <i>(Expired)</i>}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{t.description}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<TimeWidget time={t.created} />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<TimeWidget time={t.updated} />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<TimeWidget time={t.last_used} />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{t.ip_restriction}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{t.max_inactivity && timeDiff(0, t.max_inactivity)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{t.rights.map((r, n) => {
|
||||||
|
return (
|
||||||
|
<div key={n}>
|
||||||
|
{r.verb} {r.path}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</TableCell>
|
||||||
|
|
||||||
|
<TableCell>
|
||||||
|
<RouterLink to={APITokenURL(t)}>
|
||||||
|
<IconButton>
|
||||||
|
<VisibilityIcon />
|
||||||
|
</IconButton>
|
||||||
|
</RouterLink>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</TableContainer>
|
||||||
|
</VirtWebRouteContainer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
||||||
|
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
|
||||||
import VisibilityIcon from "@mui/icons-material/Visibility";
|
import VisibilityIcon from "@mui/icons-material/Visibility";
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
@@ -7,6 +9,7 @@ import {
|
|||||||
TableBody,
|
TableBody,
|
||||||
TableCell,
|
TableCell,
|
||||||
TableContainer,
|
TableContainer,
|
||||||
|
TableFooter,
|
||||||
TableHead,
|
TableHead,
|
||||||
TableRow,
|
TableRow,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
@@ -14,19 +17,27 @@ import {
|
|||||||
import { filesize } from "filesize";
|
import { filesize } from "filesize";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { VMApi, VMInfo } from "../api/VMApi";
|
import { GroupApi } from "../api/GroupApi";
|
||||||
|
import { VMApi, VMInfo, VMState } from "../api/VMApi";
|
||||||
import { AsyncWidget } from "../widgets/AsyncWidget";
|
import { AsyncWidget } from "../widgets/AsyncWidget";
|
||||||
import { RouterLink } from "../widgets/RouterLink";
|
import { RouterLink } from "../widgets/RouterLink";
|
||||||
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
||||||
import { VMStatusWidget } from "../widgets/vms/VMStatusWidget";
|
import { VMStatusWidget } from "../widgets/vms/VMStatusWidget";
|
||||||
|
|
||||||
export function VMListRoute(): React.ReactElement {
|
export function VMListRoute(): React.ReactElement {
|
||||||
|
const [groups, setGroups] = React.useState<(string | undefined)[]>();
|
||||||
const [list, setList] = React.useState<VMInfo[] | undefined>();
|
const [list, setList] = React.useState<VMInfo[] | undefined>();
|
||||||
|
|
||||||
const loadKey = React.useRef(1);
|
const loadKey = React.useRef(1);
|
||||||
|
|
||||||
const load = async () => {
|
const load = async () => {
|
||||||
setList(await VMApi.GetList());
|
const groups: (string | undefined)[] = await GroupApi.GetList();
|
||||||
|
const list = await VMApi.GetList();
|
||||||
|
|
||||||
|
if (list.find((v) => !v.group) !== undefined) groups.push(undefined);
|
||||||
|
|
||||||
|
setGroups(groups);
|
||||||
|
setList(list);
|
||||||
};
|
};
|
||||||
|
|
||||||
const reload = () => {
|
const reload = () => {
|
||||||
@@ -51,7 +62,7 @@ export function VMListRoute(): React.ReactElement {
|
|||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<VMListWidget list={list!} onReload={reload} />
|
<VMListWidget list={list!} groups={groups!} onReload={reload} />
|
||||||
</VirtWebRouteContainer>
|
</VirtWebRouteContainer>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
@@ -59,11 +70,37 @@ export function VMListRoute(): React.ReactElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function VMListWidget(p: {
|
function VMListWidget(p: {
|
||||||
|
groups: (string | undefined)[];
|
||||||
list: VMInfo[];
|
list: VMInfo[];
|
||||||
onReload: () => void;
|
onReload: () => void;
|
||||||
}): React.ReactElement {
|
}): React.ReactElement {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const [hiddenGroups, setHiddenGroups] = React.useState<
|
||||||
|
Set<string | undefined>
|
||||||
|
>(new Set());
|
||||||
|
|
||||||
|
const [runningVMs, setRunningVMs] = React.useState<Set<string>>(new Set());
|
||||||
|
|
||||||
|
const toggleHiddenGroup = (g: string | undefined) => {
|
||||||
|
if (hiddenGroups.has(g)) hiddenGroups.delete(g);
|
||||||
|
else hiddenGroups.add(g);
|
||||||
|
|
||||||
|
setHiddenGroups(new Set([...hiddenGroups]));
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateVMState = (v: VMInfo, s: VMState) => {
|
||||||
|
const running = s !== "Shutoff";
|
||||||
|
if (runningVMs.has(v.name) === running) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (running) runningVMs.add(v.name);
|
||||||
|
else runningVMs.delete(v.name);
|
||||||
|
|
||||||
|
setRunningVMs(new Set([...runningVMs]));
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TableContainer component={Paper}>
|
<TableContainer component={Paper}>
|
||||||
<Table>
|
<Table>
|
||||||
@@ -72,12 +109,41 @@ function VMListWidget(p: {
|
|||||||
<TableCell>Name</TableCell>
|
<TableCell>Name</TableCell>
|
||||||
<TableCell>Description</TableCell>
|
<TableCell>Description</TableCell>
|
||||||
<TableCell>Memory</TableCell>
|
<TableCell>Memory</TableCell>
|
||||||
|
<TableCell>vCPU</TableCell>
|
||||||
<TableCell>Status</TableCell>
|
<TableCell>Status</TableCell>
|
||||||
<TableCell>Actions</TableCell>
|
<TableCell>Actions</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{p.list.map((row) => (
|
{p.groups.map((g) => (
|
||||||
|
<React.Fragment key={g}>
|
||||||
|
{p.groups.length > 1 && (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell
|
||||||
|
style={{ paddingBottom: 2, paddingTop: 2 }}
|
||||||
|
colSpan={6}
|
||||||
|
>
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
onClick={() => {
|
||||||
|
toggleHiddenGroup(g);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{!hiddenGroups.has(g) ? (
|
||||||
|
<KeyboardArrowUpIcon />
|
||||||
|
) : (
|
||||||
|
<KeyboardArrowDownIcon />
|
||||||
|
)}
|
||||||
|
</IconButton>
|
||||||
|
{g ?? "default"}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!hiddenGroups.has(g) &&
|
||||||
|
p.list
|
||||||
|
.filter((row) => row.group === g)
|
||||||
|
.map((row) => (
|
||||||
<TableRow
|
<TableRow
|
||||||
hover
|
hover
|
||||||
key={row.name}
|
key={row.name}
|
||||||
@@ -88,9 +154,15 @@ function VMListWidget(p: {
|
|||||||
{row.name}
|
{row.name}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>{row.description ?? ""}</TableCell>
|
<TableCell>{row.description ?? ""}</TableCell>
|
||||||
<TableCell>{filesize(row.memory * 1000 * 1000)}</TableCell>
|
<TableCell>{vmMemoryToHuman(row.memory)}</TableCell>
|
||||||
|
<TableCell>{row.number_vcpu}</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<VMStatusWidget vm={row} />
|
<VMStatusWidget
|
||||||
|
vm={row}
|
||||||
|
onChange={(s) => {
|
||||||
|
updateVMState(row, s);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<Tooltip title="View this VM">
|
<Tooltip title="View this VM">
|
||||||
@@ -103,8 +175,38 @@ function VMListWidget(p: {
|
|||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))}
|
))}
|
||||||
|
</React.Fragment>
|
||||||
|
))}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
|
<TableFooter>
|
||||||
|
<TableRow>
|
||||||
|
<TableCell></TableCell>
|
||||||
|
<TableCell></TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{vmMemoryToHuman(
|
||||||
|
p.list
|
||||||
|
.filter((v) => runningVMs.has(v.name))
|
||||||
|
.reduce((s, v) => s + v.memory, 0)
|
||||||
|
)}
|
||||||
|
{" / "}
|
||||||
|
{vmMemoryToHuman(p.list.reduce((s, v) => s + v.memory, 0))}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{p.list
|
||||||
|
.filter((v) => runningVMs.has(v.name))
|
||||||
|
.reduce((s, v) => s + v.number_vcpu, 0)}
|
||||||
|
{" / "}
|
||||||
|
{p.list.reduce((s, v) => s + v.number_vcpu, 0)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell></TableCell>
|
||||||
|
<TableCell></TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableFooter>
|
||||||
</Table>
|
</Table>
|
||||||
</TableContainer>
|
</TableContainer>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function vmMemoryToHuman(size: number): string {
|
||||||
|
return filesize(size * 1000 * 1000);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,17 +1,16 @@
|
|||||||
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
|
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
|
||||||
import FullscreenIcon from "@mui/icons-material/Fullscreen";
|
import FullscreenIcon from "@mui/icons-material/Fullscreen";
|
||||||
import FullscreenExitIcon from "@mui/icons-material/FullscreenExit";
|
import FullscreenExitIcon from "@mui/icons-material/FullscreenExit";
|
||||||
|
import KeyboardAltIcon from "@mui/icons-material/KeyboardAlt";
|
||||||
import { IconButton, Tooltip } from "@mui/material";
|
import { IconButton, Tooltip } from "@mui/material";
|
||||||
import React, { useEffect } from "react";
|
import React, { useEffect } from "react";
|
||||||
import { useNavigate, useParams } from "react-router-dom";
|
import { useNavigate, useParams } from "react-router-dom";
|
||||||
import { VncScreen } from "react-vnc";
|
import { VncScreen, VncScreenHandle } from "react-vnc";
|
||||||
import { ServerApi } from "../api/ServerApi";
|
import { ServerApi } from "../api/ServerApi";
|
||||||
import { VMApi, VMInfo } from "../api/VMApi";
|
import { VMApi, VMInfo } from "../api/VMApi";
|
||||||
import { useSnackbar } from "../hooks/providers/SnackbarProvider";
|
import { useSnackbar } from "../hooks/providers/SnackbarProvider";
|
||||||
import { time } from "../utils/DateUtils";
|
import { time } from "../utils/DateUtils";
|
||||||
import { AsyncWidget } from "../widgets/AsyncWidget";
|
import { AsyncWidget } from "../widgets/AsyncWidget";
|
||||||
import RFB from "react-vnc/dist/types/noVNC/core/rfb";
|
|
||||||
import KeyboardAltIcon from "@mui/icons-material/KeyboardAlt";
|
|
||||||
|
|
||||||
interface VNCTokenInfo {
|
interface VNCTokenInfo {
|
||||||
url: string;
|
url: string;
|
||||||
@@ -43,9 +42,10 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
|
|||||||
|
|
||||||
const [token, setToken] = React.useState<VNCTokenInfo | undefined>();
|
const [token, setToken] = React.useState<VNCTokenInfo | undefined>();
|
||||||
const [counter, setCounter] = React.useState(1);
|
const [counter, setCounter] = React.useState(1);
|
||||||
const [rfb, setRFB] = React.useState<RFB | undefined>();
|
const [connected, setConnected] = React.useState(false);
|
||||||
|
|
||||||
const vncRef = React.createRef<HTMLDivElement>();
|
const vncRef = React.useRef<HTMLDivElement>(null);
|
||||||
|
const vncScreenRef = React.useRef<VncScreenHandle>(null);
|
||||||
|
|
||||||
const connect = async (force: boolean) => {
|
const connect = async (force: boolean) => {
|
||||||
try {
|
try {
|
||||||
@@ -71,7 +71,7 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const disconnected = () => {
|
const disconnected = () => {
|
||||||
setRFB(undefined);
|
setConnected(false);
|
||||||
connect(true);
|
connect(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -91,7 +91,9 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
|
|||||||
connect(false);
|
connect(false);
|
||||||
|
|
||||||
if (vncRef.current) {
|
if (vncRef.current) {
|
||||||
vncRef.current.onfullscreenchange = () => setCounter(counter + 1);
|
vncRef.current.onfullscreenchange = () => {
|
||||||
|
setCounter(counter + 1);
|
||||||
|
};
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -118,9 +120,9 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Keystrokes */}
|
{/* Keystrokes */}
|
||||||
{rfb && (
|
{connected && (
|
||||||
<Tooltip title="Send Ctrl+Alt+Del">
|
<Tooltip title="Send Ctrl+Alt+Del">
|
||||||
<IconButton onClick={() => rfb?.sendCtrlAltDel()}>
|
<IconButton onClick={() => vncScreenRef.current?.sendCtrlAltDel()}>
|
||||||
<KeyboardAltIcon />
|
<KeyboardAltIcon />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
@@ -137,12 +139,15 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<VncScreen
|
<VncScreen
|
||||||
|
ref={vncScreenRef}
|
||||||
url={token.url}
|
url={token.url}
|
||||||
onDisconnect={() => {
|
onDisconnect={() => {
|
||||||
console.info("VNC disconnected " + token?.url);
|
console.info("VNC disconnected " + token.url);
|
||||||
disconnected();
|
disconnected();
|
||||||
}}
|
}}
|
||||||
onConnect={(rfb) => setRFB(rfb)}
|
onConnect={() => {
|
||||||
|
setConnected(true);
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
53
virtweb_frontend/src/routes/ViewApiTokenRoute.tsx
Normal file
53
virtweb_frontend/src/routes/ViewApiTokenRoute.tsx
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import { Button } from "@mui/material";
|
||||||
|
import React from "react";
|
||||||
|
import { useNavigate, useParams } from "react-router-dom";
|
||||||
|
import { APIToken, APITokenURL, TokensApi } from "../api/TokensApi";
|
||||||
|
import { AsyncWidget } from "../widgets/AsyncWidget";
|
||||||
|
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
|
||||||
|
import {
|
||||||
|
APITokenDetails,
|
||||||
|
TokenWidgetStatus,
|
||||||
|
} from "../widgets/tokens/APITokenDetails";
|
||||||
|
|
||||||
|
export function ViewApiTokenRoute() {
|
||||||
|
const { id } = useParams();
|
||||||
|
|
||||||
|
const [token, setToken] = React.useState<APIToken | undefined>();
|
||||||
|
|
||||||
|
const load = async () => {
|
||||||
|
setToken(await TokensApi.GetSingle(id!));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AsyncWidget
|
||||||
|
loadKey={id}
|
||||||
|
ready={token !== undefined}
|
||||||
|
errMsg="Failed to fetch API token information!"
|
||||||
|
load={load}
|
||||||
|
build={() => <ViewAPITokenRouteInner token={token!} />}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ViewAPITokenRouteInner(p: { token: APIToken }): React.ReactElement {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<VirtWebRouteContainer
|
||||||
|
label={`API token ${p.token.name}`}
|
||||||
|
actions={
|
||||||
|
<span style={{ display: "flex", alignItems: "center" }}>
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
style={{ marginLeft: "15px" }}
|
||||||
|
onClick={() => navigate(APITokenURL(p.token, true))}
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</Button>
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<APITokenDetails token={p.token} status={TokenWidgetStatus.Read} />
|
||||||
|
</VirtWebRouteContainer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Visibility, VisibilityOff } from "@mui/icons-material";
|
import VisibilityIcon from '@mui/icons-material/Visibility';
|
||||||
|
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
|
||||||
import {
|
import {
|
||||||
Alert,
|
Alert,
|
||||||
CircularProgress,
|
CircularProgress,
|
||||||
@@ -35,7 +36,7 @@ export function LoginRoute(): React.ReactElement {
|
|||||||
const canSubmit = username.length > 0 && password.length > 0;
|
const canSubmit = username.length > 0 && password.length > 0;
|
||||||
|
|
||||||
const [showPassword, setShowPassword] = React.useState(false);
|
const [showPassword, setShowPassword] = React.useState(false);
|
||||||
const handleClickShowPassword = () => setShowPassword((show) => !show);
|
const handleClickShowPassword = () => { setShowPassword((show) => !show); };
|
||||||
|
|
||||||
const handleMouseDownPassword = (
|
const handleMouseDownPassword = (
|
||||||
event: React.MouseEvent<HTMLButtonElement>
|
event: React.MouseEvent<HTMLButtonElement>
|
||||||
@@ -104,7 +105,7 @@ export function LoginRoute(): React.ReactElement {
|
|||||||
label="Username"
|
label="Username"
|
||||||
name="username"
|
name="username"
|
||||||
value={username}
|
value={username}
|
||||||
onChange={(e) => setUsername(e.target.value)}
|
onChange={(e) => { setUsername(e.target.value); }}
|
||||||
autoComplete="username"
|
autoComplete="username"
|
||||||
autoFocus
|
autoFocus
|
||||||
/>
|
/>
|
||||||
@@ -119,7 +120,7 @@ export function LoginRoute(): React.ReactElement {
|
|||||||
type={showPassword ? "text" : "password"}
|
type={showPassword ? "text" : "password"}
|
||||||
id="password"
|
id="password"
|
||||||
value={password}
|
value={password}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => { setPassword(e.target.value); }}
|
||||||
autoComplete="current-password"
|
autoComplete="current-password"
|
||||||
endAdornment={
|
endAdornment={
|
||||||
<InputAdornment position="end">
|
<InputAdornment position="end">
|
||||||
@@ -130,7 +131,7 @@ export function LoginRoute(): React.ReactElement {
|
|||||||
onMouseDown={handleMouseDownPassword}
|
onMouseDown={handleMouseDownPassword}
|
||||||
edge="end"
|
edge="end"
|
||||||
>
|
>
|
||||||
{showPassword ? <VisibilityOff /> : <Visibility />}
|
{showPassword ? <VisibilityOffIcon /> : <VisibilityIcon />}
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</InputAdornment>
|
</InputAdornment>
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
// jest-dom adds custom jest matchers for asserting on DOM nodes.
|
|
||||||
// allows you to do things like:
|
|
||||||
// expect(element).toHaveTextContent(/react/i)
|
|
||||||
// learn more: https://github.com/testing-library/jest-dom
|
|
||||||
import '@testing-library/jest-dom';
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
export async function downloadBlob(blob: Blob, filename: string) {
|
export function downloadBlob(blob: Blob, filename: string) {
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
|
|
||||||
const link = document.createElement("a");
|
const link = document.createElement("a");
|
||||||
|
|||||||
@@ -2,8 +2,9 @@
|
|||||||
* Generate a random MAC address
|
* Generate a random MAC address
|
||||||
*/
|
*/
|
||||||
export function randomMacAddress(prefix: string | undefined): string {
|
export function randomMacAddress(prefix: string | undefined): string {
|
||||||
|
prefix = prefix ?? "";
|
||||||
let mac = "XX:XX:XX:XX:XX:XX";
|
let mac = "XX:XX:XX:XX:XX:XX";
|
||||||
mac = prefix + mac.slice(prefix?.length);
|
mac = prefix + mac.slice(prefix.length);
|
||||||
|
|
||||||
return mac.replace(/X/g, () =>
|
return mac.replace(/X/g, () =>
|
||||||
"0123456789abcdef".charAt(Math.floor(Math.random() * 16))
|
"0123456789abcdef".charAt(Math.floor(Math.random() * 16))
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ export function AsyncWidget(p: {
|
|||||||
}): React.ReactElement {
|
}): React.ReactElement {
|
||||||
const [state, setState] = useState(State.Loading);
|
const [state, setState] = useState(State.Loading);
|
||||||
|
|
||||||
const counter = useRef<any | null>(null);
|
const counter = useRef<any>(null);
|
||||||
|
|
||||||
const load = async () => {
|
const load = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -67,7 +67,7 @@ export function AsyncWidget(p: {
|
|||||||
|
|
||||||
<Button onClick={load}>Try again</Button>
|
<Button onClick={load}>Try again</Button>
|
||||||
|
|
||||||
{p.errAdditionalElement && p.errAdditionalElement()}
|
{p.errAdditionalElement?.()}
|
||||||
</Box>
|
</Box>
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import {
|
import {
|
||||||
|
mdiApi,
|
||||||
mdiBoxShadow,
|
mdiBoxShadow,
|
||||||
mdiDisc,
|
mdiDisc,
|
||||||
mdiHome,
|
mdiHome,
|
||||||
@@ -12,11 +13,9 @@ import {
|
|||||||
List,
|
List,
|
||||||
ListItemButton,
|
ListItemButton,
|
||||||
ListItemIcon,
|
ListItemIcon,
|
||||||
ListItemSecondaryAction,
|
ListItemText
|
||||||
ListItemText,
|
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import { Outlet, useLocation } from "react-router-dom";
|
import { Outlet, useLocation } from "react-router-dom";
|
||||||
import { isDebug } from "../utils/DebugUtils";
|
|
||||||
import { RouterLink } from "./RouterLink";
|
import { RouterLink } from "./RouterLink";
|
||||||
import { VirtWebAppBar } from "./VirtWebAppBar";
|
import { VirtWebAppBar } from "./VirtWebAppBar";
|
||||||
|
|
||||||
@@ -72,6 +71,11 @@ export function BaseAuthenticatedPage(): React.ReactElement {
|
|||||||
uri="/iso"
|
uri="/iso"
|
||||||
icon={<Icon path={mdiDisc} size={1} />}
|
icon={<Icon path={mdiDisc} size={1} />}
|
||||||
/>
|
/>
|
||||||
|
<NavLink
|
||||||
|
label="API tokens"
|
||||||
|
uri="/tokens"
|
||||||
|
icon={<Icon path={mdiApi} size={1} />}
|
||||||
|
/>
|
||||||
<NavLink
|
<NavLink
|
||||||
label="Sysinfo"
|
label="Sysinfo"
|
||||||
uri="/sysinfo"
|
uri="/sysinfo"
|
||||||
@@ -90,7 +94,6 @@ function NavLink(p: {
|
|||||||
icon: React.ReactElement;
|
icon: React.ReactElement;
|
||||||
uri: string;
|
uri: string;
|
||||||
label: string;
|
label: string;
|
||||||
secondaryAction?: React.ReactElement;
|
|
||||||
}): React.ReactElement {
|
}): React.ReactElement {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
return (
|
return (
|
||||||
@@ -98,9 +101,6 @@ function NavLink(p: {
|
|||||||
<ListItemButton selected={p.uri === location.pathname}>
|
<ListItemButton selected={p.uri === location.pathname}>
|
||||||
<ListItemIcon>{p.icon}</ListItemIcon>
|
<ListItemIcon>{p.icon}</ListItemIcon>
|
||||||
<ListItemText primary={p.label} />
|
<ListItemText primary={p.label} />
|
||||||
{p.secondaryAction && (
|
|
||||||
<ListItemSecondaryAction>{p.secondaryAction}</ListItemSecondaryAction>
|
|
||||||
)}
|
|
||||||
</ListItemButton>
|
</ListItemButton>
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -38,10 +38,7 @@ export function BaseLoginPage() {
|
|||||||
<Grid container component="main" sx={{ height: "100vh" }}>
|
<Grid container component="main" sx={{ height: "100vh" }}>
|
||||||
<CssBaseline />
|
<CssBaseline />
|
||||||
<Grid
|
<Grid
|
||||||
item
|
size={{ xs: false, sm: 4, md: 7 }}
|
||||||
xs={false}
|
|
||||||
sm={4}
|
|
||||||
md={7}
|
|
||||||
sx={{
|
sx={{
|
||||||
backgroundImage: "url(/login_splash.jpg)",
|
backgroundImage: "url(/login_splash.jpg)",
|
||||||
backgroundRepeat: "no-repeat",
|
backgroundRepeat: "no-repeat",
|
||||||
@@ -53,7 +50,12 @@ export function BaseLoginPage() {
|
|||||||
backgroundPosition: "center",
|
backgroundPosition: "center",
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square>
|
<Grid
|
||||||
|
size={{ xs: 12, sm: 8, md: 5 }}
|
||||||
|
component={Paper}
|
||||||
|
elevation={6}
|
||||||
|
square
|
||||||
|
>
|
||||||
<Box
|
<Box
|
||||||
sx={{
|
sx={{
|
||||||
my: 8,
|
my: 8,
|
||||||
|
|||||||
@@ -31,14 +31,16 @@ export function ConfigImportExportButtons(p: {
|
|||||||
fileEl.click();
|
fileEl.click();
|
||||||
|
|
||||||
// Wait for a file to be chosen
|
// Wait for a file to be chosen
|
||||||
await new Promise((res, _rej) =>
|
await new Promise((res) => {
|
||||||
fileEl.addEventListener("change", () => res(null))
|
fileEl.addEventListener("change", () => {
|
||||||
);
|
res(null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
if ((fileEl.files?.length ?? 0) === 0) return null;
|
if ((fileEl.files?.length ?? 0) === 0) return null;
|
||||||
|
|
||||||
// Import conf
|
// Import conf
|
||||||
let file = fileEl.files![0];
|
const file = fileEl.files![0];
|
||||||
const content = await file.text();
|
const content = await file.text();
|
||||||
p.importConf?.(JSON.parse(content));
|
p.importConf?.(JSON.parse(content));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
18
virtweb_frontend/src/widgets/InlineCode.tsx
Normal file
18
virtweb_frontend/src/widgets/InlineCode.tsx
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
export function InlineCode(p: React.PropsWithChildren): React.ReactElement {
|
||||||
|
return (
|
||||||
|
<code
|
||||||
|
style={{
|
||||||
|
display: "inline-block",
|
||||||
|
backgroundColor: "black",
|
||||||
|
color: "white",
|
||||||
|
wordBreak: "break-all",
|
||||||
|
wordWrap: "break-word",
|
||||||
|
whiteSpace: "pre-wrap",
|
||||||
|
padding: "0px 7px",
|
||||||
|
borderRadius: "5px",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{p.children}
|
||||||
|
</code>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@ export function StateActionButton<S>(p: {
|
|||||||
p.onExecuted();
|
p.onExecuted();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
alert("Failed to perform action! " + e);
|
alert(`Failed to perform action! ${e}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable react-x/no-array-index-key */
|
||||||
import { Box, Tab, Tabs } from "@mui/material";
|
import { Box, Tab, Tabs } from "@mui/material";
|
||||||
|
|
||||||
export interface TabWidgetOption<E> {
|
export interface TabWidgetOption<E> {
|
||||||
@@ -24,7 +25,9 @@ export function TabsWidget<E>(p: {
|
|||||||
<Box sx={{ borderBottom: 1, borderColor: "divider" }}>
|
<Box sx={{ borderBottom: 1, borderColor: "divider" }}>
|
||||||
<Tabs
|
<Tabs
|
||||||
value={currTabIndex}
|
value={currTabIndex}
|
||||||
onChange={(_ev, newVal) => updateActiveTab(newVal)}
|
onChange={(_ev, newVal) => {
|
||||||
|
updateActiveTab(newVal);
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{activeOptions.map((o, index) => (
|
{activeOptions.map((o, index) => (
|
||||||
<Tab key={index} label={o.label} style={{ color: o.color }} />
|
<Tab key={index} label={o.label} style={{ color: o.color }} />
|
||||||
|
|||||||
65
virtweb_frontend/src/widgets/TimeWidget.tsx
Normal file
65
virtweb_frontend/src/widgets/TimeWidget.tsx
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import { Tooltip } from "@mui/material";
|
||||||
|
import date from "date-and-time";
|
||||||
|
import { time } from "../utils/DateUtils";
|
||||||
|
|
||||||
|
export function formatDate(time: number): string {
|
||||||
|
const t = new Date();
|
||||||
|
t.setTime(1000 * time);
|
||||||
|
return date.format(t, "DD/MM/YYYY HH:mm:ss");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function timeDiff(a: number, b: number): string {
|
||||||
|
let diff = b - a;
|
||||||
|
|
||||||
|
if (diff === 0) return "now";
|
||||||
|
if (diff === 1) return "1 second";
|
||||||
|
|
||||||
|
if (diff < 60) {
|
||||||
|
return `${diff} seconds`;
|
||||||
|
}
|
||||||
|
|
||||||
|
diff = Math.floor(diff / 60);
|
||||||
|
|
||||||
|
if (diff === 1) return "1 minute";
|
||||||
|
if (diff < 24) {
|
||||||
|
return `${diff} minutes`;
|
||||||
|
}
|
||||||
|
|
||||||
|
diff = Math.floor(diff / 60);
|
||||||
|
|
||||||
|
if (diff === 1) return "1 hour";
|
||||||
|
if (diff < 24) {
|
||||||
|
return `${diff} hours`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const diffDays = Math.floor(diff / 24);
|
||||||
|
|
||||||
|
if (diffDays === 1) return "1 day";
|
||||||
|
if (diffDays < 31) {
|
||||||
|
return `${diffDays} days`;
|
||||||
|
}
|
||||||
|
|
||||||
|
diff = Math.floor(diffDays / 31);
|
||||||
|
|
||||||
|
if (diff < 12) {
|
||||||
|
return `${diff} month`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const diffYears = Math.floor(diffDays / 365);
|
||||||
|
|
||||||
|
if (diffYears === 1) return "1 year";
|
||||||
|
return `${diffYears} years`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function timeDiffFromNow(t: number): string {
|
||||||
|
return timeDiff(t, time());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TimeWidget(p: { time?: number }): React.ReactElement {
|
||||||
|
if (!p.time) return <></>;
|
||||||
|
return (
|
||||||
|
<Tooltip title={formatDate(p.time)}>
|
||||||
|
<span>{timeDiffFromNow(p.time)}</span>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -17,7 +17,7 @@ export function CheckboxInput(p: {
|
|||||||
<Checkbox
|
<Checkbox
|
||||||
disabled={!p.editable}
|
disabled={!p.editable}
|
||||||
checked={p.checked}
|
checked={p.checked}
|
||||||
onChange={(e) => p.onValueChange(e.target.checked)}
|
onChange={(e) => { p.onValueChange(e.target.checked); }}
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
label={p.label}
|
label={p.label}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { Grid, Paper, Typography } from "@mui/material";
|
/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */
|
||||||
|
import { Paper, Typography } from "@mui/material";
|
||||||
import React, { PropsWithChildren } from "react";
|
import React, { PropsWithChildren } from "react";
|
||||||
|
import Grid from "@mui/material/Grid";
|
||||||
|
|
||||||
export function EditSection(
|
export function EditSection(
|
||||||
p: {
|
p: {
|
||||||
@@ -9,7 +11,7 @@ export function EditSection(
|
|||||||
} & PropsWithChildren
|
} & PropsWithChildren
|
||||||
): React.ReactElement {
|
): React.ReactElement {
|
||||||
return (
|
return (
|
||||||
<Grid item sm={12} md={p.fullWidth ? 12 : 6}>
|
<Grid size={{ sm: 12, md: p.fullWidth ? 12 : 6 }}>
|
||||||
<Paper style={{ margin: "10px", padding: "10px" }}>
|
<Paper style={{ margin: "10px", padding: "10px" }}>
|
||||||
{(p.title || p.actions) && (
|
{(p.title || p.actions) && (
|
||||||
<span
|
<span
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import { TextInput } from "./TextInput";
|
import { TextInput } from "./TextInput";
|
||||||
|
|
||||||
@@ -22,15 +23,17 @@ export function IPInput(p: {
|
|||||||
export function IPInputWithMask(p: {
|
export function IPInputWithMask(p: {
|
||||||
label: string;
|
label: string;
|
||||||
editable: boolean;
|
editable: boolean;
|
||||||
|
ipAndMask?: string;
|
||||||
ip?: string;
|
ip?: string;
|
||||||
mask?: number;
|
mask?: number;
|
||||||
onValueChange?: (ip?: string, mask?: number) => void;
|
onValueChange?: (ip?: string, mask?: number, ipAndMask?: string) => void;
|
||||||
version: 4 | 6;
|
version: 4 | 6;
|
||||||
}): React.ReactElement {
|
}): React.ReactElement {
|
||||||
const showSlash = React.useRef(!!p.mask);
|
const showSlash = React.useRef(!!p.mask);
|
||||||
|
|
||||||
const currValue =
|
const currValue =
|
||||||
(p.ip ?? "") + (p.mask || showSlash.current ? "/" : "") + (p.mask ?? "");
|
p.ipAndMask ??
|
||||||
|
`${p.ip ?? ""}${p.mask || showSlash.current ? "/" : ""}${p.mask ?? ""}`;
|
||||||
|
|
||||||
const { onValueChange, ...props } = p;
|
const { onValueChange, ...props } = p;
|
||||||
return (
|
return (
|
||||||
@@ -38,11 +41,11 @@ export function IPInputWithMask(p: {
|
|||||||
onValueChange={(v) => {
|
onValueChange={(v) => {
|
||||||
showSlash.current = false;
|
showSlash.current = false;
|
||||||
if (!v) {
|
if (!v) {
|
||||||
onValueChange?.(undefined, undefined);
|
onValueChange?.(undefined, undefined, undefined);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const split = v?.split("/");
|
const split = v.split("/");
|
||||||
const ip =
|
const ip =
|
||||||
p.version === 4 ? sanitizeIpV4(split[0]) : sanitizeIpV6(split[0]);
|
p.version === 4 ? sanitizeIpV4(split[0]) : sanitizeIpV6(split[0]);
|
||||||
let mask = undefined;
|
let mask = undefined;
|
||||||
@@ -52,7 +55,11 @@ export function IPInputWithMask(p: {
|
|||||||
mask = sanitizeMask(p.version, split[1]);
|
mask = sanitizeMask(p.version, split[1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
onValueChange?.(ip, mask);
|
onValueChange?.(
|
||||||
|
ip,
|
||||||
|
mask,
|
||||||
|
mask || showSlash.current ? `${ip}/${mask ?? ""}` : ip
|
||||||
|
);
|
||||||
}}
|
}}
|
||||||
value={currValue}
|
value={currValue}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -63,7 +70,7 @@ export function IPInputWithMask(p: {
|
|||||||
function sanitizeIpV4(s: string | undefined): string | undefined {
|
function sanitizeIpV4(s: string | undefined): string | undefined {
|
||||||
if (s === "" || s === undefined) return s;
|
if (s === "" || s === undefined) return s;
|
||||||
|
|
||||||
let split = s.split(".");
|
const split = s.split(".");
|
||||||
if (split.length > 4) split.splice(4);
|
if (split.length > 4) split.splice(4);
|
||||||
|
|
||||||
let needAnotherIteration = false;
|
let needAnotherIteration = false;
|
||||||
@@ -100,7 +107,7 @@ function sanitizeIpV6(s: string | undefined): string | undefined {
|
|||||||
const num = parseInt(e, 16);
|
const num = parseInt(e, 16);
|
||||||
if (isNaN(num)) return "0";
|
if (isNaN(num)) return "0";
|
||||||
|
|
||||||
let s = num.toString(16);
|
const s = num.toString(16);
|
||||||
if (num > 0xffff) {
|
if (num > 0xffff) {
|
||||||
needAnotherIteration = true;
|
needAnotherIteration = true;
|
||||||
return s.slice(0, 4) + ":" + s.slice(4);
|
return s.slice(0, 4) + ":" + s.slice(4);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
|
||||||
import { TextInput } from "./TextInput";
|
import { TextInput } from "./TextInput";
|
||||||
|
|
||||||
export function MACInput(p: {
|
export function MACInput(p: {
|
||||||
@@ -32,7 +33,7 @@ function sanitizeMacAddress(s: string | undefined): string | undefined {
|
|||||||
const num = parseInt(e, 16);
|
const num = parseInt(e, 16);
|
||||||
if (isNaN(num)) return "0";
|
if (isNaN(num)) return "0";
|
||||||
|
|
||||||
let s = num.toString(16).padStart(2, "0");
|
const s = num.toString(16).padStart(2, "0");
|
||||||
if (num > 0xff) {
|
if (num > 0xff) {
|
||||||
needAnotherIteration = true;
|
needAnotherIteration = true;
|
||||||
return s.slice(0, 2) + ":" + s.slice(2);
|
return s.slice(0, 2) + ":" + s.slice(2);
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export function NWFConnStateInput(p: {
|
|||||||
label="Connection state"
|
label="Connection state"
|
||||||
value={p.value}
|
value={p.value}
|
||||||
onValueChange={(s) => {
|
onValueChange={(s) => {
|
||||||
p.onChange?.(s as any);
|
p.onChange(s as any);
|
||||||
}}
|
}}
|
||||||
options={[
|
options={[
|
||||||
{ label: "None", value: undefined },
|
{ label: "None", value: undefined },
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
/* eslint-disable react-x/no-array-index-key */
|
||||||
|
/* eslint-disable react-hooks/exhaustive-deps */
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { NWFilter, NWFilterURL } from "../../api/NWFilterApi";
|
import { NWFilter, NWFilterURL } from "../../api/NWFilterApi";
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export function NWFilterPriorityInput(p: {
|
|||||||
value={p.value?.toString()}
|
value={p.value?.toString()}
|
||||||
type="number"
|
type="number"
|
||||||
onValueChange={(v) => {
|
onValueChange={(v) => {
|
||||||
p.onChange?.(v && v !== "" ? Number(v) : undefined);
|
p.onChange(v && v !== "" ? Number(v) : undefined);
|
||||||
}}
|
}}
|
||||||
size={ServerApi.Config.constraints.nwfilter_priority}
|
size={ServerApi.Config.constraints.nwfilter_priority}
|
||||||
helperText="A lower priority value is accessed before one with a higher value"
|
helperText="A lower priority value is accessed before one with a higher value"
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable react-x/no-array-index-key */
|
||||||
import ArrowDownwardIcon from "@mui/icons-material/ArrowDownward";
|
import ArrowDownwardIcon from "@mui/icons-material/ArrowDownward";
|
||||||
import ArrowUpwardIcon from "@mui/icons-material/ArrowUpward";
|
import ArrowUpwardIcon from "@mui/icons-material/ArrowUpward";
|
||||||
import DeleteIcon from "@mui/icons-material/Delete";
|
import DeleteIcon from "@mui/icons-material/Delete";
|
||||||
@@ -66,9 +67,19 @@ export function NWFilterRules(p: {
|
|||||||
deleteRule(n);
|
deleteRule(n);
|
||||||
}}
|
}}
|
||||||
onGoDown={
|
onGoDown={
|
||||||
n < p.rules.length - 1 ? () => swapRules(n, n + 1) : undefined
|
n < p.rules.length - 1
|
||||||
|
? () => {
|
||||||
|
swapRules(n, n + 1);
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onGoUp={
|
||||||
|
n > 0
|
||||||
|
? () => {
|
||||||
|
swapRules(n, n - 1);
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
}
|
}
|
||||||
onGoUp={n > 0 ? () => swapRules(n, n - 1) : undefined}
|
|
||||||
{...p}
|
{...p}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
@@ -153,7 +164,9 @@ function NWRuleEdit(p: {
|
|||||||
editable={p.editable}
|
editable={p.editable}
|
||||||
onChange={p.onChange}
|
onChange={p.onChange}
|
||||||
selector={s}
|
selector={s}
|
||||||
onDelete={() => deleteSelector(n)}
|
onDelete={() => {
|
||||||
|
deleteSelector(n);
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|||||||
@@ -25,9 +25,7 @@ export function NWFilterSelectInput(p: {
|
|||||||
value={selectedValue}
|
value={selectedValue}
|
||||||
onDelete={p.editable ? () => p.onChange?.(undefined) : undefined}
|
onDelete={p.editable ? () => p.onChange?.(undefined) : undefined}
|
||||||
onClick={
|
onClick={
|
||||||
!p.editable && selectedValue
|
!p.editable ? () => navigate(NWFilterURL(selectedValue)) : undefined
|
||||||
? () => navigate(NWFilterURL(selectedValue))
|
|
||||||
: undefined
|
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
@@ -48,7 +46,7 @@ export function NWFilterSelectInput(p: {
|
|||||||
renderInput={(params) => (
|
renderInput={(params) => (
|
||||||
<TextField {...params} variant="standard" label={p.label} />
|
<TextField {...params} variant="standard" label={p.label} />
|
||||||
)}
|
)}
|
||||||
renderOption={(_props, option, _state) => (
|
renderOption={(_props, option) => (
|
||||||
<NWFilterItem
|
<NWFilterItem
|
||||||
dense
|
dense
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
|
/* eslint-disable react-x/no-array-index-key */
|
||||||
import { mdiIp } from "@mdi/js";
|
import { mdiIp } from "@mdi/js";
|
||||||
import Icon from "@mdi/react";
|
import Icon from "@mdi/react";
|
||||||
import DeleteIcon from "@mui/icons-material/Delete";
|
import DeleteIcon from "@mui/icons-material/Delete";
|
||||||
import {
|
import {
|
||||||
Avatar,
|
Avatar,
|
||||||
Button,
|
Button,
|
||||||
Grid,
|
|
||||||
IconButton,
|
IconButton,
|
||||||
ListItem,
|
ListItem,
|
||||||
ListItemAvatar,
|
ListItemAvatar,
|
||||||
@@ -19,6 +19,7 @@ import { useConfirm } from "../../hooks/providers/ConfirmDialogProvider";
|
|||||||
import { IPInput } from "./IPInput";
|
import { IPInput } from "./IPInput";
|
||||||
import { MACInput } from "./MACInput";
|
import { MACInput } from "./MACInput";
|
||||||
import { TextInput } from "./TextInput";
|
import { TextInput } from "./TextInput";
|
||||||
|
import Grid from "@mui/material/Grid";
|
||||||
|
|
||||||
export function NetDHCPHostReservations(p: {
|
export function NetDHCPHostReservations(p: {
|
||||||
editable: boolean;
|
editable: boolean;
|
||||||
@@ -39,7 +40,7 @@ export function NetDHCPHostReservations(p: {
|
|||||||
<>
|
<>
|
||||||
<Grid container>
|
<Grid container>
|
||||||
{p.dhcp.hosts.map((h, num) => (
|
{p.dhcp.hosts.map((h, num) => (
|
||||||
<Grid key={num} sm={12} md={6} item style={{ padding: "10px" }}>
|
<Grid key={num} size={{ sm: 12, md: 6 }} style={{ padding: "10px" }}>
|
||||||
<HostReservationWidget
|
<HostReservationWidget
|
||||||
key={num}
|
key={num}
|
||||||
{...p}
|
{...p}
|
||||||
@@ -130,7 +131,7 @@ function HostReservationWidget(p: {
|
|||||||
value={p.host.mac}
|
value={p.host.mac}
|
||||||
onValueChange={(v) => {
|
onValueChange={(v) => {
|
||||||
p.host.mac = v!;
|
p.host.mac = v!;
|
||||||
p.onChange?.();
|
p.onChange();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -142,7 +143,7 @@ function HostReservationWidget(p: {
|
|||||||
value={p.host.ip}
|
value={p.host.ip}
|
||||||
onValueChange={(v) => {
|
onValueChange={(v) => {
|
||||||
p.host.ip = v!;
|
p.host.ip = v!;
|
||||||
p.onChange?.();
|
p.onChange();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,11 +5,11 @@ import {
|
|||||||
Card,
|
Card,
|
||||||
CardActions,
|
CardActions,
|
||||||
CardContent,
|
CardContent,
|
||||||
Grid,
|
|
||||||
IconButton,
|
IconButton,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
Typography,
|
Typography,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
|
import Grid from "@mui/material/Grid";
|
||||||
import React, { PropsWithChildren } from "react";
|
import React, { PropsWithChildren } from "react";
|
||||||
import { NatEntry } from "../../api/NetworksApi";
|
import { NatEntry } from "../../api/NetworksApi";
|
||||||
import { ServerApi } from "../../api/ServerApi";
|
import { ServerApi } from "../../api/ServerApi";
|
||||||
@@ -54,6 +54,7 @@ export function NetNatConfiguration(p: {
|
|||||||
<>
|
<>
|
||||||
{p.nat.map((e, num) => (
|
{p.nat.map((e, num) => (
|
||||||
<NatEntryForm
|
<NatEntryForm
|
||||||
|
// eslint-disable-next-line react-x/no-array-index-key
|
||||||
key={num}
|
key={num}
|
||||||
{...p}
|
{...p}
|
||||||
entry={e}
|
entry={e}
|
||||||
@@ -295,7 +296,7 @@ function NATEntryProp(
|
|||||||
p: PropsWithChildren<{ label?: string }>
|
p: PropsWithChildren<{ label?: string }>
|
||||||
): React.ReactElement {
|
): React.ReactElement {
|
||||||
return (
|
return (
|
||||||
<Grid item sm={12} md={6} style={{ padding: "20px" }}>
|
<Grid size={{ sm: 12, md: 6 }} style={{ padding: "20px" }}>
|
||||||
{p.label && (
|
{p.label && (
|
||||||
<Typography variant="h6" style={{ marginBottom: "10px" }}>
|
<Typography variant="h6" style={{ marginBottom: "10px" }}>
|
||||||
{p.label}
|
{p.label}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export function PortInput(p: {
|
|||||||
value={p.value?.toString() ?? ""}
|
value={p.value?.toString() ?? ""}
|
||||||
type="number"
|
type="number"
|
||||||
onValueChange={(v) => {
|
onValueChange={(v) => {
|
||||||
p.onChange?.(sanitizePort(v));
|
p.onChange(sanitizePort(v));
|
||||||
}}
|
}}
|
||||||
checkValue={(v) => Number(v) <= 65535}
|
checkValue={(v) => Number(v) <= 65535}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -24,10 +24,13 @@ export function RadioGroupInput(p: {
|
|||||||
<RadioGroup
|
<RadioGroup
|
||||||
row
|
row
|
||||||
value={p.value}
|
value={p.value}
|
||||||
onChange={(_ev, v) => p.onValueChange?.(v)}
|
onChange={(_ev, v) => {
|
||||||
|
p.onValueChange(v);
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{p.options.map((o) => (
|
{p.options.map((o) => (
|
||||||
<FormControlLabel
|
<FormControlLabel
|
||||||
|
key={o.value}
|
||||||
disabled={!p.editable}
|
disabled={!p.editable}
|
||||||
value={o.value}
|
value={o.value}
|
||||||
control={<Radio />}
|
control={<Radio />}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user