Skip to content

Add fastapi bim cde guardrail for retail store roll-outs - #24

Merged
sergiobe-itx merged 3 commits into
InditexTech:mainfrom
jmcaamanog:feat/fastapi-bim-guardrail
Oct 14, 2026
Merged

sergiobe-itx merged 3 commits into
InditexTech:mainfrom
jmcaamanog:feat/fastapi-bim-guardrail

Conversation

@jmcaamanog

Copy link
Copy Markdown
Contributor

Summary of Changes

Adds a production-grade integration example in examples/fastapi-bim-guardrail/ demonstrating CerbIA as an asynchronous security gate middleware for an AI Assistant operating in an International Retail BIM Common Data Environment (CDE).

  • BIM WBS Matrix Modeling: Implements the international retail store work breakdown structure (bim_matrix.py) segregating Management / Contracting Packages (000GRL to 900MET) from BIM Technical Disciplines (ARQ, FAC, ENV, CLI, HUM, PCI, ELE, ALU, RED, ATH, CTV, VIS, EST).
  • Bidirectional FastAPI Middleware:
    • Input Gate: Scans incoming contractor queries against prompt injections (e.g. attempting to override structural clearance reviews or bypass BEP rules), unredacted PII (field incident reports with worker IDs/phones), secrets, and malicious submittal links.
    • Output Gate with Canary Leak Detection: Injects dynamic canary tokens into system prompts protecting confidential commercial tender rates and budget margins (PEM), intercepting model leakage before delivery.
  • Declarative Gate Config: Standard CerbIA YAML configuration (config.cerbia.yaml).
  • Automated Validation Runner: Includes test_scenarios.py verifying 5 end-to-end real-world scenarios.
  • Documentation: Detailed bilingual architecture guide and threat model specification (README.md).

Validation

  • All 5 BIM coordination scenarios validated (python test_scenarios.py).
  • Fully compliant with REUSE 3.3 specification (reuse lint passed with 0 errors).
  • Codebase formatted and linted with Ruff (ruff check & ruff format).
  • Commit signed with DCO (Signed-off-by: jmcaamanog <jose.caamano@live.com>).

@jmcaamanog
jmcaamanog requested a review from a team as a code owner October 9, 2026 07:43
@signoff-validator

signoff-validator Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Contribution License Agreement - Valid 🟢

All commits contain valid signoff. As a confirmation, remember that you are agreeing to our Contribution License Agreement.

@jmcaamanog
jmcaamanog force-pushed the feat/fastapi-bim-guardrail branch 2 times, most recently from 0e0ad7e to 9b5de06 Compare October 9, 2026 07:54

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file isn’t loaded by the app, which builds the gates in Python. Could we either load this config in the example or remove it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch! Removed config.cerbia.yaml since the example configures the gates dynamically in Python.

