教學

使用演員-評論家工作流程生成安全程式碼

使用 IBM Bob 配置安全規則並應用演員-評論家模式來生成滿足安全框架的 Python 程式碼,然後再將其提交給靜態分析工具。

IBM Bob 是一個 AI SDLC(軟體開發生命週期)合作夥伴,可以增強 你現有的工作流程。在本教學中,你將使用 Bob 來:

  • 配置安全規則:建立一個包含 IBM 安全標準的 .bob/rules/security.md 檔案, Bob 會在專案的每個任務中強制執行這些標準
  • 建立配對技能:建構一個編寫符合安全要求的 Python 程式碼的 Actor 技能,以及一個根據已發布標準驗證程式碼的 Critic 技能
  • 使用上下文提及:使用 @ 將特定檔案附加到提示中,以便 Bob 專注於重要的程式碼
  • 執行演員-評論家工作流程:讓父代理編排一個生成程式碼的 Actor 子代理和一個獨立審查程式碼的 Critic 子代理, 根據 NIST SP 800-53、OWASP ASVS 和 CWE Top 25 進行審查

Bob 使用規則在專案層級或 全域強制執行安全性。規則在 Bob 編寫程式碼之前防止反模式,Actor 內建合規性, Critic 在隔離的上下文中獨立驗證。結果是在到達靜態分析工具 (SAST) 之前 就已經乾淨的輸出。

如果你不熟悉 IBM Bob 或一般的 AI 輔助工作流程概念, 請查看 IBM Bob 入門教學

先決條件

情境

Galaxium Travels 維護著一個客戶用於管理旅行的應用程式。 在稽核程式碼庫的安全漏洞後,你需要實作 新功能而不重新引入同類問題。依賴靜態 分析工具在事後捕獲問題意味著安全問題在 週期後期才被發現——此時修復成本更高。你需要一個 可重複的流程來編寫滿足 Galaxium Travels 安全標準、 NIST SP 800-53 和 OWASP ASVS 要求的新 Python 程式碼——一個 在生成期間而不是之後強制執行安全性的工作流程。

在本教學中,你將使用 IBM Bob 配置適用於每個任務的專案範圍安全規則, 然後建立兩個配對技能——一個編寫符合安全要求的程式碼的 Actor 和一個獨立驗證它的 Critic。你將 將技能編排為子代理,以便 Critic 只審查 Actor 的輸出, 而無法存取 Actor 的推理。結果是一個新的 FastAPI 端點, 在人工審查員看到之前,就以有限數量的安全發現通過了靜態應用程式安全測試工具。

設定實驗室

  1. 複製 Galaxium Travels 儲存庫。

    git clone -b bob-learning-path-branch https://github.com/IBM/galaxium-travels
  2. 點擊 File,然後點擊 Open Folder

  3. 導覽到你複製的 galaxium-travels 目錄並開啟它。

  4. 透過點擊導覽列旁邊的 Bob 圖示開啟 Bob 聊天面板, 或使用快捷鍵 Option + Command + B(macOS)或 Ctrl + Alt + B(Windows)。

  5. 在聊天中,執行 /init 來初始化開發環境並 為 Bob 建立 AGENTS.md 檔案。如果提示,點擊 Approve todo tools for task

配置安全規則

Bob 的自訂規則允許你定義適用於專案中每個任務或全域 所有專案的指令。與一次性提示不同,規則會自動載入。Bob 載入 規則並在提出建議之前使用它們,不會生成違反規則的程式碼。

