Compare commits

..

70 Commits

Author SHA1 Message Date
Simon Pacotte
1d894c4fe0 fix review MathieuRA 2026-11-23 10:55:06 +01:00
Simon Pacotte
7477db7f3b further fixs and improvements 2026-10-20 17:48:45 +02:00
Simon Pacotte
5ae2ad9ec7 fix event test 2026-10-20 09:47:46 +02:00
Simon Pacotte
e871c5e032 refix changelog 2026-10-20 09:44:02 +02:00
Simon Pacotte
8e1fc0c9dd fix changelog 2026-10-20 09:43:25 +02:00
Simon Pacotte
3a39e1f919 fix review MathieuRA 2 2026-10-20 09:08:40 +02:00
Simon Pacotte
258f365b56 fix review MathieuRA 2026-10-20 09:08:26 +02:00
Simon Pacotte
d8dd0554a8 removed [resolve:all] added [some]/[every] 2026-10-20 09:08:01 +02:00
Simon Pacotte
fc37ec557c rework getAnyObject 2026-10-20 09:08:00 +02:00
Simon Pacotte
3257d9d9a9 add back changelog 2026-10-20 09:07:41 +02:00
Simon Pacotte
bc8d7d4cdb improve nested field and task resolution 2026-10-20 09:07:17 +02:00
Simon Pacotte
a5c7df43b7 fix wrong type 2026-10-20 09:07:17 +02:00
Simon Pacotte
d49d74abc4 remove comment 2026-10-20 09:07:17 +02:00
Simon Pacotte
d5a3b6e16a improve deep resolution 2026-10-20 09:07:16 +02:00
Simon Pacotte
9ee440bb7c implement getAnyObject and improve complex-matcher to support non-xapi objects 2026-10-20 09:07:16 +02:00
Simon Pacotte
5c7c9d698f improve resolver implementation and added resolve:all 2026-10-20 09:07:16 +02:00
Simon Pacotte
1be405308a Add recursion test and update complex-matcher calls 2026-10-20 09:07:16 +02:00
Simon Pacotte
a3fda70595 feat(complex-matcher): implement deep resolution matcher 2026-10-20 09:07:16 +02:00
Mathieu
191317630d feat(vectura): read disks from ESXi 6.x hosts (#10590) 2026-10-19 16:50:18 +02:00
ayoub-el-kajji-v
d32c9879b1 fix(hosts): multipathing should not require disconnecting srs on local storage (#10592)
XO-2336
2026-10-19 16:07:07 +02:00
Thomas Moraine
ab4d372ce2 docs(v2v): replace VDDK screenshots with vectura ones (#10620)
Update the prerequisite check and transfer form screenshots, and remove the unused VDDK/nbdinfo ones.
2026-10-19 14:23:11 +02:00
Pierre Donias
5cc6500def fix(lite/vm-creation): fix MAP_DUPLICATE_KEY on cores-per-socket (#10552)
Introduced by #8491
See #10201 (same workaround)

`VM.set_VCPUs_at_startup` ran concurrently and re-added `cores-per-socket`
between its removal and its re-addition, making the VM creation fail.
2026-10-19 14:14:05 +02:00
Olivier Lambert
8a70c4abc0 docs(xoa): align sizing guidance with the deploy form presets (#10617)
The deploy form now offers Small (2 vCPUs, 4 GiB), Medium (4 vCPUs,
8 GiB) and Large (8 vCPUs, 16 GiB, default) presets. Update the sizing
table to match, and drop the manual --max-old-space-size procedure:
since 6.8, xo-server sets its heap limit to 70% of the VM RAM.

Signed-off-by: Olivier Lambert <olivier.lambert@vates.tech>
2026-10-19 13:28:32 +02:00
Elise-F
1639a5f6a6 fix(xo6): opening console VM in new tab (#10616) 2026-10-19 11:35:34 +02:00
Olivier Lambert
d525a7d5bc feat(@vates/iscsi): bound what a peer can make the target do (#10566)
* fix(@vates/iscsi): only replace the session once the newcomer has logged in

A new TCP connection used to tear down the active session as soon as it
was accepted, before sending anything. Any peer able to reach the port,
a port scan, a failed CHAP login or a Discovery session, interrupted the
disk in use.

New connections are now kept aside until they establish a Normal session
(CHAP included when configured), and only then replace the active one.
That keeps the ability to recover from a stale connection, which is why
connections are replaced rather than refused.

Connections without a session are bounded in time (`loginTimeoutMs`,
15 s by default, also closing lingering Discovery sessions) and in number
(`maxPendingConnections`, 8 by default, oldest dropped first).

* chore: add PR number to changelog

* fix(@vates/iscsi): refuse extra connections and guard the login race

Review follow-up:
- let net.Server refuse connections past maxPendingConnections (+1 for
  the one serving the LUN) instead of evicting the oldest pending one
- a connection destroyed while its final Login Response is being written
  must not go on and replace the current session

* feat(@vates/iscsi): bound what a peer can make the target do

- allowedAddresses: close connections from other initiators as soon as
  they are accepted, so that they cannot take the pending connection
  slots and block a legitimate login
- reject a PDU whose data segment exceeds 8 KiB during login, or the
  declared MaxRecvDataSegmentLength afterwards, before reading it
- maxTransferLength (8 MiB by default): advertised in the block limits VPD
  page, longer READ/WRITE refused, which also bounds the WRITE buffer
- BlockDevice.readOnly: report the LUN write-protected and refuse WRITE
  with DATA PROTECT before soliciting any data; DiskBlockDevice sets it

* chore: add PR number to changelog

* feat(@vates/iscsi): rename allowedInitiatorAddresses, report refused connections

`allowedAddresses` did not tell whose addresses: these are the source
addresses of the initiators. `onConnectionRefused` reports each refused
one, e.g. so that a caller can tell that an initiator connects through a
NAT.

---------

Co-authored-by: Florent BEAUCHAMP <florent.beauchamp@vates.tech>
2026-10-19 10:03:00 +02:00
Mathieu
776993e119 fix(vates/types): fix vm and server type (#10598)
XO-3258
fix #10514
introduced by 0ef95d9 and b078d3d
2026-10-19 09:59:23 +02:00
Pierre Donias
8ae4ea25b2 feat(netbox): support Netbox v4.7.x (#10574)
Fixes #10565
See https://github.com/netbox-community/netbox/releases
2026-10-19 09:21:11 +02:00
Thomas Moraine
eecba81f22 docs(readme): replace XO 5 screenshots with XO 6 ones (#10600)
The last screenshot (SR statistics) is kept from XO 5, as XO 6 has no equivalent stats view yet.
2026-10-17 11:51:40 +02:00
Florent BEAUCHAMP
05aeff101b fix(immutable-backups): fix test not waiting for immutability (#10606) 2026-10-16 17:09:48 +02:00
spacotte-vates
b7af59b6ed feat(events): improve xo5 event handling (#10568)
XO-3152

Improves XO5 event handling

Event improvements - Front end test.md

Event improvements - Performance impact.md
2026-10-16 16:38:04 +02:00
Thierry Goettelmann
12e1a10394 fix(@xen-orchestra/acl): drop node:assert dependency (#10608)
node:assert is not available in the browser, so importing @xen-orchestra/acl
from a front-end bundle failed. Input checks now throw plain TypeErrors.
2026-10-16 14:24:08 +02:00
Killian
954a2034e6 test(@vates/iscsi): wait until the open-iscsi disk can be opened (#10576)
The CHAP interop test failed on CI with ENXIO on /dev/sdb (master 641f98878,
and #10549), right after waitForDevice() returned the disk.

waitForDevice() took a nonzero /sys/class/block/<name>/size as proof the disk
was ready, but the sd driver sets the size before device_add_disk(), which
creates the sysfs entry, then the /dev node, then registers the block device:
open() fails with ENOENT or ENXIO until then. Polling sysfs in a tight loop
after login hit that window in 15 of 100 logins.

isDeviceReady() now opens the device, and treats ENXIO and ENOENT as not ready
yet.
2026-10-16 11:35:10 +02:00
Thierry Goettelmann
b819ba1527 feat(web-core): make query builder model live and add search event (#10602) 2026-10-16 11:02:49 +02:00
Mathieu
ff90a80e99 feat(rest-api): expose backup-log in the SSE (#10563)
* feat(rest-api): expose backup-log in the SSE

* noop instead undefined

* fix: handle sequance

* changelog

* fix

* final fix

* emit remove event from the gc

* Kilian's feedback

---------

Co-authored-by: Killian <killian.allegrain@vates.tech>
2026-10-16 10:59:12 +02:00
Florent BEAUCHAMP
cfa75ef652 feat(xo6,rest-api): export vdi as vmdk (#10591) 2026-10-16 10:57:42 +02:00
Florent BEAUCHAMP
a350c62cc3 feat(fs, backups): don't concatenate buffers but write them directly (#10538)
* feat(fs, backups): don't concatenate buffers but write them directly
maximum throughput with a perfect source and no write goes from
4.5 to 9.6GB/s

* fix: remove Buffer concat in qcow2 stream generationonly needed for last block
2026-10-16 10:57:00 +02:00
Florent BEAUCHAMP
bb5a79e6c6 feat(xo-server, xo-web): support insecure nbd (#10540)
* feat(nbd-client): support nbd insecure networks
* feat(xo-web): support insecure nbd

also add a confirm on insecure enabling
The dialog is titled "Enable insecure NBD?" and says: "The disk data of the backups will travel unencrypted on this network. Only enable it on a network dedicated to backups and isolated from the VMs and the users (dedicated VLAN or physical network)." Both texts are new entries in messages.js, and the dialog itself is a new confirmInsecureNbd() helper in xo/index.js.

It appears in two places:

Pool Network tab (tab-network.js):
The dialog only appears when switching a network to insecure NBD. Reselecting it on a network that already has it, or switching to "NBD" or "No NBD", doesn't ask.
On cancel, nothing is sent and the drop-down keeps showing the network's current setting.
Network creation form (new/network/index.js):
The dialog appears on "Create" when insecure NBD is selected (bonded and private networks are never affected).
On cancel, the network isn't created and the form stays as is, with no error and no redirect.

* feat: update xo5,xo6 and lite ui for this settings

---------

Co-authored-by: MlssFrncJrg <119158464+MelissaFrncJrg@users.noreply.github.com>
2026-10-16 10:45:54 +02:00
Pierre Brunet
e4e7c05104 fix(fs/s3/azure): better handling of NotFound in _getSize and _unlink (#10548)
* fix: handle error codes

* chore: update changelog

* fix: apply suggestions from code review

Co-authored-by: spacotte-vates <simon.pacotte@vates.tech>

* fix: small typo

---------

Co-authored-by: spacotte-vates <simon.pacotte@vates.tech>
Co-authored-by: Florent BEAUCHAMP <florent.beauchamp@vates.tech>
2026-10-15 18:16:51 +02:00
Marie Garde
52c68a28cc feat(xo6): add edit form BR (#10478)
* feat(xo6): add edit form BR

* type disable

* wip

* fix post rebase

* form initial data ok

* form ok

* add tests dans finalize edit

* refacto for PR

* refacto for RP

* rebase ok

* feedback

* PR ok

* add changelog
2026-10-15 17:26:44 +02:00
Marie Garde
635f02bcae feat(xo6): Add backup job list (#10572) 2026-10-15 16:39:32 +02:00
Olivier Lambert
db5cb01fc9 fix(xo-server): cancel the disconnection grace period when the connection drops (#10577) 2026-10-15 16:15:00 +02:00
Florent BEAUCHAMP
928408fe8e feat(vmdk): first version of the package with streamoptimized export (#10403) 2026-10-15 15:14:34 +02:00
Mathieu
db98f15bc1 docs(rest-api): add a naming section in guidelines (#10571) 2026-10-15 13:58:39 +02:00
Mathieu
decdf61919 fix(vectura): update rustls to 0.23.46 (#10586)
cargo deny fails on master since RUSTSEC-2026-0346, 0347, 0348 and 0349
were published against rustls 0.23.45. 0.23.46 fixes all four.

vectura has no custom session store, no ECH and no brotli feature, so
only 0349 (later connections downgraded to classical key exchange through
the resumption cache) applies, in theory.

vectura 0.1.3, bumped and rebuilt with scripts/release.sh patch.
2026-10-15 11:26:00 +02:00
Thierry Goettelmann
6115c74bbe fix(web-core): keep an open select's Escape from closing its overlay (#10582) 2026-10-15 10:48:37 +02:00
Mathieu
025f6eb533 feat(vectura): bump and build in the pull request, not at release (#10573)
The binary in git is now the build of its sources. build.sh keeps the paths
of the machine out of the binary and refuses another zig or cargo-zigbuild
version, and the Vectura workflow fails when its build differs from the
committed binary. The binary is rebuilt with this build.sh: only its paths
change, the version stays 0.1.2.

vectura is no longer released on its own. release.sh runs once at the end of
the pull request which changes vectura and no longer commits. bump-pkg,
gen-deps-list.js and check-changed-pkgs.js drop the vectura pseudo-package: a
change under vectura/ requires a release of @xen-orchestra/vmware-explorer,
which ships the committed binary as is. release.sh puts Cargo.toml and
Cargo.lock back when the build or the check of the binary fails.
2026-10-15 10:43:00 +02:00
Thierry Goettelmann
3e74189479 fix(web): generate route-map.d.ts only in development mode (#10583) 2026-10-15 10:34:37 +02:00
Thierry Goettelmann
0695c6b44c fix(web-core): hide the focus outline of readonly inputs on Firefox (#10584) 2026-10-15 10:31:29 +02:00
Bastien Nollet
0bb2f12b2b fix(xo-server): avoid sequence abort on error with proxy (#10504) 2026-10-14 12:30:05 +02:00
Thierry Goettelmann
865b6a84c7 fix(web-core): use solid border and body typography in UiTextarea (#10579) 2026-10-14 09:34:13 +02:00
Thierry Goettelmann
6b82340fdc fix(web-core): balance remote resource subscriptions on url and isEnabled changes (#10473) 2026-10-14 08:59:26 +02:00
Marie Garde
d846e00dff feat(xo6): BR add detail page (#10454)
* feat(xo6): BR add detail page

* Prepare PR

* add tests

* fix breadcrum

* fix post rebase

* fix admin path

* fix link side panel

# Conflicts:
#	@xen-orchestra/web/src/modules/backup-repository/components/list/panel/cards/BackupRepositoryInfosCard.unit.test.ts
#	@xen-orchestra/web/src/modules/backup-repository/components/list/panel/cards/BackupRepositoryInfosCard.vue

* feedback

* feedback

* rebase ok
2026-10-14 08:50:18 +02:00
Florent BEAUCHAMP
f93bb67409 fix(xen-api): really throw import error while importing VM (#10551) 2026-10-13 17:13:44 +02:00
Florent BEAUCHAMP
51bb88a1ce feat(vmware-explorer): method to list/attach/detail disk to satellites (#10449)
* feat(vmware-explorer): implement attaching and detaching disks
* feat(vmware-explorer): implement a check to see if a disk can be attached to a VM
* feat(vmware-explorer): implement a method to detect what host are candidates to deploy a satellite
* refactor: computing the datastore of a datapath
2026-10-13 13:58:23 +02:00
Pierre Donias
11335b465b fix(xo-web/self): fix removing a tag from a resource set (#10550)
Fixes Zammad#65918
2026-10-13 11:05:35 +02:00
Killian
295b8838a6 docs(backups): explain when reverse replication updates the VM in place (#10558) 2026-10-13 10:01:20 +02:00
Pierre Briffaux
e0b0c75682 feat(xo6): add copy button for multiple information (#9976) 2026-10-13 09:16:35 +02:00
Thomas Moraine
286dafa267 docs: document warm migration and fix broken link in architecture page (#10570) 2026-10-12 18:20:37 +02:00
Thierry Goettelmann
b08ad1669f feat(web-core): add UiLinkList component (#10287) 2026-10-12 17:36:54 +02:00
Thomas Moraine
4731cbd629 docs(advanced.md): document estimated per-VM power consumption metric (#10569) 2026-10-12 17:13:27 +02:00
Florent BEAUCHAMP
1c4890be10 fix(xo-cli): error when using output on a rest api query (#10541) 2026-10-12 16:59:56 +02:00
Pierre Donias
4abb9d80bc feat(xo-web/patches): warn when pool master is not up to date (#10523) 2026-10-12 16:24:18 +02:00
Mathieu
87fe4e2b53 docs(rest-api): enhance REST API guideline (#10416) 2026-10-12 15:37:17 +02:00
ayoub-el-kajji-v
6058f07813 feat(api-rest): add sr probe endpoints (#10099) 2026-10-12 14:43:07 +02:00
Sebastien Rodot
d451d5c35b feat(xo-server-sdn-controller): add unit tests
- check that objects listeners are properly attached/detached on Xapi connect/disconnect
- check that xapi instance doesn't leak on reconnect
2026-10-12 14:34:55 +02:00
Sebastien Rodot
375b9fe91b fix(xo-server-sdn-controller): avoid leaking listeners on disconnect
Objects listeners are added to Xapi objects by the sdn-controller plugin, but 
they are only removed at plugin `unload()` time.

Prefer to remove them at Xapi disconnect time.
2026-10-12 14:34:55 +02:00
Sebastien Rodot
d53294f15c fix(xo-server-sdn-controller): re-watch XAPI events after reconnect
When a pool's XAPI connection drops and reconnects, xo-server destroys the
old Xapi instance and creates a new one (same pool UUID, same XAPI object
$refs). The plugin tracked managed pools by pool UUID, so _manageXapi()
short-circuited on reconnect and never attached its add/update/remove
listeners to the new Xapi instance.

From then on the plugin was blind to XAPI events: re-applying VIF traffic
rules on VM start, handling VIF/PIF plug and star-center election all
stopped silently until the plugin was reloaded.

Track the managed Xapi instances instead of pool UUIDs, and drop a dead
instance on disconnect so its replacement is managed again.
2026-10-12 14:34:55 +02:00
Sebastien Rodot
40e5ca9a73 fix(xo-server-sdn-controller): recreate stale OpenFlow controllers
When a XAPI connection drops and reconnects, xo-server creates a new
Xapi instance while the XAPI objects (and their $refs) are kept. The
ofChannels cache still held the controllers of the previous
connection, so traffic rule add/delete calls were silently skipped
without reaching the host.

Rework _getOrCreateOfChannel() to key the cache on the Xapi instance:
entries from a previous connection are dropped and the controller is
recreated, concurrent calls share the same instantiation, and a
failed instantiation clears the cache.

Also drop the cached controller when the host is disabled or its XAPI
is not connected, so it is recreated as soon as it comes back.
2026-10-12 14:34:55 +02:00
ayoub-el-kajji-v
cf760d26cd feat(backup): support ndb through http proxy (#10544) 2026-10-12 11:23:29 +02:00
Thierry Goettelmann
d4b85421fe fix(web-core): make query builder usable inside a form (#10475) 2026-10-12 09:59:46 +02:00
555 changed files with 16041 additions and 11732 deletions

View File

@@ -45,8 +45,8 @@ jobs:
- name: Hold the coverage floor
run: cargo test --locked --test coverage -- --ignored
# builds the binary as a release does, then checks it and the one in git,
# which xo-server runs
# builds the binary as release.sh does, checks it, then checks the one in git,
# which xo-server runs, is that build
binary:
runs-on: ubuntu-latest
steps:
@@ -65,4 +65,9 @@ jobs:
- run: scripts/build.sh "$RUNNER_TEMP/build"
- run: scripts/check-binary.sh "$RUNNER_TEMP/build/vectura"
- run: scripts/check-binary.sh vectura
- name: The binary in git is the build of these sources
run: |
cmp "$RUNNER_TEMP/build/vectura" vectura || {
echo '::error::vectura is not the build of these sources: run scripts/build.sh . in vectura/ and commit the binary'
exit 1
}

View File

@@ -15,7 +15,7 @@ The target drives login negotiation onto a single, fixed code path:
It implements SendTargets discovery, login (`AuthMethod=None` or one-way
**CHAP** — see [Authentication](#authentication-chap)), the ~10 SCSI
commands a Linux initiator issues to attach and use a block device
(`INQUIRY` + VPD `0x00`/`0x80`/`0x83`, `REPORT LUNS`, `READ CAPACITY 10/16`,
(`INQUIRY` + VPD `0x00`/`0x80`/`0x83`/`0xb0`, `REPORT LUNS`, `READ CAPACITY 10/16`,
`READ`/`WRITE 10/16`, `TEST UNIT READY`, `REQUEST SENSE`, `MODE SENSE`,
`SYNCHRONIZE CACHE`), the full R2T / Data-Out write path, NOP keepalive replies,
and Logout. Commands may be outstanding concurrently (Data-Out PDUs are routed
@@ -28,6 +28,19 @@ The package also ships a userspace **initiator** (`IscsiInitiator`) and an
Not implemented (yet): mutual (two-way) CHAP, Task Management (abort/reset),
target-initiated NOP keepalives, multiple connections/LUNs.
What a peer can make the target do is bounded:
- connections that have not logged in yet are limited in time (`loginTimeoutMs`)
and number (`maxPendingConnections`), and `allowedInitiatorAddresses` (the
source addresses of the expected initiators) closes the other ones as soon as
they are accepted, reporting them to `onConnectionRefused`
- a PDU data segment is at most 8 KiB during login, then the declared
`MaxRecvDataSegmentLength` (256 KiB), checked before it is read
- a single `READ`/`WRITE` is at most `maxTransferLength` (8 MiB by default),
advertised in the block limits VPD page so that initiators split their I/O
- a `BlockDevice` with `readOnly: true` is reported write-protected, and `WRITE`
is refused with `DATA PROTECT` before any data is solicited
### CLI
The package ships a `vates-iscsi` binary that serves a file as a LUN:
@@ -139,6 +152,8 @@ class RandomAccessDiskLun {
}
return out
}
// reported write-protected: WRITE is refused before reaching write()
readOnly = true
write() {
throw new Error('read-only LUN')
}

View File

@@ -18,14 +18,14 @@ The package has two independent roles with very different maturity:
## Session and connection
| Aspect | Target | Initiator |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------- |
| Connections per session | `MaxConnections=1`, enforced | opens exactly one |
| Session reinstatement | **no** — no ISID tracking; a new connection always tears down and replaces whatever connection currently exists, rather than RFC 7143's ISID-matched reinstatement (see `index.mts`'s class doc for the reasoning: safe here because the target is ephemeral, single-consumer, and CHAP-guarded) | n/a (single connection) |
| Multiple LUNs | **no** — exactly one LUN, always LUN 0 | reads are hardcoded to LUN 0 |
| `ErrorRecoveryLevel` | `0` only | requests `0` |
| Header/data digests | `HeaderDigest=None`, `DataDigest=None` — no CRC32C on the wire | same |
| Markers (`IFMarker`/`OFMarker`) | not offered (RFC-deprecated) | not offered |
| Aspect | Target | Initiator |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------- |
| Connections per session | `MaxConnections=1`, enforced | opens exactly one |
| Session reinstatement | **no** — no ISID tracking; once a new connection has established a Normal session (CHAP included), it tears down and replaces whatever connection currently exists, rather than RFC 7143's ISID-matched reinstatement (see `index.mts`'s class doc for the reasoning: safe here because the target is ephemeral, single-consumer, and CHAP-guarded). Until then it does not affect the current one, and is bounded by `loginTimeoutMs` and `maxPendingConnections` | n/a (single connection) |
| Multiple LUNs | **no** — exactly one LUN, always LUN 0 | reads are hardcoded to LUN 0 |
| `ErrorRecoveryLevel` | `0` only | requests `0` |
| Header/data digests | `HeaderDigest=None`, `DataDigest=None` — no CRC32C on the wire | same |
| Markers (`IFMarker`/`OFMarker`) | not offered (RFC-deprecated) | not offered |
## Login / text negotiation
@@ -72,17 +72,17 @@ keys if it declines transit on the first exchange.
Decoded explicitly (`types.mts#decodeCdb`); anything else maps to `unsupported` → `CHECK CONDITION` /
`ILLEGAL_REQUEST` / `INVALID COMMAND OPERATION CODE`:
| Command | Variants |
| ------------------- | ---------------------------------------------------------------- |
| `INQUIRY` | standard + EVPD (vendor/product/revision/serial from `identity`) |
| `REPORT LUNS` | |
| `READ CAPACITY` | `(10)` and `(16)` |
| `READ` | `(10)` and `(16)` |
| `WRITE` | `(10)` and `(16)` |
| `TEST UNIT READY` | |
| `REQUEST SENSE` | |
| `MODE SENSE` | `(6)` and `(10)` |
| `SYNCHRONIZE CACHE` | `(10)` and `(16)` — flushes the backing `BlockDevice` |
| Command | Variants |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `INQUIRY` | standard + EVPD `0x00`/`0x80`/`0x83` (vendor/product/revision/serial from `identity`) and `0xb0` (block limits: `maxTransferLength`) |
| `REPORT LUNS` | |
| `READ CAPACITY` | `(10)` and `(16)` |
| `READ` | `(10)` and `(16)`; longer than `maxTransferLength` → `INVALID FIELD IN CDB` |
| `WRITE` | `(10)` and `(16)`; longer than `maxTransferLength` → `INVALID FIELD IN CDB`; on a `readOnly` LUN → `DATA PROTECT` / `WRITE PROTECTED`, without soliciting data |
| `TEST UNIT READY` | |
| `REQUEST SENSE` | |
| `MODE SENSE` | `(6)` and `(10)`; `WP` set on a `readOnly` LUN |
| `SYNCHRONIZE CACHE` | `(10)` and `(16)` — flushes the backing `BlockDevice` |
**Not implemented**: persistent reservations, VAAI/thin-provisioning primitives (`UNMAP`, `WRITE SAME`, `COMPARE
AND WRITE`, ...), any vendor-specific commands — anything beyond the ~10 commands a Linux initiator actually

View File

@@ -33,7 +33,7 @@ The target drives login negotiation onto a single, fixed code path:
It implements SendTargets discovery, login (`AuthMethod=None` or one-way
**CHAP** — see [Authentication](#authentication-chap)), the ~10 SCSI
commands a Linux initiator issues to attach and use a block device
(`INQUIRY` + VPD `0x00`/`0x80`/`0x83`, `REPORT LUNS`, `READ CAPACITY 10/16`,
(`INQUIRY` + VPD `0x00`/`0x80`/`0x83`/`0xb0`, `REPORT LUNS`, `READ CAPACITY 10/16`,
`READ`/`WRITE 10/16`, `TEST UNIT READY`, `REQUEST SENSE`, `MODE SENSE`,
`SYNCHRONIZE CACHE`), the full R2T / Data-Out write path, NOP keepalive replies,
and Logout. Commands may be outstanding concurrently (Data-Out PDUs are routed
@@ -46,6 +46,19 @@ The package also ships a userspace **initiator** (`IscsiInitiator`) and an
Not implemented (yet): mutual (two-way) CHAP, Task Management (abort/reset),
target-initiated NOP keepalives, multiple connections/LUNs.
What a peer can make the target do is bounded:
- connections that have not logged in yet are limited in time (`loginTimeoutMs`)
and number (`maxPendingConnections`), and `allowedInitiatorAddresses` (the
source addresses of the expected initiators) closes the other ones as soon as
they are accepted, reporting them to `onConnectionRefused`
- a PDU data segment is at most 8 KiB during login, then the declared
`MaxRecvDataSegmentLength` (256 KiB), checked before it is read
- a single `READ`/`WRITE` is at most `maxTransferLength` (8 MiB by default),
advertised in the block limits VPD page so that initiators split their I/O
- a `BlockDevice` with `readOnly: true` is reported write-protected, and `WRITE`
is refused with `DATA PROTECT` before any data is solicited
### CLI
The package ships a `vates-iscsi` binary that serves a file as a LUN:
@@ -157,6 +170,8 @@ class RandomAccessDiskLun {
}
return out
}
// reported write-protected: WRITE is refused before reaching write()
readOnly = true
write() {
throw new Error('read-only LUN')
}

View File

@@ -35,6 +35,11 @@ VM boot mechanics, and deployment specifics live elsewhere and aren't reproduced
- Re-verified end-to-end after deploying the fix: same S3-backed boot scenario completed successfully
(~5 min total, vs ~20-25s for the equivalent local-storage boot — S3 itself is slow, but the mount no
longer wedges).
- Refined afterwards: the replacement used to happen as soon as the TCP connection was accepted, so any
peer reaching the port (a port scan, a failed CHAP login, a Discovery session) interrupted the session in
use. It now only happens once the new connection has established a Normal session; until then,
connections are bounded by `loginTimeoutMs` and `maxPendingConnections`. Regression tests:
`loopback.integ.mts`, `describe('connection admission', ...)`.
### Independently landed, cross-referenced against this pass's coverage

View File

@@ -102,10 +102,10 @@ export class DiskBlockDevice implements BlockDevice {
return result
}
/**
* Always throws: the source disk is read-only. The target answers CHECK
* CONDITION / MEDIUM ERROR, which initiators surface as an I/O error.
*/
// the target refuses WRITE commands before they reach `write()`
readonly readOnly = true
/** Always throws: the source disk is read-only. */
async write(): Promise<void> {
throw new Error('DiskBlockDevice is read-only')
}

View File

@@ -16,6 +16,11 @@ export interface BlockDevice {
getSize(): number
/** Logical block size in bytes (typically 512). */
getBlockSize(): number
/**
* When true, the LUN is reported as write-protected and WRITE commands are
* refused up front (DATA PROTECT), without soliciting their data.
*/
readonly readOnly?: boolean
/** Read exactly `length` bytes starting at byte `offset`. */
read(offset: number, length: number): Promise<Buffer>
/** Write `data` starting at byte `offset`. */

View File

@@ -24,7 +24,13 @@ import {
TEXT_FLAG_FINAL,
} from './constants.mjs'
import { buildFixedSense, handleScsiCommand, type ScsiIdentity } from './scsi.mjs'
import { buildSendTargetsResponse, LoginNegotiator, parseTextKeys } from './login.mjs'
import {
buildSendTargetsResponse,
LOGIN_MAX_DATA_SEGMENT_LENGTH,
LoginNegotiator,
OUR_MAX_RECV_DATA_SEGMENT_LENGTH,
parseTextKeys,
} from './login.mjs'
import { allocBhs, assemblePdu, type IncomingPdu, readPdu, writePdu } from './pdu.mjs'
import {
decodeCdb,
@@ -81,6 +87,16 @@ export interface ConnectionDeps {
allocateTsih(): number
/** When set, require one-way CHAP: the target challenges and verifies the initiator. */
readonly chap?: ChapCredentials
/**
* Time allowed to establish a Normal session, in ms (0 or unset disables):
* past it, the connection is closed. Also bounds Discovery sessions, which
* never become Normal ones.
*/
readonly loginTimeoutMs?: number
/** Called once this connection has established a Normal session. */
onSessionEstablished?(connection: Connection): void
/** Max length of a single READ or WRITE, in bytes. */
readonly maxTransferLength?: number
}
type Phase = 'login' | 'fullFeature' | 'closed'
@@ -123,6 +139,8 @@ export class Connection implements CommandContext {
readonly #pendingWrites = new Map<number, PendingWrite>()
#nextTargetTransferTag = 1
#loginTimer?: ReturnType<typeof setTimeout>
constructor(socket: Socket, deps: ConnectionDeps) {
this.#socket = socket
this.#deps = deps
@@ -142,9 +160,19 @@ export class Connection implements CommandContext {
/** Read and service PDUs until the peer logs out or the connection drops. */
async serve(): Promise<void> {
const { loginTimeoutMs = 0 } = this.#deps
if (loginTimeoutMs > 0) {
this.#loginTimer = setTimeout(() => {
log.warn('no session established in time, closing the connection', { remote: this.#socket.remoteAddress })
this.destroy()
}, loginTimeoutMs).unref()
}
try {
for (;;) {
const pdu = await readPdu(this.#socket)
const pdu = await readPdu(
this.#socket,
this.#phase === 'login' ? LOGIN_MAX_DATA_SEGMENT_LENGTH : OUR_MAX_RECV_DATA_SEGMENT_LENGTH
)
if (pdu === null) {
break // peer closed the connection
}
@@ -156,6 +184,7 @@ export class Connection implements CommandContext {
} catch (error) {
this.#fail(error)
} finally {
clearTimeout(this.#loginTimer)
this.#phase = 'closed'
this.#socket.destroy()
}
@@ -299,6 +328,13 @@ export class Connection implements CommandContext {
bhs[37] = statusDetail
await this.#send(assemblePdu(bhs, data))
// destroyed while the response was being written (login timeout, target
// closing): the write still succeeds, but this connection must not go on
// and replace the current session
if (this.#phase === 'closed') {
return true
}
if (statusClass !== LoginStatusClass.SUCCESS) {
// RFC 7143 §6.3: the failure response goes out first (above), then the
// target closes the connection.
@@ -316,6 +352,10 @@ export class Connection implements CommandContext {
sessionType: this.#sessionType,
target: this.#login.targetName,
})
if (this.#sessionType === 'Normal') {
clearTimeout(this.#loginTimer)
this.#deps.onSessionEstablished?.(this)
}
}
return false
}
@@ -389,13 +429,13 @@ export class Connection implements CommandContext {
// Not awaited: the read loop must move on immediately rather than block on
// this `lun.read()`. See the class doc for why no extra ordering is needed.
void this.#readGate
.run(() => handleScsiCommand(cdb, pdu.itt, this, this.#deps.identity))
.run(() => handleScsiCommand(cdb, pdu.itt, this, this.#deps.identity, this.#deps.maxTransferLength))
.catch(error => {
this.#fail(error)
})
return
}
await handleScsiCommand(cdb, pdu.itt, this, this.#deps.identity)
await handleScsiCommand(cdb, pdu.itt, this, this.#deps.identity, this.#deps.maxTransferLength)
}
async #sendReject(pdu: IncomingPdu, reason: number): Promise<void> {

View File

@@ -166,6 +166,7 @@ export const SenseKey = {
HARDWARE_ERROR: 0x04,
ILLEGAL_REQUEST: 0x05,
UNIT_ATTENTION: 0x06,
DATA_PROTECT: 0x07,
} as const
/** Additional Sense Code / Qualifier pairs we may emit. */
@@ -174,6 +175,7 @@ export const Asc = {
INVALID_COMMAND_OPERATION_CODE: { asc: 0x20, ascq: 0x00 },
INVALID_FIELD_IN_CDB: { asc: 0x24, ascq: 0x00 },
LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE: { asc: 0x21, ascq: 0x00 },
WRITE_PROTECTED: { asc: 0x27, ascq: 0x00 },
} as const
/** Reject reason codes (Reject PDU byte 2). */

View File

@@ -3,7 +3,7 @@ import { createLogger, type Logger } from '@xen-orchestra/log'
import type { BlockDevice } from './backend.mjs'
import { Connection, type ConnectionDeps } from './connection.mjs'
import type { ScsiIdentity } from './scsi.mjs'
import { DEFAULT_MAX_TRANSFER_LENGTH, type ScsiIdentity } from './scsi.mjs'
import type { ChapCredentials } from './types.mjs'
export { FileBlockDevice } from './backend.mjs'
@@ -25,6 +25,8 @@ const DEFAULT_PORT = 3260
const DEFAULT_WRITE_TIMEOUT_MS = 30_000
const DEFAULT_CMD_WINDOW = 64
const DEFAULT_READ_CONCURRENCY = 16
const DEFAULT_LOGIN_TIMEOUT_MS = 15_000
const DEFAULT_MAX_PENDING_CONNECTIONS = 8
const DEFAULT_IDENTITY: ScsiIdentity = {
vendor: 'VATES',
@@ -61,18 +63,62 @@ export interface IscsiTargetOptions {
* open-iscsi `node.session.auth` username/password). Omit for no authentication.
*/
readonly chap?: ChapCredentials
/**
* Time a new connection has to establish a Normal session, in ms (0
* disables). Also bounds Discovery sessions. Defaults to 15000.
*/
readonly loginTimeoutMs?: number
/**
* Max number of connections that have not established a Normal session yet;
* past it, new ones are refused. Defaults to 8.
*/
readonly maxPendingConnections?: number
/**
* Source addresses the initiators may connect from. When set, connections
* from any other address are closed as soon as they are accepted, before any
* login: only these initiators can take a pending connection slot.
* IPv4-mapped IPv6 addresses (`::ffff:a.b.c.d`) match their IPv4 form.
*/
readonly allowedInitiatorAddresses?: Iterable<string>
/**
* Called with the source address of each connection closed because it is
* not in `allowedInitiatorAddresses`, e.g. to tell why an initiator behind a
* NAT cannot connect.
*/
readonly onConnectionRefused?: (address: string) => void
/**
* Max length of a single READ or WRITE, in bytes, advertised in the block
* limits VPD page; longer commands are refused. At least one logical block.
* Defaults to 8 MiB.
*/
readonly maxTransferLength?: number
}
const IPV4_MAPPED_PREFIX = '::ffff:'
function normalizeAddress(address: string): string {
return address.startsWith(IPV4_MAPPED_PREFIX) && address.includes('.')
? address.slice(IPV4_MAPPED_PREFIX.length)
: address
}
/**
* A minimal iSCSI target exposing exactly one read/write LUN.
*
* Single initiator, single connection (`MaxConnections=1`),
* `ErrorRecoveryLevel=0`, no digests. A new connection always replaces the
* current one rather than being refused (see `#onConnection`): there is no
* way to tell a stale, abandoned connection (initiator gave up without
* closing the socket) from a healthy one, so refusing would let one stuck
* connection wedge the target forever. Not RFC 7143 session reinstatement (no
* ISID matching) — safe here since the target is ephemeral, CHAP-guarded, and
* `ErrorRecoveryLevel=0`, no digests.
*
* A new connection replaces the current one rather than being refused (see
* `#onSessionEstablished`): there is no way to tell a stale, abandoned
* connection (initiator gave up without closing the socket) from a healthy
* one, so refusing would let one stuck connection wedge the target forever.
* The replacement only happens once the new connection has established a
* Normal session, CHAP included when configured, so that a port scan, a failed
* login or a Discovery session cannot interrupt the current one. Until then,
* connections are bounded in time (`loginTimeoutMs`) and in number
* (`maxPendingConnections`); with `allowedInitiatorAddresses`, only the expected
* initiators can take those slots. Not RFC 7143 session reinstatement (no ISID
* matching) — safe here since the target is ephemeral, CHAP-guarded, and
* single-consumer.
*/
export class IscsiTarget {
@@ -85,9 +131,17 @@ export class IscsiTarget {
readonly #cmdWindow: number
readonly #readConcurrency: number
readonly #chap?: ChapCredentials
readonly #loginTimeoutMs: number
readonly #maxPendingConnections: number
readonly #allowedInitiatorAddresses?: ReadonlySet<string>
readonly #onConnectionRefused?: (address: string) => void
readonly #maxTransferLength: number
#server?: Server
// the connection with an established Normal session, serving the LUN
#connection?: Connection
// every open connection, so that close() can drop them all
readonly #connections = new Set<Connection>()
#tsih = 0
constructor(options: IscsiTargetOptions) {
@@ -99,6 +153,16 @@ export class IscsiTarget {
this.#cmdWindow = options.cmdWindow ?? DEFAULT_CMD_WINDOW
this.#readConcurrency = options.readConcurrency ?? DEFAULT_READ_CONCURRENCY
this.#chap = options.chap
this.#loginTimeoutMs = options.loginTimeoutMs ?? DEFAULT_LOGIN_TIMEOUT_MS
this.#maxPendingConnections = options.maxPendingConnections ?? DEFAULT_MAX_PENDING_CONNECTIONS
if (options.allowedInitiatorAddresses !== undefined) {
this.#allowedInitiatorAddresses = new Set(Array.from(options.allowedInitiatorAddresses, normalizeAddress))
}
this.#onConnectionRefused = options.onConnectionRefused
this.#maxTransferLength = options.maxTransferLength ?? DEFAULT_MAX_TRANSFER_LENGTH
if (this.#maxTransferLength < options.lun.getBlockSize()) {
throw new RangeError('maxTransferLength must be at least one logical block')
}
this.#identity = {
...DEFAULT_IDENTITY,
// Default the serial to the IQN so the LUN has a stable, unique identity.
@@ -122,28 +186,44 @@ export class IscsiTarget {
readConcurrency: this.#readConcurrency,
allocateTsih: () => this.#allocateTsih(),
chap: this.#chap,
loginTimeoutMs: this.#loginTimeoutMs,
onSessionEstablished: connection => this.#onSessionEstablished(connection),
maxTransferLength: this.#maxTransferLength,
}
}
#onConnection(socket: Socket): void {
const existing = this.#connection
if (existing !== undefined) {
// Replaces a possibly-stale connection rather than refusing; see the class doc.
log.warn('replacing existing connection with a new one', { remote: socket.remoteAddress })
existing.destroy()
const allowed = this.#allowedInitiatorAddresses
const remote = normalizeAddress(socket.remoteAddress ?? '')
if (allowed !== undefined && !allowed.has(remote)) {
log.warn('connection from an address that is not allowed, closing it', { remote })
socket.destroy()
this.#onConnectionRefused?.(remote)
return
}
socket.setNoDelay(true)
const connection = new Connection(socket, this.#deps())
this.#connection = connection
this.#connections.add(connection)
// Long-lived per-connection task; serve() handles its own errors and never
// rejects, so detaching it here is safe.
void connection.serve().finally(() => {
this.#connections.delete(connection)
if (this.#connection === connection) {
this.#connection = undefined
}
})
}
#onSessionEstablished(connection: Connection): void {
const existing = this.#connection
this.#connection = connection
if (existing !== undefined) {
// Replaces a possibly-stale connection rather than refusing; see the class doc.
log.warn('replacing existing connection with a newly logged in one')
existing.destroy()
}
}
/** Open the LUN (if needed) and start accepting connections. */
async listen(): Promise<void> {
if (this.#server !== undefined) {
@@ -152,6 +232,11 @@ export class IscsiTarget {
await this.#lun.open?.()
const server = createServer(socket => this.#onConnection(socket))
// + 1: the connection serving the LUN does not take a pending slot
server.maxConnections = this.#maxPendingConnections + 1
server.on('drop', data => {
log.warn('too many connections without a session, refusing a new one', { remote: data?.remoteAddress })
})
this.#server = server
try {
await new Promise<void>((resolve, reject) => {
@@ -175,17 +260,20 @@ export class IscsiTarget {
return address !== null && typeof address === 'object' ? address : undefined
}
/** Stop accepting connections, drop the active connection, and close the LUN. */
/** Stop accepting connections, drop every connection, and close the LUN. */
async close(): Promise<void> {
const server = this.#server
const connection = this.#connection
const connections = [...this.#connections]
this.#server = undefined
this.#connection = undefined
this.#connections.clear()
if (server !== undefined) {
await new Promise<void>((resolve, reject) => {
server.close(error => (error ? reject(error) : resolve()))
// Drop the live connection so server.close() can complete.
connection?.destroy()
// Drop the live connections so server.close() can complete.
for (const connection of connections) {
connection.destroy()
}
})
}
await this.#lun.close()

View File

@@ -35,9 +35,12 @@ const log: Logger = createLogger('vates:iscsi:login')
// Operational values the target imposes. The target drives negotiation, so these
// are pinned to a single code path (see plan): all writes are R2T-solicited
// (InitialR2T=Yes, ImmediateData=No), no digests, one connection.
const OUR_MAX_RECV_DATA_SEGMENT_LENGTH = 262144
export const OUR_MAX_RECV_DATA_SEGMENT_LENGTH = 262144
const OUR_MAX_BURST_LENGTH = 262144
const DEFAULT_INITIATOR_MAX_RECV_DATA_SEGMENT_LENGTH = 8192 // RFC 7143 default
// a declared MaxRecvDataSegmentLength only applies once logged in: until then,
// both sides keep to the 8192-byte default (RFC 7143 §13.12)
export const LOGIN_MAX_DATA_SEGMENT_LENGTH = 8192
/** Parse a NUL-delimited iSCSI text key=value data segment. */
export function parseTextKeys(data: Buffer): Map<string, string> {

View File

@@ -4,6 +4,7 @@ import { connect, type Socket } from 'node:net'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { once } from 'node:events'
import { setTimeout as delay } from 'node:timers/promises'
import { after, before, describe, it } from 'node:test'
import {
@@ -642,6 +643,200 @@ describe('connection replacement', () => {
})
})
// A connection only takes over once it has itself logged in: until then, it
// must not disturb the session in use, whatever it does or fails to do.
describe('connection admission', () => {
const CHAP = { user: 'alice', secret: 's3cr3t-s3cr3t' }
let dir: string
let backingPath: string
before(async () => {
dir = await mkdtemp(join(tmpdir(), 'vates-iscsi-admission-'))
backingPath = join(dir, 'lun.img')
await writeFile(backingPath, Buffer.alloc(LUN_SIZE, 0x5a))
})
after(async () => {
await rm(dir, { recursive: true, force: true })
})
async function withTarget(
options: {
loginTimeoutMs?: number
maxPendingConnections?: number
allowedInitiatorAddresses?: string[]
onConnectionRefused?: (address: string) => void
},
fn: (port: number) => Promise<void>
): Promise<void> {
const target = new IscsiTarget({
iqn: IQN,
host: '127.0.0.1',
port: 0,
lun: new FileBlockDevice({ path: backingPath, blockSize: BLOCK_SIZE }),
chap: CHAP,
...options,
})
await target.listen()
try {
const address = target.address()
assert.ok(address !== undefined)
await fn(address.port)
} finally {
await target.close()
}
}
async function rawConnect(port: number): Promise<Socket> {
const socket = connect(port, '127.0.0.1')
await once(socket, 'connect')
return socket
}
async function assertStillServing(initiator: IscsiInitiator): Promise<void> {
// leave the target time to act on whatever just happened
await delay(100)
assert.deepEqual(await initiator.read(0, BLOCK_SIZE), Buffer.alloc(BLOCK_SIZE, 0x5a))
}
it('a connection that sends nothing does not interrupt the session', async () => {
await withTarget({}, async port => {
const initiator = new IscsiInitiator({ host: '127.0.0.1', port, targetIqn: IQN, chap: CHAP })
await initiator.connect()
const probe = await rawConnect(port)
try {
await assertStillServing(initiator)
} finally {
probe.destroy()
await initiator.close()
}
})
})
it('a failed CHAP login does not interrupt the session', async () => {
await withTarget({}, async port => {
const initiator = new IscsiInitiator({ host: '127.0.0.1', port, targetIqn: IQN, chap: CHAP })
await initiator.connect()
try {
const intruder = new IscsiInitiator({
host: '127.0.0.1',
port,
targetIqn: IQN,
chap: { user: CHAP.user, secret: 'wrong-wrong-wrong' },
})
await assert.rejects(intruder.connect(), /login rejected/)
await assertStillServing(initiator)
} finally {
await initiator.close()
}
})
})
it('a Discovery session does not interrupt the session', async () => {
await withTarget({}, async port => {
const initiator = new IscsiInitiator({ host: '127.0.0.1', port, targetIqn: IQN, chap: CHAP })
await initiator.connect()
const socket = await rawConnect(port)
try {
const discovery = new MiniInitiator(socket)
await discovery.login('Discovery')
assert.equal((await discovery.sendTargets()).get('TargetName'), IQN)
await assertStillServing(initiator)
await discovery.logout()
} finally {
socket.destroy()
await initiator.close()
}
})
})
it('an authenticated login replaces the session', async () => {
await withTarget({}, async port => {
const stale = new IscsiInitiator({ host: '127.0.0.1', port, targetIqn: IQN, chap: CHAP })
await stale.connect()
const initiator = new IscsiInitiator({ host: '127.0.0.1', port, targetIqn: IQN, chap: CHAP })
await initiator.connect()
try {
await assert.rejects(stale.read(0, BLOCK_SIZE), /connection closed/)
await assertStillServing(initiator)
} finally {
await stale.close().catch(() => {})
await initiator.close()
}
})
})
it('closes a connection that does not log in in time', async () => {
await withTarget({ loginTimeoutMs: 100 }, async port => {
const probe = await rawConnect(port)
const closed = once(probe, 'close')
try {
await Promise.race([closed, delay(5000).then(() => assert.fail('the connection should have been closed'))])
} finally {
probe.destroy()
}
})
})
it('closes connections from an address that is not allowed, and reports it', async () => {
const refused: string[] = []
await withTarget(
{ allowedInitiatorAddresses: ['192.0.2.1'], onConnectionRefused: address => refused.push(address) },
async port => {
const probe = await rawConnect(port)
try {
await Promise.race([
once(probe, 'close'),
delay(5000).then(() => assert.fail('the connection should have been closed')),
])
} finally {
probe.destroy()
}
}
)
assert.deepEqual(refused, ['127.0.0.1'])
})
it('serves an allowed address, also in its IPv4-mapped IPv6 form', async () => {
for (const allowed of ['127.0.0.1', '::ffff:127.0.0.1']) {
await withTarget({ allowedInitiatorAddresses: [allowed] }, async port => {
const initiator = new IscsiInitiator({ host: '127.0.0.1', port, targetIqn: IQN, chap: CHAP })
await initiator.connect()
try {
await assertStillServing(initiator)
} finally {
await initiator.close()
}
})
}
})
it('refuses connections without a session past the limit', async () => {
await withTarget({ maxPendingConnections: 2 }, async port => {
const initiator = new IscsiInitiator({ host: '127.0.0.1', port, targetIqn: IQN, chap: CHAP })
await initiator.connect()
const probes = [await rawConnect(port), await rawConnect(port)]
try {
const extra = await rawConnect(port)
probes.push(extra)
await Promise.race([
once(extra, 'close'),
delay(5000).then(() => assert.fail('the connection should have been refused')),
])
assert.equal(probes[0].destroyed, false)
assert.equal(probes[1].destroyed, false)
await assertStillServing(initiator)
} finally {
for (const probe of probes) {
probe.destroy()
}
await initiator.close()
}
})
})
})
// One loopback that exercises BOTH one-way CHAP roles at once: our target is the
// authenticator (challenges + verifies) and our initiator is the responder
// (answers the challenge). This is the same code path each production role uses

View File

@@ -86,8 +86,12 @@ export class IncomingPdu {
* No per-read timeout, intentionally — a target may sit idle between commands
* indefinitely. Liveness is a transport concern (socket timeout / NOP
* keepalives), handled elsewhere.
*
* A PDU announcing a data segment longer than `maxDataSegmentLength` is
* rejected before its payload is read, so a peer cannot make us buffer up to
* the 16 MiB the 24-bit length field allows.
*/
export async function readPdu(stream: Readable): Promise<IncomingPdu | null> {
export async function readPdu(stream: Readable, maxDataSegmentLength = Infinity): Promise<IncomingPdu | null> {
const bhs = await readChunk(stream, BHS_LENGTH)
if (bhs === null) {
return null // clean EOF between PDUs
@@ -98,6 +102,9 @@ export async function readPdu(stream: Readable): Promise<IncomingPdu | null> {
const totalAhsLength = bhs.readUInt8(4)
const dataSegmentLength = bhs.readUIntBE(5, 3)
if (dataSegmentLength > maxDataSegmentLength) {
throw new Error(`iSCSI data segment too long (${dataSegmentLength} > ${maxDataSegmentLength} bytes)`)
}
const ahsBytes = totalAhsLength * 4
const dataBytesPadded = roundUp4(dataSegmentLength)

View File

@@ -56,6 +56,24 @@ describe('assemblePdu / readPdu round-trip', () => {
})
describe('readPdu framing', () => {
it('rejects a data segment longer than the limit before reading it', async () => {
const bhs = allocBhs(InitiatorOpcode.SCSI_COMMAND)
bhs.writeUIntBE(16 * 1024 * 1024 - 1, 5, 3) // announced data segment length
const stream = new PassThrough()
stream.write(bhs) // the announced payload is never sent
await assert.rejects(readPdu(stream, 8192), /data segment too long/)
})
it('accepts a data segment of exactly the limit', async () => {
const data = Buffer.alloc(8192, 0x5a)
const pdu = await (async () => {
const stream = new PassThrough()
stream.end(buildScsiCommandPdu(1, 1, Buffer.alloc(16), data))
return readPdu(stream, 8192)
})()
assert.deepEqual(pdu?.data, data)
})
it('reassembles a PDU split across multiple TCP chunks', async () => {
const data = Buffer.from('hello world!!') // 13 bytes -> padded to 16
const wire = buildScsiCommandPdu(7, 7, Buffer.alloc(16), data)

View File

@@ -40,13 +40,20 @@ export function buildStandardInquiry(identity: ScsiIdentity): Buffer {
return buffer
}
const SUPPORTED_VPD_PAGES = [0x00, 0x80, 0x83]
const SUPPORTED_VPD_PAGES = [0x00, 0x80, 0x83, 0xb0]
/** Default max length of a single READ or WRITE, in bytes. */
export const DEFAULT_MAX_TRANSFER_LENGTH = 8 * 1024 * 1024
/**
* Build an INQUIRY EVPD page, or `undefined` for an unsupported page code (the
* caller then returns CHECK CONDITION / INVALID FIELD IN CDB).
*/
export function buildVpd(pageCode: number, identity: ScsiIdentity): Buffer | undefined {
export function buildVpd(
pageCode: number,
identity: ScsiIdentity,
maxTransferBlocks = DEFAULT_MAX_TRANSFER_LENGTH / 512
): Buffer | undefined {
switch (pageCode) {
case 0x00: {
// Supported VPD pages.
@@ -83,6 +90,15 @@ export function buildVpd(pageCode: number, identity: ScsiIdentity): Buffer | und
descriptor.copy(buffer, 4)
return buffer
}
case 0xb0: {
// Block limits: initiators split their I/O to the max transfer length
// instead of seeing it refused.
const buffer = Buffer.alloc(64)
buffer[1] = 0xb0
buffer.writeUInt16BE(0x3c, 2)
buffer.writeUInt32BE(maxTransferBlocks, 8) // maximum transfer length
return buffer
}
default:
return undefined
}
@@ -125,15 +141,21 @@ export function buildFixedSense({ key, asc, ascq }: SenseInfo): Buffer {
return buffer
}
// WP bit of the device-specific parameter in the mode parameter header
const MODE_SENSE_WRITE_PROTECT = 0x80
/** Minimal MODE SENSE parameter data: a header with no block descriptor or pages. */
export function buildModeSense(long: boolean): Buffer {
export function buildModeSense(long: boolean, writeProtected = false): Buffer {
const deviceSpecific = writeProtected ? MODE_SENSE_WRITE_PROTECT : 0
if (long) {
const buffer = Buffer.alloc(8)
buffer.writeUInt16BE(6, 0) // mode data length (8 - 2)
buffer[3] = deviceSpecific
return buffer
}
const buffer = Buffer.alloc(4)
buffer[0] = 3 // mode data length (4 - 1)
buffer[2] = deviceSpecific
return buffer
}
@@ -150,6 +172,7 @@ const ILLEGAL_REQUEST_LBA_OUT_OF_RANGE: SenseInfo = {
...Asc.LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE,
}
const MEDIUM_ERROR_NO_ADDITIONAL_SENSE: SenseInfo = { key: SenseKey.MEDIUM_ERROR, ...Asc.NO_ADDITIONAL_SENSE }
const DATA_PROTECT_WRITE_PROTECTED: SenseInfo = { key: SenseKey.DATA_PROTECT, ...Asc.WRITE_PROTECTED }
function checkCondition(ctx: CommandContext, itt: number, sense: SenseInfo): Promise<void> {
return ctx.sendScsiResponse(itt, ScsiStatus.CHECK_CONDITION, { sense: buildFixedSense(sense) })
@@ -161,16 +184,22 @@ function checkCondition(ctx: CommandContext, itt: number, sense: SenseInfo): Pro
* `cdb` is the 16-byte CDB from the SCSI Command PDU and `itt` its Initiator
* Task Tag. Read commands stream Data-In; WRITE solicits Data-Out via R2T;
* everything else returns status (with sense on error).
*
* A READ or WRITE longer than `maxTransferLength` bytes, advertised in the
* block limits VPD page, is refused with INVALID FIELD IN CDB: it also bounds
* the buffer a WRITE allocates.
*/
export async function handleScsiCommand(
cdb: Buffer,
itt: number,
ctx: CommandContext,
identity: ScsiIdentity
identity: ScsiIdentity,
maxTransferLength = DEFAULT_MAX_TRANSFER_LENGTH
): Promise<void> {
const { lun } = ctx
const blockSize = lun.getBlockSize()
const blockCount = lun.getSize() / blockSize
const maxTransferBlocks = Math.floor(maxTransferLength / blockSize)
const request = decodeCdb(cdb)
log.debug('scsi command', { itt, ...request })
@@ -183,7 +212,7 @@ export async function handleScsiCommand(
}
return ctx.sendReadData(itt, buildStandardInquiry(identity), request.allocationLength)
}
const page = buildVpd(request.pageCode, identity)
const page = buildVpd(request.pageCode, identity, maxTransferBlocks)
if (page === undefined) {
return checkCondition(ctx, itt, ILLEGAL_REQUEST_INVALID_FIELD)
}
@@ -203,6 +232,9 @@ export async function handleScsiCommand(
if (request.lba + request.blocks > blockCount) {
return checkCondition(ctx, itt, ILLEGAL_REQUEST_LBA_OUT_OF_RANGE)
}
if (request.blocks > maxTransferBlocks) {
return checkCondition(ctx, itt, ILLEGAL_REQUEST_INVALID_FIELD)
}
const byteLength = request.blocks * blockSize
if (byteLength === 0) {
return ctx.sendReadData(itt, Buffer.alloc(0), 0)
@@ -221,9 +253,15 @@ export async function handleScsiCommand(
}
case 'write': {
if (lun.readOnly === true) {
return checkCondition(ctx, itt, DATA_PROTECT_WRITE_PROTECTED)
}
if (request.lba + request.blocks > blockCount) {
return checkCondition(ctx, itt, ILLEGAL_REQUEST_LBA_OUT_OF_RANGE)
}
if (request.blocks > maxTransferBlocks) {
return checkCondition(ctx, itt, ILLEGAL_REQUEST_INVALID_FIELD)
}
const byteLength = request.blocks * blockSize
if (byteLength === 0) {
return ctx.sendScsiResponse(itt, ScsiStatus.GOOD)
@@ -243,7 +281,7 @@ export async function handleScsiCommand(
}
case 'modeSense':
return ctx.sendReadData(itt, buildModeSense(request.long), request.allocationLength)
return ctx.sendReadData(itt, buildModeSense(request.long, lun.readOnly === true), request.allocationLength)
case 'syncCache':
await lun.flush()

View File

@@ -145,9 +145,17 @@ describe('response encoders', () => {
it('advertises supported VPD pages and rejects unknown ones', () => {
const page00 = buildVpd(0x00, IDENTITY)
assert.ok(page00 !== undefined)
assert.deepEqual([...page00.subarray(4)], [0x00, 0x80, 0x83])
assert.deepEqual([...page00.subarray(4)], [0x00, 0x80, 0x83, 0xb0])
assert.equal(buildVpd(0x55, IDENTITY), undefined)
})
it('advertises the max transfer length in the block limits page', () => {
const page = buildVpd(0xb0, IDENTITY, 2048)
assert.ok(page !== undefined)
assert.equal(page[1], 0xb0)
assert.equal(page.readUInt16BE(2), 0x3c)
assert.equal(page.readUInt32BE(8), 2048)
})
})
describe('handleScsiCommand', () => {
@@ -234,4 +242,61 @@ describe('handleScsiCommand', () => {
assert.equal(ctx.responses[0].status, ScsiStatus.CHECK_CONDITION)
assert.equal(ctx.responses[0].options?.sense?.[12], 0x20) // INVALID COMMAND OPERATION CODE
})
for (const [name, opcode] of [
['READ(10)', 0x28],
['WRITE(10)', 0x2a],
] as const) {
it(`refuses a ${name} longer than the max transfer length, without reading or soliciting data`, async () => {
let reads = 0
const lun = new MemoryBlockDevice(8192)
const read = lun.read.bind(lun)
lun.read = (offset, length) => {
reads++
return read(offset, length)
}
const ctx = new FakeContext(lun)
const buffer = Buffer.alloc(16)
buffer[0] = opcode
buffer.writeUInt16BE(3, 7) // 3 blocks, the limit is 2
await handleScsiCommand(buffer, 1, ctx, IDENTITY, 1024)
assert.equal(ctx.responses[0].status, ScsiStatus.CHECK_CONDITION)
assert.equal(ctx.responses[0].options?.sense?.[2], SenseKey.ILLEGAL_REQUEST)
assert.equal(ctx.responses[0].options?.sense?.[12], 0x24) // INVALID FIELD IN CDB
assert.equal(reads, 0)
assert.equal(ctx.writes.length, 0)
})
}
describe('read-only LUN', () => {
class ReadOnlyBlockDevice extends MemoryBlockDevice {
readonly readOnly = true
}
it('refuses WRITE(10) with DATA PROTECT, without soliciting its data', async () => {
const ctx = new FakeContext(new ReadOnlyBlockDevice(4096))
const buffer = Buffer.alloc(16)
buffer[0] = 0x2a
buffer.writeUInt16BE(1, 7)
await handleScsiCommand(buffer, 1, ctx, IDENTITY)
assert.equal(ctx.writes.length, 0)
assert.equal(ctx.responses[0].status, ScsiStatus.CHECK_CONDITION)
assert.equal(ctx.responses[0].options?.sense?.[2], SenseKey.DATA_PROTECT)
assert.equal(ctx.responses[0].options?.sense?.[12], 0x27) // WRITE PROTECTED
})
it('reports write protection in MODE SENSE(6) and MODE SENSE(10)', async () => {
const ctx = new FakeContext(new ReadOnlyBlockDevice(4096))
await handleScsiCommand(cdb(0x1a, 0x00, 0x3f, 0x00, 255), 1, ctx, IDENTITY)
await handleScsiCommand(cdb(0x5a, 0x00, 0x3f, 0, 0, 0, 0, 0x01, 0x00), 2, ctx, IDENTITY)
assert.equal(ctx.reads[0].data[2] & 0x80, 0x80)
assert.equal(ctx.reads[1].data[3] & 0x80, 0x80)
})
it('does not report a writable LUN as write-protected', async () => {
const ctx = new FakeContext(new MemoryBlockDevice(4096))
await handleScsiCommand(cdb(0x1a, 0x00, 0x3f, 0x00, 255), 1, ctx, IDENTITY)
assert.equal(ctx.reads[0].data[2] & 0x80, 0)
})
})
})

View File

@@ -56,17 +56,21 @@ function parseAttachedDisk(sessionOutput: string): string | undefined {
}
/**
* `stat()`ing the device node only proves udev created it, not that the SCSI
* layer has finished attaching it — `open()` right after can still fail with
* ENXIO. `/sys/class/block/<name>/size` reporting nonzero is what actually
* means ready, the same check `_cache.mjs`'s `openLocalDevice` uses for the
* same reason on XAPI-plugged devices.
* Neither the device node nor a nonzero `/sys/class/block/<name>/size` means
* the disk can be opened: the sd driver sets the size before
* `device_add_disk()`, which creates the sysfs entry, then the `/dev` node, then
* registers the block device: until then `open()` fails with ENOENT or ENXIO.
* Only an `open()` that succeeds means ready.
*/
async function isDeviceReady(name: string): Promise<boolean> {
try {
return Number.parseInt(await readFile(`/sys/class/block/${name}/size`, 'utf8'), 10) > 0
} catch {
return false
await (await openFile(`/dev/${name}`, 'r')).close()
return true
} catch (error) {
if (error instanceof Error && 'code' in error && (error.code === 'ENXIO' || error.code === 'ENOENT')) {
return false
}
throw error
}
}

View File

@@ -1,4 +1,7 @@
import { Socket } from 'node:net'
import { once } from 'node:events'
import { request as httpRequest } from 'node:http'
import { request as httpsRequest } from 'node:https'
import { isIPv6, Socket } from 'node:net'
import { connect } from 'node:tls'
import { spawn } from 'node:child_process'
import AbstractNbdClient from './AbstractNbdClient.mjs'
@@ -11,6 +14,9 @@ import { NBD_DEFAULT_PORT, NBD_OPT_STARTTLS } from './constants.mjs'
* @extends {AbstractNbdClient}
*/
export default class NbdTcpClient extends AbstractNbdClient {
#httpProxy
#proxyRejectUnauthorized
#proxyTimeout
#serverAddress
#serverCert
#serverPort
@@ -21,18 +27,103 @@ export default class NbdTcpClient extends AbstractNbdClient {
* @param {number} [settings.port]
* @param {string} [settings.exportname]
* @param {string} [settings.cert] - PEM certificate, enables TLS when set
* @param {string} [settings.httpProxy] - URL of an HTTP(S) proxy, the connection is tunneled through it with `CONNECT`
* @param {boolean} [settings.proxyRejectUnauthorized=true] - whether to check the certificate of an HTTPS proxy
* @param {number} [settings.proxyTimeout=6e4] - delay in ms after which an unanswered `CONNECT` is aborted
* @param {object} [options] - see {@link AbstractNbdClient}
*/
constructor({ address, port = NBD_DEFAULT_PORT, exportname, cert }, options) {
constructor(
{
address,
port = NBD_DEFAULT_PORT,
exportname,
cert,
httpProxy,
proxyRejectUnauthorized = true,
proxyTimeout = 6e4,
},
options
) {
super({ exportname }, options)
// other proxy protocols (e.g. SOCKS) are not supported for now
if (httpProxy !== undefined) {
const { protocol } = new URL(httpProxy)
if (protocol !== 'http:' && protocol !== 'https:') {
const error = new Error(`unsupported proxy protocol ${protocol}, only http: and https: are supported`)
error.code = 'NBD_PROXY_UNSUPPORTED_PROTOCOL'
throw error
}
}
this.#serverAddress = address
this.#serverPort = port
this.#serverCert = cert
this.#httpProxy = httpProxy
this.#proxyRejectUnauthorized = proxyRejectUnauthorized
this.#proxyTimeout = proxyTimeout
}
/**
* Open a raw TCP tunnel to the NBD server through an HTTP proxy
*
* https://datatracker.ietf.org/doc/html/rfc9110#section-9.3.6
*
* @returns {Promise<import('node:net').Socket>}
*/
async #connectThroughHttpProxy() {
const proxy = new URL(this.#httpProxy)
const isHttps = proxy.protocol === 'https:'
const address = this.#serverAddress
const target = `${isIPv6(address) ? `[${address}]` : address}:${this.#serverPort}`
const headers = { host: target }
if (proxy.username !== '' || proxy.password !== '') {
const credentials = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`
headers['proxy-authorization'] = `Basic ${Buffer.from(credentials).toString('base64')}`
}
const req = (isHttps ? httpsRequest : httpRequest)({
agent: false,
headers,
// URL keeps the brackets around IPv6 addresses
hostname: proxy.hostname.replace(/^\[(.*)\]$/, '$1'),
method: 'CONNECT',
path: target,
port: proxy.port,
rejectUnauthorized: this.#proxyRejectUnauthorized,
timeout: this.#proxyTimeout,
})
// `timeout` only emits an event, the request must be aborted explicitly
req.on('timeout', () => {
const error = new Error(`HTTP proxy did not answer the CONNECT to ${target} in time`)
error.code = 'NBD_PROXY_CONNECT_TIMEOUT'
req.destroy(error)
})
req.end()
// the NBD server may already have sent some data, it is in `head`
const [res, socket, head] = await once(req, 'connect')
// the tunnel is established, NBD has its own timeouts
socket.setTimeout(0)
if (res.statusCode !== 200) {
socket.destroy()
const error = new Error(`HTTP proxy refused to connect to ${target}: ${res.statusCode} ${res.statusMessage}`)
error.code = 'NBD_PROXY_CONNECT_FAILED'
throw error
}
if (head.length !== 0) {
socket.unshift(head)
}
return socket
}
// mandatory , at least to start the handshake: the connection always starts
// unsecured, and is upgraded to TLS during the handshake
async _openTransport() {
if (this.#httpProxy !== undefined) {
const socket = await this.#connectThroughHttpProxy()
return { readable: socket, writable: socket }
}
const socket = new Socket()
await new Promise((resolve, reject) => {
socket.connect(this.#serverPort, this.#serverAddress)

View File

@@ -0,0 +1,107 @@
import assert from 'node:assert/strict'
import { after, before, describe, it } from 'node:test'
import { createServer as createHttpServer } from 'node:http'
import { connect, createServer as createTcpServer } from 'node:net'
import { once } from 'node:events'
import NbdTcpClient from './NbdTcpClient.mjs'
import { serveNbd } from './tests/fake-nbd-server.mjs'
const BLOCK_SIZE = 64 * 1024
const DATA = Buffer.alloc(4 * BLOCK_SIZE)
for (let i = 0; i < DATA.length; i++) {
DATA[i] = i % 251
}
const CREDENTIALS = 'Basic ' + Buffer.from('user:p@ss').toString('base64')
describe('NbdTcpClient through an HTTP proxy', () => {
let nbdServer, proxyServer, nbdPort, proxyPort
const connectRequests = []
before(async () => {
nbdServer = createTcpServer(socket => {
serveNbd({ readable: socket, writable: socket, data: DATA }).catch(() => {})
})
nbdServer.listen(0, '127.0.0.1')
await once(nbdServer, 'listening')
nbdPort = nbdServer.address().port
// minimal CONNECT proxy, similar to the XO Proxy one
proxyServer = createHttpServer()
proxyServer.on('connect', (req, clientSocket, head) => {
connectRequests.push(req.url)
if (req.headers['proxy-authorization'] !== CREDENTIALS) {
clientSocket.end('HTTP/1.1 407 Proxy Authentication Required\r\n\r\n')
return
}
const { hostname, port } = new URL('http://' + req.url)
const serverSocket = connect(port, hostname, () => {
clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n')
serverSocket.write(head)
serverSocket.pipe(clientSocket).pipe(serverSocket)
})
serverSocket.on('error', () => clientSocket.destroy())
clientSocket.on('error', () => serverSocket.destroy())
})
proxyServer.listen(0, '127.0.0.1')
await once(proxyServer, 'listening')
proxyPort = proxyServer.address().port
})
after(() => {
proxyServer.closeAllConnections()
proxyServer.close()
nbdServer.close()
})
it('tunnels the NBD connection with CONNECT', async () => {
const client = new NbdTcpClient({
address: '127.0.0.1',
port: nbdPort,
httpProxy: `http://user:p%40ss@127.0.0.1:${proxyPort}`,
})
await client.connect()
try {
assert.equal(client.exportSize, BigInt(DATA.length))
const block = await client.readBlock(2, BLOCK_SIZE)
assert.deepEqual(block, DATA.subarray(2 * BLOCK_SIZE, 3 * BLOCK_SIZE))
} finally {
await client.disconnect()
}
assert.equal(connectRequests.at(-1), `127.0.0.1:${nbdPort}`)
})
it('fails when the proxy refuses the connection', async () => {
const client = new NbdTcpClient({
address: '127.0.0.1',
port: nbdPort,
httpProxy: `http://user:wrong@127.0.0.1:${proxyPort}`,
})
await assert.rejects(client.connect(), { code: 'NBD_PROXY_CONNECT_FAILED' })
await client.disconnect().catch(() => {})
})
it('aborts the CONNECT when the proxy does not answer', async () => {
// accepts the TCP connection but never answers
const silentProxy = createTcpServer(() => {})
silentProxy.listen(0, '127.0.0.1')
await once(silentProxy, 'listening')
try {
const client = new NbdTcpClient({
address: '127.0.0.1',
port: nbdPort,
httpProxy: `http://127.0.0.1:${silentProxy.address().port}`,
proxyTimeout: 50,
})
await assert.rejects(client.connect(), { code: 'NBD_PROXY_CONNECT_TIMEOUT' })
} finally {
silentProxy.close()
}
})
it('rejects unsupported proxy protocols', () => {
assert.throws(() => new NbdTcpClient({ address: '127.0.0.1', httpProxy: 'socks5://127.0.0.1:1080' }), {
code: 'NBD_PROXY_UNSUPPORTED_PROTOCOL',
})
})
})

View File

@@ -34,7 +34,8 @@
"typescript": "~5.6.3",
"typescript-eslint": "^8.61.0",
"@types/express": "^5.0.0",
"@xen-orchestra/disk-transform": "^1.3.3"
"@xen-orchestra/disk-transform": "^1.3.3",
"complex-matcher": "^1.1.1"
},
"scripts": {
"build": "tsc",

View File

@@ -663,6 +663,19 @@ export const SUPPORTED_VDI_FORMAT = {
export type SUPPORTED_VDI_FORMAT = (typeof SUPPORTED_VDI_FORMAT)[keyof typeof SUPPORTED_VDI_FORMAT]
/**
* Formats a VDI can be exported to by XO: the XAPI ones, plus the ones XO generates
* itself from the blocks of the disk.
*/
export const SUPPORTED_VDI_EXPORT_FORMAT = {
raw: 'raw',
vhd: 'vhd',
qcow2: 'qcow2',
vmdk: 'vmdk',
} as const
export type SUPPORTED_VDI_EXPORT_FORMAT = (typeof SUPPORTED_VDI_EXPORT_FORMAT)[keyof typeof SUPPORTED_VDI_EXPORT_FORMAT]
// ----- XAPI Stats
type XapiStatsResponse<T> = {

View File

@@ -1,4 +1,4 @@
import { EventEmitter, Readable } from 'node:stream'
import type { EventEmitter, Readable } from 'node:stream'
import type {
AnyXoJob,
AnyXoLog,
@@ -12,6 +12,7 @@ import type {
XoPool,
XoPoolBackupArchive,
XoProxy,
XoRecord,
XoSchedule,
XoServer,
XoTask,
@@ -23,6 +24,7 @@ import type {
import { VatesTask } from './lib/vates-task.mjs'
import type { PluginRestRouteDefinition } from './lib/rest-api.mjs'
import type { RPU_RECOVERY_STEP_NAME } from './common.mjs'
import type { Node as CmNode, Resolver } from 'complex-matcher'
import {
Xapi,
XapiHostStats,
@@ -52,7 +54,6 @@ import {
XoGroupRole,
XoUserRole,
} from './index.mjs'
import { IncomingHttpHeaders } from 'node:http'
type FeatureCode =
| 'BACKUP.DELTA'
@@ -192,7 +193,16 @@ export type BackupArchiveDiskMount = {
port: number
}
export type XoApp = {
type XoStoreRangeOptions = {
gt?: string
gte?: string
lt?: string
lte?: string
limit?: number
reverse?: boolean
}
export type XoApp = EventEmitter & {
hooks: EventEmitter
_redis: {
get(key: string): Promise<string | null>
@@ -253,6 +263,7 @@ export type XoApp = {
user?: XoUser
permission?: XoUser['permission'] | 'none' | null
}
backupLogsEe: EventEmitter
// methods ------------
allocIpAddresses(vifId: XoVif['id'], addAddresses?: string[], removeAddresses?: string[]): Promise<void>
@@ -297,6 +308,13 @@ export type XoApp = {
description?: XoAclRole['description']
privileges?: Omit<XoAclBasePrivilege, 'id' | 'roleId'>[]
}): Promise<XoAclRole>
createApiConnection(remoteAddress: string): EventEmitter & {
close(): void
get<T = unknown>(key: string, defaultValue: unknown): T
has(key: string): boolean
set(key: string, value: unknown): void
unset(key: string): void
}
createAuthenticationToken(opts: {
client?: {
id?: string
@@ -343,6 +361,7 @@ export type XoApp = {
roleId: XoAclRole['id'],
opts?: { bypassAuthorization?: boolean }
): Promise<boolean>
deleteSchedule(id: XoSchedule['id']): Promise<void>
getAclV2GroupRoles(
groupId: XoGroup['id'],
opts?: { bypassAuthorization?: boolean }
@@ -389,6 +408,10 @@ export type XoApp = {
}
getBackupNgLogs(): Promise<Record<string, AnyXoLog>>
getBackupNgLogs(id: AnyXoLog['id']): Promise<AnyXoLog>
/** Please use `REMOVE_CACHE_ENTRY` const to clear the cache */
getBackupNgLogs(removeCacheEntry: {}): void
/** Please use `REMOVE_CACHE_ENTRY` const to clear a cache entry */
getBackupNgLogs(removeCacheEntry: {}, id: AnyXoLog['id']): void
getBackupNgLogsSorted(opts: {
after?: number
before?: number
@@ -406,6 +429,18 @@ export type XoApp = {
) => Record<T['id'], T> | undefined
getTotalBackupSizeOnRemote(id: XoBackupRepository['id']): Promise<{ onDisk: number }>
getSchedule(id: XoSchedule['id']): Promise<XoSchedule>
getStore(namespace: string): Promise<{
/** rejects with an error having `notFound: true` when the key does not exist */
get(key: string): Promise<unknown>
has(key: string): Promise<boolean>
put(key: string, value: unknown): Promise<void>
del(key: string): Promise<void>
del(key: string, cb: (error?: Error | null) => void): void
/** object mode stream of `{ key, value }` */
createReadStream(opts?: XoStoreRangeOptions): Readable
/** object mode stream of keys */
createKeyStream(opts?: XoStoreRangeOptions): Readable
}>
getUser: (id: XoUser['id'], opts?: { obfuscatePassword?: boolean }) => Promise<XoUser>
getUserIdentityFields(): string[]
getXapi(maybeId: XapiXoRecord['id'] | XapiXoRecord): Xapi
@@ -420,20 +455,6 @@ export type XoApp = {
getXoEventEmitterByType(type: string): EventEmitter
hasFeatureAuthorization(featureCode: string): Promise<boolean>
hasObject<T extends XapiXoRecord>(id: T['id'], type: T['type']): boolean
httpRequest(
url: string,
opts: {
auth?: string
body?: string | NodeJS.ArrayBufferView | Readable | null
bypassStatusCheck?: boolean
headers?: IncomingHttpHeaders
method: string
rejectUnauthorized?: boolean
bodyTimeout?: number
headersTimeout?: number
signal?: AbortSignal
}
): Promise<Response>
listMetadataBackups(backupRepositoryIds: XoBackupRepository['id'][]): Promise<{
xo: Record<XoBackupRepository['id'], XoConfigBackupArchive[]>
pool: Record<XoBackupRepository['id'], Record<XoPool['id'], XoPoolBackupArchive[]>>
@@ -456,6 +477,7 @@ export type XoApp = {
diskId: string
hostId: XoHost['id']
}): Promise<BackupArchiveDiskMount>
getVmBackupArchive(id: XoVmBackupArchive['id']): Promise<XoVmBackupArchive>
pingRemote(id: XoBackupRepository['id']): Promise<{ success: true }>
/**
* Record the live mounts a proxy created by itself, while running a restore: they never went
@@ -560,6 +582,10 @@ export type XoApp = {
): Promise<XoBackupRepository>
getAllXapis(): Record<string, Xapi>
getObjects(opts?: { filter?: Record<string, unknown>; limit?: number }): Record<string, XapiXoRecord>
getAnyObject<T extends XoRecord>(id: T['id']): Promise<T>
/** Can't be narrower as buildResolver will be asked to walk objects */
buildResolver(objects: object | object[], node: CmNode): Promise<Resolver>
xapiObjectResolver: Resolver
getLicenses(params?: { productType?: LicenseProductType }): Promise<License[]>
bindLicense(params: { licenseId: string; boundObjectId: string }): Promise<License>
unbindLicense(params: {

View File

@@ -118,7 +118,7 @@ type BaseXoVm = BaseXapiXo & {
/**
* @deprecated use pvDriversVersion instead
*/
xentools?:
xenTools?:
| false
| {
major: null | number
@@ -609,6 +609,7 @@ export type XoServer = {
label?: string
master?: XoHost['id']
poolId?: XoPool['id']
poolMembersAddresses?: string[]
poolNameDescription?: string
poolNameLabel?: string
readOnly: boolean

View File

@@ -25,4 +25,14 @@ export default {
update: {
tags: true,
},
probe: {
nfs: true,
zfs: true,
hba: true,
iscsiiqn: true,
iscsilun: true,
'iscsi-exists': true,
'hba-exists': true,
'nfs-exists': true,
},
}

View File

@@ -8,8 +8,6 @@ import { default as backupRepository } from './backup-repository.mjs'
import { default as gpuGroup } from './gpuGroup.mjs'
import { default as group } from './group.mjs'
import { default as host } from './host.mjs'
import { default as kubernetesCluster } from './kubernetes-cluster.mjs'
import { default as kubernetesNode } from './kubernetes-node.mjs'
import { default as message } from './message.mjs'
import { default as network } from './network.mjs'
import { default as pbd } from './pbd.mjs'
@@ -52,8 +50,6 @@ export const SUPPORTED_ACTIONS_BY_RESOURCE = {
group,
gpuGroup,
host,
'kubernetes-cluster': kubernetesCluster,
'kubernetes-node': kubernetesNode,
message,
network,
pbd,

View File

@@ -1,6 +0,0 @@
export default {
create: true,
delete: true,
read: true,
'read-config': true,
}

View File

@@ -1,3 +0,0 @@
export default {
read: true,
}

View File

@@ -14,21 +14,24 @@ export class Privilege<T extends SupportedResource> {
#resource: TPrivilege<T>['resource']
#effect: TPrivilege<T>['effect']
constructor({
action,
selector,
resource,
effect,
}: {
action: TPrivilege<T>['action']
selector?: TPrivilege<T>['selector']
resource: TPrivilege<T>['resource']
effect: TPrivilege<T>['effect']
}) {
constructor(
{
action,
selector,
resource,
effect,
}: {
action: TPrivilege<T>['action']
selector?: TPrivilege<T>['selector']
resource: TPrivilege<T>['resource']
effect: TPrivilege<T>['effect']
},
resolver?: CM.Resolver
) {
Privilege.checkActionIsValid(resource, action)
this.#action = action
this.#selector = selector !== undefined ? CM.parse(selector).createPredicate() : undefined
this.#selector = selector !== undefined ? CM.parse(selector).createPredicate(resolver) : undefined
this.#resource = resource
this.#effect = effect
}

View File

@@ -1,4 +1,3 @@
import assert from 'node:assert'
import type { XoUser } from '@vates/types/xo'
import { SUPPORTED_ACTIONS_BY_RESOURCE } from './actions/index.mjs'
@@ -17,6 +16,7 @@ export { SUPPORTED_ACTIONS_BY_RESOURCE }
export type * from './generated/privilege-types.mjs'
import { AnyPrivilege } from './generated/privilege-types.mjs'
import type { Resolver } from 'complex-matcher'
export type AnyPrivilegeOnParam = {
[Resource in SupportedResource]: {
@@ -27,25 +27,39 @@ export type AnyPrivilegeOnParam = {
}
}[SupportedResource]
export function hasPrivilegeOn<T extends SupportedResource>({
user,
action,
resource,
objects,
userPrivileges,
}: {
user: XoUser
resource: T
action: SupportedActions<T>
objects: object | object[]
userPrivileges: AnyPrivilege[]
}) {
export function hasPrivilegeOn<T extends SupportedResource>(
{
user,
action,
resource,
objects,
userPrivileges,
}: {
user: XoUser
resource: T
action: SupportedActions<T>
objects: object | object[]
userPrivileges: AnyPrivilege[]
},
resolver?: Resolver
) {
// Function that will be called outside of the module
// We cannot be sure types are respected
assert.strictEqual(typeof user?.permission, 'string')
assert.strictEqual(typeof action, 'string')
assert.strictEqual(typeof resource, 'string')
assert.strictEqual(objects === undefined, false)
if (typeof user?.permission !== 'string') {
throw new TypeError('user.permission must be a string')
}
if (typeof action !== 'string') {
throw new TypeError('action must be a string')
}
if (typeof resource !== 'string') {
throw new TypeError('resource must be a string')
}
if (objects === undefined) {
throw new TypeError('objects must be defined')
}
CPrivilege.checkActionIsValid(resource, action as SupportedActions<typeof resource>)
@@ -61,7 +75,7 @@ export function hasPrivilegeOn<T extends SupportedResource>({
}
for (const userPrivilege of userPrivileges) {
const privilege = new CPrivilege(userPrivilege as Privilege<typeof userPrivilege.resource>)
const privilege = new CPrivilege(userPrivilege as Privilege<typeof userPrivilege.resource>, resolver)
for (const [object, effects] of effectsByObject.entries()) {
if (!privilege.match({ action, resource, object })) {
@@ -81,17 +95,24 @@ export function hasPrivilegeOn<T extends SupportedResource>({
return true
}
export function getMissingPrivileges(params: AnyPrivilegeOnParam[], userPrivileges: AnyPrivilege[]) {
export function getMissingPrivileges(
params: AnyPrivilegeOnParam[],
userPrivileges: AnyPrivilege[],
resolver?: Resolver
) {
return params
.filter(
param =>
!hasPrivilegeOn({
user: param.user,
resource: param.resource,
action: param.action as SupportedActions<typeof param.resource>,
objects: param.objects,
userPrivileges,
})
!hasPrivilegeOn(
{
user: param.user,
resource: param.resource,
action: param.action as SupportedActions<typeof param.resource>,
objects: param.objects,
userPrivileges,
},
resolver
)
)
.map(({ action, objects, resource }) => {
let objectIds: unknown[] | undefined
@@ -122,18 +143,21 @@ export function getMissingPrivileges(params: AnyPrivilegeOnParam[], userPrivileg
})
}
export function hasPrivileges(params: AnyPrivilegeOnParam[], userPrivileges: AnyPrivilege[]) {
return getMissingPrivileges(params, userPrivileges).length === 0
export function hasPrivileges(params: AnyPrivilegeOnParam[], userPrivileges: AnyPrivilege[], resolver?: Resolver) {
return getMissingPrivileges(params, userPrivileges, resolver).length === 0
}
export function filterObjectsWithPrivilege<Resource extends SupportedResource, Object extends object>(param: {
user: XoUser
resource: Resource
action: SupportedActions<Resource>
objects: Object[]
userPrivileges: AnyPrivilege[]
}) {
return param.objects.filter(obj => hasPrivilegeOn({ ...param, objects: obj }))
export function filterObjectsWithPrivilege<Resource extends SupportedResource, Object extends object>(
param: {
user: XoUser
resource: Resource
action: SupportedActions<Resource>
objects: Object[]
userPrivileges: AnyPrivilege[]
},
resolver?: Resolver
) {
return param.objects.filter(obj => hasPrivilegeOn({ ...param, objects: obj }, resolver))
}
// Utils

View File

@@ -91,6 +91,9 @@ suite('ACL V2 behavior', async () => {
const templateDeny = { id: 'template-deny-id', $pool: '2' }
const vdis = [{ $SR: '2' }, { $SR: '2' }]
const vdisMultipleSrs = [{ $SR: '1' }, { $SR: '2' }]
const vdisOnTaggedSr = [{ $SR: '4' }]
const vdisOnUntaggedSr = [{ $SR: '5' }]
const srs = { '4': { tags: ['tag'] } }
const vifs = [{ $network: '1' }]
const iso = { id: 'iso-vdi-id', $SR: '3' }
const hostAffinity = { id: 'affinity-host-id', $pool: '1' }
@@ -121,6 +124,14 @@ suite('ACL V2 behavior', async () => {
effect: 'allow',
roleId,
} satisfies TPrivilege<'vdi'>
const vdiCreateResolve = {
id: privilegeId,
action: 'create',
resource: 'vdi',
selector: '$SR:[resolve]:tags:tag',
effect: 'allow',
roleId,
} satisfies TPrivilege<'vdi'>
const vifCreate = {
id: privilegeId,
action: 'create',
@@ -171,6 +182,11 @@ suite('ACL V2 behavior', async () => {
hostVm,
]
const resolvePrivileges = [vdiCreateResolve]
// === Resolvers
const srTagResolver = (id: string) => srs[id]
// === Test ===
suite('hasPrivilegeOn behavior', () => {
test('Should always return true for admin', () => {
@@ -258,6 +274,35 @@ suite('ACL V2 behavior', async () => {
false
)
})
test('should allow create on vdi whose SR has tag', () => {
assert.strictEqual(
hasPrivilegeOn(
{
user,
action: 'create',
resource: 'vdi',
objects: vdisOnTaggedSr,
userPrivileges: resolvePrivileges,
},
srTagResolver
),
true
)
assert.strictEqual(
hasPrivilegeOn(
{
user,
action: 'create',
resource: 'vdi',
objects: vdisOnUntaggedSr,
userPrivileges: resolvePrivileges,
},
srTagResolver
),
false
)
})
})
suite('getMissingPrivileges behavior', () => {

View File

@@ -45,11 +45,6 @@ export class RemoteVhdDisk extends RemoteDisk {
*/
#blockSize = 2 * 1024 * 1024
/**
* @type {number}
*/
#bitmapSize = 512
/**
* @type {() => any}
*/
@@ -263,10 +258,7 @@ export class RemoteVhdDisk extends RemoteDisk {
if (this.#vhd === undefined) {
throw new Error(`can't call readBlock of a RemoteVhdDisk before init`)
}
await this.#vhd.writeEntireBlock({
id: diskBlock.index,
buffer: Buffer.concat([Buffer.alloc(this.#bitmapSize, 255), diskBlock.data]),
})
await this.#vhd.writeBlockData(diskBlock.index, diskBlock.data)
return this.getBlockSize()
}

View File

@@ -28,6 +28,7 @@ function getEncryptor(algorithm = DEFAULT_ENCRYPTION_ALGORITHM, key) {
ivLength: 0,
authTagLength: 0,
encryptData: buffer => buffer,
encryptDataParts: buffers => buffers,
encryptStream: stream => stream,
decryptData: buffer => buffer,
decryptStream: stream => stream,
@@ -109,11 +110,17 @@ function getEncryptor(algorithm = DEFAULT_ENCRYPTION_ALGORITHM, key) {
)
}
function encryptData(buffer) {
// data can be an array of buffers, encrypted as their concatenation
// returns the encrypted file as an array of buffers, to be written one after the other
function encryptDataParts(data) {
const iv = crypto.randomBytes(ivLength)
const cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv)
const encrypted = cipher.update(buffer)
return Buffer.concat([iv, encrypted, cipher.final(), authTagLength > 0 ? cipher.getAuthTag() : Buffer.alloc(0)])
const encrypted = Array.isArray(data) ? data.map(buffer => cipher.update(buffer)) : [cipher.update(data)]
return [iv, ...encrypted, cipher.final(), authTagLength > 0 ? cipher.getAuthTag() : Buffer.alloc(0)]
}
function encryptData(data) {
return Buffer.concat(encryptDataParts(data))
}
function decryptData(buffer) {
@@ -128,7 +135,10 @@ function getEncryptor(algorithm = DEFAULT_ENCRYPTION_ALGORITHM, key) {
encrypted = buffer.slice(ivLength)
}
const decrypted = decipher.update(encrypted)
return Buffer.concat([decrypted, decipher.final()])
// final() must always be called: it checks the auth tag
const final = decipher.final()
// nothing is left with stream modes (like GCM): no need to copy the data
return final.length === 0 ? decrypted : Buffer.concat([decrypted, final])
}
return {
@@ -138,6 +148,7 @@ function getEncryptor(algorithm = DEFAULT_ENCRYPTION_ALGORITHM, key) {
authTagLength,
ivLength,
encryptData,
encryptDataParts,
encryptStream,
decryptData,
decryptStream,

View File

@@ -36,6 +36,16 @@ algorithms.forEach(algorithm => {
assert.equal(decrypted.equals(buffer), true)
})
it('handle an array of buffers', () => {
// like a VHD block: a bitmap then the data, sizes not aligned on the cipher block size
const parts = [crypto.randomBytes(512), crypto.randomBytes(1024 * 1024 + 1)]
const encrypted = Buffer.concat(encryptor.encryptDataParts(parts))
// same layout as a single buffer: existing remotes must still be readable
const decrypted = encryptor.decryptData(encrypted)
assert.equal(decrypted.equals(Buffer.concat(parts)), true)
})
it('handle stream', async () => {
const stream = Readable.from(buffer)
stream.length = buffer.length

View File

@@ -397,8 +397,15 @@ export default class RemoteHandlerAbstract {
await this._mktree(normalizePath(dir), { mode })
}
// data can be an array of buffers, the file is then their concatenation
async outputFile(file, data, { dirMode, flags = 'wx' } = {}) {
const encryptedData = this.#encryptor.encryptData(data)
// the encrypted parts are not concatenated when the handler can write them as is
let encryptedData = this._writesBufferArrays
? this.#encryptor.encryptDataParts(data)
: this.#encryptor.encryptData(data)
if (Array.isArray(encryptedData) && !this._writesBufferArrays) {
encryptedData = Buffer.concat(encryptedData)
}
await this._outputFile(normalizePath(file), encryptedData, { dirMode, flags })
}
@@ -803,6 +810,11 @@ export default class RemoteHandlerAbstract {
throw new Error('Not implemented')
}
// whether _writeFile accepts an array of buffers (written one after the other, without concatenating them)
get _writesBufferArrays() {
return false
}
get isEncrypted() {
return this.#encryptor.id !== 'NULL_ENCRYPTOR'
}

View File

@@ -249,8 +249,19 @@ export default class AzureHandler extends RemoteHandlerAbstract {
}
file = this.#makeFullPath(file)
const blobClient = this.#containerClient.getBlobClient(file)
const properties = await blobClient.getProperties()
return properties.contentLength
try {
const properties = await blobClient.getProperties()
return properties.contentLength
} catch (e) {
// a HEAD response has no body, so there is no BlobNotFound code to match
if (e.name === 'RestError' && e.statusCode === 404) {
const error = new Error(`ENOENT: no such file '${file}'`, { cause: e })
error.code = 'ENOENT'
error.path = file
throw error
}
throw e
}
}
async _read(file, buffer, position = 0) {

View File

@@ -51,6 +51,22 @@ function dontAddSyncStackTrace(fn, ...args) {
return fn.apply(this, args)
}
// writes the buffers one after the other with writev: no need to concatenate them
// libuv already resumes the partial writes, a short count means the write stopped (like a full disk)
// fs-extra goes through graceful-fs: an EMFILE on open is queued, like with fs.writeFile
async function writeBuffers(path, buffers, flags) {
const fd = await fs.open(path, flags)
try {
const length = buffers.reduce((sum, buffer) => sum + buffer.length, 0)
const { bytesWritten } = await fs.writev(fd, buffers, 0)
if (bytesWritten !== length) {
throw new Error(`incomplete write of ${path}: ${bytesWritten} of ${length} bytes`)
}
} finally {
await fs.close(fd)
}
}
export default class LocalHandler extends RemoteHandlerAbstract {
#addSyncStackTrace
#retriesOnEagain
@@ -250,6 +266,13 @@ export default class LocalHandler extends RemoteHandlerAbstract {
}
_writeFile(file, data, { flags }) {
if (Array.isArray(data)) {
return this.#addSyncStackTrace(writeBuffers, this.getFilePath(file), data, flags)
}
return this.#addSyncStackTrace(fs.writeFile, this.getFilePath(file), data, { flag: flags })
}
get _writesBufferArrays() {
return true
}
}

View File

@@ -303,7 +303,14 @@ export default class S3Handler extends RemoteHandlerAbstract {
}
async _unlink(path) {
await this.#s3.send(new DeleteObjectCommand(this.#createParams(path)))
try {
await this.#s3.send(new DeleteObjectCommand(this.#createParams(path)))
} catch (error) {
// Some providers answers 404 NoSuchKey where AWS answers 204
if (error.name !== 'NoSuchKey' && error.$metadata?.httpStatusCode !== 404) {
throw error
}
}
if (await this.#isNotEmptyDir(path)) {
const error = new Error(`EISDIR: illegal operation on a directory, unlink '${path}'`)
@@ -370,8 +377,20 @@ export default class S3Handler extends RemoteHandlerAbstract {
if (typeof file !== 'string') {
file = file.fd
}
const result = await this.#s3.send(new HeadObjectCommand(this.#createParams(file)))
return +result.ContentLength
try {
const result = await this.#s3.send(new HeadObjectCommand(this.#createParams(file)))
return +result.ContentLength
} catch (error) {
// a HEAD response has no body, so a missing object is reported as
// NotFound instead of the NoSuchKey the other methods get
if (error.name === 'NotFound' || error.$metadata?.httpStatusCode === 404) {
const enoentError = new Error(`ENOENT: no such file '${file}'`, { cause: error })
enoentError.code = 'ENOENT'
enoentError.path = file
throw enoentError
}
throw error
}
}
async _read(file, buffer, position = 0) {

View File

@@ -136,7 +136,7 @@ export abstract class RemoteHandlerAbstract {
abstract read(file: FileDescriptor, buffer: Buffer, position?: number): Promise<ReadResult>
abstract outputStream(path: string, input: Readable, options?: OutputStreamOptions): Promise<void>
abstract outputFile(file: string, data: string | Buffer, options?: OutputFileOptions): Promise<void>
abstract outputFile(file: string, data: string | Buffer | Buffer[], options?: OutputFileOptions): Promise<void>
abstract writeFile(file: string, data: string | Buffer, options?: WriteFileOptions): Promise<void>
abstract write(file: FileArg, buffer: Buffer, position?: number): Promise<void>

View File

@@ -139,7 +139,13 @@ describe('protectRemotes/watchRemote', async () => {
await fs.writeFile(path.join(vmDir, `${BACKUP_DATE}.json`), '{}')
// The whole directory (and its contents) must become immutable.
// `chattr -R` flags the directory before recursing into its children, so
// waiting on the directory alone races with the files inside it.
await waitFor(() => Directory.isImmutable(vhdDir))
await waitFor(() => Directory.isImmutable(blocks))
await waitFor(() => File.isImmutable(bat))
await waitFor(() => File.isImmutable(header))
await waitFor(() => File.isImmutable(footer))
assert.strictEqual(await Directory.isImmutable(vhdDir), true, 'vhd dir should be immutable')
assert.strictEqual(await File.isImmutable(bat), true, 'bat should be immutable')

View File

@@ -2,6 +2,7 @@
## **next**
- [New network] Choose between no NBD, secure NBD and insecure NBD (not encrypted) when creating a network (PR [#10540](https://github.com/vatesfr/xen-orchestra/pull/10540))
- [VM/System] Fix video RAM displayed in bytes instead of MiB (PR [#10486](https://github.com/vatesfr/xen-orchestra/pull/10486))
- [Treeview] Add a search bar and virtualize the tree (PR [#10414](https://github.com/vatesfr/xen-orchestra/pull/10414))
- [New/VM] Hide guest tools ISO SR in new VM ISO selector (PR [#10430](https://github.com/vatesfr/xen-orchestra/pull/10430))
@@ -12,6 +13,8 @@
- [VM/New] Fix UEFI VMs booting in BIOS mode when created with a network install or without disk (PR [#10521](https://github.com/vatesfr/xen-orchestra/pull/10521))
- [Treeview] Press Ctrl+K (Cmd+K on macOS) to focus the treeview search (PR [#10492](https://github.com/vatesfr/xen-orchestra/pull/10492))
- [Pool] Fix connection, stats and consoles when overriding the pool master with `?master=`: use HTTPS by default instead of the protocol and port of the page (PR [#9955](https://github.com/vatesfr/xen-orchestra/pull/9955))
- [Pool/Host/VM] Add copy button for multiple information on Host/VM Dashboard and Pool/Host/VM System tabs (PR [#9976](https://github.com/vatesfr/xen-orchestra/pull/9976))
- [New/VM] Fix `MAP_DUPLICATE_KEY` error that could randomly prevent the VM creation (PR [#10552](https://github.com/vatesfr/xen-orchestra/pull/10552))
## **0.26.0** (2026-10-01)

View File

@@ -7,7 +7,7 @@
{{ powerState.text }}
</template>
</VtsKeyValueRow>
<VtsKeyValueRow :label="t('ip-address')" :value="host.address" />
<VtsKeyValueRow :label="t('ip-address')" :value="host.address" copy />
<VtsKeyValueRow :label="t('started')" :value="isRunning ? relativeStartTime : undefined" />
<VtsKeyValueRow :label="t('master')">
<template #value>
@@ -27,7 +27,7 @@
</VtsKeyValueRow>
</VtsKeyValueList>
<VtsKeyValueList>
<VtsKeyValueRow :label="t('uuid')" :value="host.uuid" />
<VtsKeyValueRow :label="t('uuid')" :value="host.uuid" copy />
<VtsKeyValueRow :label="t('description')" :value="host.name_description" />
<VtsKeyValueRow :label="t('version')" :value="host.software_version.product_version" />
<VtsKeyValueRow

View File

@@ -4,8 +4,8 @@
{{ t('general-information') }}
</UiTitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('name')" :value="host.name_label" />
<VtsTabularKeyValueRow :label="t('uuid')" :value="host.uuid" />
<VtsTabularKeyValueRow :label="t('name')" :value="host.name_label" copy />
<VtsTabularKeyValueRow :label="t('uuid')" :value="host.uuid" copy />
<VtsTabularKeyValueRow :label="t('description')" :value="host.name_description" />
<VtsTabularKeyValueRow :label="t('tags')">
<template v-if="host.tags.length > 0" #value>

View File

@@ -4,9 +4,9 @@
{{ t('networking') }}
</UiTitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('ip-address')" :value="host.address" />
<VtsTabularKeyValueRow :label="t('ip-address')" :value="host.address" copy />
<VtsTabularKeyValueRow :label="t('remote-syslog')" :value="host.logging.syslog_destination" />
<VtsTabularKeyValueRow :label="t('iscsi-iqn')" :value="host.iscsi_iqn" />
<VtsTabularKeyValueRow :label="t('iscsi-iqn')" :value="host.iscsi_iqn" copy />
<VtsTabularKeyValueRow :label="t('multi-pathing')">
<template #value>
<VtsStatus :status="host.multipathing" />

View File

@@ -4,8 +4,8 @@
{{ t('general-information') }}
</UiTitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('name')" :value="pool.name_label" />
<VtsTabularKeyValueRow :label="t('uuid')" :value="pool.uuid" />
<VtsTabularKeyValueRow :label="t('name')" :value="pool.name_label" copy />
<VtsTabularKeyValueRow :label="t('uuid')" :value="pool.uuid" copy />
<VtsTabularKeyValueRow :label="t('description')" :value="pool.name_description" />
<VtsTabularKeyValueRow :label="t('tags')">
<template v-if="pool.tags.length > 0" #value>

View File

@@ -9,12 +9,12 @@
</span>
</template>
</VtsKeyValueRow>
<VtsKeyValueRow :label="t('ip-address')" :value="mainIpAddress" />
<VtsKeyValueRow :label="t('ip-address')" :value="mainIpAddress" copy />
<VtsKeyValueRow :label="t('created-on')" :value="installDateFormatted" />
<VtsKeyValueRow :label="t('started')" :value="relativeStartTime" />
</VtsKeyValueList>
<VtsKeyValueList>
<VtsKeyValueRow :label="t('uuid')" :value="vm.uuid" />
<VtsKeyValueRow :label="t('uuid')" :value="vm.uuid" copy />
<VtsKeyValueRow :label="t('host')">
<template #value>
<UiLink

View File

@@ -4,8 +4,8 @@
{{ t('general-information') }}
</UiTitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('name')" :value="vm.name_label" />
<VtsTabularKeyValueRow :label="t('id')" :value="vm.uuid" />
<VtsTabularKeyValueRow :label="t('name')" :value="vm.name_label" copy />
<VtsTabularKeyValueRow :label="t('id')" :value="vm.uuid" copy />
<VtsTabularKeyValueRow :label="t('description')" :value="vm.name_description" />
<VtsTabularKeyValueRow :label="t('tags')">
<template v-if="vm.tags.length > 0" #value>

View File

@@ -12,6 +12,8 @@ export function createNetworkOperations(xenApi: XenApi) {
nameDescription?: string
mtu?: number
nbd?: boolean
/** NBD in clear, only on a network dedicated to backups. Mutually exclusive with `nbd` */
insecureNbd?: boolean
}
type NetworkCreateParams = BaseNetworkCreateParams & {
@@ -34,18 +36,25 @@ export function createNetworkOperations(xenApi: XenApi) {
},
])
// nbd and insecure_nbd are incompatible purposes, at most one of them is added
const addNbdPurpose = async (networkRef: XenApiNetwork['$ref'], { nbd, insecureNbd }: BaseNetworkCreateParams) => {
if (nbd) {
await xenApi.call('network.add_purpose', [networkRef, 'nbd'])
} else if (insecureNbd) {
await xenApi.call('network.add_purpose', [networkRef, 'insecure_nbd'])
}
}
return {
create: async (params: NetworkCreateParams): Promise<XenApiNetwork['$ref']> => {
const { nameLabel, nameDescription = '', mtu = 1500, vlan = 0, pifRef, nbd } = params
const { nameLabel, nameDescription = '', mtu = 1500, vlan = 0, pifRef } = params
const networkRef = await createEmptyNetwork(nameLabel, nameDescription, mtu)
try {
await xenApi.call('pool.create_VLAN_from_PIF', [pifRef, networkRef, vlan])
if (nbd) {
await xenApi.call('network.add_purpose', [networkRef, 'nbd'])
}
await addNbdPurpose(networkRef, params)
} catch (error) {
await xenApi.call('network.destroy', [networkRef])
throw error
@@ -55,7 +64,7 @@ export function createNetworkOperations(xenApi: XenApi) {
},
createBonded: async (params: BondedNetworkCreateParams): Promise<XenApiNetwork['$ref']> => {
const { nameLabel, nameDescription = '', mtu = 1500, pifRefs, bondMode, nbd } = params
const { nameLabel, nameDescription = '', mtu = 1500, pifRefs, bondMode } = params
const networkRef = await createEmptyNetwork(nameLabel, nameDescription, mtu)
@@ -87,9 +96,7 @@ export function createNetworkOperations(xenApi: XenApi) {
)
)
if (nbd) {
await xenApi.call('network.add_purpose', [networkRef, 'nbd'])
}
await addNbdPurpose(networkRef, params)
} catch (error) {
await xenApi.call('network.destroy', [networkRef])
throw error
@@ -99,17 +106,15 @@ export function createNetworkOperations(xenApi: XenApi) {
},
createInternal: async (params: BaseNetworkCreateParams): Promise<XenApiNetwork['$ref']> => {
const { nameLabel, nameDescription = '', mtu = 1500, nbd } = params
const { nameLabel, nameDescription = '', mtu = 1500 } = params
const networkRef = await createEmptyNetwork(nameLabel, nameDescription, mtu)
if (nbd) {
try {
await xenApi.call('network.add_purpose', [networkRef, 'nbd'])
} catch (error) {
await xenApi.call('network.destroy', [networkRef])
throw error
}
try {
await addNbdPurpose(networkRef, params)
} catch (error) {
await xenApi.call('network.destroy', [networkRef])
throw error
}
return networkRef

View File

@@ -104,12 +104,19 @@ export function createVmOperations(xenApi: XenApi) {
setCopyBiosString: (vmRefs: VmRefs, hostRef: XenApiHost['$ref']) =>
Promise.all(toArray(vmRefs).map(vmRef => xenApi.call('VM.set_copy_bios_string', [vmRef, hostRef]))),
// XAPI may re-add `cores-per-socket` between `remove_from_platform` and `add_to_platform` (e.g. when setting the
// VCPUs), which fails with `MAP_DUPLICATE_KEY`, so the whole `platform` map is replaced instead, like xen-api does:
// https://github.com/vatesfr/xen-orchestra/blob/493aa7f15d51f60e34d0f76db2b033ccfc56737b/packages/xen-api/index.mjs#L542-L549
setCoresPerSocket: async (vmRef: XenApiVm['$ref'], coresPerSocket: number | null) => {
await xenApi.call('VM.remove_from_platform', [vmRef, 'cores-per-socket'])
const platform = await xenApi.getField<XenApiVm['platform']>('VM', vmRef, 'platform')
if (coresPerSocket !== null) {
await xenApi.call('VM.add_to_platform', [vmRef, 'cores-per-socket', String(coresPerSocket)])
if (coresPerSocket === null) {
delete platform['cores-per-socket']
} else {
platform['cores-per-socket'] = String(coresPerSocket)
}
await xenApi.call('VM.set_platform', [vmRef, platform])
},
setCpuMask: (vmRefs: VmRefs, mask: string[] | null) =>

View File

@@ -12,7 +12,7 @@
<NewNetworkDescriptionTextarea v-bind="descriptionInputBindings" />
</div>
<NetworkFormSelect v-bind="bondModeSelectBindings" class="bond-mode" />
<NewNetworkNbdCheckbox class="nbd" v-bind="nbdCheckboxBindings" />
<NewNetworkNbdRadio class="nbd" v-bind="nbdRadioBindings" />
<NewNetworkButtonsSection :cancel-to :submit-label="t('action:create-bonded-network')" />
</VtsForm>
</template>
@@ -22,7 +22,7 @@ import NetworkFormNumberInput from '@/modules/network/components/form/new/inputs
import NetworkFormSelect from '@/modules/network/components/form/new/inputs/NetworkFormSelect.vue'
import NetworkFormTextInput from '@/modules/network/components/form/new/inputs/NetworkFormTextInput.vue'
import NewNetworkDescriptionTextarea from '@/modules/network/components/form/new/inputs/NewNetworkDescriptionTextarea.vue'
import NewNetworkNbdCheckbox from '@/modules/network/components/form/new/inputs/NewNetworkNbdCheckbox.vue'
import NewNetworkNbdRadio from '@/modules/network/components/form/new/inputs/NewNetworkNbdRadio.vue'
import NewNetworkButtonsSection from '@/modules/network/components/form/new/NewNetworkButtonsSection.vue'
import { useNewBondedNetworkForm } from '@/modules/network/form/new-bonded/use-new-bonded-network-form.ts'
import type { NewBondedNetworkPayload } from '@/modules/network/jobs/bonded-network-create.job.ts'
@@ -46,7 +46,7 @@ const {
nameInputBindings,
mtuInputBindings,
descriptionInputBindings,
nbdCheckboxBindings,
nbdRadioBindings,
bondModeSelectBindings,
validateAndBuildPayload,
} = useNewBondedNetworkForm()

View File

@@ -9,7 +9,7 @@
<NewNetworkDescriptionTextarea v-bind="descriptionInputBindings" />
</div>
<div class="nbd">
<NewNetworkNbdCheckbox v-bind="nbdCheckboxBindings" />
<NewNetworkNbdRadio v-bind="nbdRadioBindings" />
</div>
<NewNetworkButtonsSection :cancel-to :submit-label="t('action:create-internal-network')" />
</form>
@@ -19,7 +19,7 @@
import NetworkFormNumberInput from '@/modules/network/components/form/new/inputs/NetworkFormNumberInput.vue'
import NetworkFormTextInput from '@/modules/network/components/form/new/inputs/NetworkFormTextInput.vue'
import NewNetworkDescriptionTextarea from '@/modules/network/components/form/new/inputs/NewNetworkDescriptionTextarea.vue'
import NewNetworkNbdCheckbox from '@/modules/network/components/form/new/inputs/NewNetworkNbdCheckbox.vue'
import NewNetworkNbdRadio from '@/modules/network/components/form/new/inputs/NewNetworkNbdRadio.vue'
import NewNetworkButtonsSection from '@/modules/network/components/form/new/NewNetworkButtonsSection.vue'
import { useNewInternalNetworkForm } from '@/modules/network/form/new-internal/use-new-internal-network-form.ts'
import type { NewInternalNetworkPayload } from '@/modules/network/jobs/internal-network-create.job.ts'
@@ -41,7 +41,7 @@ const {
nameInputBindings,
mtuInputBindings,
descriptionInputBindings,
nbdCheckboxBindings,
nbdRadioBindings,
validateAndBuildPayload,
} = useNewInternalNetworkForm()

View File

@@ -12,7 +12,7 @@
<NewNetworkDescriptionTextarea v-bind="descriptionInputBindings" />
</div>
<NetworkFormNumberInput v-bind="vlanInputBindings" class="vlan" />
<NewNetworkNbdCheckbox class="nbd" v-bind="nbdCheckboxBindings" />
<NewNetworkNbdRadio class="nbd" v-bind="nbdRadioBindings" />
<NewNetworkButtonsSection :cancel-to :submit-label="t('action:create-network')" />
</VtsForm>
</template>
@@ -22,7 +22,7 @@ import NetworkFormNumberInput from '@/modules/network/components/form/new/inputs
import NetworkFormSelect from '@/modules/network/components/form/new/inputs/NetworkFormSelect.vue'
import NetworkFormTextInput from '@/modules/network/components/form/new/inputs/NetworkFormTextInput.vue'
import NewNetworkDescriptionTextarea from '@/modules/network/components/form/new/inputs/NewNetworkDescriptionTextarea.vue'
import NewNetworkNbdCheckbox from '@/modules/network/components/form/new/inputs/NewNetworkNbdCheckbox.vue'
import NewNetworkNbdRadio from '@/modules/network/components/form/new/inputs/NewNetworkNbdRadio.vue'
import NewNetworkButtonsSection from '@/modules/network/components/form/new/NewNetworkButtonsSection.vue'
import { useNewNetworkForm } from '@/modules/network/form/new/use-new-network-form.ts'
import type { NewNetworkPayload } from '@/modules/network/jobs/network-create.job.ts'
@@ -47,7 +47,7 @@ const {
mtuInputBindings,
descriptionInputBindings,
vlanInputBindings,
nbdCheckboxBindings,
nbdRadioBindings,
validateAndBuildPayload,
} = useNewNetworkForm()

View File

@@ -1,14 +0,0 @@
<template>
<UiCheckbox v-model="model" accent="brand">
{{ t('network-block-device') }}
</UiCheckbox>
</template>
<script lang="ts" setup>
import UiCheckbox from '@core/components/ui/checkbox/UiCheckbox.vue'
import { useI18n } from 'vue-i18n'
const model = defineModel<boolean>({ required: true })
const { t } = useI18n()
</script>

View File

@@ -0,0 +1,35 @@
<template>
<UiRadioButtonGroup
:label="t('network-block-device')"
:accent="model === 'insecure-nbd' ? 'warning' : 'brand'"
:gap="uiStore.isSmall ? 'narrow' : 'wide'"
>
<UiRadioButton v-for="option of options" :key="option.value" v-model="model" accent="brand" :value="option.value">
{{ option.label }}
</UiRadioButton>
<template v-if="model === 'insecure-nbd'" #info>
{{ t('nbd:insecure-warning') }}
</template>
</UiRadioButtonGroup>
</template>
<script lang="ts" setup>
import type { NetworkNbdMode } from '@/modules/network/form/use-network-form-base.ts'
import UiRadioButton from '@core/components/ui/radio-button/UiRadioButton.vue'
import UiRadioButtonGroup from '@core/components/ui/radio-button-group/UiRadioButtonGroup.vue'
import { useUiStore } from '@core/stores/ui.store.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const model = defineModel<NetworkNbdMode>({ required: true })
const { t } = useI18n()
const uiStore = useUiStore()
const options = computed<{ label: string; value: NetworkNbdMode }[]>(() => [
{ label: t('nbd:disabled'), value: 'none' },
{ label: t('nbd:secure'), value: 'nbd' },
{ label: t('nbd:insecure'), value: 'insecure-nbd' },
])
</script>

View File

@@ -20,7 +20,7 @@ export function useNewBondedNetworkForm() {
name: '',
description: '',
mtu: undefined,
nbd: false,
nbd: 'none',
pifRefs: [],
bondMode: undefined,
})
@@ -44,7 +44,7 @@ export function useNewBondedNetworkForm() {
nameInputBindings,
descriptionInputBindings,
mtuInputBindings,
nbdCheckboxBindings,
nbdRadioBindings,
} = useNetworkFormBase(formData, extraConfig)
const { interfacesSelectId } = useNetworkPifSelect(toRef(formData, 'pifRefs'), {
@@ -78,7 +78,7 @@ export function useNewBondedNetworkForm() {
nameInputBindings,
descriptionInputBindings,
mtuInputBindings,
nbdCheckboxBindings,
nbdRadioBindings,
interfaceSelectBindings: useSelect(interfacesSelectId, 'pifRefs', () => ({ label: t('interfaces') })),
bondModeSelectBindings: useSelect(bondModeSelectId, 'bondMode', () => ({ label: t('bond-mode') })),
validateAndBuildPayload,

View File

@@ -7,7 +7,7 @@ export function useNewInternalNetworkForm() {
name: '',
description: '',
mtu: undefined,
nbd: false,
nbd: 'none',
})
const {
@@ -17,7 +17,7 @@ export function useNewInternalNetworkForm() {
nameInputBindings,
descriptionInputBindings,
mtuInputBindings,
nbdCheckboxBindings,
nbdRadioBindings,
} = useNetworkFormBase(formData)
async function validateAndBuildPayload(): Promise<NewInternalNetworkPayload | undefined> {
@@ -35,7 +35,7 @@ export function useNewInternalNetworkForm() {
nameInputBindings,
descriptionInputBindings,
mtuInputBindings,
nbdCheckboxBindings,
nbdRadioBindings,
validateAndBuildPayload,
}
}

View File

@@ -16,7 +16,7 @@ export function useNewNetworkForm() {
name: '',
description: '',
mtu: undefined,
nbd: false,
nbd: 'none',
pifRef: undefined,
vlan: undefined,
})
@@ -52,7 +52,7 @@ export function useNewNetworkForm() {
nameInputBindings,
descriptionInputBindings,
mtuInputBindings,
nbdCheckboxBindings,
nbdRadioBindings,
} = useNetworkFormBase(formData, extraConfig)
const { interfacesSelectId } = useNetworkPifSelect(toRef(formData, 'pifRef'), { value: '$ref' })
@@ -81,7 +81,7 @@ export function useNewNetworkForm() {
nameInputBindings,
descriptionInputBindings,
mtuInputBindings,
nbdCheckboxBindings,
nbdRadioBindings,
interfaceSelectBindings: useSelect(interfacesSelectId, 'pifRef', () => ({ label: t('interface') })),
vlanInputBindings: useField('vlan', () => ({ label: t('vlan') })),
validateAndBuildPayload,

View File

@@ -12,11 +12,14 @@ import { useValidatedForm } from '@core/packages/validated-form'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
// 'nbd': NBD over TLS, 'insecure-nbd': NBD in clear, only on a network dedicated to backups
export type NetworkNbdMode = 'none' | 'nbd' | 'insecure-nbd'
export type BaseNetworkFormData = {
name: string
description: string
mtu: number | undefined
nbd: boolean
nbd: NetworkNbdMode
}
export function useNetworkFormBase<T extends BaseNetworkFormData>(formData: T, extraConfig?: FormValidationConfig<T>) {
@@ -65,8 +68,10 @@ export function useNetworkFormBase<T extends BaseNetworkFormData>(formData: T, e
payload.mtu = formData.mtu
}
if (formData.nbd) {
payload.nbd = formData.nbd
if (formData.nbd === 'nbd') {
payload.nbd = true
} else if (formData.nbd === 'insecure-nbd') {
payload.insecureNbd = true
}
return payload
@@ -81,6 +86,6 @@ export function useNetworkFormBase<T extends BaseNetworkFormData>(formData: T, e
nameInputBindings: useField('name', () => ({ label: t('name'), required: true })),
descriptionInputBindings: useField('description'),
mtuInputBindings: useField('mtu', () => ({ label: t('mtu'), info: t('mtu-default-value-message') })),
nbdCheckboxBindings: useField('nbd'),
nbdRadioBindings: useField('nbd'),
}
}

View File

@@ -24,6 +24,7 @@ export const useBondedNetworkCreateJob = defineJob('bonded-network.create', [pay
pifRefs: payload.pifRefs,
bondMode: payload.bondMode,
nbd: payload.nbd,
insecureNbd: payload.insecureNbd,
})
return xapi.getField<XenApiNetwork['uuid']>('network', networkRef, 'uuid')

View File

@@ -18,6 +18,7 @@ export const useInternalNetworkCreateJob = defineJob('internal-network.create',
nameDescription: payload.description,
mtu: payload.mtu,
nbd: payload.nbd,
insecureNbd: payload.insecureNbd,
})
return xapi.getField<XenApiNetwork['uuid']>('network', networkRef, 'uuid')

View File

@@ -9,6 +9,7 @@ export type BaseNewNetworkPayload = {
description?: string
mtu?: number
nbd?: boolean
insecureNbd?: boolean
}
export type NewNetworkPayload = BaseNewNetworkPayload & {
@@ -29,6 +30,7 @@ export const useNetworkCreateJob = defineJob('network.create', [payloadArg], ()
vlan: payload.vlan,
pifRef: payload.pifRef,
nbd: payload.nbd,
insecureNbd: payload.insecureNbd,
})
return xapi.getField<XenApiNetwork['uuid']>('network', networkRef, 'uuid')

View File

@@ -605,11 +605,13 @@ const _createVm = defer(async ($defer: Defer) => {
xapi.vm.setAffinityHost(vmRefs, vmCreationParams.value.affinityHost),
xapi.vm.setMemory(vmRefs, vmCreationParams.value.memory),
xapi.vm.setAutoPowerOn(vmRefs[0], vmCreationParams.value.autoPoweron),
xapi.vm.setCoresPerSocket(vmRefs[0], vmCreationParams.value.coresPerSocket),
xapi.vm.setHvmBootFirmware(vmRefs[0], vmCreationParams.value.hvmBootFirmware),
xapi.vm.setVCPUsAtStartup(vmRefs, vmCreationParams.value.cpus),
])
// Replaces the whole `platform` map, so it must not run concurrently with other `platform` changes
await xapi.vm.setCoresPerSocket(vmRefs[0], vmCreationParams.value.coresPerSocket)
// VTPM
if (vmState.boot_firmware === 'uefi' && vmState.create_vtpm) {
const vtpmRef = await xapi.vtpm.create(vmRefs[0])

View File

@@ -779,6 +779,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/link-list/ui-link-list': RouteRecordInfo<
'/story/web-core/ui/link-list/ui-link-list',
'/story/web-core/ui/link-list/ui-link-list',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/log-entry-viewer/ui-log-entry-viewer': RouteRecordInfo<
'/story/web-core/ui/log-entry-viewer/ui-log-entry-viewer',
'/story/web-core/ui/log-entry-viewer/ui-log-entry-viewer',
@@ -1746,6 +1753,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/link-list/ui-link-list.story.vue': {
routes:
| '/story/web-core/ui/link-list/ui-link-list'
views:
| never
}
'src/stories/web-core/ui/log-entry-viewer/ui-log-entry-viewer.story.vue': {
routes:
| '/story/web-core/ui/log-entry-viewer/ui-log-entry-viewer'

View File

@@ -4,6 +4,11 @@
:params="[
prop('label').str().preset('CPU').widget(),
prop('value').str().preset('4 vCPUs').widget(),
prop('copy').bool().help('Displays a copy button that copies the value prop').widget(),
prop('copy-value')
.str()
.help('Displays a copy button that copies this string instead of the value prop')
.widget(),
slot('label').help('Overrides the label prop'),
slot('value').help('Overrides the value prop, meant to receive text or inline elements'),
]"

View File

@@ -4,6 +4,11 @@
:params="[
prop('label').str().preset('IP Address').widget(),
prop('value').str().preset('192.168.1.10').widget(),
prop('copy').bool().help('Displays a copy button that copies the value prop').widget(),
prop('copy-value')
.str()
.help('Displays a copy button that copies this string instead of the value prop')
.widget(),
slot('label').help('Overrides the label prop'),
slot('value').help('Overrides the value prop, meant to receive text or inline elements'),
]"

View File

@@ -4,6 +4,11 @@
:params="[
prop('label').str().preset('IP Address').widget(),
prop('value').str().preset('192.168.1.10').widget(),
prop('copy').bool().help('Displays a copy button that copies the value prop').widget(),
prop('copy-value')
.str()
.help('Displays a copy button that copies this string instead of the value prop')
.widget(),
slot('label').help('Overrides the label prop'),
slot('value').help('Overrides the value prop, meant to receive text or inline elements'),
]"

View File

@@ -0,0 +1,41 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('variant').required().enum('horizontal', 'vertical').preset('vertical').widget(),
prop('visible-items')
.num()
.widget()
.help('Number of links to display when collapsed. Vertical only, and requires `total-items`'),
prop('total-items')
.num()
.preset(groups.length)
.widget()
.help('Total number of links. Used to label the button that expands the list'),
slot().help('Meant to receive UiLink components'),
]"
>
<UiLinkList v-bind="properties">
<UiLink v-for="group in groups" :key="group.id" icon="table:group" size="small" to="#">
{{ group.name }}
</UiLink>
</UiLinkList>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, slot } from '@/libs/story/story-param.ts'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiLinkList from '@core/components/ui/link-list/UiLinkList.vue'
const groups = [
{ id: '1', name: 'Administrators' },
{ id: '2', name: 'Developers' },
{ id: '3', name: 'Support' },
{ id: '4', name: 'Auditors' },
{ id: '5', name: 'Operators' },
{ id: '6', name: 'Guests' },
{ id: '7', name: 'Contractors' },
]
</script>

View File

@@ -32,6 +32,7 @@
"scripts": {
"qa": "node --env-file-if-exists=.env --test --test-concurrency=1 tests/*.test.js",
"qa:infrastructure": "node --env-file-if-exists=.env --test tests/infrastructure.test.js",
"qa:acl": "node --env-file-if-exists=.env --test tests/acl.test.js",
"qa:vm": "node --env-file-if-exists=.env --test tests/vm.test.js",
"qa:backup:base": "node --env-file-if-exists=.env --test tests/backup.test.js",
"qa:backup:nbd": "node --env-file-if-exists=.env --test tests/backup.nbd.test.js",

View File

@@ -0,0 +1,604 @@
import '../logSetup.js'
import assert from 'node:assert/strict'
import { after, before, describe, it } from 'node:test'
import { createLogger } from '@xen-orchestra/log'
import { getRequiredEnv } from '../utils/index.js'
import { xoConnection } from '../client/xoLibClient.js'
import {
connectAs,
createTestGroup,
createTestUser,
deleteTestGroup,
deleteTestUser,
EVENT_WINDOW,
fetchAllObjects,
grant,
findVmStorage,
pickObjectsByType,
purgeLeftoverFixtures,
recordPushedObjects,
revoke,
summarize,
wait,
waitUntil,
withTag,
} from '../utils/aclUtils.js'
const log = createLogger('xo:qa-test:acl')
// Time left for the server to apply an ACL change before it is observed.
const SETTLE = 2_000
describe('ACL — server-side object filtering', () => {
/** admin connection: arranges the fixtures */
let admin
/** low-privilege connection: observes what the server sends it */
let user
let testUser
let recorder
let referenceVmId
let referencePoolId
before(async () => {
admin = await xoConnection({
xoUrl: getRequiredEnv('HOSTNAME'),
username: getRequiredEnv('USERNAME'),
password: getRequiredEnv('PASSWORD'),
})
// an `after` hook does not run when its `before` threw, so a suite that
// failed half way leaves fixtures — and their ACLs — on the appliance
await purgeLeftoverFixtures(admin)
referenceVmId = getRequiredEnv('REFERENCE_VM_ID')
// fail early and clearly rather than through a confusing assertion later
const allObjects = await fetchAllObjects(admin)
const referenceVm = allObjects[referenceVmId]
assert.notEqual(referenceVm, undefined, `REFERENCE_VM_ID ${referenceVmId} is not a known XO object`)
assert.equal(referenceVm.type, 'VM', `REFERENCE_VM_ID ${referenceVmId} is a ${referenceVm.type}, not a VM`)
referencePoolId = referenceVm.$pool
assert.notEqual(referencePoolId, undefined, 'the reference VM has no $pool')
log.debug('admin sees the whole infrastructure', {
summary: summarize(allObjects, 20),
referencePoolId,
})
testUser = await createTestUser(admin)
user = await connectAs(testUser)
recorder = recordPushedObjects(user)
})
after(async () => {
recorder?.stop()
await user?.close()
if (testUser !== undefined) {
await deleteTestUser(admin, testUser.id)
}
await admin?.close()
})
describe('a user without any ACL', () => {
it('is granted no permission at all', async () => {
const permissions = await user.call('acl.getCurrentPermissions')
const granted = Object.keys(permissions)
assert.equal(granted.length, 0, `expected no ACL, got: ${granted.join(', ')}`)
})
// Path 1 of 2: the bulk fetch xo-web performs on sign-in.
it('receives no object from xo.getAllObjects', async () => {
const objects = await fetchAllObjects(user)
const received = Object.keys(objects).length
assert.equal(received, 0, `expected no object, received ${received}: ${summarize(objects)}`)
})
// Tags carry organisational meaning — `customer-acme`, `prod-finance` —
// so the configured list is scoped to the objects the caller may see
// rather than locked to admins, which would cost everyone tag colours.
it('receives no configured tag', async () => {
const tags = await user.call('tag.getAllConfigured')
assert.equal(tags.length, 0, `expected no tag, received: ${tags.map(({ id }) => id).join(', ')}`)
})
// Path 2 of 2: the push stream. A fix could land one path and miss the
// other, so they are asserted separately.
it('receives no object on the event stream while the infrastructure changes', async () => {
recorder.reset()
await withTag(admin, referenceVmId, `qa-acl-${Date.now()}`, () => wait(EVENT_WINDOW))
// `exited` is not asserted: removals carry ids only and are forwarded to
// every connection by design
const pushed = Object.fromEntries(recorder.entered)
const nPushed = recorder.entered.size
assert.equal(nPushed, 0, `expected nothing to be pushed, received ${nPushed}: ${summarize(pushed)}`)
})
})
describe('a user with `view` on a single VM', () => {
before(async () => {
await grant(admin, testUser.id, referenceVmId)
await wait(SETTLE)
})
after(async () => {
await revoke(admin, testUser.id, referenceVmId)
})
it('receives that VM', async () => {
const objects = await fetchAllObjects(user)
assert.ok(referenceVmId in objects, `the granted VM was not returned; received ${summarize(objects)}`)
})
it('receives no other VM, and no host, pool, SR or network', async () => {
const objects = await fetchAllObjects(user)
const otherVmIds = Object.keys(objects).filter(id => objects[id].type === 'VM' && id !== referenceVmId)
assert.equal(
otherVmIds.length,
0,
`expected only the granted VM, also received ${otherVmIds.length} others, e.g. ${otherVmIds.slice(0, 3).join(', ')}`
)
// the VM's own disks, interfaces and snapshots are expected: access is
// inherited downwards. Its container is not.
const infrastructure = Object.fromEntries(
Object.entries(objects).filter(([, object]) => ['host', 'pool', 'SR', 'network'].includes(object.type))
)
const nLeaked = Object.keys(infrastructure).length
assert.equal(nLeaked, 0, `expected no infrastructure object, received ${nLeaked}: ${summarize(infrastructure)}`)
log.debug('objects visible with a single VM grant', { summary: summarize(objects, 20) })
})
})
// Permissions are inherited downwards: granting a pool grants everything it
// contains. This is the resolver's `checkMember('$container')` / `$pool`
// rules, and it is what makes a single ACL usable in practice.
describe('a user with `view` on a pool', () => {
let visible
before(async () => {
await grant(admin, testUser.id, referencePoolId)
await wait(SETTLE)
visible = await fetchAllObjects(user)
})
after(async () => {
await revoke(admin, testUser.id, referencePoolId)
})
it('receives the pool itself', () => {
assert.ok(referencePoolId in visible, `the granted pool was not returned; received ${summarize(visible)}`)
})
it('receives every host of that pool', async () => {
const everything = await fetchAllObjects(admin)
const expected = Object.keys(everything)
.filter(id => everything[id].type === 'host' && everything[id].$pool === referencePoolId)
.sort()
const received = Object.keys(visible)
.filter(id => visible[id].type === 'host')
.sort()
// under-sharing is as much a bug as over-sharing
assert.deepEqual(received, expected, 'the hosts of the granted pool were not all returned')
})
it('receives the VMs, SRs and networks of that pool', () => {
for (const type of ['VM', 'SR', 'network']) {
const n = Object.values(visible).filter(object => object.type === type).length
assert.ok(n > 0, `expected at least one ${type}, received ${summarize(visible)}`)
}
})
// Every XO object carries the pool it belongs to, which makes the
// cross-pool check exact. On a single-pool lab this passes trivially.
it('receives nothing belonging to another pool', () => {
const foreign = Object.fromEntries(
Object.entries(visible).filter(([, object]) => object.$pool !== referencePoolId)
)
const nForeign = Object.keys(foreign).length
assert.equal(
nForeign,
0,
`expected nothing outside the granted pool, received ${nForeign}: ${summarize(foreign)}`
)
})
})
// A grant made to a group must reach its members, and must stop reaching
// them as soon as they leave it — which is also the only coverage of the
// group-membership cache invalidation.
describe('a user granted access through a group', () => {
let group
before(async () => {
group = await createTestGroup(admin)
await admin.call('group.addUser', { id: group.id, userId: testUser.id })
await grant(admin, group.id, referenceVmId)
await wait(SETTLE)
})
after(async () => {
await revoke(admin, group.id, referenceVmId)
await deleteTestGroup(admin, group.id)
})
it('receives the VM granted to the group', async () => {
const objects = await fetchAllObjects(user)
assert.ok(
referenceVmId in objects,
`the VM granted to the group was not returned; received ${summarize(objects)}`
)
})
it('stops receiving it once removed from the group', async () => {
await admin.call('group.removeUser', { id: group.id, userId: testUser.id })
await wait(SETTLE)
const objects = await fetchAllObjects(user)
const received = Object.keys(objects).length
assert.equal(
received,
0,
`expected no object after leaving the group, received ${received}: ${summarize(objects)}`
)
})
})
// Access flows from a container to what it holds, never back up. Reaching a
// VM's storage must not reach the VM: on a shared SR that would expose every
// other tenant's disks and names.
describe('a user with `view` on an SR', () => {
let srId
let vdiId
let visible
before(async () => {
const everything = await fetchAllObjects(admin)
const storage = findVmStorage(everything, referenceVmId)
assert.notEqual(storage, undefined, `the reference VM ${referenceVmId} has no disk to derive an SR from`)
;({ srId, vdiId } = storage)
await grant(admin, testUser.id, srId)
await wait(SETTLE)
visible = await fetchAllObjects(user)
})
after(async () => {
await revoke(admin, testUser.id, srId)
})
it('receives the SR itself', () => {
assert.ok(srId in visible, `the granted SR was not returned; received ${summarize(visible)}`)
})
// Managed and unmanaged disks alike: an unmanaged VDI is the same XAPI
// object, and the ISO/disk pickers walk the SR's whole VDI list.
it('receives every disk held by that SR, managed or not', async () => {
assert.ok(vdiId in visible, `the disk ${vdiId} on the granted SR was not returned`)
const everything = await fetchAllObjects(admin)
const onSr = Object.keys(everything).filter(
id => ['VDI', 'VDI-unmanaged'].includes(everything[id].type) && everything[id].$SR === srId
)
const missing = onSr.filter(id => !(id in visible))
assert.equal(
missing.length,
0,
`${missing.length} of the ${onSr.length} disks on the SR were not returned, e.g. ${missing.slice(0, 3).join(', ')}`
)
})
it('receives no disk belonging to another SR', () => {
const foreign = Object.values(visible).filter(
object => ['VDI', 'VDI-unmanaged'].includes(object.type) && object.$SR !== srId
)
assert.equal(foreign.length, 0, `received ${foreign.length} disks belonging to another SR`)
})
// The reference VM is on this SR by construction, so there is something
// real to leak here.
it('receives no VM, even the ones whose disks are on that SR', () => {
const vms = Object.fromEntries(Object.entries(visible).filter(([, object]) => object.type === 'VM'))
const nVms = Object.keys(vms).length
assert.equal(
nVms,
0,
`expected no VM through an SR grant, received ${nVms} (including the reference VM: ${referenceVmId in vms})`
)
})
it('receives no host and no pool', () => {
const containers = Object.fromEntries(
Object.entries(visible).filter(([, object]) => object.type === 'host' || object.type === 'pool')
)
const nContainers = Object.keys(containers).length
assert.equal(nContainers, 0, `expected no container, received ${nContainers}: ${summarize(containers)}`)
})
})
// Filtering is computed per user. A regression that reused one user's filter
// for every connection would still pass every test above, since they all
// observe a single account.
describe('two users connected at once', () => {
let otherUser
let otherConnection
let otherRecorder
before(async () => {
otherUser = await createTestUser(admin)
otherConnection = await connectAs(otherUser)
otherRecorder = recordPushedObjects(otherConnection)
await grant(admin, testUser.id, referenceVmId)
await wait(SETTLE)
})
after(async () => {
otherRecorder?.stop()
await otherConnection?.close()
await revoke(admin, testUser.id, referenceVmId)
if (otherUser !== undefined) {
await deleteTestUser(admin, otherUser.id)
}
})
it('the granted user receives the VM', async () => {
const objects = await fetchAllObjects(user)
assert.ok(referenceVmId in objects, 'the granted user did not receive the VM')
})
it('the other user receives nothing', async () => {
const objects = await fetchAllObjects(otherConnection)
const received = Object.keys(objects).length
assert.equal(received, 0, `the ungranted user received ${received} objects: ${summarize(objects)}`)
})
it('an update to the VM is pushed only to the granted user', async () => {
recorder.reset()
otherRecorder.reset()
await withTag(admin, referenceVmId, `qa-acl-${Date.now()}`, () => wait(EVENT_WINDOW))
assert.ok(recorder.entered.has(referenceVmId), 'the granted user was not told about the change')
const leaked = Object.fromEntries(otherRecorder.entered)
const nLeaked = otherRecorder.entered.size
assert.equal(nLeaked, 0, `the ungranted user was pushed ${nLeaked} objects: ${summarize(leaked)}`)
})
// An ACL change invalidates every cached permission set, but concerns only
// its own subject. Without the comparison that follows the invalidation,
// one grant re-sends the whole visible set of every connected client.
it('does not re-push to a user whose own permissions did not change', async () => {
// let the previous test's tag cleanup reach us before we start counting
await wait(SETTLE)
recorder.reset()
await grant(admin, otherUser.id, referenceVmId)
try {
await wait(SETTLE)
const pushed = Object.fromEntries(recorder.entered)
const nPushed = recorder.entered.size
assert.equal(
nPushed,
0,
`an unrelated grant re-sent ${nPushed} objects to a user whose permissions were untouched: ${summarize(pushed)}`
)
} finally {
await revoke(admin, otherUser.id, referenceVmId)
}
})
})
// The event stream only carries *changes*, so a user granted access to an
// object that already exists would never hear about it. The server pushes
// their visible set on a permission change to close that gap — nothing else
// in the suite, nor in the unit tests, covers it.
describe('a permission granted while connected', () => {
before(async () => {
// The grant below must be a *change*, in two senses. An ACL that already
// exists is silently ignored and emits no event at all. And a grant made
// inside the debounce window of a preceding revocation is merged with
// it: the comparison is then made against the state from before that
// revocation, the permissions come out identical, and no push is due —
// correctly, since the client never lost the objects.
//
// So: revoke, then let the window close.
await revoke(admin, testUser.id, referenceVmId)
await wait(SETTLE)
})
after(async () => {
await revoke(admin, testUser.id, referenceVmId)
})
it('reaches the client without reconnecting', async () => {
const before = await user.call('acl.getCurrentPermissions')
assert.equal(
Object.keys(before).length,
0,
`the user already holds permissions, so the grant would change nothing: ${Object.keys(before).join(', ')}`
)
recorder.reset()
await grant(admin, testUser.id, referenceVmId)
const arrived = await waitUntil(() => recorder.entered.has(referenceVmId))
assert.ok(arrived, `the VM was never pushed after the grant (received ${recorder.entered.size} objects)`)
})
it('stops reaching the client once revoked', async () => {
await revoke(admin, testUser.id, referenceVmId)
await wait(SETTLE)
// a fresh fetch must no longer return it
const objects = await fetchAllObjects(user)
const received = Object.keys(objects).length
assert.equal(received, 0, `expected no object after the revocation, received ${received}: ${summarize(objects)}`)
// and no further update about it must be pushed
recorder.reset()
await withTag(admin, referenceVmId, `qa-acl-${Date.now()}`, () => wait(EVENT_WINDOW))
assert.ok(
!recorder.entered.has(referenceVmId),
'updates about the VM were still pushed after the permission was revoked'
)
})
})
// Self-service users hold no ACL on the resources they build from: the
// server grants them an implicit `view` on their resource sets, which is
// what keeps the VM creation form usable once filtering is on.
describe('a user who is the subject of a resource set', () => {
let resourceSetId
let setObjects
let outsider
let outsiderConnection
let visible
before(async () => {
const everything = await fetchAllObjects(admin)
setObjects = pickObjectsByType(everything, referencePoolId, ['VM-template', 'SR', 'network'])
for (const type of ['VM-template', 'SR', 'network']) {
assert.notEqual(setObjects[type], undefined, `no ${type} found in pool ${referencePoolId}`)
}
const set = await admin.call('resourceSet.create', {
name: `qa-acl-${Date.now()}`,
subjects: [testUser.id],
objects: Object.values(setObjects),
})
resourceSetId = set.id
outsider = await createTestUser(admin)
outsiderConnection = await connectAs(outsider)
await wait(SETTLE)
visible = await fetchAllObjects(user)
})
after(async () => {
await outsiderConnection?.close()
if (outsider !== undefined) {
await deleteTestUser(admin, outsider.id)
}
if (resourceSetId !== undefined) {
await admin
.call('resourceSet.delete', { id: resourceSetId })
.catch(error => log.warn('failed to delete the test resource set', { error }))
}
})
it('receives the resources of the set', () => {
for (const [type, id] of Object.entries(setObjects)) {
assert.ok(id in visible, `the ${type} of the resource set was not returned; received ${summarize(visible)}`)
}
})
// what the ISO and disk pickers of the VM creation form rely on
it('receives the disks of the set SR', () => {
const vdis = Object.values(visible).filter(object => object.type === 'VDI' && object.$SR === setObjects.SR)
assert.ok(vdis.length > 0, `expected disks on the resource set SR; received ${summarize(visible)}`)
})
it('receives no VM belonging to anyone else', () => {
// guard against passing for the wrong reason: a user who sees nothing at
// all trivially sees no VM
assert.ok(Object.keys(visible).length > 0, 'the user sees nothing, so this proves nothing')
const vms = Object.values(visible).filter(object => object.type === 'VM')
assert.equal(vms.length, 0, `a resource set must not expose VMs, received ${vms.length}`)
})
it('can read the set it is a subject of', async () => {
const set = await user.call('resourceSet.get', { id: resourceSetId })
assert.equal(set.id, resourceSetId)
})
it('is refused to a user who is not a subject', async () => {
await assert.rejects(
() => outsiderConnection.call('resourceSet.get', { id: resourceSetId }),
error => error.code === 2,
'a non-subject was able to read the resource set'
)
})
})
// Filtering must not reach admins: over-filtering would break XO for the
// people who run it, and no other test would notice.
describe('an admin', () => {
it('still receives the whole infrastructure', async () => {
const objects = await fetchAllObjects(admin)
assert.ok(referenceVmId in objects, 'the admin lost sight of the reference VM')
for (const type of ['pool', 'host', 'SR', 'network', 'VM']) {
const n = Object.values(objects).filter(object => object.type === type).length
assert.ok(n > 0, `the admin received no ${type}; got ${summarize(objects)}`)
}
const pools = new Set(Object.values(objects).map(object => object.$pool))
assert.ok(pools.size > 0, 'the admin received objects from no pool at all')
log.debug('admin view unchanged', { objects: Object.keys(objects).length, pools: pools.size })
})
})
// Methods that returned infrastructure-wide data to any authenticated user.
describe('methods restricted to admins', () => {
const RESTRICTED = ['pool.listPoolsMatchingCriteria', 'backupNg.getSuggestedExcludedTags']
// kept open on purpose, see the comment in src/api/cloud-config.mjs
const OPEN = ['cloudConfig.getAll', 'cloudConfig.getAllNetworkConfigs']
for (const method of RESTRICTED) {
it(`${method} is refused to a non-admin`, async () => {
await assert.rejects(
() => user.call(method, {}),
error => error.code === 2,
`${method} did not refuse a non-admin`
)
})
}
for (const method of OPEN) {
it(`${method} still answers a non-admin`, async () => {
await assert.doesNotReject(() => user.call(method, {}))
})
}
// the lock must not cost admins the feature
for (const method of RESTRICTED) {
it(`${method} still answers an admin`, async () => {
await assert.doesNotReject(() => admin.call(method, {}))
})
}
})
})

View File

@@ -0,0 +1,393 @@
import { createLogger } from '@xen-orchestra/log'
import { getRequiredEnv } from './index.js'
import { xoConnection } from '../client/xoLibClient.js'
const log = createLogger('xo:qa-test:acl')
/**
* The subset of the xo-lib client this suite uses.
*
* @typedef {{
* user: { id: string, email: string, permission: string },
* call: (method: string, params?: object) => Promise<any>,
* on: (event: string, listener: (...args: any[]) => void) => void,
* removeListener: (event: string, listener: (...args: any[]) => void) => void,
* close: () => Promise<void>,
* }} XoClient
*/
/**
* How long to watch the event stream before concluding that nothing arrived.
*
* The event assertions are the only source of flakiness in the ACL suite:
* they prove a *negative* ("nothing was pushed"), so the window has to be long
* enough for a change made by the admin to have travelled back.
*/
const configured = Number(process.env.ACL_EVENT_WINDOW)
export const EVENT_WINDOW = Number.isFinite(configured) && configured > 0 ? configured : 10_000
/** Prefix of every account created by this suite, so leftovers are recognizable. */
export const TEST_USER_PREFIX = 'qa-acl-'
export const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
/**
* Opens a second, independent XO connection signed in as another account.
*
* The whole suite rests on this: an admin connection arranges the fixtures
* while a low-privilege connection observes what the server actually sends it.
* The bug is only visible on the wire — xo-web filters client-side, so the UI
* looks identical whether or not the server does its job.
*
* @param {object} credentials
* @param {string} credentials.email
* @param {string} credentials.password
* @returns {Promise<XoClient>} a signed-in xo-lib client
*/
export function connectAs({ email, password }) {
return xoConnection({
xoUrl: getRequiredEnv('HOSTNAME'),
// XO looks accounts up by name, which is the email for local accounts
username: email,
password,
})
}
/**
* Creates a throw-away account.
*
* @param {XoClient} xo - an admin connection
* @param {object} [opts]
* @param {string} [opts.permission] - defaults to `none`, i.e. the "User" role
* @returns {Promise<{ id: string, email: string, password: string }>}
*/
export async function createTestUser(xo, { permission = 'none' } = {}) {
const email = `${TEST_USER_PREFIX}${Date.now()}-${Math.random().toString(36).slice(2, 8)}@qa.test`
const password = Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2)
const id = await xo.call('user.create', { email, password, permission })
log.debug('created test user', { id, email, permission })
return { id, email, password }
}
/**
* Deletes an account, ignoring the error if it is already gone, so that
* teardown never masks the failure that led to it.
*
* @param {XoClient} xo - an admin connection
* @param {string} id
*/
export async function deleteTestUser(xo, id) {
try {
await xo.call('user.delete', { id })
log.debug('deleted test user', { id })
} catch (error) {
log.warn('failed to delete test user', { error, id })
}
}
/**
* Creates a throw-away group.
*
* @param {XoClient} xo - an admin connection
* @returns {Promise<{ id: string, name: string }>}
*/
export async function createTestGroup(xo) {
const name = `${TEST_USER_PREFIX}${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
const id = await xo.call('group.create', { name })
log.debug('created test group', { id, name })
return { id, name }
}
/**
* Deletes a group, ignoring the error if it is already gone, so that teardown
* never masks the failure that led to it.
*
* @param {XoClient} xo - an admin connection
* @param {string} id
*/
export async function deleteTestGroup(xo, id) {
try {
await xo.call('group.delete', { id })
log.debug('deleted test group', { id })
} catch (error) {
log.warn('failed to delete test group', { error, id })
}
}
/**
* Accumulates everything the server pushes on a connection.
*
* Note that `exited` may legitimately contain ids the connection never
* received: removals carry ids only and the object is already gone from the
* collection when the event is emitted, so the server cannot evaluate who was
* allowed to see it and forwards them to everyone. Assertions about leaked
* data must therefore be made on `entered`.
*
* @param {XoClient} xo
* @returns {{ entered: Map<string, object>, exited: Set<string>, reset(): void, stop(): void }}
*/
export function recordPushedObjects(xo) {
const entered = new Map()
const exited = new Set()
const onNotification = notification => {
if (notification.method !== 'all') {
return
}
const { type, items } = notification.params
for (const id of Object.keys(items)) {
if (type === 'enter') {
entered.set(id, items[id])
} else {
exited.add(id)
}
}
}
xo.on('notification', onNotification)
return {
entered,
exited,
reset() {
entered.clear()
exited.clear()
},
stop() {
xo.removeListener('notification', onNotification)
},
}
}
/**
* Everything the server is willing to hand over to this connection.
*
* @param {XoClient} xo
* @returns {Promise<{ [id: string]: object }>}
*/
export function fetchAllObjects(xo) {
return xo.call('xo.getAllObjects', {})
}
/**
* Counts the returned objects by type, to make failures readable.
*
* @param {{ [id: string]: object }} objects
* @returns {{ [type: string]: number }}
*/
export function countByType(objects) {
const counts = {}
for (const id of Object.keys(objects)) {
const { type } = objects[id]
counts[type] = (counts[type] ?? 0) + 1
}
return counts
}
/**
* Polls until a condition holds, or gives up.
*
* Preferable to a flat sleep for assertions that wait for something to
* *happen*: the test finishes as soon as it does, and only pays the full
* timeout when it genuinely failed.
*
* @param {() => boolean} predicate
* @param {object} [opts]
* @param {number} [opts.timeout]
* @param {number} [opts.interval]
* @returns {Promise<boolean>} whether the condition held before the timeout
*/
export async function waitUntil(predicate, { timeout = EVENT_WINDOW, interval = 250 } = {}) {
const deadline = Date.now() + timeout
do {
if (predicate()) {
return true
}
await wait(interval)
} while (Date.now() < deadline)
return predicate()
}
/**
* Picks one object of each given type belonging to a pool.
*
* @param {{ [id: string]: object }} objects - the admin's view
* @param {string} poolId
* @param {string[]} types
* @returns {{ [type: string]: string | undefined }} one id per type
*/
export function pickObjectsByType(objects, poolId, types) {
const picked = {}
for (const id of Object.keys(objects)) {
const object = objects[id]
if (object.$pool === poolId && types.includes(object.type) && picked[object.type] === undefined) {
picked[object.type] = id
}
}
return picked
}
/**
* Finds the SR holding one of a VM's disks, along with that disk.
*
* Granting an SR is only a meaningful non-leak test if a VM actually lives on
* it: the point is to prove that reaching a VM's storage does not reach the VM.
*
* @param {{ [id: string]: object }} objects - the admin's view
* @param {string} vmId
* @returns {{ srId: string, vdiId: string } | undefined}
*/
export function findVmStorage(objects, vmId) {
const vm = objects[vmId]
for (const vbdId of vm?.$VBDs ?? []) {
const vbd = objects[vbdId]
if (vbd === undefined || vbd.is_cd_drive || vbd.VDI == null) {
continue
}
const vdi = objects[vbd.VDI]
if (vdi?.$SR != null) {
return { srId: vdi.$SR, vdiId: vdi.id }
}
}
}
/**
* Renders a type breakdown on a single line, most numerous first.
*
* Assertions in this suite compare *counts*, never the object collections
* themselves: a failing `deepEqual` on 28k ids buries the result under a diff
* nobody can read. The numbers go in the assertion, the detail goes here.
*
* @param {{ [id: string]: object }} objects
* @param {number} [max] - number of types to show before summarising the rest
* @returns {string}
*/
export function summarize(objects, max = 6) {
const entries = Object.entries(countByType(objects)).sort((a, b) => b[1] - a[1])
if (entries.length === 0) {
return 'nothing'
}
const shown = entries.slice(0, max).map(([type, count]) => `${count} ${type}`)
const remaining = entries.length - max
if (remaining > 0) {
shown.push(`and ${remaining} other type${remaining > 1 ? 's' : ''}`)
}
return shown.join(', ')
}
/**
* Makes an object change so that the server has something to push.
*
* Tagging goes all the way to XAPI, so it produces a genuine object update
* rather than something synthesised by xo-server.
*
* @param {XoClient} xo - an admin connection
* @param {string} objectId
* @param {string} tag
*/
export async function withTag(xo, objectId, tag, fn) {
await xo.call('tag.add', { id: objectId, tag })
try {
return await fn()
} finally {
await xo.call('tag.remove', { id: objectId, tag }).catch(error => {
log.warn('failed to remove the test tag', { error, objectId, tag })
})
}
}
/**
* Grants a permission, making sure it is a *change*.
*
* `addAcl` silently ignores an ACL that already exists, which emits no event
* and therefore triggers no invalidation — correct behaviour, but it turns a
* test that expects a push into a silent no-op. Revoking first guarantees the
* grant produces something to observe.
*
* @param {XoClient} xo - an admin connection
* @param {string} subject - a user or group id
* @param {string} object
* @param {string} [action]
*/
export async function grant(xo, subject, object, action = 'viewer') {
await revoke(xo, subject, object, action)
await xo.call('acl.add', { subject, object, action })
}
/**
* Revokes a permission, tolerating its absence.
*
* @param {XoClient} xo - an admin connection
* @param {string} subject
* @param {string} object
* @param {string} [action]
*/
export async function revoke(xo, subject, object, action = 'viewer') {
try {
await xo.call('acl.remove', { subject, object, action })
} catch (error) {
log.warn('failed to revoke an ACL', { error, subject, object, action })
}
}
/**
* Deletes whatever a previous run left behind.
*
* An `after` hook does not run when its `before` threw, so a suite that fails
* half way leaves users, groups and resource sets on the appliance — and their
* ACLs with them. The next run then starts from a state it did not choose,
* which is how a grant becomes a no-op and a test fails for reasons that have
* nothing to do with the code under test.
*
* Deleting a user or a group removes its ACLs, so they need no separate pass.
*
* @param {XoClient} xo - an admin connection
*/
export async function purgeLeftoverFixtures(xo) {
const mine = name => name !== undefined && name.startsWith(TEST_USER_PREFIX)
const [users, groups, resourceSets] = await Promise.all([
xo.call('user.getAll'),
xo.call('group.getAll'),
xo.call('resourceSet.getAll'),
])
const stale = {
users: users.filter(({ email }) => mine(email)),
groups: groups.filter(({ name }) => mine(name)),
resourceSets: resourceSets.filter(({ name }) => mine(name)),
}
const nStale = stale.users.length + stale.groups.length + stale.resourceSets.length
if (nStale === 0) {
return
}
log.warn('deleting fixtures left by a previous run', {
users: stale.users.length,
groups: stale.groups.length,
resourceSets: stale.resourceSets.length,
})
for (const [method, records] of [
['user.delete', stale.users],
['group.delete', stale.groups],
['resourceSet.delete', stale.resourceSets],
]) {
for (const { id } of records) {
try {
await xo.call(method, { id })
} catch (error) {
log.warn('failed to delete a leftover fixture', { error, method, id })
}
}
}
}

View File

@@ -347,7 +347,10 @@ export class QcowStreamGenerator {
if (data.length < disk.getBlockSize()) {
truncatedBlock = { data, index }
}
yield* self.#trackAndYield(Buffer.concat([data], disk.getBlockSize()))
// only the truncated last block is padded: a full block is yielded without copying it
yield* self.#trackAndYield(
data.length < disk.getBlockSize() ? Buffer.concat([data], disk.getBlockSize()) : data
)
nbGeneratedBlock++
}

View File

@@ -18,6 +18,8 @@ Naming is hard, building a coherent API is hard: ask/propose naming **before** s
Use the `@Deprecated()` decorator if needed, and never remove a route without changing the API version.
URLs must be written in `snake_case`.
### Resource consistency
For a given resource (VMs, VIFs, users, etc.), property names must be consistent across all endpoints. The types and names of properties must also be coherent with the types in `@vates/types/xo.mts`.
@@ -39,6 +41,21 @@ PATCH /vms/:id
}
```
## Naming
Always use the full name of a concept, never a shortened one, even if the context seems to make it obvious. This applies everywhere, not only to endpoints: route paths, RBAC resources, identifiers (variables, functions, types, files), JSDoc, OpenAPI descriptions, role descriptions, etc.
```
GET /backup-repositories/:id // OK ✅
GET /repositories/:id // Not OK ❌
const backupRepository = ... // OK ✅
const repository = ... // Not OK ❌
description: 'Full control over backup repositories' // OK ✅
description: 'Full control over repositories' // Not OK ❌
```
## Code organisation
- the service must handle the domain/functional logic of one or multiple REST API routes
@@ -102,7 +119,14 @@ In order not to pollute important decorators, all example structures should be i
## Actions
REST API actions are reserved to user actions that won't fit the REST API. The REST API actions must use the `this.createAction` method to handle correctly synchronous and asynchronous mode.
When to use an action?
- anything that cannot be presented in REST format (e.g, SR.scan)
- operations that can take a long time (e.g, mount live disk)
An action endpoint must contain the `actions` segment in the URL (e.g. `/srs/:sr-id/actions/scan`, `/backup-archives/:ba-id/live_disks/:live-disk-id/actions/unmount`)
REST API actions are reserved to user actions that won't fit the REST API. The REST API actions must use the `this.createAction` method (and must only be used for action endpoints) to handle correctly synchronous and asynchronous mode.
If your action endpoint includes a request body, don't forget to add `params` to the `taskProperties` property (obfuscate sensitive params such as passwords)

View File

@@ -42,8 +42,10 @@
"@xen-orchestra/backups": "^0.76.1",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/qcow2": "^1.4.0",
"@xen-orchestra/vmdk": "^0.1.0",
"@xen-orchestra/xapi": "^9.0.1",
"complex-matcher": "^1.1.1",
"fast-xml-parser": "^5.10.1",
"golike-defer": "^0.5.1",
"inversify": "^6.2.2",
"inversify-binding-decorators": "^4.0.0",

View File

@@ -57,6 +57,12 @@ export abstract class BaseController<T extends XoRecord, IsSync extends boolean>
: []
) as AnyPrivilege[]
const privilegeResolver = await this.restApi.buildPrivilegeResolver(
objects,
userPrivileges,
opts?.privilege?.resource
)
let limit = opts?.limit ?? Infinity
for (const object of objects) {
if (limit === 0) {
@@ -65,7 +71,7 @@ export abstract class BaseController<T extends XoRecord, IsSync extends boolean>
if (
opts?.privilege !== undefined &&
!hasPrivilegeOn({ user, userPrivileges, objects: object, ...opts.privilege })
!hasPrivilegeOn({ user, userPrivileges, objects: object, ...opts.privilege }, privilegeResolver)
) {
continue
}
@@ -105,15 +111,20 @@ export abstract class BaseController<T extends XoRecord, IsSync extends boolean>
const objectFilter = (task: XoTask) =>
task.properties.objectId === object.id || task.properties.params?.id === object.id
let userFilter: (task: XoTask) => boolean = () => true
if (filter !== undefined) {
userFilter = typeof filter === 'string' ? safeParseComplexMatcher(filter).createPredicate() : filter
const objectTasks: XoTask[] = []
for await (const task of this.restApi.tasks.list({ filter: objectFilter })) {
objectTasks.push(task)
}
for await (const task of this.restApi.tasks.list({ filter: objectFilter })) {
if (limit === 0) {
break
}
let userFilter: (task: XoTask) => boolean = () => true
if (filter !== undefined) {
const parsedFilter = safeParseComplexMatcher(filter)
userFilter = parsedFilter.createPredicate(await this.restApi.buildResolver(objectTasks, parsedFilter))
}
for (const task of objectTasks) {
if (limit === 0) break
if (userFilter(task)) {
tasks[task.id] = task
limit--

View File

@@ -1,7 +1,7 @@
import { createLogger } from '@xen-orchestra/log'
import type { EventEmitter } from 'node:events'
import { AnyPrivilege, hasPrivilegeOn, SupportedResource } from '@xen-orchestra/acl'
import { XAPI_TYPES, type XapiXoRecord, type XoUser } from '@vates/types'
import { XAPI_TYPES, XoRecord, type XapiXoRecord, type XoUser } from '@vates/types'
import type { CollectionEventType, EventType, NonXapiListenerType, XoListenerType } from '../events/event.type.mjs'
import { iocContainer } from '../ioc/ioc.mjs'
import { RestApi } from '../rest-api/rest-api.mjs'
@@ -124,8 +124,8 @@ export abstract class Listener<Type extends XoListenerType | undefined = undefin
userId,
}: {
event: CollectionEventType
object: object | undefined
previousObject: object | undefined
object: Partial<XoRecord> | undefined
previousObject: Partial<XoRecord> | undefined
userId: XoUser['id']
}): Promise<CollectionEventType | undefined> {
if (this.type === undefined || (object === undefined && previousObject === undefined)) {
@@ -142,7 +142,6 @@ export abstract class Listener<Type extends XoListenerType | undefined = undefin
return event
}
const userPrivileges = (await restApi.xoApp.getAclV2UserPrivileges(user.id)) as AnyPrivilege[]
let resource: SupportedResource | undefined
if (!XAPI_TYPES.includes(this.type)) {
@@ -156,36 +155,60 @@ export abstract class Listener<Type extends XoListenerType | undefined = undefin
;[resource] = resourceXapiType as [keyof typeof XAPI_TYPE_BY_ACL_RESOURCE, XapiXoRecord['type']]
}
const userPrivileges = (await restApi.xoApp.getAclV2UserPrivileges(user.id)) as AnyPrivilege[]
const privilegeResolver = await restApi.buildPrivilegeResolver(
[object, previousObject].filter(o => o !== undefined),
userPrivileges,
resource
)
switch (event) {
case 'add':
if (object === undefined) {
return
}
if (!hasPrivilegeOn({ user, userPrivileges, action: 'read', objects: object, resource })) {
if (
!hasPrivilegeOn(
{
user,
userPrivileges,
action: 'read',
objects: object,
resource,
},
privilegeResolver
)
) {
return
}
return 'add'
case 'update': {
const canSeeObject =
object !== undefined &&
hasPrivilegeOn({
user,
userPrivileges,
action: 'read',
objects: object,
resource,
})
hasPrivilegeOn(
{
user,
userPrivileges,
action: 'read',
objects: object,
resource,
},
privilegeResolver
)
const canSeePreviousObject =
previousObject !== undefined &&
hasPrivilegeOn({
user,
userPrivileges,
action: 'read',
objects: previousObject,
resource,
})
hasPrivilegeOn(
{
user,
userPrivileges,
action: 'read',
objects: previousObject,
resource,
},
privilegeResolver
)
if (canSeeObject && canSeePreviousObject) {
return 'update'
@@ -203,13 +226,16 @@ export abstract class Listener<Type extends XoListenerType | undefined = undefin
}
case 'remove':
if (
!hasPrivilegeOn({
user,
userPrivileges,
action: 'read',
objects: object ?? previousObject!,
resource,
})
!hasPrivilegeOn(
{
user,
userPrivileges,
action: 'read',
objects: object ?? previousObject!,
resource,
},
privilegeResolver
)
) {
return
}

View File

@@ -18,7 +18,7 @@ export abstract class XoController<T extends NonXapiXoRecord> extends BaseContro
): Promise<Record<T['id'], T>> {
let objects = await this.getAllCollectionObjects(opts)
objects = limitAndFilterArray(objects, opts)
objects = await limitAndFilterArray(objects, { filter: opts.filter, limit: opts.limit }, this.restApi)
const objectById = {} as Record<T['id'], T>

View File

@@ -316,7 +316,8 @@ export class AclRoleController extends XoController<XoAclRole> {
@Query() limit?: number
): SendObjects<Partial<Unbrand<AnyPrivilege>>> {
const privileges = (await this.restApi.xoApp.getAclV2RolePrivileges(id as XoAclRole['id'])) as AnyPrivilege[]
return this.sendObjects(limitAndFilterArray(privileges, { filter }), req, {
return this.sendObjects(await limitAndFilterArray(privileges, { filter }, this.restApi), req, {
path: 'acl-privileges',
limit,
privilege: { resource: 'acl-privilege', action: 'read' },
@@ -488,7 +489,7 @@ export class AclRoleController extends XoController<XoAclRole> {
)
)
return this.sendObjects(limitAndFilterArray(users, { filter }), req, {
return this.sendObjects(await limitAndFilterArray(users, { filter }, this.restApi), req, {
path: 'users',
limit,
privilege: { resource: 'user', action: 'read' },
@@ -534,7 +535,7 @@ export class AclRoleController extends XoController<XoAclRole> {
)
)
return this.sendObjects(limitAndFilterArray(groups, { filter }), req, {
return this.sendObjects(await limitAndFilterArray(groups, { filter }, this.restApi), req, {
path: 'groups',
limit,
privilege: { resource: 'group', action: 'read' },

View File

@@ -60,7 +60,8 @@ export class AlarmService {
let userFilter: (obj: XoAlarm) => boolean = () => true
if (filter !== undefined) {
userFilter = typeof filter === 'string' ? safeParseComplexMatcher(filter).createPredicate() : filter
userFilter =
typeof filter === 'string' ? safeParseComplexMatcher(filter).createPredicate(this.#restApi.resolver) : filter
}
const alarms: Record<XoAlarm['id'], XoAlarm> = {}
for (const id in rawAlarms) {

View File

@@ -42,9 +42,8 @@ import {
} from '../open-api/oa-examples/backup-archive.oa-example.mjs'
import { taskLocation } from '../open-api/oa-examples/task.oa-example.mjs'
import { SendObjects } from '../helpers/helper.type.mjs'
import { BackupArchiveService } from './backup-archive.service.mjs'
import type { MountLiveDiskBody } from './backup-archive.type.mjs'
import { acl, autoBindService } from '../middlewares/acl.middleware.mjs'
import { acl } from '../middlewares/acl.middleware.mjs'
@Route('backup-archives')
@Security('*')
@@ -53,14 +52,8 @@ import { acl, autoBindService } from '../middlewares/acl.middleware.mjs'
@Tags('backup-archives')
@provide(BackupArchiveController)
export class BackupArchiveController extends XoController<XoVmBackupArchive> {
#backupArchiveService: BackupArchiveService
constructor(
@inject(RestApi) restApi: RestApi,
@inject(BackupArchiveService) backupArchiveService: BackupArchiveService
) {
constructor(@inject(RestApi) restApi: RestApi) {
super('backup-archive', restApi)
this.#backupArchiveService = backupArchiveService
}
async getAllCollectionObjects({
@@ -88,7 +81,7 @@ export class BackupArchiveController extends XoController<XoVmBackupArchive> {
}
getCollectionObject(id: XoVmBackupArchive['id']): Promise<XoVmBackupArchive> {
return this.#backupArchiveService.getBackupArchive(id)
return this.restApi.xoApp.getVmBackupArchive(id)
}
/**
@@ -138,7 +131,7 @@ export class BackupArchiveController extends XoController<XoVmBackupArchive> {
resource: 'backup-archive',
action: 'read',
objectId: 'params.id',
getObject: autoBindService(BackupArchiveService, 'getBackupArchive'),
getObject: ({ restApi }) => restApi.xoApp.getVmBackupArchive,
})
)
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)

View File

@@ -1,31 +0,0 @@
import { noSuchObject } from 'xo-common/api-errors.js'
import type { XoBackupRepository, XoVm, XoVmBackupArchive } from '@vates/types'
import type { RestApi } from '../rest-api/rest-api.mjs'
// BR uuid/xo-vm-backups/VM uuid/(ISO 8601 compact).json
const BACKUP_ARCHIVE_ID_REGEX = /^([0-9a-fA-F-]{36})\/+xo-vm-backups\/+([0-9a-fA-F-]{36})\/+(\d{8}T\d{6}Z)\.json$/
export class BackupArchiveService {
#restApi: RestApi
constructor(restApi: RestApi) {
this.#restApi = restApi
}
async getBackupArchive(id: XoVmBackupArchive['id']): Promise<XoVmBackupArchive> {
const match = id.match(BACKUP_ARCHIVE_ID_REGEX)
if (match === null) {
throw noSuchObject(id, 'backup-archive')
}
const [, brId, vmId] = match as [XoVmBackupArchive['id'], XoBackupRepository['id'], XoVm['id'], string]
const backupArchive = (await this.#restApi.xoApp.listVmBackupsNg([brId]))[brId]?.[vmId]?.find(ba => ba.id === id)
if (backupArchive === undefined) {
throw noSuchObject(id, 'backup-archive')
}
return backupArchive
}
}

View File

@@ -38,7 +38,7 @@ import {
Unbrand,
} from '../open-api/common/response.common.mjs'
import { RestApi } from '../rest-api/rest-api.mjs'
import { BASE_URL, limitAndFilterArray, safeParseComplexMatcher } from '../helpers/utils.helper.mjs'
import { BASE_URL, limitAndFilterArray } from '../helpers/utils.helper.mjs'
import type {
UnbrandAnyXoBackupJob,
UnbrandXoMetadataBackupJob,
@@ -218,7 +218,8 @@ export class DeprecatedBackupController extends XoController<AnyXoBackupJob> {
@Query() limit?: number
): SendObjects<Partial<UnbrandXoVmBackupJob>> {
const vmBackupJobs = await this.restApi.xoApp.getAllJobs('backup')
return this.sendObjects(limitAndFilterArray(vmBackupJobs, { filter }), req, {
return this.sendObjects(await limitAndFilterArray(vmBackupJobs, { filter }, this.restApi), req, {
path: 'backup-jobs',
limit,
privilege: { action: 'read', resource: 'backup-job' },
@@ -272,7 +273,8 @@ export class DeprecatedBackupController extends XoController<AnyXoBackupJob> {
@Query() limit?: number
): SendObjects<Partial<UnbrandXoMetadataBackupJob>> {
const metadataBackupJobs = await this.restApi.xoApp.getAllJobs('metadataBackup')
return this.sendObjects(limitAndFilterArray(metadataBackupJobs, { filter }), req, {
return this.sendObjects(await limitAndFilterArray(metadataBackupJobs, { filter }, this.restApi), req, {
path: 'backup-jobs',
limit,
privilege: { action: 'read', resource: 'backup-job' },
@@ -316,7 +318,8 @@ export class DeprecatedBackupController extends XoController<AnyXoBackupJob> {
@Query() limit?: number
): SendObjects<Partial<UnbrandXoMirrorBackupJob>> {
const mirrorBackupJobs = await this.restApi.xoApp.getAllJobs('mirrorBackup')
return this.sendObjects(limitAndFilterArray(mirrorBackupJobs, { filter }), req, {
return this.sendObjects(await limitAndFilterArray(mirrorBackupJobs, { filter }, this.restApi), req, {
path: 'backup-jobs',
limit,
privilege: { action: 'read', resource: 'backup-job' },
@@ -359,17 +362,11 @@ export class DeprecatedBackupController extends XoController<AnyXoBackupJob> {
@Query() filter?: string,
@Query() limit?: number
): SendObjects<Partial<Unbrand<XoBackupLog>>> {
const userFilter = filter === undefined ? () => true : safeParseComplexMatcher(filter).createPredicate()
const logs = (await this.restApi.xoApp.getBackupNgLogsSorted({
filter: (log: AnyXoLog) => this.#backupLogService.isBackupLog(log),
})) as XoBackupLog[]
const predicate = (log: AnyXoLog) => {
if (!this.#backupLogService.isBackupLog(log)) {
return false
}
return userFilter(log)
}
const logs = (await this.restApi.xoApp.getBackupNgLogsSorted({ filter: predicate })) as XoBackupLog[]
return this.sendObjects(logs, req, {
return this.sendObjects(await limitAndFilterArray(logs, { filter }, this.restApi), req, {
path: 'backup-logs',
limit,
privilege: { action: 'read', resource: 'backup-log' },

View File

@@ -50,6 +50,8 @@ function bindRestApi(user: Partial<XoUser>, userPrivileges: AnyPrivilege[] = [])
getUser: async () => _user,
getAclV2UserPrivileges: async () => userPrivileges,
},
// none of the selectors uses [resolve], so the resolver is never called
buildPrivilegeResolver: async () => undefined,
} as unknown as RestApi)
return _user

View File

@@ -10,7 +10,6 @@ import { AlarmService } from '../alarms/alarm.service.mjs'
import type { RestApi } from '../rest-api/rest-api.mjs'
import { XAPI_TYPES, type XapiXoRecord } from '@vates/types'
import { BackupJobService } from '../backup-jobs/backup-job.service.mjs'
import { KubernetesEventService } from '../kubernetes/kubernetes.event.mjs'
const log = createLogger('xo:rest-api:event-service')
@@ -52,9 +51,8 @@ export class EventService {
} else if (type === 'backup-archive') {
// the backup archives are not a registered collection: the backups cache owns their emitter
eventEmitter = this.#restApi.xoApp.vmBackupArchives
} else if (type === 'kubernetes-cluster' || type === 'kubernetes-node') {
// TODO: Stand in for registerCollection in xo-server
eventEmitter = this.#restApi.ioc.get(KubernetesEventService).emitterFor(type)
} else if (type === 'backup-log') {
eventEmitter = this.#restApi.xoApp.backupLogsEe
} else if (XAPI_TYPES.includes(isMessage ? 'message' : type)) {
// alarm is purely XO-related; it doesn't exist at the XAPI level.
// alarm is a message with parsed values. So, in the case of an alarm listener, it listens for message collection.

View File

@@ -1,5 +1,4 @@
import type { Branded, XapiXoRecord } from '@vates/types'
import { KubernetesCollections } from '../kubernetes/kubernetes.event.mjs'
export type SubscriberId = Branded<'Subscriber'>
@@ -19,7 +18,7 @@ export type NonXapiListenerType =
| 'backup-archive'
| 'schedule'
| 'authentication_token'
| KubernetesCollections
| 'backup-log'
export type XoListenerType = XapiListenerType | NonXapiListenerType

View File

@@ -285,7 +285,8 @@ export class GroupController extends XoController<XoGroup> {
): SendObjects<Partial<Unbrand<XoUser>>> {
const group = await this.getObject(id as XoGroup['id'])
const users = await Promise.all(group.users.map(id => this.restApi.xoApp.getUser(id, { obfuscatePassword: true })))
return this.sendObjects(limitAndFilterArray(users, { filter }), req, {
return this.sendObjects(await limitAndFilterArray(users, { filter }, this.restApi), req, {
path: 'users',
limit,
privilege: { action: 'read', resource: 'user' },
@@ -354,7 +355,7 @@ export class GroupController extends XoController<XoGroup> {
const group = await this.getObject(id as XoGroup['id'])
const roles = await Promise.all(group.aclRoleIds.map(roleId => this.restApi.xoApp.getAclV2Role(roleId)))
return this.sendObjects(limitAndFilterArray(roles, { filter }), req, {
return this.sendObjects(await limitAndFilterArray(roles, { filter }, this.restApi), req, {
path: 'acl-roles',
limit,
privilege: { action: 'read', resource: 'acl-role' },

View File

@@ -6,7 +6,11 @@ import { isPromise } from 'node:util/types'
import { MaybePromise, PromiseWriteInStreamError } from './helper.type.mjs'
import { Writable } from 'node:stream'
import { ApiError } from './error.helper.mjs'
import { XMLParser } from 'fast-xml-parser'
import type { RestApi } from '../rest-api/rest-api.mjs'
export const BASE_URL = '/rest/v0'
export { default as forEach } from 'lodash/forEach.js'
export const NDJSON_CONTENT_TYPE = 'application/x-ndjson'
const log = createLogger('xo:rest-api:utils-helper')
@@ -139,13 +143,18 @@ export function safeParseComplexMatcher(string: string) {
}
}
export function limitAndFilterArray<T>(
export async function limitAndFilterArray<T>(
array: T[],
{ filter, limit = Infinity }: { filter?: string | ((obj: T) => boolean); limit?: number } = {}
): T[] {
if (filter !== undefined) {
const predicate = typeof filter === 'string' ? safeParseComplexMatcher(filter).createPredicate() : filter
array = array.filter(predicate)
{ filter, limit = Infinity }: { filter?: string | ((obj: T) => boolean); limit?: number },
restApi: RestApi
): Promise<T[]> {
if (typeof filter === 'string') {
const parsedFilter = safeParseComplexMatcher(filter)
const userFilter = parsedFilter.createPredicate(await restApi.buildResolver(array, parsedFilter))
array = array.filter(userFilter)
} else if (filter !== undefined) {
array = array.filter(filter)
}
if (limit < array.length) {
@@ -154,3 +163,26 @@ export function limitAndFilterArray<T>(
return array
}
export const parseXml = (function () {
const parser = new XMLParser({
attributeNamePrefix: '',
ignoreAttributes: false,
ignoreDeclaration: true,
parseTagValue: false,
parseAttributeValue: false,
})
return xml => {
try {
return parser.parse(Buffer.isBuffer(xml) ? xml.toString() : xml)
} catch (error) {
log.warn('parseXml', { error, xml })
return ''
}
}
})()
export function ensureArray<T>(value: T | T[] | undefined): T[] {
return value === undefined ? [] : Array.isArray(value) ? value : [value]
}

View File

@@ -50,6 +50,11 @@ import {
hostMissingPatches,
hostStats,
partialHosts,
nfsExport,
srUuids,
hbaExport,
iscsiIqnExport,
iscsiLunExport,
} from '../open-api/oa-examples/host.oa-example.mjs'
import { RestApi } from '../rest-api/rest-api.mjs'
import type { SendObjects } from '../helpers/helper.type.mjs'
@@ -72,6 +77,7 @@ import { HostService } from './host.service.mjs'
import { messageIds, partialMessages } from '../open-api/oa-examples/message.oa-example.mjs'
import { partialTasks, taskIds, taskLocation } from '../open-api/oa-examples/task.oa-example.mjs'
import type { SupportedActions } from '@xen-orchestra/acl'
import type { XoSrHbaExport, XoSrIscsiIqnsExport, XoSrIscsiLunsExport, XoSrNfsExport } from './host.type.mjs'
@Route('hosts')
@Security('*')
@@ -929,6 +935,10 @@ export class HostController extends XapiXoController<XoHost> {
})
}
#sanitizeProbeBody<T extends { chapPassword?: string }>(body: T): T {
return body.chapPassword !== undefined ? { ...body, chapPassword: '***obfuscated***' } : body
}
/**
* Required privilege:
* - resource: host, action: scan-pifs
@@ -975,4 +985,362 @@ export class HostController extends XapiXoController<XoHost> {
},
})
}
/**
* Detects all NFS shares (exports) on a NFS server and returns a table of exports with their paths and ACLs
*
* Required privilege:
* - resource: host, action: probe:nfs
*
* @example id "c4284e12-37c9-7967-b9e8-83ef229c3e03"
* @example body {"server": "192.168.1.1", "nfsVersion": "4"}
*/
@Example(taskLocation)
@Example(nfsExport)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/probe_nfs')
@Middlewares([json(), acl({ resource: 'host', action: 'probe:nfs', objectId: 'params.id' })])
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(200, 'OK')
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
probeNfs(
@Path() id: string,
@Body()
body: {
server: string
nfsVersion?: string
},
@Query() sync?: boolean
): CreateActionReturnType<XoSrNfsExport[]> {
const hostId = id as XoHost['id']
const action = () => {
return this.#hostService.probeNfs(hostId, body.server, body.nfsVersion)
}
return this.createAction<XoSrNfsExport[]>(action, {
sync,
statusCode: 200,
taskProperties: {
name: 'probe NFS exports',
objectId: hostId,
params: body,
},
})
}
/**
* Detects all ZFS pools and returns a dict of pools with their parameters { <poolname>: {<paramdict>}}
*
* Required privilege:
* - resource: host, action: probe:zfs
*
* @example id "c4284e12-37c9-7967-b9e8-83ef229c3e03"
*/
//TODO: add @Example when we have a host using a zfs SR
@Example(taskLocation)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/probe_zfs')
@Middlewares(acl({ resource: 'host', action: 'probe:zfs', objectId: 'params.id' }))
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(200, 'OK')
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
probeZfs(@Path() id: string, @Query() sync?: boolean): CreateActionReturnType<Record<string, unknown>> {
const hostId = id as XoHost['id']
const action = () => {
return this.#hostService.probeZfs(hostId)
}
//FIXME: fix the return type of the createAction
return this.createAction<Record<string, unknown>>(action, {
sync,
statusCode: 200,
taskProperties: {
name: 'probe ZFS pools',
objectId: hostId,
},
})
}
/**
* Detects all HBA devices on the host
*
* Required privilege:
* - resource: host, action: probe:hba
*
* @example id "c4284e12-37c9-7967-b9e8-83ef229c3e03"
*/
@Example(taskLocation)
@Example(hbaExport)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/probe_hba')
@Middlewares(acl({ resource: 'host', action: 'probe:hba', objectId: 'params.id' }))
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(200, 'OK')
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
probeHba(@Path() id: string, @Query() sync?: boolean): CreateActionReturnType<XoSrHbaExport[]> {
const hostId = id as XoHost['id']
const action = () => {
return this.#hostService.probeHba(hostId)
}
return this.createAction<XoSrHbaExport[]>(action, {
sync,
statusCode: 200,
taskProperties: {
name: 'probe HBA devices',
objectId: hostId,
},
})
}
/**
* Detects all iSCSI IQN on a Target (iSCSI "server")
* returns a table of IQN or empty table if no iSCSI connection to the target
*
* Required privilege:
* - resource: host, action: probe:iscsiiqn
*
* @example id "c4284e12-37c9-7967-b9e8-83ef229c3e03"
* @example body {"targetIp": "192.168.1.100", "port": 3260, "chapUser": "chapUser", "chapPassword": "chapPassword"}
*/
@Example(taskLocation)
@Example(iscsiIqnExport)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/probe_iscsi_iqns')
@Middlewares([json(), acl({ resource: 'host', action: 'probe:iscsiiqn', objectId: 'params.id' })])
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(200, 'OK')
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
probeIscsiIqns(
@Path() id: string,
@Body()
body: {
targetIp: string
port?: number
chapUser?: string
chapPassword?: string
},
@Query() sync?: boolean
): CreateActionReturnType<XoSrIscsiIqnsExport[]> {
const hostId = id as XoHost['id']
const action = () => {
return this.#hostService.probeIscsiIqns(hostId, body.targetIp, body.port, body.chapUser, body.chapPassword)
}
return this.createAction<XoSrIscsiIqnsExport[]>(action, {
sync,
statusCode: 200,
taskProperties: {
name: 'probe iSCSI IQNs',
objectId: hostId,
params: this.#sanitizeProbeBody(body),
},
})
}
/**
* Detects all iSCSI ID and LUNs on a Target and return a LUN table
*
* Required privilege:
* - resource: host, action: probe:iscsilun
*
* @example id "c4284e12-37c9-7967-b9e8-83ef229c3e03"
* @example body {"targetIp": "192.168.1.100", "targetIqn": "iqn.2018-01.com.example:storage.lun0", "port": 3260, "chapUser": "chapUser", "chapPassword": "chapPassword" }
*/
@Example(taskLocation)
@Example(iscsiLunExport)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/probe_iscsi_luns')
@Middlewares([json(), acl({ resource: 'host', action: 'probe:iscsilun', objectId: 'params.id' })])
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(200, 'OK')
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
probeIscsiLuns(
@Path() id: string,
@Body()
body: {
targetIp: string
targetIqn: string
port?: number
chapUser?: string
chapPassword?: string
},
@Query() sync?: boolean
): CreateActionReturnType<XoSrIscsiLunsExport[]> {
const hostId = id as XoHost['id']
const action = () => {
return this.#hostService.probeIscsiLuns(
hostId,
body.targetIp,
body.targetIqn,
body.port,
body.chapUser,
body.chapPassword
)
}
return this.createAction<XoSrIscsiLunsExport[]>(action, {
sync,
statusCode: 200,
taskProperties: {
name: 'probe iSCSI LUNs',
objectId: hostId,
params: this.#sanitizeProbeBody(body),
},
})
}
/**
* Detects if this target already exists in XAPI
* returns a table of SR UUID, empty if no existing connections
*
* Required privilege:
* - resource: host, action: probe:iscsi-exists
*
* @example id "c4284e12-37c9-7967-b9e8-83ef229c3e03"
* @example body {"targetIp": "192.168.1.100", "targetIqn": "iqn.2018-01.com.example:storage.lun0", "port": 3260, "chapUser": "chapUser", "chapPassword": "chapPassword" }
*/
@Example(taskLocation)
@Example(srUuids)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/probe_iscsi_exists')
@Middlewares([json(), acl({ resource: 'host', action: 'probe:iscsi-exists', objectId: 'params.id' })])
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(200, 'OK')
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
probeIscsiExists(
@Path() id: string,
@Body()
body: {
targetIp: string
targetIqn: string
scsiId: string
port?: number
chapUser?: string
chapPassword?: string
},
@Query() sync?: boolean
): CreateActionReturnType<string[]> {
const hostId = id as XoHost['id']
const action = () => {
return this.#hostService.probeIscsiExists(
hostId,
body.targetIp,
body.targetIqn,
body.scsiId,
body.port,
body.chapUser,
body.chapPassword
)
}
return this.createAction<string[]>(action, {
sync,
statusCode: 200,
taskProperties: {
name: 'probe iSCSI SR existence',
objectId: hostId,
params: this.#sanitizeProbeBody(body),
},
})
}
/**
* Detect if this HBA already exists in XAPI
* returns a table of SR UUID, empty if no existing connections
*
* Required privilege:
* - resource: host, action: probe:hba-exists
*
* @example id "c4284e12-37c9-7967-b9e8-83ef229c3e03"
* @example body {"scsiId": "360014050023c9f066c030d1185f8e7e2"}
*/
@Example(taskLocation)
@Example(srUuids)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/probe_hba_exists')
@Middlewares([json(), acl({ resource: 'host', action: 'probe:hba-exists', objectId: 'params.id' })])
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(200, 'OK')
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
probeHbaExists(
@Path() id: string,
@Body() body: { scsiId: string },
@Query() sync?: boolean
): CreateActionReturnType<string[]> {
const hostId = id as XoHost['id']
const action = () => {
return this.#hostService.probeHbaExists(hostId, body.scsiId)
}
return this.createAction<string[]>(action, {
sync,
statusCode: 200,
taskProperties: {
name: 'probe HBA SR existence',
objectId: hostId,
params: body,
},
})
}
/**
* Detects if this NFS SR already exists in XAPI
* returns a table of SR UUID, empty if no existing connections
*
* Required privilege:
* - resource: host, action: probe:nfs-exists
*
* @example id "c4284e12-37c9-7967-b9e8-83ef229c3e03"
* @example body {"server": "192.168.1.1", "serverPath": "/srv/nfs", "nfsVersion": "4"}
*/
@Example(taskLocation)
@Example(srUuids)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/probe_nfs_exists')
@Middlewares([json(), acl({ resource: 'host', action: 'probe:nfs-exists', objectId: 'params.id' })])
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(200, 'OK')
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
probeNfsExists(
@Path() id: string,
@Body()
body: {
server: string
serverPath: string
nfsVersion?: string
},
@Query() sync?: boolean
): CreateActionReturnType<string[]> {
const hostId = id as XoHost['id']
const action = () => {
return this.#hostService.probeNfsExists(hostId, body.server, body.serverPath, body.nfsVersion)
}
return this.createAction<string[]>(action, {
sync,
statusCode: 200,
taskProperties: {
name: 'probe NFS SR existence',
objectId: hostId,
params: body,
},
})
}
}

View File

@@ -2,9 +2,15 @@ import { asyncEach } from '@vates/async-each'
import { createLogger } from '@xen-orchestra/log'
import { HOST_POWER_STATE, Xapi, XcpPatches, XenApiHostWrapped, XoPool, XsPatches, type XoHost } from '@vates/types'
import { incorrectState } from 'xo-common/api-errors.js'
import { parseXml, ensureArray } from '../helpers/utils.helper.mjs'
import type {
MissingPatchesInfo,
XoSrNfsExport,
XoSrHbaExport,
XoSrIscsiIqnsExport,
XoSrIscsiLunsExport,
} from './host.type.mjs'
import type { RestApi } from '../rest-api/rest-api.mjs'
import type { MissingPatchesInfo } from './host.type.mjs'
import semver from 'semver'
const log = createLogger('xo:rest-api:host-service')
@@ -203,4 +209,274 @@ export class HostService {
return { xapi, xapiHost }
}
async probeNfs(id: XoHost['id'], server: string, nfsVersion?: string): Promise<XoSrNfsExport[]> {
const xapiHost = this.#restApi.getXapiObject<XoHost>(id, 'host')
const xapi = xapiHost.$xapi
let xml: ReturnType<typeof parseXml>
const deviceConfig = {
nfsversion: nfsVersion,
server,
}
try {
await xapi.callAsync('SR.probe', xapiHost.$ref, deviceConfig, 'nfs', {})
throw new Error('the call above should have thrown an error')
} catch (error: any) {
if (error.code !== 'SR_BACKEND_FAILURE_101') {
throw error
}
xml = parseXml(error.params[2])
}
// NFSv4 doesn't return the full path, and we need to add a slash at the beginning of it, or SR creation with this path will fail
const nfsExports: XoSrNfsExport[] = ensureArray(xml['nfs-exports'].Export).map(nfsExport => ({
path: nfsExport.Path.trim().replace(/^\/?/, '/'),
acl: nfsExport.Accesslist.trim(),
}))
return nfsExports
}
async probeZfs(id: XoHost['id']) {
const xapiHost = this.#restApi.getXapiObject<XoHost>(id, 'host')
const xapi = xapiHost.$xapi
try {
const result = (await xapi.callAsync('host.call_plugin', xapiHost.$ref, 'zfs.py', 'list_zfs_pools', {})) as string
return JSON.parse(result)
} catch (error: any) {
if (error.code === 'XENAPI_MISSING_PLUGIN' || error.code === 'UNKNOWN_XENAPI_PLUGIN_FUNCTION') {
return {}
} else {
throw error
}
}
}
async probeHba(id: XoHost['id']): Promise<XoSrHbaExport[]> {
const xapiHost = this.#restApi.getXapiObject<XoHost>(id, 'host')
const xapi = xapiHost.$xapi
let xml: ReturnType<typeof parseXml>
try {
await xapi.callAsync('SR.probe', xapiHost.$ref, {}, 'lvmohba', {})
throw new Error('the call above should have thrown an error')
} catch (error: any) {
if (error.code !== 'SR_BACKEND_FAILURE_107') {
throw error
}
xml = parseXml(error.params[2])
}
const hbaDevices: XoSrHbaExport[] = ensureArray(xml.Devlist.BlockDevice).map(hbaDevice => ({
hba: hbaDevice.hba.trim(),
id: hbaDevice.id.trim(),
lun: +hbaDevice.lun.trim(),
path: hbaDevice.path.trim(),
scsiId: hbaDevice.SCSIid.trim(),
serial: hbaDevice.serial.trim(),
size: +hbaDevice.size.trim(),
vendor: hbaDevice.vendor.trim(),
}))
return hbaDevices
}
async probeIscsiIqns(
id: XoHost['id'],
targetIp: string,
port?: number,
chapUser?: string,
chapPassword?: string
): Promise<XoSrIscsiIqnsExport[]> {
const xapiHost = this.#restApi.getXapiObject<XoHost>(id, 'host')
const xapi = xapiHost.$xapi
type DeviceConfig = {
target: string
chapuser?: string
chappassword?: string
port?: string
}
const deviceConfig: DeviceConfig = {
target: targetIp,
}
if (chapUser && chapPassword) {
deviceConfig.chapuser = chapUser
deviceConfig.chappassword = chapPassword
}
if (port) {
deviceConfig.port = String(port)
}
let xml: ReturnType<typeof parseXml>
try {
await xapi.callAsync('SR.probe', xapiHost.$ref, deviceConfig, 'lvmoiscsi', {})
throw new Error('the call above should have thrown an error')
} catch (error: any) {
if (error.code === 'SR_BACKEND_FAILURE_141') {
return []
}
if (error.code !== 'SR_BACKEND_FAILURE_96') {
throw error
}
xml = parseXml(error.params[2])
}
const targets: XoSrIscsiIqnsExport[] = ensureArray(xml['iscsi-target-iqns'].TGT)
.filter(target => target.IPAddress.trim() === targetIp) // if the target is on another IP address, do not display it
.map(target => ({
iqn: target.TargetIQN.trim(),
ip: target.IPAddress.trim(),
}))
return targets
}
async probeIscsiLuns(
id: XoHost['id'],
targetIp: string,
targetIqn: string,
port?: number,
chapUser?: string,
chapPassword?: string
): Promise<XoSrIscsiLunsExport[]> {
const xapiHost = this.#restApi.getXapiObject<XoHost>(id, 'host')
const xapi = xapiHost.$xapi
type DeviceConfig = {
target: string
targetIQN: string
chapuser?: string
chappassword?: string
port?: string
}
const deviceConfig: DeviceConfig = {
target: targetIp,
targetIQN: targetIqn,
}
if (chapUser && chapPassword) {
deviceConfig.chapuser = chapUser
deviceConfig.chappassword = chapPassword
}
if (port) {
deviceConfig.port = String(port)
}
let xml: ReturnType<typeof parseXml>
try {
await xapi.callAsync('SR.probe', xapiHost.$ref, deviceConfig, 'lvmoiscsi', {})
throw new Error('the call above should have thrown an error')
} catch (error: any) {
if (error.code !== 'SR_BACKEND_FAILURE_107') {
throw error
}
xml = parseXml(error.params[2])
}
const luns: XoSrIscsiLunsExport[] = ensureArray(xml['iscsi-target'].LUN).map(lun => ({
id: lun.LUNid.trim(),
vendor: lun.vendor.trim(),
serial: lun.serial?.trim() || '',
size: lun.size?.trim(),
scsiId: lun.SCSIid.trim(),
}))
return luns
}
async probeIscsiExists(
id: XoHost['id'],
targetIp: string,
targetIqn: string,
scsiId: string,
port?: number,
chapUser?: string,
chapPassword?: string
): Promise<string[]> {
const xapiHost = this.#restApi.getXapiObject<XoHost>(id, 'host')
const xapi = xapiHost.$xapi
type DeviceConfig = {
target: string
targetIQN: string
SCSIid: string
port?: string
chapuser?: string
chappassword?: string
}
const deviceConfig: DeviceConfig = {
target: targetIp,
targetIQN: targetIqn,
SCSIid: scsiId,
}
if (chapUser && chapPassword) {
deviceConfig.chapuser = chapUser
deviceConfig.chappassword = chapPassword
}
if (port) {
deviceConfig.port = String(port)
}
const xml = parseXml(await xapi.callAsync('SR.probe', xapiHost.$ref, deviceConfig, 'lvmoiscsi', {}))
// UUIDs of the SRs connected to this LUN
const srs: string[] = ensureArray(xml.SRlist.SR).map(sr => sr.UUID.trim())
return srs
}
async probeHbaExists(id: XoHost['id'], scsiId: string): Promise<string[]> {
const xapiHost = this.#restApi.getXapiObject<XoHost>(id, 'host')
const xapi = xapiHost.$xapi
const deviceConfig = {
SCSIid: scsiId,
}
const xml = parseXml(await xapi.callAsync('SR.probe', xapiHost.$ref, deviceConfig, 'lvmohba', {}))
// get the UUID of SR connected to this LUN
const srs: string[] = ensureArray(xml.SRlist.SR).map(sr => sr.UUID.trim())
return srs
}
async probeNfsExists(id: XoHost['id'], server: string, serverPath: string, nfsVersion?: string): Promise<string[]> {
const xapiHost = this.#restApi.getXapiObject<XoHost>(id, 'host')
const xapi = xapiHost.$xapi
const deviceConfig = {
nfsversion: nfsVersion,
server,
serverpath: serverPath,
}
const xml = parseXml(await xapi.callAsync('SR.probe', xapiHost.$ref, deviceConfig, 'nfs', {}))
const srs: string[] = ensureArray(xml.SRlist.SR).map(sr => sr.UUID.trim())
return srs
}
}

View File

@@ -7,3 +7,32 @@ export type MissingPatchesInfo = {
nHostsFailed: number
missingPatches: XcpPatches[] | XsPatches[]
}
export type XoSrNfsExport = {
path: string
acl: string
}
export type XoSrHbaExport = {
hba: string
id: string
lun: number
path: string
scsiId: string
serial: string
size: number
vendor: string
}
export type XoSrIscsiLunsExport = {
id: string
vendor: string
serial: string
size?: string
scsiId: string
}
export type XoSrIscsiIqnsExport = {
iqn: string
ip: string
}

View File

@@ -6,21 +6,16 @@ import type { XoApp } from '@vates/types/xo-app'
import genericErrorHandler from './middlewares/generic-error-handler.middleware.mjs'
import tsoaToXoErrorHandler from './middlewares/tsoa-to-xo-error.middleware.mjs'
import { RegisterRoutes } from './open-api/routes/routes.js'
import { iocContainer, setupContainer } from './ioc/ioc.mjs'
import { setupContainer } from './ioc/ioc.mjs'
import { setupApiContext } from './middlewares/authentication.middleware.mjs'
import { logMiddleware } from './middlewares/log.middleware.mjs'
import { mcpGateMiddleware } from './middlewares/mcp-gate.middleware.mjs'
import { type OpenAPIV3 } from 'openapi-types'
import { createExternalRouter, sendObjects } from './router/external-router.mjs'
import { BASE_URL } from './helpers/utils.helper.mjs'
import { KUBERNETES_WILDCARD_ENDPOINT, kubernetesRoutes } from './kubernetes/kubernetes.routes.mjs'
import { KubernetesOpenApiService } from './kubernetes/kubernetes.openapi.mjs'
import { createLogger } from '@xen-orchestra/log'
export { sendObjects }
const log = createLogger('xo:rest-api')
// Avoid using "import from" to import a json file as this requires assert/with and will break compatibility with recent node versions
// https://github.com/nodejs/node/issues/51622
const require = createRequire(import.meta.url)
@@ -57,11 +52,6 @@ export default function setupRestApi(express: Express, xoApp: XoApp) {
// Create dynamic router so it can be used by plugin to register rest routes
const { mountExternalRoute, externalRouter } = createExternalRouter(swaggerOpenApiSpec)
kubernetesRoutes.forEach(kubernetesRoute => {
mountExternalRoute(kubernetesRoute)
})
delete swaggerOpenApiSpec.paths[KUBERNETES_WILDCARD_ENDPOINT]
express.use(BASE_URL, setupApiContext(xoApp))
express.use(BASE_URL, logMiddleware)
express.use(BASE_URL, mcpGateMiddleware)
@@ -70,12 +60,7 @@ export default function setupRestApi(express: Express, xoApp: XoApp) {
express.use(BASE_URL, externalRouter)
express.get(`${BASE_URL}/docs/swagger.json`, async (_req, res) => {
try {
await iocContainer.get(KubernetesOpenApiService).apply(swaggerOpenApiSpec)
} catch (error) {
log.warn('An error occured while fetching the CAPI schema', { error })
}
express.get(`${BASE_URL}/docs/swagger.json`, (_req, res) => {
res.setHeader('Content-Type', 'application/json')
res.json(swaggerOpenApiSpec)
})

View File

@@ -14,13 +14,9 @@ import { BackupJobService } from '../backup-jobs/backup-job.service.mjs'
import { BackupLogService } from '../backup-logs/backup-log.service.mjs'
import { EventService } from '../events/event.service.mjs'
import { NetworkService } from '../networks/network.service.mjs'
import { BackupArchiveService } from '../backup-archives/backup-archive.service.mjs'
import { SrService } from '../srs/sr.service.mjs'
import { LicenseService } from '../licenses/license.service.mjs'
import { BackupRepositoryService } from '../backup-repositories/backup-repository.service.mjs'
import { KubernetesService } from '../kubernetes/kubernetes.service.mjs'
import { KubernetesOpenApiService } from '../kubernetes/kubernetes.openapi.mjs'
import { KubernetesEventService } from '../kubernetes/kubernetes.event.mjs'
const iocContainer = new Container()
@@ -117,14 +113,6 @@ export function setupContainer(xoApp: XoApp) {
})
.inSingletonScope()
iocContainer
.bind(BackupArchiveService)
.toDynamicValue(ctx => {
const restApi = ctx.container.get(RestApi)
return new BackupArchiveService(restApi)
})
.inSingletonScope()
iocContainer
.bind(SrService)
.toDynamicValue(ctx => {
@@ -148,30 +136,6 @@ export function setupContainer(xoApp: XoApp) {
return new BackupRepositoryService(restApi)
})
.inSingletonScope()
iocContainer
.bind(KubernetesService)
.toDynamicValue(ctx => {
const restApi = ctx.container.get(RestApi)
return new KubernetesService(restApi)
})
.inSingletonScope()
iocContainer
.bind(KubernetesOpenApiService)
.toDynamicValue(ctx => {
const kubernetesService = ctx.container.get(KubernetesService)
return new KubernetesOpenApiService(kubernetesService)
})
.inSingletonScope()
iocContainer
.bind(KubernetesEventService)
.toDynamicValue(ctx => {
const kubernetesService = ctx.container.get(KubernetesService)
return new KubernetesEventService(kubernetesService)
})
.inSingletonScope()
}
export { iocContainer }

View File

@@ -1,45 +0,0 @@
import { createLogger } from '@xen-orchestra/log'
import { ApiError } from '../helpers/error.helper.mjs'
import { RestApi } from '../rest-api/rest-api.mjs'
const log = createLogger('xo:rest-api:kubernetes-config')
/**
* Returns the normalized kubernetes proxy CAPI URL.
*
* TODO: replace with dynamic URL stored in REDIS ?
*/
export async function getCAPIUrl(restApi: RestApi): Promise<string> {
const configCAPIUrl = restApi.xoApp.config.getOptional<string>('rest-api.kubernetesProxyUrl')
if (configCAPIUrl === undefined || configCAPIUrl.trim() === '') {
throw new ApiError('Missing kubernetes proxy URL (rest-api.kubernetesProxyUrl) in config file', 503)
}
const CAPIUrl = configCAPIUrl.trim()
let url: URL
try {
url = new URL(CAPIUrl)
} catch (error) {
log.warn(`CAPI proxy URL at ${CAPIUrl} malformed`, error)
throw new ApiError(`CAPI proxy URL "${CAPIUrl}" malformed`, 503)
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new ApiError(`CAPI proxy URL "${CAPIUrl}" unsupported protocol`, 503)
}
return url.href.replace(/\/+$/, '')
}
export function getCAPIApiKey(restApi: RestApi): string {
const apiKey = restApi.xoApp.config.getOptional<string>('rest-api.kubernetesProxyKey')
if (apiKey === undefined || apiKey.trim() === '') {
throw new ApiError('Missing kubernetes proxy key (rest-api.kubernetesProxyKey) in config file', 503)
}
return apiKey.trim()
}

View File

@@ -1,277 +0,0 @@
import { EventEmitter } from 'node:events'
import { KubernetesService } from './kubernetes.service.mjs'
import { createLogger } from '@xen-orchestra/log'
import { createSseParser, SseEvent } from './kubernetes.sse.helper.mjs'
import { Readable } from 'node:stream'
import { setTimeout as delay } from 'node:timers/promises'
const log = createLogger('xo:rest-api:kubernetes-event')
const COLLECTION_EVENTS: readonly string[] = ['add', 'update', 'remove']
const RETRY_MIN = 1000
const RETRY_MAX = 30000
const HEALTHY_CONNECTION = 10000
const KUBERNETES_COLLECTIONS = ['kubernetes-cluster', 'kubernetes-node'] as const
export type KubernetesCollections = (typeof KUBERNETES_COLLECTIONS)[number]
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
export class KubernetesEventService {
#kubernetesService: KubernetesService
#emitters: Map<KubernetesCollections, EventEmitter>
#watcher: { abortController: AbortController; lastKnown: Map<KubernetesCollections, Map<string, object>> } | undefined
constructor(kubernetesService: KubernetesService) {
this.#kubernetesService = kubernetesService
this.#emitters = new Map()
for (const collection of KUBERNETES_COLLECTIONS) {
const emitter = new EventEmitter()
this.#emitters.set(collection, emitter)
emitter.on('newListener', name => {
if (typeof name === 'string' && COLLECTION_EVENTS.includes(name) && this.#getListenerCount() === 0) {
this.#startWatching().catch(error => log.warn('Kubernetes watcher failed to start', { error }))
}
})
emitter.on('removeListener', name => {
if (typeof name === 'string' && COLLECTION_EVENTS.includes(name) && this.#getListenerCount() === 0) {
this.#stopWatching()
}
})
}
process.on('SIGTERM', () => {
this.#stopWatching()
})
}
emitterFor(collection: KubernetesCollections): EventEmitter {
const emitter = this.#emitters.get(collection)
if (!emitter) {
throw new Error(`collection ${collection} has no emitter`)
}
return emitter
}
async #startWatching(): Promise<void> {
const abortController = new AbortController()
const lastKnown = new Map()
for (const collection of KUBERNETES_COLLECTIONS) lastKnown.set(collection, new Map())
this.#watcher = { abortController, lastKnown }
this.#watch(abortController).catch(error => log.warn('CAPI watcher stopped', { error }))
}
#stopWatching(): void {
if (this.#watcher) {
this.#watcher.abortController.abort()
}
this.#watcher = undefined
}
async #watch(abortController: AbortController) {
let attempt = 0
let firstConnection = true
while (!abortController.signal.aborted) {
let openedAt: number | undefined
try {
const path = `kubernetes/events`
const stream = await this.#kubernetesService.openEventStream(path, { signal: abortController.signal })
openedAt = Date.now()
try {
await this.#resync(!firstConnection)
} catch (error) {
log.warn('could not resynchronise the kubernetes collections', { error })
}
firstConnection = false
const parser = createSseParser()
for await (const chunk of Readable.fromWeb(stream)) {
this.#handleEvents(parser.push(chunk as Uint8Array))
}
this.#handleEvents(parser.end())
log.debug('Stream ended')
} catch (error) {
if (!abortController.signal.aborted) {
log.warn('Kubernetes event stream failed', { error })
}
}
if (abortController.signal.aborted) break
if (openedAt !== undefined && Date.now() - openedAt > HEALTHY_CONNECTION) {
attempt = 0
}
let reconnectionDelay = Math.min(RETRY_MAX, RETRY_MIN * 2 ** attempt)
reconnectionDelay = reconnectionDelay / 2 + (Math.random() * reconnectionDelay) / 2
try {
await delay(reconnectionDelay, undefined, { signal: abortController.signal })
} catch {
break
}
attempt++
}
}
#handleEvents(events: SseEvent[]): void {
for (const event of events) {
this.#handleEvent(event)
}
}
/**
* Turns an event of the kubernetes API into an event of the collection it belongs to
*
* The name of the event gives both the kind of the object (`cluster.created` -> `cluster`)
* and what happened to it, and the object itself is nested under a key named after its kind
*/
#handleEvent({ data, event }: SseEvent): void {
if (event === 'ping') {
return
}
if (event === 'error') {
log.warn('the kubernetes API answered an error on the event stream', { data })
return
}
const match = /^(?<payloadKey>[^.]+)\.(?<action>.+)$/.exec(event)
if (match === null) {
log.debug('ignoring an event which is not named after an object', { event })
return
}
const { action = '', payloadKey = '' } = match.groups ?? {}
const collection = this.#getCollectionType(payloadKey)
if (collection === undefined) {
log.debug('ignoring an event of an object which is not exposed by XO', { event })
return
}
if (!isRecord(data)) {
log.warn('ignoring an event whose data is not an object', { data, event })
return
}
const { id } = data
if (typeof id !== 'string') {
log.warn('ignoring an event whose object has no identifier', { data, event })
return
}
const emitter = this.emitterFor(collection)
// the objects are kept to be sent as the previous version of an updated or removed
// object, which the subscribers' privileges are checked against
const lastKnowns = this.#watcher?.lastKnown.get(collection)
// the object of a removed event is not sent by the kubernetes API, only its last
// known version is available
if (action === 'deleted') {
emitter.emit('remove', undefined, lastKnowns?.get(id))
lastKnowns?.delete(id)
return
}
const object = data[payloadKey]
if (!isRecord(object)) {
// e.g. `cluster.kubeconfig.available` only describes a change of context
log.debug('ignoring an event which does not carry its object', { event })
return
}
if (action === 'created') {
emitter.emit('add', object)
} else {
emitter.emit('update', object, lastKnowns?.get(id))
}
lastKnowns?.set(id, object)
}
async #resync(emit: boolean) {
const [clusters, nodes] = await Promise.all([
this.#kubernetesService.listClusters(),
this.#kubernetesService.listNodes(),
])
if (Array.isArray(clusters)) {
this.#resyncCollection(emit, 'kubernetes-cluster', clusters)
}
if (Array.isArray(nodes)) {
this.#resyncCollection(emit, 'kubernetes-node', nodes)
}
}
#resyncCollection(emit: boolean, collection: KubernetesCollections, records: unknown[]) {
const emitter = this.emitterFor(collection)
const lastKnowns = this.#watcher?.lastKnown.get(collection)
for (const record of records) {
if (isRecord(record) && typeof record['id'] === 'string') {
const recordId = record.id
if (emit) {
if (lastKnowns?.has(recordId)) {
emitter.emit('update', record, lastKnowns?.get(recordId))
} else {
emitter.emit('add', record)
}
}
lastKnowns?.set(record.id, record)
}
}
if (lastKnowns) {
for (const [id, lastKnown] of lastKnowns) {
if (!records.find(record => isRecord(record) && record.id === id)) {
if (emit) emitter.emit('remove', undefined, lastKnown)
lastKnowns.delete(id)
}
}
}
}
#getListenerCount(): number {
let listenerCount = 0
for (const emitter of this.#emitters.values()) {
for (const event of COLLECTION_EVENTS) {
listenerCount += emitter.listenerCount(event)
}
}
return listenerCount
}
#getCollectionType(type: string): KubernetesCollections | undefined {
switch (type) {
case 'node':
return 'kubernetes-node'
case 'cluster':
return 'kubernetes-cluster'
}
return undefined
}
}

View File

@@ -1,316 +0,0 @@
import assert from 'node:assert/strict'
import { afterEach, describe, it } from 'node:test'
import { setTimeout as delay } from 'node:timers/promises'
import { configure } from '@xen-orchestra/log/configure'
import createMemoryTransport from '@xen-orchestra/log/transports/memory'
import { KubernetesEventService } from './kubernetes.event.mjs'
import type { KubernetesService } from './kubernetes.service.mjs'
// the logs are kept in memory instead of being printed while the tests run
configure({ level: 'WARN', transport: createMemoryTransport() })
// each service registers a handler on `SIGTERM` to stop its watcher: the tests create
// many of them, which node would report as a leak
process.setMaxListeners(0)
const encoder = new TextEncoder()
const CLUSTER = { id: 'cluster-1', name: 'first', phase: 'Provisioned' }
const OTHER_CLUSTER = { id: 'cluster-2', name: 'second', phase: 'Provisioned' }
const NODE = { id: 'node-1', name: 'first-node', $cluster: 'cluster-1' }
const sseFrame = (event: string, data: unknown) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`
// the kubernetes API sends its objects in an envelope which identifies them, nested under
// a key named after their kind
const clusterFrame = (action: string, cluster: { id: string; name?: string }) =>
sseFrame(`cluster.${action}`, {
observed_at: '2026-10-26T10:00:00Z',
namespace: 'default',
id: cluster.id,
name: cluster.name,
cluster,
})
type Emission = { collection: string; type: string; object: unknown; previous: unknown }
async function waitFor(predicate: () => boolean, message: string, timeout = 1000) {
const deadline = Date.now() + timeout
while (!predicate()) {
if (Date.now() > deadline) {
assert.fail(message)
}
await delay(5)
}
}
// A service whose event stream is driven by the test: `send` pushes raw SSE frames into
// the stream the watcher is currently reading, and `endStream` ends it, which makes the
// watcher reconnect
function createWatcher({ clusters = [], nodes = [] }: { clusters?: unknown[]; nodes?: unknown[] } = {}) {
let controller: ReadableStreamDefaultController<Uint8Array> | undefined
const state = { clusters, nodes, openCount: 0, paths: [] as string[] }
const kubernetesService = {
listClusters: async () => state.clusters,
listNodes: async () => state.nodes,
openEventStream: async (path: string, { signal }: { signal: AbortSignal }) => {
state.paths.push(path)
state.openCount++
return new ReadableStream<Uint8Array>({
start(streamController) {
controller = streamController
// mimics the body of the request being destroyed when the watcher stops
signal.addEventListener('abort', () => {
try {
streamController.close()
} catch {
// the stream has already been ended by the test
}
})
},
})
},
}
const service = new KubernetesEventService(kubernetesService as unknown as KubernetesService)
const emissions: Emission[] = []
const detach: Array<() => void> = []
// the watcher starts as soon as a collection has a listener
for (const collection of ['kubernetes-cluster', 'kubernetes-node'] as const) {
const emitter = service.emitterFor(collection)
for (const type of ['add', 'update', 'remove'] as const) {
const handler = (object: unknown, previous: unknown) => {
emissions.push({ collection, type, object, previous })
}
emitter.on(type, handler)
detach.push(() => emitter.off(type, handler))
}
}
return {
emissions,
service,
state,
send: (...frames: string[]) => {
for (const frame of frames) {
controller!.enqueue(encoder.encode(frame))
}
},
endStream: () => {
controller!.close()
controller = undefined
},
// removing the last listener stops the watcher
stop: () => detach.forEach(off => off()),
}
}
let watcher: ReturnType<typeof createWatcher> | undefined
afterEach(() => {
watcher?.stop()
watcher = undefined
})
async function startWatcher(options?: { clusters?: unknown[]; nodes?: unknown[] }) {
const started = (watcher = createWatcher(options))
await waitFor(() => started.state.openCount === 1, 'the event stream has not been opened')
return started
}
describe('KubernetesEventService#emitterFor', () => {
const service = () => new KubernetesEventService({} as unknown as KubernetesService)
it('returns the same emitter for a collection', () => {
const kubernetesEventService = service()
assert.equal(
kubernetesEventService.emitterFor('kubernetes-cluster'),
kubernetesEventService.emitterFor('kubernetes-cluster')
)
})
it('returns a distinct emitter for each collection', () => {
const kubernetesEventService = service()
assert.notEqual(
kubernetesEventService.emitterFor('kubernetes-cluster'),
kubernetesEventService.emitterFor('kubernetes-node')
)
})
it('throws for a collection which is not watched', () => {
assert.throws(() => service().emitterFor('kubernetes-pool' as 'kubernetes-node'), /no emitter/)
})
})
describe('the events of the kubernetes API', () => {
it('opens a single stream for every collection', async () => {
const watcher = await startWatcher()
assert.deepEqual(watcher.state.paths, ['kubernetes/events'])
})
it('emits an add when an object is created', async () => {
const watcher = await startWatcher()
watcher.send(clusterFrame('created', CLUSTER))
await waitFor(() => watcher.emissions.length === 1, 'the created cluster has not been emitted')
assert.deepEqual(watcher.emissions, [
{ collection: 'kubernetes-cluster', type: 'add', object: CLUSTER, previous: undefined },
])
})
it('emits an update with the previous version of the object', async () => {
const watcher = await startWatcher()
const updated = { ...CLUSTER, phase: 'Running' }
watcher.send(clusterFrame('created', CLUSTER), clusterFrame('updated', updated))
await waitFor(() => watcher.emissions.length === 2, 'the updated cluster has not been emitted')
assert.deepEqual(watcher.emissions[1], {
collection: 'kubernetes-cluster',
type: 'update',
object: updated,
previous: CLUSTER,
})
})
it('emits a remove with the last known version of the object', async () => {
const watcher = await startWatcher()
// the object of a deleted event is not sent by the kubernetes API
watcher.send(clusterFrame('created', CLUSTER), sseFrame('cluster.deleted', { id: CLUSTER.id, name: CLUSTER.name }))
await waitFor(() => watcher.emissions.length === 2, 'the deleted cluster has not been emitted')
assert.deepEqual(watcher.emissions[1], {
collection: 'kubernetes-cluster',
type: 'remove',
object: undefined,
previous: CLUSTER,
})
})
it('forgets a deleted object', async () => {
const watcher = await startWatcher()
const deleted = sseFrame('cluster.deleted', { id: CLUSTER.id })
watcher.send(clusterFrame('created', CLUSTER), deleted, deleted)
await waitFor(() => watcher.emissions.length === 3, 'the deleted cluster has not been emitted twice')
assert.deepEqual(watcher.emissions[2], {
collection: 'kubernetes-cluster',
type: 'remove',
object: undefined,
previous: undefined,
})
})
it('emits the events of a node on its own collection', async () => {
const watcher = await startWatcher()
watcher.send(sseFrame('node.created', { id: NODE.id, name: NODE.name, node: NODE }))
await waitFor(() => watcher.emissions.length === 1, 'the created node has not been emitted')
assert.deepEqual(watcher.emissions, [
{ collection: 'kubernetes-node', type: 'add', object: NODE, previous: undefined },
])
})
describe('ignores', () => {
// the events are handled in the order they are received: a known event sent after the
// ignored ones tells that they have been handled
const assertIgnored = async (...frames: string[]) => {
const watcher = await startWatcher()
watcher.send(...frames, clusterFrame('created', OTHER_CLUSTER))
await waitFor(() => watcher.emissions.length > 0, 'nothing has been emitted at all')
assert.deepEqual(watcher.emissions, [
{ collection: 'kubernetes-cluster', type: 'add', object: OTHER_CLUSTER, previous: undefined },
])
}
it('the heartbeats', () => assertIgnored(sseFrame('ping', {})))
it('the errors of the stream', () => assertIgnored(sseFrame('error', { detail: 'something went wrong' })))
it('the events of an object which is not exposed by XO', () =>
assertIgnored(sseFrame('machine.created', { id: 'machine-1', machine: { id: 'machine-1' } })))
it('the events which do not carry their object', () =>
// `cluster.kubeconfig.available` only describes a change of context
assertIgnored(sseFrame('cluster.kubeconfig.available', { id: CLUSTER.id, context: 'admin@first' })))
it('the events whose object has no identifier', () => assertIgnored(sseFrame('cluster.created', { cluster: {} })))
it('the events which are not named after an object', () => assertIgnored(sseFrame('shutdown', { id: CLUSTER.id })))
})
})
describe('the resynchronisation of the collections', () => {
it('records the objects of the first connection without emitting them', async () => {
const watcher = await startWatcher({ clusters: [CLUSTER], nodes: [NODE] })
// nothing is emitted for the objects which are fetched on the first connection, but
// they are known: the deletion of one of them carries its last known version
watcher.send(sseFrame('cluster.deleted', { id: CLUSTER.id }))
await waitFor(() => watcher.emissions.length === 1, 'the deleted cluster has not been emitted')
assert.deepEqual(watcher.emissions, [
{ collection: 'kubernetes-cluster', type: 'remove', object: undefined, previous: CLUSTER },
])
})
it('emits the changes which happened while the stream was interrupted', async () => {
const watcher = await startWatcher({ clusters: [CLUSTER, OTHER_CLUSTER] })
const updated = { ...OTHER_CLUSTER, phase: 'Running' }
const created = { id: 'cluster-3', name: 'third' }
// while disconnected, a cluster has been deleted, another has changed and a third one
// has appeared
watcher.state.clusters = [updated, created]
watcher.endStream()
await waitFor(() => watcher.state.openCount === 2, 'the watcher has not reconnected', 5000)
await waitFor(() => watcher.emissions.length === 3, 'the differences have not been emitted')
assert.deepEqual(watcher.emissions, [
{ collection: 'kubernetes-cluster', type: 'update', object: updated, previous: OTHER_CLUSTER },
{ collection: 'kubernetes-cluster', type: 'add', object: created, previous: undefined },
{ collection: 'kubernetes-cluster', type: 'remove', object: undefined, previous: CLUSTER },
])
})
it('keeps handling the events after a reconnection', async () => {
const watcher = await startWatcher()
watcher.endStream()
await waitFor(() => watcher.state.openCount === 2, 'the watcher has not reconnected', 5000)
watcher.send(clusterFrame('created', CLUSTER))
await waitFor(() => watcher.emissions.length === 1, 'the created cluster has not been emitted')
assert.deepEqual(watcher.emissions, [
{ collection: 'kubernetes-cluster', type: 'add', object: CLUSTER, previous: undefined },
])
})
})

View File

@@ -1,256 +0,0 @@
import { createLogger } from '@xen-orchestra/log'
import { OpenAPIV3 } from 'openapi-types'
import { PROXIED_METHODS, type KubernetesAclRule } from './kubernetes.routes.mjs'
import {
badGatewayResp,
badRequestResp,
forbiddenOperationResp,
invalidParameters,
serviceUnavailableResp,
unauthorizedResp,
} from '../open-api/common/response.common.mjs'
const log = createLogger('xo:rest-api:kubernetes-openapi-helper')
const CAPI_IGNORED_PATHS = new Set(['/ping'])
const CAPI_SCHEMA_PREFIX = 'Kubernetes'
const SCHEMA_REF_PREFIX = '#/components/schemas/'
// Only the fields describing CAPI's data are imported
const IMPORTED_OPERATION_FIELDS = ['parameters', 'requestBody', 'responses', 'summary'] as const
// Header parameters describing the HTTP protocol itself
const IGNORED_HEADER_PARAMETERS = new Set(['accept', 'content-type'])
const XO_ERROR_RESPONSES = {
[badRequestResp.status]: { description: badRequestResp.description },
[unauthorizedResp.status]: { description: unauthorizedResp.description },
[forbiddenOperationResp.status]: { description: forbiddenOperationResp.description },
[invalidParameters.status]: { description: invalidParameters.description },
[badGatewayResp.status]: { description: badGatewayResp.description },
[serviceUnavailableResp.status]: { description: serviceUnavailableResp.description },
}
const TAG = 'kubernetes'
export type CAPISpecFragment = {
paths: OpenAPIV3.PathsObject
schemas: Record<string, OpenAPIV3.SchemaObject>
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
/**
* Turns a CAPI path into the path XO REST API path
*
* `/kubernetes/clusters/` -> `/kubernetes/clusters`
*/
export function CAPIPathToXoPath(path: string): string {
return path.length > 1 ? path.replace(/\/+$/, '') : path
}
/**
* Must be used for both the schema names and the references pointing to them
*/
function prefixSchemaName(name: string): string {
return CAPI_SCHEMA_PREFIX + name.charAt(0).toUpperCase() + name.slice(1)
}
/**
* Prefixes every reference to a CAPI schema
*/
export function prefixSchemaRefs(node: unknown): void {
if (Array.isArray(node)) {
node.forEach(child => prefixSchemaRefs(child))
return
}
if (!isRecord(node)) {
return
}
const { $ref } = node
if (typeof $ref === 'string' && $ref.startsWith(SCHEMA_REF_PREFIX)) {
node.$ref = SCHEMA_REF_PREFIX + prefixSchemaName($ref.slice(SCHEMA_REF_PREFIX.length))
}
Object.values(node).forEach(child => prefixSchemaRefs(child))
}
/**
* Converts the OpenAPI 3.1 nullable types to 3.0
*/
export function convertNullableTypes(node: unknown): void {
if (Array.isArray(node)) {
node.forEach(child => convertNullableTypes(child))
return
}
if (!isRecord(node)) {
return
}
const { type } = node
if (Array.isArray(type)) {
const types = type.filter(_ => _ !== 'null')
if (types.length !== type.length) {
node.nullable = true
}
if (types.length === 1) {
node.type = types[0]
} else {
// OpenAPI 3.0 cannot express a union of types, the schema is left untyped
delete node.type
if (types.length > 1) {
log.warn('a union type cannot be converted to OpenAPI 3.0 and is left untyped', { type })
}
}
}
Object.values(node).forEach(child => convertNullableTypes(child))
}
function importResponses(responses: unknown): OpenAPIV3.ResponsesObject {
const importedResponses: Record<string, unknown> = {}
if (isRecord(responses)) {
Object.entries(responses).forEach(([status, response]) => {
if (status.match(/^2\d\d$/)) {
importedResponses[status] = response
}
})
}
return { ...importedResponses, ...XO_ERROR_RESPONSES } as OpenAPIV3.ResponsesObject
}
/**
* The parameters describing the HTTP protocol are removed, and the key itself when it becomes empty
*/
function importParameters(parameters: unknown): unknown {
if (!Array.isArray(parameters)) {
return parameters
}
const importedParameters = parameters.filter(parameter => {
if (!isRecord(parameter) || parameter.in !== 'header' || typeof parameter.name !== 'string') {
return true
}
return !IGNORED_HEADER_PARAMETERS.has(parameter.name.toLowerCase())
})
return importedParameters.length > 0 ? importedParameters : undefined
}
// XO owns the description: it documents how the endpoint can be used, which CAPI does not
// know about
function describeOperation(rule: KubernetesAclRule | undefined): string {
const description = ['Proxied to the kubernetes API.', '']
if (rule === undefined) {
description.push('Only administrators can use this endpoint.')
} else {
const { action, resource } = rule.privilege
description.push('Required privilege:', `- resource: ${resource}, action: ${action}`)
}
return description.join('\n')
}
/**
* Returns the ACL rules declared for an endpoint CAPI does not expose for logging
*/
export function findUnknownAclRules(paths: OpenAPIV3.PathsObject, aclRules: KubernetesAclRule[]): KubernetesAclRule[] {
return aclRules.filter(rule => paths[rule.endpoint]?.[rule.method] === undefined)
}
/**
* Extracts from CAPI's OpenAPI specification the paths and schemas to merge into XO's specification
*/
export function transformCAPISpec(spec: unknown, aclRules: KubernetesAclRule[] = []): CAPISpecFragment {
const fragment: CAPISpecFragment = { paths: {}, schemas: {} }
if (!isRecord(spec) || !isRecord(spec.paths)) {
log.warn('CAPI specification is malformed and is ignored')
return fragment
}
const { openapi } = spec
if (typeof openapi !== 'string' || !openapi.startsWith('3.')) {
log.warn('CAPI specification version is not supported and is ignored', { openapi })
return fragment
}
// the specification is cloned as it is modified in place below and the caller may reuse it
const source = structuredClone(spec)
convertNullableTypes(source)
prefixSchemaRefs(source)
for (const [CAPIPath, pathItem] of Object.entries(source.paths as Record<string, unknown>)) {
if (CAPI_IGNORED_PATHS.has(CAPIPath) || !isRecord(pathItem)) {
continue
}
const xoPath = CAPIPathToXoPath(CAPIPath)
const operations: Record<string, unknown> = {}
for (const method of PROXIED_METHODS) {
const operation = pathItem[method]
if (!isRecord(operation)) {
continue
}
const importedOperation: Record<string, unknown> = {}
for (const field of IMPORTED_OPERATION_FIELDS) {
if (field !== 'responses' && operation[field] !== undefined) {
importedOperation[field] = operation[field]
}
}
importedOperation.responses = importResponses(operation.responses)
importedOperation.parameters = importParameters(importedOperation.parameters)
if (importedOperation.parameters === undefined) {
delete importedOperation.parameters
}
importedOperation.tags = [TAG]
importedOperation.description = describeOperation(
aclRules.find(rule => rule.method === method && rule.endpoint === xoPath)
)
operations[method] = importedOperation
}
if (Object.keys(operations).length > 0) {
fragment.paths[xoPath] = operations as OpenAPIV3.PathItemObject
}
}
const components = source.components
if (isRecord(components) && isRecord(components.schemas)) {
for (const [name, schema] of Object.entries(components.schemas)) {
fragment.schemas[prefixSchemaName(name)] = schema as OpenAPIV3.SchemaObject
}
}
return fragment
}
/**
* Merges a CAPI fragment into XO's specification
*/
export function mergeFragment(targetSpec: OpenAPIV3.Document, { paths, schemas }: CAPISpecFragment): void {
Object.assign(targetSpec.paths, paths)
const components = (targetSpec.components ??= {})
const targetSchemas = (components.schemas ??= {})
Object.assign(targetSchemas, schemas)
}

View File

@@ -1,455 +0,0 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import type { OpenAPIV3 } from 'openapi-types'
import {
CAPIPathToXoPath,
convertNullableTypes,
findUnknownAclRules,
mergeFragment,
prefixSchemaRefs,
transformCAPISpec,
} from './kubernetes.openapi.helper.mjs'
import type { KubernetesAclRule } from './kubernetes.routes.mjs'
const READ_CLUSTERS: KubernetesAclRule = {
method: 'get',
endpoint: '/kubernetes/clusters',
privilege: { resource: 'kubernetes-cluster', action: 'read' },
}
const CAPI_PATHS = ['/kubernetes/clusters', '/kubernetes/clusters/{id}/config', '/kubernetes/quotas']
const CAPI_SPEC_FIXTURE = {
openapi: '3.1.0',
info: { title: 'Cluster service', version: '0.1.0' },
components: {
schemas: {
ClusterCreateParams: {
description: 'ClusterCreateParams schema',
properties: {
controlPlaneReplicas: { format: 'int32', minimum: 1, type: 'integer' },
name: { type: 'string' },
},
required: ['controlPlaneReplicas', 'name'],
type: 'object',
},
ClusterInfo: {
description: 'ClusterInfo schema',
properties: {
name: { type: 'string' },
phase: { type: 'string' },
},
required: ['name', 'phase'],
type: 'object',
},
ErrorItem: {
properties: {
more: { description: 'Additional information about the error', type: ['object', 'null'] },
name: { type: 'string' },
},
required: ['name'],
type: 'object',
},
HTTPError: {
description: 'HTTPError schema',
properties: {
detail: { type: 'string' },
errors: { items: { $ref: '#/components/schemas/ErrorItem' }, type: ['array', 'null'] },
status: { example: 403, type: 'integer' },
},
type: 'object',
},
string: { description: 'string schema', type: 'string' },
},
},
paths: {
'/kubernetes/clusters/': {
get: {
description: '#### Controller: \n\n`capv-proxy/internal/components/webserver/handlers`\n\n---\n\n',
operationId: 'GET_/kubernetes/clusters/',
parameters: [{ in: 'header', name: 'Accept', schema: { type: 'string' } }],
responses: {
'200': {
content: {
'application/json': { schema: { items: { $ref: '#/components/schemas/ClusterInfo' }, type: 'array' } },
},
description: 'OK',
},
'400': {
content: { 'application/json': { schema: { $ref: '#/components/schemas/HTTPError' } } },
description: 'Bad Request _(validation or deserialization error)_',
},
},
summary: 'get clusters',
tags: ['Clusters'],
},
post: {
operationId: 'POST_/kubernetes/clusters/',
requestBody: {
content: { 'application/json': { schema: { $ref: '#/components/schemas/ClusterCreateParams' } } },
required: true,
},
responses: {
'200': {
content: { 'application/json': { schema: { $ref: '#/components/schemas/ClusterInfo' } } },
description: 'OK',
},
},
summary: 'create cluster',
tags: ['Clusters'],
},
},
'/kubernetes/clusters/{id}/config': {
get: {
operationId: 'GET_/kubernetes/clusters/:id/config',
parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }],
responses: {
'200': {
content: { 'application/json': { schema: { $ref: '#/components/schemas/string' } } },
description: 'OK',
},
},
summary: 'get cluster config',
tags: ['Clusters'],
},
},
// not mounted by XO: must be reported as drift
'/kubernetes/quotas': {
get: {
responses: { '200': { description: 'OK' } },
summary: 'get quotas',
tags: ['Quotas'],
},
},
// never exposed by XO: must neither be imported nor reported as drift
'/ping': {
get: {
responses: { '200': { description: 'OK' } },
summary: 'ping',
tags: ['Health'],
},
},
},
}
const transformFixture = (aclRules: KubernetesAclRule[] = []) => transformCAPISpec(CAPI_SPEC_FIXTURE, aclRules)
describe('CAPIPathToXoPath', () => {
it('strips the CAPI prefix and the trailing slash', () => {
assert.equal(CAPIPathToXoPath('/kubernetes/clusters/'), '/kubernetes/clusters')
})
it('keeps the path parameters and the sub paths', () => {
assert.equal(CAPIPathToXoPath('/kubernetes/clusters/{id}/nodes'), '/kubernetes/clusters/{id}/nodes')
})
it('strips repeated trailing slashes', () => {
assert.equal(CAPIPathToXoPath('/kubernetes/clusters///'), '/kubernetes/clusters')
})
it('leaves a path without the CAPI prefix untouched', () => {
assert.equal(CAPIPathToXoPath('/ping'), '/ping')
})
it('keeps the root path', () => {
assert.equal(CAPIPathToXoPath('/'), '/')
})
})
describe('convertNullableTypes', () => {
it('converts a nullable type', () => {
const schema = { type: ['object', 'null'] }
convertNullableTypes(schema)
assert.deepEqual(schema, { type: 'object', nullable: true })
})
it('converts a nullable array', () => {
const schema = { items: { type: 'string' }, type: ['array', 'null'] }
convertNullableTypes(schema)
assert.deepEqual(schema, { items: { type: 'string' }, type: 'array', nullable: true })
})
it('converts a type which can only be null', () => {
const schema = { type: ['null'] }
convertNullableTypes(schema)
assert.deepEqual(schema, { nullable: true })
})
it('leaves untyped a union of types, which OpenAPI 3.0 cannot express', () => {
const schema = { type: ['string', 'number'] }
convertNullableTypes(schema)
assert.deepEqual(schema, {})
})
it('leaves a single type untouched', () => {
const schema = { type: 'string' }
convertNullableTypes(schema)
assert.deepEqual(schema, { type: 'string' })
})
it('converts nested types', () => {
const schema = {
properties: { errors: { items: { properties: { more: { type: ['object', 'null'] } } } } },
type: 'object',
}
convertNullableTypes(schema)
assert.deepEqual(schema.properties.errors.items.properties.more, { type: 'object', nullable: true })
})
})
describe('prefixSchemaRefs', () => {
it('prefixes a reference', () => {
const node = { $ref: '#/components/schemas/ClusterInfo' }
prefixSchemaRefs(node)
assert.equal(node.$ref, '#/components/schemas/KubernetesClusterInfo')
})
it('prefixes nested references', () => {
const node = { content: [{ schema: { items: { $ref: '#/components/schemas/ErrorItem' } } }] }
prefixSchemaRefs(node)
assert.equal(node.content[0].schema.items.$ref, '#/components/schemas/KubernetesErrorItem')
})
it('leaves the references which do not point to a schema untouched', () => {
const node = { $ref: '#/components/parameters/id' }
prefixSchemaRefs(node)
assert.equal(node.$ref, '#/components/parameters/id')
})
})
describe('transformCAPISpec', () => {
it('extracts every CAPI path, as every CAPI endpoint is proxied', () => {
const { paths } = transformFixture()
assert.deepEqual(Object.keys(paths).sort(), CAPI_PATHS.slice().sort())
})
it('does not extract the paths which are never exposed by XO', () => {
assert.equal(transformFixture().paths['/ping'], undefined)
})
it('only imports the fields describing CAPI data, and the ones owned by XO', () => {
// this endpoint has no parameter left once the `Accept` header one is removed
const operation = transformFixture().paths['/kubernetes/clusters']!.get!
assert.deepEqual(Object.keys(operation).sort(), ['description', 'responses', 'summary', 'tags'])
assert.deepEqual(operation.tags, ['kubernetes'])
const parameterizedOperation = transformFixture().paths['/kubernetes/clusters/{id}/config']!.get!
assert.deepEqual(Object.keys(parameterizedOperation).sort(), [
'description',
'parameters',
'responses',
'summary',
'tags',
])
})
it('removes the parameters describing the HTTP protocol', () => {
// the `Accept` header parameter is the only parameter of this endpoint
assert.equal(transformFixture().paths['/kubernetes/clusters']!.get!.parameters, undefined)
// the path parameters are kept
assert.deepEqual(transformFixture().paths['/kubernetes/clusters/{id}/config']!.get!.parameters, [
{ in: 'path', name: 'id', required: true, schema: { type: 'string' } },
])
})
it('imports the responses of CAPI which describe a success', () => {
const { responses } = transformFixture().paths['/kubernetes/clusters']!.get!
const success = responses['200'] as OpenAPIV3.ResponseObject
assert.equal(success.description, 'OK')
assert.deepEqual(success.content!['application/json'].schema, {
items: { $ref: '#/components/schemas/KubernetesClusterInfo' },
type: 'array',
})
})
it('replaces the responses of CAPI which describe an error', () => {
// CAPI describes this status with its own error schema, XO answers its own errors
const { responses } = transformFixture().paths['/kubernetes/clusters']!.get!
const badRequest = responses['400'] as OpenAPIV3.ResponseObject
assert.equal(badRequest.description, 'Bad request')
assert.equal(badRequest.content, undefined)
})
it('documents the errors which are answered by XO and not by CAPI', () => {
// this endpoint only declares a `200` in CAPI's specification
const { responses } = transformFixture().paths['/kubernetes/clusters']!.post!
assert.deepEqual(Object.keys(responses).sort(), ['200', '400', '401', '403', '422', '502', '503'])
})
it('does not document a status which is not answered by XO', () => {
// CAPI errors are answered as a bad gateway
for (const pathItem of Object.values(transformFixture().paths)) {
for (const operation of Object.values(pathItem!)) {
assert.equal((operation as OpenAPIV3.OperationObject).responses?.['500'], undefined)
}
}
})
it('documents that an endpoint without privilege can only be used by administrators', () => {
const { description } = transformFixture().paths['/kubernetes/clusters']!.get!
assert.match(description!, /Only administrators/)
})
it('documents the privilege required by an endpoint', () => {
const { description } = transformFixture([READ_CLUSTERS]).paths['/kubernetes/clusters']!.get!
assert.match(description!, /resource: kubernetes-cluster, action: read/)
})
it('prefixes the schemas', () => {
assert.deepEqual(Object.keys(transformFixture().schemas).sort(), [
'KubernetesClusterCreateParams',
'KubernetesClusterInfo',
'KubernetesErrorItem',
'KubernetesHTTPError',
'KubernetesString',
])
})
it('every reference of the extracted paths points to an extracted schema', () => {
const { paths, schemas } = transformFixture()
const refs: string[] = []
const collectRefs = (node: unknown) => {
if (Array.isArray(node)) {
return node.forEach(collectRefs)
}
if (typeof node !== 'object' || node === null) {
return
}
const { $ref } = node as { $ref?: unknown }
if (typeof $ref === 'string') {
refs.push($ref)
}
Object.values(node).forEach(collectRefs)
}
collectRefs(paths)
assert.ok(refs.length > 0)
for (const ref of refs) {
assert.ok(
schemas[ref.replace('#/components/schemas/', '')] !== undefined,
`${ref} does not point to an extracted schema`
)
}
})
it('converts the nullable types of the extracted schemas', () => {
const { schemas } = transformFixture()
assert.deepEqual(schemas.KubernetesHTTPError!.properties!.errors, {
items: { $ref: '#/components/schemas/KubernetesErrorItem' },
type: 'array',
nullable: true,
})
assert.deepEqual(schemas.KubernetesErrorItem!.properties!.more, {
description: 'Additional information about the error',
type: 'object',
nullable: true,
})
})
it('does not modify the given specification', () => {
const spec = structuredClone(CAPI_SPEC_FIXTURE)
transformCAPISpec(spec)
assert.deepEqual(spec, CAPI_SPEC_FIXTURE)
})
it('ignores a malformed specification', () => {
const empty = { paths: {}, schemas: {} }
assert.deepEqual(transformCAPISpec(undefined), empty)
assert.deepEqual(transformCAPISpec({}), empty)
assert.deepEqual(transformCAPISpec({ openapi: '3.0.0' }), empty)
})
it('ignores an unsupported specification version', () => {
assert.deepEqual(transformCAPISpec({ ...CAPI_SPEC_FIXTURE, openapi: '2.0' }), { paths: {}, schemas: {} })
})
})
describe('mergeFragment', () => {
const makeTargetSpec = (): OpenAPIV3.Document => ({
openapi: '3.0.0',
info: { title: 'xo-server', version: '1.0.0' },
paths: {
'/vms': { get: { responses: { '200': { description: 'Success' } } } },
},
})
it('adds the CAPI paths, which XO does not declare', () => {
const targetSpec = makeTargetSpec()
mergeFragment(targetSpec, transformFixture())
assert.deepEqual(Object.keys(targetSpec.paths).sort(), ['/vms', ...CAPI_PATHS].sort())
})
it('adds the responses and their schemas', () => {
const targetSpec = makeTargetSpec()
mergeFragment(targetSpec, transformFixture())
const response = targetSpec.paths['/kubernetes/clusters']!.get!.responses['200'] as OpenAPIV3.ResponseObject
assert.equal(response.description, 'OK')
assert.deepEqual(response.content!['application/json'].schema, {
items: { $ref: '#/components/schemas/KubernetesClusterInfo' },
type: 'array',
})
})
it('adds the request bodies', () => {
const targetSpec = makeTargetSpec()
mergeFragment(targetSpec, transformFixture())
assert.deepEqual(targetSpec.paths['/kubernetes/clusters']!.post!.requestBody, {
content: { 'application/json': { schema: { $ref: '#/components/schemas/KubernetesClusterCreateParams' } } },
required: true,
})
})
it('does not modify the paths of the other routes', () => {
const targetSpec = makeTargetSpec()
mergeFragment(targetSpec, transformFixture())
assert.deepEqual(targetSpec.paths['/vms'], { get: { responses: { '200': { description: 'Success' } } } })
})
it('adds the schemas', () => {
const targetSpec = makeTargetSpec()
mergeFragment(targetSpec, transformFixture())
assert.notEqual(targetSpec.components!.schemas!.KubernetesClusterInfo, undefined)
})
it('gives the same result when applied twice', () => {
const targetSpec = makeTargetSpec()
mergeFragment(targetSpec, transformFixture())
const once = structuredClone(targetSpec)
mergeFragment(targetSpec, transformFixture())
assert.deepEqual(targetSpec, once)
})
})
describe('findUnknownAclRules', () => {
it('returns the rules declared for an endpoint CAPI does not expose', () => {
const unknownRule: KubernetesAclRule = {
method: 'get',
endpoint: '/kubernetes/quotas/{id}',
privilege: { resource: 'kubernetes-cluster', action: 'read' },
}
const { paths } = transformFixture()
assert.deepEqual(findUnknownAclRules(paths, [READ_CLUSTERS, unknownRule]), [unknownRule])
})
it('takes the method into account', () => {
const { paths } = transformFixture()
assert.deepEqual(findUnknownAclRules(paths, [{ ...READ_CLUSTERS, method: 'patch' }]), [
{ ...READ_CLUSTERS, method: 'patch' },
])
})
})

View File

@@ -1,70 +0,0 @@
import { createLogger } from '@xen-orchestra/log'
import { OpenAPIV3 } from 'openapi-types'
import { AsyncCacheEntry, getFromAsyncCache } from '../helpers/cache.helper.mjs'
import { KUBERNETES_ACL_RULES } from './kubernetes.routes.mjs'
import { MaybePromise } from '../helpers/helper.type.mjs'
import { KubernetesService } from './kubernetes.service.mjs'
import {
type CAPISpecFragment,
findUnknownAclRules,
mergeFragment,
transformCAPISpec,
} from './kubernetes.openapi.helper.mjs'
const log = createLogger('xo:rest-api:kubernetes-openapi')
const CAPI_SPEC_CACHE_KEY = 'capiSpec'
export class KubernetesOpenApiService {
#kubernetesService: KubernetesService
#cache = new Map<string, AsyncCacheEntry<MaybePromise<CAPISpecFragment>>>()
#lastUnknownAclEndpoints: string | undefined
constructor(kubernetesService: KubernetesService) {
this.#kubernetesService = kubernetesService
}
/**
* Completes XO's specification with CAPI's own specification
*/
async apply(targetSpec: OpenAPIV3.Document): Promise<void> {
const result = await getFromAsyncCache(
this.#cache,
CAPI_SPEC_CACHE_KEY,
async () => transformCAPISpec(await this.#kubernetesService.getCAPISpec(), KUBERNETES_ACL_RULES),
{
expiresIn: 10 * 60 * 1e3,
timeout: 5e3,
}
)
if (result?.value === undefined) {
return
}
mergeFragment(targetSpec, result.value)
this.#logUnknownAclEndpoints(result.value)
}
/**
* The rules are logged only when they change, as the specification is applied on every
* request made to the documentation
*/
#logUnknownAclEndpoints({ paths }: CAPISpecFragment): void {
const unknownRules = findUnknownAclRules(paths, KUBERNETES_ACL_RULES)
const endpoints = unknownRules.map(({ endpoint, method }) => `${method.toUpperCase()} ${endpoint}`).join(', ')
if (endpoints === this.#lastUnknownAclEndpoints) {
return
}
this.#lastUnknownAclEndpoints = endpoints
if (unknownRules.length > 0) {
log.warn('privileges are declared for kubernetes endpoints which do not exist and are therefore never used', {
endpoints,
})
}
}
}

View File

@@ -1,208 +0,0 @@
import { unauthorized } from 'xo-common/api-errors.js'
import { ApiError } from '../helpers/error.helper.mjs'
import { KubernetesService } from './kubernetes.service.mjs'
import type { RouteDefinition } from '../router/types.mjs'
import { SupportedActions } from '@xen-orchestra/acl'
// Every CAPI endpoint is proxied, the routes are mounted on a wildcard endpoint
export const KUBERNETES_WILDCARD_ENDPOINT = '/kubernetes/*'
const XO_PATH_PREFIX = '/kubernetes'
const CAPI_PATH_PREFIX = 'kubernetes'
// The only resource used by the rules for now, the privileges of a route are declared for
// a single resource
const KUBERNETES_ACL_RESOURCE = 'kubernetes-cluster'
//The methods proxied to CAPI
export const PROXIED_METHODS: readonly RouteDefinition['method'][] = ['get', 'post', 'put', 'patch', 'delete']
/**
* Privilege required to use a kubernetes endpoint as a non administrator
*
* The endpoint is declared as it is exposed by XO (`/kubernetes/clusters/{id}/nodes`), with its parameters
*/
export type KubernetesAclRule = {
method: RouteDefinition['method']
endpoint: string
privilege: { resource: typeof KUBERNETES_ACL_RESOURCE; action: SupportedActions<typeof KUBERNETES_ACL_RESOURCE> }
}
/**
* The endpoints in this array can have their privileges configured,
* otherwise they are only accessible to admins
*/
export const KUBERNETES_ACL_RULES: KubernetesAclRule[] = [
{
method: 'get',
endpoint: '/kubernetes/clusters',
privilege: {
resource: 'kubernetes-cluster',
action: 'read',
},
},
{
method: 'post',
endpoint: '/kubernetes/clusters',
privilege: {
resource: 'kubernetes-cluster',
action: 'create',
},
},
{
method: 'get',
endpoint: '/kubernetes/clusters/{id}',
privilege: {
resource: 'kubernetes-cluster',
action: 'read',
},
},
{
method: 'delete',
endpoint: '/kubernetes/clusters/{id}',
privilege: {
resource: 'kubernetes-cluster',
action: 'delete',
},
},
{
method: 'get',
endpoint: '/kubernetes/clusters/{id}/config',
privilege: {
resource: 'kubernetes-cluster',
action: 'read-config',
},
},
{
method: 'get',
endpoint: '/kubernetes/clusters/{id}/nodes',
privilege: {
resource: 'kubernetes-cluster',
action: 'read',
},
},
]
/**
* Throws if the path cannot be safely forwarded to CAPI
*/
export function checkCAPISubPath(subPath: string): void {
for (const segment of subPath.split('/')) {
let decodedSegment
try {
decodedSegment = decodeURIComponent(segment)
} catch (error) {
throw new ApiError(`the path segment "${segment}" is not correctly encoded`, 400)
}
if (decodedSegment === '..' || decodedSegment.includes('/')) {
throw new ApiError(`the path segment "${segment}" is not allowed`, 400)
}
}
}
export type KubernetesAclRuleMatch = {
rule: KubernetesAclRule
params: Record<string, string>
}
/**
* Compiles the given rules to be matched against the method and the path of a request
*
* Exported for testing
*/
export function createAclRuleMatcher(
rules: KubernetesAclRule[]
): (method: string, path: string) => KubernetesAclRuleMatch | undefined {
const compiledRules = rules.map(rule => {
const paramNames: string[] = []
const source = rule.endpoint.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\\\{(\w+)\\\}/g, (_, name: string) => {
paramNames.push(name)
return '([^/]+)'
})
return { paramNames, regExp: new RegExp(`^${source}$`), rule }
})
return function findAclRule(method, path) {
for (const { paramNames, regExp, rule } of compiledRules) {
if (rule.method !== method) {
continue
}
const match = regExp.exec(path)
if (match === null) {
continue
}
const params: Record<string, string> = {}
paramNames.forEach((name, index) => {
params[name] = decodeURIComponent(match[index + 1])
})
return { params, rule }
}
}
}
const findAclRule = createAclRuleMatcher(KUBERNETES_ACL_RULES)
function getRequestPath(req: { url: string }): string {
const queryStart = req.url.indexOf('?')
return queryStart === -1 ? req.url : req.url.slice(0, queryStart)
}
/**
* Returns the action required to use the requested endpoint, or `undefined` when no
* privilege is declared for it
*
* Exported for testing
*/
export function getAclAction(
method: RouteDefinition['method'],
req: { url: string }
): KubernetesAclRule['privilege']['action'] | undefined {
return findAclRule(method, getRequestPath(req))?.rule.privilege.action
}
/**
* Returns the objects the privileges are checked against
*
* Exported for testing
*/
export function getAclObjects(method: RouteDefinition['method'], req: { url: string }): [Record<string, string>] {
return [findAclRule(method, getRequestPath(req))?.params ?? {}]
}
export const kubernetesRoutes: RouteDefinition[] = PROXIED_METHODS.map(method => ({
method,
endpoint: KUBERNETES_WILDCARD_ENDPOINT,
tags: ['kubernetes'],
middlewares: [
{
name: 'acl',
acls: {
resource: KUBERNETES_ACL_RESOURCE,
action: ({ req }) => getAclAction(method, req),
objects: ({ req }) => getAclObjects(method, req),
},
},
],
callback: async ({ req, res, restApi }) => {
const path = getRequestPath(req)
// an endpoint without privilege can only be used by an administrator
if (findAclRule(method, path) === undefined && restApi.getCurrentUser().permission !== 'admin') {
throw unauthorized()
}
const CAPISubPath = path.slice(XO_PATH_PREFIX.length)
checkCAPISubPath(CAPISubPath)
await restApi.ioc.get(KubernetesService).forwardRequest(`${CAPI_PATH_PREFIX}${CAPISubPath}`, req, res)
},
}))

View File

@@ -1,158 +0,0 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import {
checkCAPISubPath,
createAclRuleMatcher,
getAclAction,
getAclObjects,
KUBERNETES_ACL_RULES,
type KubernetesAclRule,
} from './kubernetes.routes.mjs'
const READ_CLUSTERS: KubernetesAclRule = {
method: 'get',
endpoint: '/kubernetes/clusters',
privilege: { resource: 'kubernetes-cluster', action: 'read' },
}
const READ_CLUSTER: KubernetesAclRule = {
method: 'get',
endpoint: '/kubernetes/clusters/{id}',
privilege: { resource: 'kubernetes-cluster', action: 'read' },
}
const READ_CLUSTER_CONFIG: KubernetesAclRule = {
method: 'get',
endpoint: '/kubernetes/clusters/{id}/config',
privilege: { resource: 'kubernetes-cluster', action: 'read-config' },
}
const DELETE_CLUSTER: KubernetesAclRule = {
method: 'delete',
endpoint: '/kubernetes/clusters/{id}',
privilege: { resource: 'kubernetes-cluster', action: 'delete' },
}
describe('createAclRuleMatcher', () => {
const findAclRule = createAclRuleMatcher([READ_CLUSTERS, READ_CLUSTER, READ_CLUSTER_CONFIG, DELETE_CLUSTER])
it('matches an endpoint without parameter', () => {
assert.deepEqual(findAclRule('get', '/kubernetes/clusters'), { params: {}, rule: READ_CLUSTERS })
})
it('matches an endpoint with a parameter and extracts it', () => {
assert.deepEqual(findAclRule('get', '/kubernetes/clusters/cluster-1'), {
params: { id: 'cluster-1' },
rule: READ_CLUSTER,
})
})
it('decodes the extracted parameters', () => {
assert.deepEqual(findAclRule('get', '/kubernetes/clusters/my%20cluster')?.params, { id: 'my cluster' })
})
it('matches the sub paths of an endpoint with a parameter', () => {
assert.equal(findAclRule('get', '/kubernetes/clusters/cluster-1/config')?.rule, READ_CLUSTER_CONFIG)
})
it('does not match a parameter on several path segments', () => {
// `/kubernetes/clusters/{id}` must not match this path, which has no rule
assert.equal(findAclRule('get', '/kubernetes/clusters/cluster-1/nodes'), undefined)
})
it('takes the method into account', () => {
assert.equal(findAclRule('delete', '/kubernetes/clusters/cluster-1')?.rule, DELETE_CLUSTER)
assert.equal(findAclRule('post', '/kubernetes/clusters/cluster-1'), undefined)
})
it('does not match an unknown endpoint', () => {
assert.equal(findAclRule('get', '/kubernetes/quotas'), undefined)
})
it('does not match a partial path', () => {
assert.equal(findAclRule('get', '/kubernetes/clusters/cluster-1/'), undefined)
assert.equal(findAclRule('get', '/other/kubernetes/clusters'), undefined)
})
it('uses the first matching rule', () => {
const other: KubernetesAclRule = { ...READ_CLUSTERS, privilege: { resource: 'kubernetes-cluster', action: '*' } }
assert.equal(createAclRuleMatcher([READ_CLUSTERS, other])('get', '/kubernetes/clusters')?.rule, READ_CLUSTERS)
assert.equal(createAclRuleMatcher([other, READ_CLUSTERS])('get', '/kubernetes/clusters')?.rule, other)
})
it('never matches when there is no rule', () => {
assert.equal(createAclRuleMatcher([])('get', '/kubernetes/clusters'), undefined)
})
})
describe('getAclAction', () => {
it('returns the action declared for each endpoint', () => {
assert.equal(getAclAction('get', { url: '/kubernetes/clusters' }), 'read')
assert.equal(getAclAction('post', { url: '/kubernetes/clusters' }), 'create')
assert.equal(getAclAction('get', { url: '/kubernetes/clusters/cluster-1' }), 'read')
assert.equal(getAclAction('delete', { url: '/kubernetes/clusters/cluster-1' }), 'delete')
assert.equal(getAclAction('get', { url: '/kubernetes/clusters/cluster-1/nodes' }), 'read')
assert.equal(getAclAction('get', { url: '/kubernetes/clusters/cluster-1/config' }), 'read-config')
})
it('ignores the query string', () => {
assert.equal(getAclAction('get', { url: '/kubernetes/clusters?fields=name' }), 'read')
})
it('returns undefined when no privilege is declared for the endpoint', () => {
// the request is then refused by the callback, unless the user is an administrator
assert.equal(getAclAction('get', { url: '/kubernetes/quotas' }), undefined)
assert.equal(getAclAction('put', { url: '/kubernetes/clusters/cluster-1' }), undefined)
})
it('declares an action for every method and endpoint of the rules', () => {
for (const { endpoint, method, privilege } of KUBERNETES_ACL_RULES) {
const url = endpoint.replace(/\{\w+\}/g, 'cluster-1')
assert.equal(getAclAction(method, { url }), privilege.action, `${method} ${endpoint}`)
}
})
})
describe('getAclObjects', () => {
it('returns the parameters of the endpoint', () => {
assert.deepEqual(getAclObjects('get', { url: '/kubernetes/clusters/cluster-1' }), [{ id: 'cluster-1' }])
assert.deepEqual(getAclObjects('get', { url: '/kubernetes/clusters/cluster-1/config' }), [{ id: 'cluster-1' }])
})
it('returns a single empty object for an endpoint without parameter', () => {
assert.deepEqual(getAclObjects('get', { url: '/kubernetes/clusters' }), [{}])
})
it('never returns an empty array, even when no rule matches', () => {
// an empty array would make the privileges not be checked at all
assert.deepEqual(getAclObjects('get', { url: '/kubernetes/quotas' }), [{}])
assert.equal(getAclObjects('patch', { url: '/kubernetes/clusters' }).length, 1)
})
})
describe('checkCAPISubPath', () => {
it('accepts a regular path', () => {
checkCAPISubPath('/clusters')
checkCAPISubPath('/clusters/cluster-1/nodes')
checkCAPISubPath('/clusters/my%20cluster')
})
it('refuses a parent directory segment', () => {
assert.throws(() => checkCAPISubPath('/clusters/../../ping'), { status: 400 })
})
it('refuses an encoded parent directory segment', () => {
assert.throws(() => checkCAPISubPath('/clusters/%2e%2e/ping'), { status: 400 })
})
it('refuses an encoded path separator', () => {
assert.throws(() => checkCAPISubPath('/clusters/cluster%2f..%2fping'), { status: 400 })
})
it('refuses a malformed encoding', () => {
assert.throws(() => checkCAPISubPath('/clusters/%zz'), { status: 400 })
})
})

View File

@@ -1,195 +0,0 @@
import { createLogger } from '@xen-orchestra/log'
import { RestApi } from '../rest-api/rest-api.mjs'
import { getCAPIApiKey, getCAPIUrl } from './kubernetes.config.mjs'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { type Request as ExRequest, type Response as ExResponse } from 'express'
import { ApiError } from '../helpers/error.helper.mjs'
import { XoApp } from '@vates/types'
import { HttpStatusCodeLiteral } from 'tsoa'
import { invalidParameters } from 'xo-common/api-errors.js'
const log = createLogger('xo:rest-api:kubernetes-service')
const CAPI_SPEC_PATH = 'swagger/openapi.json'
const DEFAULT_TIMEOUT = 10e3
const RELAYED_CAPI_STATUSES = new Set<number>([400, 404, 409, 422])
function isRelayableStatus(status: number): status is HttpStatusCodeLiteral {
return RELAYED_CAPI_STATUSES.has(status)
}
export class KubernetesService {
#restApi: RestApi
constructor(restApi: RestApi) {
this.#restApi = restApi
}
/**
* Forwards a REST request to CAPI and parsing the result
*/
async forwardRequest(CAPIPath: string, req: ExRequest, res: ExResponse): Promise<void> {
let CAPIUrl = await this.#getTargetUrl(CAPIPath)
const queryStart = req.url.indexOf('?')
if (queryStart !== -1) CAPIUrl += req.url.slice(queryStart)
const hasBody =
(req.headers['content-length'] && parseInt(req.headers['content-length']) > 0) ||
req.headers['transfer-encoding'] !== undefined
const headers: Record<string, string> = {}
if (req.headers.accept) headers.accept = req.headers.accept
if (hasBody) {
if (req.headers['content-type']) headers['content-type'] = req.headers['content-type']
if (req.headers['content-length']) headers['content-length'] = req.headers['content-length']
}
const reqOpts: NonNullable<Parameters<XoApp['httpRequest']>[1]> = {
bypassStatusCheck: true,
headers,
method: req.method,
}
if (hasBody) {
reqOpts.body = req
}
const CAPIRes = await this.#getResponse(CAPIUrl, reqOpts)
if (!CAPIRes.ok) {
await this.#throwCAPIError(CAPIUrl, CAPIRes)
}
res.status(CAPIRes.status)
const CAPIResContentType = CAPIRes.headers.get('content-type')
if (CAPIResContentType !== null) res.contentType(CAPIResContentType)
if (CAPIRes.body) {
await pipeline(Readable.fromWeb(CAPIRes.body), res)
} else {
res.end()
}
}
/**
* Fetches the OpenAPI specification of CAPI
*/
async getCAPISpec(): Promise<unknown> {
return this.#callCAPI(CAPI_SPEC_PATH)
}
async listClusters(): Promise<unknown> {
return this.#callCAPI('kubernetes/clusters')
}
async listNodes(): Promise<unknown> {
return this.#callCAPI('kubernetes/nodes')
}
async openEventStream(CAPIPath: string, { signal }: { signal: AbortSignal }): Promise<NonNullable<Response['body']>> {
const CAPIUrl = await this.#getTargetUrl(CAPIPath)
const CAPIRes = await this.#getResponse(CAPIUrl, {
bypassStatusCheck: true,
headers: { accept: 'text/event-stream' },
method: 'GET',
bodyTimeout: 0,
signal,
})
if (!CAPIRes.ok) {
await this.#throwCAPIError(CAPIUrl, CAPIRes)
}
if (CAPIRes.body === null) {
throw new ApiError('CAPI answered 2xx with no body', 502)
}
return CAPIRes.body
}
async #callCAPI(path: string): Promise<unknown> {
const CAPIUrl = await this.#getTargetUrl(path)
const CAPIRes = await this.#getResponse(CAPIUrl, {
bypassStatusCheck: true,
headers: { accept: 'application/json' },
method: 'GET',
})
if (!CAPIRes.ok) {
await this.#throwCAPIError(CAPIUrl, CAPIRes)
}
return CAPIRes.body === null || CAPIRes.status === 204 ? undefined : await CAPIRes.json()
}
/**
* Builds the error and throws when CAPI answers with an error
*/
async #throwCAPIError(CAPIUrl: string, CAPIRes: Response): Promise<never> {
let text = (await CAPIRes.text().catch(() => '')).substring(0, 1024)
try {
text = JSON.parse(text)
} catch {
// This way if the content is not JSON we don't throw.
}
let message = `CAPI answered with the status ${CAPIRes.status}`
if (typeof text === 'object' && text !== null) {
log.warn(`CAPI answered with an error at ${CAPIUrl}`, { CAPIError: text, status: CAPIRes.status })
const { detail, title, errors } = text as { detail?: unknown; title?: unknown; errors?: unknown }
if ((CAPIRes.status === 400 || CAPIRes.status === 422) && Array.isArray(errors) && errors.length > 0) {
throw invalidParameters(typeof detail === 'string' ? detail : undefined, errors)
}
if (typeof detail === 'string') {
message = detail
} else if (typeof title === 'string') {
message = title
}
}
throw new ApiError(message, isRelayableStatus(CAPIRes.status) ? CAPIRes.status : 502, {
data: { CAPIError: text },
})
}
/**
* Builds the call CAPI URL
*/
async #getTargetUrl(CAPIPath: string): Promise<string> {
return `${await getCAPIUrl(this.#restApi)}/${CAPIPath.replace(/^\//, '')}`
}
/**
* Run the CAPI requests and handle the errors if needed
*/
async #getResponse(CAPIUrl: string, reqOpts: NonNullable<Parameters<XoApp['httpRequest']>[1]>): Promise<Response> {
const timeout = this.#restApi.xoApp.config.getOptionalDuration('rest-api.kubernetesProxyTimeout') ?? DEFAULT_TIMEOUT
const apiKey = getCAPIApiKey(this.#restApi)
try {
return await this.#restApi.xoApp.httpRequest(CAPIUrl, {
headersTimeout: timeout,
...reqOpts,
headers: { ...reqOpts.headers, 'API-Key': apiKey },
})
} catch (error) {
if (error != null && typeof error === 'object' && 'response' in error) {
return (error as { response: Response }).response
} else if (error instanceof Error && error.name === 'AbortError') {
throw error
} else {
log.warn(`CAPI unreachable at ${CAPIUrl}`, error)
throw new ApiError('An error occurred while reaching the CAPI', 503)
}
}
}
}

View File

@@ -1,315 +0,0 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { invalidParameters } from 'xo-common/api-errors.js'
import { ApiError } from '../helpers/error.helper.mjs'
import { KubernetesService } from './kubernetes.service.mjs'
import type { RestApi } from '../rest-api/rest-api.mjs'
import type { XoApp } from '@vates/types'
const CAPI_URL = 'http://capi.invalid:30080'
const CAPI_KEY = 'a-secret-key'
type HttpRequest = XoApp['httpRequest']
// A service backed by a fake `xoApp`: `httpRequest` is the only thing the tests need to
// control, and the CAPI URL and API key come from the configuration to avoid depending on
// the hardcoded development values. `config` overrides an entry, with an explicit
// `undefined` standing for an entry which is not configured at all
function makeService(httpRequest: HttpRequest, config: Record<string, string | undefined> = {}): KubernetesService {
const entries: Record<string, string | undefined> = {
'rest-api.kubernetesProxyUrl': CAPI_URL,
'rest-api.kubernetesProxyKey': CAPI_KEY,
...config,
}
const xoApp = {
config: {
getOptional: (path: string) => entries[path],
getOptionalDuration: () => undefined,
},
httpRequest,
}
return new KubernetesService({ xoApp } as unknown as RestApi)
}
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
}
// mimics `xoApp.httpRequest`, which throws on any non 2xx response and exposes it as
// `error.response` when `bypassStatusCheck` is used
function throwingHttpRequest(response: Response): HttpRequest {
return async () => {
throw Object.assign(new Error(`${response.status}`), { response })
}
}
async function assertApiError(promise: Promise<unknown>, { status, message }: { status: number; message?: string }) {
const error = await promise.then(
() => assert.fail('expected the promise to be rejected'),
(error: unknown) => error
)
assert.ok(error instanceof ApiError, `expected an ApiError, got ${String(error)}`)
assert.equal(error.status, status)
if (message !== undefined) {
assert.equal(error.message, message)
}
return error
}
// the errors of the invalid parameters are not `ApiError`s but XO errors, as they are
// built by `xo-common`
async function assertInvalidParameters(
promise: Promise<unknown>,
{ message, errors }: { message: string; errors: unknown }
) {
const error = await promise.then(
() => assert.fail('expected the promise to be rejected'),
(error: unknown) => error
)
assert.ok(invalidParameters.is(error), `expected an invalidParameters error, got ${String(error)}`)
assert.equal((error as Error).message, message)
assert.deepEqual((error as { data: { errors: unknown } }).data.errors, errors)
}
describe('getCAPISpec', () => {
it('returns the parsed specification', async () => {
const service = makeService(async () => jsonResponse({ openapi: '3.1.0', paths: {} }))
assert.deepEqual(await service.getCAPISpec(), { openapi: '3.1.0', paths: {} })
})
it('returns undefined when the response has no content', async () => {
const service = makeService(async () => new Response(null, { status: 204 }))
assert.equal(await service.getCAPISpec(), undefined)
})
it('requests the specification of the configured CAPI', async () => {
let url: string | undefined
let opts: Parameters<HttpRequest>[1]
const service = makeService(async (_url, _opts) => {
url = _url
opts = _opts
return jsonResponse({})
})
await service.getCAPISpec()
assert.equal(url, `${CAPI_URL}/swagger/openapi.json`)
assert.equal(opts!.method, 'GET')
assert.equal(opts!.body, undefined)
assert.equal(opts!.headers!.accept, 'application/json')
})
it('relays the status of the CAPI error', async () => {
const service = makeService(throwingHttpRequest(jsonResponse({ title: 'not found' }, 404)))
await assertApiError(service.getCAPISpec(), { status: 404 })
})
it('uses a bad gateway status when the CAPI status cannot be relayed', async () => {
const service = makeService(throwingHttpRequest(jsonResponse({ title: 'teapot' }, 418)))
await assertApiError(service.getCAPISpec(), { status: 502 })
})
it('uses the detail of the CAPI error as message', async () => {
const service = makeService(throwingHttpRequest(jsonResponse({ detail: 'workerReplicas must be >= 1' }, 400)))
const error = await assertApiError(service.getCAPISpec(), {
status: 400,
message: 'workerReplicas must be >= 1',
})
assert.deepEqual(error.data, { CAPIError: { detail: 'workerReplicas must be >= 1' } })
})
it('falls back on the title of the CAPI error as message', async () => {
const service = makeService(throwingHttpRequest(jsonResponse({ title: 'Bad Request' }, 400)))
await assertApiError(service.getCAPISpec(), {
status: 400,
message: 'Bad Request',
})
})
it('keeps the body of a CAPI error which is not JSON', async () => {
const service = makeService(throwingHttpRequest(new Response('<html>Bad Gateway</html>', { status: 500 })))
const error = await assertApiError(service.getCAPISpec(), {
status: 502,
message: 'CAPI answered with the status 500',
})
assert.deepEqual(error.data, { CAPIError: '<html>Bad Gateway</html>' })
})
it('translates the validation errors of CAPI into invalid parameters', async () => {
const errors = [{ name: 'workerReplicas', reason: 'must be >= 1' }]
const service = makeService(
throwingHttpRequest(jsonResponse({ detail: 'workerReplicas must be >= 1', errors }, 422))
)
await assertInvalidParameters(service.getCAPISpec(), { message: 'workerReplicas must be >= 1', errors })
})
it('also translates the validation errors answered with a bad request status', async () => {
// CAPI used to answer `400` for an invalid input, before answering `422`
const errors = [{ name: 'name', reason: 'is required' }]
const service = makeService(throwingHttpRequest(jsonResponse({ errors }, 400)))
await assertInvalidParameters(service.getCAPISpec(), { message: 'invalid parameters', errors })
})
it('does not translate an error which has no validation error', async () => {
// e.g. CAPI answers a bad request when a cluster does not exist
const service = makeService(throwingHttpRequest(jsonResponse({ detail: 'unknown cluster' }, 400)))
await assertApiError(service.getCAPISpec(), { status: 400, message: 'unknown cluster' })
})
it('does not translate an error whose validation errors are empty', async () => {
const service = makeService(throwingHttpRequest(jsonResponse({ detail: 'nope', errors: [] }, 422)))
await assertApiError(service.getCAPISpec(), { status: 422, message: 'nope' })
})
it('throws a service unavailable error when CAPI cannot be reached', async () => {
const service = makeService(async () => {
throw new Error('connect ECONNREFUSED')
})
await assertApiError(service.getCAPISpec(), {
status: 503,
message: 'An error occurred while reaching the CAPI',
})
})
})
describe('openEventStream', () => {
const abortController = new AbortController()
it('requests the stream and returns its body', async () => {
let url: string | undefined
let opts: Parameters<HttpRequest>[1]
const service = makeService(async (_url, _opts) => {
url = _url
opts = _opts
return new Response('event: ping\ndata: {}\n\n', { headers: { 'content-type': 'text/event-stream' } })
})
const stream = await service.openEventStream('kubernetes/clusters/cluster-1/events', {
signal: abortController.signal,
})
assert.equal(url, `${CAPI_URL}/kubernetes/clusters/cluster-1/events`)
assert.equal(opts!.headers!.accept, 'text/event-stream')
assert.equal(opts!.signal, abortController.signal)
// an event stream is idle most of the time: it must not be aborted between two events
assert.equal(opts!.bodyTimeout, 0)
const { value } = await stream.getReader().read()
assert.equal(new TextDecoder().decode(value), 'event: ping\ndata: {}\n\n')
})
it('throws the error answered by CAPI', async () => {
const service = makeService(throwingHttpRequest(jsonResponse({ detail: 'unknown cluster' }, 404)))
await assertApiError(
service.openEventStream('kubernetes/clusters/nope/events', { signal: abortController.signal }),
{ status: 404, message: 'unknown cluster' }
)
})
it('throws a bad gateway error when the response has no body', async () => {
const service = makeService(async () => new Response(null, { status: 204 }))
await assertApiError(
service.openEventStream('kubernetes/clusters/cluster-1/events', { signal: abortController.signal }),
{ status: 502 }
)
})
it('rethrows an abort as-is, as it is not a failure', async () => {
const service = makeService(async () => {
throw Object.assign(new Error('This operation was aborted'), { name: 'AbortError' })
})
const error = await service
.openEventStream('kubernetes/clusters/cluster-1/events', { signal: abortController.signal })
.then(
() => assert.fail('expected the promise to be rejected'),
(error: unknown) => error
)
assert.ok(!(error instanceof ApiError))
assert.equal((error as Error).name, 'AbortError')
})
})
describe('the CAPI URL', () => {
it('fails before reaching CAPI when it is not configured', async () => {
const service = makeService(() => assert.fail('CAPI must not be called without an URL'), {
'rest-api.kubernetesProxyUrl': undefined,
})
await assertApiError(service.getCAPISpec(), {
status: 503,
message: 'Missing kubernetes proxy URL (rest-api.kubernetesProxyUrl) in config file',
})
})
})
describe('the API key', () => {
// the key is added by `#getResponse`, through which every call to CAPI goes
it('is sent as a header, next to the headers of the request', async () => {
let opts: Parameters<HttpRequest>[1]
const service = makeService(async (_url, _opts) => {
opts = _opts
return jsonResponse({})
})
await service.getCAPISpec()
assert.equal(opts!.headers!['API-Key'], CAPI_KEY)
assert.equal(opts!.headers!.accept, 'application/json')
})
it('is sent on the event stream as well', async () => {
let opts: Parameters<HttpRequest>[1]
const service = makeService(async (_url, _opts) => {
opts = _opts
return new Response('', { headers: { 'content-type': 'text/event-stream' } })
})
await service.openEventStream('kubernetes/events', { signal: new AbortController().signal })
assert.equal(opts!.headers!['API-Key'], CAPI_KEY)
assert.equal(opts!.headers!.accept, 'text/event-stream')
})
it('fails before reaching CAPI when it is not configured', async () => {
const service = makeService(() => assert.fail('CAPI must not be called without an API key'), {
'rest-api.kubernetesProxyKey': undefined,
})
await assertApiError(service.getCAPISpec(), {
status: 503,
message: 'Missing kubernetes proxy key (rest-api.kubernetesProxyKey) in config file',
})
})
it('fails when it is configured but blank', async () => {
const service = makeService(() => assert.fail('CAPI must not be called without an API key'), {
'rest-api.kubernetesProxyKey': ' \t ',
})
await assertApiError(service.getCAPISpec(), { status: 503 })
})
})

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