Complete customer transfers on first authenticated inventory
Rust development slice / linux (push) Failing after 8s

This commit is contained in:
2026-11-18 22:57:05 +01:00
parent 65d84a19c0
commit 480e3749a6
13 changed files with 234 additions and 76 deletions
+15 -17
View File
@@ -232,6 +232,7 @@ test('moves an existing pairing through the WebUI and waits for target inventory
target_asset_id: 'new-asset', target_agent_id: 'new-agent', target_hostname: 'NORD-PC' };
let state = '';
let canEnroll = false;
let posts = 0;
const listing = (items: unknown[]) => ({ items, next_cursor: null, truncated: false,
completeness: 'complete', as_of: new Date().toISOString() });
await page.route(origin + '/auth/config', r => r.fulfill({ json: {
@@ -257,14 +258,10 @@ test('moves an existing pairing through the WebUI and waits for target inventory
expect(req.headers()['x-csrf-token']).toBe('move-csrf');
expect(req.headers()['x-rmm-tenant']).toBe(source.tenant_id);
expect(url.searchParams.get('agent_id')).toBe(device.agent_id);
if (url.pathname === move) {
expect(req.postDataJSON()).toEqual({ target_tenant_id: target.tenant_id });
state = 'pending';
} else {
expect(url.pathname).toBe(move + '/move-fixture/complete');
expect(state).toBe('ready');
state = 'completed';
}
expect(url.pathname).toBe(move);
expect(req.postDataJSON()).toEqual({ target_tenant_id: target.tenant_id });
posts++;
state = 'pending';
return r.fulfill({ json: { state } });
}
return r.fulfill({ status: 404, json: { code: 'NOT_FOUND' } });
@@ -275,22 +272,23 @@ test('moves an existing pairing through the WebUI and waits for target inventory
await page.getByText('Kunden wechseln', { exact: true }).click();
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption(target.tenant_id);
await expect(page.getByText('Für diesen Zielkunden fehlt das Recht', { exact: false })).toBeVisible();
const prepare = page.getByRole('button', { name: 'Kundenwechsel vormerken' });
const prepare = page.getByRole('button', { name: 'Kundenwechsel starten' });
await expect(prepare).toBeDisabled();
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption('');
canEnroll = true;
await page.getByRole('combobox', { name: 'Zielkunde', exact: true }).selectOption(target.tenant_id);
await prepare.click();
await expect(page.getByText('Der Wechsel ist vorgemerkt.', { exact: false })).toBeVisible();
const finish = page.getByRole('button', { name: 'Kundenwechsel abschließen' });
await expect(finish).toHaveCount(0);
state = 'ready';
await expect(finish).toBeDisabled({ timeout: 10000 });
await page.getByRole('checkbox', { name: 'Ich bestätige den Kundenwechsel für dieses Gerät.' }).check();
await finish.click();
await expect(page.getByText('Kundenwechsel abgeschlossen.', { exact: false })).toBeVisible();
await expect(page.getByRole('link', { name: 'Neue Kopplung öffnen' })).toHaveAttribute('href',
const destination = page.getByRole('link', { name: 'Neue Kopplung öffnen' });
state = 'enrolled';
await expect(page.getByText('Der Wechsel wird mit der ersten Inventarmeldung', { exact: false }))
.toBeVisible({ timeout: 10000 });
await expect(destination).toHaveCount(0);
state = 'completed';
await expect(page.getByText('Kundenwechsel abgeschlossen.', { exact: false })).toBeVisible({ timeout: 10000 });
await expect(destination).toHaveAttribute('href',
'#geraete/' + target.tenant_id + '/new-asset/new-agent');
expect(posts).toBe(1);
});
test('shows real VM hosts and the Hetzner placeholder without adding a device', async ({ page }) => {
+50 -4
View File
@@ -20,6 +20,7 @@ import subprocess
import sys
import tempfile
import time
import urllib.parse
import uuid
from local_access_database import command
@@ -40,6 +41,27 @@ def until(probe, seconds=80):
raise AssertionError(f"Timed out waiting for {probe.__name__}")
def existing_transfer(sql, with_inventory):
"""Seed the state left by the old server before the extra confirmation."""
asset_a, asset_b, agent_a, agent_b, move = (uuid.uuid4() for _ in range(5))
sql(f"""INSERT INTO assets VALUES ('{A}','{asset_a}'),('{B}','{asset_b}');
INSERT INTO agent_installations
(tenant_id,asset_id,agent_id,certificate_sha256,last_contact_at,
last_authenticated_at,last_authenticated_certificate_sha256)
SELECT tenant::uuid,asset::uuid,agent::uuid,pin,now(),now(),pin
FROM (VALUES ('{A}','{asset_a}','{agent_a}','{secrets.token_hex(32)}'),
('{B}','{asset_b}','{agent_b}','{secrets.token_hex(32)}')) x(tenant,asset,agent,pin);
INSERT INTO device_customer_transfers (transfer_id,source_tenant_id,source_asset_id,source_agent_id,
target_tenant_id,target_asset_id,target_agent_id,requested_by,csr_sha256)
VALUES ('{move}','{A}','{asset_a}','{agent_a}','{B}','{asset_b}','{agent_b}','fixture',repeat('a',64));""")
if with_inventory:
sql(f"""INSERT INTO observations(tenant_id,agent_id,message_id,boot_id,sequence,
observed_at,source_id,quality,completeness,snapshot_id,data,payload_sha256)
VALUES ('{B}','{agent_b}',gen_random_uuid(),gen_random_uuid(),1,now(),'linux.base','valid',
'partial',gen_random_uuid(),'{{"hostname":"Legacy ready VM"}}',repeat('b',64));""")
return str(agent_a), str(asset_b), str(agent_b)
def run(server, agent, folder, db, api):
pg_password = secrets.token_hex(24)
command(["docker", "run", "-d", "--name", db, "-p", "127.0.0.1::5432",
@@ -58,6 +80,9 @@ def run(server, agent, folder, db, api):
ALTER DATABASE postgres OWNER TO rmm_migrator;
ALTER SCHEMA public OWNER TO rmm_migrator;""")
for migration in sorted((ROOT / "migrations").glob("*.sql")):
if migration.name.startswith("0044_"):
ready_source, ready_asset, ready_target = existing_transfer(sql, with_inventory=True)
waiting_source, waiting_asset, waiting_target = existing_transfer(sql, with_inventory=False)
sql(migration.read_text(), "rmm_migrator")
users, login_data = [], {}
@@ -149,6 +174,19 @@ def run(server, agent, folder, db, api):
return headers
owner, source_only, target_only = map(login, ("owner", "sourceonly", "targetonly"))
def fleet_ids(headers, hostname=None):
query = "" if hostname is None else "&q=" + urllib.parse.quote(hostname)
status, listing, _ = request("/api/v1/devices?view=current" + query, headers=headers)
assert status == 200, (status, listing)
return {row["agent_id"] for row in listing["items"]}
fleet = fleet_ids(owner)
assert {ready_target, waiting_source} <= fleet and {ready_source, waiting_target}.isdisjoint(fleet)
for asset, agent_id, expected in [(ready_asset, ready_target, 200), (waiting_asset, waiting_target, 404)]:
assert request(f"/api/v1/tenants/{B}/devices/{asset}?agent_id={agent_id}", headers=target_only)[0] == expected
print("PASS migration completes an existing reported transfer and hides an authenticated target without inventory")
token = secrets.token_hex(32)
token_path = folder / "enrollment"
token_path.write_text(token)
@@ -201,13 +239,15 @@ def run(server, agent, folder, db, api):
finally:
proc.send_signal(signal.SIGCONT)
def target_ready():
def target_completed():
status, dto, _ = request(transfer + query, headers=owner)
assert status == 200, (status, dto)
move = dto["transfer"]
return move if move["state"] == "ready" else None
ids = fleet_ids(owner, old["hostname"])
assert len(ids) == 1, ("fleet during transfer", ids)
return move if move["state"] == "completed" else None
moved = until(target_ready)
moved = until(target_completed)
assert moved["target_hostname"] == old["hostname"]
target_agent, target_asset = moved["target_agent_id"], moved["target_asset_id"]
assert target_agent != old_agent and target_asset != old_asset
@@ -215,11 +255,16 @@ def run(server, agent, folder, db, api):
assert local["agent_id"] == target_agent
assert not list(state.glob("customer-move-*-prior-journal.sqlite"))
assert proc.poll() is None
print("PASS the existing Linux process received a signed handoff and reported fresh target inventory")
assert target_agent in fleet_ids(owner) and old_agent not in fleet_ids(owner)
print("PASS fresh inventory from the running Linux process switches the sole active entry automatically")
route = suffix(moved["transfer_id"], "complete")
assert request(route, {}, owner)[0] == 200
assert request(route, {}, owner)[0] == 200
assert sql(f"""SELECT count(*) FROM audit_events
WHERE event_type='device_customer_transfer_completed'
AND data->'decision'->>'agent_id'='{old_agent}'
AND data->>'completion_origin'='automatic_after_target_inventory';""") == "1"
assert request("/agent/v1/customer-transfer", tls=old_context)[0] == 401
status, historic, _ = request(f"/api/v1/tenants/{A}/devices?view=history", headers=source_only)
assert status == 200 and any(x["agent_id"] == old_agent and x["lifecycle"] == "revoked" for x in historic["items"])
@@ -255,6 +300,7 @@ def run(server, agent, folder, db, api):
status, fleet, _ = request("/api/v1/devices?view=current", headers=bearer)
assert status == 200
assert (target_agent in {row["agent_id"] for row in fleet["items"]}) == (audience == "all")
assert all(row["agent_id"] != old_agent for row in fleet["items"])
destination = f"/api/v1/tenants/{B}/devices/{target_asset}?agent_id={target_agent}"
assert request(destination, headers={**bearer, "X-RMM-Tenant": B})[0] == (200 if audience == "all" else 404)
assert request(transfer + query, headers={**bearer, "X-RMM-Tenant": A})[0] == 403