Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion NOTICE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -619,7 +619,7 @@ License: UNLICENSED


------------------------------------------------------------------------
@elastic/schemas@0.12.0
@elastic/schemas@0.13.0
License: Apache-2.0
Repository: https://github.com/elastic/schemas-js
Publisher: Elastic Client Library Maintainers
Expand Down
4 changes: 2 additions & 2 deletions codegen/functional/kb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,8 +426,8 @@ const skippedFilesStack = new Set<string>([
"security_entity_analytics_api_schedule_risk_engine_now.yml",

// 9.5.3 has no GET/POST /api/observability/slos/_snapshot routes (9.6).
"slo_bulk_snapshot_op.yml",
"slo_get_snapshot_op.yml",
"slo_bulk_snapshot.yml",
"slo_get_snapshot.yml",

// Feature or route gated off in this stack config (404 / not available with
// current configuration).
Expand Down
4 changes: 2 additions & 2 deletions codegen/functional/stack-since.json
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,8 @@
"security-osquery-api.osquery_get_scheduled_action_results": "9.4.0",
"security-osquery-api.osquery_get_scheduled_query_results": "9.4.0",
"security-osquery-api.osquery_get_unified_history": "9.4.0",
"slo.bulk_snapshot_op": "9.6.0",
"slo.get_snapshot_op": "9.6.0",
"slo.bulk_snapshot": "9.6.0",
"slo.get_snapshot": "9.6.0",
"streams.delete_streams_name": "9.1.0",
"streams.delete_streams_streamname_attachments_attachmenttype_attachmentid": "9.3.0",
"streams.get_streams": "9.1.0",
Expand Down
20,364 changes: 11,230 additions & 9,134 deletions docs/cli/schema.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
"@cli-schema/spec": "^0.2.0",
"@elastic/agent-env": "0.1.2",
"@elastic/config-resolver": "0.1.3",
"@elastic/schemas": "0.12.0",
"@elastic/schemas": "0.13.0",
"ajv": "^8.0.0",
"cli-table3": "^0.6.5",
"commander": "^15.0.0",
Expand Down
6 changes: 4 additions & 2 deletions src/es/request-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import type { EsRequestParams } from '../lib/es-client.ts'
import type { EsApiDefinition } from './types.ts'
import { selectPathTemplate } from './types.ts'
import type { SchemaArgDefinition } from '../lib/json-schema-args.ts'
import type { RawJsonValue, ParsedResult } from '../factory.ts'
import { encodeMultiTargetPathParam } from '../lib/path-encoding.ts'
Expand All @@ -15,7 +16,7 @@ import { interpolatePath, requirePathParams, routeBody, routeQuery } from '../li
* and the schema arg definitions extracted from `def.input`.
*
* Each `SchemaArgDefinition` carries a `foundIn` field that determines routing:
* - `"path"` → value is interpolated into the URL path template
* - `"path"` → value is interpolated into the path template chosen by `selectPathTemplate`
* - `"query"` → value is added to the querystring (key = `schemaKey`, the snake_case ES name)
* - `"body"` or `undefined` → value is collected into the request body object
*
Expand All @@ -36,7 +37,8 @@ export function buildRequestParams (
const rawBody = parsed.rawBodyValues ?? {}

requirePathParams(schemaArgs, input)
const path = interpolatePath(def.path, input, encodeMultiTargetPathParam)
const supplied = schemaArgs.filter((a) => a.foundIn === 'path' && input[a.schemaKey] !== undefined).map((a) => a.schemaKey)
const path = interpolatePath(selectPathTemplate(def, supplied), input, encodeMultiTargetPathParam)
const querystring = routeQuery(schemaArgs, input)
const body = collectBody(schemaArgs, input, rawBody, def.path, def.bodyFormat)

Expand Down
33 changes: 31 additions & 2 deletions src/es/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,33 @@ function extractPathTokens (path: string): string[] {
return [...path.matchAll(/\{([^}]+)\}/g)].map((m) => m[1] as string)
}

/**
* Returns `def.path` followed by every `x-urls` path that accepts `def.method`.
* Optional path params may appear only in an alternate URL (e.g. `node_id` on `cluster.stats`).
*/
function pathTemplates (def: EsApiDefinition): string[] {
const urls = (def.input?.['x-urls'] ?? []) as Array<{ path: string, methods: string[] }>
return [def.path, ...urls.filter((u) => u.methods.includes(def.method)).map((u) => u.path)]
}

/**
* Picks the first path template whose params are exactly the supplied ones, falling back to `def.path`.
* Throws an `input_error` when the chosen template cannot carry every supplied param, rather than dropping it.
* A superset template would let `interpolatePath` drop a missing segment and shift later values into its slot.
*/
export function selectPathTemplate (def: EsApiDefinition, supplied: string[]): string {
const template = pathTemplates(def).find((t) => {
const tokens = extractPathTokens(t)
return tokens.length === supplied.length && supplied.every((k) => tokens.includes(k))
}) ?? def.path
Comment thread
JoshMock marked this conversation as resolved.
Resolved
const tokens = extractPathTokens(template)
const dropped = supplied.filter((k) => !tokens.includes(k))
if (dropped.length > 0) {
throw Object.assign(new Error(`no URL for "${def.name}" accepts path parameter(s) ${dropped.join(', ')} with the others supplied`), { code: 'input_error' })
}
return template
}

/**
* Validates an `EsApiDefinition` against the data-model rules.
*
Expand All @@ -93,6 +120,7 @@ function extractPathTokens (path: string): string[] {
* - if `input` is provided:
* - every `{param}` token in the path has a corresponding property with `x-found-in: "path"`
* - every property with `x-found-in: "path"` has a matching `{param}` token in the path
* or in an `x-urls` path for the same method
*
* @throws {Error} if any validation rule is violated
*/
Expand Down Expand Up @@ -130,10 +158,11 @@ export function validateApiDefinition (def: EsApiDefinition): SchemaArgDefinitio
}
}

