# Security model

Модель безопасности 1C MCP Gateway: policy engine, identity, tokens, approvals и audit.

## Prerequisites

- Понимание профилей (`production` / `dev` / `test`) и toolsets (§6.1 TZ).
- Доступ к `apps/gateway`, packages `policy-engine`, `secrets-vault`.
- Для enterprise: OIDC (`ONEC_OIDC_*`), vault (`ONEC_VAULT_ADDR`).

## Пошаговая настройка

### 1. Базовые принципы (deny by default)

| Правило | Реализация |
|---------|------------|
| Read-only first | `production` → только read toolsets |
| Secrets never in args | `passwordEnv`, `tokenEnv`, vault refs |
| Restrictions in list+call | PolicyEngine фильтрует `tools/list` |
| Write needs approval | `approval.create` → one-time `approvalId` |
| Audit everything | Append-only `.data/audit.jsonl` + redaction |

### 2. Identity model

Principal types (`.data/identity.json`):

- `web-console-user` — оператор UI
- `mcp-caller` — HTTP MCP token bearer
- `service-account` — CI/automation
- `onec-user` — mapped 1C user (`/api/identity/onec-mappings`)

HTTP token fields: `actorPrincipalId`, `onBehalfOfPrincipalId`, `oneCUsername`.

### 3. Token model (HTTP MCP)

Хранение: SHA-256 hash в `.data/http-mcp-tokens.json` (plaintext только при выпуске).

```http
POST /api/mcp-tokens
{
  "title": "dev-read",
  "scopes": ["mcp:call", "connections.manage:read"],
  "expiresAt": "2026-06-01T00:00:00Z",
  "allowedClients": ["cursor"],
  "rateLimit": { "windowSeconds": 60, "maxRequests": 120 }
}
```

Bootstrap env `ONEC_MCP_HTTP_TOKEN` → hash as `env-bootstrap` (см. [MCP_CONNECTION.md](./MCP_CONNECTION.md)).

### 4. Risk levels и scopes

| Level | Примеры tools | Gates |
|-------|---------------|-------|
| `public-read` | `list_profiles` | token optional (stdio) |
| `business-read` | `query_1c_odata_readonly` | scope + prod OK |
| `business-write` | `apply_1c_patch_to_files` | approval, idempotency |
| `write-critical` | `import_1c_configuration_to_test` | test only + rollback plan |
| `admin-system` | disabled by default | — |

### 5. Security pipeline (tools/call)

15 шагов (TZ §10.6): authenticate → policy → schema → preflight → execute → redact → audit.

Write/admin дополнительно: `dryRun`, `changeSummary`, `businessReason`, `rollbackPlan`.

### 6. Production hardening checklist

```bash
export ONEC_MCP_ALLOW_INSECURE_HTTP=0
export ONEC_MCP_REQUIRE_HTTP_SERVICE_PATH=1   # если HTTP service обязателен
export ONEC_MCP_HTTP_HOST=127.0.0.1
# OIDC for Web Console (enterprise):
export ONEC_OIDC_ISSUER=https://idp.example.com
export ONEC_OIDC_CLIENT_ID=onec-mcp-gateway
```

## Copy-ready config

stdio local (trusted dev machine):

```json
{
  "mcpServers": {
    "1c-mcp-gateway": {
      "command": "npm",
      "args": ["run", "dev:gateway"],
      "cwd": "/var/www/mwi.yatsuk.pro"
    }
  }
}
```

HTTP production client:

```http
Authorization: Bearer <scoped-token>
X-MCP-Client-ID: cursor
```

## Проверка tools/list

1. Token **без** write scopes → `propose_1c_code_patch` **отсутствует**.
2. Profile `production` → нет `import_*`, `load_extension_*`.
3. `GET 1c://{profile}/policy` resource — policy version snapshot.

## Первый тестовый prompt

```
Вызови list_profiles. Для каждого production-профиля проверь через policy resource,
какие toolsets разрешены. Попробуй вызвать propose_1c_code_patch с dryRun — ожидай отказ для production.
```

## Типовые ошибки

| Ошибка | Причина |
|--------|---------|
| `Policy denied` | Scope/env mismatch |
| `Approval required` | Write без approvalId |
| `Approval already used` | One-time approval |
| `HTTPS required` | Insecure published-web URL |
| Secret in audit | Bug — report; check redaction keys |

## Security warning

- Данные 1С и BSL — **untrusted content** для LLM (prompt injection).
- Никогда не включайте `execute_1c_code`, arbitrary SQL, universal admin tools.
- Разделяйте prod read endpoint и dev write gateway physically или by `ONEC_MCP_DATA_DIR`.
- PII masking в audit не отменяет необходимость data classification в org.

## Related docs

- [MCP_CONNECTION.md](./MCP_CONNECTION.md) — approvals, audit redaction
- [THREAT_MODEL.md](./THREAT_MODEL.md) — STRIDE, mitigations
- [PRODUCTION_STORAGE.md](./PRODUCTION_STORAGE.md) — backup before policy change
- [CI_READONLY_ENDPOINT.md](./CI_READONLY_ENDPOINT.md) — CI tokens