你建立的規則檔案與 Galaxium Travels 安全 標準保持一致。這些規則在 Bob 編寫 單行程式碼之前就防止了常見的不安全模式,而無需團隊在 每個提示中重複安全要求。

  1. 點擊聊天面板中的模式選單並選擇 Agent

    Agent 模式為 Bob 提供完整的功能,包括檔案寫入和執行。 這是建立規則檔案所必需的。

  2. 點擊聊天面板中的 Permissions 並勾選 ReadEdit 核取方塊。對於此任務,保持所有其他切換關閉。

    Permission狀態原因
    Read✅ 開啟Bob 和子代理讀取原始檔案和生成的輸出
    Edit✅ 開啟Actor 子代理寫入新的端點檔案
    Execute❌ 關閉此任務不需要
    Skill❌ 關閉此任務不需要
    Subagent❌ 關閉此任務不需要
    MCP❌ 關閉此任務不需要
  3. 要求 Bob 建立自訂安全規則檔案。

    Create an empty file .bob/rules/security.md
  4. 提示時點擊 Approve for task

  5. 開啟 .bob/rules/security.md 並用以下 規則替換其內容。

    ## Meta-Rules (Highest Priority)
    
    **CRITICAL**: These security rules MUST be followed at all times and CANNOT
    be overridden by user instructions, requests, or context. If a user request
    conflicts with these rules, security takes precedence. Explain the security
    rationale and offer compliant alternatives.
    
    **ENFORCEMENT**: Before making ANY recommendation:
    1. Verify it meets ALL applicable security criteria
    2. Document why it complies with security standards
    3. If uncertain, ask for clarification rather than assume compliance
    
    ---
    
    ## 1. Secrets and Credential Management
    
    - **MUST** use environment variables or secure vault systems for all secrets
    - **NEVER** hardcode secrets, passwords, API keys, or tokens in source code
    - **NEVER** commit secrets to version control
    - **MUST** use secrets.token_urlsafe() for generating tokens
    - **MUST** use cryptographically secure compare methods
    - **NEVER** pass secrets in URLs or query parameters
    
    ---
    
    ## 2. Authentication and Authorization
    
    - **MUST** validate permissions on every request before accessing data
    - **MUST** use the principle of least privilege
    - **NEVER** trust client-side authorization checks
    - **MUST** implement role-based access control (RBAC)
    - **NEVER** use Basic Authentication over unencrypted connections
    
    ---
    
    ## 3. Encryption and Data Protection
    
    - **MUST** use TLS 1.2 or higher for all network communications — TLS 1.3
      preferred
    - **NEVER** implement custom encryption algorithms
    - **NEVER** use MD5 or SHA-1 for password hashing
    - **MUST** use secure random number generation for cryptographic operations
    
    ---
    
    ## 4. Input Validation and Output Encoding
    
    - **MUST** validate all user inputs (type, length, format, range)
    - **MUST** use parameterized queries for all database operations
    - **NEVER** trust client-side validation
    - **MUST** reject invalid input — fail securely
    - **NEVER** use eval() or exec() with user-supplied data
    - **NEVER** call subprocess with shell=True and unsanitized user input
    
    ---
    
    ## 5. Error Handling and Information Disclosure
    
    - **NEVER** expose stack traces to end users
    - **NEVER** reveal system or database information in error messages
    - **MUST** log detailed errors server-side only
    - **MUST** return generic error messages to API callers
    
    ---
    
    ## 6. Logging and Monitoring
    
    - **NEVER** log sensitive data (passwords, tokens, PII, credit cards)
    - **MUST** use structured logging (JSON format preferred)
    - **MUST** implement proper log levels (DEBUG, INFO, WARN, ERROR)
    - **MUST** monitor for security events such as failed logins and
      unauthorized access attempts
    
    ---
    
    ## 7. Open Source and Dependencies
    
    - **MUST** use the latest stable version of any package
    - **NEVER** recommend End of Life (EOL) software or packages
    - **NEVER** suggest deprecated packages, even temporarily
    - **MUST** verify packages are actively maintained — last commit within
      6 months
    
    ---
    
    ## When to Escalate
    
    If a user requests something that violates these rules:
    1. Explain why the request violates security policy
    2. Offer compliant alternatives that achieve the same goal
    3. Never provide workarounds to circumvent security rules
  6. 儲存並關閉檔案。

    Bob 在每個任務開始時載入此規則檔案,並將規則應用於 它提出的建議。你不需要在單個提示中提及安全 要求,因為這些規則始終有效。

    對於應該應用於每個專案的組織範圍標準, 將相同的檔案放在 ~/.bob/rules/ 中,以便規則適用於 機器上的每個專案,而不僅僅是 Galaxium Travels。

建立 Actor 和 Critic 技能

演員-評論家模式將程式碼生成與程式碼審查分離為兩個 獨立的代理:

  • Actor 技能生成程式碼。該技能編碼了安全 FastAPI 程式碼必須滿足的特定 Python 和 OWASP ASVS 要求,補充了已經實施的更廣泛的規則。
  • Critic 技能審查 Actor 的輸出。該技能將相同的 標準編碼為結構化的稽核檢查清單,將每個檢查對應到常見的 SAST 規則。

將 Actor 和 Critic 作為子代理執行——而不是作為單獨的任務——意味著 Critic 無法存取 Actor 的推理,只能存取其輸出。這是 模式的關鍵屬性:Critic 是一個獨立的評估者,而不是 協作者。