const allTokens = new Set(pathTemplates(def).flatMap(extractPathTokens))
for (const key of pathFields) {
if (!tokens.has(key)) {
if (!allTokens.has(key)) {
throw new Error(
`input field "${key}" has x-found-in: "path" but there is no {${key}} token in the path template for definition "${def.name}"`
`input field "${key}" has x-found-in: "path" but there is no {${key}} token in any path template for definition "${def.name}"`
)
}
}
Expand Down
55 changes: 54 additions & 1 deletion test/es/request-builder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* SPDX-License-Identifier: Apache-2.0
*/

import { describe, it } from 'node:test'
import { before, describe, it } from 'node:test'
import assert from 'node:assert/strict'
import type { EsApiDefinition } from '../../src/es/types.ts'
import { buildRequestParams } from '../../src/es/request-builder.ts'
Expand Down Expand Up @@ -362,6 +362,59 @@ describe('buildRequestParams', () => {
})
})

describe('path params only in an x-urls variant', () => {
const input = {
...schema({ node_id: { type: 'string', 'x-found-in': 'path' } }),
'x-urls': [
{ path: '/_cluster/stats', methods: ['GET'] },
{ path: '/_cluster/stats/nodes/{node_id}', methods: ['GET'] },
],
}
const def = makeDefinition({ path: '/_cluster/stats', input })

it('uses the x-urls path that carries the supplied param', () => {
assert.equal(buildRequestParams(def, parsedResult({ node_id: 'a/b' }), args(input)).path, '/_cluster/stats/nodes/a%2Fb')
})

it('uses def.path when the param is omitted', () => {
assert.equal(buildRequestParams(def, parsedResult(), args(input)).path, '/_cluster/stats')
})

it('ignores x-urls entries for other methods', () => {
const postOnly = { ...input, 'x-urls': [{ path: '/_cluster/stats/nodes/{node_id}', methods: ['POST'] }] }
const build = () => buildRequestParams(makeDefinition({ path: '/_cluster/stats', input: postOnly }), parsedResult({ node_id: 'n1' }), args(postOnly))
assert.throws(build, { code: 'input_error', message: /node_id/ })
})
})

describe('real prometheus.remote_write x-urls routing', () => {
let def: EsApiDefinition
before(async () => {
const { loadEsApisInFile } = await import('../../src/es/apis.ts')
const [loaded] = await loadEsApisInFile('prometheus.remote_write')
assert.ok(loaded?.input != null)
def = loaded
})
const route = (input: Record<string, unknown>) =>
buildRequestParams(def, parsedResult({ write_message: 'x', ...input }), args(def.input ?? {})).path

it('uses the base path with no path params', () => {
assert.equal(route({}), '/_prometheus/api/v1/write')
})

it('uses the dataset path for dataset only', () => {
assert.equal(route({ dataset: 'ds' }), '/_prometheus/metrics/ds/api/v1/write')
})

it('uses the dataset/namespace path for both', () => {
assert.equal(route({ dataset: 'ds', namespace: 'ns' }), '/_prometheus/metrics/ds/ns/api/v1/write')
})

it('rejects namespace without dataset instead of dropping it', () => {
assert.throws(() => route({ namespace: 'ns' }), { code: 'input_error', message: /namespace/ })
})
})

