# Universal Blueprint (Template)

## 1. Metadata & Context
* **Title:** Secure Graph API Implementation Plan
* **Date:** 17-05-2026
* **Objective:** Establish a secure, workspace-isolated FastAPI MCP server in `backend-sre/app/` to serve as the new backend for the SRE monorepo, replacing the legacy implementation. Focus exclusively on secure Graph-to-Frontend communication, deferring any RAG chatbot features.
* **Methodology:** Scaffold a modern FastAPI application adhering to rigorous security practices. Implement CORS hardening for specific frontend ports, robust Supabase JWT validation using `PyJWT`, and secure Neo4j interaction using strictly parameterized Cypher queries. The legacy `old_repositori_MySRE` will be used solely as a structural and API contract reference.
* **Assumptions & Constraints:** 
  * Only `backend-sre/app/` is modified. `old_repositori_MySRE` is read-only.
  * No RAG chatbot logic will be implemented in this phase.
  * Only Next.js ports 6100, 6001, 6002, and 6003 are whitelisted for CORS.
  * Neo4j interactions will be strictly parameterized to prevent injection.
* **Strategic Decider:**
  | Option/Decision | Alternatives | Rationale | Status |
  | :--- | :--- | :--- | :--- |
  | **Auth Strategy** | `supabase-py` native auth checks | Use `PyJWT` for fast offline decoding, checking `role` and `aud`, to minimize latency. Fallback to Supabase SDK ping only for high-risk operations to mitigate revoked token window. | Decided |
  | **Neo4j Cypher Execution** | String interpolation | Strictly enforced parameterized queries (e.g., `$user_id`) to eliminate Cypher injection risks. | Decided |
  | **CORS Policy** | Wildcard `*` or dynamic regex | Hardcoded port whitelist (6100, 6001, 6002, 6003) to ensure strict isolation with the monorepo frontend services. | Decided |
* **Knowledge Provenance:**
  | Research Topic | Tool (Context7/MCP) | Key Findings | Result |
  | :--- | :--- | :--- | :--- |
  | Supabase JWT Offline Decoding | PyJWT Docs / Supabase Docs | JWTs contain `role` and `aud` claims. The secret is required for signature verification. | Applied in security.py |
  | FastAPI CORS Middleware | FastAPI Docs | `CORSMiddleware` requires a strict list of `allow_origins`. | Applied in main.py |

## 2. Structure & Dependencies
* **Folder Tree:** 
  ```text
  backend-sre/app/
  ├── main.py (New/Updated)
  ├── core/
  │   └── security.py (New)
  └── api/
      └── routes/
          └── mcp_routes.py (New)
  ```
* **Dependency Graph:** 
  | Affected File | Main Module | Impact |
  | :--- | :--- | :--- |
  | `app/core/security.py` | `PyJWT`, `supabase` | Provides centralized authentication dependency (`get_current_user`) for all secured routes. |
  | `app/main.py` | `fastapi`, `uvicorn` | Application entry point; configures CORS middleware and includes routers. |
  | `app/api/routes/mcp_routes.py`| `fastapi` | Exposes the secure JSON-RPC / MCP endpoints to the frontend. |

## 3. Concept & Logic
* **Flow Diagram (Mermaid):** 
```mermaid
sequenceDiagram
    participant Frontend as Next.js Frontend (Port 610x)
    participant FastAPI as FastAPI Server (app/main.py)
    participant Auth as Security Module (app/core/security.py)
    participant Neo4j as Graph Database

    Frontend->>FastAPI: Request with Supabase JWT
    FastAPI->>Auth: Validate JWT (Offline PyJWT)
    alt Invalid Token
        Auth-->>FastAPI: 401 Unauthorized
        FastAPI-->>Frontend: Error Response
    else Valid Token (role=authenticated, aud=authenticated)
        Auth-->>FastAPI: User Context
        FastAPI->>Neo4j: Parameterized Cypher Query
        Neo4j-->>FastAPI: Query Results
        FastAPI-->>Frontend: Secure JSON Response
    end
```
* **Execution Synopsis:** 
  | Intent | Goal | Step | Status |
  | :--- | :--- | :--- | :--- |
  | Secure Access | Validate Supabase JWTs locally | Implement `security.py` with `PyJWT.decode` | Planned |
  | Isolate Network | Restrict API access to specific frontends | Configure `CORSMiddleware` in `main.py` | Planned |
  | Prevent Injection | Secure database queries | Ensure all Neo4j driver calls use parameter dicts | Planned |
* **Data Contract:** 
  * `Input Schema`: Standard HTTP requests bearing `Authorization: Bearer <token>` header from allowed origins.
  * `Output Schema`: Standardized JSON responses ensuring no internal database stack traces are leaked on error.

## 4. Execution & Quality
* **Execution Matrix:**
  | Checkbox | Phase | Task | Detail Task | Description | Acceptance Criteria | Input / Output State | Validation Command | Risk |
  | :---: | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
  | [ ] | 1. Security | Implement JWT Auth | Create `app/core/security.py` | Write the FastAPI dependency using `PyJWT` to decode the Supabase token, verifying `aud` and `role`. | File exists, successfully imports `jwt` and `fastapi.security`. Handles `ExpiredSignatureError` and `DecodeError`. | JWT String -> User ID/Dict | `python -m py_compile app/core/security.py` | Med: Incorrect secret handling |
  | [ ] | 2. Routing | Setup Entrypoint & CORS | Create `app/main.py` | Initialize `FastAPI()`, add `CORSMiddleware` with exact port whitelist, and wire up `uvicorn`. | App runs without syntax errors, CORS blocks unknown origins. | App config -> Running ASGI | `python -m py_compile app/main.py` | Low |
  | [ ] | 3. API | Scaffold MCP Routes | Create `app/api/routes/mcp_routes.py` | Create placeholder endpoints for the required MCP tools ensuring they require the `get_current_user` dependency. | Endpoints defined, secured by dependency. | Request -> Secured JSON | `python -m py_compile app/api/routes/mcp_routes.py` | Low |

* **Exit Conditions (Hard Gate):** 
  * `app/core/security.py` successfully parses mock JWTs or enforces strict 401s.
  * CORS strictly rejects `localhost:3000` but allows `localhost:6100`.
  * No string concatenation is used in any provided Cypher query examples.
* **Resource Requirements:** Standard local development resources. Dependencies (`fastapi`, `uvicorn`, `PyJWT`, `supabase`) are already installed in `venv`.
* **Rollback Strategy:** Delete the newly created files (`main.py`, `security.py`, `mcp_routes.py`) in `app/` and revert to the clean scaffold state. No legacy code is modified, so no complex rollback is needed.