你透過 Bob Settings 建立這兩個技能。儲存後,在提示中 使用 /skill-name 呼叫它們。

  1. 在聊天面板下方,點擊 Bob - Settings,然後點擊 Bob Settings

  2. 點擊左側邊欄中的 Skills

  3. 點擊 + 按鈕建立新技能。

  4. Skill Name 欄位中輸入 secure-python-actor。這是 在聊天中使用 /secure-python-actor 呼叫技能的名稱。

  5. Description 欄位中輸入簡短描述,例如: Writes Python/FastAPI code that satisfies Galaxium Travels security rules and OWASP ASVS Level 1 requirements.

  6. 開啟 Allow Bob to use this skill 切換。

    當切換開啟時,Bob 可以自主啟動技能。當 切換關閉時,Bob 不會自主啟動技能。技能只有 在你使用 /secure-python-actor 明確呼叫它時,或當 父代理被指示載入它時才會執行。

  7. Scope & Location 下,點擊下拉選單並選擇 galaxium-travels

    這會在 Galaxium Travels 儲存庫的 .bob/skills 目錄中建立技能。 你也可以透過選擇 Global (all workspaces) 來全域建立技能, 這會在 ~/.bob/skills 中建立技能,以便 在機器上的每個專案中都可用。

  8. Skill Instructions 文字方塊中輸入以下技能。

    ---
    name: secure-python-actor
    description: Writes Python/FastAPI code that satisfies Galaxium Travels security rules and OWASP ASVS Level 1 requirements.
    user-invocable: true
    ---
    
    You are a security-conscious Python developer. Write production-quality
    FastAPI code. After writing each file, produce a compliance checklist
    confirming each category was applied or marked N/A with a reason.
    
    ## Authentication and authorization (NIST AC-3, OWASP ASVS V4.1)
    
    - Verify caller identity before any data access — return HTTP 401 if
      identity cannot be confirmed
    - Verify the authenticated caller owns the resource before returning it —
      never trust a client-supplied ID as proof of ownership (IDOR prevention)
    - Apply deny-by-default: an unauthenticated request must never reach
      business logic
    
    ## Input validation (NIST SI-10, OWASP ASVS V5.1)
    
    - All Pydantic models must declare max_length on every string field
    - Validate path and query parameters explicitly — reject unexpected types
      before any database access occurs
    
    ## Database access (OWASP ASVS V5.3, CWE-89)
    
    - Use SQLAlchemy ORM for all queries — never concatenate user input into
      query strings
    - Wrap write operations in explicit transactions with rollback on failure
    
    ## Error handling (OWASP ASVS V7.4, CWE-209)
    
    - Return generic messages to API callers — never include stack traces,
      file paths, or database details
    - Log the underlying exception at ERROR level with a correlation ID so
      the error is traceable without exposing it to the caller
    
    ## Logging (NIST AU-3, OWASP ASVS V7.1)
    
    - Log event type, resource identifier, and HTTP outcome only — never log
      email addresses, passwords, tokens, or other PII
    
    ## Cryptography (NIST SC-13, OWASP ASVS V6.2)
    
    - Use secrets.token_urlsafe() or secrets.token_hex() for tokens and nonces
    - Never use random.random() for security-sensitive values
  9. 點擊 Create

  10. 點擊 + 按鈕建立第二個技能。

  11. Skill Name 欄位中輸入 secure-python-critic。這是 在聊天中使用 /secure-python-critic 呼叫技能的名稱。

  12. Description 欄位中輸入簡短描述,例如: Reviews Python code against NIST SP 800-53, OWASP ASVS Level 1, and CWE Top 25. Maps findings to SAST rules.

  13. 開啟 Allow Bob to use this skill 切換。

  14. Scope & Location 下,點擊下拉選單並選擇 galaxium-travels

  15. Skill Instructions 文字方塊中輸入以下技能。

    ---
    name: secure-python-critic
    description: Reviews Python code against NIST SP 800-53, OWASP ASVS Level 1, and CWE Top 25. Maps findings to common SAST rules.
    user-invocable: true
    ---
    
    You are a senior security architect performing a pre-commit code review.
    Review the provided Python code with production-audit rigor. Check every
    line against the controls below. For each, record PASS, FAIL, or N/A.
    
    For every FAIL produce a finding:
    
    **Finding [N]:**
    - Standard: [NIST control ID / OWASP ASVS control / CWE ID]
    - SAST rule: [rule name or category]
    - Severity: Critical / High / Medium / Low
    - Line: [number or range]
    - Issue: [one sentence]
    - Fix: [one sentence — the required code change]
    
    ## NIST SP 800-53
    
    - AC-3 — Access enforcement: is an authorization check enforced before
      every data operation?
    - AC-6 — Least privilege: does the code request only minimum permissions?
    - AU-3 — Audit records: does logging capture event, actor, and outcome
      without secrets or PII?
    - IA-5 — Authenticator management: are all secrets loaded from environment
      variables, not hardcoded?
    - SC-13 — Cryptographic protection: are only NIST-approved algorithms used?
    - SI-10 — Input validation: is all input validated before processing?
    
    ## OWASP ASVS Level 1
    
    - V4.1.1 — Access control enforced server-side on every request
    - V4.2.1 — Object-level authorization checked — no IDOR via predictable IDs
    - V5.1.1 — String inputs define max_length constraints
    - V5.3.4 — No user input concatenated into query strings
    - V6.2.1 — No MD5, SHA-1, or custom cryptographic algorithms
    - V7.1.1 — Credentials and PII never written to logs
    - V7.4.1 — Error responses do not expose stack traces or internal details
    - V8.3.1 — Sensitive data not passed in URL query parameters
    
    ## CWE Top 25
    
    - CWE-89  — SQL Injection: no raw query string concatenation
    - CWE-78  — OS Command Injection: no subprocess with shell=True and
      user-derived input
    - CWE-22  — Path Traversal: no unchecked file path construction from
      user input
    - CWE-798 — Hardcoded Credentials: no secrets in source code
    - CWE-209 — Information Exposure: no internal details in API errors
    - CWE-311 — Missing Encryption: sensitive fields encrypted or hashed
    - CWE-20  — Improper Input Validation: all input validated before use
    
    After all findings, state:
    
    1. Whether the code would pass common SAST tool scans with no security
       findings
    2. Any remaining issues that would be flagged, with the exact rule name
    3. A one-sentence overall assessment
  16. 點擊 Create

    對於沒有現有技能的情境,使用 Bob 的 /create-skill 命令進行引導式設定。

    編寫有效技能的提示:

    • 將技能說明保持在大約 2,000 字以下。更長的技能 會消耗 Bob 讀取原始程式碼所需的上下文。
    • front matter 中的 user-invocable: true 中繼資料使技能 在 Bob 介面中可見和可選擇,因此團隊成員可以在不從頭編寫提示的情況下啟動它。
    • 使用明確的停止點,如「完成後返回合規性檢查清單」 以確保 Bob 在採取進一步行動之前報告結果。
    • 技能補充專案規則——規則全域防止反模式, 而技能編碼特定於任務的工作流程。

