0Pricing
AI Agents · บทเรียน

การบังคับใช้นโยบายกับการกระทำของเอเจนต์

ตรวจสอบนโยบายก่อนดำเนินการ รายการอนุญาตและรายการปฏิเสธ และกฎนโยบายแบบไดนามิก

การบังคับใช้นโยบายกับการกระทำของเอเจนต์ เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน

การบังคับใช้นโยบายเอเจนต์คืออะไร

การบังคับใช้นโยบายคือจุดตรวจ ณ เวลาทำงานที่ทำงาน ก่อนการกระทำของเอเจนต์ทุกครั้ง เพื่อตัดสินว่าการกระทำนั้นได้รับอนุญาตหรือไม่ หากไม่มีสิ่งนี้ ข้อจำกัดเพียงอย่างเดียวของเอเจนต์คือความสามารถของ LLM ในการทำตามคำสั่ง ซึ่งอาจถูกหลีกเลี่ยงหรือตีความผิดได้

การบังคับใช้ต้องอยู่ ภายนอก LLM และอยู่ในโครงสร้างพื้นฐานของคุณ

รูปแบบการตรวจสอบก่อนดำเนินการ

ก่อนเรียกใช้เครื่องมือใด ๆ ให้เรียก can_agent_do(action, context) ฟังก์ชันนี้คือจุดบังคับใช้เพียงจุดเดียว เส้นทางทุกเส้นทางที่นำไปสู่การดำเนินการจะต้องผ่านฟังก์ชันนี้

def can_agent_do(action: str, context: dict) -> tuple[bool, str]:
    '''
    Returns (allowed: bool, reason: str).
    Context includes: user_id, agent_id, session_id, parameters, timestamp.
    '''
    # 1. Check denylist first (fast path for obvious violations)
    if action in DENIED_ACTIONS:
        return False, f'Action "{action}" is on the global denylist'

    # 2. Check allowlist
    if action not in ALLOWED_ACTIONS:
        return False, f'Action "{action}" is not on the allowlist'

    # 3. Context-specific checks
    return check_context_policy(action, context)

กำหนดรายการอนุญาตและรายการปฏิเสธ

รายการอนุญาตจะแสดงการกระทำทั้งหมดที่เอเจนต์ได้รับอนุญาตให้ทำ สิ่งใดก็ตามที่ไม่อยู่ในรายการจะถูกบล็อกเป็นค่าเริ่มต้น ส่วน รายการปฏิเสธจะเพิ่มชั้นความปลอดภัยอีกระดับสำหรับการกระทำที่ไม่ควรได้รับอนุญาตไม่ว่าบริบทจะเป็นอย่างไร

# Allowlist: tools the agent can use
ALLOWED_ACTIONS = {
    'web_search',
    'read_file',
    'write_file',
    'send_email',
    'create_calendar_event',
    'query_database',
    'execute_python_sandbox',
    'fetch_url',
    'create_ticket'
}

# Denylist: actions that are always blocked, regardless of context
DENIED_ACTIONS = {
    'delete_all_records',
    'export_entire_database',
    'send_mass_email',
    'modify_system_config',
    'create_admin_user',
    'disable_audit_logging'
}

if __name__ == '__main__':
    for action in ('web_search', 'send_mass_email'):
        print(f"{action}: allowed={action in ALLOWED_ACTIONS} denied={action in DENIED_ACTIONS}")

การตรวจสอบนโยบายตามบริบท

นอกเหนือจากรายการอนุญาตและรายการปฏิเสธแบบง่ายแล้ว นโยบายมักขึ้นอยู่กับบริบท เช่น ผู้ใช้คือใคร มีบทบาทอะไร ขณะนี้กี่โมง และทรัพยากรเป้าหมายคืออะไร สิ่งเหล่านี้คือการตรวจสอบตามบริบท

from datetime import datetime, timezone

def check_context_policy(action: str, context: dict) -> tuple[bool, str]:
    user_id   = context.get('user_id', '')
    params    = context.get('parameters', {})
    user_role = context.get('user_role', 'user')

    # send_email: only agents with email_sender role
    if action == 'send_email':
        if user_role not in ('email_agent', 'admin'):
            return False, f'Role "{user_role}" cannot send emails'
        recipient = params.get('to', '')
        if not recipient.endswith('@trusted-domain.com'):
            return False, 'Email recipient must be in @trusted-domain.com'

    # write_file: path restrictions
    if action == 'write_file':
        path = params.get('path', '')
        if not path.startswith('/tmp/') and not path.startswith('/workspace/'):
            return False, f'File writes outside /tmp/ and /workspace/ are not allowed'

    return True, 'Permitted'

if __name__ == '__main__':
    ctx = {'user_id': 'u1', 'user_role': 'user',
           'parameters': {'to': 'someone@gmail.com'}}
    print('send_email as user:', check_context_policy('send_email', ctx))

    ctx2 = {'user_id': 'u1', 'user_role': 'user',
            'parameters': {'path': '/etc/passwd'}}
    print('write_file outside sandbox:', check_context_policy('write_file', ctx2))

นโยบายแบบไดนามิกจากกลไกนโยบาย

นโยบายที่เขียนตายตัวในโค้ดแก้ไขได้ยากเมื่อใช้งานจริง ให้ใช้กลไกนโยบาย เช่น OPA — เอเจนต์นโยบายแบบเปิด เพื่อประเมินนโยบายที่กำหนดเป็นข้อมูล ไม่ใช่โค้ด คุณสามารถอัปเดตนโยบายได้โดยไม่ต้องนำเอเจนต์ไปติดตั้งใหม่

import requests

OPA_URL = 'http://localhost:8181/v1/data/agent/allow'

def opa_policy_check(action: str, context: dict) -> tuple[bool, str]:
    payload = {
        'input': {
            'action':   action,
            'user_id':  context.get('user_id'),
            'role':     context.get('user_role', 'user'),
            'params':   context.get('parameters', {}),
            'time_utc': datetime.now(timezone.utc).isoformat()
        }
    }
    try:
        resp = requests.post(OPA_URL, json=payload, timeout=0.5)
        result = resp.json().get('result', {})
        allowed = result.get('allow', False)
        reason  = result.get('reason', 'Policy decision')
        return allowed, reason
    except Exception as e:
        # Fail closed: deny if policy engine is unreachable
        return False, f'Policy engine unavailable: {e}'

ปฏิเสธเมื่อขัดข้องเทียบกับอนุญาตเมื่อขัดข้อง

เมื่อกลไกนโยบายไม่พร้อมใช้งาน คุณมีทางเลือกสองแบบ:

  • ปฏิเสธเมื่อขัดข้อง: ปฏิเสธการกระทำทั้งหมด ปลอดภัย แต่เอเจนต์จะหยุดทำงาน
  • อนุญาตเมื่อขัดข้อง: อนุญาตการกระทำทั้งหมด เอเจนต์ยังทำงานต่อได้ แต่นโยบายจะไม่ถูกบังคับใช้

สำหรับเอเจนต์ที่อ่อนไหวด้านความปลอดภัย ให้ปฏิเสธเมื่อขัดข้องเสมอ สำหรับเอเจนต์ด้านประสิทธิภาพการทำงานที่มีการกระทำความเสี่ยงต่ำ การอนุญาตเมื่อขัดข้องอาจยอมรับได้

FAIL_CLOSED = True  # Configure per agent

def safe_policy_check(action: str, context: dict) -> tuple[bool, str]:
    try:
        return can_agent_do(action, context)
    except Exception as e:
        if FAIL_CLOSED:
            return False, f'Policy check failed (fail-closed): {e}'
        else:
            # Log the failure but allow the action
            import logging
            logging.warning('Policy check error (fail-open): %s', e)
            return True, 'Policy check bypassed due to error (fail-open)'

จำกัดอัตราการกระทำ

การบังคับใช้นโยบายอาจรวมถึงขีดจำกัดอัตราการกระทำ เช่น เอเจนต์อาจได้รับอนุญาตให้ส่งอีเมลได้ แต่ส่งได้เพียง 5 ฉบับต่อเซสชันเท่านั้น หากเกินขีดจำกัด การกระทำนั้นจะถูกปฏิเสธ

from collections import defaultdict
import time

action_counts: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
action_window_start: dict[str, float] = defaultdict(float)

ACTION_RATE_LIMITS = {
    'send_email':   {'limit': 5,  'window_secs': 3600},  # 5/hour
    'write_file':   {'limit': 50, 'window_secs': 300},
    'web_search':   {'limit': 20, 'window_secs': 60}
}

def check_rate_limit(action: str, session_id: str) -> tuple[bool, str]:
    limit_config = ACTION_RATE_LIMITS.get(action)
    if not limit_config:
        return True, 'No rate limit defined'

    window = limit_config['window_secs']
    now = time.time()
    key = f'{session_id}:{action}'

    if now - action_window_start[key] > window:
        action_counts[key] = defaultdict(int)
        action_window_start[key] = now

    action_counts[key]['count'] += 1
    if action_counts[key]['count'] > limit_config['limit']:
        return False, f'Rate limit exceeded: {action} ({limit_config["limit"]}/{window}s)'
    return True, 'Within rate limit'

if __name__ == '__main__':
    for i in range(6):
        allowed, reason = check_rate_limit('send_email', 'session-1')
    print(f'After 6 send_email calls: allowed={allowed}, reason={reason}')

บันทึกการละเมิดนโยบาย

การปฏิเสธตามนโยบายทุกครั้งต้องบันทึกพร้อมบริบทอย่างครบถ้วน บันทึกเหล่านี้คือจุดแรกที่ควรตรวจสอบเมื่อแก้ไขพฤติกรรมเอเจนต์ที่ไม่คาดคิดหรือสืบสวนเหตุการณ์ด้านความปลอดภัย

import logging, json, time

policy_logger = logging.getLogger('agent.policy')

def enforced_action(agent_id: str, user_id: str, action: str,
                    context: dict, audit_log) -> tuple[bool, str]:
    allowed, reason = safe_policy_check(action, context)

    log_entry = {
        'ts':       time.time(),
        'agent_id': agent_id,
        'user_id':  user_id,
        'action':   action,
        'allowed':  allowed,
        'reason':   reason,
        'params':   context.get('parameters', {})
    }

    if allowed:
        policy_logger.info('ALLOWED %s', json.dumps(log_entry))
    else:
        policy_logger.warning('DENIED %s', json.dumps(log_entry))

    audit_log.append(
        agent_id, user_id,
        f'POLICY_{"ALLOW" if allowed else "DENY"}',
        {'action': action},
        {'allowed': allowed, 'reason': reason},
        context.get('session_id', '')
    )
    return allowed, reason

กำหนดขอบเขตทรัพยากร

แม้แต่การกระทำที่ได้รับอนุญาตก็ต้องกำหนดขอบเขตทรัพยากรที่เอเจนต์เข้าถึงได้ เอเจนต์ที่จัดการเอกสารของผู้ใช้ A ไม่ควรอ่านไฟล์ของผู้ใช้ B ได้ แม้ว่า read_file จะอยู่ในรายการอนุญาตก็ตาม

def check_resource_scope(action: str, context: dict) -> tuple[bool, str]:
    user_id  = context.get('user_id', '')
    params   = context.get('parameters', {})

    if action == 'read_file':
        path = params.get('path', '')
        # Each user's files must be under their own namespace
        if not path.startswith(f'/workspace/{user_id}/'):
            return False, (
                f'User {user_id} cannot read files outside '
                f'/workspace/{user_id}/'
            )

    if action == 'query_database':
        table = params.get('table', '')
        allowed_tables = {'products', 'public_docs', f'user_{user_id}_data'}
        if table not in allowed_tables:
            return False, f'Table "{table}" not in scope for user {user_id}'

    return True, 'Resource scope check passed'

if __name__ == '__main__':
    ctx = {'user_id': 'u1', 'parameters': {'path': '/workspace/u2/secret.txt'}}
    print('Cross-user file read:', check_resource_scope('read_file', ctx))

    ctx2 = {'user_id': 'u1', 'parameters': {'path': '/workspace/u1/notes.txt'}}
    print('Own file read:      ', check_resource_scope('read_file', ctx2))

ทดสอบกฎนโยบาย

กฎนโยบายคือโค้ด จึงต้องผ่านการทดสอบ ให้เขียนการทดสอบหน่วยสำหรับแต่ละกฎ เพื่อให้แน่ใจว่าการปฏิเสธและการอนุญาตทำงานอย่างถูกต้อง และกรณีขอบจะไม่ทำให้เกิดการเลี่ยงการบังคับใช้นโยบายโดยไม่ตั้งใจ

def test_policy_rules():
    # Denylist blocks unconditionally
    ok, msg = can_agent_do('delete_all_records', {'user_role': 'admin'})
    assert not ok, 'Denylist should block even for admin'

    # Email requires trusted domain
    ok, msg = can_agent_do('send_email', {
        'user_role': 'email_agent',
        'parameters': {'to': 'attacker@evil.com'}
    })
    assert not ok, 'Should block untrusted email recipient'

    # File write outside allowed paths
    ok, msg = can_agent_do('write_file', {
        'user_role': 'user',
        'parameters': {'path': '/etc/crontab'}
    })
    assert not ok, 'Should block write to /etc/'

    print('All policy tests passed')

test_policy_rules()

แคชการตัดสินใจด้านนโยบาย

การเรียกกลไกนโยบายสำหรับการกระทำทุกครั้งจะเพิ่มความหน่วง โดยเฉพาะเมื่อใช้บริการ OPA ภายนอก ให้แคชการตัดสินใจล่าสุดสำหรับคู่ (การกระทำ, แฮชบริบท) โดยกำหนด TTL ให้สั้น เพื่อลดการเรียกไปกลับ

import hashlib, time

policy_cache: dict[str, dict] = {}
POLICY_CACHE_TTL = 10  # seconds — short TTL so policy updates take effect quickly

def cached_policy_check(action: str, context: dict) -> tuple[bool, str]:
    ctx_hash = hashlib.md5(
        f'{action}:{context.get("user_id")}:{context.get("user_role")}'
        .encode()
    ).hexdigest()
    key = f'{action}:{ctx_hash}'
    entry = policy_cache.get(key)
    if entry and time.time() - entry['ts'] < POLICY_CACHE_TTL:
        return entry['result']
    result = can_agent_do(action, context)
    policy_cache[key] = {'result': result, 'ts': time.time()}
    return result

แนวทางปฏิเสธเมื่อขัดข้องในการบังคับใช้นโยบายคืออะไร

การตัดสินใจระหว่างการปฏิเสธเมื่อขัดข้องกับการอนุญาตเมื่อขัดข้องเป็นการแลกเปลี่ยนด้านความปลอดภัยพื้นฐานสำหรับระบบบังคับใช้นโยบายทุกประเภท การรู้ว่าแต่ละแนวทางเหมาะสมเมื่อใดถือเป็นแนวคิดหลักด้านธรรมาภิบาล

สรุปการบังคับใช้นโยบาย

การบังคับใช้นโยบายเอเจนต์ใช้ การตรวจสอบก่อนดำเนินการ เป็นจุดตรวจเพียงจุดเดียว ใช้ รายการอนุญาต + รายการปฏิเสธ สำหรับการตัดสินใจพื้นฐาน ใช้ กฎตามบริบท สำหรับการกำหนดขอบเขตทรัพยากรและตรวจสอบบทบาท ใช้ กลไกนโยบายแบบไดนามิก (OPA) สำหรับกฎที่อัปเดตได้ ใช้ ขีดจำกัดอัตราการกระทำ แยกตามการกระทำและเซสชัน และใช้ค่าเริ่มต้นแบบ ปฏิเสธเมื่อขัดข้อง สำหรับเอเจนต์ที่มีความสำคัญต่อความปลอดภัย

คำถามที่พบบ่อย

บทเรียน “การบังคับใช้นโยบายกับการกระทำของเอเจนต์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การบังคับใช้นโยบายกับการกระทำของเอเจนต์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การบังคับใช้นโยบายกับการกระทำของเอเจนต์”

ตรวจสอบนโยบายก่อนดำเนินการ รายการอนุญาตและรายการปฏิเสธ และกฎนโยบายแบบไดนามิก คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การบังคับใช้นโยบายกับการกระทำของเอเจนต์” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม

ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การบันทึกการกระทำของเอเจนต์แบบแก้ไขไม่ได้
  2. การบังคับใช้นโยบายกับการกระทำของเอเจนต์
  3. การปฏิบัติตามข้อกำหนด: GDPR และ SOC2
  4. จุดอนุมัติโดยมนุษย์ในวงจรการทำงาน
← กลับไปที่ AI Agents