Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Harden hosted mobile approval proof setup

rcourtmanbefb0160f70c
diff --git a/tests/integration/scripts/approval-store-helper/main.go b/tests/integration/scripts/approval-store-helper/main.go
new file mode 100644
index 0000000000..fa73e29ffc
--- /dev/null
+++ b/tests/integration/scripts/approval-store-helper/main.go
@@ -0,0 +1,353 @@
+package main
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+const defaultTargetType = "agent"
+
+var osExit = os.Exit
+
+type cliArgs struct {
+ action string
+ approvalID string
+ command string
+ context string
+ dataDir string
+ executionID string
+ orgID string
+ risk string
+ targetID string
+ targetName string
+ targetType string
+ timeout time.Duration
+ toolID string
+}
+
+type helperResult struct {
+ Action string `json:"action"`
+ DataDir string `json:"dataDir"`
+ Found bool `json:"found"`
+ OrgID string `json:"orgId"`
+ ApprovalID string `json:"approvalId"`
+ Approval *approval.ApprovalRequest `json:"approval,omitempty"`
+}
+
+func usage(message string) {
+ if message != "" {
+ fmt.Fprintf(os.Stderr, "error: %s\n\n", message)
+ }
+ fmt.Fprintln(os.Stderr, "usage: approval-store-helper <create|get> --data-dir <dir> --org-id <id> --approval-id <id> [--command <command>] [--target-type <type>] [--target-id <id>] [--target-name <name>] [--context <text>] [--risk <low|medium|high>] [--tool-id <id>] [--execution-id <id>] [--timeout <duration>]")
+ osExit(2)
+}
+
+func parseArgs(argv []string) cliArgs {
+ if len(argv) == 0 {
+ usage("missing action")
+ }
+
+ args := cliArgs{
+ action: strings.TrimSpace(argv[0]),
+ targetType: defaultTargetType,
+ timeout: 15 * time.Minute,
+ toolID: "pulse_control",
+ }
+ flags := flag.NewFlagSet("approval-store-helper", flag.ContinueOnError)
+ flags.SetOutput(os.Stderr)
+ flags.StringVar(&args.approvalID, "approval-id", "", "approval id")
+ flags.StringVar(&args.command, "command", "", "command awaiting approval")
+ flags.StringVar(&args.context, "context", "", "approval context")
+ flags.StringVar(&args.dataDir, "data-dir", "", "approval store data directory")
+ flags.StringVar(&args.executionID, "execution-id", "", "execution id")
+ flags.StringVar(&args.orgID, "org-id", "", "organization id")
+ flags.StringVar(&args.risk, "risk", "", "risk level")
+ flags.StringVar(&args.targetID, "target-id", "", "approval target id")
+ flags.StringVar(&args.targetName, "target-name", "", "approval target name")
+ flags.StringVar(&args.targetType, "target-type", defaultTargetType, "approval target type")
+ flags.DurationVar(&args.timeout, "timeout", args.timeout, "approval timeout")
+ flags.StringVar(&args.toolID, "tool-id", args.toolID, "tool id")
+
+ if err := flags.Parse(argv[1:]); err != nil {
+ usage(err.Error())
+ }
+ if flags.NArg() != 0 {
+ usage(fmt.Sprintf("unexpected argument %q", flags.Arg(0)))
+ }
+ if args.action != "create" && args.action != "get" {
+ usage(fmt.Sprintf("unsupported action %q", args.action))
+ }
+ if strings.TrimSpace(args.dataDir) == "" {
+ usage("--data-dir is required")
+ }
+ if strings.TrimSpace(args.approvalID) == "" {
+ usage("--approval-id is required")
+ }
+ if args.timeout <= 0 {
+ usage("--timeout must be positive")
+ }
+ if args.action == "create" {
+ if strings.TrimSpace(args.command) == "" {
+ usage("--command is required for create")
+ }
+ if strings.TrimSpace(args.targetID) == "" {
+ usage("--target-id is required for create")
+ }
+ }
+
+ args.orgID = approval.NormalizeOrgID(args.orgID)
+ args.targetType = strings.ToLower(strings.TrimSpace(args.targetType))
+ if args.targetType == "" {
+ args.targetType = defaultTargetType
+ }
+ if args.executionID == "" {
+ args.executionID = "mobile-release-proof-" + strings.TrimSpace(args.approvalID)
+ }
+ if args.context == "" {
+ args.context = args.command
+ }
+ if args.risk == "" {
+ args.risk = string(approval.AssessRiskLevel(args.command, args.targetType))
+ }
+
+ return args
+}
+
+func main() {
+ args := parseArgs(os.Args[1:])
+ if err := run(args); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
+
+func run(args cliArgs) error {
+ dataDir, err := filepath.Abs(args.dataDir)
+ if err != nil {
+ return fmt.Errorf("resolve data dir: %w", err)
+ }
+ if err := os.MkdirAll(dataDir, 0700); err != nil {
+ return fmt.Errorf("create data dir: %w", err)
+ }
+
+ store, err := approval.NewStore(approval.StoreConfig{
+ DataDir: dataDir,
+ DefaultTimeout: args.timeout,
+ MaxApprovals: 100,
+ })
+ if err != nil {
+ return fmt.Errorf("open approval store: %w", err)
+ }
+
+ var req *approval.ApprovalRequest
+ found := false
+ switch args.action {
+ case "create":
+ req = buildApprovalRequest(args)
+ if err := store.CreateApproval(req); err != nil {
+ return fmt.Errorf("create approval: %w", err)
+ }
+ store.Flush()
+ found = true
+ case "get":
+ req, found = store.GetApproval(args.approvalID)
+ }
+
+ result := helperResult{
+ Action: args.action,
+ DataDir: dataDir,
+ Found: found,
+ OrgID: args.orgID,
+ ApprovalID: args.approvalID,
+ Approval: req,
+ }
+ encoded, err := json.MarshalIndent(result, "", " ")
+ if err != nil {
+ return fmt.Errorf("encode result: %w", err)
+ }
+ fmt.Printf("%s\n", encoded)
+ return nil
+}
+
+func buildApprovalRequest(args cliArgs) *approval.ApprovalRequest {
+ now := time.Now().UTC()
+ expiresAt := now.Add(args.timeout)
+ actionID := uuid.NewString()
+ capabilityName := approvalCapabilityForTargetType(args.targetType)
+ resourceID := approvalAuditResourceID(args.targetType, args.targetID, args.targetName)
+ plan := &unifiedresources.ActionPlan{
+ ActionID: actionID,
+ RequestID: args.approvalID,
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unifiedresources.ApprovalAdmin,
+ PredictedBlastRadius: approvalBlastRadius(args.targetType, args.command),
+ RollbackAvailable: approvalRollbackAvailable(args.targetType, args.command),
+ Message: strings.TrimSpace(args.context),
+ PlannedAt: now,
+ ExpiresAt: expiresAt,
+ PolicyVersion: "v6-mobile-release-proof",
+ PlanHash: approvalPlanHash(actionID, args.approvalID, capabilityName, resourceID, args.command, args.targetType, args.targetID, args.context),
+ }
+
+ req := &approval.ApprovalRequest{
+ ID: args.approvalID,
+ OrgID: args.orgID,
+ ExecutionID: args.executionID,
+ ToolID: args.toolID,
+ Command: args.command,
+ TargetType: args.targetType,
+ TargetID: args.targetID,
+ TargetName: args.targetName,
+ Context: args.context,
+ RiskLevel: approval.RiskLevel(args.risk),
+ RequestedAt: now,
+ ExpiresAt: expiresAt,
+ Plan: plan,
+ }
+ req.ContextConfidence = approvalContextConfidence(req)
+ req.Preflight = approvalPreflight(req)
+ return req
+}
+
+func approvalCapabilityForTargetType(targetType string) string {
+ switch strings.ToLower(strings.TrimSpace(targetType)) {
+ case "docker", "app-container", "docker-service":
+ return "pulse_docker"
+ case "file":
+ return "pulse_file_edit"
+ case "kubernetes", "pod", "k8s-cluster", "k8s-node", "k8s-deployment":
+ return "pulse_kubernetes"
+ default:
+ return "pulse_control"
+ }
+}
+
+func approvalAuditResourceID(targetType, targetID, targetName string) string {
+ targetType = strings.TrimSpace(targetType)
+ targetID = strings.TrimSpace(targetID)
+ if targetID == "" {
+ targetID = strings.TrimSpace(targetName)
+ }
+ if targetID == "" {
+ return targetType
+ }
+ if targetType == "" || strings.Contains(targetID, ":") {
+ return targetID
+ }
+ return targetType + ":" + targetID
+}
+
+func approvalBlastRadius(targetType, command string) []string {
+ commandLower := strings.ToLower(strings.TrimSpace(command))
+ switch {
+ case strings.Contains(commandLower, "delete") || strings.HasPrefix(commandLower, "rm ") || strings.Contains(commandLower, " rm "):
+ return []string{"destructive target change"}
+ case strings.Contains(commandLower, "restart") || strings.Contains(commandLower, "reboot") || strings.Contains(commandLower, "shutdown") || strings.Contains(commandLower, "stop"):
+ return []string{"service interruption on target"}
+ case strings.ToLower(strings.TrimSpace(targetType)) == "file":
+ return []string{"file contents on target"}
+ case strings.Contains(strings.ToLower(strings.TrimSpace(targetType)), "k8s") || strings.ToLower(strings.TrimSpace(targetType)) == "kubernetes":
+ return []string{"kubernetes workload state"}
+ default:
+ return []string{"target resource state"}
+ }
+}
+
+func approvalRollbackAvailable(targetType, command string) bool {
+ commandLower := strings.ToLower(strings.TrimSpace(command))
+ if strings.ToLower(strings.TrimSpace(targetType)) == "file" || strings.Contains(commandLower, "delete") || strings.HasPrefix(commandLower, "rm ") || strings.Contains(commandLower, " rm ") {
+ return false
+ }
+ return strings.Contains(commandLower, "restart") || strings.Contains(commandLower, "start") || strings.Contains(commandLower, "stop")
+}
+
+func approvalContextConfidence(req *approval.ApprovalRequest) *approval.ContextConfidence {
+ targetType := strings.TrimSpace(req.TargetType)
+ targetID := strings.TrimSpace(req.TargetID)
+ targetName := strings.TrimSpace(req.TargetName)
+ evidence := make([]string, 0, 3)
+ if targetType != "" {
+ evidence = append(evidence, fmt.Sprintf("Target type resolved as %s.", targetType))
+ }
+ if targetID != "" {
+ evidence = append(evidence, fmt.Sprintf("Target identifier bound to %s.", targetID))
+ }
+ if targetName != "" {
+ evidence = append(evidence, fmt.Sprintf("Display target resolved as %s.", targetName))
+ }
+
+ level := approval.ContextConfidenceUnknown
+ summary := "Pulse Assistant could not bind this action to a resolved target."
+ switch {
+ case targetType != "" && targetID != "":
+ level = approval.ContextConfidenceVerified
+ summary = "Target was resolved to a concrete resource before approval."
+ case targetType != "" && targetName != "":
+ level = approval.ContextConfidencePartial
+ summary = "Target type and display name were resolved before approval."
+ case targetType != "" || targetName != "":
+ level = approval.ContextConfidenceInferred
+ summary = "Target context was inferred from the requested action."
+ }
+
+ return &approval.ContextConfidence{
+ Level: level,
+ Summary: summary,
+ Evidence: evidence,
+ }
+}
+
+func approvalPreflight(req *approval.ApprovalRequest) *approval.ActionPreflight {
+ target := approvalAuditResourceID(req.TargetType, req.TargetID, req.TargetName)
+ intendedChange := strings.TrimSpace(req.Context)
+ if intendedChange == "" {
+ intendedChange = strings.TrimSpace(req.Command)
+ }
+
+ return &approval.ActionPreflight{
+ Target: target,
+ CurrentState: fmt.Sprintf("Resolved approval target: %s.", target),
+ IntendedChange: intendedChange,
+ DryRunAvailable: false,
+ DryRunSummary: "No provider-supported dry run is available for this action; Pulse will hold execution until approval and validate the approval binding before dispatch.",
+ SafetyChecks: []string{
+ "Approval is scoped to the current organization.",
+ "Command hash must match before execution.",
+ "Approval can be consumed only once.",
+ "Target type and identifier must match the planned action.",
+ },
+ VerificationSteps: []string{
+ "Persist unified action audit lifecycle.",
+ "Dispatch only after approval is granted.",
+ "Capture command result or execution error.",
+ "Require Assistant read-after-write verification before final response.",
+ },
+ GeneratedAt: time.Now().UTC(),
+ }
+}
+
+func approvalPlanHash(actionID, requestID, capabilityName, resourceID, command, targetType, targetID, context string) string {
+ sum := sha256.Sum256([]byte(strings.Join([]string{
+ actionID,
+ requestID,
+ capabilityName,
+ strings.TrimSpace(resourceID),
+ command,
+ strings.TrimSpace(targetType),
+ strings.TrimSpace(targetID),
+ strings.TrimSpace(context),
+ }, "|")))
+ return hex.EncodeToString(sum[:])
+}
diff --git a/tests/integration/scripts/approval-store-helper/main_test.go b/tests/integration/scripts/approval-store-helper/main_test.go
new file mode 100644
index 0000000000..56a6a0221c
--- /dev/null
+++ b/tests/integration/scripts/approval-store-helper/main_test.go
@@ -0,0 +1,86 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
+)
+
+func TestRunCreateAndGetPersistsProductShapedApproval(t *testing.T) {
+ dataDir := t.TempDir()
+
+ createArgs := cliArgs{
+ action: "create",
+ approvalID: "approval-1",
+ command: "systemctl restart pulse-relay",
+ context: "Approve the seeded relay restart fix.",
+ dataDir: dataDir,
+ orgID: "org-1",
+ risk: "high",
+ targetID: "relay_123",
+ targetName: "Pulse Relay",
+ targetType: defaultTargetType,
+ timeout: 15 * time.Minute,
+ toolID: "pulse_control",
+ }
+ if err := run(createArgs); err != nil {
+ t.Fatalf("run create: %v", err)
+ }
+
+ approvalsPath := filepath.Join(dataDir, "ai_approvals.json")
+ if _, err := os.Stat(approvalsPath); err != nil {
+ t.Fatalf("approval file was not persisted: %v", err)
+ }
+
+ store, err := approval.NewStore(approval.StoreConfig{DataDir: dataDir})
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ got, ok := store.GetApproval("approval-1")
+ if !ok {
+ t.Fatal("approval was not loaded")
+ }
+ if got.OrgID != "org-1" {
+ t.Fatalf("OrgID = %q, want org-1", got.OrgID)
+ }
+ if got.TargetType != defaultTargetType {
+ t.Fatalf("TargetType = %q, want %q", got.TargetType, defaultTargetType)
+ }
+ if got.CommandHash == "" {
+ t.Fatal("CommandHash was not populated")
+ }
+ if got.Plan == nil || !got.Plan.RequiresApproval || got.Plan.PlanHash == "" {
+ t.Fatalf("approval plan was not populated: %+v", got.Plan)
+ }
+ if got.ContextConfidence == nil || got.ContextConfidence.Level != approval.ContextConfidenceVerified {
+ t.Fatalf("context confidence = %+v, want verified", got.ContextConfidence)
+ }
+ if got.Preflight == nil || got.Preflight.Target != "agent:relay_123" {
+ t.Fatalf("preflight = %+v, want agent:relay_123 target", got.Preflight)
+ }
+
+ getArgs := createArgs
+ getArgs.action = "get"
+ getArgs.command = ""
+ if err := run(getArgs); err != nil {
+ t.Fatalf("run get: %v", err)
+ }
+}
+
+func TestParseArgsRequiresCreateFields(t *testing.T) {
+ defer func() {
+ if recovered := recover(); recovered == nil {
+ t.Fatal("expected usage to exit")
+ }
+ }()
+ oldExit := osExit
+ osExit = func(code int) {
+ panic(code)
+ }
+ defer func() { osExit = oldExit }()
+
+ parseArgs([]string{"create", "--data-dir", t.TempDir(), "--approval-id", "approval-1"})
+}
diff --git a/tests/integration/scripts/hosted-tenant-approval-store.mjs b/tests/integration/scripts/hosted-tenant-approval-store.mjs
index 7d3e4ba052..eb0681c92d 100644
--- a/tests/integration/scripts/hosted-tenant-approval-store.mjs
+++ b/tests/integration/scripts/hosted-tenant-approval-store.mjs
@@ -7,6 +7,7 @@ import path from 'node:path';
import process from 'node:process';
import {
+ assertHostedTenantRuntimeExists,
resolveHostedTenantOrgDataDir,
restartHostedTenantRuntime,
runRemote,
@@ -83,7 +84,7 @@ function buildLocalHelper(tempDir) {
'-buildvcs=false',
'-o',
binaryPath,
- './tests/integration/scripts/approval-store-helper.go',
+ './tests/integration/scripts/approval-store-helper',
], {
cwd: repoRoot,
env: {
@@ -100,6 +101,11 @@ function buildLocalHelper(tempDir) {
function main() {
const args = parseArgs(process.argv.slice(2));
+
+ if (args.action === 'create') {
+ assertHostedTenantRuntimeExists(args.cloudHost, args.tenantId);
+ }
+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulse-hosted-approval-helper-'));
const localBinaryPath = buildLocalHelper(tempDir);
const remoteBinaryPath = `/tmp/approval-store-helper-${process.pid}-${Date.now()}`;
@@ -142,4 +148,9 @@ function main() {
}
}
-main();
+try {
+ main();
+} catch (error) {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+}
diff --git a/tests/integration/scripts/hosted-tenant-runtime-check.mjs b/tests/integration/scripts/hosted-tenant-runtime-check.mjs
new file mode 100644
index 0000000000..584bce69f1
--- /dev/null
+++ b/tests/integration/scripts/hosted-tenant-runtime-check.mjs
@@ -0,0 +1,81 @@
+#!/usr/bin/env node
+
+import process from 'node:process';
+import { pathToFileURL } from 'node:url';
+
+import { assertHostedTenantRuntimeExists } from './hosted-tenant-runtime.mjs';
+
+const DEFAULT_CLOUD_HOST = 'root@pulse-cloud';
+
+function usage(message) {
+ if (message) {
+ console.error(`error: ${message}`);
+ console.error('');
+ }
+
+ console.error(
+ 'usage: node ./tests/integration/scripts/hosted-tenant-runtime-check.mjs --tenant-id <id> [--cloud-host <user@host>]',
+ );
+ process.exit(1);
+}
+
+export function parseArgs(argv) {
+ const parsed = {
+ cloudHost: DEFAULT_CLOUD_HOST,
+ tenantId: '',
+ };
+
+ for (let index = 0; index < argv.length; index += 1) {
+ const arg = argv[index];
+ switch (arg) {
+ case '--cloud-host':
+ parsed.cloudHost = argv[index + 1] ?? usage('missing value for --cloud-host');
+ index += 1;
+ break;
+ case '--tenant-id':
+ parsed.tenantId = argv[index + 1] ?? usage('missing value for --tenant-id');
+ index += 1;
+ break;
+ case '--help':
+ case '-h':
+ usage();
+ break;
+ default:
+ usage(`unsupported flag ${arg}`);
+ }
+ }
+
+ parsed.cloudHost = String(parsed.cloudHost || '').trim();
+ parsed.tenantId = String(parsed.tenantId || '').trim();
+
+ if (!parsed.tenantId) {
+ usage('--tenant-id is required');
+ }
+ if (!parsed.cloudHost) {
+ usage('--cloud-host is required');
+ }
+
+ return parsed;
+}
+
+export function main(argv = process.argv.slice(2)) {
+ const args = parseArgs(argv);
+ const status = assertHostedTenantRuntimeExists(args.cloudHost, args.tenantId).trim();
+ process.stdout.write(`${JSON.stringify({
+ cloudHost: args.cloudHost,
+ status,
+ tenantId: args.tenantId,
+ }, null, 2)}\n`);
+}
+
+const invokedAsScript = process.argv[1]
+ && import.meta.url === pathToFileURL(process.argv[1]).href;
+
+if (invokedAsScript) {
+ try {
+ main();
+ } catch (error) {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+ }
+}
diff --git a/tests/integration/scripts/hosted-tenant-runtime.mjs b/tests/integration/scripts/hosted-tenant-runtime.mjs
index 04c7d33dc0..2ef938557c 100644
--- a/tests/integration/scripts/hosted-tenant-runtime.mjs
+++ b/tests/integration/scripts/hosted-tenant-runtime.mjs
@@ -24,11 +24,64 @@ export function resolveHostedTenantOrgDataDir(tenantId, orgId) {
return `/data/tenants/${tenantId}/orgs/${scopedOrgId}`;
}
-export function restartHostedTenantRuntime(cloudHost, tenantId) {
- const containerName = `pulse-${tenantId}`;
+export function hostedTenantContainerName(tenantId) {
+ const normalizedTenantId = String(tenantId || '').trim();
+ if (!normalizedTenantId) {
+ throw new Error('tenantId is required');
+ }
+ return `pulse-${normalizedTenantId}`;
+}
+
+function remoteFailureOutput(error) {
+ const remoteOutput = ['stderr', 'stdout']
+ .map((field) => error?.[field])
+ .filter((value) => value !== undefined && value !== null && String(value).trim() !== '')
+ .map((value) => String(value).trim())
+ .join('\n');
+ if (remoteOutput) {
+ return remoteOutput;
+ }
+ return String(error?.message || '').trim();
+}
+
+export function hostedTenantRuntimeExistsScript(tenantId) {
+ const containerName = hostedTenantContainerName(tenantId);
+ return `
+set -eu
+container=${shellQuote(containerName)}
+if ! docker inspect "$container" >/dev/null 2>&1; then
+ echo "hosted tenant runtime container $container does not exist" >&2
+ echo "create or restore an active hosted tenant before running hosted mobile proof seeding" >&2
+ exit 72
+fi
+docker inspect --format '{{.Name}} {{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$container"
+`;
+}
+
+export function assertHostedTenantRuntimeExists(cloudHost, tenantId, runner = runRemote) {
+ const containerName = hostedTenantContainerName(tenantId);
+ try {
+ return runner(cloudHost, `sh -lc ${shellQuote(hostedTenantRuntimeExistsScript(tenantId))}`);
+ } catch (error) {
+ const detail = remoteFailureOutput(error);
+ throw new Error([
+ `hosted tenant runtime ${containerName} is unavailable on ${cloudHost}`,
+ 'Hosted mobile proof seeding requires an active hosted tenant container before it mutates approval or token data.',
+ detail,
+ ].filter(Boolean).join('\n'));
+ }
+}
+
+export function restartHostedTenantRuntime(cloudHost, tenantId, runner = runRemote) {
+ const containerName = hostedTenantContainerName(tenantId);
const script = `
set -eu
container=${shellQuote(containerName)}
+if ! docker inspect "$container" >/dev/null 2>&1; then
+ echo "hosted tenant runtime container $container does not exist" >&2
+ echo "create or restore an active hosted tenant before restarting hosted mobile proof state" >&2
+ exit 72
+fi
docker restart "$container" >/dev/null
deadline=$(( $(date +%s) + 60 ))
while [ "$(date +%s)" -lt "$deadline" ]; do
@@ -44,5 +97,13 @@ echo "timed out waiting for $container to become ready" >&2
docker inspect --format '{{json .State}}' "$container" >&2 || true
exit 1
`;
- runRemote(cloudHost, `sh -lc ${shellQuote(script)}`);
+ try {
+ runner(cloudHost, `sh -lc ${shellQuote(script)}`);
+ } catch (error) {
+ const detail = remoteFailureOutput(error);
+ throw new Error([
+ `failed to restart hosted tenant runtime ${containerName} on ${cloudHost}`,
+ detail,
+ ].filter(Boolean).join('\n'));
+ }
}
diff --git a/tests/integration/scripts/hosted-tenant-runtime.test.mjs b/tests/integration/scripts/hosted-tenant-runtime.test.mjs
new file mode 100644
index 0000000000..5b3a663014
--- /dev/null
+++ b/tests/integration/scripts/hosted-tenant-runtime.test.mjs
@@ -0,0 +1,79 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import {
+ assertHostedTenantRuntimeExists,
+ hostedTenantContainerName,
+ hostedTenantRuntimeExistsScript,
+ restartHostedTenantRuntime,
+} from './hosted-tenant-runtime.mjs';
+import { parseArgs as parseRuntimeCheckArgs } from './hosted-tenant-runtime-check.mjs';
+
+test('hostedTenantContainerName derives the canonical runtime container name', () => {
+ assert.equal(hostedTenantContainerName(' t-P62TP8K28Y '), 'pulse-t-P62TP8K28Y');
+});
+
+test('hostedTenantRuntimeExistsScript checks for the tenant container before reporting state', () => {
+ const script = hostedTenantRuntimeExistsScript('t-P62TP8K28Y');
+
+ assert.match(script, /docker inspect "\$container" >\/dev\/null 2>&1/);
+ assert.match(script, /hosted tenant runtime container \$container does not exist/);
+ assert.match(script, /docker inspect --format/);
+});
+
+test('assertHostedTenantRuntimeExists wraps missing runtime failures with proof guidance', () => {
+ const calls = [];
+ const runner = (host, command) => {
+ calls.push({ command, host });
+ const error = new Error('ssh failed');
+ error.stderr = 'hosted tenant runtime container pulse-t-missing does not exist';
+ throw error;
+ };
+
+ assert.throws(
+ () => assertHostedTenantRuntimeExists('root@pulse-cloud', 't-missing', runner),
+ /Hosted mobile proof seeding requires an active hosted tenant container/,
+ );
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].host, 'root@pulse-cloud');
+ assert.match(calls[0].command, /docker inspect/);
+});
+
+test('assertHostedTenantRuntimeExists prefers remote stderr over noisy ssh command text', () => {
+ const runner = () => {
+ const error = new Error('Command failed: ssh root@pulse-cloud sh -lc very-long-command');
+ error.stderr = 'hosted tenant runtime container pulse-t-missing does not exist';
+ throw error;
+ };
+
+ assert.throws(
+ () => assertHostedTenantRuntimeExists('root@pulse-cloud', 't-missing', runner),
+ (error) => {
+ assert.match(error.message, /hosted tenant runtime container pulse-t-missing does not exist/);
+ assert.doesNotMatch(error.message, /very-long-command/);
+ return true;
+ },
+ );
+});
+
+test('restartHostedTenantRuntime checks runtime existence before restart', () => {
+ const calls = [];
+ const runner = (host, command) => {
+ calls.push({ command, host });
+ return '';
+ };
+
+ restartHostedTenantRuntime('root@pulse-cloud', 't-P62TP8K28Y', runner);
+
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].host, 'root@pulse-cloud');
+ assert.match(calls[0].command, /docker inspect/);
+ assert.match(calls[0].command, /docker restart/);
+});
+
+test('hosted tenant runtime check CLI defaults to the production cloud host', () => {
+ const parsed = parseRuntimeCheckArgs(['--tenant-id', 't-canary']);
+
+ assert.equal(parsed.cloudHost, 'root@pulse-cloud');
+ assert.equal(parsed.tenantId, 't-canary');
+});