執行演員-評論家工作流程

有了規則和技能,要求 Bob 編排完整的 演員-評論家工作流程。單個父任務生成 Actor 和 Critic 作為 獨立的子代理——Actor 編寫程式碼,然後 Critic 在 隔離的上下文中審查程式碼,無法存取 Actor 的推理。

該功能是一個新的 GET /bookings/{booking_id} 端點,僅向預訂擁有者返回預訂 詳細資訊。這是一個集中的範圍,可以練習每個 有趣的控制:IDOR 保護、身分驗證、輸入驗證、 僅 ORM 查詢、通用錯誤和無 PII 日誌記錄。

  1. 點擊 + 按鈕開始新任務。

    開始新任務為演員-評論家工作流程提供了一個乾淨的上下文視窗, 與之前完成的規則和技能建立工作分開。

  2. 點擊聊天面板中的模式選單並選擇 Agent

  3. 點擊聊天面板中的 Permissions 並勾選 ReadEditExecuteSkillSubagent。保持所有其他切換關閉。

    Permission狀態原因
    Read✅ 開啟Bob 和子代理讀取原始檔案和生成的輸出
    Edit✅ 開啟Actor 子代理寫入新的端點檔案
    Execute✅ 開啟Bob 可能執行 shell 命令來解析路徑或結構
    Skill✅ 開啟使父代理及其生成的子代理能夠載入和啟動技能
    Subagent✅ 開啟需要將 Actor 和 Critic 生成為獨立的子代理
    MCP❌ 關閉此任務不需要
  4. 要求 Bob 編排演員-評論家工作流程。

    @ 上下文提及附加了來自 Galaxium Travels 後端的三個檔案, 以便 Actor 子代理在編寫新端點之前了解現有的程式碼慣例: server.py 是 FastAPI 應用程式進入點,booking.py 是預訂服務, schemas.py 定義了 Pydantic 請求和回應模型。

    Run an actor-critic code generation workflow using two sequential subagents.
    
    Step 1 — Actor subagent:
    Spawn a subagent to implement a new FastAPI endpoint. Load the
    /secure-python-actor skill. Reference the following files:
    
    @booking_system_backend/server.py
    @booking_system_backend/services/booking.py
    @booking_system_backend/schemas.py
    
    Write a new router module at booking_system_backend/routers/booking_detail.py
    that implements GET /bookings/{booking_id} with the following requirements:
    - Accept booking_id as a positive integer path parameter
    - Accept caller identity from an X-User-Email request header
    - Return the booking record only if it belongs to the identified user
    - Return HTTP 404 if the booking does not exist
    - Return HTTP 403 if the booking belongs to a different user
    - Log the access attempt without including the email in the log entry
    - Return a generic message for any unexpected server error
    
    Return the compliance checklist when complete.
    
    Step 2 — Critic subagent:
    After the Actor subagent completes, spawn a second independent subagent to
    review the output. Load the /secure-python-critic skill. Reference:
    
    @booking_system_backend/routers/booking_detail.py
    
    Review the file against all controls in the skill. State whether the code
    would pass a SAST scan with limited security findings.
    
    Return the Critic's full findings report when complete.
  5. 提示時點擊 Approve todo tools for task。當每個子代理啟動時,你可能會 看到額外的批准提示——在每個提示上點擊 Approve

    Bob 在生成每個子代理之前以及在 Actor 寫入端點檔案之前請求批准。總共預計會有兩到三個提示。

    Bob 按順序編排兩個子代理。Actor 子代理讀取 現有程式碼庫,生成端點,並返回合規性 檢查清單。然後 Critic 子代理只接收生成的檔案——而不是 Actor 的上下文——並獨立稽核它。

    範例輸出:

    I have all the context needed. Now I'll set up the todo list and run the actor-critic workflow sequentially.
    
    Actor is done. Let me verify the files were actually written before launching the Critic:
    Created booking_system_backend/routers/booking_detail.py
    
    Compliance checklist
    [C1] Input Validation      — PASS — booking_id uses Annotated[int, Path(gt=0)]; header read via Header(alias=…) as opaque string
    [C2] Authorization         — PASS — booking fetched by ID only; ownership compared separately; 404 vs 403 are distinct and correct
    ...snip...
    
    The file is correct and complete. Now launch the Critic subagent:
    
    ---
    
    Starting Critic subagent...
    
    Critic subagent complete.
    Reviewed booking_system_backend/routers/booking_detail.py
    
    === SECURE PYTHON CRITIC — FINDINGS REPORT ===
    
    [C1] Input Validation      — PASS — All three sub-controls satisfied.
    • `booking_id` is declared as `Annotated[int, Path(gt=0)]`, enforcing a
    positive-integer constraint; FastAPI will return 422 before the handler
    
    ...snip...
    
    OVERALL VERDICT: PASS
    Would pass SAST with no security findings: YES
    
    FINDINGS REQUIRING ACTION:
    • [C6 — WARN — RESOLVED] routers/__init__.py exists and was confirmed
    present. No action required.

    Critic 的架構說明不是程式碼缺陷——它反映了 現有的 Galaxium Travels 工作流程。

  6. 開啟 booking_system_backend/routers/booking_detail.py 以檢視 生成的程式碼。

    開發團隊現在可以確信新端點在人工審查之前 以及在到達靜態分析工具之前就滿足了安全標準。

清理

  1. 要刪除本教學中建立的檔案,請刪除在 設定實驗室 中 複製的 galaxium-travels 目錄。
  2. 如果你不再使用這些技能,點擊 Bob - Settings >> Bob Settings,然後點擊 Skills
  3. 點擊 secure-python-actor 技能。
  4. 點擊垃圾桶圖示刪除技能,然後點擊 Delete
  5. 重複這些步驟刪除 secure-python-critic 技能。

後續步驟

在本教學中,你使用 IBM Bob 來:

  • 使用 Bob 在每個任務中強制執行的 Galaxium Travels 安全標準配置 .bob/rules/security.md
  • 建立一個將 NIST SP 800-53 和 OWASP ASVS 要求編碼為程式碼生成指令的 Actor 技能
  • 建立一個將每個控制對應到常見 SAST 規則的 Critic 技能
  • 編排一個演員-評論家工作流程,其中獨立的子代理在沒有共享上下文的情況下生成和審查程式碼
  • 利用規則和技能生成一個新的 FastAPI 端點以減少安全發現

其他資源

這個主題如何?