Comment thread examples/fastapi-bim-guardrail/app.py Outdated
app = FastAPI(
title="CerbIA BIM Common Data Environment (CDE) Guardrail API",
description=(
"Production-grade Security Gate middleware securing AI Agent interactions "

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we change "Production-grade" to "Illustrative example" and say that the model response is simulated? For example: "Illustrative FastAPI example showing input and output scanning with CerbIA."

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the docstrings and FastAPI metadata to describe it as an illustrative example with simulated model responses, as suggested.


| Package Code | Package Name (ES / EN) | Discipline Code | Discipline Name (ES / EN) |
| :--- | :--- | :---: | :--- |
| `000GRL` | GESTIÓN PROYECTO / PROJECT MANAGEMENT | `000` | GESTIÓN / MANAGEMENT |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we keep the matrix data and its labels in English too? The package and discipline names are currently Spanish, which makes the example harder to follow for readers who don’t speak Spanish. If the Spanish DNI case is important for demonstrating PII detection, that input can stay with a short English explanation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated! All package and discipline labels are now in English (200HVAC - HVAC & Mechanical Works / HVAC), while keeping the Spanish DNI test case clearly contextualized in English for PII validation.


---

## 🏗️ BIM Work Breakdown Structure (WBS) Matrix

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we simplify this and focus on the CerbIA flow? The BIM matrix and extra endpoints add a lot of domain-specific detail. One English package/discipline example should be enough to show input scanning, model handling, and output scanning.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done! Trimmed down the matrix to a single illustrative package/discipline (200HVAC / HVAC) to keep the primary focus on the CerbIA security gate flow.

Comment thread examples/fastapi-bim-guardrail/app.py Outdated
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field

try:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we use one import instead of catching ImportError and retrying? The fallback can hide an import error from inside bim_matrix. from bim_matrix import ... works for the script, and the README can use uvicorn --app-dir examples/fastapi-bim-guardrail app:app --reload for the server.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switched to direct from bim_matrix import ... and updated the README instructions to use uvicorn --app-dir examples/fastapi-bim-guardrail app:app --reload.

- Validates AI response before dispatching to the client.
"""
# Verify package validity
valid_entries = get_matrix_entries_by_package(request.package_code)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we also check that this discipline belongs to the package? Right now 200CLI with NOTREAL still returns 200 APPROVED. For example:

if not any(entry.discipline_code.upper() == request.discipline_code.upper() for entry in valid_entries):
    raise HTTPException(status_code=400, detail="Invalid discipline for package")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the discipline-to-package check and test coverage for it. Requests with mismatched or invalid disciplines now return HTTP 400 Bad Request.



BIM_WBS_MATRIX: Final[tuple[BimMatrixEntry, ...]] = (
BimMatrixEntry("000GRL", "GESTIÓN PROYECTO", "PROJECT MANAGEMENT", "000", "GESTIÓN", "MANAGEMENT"),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we remove this Spanish matrix and keep just one small English package/discipline example? The current values make the source harder to follow, and most of this matrix isn’t needed to show how CerbIA is integrated.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simplified to a single English BimMatrixEntry('200HVAC', 'HVAC & Mechanical Works', 'HVAC', 'Heating, Ventilation & Air Conditioning').

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we turn these into pytest tests and assert the expected status and response for each scenario? At the moment, a wrong result is only printed, so the script still exits successfully. For example:

def test_prompt_injection_is_blocked(client: TestClient) -> None:
    response = client.post("/api/v1/bim/query", json=prompt_injection_request)
    assert response.status_code == 400
    assert response.json()["detail"]["error"] == "SECURITY_GATE_BLOCKED_INPUT"

Then pytest will fail if a scenario stops working.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Converted the entire scenario runner into a standard pytest test suite with TestClient(app) and explicit assertions across all 11 test cases (200, 400, 404, 422).


## 🛡️ Security Architecture: Threat Model & Guardrails

```

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we use a Mermaid diagram here instead of the ASCII art? It’ll be easier to read and maintain. For example:

flowchart TD
    A[User prompt] --> B{Input gate}
    B -->|Unsafe| C[HTTP 400]
    B -->|Safe| D[Model response]
    D --> E{Output gate}
    E -->|Leaked canary or sensitive data| F[HTTP 422]
    E -->|Safe| G[HTTP 200]
Loading

Since the model is simulated in this example, “Model response” may be clearer than “LLM inference”.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced the ASCII diagram with the suggested Mermaid flowchart TD diagram and clarified the model response as simulated.

@sergiobe-itx sergiobe-itx added the skip-release Do not publish a release for this change. label Oct 13, 2026
- Model illustrative retail store BIM WBS package and discipline in English
- Integrate CerbIA input and output security gates into a FastAPI service
- Add canary token protection against confidential tender budget exfiltration
- Provide comprehensive pytest test suite covering input safety and output gates

Signed-off-by: jmcaamanog <jose.caamano@live.com>
@jmcaamanog
jmcaamanog force-pushed the feat/fastapi-bim-guardrail branch from 9b5de06 to 78a55ca Compare October 14, 2026 06:55
@jmcaamanog

Copy link
Copy Markdown
Contributor Author

Hi @sergiobe-itx! Thanks a lot for the thorough and helpful review! 🚀

All suggested changes have been implemented:

  1. Removed config.cerbia.yaml since gates are configured in Python.
  2. Simplified the BIM WBS matrix to a single English package and discipline (200HVAC - HVAC & Mechanical Works / HVAC).
  3. Added discipline-to-package validation returning HTTP 400 Bad Request for invalid or mismatched disciplines.
  4. Switched to direct from bim_matrix import ... and updated the documentation to use uvicorn --app-dir examples/fastapi-bim-guardrail app:app --reload.
  5. Clarified docstrings and OpenAPI metadata as an illustrative example with simulated model responses.
  6. Converted the scenario runner into a full pytest suite with TestClient(app) and explicit assertions across all 11 test cases.
  7. Replaced the ASCII diagram with the suggested Mermaid flowchart TD diagram in the README.

All checks are passing green, REUSE 3.3 compliant, and commits are signed with SSH. Ready for your review!

sergiobe-itx
sergiobe-itx previously approved these changes Oct 14, 2026
@sergiobe-itx sergiobe-itx self-assigned this Oct 14, 2026
@sergiobe-itx

Copy link
Copy Markdown
Contributor

@jmcaamanog Please create a dependency group named "examples" and add fastapi, httpx and uvicorn:

...
[dependency-groups]
 dev = [
    "pre-commit==4.6.1",
    ...
    "typer==0.27.0",
 ]

examples = [
    "fastapi",
    "httpx",
    "uvicorn",
]

Then regenerate the lockfile and include the updated uv.lock: uv lock

This should resolve the missing FastAPI dependency during pytest collection.

…corn

Signed-off-by: jmcaamanog <jose.caamano@live.com>
@jmcaamanog

Copy link
Copy Markdown
Contributor Author

Done @sergiobe-itx! Added the examples dependency group with fastapi, httpx, and uvicorn in pyproject.toml and regenerated uv.lock via uv lock. Thank you!

@sergiobe-itx sergiobe-itx changed the title feat(examples): add fastapi bim cde guardrail for retail store roll-outs Add fastapi bim cde guardrail for retail store roll-outs Oct 14, 2026
@sergiobe-itx
sergiobe-itx merged commit 1539266 into InditexTech:main Oct 14, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-release Do not publish a release for this change.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants