From c5eda39ab63cdd87b9a6626b2c3cb62c44e9b11e Mon Sep 17 00:00:00 2001 From: goldjg Date: Sun, 20 Sep 2026 18:49:17 +0100 Subject: [PATCH 1/3] Add authoritative Microsoft Graph export pipeline Pin Microsoft Graph metadata ingestion, add deterministic YAML export support, and suppress duplicate workflow artifacts and publications using semantic hashes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/carl/current-pr-contract.md | 90 +++++--- .github/carl/memory.md | 16 +- .../microsoft-graph-authoritative-export.md | 63 +++++ .../daily-api-index-export-sharded.yml | 74 ++++-- .github/workflows/daily-api-index-export.yml | 66 ++++-- .gitignore | 1 + README.md | 18 +- config/sources/azure.json | 1 + config/sources/microsoft-graph.json | 14 ++ docs/ADDING_API_SOURCES.md | 50 +++- docs/inventory/API_INDEX_SCHEMA.md | 7 +- docs/inventory/EXPORT_PIPELINE.md | 28 ++- refresh-database.sh | 55 +++-- refresh_database.py | 63 ++++- requirements.txt | 3 + scripts/export/export_api_inventory.py | 218 +++++++++++++++--- scripts/export/hash_inventory.py | 71 ++++++ scripts/export/normalize_api_inventory.py | 8 +- tests/test_api_inventory_export.py | 184 +++++++++++++++ tests/test_api_inventory_normalization.py | 10 + tests/test_inventory_hash.py | 73 ++++++ tests/test_refresh_database.py | 90 ++++++++ 22 files changed, 1065 insertions(+), 138 deletions(-) create mode 100644 .github/carl/plans/microsoft-graph-authoritative-export.md create mode 100644 config/sources/microsoft-graph.json create mode 100644 scripts/export/hash_inventory.py create mode 100644 tests/test_inventory_hash.py create mode 100644 tests/test_refresh_database.py diff --git a/.github/carl/current-pr-contract.md b/.github/carl/current-pr-contract.md index e917dee..2c7b058 100644 --- a/.github/carl/current-pr-contract.md +++ b/.github/carl/current-pr-contract.md @@ -11,16 +11,18 @@ PR constraints are historical evidence unless they are explicitly promoted to durable invariants. ## Goal -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. +Add deterministic, offline-capable Microsoft Graph OpenAPI ingestion from the authoritative `microsoftgraph/msgraph-metadata` repository, pinned by commit SHA, and produce an APISpy-compatible grouped/sharded export without committing generated artifacts. ## Contract status active ## Non-goals -- 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. +- Do not change CodeQL queries or analyser behaviour. +- Do not alter workflow schedules, permissions beyond what publication already requires, or retention periods. +- Do not commit inventory, database, SARIF, shard, packaged outputs, or the cloned Graph source repository. +- Do not change flat inventory schema 2.1.0 or grouped/sharded schema 3.2.0. +- Do not resolve remote references, retain examples/descriptions, infer vulnerabilities, or add model/runtime-network functionality. +- Do not schedule automatic Graph publication or modify APISpy generated data in this SpecQL phase. ## Carry-forward rules The following constraints from this PR are promoted to durable invariants and must persist into all future PRs: @@ -30,23 +32,29 @@ 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 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. +- Register `microsoftgraph/msgraph-metadata` as an authoritative source pinned to commit `b8cbef92f6959dca8150bf3edcc650863765e529`. +- Extend source refresh configuration with optional exact-commit checkout support. +- Add safe YAML ingestion using `yaml.safe_load`; PyYAML is justified because the authoritative 44–70 MB OpenAPI documents are YAML and the standard library has no YAML parser. +- Auto-select a bounded `microsoft-graph` export profile from the authoritative source repository identifier, while retaining an explicit CLI override. +- Include OpenAPI server base paths (`/v1.0` and `/beta`) in exported route templates, classify the exact Graph host as data plane, and group Graph operations into one `Microsoft.Graph` shard compatible with APISpy's fail-closed host routing. +- Preserve OData parameter names, local-reference-only schema summarisation, deterministic ordering, existing schemas, and all Azure behaviour. +- Add focused fixtures/tests, source and export documentation, and durable cARL notes. +- Generate a local ignored candidate export for validation; do not commit it. +- Compute a semantic content hash that excludes volatile `generated_at` metadata. +- Restore the last changed-export hash from a tiny Actions cache and upload export artifacts, publish releases, and dispatch APISpy updates only when semantic content changed. ## Intentional amendments -- Supersedes the completed generated-artefact-boundary hardening scope. -- User-approved continuation of the UndREST research-platform implementation permits this bounded exporter change. +- Supersedes the completed SpecQL 3.2.0 family/lineage phase. +- User approval to “do it” explicitly authorises this bounded source-config, exporter, dependency, documentation, and local candidate-generation work. +- APISpy bundling remains a subsequent separately governed phase after the candidate export is validated. ## Forbidden scope -- Modifying CodeQL queries, analyser/runtime entry points, workflows, source configs, or dependencies. -- Regenerating or editing generated database, SARIF, JSON inventory, shard, or packaged artefacts. +- Modifying CodeQL queries, analyser behaviour, workflow schedules, or generated committed artifacts. +- Committing the cloned Graph metadata repository or generated inventory output. - 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. +- Fetching remote `$ref` content or deriving routes from anything except the pinned authoritative OpenAPI documents. +- Adding speculative vulnerability labels or Graph endpoint metadata not present in the source. ## Architectural constraints - Static API knowledge remains owned by SpecQL; observations and findings remain owned by APISpy. @@ -64,33 +72,51 @@ The following constraints from this PR are promoted to durable invariants and mu ## Files expected to change - `.github/carl/current-pr-contract.md` - `.github/carl/memory.md` +- `.github/carl/plans/microsoft-graph-authoritative-export.md` +- `.gitignore` +- `requirements.txt` +- `config/sources/microsoft-graph.json` +- `config/sources/azure.json` +- `refresh_database.py` +- `refresh-database.sh` - `scripts/export/export_api_inventory.py` +- `scripts/export/hash_inventory.py` +- `scripts/export/normalize_api_inventory.py` +- `.github/workflows/daily-api-index-export.yml` +- `.github/workflows/daily-api-index-export-sharded.yml` - `tests/test_api_inventory_export.py` - `tests/test_api_inventory_normalization.py` +- `tests/test_refresh_database.py` +- `tests/test_inventory_hash.py` +- `docs/ADDING_API_SOURCES.md` - `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 +- `README.md` ## 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.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 `python3 -m compileall` on changed Python files, `git diff --check`, and `carl doctor` when available. +- `python3 -m pytest tests/test_api_inventory_export.py tests/test_api_inventory_normalization.py tests/test_refresh_database.py tests/test_inventory_hash.py -v` +- `python3 -m pytest -q` +- `bash -n refresh-database.sh` +- Parse both modified workflow YAML files. +- Confirm identical semantic exports with different timestamps hash equally and changed routes hash differently. +- Confirm artifact upload, shard release publication, and APISpy dispatch are all gated by the content-change output. +- Confirm JSON/Azure behavior remains unchanged and schemas remain 2.1.0/3.2.0. +- Confirm YAML uses safe loading and fails clearly when PyYAML is unavailable. +- Confirm Graph host, `/v1.0` and `/beta` prefixes, preview classification, OData parameters, fixed provider namespace, deterministic shard name, and pinned provenance. +- Generate a local ignored Graph candidate and inspect route/provider/version counts without committing artifacts. +- Run `python3 -m compileall` on changed Python files, `git diff --check`, protected-path checks, and `carl doctor`. ## Stop conditions -- 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. +- The pinned authoritative source is unavailable or its license/provenance cannot be verified. +- Existing Azure route identity, matching keys, or schemas regress. +- YAML parsing requires unsafe loading or remote-reference resolution. +- Generated inventory, database, source clone, SARIF, or shard artifacts become tracked. - A secret or raw example/default value would be retained. ## Escalation triggers -- 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. +- Any need to modify workflows, CodeQL queries, or analyser logic. +- Any need for a breaking schema version or multiple Graph shards unsupported by APISpy routing. +- Any source other than the pinned official Microsoft Graph metadata repository is required. ## Context reset notes -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. +This contract covers authoritative Microsoft Graph source acquisition and SpecQL export only. APISpy generated-pack integration begins only after this phase produces and validates a local candidate. diff --git a/.github/carl/memory.md b/.github/carl/memory.md index bf659b0..b72a35e 100644 --- a/.github/carl/memory.md +++ b/.github/carl/memory.md @@ -54,15 +54,14 @@ SpeQL is a Python + CodeQL analysis pipeline targeting Azure REST API JSON specs | `inventory/` | Generated; only `.gitkeep` tracked | Exported API index artefacts (`.json`, `.min.json`, `shards/`, and packaged `.zip` outputs are gitignored) | | `azure-rest-api-specs/` | Cloned externally; gitignored | Source spec corpus managed by refresh scripts | | `queries/azure-security/` | Committed | CodeQL query pack with `qlpack.yml` | -| `config/sources/` | Committed | One JSON per spec source (currently `azure.json`) | +| `config/sources/` | Committed | One JSON per spec source (`azure.json`, pinned `microsoft-graph.json`) | | `scripts/export/` | Committed | Export pipeline Python modules | | `scripts/sarif-analysis/` | Committed | SARIF threat hunting shell scripts | | `tests/` | Committed | Unit tests for export pipeline (120 tests; run without CodeQL or DB) | ### Multi-source architecture -Scripts accept `--source-config config/sources/.json` to support any OpenAPI/Swagger spec corpus. -Adding a new source requires only a source config JSON and optionally a platform-specific query directory. +Refresh scripts accept `--source-config config/sources/.json` to support multiple OpenAPI/Swagger corpora. Source configs may pin an exact `source_commit`. The exporter supports a generic JSON profile and a reviewed `microsoft-graph` YAML profile; unusual routing semantics require an explicit bounded profile rather than heuristics. ### Export pipeline @@ -74,7 +73,7 @@ Adding a new source requires only a source config JSON and optionally a platform - Minified variants (`*.min.json`) with `--minified` - Packaged sharded export ZIPs for release publication -Published to UndREST-APISpy via GitHub Releases. +Published to UndREST-APISpy via GitHub Releases. Export workflows compute semantic SHA-256 hashes with volatile `generated_at` metadata removed and only upload artifacts, replace the shard release, or dispatch APISpy when content changed; a tiny Actions cache stores the last changed hash. ### GitHub Actions workflows @@ -93,7 +92,7 @@ JSON specs). This is a hard version pin, not a preference. ## Python dependencies -`requirements.txt` currently lists only `pyfiglet>=0.8.0` (for the ASCII art logo). +`requirements.txt` lists `pyfiglet>=0.8.0` for the CLI logo and `PyYAML>=6.0,<7.0` for safe parsing of authoritative OpenAPI YAML sources. Hidden runtime dependencies not in requirements.txt: - `pytest` — test runner; installed separately by CI workflows and docs @@ -123,7 +122,8 @@ requires a package, document it explicitly rather than silently adding. ## Ecosystem context - **APISpy** (UndREST-Labs/UndREST-APISpy): browser extension that consumes SpeQL's exported JSON index for real-time request classification. -- **azure-rest-api-specs** (Azure/azure-rest-api-specs): upstream spec corpus; cloned by refresh scripts, never vendored. +- **azure-rest-api-specs** (Azure/azure-rest-api-specs): upstream Azure spec corpus; cloned by refresh scripts, never vendored. +- **msgraph-metadata** (microsoftgraph/msgraph-metadata): authoritative Microsoft Graph OpenAPI source, pinned by exact commit and cloned locally; only canonical `openapi.yaml` files for v1.0 and beta are ingested. ## cARL installation @@ -135,7 +135,7 @@ requires a package, document it explicitly rather than silently adding. ## Core invariants -- Do not commit database/, results/, azure-rest-api-specs/, or generated inventory exports (JSON, shards, or packaged ZIPs). +- Do not commit database/, results/, azure-rest-api-specs/, msgraph-metadata/, or generated inventory exports (JSON, shards, or packaged ZIPs). - Always pin CodeQL CLI to 2.20.1 or 2.20.2 in setup, docs, and CI. - 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. @@ -155,4 +155,4 @@ requires a package, document it explicitly rather than silently adding. ## Last updated -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 +2026-09-20 — pinned Microsoft Graph export plus semantic-hash deduplication for export artifacts and publication. \ No newline at end of file diff --git a/.github/carl/plans/microsoft-graph-authoritative-export.md b/.github/carl/plans/microsoft-graph-authoritative-export.md new file mode 100644 index 0000000..375c75f --- /dev/null +++ b/.github/carl/plans/microsoft-graph-authoritative-export.md @@ -0,0 +1,63 @@ +# Microsoft Graph Authoritative Export Plan + +## Status +Active — user-approved implementation. + +## Source + +- Repository: `https://github.com/microsoftgraph/msgraph-metadata.git` +- Revision: `b8cbef92f6959dca8150bf3edcc650863765e529` +- License: MIT +- Inputs: + - `openapi/v1.0/openapi.yaml` + - `openapi/beta/openapi.yaml` + +The repository is Microsoft's canonical Graph metadata/OpenAPI source. The exact +commit is recorded in source configuration and checked out detached for +reproducibility. + +## Implementation + +1. Add a Microsoft Graph source config with exact-commit pinning. +2. Extend Python source refresh to honor an optional `source_commit` after clone + or fetch. Do not alter unrelated workflows. +3. Add safe YAML discovery/loading to the exporter. Use `yaml.safe_load`; never + resolve remote references. +4. Auto-select a `microsoft-graph` profile for the official source repository, + with an explicit `--source-profile` override for local fixtures. +5. For that profile only: + - use exact host `graph.microsoft.com`; + - prepend the OpenAPI server base path (`/v1.0` or `/beta`) to route paths; + - classify the plane as `data`; + - group all routes under the single provider namespace `Microsoft.Graph` so + APISpy's existing exact-host single-shard fallback remains fail-closed and + deterministic; + - preserve source path templates, operation IDs, OData parameter names, and + bounded local-reference research metadata. +6. Add focused fixtures/tests for JSON compatibility, YAML safety, v1.0/beta, + route-key normalisation, provider grouping, and dependency failure. +7. Update source/export/schema documentation and durable cARL memory. +8. Clone the pinned source locally, generate an ignored candidate export, inspect + counts and provenance, and do not commit generated output or the source clone. +9. Compute deterministic semantic hashes with volatile export timestamps removed. + Export workflows restore the last changed hash from a tiny Actions cache and + only upload artifacts, publish the shard release, or dispatch APISpy when the + new hash differs. + +## Validation + +- Targeted export and normalization tests. +- Full pytest suite. +- Python compile checks. +- Candidate export inspection for one provider shard, exact host, both versions, + and pinned source commit. +- `git diff --check`, generated-artifact/source-clone tracking checks, and + `carl doctor`. + +## Stop conditions + +- Upstream revision or license cannot be verified. +- Safe YAML parsing cannot be used. +- Azure output changes unexpectedly. +- A breaking schema change or speculative route derivation is required. +- Generated artifacts or source clones become tracked. diff --git a/.github/workflows/daily-api-index-export-sharded.yml b/.github/workflows/daily-api-index-export-sharded.yml index 92f182d..277c30d 100644 --- a/.github/workflows/daily-api-index-export-sharded.yml +++ b/.github/workflows/daily-api-index-export-sharded.yml @@ -12,9 +12,9 @@ on: required: false default: 'config/sources/azure.json' spec_scope: - description: 'Subdirectory within the specs repo to export (default: specification)' + description: 'Optional subdirectory override within the specs repo' required: false - default: 'specification' + default: '' jobs: export-api-index-sharded: @@ -33,7 +33,7 @@ jobs: - name: Install dependencies run: | - pip install pyfiglet pytest + pip install -r requirements.txt pytest - name: Resolve source config id: source @@ -41,12 +41,12 @@ jobs: SOURCE_CONFIG="${{ github.event.inputs.source_config || 'config/sources/azure.json' }}" echo "config=${SOURCE_CONFIG}" >> "$GITHUB_OUTPUT" # Read fields from the source config for use in later steps + SOURCE_ID=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('id','unknown'))") SPECS_DIR=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('specs_dir','azure-rest-api-specs'))") SOURCE_REPO=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('source_repo','unknown'))") - SOURCE_BRANCH=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('source_branch','main'))") + echo "source_id=${SOURCE_ID}" >> "$GITHUB_OUTPUT" echo "specs_dir=${SPECS_DIR}" >> "$GITHUB_OUTPUT" echo "source_repo=${SOURCE_REPO}" >> "$GITHUB_OUTPUT" - echo "source_branch=${SOURCE_BRANCH}" >> "$GITHUB_OUTPUT" - name: Clone / update spec repository run: | @@ -56,26 +56,62 @@ jobs: --skip-db-build - name: Run API inventory export + env: + SPEC_SCOPE: ${{ github.event.inputs.spec_scope }} run: | - SCOPE="${{ github.event.inputs.spec_scope || 'specification' }}" - python3 scripts/export/export_api_inventory.py \ - --source "${{ steps.source.outputs.specs_dir }}/${SCOPE}" \ - --output-dir inventory/ \ - --source-repo "${{ steps.source.outputs.source_repo }}" \ - --source-branch "${{ steps.source.outputs.source_branch }}" \ - --sharded \ - --minified \ + ARGS=( + --source-config "${{ steps.source.outputs.config }}" + --output-dir inventory/ + --sharded + --minified --verbose + ) + if [ -n "$SPEC_SCOPE" ]; then + ARGS+=(--source "${{ steps.source.outputs.specs_dir }}/${SPEC_SCOPE}") + fi + python3 scripts/export/export_api_inventory.py "${ARGS[@]}" - name: Run export pipeline tests run: | python3 -m pytest \ tests/test_api_inventory_export.py \ tests/test_api_inventory_normalization.py \ + tests/test_inventory_hash.py \ + tests/test_refresh_database.py \ -v + - name: Restore last changed-export hash + uses: actions/cache/restore@v4 + with: + path: .artifact-state/sharded-${{ steps.source.outputs.source_id }} + key: inventory-sharded-state-${{ steps.source.outputs.source_id }}-${{ github.run_id }} + restore-keys: | + inventory-sharded-state-${{ steps.source.outputs.source_id }}- + + - name: Compare export content + id: content + run: | + STATE_DIR=".artifact-state/sharded-${{ steps.source.outputs.source_id }}" + CURRENT_HASH=$(python3 scripts/export/hash_inventory.py --inventory-dir inventory --format sharded) + PREVIOUS_HASH=$(cat "${STATE_DIR}/last.sha256" 2>/dev/null || true) + if [ "$CURRENT_HASH" = "$PREVIOUS_HASH" ]; then + echo "changed=false" >> "$GITHUB_OUTPUT" + echo "Export content is unchanged; skipping release, dispatch, and artifact upload." + else + mkdir -p "$STATE_DIR" + printf '%s\n' "$CURRENT_HASH" > "${STATE_DIR}/last.sha256" + echo "changed=true" >> "$GITHUB_OUTPUT" + echo "Export content changed: ${PREVIOUS_HASH:-} -> $CURRENT_HASH" + fi + + - name: Package changed shard export + if: steps.content.outputs.changed == 'true' + run: | + cd inventory + zip -q -r "api-index-sharded-${{ github.run_id }}.zip" shards/ + - name: Publish shards to GitHub Release - if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + if: steps.content.outputs.changed == 'true' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | @@ -94,7 +130,7 @@ jobs: fi - name: Trigger APISpy shard update - if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + if: steps.content.outputs.changed == 'true' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') run: | curl -X POST \ -H "Authorization: Bearer ${{ secrets.APISPY_DISPATCH_TOKEN }}" \ @@ -112,9 +148,17 @@ jobs: }' - name: Upload inventory artifact + if: steps.content.outputs.changed == 'true' uses: actions/upload-artifact@v4 with: name: api-index-sharded-${{ github.run_id }} path: inventory/ retention-days: 2 + - name: Save changed-export hash + if: steps.content.outputs.changed == 'true' + uses: actions/cache/save@v4 + with: + path: .artifact-state/sharded-${{ steps.source.outputs.source_id }} + key: inventory-sharded-state-${{ steps.source.outputs.source_id }}-${{ github.run_id }} + diff --git a/.github/workflows/daily-api-index-export.yml b/.github/workflows/daily-api-index-export.yml index 54264e5..22cf0f4 100644 --- a/.github/workflows/daily-api-index-export.yml +++ b/.github/workflows/daily-api-index-export.yml @@ -12,9 +12,9 @@ on: required: false default: 'config/sources/azure.json' spec_scope: - description: 'Subdirectory within the specs repo to export (default: specification)' + description: 'Optional subdirectory override within the specs repo' required: false - default: 'specification' + default: '' jobs: export-api-index: @@ -33,19 +33,17 @@ jobs: - name: Install dependencies run: | - pip install pyfiglet pytest + pip install -r requirements.txt pytest - name: Resolve source config id: source run: | SOURCE_CONFIG="${{ github.event.inputs.source_config || 'config/sources/azure.json' }}" echo "config=${SOURCE_CONFIG}" >> "$GITHUB_OUTPUT" + SOURCE_ID=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('id','unknown'))") SPECS_DIR=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('specs_dir','azure-rest-api-specs'))") - SOURCE_REPO=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('source_repo','unknown'))") - SOURCE_BRANCH=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('source_branch','main'))") + echo "source_id=${SOURCE_ID}" >> "$GITHUB_OUTPUT" echo "specs_dir=${SPECS_DIR}" >> "$GITHUB_OUTPUT" - echo "source_repo=${SOURCE_REPO}" >> "$GITHUB_OUTPUT" - echo "source_branch=${SOURCE_BRANCH}" >> "$GITHUB_OUTPUT" - name: Clone / update spec repository run: | @@ -55,28 +53,66 @@ jobs: --skip-db-build - name: Run API inventory export + env: + SPEC_SCOPE: ${{ github.event.inputs.spec_scope }} run: | - SCOPE="${{ github.event.inputs.spec_scope || 'specification' }}" - python3 scripts/export/export_api_inventory.py \ - --source "${{ steps.source.outputs.specs_dir }}/${SCOPE}" \ - --output-dir inventory/ \ - --source-repo "${{ steps.source.outputs.source_repo }}" \ - --source-branch "${{ steps.source.outputs.source_branch }}" \ - --grouped \ - --minified \ + ARGS=( + --source-config "${{ steps.source.outputs.config }}" + --output-dir inventory/ + --grouped + --minified --verbose + ) + if [ -n "$SPEC_SCOPE" ]; then + ARGS+=(--source "${{ steps.source.outputs.specs_dir }}/${SPEC_SCOPE}") + fi + python3 scripts/export/export_api_inventory.py "${ARGS[@]}" - name: Run export pipeline tests run: | python3 -m pytest \ tests/test_api_inventory_export.py \ tests/test_api_inventory_normalization.py \ + tests/test_inventory_hash.py \ + tests/test_refresh_database.py \ -v + - name: Restore last changed-export hash + uses: actions/cache/restore@v4 + with: + path: .artifact-state/grouped-${{ steps.source.outputs.source_id }} + key: inventory-grouped-state-${{ steps.source.outputs.source_id }}-${{ github.run_id }} + restore-keys: | + inventory-grouped-state-${{ steps.source.outputs.source_id }}- + + - name: Compare export content + id: content + run: | + STATE_DIR=".artifact-state/grouped-${{ steps.source.outputs.source_id }}" + CURRENT_HASH=$(python3 scripts/export/hash_inventory.py --inventory-dir inventory --format grouped) + PREVIOUS_HASH=$(cat "${STATE_DIR}/last.sha256" 2>/dev/null || true) + if [ "$CURRENT_HASH" = "$PREVIOUS_HASH" ]; then + echo "changed=false" >> "$GITHUB_OUTPUT" + echo "Export content is unchanged; skipping artifact upload." + else + mkdir -p "$STATE_DIR" + printf '%s\n' "$CURRENT_HASH" > "${STATE_DIR}/last.sha256" + echo "changed=true" >> "$GITHUB_OUTPUT" + echo "Export content changed: ${PREVIOUS_HASH:-} -> $CURRENT_HASH" + fi + - name: Upload inventory artifact + if: steps.content.outputs.changed == 'true' uses: actions/upload-artifact@v4 with: name: api-index-${{ github.run_id }} path: inventory/ retention-days: 2 + - name: Save changed-export hash + if: steps.content.outputs.changed == 'true' + uses: actions/cache/save@v4 + with: + path: .artifact-state/grouped-${{ steps.source.outputs.source_id }} + key: inventory-grouped-state-${{ steps.source.outputs.source_id }}-${{ github.run_id }} + diff --git a/.gitignore b/.gitignore index c5c51e6..39e633f 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,7 @@ Thumbs.db # Cloned upstream API spec corpus # Owned by: `refresh_database.py`, `refresh-database.sh`, and export/scan workflows azure-rest-api-specs/ +msgraph-metadata/ # Generated CodeQL databases and build logs # Owned by: `refresh_database.py`, `refresh-database.sh`, and `.github/workflows/speql-security-scan.yml` diff --git a/README.md b/README.md index 475715c..6a0411d 100644 --- a/README.md +++ b/README.md @@ -246,8 +246,15 @@ SpeQL is designed to work with any OpenAPI/Swagger spec corpus, not just 1. **A source config file** (`config/sources/.json`) — declares the upstream repository URL, local directory names, and metadata. 2. **Optionally, platform-specific CodeQL queries** (`queries/-security/`). +3. **For unusual layouts, a reviewed export profile** such as the built-in + `microsoft-graph` profile for canonical OpenAPI YAML. -All scripts and workflows accept a `--source-config` flag: +The registered Microsoft Graph source is pinned to +`microsoftgraph/msgraph-metadata@b8cbef92f6959dca8150bf3edcc650863765e529` +and emits a single `Microsoft.Graph` shard covering authoritative v1.0 and beta +routes without runtime fetching or speculative metadata. + +All refresh scripts accept a `--source-config` flag: ```bash # Refresh using a custom source @@ -415,11 +422,10 @@ python3 scripts/export/export_api_inventory.py \ --output-dir inventory/ \ --sharded --minified --verbose -# Custom source +# Microsoft Graph (after refreshing config/sources/microsoft-graph.json) python3 scripts/export/export_api_inventory.py \ - --source my-platform-api-specs/specification \ - --source-repo MyOrg/my-platform-api-specs \ - --output-dir inventory/ \ + --source-config config/sources/microsoft-graph.json \ + --output-dir inventory/graph \ --sharded --minified --verbose ``` @@ -428,7 +434,7 @@ python3 scripts/export/export_api_inventory.py \ - `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. +**Cross-repo pipeline:** The `daily-api-index-export-sharded.yml` workflow runs nightly and computes a semantic content hash with volatile generation timestamps removed. It publishes the sharded zip, stores an Actions artifact, and triggers [UndREST-APISpy](https://github.com/UndREST-Labs/UndREST-APISpy) only when the export differs from the last changed export. The grouped workflow applies the same deduplication before artifact upload. See [docs/inventory/EXPORT_PIPELINE.md](docs/inventory/EXPORT_PIPELINE.md) for the full schema and consumer guide. diff --git a/config/sources/azure.json b/config/sources/azure.json index 168cf62..2cea999 100644 --- a/config/sources/azure.json +++ b/config/sources/azure.json @@ -5,6 +5,7 @@ "specs_dir": "azure-rest-api-specs", "database_dir": "database/azure-api-db", "default_spec_path": "specification/logic", + "export_spec_path": "specification", "source_repo": "Azure/azure-rest-api-specs", "source_branch": "main", "query_packs": [ diff --git a/config/sources/microsoft-graph.json b/config/sources/microsoft-graph.json new file mode 100644 index 0000000..39b755c --- /dev/null +++ b/config/sources/microsoft-graph.json @@ -0,0 +1,14 @@ +{ + "id": "microsoft-graph", + "name": "Microsoft Graph OpenAPI Metadata", + "repo_url": "https://github.com/microsoftgraph/msgraph-metadata.git", + "specs_dir": "msgraph-metadata", + "database_dir": "database/microsoft-graph-api-db", + "default_spec_path": "openapi", + "export_spec_path": "openapi", + "source_repo": "microsoftgraph/msgraph-metadata", + "source_branch": "master", + "source_commit": "b8cbef92f6959dca8150bf3edcc650863765e529", + "export_profile": "microsoft-graph", + "query_packs": [] +} diff --git a/docs/ADDING_API_SOURCES.md b/docs/ADDING_API_SOURCES.md index 81a2af8..07dd69d 100644 --- a/docs/ADDING_API_SOURCES.md +++ b/docs/ADDING_API_SOURCES.md @@ -6,8 +6,11 @@ source requires only: 1. A JSON source config file in `config/sources/` 2. Optionally, platform-specific CodeQL queries in `queries/-security/` +3. For unusual source layouts, an existing bounded export profile -No changes to core scripts are needed. +Most JSON OpenAPI sources require no core changes. Authoritative YAML sources +require PyYAML, and source-specific route semantics must use an explicitly +reviewed export profile rather than heuristic metadata invention. --- @@ -36,8 +39,11 @@ Source configs live in `config/sources/` and follow this schema: "specs_dir": "my-platform-api-specs", "database_dir": "database/my-platform-api-db", "default_spec_path": "specification", + "export_spec_path": "specification", "source_repo": "MyOrg/my-platform-api-specs", "source_branch": "main", + "source_commit": "", + "export_profile": "generic", "query_packs": ["queries/my-platform-security"] } ``` @@ -52,8 +58,11 @@ Source configs live in `config/sources/` and follow this schema: | `specs_dir` | Yes | — | Local directory where the repo is cloned | | `database_dir` | Yes | — | Where to write the CodeQL database | | `default_spec_path` | Yes | — | Default subdirectory within `specs_dir` to index | +| `export_spec_path` | No | `default_spec_path` | Default export scope; use this to preserve a narrower interactive/database default | | `source_repo` | No | `"unknown"` | `org/repo` identifier recorded in export metadata | | `source_branch` | No | `"main"` | Branch name recorded in export metadata | +| `source_commit` | No | branch head | Exact full commit SHA to fetch, check out detached, and verify for reproducible acquisition | +| `export_profile` | No | `"generic"` | Reviewed source-specific exporter profile; currently `generic` or `microsoft-graph` | | `query_packs` | No | `["queries/azure-security"]` | List of query pack directories to run against this source's database | Save the file as `config/sources/.json`. @@ -70,9 +79,11 @@ python3 refresh_database.py --source-config config/sources/my-platform.json --al ./refresh-database.sh --source-config config/sources/my-platform.json --all --skip-db-build ``` -The `--source-config` flag causes the scripts to read `repo_url`, `specs_dir`, -`database_dir`, and `default_spec_path` from the config file rather than using -the built-in Azure defaults. +The `--source-config` flag causes the refresh scripts to read `repo_url`, +`specs_dir`, `database_dir`, `default_spec_path`, and optional `source_commit` +from the config file rather than using the built-in Azure defaults. When +`source_commit` is present, refresh fetches that exact revision, checks it out +detached, and verifies `HEAD`. All other flags (`--fresh`, `--path`, `--branch`, `--clean`, etc.) still work as normal and override the config values when provided. @@ -102,6 +113,7 @@ python3 scripts/export/export_api_inventory.py \ --output-dir inventory/ \ --source-repo MyOrg/my-platform-api-specs \ --source-branch main \ + --source-profile generic \ --sharded \ --minified \ --verbose @@ -111,6 +123,29 @@ The `--source-repo` and `--source-branch` arguments are recorded in the export metadata so that consumers of the index can trace the data back to its origin. When omitted, the values are auto-detected from the git remote. +### Microsoft Graph authoritative export + +```bash +python3 refresh_database.py \ + --source-config config/sources/microsoft-graph.json \ + --all \ + --skip-db-build + +python3 scripts/export/export_api_inventory.py \ + --source-config config/sources/microsoft-graph.json \ + --output-dir inventory/graph \ + --sharded \ + --minified +``` + +The source is Microsoft's MIT-licensed +[`microsoftgraph/msgraph-metadata`](https://github.com/microsoftgraph/msgraph-metadata) +repository. The profile safely parses the official OpenAPI YAML, includes +`/v1.0` or `/beta` from each server URL in route templates, classifies the exact +`graph.microsoft.com` host as data plane, and emits one `Microsoft.Graph` +provider shard. A single shard is intentional: APISpy can route an exact host +to one shard without guessing. The profile never fetches remote `$ref` content. + --- ## Step 5 — Add platform-specific CodeQL queries (optional) @@ -213,6 +248,13 @@ registered sources are: | File | Source | Query packs | |------|--------|-------------| | `azure.json` | `Azure/azure-rest-api-specs` — Microsoft Azure REST API Specifications | `queries/azure-security` | +| `microsoft-graph.json` | `microsoftgraph/msgraph-metadata` — pinned canonical Graph v1.0/beta OpenAPI | none | + +`microsoft-graph.json` pins commit +`b8cbef92f6959dca8150bf3edcc650863765e529` and uses only +`openapi/v1.0/openapi.yaml` plus `openapi/beta/openapi.yaml`. Alternate generated +profiles in those directories are deliberately excluded to avoid duplicate +routes. Add your new file to this table when you create it. diff --git a/docs/inventory/API_INDEX_SCHEMA.md b/docs/inventory/API_INDEX_SCHEMA.md index 7330c35..5b831c8 100644 --- a/docs/inventory/API_INDEX_SCHEMA.md +++ b/docs/inventory/API_INDEX_SCHEMA.md @@ -180,7 +180,7 @@ providers |----------------------|--------|-------------| | `method` | string | HTTP method (uppercase) | | `path_template` | string | URL path template with `{paramName}` placeholders | -| `provider_namespace` | string | E.g. `"Microsoft.Storage"`, or `"unknown"` | +| `provider_namespace` | string | E.g. `"Microsoft.Storage"`, source-profile namespace `"Microsoft.Graph"`, 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 | @@ -216,6 +216,11 @@ providers resource-type path. It is structural only: descriptions, tags, operation names, examples, and inferred product semantics are not used. +For the `microsoft-graph` source profile, canonical `/v1.0` and `/beta` paths are +grouped under the fixed source namespace `Microsoft.Graph`. Graph routes do not +receive ARM-specific `api_family` metadata because they have no +`/providers/{namespace}` structure. + #### Route `version_lineage` object ```json diff --git a/docs/inventory/EXPORT_PIPELINE.md b/docs/inventory/EXPORT_PIPELINE.md index 3cd74b5..04d7709 100644 --- a/docs/inventory/EXPORT_PIPELINE.md +++ b/docs/inventory/EXPORT_PIPELINE.md @@ -76,8 +76,10 @@ python3 scripts/export/export_api_inventory.py \ | Option | Default | Description | |-----------------|----------------------------------------|------------------------------------------------| -| `--source` | `azure-rest-api-specs/specification` | Path to the specifications directory to walk | +| `--source-config` | _(none)_ | Source config used to derive source path, provenance, and profile | +| `--source` | source config or `azure-rest-api-specs/specification` | Path override for the specifications directory | | `--output-dir` | `inventory/` | Directory where output files are written | +| `--source-profile` | `auto` | `generic`, `microsoft-graph`, or source-repository auto-detection | | `--minified` | _(off)_ | Also write minified variants (no indentation) | | `--grouped` | _(off)_ | Also write grouped/deduplicated `api-index-grouped.json` (schema 3.2.0) | | `--verbose` | _(off)_ | Print per-file progress messages | @@ -97,6 +99,19 @@ All files are listed in `.gitignore` and are not committed to the repository. They are produced as build artifacts by the CI workflow and uploaded as GitHub Actions artifacts. +### Microsoft Graph + +The `microsoft-graph` profile ingests the two canonical YAML documents from the +pinned `microsoftgraph/msgraph-metadata` checkout: + +- `openapi/v1.0/openapi.yaml` +- `openapi/beta/openapi.yaml` + +It excludes alternate generated profiles, prepends each document's server base +path to its routes, and groups all operations into `Microsoft.Graph`. PyYAML is +the only added runtime dependency and loading uses `yaml.safe_load`. Remote +references are never fetched. + See [API_INDEX_SCHEMA.md](./API_INDEX_SCHEMA.md) for a full description of every field in the output. @@ -110,7 +125,7 @@ field in the output. | **Output** | SARIF findings, security reports | Normalized JSON index of all known operations | | **Scope** | Focused queries (e.g. SAS URI exposure) | All operations across the entire spec corpus | | **Consumer** | Security engineers, CodeQL analysis | APISpy extension, runtime comparison tools | -| **CodeQL required** | Yes | No — pure Python, stdlib only | +| **CodeQL required** | Yes | No — Python plus PyYAML for YAML OpenAPI sources | | **Run frequency** | On demand / weekly | Daily (scheduled CI) | --- @@ -118,13 +133,16 @@ field in the output. ## Scheduled / CI Generation A GitHub Actions workflow at `.github/workflows/daily-api-index-export.yml` -runs the export automatically every day at 04:00 UTC and uploads the result as -a build artifact. +runs the export automatically every day at 04:00 UTC. Both export workflows +compute a semantic SHA-256 over canonical JSON with volatile `generated_at` +metadata removed. They restore the last changed-export hash from a small Actions +cache and upload a new artifact only when content differs. The sharded workflow +also skips release replacement and APISpy dispatch for unchanged output. To trigger the workflow manually from the GitHub UI: 1. Navigate to **Actions → Daily API Index Export** 2. Click **Run workflow** -3. Optionally set `spec_scope` (default: `specification`) +3. Optionally set `spec_scope`; otherwise the source config's `export_spec_path` (or `default_spec_path`) is used --- diff --git a/refresh-database.sh b/refresh-database.sh index cc80c0b..35b6f80 100644 --- a/refresh-database.sh +++ b/refresh-database.sh @@ -49,6 +49,7 @@ SPECS_DIR="" DATABASE_DIR="" DEFAULT_SPEC_PATH="" SOURCE_NAME="" +SOURCE_COMMIT="" CONFIG_FILE="config/SpeQL.yml" @@ -177,6 +178,7 @@ load_source_config() { DATABASE_DIR="database/azure-api-db" DEFAULT_SPEC_PATH="specification/logic" SOURCE_NAME="Azure REST API Specifications" + SOURCE_COMMIT="" return fi @@ -185,12 +187,18 @@ load_source_config() { DATABASE_DIR=$(_json_field "$cfg_file" "database_dir" "database/azure-api-db") DEFAULT_SPEC_PATH=$(_json_field "$cfg_file" "default_spec_path" "specification/logic") SOURCE_NAME=$(_json_field "$cfg_file" "name" "API Specifications") + SOURCE_COMMIT=$(_json_field "$cfg_file" "source_commit" "") print_info "Loaded source config: $cfg_file ($SOURCE_NAME)" } # Function to clone or update the source repo manage_source_repo() { print_info "Managing spec repository: $REPO_URL" + + if [ -n "$SOURCE_COMMIT" ] && [[ ! "$SOURCE_COMMIT" =~ ^[0-9a-fA-F]{40}$ ]]; then + print_error "source_commit must be a full 40-character hexadecimal Git SHA" + return 1 + fi if [ "$FRESH_CLONE" = true ] && [ -d "$SPECS_DIR" ]; then print_warning "Removing existing directory '$SPECS_DIR' for fresh clone..." @@ -201,17 +209,19 @@ manage_source_repo() { print_info "Updating existing spec repository in '$SPECS_DIR'..." cd "$SPECS_DIR" - # Fetch latest changes - git fetch origin "$BRANCH" - - # Reset to latest - git reset --hard "origin/$BRANCH" - - # Clean untracked files + local revision="${SOURCE_COMMIT:-$BRANCH}" + git fetch --depth 1 origin "$revision" + + if [ -n "$SOURCE_COMMIT" ]; then + git checkout --detach "$SOURCE_COMMIT" + else + git reset --hard "origin/$BRANCH" + fi + git clean -fdx - + cd .. - print_success "Repository updated to latest version" + print_success "Repository updated to ${SOURCE_COMMIT:-origin/$BRANCH}" else print_info "Cloning spec repository (this may take a few minutes)..." @@ -225,14 +235,29 @@ manage_source_repo() { git sparse-checkout set "$SPEC_PATH" cd .. fi - + + if [ -n "$SOURCE_COMMIT" ]; then + git -C "$SPECS_DIR" fetch --depth 1 origin "$SOURCE_COMMIT" + git -C "$SPECS_DIR" checkout --detach "$SOURCE_COMMIT" + fi + print_success "Repository cloned successfully" fi - + + if [ -n "$SOURCE_COMMIT" ]; then + local checked_out + checked_out=$(git -C "$SPECS_DIR" rev-parse HEAD) + if [ "${checked_out,,}" != "${SOURCE_COMMIT,,}" ]; then + print_error "Checked-out revision does not match pinned commit: $SOURCE_COMMIT" + return 1 + fi + fi + # Display stats if [ -d "$SPECS_DIR" ]; then - local json_count=$(find "$SPECS_DIR/$SPEC_PATH" -name "*.json" 2>/dev/null | wc -l) - print_info "Found $json_count JSON files in $SPEC_PATH" + local spec_count + spec_count=$(find "$SPECS_DIR/$SPEC_PATH" -type f \( -name "*.json" -o -name "*.yaml" -o -name "*.yml" \) 2>/dev/null | wc -l) + print_info "Found $spec_count JSON/YAML files in $SPEC_PATH" fi } @@ -382,6 +407,9 @@ load_source_config # Apply overrides from CLI flags BRANCH="${BRANCH_OVERRIDE:-$(_json_field "${SOURCE_CONFIG:-$DEFAULT_SOURCE_CONFIG}" source_branch main)}" +if [ -n "$BRANCH_OVERRIDE" ]; then + SOURCE_COMMIT="" +fi if [ "$INCLUDE_ALL" = true ]; then # Use the top-level spec root directory from default_spec_path @@ -411,6 +439,7 @@ main() { echo " - Database directory: $DATABASE_DIR" echo " - Specification path: $SPEC_PATH" echo " - Branch: $BRANCH" + echo " - Pinned commit: ${SOURCE_COMMIT:-'(branch head)'}" echo " - Fresh clone: $FRESH_CLONE" echo " - Skip DB build: $SKIP_DB_BUILD" echo "" diff --git a/refresh_database.py b/refresh_database.py index 097f6b1..4d5d8d4 100644 --- a/refresh_database.py +++ b/refresh_database.py @@ -165,10 +165,15 @@ def manage_source_repo( branch: str, spec_path: str, include_all: bool, + source_commit: str = "", ) -> bool: """Clone or update an API spec source repository.""" print_info(f"Managing spec repository: {repo_url}") + if source_commit and not re.fullmatch(r"[0-9a-fA-F]{40}", source_commit): + print_error("source_commit must be a full 40-character hexadecimal Git SHA") + return False + specs_path = Path(specs_dir) # Handle fresh clone @@ -180,22 +185,21 @@ def manage_source_repo( if (specs_path / ".git").exists(): print_info(f"Updating existing spec repository in '{specs_dir}'...") - # Fetch latest - success, _ = run_command(["git", "fetch", "origin", branch], cwd=specs_dir) + revision = source_commit or branch + success, _ = run_command(["git", "fetch", "--depth", "1", "origin", revision], cwd=specs_dir) if not success: - print_error("Failed to fetch from remote") + print_error(f"Failed to fetch source revision: {revision}") return False - # Reset to latest - success, _ = run_command(["git", "reset", "--hard", f"origin/{branch}"], cwd=specs_dir) + target = source_commit or f"origin/{branch}" + checkout_cmd = ["git", "checkout", "--detach", target] if source_commit else ["git", "reset", "--hard", target] + success, _ = run_command(checkout_cmd, cwd=specs_dir) if not success: - print_error("Failed to reset to latest version") + print_error(f"Failed to check out source revision: {target}") return False - # Clean untracked files run_command(["git", "clean", "-fdx"], cwd=specs_dir) - - print_success("Repository updated to latest version") + print_success(f"Repository updated to {target}") else: print_info("Cloning spec repository (this may take a few minutes)...") @@ -223,13 +227,38 @@ def manage_source_repo( print_error("Failed to clone repository") return False + if source_commit: + success, _ = run_command( + ["git", "fetch", "--depth", "1", "origin", source_commit], + cwd=specs_dir, + ) + if not success: + print_error(f"Failed to fetch pinned source commit: {source_commit}") + return False + success, _ = run_command( + ["git", "checkout", "--detach", source_commit], + cwd=specs_dir, + ) + if not success: + print_error(f"Failed to check out pinned source commit: {source_commit}") + return False + print_success("Repository cloned successfully") + if source_commit: + success, head = run_command(["git", "rev-parse", "HEAD"], cwd=specs_dir, capture=True) + if not success or head.strip().lower() != source_commit.lower(): + print_error(f"Checked-out revision does not match pinned commit: {source_commit}") + return False + # Display stats spec_full_path = specs_path / spec_path if spec_full_path.exists(): - json_files = list(spec_full_path.rglob("*.json")) - print_info(f"Found {len(json_files)} JSON files in {spec_path}") + spec_files = [ + path for path in spec_full_path.rglob("*") + if path.is_file() and path.suffix.lower() in {".json", ".yaml", ".yml"} + ] + print_info(f"Found {len(spec_files)} JSON/YAML files in {spec_path}") return True @@ -511,6 +540,7 @@ def main(): database_dir = cfg.get("database_dir", _FALLBACK_SOURCE["database_dir"]) default_spec_path = cfg.get("default_spec_path", _FALLBACK_SOURCE["default_spec_path"]) branch = args.branch or cfg.get("source_branch", "main") + source_commit = "" if args.branch else str(cfg.get("source_commit", "")).strip() # Derive final spec path if args.all: @@ -542,6 +572,7 @@ def main(): print(f" - Database directory: {database_dir}") print(f" - Specification path: {spec_path}") print(f" - Branch: {branch}") + print(f" - Pinned commit: {source_commit or '(branch head)'}") print(f" - Fresh clone: {args.fresh}") print(f" - Skip DB build: {args.skip_db_build}") print() @@ -551,7 +582,15 @@ def main(): sys.exit(1) # Manage source repo - if not manage_source_repo(repo_url, specs_dir, args.fresh, branch, spec_path, args.all): + if not manage_source_repo( + repo_url, + specs_dir, + args.fresh, + branch, + spec_path, + args.all, + source_commit=source_commit, + ): sys.exit(1) # Build database if not skipped diff --git a/requirements.txt b/requirements.txt index 46e16d0..2fa7d5e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,3 +3,6 @@ # For rendering the SpeQL logo in ASCII art pyfiglet>=0.8.0 + +# Safe parsing of authoritative OpenAPI YAML sources such as Microsoft Graph +PyYAML>=6.0,<7.0 diff --git a/scripts/export/export_api_inventory.py b/scripts/export/export_api_inventory.py index 7c2b905..8f79482 100644 --- a/scripts/export/export_api_inventory.py +++ b/scripts/export/export_api_inventory.py @@ -2,7 +2,7 @@ """ export_api_inventory.py — SpecRecon API Inventory Export -Walks a directory of OpenAPI/Swagger JSON spec files, parses every operation, and +Walks a directory of OpenAPI/Swagger spec files, parses every operation, and produces a normalized api-index.json that can be used for "spec vs reality" comparison of REST API calls. @@ -14,10 +14,12 @@ python3 scripts/export/export_api_inventory.py [options] Options: - --source Path to the specifications directory (default: azure-rest-api-specs/specification) + --source-config Optional source config for path, provenance, and profile + --source Path to the specifications directory (default: config or azure-rest-api-specs/specification) --output-dir Directory where the output files are written (default: inventory/) --source-repo Upstream repository identifier recorded in metadata (e.g. Azure/azure-rest-api-specs) --source-branch Branch name recorded in metadata (default: main) + --source-profile Source-specific parsing profile (default: auto) --minified Also produce a minified api-index.min.json (no indentation) --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) @@ -41,6 +43,12 @@ import sys from datetime import datetime, timezone from pathlib import Path +from urllib.parse import urlsplit + +try: + import yaml +except ImportError: # pragma: no cover - exercised through dependency-failure tests + yaml = None # Allow running as a standalone script or as a package member _HERE = Path(__file__).parent @@ -80,6 +88,16 @@ _DEFAULT_SOURCE_REPO = "unknown" _DEFAULT_SOURCE_BRANCH = "main" +_SOURCE_PROFILE_AUTO = "auto" +_SOURCE_PROFILE_GENERIC = "generic" +_SOURCE_PROFILE_MICROSOFT_GRAPH = "microsoft-graph" +_MICROSOFT_GRAPH_SOURCE_REPO = "microsoftgraph/msgraph-metadata" +_MICROSOFT_GRAPH_PROVIDER_NAMESPACE = "Microsoft.Graph" +_MICROSOFT_GRAPH_OPENAPI_PATHS = frozenset({ + "v1.0/openapi.yaml", + "beta/openapi.yaml", +}) + # Directories whose contents should be skipped entirely _SKIP_DIRS = { "examples", @@ -163,15 +181,28 @@ def _should_skip_dir(dir_name: str) -> bool: return dir_name.lower() in _SKIP_DIRS -def discover_spec_files(source_dir: Path) -> list: - """Yield all JSON spec files under *source_dir*, skipping skip-listed dirs.""" +def discover_spec_files( + source_dir: Path, + include_yaml: bool = False, + allowed_relative_paths: set = None, +) -> list: + """Yield supported spec files under *source_dir*, skipping excluded dirs.""" + suffixes = {".json"} + if include_yaml: + suffixes.update({".yaml", ".yml"}) + spec_files = [] for root, dirs, files in os.walk(source_dir): # Prune directories in-place so os.walk doesn't descend into them dirs[:] = [d for d in dirs if not _should_skip_dir(d)] for fname in files: - if fname.endswith(".json"): - spec_files.append(Path(root) / fname) + candidate = Path(root) / fname + if candidate.suffix.lower() not in suffixes: + continue + relative = candidate.relative_to(source_dir).as_posix() + if allowed_relative_paths is not None and relative not in allowed_relative_paths: + continue + spec_files.append(candidate) return spec_files @@ -233,14 +264,79 @@ def _detect_host(spec: dict, file_path: Path) -> str: if servers and isinstance(servers, list): first_url = servers[0].get("url", "") if isinstance(servers[0], dict) else "" if first_url: - # Strip scheme and path to get just the host - stripped = first_url.split("//", 1)[-1].split("/")[0].strip() - if stripped: - return stripped.lower() + parsed = urlsplit(first_url) + if parsed.hostname: + return parsed.hostname.lower() return "unknown" +def _detect_server_base_path(spec: dict) -> str: + """Return a normalized base path from Swagger/OpenAPI server metadata.""" + base_path = spec.get("basePath", "") + if isinstance(base_path, str) and base_path.strip("/"): + return "/" + base_path.strip("/") + + servers = spec.get("servers", []) + if isinstance(servers, list) and servers and isinstance(servers[0], dict): + server_url = servers[0].get("url", "") + if isinstance(server_url, str): + path = urlsplit(server_url).path + if path and path != "/": + return "/" + path.strip("/") + return "" + + +def _join_server_path(base_path: str, path_template: str) -> str: + """Join a server base path and OpenAPI path without changing placeholders.""" + if not base_path: + return path_template + normalized_path = "/" + str(path_template or "").lstrip("/") + if normalized_path == base_path or normalized_path.startswith(base_path + "/"): + return normalized_path + return base_path.rstrip("/") + normalized_path + + +def _resolve_source_profile(source_profile: str, source_repo: str) -> str: + """Resolve an explicit or source-derived export profile.""" + profile = source_profile or _SOURCE_PROFILE_AUTO + if profile != _SOURCE_PROFILE_AUTO: + return profile + if str(source_repo or "").lower() == _MICROSOFT_GRAPH_SOURCE_REPO: + return _SOURCE_PROFILE_MICROSOFT_GRAPH + return _SOURCE_PROFILE_GENERIC + + +def _load_export_source_config(config_path: Path) -> dict: + """Load and validate an exporter source configuration file.""" + try: + with open(config_path, "r", encoding="utf-8") as fh: + config = json.load(fh) + except (OSError, json.JSONDecodeError) as exc: + raise ValueError(f"Cannot load source config {config_path}: {exc}") from exc + if not isinstance(config, dict): + raise ValueError(f"Source config must be a JSON object: {config_path}") + return config + + +def _load_spec_document(file_path: Path): + """Load a JSON or YAML spec document without resolving external content.""" + suffix = file_path.suffix.lower() + try: + with open(file_path, "r", encoding="utf-8", errors="replace") as fh: + if suffix in {".yaml", ".yml"}: + if yaml is None: + raise RuntimeError("PyYAML is required to parse OpenAPI YAML files") + return yaml.safe_load(fh) + return json.load(fh) + except json.JSONDecodeError as exc: + raise ValueError(f"JSON decode error in {file_path}: {exc}") from exc + except Exception as exc: + if yaml is not None and isinstance(exc, yaml.YAMLError): + raise ValueError(f"YAML decode error in {file_path}: {exc}") from exc + raise + + 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): @@ -561,6 +657,7 @@ def _parse_spec_file( source_dir: Path, verbose: bool, include_research_metadata: bool = False, + source_profile: str = _SOURCE_PROFILE_GENERIC, ) -> tuple: """Parse a single spec file and return (list_of_operations, error_or_None). @@ -574,12 +671,9 @@ def _parse_spec_file( rel_path = file_path try: - with open(file_path, "r", encoding="utf-8", errors="replace") as fh: - spec = json.load(fh) - except json.JSONDecodeError as exc: - return [], f"JSON decode error in {file_path}: {exc}" - except OSError as exc: - return [], f"Cannot read {file_path}: {exc}" + spec = _load_spec_document(file_path) + except (OSError, ValueError, RuntimeError) as exc: + return [], str(exc) if not isinstance(spec, dict): return [], None # Not a spec object — skip silently @@ -591,6 +685,11 @@ def _parse_spec_file( return [], None # Not a recognized OpenAPI spec — skip host = _detect_host(spec, file_path) + server_base_path = ( + _detect_server_base_path(spec) + if source_profile == _SOURCE_PROFILE_MICROSOFT_GRAPH + else "" + ) api_version_from_path = extract_api_version_from_path(str(file_path)) api_version_from_info = spec.get("info", {}).get("version", "") api_version = api_version_from_path if api_version_from_path != "unknown" else api_version_from_info @@ -609,10 +708,15 @@ def _parse_spec_file( # "paths" | "x-ms-paths" | "other" — recorded as provenance in each op entry source_kind = detect_source_kind(paths_block_key) - for path_template, path_item in paths_obj.items(): + for raw_path_template, path_item in paths_obj.items(): if not isinstance(path_item, dict): continue + path_template = ( + _join_server_path(server_base_path, raw_path_template) + if source_profile == _SOURCE_PROFILE_MICROSOFT_GRAPH + else raw_path_template + ) http_methods = ["get", "put", "post", "delete", "options", "head", "patch", "trace"] for method_lower in http_methods: operation = path_item.get(method_lower) @@ -640,6 +744,8 @@ def _parse_spec_file( "is_preview": preview, "lookup_key": lookup_key, } + if source_profile == _SOURCE_PROFILE_MICROSOFT_GRAPH: + entry["_provider_namespace"] = _MICROSOFT_GRAPH_PROVIDER_NAMESPACE if include_research_metadata: entry["_research_metadata"] = _operation_research_metadata(path_item, operation, spec) operations.append(entry) @@ -657,7 +763,7 @@ def _parse_spec_file( def _build_summary(operations: list, spec_file_count: int, error_count: int) -> dict: provider_set = set() for op in operations: - ns = extract_provider_namespace(op["path_template"]) + ns = op.get("_provider_namespace") or extract_provider_namespace(op["path_template"]) if ns != "unknown": provider_set.add(ns) providers = sorted(provider_set) @@ -855,7 +961,7 @@ def _build_grouped_index(flat_ops: list) -> dict: host = op["host"] method = op["method"] path_template = op["path_template"] - provider_ns = extract_provider_namespace(path_template) + provider_ns = op.get("_provider_namespace") or extract_provider_namespace(path_template) route_key = f"{method} {normalize_path_template_for_key(path_template)}" # Navigate / create the nested slots @@ -1067,6 +1173,7 @@ def run_export( sharded: bool = False, source_repo: str = "", source_branch: str = "", + source_profile: str = _SOURCE_PROFILE_AUTO, ) -> int: """Execute the full export pipeline. Returns an exit code (0 = success). @@ -1081,6 +1188,8 @@ def run_export( metadata). Auto-detected from git when empty. source_branch: Branch name used to clone the source repo (recorded in metadata). Defaults to "main" when empty. + source_profile: Source-specific deterministic parsing profile. "auto" + selects Microsoft Graph only for its official repository. """ print(f"[SpecRecon] Starting API inventory export") @@ -1102,6 +1211,8 @@ def run_export( source_repo = _detect_source_repo(source_dir) resolved_source_branch = source_branch or _DEFAULT_SOURCE_BRANCH + resolved_source_profile = _resolve_source_profile(source_profile, source_repo) + print(f"[SpecRecon] Profile: {resolved_source_profile}") metadata = { "generated_at": generated_at, @@ -1116,8 +1227,13 @@ def run_export( # Discover spec files print(f"[SpecRecon] Scanning spec files …") - spec_files = discover_spec_files(source_dir) - print(f"[SpecRecon] Found {len(spec_files)} JSON files to inspect") + is_graph_profile = resolved_source_profile == _SOURCE_PROFILE_MICROSOFT_GRAPH + spec_files = discover_spec_files( + source_dir, + include_yaml=is_graph_profile, + allowed_relative_paths=set(_MICROSOFT_GRAPH_OPENAPI_PATHS) if is_graph_profile else None, + ) + print(f"[SpecRecon] Found {len(spec_files)} spec files to inspect") all_operations = [] errors = [] @@ -1130,6 +1246,7 @@ def run_export( source_dir, verbose, include_research_metadata=grouped or sharded, + source_profile=resolved_source_profile, ) if err: errors.append(err) @@ -1228,10 +1345,16 @@ def _build_parser() -> argparse.ArgumentParser: ), formatter_class=argparse.RawDescriptionHelpFormatter, ) + parser.add_argument( + "--source-config", + default="", + metavar="PATH", + help="Optional source config used to derive source path, provenance, and export profile", + ) parser.add_argument( "--source", - default="azure-rest-api-specs/specification", - help="Path to the specifications directory (default: azure-rest-api-specs/specification)", + default="", + help="Path to the specifications directory (default: source config or azure-rest-api-specs/specification)", ) parser.add_argument( "--output-dir", @@ -1257,6 +1380,19 @@ def _build_parser() -> argparse.ArgumentParser: "Defaults to 'main' when omitted." ), ) + parser.add_argument( + "--source-profile", + choices=[ + _SOURCE_PROFILE_AUTO, + _SOURCE_PROFILE_GENERIC, + _SOURCE_PROFILE_MICROSOFT_GRAPH, + ], + default=_SOURCE_PROFILE_AUTO, + help=( + "Source-specific parsing profile. 'auto' selects microsoft-graph " + "only for source_repo microsoftgraph/msgraph-metadata." + ), + ) parser.add_argument( "--minified", action="store_true", @@ -1292,8 +1428,37 @@ def main(): parser = _build_parser() args = parser.parse_args() - source_dir = Path(args.source).expanduser().resolve() + config = {} + if args.source_config: + try: + config = _load_export_source_config(Path(args.source_config).expanduser()) + except ValueError as exc: + parser.error(str(exc)) + + configured_source = "" + if config: + specs_dir = str(config.get("specs_dir", "")).strip() + spec_path = str( + config.get("export_spec_path", config.get("default_spec_path", "")) + ).strip() + if specs_dir: + configured_source = str(Path(specs_dir) / spec_path) if spec_path else specs_dir + + source_dir = Path( + args.source or configured_source or "azure-rest-api-specs/specification" + ).expanduser().resolve() output_dir = Path(args.output_dir).expanduser().resolve() + source_repo = args.source_repo or str(config.get("source_repo", "")) + source_branch = args.source_branch or str(config.get("source_branch", "")) + source_profile = args.source_profile + if source_profile == _SOURCE_PROFILE_AUTO and config.get("export_profile"): + source_profile = str(config["export_profile"]) + if source_profile not in { + _SOURCE_PROFILE_AUTO, + _SOURCE_PROFILE_GENERIC, + _SOURCE_PROFILE_MICROSOFT_GRAPH, + }: + parser.error(f"Unsupported export_profile in source config: {source_profile}") sys.exit(run_export( source_dir, @@ -1302,8 +1467,9 @@ def main(): args.verbose, args.grouped, args.sharded, - source_repo=args.source_repo, - source_branch=args.source_branch, + source_repo=source_repo, + source_branch=source_branch, + source_profile=source_profile, )) diff --git a/scripts/export/hash_inventory.py b/scripts/export/hash_inventory.py new file mode 100644 index 0000000..404938a --- /dev/null +++ b/scripts/export/hash_inventory.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Compute a deterministic semantic hash for generated API inventory output.""" + +import argparse +import hashlib +import json +from pathlib import Path + + +_VOLATILE_METADATA_FIELDS = frozenset({"generated_at"}) + + +def _canonical_payload(path: Path) -> bytes: + with open(path, "r", encoding="utf-8") as handle: + payload = json.load(handle) + metadata = payload.get("metadata") + if isinstance(metadata, dict): + for field in _VOLATILE_METADATA_FIELDS: + metadata.pop(field, None) + return json.dumps( + payload, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + ).encode("utf-8") + + +def inventory_files(inventory_dir: Path, export_format: str) -> list[Path]: + if export_format == "grouped": + minified = inventory_dir / "api-index-grouped.min.json" + pretty = inventory_dir / "api-index-grouped.json" + if minified.is_file(): + return [minified] + if pretty.is_file(): + return [pretty] + raise FileNotFoundError("grouped inventory output not found") + + shards_dir = inventory_dir / "shards" + minified_shards = sorted(shards_dir.glob("*.min.json")) + if minified_shards: + return minified_shards + pretty_shards = sorted( + path for path in shards_dir.glob("*.json") + if not path.name.endswith(".min.json") + ) + if pretty_shards: + return pretty_shards + raise FileNotFoundError("sharded inventory output not found") + + +def compute_inventory_hash(inventory_dir: Path, export_format: str) -> str: + digest = hashlib.sha256() + for path in inventory_files(inventory_dir, export_format): + relative = path.relative_to(inventory_dir).as_posix().encode("utf-8") + payload_digest = hashlib.sha256(_canonical_payload(path)).digest() + digest.update(relative) + digest.update(b"\0") + digest.update(payload_digest) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--inventory-dir", default="inventory", type=Path) + parser.add_argument("--format", choices=["grouped", "sharded"], required=True) + args = parser.parse_args() + print(compute_inventory_hash(args.inventory_dir, args.format)) + + +if __name__ == "__main__": + main() diff --git a/scripts/export/normalize_api_inventory.py b/scripts/export/normalize_api_inventory.py index fa68a1d..4292a21 100644 --- a/scripts/export/normalize_api_inventory.py +++ b/scripts/export/normalize_api_inventory.py @@ -76,6 +76,10 @@ def extract_resource_provider_family(path_template: str) -> str: "management.core.windows.net", } +_DATA_HOSTS = { + "graph.microsoft.com", +} + def classify_plane(host: str, path_template: str) -> str: """Return ``"management"``, ``"data"``, or ``"unknown"`` for an operation. @@ -92,6 +96,8 @@ def classify_plane(host: str, path_template: str) -> str: if host_lower in _MANAGEMENT_HOSTS: return "management" + if host_lower in _DATA_HOSTS: + return "data" if host_lower: # Known data-plane host suffixes @@ -128,7 +134,7 @@ def classify_plane(host: str, path_template: str) -> str: # Stability classification # --------------------------------------------------------------------------- -_PREVIEW_VERSION_RE = re.compile(r"preview", re.IGNORECASE) +_PREVIEW_VERSION_RE = re.compile(r"(?:preview|beta|alpha)", re.IGNORECASE) def is_preview_version(api_version: str) -> bool: diff --git a/tests/test_api_inventory_export.py b/tests/test_api_inventory_export.py index 10609f6..cc49394 100644 --- a/tests/test_api_inventory_export.py +++ b/tests/test_api_inventory_export.py @@ -9,6 +9,8 @@ import tempfile from pathlib import Path +import pytest + # Make the export package importable when running from the repo root _EXPORT_DIR = Path(__file__).parent.parent / "scripts" / "export" sys.path.insert(0, str(_EXPORT_DIR)) @@ -27,6 +29,23 @@ def _write_spec(directory: Path, filename: str, spec_obj: dict) -> Path: return p +def _write_yaml_spec(directory: Path, filename: str, spec_obj: dict) -> Path: + """Write a spec dict as YAML into *directory* and return the Path.""" + p = directory / filename + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(exp.yaml.safe_dump(spec_obj, sort_keys=False), encoding="utf-8") + return p + + +def _minimal_graph_openapi(version: str, paths: dict) -> dict: + return { + "openapi": "3.0.4", + "info": {"title": "Microsoft Graph", "version": version}, + "servers": [{"url": f"https://graph.microsoft.com/{version}"}], + "paths": paths, + } + + def _minimal_swagger(paths: dict = None, x_ms_paths: dict = None) -> dict: """Return a minimal valid Swagger 2.0 document.""" doc = { @@ -51,6 +70,35 @@ def test_module_importable(self): def test_run_export_callable(self): assert callable(exp.run_export) + def test_export_source_config_loaded(self, tmp_path): + config_path = tmp_path / "source.json" + config_path.write_text(json.dumps({ + "source_repo": "microsoftgraph/msgraph-metadata", + "export_profile": "microsoft-graph", + })) + config = exp._load_export_source_config(config_path) + assert config["export_profile"] == "microsoft-graph" + + def test_invalid_export_source_config_rejected(self, tmp_path): + config_path = tmp_path / "source.json" + config_path.write_text("[not-json", encoding="utf-8") + with pytest.raises(ValueError, match="Cannot load source config"): + exp._load_export_source_config(config_path) + + def test_registered_graph_source_is_pinned(self): + config_path = Path(__file__).parent.parent / "config" / "sources" / "microsoft-graph.json" + config = exp._load_export_source_config(config_path) + assert config["source_repo"] == "microsoftgraph/msgraph-metadata" + assert config["source_commit"] == "b8cbef92f6959dca8150bf3edcc650863765e529" + assert config["export_profile"] == "microsoft-graph" + assert config["export_spec_path"] == "openapi" + + def test_registered_azure_source_preserves_full_export_scope(self): + config_path = Path(__file__).parent.parent / "config" / "sources" / "azure.json" + config = exp._load_export_source_config(config_path) + assert config["default_spec_path"] == "specification/logic" + assert config["export_spec_path"] == "specification" + # --------------------------------------------------------------------------- # discover_spec_files @@ -71,9 +119,35 @@ def test_skips_examples_directory(self, tmp_path): def test_skips_non_json_files(self, tmp_path): (tmp_path / "readme.md").write_text("# hello") + (tmp_path / "graph.yaml").write_text("openapi: 3.0.4") files = exp.discover_spec_files(tmp_path) assert not any(f.suffix != ".json" for f in files) + def test_graph_profile_discovers_yaml(self, tmp_path): + (tmp_path / "graph.yaml").write_text("openapi: 3.0.4") + files = exp.discover_spec_files(tmp_path, include_yaml=True) + assert [f.name for f in files] == ["graph.yaml"] + + def test_graph_profile_limits_ingestion_to_canonical_openapi_files(self, tmp_path): + for relative in ( + "v1.0/openapi.yaml", + "beta/openapi.yaml", + "v1.0/default.yaml", + "beta/powershell_v2.yaml", + ): + path = tmp_path / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("openapi: 3.0.4") + files = exp.discover_spec_files( + tmp_path, + include_yaml=True, + allowed_relative_paths=set(exp._MICROSOFT_GRAPH_OPENAPI_PATHS), + ) + assert {path.relative_to(tmp_path).as_posix() for path in files} == { + "v1.0/openapi.yaml", + "beta/openapi.yaml", + } + # --------------------------------------------------------------------------- # _parse_spec_file @@ -172,6 +246,116 @@ def test_openapi3_spec_parsed(self, tmp_path): assert ops[0]["host"] == "management.azure.com" +# --------------------------------------------------------------------------- +# Microsoft Graph OpenAPI profile +# --------------------------------------------------------------------------- + +class TestMicrosoftGraphProfile: + def test_profile_auto_selected_only_for_official_source(self): + assert exp._resolve_source_profile("auto", "microsoftgraph/msgraph-metadata") == "microsoft-graph" + assert exp._resolve_source_profile("auto", "Example/other") == "generic" + assert exp._resolve_source_profile("generic", "microsoftgraph/msgraph-metadata") == "generic" + + def test_v1_yaml_uses_server_prefix_and_fixed_provider(self, tmp_path): + spec = _minimal_graph_openapi("v1.0", { + "/users/{user-id}": { + "get": { + "operationId": "users.user.GetUser", + "parameters": [ + {"name": "$select", "in": "query", "required": False}, + {"name": "user-id", "in": "path", "required": True}, + ], + "responses": {"200": {"description": "OK"}}, + } + } + }) + path = _write_yaml_spec(tmp_path, "openapi.yaml", spec) + ops, err = exp._parse_spec_file( + path, + tmp_path, + verbose=False, + include_research_metadata=True, + source_profile="microsoft-graph", + ) + assert err is None + assert len(ops) == 1 + operation = ops[0] + assert operation["host"] == "graph.microsoft.com" + assert operation["path_template"] == "/v1.0/users/{user-id}" + assert operation["api_versions"] == ["v1.0"] + assert operation["plane"] == "data" + assert operation["is_preview"] is False + assert operation["_provider_namespace"] == "Microsoft.Graph" + assert operation["_research_metadata"]["parameters"]["query"] == ["$select"] + + def test_beta_yaml_is_preview(self, tmp_path): + spec = _minimal_graph_openapi("beta", { + "/groups": { + "get": {"operationId": "groups.ListGroups", "responses": {"200": {}}} + } + }) + path = _write_yaml_spec(tmp_path, "openapi.yaml", spec) + ops, err = exp._parse_spec_file( + path, + tmp_path, + verbose=False, + source_profile="microsoft-graph", + ) + assert err is None + assert ops[0]["path_template"] == "/beta/groups" + assert ops[0]["is_preview"] is True + + def test_yaml_dependency_failure_is_clear(self, tmp_path, monkeypatch): + path = tmp_path / "openapi.yaml" + path.write_text("openapi: 3.0.4", encoding="utf-8") + monkeypatch.setattr(exp, "yaml", None) + ops, err = exp._parse_spec_file( + path, + tmp_path, + verbose=False, + source_profile="microsoft-graph", + ) + assert ops == [] + assert "PyYAML is required" in err + + def test_graph_export_writes_single_compatible_shard(self, tmp_path): + source = tmp_path / "openapi" + v1 = _minimal_graph_openapi("v1.0", { + "/users/{user-id}": { + "get": {"operationId": "users.user.GetUser", "responses": {"200": {}}} + } + }) + beta = _minimal_graph_openapi("beta", { + "/groups": { + "get": {"operationId": "groups.ListGroups", "responses": {"200": {}}} + } + }) + _write_yaml_spec(source / "v1.0", "openapi.yaml", v1) + _write_yaml_spec(source / "beta", "openapi.yaml", beta) + output = tmp_path / "inventory" + + result = exp.run_export( + source, + output, + minified=True, + verbose=False, + grouped=True, + sharded=True, + source_repo="microsoftgraph/msgraph-metadata", + source_branch="master", + ) + + assert result == 0 + shard = json.loads((output / "shards" / "Microsoft.Graph.json").read_text()) + assert shard["provider_namespace"] == "Microsoft.Graph" + assert set(shard["hosts"]) == {"graph.microsoft.com"} + routes = shard["hosts"]["graph.microsoft.com"]["routes"] + assert "GET /v1.0/users/{name}" in routes + assert "GET /beta/groups" in routes + assert not (output / "shards" / "unknown.json").exists() + assert shard["metadata"]["source_repo"] == "microsoftgraph/msgraph-metadata" + + # --------------------------------------------------------------------------- # Metadata block # --------------------------------------------------------------------------- diff --git a/tests/test_api_inventory_normalization.py b/tests/test_api_inventory_normalization.py index ab2be28..015e6b0 100644 --- a/tests/test_api_inventory_normalization.py +++ b/tests/test_api_inventory_normalization.py @@ -108,6 +108,10 @@ def test_vault_data(self): result = norm.classify_plane("myvault.vault.azure.net", "/secrets/{name}") assert result == "data" + def test_microsoft_graph_data(self): + result = norm.classify_plane("graph.microsoft.com", "/v1.0/users") + assert result == "data" + def test_providers_path_heuristic(self): # No host but path contains /providers/ result = norm.classify_plane("", "/subscriptions/{sub}/providers/Microsoft.Storage/storageAccounts") @@ -159,6 +163,12 @@ def test_preview_suffix(self): def test_privatepreview(self): assert norm.is_preview_version("2023-01-01-privatepreview") is True + def test_graph_beta(self): + assert norm.is_preview_version("beta") is True + + def test_alpha(self): + assert norm.is_preview_version("alpha") is True + def test_stable_date(self): assert norm.is_preview_version("2023-01-01") is False diff --git a/tests/test_inventory_hash.py b/tests/test_inventory_hash.py new file mode 100644 index 0000000..4a2d74f --- /dev/null +++ b/tests/test_inventory_hash.py @@ -0,0 +1,73 @@ +"""Tests for semantic inventory hashing used by export workflows.""" + +import json +import sys +from pathlib import Path + +_EXPORT_DIR = Path(__file__).parent.parent / "scripts" / "export" +sys.path.insert(0, str(_EXPORT_DIR)) + +import hash_inventory + + +def _write(path: Path, payload: dict) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload), encoding="utf-8") + + +def _payload(generated_at: str, route: str = "GET /things") -> dict: + return { + "metadata": { + "generated_at": generated_at, + "source_commit": "abc123", + "schema_version": "3.2.0", + }, + "providers": { + "Example.Service": { + "hosts": { + "api.example.com": { + "routes": {route: {"method": "GET"}}, + } + } + } + }, + } + + +def test_grouped_hash_ignores_generated_timestamp(tmp_path): + output = tmp_path / "inventory" + path = output / "api-index-grouped.min.json" + _write(path, _payload("2026-09-20T01:00:00Z")) + first = hash_inventory.compute_inventory_hash(output, "grouped") + _write(path, _payload("2026-09-20T02:00:00Z")) + second = hash_inventory.compute_inventory_hash(output, "grouped") + assert first == second + + +def test_grouped_hash_changes_with_semantic_content(tmp_path): + output = tmp_path / "inventory" + path = output / "api-index-grouped.min.json" + _write(path, _payload("2026-09-20T01:00:00Z")) + first = hash_inventory.compute_inventory_hash(output, "grouped") + _write(path, _payload("2026-09-20T01:00:00Z", route="GET /other")) + second = hash_inventory.compute_inventory_hash(output, "grouped") + assert first != second + + +def test_sharded_hash_is_stable_across_file_creation_order(tmp_path): + first_dir = tmp_path / "first" + second_dir = tmp_path / "second" + _write(first_dir / "shards" / "B.min.json", _payload("2026-09-20T01:00:00Z", "GET /b")) + _write(first_dir / "shards" / "A.min.json", _payload("2026-09-20T01:00:00Z", "GET /a")) + _write(second_dir / "shards" / "A.min.json", _payload("2026-09-21T01:00:00Z", "GET /a")) + _write(second_dir / "shards" / "B.min.json", _payload("2026-09-21T01:00:00Z", "GET /b")) + assert hash_inventory.compute_inventory_hash(first_dir, "sharded") == hash_inventory.compute_inventory_hash(second_dir, "sharded") + + +def test_sharded_hash_changes_when_file_set_changes(tmp_path): + output = tmp_path / "inventory" + _write(output / "shards" / "A.min.json", _payload("2026-09-20T01:00:00Z", "GET /a")) + first = hash_inventory.compute_inventory_hash(output, "sharded") + _write(output / "shards" / "B.min.json", _payload("2026-09-20T01:00:00Z", "GET /b")) + second = hash_inventory.compute_inventory_hash(output, "sharded") + assert first != second diff --git a/tests/test_refresh_database.py b/tests/test_refresh_database.py new file mode 100644 index 0000000..df95b02 --- /dev/null +++ b/tests/test_refresh_database.py @@ -0,0 +1,90 @@ +"""Tests for source-repository revision pinning.""" + +import refresh_database as refresh + + +def test_manage_source_repo_checks_out_pinned_commit(tmp_path, monkeypatch): + repo = tmp_path / "source" + (repo / ".git").mkdir(parents=True) + calls = [] + pinned = "0123456789abcdef0123456789abcdef01234567" + + def fake_run(command, cwd=None, capture=False): + calls.append((command, cwd)) + return True, pinned + "\n" if command == ["git", "rev-parse", "HEAD"] else "" + + monkeypatch.setattr(refresh, "run_command", fake_run) + + assert refresh.manage_source_repo( + repo_url="https://github.com/example/source.git", + specs_dir=str(repo), + fresh=False, + branch="main", + spec_path="openapi", + include_all=True, + source_commit=pinned, + ) + + commands = [command for command, _cwd in calls] + assert ["git", "fetch", "--depth", "1", "origin", "0123456789abcdef0123456789abcdef01234567"] in commands + assert ["git", "checkout", "--detach", "0123456789abcdef0123456789abcdef01234567"] in commands + assert not any(command[:3] == ["git", "reset", "--hard"] for command in commands) + + +def test_manage_source_repo_rejects_invalid_commit_pin(tmp_path): + assert not refresh.manage_source_repo( + repo_url="https://github.com/example/source.git", + specs_dir=str(tmp_path / "source"), + fresh=False, + branch="main", + spec_path="openapi", + include_all=True, + source_commit="not-a-full-sha", + ) + + +def test_manage_source_repo_rejects_mismatched_pinned_commit(tmp_path, monkeypatch): + repo = tmp_path / "source" + (repo / ".git").mkdir(parents=True) + + def fake_run(command, cwd=None, capture=False): + if command == ["git", "rev-parse", "HEAD"]: + return True, "ffffffffffffffffffffffffffffffffffffffff\n" + return True, "" + + monkeypatch.setattr(refresh, "run_command", fake_run) + + assert not refresh.manage_source_repo( + repo_url="https://github.com/example/source.git", + specs_dir=str(repo), + fresh=False, + branch="main", + spec_path="openapi", + include_all=True, + source_commit="0123456789abcdef0123456789abcdef01234567", + ) + + +def test_manage_source_repo_uses_branch_without_pin(tmp_path, monkeypatch): + repo = tmp_path / "source" + (repo / ".git").mkdir(parents=True) + calls = [] + + def fake_run(command, cwd=None, capture=False): + calls.append((command, cwd)) + return True, "" + + monkeypatch.setattr(refresh, "run_command", fake_run) + + assert refresh.manage_source_repo( + repo_url="https://github.com/example/source.git", + specs_dir=str(repo), + fresh=False, + branch="main", + spec_path="specification", + include_all=True, + ) + + commands = [command for command, _cwd in calls] + assert ["git", "fetch", "--depth", "1", "origin", "main"] in commands + assert ["git", "reset", "--hard", "origin/main"] in commands From 15be16f0d2c0bfc7c7092be1c58b8b74849262c6 Mon Sep 17 00:00:00 2001 From: goldjg Date: Sun, 20 Sep 2026 18:58:53 +0100 Subject: [PATCH 2/3] Harden export publication deduplication Serialize per-source exports, gate APISpy publication by source configuration, and use a stable release asset to prevent duplicate or stale publication races. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/carl/current-pr-contract.md | 3 +- .github/carl/memory.md | 2 +- .../daily-api-index-export-sharded.yml | 28 ++++++++++++++----- .github/workflows/daily-api-index-export.yml | 4 +++ README.md | 4 +-- config/sources/azure.json | 1 + config/sources/microsoft-graph.json | 1 + docs/ADDING_API_SOURCES.md | 1 + docs/QUICK_REFERENCE.md | 6 ++-- docs/REPOSITORY_STRUCTURE.md | 2 +- docs/inventory/EXPORT_PIPELINE.md | 7 +++-- 11 files changed, 42 insertions(+), 17 deletions(-) diff --git a/.github/carl/current-pr-contract.md b/.github/carl/current-pr-contract.md index 2c7b058..a26f5c1 100644 --- a/.github/carl/current-pr-contract.md +++ b/.github/carl/current-pr-contract.md @@ -41,7 +41,8 @@ The following constraints from this PR are promoted to durable invariants and mu - Add focused fixtures/tests, source and export documentation, and durable cARL notes. - Generate a local ignored candidate export for validation; do not commit it. - Compute a semantic content hash that excludes volatile `generated_at` metadata. -- Restore the last changed-export hash from a tiny Actions cache and upload export artifacts, publish releases, and dispatch APISpy updates only when semantic content changed. +- Restore the last changed-export hash from a tiny Actions cache and upload export artifacts only when semantic content changed. +- Serialize per-source workflow runs to prevent duplicate publication races; only sources explicitly configured for APISpy publication may replace the stable release asset and dispatch updates. ## Intentional amendments - Supersedes the completed SpecQL 3.2.0 family/lineage phase. diff --git a/.github/carl/memory.md b/.github/carl/memory.md index b72a35e..537e815 100644 --- a/.github/carl/memory.md +++ b/.github/carl/memory.md @@ -73,7 +73,7 @@ Refresh scripts accept `--source-config config/sources/.json` to suppo - Minified variants (`*.min.json`) with `--minified` - Packaged sharded export ZIPs for release publication -Published to UndREST-APISpy via GitHub Releases. Export workflows compute semantic SHA-256 hashes with volatile `generated_at` metadata removed and only upload artifacts, replace the shard release, or dispatch APISpy when content changed; a tiny Actions cache stores the last changed hash. +Published to UndREST-APISpy via a stable GitHub Release asset only for sources with `publish_to_apispy: true`. Export workflows serialize per-source runs, compute semantic SHA-256 hashes with volatile `generated_at` removed, and only upload artifacts, replace the release, or dispatch APISpy when content changed; a tiny Actions cache stores the last changed hash. ### GitHub Actions workflows diff --git a/.github/workflows/daily-api-index-export-sharded.yml b/.github/workflows/daily-api-index-export-sharded.yml index 277c30d..a10d2bb 100644 --- a/.github/workflows/daily-api-index-export-sharded.yml +++ b/.github/workflows/daily-api-index-export-sharded.yml @@ -16,6 +16,10 @@ on: required: false default: '' +concurrency: + group: inventory-sharded-${{ github.event.inputs.source_config || 'config/sources/azure.json' }} + cancel-in-progress: false + jobs: export-api-index-sharded: runs-on: ubuntu-latest @@ -44,9 +48,13 @@ jobs: SOURCE_ID=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('id','unknown'))") SPECS_DIR=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('specs_dir','azure-rest-api-specs'))") SOURCE_REPO=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('source_repo','unknown'))") + SOURCE_NAME=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('name', cfg.get('id','unknown')))") + PUBLISH_TO_APISPY=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(str(bool(cfg.get('publish_to_apispy', False))).lower())") echo "source_id=${SOURCE_ID}" >> "$GITHUB_OUTPUT" echo "specs_dir=${SPECS_DIR}" >> "$GITHUB_OUTPUT" echo "source_repo=${SOURCE_REPO}" >> "$GITHUB_OUTPUT" + echo "source_name=${SOURCE_NAME}" >> "$GITHUB_OUTPUT" + echo "publish_to_apispy=${PUBLISH_TO_APISPY}" >> "$GITHUB_OUTPUT" - name: Clone / update spec repository run: | @@ -105,13 +113,13 @@ jobs: fi - name: Package changed shard export - if: steps.content.outputs.changed == 'true' + if: steps.content.outputs.changed == 'true' && steps.source.outputs.publish_to_apispy == 'true' run: | cd inventory - zip -q -r "api-index-sharded-${{ github.run_id }}.zip" shards/ + zip -q -r "api-index-sharded.zip" shards/ - name: Publish shards to GitHub Release - if: steps.content.outputs.changed == 'true' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') + if: steps.content.outputs.changed == 'true' && steps.source.outputs.publish_to_apispy == 'true' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | @@ -121,16 +129,16 @@ jobs: # Create release if it doesn't exist, then upload/overwrite assets if gh release view shards-latest > /dev/null 2>&1; then - gh release upload shards-latest inventory/api-index-sharded-*.zip --clobber + gh release upload shards-latest inventory/api-index-sharded.zip --clobber else - gh release create shards-latest inventory/api-index-sharded-*.zip \ + gh release create shards-latest inventory/api-index-sharded.zip \ --title "Latest API Shards" \ --notes "$NOTES" \ --latest fi - name: Trigger APISpy shard update - if: steps.content.outputs.changed == 'true' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') + if: steps.content.outputs.changed == 'true' && steps.source.outputs.publish_to_apispy == 'true' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') run: | curl -X POST \ -H "Authorization: Bearer ${{ secrets.APISPY_DISPATCH_TOKEN }}" \ @@ -143,6 +151,10 @@ jobs: "client_payload": { "run_id": "${{ github.run_id }}", "tag": "shards-latest", + "source_id": "${{ steps.source.outputs.source_id }}", + "pack_id": "${{ steps.source.outputs.source_id }}", + "pack_name": "${{ steps.source.outputs.source_name }}", + "platform": "azure", "triggered_by": "${{ github.event_name }}" } }' @@ -152,7 +164,9 @@ jobs: uses: actions/upload-artifact@v4 with: name: api-index-sharded-${{ github.run_id }} - path: inventory/ + path: | + inventory/ + !inventory/api-index-sharded.zip retention-days: 2 - name: Save changed-export hash diff --git a/.github/workflows/daily-api-index-export.yml b/.github/workflows/daily-api-index-export.yml index 22cf0f4..8493da6 100644 --- a/.github/workflows/daily-api-index-export.yml +++ b/.github/workflows/daily-api-index-export.yml @@ -16,6 +16,10 @@ on: required: false default: '' +concurrency: + group: inventory-grouped-${{ github.event.inputs.source_config || 'config/sources/azure.json' }} + cancel-in-progress: false + jobs: export-api-index: runs-on: ubuntu-latest diff --git a/README.md b/README.md index 6a0411d..10ff129 100644 --- a/README.md +++ b/README.md @@ -205,7 +205,7 @@ UndREST-SpecQL/ │ ├── CONSUMER_GUIDE.md │ └── EXPORT_PIPELINE.md ├── inventory/ # Export artifacts (generated) -│ └── api-index-sharded-.zip +│ └── api-index-sharded.zip ├── queries/ # CodeQL queries — one subdirectory per platform │ ├── README.md # How to add queries for a new platform │ └── azure-security/ @@ -434,7 +434,7 @@ python3 scripts/export/export_api_inventory.py \ - `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 and computes a semantic content hash with volatile generation timestamps removed. It publishes the sharded zip, stores an Actions artifact, and triggers [UndREST-APISpy](https://github.com/UndREST-Labs/UndREST-APISpy) only when the export differs from the last changed export. The grouped workflow applies the same deduplication before artifact upload. +**Cross-repo pipeline:** The `daily-api-index-export-sharded.yml` workflow runs nightly and computes a semantic content hash with volatile generation timestamps removed. Per-source runs are serialized to prevent duplicate publication races. For sources explicitly configured with `publish_to_apispy: true`, it replaces the stable sharded release asset and triggers [UndREST-APISpy](https://github.com/UndREST-Labs/UndREST-APISpy) only when the export differs from the last changed export. The grouped workflow applies the same deduplication before artifact upload. See [docs/inventory/EXPORT_PIPELINE.md](docs/inventory/EXPORT_PIPELINE.md) for the full schema and consumer guide. diff --git a/config/sources/azure.json b/config/sources/azure.json index 2cea999..7f02d94 100644 --- a/config/sources/azure.json +++ b/config/sources/azure.json @@ -8,6 +8,7 @@ "export_spec_path": "specification", "source_repo": "Azure/azure-rest-api-specs", "source_branch": "main", + "publish_to_apispy": true, "query_packs": [ "queries/azure-security" ] diff --git a/config/sources/microsoft-graph.json b/config/sources/microsoft-graph.json index 39b755c..d32b3a3 100644 --- a/config/sources/microsoft-graph.json +++ b/config/sources/microsoft-graph.json @@ -9,6 +9,7 @@ "source_repo": "microsoftgraph/msgraph-metadata", "source_branch": "master", "source_commit": "b8cbef92f6959dca8150bf3edcc650863765e529", + "publish_to_apispy": false, "export_profile": "microsoft-graph", "query_packs": [] } diff --git a/docs/ADDING_API_SOURCES.md b/docs/ADDING_API_SOURCES.md index 07dd69d..8425f1a 100644 --- a/docs/ADDING_API_SOURCES.md +++ b/docs/ADDING_API_SOURCES.md @@ -59,6 +59,7 @@ Source configs live in `config/sources/` and follow this schema: | `database_dir` | Yes | — | Where to write the CodeQL database | | `default_spec_path` | Yes | — | Default subdirectory within `specs_dir` to index | | `export_spec_path` | No | `default_spec_path` | Default export scope; use this to preserve a narrower interactive/database default | +| `publish_to_apispy` | No | `false` | Allow the sharded workflow to replace the shared APISpy release and dispatch an update | | `source_repo` | No | `"unknown"` | `org/repo` identifier recorded in export metadata | | `source_branch` | No | `"main"` | Branch name recorded in export metadata | | `source_commit` | No | branch head | Exact full commit SHA to fetch, check out detached, and verify for reproducible acquisition | diff --git a/docs/QUICK_REFERENCE.md b/docs/QUICK_REFERENCE.md index 9d80e37..a4afcfa 100644 --- a/docs/QUICK_REFERENCE.md +++ b/docs/QUICK_REFERENCE.md @@ -291,11 +291,11 @@ node apispy/tests/test_matcher.js ### Re-bundle provider shards ```bash -# Populate from a SpecRecon zip export (all shards, no size limit) -python3 apispy/scripts/prepare_data.py --zip inventory/api-index-sharded-.zip +# Populate from the stable SpecRecon release export (all shards, no size limit) +python3 apispy/scripts/prepare_data.py --zip inventory/api-index-sharded.zip # Optional: exclude shards larger than N KB -python3 apispy/scripts/prepare_data.py --zip inventory/api-index-sharded-.zip --size-limit 100 +python3 apispy/scripts/prepare_data.py --zip inventory/api-index-sharded.zip --size-limit 100 ``` Reload the unpacked extension in Chrome after re-bundling to pick up new data. diff --git a/docs/REPOSITORY_STRUCTURE.md b/docs/REPOSITORY_STRUCTURE.md index 4ea2afb..3ea82e9 100644 --- a/docs/REPOSITORY_STRUCTURE.md +++ b/docs/REPOSITORY_STRUCTURE.md @@ -48,7 +48,7 @@ SpeQL/ │ ├── CONSUMER_GUIDE.md │ └── EXPORT_PIPELINE.md ├── inventory/ # SpecRecon export artifacts (generated, not tracked) -│ └── api-index-sharded-.zip +│ └── api-index-sharded.zip ├── queries/ # CodeQL security queries │ └── azure-security/ │ ├── SasUriInResponse.ql # Detects SAS URIs in API responses diff --git a/docs/inventory/EXPORT_PIPELINE.md b/docs/inventory/EXPORT_PIPELINE.md index 04d7709..7782ced 100644 --- a/docs/inventory/EXPORT_PIPELINE.md +++ b/docs/inventory/EXPORT_PIPELINE.md @@ -136,8 +136,11 @@ A GitHub Actions workflow at `.github/workflows/daily-api-index-export.yml` runs the export automatically every day at 04:00 UTC. Both export workflows compute a semantic SHA-256 over canonical JSON with volatile `generated_at` metadata removed. They restore the last changed-export hash from a small Actions -cache and upload a new artifact only when content differs. The sharded workflow -also skips release replacement and APISpy dispatch for unchanged output. +cache and upload a new artifact only when content differs. Runs are serialized +per source and export format so concurrent jobs cannot publish the same change +twice. The sharded workflow also skips release replacement and APISpy dispatch +for unchanged output, and only sources explicitly configured with +`publish_to_apispy: true` may replace the shared APISpy release. To trigger the workflow manually from the GitHub UI: 1. Navigate to **Actions → Daily API Index Export** From b9d362db03d3f9cf156ebd1858853b2c3456c1e8 Mon Sep 17 00:00:00 2001 From: goldjg Date: Sun, 20 Sep 2026 19:07:13 +0100 Subject: [PATCH 3/3] Preserve APISpy pack identity on dispatch Send explicit source-configured pack metadata so Azure refreshes replace the existing Azure pack instead of creating a duplicate. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../workflows/daily-api-index-export-sharded.yml | 14 +++++++++----- config/sources/azure.json | 3 +++ config/sources/microsoft-graph.json | 3 +++ docs/ADDING_API_SOURCES.md | 3 +++ tests/test_api_inventory_export.py | 4 ++++ 5 files changed, 22 insertions(+), 5 deletions(-) diff --git a/.github/workflows/daily-api-index-export-sharded.yml b/.github/workflows/daily-api-index-export-sharded.yml index a10d2bb..4fcb267 100644 --- a/.github/workflows/daily-api-index-export-sharded.yml +++ b/.github/workflows/daily-api-index-export-sharded.yml @@ -48,13 +48,17 @@ jobs: SOURCE_ID=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('id','unknown'))") SPECS_DIR=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('specs_dir','azure-rest-api-specs'))") SOURCE_REPO=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('source_repo','unknown'))") - SOURCE_NAME=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('name', cfg.get('id','unknown')))") PUBLISH_TO_APISPY=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(str(bool(cfg.get('publish_to_apispy', False))).lower())") + APISPY_PACK_ID=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('apispy_pack_id', cfg.get('id','unknown')))") + APISPY_PACK_NAME=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('apispy_pack_name', cfg.get('name', cfg.get('id','unknown'))))") + APISPY_PLATFORM=$(python3 -c "import json; cfg=json.load(open('${SOURCE_CONFIG}')); print(cfg.get('apispy_platform', cfg.get('id','unknown')))") echo "source_id=${SOURCE_ID}" >> "$GITHUB_OUTPUT" echo "specs_dir=${SPECS_DIR}" >> "$GITHUB_OUTPUT" echo "source_repo=${SOURCE_REPO}" >> "$GITHUB_OUTPUT" - echo "source_name=${SOURCE_NAME}" >> "$GITHUB_OUTPUT" echo "publish_to_apispy=${PUBLISH_TO_APISPY}" >> "$GITHUB_OUTPUT" + echo "apispy_pack_id=${APISPY_PACK_ID}" >> "$GITHUB_OUTPUT" + echo "apispy_pack_name=${APISPY_PACK_NAME}" >> "$GITHUB_OUTPUT" + echo "apispy_platform=${APISPY_PLATFORM}" >> "$GITHUB_OUTPUT" - name: Clone / update spec repository run: | @@ -152,9 +156,9 @@ jobs: "run_id": "${{ github.run_id }}", "tag": "shards-latest", "source_id": "${{ steps.source.outputs.source_id }}", - "pack_id": "${{ steps.source.outputs.source_id }}", - "pack_name": "${{ steps.source.outputs.source_name }}", - "platform": "azure", + "pack_id": "${{ steps.source.outputs.apispy_pack_id }}", + "pack_name": "${{ steps.source.outputs.apispy_pack_name }}", + "platform": "${{ steps.source.outputs.apispy_platform }}", "triggered_by": "${{ github.event_name }}" } }' diff --git a/config/sources/azure.json b/config/sources/azure.json index 7f02d94..2daba3c 100644 --- a/config/sources/azure.json +++ b/config/sources/azure.json @@ -9,6 +9,9 @@ "source_repo": "Azure/azure-rest-api-specs", "source_branch": "main", "publish_to_apispy": true, + "apispy_pack_id": "azure-rest-api-specs", + "apispy_pack_name": "Azure REST API Specs", + "apispy_platform": "azure", "query_packs": [ "queries/azure-security" ] diff --git a/config/sources/microsoft-graph.json b/config/sources/microsoft-graph.json index d32b3a3..b477b2e 100644 --- a/config/sources/microsoft-graph.json +++ b/config/sources/microsoft-graph.json @@ -10,6 +10,9 @@ "source_branch": "master", "source_commit": "b8cbef92f6959dca8150bf3edcc650863765e529", "publish_to_apispy": false, + "apispy_pack_id": "microsoft-graph", + "apispy_pack_name": "Microsoft Graph", + "apispy_platform": "microsoft-graph", "export_profile": "microsoft-graph", "query_packs": [] } diff --git a/docs/ADDING_API_SOURCES.md b/docs/ADDING_API_SOURCES.md index 8425f1a..f6e0149 100644 --- a/docs/ADDING_API_SOURCES.md +++ b/docs/ADDING_API_SOURCES.md @@ -60,6 +60,9 @@ Source configs live in `config/sources/` and follow this schema: | `default_spec_path` | Yes | — | Default subdirectory within `specs_dir` to index | | `export_spec_path` | No | `default_spec_path` | Default export scope; use this to preserve a narrower interactive/database default | | `publish_to_apispy` | No | `false` | Allow the sharded workflow to replace the shared APISpy release and dispatch an update | +| `apispy_pack_id` | No | source `id` | APISpy manifest pack ID sent with publication dispatches | +| `apispy_pack_name` | No | source `name` | APISpy display name sent with publication dispatches | +| `apispy_platform` | No | source `id` | APISpy platform identifier sent with publication dispatches | | `source_repo` | No | `"unknown"` | `org/repo` identifier recorded in export metadata | | `source_branch` | No | `"main"` | Branch name recorded in export metadata | | `source_commit` | No | branch head | Exact full commit SHA to fetch, check out detached, and verify for reproducible acquisition | diff --git a/tests/test_api_inventory_export.py b/tests/test_api_inventory_export.py index cc49394..e4978fd 100644 --- a/tests/test_api_inventory_export.py +++ b/tests/test_api_inventory_export.py @@ -92,12 +92,16 @@ def test_registered_graph_source_is_pinned(self): assert config["source_commit"] == "b8cbef92f6959dca8150bf3edcc650863765e529" assert config["export_profile"] == "microsoft-graph" assert config["export_spec_path"] == "openapi" + assert config["publish_to_apispy"] is False + assert config["apispy_pack_id"] == "microsoft-graph" def test_registered_azure_source_preserves_full_export_scope(self): config_path = Path(__file__).parent.parent / "config" / "sources" / "azure.json" config = exp._load_export_source_config(config_path) assert config["default_spec_path"] == "specification/logic" assert config["export_spec_path"] == "specification" + assert config["publish_to_apispy"] is True + assert config["apispy_pack_id"] == "azure-rest-api-specs" # ---------------------------------------------------------------------------