Skip to content

Démarrage Rapide

Protégez votre agent IA avec EnforceCore en moins de 5 minutes.


Installation

pip install enforcecore

Python 3.11+ requis. Dépendances : Pydantic v2, PyYAML, structlog, cryptography.

Note : EnforceCore est stable à la version v1.0.1. L'API de 30 symboles Tier 1 est gelée.


1. Créer une Politique

Créez un fichier policy.yaml qui définit ce que votre agent peut faire :

name: "ma-politique-agent"
version: "1.0"

rules:
  allowed_tools:
    - "search_web"
    - "read_file"
    - "calculator"
  denied_tools:
    - "execute_shell"
    - "send_email"
  pii_redaction:
    enabled: true
    categories:
      - email
      - phone
      - ssn
      - credit_card
      - ip_address
      - passport

  content_rules:
    enabled: true
    categories:
      - shell_injection
      - path_traversal
      - sql_injection
      - code_execution

  rate_limits:
    per_tool: 10         # max appels par outil par minute
    global: 50           # max appels totaux par minute

  network:
    allowed_domains:
      - "api.example.com"
      - "*.trusted.io"
    denied_domains:
      - "*.evil.com"

  resource_limits:
    max_call_duration_seconds: 30
    max_memory_mb: 256
    max_cost_usd: 1.00

on_violation: "block"

2. Protéger vos Outils

Utilisez le décorateur @enforce sur toute fonction appelée par votre agent :

from enforcecore import enforce

# Fonctions async
@enforce(policy="policy.yaml")
async def search_web(query: str) -> str:
    return await api.search(query)

# Fonctions sync
@enforce(policy="policy.yaml")
def read_file(path: str) -> str:
    return open(path).read()

Chaque appel passe maintenant par le pipeline d'enforcement :

  1. Pré-appel — Évaluation de politique, validation du nom d'outil, vérification de taille
  2. Rédaction entrées — Données personnelles détectées et remplacées
  3. Exécution — L'outil s'exécute avec les limites de ressources
  4. Rédaction sorties — Données personnelles redactées dans la réponse
  5. Audit — Entrée chaînée par Merkle enregistrée

3. Politiques Inline

Pour le prototypage rapide, sans fichier YAML :

@enforce(
    allowed_tools=["search_web", "calculator"],
    pii_redaction=True,
    max_cost_usd=5.0,
)
async def my_tool(args: dict) -> str: ...

4. Hooks de Cycle de Vie

Ajoutez une observabilité personnalisée en vous connectant au pipeline d'enforcement :

from enforcecore import on_violation, on_post_call

@on_violation
def alerte_securite(ctx):
    """Appelé chaque fois qu'un appel d'outil est bloqué."""
    print(f"⚠️ {ctx.tool_name} bloqué : {ctx.violation_type}")

@on_post_call
def log_metriques(ctx):
    """Appelé après chaque appel d'outil réussi."""
    print(f"✅ {ctx.tool_name} terminé en {ctx.overhead_ms:.1f}ms")

5. Contrôle Programmatique

from enforcecore import Enforcer, Policy

enforcer = Enforcer(Policy.from_file("policy.yaml"))
result = await enforcer.enforce_async(search_fn, "query", tool_name="search_web")

6. Vérifier la Piste d'Audit

Chaque appel est enregistré dans un fichier JSONL chaîné par Merkle :

from enforcecore import verify_trail, load_trail

result = verify_trail("audit.jsonl")
print(result.is_valid)        # True
print(result.chain_intact)    # Aucune falsification

trail = load_trail("audit.jsonl")
for entry in trail:
    print(f"{entry.tool_name} → {entry.decision}")

7. Tester vos Politiques

from enforcecore.core.policy import Policy
from enforcecore.eval import ScenarioRunner

policy = Policy.from_file("policy.yaml")
runner = ScenarioRunner(policy)
suite = runner.run_all()
print(f"Taux de confinement : {suite.containment_rate:.0%}")

Configuration

ENFORCECORE_DEFAULT_POLICY=policies/default.yaml
ENFORCECORE_AUDIT_PATH=./audit_logs/
ENFORCECORE_AUDIT_ENABLED=true
ENFORCECORE_REDACTION_ENABLED=true
ENFORCECORE_LOG_LEVEL=INFO
ENFORCECORE_COST_BUDGET_USD=100.0
ENFORCECORE_FAIL_OPEN=false   # JAMAIS true en production
ENFORCECORE_DEV_MODE=false
ENFORCECORE_AUDIT_IMMUTABLE=false       # Fichiers d'audit append-only au niveau OS
ENFORCECORE_AUDIT_WITNESS_FILE=         # Chemin du fichier witness JSONL

8. Renforcer votre Piste d'Audit (v1.0.0b4+)

Pour une protection maximale contre la falsification, activez les fichiers append-only et un backend witness :

# Via variables d'environnement (zéro modification de code)
ENFORCECORE_AUDIT_IMMUTABLE=true
ENFORCECORE_AUDIT_WITNESS_FILE=/secure/witness.jsonl

Ou programmatiquement :

from enforcecore import Auditor
from enforcecore.auditor.witness import FileWitness

auditor = Auditor(
    output_path="audit.jsonl",
    immutable=True,  # Append-only au niveau OS (chattr +a / chflags uappend)
    witness=FileWitness("/secure/witness.jsonl"),  # Witness à hash uniquement
)

Vérification croisée avec le witness :

from enforcecore.auditor.witness import verify_with_witness

result = verify_with_witness(
    trail_path="audit.jsonl",
    witness_path="/secure/witness.jsonl",
)
assert result.is_valid  # Détecte les attaques par reconstruction de chaîne

Prochaines Étapes

ESC