# 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 的平台。** 因此安全模型必须保证: ```text 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 总体架构 ```text ┌──────────────┐ │ Authentication│ └──────┬───────┘ ↓ ┌──────────────┐ │ Security │ │ Context │ └──────┬───────┘ ↓ ┌──────────────────────────┐ │ Authorization Runtime │ │ │ │ Permission │ │ Role │ │ Policy │ │ Scope │ │ Resource Access │ └────────────┬─────────────┘ ↓ ┌───────────────┐ │ Action Runtime│ └───────┬───────┘ ↓ Execution ``` --- # 4. Security Context 所有 Runtime 操作必须携带统一 Security Context。 ```ts 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 } ``` 禁止: ```ts someService.doSomething(userId) ``` 推荐: ```ts someService.doSomething({ securityContext, ... }) ``` --- # 5. Actor 模型 DevOS 的 Actor 不只是 User。 ```ts type ActorType = | "user" | "agent" | "plugin" | "mcp" | "workflow" | "scheduler" | "service" | "system" ``` 统一: ```ts interface ActorIdentity { id: string type: ActorType organizationId?: string displayName?: string } ``` --- # 6. 最重要的安全规则 ## Agent 不是超级用户 绝对禁止: ```text Agent ↓ Database ``` 也禁止: ```text Agent ↓ Redis ``` 以及: ```text Agent ↓ Filesystem ``` Agent 必须: ```text Agent ↓ Capability ↓ Action ↓ Action Runtime ↓ Authorization ↓ Execution ``` --- # 7. Plugin 不是可信代码 Plugin 默认视为: > **半可信扩展。** Plugin 必须声明: ```yaml permissions: - seo.website.read - seo.website.scan ``` 而不是: ```yaml permissions: - * ``` 默认拒绝。 --- # 8. MCP 不是安全边界 MCP 只是能力访问协议。 禁止: ```text MCP ↓ Internal Service ``` 绕过: ```text Authorization Action Runtime Audit ``` 正确: ```text MCP ↓ Capability ↓ Action ↓ Authorization ↓ Action Runtime ``` --- # 9. Multi-Tenancy 模型 DevOS 使用层级 Scope: ```text Global ↓ Organization ↓ Project ↓ Environment ↓ Resource ``` 例如: ```text Organization A ├── Project SEO-A │ ├── dev │ ├── staging │ └── production │ └── Project CRM-A ├── dev └── production ``` --- # 10. Organization Organization 是主要租户边界。 ```ts interface Organization { id: string name: string status: "active" | "suspended" | "deleted" } ``` 所有组织级资源必须带: ```text organizationId ``` --- # 11. Project Project 是业务隔离与执行隔离单位。 ```ts interface Project { id: string organizationId: string name: string } ``` Project 不允许跨 Organization。 --- # 12. Environment Environment: ```text development staging production ``` 必须独立。 尤其: ```text production ``` 不能因为 Agent 或 Plugin 请求而自动获得。 --- # 13. Environment Protection 生产环境必须支持: ```yaml production: protected: true requireApproval: true allowAgentDirectExecution: false ``` 高风险操作: ```text delete deploy rotate-secret publish send billing dns-change database-migration ``` 默认进入 Approval 流程。 --- # 14. Permission 模型 Permission 使用: ```text .. ``` 例如: ```text 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: ```text seo.website.scan ``` Permission: ```text seo.website.scan ``` 通常可以一一对应,但概念必须保持独立。 Action 是执行能力。 Permission 是访问控制。 --- # 16. Permission Registry 建立统一: ```text PermissionRegistry ``` 负责: - 注册 - 查询 - 描述 - 分类 - 风险等级 - 默认策略 - 兼容性 例如: ```ts interface PermissionDefinition { id: string description: string resource: string action: string riskLevel: | "low" | "medium" | "high" | "critical" requiresApproval: boolean } ``` --- # 17. Role Role 是 Permission 集合。 例如: ```text Owner Admin Developer Operator Viewer Agent Operator ``` ```ts interface Role { id: string name: string permissions: string[] } ``` --- # 18. Role 不应该硬编码 禁止: ```ts if (user.role === "admin") { ... } ``` 推荐: ```ts authorization.require( "devops.server.deploy" ) ``` 原因: 未来必须支持: - Custom Role - Organization Role - Project Role - Agent Role - Plugin Role - Temporary Role --- # 19. Policy RBAC 不足以表达: ```text User 可以 deploy 但是: production 不允许直接 deploy ``` 因此需要 Policy Runtime。 例如: ```ts interface AuthorizationPolicy { id: string evaluate( context: AuthorizationContext ): PolicyDecision } ``` 结果: ```ts type PolicyDecision = | { effect: "allow" } | { effect: "deny" reason: string } | { effect: "approval_required" reason: string } ``` --- # 20. Authorization Decision 统一: ```ts interface AuthorizationDecision { allowed: boolean requiresApproval: boolean reason?: string matchedPermissions: string[] matchedPolicies: string[] scope: ScopeContext } ``` --- # 21. Authorization 流程 所有 Action: ```text Request ↓ Authentication ↓ Build Security Context ↓ Permission Check ↓ Resource Check ↓ Scope Check ↓ Policy Check ↓ Approval Check ↓ Rate Limit ↓ Action Runtime ``` --- # 22. Default Deny 任何没有明确允许的操作: ```text DENY ``` 禁止: ```ts if (!permission) { return true } ``` --- # 23. Resource-Level Authorization 不仅判断: ```text can update website ``` 还必须判断: ```text can update THIS website ``` 例如: ```text User ├── Project A │ └── Website A │ └── Project B └── Website B ``` User 有: ```text seo.website.update ``` 不代表可以: ```text Website B ``` --- # 24. Scope Provider 建立: ```ts interface ScopeProvider { resolve( context: SecurityContext, resource: ResourceDefinition ): ScopeConstraint } ``` 例如自动注入: ```sql organization_id = $organizationId AND project_id = $projectId ``` 业务代码不应该手工到处写: ```ts where: { organizationId, projectId } ``` 应该由 Data Runtime + Scope Runtime 统一处理。 --- # 25. Database Multi-Tenancy 所有 Tenant Resource 必须具备: ```text organizationId ``` Project Resource: ```text organizationId projectId ``` Environment Resource: ```text organizationId projectId environmentId ``` --- # 26. PostgreSQL Row-Level Security DevOS 第一阶段可以使用: ```text Application-level scope enforcement ``` 但架构必须为 PostgreSQL RLS 留出空间。 高安全部署可以启用: ```text PostgreSQL RLS ``` 形成: ```text Application Authorization + Data Runtime Scope + Database RLS ``` 三层防护。 --- # 27. Cross-Tenant Protection 绝对禁止: ```http GET /api/websites/:id ``` 直接: ```sql SELECT * FROM websites WHERE id = $id ``` 必须: ```text id + organization scope + project scope + permission ``` --- # 28. IDOR 防护 所有资源 ID 都必须经过 Scope 验证。 例如: ```text GET /api/projects/project-B ``` 如果当前 Actor 属于: ```text Organization A ``` 而 Project B 属于: ```text Organization B ``` 必须: ```text 404 ``` 或: ```text 403 ``` 具体选择由 API Security Policy 决定。 对外 API 推荐尽量避免泄漏资源存在性。 --- # 29. Authentication 支持: ```text Session JWT API Key Service Token OAuth/OIDC MCP Auth CLI Token ``` 但所有认证方式最终转换成: ```text ActorIdentity + SecurityContext ``` --- # 30. Session Session Runtime: ```ts 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 必须: ```text hash only ``` 数据库不能保存: ```text plaintext API key ``` 展示: ```text sk_live_•••••••••• ``` 创建后原则上只展示一次。 --- # 33. Service Account 系统间调用使用: ```text Service Account ``` 而不是共享管理员账号。 例如: ```text devos-worker devos-mcp devos-agent devos-scheduler ``` 每个 Service Account 使用最小权限。 --- # 34. Least Privilege 默认原则: ```text Minimum permission + Minimum scope + Minimum lifetime ``` 尤其针对: - Agent - Plugin - MCP - Service - API Key --- # 35. Agent Permission Agent 应拥有: ```text Agent Identity ``` 例如: ```text agent:seo-operator ``` 它拥有: ```text seo.website.read seo.website.scan seo.keyword.search ``` 不应该拥有: ```text core.user.delete billing.refund secret.read ``` 除非显式授权。 --- # 36. Agent Delegation 用户可以: ```text User ↓ Delegate Goal ↓ Agent ``` Agent 的权限不能超过用户授权边界。 默认: ```text AgentPermission = Intersection( AgentPolicy, UserDelegatedPermission, ProjectScope ) ``` --- # 37. Agent Approval 高风险操作: ```text Agent ↓ Action ↓ Approval Required ↓ Human ↓ Approve ↓ Execution ``` Agent 不允许自行批准自己的操作。 --- # 38. Approval Runtime 建议: ```text packages/approval/ ``` 定义: ```ts interface ApprovalRequest { id: string actionId: string executionId: string actorId: string organizationId: string projectId?: string environmentId?: string reason: string riskLevel: string expiresAt: Date } ``` 状态: ```text pending approved rejected expired cancelled ``` --- # 39. Approval 不等于 Permission 两者不同: ```text Permission: 允许不允许? Approval: 这一次是否需要人工确认? ``` 即: ```text Permission = capability authorization Approval = execution authorization ``` --- # 40. Secret Security Secret Runtime 必须遵守: ```text Agent Plugin MCP UI Log Event Audit ``` 默认都不能看到 Secret 明文。 --- # 41. Secret Access Secret 使用: ```text secret://provider/name ``` 执行时: ```text Secret Reference ↓ Authorization ↓ Secret Runtime ↓ Decrypt ↓ Memory ↓ Provider ``` 明文生命周期尽可能短。 --- # 42. Secret Leak Protection 以下内容必须自动 Redact: ```text API Keys Tokens Passwords Private Keys OAuth Secrets Cookie Authorization Headers Connection Strings ``` 所有: ```text Log Trace Event Audit Error Task Output Agent Observation ``` 必须执行 Secret Redaction。 --- # 43. File Security File Runtime 必须检查: ```text Actor Organization Project Environment Permission File visibility ``` 禁止: ```text /download/:fileId ``` 直接暴露 Object Storage URL。 使用: ```text Signed URL ``` 并限制: ```text TTL scope method content-type ``` --- # 44. Task Security Task 必须保存: ```text organizationId projectId environmentId actorId ``` Worker 执行 Task 时恢复完整 Security Context。 禁止 Worker: ```text system user ``` 执行所有任务。 --- # 45. Job Security Job 继承 Task Scope: ```text Task ↓ Job ↓ Execution ``` 必须保证: ```text Job.organizationId = Task.organizationId ``` 不能通过修改 Job 数据扩大权限。 --- # 46. Event Security Event Payload 可能包含敏感信息。 因此 Event 定义: ```ts interface EventDefinition { id: string visibility: | "public" | "organization" | "project" | "internal" sensitiveFields?: string[] } ``` --- # 47. Event Subscriber Authorization Subscriber 不因为订阅了 Event 就自动获得全部 Payload。 必须: ```text Subscribe Permission + Event Visibility + Scope ``` --- # 48. Webhook Security Webhook 必须: ```text HMAC signature timestamp nonce/idempotency retry timeout ``` 同时必须防止: ```text SSRF private IP access localhost access metadata endpoint access ``` --- # 49. MCP Security MCP Server 必须注册: ```text MCP Identity ``` 每一个 MCP Capability 必须声明: ```yaml permissions: - seo.website.read ``` MCP Tool 调用: ```text MCP Request ↓ Authenticate ↓ Resolve Actor ↓ Capability ↓ Authorization ↓ Action ↓ Execution ``` --- # 50. Plugin Security Plugin Manifest: ```yaml id: example.plugin permissions: - seo.website.read - seo.website.scan scopes: - organization - project network: allowed: - api.example.com ``` 未来可以支持更细粒度: ```text filesystem network process database secret ``` --- # 51. Plugin Permission Approval 安装 Plugin 时: ```text Plugin Manifest ↓ Permission Review ↓ Risk Analysis ↓ User Approval ↓ Install ``` Plugin 请求新增高权限时: ```text Upgrade ↓ Permission Diff ↓ Re-approval ``` --- # 52. Capability Risk Level 每个 Action 建议拥有: ```text low medium high critical ``` 例如: ```text website.read low website.scan low website.update medium dns.update high server.restart high server.delete critical secret.rotate critical ``` --- # 53. Security Policy 建立: ```text SecurityPolicyRuntime ``` 负责: - IP policy - Environment policy - Agent policy - Plugin policy - MCP policy - Rate policy - Approval policy - Data access policy - Secret policy --- # 54. Rate Limit 安全层必须统一支持: ```text per user per organization per project per IP per token per plugin per agent per action ``` 例如: ```text seo.website.scan ``` 可以: ```text 100 / hour / project ``` --- # 55. Abuse Protection 针对 Agent / MCP 尤其需要: ```text max iterations max actions max task count max execution time max cost max network calls ``` 这些限制由: ```text Agent Budget Task Budget Action Rate Limit Organization Quota ``` 共同决定。 --- # 56. Security Boundary DevOS 的主要安全边界: ```text Browser ↓ API ↓ Authentication ↓ Authorization ↓ Action Runtime ↓ Domain Runtime ↓ Infrastructure ``` 另外: ```text Agent Plugin MCP Workflow Scheduler CLI ``` 都必须重新进入这条边界。 --- # 57. 禁止的架构 ## 57.1 UI 直接访问 DB ```text UI → DB ``` 禁止。 --- ## 57.2 Agent 直接访问 DB ```text Agent → Prisma ``` 禁止。 --- ## 57.3 Plugin 直接读取 Secret DB ```text Plugin → secret table ``` 禁止。 --- ## 57.4 MCP 绕过 Action ```text MCP → Service → DB ``` 禁止。 --- ## 57.5 Worker 使用超级用户 ```text Worker → admin ``` 禁止。 --- ## 57.6 API Controller 自己判断权限 禁止散落: ```ts if (user.role === "admin") ``` 应该: ```ts authorization.authorize(...) ``` --- # 58. Security Middleware 建议 Action Runtime Pipeline: ```text RequestId ↓ Authentication ↓ SecurityContext ↓ Authorization ↓ Scope ↓ Policy ↓ Approval ↓ RateLimit ↓ Idempotency ↓ Audit ↓ Action ↓ Execution ↓ Event ``` --- # 59. Authorization API 建议: ```ts authorization.check() authorization.require() authorization.can() authorization.explain() ``` 例如: ```ts await authorization.require({ permission: "seo.website.update", resource: website, context, }) ``` --- # 60. Explain Authorization 开发与管理员必须能够解释: ```text 为什么允许? 为什么拒绝? ``` 例如: ```json { "allowed": false, "reason": "Production environment is protected", "matchedPermissions": [ "devops.server.deploy" ], "matchedPolicies": [ "production-protection" ] } ``` 但生产环境下对普通用户不要泄漏过多内部安全信息。 --- # 61. Audit 所有安全敏感操作必须 Audit: ```text 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 必须包含: ```text actor target action scope reason result timestamp requestId executionId ``` --- # 62. Security Event 统一事件: ```text 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 不应只返回: ```text 403 ``` 系统内部必须记录: ```text actor permission resource scope requestId reason ``` 用于: - Security Analytics - Audit - Incident Detection --- # 64. Security Incident 未来支持: ```text SecurityIncident ``` 例如: ```text 大量权限失败 大量 API Key 尝试 异常 Agent 行为 异常 Plugin 行为 异常跨 Project 访问 异常 Secret 请求 ``` 可触发: ```text Alert ↓ Notification ↓ Temporary Block ↓ Human Review ``` --- # 65. Database Schema 核心表: ```text 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 可以缓存: ```text Redis ``` 但是: ```text Permission change ↓ Cache invalidation ``` 必须可靠。 高风险权限不能依赖无限 TTL。 --- # 67. Authorization Cache 缓存 Key: ```text authz:{actor}:{organization}:{project}:{resource}:{action} ``` 必须包含: ```text policyVersion permissionVersion ``` 避免权限更新后旧缓存继续生效。 --- # 68. Security Context Snapshot Task / Execution 创建时记录: ```text actor organization project environment permissions policy version runtime version ``` 目的: > 让历史 Execution 可以解释当时为什么允许执行。 --- # 69. Permission Versioning Permission 变化必须可追踪。 例如: ```text permissionVersion = 17 policyVersion = 9 ``` Execution: ```json { "permissionVersion": 17, "policyVersion": 9 } ``` --- # 70. Environment Isolation Production: ```text prod secrets prod credentials prod providers prod tasks prod files ``` 不能默认被: ```text development staging ``` 访问。 --- # 71. Credential Isolation Credential 必须绑定: ```text organization project environment provider ``` 例如: ```text OpenAI / Project A / Production ``` 不能自动用于: ```text Project B ``` --- # 72. Provider Security Provider Resolver 必须验证: ```text Actor Permission Environment Credential Scope Provider Policy ``` --- # 73. Network Security 外部请求建议统一经过: ```text Network / Provider Runtime ``` 而不是 Plugin 自己随意: ```ts fetch(url) ``` 未来可实现: ```text allowlist domain policy SSRF protection timeout proxy audit rate limit ``` --- # 74. SSRF Protection 所有服务器端 URL 请求必须检查: ```text http https ``` 并禁止或严格控制: ```text 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 如果支持: ```text SSH Docker Shell Process ``` 必须视为: ```text critical capability ``` 不能直接暴露给 Agent。 必须: ```text Command Policy + Allowlist + Environment Policy + Approval + Audit ``` --- # 76. Dangerous Action Action Definition 可以声明: ```ts { id: "devops.server.restart", riskLevel: "high", requiresApproval: true, allowedActorTypes: [ "user", "agent" ] } ``` --- # 77. Security Metadata 所有 Resource / Action 建议支持: ```ts security: { riskLevel, sensitive, requiresApproval, allowedActorTypes, allowedScopes, } ``` --- # 78. UI Security Frontend: ```text Permission ↓ UI visibility ``` 可以隐藏按钮。 但是: > UI 隐藏绝不能作为真正安全控制。 后端仍必须: ```text Authorization ``` --- # 79. UI Capability Discovery 前端从后端获取: ```text available Actions available Resources available Commands ``` 而不是自己猜: ```ts if (role === "admin") ``` --- # 80. Agent Capability Discovery Agent 也只能发现: ```text 当前 Actor + 当前 Scope + 当前 Policy ``` 允许使用的 Capability。 禁止: ```text 把所有系统 Action 都暴露给 Agent ``` --- # 81. Progressive Security Disclosure Capability Discovery 推荐: ### Level 1 ```text seo.website.scan ``` ### Level 2 ```text description input schema risk ``` ### Level 3 ```text full instructions ``` ### Level 4 ```text execution ``` 安全与 Token 优化同时实现。 --- # 82. Security Testing 必须测试: ```text 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 例如: ```text Organization A Organization B ``` 测试: ```text 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 必须至少测试: ```text 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: ```text identity authorization action resource data config secret plugin mcp agent task event storage ``` --- # 86. Architecture Lint 必须增加架构规则: 禁止: ```text ui → prisma agent → prisma plugin → prisma mcp → prisma ui → redis agent → redis plugin → redis plugin → secret table agent → secret table ``` 允许: ```text Runtime → Prisma Runtime → Redis Runtime → Secret ``` --- # 87. Package Boundary 建议: ```text packages/security/ packages/identity/ packages/authorization/ packages/policy/ packages/approval/ packages/tenancy/ ``` 依赖关系: ```text identity ↓ security ↓ authorization ↓ policy ↓ action-runtime ``` 而: ```text domain ``` 只能依赖: ```text security abstractions ``` 不能依赖: ```text 具体认证数据库实现 ``` --- # 88. Security Runtime API 建议最终统一为: ```ts 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 不得创建第二套: ```text Auth RBAC Permission Tenant Policy Approval ``` --- ### Rule 2 发现已有权限系统: ```text 保留可复用部分 → 迁移到 Security Runtime ``` 不要简单删除。 --- ### Rule 3 任何新增 Action: 必须定义: ```text permission riskLevel scope approval ``` --- ### Rule 4 任何新增 Resource: 必须定义: ```text organization scope project scope environment scope ``` 根据实际需要选择。 --- ### Rule 5 任何新增 Plugin: 必须定义: ```text permissions scopes risk ``` --- ### Rule 6 任何新增 MCP: 必须定义: ```text identity permissions scope ``` --- ### Rule 7 任何 Agent Capability: 必须经过: ```text Capability Registry + Authorization ``` --- ### Rule 8 不得为了“方便”创建: ```text admin() sudo() rootContext() bypassAuth() skipPermission() ``` 之类生产代码。 测试环境也必须明确标识。 --- # 90. Emergency Break Glass 生产环境可以存在: ```text Break Glass ``` 但必须: ```text 极少数用户 + 强认证 + 短时有效 + 强制 Audit + 自动告警 ``` 禁止普通管理员默认拥有。 --- # 91. Security Configuration 例如: ```yaml 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 系统启动时检查: ```text JWT secret encryption key session config database TLS Redis security object storage security production protection secret provider audit storage ``` 发现严重问题: ```text FAIL ``` 不能仅 Warning。 --- # 93. Security Doctor CLI: ```bash devos security doctor ``` 检查: ```text ✓ Authentication ✓ Authorization ✓ Tenant isolation ✓ Secret encryption ✓ Production protection ✓ API key hashing ✓ Webhook signing ✓ SSRF protection ✓ Audit ✓ Security headers ``` --- # 94. Security Headers Web/API 默认考虑: ```text CSP HSTS X-Content-Type-Options Referrer-Policy Frame protection ``` 具体策略根据部署模式配置。 --- # 95. CORS 禁止: ```text Access-Control-Allow-Origin: * ``` 用于需要认证的生产 API。 必须通过: ```text Allowed Origins ``` 明确控制。 --- # 96. CSRF Cookie Session 模式必须支持: ```text CSRF protection ``` Bearer Token API 根据认证模式决定是否需要。 --- # 97. Password Security 如果 DevOS 自己管理密码: 必须: ```text Argon2id ``` 优先。 禁止: ```text MD5 SHA1 plaintext ``` 密码不得出现在: ```text logs events audit traces ``` --- # 98. Account Lock / Abuse 支持: ```text failed login detection rate limiting temporary lock security notification ``` 不要仅依赖: ```text IP ``` 也要考虑: ```text account device/session token ``` --- # 99. Security Audit UI UI: ```text Settings └── Security ├── Sessions ├── API Keys ├── Service Accounts ├── Roles ├── Permissions ├── Policies ├── Approvals ├── Security Events └── Audit Logs ``` --- # 100. Project Security UI Project: ```text Project └── Security ├── Members ├── Roles ├── Agents ├── Plugins ├── MCP ├── Credentials ├── Environments └── Policies ``` --- # 101. Environment Security UI Production: ```text Production ├── Protected ├── Approval Required ├── Credentials ├── Secrets ├── Allowed Agents └── Allowed Plugins ``` --- # 102. Plugin Security UI Plugin 页面显示: ```text Plugin ├── Permissions ├── Scope ├── Risk ├── Credentials ├── Network Access ├── Actions ├── MCP └── Audit ``` 用户必须能够知道: > 这个 Plugin 到底能做什么。 --- # 103. Agent Security UI Agent 页面: ```text Agent ├── Identity ├── Permissions ├── Delegations ├── Allowed Projects ├── Allowed Environments ├── Skills ├── Capabilities ├── Budget └── Audit ``` --- # 104. Security Trace 一次执行: ```text User ↓ Goal ↓ Agent ↓ Skill ↓ Capability ↓ Permission ↓ Policy ↓ Approval ↓ Action ↓ Execution ``` 必须可以追踪。 --- # 105. 完整 Security Decision Trace 例如: ```json { "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 必须使用统一: ```text requestId correlationId traceId executionId taskId jobId actorId organizationId projectId environmentId ``` 不得建立第二套 Trace ID。 --- # 107. Security 与 Event Runtime Security Event: ```text Security Runtime ↓ Event Runtime ``` 而不是自己创建: ```text security-event-bus ``` 避免重复基础设施。 --- # 108. Security 与 Audit Runtime Security Audit: ```text Security ↓ Audit Runtime ``` 不要建立第二套 Audit Database。 --- # 109. Security 与 Data Runtime 所有 Resource Query: ```text Data Runtime ↓ Scope Runtime ↓ Authorization ``` 确保: ```text 搜索 查询 导出 统计 ``` 都不会绕过 Tenant Scope。 --- # 110. Search Security Global Search 必须应用: ```text Actor Permission + Organization Scope + Project Scope + Resource Policy ``` 搜索结果不能成为权限泄漏渠道。 --- # 111. Export Security Export 是高风险读取操作。 必须: ```text permission scope field permission sensitive field policy audit ``` 大规模 Export: ```text Task ↓ Job ↓ Worker ``` 并继承 Security Context。 --- # 112. Import Security Import 必须检查: ```text file schema resource permission field permission scope validation ``` 不能因为上传 CSV 就绕过 Action Runtime。 --- # 113. Cache Security 缓存不能跨 Tenant 污染。 错误: ```text cache:website:{id} ``` 如果 ID 可能被错误访问。 推荐: ```text cache:{organization}:{project}:website:{id} ``` 并结合 Scope。 --- # 114. Redis Security Redis 中不得保存: ```text plaintext secrets passwords long-lived credentials ``` 可以保存: ```text session metadata locks queue data temporary authorization cache ``` 但必须有 TTL 与隔离策略。 --- # 115. Object Storage Security 默认: ```text private ``` 只有通过 Storage Runtime 获取: ```text signed URL ``` 才允许访问。 --- # 116. Security Defaults DevOS 默认: ```text deny private short-lived scoped audited approval-sensitive ``` 而不是: ```text 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 必须建立: ```text 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: ```text Org A ``` 不能读取: ```text Org B ``` --- ### Scenario 2 Agent A: ```text Project A ``` 不能执行: ```text Project B ``` --- ### Scenario 3 Plugin A: 没有: ```text secret.read ``` 不能获取 Secret。 --- ### Scenario 4 MCP: 没有: ```text server.restart ``` 不能调用。 --- ### Scenario 5 Agent: 拥有: ```text deploy ``` 但 Production: ```text approval required ``` 必须进入 Approval。 --- ### Scenario 6 用户拥有: ```text resource.read ``` 但 Resource 不属于当前 Project: ```text DENY ``` --- ### Scenario 7 Search: 不能返回其他 Organization 数据。 --- ### Scenario 8 Export: 不能导出当前 Actor 无权读取的字段。 --- # 120. Security CI Gate CI 必须至少执行: ```bash pnpm lint pnpm typecheck pnpm test pnpm test:security pnpm test:contract pnpm test:e2e ``` 安全相关代码发生变化时: ```text Security Suite = Mandatory ``` 不能允许: ```text test skipped ``` 进入生产。 --- # 121. Zcode Security Implementation Protocol Zcode 实现任何功能时必须执行: ```text 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: ```text 创建第二套 RBAC 创建第二套 Tenant System 创建第二套 Permission System 创建第二套 Audit 创建第二套 Approval 创建第二套 Secret Access 创建超级 Agent 创建万能 Plugin Token 创建 bypassAuth() 创建 skipPermission() 创建 rootContext() ``` --- # 123. Zcode Master Security Prompt 以后可以直接将以下内容作为 Zcode 的安全实施规则: ```text 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 安全体系最终形成: ```text 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 不完整。** 最终必须保证: ```text WHO ↓ CAN DO WHAT ↓ ON WHICH RESOURCE ↓ IN WHICH SCOPE ↓ UNDER WHICH POLICY ↓ WITH WHICH APPROVAL ↓ EXECUTED HOW ↓ AUDITED WHERE ``` 这就是 DevOS 的统一安全模型。