it('NDJSON format applies to msearch searches field', () => {
const input = schema({
searches: { type: 'array', description: 'Searches', 'x-found-in': 'body' },
Expand Down
24 changes: 24 additions & 0 deletions test/es/types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,30 @@ describe('validateApiDefinition', () => {
assert.throws(() => validateApiDefinition(def), /x-found-in.*path|path.*template.*index/i)
})

it('allows an x-found-in: "path" field whose {token} is only in a same-method x-urls entry', () => {
const def: EsApiDefinition = {
...validBase(),
path: '/_cluster/stats',
input: {
...schema({ node_id: { type: 'string', 'x-found-in': 'path' } }),
'x-urls': [{ path: '/_cluster/stats', methods: ['GET'] }, { path: '/_cluster/stats/nodes/{node_id}', methods: ['GET'] }],
},
}
assert.doesNotThrow(() => validateApiDefinition(def))
})

it('rejects an x-found-in: "path" field whose {token} is only in a different-method x-urls entry', () => {
const def: EsApiDefinition = {
...validBase(),
path: '/_cluster/stats',
input: {
...schema({ node_id: { type: 'string', 'x-found-in': 'path' } }),
'x-urls': [{ path: '/_cluster/stats/nodes/{node_id}', methods: ['POST'] }],
},
}
assert.throws(() => validateApiDefinition(def), /no \{node_id\} token/)
})

it('allows an optional x-found-in: "path" field if it has a {token} in path', () => {
const def: EsApiDefinition = {
...validBase(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
# Copyright Elasticsearch B.V. and contributors
# SPDX-License-Identifier: Apache-2.0
# Cloud control plane API: Get stack versions (GET /api/v1/stack/versions)
# Cloud control plane API: Get stack versions (GET /api/v1/regions/{region}/stack/versions)
# Region for {region} is derived from deployments.list-deployments.
---
"stack get-version-stacks":
- do:
stack.get-version-stacks: {}
deployments.list-deployments: {}
- set: {"deployments.0.resources.0.region": region}
- do:
stack.get-version-stacks:
region: $region
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ requires:
---
teardown:
- do:
slo.delete_slo_op:
slo.delete_slo:
space_id: default
id: cli-ft-bulk-delete-slo
ignore: [404]
---
"slo bulk-delete-op":
"slo bulk-delete":
- do:
slo.create_slo_op:
slo.create_slo:
space_id: default
body:
id: cli-ft-bulk-delete-slo
Expand All @@ -41,7 +41,7 @@ teardown:
- match: {id: cli-ft-bulk-delete-slo}

- do:
slo.bulk_delete_op:
slo.bulk_delete:
space_id: default
body:
list:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ requires:
serverless: true
stack: true
---
"slo bulk-delete-status-op":
"slo bulk-delete-status":
- do:
catch: missing
slo.bulk_delete_status_op:
slo.bulk_delete_status:
space_id: default
task_id: "non-existent-task-id"
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ requires:
---
teardown:
- do:
slo.delete_slo_op:
slo.delete_slo:
space_id: default
id: cli-ft-bulk-snapshot-slo
ignore: [404]
---
"slo bulk-snapshot-op":
"slo bulk-snapshot":
- do:
slo.create_slo_op:
slo.create_slo:
space_id: default
body:
id: cli-ft-bulk-snapshot-slo
Expand All @@ -39,7 +39,7 @@ teardown:
- match: {id: cli-ft-bulk-snapshot-slo}

- do:
slo.bulk_snapshot_op:
slo.bulk_snapshot:
space_id: default
body:
at: "2025-01-01T00:00:00.000Z"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ requires:
---
teardown:
- do:
slo.delete_slo_op:
slo.delete_slo:
space_id: default
id: cli-ft-create-slo
ignore: [404]
---
"slo create-slo-op":
"slo create-slo":
- do:
slo.create_slo_op:
slo.create_slo:
space_id: default
body:
id: cli-ft-create-slo
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ requires:
---
setup:
- do:
slo.create_slo_op:
slo.create_slo:
space_id: default
body:
id: cli-ft-delete-rollup-slo
Expand All @@ -34,14 +34,14 @@ setup:
---
teardown:
- do:
slo.delete_slo_op:
slo.delete_slo:
space_id: default
id: cli-ft-delete-rollup-slo
ignore: [404]
---
"slo delete-rollup-data-op":
"slo delete-rollup-data":
- do:
slo.delete_rollup_data_op:
slo.delete_rollup_data:
space_id: default
body:
list:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ requires:
---
setup:
- do:
slo.create_slo_op:
slo.create_slo:
space_id: default
body:
id: cli-ft-delete-slo
Expand All @@ -32,13 +32,13 @@ setup:
---
teardown:
- do:
slo.delete_slo_op:
slo.delete_slo:
space_id: default
id: cli-ft-delete-slo
ignore: [404]
---
"slo delete-slo-op":
"slo delete-slo":
- do:
slo.delete_slo_op:
slo.delete_slo:
space_id: default
id: cli-ft-delete-slo
Loading
Loading