Files
devos/Docs/DevOS-Platform-v2/25_SECURITY_AUTHORIZATION_TENANCY_RUNTIME.md
T
phptits 851ccf1d7f v2 platform runtime (docs 22 Phase 2/4/7 + 17): Project/Environment + Config + Storage + Observability
- Project/Environment model with default environments (dev/staging/prod)
- Config Runtime: cascade resolution (platform→org→project→env), secrets via vault
- Storage Runtime: local provider, sha256 dedup, integrity check, file list/upload/delete
- Observability: execution query, per-action summary (success rate, avg, p95), health
- Realtime SSE: workspace event stream endpoint (GET /api/v1/v2/realtime/events)
- Phase 1 acceptance: core.health.check, core.user.create, core.user.list
- Actions: core.project.*, core.config.*, core.file.*, core.user.* (62 total)
2026-09-11 21:11:07 +00:00

39 KiB
Raw Blame History

DevOS Security / Authorization / Tenancy Runtime

文档版本:v1.0
文件名:25_SECURITY_AUTHORIZATION_TENANCY_RUNTIME.md
适用项目:/home/dev/bun/devos
状态:Architecture / Implementation Specification
前置文档:01–24


1. 文档目的

本文件定义 DevOS 的统一:

  • Security Runtime
  • Authentication
  • Authorization
  • Permission
  • Role / Policy
  • Organization / Tenant
  • Project Scope
  • Environment Isolation
  • Resource Scope
  • Action Authorization
  • Agent Authorization
  • Plugin Authorization
  • MCP Authorization
  • Secret Protection
  • File / Storage Authorization
  • Task / Job Authorization
  • Audit Security
  • API Security
  • Session Security

目标不是建立一个简单的 RBAC 后台。

DevOS 是一个:

Human + Agent + Plugin + MCP + Workflow + Task + API 共用执行 Runtime 的平台。

因此安全模型必须保证:

User
Agent
Plugin
MCP
Workflow
Scheduler
API
CLI
System
    ↓
Security Context
    ↓
Authentication
    ↓
Authorization
    ↓
Scope / Policy
    ↓
Action Runtime
    ↓
Execution

任何入口都不能绕过 Security Runtime。


2. 核心安全原则

DevOS 遵循以下不可违反的原则。

2.1 Authentication ≠ Authorization

Authentication:

你是谁?

Authorization:

你可以做什么?

Scope:

你可以对哪些对象做?

Policy:

在什么条件下可以做?

四者必须独立。


3. Security Runtime 总体架构

                    ┌──────────────┐
                    │ Authentication│
                    └──────┬───────┘
                           ↓
                    ┌──────────────┐
                    │ Security     │
                    │ Context      │
                    └──────┬───────┘
                           ↓
             ┌──────────────────────────┐
             │ Authorization Runtime    │
             │                          │
             │ Permission               │
             │ Role                     │
             │ Policy                   │
             │ Scope                    │
             │ Resource Access          │
             └────────────┬─────────────┘
                          ↓
                  ┌───────────────┐
                  │ Action Runtime│
                  └───────┬───────┘
                          ↓
                     Execution

4. Security Context

所有 Runtime 操作必须携带统一 Security Context。

interface SecurityContext {
  actor: ActorIdentity

  organizationId: string | null

  projectId: string | null

  environmentId: string | null

  sessionId?: string

  requestId: string

  correlationId: string

  permissions: PermissionSet

  roles: RoleRef[]

  scopes: ScopeContext

  authMethod: AuthMethod

  metadata: Record<string, unknown>
}

禁止:

someService.doSomething(userId)

推荐:

someService.doSomething({
  securityContext,
  ...
})

5. Actor 模型

DevOS 的 Actor 不只是 User。

type ActorType =
  | "user"
  | "agent"
  | "plugin"
  | "mcp"
  | "workflow"
  | "scheduler"
  | "service"
  | "system"

统一:

interface ActorIdentity {
  id: string
  type: ActorType
  organizationId?: string
  displayName?: string
}

6. 最重要的安全规则

Agent 不是超级用户

绝对禁止:

Agent
 ↓
Database

也禁止:

Agent
 ↓
Redis

以及:

Agent
 ↓
Filesystem

Agent 必须:

Agent
 ↓
Capability
 ↓
Action
 ↓
Action Runtime
 ↓
Authorization
 ↓
Execution

7. Plugin 不是可信代码

Plugin 默认视为:

半可信扩展。

Plugin 必须声明:

permissions:
  - seo.website.read
  - seo.website.scan

而不是:

permissions:
  - *

默认拒绝。


8. MCP 不是安全边界

MCP 只是能力访问协议。

禁止:

MCP
 ↓
