From 165770d3fdda74c932f92904a0f54c7dbe6d4cb5 Mon Sep 17 00:00:00 2001 From: Kevin Delemme Date: Mon, 30 Nov 2026 10:07:27 -0500 Subject: [PATCH 1/3] feat(kb): short canonical names for slo commands Rename the 15 `elastic kb slo` commands from Kibana's legacy operationId names (`find-slos-op`, `get-slo-op`, ...) to short canonical names that follow one rule: `list*` for paginated results, `get*` for a single element (`list`, `get`, `create`, `list-definitions`, `get-snapshot`, ...). Every legacy `*-op` name stays registered as a Commander alias. - factory: `CommandConfig.aliases`, validated and registered by `defineCommand`; lazy stub leaves carry the same aliases. - policy: `isCommandAllowed` accepts a list of dot-paths; leaves match through their canonical path or any alias path, so an existing `commands.blocked` entry such as `stack.kb.slo.delete-slo-op` still blocks the renamed `stack.kb.slo.delete`. - kb: `src/kb/aliases.ts` naming table keyed by upstream `@elastic/schemas` names; registration, the namespaced argv sniff and stub leaves use it. The flat `kb ` sniff keeps matching upstream names only. - codegen: KB functional scripts invoke the canonical names via `cliPath`. - docs: regenerated `docs/cli/schema.json`; alias matching documented in the configuration reference. --- codegen/functional/kb.ts | 12 ++- codegen/functional/test/mapper.test.ts | 13 +++ docs/cli/configuration_reference.md | 4 +- docs/cli/schema.json | 75 ++++++++++--- src/factory-core.ts | 33 ++++-- src/factory.ts | 19 +++- src/kb/aliases.ts | 77 ++++++++++++++ src/kb/register.ts | 16 ++- src/lib/lazy-leaf.ts | 17 +-- test/cli-schema.test.ts | 12 +++ test/completion-cli.test.ts | 21 ++++ test/factory.test.ts | 141 +++++++++++++++++++++++++ test/kb/aliases.test.ts | 122 +++++++++++++++++++++ test/kb/register.test.ts | 107 +++++++++++++++++++ test/lib/lazy-leaf.test.ts | 54 ++++++++++ 15 files changed, 686 insertions(+), 37 deletions(-) create mode 100644 src/kb/aliases.ts create mode 100644 test/kb/aliases.test.ts create mode 100644 test/lib/lazy-leaf.test.ts diff --git a/codegen/functional/kb.ts b/codegen/functional/kb.ts index 847fd744..8ce9e52d 100644 --- a/codegen/functional/kb.ts +++ b/codegen/functional/kb.ts @@ -18,11 +18,18 @@ * client is the CLI. It maps each `namespace.action` to `stack kb * ` and routes params/body to flags, reusing the shared mapper and * generator that also drive the Elasticsearch functional tests. + * + * Definitions reference upstream `@elastic/schemas` names (e.g. `slo.find_slos_op`). + * Each definition is loaded with a precomputed `cliPath` built by + * `resolveKbCommandNaming` (which `src/kb/register.ts` also uses), so scripts + * invoke the canonical CLI name (e.g. `stack kb slo list`) rather than the + * upstream name. */ import { readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs' import { join, basename } from 'node:path' import { loadAllKbApis } from '../../src/kb/apis.ts' +import { resolveKbCommandNaming } from '../../src/kb/aliases.ts' import { parseTestFile, shouldSkipServerlessProject, shouldSkipStackVersion, stackSinceFor } from './parser.ts' import stackSince from './stack-since.json' with { type: 'json' } import { generateScript, generateRunner, type RunnerScript } from './generator.ts' @@ -85,7 +92,10 @@ const STREAM_IMPORT_PREAMBLE = [ 'CONTENT_PACK="$SCRIPT_DIR/../cli-ft-content-pack.zip"' ] -const apis = await loadAllKbApis() +const apis = (await loadAllKbApis()).map((def) => ({ + ...def, + cliPath: [def.namespace, resolveKbCommandNaming(def.namespace, def.name).name], +})) mkdirSync(OUT_DIR, { recursive: true }) diff --git a/codegen/functional/test/mapper.test.ts b/codegen/functional/test/mapper.test.ts index d32c6c14..b785d27a 100644 --- a/codegen/functional/test/mapper.test.ts +++ b/codegen/functional/test/mapper.test.ts @@ -7,6 +7,8 @@ import { describe, it } from 'node:test' import assert from 'node:assert/strict' import { buildActionMap, mapAction } from '../mapper.ts' import type { EsApiDefinition } from '../../../src/es/types.ts' +import type { ApiActionDef } from '../types.ts' +import { resolveKbCommandNaming } from '../../../src/kb/aliases.ts' const testDefs: EsApiDefinition[] = [ { @@ -174,4 +176,15 @@ describe('mapAction', () => { assert.ok(result) assert.ok(!result.cliArgs.includes('--yes')) }) + + it('maps a KB action to its canonical CLI name through cliPath', () => { + const def: ApiActionDef = { + namespace: 'slo', + name: 'find-slos-op', + method: 'GET', + cliPath: ['slo', resolveKbCommandNaming('slo', 'find-slos-op').name], + } + const result = mapAction('slo.find_slos_op', {}, buildActionMap([def]), ['stack', 'kb']) + assert.deepStrictEqual(result?.cliArgs, ['stack', 'kb', 'slo', 'list']) + }) }) diff --git a/docs/cli/configuration_reference.md b/docs/cli/configuration_reference.md index bcc40e3b..ff4528bb 100644 --- a/docs/cli/configuration_reference.md +++ b/docs/cli/configuration_reference.md @@ -66,8 +66,8 @@ Policy controlling which commands are permitted to run. Applies at the root leve | Name | Type | Required | Default value | Description | | - | - | - | - | - | | `profile` | string (`serverless` \| `stack` \| `default`) | no | - | Built-in allow-list profile. Mutually exclusive with `allowed`. | -| `allowed` | array of strings | no | - | Explicit allow-list of command names/namespaces. Entries can use a trailing wildcard (example: `stack.es.*`) to match a namespace. Mutually exclusive with `profile` and `blocked`. | -| `blocked` | array of strings | no | - | Explicit deny-list of command names/namespaces (everything else is allowed). Entries can use a trailing wildcard. Mutually exclusive with `allowed`. | +| `allowed` | array of strings | no | - | Explicit allow-list of command names/namespaces. Entries can use a trailing wildcard (example: `stack.es.*`) to match a namespace. An entry naming a command's alias matches the command (example: `stack.kb.slo.delete-slo-op` applies to `stack.kb.slo.delete`). Mutually exclusive with `profile` and `blocked`. | +| `blocked` | array of strings | no | - | Explicit deny-list of command names/namespaces (everything else is allowed). Entries can use a trailing wildcard. An entry naming a command's alias matches the command (example: `stack.kb.slo.delete-slo-op` applies to `stack.kb.slo.delete`). Mutually exclusive with `allowed`. | Valid combinations: diff --git a/docs/cli/schema.json b/docs/cli/schema.json index 85deddfd..a7649025 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -105764,7 +105764,7 @@ "kb", "slo" ], - "name": "find-slos-op", + "name": "list", "parameters": [ { "role": "flag", @@ -105864,6 +105864,9 @@ } ], "summary": "Get a paginated list of SLOs", + "aliases": [ + "find-slos-op" + ], "intent": { "destructive": false, "idempotent": true, @@ -105877,7 +105880,7 @@ "kb", "slo" ], - "name": "create-slo-op", + "name": "create", "parameters": [ { "role": "flag", @@ -105986,6 +105989,9 @@ } ], "summary": "Create an SLO", + "aliases": [ + "create-slo-op" + ], "intent": { "requiresAuth": true } @@ -105996,7 +106002,7 @@ "kb", "slo" ], - "name": "bulk-delete-op", + "name": "bulk-delete", "parameters": [ { "role": "flag", @@ -106030,6 +106036,9 @@ } ], "summary": "Bulk delete SLO definitions and their associated summary and rollup data.", + "aliases": [ + "bulk-delete-op" + ], "intent": { "requiresAuth": true } @@ -106040,7 +106049,7 @@ "kb", "slo" ], - "name": "bulk-delete-status-op", + "name": "bulk-delete-status", "parameters": [ { "role": "flag", @@ -106072,6 +106081,9 @@ } ], "summary": "Retrieve the status of the bulk deletion", + "aliases": [ + "bulk-delete-status-op" + ], "intent": { "destructive": false, "idempotent": true, @@ -106085,7 +106097,7 @@ "kb", "slo" ], - "name": "delete-rollup-data-op", + "name": "delete-rollup-data", "parameters": [ { "role": "flag", @@ -106132,6 +106144,9 @@ } ], "summary": "Batch delete rollup and summary data", + "aliases": [ + "delete-rollup-data-op" + ], "intent": { "requiresAuth": true } @@ -106142,7 +106157,7 @@ "kb", "slo" ], - "name": "bulk-snapshot-op", + "name": "bulk-snapshot", "parameters": [ { "role": "flag", @@ -106182,6 +106197,9 @@ } ], "summary": "Compute SLO instance summaries in bulk at a point in time", + "aliases": [ + "bulk-snapshot-op" + ], "intent": { "requiresAuth": true } @@ -106192,7 +106210,7 @@ "kb", "slo" ], - "name": "get-definitions-op", + "name": "list-definitions", "parameters": [ { "role": "flag", @@ -106267,6 +106285,9 @@ } ], "summary": "Get the SLO definitions", + "aliases": [ + "get-definitions-op" + ], "intent": { "destructive": false, "idempotent": true, @@ -106280,7 +106301,7 @@ "kb", "slo" ], - "name": "delete-slo-instances-op", + "name": "delete-instances", "parameters": [ { "role": "flag", @@ -106313,6 +106334,9 @@ } ], "summary": "Batch delete SLO instances", + "aliases": [ + "delete-slo-instances-op" + ], "intent": { "requiresAuth": true } @@ -106323,7 +106347,7 @@ "kb", "slo" ], - "name": "delete-slo-op", + "name": "delete", "parameters": [ { "role": "flag", @@ -106362,6 +106386,9 @@ } ], "summary": "Delete an SLO", + "aliases": [ + "delete-slo-op" + ], "intent": { "destructive": true, "idempotent": true, @@ -106375,7 +106402,7 @@ "kb", "slo" ], - "name": "get-slo-op", + "name": "get", "parameters": [ { "role": "flag", @@ -106424,6 +106451,9 @@ } ], "summary": "Get an SLO", + "aliases": [ + "get-slo-op" + ], "intent": { "destructive": false, "idempotent": true, @@ -106437,7 +106467,7 @@ "kb", "slo" ], - "name": "update-slo-op", + "name": "update", "parameters": [ { "role": "flag", @@ -106540,6 +106570,9 @@ } ], "summary": "Update an SLO", + "aliases": [ + "update-slo-op" + ], "intent": { "destructive": false, "idempotent": true, @@ -106553,7 +106586,7 @@ "kb", "slo" ], - "name": "reset-slo-op", + "name": "reset", "parameters": [ { "role": "flag", @@ -106585,6 +106618,9 @@ } ], "summary": "Reset an SLO", + "aliases": [ + "reset-slo-op" + ], "intent": { "requiresAuth": true } @@ -106595,7 +106631,7 @@ "kb", "slo" ], - "name": "get-snapshot-op", + "name": "get-snapshot", "parameters": [ { "role": "flag", @@ -106644,6 +106680,9 @@ } ], "summary": "Compute an SLO instance summary at a point in time", + "aliases": [ + "get-snapshot-op" + ], "intent": { "destructive": false, "idempotent": true, @@ -106657,7 +106696,7 @@ "kb", "slo" ], - "name": "disable-slo-op", + "name": "disable", "parameters": [ { "role": "flag", @@ -106689,6 +106728,9 @@ } ], "summary": "Disable an SLO", + "aliases": [ + "disable-slo-op" + ], "intent": { "requiresAuth": true } @@ -106699,7 +106741,7 @@ "kb", "slo" ], - "name": "enable-slo-op", + "name": "enable", "parameters": [ { "role": "flag", @@ -106731,6 +106773,9 @@ } ], "summary": "Enable an SLO", + "aliases": [ + "enable-slo-op" + ], "intent": { "requiresAuth": true } diff --git a/src/factory-core.ts b/src/factory-core.ts index ecc5203e..cde42376 100644 --- a/src/factory-core.ts +++ b/src/factory-core.ts @@ -76,6 +76,12 @@ export interface ParsedResult { */ export interface CommandConfig { name: string + /** + * Alternate names that invoke the same command. Each must be a valid command name, + * distinct from `name` and from the other aliases. Command policies match a leaf + * through any of its aliases as well as its canonical name. + */ + aliases?: readonly string[] description: string options?: OptionDefinition[] positionalArg?: { name: string; description: string; required?: boolean } @@ -170,7 +176,12 @@ export function isStubGroup (cmd: OpaqueCommandHandle): boolean { // --------------------------------------------------------------------------- /** - * Returns true if `commandDotPath` is permitted under the given policy. + * Returns true if the command identified by `commandDotPath` is permitted under the given policy. + * + * Pass a list to identify a leaf by its canonical dot-path plus one dot-path per alias + * (e.g. `['stack.kb.slo.delete', 'stack.kb.slo.delete-slo-op']`); an entry matches the + * command when it matches any path in the list, so policies naming a legacy alias keep + * applying after a rename. * * Matching rules: * - No policy (or empty policy) → always allowed @@ -180,16 +191,21 @@ export function isStubGroup (cmd: OpaqueCommandHandle): boolean { * (e.g. `elasticsearch.*` matches `elasticsearch.search` but NOT `elasticsearch` itself) * - All other entries are exact matches */ -export function isCommandAllowed (commandDotPath: string, policy: CommandPolicy | undefined): boolean { +export function isCommandAllowed (commandDotPath: string | readonly string[], policy: CommandPolicy | undefined): boolean { if (policy == null) return true + const paths: readonly string[] = typeof commandDotPath === 'string' ? [commandDotPath] : commandDotPath - function matches (pattern: string): boolean { + function matchesPath (path: string, pattern: string): boolean { if (pattern.endsWith('.*')) { const prefix = pattern.slice(0, -2) - return commandDotPath === prefix + '.' + commandDotPath.slice(prefix.length + 1) && - commandDotPath.startsWith(prefix + '.') + return path === prefix + '.' + path.slice(prefix.length + 1) && + path.startsWith(prefix + '.') } - return commandDotPath === pattern + return path === pattern + } + + function matches (pattern: string): boolean { + return paths.some(path => matchesPath(path, pattern)) } if (policy.profile != null) { @@ -211,6 +227,8 @@ export function isCommandAllowed (commandDotPath: string, policy: CommandPolicy * Walk the command tree and hide any commands the policy blocks. * Groups where every child is hidden are hidden too. * Stub groups (unloaded lazy namespaces) are never hidden. + * Leaves match through their canonical dot-path or any alias dot-path; groups match + * through their canonical dot-path only. * Call on the root program so dot-paths like `es.cat.health` are built correctly. */ export function hideBlockedCommands (root: OpaqueCommandHandle, policy: CommandPolicy | undefined, prefix = ''): void { @@ -222,7 +240,8 @@ export function hideBlockedCommands (root: OpaqueCommandHandle, policy: CommandP hideBlockedCommands(child, policy, path) if (subs.every(isHidden)) setHidden(child, true) } else if (!isStubGroup(child)) { - setHidden(child, !isCommandAllowed(path, policy)) + const aliasPaths = child.aliases().map(alias => prefix ? `${prefix}.${alias}` : alias) + setHidden(child, !isCommandAllowed([path, ...aliasPaths], policy)) } } } diff --git a/src/factory.ts b/src/factory.ts index b7b56348..cea896a3 100644 --- a/src/factory.ts +++ b/src/factory.ts @@ -556,8 +556,10 @@ function enforceCommandPolicy (cmd: Command, policy: CommandPolicy | undefined, // commandPath returns e.g. "elastic elasticsearch search"; strip root program name and dot-join const parts = commandPath(cmd).split(' ') // if mounted under a root program (e.g. "elastic"), strip that first segment - const dotPath = (parts.length > 1 ? parts.slice(1) : parts).join('.') - if (!isCommandAllowed(dotPath, policy)) { + const segments = parts.length > 1 ? parts.slice(1) : parts + const dotPath = segments.join('.') + const aliasPaths = cmd.aliases().map(alias => [...segments.slice(0, -1), alias].join('.')) + if (!isCommandAllowed([dotPath, ...aliasPaths], policy)) { if (jsonFormat === true) { emitError(cmd, jsonFormat, { code: 'command_blocked', @@ -740,6 +742,18 @@ async function renderResult ( */ export function defineCommand (config: CommandConfig): OpaqueCommandHandle { validateName(config.name, 'command') + const aliases = config.aliases ?? [] + const seenAliases = new Set() + for (const alias of aliases) { + validateName(alias, 'command') + if (alias === config.name) { + throw new Error(`command ${JSON.stringify(config.name)}: alias ${JSON.stringify(alias)} duplicates the command name`) + } + if (seenAliases.has(alias)) { + throw new Error(`command ${JSON.stringify(config.name)}: duplicate alias ${JSON.stringify(alias)}`) + } + seenAliases.add(alias) + } validateOptions(config.options ?? []) validateInput(config.name, config.input) // --input-file is reserved when input is a schema; catch collision at definition time @@ -748,6 +762,7 @@ export function defineCommand (config: CommandConfig): OpaqueCommandHandle { } const cmd = new Command(config.name) + if (aliases.length > 0) cmd.aliases([...aliases]) cmd.description(config.description) configureErrorOutput(cmd) cmd.configureOutput({ diff --git a/src/kb/aliases.ts b/src/kb/aliases.ts new file mode 100644 index 00000000..d510c5ef --- /dev/null +++ b/src/kb/aliases.ts @@ -0,0 +1,77 @@ +/* + * Copyright Elasticsearch B.V. and contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +/* + * Canonical CLI names and aliases for Kibana commands. + * + * Kibana command names come from `@elastic/schemas`, which derives them from Kibana's + * OpenAPI `operationId`s (e.g. `find-slos-op`). This table gives selected commands a + * short canonical name (`list*` for paginated results, `get*` for a single element) and + * keeps the upstream name as a Commander alias so existing scripts keep working. + * Commands without an entry keep their upstream name and have no aliases. + * + * Keys are upstream `@elastic/schemas` names (`def.name`), which also drive + * `loadKbApi` and request building. When upstream renames one, re-key the entry and keep + * every name already shipped (canonical and legacy) in `aliases`. + * + * No imports: this module is on the `kb --help` startup path and must not pull in + * schema definitions. + */ + +/** Canonical CLI name and alternate names for one Kibana command. */ +export interface KbCommandNaming { + /** Name shown in help, completion, and the CLI schema. */ + readonly name: string + /** Alternate names that invoke the same command; include every previously shipped name. */ + readonly aliases?: readonly string[] +} + +/** Naming overrides keyed by Kibana namespace, then by upstream `@elastic/schemas` command name. */ +export const KB_COMMAND_NAMING: Readonly>>> = { + slo: { + 'find-slos-op': { name: 'list', aliases: ['find-slos-op'] }, + 'create-slo-op': { name: 'create', aliases: ['create-slo-op'] }, + 'get-slo-op': { name: 'get', aliases: ['get-slo-op'] }, + 'update-slo-op': { name: 'update', aliases: ['update-slo-op'] }, + 'delete-slo-op': { name: 'delete', aliases: ['delete-slo-op'] }, + 'enable-slo-op': { name: 'enable', aliases: ['enable-slo-op'] }, + 'disable-slo-op': { name: 'disable', aliases: ['disable-slo-op'] }, + 'reset-slo-op': { name: 'reset', aliases: ['reset-slo-op'] }, + 'get-definitions-op': { name: 'list-definitions', aliases: ['get-definitions-op'] }, + 'get-snapshot-op': { name: 'get-snapshot', aliases: ['get-snapshot-op'] }, + 'bulk-snapshot-op': { name: 'bulk-snapshot', aliases: ['bulk-snapshot-op'] }, + 'bulk-delete-op': { name: 'bulk-delete', aliases: ['bulk-delete-op'] }, + 'bulk-delete-status-op': { name: 'bulk-delete-status', aliases: ['bulk-delete-status-op'] }, + 'delete-rollup-data-op': { name: 'delete-rollup-data', aliases: ['delete-rollup-data-op'] }, + 'delete-slo-instances-op': { name: 'delete-instances', aliases: ['delete-slo-instances-op'] }, + }, +} + +/** + * Resolves the CLI name and aliases for a Kibana command. + * + * @param namespace - Kibana namespace of the command (e.g. `slo`) + * @param upstreamName - command name from `@elastic/schemas` (e.g. `find-slos-op`) + * @returns the canonical name and aliases; the upstream name with no aliases when unmapped + */ +export function resolveKbCommandNaming (namespace: string, upstreamName: string): { name: string; aliases: readonly string[] } { + const entries = Object.hasOwn(KB_COMMAND_NAMING, namespace) ? KB_COMMAND_NAMING[namespace] : undefined + const naming = entries != null && Object.hasOwn(entries, upstreamName) ? entries[upstreamName] : undefined + if (naming == null) return { name: upstreamName, aliases: [] } + return { name: naming.name, aliases: naming.aliases ?? [] } +} + +/** + * Returns true when `token` invokes the Kibana command, by its CLI name or one of its aliases. + * + * @param namespace - Kibana namespace of the command (e.g. `slo`) + * @param upstreamName - command name from `@elastic/schemas` (e.g. `find-slos-op`) + * @param token - command token typed on the command line + * @returns whether the token names the command + */ +export function matchesKbCommandToken (namespace: string, upstreamName: string, token: string): boolean { + const { name, aliases } = resolveKbCommandNaming(namespace, upstreamName) + return token === name || aliases.includes(token) +} diff --git a/src/kb/register.ts b/src/kb/register.ts index 8564456f..d8bc39d3 100644 --- a/src/kb/register.ts +++ b/src/kb/register.ts @@ -16,6 +16,7 @@ import type { AvailabilityTarget } from '../lib/availability.ts' import { isAvailable, parseVersionHint } from '../lib/availability.ts' import { getResolvedConfig } from '../config/store.ts' import { buildStubLeaf } from '../lib/lazy-leaf.ts' +import { matchesKbCommandToken, resolveKbCommandNaming } from './aliases.ts' // Every Kibana definition passes `validateKbApiDefinition` as of @elastic/schemas 0.5.1; // the five upstream path-param defects that used to need an allowlist here are fixed. @@ -27,8 +28,10 @@ import { buildStubLeaf } from '../lib/lazy-leaf.ts' function buildLeafHandle (def: KbApiDefinition, target?: AvailabilityTarget): OpaqueCommandHandle { validateKbApiDefinition(def) const intent = def.intent ?? inferIntentFromHttp(def.method) + const { name, aliases } = resolveKbCommandNaming(def.namespace, def.name) return defineCommand({ - name: def.name, + name, + ...(aliases.length > 0 ? { aliases } : {}), description: def.description, ...(def.input !== undefined ? { input: def.input } : {}), readOnly: def.method === 'GET' || def.method === 'HEAD', @@ -42,6 +45,9 @@ function buildLeafHandle (def: KbApiDefinition, target?: AvailabilityTarget): Op /** * Sniffs `process.argv` to identify which KB leaf command the user * intends to invoke. Returns `null` on ambiguity or help requests. + * `kb ` matches canonical names and aliases; `kb ` + * matches upstream names only, so short canonical names like `list` cannot + * match across namespaces. */ function sniffInvokedLeaf (argv: readonly string[], manifest: readonly KbApiMeta[]): KbApiMeta | null { const kbIdx = argv.findIndex((a, i) => i >= 2 && (a === 'kb' || a === 'kibana')) @@ -50,7 +56,7 @@ function sniffInvokedLeaf (argv: readonly string[], manifest: readonly KbApiMeta if (afterKb.length === 0) return null const namespaces = new Set(manifest.map(m => m.namespace)) if (afterKb.length >= 2 && namespaces.has(afterKb[0]!)) { - return manifest.find(m => m.namespace === afterKb[0]! && m.name === afterKb[1]!) ?? null + return manifest.find(m => m.namespace === afterKb[0]! && matchesKbCommandToken(m.namespace, m.name, afterKb[1]!)) ?? null } if (afterKb.length >= 1 && !namespaces.has(afterKb[0]!)) { return manifest.find(m => m.name === afterKb[0]!) ?? null @@ -101,7 +107,11 @@ export async function registerKbCommandsLazy ( function leafHandleFor (m: KbApiMeta): OpaqueCommandHandle { if (invoked != null && invokedDef != null && m === invoked) return buildLeafHandle(invokedDef, target) - return buildStubLeaf(m, async () => buildLeafHandle(await loadKbApi(m), target)) + const { name, aliases } = resolveKbCommandNaming(m.namespace!, m.name) + return buildStubLeaf( + { name, description: m.description, ...(aliases.length > 0 ? { aliases } : {}) }, + async () => buildLeafHandle(await loadKbApi(m), target), + ) } const namespaceHandles: OpaqueCommandHandle[] = [] diff --git a/src/lib/lazy-leaf.ts b/src/lib/lazy-leaf.ts index 515a52e5..c7d09914 100644 --- a/src/lib/lazy-leaf.ts +++ b/src/lib/lazy-leaf.ts @@ -7,25 +7,28 @@ // graph, so loading the real leaf stays with the caller's `loadReal` callback. import { Command } from 'commander' -/** Name and description shown for a stub leaf in group-level help. */ +/** Name, aliases, and description shown for a stub leaf in group-level help. */ export interface StubLeafMeta { name: string + /** Alternate names the stub answers to; should match the real leaf's aliases. */ + aliases?: readonly string[] description: string } /** - * Builds a lightweight stub leaf: name and description only, no options. Commander - * lists it in group-level help without resolving its input schema. If the stub is - * invoked (the argv sniff missed it), it loads the real leaf via `loadReal`, swaps - * itself out of its parent for that leaf, and re-enters Commander parsing so the real - * leaf's options dispatch. + * Builds a lightweight stub leaf: name, aliases, and description only, no options. + * Commander lists it in group-level help without resolving its input schema. If the + * stub is invoked (the argv sniff missed it), by name or by alias, it loads the real + * leaf via `loadReal`, swaps itself out of its parent for that leaf, and re-enters + * Commander parsing under the canonical name so the real leaf's options dispatch. * - * @param meta - name and description for the stub + * @param meta - name, aliases, and description for the stub * @param loadReal - loads and builds the real leaf command on demand * @returns the stub command */ export function buildStubLeaf (meta: StubLeafMeta, loadReal: () => Promise): Command { const cmd = new Command(meta.name) + if (meta.aliases != null && meta.aliases.length > 0) cmd.aliases([...meta.aliases]) cmd.description(meta.description) cmd.allowUnknownOption(true) cmd.allowExcessArguments(true) diff --git a/test/cli-schema.test.ts b/test/cli-schema.test.ts index 66aefea0..f5007553 100644 --- a/test/cli-schema.test.ts +++ b/test/cli-schema.test.ts @@ -31,6 +31,7 @@ interface CliParameter { interface CliCommand { name: string + aliases?: string[] parameters: CliParameter[] } @@ -84,4 +85,15 @@ describe('cli schema', () => { assert.equal(routing?.repeatable, true) assert.equal(routing?.separator, undefined) }) + + it('emits slo commands under their canonical names with the legacy names as aliases', async () => { + const { code, stdout, stderr } = await runCliSchema() + assert.equal(code, 0, stderr) + + const schema = JSON.parse(stdout) as { namespaces: CliNamespace[] } + const slo = ['stack', 'kb', 'slo'] + assert.deepEqual(findCommand(schema.namespaces, slo, 'list')?.aliases, ['find-slos-op']) + assert.deepEqual(findCommand(schema.namespaces, slo, 'get')?.aliases, ['get-slo-op']) + assert.equal(findCommand(schema.namespaces, slo, 'find-slos-op'), undefined) + }) }) diff --git a/test/completion-cli.test.ts b/test/completion-cli.test.ts index 092628cd..31663765 100644 --- a/test/completion-cli.test.ts +++ b/test/completion-cli.test.ts @@ -81,6 +81,27 @@ describe('elastic CLI -- shell completion end-to-end', () => { assert.ok(out.candidates.includes('search')) }) + it('`__complete -- kb slo ""` lists slo canonical names and legacy aliases', async () => { + const { code, stdout } = await runCli(['__complete', '--', 'kb', 'slo', '']) + assert.equal(code, 0) + const out = parseProtocol(stdout) + for (const expected of ['list', 'get', 'find-slos-op', 'get-slo-op']) { + assert.ok(out.candidates.includes(expected), `missing "${expected}" in ${out.candidates.join(',')}`) + } + }) + + it('`__complete -- kb slo get-slo-op --` lists the flags of the leaf reached through its alias', async () => { + const { code, stdout } = await runCli(['__complete', '--', 'kb', 'slo', 'get-slo-op', '--']) + assert.equal(code, 0) + assert.ok(parseProtocol(stdout).candidates.includes('--id')) + }) + + it('`__complete -- kb slo list --` lists the flags of the leaf reached through its canonical name', async () => { + const { code, stdout } = await runCli(['__complete', '--', 'kb', 'slo', 'list', '--']) + assert.equal(code, 0) + assert.ok(parseProtocol(stdout).candidates.includes('--kql-query')) + }) + it('`__complete -- --use-context ""` lists context names from a temp config', async () => { const dir = await mkdtemp(join(tmpdir(), 'elastic-cli-complete-')) try { diff --git a/test/factory.test.ts b/test/factory.test.ts index 1d014a46..fc416f8e 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -724,6 +724,65 @@ describe('defineCommand', () => { }) }) + describe('aliases', () => { + it('registers aliases on the command', () => { + const cmd = defineCommand({ name: 'get', aliases: ['legacy-op'], description: 'Get', handler: () => ({}) }) + assert.deepEqual(cmd.aliases(), ['legacy-op']) + }) + + it('runs the handler when invoked through an alias inside a group', async () => { + const received: ParsedResult[] = [] + const cmd = defineCommand({ + name: 'get', + aliases: ['legacy-op'], + description: 'Get', + handler: (p) => { received.push(p); return {} }, + }) + const group = defineGroup({ name: 'slo', description: 'SLO' }, cmd) + group.exitOverride() + await captureDuring(() => group.parseAsync(['legacy-op'], { from: 'user' })) + assert.equal(received.length, 1) + }) + + it('throws when an alias is not a valid command name', () => { + assert.throws( + () => defineCommand({ name: 'get', aliases: ['Bad'], description: 'Get', handler: () => ({}) }), + /invalid command name/, + ) + }) + + it('throws when an alias is repeated', () => { + assert.throws( + () => defineCommand({ name: 'get', aliases: ['a', 'a'], description: 'Get', handler: () => ({}) }), + /duplicate alias "a"/, + ) + }) + + it('throws when an alias equals the command name', () => { + assert.throws( + () => defineCommand({ name: 'get', aliases: ['get'], description: 'Get', handler: () => ({}) }), + /alias "get" duplicates the command name/, + ) + }) + + it('lists leaf aliases in group --help --json output', async () => { + const cmd = defineCommand({ name: 'get', aliases: ['legacy-op'], description: 'Get', handler: () => ({}) }) + const group = defineGroup({ name: 'slo', description: 'SLO' }, cmd) + const prog = new Command('elastic') + prog.option('--json', 'output as JSON') + prog.addCommand(group) + prog.exitOverride() + group.exitOverride() + let out = '' + group.configureOutput({ writeOut: (s) => { out += s } }) + try { + await prog.parseAsync(['--json', 'slo', '--help'], { from: 'user' }) + } catch { /* exitOverride throws on --help */ } + const parsed = JSON.parse(out) as { commands: Array<{ name: string; aliases?: string[] }> } + assert.deepEqual(parsed.commands.find((c) => c.name === 'get')?.aliases, ['legacy-op']) + }) + }) + describe('option short alias validation', () => { it('throws when short alias is more than one character', () => { assert.throws( @@ -3075,6 +3134,30 @@ describe('isCommandAllowed', () => { // cloud.hosted is already blocked by the serverless profile; the extra blocked entry doesn't matter assert.equal(isCommandAllowed('cloud.hosted.deployments.list', policy), false) }) + + // --- canonical path plus alias paths --- + + const sloDeletePaths = ['stack.kb.slo.delete', 'stack.kb.slo.delete-slo-op'] + + it('path list: blocked entry naming an alias path blocks the command', () => { + assert.equal(isCommandAllowed(sloDeletePaths, { blocked: ['stack.kb.slo.delete-slo-op'] }), false) + }) + + it('path list: allowed entry naming an alias path permits the command', () => { + assert.equal(isCommandAllowed(sloDeletePaths, { allowed: ['stack.kb.slo.delete-slo-op'] }), true) + }) + + it('path list: wildcard still matches', () => { + assert.equal(isCommandAllowed(sloDeletePaths, { allowed: ['stack.kb.slo.*'] }), true) + }) + + it('path list: profile + blocked entry naming an alias path blocks the command', () => { + assert.equal(isCommandAllowed(sloDeletePaths, { profile: 'stack', blocked: ['stack.kb.slo.delete-slo-op'] }), false) + }) + + it('path list: permits the command when no path matches a blocked entry', () => { + assert.equal(isCommandAllowed(sloDeletePaths, { blocked: ['stack.kb.slo.get'] }), true) + }) }) describe('command policy enforcement', () => { @@ -3178,6 +3261,50 @@ describe('command policy enforcement', () => { const err = parsed['error'] as Record assert.equal(err['code'], 'command_blocked') }) + + describe('blocked entry naming a leaf alias', () => { + async function runSloDelete (argv: string[]): Promise<{ handlerCalled: boolean, stderr: string }> { + let handlerCalled = false + const leaf = defineCommand({ + name: 'delete', + aliases: ['delete-slo-op'], + description: 'Delete', + handler: () => { handlerCalled = true; return {} }, + }) + const group = defineGroup({ name: 'slo', description: 'SLO' }, leaf) + const prog = new Command('elastic') + prog.option('--json', 'output as JSON') + prog.addCommand(group) + prog.exitOverride() + group.exitOverride() + leaf.exitOverride() + const { stderr } = await captureStreams(() => prog.parseAsync(argv, { from: 'user' }).then(() => {})) + return { handlerCalled, stderr } + } + + beforeEach(() => { + setResolvedConfig({ context: {}, commands: { blocked: ['slo.delete-slo-op'] } }) + }) + + it('blocks the command invoked by its canonical name', async () => { + const { handlerCalled, stderr } = await runSloDelete(['slo', 'delete']) + assert.equal(handlerCalled, false) + assert.match(stderr, /command "slo\.delete" is not allowed/) + }) + + it('blocks the command invoked by its alias', async () => { + const { handlerCalled, stderr } = await runSloDelete(['slo', 'delete-slo-op']) + assert.equal(handlerCalled, false) + assert.match(stderr, /command "slo\.delete" is not allowed/) + }) + + it('emits command_blocked with --json', async () => { + const { handlerCalled, stderr } = await runSloDelete(['--json', 'slo', 'delete-slo-op']) + assert.equal(handlerCalled, false) + const parsed = JSON.parse(stderr) as { error: { code: string } } + assert.equal(parsed.error.code, 'command_blocked') + }) + }) }) describe('hideBlockedCommands', () => { @@ -3250,6 +3377,20 @@ describe('hideBlockedCommands', () => { assert.equal((leaf as unknown as Record)['_hidden'], true) assert.equal((inner as unknown as Record)['_hidden'], true) }) + + it('hides a leaf when a blocked entry names its alias', () => { + const cmd = defineCommand({ name: 'search', aliases: ['legacy-op'], description: 'Search', handler: () => ({}) }) + const root = makeRoot(defineGroup({ name: 'es', description: 'ES' }, cmd)) + hideBlockedCommands(root, { blocked: ['es.legacy-op'] }) + assert.equal((cmd as unknown as Record)['_hidden'], true) + }) + + it('shows a leaf when an allowed entry names its alias', () => { + const cmd = defineCommand({ name: 'search', aliases: ['legacy-op'], description: 'Search', handler: () => ({}) }) + const root = makeRoot(defineGroup({ name: 'es', description: 'ES' }, cmd)) + hideBlockedCommands(root, { allowed: ['es.legacy-op'] }) + assert.equal((cmd as unknown as Record)['_hidden'], false) + }) }) describe('no Commander API leaks', () => { diff --git a/test/kb/aliases.test.ts b/test/kb/aliases.test.ts new file mode 100644 index 00000000..95a067d0 --- /dev/null +++ b/test/kb/aliases.test.ts @@ -0,0 +1,122 @@ +/* + * Copyright Elasticsearch B.V. and contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it } from 'node:test' +import assert from 'node:assert/strict' +import { KB_COMMAND_NAMING, resolveKbCommandNaming, matchesKbCommandToken } from '../../src/kb/aliases.ts' +import { kbApiManifest } from '../../src/kb/apis.ts' +import { validateName } from '../../src/factory-core.ts' + +describe('KB_COMMAND_NAMING', () => { + it('maps every slo upstream name to its canonical name and legacy alias', () => { + assert.deepEqual(KB_COMMAND_NAMING['slo'], { + 'find-slos-op': { name: 'list', aliases: ['find-slos-op'] }, + 'create-slo-op': { name: 'create', aliases: ['create-slo-op'] }, + 'get-slo-op': { name: 'get', aliases: ['get-slo-op'] }, + 'update-slo-op': { name: 'update', aliases: ['update-slo-op'] }, + 'delete-slo-op': { name: 'delete', aliases: ['delete-slo-op'] }, + 'enable-slo-op': { name: 'enable', aliases: ['enable-slo-op'] }, + 'disable-slo-op': { name: 'disable', aliases: ['disable-slo-op'] }, + 'reset-slo-op': { name: 'reset', aliases: ['reset-slo-op'] }, + 'get-definitions-op': { name: 'list-definitions', aliases: ['get-definitions-op'] }, + 'get-snapshot-op': { name: 'get-snapshot', aliases: ['get-snapshot-op'] }, + 'bulk-snapshot-op': { name: 'bulk-snapshot', aliases: ['bulk-snapshot-op'] }, + 'bulk-delete-op': { name: 'bulk-delete', aliases: ['bulk-delete-op'] }, + 'bulk-delete-status-op': { name: 'bulk-delete-status', aliases: ['bulk-delete-status-op'] }, + 'delete-rollup-data-op': { name: 'delete-rollup-data', aliases: ['delete-rollup-data-op'] }, + 'delete-slo-instances-op': { name: 'delete-instances', aliases: ['delete-slo-instances-op'] }, + }) + }) + + it('has entries for every key in the current Kibana manifest', () => { + const missing: string[] = [] + for (const [namespace, entries] of Object.entries(KB_COMMAND_NAMING)) { + for (const upstreamName of Object.keys(entries)) { + if (!kbApiManifest.some(m => m.namespace === namespace && m.name === upstreamName)) { + missing.push(`${namespace} ${upstreamName}`) + } + } + } + assert.deepEqual(missing, []) + }) + + it('keeps every renamed upstream name as an alias', () => { + const dropped: string[] = [] + for (const [namespace, entries] of Object.entries(KB_COMMAND_NAMING)) { + for (const [upstreamName, naming] of Object.entries(entries)) { + if (naming.name !== upstreamName && !(naming.aliases ?? []).includes(upstreamName)) { + dropped.push(`${namespace} ${upstreamName}`) + } + } + } + assert.deepEqual(dropped, []) + }) + + it('uses valid command names for every resolved name and alias', () => { + for (const m of kbApiManifest) { + const { name, aliases } = resolveKbCommandNaming(m.namespace ?? '', m.name) + for (const n of [name, ...aliases]) assert.doesNotThrow(() => validateName(n, 'command'), `${m.namespace} ${n}`) + } + }) + + it('has no duplicate names or aliases within a namespace', () => { + const seen = new Map>() + const duplicates: string[] = [] + for (const m of kbApiManifest) { + const namespace = m.namespace ?? '' + let names = seen.get(namespace) + if (names == null) { + names = new Set() + seen.set(namespace, names) + } + const { name, aliases } = resolveKbCommandNaming(namespace, m.name) + for (const n of [name, ...aliases]) { + if (names.has(n)) duplicates.push(`${namespace} ${n}`) + names.add(n) + } + } + assert.deepEqual(duplicates, []) + }) +}) + +describe('resolveKbCommandNaming', () => { + it('returns the upstream name with no aliases for an unmapped command', () => { + assert.deepEqual(resolveKbCommandNaming('spaces', 'get-spaces-space'), { name: 'get-spaces-space', aliases: [] }) + }) + + it('returns the canonical name and aliases for a mapped command', () => { + assert.deepEqual(resolveKbCommandNaming('slo', 'find-slos-op'), { name: 'list', aliases: ['find-slos-op'] }) + }) + + it('ignores prototype keys', () => { + for (const key of ['constructor', '__proto__', 'toString']) { + assert.deepEqual(resolveKbCommandNaming(key, 'find-slos-op'), { name: 'find-slos-op', aliases: [] }) + assert.deepEqual(resolveKbCommandNaming('slo', key), { name: key, aliases: [] }) + } + }) +}) + +describe('matchesKbCommandToken', () => { + it('matches the canonical name and the legacy alias', () => { + assert.equal(matchesKbCommandToken('slo', 'find-slos-op', 'list'), true) + assert.equal(matchesKbCommandToken('slo', 'find-slos-op', 'find-slos-op'), true) + }) + + it('does not match an unrelated token', () => { + assert.equal(matchesKbCommandToken('slo', 'find-slos-op', 'find'), false) + }) + + it('matches the upstream name of an unmapped command', () => { + assert.equal(matchesKbCommandToken('spaces', 'get-spaces-space', 'get-spaces-space'), true) + }) + + it('never matches through prototype keys', () => { + for (const key of ['constructor', '__proto__', 'toString']) { + assert.equal(matchesKbCommandToken(key, 'find-slos-op', 'list'), false) + assert.equal(matchesKbCommandToken('slo', key, 'list'), false) + assert.equal(matchesKbCommandToken('slo', 'find-slos-op', key), false) + } + }) +}) diff --git a/test/kb/register.test.ts b/test/kb/register.test.ts index 14e05d92..d59a7442 100644 --- a/test/kb/register.test.ts +++ b/test/kb/register.test.ts @@ -201,3 +201,110 @@ describe('registerKbCommandsLazy', () => { assert.deepEqual(urls, ['http://localhost:5601/api/spaces/space?purpose=any']) }) }) + +describe('slo command naming', () => { + const SLO_NAMES: ReadonlyArray = [ + ['list', 'find-slos-op'], + ['create', 'create-slo-op'], + ['get', 'get-slo-op'], + ['update', 'update-slo-op'], + ['delete', 'delete-slo-op'], + ['enable', 'enable-slo-op'], + ['disable', 'disable-slo-op'], + ['reset', 'reset-slo-op'], + ['list-definitions', 'get-definitions-op'], + ['get-snapshot', 'get-snapshot-op'], + ['bulk-snapshot', 'bulk-snapshot-op'], + ['bulk-delete', 'bulk-delete-op'], + ['bulk-delete-status', 'bulk-delete-status-op'], + ['delete-rollup-data', 'delete-rollup-data-op'], + ['delete-instances', 'delete-slo-instances-op'], + ] + + async function sloDefs (): Promise { + return (await loadAllKbApis()).filter((d) => d.namespace === 'slo') + } + + function sloLeaf (kb: Command, name: string): Command | undefined { + return kb.commands.find((c) => c.name() === 'slo')?.commands.find((c) => c.name() === name) + } + + it('registers slo leaves under canonical names with legacy aliases', async () => { + const kb = registerKbCommands(await sloDefs()) + const slo = kb.commands.find((c) => c.name() === 'slo') + assert.ok(slo != null) + assert.deepEqual( + new Map(slo.commands.map((c) => [c.name(), c.aliases()])), + new Map(SLO_NAMES.map(([name, alias]) => [name, [alias]])), + ) + }) + + it('throws when a command name collides with another command name in the namespace', async () => { + const synthetic: KbApiDefinition = { + name: 'list', + namespace: 'slo', + description: 'x', + method: 'GET', + path: '/api/observability/slos', + } + const defs = await sloDefs() + assert.throws(() => registerKbCommands([...defs, synthetic]), /cannot add command 'list'/) + }) + + for (const token of ['list', 'find-slos-op']) { + it(`loads the real slo list leaf when argv names it as ${token}`, async () => { + const kb = await registerKbCommandsLazy({ argv: ['node', 'elastic', 'kb', 'slo', token] }) + const leaf = sloLeaf(kb, 'list') + assert.ok(leaf != null) + assert.equal(hasDryRun(leaf), true) + }) + } + + it('builds slo stubs with canonical names and legacy aliases when argv names no leaf', async () => { + const kb = await registerKbCommandsLazy({ argv: ['node', 'elastic', 'kb', 'slo'] }) + const stub = sloLeaf(kb, 'get') + assert.ok(stub != null) + assert.deepEqual(stub.aliases(), ['get-slo-op']) + assert.equal(hasDryRun(stub), false) + }) + + it('does not sniff a canonical slo name when the namespace token is omitted', async () => { + const kb = await registerKbCommandsLazy({ argv: ['node', 'elastic', 'kb', 'list'] }) + const leaf = sloLeaf(kb, 'list') + assert.ok(leaf != null) + assert.equal(hasDryRun(leaf), false) + }) + + it('swaps a stub for the real leaf when invoked through its alias after the sniff misses', async (t) => { + // the sniffer takes the `--use-context` value as the kb token and misses the leaf + const argv = ['node', 'elastic', '--use-context', 'kb', 'kb', 'slo', 'get-slo-op', '--id', 'my-slo'] + const kb = await registerKbCommandsLazy({ argv }) + const stub = sloLeaf(kb, 'get') + assert.ok(stub != null) + assert.equal(hasDryRun(stub), false) + + const getDef = (await sloDefs()).find((d) => d.name === 'get-slo-op') + assert.ok(getDef != null) + + setResolvedConfig({ context: { kibana: { url: 'http://localhost:5601', auth: { api_key: 'k' } } } }) + t.after(() => { + _testResetKibanaClient() + setResolvedConfig({ context: {} } as ResolvedConfig) + }) + const urls: string[] = [] + getKibanaClient()._testSetFetch(async (url) => { + urls.push(String(url)) + return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } }) + }) + t.mock.method(process, 'exit', (code?: number) => { throw new Error(`process.exit(${code})`) }) + // stdin is not a TTY under the test runner; on Windows an open stdin pipe blocks readFileSync(0) + t.after(_testSetStdinReader(() => '')) + capture(t) + + const root = new Command('elastic').option('--use-context ').addCommand(kb) + await root.parseAsync(argv) + + assert.equal(urls.length, 1) + assert.equal(new URL(urls[0]!).pathname, getDef.path.replace('{id}', 'my-slo')) + }) +}) diff --git a/test/lib/lazy-leaf.test.ts b/test/lib/lazy-leaf.test.ts new file mode 100644 index 00000000..c2e11680 --- /dev/null +++ b/test/lib/lazy-leaf.test.ts @@ -0,0 +1,54 @@ +/* + * Copyright Elasticsearch B.V. and contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it } from 'node:test' +import assert from 'node:assert/strict' +import { Command } from 'commander' +import { buildStubLeaf } from '../../src/lib/lazy-leaf.ts' +import { defineCommand } from '../../src/factory.ts' +import type { ParsedResult } from '../../src/factory-core.ts' +import { capture } from '../helpers/capture.ts' + +describe('buildStubLeaf', () => { + it('registers aliases on the stub', () => { + const stub = buildStubLeaf( + { name: 'get', description: 'd', aliases: ['get-slo-op'] }, + async () => new Command('get'), + ) + assert.deepEqual(stub.aliases(), ['get-slo-op']) + }) + + it('has no aliases when none are given', () => { + const stub = buildStubLeaf({ name: 'get', description: 'd' }, async () => new Command('get')) + assert.deepEqual(stub.aliases(), []) + }) + + it('swaps itself for the real leaf when invoked through an alias', async (t) => { + const received: ParsedResult[] = [] + const real = defineCommand({ + name: 'get', + aliases: ['get-slo-op'], + description: 'd', + options: [{ long: 'id', type: 'string', description: 'id' }], + handler: (p) => { received.push(p); return {} }, + }) + let loads = 0 + const stub = buildStubLeaf( + { name: 'get', description: 'd', aliases: ['get-slo-op'] }, + async () => { loads++; return real }, + ) + const parent = new Command('slo') + parent.exitOverride() + parent.addCommand(stub) + capture(t) + + await parent.parseAsync(['get-slo-op', '--id', 'x'], { from: 'user' }) + + assert.equal(loads, 1) + assert.deepEqual(parent.commands, [real]) + assert.equal(received.length, 1) + assert.equal(received[0]?.options['id'], 'x') + }) +}) From f61eb82008db34da2a96f328353177637992e0f4 Mon Sep 17 00:00:00 2001 From: Kevin Delemme Date: Mon, 30 Nov 2026 10:23:05 -0500 Subject: [PATCH 2/3] docs(config): limit policy alias matching to leaf commands Group aliases (e.g. stack.kibana) are not matched by commands.allowed or commands.blocked; entries must use canonical group names. --- docs/cli/configuration_reference.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/cli/configuration_reference.md b/docs/cli/configuration_reference.md index ff4528bb..ca76890a 100644 --- a/docs/cli/configuration_reference.md +++ b/docs/cli/configuration_reference.md @@ -66,8 +66,8 @@ Policy controlling which commands are permitted to run. Applies at the root leve | Name | Type | Required | Default value | Description | | - | - | - | - | - | | `profile` | string (`serverless` \| `stack` \| `default`) | no | - | Built-in allow-list profile. Mutually exclusive with `allowed`. | -| `allowed` | array of strings | no | - | Explicit allow-list of command names/namespaces. Entries can use a trailing wildcard (example: `stack.es.*`) to match a namespace. An entry naming a command's alias matches the command (example: `stack.kb.slo.delete-slo-op` applies to `stack.kb.slo.delete`). Mutually exclusive with `profile` and `blocked`. | -| `blocked` | array of strings | no | - | Explicit deny-list of command names/namespaces (everything else is allowed). Entries can use a trailing wildcard. An entry naming a command's alias matches the command (example: `stack.kb.slo.delete-slo-op` applies to `stack.kb.slo.delete`). Mutually exclusive with `allowed`. | +| `allowed` | array of strings | no | - | Explicit allow-list of command names/namespaces. Entries can use a trailing wildcard (example: `stack.es.*`) to match a namespace. An entry naming a leaf command's alias matches the command (example: `stack.kb.slo.delete-slo-op` applies to `stack.kb.slo.delete`); group aliases do not match, so use canonical group names (`stack.kb`, not `stack.kibana`). Mutually exclusive with `profile` and `blocked`. | +| `blocked` | array of strings | no | - | Explicit deny-list of command names/namespaces (everything else is allowed). Entries can use a trailing wildcard. An entry naming a leaf command's alias matches the command (example: `stack.kb.slo.delete-slo-op` applies to `stack.kb.slo.delete`); group aliases do not match, so use canonical group names (`stack.kb`, not `stack.kibana`). Mutually exclusive with `allowed`. | Valid combinations: From 0ddf5b58e07322beb1bd57c75db2dcd2b8da6d1f Mon Sep 17 00:00:00 2001 From: Kevin Delemme Date: Mon, 30 Nov 2026 10:32:54 -0500 Subject: [PATCH 3/3] feat(kb)!: drop legacy slo command names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 15 `elastic kb slo` commands are registered under their short names only. Kibana operationId names such as `find-slos-op` are no longer aliases: the CLI is in technical preview, so renames are clean breaks (as in #199 and #201). Generic command alias support and alias-aware policy matching are removed with them. BREAKING CHANGE: `elastic kb slo` commands answer to their short names only (`find-slos-op` → `list`, `get-definitions-op` → `list-definitions`, ...). Update `commands.allowed`/`commands.blocked` entries that name the old paths. --- codegen/functional/kb.ts | 10 +- codegen/functional/test/mapper.test.ts | 4 +- docs/cli/configuration_reference.md | 4 +- docs/cli/schema.json | 45 -------- src/factory-core.ts | 33 ++---- src/factory.ts | 19 +--- src/kb/aliases.ts | 77 -------------- src/kb/command-names.ts | 54 ++++++++++ src/kb/register.ts | 16 ++- src/lib/lazy-leaf.ts | 17 ++- test/cli-schema.test.ts | 7 +- test/cli.test.ts | 24 +++++ test/completion-cli.test.ts | 13 +-- test/factory.test.ts | 141 ------------------------- test/kb/aliases.test.ts | 122 --------------------- test/kb/command-names.test.ts | 85 +++++++++++++++ test/kb/register.test.ts | 65 ++++++------ test/lib/lazy-leaf.test.ts | 54 ---------- 18 files changed, 238 insertions(+), 552 deletions(-) delete mode 100644 src/kb/aliases.ts create mode 100644 src/kb/command-names.ts delete mode 100644 test/kb/aliases.test.ts create mode 100644 test/kb/command-names.test.ts delete mode 100644 test/lib/lazy-leaf.test.ts diff --git a/codegen/functional/kb.ts b/codegen/functional/kb.ts index 8ce9e52d..16a27fa8 100644 --- a/codegen/functional/kb.ts +++ b/codegen/functional/kb.ts @@ -21,15 +21,15 @@ * * Definitions reference upstream `@elastic/schemas` names (e.g. `slo.find_slos_op`). * Each definition is loaded with a precomputed `cliPath` built by - * `resolveKbCommandNaming` (which `src/kb/register.ts` also uses), so scripts - * invoke the canonical CLI name (e.g. `stack kb slo list`) rather than the - * upstream name. + * `resolveKbCommandName` (which `src/kb/register.ts` also uses), so scripts + * invoke the CLI name (e.g. `stack kb slo list`); the upstream name is not + * registered for renamed commands. */ import { readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs' import { join, basename } from 'node:path' import { loadAllKbApis } from '../../src/kb/apis.ts' -import { resolveKbCommandNaming } from '../../src/kb/aliases.ts' +import { resolveKbCommandName } from '../../src/kb/command-names.ts' import { parseTestFile, shouldSkipServerlessProject, shouldSkipStackVersion, stackSinceFor } from './parser.ts' import stackSince from './stack-since.json' with { type: 'json' } import { generateScript, generateRunner, type RunnerScript } from './generator.ts' @@ -94,7 +94,7 @@ const STREAM_IMPORT_PREAMBLE = [ const apis = (await loadAllKbApis()).map((def) => ({ ...def, - cliPath: [def.namespace, resolveKbCommandNaming(def.namespace, def.name).name], + cliPath: [def.namespace, resolveKbCommandName(def.namespace, def.name)], })) mkdirSync(OUT_DIR, { recursive: true }) diff --git a/codegen/functional/test/mapper.test.ts b/codegen/functional/test/mapper.test.ts index b785d27a..e8cd7c32 100644 --- a/codegen/functional/test/mapper.test.ts +++ b/codegen/functional/test/mapper.test.ts @@ -8,7 +8,7 @@ import assert from 'node:assert/strict' import { buildActionMap, mapAction } from '../mapper.ts' import type { EsApiDefinition } from '../../../src/es/types.ts' import type { ApiActionDef } from '../types.ts' -import { resolveKbCommandNaming } from '../../../src/kb/aliases.ts' +import { resolveKbCommandName } from '../../../src/kb/command-names.ts' const testDefs: EsApiDefinition[] = [ { @@ -182,7 +182,7 @@ describe('mapAction', () => { namespace: 'slo', name: 'find-slos-op', method: 'GET', - cliPath: ['slo', resolveKbCommandNaming('slo', 'find-slos-op').name], + cliPath: ['slo', resolveKbCommandName('slo', 'find-slos-op')], } const result = mapAction('slo.find_slos_op', {}, buildActionMap([def]), ['stack', 'kb']) assert.deepStrictEqual(result?.cliArgs, ['stack', 'kb', 'slo', 'list']) diff --git a/docs/cli/configuration_reference.md b/docs/cli/configuration_reference.md index ca76890a..bcc40e3b 100644 --- a/docs/cli/configuration_reference.md +++ b/docs/cli/configuration_reference.md @@ -66,8 +66,8 @@ Policy controlling which commands are permitted to run. Applies at the root leve | Name | Type | Required | Default value | Description | | - | - | - | - | - | | `profile` | string (`serverless` \| `stack` \| `default`) | no | - | Built-in allow-list profile. Mutually exclusive with `allowed`. | -| `allowed` | array of strings | no | - | Explicit allow-list of command names/namespaces. Entries can use a trailing wildcard (example: `stack.es.*`) to match a namespace. An entry naming a leaf command's alias matches the command (example: `stack.kb.slo.delete-slo-op` applies to `stack.kb.slo.delete`); group aliases do not match, so use canonical group names (`stack.kb`, not `stack.kibana`). Mutually exclusive with `profile` and `blocked`. | -| `blocked` | array of strings | no | - | Explicit deny-list of command names/namespaces (everything else is allowed). Entries can use a trailing wildcard. An entry naming a leaf command's alias matches the command (example: `stack.kb.slo.delete-slo-op` applies to `stack.kb.slo.delete`); group aliases do not match, so use canonical group names (`stack.kb`, not `stack.kibana`). Mutually exclusive with `allowed`. | +| `allowed` | array of strings | no | - | Explicit allow-list of command names/namespaces. Entries can use a trailing wildcard (example: `stack.es.*`) to match a namespace. Mutually exclusive with `profile` and `blocked`. | +| `blocked` | array of strings | no | - | Explicit deny-list of command names/namespaces (everything else is allowed). Entries can use a trailing wildcard. Mutually exclusive with `allowed`. | Valid combinations: diff --git a/docs/cli/schema.json b/docs/cli/schema.json index a7649025..de3044ce 100644 --- a/docs/cli/schema.json +++ b/docs/cli/schema.json @@ -105864,9 +105864,6 @@ } ], "summary": "Get a paginated list of SLOs", - "aliases": [ - "find-slos-op" - ], "intent": { "destructive": false, "idempotent": true, @@ -105989,9 +105986,6 @@ } ], "summary": "Create an SLO", - "aliases": [ - "create-slo-op" - ], "intent": { "requiresAuth": true } @@ -106036,9 +106030,6 @@ } ], "summary": "Bulk delete SLO definitions and their associated summary and rollup data.", - "aliases": [ - "bulk-delete-op" - ], "intent": { "requiresAuth": true } @@ -106081,9 +106072,6 @@ } ], "summary": "Retrieve the status of the bulk deletion", - "aliases": [ - "bulk-delete-status-op" - ], "intent": { "destructive": false, "idempotent": true, @@ -106144,9 +106132,6 @@ } ], "summary": "Batch delete rollup and summary data", - "aliases": [ - "delete-rollup-data-op" - ], "intent": { "requiresAuth": true } @@ -106197,9 +106182,6 @@ } ], "summary": "Compute SLO instance summaries in bulk at a point in time", - "aliases": [ - "bulk-snapshot-op" - ], "intent": { "requiresAuth": true } @@ -106285,9 +106267,6 @@ } ], "summary": "Get the SLO definitions", - "aliases": [ - "get-definitions-op" - ], "intent": { "destructive": false, "idempotent": true, @@ -106334,9 +106313,6 @@ } ], "summary": "Batch delete SLO instances", - "aliases": [ - "delete-slo-instances-op" - ], "intent": { "requiresAuth": true } @@ -106386,9 +106362,6 @@ } ], "summary": "Delete an SLO", - "aliases": [ - "delete-slo-op" - ], "intent": { "destructive": true, "idempotent": true, @@ -106451,9 +106424,6 @@ } ], "summary": "Get an SLO", - "aliases": [ - "get-slo-op" - ], "intent": { "destructive": false, "idempotent": true, @@ -106570,9 +106540,6 @@ } ], "summary": "Update an SLO", - "aliases": [ - "update-slo-op" - ], "intent": { "destructive": false, "idempotent": true, @@ -106618,9 +106585,6 @@ } ], "summary": "Reset an SLO", - "aliases": [ - "reset-slo-op" - ], "intent": { "requiresAuth": true } @@ -106680,9 +106644,6 @@ } ], "summary": "Compute an SLO instance summary at a point in time", - "aliases": [ - "get-snapshot-op" - ], "intent": { "destructive": false, "idempotent": true, @@ -106728,9 +106689,6 @@ } ], "summary": "Disable an SLO", - "aliases": [ - "disable-slo-op" - ], "intent": { "requiresAuth": true } @@ -106773,9 +106731,6 @@ } ], "summary": "Enable an SLO", - "aliases": [ - "enable-slo-op" - ], "intent": { "requiresAuth": true } diff --git a/src/factory-core.ts b/src/factory-core.ts index cde42376..ecc5203e 100644 --- a/src/factory-core.ts +++ b/src/factory-core.ts @@ -76,12 +76,6 @@ export interface ParsedResult { */ export interface CommandConfig { name: string - /** - * Alternate names that invoke the same command. Each must be a valid command name, - * distinct from `name` and from the other aliases. Command policies match a leaf - * through any of its aliases as well as its canonical name. - */ - aliases?: readonly string[] description: string options?: OptionDefinition[] positionalArg?: { name: string; description: string; required?: boolean } @@ -176,12 +170,7 @@ export function isStubGroup (cmd: OpaqueCommandHandle): boolean { // --------------------------------------------------------------------------- /** - * Returns true if the command identified by `commandDotPath` is permitted under the given policy. - * - * Pass a list to identify a leaf by its canonical dot-path plus one dot-path per alias - * (e.g. `['stack.kb.slo.delete', 'stack.kb.slo.delete-slo-op']`); an entry matches the - * command when it matches any path in the list, so policies naming a legacy alias keep - * applying after a rename. + * Returns true if `commandDotPath` is permitted under the given policy. * * Matching rules: * - No policy (or empty policy) → always allowed @@ -191,21 +180,16 @@ export function isStubGroup (cmd: OpaqueCommandHandle): boolean { * (e.g. `elasticsearch.*` matches `elasticsearch.search` but NOT `elasticsearch` itself) * - All other entries are exact matches */ -export function isCommandAllowed (commandDotPath: string | readonly string[], policy: CommandPolicy | undefined): boolean { +export function isCommandAllowed (commandDotPath: string, policy: CommandPolicy | undefined): boolean { if (policy == null) return true - const paths: readonly string[] = typeof commandDotPath === 'string' ? [commandDotPath] : commandDotPath - function matchesPath (path: string, pattern: string): boolean { + function matches (pattern: string): boolean { if (pattern.endsWith('.*')) { const prefix = pattern.slice(0, -2) - return path === prefix + '.' + path.slice(prefix.length + 1) && - path.startsWith(prefix + '.') + return commandDotPath === prefix + '.' + commandDotPath.slice(prefix.length + 1) && + commandDotPath.startsWith(prefix + '.') } - return path === pattern - } - - function matches (pattern: string): boolean { - return paths.some(path => matchesPath(path, pattern)) + return commandDotPath === pattern } if (policy.profile != null) { @@ -227,8 +211,6 @@ export function isCommandAllowed (commandDotPath: string | readonly string[], po * Walk the command tree and hide any commands the policy blocks. * Groups where every child is hidden are hidden too. * Stub groups (unloaded lazy namespaces) are never hidden. - * Leaves match through their canonical dot-path or any alias dot-path; groups match - * through their canonical dot-path only. * Call on the root program so dot-paths like `es.cat.health` are built correctly. */ export function hideBlockedCommands (root: OpaqueCommandHandle, policy: CommandPolicy | undefined, prefix = ''): void { @@ -240,8 +222,7 @@ export function hideBlockedCommands (root: OpaqueCommandHandle, policy: CommandP hideBlockedCommands(child, policy, path) if (subs.every(isHidden)) setHidden(child, true) } else if (!isStubGroup(child)) { - const aliasPaths = child.aliases().map(alias => prefix ? `${prefix}.${alias}` : alias) - setHidden(child, !isCommandAllowed([path, ...aliasPaths], policy)) + setHidden(child, !isCommandAllowed(path, policy)) } } } diff --git a/src/factory.ts b/src/factory.ts index cea896a3..b7b56348 100644 --- a/src/factory.ts +++ b/src/factory.ts @@ -556,10 +556,8 @@ function enforceCommandPolicy (cmd: Command, policy: CommandPolicy | undefined, // commandPath returns e.g. "elastic elasticsearch search"; strip root program name and dot-join const parts = commandPath(cmd).split(' ') // if mounted under a root program (e.g. "elastic"), strip that first segment - const segments = parts.length > 1 ? parts.slice(1) : parts - const dotPath = segments.join('.') - const aliasPaths = cmd.aliases().map(alias => [...segments.slice(0, -1), alias].join('.')) - if (!isCommandAllowed([dotPath, ...aliasPaths], policy)) { + const dotPath = (parts.length > 1 ? parts.slice(1) : parts).join('.') + if (!isCommandAllowed(dotPath, policy)) { if (jsonFormat === true) { emitError(cmd, jsonFormat, { code: 'command_blocked', @@ -742,18 +740,6 @@ async function renderResult ( */ export function defineCommand (config: CommandConfig): OpaqueCommandHandle { validateName(config.name, 'command') - const aliases = config.aliases ?? [] - const seenAliases = new Set() - for (const alias of aliases) { - validateName(alias, 'command') - if (alias === config.name) { - throw new Error(`command ${JSON.stringify(config.name)}: alias ${JSON.stringify(alias)} duplicates the command name`) - } - if (seenAliases.has(alias)) { - throw new Error(`command ${JSON.stringify(config.name)}: duplicate alias ${JSON.stringify(alias)}`) - } - seenAliases.add(alias) - } validateOptions(config.options ?? []) validateInput(config.name, config.input) // --input-file is reserved when input is a schema; catch collision at definition time @@ -762,7 +748,6 @@ export function defineCommand (config: CommandConfig): OpaqueCommandHandle { } const cmd = new Command(config.name) - if (aliases.length > 0) cmd.aliases([...aliases]) cmd.description(config.description) configureErrorOutput(cmd) cmd.configureOutput({ diff --git a/src/kb/aliases.ts b/src/kb/aliases.ts deleted file mode 100644 index d510c5ef..00000000 --- a/src/kb/aliases.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and contributors - * SPDX-License-Identifier: Apache-2.0 - */ - -/* - * Canonical CLI names and aliases for Kibana commands. - * - * Kibana command names come from `@elastic/schemas`, which derives them from Kibana's - * OpenAPI `operationId`s (e.g. `find-slos-op`). This table gives selected commands a - * short canonical name (`list*` for paginated results, `get*` for a single element) and - * keeps the upstream name as a Commander alias so existing scripts keep working. - * Commands without an entry keep their upstream name and have no aliases. - * - * Keys are upstream `@elastic/schemas` names (`def.name`), which also drive - * `loadKbApi` and request building. When upstream renames one, re-key the entry and keep - * every name already shipped (canonical and legacy) in `aliases`. - * - * No imports: this module is on the `kb --help` startup path and must not pull in - * schema definitions. - */ - -/** Canonical CLI name and alternate names for one Kibana command. */ -export interface KbCommandNaming { - /** Name shown in help, completion, and the CLI schema. */ - readonly name: string - /** Alternate names that invoke the same command; include every previously shipped name. */ - readonly aliases?: readonly string[] -} - -/** Naming overrides keyed by Kibana namespace, then by upstream `@elastic/schemas` command name. */ -export const KB_COMMAND_NAMING: Readonly>>> = { - slo: { - 'find-slos-op': { name: 'list', aliases: ['find-slos-op'] }, - 'create-slo-op': { name: 'create', aliases: ['create-slo-op'] }, - 'get-slo-op': { name: 'get', aliases: ['get-slo-op'] }, - 'update-slo-op': { name: 'update', aliases: ['update-slo-op'] }, - 'delete-slo-op': { name: 'delete', aliases: ['delete-slo-op'] }, - 'enable-slo-op': { name: 'enable', aliases: ['enable-slo-op'] }, - 'disable-slo-op': { name: 'disable', aliases: ['disable-slo-op'] }, - 'reset-slo-op': { name: 'reset', aliases: ['reset-slo-op'] }, - 'get-definitions-op': { name: 'list-definitions', aliases: ['get-definitions-op'] }, - 'get-snapshot-op': { name: 'get-snapshot', aliases: ['get-snapshot-op'] }, - 'bulk-snapshot-op': { name: 'bulk-snapshot', aliases: ['bulk-snapshot-op'] }, - 'bulk-delete-op': { name: 'bulk-delete', aliases: ['bulk-delete-op'] }, - 'bulk-delete-status-op': { name: 'bulk-delete-status', aliases: ['bulk-delete-status-op'] }, - 'delete-rollup-data-op': { name: 'delete-rollup-data', aliases: ['delete-rollup-data-op'] }, - 'delete-slo-instances-op': { name: 'delete-instances', aliases: ['delete-slo-instances-op'] }, - }, -} - -/** - * Resolves the CLI name and aliases for a Kibana command. - * - * @param namespace - Kibana namespace of the command (e.g. `slo`) - * @param upstreamName - command name from `@elastic/schemas` (e.g. `find-slos-op`) - * @returns the canonical name and aliases; the upstream name with no aliases when unmapped - */ -export function resolveKbCommandNaming (namespace: string, upstreamName: string): { name: string; aliases: readonly string[] } { - const entries = Object.hasOwn(KB_COMMAND_NAMING, namespace) ? KB_COMMAND_NAMING[namespace] : undefined - const naming = entries != null && Object.hasOwn(entries, upstreamName) ? entries[upstreamName] : undefined - if (naming == null) return { name: upstreamName, aliases: [] } - return { name: naming.name, aliases: naming.aliases ?? [] } -} - -/** - * Returns true when `token` invokes the Kibana command, by its CLI name or one of its aliases. - * - * @param namespace - Kibana namespace of the command (e.g. `slo`) - * @param upstreamName - command name from `@elastic/schemas` (e.g. `find-slos-op`) - * @param token - command token typed on the command line - * @returns whether the token names the command - */ -export function matchesKbCommandToken (namespace: string, upstreamName: string, token: string): boolean { - const { name, aliases } = resolveKbCommandNaming(namespace, upstreamName) - return token === name || aliases.includes(token) -} diff --git a/src/kb/command-names.ts b/src/kb/command-names.ts new file mode 100644 index 00000000..9666862d --- /dev/null +++ b/src/kb/command-names.ts @@ -0,0 +1,54 @@ +/* + * Copyright Elasticsearch B.V. and contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +/* + * CLI names for Kibana commands. + * + * Kibana command names come from `@elastic/schemas`, which derives them from Kibana's + * OpenAPI `operationId`s (e.g. `find-slos-op`). This table gives selected commands a + * short CLI name (`list*` for paginated results, `get*` for a single element). + * Commands without an entry keep their upstream name. A renamed command answers to its + * CLI name only: while the CLI is in technical preview, renames are clean breaks. + * + * Keys are upstream `@elastic/schemas` names (`def.name`), which also drive + * `loadKbApi` and request building. When upstream renames one, re-key the entry. + * + * No imports: this module is on the `kb --help` startup path and must not pull in + * schema definitions. + */ + +/** CLI names keyed by Kibana namespace, then by upstream `@elastic/schemas` command name. */ +export const KB_COMMAND_NAMES: Readonly>>> = { + slo: { + 'find-slos-op': 'list', + 'create-slo-op': 'create', + 'get-slo-op': 'get', + 'update-slo-op': 'update', + 'delete-slo-op': 'delete', + 'enable-slo-op': 'enable', + 'disable-slo-op': 'disable', + 'reset-slo-op': 'reset', + 'get-definitions-op': 'list-definitions', + 'get-snapshot-op': 'get-snapshot', + 'bulk-snapshot-op': 'bulk-snapshot', + 'bulk-delete-op': 'bulk-delete', + 'bulk-delete-status-op': 'bulk-delete-status', + 'delete-rollup-data-op': 'delete-rollup-data', + 'delete-slo-instances-op': 'delete-instances', + }, +} + +/** + * Resolves the CLI name of a Kibana command. + * + * @param namespace - Kibana namespace of the command (e.g. `slo`) + * @param upstreamName - command name from `@elastic/schemas` (e.g. `find-slos-op`) + * @returns the CLI name; the upstream name when unmapped + */ +export function resolveKbCommandName (namespace: string, upstreamName: string): string { + const entries = Object.hasOwn(KB_COMMAND_NAMES, namespace) ? KB_COMMAND_NAMES[namespace] : undefined + const name = entries != null && Object.hasOwn(entries, upstreamName) ? entries[upstreamName] : undefined + return name ?? upstreamName +} diff --git a/src/kb/register.ts b/src/kb/register.ts index d8bc39d3..8d7ef1a7 100644 --- a/src/kb/register.ts +++ b/src/kb/register.ts @@ -16,7 +16,7 @@ import type { AvailabilityTarget } from '../lib/availability.ts' import { isAvailable, parseVersionHint } from '../lib/availability.ts' import { getResolvedConfig } from '../config/store.ts' import { buildStubLeaf } from '../lib/lazy-leaf.ts' -import { matchesKbCommandToken, resolveKbCommandNaming } from './aliases.ts' +import { resolveKbCommandName } from './command-names.ts' // Every Kibana definition passes `validateKbApiDefinition` as of @elastic/schemas 0.5.1; // the five upstream path-param defects that used to need an allowlist here are fixed. @@ -28,10 +28,8 @@ import { matchesKbCommandToken, resolveKbCommandNaming } from './aliases.ts' function buildLeafHandle (def: KbApiDefinition, target?: AvailabilityTarget): OpaqueCommandHandle { validateKbApiDefinition(def) const intent = def.intent ?? inferIntentFromHttp(def.method) - const { name, aliases } = resolveKbCommandNaming(def.namespace, def.name) return defineCommand({ - name, - ...(aliases.length > 0 ? { aliases } : {}), + name: resolveKbCommandName(def.namespace, def.name), description: def.description, ...(def.input !== undefined ? { input: def.input } : {}), readOnly: def.method === 'GET' || def.method === 'HEAD', @@ -45,9 +43,8 @@ function buildLeafHandle (def: KbApiDefinition, target?: AvailabilityTarget): Op /** * Sniffs `process.argv` to identify which KB leaf command the user * intends to invoke. Returns `null` on ambiguity or help requests. - * `kb ` matches canonical names and aliases; `kb ` - * matches upstream names only, so short canonical names like `list` cannot - * match across namespaces. + * `kb ` matches CLI names; `kb ` matches upstream + * names only, so short CLI names like `list` cannot match across namespaces. */ function sniffInvokedLeaf (argv: readonly string[], manifest: readonly KbApiMeta[]): KbApiMeta | null { const kbIdx = argv.findIndex((a, i) => i >= 2 && (a === 'kb' || a === 'kibana')) @@ -56,7 +53,7 @@ function sniffInvokedLeaf (argv: readonly string[], manifest: readonly KbApiMeta if (afterKb.length === 0) return null const namespaces = new Set(manifest.map(m => m.namespace)) if (afterKb.length >= 2 && namespaces.has(afterKb[0]!)) { - return manifest.find(m => m.namespace === afterKb[0]! && matchesKbCommandToken(m.namespace, m.name, afterKb[1]!)) ?? null + return manifest.find(m => m.namespace === afterKb[0]! && resolveKbCommandName(m.namespace, m.name) === afterKb[1]!) ?? null } if (afterKb.length >= 1 && !namespaces.has(afterKb[0]!)) { return manifest.find(m => m.name === afterKb[0]!) ?? null @@ -107,9 +104,8 @@ export async function registerKbCommandsLazy ( function leafHandleFor (m: KbApiMeta): OpaqueCommandHandle { if (invoked != null && invokedDef != null && m === invoked) return buildLeafHandle(invokedDef, target) - const { name, aliases } = resolveKbCommandNaming(m.namespace!, m.name) return buildStubLeaf( - { name, description: m.description, ...(aliases.length > 0 ? { aliases } : {}) }, + { name: resolveKbCommandName(m.namespace!, m.name), description: m.description }, async () => buildLeafHandle(await loadKbApi(m), target), ) } diff --git a/src/lib/lazy-leaf.ts b/src/lib/lazy-leaf.ts index c7d09914..515a52e5 100644 --- a/src/lib/lazy-leaf.ts +++ b/src/lib/lazy-leaf.ts @@ -7,28 +7,25 @@ // graph, so loading the real leaf stays with the caller's `loadReal` callback. import { Command } from 'commander' -/** Name, aliases, and description shown for a stub leaf in group-level help. */ +/** Name and description shown for a stub leaf in group-level help. */ export interface StubLeafMeta { name: string - /** Alternate names the stub answers to; should match the real leaf's aliases. */ - aliases?: readonly string[] description: string } /** - * Builds a lightweight stub leaf: name, aliases, and description only, no options. - * Commander lists it in group-level help without resolving its input schema. If the - * stub is invoked (the argv sniff missed it), by name or by alias, it loads the real - * leaf via `loadReal`, swaps itself out of its parent for that leaf, and re-enters - * Commander parsing under the canonical name so the real leaf's options dispatch. + * Builds a lightweight stub leaf: name and description only, no options. Commander + * lists it in group-level help without resolving its input schema. If the stub is + * invoked (the argv sniff missed it), it loads the real leaf via `loadReal`, swaps + * itself out of its parent for that leaf, and re-enters Commander parsing so the real + * leaf's options dispatch. * - * @param meta - name, aliases, and description for the stub + * @param meta - name and description for the stub * @param loadReal - loads and builds the real leaf command on demand * @returns the stub command */ export function buildStubLeaf (meta: StubLeafMeta, loadReal: () => Promise): Command { const cmd = new Command(meta.name) - if (meta.aliases != null && meta.aliases.length > 0) cmd.aliases([...meta.aliases]) cmd.description(meta.description) cmd.allowUnknownOption(true) cmd.allowExcessArguments(true) diff --git a/test/cli-schema.test.ts b/test/cli-schema.test.ts index f5007553..1b76805c 100644 --- a/test/cli-schema.test.ts +++ b/test/cli-schema.test.ts @@ -86,14 +86,15 @@ describe('cli schema', () => { assert.equal(routing?.separator, undefined) }) - it('emits slo commands under their canonical names with the legacy names as aliases', async () => { + it('emits slo commands under their canonical names only', async () => { const { code, stdout, stderr } = await runCliSchema() assert.equal(code, 0, stderr) const schema = JSON.parse(stdout) as { namespaces: CliNamespace[] } const slo = ['stack', 'kb', 'slo'] - assert.deepEqual(findCommand(schema.namespaces, slo, 'list')?.aliases, ['find-slos-op']) - assert.deepEqual(findCommand(schema.namespaces, slo, 'get')?.aliases, ['get-slo-op']) + const list = findCommand(schema.namespaces, slo, 'list') + assert.ok(list != null) + assert.equal(list.aliases, undefined) assert.equal(findCommand(schema.namespaces, slo, 'find-slos-op'), undefined) }) }) diff --git a/test/cli.test.ts b/test/cli.test.ts index 09843d13..233f10df 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -619,6 +619,30 @@ describe('elastic CLI -- command and option error ordering', () => { } }) + it('rejects a renamed kb slo command by its upstream name', async () => { + const dir = await mkdtemp(join(tmpdir(), 'elastic-cli-kb-upstream-name-')) + await writeFile(join(dir, '.elasticrc.yml'), [ + 'current_context: local', + 'contexts:', + ' local:', + ' kibana:', + ' url: http://localhost:5601', + '', + ].join('\n')) + + try { + const { code, stderr } = await runCli( + ['stack', 'kb', 'slo', 'find-slos-op'], + { cwd: dir, env: { HOME: dir, USERPROFILE: dir, XDG_CONFIG_HOME: dir } } + ) + + assert.equal(code, 1) + assert.match(stderr, /unknown command: find-slos-op/) + } finally { + await rm(dir, { recursive: true }) + } + }) + it('suggests the closest sibling for a near misspelling', async () => { const dir = await mkdtemp(join(tmpdir(), 'elastic-cli-suggest-command-')) await writeFile(join(dir, '.elasticrc.yml'), [ diff --git a/test/completion-cli.test.ts b/test/completion-cli.test.ts index 31663765..69da81ed 100644 --- a/test/completion-cli.test.ts +++ b/test/completion-cli.test.ts @@ -81,19 +81,16 @@ describe('elastic CLI -- shell completion end-to-end', () => { assert.ok(out.candidates.includes('search')) }) - it('`__complete -- kb slo ""` lists slo canonical names and legacy aliases', async () => { + it('`__complete -- kb slo ""` lists slo canonical names and no upstream names', async () => { const { code, stdout } = await runCli(['__complete', '--', 'kb', 'slo', '']) assert.equal(code, 0) const out = parseProtocol(stdout) - for (const expected of ['list', 'get', 'find-slos-op', 'get-slo-op']) { + for (const expected of ['list', 'get']) { assert.ok(out.candidates.includes(expected), `missing "${expected}" in ${out.candidates.join(',')}`) } - }) - - it('`__complete -- kb slo get-slo-op --` lists the flags of the leaf reached through its alias', async () => { - const { code, stdout } = await runCli(['__complete', '--', 'kb', 'slo', 'get-slo-op', '--']) - assert.equal(code, 0) - assert.ok(parseProtocol(stdout).candidates.includes('--id')) + for (const unexpected of ['find-slos-op', 'get-slo-op']) { + assert.ok(!out.candidates.includes(unexpected), `unexpected "${unexpected}" in ${out.candidates.join(',')}`) + } }) it('`__complete -- kb slo list --` lists the flags of the leaf reached through its canonical name', async () => { diff --git a/test/factory.test.ts b/test/factory.test.ts index fc416f8e..1d014a46 100644 --- a/test/factory.test.ts +++ b/test/factory.test.ts @@ -724,65 +724,6 @@ describe('defineCommand', () => { }) }) - describe('aliases', () => { - it('registers aliases on the command', () => { - const cmd = defineCommand({ name: 'get', aliases: ['legacy-op'], description: 'Get', handler: () => ({}) }) - assert.deepEqual(cmd.aliases(), ['legacy-op']) - }) - - it('runs the handler when invoked through an alias inside a group', async () => { - const received: ParsedResult[] = [] - const cmd = defineCommand({ - name: 'get', - aliases: ['legacy-op'], - description: 'Get', - handler: (p) => { received.push(p); return {} }, - }) - const group = defineGroup({ name: 'slo', description: 'SLO' }, cmd) - group.exitOverride() - await captureDuring(() => group.parseAsync(['legacy-op'], { from: 'user' })) - assert.equal(received.length, 1) - }) - - it('throws when an alias is not a valid command name', () => { - assert.throws( - () => defineCommand({ name: 'get', aliases: ['Bad'], description: 'Get', handler: () => ({}) }), - /invalid command name/, - ) - }) - - it('throws when an alias is repeated', () => { - assert.throws( - () => defineCommand({ name: 'get', aliases: ['a', 'a'], description: 'Get', handler: () => ({}) }), - /duplicate alias "a"/, - ) - }) - - it('throws when an alias equals the command name', () => { - assert.throws( - () => defineCommand({ name: 'get', aliases: ['get'], description: 'Get', handler: () => ({}) }), - /alias "get" duplicates the command name/, - ) - }) - - it('lists leaf aliases in group --help --json output', async () => { - const cmd = defineCommand({ name: 'get', aliases: ['legacy-op'], description: 'Get', handler: () => ({}) }) - const group = defineGroup({ name: 'slo', description: 'SLO' }, cmd) - const prog = new Command('elastic') - prog.option('--json', 'output as JSON') - prog.addCommand(group) - prog.exitOverride() - group.exitOverride() - let out = '' - group.configureOutput({ writeOut: (s) => { out += s } }) - try { - await prog.parseAsync(['--json', 'slo', '--help'], { from: 'user' }) - } catch { /* exitOverride throws on --help */ } - const parsed = JSON.parse(out) as { commands: Array<{ name: string; aliases?: string[] }> } - assert.deepEqual(parsed.commands.find((c) => c.name === 'get')?.aliases, ['legacy-op']) - }) - }) - describe('option short alias validation', () => { it('throws when short alias is more than one character', () => { assert.throws( @@ -3134,30 +3075,6 @@ describe('isCommandAllowed', () => { // cloud.hosted is already blocked by the serverless profile; the extra blocked entry doesn't matter assert.equal(isCommandAllowed('cloud.hosted.deployments.list', policy), false) }) - - // --- canonical path plus alias paths --- - - const sloDeletePaths = ['stack.kb.slo.delete', 'stack.kb.slo.delete-slo-op'] - - it('path list: blocked entry naming an alias path blocks the command', () => { - assert.equal(isCommandAllowed(sloDeletePaths, { blocked: ['stack.kb.slo.delete-slo-op'] }), false) - }) - - it('path list: allowed entry naming an alias path permits the command', () => { - assert.equal(isCommandAllowed(sloDeletePaths, { allowed: ['stack.kb.slo.delete-slo-op'] }), true) - }) - - it('path list: wildcard still matches', () => { - assert.equal(isCommandAllowed(sloDeletePaths, { allowed: ['stack.kb.slo.*'] }), true) - }) - - it('path list: profile + blocked entry naming an alias path blocks the command', () => { - assert.equal(isCommandAllowed(sloDeletePaths, { profile: 'stack', blocked: ['stack.kb.slo.delete-slo-op'] }), false) - }) - - it('path list: permits the command when no path matches a blocked entry', () => { - assert.equal(isCommandAllowed(sloDeletePaths, { blocked: ['stack.kb.slo.get'] }), true) - }) }) describe('command policy enforcement', () => { @@ -3261,50 +3178,6 @@ describe('command policy enforcement', () => { const err = parsed['error'] as Record assert.equal(err['code'], 'command_blocked') }) - - describe('blocked entry naming a leaf alias', () => { - async function runSloDelete (argv: string[]): Promise<{ handlerCalled: boolean, stderr: string }> { - let handlerCalled = false - const leaf = defineCommand({ - name: 'delete', - aliases: ['delete-slo-op'], - description: 'Delete', - handler: () => { handlerCalled = true; return {} }, - }) - const group = defineGroup({ name: 'slo', description: 'SLO' }, leaf) - const prog = new Command('elastic') - prog.option('--json', 'output as JSON') - prog.addCommand(group) - prog.exitOverride() - group.exitOverride() - leaf.exitOverride() - const { stderr } = await captureStreams(() => prog.parseAsync(argv, { from: 'user' }).then(() => {})) - return { handlerCalled, stderr } - } - - beforeEach(() => { - setResolvedConfig({ context: {}, commands: { blocked: ['slo.delete-slo-op'] } }) - }) - - it('blocks the command invoked by its canonical name', async () => { - const { handlerCalled, stderr } = await runSloDelete(['slo', 'delete']) - assert.equal(handlerCalled, false) - assert.match(stderr, /command "slo\.delete" is not allowed/) - }) - - it('blocks the command invoked by its alias', async () => { - const { handlerCalled, stderr } = await runSloDelete(['slo', 'delete-slo-op']) - assert.equal(handlerCalled, false) - assert.match(stderr, /command "slo\.delete" is not allowed/) - }) - - it('emits command_blocked with --json', async () => { - const { handlerCalled, stderr } = await runSloDelete(['--json', 'slo', 'delete-slo-op']) - assert.equal(handlerCalled, false) - const parsed = JSON.parse(stderr) as { error: { code: string } } - assert.equal(parsed.error.code, 'command_blocked') - }) - }) }) describe('hideBlockedCommands', () => { @@ -3377,20 +3250,6 @@ describe('hideBlockedCommands', () => { assert.equal((leaf as unknown as Record)['_hidden'], true) assert.equal((inner as unknown as Record)['_hidden'], true) }) - - it('hides a leaf when a blocked entry names its alias', () => { - const cmd = defineCommand({ name: 'search', aliases: ['legacy-op'], description: 'Search', handler: () => ({}) }) - const root = makeRoot(defineGroup({ name: 'es', description: 'ES' }, cmd)) - hideBlockedCommands(root, { blocked: ['es.legacy-op'] }) - assert.equal((cmd as unknown as Record)['_hidden'], true) - }) - - it('shows a leaf when an allowed entry names its alias', () => { - const cmd = defineCommand({ name: 'search', aliases: ['legacy-op'], description: 'Search', handler: () => ({}) }) - const root = makeRoot(defineGroup({ name: 'es', description: 'ES' }, cmd)) - hideBlockedCommands(root, { allowed: ['es.legacy-op'] }) - assert.equal((cmd as unknown as Record)['_hidden'], false) - }) }) describe('no Commander API leaks', () => { diff --git a/test/kb/aliases.test.ts b/test/kb/aliases.test.ts deleted file mode 100644 index 95a067d0..00000000 --- a/test/kb/aliases.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and contributors - * SPDX-License-Identifier: Apache-2.0 - */ - -import { describe, it } from 'node:test' -import assert from 'node:assert/strict' -import { KB_COMMAND_NAMING, resolveKbCommandNaming, matchesKbCommandToken } from '../../src/kb/aliases.ts' -import { kbApiManifest } from '../../src/kb/apis.ts' -import { validateName } from '../../src/factory-core.ts' - -describe('KB_COMMAND_NAMING', () => { - it('maps every slo upstream name to its canonical name and legacy alias', () => { - assert.deepEqual(KB_COMMAND_NAMING['slo'], { - 'find-slos-op': { name: 'list', aliases: ['find-slos-op'] }, - 'create-slo-op': { name: 'create', aliases: ['create-slo-op'] }, - 'get-slo-op': { name: 'get', aliases: ['get-slo-op'] }, - 'update-slo-op': { name: 'update', aliases: ['update-slo-op'] }, - 'delete-slo-op': { name: 'delete', aliases: ['delete-slo-op'] }, - 'enable-slo-op': { name: 'enable', aliases: ['enable-slo-op'] }, - 'disable-slo-op': { name: 'disable', aliases: ['disable-slo-op'] }, - 'reset-slo-op': { name: 'reset', aliases: ['reset-slo-op'] }, - 'get-definitions-op': { name: 'list-definitions', aliases: ['get-definitions-op'] }, - 'get-snapshot-op': { name: 'get-snapshot', aliases: ['get-snapshot-op'] }, - 'bulk-snapshot-op': { name: 'bulk-snapshot', aliases: ['bulk-snapshot-op'] }, - 'bulk-delete-op': { name: 'bulk-delete', aliases: ['bulk-delete-op'] }, - 'bulk-delete-status-op': { name: 'bulk-delete-status', aliases: ['bulk-delete-status-op'] }, - 'delete-rollup-data-op': { name: 'delete-rollup-data', aliases: ['delete-rollup-data-op'] }, - 'delete-slo-instances-op': { name: 'delete-instances', aliases: ['delete-slo-instances-op'] }, - }) - }) - - it('has entries for every key in the current Kibana manifest', () => { - const missing: string[] = [] - for (const [namespace, entries] of Object.entries(KB_COMMAND_NAMING)) { - for (const upstreamName of Object.keys(entries)) { - if (!kbApiManifest.some(m => m.namespace === namespace && m.name === upstreamName)) { - missing.push(`${namespace} ${upstreamName}`) - } - } - } - assert.deepEqual(missing, []) - }) - - it('keeps every renamed upstream name as an alias', () => { - const dropped: string[] = [] - for (const [namespace, entries] of Object.entries(KB_COMMAND_NAMING)) { - for (const [upstreamName, naming] of Object.entries(entries)) { - if (naming.name !== upstreamName && !(naming.aliases ?? []).includes(upstreamName)) { - dropped.push(`${namespace} ${upstreamName}`) - } - } - } - assert.deepEqual(dropped, []) - }) - - it('uses valid command names for every resolved name and alias', () => { - for (const m of kbApiManifest) { - const { name, aliases } = resolveKbCommandNaming(m.namespace ?? '', m.name) - for (const n of [name, ...aliases]) assert.doesNotThrow(() => validateName(n, 'command'), `${m.namespace} ${n}`) - } - }) - - it('has no duplicate names or aliases within a namespace', () => { - const seen = new Map>() - const duplicates: string[] = [] - for (const m of kbApiManifest) { - const namespace = m.namespace ?? '' - let names = seen.get(namespace) - if (names == null) { - names = new Set() - seen.set(namespace, names) - } - const { name, aliases } = resolveKbCommandNaming(namespace, m.name) - for (const n of [name, ...aliases]) { - if (names.has(n)) duplicates.push(`${namespace} ${n}`) - names.add(n) - } - } - assert.deepEqual(duplicates, []) - }) -}) - -describe('resolveKbCommandNaming', () => { - it('returns the upstream name with no aliases for an unmapped command', () => { - assert.deepEqual(resolveKbCommandNaming('spaces', 'get-spaces-space'), { name: 'get-spaces-space', aliases: [] }) - }) - - it('returns the canonical name and aliases for a mapped command', () => { - assert.deepEqual(resolveKbCommandNaming('slo', 'find-slos-op'), { name: 'list', aliases: ['find-slos-op'] }) - }) - - it('ignores prototype keys', () => { - for (const key of ['constructor', '__proto__', 'toString']) { - assert.deepEqual(resolveKbCommandNaming(key, 'find-slos-op'), { name: 'find-slos-op', aliases: [] }) - assert.deepEqual(resolveKbCommandNaming('slo', key), { name: key, aliases: [] }) - } - }) -}) - -describe('matchesKbCommandToken', () => { - it('matches the canonical name and the legacy alias', () => { - assert.equal(matchesKbCommandToken('slo', 'find-slos-op', 'list'), true) - assert.equal(matchesKbCommandToken('slo', 'find-slos-op', 'find-slos-op'), true) - }) - - it('does not match an unrelated token', () => { - assert.equal(matchesKbCommandToken('slo', 'find-slos-op', 'find'), false) - }) - - it('matches the upstream name of an unmapped command', () => { - assert.equal(matchesKbCommandToken('spaces', 'get-spaces-space', 'get-spaces-space'), true) - }) - - it('never matches through prototype keys', () => { - for (const key of ['constructor', '__proto__', 'toString']) { - assert.equal(matchesKbCommandToken(key, 'find-slos-op', 'list'), false) - assert.equal(matchesKbCommandToken('slo', key, 'list'), false) - assert.equal(matchesKbCommandToken('slo', 'find-slos-op', key), false) - } - }) -}) diff --git a/test/kb/command-names.test.ts b/test/kb/command-names.test.ts new file mode 100644 index 00000000..eaeced3e --- /dev/null +++ b/test/kb/command-names.test.ts @@ -0,0 +1,85 @@ +/* + * Copyright Elasticsearch B.V. and contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it } from 'node:test' +import assert from 'node:assert/strict' +import { KB_COMMAND_NAMES, resolveKbCommandName } from '../../src/kb/command-names.ts' +import { kbApiManifest } from '../../src/kb/apis.ts' +import { validateName } from '../../src/factory-core.ts' + +describe('KB_COMMAND_NAMES', () => { + it('maps every slo upstream name to its CLI name', () => { + assert.deepEqual(KB_COMMAND_NAMES['slo'], { + 'find-slos-op': 'list', + 'create-slo-op': 'create', + 'get-slo-op': 'get', + 'update-slo-op': 'update', + 'delete-slo-op': 'delete', + 'enable-slo-op': 'enable', + 'disable-slo-op': 'disable', + 'reset-slo-op': 'reset', + 'get-definitions-op': 'list-definitions', + 'get-snapshot-op': 'get-snapshot', + 'bulk-snapshot-op': 'bulk-snapshot', + 'bulk-delete-op': 'bulk-delete', + 'bulk-delete-status-op': 'bulk-delete-status', + 'delete-rollup-data-op': 'delete-rollup-data', + 'delete-slo-instances-op': 'delete-instances', + }) + }) + + it('has entries for every key in the current Kibana manifest', () => { + const missing: string[] = [] + for (const [namespace, entries] of Object.entries(KB_COMMAND_NAMES)) { + for (const upstreamName of Object.keys(entries)) { + if (!kbApiManifest.some(m => m.namespace === namespace && m.name === upstreamName)) { + missing.push(`${namespace} ${upstreamName}`) + } + } + } + assert.deepEqual(missing, []) + }) + + it('uses a valid command name for every resolved name', () => { + for (const m of kbApiManifest) { + const name = resolveKbCommandName(m.namespace ?? '', m.name) + assert.doesNotThrow(() => validateName(name, 'command'), `${m.namespace} ${name}`) + } + }) + + it('has no duplicate CLI names within a namespace', () => { + const seen = new Map>() + const duplicates: string[] = [] + for (const m of kbApiManifest) { + const namespace = m.namespace ?? '' + let names = seen.get(namespace) + if (names == null) { + names = new Set() + seen.set(namespace, names) + } + const name = resolveKbCommandName(namespace, m.name) + if (names.has(name)) duplicates.push(`${namespace} ${name}`) + names.add(name) + } + assert.deepEqual(duplicates, []) + }) +}) + +describe('resolveKbCommandName', () => { + it('returns the upstream name for an unmapped command', () => { + assert.equal(resolveKbCommandName('spaces', 'get-spaces-space'), 'get-spaces-space') + }) + + it('returns the CLI name for a mapped command', () => { + assert.equal(resolveKbCommandName('slo', 'find-slos-op'), 'list') + }) + + it('ignores prototype keys', () => { + for (const key of ['constructor', '__proto__', 'toString']) { + assert.equal(resolveKbCommandName(key, 'find-slos-op'), 'find-slos-op') + assert.equal(resolveKbCommandName('slo', key), key) + } + }) +}) diff --git a/test/kb/register.test.ts b/test/kb/register.test.ts index d59a7442..e965e540 100644 --- a/test/kb/register.test.ts +++ b/test/kb/register.test.ts @@ -203,22 +203,22 @@ describe('registerKbCommandsLazy', () => { }) describe('slo command naming', () => { - const SLO_NAMES: ReadonlyArray = [ - ['list', 'find-slos-op'], - ['create', 'create-slo-op'], - ['get', 'get-slo-op'], - ['update', 'update-slo-op'], - ['delete', 'delete-slo-op'], - ['enable', 'enable-slo-op'], - ['disable', 'disable-slo-op'], - ['reset', 'reset-slo-op'], - ['list-definitions', 'get-definitions-op'], - ['get-snapshot', 'get-snapshot-op'], - ['bulk-snapshot', 'bulk-snapshot-op'], - ['bulk-delete', 'bulk-delete-op'], - ['bulk-delete-status', 'bulk-delete-status-op'], - ['delete-rollup-data', 'delete-rollup-data-op'], - ['delete-instances', 'delete-slo-instances-op'], + const SLO_NAMES: readonly string[] = [ + 'list', + 'create', + 'get', + 'update', + 'delete', + 'enable', + 'disable', + 'reset', + 'list-definitions', + 'get-snapshot', + 'bulk-snapshot', + 'bulk-delete', + 'bulk-delete-status', + 'delete-rollup-data', + 'delete-instances', ] async function sloDefs (): Promise { @@ -229,13 +229,13 @@ describe('slo command naming', () => { return kb.commands.find((c) => c.name() === 'slo')?.commands.find((c) => c.name() === name) } - it('registers slo leaves under canonical names with legacy aliases', async () => { + it('registers slo leaves under canonical names without aliases', async () => { const kb = registerKbCommands(await sloDefs()) const slo = kb.commands.find((c) => c.name() === 'slo') assert.ok(slo != null) assert.deepEqual( new Map(slo.commands.map((c) => [c.name(), c.aliases()])), - new Map(SLO_NAMES.map(([name, alias]) => [name, [alias]])), + new Map(SLO_NAMES.map((name) => [name, []])), ) }) @@ -251,20 +251,25 @@ describe('slo command naming', () => { assert.throws(() => registerKbCommands([...defs, synthetic]), /cannot add command 'list'/) }) - for (const token of ['list', 'find-slos-op']) { - it(`loads the real slo list leaf when argv names it as ${token}`, async () => { - const kb = await registerKbCommandsLazy({ argv: ['node', 'elastic', 'kb', 'slo', token] }) - const leaf = sloLeaf(kb, 'list') - assert.ok(leaf != null) - assert.equal(hasDryRun(leaf), true) - }) - } + it('loads the real slo list leaf when argv names it', async () => { + const kb = await registerKbCommandsLazy({ argv: ['node', 'elastic', 'kb', 'slo', 'list'] }) + const leaf = sloLeaf(kb, 'list') + assert.ok(leaf != null) + assert.equal(hasDryRun(leaf), true) + }) + + it('stays on stubs when argv names a slo command by its upstream name', async () => { + const kb = await registerKbCommandsLazy({ argv: ['node', 'elastic', 'kb', 'slo', 'find-slos-op'] }) + const stub = sloLeaf(kb, 'list') + assert.ok(stub != null) + assert.equal(hasDryRun(stub), false) + }) - it('builds slo stubs with canonical names and legacy aliases when argv names no leaf', async () => { + it('builds slo stubs with canonical names and no aliases when argv names no leaf', async () => { const kb = await registerKbCommandsLazy({ argv: ['node', 'elastic', 'kb', 'slo'] }) const stub = sloLeaf(kb, 'get') assert.ok(stub != null) - assert.deepEqual(stub.aliases(), ['get-slo-op']) + assert.deepEqual(stub.aliases(), []) assert.equal(hasDryRun(stub), false) }) @@ -275,9 +280,9 @@ describe('slo command naming', () => { assert.equal(hasDryRun(leaf), false) }) - it('swaps a stub for the real leaf when invoked through its alias after the sniff misses', async (t) => { + it('swaps a renamed stub for the real leaf after the sniff misses', async (t) => { // the sniffer takes the `--use-context` value as the kb token and misses the leaf - const argv = ['node', 'elastic', '--use-context', 'kb', 'kb', 'slo', 'get-slo-op', '--id', 'my-slo'] + const argv = ['node', 'elastic', '--use-context', 'kb', 'kb', 'slo', 'get', '--id', 'my-slo'] const kb = await registerKbCommandsLazy({ argv }) const stub = sloLeaf(kb, 'get') assert.ok(stub != null) diff --git a/test/lib/lazy-leaf.test.ts b/test/lib/lazy-leaf.test.ts deleted file mode 100644 index c2e11680..00000000 --- a/test/lib/lazy-leaf.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and contributors - * SPDX-License-Identifier: Apache-2.0 - */ - -import { describe, it } from 'node:test' -import assert from 'node:assert/strict' -import { Command } from 'commander' -import { buildStubLeaf } from '../../src/lib/lazy-leaf.ts' -import { defineCommand } from '../../src/factory.ts' -import type { ParsedResult } from '../../src/factory-core.ts' -import { capture } from '../helpers/capture.ts' - -describe('buildStubLeaf', () => { - it('registers aliases on the stub', () => { - const stub = buildStubLeaf( - { name: 'get', description: 'd', aliases: ['get-slo-op'] }, - async () => new Command('get'), - ) - assert.deepEqual(stub.aliases(), ['get-slo-op']) - }) - - it('has no aliases when none are given', () => { - const stub = buildStubLeaf({ name: 'get', description: 'd' }, async () => new Command('get')) - assert.deepEqual(stub.aliases(), []) - }) - - it('swaps itself for the real leaf when invoked through an alias', async (t) => { - const received: ParsedResult[] = [] - const real = defineCommand({ - name: 'get', - aliases: ['get-slo-op'], - description: 'd', - options: [{ long: 'id', type: 'string', description: 'id' }], - handler: (p) => { received.push(p); return {} }, - }) - let loads = 0 - const stub = buildStubLeaf( - { name: 'get', description: 'd', aliases: ['get-slo-op'] }, - async () => { loads++; return real }, - ) - const parent = new Command('slo') - parent.exitOverride() - parent.addCommand(stub) - capture(t) - - await parent.parseAsync(['get-slo-op', '--id', 'x'], { from: 'user' }) - - assert.equal(loads, 1) - assert.deepEqual(parent.commands, [real]) - assert.equal(received.length, 1) - assert.equal(received[0]?.options['id'], 'x') - }) -})