From 4db7cedfd8ddcf5e26c15f6329276bee9f68ac49 Mon Sep 17 00:00:00 2001 From: goldjg Date: Sun, 20 Sep 2026 16:49:01 +0100 Subject: [PATCH 1/2] Add bounded API research metadata Bump grouped and sharded inventory to schema 3.1.0 with optional documented auth, parameter, and schema summaries while preserving flat 2.1.0 compatibility. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/carl/current-pr-contract.md | 91 +++--- .github/carl/memory.md | 8 +- README.md | 2 +- docs/inventory/API_INDEX_SCHEMA.md | 41 ++- docs/inventory/CONSUMER_GUIDE.md | 4 +- docs/inventory/EXPORT_PIPELINE.md | 6 +- scripts/export/export_api_inventory.py | 436 ++++++++++++++++++++++++- tests/test_api_inventory_export.py | 188 ++++++++++- 8 files changed, 701 insertions(+), 75 deletions(-) diff --git a/.github/carl/current-pr-contract.md b/.github/carl/current-pr-contract.md index 670b33d..18bf464 100644 --- a/.github/carl/current-pr-contract.md +++ b/.github/carl/current-pr-contract.md @@ -11,18 +11,16 @@ PR constraints are historical evidence unless they are explicitly promoted to durable invariants. ## Goal -Harden generated artefact boundaries so generated databases, cloned spec corpora, -SARIF/results, exported inventory, and local-only cache/env files cannot be -accidentally committed. +Add bounded, deterministic security-research metadata to grouped and sharded API inventory exports so APISpy can correlate documented authentication, parameters, and schema shapes without receiving raw examples or descriptions. ## Contract status active ## Non-goals -- Do not refactor product code or change query logic. -- Do not regenerate inventory, database, SARIF, or shard outputs. -- Do not modify workflows or CodeQL queries. -- Do not add Python packages to `requirements.txt`. +- Do not change CodeQL queries, analyser behaviour, workflows, dependencies, or source configuration. +- Do not regenerate or commit inventory, database, SARIF, shard, or packaged outputs. +- Do not change flat inventory schema 2.1.0. +- Do not resolve remote references, retain examples/descriptions, infer vulnerabilities, or add model/network functionality. ## Carry-forward rules The following constraints from this PR are promoted to durable invariants and must persist into all future PRs: @@ -32,59 +30,62 @@ The following constraints from this PR are promoted to durable invariants and mu - `carl doctor` must remain healthy after any changes to `.github/carl/` artefacts. ## Approved scope -- Update `.gitignore` to ignore generated/heavy/local artefacts and add ownership comments. -- Remove already tracked generated inventory ZIP exports if needed to make the ignore boundary effective. -- Update `README.md` or `CONTRIBUTING.md` only if artefact ownership needs clarification. -- Update `.github/carl/memory.md` only if generated artefact boundaries or canonical operating assumptions change. -- Update this contract to match the approved scope and validation for this PR. +- Add compact auth, parameter-name, request-schema, and response-schema summaries to grouped/sharded version entries. +- Resolve only bounded local JSON references required to describe schema shape. +- Bump grouped/sharded schema from 3.0.0 to additive 3.1.0 while preserving existing fields and route keys. +- Add focused exporter compatibility and metadata tests. +- Update schema documentation and durable cARL architecture notes. +- Update APISpy separately to consume the new fields optionally while remaining compatible with 3.0.0 shards. ## Intentional amendments -- Supersedes the previous lightweight-test workflow scope in this file. -- Allows tracked generated inventory ZIP removals as part of repository-boundary hardening. +- Supersedes the completed generated-artefact-boundary hardening scope. +- User-approved continuation of the UndREST research-platform implementation permits this bounded exporter change. ## Forbidden scope -- Modifying product behaviour in `SpeQL.py`, `analyze.py`, `refresh_database.py`, `run-queries.sh`, or export logic. -- Modifying CodeQL queries under `queries/`. -- Modifying workflows under `.github/workflows/`. -- Modifying source configs under `config/sources/`. -- Adding/removing/changing Python packages in `requirements.txt`. -- Regenerating or editing generated database, SARIF, JSON inventory, or shard contents. +- Modifying CodeQL queries, analyser/runtime entry points, workflows, source configs, or dependencies. +- Regenerating or editing generated database, SARIF, JSON inventory, shard, or packaged artefacts. +- Breaking flat 2.1.0 or existing grouped/sharded route and version fields. +- Exporting raw examples, descriptions, defaults, credentials, or unrestricted schema content. +- Adding speculative vulnerability labels or API-specific hard-coding. ## Architectural constraints -- SpeQL architecture and product behaviour must remain identical before and after this PR. -- `.gitignore` should document which script or pipeline owns each generated artefact area. -- Generated inventory boundaries must cover flat, grouped, sharded, and packaged export outputs. -- `requirements.txt` remains runtime-focused; pytest is installed separately as a test tool. +- Static API knowledge remains owned by SpecQL; observations and findings remain owned by APISpy. +- Metadata extraction must be deterministic, bounded, provider-neutral, and derived only from OpenAPI/Swagger structure. +- Existing 3.0.0 consumers must continue to function by ignoring additive 3.1.0 fields. +- Local `$ref` cycles and malformed schemas must fail safely without aborting export. +- Export pipeline output remains deterministic for identical input. ## Security constraints -- No secrets, tokens, or credentials may be committed. -- No new external network dependencies or dependencies in-repo may be introduced. -- Ignore rules must not accidentally hide committed source files outside the intended generated/local artefact boundaries. +- No secrets, tokens, credentials, examples, or sensitive default values may be copied into metadata. +- Security metadata describes documented mechanisms only; it must not imply effective authorization or vulnerability status. +- Fingerprints must represent schema structure, not raw payload content. +- No external network or model dependencies may be introduced. ## Files expected to change -- `.github/carl/current-pr-contract.md` — amended scope for this PR -- `.gitignore` — hardened generated/local artefact boundaries -- `inventory/api-index-23389057738.zip` — remove tracked generated export if confirmed in scope -- `inventory/api-index-sharded-23390552485.zip` — remove tracked generated export if confirmed in scope -- `README.md` and/or `CONTRIBUTING.md` — ownership clarification only if needed -- `.github/carl/memory.md` — durable generated-artefact boundary reconciliation (if needed) +- `.github/carl/current-pr-contract.md` +- `.github/carl/memory.md` +- `scripts/export/export_api_inventory.py` +- `tests/test_api_inventory_export.py` +- `docs/inventory/API_INDEX_SCHEMA.md` ## Tests / validation -- Install runtime deps: `pip3 install -r requirements.txt` -- Install test tool explicitly: `pip3 install pytest` -- Run lightweight tests: `python3 -m pytest tests/test_api_inventory_export.py tests/test_api_inventory_normalization.py -v` -- Confirm `git status` contains only intended `.gitignore`, docs, cARL, and generated ZIP removal changes -- Confirm no generated artefacts are newly added +- `python3 -m pytest tests/test_api_inventory_export.py tests/test_api_inventory_normalization.py -v` +- Confirm flat output remains schema 2.1.0 and does not contain new grouped-only metadata. +- Confirm grouped and sharded output use schema 3.1.0 with optional bounded metadata. +- Confirm malformed/cyclic local references do not fail export. +- Confirm no generated artefacts appear in git status. +- Run `git diff --check` and `carl doctor` when available. ## Stop conditions -- Any change that alters product script or CodeQL query behaviour. -- Any generated database, SARIF, JSON inventory, or shard file appearing in git status as a new addition. -- Any secret detected in changed files. +- Metadata requires remote reference fetching or new dependencies. +- Existing route identity, matching keys, or flat output would need a breaking change. +- Generated inventory, database, SARIF, or shard artefacts appear in git status. +- A secret or raw example/default value would be retained. ## Escalation triggers -- If hardening requires modifying workflows, product code, or query logic. -- If additional tracked generated artefacts outside the approved scope need deletion. -- If ignore patterns would overlap committed source files or docs unexpectedly. +- Any need to modify workflows, CodeQL queries, analyser logic, dependencies, or source configs. +- Any proposed metadata whose semantics cannot be derived deterministically from the specification. +- Any need for a breaking grouped/sharded schema version. ## Context reset notes -This contract covers generated-artefact boundary hardening only. Close/reset after merge. +This contract covers the additive SpecQL 3.1.0 research-enrichment phase and optional APISpy consumption. diff --git a/.github/carl/memory.md b/.github/carl/memory.md index fa0a69d..3607656 100644 --- a/.github/carl/memory.md +++ b/.github/carl/memory.md @@ -68,8 +68,9 @@ Adding a new source requires only a source config JSON and optionally a platform `scripts/export/export_api_inventory.py` walks the spec corpus and produces: - `api-index.json` — flat index of every operation -- `api-index-grouped.json` — nested by provider/host/route (with `--grouped`) -- `shards/.json` — per-provider shards (with `--sharded`) +- `api-index-grouped.json` — nested by provider/host/route (with `--grouped`, schema 3.1.0) +- `shards/.json` — per-provider shards (with `--sharded`, schema 3.1.0) +- Grouped/sharded version entries optionally include bounded documented auth, parameter names, and request/response schema summaries for APISpy research correlation. Flat schema 2.1.0 remains unchanged. - Minified variants (`*.min.json`) with `--minified` - Packaged sharded export ZIPs for release publication @@ -139,6 +140,7 @@ requires a package, document it explicitly rather than silently adding. - requirements.txt lists only runtime-required Python packages; test tools (pytest) are documented separately. - Export pipeline output is deterministic given the same spec corpus input. - SpeQL product code changes must not alter the export pipeline's JSON schema without updating APISpy consumers. +- Grouped/sharded research metadata must remain deterministic and bounded; it may resolve local schema references but must not export descriptions, examples, defaults, raw schemas, or remote-reference content. ## Known sharp edges @@ -153,4 +155,4 @@ requires a package, document it explicitly rather than silently adding. ## Last updated -2026-06-30 — cARL installation; initial SpecQL-specific memory populated. \ No newline at end of file +2026-09-20 — grouped/sharded schema 3.1.0 adds bounded research enrichment metadata while flat schema 2.1.0 remains stable. \ No newline at end of file diff --git a/README.md b/README.md index 854a3a4..085f86c 100644 --- a/README.md +++ b/README.md @@ -425,7 +425,7 @@ python3 scripts/export/export_api_inventory.py \ **Output formats:** - `api-index.json` — Flat pretty-printed index -- `api-index-grouped.json` — Grouped/deduplicated (schema 3.0.0) +- `api-index-grouped.json` — Grouped/deduplicated (schema 3.1.0; additive auth/parameter/schema summaries) - `shards/{Provider.Namespace}.min.json` — Per-provider shards for APISpy **Cross-repo pipeline:** The `daily-api-index-export-sharded.yml` workflow runs nightly, publishes the sharded zip to the `shards-latest` GitHub Release, and triggers [UndREST-APISpy](https://github.com/UndREST-Labs/UndREST-APISpy) to update its extension shard data automatically. diff --git a/docs/inventory/API_INDEX_SCHEMA.md b/docs/inventory/API_INDEX_SCHEMA.md index fb56097..c89e868 100644 --- a/docs/inventory/API_INDEX_SCHEMA.md +++ b/docs/inventory/API_INDEX_SCHEMA.md @@ -7,8 +7,8 @@ Two formats are available: | File | Schema version | Flag | Description | |------|---------------|------|-------------| | `api-index.json` / `api-index.min.json` | `2.1.0` | _(default)_ | Flat array — one entry per HTTP operation found | -| `api-index-grouped.json` / `api-index-grouped.min.json` | `3.0.0` | `--grouped` | Grouped/deduplicated — routes nested by provider → host → route → version | -| `shards/{Provider.Namespace}.json` / `shards/{Provider.Namespace}.min.json` | `3.0.0` | `--sharded` | Per-provider shard — same grouped structure scoped to one provider namespace | +| `api-index-grouped.json` / `api-index-grouped.min.json` | `3.1.0` | `--grouped` | Grouped/deduplicated — routes nested by provider → host → route → version | +| `shards/{Provider.Namespace}.json` / `shards/{Provider.Namespace}.min.json` | `3.1.0` | `--sharded` | Per-provider shard — same grouped structure scoped to one provider namespace | > **Why the grouped format?** > The flat format repeats `host`, `provider_namespace`, `method`, `path_template`, @@ -104,7 +104,7 @@ Each element represents one HTTP operation (method + path) found in a spec file. --- -## Grouped Format — `api-index-grouped.json` (schema `3.0.0`) +## Grouped Format — `api-index-grouped.json` (schema `3.1.0`) ### Top-Level Structure @@ -122,7 +122,7 @@ Same fields as the flat metadata, with two additions: ```json { - "schema_version": "3.0.0", + "schema_version": "3.1.0", "export_format": "grouped" } ``` @@ -171,7 +171,25 @@ providers "is_preview": false, "spec_files": ["storage/resource-manager/Microsoft.Storage/stable/2023-01-01/storage.json"], "operation_ids": ["StorageAccounts_GetProperties"], - "source_kinds": ["paths"] + "source_kinds": ["paths"], + "auth": { + "status": "required", + "requirements": [{"azure_auth": ["user_impersonation"]}], + "schemes": [{"name": "azure_auth", "type": "oauth2"}] + }, + "parameters": { + "path": ["accountName", "resourceGroupName", "subscriptionId"], + "query": ["api-version"] + }, + "request_schemas": [], + "response_schemas": [ + { + "fingerprint": "sha256:0123456789abcdef01234567", + "type": "object", + "top_level_fields": [{"name": "id", "type": "string", "required": false}], + "status_codes": ["200"] + } + ] } ``` @@ -181,6 +199,12 @@ providers | `spec_files` | array | Relative paths to all spec files that define this route at this version | | `operation_ids`| array | `operationId` values found at this version (deduplicated) | | `source_kinds` | array | Which paths blocks contributed: `"paths"`, `"x-ms-paths"` (deduplicated) | +| `auth` | object | Documented auth status (`required`, `optional_or_anonymous`, `unspecified`, or `mixed`), requirement alternatives, and referenced scheme descriptors | +| `parameters` | object | Bounded parameter-name arrays grouped by location (`query`, `path`, `header`, `cookie`) | +| `request_schemas` | array | Deduplicated bounded request-body schema summaries with structural fingerprints | +| `response_schemas` | array | Deduplicated bounded response schema summaries with status codes and content types | + +These additive fields are omitted when the specification provides no corresponding metadata. Schema fingerprints are SHA-256 hashes of a canonical, bounded structural shape. The shape includes types, formats, required-property state, property names, arrays, object additional-property structure, and composition keywords. Top-level field summaries union `allOf` fields and conservatively include fields from `oneOf`/`anyOf` alternatives to avoid false undocumented-field signals. Descriptions, examples, defaults, enum values, and raw schema documents are excluded. Only local JSON references are resolved; external or cyclic references are represented by safe marker types. > **Size win:** a route that appears in 10 spec versions goes from 10 flat entries > (each repeating host, method, path_template, spec_file, plane, …) to 1 route @@ -262,10 +286,10 @@ the exact route cannot be matched. --- -## Sharded Format — `shards/{Provider.Namespace}.json` (schema `3.0.0`) +## Sharded Format — `shards/{Provider.Namespace}.json` (schema `3.1.0`) When `--sharded` is used, the exporter writes one JSON file per provider namespace -into a `shards/` subdirectory. Each shard uses the same schema version (`3.0.0`) as +into a `shards/` subdirectory. Each shard uses the same schema version (`3.1.0`) as the grouped format but scopes the content to a single provider. ### File naming @@ -292,7 +316,7 @@ additional `provider_namespace` field: ```json { - "schema_version": "3.0.0", + "schema_version": "3.1.0", "export_format": "sharded", "provider_namespace": "Microsoft.Storage" } @@ -363,6 +387,7 @@ Consumers should check `schema_version` before processing. | Version | Format | Changes | |---------|--------|---------| +| `3.1.0` | grouped / sharded | Added bounded `auth`, parameter-name, request-schema, and response-schema summaries to version entries. Local schema references are resolved for structural fingerprints; descriptions, examples, defaults, and remote references are not exported. Existing 3.0.0 fields are unchanged. | | `3.0.0` | grouped / sharded | **New format.** Providers → hosts → routes → versions hierarchy. Replaces the flat operations array for size-sensitive consumers. `export_format: "grouped"` in metadata. The `--sharded` flag uses the same schema but scopes each file to one provider namespace (`export_format: "sharded"`). | | `2.1.0` | flat | Added `source_kind` field to each operation entry (which paths block the operation came from: `"paths"` or `"x-ms-paths"`). | | `2.0.0` | flat | **Breaking**: removed `provider_namespace`, `resource_provider_family`, `stable_versions`, `preview_versions`, `source_kind`, `tags`, `parameter_names`, `required_query_parameters`, and `has_api_version_parameter`. | diff --git a/docs/inventory/CONSUMER_GUIDE.md b/docs/inventory/CONSUMER_GUIDE.md index 1dec3ae..75d77df 100644 --- a/docs/inventory/CONSUMER_GUIDE.md +++ b/docs/inventory/CONSUMER_GUIDE.md @@ -13,7 +13,7 @@ The export pipeline produces two formats: | File | Schema | Best for | |------|--------|----------| | `api-index.json` | `2.1.0` | Tooling that processes every operation individually (analysis scripts, grep, jq) | -| `api-index-grouped.json` | `3.0.0` | Runtime consumers that need compact, pre-grouped data (browser extensions, proxies) | +| `api-index-grouped.json` | `3.1.0` | Runtime consumers that need compact, pre-grouped data and optional research metadata (browser extensions, proxies) | This guide focuses on the **grouped format** (`api-index-grouped.json`), which is the recommended format for size-sensitive consumers. The flat format is documented @@ -193,7 +193,7 @@ for ns, prov in index["providers"].items(): - `metadata.generated_at` — when the index was produced - `metadata.source_commit` — the exact Azure REST API specs commit used -- `metadata.schema_version` — `"3.0.0"` for the grouped format; check before processing +- `metadata.schema_version` — `"3.1.0"` for current grouped/sharded exports; 3.0.0 consumers can ignore additive research fields - `metadata.export_format` — `"grouped"` (distinguishes from flat format files) The index is regenerated daily by the SpecRecon CI workflow. diff --git a/docs/inventory/EXPORT_PIPELINE.md b/docs/inventory/EXPORT_PIPELINE.md index 6a503c3..4b7a206 100644 --- a/docs/inventory/EXPORT_PIPELINE.md +++ b/docs/inventory/EXPORT_PIPELINE.md @@ -16,7 +16,7 @@ Two complementary formats are produced: - **`api-index.json`** — flat array, one entry per HTTP operation (schema `2.1.0`). Suitable for tooling that iterates over every operation individually. -- **`api-index-grouped.json`** — grouped/deduplicated structure (schema `3.0.0`). +- **`api-index-grouped.json`** — grouped/deduplicated structure (schema `3.1.0`) with optional bounded research metadata. Routes are nested by provider namespace → host → route → version, so shared fields are stored only once. This is the preferred format for size-sensitive consumers such as the future **APISpy** browser extension. @@ -79,7 +79,7 @@ python3 scripts/export/export_api_inventory.py \ | `--source` | `azure-rest-api-specs/specification` | Path to the specifications directory to walk | | `--output-dir` | `inventory/` | Directory where output files are written | | `--minified` | _(off)_ | Also write minified variants (no indentation) | -| `--grouped` | _(off)_ | Also write grouped/deduplicated `api-index-grouped.json` (schema 3.0.0) | +| `--grouped` | _(off)_ | Also write grouped/deduplicated `api-index-grouped.json` (schema 3.1.0) | | `--verbose` | _(off)_ | Print per-file progress messages | --- @@ -90,7 +90,7 @@ python3 scripts/export/export_api_inventory.py \ |-----------------------------------|--------------|-------------| | `inventory/api-index.json` | _(always)_ | Flat pretty-printed index (schema 2.1.0, human-readable) | | `inventory/api-index.min.json` | `--minified` | Flat minified index (same data, no indentation) | -| `inventory/api-index-grouped.json` | `--grouped` | Grouped/deduplicated index (schema 3.0.0, recommended for runtime consumers) | +| `inventory/api-index-grouped.json` | `--grouped` | Grouped/deduplicated index (schema 3.1.0, recommended for runtime consumers) | | `inventory/api-index-grouped.min.json` | `--grouped --minified` | Grouped minified index | All files are listed in `.gitignore` and are not committed to the repository. diff --git a/scripts/export/export_api_inventory.py b/scripts/export/export_api_inventory.py index 3d9950a..93756bb 100644 --- a/scripts/export/export_api_inventory.py +++ b/scripts/export/export_api_inventory.py @@ -19,20 +19,21 @@ --source-repo Upstream repository identifier recorded in metadata (e.g. Azure/azure-rest-api-specs) --source-branch Branch name recorded in metadata (default: main) --minified Also produce a minified api-index.min.json (no indentation) - --grouped Also produce a grouped/deduplicated api-index-grouped.json (schema 3.0.0) - --sharded Also produce per-provider shards under {output-dir}/shards/ (schema 3.0.0) + --grouped Also produce a grouped/deduplicated api-index-grouped.json (schema 3.1.0) + --sharded Also produce per-provider shards under {output-dir}/shards/ (schema 3.1.0) --verbose Print per-file progress messages Output files: api-index.json Flat pretty-printed index (schema 2.1.0) api-index.min.json Flat minified index (with --minified) - api-index-grouped.json Grouped/deduplicated index (with --grouped, schema 3.0.0) + api-index-grouped.json Grouped/deduplicated index (with --grouped, schema 3.1.0) api-index-grouped.min.json Grouped minified index (with --grouped --minified) - shards/{Provider.Namespace}.json Per-provider shard (with --sharded, schema 3.0.0) + shards/{Provider.Namespace}.json Per-provider shard (with --sharded, schema 3.1.0) shards/{Provider.Namespace}.min.json Minified per-provider shard (with --sharded --minified) """ import argparse +import hashlib import json import os import re @@ -65,7 +66,12 @@ TOOL_NAME = "SpecRecon" TOOL_COMPONENT = "SpeQL" SCHEMA_VERSION = "2.1.0" # flat format — minor bump for additive source_kind field -GROUPED_SCHEMA_VERSION = "3.0.0" # grouped/deduplicated format +GROUPED_SCHEMA_VERSION = "3.1.0" # additive research metadata for grouped/sharded format + +_MAX_SCHEMA_DEPTH = 8 +_MAX_SCHEMA_NODES = 1000 +_MAX_TOP_LEVEL_FIELDS = 100 +_MAX_METADATA_ITEMS = 100 # Source metadata defaults — overridden at runtime via CLI args or source config. # These remain as module-level sentinels so that callers that import and use @@ -234,7 +240,327 @@ def _detect_host(spec: dict, file_path: Path) -> str: return "unknown" -def _parse_spec_file(file_path: Path, source_dir: Path, verbose: bool) -> tuple: +def _resolve_local_ref(spec: dict, value, seen: set = None): + """Resolve a local JSON pointer without fetching external content.""" + if not isinstance(value, dict) or not isinstance(value.get("$ref"), str): + return value + ref = value["$ref"] + if not ref.startswith("#/"): + return value + seen = set() if seen is None else set(seen) + if ref in seen or len(seen) >= _MAX_SCHEMA_DEPTH: + return {"type": "cyclic_ref"} + seen.add(ref) + current = spec + try: + for token in ref[2:].split("/"): + token = token.replace("~1", "/").replace("~0", "~") + current = current[token] + except (KeyError, TypeError): + return {"type": "unresolved_ref"} + return _resolve_local_ref(spec, current, seen) + + +def _schema_shape(schema, spec: dict, depth: int = 0, seen_refs: set = None, budget: list = None): + """Return a bounded structural representation suitable for fingerprinting.""" + if budget is None: + budget = [_MAX_SCHEMA_NODES] + if budget[0] <= 0 or depth > _MAX_SCHEMA_DEPTH: + return {"type": "truncated"} + budget[0] -= 1 + + seen_refs = set() if seen_refs is None else set(seen_refs) + if isinstance(schema, dict) and isinstance(schema.get("$ref"), str): + ref = schema["$ref"] + if not ref.startswith("#/"): + return {"type": "external_ref"} + if ref in seen_refs: + return {"type": "cyclic_ref"} + seen_refs.add(ref) + resolved = _resolve_local_ref(spec, schema, seen_refs - {ref}) + if resolved is schema or ( + isinstance(resolved, dict) and resolved.get("type") in {"cyclic_ref", "unresolved_ref"} + ): + return resolved + return _schema_shape(resolved, spec, depth + 1, seen_refs, budget) + + if not isinstance(schema, dict): + return {"type": "unknown"} + + schema_type = schema.get("type") + if not schema_type: + if isinstance(schema.get("properties"), dict): + schema_type = "object" + elif "items" in schema: + schema_type = "array" + else: + schema_type = "unknown" + + shape = {"type": str(schema_type)} + if isinstance(schema.get("format"), str): + shape["format"] = schema["format"][:64] + if schema.get("nullable") is True or schema.get("x-nullable") is True: + shape["nullable"] = True + + required = set(schema.get("required", [])) if isinstance(schema.get("required"), list) else set() + properties = schema.get("properties") + if isinstance(properties, dict): + shape["properties"] = { + str(name)[:200]: { + "required": name in required, + "schema": _schema_shape(properties[name], spec, depth + 1, seen_refs, budget), + } + for name in sorted(properties, key=str)[:_MAX_TOP_LEVEL_FIELDS] + } + if len(properties) > _MAX_TOP_LEVEL_FIELDS: + shape["properties_truncated"] = True + + if "items" in schema: + shape["items"] = _schema_shape(schema.get("items"), spec, depth + 1, seen_refs, budget) + + additional = schema.get("additionalProperties") + if isinstance(additional, bool): + shape["additional_properties"] = additional + elif isinstance(additional, dict): + shape["additional_properties"] = _schema_shape(additional, spec, depth + 1, seen_refs, budget) + + for keyword in ("allOf", "oneOf", "anyOf"): + variants = schema.get(keyword) + if isinstance(variants, list): + shape[keyword] = [ + _schema_shape(item, spec, depth + 1, seen_refs, budget) + for item in variants[:20] + ] + if len(variants) > 20: + shape[f"{keyword}_truncated"] = True + + return shape + + +def _effective_top_level_fields(shape: dict) -> tuple: + fields = {} + truncated = bool(shape.get("properties_truncated")) + + for name, field in shape.get("properties", {}).items(): + fields[name] = { + "name": name, + "type": field.get("schema", {}).get("type", "unknown"), + "required": bool(field.get("required")), + } + + for branch in shape.get("allOf", []): + branch_fields, branch_truncated = _effective_top_level_fields(branch) + truncated = truncated or branch_truncated + for field in branch_fields: + current = fields.get(field["name"]) + if not current: + fields[field["name"]] = dict(field) + else: + if current["type"] != field["type"]: + current["type"] = "mixed" + current["required"] = current["required"] or field["required"] + + for keyword in ("oneOf", "anyOf"): + branches = shape.get(keyword, []) + if not branches: + continue + branch_maps = [] + for branch in branches: + branch_fields, branch_truncated = _effective_top_level_fields(branch) + truncated = truncated or branch_truncated + branch_maps.append({field["name"]: field for field in branch_fields}) + for name in sorted(set().union(*(set(branch) for branch in branch_maps))): + alternatives = [branch[name] for branch in branch_maps if name in branch] + types = {field["type"] for field in alternatives} + alternative = { + "name": name, + "type": next(iter(types)) if len(types) == 1 else "mixed", + "required": len(alternatives) == len(branch_maps) and all(field["required"] for field in alternatives), + } + current = fields.get(name) + if not current: + fields[name] = alternative + elif current["type"] != alternative["type"]: + current["type"] = "mixed" + + ordered = [fields[name] for name in sorted(fields)[:_MAX_TOP_LEVEL_FIELDS]] + return ordered, truncated or len(fields) > _MAX_TOP_LEVEL_FIELDS + + +def _schema_summary(schema, spec: dict): + if not isinstance(schema, dict): + return None + shape = _schema_shape(schema, spec) + encoded = json.dumps(shape, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + top_level_fields, fields_truncated = _effective_top_level_fields(shape) + schema_type = shape.get("type", "unknown") + if schema_type == "unknown" and top_level_fields: + schema_type = "object" + summary = { + "fingerprint": "sha256:" + hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:24], + "type": schema_type, + "top_level_fields": top_level_fields, + } + if fields_truncated: + summary["fields_truncated"] = True + return summary + + +def _parameter_metadata(path_item: dict, operation: dict, spec: dict) -> dict: + combined = [] + for source in (path_item.get("parameters", []), operation.get("parameters", [])): + if isinstance(source, list): + combined.extend(source) + names = {"query": set(), "path": set(), "header": set(), "cookie": set()} + body_schemas = [] + for parameter in combined: + parameter = _resolve_local_ref(spec, parameter) + if not isinstance(parameter, dict): + continue + location = parameter.get("in") + name = parameter.get("name") + if location in names and isinstance(name, str): + names[location].add(name[:200]) + if location == "body": + summary = _schema_summary(parameter.get("schema"), spec) + if summary: + body_schemas.append(summary) + + request_body = _resolve_local_ref(spec, operation.get("requestBody")) + if isinstance(request_body, dict): + content = request_body.get("content", {}) + if isinstance(content, dict): + for content_type in sorted(content)[:20]: + media = content.get(content_type) + summary = _schema_summary(media.get("schema"), spec) if isinstance(media, dict) else None + if summary: + summary = {**summary, "content_types": [str(content_type)[:200]]} + body_schemas.append(summary) + + deduped = {} + for summary in body_schemas: + key = summary["fingerprint"] + if key not in deduped: + deduped[key] = summary + else: + content_types = set(deduped[key].get("content_types", [])) + content_types.update(summary.get("content_types", [])) + if content_types: + deduped[key]["content_types"] = sorted(content_types)[:20] + + return { + "parameters": {key: sorted(values)[:_MAX_METADATA_ITEMS] for key, values in names.items() if values}, + "request_schemas": [deduped[key] for key in sorted(deduped)[:20]], + } + + +def _response_metadata(operation: dict, spec: dict) -> list: + grouped = {} + responses = operation.get("responses", {}) + if not isinstance(responses, dict): + return [] + for status_code in sorted(responses, key=str)[:_MAX_METADATA_ITEMS]: + response = _resolve_local_ref(spec, responses[status_code]) + if not isinstance(response, dict): + continue + candidates = [] + if isinstance(response.get("schema"), dict): + candidates.append((None, response["schema"])) + content = response.get("content", {}) + if isinstance(content, dict): + for content_type in sorted(content)[:20]: + media = content.get(content_type) + if isinstance(media, dict) and isinstance(media.get("schema"), dict): + candidates.append((str(content_type)[:200], media["schema"])) + for content_type, schema in candidates: + summary = _schema_summary(schema, spec) + if not summary: + continue + key = summary["fingerprint"] + item = grouped.setdefault(key, {**summary, "status_codes": [], "content_types": []}) + code = str(status_code)[:32] + if code not in item["status_codes"]: + item["status_codes"].append(code) + if content_type and content_type not in item["content_types"]: + item["content_types"].append(content_type) + result = [] + for key in sorted(grouped)[:50]: + item = grouped[key] + item["status_codes"].sort() + item["content_types"].sort() + if not item["content_types"]: + item.pop("content_types") + result.append(item) + return result + + +def _security_metadata(operation: dict, spec: dict) -> dict: + declared = "security" in operation or "security" in spec + requirements = operation.get("security") if "security" in operation else spec.get("security") + if not isinstance(requirements, list): + requirements = [] + + cleaned_requirements = [] + scheme_names = set() + for requirement in requirements[:20]: + if not isinstance(requirement, dict): + continue + cleaned = {} + for name in sorted(requirement, key=str)[:20]: + scopes = requirement.get(name) + cleaned[str(name)[:200]] = sorted(str(scope)[:200] for scope in scopes[:100]) if isinstance(scopes, list) else [] + scheme_names.add(str(name)) + cleaned_requirements.append(cleaned) + + definitions = spec.get("securityDefinitions", {}) + components = spec.get("components", {}) + if isinstance(components, dict) and isinstance(components.get("securitySchemes"), dict): + definitions = {**(definitions if isinstance(definitions, dict) else {}), **components["securitySchemes"]} + schemes = [] + for name in sorted(scheme_names)[:20]: + definition = _resolve_local_ref(spec, definitions.get(name)) if isinstance(definitions, dict) else None + descriptor = {"name": name[:200], "type": "unknown"} + if isinstance(definition, dict): + descriptor["type"] = str(definition.get("type", "unknown"))[:64] + for source_key, target_key in (("in", "location"), ("scheme", "scheme"), ("name", "parameter_name")): + if isinstance(definition.get(source_key), str): + descriptor[target_key] = definition[source_key][:64] + flows = definition.get("flows") + if isinstance(flows, dict): + descriptor["oauth_flows"] = sorted(str(flow)[:64] for flow in flows)[:20] + elif isinstance(definition.get("flow"), str): + descriptor["oauth_flows"] = [definition["flow"][:64]] + schemes.append(descriptor) + + if not declared: + status = "unspecified" + elif not requirements or any(not requirement for requirement in cleaned_requirements): + status = "optional_or_anonymous" + else: + status = "required" + return { + "status": status, + "requirements": cleaned_requirements, + "schemes": schemes, + } + + +def _operation_research_metadata(path_item: dict, operation: dict, spec: dict) -> dict: + request = _parameter_metadata(path_item, operation, spec) + return { + "auth": _security_metadata(operation, spec), + "parameters": request["parameters"], + "request_schemas": request["request_schemas"], + "response_schemas": _response_metadata(operation, spec), + } + + +def _parse_spec_file( + file_path: Path, + source_dir: Path, + verbose: bool, + include_research_metadata: bool = False, +) -> tuple: """Parse a single spec file and return (list_of_operations, error_or_None). Each operation is a dict matching the api-index.json schema. @@ -313,6 +639,8 @@ def _parse_spec_file(file_path: Path, source_dir: Path, verbose: bool) -> tuple: "is_preview": preview, "lookup_key": lookup_key, } + if include_research_metadata: + entry["_research_metadata"] = _operation_research_metadata(path_item, operation, spec) operations.append(entry) if verbose and operations: @@ -349,6 +677,62 @@ def _build_summary(operations: list, spec_file_count: int, error_count: int) -> # Grouped export helpers # --------------------------------------------------------------------------- +def _merge_unique_objects(existing: list, incoming: list, limit: int) -> list: + keyed = { + json.dumps(item, sort_keys=True, separators=(",", ":"), ensure_ascii=False): item + for item in existing if isinstance(item, dict) + } + for item in incoming: + if isinstance(item, dict): + key = json.dumps(item, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + keyed.setdefault(key, item) + return [keyed[key] for key in sorted(keyed)[:limit]] + + +def _merge_schema_summaries(existing: list, incoming: list, limit: int) -> list: + merged = {item.get("fingerprint"): dict(item) for item in existing if isinstance(item, dict) and item.get("fingerprint")} + for item in incoming: + if not isinstance(item, dict) or not item.get("fingerprint"): + continue + fingerprint = item["fingerprint"] + if fingerprint not in merged: + merged[fingerprint] = dict(item) + continue + for field in ("status_codes", "content_types"): + values = set(merged[fingerprint].get(field, [])) + values.update(item.get(field, [])) + if values: + merged[fingerprint][field] = sorted(values)[:_MAX_METADATA_ITEMS] + return [merged[key] for key in sorted(merged)[:limit]] + + +def _merge_research_metadata(target: dict, metadata: dict) -> None: + auth = metadata.get("auth", {}) if isinstance(metadata, dict) else {} + target_auth = target["auth"] + statuses = {target_auth.get("status", "unspecified"), auth.get("status", "unspecified")} + statuses.discard("unspecified") + target_auth["status"] = statuses.pop() if len(statuses) == 1 else ("mixed" if statuses else "unspecified") + target_auth["requirements"] = _merge_unique_objects( + target_auth.get("requirements", []), auth.get("requirements", []), 50 + ) + target_auth["schemes"] = _merge_unique_objects( + target_auth.get("schemes", []), auth.get("schemes", []), 50 + ) + + for location, names in metadata.get("parameters", {}).items(): + current = set(target["parameters"].get(location, [])) + if isinstance(names, list): + current.update(str(name)[:200] for name in names) + target["parameters"][location] = sorted(current)[:_MAX_METADATA_ITEMS] + + target["request_schemas"] = _merge_schema_summaries( + target.get("request_schemas", []), metadata.get("request_schemas", []), 20 + ) + target["response_schemas"] = _merge_schema_summaries( + target.get("response_schemas", []), metadata.get("response_schemas", []), 50 + ) + + def _build_grouped_index(flat_ops: list) -> dict: """Transform the flat operations list into a grouped providers structure. @@ -405,8 +789,13 @@ def _build_grouped_index(flat_ops: list) -> dict: "spec_files": [], "operation_ids": [], "source_kinds": [], + "auth": {"status": "unspecified", "requirements": [], "schemes": []}, + "parameters": {}, + "request_schemas": [], + "response_schemas": [], } ver = route["versions"][api_version] + _merge_research_metadata(ver, op.get("_research_metadata", {})) # Combine preview classification across all contributing ops for this version. # If any op for (route_key, api_version) is preview, mark the version as preview. ver["is_preview"] = bool(ver.get("is_preview")) or bool(op["is_preview"]) @@ -423,6 +812,24 @@ def _build_grouped_index(flat_ops: list) -> dict: if source_kind and source_kind not in ver["source_kinds"]: ver["source_kinds"].append(source_kind) + for provider in providers.values(): + for host_entry in provider.get("hosts", {}).values(): + for route in host_entry.get("routes", {}).values(): + for version in route.get("versions", {}).values(): + auth = version.get("auth", {}) + if auth.get("status") == "unspecified" and not auth.get("requirements") and not auth.get("schemes"): + version.pop("auth", None) + parameters = version.get("parameters", {}) + for location in list(parameters): + if not parameters[location]: + parameters.pop(location) + if not parameters: + version.pop("parameters", None) + if not version.get("request_schemas"): + version.pop("request_schemas", None) + if not version.get("response_schemas"): + version.pop("response_schemas", None) + return providers @@ -611,7 +1018,12 @@ def run_export( for i, spec_file in enumerate(spec_files, start=1): if verbose: print(f"[{i}/{len(spec_files)}] {spec_file.name}", end=" ") - ops, err = _parse_spec_file(spec_file, source_dir, verbose) + ops, err = _parse_spec_file( + spec_file, + source_dir, + verbose, + include_research_metadata=grouped or sharded, + ) if err: errors.append(err) if verbose: @@ -622,9 +1034,13 @@ def run_export( summary = _build_summary(all_operations, len(spec_files), len(errors)) + flat_operations = [ + {key: value for key, value in operation.items() if not key.startswith("_")} + for operation in all_operations + ] payload = { "metadata": metadata, - "operations": all_operations, + "operations": flat_operations, "summary": summary, } @@ -744,7 +1160,7 @@ def _build_parser() -> argparse.ArgumentParser: action="store_true", help=( "Also produce a grouped/deduplicated api-index-grouped.json " - "(schema 3.0.0). Routes are grouped by provider → host → route, " + "(schema 3.1.0). Routes are grouped by provider → host → route, " "with version-specific info nested underneath." ), ) @@ -754,7 +1170,7 @@ def _build_parser() -> argparse.ArgumentParser: help=( "Also produce per-provider shard files under {output-dir}/shards/. " "Each file is named {Provider.Namespace}.json and contains only that " - "provider's routes in the same grouped (schema 3.0.0) structure." + "provider's routes in the same grouped (schema 3.1.0) structure." ), ) parser.add_argument( diff --git a/tests/test_api_inventory_export.py b/tests/test_api_inventory_export.py index 32dd988..b0e95c9 100644 --- a/tests/test_api_inventory_export.py +++ b/tests/test_api_inventory_export.py @@ -109,6 +109,7 @@ def test_single_get_operation(self, tmp_path): assert op["operation_id"] == "StorageAccounts_Get" assert op["host"] == "management.azure.com" assert "lookup_key" in op + assert "_research_metadata" not in op def test_multiple_methods_on_same_path(self, tmp_path): path = "/providers/Microsoft.Compute/virtualMachines/{vmName}" @@ -297,7 +298,7 @@ def test_operation_fields_present(self, tmp_path): # --------------------------------------------------------------------------- class TestGroupedExport: - """Tests for the --grouped / grouped=True export mode (schema 3.0.0).""" + """Tests for the --grouped / grouped=True export mode (schema 3.1.0).""" def test_grouped_flag_produces_grouped_file(self, tmp_path): source = tmp_path / "spec" @@ -334,7 +335,7 @@ def test_grouped_metadata_schema_version(self, tmp_path): exp.run_export(source, output, minified=False, verbose=False, grouped=True) index = json.loads((output / "api-index-grouped.json").read_text()) - assert index["metadata"]["schema_version"] == "3.0.0" + assert index["metadata"]["schema_version"] == "3.1.0" assert index["metadata"]["export_format"] == "grouped" def test_flat_index_still_produced_with_grouped(self, tmp_path): @@ -420,6 +421,187 @@ def test_version_nesting_structure(self, tmp_path): assert "spec_files" in ver assert "operation_ids" in ver assert "source_kinds" in ver + assert "auth" not in ver + assert "parameters" not in ver + assert "request_schemas" not in ver + assert "response_schemas" not in ver + + def test_grouped_research_metadata_swagger2(self, tmp_path): + source = tmp_path / "spec" + v_dir = source / "Microsoft.Test" / "stable" / "2023-01-01" + v_dir.mkdir(parents=True) + spec = _minimal_swagger(paths={ + "/providers/Microsoft.Test/things/{name}": { + "parameters": [{"name": "name", "in": "path", "required": True, "type": "string"}], + "post": { + "operationId": "Things_Create", + "security": [{"oauth2": ["Things.Write"]}], + "parameters": [ + {"name": "api-version", "in": "query", "required": True, "type": "string"}, + {"name": "body", "in": "body", "schema": {"$ref": "#/definitions/Thing"}}, + ], + "responses": { + "200": {"schema": {"$ref": "#/definitions/Thing"}}, + "201": {"schema": {"$ref": "#/definitions/Thing"}}, + }, + }, + } + }) + spec["securityDefinitions"] = { + "oauth2": {"type": "oauth2", "flow": "implicit", "authorizationUrl": "https://login.example/authorize"} + } + spec["definitions"] = { + "Thing": { + "type": "object", + "required": ["id"], + "properties": { + "id": {"type": "string", "description": "untrusted prose", "example": "secret"}, + "enabled": {"type": "boolean", "default": True}, + }, + } + } + _write_spec(v_dir, "test.json", spec) + output = tmp_path / "out" + + exp.run_export(source, output, minified=False, verbose=False, grouped=True) + index = json.loads((output / "api-index-grouped.json").read_text()) + version = ( + index["providers"]["Microsoft.Test"] + ["hosts"]["management.azure.com"] + ["routes"]["POST /providers/Microsoft.Test/things/{name}"] + ["versions"]["2023-01-01"] + ) + + assert version["auth"]["status"] == "required" + assert version["auth"]["requirements"] == [{"oauth2": ["Things.Write"]}] + assert version["auth"]["schemes"] == [{"name": "oauth2", "type": "oauth2", "oauth_flows": ["implicit"]}] + assert version["parameters"] == {"path": ["name"], "query": ["api-version"]} + assert version["request_schemas"][0]["fingerprint"].startswith("sha256:") + assert version["request_schemas"][0]["top_level_fields"] == [ + {"name": "enabled", "type": "boolean", "required": False}, + {"name": "id", "type": "string", "required": True}, + ] + assert version["response_schemas"][0]["status_codes"] == ["200", "201"] + serialized = json.dumps(version) + assert "untrusted prose" not in serialized + assert "secret" not in serialized + assert "default" not in serialized + + def test_flat_schema_remains_2_1_without_research_metadata(self, tmp_path): + source = tmp_path / "spec" + v_dir = source / "Microsoft.Test" / "stable" / "2023-01-01" + v_dir.mkdir(parents=True) + _write_spec(v_dir, "test.json", _minimal_swagger(paths={ + "/providers/Microsoft.Test/things": { + "get": {"operationId": "Things_List", "security": [], "responses": {}} + } + })) + output = tmp_path / "out" + + exp.run_export(source, output, minified=False, verbose=False, grouped=True) + flat = json.loads((output / "api-index.json").read_text()) + + assert flat["metadata"]["schema_version"] == "2.1.0" + assert "_research_metadata" not in flat["operations"][0] + assert "auth" not in flat["operations"][0] + + def test_openapi3_metadata_and_anonymous_override(self, tmp_path): + source = tmp_path / "spec" + v_dir = source / "Microsoft.Test" / "stable" / "2024-01-01" + v_dir.mkdir(parents=True) + spec = { + "openapi": "3.0.0", + "info": {"title": "Test", "version": "2024-01-01"}, + "servers": [{"url": "https://management.azure.com"}], + "security": [{"bearerAuth": []}], + "components": { + "securitySchemes": {"bearerAuth": {"type": "http", "scheme": "bearer"}}, + "schemas": { + "Node": { + "type": "object", + "properties": {"child": {"$ref": "#/components/schemas/Node"}}, + } + }, + }, + "paths": { + "/providers/Microsoft.Test/nodes": { + "post": { + "operationId": "Nodes_Create", + "security": [], + "requestBody": { + "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Node"}}} + }, + "responses": { + "200": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/Node"}}}} + }, + } + } + }, + } + _write_spec(v_dir, "test.json", spec) + output = tmp_path / "out" + + exp.run_export(source, output, minified=False, verbose=False, grouped=True) + index = json.loads((output / "api-index-grouped.json").read_text()) + version = ( + index["providers"]["Microsoft.Test"] + ["hosts"]["management.azure.com"] + ["routes"]["POST /providers/Microsoft.Test/nodes"] + ["versions"]["2024-01-01"] + ) + + assert version["auth"]["status"] == "optional_or_anonymous" + assert version["auth"]["schemes"] == [] + assert version["request_schemas"][0]["content_types"] == ["application/json"] + assert version["request_schemas"][0]["top_level_fields"][0]["name"] == "child" + assert version["response_schemas"][0]["content_types"] == ["application/json"] + + def test_composed_schema_fields_are_summarized_conservatively(self, tmp_path): + source = tmp_path / "spec" + v_dir = source / "Microsoft.Test" / "stable" / "2024-01-01" + v_dir.mkdir(parents=True) + spec = _minimal_swagger(paths={ + "/providers/Microsoft.Test/things": { + "post": { + "operationId": "Things_Create", + "parameters": [{ + "name": "body", + "in": "body", + "schema": { + "type": "object", + "required": ["name"], + "properties": {"name": {"type": "string"}}, + "allOf": [{"$ref": "#/definitions/Base"}], + }, + }], + "responses": {}, + } + } + }) + spec["definitions"] = { + "Base": { + "type": "object", + "required": ["id"], + "properties": {"id": {"type": "string"}}, + } + } + _write_spec(v_dir, "test.json", spec) + output = tmp_path / "out" + + exp.run_export(source, output, minified=False, verbose=False, grouped=True) + index = json.loads((output / "api-index-grouped.json").read_text()) + fields = ( + index["providers"]["Microsoft.Test"] + ["hosts"]["management.azure.com"] + ["routes"]["POST /providers/Microsoft.Test/things"] + ["versions"]["2024-01-01"] + ["request_schemas"][0]["top_level_fields"] + ) + + assert fields == [ + {"name": "id", "type": "string", "required": True}, + {"name": "name", "type": "string", "required": True}, + ] def test_route_common_fields(self, tmp_path): """Each route entry must have method, path_template, provider_namespace, plane, lookup_key.""" @@ -660,7 +842,7 @@ def test_shard_metadata_export_format(self, tmp_path): exp.run_export(source, output, minified=False, verbose=False, sharded=True) shard = json.loads((output / "shards" / "Microsoft.Storage.json").read_text()) assert shard["metadata"]["export_format"] == "sharded" - assert shard["metadata"]["schema_version"] == "3.0.0" + assert shard["metadata"]["schema_version"] == "3.1.0" assert shard["metadata"]["provider_namespace"] == "Microsoft.Storage" def test_shard_contains_only_its_provider_routes(self, tmp_path): From 9a55dcffd70f0ec692dcc0dbc40937253950dcf7 Mon Sep 17 00:00:00 2001 From: goldjg Date: Sun, 20 Sep 2026 16:59:57 +0100 Subject: [PATCH 2/2] Add bounded API family and version lineage metadata Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/carl/current-pr-contract.md | 27 ++-- .github/carl/memory.md | 10 +- README.md | 2 +- docs/inventory/API_INDEX_SCHEMA.md | 105 +++++++++++++-- docs/inventory/CONSUMER_GUIDE.md | 30 ++++- docs/inventory/EXPORT_PIPELINE.md | 6 +- scripts/export/export_api_inventory.py | 121 ++++++++++++++++- tests/test_api_inventory_export.py | 150 +++++++++++++++++++++- tests/test_api_inventory_normalization.py | 13 ++ 9 files changed, 424 insertions(+), 40 deletions(-) diff --git a/.github/carl/current-pr-contract.md b/.github/carl/current-pr-contract.md index 18bf464..e917dee 100644 --- a/.github/carl/current-pr-contract.md +++ b/.github/carl/current-pr-contract.md @@ -11,7 +11,7 @@ PR constraints are historical evidence unless they are explicitly promoted to durable invariants. ## Goal -Add bounded, deterministic security-research metadata to grouped and sharded API inventory exports so APISpy can correlate documented authentication, parameters, and schema shapes without receiving raw examples or descriptions. +Add bounded, deterministic API-family/resource-hierarchy and version-lineage metadata to grouped and sharded API inventory exports so APISpy can correlate sibling operations and API-version relationships without receiving prose, examples, raw schemas, or live observations. ## Contract status active @@ -30,12 +30,12 @@ The following constraints from this PR are promoted to durable invariants and mu - `carl doctor` must remain healthy after any changes to `.github/carl/` artefacts. ## Approved scope -- Add compact auth, parameter-name, request-schema, and response-schema summaries to grouped/sharded version entries. -- Resolve only bounded local JSON references required to describe schema shape. -- Bump grouped/sharded schema from 3.0.0 to additive 3.1.0 while preserving existing fields and route keys. -- Add focused exporter compatibility and metadata tests. -- Update schema documentation and durable cARL architecture notes. -- Update APISpy separately to consume the new fields optionally while remaining compatible with 3.0.0 shards. +- Add compact API-family/resource-hierarchy metadata to grouped/sharded route entries derived from normalised route template segments, provider namespace, and bounded resource-type paths. +- Add compact version-lineage metadata to grouped/sharded route entries derived from deterministic ordering of version keys and preview/stable classification when derivable from version strings. +- Preserve the existing bounded auth, parameter-name, request-schema, and response-schema summaries on grouped/sharded version entries. +- Bump grouped/sharded schema from additive 3.1.0 to additive 3.2.0 while preserving existing fields and route keys. +- Add focused exporter compatibility, hierarchy, lineage, truncation, omission, and flat-schema tests. +- Update schema documentation, consumer guidance, export guide, README version references if present, and durable cARL architecture notes. ## Intentional amendments - Supersedes the completed generated-artefact-boundary hardening scope. @@ -51,7 +51,7 @@ The following constraints from this PR are promoted to durable invariants and mu ## Architectural constraints - Static API knowledge remains owned by SpecQL; observations and findings remain owned by APISpy. - Metadata extraction must be deterministic, bounded, provider-neutral, and derived only from OpenAPI/Swagger structure. -- Existing 3.0.0 consumers must continue to function by ignoring additive 3.1.0 fields. +- Existing 3.1.0 consumers must continue to function by ignoring additive 3.2.0 fields. - Local `$ref` cycles and malformed schemas must fail safely without aborting export. - Export pipeline output remains deterministic for identical input. @@ -66,15 +66,20 @@ The following constraints from this PR are promoted to durable invariants and mu - `.github/carl/memory.md` - `scripts/export/export_api_inventory.py` - `tests/test_api_inventory_export.py` +- `tests/test_api_inventory_normalization.py` - `docs/inventory/API_INDEX_SCHEMA.md` +- `docs/inventory/CONSUMER_GUIDE.md` +- `docs/inventory/EXPORT_PIPELINE.md` +- `README.md` if it states grouped/sharded schema version ## Tests / validation - `python3 -m pytest tests/test_api_inventory_export.py tests/test_api_inventory_normalization.py -v` - Confirm flat output remains schema 2.1.0 and does not contain new grouped-only metadata. -- Confirm grouped and sharded output use schema 3.1.0 with optional bounded metadata. +- Confirm grouped and sharded output use schema 3.2.0 with optional bounded metadata. - Confirm malformed/cyclic local references do not fail export. +- Confirm API-family/resource-hierarchy metadata, version-lineage ordering, preview/stable classification, truncation markers, omission when empty, and flat-output stability. - Confirm no generated artefacts appear in git status. -- Run `git diff --check` and `carl doctor` when available. +- Run `python3 -m compileall` on changed Python files, `git diff --check`, and `carl doctor` when available. ## Stop conditions - Metadata requires remote reference fetching or new dependencies. @@ -88,4 +93,4 @@ The following constraints from this PR are promoted to durable invariants and mu - Any need for a breaking grouped/sharded schema version. ## Context reset notes -This contract covers the additive SpecQL 3.1.0 research-enrichment phase and optional APISpy consumption. +This contract covers the additive SpecQL 3.2.0 sibling-correlation metadata phase for SpecQL exports only. APISpy consumption is out of scope for this phase. diff --git a/.github/carl/memory.md b/.github/carl/memory.md index 3607656..bf659b0 100644 --- a/.github/carl/memory.md +++ b/.github/carl/memory.md @@ -68,9 +68,9 @@ Adding a new source requires only a source config JSON and optionally a platform `scripts/export/export_api_inventory.py` walks the spec corpus and produces: - `api-index.json` — flat index of every operation -- `api-index-grouped.json` — nested by provider/host/route (with `--grouped`, schema 3.1.0) -- `shards/.json` — per-provider shards (with `--sharded`, schema 3.1.0) -- Grouped/sharded version entries optionally include bounded documented auth, parameter names, and request/response schema summaries for APISpy research correlation. Flat schema 2.1.0 remains unchanged. +- `api-index-grouped.json` — nested by provider/host/route (with `--grouped`, schema 3.2.0) +- `shards/.json` — per-provider shards (with `--sharded`, schema 3.2.0) +- Grouped/sharded route entries optionally include bounded `api_family` and `version_lineage` metadata for sibling-operation correlation, and version entries optionally include bounded documented auth, parameter names, and request/response schema summaries for APISpy research correlation. Flat schema 2.1.0 remains unchanged. - Minified variants (`*.min.json`) with `--minified` - Packaged sharded export ZIPs for release publication @@ -140,7 +140,7 @@ requires a package, document it explicitly rather than silently adding. - requirements.txt lists only runtime-required Python packages; test tools (pytest) are documented separately. - Export pipeline output is deterministic given the same spec corpus input. - SpeQL product code changes must not alter the export pipeline's JSON schema without updating APISpy consumers. -- Grouped/sharded research metadata must remain deterministic and bounded; it may resolve local schema references but must not export descriptions, examples, defaults, raw schemas, or remote-reference content. +- Grouped/sharded research and route-correlation metadata must remain deterministic and bounded; it may resolve local schema references but must not export descriptions, examples, defaults, raw schemas, or remote-reference content. ## Known sharp edges @@ -155,4 +155,4 @@ requires a package, document it explicitly rather than silently adding. ## Last updated -2026-09-20 — grouped/sharded schema 3.1.0 adds bounded research enrichment metadata while flat schema 2.1.0 remains stable. \ No newline at end of file +2026-09-20 — grouped/sharded schema 3.2.0 adds bounded API-family/resource-hierarchy and version-lineage metadata while flat schema 2.1.0 remains stable. \ No newline at end of file diff --git a/README.md b/README.md index 085f86c..475715c 100644 --- a/README.md +++ b/README.md @@ -425,7 +425,7 @@ python3 scripts/export/export_api_inventory.py \ **Output formats:** - `api-index.json` — Flat pretty-printed index -- `api-index-grouped.json` — Grouped/deduplicated (schema 3.1.0; additive auth/parameter/schema summaries) +- `api-index-grouped.json` — Grouped/deduplicated (schema 3.2.0; additive auth/parameter/schema summaries plus API-family and version-lineage metadata) - `shards/{Provider.Namespace}.min.json` — Per-provider shards for APISpy **Cross-repo pipeline:** The `daily-api-index-export-sharded.yml` workflow runs nightly, publishes the sharded zip to the `shards-latest` GitHub Release, and triggers [UndREST-APISpy](https://github.com/UndREST-Labs/UndREST-APISpy) to update its extension shard data automatically. diff --git a/docs/inventory/API_INDEX_SCHEMA.md b/docs/inventory/API_INDEX_SCHEMA.md index c89e868..7330c35 100644 --- a/docs/inventory/API_INDEX_SCHEMA.md +++ b/docs/inventory/API_INDEX_SCHEMA.md @@ -7,8 +7,8 @@ Two formats are available: | File | Schema version | Flag | Description | |------|---------------|------|-------------| | `api-index.json` / `api-index.min.json` | `2.1.0` | _(default)_ | Flat array — one entry per HTTP operation found | -| `api-index-grouped.json` / `api-index-grouped.min.json` | `3.1.0` | `--grouped` | Grouped/deduplicated — routes nested by provider → host → route → version | -| `shards/{Provider.Namespace}.json` / `shards/{Provider.Namespace}.min.json` | `3.1.0` | `--sharded` | Per-provider shard — same grouped structure scoped to one provider namespace | +| `api-index-grouped.json` / `api-index-grouped.min.json` | `3.2.0` | `--grouped` | Grouped/deduplicated — routes nested by provider → host → route → version | +| `shards/{Provider.Namespace}.json` / `shards/{Provider.Namespace}.min.json` | `3.2.0` | `--sharded` | Per-provider shard — same grouped structure scoped to one provider namespace | > **Why the grouped format?** > The flat format repeats `host`, `provider_namespace`, `method`, `path_template`, @@ -104,7 +104,7 @@ Each element represents one HTTP operation (method + path) found in a spec file. --- -## Grouped Format — `api-index-grouped.json` (schema `3.1.0`) +## Grouped Format — `api-index-grouped.json` (schema `3.2.0`) ### Top-Level Structure @@ -122,7 +122,7 @@ Same fields as the flat metadata, with two additions: ```json { - "schema_version": "3.1.0", + "schema_version": "3.2.0", "export_format": "grouped" } ``` @@ -151,7 +151,28 @@ providers "provider_namespace": "Microsoft.Storage", "plane": "management", "lookup_key": "management.azure.com|GET|/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}", - "versions": { ... } + "api_family": { + "family_key": "Microsoft.Storage/storageAccounts", + "provider_namespace": "Microsoft.Storage", + "resource_type_path": ["storageAccounts"], + "resource_key": "Microsoft.Storage/storageAccounts", + "resource_depth": 1 + }, + "versions": { ... }, + "version_lineage": { + "ordered_versions": [ + { + "api_version": "2022-01-01", + "stability": "stable", + "next_version": "2023-01-01" + }, + { + "api_version": "2023-01-01", + "stability": "stable", + "previous_version": "2022-01-01" + } + ] + } } ``` @@ -162,7 +183,74 @@ providers | `provider_namespace` | string | E.g. `"Microsoft.Storage"`, or `"unknown"` | | `plane` | string | `"management"`, `"data"`, or `"unknown"` | | `lookup_key` | string | `"||"` for fast exact matching | +| `api_family` | object | Optional bounded structural family/hierarchy metadata derived from the normalized route template and provider namespace | | `versions` | object | Map of `api_version → version entry` (see below) | +| `version_lineage` | object | Optional bounded ordered version list and previous/next links derived from this route's version keys | + +#### Route `api_family` object + +```json +{ + "family_key": "Microsoft.Storage/storageAccounts", + "provider_namespace": "Microsoft.Storage", + "resource_type_path": ["storageAccounts", "blobServices", "containers"], + "resource_key": "Microsoft.Storage/storageAccounts/blobServices/containers", + "resource_depth": 3, + "parent_resource_type_path": ["storageAccounts", "blobServices"], + "parent_resource_key": "Microsoft.Storage/storageAccounts/blobServices" +} +``` + +| Field | Type | Description | +|-------|------|-------------| +| `family_key` | string | Provider namespace plus top-level resource type. Sibling operations on the same top-level resource family share this key. | +| `provider_namespace` | string | Provider namespace used to derive the family. | +| `resource_type_path` | array | Bounded ordered resource-type segments after `/providers/{namespace}`. Template parameters and Azure singleton `default` name segments are excluded. | +| `resource_key` | string | Provider namespace plus the full bounded `resource_type_path`. | +| `resource_depth` | integer | Number of derived resource-type segments before bounding. | +| `parent_resource_type_path` | array | Optional bounded parent resource-type path, present only for nested resources. | +| `parent_resource_key` | string | Optional provider namespace plus `parent_resource_type_path`. | +| `resource_type_path_truncated` | boolean | Present and `true` when the route contains more resource-type segments than the exporter cap. | + +`api_family` is omitted when a route has no provider namespace or no structural +resource-type path. It is structural only: descriptions, tags, operation names, +examples, and inferred product semantics are not used. + +#### Route `version_lineage` object + +```json +{ + "ordered_versions": [ + { + "api_version": "2022-01-01", + "stability": "stable", + "next_version": "2023-01-01-preview" + }, + { + "api_version": "2023-01-01-preview", + "stability": "preview", + "previous_version": "2022-01-01" + } + ] +} +``` + +| Field | Type | Description | +|-------|------|-------------| +| `ordered_versions` | array | Bounded list of version entries sorted deterministically by date-like prefix and then lexically. | +| `versions_truncated` | boolean | Present and `true` when more version keys exist than the exporter cap. | + +Each `ordered_versions` item contains: + +| Field | Type | Description | +|-------|------|-------------| +| `api_version` | string | Version key from the route's `versions` object. | +| `stability` | string | `"preview"` when the version string contains `preview`, `"stable"` for bare `YYYY-MM-DD`, otherwise `"unknown"`. | +| `previous_version` | string | Previous version in the bounded ordered list; omitted for the first item. | +| `next_version` | string | Next version in the bounded ordered list; omitted for the last item. | + +`version_lineage` is omitted when a route has no known version keys other than +`"unknown"`. #### Version Entry (version-specific fields) @@ -286,10 +374,10 @@ the exact route cannot be matched. --- -## Sharded Format — `shards/{Provider.Namespace}.json` (schema `3.1.0`) +## Sharded Format — `shards/{Provider.Namespace}.json` (schema `3.2.0`) When `--sharded` is used, the exporter writes one JSON file per provider namespace -into a `shards/` subdirectory. Each shard uses the same schema version (`3.1.0`) as +into a `shards/` subdirectory. Each shard uses the same schema version (`3.2.0`) as the grouped format but scopes the content to a single provider. ### File naming @@ -316,7 +404,7 @@ additional `provider_namespace` field: ```json { - "schema_version": "3.1.0", + "schema_version": "3.2.0", "export_format": "sharded", "provider_namespace": "Microsoft.Storage" } @@ -387,6 +475,7 @@ Consumers should check `schema_version` before processing. | Version | Format | Changes | |---------|--------|---------| +| `3.2.0` | grouped / sharded | Added bounded route-level `api_family` and `version_lineage` metadata so consumers can correlate sibling operations, parent/child resource hierarchy, ordered API versions, and deterministically derived preview/stable version classes. Existing 3.1.0 fields are unchanged. | | `3.1.0` | grouped / sharded | Added bounded `auth`, parameter-name, request-schema, and response-schema summaries to version entries. Local schema references are resolved for structural fingerprints; descriptions, examples, defaults, and remote references are not exported. Existing 3.0.0 fields are unchanged. | | `3.0.0` | grouped / sharded | **New format.** Providers → hosts → routes → versions hierarchy. Replaces the flat operations array for size-sensitive consumers. `export_format: "grouped"` in metadata. The `--sharded` flag uses the same schema but scopes each file to one provider namespace (`export_format: "sharded"`). | | `2.1.0` | flat | Added `source_kind` field to each operation entry (which paths block the operation came from: `"paths"` or `"x-ms-paths"`). | diff --git a/docs/inventory/CONSUMER_GUIDE.md b/docs/inventory/CONSUMER_GUIDE.md index 75d77df..4eca96e 100644 --- a/docs/inventory/CONSUMER_GUIDE.md +++ b/docs/inventory/CONSUMER_GUIDE.md @@ -13,7 +13,7 @@ The export pipeline produces two formats: | File | Schema | Best for | |------|--------|----------| | `api-index.json` | `2.1.0` | Tooling that processes every operation individually (analysis scripts, grep, jq) | -| `api-index-grouped.json` | `3.1.0` | Runtime consumers that need compact, pre-grouped data and optional research metadata (browser extensions, proxies) | +| `api-index-grouped.json` | `3.2.0` | Runtime consumers that need compact, pre-grouped data and optional research metadata (browser extensions, proxies) | This guide focuses on the **grouped format** (`api-index-grouped.json`), which is the recommended format for size-sensitive consumers. The flat format is documented @@ -35,6 +35,8 @@ providers ├─ provider_namespace ├─ plane ├─ lookup_key ← "host|METHOD|path_template" + ├─ api_family ← structural sibling/resource hierarchy metadata + ├─ version_lineage ← ordered versions with previous/next links └─ versions └─ api_version ├─ is_preview @@ -61,6 +63,9 @@ index can answer: | Is this operation preview-only? | If all version entries have `is_preview: true` | | Which Azure service owns this path? | Read `provider_namespace` from the route | | Is this a management-plane or data-plane call? | Read `plane` from the route | +| Which sibling operations belong to the same resource family? | Group routes by `api_family.family_key` | +| What is the parent/child resource relationship? | Read `api_family.resource_type_path` and `api_family.parent_resource_key` | +| Which versions exist and what is their relative order? | Read `version_lineage.ordered_versions` | --- @@ -137,6 +142,27 @@ def check_version(route, observed_api_version): return "route_match_no_versions", None ``` +### Step 6 — Correlate sibling operations and versions + +The grouped `3.2.0` route entry includes optional structural metadata for +correlation. It is additive; consumers that only understand `3.1.0` can ignore it. + +```python +family = route.get("api_family", {}) +family_key = family.get("family_key") # e.g. Microsoft.Storage/storageAccounts +resource_path = family.get("resource_type_path", []) # e.g. ["storageAccounts", "blobServices"] +parent_key = family.get("parent_resource_key") + +lineage = route.get("version_lineage", {}).get("ordered_versions", []) +for item in lineage: + print(item["api_version"], item["stability"], item.get("previous_version"), item.get("next_version")) +``` + +`api_family` is derived from normalized route-template segments and provider +namespace only. `version_lineage` is derived from route version keys only; the +`stability` value is `"preview"` for version strings containing `preview`, +`"stable"` for bare `YYYY-MM-DD`, and `"unknown"` otherwise. + --- ## "Spec vs Reality" Matching Outcomes @@ -193,7 +219,7 @@ for ns, prov in index["providers"].items(): - `metadata.generated_at` — when the index was produced - `metadata.source_commit` — the exact Azure REST API specs commit used -- `metadata.schema_version` — `"3.1.0"` for current grouped/sharded exports; 3.0.0 consumers can ignore additive research fields +- `metadata.schema_version` — `"3.2.0"` for current grouped/sharded exports; 3.1.0 consumers can ignore additive route-correlation fields - `metadata.export_format` — `"grouped"` (distinguishes from flat format files) The index is regenerated daily by the SpecRecon CI workflow. diff --git a/docs/inventory/EXPORT_PIPELINE.md b/docs/inventory/EXPORT_PIPELINE.md index 4b7a206..3cd74b5 100644 --- a/docs/inventory/EXPORT_PIPELINE.md +++ b/docs/inventory/EXPORT_PIPELINE.md @@ -16,7 +16,7 @@ Two complementary formats are produced: - **`api-index.json`** — flat array, one entry per HTTP operation (schema `2.1.0`). Suitable for tooling that iterates over every operation individually. -- **`api-index-grouped.json`** — grouped/deduplicated structure (schema `3.1.0`) with optional bounded research metadata. +- **`api-index-grouped.json`** — grouped/deduplicated structure (schema `3.2.0`) with optional bounded research and route-correlation metadata. Routes are nested by provider namespace → host → route → version, so shared fields are stored only once. This is the preferred format for size-sensitive consumers such as the future **APISpy** browser extension. @@ -79,7 +79,7 @@ python3 scripts/export/export_api_inventory.py \ | `--source` | `azure-rest-api-specs/specification` | Path to the specifications directory to walk | | `--output-dir` | `inventory/` | Directory where output files are written | | `--minified` | _(off)_ | Also write minified variants (no indentation) | -| `--grouped` | _(off)_ | Also write grouped/deduplicated `api-index-grouped.json` (schema 3.1.0) | +| `--grouped` | _(off)_ | Also write grouped/deduplicated `api-index-grouped.json` (schema 3.2.0) | | `--verbose` | _(off)_ | Print per-file progress messages | --- @@ -90,7 +90,7 @@ python3 scripts/export/export_api_inventory.py \ |-----------------------------------|--------------|-------------| | `inventory/api-index.json` | _(always)_ | Flat pretty-printed index (schema 2.1.0, human-readable) | | `inventory/api-index.min.json` | `--minified` | Flat minified index (same data, no indentation) | -| `inventory/api-index-grouped.json` | `--grouped` | Grouped/deduplicated index (schema 3.1.0, recommended for runtime consumers) | +| `inventory/api-index-grouped.json` | `--grouped` | Grouped/deduplicated index (schema 3.2.0, recommended for runtime consumers) | | `inventory/api-index-grouped.min.json` | `--grouped --minified` | Grouped minified index | All files are listed in `.gitignore` and are not committed to the repository. diff --git a/scripts/export/export_api_inventory.py b/scripts/export/export_api_inventory.py index 93756bb..7c2b905 100644 --- a/scripts/export/export_api_inventory.py +++ b/scripts/export/export_api_inventory.py @@ -19,16 +19,16 @@ --source-repo Upstream repository identifier recorded in metadata (e.g. Azure/azure-rest-api-specs) --source-branch Branch name recorded in metadata (default: main) --minified Also produce a minified api-index.min.json (no indentation) - --grouped Also produce a grouped/deduplicated api-index-grouped.json (schema 3.1.0) - --sharded Also produce per-provider shards under {output-dir}/shards/ (schema 3.1.0) + --grouped Also produce a grouped/deduplicated api-index-grouped.json (schema 3.2.0) + --sharded Also produce per-provider shards under {output-dir}/shards/ (schema 3.2.0) --verbose Print per-file progress messages Output files: api-index.json Flat pretty-printed index (schema 2.1.0) api-index.min.json Flat minified index (with --minified) - api-index-grouped.json Grouped/deduplicated index (with --grouped, schema 3.1.0) + api-index-grouped.json Grouped/deduplicated index (with --grouped, schema 3.2.0) api-index-grouped.min.json Grouped minified index (with --grouped --minified) - shards/{Provider.Namespace}.json Per-provider shard (with --sharded, schema 3.1.0) + shards/{Provider.Namespace}.json Per-provider shard (with --sharded, schema 3.2.0) shards/{Provider.Namespace}.min.json Minified per-provider shard (with --sharded --minified) """ @@ -66,12 +66,13 @@ TOOL_NAME = "SpecRecon" TOOL_COMPONENT = "SpeQL" SCHEMA_VERSION = "2.1.0" # flat format — minor bump for additive source_kind field -GROUPED_SCHEMA_VERSION = "3.1.0" # additive research metadata for grouped/sharded format +GROUPED_SCHEMA_VERSION = "3.2.0" # additive sibling-correlation metadata for grouped/sharded format _MAX_SCHEMA_DEPTH = 8 _MAX_SCHEMA_NODES = 1000 _MAX_TOP_LEVEL_FIELDS = 100 _MAX_METADATA_ITEMS = 100 +_MAX_RESOURCE_TYPE_SEGMENTS = 20 # Source metadata defaults — overridden at runtime via CLI args or source config. # These remain as module-level sentinels so that callers that import and use @@ -733,6 +734,106 @@ def _merge_research_metadata(target: dict, metadata: dict) -> None: ) +def _path_segments(path_template: str) -> list: + normalized = normalize_path_template_for_key(path_template) + if not isinstance(normalized, str): + return [] + path_only = normalized.split("?", 1)[0] + return [segment for segment in path_only.strip("/").split("/") if segment] + + +def _is_template_parameter(segment: str) -> bool: + return segment.startswith("{") and segment.endswith("}") + + +def _api_family_metadata(provider_ns: str, path_template: str) -> dict: + """Derive bounded route-family metadata from structural route segments.""" + if not provider_ns or provider_ns == "unknown": + return {} + + segments = _path_segments(path_template) + provider_index = None + for index, segment in enumerate(segments[:-1]): + if segment.lower() == "providers" and segments[index + 1].lower() == provider_ns.lower(): + provider_index = index + 1 + break + if provider_index is None: + return {} + + all_resource_types = [ + segment[:200] + for segment in segments[provider_index + 1:] + if not _is_template_parameter(segment) and segment.lower() != "default" + ] + if not all_resource_types: + return {} + + resource_type_path = all_resource_types[:_MAX_RESOURCE_TYPE_SEGMENTS] + family_key = f"{provider_ns}/{resource_type_path[0]}" + resource_key = f"{provider_ns}/{'/'.join(resource_type_path)}" + + metadata = { + "family_key": family_key, + "provider_namespace": provider_ns, + "resource_type_path": resource_type_path, + "resource_key": resource_key, + "resource_depth": len(all_resource_types), + } + if len(resource_type_path) > 1: + parent_path = resource_type_path[:-1] + metadata["parent_resource_type_path"] = parent_path + metadata["parent_resource_key"] = f"{provider_ns}/{'/'.join(parent_path)}" + if len(all_resource_types) > _MAX_RESOURCE_TYPE_SEGMENTS: + metadata["resource_type_path_truncated"] = True + return metadata + + +def _version_stability_from_string(api_version: str) -> str: + version = str(api_version or "") + if is_preview_version(version): + return "preview" + if re.fullmatch(r"\d{4}-\d{2}-\d{2}", version): + return "stable" + return "unknown" + + +def _version_sort_key(api_version: str) -> tuple: + version = str(api_version or "") + match = re.match(r"^(\d{4})-(\d{2})-(\d{2})(.*)$", version) + if match: + suffix = match.group(4).lower() + return (0, int(match.group(1)), int(match.group(2)), int(match.group(3)), suffix, version.lower()) + return (1, version.lower()) + + +def _version_lineage_metadata(versions: dict) -> dict: + """Return bounded ordered version lineage for a route.""" + ordered_versions = sorted( + (str(version) for version in versions if version and version != "unknown"), + key=_version_sort_key, + ) + if not ordered_versions: + return {} + + bounded_versions = ordered_versions[:_MAX_METADATA_ITEMS] + entries = [] + for index, api_version in enumerate(bounded_versions): + entry = { + "api_version": api_version, + "stability": _version_stability_from_string(api_version), + } + if index > 0: + entry["previous_version"] = bounded_versions[index - 1] + if index + 1 < len(bounded_versions): + entry["next_version"] = bounded_versions[index + 1] + entries.append(entry) + + metadata = {"ordered_versions": entries} + if len(ordered_versions) > _MAX_METADATA_ITEMS: + metadata["versions_truncated"] = True + return metadata + + def _build_grouped_index(flat_ops: list) -> dict: """Transform the flat operations list into a grouped providers structure. @@ -815,6 +916,12 @@ def _build_grouped_index(flat_ops: list) -> dict: for provider in providers.values(): for host_entry in provider.get("hosts", {}).values(): for route in host_entry.get("routes", {}).values(): + api_family = _api_family_metadata(route.get("provider_namespace", ""), route.get("path_template", "")) + if api_family: + route["api_family"] = api_family + version_lineage = _version_lineage_metadata(route.get("versions", {})) + if version_lineage: + route["version_lineage"] = version_lineage for version in route.get("versions", {}).values(): auth = version.get("auth", {}) if auth.get("status") == "unspecified" and not auth.get("requirements") and not auth.get("schemes"): @@ -1160,7 +1267,7 @@ def _build_parser() -> argparse.ArgumentParser: action="store_true", help=( "Also produce a grouped/deduplicated api-index-grouped.json " - "(schema 3.1.0). Routes are grouped by provider → host → route, " + "(schema 3.2.0). Routes are grouped by provider → host → route, " "with version-specific info nested underneath." ), ) @@ -1170,7 +1277,7 @@ def _build_parser() -> argparse.ArgumentParser: help=( "Also produce per-provider shard files under {output-dir}/shards/. " "Each file is named {Provider.Namespace}.json and contains only that " - "provider's routes in the same grouped (schema 3.1.0) structure." + "provider's routes in the same grouped (schema 3.2.0) structure." ), ) parser.add_argument( diff --git a/tests/test_api_inventory_export.py b/tests/test_api_inventory_export.py index b0e95c9..10609f6 100644 --- a/tests/test_api_inventory_export.py +++ b/tests/test_api_inventory_export.py @@ -298,7 +298,7 @@ def test_operation_fields_present(self, tmp_path): # --------------------------------------------------------------------------- class TestGroupedExport: - """Tests for the --grouped / grouped=True export mode (schema 3.1.0).""" + """Tests for the --grouped / grouped=True export mode (schema 3.2.0).""" def test_grouped_flag_produces_grouped_file(self, tmp_path): source = tmp_path / "spec" @@ -335,7 +335,7 @@ def test_grouped_metadata_schema_version(self, tmp_path): exp.run_export(source, output, minified=False, verbose=False, grouped=True) index = json.loads((output / "api-index-grouped.json").read_text()) - assert index["metadata"]["schema_version"] == "3.1.0" + assert index["metadata"]["schema_version"] == "3.2.0" assert index["metadata"]["export_format"] == "grouped" def test_flat_index_still_produced_with_grouped(self, tmp_path): @@ -426,6 +426,148 @@ def test_version_nesting_structure(self, tmp_path): assert "request_schemas" not in ver assert "response_schemas" not in ver + def test_api_family_metadata_resource_hierarchy(self, tmp_path): + """Route entries expose bounded API-family and parent hierarchy metadata.""" + source = tmp_path / "spec" + v_dir = source / "Microsoft.Storage" / "stable" / "2023-01-01" + v_dir.mkdir(parents=True) + path = ( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}" + "/providers/Microsoft.Storage/storageAccounts/{accountName}" + "/blobServices/default/containers/{containerName}" + ) + _write_spec(v_dir, "storage.json", _minimal_swagger(paths={ + path: {"get": {"operationId": "Containers_Get", "responses": {}}} + })) + output = tmp_path / "out" + + exp.run_export(source, output, minified=False, verbose=False, grouped=True) + index = json.loads((output / "api-index-grouped.json").read_text()) + route_key = ( + "GET /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}" + "/providers/Microsoft.Storage/storageAccounts/{name}" + "/blobServices/default/containers/{name}" + ) + api_family = ( + index["providers"]["Microsoft.Storage"] + ["hosts"]["management.azure.com"] + ["routes"][route_key] + ["api_family"] + ) + + assert api_family == { + "family_key": "Microsoft.Storage/storageAccounts", + "provider_namespace": "Microsoft.Storage", + "resource_type_path": ["storageAccounts", "blobServices", "containers"], + "resource_key": "Microsoft.Storage/storageAccounts/blobServices/containers", + "resource_depth": 3, + "parent_resource_type_path": ["storageAccounts", "blobServices"], + "parent_resource_key": "Microsoft.Storage/storageAccounts/blobServices", + } + + def test_version_lineage_ordering_and_stability(self, tmp_path): + """Route entries expose ordered version links and deterministic stability classes.""" + source = tmp_path / "spec" + versions = ( + ("2023-06-01-preview", "preview"), + ("2022-01-01", "stable"), + ("2023-01-01", "stable"), + ("vNext", "stable"), + ) + for version, directory in versions: + v_dir = source / "Microsoft.Storage" / directory / version + v_dir.mkdir(parents=True) + spec = _minimal_swagger(paths={ + "/providers/Microsoft.Storage/storageAccounts/{accountName}": { + "get": {"operationId": f"StorageAccounts_Get_{version}", "responses": {}} + } + }) + spec["info"]["version"] = version + _write_spec(v_dir, f"{version}.json", spec) + output = tmp_path / "out" + + exp.run_export(source, output, minified=False, verbose=False, grouped=True) + index = json.loads((output / "api-index-grouped.json").read_text()) + route = ( + index["providers"]["Microsoft.Storage"] + ["hosts"]["management.azure.com"] + ["routes"]["GET /providers/Microsoft.Storage/storageAccounts/{name}"] + ) + lineage = route["version_lineage"]["ordered_versions"] + + assert [entry["api_version"] for entry in lineage] == [ + "2022-01-01", + "2023-01-01", + "2023-06-01-preview", + "vNext", + ] + assert [entry["stability"] for entry in lineage] == [ + "stable", + "stable", + "preview", + "unknown", + ] + assert "previous_version" not in lineage[0] + assert lineage[0]["next_version"] == "2023-01-01" + assert lineage[1]["previous_version"] == "2022-01-01" + assert lineage[1]["next_version"] == "2023-06-01-preview" + assert lineage[-1]["previous_version"] == "2023-06-01-preview" + assert "next_version" not in lineage[-1] + + def test_bounded_hierarchy_and_version_lineage_truncation(self): + """Bounded route metadata reports truncation when caps are exceeded.""" + long_path = "/providers/Microsoft.Test/" + "/".join( + f"type{i}/{{name{i}}}" for i in range(exp._MAX_RESOURCE_TYPE_SEGMENTS + 5) + ) + flat_ops = [] + for index in range(exp._MAX_METADATA_ITEMS + 5): + version = f"20{index // 12:02d}-{(index % 12) + 1:02d}-01" + flat_ops.append({ + "host": "management.azure.com", + "method": "GET", + "path_template": long_path, + "operation_id": f"Things_Get_{index}", + "api_versions": [version], + "spec_file": f"spec/{version}/test.json", + "source_kind": "paths", + "plane": "management", + "is_preview": False, + "lookup_key": f"management.azure.com|GET|{long_path}", + }) + + providers = exp._build_grouped_index(flat_ops) + route = ( + providers["Microsoft.Test"] + ["hosts"]["management.azure.com"] + ["routes"][f"GET {exp.normalize_path_template_for_key(long_path)}"] + ) + + assert len(route["api_family"]["resource_type_path"]) == exp._MAX_RESOURCE_TYPE_SEGMENTS + assert route["api_family"]["resource_type_path_truncated"] is True + assert len(route["version_lineage"]["ordered_versions"]) == exp._MAX_METADATA_ITEMS + assert route["version_lineage"]["versions_truncated"] is True + + def test_family_and_lineage_omitted_when_empty(self): + """Routes without provider resources or known versions omit optional route metadata.""" + flat_ops = [{ + "host": "example.test", + "method": "GET", + "path_template": "/status", + "operation_id": "Status_Get", + "api_versions": ["unknown"], + "spec_file": "status.json", + "source_kind": "paths", + "plane": "unknown", + "is_preview": False, + "lookup_key": "example.test|GET|/status", + }] + + providers = exp._build_grouped_index(flat_ops) + route = providers["unknown"]["hosts"]["example.test"]["routes"]["GET /status"] + + assert "api_family" not in route + assert "version_lineage" not in route + def test_grouped_research_metadata_swagger2(self, tmp_path): source = tmp_path / "spec" v_dir = source / "Microsoft.Test" / "stable" / "2023-01-01" @@ -504,6 +646,8 @@ def test_flat_schema_remains_2_1_without_research_metadata(self, tmp_path): assert flat["metadata"]["schema_version"] == "2.1.0" assert "_research_metadata" not in flat["operations"][0] assert "auth" not in flat["operations"][0] + assert "api_family" not in flat["operations"][0] + assert "version_lineage" not in flat["operations"][0] def test_openapi3_metadata_and_anonymous_override(self, tmp_path): source = tmp_path / "spec" @@ -842,7 +986,7 @@ def test_shard_metadata_export_format(self, tmp_path): exp.run_export(source, output, minified=False, verbose=False, sharded=True) shard = json.loads((output / "shards" / "Microsoft.Storage.json").read_text()) assert shard["metadata"]["export_format"] == "sharded" - assert shard["metadata"]["schema_version"] == "3.1.0" + assert shard["metadata"]["schema_version"] == "3.2.0" assert shard["metadata"]["provider_namespace"] == "Microsoft.Storage" def test_shard_contains_only_its_provider_routes(self, tmp_path): diff --git a/tests/test_api_inventory_normalization.py b/tests/test_api_inventory_normalization.py index 9a706c9..ab2be28 100644 --- a/tests/test_api_inventory_normalization.py +++ b/tests/test_api_inventory_normalization.py @@ -311,6 +311,19 @@ def test_default_singleton_preserved(self): assert "blobServices/default" in result assert "{name}" in result + def test_nested_singleton_child_resource_names_replaced(self): + path = ( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}" + "/providers/Microsoft.Storage/storageAccounts/{accountName}" + "/blobServices/default/containers/{containerName}" + ) + expected = ( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}" + "/providers/Microsoft.Storage/storageAccounts/{name}" + "/blobServices/default/containers/{name}" + ) + assert norm.normalize_path_template_for_key(path) == expected + def test_storage_account_name_replaced(self): path = ( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}"