Compare commits

..

17 Commits

Author SHA1 Message Date
Alexandre Mouillard
b322f12769 feat(xo6/lite): add stats tabs for hosts, VMs and pools
Charts the CPU, RAM, network and load (or disk for VMs) stats over the
last 10 minutes, 2 hours, week or year, with one line per CPU,
interface, disk or host and an option to show the totals, as in XO 5.

The stats-to-chart mapping and the toolbar/charts components live in
web-core, shared by XO 6 and XO Lite.
2026-12-01 15:49:42 +01:00
Alina D
2475403b11 feat(lite): add possibility to delete a VIF (#10726) 2026-12-01 13:21:55 +01:00
MikitaKavaliouVates
0ae5d39aa5 feat(@vates/task, xapi, backups, xo-server, backup-reports): abort backup jobs running in the main thread (#10875)
BREAKING CHANGE: a subtask created under an aborted task no longer runs, unless it is created with
`cleanup: true`.

🔗 XO-3352

With backups.disableWorkers, a backup job could not be stopped. It can now be aborted from its task, the "run schedule" action or job.cancel: the transfers stop, the cleanup still runs and the run ends interrupted.

@vates/task: the new root option skipSubtasksAfterAbort skips the steps of an aborted task, except cleanup: true ones. Only backups use it.
Fixes the VM directory lock not being released after a failed transfer.
2026-12-01 11:52:21 +01:00
Sylvère
77b00ff871 feat(lite): 0.28.0 (#10951) 2026-12-01 08:22:41 +01:00
Sylvère
ed86fbec17 feat: release 6.11 (#10949) 2026-11-30 17:01:05 +01:00
Sylvère
1e6a049072 feat: technical release (#10946) 2026-11-30 14:26:35 +01:00
Mathieu
032159a609 feat(rest-api): CSRF middleware protection (#10945)
* feat: add CSRF protection middleware

* feat: scope urlencode middleware to signin routes

* feat: cookie sameSite default to lax

* changelog

---------

Co-authored-by: MathieuRA <contact@mathieu-raisin.fr>
2026-11-30 13:50:38 +01:00
Mathieu
a5295c6731 fix(auth-ldap): block LDAP unauthenticated bind via null password in session.signIn (#10944)
A JSON `null` password sent to `session.signIn` reached the LDAP provider,
which passed it to `client.bind()`. ldapts turns this into an LDAP
unauthenticated bind (DN + empty password), which some directories, such as
Active Directory by default, accept as a successful login. Anyone knowing a
username could sign in without its password.

- xo-server-auth-ldap: only bind with non-empty string username and password
- xo-server: reject empty or non-string passwords in `authenticateUser`,
  before any provider is called
- xo-server: add a `params` schema to `session.signIn` so non-string
  credentials are rejected at the API layer

Co-authored-by: Pierre Donias <pierre.donias@vates.tech>
2026-11-30 13:42:17 +01:00
Alex Castillo González
c8260fb259 fix(rest-api): keep colons in the password of Basic authentication (#10801) 2026-11-30 12:07:47 +01:00
Sylvère
756d7fa940 fix(xo6): my tasks optimization (#10935) 2026-11-30 11:11:04 +01:00
Thierry Goettelmann
8f925cb605 chore(xo6,web-core): upgrade vitest to v5 (#10941)
With Node 26, most unit test suites of `@xen-orchestra/web` fail at
import: Node's native `localStorage` is enabled by default, is
`undefined` without `--localstorage-file`, and shadows the one provided
by the test environment. Vitest 5 handles it.

See XO-3517
2026-11-30 09:43:30 +01:00
Florent BEAUCHAMP
54051163e0 feat(vdi): implement resize online (#10845)
* refactor(xapi): extract VDI.resize method
* refactor(xapi): centralize size check
* feat(xapi): implement resize online
2026-11-27 15:05:51 +01:00
vates-bot
9ff4716ef1 feat(web-stack/i18n): update Xen Orchestra 6 (#10680) 2026-11-27 14:18:00 +01:00
Sylvère
810e342df2 feat: technical release (#10926)
* feat(xo-collection): 1.0.1

* feat(@vates/nbd-client): 3.7.2

* feat(@vates/types): 3.1.0

* feat(@xen-orchestra/backups): 1.0.1

* feat(@xen-orchestra/web-core): 0.66.1

* feat(@xen-orchestra/proxy): 0.35.1

* feat(@xen-orchestra/vmware-explorer): 1.4.0

* feat(@xen-orchestra/rest-api): 0.43.0

* feat(@xen-orchestra/web): 0.66.1

* feat(xo-server): 5.214.1

* chore(CHANGELOG): update next
2026-11-27 11:10:16 +01:00
Florent BEAUCHAMP
20e90b6d0f fix(xo-web): sanitize-html dependency (#10899)
Since 2.17.6, sanitize-html depends on htmlparser2 ^12, which is
ESM-only. Browserify cannot bundle it and the build fails with:

    'import' and 'export' may appear only with 'sourceType: module'

The dev setup is not affected because yarn.lock resolves 2.17.4, but
xoa-packager installs each package with `npm install` and no lockfile,
so `^2.17.4` resolves to the latest release as soon as xo-web's
node_modules is recreated.

Pin the exact version until xo-web's bundler can handle ESM-only
dependencies.
2026-11-27 10:00:36 +01:00
Joris K
c23587cbdc fix(xo6/site): stop displaying the site pages below the pools loader (#10923) 2026-11-27 09:46:51 +01:00
Mathieu
f67f94a60b feat(vmware-explorer): fall back to RSA key exchange on ESXi 6.5 data port (#10802)
feat(vmware-explorer): fall back to RSA key exchange on ESXi 6.5 data port (#10802)
2026-11-26 17:09:13 +01:00
214 changed files with 7696 additions and 863 deletions

View File

@@ -13,7 +13,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "3.7.1",
"version": "3.7.2",
"engines": {
"node": ">=14.0"
},

View File

@@ -25,6 +25,17 @@ const task = new Task({
const { reason } = event
}
},
// only for a detached task, inherited by its subtasks
//
// if true, a subtask created after the abort of its parent is aborted, and ended, right away: running it rejects
// with the abort reason without calling its function, so the remaining steps of an aborted task are skipped
skipSubtasksAfterAbort: false,
// if true, this subtask does not follow the abort of its parent, so that it still runs after an abort
//
// meant for the cleanup steps of an aborted task
cleanup: false,
})
// this field is settable once before being observed
@@ -38,9 +49,12 @@ task.id
// - failure
task.status
// Triggers the abort signal associated to the task.
// Triggers the abort signal associated to the task, and the ones of its subtasks.
//
// This simply requests the task to abort, it will be up to the task to handle or not this signal.
// A running task is only requested to abort: it is up to its function to handle or not this signal.
//
// A task that is not running ends right away as failed, with `reason` as result, and running it afterwards rejects
// with `reason` without calling its function. See `skipSubtasksAfterAbort` for the subtasks created after the abort.
task.abort(reason)
// if fn rejects, the task will be marked as failed

View File

@@ -41,6 +41,17 @@ const task = new Task({
const { reason } = event
}
},
// only for a detached task, inherited by its subtasks
//
// if true, a subtask created after the abort of its parent is aborted, and ended, right away: running it rejects
// with the abort reason without calling its function, so the remaining steps of an aborted task are skipped
skipSubtasksAfterAbort: false,
// if true, this subtask does not follow the abort of its parent, so that it still runs after an abort
//
// meant for the cleanup steps of an aborted task
cleanup: false,
})
// this field is settable once before being observed
@@ -54,9 +65,12 @@ task.id
// - failure
task.status
// Triggers the abort signal associated to the task.
// Triggers the abort signal associated to the task, and the ones of its subtasks.
//
// This simply requests the task to abort, it will be up to the task to handle or not this signal.
// A running task is only requested to abort: it is up to its function to handle or not this signal.
//
// A task that is not running ends right away as failed, with `reason` as result, and running it afterwards rejects
// with `reason` without calling its function. See `skipSubtasksAfterAbort` for the subtasks created after the abort.
task.abort(reason)
// if fn rejects, the task will be marked as failed

View File

@@ -35,6 +35,17 @@ function define(object, property, value) {
const noop = Function.prototype
// aborts `controller` when `signal` is aborted, right away if it already is
//
// `signal.aborted` must be checked: the abort event of an already aborted signal is never dispatched again
function followSignal(signal, controller) {
if (signal.aborted) {
controller.abort(signal.reason)
} else {
signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true })
}
}
const FAILURE = 'failure'
const PENDING = 'pending'
const SUCCESS = 'success'
@@ -86,11 +97,12 @@ class Task {
}
}
// These two properties should not be used outside the class
// These properties should not be used outside the class
//
// To ensure compatibility between multiple versions of this lib, they are kept public for now
_abortController = new AbortController()
_onProgress
_skipSubtasksAfterAbort = false
get id() {
// Use a compact, sortable, string representation of the creation date,
@@ -110,18 +122,26 @@ class Task {
return this.#status
}
constructor({ properties, onProgress } = {}) {
// `skipSubtasksAfterAbort` (root task only, inherited by its subtasks): a subtask created after the abort is
// aborted right away, so the steps of an aborted task are skipped.
//
// `cleanup`: this subtask does not follow the abort of its parent, so that it still runs after an abort.
constructor({ properties, onProgress, cleanup = false, skipSubtasksAfterAbort = false } = {}) {
this.#startData = { properties }
// the parent signal this task's abort follows, once its own listener is registered
let parentSignal
if (onProgress !== undefined) {
this._onProgress = onProgress
this._skipSubtasksAfterAbort = skipSubtasksAfterAbort
} else {
const parent = getTask()
if (parent !== undefined) {
const { signal } = parent._abortController
signal.addEventListener('abort', () => {
this._abortController.abort(signal.reason)
})
// `_skipSubtasksAfterAbort` is missing on a task created by an older version of this library
this._skipSubtasksAfterAbort = parent._skipSubtasksAfterAbort === true
if (!cleanup) {
parentSignal = parent._abortController.signal
}
this._onProgress = parent._onProgress
this.#startData.parentId = parent.id
@@ -138,10 +158,23 @@ class Task {
this.#emit('abortionRequested', { reason: signal.reason })
if (!this.#running) {
this.#endedByAbort = true
this.#end(FAILURE, signal.reason)
}
}
})
if (parentSignal !== undefined) {
if (this._skipSubtasksAfterAbort) {
// after the listener above: a task created under an aborted parent is aborted, and ended, right away (its
// `run()` then rejects without calling its function), as if its parent had been aborted just after its creation
followSignal(parentSignal, this._abortController)
} else {
parentSignal.addEventListener('abort', () => {
this._abortController.abort(parentSignal.reason)
})
}
}
}
abort(reason) {
@@ -192,8 +225,14 @@ class Task {
return result
}
#endedByAbort = false
#running = false
async runInside(fn) {
// aborted before it could run, either directly or because it was created under an aborted parent
if (this.#endedByAbort) {
throw this._abortController.signal.reason
}
assert.equal(this.status, PENDING)
assert.equal(this.#running, false)
this.#running = true

View File

@@ -175,6 +175,213 @@ describe('Task', function () {
})
})
describe('subtask of an aborted task', function () {
// events of `subtask`, in the order they were emitted to the root task
const subtaskEventTypes = (task, subtask) => task.$events.filter(_ => _.id === subtask.id).map(_ => _.type)
describe('without skipSubtasksAfterAbort', function () {
it('runs when created after the abort, as before this option existed', async function () {
const task = createTask()
await task.run(async () => {
task.abort()
assert.equal(
await Task.run(() => {
assert.equal(Task.abortSignal.aborted, false)
return 'done'
}),
'done'
)
})
})
it('is aborted when its parent is aborted while it runs', async function () {
const task = createTask()
await task.run(() =>
Task.run(() => {
task.abort()
assert.equal(Task.abortSignal.aborted, true)
})
)
})
})
describe('with skipSubtasksAfterAbort', function () {
it('does not run when created after the abort', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
const reason = {}
let called = false
let subtask
await task.run(async () => {
task.abort(reason)
subtask = new Task()
await assert.rejects(
subtask.run(() => {
called = true
}),
error => error === reason
)
})
assert.equal(called, false)
assert.equal(subtask.status, 'failure')
assert.deepEqual(subtaskEventTypes(task, subtask), ['start', 'abortionRequested', 'end'])
const end = task.$events.findLast(_ => _.id === subtask.id)
assert.equal(end.status, 'failure')
assert.equal(end.result, reason)
})
it('does not run a step started with Task.run() after the abort', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
let called = false
await task.run(async () => {
task.abort()
await assert.rejects(
Task.run({ properties: { name: 'step' } }, () => {
called = true
}),
{ name: 'AbortError' }
)
})
assert.equal(called, false)
})
it('does not run when created before the abort and run after it', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
const reason = {}
let called = false
let subtask
await task.run(async () => {
subtask = new Task()
task.abort(reason)
await assert.rejects(
subtask.run(() => {
called = true
}),
error => error === reason
)
})
assert.equal(called, false)
assert.equal(subtask.status, 'failure')
assert.deepEqual(subtaskEventTypes(task, subtask), ['start', 'abortionRequested', 'end'])
})
it('is inherited by the subtasks of the subtasks', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
let called = false
await task.run(() =>
Task.run(async () => {
task.abort()
await assert.rejects(
Task.run(() => {
called = true
}),
{ name: 'AbortError' }
)
}).catch(noop)
)
assert.equal(called, false)
})
it('is ignored on a subtask', async function () {
const task = createTask()
await task.run(async () => {
task.abort()
assert.equal(await Task.run({ skipSubtasksAfterAbort: true }, () => Task.run(() => 'done')), 'done')
})
})
})
it('still throws when run after it ended for another reason', async function () {
const task = createTask()
task.start()
task.success()
await assert.rejects(task.run(noop), { name: 'AssertionError' })
})
})
describe('cleanup subtask', function () {
it('runs when created after the abort', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
let subtask
await task.run(async () => {
task.abort()
subtask = new Task({ cleanup: true })
const result = await subtask.run(() => {
assert.equal(Task.abortSignal.aborted, false)
return 'cleaned'
})
assert.equal(result, 'cleaned')
})
assert.equal(subtask.status, 'success')
})
it('runs through Task.run() with the cleanup option', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
await task.run(async () => {
task.abort()
assert.equal(await Task.run({ properties: { name: 'clean-vm' }, cleanup: true }, () => 'cleaned'), 'cleaned')
})
})
it('is not aborted when its parent is aborted while it runs', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
await task.run(() =>
Task.run({ cleanup: true }, () => {
task.abort()
assert.equal(Task.abortSignal.aborted, false)
})
)
})
it('lets its own subtasks run normally', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
await task.run(async () => {
task.abort()
const result = await Task.run({ cleanup: true }, () => Task.run(() => 'done'))
assert.equal(result, 'done')
})
})
})
describe('without abort', function () {
it('emits the same events for a task and its subtasks', async function () {
const task = createTask()
await task.run(() => Task.run({ properties: { name: 'step' } }, () => Task.run(() => 'foo')))
assert.deepEqual(
task.$events.map(_ => _.type),
['start', 'start', 'start', 'end', 'end', 'end']
)
assert.equal(task.status, 'success')
})
})
describe('#failure()', function () {
const error = new Error()

View File

@@ -1,7 +1,7 @@
{
"name": "@vates/types",
"private": false,
"version": "3.0.0",
"version": "3.2.0",
"main": "./dist/index.mjs",
"exports": {
".": {

View File

@@ -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

View File

@@ -30,7 +30,7 @@
},
"devDependencies": {
"@eslint/js": "^9.19.0",
"@vates/types": "^3.0.0",
"@vates/types": "^3.2.0",
"rimraf": "^6.0.1",
"typescript": "~5.6",
"typescript-eslint": "^8.61.0"

View File

@@ -21,7 +21,7 @@
"tar-stream": "^3.1.8",
"@types/tar-stream": "^3.1.4",
"tmp": "^0.2.1",
"@vates/types": "^3.0.0"
"@vates/types": "^3.2.0"
},
"dependencies": {
"@xen-orchestra/log": "^1.0.0",

View File

@@ -8,7 +8,7 @@
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/fs": "^4.11.0",
"filenamify": "^6.0.0",
"getopts": "^2.2.5",

View File

@@ -21,6 +21,9 @@ export class HealthCheckVmBackup {
const xapi = this.#xapi
const restoredId = restoredVm.uuid
// the health check stops waiting once the backup is aborted; the caller removes the restored VM
const signal = Task.abortSignal
// remove vifs
await Promise.all(restoredVm.$VIFs.map(vif => xapi.callAsync('VIF.destroy', vif.$ref)))
const waitForScript = restoredVm.tags.includes('xo-backup-health-check-xenstore')
@@ -33,6 +36,7 @@ export class HealthCheckVmBackup {
// start Vm
await xapi.callAsync(
signal,
'VM.start',
restoredVm.$ref,
false, // Start paused?
@@ -51,6 +55,7 @@ export class HealthCheckVmBackup {
// wait for the 'Running' event to be really stored in local xapi object cache
restoredVm = await xapi.waitObjectState(restoredVm.$ref, vm => vm.power_state === 'Running', {
signal,
timeout: remainingTimeout,
timeoutMessage: refOrUuid =>
`local xapi did not get Running state for VM ${refOrUuid} after ${timeout / 1000} second`,
@@ -61,6 +66,7 @@ export class HealthCheckVmBackup {
// wait for the guest tools to be detected
await xapi.waitObjectState(restoredVm.guest_metrics, gm => gm?.PV_drivers_detected, {
signal,
timeout: remainingTimeout,
timeoutMessage: refOrUuid =>
`timeout reached while waiting for ${refOrUuid} to report the driver version through the Xen tools. Please check or update the Xen tools.`,
@@ -77,6 +83,7 @@ export class HealthCheckVmBackup {
(vm.xenstore_data['vm-data/xo-backup-health-check'] === 'success' ||
vm.xenstore_data['vm-data/xo-backup-health-check'] === 'failure'),
{
signal,
timeout: remainingTimeout,
timeoutMessage: refOrUuid =>
`timeout reached while waiting for ${refOrUuid} to report the startup script execution.`,

View File

@@ -0,0 +1,52 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { Task } from '@vates/task'
import { HealthCheckVmBackup } from './HealthCheckVmBackup.mjs'
describe('HealthCheckVmBackup#run() after an abort', () => {
it('stops waiting for the restored VM without waiting for its timeout', async () => {
// resolved once the restored VM is started
const { promise: pStarted, resolve: onStarted } = Promise.withResolvers()
const xapi = {
callAsync: async (...args) => {
if (args.includes('VM.start')) {
onStarted()
}
},
// the restored VM never reaches the expected state: only an abort can end the wait
waitObjectState: (ref, predicate, { signal } = {}) =>
new Promise((resolve, reject) => {
// as `Xapi#waitObjectState()` does, rejects right away when already aborted
if (signal?.aborted) {
reject(signal.reason)
} else {
signal?.addEventListener('abort', () => reject(signal.reason), { once: true })
}
}),
}
const healthCheck = new HealthCheckVmBackup({
restoredVm: { $ref: 'vm-ref', $VIFs: [], tags: [], uuid: 'vm-uuid' },
timeout: 60e3,
xapi,
})
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const result = await vmTask
.run(async () => {
const pRun = healthCheck.run()
await pStarted
vmTask.abort()
return Promise.race([
pRun.then(
() => 'resolved',
error => error.name
),
new Promise(resolve => setTimeout(resolve, 1e3, 'still waiting')),
])
})
.catch(error => error.name)
assert.equal(result, 'AbortError')
})
})

View File

@@ -3,6 +3,7 @@ import assert from 'node:assert'
import { formatFilenameDate } from './_filenameDate.mjs'
import { importIncrementalVm } from './_incrementalVm.mjs'
import { liveMountXapiLabels } from './liveMountXapiLabels.mjs'
import { destroyOnAbort } from './_destroyOnAbort.mjs'
import { watchStreamSize } from './_watchStreamSize.mjs'
import { decorateClass } from '@vates/decorate-with'
import { Task } from '@vates/task'
@@ -425,6 +426,13 @@ export class ImportVmBackup {
}
backup = await adapter.readFullVmBackup(metadata)
watchStreamSize(backup, sizeContainer)
// the restore stops once aborted (e.g. the health check of an aborted backup): a full backup is a stream that
// `VM_import()` sends as is, destroying it fails the import, and XAPI drops the partial VM
//
// set up as soon as the stream exists, so that an abort landing before the import starts, or leaving the transfer
// subtask unable to run, still closes it (a file handle or an S3 request)
$defer(destroyOnAbort(backup, Task.abortSignal))
} else {
assert.strictEqual(metadata.mode, 'delta')
@@ -451,12 +459,21 @@ export class ImportVmBackup {
additionalVmTag !== undefined && vm.add_tags(additionalVmTag),
])
const vmRef = isFull
? await xapi.VM_import(backup, srRef, onVmCreation)
: await importIncrementalVm(backup, await xapi.getRecord('SR', srRef), {
newMacAddresses,
vmNamePrefix,
})
const signal = Task.abortSignal
let vmRef
try {
vmRef = isFull
? await xapi.VM_import(backup, srRef, onVmCreation)
: await importIncrementalVm(backup, await xapi.getRecord('SR', srRef), {
newMacAddresses,
signal,
vmNamePrefix,
})
} catch (error) {
// the error of the destroyed stream: report the abort instead
signal?.throwIfAborted()
throw error
}
let size = 0
if (isFull) {
size = sizeContainer.size

View File

@@ -304,3 +304,109 @@ describe('ImportVmBackup#_reuseNearestSnapshot()', () => {
await assert.rejects(() => importer._reuseNearestSnapshot(new Set([SYSTEM.uuid])), /would transfer the disk/)
})
})
describe('ImportVmBackup#run() after an abort', () => {
// a full restore whose steps `xapi` and `adapter` are controlled by the test: it reads `xva` and imports it with
// `VM_import()`, which, as the XAPI one does, reads its input until it ends and fails when the input fails
async function makeFullRestore({ onOpen, onSrLookup } = {}) {
const { PassThrough } = await import('node:stream')
const xva = new PassThrough()
// `importing` is resolved once `VM_import()` reads the stream
const { promise: importing, resolve: onImport } = Promise.withResolvers()
const state = { imported: false, importing }
const importer = new ImportVmBackup({
adapter: {
_handler: { _remote: {} },
readFullVmBackup: async () => {
await onOpen?.()
return xva
},
},
metadata: { ...makeMetadata(), mode: 'full' },
srUuid: DEFAULT_SR,
xapi: {
call: async () => {
await onSrLookup?.()
return 'OpaqueRef:sr'
},
VM_import: stream =>
new Promise((resolve, reject) => {
state.imported = true
onImport()
stream.on('error', () => reject(new Error('premature close'))).resume()
}),
},
})
return { importer, state, xva }
}
// the outcome of `run()`, `'still running'` if it does not settle within a second
const outcomeOf = pRun =>
Promise.race([
pRun.then(
() => 'resolved',
error => error.name
),
new Promise(resolve => setTimeout(resolve, 1e3, 'still running')),
])
it('stops the import of a full backup and fails with the abort', async () => {
const { Task } = await import('@vates/task')
const { importer, state } = await makeFullRestore()
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const result = await vmTask
.run(async () => {
const pRun = importer.run()
await state.importing
vmTask.abort()
return outcomeOf(pRun)
})
.catch(error => error.name)
assert.equal(result, 'AbortError')
})
it('stops a full restore aborted before its import has started, and destroys its stream', async () => {
const { Task } = await import('@vates/task')
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
// the abort lands during the lookup of the SR, after the transfer subtask started
const { importer, xva } = await makeFullRestore({ onSrLookup: () => vmTask.abort() })
const result = await vmTask.run(() => outcomeOf(importer.run())).catch(error => error.name)
assert.equal(result, 'AbortError')
assert.equal(xva.destroyed, true)
})
it('destroys the stream of a full backup when the abort lands while it is opened', async () => {
const { Task } = await import('@vates/task')
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
// the transfer subtask is then created under an aborted task: it fails without running
const { importer, state, xva } = await makeFullRestore({ onOpen: () => vmTask.abort() })
const result = await vmTask.run(() => outcomeOf(importer.run())).catch(error => error.name)
assert.equal(result, 'AbortError')
assert.equal(state.imported, false)
assert.equal(xva.destroyed, true, 'the stream (a file handle or an S3 request) is not left open')
})
it('restores a full backup outside a task, as the proxy does', async t => {
// `golike-defer` logs the errors of the deferred functions instead of rejecting with them
const logError = t.mock.method(console, 'error', () => {})
const { importer, xva } = await makeFullRestore()
importer._xapi.VM_import = async stream => {
stream.resume()
throw new Error('stop after the import')
}
xva.end()
// the error of the import, not one of the abort handling, which has no signal to listen to
await assert.rejects(importer.run(), { message: 'stop after the import' })
assert.deepEqual(
logError.mock.calls.map(call => String(call.arguments[0])),
[]
)
})
})

View File

@@ -317,6 +317,34 @@ describe('RemoteAdapter#writeVhd validated by checkDisk', { concurrency: 1 }, ()
assert.deepEqual(await handler.list(basePath, { ignoreMissing: true }), useVhdDirectory ? ['data'] : [])
assert.deepEqual(await handler.list(`${basePath}/data`, { ignoreMissing: true }), [])
})
test(`${mode}: an aborted write stops and leaves no disk behind`, async () => {
const adapter = await getAdapter({ useVhdDirectory })
const path = `${basePath}/${adapter.getVhdFileName('base')}`
const controller = new AbortController()
const read = []
// the backup is aborted once the first block has been read
class AbortedDisk extends MockDisk {
async readBlock(index) {
read.push(index)
if (read.length === 1) {
controller.abort()
}
return super.readBlock(index)
}
}
await assert.rejects(
adapter.writeVhd(path, new AbortedDisk(8, [0, 1, 2, 3, 4, 5, 6, 7], 0x11), {
signal: controller.signal,
uuid: uniqueIdBuffer(),
}),
{ name: 'AbortError' }
)
assert.deepEqual(await handler.list(basePath, { ignoreMissing: true }), useVhdDirectory ? ['data'] : [])
assert.deepEqual(await handler.list(`${basePath}/data`, { ignoreMissing: true }), [])
})
}
})

View File

@@ -687,12 +687,14 @@ export class RemoteAdapter {
return path
}
async writeVhd(path, disk, { validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
// `signal` stops the write once aborted: the partial disk is then removed
async writeVhd(path, disk, { signal, validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
const handler = this._handler
if (this.useVhdDirectory()) {
return await writeToVhdDirectory({
disk,
signal,
target: {
handler,
path,
@@ -705,7 +707,11 @@ export class RemoteAdapter {
},
})
} else {
const stream = await toVhdStream(disk, { uuid, parentUuid, parentPath })
const stream = await toVhdStream(disk, { signal, uuid, parentUuid, parentPath })
// the stream starts reading the disk before the output stream is piped (`outputStream()` creates it first): an
// error in between (an abort, a read error) must not be emitted without listener, which would crash the process
// the pipeline still fails with this error, kept by the stream
stream.on('error', noop)
const size = await this.outputStream(path, stream, {
validator,
// no checksum for VHDs, because they will be invalidated by

View File

@@ -178,6 +178,8 @@ process.on('message', async message => {
? await Task.run(
{
properties: { name: 'backup run', ...message.data.jobData },
// the steps of an aborted backup are skipped, as when the backup runs in the main thread
skipSubtasksAfterAbort: true,
onProgress: data =>
emitMessage({
data,

View File

@@ -0,0 +1,28 @@
const noop = Function.prototype
/**
* Destroys `stream` with the reason of `signal` once it is aborted, right away if it already is.
*
* Nothing may be listening to the stream when it is destroyed: an error event without a listener would crash the
* process, so a noop listener is added.
*
* @param {import('node:stream').Readable} stream
* @param {AbortSignal} [signal] nothing is done without a signal, e.g. a restore run outside a task
* @returns {() => void} removes the abort listener
*/
export function destroyOnAbort(stream, signal) {
if (signal === undefined) {
return noop
}
stream.on('error', noop)
const onAbort = () => stream.destroy(signal.reason)
if (signal.aborted) {
onAbort()
return noop
}
signal.addEventListener('abort', onAbort, { once: true })
return () => signal.removeEventListener('abort', onAbort)
}

View File

@@ -0,0 +1,50 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { PassThrough } from 'node:stream'
import { destroyOnAbort } from './_destroyOnAbort.mjs'
describe('destroyOnAbort()', () => {
it('does nothing without a signal', () => {
const stream = new PassThrough()
destroyOnAbort(stream, undefined)()
assert.equal(stream.destroyed, false)
assert.equal(stream.listenerCount('error'), 0)
})
it('destroys the stream right away when the signal is already aborted', () => {
const stream = new PassThrough()
const reason = new Error('aborted')
destroyOnAbort(stream, AbortSignal.abort(reason))
assert.equal(stream.destroyed, true)
assert.equal(stream.errored, reason)
})
it('destroys the stream once aborted, without crashing when nothing listens to it', async () => {
const stream = new PassThrough()
const controller = new AbortController()
const reason = new Error('aborted')
destroyOnAbort(stream, controller.signal)
controller.abort(reason)
// the error event is emitted on the next tick: an unhandled one would crash the test process
await new Promise(resolve => setImmediate(resolve))
assert.equal(stream.destroyed, true)
assert.equal(stream.errored, reason)
})
it('returns a function that stops listening to the signal', () => {
const stream = new PassThrough()
const controller = new AbortController()
destroyOnAbort(stream, controller.signal)()
controller.abort()
assert.equal(stream.destroyed, false)
})
})

View File

@@ -32,7 +32,9 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
const disks = {}
const vdis = {}
const vbds = {}
await abortableMap(signal, vm.$VBDs, async (signal, vbd) => {
// the signal given to the callback stops the other initializations when one fails; the disks keep `signal`, which
// must keep reaching them once the export is built
await abortableMap(signal, vm.$VBDs, async (_initSignal, vbd) => {
let vdi
if (vbd.type !== 'Disk' || !(vdi = vbd.$VDI)) {
// Ignore this VBD.
@@ -68,6 +70,7 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
baseRef: baseVdi?.$ref,
nbdConcurrency,
preferNbd,
signal,
})
await disks[vdiRef].init()
})
@@ -84,6 +87,7 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
xapi: vm.$xapi,
nbdConcurrency,
preferNbd,
signal,
})
await disks[vdiRef].init()
}

View File

@@ -40,6 +40,9 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
}
async run() {
// abort signal of the backup run: once aborted, no new VM backup starts and no VM backup is retried
const signal = Task.abortSignal
const job = this._job
const schedule = this._schedule
const settings = this._settings
@@ -81,6 +84,10 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
const nTriesByVmId = {}
const handleVm = async vmUuid => {
if (signal?.aborted) {
return
}
if (nTriesByVmId[vmUuid] === undefined) {
nTriesByVmId[vmUuid] = 0
}
@@ -143,9 +150,10 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
nbVmsDone++
return task.success(result)
}
if (isLastRun) {
// once aborted, the VM backup is not retried: it failed because of the abort, whatever its error
if (isLastRun || signal?.aborted) {
nbVmsDone++
return task.failure(taskError)
return task.failure(signal?.aborted ? signal.reason : taskError)
}
Task.set('progress', Math.round((nbVmsDone * 100) / nbVms))
// don't end the task

View File

@@ -0,0 +1,73 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { Task } from '@vates/task'
import { FullRemote } from './_vmRunners/FullRemote.mjs'
import { VmsRemote } from './VmsRemote.mjs'
// a VM backup that runs until the run is aborted, as a transfer does
const backupUntilAborted = () =>
new Promise((resolve, reject) => {
const signal = Task.abortSignal
if (signal.aborted) {
reject(signal.reason)
} else {
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
}
})
function createRunner({ vms, settings = {} }) {
const sourceAdapter = {
listAllVms: async () => vms,
listVmBackups: async () => [{ mode: 'full', vm: {} }],
}
return new VmsRemote({
config: { snapshotNameLabelTpl: '[XO Backup {job.name}] {vm.name_label}' },
getAdapter: async remoteId => ({ value: remoteId === 'source' ? sourceAdapter : {}, dispose() {} }),
getConnectedRecord: async () => {
throw new Error('no record in these tests')
},
job: {
id: 'job',
mode: 'full',
name: 'job',
remotes: { id: { __or: ['source', 'target'] } },
settings: { '': { concurrency: 1, ...settings } },
sourceRemote: 'source',
},
schedule: { id: 'schedule' },
})
}
// runs the runner inside a root task, aborted once the first VM backup has started
async function runAndAbort(runner, calls) {
const events = []
const root = new Task({ skipSubtasksAfterAbort: true, onProgress: event => events.push(event) })
const pRun = root.run(() => runner.run())
while ((calls.vm1 ?? 0) === 0) {
await new Promise(resolve => setImmediate(resolve))
}
root.abort()
await pRun.catch(() => {})
return events.filter(_ => _.type === 'start' && _.properties?.type === 'VM').map(_ => _.properties.id)
}
describe('VmsRemote#run() after an abort', () => {
it('does not start the backup of the next VMs, nor retry the aborted one', async t => {
const calls = {}
t.mock.method(FullRemote.prototype, 'run', function () {
calls[this._vmUuid] = (calls[this._vmUuid] ?? 0) + 1
return this._vmUuid === 'vm1' ? backupUntilAborted() : Promise.resolve()
})
const vmTaskIds = await runAndAbort(
createRunner({ vms: ['vm1', 'vm2'], settings: { nRetriesVmBackupFailures: 2 } }),
calls
)
assert.deepEqual(calls, { vm1: 1 }, 'the aborted VM is not retried and the second VM is not backed up')
assert.deepEqual(vmTaskIds, ['vm1'], 'no task is created for the VMs not started')
})
})

View File

@@ -63,6 +63,9 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
}
async run() {
// abort signal of the backup run: once aborted, no new VM backup starts and no VM backup is retried
const signal = Task.abortSignal
const job = this._job
// FIXME: proper SimpleIdPattern handling
@@ -143,6 +146,10 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
await asyncEach(
[...vms].filter(vm => batchIds.has(vm.uuid)),
async vm => {
if (signal?.aborted) {
return
}
const { task } = getVmTask(vm.uuid, vm.name_label)
const vmSettings = { ...settings, ...allSettings[vm.uuid] }
@@ -205,9 +212,14 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
const queue = new Set(snapshotedVmIds)
const handleVm = vmUuid => {
if (signal?.aborted) {
return
}
const vmBackupFailed = async (error, task) => {
if (isLastRun) {
return task.failure(error)
// once aborted, the VM backup is not retried: it failed because of the abort, whatever its error
if (isLastRun || signal?.aborted) {
return task.failure(signal?.aborted ? signal.reason : error)
} else {
// don't end the task
task.warning(`Retry the VM backup due to an error`, {

View File

@@ -0,0 +1,89 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { Task } from '@vates/task'
import { VmsXapi } from './VmsXapi.mjs'
// a VM backup that runs until the run is aborted, as a transfer does
const backupUntilAborted = () =>
new Promise((resolve, reject) => {
const signal = Task.abortSignal
if (signal.aborted) {
reject(signal.reason)
} else {
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
}
})
function createRunner({ backups, settings = {} }) {
const runner = new VmsXapi({
config: { snapshotNameLabelTpl: '[XO Backup {job.name}] {vm.name_label}' },
getAdapter: () => {
throw new Error('no remote in these tests')
},
getConnectedRecord: async (type, id) => ({ $type: type, uuid: id, name_label: id }),
job: {
id: 'job',
mode: 'full',
name: 'job',
settings: { '': { concurrency: 1, ...settings } },
srs: { id: 'sr' },
vms: { id: { __or: Object.keys(backups) } },
},
schedule: { id: 'schedule' },
})
const calls = Object.fromEntries(Object.keys(backups).map(id => [id, 0]))
runner._getVmBackup = (mode, { vm }) => ({
run: () => {
++calls[vm.uuid]
return backups[vm.uuid]()
},
})
return { runner, calls }
}
// runs the runner inside a root task, aborted once the first VM backup has started
async function runAndAbort(runner, calls) {
const events = []
const root = new Task({ skipSubtasksAfterAbort: true, onProgress: event => events.push(event) })
const pRun = root.run(() => runner.run())
while (calls.vm1 === 0) {
await new Promise(resolve => setImmediate(resolve))
}
root.abort()
await pRun.catch(() => {})
const vmTaskIds = events.filter(_ => _.type === 'start' && _.properties?.type === 'VM').map(_ => _.properties.id)
return { events, vmTaskIds }
}
describe('VmsXapi#run() after an abort', () => {
it('does not start the backup of the next VMs', async () => {
const { runner, calls } = createRunner({
backups: { vm1: backupUntilAborted, vm2: async () => {} },
})
const { vmTaskIds } = await runAndAbort(runner, calls)
assert.equal(calls.vm2, 0, 'the second VM is not backed up')
assert.deepEqual(vmTaskIds, ['vm1'], 'no task is created for the VMs not started')
})
it('does not retry the aborted VM', async () => {
const { runner, calls } = createRunner({
backups: { vm1: backupUntilAborted },
settings: { nRetriesVmBackupFailures: 2 },
})
const { events } = await runAndAbort(runner, calls)
assert.equal(calls.vm1, 1, 'the aborted VM backup is not run again')
const vmTaskId = events.find(_ => _.type === 'start' && _.properties?.id === 'vm1').id
const vmEnd = events.find(_ => _.type === 'end' && _.id === vmTaskId)
assert.equal(vmEnd.status, 'failure')
assert.equal(vmEnd.result.name, 'AbortError')
})
})

View File

@@ -3,6 +3,7 @@ import { createLogger } from '@xen-orchestra/log'
import { AbstractRemote } from './_AbstractRemote.mjs'
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
import { destroyOnAbort } from '../../_destroyOnAbort.mjs'
import { watchStreamSize } from '../../_watchStreamSize.mjs'
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
import { Task } from '@vates/task'
@@ -23,6 +24,7 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
const nbTransferrableVms = transferList.length
let nbTransferredVms = 0
for (const metadata of transferList) {
Task.abortSignal?.throwIfAborted()
const stream = this._throttleStream(await this._sourceRemoteAdapter.readFullVmBackup(metadata))
const sizeContainer = watchStreamSize(stream)
let checksum
@@ -36,6 +38,9 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
// a single writer can consume the stream itself: no need to fork it
const isForked = this._writers.size > 1
// the source is a plain stream: destroying it stops the reading and makes the writers fail
const stopDestroyOnAbort = destroyOnAbort(stream, Task.abortSignal)
// @todo shouldn't transfer backup if it will be deleted by retention policy (higher retention on source than destination)
await this._callWriters(
writer =>
@@ -51,7 +56,7 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
sizeContainer,
}),
'writer.run()'
)
).finally(stopDestroyOnAbort)
// for healthcheck
this._vm = metadata.vm
nbTransferredVms++

View File

@@ -0,0 +1,119 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { PassThrough } from 'node:stream'
import { Task } from '@vates/task'
import { FullRemote } from './FullRemote.mjs'
const makeRunner = props => Object.assign(Object.create(FullRemote.prototype), props)
describe('FullRemote#_run() after an abort', () => {
it('stops reading the source backup', async () => {
const source = new PassThrough()
// resolved once the writer reads the stream
const { promise: pWriting, resolve: onWriting } = Promise.withResolvers()
const runner = makeRunner({
_computeTransferList: async () => [{ timestamp: 0, vm: {}, vmSnapshot: {} }],
_sourceRemoteAdapter: {
readFullVmBackup: async () => source,
readFullVmBackupChecksum: async () => {
throw new Error('no checksum')
},
},
_throttleStream: stream => stream,
_writers: new Set([
{
// a writer which writes until its input ends or fails
run: ({ stream }) =>
new Promise((resolve, reject) => {
onWriting()
stream.on('error', reject).on('end', resolve).resume()
}),
},
]),
})
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const result = await vmTask
.run(async () => {
const pRun = runner._run()
await pWriting
vmTask.abort()
return Promise.race([
pRun.then(
() => 'resolved',
error => error.name
),
new Promise(resolve => setTimeout(resolve, 1e3, 'still reading')),
])
})
.catch(error => error.name)
assert.equal(result, 'AbortError')
})
it('destroys the source stream when the abort came while the source was being opened', async () => {
// nothing listens to its errors: destroying it must not crash the process
const source = new PassThrough()
let written = false
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const runner = makeRunner({
_computeTransferList: async () => [{ timestamp: 0, vm: {}, vmSnapshot: {} }],
_sourceRemoteAdapter: {
readFullVmBackup: async () => source,
readFullVmBackupChecksum: async () => {
// the abort lands during the awaits that precede the registration of the listener
vmTask.abort()
throw new Error('no checksum')
},
},
_throttleStream: stream => stream,
_writers: new Set([
{
run: async () => {
written = true
},
},
]),
})
// the writers do not consume the stream: only the abort handling can close it
await vmTask.run(() => runner._run()).catch(() => {})
assert.equal(source.destroyed, true)
assert.equal(written, true)
})
it('does not open the source of the next backup once aborted', async () => {
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
let opened = 0
const runner = makeRunner({
_computeTransferList: async () => [
{ timestamp: 0, vm: {}, vmSnapshot: {} },
{ timestamp: 1, vm: {}, vmSnapshot: {} },
],
_sourceRemoteAdapter: {
readFullVmBackup: async () => {
++opened
// nothing listens to its errors: destroying it must not crash the process
return new PassThrough()
},
readFullVmBackupChecksum: async () => 'checksum',
},
_throttleStream: stream => stream,
_writers: new Set([
{
run: async () => {
vmTask.abort()
},
},
]),
})
await assert.rejects(
vmTask.run(() => runner._run()),
{ name: 'AbortError' }
)
assert.equal(opened, 1)
})
})

View File

@@ -1,4 +1,5 @@
import { createLogger } from '@xen-orchestra/log'
import { Task } from '@vates/task'
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
@@ -55,6 +56,8 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
(
await this._xapi.VM_export(exportedVm.$ref, {
compress: Boolean(compression) && (compression === 'native' ? 'gzip' : 'zstd'),
// the export stream fails once the backup is aborted, which stops the writers
signal: Task.abortSignal,
useSnapshot: false,
})
).body

View File

@@ -0,0 +1,68 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { PassThrough } from 'node:stream'
import { Task } from '@vates/task'
import { FullXapi } from './FullXapi.mjs'
const makeRunner = props => Object.assign(Object.create(FullXapi.prototype), props)
describe('FullXapi#_copy() after an abort', () => {
it('stops the XAPI export, and settles only once its writers have settled', async () => {
let exportOpts
// resolved once the XAPI export is called
const { promise: pExport, resolve: onExport } = Promise.withResolvers()
let writerSettledAt
const body = new PassThrough()
const runner = makeRunner({
job: {},
_vm: { uuid: 'vm-uuid' },
_exportedVm: { $ref: 'snapshot-ref', $getDisks: async () => [] },
_throttleStream: stream => stream,
_xapi: {
// as the HTTP export does: the body fails once the signal is aborted
VM_export: async (ref, opts) => {
exportOpts = opts
onExport()
opts.signal?.addEventListener('abort', () => body.destroy(opts.signal.reason), { once: true })
return { body }
},
},
_writers: new Set([
{
// a writer that needs some time to clean up after its input failed
run: ({ stream }) =>
new Promise((resolve, reject) => {
stream.on('error', error =>
setTimeout(() => {
writerSettledAt = Date.now()
reject(error)
}, 100)
)
stream.resume()
}),
},
]),
})
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
let copyRejectedAt
await vmTask
.run(async () => {
const pCopy = runner._copy()
await pExport
assert.ok(exportOpts.signal instanceof AbortSignal, 'the export gets the abort signal')
vmTask.abort()
await assert.rejects(pCopy, { name: 'AbortError' })
copyRejectedAt = Date.now()
})
.catch(error => {
if (error.name !== 'AbortError') {
throw error
}
})
assert.ok(writerSettledAt <= copyRejectedAt, 'the copy settles after its writers')
})
})

View File

@@ -85,6 +85,8 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
const nbTransferrableVms = transferList.length
let nbTransferredVms = 0
for (const metadata of transferList) {
// an abort during the previous VM's writer steps: its disks would be opened and never closed
Task.abortSignal?.throwIfAborted()
assert.strictEqual(metadata.mode, 'delta')
const incrementalExport = await this._sourceRemoteAdapter.readIncrementalVmBackup(metadata, undefined, {
useChain: false,

View File

@@ -1,5 +1,6 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { Task } from '@vates/task'
import { IncrementalRemote } from './IncrementalRemote.mjs'
@@ -43,3 +44,42 @@ describe('IncrementalRemote prepare()', () => {
assert.equal(aggWriter.props.schedule, schedule)
})
})
describe('IncrementalRemote#_run() after an abort', () => {
it('does not open the disks of the next backup once aborted', async () => {
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
let opened = 0
// a real instance: `_run()` uses a private method
const runner = Object.assign(makeRunner({ schedule: { id: 'schedule-id' } }), {
_computeTransferList: async () => [
{ mode: 'delta', timestamp: 0, vm: {}, vmSnapshot: {} },
{ mode: 'delta', timestamp: 1, vm: {}, vmSnapshot: {} },
],
_selectBaseVm: async () => {},
_sourceRemoteAdapter: {
getVhdDirectoryCompression: () => undefined,
readIncrementalVmBackup: async () => {
++opened
return { disks: {}, vbds: {}, vdis: {}, vifs: {}, vm: {}, vtpms: {} }
},
},
_writers: new Set([
{
getVhdDirectoryCompression: () => undefined,
prepare: async () => {},
transfer: async () => {},
// the abort lands during the writer steps of the first backup
cleanup: async () => {
vmTask.abort()
},
},
]),
})
await assert.rejects(
vmTask.run(() => runner._run()),
{ name: 'AbortError' }
)
assert.equal(opened, 1)
})
})

View File

@@ -55,6 +55,8 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
const deltaExport = await exportIncrementalVm(exportedVm, baseVdis, {
nbdConcurrency: this._settings.nbdConcurrency,
preferNbd: this._settings.preferNbd,
// the reads of the disks stop once the backup is aborted
signal: Task.abortSignal,
})
const isVhdDifferencing = {}

View File

@@ -233,6 +233,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
const snapshotRef = await vm[settings.checkpointSnapshot ? '$checkpoint' : '$snapshot']({
ignoredVdisTag: '[NOBAK]',
name_label: TEMP_SNAPSHOT_NAME,
signal: Task.abortSignal,
unplugVusbs: true,
})
this.timestamp = Date.now()

View File

@@ -2,6 +2,7 @@ import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { formatDateTime } from '@xen-orchestra/xapi'
import { Task } from '@vates/task'
import { AbstractXapi } from './_AbstractXapi.mjs'
import { DATETIME, EXPORTED_SUCCESSFULLY, JOB_ID, SCHEDULE_ID } from '../../_otherConfig.mjs'
@@ -657,3 +658,80 @@ describe('run() purges the snapshot data only while the snapshot exists', () =>
assert.deepEqual(calls.vmDestroyed, [], 'the live VM must never be destroyed')
})
})
describe('after an abort', () => {
it('_snapshot() passes the abort signal to the snapshot', async () => {
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
let received
const runner = makeRunner({
_settings: { bypassVdiChainsCheck: true },
_vm: {
$ref: 'vm-ref',
uuid: 'vm-uuid',
$snapshot: async opts => {
received = opts
// the backup is aborted while the snapshot is being taken
vmTask.abort()
throw new Error('stop after the snapshot call')
},
},
_xapi: {},
_mustDoSnapshot: async () => true,
})
await vmTask.run(() => assert.rejects(runner._snapshot(), /stop after the snapshot call/)).catch(() => {})
assert.ok(received.signal instanceof AbortSignal, 'the snapshot gets a signal')
assert.equal(received.signal.aborted, true, 'the snapshot gets the abort signal of the backup')
})
it('run() still applies the retention and restores the blocked operations, but skips the health check', async () => {
const calls = []
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const runner = makeRunner({
_settings: { offlineBackup: false, snapshotRetention: 0 },
_vm: {
uuid: 'live-uuid',
power_state: 'Halted',
blocked_operations: {},
update_blocked_operations: async ops => {
calls.push(Object.values(ops).every(_ => _ === null) ? 'unblock' : 'block')
},
$call: async () => {},
},
_writers: new Set([{ beforeBackup: async () => {}, afterBackup: async () => calls.push('afterBackup') }]),
_xapi: {},
_cleanMetadata: async () => {},
_fetchJobSnapshots: async () => {},
_selectBaseVm: async () => {},
_removeUnusedSnapshots: async () => calls.push('removeUnusedSnapshots'),
_removeSnapshotData: async () => calls.push('removeSnapshotData'),
_healthCheck: async () => calls.push('healthCheck'),
_snapshot: async function () {
this._exportedVm = { $ref: 'snapshot-ref', is_a_snapshot: true }
},
// a transfer, aborted while it runs
_copy: () =>
new Promise((resolve, reject) => {
const signal = Task.abortSignal
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
setImmediate(() => {
calls.push('abort')
vmTask.abort()
})
}),
})
await vmTask.run(() => assert.rejects(runner.run(), { name: 'AbortError' })).catch(() => {})
assert.deepEqual(calls, [
'block',
'removeUnusedSnapshots',
'abort',
'removeUnusedSnapshots',
'removeSnapshotData',
'unblock',
'afterBackup',
])
})
})

View File

@@ -161,8 +161,24 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
this._prepare = task.wrapInside(this._prepare)
this.transfer = task.wrapInside(this.transfer)
this.healthCheck = task.wrapInside(this.healthCheck)
this.cleanup = task.wrapInside(this.cleanup)
this.afterBackup = task.wrap(this.afterBackup)
// `cleanup()` applies the retention once the backup has been written: an abort that arrives after the transfer
// has already ended the task, the retention then runs in a cleanup subtask, which the abort does not stop
const cleanupInTask = task.wrapInside(this.cleanup)
const cleanup = this.cleanup
this.cleanup = function () {
return task.status === 'pending'
? cleanupInTask.apply(this, arguments)
: Task.run({ properties: { name: 'retention' }, cleanup: true }, () => cleanup.apply(this, arguments))
}
// `afterBackup()` cleans the VM directory and releases its lock: it must run even when the task has already
// ended because the transfer failed or was aborted, outside of it then
const afterBackupInTask = task.wrap(this.afterBackup)
const afterBackup = this.afterBackup
this.afterBackup = function () {
return task.status === 'pending' ? afterBackupInTask.apply(this, arguments) : afterBackup.apply(this, arguments)
}
return this._prepare()
}
@@ -265,6 +281,8 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
}
let size = 0
await Task.run({ properties: { name: 'transfer' } }, async () => {
// stops the writes once the backup is aborted
const signal = Task.abortSignal
await asyncEach(
Object.entries(deltaExport.disks),
async ([diskRef, disk]) => {
@@ -285,6 +303,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
// no checksum for VHDs, because they will be invalidated by
// merges and chains
checksum: false,
signal,
validator: tmpPath => checkDisk(handler, tmpPath),
writeBlockConcurrency: this._config.writeBlockConcurrency,
uuid: packUuid(vdi.uuid),
@@ -300,6 +319,11 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
return { size }
})
// the metadata makes the backup restorable: it is not written for an aborted backup, whose disks are removed by
// the clean-vm of `afterBackup()`
Task.abortSignal?.throwIfAborted()
metadataContent.tags = await this.getLongTermRetentionTags(metadataContent)
metadataContent.size = size // @todo return exactly the size written by this writer
this._metadataFileName = await adapter.writeVmBackupMetadata(vm.uuid, metadataContent)

View File

@@ -0,0 +1,266 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { Task } from '@vates/task'
import { IncrementalRemoteWriter } from './IncrementalRemoteWriter.mjs'
// a writer on a fake remote, whose transfer fails as an aborted transfer does
function createWriter() {
const calls = { cleanVm: 0, cleanVmOptions: [], deletedEntries: [], lockDisposed: false }
const writer = new IncrementalRemoteWriter({
adapter: {
deleteDeltaVmBackups: async backups => {
calls.deletedEntries.push(...backups.map(_ => _._filename))
},
handler: {
mktree: async () => {},
lock: async () => ({
dispose: async () => {
calls.lockDisposed = true
},
}),
},
cleanVm: async (vmDir, options) => {
++calls.cleanVm
calls.cleanVmOptions.push(options)
return {}
},
},
config: { disableMergeWorker: true },
job: { id: 'job', mode: 'delta' },
remoteId: 'remote',
schedule: { id: 'schedule' },
settings: {},
vmUuid: 'vm',
})
// what `prepare()` wraps in its "export" task
writer._prepare = async () => {
// the backups past the retention
writer._oldEntries = [{ _filename: 'old1.json' }, { _filename: 'old2.json' }]
}
writer.transfer = () =>
new Promise((resolve, reject) => {
const signal = Task.abortSignal
if (signal.aborted) {
reject(signal.reason)
} else {
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
}
})
return { calls, writer }
}
// the steps of a VM backup for this writer, in the order `_AbstractXapi#run()` calls them
async function runSteps(writer, { abort, afterTransfer = () => {} }) {
const events = []
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress: event => events.push(event) })
let afterBackupError
await vmTask
.run(async () => {
await writer.beforeBackup()
try {
await writer.prepare({ isFull: true })
const pTransfer = writer.transfer()
abort(vmTask)
await pTransfer
afterTransfer(vmTask)
await writer.cleanup()
} finally {
// `$defer` of `_AbstractXapi#run()`
await writer.afterBackup().catch(error => {
afterBackupError = error
})
}
})
.catch(() => {})
return { afterBackupError, events }
}
describe('IncrementalRemoteWriter#afterBackup()', () => {
it('cleans the VM directory and releases the lock after a failed transfer', async () => {
const { calls, writer } = createWriter()
const { afterBackupError } = await runSteps(writer, {
// a transfer that fails for another reason than an abort
abort: vmTask => setImmediate(() => vmTask._abortController.abort(new Error('target unreachable'))),
})
assert.equal(afterBackupError, undefined)
assert.equal(calls.cleanVm, 2, 'clean-vm runs before and after the backup')
assert.equal(calls.lockDisposed, true)
})
it('cleans the VM directory and releases the lock after an abort, in a clean-vm subtask', async () => {
const { calls, writer } = createWriter()
const { afterBackupError, events } = await runSteps(writer, {
abort: vmTask => setImmediate(() => vmTask.abort()),
})
assert.equal(afterBackupError, undefined)
assert.equal(calls.cleanVm, 2, 'clean-vm runs before and after the backup')
assert.equal(calls.lockDisposed, true)
const cleanVmIds = events.filter(_ => _.type === 'start' && _.properties?.name === 'clean-vm').map(_ => _.id)
assert.equal(cleanVmIds.length, 2)
const lastCleanVmEnd = events.find(_ => _.type === 'end' && _.id === cleanVmIds[1])
assert.equal(lastCleanVmEnd.status, 'success')
})
it('releases the lock when the clean-vm after the backup fails', async () => {
const { calls, writer } = createWriter()
writer.transfer = async () => {}
const cleanVm = writer._cleanVm
writer._cleanVm = function (options) {
return options.cleanup ? Promise.reject(new Error('clean-vm failed')) : cleanVm.call(this, options)
}
const { afterBackupError } = await runSteps(writer, { abort: () => {} })
assert.equal(afterBackupError?.message, 'clean-vm failed')
assert.equal(calls.lockDisposed, true)
})
})
describe('IncrementalRemoteWriter clean-vm and abort', () => {
it('merges before and after the backup when it is not aborted', async () => {
const { calls, writer } = createWriter()
writer.transfer = async () => {}
await runSteps(writer, { abort: () => {} })
assert.deepEqual(
calls.cleanVmOptions.map(_ => _.merge),
[true, true]
)
})
it('still merges in the cleanup made after an abort, which is not stopped (level 1)', async () => {
const { calls, writer } = createWriter()
await runSteps(writer, { abort: vmTask => setImmediate(() => vmTask.abort()) })
assert.deepEqual(
calls.cleanVmOptions.map(_ => _.merge),
[true, true]
)
})
it('aborts the clean-vm made before the transfer with the backup', async () => {
const { calls, writer } = createWriter()
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
let signal
writer._adapter.cleanVm = async () => {
signal = Task.abortSignal
vmTask.abort()
++calls.cleanVm
return {}
}
await vmTask.run(() => writer.beforeBackup())
assert.equal(signal.aborted, true)
})
})
describe('IncrementalRemoteWriter#cleanup() and abort', () => {
it('applies the retention in the export task when the backup is not aborted', async () => {
const { calls, writer } = createWriter()
writer.transfer = async () => {}
const { events } = await runSteps(writer, { abort: () => {} })
assert.deepEqual(calls.deletedEntries, ['old2.json', 'old1.json'])
assert.equal(
events.some(_ => _.type === 'start' && _.properties?.name === 'retention'),
false,
'no retention subtask'
)
})
it('still applies the retention when the abort arrives after the transfer, in a retention subtask', async () => {
const { calls, writer } = createWriter()
writer.transfer = async () => {}
const { afterBackupError, events } = await runSteps(writer, {
abort: () => {},
afterTransfer: vmTask => vmTask.abort(),
})
assert.equal(afterBackupError, undefined)
assert.deepEqual(calls.deletedEntries, ['old2.json', 'old1.json'])
const retentionStart = events.find(_ => _.type === 'start' && _.properties?.name === 'retention')
assert.notEqual(retentionStart, undefined)
const retentionEnd = events.find(_ => _.type === 'end' && _.id === retentionStart.id)
assert.equal(retentionEnd.status, 'success')
})
it('does not apply the retention when the transfer is aborted', async () => {
const { calls, writer } = createWriter()
await runSteps(writer, { abort: vmTask => setImmediate(() => vmTask.abort()) })
assert.deepEqual(calls.deletedEntries, [])
})
})
describe('IncrementalRemoteWriter#transfer() after an abort', () => {
it('stops writing the disks and writes no metadata', async () => {
const writes = []
let metadataWritten = false
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const writer = new IncrementalRemoteWriter({
adapter: {
getVhdFileName: basename => `${basename}.vhd`,
handler: { readFile: async () => Promise.reject(new Error('no such file')) },
listVmBackups: async () => [],
writeVhd: async (path, disk, { signal }) => {
if (signal?.aborted) {
throw signal.reason
}
writes.push(path)
// the backup is aborted once the first disk has been written
vmTask.abort()
return 1
},
writeVmBackupMetadata: async () => {
metadataWritten = true
},
},
config: {},
job: { id: 'job', mode: 'delta' },
remoteId: 'remote',
schedule: { id: 'schedule' },
settings: { diskPerVmConcurrency: 1 },
vmUuid: 'vm',
})
const disk = { close: async () => {} }
const deltaExport = {
disks: { vdi1: disk, vdi2: disk },
vbds: {},
vdis: { vdi1: { uuid: 'uuid1', $snapshot_of$uuid: 'src1' }, vdi2: { uuid: 'uuid2', $snapshot_of$uuid: 'src2' } },
vifs: {},
vm: { uuid: 'vm' },
vtpms: {},
}
await vmTask
.run(() =>
writer.transfer({
deltaExport,
isVhdDifferencing: { vdi1: false, vdi2: false },
timestamp: 0,
vm: { uuid: 'vm' },
vmSnapshot: {},
})
)
.catch(() => {})
assert.equal(writes.length, 1, 'the second disk is not written')
assert.equal(metadataWritten, false, 'no metadata is written for an aborted backup')
})
})

View File

@@ -327,11 +327,20 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
})
this._prepare = task.wrapInside(this._prepare)
this.transfer = task.wrapInside(this.transfer)
// `cleanup()` applies the retention once the backup has been written: an abort that arrives after the transfer
// has already ended the task, the retention then runs in a cleanup subtask, which the abort does not stop
let cleanupInTask
if (this._healthCheckSr !== undefined) {
this.cleanup = task.wrapInside(this.cleanup)
cleanupInTask = task.wrapInside(this.cleanup)
this.healthCheck = task.wrap(this.healthCheck)
} else {
this.cleanup = task.wrap(this.cleanup)
cleanupInTask = task.wrap(this.cleanup)
}
const cleanup = this.cleanup
this.cleanup = function () {
return task.status === 'pending'
? cleanupInTask.apply(this, arguments)
: Task.run({ properties: { name: 'retention' }, cleanup: true }, () => cleanup.apply(this, arguments))
}
return this._prepare(isFull)
@@ -504,6 +513,8 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
let targetVmRef
await Task.run({ properties: { name: 'transfer' } }, async () => {
targetVmRef = await importIncrementalVm(this.#decorateVmMetadata(deltaExport, timestamp), sr, {
// the import is stopped once the backup is aborted, and the VM and VDIs it created are destroyed
signal: Task.abortSignal,
targetRef: this._targetVmRef,
})
// this also ensure the data are up to date on the snapshot

View File

@@ -0,0 +1,83 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { Task } from '@vates/task'
import { IncrementalXapiWriter } from './IncrementalXapiWriter.mjs'
// a writer whose retention is recorded instead of destroying the old replicas
function createWriter({ healthCheckSr } = {}) {
const calls = { deleteOldEntries: 0, deleteOrphanVdis: 0 }
const writer = new IncrementalXapiWriter({
config: {},
healthCheckSr,
job: { id: 'job' },
schedule: { id: 'schedule' },
settings: {},
sr: { name_label: 'sr', uuid: 'sr' },
vmUuid: 'vm',
})
// what `prepare()` wraps in its "export" task
writer._prepare = async () => {}
writer.transfer = async () => {}
writer._deleteOldEntries = async () => {
++calls.deleteOldEntries
}
writer._deleteOrphanVdis = async () => {
++calls.deleteOrphanVdis
}
return { calls, writer }
}
// the steps of a VM backup for this writer, in the order `IncrementalXapi#_copy()` calls them
async function runSteps(writer, { afterTransfer = () => {} } = {}) {
const events = []
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress: event => events.push(event) })
let cleanupError
await vmTask
.run(async () => {
await writer.prepare({ isFull: true })
await writer.transfer()
afterTransfer(vmTask)
await writer.cleanup().catch(error => {
cleanupError = error
})
})
.catch(() => {})
return { cleanupError, events }
}
const retentionTaskOf = events => events.find(_ => _.type === 'start' && _.properties?.name === 'retention')
for (const [label, healthCheckSr] of [
['without health check', undefined],
['with health check', { uuid: 'health-check-sr' }],
]) {
describe(`IncrementalXapiWriter#cleanup() and abort, ${label}`, () => {
it('applies the retention in the export task when the backup is not aborted', async () => {
const { calls, writer } = createWriter({ healthCheckSr })
const { cleanupError, events } = await runSteps(writer)
assert.equal(cleanupError, undefined)
assert.deepEqual(calls, { deleteOldEntries: 1, deleteOrphanVdis: 1 })
assert.equal(retentionTaskOf(events), undefined, 'no retention subtask')
})
it('still applies the retention when the abort arrives after the transfer, in a retention subtask', async () => {
const { calls, writer } = createWriter({ healthCheckSr })
const { cleanupError, events } = await runSteps(writer, { afterTransfer: vmTask => vmTask.abort() })
assert.equal(cleanupError, undefined)
assert.deepEqual(calls, { deleteOldEntries: 1, deleteOrphanVdis: 1 })
const retentionStart = retentionTaskOf(events)
assert.notEqual(retentionStart, undefined)
const retentionEnd = events.find(_ => _.type === 'end' && _.id === retentionStart.id)
assert.equal(retentionEnd.status, 'success')
})
})
}

View File

@@ -26,9 +26,12 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
this._vmBackupDir = getVmBackupDir(rest.vmUuid)
}
async _cleanVm(options) {
// `cleanup`: the clean-vm is a cleanup subtask, it also runs after the backup has been aborted. Otherwise it is
// not started once the backup is aborted, but a merge already running is not interrupted: `cleanVm()` does not
// read the signal
async _cleanVm({ cleanup = false, ...options }) {
try {
return await Task.run({ properties: { name: 'clean-vm' } }, () => {
return await Task.run({ properties: { name: 'clean-vm' }, cleanup }, () => {
return this._adapter.cleanVm(this._vmBackupDir, {
...options,
logInfo: info,
@@ -72,8 +75,13 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
const { handler } = this._adapter
const synchronousMerge = this._settings.mergeBackupsSynchronously
const willMergeInWorker = !synchronousMerge && !disableMergeWorker && typeof handler.getRealPath === 'function'
const { merge } = await this._cleanVm({ remove: true, merge: !willMergeInWorker })
await this.#lock.dispose()
let merge
try {
// part of the cleanup: it also runs after an abort, merge included (skipping it is a level 2 abort)
;({ merge } = await this._cleanVm({ cleanup: true, remove: true, merge: !willMergeInWorker }))
} finally {
await this.#lock.dispose()
}
if (merge && willMergeInWorker) {
const taskFile =

View File

@@ -48,13 +48,20 @@ export const MixinXapiWriter = (BaseClass = Object) =>
if (await this.#isAlreadyOnHealthCheckSr(baseVm)) {
healthCheckVmRef = await Task.run(
{ properties: { name: 'cloning-vm' } },
async () => await xapi.callAsync('VM.clone', this._targetVmRef, `Health Check - ${baseVm.name_label}`)
async () =>
await xapi.callAsync(
Task.abortSignal,
'VM.clone',
this._targetVmRef,
`Health Check - ${baseVm.name_label}`
)
)
} else {
healthCheckVmRef = await Task.run(
{ properties: { name: 'copying-vm' } },
async () =>
await xapi.callAsync(
Task.abortSignal,
'VM.copy',
this._targetVmRef,
`Health Check - ${baseVm.name_label}`,

View File

@@ -0,0 +1,43 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { Task } from '@vates/task'
import { FullXapiWriter } from './FullXapiWriter.mjs'
describe('MixinXapiWriter#healthCheck() after an abort', () => {
it('passes the abort signal to the copy of the replica', async () => {
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const calls = []
const xapi = {
getObject: ref => ({ $ref: ref, $xapi: xapi, name_label: 'replica' }),
VM_getDisks: async () => [],
callAsync: async (...args) => {
calls.push(args)
// the backup is aborted while the replica is being copied
vmTask.abort()
throw new Error('stop after the copy call')
},
}
const writer = new FullXapiWriter({
config: {},
healthCheckSr: { $ref: 'OpaqueRef:health-check-sr', uuid: 'health-check-sr' },
job: { id: 'job' },
schedule: { id: 'schedule' },
settings: { healthCheckTimeout: '10m' },
sr: { $xapi: xapi, name_label: 'sr', uuid: 'sr' },
vmUuid: 'vm',
})
writer._targetVmRef = 'OpaqueRef:replica'
// the replica is not on the health check SR: it is copied there
xapi.VM_getDisks = async () => ['OpaqueRef:vdi']
xapi.getObject = ref =>
ref === 'OpaqueRef:vdi' ? { $SR: { uuid: 'sr' } } : { $ref: ref, $xapi: xapi, name_label: 'replica' }
await vmTask.run(() => assert.rejects(writer.healthCheck(), /stop after the copy call/)).catch(() => {})
const [[signal, method]] = calls
assert.ok(signal instanceof AbortSignal, 'the copy gets a signal')
assert.equal(signal.aborted, true, 'the copy gets the abort signal of the backup')
assert.equal(method, 'VM.copy')
})
})

View File

@@ -13,6 +13,7 @@
- [Of created VMs](#of-created-vms-and-their-associated-vdis)
- [Task logs](#task-logs)
- [During backup](#during-backup)
- [Aborted backup](#aborted-backup)
- [During restoration](#during-restoration)
- [API](#api)
- [Run description object](#run-description-object)
@@ -240,6 +241,41 @@ job.start(data: { mode: Mode, reportWhen: ReportWhen })
└─ job.end
```
### Aborted backup
When the backup runs in the xo-server process (`backups.disableWorkers`), it can be aborted from its task. The abort is
always an `AbortError`, and it changes the task log above as follows:
```
job.start(data: { mode: Mode, reportWhen: ReportWhen })
├─ task.info(message: 'abort requested', data: { type: 'abortRequested', userId: string }) // when requested by a user
├─ task.abortionRequested(reason: AbortError)
├─ task.start(data: { type: 'VM', id: string, name_label?: string }) // VM being backed up
│ ├─ task.abortionRequested(reason: AbortError)
│ ├─ task.start(message: 'export', data: { … })
│ │ ├─ task.start(message: 'transfer')
│ │ │ └─ task.end(status: 'failure', result: AbortError) // the transfer stops
│ │ └─ task.end(status: 'failure', result: AbortError)
│ ├─ task.start(message: 'clean-vm') // cleanup subtask, still run
│ │ └─ task.end
│ └─ task.end(status: 'failure', result: AbortError)
│ // no task for the VMs not started yet, no retry, no health check
└─ job.end(status: 'failure', result: AbortError)
```
- A step started as a subtask once the run is aborted fails right away, without running (the root task of the run
is created with `skipSubtasksAfterAbort: true` in `@vates/task`).
- The cleanup still runs: snapshot retention, removal of the snapshot data, restore of the VM's blocked operations,
and the writers' `afterBackup()`. `clean-vm` (and the merge it runs) is a cleanup subtask (`cleanup: true` in
`@vates/task`), which the abort does not stop.
- The metadata of an incremental backup is not written, so the aborted backup is never listed as restorable; its disks
are removed by `clean-vm`.
- The retention of the backups (or replicas) only applies once the new one has been written. When the abort arrives
after the transfer, the `export` task has already ended: the retention runs in a `retention` cleanup subtask of the VM
task, before `clean-vm`.
- In the backup logs and reports, a task that failed after an abort was requested on it (`abortionRequested`) has the
status `interrupted`, and does not make its parent `failure`.
### During restoration
```

View File

@@ -8,7 +8,7 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "1.0.0",
"version": "1.0.1",
"engines": {
"node": ">=22.19"
},
@@ -27,10 +27,10 @@
"@vates/disposable": "^0.1.7",
"@vates/fuse-vhd": "^2.1.4",
"@vates/generator-toolbox": "^1.1.3",
"@vates/nbd-client": "^3.7.1",
"@vates/nbd-client": "^3.7.2",
"@vates/parse-duration": "^0.1.1",
"@vates/task": "^0.7.0",
"@vates/types": "^3.0.0",
"@vates/types": "^3.2.0",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/fs": "^4.11.0",
@@ -70,7 +70,7 @@
"typescript": "^5.9.3"
},
"peerDependencies": {
"@xen-orchestra/xapi": "^10.0.0"
"@xen-orchestra/xapi": "^10.1.0"
},
"license": "AGPL-3.0-or-later",
"author": {

View File

@@ -20,7 +20,7 @@
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^1.0.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.11.0",

View File

@@ -22,7 +22,7 @@
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/log": "^1.0.0",
"app-conf": "^3.0.0",
"execa": "^5.0.0",

View File

@@ -2,6 +2,11 @@
## **next**
- [VM/Network] Add possibility to delete a VIF (PR [#10726](https://github.com/vatesfr/xen-orchestra/pull/10726))
- [Host/VM/Pool] Add a Stats tab showing the CPU, RAM, network and load (or disk for VMs) charts over the last 10 minutes, 2 hours, week or year, with one line per CPU, interface, disk or host and an option to show the totals (PR [#10956](https://github.com/vatesfr/xen-orchestra/pull/10956))
## **0.28.0** (2026/12/01)
- [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))

View File

@@ -1,6 +1,6 @@
{
"name": "@xen-orchestra/lite",
"version": "0.27.0",
"version": "0.28.0",
"type": "module",
"scripts": {
"dev": "GIT_HEAD=$(git rev-parse HEAD) vite",
@@ -27,13 +27,13 @@
"@types/file-saver": "^2.0.7",
"@types/lodash-es": "^4.17.12",
"@types/node": "^18.19.80",
"@vates/types": "^3.0.0",
"@vates/types": "^3.2.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.66.0",
"@xen-orchestra/web-core": "^0.67.0",
"complex-matcher": "^1.1.1",
"d3-time-format": "^4.1.0",
"decorator-synchronized": "^0.6.0",

View File

@@ -0,0 +1,25 @@
<template>
<VtsStatsCharts :charts :granularity :loading="hostStats === undefined" :error="hasError || !!lastError" />
</template>
<script lang="ts" setup>
import { useObjectStats } from '@/composables/object-stats.composable.ts'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
import { useHostStatsCharts } from '@core/composables/stats-charts/host-stats-charts.composable.ts'
import type { XapiStatsGranularity } from '@vates/types/common'
// The parent re-mounts this component (`key`) when the host or the granularity changes
const { host, granularity, showTotals } = defineProps<{
host: XenApiHost
granularity: XapiStatsGranularity
showTotals: boolean
}>()
const { getStats, lastError } = useHostStore().subscribe()
const { stats: hostStats, hasError } = useObjectStats<XenApiHost>(getStats, host, granularity)
const charts = useHostStatsCharts(hostStats, () => showTotals)
</script>

View File

@@ -6,6 +6,9 @@
<RouterTab :to="{ name: '/host/[uuid]/console', params: { uuid } }">
{{ t('console') }}
</RouterTab>
<RouterTab :to="{ name: '/host/[uuid]/stats', params: { uuid } }">
{{ t('stats') }}
</RouterTab>
<RouterTab :to="{ name: '/host/[uuid]/system', params: { uuid } }">
{{ t('system') }}
</RouterTab>

View File

@@ -0,0 +1,50 @@
<template>
<VtsStatsCharts :charts :granularity :loading :error="hasError || !!lastError" />
</template>
<script lang="ts" setup>
import useFetchStats from '@/composables/fetch-stats.composable.ts'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
import { type PoolHostStats, usePoolStatsCharts } from '@core/composables/stats-charts/pool-stats-charts.composable.ts'
import type { XapiStatsGranularity } from '@vates/types/common'
import { differenceBy } from 'lodash-es'
import { computed, watch } from 'vue'
// The parent re-mounts this component (`key`) when the granularity changes
const { granularity, showTotals } = defineProps<{
granularity: XapiStatsGranularity
showTotals: boolean
}>()
const { getStats, runningHosts, lastError } = useHostStore().subscribe()
// The running hosts are only known once their metrics are loaded
const { isReady: areHostMetricsReady } = useHostMetricsStore().subscribe()
const { stats, register, unregister } = useFetchStats<XenApiHost>(getStats, granularity)
watch(
runningHosts,
(hosts, previousHosts = []) => {
differenceBy(hosts, previousHosts, 'uuid').forEach(host => register(host))
differenceBy(previousHosts, hosts, 'uuid').forEach(host => unregister(host))
},
{ immediate: true }
)
// A host whose stats can't be fetched doesn't hold the others back
const loading = computed(
() => !areHostMetricsReady.value || stats.value.some(stat => stat.stats === undefined && !stat.hasError)
)
const hasError = computed(() => stats.value.length > 0 && stats.value.every(stat => stat.hasError))
const hostsStats = computed<PoolHostStats[]>(() =>
stats.value.flatMap(({ name, response }) => (response === undefined ? [] : [{ name, stats: response }]))
)
const charts = usePoolStatsCharts(hostsStats, () => showTotals)
</script>

View File

@@ -6,7 +6,7 @@
<RouterTab :to="{ name: '/pool/[uuid]/alarms', params: { uuid: pool?.uuid ?? '-' } }" disabled>
{{ t('alarms') }}
</RouterTab>
<RouterTab :to="{ name: '/pool/[uuid]/stats', params: { uuid: pool?.uuid ?? '-' } }" disabled>
<RouterTab :to="{ name: '/pool/[uuid]/stats', params: { uuid: pool?.uuid ?? '-' } }">
{{ t('stats') }}
</RouterTab>
<RouterTab :to="{ name: '/pool/[uuid]/system', params: { uuid: pool?.uuid ?? '-' } }">

View File

@@ -0,0 +1,25 @@
<template>
<VtsStatsCharts :charts :granularity :loading="vmStats === undefined" :error="hasError || !!lastError" />
</template>
<script lang="ts" setup>
import { useObjectStats } from '@/composables/object-stats.composable.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
import { useVmStatsCharts } from '@core/composables/stats-charts/vm-stats-charts.composable.ts'
import type { XapiStatsGranularity } from '@vates/types/common'
// The parent re-mounts this component (`key`) when the VM or the granularity changes
const { vm, granularity, showTotals } = defineProps<{
vm: XenApiVm
granularity: XapiStatsGranularity
showTotals: boolean
}>()
const { getStats, lastError } = useVmStore().subscribe()
const { stats: vmStats, hasError } = useObjectStats<XenApiVm>(getStats, vm, granularity)
const charts = useVmStatsCharts(vmStats, () => showTotals)
</script>

View File

@@ -9,7 +9,7 @@
<RouterTab :to="{ name: '/vm/[uuid]/alarms', params: { uuid } }" disabled>
{{ t('alarms') }}
</RouterTab>
<RouterTab :to="{ name: '/vm/[uuid]/stats', params: { uuid } }" disabled>
<RouterTab :to="{ name: '/vm/[uuid]/stats', params: { uuid } }">
{{ t('stats') }}
</RouterTab>
<RouterTab :to="{ name: '/vm/[uuid]/system', params: { uuid } }">

View File

@@ -1,13 +1,17 @@
import { type GRANULARITY, RRD_STEP_FROM_STRING, type XapiStatsResponse } from '@/libs/xapi-stats.ts'
import { RRD_STEP_FROM_STRING, type XapiStatsResponse } from '@/libs/xapi-stats.ts'
import type { XenApiHost, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import type { XapiHostStatsRaw, XapiVmStatsRaw } from '@vates/types/common'
import type { XapiHostStatsRaw, XapiStatsGranularity, XapiVmStatsRaw } from '@vates/types/common'
import { type Pausable, promiseTimeout, useTimeoutPoll } from '@vueuse/core'
import { computed, type ComputedRef, onUnmounted, ref, type Ref } from 'vue'
import { computed, type ComputedRef, markRaw, onUnmounted, ref, type Ref } from 'vue'
export type Stat<T> = {
canBeExpired: boolean
// The last fetch failed: `stats` holds the previous ones, if any
hasError: boolean
id: string
name: string
// Shaped like the XO REST API stats, which the web-core stats charts expect
response: XapiStatsResponse<T> | undefined
stats: T | undefined
pausable: Pausable
}
@@ -17,7 +21,7 @@ export type GetStats<
S extends XapiHostStatsRaw | XapiVmStatsRaw = T extends XenApiHost ? XapiHostStatsRaw : XapiVmStatsRaw,
> = (
uuid: T['uuid'],
granularity: GRANULARITY,
granularity: XapiStatsGranularity,
ignoreExpired: boolean,
opts: { abortSignal?: AbortSignal }
) => Promise<XapiStatsResponse<S> | undefined> | undefined
@@ -33,10 +37,13 @@ export type FetchedStats<
timestampEnd: ComputedRef<number>
}
// In seconds
const RETRY_DELAY = 10
export default function useFetchStats<
T extends XenApiHost | XenApiVm,
S extends XapiHostStatsRaw | XapiVmStatsRaw = T extends XenApiHost ? XapiHostStatsRaw : XapiVmStatsRaw,
>(getStats: GetStats<T, S>, granularity: GRANULARITY): FetchedStats<T, S> {
>(getStats: GetStats<T, S>, granularity: XapiStatsGranularity): FetchedStats<T, S> {
const stats = ref(new Map()) as Ref<Map<string, Stat<S>>>
const timestamp = ref<number[]>([0, 0])
const abortController = new AbortController()
@@ -48,15 +55,36 @@ export default function useFetchStats<
return
}
const ignoreExpired = computed(() => !stats.value.has(mapKey))
let isFirstCall = true
const pausable = useTimeoutPoll(
async () => {
const newStats = (await getStats(object.uuid, granularity, ignoreExpired.value, {
abortSignal: abortController.signal,
})) as XapiStatsResponse<S>
let newStats: XapiStatsResponse<S> | undefined
let hasError = false
// The first call accepts expired cached stats (e.g. when coming back to a page) to show something right away
const ignoreExpired = isFirstCall
isFirstCall = false
try {
newStats = await getStats(object.uuid, granularity, ignoreExpired, {
abortSignal: abortController.signal,
})
} catch {
hasError = true
}
// The object may have been unregistered while its stats were being fetched
const stat = stats.value.get(mapKey)
if (stat === undefined) {
return
}
stat.hasError = hasError
// Without new stats (failure, disconnected XAPI…), retries soon, but not in a tight loop
if (newStats === undefined) {
await promiseTimeout(Math.min(RRD_STEP_FROM_STRING[granularity], RETRY_DELAY) * 1000)
return
}
@@ -66,9 +94,16 @@ export default function useFetchStats<
newStats.endTimestamp,
]
stats.value.get(mapKey)!.stats = newStats.stats
stats.value.get(mapKey)!.canBeExpired = newStats.canBeExpired
await promiseTimeout(newStats.interval * 1000)
// Raw: replacing the stats is enough to update the charts, which then read their samples without proxies.
// Unchanged stats (e.g. the cache read again right after the first call) don't redraw the charts
if (stat.response?.endTimestamp !== newStats.endTimestamp) {
stat.stats = markRaw(newStats.stats)
stat.response = markRaw(newStats)
}
stat.canBeExpired = newStats.canBeExpired
// Cached stats (`canBeExpired`), possibly old (e.g. when coming back to a page), are checked again right away:
// the next call skips the cache if it's expired, instead of a full interval later, which can be a day
await promiseTimeout(newStats.canBeExpired ? 0 : newStats.interval * 1000)
},
0,
{ immediate: true }
@@ -76,8 +111,10 @@ export default function useFetchStats<
stats.value.set(mapKey, {
canBeExpired: false,
hasError: false,
id: object.uuid,
name: object.name_label,
response: undefined,
stats: undefined,
pausable,
})

View File

@@ -0,0 +1,20 @@
import useFetchStats, { type GetStats } from '@/composables/fetch-stats.composable.ts'
import type { XenApiHost, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import type { XapiHostStatsRaw, XapiStatsGranularity, XapiVmStatsRaw } from '@vates/types/common'
import { computed } from 'vue'
// Polls the stats of a single host or VM. The object and the granularity are fixed: the caller must be re-mounted to
// change them
export function useObjectStats<
T extends XenApiHost | XenApiVm,
S extends XapiHostStatsRaw | XapiVmStatsRaw = T extends XenApiHost ? XapiHostStatsRaw : XapiVmStatsRaw,
>(getStats: GetStats<T, S>, object: T, granularity: XapiStatsGranularity) {
const { stats, register } = useFetchStats<T, S>(getStats, granularity)
register(object)
return {
stats: computed(() => stats.value[0]?.response),
hasError: computed(() => stats.value[0]?.hasError === true),
}
}

View File

@@ -1,6 +1,7 @@
import type XenApi from '@/libs/xen-api/xen-api.ts'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import type { XapiHostStatsRaw, XapiVmStatsRaw } from '@vates/types'
import type { XapiStatsGranularity } from '@vates/types/common'
import { synchronized } from 'decorator-synchronized'
// eslint-disable-next-line import/default -- https://github.com/json5/json5/issues/287
import JSON5 from 'json5'
@@ -32,7 +33,7 @@ export enum GRANULARITY {
Days = 'days',
}
export const RRD_STEP_FROM_STRING: { [key in GRANULARITY]: RRD_STEP } = {
export const RRD_STEP_FROM_STRING: Record<XapiStatsGranularity, RRD_STEP> = {
[GRANULARITY.Seconds]: RRD_STEP.Seconds,
[GRANULARITY.Minutes]: RRD_STEP.Minutes,
[GRANULARITY.Hours]: RRD_STEP.Hours,
@@ -416,7 +417,7 @@ export default class XapiStats {
host: XenApiHost
ignoreExpired?: boolean
uuid: any
granularity: GRANULARITY
granularity: XapiStatsGranularity
}) {
const step = granularity === undefined ? RRD_STEP.Seconds : RRD_STEP_FROM_STRING[granularity]
if (step === undefined) {

View File

@@ -25,6 +25,7 @@
<script lang="ts" setup>
import type { XenApiNetwork, XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVifConnection } from '@/modules/vif/composables/use-vif-connection.composable.ts'
import { useVifDelete } from '@/modules/vif/composables/use-vif-delete.composable.ts'
import { useVifEdit } from '@/modules/vif/composables/use-vif-edit.composable.ts'
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { useVifStore } from '@/stores/xen-api/vif.store.ts'
@@ -106,6 +107,8 @@ const { HeadCells, BodyCells } = useVifColumns({
vm: () => vm,
})
const { deleteVifs, canDeleteVifs, isDeletingVifs, deleteVifsErrorMessage } = useVifDelete(() => [vif])
const connectionAction = useMapper(
() => (vif.currently_attached ? CONNECTION_ACTION.DISCONNECT : CONNECTION_ACTION.CONNECT),
() => ({
@@ -143,6 +146,15 @@ const { HeadCells, BodyCells } = useVifColumns({
actions: [
{ label: t('action:edit'), icon: 'action:edit', onClick: () => goToVifEdit(vif) } satisfies ActionItem,
connectionAction.value,
{
label: t('action:delete'),
icon: 'action:delete',
onClick: () => deleteVifs(),
disabled: !canDeleteVifs.value,
busy: isDeletingVifs.value,
hint: canDeleteVifs.value ? undefined : deleteVifsErrorMessage.value,
accent: 'danger',
} satisfies ActionItem,
],
}),
}

View File

@@ -0,0 +1,20 @@
<template>
<VtsDeleteButton
:hint="deleteVifsErrorMessage"
:disabled="!canDeleteVifs"
:busy="isDeletingVifs"
@click="deleteVifs()"
/>
</template>
<script lang="ts" setup>
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { useVifDelete } from '@/modules/vif/composables/use-vif-delete.composable.ts'
import VtsDeleteButton from '@core/components/delete-button/VtsDeleteButton.vue'
const { vif } = defineProps<{
vif: XenApiVif
}>()
const { deleteVifs, canDeleteVifs, isDeletingVifs, deleteVifsErrorMessage } = useVifDelete(() => [vif])
</script>

View File

@@ -3,6 +3,7 @@
<template v-if="vif" #actions>
<VifEditButton :vif />
<VifConnectionToggleButton v-if="vm" :vif :vm />
<VifDeleteButton :vif />
</template>
<template v-if="vif" #default>
<!-- VIF -->
@@ -110,6 +111,7 @@
<script setup lang="ts">
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import VifConnectionToggleButton from '@/modules/vif/components/actions/connection/VifConnectionToggleButton.vue'
import VifDeleteButton from '@/modules/vif/components/actions/delete/VifDeleteButton.vue'
import VifEditButton from '@/modules/vif/components/actions/edit/VifEditButton.vue'
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'

View File

@@ -0,0 +1,51 @@
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { useVifDeleteJob } from '@/modules/vif/jobs/vif-delete.job.ts'
import { useDeleteModal } from '@core/composables/modals/use-delete-modal.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { toComputed } from '@core/utils/to-computed.util.ts'
import type { MaybeRefOrGetter } from 'vue'
import { useI18n } from 'vue-i18n'
export function useVifDelete(rawVifs: MaybeRefOrGetter<XenApiVif[]>) {
const vifs = toComputed(rawVifs)
const { t } = useI18n()
const selectedVifId = useRouteQuery('id')
const {
run,
canRun: canDeleteVifs,
isRunning: isDeletingVifs,
errorMessage: deleteVifsErrorMessage,
} = useVifDeleteJob(vifs)
const { open } = useDeleteModal()
function deleteVifs() {
const count = vifs.value.length
return open({
props: {
subject: t('n-vifs', { n: count }),
confirmLabel: t('action:delete-n-vifs', { n: count }),
},
events: {
onConfirm: () => {
const isSelectedVifDeleted = vifs.value.some(vif => vif.uuid === selectedVifId.value)
run({
detached: true,
onSuccess: () => {
if (isSelectedVifDeleted) {
selectedVifId.value = ''
}
},
})
},
},
})
}
return { deleteVifs, canDeleteVifs, isDeletingVifs, deleteVifsErrorMessage }
}

View File

@@ -0,0 +1,37 @@
import { vifsArg } from '@/modules/vif/jobs/vif-args.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
export const useVifDeleteJob = defineJob('vif.delete', [vifsArg], () => {
const xapi = useXenApiStore().getXapi()
const { t } = useI18n()
return {
async run(vifs) {
const results = await Promise.allSettled(vifs.map(vif => xapi.vif.delete(vif.$ref)))
results.forEach((result, index) => {
if (result.status === 'rejected') {
console.error(`Failed to delete VIF ${vifs[index].uuid}:`, result.reason)
}
})
return results
},
validate: (isRunning, vifs) => {
if (vifs.length === 0) {
throw new JobError(t('job:vif-delete:missing-vif'))
}
if (isRunning) {
throw new JobRunningError(t('job:delete:in-progress'))
}
if (vifs.some(vif => vif.currently_attached)) {
throw new JobError(t('vif-connected'))
}
},
}
})

View File

@@ -0,0 +1,78 @@
<template>
<div class="stats">
<VtsStateHero v-if="host === undefined" format="page" type="not-found" size="large">
{{ t('object-not-found', { id: route.params.uuid }) }}
</VtsStateHero>
<!-- The power state is unknown until the host metrics are loaded -->
<VtsStateHero v-else-if="!areHostMetricsReady" format="page" type="busy" size="large" />
<VtsStateHero v-else-if="!isHostRunning" format="page" type="offline" size="large" horizontal>
<span>{{ t('engines-off') }}</span>
<span class="title typo-h1">{{ t('host-off') }}</span>
<div class="description typo-body-bold">
<span>{{ t('host-currently-shutdown') }}</span>
<span>{{ t('start-host') }}</span>
</div>
</VtsStateHero>
<template v-else>
<VtsStatsToolbar v-model:granularity="granularity" v-model:show-totals="showTotals" />
<HostStatsCharts :key="`${host.uuid}-${granularity}`" :host :granularity :show-totals />
</template>
</div>
</template>
<script lang="ts" setup>
import HostStatsCharts from '@/components/host/HostStatsCharts.vue'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { usePageTitleStore } from '@/stores/page-title.store.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import VtsStatsToolbar from '@core/components/stats-toolbar/VtsStatsToolbar.vue'
import { HOST_POWER_STATE } from '@vates/types'
import type { XapiStatsGranularity } from '@vates/types/common'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
const { t } = useI18n()
usePageTitleStore().setTitle(t('stats'))
const route = useRoute<'/host/[uuid]/stats'>()
const { getByUuid } = useHostStore().subscribe()
const host = computed(() => getByUuid(route.params.uuid as XenApiHost['uuid']))
const { getHostPowerState, isReady: areHostMetricsReady } = useHostMetricsStore().subscribe()
// As in XO 6, a host whose state is unknown (e.g. disconnected) is shown as off: it has no stats to show
const isHostRunning = computed(() => getHostPowerState(host.value) === HOST_POWER_STATE.RUNNING)
const granularity = ref<XapiStatsGranularity>('seconds')
const showTotals = ref(false)
</script>
<style lang="postcss" scoped>
.stats {
display: flex;
flex: 1;
flex-direction: column;
gap: 0.8rem;
min-height: 0;
padding: 0.8rem;
overflow-y: auto;
.title {
color: var(--color-neutral-txt-primary);
}
.description {
display: flex;
flex-direction: column;
gap: 1.4rem;
color: var(--color-neutral-txt-secondary);
}
}
</style>

View File

@@ -1,11 +1,33 @@
<template>
<PageUnderConstruction />
<div class="stats">
<VtsStatsToolbar v-model:granularity="granularity" v-model:show-totals="showTotals" />
<PoolStatsCharts :key="granularity" :granularity :show-totals />
</div>
</template>
<script lang="ts" setup>
import PageUnderConstruction from '@/components/PageUnderConstruction.vue'
import PoolStatsCharts from '@/components/pool/PoolStatsCharts.vue'
import { usePageTitleStore } from '@/stores/page-title.store.ts'
import VtsStatsToolbar from '@core/components/stats-toolbar/VtsStatsToolbar.vue'
import type { XapiStatsGranularity } from '@vates/types/common'
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
usePageTitleStore().setTitle(useI18n().t('stats'))
const granularity = ref<XapiStatsGranularity>('seconds')
const showTotals = ref(false)
</script>
<style lang="postcss" scoped>
.stats {
display: flex;
flex: 1;
flex-direction: column;
gap: 0.8rem;
min-height: 0;
padding: 0.8rem;
overflow-y: auto;
}
</style>

View File

@@ -1,11 +1,73 @@
<template>
<PageUnderConstruction />
<div class="stats">
<VtsStateHero v-if="vm === undefined" format="page" type="not-found" size="large">
{{ t('object-not-found', { id: route.params.uuid }) }}
</VtsStateHero>
<VtsStateHero v-else-if="!isVmActive" format="page" type="offline" size="large" horizontal>
<span>{{ t('all-quiet-launchpad') }}</span>
<span class="title typo-h1">{{ t('vm-shutdown') }}</span>
<div class="description typo-body-bold">
<span>{{ t('vm-off') }}</span>
<span>{{ t('start-vm') }}</span>
</div>
</VtsStateHero>
<template v-else>
<VtsStatsToolbar v-model:granularity="granularity" v-model:show-totals="showTotals" />
<VmStatsCharts :key="`${vm.uuid}-${granularity}`" :vm :granularity :show-totals />
</template>
</div>
</template>
<script lang="ts" setup>
import PageUnderConstruction from '@/components/PageUnderConstruction.vue'
import VmStatsCharts from '@/components/vm/VmStatsCharts.vue'
import { ACTIVE_STATES } from '@/libs/utils.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { usePageTitleStore } from '@/stores/page-title.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import VtsStatsToolbar from '@core/components/stats-toolbar/VtsStatsToolbar.vue'
import type { XapiStatsGranularity } from '@vates/types/common'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
usePageTitleStore().setTitle(useI18n().t('stats'))
const { t } = useI18n()
usePageTitleStore().setTitle(t('stats'))
const route = useRoute<'/vm/[uuid]/stats'>()
const { getByUuid } = useVmStore().subscribe()
const vm = computed(() => getByUuid(route.params.uuid as XenApiVm['uuid']))
// A paused VM is still on its host, which keeps recording its stats
const isVmActive = computed(() => vm.value !== undefined && ACTIVE_STATES.has(vm.value.power_state))
const granularity = ref<XapiStatsGranularity>('seconds')
const showTotals = ref(false)
</script>
<style lang="postcss" scoped>
.stats {
display: flex;
flex: 1;
flex-direction: column;
gap: 0.8rem;
min-height: 0;
padding: 0.8rem;
overflow-y: auto;
.title {
color: var(--color-neutral-txt-primary);
}
.description {
display: flex;
flex-direction: column;
gap: 1.4rem;
color: var(--color-neutral-txt-secondary);
}
}
</style>

View File

@@ -52,6 +52,7 @@ declare module 'vue-router/auto-routes' {
| '/host/[uuid]/console'
| '/host/[uuid]/dashboard'
| '/host/[uuid]/network'
| '/host/[uuid]/stats'
| '/host/[uuid]/storage'
| '/host/[uuid]/system'
| '/host/[uuid]/tasks'
@@ -78,6 +79,13 @@ declare module 'vue-router/auto-routes' {
{ uuid: ParamValue<false> },
| never
>,
'/host/[uuid]/stats': RouteRecordInfo<
'/host/[uuid]/stats',
'/host/:uuid/stats',
{ uuid: ParamValue<true> },
{ uuid: ParamValue<false> },
| never
>,
'/host/[uuid]/storage': RouteRecordInfo<
'/host/[uuid]/storage',
'/host/:uuid/storage',
@@ -590,6 +598,20 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/stats-charts/vts-stats-charts': RouteRecordInfo<
'/story/web-core/stats-charts/vts-stats-charts',
'/story/web-core/stats-charts/vts-stats-charts',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/stats-toolbar/vts-stats-toolbar': RouteRecordInfo<
'/story/web-core/stats-toolbar/vts-stats-toolbar',
'/story/web-core/stats-toolbar/vts-stats-toolbar',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/status/vts-status': RouteRecordInfo<
'/story/web-core/status/vts-status',
'/story/web-core/status/vts-status',
@@ -1349,6 +1371,7 @@ declare module 'vue-router/auto-routes' {
| '/host/[uuid]/console'
| '/host/[uuid]/dashboard'
| '/host/[uuid]/network'
| '/host/[uuid]/stats'
| '/host/[uuid]/storage'
| '/host/[uuid]/system'
| '/host/[uuid]/tasks'
@@ -1374,6 +1397,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/pages/host/[uuid]/stats.vue': {
routes:
| '/host/[uuid]/stats'
views:
| never
}
'src/pages/host/[uuid]/storage.vue': {
routes:
| '/host/[uuid]/storage'
@@ -1815,6 +1844,18 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/stats-charts/vts-stats-charts.story.vue': {
routes:
| '/story/web-core/stats-charts/vts-stats-charts'
views:
| never
}
'src/stories/web-core/stats-toolbar/vts-stats-toolbar.story.vue': {
routes:
| '/story/web-core/stats-toolbar/vts-stats-toolbar'
views:
| never
}
'src/stories/web-core/status/vts-status.story.vue': {
routes:
| '/story/web-core/status/vts-status'

View File

@@ -0,0 +1,60 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('charts').type('StatsChart[]').preset(charts).required().widget(),
prop('granularity')
.type('XapiStatsGranularity')
.enum('seconds', 'minutes', 'hours', 'days')
.preset('seconds')
.required()
.widget(),
prop('loading').bool().required().widget(),
prop('error').bool().widget(),
]"
>
<VtsStatsCharts v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop } from '@/libs/story/story-param.ts'
import type { StatsChart } from '@core/composables/stats-charts/stats-chart-builders.composable.ts'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
const SAMPLE_COUNT = 60
const now = Date.now()
function buildSeries(label: string, getValue: (index: number) => number) {
return {
label,
data: Array.from({ length: SAMPLE_COUNT }, (_, index) => ({
timestamp: now - (SAMPLE_COUNT - index) * 5000,
value: getValue(index),
})),
}
}
const charts: StatsChart[] = [
{
id: 'cpu',
title: 'CPU usage',
data: [
buildSeries('CPU 0', index => 20 + 10 * Math.sin(index / 5)),
buildSeries('CPU 1', index => 40 + 15 * Math.cos(index / 7)),
],
maxValue: 100,
valueFormatter: value => (value === null ? '' : `${value.toFixed(0)}%`),
},
{
id: 'ram',
title: 'RAM usage',
data: [],
maxValue: 100,
valueFormatter: value => String(value ?? ''),
noDataMessage: 'Guest tools are required to show the RAM usage',
},
]
</script>

View File

@@ -0,0 +1,25 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
model('granularity')
.preset('seconds')
.prop(p => p.type('XapiStatsGranularity').enum('seconds', 'minutes', 'hours', 'days'))
.required()
.help('Period covered by the stats'),
model('showTotals')
.preset(false)
.prop(p => p.bool())
.required()
.help('Whether the charts add a total line'),
]"
>
<VtsStatsToolbar v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { model } from '@/libs/story/story-param.ts'
import VtsStatsToolbar from '@core/components/stats-toolbar/VtsStatsToolbar.vue'
</script>

View File

@@ -34,7 +34,7 @@
"devDependencies": {
"@eslint/js": "^9.19.0",
"@types/node": "^22.3.0",
"@vates/types": "^3.0.0",
"@vates/types": "^3.2.0",
"rimraf": "^6.0.0",
"typescript": "~5.6.3",
"typescript-eslint": "^8.61.0"

View File

@@ -36,7 +36,7 @@
"xo-common": "^0.11.0"
},
"devDependencies": {
"@vates/types": "^3.0.0"
"@vates/types": "^3.2.0"
},
"scripts": {
"postversion": "npm publish --access public",

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@xen-orchestra/proxy",
"version": "0.35.0",
"version": "0.35.2",
"license": "AGPL-3.0-or-later",
"description": "XO Proxy used to remotely execute backup jobs",
"keywords": [
@@ -34,13 +34,13 @@
"@vates/disposable": "^0.1.7",
"@vates/task": "^0.7.0",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/backups": "^1.0.0",
"@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.24.0",
"@xen-orchestra/self-signed": "^0.2.1",
"@xen-orchestra/xapi": "^10.0.0",
"@xen-orchestra/xapi": "^10.1.0",
"ajv": "^8.0.3",
"app-conf": "^3.0.0",
"async-iterator-to-stream": "^1.1.0",

View File

@@ -22,10 +22,10 @@
"dependencies": {
"@vates/async-each": "^1.0.3",
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/vmware-explorer": "^1.3.0",
"@xen-orchestra/vmware-explorer": "^1.4.0",
"nodemailer": "^7.0.13",
"xo-lib": "^0.11.2"
},

View File

@@ -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.42.0",
"version": "0.43.1",
"description": "REST API to manage your XOA",
"license": "AGPL-3.0-or-later",
"private": false,
@@ -38,14 +38,14 @@
"@vates/async-each": "^1.0.3",
"@vates/obfuscate": "^0.2.0",
"@vates/task": "^0.7.0",
"@vates/types": "^3.0.0",
"@vates/types": "^3.2.0",
"@xen-orchestra/acl": "^1.9.0",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/cron": "^1.0.7",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/qcow2": "^1.4.1",
"@xen-orchestra/vmdk": "^1.0.0",
"@xen-orchestra/xapi": "^10.0.0",
"@xen-orchestra/xapi": "^10.1.0",
"complex-matcher": "^1.1.1",
"fast-xml-parser": "^5.10.1",
"golike-defer": "^0.5.1",

View File

@@ -13,6 +13,7 @@ import { mcpGateMiddleware } from './middlewares/mcp-gate.middleware.mjs'
import { type OpenAPIV3 } from 'openapi-types'
import { createExternalRouter, sendObjects } from './router/external-router.mjs'
import { BASE_URL } from './helpers/utils.helper.mjs'
import { rejectCrossSiteMutation } from './middlewares/csrf.middleware.mjs'
export { sendObjects }
@@ -55,6 +56,7 @@ export default function setupRestApi(express: Express, xoApp: XoApp) {
express.use(BASE_URL, setupApiContext(xoApp))
express.use(BASE_URL, logMiddleware)
express.use(BASE_URL, mcpGateMiddleware)
express.use(BASE_URL, rejectCrossSiteMutation)
RegisterRoutes(express)

View File

@@ -9,6 +9,7 @@ import type { AuthenticatedRequest } from '../helpers/helper.type.mjs'
import { iocContainer } from '../ioc/ioc.mjs'
import { RestApi } from '../rest-api/rest-api.mjs'
import { ACL_MIDDLEWARE_NAME } from './acl.middleware.mjs'
import { parseBasicCredentials } from './basic-auth.helper.mjs'
import type { SecurityName } from '@vates/types'
const log = createLogger('xo:rest-api:authentication')
@@ -73,7 +74,7 @@ export function setupApiContext(xoApp: XoApp) {
return next(new ApiError('Malformed Authorization header', 400))
}
const [username, password] = Buffer.from(encoded, 'base64').toString().split(':')
const { username, password } = parseBasicCredentials(encoded)
Object.assign(credentials, { username, password, otp: query.otp })
res.locals.authType = 'basic'
}

View File

@@ -0,0 +1,14 @@
/**
* Extracts the credentials from the base64 payload of a `Authorization: Basic` header.
*
* Per RFC 7617 §2, the user-id cannot contain a colon but the password can: split on the
* first colon only and keep the remainder as the password.
*/
export function parseBasicCredentials(encoded: string): { username: string; password: string | undefined } {
const decoded = Buffer.from(encoded, 'base64').toString()
const index = decoded.indexOf(':')
if (index === -1) {
return { username: decoded, password: undefined }
}
return { username: decoded.slice(0, index), password: decoded.slice(index + 1) }
}

View File

@@ -0,0 +1,25 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { parseBasicCredentials } from './basic-auth.helper.mjs'
const encode = (value: string) => Buffer.from(value).toString('base64')
describe('parseBasicCredentials()', () => {
it('splits username and password', () => {
assert.deepEqual(parseBasicCredentials(encode('user:pass')), { username: 'user', password: 'pass' })
})
it('keeps colons found in the password', () => {
assert.deepEqual(parseBasicCredentials(encode('user:a:b')), { username: 'user', password: 'a:b' })
assert.deepEqual(parseBasicCredentials(encode('user::')), { username: 'user', password: ':' })
})
it('supports an empty password', () => {
assert.deepEqual(parseBasicCredentials(encode('user:')), { username: 'user', password: '' })
})
it('has no password when there is no colon', () => {
assert.deepEqual(parseBasicCredentials(encode('user')), { username: 'user', password: undefined })
})
})

View File

@@ -0,0 +1,31 @@
import type { NextFunction, Response, Request } from 'express'
import { ApiError } from '../helpers/error.helper.mjs'
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
function isCrossSite(req: Request): boolean {
const secFetchSite = req.headers['sec-fetch-site']
if (secFetchSite !== undefined) {
return secFetchSite === 'cross-site'
}
const { origin } = req.headers
if (origin !== undefined) {
try {
return new URL(origin).host !== req.headers.host
} catch (error) {
return true
}
}
return false
}
export function rejectCrossSiteMutation(req: Request, res: Response, next: NextFunction) {
// res.locals.authType is setup by authentication.middleware#setupApiContext
if (!SAFE_METHODS.has(req.method) && res.locals.authType === 'token' && isCrossSite(req)) {
return next(new ApiError('cross-site request rejected', 403))
}
next()
}

View File

@@ -0,0 +1,78 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { Request, Response } from 'express'
import { ApiError } from '../helpers/error.helper.mjs'
import { rejectCrossSiteMutation } from './csrf.middleware.mjs'
const run = (method: string, opts: { authType?: 'token' | 'basic'; headers?: Request['headers'] }) => {
const req = { method, headers: opts.headers ?? {} } as Request
const res = { locals: { authType: 'authType' in opts ? opts.authType : 'token' } } as unknown as Response
let next: unknown
rejectCrossSiteMutation(req, res, (err?: unknown) => {
next = err
})
return next
}
const UNSAFE = ['POST', 'PUT', 'PATCH', 'DELETE']
describe('rejectCrossSiteMutation', () => {
describe('lets through', () => {
it('a safe method, even cross-site with a cookie', () => {
assert.equal(run('GET', { headers: { 'sec-fetch-site': 'cross-site' } }), undefined)
})
for (const method of UNSAFE) {
it(`${method} authenticated by basic, even cross-site`, () => {
assert.equal(run(method, { authType: 'basic', headers: { 'sec-fetch-site': 'cross-site' } }), undefined)
})
it(`${method} unauthenticated, even cross-site`, () => {
assert.equal(run(method, { authType: undefined, headers: { 'sec-fetch-site': 'cross-site' } }), undefined)
})
it(`${method} cookie + Sec-Fetch-Site same-origin`, () => {
assert.equal(run(method, { headers: { 'sec-fetch-site': 'same-origin' } }), undefined)
})
it(`${method} cookie + Sec-Fetch-Site same-site`, () => {
assert.equal(run(method, { headers: { 'sec-fetch-site': 'same-site' } }), undefined)
})
it(`${method} cookie + Sec-Fetch-Site none`, () => {
assert.equal(run(method, { headers: { 'sec-fetch-site': 'none' } }), undefined)
})
it(`${method} cookie + no metadata (xo-cli, curl)`, () => {
assert.equal(run(method, { headers: {} }), undefined)
})
it(`${method} cookie + Origin matches Host`, () => {
assert.equal(run(method, { headers: { origin: 'https://xo.example.com', host: 'xo.example.com' } }), undefined)
})
it(`${method} cookie: Sec-Fetch-Site wins over a mismatching Origin`, () => {
assert.equal(
run(method, {
headers: { 'sec-fetch-site': 'same-origin', origin: 'https://evil.com', host: 'xo.example.com' },
}),
undefined
)
})
}
})
describe('rejects (403)', () => {
const assertRejected = (error: unknown) => {
assert.ok(error instanceof ApiError)
assert.equal((error as ApiError).status, 403)
}
for (const method of UNSAFE) {
it(`${method} cookie + Sec-Fetch-Site cross-site`, () => {
assertRejected(run(method, { headers: { 'sec-fetch-site': 'cross-site' } }))
})
it(`${method} cookie + Origin host != Host`, () => {
assertRejected(run(method, { headers: { origin: 'https://evil.com', host: 'xo.example.com' } }))
})
it(`${method} cookie + malformed Origin (fail closed)`, () => {
assertRejected(run(method, { headers: { origin: 'null', host: 'xo.example.com' } }))
})
}
})
})

View File

@@ -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)
}
}

View File

@@ -1,7 +1,7 @@
{
"license": "ISC",
"private": false,
"version": "1.3.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": {

View File

@@ -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",

View File

@@ -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"

View File

@@ -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.

View File

@@ -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",

View File

@@ -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

View File

@@ -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

View File

@@ -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. |

View File

@@ -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

View File

@@ -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

View File

@@ -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"

View File

@@ -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!(

View File

@@ -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,
)

View File

@@ -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) {

View File

@@ -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]

View File

@@ -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);

View 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());
}
}

View File

@@ -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 [

View File

@@ -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:?}");
}
}

View File

@@ -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";

View File

@@ -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);
};

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