Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions create-a-container/openapi.v1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1307,10 +1307,13 @@ paths:
post:
operationId: exec_container
tags: [Containers]
summary: Run one command as root in a running guest (owner/admin)
summary: Run one command in a running guest as the authenticated caller (owner/admin)
description: >-
Proxmox guests only. The command runs through the Proxmox console API,
so the guest needs no SSH route, but it needs a POSIX `sh`. The
so the guest needs no SSH route. It needs a POSIX `sh`, `sudo`,
`setsid`, `timeout`, and a non-root Linux account with the caller's exact Manager
username. Guest and Manager numeric UIDs can differ. The Manager
selects this account for both owners and admins. The
executable and its arguments are passed as separate words, without
shell interpretation. The first call on a guest created before this
feature switches its console mode and returns `exec_restart_required`;
Expand Down Expand Up @@ -1357,9 +1360,9 @@ paths:
'401': { description: Authentication required }
'403': { $ref: '#/components/responses/Forbidden' }
'404': { $ref: '#/components/responses/NotFound' }
'409': { description: 'Guest is stopped (guest_not_running), its hostname does not match (guest_identity_mismatch), another command is running in it (exec_busy), or it must be restarted once to enable exec (exec_restart_required)' }
'409': { description: 'Guest is stopped (guest_not_running), its hostname does not match (guest_identity_mismatch), its matching non-root caller account is unavailable (guest_user_unavailable), another command is running in it (exec_busy), or it must be restarted once to enable exec (exec_restart_required)' }
'415': { description: Expected application/json }
'501': { description: Execution is unavailable on this node }
'501': { description: Execution is unavailable on this node or the guest lacks required tools such as sudo or setsid (exec_unavailable) }
'502': { description: Guest command outcome is unknown }
'504': { description: Guest command timed out }
/sites/{siteId}/containers/{id}/collaborators:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ jest.mock('../../../../utils/guest-exec', () => ({
const { executeGuest, EXEC_LEASE_SECONDS } = require('../../../../utils/guest-exec');

describe('POST container exec', () => {
let app, site, otherSite, node, box, otherBox, owner, ownerKey, adminKey, viewerKey, audit;
let app, site, otherSite, node, box, otherBox, owner, ownerKey, admin, adminKey, viewerKey, audit;
const argv = ['node', '--version'];
// The guest's NSS directory assigns its own numeric IDs independently of Manager.
const guestUid = 12001;
const result = {
stdout: Buffer.from([0, 255, 10]).toString('base64'),
stderr: Buffer.from('guest diagnostic').toString('base64'),
Expand All @@ -21,7 +23,7 @@ describe('POST container exec', () => {
beforeAll(async () => {
await resetDb();
app = buildApp();
const admin = await createUser({ admin: true });
admin = await createUser({ admin: true });
owner = await createUser();
const viewer = await createUser();
({ plainKey: ownerKey } = await createApiKey(owner));
Expand All @@ -45,7 +47,7 @@ describe('POST container exec', () => {
beforeEach(async () => {
await Container.update({ execLeaseUntil: null }, { where: {} });
executeGuest.mockReset();
executeGuest.mockResolvedValue(result);
executeGuest.mockResolvedValue({ ...result, guestUid });
audit = jest.spyOn(console, 'info').mockImplementation(() => {});
});
afterEach(() => audit.mockRestore());
Expand All @@ -65,24 +67,30 @@ describe('POST container exec', () => {
expect(executeGuest).toHaveBeenCalledTimes(1);
expect(executeGuest).toHaveBeenCalledWith({
node: expect.objectContaining({ id: node.id, name: node.name }), vmid: 701, hostname: box.hostname, argv: args,
guestUser: owner.uid,
leaseUntil: expect.any(Date),
});
const { leaseUntil } = executeGuest.mock.calls[0][0];
expect(leaseUntil.getTime() - Date.now()).toBeGreaterThan((EXEC_LEASE_SECONDS - 10) * 1000);
const log = audit.mock.calls[0][0];
expect(JSON.parse(log)).toMatchObject({
event: 'container.exec', callerUidNumber: owner.uidNumber, siteId: site.id, containerId: box.id,
requestedGuestUser: owner.uid, guestUid,
startedAt: expect.any(String), durationMs: expect.any(Number), outcome: 'exited', exitCode: 0,
});
for (const secret of ['secret=', result.stdout, result.stderr, ownerKey]) expect(log).not.toContain(secret);
});

test('an authorized admin receives a nonzero exit and truncation as an ordinary result', async () => {
const failed = { ...result, exitCode: 23, stderrTruncated: true };
executeGuest.mockResolvedValue(failed);
executeGuest.mockResolvedValue({ ...failed, guestUid: 12002 });
const res = await post({ argv }, { key: adminKey });
expect(res.status).toBe(200);
expect(res.body.data).toEqual(failed);
expect(executeGuest.mock.calls[0][0].guestUser).toBe(admin.uid);
expect(JSON.parse(audit.mock.calls[0][0])).toMatchObject({
callerUidNumber: admin.uidNumber, requestedGuestUser: admin.uid, guestUid: 12002,
});
});

test('denies anonymous callers, read-only collaborators, other owners and cross-site requests', async () => {
Expand All @@ -99,6 +107,7 @@ describe('POST container exec', () => {
{}, { argv: [] }, { argv: [''] }, { argv: 'ls' }, { argv: ['ls', 1] },
{ argv: ['ls', 'x\0y'] }, { argv: ['ls', '\ud800'] }, { argv: Array(129).fill('x') },
{ argv: ['x'.repeat(16384)] }, { argv, vmid: 702 }, { argv, user: 'root' },
{ argv, guestUser: { name: admin.uid, uid: admin.uidNumber } },
]) {
expect((await post(body)).status).toBe(400);
}
Expand All @@ -120,7 +129,7 @@ describe('POST container exec', () => {

test('runs one command per guest at a time, across Manager processes', async () => {
let finish;
executeGuest.mockImplementation(() => new Promise((resolve) => { finish = () => resolve(result); }));
executeGuest.mockImplementation(() => new Promise((resolve) => { finish = () => resolve({ ...result, guestUid }); }));
// supertest sends a request only once it is awaited or then()'d.
const first = post({ argv }).then((res) => res);
await new Promise((resolve) => { const wait = () => (finish ? resolve() : setTimeout(wait, 5)); wait(); });
Expand Down Expand Up @@ -153,7 +162,7 @@ describe('POST container exec', () => {

test.each([
['exec_restart_required', 409], ['guest_not_running', 409],
['guest_identity_mismatch', 409], ['exec_unavailable', 501],
['guest_identity_mismatch', 409], ['guest_user_unavailable', 409], ['exec_unavailable', 501],
['exec_timeout', 504], ['exec_outcome_unknown', 502], ['ECONNRESET', 502],
])('maps backend failure %s without logging or returning raw diagnostics', async (code, status) => {
executeGuest.mockRejectedValue(Object.assign(new Error('private diagnostic'), { code }));
Expand All @@ -163,7 +172,9 @@ describe('POST container exec', () => {
expect(res.body.error.code).toBe(expectedCode);
expect(res.text).not.toContain('private diagnostic');
expect(audit.mock.calls[0][0]).not.toContain('private diagnostic');
expect(JSON.parse(audit.mock.calls[0][0]).outcome).toBe(expectedCode);
const log = JSON.parse(audit.mock.calls[0][0]);
expect(log).toMatchObject({ outcome: expectedCode, requestedGuestUser: owner.uid });
expect(log).not.toHaveProperty('guestUid');
expect(executeGuest).toHaveBeenCalledTimes(1);
});
});
14 changes: 8 additions & 6 deletions create-a-container/routers/api/v1/containers.js
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,7 @@ const execErrors = new Map([
['exec_restart_required', [409, 'Restart the guest to enable command execution']],
['guest_not_running', [409, 'The guest is not running']],
['guest_identity_mismatch', [409, 'The running guest identity could not be verified']],
['guest_user_unavailable', [409, 'The command could not be run as the authenticated guest user']],
['exec_timeout', [504, 'Guest execution timed out']],
['exec_outcome_unknown', [502, 'The guest command outcome is unknown']],
]);
Expand Down Expand Up @@ -456,9 +457,7 @@ router.post('/:id/exec', asyncHandler(async (req, res) => {
};
res.set('Cache-Control', 'no-store');
try {
// Look up only the stable numerical account ID for the audit record.
// A bearer-authenticated session also holds the credential's ORM record.
const caller = await User.findOne({ where: { uid: req.session.user }, attributes: ['uidNumber'], raw: true });
const caller = await User.findOne({ where: { uid: req.session.user }, attributes: ['uid', 'uidNumber'], raw: true });
if (!Number.isSafeInteger(caller?.uidNumber)) throw new ApiError(403, 'forbidden', 'Unknown Manager account');
audit.callerUidNumber = caller.uidNumber;
if (![req.params.siteId, req.params.id].every(id => /^[1-9]\d*$/.test(id) && Number.isSafeInteger(Number(id)))) {
Expand All @@ -467,6 +466,7 @@ router.post('/:id/exec', asyncHandler(async (req, res) => {
const { site, container } = await loadContainerForSession(siteId, containerId, req.session, { requireManage: true });
if (container.siteId !== site.id) throw new ApiError(404, 'not_found', 'Container not found');
const argv = readExecArgs(req);
audit.requestedGuestUser = caller.uid;
if (container.node.nodeType !== 'proxmox') throw new ApiError(501, 'exec_unavailable', 'Guest execution is unavailable on this node');
if (!container.containerId) throw new ApiError(409, 'guest_not_running', 'The guest has not been provisioned');
const vmid = Number(container.containerId);
Expand All @@ -482,7 +482,7 @@ router.post('/:id/exec', asyncHandler(async (req, res) => {
let keepLease = false;
try {
result = await executeGuest({
node: container.node, vmid, hostname: container.hostname, argv, leaseUntil: lease,
node: container.node, vmid, hostname: container.hostname, argv, guestUser: caller.uid, leaseUntil: lease,
});
} catch (err) {
const code = execErrors.has(err?.code) ? err.code : 'exec_outcome_unknown';
Expand All @@ -495,9 +495,11 @@ router.post('/:id/exec', asyncHandler(async (req, res) => {
} finally {
if (!keepLease) await container.releaseExecLease(lease);
}
const { guestUid, ...commandResult } = result;
audit.outcome = 'exited';
audit.exitCode = result.exitCode;
return ok(res, result);
audit.guestUid = guestUid;
audit.exitCode = commandResult.exitCode;
return ok(res, commandResult);
} catch (err) {
const safe = err instanceof ApiError ? err : new ApiError(500, 'internal_error', 'Internal server error');
audit.outcome = safe.code;
Expand Down
Loading
Loading