Sol review (org-redact5, changes 6): - org-service: Node filesystem errors become "cannot <syscall> <label> (<CODE>)"; code, syscall, deleteStep and deleteReceipt stay. git failures name the verb and exit code, never git's stderr. - org-console: consoleStop names "another checkout", not the entry path. Exit 3. - config-command: the system config is named by where it came from. Exit 3. - cli org: documents and raw fs errors are named by kind and code. Exit 2. - instances: --vars file named by flag and kind. Exit 4. - hosts: a refused command is named by the basename refusedCommand matched. - role.mjs (T1): the change is back to the readJsonFile label only. Sentinel tests for each; pins in last-values, rename-b-commands, org-recovery.
190 lines
9.3 KiB
JavaScript
190 lines
9.3 KiB
JavaScript
// The installed organization config commands, as one callable service:
|
|
// validate ID the installed loader, every role definition it uses, the
|
|
// project files under its declared roots, and a stat check
|
|
// of every credential reference
|
|
// resolve ID INSTANCE [--project ID] one role instance's resolved record
|
|
// Both print JSON on stdout and problems on stderr. The v1 serialization (the `business` key,
|
|
// `business:` provenance, the canonical preimage and digest) is the stage A contract; it does not
|
|
// change with the spelling.
|
|
//
|
|
// Rename design r2, stage B: `mosaic business validate|resolve` (src/cli.mjs, and the old
|
|
// packages/business/src/cli.mjs path that forwards to it) and `mosaic org config validate|resolve`
|
|
// (packages/cli/src/cli.mjs) both call runConfigCommand. It never exits the process or runs on
|
|
// import: it writes to the streams it is given and returns the exit code. A spelling sets only the
|
|
// usage line (its prefix and text). Status, stdout and every other stderr line, refusals and
|
|
// warnings included, are byte for byte the same for both: they keep the `mosaic business: ` prefix
|
|
// so a caller moving to the new spelling keeps the diagnostic contract.
|
|
//
|
|
// Exit codes: 0 ok; 2 invalid (organization, role, project file or a credential reference);
|
|
// 3 system config problem; 4 usage, or a required file missing.
|
|
|
|
import { spawnSync } from "node:child_process";
|
|
import { existsSync } from "node:fs";
|
|
import { dirname, join, resolve } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { OrganizationConfigError } from "./errors.mjs";
|
|
import { configDir, loadOrganization } from "./organization-config.mjs";
|
|
import { loadProject, projectFilePath } from "./project.mjs";
|
|
import { checkCredentialRef } from "./credentials.mjs";
|
|
import { systemVars, resolveInstance } from "./resolve.mjs";
|
|
|
|
const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
|
|
|
|
// The old spelling's prefix and usage are byte for byte what `mosaic business` printed before stage B.
|
|
export const BUSINESS_CONFIG = Object.freeze({
|
|
prefix: "mosaic business",
|
|
usage: "usage: mosaic business validate <business> | resolve <business> <instance> [--project <id>]",
|
|
});
|
|
export const ORG_CONFIG = Object.freeze({
|
|
prefix: "mosaic org config",
|
|
usage: "usage: mosaic org config validate ID | resolve ID INSTANCE [--project ID]",
|
|
});
|
|
|
|
// Thrown after the message is written; runConfigCommand turns it into the exit code.
|
|
class Exit {
|
|
constructor(code) {
|
|
this.code = code;
|
|
}
|
|
}
|
|
|
|
// argv is [verb, ...args]. Returns the exit code. An error that is not an OrganizationConfigError
|
|
// (a bug, not a refusal) is thrown to the caller, as the old executable let it escape.
|
|
export function runConfigCommand(argv, { stdout = process.stdout, stderr = process.stderr, env = process.env, spelling = BUSINESS_CONFIG } = {}) {
|
|
// Diagnostics keep the old prefix in both spellings; only the usage line follows the spelling.
|
|
const say = (message) => stderr.write(`${BUSINESS_CONFIG.prefix}: ${message}\n`);
|
|
const usage = () => {
|
|
stderr.write(`${spelling.prefix}: ${spelling.usage}\n`);
|
|
throw new Exit(4);
|
|
};
|
|
const fail = (code, message) => {
|
|
say(message);
|
|
throw new Exit(code);
|
|
};
|
|
|
|
const loadSystem = () => {
|
|
const proc = spawnSync(process.execPath, [join(REPO, "scripts", "mosaic-config.mjs"), "validate"], {
|
|
encoding: "utf8",
|
|
maxBuffer: 1024 * 1024,
|
|
env,
|
|
});
|
|
// Render known key paths with fixed constraints; never relay child stderr.
|
|
if (proc.status !== 0) {
|
|
const problem = proc.stderr.trim();
|
|
const field = problem.startsWith('mosaic-config: execution "dataRoot"') ? "dataRoot"
|
|
: /^mosaic-config: (?:unsupported )?"?((?:configVersion|environment|dataRoot|execution|console|federation|compactionReadBytes|compactionStreams)(?:\.[A-Za-z][A-Za-z0-9]*|\[\d+\])*)"?(?=[: ])/u.exec(problem)?.[1];
|
|
const name = "a 1-200 character name starting with a letter or digit and containing only letters, digits, . _ : / -";
|
|
const expected = { configVersion: "1", environment: "development or production", dataRoot: "a canonical absolute instance data path",
|
|
"execution.backend": "docker", "execution.adapter": "pi or mock", "execution.provider": name, "execution.model": name };
|
|
const detail = problem.startsWith("mosaic-config: configuration is not valid JSON (")
|
|
? "configuration is not valid JSON; expected readable JSON: "
|
|
: field ? `${field}: expected ${expected[field] ?? "a value satisfying the system configuration schema"}: `
|
|
: "expected valid system configuration: ";
|
|
// Name the config by where it came from, never by host path (PR #1916).
|
|
fail(3, `system config problem (mosaic-config exit ${proc.status}): ${detail}${env.MOSAIC_CONFIG ? "the system config MOSAIC_CONFIG names" : "the default system config"}${proc.error?.code ? ` (${proc.error.code})` : ""}`);
|
|
}
|
|
try {
|
|
return JSON.parse(proc.stdout);
|
|
} catch {
|
|
fail(3, "system config: mosaic-config printed something that isn't JSON");
|
|
}
|
|
};
|
|
const load = (id) => loadOrganization(id, { dir: configDir(env), rolesDir: resolve(env.MOSAIC_ROLES_DIR || join(REPO, "roles")) });
|
|
|
|
// Check credential references; return the problems and warnings.
|
|
const checkRefs = (refs, forbiddenRoots) => {
|
|
const problems = [];
|
|
const warnings = [];
|
|
for (const ref of refs) {
|
|
const result = checkCredentialRef(ref, { forbiddenRoots, env });
|
|
problems.push(...result.problems);
|
|
warnings.push(...result.warnings);
|
|
}
|
|
return { problems, warnings };
|
|
};
|
|
const forbiddenRoots = (config, organization) =>
|
|
[REPO, config.dataRoot, ...Object.values(organization.projects).filter((p) => p.kind !== "library").map((p) => p.root)];
|
|
|
|
const validate = (args) => {
|
|
if (args.length !== 1) usage();
|
|
const config = loadSystem();
|
|
const system = systemVars(config);
|
|
const organization = load(args[0]);
|
|
const projects = {};
|
|
const warnings = [];
|
|
for (const [id, entry] of Object.entries(organization.projects)) {
|
|
if (entry.kind === "library") { projects[id] = "library"; continue; }
|
|
const file = projectFilePath(entry.root);
|
|
if (!existsSync(file)) {
|
|
projects[id] = "absent";
|
|
warnings.push(`project ${id}: no project file at ${file}; it has no project variables`);
|
|
continue;
|
|
}
|
|
const project = loadProject(entry.root);
|
|
if (project.id !== id) fail(2, `project file of project ${id} has id that does not match the declared project key`);
|
|
for (const instance of Object.keys(organization.roles)) resolveInstance({ system, business: organization, project, instance });
|
|
projects[id] = "valid";
|
|
}
|
|
const refs = [
|
|
...Object.values(organization.tracker?.sync?.credentials ?? {}),
|
|
...Object.values(organization.roles).flatMap((r) => Object.values(r.credentials)),
|
|
];
|
|
const checked = checkRefs(refs, forbiddenRoots(config, organization));
|
|
warnings.push(...checked.warnings);
|
|
const instances = {};
|
|
for (const instance of Object.keys(organization.roles)) {
|
|
instances[instance] = resolveInstance({ system, business: organization, instance }).digest;
|
|
}
|
|
for (const w of warnings) say(`warning: ${w}`);
|
|
if (checked.problems.length > 0) {
|
|
for (const p of checked.problems) say(p);
|
|
fail(2, `business ${organization.id}: ${checked.problems.length} credential reference problem(s)`);
|
|
}
|
|
// v1 output: the key stays `business`.
|
|
stdout.write(`${JSON.stringify({ business: organization.id, file: organization.file, projects, instances }, null, 2)}\n`);
|
|
};
|
|
|
|
const resolveCommand = (args) => {
|
|
let project = null;
|
|
const rest = [];
|
|
for (let i = 0; i < args.length; i++) {
|
|
if (args[i] === "--project") {
|
|
if (!args[i + 1] || project !== null) usage();
|
|
project = args[++i];
|
|
} else rest.push(args[i]);
|
|
}
|
|
if (rest.length !== 2) usage();
|
|
const [organizationId, instance] = rest;
|
|
const config = loadSystem();
|
|
const organization = load(organizationId);
|
|
let loaded = null;
|
|
if (project !== null) {
|
|
const entry = Object.hasOwn(organization.projects, project) ? organization.projects[project] : null;
|
|
if (!entry) fail(2, `business ${organization.id} declares no project ${JSON.stringify(project)}`);
|
|
if (entry.kind !== "library") loaded = loadProject(entry.root);
|
|
}
|
|
const resolved = resolveInstance({ system: systemVars(config), business: organization, project: loaded, instance });
|
|
const checked = checkRefs(Object.values(resolved.credentials), forbiddenRoots(config, organization));
|
|
for (const w of checked.warnings) say(`warning: ${w}`);
|
|
if (checked.problems.length > 0) {
|
|
for (const p of checked.problems) say(p);
|
|
fail(2, `${organization.id} ${instance}: ${checked.problems.length} credential reference problem(s)`);
|
|
}
|
|
stdout.write(`${JSON.stringify(resolved, null, 2)}\n`);
|
|
};
|
|
|
|
const [verb, ...args] = argv;
|
|
try {
|
|
if (verb === "validate") validate(args);
|
|
else if (verb === "resolve") resolveCommand(args);
|
|
else usage();
|
|
return 0;
|
|
} catch (error) {
|
|
if (error instanceof Exit) return error.code;
|
|
if (error instanceof OrganizationConfigError) {
|
|
say(error.message);
|
|
return error.exitCode;
|
|
}
|
|
throw error;
|
|
}
|
|
}
|