Internal Service

绕过:

Authorization
Action Runtime
Audit

正确:

MCP
 ↓
Capability
 ↓
Action
 ↓
Authorization
 ↓
Action Runtime

9. Multi-Tenancy 模型

DevOS 使用层级 Scope:

Global
  ↓
Organization
  ↓
Project
  ↓
Environment
  ↓
Resource

例如:

Organization A
 ├── Project SEO-A
 │    ├── dev
 │    ├── staging
 │    └── production
 │
 └── Project CRM-A
      ├── dev
      └── production

10. Organization

Organization 是主要租户边界。

interface Organization {
  id: string
  name: string
  status: "active" | "suspended" | "deleted"
}

所有组织级资源必须带:

organizationId

11. Project

Project 是业务隔离与执行隔离单位。

interface Project {
  id: string
  organizationId: string
  name: string
}

Project 不允许跨 Organization。


12. Environment

Environment:

development
staging
production

必须独立。

尤其:

production

不能因为 Agent 或 Plugin 请求而自动获得。


13. Environment Protection

生产环境必须支持:

production:
  protected: true
  requireApproval: true
  allowAgentDirectExecution: false

高风险操作:

delete
deploy
rotate-secret
publish
send
billing
dns-change
database-migration

默认进入 Approval 流程。


14. Permission 模型

Permission 使用:

<namespace>.<resource>.<action>

例如:

core.user.read
core.user.create
core.user.update
core.user.delete

seo.website.read
seo.website.scan
seo.website.update

devops.server.read
devops.server.deploy
devops.server.restart

15. Permission 不等于 Action

Action:

seo.website.scan

Permission:

seo.website.scan

通常可以一一对应,但概念必须保持独立。

Action 是执行能力。

Permission 是访问控制。


16. Permission Registry

建立统一:

PermissionRegistry

负责:

  • 注册
  • 查询
  • 描述
  • 分类
  • 风险等级
  • 默认策略
  • 兼容性

例如:

interface PermissionDefinition {
  id: string

  description: string

  resource: string

  action: string

  riskLevel:
    | "low"
    | "medium"
    | "high"
    | "critical"

  requiresApproval: boolean
}

17. Role

Role 是 Permission 集合。

例如:

Owner
Admin
Developer
Operator
Viewer
Agent Operator
interface Role {
  id: string
  name: string
  permissions: string[]
}

18. Role 不应该硬编码

禁止:

if (user.role === "admin") {
  ...
}

推荐:

authorization.require(
  "devops.server.deploy"
)

原因:

未来必须支持:

  • Custom Role
  • Organization Role
  • Project Role
  • Agent Role
  • Plugin Role
  • Temporary Role

19. Policy

RBAC 不足以表达:

User 可以 deploy
但是:
production 不允许直接 deploy

因此需要 Policy Runtime。

例如:

interface AuthorizationPolicy {
  id: string

  evaluate(
    context: AuthorizationContext
  ): PolicyDecision
}

结果:

type PolicyDecision =
  | {
      effect: "allow"
    }
  | {
      effect: "deny"
      reason: string
    }
  | {
      effect: "approval_required"
      reason: string
    }

20. Authorization Decision

统一:

interface AuthorizationDecision {
  allowed: boolean

  requiresApproval: boolean

  reason?: string

  matchedPermissions: string[]

  matchedPolicies: string[]

  scope: ScopeContext
}

21. Authorization 流程

所有 Action:

Request
 ↓
Authentication
 ↓
Build Security Context
 ↓
Permission Check
 ↓
Resource Check
 ↓
Scope Check
 ↓
Policy Check
 ↓
Approval Check
 ↓
Rate Limit
 ↓
Action Runtime

22. Default Deny

任何没有明确允许的操作:

DENY

禁止:

if (!permission) {
  return true
}

23. Resource-Level Authorization

不仅判断:

can update website

还必须判断:

can update THIS website

例如:

User
 ├── Project A
 │    └── Website A
 │
 └── Project B
      └── Website B

User 有:

seo.website.update

不代表可以:

Website B

24. Scope Provider

建立:

interface ScopeProvider {
  resolve(
    context: SecurityContext,
    resource: ResourceDefinition
  ): ScopeConstraint
}

例如自动注入:

organization_id = $organizationId
AND project_id = $projectId

业务代码不应该手工到处写:

where: {
  organizationId,
  projectId
}

应该由 Data Runtime + Scope Runtime 统一处理。


25. Database Multi-Tenancy

所有 Tenant Resource 必须具备:

organizationId

Project Resource:

organizationId
projectId

Environment Resource:

organizationId
projectId
environmentId

26. PostgreSQL Row-Level Security

DevOS 第一阶段可以使用:

Application-level scope enforcement

但架构必须为 PostgreSQL RLS 留出空间。

高安全部署可以启用:

PostgreSQL RLS

形成:

Application Authorization
+
Data Runtime Scope
+
Database RLS

三层防护。


27. Cross-Tenant Protection

绝对禁止:

GET /api/websites/:id

直接:

SELECT * FROM websites
WHERE id = $id

必须:

id
+
organization scope
+
project scope
+
permission

28. IDOR 防护

所有资源 ID 都必须经过 Scope 验证。

例如:

GET /api/projects/project-B

如果当前 Actor 属于:

Organization A

而 Project B 属于:

Organization B

必须:

404

或:

403

具体选择由 API Security Policy 决定。

对外 API 推荐尽量避免泄漏资源存在性。


29. Authentication

支持:

Session
JWT
API Key
Service Token
OAuth/OIDC
MCP Auth
CLI Token

但所有认证方式最终转换成:

ActorIdentity
+
SecurityContext

30. Session

Session Runtime:

interface Session {
  id: string
  actorId: string

  createdAt: Date
  expiresAt: Date

  lastSeenAt: Date

  ipHash?: string
  userAgentHash?: string

  revokedAt?: Date
}

敏感原始信息不应无限期保存。


31. Token

Token 必须:

  • 有过期时间
  • 可撤销
  • 可追踪
  • 有 Scope
  • 有 Actor
  • 有用途
  • 有创建时间

不要使用永不过期超级 Token。


32. API Key

API Key 必须:

hash only

数据库不能保存:

plaintext API key

展示:

sk_live_••••••••••

创建后原则上只展示一次。


33. Service Account

系统间调用使用:

Service Account

而不是共享管理员账号。

例如:

devos-worker
devos-mcp
devos-agent
devos-scheduler

每个 Service Account 使用最小权限。


34. Least Privilege

默认原则:

Minimum permission
+
Minimum scope
+
Minimum lifetime

尤其针对:

  • Agent
  • Plugin
  • MCP
  • Service
  • API Key

35. Agent Permission

Agent 应拥有:

Agent Identity

例如:

agent:seo-operator

它拥有:

seo.website.read
seo.website.scan
seo.keyword.search

不应该拥有:

core.user.delete
billing.refund
secret.read

除非显式授权。


36. Agent Delegation

用户可以:

User
 ↓
Delegate Goal
 ↓
Agent

Agent 的权限不能超过用户授权边界。

默认:

AgentPermission
=
Intersection(
  AgentPolicy,
  UserDelegatedPermission,
  ProjectScope
)

37. Agent Approval

高风险操作:

Agent
 ↓
Action
 ↓
Approval Required
 ↓
Human
 ↓
Approve
 ↓
Execution

Agent 不允许自行批准自己的操作。


38. Approval Runtime

建议:

packages/approval/

定义:

interface ApprovalRequest {
  id: string

  actionId: string

  executionId: string

  actorId: string

  organizationId: string

  projectId?: string

  environmentId?: string

  reason: string

  riskLevel: string

  expiresAt: Date
}

状态:

pending
approved
rejected
expired
cancelled

39. Approval 不等于 Permission

两者不同:

Permission:
允许不允许?

Approval:
这一次是否需要人工确认?

即:

Permission = capability authorization
Approval = execution authorization

40. Secret Security

Secret Runtime 必须遵守:

Agent
Plugin
MCP
UI
Log
Event
Audit

默认都不能看到 Secret 明文。


41. Secret Access

Secret 使用:

secret://provider/name

执行时:

Secret Reference
 ↓
Authorization
 ↓
Secret Runtime
 ↓
Decrypt
 ↓
Memory
 ↓
Provider

明文生命周期尽可能短。


42. Secret Leak Protection

以下内容必须自动 Redact:

API Keys
Tokens
Passwords
Private Keys
OAuth Secrets
Cookie
Authorization Headers
Connection Strings

所有:

Log
Trace
Event
Audit
Error
Task Output
Agent Observation

必须执行 Secret Redaction。


43. File Security

File Runtime 必须检查:

Actor
Organization
Project
Environment
Permission
File visibility

禁止:

/download/:fileId

直接暴露 Object Storage URL。

使用:

Signed URL

并限制:

TTL
scope
method
content-type

44. Task Security

Task 必须保存:

organizationId
projectId
environmentId
actorId

Worker 执行 Task 时恢复完整 Security Context。

禁止 Worker:

system user

执行所有任务。


45. Job Security

Job 继承 Task Scope:

Task
 ↓
Job
 ↓
Execution

必须保证:

Job.organizationId
=
Task.organizationId

不能通过修改 Job 数据扩大权限。


