mirror of
https://github.com/vatesfr/xen-orchestra.git
synced 2026-11-27 09:17:18 -06:00
Compare commits
51 Commits
rest-api/p
...
fix/my-tas
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd91c70dfe | ||
|
|
ffce2806d4 | ||
|
|
28e6fc56bb | ||
|
|
4e2c272398 | ||
|
|
54051163e0 | ||
|
|
9ff4716ef1 | ||
|
|
810e342df2 | ||
|
|
20e90b6d0f | ||
|
|
c23587cbdc | ||
|
|
f67f94a60b | ||
|
|
07722cd4f3 | ||
|
|
b6d1387425 | ||
|
|
8f8c8ca405 | ||
|
|
424f970cf9 | ||
|
|
dfc298e40b | ||
|
|
750c74beb1 | ||
|
|
050c47079a | ||
|
|
dca9d63799 | ||
|
|
c42b46b833 | ||
|
|
77c24dacd7 | ||
|
|
9bee5dc5b1 | ||
|
|
2313809c11 | ||
|
|
21d458cdd1 | ||
|
|
fa675eead1 | ||
|
|
31c3f5bb20 | ||
|
|
7e850aedaf | ||
|
|
069cb2816a | ||
|
|
7c63be3aaf | ||
|
|
9c68705932 | ||
|
|
14ed5fd5b9 | ||
|
|
f7e476cd81 | ||
|
|
2a4491aeda | ||
|
|
e9760747f9 | ||
|
|
eae4e889b6 | ||
|
|
fdbfa97002 | ||
|
|
57c1865270 | ||
|
|
a0a11fdd48 | ||
|
|
54fb7a33b8 | ||
|
|
edbfe8c7e4 | ||
|
|
e97cea2dd6 | ||
|
|
467c0130fc | ||
|
|
de62672a07 | ||
|
|
4b242221f3 | ||
|
|
0be66a2698 | ||
|
|
82dabbf0cd | ||
|
|
1fca20d82e | ||
|
|
04de2031e6 | ||
|
|
7c6b48d139 | ||
|
|
06080bbec6 | ||
|
|
f608a47d8f | ||
|
|
543aebb302 |
@@ -14,7 +14,7 @@
|
||||
"url": "https://vates.fr"
|
||||
},
|
||||
"license": "ISC",
|
||||
"version": "0.1.6",
|
||||
"version": "0.1.7",
|
||||
"engines": {
|
||||
"node": ">=8.10"
|
||||
},
|
||||
@@ -25,7 +25,7 @@
|
||||
"dependencies": {
|
||||
"@vates/multi-key-map": "^0.2.0",
|
||||
"@xen-orchestra/async-map": "^0.1.5",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"ensure-array": "^1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vates/fuse-vhd",
|
||||
"version": "2.1.3",
|
||||
"version": "2.1.4",
|
||||
"license": "ISC",
|
||||
"private": false,
|
||||
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@vates/fuse-vhd",
|
||||
@@ -19,12 +19,12 @@
|
||||
},
|
||||
"main": "./index.mjs",
|
||||
"dependencies": {
|
||||
"@xen-orchestra/fs": "^4.10.0",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/fs": "^4.11.0",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"fuse-native": "^2.2.6",
|
||||
"lru-cache": "^7.14.0",
|
||||
"promise-toolbox": "^0.21.0",
|
||||
"vhd-lib": "^4.17.0"
|
||||
"vhd-lib": "^4.17.1"
|
||||
},
|
||||
"bin": {
|
||||
"xo-fuse-vhd": "./cli.mjs"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vates/iscsi",
|
||||
"version": "0.4.0",
|
||||
"version": "0.4.1",
|
||||
"main": "dist/index.mjs",
|
||||
"types": "dist/index.d.mts",
|
||||
"bin": {
|
||||
@@ -24,7 +24,7 @@
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@vates/read-chunk": "^1.2.1",
|
||||
"@xen-orchestra/disk-transform": "^1.3.4",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"promise-toolbox": "^0.21.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from 'node:assert'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { pFromCallback } from 'promise-toolbox'
|
||||
import { pFromCallback, pTimeout } from 'promise-toolbox'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import AbstractNbdClient from './AbstractNbdClient.mjs'
|
||||
|
||||
@@ -9,6 +9,9 @@ const { warn } = createLogger('vates:nbd-client:stdio')
|
||||
// only the tail is kept: it's the part describing why the server died
|
||||
const STDERR_MAX_LENGTH = 4096
|
||||
|
||||
// how long a failed connection waits for the server to exit and its stderr to end
|
||||
const CLOSE_TIMEOUT = 1e3
|
||||
|
||||
/**
|
||||
* NBD client talking to a server through its standard streams, like
|
||||
* `nbdkit -s` or `qemu-nbd` in `--fd` mode: the queries are written to the
|
||||
@@ -28,7 +31,7 @@ export default class NbdStdioClient extends AbstractNbdClient {
|
||||
#cwd
|
||||
#env
|
||||
|
||||
/** @type {{ child: import('node:child_process').ChildProcess, closing: boolean, stderr: string }|undefined} */
|
||||
/** @type {{ child: import('node:child_process').ChildProcess, closing: boolean, stderr: string, closed: Promise<unknown> }|undefined} */
|
||||
#state
|
||||
|
||||
/**
|
||||
@@ -68,6 +71,36 @@ export default class NbdStdioClient extends AbstractNbdClient {
|
||||
return this.#state?.child.pid
|
||||
}
|
||||
|
||||
/**
|
||||
* A server dying before the handshake makes it fail with "stream has ended
|
||||
* without data", and the exit handler, racing with the teardown, often
|
||||
* reports nothing: what the server wrote on stderr is the only reason given,
|
||||
* so it becomes the error.
|
||||
*/
|
||||
async connect() {
|
||||
try {
|
||||
return await super.connect()
|
||||
} catch (error) {
|
||||
const state = this.#state
|
||||
const closed =
|
||||
state !== undefined &&
|
||||
(await pTimeout.call(state.closed, CLOSE_TIMEOUT).then(
|
||||
() => true,
|
||||
() => false
|
||||
))
|
||||
// exitCode is null when the process was killed, by us when it did not die by itself
|
||||
if (closed && state.child.exitCode !== null && state.stderr !== '') {
|
||||
const serverError = new Error(state.stderr.trim(), { cause: error })
|
||||
serverError.code = 'NBD_SERVER_EXITED'
|
||||
serverError.exitCode = state.child.exitCode
|
||||
serverError.command = this.#command
|
||||
serverError.stderr = state.stderr
|
||||
throw serverError
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async _openTransport() {
|
||||
const child = spawn(this.#command, this.#args, {
|
||||
cwd: this.#cwd,
|
||||
@@ -75,7 +108,13 @@ export default class NbdStdioClient extends AbstractNbdClient {
|
||||
// the protocol goes through stdin/stdout, stderr is only used for diagnostics
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
})
|
||||
const state = { child, closing: false, stderr: '' }
|
||||
const state = {
|
||||
child,
|
||||
closing: false,
|
||||
stderr: '',
|
||||
// 'close' comes after the exit and the end of the standard streams: stderr is complete
|
||||
closed: new Promise(resolve => child.once('close', resolve)),
|
||||
}
|
||||
this.#state = state
|
||||
|
||||
child.stderr.setEncoding('utf8')
|
||||
|
||||
19
@vates/nbd-client/NbdStdioClient.test.mjs
Normal file
19
@vates/nbd-client/NbdStdioClient.test.mjs
Normal file
@@ -0,0 +1,19 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
|
||||
import NbdStdioClient from './NbdStdioClient.mjs'
|
||||
|
||||
describe('NbdStdioClient', () => {
|
||||
it('reports what the server wrote on stderr when it dies before the handshake', async () => {
|
||||
// the end of stdout and the exit of the process come in either order: repeat
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const client = new NbdStdioClient({ command: 'sh', args: ['-c', 'echo "the actual reason" >&2; exit 1'] })
|
||||
await assert.rejects(client.connect(), {
|
||||
code: 'NBD_SERVER_EXITED',
|
||||
exitCode: 1,
|
||||
message: 'the actual reason',
|
||||
stderr: 'the actual reason\n',
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -13,7 +13,7 @@
|
||||
"url": "https://vates.fr"
|
||||
},
|
||||
"license": "ISC",
|
||||
"version": "3.7.0",
|
||||
"version": "3.7.2",
|
||||
"engines": {
|
||||
"node": ">=14.0"
|
||||
},
|
||||
@@ -23,9 +23,9 @@
|
||||
"@vates/read-chunk": "^1.2.1",
|
||||
"@xen-orchestra/async-map": "^0.1.5",
|
||||
"@xen-orchestra/disk-transform": "^1.3.4",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"promise-toolbox": "^0.21.0",
|
||||
"xen-api": "^5.1.0"
|
||||
"xen-api": "^6.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"tap": "^18.7.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vates/node-vsphere-soap",
|
||||
"version": "2.2.0",
|
||||
"version": "2.2.1",
|
||||
"description": "interface to vSphere SOAP/WSDL from node for interfacing with vCenter or ESXi, forked from node-vsphere-soap",
|
||||
"main": "lib/client.mjs",
|
||||
"author": "reedog117",
|
||||
@@ -11,7 +11,7 @@
|
||||
},
|
||||
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
|
||||
"dependencies": {
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"axios": "^1.15.0",
|
||||
"soap": "^1.0.0",
|
||||
"soap-cookie": "^0.10.1"
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"url": "https://vates.fr"
|
||||
},
|
||||
"license": "ISC",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"engines": {
|
||||
"node": ">=8.10"
|
||||
},
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
"url": "https://vates.fr"
|
||||
},
|
||||
"license": "ISC",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@vates/types",
|
||||
"private": false,
|
||||
"version": "2.5.0",
|
||||
"version": "3.1.0",
|
||||
"main": "./dist/index.mjs",
|
||||
"exports": {
|
||||
".": {
|
||||
|
||||
@@ -22,6 +22,11 @@ export const BACKUP_EXPRESSION_CONTEXT = {
|
||||
tags: { type: 'string[]' },
|
||||
power_state: { type: 'string' },
|
||||
},
|
||||
pool: {
|
||||
name_label: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
tags: { type: 'string[]' },
|
||||
},
|
||||
chainLength: { type: 'number' },
|
||||
} as const
|
||||
|
||||
@@ -33,6 +38,8 @@ export const BACKUP_SETTING_CONTEXT = {
|
||||
vmFilter: ['vm', 'run'],
|
||||
srs: ['sr', 'run'],
|
||||
remotes: ['backupRepository', 'run'],
|
||||
vms: ['vm', 'run'],
|
||||
pools: ['pool', 'run'],
|
||||
} as const
|
||||
|
||||
export type BACKUP_SETTING_CONTEXT = (typeof BACKUP_SETTING_CONTEXT)[keyof typeof BACKUP_SETTING_CONTEXT]
|
||||
|
||||
@@ -822,3 +822,16 @@ export type RPU_RECOVERY_STEP_NAME = (typeof RPU_RECOVERY_STEP_NAMES)[number]
|
||||
export const COMMON_TAG = {
|
||||
NOBAK: 'xo:no-bak',
|
||||
} as const
|
||||
|
||||
/**
|
||||
* a package of the XO appliance with another version available
|
||||
*
|
||||
* Returned by `xoa-updater` as `upgradablePackages` at the end of an update check.
|
||||
*/
|
||||
export type XoaPackageUpdate = {
|
||||
name: string
|
||||
/** version which will be installed */
|
||||
version: string
|
||||
/** undefined: the package is not installed yet */
|
||||
installedVersion?: string
|
||||
}
|
||||
|
||||
@@ -462,6 +462,7 @@ export interface Xapi {
|
||||
stream: Readable | Buffer,
|
||||
opts: { signal?: AbortSignal; format: SUPPORTED_VDI_FORMAT }
|
||||
): Promise<void>
|
||||
VDI_resize(vdiRef: XenApiVdi['$ref'], size: number): Promise<void>
|
||||
VIF_create(
|
||||
options: {
|
||||
currently_attached?: boolean
|
||||
|
||||
@@ -472,10 +472,7 @@ export type XoApp = EventEmitter & {
|
||||
getPlugin(id: XoPlugin['id']): Promise<XoPlugin>
|
||||
getPlugins(): Promise<XoPlugin[]>
|
||||
getProxy(id: XoProxy['id']): Promise<XoProxy>
|
||||
updateProxy(
|
||||
id: XoProxy['id'],
|
||||
updates: { address?: string | null; authenticationToken?: string; name?: string; vmUuid?: XoVm['id'] | null }
|
||||
): Promise<XoProxy>
|
||||
getProxyApplianceUpdaterState(id: XoProxy['id']): Promise<{ level: string; message: string; state: string }>
|
||||
getRemote(id: XoBackupRepository['id']): Promise<XoBackupRepository>
|
||||
getAllRemotes(): Promise<XoBackupRepository[]>
|
||||
removeRemote(id: XoBackupRepository['id']): Promise<void>
|
||||
@@ -507,7 +504,10 @@ export type XoApp = EventEmitter & {
|
||||
* `assertBrowserMediaInsertable` reports the predictable failures synchronously, e.g. before
|
||||
* starting a task.
|
||||
*/
|
||||
insertBrowserMedia(params: { id: XoBrowserMediaSession['id']; vmId: XoVm['id'] }): Promise<{ vdiId: XoVdi['id'] }>
|
||||
insertBrowserMedia(params: {
|
||||
id: XoBrowserMediaSession['id']
|
||||
vmId: XoVm['id']
|
||||
}): Promise<{ vdiId: XoVdi['id'] }>
|
||||
assertBrowserMediaInsertable(params: { id: XoBrowserMediaSession['id']; vmId: XoVm['id'] }): void
|
||||
/** Eject the ISO of a browser media session, release its storage, and disconnect the browser */
|
||||
ejectBrowserMedia(id: XoBrowserMediaSession['id']): Promise<void>
|
||||
|
||||
@@ -646,7 +646,7 @@ export type XoVmBackupJob = BaseXoJob & {
|
||||
proxy?: XoProxy['id']
|
||||
mode: 'full' | 'delta'
|
||||
remotes?: CMType.IdOr<XoBackupRepository['id']> | string
|
||||
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown>
|
||||
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown> | string
|
||||
srs?: CMType.IdOr<XoSr['id']> | string
|
||||
type: 'backup'
|
||||
settings: {
|
||||
@@ -663,7 +663,7 @@ export type XoMetadataBackupJobScheduleSettings = {
|
||||
}
|
||||
export type XoMetadataBackupJob = BaseXoJob & {
|
||||
type: 'metadataBackup'
|
||||
pools?: CMType.IdOr<XoPool['id']>
|
||||
pools?: CMType.IdOr<XoPool['id']> | string
|
||||
remotes: CMType.IdOr<XoBackupRepository['id']>
|
||||
settings: {
|
||||
''?: XoMetadataBackupJobGeneralSettings
|
||||
@@ -696,6 +696,7 @@ export type XoMirrorBackupJob = BaseXoJob & {
|
||||
sourceRemote: XoBackupRepository['id']
|
||||
remotes: CMType.IdOr<XoBackupRepository['id']>
|
||||
proxy?: XoProxy['id']
|
||||
filter?: { vm: { uuid: { __or: XoVm['id'][] } } } | null
|
||||
settings: {
|
||||
'': XoMirrorBackupGeneralSettings
|
||||
[scheduleId: XoSchedule['id']]: XoMirrorBackupScheduleSettings | undefined
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"main": "dist/index.mjs",
|
||||
"name": "@xen-orchestra/acl",
|
||||
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/acl",
|
||||
"version": "1.8.0",
|
||||
"version": "1.9.0",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"private": false,
|
||||
"type": "module",
|
||||
@@ -30,7 +30,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.19.0",
|
||||
"@vates/types": "^2.5.0",
|
||||
"@vates/types": "^3.1.0",
|
||||
"rimraf": "^6.0.1",
|
||||
"typescript": "~5.6",
|
||||
"typescript-eslint": "^8.61.0"
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
export default {
|
||||
read: true,
|
||||
update: {
|
||||
name: true,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"type": "git",
|
||||
"url": "https://github.com/vatesfr/xen-orchestra.git"
|
||||
},
|
||||
"version": "0.4.0",
|
||||
"version": "0.4.1",
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
@@ -17,7 +17,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@vates/decorate-with": "^2.1.0",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"golike-defer": "^0.5.1",
|
||||
"object-hash": "^2.0.1"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@xen-orchestra/autopilot-docking",
|
||||
"version": "0.0.0",
|
||||
"version": "0.1.0",
|
||||
"description": "Live ISO that prepares a VM imported from another hypervisor to boot on XCP-ng",
|
||||
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/autopilot-docking",
|
||||
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xen-orchestra/backup-archive",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"description": "Helper to handle generic backup archives",
|
||||
"license": "ISC",
|
||||
"author": "",
|
||||
@@ -21,18 +21,18 @@
|
||||
"tar-stream": "^3.1.8",
|
||||
"@types/tar-stream": "^3.1.4",
|
||||
"tmp": "^0.2.1",
|
||||
"@vates/types": "^2.5.0"
|
||||
"@vates/types": "^3.1.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@xen-orchestra/log": "^0.7.1",
|
||||
"@xen-orchestra/fs": "^4.10.0",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"@xen-orchestra/fs": "^4.11.0",
|
||||
"@xen-orchestra/disk-transform": "^1.3.4",
|
||||
"@vates/task": "0.7.0",
|
||||
"golike-defer": "0.5.1",
|
||||
"uuid": "^9.0.0",
|
||||
"promise-toolbox": "^0.21.0",
|
||||
"@vates/async-each": "^1.0.1",
|
||||
"vhd-lib": "^4.17.0"
|
||||
"vhd-lib": "^4.17.1"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "yarn run clean && tsc",
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@xen-orchestra/async-map": "^0.1.5",
|
||||
"@xen-orchestra/backups": "^0.78.0",
|
||||
"@xen-orchestra/fs": "^4.10.0",
|
||||
"@xen-orchestra/backups": "^1.0.1",
|
||||
"@xen-orchestra/fs": "^4.11.0",
|
||||
"filenamify": "^6.0.0",
|
||||
"getopts": "^2.2.5",
|
||||
"lodash": "^4.18.0",
|
||||
@@ -28,7 +28,7 @@
|
||||
"scripts": {
|
||||
"postversion": "npm publish --access public"
|
||||
},
|
||||
"version": "1.1.18",
|
||||
"version": "1.1.19",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"author": {
|
||||
"name": "Vates SAS",
|
||||
|
||||
@@ -9,6 +9,7 @@ const { warn } = createLogger('xo:backups:buildContext')
|
||||
/**
|
||||
* @typedef {import('@vates/types/xen-api').XenApiVm} XenApiVm
|
||||
* @typedef {import('@vates/types/xo').XoSr} XoSr
|
||||
* @typedef {import('@vates/types/xo').XoPool} XoPool
|
||||
* @typedef {import('@vates/types/xo').XoBackupRepository} XoBackupRepository
|
||||
*
|
||||
* @typedef {object} RunContext
|
||||
@@ -30,6 +31,10 @@ const { warn } = createLogger('xo:backups:buildContext')
|
||||
* @typedef {object} BackupRepositoryContext
|
||||
* @property {{name: string, type: string | undefined, tags: string[]}} backupRepository
|
||||
* @property {RunContext} run
|
||||
*
|
||||
* @typedef {object} PoolContext
|
||||
* @property {{name_label: string, description: string, tags: string[]}} pool
|
||||
* @property {RunContext} run
|
||||
*/
|
||||
|
||||
/**
|
||||
@@ -109,3 +114,19 @@ export function buildBackupRepositoryContext(backupRepository, run) {
|
||||
run,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {XoPool} pool
|
||||
* @param {RunContext} run
|
||||
* @returns {PoolContext}
|
||||
*/
|
||||
export function buildPoolContext(pool, run) {
|
||||
return {
|
||||
pool: {
|
||||
name_label: pool.name_label,
|
||||
description: pool.name_description,
|
||||
tags: Array.isArray(pool.tags) ? pool.tags : [],
|
||||
},
|
||||
run,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import { buildRunContext, buildVmContext, buildSrContext, buildBackupRepositoryContext } from './_buildContext.mjs'
|
||||
import {
|
||||
buildRunContext,
|
||||
buildVmContext,
|
||||
buildSrContext,
|
||||
buildBackupRepositoryContext,
|
||||
buildPoolContext,
|
||||
} from './_buildContext.mjs'
|
||||
import { BACKUP_EXPRESSION_CONTEXT } from '@vates/types/backup-expression-context'
|
||||
|
||||
describe('buildContext', () => {
|
||||
@@ -144,4 +150,39 @@ describe('buildContext', () => {
|
||||
Object.keys(BACKUP_EXPRESSION_CONTEXT.backupRepository).sort()
|
||||
)
|
||||
})
|
||||
|
||||
it('buildPoolContext', () => {
|
||||
const pool1 = {
|
||||
name_label: 'name_label',
|
||||
name_description: 'description',
|
||||
ignored: 'ignored',
|
||||
}
|
||||
const poolContext1 = buildPoolContext(pool1, runContext)
|
||||
assert.deepEqual(poolContext1, {
|
||||
pool: {
|
||||
name_label: 'name_label',
|
||||
description: 'description',
|
||||
tags: [],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
})
|
||||
assert.deepEqual(Object.keys(poolContext1.pool).sort(), Object.keys(BACKUP_EXPRESSION_CONTEXT.pool).sort())
|
||||
|
||||
const pool2 = {
|
||||
name_label: 'name_label',
|
||||
name_description: 'description',
|
||||
tags: ['tag'],
|
||||
ignored: 'ignored',
|
||||
}
|
||||
const poolContext2 = buildPoolContext(pool2, runContext)
|
||||
assert.deepEqual(poolContext2, {
|
||||
pool: {
|
||||
name_label: 'name_label',
|
||||
description: 'description',
|
||||
tags: ['tag'],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
})
|
||||
assert.deepEqual(Object.keys(poolContext2.pool).sort(), Object.keys(BACKUP_EXPRESSION_CONTEXT.pool).sort())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -83,6 +83,7 @@ const main = Disposable.wrap(async function* main(args) {
|
||||
handler.unlink(taskFile).catch(error => warn('deleting task failure', { error }))
|
||||
} catch (error) {
|
||||
warn('failure handling task', { error })
|
||||
if (error.code === 'ELOCKED') await new Promise(resolve => setTimeout(resolve, 5 * 60e3))
|
||||
}
|
||||
},
|
||||
{ concurrency }
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
"type": "git",
|
||||
"url": "https://github.com/vatesfr/xen-orchestra.git"
|
||||
},
|
||||
"version": "0.78.0",
|
||||
"version": "1.0.1",
|
||||
"engines": {
|
||||
"node": ">=22.19"
|
||||
},
|
||||
@@ -24,20 +24,20 @@
|
||||
"@vates/cached-dns.lookup": "^1.0.0",
|
||||
"@vates/compose": "^2.1.0",
|
||||
"@vates/decorate-with": "^2.1.0",
|
||||
"@vates/disposable": "^0.1.6",
|
||||
"@vates/fuse-vhd": "^2.1.3",
|
||||
"@vates/disposable": "^0.1.7",
|
||||
"@vates/fuse-vhd": "^2.1.4",
|
||||
"@vates/generator-toolbox": "^1.1.3",
|
||||
"@vates/nbd-client": "^3.7.0",
|
||||
"@vates/nbd-client": "^3.7.2",
|
||||
"@vates/parse-duration": "^0.1.1",
|
||||
"@vates/task": "^0.7.0",
|
||||
"@vates/types": "^2.5.0",
|
||||
"@vates/types": "^3.1.0",
|
||||
"@xen-orchestra/async-map": "^0.1.5",
|
||||
"@xen-orchestra/disk-transform": "^1.3.4",
|
||||
"@xen-orchestra/fs": "^4.10.0",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/fs": "^4.11.0",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"@xen-orchestra/qcow2": "^1.4.1",
|
||||
"@xen-orchestra/template": "^0.1.1",
|
||||
"@xen-orchestra/backup-archive": "^1.2.0",
|
||||
"@xen-orchestra/backup-archive": "^1.2.1",
|
||||
"app-conf": "^3.0.0",
|
||||
"compare-versions": "^6.0.0",
|
||||
"complex-matcher": "^1.1.1",
|
||||
@@ -56,8 +56,8 @@
|
||||
"tar": "^7.5.19",
|
||||
"uuid": "^9.0.0",
|
||||
"value-matcher": "^0.2.0",
|
||||
"vhd-lib": "^4.17.0",
|
||||
"xen-api": "^5.1.0",
|
||||
"vhd-lib": "^4.17.1",
|
||||
"xen-api": "^6.0.0",
|
||||
"xo-common": "^0.11.0",
|
||||
"xo-remote-parser": "^2.0.0",
|
||||
"yazl": "^2.5.1"
|
||||
@@ -70,7 +70,7 @@
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@xen-orchestra/xapi": "^9.1.0"
|
||||
"@xen-orchestra/xapi": "^10.0.0"
|
||||
},
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"author": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": false,
|
||||
"name": "@xen-orchestra/cr-seed-cli",
|
||||
"version": "1.0.3",
|
||||
"version": "1.0.4",
|
||||
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/cr-seed-cli",
|
||||
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
|
||||
"repository": {
|
||||
@@ -18,7 +18,7 @@
|
||||
"preferGlobal": true,
|
||||
"dependencies": {
|
||||
"golike-defer": "^0.5.1",
|
||||
"xen-api": "^5.1.0"
|
||||
"xen-api": "^6.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"postversion": "npm publish"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": false,
|
||||
"name": "@xen-orchestra/disk-cli",
|
||||
"version": "2.2.5",
|
||||
"version": "2.2.6",
|
||||
"description": "CLI tool to inspect and manage disks in backup repositories",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
@@ -20,13 +20,13 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@xen-orchestra/backups": "^0.78.0",
|
||||
"@xen-orchestra/backup-archive": "^1.2.0",
|
||||
"@xen-orchestra/backups": "^1.0.1",
|
||||
"@xen-orchestra/backup-archive": "^1.2.1",
|
||||
"@xen-orchestra/disk-transform": "^1.3.4",
|
||||
"@xen-orchestra/fs": "^4.10.0",
|
||||
"@xen-orchestra/fs": "^4.11.0",
|
||||
"@xen-orchestra/qcow2": "^1.4.1",
|
||||
"promise-toolbox": "^0.21.0",
|
||||
"vhd-lib": "^4.17.0"
|
||||
"vhd-lib": "^4.17.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.3.0",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": false,
|
||||
"name": "@xen-orchestra/fs",
|
||||
"version": "4.10.0",
|
||||
"version": "4.11.0",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"description": "The File System for Xen Orchestra backups.",
|
||||
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/fs",
|
||||
@@ -30,7 +30,7 @@
|
||||
"@vates/coalesce-calls": "^0.1.0",
|
||||
"@vates/decorate-with": "^2.1.0",
|
||||
"@vates/read-chunk": "^1.2.1",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"bind-property-descriptor": "^2.0.0",
|
||||
"decorator-synchronized": "^0.6.0",
|
||||
"execa": "^5.0.0",
|
||||
|
||||
@@ -16,14 +16,14 @@
|
||||
"xo-immutable-remote": "./dist/protectRemotes.mjs"
|
||||
},
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"version": "3.0.9",
|
||||
"version": "3.0.10",
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@xen-orchestra/backups": "^0.78.0",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/backups": "^1.0.1",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"app-conf": "^3.0.0",
|
||||
"execa": "^5.0.0",
|
||||
"ms": "^2.1.3"
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
## **next**
|
||||
|
||||
- [VDIs] The used space of a VDI now includes its whole snapshot chain instead of only its last layer, which showed almost 0% for disks with snapshots. It is shown as a size, without usage bar or free space (PR [#10116](https://github.com/vatesfr/xen-orchestra/pull/10116))
|
||||
- [Web-Core/UiCircleProgressBar] Add a brand accent and an option to hide the value (PR [#10849](https://github.com/vatesfr/xen-orchestra/pull/10849))
|
||||
- [Tables] Cells fit on one line: long names are cut in the middle, extra tags go under "+N" and long texts end with "…" (PR [#10850](https://github.com/vatesfr/xen-orchestra/pull/10850))
|
||||
- [Pages] The page header and tabs now stay in place on every page: dashboards, System tabs, consoles, tasks, settings and creation forms scroll under them instead of scrolling with them (PR [#10822](https://github.com/vatesfr/xen-orchestra/pull/10822))
|
||||
@@ -16,6 +17,8 @@
|
||||
- [Side panels] Fix the double scrollbar when the side panel content is taller than the screen: the page header now stays in place, and the list and the side panel each scroll on their own. All scrollbars are now thin, like the side panel one (PR [#10807](https://github.com/vatesfr/xen-orchestra/pull/10807))
|
||||
- [Mobile] Searchable dropdown lists no longer overflow the screen (PR [#10854](https://github.com/vatesfr/xen-orchestra/pull/10854))
|
||||
- [New/VM] Fix the storage table overflowing horizontally, which hid part of the delete button (PR [#10851](https://github.com/vatesfr/xen-orchestra/pull/10851))
|
||||
- [New/VM] Fix template disk settings being applied to every disk of the new VM: each disk now keeps its own name, description and SR (PR [#10898](https://github.com/vatesfr/xen-orchestra/pull/10898))
|
||||
- [VM/System] Display the default 4 MiB video RAM for HVM VMs that don't define it, as XO 6 does (PR [#10901](https://github.com/vatesfr/xen-orchestra/pull/10901))
|
||||
|
||||
## **0.27.0** (2026-10-29)
|
||||
|
||||
|
||||
@@ -27,13 +27,13 @@
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/node": "^18.19.80",
|
||||
"@vates/types": "^2.5.0",
|
||||
"@vates/types": "^3.1.0",
|
||||
"@vitejs/plugin-vue": "^6.0.0",
|
||||
"@vue/tsconfig": "^0.9.0",
|
||||
"@vueuse/core": "^14.0.0",
|
||||
"@vueuse/math": "^14.0.0",
|
||||
"@vueuse/shared": "^14.0.0",
|
||||
"@xen-orchestra/web-core": "^0.65.0",
|
||||
"@xen-orchestra/web-core": "^0.66.1",
|
||||
"complex-matcher": "^1.1.1",
|
||||
"d3-time-format": "^4.1.0",
|
||||
"decorator-synchronized": "^0.6.0",
|
||||
|
||||
@@ -42,7 +42,7 @@ const progress = computed(() => {
|
||||
.progress-circle-fill {
|
||||
animation: progress 1s ease-out forwards;
|
||||
fill: none;
|
||||
stroke: var(--color-success-item-base);
|
||||
stroke: var(--color-success-data);
|
||||
stroke-width: 1.2;
|
||||
stroke-linecap: round;
|
||||
stroke-dasharray: v-bind(progress), 100;
|
||||
|
||||
@@ -68,11 +68,11 @@ const hasError = computed(() => hostStoreHasError.value || vmStoreHasError.value
|
||||
<style lang="postcss" scoped>
|
||||
.progress-item {
|
||||
--progress-bar-height: 1.2rem;
|
||||
--progress-bar-color: var(--color-brand-item-base);
|
||||
--progress-bar-color: var(--color-brand-data);
|
||||
--progress-bar-background-color: var(--color-neutral-background-disabled);
|
||||
|
||||
&.warning {
|
||||
--progress-bar-color: var(--color-warning-item-base);
|
||||
--progress-bar-color: var(--color-warning-data);
|
||||
--footer-value-color: var(--color-warning-item-base);
|
||||
}
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ const inactive = computed(() => props.total - props.active)
|
||||
width: 1.3rem;
|
||||
height: 1.3rem;
|
||||
border-radius: 0.65rem;
|
||||
background-color: var(--color-success-item-base);
|
||||
background-color: var(--color-success-data);
|
||||
|
||||
&.inactive {
|
||||
background-color: var(--color-neutral-background-disabled);
|
||||
|
||||
@@ -143,7 +143,7 @@ const state = useTableState({
|
||||
})
|
||||
|
||||
const { HeadCells, BodyCells } = useVmColumns({
|
||||
exclude: ['actions', 'checkbox'],
|
||||
exclude: ['actions', 'checkbox', 'lastBackupDate'],
|
||||
body: (vm: XenApiVm) => {
|
||||
const guestMetrics = computed(() => getGuestMetrics(vm.guest_metrics))
|
||||
const vmMetrics = computed(() => getVmMetrics(vm.metrics))
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { getHostIcon } from '@/modules/host/utils/host.util.ts'
|
||||
import { useVmUtils } from '@/modules/vm/composables/vm-utils.composable.ts'
|
||||
import { getVmDomainType } from '@/modules/vm/utils/vm.util.ts'
|
||||
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
|
||||
@@ -133,16 +134,7 @@ const ram = computed(() => formatSizeRaw(vm.memory_dynamic_max, 0))
|
||||
|
||||
const osVersion = computed(() => guestMetrics.value?.os_version.name)
|
||||
|
||||
const domainType = computed(() => {
|
||||
if (
|
||||
vm.domain_type !== undefined && // XS < 7.5
|
||||
vm.domain_type !== 'unspecified' // detection failed
|
||||
) {
|
||||
return vm.domain_type
|
||||
}
|
||||
|
||||
return vm.HVM_boot_policy === '' ? 'pv' : 'hvm'
|
||||
})
|
||||
const domainType = computed(() => getVmDomainType(vm))
|
||||
|
||||
const virtualizationType = computed(() =>
|
||||
domainType.value === 'hvm' && guestMetrics.value?.PV_drivers_detected ? 'pvhvm' : domainType.value
|
||||
|
||||
@@ -10,8 +10,8 @@
|
||||
</template>
|
||||
</VtsTabularKeyValueRow>
|
||||
<VtsTabularKeyValueRow :label="t('video-ram')">
|
||||
<template v-if="vm.platform.videoram" #value>
|
||||
{{ `${vm.platform.videoram} ${t('bytes:mi')}` }}
|
||||
<template v-if="videoRam" #value>
|
||||
{{ `${videoRam} ${t('bytes:mi')}` }}
|
||||
</template>
|
||||
</VtsTabularKeyValueRow>
|
||||
</VtsTabularKeyValueList>
|
||||
@@ -20,14 +20,18 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { getVmDomainType } from '@/modules/vm/utils/vm.util.ts'
|
||||
import VtsStatus from '@core/components/status/VtsStatus.vue'
|
||||
import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsTabularKeyValueList.vue'
|
||||
import VtsTabularKeyValueRow from '@core/components/tabular-key-value-row/VtsTabularKeyValueRow.vue'
|
||||
import UiCard from '@core/components/ui/card/UiCard.vue'
|
||||
import UiTitle from '@core/components/ui/title/UiTitle.vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
defineProps<{ vm: XenApiVm }>()
|
||||
const { vm } = defineProps<{ vm: XenApiVm }>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const videoRam = computed(() => (getVmDomainType(vm) === 'hvm' ? Number(vm.platform.videoram ?? 4) : undefined))
|
||||
</script>
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { getVmDomainType } from '@/modules/vm/utils/vm.util.ts'
|
||||
import { useHostStore } from '@/stores/xen-api/host.store.ts'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import { useVtpmStore } from '@/stores/xen-api/vtpm.store.ts'
|
||||
@@ -55,16 +56,7 @@ const { pool } = usePoolStore().subscribe()
|
||||
const { getByOpaqueRef: getHostOpaqueRef } = useHostStore().subscribe()
|
||||
const { getByOpaqueRef: getVtpmOpaqueRef } = useVtpmStore().subscribe()
|
||||
|
||||
/**
|
||||
* @see `packages/xo-server/src/xapi/utils.mjs`:57
|
||||
**/
|
||||
const virtualizationMode = computed(() =>
|
||||
vm.domain_type !== undefined && vm.domain_type !== 'unspecified'
|
||||
? vm.domain_type
|
||||
: vm.HVM_boot_policy === ''
|
||||
? 'pv'
|
||||
: 'hvm'
|
||||
)
|
||||
const virtualizationMode = computed(() => getVmDomainType(vm))
|
||||
|
||||
const isNestedVirtualizationEnabled = computed(() => {
|
||||
const poolMaster = pool.value !== undefined ? getHostOpaqueRef(pool.value.master) : undefined
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiVbd, XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { getVdiFormat, getVdiIcon } from '@/modules/vdi/utils/vdi.util.ts'
|
||||
import { useVdiStore } from '@/stores/xen-api/vdi.store.ts'
|
||||
import VtsRow from '@core/components/table/VtsRow.vue'
|
||||
import VtsTable from '@core/components/table/VtsTable.vue'
|
||||
import UiQuerySearchBar from '@core/components/ui/query-search-bar/UiQuerySearchBar.vue'
|
||||
@@ -43,6 +44,7 @@ const { vdis, vbds, busy, error } = defineProps<{
|
||||
error?: boolean
|
||||
}>()
|
||||
const { t } = useI18n()
|
||||
const { getChainPhysicalUsage } = useVdiStore().subscribe()
|
||||
const selectedVdiId = useRouteQuery('id')
|
||||
const { items: filteredVdis, searchBindings } = useSearchFilter(() => vdis)
|
||||
const state = useTableState({
|
||||
@@ -56,6 +58,7 @@ const { HeadCells, BodyCells } = useVdiColumns({
|
||||
exclude: ['actions'],
|
||||
body: (vdi: XenApiVdi) => {
|
||||
const vdiVbds = computed(() => vbds.filter(vbd => vbd.VDI === vdi.$ref))
|
||||
const usedSpace = computed(() => formatSizeRaw(getChainPhysicalUsage(vdi), 2))
|
||||
const size = computed(() => formatSizeRaw(vdi.virtual_size, 2))
|
||||
const format = computed(() => getVdiFormat(vdi.sm_config['image-format']))
|
||||
return {
|
||||
@@ -65,7 +68,7 @@ const { HeadCells, BodyCells } = useVdiColumns({
|
||||
icon: getVdiIcon(vdiVbds.value),
|
||||
}),
|
||||
description: r => r(vdi.name_description),
|
||||
usedSpace: r => r(vdi.physical_utilisation, vdi.virtual_size),
|
||||
usedSpace: r => r(usedSpace.value.value, usedSpace.value.prefix),
|
||||
size: r => r(size.value.value, size.value.prefix),
|
||||
format: r => r(format.value),
|
||||
selectItem: r => r(() => (selectedVdiId.value = vdi.uuid)),
|
||||
|
||||
@@ -1,12 +1,48 @@
|
||||
<template>
|
||||
<VtsSpaceCard :used="vdi.physical_utilisation" :total="vdi.virtual_size" :label="vdi.name_label" />
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle size="medium" :label="t('space')" />
|
||||
<VtsCardRowList>
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>{{ t('used-space') }}</template>
|
||||
<template #value>{{ usedSpace }}</template>
|
||||
<template v-if="chainPhysicalUsage > 0" #addons>
|
||||
<VtsCopyButton :value="usedSpace" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>{{ t('size') }}</template>
|
||||
<template #value>{{ size }}</template>
|
||||
<template v-if="vdi.virtual_size > 0" #addons>
|
||||
<VtsCopyButton :value="size" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import VtsSpaceCard from '@core/components/space-card/VtsSpaceCard.vue'
|
||||
import { useVdiStore } from '@/stores/xen-api/vdi.store.ts'
|
||||
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
|
||||
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
|
||||
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
|
||||
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
|
||||
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
|
||||
import { formatSize } from '@core/utils/size.util.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
defineProps<{
|
||||
const { vdi } = defineProps<{
|
||||
vdi: XenApiVdi
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { getChainPhysicalUsage } = useVdiStore().subscribe()
|
||||
|
||||
const chainPhysicalUsage = computed(() => getChainPhysicalUsage(vdi))
|
||||
|
||||
const usedSpace = computed(() => formatSize(chainPhysicalUsage.value, 2))
|
||||
|
||||
const size = computed(() => formatSize(vdi.virtual_size, 2))
|
||||
</script>
|
||||
|
||||
@@ -43,6 +43,20 @@ export function areVmToolsDetected(guestMetrics: XenApiVmGuestMetrics | undefine
|
||||
return managementAgentDetected && pvDriversDetected
|
||||
}
|
||||
|
||||
/**
|
||||
* @see `packages/xo-server/src/xapi/utils.mjs`:57
|
||||
**/
|
||||
export function getVmDomainType(vm: XenApiVm) {
|
||||
if (
|
||||
vm.domain_type !== undefined && // XS < 7.5
|
||||
vm.domain_type !== 'unspecified' // detection failed
|
||||
) {
|
||||
return vm.domain_type
|
||||
}
|
||||
|
||||
return vm.HVM_boot_policy === '' ? 'pv' : 'hvm'
|
||||
}
|
||||
|
||||
export type VmPowerStateAction =
|
||||
| 'start'
|
||||
| 'pause'
|
||||
|
||||
@@ -512,6 +512,7 @@ const getExistingVdis = (template: XenApiVm) => {
|
||||
|
||||
acc.push({
|
||||
id: vdi.$ref,
|
||||
userdevice: vbd.userdevice,
|
||||
name_label: vdi.name_label,
|
||||
name_description: vdi.name_description,
|
||||
size: bytesToGiB(vdi.virtual_size),
|
||||
@@ -698,6 +699,7 @@ const _createVm = defer(async ($defer: Defer) => {
|
||||
const vdiRef = await xapi.getField<XenApiVdi['$ref']>('VBD', vbdRef, 'VDI')
|
||||
const type = await xapi.getField<VBD_TYPE>('VBD', vbdRef, 'type')
|
||||
const bootable = await xapi.getField<boolean>('VBD', vbdRef, 'bootable')
|
||||
const userdevice = await xapi.getField<XenApiVbd['userdevice']>('VBD', vbdRef, 'userdevice')
|
||||
|
||||
if (!hasBootableDisk) {
|
||||
hasBootableDisk = bootable
|
||||
@@ -707,45 +709,49 @@ const _createVm = defer(async ($defer: Defer) => {
|
||||
continue
|
||||
}
|
||||
|
||||
for (const vdi of existingVdis) {
|
||||
const srRef = await xapi.getField<XenApiSr['$ref']>('VDI', vdiRef, 'SR')
|
||||
const vbdRefs = await xapi.getField<XenApiVbd['$ref'][]>('VDI', vdiRef, 'VBDs')
|
||||
const vdi = existingVdis.find(vdi => vdi.userdevice === userdevice)
|
||||
|
||||
await xapi.vdi.setNameLabel(vdiRef, vdi.name_label)
|
||||
await xapi.vdi.setNameDescription(vdiRef, vdi.name_description)
|
||||
if (vdi === undefined) {
|
||||
continue
|
||||
}
|
||||
|
||||
// EDIT SR: Migrate VDI or create new one
|
||||
if (vdi.SR !== srRef) {
|
||||
try {
|
||||
await xapi.vdi.poolMigrate(vdiRef, vdi.SR)
|
||||
} catch (error) {
|
||||
if (!(error instanceof Error)) {
|
||||
throw error
|
||||
}
|
||||
const srRef = await xapi.getField<XenApiSr['$ref']>('VDI', vdiRef, 'SR')
|
||||
const vbdRefs = await xapi.getField<XenApiVbd['$ref'][]>('VDI', vdiRef, 'VBDs')
|
||||
|
||||
const { message } = error
|
||||
await xapi.vdi.setNameLabel(vdiRef, vdi.name_label)
|
||||
await xapi.vdi.setNameDescription(vdiRef, vdi.name_description)
|
||||
|
||||
if (
|
||||
message !== 'NO_HOSTS_AVAILABLE' &&
|
||||
message !== 'LICENCE_RESTRICTION' &&
|
||||
message !== 'VDI_NEEDS_VM_FOR_MIGRATE'
|
||||
) {
|
||||
throw error
|
||||
}
|
||||
|
||||
const newVdiRef = await xapi.vdi.copy(vdiRef, vdi.SR)
|
||||
|
||||
if (vbdRefs) {
|
||||
for (const vbdRef of vbdRefs) {
|
||||
const vbd = await xapi.getField<XenApiVbd>('VBD', vbdRef, 'record')
|
||||
|
||||
await xapi.vbd.delete(vbdRef)
|
||||
await xapi.vbd.create({ ...vbd, vmRefs, vdiRef: newVdiRef[0] })
|
||||
}
|
||||
}
|
||||
|
||||
await xapi.vdi.delete(vdiRef)
|
||||
// EDIT SR: Migrate VDI or create new one
|
||||
if (vdi.SR !== srRef) {
|
||||
try {
|
||||
await xapi.vdi.poolMigrate(vdiRef, vdi.SR)
|
||||
} catch (error) {
|
||||
if (!(error instanceof Error)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
const { message } = error
|
||||
|
||||
if (
|
||||
message !== 'NO_HOSTS_AVAILABLE' &&
|
||||
message !== 'LICENCE_RESTRICTION' &&
|
||||
message !== 'VDI_NEEDS_VM_FOR_MIGRATE'
|
||||
) {
|
||||
throw error
|
||||
}
|
||||
|
||||
const newVdiRef = await xapi.vdi.copy(vdiRef, vdi.SR)
|
||||
|
||||
if (vbdRefs) {
|
||||
for (const vbdRef of vbdRefs) {
|
||||
const vbd = await xapi.getField<XenApiVbd>('VBD', vbdRef, 'record')
|
||||
|
||||
await xapi.vbd.delete(vbdRef)
|
||||
await xapi.vbd.create({ ...vbd, vmRefs, vdiRef: newVdiRef[0] })
|
||||
}
|
||||
}
|
||||
|
||||
await xapi.vdi.delete(vdiRef)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
117
@xen-orchestra/lite/src/route-map.d.ts
vendored
117
@xen-orchestra/lite/src/route-map.d.ts
vendored
@@ -653,6 +653,13 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/task/vts-task-list': RouteRecordInfo<
|
||||
'/story/web-core/task/vts-task-list',
|
||||
'/story/web-core/task/vts-task-list',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/tree/vts-tree-item': RouteRecordInfo<
|
||||
'/story/web-core/tree/vts-tree-item',
|
||||
'/story/web-core/tree/vts-tree-item',
|
||||
@@ -884,6 +891,13 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/group-subcategory/ui-group-subcategory': RouteRecordInfo<
|
||||
'/story/web-core/ui/group-subcategory/ui-group-subcategory',
|
||||
'/story/web-core/ui/group-subcategory/ui-group-subcategory',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/head-bar/ui-head-bar': RouteRecordInfo<
|
||||
'/story/web-core/ui/head-bar/ui-head-bar',
|
||||
'/story/web-core/ui/head-bar/ui-head-bar',
|
||||
@@ -891,6 +905,13 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/image-radio-button/ui-image-radio-button': RouteRecordInfo<
|
||||
'/story/web-core/ui/image-radio-button/ui-image-radio-button',
|
||||
'/story/web-core/ui/image-radio-button/ui-image-radio-button',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/info/ui-info': RouteRecordInfo<
|
||||
'/story/web-core/ui/info/ui-info',
|
||||
'/story/web-core/ui/info/ui-info',
|
||||
@@ -1045,6 +1066,20 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/rich-checkbox/ui-rich-checkbox': RouteRecordInfo<
|
||||
'/story/web-core/ui/rich-checkbox/ui-rich-checkbox',
|
||||
'/story/web-core/ui/rich-checkbox/ui-rich-checkbox',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group': RouteRecordInfo<
|
||||
'/story/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group',
|
||||
'/story/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/rich-radio-button/ui-rich-radio-button': RouteRecordInfo<
|
||||
'/story/web-core/ui/rich-radio-button/ui-rich-radio-button',
|
||||
'/story/web-core/ui/rich-radio-button/ui-rich-radio-button',
|
||||
@@ -1052,6 +1087,13 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group': RouteRecordInfo<
|
||||
'/story/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group',
|
||||
'/story/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/stacked-bar/ui-stacked-bar': RouteRecordInfo<
|
||||
'/story/web-core/ui/stacked-bar/ui-stacked-bar',
|
||||
'/story/web-core/ui/stacked-bar/ui-stacked-bar',
|
||||
@@ -1108,6 +1150,13 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/tag/ui-label-value-tag': RouteRecordInfo<
|
||||
'/story/web-core/ui/tag/ui-label-value-tag',
|
||||
'/story/web-core/ui/tag/ui-label-value-tag',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/tag/ui-tag': RouteRecordInfo<
|
||||
'/story/web-core/ui/tag/ui-tag',
|
||||
'/story/web-core/ui/tag/ui-tag',
|
||||
@@ -1122,13 +1171,6 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/tag/ui-tertiary-tag': RouteRecordInfo<
|
||||
'/story/web-core/ui/tag/ui-tertiary-tag',
|
||||
'/story/web-core/ui/tag/ui-tertiary-tag',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/task-item/ui-task-item': RouteRecordInfo<
|
||||
'/story/web-core/ui/task-item/ui-task-item',
|
||||
'/story/web-core/ui/task-item/ui-task-item',
|
||||
@@ -1136,13 +1178,6 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/task-list/ui-task-list': RouteRecordInfo<
|
||||
'/story/web-core/ui/task-list/ui-task-list',
|
||||
'/story/web-core/ui/task-list/ui-task-list',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/title/ui-title': RouteRecordInfo<
|
||||
'/story/web-core/ui/title/ui-title',
|
||||
'/story/web-core/ui/title/ui-title',
|
||||
@@ -1834,6 +1869,12 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/task/vts-task-list.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/task/vts-task-list'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/tree/vts-tree-item.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/tree/vts-tree-item'
|
||||
@@ -2032,12 +2073,24 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/group-subcategory/ui-group-subcategory.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/group-subcategory/ui-group-subcategory'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/head-bar/ui-head-bar.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/head-bar/ui-head-bar'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/image-radio-button/ui-image-radio-button.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/image-radio-button/ui-image-radio-button'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/info/ui-info.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/info/ui-info'
|
||||
@@ -2170,12 +2223,30 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/rich-checkbox/ui-rich-checkbox.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/rich-checkbox/ui-rich-checkbox'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/rich-radio-button/ui-rich-radio-button.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/rich-radio-button/ui-rich-radio-button'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/stacked-bar/ui-stacked-bar.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/stacked-bar/ui-stacked-bar'
|
||||
@@ -2224,6 +2295,12 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/tag/ui-label-value-tag.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/tag/ui-label-value-tag'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/tag/ui-tag.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/tag/ui-tag'
|
||||
@@ -2236,24 +2313,12 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/tag/ui-tertiary-tag.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/tag/ui-tertiary-tag'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/task-item/ui-task-item.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/task-item/ui-task-item'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/task-list/ui-task-list.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/task-list/ui-task-list'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/title/ui-title.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/title/ui-title'
|
||||
|
||||
@@ -1,9 +1,37 @@
|
||||
import type { XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { createXapiStoreConfig } from '@/stores/xen-api/create-xapi-store-config.ts'
|
||||
import { createSubscribableStoreContext } from '@core/utils/create-subscribable-store-context.util.ts'
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
export const useVdiStore = defineStore('xen-api-vdi', () => {
|
||||
const config = createXapiStoreConfig('vdi')
|
||||
const { context: baseContext, ...configRest } = createXapiStoreConfig('vdi')
|
||||
|
||||
return createSubscribableStoreContext(config, {})
|
||||
const getChainPhysicalUsage = (vdi: XenApiVdi) => {
|
||||
if (vdi.is_a_snapshot || !vdi.managed) {
|
||||
return vdi.physical_utilisation
|
||||
}
|
||||
|
||||
let total = vdi.physical_utilisation
|
||||
let parentUuid = vdi.sm_config['vhd-parent'] as XenApiVdi['uuid'] | undefined
|
||||
|
||||
while (parentUuid !== undefined) {
|
||||
const parent = baseContext.getByUuid(parentUuid)
|
||||
|
||||
if (parent === undefined) {
|
||||
break
|
||||
}
|
||||
|
||||
total += parent.physical_utilisation
|
||||
parentUuid = parent.sm_config['vhd-parent'] as XenApiVdi['uuid'] | undefined
|
||||
}
|
||||
|
||||
return total
|
||||
}
|
||||
|
||||
const context = {
|
||||
...baseContext,
|
||||
getChainPhysicalUsage,
|
||||
}
|
||||
|
||||
return createSubscribableStoreContext({ context, ...configRest }, {})
|
||||
})
|
||||
|
||||
@@ -2,36 +2,32 @@
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
prop('accent').required().enum('neutral', 'warning', 'danger').preset('neutral').widget(),
|
||||
prop('options').required().arr('FormOption<TEntry, TValue>').widget().preset(options),
|
||||
prop('selectedLabel').str(),
|
||||
prop('required').bool().widget(),
|
||||
prop('placeholder').str().widget().preset('Choose colors'),
|
||||
prop('searchPlaceholder').str().widget().preset('Search colors'),
|
||||
prop('loading').bool().widget(),
|
||||
model('search'),
|
||||
prop('accent').required().enum('neutral', 'success', 'warning', 'danger').preset('neutral').widget(),
|
||||
prop('id').required().obj('FormSelectId').preset(id),
|
||||
slot(),
|
||||
]"
|
||||
>
|
||||
<VtsSelect v-bind="properties" v-model:search="searchTerm" :selected-label />
|
||||
<VtsSelect v-bind="properties" />
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { model, prop, slot } from '@/libs/story/story-param.ts'
|
||||
import { prop, slot } from '@/libs/story/story-param.ts'
|
||||
import VtsSelect from '@core/components/select/VtsSelect.vue'
|
||||
import { useFormSelect } from '@core/packages/form-select'
|
||||
import { upperFirst } from 'lodash-es'
|
||||
|
||||
const colors = ['blue', 'yellow', 'red', 'green', 'orange', 'purple', 'white', 'grey', 'black']
|
||||
|
||||
const { options, searchTerm, selectedLabel } = useFormSelect(colors, {
|
||||
properties: color => ({
|
||||
value: color,
|
||||
label: `${upperFirst(color)} color`,
|
||||
disabled: color === 'blue' || color === 'orange' || color === 'black',
|
||||
}),
|
||||
const { id } = useFormSelect(colors, {
|
||||
option: {
|
||||
label: color => `${upperFirst(color)} color`,
|
||||
disabled: color => color === 'blue' || color === 'orange' || color === 'black',
|
||||
},
|
||||
multiple: true,
|
||||
searchable: true,
|
||||
placeholder: 'Choose colors',
|
||||
searchPlaceholder: 'Search colors',
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
prop('tasks').type('Task[]').required().preset(allTasks),
|
||||
prop('selectedTaskId').str().widget(),
|
||||
prop('showEyeIcon').bool().widget(),
|
||||
prop('autoCollapseCompleted').bool().widget(),
|
||||
prop('expandAll')
|
||||
.bool()
|
||||
.widget()
|
||||
.help('Shows every task expanded; turning it off restores the tasks expanded before'),
|
||||
prop('unreadTaskIds').type('ReadonlySet<string>').help('Shows an unread dot column, with a dot for these tasks'),
|
||||
event('select').args({ id: 'string' }),
|
||||
]"
|
||||
:presets="{
|
||||
'Unread tasks': {
|
||||
props: {
|
||||
unreadTaskIds: new Set(['1', '1-2', '4', '9', '9-2', '9-2-1']),
|
||||
},
|
||||
},
|
||||
}"
|
||||
>
|
||||
<VtsTaskList v-bind="properties" />
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, prop } from '@/libs/story/story-param.ts'
|
||||
import { allTasks } from '@/stories/web-core/ui/task-item/mock-tasks.ts'
|
||||
import VtsTaskList from '@core/components/task/VtsTaskList.vue'
|
||||
</script>
|
||||
@@ -3,6 +3,7 @@
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('accent').type('CheckboxAccent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
|
||||
prop('value').str().help('Used when the model is an array'),
|
||||
prop('disabled').bool().widget(),
|
||||
slot(),
|
||||
slot('info'),
|
||||
@@ -10,7 +11,7 @@
|
||||
setting('defaultSlot').widget(text()).preset('Label'),
|
||||
setting('info').widget(text()).preset('Lorem ipsum dolor sit amet, consectetur adipiscing elit.'),
|
||||
setting('message').widget(text()).preset('Lorem ipsum dolor sit amet, consectetur adipiscing elit.'),
|
||||
model().type('boolean').preset(undefined),
|
||||
model().type('boolean | undefined | string[]').preset(undefined).help('undefined means partly checked'),
|
||||
]"
|
||||
>
|
||||
<UiCheckbox v-bind="properties">
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ settings }"
|
||||
:params="[
|
||||
slot().help('Meant to receive the subcategory title'),
|
||||
slot('info').help('Meant to receive a short text displayed on the right'),
|
||||
setting('defaultSlot').widget(text()).preset('Into a pool'),
|
||||
setting('info').widget(text()).preset('Writes to a pool'),
|
||||
]"
|
||||
>
|
||||
<UiGroupSubcategory>
|
||||
{{ settings.defaultSlot }}
|
||||
<template v-if="settings.info" #info>{{ settings.info }}</template>
|
||||
</UiGroupSubcategory>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { text } from '@/libs/story/story-widget.ts'
|
||||
import UiGroupSubcategory from '@core/components/ui/group-subcategory/UiGroupSubcategory.vue'
|
||||
</script>
|
||||
@@ -0,0 +1,39 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('accent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
|
||||
prop('size').required().enum('small', 'medium').preset('medium').widget(),
|
||||
prop('disabled').bool().widget(),
|
||||
prop('src').required().str().help('Image URL for rich mode'),
|
||||
prop('alt').required().str().help('Alt text for image'),
|
||||
model().type('string').preset(''),
|
||||
setting('defaultSlot').widget(text()).preset('Label'),
|
||||
]"
|
||||
>
|
||||
<div class="radio">
|
||||
<UiImageRadioButton v-model="selectedRadio" value="1" v-bind="properties" :src="imageUrl" :alt="properties.alt">
|
||||
{{ settings.defaultSlot }}
|
||||
</UiImageRadioButton>
|
||||
</div>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { model, prop, setting } from '@/libs/story/story-param.ts'
|
||||
import { text } from '@/libs/story/story-widget.ts'
|
||||
import UiImageRadioButton from '@core/components/ui/image-radio-button/UiImageRadioButton.vue'
|
||||
import { ref } from 'vue'
|
||||
import imageUrl from '../../../../assets/color-mode-dark.svg'
|
||||
|
||||
const selectedRadio = ref('')
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.radio {
|
||||
display: flex;
|
||||
gap: 1.6rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
</style>
|
||||
@@ -10,16 +10,16 @@
|
||||
slot().help('Meant to receive a list of radio button components'),
|
||||
slot('label').help('Meant to receive a label UiLabel component or another component'),
|
||||
slot('info').help('Meant to receive a message info or UiInfo component or another component'),
|
||||
setting('richRadioButton').widget(boolean()),
|
||||
setting('imageRadioButton').widget(boolean()),
|
||||
]"
|
||||
>
|
||||
<UiRadioButtonGroup v-bind="properties">
|
||||
<component
|
||||
:is="settings.richRadioButton === true ? UiRichRadioButton : UiRadioButton"
|
||||
:is="settings.imageRadioButton === true ? UiImageRadioButton : UiRadioButton"
|
||||
v-for="(label, index) in labels"
|
||||
:key="index"
|
||||
v-model="selectedRadio"
|
||||
v-bind="richButtonProps(properties, settings.richRadioButton)"
|
||||
v-bind="imageButtonProps(properties, settings.imageRadioButton)"
|
||||
:value="`radio-${index}`"
|
||||
>
|
||||
{{ label }}
|
||||
@@ -32,9 +32,9 @@
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { prop, setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { boolean } from '@/libs/story/story-widget.ts'
|
||||
import UiImageRadioButton from '@core/components/ui/image-radio-button/UiImageRadioButton.vue'
|
||||
import UiRadioButton from '@core/components/ui/radio-button/UiRadioButton.vue'
|
||||
import UiRadioButtonGroup from '@core/components/ui/radio-button-group/UiRadioButtonGroup.vue'
|
||||
import UiRichRadioButton from '@core/components/ui/rich-radio-button/UiRichRadioButton.vue'
|
||||
import { ref } from 'vue'
|
||||
import imageUrl from '../../../../assets/color-mode-dark.svg'
|
||||
|
||||
@@ -42,8 +42,8 @@ const selectedRadio = ref('')
|
||||
|
||||
const labels = ref(['Label 1', 'Label 2', 'Label 3'])
|
||||
|
||||
const richButtonProps = (properties: any, richRadioButton: boolean) => {
|
||||
if (richRadioButton) {
|
||||
const imageButtonProps = (properties: any, imageRadioButton: boolean) => {
|
||||
if (imageRadioButton) {
|
||||
return {
|
||||
...properties,
|
||||
src: imageUrl,
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
prop('accent').type('RichCheckboxAccent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
|
||||
prop('label').str().widget().preset('Backup repositories'),
|
||||
prop('info').str().widget(),
|
||||
prop('message').str().widget().help('Only displayed when the accent is not brand'),
|
||||
prop('vertical').bool().widget().preset(true),
|
||||
slot().help('Meant to receive UiRichCheckbox components, and UiGroupSubcategory components in vertical mode'),
|
||||
slot('label').help('Meant to receive a UiLabel component or another component'),
|
||||
slot('info').help('Meant to receive a UiInfo component or another component'),
|
||||
slot('message').help('Meant to receive a UiInfo component or another component'),
|
||||
]"
|
||||
>
|
||||
<UiRichCheckboxGroup v-bind="properties">
|
||||
<template v-for="category of properties.vertical ? categories : horizontalCategories" :key="category.title">
|
||||
<UiGroupSubcategory v-if="properties.vertical">
|
||||
{{ category.title }}
|
||||
<template v-if="category.info" #info>{{ category.info }}</template>
|
||||
</UiGroupSubcategory>
|
||||
<UiRichCheckbox
|
||||
v-for="option of category.options"
|
||||
:key="option.value"
|
||||
v-model="selectedRepositories"
|
||||
:accent="properties.accent"
|
||||
:value="option.value"
|
||||
:tag="option.tag"
|
||||
:description="option.description"
|
||||
:disabled="option.disabled"
|
||||
icon="fa:server"
|
||||
>
|
||||
{{ option.label }}
|
||||
</UiRichCheckbox>
|
||||
</template>
|
||||
</UiRichCheckboxGroup>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { prop, slot } from '@/libs/story/story-param.ts'
|
||||
import UiGroupSubcategory from '@core/components/ui/group-subcategory/UiGroupSubcategory.vue'
|
||||
import UiRichCheckbox from '@core/components/ui/rich-checkbox/UiRichCheckbox.vue'
|
||||
import UiRichCheckboxGroup from '@core/components/ui/rich-checkbox-group/UiRichCheckboxGroup.vue'
|
||||
import { ref } from 'vue'
|
||||
|
||||
type StoryOption = {
|
||||
value: string
|
||||
label: string
|
||||
description: string
|
||||
tag?: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const selectedRepositories = ref(['nfs-backups', 'smb-archive'])
|
||||
|
||||
const categories: { title: string; info?: string; options: StoryOption[] }[] = [
|
||||
{
|
||||
title: 'Category 1',
|
||||
options: [
|
||||
{ value: 'rd-s3', label: 'RD - S3', description: '3.1 TiB free', tag: 'Source' },
|
||||
{ value: 'nfs-backups', label: 'NFS backups', description: '4.2 TiB free' },
|
||||
{ value: 'local-backups', label: 'Local backups', description: '120 GiB free', disabled: true },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Category 2',
|
||||
info: 'Info',
|
||||
options: [{ value: 'smb-archive', label: 'SMB archive', description: '900 GiB free' }],
|
||||
},
|
||||
]
|
||||
|
||||
const horizontalCategories = categories.slice(0, 1)
|
||||
</script>
|
||||
@@ -0,0 +1,41 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('accent').type('RichCheckboxAccent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
|
||||
prop('value').str().help('Used when the model is an array'),
|
||||
iconProp(),
|
||||
prop('tag').str().widget().preset('Label'),
|
||||
prop('description').str().widget().preset('Description'),
|
||||
prop('info').str().widget(),
|
||||
prop('message').str().widget().help('Only displayed when the accent is not brand'),
|
||||
prop('disabled').bool().widget(),
|
||||
model().type('boolean | undefined | string[]').preset(undefined).help('undefined means partly checked'),
|
||||
slot().help('Meant to receive the label'),
|
||||
slot('tag').help('Meant to receive a UiTag component, to use another accent than the default info one'),
|
||||
slot('description'),
|
||||
slot('info'),
|
||||
slot('message'),
|
||||
setting('defaultSlot').widget(text()).preset('Label'),
|
||||
]"
|
||||
>
|
||||
<div class="checkbox">
|
||||
<UiRichCheckbox v-bind="properties">
|
||||
{{ settings.defaultSlot }}
|
||||
</UiRichCheckbox>
|
||||
</div>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { iconProp, model, prop, setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { text } from '@/libs/story/story-widget.ts'
|
||||
import UiRichCheckbox from '@core/components/ui/rich-checkbox/UiRichCheckbox.vue'
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.checkbox {
|
||||
max-width: 40rem;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,125 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
prop('accent')
|
||||
.type('RichRadioButtonAccent')
|
||||
.required()
|
||||
.enum('brand', 'warning', 'danger')
|
||||
.preset('brand')
|
||||
.widget(),
|
||||
prop('label').str().widget().preset('Restore type'),
|
||||
prop('info').str().widget(),
|
||||
prop('message').str().widget().help('Only displayed when the accent is not brand'),
|
||||
prop('vertical').bool().widget().preset(true),
|
||||
slot().help('Meant to receive UiRichRadioButton components, and UiGroupSubcategory components in vertical mode'),
|
||||
slot('label').help('Meant to receive a UiLabel component or another component'),
|
||||
slot('info').help('Meant to receive a UiInfo component or another component'),
|
||||
slot('message').help('Meant to receive a UiInfo component or another component'),
|
||||
]"
|
||||
>
|
||||
<UiRichRadioButtonGroup v-bind="properties">
|
||||
<template v-for="category of properties.vertical ? categories : horizontalCategories" :key="category.title">
|
||||
<UiGroupSubcategory v-if="properties.vertical">
|
||||
{{ category.title }}
|
||||
<template #info>{{ category.info }}</template>
|
||||
</UiGroupSubcategory>
|
||||
<UiRichRadioButton
|
||||
v-for="option of category.options"
|
||||
:key="option.value"
|
||||
v-model="selectedRadio"
|
||||
:accent="properties.accent"
|
||||
:value="option.value"
|
||||
:icon="option.icon"
|
||||
:description="option.description"
|
||||
:disabled="option.disabled"
|
||||
>
|
||||
{{ option.label }}
|
||||
<template v-if="option.tag" #tag>
|
||||
<UiTag :accent="option.tag.accent" variant="secondary">{{ option.tag.label }}</UiTag>
|
||||
</template>
|
||||
</UiRichRadioButton>
|
||||
</template>
|
||||
</UiRichRadioButtonGroup>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { prop, slot } from '@/libs/story/story-param.ts'
|
||||
import type { IconName } from '@core/icons'
|
||||
import UiGroupSubcategory from '@core/components/ui/group-subcategory/UiGroupSubcategory.vue'
|
||||
import UiRichRadioButton from '@core/components/ui/rich-radio-button/UiRichRadioButton.vue'
|
||||
import UiRichRadioButtonGroup from '@core/components/ui/rich-radio-button-group/UiRichRadioButtonGroup.vue'
|
||||
import UiTag, { type TagAccent } from '@core/components/ui/tag/UiTag.vue'
|
||||
import { ref } from 'vue'
|
||||
|
||||
type StoryOption = {
|
||||
value: string
|
||||
label: string
|
||||
description: string
|
||||
icon: IconName
|
||||
tag?: { label: string; accent: TagAccent }
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const selectedRadio = ref('copy-then-start')
|
||||
|
||||
const categories: { title: string; info: string; options: StoryOption[] }[] = [
|
||||
{
|
||||
title: 'Into a pool',
|
||||
info: 'Writes to a pool',
|
||||
options: [
|
||||
{
|
||||
value: 'copy-then-start',
|
||||
label: 'Copy, then start',
|
||||
description:
|
||||
'Copy the disks to a storage of the pool, then start the VM. When a snapshot of the VM is still in the pool, only the blocks that differ are transferred, if possible.',
|
||||
icon: 'action:copy',
|
||||
tag: { label: 'Default', accent: 'info' },
|
||||
},
|
||||
{
|
||||
value: 'start-now',
|
||||
label: 'Start now',
|
||||
description: 'Start the VM right away from the backup. What it writes goes to a cache storage.',
|
||||
icon: 'status:running',
|
||||
tag: { label: 'Live restore', accent: 'neutral' },
|
||||
},
|
||||
{
|
||||
value: 'attach-disk',
|
||||
label: 'Attach a disk to a running VM',
|
||||
description: 'Serve a disk of the backup, read-only, to an existing VM. Nothing is copied.',
|
||||
icon: 'action:attach',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Out of the backup',
|
||||
info: 'Nothing written to a pool',
|
||||
options: [
|
||||
{
|
||||
value: 'download-files',
|
||||
label: 'Download files',
|
||||
description:
|
||||
'Browse a partition of a disk and download individual files or folders. Best for a small amount of data.',
|
||||
icon: 'action:download',
|
||||
},
|
||||
{
|
||||
value: 'export-disk',
|
||||
label: 'Export a disk',
|
||||
description: 'Convert one disk to qcow2, vmdk, vhd or raw, then download it.',
|
||||
icon: 'action:download',
|
||||
},
|
||||
{
|
||||
value: 'export-vm',
|
||||
label: 'Export the VM',
|
||||
description: 'Build an XVA from the backup, to import into XCP-ng or XenServer.',
|
||||
icon: 'action:download',
|
||||
disabled: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const horizontalCategories = categories.slice(0, 1)
|
||||
</script>
|
||||
@@ -2,17 +2,30 @@
|
||||
<ComponentStory
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('accent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
|
||||
prop('size').required().enum('small', 'medium').preset('medium').widget(),
|
||||
prop('accent')
|
||||
.type('RichRadioButtonAccent')
|
||||
.required()
|
||||
.enum('brand', 'warning', 'danger')
|
||||
.preset('brand')
|
||||
.widget(),
|
||||
iconProp(),
|
||||
prop('tag').str().widget().preset('Label'),
|
||||
prop('description').str().widget().preset('Description'),
|
||||
prop('info').str().widget(),
|
||||
prop('disabled').bool().widget(),
|
||||
prop('src').required().str().help('Image URL for rich mode'),
|
||||
prop('alt').required().str().help('Alt text for image'),
|
||||
model().type('string').preset(''),
|
||||
model().type('string'),
|
||||
slot().help('Meant to receive the label'),
|
||||
slot('tag').help('Meant to receive a UiTag component, to use another accent than the default info one'),
|
||||
slot('description'),
|
||||
slot('info'),
|
||||
setting('defaultSlot').widget(text()).preset('Label'),
|
||||
]"
|
||||
>
|
||||
<div class="radio">
|
||||
<UiRichRadioButton v-model="selectedRadio" value="1" v-bind="properties" :src="imageUrl" :alt="properties.alt">
|
||||
<div class="radios">
|
||||
<UiRichRadioButton v-model="selectedRadio" v-bind="properties" value="1">
|
||||
{{ settings.defaultSlot }}
|
||||
</UiRichRadioButton>
|
||||
<UiRichRadioButton v-model="selectedRadio" v-bind="properties" value="2">
|
||||
{{ settings.defaultSlot }}
|
||||
</UiRichRadioButton>
|
||||
</div>
|
||||
@@ -21,19 +34,19 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { model, prop, setting } from '@/libs/story/story-param.ts'
|
||||
import { iconProp, model, prop, setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { text } from '@/libs/story/story-widget.ts'
|
||||
import UiRichRadioButton from '@core/components/ui/rich-radio-button/UiRichRadioButton.vue'
|
||||
import { ref } from 'vue'
|
||||
import imageUrl from '../../../../assets/color-mode-dark.svg'
|
||||
|
||||
const selectedRadio = ref('')
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.radio {
|
||||
.radios {
|
||||
display: flex;
|
||||
gap: 1.6rem;
|
||||
flex-wrap: wrap;
|
||||
flex-direction: column;
|
||||
gap: 0.8rem;
|
||||
max-width: 40rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -20,12 +20,15 @@
|
||||
setting('maxWidth').widget(number()).help('Maximum width, in rem'),
|
||||
]"
|
||||
>
|
||||
<UiTertiaryTag v-bind="properties" :style="{ maxWidth: settings.maxWidth ? `${settings.maxWidth}rem` : undefined }">
|
||||
<UiLabelValueTag
|
||||
v-bind="properties"
|
||||
:style="{ maxWidth: settings.maxWidth ? `${settings.maxWidth}rem` : undefined }"
|
||||
>
|
||||
{{ settings.slot }}
|
||||
<template #term>
|
||||
{{ settings.term }}
|
||||
</template>
|
||||
</UiTertiaryTag>
|
||||
</UiLabelValueTag>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
@@ -33,5 +36,5 @@
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { prop, setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { number } from '@/libs/story/story-widget.ts'
|
||||
import UiTertiaryTag from '@core/components/ui/tag/UiTertiaryTag.vue'
|
||||
import UiLabelValueTag from '@core/components/ui/tag/UiLabelValueTag.vue'
|
||||
</script>
|
||||
@@ -9,6 +9,7 @@
|
||||
.enum('brand', 'info', 'neutral', 'success', 'warning', 'danger', 'muted')
|
||||
.widget(),
|
||||
prop('variant').type('TagVariant').required().preset('primary').enum('primary', 'secondary').widget(),
|
||||
iconProp(),
|
||||
slot(),
|
||||
setting('slot').preset('Label').widget(),
|
||||
]"
|
||||
@@ -21,6 +22,6 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { prop, setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { iconProp, prop, setting, slot } from '@/libs/story/story-param.ts'
|
||||
import UiTag from '@core/components/ui/tag/UiTag.vue'
|
||||
</script>
|
||||
|
||||
@@ -8,18 +8,18 @@
|
||||
<UiTag accent="success" variant="primary">{{ settings.slot }}</UiTag>
|
||||
<UiTag accent="warning" variant="secondary">{{ settings.slot }}</UiTag>
|
||||
<UiTag accent="danger" variant="secondary">{{ settings.slot }}</UiTag>
|
||||
<UiTertiaryTag accent="info">
|
||||
<UiLabelValueTag accent="info">
|
||||
{{ settings.slot }}
|
||||
<template #term>
|
||||
{{ settings.slot }}
|
||||
</template>
|
||||
</UiTertiaryTag>
|
||||
<UiTertiaryTag accent="success">
|
||||
</UiLabelValueTag>
|
||||
<UiLabelValueTag accent="success">
|
||||
{{ settings.slot }}
|
||||
<template #term>
|
||||
{{ settings.slot }}
|
||||
</template>
|
||||
</UiTertiaryTag>
|
||||
</UiLabelValueTag>
|
||||
</UiTagsList>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
@@ -27,7 +27,7 @@
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { setting, slot } from '@/libs/story/story-param.ts'
|
||||
import UiLabelValueTag from '@core/components/ui/tag/UiLabelValueTag.vue'
|
||||
import UiTag from '@core/components/ui/tag/UiTag.vue'
|
||||
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
|
||||
import UiTertiaryTag from '@core/components/ui/tag/UiTertiaryTag.vue'
|
||||
</script>
|
||||
|
||||
@@ -67,10 +67,107 @@ export const deepNestedTask: Task = {
|
||||
],
|
||||
}
|
||||
|
||||
export const pendingWithoutProgressTask: Task = {
|
||||
id: '6',
|
||||
name: 'Queued replication',
|
||||
status: 'pending',
|
||||
start: Date.now() - 2 * 60_000,
|
||||
}
|
||||
|
||||
export const pendingFullProgressTask: Task = {
|
||||
id: '7',
|
||||
name: 'Finalize export',
|
||||
status: 'pending',
|
||||
progress: 100,
|
||||
start: Date.now() - 60_000,
|
||||
infos: [{ message: 'Waiting for cleanup', data: null }],
|
||||
}
|
||||
|
||||
export const infosAndWarningsTask: Task = {
|
||||
id: '8',
|
||||
name: 'Rolling pool update',
|
||||
status: 'pending',
|
||||
progress: 50,
|
||||
start: Date.now() - 3 * 60 * 60_000,
|
||||
infos: [{ message: 'Hosts updated', data: { hosts: 4, done: 2 } }],
|
||||
warnings: [{ message: 'Reboot required after update', data: { host: 'host-3' } }],
|
||||
subtasks: [
|
||||
{ id: '8-1', name: 'host-1', status: 'success', progress: 100, end: Date.now() - 2 * 60 * 60_000 },
|
||||
{ id: '8-2', name: 'host-2', status: 'success', progress: 100, end: Date.now() - 60 * 60_000 },
|
||||
{ id: '8-3', name: 'host-3', status: 'pending', progress: 30, start: Date.now() - 15 * 60_000 },
|
||||
],
|
||||
}
|
||||
|
||||
export const failedNestedTask: Task = {
|
||||
id: '9',
|
||||
name: 'Disaster recovery drill',
|
||||
status: 'failure',
|
||||
progress: 100,
|
||||
start: Date.now() - 8 * 60 * 60_000,
|
||||
end: Date.now() - 7 * 60 * 60_000,
|
||||
subtasks: [
|
||||
{ id: '9-1', name: 'Provision VM', status: 'success', progress: 100, end: Date.now() - 7.5 * 60 * 60_000 },
|
||||
{
|
||||
id: '9-2',
|
||||
name: 'Restore data',
|
||||
status: 'failure',
|
||||
progress: 100,
|
||||
end: Date.now() - 7 * 60 * 60_000,
|
||||
warnings: [{ message: 'Missing backup files', data: { missing: 3 } }],
|
||||
subtasks: [
|
||||
{ id: '9-2-1', name: 'Mount SR', status: 'failure', progress: 100, end: Date.now() - 7.1 * 60 * 60_000 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
export const interruptedTask: Task = {
|
||||
id: '10',
|
||||
name: 'Storage migration',
|
||||
status: 'interrupted',
|
||||
progress: 10,
|
||||
start: Date.now() - 2 * 60 * 60_000,
|
||||
infos: [
|
||||
{ message: 'Rows migrated before interruption', data: { rows: 1200 } },
|
||||
{ message: 'Task manually aborted', data: null },
|
||||
],
|
||||
}
|
||||
|
||||
export const longNameTask: Task = {
|
||||
id: '11',
|
||||
name: 'Very long task name that should wrap gracefully in the task list UI when space is limited',
|
||||
status: 'pending',
|
||||
progress: 8,
|
||||
start: Date.now() - 2 * 60 * 60_000,
|
||||
}
|
||||
|
||||
export const longNameWithEverythingTask: Task = {
|
||||
id: '12',
|
||||
name: 'Very long task name for a full backup job that also has subtasks, infos, warnings and an end time to display',
|
||||
to: '#',
|
||||
status: 'failure',
|
||||
progress: 100,
|
||||
start: Date.now() - 5 * 60 * 60_000,
|
||||
end: Date.now() - 4 * 60 * 60_000,
|
||||
infos: [{ message: 'Transferred 120 GiB', data: { size: 120 } }],
|
||||
warnings: [{ message: 'Some VDIs were skipped', data: { skipped: 2 } }],
|
||||
subtasks: [
|
||||
{ id: '12-1', name: 'Snapshot', status: 'success', progress: 100, end: Date.now() - 4.5 * 60 * 60_000 },
|
||||
{ id: '12-2', name: 'Transfer', status: 'failure', progress: 100, end: Date.now() - 4 * 60 * 60_000 },
|
||||
],
|
||||
}
|
||||
|
||||
export const allTasks: Task[] = [
|
||||
pendingBackupTask,
|
||||
completedWithRootLinkTask,
|
||||
failedWithWarningsTask,
|
||||
migrationNamePartsTask,
|
||||
deepNestedTask,
|
||||
pendingWithoutProgressTask,
|
||||
pendingFullProgressTask,
|
||||
infosAndWarningsTask,
|
||||
failedNestedTask,
|
||||
interruptedTask,
|
||||
longNameTask,
|
||||
longNameWithEverythingTask,
|
||||
]
|
||||
|
||||
@@ -4,27 +4,22 @@
|
||||
:presets
|
||||
:params="[
|
||||
prop('task').type('object').required().widget().preset(pendingBackupTask),
|
||||
prop('depth').type('number').required().preset(1),
|
||||
model('expanded').prop(p => p.type('boolean').widget(boolean()).preset(false)),
|
||||
prop('selected').type('boolean').widget(boolean()).preset(false),
|
||||
prop('showEyeIcon').type('boolean').widget(boolean()).preset(true),
|
||||
event('expand'),
|
||||
prop('showUnread').bool().widget().help('Reserves the unread dot column'),
|
||||
prop('unread').bool().widget(),
|
||||
event('select').args({ id: 'string' }),
|
||||
]"
|
||||
>
|
||||
<ul>
|
||||
<UiTaskItem v-bind="properties" @expand="properties['onUpdate:expanded']?.(!properties.expanded)" />
|
||||
</ul>
|
||||
<UiTaskItem v-bind="properties" />
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, model, prop } from '@/libs/story/story-param.ts'
|
||||
import { event, prop } from '@/libs/story/story-param.ts'
|
||||
import { boolean } from '@/libs/story/story-widget.ts'
|
||||
import {
|
||||
completedWithRootLinkTask,
|
||||
deepNestedTask,
|
||||
failedWithWarningsTask,
|
||||
migrationNamePartsTask,
|
||||
pendingBackupTask,
|
||||
@@ -40,45 +35,24 @@ const presets: Record<
|
||||
'Pending backup': {
|
||||
props: {
|
||||
task: pendingBackupTask,
|
||||
depth: 1,
|
||||
expanded: false,
|
||||
selected: false,
|
||||
showEyeIcon: true,
|
||||
},
|
||||
},
|
||||
'Completed + root link': {
|
||||
props: {
|
||||
task: completedWithRootLinkTask,
|
||||
depth: 1,
|
||||
expanded: false,
|
||||
selected: false,
|
||||
showEyeIcon: true,
|
||||
},
|
||||
},
|
||||
'Failed + warnings': {
|
||||
props: {
|
||||
task: failedWithWarningsTask,
|
||||
depth: 1,
|
||||
expanded: false,
|
||||
selected: false,
|
||||
showEyeIcon: true,
|
||||
},
|
||||
},
|
||||
'Migration (nameParts)': {
|
||||
props: {
|
||||
task: migrationNamePartsTask,
|
||||
depth: 1,
|
||||
expanded: false,
|
||||
selected: false,
|
||||
showEyeIcon: true,
|
||||
},
|
||||
},
|
||||
'Deep nested': {
|
||||
props: {
|
||||
task: deepNestedTask,
|
||||
depth: 1,
|
||||
expanded: true,
|
||||
selected: false,
|
||||
showEyeIcon: true,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[prop('tasks').type('Task[]').required().preset(allTasks), event('select')]"
|
||||
>
|
||||
<UiTaskList v-bind="properties" />
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, prop } from '@/libs/story/story-param.ts'
|
||||
import { allTasks } from '@/stories/web-core/ui/task-item/mock-tasks.ts'
|
||||
import UiTaskList from '@core/components/ui/task-list/UiTaskList.vue'
|
||||
</script>
|
||||
@@ -1,8 +1,16 @@
|
||||
import type { XenApiHost, XenApiNetwork, XenApiSr, XenApiVdi, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import type {
|
||||
XenApiHost,
|
||||
XenApiNetwork,
|
||||
XenApiSr,
|
||||
XenApiVbd,
|
||||
XenApiVdi,
|
||||
XenApiVm,
|
||||
} from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { type OPAQUE_REF_NULL, type VDI_TYPE } from '@vates/types/common'
|
||||
|
||||
export interface Vdi {
|
||||
id?: XenApiVdi['$ref'] | undefined
|
||||
userdevice?: XenApiVbd['userdevice']
|
||||
name_label: string
|
||||
name_description: string
|
||||
size: number
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": false,
|
||||
"name": "@xen-orchestra/log",
|
||||
"version": "0.7.2",
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"description": "Logging system with decoupled producers/consumer",
|
||||
"keywords": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": false,
|
||||
"name": "@xen-orchestra/mcp",
|
||||
"version": "1.4.3",
|
||||
"version": "1.4.4",
|
||||
"description": "MCP server for Xen Orchestra — allows AI assistants to query and manage XO infrastructure",
|
||||
"type": "module",
|
||||
"main": "./dist/index.mjs",
|
||||
@@ -34,7 +34,7 @@
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.19.0",
|
||||
"@types/node": "^22.3.0",
|
||||
"@vates/types": "^2.5.0",
|
||||
"@vates/types": "^3.1.0",
|
||||
"rimraf": "^6.0.0",
|
||||
"typescript": "~5.6.3",
|
||||
"typescript-eslint": "^8.61.0"
|
||||
|
||||
@@ -14,18 +14,18 @@
|
||||
"url": "https://vates.fr"
|
||||
},
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"version": "0.23.0",
|
||||
"version": "0.24.0",
|
||||
"engines": {
|
||||
"node": ">=15.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@vates/event-listeners-manager": "^1.0.1",
|
||||
"@vates/iscsi": "^0.4.0",
|
||||
"@vates/iscsi": "^0.4.1",
|
||||
"@vates/parse-duration": "^0.1.1",
|
||||
"@vates/task": "^0.7.0",
|
||||
"@xen-orchestra/backup-archive": "^1.2.0",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/backup-archive": "^1.2.1",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"acme-client": "^5.0.0",
|
||||
"app-conf": "^3.0.0",
|
||||
"fast-xml-parser": "^4.0.0",
|
||||
@@ -36,7 +36,7 @@
|
||||
"xo-common": "^0.11.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vates/types": "^2.5.0"
|
||||
"@vates/types": "^3.1.0"
|
||||
},
|
||||
"scripts": {
|
||||
"postversion": "npm publish --access public",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@xen-orchestra/proxy",
|
||||
"version": "0.34.0",
|
||||
"version": "0.35.1",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"description": "XO Proxy used to remotely execute backup jobs",
|
||||
"keywords": [
|
||||
@@ -31,16 +31,16 @@
|
||||
"@vates/cached-dns.lookup": "^1.0.0",
|
||||
"@vates/compose": "^2.1.0",
|
||||
"@vates/decorate-with": "^2.1.0",
|
||||
"@vates/disposable": "^0.1.6",
|
||||
"@vates/disposable": "^0.1.7",
|
||||
"@vates/task": "^0.7.0",
|
||||
"@xen-orchestra/async-map": "^0.1.5",
|
||||
"@xen-orchestra/backups": "^0.78.0",
|
||||
"@xen-orchestra/fs": "^4.10.0",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/backups": "^1.0.1",
|
||||
"@xen-orchestra/fs": "^4.11.0",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"@xen-orchestra/mixin": "^0.2.1",
|
||||
"@xen-orchestra/mixins": "^0.23.0",
|
||||
"@xen-orchestra/mixins": "^0.24.0",
|
||||
"@xen-orchestra/self-signed": "^0.2.1",
|
||||
"@xen-orchestra/xapi": "^9.1.0",
|
||||
"@xen-orchestra/xapi": "^10.0.0",
|
||||
"ajv": "^8.0.3",
|
||||
"app-conf": "^3.0.0",
|
||||
"async-iterator-to-stream": "^1.1.0",
|
||||
@@ -62,7 +62,7 @@
|
||||
"source-map-support": "^0.5.16",
|
||||
"stoppable": "^1.0.6",
|
||||
"xdg-basedir": "^5.1.0",
|
||||
"xen-api": "^5.1.0",
|
||||
"xen-api": "^6.0.0",
|
||||
"xo-common": "^0.11.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "@xen-orchestra/qa-test",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"version": "1.4.0",
|
||||
"version": "1.5.0",
|
||||
"description": "XenOrchestra QA Test Suite",
|
||||
"author": {
|
||||
"name": "Vates SAS",
|
||||
@@ -22,10 +22,10 @@
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@vates/read-chunk": "^1.2.1",
|
||||
"@xen-orchestra/backups": "^0.78.0",
|
||||
"@xen-orchestra/fs": "^4.10.0",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/vmware-explorer": "^1.2.0",
|
||||
"@xen-orchestra/backups": "^1.0.1",
|
||||
"@xen-orchestra/fs": "^4.11.0",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"@xen-orchestra/vmware-explorer": "^1.4.0",
|
||||
"nodemailer": "^7.0.13",
|
||||
"xo-lib": "^0.11.2"
|
||||
},
|
||||
|
||||
@@ -37,12 +37,38 @@ function getBranchName() {
|
||||
}
|
||||
}
|
||||
|
||||
function getCommitHash() {
|
||||
try {
|
||||
return execSync('git rev-parse --short HEAD', { encoding: 'utf8', cwd: ROOT }).trim()
|
||||
} catch {
|
||||
return 'unknown'
|
||||
}
|
||||
}
|
||||
|
||||
function formatDatetime(date) {
|
||||
// "2026-05-20 08:42 UTC"
|
||||
return date
|
||||
.toISOString()
|
||||
.replace('T', ' ')
|
||||
.replace(/:\d{2}\.\d+Z$/, ' UTC')
|
||||
// "19/11/2026 13:43 (Paris)"
|
||||
return `${date.toLocaleString('fr-FR', {
|
||||
timeZone: 'Europe/Paris',
|
||||
dateStyle: 'short',
|
||||
timeStyle: 'short',
|
||||
})} (Paris)`
|
||||
}
|
||||
|
||||
function formatDuration(ms) {
|
||||
const hours = Math.floor(ms / 3600000)
|
||||
const minutes = Math.floor((ms / 60000) % 60)
|
||||
.toString()
|
||||
.padStart(2, '0')
|
||||
return `${hours}h${minutes}`
|
||||
}
|
||||
|
||||
function getCount(output, label) {
|
||||
const match = output.match(new RegExp(`ℹ ${label} (\\d+)`))
|
||||
if (match === null) {
|
||||
return '?'
|
||||
} else {
|
||||
return match[1]
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -123,14 +149,27 @@ if (process.argv.includes('--smtp-test')) {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const branch = getBranchName()
|
||||
const commitHash = getCommitHash()
|
||||
const startedAt = new Date()
|
||||
|
||||
process.stderr.write(`[run-and-report] branch=${branch}\n`)
|
||||
|
||||
const { success, output, logFilePath } = await runTests()
|
||||
const runtimeInMs = Date.now() - startedAt.getTime()
|
||||
|
||||
const emoji = success ? '✅' : '❌'
|
||||
const status = success ? 'success' : 'failure'
|
||||
const subject = `test run ${formatDatetime(startedAt)} ${branch} ${status}`
|
||||
const successTests = getCount(output, 'pass')
|
||||
const totalTests = getCount(output, 'tests')
|
||||
const failedTests = getCount(output, 'fail')
|
||||
const cancelledTests = getCount(output, 'cancelled')
|
||||
const skippedTests = getCount(output, 'skipped')
|
||||
|
||||
const subject = `${emoji} ${status} ${successTests}/${totalTests} passed ${formatDatetime(startedAt)} on ${branch}@${commitHash}`
|
||||
const summary = `Result: ${emoji} ${status}
|
||||
Commit: ${branch}@${commitHash}
|
||||
Tests: ${successTests}/${totalTests} passed, ${failedTests} failed, ${cancelledTests} cancelled, ${skippedTests} skipped
|
||||
Duration: ${formatDuration(runtimeInMs)}`
|
||||
|
||||
// Attach the full structured debug log if we found its path
|
||||
const attachments = []
|
||||
@@ -149,7 +188,9 @@ await transport.sendMail({
|
||||
from: process.env.SMTP_FROM ?? process.env.SMTP_USER,
|
||||
to: process.env.SMTP_TO,
|
||||
subject,
|
||||
text: output,
|
||||
text: `${summary}
|
||||
----------------------------------------
|
||||
${output}`,
|
||||
attachments,
|
||||
})
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"main": "./dist/index.mjs",
|
||||
"name": "@xen-orchestra/rest-api",
|
||||
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/rest-api",
|
||||
"version": "0.41.1",
|
||||
"version": "0.43.0",
|
||||
"description": "REST API to manage your XOA",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"private": false,
|
||||
@@ -36,16 +36,16 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@vates/obfuscate": "^0.1.0",
|
||||
"@vates/obfuscate": "^0.2.0",
|
||||
"@vates/task": "^0.7.0",
|
||||
"@vates/types": "^2.5.0",
|
||||
"@xen-orchestra/acl": "^1.8.0",
|
||||
"@xen-orchestra/backups": "^0.78.0",
|
||||
"@vates/types": "^3.1.0",
|
||||
"@xen-orchestra/acl": "^1.9.0",
|
||||
"@xen-orchestra/backups": "^1.0.1",
|
||||
"@xen-orchestra/cron": "^1.0.7",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"@xen-orchestra/qcow2": "^1.4.1",
|
||||
"@xen-orchestra/vmdk": "^1.0.0",
|
||||
"@xen-orchestra/xapi": "^9.1.0",
|
||||
"@xen-orchestra/xapi": "^10.0.0",
|
||||
"complex-matcher": "^1.1.1",
|
||||
"fast-xml-parser": "^5.10.1",
|
||||
"golike-defer": "^0.5.1",
|
||||
@@ -57,7 +57,7 @@
|
||||
"swagger-ui-express": "^5.0.1",
|
||||
"tsoa": "^6.6.0",
|
||||
"value-matcher": "^0.2.0",
|
||||
"vhd-lib": "^4.17.0",
|
||||
"vhd-lib": "^4.17.1",
|
||||
"xo-common": "^0.11.0",
|
||||
"xo-remote-parser": "^2.0.0",
|
||||
"zod": "^4.3.6",
|
||||
|
||||
@@ -15,6 +15,8 @@ import type {
|
||||
import type { RestApi } from '../rest-api/rest-api.mjs'
|
||||
import { assertValidCron, vmContainsNoBakTag } from '../helpers/utils.helper.mjs'
|
||||
import type { CreateBackupJobBody, CreateBackupJobSchedule, UpdateBackupJobBody } from './backup-job.type.mjs'
|
||||
import { compileExpression, isExpression } from '@xen-orchestra/backups/_expressionPredicate.mjs'
|
||||
import { buildRunContext, buildVmContext } from '@xen-orchestra/backups/_buildContext.mjs'
|
||||
|
||||
export class BackupJobService {
|
||||
#backupJobTypes = ['backup', 'metadataBackup', 'mirrorBackup']
|
||||
@@ -69,12 +71,24 @@ export class BackupJobService {
|
||||
*/
|
||||
assertJobHasValidExpressions(type: AnyXoBackupJob['type'], job: UpdateBackupJobBody): void {
|
||||
if (type === 'backup') {
|
||||
const { srs, remotes, settings } = job as Extract<UpdateBackupJobBody, { srs?: unknown }>
|
||||
const { srs, remotes, vms, settings } = job as Extract<UpdateBackupJobBody, { srs?: unknown }>
|
||||
assertValidExpression('srs', srs)
|
||||
assertValidExpression('remotes', remotes)
|
||||
assertValidExpression('vms', vms)
|
||||
assertValidSettingsExpression(settings, ['healthCheckVmsWithTags', 'fullInterval'])
|
||||
} else if (type === 'mirrorBackup') {
|
||||
assertValidSettingsExpression(job.settings, ['healthCheckVmsWithTags', 'vmFilter'])
|
||||
const { filter, remotes, settings } = job as Extract<UpdateBackupJobBody, { sourceRemote?: unknown }>
|
||||
assertValidSettingsExpression(settings, ['healthCheckVmsWithTags', 'vmFilter'])
|
||||
assertValidExpression('remotes', remotes)
|
||||
if (filter != null && filter.vm.uuid.__or.length === 0) {
|
||||
throw invalidParameters('filter must contain at least one VM', [
|
||||
{ instancePath: '/filter/vm/uuid/__or', message: 'must NOT have fewer than 1 items' },
|
||||
])
|
||||
}
|
||||
} else if (type === 'metadataBackup') {
|
||||
const { remotes, pools } = job as Extract<UpdateBackupJobBody, { pools?: unknown }>
|
||||
assertValidExpression('remotes', remotes)
|
||||
assertValidExpression('pools', pools)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,16 +104,47 @@ export class BackupJobService {
|
||||
return false
|
||||
}
|
||||
|
||||
const isVmInJob = await this.getBackupJobVmMatcher(backupJob)
|
||||
return isVmInJob(vm)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a function telling whether a VM is selected by the `vms` of the job,
|
||||
* whether it is a list of IDs, an object pattern or an expression
|
||||
*/
|
||||
async getBackupJobVmMatcher(backupJob: XoVmBackupJob): Promise<(vm: XoVm) => boolean> {
|
||||
try {
|
||||
const vmIds: XoVm['id'][] = extractIdsFromSimplePattern(backupJob.vms)
|
||||
return vmIds.some(id => id === vm.id)
|
||||
const vmIds = new Set<XoVm['id']>(extractIdsFromSimplePattern(backupJob.vms))
|
||||
return vm => vmIds.has(vm.id)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
} catch (_) {
|
||||
const predicate = createPredicate(backupJob.vms)
|
||||
return predicate(vm)
|
||||
if (!isExpression(backupJob.vms)) {
|
||||
return createPredicate(backupJob.vms)
|
||||
}
|
||||
|
||||
// `run:` clauses depend on the timezone, which is resolved per schedule like the executor does,
|
||||
// so the VM is in the job if it matches for at least one of its schedules
|
||||
const predicate = compileExpression(backupJob.vms)
|
||||
const now = new Date()
|
||||
const runContexts = (await this.#getScheduleTimezones(backupJob)).map(timezone => buildRunContext(now, timezone))
|
||||
return vm => runContexts.some(runContext => predicate(buildVmContext(vm, runContext)))
|
||||
}
|
||||
}
|
||||
|
||||
async #getScheduleTimezones(backupJob: XoVmBackupJob): Promise<(string | undefined)[]> {
|
||||
const schedules = (await this.#restApi.xoApp.getAllSchedules()).filter(schedule => schedule.jobId === backupJob.id)
|
||||
if (schedules.length === 0) {
|
||||
return [backupJob.settings['']?.timezone]
|
||||
}
|
||||
|
||||
return schedules.map(schedule => {
|
||||
const scheduleTimezone = backupJob.settings[schedule.id]?.timezone
|
||||
return typeof scheduleTimezone === 'string'
|
||||
? scheduleTimezone
|
||||
: (backupJob.settings['']?.timezone ?? schedule.timezone)
|
||||
})
|
||||
}
|
||||
|
||||
async backupJobHasAtLeastOneScheduleEnabled(id: XoVmBackupJob['id']): Promise<boolean> {
|
||||
const backupJob = await this.#restApi.xoApp.getJob<XoVmBackupJob>(id)
|
||||
|
||||
|
||||
@@ -6,15 +6,19 @@ import type {
|
||||
XoMetadataBackupJobGeneralSettings,
|
||||
XoMetadataBackupJobScheduleSettings,
|
||||
XoMirrorBackupGeneralSettings,
|
||||
XoVm,
|
||||
} from '@vates/types'
|
||||
import { Unbrand } from '../open-api/common/response.common.mjs'
|
||||
import type * as CMType from '@vates/types/lib/complex-matcher'
|
||||
|
||||
// Manual copy because with Unbrand<>, tsoa emits an empty schema. If XoVmBackupJobScheduleSettings changes
|
||||
// in @vates/types, you have to update this copy too.
|
||||
type UnbrandedXoVmBackupJobScheduleSettings = {
|
||||
/**
|
||||
* Copy of XoVmBackupJobScheduleSettings without the brand:
|
||||
* tsoa empties any mapped type (Unbrand, Pick, Omit…) nested under Unbrand<UnbrandedXoVmBackupJob>,
|
||||
* which dropped every schedule setting from the request bodies
|
||||
*/
|
||||
type VmBackupJobScheduleSettings = {
|
||||
exportRetention?: number
|
||||
healthCheckVmsWithTags?: string[] | string
|
||||
healthCheckVmsWithTags?: XoVm['tags'] | string
|
||||
fullInterval?: number | string
|
||||
copyRetention?: number
|
||||
snapshotRetention?: number
|
||||
@@ -25,17 +29,17 @@ type UnbrandedXoVmBackupJobScheduleSettings = {
|
||||
|
||||
type UnbrandedXoVmBackupJob = Omit<XoVmBackupJob, 'settings' | 'remotes' | 'vms' | 'srs'> & {
|
||||
remotes?: CMType.IdOr<string> | string
|
||||
vms: CMType.IdOr<string> | Record<string, unknown>
|
||||
vms: CMType.IdOr<string> | Record<string, unknown> | string
|
||||
srs?: CMType.IdOr<string> | string
|
||||
settings: {
|
||||
'': XoVmBackupJobGeneralSettings
|
||||
[scheduleId: string]: UnbrandedXoVmBackupJobScheduleSettings | undefined
|
||||
[scheduleId: string]: VmBackupJobScheduleSettings | undefined
|
||||
}
|
||||
}
|
||||
export type UnbrandXoVmBackupJob = Unbrand<UnbrandedXoVmBackupJob>
|
||||
|
||||
type UnbrandedXoMetadataBackupJob = Omit<XoMetadataBackupJob, 'settings' | 'pools' | 'remotes'> & {
|
||||
pools?: CMType.IdOr<string>
|
||||
pools?: CMType.IdOr<string> | string
|
||||
remotes: CMType.IdOr<string>
|
||||
settings: {
|
||||
''?: XoMetadataBackupJobGeneralSettings
|
||||
@@ -44,21 +48,23 @@ type UnbrandedXoMetadataBackupJob = Omit<XoMetadataBackupJob, 'settings' | 'pool
|
||||
}
|
||||
export type UnbrandXoMetadataBackupJob = Unbrand<UnbrandedXoMetadataBackupJob>
|
||||
|
||||
// Manual copy because with Unbrand<>, tsoa emits an empty schema. If XoMirrorBackupScheduleSettings changes
|
||||
// in @vates/types, you have to update this copy too.
|
||||
type UnbrandedXoMirrorBackupScheduleSettings = {
|
||||
/**
|
||||
* Same as VmBackupJobScheduleSettings
|
||||
*/
|
||||
type MirrorBackupJobScheduleSettings = {
|
||||
exportRetention?: number
|
||||
healthCheckVmsWithTags?: string[] | string
|
||||
healthCheckVmsWithTags?: XoVm['tags'] | string
|
||||
vmFilter?: string
|
||||
healthCheckSr?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
type UnbrandedXoMirrorBackupJob = Omit<XoMirrorBackupJob, 'settings' | 'remotes'> & {
|
||||
type UnbrandedXoMirrorBackupJob = Omit<XoMirrorBackupJob, 'settings' | 'remotes' | 'filter'> & {
|
||||
remotes: CMType.IdOr<string>
|
||||
filter?: { vm: { uuid: { __or: string[] } } } | null
|
||||
settings: {
|
||||
'': XoMirrorBackupGeneralSettings
|
||||
[scheduleId: string]: UnbrandedXoMirrorBackupScheduleSettings | undefined
|
||||
[scheduleId: string]: MirrorBackupJobScheduleSettings | undefined
|
||||
}
|
||||
}
|
||||
export type UnbrandXoMirrorBackupJob = Unbrand<UnbrandedXoMirrorBackupJob>
|
||||
|
||||
@@ -27,3 +27,9 @@ export const proxy = {
|
||||
}
|
||||
|
||||
export const proxyHealth = { success: true }
|
||||
|
||||
export const proxyApplianceUpdaterState = {
|
||||
level: 'info',
|
||||
message: 'All up to date',
|
||||
state: 'xoa-up-to-date',
|
||||
}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import {
|
||||
Body,
|
||||
Example,
|
||||
Extension,
|
||||
Get,
|
||||
Middlewares,
|
||||
Patch,
|
||||
Path,
|
||||
Query,
|
||||
Request,
|
||||
@@ -15,26 +13,28 @@ import {
|
||||
Tags,
|
||||
} from 'tsoa'
|
||||
import { inject } from 'inversify'
|
||||
import { json } from 'express'
|
||||
import { provide } from 'inversify-binding-decorators'
|
||||
import type { Request as ExRequest } from 'express'
|
||||
import type { XoProxy, XoVm } from '@vates/types'
|
||||
import { forbiddenOperation } from 'xo-common/api-errors.js'
|
||||
import type { XoApp, XoProxy } from '@vates/types'
|
||||
|
||||
import { acl, actionFromBody } from '../middlewares/acl.middleware.mjs'
|
||||
import { acl } from '../middlewares/acl.middleware.mjs'
|
||||
import { ApiError } from '../helpers/error.helper.mjs'
|
||||
import {
|
||||
badRequestResp,
|
||||
forbiddenOperationResp,
|
||||
internalServerErrorResp,
|
||||
invalidParameters,
|
||||
noContentResp,
|
||||
notFoundResp,
|
||||
proxyUnreachableResp,
|
||||
unauthorizedResp,
|
||||
type Unbrand,
|
||||
} from '../open-api/common/response.common.mjs'
|
||||
import { partialProxies, proxy, proxyHealth, proxyIds } from '../open-api/oa-examples/proxy.oa-example.mjs'
|
||||
import {
|
||||
partialProxies,
|
||||
proxy,
|
||||
proxyHealth,
|
||||
proxyIds,
|
||||
proxyApplianceUpdaterState,
|
||||
} from '../open-api/oa-examples/proxy.oa-example.mjs'
|
||||
import type { SendObjects } from '../helpers/helper.type.mjs'
|
||||
import { XoController } from '../abstract-classes/xo-controller.mjs'
|
||||
import { RestApi } from '../rest-api/rest-api.mjs'
|
||||
@@ -154,51 +154,33 @@ export class ProxyController extends XoController<XoProxy> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a proxy
|
||||
* Returns the state of the proxy appliance updater (e.g. `xoa-up-to-date`, or a state ending with `-upgrade-needed`)
|
||||
*
|
||||
* Set `address` or `vmUuid` to `null` to remove it.
|
||||
* Before reading the state, sets the updater channel to the one expected by Xen Orchestra.
|
||||
* A successful result is cached for 60 seconds per proxy, errors are not cached.
|
||||
*
|
||||
* Only an administrator can change `address` or `vmUuid`
|
||||
*
|
||||
* Required privileges:
|
||||
* - resource: proxy, action: update (grants all fields)
|
||||
* - resource: proxy, action: update:name (if name is passed)
|
||||
* Required privilege:
|
||||
* - resource: proxy, action: read
|
||||
*
|
||||
* @example id "e625ea0c-a876-405a-b838-109d762efe88"
|
||||
* @example body { "name": "My proxy" }
|
||||
*/
|
||||
@Extension('x-mcp-exposure', 'confirm')
|
||||
@Patch('{id}')
|
||||
@Middlewares([
|
||||
json(),
|
||||
@Example(proxyApplianceUpdaterState)
|
||||
@Extension('x-mcp-exposure', 'allow')
|
||||
@Get('{id}/appliance_updater_state')
|
||||
@Middlewares(
|
||||
acl({
|
||||
resource: 'proxy',
|
||||
action: actionFromBody<'proxy'>('update:name'),
|
||||
action: 'read',
|
||||
objectId: 'params.id',
|
||||
getObject: ({ restApi }) => restApi.xoApp.getProxy,
|
||||
}),
|
||||
])
|
||||
@SuccessResponse(noContentResp.status, noContentResp.description)
|
||||
})
|
||||
)
|
||||
@SuccessResponse(200, 'OK')
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(invalidParameters.status, invalidParameters.description)
|
||||
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
|
||||
async updateProxy(
|
||||
@Path() id: string,
|
||||
@Body() body: { address?: string | null; name?: string; vmUuid?: string | null }
|
||||
): Promise<void> {
|
||||
const user = this.restApi.getCurrentUser()
|
||||
if (user.permission !== 'admin' && (body.address !== undefined || body.vmUuid !== undefined)) {
|
||||
throw forbiddenOperation('update proxy', 'only an administrator can change address or vmUuid')
|
||||
}
|
||||
|
||||
if (typeof body.vmUuid === 'string') {
|
||||
this.restApi.getObject<XoVm>(body.vmUuid as XoVm['id'], 'VM')
|
||||
}
|
||||
|
||||
await this.restApi.xoApp.updateProxy(id as XoProxy['id'], {
|
||||
...body,
|
||||
vmUuid: body.vmUuid as XoVm['id'] | null | undefined,
|
||||
})
|
||||
@Response(proxyUnreachableResp.status, proxyUnreachableResp.description)
|
||||
getProxyApplianceUpdaterState(@Path() id: string): ReturnType<XoApp['getProxyApplianceUpdaterState']> {
|
||||
return callProxy(this.restApi.xoApp.getProxyApplianceUpdaterState(id as XoProxy['id']))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,112 +1,69 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import { forbiddenOperation } from 'xo-common/api-errors.js'
|
||||
|
||||
import { ApiError } from '../helpers/error.helper.mjs'
|
||||
import { ProxyController } from './proxy.controller.mjs'
|
||||
import type { RestApi } from '../rest-api/rest-api.mjs'
|
||||
|
||||
function createController(checkProxyHealth: (id: string) => Promise<void>) {
|
||||
const calls: unknown[] = []
|
||||
const restApi = {
|
||||
xoApp: {
|
||||
checkProxyHealth: async (id: string) => {
|
||||
calls.push(['checkProxyHealth', id])
|
||||
return checkProxyHealth(id)
|
||||
},
|
||||
},
|
||||
} as unknown as RestApi
|
||||
const controller = new ProxyController(restApi)
|
||||
return { calls, controller }
|
||||
}
|
||||
|
||||
const proxyId = 'e625ea0c-a876-405a-b838-109d762efe88'
|
||||
|
||||
describe('ProxyController.getProxyHealth', () => {
|
||||
it('forwards the id and returns success when the proxy is reachable', async () => {
|
||||
const { calls, controller } = createController(async () => {})
|
||||
const updaterState = { level: 'info', message: 'xoa is up to date', state: 'xoa-up-to-date' }
|
||||
|
||||
assert.deepEqual(await controller.getProxyHealth(proxyId), { success: true })
|
||||
assert.deepEqual(calls, [['checkProxyHealth', proxyId]])
|
||||
})
|
||||
const unreachableErrors = [
|
||||
Object.assign(new TypeError('fetch failed'), { code: 'PROXY_UNREACHABLE' }),
|
||||
Object.assign(new Error('cannot get the proxy address'), { code: 'PROXY_UNREACHABLE' }),
|
||||
]
|
||||
|
||||
it('throws a 502 ApiError when the proxy is unreachable', async () => {
|
||||
const { controller } = createController(async () => {
|
||||
throw Object.assign(new TypeError('fetch failed'), { code: 'PROXY_UNREACHABLE' })
|
||||
})
|
||||
|
||||
await assert.rejects(
|
||||
controller.getProxyHealth(proxyId),
|
||||
error => error instanceof ApiError && error.status === 502 && error.message === 'Proxy unreachable'
|
||||
)
|
||||
})
|
||||
|
||||
it('rethrows unrelated errors unchanged', async () => {
|
||||
const unrelatedError = new Error('500 Internal Server Error')
|
||||
const { controller } = createController(async () => {
|
||||
throw unrelatedError
|
||||
})
|
||||
|
||||
await assert.rejects(controller.getProxyHealth(proxyId), error => error === unrelatedError)
|
||||
})
|
||||
})
|
||||
|
||||
const vmUuid = '3d0c7bd6-8b7e-4b2a-9c1f-6f0e5d4c3b2a'
|
||||
|
||||
function createUpdateController({ permission = 'admin' }: { permission?: string } = {}) {
|
||||
function createController(result: () => Promise<unknown>) {
|
||||
const calls: unknown[] = []
|
||||
const record =
|
||||
(method: string) =>
|
||||
async (...args: unknown[]) => {
|
||||
calls.push([method, ...args])
|
||||
return result()
|
||||
}
|
||||
const restApi = {
|
||||
getCurrentUser: () => ({ id: 'user-id', permission }),
|
||||
getObject: (...args: unknown[]) => {
|
||||
calls.push(['getObject', ...args])
|
||||
},
|
||||
xoApp: {
|
||||
updateProxy: async (...args: unknown[]) => {
|
||||
calls.push(['updateProxy', ...args])
|
||||
},
|
||||
checkProxyHealth: record('checkProxyHealth'),
|
||||
getProxyApplianceUpdaterState: record('getProxyApplianceUpdaterState'),
|
||||
},
|
||||
} as unknown as RestApi
|
||||
const controller = new ProxyController(restApi)
|
||||
return { calls, controller }
|
||||
}
|
||||
|
||||
describe('ProxyController.updateProxy', () => {
|
||||
it('forwards the body to updateProxy after checking the VM exists', async () => {
|
||||
const { calls, controller } = createUpdateController()
|
||||
const body = { address: '192.168.1.10:443', name: 'My proxy', vmUuid }
|
||||
for (const [method, xoAppMethod, xoAppResult, expected] of [
|
||||
['getProxyHealth', 'checkProxyHealth', undefined, { success: true }],
|
||||
['getProxyApplianceUpdaterState', 'getProxyApplianceUpdaterState', updaterState, updaterState],
|
||||
] as const) {
|
||||
describe(`ProxyController.${method}`, () => {
|
||||
it(`forwards the id to ${xoAppMethod} and returns the result`, async () => {
|
||||
const { calls, controller } = createController(async () => xoAppResult)
|
||||
|
||||
await controller.updateProxy(proxyId, body)
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
['getObject', vmUuid, 'VM'],
|
||||
['updateProxy', proxyId, body],
|
||||
])
|
||||
})
|
||||
|
||||
it('forwards null to remove address or vmUuid', async () => {
|
||||
const { calls, controller } = createUpdateController()
|
||||
|
||||
await controller.updateProxy(proxyId, { address: null, vmUuid: null })
|
||||
|
||||
assert.deepEqual(calls, [['updateProxy', proxyId, { address: null, vmUuid: null }]])
|
||||
})
|
||||
|
||||
it('lets a non-admin change the name', async () => {
|
||||
const { calls, controller } = createUpdateController({ permission: 'none' })
|
||||
|
||||
await controller.updateProxy(proxyId, { name: 'My proxy' })
|
||||
|
||||
assert.deepEqual(calls, [['updateProxy', proxyId, { name: 'My proxy', vmUuid: undefined }]])
|
||||
})
|
||||
|
||||
for (const body of [{ address: 'attacker:443' }, { address: null }, { vmUuid }, { vmUuid: null }]) {
|
||||
it(`refuses ${JSON.stringify(body)} to a non-admin`, async () => {
|
||||
const { calls, controller } = createUpdateController({ permission: 'none' })
|
||||
|
||||
await assert.rejects(controller.updateProxy(proxyId, { name: 'My proxy', ...body }), error =>
|
||||
forbiddenOperation.is(error)
|
||||
)
|
||||
assert.deepEqual(calls, [])
|
||||
assert.deepEqual(await controller[method](proxyId), expected)
|
||||
assert.deepEqual(calls, [[xoAppMethod, proxyId]])
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
for (const unreachableError of unreachableErrors) {
|
||||
it(`throws a 502 ApiError on "${unreachableError.message}"`, async () => {
|
||||
const { controller } = createController(async () => {
|
||||
throw unreachableError
|
||||
})
|
||||
|
||||
await assert.rejects(
|
||||
controller[method](proxyId),
|
||||
error => error instanceof ApiError && error.status === 502 && error.message === 'Proxy unreachable'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
it('rethrows unrelated errors unchanged', async () => {
|
||||
const unrelatedError = new Error('401 Unauthorized')
|
||||
const { controller } = createController(async () => {
|
||||
throw unrelatedError
|
||||
})
|
||||
|
||||
await assert.rejects(controller[method](proxyId), error => error === unrelatedError)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -33,7 +33,6 @@ import type {
|
||||
} from '@vates/types'
|
||||
|
||||
import { SUPPORTED_ACTIONS_BY_RESOURCE, type SupportedActions } from '@xen-orchestra/acl'
|
||||
import { invalidParameters } from 'xo-common/api-errors.js'
|
||||
|
||||
import { acl, actionsFromBody } from '../middlewares/acl.middleware.mjs'
|
||||
import { AlarmService } from '../alarms/alarm.service.mjs'
|
||||
@@ -245,11 +244,7 @@ export class VdiController extends XapiXoController<XoVdi> {
|
||||
await $xapi.call('VDI.set_name_description', $ref, name_description)
|
||||
}
|
||||
if (size !== undefined) {
|
||||
const currentSize = this.getObject(id as XoVdi['id']).size
|
||||
if (size < currentSize) {
|
||||
throw invalidParameters(`cannot set new size (${size}) below the current size (${currentSize})`)
|
||||
}
|
||||
await $xapi.callAsync('VDI.resize', $ref, size)
|
||||
await $xapi.VDI_resize($ref, size)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
XoBackupLog,
|
||||
} from '@vates/types'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import { createPredicate } from 'value-matcher'
|
||||
import { extractIdsFromSimplePattern } from '@xen-orchestra/backups/extractIdsFromSimplePattern.mjs'
|
||||
import { noSuchObject } from 'xo-common/api-errors.js'
|
||||
import { parse } from 'xo-remote-parser'
|
||||
@@ -361,23 +360,22 @@ export class XoaService {
|
||||
const nonReplicaVms = Object.values(this.#restApi.getObjectsByType<XoVm>('VM', { filter: vm => !isReplicaVm(vm) }))
|
||||
const restApi = this.#restApi
|
||||
const xoApp = restApi.xoApp
|
||||
function _extractVmIdsFromBackupJob(job: XoVmBackupJob) {
|
||||
let vmIds: XoVm['id'][]
|
||||
const backupJobService = this.#backupJobService
|
||||
async function _extractVmIdsFromBackupJob(job: XoVmBackupJob): Promise<XoVm['id'][]> {
|
||||
try {
|
||||
vmIds = extractIdsFromSimplePattern(job.vms)
|
||||
return extractIdsFromSimplePattern(job.vms)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
} catch (_) {
|
||||
const predicate = createPredicate(job.vms)
|
||||
vmIds = nonReplicaVms.filter(predicate).map(vm => vm.id)
|
||||
const isVmInJob = await backupJobService.getBackupJobVmMatcher(job)
|
||||
return nonReplicaVms.filter(isVmInJob).map(vm => vm.id)
|
||||
}
|
||||
return vmIds
|
||||
}
|
||||
function _processVmsProtection(job: XoVmBackupJob, isProtected: boolean) {
|
||||
async function _processVmsProtection(job: XoVmBackupJob, isProtected: boolean) {
|
||||
if (job.type !== BACKUP_TYPE.backup) {
|
||||
return
|
||||
}
|
||||
|
||||
_extractVmIdsFromBackupJob(job).forEach(vmId => {
|
||||
;(await _extractVmIdsFromBackupJob(job)).forEach(vmId => {
|
||||
_updateVmProtection(vmId, isProtected)
|
||||
})
|
||||
}
|
||||
@@ -434,7 +432,7 @@ export class XoaService {
|
||||
|
||||
for (const job of jobs) {
|
||||
if (!(await this.#backupJobService.backupJobHasAtLeastOneScheduleEnabled(job.id))) {
|
||||
_processVmsProtection(job, false)
|
||||
await _processVmsProtection(job, false)
|
||||
disabledJobs++
|
||||
continue
|
||||
}
|
||||
@@ -486,7 +484,7 @@ export class XoaService {
|
||||
}
|
||||
|
||||
if (last3BackupLogs.length === 0) {
|
||||
_processVmsProtection(job, false)
|
||||
await _processVmsProtection(job, false)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -500,11 +498,11 @@ export class XoaService {
|
||||
backupLogStatusesByVm[id].push(isSuccess)
|
||||
}
|
||||
|
||||
last3BackupLogs.forEach(jobLob => {
|
||||
const { tasks, status } = jobLob
|
||||
let jobVmIds: XoVm['id'][] | undefined
|
||||
for (const { tasks, status } of last3BackupLogs) {
|
||||
if (tasks === undefined) {
|
||||
const vmIds = _extractVmIdsFromBackupJob(job)
|
||||
vmIds.forEach(vmId => updateVmBackupLogStatuses(vmId, status === 'success'))
|
||||
jobVmIds ??= await _extractVmIdsFromBackupJob(job)
|
||||
jobVmIds.forEach(vmId => updateVmBackupLogStatuses(vmId, status === 'success'))
|
||||
} else {
|
||||
tasks.forEach(task => {
|
||||
if (task.data === undefined) {
|
||||
@@ -513,7 +511,7 @@ export class XoaService {
|
||||
updateVmBackupLogStatuses(task.data.id as XoVm['id'], task.status === 'success')
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
for (const [vmId, statuses] of Object.entries(backupLogStatusesByVm)) {
|
||||
_updateVmProtection(
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"license": "ISC",
|
||||
"private": false,
|
||||
"version": "1.2.0",
|
||||
"version": "1.4.0",
|
||||
"name": "@xen-orchestra/vmware-explorer",
|
||||
"description": "Reads the VMs and the disks of an ESXi host or a vCenter",
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@vates/node-vsphere-soap": "^2.2.0",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@vates/node-vsphere-soap": "^2.2.1",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"promise-toolbox": "^0.21.0",
|
||||
"undici": "^7.8.0"
|
||||
},
|
||||
|
||||
72
@xen-orchestra/vmware-explorer/vectura/Cargo.lock
generated
72
@xen-orchestra/vmware-explorer/vectura/Cargo.lock
generated
@@ -299,6 +299,21 @@ dependencies = [
|
||||
"miniz_oxide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foreign-types"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
|
||||
dependencies = [
|
||||
"foreign-types-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foreign-types-shared"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
|
||||
|
||||
[[package]]
|
||||
name = "fs_extra"
|
||||
version = "1.3.0"
|
||||
@@ -460,12 +475,59 @@ version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "openssl"
|
||||
version = "0.10.82"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"cfg-if",
|
||||
"foreign-types",
|
||||
"libc",
|
||||
"openssl-macros",
|
||||
"openssl-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openssl-macros"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openssl-probe"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
|
||||
|
||||
[[package]]
|
||||
name = "openssl-src"
|
||||
version = "300.6.1+3.6.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openssl-sys"
|
||||
version = "0.9.118"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
"openssl-src",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.34"
|
||||
@@ -801,13 +863,21 @@ version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "vcpkg"
|
||||
version = "0.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||
|
||||
[[package]]
|
||||
name = "vectura"
|
||||
version = "0.2.1"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"clap",
|
||||
"flate2",
|
||||
"openssl",
|
||||
"openssl-src",
|
||||
"quick-xml",
|
||||
"rcgen",
|
||||
"rustls",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "vectura"
|
||||
version = "0.2.1"
|
||||
version = "0.3.0"
|
||||
edition = "2024"
|
||||
description = "Standalone client for VMware's NFC disk-read protocol"
|
||||
# The license of the Xen Orchestra application components, see LICENSE.md at
|
||||
@@ -15,12 +15,20 @@ publish = false
|
||||
aws-lc-rs = "1.18.1"
|
||||
clap = { version = "4.6.6", features = ["derive"] }
|
||||
flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] }
|
||||
openssl = { version = "0.10.82", features = ["vendored"] }
|
||||
quick-xml = "0.42.0"
|
||||
rustls = "0.23"
|
||||
rustls-native-certs = "0.8.4"
|
||||
rustls-pki-types = "1.15.1"
|
||||
thiserror = "2.0.20"
|
||||
|
||||
[build-dependencies]
|
||||
# Not used by a build script: the entry only turns on a feature of the
|
||||
# OpenSSL build `openssl` asks for. Without DSO support OpenSSL cannot load
|
||||
# an engine or a provider from a file at run time, whatever a configuration
|
||||
# file or the environment asks.
|
||||
openssl-src = { version = "300.6.1", features = ["no-dso"] }
|
||||
|
||||
[dev-dependencies]
|
||||
rcgen = { version = "0.14.10", default-features = false, features = ["aws_lc_rs"] }
|
||||
serde_json = "1.0.151"
|
||||
|
||||
@@ -117,7 +117,8 @@ scripts/build.sh .
|
||||
```
|
||||
|
||||
The build is reproducible: `scripts/build.sh` keeps the paths of the machine
|
||||
out of the binary and refuses any zig or cargo-zigbuild but the versions the
|
||||
out of the binary, builds under `/tmp/vectura-build`, a path OpenSSL writes
|
||||
into the binary, and refuses any zig or cargo-zigbuild but the versions the
|
||||
workflow installs. Linux x86_64 machines build the same binary; macOS and
|
||||
aarch64 hosts are untested.
|
||||
|
||||
@@ -128,3 +129,8 @@ and Ubuntu 20.04. It needs [zig](https://ziglang.org/download/) 0.16.0 and:
|
||||
```sh
|
||||
cargo install --locked cargo-zigbuild@0.23.4
|
||||
```
|
||||
|
||||
OpenSSL is compiled from its sources, which takes perl, to run its
|
||||
`Configure` script, and make. Debian and Ubuntu install both with
|
||||
`build-essential`; on Fedora and RHEL, `perl-core` brings the perl modules
|
||||
`Configure` loads.
|
||||
|
||||
@@ -29,8 +29,10 @@ unmaintained = "workspace"
|
||||
unsound = "workspace"
|
||||
|
||||
[licenses]
|
||||
# What may enter the binary. OpenSSL is on the list for aws-lc-sys, which the
|
||||
# default rustls crypto provider builds on; nothing else needs it.
|
||||
# What may enter the binary. The OpenSSL license is on the list for
|
||||
# aws-lc-sys, which the default rustls crypto provider builds on; nothing else
|
||||
# needs it. The OpenSSL 3 sources the RSA key exchange fallback links are
|
||||
# under Apache-2.0.
|
||||
allow = [
|
||||
"0BSD",
|
||||
"Apache-2.0",
|
||||
|
||||
@@ -71,10 +71,14 @@ thirty minutes, makes the ordinary run not need one.
|
||||
|
||||
## Why rustls, synchronous I/O and two threads
|
||||
|
||||
- **rustls with aws-lc-rs, no OpenSSL.** One TLS stack, in the binary,
|
||||
with no system library to match at run time and no shell out. ESXi 6.0,
|
||||
7 and 8 hosts negotiate TLS 1.2 with ECDHE and AES-GCM on both ports,
|
||||
which rustls speaks.
|
||||
- **rustls with aws-lc-rs, and OpenSSL for one handshake.** The TLS
|
||||
stack is in the binary, with no system library to match at run time
|
||||
and no shell out. ESXi 6.0, 7 and 8 hosts negotiate TLS 1.2 with ECDHE
|
||||
and AES-GCM on both ports, which rustls speaks. The data port of some
|
||||
ESXi 6.5 hosts accepts RSA key exchange alone, which rustls leaves out
|
||||
on purpose, so a copy of OpenSSL is compiled in and used for that port
|
||||
when the host has refused rustls, and for nothing else. The security
|
||||
model says what such a session gives up.
|
||||
- **Synchronous `std` I/O, no async runtime.** A run is two sockets and
|
||||
two pipes. Two threads joined by a bounded channel cover that with
|
||||
back pressure for free and nothing to schedule. An async runtime would
|
||||
|
||||
@@ -64,6 +64,39 @@ presenting the same certificate. There is no flag to accept or refuse
|
||||
this: a 6.x host is served like any other, and the management port, which
|
||||
carries the password, is verified the same way on every host.
|
||||
|
||||
The data port of some ESXi 6.5 hosts accepts no ECDHE suite. When the
|
||||
host answers the first handshake with a `handshake_failure` alert, and
|
||||
only then, Vectura connects again and offers TLS 1.2 with RSA key
|
||||
exchange and AES-GCM. The certificate is judged by its thumbprint, compared
|
||||
with the ticket's once the handshake completes. By then the client has
|
||||
sent `ClientKeyExchange` and `Finished`, but no ticket and no application
|
||||
data go out before the check, and the second session must present the
|
||||
same certificate. With RSA key exchange the host signs
|
||||
nothing: it proves it holds the private key by decrypting the secret the
|
||||
client sent, which the `Finished` messages confirm, so the pinned
|
||||
certificate still authenticates it. Two things are given up, on such a
|
||||
host and on port 902 only:
|
||||
|
||||
- **Forward secrecy.** With RSA key exchange the session keys are sent
|
||||
encrypted to the host's key. Whoever records the session and later
|
||||
obtains that private key can read the disk that was carried.
|
||||
- **The choice of suites.** An attacker on the network can forge the
|
||||
alert, which is not authenticated, and so make Vectura offer RSA key
|
||||
exchange to a host that has ECDHE. They gain nothing at once, since
|
||||
the handshake still needs the host's private key, but the session
|
||||
they record loses forward secrecy.
|
||||
|
||||
There is no flag to forbid the retry, as there is none for the 6.x
|
||||
dialect. The transcript says when it happened, and the management port,
|
||||
which carries the password, never uses it.
|
||||
|
||||
OpenSSL is in the binary, built without the means to load code from a
|
||||
file. When the retry opens it, it still reads its configuration file if
|
||||
one exists: `/usr/local/ssl/openssl.cnf`, or the file `OPENSSL_CONF`
|
||||
names. Vectura sets the protocol version and the two suites itself after
|
||||
that. Whoever can write that file or set the environment of the process
|
||||
is already trusted with the password.
|
||||
|
||||
An attacker who controls the network between Vectura and the host sees
|
||||
TLS on 443 and TLS on 902, and can complete neither handshake without the
|
||||
host's private key. What they can do is drop the connection, which ends
|
||||
|
||||
@@ -27,6 +27,7 @@ are most likely to meet, what each means and what to do.
|
||||
|
||||
| Message | Meaning | Do |
|
||||
| ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `host refused every supported TLS suite (ECDHE, then RSA key exchange with AES-GCM)` | The data port accepts neither ECDHE nor RSA key exchange with AES-GCM. | Not supported: Vectura offers nothing weaker. |
|
||||
| `greeting: the host does not announce "NFCSSL supported"; announced: [...]` | The host cannot carry the disk inside a second TLS session. | Not seen on a supported host. `--transport nfc` would carry the disk in clear text; understand what that means before using it. |
|
||||
| `open "[ds] vm/x.vmdk": the host reported error 11: NfcAioProcessOpenFileMsg: permission check failed ...` | The ticket covers the files of the virtual machine `--vm-id` names, and this path is not one of them, or the account may not read it. | Check `--vm-id` against `--disk`. |
|
||||
| `... Thin/TBZ/Sparse disks cannot be opened in multiwriter mode` | The disk is the link a running virtual machine writes to. | Power the virtual machine off, or take a snapshot and read a base link. |
|
||||
|
||||
@@ -9,7 +9,7 @@ documentation is cited where it states the limit.
|
||||
|
||||
| Requirement | Detail |
|
||||
| ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| ESXi 7.x or 8.x, directly or through a vCenter; ESXi 6.x directly | With a vCenter, `--host` names the vCenter and the ticket names the ESXi host that holds the virtual machine; the data port is opened on that host. |
|
||||
| ESXi 6.x, 7.x or 8.x directly; 6.5, 6.7, 7.x or 8.x through a vCenter | With a vCenter, `--host` names the vCenter and the ticket names the ESXi host that holds the virtual machine; the data port is opened on that host. |
|
||||
| `SHA256 supported` in the data port's greeting, for the modern dialect | The ticket dialogue confirms the data port's certificate by its SHA-256. A host that does not announce it, ESXi 6.x, is read in the [legacy dialect](#esxi-6x-hosts). |
|
||||
| `NFCSSL supported` in the greeting, for `--transport nfcssl` | Without it, only `--transport nfc` can run, in clear text. Every host measured, 6.0 included, announces it. |
|
||||
| Port 443 and port 902 reachable | 443 for the management calls, on the vCenter when there is one; 902 for the greeting, the ticket dialogue and the disk, always on the ESXi host. |
|
||||
@@ -31,7 +31,8 @@ NBD export are the same; the disk session differs:
|
||||
| Compression | None, whatever `--compression` says: each read comes back as stored. | Measured on ESXi 6.0 |
|
||||
| Capacity | Not in the open reply. Found by 512-byte reads from the size the disk's geometry gives: 26 reads for an 8 GiB disk, 6 for a 24 GiB disk. | Measured on ESXi 6.0 |
|
||||
| Throughput | 3 to 5 MiB/s per process over a link with a 30 ms round trip. | Measured on ESXi 6.0 |
|
||||
| Versions | ESXi 6.0.0, reached directly. ESXi 6.5, 6.7 and a 6.x vCenter are untested. | |
|
||||
| Versions | ESXi 6.0.0, reached directly. ESXi 6.5 and 6.7, through a 6.x vCenter. | |
|
||||
| Ticket of a vCenter | Known to vpxa, the vCenter's agent on the host, not to hostd: the dialogue asks `PROXY vpxa-nfcssl`, which hostd would drop as `session ticket ... not found`. | ESXi 6.5 and 6.7 |
|
||||
|
||||
Several `serve` processes can read the same disk at once, each over its
|
||||
own session: two processes read about 9 MiB/s over the link above, where
|
||||
@@ -86,11 +87,12 @@ A run longer than the session lifetime serves the whole disk and exits
|
||||
|
||||
## TLS
|
||||
|
||||
| Item | Value | Source |
|
||||
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
|
||||
| Versions the hosts negotiate | TLS 1.2 on both ports, `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384` or the AES-128 variant | Measured; the vSphere 7 and 8 documentation on the default cipher suites |
|
||||
| Certificate on 902 | The same certificate as on 443 on every host measured | Measured |
|
||||
| Data port verification | The SHA-1 thumbprint in the ticket, the SHA-256 confirmed in the dialogue on ESXi 7 and later, and the second TLS session must present the certificate of the first | Vectura |
|
||||
| Item | Value | Source |
|
||||
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
|
||||
| Versions the hosts negotiate | TLS 1.2 on both ports, `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384` or the AES-128 variant | Measured; the vSphere 7 and 8 documentation on the default cipher suites |
|
||||
| RSA key exchange on 902 | Offered only after the host refused the first handshake with a `handshake_failure` alert: TLS 1.2, `TLS_RSA_WITH_AES_256_GCM_SHA384` or the AES-128 variant, no forward secrecy. Never on 443. | Vectura; reported on an ESXi 6.5 U3 host, not measured |
|
||||
| Certificate on 902 | The same certificate as on 443 on every host measured | Measured |
|
||||
| Data port verification | The SHA-1 thumbprint in the ticket, the SHA-256 confirmed in the dialogue on ESXi 7 and later, and the second TLS session must present the certificate of the first | Vectura |
|
||||
|
||||
## Throughput, measured
|
||||
|
||||
|
||||
@@ -12,26 +12,30 @@ is never delayed by the transcript.
|
||||
|
||||
## Lines, in session order
|
||||
|
||||
| Line | When | Fields |
|
||||
| --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `<call>: <status> in <n> ms` | After each management call on port 443: `RetrieveServiceContent`, `Login`, `RetrieveInternalContent`, `NfcGetVmFiles`, and `Logout` at the end. | The HTTP status the host answered, and the time from request to full response. |
|
||||
| `greeting: <capabilities>` | After the data port's greeting line. | The capabilities the host announced, comma separated, as the host wrote them, such as `NFCSSL supported, SHA256 supported`. |
|
||||
| `legacy dialect: no in-band thumbprint check, one read in flight, no compression` | After the greeting, when it does not announce `SHA256 supported`. | None: the line says what the legacy dialect gives up. |
|
||||
| `first session tls <version> <suite>` | After the first TLS handshake on the data port. | The protocol version and cipher suite, in rustls's names, such as `TLSv1_2 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`. |
|
||||
| `> <line>` | Each line sent in the ticket dialogue. | `SESSION <ticket>`, `BANNER `, `THUMBPRINT_SHA2 <tag>` or, on a legacy host, `THUMBPRINT <tag>`, `PROXY nfcssl` or `PROXY nfc`. |
|
||||
| `< <line>` | Each line the host answered. | The host's reply, such as `220 ...` or `200 <thumbprint>`. |
|
||||
| `second session tls <version> <suite>` | After the second TLS handshake, `--transport nfcssl` only. | As above. |
|
||||
| `> handshake type <n>` | Each handshake message sent. | The message type: 43, 33 and 51 are sent, then 54, 55 and 52 after the host's replies; only 43 and 33 on a legacy host. |
|
||||
| `< handshake type <n>` | Each handshake message received. | The message type: 36 and 51 after the first three, 52 after the last three; only 36 on a legacy host. |
|
||||
| `open: <capacity> bytes, sector size <n>` | After the host's open reply. | The disk's virtual capacity and its sector size, as reported; on a legacy host, the capacity the search found. |
|
||||
| `capacity search: <n> reads from the <size> bytes the geometry gives` | After the open, on a legacy host. | The 512-byte reads the capacity search took, and the size the open reply's geometry gives. |
|
||||
| `nbd option <n>: <outcome>` | After each NBD option. | The option number and how it was answered: `export`, `info`, `acknowledged`, `invalid` or `unsupported`. |
|
||||
| `nbd export: <size> bytes` | When transmission starts. | The export size sent to the client. |
|
||||
| `progress: served <n> GiB, compression ratio <r>, depth <d>` | Each time the bytes served cross a whole gibibyte. | Whole gibibytes served so far, wire bytes per served byte with two decimals, and the depth in use. |
|
||||
| `summary: bytes served <n>, wire bytes <n>, host reads <n>, elapsed <s> s` | When the session ends, before `Logout`. | Bytes served to the client, bytes received from the host for them, host reads issued, and the seconds since negotiation began, with one decimal. |
|
||||
| Line | When | Fields |
|
||||
| --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `<call>: <status> in <n> ms` | After each management call on port 443: `RetrieveServiceContent`, `Login`, `RetrieveInternalContent`, `NfcGetVmFiles`, and `Logout` at the end. | The HTTP status the host answered, and the time from request to full response. |
|
||||
| `greeting: <capabilities>` | After the data port's greeting line. | The capabilities the host announced, comma separated, as the host wrote them, such as `NFCSSL supported, SHA256 supported`. |
|
||||
| `legacy dialect: no in-band thumbprint check, one read in flight, no compression` | After the greeting, when it does not announce `SHA256 supported`. | None: the line says what the legacy dialect gives up. |
|
||||
| `first session tls fallback: host refused ECDHE, retrying with RSA key exchange` | After the host refused the first TLS handshake on the data port for want of a common suite. | None: the data port is connected to again and offered RSA key exchange, for both sessions. |
|
||||
| `first session tls <version> <suite>` | After the first TLS handshake on the data port. | The protocol version in rustls's name and the cipher suite in its IANA name, such as `TLSv1_2 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`. |
|
||||
| `> <line>` | Each line sent in the ticket dialogue. | `SESSION <ticket>`, `BANNER `, `THUMBPRINT_SHA2 <tag>` or, on a legacy host, `THUMBPRINT <tag>`, `PROXY nfcssl` or `PROXY nfc`; on a legacy host reached through a vCenter, `PROXY vpxa-nfcssl` or `PROXY vpxa-nfc`. |
|
||||
| `< <line>` | Each line the host answered. | The host's reply, such as `220 ...`, `200 <thumbprint>` or `200 Connect ha-nfcssl`; `200 Connect vpxa-nfcssl` when vpxa was asked. |
|
||||
| `second session tls <version> <suite>` | After the second TLS handshake, `--transport nfcssl` only. | As above. |
|
||||
| `> handshake type <n>` | Each handshake message sent. | The message type: 43, 33 and 51 are sent, then 54, 55 and 52 after the host's replies; only 43 and 33 on a legacy host. |
|
||||
| `< handshake type <n>` | Each handshake message received. | The message type: 36 and 51 after the first three, 52 after the last three; only 36 on a legacy host. |
|
||||
| `open: <capacity> bytes, sector size <n>` | After the host's open reply. | The disk's virtual capacity and its sector size, as reported; on a legacy host, the capacity the search found. |
|
||||
| `capacity search: <n> reads from the <size> bytes the geometry gives` | After the open, on a legacy host. | The 512-byte reads the capacity search took, and the size the open reply's geometry gives. |
|
||||
| `nbd option <n>: <outcome>` | After each NBD option. | The option number and how it was answered: `export`, `info`, `acknowledged`, `invalid` or `unsupported`. |
|
||||
| `nbd export: <size> bytes` | When transmission starts. | The export size sent to the client. |
|
||||
| `progress: served <n> GiB, compression ratio <r>, depth <d>` | Each time the bytes served cross a whole gibibyte. | Whole gibibytes served so far, wire bytes per served byte with two decimals, and the depth in use. |
|
||||
| `summary: bytes served <n>, wire bytes <n>, host reads <n>, elapsed <s> s` | When the session ends, before `Logout`. | Bytes served to the client, bytes received from the host for them, host reads issued, and the seconds since negotiation began, with one decimal. |
|
||||
|
||||
`fingerprint --verbose` writes `<port> tls <version> <suite>` per port,
|
||||
with `443` or the value of `--nfc-port` as the port.
|
||||
with `443` or the value of `--nfc-port` as the port, as each handshake
|
||||
completes. When the data port refuses ECDHE, `<port> tls fallback: host
|
||||
refused ECDHE, retrying with RSA key exchange` comes before that port's
|
||||
line.
|
||||
|
||||
## Ratios
|
||||
|
||||
|
||||
@@ -39,6 +39,29 @@ RUSTFLAGS="--remap-path-prefix=${CARGO_HOME:-$HOME/.cargo}=/cargo --remap-path-p
|
||||
export RUSTFLAGS
|
||||
unset CARGO_ENCODED_RUSTFLAGS
|
||||
|
||||
cargo zigbuild --locked --release --target x86_64-unknown-linux-gnu.2.31
|
||||
# OpenSSL, which is compiled from its sources, writes into the binary the date
|
||||
# of its build and two absolute paths: the directory it is built in, under the
|
||||
# target directory, and the compiler, a wrapper cargo-zigbuild keeps in its
|
||||
# cache. No flag remaps them, so all three are the same on every machine. The
|
||||
# two directories are named in the binary and never read: OpenSSL is built
|
||||
# without the support for loading code at run time. Its configuration file is
|
||||
# another matter, see the security model.
|
||||
build=/tmp/vectura-build
|
||||
# /tmp is shared: a directory someone else prepared could plant what gets
|
||||
# linked into the binary.
|
||||
mkdir -p "$build"
|
||||
if [ -L "$build" ] || [ ! -O "$build" ]; then
|
||||
echo "$build is not a directory of yours, refusing to build in it" >&2
|
||||
exit 1
|
||||
fi
|
||||
chmod 700 "$build"
|
||||
export CARGO_TARGET_DIR=$build/target
|
||||
export CARGO_ZIGBUILD_CACHE_DIR=$build/zigbuild
|
||||
export SOURCE_DATE_EPOCH=1
|
||||
|
||||
# cargo-zigbuild names the directory of that wrapper after its own path, which
|
||||
# depends on the home directory: it runs from a copy at a fixed path.
|
||||
install -m 755 "$(command -v cargo-zigbuild)" "$build/cargo-zigbuild"
|
||||
"$build/cargo-zigbuild" zigbuild --locked --release --target x86_64-unknown-linux-gnu.2.31
|
||||
# the glibc suffix is for zig only: the binary lands under the plain triple
|
||||
install -m 755 target/x86_64-unknown-linux-gnu/release/vectura "$out"
|
||||
install -m 755 "$CARGO_TARGET_DIR/x86_64-unknown-linux-gnu/release/vectura" "$out"
|
||||
|
||||
@@ -297,21 +297,21 @@ fn report_parse(error: &clap::Error) -> ExitCode {
|
||||
/// Probes both ports, then prints their thumbprints, management port first.
|
||||
fn fingerprint(arguments: &Fingerprint) -> Result<(), Failure> {
|
||||
let HostPort { host, port } = &arguments.host;
|
||||
let transcript = Transcript::new(arguments.verbose);
|
||||
let management = tls::connect(host, *port)
|
||||
.and_then(|mut stream| tls::capture(&mut stream, host))
|
||||
.map_err(|source| Failure::Management {
|
||||
address: format!("{host}:{port}"),
|
||||
source,
|
||||
})?;
|
||||
let data = nfc::capture(host, arguments.nfc_port).map_err(|source| Failure::Data {
|
||||
address: format!("{host}:{}", arguments.nfc_port),
|
||||
source,
|
||||
})?;
|
||||
transcript.tls(&port.to_string(), management.version, management.suite);
|
||||
let data =
|
||||
nfc::capture(host, arguments.nfc_port, transcript).map_err(|source| Failure::Data {
|
||||
address: format!("{host}:{}", arguments.nfc_port),
|
||||
source,
|
||||
})?;
|
||||
transcript.tls(&arguments.nfc_port.to_string(), data.version, data.suite);
|
||||
let presented = [(*port, management), (arguments.nfc_port, data)];
|
||||
let transcript = Transcript::new(arguments.verbose);
|
||||
for (port, presented) in &presented {
|
||||
transcript.tls(&port.to_string(), presented.version, presented.suite);
|
||||
}
|
||||
let mut stdout = io::stdout().lock();
|
||||
for (port, presented) in &presented {
|
||||
writeln!(
|
||||
|
||||
@@ -21,7 +21,7 @@ use std::net::TcpStream;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::str::FromStr;
|
||||
|
||||
use rustls::{ClientConnection, Stream};
|
||||
use rustls::Stream;
|
||||
use rustls_pki_types::CertificateDer;
|
||||
|
||||
use crate::transcript::Transcript;
|
||||
@@ -64,19 +64,19 @@ pub enum Transport {
|
||||
}
|
||||
|
||||
impl Transport {
|
||||
/// The dialogue line asking for this transport, without its line end.
|
||||
const fn proxy(self) -> &'static str {
|
||||
match self {
|
||||
Transport::Nfcssl => "PROXY nfcssl",
|
||||
Transport::Nfc => "PROXY nfc",
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole reply granting this transport; nothing else is written before it.
|
||||
const fn granted(self) -> &'static str {
|
||||
match self {
|
||||
Transport::Nfcssl => "200 Connect ha-nfcssl",
|
||||
Transport::Nfc => "200 Connect ha-nfc",
|
||||
/// The dialogue line asking for this transport, without its line end,
|
||||
/// and the whole reply granting it.
|
||||
///
|
||||
/// With `vpxa`, it is asked of vpxa, the vCenter's agent on the host,
|
||||
/// instead of hostd: the hostd of an ESXi 6.5 or 6.7 host drops a
|
||||
/// ticket its vCenter issued as not found, since the vCenter
|
||||
/// registered it with vpxa.
|
||||
const fn proxy(self, vpxa: bool) -> (&'static str, &'static str) {
|
||||
match (self, vpxa) {
|
||||
(Transport::Nfcssl, false) => ("PROXY nfcssl", "200 Connect ha-nfcssl"),
|
||||
(Transport::Nfc, false) => ("PROXY nfc", "200 Connect ha-nfc"),
|
||||
(Transport::Nfcssl, true) => ("PROXY vpxa-nfcssl", "200 Connect vpxa-nfcssl"),
|
||||
(Transport::Nfc, true) => ("PROXY vpxa-nfc", "200 Connect vpxa-nfc"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -171,6 +171,11 @@ pub enum Error {
|
||||
/// The SHA-256 thumbprint of the certificate the first session verified.
|
||||
presented: String,
|
||||
},
|
||||
/// The connection reopened for RSA key exchange was greeted differently.
|
||||
#[error(
|
||||
"greeting: the host announced other capabilities on the connection reopened for RSA key exchange"
|
||||
)]
|
||||
GreetingChanged,
|
||||
/// The second TLS session did not present the certificate the first one did.
|
||||
#[error("the second tls session presented another certificate than the first")]
|
||||
Certificate,
|
||||
@@ -330,14 +335,54 @@ pub fn read_greeting<R: Read>(reader: &mut R) -> Result<greeting::Greeting, Erro
|
||||
/// Reads a host's data-port greeting, then captures the certificate TLS presents.
|
||||
///
|
||||
/// TLS starts on the same connection right after the greeting line,
|
||||
/// whatever capabilities it announces.
|
||||
/// whatever capabilities it announces. A host that refuses the ECDHE suites
|
||||
/// is asked again on a new connection, with RSA key exchange, which
|
||||
/// `transcript` says under the port's number. That connection must be
|
||||
/// greeted as the first one was.
|
||||
///
|
||||
/// # Errors
|
||||
/// When connecting, reading the greeting or the TLS handshake fails.
|
||||
pub(crate) fn capture(host: &str, port: u16) -> Result<tls::Presented, Error> {
|
||||
/// When connecting, reading the greeting or the TLS handshake fails, or the
|
||||
/// reopened connection is greeted differently.
|
||||
pub(crate) fn capture(
|
||||
host: &str,
|
||||
port: u16,
|
||||
transcript: Transcript,
|
||||
) -> Result<tls::Presented, Error> {
|
||||
let mut stream = tls::connect(host, port)?;
|
||||
read_greeting(&mut stream)?;
|
||||
Ok(tls::capture(&mut stream, host)?)
|
||||
let greeted = read_greeting(&mut stream)?;
|
||||
match tls::capture(&mut stream, host) {
|
||||
Err(error) if error.refused_suites() => {
|
||||
transcript.fallback(&port.to_string());
|
||||
let (stream, again) = greet_again(host, port)?;
|
||||
// Another greeting means another peer: its certificate is not
|
||||
// the data port's.
|
||||
if again != greeted {
|
||||
return Err(Error::GreetingChanged);
|
||||
}
|
||||
Ok(tls::capture_rsa_kx(&stream)?)
|
||||
}
|
||||
presented => Ok(presented?),
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a new connection to a host that refused the ECDHE suites, past its greeting.
|
||||
///
|
||||
/// The refusal is a fatal alert, after which the host closes the connection,
|
||||
/// so the RSA key exchange retry cannot reuse it. The greeting read on the
|
||||
/// new connection is returned for the caller to compare with the first one.
|
||||
fn greet_again(host: &str, port: u16) -> Result<(TcpStream, greeting::Greeting), Error> {
|
||||
let mut stream = tls::connect(host, port)?;
|
||||
let greeted = read_greeting(&mut stream)?;
|
||||
Ok((stream, greeted))
|
||||
}
|
||||
|
||||
/// The byte stream of `session`, whose records travel on `stream`.
|
||||
fn wire<'a>(session: &'a mut tls::Session, stream: &'a mut TcpStream) -> Box<dyn Wire + 'a> {
|
||||
match session {
|
||||
tls::Session::Ecdhe(connection) => Box::new(Stream::new(&mut **connection, stream)),
|
||||
// The session owns its clone of the socket.
|
||||
tls::Session::RsaKx(session) => Box::new(session),
|
||||
}
|
||||
}
|
||||
|
||||
/// An established data session, ready to open a disk.
|
||||
@@ -353,7 +398,7 @@ pub struct Connection {
|
||||
/// What carries the disk session: the second TLS session, or the socket in clear.
|
||||
#[derive(Debug)]
|
||||
enum Plane {
|
||||
Tls(Box<ClientConnection>),
|
||||
Tls(tls::Session),
|
||||
Clear,
|
||||
}
|
||||
|
||||
@@ -370,9 +415,14 @@ impl Connection {
|
||||
/// present the certificate `pin` names, which is the ticket's thumbprint;
|
||||
/// `secret` is the ticket presented in that session. With `nfcssl` the
|
||||
/// second TLS session must present the same certificate; with `nfc` the
|
||||
/// connection goes on in clear. The handshake, hello, version and
|
||||
/// capabilities exchanges follow, each waiting for its reply; a legacy
|
||||
/// host gets the start of the handshake alone.
|
||||
/// connection goes on in clear. A host that refuses the ECDHE suites is
|
||||
/// connected to again and both sessions use RSA key exchange, under the
|
||||
/// same pin. `vcenter` says a vCenter issued the ticket: a legacy host
|
||||
/// is then asked for the transport of vpxa, the vCenter's agent on the
|
||||
/// host; since vCenter 7.0 U1, hostd serves a vCenter's tickets, as it
|
||||
/// does a host's own. The handshake, hello, version and capabilities
|
||||
/// exchanges follow, each waiting for its reply; a legacy host gets the
|
||||
/// start of the handshake alone.
|
||||
///
|
||||
/// # Errors
|
||||
/// When any phase fails, naming that phase.
|
||||
@@ -382,6 +432,7 @@ impl Connection {
|
||||
secret: &str,
|
||||
pin: &tls::Pin,
|
||||
transport: Transport,
|
||||
vcenter: bool,
|
||||
transcript: Transcript,
|
||||
) -> Result<Connection, Error> {
|
||||
let mut stream = tls::connect(host, port)?;
|
||||
@@ -395,33 +446,53 @@ impl Connection {
|
||||
greeted.require(greeting::NFCSSL_SUPPORTED)?;
|
||||
}
|
||||
let client = tls::Client::new(&tls::Trust::Pin(pin.clone()))?;
|
||||
let mut first = client.handshake(&mut stream, host)?;
|
||||
let (version, suite) = tls::negotiated(&first)?;
|
||||
let mut first = match client.handshake(&mut stream, host) {
|
||||
Ok(connection) => tls::Session::Ecdhe(Box::new(connection)),
|
||||
Err(error) if error.refused_suites() => {
|
||||
transcript.fallback("first session");
|
||||
let (reopened, again) = greet_again(host, port)?;
|
||||
// The dialect and transport were chosen from the first
|
||||
// greeting: another one means another peer or another state.
|
||||
if again != greeted {
|
||||
return Err(Error::GreetingChanged);
|
||||
}
|
||||
stream = reopened;
|
||||
tls::rsa_kx(&stream, pin)?
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
let (version, suite) = first.negotiated()?;
|
||||
transcript.tls("first session", version, suite);
|
||||
let certificate = tls::peer_certificate(&first)?;
|
||||
let certificate = first.certificate()?;
|
||||
let tag = draw_tag()?;
|
||||
dialogue(
|
||||
&mut Stream::new(&mut first, &mut stream),
|
||||
&mut wire(&mut first, &mut stream),
|
||||
secret,
|
||||
&tag,
|
||||
&certificate,
|
||||
transport,
|
||||
transport.proxy(vcenter && dialect == Dialect::Legacy),
|
||||
dialect,
|
||||
transcript,
|
||||
)?;
|
||||
// The PROXY reply is the last thing the host sends in the first
|
||||
// session, so nothing of it is left unread; dropping the connection
|
||||
// without a close notify keeps the stream clear for what follows.
|
||||
let fallback = matches!(first, tls::Session::RsaKx(_));
|
||||
drop(first);
|
||||
let plane = match transport {
|
||||
Transport::Nfcssl => {
|
||||
let session = client.handshake(&mut stream, host)?;
|
||||
let (version, suite) = tls::negotiated(&session)?;
|
||||
// The host that refused ECDHE once is not offered it again.
|
||||
let session = if fallback {
|
||||
tls::rsa_kx(&stream, pin)?
|
||||
} else {
|
||||
tls::Session::Ecdhe(Box::new(client.handshake(&mut stream, host)?))
|
||||
};
|
||||
let (version, suite) = session.negotiated()?;
|
||||
transcript.tls("second session", version, suite);
|
||||
if tls::peer_certificate(&session)? != certificate {
|
||||
if session.certificate()? != certificate {
|
||||
return Err(Error::Certificate);
|
||||
}
|
||||
Plane::Tls(Box::new(session))
|
||||
Plane::Tls(session)
|
||||
}
|
||||
Transport::Nfc => Plane::Clear,
|
||||
};
|
||||
@@ -587,7 +658,7 @@ impl Connection {
|
||||
|
||||
fn data(&mut self) -> Box<dyn Wire + '_> {
|
||||
match &mut self.plane {
|
||||
Plane::Tls(session) => Box::new(Stream::new(&mut **session, &mut self.stream)),
|
||||
Plane::Tls(session) => wire(session, &mut self.stream),
|
||||
Plane::Clear => Box::new(&mut self.stream),
|
||||
}
|
||||
}
|
||||
@@ -657,14 +728,14 @@ fn draw_tag() -> Result<[u8; handshake::TAG_LEN], Error> {
|
||||
/// `200 <hash>`, where the hash must be the SHA-256 thumbprint of the
|
||||
/// certificate this session verified; a legacy host is asked `THUMBPRINT
|
||||
/// <tag>` instead, and its reply, a SHA-1 hash, must only start with `200 `.
|
||||
/// The `PROXY` line asking for `transport` must be answered with exactly
|
||||
/// the line granting it; nothing else is written before that.
|
||||
/// The `PROXY` line, from [`Transport::proxy`], must be answered with
|
||||
/// exactly the line granting it; nothing else is written before that.
|
||||
fn dialogue<S: Read + Write>(
|
||||
stream: &mut S,
|
||||
secret: &str,
|
||||
tag: &[u8; handshake::TAG_LEN],
|
||||
certificate: &CertificateDer<'_>,
|
||||
transport: Transport,
|
||||
(proxy, granted): (&'static str, &'static str),
|
||||
dialect: Dialect,
|
||||
transcript: Transcript,
|
||||
) -> Result<(), Error> {
|
||||
@@ -705,17 +776,13 @@ fn dialogue<S: Read + Write>(
|
||||
});
|
||||
}
|
||||
}
|
||||
send(
|
||||
stream,
|
||||
format!("{}\r\n", transport.proxy()).as_bytes(),
|
||||
"dialogue",
|
||||
)?;
|
||||
transcript.sent(transport.proxy());
|
||||
send(stream, format!("{proxy}\r\n").as_bytes(), "dialogue")?;
|
||||
transcript.sent(proxy);
|
||||
let answer = reply(stream)?;
|
||||
transcript.received(&answer);
|
||||
if answer != transport.granted() {
|
||||
if answer != granted {
|
||||
return Err(Error::Dialogue {
|
||||
command: transport.proxy(),
|
||||
command: proxy,
|
||||
reply: answer,
|
||||
});
|
||||
}
|
||||
@@ -1130,10 +1197,76 @@ mod tests {
|
||||
use super::*;
|
||||
use greeting::ESXI_8;
|
||||
use std::io::Cursor;
|
||||
use std::net::TcpListener;
|
||||
use std::thread;
|
||||
|
||||
const TAG: &[u8; 16] = b"ABCDEFGHIJKLMNOP";
|
||||
const QUIET: Transcript = Transcript::new(false);
|
||||
|
||||
/// A fatal `handshake_failure` alert, as one TLS 1.2 record.
|
||||
const HANDSHAKE_FAILURE: [u8; 7] = [0x15, 0x03, 0x03, 0x00, 0x02, 0x02, 0x28];
|
||||
|
||||
/// A host that refuses ECDHE, then greets the reopened connection as another peer.
|
||||
///
|
||||
/// Returns its port and what the client wrote on the reopened connection.
|
||||
fn greeting_differently_after_refusing_ecdhe() -> (u16, thread::JoinHandle<Vec<u8>>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let host = thread::spawn(move || {
|
||||
let (mut first, _) = listener.accept().unwrap();
|
||||
first.write_all(ESXI_8).unwrap();
|
||||
let mut header = [0_u8; 5];
|
||||
first.read_exact(&mut header).unwrap();
|
||||
let mut hello = vec![0_u8; usize::from(u16::from_be_bytes([header[3], header[4]]))];
|
||||
first.read_exact(&mut hello).unwrap();
|
||||
first.write_all(&HANDSHAKE_FAILURE).unwrap();
|
||||
drop(first);
|
||||
let (mut second, _) = listener.accept().unwrap();
|
||||
second
|
||||
.write_all(b"220 VMware Authentication Daemon Version 1.10: SSL Required, NFCSSL supported/t\r\n")
|
||||
.unwrap();
|
||||
let mut received = Vec::new();
|
||||
// The client leaves at once; whatever it wrote first is returned.
|
||||
let _ = second.read_to_end(&mut received);
|
||||
received
|
||||
});
|
||||
(port, host)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_greeting_differently_after_refusing_ecdhe_is_not_offered_rsa_key_exchange() {
|
||||
let (port, host) = greeting_differently_after_refusing_ecdhe();
|
||||
let pin = tls::Pin::sha256(&tls::sha256(b"a certificate")).unwrap();
|
||||
|
||||
let error = Connection::establish(
|
||||
"127.0.0.1",
|
||||
port,
|
||||
"ticket",
|
||||
&pin,
|
||||
Transport::Nfcssl,
|
||||
false,
|
||||
QUIET,
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(matches!(error, Error::GreetingChanged), "{error:?}");
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"greeting: the host announced other capabilities on the connection reopened for RSA key exchange"
|
||||
);
|
||||
assert!(host.join().unwrap().is_empty(), "no handshake was started");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_capture_greeted_differently_after_refusing_ecdhe_reports_no_thumbprint() {
|
||||
let (port, host) = greeting_differently_after_refusing_ecdhe();
|
||||
|
||||
let error = capture("127.0.0.1", port, QUIET).unwrap_err();
|
||||
|
||||
assert!(matches!(error, Error::GreetingChanged), "{error:?}");
|
||||
assert!(host.join().unwrap().is_empty(), "no handshake was started");
|
||||
}
|
||||
|
||||
/// A scripted peer: replies come from `input`, each write the client makes lands in `writes`.
|
||||
///
|
||||
/// Reads time out until `unlock_at` bytes have been written, the way a
|
||||
@@ -1303,7 +1436,7 @@ mod tests {
|
||||
"ticket-0",
|
||||
TAG,
|
||||
&certificate(),
|
||||
Transport::Nfcssl,
|
||||
Transport::Nfcssl.proxy(false),
|
||||
Dialect::Modern,
|
||||
QUIET,
|
||||
)
|
||||
@@ -1328,7 +1461,7 @@ mod tests {
|
||||
"ticket-0",
|
||||
TAG,
|
||||
&certificate(),
|
||||
Transport::Nfc,
|
||||
Transport::Nfc.proxy(false),
|
||||
Dialect::Modern,
|
||||
QUIET,
|
||||
)
|
||||
@@ -1350,7 +1483,7 @@ mod tests {
|
||||
"ticket-0",
|
||||
TAG,
|
||||
&certificate(),
|
||||
Transport::Nfc,
|
||||
Transport::Nfc.proxy(false),
|
||||
Dialect::Modern,
|
||||
QUIET,
|
||||
)
|
||||
@@ -1371,7 +1504,7 @@ mod tests {
|
||||
"ticket-0",
|
||||
TAG,
|
||||
&certificate(),
|
||||
Transport::Nfcssl,
|
||||
Transport::Nfcssl.proxy(false),
|
||||
Dialect::Modern,
|
||||
QUIET,
|
||||
)
|
||||
@@ -1393,7 +1526,7 @@ mod tests {
|
||||
"ticket-0",
|
||||
TAG,
|
||||
&certificate(),
|
||||
Transport::Nfcssl,
|
||||
Transport::Nfcssl.proxy(false),
|
||||
Dialect::Modern,
|
||||
QUIET,
|
||||
)
|
||||
@@ -1416,7 +1549,7 @@ mod tests {
|
||||
"ticket-0",
|
||||
TAG,
|
||||
&certificate(),
|
||||
Transport::Nfcssl,
|
||||
Transport::Nfcssl.proxy(false),
|
||||
Dialect::Modern,
|
||||
QUIET,
|
||||
)
|
||||
@@ -1445,7 +1578,7 @@ mod tests {
|
||||
"ticket-0",
|
||||
TAG,
|
||||
&certificate(),
|
||||
Transport::Nfcssl,
|
||||
Transport::Nfcssl.proxy(false),
|
||||
Dialect::Modern,
|
||||
QUIET,
|
||||
)
|
||||
@@ -1466,7 +1599,7 @@ mod tests {
|
||||
"ticket-0",
|
||||
TAG,
|
||||
&certificate(),
|
||||
Transport::Nfcssl,
|
||||
Transport::Nfcssl.proxy(false),
|
||||
Dialect::Modern,
|
||||
QUIET,
|
||||
)
|
||||
@@ -2006,7 +2139,7 @@ mod tests {
|
||||
"ticket-0",
|
||||
TAG,
|
||||
&certificate(),
|
||||
Transport::Nfcssl,
|
||||
Transport::Nfcssl.proxy(false),
|
||||
Dialect::Legacy,
|
||||
QUIET,
|
||||
)
|
||||
@@ -2027,7 +2160,7 @@ mod tests {
|
||||
"ticket-0",
|
||||
TAG,
|
||||
&certificate(),
|
||||
Transport::Nfcssl,
|
||||
Transport::Nfcssl.proxy(false),
|
||||
Dialect::Legacy,
|
||||
QUIET,
|
||||
)
|
||||
|
||||
@@ -139,6 +139,7 @@ fn export<R: Read + Send + 'static, W: Write>(
|
||||
&ticket.secret,
|
||||
&ticket.thumbprint,
|
||||
target.transport,
|
||||
session.vcenter(),
|
||||
target.transcript,
|
||||
)?;
|
||||
let disk = match connection.open(&target.disk) {
|
||||
|
||||
@@ -144,6 +144,7 @@ pub struct Session {
|
||||
port: u16,
|
||||
client: tls::Client,
|
||||
manager: String,
|
||||
vcenter: bool,
|
||||
cookie: Cookie,
|
||||
transcript: Transcript,
|
||||
}
|
||||
@@ -173,7 +174,7 @@ impl Session {
|
||||
&this(SERVICE_INSTANCE, SERVICE_INSTANCE),
|
||||
transcript,
|
||||
)?;
|
||||
let manager = service_content(&String::from_utf8_lossy(&content.body))?;
|
||||
let (manager, vcenter) = service_content(&String::from_utf8_lossy(&content.body))?;
|
||||
let inner = format!(
|
||||
"{}<userName>{}</userName><password>{}</password>",
|
||||
this("SessionManager", &manager),
|
||||
@@ -198,11 +199,18 @@ impl Session {
|
||||
port,
|
||||
client,
|
||||
manager,
|
||||
vcenter,
|
||||
cookie: Cookie(cookie),
|
||||
transcript,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a vCenter answered, as its service content's `about.apiType` states.
|
||||
#[must_use]
|
||||
pub const fn vcenter(&self) -> bool {
|
||||
self.vcenter
|
||||
}
|
||||
|
||||
/// Asks the NFC service for a fresh ticket to the files of the VM `vm_id` names.
|
||||
///
|
||||
/// # Errors
|
||||
@@ -303,12 +311,15 @@ fn this(kind: &str, reference: &str) -> String {
|
||||
format!("<_this type=\"{kind}\">{}</_this>", escape(reference))
|
||||
}
|
||||
|
||||
/// Returns the session manager the service content names.
|
||||
fn service_content(content: &str) -> Result<String, Error> {
|
||||
element(content, "sessionManager").ok_or(Error::Missing {
|
||||
/// Returns the session manager the service content names, and whether
|
||||
/// `about.apiType` says a vCenter answered.
|
||||
fn service_content(content: &str) -> Result<(String, bool), Error> {
|
||||
let manager = element(content, "sessionManager").ok_or(Error::Missing {
|
||||
call: "RetrieveServiceContent",
|
||||
element: "sessionManager",
|
||||
})
|
||||
})?;
|
||||
let vcenter = element(content, "apiType").as_deref() == Some("VirtualCenter");
|
||||
Ok((manager, vcenter))
|
||||
}
|
||||
|
||||
/// Reads the ticket out of an `NfcGetVmFiles` reply.
|
||||
@@ -398,6 +409,7 @@ mod tests {
|
||||
))
|
||||
.unwrap(),
|
||||
manager: "ha-sessionmgr".to_owned(),
|
||||
vcenter: false,
|
||||
cookie: Cookie("vmware_soap_session=\"mock-cookie\"".to_owned()),
|
||||
transcript: Transcript::new(false),
|
||||
};
|
||||
@@ -474,16 +486,22 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn an_esxi_service_content_yields_its_session_manager() {
|
||||
assert_eq!(service_content(SERVICE_CONTENT).unwrap(), "ha-sessionmgr");
|
||||
assert_eq!(
|
||||
service_content(SERVICE_CONTENT).unwrap(),
|
||||
("ha-sessionmgr".to_owned(), false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vcenter_service_content_yields_its_session_manager() {
|
||||
fn a_vcenter_service_content_yields_its_session_manager_and_says_so() {
|
||||
let content = SERVICE_CONTENT
|
||||
.replace("HostAgent", "VirtualCenter")
|
||||
.replace("ha-sessionmgr", "SessionManager");
|
||||
|
||||
assert_eq!(service_content(&content).unwrap(), "SessionManager");
|
||||
assert_eq!(
|
||||
service_content(&content).unwrap(),
|
||||
("SessionManager".to_owned(), true)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -5,6 +5,10 @@
|
||||
//! accept-everything verifier never leaves this module: [`capture`] runs a TLS
|
||||
//! handshake with it, sends nothing afterwards and drops the connection
|
||||
//! before returning.
|
||||
//!
|
||||
//! rustls only knows ECDHE key exchange. A data port that refuses it is
|
||||
//! retried through [`rsa_kx`], which the `legacy` module runs on OpenSSL; a
|
||||
//! [`Session`] is either of the two.
|
||||
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
@@ -13,15 +17,19 @@ use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use aws_lc_rs::digest;
|
||||
use openssl::error::ErrorStack;
|
||||
use openssl::ssl::SslStream;
|
||||
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
|
||||
use rustls::crypto::aws_lc_rs::default_provider;
|
||||
use rustls::crypto::{CryptoProvider, verify_tls12_signature, verify_tls13_signature};
|
||||
use rustls::{
|
||||
CertificateError, CipherSuite, ClientConfig, ClientConnection, DigitallySignedStruct,
|
||||
ProtocolVersion, RootCertStore, SignatureScheme,
|
||||
AlertDescription, CertificateError, CipherSuite, ClientConfig, ClientConnection,
|
||||
DigitallySignedStruct, ProtocolVersion, RootCertStore, SignatureScheme,
|
||||
};
|
||||
use rustls_pki_types::{CertificateDer, InvalidDnsNameError, ServerName, UnixTime};
|
||||
|
||||
mod legacy;
|
||||
|
||||
/// How long a TCP connect may take before the host counts as unreachable.
|
||||
///
|
||||
/// Ten seconds: a host on the same network answers within milliseconds, and
|
||||
@@ -75,6 +83,68 @@ pub enum Error {
|
||||
/// rustls rejected the client configuration.
|
||||
#[error("tls configuration rejected: {0}")]
|
||||
Config(#[source] rustls::Error),
|
||||
/// OpenSSL rejected the configuration of the RSA key exchange fallback.
|
||||
#[error("tls configuration rejected: {0}")]
|
||||
LegacyConfig(#[source] ErrorStack),
|
||||
/// The host refused the ECDHE suites, then the RSA key exchange ones.
|
||||
#[error("host refused every supported TLS suite (ECDHE, then RSA key exchange with AES-GCM)")]
|
||||
NoCommonSuite,
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// Whether the host answered the handshake with a `handshake_failure` alert.
|
||||
///
|
||||
/// That alert is how a server says it shares no cipher suite with the
|
||||
/// client. Nothing else counts: a refused certificate, a closed socket or
|
||||
/// a timeout must never lead to the RSA key exchange fallback.
|
||||
#[must_use]
|
||||
pub(crate) fn refused_suites(&self) -> bool {
|
||||
let Error::TlsHandshake(error) = self else {
|
||||
return false;
|
||||
};
|
||||
error
|
||||
.get_ref()
|
||||
.and_then(|inner| inner.downcast_ref::<rustls::Error>())
|
||||
.is_some_and(|inner| {
|
||||
matches!(
|
||||
inner,
|
||||
rustls::Error::AlertReceived(AlertDescription::HandshakeFailure)
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A completed TLS session on a data port, by the stack that negotiated it.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum Session {
|
||||
/// rustls, with ECDHE key exchange: every host that offers it.
|
||||
Ecdhe(Box<ClientConnection>),
|
||||
/// OpenSSL, with RSA key exchange: a host that refused ECDHE.
|
||||
RsaKx(SslStream<TcpStream>),
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The protocol version and cipher suite the session negotiated.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the session has not completed its handshake.
|
||||
pub(crate) fn negotiated(&self) -> Result<(ProtocolVersion, CipherSuite), Error> {
|
||||
match self {
|
||||
Session::Ecdhe(connection) => negotiated(connection),
|
||||
Session::RsaKx(session) => legacy::negotiated(session),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first certificate of the chain the peer sent, DER encoded.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the session carries no certificate.
|
||||
pub(crate) fn certificate(&self) -> Result<CertificateDer<'static>, Error> {
|
||||
match self {
|
||||
Session::Ecdhe(connection) => peer_certificate(connection),
|
||||
Session::RsaKx(session) => legacy::certificate(session),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a host presented during a TLS handshake that carried nothing else.
|
||||
@@ -328,6 +398,38 @@ pub(crate) fn capture(stream: &mut TcpStream, host: &str) -> Result<Presented, E
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs a TLS 1.2 handshake with RSA key exchange on `stream`, pinned to `pin`.
|
||||
///
|
||||
/// For a host that refused the ECDHE suites, on a fresh connection: the
|
||||
/// refusal closed the first one. The session has no forward secrecy. Nothing
|
||||
/// is written after the handshake when the certificate is not the pinned one.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the host refuses these suites too, presents another certificate, or
|
||||
/// the TLS handshake fails or times out.
|
||||
pub(crate) fn rsa_kx(stream: &TcpStream, pin: &Pin) -> Result<Session, Error> {
|
||||
legacy::handshake(stream, Some(pin)).map(Session::RsaKx)
|
||||
}
|
||||
|
||||
/// What a host that refused the ECDHE suites presents with RSA key exchange.
|
||||
///
|
||||
/// The counterpart of [`capture`]: any certificate is accepted, nothing is
|
||||
/// sent after the TLS handshake, and the session is dropped on return.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the host refuses these suites too, or the TLS handshake fails, times
|
||||
/// out or ends without a certificate.
|
||||
pub(crate) fn capture_rsa_kx(stream: &TcpStream) -> Result<Presented, Error> {
|
||||
let session = legacy::handshake(stream, None)?;
|
||||
let certificate = legacy::certificate(&session)?;
|
||||
let (version, suite) = legacy::negotiated(&session)?;
|
||||
Ok(Presented {
|
||||
certificate,
|
||||
version,
|
||||
suite,
|
||||
})
|
||||
}
|
||||
|
||||
/// The protocol version and cipher suite a completed session negotiated.
|
||||
///
|
||||
/// # Errors
|
||||
@@ -605,6 +707,10 @@ mod tests {
|
||||
sha1(&certificate)
|
||||
)
|
||||
);
|
||||
assert!(
|
||||
!error.refused_suites(),
|
||||
"a refused certificate never leads to the fallback"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -639,6 +745,33 @@ mod tests {
|
||||
assert!(matches!(error, Error::TlsHandshake(_)), "{error:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_handshake_failure_alert_counts_as_refused_suites() {
|
||||
let alert = |description| {
|
||||
Error::TlsHandshake(io::Error::other(rustls::Error::AlertReceived(description)))
|
||||
};
|
||||
assert!(alert(AlertDescription::HandshakeFailure).refused_suites());
|
||||
for other in [
|
||||
AlertDescription::BadCertificate,
|
||||
AlertDescription::ProtocolVersion,
|
||||
AlertDescription::InsufficientSecurity,
|
||||
AlertDescription::InternalError,
|
||||
] {
|
||||
assert!(!alert(other).refused_suites(), "{other:?}");
|
||||
}
|
||||
for kind in [
|
||||
io::ErrorKind::ConnectionReset,
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
io::ErrorKind::TimedOut,
|
||||
] {
|
||||
assert!(
|
||||
!Error::TlsHandshake(kind.into()).refused_suites(),
|
||||
"{kind:?}"
|
||||
);
|
||||
}
|
||||
assert!(!Error::NoCommonSuite.refused_suites());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timeout_is_described_as_such_and_other_errors_keep_their_message() {
|
||||
let timeout = io::Error::from(io::ErrorKind::WouldBlock);
|
||||
|
||||
326
@xen-orchestra/vmware-explorer/vectura/src/tls/legacy.rs
Normal file
326
@xen-orchestra/vmware-explorer/vectura/src/tls/legacy.rs
Normal file
@@ -0,0 +1,326 @@
|
||||
//! TLS 1.2 with RSA key exchange, for a data port that offers nothing else.
|
||||
//!
|
||||
//! The data port of some ESXi 6.5 hosts accepts no ECDHE suite, and rustls
|
||||
//! implements no other key exchange. This module runs the handshake with
|
||||
//! OpenSSL instead, restricted to the two AES-GCM suites of RFC 5288 that use
|
||||
//! RSA key exchange. Such a session has no forward secrecy: whoever later
|
||||
//! obtains the host's private key can decrypt a recording of it.
|
||||
//!
|
||||
//! No chain and no host name are checked here. The certificate is judged by
|
||||
//! its thumbprint alone, before the session is handed to the caller. The
|
||||
//! handshake has by then sent `ClientKeyExchange` and `Finished`, but no
|
||||
//! ticket and no application data reach a host that presented another
|
||||
//! certificate.
|
||||
|
||||
// Rust guideline compliant 2026-10-09
|
||||
|
||||
use std::io;
|
||||
use std::net::TcpStream;
|
||||
|
||||
use openssl::error::ErrorStack;
|
||||
use openssl::ssl::{
|
||||
HandshakeError, Ssl, SslContext, SslMethod, SslStream, SslVerifyMode, SslVersion,
|
||||
};
|
||||
use rustls::{CipherSuite, ProtocolVersion};
|
||||
use rustls_pki_types::CertificateDer;
|
||||
|
||||
use super::{Error, Pin};
|
||||
|
||||
/// The suites offered, in OpenSSL's names: RSA key exchange with AES-GCM.
|
||||
///
|
||||
/// `TLS_RSA_WITH_AES_256_GCM_SHA384` and `TLS_RSA_WITH_AES_128_GCM_SHA256`.
|
||||
/// The CBC suites a host may also accept are left out: they would add the
|
||||
/// padding-oracle exposure of MAC-then-encrypt for no host known to need them.
|
||||
const SUITES: &str = "AES256-GCM-SHA384:AES128-GCM-SHA256";
|
||||
|
||||
/// OpenSSL's reason code for a `handshake_failure` alert received from the peer.
|
||||
///
|
||||
/// `SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE`: 1000 (`SSL_AD_REASON_OFFSET`) plus
|
||||
/// the alert's number, 40. A server sends this alert when it shares no suite
|
||||
/// with the client.
|
||||
const HANDSHAKE_FAILURE_ALERT: i32 = 1040;
|
||||
|
||||
/// OpenSSL's number for its SSL library, `ERR_LIB_SSL`.
|
||||
///
|
||||
/// Reason codes are numbered per library: 1040 names the alert only in an
|
||||
/// error the SSL library raised.
|
||||
const SSL_LIBRARY: i32 = 20;
|
||||
|
||||
/// Runs the TLS handshake on a clone of `stream` and returns the session.
|
||||
///
|
||||
/// With a `pin`, the certificate presented must match it; without one any
|
||||
/// certificate is accepted, which only a thumbprint capture wants. The
|
||||
/// session owns its clone of the socket: dropping it sends no close notify
|
||||
/// and leaves `stream` open.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the host refuses both suites, presents another certificate than the
|
||||
/// pinned one, or the handshake fails or times out.
|
||||
pub(super) fn handshake(
|
||||
stream: &TcpStream,
|
||||
pin: Option<&Pin>,
|
||||
) -> Result<SslStream<TcpStream>, Error> {
|
||||
let ssl = configure().map_err(Error::LegacyConfig)?;
|
||||
let socket = stream.try_clone().map_err(Error::TlsHandshake)?;
|
||||
let session = ssl.connect(socket).map_err(failure)?;
|
||||
if let Some(pin) = pin {
|
||||
let presented = certificate(&session)?;
|
||||
if !pin.matches(&presented) {
|
||||
return Err(Error::Mismatch {
|
||||
expected: pin.clone(),
|
||||
presented: pin.digest_of(&presented),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// The first certificate the peer of `session` sent, DER encoded.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the session carries no certificate.
|
||||
pub(super) fn certificate(
|
||||
session: &SslStream<TcpStream>,
|
||||
) -> Result<CertificateDer<'static>, Error> {
|
||||
session
|
||||
.ssl()
|
||||
.peer_certificate()
|
||||
.and_then(|certificate| certificate.to_der().ok())
|
||||
.map(CertificateDer::from)
|
||||
.ok_or(Error::Incomplete("a certificate"))
|
||||
}
|
||||
|
||||
/// The protocol version and cipher suite `session` negotiated.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the session reports no suite, or another version than TLS 1.2.
|
||||
pub(super) fn negotiated(
|
||||
session: &SslStream<TcpStream>,
|
||||
) -> Result<(ProtocolVersion, CipherSuite), Error> {
|
||||
if session.ssl().version2() != Some(SslVersion::TLS1_2) {
|
||||
return Err(Error::Incomplete("a protocol version"));
|
||||
}
|
||||
let suite = session
|
||||
.ssl()
|
||||
.current_cipher()
|
||||
.ok_or(Error::Incomplete("a cipher suite"))?;
|
||||
Ok((
|
||||
ProtocolVersion::TLSv1_2,
|
||||
CipherSuite::from(u16::from_be_bytes(suite.protocol_id())),
|
||||
))
|
||||
}
|
||||
|
||||
/// A client restricted to TLS 1.2 and [`SUITES`], with no chain verification.
|
||||
fn configure() -> Result<Ssl, ErrorStack> {
|
||||
let mut context = SslContext::builder(SslMethod::tls_client())?;
|
||||
context.set_min_proto_version(Some(SslVersion::TLS1_2))?;
|
||||
context.set_max_proto_version(Some(SslVersion::TLS1_2))?;
|
||||
context.set_cipher_list(SUITES)?;
|
||||
// The thumbprint is the whole verdict, given by `handshake`.
|
||||
context.set_verify(SslVerifyMode::NONE);
|
||||
Ssl::new(&context.build())
|
||||
}
|
||||
|
||||
/// Turns a failed handshake into the error that names its cause.
|
||||
fn failure(error: HandshakeError<TcpStream>) -> Error {
|
||||
match error {
|
||||
HandshakeError::SetupFailure(stack) => Error::LegacyConfig(stack),
|
||||
// The socket carries a timeout, which OpenSSL reports as a retry.
|
||||
HandshakeError::WouldBlock(_) => Error::TlsHandshake(io::ErrorKind::TimedOut.into()),
|
||||
HandshakeError::Failure(interrupted) => {
|
||||
let error = interrupted.into_error();
|
||||
let refused = error.ssl_error().is_some_and(|stack| {
|
||||
stack
|
||||
.errors()
|
||||
.iter()
|
||||
.any(|entry| is_refusal(entry.library_code(), entry.reason_code()))
|
||||
});
|
||||
if refused {
|
||||
Error::NoCommonSuite
|
||||
} else {
|
||||
Error::TlsHandshake(error.into_io_error().unwrap_or_else(io::Error::other))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an error stack entry is the peer's `handshake_failure` alert.
|
||||
fn is_refusal(library: i32, reason: i32) -> bool {
|
||||
library == SSL_LIBRARY && reason == HANDSHAKE_FAILURE_ALERT
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Read;
|
||||
use std::net::TcpListener;
|
||||
use std::thread::{self, JoinHandle};
|
||||
|
||||
use openssl::asn1::Asn1Time;
|
||||
use openssl::hash::MessageDigest;
|
||||
use openssl::pkey::PKey;
|
||||
use openssl::rsa::Rsa;
|
||||
use openssl::x509::{X509, X509NameBuilder};
|
||||
|
||||
use super::super::{Client, Session, Trust, capture, capture_rsa_kx, connect, rsa_kx, sha256};
|
||||
use super::*;
|
||||
|
||||
/// A self-signed certificate with an RSA key, which RSA key exchange needs.
|
||||
fn issue() -> (X509, PKey<openssl::pkey::Private>) {
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut name = X509NameBuilder::new().unwrap();
|
||||
name.append_entry_by_text("CN", "esxi.test").unwrap();
|
||||
let name = name.build();
|
||||
let mut certificate = X509::builder().unwrap();
|
||||
certificate.set_version(2).unwrap();
|
||||
certificate.set_subject_name(&name).unwrap();
|
||||
certificate.set_issuer_name(&name).unwrap();
|
||||
certificate.set_pubkey(&key).unwrap();
|
||||
certificate
|
||||
.set_not_before(&Asn1Time::days_from_now(0).unwrap())
|
||||
.unwrap();
|
||||
certificate
|
||||
.set_not_after(&Asn1Time::days_from_now(1).unwrap())
|
||||
.unwrap();
|
||||
certificate.sign(&key, MessageDigest::sha256()).unwrap();
|
||||
(certificate.build(), key)
|
||||
}
|
||||
|
||||
/// A loopback TLS 1.2 server offering `suites` alone, for `connections` clients.
|
||||
///
|
||||
/// The thread returns the bytes each client sent after its handshake, or
|
||||
/// `None` when the handshake failed.
|
||||
fn server(
|
||||
suites: &'static str,
|
||||
connections: usize,
|
||||
) -> (
|
||||
CertificateDer<'static>,
|
||||
u16,
|
||||
JoinHandle<Vec<Option<Vec<u8>>>>,
|
||||
) {
|
||||
let (certificate, key) = issue();
|
||||
let der = CertificateDer::from(certificate.to_der().unwrap());
|
||||
let mut context = SslContext::builder(SslMethod::tls_server()).unwrap();
|
||||
context
|
||||
.set_max_proto_version(Some(SslVersion::TLS1_2))
|
||||
.unwrap();
|
||||
context.set_cipher_list(suites).unwrap();
|
||||
context.set_certificate(&certificate).unwrap();
|
||||
context.set_private_key(&key).unwrap();
|
||||
let context = context.build();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let served = thread::spawn(move || {
|
||||
(0..connections)
|
||||
.map(|_| {
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let mut session = Ssl::new(&context).unwrap().accept(stream).ok()?;
|
||||
let mut received = Vec::new();
|
||||
// The client leaves without a close notify, which reads as an error.
|
||||
let _ = session.read_to_end(&mut received);
|
||||
Some(received)
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
(der, port, served)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_rsa_only_host_refuses_rustls_then_completes_the_fallback_with_the_pinned_certificate() {
|
||||
let (certificate, port, served) = server("AES256-GCM-SHA384", 2);
|
||||
let pin = Pin::sha256(&sha256(&certificate)).unwrap();
|
||||
let client = Client::new(&Trust::Pin(pin.clone())).unwrap();
|
||||
let mut stream = connect("127.0.0.1", port).unwrap();
|
||||
|
||||
let refusal = client.handshake(&mut stream, "127.0.0.1").unwrap_err();
|
||||
|
||||
assert!(refusal.refused_suites(), "{refusal:?}");
|
||||
let stream = connect("127.0.0.1", port).unwrap();
|
||||
let session = rsa_kx(&stream, &pin).unwrap();
|
||||
assert!(matches!(session, Session::RsaKx(_)));
|
||||
assert_eq!(session.certificate().unwrap(), certificate);
|
||||
assert_eq!(
|
||||
session.negotiated().unwrap(),
|
||||
(
|
||||
ProtocolVersion::TLSv1_2,
|
||||
CipherSuite::TLS_RSA_WITH_AES_256_GCM_SHA384
|
||||
)
|
||||
);
|
||||
drop(session);
|
||||
drop(stream);
|
||||
assert_eq!(served.join().unwrap(), [None, Some(Vec::new())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fallback_capture_reports_the_certificate_and_the_128_bit_suite() {
|
||||
let (certificate, port, _) = server("AES128-GCM-SHA256", 1);
|
||||
let stream = connect("127.0.0.1", port).unwrap();
|
||||
|
||||
let presented = capture_rsa_kx(&stream).unwrap();
|
||||
|
||||
assert_eq!(presented.certificate, certificate);
|
||||
assert_eq!(presented.version, ProtocolVersion::TLSv1_2);
|
||||
assert_eq!(
|
||||
presented.suite,
|
||||
CipherSuite::TLS_RSA_WITH_AES_128_GCM_SHA256
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pin_mismatch_on_the_fallback_is_refused_before_any_write() {
|
||||
let (certificate, port, served) = server("AES256-GCM-SHA384", 1);
|
||||
let pin = Pin::sha256(&sha256(b"another certificate")).unwrap();
|
||||
let stream = connect("127.0.0.1", port).unwrap();
|
||||
|
||||
let error = rsa_kx(&stream, &pin).unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
format!(
|
||||
"certificate thumbprint mismatch: expected {pin}, the host presented {}",
|
||||
sha256(&certificate)
|
||||
)
|
||||
);
|
||||
assert!(!error.refused_suites());
|
||||
drop(stream);
|
||||
assert_eq!(served.join().unwrap(), [Some(Vec::new())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_offering_only_cbc_with_rsa_key_exchange_shares_no_suite() {
|
||||
let (certificate, port, _) = server("AES256-SHA256", 2);
|
||||
let mut stream = connect("127.0.0.1", port).unwrap();
|
||||
let refusal = capture(&mut stream, "127.0.0.1").unwrap_err();
|
||||
assert!(refusal.refused_suites(), "{refusal:?}");
|
||||
let stream = connect("127.0.0.1", port).unwrap();
|
||||
|
||||
let error = rsa_kx(&stream, &Pin::sha256(&sha256(&certificate)).unwrap()).unwrap_err();
|
||||
|
||||
assert!(matches!(error, Error::NoCommonSuite), "{error:?}");
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"host refused every supported TLS suite (ECDHE, then RSA key exchange with AES-GCM)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_alert_reason_code_is_a_refusal_only_from_the_ssl_library() {
|
||||
// 6 is ERR_LIB_EVP, whose reason codes are numbered on their own.
|
||||
assert!(is_refusal(SSL_LIBRARY, HANDSHAKE_FAILURE_ALERT));
|
||||
assert!(!is_refusal(6, HANDSHAKE_FAILURE_ALERT));
|
||||
assert!(!is_refusal(SSL_LIBRARY, HANDSHAKE_FAILURE_ALERT + 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_that_closes_during_the_fallback_is_a_handshake_failure_not_a_refusal() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let closing = thread::spawn(move || drop(listener.accept().unwrap()));
|
||||
let stream = connect("127.0.0.1", port).unwrap();
|
||||
closing.join().unwrap();
|
||||
|
||||
let error = capture_rsa_kx(&stream).unwrap_err();
|
||||
|
||||
assert!(matches!(error, Error::TlsHandshake(_)), "{error:?}");
|
||||
assert!(!error.refused_suites());
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,14 @@ impl Transcript {
|
||||
|
||||
/// The protocol version and cipher suite the TLS session at `place` negotiated.
|
||||
pub fn tls(&self, place: &str, version: ProtocolVersion, suite: CipherSuite) {
|
||||
self.line(&format!("{place} tls {version:?} {suite:?}"));
|
||||
self.line(&format!("{place} tls {version:?} {}", suite_name(suite)));
|
||||
}
|
||||
|
||||
/// That the data port refused the ECDHE suites at `place` and is asked again.
|
||||
pub fn fallback(&self, place: &str) {
|
||||
self.line(&format!(
|
||||
"{place} tls fallback: host refused ECDHE, retrying with RSA key exchange"
|
||||
));
|
||||
}
|
||||
|
||||
/// A dialogue line sent to the host, without its line end; never the ticket.
|
||||
@@ -118,6 +125,18 @@ impl Transcript {
|
||||
}
|
||||
}
|
||||
|
||||
/// The IANA name of `suite`.
|
||||
///
|
||||
/// rustls prints the name of the suites it implements and a bare number for
|
||||
/// the others, which the two RSA key exchange suites of the fallback are.
|
||||
fn suite_name(suite: CipherSuite) -> String {
|
||||
match u16::from(suite) {
|
||||
0x009C => "TLS_RSA_WITH_AES_128_GCM_SHA256".to_owned(),
|
||||
0x009D => "TLS_RSA_WITH_AES_256_GCM_SHA384".to_owned(),
|
||||
_ => format!("{suite:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `wire` over `logical` with two decimals, in integer arithmetic; 0.00 before any byte.
|
||||
fn ratio(wire: u64, logical: u64) -> String {
|
||||
let hundredths = wire.saturating_mul(100) / logical.max(1);
|
||||
@@ -128,6 +147,18 @@ fn ratio(wire: u64, logical: u64) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_suite_is_named_whether_or_not_rustls_implements_it() {
|
||||
for (suite, expected) in [
|
||||
(0x009C, "TLS_RSA_WITH_AES_128_GCM_SHA256"),
|
||||
(0x009D, "TLS_RSA_WITH_AES_256_GCM_SHA384"),
|
||||
(0x1302, "TLS13_AES_256_GCM_SHA384"),
|
||||
(0xC02F, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"),
|
||||
] {
|
||||
assert_eq!(suite_name(CipherSuite::from(suite)), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ratio_has_two_decimals_and_is_zero_before_any_byte() {
|
||||
for (wire, logical, expected) in [
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::net::TcpListener;
|
||||
use std::process::{Command, Output};
|
||||
|
||||
use crate::support::{DataPort, GREETING, GREETING_WITHOUT_SHA256, Host, Observed, text};
|
||||
use crate::support::{DataPort, GREETING, GREETING_WITHOUT_SHA256, Host, Observed, Scenario, text};
|
||||
|
||||
/// Runs the built binary with `args` and waits for it.
|
||||
fn vectura(args: &[&str]) -> Output {
|
||||
@@ -161,3 +161,69 @@ fn a_refused_data_port_fails_naming_its_address() {
|
||||
failure_naming(&output, &format!("127.0.0.1:{data}"));
|
||||
assert!(host.management().handshake_completed);
|
||||
}
|
||||
|
||||
/// A host whose data port accepts `suites` alone, like an ESXi 6.5 one.
|
||||
fn restricted_to(suites: &'static str) -> Host {
|
||||
Host::start(Scenario {
|
||||
data: DataPort::Greeting(GREETING_WITHOUT_SHA256),
|
||||
data_suites: Some(suites),
|
||||
..Scenario::default()
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_rsa_only_data_port_is_fingerprinted_through_the_fallback() {
|
||||
let host = restricted_to("AES256-GCM-SHA384");
|
||||
|
||||
let output = fingerprint(&host, true);
|
||||
|
||||
assert_eq!(
|
||||
output.status.code(),
|
||||
Some(0),
|
||||
"stderr: {}",
|
||||
text(&output.stderr)
|
||||
);
|
||||
assert_eq!(text(&output.stdout), expected_stdout(&host));
|
||||
let refused = host.data();
|
||||
assert!(
|
||||
refused.handshake_started && !refused.handshake_completed,
|
||||
"the ECDHE offer is refused first: {refused:?}"
|
||||
);
|
||||
let accepted = host.data();
|
||||
assert_eq!(
|
||||
accepted.suite.as_deref(),
|
||||
Some("TLS_RSA_WITH_AES_256_GCM_SHA384")
|
||||
);
|
||||
assert_eq!(
|
||||
accepted.bytes_after_tls_handshake, 0,
|
||||
"nothing is sent after the TLS handshake: {accepted:?}"
|
||||
);
|
||||
let expected = verbose_line(host.management_port, &host.management())
|
||||
+ &format!(
|
||||
"{} tls fallback: host refused ECDHE, retrying with RSA key exchange\n",
|
||||
host.data_port
|
||||
)
|
||||
+ &verbose_line(host.data_port, &accepted);
|
||||
assert_eq!(text(&output.stderr), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_data_port_with_no_common_suite_fails_naming_the_cause() {
|
||||
// CBC with RSA key exchange: neither rustls nor the fallback offers it.
|
||||
let host = restricted_to("AES256-SHA256");
|
||||
|
||||
let output = fingerprint(&host, false);
|
||||
|
||||
let stderr = failure_naming(&output, &format!("127.0.0.1:{}", host.data_port));
|
||||
assert!(
|
||||
stderr.contains(
|
||||
"host refused every supported TLS suite (ECDHE, then RSA key exchange with AES-GCM)"
|
||||
),
|
||||
"{stderr}"
|
||||
);
|
||||
assert!(!stderr.contains("HandshakeFailure"), "{stderr}");
|
||||
for _ in 0..2 {
|
||||
let refused = host.data();
|
||||
assert!(!refused.handshake_completed, "{refused:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -446,6 +446,24 @@ fn a_vcenter_serves_the_disk_from_the_host_its_ticket_names() {
|
||||
healthy_session(&events, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legacy_host_through_a_vcenter_is_asked_for_the_transport_of_vpxa() {
|
||||
// The mock grants a vCenter's ticket on a legacy host to vpxa only.
|
||||
let host = Host::start(Scenario {
|
||||
data: DataPort::Greeting(GREETING_WITHOUT_SHA256),
|
||||
vcenter: true,
|
||||
..Scenario::default()
|
||||
});
|
||||
let mut child = spawn(&host, Some(PASSWORD), &pin(&host));
|
||||
negotiate(&mut child, true);
|
||||
let events = session_ends_cleanly(&host, child);
|
||||
|
||||
assert!(
|
||||
events.contains(&Event::Proxy("vpxa-nfcssl".to_owned())),
|
||||
"{events:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_login_reports_the_fault_without_the_password() {
|
||||
let fault = "Cannot complete login due to an incorrect user name or password.";
|
||||
@@ -582,6 +600,123 @@ fn a_legacy_host_exports_the_capacity_its_reads_reveal_and_serves_the_disk_bytes
|
||||
);
|
||||
}
|
||||
|
||||
/// A legacy host whose data port accepts RSA key exchange alone, like an ESXi 6.5 one.
|
||||
///
|
||||
/// Its ticket carries the SHA-1 thumbprint of `ticket_thumbprint`.
|
||||
fn rsa_only(ticket_thumbprint: Thumbprint) -> Scenario {
|
||||
Scenario {
|
||||
data: DataPort::Greeting(GREETING_WITHOUT_SHA256),
|
||||
data_suites: Some("AES256-GCM-SHA384"),
|
||||
ticket_thumbprint,
|
||||
..Scenario::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_that_refuses_ecdhe_serves_the_disk_over_rsa_key_exchange_in_both_sessions() {
|
||||
let capacity = Scenario::default().capacity;
|
||||
let host = Host::start(rsa_only(Thumbprint::Own));
|
||||
let mut child = spawn(&host, Some(PASSWORD), &pinned(&host, &["--verbose"]));
|
||||
|
||||
let export = negotiate(&mut child, true);
|
||||
let first = read_at(&mut child, 1, 0, 4 * MIB);
|
||||
let last = read_at(&mut child, 2, capacity - SECTOR, SECTOR);
|
||||
disconnect(&mut child);
|
||||
let output = finish(child);
|
||||
|
||||
assert_eq!(
|
||||
output.status.code(),
|
||||
Some(0),
|
||||
"stderr: {}",
|
||||
text(&output.stderr)
|
||||
);
|
||||
assert_eq!(export.size, capacity);
|
||||
matches_disk(&first, 0, 4 * MIB);
|
||||
matches_disk(&last, capacity - SECTOR, SECTOR);
|
||||
let refused = host.data();
|
||||
assert!(
|
||||
refused.handshake_started && !refused.handshake_completed,
|
||||
"the ECDHE offer is refused first: {refused:?}"
|
||||
);
|
||||
let served = host.data();
|
||||
assert!(served.second_handshake, "{served:?}");
|
||||
let stderr = text(&output.stderr);
|
||||
let lines = [
|
||||
"first session tls fallback: host refused ECDHE, retrying with RSA key exchange\n\
|
||||
first session tls TLSv1_2 TLS_RSA_WITH_AES_256_GCM_SHA384\n",
|
||||
"second session tls TLSv1_2 TLS_RSA_WITH_AES_256_GCM_SHA384\n",
|
||||
];
|
||||
for line in lines {
|
||||
assert!(stderr.contains(line), "{stderr}");
|
||||
}
|
||||
secrets_absent(&output);
|
||||
let opened = legacy_events_up_to_open();
|
||||
assert_eq!(host.events()[..opened.len()], opened);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_that_offers_ecdhe_is_never_asked_for_rsa_key_exchange() {
|
||||
let host = Host::start(Scenario {
|
||||
capacity: SMALL,
|
||||
..Scenario::default()
|
||||
});
|
||||
let mut child = spawn(&host, Some(PASSWORD), &pinned(&host, &["--verbose"]));
|
||||
|
||||
negotiate(&mut child, true);
|
||||
disconnect(&mut child);
|
||||
let output = finish(child);
|
||||
|
||||
assert_eq!(output.status.code(), Some(0));
|
||||
let stderr = text(&output.stderr);
|
||||
assert!(!stderr.contains("fallback"), "{stderr}");
|
||||
assert!(!stderr.contains("TLS_RSA_"), "{stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pin_mismatch_does_not_trigger_the_fallback() {
|
||||
let host = Host::start(Scenario {
|
||||
ticket_thumbprint: Thumbprint::Other,
|
||||
..Scenario::default()
|
||||
});
|
||||
|
||||
let output = finish(spawn(&host, Some(PASSWORD), &pinned(&host, &["--verbose"])));
|
||||
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
let stderr = text(&output.stderr);
|
||||
assert!(
|
||||
stderr.contains("vectura: data plane: certificate thumbprint mismatch"),
|
||||
"{stderr}"
|
||||
);
|
||||
assert!(!stderr.contains("fallback"), "{stderr}");
|
||||
assert!(
|
||||
!host.events().contains(&Event::Session(TICKET.to_owned())),
|
||||
"the ticket was never presented: {:?}",
|
||||
host.events()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ticket_thumbprint_that_is_not_the_certificate_aborts_the_fallback_before_any_write() {
|
||||
let (host, stderr) = fails_then_logs_out(rsa_only(Thumbprint::Other));
|
||||
|
||||
assert!(
|
||||
stderr.starts_with("vectura: data plane: certificate thumbprint mismatch"),
|
||||
"{stderr}"
|
||||
);
|
||||
assert!(!host.data().handshake_completed);
|
||||
let pinned = host.data();
|
||||
assert!(pinned.handshake_completed, "{pinned:?}");
|
||||
assert_eq!(
|
||||
pinned.bytes_after_tls_handshake, 0,
|
||||
"nothing is written to a host presenting another certificate: {pinned:?}"
|
||||
);
|
||||
assert!(
|
||||
!host.events().contains(&Event::Session(TICKET.to_owned())),
|
||||
"the ticket was never presented: {:?}",
|
||||
host.events()
|
||||
);
|
||||
}
|
||||
|
||||
/// The text an ESXi 6.0 host sends when the path names no disk.
|
||||
const LEGACY_OPEN_ERROR: &str =
|
||||
"NfcFssrvrOpen: permission check failed for file [datastore1] vm/vm.vmdk, access = 1";
|
||||
|
||||
@@ -19,6 +19,12 @@ use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use aws_lc_rs::digest::{self, Algorithm, SHA1_FOR_LEGACY_USE_ONLY, SHA256};
|
||||
use openssl::asn1::Asn1Time;
|
||||
use openssl::hash::MessageDigest;
|
||||
use openssl::pkey::PKey;
|
||||
use openssl::rsa::Rsa;
|
||||
use openssl::ssl::{Ssl, SslContext, SslMethod, SslStream, SslVersion};
|
||||
use openssl::x509::{X509, X509NameBuilder};
|
||||
use rustls::{IoState, ServerConfig, ServerConnection, Stream};
|
||||
use rustls_pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
|
||||
|
||||
@@ -159,6 +165,13 @@ pub enum ReadFault {
|
||||
pub struct Scenario {
|
||||
/// What the data port does on connection.
|
||||
pub data: DataPort,
|
||||
/// The only suites the data port accepts, as an OpenSSL cipher list, with TLS 1.2 at most.
|
||||
///
|
||||
/// `None` is a host that offers ECDHE. With a list, the host has an RSA
|
||||
/// key, as RSA key exchange needs, and the data port serves every
|
||||
/// connection instead of the first only: a client refused once may come
|
||||
/// back, and [`Host::data`] then reports the connections in order.
|
||||
pub data_suites: Option<&'static str>,
|
||||
/// Whether the management port plays a vCenter.
|
||||
///
|
||||
/// It reports `VirtualCenter`, and its ticket names [`VCENTER_DATA_HOST`],
|
||||
@@ -197,6 +210,7 @@ impl Default for Scenario {
|
||||
fn default() -> Scenario {
|
||||
Scenario {
|
||||
data: DataPort::Greeting(GREETING),
|
||||
data_suites: None,
|
||||
vcenter: false,
|
||||
login: Ok(()),
|
||||
ticket_thumbprint: Thumbprint::Own,
|
||||
@@ -324,14 +338,20 @@ pub struct Host {
|
||||
impl Host {
|
||||
/// Starts a host with a fresh self-signed certificate that plays `scenario`.
|
||||
pub fn start(scenario: Scenario) -> Host {
|
||||
let issued = rcgen::generate_simple_self_signed(vec![
|
||||
"esxi.test".to_owned(),
|
||||
"127.0.0.1".to_owned(),
|
||||
])
|
||||
.expect("a self-signed certificate is generated");
|
||||
let certificate = issued.cert.der().clone();
|
||||
let key =
|
||||
PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(issued.signing_key.serialize_der()));
|
||||
let restricted = scenario.data_suites.map(restricted);
|
||||
let (certificate, key) = if let Some((certificate, key, _)) = &restricted {
|
||||
(certificate.clone(), key.clone_key())
|
||||
} else {
|
||||
let issued = rcgen::generate_simple_self_signed(vec![
|
||||
"esxi.test".to_owned(),
|
||||
"127.0.0.1".to_owned(),
|
||||
])
|
||||
.expect("a self-signed certificate is generated");
|
||||
(
|
||||
issued.cert.der().clone(),
|
||||
PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(issued.signing_key.serialize_der())),
|
||||
)
|
||||
};
|
||||
let config = Arc::new(
|
||||
ServerConfig::builder()
|
||||
.with_no_client_auth()
|
||||
@@ -347,6 +367,7 @@ impl Host {
|
||||
let mock = Arc::new(Mock {
|
||||
scenario,
|
||||
config,
|
||||
restricted: restricted.map(|(_, _, context)| context),
|
||||
events: Mutex::new(Vec::new()),
|
||||
certificate: certificate.clone(),
|
||||
data_port,
|
||||
@@ -357,7 +378,12 @@ impl Host {
|
||||
true,
|
||||
serve_management,
|
||||
);
|
||||
let data = listen(data_listener, Arc::clone(&mock), false, serve_data);
|
||||
let data = listen(
|
||||
data_listener,
|
||||
Arc::clone(&mock),
|
||||
mock.restricted.is_some(),
|
||||
serve_data,
|
||||
);
|
||||
Host {
|
||||
certificate,
|
||||
management_port,
|
||||
@@ -392,7 +418,7 @@ impl Host {
|
||||
.expect("the management port served a connection")
|
||||
}
|
||||
|
||||
/// What the data port observed; panics when it was never contacted.
|
||||
/// What the data port observed on its next connection; panics when there was none.
|
||||
pub fn data(&self) -> Observed {
|
||||
self.data
|
||||
.recv_timeout(REPORT_TIMEOUT)
|
||||
@@ -437,16 +463,69 @@ pub fn text(bytes: &[u8]) -> String {
|
||||
String::from_utf8(bytes.to_vec()).expect("the output is UTF-8")
|
||||
}
|
||||
|
||||
/// An RSA certificate and key, and the TLS 1.2 server that accepts `suites` alone with them.
|
||||
fn restricted(suites: &str) -> (CertificateDer<'static>, PrivateKeyDer<'static>, SslContext) {
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).expect("an RSA key is generated"))
|
||||
.expect("the key is usable");
|
||||
let mut name = X509NameBuilder::new().expect("a name builder");
|
||||
name.append_entry_by_text("CN", "esxi.test")
|
||||
.expect("a common name");
|
||||
let name = name.build();
|
||||
let mut certificate = X509::builder().expect("a certificate builder");
|
||||
certificate.set_version(2).expect("version 3");
|
||||
certificate.set_subject_name(&name).expect("a subject");
|
||||
certificate.set_issuer_name(&name).expect("an issuer");
|
||||
certificate.set_pubkey(&key).expect("a public key");
|
||||
certificate
|
||||
.set_not_before(&Asn1Time::days_from_now(0).expect("today"))
|
||||
.expect("a start");
|
||||
certificate
|
||||
.set_not_after(&Asn1Time::days_from_now(1).expect("tomorrow"))
|
||||
.expect("an end");
|
||||
certificate
|
||||
.sign(&key, MessageDigest::sha256())
|
||||
.expect("the certificate is signed");
|
||||
let certificate = certificate.build();
|
||||
let mut context = SslContext::builder(SslMethod::tls_server()).expect("a server context");
|
||||
context
|
||||
.set_max_proto_version(Some(SslVersion::TLS1_2))
|
||||
.expect("TLS 1.2 is available");
|
||||
context.set_cipher_list(suites).expect("the suites exist");
|
||||
context
|
||||
.set_certificate(&certificate)
|
||||
.expect("the certificate is accepted");
|
||||
context.set_private_key(&key).expect("the key matches");
|
||||
(
|
||||
CertificateDer::from(certificate.to_der().expect("the certificate encodes")),
|
||||
PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(
|
||||
key.private_key_to_pkcs8().expect("the key encodes"),
|
||||
)),
|
||||
context.build(),
|
||||
)
|
||||
}
|
||||
|
||||
/// What both port threads share.
|
||||
#[derive(Debug)]
|
||||
struct Mock {
|
||||
scenario: Scenario,
|
||||
config: Arc<ServerConfig>,
|
||||
/// The data port's TLS server when the scenario restricts its suites.
|
||||
restricted: Option<SslContext>,
|
||||
events: Mutex<Vec<Event>>,
|
||||
certificate: CertificateDer<'static>,
|
||||
data_port: u16,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Mock {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
// `SslContext` has no `Debug`; the scenario says whether it is there.
|
||||
formatter
|
||||
.debug_struct("Mock")
|
||||
.field("scenario", &self.scenario)
|
||||
.field("data_port", &self.data_port)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Mock {
|
||||
fn record(&self, event: Event) {
|
||||
self.events
|
||||
@@ -748,6 +827,8 @@ fn fault(text: &str) -> String {
|
||||
/// The disk session as the mock carries it: TLS or the socket in clear.
|
||||
enum Plane<'a> {
|
||||
Tls(&'a mut ServerConnection, &'a mut TcpStream),
|
||||
/// TLS as OpenSSL serves it, on its own clone of the socket.
|
||||
Restricted(SslStream<TcpStream>),
|
||||
Clear(&'a mut TcpStream),
|
||||
}
|
||||
|
||||
@@ -756,6 +837,13 @@ impl Plane<'_> {
|
||||
fn message(&mut self) -> Option<Vec<u8>> {
|
||||
match self {
|
||||
Plane::Tls(connection, stream) => next_record(connection, stream),
|
||||
// OpenSSL hands over the plaintext of one record per read.
|
||||
Plane::Restricted(session) => {
|
||||
let mut message = vec![0_u8; 1 << 14];
|
||||
let length = session.read(&mut message).ok().filter(|read| *read > 0)?;
|
||||
message.truncate(length);
|
||||
Some(message)
|
||||
}
|
||||
Plane::Clear(stream) => {
|
||||
let mut message = vec![0_u8; MESSAGE_LEN];
|
||||
stream.read_exact(&mut message).ok()?;
|
||||
@@ -773,15 +861,22 @@ impl Plane<'_> {
|
||||
fn send(&mut self, bytes: &[u8]) -> Option<()> {
|
||||
match self {
|
||||
Plane::Tls(connection, stream) => send_record(connection, stream, bytes),
|
||||
Plane::Restricted(session) => send(session, bytes),
|
||||
Plane::Clear(stream) => send(stream, bytes),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the TLS session properly; the clear session just closes.
|
||||
fn close(self) {
|
||||
if let Plane::Tls(connection, stream) = self {
|
||||
connection.send_close_notify();
|
||||
let _ = connection.complete_io(stream);
|
||||
match self {
|
||||
Plane::Tls(connection, stream) => {
|
||||
connection.send_close_notify();
|
||||
let _ = connection.complete_io(stream);
|
||||
}
|
||||
Plane::Restricted(mut session) => {
|
||||
let _ = session.shutdown();
|
||||
}
|
||||
Plane::Clear(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -792,6 +887,7 @@ impl Read for Plane<'_> {
|
||||
Plane::Tls(connection, stream) => {
|
||||
Stream::new(&mut **connection, &mut **stream).read(buffer)
|
||||
}
|
||||
Plane::Restricted(session) => session.read(buffer),
|
||||
Plane::Clear(stream) => stream.read(buffer),
|
||||
}
|
||||
}
|
||||
@@ -803,6 +899,7 @@ impl Write for Plane<'_> {
|
||||
Plane::Tls(connection, stream) => {
|
||||
Stream::new(&mut **connection, &mut **stream).write(buffer)
|
||||
}
|
||||
Plane::Restricted(session) => session.write(buffer),
|
||||
Plane::Clear(stream) => stream.write(buffer),
|
||||
}
|
||||
}
|
||||
@@ -810,6 +907,7 @@ impl Write for Plane<'_> {
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
match self {
|
||||
Plane::Tls(connection, stream) => Stream::new(&mut **connection, &mut **stream).flush(),
|
||||
Plane::Restricted(session) => session.flush(),
|
||||
Plane::Clear(stream) => stream.flush(),
|
||||
}
|
||||
}
|
||||
@@ -824,6 +922,10 @@ fn serve_data(mut stream: TcpStream, mock: &Mock) -> Observed {
|
||||
if stream.write_all(greeting).is_err() {
|
||||
return observed;
|
||||
}
|
||||
if let Some(context) = &mock.restricted {
|
||||
serve_restricted(stream, mock, context, &mut observed);
|
||||
return observed;
|
||||
}
|
||||
let Some(mut first) = handshake(&mut stream, mock, &mut observed) else {
|
||||
return observed;
|
||||
};
|
||||
@@ -835,7 +937,7 @@ fn serve_data(mut stream: TcpStream, mock: &Mock) -> Observed {
|
||||
drop(first);
|
||||
let socket = stream.try_clone().expect("the socket clones");
|
||||
let mut second;
|
||||
let mut plane = if transport == "nfc" {
|
||||
let mut plane = if transport.ends_with("nfc") {
|
||||
Plane::Clear(&mut stream)
|
||||
} else {
|
||||
second = ServerConnection::new(Arc::clone(&mock.config))
|
||||
@@ -857,6 +959,75 @@ fn serve_data(mut stream: TcpStream, mock: &Mock) -> Observed {
|
||||
observed
|
||||
}
|
||||
|
||||
/// Accepts one TLS session with the restricted suites on a clone of `stream`.
|
||||
fn accept(stream: &TcpStream, context: &SslContext) -> Option<SslStream<TcpStream>> {
|
||||
let socket = stream.try_clone().expect("the socket clones");
|
||||
Ssl::new(context)
|
||||
.expect("the server context is valid")
|
||||
.accept(socket)
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// [`serve_data`] past the greeting, for a data port whose suites are restricted.
|
||||
///
|
||||
/// A client offering none of them is answered with a `handshake_failure`
|
||||
/// alert and the connection ends there, as on a host.
|
||||
fn serve_restricted(
|
||||
mut stream: TcpStream,
|
||||
mock: &Mock,
|
||||
context: &SslContext,
|
||||
observed: &mut Observed,
|
||||
) {
|
||||
let mut first = [0_u8; 1];
|
||||
observed.handshake_started = matches!(stream.peek(&mut first), Ok(1));
|
||||
let Some(mut first) = accept(&stream, context) else {
|
||||
return;
|
||||
};
|
||||
observed.handshake_completed = true;
|
||||
// The names rustls debug-prints, which the transcript uses.
|
||||
observed.version = Some(first.ssl().version_str().replace('.', "_"));
|
||||
observed.suite = first
|
||||
.ssl()
|
||||
.current_cipher()
|
||||
.and_then(openssl::ssl::SslCipherRef::standard_name)
|
||||
.map(str::to_owned);
|
||||
let (read, granted) = dialogue(&mut first, mock);
|
||||
observed.bytes_after_tls_handshake = read;
|
||||
let Some(transport) = granted else {
|
||||
return;
|
||||
};
|
||||
// No close notify, as on the other path: the socket goes on.
|
||||
drop(first);
|
||||
let mut plane = if transport.ends_with("nfc") {
|
||||
Plane::Clear(&mut stream)
|
||||
} else {
|
||||
let Some(second) = accept(&stream, context) else {
|
||||
return;
|
||||
};
|
||||
observed.second_handshake = true;
|
||||
Plane::Restricted(second)
|
||||
};
|
||||
if mock.legacy() {
|
||||
if legacy_shake(&mut plane, mock).is_some() {
|
||||
legacy_messages(&mut plane, mock);
|
||||
}
|
||||
} else if shake(&mut plane, mock).is_some() {
|
||||
let socket = stream_clone(&plane);
|
||||
if let Some(socket) = socket {
|
||||
records(&mut plane, &socket, mock, observed);
|
||||
}
|
||||
}
|
||||
plane.close();
|
||||
}
|
||||
|
||||
/// A handle on the socket under `plane`, to set its timeouts.
|
||||
fn stream_clone(plane: &Plane<'_>) -> Option<TcpStream> {
|
||||
match plane {
|
||||
Plane::Tls(_, stream) | Plane::Clear(stream) => stream.try_clone().ok(),
|
||||
Plane::Restricted(session) => session.get_ref().try_clone().ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the ticket dialogue: the bytes read, and the transport `PROXY` was granted, if any.
|
||||
fn dialogue<S: Read + Write>(tls: &mut S, mock: &Mock) -> (usize, Option<String>) {
|
||||
let mut read = 0;
|
||||
@@ -888,11 +1059,20 @@ fn dialogue<S: Read + Write>(tls: &mut S, mock: &Mock) -> (usize, Option<String>
|
||||
"200 {}",
|
||||
mock.thumbprint(&SHA256, mock.scenario.announced_thumbprint)
|
||||
)
|
||||
} else if let Some(transport @ ("nfc" | "nfcssl")) = text.strip_prefix("PROXY ") {
|
||||
} else if let Some(transport @ ("nfc" | "nfcssl" | "vpxa-nfc" | "vpxa-nfcssl")) =
|
||||
text.strip_prefix("PROXY ")
|
||||
// A 6.x host knows a vCenter's ticket under vpxa's services only.
|
||||
&& transport.starts_with("vpxa-") == (mock.scenario.vcenter && mock.legacy())
|
||||
{
|
||||
mock.record(Event::Proxy(transport.to_owned()));
|
||||
let service = if transport.starts_with("vpxa-") {
|
||||
transport.to_owned()
|
||||
} else {
|
||||
format!("ha-{transport}")
|
||||
};
|
||||
mock.scenario
|
||||
.proxy_reply
|
||||
.map_or_else(|| format!("200 Connect ha-{transport}"), str::to_owned)
|
||||
.map_or_else(|| format!("200 Connect {service}"), str::to_owned)
|
||||
} else {
|
||||
return (read, None);
|
||||
};
|
||||
|
||||
Binary file not shown.
@@ -42,24 +42,30 @@ XO 6 tests import the generic helpers through `@core-test` too, so a helper exis
|
||||
|
||||
Testing uses **Vitest 4** with a single `unit` project (see `vitest.config.ts`): every test matches `**/*.unit.test.ts` and runs on `happy-dom`, CLI-only, no browser.
|
||||
|
||||
| Path | Role |
|
||||
| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `vitest.config.ts` | Runner config: `vue` + `vue-i18n` plugins, `@core` / `@core-test` aliases, `globals: true` |
|
||||
| `test/setup.ts` | Global setup: auto-unmounts every mounted wrapper after each test |
|
||||
| `test/create-global-test-config.ts` | `global` mount options: the real `vue-i18n`, a Pinia and a router (needed by `useUiStore`); optional `provide` |
|
||||
| `test/i18n.ts` | The `t` of that `vue-i18n` instance, to build expected texts from their translation key |
|
||||
| `test/find-accented-labels.ts` | `findAccentedTags` / `findAccentedInfos`: each `UiTag` / `UiInfo` a wrapper renders, as `{ label, accent }`, in order; `findInfoLabels`: the `UiInfo` messages alone (also used by XO 6) |
|
||||
| `test/field-events.ts` | `setFieldValue` / `blurField`: sets a field's value or moves the focus out of it as the user would, returns the `update:modelValue` / `blur` events emitted (also used by XO 6) |
|
||||
| `test/read-forwarded-flag.ts` | `readForwardedFlag`: the value a child component receives for a boolean prop, mounted with it then without it (`[true, false]` when forwarded) (also used by XO 6) |
|
||||
| `test/mount-field.ts` | `mountField`: mounts a text field component with a `neutral` accent and a `'Value'` model, attached to the document; optional slots and attributes |
|
||||
| `test/submit-confirmation-text.ts` | `submitConfirmationText(wrapper, text)`: types and submits the confirmation text of a modal, returns `{ isConfirmed, errors }` |
|
||||
| `test/mount-composable.ts` | `mountComposable`: runs a composable inside a mounted component, its result read through `wrapper.vm`; takes the `global` options, `createGlobalTestConfig()` by default |
|
||||
| `test/get-success-state.ts` | `getSuccessState`: the title, the message and the link of the `VtsSuccessStateHero` a wrapper renders, `undefined` without a title or a link (also used by XO 6) |
|
||||
| `test/find-links.ts` | `findLinks(wrapper, selector?)`: every `UiLink` of a wrapper (or every plain link matching `selector`) as its `[text, href]`, in order (also used by XO 6) |
|
||||
| `test/expect-loader.ts` | `hasLoader(wrapper)`: whether a `UiLoader` is rendered; `expectLoaderInsteadOf(wrapper, findContent)`: a `UiLoader` shown and the content it stands for empty (also used by XO 6) |
|
||||
| `test/find-title.ts` | `findTitle`: the `.title` of a `VtsSuccessStateHero` or a list item, `undefined` without one (also used by XO 6) |
|
||||
| `tsconfig.vitest.json` | Type-checks test files with the Vitest globals and the `@core-test` alias |
|
||||
| `tsconfig.app.json` | Type-checks the library, test files excluded |
|
||||
| Path | Role |
|
||||
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `vitest.config.ts` | Runner config: `vue` + `vue-i18n` plugins, `@core` / `@core-test` aliases, `globals: true` |
|
||||
| `test/setup.ts` | Global setup: auto-unmounts every mounted wrapper after each test |
|
||||
| `test/create-global-test-config.ts` | `global` mount options: the real `vue-i18n`, a Pinia and a router (needed by `useUiStore`); optional `provide` |
|
||||
| `test/i18n.ts` | The `t` of that `vue-i18n` instance, to build expected texts from their translation key |
|
||||
| `test/find-accented-labels.ts` | `findAccentedTags` / `findAccentedInfos`: each `UiTag` / `UiInfo` a wrapper renders, as `{ label, accent }`, in order; `findInfoLabels`: the `UiInfo` messages alone (also used by XO 6) |
|
||||
| `test/field-events.ts` | `setFieldValue` / `blurField`: sets a field's value or moves the focus out of it as the user would, returns the `update:modelValue` / `blur` events emitted (also used by XO 6) |
|
||||
| `test/read-forwarded-flag.ts` | `readForwardedFlag`: the value a child component receives for a boolean prop, mounted with it then without it (`[true, false]` when forwarded) (also used by XO 6) |
|
||||
| `test/mount-field.ts` | `mountField`: mounts a text field component with a `neutral` accent and a `'Value'` model, attached to the document; optional slots and attributes |
|
||||
| `test/submit-confirmation-text.ts` | `submitConfirmationText(wrapper, text)`: types and submits the confirmation text of a modal, returns `{ isConfirmed, errors }` |
|
||||
| `test/mount-composable.ts` | `mountComposable`: runs a composable inside a mounted component, its result read through `wrapper.vm`; takes the `global` options, `createGlobalTestConfig()` by default |
|
||||
| `test/get-success-state.ts` | `getSuccessState`: the title, the message and the link of the `VtsSuccessStateHero` a wrapper renders, `undefined` without a title or a link (also used by XO 6) |
|
||||
| `test/find-links.ts` | `findLinks(wrapper, selector?)`: every `UiLink` of a wrapper (or every plain link matching `selector`) as its `[text, href]`, in order (also used by XO 6) |
|
||||
| `test/expect-loader.ts` | `hasLoader(wrapper)`: whether a `UiLoader` is rendered; `expectLoaderInsteadOf(wrapper, findContent)`: a `UiLoader` shown and the content it stands for empty (also used by XO 6) |
|
||||
| `test/select.ts` | `openSelect`, `findShownSelections`, `findSelectOptionLabels`, `pickSelectOption(wrapper, label, { detailed? })`: opens a `VtsSelect`, reads the selection it shows, reads or picks its options (`detailed`: the option shows details after its label); `chooseSelectOption(wrapper, label, { container?, detailed? })`: opens the select inside `container`, then picks the option (also used by XO 6) |
|
||||
| `test/is-placeholder-shown.ts` | `isPlaceholderShown(field)`: whether a readonly input shows its placeholder in place of its value |
|
||||
| `test/inject-or-throw.ts` | `injectOrThrow(key)`: `inject(key)`, throwing when nothing provides it |
|
||||
| `test/mount-with-setup.ts` | `mountWithSetup(setup, { global?, attachTo? })`: mounts a component whose `setup` sets up what its render needs below it (a select, a provided context) and returns that render (XO 6 wraps it with its config); `mountWithSetupResult(setup, options)`: the same, keeping what `setup` builds (a form, a composable's return), `setup` returning `{ result, render }`, returns `{ wrapper, result }`; `mountComposableUnderSetup(setup, composable, options)`: runs `composable` (given what `setup` returned) in a child of the component whose `setup` provides what it injects, returns `{ provided, result }` |
|
||||
| `test/mount-with-select.ts` | `renderSelect(id, { accent?, ref? }, slots?)`: renders the `VtsSelect` of a select id, `neutral` accent by default; `mountSelect`: a `VtsSelect` of string sources, its config, accent, wrapper message, option slot and a callback receiving the mounted select |
|
||||
| `test/find-title.ts` | `findTitle`: the `.title` of a `VtsSuccessStateHero` or a list item, `undefined` without one (also used by XO 6) |
|
||||
| `test/create-task-item.ts` | `createTaskItem`: a `Task` as the task lists display it, with the given overrides (also used by XO 6) |
|
||||
| `tsconfig.vitest.json` | Type-checks test files with the Vitest globals and the `@core-test` alias |
|
||||
| `tsconfig.app.json` | Type-checks the library, test files excluded |
|
||||
|
||||
Test files sit next to the code they test, as `lib/**/*.unit.test.ts`. Shared test infrastructure lives in `test/`, outside `lib/`. The shared `scripts/npmignore` keeps all of it out of the published package.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Testing composables
|
||||
|
||||
A composable that relies on a Vue context (`useI18n`, `inject`, an effect scope, plugins) must run **inside a mounted component**: a throwaway component whose `setup` calls it, mounted with the package's global test config. `mountComposable` (`@core-test/mount-composable.ts`) does it and returns `{ wrapper }`; XO 6 wraps it with its own global test config (see [XO 6 composables](../../../web/docs/tests/testing-composables.md)). `mountComposable` renders nothing, so a composable needing rendered elements (a `useTemplateRef` target, as `useMenuPopup`) is the one case mounted by hand, with a component rendering them. A composable needing no Vue context is called directly, like a [utility](./testing-utilities.md).
|
||||
A composable that relies on a Vue context (`useI18n`, `inject`, an effect scope, plugins) must run **inside a mounted component**: a throwaway component whose `setup` calls it, mounted with the package's global test config. `mountComposable` (`@core-test/mount-composable.ts`) does it and returns `{ wrapper }`; XO 6 wraps it with its own global test config (see [XO 6 composables](../../../web/docs/tests/testing-composables.md)). `mountComposable` renders nothing, so a composable needing rendered elements (a `useTemplateRef` target, as `useMenuPopup`) is mounted with `mountWithSetupResult` (`@core-test/mount-with-setup.ts`): its `setup` calls the composable and returns it as `result`, with a render of those elements. A composable needing no Vue context is called directly, like a [utility](./testing-utilities.md).
|
||||
|
||||
Because the real i18n instance is installed, translations resolve to actual strings, and the assertion builds its expected label with `t` instead of hard-coding the wording — see [Assert behavior](./assert-behavior.md).
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user