Permissions & Secrets — инфраструктурный слой, который отвечает на два критических вопроса: кто или что имеет право выполнить действие и как система безопасно получает необходимые credentials, не превращая prompt, memory или logs в хранилище секретов.
№48 Guardrails & Policies решает, разрешено ли действие в данном контексте; №51 определяет, имеет ли principal техническую capability выполнить его и какие credentials нужны. №49 HITL может потребовать approval, но approval не создаёт отсутствующий permission. №50 Contracts задаёт shape identity/scope/action claims. №52 Prompt Injection & Agent Security изучает попытки заставить систему злоупотребить уже имеющимися capabilities. №54 Connectors использует auth flows и credentials для конкретных систем. №76 Governance задаёт более широкий data/compliance слой.
Prerequisites: №10 State, №12 Tools, №42 Events, №46 Observability, №48 Policies, №50 Contracts. Forward references: №52 Security, №53 Sandbox, №54 Connectors, №60 Artifact Store, №76 Data Governance & Privacy. Более поздние темы — implementation/detail references, не обязательные prerequisites.
REQUEST-TIME: YES — permission check и credential injection перед sensitive action. CONTROL PLANE: YES — principals, roles, scopes, secret lifecycle, revocation, policy mapping. DATA PLANE: YES — actual access to APIs/DB/files. OFFLINE: YES — audits, rotation, access review, secret scanning, regression/security tests.
Success: authorized principal receives minimum capability for exact resource/action and secret never leaks to untrusted context. Retryable: temporary token issuance/vault outage where safe. Permanent: scope missing, principal disabled, revoked credential, forbidden tenant/environment. Idempotency: token/permission operations should not multiply grants. Persist: principal, scope, secret_ref, issuance/revocation metadata, not raw secret. Trace: access decision and credential use, never secret content.
№51 не владеет context-sensitive business policy, prompt-injection threat model, connector business semantics, human approval lifecycle, sandbox containment или enterprise IAM продуктом целиком. Она владеет IDENTITY → AUTHORIZATION SCOPE → CREDENTIAL DELIVERY → REVOCATION.
Prompt содержит API key, DB password или OAuth token.
Модель может повторить его в output, tool args, memory, trace или через prompt injection.
Model emits structured intent:
send_email(recipient_id, body_ref)
Без raw credential.
Tool wrapper resolves secret_ref / short-lived token inside protected runtime, checks scope, executes and returns sanitized result.
Конкретный пользователь и его tenant/org memberships. Действие может происходить «on behalf of user».
Worker/service/automation account с собственной ограниченной role.
Agent/subagent как логический actor в trace. Обычно не хранит credential сам, а использует host capability.
К какому customer/workspace относятся data/resources.
Конкретный deployment/process/pod/host может получать machine credential независимо от модели.
Service действует в ограниченном subset прав пользователя, а не от имени супер-аккаунта.
Система подтверждает principal: session, service identity, signed token, workload credential.
Вопрос: кто это?
Проверяется action/resource/scope/tenant/context.
Вопрос: что этому principal разрешено?
get_report(report_id) должен expose только read нужного prefix/tenant. Security boundary — это не только credential scope, но и узость самого tool interface.LLM, search, SaaS, payment, infrastructure APIs.
Access/refresh tokens, authorization codes, session credentials.
Password, DSN containing password, client certificates.
Private keys, signing keys, webhook signing secrets.
Cookies, bearer tokens, access session state.
Cloud creds, SSH keys, registry credentials.
Emergency credentials with broad power.
Secret ID/reference can be non-secret if it reveals no credential material and access to resolve it is separately controlled.
{
"connector_id": "gmail:brand_A",
"credential_ref": "secret://connectors/gmail/brand_A",
"allowed_scopes": [
"mail.read",
"draft.create"
],
"tenant_id": "brand_A",
"environment": "prod"
}Agent может знать:
Но не должен видеть access token / refresh token / password.
credential_ref или connector_id, а actual secret разрешать только runtime principal внутри trusted tool layer.Легко внедрить, но leakage может жить месяцами. Использовать только с узкими scopes и rotation.
Runtime exchanges identity for temporary token with small TTL and narrow audience/scope.
Capability создаётся только непосредственно перед operation и исчезает после TTL/use.
| Environment | Data | Credentials | Allowed side effects |
|---|---|---|---|
| LOCAL / DEV | Synthetic/redacted where possible. | Dev-only credentials. | Mocks/sandbox/test resources. |
| STAGING | Controlled non-prod data. | Staging accounts/scopes. | Staging-only external resources. |
| PROD | Real tenant data. | Prod workload identity / secret refs. | Policy/permission controlled. |
| BREAK-GLASS | Only incident context. | Emergency credential. | Time-bound, audited, explicit approval. |
Parent не передаёт raw credential. Он выдаёт subagent логический capability token/ref с ограниченными action/resource/budget/expiry.
Пример: parent может read+write, subagent получает только read.
Каждый новый subagent автоматически наследует весь environment, API keys и admin tools parent process.
Это резко увеличивает blast radius prompt injection или ошибки маршрутизации.
Principal имеет scope post.publish для channel A.
В текущем workflow public publish требует human approval.
Authorized approver approves exact payload. После approval permission всё равно проверяется перед execute.
| Surface | Что хранить | Что не хранить |
|---|---|---|
| Prompt / context | connector_id, capability metadata, secret_ref if safe. | Raw token/password/private key. |
| Trace / logs | credential_id/ref, token issuer, scope, outcome. | Authorization header, cookie, raw secret. |
| Memory | «Использовать account A» / connector ref. | Credential material. |
| Error message | SAFE code + masked identifier. | Full DSN/token/request headers. |
| Artifacts | Sanitized config reference. | .env, key files, browser session dumps unless explicitly protected. |
Плановая/incident rotation без массового редактирования prompts/configs благодаря secret_ref.
Immediate disable token/session/key when principal or connector no longer trusted.
Runtime token caches должны уважать revocation/TTL.
Понять, где credential применялся после suspected compromise.
secret_ref, rotation меняет значение в одном controlled store. Если raw secret размазан по .env, prompts, JSON, notebooks и workflows — rotation превращается в incident project.Для incident recovery может существовать более широкий emergency credential.
Break-glass secret не должен быть доступен обычному agent runtime или prompt. AI может подготовить incident plan, но activation широкого emergency access — отдельный protected control path.
Correct principal/scope/tenant succeeds.
Wrong role/scope/action/resource blocked.
Valid credential A cannot access B resource through parameter manipulation.
Prompts/logs/traces/artifacts checked for credential material.
Revoked token stops working within expected window.
New secret works; old is removed without app edits.
Subagent cannot expand delegated capability.
High-risk operation fails safely, not with bypass.
user → agent → runtime service → external account.
action, resource, scope, tenant, policy result.
credential_ref / key version / token issuer, never raw token.
issued, resolved, used, rotated, revoked.
allowed/denied/executed/failed and authoritative result.
Unexpected tenant, unusual scope, old key use, excessive credential resolution.
% sensitive capabilities with narrow scopes instead of broad shared credential.
Confirmed raw secret occurrences in model context/logs/artifacts. Target: zero.
Median/max lifetime by credential class.
Time from revoke decision to unusable credential.
Permission denials by principal/action/resource.
Unauthorized cross-tenant access. Target: zero.
% credentials rotated within policy window.
Number of admin/all-scope secrets reachable by runtime.
security/ ├── principals.py ├── authorize.py ├── scopes.py ├── tenant.py ├── secret_refs.py ├── redaction.py └── tests/ connectors/ ├── registry.yaml └── wrappers/ secrets: dev -> dev secret store prod -> vault / protected environment runtime pattern: model sees capability metadata model emits action intent host validates scope/policy wrapper resolves credential_ref API call executes result sanitized raw credential discarded
Полноценный enterprise IAM/Vault/policy stack подключается, когда scale/compliance/teams justify it.
| Вопрос | Ответ |
|---|---|
| Стоит ли реализовывать? | Да, до подключения реальных sensitive tools. |
| Separate Component? | YES как отдельная логическая security responsibility в Production Fabric. Это не обязательно отдельный server. |
| Минимум 80% ценности? | Principals, scopes, tenant binding, secret refs, protected injection, env separation, revocation/rotation, audit. |
| Когда overkill? | Писать собственный OAuth/IAM/Vault/KMS stack вместо использования стандартных OS/cloud/library mechanisms. |
| Trigger? | Любой external API, DB, filesystem, connector или privileged side effect, требующий credential. |
| Как измерить uplift? | Secret exposure, cross-tenant escapes, broad credentials, permission failures, rotation/revocation time, security incidents. |
| Можно ли rule/tool/code вместо LLM-agent? | Да, полностью. Security authority должна быть deterministic host infrastructure. LLM может только предложить intent. |
Prompt/context/memory содержат capability refs, не raw credential.
Scope выдаётся по action/resource/tenant, не «на всякий случай».
Critical principal/tenant/resource не должен свободно выбираться моделью.
Temporary token снижает blast radius leakage.
Subagent получает не больше parent и обычно меньше.
Dev/staging/prod credentials и resources не смешиваются.
Human approval не расширяет технические scopes.
Приложение знает secret_ref; raw value может меняться независимо.
Логировать credential identity/version/scope/outcome без secret material.
USER / EVENT / SYSTEM TASK
↓
IDENTITY:
user + tenant + runtime principal
↓
REQUESTED CAPABILITY
↓
AUTHORIZATION:
principal × action × resource × scope
↓
POLICY:
is this allowed NOW?
↓
[ HITL if required ]
↓
TOOL / CONNECTOR CONTRACT
↓
SECRET REF / TOKEN EXCHANGE
↓
PROTECTED RUNTIME RESOLVES CREDENTIAL
↓
EXTERNAL API / DB / FILESYSTEM
↓
SANITIZED RESULT
↓
TRACE:
who + capability + scope + credential_ref/version + outcome
↓
ROTATE / REVOKE / AUDIT
NEVER:
RAW SECRET
↓
PROMPT
↓
MODEL
↓
MEMORY / LOG / OUTPUT
CORE PRINCIPLE:
THE MODEL SHOULD RECEIVE
A CAPABILITY,
NOT A PASSWORD.
PERMISSION DEFINES
WHAT THE PRINCIPAL CAN DO.
POLICY MAY NARROW THAT PERMISSION,
BUT IT MUST NEVER CREATE
A PRIVILEGE THE PRINCIPAL DOES NOT HAVE.
A. Related ECC ideas. Context-as-cache, scoped memory, lifecycle hooks, selective capabilities, feature flags, deterministic enforcement, provider-neutral adapters and eval-gated learning are applied only where relevant to №51 Permissions & Secrets.
B–E. Existing boundary and placement. The existing conceptual boundary, class PRODUCTION, default ON and owner Production Fabric remain authoritative. Runtime/control/data/offline placement is unchanged; durable state stays outside model context.
F–H. Hooks and contracts. Use bounded PRE_MODEL/POST_MODEL, PRE_TOOL/POST_TOOL, CHECKPOINT and TASK_COMPLETED events as applicable. Illustrative fields and canonical contracts are defined in NEW_CONTRACTS_SPEC.md; no universal schema is implied.
I–J. Security and evaluation. Host-side schema, permission, secret, budget, idempotency and audit checks take precedence over LLM output. Optional mechanisms require a feature flag and WITH/WITHOUT ablation; measure quality, acceptance, correction, latency, cost, escalations and severe errors.
K–L. Task profiles and cross-references. A TaskProfile selects the relevant skill, tool/context slice, memory scope and enforcement profile independently from FAST/STANDARD/DEEP. See cross-reference map, hook spec and ablation plan. Provider adapters remain outside the core.