diff --git a/.changeset/answers-are-read-by-their-shape.md b/.changeset/answers-are-read-by-their-shape.md new file mode 100644 index 000000000..3d1c54e57 --- /dev/null +++ b/.changeset/answers-are-read-by-their-shape.md @@ -0,0 +1,8 @@ +--- +"@fnndsc/menu": minor +"@fnndsc/argus": patch +--- + +ARGUS reads listings, a feed's access and tags, runs and games by their shape, keeping the good rows of a mixed answer. + +Eleven places took an answer's model as whatever they expected it to be. Each now reads it through a schema in `@fnndsc/menu` (`fsListings_read`, `elements_read` and the shapes beside them), element by element where a list is read: a malformed block, entry or row is left out and named, the rest kept, and an answer of the wrong shape reads as none instead of failing later. diff --git a/.changeset/what-is-read-is-read-whole.md b/.changeset/what-is-read-is-read-whole.md new file mode 100644 index 000000000..ee75ac079 --- /dev/null +++ b/.changeset/what-is-read-is-read-whole.md @@ -0,0 +1,11 @@ +--- +"@fnndsc/stratus": minor +"@fnndsc/menu": minor +"@fnndsc/argus": patch +--- + +What stratus and ARGUS read is read whole before it is acted on, and nothing unread is said as nothing. + +stratus: a VM's keep is refused unless its deploy record and declaration read by every field adoption uses (a list or a bare object no longer passes), naming the field; a kept record is read by the fields its store uses and must name itself (`KeptFolders` and `SpecStore` take the record's schema); kept documents keep the fields they were not read for through a read and a merge; a Red Hat cluster list or GoDaddy record list with a row that could be the asked name and does not read is refused before anything is changed; a Red Hat refusal is worded by its reason alone, never the rest of the answer; a smoke verdict's null timing reads; a kept verify that does not read is said as kept and unreadable, not as none; and the Kubernetes and Resource Manager JSON answers are parsed by name, refused without quoting. + +menu and ARGUS: an ACL block reads only with its users, groups and public access (`fsAclBlockSchema`), and a feed whose access does not read shows ACCESS UNREAD, never shared with nobody; a listing carries whether it is fresh, what was unread and what was left out, and a listing of which nothing reads no longer hides the next; a showpiece reads only with its program (`gamesShowSchema`, `GamesShow`), and only what read is shown. diff --git a/.changeset/what-stratus-reads-is-read-by-shape.md b/.changeset/what-stratus-reads-is-read-by-shape.md new file mode 100644 index 000000000..bda2f5190 --- /dev/null +++ b/.changeset/what-stratus-reads-is-read-by-shape.md @@ -0,0 +1,7 @@ +--- +"@fnndsc/stratus": patch +--- + +A malformed plan, keep, verify, manifest list or Red Hat answer is refused by name, never cast and failing later. + +Every document stratus did not write itself (a plan kept on this host, a keep in the tenancy's vault, the last verify, the platform manifests, ChRIS's secrets, a Terraform state, Red Hat's and GoDaddy's answers, what a program on a VM printed) is now read through a schema in the module that owns it, naming only the fields read and keeping the rest. One that does not read is refused naming the document and the field, never quoting it; a list of hosts, manifests or records is read row by row, a malformed row left out; and the nulls Red Hat answers for a new cluster (no status words, no progress yet) read as absent. A `state.json` kept here that is no JSON object naming what it keeps is refused by its file, never quoted. stratus now depends on zod. diff --git a/apps/argus/src/app/access.ts b/apps/argus/src/app/access.ts index 5902bf7f8..66f9ee277 100644 --- a/apps/argus/src/app/access.ts +++ b/apps/argus/src/app/access.ts @@ -14,7 +14,7 @@ * user and what to refresh once something changed. */ import type { WireEnvelope } from '@fnndsc/menu'; -import { arg_quote, POSIX_IDENTITY_MODEL_KIND, posixIdentityModelSchema, type PosixGroup } from '@fnndsc/menu'; +import { ANSWER_MODEL_KINDS, arg_quote, elements_read, fsAclBlockSchema, POSIX_IDENTITY_MODEL_KIND, posixIdentityModelSchema, type PosixGroup } from '@fnndsc/menu'; import type { ExecuteOutcome } from '../calypso/client.js'; import type { PaneAskChoice, PaneAskRequest } from '../features/ask/paneAsk.js'; @@ -59,10 +59,12 @@ export interface AccessVerbs { */ export function holders_extract(outcome: ExecuteOutcome): FeedHolders | null { for (const envelope of outcome.envelopes as ReadonlyArray) { - if (envelope.model?.kind !== 'fs.acl') continue; - const block = (envelope.model.data as Array<{ usernames?: string[]; groups?: string[]; public?: boolean }>)[0]; - if (block === undefined) return null; - return { users: block.usernames ?? [], groups: block.groups ?? [], public: block.public === true }; + if (envelope.model?.kind !== ANSWER_MODEL_KINDS.fsAcl) continue; + // Read by shape: the feed's block, or none (unread, never nobody) when any block does not read. + const read = elements_read(envelope.model.data, fsAclBlockSchema); + const block = read.kept[0]; + if (block === undefined || read.skipped.length > 0) return null; + return { users: block.usernames, groups: block.groups, public: block.public }; } return null; } diff --git a/apps/argus/src/app/cycler.ts b/apps/argus/src/app/cycler.ts index 38f52bb38..ae3fa94c3 100644 --- a/apps/argus/src/app/cycler.ts +++ b/apps/argus/src/app/cycler.ts @@ -11,8 +11,8 @@ */ import { pipelineDiagramModelSchema, DAG_MODEL_KINDS, type PipelineDiagramModel, type PipelineDiagramNode, type WireEnvelope, arg_quote } from '@fnndsc/menu'; +import { answerListings_extract, type Listed } from '../calypso/answerModel.js'; import type { ArgusClient, ExecuteOutcome } from '../calypso/client.js'; -import type { FsListing } from '../features/files/entries.js'; import { ChrisSpace, type SceneNode } from '../scene/chrisSpace.js'; /** How long each pipeline holds the stage. */ @@ -139,12 +139,8 @@ export class PipelineCycler { */ export function cyclerNames_seed(client: Pick, cycler: Pick): void { void client.line_execute('ls /bin', { silent: true, observe: false }).then((outcome: ExecuteOutcome): void => { - const listing: WireEnvelope | undefined = outcome.envelopes.find( - (envelope: WireEnvelope): boolean => envelope.model?.kind === 'fs.listing', - ); - const data: FsListing[] | undefined = listing?.model?.data as FsListing[] | undefined; - const names: string[] = (data ?? []) - .flatMap((entry: FsListing) => entry.items) + const names: string[] = answerListings_extract(outcome) + .flatMap((entry: Listed) => entry.items) .filter((item): boolean => item.type === 'pipeline') .map((item): string => item.name); cycler.names_set(names); diff --git a/apps/argus/src/app/dashboardTiles.ts b/apps/argus/src/app/dashboardTiles.ts index d1c6a4f99..7eeb5267f 100644 --- a/apps/argus/src/app/dashboardTiles.ts +++ b/apps/argus/src/app/dashboardTiles.ts @@ -8,9 +8,9 @@ import type { SessionNotes } from '@fnndsc/menu'; import type { GroupSnapshot } from './dormant.js'; +import { answerListings_extract, type Listed } from '../calypso/answerModel.js'; import type { ExecuteOutcome } from '../calypso/client.js'; import { DRAWER_CHORDS, VERB_LINES, type DrawerChord } from '../console/argusLang.js'; -import type { FsListingEntry } from '../features/files/entries.js'; import { TILE_ABOUT, type TileAbout } from '../features/launcher/about.js'; import type { LauncherRow, LauncherTile } from '../features/launcher/panel.js'; @@ -62,24 +62,17 @@ export function dashboardTiles_build(hooks: DashboardHooks): () => Promise; - const first = listings[0]; - if (first !== undefined && Array.isArray(first.items)) { - entries = first.items as FsListingEntry[]; - if (typeof first.path === 'string') homePath = first.path; - } - } - const folders: FsListingEntry[] = entries.filter((entry: FsListingEntry): boolean => entry.type === 'dir'); + // The home listing read by shape: a malformed entry is left out, never cast. + const first: Listed | undefined = answerListings_extract(home)[0]; + const entries: Listed['items'] = first?.items ?? []; + const homePath: string = first?.path ?? '~'; + const folders: Listed['items'] = entries.filter((entry): boolean => entry.type === 'dir'); const desktops: GroupSnapshot[] = hooks.desktops(); const files: LauncherTile = { key: 'files', name: 'FILES', hue: '--harvestgold', numeral: '2', figures: [{ text: `${entries.length} ENTRIES` }], - rows: folders.slice(0, 5).map((entry: FsListingEntry): LauncherRow => ({ + rows: folders.slice(0, 5).map((entry): LauncherRow => ({ text: entry.name, open: (): void => hooks.home_cd(homePath.endsWith('/') ? `${homePath}${entry.name}` : `${homePath}/${entry.name}`), })), diff --git a/apps/argus/src/app/feedRows.ts b/apps/argus/src/app/feedRows.ts index 434200c87..e23cd505a 100644 --- a/apps/argus/src/app/feedRows.ts +++ b/apps/argus/src/app/feedRows.ts @@ -15,7 +15,7 @@ * A module of the host: the host builds the feed verbs once * (`feedVerbs_wire`) and hands them to every roster. */ -import { ansi_strip, type FeedListEntry } from '@fnndsc/menu'; +import { ansi_strip, ANSWER_MODEL_KINDS, elements_read, fsXattrBlockSchema, type FeedListEntry } from '@fnndsc/menu'; import type { ExecuteOutcome } from '../calypso/client.js'; import type { ListingAction } from '../features/roster/row.js'; @@ -63,9 +63,9 @@ export interface FeedRowHandlers { */ export function feedTags_extract(outcome: ExecuteOutcome): string[] { for (const envelope of outcome.envelopes) { - if (envelope.model?.kind !== 'fs.xattr') continue; - const blocks = envelope.model.data as Array<{ tags?: unknown }>; - return (blocks[0]?.tags as string[] | undefined) ?? []; + if (envelope.model?.kind !== ANSWER_MODEL_KINDS.fsXattr) continue; + // Read by shape: the feed's block's tags, or none when it does not read. + return [...(elements_read(envelope.model.data, fsXattrBlockSchema).kept[0]?.tags ?? [])]; } return []; } diff --git a/apps/argus/src/app/gamesPane.ts b/apps/argus/src/app/gamesPane.ts index aa2ac8bb1..6b725406d 100644 --- a/apps/argus/src/app/gamesPane.ts +++ b/apps/argus/src/app/gamesPane.ts @@ -6,6 +6,8 @@ * A module of the host, shaped as the HELP pane's: the host hands in its * spawn and placement verbs. */ +import type { GamesShow } from '@fnndsc/menu'; + import { GamesPanel, program_isName } from '../features/games/panel.js'; import type { HostContext } from './hostContext.js'; import type { HelpPaneHooks } from './helpPane.js'; @@ -16,7 +18,7 @@ export interface GamesPaneModule { /** Builds one GAMES pane. */ instance_build: (id: string) => PaneInstance; /** Runs a program the kernel named, on the GAMES pane on stage or a new one beside the focused pane; returns what happened, for the console. */ - show: (data: unknown) => string; + show: (data: GamesShow) => string; } /** @@ -45,9 +47,9 @@ export function gamesPane_wire(context: Pick { - const program: unknown = typeof data === 'object' && data !== null ? (data as { program?: unknown }).program : undefined; - if (typeof program !== 'string' || !program_isName(program)) return `games: no program named ${String(program)}`; + const show = (data: GamesShow): string => { + const program: string = data.program; + if (!program_isName(program)) return `games: no program named ${program}`; const standing: string | undefined = panels.ids('games').find((id: string): boolean => layout.panes_shown().includes(id)); if (standing !== undefined) { layout.focus_set(standing); diff --git a/apps/argus/src/app/surfaceHost.ts b/apps/argus/src/app/surfaceHost.ts index 097e5dab9..bb79f7550 100644 --- a/apps/argus/src/app/surfaceHost.ts +++ b/apps/argus/src/app/surfaceHost.ts @@ -13,7 +13,7 @@ * * @module */ -import { ansi_strip, type WireEnvelope } from '@fnndsc/menu'; +import { ansi_strip, ANSWER_MODEL_KINDS, elements_read, pluginInstanceRowSchema, runScheduledSchema, type WireEnvelope } from '@fnndsc/menu'; import { binView_wire } from './binView.js'; import { browser_wire } from './browser.js'; @@ -341,10 +341,10 @@ export function surfaceRecents_wire(s: Pick { const names: string[] = []; for (const envelope of outcome.envelopes) { - if (envelope.model?.kind !== 'plugininstance.list' || !Array.isArray(envelope.model.data)) continue; - for (const row of envelope.model.data as Array<{ pluginName?: unknown; pluginVersion?: unknown; owner?: unknown }>) { - if (typeof row.pluginName !== 'string' || typeof row.pluginVersion !== 'string') continue; - if (s.promptUser !== null && typeof row.owner === 'string' && row.owner !== s.promptUser) continue; + if (envelope.model?.kind !== ANSWER_MODEL_KINDS.pluginInstanceList) continue; + // Row by row, by shape: a row without a plugin's name and version is left out, the rest kept. + for (const row of elements_read(envelope.model.data, pluginInstanceRowSchema).kept) { + if (s.promptUser !== null && row.owner !== undefined && row.owner !== s.promptUser) continue; if (row.pluginName === 'pl-dircopy') continue; const name: string = `${row.pluginName}-v${row.pluginVersion}`; if (!names.includes(name)) names.push(name); @@ -450,9 +450,9 @@ export function surfaceRun_wire(s: Pick envelope.model?.kind === 'run.scheduled' || envelope.model?.kind === 'pipeline.scheduled', ); - const data: { feedId?: unknown } | undefined = scheduled?.model?.data as { feedId?: unknown } | undefined; - if (typeof data?.feedId === 'number') { - panel.run_show(data.feedId); + const landed = runScheduledSchema.safeParse(scheduled?.model?.data); + if (landed.success) { + panel.run_show(landed.data.feedId); return; } const refusal: string = ansi_strip(outcome.envelopes diff --git a/apps/argus/src/app/surfaceSession.ts b/apps/argus/src/app/surfaceSession.ts index f6d1f91e7..86402f5f4 100644 --- a/apps/argus/src/app/surfaceSession.ts +++ b/apps/argus/src/app/surfaceSession.ts @@ -14,6 +14,7 @@ * @module */ import type { ClosingCause, PromptContext, WireEnvelope, WatchState, LaneTelemetry, CubeTelemetry, JobsStateTelemetry } from '@fnndsc/menu'; +import { gamesChimeSchema, gamesShowSchema } from '@fnndsc/menu'; import { buildMatch_wire } from './buildMatch.js'; import { consoleZoom_set, consoleZoomSet_install, consoleZoom_toggle, drawer_wire, zoom_wire } from './consoleDrawer.js'; @@ -76,8 +77,10 @@ export function surfaceInstruments_wire(s: Pick { // A chime (timer, leave): noted in the console, and spoken. if (envelope.model?.kind === 'games.chime') { - const text: unknown = (envelope.model.data as { text?: unknown } | null)?.text; - if (typeof text === 'string') { s.terminal.line_note(`🔔 ${text}`); voice_say({ text }); } + const chime = gamesChimeSchema.safeParse(envelope.model.data); + if (chime.success) { s.terminal.line_note(`🔔 ${chime.data.text}`); voice_say({ text: chime.data.text }); } return; } // A task's end, or a joblet's (`[1]+ Done pull …`), or a joblet diff --git a/apps/argus/src/app/tags.ts b/apps/argus/src/app/tags.ts index fd6ee081e..63df99883 100644 --- a/apps/argus/src/app/tags.ts +++ b/apps/argus/src/app/tags.ts @@ -11,8 +11,8 @@ * A module of the host: the host hands in the pane question and a way to * show the roster again once a tag changed. */ -import type { WireEnvelope } from '@fnndsc/menu'; import { arg_quote } from '@fnndsc/menu'; +import { answerListings_extract } from '../calypso/answerModel.js'; import type { ExecuteOutcome } from '../calypso/client.js'; import type { PaneAskChoice, PaneAskRequest } from '../features/ask/paneAsk.js'; import type { HostContext } from './hostContext.js'; @@ -41,12 +41,7 @@ export interface TagVerbs { * @returns The names, in the kernel's order. */ export function tagNames_extract(outcome: ExecuteOutcome): string[] { - for (const envelope of outcome.envelopes as ReadonlyArray) { - if (envelope.model?.kind !== 'fs.listing') continue; - const listings = envelope.model.data as Array<{ items?: Array<{ name?: unknown }> }>; - return (listings[0]?.items ?? []).map((item): string => String(item.name ?? '')).filter((name: string): boolean => name !== ''); - } - return []; + return (answerListings_extract(outcome)[0]?.items ?? []).map((item): string => item.name).filter((name: string): boolean => name !== ''); } /** diff --git a/apps/argus/src/app/trekBridge.ts b/apps/argus/src/app/trekBridge.ts index b92186227..dce35b043 100644 --- a/apps/argus/src/app/trekBridge.ts +++ b/apps/argus/src/app/trekBridge.ts @@ -12,6 +12,8 @@ * A module of the host, shaped as the GAMES pane's: the host hands in its * context and reads the bridge's verbs. */ +import { gamesTrekSchema } from '@fnndsc/menu'; + import type { SurfaceAsk } from '../calypso/client.js'; import { TrekBridge } from '../features/trek/bridge.js'; import type { BridgeVoice, CueName } from '../features/trek/cues.js'; @@ -102,7 +104,8 @@ export function trekBridge_wire(context: Pick): TrekBridg // The operator's own command, never instrument traffic: the daemon lets it ask its questions. const outcome = await context.client.line_execute(line, { operator: true }); const ended = outcome.envelopes.find((envelope) => envelope.model?.kind === 'games.trek'); - opened.harness_get().end(typeof (ended?.model?.data as { exit?: number } | undefined)?.exit === 'number' ? (ended?.model?.data as { exit: number }).exit : 0); + // How the game ended, read by shape; an end that does not read is a clean one, as before. + opened.harness_get().end(gamesTrekSchema.safeParse(ended?.model?.data).data?.exit ?? 0); } catch { opened.harness_get().end(1); } finally { diff --git a/apps/argus/src/calypso/answerModel.ts b/apps/argus/src/calypso/answerModel.ts index 3d9eb002f..3697cba37 100644 --- a/apps/argus/src/calypso/answerModel.ts +++ b/apps/argus/src/calypso/answerModel.ts @@ -22,7 +22,7 @@ * @module */ -import { ansi_strip } from '@fnndsc/menu'; +import { ansi_strip, ANSWER_MODEL_KINDS, fsListings_read } from '@fnndsc/menu'; /** * An answer as these readings see it: its envelopes, each with what it rendered and the model it carries. @@ -50,6 +50,12 @@ export interface Listed { readonly path: string; /** What it holds. */ readonly items: ReadonlyArray<{ name: string; type: string; status?: string; title?: string }>; + /** Whether it was read afresh, when the listing says. */ + readonly fresh?: boolean; + /** What of the folder could not be read, when a partial read kept the rest. */ + readonly unread?: string; + /** Its entries left out for not reading, as `#: why`. */ + readonly skipped?: ReadonlyArray; } /** @@ -105,7 +111,10 @@ export function answerModel_extract(answer: AnswerEnvelopes, kind: string, pa } /** - * The listings an `ls` answered. + * The listings an `ls` answered, each block and entry read by shape + * (`fsListings_read`): a malformed block or entry is left out, every other + * one kept, each block carrying its freshness, what of it went unread and + * the entries left out. A listing of which no block reads is passed over. * * @param answer - The answer. * @returns Them, or none. @@ -117,8 +126,11 @@ export function answerModel_extract(answer: AnswerEnvelopes, kind: string, pa */ export function answerListings_extract(answer: AnswerEnvelopes): Listed[] { for (const envelope of answer.envelopes) { - if (envelope.model?.kind !== 'fs.listing' || !Array.isArray(envelope.model.data)) continue; - return (envelope.model.data as unknown[]).filter((one: unknown): one is Listed => typeof one === 'object' && one !== null && typeof (one as { path?: unknown }).path === 'string' && Array.isArray((one as { items?: unknown }).items)); + if (envelope.model?.kind !== ANSWER_MODEL_KINDS.fsListing) continue; + const read = fsListings_read(envelope.model.data); + // A listing none of whose blocks reads is passed over for a later one, as a model of the wrong shape is. + if (read.blocks.length === 0 && read.skipped.length > 0) continue; + return read.blocks.slice(); } return []; } diff --git a/apps/argus/tests/unit/dashboardTiles.test.ts b/apps/argus/tests/unit/dashboardTiles.test.ts index 89c63b9e9..3384881aa 100644 --- a/apps/argus/tests/unit/dashboardTiles.test.ts +++ b/apps/argus/tests/unit/dashboardTiles.test.ts @@ -37,6 +37,14 @@ describe('the dashboard tiles', () => { expect(keys(await dashboardTiles_build(hooks(30, contribution(10)))())).toEqual(['files', 'analyses', 'pacs', 'panes', 'universe', 'help', 'notes', 'console']); }); + it('reads home by shape: a malformed entry is left out, a model of the wrong shape is no listing, never a throw', async () => { + const answer = (data: unknown) => async (): Promise => ({ envelopes: [{ status: 'ok', rendered: '', model: { kind: 'fs.listing', data } }] } as unknown as ExecuteOutcome); + const figure = async (data: unknown): Promise => (await dashboardTiles_build({ ...hooks(0), ask: answer(data) })()).find((t) => t.key === 'files')?.figures[0]?.text; + expect(await figure([{ path: '/home/u', items: [{ name: 'a', type: 'dir' }, { name: 7, type: 'dir' }, { name: 'b', type: 'file' }] }])).toBe('2 ENTRIES'); + expect(await figure(null)).toBe('0 ENTRIES'); + expect(await figure([{ path: '/home/u', items: 'nonsense' }])).toBe('0 ENTRIES'); + }); + it('lets a composition say what FILES holds, and says something neutral without one', async () => { const alone = await dashboardTiles_build(hooks(3))(); expect(alone.find((t) => t.key === 'files')?.about.text).toBe('Your home: the files this session holds.'); diff --git a/apps/argus/tests/unit/feedTags.test.ts b/apps/argus/tests/unit/feedTags.test.ts index efd1fd182..8aad74d06 100644 --- a/apps/argus/tests/unit/feedTags.test.ts +++ b/apps/argus/tests/unit/feedTags.test.ts @@ -24,7 +24,7 @@ describe('the lines a tag is hung by', () => { }); it('reads the tag names from ls /proc/tags and a feed\'s tags from getfattr', () => { - expect(tagNames_extract(outcome({ kind: 'fs.listing', data: [{ path: '/proc/tags', items: [{ name: 'urgent' }, { name: 'qc' }] }] }))).toEqual(['urgent', 'qc']); + expect(tagNames_extract(outcome({ kind: 'fs.listing', data: [{ path: '/proc/tags', items: [{ name: 'urgent', type: 'dir' }, { name: 'qc', type: 'dir' }] }] }))).toEqual(['urgent', 'qc']); expect(tagNames_extract(outcome({ kind: 'fs.cwd', data: {} }))).toEqual([]); expect(feedTags_extract(outcome({ kind: 'fs.xattr', data: [{ path: 'feed_12', feedId: 12, tags: ['urgent'] }] }))).toEqual(['urgent']); }); diff --git a/apps/argus/tests/unit/typedAnswers.test.ts b/apps/argus/tests/unit/typedAnswers.test.ts new file mode 100644 index 000000000..7bb8f6f01 --- /dev/null +++ b/apps/argus/tests/unit/typedAnswers.test.ts @@ -0,0 +1,98 @@ +/** + * @file The engine's answers read by shape at each surface site: a listing + * block by block and entry by entry (a malformed one left out, the rest + * kept), a feed's access and tags, never cast; a model of the wrong shape + * reads as no answer and never throws. + */ +import { describe, it, expect } from '@jest/globals'; +import { answerListings_extract } from '../../src/calypso/answerModel.js'; +import type { ExecuteOutcome } from '../../src/calypso/client.js'; +import { holders_extract } from '../../src/app/access.js'; +import { feedTags_extract } from '../../src/app/feedRows.js'; +import { tagNames_extract } from '../../src/app/tags.js'; +import { cyclerNames_seed } from '../../src/app/cycler.js'; + +const outcome = (kind: string, data: unknown): ExecuteOutcome => ({ envelopes: [{ status: 'ok', rendered: '', model: { kind, data } } as never], liveChannels: new Set() }); + +/** An `ls` of two paths, as brasa's ls answers it, with one malformed entry and one malformed block among them. */ +const TWO_PATHS: unknown = [ + { path: '/home/me', items: [ + { name: 'feeds', type: 'dir', size: 0, owner: 'me', date: '2026-12-01T00:00:00Z' }, + { name: 42, type: 'file' }, + { name: 'notes.txt', type: 'file', size: 12, owner: 'me', date: '2026-12-01T00:00:00Z', title: 'notes' }, + ] }, + { path: 7, items: [] }, + { path: '/scripts', items: [{ name: 'mine', type: 'dir' }, { name: 'chrisproject', type: 'source', status: 'cloned' }] }, +]; + +describe('a listing read by shape', () => { + it('keeps every block and entry that reads, beside the ones that do not', () => { + const blocks = answerListings_extract(outcome('fs.listing', TWO_PATHS)); + expect(blocks.map((block) => block.path)).toEqual(['/home/me', '/scripts']); + expect(blocks[0]?.items.map((item) => item.name)).toEqual(['feeds', 'notes.txt']); + expect(blocks[1]?.items.map((item) => `${item.name}:${item.type}:${item.status ?? ''}`)).toEqual(['mine:dir:', 'chrisproject:source:cloned']); + }); + + it('reads no listing from a model that is no list, or of another kind, and never throws', () => { + expect(answerListings_extract(outcome('fs.listing', { path: '/a', items: [] }))).toEqual([]); + expect(answerListings_extract(outcome('fs.listing', null))).toEqual([]); + expect(answerListings_extract(outcome('fs.cwd', TWO_PATHS))).toEqual([]); + }); + + it('carries whether a block was read afresh, what of it went unread, and the entries left out', () => { + const [block] = answerListings_extract(outcome('fs.listing', [{ path: '/a', fresh: false, unread: 'page 2 refused', items: [{ name: 'x', type: 'dir' }, { name: 3 }] }])); + expect(block).toMatchObject({ path: '/a', fresh: false, unread: 'page 2 refused' }); + expect(block?.skipped).toHaveLength(1); + }); + + it('passes over a listing of which nothing reads for a later one that does', () => { + const two: ExecuteOutcome = { envelopes: [ + { status: 'ok', rendered: '', model: { kind: 'fs.listing', data: 'nonsense' } } as never, + { status: 'ok', rendered: '', model: { kind: 'fs.listing', data: [{ path: '/b', items: [{ name: 'y', type: 'file' }] }] } } as never, + ], liveChannels: new Set() }; + expect(answerListings_extract(two).map((block) => block.path)).toEqual(['/b']); + }); + + it('the tag names are the first block\'s entries that read', () => { + expect(tagNames_extract(outcome('fs.listing', [{ path: '/proc/tags', items: [{ name: 'brain', type: 'dir' }, { name: null, type: 'dir' }, { name: 'lung', type: 'dir' }] }]))).toEqual(['brain', 'lung']); + expect(tagNames_extract(outcome('fs.listing', 'nonsense'))).toEqual([]); + }); +}); + +describe('a feed\'s access and tags read by shape', () => { + it('reads the holders, and none from a block of the wrong shape', () => { + expect(holders_extract(outcome('fs.acl', [{ path: 'feed_12', usernames: ['ann'], groups: [], public: false }]))).toEqual({ users: ['ann'], groups: [], public: false }); + expect(holders_extract(outcome('fs.acl', [{ usernames: 'ann' }]))).toBeNull(); + expect(holders_extract(outcome('fs.acl', { usernames: ['ann'] }))).toBeNull(); + }); + + it('reads an ACL block that says nothing of its holders as unread, never as shared with nobody', () => { + expect(holders_extract(outcome('fs.acl', [{ path: 'feed_12' }]))).toBeNull(); + expect(holders_extract(outcome('fs.acl', [{ path: 'feed_12', usernames: [], groups: [] }]))).toBeNull(); + expect(holders_extract(outcome('fs.acl', [{ path: 'feed_12', usernames: [], groups: [], public: false }, { path: 'feed_12' }]))).toBeNull(); + expect(holders_extract(outcome('fs.acl', [{ path: 'feed_12', usernames: ['ann'], groups: [], public: true }]))).toEqual({ users: ['ann'], groups: [], public: true }); + }); + + it('reads the tags, and none from a block of the wrong shape', () => { + expect(feedTags_extract(outcome('fs.xattr', [{ path: 'feed_12', feedId: 12, tags: ['brain'] }]))).toEqual(['brain']); + expect(feedTags_extract(outcome('fs.xattr', [{ path: 'feed_12', tags: [3] }]))).toEqual([]); + expect(feedTags_extract(outcome('fs.xattr', null))).toEqual([]); + }); +}); + +describe('the cycler\'s pipelines read by shape', () => { + /** The names the cycler is handed for an `ls /bin` answering this model. */ + const seeded = async (data: unknown): Promise => { + let names: string[] | null = null; + const answered = Promise.resolve(outcome('fs.listing', data)); + cyclerNames_seed({ line_execute: () => answered }, { names_set: (named: string[]): void => { names = named; } }); + await answered; + await Promise.resolve(); + return names; + }; + + it('names the pipelines that read, leaves a malformed entry out, and reads none from the wrong shape', async () => { + expect(await seeded([{ path: '/bin', items: [{ name: 'fetal', type: 'pipeline' }, { name: 9, type: 'pipeline' }, { name: 'ls', type: 'builtin' }] }])).toEqual(['fetal']); + expect(await seeded({ path: '/bin', items: [] })).toEqual([]); + }); +}); diff --git a/package-lock.json b/package-lock.json index 61938f3bc..450de7f89 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19390,7 +19390,8 @@ "oci-resourcemanager": "2.144.0", "oci-resourcesearch": "2.144.0", "oci-secrets": "2.144.0", - "oci-vault": "2.144.0" + "oci-vault": "2.144.0", + "zod": "^4.6.7" }, "bin": { "stratus": "dist/stratus.js" diff --git a/packages/menu/src/answers.ts b/packages/menu/src/answers.ts new file mode 100644 index 000000000..ac031b562 --- /dev/null +++ b/packages/menu/src/answers.ts @@ -0,0 +1,209 @@ +/** + * @file The answers a surface reads back from the engine's common lines, by + * shape: a listing, a feed's access and tags, a run scheduled, a plugin + * instance row, a game's end and a chime. Each schema names only the fields + * a surface reads and keeps the rest; a reader of a list reads element by + * element, so one malformed block or row is left out and named while the + * rest are kept. + * + * Key components: + * - fsListings_read: the blocks of an `fs.listing` model, each item read by shape. + * - elements_read: any list, element by element, with what was left out. + * - fsAclBlockSchema, fsXattrBlockSchema, runScheduledSchema, pluginInstanceRowSchema, gamesTrekSchema, gamesChimeSchema, gamesShowSchema: the shapes. + * + * Typical usage: + * ```ts + * const read: FsListingsRead = fsListings_read(envelope.model.data); + * for (const block of read.blocks) draw(block.path, block.items); + * ``` + * + * Dependencies: zod. + * + * @module + */ +import { z } from 'zod'; + +/** The model kinds these answers carry. */ +export const ANSWER_MODEL_KINDS = { + fsListing: 'fs.listing', + fsAcl: 'fs.acl', + fsXattr: 'fs.xattr', + runScheduled: 'run.scheduled', + pipelineScheduled: 'pipeline.scheduled', + pluginInstanceList: 'plugininstance.list', + gamesTrek: 'games.trek', + gamesChime: 'games.chime', + gamesShow: 'games.show', +} as const; + +/** + * One listed entry as a surface reads it: its name and kind, anything else + * the engine carries kept (`listingItemSchema` holds the whole of what `ls` + * makes; a mount may list less). + */ +export const listedItemSchema = z.looseObject({ + name: z.string(), + type: z.string(), + status: z.string().optional(), + title: z.string().optional(), +}); + +/** One listed entry as a surface reads it. */ +export type ListedItem = z.infer; + +/** One block of an `fs.listing` model: the folder listed, and its entries, each read on its own. */ +const listingBlockSchema = z.looseObject({ + path: z.string(), + items: z.array(z.unknown()), + fresh: z.boolean().optional(), + unread: z.string().optional(), +}); + +/** + * One folder an `ls` listed, its readable entries. + * + * @example + * ```ts + * const block: ListedBlock = { path: '/scripts', items: [{ name: 'mine', type: 'dir' }] }; + * ``` + */ +export interface ListedBlock { + /** The folder listed. */ + readonly path: string; + /** Its entries that read by shape. */ + readonly items: ReadonlyArray; + /** Whether it was read afresh rather than from the cache, when the listing says. */ + readonly fresh?: boolean; + /** What of the folder could not be read (a page refused), when a partial read kept the rest. */ + readonly unread?: string; + /** Its entries left out for not reading, as `#: why`; absent when none was. */ + readonly skipped?: ReadonlyArray; +} + +/** + * What reading a list left: the elements that read, and what was left out, by position. + * + * @example + * ```ts + * const read: ElementsRead<{ feedId: number }> = { kept: [{ feedId: 3 }], skipped: ['#2: Invalid input'] }; + * ``` + */ +export interface ElementsRead { + /** The elements that read, in order. */ + readonly kept: ReadonlyArray; + /** The elements left out, as `#: ` from one. */ + readonly skipped: ReadonlyArray; +} + +/** + * Reads a list element by element: what reads is kept, what does not is left + * out and named. Data that is no list reads as none, said once. + * + * @param data - The list, as it arrived. + * @param schema - One element's shape. + * @returns The elements kept and those left out. + * + * @example + * ```ts + * elements_read([{ feedId: 3 }, 'x'], runScheduledSchema).skipped; // ['#2: …'] + * ``` + */ +export function elements_read(data: unknown, schema: z.ZodType): ElementsRead { + if (!Array.isArray(data)) return { kept: [], skipped: ['not a list'] }; + const kept: T[] = []; + const skipped: string[] = []; + data.forEach((one: unknown, index: number): void => { + const read = schema.safeParse(one); + if (read.success) kept.push(read.data); + else skipped.push(`#${String(index + 1)}: ${read.error.issues[0]?.message ?? 'malformed'}`); + }); + return { kept, skipped }; +} + +/** + * What an `fs.listing` model read to. + * + * @example + * ```ts + * const read: FsListingsRead = fsListings_read(envelope.model.data); + * ``` + */ +export interface FsListingsRead { + /** The folders listed, each with the entries that read. */ + readonly blocks: ReadonlyArray; + /** What was left out: a block as `#`, an entry as `#`. */ + readonly skipped: ReadonlyArray; +} + +/** + * Reads an `fs.listing` model block by block and entry by entry: a malformed + * block or entry is left out and named, every other one kept. + * + * @param data - The model's data. + * @returns The blocks and what was left out. + * + * @example + * ```ts + * fsListings_read([{ path: '/a', items: [{ name: 'x', type: 'dir' }, { name: 3 }] }]).skipped; // ['/a#2: …'] + * ``` + */ +export function fsListings_read(data: unknown): FsListingsRead { + const blocks = elements_read(data, listingBlockSchema); + const skipped: string[] = blocks.skipped.slice(); + const read: ListedBlock[] = blocks.kept.map((block): ListedBlock => { + const items = elements_read(block.items, listedItemSchema); + // One by one, never spread into a call: a listing of many malformed entries would overflow the call's arguments. + for (const why of items.skipped) skipped.push(`${block.path}${why}`); + return { + path: block.path, + items: items.kept, + ...(block.fresh === undefined ? {} : { fresh: block.fresh }), + ...(block.unread === undefined ? {} : { unread: block.unread }), + ...(items.skipped.length === 0 ? {} : { skipped: items.skipped }), + }; + }); + return { blocks: read, skipped }; +} + +/** One block of `getfacl`'s model: who holds a feed besides its owner, each part always said (a block missing one is unread, never nobody). */ +export const fsAclBlockSchema = z.looseObject({ + usernames: z.array(z.string()), + groups: z.array(z.string()), + public: z.boolean(), +}); + +/** One block of `getfattr`'s model: the tags a feed wears. */ +export const fsXattrBlockSchema = z.looseObject({ + tags: z.array(z.string()), +}); + +/** What `run.scheduled` and `pipeline.scheduled` say of where the work landed. */ +export const runScheduledSchema = z.looseObject({ + feedId: z.number(), +}); + +/** One row of `plugininstance list`, as a surface reads it. */ +export const pluginInstanceRowSchema = z.looseObject({ + pluginName: z.string(), + pluginVersion: z.string(), + owner: z.string().optional(), +}); + +/** How a trek game ended. */ +export const gamesTrekSchema = z.looseObject({ + exit: z.number(), +}); + +/** A chime that rang. */ +export const gamesChimeSchema = z.looseObject({ + text: z.string(), +}); + +/** A showpiece to play: its program, and `pane` true to play it in the GAMES pane. */ +export const gamesShowSchema = z.looseObject({ + program: z.string(), + pane: z.boolean().optional(), +}); + +/** A showpiece as a surface reads it. */ +export type GamesShow = z.infer; diff --git a/packages/menu/src/index.ts b/packages/menu/src/index.ts index 38b4302de..08f0424bd 100644 --- a/packages/menu/src/index.ts +++ b/packages/menu/src/index.ts @@ -431,3 +431,4 @@ export { } from './ansi/grammar.js'; export { AnsiPlainStream, ansi_tokenize, ansi_strip, ansi_width, ansi_present, ansiTokens_merge } from './ansi/plain.js'; export { TERMINAL_STATE_OSC, TERMINAL_STATES, terminalState_isRunning, terminalState_render, terminalState_parse, type TerminalState } from './ansi/terminalState.js'; +export { ANSWER_MODEL_KINDS, listedItemSchema, elements_read, fsListings_read, fsAclBlockSchema, fsXattrBlockSchema, runScheduledSchema, pluginInstanceRowSchema, gamesTrekSchema, gamesChimeSchema, gamesShowSchema, type GamesShow, type ListedItem, type ListedBlock, type ElementsRead, type FsListingsRead } from './answers.js'; diff --git a/packages/menu/src/proc.ts b/packages/menu/src/proc.ts index 6f8713eaa..3d12c9cb3 100644 --- a/packages/menu/src/proc.ts +++ b/packages/menu/src/proc.ts @@ -72,14 +72,11 @@ export interface ProcPromptJobGroup { parent: number | null; } -/** - * A warm-up step that failed behind the prompt and has not since succeeded. - * - * @property label - The boot-step label, as the readout named it. - * @property message - What the failure said. - */ +/** A warm-up step that failed behind the prompt and has not since succeeded. */ export interface WarmupFailureReport { + /** The boot-step label, as the readout named it. */ label: string; + /** What the failure said. */ message: string; } diff --git a/packages/menu/tests/answers.test.ts b/packages/menu/tests/answers.test.ts new file mode 100644 index 000000000..85f43a654 --- /dev/null +++ b/packages/menu/tests/answers.test.ts @@ -0,0 +1,68 @@ +/** + * @file The common answers read by shape: a list element by element, a + * listing block by block and entry by entry, each left-out one named; an + * always-empty reader would fail here. + */ +import { describe, it, expect } from '@jest/globals'; +import { elements_read, fsAclBlockSchema, fsListings_read, gamesChimeSchema, gamesShowSchema, gamesTrekSchema, pluginInstanceRowSchema, runScheduledSchema } from '../src/answers.js'; + +describe('a list read element by element', () => { + it('keeps what reads and names what does not, by position', () => { + const read = elements_read([{ feedId: 3 }, 'x', { feedId: '4' }, { feedId: 5, newFeed: true }], runScheduledSchema); + expect(read.kept).toEqual([{ feedId: 3 }, { feedId: 5, newFeed: true }]); + expect(read.skipped.map((why: string): string => why.split(':')[0] ?? '')).toEqual(['#2', '#3']); + expect(elements_read({ feedId: 3 }, runScheduledSchema)).toEqual({ kept: [], skipped: ['not a list'] }); + }); +}); + +describe('a listing', () => { + it('keeps the blocks and entries that read across several paths, and names the rest', () => { + const read = fsListings_read([ + { path: '/a', items: [{ name: 'x', type: 'dir', size: 0 }, { name: 1, type: 'file' }, { name: 'y', type: 'file' }] }, + { items: [] }, + { path: '/b', items: [{ name: 'z', type: 'plugin', version: '1.0' }] }, + ]); + expect(read.blocks.map((block) => [block.path, block.items.map((item) => item.name)])).toEqual([['/a', ['x', 'y']], ['/b', ['z']]]); + expect(read.blocks[1]?.items[0]).toMatchObject({ version: '1.0' }); + expect(read.skipped.map((why: string): string => why.split(':')[0] ?? '')).toEqual(['#2', '/a#2']); + }); +}); + +describe('the other shapes', () => { + it('read what a surface reads and refuse the wrong type', () => { + expect(pluginInstanceRowSchema.safeParse({ pluginName: 'pl-x', pluginVersion: '1.0', id: 3 }).success).toBe(true); + expect(pluginInstanceRowSchema.safeParse({ pluginName: 'pl-x' }).success).toBe(false); + expect(gamesTrekSchema.safeParse({ seed: 1, exit: 2 }).data?.exit).toBe(2); + expect(gamesTrekSchema.safeParse({ exit: '2' }).success).toBe(false); + expect(gamesChimeSchema.safeParse({ text: 7 }).success).toBe(false); + expect(gamesShowSchema.safeParse({ program: 'sl', pane: true }).data?.pane).toBe(true); + expect(gamesShowSchema.safeParse(undefined).success).toBe(false); + }); + + it('a showpiece reads only with its program, and a pane of the wrong type does not read', () => { + expect(gamesShowSchema.safeParse({ pane: true }).success).toBe(false); + expect(gamesShowSchema.safeParse({ program: 'sl', pane: 'yes' }).success).toBe(false); + }); + + it('an ACL block reads only when it says its users, its groups and whether it is public', () => { + expect(fsAclBlockSchema.safeParse({ path: 'feed_1', usernames: [], groups: [], public: false }).success).toBe(true); + expect(fsAclBlockSchema.safeParse({ path: 'feed_1' }).success).toBe(false); + expect(fsAclBlockSchema.safeParse({ path: 'feed_1', usernames: [], groups: [] }).success).toBe(false); + }); +}); + +describe('a listing as ls answers it', () => { + it('keeps whether it was read afresh, what went unread, and the entries left out, on its block', () => { + const read = fsListings_read([{ path: '/a', items: [{ name: 'x', type: 'dir' }, { name: 2 }], fresh: true, unread: 'page 2 refused' }]); + expect(read.blocks[0]).toMatchObject({ path: '/a', fresh: true, unread: 'page 2 refused' }); + expect(read.blocks[0]?.skipped?.map((why: string): string => why.split(':')[0] ?? '')).toEqual(['#2']); + }); + + it('names every entry left out of a listing too long to spread into one call', () => { + const items: unknown[] = [{ name: 'kept', type: 'file' }]; + for (let index = 0; index < 140_000; index++) items.push({ name: index }); + const read = fsListings_read([{ path: '/many', items }]); + expect(read.blocks[0]?.items).toEqual([{ name: 'kept', type: 'file' }]); + expect(read.skipped).toHaveLength(140_000); + }); +}); diff --git a/packages/stratus/package.json b/packages/stratus/package.json index 508464d94..b11b5ee4b 100644 --- a/packages/stratus/package.json +++ b/packages/stratus/package.json @@ -73,6 +73,7 @@ "oci-resourcemanager": "2.144.0", "oci-resourcesearch": "2.144.0", "oci-secrets": "2.144.0", - "oci-vault": "2.144.0" + "oci-vault": "2.144.0", + "zod": "^4.6.7" } } diff --git a/packages/stratus/src/checkout/harborOci.ts b/packages/stratus/src/checkout/harborOci.ts index 801b6cdb3..6ddc24fd1 100644 --- a/packages/stratus/src/checkout/harborOci.ts +++ b/packages/stratus/src/checkout/harborOci.ts @@ -19,7 +19,11 @@ */ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'; import { join } from 'node:path'; + +import { z } from 'zod'; + import type { ClusterSpec } from '../cluster/spec.js'; +import { json_read } from '../read.js'; /** The build's steps, in the order `just install` runs them. */ export const HARBOR_STEPS: ReadonlyArray = ['preflight', 'cluster', 'iso', 'infra-plan', 'infra-apply', 'dns', 'manifests', 'hosts', 'run', 'postinstall', 'verify']; @@ -129,7 +133,7 @@ function state_read(root: string): Record | null { const path: string = join(root, 'state', 'harbor.json'); const text: string | null = text_read(path); if (text === null) return null; - const state: Record = JSON.parse(text) as Record; + const state: Record = { ...json_read(text, z.record(z.string(), z.unknown()), path) }; for (const field of SECRET_STATE_FIELDS) { if (state[field] !== undefined) state[field] = `withheld: a secret, on the host in ${path}`; } @@ -140,8 +144,7 @@ function state_read(root: string): Record | null { function terraformResources_count(stackDir: string): number | null { const text: string | null = text_read(join(stackDir, 'terraform.tfstate')); if (text === null) return null; - const resources: unknown = (JSON.parse(text) as { resources?: unknown }).resources; - return Array.isArray(resources) ? resources.length : 0; + return json_read(text, z.looseObject({ resources: z.array(z.unknown()).optional() }), join(stackDir, 'terraform.tfstate')).resources?.length ?? 0; } /** diff --git a/packages/stratus/src/chris/compose.ts b/packages/stratus/src/chris/compose.ts index 70940ed97..d10f09fc7 100644 --- a/packages/stratus/src/chris/compose.ts +++ b/packages/stratus/src/chris/compose.ts @@ -30,6 +30,8 @@ * @module */ import * as yaml from 'js-yaml'; +import { z } from 'zod'; + import { CHRIS_IMAGES, PORTER_DIST_TAG, type ChrisProfile } from './profiles.js'; /** What a deploy keeps secret, generated once and reused by every replay. */ @@ -46,6 +48,17 @@ export interface ChrisSecrets { launcherSecret?: string; } +/** A deploy's secrets as they are kept, read back by their shape (a refusal never quotes them). */ +export const chrisSecretsSchema = z.looseObject({ + djangoKey: z.string(), + postgresPassword: z.string(), + pfconSecretKey: z.string(), + pfconPassword: z.string(), + adminPassword: z.string(), + porterSecret: z.string().optional(), + launcherSecret: z.string().optional(), +}); + /** Berths behind porter, as a deploy puts them up. */ export interface ChrisBerths { /** The group that owns Docker's socket on the VM, given to the launcher alone. */ diff --git a/packages/stratus/src/chris/registrar.ts b/packages/stratus/src/chris/registrar.ts index 3f0cfdc3b..7e147a623 100644 --- a/packages/stratus/src/chris/registrar.ts +++ b/packages/stratus/src/chris/registrar.ts @@ -12,6 +12,32 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; +import { elements_read } from '@fnndsc/menu'; +import { z } from 'zod'; + +import { json_read } from '../read.js'; + +/** One DNS record as GoDaddy lists it. */ +const godaddyRecordSchema = z.looseObject({ recordId: z.string(), type: z.string(), name: z.string(), data: z.string(), ttl: z.number() }); + +/** GoDaddy's answer to a records listing: its items, each read on its own. */ +const godaddyRecordsSchema = z.looseObject({ items: z.array(z.unknown()).optional() }); + +/** A record's name alone, to tell whether one that does not read could be the name asked for. */ +const godaddyNamedSchema = z.looseObject({ name: z.string() }); + +/** + * Whether a listed record could be the name's: it names it, or names nothing readable. + * + * @param item - The listed record. + * @param name - The name asked for. + * @returns False only for a record that surely names another. + */ +function recordName_couldBe(item: unknown, name: string): boolean { + const named = godaddyNamedSchema.safeParse(item); + return !named.success || named.data.name === name; +} + /** A record at the registrar. */ export interface RegistrarRecord { readonly id: string; @@ -119,8 +145,12 @@ export function goDaddy_make(tokenFile: string = goDaddyToken_path(), fetcher: t id: 'GoDaddy', serves: (nameservers: ReadonlyArray): boolean => nameservers.length > 0 && nameservers.every((server: string): boolean => /\.domaincontrol\.com\.?$/i.test(server)), async records_list(zone: string, name: string): Promise { - const answer = await (await ask('GET', `${base}/${encodeURIComponent(zone)}/dns-records?name=${encodeURIComponent(name)}&pageSize=100`)).json() as { items?: Array<{ recordId: string; type: string; name: string; data: string; ttl: number }> }; - return (answer.items ?? []).filter((item): boolean => item.name === name).map((item): RegistrarRecord => ({ id: item.recordId, type: item.type, name: item.name, data: item.data, ttl: item.ttl })); + const answer = json_read(await (await ask('GET', `${base}/${encodeURIComponent(zone)}/dns-records?name=${encodeURIComponent(name)}&pageSize=100`)).text(), godaddyRecordsSchema, `GoDaddy records of ${name}.${zone}`); + const items: unknown[] = answer.items ?? []; + // A record that does not read is left out only when it is surely another name's: one that could be this name's is refused, before anything is changed. + const unread: number = items.findIndex((item: unknown): boolean => !godaddyRecordSchema.safeParse(item).success && recordName_couldBe(item, name)); + if (unread >= 0) throw new Error(`GoDaddy records of ${name}.${zone}: record #${String(unread + 1)} could be this name's and does not read, so nothing was changed`); + return elements_read(items, godaddyRecordSchema).kept.filter((item): boolean => item.name === name).map((item): RegistrarRecord => ({ id: item.recordId, type: item.type, name: item.name, data: item.data, ttl: item.ttl })); }, async record_delete(zone: string, id: string): Promise { await ask('DELETE', `${base}/${encodeURIComponent(zone)}/dns-records/${encodeURIComponent(id)}`); diff --git a/packages/stratus/src/chris/secrets.ts b/packages/stratus/src/chris/secrets.ts index 268ed2a45..6f51d1c02 100644 --- a/packages/stratus/src/chris/secrets.ts +++ b/packages/stratus/src/chris/secrets.ts @@ -11,7 +11,8 @@ import { randomBytes } from 'crypto'; import * as fs from 'fs'; import * as path from 'path'; import type { VmStore } from '../vm/state.js'; -import type { ChrisSecrets } from './compose.js'; +import { chrisSecretsSchema, type ChrisSecrets } from './compose.js'; +import { json_read } from '../read.js'; /** * A secret: 32 random bytes, URL-safe. @@ -42,7 +43,7 @@ function secretsFile_derive(store: VmStore, name: string): string { */ export function secrets_read(store: VmStore, name: string): ChrisSecrets | null { const file: string = secretsFile_derive(store, name); - return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf-8')) as ChrisSecrets : null; + return fs.existsSync(file) ? json_read(fs.readFileSync(file, 'utf-8'), chrisSecretsSchema, file) : null; } /** diff --git a/packages/stratus/src/chris/users.ts b/packages/stratus/src/chris/users.ts index 6360eae94..a95e88c8d 100644 --- a/packages/stratus/src/chris/users.ts +++ b/packages/stratus/src/chris/users.ts @@ -10,10 +10,15 @@ * @module */ import type { JobContext, JobRun } from '@fnndsc/brasa/core'; +import { z } from 'zod'; + +import { CHRIS_DIR } from './compose.js'; +import type { DeployDeps } from './deploy.js'; import type { BuildCall } from '../cloud/builder.js'; +import { json_read } from '../read.js'; import { vmRemote_open, type RemoteAnswer, type VmRemote } from '../vm/remote.js'; -import type { DeployDeps } from './deploy.js'; -import { CHRIS_DIR } from './compose.js'; + + /** The account asked for, with the groups it joins beside `all_users` (every account's). */ export interface UserAsk { @@ -204,11 +209,11 @@ export function userAnswer_parse(stdout: string): UserAnswer | null { const [, kind = '', ...rest] = line.split(' '); const value: string = rest.join(' '); if (kind === 'added') return { kind: 'added' }; - if (kind === 'exists') return { kind: 'exists', email: JSON.parse(value) as string }; - if (kind === 'email-taken') return { kind: 'emailTaken', username: JSON.parse(value) as string }; + if (kind === 'exists') return { kind: 'exists', email: json_read(value, z.string(), 'chris user: the email it holds') }; + if (kind === 'email-taken') return { kind: 'emailTaken', username: json_read(value, z.string(), 'chris user: who holds the email') }; if (kind === 'changed') return { kind: 'changed' }; if (kind === 'absent') return { kind: 'absent' }; - if (kind === 'no-group') return { kind: 'noGroup', groups: JSON.parse(value) as string[] }; + if (kind === 'no-group') return { kind: 'noGroup', groups: json_read(value, z.array(z.string()), 'chris user: the groups missing') }; return null; } diff --git a/packages/stratus/src/cloud/builder.ts b/packages/stratus/src/cloud/builder.ts index b73fcb27b..8a48832c7 100644 --- a/packages/stratus/src/cloud/builder.ts +++ b/packages/stratus/src/cloud/builder.ts @@ -9,8 +9,11 @@ * * @module */ +import { z } from 'zod'; + import type { ClusterSpec } from '../cluster/spec.js'; import type { PlatformManifest } from '../installer/installer.js'; +import { json_read } from '../read.js'; /** One check the build makes before it starts. */ export interface PreflightCheck { @@ -33,19 +36,51 @@ export interface PlanRow { changes?: ReadonlyArray<{ path: string; before: string | null; after: string | null }>; } -/** - * An infrastructure plan, as the operator is asked about it. - * - * @property ref - The cloud's handle on it, for the apply (OCI: the plan job's id). - * @property rows - Each change. - */ +/** An infrastructure plan, as the operator is asked about it. */ export interface InfraPlan { + /** The cloud's handle on it, for the apply (OCI: the plan job's id). */ ref: string; + /** Each change. */ rows: ReadonlyArray; /** The stack the plan was made in, when the plan made one. */ stackRef?: string; } +/** One change of a plan as stratus reads it back from where it kept it; anything else the plan carries is kept. */ +const planRowSchema = z.looseObject({ + action: z.enum(['create', 'change', 'destroy']), + kind: z.string(), + name: z.string(), + drift: z.boolean().optional(), + type: z.string().optional(), + changes: z.array(z.looseObject({ path: z.string(), before: z.string().nullable(), after: z.string().nullable() })).optional(), +}); + +/** A plan as stratus reads it back: its handle, its rows, and the stack it was made in. */ +const infraPlanSchema = z.looseObject({ + ref: z.string(), + rows: z.array(planRowSchema), + stackRef: z.string().optional(), +}); + +/** + * Reads a plan kept on this host (`plan.json`) by its shape, whole: a plan + * with one malformed row is refused, never counted short. + * + * @param text - The kept plan's text. + * @param what - What it is, for the refusal (`store: plan.json`). + * @returns The plan. + * @throws {ReadRefusal} When it does not read as a plan. + * + * @example + * ```ts + * const plan: InfraPlan = infraPlan_read(planText, `${name}: plan.json`); + * ``` + */ +export function infraPlan_read(text: string, what: string): InfraPlan { + return json_read(text, infraPlanSchema, what); +} + /** A plan's counts: a resource both destroyed and created is replaced, drift is apart from real change. */ export interface PlanCounts { create: number; diff --git a/packages/stratus/src/cloud/oci/rmApi.ts b/packages/stratus/src/cloud/oci/rmApi.ts index 101cffcf6..2829aad4c 100644 --- a/packages/stratus/src/cloud/oci/rmApi.ts +++ b/packages/stratus/src/cloud/oci/rmApi.ts @@ -12,7 +12,16 @@ */ import * as common from 'oci-common'; import * as resourcemanager from 'oci-resourcemanager'; +import { z } from 'zod'; + import { notFound } from './errors.js'; +import { json_read } from '../../read.js'; + +/** A Terraform state as Resource Manager hands it, read for its resources and outputs; the rest kept. */ +const tfStateSchema = z.looseObject({ + resources: z.array(z.looseObject({ mode: z.string().optional(), instances: z.array(z.unknown()).optional() })).optional(), + outputs: z.record(z.string(), z.looseObject({ value: z.unknown().optional() })).optional(), +}); /** The Terraform the stacks run: the newest Resource Manager offers. */ export const RM_TERRAFORM_VERSION: string = '1.5.x'; @@ -191,11 +200,11 @@ function rmStackCalls_make(client: resourcemanager.ResourceManagerClient): RmSta return found; }, async stackResources_count(stackId) { - const state = JSON.parse(await stream_text((await client.getStackTfState({ stackId })).value)) as { resources?: Array<{ mode?: string; instances?: unknown[] }> }; + const state = json_read(await stream_text((await client.getStackTfState({ stackId })).value), tfStateSchema, `stack ${stackId}: its Terraform state`); return (state.resources ?? []).filter((resource): boolean => resource.mode !== 'data').reduce((sum: number, resource): number => sum + (resource.instances?.length ?? 1), 0); }, async stackOutputs_read(stackId) { - const state = JSON.parse(await stream_text((await client.getStackTfState({ stackId })).value)) as { outputs?: Record }; + const state = json_read(await stream_text((await client.getStackTfState({ stackId })).value), tfStateSchema, `stack ${stackId}: its Terraform state`); const outputs: Record = {}; for (const [name, output] of Object.entries(state.outputs ?? {})) { if (output.value !== undefined && output.value !== null) outputs[name] = typeof output.value === 'string' ? output.value : JSON.stringify(output.value); @@ -239,7 +248,8 @@ function rmJobCalls_make(client: resourcemanager.ResourceManagerClient): RmJobCa }, async jobPlan_read(jobId) { const response = await client.getJobTfPlan({ jobId, tfPlanFormat: resourcemanager.requests.GetJobTfPlanRequest.TfPlanFormat.Json }); - return JSON.parse(await stream_text(response.value)) as unknown; + // Parsed by name: a plan that is no JSON is refused as the job's plan, never quoted (a plan carries what it sets). + return json_read(await stream_text(response.value), z.unknown(), `job ${jobId}: plan`); }, async jobOutputs_read(jobId) { const outputs: Record = {}; diff --git a/packages/stratus/src/cluster/adopt.ts b/packages/stratus/src/cluster/adopt.ts index 4e12baa8b..86c214646 100644 --- a/packages/stratus/src/cluster/adopt.ts +++ b/packages/stratus/src/cluster/adopt.ts @@ -17,14 +17,21 @@ */ import { existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; + import type { JobContext, JobRun } from '@fnndsc/brasa/core'; -import { envFile_parse, harborCluster_read, type HarborCluster } from '../checkout/harborOci.js'; -import type { CloudBuilder } from '../cloud/builder.js'; +import { z } from 'zod'; + import { specYaml_parse, SPEC_DEFAULT, type ClusterSpec } from './spec.js'; -import { smokeVerdict_words } from '../kube/chris.js'; +import type { ClusterRecord, ClusterStore, StepRecord } from './state.js'; import { MACHINE_STEPS } from './steps.js'; import { ADOPTED_COMPARTMENT } from './view.js'; -import type { ClusterRecord, ClusterStore, StepRecord } from './state.js'; +import { envFile_parse, harborCluster_read, type HarborCluster } from '../checkout/harborOci.js'; +import type { CloudBuilder } from '../cloud/builder.js'; +import { smokeVerdict_words } from '../kube/chris.js'; +import { json_read } from '../read.js'; + +/** A Terraform state's outputs, as an adoption reads the load balancers' addresses from them. */ +const terraformOutputsSchema = z.looseObject({ outputs: z.record(z.string(), z.looseObject({ value: z.unknown().optional() })).optional() }); /** What adoption reads from a checkout. */ export interface CheckoutRead { @@ -119,9 +126,10 @@ export function checkout_read(name: string, root: string, now: Date): CheckoutRe if (typeof harbor[field] === 'string') ids[key] = harbor[field] as string; } // The load balancers' addresses, from the state's outputs, for the DNS check. - const outputs: Record = (JSON.parse(readFileSync(stateFile, 'utf-8')) as { outputs?: Record }).outputs ?? {}; + const outputs = json_read(readFileSync(stateFile, 'utf-8'), terraformOutputsSchema, stateFile).outputs ?? {}; for (const [key, output] of [['apiIp', 'open_shift_api_lb_addr'], ['apiIntIp', 'open_shift_api_int_lb_addr'], ['appsIp', 'open_shift_apps_lb_addr']] as const) { - if (typeof outputs[output]?.value === 'string') ids[key] = outputs[output]!.value as string; + const value: unknown = outputs[output]?.value; + if (typeof value === 'string') ids[key] = value; } const record: ClusterRecord = { name, created: now.toISOString(), region, baseDomain, steps, ids, compartmentId, @@ -130,7 +138,7 @@ export function checkout_read(name: string, root: string, now: Date): CheckoutRe const secrets = cluster.secrets.filter((secret): boolean => KEPT_SECRETS.includes(secret.name)); return { cluster, record, spec: parsed.spec, stateFile, secrets, - variables: variables_stringify(JSON.parse(readFileSync(tfvarsFile, 'utf-8')) as Record), + variables: variables_stringify(json_read(readFileSync(tfvarsFile, 'utf-8'), z.record(z.string(), z.unknown()), tfvarsFile)), stackVersion: settings['OCI_STACK_VERSION'] ?? '', }; } diff --git a/packages/stratus/src/cluster/keep.ts b/packages/stratus/src/cluster/keep.ts index 4b607eeeb..b1d49b146 100644 --- a/packages/stratus/src/cluster/keep.ts +++ b/packages/stratus/src/cluster/keep.ts @@ -8,9 +8,12 @@ * * @module */ -import type { BuildCall, CloudBuilder } from '../cloud/builder.js'; -import { lock_adopt, lock_newer, lock_read, type KeptLock } from '../kept/lock.js'; +import { z } from 'zod'; + import type { ClusterRecord, ClusterStore } from './state.js'; +import type { BuildCall, CloudBuilder } from '../cloud/builder.js'; +import { keptLockSchema, lock_adopt, lock_newer, lock_read, type KeptLock } from '../kept/lock.js'; +import { json_read } from '../read.js'; /** What one cluster's secret holds. */ export interface ClusterKept { @@ -18,6 +21,9 @@ export interface ClusterKept { readonly lock?: KeptLock; } +/** A cluster's keep as the vault holds it, read back by its shape: whose it is, and its lock. */ +const clusterKeptSchema = z.looseObject({ cluster: z.string(), lock: keptLockSchema.optional() }); + /** * The secret's name in the tenancy's vault. * @@ -41,7 +47,7 @@ export async function clusterKept_read(builder: CloudBuilder, name: string, regi if (builder.keep_read === undefined) return null; const content: string | null = await builder.keep_read({ region, name: clusterKeepName_derive(name) }); if (content === null) return null; - const kept: ClusterKept = JSON.parse(content) as ClusterKept; + const kept: ClusterKept = json_read(content, clusterKeptSchema, clusterKeepName_derive(name)); if (kept.cluster !== name) throw new Error(`${clusterKeepName_derive(name)}: the tenancy's secret is not a cluster's keep`); return kept; } diff --git a/packages/stratus/src/cluster/readout.ts b/packages/stratus/src/cluster/readout.ts index a2d10c398..920ab11a2 100644 --- a/packages/stratus/src/cluster/readout.ts +++ b/packages/stratus/src/cluster/readout.ts @@ -11,15 +11,17 @@ */ import * as fs from 'fs'; import * as path from 'path'; -import { taskState_isOver, type ClusterCondition, type ClusterSummary, type PlanSummary, type VerifyCheckModel } from '@fnndsc/menu'; + import { runner_get, type JobRecord } from '@fnndsc/brasa/core'; -import { plan_count, TEARDOWN_STEPS, type InfraPlan, type PlanRow, type TeardownStep } from '../cloud/builder.js'; -import { lastDone_find, type HarborCluster, type StepState } from '../checkout/harborOci.js'; -import { lock_read, lockKept_is } from '../kept/lock.js'; +import { taskState_isOver, type ClusterCondition, type ClusterSummary, type PlanSummary, type VerifyCheckModel } from '@fnndsc/menu'; + import type { ClusterRecord, ClusterStore } from './state.js'; import { BUILD_STEPS, buildJob_id, FIRST_BILLING_STEP, stepNext_find, STEPS_SOURCE, teardownJob_id } from './steps.js'; - -import { VERIFY_FILE, type VerifyKept } from './verify.js'; +import { VERIFY_FILE, verifyKept_read, verifyUnread_check, type VerifyKept } from './verify.js'; +import { lastDone_find, type HarborCluster, type StepState } from '../checkout/harborOci.js'; +import { infraPlan_read, plan_count, TEARDOWN_STEPS, type InfraPlan, type PlanRow, type TeardownStep } from '../cloud/builder.js'; +import { lock_read, lockKept_is } from '../kept/lock.js'; +import { ReadRefusal } from '../read.js'; export { VERIFY_FILE, type VerifyKept }; @@ -194,7 +196,13 @@ export function clusterReadout_build(cluster: HarborCluster, store: ClusterStore const runningStep: string | null = running === 'teardown' ? 'teardown' : cluster.steps.find((step: StepState): boolean => step.state === 'running')?.name ?? null; const planText: string | null = store?.file_read(cluster.name, 'plan.json') ?? null; const verifyText: string | null = store?.file_read(cluster.name, VERIFY_FILE) ?? null; - const verify: VerifyKept | null = verifyText === null ? null : JSON.parse(verifyText) as VerifyKept; + // A kept verify that does not read is said as kept and not readable, never as none and never cast: the status of the cluster still reads. + let verify: VerifyKept | null = null; + try { + verify = verifyText === null ? null : verifyKept_read(verifyText, `${cluster.name}: ${VERIFY_FILE}`); + } catch (error: unknown) { + verify = { at: '', checks: [verifyUnread_check(VERIFY_FILE, error instanceof ReadRefusal ? error.why : 'malformed')] }; + } // Billing starts with the first resource the billing step makes: once it runs (or failed part way), not only once it is done. const billingState: string = stepState_read(cluster, FIRST_BILLING_STEP); const applied: boolean = billingState === 'done' || billingState === 'running' || billingState === 'failed' || record?.steps[FIRST_BILLING_STEP]?.started !== undefined || lastDone_find(cluster) !== null && (record === null || record.adopted !== undefined); @@ -217,7 +225,7 @@ export function clusterReadout_build(cluster: HarborCluster, store: ClusterStore next: record === null || record.adopted !== undefined || record.gone !== undefined ? null : stepNext_find(record), billingStep: FIRST_BILLING_STEP, running: running !== null ? { job: (job as JobRecord).id, step: runningStep, since: record?.steps[runningStep ?? '']?.started ?? (job as JobRecord).started } : null, - plan: planText === null || store === null ? null : planSummary_build(JSON.parse(planText) as InfraPlan, fileTime_read(store, cluster.name, 'plan.json')), + plan: planText === null || store === null ? null : planSummary_build(infraPlan_read(planText, `${cluster.name}: plan.json`), fileTime_read(store, cluster.name, 'plan.json')), verify: verify === null ? null : { at: verify.at, checks: verify.checks }, asking, }; diff --git a/packages/stratus/src/cluster/state.ts b/packages/stratus/src/cluster/state.ts index 69f87f524..a69d5c4a5 100644 --- a/packages/stratus/src/cluster/state.ts +++ b/packages/stratus/src/cluster/state.ts @@ -23,8 +23,11 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; + +import { z } from 'zod'; + import { specYaml_parse, specYaml_render, type ClusterSpec } from './spec.js'; -import { file_writeAtomic, KeptFolders } from '../kept/specStore.js'; +import { file_writeAtomic, KeptFolders, keptRecordSchema } from '../kept/specStore.js'; /** Where a step stands in a cluster this session builds. */ export type BuiltStepState = 'not done' | 'running' | 'done' | 'failed'; @@ -47,8 +50,6 @@ export interface StepRecord { * @property baseDomain - The DNS zone its cluster's names live under. * @property steps - Each step's history, by name. * @property ids - What the build recorded for later steps (the installer's ids, the stack's, the ISO object). - * @property billingAccepted - When the operator answered yes to the cost of the first billing step. - * @property buildAccepted - When the operator answered yes to what a build makes before it bills (the compartment, the records at Red Hat, the discovery ISO and its link, the plan). * @property compartmentId - The compartment its resources live in, when known. * @property adopted - Where it was adopted from, and when: built elsewhere, never built on here. * @property gone - When its teardown removed what it built. @@ -63,7 +64,9 @@ export interface ClusterRecord { baseDomain: string; steps: Record; ids: Record; + /** When the operator answered yes to the cost of the first billing step. */ billingAccepted?: string; + /** When the operator answered yes to what a build makes before it bills (the compartment, the records at Red Hat, the discovery ISO and its link, the plan). */ buildAccepted?: string; compartmentId?: string; /** When its spec was last declared again (`cluster new` on a kept cluster); after a build, the build has a change to plan. */ @@ -128,13 +131,20 @@ export const CLUSTER_TAG: string = 'mise-cluster'; /** A cluster name is a DNS label: lower-case letters, digits and hyphens, at most 54. */ export const CLUSTER_NAME: RegExp = /^[a-z]([a-z0-9-]{0,52}[a-z0-9])?$/; +/** A cluster's `state.json` as it is read back: what every record carries, its domain, its steps and the handles a build reads; the rest kept. */ +const clusterRecordSchema = keptRecordSchema.extend({ + baseDomain: z.string(), + steps: z.record(z.string(), z.looseObject({ state: z.enum(['not done', 'running', 'done', 'failed']) })), + ids: z.record(z.string(), z.string()), +}); + /** The clusters this daemon builds, on its host. */ export class ClusterStore extends KeptFolders { /** * @param root - The folder the clusters live in. */ constructor(root: string) { - super(root, (): string => 'cluster'); + super(root, (): string => 'cluster', clusterRecordSchema); } /** diff --git a/packages/stratus/src/cluster/steps.ts b/packages/stratus/src/cluster/steps.ts index 620246183..71e90b875 100644 --- a/packages/stratus/src/cluster/steps.ts +++ b/packages/stratus/src/cluster/steps.ts @@ -18,14 +18,16 @@ * @module */ import { join } from 'node:path'; + import type { JobContext, JobRun } from '@fnndsc/brasa/core'; -import { CHRIS_RELEASE, CHRIS_WAITS, chrisWork_cluster, hostRun_spawn, type ChrisCall, type ChrisWaits, type ChrisWork, type HostRun } from '../kube/chris.js'; -import type { VerifyReach } from '../commands/verify.js'; -import { planCounts_alter, plan_count, planCounts_words, type BuildCall, type CloudBuilder, type InfraOutputs, type InfraPlan, type PreflightCheck } from '../cloud/builder.js'; -import type { Installer, InstallerHost, InstallerIds, InstallStatus, PlatformManifest } from '../installer/installer.js'; + import { specNodes_build, type ClusterSpec, type SpecNode } from './spec.js'; import type { ClusterRecord, ClusterStore, StepRecord } from './state.js'; import { verify_run, verifyChecks_keep, type VerifyCheck } from './verify.js'; +import { infraPlan_read, planCounts_alter, plan_count, planCounts_words, type BuildCall, type CloudBuilder, type InfraOutputs, type InfraPlan, type PreflightCheck } from '../cloud/builder.js'; +import type { VerifyReach } from '../commands/verify.js'; +import { platformManifests_read, type Installer, type InstallerHost, type InstallerIds, type InstallStatus, type PlatformManifest } from '../installer/installer.js'; +import { CHRIS_RELEASE, CHRIS_WAITS, chrisWork_cluster, hostRun_spawn, type ChrisCall, type ChrisWaits, type ChrisWork, type HostRun } from '../kube/chris.js'; /** The build's steps, in order: the machine, then ChRIS on it. */ export const BUILD_STEPS: ReadonlyArray = ['compartment', 'preflight', 'cluster', 'iso', 'infra-plan', 'infra-apply', 'dns', 'manifests', 'hosts', 'run', 'postinstall', 'verify', 'chris-deploy', 'chris-seed', 'smoke']; @@ -246,7 +248,7 @@ const STEP_WORK: Readonly Promise>> = if (record.ids['appliedAt'] !== undefined) return `already applied: ${record.ids['stackRef'] ?? ''}`; const text: string | null = call.deps.store.file_read(call.name, 'plan.json'); if (text === null) throw new Error('no plan recorded: infra-plan has not been done'); - const plan: InfraPlan = JSON.parse(text) as InfraPlan; + const plan: InfraPlan = infraPlan_read(text, `${call.name}: plan.json`); const outputs: InfraOutputs = await call.deps.builder.infra_apply({ cluster: call.name, plan, region: record.region, ...(record.ids['stackRef'] !== undefined ? { stackRef: record.ids['stackRef'] } : {}) }, call); call.remember({ stackRef: outputs.stackRef, apiIp: outputs.apiIp, apiIntIp: outputs.apiIntIp, appsIp: outputs.appsIp, appliedAt: new Date().toISOString() }); // The manifests the stack made, for the manifests step, kept with the cluster. @@ -262,7 +264,7 @@ const STEP_WORK: Readonly Promise>> = manifests: async (call: StepCall): Promise => { const text: string | null = call.deps.store.file_read(call.name, 'manifests.json'); if (text === null) throw new Error('no manifests recorded: infra-apply has not been done'); - const manifests: PlatformManifest[] = JSON.parse(text) as PlatformManifest[]; + const manifests: PlatformManifest[] = platformManifests_read(text, `${call.name}: manifests.json`); await call.deps.installer.manifests_upload(ids_need(call.record()), manifests); call.log(`sent ${manifests.map((manifest: PlatformManifest): string => manifest.name).join(', ')}`); return `${manifests.length} platform manifests sent`; diff --git a/packages/stratus/src/cluster/verify.ts b/packages/stratus/src/cluster/verify.ts index 213235647..f0503f002 100644 --- a/packages/stratus/src/cluster/verify.ts +++ b/packages/stratus/src/cluster/verify.ts @@ -11,8 +11,11 @@ * * @module */ -import type { VerifyCheckModel } from '@fnndsc/menu'; +import { elements_read, verifyCheckSchema, type VerifyCheckModel } from '@fnndsc/menu'; +import { z } from 'zod'; + import type { KubeApi } from '../kube/kube.js'; +import { json_read } from '../read.js'; import type { ClusterRecord, ClusterStore } from './state.js'; /** The file `verify` keeps its checks in, beside `plan.json`. */ @@ -24,6 +27,43 @@ export interface VerifyKept { checks: VerifyCheckModel[]; } +/** The last verify's checks as this host keeps them, read back by their shape. */ +const verifyKeptSchema = z.looseObject({ at: z.string(), checks: z.array(z.unknown()) }); + +/** + * A check, or a part of a verify, that did not read, said as a check not run: what it is and why, never its content. + * + * @param name - What did not read (`#3`, `verify.json`). + * @param why - Why. + * @returns The check. + * @example + * verifyUnread_check('#3', 'name: expected string'); // { name: '#3', ok: null, detail: 'not readable: name: expected string', how: 'reads' } + */ +export function verifyUnread_check(name: string, why: string): VerifyCheckModel { + return { name, ok: null, detail: `not readable: ${why}`, how: 'reads' }; +} + +/** + * Reads the last verify this host keeps, by its shape. + * + * @param text - The kept file's text. + * @param what - What it is, for the refusal (`trial: verify.json`). + * @returns The checks and when they ran. + * @throws {ReadRefusal} When it does not read as a verify (a check that does not read is kept as one not readable). + * + * @example + * ```ts + * const verify: VerifyKept = verifyKept_read(text, `${name}: ${VERIFY_FILE}`); + * ``` + */ +export function verifyKept_read(text: string, what: string): VerifyKept { + const kept = json_read(text, verifyKeptSchema, what); + // Check by check: one that does not read is said as not readable, the rest kept. + const read = elements_read(kept.checks, verifyCheckSchema); + const unread: VerifyCheckModel[] = read.skipped.map((why: string): VerifyCheckModel => verifyUnread_check(why.split(':')[0] ?? '#?', why.slice(why.indexOf(':') + 1).trim())); + return { at: kept.at, checks: [...read.kept, ...unread] }; +} + /** The storage class ChRIS's claims use. */ export const STORAGE_CLASS: string = 'oci-bv'; diff --git a/packages/stratus/src/commands/build.ts b/packages/stratus/src/commands/build.ts index 6ebb6e33d..6890eb2f1 100644 --- a/packages/stratus/src/commands/build.ts +++ b/packages/stratus/src/commands/build.ts @@ -13,28 +13,29 @@ * * @module */ -import chalk from 'chalk'; import { hostDisk_refusal } from '@fnndsc/brasa/core'; -import { clusterLock_write } from '../cluster/keep.js'; -import { envelope_error, envelope_ok, LINE_DECLINED_MODEL_KIND, STRATUS_CLUSTER_STATE_EVENT, STRATUS_PROMPT_PURPOSES, taskState_isOver, type CommandEnvelope } from '@fnndsc/menu'; import { commandCancellation_enable, commandCancellation_signalGet, JobRefusal, repl_confirm, repl_question, repl_questionHidden, runner_get, sink_dataLine, sink_get, type JobRecord, type JobRunner, } from '@fnndsc/brasa/core'; +import { envelope_error, envelope_ok, LINE_DECLINED_MODEL_KIND, STRATUS_CLUSTER_STATE_EVENT, STRATUS_PROMPT_PURPOSES, taskState_isOver, type CommandEnvelope } from '@fnndsc/menu'; +import chalk from 'chalk'; + +import type { VerifyReach } from './verify.js'; +import type { HarborCluster } from '../checkout/harborOci.js'; +import { infraPlan_read, planCounts_alter, plan_count, planCounts_words, type CloudBuilder } from '../cloud/builder.js'; import type { CloudDriver, CloudPrice, CloudShape, FoundCluster } from '../cloud/driver.js'; -import { planCounts_alter, plan_count, planCounts_words, type CloudBuilder, type InfraPlan } from '../cloud/builder.js'; import { adoption_keep, adoptRun_make, checkout_read, type CheckoutRead } from '../cluster/adopt.js'; import { foundCluster_describe, foundRecord_make } from '../cluster/found.js'; -import type { InstallerAccountKeeper } from '../installer/account.js'; -import type { VerifyReach } from './verify.js'; -import type { HarborCluster } from '../checkout/harborOci.js'; -import type { ClusterTree } from '../vfs/clusters.js'; -import { CLUSTER_NAME, CLUSTER_TAG, type ClusterRecord, type ClusterStore } from '../cluster/state.js'; -import { clusterSpec_diff, SPEC_DEFAULT, specOptions_apply, specYaml_render, type ClusterSpec } from '../cluster/spec.js'; -import { cost_words, familyShape_find, specCostWhole_compute, specFit_read, type SpecCost, type ZoneFit } from '../cluster/sizing.js'; +import { clusterLock_write } from '../cluster/keep.js'; import { clusterSummary_read } from '../cluster/readout.js'; +import { cost_words, familyShape_find, specCostWhole_compute, specFit_read, type SpecCost, type ZoneFit } from '../cluster/sizing.js'; +import { clusterSpec_diff, SPEC_DEFAULT, specOptions_apply, specYaml_render, type ClusterSpec } from '../cluster/spec.js'; +import { CLUSTER_NAME, CLUSTER_TAG, type ClusterRecord, type ClusterStore } from '../cluster/state.js'; import { BUILD_STEPS, buildJob_id, buildRun_make, FIRST_BILLING_STEP, planRun_make, stepNext_find, STEPS_SOURCE, STEPS_WRITTEN, type BuildDeps } from '../cluster/steps.js'; +import type { InstallerAccountKeeper } from '../installer/account.js'; import { TIER_HELD, TIER_REFUSAL, tasks_granted, tierRefusal_get } from '../tier.js'; +import type { ClusterTree } from '../vfs/clusters.js'; /** What the build verbs read from the session. */ export interface BuildCommandContext { @@ -283,7 +284,7 @@ export async function clusterPlan_run(context: BuildCommandContext, named: strin } const planText: string | null = context.store.file_read(cluster.name, 'plan.json'); if (planText !== null) { - const counts = plan_count(JSON.parse(planText) as InfraPlan); + const counts = plan_count(infraPlan_read(planText, `${cluster.name}: plan.json`)); lines.push(`plan ${planCounts_words(counts)}${planCounts_alter(counts) ? chalk.red(' · an apply would touch what exists: refused unless allowed by name') : ''}`); if (record.adopted !== undefined) lines.push(chalk.gray(` adopted from ${record.adopted.from}: planned against, never built on`)); } else if (!tasks_granted() && record.adopted === undefined) { @@ -345,7 +346,7 @@ export async function job_runFollowed(id: string, label: string, run: Parameters */ async function billing_question(context: BuildCommandContext, name: string, record: ClusterRecord, spec: ClusterSpec): Promise { const planText: string | null = context.store.file_read(name, 'plan.json'); - const created: number = planText === null ? 0 : plan_count(JSON.parse(planText) as InfraPlan).create; + const created: number = planText === null ? 0 : plan_count(infraPlan_read(planText, `${name}: plan.json`)).create; const cost: SpecCost | null = await cost_read(context, record.region, spec); return `${FIRST_BILLING_STEP} creates ${created} resources. Billing starts at ${cost === null ? 'an unpriced rate' : cost_words(cost)}. Continue? [y/N]`; } diff --git a/packages/stratus/src/commands/chris.ts b/packages/stratus/src/commands/chris.ts index 2a4f14a8d..ea6503b04 100644 --- a/packages/stratus/src/commands/chris.ts +++ b/packages/stratus/src/commands/chris.ts @@ -32,28 +32,30 @@ * @module */ import * as fs from 'fs'; -import chalk from 'chalk'; -import { berthCapacity_derive, CHRIS_PROFILE_OFFERS, envelope_error, envelope_ok, LINE_DECLINED_MODEL_KIND, STRATUS_CHRIS_PLAN_MODEL_KIND, STRATUS_CHRIS_STATUS_MODEL_KIND, type ChrisProfileOffer, type ChrisStatusRow, type CommandEnvelope, STRATUS_PROMPT_PURPOSES } from '@fnndsc/menu'; + import { command_declare, declaredCommand_run, hostDisk_refusal, repl_confirm, repl_questionHidden, type CommandArguments, type CommandDeclaration, type CommandGrammar } from '@fnndsc/brasa/core'; -import type { CloudBuilder } from '../cloud/builder.js'; -import type { NetStore } from '../net/state.js'; -import type { VmSpec } from '../vm/spec.js'; -import type { BerthLimits, VmRecord, VmStore } from '../vm/state.js'; -import type { VmRemote } from '../vm/remote.js'; -import type { BuildCall } from '../cloud/builder.js'; -import { BERTH_LIMITS_DEFAULT, CHRIS_PROFILES, floor_short, type ChrisProfile } from '../chris/profiles.js'; -import { VM_KEYLESS, vmKeyless_is } from '../vm/keep.js'; -import { launcherSecret_ensure, porterSecret_ensure, secret_make, secrets_ensure, secrets_read } from '../chris/secrets.js'; -import { CHRIS_JOBS, chrisDeployRun_make, type DeployDeps } from '../chris/deploy.js'; -import { host_split, point_plan, pointPlan_words, POINT_TTL, type Registrar } from '../chris/registrar.js'; -import { ALL_USERS, chrisUserAddRun_make, chrisUserModRun_make, EMAIL, GROUP_NAME, USER_JOBS, USER_NAME, type UserAddResult, type UserAnswer, type UserModAsk } from '../chris/users.js'; -import { CHRIS_ADMIN, chrisPasswdRun_make, PASSWD_JOBS, type PasswdResult } from '../chris/passwd.js'; +import { berthCapacity_derive, CHRIS_PROFILE_OFFERS, envelope_error, envelope_ok, LINE_DECLINED_MODEL_KIND, STRATUS_CHRIS_PLAN_MODEL_KIND, STRATUS_CHRIS_STATUS_MODEL_KIND, type ChrisProfileOffer, type ChrisStatusRow, type CommandEnvelope, STRATUS_PROMPT_PURPOSES } from '@fnndsc/menu'; +import chalk from 'chalk'; + import { job_runFollowed } from './build.js'; import { flags_map } from './declared.js'; -import { tierRefusal_get } from '../tier.js'; +import { CHRIS_JOBS, chrisDeployRun_make, type DeployDeps } from '../chris/deploy.js'; import { chrisLive_read, type ChrisLive, type HttpGet } from '../chris/live.js'; +import { CHRIS_ADMIN, chrisPasswdRun_make, PASSWD_JOBS, type PasswdResult } from '../chris/passwd.js'; import { berthLimits_words, chrisPlan_derive, chrisPlan_words, type ChrisPlan } from '../chris/plan.js'; import { chrisPluginApplyRun_make, chrisPluginPlanRun_make, PLUGIN_JOBS, PLUGIN_REF, PLUGIN_SOURCE, PLUGIN_SYNC_CHELL_MIN, pluginPlanAdds_count, pluginPlanStanding_words, pluginSyncQuestion_words, type PluginApplyResult, type PluginPlanRead, type PluginPlanResult, type PluginSyncAsk } from '../chris/plugins.js'; +import { BERTH_LIMITS_DEFAULT, CHRIS_PROFILES, floor_short, type ChrisProfile } from '../chris/profiles.js'; +import { host_split, point_plan, pointPlan_words, POINT_TTL, type Registrar } from '../chris/registrar.js'; +import { launcherSecret_ensure, porterSecret_ensure, secret_make, secrets_ensure, secrets_read } from '../chris/secrets.js'; +import { ALL_USERS, chrisUserAddRun_make, chrisUserModRun_make, EMAIL, GROUP_NAME, USER_JOBS, USER_NAME, type UserAddResult, type UserAnswer, type UserModAsk } from '../chris/users.js'; +import type { BuildCall } from '../cloud/builder.js'; +import type { CloudBuilder } from '../cloud/builder.js'; +import type { NetStore } from '../net/state.js'; +import { tierRefusal_get } from '../tier.js'; +import { VM_KEYLESS, vmKeyless_is } from '../vm/keep.js'; +import type { VmRemote } from '../vm/remote.js'; +import type { VmSpec } from '../vm/spec.js'; +import type { BerthLimits, VmRecord, VmStore } from '../vm/state.js'; /** What `chris` reads from the session. */ export interface ChrisCommandContext { diff --git a/packages/stratus/src/commands/net.ts b/packages/stratus/src/commands/net.ts index 3174a24d3..c1019b43d 100644 --- a/packages/stratus/src/commands/net.ts +++ b/packages/stratus/src/commands/net.ts @@ -13,17 +13,18 @@ * * @module */ -import chalk from 'chalk'; -import { envelope_error, envelope_ok, LINE_DECLINED_MODEL_KIND, STRATUS_NET_STATUS_MODEL_KIND, STRATUS_PROMPT_PURPOSES, type CommandEnvelope, type NetStatusRow } from '@fnndsc/menu'; import { command_declare, declaredCommand_run, repl_confirm, repl_question, type CommandArguments, type CommandDeclaration, type CommandGrammar } from '@fnndsc/brasa/core'; -import { plan_count, planCounts_alter, planCounts_words, type CloudBuilder, type InfraPlan, type PlanCounts } from '../cloud/builder.js'; +import { envelope_error, envelope_ok, LINE_DECLINED_MODEL_KIND, STRATUS_NET_STATUS_MODEL_KIND, STRATUS_PROMPT_PURPOSES, type CommandEnvelope, type NetStatusRow } from '@fnndsc/menu'; +import chalk from 'chalk'; + +import { job_runFollowed } from './build.js'; +import { infraPlan_read, plan_count, planCounts_alter, planCounts_words, type CloudBuilder, type InfraPlan, type PlanCounts } from '../cloud/builder.js'; import type { CloudDriver } from '../cloud/driver.js'; +import { NET_JOBS, netApplyRun_make, netPlanRun_make, netTeardownRun_make, standing_words, type NetDeps } from '../net/build.js'; import { cidr_read, NET_RESOURCES, netSpec_diff, subnet_derive, type NetSpec } from '../net/spec.js'; import { NET_NAME, type NetRecord, type NetStore } from '../net/state.js'; -import { netsFound_read, type FoundNet } from '../vm/found.js'; -import { NET_JOBS, netApplyRun_make, netPlanRun_make, netTeardownRun_make, standing_words, type NetDeps } from '../net/build.js'; -import { job_runFollowed } from './build.js'; import { TIER_REFUSAL, tasks_granted, tierRefusal_get } from '../tier.js'; +import { netsFound_read, type FoundNet } from '../vm/found.js'; /** What `net` reads from the session. */ export interface NetCommandContext { @@ -230,7 +231,7 @@ function netNew_run(context: NetCommandContext, name: string, cidrText: string | function planKept_read(context: NetCommandContext, name: string): { plan: InfraPlan; counts: PlanCounts } | null { const text: string | null = context.store.file_read(name, 'plan.json'); if (text === null) return null; - const plan: InfraPlan = JSON.parse(text) as InfraPlan; + const plan: InfraPlan = infraPlan_read(text, `${name}: plan.json`); return { plan, counts: plan_count(plan) }; } diff --git a/packages/stratus/src/commands/protect.ts b/packages/stratus/src/commands/protect.ts index e1f6d2204..e80294999 100644 --- a/packages/stratus/src/commands/protect.ts +++ b/packages/stratus/src/commands/protect.ts @@ -11,12 +11,13 @@ * * @module */ -import chalk from 'chalk'; import { envelope_error, envelope_ok, type CommandEnvelope } from '@fnndsc/menu'; -import type { ClusterRecord } from '../cluster/state.js'; +import chalk from 'chalk'; + +import type { BuildCommandContext } from './build.js'; import { clusterLock_refresh, clusterLock_write } from '../cluster/keep.js'; +import type { ClusterRecord } from '../cluster/state.js'; import { lock_where } from '../kept/lock.js'; -import type { BuildCommandContext } from './build.js'; import { tasks_granted } from '../tier.js'; /** diff --git a/packages/stratus/src/commands/teardown.ts b/packages/stratus/src/commands/teardown.ts index ade612703..ad616a09d 100644 --- a/packages/stratus/src/commands/teardown.ts +++ b/packages/stratus/src/commands/teardown.ts @@ -5,20 +5,22 @@ * @module */ import { readFileSync } from 'node:fs'; -import chalk from 'chalk'; -import { envelope_error, envelope_ok, STRATUS_PROMPT_PURPOSES, type CommandEnvelope } from '@fnndsc/menu'; + import { repl_question, sink_dataLine } from '@fnndsc/brasa/core'; +import { envelope_error, envelope_ok, STRATUS_PROMPT_PURPOSES, type CommandEnvelope } from '@fnndsc/menu'; +import chalk from 'chalk'; + +import { clusterState_show, job_runFollowed, type BuildCommandContext } from './build.js'; +import { verifyReach_default } from './verify.js'; import type { HarborCluster } from '../checkout/harborOci.js'; +import { TEARDOWN_STEPS, type TeardownStep } from '../cloud/builder.js'; import { foundClusters_describe, foundRecord_make } from '../cluster/found.js'; import { clusterLock_refresh } from '../cluster/keep.js'; import { SPEC_DEFAULT } from '../cluster/spec.js'; -import { TEARDOWN_STEPS, type TeardownStep } from '../cloud/builder.js'; +import { HOURS_PER_MONTH, money_words, spend_read } from '../cluster/spend.js'; import type { ClusterRecord, TeardownStepRecord } from '../cluster/state.js'; import { teardownJob_id } from '../cluster/steps.js'; -import { HOURS_PER_MONTH, money_words, spend_read } from '../cluster/spend.js'; import { clusterVolumes_read, teardownRun_make } from '../cluster/teardown.js'; -import { clusterState_show, job_runFollowed, type BuildCommandContext } from './build.js'; -import { verifyReach_default } from './verify.js'; import { tierRefusal_get } from '../tier.js'; /** diff --git a/packages/stratus/src/commands/vm.ts b/packages/stratus/src/commands/vm.ts index 55fdd2f2a..ab8f1ed0d 100644 --- a/packages/stratus/src/commands/vm.ts +++ b/packages/stratus/src/commands/vm.ts @@ -22,29 +22,30 @@ * * @module */ -import chalk from 'chalk'; -import { envelope_error, envelope_ok, LINE_DECLINED_MODEL_KIND, taskState_isOver, STRATUS_VM_LIMITS_MODEL_KIND, STRATUS_VM_STATE_EVENT, STRATUS_VM_STATUS_MODEL_KIND, type CommandEnvelope, type VmState, type VmStatusRow, STRATUS_PROMPT_PURPOSES, STRATUS_VM_STEP_EVENT, type VmStepEvent } from '@fnndsc/menu'; import { command_declare, declaredCommand_run, hostProcess_refusal, repl_confirm, repl_question, runner_get, sink_dataLine, sink_get, type CommandArguments, type CommandDeclaration, type CommandGrammar } from '@fnndsc/brasa/core'; -import { plan_count, planCounts_words, type BuildCall, type CloudBuilder, type InfraPlan, type PlanCounts } from '../cloud/builder.js'; -import { keepFailure_describe } from '../cloud/keepFault.js'; -import type { VmRemote } from '../vm/remote.js'; -import { sshArgs_build } from '../vm/remote.js'; -import { vmPorts_open as vmPorts_openOf, vmLimits_derive, vmLimits_lines, vmSpec_dataLoss, vmSpec_diff, vmSpec_read, vmSsh_words, sshKeyFile_resolve, type VmSpec } from '../vm/spec.js'; -import { VM_HOST_JOB, vmHost_current, vmHost_owed, vmHostRun_make } from '../vm/host.js'; -import type { CloudShape } from '../cloud/driver.js'; -import { CHRIS_PORTER_TAG, CHRIS_URL_TAG, VM_NAME, type VmRecord, type VmStore } from '../vm/state.js'; -import { vmsFound_read, vmTakeover_run, type FoundVm } from '../vm/found.js'; -import { VM_KEYLESS, vmKey_held, vmKeyless_is, vmKept_read, vmKept_write, vmLock_adopt } from '../vm/keep.js'; -import { lock_read, lock_where, lockKept_is } from '../kept/lock.js'; -import { cost_words, planFile_derive, VM_JOBS, vmApplyRun_make, vmNet_read, vmPlanRun_make, vmTeardownRun_make, type VmCost, type VmDeps, type VmPart } from '../vm/build.js'; +import { envelope_error, envelope_ok, LINE_DECLINED_MODEL_KIND, taskState_isOver, STRATUS_VM_LIMITS_MODEL_KIND, STRATUS_VM_STATE_EVENT, STRATUS_VM_STATUS_MODEL_KIND, type CommandEnvelope, type VmState, type VmStatusRow, STRATUS_PROMPT_PURPOSES, STRATUS_VM_STEP_EVENT, type VmStepEvent } from '@fnndsc/menu'; +import chalk from 'chalk'; + import { job_runFollowed } from './build.js'; import { flags_map } from './declared.js'; +import { cost_line, cost_read, costChange_words, vmCost_run } from './vmCost.js'; +import { infraPlan_read, plan_count, planCounts_words, type BuildCall, type CloudBuilder, type InfraPlan, type PlanCounts } from '../cloud/builder.js'; +import type { CloudShape } from '../cloud/driver.js'; +import { keepFailure_describe } from '../cloud/keepFault.js'; import { STEPS_SOURCE } from '../cluster/steps.js'; -import { VM_GROW_JOB, vmGrowRun_make, vmPlan_judge, type VmPlanJudged } from '../vm/resize.js'; +import { lock_read, lock_where, lockKept_is } from '../kept/lock.js'; import { tasks_granted, tierRefusal_get } from '../tier.js'; +import { cost_words, planFile_derive, VM_JOBS, vmApplyRun_make, vmNet_read, vmPlanRun_make, vmTeardownRun_make, type VmCost, type VmDeps, type VmPart } from '../vm/build.js'; +import { vmsFound_read, vmTakeover_run, type FoundVm } from '../vm/found.js'; +import { VM_HOST_JOB, vmHost_current, vmHost_owed, vmHostRun_make } from '../vm/host.js'; +import { VM_KEYLESS, vmKey_held, vmKeyless_is, vmKept_read, vmKept_write, vmLock_adopt } from '../vm/keep.js'; import { shWord_write } from '../vm/quoting.js'; +import type { VmRemote } from '../vm/remote.js'; +import { sshArgs_build } from '../vm/remote.js'; +import { VM_GROW_JOB, vmGrowRun_make, vmPlan_judge, type VmPlanJudged } from '../vm/resize.js'; +import { vmPorts_open as vmPorts_openOf, vmLimits_derive, vmLimits_lines, vmSpec_dataLoss, vmSpec_diff, vmSpec_read, vmSsh_words, sshKeyFile_resolve, type VmSpec } from '../vm/spec.js'; +import { CHRIS_PORTER_TAG, CHRIS_URL_TAG, VM_NAME, type VmRecord, type VmStore } from '../vm/state.js'; import { vmCache_reconcile, vmStands_refresh, type VmTenancyContext } from '../vm/truth.js'; -import { cost_line, cost_read, costChange_words, vmCost_run } from './vmCost.js'; /** What `vm` reads from the session: the tenancy's, and how a VM is reached. */ export interface VmCommandContext extends VmTenancyContext { @@ -521,7 +522,7 @@ async function vmPlan_run(context: VmCommandContext, named: string | undefined): function planKept_read(context: VmCommandContext, name: string, part: VmPart): { plan: InfraPlan; counts: PlanCounts } | null { const text: string | null = context.store.file_read(name, planFile_derive(part)); if (text === null) return null; - const plan: InfraPlan = JSON.parse(text) as InfraPlan; + const plan: InfraPlan = infraPlan_read(text, `${name}: ${planFile_derive(part)}`); return { plan, counts: plan_count(plan) }; } diff --git a/packages/stratus/src/installer/assisted.ts b/packages/stratus/src/installer/assisted.ts index f1a12797d..b6df5009d 100644 --- a/packages/stratus/src/installer/assisted.ts +++ b/packages/stratus/src/installer/assisted.ts @@ -12,7 +12,29 @@ * * @module */ +import { z } from 'zod'; + import type { Installer, InstallerCredentials, InstallerHost, InstallerIds, InstallStatus, PlatformManifest } from './installer.js'; +import { json_read, jsonRows_read } from '../read.js'; + +/** + * What Red Hat's answers read as: the fields stratus reads, the rest kept. + * A field Red Hat answers as null today is taken as absent (a cluster's + * `status_info`, its `progress` and `total_percentage` while it is new). + */ +export const ASSISTED_ANSWERS = { + token: z.looseObject({ access_token: z.string(), expires_in: z.number() }), + error: z.looseObject({ reason: z.string().nullish() }), + pullSecret: z.looseObject({ auths: z.record(z.string(), z.unknown()).nullish() }), + made: z.looseObject({ id: z.string() }), + // Only what the duplicate check compares, of any type: a row is never left out of it for a field it does not read. + clusterListed: z.looseObject({ name: z.unknown().optional(), base_dns_domain: z.unknown().optional() }), + image: z.looseObject({ url: z.string(), expires_at: z.string().nullish() }), + manifestListed: z.looseObject({ folder: z.string(), file_name: z.string() }), + host: z.looseObject({ id: z.string(), requested_hostname: z.string().nullish(), status: z.string(), role: z.string().nullish(), created_at: z.string().nullish() }), + cluster: z.looseObject({ status: z.string(), status_info: z.string().nullish(), progress: z.looseObject({ total_percentage: z.number().nullish() }).nullish() }), + credentials: z.looseObject({ username: z.string(), password: z.string(), console_url: z.string() }), +}; /** Red Hat's token endpoint. */ export const RED_HAT_SSO_URL: string = 'https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token'; @@ -84,7 +106,7 @@ export class AssistedInstaller implements Installer { const answer = await this.fetchFn(RED_HAT_SSO_URL, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body }); const text: string = await answer.text(); if (answer.status !== 200) throw new InstallerError(answer.status, `Red Hat token: HTTP ${answer.status}`); - const json = JSON.parse(text) as { access_token: string; expires_in: number }; + const json = json_read(text, ASSISTED_ANSWERS.token, 'Red Hat token'); this.token = { value: json.access_token, until: Date.now() + json.expires_in * 1000 }; return this.token.value; } @@ -106,9 +128,10 @@ export class AssistedInstaller implements Installer { }); const text: string = await answer.text(); if (!ok.includes(answer.status)) { - let reason: string = text.slice(0, 200); - try { reason = (JSON.parse(text) as { reason?: string }).reason ?? reason; } catch { /* not JSON */ } - throw new InstallerError(answer.status, `${method} ${url.replace(ASSISTED_API, '')}: HTTP ${answer.status}: ${reason}`); + // Red Hat's reason alone, when it words one: never the rest of the answer, which may carry what was sent. + let reason: string | null = null; + try { reason = json_read(text, ASSISTED_ANSWERS.error, 'Red Hat refusal').reason ?? null; } catch { /* no reason worded: the call and its status alone */ } + throw new InstallerError(answer.status, `${method} ${url.replace(ASSISTED_API, '')}: HTTP ${String(answer.status)}${reason === null ? '' : `: ${reason}`}`); } return text; } @@ -116,38 +139,39 @@ export class AssistedInstaller implements Installer { /** The account's pull secret, fetched now and never kept. */ private async pullSecret_get(): Promise { const text: string = await this.call('POST', `${OCM_API}/api/accounts_mgmt/v1/access_token`, [200], {}); - const secret = JSON.parse(text) as { auths?: Record }; - if (secret.auths === undefined || Object.keys(secret.auths).length === 0) throw new Error('Red Hat gave no pull secret for this account'); + const secret = json_read(text, ASSISTED_ANSWERS.pullSecret, 'Red Hat pull secret'); + if (secret.auths === undefined || secret.auths === null || Object.keys(secret.auths).length === 0) throw new Error('Red Hat gave no pull secret for this account'); return text; } async cluster_create(request: { name: string; baseDomain: string; version: string; controlPlaneCount: number }): Promise { - const existing = JSON.parse(await this.call('GET', `${ASSISTED_API}/clusters`, [200])) as Array<{ id: string; name: string; base_dns_domain: string }>; + // Row by row: every object Red Hat lists is compared, whatever else it carries. + const existing = jsonRows_read(await this.call('GET', `${ASSISTED_API}/clusters`, [200]), ASSISTED_ANSWERS.clusterListed, 'GET /clusters').kept; if (existing.some((cluster): boolean => cluster.name === request.name && cluster.base_dns_domain === request.baseDomain)) { throw new Error(`a cluster ${request.name}.${request.baseDomain} already exists at Red Hat that this cluster did not record`); } const pullSecret: string = await this.pullSecret_get(); const sshPublicKey: string = this.options.sshPublicKey().trim(); - const cluster = JSON.parse(await this.call('POST', `${ASSISTED_API}/clusters`, [201], { + const cluster = json_read(await this.call('POST', `${ASSISTED_API}/clusters`, [201], { name: request.name, base_dns_domain: request.baseDomain, openshift_version: request.version, cpu_architecture: 'x86_64', high_availability_mode: 'Full', control_plane_count: request.controlPlaneCount, user_managed_networking: true, platform: { type: 'external', external: { platform_name: 'oci', cloud_controller_manager: 'External' } }, pull_secret: pullSecret, ssh_public_key: sshPublicKey, - })) as { id: string }; - const infraEnv = JSON.parse(await this.call('POST', `${ASSISTED_API}/infra-envs`, [201], { + }), ASSISTED_ANSWERS.made, 'POST /clusters'); + const infraEnv = json_read(await this.call('POST', `${ASSISTED_API}/infra-envs`, [201], { name: `${request.name}-infra-env`, cluster_id: cluster.id, pull_secret: pullSecret, ssh_authorized_key: sshPublicKey, image_type: 'minimal-iso', cpu_architecture: 'x86_64', openshift_version: request.version, - })) as { id: string }; + }), ASSISTED_ANSWERS.made, 'POST /infra-envs'); return { clusterId: cluster.id, infraEnvId: infraEnv.id }; } async isoUrl_get(ids: InstallerIds): Promise<{ url: string; expires: string }> { - const image = JSON.parse(await this.call('GET', `${ASSISTED_API}/infra-envs/${ids.infraEnvId}/downloads/image-url`, [200])) as { url: string; expires_at: string }; - return { url: image.url, expires: image.expires_at }; + const image = json_read(await this.call('GET', `${ASSISTED_API}/infra-envs/${ids.infraEnvId}/downloads/image-url`, [200]), ASSISTED_ANSWERS.image, 'GET /infra-envs/…/image-url'); + return { url: image.url, expires: image.expires_at ?? '' }; } async manifests_upload(ids: InstallerIds, manifests: ReadonlyArray): Promise { - const existing = JSON.parse(await this.call('GET', `${ASSISTED_API}/clusters/${ids.clusterId}/manifests`, [200])) as Array<{ folder: string; file_name: string }>; + const existing = jsonRows_read(await this.call('GET', `${ASSISTED_API}/clusters/${ids.clusterId}/manifests`, [200]), ASSISTED_ANSWERS.manifestListed, 'GET /clusters/…/manifests').kept; for (const manifest of manifests) { if (existing.some((entry): boolean => entry.folder === 'manifests' && entry.file_name === manifest.name)) { await this.call('DELETE', `${ASSISTED_API}/clusters/${ids.clusterId}/manifests?folder=manifests&file_name=${encodeURIComponent(manifest.name)}`, [200, 204, 404]); @@ -157,7 +181,8 @@ export class AssistedInstaller implements Installer { } async hosts_list(ids: InstallerIds): Promise { - const hosts = JSON.parse(await this.call('GET', `${ASSISTED_API}/infra-envs/${ids.infraEnvId}/hosts`, [200])) as Array<{ id: string; requested_hostname?: string; status: string; role?: string; created_at?: string }>; + // Row by row: a host that does not read is left out, the hosts that do are drawn. + const hosts = jsonRows_read(await this.call('GET', `${ASSISTED_API}/infra-envs/${ids.infraEnvId}/hosts`, [200]), ASSISTED_ANSWERS.host, 'GET /infra-envs/…/hosts').kept; return hosts.map((host): InstallerHost => ({ id: host.id, name: (host.requested_hostname ?? host.id).split('.')[0] as string, @@ -177,7 +202,7 @@ export class AssistedInstaller implements Installer { } async install_status(ids: InstallerIds): Promise { - const cluster = JSON.parse(await this.call('GET', `${ASSISTED_API}/clusters/${ids.clusterId}`, [200])) as { status: string; status_info?: string; progress?: { total_percentage?: number } }; + const cluster = json_read(await this.call('GET', `${ASSISTED_API}/clusters/${ids.clusterId}`, [200]), ASSISTED_ANSWERS.cluster, 'GET /clusters/…'); const percent: number = cluster.progress?.total_percentage ?? 0; const note: string = cluster.status_info ?? cluster.status; if (cluster.status === 'installed') return { state: 'installed', percent: 100, note }; @@ -192,7 +217,7 @@ export class AssistedInstaller implements Installer { } async credentials_get(ids: InstallerIds): Promise { - const credentials = JSON.parse(await this.call('GET', `${ASSISTED_API}/clusters/${ids.clusterId}/credentials`, [200])) as { username: string; password: string; console_url: string }; + const credentials = json_read(await this.call('GET', `${ASSISTED_API}/clusters/${ids.clusterId}/credentials`, [200]), ASSISTED_ANSWERS.credentials, 'GET /clusters/…/credentials'); return { username: credentials.username, password: credentials.password, consoleUrl: credentials.console_url }; } @@ -202,7 +227,8 @@ export class AssistedInstaller implements Installer { // infra-env, then the cluster. Each is gone already when it answers 404, // which is what lets a teardown that stopped part way run again. const listed: string = await this.call('GET', `${ASSISTED_API}/infra-envs/${ids.infraEnvId}/hosts`, [200, 404]); - const hosts = (listed.trim().startsWith('[') ? JSON.parse(listed) : []) as Array<{ id: string }>; + // Gone already (404) lists none; a host that does not read is left out, the rest removed. + const hosts = listed.trim().startsWith('[') ? jsonRows_read(listed, ASSISTED_ANSWERS.made, 'GET /infra-envs/…/hosts').kept : []; for (const host of hosts) await this.call('DELETE', `${ASSISTED_API}/infra-envs/${ids.infraEnvId}/hosts/${host.id}`, [204, 404]); await this.call('DELETE', `${ASSISTED_API}/infra-envs/${ids.infraEnvId}`, [204, 404]); await this.call('DELETE', `${ASSISTED_API}/clusters/${ids.clusterId}`, [204, 404]); diff --git a/packages/stratus/src/installer/installer.ts b/packages/stratus/src/installer/installer.ts index 9ace3ad41..d8ded055f 100644 --- a/packages/stratus/src/installer/installer.ts +++ b/packages/stratus/src/installer/installer.ts @@ -11,6 +11,9 @@ * * @module */ +import { z } from 'zod'; + +import { json_read } from '../read.js'; /** The installer's handles on a cluster. */ export interface InstallerIds { @@ -50,6 +53,24 @@ export interface PlatformManifest { content: string; } +/** + * Reads the platform manifests a cluster keeps on this host, whole: one that + * does not read refuses them all, so none is sent short. + * + * @param text - The kept file's text. + * @param what - What it is, for the refusal (`trial: manifests.json`). + * @returns The manifests. + * @throws {ReadRefusal} When they do not read. + * + * @example + * ```ts + * const manifests: PlatformManifest[] = platformManifests_read(text, `${name}: manifests.json`); + * ``` + */ +export function platformManifests_read(text: string, what: string): PlatformManifest[] { + return json_read(text, z.array(z.object({ name: z.string(), content: z.string() })), what); +} + /** The cluster's administrator sign-in, kept on the host only. */ export interface InstallerCredentials { username: string; diff --git a/packages/stratus/src/kept/lock.ts b/packages/stratus/src/kept/lock.ts index fd7203b18..9b6b3b24f 100644 --- a/packages/stratus/src/kept/lock.ts +++ b/packages/stratus/src/kept/lock.ts @@ -10,6 +10,7 @@ * * @module */ +import { z } from 'zod'; /** A lock, with when it was set. */ export interface KeptLock { @@ -17,6 +18,9 @@ export interface KeptLock { readonly at: string; } +/** A lock as a keep in the tenancy carries it, read back by its shape. */ +export const keptLockSchema = z.looseObject({ protected: z.boolean(), at: z.string() }); + /** What a record keeps of its lock. */ export interface LockedRecord { created: string; diff --git a/packages/stratus/src/kept/specStore.ts b/packages/stratus/src/kept/specStore.ts index 77bd65ec7..c2b7222ea 100644 --- a/packages/stratus/src/kept/specStore.ts +++ b/packages/stratus/src/kept/specStore.ts @@ -23,6 +23,10 @@ import * as fs from 'fs'; import * as path from 'path'; +import { z } from 'zod'; + +import { json_read, ReadRefusal } from '../read.js'; + /** What every kept record carries. */ export interface KeptRecord { name: string; @@ -60,6 +64,17 @@ export function file_writeAtomic(file: string, text: string): void { */ const RECORD_NOUNS: WeakMap string> = new WeakMap(); +/** + * What every kept record's `state.json` must read as: what it keeps, when it + * was made, where, when last declared. The rest is the store's, kept. + */ +export const keptRecordSchema = z.looseObject({ + name: z.string(), + created: z.string(), + region: z.string(), + declared: z.string().optional(), +}); + /** * The folders a daemon keeps one kind of thing in, on its host: one folder * per name, its record in `state.json` written whole and owner-only, its own @@ -69,8 +84,9 @@ export abstract class KeptFolders { /** * @param root - The folder they live in. * @param recordNoun - What is kept, in a word (`cluster`, `network`), for the refusals; read only when one is made. + * @param recordSchema - What its `state.json` must read as: every field the store reads, by type; the rest kept. */ - constructor(readonly root: string, recordNoun: () => string) { + constructor(readonly root: string, recordNoun: () => string, readonly recordSchema: z.ZodType) { RECORD_NOUNS.set(this, recordNoun); } @@ -95,11 +111,16 @@ export abstract class KeptFolders { * * @param name - Its name. * @returns Its record, or null when none is kept. + * @throws {ReadRefusal} When its `state.json` does not read as the store's record, or names another: refused by the file, never quoted. */ record_read(name: string): Record | null { const file: string = path.join(this.folder_derive(name), 'state.json'); if (!fs.existsSync(file)) return null; - return JSON.parse(fs.readFileSync(file, 'utf-8')) as Record; + // Read by shape: a state that does not read is refused by its file, not failing later as `undefined`. + const record: Record = json_read(fs.readFileSync(file, 'utf-8'), this.recordSchema, file); + // A record naming another would be written back to that other's folder. + if (record.name !== name) throw new ReadRefusal(file, 'name: names another'); + return record; } /** @@ -156,10 +177,11 @@ export class SpecStore extends KeptFolders) { + constructor(root: string, protected readonly codec: SpecCodec, recordSchema: z.ZodType) { // The codec's noun, read only when a refusal says it. - super(root, (): string => codec.noun); + super(root, (): string => codec.noun, recordSchema); } /** diff --git a/packages/stratus/src/kube/chris.ts b/packages/stratus/src/kube/chris.ts index 6a5e6136a..5c83edc50 100644 --- a/packages/stratus/src/kube/chris.ts +++ b/packages/stratus/src/kube/chris.ts @@ -21,9 +21,12 @@ import { randomBytes } from 'node:crypto'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; + +import { z } from 'zod'; + import { KubeError, type KubeApi } from './kube.js'; -import { cpuFree_read } from '../cluster/verify.js'; import type { ClusterSpec } from '../cluster/spec.js'; +import { cpuFree_read } from '../cluster/verify.js'; /** What is installed, and as whom the smoke journey logs in; `harbor-oci`'s pins. */ export interface ChrisRelease { @@ -449,13 +452,13 @@ export function seedJob_build(release: ChrisRelease, timeoutSeconds: number): un }; } -/** The verdict `chris_smoke` prints last, as far as it is read. */ -interface SmokeVerdict { - verdict?: string; - failed_step?: string | null; - duration_s?: number; - steps?: Array<{ name: string; ok: boolean }>; -} +/** The verdict `chris_smoke` prints last: its verdict read by type, the rest only when it is of the type the words use (a null timing is no timing). */ +const smokeVerdictSchema = z.looseObject({ + verdict: z.string(), + failed_step: z.unknown().optional(), + duration_s: z.unknown().optional(), + steps: z.unknown().optional(), +}); /** * The journey's last line in a few words: `chris_smoke` ends with its verdict @@ -466,14 +469,17 @@ interface SmokeVerdict { * @returns The words. */ export function smokeVerdict_words(line: string): string { - let verdict: SmokeVerdict; + let data: unknown; try { - verdict = JSON.parse(line) as SmokeVerdict; + data = JSON.parse(line) as unknown; } catch { return line; } - if (typeof verdict !== 'object' || verdict === null || typeof verdict.verdict !== 'string') return line; - const steps: number = verdict.steps?.length ?? 0; + // Read by its shape: a line that is no verdict is kept as it is. + const read = smokeVerdictSchema.safeParse(data); + if (!read.success) return line; + const verdict = read.data; + const steps: number = Array.isArray(verdict.steps) ? verdict.steps.length : 0; const failed: string = typeof verdict.failed_step === 'string' ? ` · failed at ${verdict.failed_step}` : ''; const seconds: string = typeof verdict.duration_s === 'number' ? ` · ${Math.round(verdict.duration_s)} s` : ''; return `${verdict.verdict} · ${steps} step${steps === 1 ? '' : 's'}${failed}${seconds}`; diff --git a/packages/stratus/src/kube/kubeHttp.ts b/packages/stratus/src/kube/kubeHttp.ts index c5ab35175..d1bdbe57d 100644 --- a/packages/stratus/src/kube/kubeHttp.ts +++ b/packages/stratus/src/kube/kubeHttp.ts @@ -6,7 +6,14 @@ * @module */ import { request } from 'node:https'; + +import { z } from 'zod'; + import { KubeError, type KubeAccess, type KubeApi } from './kube.js'; +import { json_read } from '../read.js'; + +/** A Kubernetes Status as a busy answer carries it: how long it asks to be waited. */ +const kubeStatusSchema = z.looseObject({ details: z.looseObject({ retryAfterSeconds: z.number().optional() }).optional() }); /** How long one call may take, in milliseconds. */ const KUBE_TIMEOUT_MS: number = 30_000; @@ -23,8 +30,8 @@ const BUSY_TRIES: number = 10; export function busyWait_parse(text: string): number { let seconds: number = 2; try { - const asked: unknown = (JSON.parse(text) as { details?: { retryAfterSeconds?: unknown } }).details?.retryAfterSeconds; - if (typeof asked === 'number') seconds = asked; + const asked: number | undefined = kubeStatusSchema.safeParse(JSON.parse(text) as unknown).data?.details?.retryAfterSeconds; + if (asked !== undefined) seconds = asked; } catch { // Not a Status: the default. } @@ -85,9 +92,10 @@ export function kubeApi_make(access: KubeAccess): KubeApi { return answer.text; }; return { - json_get: async (path: string): Promise => JSON.parse(await ok('GET', path)) as unknown, + // Parsed by name: an answer that is no JSON is refused as `GET `, never quoted (a secret's answer holds it). + json_get: async (path: string): Promise => json_read(await ok('GET', path), z.unknown(), `GET ${path}`), text_get: (path: string): Promise => ok('GET', path), - json_post: async (path: string, body: unknown): Promise => JSON.parse(await ok('POST', path, body)) as unknown, + json_post: async (path: string, body: unknown): Promise => json_read(await ok('POST', path, body), z.unknown(), `POST ${path}`), delete: async (path: string): Promise => { await ok('DELETE', path); }, }; } diff --git a/packages/stratus/src/net/build.ts b/packages/stratus/src/net/build.ts index 751ee1160..33e20a8d0 100644 --- a/packages/stratus/src/net/build.ts +++ b/packages/stratus/src/net/build.ts @@ -10,10 +10,11 @@ * @module */ import type { JobContext, JobRun } from '@fnndsc/brasa/core'; -import type { CloudDriver, ResourceCounts } from '../cloud/driver.js'; -import { plan_count, planCounts_words, type BuildCall, type CloudBuilder, type InfraPlan } from '../cloud/builder.js'; -import { NET_TAG, type NetRecord, type NetStore } from './state.js'; + import type { NetSpec } from './spec.js'; +import { NET_TAG, type NetRecord, type NetStore } from './state.js'; +import { infraPlan_read, plan_count, planCounts_words, type BuildCall, type CloudBuilder, type InfraPlan } from '../cloud/builder.js'; +import type { CloudDriver, ResourceCounts } from '../cloud/driver.js'; /** What a network's jobs run over. */ export interface NetDeps { @@ -140,7 +141,7 @@ export function netApplyRun_make(name: string, deps: NetDeps): JobRun { const { record } = net_read(deps.store, name); const planText: string | null = deps.store.file_read(name, 'plan.json'); if (planText === null || record.stackRef === undefined) throw new Error(`${name}: no plan to apply (net build ${name} makes one)`); - const plan: InfraPlan = JSON.parse(planText) as InfraPlan; + const plan: InfraPlan = infraPlan_read(planText, `${name}: plan.json`); const outputs: Record = await builder.moduleApply_run({ region: record.region, stackRef: record.stackRef, plan, label: name }, call_make(context)); const built = deps.store.spec_read(name); deps.store.record_update(name, (current: NetRecord): void => { current.outputs = outputs; current.built = new Date().toISOString(); if (built !== null && 'spec' in built) current.builtCidr = built.spec.cidr; delete current.gone; }); diff --git a/packages/stratus/src/net/state.ts b/packages/stratus/src/net/state.ts index 4cc85d577..d02f99cc4 100644 --- a/packages/stratus/src/net/state.ts +++ b/packages/stratus/src/net/state.ts @@ -10,7 +10,7 @@ import * as os from 'os'; import * as path from 'path'; import { netSpecYaml_parse, netSpecYaml_render, type NetSpec } from './spec.js'; -import { SpecStore, type KeptRecord } from '../kept/specStore.js'; +import { keptRecordSchema, SpecStore, type KeptRecord } from '../kept/specStore.js'; /** * What `state.json` holds: the network's name (and its place's, an OCI @@ -60,6 +60,6 @@ export class NetStore extends SpecStore { * @param root - The folder the networks live in. */ constructor(root: string) { - super(root, { noun: 'network', render: netSpecYaml_render, parse: netSpecYaml_parse }); + super(root, { noun: 'network', render: netSpecYaml_render, parse: netSpecYaml_parse }, keptRecordSchema); } } diff --git a/packages/stratus/src/read.ts b/packages/stratus/src/read.ts new file mode 100644 index 000000000..fa464fa8f --- /dev/null +++ b/packages/stratus/src/read.ts @@ -0,0 +1,126 @@ +/** + * @file Reading what stratus did not write itself by its shape: a plan, a + * record kept in the tenancy, a REST answer. A document is parsed and read + * through a schema that names only the fields stratus reads (the rest kept); + * one that does not parse or does not read is refused by name, never + * cast and left to fail later as `undefined`. A list whose rows stand apart + * (a host, a manifest) is read row by row: a malformed row is left out, the + * rest kept. The refusal names the document and the field, never its + * content, which may be a secret. + * + * Key components: + * - json_read: a JSON document, read by its schema, or refused by name. + * - jsonRows_read: a JSON list, row by row. + * - ReadRefusal: the refusal, naming the document and the field. + * + * Typical usage: + * ```ts + * const plan: InfraPlan = json_read(planText, infraPlanSchema, `${name}: plan.json`); + * ``` + * + * Dependencies: zod, and menu's element reader. + * + * @module + */ +import { elements_read, type ElementsRead } from '@fnndsc/menu'; +import { z } from 'zod'; + +/** + * A document refused because it does not read as what it should be: named by + * what it is and the first field that does not read, its content never quoted. + * + * @example + * ```ts + * throw new ReadRefusal('store: plan.json', 'rows.0.action: Invalid option'); + * ``` + */ +export class ReadRefusal extends Error { + /** What the document is (`store: plan.json`, `GET /clusters/x`). */ + public readonly what: string; + + /** Why it does not read (`rows.0.action: Invalid option`), its content never quoted. */ + public readonly why: string; + + /** + * @param what - What the document is. + * @param why - Why it does not read. + */ + constructor(what: string, why: string) { + super(`${what}: not readable as expected (${why})`); + this.name = 'ReadRefusal'; + this.what = what; + this.why = why; + } +} + +/** + * Parses JSON text, refusing what does not parse by name, never quoting it. + * + * @param text - The text. + * @param what - What the document is. + * @returns The parsed value. + * @throws {ReadRefusal} When it is not JSON. + */ +function json_parse(text: string, what: string): unknown { + try { + return JSON.parse(text) as unknown; + } catch { + // The parser's own words quote what it could not parse, which may be a secret. + throw new ReadRefusal(what, 'not JSON'); + } +} + +/** + * The first issue of a schema's refusal, as a path and a message, with no value in it. + * + * @param error - The refusal. + * @returns `rows.0.action: Invalid option …`. + * @example + * issue_say(z.object({ a: z.string() }).safeParse({ a: 1 }).error!); // 'a: Invalid input: expected string, received number' + */ +export function issue_say(error: z.ZodError): string { + const issue = error.issues[0]; + if (issue === undefined) return 'malformed'; + return issue.path.length === 0 ? issue.message : `${issue.path.join('.')}: ${issue.message}`; +} + +/** + * Reads a JSON document by its schema. + * + * @param text - The document's text. + * @param schema - What it must read as (the fields read; the rest kept by a loose schema). + * @param what - What the document is, for the refusal. + * @returns What it read as. + * @throws {ReadRefusal} When it does not parse or does not read. + * + * @example + * ```ts + * const answer = json_read(text, tokenAnswerSchema, 'Red Hat token'); + * ``` + */ +export function json_read(text: string, schema: z.ZodType, what: string): T { + const read = schema.safeParse(json_parse(text, what)); + if (!read.success) throw new ReadRefusal(what, issue_say(read.error)); + return read.data; +} + +/** + * Reads a JSON list row by row: a malformed row is left out and named, the + * rest kept. Text that is no JSON list is refused by name. + * + * @param text - The document's text. + * @param schema - One row's shape. + * @param what - What the document is, for the refusal. + * @returns The rows kept, and those left out by position. + * @throws {ReadRefusal} When it does not parse, or is no list. + * + * @example + * ```ts + * const hosts = jsonRows_read(text, hostSchema, 'GET /infra-envs/x/hosts').kept; + * ``` + */ +export function jsonRows_read(text: string, schema: z.ZodType, what: string): ElementsRead { + const data: unknown = json_parse(text, what); + if (!Array.isArray(data)) throw new ReadRefusal(what, 'not a list'); + return elements_read(data, schema); +} diff --git a/packages/stratus/src/vm/build.ts b/packages/stratus/src/vm/build.ts index afc8b609a..50608b609 100644 --- a/packages/stratus/src/vm/build.ts +++ b/packages/stratus/src/vm/build.ts @@ -12,14 +12,16 @@ * @module */ import * as path from 'path'; + import type { JobContext, JobRun } from '@fnndsc/brasa/core'; + +import { vmKeepName_derive, vmKept_write } from './keep.js'; +import { vmPorts_open, type VmSpec } from './spec.js'; +import { VM_TAG, type VmRecord, type VmStore } from './state.js'; +import { infraPlan_read, plan_count, planCounts_words, type BuildCall, type CloudBuilder, type InfraPlan, type StackModule } from '../cloud/builder.js'; import type { CloudDriver, CloudPrice, ServicePrices } from '../cloud/driver.js'; -import { plan_count, planCounts_words, type BuildCall, type CloudBuilder, type InfraPlan, type StackModule } from '../cloud/builder.js'; import { HOURS_PER_MONTH } from '../cluster/spend.js'; import type { NetRecord, NetStore } from '../net/state.js'; -import { vmPorts_open, type VmSpec } from './spec.js'; -import { VM_TAG, type VmRecord, type VmStore } from './state.js'; -import { vmKeepName_derive, vmKept_write } from './keep.js'; /** What a VM's jobs run over. */ export interface VmDeps { @@ -181,7 +183,7 @@ export function vmApplyRun_make(name: string, part: VmPart, deps: VmDeps): JobRu const planText: string | null = deps.store.file_read(name, planFile_derive(part)); const stackRef: string | undefined = part === 'data' ? record.dataStackRef : record.machineStackRef; if (planText === null || stackRef === undefined) throw new Error(`${name}: no ${part} plan to apply (vm build ${name} makes one)`); - const plan: InfraPlan = JSON.parse(planText) as InfraPlan; + const plan: InfraPlan = infraPlan_read(planText, `${name}: ${planFile_derive(part)}`); // The machine admits only the VM's own key: kept in the tenancy before the machine is made with it, so any // session on any host reaches the machine, and a key that cannot be kept stops the build before it bills. if (part === 'machine' && deps.builder.keep_write !== undefined) { diff --git a/packages/stratus/src/vm/keep.ts b/packages/stratus/src/vm/keep.ts index e5c6433fa..48fdc2857 100644 --- a/packages/stratus/src/vm/keep.ts +++ b/packages/stratus/src/vm/keep.ts @@ -26,13 +26,18 @@ */ import * as fs from 'fs'; import * as path from 'path'; -import type { BuildCall, CloudBuilder } from '../cloud/builder.js'; -import type { ChrisSecrets } from '../chris/compose.js'; -import { KeepFault } from '../cloud/keepFault.js'; -import { secrets_read, secrets_write } from '../chris/secrets.js'; -import { lock_adopt, lock_newer, lock_read, type KeptLock } from '../kept/lock.js'; + +import { z } from 'zod'; + import type { VmSpec } from './spec.js'; import type { VmRecord, VmStore } from './state.js'; +import { chrisSecretsSchema, type ChrisSecrets } from '../chris/compose.js'; +import { secrets_read, secrets_write } from '../chris/secrets.js'; +import type { BuildCall, CloudBuilder } from '../cloud/builder.js'; +import { KeepFault } from '../cloud/keepFault.js'; +import { keptLockSchema, lock_adopt, lock_newer, lock_read, type KeptLock } from '../kept/lock.js'; +import { issue_say } from '../read.js'; + /** What a verb says of a VM whose SSH key neither the tenancy nor this host keeps. */ export const VM_KEYLESS: string = 'the tenancy keeps no SSH key for it, and this host holds none: it was built before stratus kept keys in the tenancy, so the machine is not reached from here (vm keep , on the host that holds its key, keeps it in the tenancy)'; @@ -49,6 +54,44 @@ export interface VmKept { readonly lock?: KeptLock; } +/** A deploy's record as a keep holds it: the fields adoption hands the cache, by type; the rest kept. */ +const chrisRecordSchema = z.looseObject({ + profile: z.string(), + compute: z.string(), + host: z.string().nullable(), + url: z.string(), + deployed: z.string(), + dns: z.enum(['waiting', 'seen']).optional(), + porter: z.string().optional(), + image: z.string().optional(), + porterVersion: z.string().optional(), + berths: z.literal('launcher').optional(), + berthImage: z.string().optional(), + berthLimits: z.looseObject({ cpus: z.number(), memoryGib: z.number() }).optional(), +}); + +/** A declaration as a keep holds it: every field the cache renders, by type; the rest kept. */ +const vmSpecSchema = z.looseObject({ + net: z.string(), + open: z.array(z.number()), + vcpu: z.number(), + memory: z.number(), + disk: z.number(), + data: z.number(), + dataBackup: z.enum(['daily', 'none']), + os: z.string(), + ssh: z.looseObject({ port: z.number(), user: z.string(), key: z.string(), on: z.boolean() }).optional(), +}); + +/** A VM's keep as the vault holds it, read back by its shape: whose it is, its key, its ChRIS, its declaration, its lock; what it does not name kept, at every depth. */ +const vmKeptSchema = z.looseObject({ + vm: z.string(), + ssh: z.looseObject({ privateKey: z.string(), publicKey: z.string() }).optional(), + chris: z.looseObject({ record: chrisRecordSchema, secrets: chrisSecretsSchema }).optional(), + declared: z.looseObject({ spec: vmSpecSchema, at: z.string() }).optional(), + lock: keptLockSchema.optional(), +}); + /** * Two keeps of one VM as one: each part from whichever holds it, the * newer declaration of the two, this host's key and ChRIS over the vault's @@ -67,7 +110,8 @@ export function vmKept_merge(vault: VmKept | null, here: VmKept): VmKept { const chris: VmKept['chris'] = here.chris === undefined ? vault?.chris : vault?.chris === undefined ? here.chris : here.chris.record.deployed >= vault.chris.record.deployed ? here.chris : vault.chris; const lock: KeptLock | undefined = lock_newer(here.lock, vault?.lock); - return { vm: here.vm, ...(ssh !== undefined ? { ssh } : {}), ...(chris !== undefined ? { chris } : {}), ...(declared !== undefined ? { declared } : {}), ...(lock !== undefined ? { lock } : {}) }; + // What neither names is kept from both, this host's over the vault's: a field a newer stratus wrote survives an older one's round trip. + return { ...vault, ...here, vm: here.vm, ...(ssh !== undefined ? { ssh } : {}), ...(chris !== undefined ? { chris } : {}), ...(declared !== undefined ? { declared } : {}), ...(lock !== undefined ? { lock } : {}) }; } /** @@ -83,17 +127,18 @@ export async function vmKept_read(builder: CloudBuilder, name: string, region: s if (builder.keep_read === undefined) return null; const content: string | null = await builder.keep_read({ region, name: vmKeepName_derive(name) }); if (content === null) return null; - let kept: VmKept; + let data: unknown; try { - kept = JSON.parse(content) as VmKept; + data = JSON.parse(content) as unknown; } catch { // The parser's own words quote what it could not parse, and that is a secret. throw new KeepFault(`${vmKeepName_derive(name)}: the tenancy's secret is not a readable record`); } - if (kept === null || typeof kept !== 'object') throw new KeepFault(`${vmKeepName_derive(name)}: the tenancy's secret is not a VM's keep`); - const sshBad: boolean = kept.ssh !== undefined && (typeof kept.ssh.privateKey !== 'string' || typeof kept.ssh.publicKey !== 'string'); - if (kept.vm !== name || sshBad) throw new KeepFault(`${vmKeepName_derive(name)}: the tenancy's secret is not a VM's keep`); - return kept; + // Read by its shape; the refusal names the secret, never what it holds. + const read = vmKeptSchema.safeParse(data); + if (!read.success) throw new KeepFault(`${vmKeepName_derive(name)}: the tenancy's secret is not a VM's keep (${issue_say(read.error)})`); + if (read.data.vm !== name) throw new KeepFault(`${vmKeepName_derive(name)}: the tenancy's secret is not a VM's keep (vm: names another VM)`); + return read.data; } /** diff --git a/packages/stratus/src/vm/state.ts b/packages/stratus/src/vm/state.ts index c07a4c20a..047c9c335 100644 --- a/packages/stratus/src/vm/state.ts +++ b/packages/stratus/src/vm/state.ts @@ -13,7 +13,7 @@ import { spawnSync, type SpawnSyncReturns } from 'child_process'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { SpecStore, type KeptRecord } from '../kept/specStore.js'; +import { keptRecordSchema, SpecStore, type KeptRecord } from '../kept/specStore.js'; import type { VmHostState } from './host.js'; import { vmSpecYaml_parse, vmSpecYaml_render, type VmSpec } from './spec.js'; @@ -117,7 +117,7 @@ export class VmStore extends SpecStore { * @param root - The folder the VMs live in. */ constructor(root: string) { - super(root, { noun: 'VM', render: vmSpecYaml_render, parse: vmSpecYaml_parse }); + super(root, { noun: 'VM', render: vmSpecYaml_render, parse: vmSpecYaml_parse }, keptRecordSchema); } /** diff --git a/packages/stratus/tests/build.test.ts b/packages/stratus/tests/build.test.ts index 449b63ece..1e6d0474e 100644 --- a/packages/stratus/tests/build.test.ts +++ b/packages/stratus/tests/build.test.ts @@ -631,6 +631,14 @@ describe('the controller readout', () => { expect(clusterRun_derive({ ...job, id: 'd-build' } as JobRecord)).toBe('build'); }); + it('says a kept verify that does not read as kept and unread, never as none', () => { + const store_with = (verifyText: string | null): ClusterStore => ({ record_read: (): ClusterRecord => record_of(), file_read: (_name: string, file: string): string | null => (file === 'verify.json' ? verifyText : null), spec_read: (): null => null, folder_derive: (): string => '/nowhere' }) as unknown as ClusterStore; + const unread = clusterReadout_build(cluster_with({ run: 'done' }), store_with('{"at":"x","checks":{}}'), undefined).verify; + expect(unread?.checks).toEqual([expect.objectContaining({ name: 'verify.json', ok: null, how: 'reads' })]); + expect(unread?.checks[0]?.detail).toMatch(/^not readable: checks: /); + expect(clusterReadout_build(cluster_with({ run: 'done' }), store_with(null), undefined).verify).toBeNull(); + }); + it('names what is refused on each kind of cluster', () => { expect(refusals_derive(cluster_with({}, 'checkout'), null)).toEqual({ build: 'read from a harbor-oci checkout, not built here', teardown: 'read from a harbor-oci checkout, not built here' }); // An adopted cluster is torn down as a built one is: the lock is its only guard. diff --git a/packages/stratus/tests/keptStores.test.ts b/packages/stratus/tests/keptStores.test.ts index c647d446c..8988a80c7 100644 --- a/packages/stratus/tests/keptStores.test.ts +++ b/packages/stratus/tests/keptStores.test.ts @@ -12,7 +12,7 @@ import { ClusterStore, type ClusterRecord } from '../src/cluster/state.js'; import { SPEC_DEFAULT } from '../src/cluster/spec.js'; import { NetStore } from '../src/net/state.js'; import { VmStore } from '../src/vm/state.js'; -import { SpecStore, type KeptRecord, type SpecCodec } from '../src/kept/specStore.js'; +import { keptRecordSchema, SpecStore, type KeptRecord, type SpecCodec } from '../src/kept/specStore.js'; let root: string; @@ -39,7 +39,7 @@ describe('a change to a record that is not kept', () => { it('reads the store\'s noun only when it refuses', () => { let reads: number = 0; const codec: SpecCodec> = { get noun(): string { reads += 1; return 'thing'; }, render: (): string => 'x: 1\n', parse: (): { spec: Record } => ({ spec: {} }) }; - const store: SpecStore, KeptRecord> = new SpecStore(join(root, 'things'), codec); + const store: SpecStore, KeptRecord> = new SpecStore(join(root, 'things'), codec, keptRecordSchema); store.declare('t', {}, 'r'); store.declare('t', {}, 'r'); store.record_update('t', (): void => undefined); diff --git a/packages/stratus/tests/kubeHttpRead.test.ts b/packages/stratus/tests/kubeHttpRead.test.ts new file mode 100644 index 000000000..3a2ca61c2 --- /dev/null +++ b/packages/stratus/tests/kubeHttpRead.test.ts @@ -0,0 +1,49 @@ +/** + * @file The Kubernetes wire parses each JSON answer by name: an answer that + * is no JSON is refused as the call that asked for it, never quoted (a + * secret's answer holds it). Over a stand-in `node:https`; synthetic values. + */ +import { EventEmitter } from 'node:events'; +import { describe, it, expect, jest } from '@jest/globals'; + +/** What the stand-in server answers next. */ +const world: { body: string } = { body: '' }; + +/** A stand-in for `https.request`: answers 200 with the body set, once the request ends. */ +function request(_url: URL, _options: unknown, respond: (res: EventEmitter & { statusCode: number }) => void): EventEmitter { + const req = Object.assign(new EventEmitter(), { + write: (): void => undefined, + destroy: (): void => undefined, + end: (): void => { + const res = Object.assign(new EventEmitter(), { statusCode: 200 }); + respond(res); + res.emit('data', Buffer.from(world.body, 'utf-8')); + res.emit('end'); + }, + }); + return req; +} + +jest.unstable_mockModule('node:https', () => ({ request })); + +const { kubeApi_make } = await import('../src/kube/kubeHttp.js'); + +const ACCESS = { server: 'https://api.example.test:6443', ca: null, cert: null, key: null, token: null }; + +describe('the Kubernetes wire', () => { + it('reads a JSON answer', async () => { + world.body = '{"kind":"Secret"}'; + await expect(kubeApi_make(ACCESS).json_get('/x')).resolves.toStrictEqual({ kind: 'Secret' }); + }); + + it('refuses an answer that is no JSON by the call, never quoting it', async () => { + world.body = '{"data":{"token":"MARKER-SECRET-7f3a"'; + const api = kubeApi_make(ACCESS); + for (const asked of [api.json_get('/api/v1/secrets/s'), api.json_post('/api/v1/x', {})]) { + const error: unknown = await asked.catch((caught: unknown): unknown => caught); + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toMatch(/^(GET \/api\/v1\/secrets\/s|POST \/api\/v1\/x): /); + expect((error as Error).message).not.toContain('MARKER-SECRET'); + } + }); +}); diff --git a/packages/stratus/tests/ociWire.test.ts b/packages/stratus/tests/ociWire.test.ts index cd2bfa3ad..6082855f5 100644 --- a/packages/stratus/tests/ociWire.test.ts +++ b/packages/stratus/tests/ociWire.test.ts @@ -941,6 +941,14 @@ describe('rmApi_make', () => { expect(seen_take()).toStrictEqual([on('getJobTfPlan', { jobId: 'j1', tfPlanFormat: 'JSON' })]); }); + it('jobPlan_read refuses a plan that is no JSON by the job, never quoting it', async () => { + answers_set({ getJobTfPlan: resolved({ value: '{"secret":"MARKER-PLAN-91c2"' }) }); + const error: unknown = await rm.jobPlan_read('j1').catch((caught: unknown): unknown => caught); + expect((error as Error).message).toMatch(/^job j1: plan: /); + expect((error as Error).message).not.toContain('MARKER-PLAN'); + seen_take(); + }); + it('stackResources_count and stackOutputs_read read the state', async () => { const state: Row = { resources: [{ mode: 'managed', instances: [{}, {}] }, { mode: 'data', instances: [{}] }, { mode: 'managed' }], diff --git a/packages/stratus/tests/readers.test.ts b/packages/stratus/tests/readers.test.ts new file mode 100644 index 000000000..47184fca7 --- /dev/null +++ b/packages/stratus/tests/readers.test.ts @@ -0,0 +1,184 @@ +/** + * @file What stratus did not write itself, read by its shape: a kept plan, + * a keep in the tenancy, a verify, the platform manifests, ChRIS's secrets, + * Red Hat's answers. Each reads a real-shaped document (synthetic values), + * refuses a field of the wrong type by name (never quoting the document), + * keeps the good rows of a list beside a malformed one, and takes the nulls + * Red Hat answers today. + */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, it, expect } from '@jest/globals'; +import { z } from 'zod'; +import { infraPlan_read, type CloudBuilder } from '../src/cloud/builder.js'; +import { ReadRefusal, json_read, jsonRows_read } from '../src/read.js'; +import { verifyKept_read } from '../src/cluster/verify.js'; +import { platformManifests_read } from '../src/installer/installer.js'; +import { chrisSecretsSchema } from '../src/chris/compose.js'; +import { clusterKept_read } from '../src/cluster/keep.js'; +import { vmKept_read } from '../src/vm/keep.js'; +import { NetStore } from '../src/net/state.js'; +import { AssistedInstaller, ASSISTED_API, RED_HAT_SSO_URL, type InstallerFetch } from '../src/installer/assisted.js'; +import { smokeVerdict_words } from '../src/kube/chris.js'; +import { userAnswer_parse } from '../src/chris/users.js'; + +/** A plan as stratus keeps it after `vm build` plans: a create, a change with its leaves, a tag drift. */ +const PLAN = { + ref: 'ocid1.ormjob.oc1..plan-store', + stackRef: 'ocid1.ormstack.oc1..store', + rows: [ + { action: 'create', kind: 'instances', name: 'oci_core_instance.vm', type: 'oci_core_instance' }, + { action: 'change', kind: 'volumes', name: 'oci_core_volume.data', changes: [{ path: 'size_in_gbs', before: '50', after: '100' }, { path: 'freeform_tags.note', before: null, after: 'x' }] }, + { action: 'change', kind: 'vcns', name: 'oci_core_vcn.net', drift: true }, + ], + createdBy: 'stratus', +}; + +/** The refusal a call throws. */ +function refusal_get(call: () => unknown): ReadRefusal { + try { + call(); + } catch (error: unknown) { + if (error instanceof ReadRefusal) return error; + throw error; + } + throw new Error('nothing was refused'); +} + +describe('a kept plan', () => { + it('reads whole, its rows and anything else it carries kept', () => { + const plan = infraPlan_read(JSON.stringify(PLAN), 'store: data-plan.json'); + expect(plan.rows.map((row) => row.action)).toEqual(['create', 'change', 'change']); + expect(plan.rows[1]?.changes?.[1]).toEqual({ path: 'freeform_tags.note', before: null, after: 'x' }); + expect(plan.stackRef).toBe('ocid1.ormstack.oc1..store'); + }); + + it('is refused by name, the field said, when a row does not read, and when it is no JSON', () => { + const bad = refusal_get(() => infraPlan_read(JSON.stringify({ ...PLAN, rows: [{ ...PLAN.rows[0], action: 'explode' }] }), 'store: data-plan.json')); + expect(bad.message).toMatch(/^store: data-plan\.json: not readable as expected \(rows\.0\.action: /); + expect(refusal_get(() => infraPlan_read('{"ref": "secret-sauce"', 'store: plan.json')).message).toBe('store: plan.json: not readable as expected (not JSON)'); + expect(refusal_get(() => infraPlan_read(JSON.stringify({ rows: [] }), 'x: plan.json')).message).toContain('ref:'); + }); +}); + +describe('a list read row by row', () => { + it('keeps the rows that read and names the one that does not', () => { + const read = jsonRows_read(JSON.stringify([{ id: 'h-1' }, { id: 7 }, { id: 'h-3' }]), ASSISTED_ROW, 'hosts'); + expect(read.kept).toEqual([{ id: 'h-1' }, { id: 'h-3' }]); + expect(read.skipped.map((why: string): string => why.split(':')[0] ?? '')).toEqual(['#2']); + expect(refusal_get(() => jsonRows_read('{"id":"h-1"}', ASSISTED_ROW, 'hosts')).message).toBe('hosts: not readable as expected (not a list)'); + }); +}); + +/** One row the list test reads. */ +const ASSISTED_ROW = z.object({ id: z.string() }); + +describe('records kept here', () => { + it('a verify reads with its checks, and one of the wrong shape is refused by name', () => { + const verify = verifyKept_read(JSON.stringify({ at: '2026-12-01T10:00:00Z', checks: [{ name: 'nodes', ok: true, detail: '6 ready', how: 'reads' }] }), 'quay: verify.json'); + expect(verify.at).toBe('2026-12-01T10:00:00Z'); + expect(() => verifyKept_read(JSON.stringify({ at: 3, checks: [] }), 'quay: verify.json')).toThrow('quay: verify.json: not readable as expected (at: '); + }); + + it('the platform manifests read whole, or not at all', () => { + expect(platformManifests_read(JSON.stringify([{ name: 'oci-ccm.yml', content: 'kind: x' }]), 'quay: manifests.json')).toEqual([{ name: 'oci-ccm.yml', content: 'kind: x' }]); + expect(() => platformManifests_read(JSON.stringify([{ name: 'a.yml', content: 'x' }, { name: 'b.yml' }]), 'quay: manifests.json')).toThrow('1.content'); + }); + + it('ChRIS\'s secrets read, and a refusal never quotes them', () => { + const secrets = { djangoKey: 'd-SECRET', postgresPassword: 'p-SECRET', pfconSecretKey: 's', pfconPassword: 'f', adminPassword: 'a', porterSecret: 'ps' }; + expect(json_read(JSON.stringify(secrets), chrisSecretsSchema, 'store: chris.json')).toEqual(secrets); + const refused = refusal_get(() => json_read(JSON.stringify({ ...secrets, adminPassword: 42 }), chrisSecretsSchema, 'store: chris.json')); + expect(refused.message).toContain('adminPassword'); + expect(refused.message).not.toContain('SECRET'); + }); +}); + +describe('a state kept on this host', () => { + it('reads whole, and one that is no object naming what it keeps is refused by its file, never quoted', () => { + const root: string = mkdtempSync(join(tmpdir(), 'stratus-state-')); + try { + const store: NetStore = new NetStore(root); + const state = (name: string, text: string): string => { + mkdirSync(join(root, name), { recursive: true }); + writeFileSync(join(root, name, 'state.json'), text); + return join(root, name, 'state.json'); + }; + state('good', JSON.stringify({ name: 'good', created: 'then', region: 'us-ashburn-1', placeId: 'p-1' })); + expect(store.record_read('good')).toMatchObject({ name: 'good', placeId: 'p-1' }); + const nameless: string = state('nameless', JSON.stringify({ created: 'then', region: 'r', key: 'SECRET' })); + expect(refusal_get(() => store.record_read('nameless')).message).toBe(`${nameless}: not readable as expected (name: Invalid input: expected string, received undefined)`); + const torn: string = state('torn', '{"name": "torn", "key": "SECRET"'); + const refused: Error = refusal_get(() => store.record_read('torn')); + expect(refused.message).toBe(`${torn}: not readable as expected (not JSON)`); + expect(refused.message).not.toContain('SECRET'); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); + +describe('keeps in the tenancy', () => { + /** A builder whose vault holds the one text given. */ + const vault = (content: string): CloudBuilder => ({ keep_read: async (): Promise => content }) as unknown as CloudBuilder; + + it('a cluster\'s keep reads with its lock, and one of the wrong shape is refused by the secret\'s name', async () => { + expect(await clusterKept_read(vault(JSON.stringify({ cluster: 'quay', lock: { protected: true, at: '2026-12-01T00:00:00Z' } })), 'quay', 'r')).toEqual({ cluster: 'quay', lock: { protected: true, at: '2026-12-01T00:00:00Z' } }); + await expect(clusterKept_read(vault(JSON.stringify({ cluster: 'quay', lock: { protected: 'yes', at: 'x' } })), 'quay', 'r')).rejects.toThrow('mise-cluster-quay: not readable as expected (lock.protected:'); + }); + + it('a VM\'s keep reads with its key and ChRIS, and a malformed one is refused without its secrets', async () => { + const keep = { vm: 'store', ssh: { privateKey: 'PRIVATE-KEY', publicKey: 'ssh-ed25519 AAAA' }, chris: { record: { profile: 'minimal', compute: 'host', host: null, url: 'u', deployed: 'd' }, secrets: { djangoKey: 'd', postgresPassword: 'p', pfconSecretKey: 's', pfconPassword: 'f', adminPassword: 'a' } }, lock: { protected: false, at: '2026-12-01T00:00:00Z' } }; + expect((await vmKept_read(vault(JSON.stringify(keep)), 'store', 'r'))?.ssh?.publicKey).toBe('ssh-ed25519 AAAA'); + const bad = vmKept_read(vault(JSON.stringify({ ...keep, chris: { ...keep.chris, secrets: { djangoKey: 'd' } } })), 'store', 'r'); + await expect(bad).rejects.toThrow("mise-vm-store: the tenancy's secret is not a VM's keep"); + await expect(vmKept_read(vault(JSON.stringify({ ...keep, ssh: { privateKey: 3, publicKey: 'p' } })), 'store', 'r')).rejects.not.toThrow('PRIVATE-KEY'); + }); +}); + +describe('Red Hat\'s answers', () => { + /** A Red Hat that answers each address with the body given. */ + const redHat = (answers: Record): AssistedInstaller => { + const fetchFn: InstallerFetch = async (url: string) => { + if (url === RED_HAT_SSO_URL) return { status: 200, text: async (): Promise => JSON.stringify({ access_token: 't', expires_in: 900 }) }; + return { status: 200, text: async (): Promise => JSON.stringify(answers[url] ?? null) }; + }; + return new AssistedInstaller({ account: () => ({ clientId: 'i', clientSecret: 's' }), sshPublicKey: () => 'k', fetch: fetchFn }); + }; + const IDS = { clusterId: 'c-1', infraEnvId: 'ie-1' }; + + it('takes the nulls a new cluster answers today: no status words, no progress yet', async () => { + const installer = redHat({ [`${ASSISTED_API}/clusters/c-1`]: { id: 'c-1', status: 'insufficient', status_info: null, progress: null } }); + expect(await installer.install_status(IDS)).toEqual({ state: 'pending', percent: 0, note: 'insufficient: insufficient' }); + const later = redHat({ [`${ASSISTED_API}/clusters/c-1`]: { id: 'c-1', status: 'installing', status_info: 'Installing', progress: { total_percentage: null } } }); + expect(await later.install_status(IDS)).toEqual({ state: 'installing', percent: 0, note: 'Installing' }); + }); + + it('a cluster answer of the wrong shape is refused by name', async () => { + await expect(redHat({ [`${ASSISTED_API}/clusters/c-1`]: { status: 7 } }).install_status(IDS)).rejects.toThrow('GET /clusters/…: not readable as expected (status:'); + }); + + it('the hosts read row by row: one that does not read is left out, the rest drawn', async () => { + const installer = redHat({ [`${ASSISTED_API}/infra-envs/ie-1/hosts`]: [ + { id: 'h-1', requested_hostname: 'quay-cp-1.quay.example.org', status: 'known', role: 'master', created_at: '2026-12-01T00:00:00Z' }, + { id: 'h-2', status: 42 }, + { id: 'h-3', requested_hostname: null, status: 'discovering', role: null, created_at: null }, + ] }); + expect((await installer.hosts_list(IDS)).map((host) => `${host.name}:${host.role}:${String(host.ready)}`)).toEqual(['h-3:auto:false', 'quay-cp-1:master:true']); + }); +}); + +describe('what a remote program printed', () => { + it('a smoke verdict reads by its shape; any other line is kept as it is', () => { + expect(smokeVerdict_words(JSON.stringify({ verdict: 'pass', failed_step: null, duration_s: 17.2, steps: [{ name: 'a', ok: true }] }))).toBe('pass · 1 step · 17 s'); + expect(smokeVerdict_words(JSON.stringify({ verdict: 3 }))).toBe('{"verdict":3}'); + expect(smokeVerdict_words('not json')).toBe('not json'); + }); + + it('a user program\'s answer reads its value by shape, and refuses one of the wrong type', () => { + expect(userAnswer_parse('… \nstratus-user exists "a@b.org"\n')).toEqual({ kind: 'exists', email: 'a@b.org' }); + expect(userAnswer_parse('stratus-user no-group ["lab","pacs"]\n')).toEqual({ kind: 'noGroup', groups: ['lab', 'pacs'] }); + expect(() => userAnswer_parse('stratus-user no-group [1]\n')).toThrow('chris user: the groups missing: not readable as expected (0:'); + }); +}); diff --git a/packages/stratus/tests/readersWhole.test.ts b/packages/stratus/tests/readersWhole.test.ts new file mode 100644 index 000000000..a36552ce6 --- /dev/null +++ b/packages/stratus/tests/readersWhole.test.ts @@ -0,0 +1,155 @@ +/** + * @file What stratus reads is read whole before it acts on it: a keep's + * deploy record and declaration by every field adoption hands the cache, a + * kept record by its store's fields and its own name, Red Hat's and + * GoDaddy's lists with no row of the asked name left unread, a refusal that + * never quotes what else the answer held, a smoke verdict's null timing, a + * verify whose unread checks are said, and every JSON answer parsed by name. + * Synthetic values throughout. + */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, it, expect, afterEach } from '@jest/globals'; +import type { CloudBuilder } from '../src/cloud/builder.js'; +import { ClusterStore } from '../src/cluster/state.js'; +import { verifyKept_read } from '../src/cluster/verify.js'; +import { goDaddy_make } from '../src/chris/registrar.js'; +import { AssistedInstaller, ASSISTED_API, OCM_API, RED_HAT_SSO_URL, type InstallerFetch } from '../src/installer/assisted.js'; +import { smokeVerdict_words } from '../src/kube/chris.js'; +import { NetStore } from '../src/net/state.js'; +import { vmKept_merge, vmKept_read, type VmKept } from '../src/vm/keep.js'; + +/** A cloud whose vault holds the content given. */ +const vault = (content: string): CloudBuilder => ({ keep_read: async (): Promise => content }) as unknown as CloudBuilder; + +/** A deploy's secrets as a keep holds them. */ +const SECRETS = { djangoKey: 'd', postgresPassword: 'p', pfconSecretKey: 's', pfconPassword: 'f', adminPassword: 'a' }; + +/** A deploy's record as a keep holds it. */ +const RECORD = { profile: 'minimal', compute: 'host', host: null, url: 'http://10.0.0.2:8000/api/v1/', deployed: '2026-12-01T00:00:00Z' }; + +/** A declaration as a keep holds it. */ +const SPEC = { net: 'scratch', open: [443], vcpu: 2, memory: 16, disk: 50, data: 100, dataBackup: 'none', os: 'ubuntu-26.04' }; + +/** Folders made by a test, removed after it. */ +const made: string[] = []; +afterEach((): void => { for (const folder of made.splice(0)) rmSync(folder, { recursive: true, force: true }); }); + +/** A fresh folder. */ +function folder_make(): string { + const folder: string = mkdtempSync(join(tmpdir(), 'stratus-whole-')); + made.push(folder); + return folder; +} + +describe('a VM\'s keep', () => { + it('refuses a deploy record or a declaration that is a list, or lacks a field adoption reads, naming the field', async () => { + const keep = { vm: 'store', chris: { record: RECORD, secrets: SECRETS }, declared: { spec: SPEC, at: '2026-12-01T00:00:00Z' } }; + expect((await vmKept_read(vault(JSON.stringify(keep)), 'store', 'r'))?.chris?.record.deployed).toBe('2026-12-01T00:00:00Z'); + await expect(vmKept_read(vault(JSON.stringify({ ...keep, chris: { record: [], secrets: SECRETS } })), 'store', 'r')).rejects.toThrow('(chris.record:'); + await expect(vmKept_read(vault(JSON.stringify({ ...keep, declared: { spec: [], at: 'x' } })), 'store', 'r')).rejects.toThrow('(declared.spec:'); + const { deployed: _deployed, ...undated } = RECORD; + await expect(vmKept_read(vault(JSON.stringify({ ...keep, chris: { record: undated, secrets: SECRETS } })), 'store', 'r')).rejects.toThrow('(chris.record.deployed:'); + await expect(vmKept_read(vault(JSON.stringify({ ...keep, declared: { spec: { ...SPEC, vcpu: '2' }, at: 'x' } })), 'store', 'r')).rejects.toThrow('(declared.spec.vcpu:'); + }); + + it('keeps what it does not name, at every depth, through a read and a merge', async () => { + const keep = { + vm: 'store', later: 'top', + ssh: { privateKey: 'k', publicKey: 'p', later: 'ssh' }, + chris: { record: { ...RECORD, later: 'record' }, secrets: { ...SECRETS, later: 'secrets' }, later: 'chris' }, + declared: { spec: { ...SPEC, later: 'spec' }, at: '2026-12-01T00:00:00Z', later: 'declared' }, + lock: { protected: true, at: '2026-12-01T00:00:00Z', later: 'lock' }, + }; + const read: VmKept | null = await vmKept_read(vault(JSON.stringify(keep)), 'store', 'r'); + expect(read).toEqual(keep); + expect(vmKept_merge(read, { vm: 'store' })).toEqual(keep); + }); +}); + +describe('a record kept on this host', () => { + it('is refused when it lacks a field its store reads, before anything reads it', () => { + const root: string = folder_make(); + mkdirSync(join(root, 'demo')); + writeFileSync(join(root, 'demo', 'state.json'), JSON.stringify({ name: 'demo' })); + expect(() => new ClusterStore(root).record_read('demo')).toThrow(/state\.json: not readable as expected \(created: /); + writeFileSync(join(root, 'demo', 'state.json'), JSON.stringify({ name: 'demo', created: 'c', region: 'r', baseDomain: 'x.org', steps: { cluster: { state: 'exploded' } }, ids: {} })); + expect(() => new ClusterStore(root).record_read('demo')).toThrow('(steps.cluster.state: '); + }); + + it('is refused when it names another, so no change is written to that other\'s folder', () => { + const root: string = folder_make(); + mkdirSync(join(root, 'alpha')); + writeFileSync(join(root, 'alpha', 'state.json'), JSON.stringify({ name: 'beta', created: 'c', region: 'r' })); + const nets: NetStore = new NetStore(root); + expect(() => nets.record_read('alpha')).toThrow('(name: names another)'); + expect(() => nets.record_update('alpha', (): void => undefined)).toThrow('(name: names another)'); + expect(nets.names_list()).toEqual(['alpha']); + }); +}); + +describe('Red Hat', () => { + /** A Red Hat answering from a table, the calls kept. */ + const redHat = (answers: Record, calls: string[]): AssistedInstaller => { + const fetchFn: InstallerFetch = async (url, init) => { + const key: string = `${init?.method ?? 'GET'} ${url}`; + calls.push(key); + const answer = answers[key]; + if (answer === undefined) return { status: 404, text: async (): Promise => '{}' }; + return { status: answer.status, text: async (): Promise => JSON.stringify(answer.body) }; + }; + return new AssistedInstaller({ account: () => ({ clientId: 'i', clientSecret: 's' }), sshPublicKey: () => 'k', fetch: fetchFn }); + }; + const TOKEN = { [`POST ${RED_HAT_SSO_URL}`]: { status: 200, body: { access_token: 't', expires_in: 900 } } }; + + it('refuses to make a cluster whose name it lists, even on a row without an id', async () => { + const calls: string[] = []; + const installer = redHat({ ...TOKEN, [`GET ${ASSISTED_API}/clusters`]: { status: 200, body: [{ name: 'trial', base_dns_domain: 'oci.example.org' }] } }, calls); + await expect(installer.cluster_create({ name: 'trial', baseDomain: 'oci.example.org', version: '4.22', controlPlaneCount: 3 })).rejects.toThrow('already exists at Red Hat'); + expect(calls.filter((call: string): boolean => call.startsWith('POST ') && call !== `POST ${RED_HAT_SSO_URL}`)).toEqual([]); + expect(calls).not.toContain(`POST ${OCM_API}/api/accounts_mgmt/v1/access_token`); + }); + + it('words a refusal by its reason alone, never by the rest of what it answered', async () => { + const installer = redHat({ ...TOKEN, [`POST ${ASSISTED_API}/clusters/c-1/actions/install`]: { status: 400, body: { reason: 7, other: 'MARKER-SECRET' } } }, []); + const refused: Error = await installer.install_start({ clusterId: 'c-1', infraEnvId: 'ie-1' }).catch((error: Error) => error) as Error; + expect(refused.message).toBe('POST /clusters/c-1/actions/install: HTTP 400'); + const worded = redHat({ ...TOKEN, [`POST ${ASSISTED_API}/clusters/c-1/actions/install`]: { status: 409, body: { reason: 'not ready', other: 'MARKER-SECRET' } } }, []); + await expect(worded.install_start({ clusterId: 'c-1', infraEnvId: 'ie-1' })).rejects.toThrow(/^POST \/clusters\/c-1\/actions\/install: HTTP 409: not ready$/); + }); +}); + +describe('GoDaddy', () => { + /** GoDaddy answering a listing with the items given. */ + const goDaddy = (items: unknown[]): ReturnType => { + const token: string = join(folder_make(), 'godaddy'); + writeFileSync(token, 'tok\n'); + const fetcher = (async (): Promise => new Response(JSON.stringify({ items }), { status: 200 })) as typeof fetch; + return goDaddy_make(token, fetcher); + }; + const ROW = { recordId: 'r-1', type: 'A', name: 'cube', data: '10.0.0.2', ttl: 600 }; + + it('refuses a listing in which a record of the name does not read, and leaves out one surely of another', async () => { + expect(await goDaddy([ROW, { ...ROW, name: 'other', ttl: 'x' }])?.records_list('example.org', 'cube')).toEqual([{ id: 'r-1', type: 'A', name: 'cube', data: '10.0.0.2', ttl: 600 }]); + await expect(goDaddy([ROW, { ...ROW, recordId: 'r-2', ttl: '600' }])?.records_list('example.org', 'cube')).rejects.toThrow('record #2 could be this name\'s and does not read'); + await expect(goDaddy([{ recordId: 'r-3' }])?.records_list('example.org', 'cube')).rejects.toThrow('record #1 could be this name\'s'); + }); +}); + +describe('what a remote program printed', () => { + it('a smoke verdict with a null timing reads, as before', () => { + expect(smokeVerdict_words('{"verdict":"pass","failed_step":null,"duration_s":null}')).toBe('pass · 0 steps'); + expect(smokeVerdict_words('{"verdict":"fail","failed_step":"login","steps":"three"}')).toBe('fail · 0 steps · failed at login'); + }); +}); + +describe('a kept verify', () => { + it('keeps the checks that read and says the one that does not as not readable', () => { + const verify = verifyKept_read(JSON.stringify({ at: '2026-12-01T10:00:00Z', checks: [{ name: 'nodes', ok: true, detail: '6 ready', how: 'reads' }, { name: 'dns', ok: 'yes', detail: 'SECRET-DETAIL', how: 'reads' }] }), 'quay: verify.json'); + expect(verify.checks[0]).toEqual({ name: 'nodes', ok: true, detail: '6 ready', how: 'reads' }); + expect(verify.checks[1]).toMatchObject({ name: '#2', ok: null, how: 'reads' }); + expect(verify.checks[1]?.detail).toMatch(/^not readable: /); + expect(JSON.stringify(verify)).not.toContain('SECRET-DETAIL'); + }); +}); diff --git a/scripts/eslint-baseline.json b/scripts/eslint-baseline.json index 51b409db9..364489e8f 100644 --- a/scripts/eslint-baseline.json +++ b/scripts/eslint-baseline.json @@ -3,7 +3,7 @@ "@typescript-eslint/await-thenable": 1, "@typescript-eslint/explicit-function-return-type": 4, "@typescript-eslint/naming-convention": 1447, - "@typescript-eslint/no-base-to-string": 6, + "@typescript-eslint/no-base-to-string": 5, "@typescript-eslint/no-confusing-void-expression": 355, "@typescript-eslint/no-deprecated": 1, "@typescript-eslint/no-invalid-void-type": 3, @@ -32,7 +32,7 @@ "jsdoc/escape-inline-tags": 3, "jsdoc/multiline-blocks": 1, "jsdoc/require-example": 1120, - "jsdoc/require-jsdoc": 1744, + "jsdoc/require-jsdoc": 1724, "jsdoc/require-param": 476, "jsdoc/require-returns": 334, "jsdoc/require-throws": 8, @@ -271,9 +271,9 @@ "@typescript-eslint/restrict-template-expressions": 11, "import/order": 4, "jsdoc/check-param-names": 4, - "jsdoc/check-tag-names": 55, + "jsdoc/check-tag-names": 54, "jsdoc/require-example": 94, - "jsdoc/require-jsdoc": 269, + "jsdoc/require-jsdoc": 267, "jsdoc/require-param": 30, "jsdoc/require-returns": 16, "local/file-overview-sections": 85 @@ -328,25 +328,25 @@ "@typescript-eslint/no-base-to-string": 5, "@typescript-eslint/no-confusing-void-expression": 27, "@typescript-eslint/no-dynamic-delete": 2, - "@typescript-eslint/no-non-null-assertion": 3, + "@typescript-eslint/no-non-null-assertion": 2, "@typescript-eslint/no-unnecessary-boolean-literal-compare": 4, - "@typescript-eslint/no-unnecessary-condition": 160, - "@typescript-eslint/no-unnecessary-type-assertion": 47, + "@typescript-eslint/no-unnecessary-condition": 159, + "@typescript-eslint/no-unnecessary-type-assertion": 45, "@typescript-eslint/no-unnecessary-type-conversion": 13, "@typescript-eslint/no-unsafe-argument": 1, "@typescript-eslint/no-unsafe-assignment": 2, "@typescript-eslint/no-unsafe-enum-comparison": 9, "@typescript-eslint/no-unused-vars": 11, "@typescript-eslint/require-await": 88, - "@typescript-eslint/restrict-template-expressions": 317, + "@typescript-eslint/restrict-template-expressions": 316, "@typescript-eslint/typedef": 69, "@typescript-eslint/unbound-method": 10, "import/first": 2, - "import/order": 312, + "import/order": 198, "jsdoc/check-param-names": 65, - "jsdoc/check-tag-names": 118, + "jsdoc/check-tag-names": 117, "jsdoc/require-example": 564, - "jsdoc/require-jsdoc": 1698, + "jsdoc/require-jsdoc": 1645, "jsdoc/require-param": 218, "jsdoc/require-returns": 88, "jsdoc/require-throws": 2, diff --git a/scripts/ratchet-baseline.json b/scripts/ratchet-baseline.json index a3662d0f8..09c6362dd 100644 --- a/scripts/ratchet-baseline.json +++ b/scripts/ratchet-baseline.json @@ -9,7 +9,7 @@ "lines": 68.5, "statements": 66.1, "branches": 57, - "functions": 63.1, + "functions": 63.6, "allowance": { "below": 0.3, "above": 0.7 diff --git a/scripts/shape-baseline.json b/scripts/shape-baseline.json index 23bafc191..66ebd71c5 100644 --- a/scripts/shape-baseline.json +++ b/scripts/shape-baseline.json @@ -2,7 +2,7 @@ "apps/argus": { "complexity": 104, "max-depth": 12, - "sonarjs/cognitive-complexity": 97 + "sonarjs/cognitive-complexity": 96 }, "apps/porter": { "complexity": 7,