توليد كود آمن بسير عمل actor-critic
استخدم IBM Bob لتكوين قواعد الأمان وتطبيق نمط actor-critic لتوليد كود Python يرضي أطر الأمان قبل وصوله إلى أداة التحليل الثابت.
IBM Bob هو شريك ذكاء اصطناعي في دورة حياة تطوير البرمجيات (SDLC) يعزز سير عملك الحالي. في هذا الدرس، ستستخدم Bob من أجل:
- تكوين قواعد الأمان: إنشاء ملف
.bob/rules/security.mdبمعايير أمان IBM التي يُطبِّقها Bob على كل مهمة في المشروع - إنشاء مهارات متزاوجة: بناء مهارة Actor تكتب كود Python المتوافق مع الأمان ومهارة Critic تُقيِّمه مقابل المعايير المنشورة
- استخدام mentions السياق: استخدام
@لإرفاق ملفات محددة بطلب حتى يركز Bob على الكود المهم - تشغيل سير عمل actor-critic: إسناد مهمة لوكيل أصل لتنسيق وكيل Actor فرعي يُولِّد الكود ووكيل Critic فرعي يراجعه بشكل مستقل مقابل NIST SP 800-53 وOWASP ASVS وCWE Top 25
Bob يستخدم القواعد لتطبيق الأمان على مستوى المشروع أو على المستوى العام. القواعد تمنع الأنماط المضادة قبل أن يكتب Bob سطراً واحداً، والـ Actor يبني الامتثال بداخله، والـ Critic يتحقق بشكل مستقل في سياق معزول. النتيجة هي مخرجات نظيفة قبل وصولها إلى أداة التحليل الثابت (SAST).
إذا لم تكن مألوفاً مع IBM Bob أو مفاهيم سير العمل المدعوم بالذكاء الاصطناعي، راجع دروس البدء مع IBM Bob.
المتطلبات الأساسية
السيناريو
Galaxium Travels يُشغِّل تطبيقاً يستخدمه العملاء لإدارة السفر. بعد تدقيق قاعدة الكود بحثاً عن ثغرات أمنية، تحتاج إلى تنفيذ ميزات جديدة دون إعادة إدخال نفس فئة المشاكل. الاعتماد على أدوات التحليل الثابت لاكتشاف المشاكل بعد الحقيقة يعني اكتشاف مشاكل الأمان في وقت متأخر من الدورة — عندما يكون إصلاحها أكثر تكلفة. تحتاج إلى عملية قابلة للتكرار لكتابة كود Python جديد يرضي معايير أمان Galaxium Travels ومتطلبات NIST SP 800-53 وOWASP ASVS منذ البداية — سير عمل يُطبِّق الأمان أثناء التوليد، وليس بعده.
في هذا الدرس، ستستخدم IBM Bob لتكوين قواعد أمان على مستوى المشروع تُطبَّق على كل مهمة، ثم إنشاء مهارتين متزاوجتين — Actor يكتب كوداً متوافقاً مع الأمان وCritic يتحقق منه بشكل مستقل. ستُنسِّق المهارات كوكلاء فرعيين حتى يراجع Critic فقط مخرجات Actor، دون الوصول إلى تفكير Actor.
إعداد البيئة
-
استنسخ مستودع Galaxium Travels.
git clone -b bob-learning-path-branch https://github.com/IBM/galaxium-travels -
انقر على File ثم Open Folder.
-
انتقل إلى مجلد
galaxium-travelsالذي استنسخته وافتحه. -
افتح لوحة دردشة Bob بالنقر على أيقونة Bob بجانب شريط التنقل، أو استخدم الاختصار Option + Command + B (macOS) أو Ctrl + Alt + B (Windows).
-
في الدردشة، نفّذ
/initلتهيئة بيئة التطوير وإنشاء ملفات AGENTS.md لـ Bob. انقر على Approve todo tools for task إذا طُلب ذلك.
تكوين قواعد الأمان
القواعد المخصصة في Bob تتيح لك تعريف تعليمات تُطبَّق على كل مهمة في المشروع، أو على المستوى العام عبر جميع المشاريع. على عكس الطلب لمرة واحدة، تُحمَّل القواعد تلقائياً. يُحمِّل Bob القواعد ويستخدمها قبل تقديم التوصيات ولن يُولِّد كوداً ينتهك القواعد.
-
انقر على قائمة الوضع في لوحة الدردشة واختر Agent.
وضع Agent يمنح Bob قدرات كاملة، بما في ذلك كتابة الملفات والتنفيذ. هذا ضروري لإنشاء ملف القواعد.
-
انقر على Permissions في لوحة الدردشة وتحقق من مربعات Read وEdit. اترك جميع المبدّلات الأخرى غير محددة لهذه المهمة.
الصلاحية الحالة السبب Read ✅ مفعّل Bob والوكلاء الفرعيون يقرؤون الملفات المصدرية والمخرجات المُولَّدة Edit ✅ مفعّل وكيل Actor الفرعي يكتب ملف نقطة النهاية الجديد Execute ❌ متوقف غير مطلوب لهذه المهمة Skill ❌ متوقف غير مطلوب لهذه المهمة Subagent ❌ متوقف غير مطلوب لهذه المهمة MCP ❌ متوقف غير مطلوب لهذه المهمة -
اطلب من Bob إنشاء ملف قاعدة الأمان المخصص.
Create an empty file .bob/rules/security.md -
انقر على Approve for task عند المطالبة.
-
افتح
.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 -
احفظ الملف وأغلقه.
يُحمِّل Bob ملف القاعدة هذا في بداية كل مهمة ويُطبِّق القواعد على التوصيات التي يقدمها. لا تحتاج إلى ذكر متطلبات الأمان في الطلبات الفردية لأن هذه القواعد سارية دائمًا. وللمعايير المؤسسية التي يجب تطبيقها على كل مشروع، ضع الملف نفسه في
~/.bob/rules/كي تسري القواعد على كل مشروع في الجهاز، وليس Galaxium Travels فقط.
إنشاء مهارتي Actor وCritic
نمط actor-critic يفصل توليد الكود من مراجعة الكود إلى وكيلين مستقلين:
- مهارة Actor تُولِّد الكود. المهارة تُدوِّن متطلبات Python وOWASP ASVS المحددة التي يجب أن يرضيها الكود الآمن لـ FastAPI، مما يكمل القواعد الأوسع الموجودة بالفعل.
- مهارة Critic تراجع مخرجات Actor. المهارة تُدوِّن نفس المعايير كقائمة تدقيق منظمة، تُحدِّد كل فحص إلى قواعد SAST الشائعة.
تشغيل Actor وCritic كوكلاء فرعيين — بدلاً من مهام منفصلة — يعني أن Critic لا يصل إلى تفكير Actor، فقط مخرجاته. هذه هي الخاصية الرئيسية للنمط: Critic هو مُقيِّم مستقل، وليس متعاوناً.
تُنشئ كلتا المهارتين عبر Bob Settings. بمجرد الحفظ، استدعِهما في الطلبات بـ /skill-name.
-
تحت لوحة الدردشة، انقر على Bob - Settings ثم انقر على Bob Settings.
-
انقر على Skills في الشريط الجانبي الأيسر.
-
انقر على زر + لإنشاء مهارة جديدة.
-
أدخل
secure-python-actorفي حقل Skill Name. هذا هو الاسم المستخدم لاستدعاء المهارة بـ/secure-python-actorفي الدردشة. -
أدخل وصفاً قصيراً في حقل Description، على سبيل المثال:
Writes Python/FastAPI code that satisfies Galaxium Travels security rules and OWASP ASVS Level 1 requirements. -
شغّل مبدّل Allow Bob to use this skill.
عند تشغيل المبدّل، يمكن لـ Bob تفعيل المهارة ذاتيًا. وعند إيقافه، لا يفعّلها Bob ذاتيًا؛ ولا تعمل المهارة إلا عند استدعائها صراحةً بـ
/secure-python-actorأو عندما يُطلب من وكيل أصل تحميلها. -
تحت Scope & Location، انقر على القائمة المنسدلة واختر galaxium-travels.
ينشئ ذلك المهارة في مستودع Galaxium Travels ضمن دليل
.bob/skills. ويمكنك أيضًا إنشاء مهارات عامة باختيار Global (all workspaces)، فتُنشأ في~/.bob/skillsوتتوفر في كل مشروع على الجهاز. -
أدخل المهارة التالية في مربع نص 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 -
انقر على Create.
إذا لم تكن لديك مهارة قائمة في سيناريو ما، استخدم أمر
/create-skillفي Bob لإعداد موجّه.نصائح لكتابة مهارات فعالة:
- أبقِ تعليمات المهارة دون نحو 2,000 كلمة. تستهلك المهارات الأطول سياقًا يحتاجه Bob لقراءة الكود المصدر.
- تجعل بيانات
user-invocable: trueفي الـ front matter المهارة مرئية وقابلة للاختيار في واجهة Bob، ليتمكن أعضاء الفريق من تفعيلها من دون كتابة طلب من البداية. - استخدم نقاط توقف صريحة مثل «أعد قائمة تدقيق الامتثال عند الاكتمال» لضمان أن يبلّغ Bob النتائج قبل اتخاذ إجراء إضافي.
- تكمل المهارات قواعد المشروع؛ فالقواعد تمنع الأنماط المضادة عالميًا، بينما تشفّر المهارات سير العمل الخاص بالمهمة.
-
انقر على زر + لإنشاء مهارة ثانية.
-
أدخل
secure-python-criticفي حقل Skill Name. -
أدخل وصفاً قصيراً في حقل Description، على سبيل المثال:
Reviews Python code against NIST SP 800-53, OWASP ASVS Level 1, and CWE Top 25. Maps findings to SAST rules. -
شغّل مبدّل Allow Bob to use this skill.
-
تحت Scope & Location، انقر على القائمة المنسدلة واختر galaxium-travels.
-
أدخل المهارة التالية في مربع نص 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 -
انقر على Create.
تشغيل سير عمل actor-critic
مع وجود القواعد والمهارات، اطلب من Bob تنسيق سير عمل actor-critic الكامل. مهمة أصل واحدة تُفرز Actor وCritic كوكلاء فرعيين مستقلين — Actor يكتب الكود، ثم Critic يراجعه في سياق معزول دون الوصول إلى تفكير Actor.
الميزة هي نقطة نهاية GET /bookings/{booking_id} جديدة تُعيد تفاصيل الحجز فقط لمالك الحجز. هذا نطاق مركّز يُمارس كل ضابط مثير للاهتمام: حماية IDOR، والتحقق من الهوية، والتحقق من المدخلات، واستعلامات ORM فقط، والأخطاء العامة، والتسجيل الخالي من PII.
-
انقر على زر + لبدء مهمة جديدة.
يمنح بدء مهمة جديدة سير عمل actor-critic نافذة سياق نظيفة، منفصلة عن عمل إنشاء القواعد والمهارات السابق.
-
انقر على قائمة الوضع في لوحة الدردشة واختر Agent.
-
انقر على Permissions في لوحة الدردشة وتحقق من Read وEdit وExecute وSkill وSubagent. اترك جميع المبدّلات الأخرى غير محددة.
الصلاحية الحالة السبب Read ✅ مفعّل Bob والوكلاء الفرعيون يقرؤون الملفات المصدرية والمخرجات المُولَّدة Edit ✅ مفعّل وكيل Actor الفرعي يكتب ملف نقطة النهاية الجديد Execute ✅ مفعّل قد يشغّل Bob أوامر shell لحل المسارات أو الهيكل Skill ✅ مفعّل يُمكِّن الوكيل الأصل والوكلاء الفرعية التي يُفرزها من تحميل المهارات وتفعيلها Subagent ✅ مفعّل مطلوب لإفراز Actor وCritic كوكلاء فرعيين مستقلين MCP ❌ متوقف غير مطلوب لهذه المهمة -
اطلب من Bob تنسيق سير عمل actor-critic.
تضيف mentions السياق أدناه ثلاثة ملفات من خلفية 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. -
انقر على Approve todo tools for task عند المطالبة. عند بدء كل وكيل فرعي قد ترى طلبات موافقة إضافية — انقر على Approve على كل منها.
يطلب Bob الموافقة قبل تشغيل كل وكيل فرعي وقبل أن يكتب Actor نقطة النهاية. توقّع ظهور طلبين أو ثلاثة طلبات موافقة إجمالًا.
ينسّق Bob كلا الوكيلين الفرعيين بالتسلسل. يقرأ وكيل Actor الفرعي قاعدة الكود القائمة، ويولّد نقطة النهاية، ويعيد قائمة تدقيق الامتثال. ثم يتلقى وكيل Critic الفرعي الملف المولّد فقط — لا سياق Actor — ويدققه بصورة مستقلة.
ملاحظة Critic المعمارية ليست عيبًا في الكود؛ بل تعكس سير العمل القائم في Galaxium Travels.
-
افتح
booking_system_backend/routers/booking_detail.pyلمراجعة الكود المُولَّد.يمكن لفريق التطوير الآن أن يكون واثقاً من أن نقطة النهاية الجديدة ترضي معايير الأمان قبل أن يراجعها إنسان، وقبل وصولها إلى أداة التحليل الثابت.
التنظيف
- لإزالة الملفات التي أُنشئت في هذا الدرس، احذف مجلد
galaxium-travelsالذي استُنسخ في إعداد البيئة. - إذا كنت لن تستخدم المهارات بعد الآن، انقر على Bob - Settings >> Bob Settings ثم Skills.
- انقر على مهارة secure-python-actor.
- انقر على أيقونة سلة المهملات لحذف المهارة، ثم انقر على Delete.
- كرر هذه الخطوات لحذف مهارة secure-python-critic.
الخطوات التالية
في هذا الدرس، استخدمت IBM Bob من أجل:
- تكوين
.bob/rules/security.mdبمعايير أمان Galaxium Travels التي يُطبِّقها Bob على كل مهمة - إنشاء مهارة Actor تُدوِّن متطلبات NIST SP 800-53 وOWASP ASVS كتعليمات توليد كود
- إنشاء مهارة Critic تُحدِّد كل ضابط إلى قواعد SAST الشائعة
- تنسيق سير عمل actor-critic حيث يُولِّد وكلاء فرعيون مستقلون ويراجعون الكود دون سياق مشترك
- إنتاج نقطة نهاية FastAPI جديدة باستخدام القواعد والمهارات لتقليل نتائج الأمان
موارد إضافية
تدقيق الكود وتوليد التقارير
استخدم IBM Bob لإنشاء مهارة تدقيق أمني قابلة لإعادة الاستخدام، مسح تطبيق مقابل متطلبات OWASP ASVS، وتوليد تقارير SARIF وOSCAL يمكن للمطورين ووكلاء الذكاء الاصطناعي التصرف بناءً عليها.
إنشاء نافذة سياق جديدة
أدِر نافذة سياق Bob للحفاظ على الذاكرة والتحكم في التكلفة وجودة المخرجات أثناء المحادثات المعقدة أو الطويلة.