> ## Documentation Index
> Fetch the complete documentation index at: https://docs.p36-csq.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Security Handover for GxP Environments

> Formal security handover document for customer QA/Validation teams evaluating the CSQ MCP server in regulated life-sciences environments.

## 1. Purpose and Scope

This document is a **formal security handover** for the **CSQ MCP Server** ("the server"). It is intended for **customer QA/Validation teams** in life-sciences environments that operate under **GxP**, **FDA 21 CFR Part 11**, and **EU Annex 11** expectations.

The document provides:

* A system classification and clear statement of the system boundary.
* A data-flow description that shows what crosses the customer’s trust boundary.
* A threat model and mitigations for the two primary customer concerns:
  1. **Will P36 see our internal code or data?**
  2. **Can the server instruct our local LLM to perform unauthorized actions?**
* A controls matrix mapping implemented controls to FDA 21 CFR Part 11, EU Annex 11, and general GxP expectations.
* A responsibility matrix for the customer and P36.

**Important scope note:** The server is a **non-records auxiliary guidance system**. It does not create, modify, or store GxP records. It only provides tenant-scoped catalog data and structured prompts to an AI assistant running inside the customer’s own IDE. The customer’s qualified personnel remain responsible for reviewing and importing the AI-generated draft into the CSQ Cockpit.

## 2. System Classification

| Attribute             | Classification                                                                                                                                                        |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **System name**       | CSQ MCP Server                                                                                                                                                        |
| **Purpose**           | Provide tenant-scoped BTP service/feature catalog data and guided prompts to assist customers in drafting a BTP use-case qualification export.                        |
| **GxP impact**        | **Non-records auxiliary system**. The server does not create, modify, or store GxP records. It provides guidance and read-only data only.                             |
| **Data direction**    | Strictly **read-only** from P36 to the customer. The server never receives source code, prompts, or AI-generated output from the customer.                            |
| **Hosting model**     | Single-tenant instance per customer deployment, managed by P36. The customer supplies the API token; the server resolves exactly one tenant database per token.       |
| **Human-in-the-loop** | Required. The AI-generated JSON is written to a local file in the customer’s workspace, reviewed locally, and imported manually into the CSQ Cockpit by the customer. |

## 3. Data Flow

```mermaid theme={null}
flowchart LR
  IDE["AI-assisted IDE (LLM)"] -- "HTTPS + API key" --> MCP["CSQ MCP Server"]
  MCP -- "catalog + schema + prompt" --> IDE
  IDE -- "UseCaseExport JSON to user" --> User
```

**Data categories that cross the boundary:**

* **Authentication token:** The customer’s Bearer token is sent in the `Authorization` header. It is resolved against a SHA-256 hash on the server; the raw token is never logged.
* **Tool inputs:** The AI assistant sends only tool names and tool arguments (e.g., a `referenceServiceTid` string). No source code, prompts, or generated output are sent.
* **Tool outputs:** Structured tenant catalog data (service names, feature names, risk-model guidance) and staged-flow instructions. All outputs are sanitized before serialization.

**Data categories that do NOT cross the boundary:**

* Customer source code.
* Customer prompts to the AI assistant.
* AI-generated draft JSON.
* Any command or instruction that could mutate the customer’s local system.

## 4. Threat Model and Mitigations

### 4.1 Threat: P36 sees customer source code or internal data

**Concern:** The customer fears that connecting the MCP server exposes internal code, configuration, or generated drafts to P36.

**Mitigation evidence:**

* **The server never requests code.** The tools exposed by the server are limited to `list_supported_services`, `list_features_for_service`, `list_service_instances_for_service`, `get_use_case_schema`, `get_use_case_example`, `get_risk_rubric`, and `advance_analyze_btp_usage_flow`. None of these tools accept file contents, code, or generated output.
* **The AI assistant runs locally.** The LLM that reads the repository and drafts the JSON runs entirely on the customer’s device using the customer’s model and credentials. P36 does not operate the LLM.
* **The JSON is written locally.** The staged prompt explicitly instructs the AI assistant to write the draft to a local file in the workspace and to validate it locally before presenting it to the user.
* **Audit logging contains no row contents.** The audit channel records `tenantId`, `principalId`, `tokenFingerprint`, `method`, `target`, `argHash`, `status`, and `durationMs` — never the tool response body or any customer code.
* **No outbound telemetry.** The server does not send customer data to external analytics or monitoring services.

### 4.2 Threat: The server instructs the customer’s LLM to run harmful or malicious instructions

**Concern:** The customer fears that an MCP tool or prompt could instruct the local LLM to perform unauthorized actions, exfiltrate data, or modify systems.

**Mitigation evidence:**

* **Strictly read-only tool surface.** The server exposes no tools that execute shell commands, write files, submit data, or call external APIs on the customer’s behalf.
* **No write-back to CSQ.** There is no `submit_use_case`, `upload`, or similar tool. The final JSON import is performed manually by the customer inside the CSQ Cockpit.
* **Prompt-injection hardening.** Tenant database outputs are sanitized before being sent to the AI assistant: control characters are stripped, code fences and role markers are neutralized, string length is capped, and a visible warning is prepended to every DB-backed output. The prompt itself contains a security contract instructing the LLM to treat wrapped tenant data as data, not instructions.
* **Input validation.** Every tool input is validated by a strict Zod schema with `additionalProperties: false`.
* **Tenant isolation.** A token resolves to exactly one tenant database. Cross-tenant or unknown-tenant requests are rejected with `403` and do not reach the database layer.
* **Rate limiting.** A global pre-authentication limiter and a per-principal post-authentication limiter protect the endpoint from brute-force or abuse.
* **The server does not execute customer instructions.** The server only responds to explicit tool calls with pre-defined, read-only operations.