46. Event Security

Event Payload 可能包含敏感信息。

因此 Event 定义:

interface EventDefinition {
  id: string

  visibility:
    | "public"
    | "organization"
    | "project"
    | "internal"

  sensitiveFields?: string[]
}

47. Event Subscriber Authorization

Subscriber 不因为订阅了 Event 就自动获得全部 Payload。

必须:

Subscribe Permission
+
Event Visibility
+
Scope

48. Webhook Security

Webhook 必须:

HMAC signature
timestamp
nonce/idempotency
retry
timeout

同时必须防止:

SSRF
private IP access
localhost access
metadata endpoint access

49. MCP Security

MCP Server 必须注册:

MCP Identity

每一个 MCP Capability 必须声明:

permissions:
  - seo.website.read

MCP Tool 调用:

MCP Request
 ↓
Authenticate
 ↓
Resolve Actor
 ↓
Capability
 ↓
Authorization
 ↓
Action
 ↓
Execution

50. Plugin Security

Plugin Manifest:

id: example.plugin

permissions:
  - seo.website.read
  - seo.website.scan

scopes:
  - organization
  - project

network:
  allowed:
    - api.example.com

未来可以支持更细粒度:

filesystem
network
process
database
secret

51. Plugin Permission Approval

安装 Plugin 时:

Plugin Manifest
 ↓
Permission Review
 ↓
Risk Analysis
 ↓
User Approval
 ↓
Install

Plugin 请求新增高权限时:

Upgrade
 ↓
Permission Diff
 ↓
Re-approval

52. Capability Risk Level

每个 Action 建议拥有:

low
medium
high
critical

例如:

website.read        low
website.scan        low
website.update      medium
dns.update          high
server.restart      high
server.delete       critical
secret.rotate       critical

53. Security Policy

建立:

SecurityPolicyRuntime

负责:

  • IP policy
  • Environment policy
  • Agent policy
  • Plugin policy
  • MCP policy
  • Rate policy
  • Approval policy
  • Data access policy
  • Secret policy

54. Rate Limit

安全层必须统一支持:

per user
per organization
per project
per IP
per token
per plugin
per agent
per action

例如:

seo.website.scan

可以:

100 / hour / project

55. Abuse Protection

针对 Agent / MCP 尤其需要:

max iterations
max actions
max task count
max execution time
max cost
max network calls

这些限制由:

Agent Budget
Task Budget
Action Rate Limit
Organization Quota

共同决定。


56. Security Boundary

DevOS 的主要安全边界:

Browser
   ↓
API
   ↓
Authentication
   ↓
Authorization
   ↓
Action Runtime
   ↓
Domain Runtime
   ↓
Infrastructure

另外:

Agent
Plugin
MCP
Workflow
Scheduler
CLI

都必须重新进入这条边界。


57. 禁止的架构

57.1 UI 直接访问 DB

UI → DB

禁止。


57.2 Agent 直接访问 DB

Agent → Prisma

禁止。


57.3 Plugin 直接读取 Secret DB

Plugin → secret table

禁止。


57.4 MCP 绕过 Action

MCP → Service → DB

禁止。


57.5 Worker 使用超级用户

Worker → admin

禁止。


57.6 API Controller 自己判断权限

禁止散落:

if (user.role === "admin")

应该:

authorization.authorize(...)

58. Security Middleware

建议 Action Runtime Pipeline:

RequestId
 ↓
Authentication
 ↓
SecurityContext
 ↓
Authorization
 ↓
Scope
 ↓
Policy
 ↓
Approval
 ↓
RateLimit
 ↓
Idempotency
 ↓
Audit
 ↓
Action
 ↓
Execution
 ↓
Event

59. Authorization API

建议:

authorization.check()

authorization.require()

authorization.can()

authorization.explain()

例如:

await authorization.require({
  permission: "seo.website.update",
  resource: website,
  context,
})

60. Explain Authorization

开发与管理员必须能够解释:

为什么允许?
为什么拒绝?

例如:

{
  "allowed": false,
  "reason": "Production environment is protected",
  "matchedPermissions": [
    "devops.server.deploy"
  ],
  "matchedPolicies": [
    "production-protection"
  ]
}

但生产环境下对普通用户不要泄漏过多内部安全信息。


61. Audit

所有安全敏感操作必须 Audit:

login
logout
permission.change
role.change
plugin.install
plugin.permission.change
secret.access
secret.rotate
agent.approve
agent.execute
environment.change
api_key.create
api_key.revoke

Audit 必须包含:

actor
target
action
scope
reason
result
timestamp
requestId
executionId

62. Security Event

统一事件:

security.login
security.logout
security.login_failed
security.permission_denied
security.role_changed
security.secret_accessed
security.secret_rotated
security.approval_requested
security.approval_completed
security.api_key_created
security.api_key_revoked

63. Failed Authorization

Permission Denied 不应只返回:

403

系统内部必须记录:

actor
permission
resource
scope
requestId
reason

用于:

  • Security Analytics
  • Audit
  • Incident Detection

64. Security Incident

未来支持:

SecurityIncident

例如:

大量权限失败
大量 API Key 尝试
异常 Agent 行为
异常 Plugin 行为
异常跨 Project 访问
异常 Secret 请求

可触发:

Alert
 ↓
Notification
 ↓
Temporary Block
 ↓
Human Review

65. Database Schema

核心表:

organizations
organization_members

users
sessions
api_keys
service_accounts

roles
permissions
role_permissions
member_roles

policies
policy_bindings

approvals

security_events
audit_logs

resource_permissions
project_members
environment_policies

具体表结构必须与 Data Runtime / Identity Runtime 统一。


66. Permission Cache

Permission 可以缓存:

Redis

但是:

Permission change
 ↓
Cache invalidation

必须可靠。

高风险权限不能依赖无限 TTL。


67. Authorization Cache

缓存 Key:

authz:{actor}:{organization}:{project}:{resource}:{action}

必须包含:

policyVersion
permissionVersion

避免权限更新后旧缓存继续生效。


68. Security Context Snapshot

Task / Execution 创建时记录:

actor
organization
project
environment
permissions
policy version
runtime version

目的:

让历史 Execution 可以解释当时为什么允许执行。


69. Permission Versioning

Permission 变化必须可追踪。

例如:

permissionVersion = 17
policyVersion = 9

Execution:

{
  "permissionVersion": 17,
  "policyVersion": 9
}

70. Environment Isolation

Production:

prod secrets
prod credentials
prod providers
prod tasks
prod files

不能默认被:

development
staging

访问。


71. Credential Isolation

Credential 必须绑定:

organization
project
environment
provider

例如:

OpenAI / Project A / Production

不能自动用于:

Project B

72. Provider Security

Provider Resolver 必须验证:

Actor Permission
Environment
Credential Scope
Provider Policy

73. Network Security

外部请求建议统一经过:

Network / Provider Runtime

而不是 Plugin 自己随意:

fetch(url)

未来可实现:

allowlist
domain policy
SSRF protection
timeout
proxy
audit
rate limit

74. SSRF Protection

所有服务器端 URL 请求必须检查:

http
https

并禁止或严格控制:

127.0.0.1
localhost
0.0.0.0
::1
private networks
link-local
cloud metadata endpoints
unix socket
file://

DNS Rebinding 也必须考虑。


75. Command Execution

DevOS 如果支持:

SSH
Docker
Shell
Process

必须视为:

critical capability

不能直接暴露给 Agent。

必须:

Command Policy
+
Allowlist
+
Environment Policy
+
Approval
+
Audit

76. Dangerous Action

Action Definition 可以声明:

{
  id: "devops.server.restart",

  riskLevel: "high",

  requiresApproval: true,

  allowedActorTypes: [
    "user",
    "agent"
  ]
}

77. Security Metadata

所有 Resource / Action 建议支持:

security: {
  riskLevel,
  sensitive,
  requiresApproval,
  allowedActorTypes,
  allowedScopes,
}

78. UI Security

Frontend:

Permission
 ↓
UI visibility

可以隐藏按钮。

但是:

UI 隐藏绝不能作为真正安全控制。

后端仍必须:

Authorization

79. UI Capability Discovery

前端从后端获取:

available Actions
available Resources
available Commands

而不是自己猜:

if (role === "admin")

80. Agent Capability Discovery

Agent 也只能发现:

当前 Actor
+
当前 Scope
+
当前 Policy

允许使用的 Capability。

禁止:

把所有系统 Action 都暴露给 Agent

81. Progressive Security Disclosure

Capability Discovery 推荐:

Level 1

seo.website.scan

Level 2

description
input schema
risk

Level 3

full instructions

Level 4

execution

安全与 Token 优化同时实现。


82. Security Testing

必须测试:

Authentication
Authorization
Tenant Isolation
Project Isolation
Environment Isolation
Agent Delegation
Plugin Permission
MCP Permission
Secret Isolation
File Isolation
Task Isolation
Event Isolation
Webhook Security
SSRF
IDOR
Rate Limit
Approval
Audit

83. 必须存在的 Tenant Isolation Tests

例如:

Organization A
Organization B

测试:

A user cannot read B resource
A user cannot update B resource
A agent cannot execute B task
A plugin cannot access B secret
A webhook cannot access B artifact
A search cannot return B resource

84. Authorization Contract Test

每个 Action 必须至少测试:

authorized user
unauthorized user
wrong organization
wrong project
wrong environment
expired session
disabled account
agent without delegation
plugin without permission
MCP without permission

85. Security Regression Tests

每次修改以下模块必须运行完整 Security Suite:

identity
authorization
action
resource
data
config
secret
plugin
mcp
agent
task
event
storage

86. Architecture Lint

必须增加架构规则:

禁止:

ui → prisma
agent → prisma
plugin → prisma
mcp → prisma

ui → redis
agent → redis
plugin → redis

plugin → secret table
agent → secret table

允许:

Runtime → Prisma
Runtime → Redis
Runtime → Secret

87. Package Boundary

建议:

packages/security/
packages/identity/
packages/authorization/
packages/policy/
packages/approval/
packages/tenancy/

依赖关系:

identity
   ↓
security
   ↓
authorization
   ↓
policy
   ↓
action-runtime

而:

domain

只能依赖:

security abstractions

不能依赖:

具体认证数据库实现

88. Security Runtime API

建议最终统一为:

security.authenticate()

security.getContext()

authorization.check()

authorization.require()

authorization.can()

authorization.explain()

policy.evaluate()

scope.resolve()

approval.request()

approval.require()

tenant.resolve()

environment.authorize()

89. Zcode 实施规则

Zcode 修改 DevOS 时:

Rule 1

不得创建第二套:

Auth
RBAC
Permission
Tenant
Policy
Approval

Rule 2

发现已有权限系统:

保留可复用部分
→ 迁移到 Security Runtime

不要简单删除。


Rule 3

任何新增 Action:

必须定义:

permission
riskLevel
scope
approval

Rule 4

任何新增 Resource:

必须定义:

organization scope
project scope
environment scope

根据实际需要选择。


Rule 5

任何新增 Plugin:

必须定义:

permissions
scopes
risk

Rule 6

任何新增 MCP:

必须定义:

identity
permissions
scope

Rule 7

任何 Agent Capability:

必须经过:

Capability Registry
+
Authorization

Rule 8

不得为了“方便”创建:

admin()
sudo()
rootContext()
bypassAuth()
skipPermission()

之类生产代码。

测试环境也必须明确标识。


90. Emergency Break Glass

生产环境可以存在:

Break Glass

但必须:

极少数用户
+
强认证
+
短时有效
+
强制 Audit
+
自动告警

禁止普通管理员默认拥有。


91. Security Configuration

例如:

security:
  defaultDeny: true

  sessions:
    maxLifetime: 30d

  apiKeys:
    maxLifetime: 365d

  production:
    requireApproval: true

  agents:
    requireDelegation: true

  plugins:
    requirePermissionApproval: true

  mcp:
    requireAuthentication: true

  secrets:
    redactLogs: true

  webhooks:
    requireSignature: true

92. Security Health Check

系统启动时检查:

JWT secret
encryption key
session config
database TLS
Redis security
object storage security
production protection
secret provider
audit storage

发现严重问题:

FAIL

不能仅 Warning。


93. Security Doctor

CLI:

devos security doctor

检查:

✓ Authentication
✓ Authorization
✓ Tenant isolation
✓ Secret encryption
✓ Production protection
✓ API key hashing
✓ Webhook signing
✓ SSRF protection
✓ Audit
✓ Security headers

94. Security Headers

Web/API 默认考虑:

CSP
HSTS
X-Content-Type-Options
Referrer-Policy
Frame protection

具体策略根据部署模式配置。


95. CORS

禁止:

Access-Control-Allow-Origin: *

用于需要认证的生产 API。

必须通过:

Allowed Origins

明确控制。


96. CSRF

Cookie Session 模式必须支持:

CSRF protection

Bearer Token API 根据认证模式决定是否需要。


97. Password Security

如果 DevOS 自己管理密码:

必须:

Argon2id

优先。

禁止:

MD5
SHA1
plaintext

密码不得出现在:

logs
events
audit
traces

98. Account Lock / Abuse

支持:

failed login detection
rate limiting
temporary lock
security notification

不要仅依赖:

IP

也要考虑:

account
device/session
token

99. Security Audit UI

UI:

Settings
 └── Security
      ├── Sessions
      ├── API Keys
      ├── Service Accounts
      ├── Roles
      ├── Permissions
      ├── Policies
      ├── Approvals
      ├── Security Events
      └── Audit Logs

100. Project Security UI

Project:

Project
 └── Security
      ├── Members
      ├── Roles
      ├── Agents
      ├── Plugins
      ├── MCP
      ├── Credentials
      ├── Environments
      └── Policies

101. Environment Security UI

Production:

Production
 ├── Protected
 ├── Approval Required
 ├── Credentials
 ├── Secrets
 ├── Allowed Agents
 └── Allowed Plugins

102. Plugin Security UI

Plugin 页面显示:

Plugin
 ├── Permissions
 ├── Scope
 ├── Risk
 ├── Credentials
 ├── Network Access
 ├── Actions
 ├── MCP
 └── Audit

用户必须能够知道:

这个 Plugin 到底能做什么。


103. Agent Security UI

Agent 页面:

Agent
 ├── Identity
 ├── Permissions
 ├── Delegations
 ├── Allowed Projects
 ├── Allowed Environments
 ├── Skills
 ├── Capabilities
 ├── Budget
 └── Audit

104. Security Trace

一次执行:

User
 ↓
Goal
 ↓
Agent
 ↓
Skill
 ↓
Capability
 ↓
Permission
 ↓
Policy
 ↓
Approval
 ↓
Action
 ↓
Execution

必须可以追踪。


105. 完整 Security Decision Trace

例如:

{
  "actor": "agent:seo-operator",

  "delegatedBy": "user:123",

  "organizationId": "org-1",

  "projectId": "project-1",

  "environmentId": "production",

  "action": "seo.website.publish",

  "permission": "seo.website.publish",

  "permissionGranted": true,

  "policyAllowed": false,

  "approvalRequired": true,

  "approvalId": "approval-123"
}

106. Security 与 Observability

Security Runtime 必须使用统一:

requestId
correlationId
traceId
executionId
taskId
jobId
actorId
organizationId
projectId
environmentId

不得建立第二套 Trace ID。


107. Security 与 Event Runtime

Security Event:

Security Runtime
 ↓
Event Runtime

而不是自己创建:

security-event-bus

避免重复基础设施。


108. Security 与 Audit Runtime

Security Audit:

Security
 ↓
Audit Runtime

不要建立第二套 Audit Database。


109. Security 与 Data Runtime

所有 Resource Query:

Data Runtime
 ↓
Scope Runtime
 ↓
Authorization

确保:

搜索
查询
导出
统计

都不会绕过 Tenant Scope。


110. Search Security

Global Search 必须应用:

Actor Permission
+
Organization Scope
+
Project Scope
+
Resource Policy

搜索结果不能成为权限泄漏渠道。


111. Export Security

Export 是高风险读取操作。

必须:

permission
scope
field permission
sensitive field policy
audit

大规模 Export:

Task
 ↓
Job
 ↓
Worker

并继承 Security Context。


112. Import Security

Import 必须检查:

file
schema
resource permission
field permission
scope
validation

不能因为上传 CSV 就绕过 Action Runtime。


113. Cache Security

缓存不能跨 Tenant 污染。

错误:

cache:website:{id}

如果 ID 可能被错误访问。

推荐:

cache:{organization}:{project}:website:{id}

并结合 Scope。


114. Redis Security

Redis 中不得保存:

plaintext secrets
passwords
long-lived credentials

可以保存:

session metadata
locks
queue data
temporary authorization cache

但必须有 TTL 与隔离策略。


115. Object Storage Security

默认:

private

只有通过 Storage Runtime 获取:

signed URL

才允许访问。


116. Security Defaults

DevOS 默认:

deny
private
short-lived
scoped
audited
approval-sensitive

而不是:

allow
public
long-lived
global
silent

117. Definition of Done

Security Runtime 阶段必须完成:

  • Authentication
  • SecurityContext
  • Permission Registry
  • Role
  • Authorization
  • Policy
  • Scope
  • Organization
  • Project Scope
  • Environment Scope
  • Approval
  • Agent Delegation
  • Plugin Permission
  • MCP Permission
  • Secret Protection
  • File Scope
  • Task Scope
  • Event Scope
  • Audit
  • Security Events
  • Rate Limit
  • SSRF Protection
  • IDOR Tests
  • Tenant Isolation Tests
  • Architecture Boundary Tests

118. Security Contract Tests

必须建立:

security.contract.spec.ts
authorization.contract.spec.ts
tenant-isolation.contract.spec.ts
agent-delegation.contract.spec.ts
plugin-security.contract.spec.ts
mcp-security.contract.spec.ts
secret-isolation.contract.spec.ts
environment-isolation.contract.spec.ts

119. 最低验收场景

必须通过:

Scenario 1

User A:

Org A

不能读取:

Org B

Scenario 2

Agent A:

Project A

不能执行:

Project B

Scenario 3

Plugin A:

没有:

secret.read

不能获取 Secret。


Scenario 4

MCP:

没有:

server.restart

不能调用。


Scenario 5

Agent:

拥有:

deploy

但 Production:

approval required

必须进入 Approval。


Scenario 6

用户拥有:

resource.read

但 Resource 不属于当前 Project:

DENY

Scenario 7

Search:

不能返回其他 Organization 数据。


Scenario 8

Export:

不能导出当前 Actor 无权读取的字段。


120. Security CI Gate

CI 必须至少执行:

pnpm lint
pnpm typecheck
pnpm test
pnpm test:security
pnpm test:contract
pnpm test:e2e

安全相关代码发生变化时:

Security Suite = Mandatory

不能允许:

test skipped

进入生产。


121. Zcode Security Implementation Protocol

Zcode 实现任何功能时必须执行:

1. Identify Actor
2. Identify Organization
3. Identify Project
4. Identify Environment
5. Identify Resource
6. Identify Action
7. Identify Permission
8. Identify Policy
9. Identify Scope
10. Identify Risk
11. Identify Approval
12. Implement
13. Add Contract Test
14. Add Tenant Isolation Test
15. Add Audit
16. Run Security Gate

122. Zcode 禁止事项

禁止 Zcode:

创建第二套 RBAC
创建第二套 Tenant System
创建第二套 Permission System
创建第二套 Audit
创建第二套 Approval
创建第二套 Secret Access
创建超级 Agent
创建万能 Plugin Token
创建 bypassAuth()
创建 skipPermission()
创建 rootContext()

123. Zcode Master Security Prompt

以后可以直接将以下内容作为 Zcode 的安全实施规则:

DEVOS SECURITY MASTER PROTOCOL

You are implementing code inside the DevOS platform.

Security is a Runtime concern, not a UI concern.

Before implementing any feature:

1. Identify the Actor.
2. Identify Organization scope.
3. Identify Project scope.
4. Identify Environment scope.
5. Identify Resource.
6. Identify Action.
7. Identify required Permission.
8. Identify Policy constraints.
9. Identify risk level.
10. Determine whether Approval is required.
11. Route execution through Action Runtime.
12. Preserve SecurityContext.
13. Preserve tenant/project/environment scope.
14. Record semantic Audit.
15. Emit required Security/Event records.
16. Add authorization contract tests.
17. Add cross-tenant isolation tests.
18. Add wrong-project tests.
19. Add wrong-environment tests.
20. Add Agent/Plugin/MCP boundary tests where applicable.

Never:

- access database directly from UI;
- access database directly from Agent;
- access database directly from Plugin;
- access secrets directly from Plugin;
- bypass Action Runtime from MCP;
- create a second authorization system;
- create a second tenant system;
- create a superuser Agent;
- use plaintext API keys;
- log secrets;
- expose private storage directly;
- trust UI permission checks;
- use role-name conditionals as the primary authorization mechanism;
- create bypassAuth(), sudo(), rootContext(), or skipPermission().

Default security posture:

DENY
PRIVATE
SCOPED
AUDITED
SHORT-LIVED
LEAST-PRIVILEGE

Human, Agent, Plugin, MCP, Workflow, Scheduler and API must all use the same Security + Action Runtime.

If an existing security implementation exists, audit it first and migrate/reuse it where possible.

Do not introduce duplicate infrastructure.
Do not make architectural changes outside the current bounded task.

124. 最终架构

DevOS 安全体系最终形成:

                    Actor
                      ↓
               Authentication
                      ↓
               SecurityContext
                      ↓
        ┌─────────────────────────┐
        │ Authorization Runtime  │
        │                         │
        │ Permission              │
        │ Role                    │
        │ Policy                  │
        │ Scope                   │
        │ Risk                    │
        │ Approval                │
        └────────────┬────────────┘
                     ↓
              Capability
                     ↓
                  Action
                     ↓
             Action Runtime
                     ↓
                Execution
                     ↓
        ┌────────────┼────────────┐
        ↓            ↓            ↓
      Task          Event       Audit
        ↓            ↓            ↓
      Worker      Notification Security

125. DevOS Security Golden Rule

任何人、任何 Agent、任何 Plugin、任何 MCP、任何 Workflow、任何 Scheduler、任何 API,都必须在相同的 Security Context + Authorization + Scope + Policy 下,通过统一 Action Runtime 执行。

进一步:

没有 Scope 的 Permission 不完整;没有 Authorization 的 Capability 不可执行;没有 Audit 的高风险 Execution 不完整。

最终必须保证:

WHO
  ↓
CAN DO WHAT
  ↓
ON WHICH RESOURCE
  ↓
IN WHICH SCOPE
  ↓
UNDER WHICH POLICY
  ↓
WITH WHICH APPROVAL
  ↓
EXECUTED HOW
  ↓
AUDITED WHERE

这就是 DevOS 的统一安全模型。