### 4.3 Threat: Unauthorized access to tenant data

**Mitigation evidence:**

* **API key authentication.** Tokens are stored as SHA-256 hashes in AWS Secrets Manager; comparison uses `crypto.timingSafeEqual` to prevent timing attacks.
* **Cognito JWT support (optional).** When enabled, JWTs are verified against a JWKS, with audience, issuer, and tenant claim validation.
* **Token expiration.** API key hashes can include an `expiresAt` field; expired keys are rejected automatically.
* **Database isolation.** Each tenant is mapped to its own database. The DB user is read-only (`GRANT SELECT`), queries are parameterized, and table/database identifiers are whitelisted against a strict pattern before interpolation.
* **Secrets management.** In production, `DB_PASSWORD` and `TENANT_REGISTRY_JSON` are sourced from AWS Secrets Manager. Plain env files are rejected when `NODE_ENV=production`.
* **Transport security.** The Node process binds to `127.0.0.1` by default; TLS 1.2/1.3 termination, HSTS, and strict security headers are enforced by nginx.
* **Host hardening.** The systemd service runs with `NoNewPrivileges`, `ProtectSystem=strict`, `ProtectHome`, and `PrivateTmp`. The Docker container runs as a non-root `node` user.

## 5. Controls Matrix

| Control                                  | Implementation                                                                                                                                                        | FDA 21 CFR Part 11                                         | EU Annex 11                           | General GxP                                  |
| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------- | -------------------------------------------- |
| **System boundary & classification**     | Documented as non-records auxiliary system; no GxP record creation, modification, or storage.                                                                         | §11.10(a) — validation scope                               | §1 — scope and risk-based approach    | Data integrity by design                     |
| **Access control & authority checks**    | API key hashing + optional Cognito JWT; tenant resolved from registry; unknown/forbidden tenants rejected with 403; constant-time comparison.                         | §11.10(d) — access controls; §11.10(g) — authority checks  | §7 — access control; §8 — audit trail | Physical/logical separation of tenants       |
| **Audit trails**                         | Structured audit logs on dedicated `audit` channel: tenantId, principalId, tokenFingerprint, method, target, argHash, status, durationMs, ip. No secrets logged.      | §11.10(e) — audit trails; §11.10(k) — system documentation | §9 — audit trail                      | ALCOA+ attributable and complete records     |
| **Data integrity — read-only DB**        | Catalog repository executes only `SELECT` statements; read-only DB user; parameterized queries; identifier whitelisting.                                              | §11.10(b) — accurate records                               | §4 — data integrity                   | No unauthorized modification of data         |
| **Data integrity — output sanitization** | `sanitizeOutput.ts` strips control chars, neutralizes code fences/role markers, caps length, and wraps untrusted data with a visible warning.                         | §11.10(b) — accurate records                               | §4 — data integrity                   | Prevent prompt injection affecting AI output |
| **Electronic signature / identity**      | Bearer token or verified Cognito JWT; token fingerprint in audit logs; no shared credentials.                                                                         | §11.100 — signature/identification                         | §7 — unique user identification       | Non-repudiation of access                    |
| **Validation evidence**                  | Automated test suite (`vitest`) with 41 tests covering auth, tenant isolation, rate limiting, audit logging, secrets handling, and prompt-injection hardening.        | §11.10(a) — validation                                     | §4 — validation                       | Evidence-based qualification                 |
| **Change control**                       | Bitbucket pipeline runs `npm test`, `npm audit --omit=dev --audit-level=high`, and builds the container before deployment.                                            | §11.10(k) — system documentation                           | §13 — change control                  | Controlled deployment of changes             |
| **Incident / security monitoring**       | Rate limiting; audit logs; health endpoint restricted by CIDR; nginx logs.                                                                                            | §11.10(c) — operational checks                             | §10 — security incidents              | Detect and respond to misuse                 |
| **Human review gate**                    | AI-generated JSON is written to a local file; the customer must review and import it manually into the CSQ Cockpit.                                                   | §11.10(b) — human review                                   | §4 — accuracy checks                  | Human-in-the-loop for regulated decisions    |
| **TLS / transport security**             | TLS 1.2/1.3 only; HSTS; nginx reverse proxy; loopback bind by default; DB TLS with certificate verification.                                                          | §11.30 — controls for open systems                         | §6 — security                         | Confidentiality in transit                   |
| **Secrets rotation**                     | API key hashes support multiple entries and `expiresAt`; SIGHUP reloads `TENANT_REGISTRY_JSON` from AWS Secrets Manager without restart; 90-day rotation recommended. | §11.300 — signature controls                               | §7 — password management              | Key lifecycle management                     |

## 6. Responsibility Matrix

| Activity                                                      | P36 |                    Customer                    |
| ------------------------------------------------------------- | :-: | :--------------------------------------------: |
| Operate the MCP server instance                               |  ✅  |                                                |
| Provide and rotate tenant API tokens / Cognito configuration  |  ✅  |                                                |
| Protect the tenant token as a production credential           |     |                        ✅                       |
| Operate the AI assistant and IDE on customer devices          |     |                        ✅                       |
| Review and import the AI-generated JSON into the CSQ Cockpit  |     |                        ✅                       |
| Approve the final use-case qualification in CSQ               |     |                        ✅                       |
| Maintain AWS Secrets Manager secrets and IAM instance profile |  ✅  |                                                |
| Maintain the read-only database user and network access       |  ✅  |                                                |
| Monitor audit logs for unauthorized access                    |  ✅  | ✅ (customer may receive audit logs if desired) |
| Validate the system for the customer’s specific GxP use       |     |                        ✅                       |
