> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zenable.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Policy as Code

> Automatic conversion of policies to executable rules with version control and testing

## Overview

Translating governance policies into enforceable technical controls is error-prone. Zenable provides automatic conversion of policies to executable rules with version control and testing, ensuring 100% policy enforcement with full traceability.

## How Zenable Works

Upload your policy documents once, and Zenable automatically:

1. **Extracts** technical requirements from natural language
2. **Converts** them into enforceable rules
3. **Applies** them across every line of code

## Creating Policies as Code

<Steps>
  <Step title="Create Your Requirements">
    Go to [zenable.app/requirements](https://www.zenable.app/requirements?utm_source=docs\&utm_medium=policy-as-code\&utm_content=requirements) to:

    * Upload a policy document, or
    * Create a requirement directly
  </Step>

  <Step title="View Guardrails as Code">
    Visit [zenable.app/guardrails](https://www.zenable.app/guardrails?utm_source=docs\&utm_medium=policy-as-code\&utm_content=guardrails) to see your requirements translated into executable guardrails
  </Step>

  <Step title="Automatic Enforcement">
    Your policies are now automatically enforced across all development - no additional configuration needed
  </Step>
</Steps>

## Real-World Policy Example

Imagine uploading a policy document that states:

> "All payment processing code must use encrypted channels, implement idempotency keys, log all transactions with correlation IDs, and retry failed transactions with exponential backoff."

### What Zenable Prevents

With this policy uploaded, Zenable automatically enforces:

<Card title="Missing Encryption" icon="lock">
  ```python theme={null}
  # ❌ Would be flagged
  def process_payment(amount, card):
      response = requests.post(
          "http://payment-api.com/charge",  # Unencrypted!
          json={"amount": amount, "card": card}
      )

  # ✅ Zenable ensures
  def process_payment(amount, card):
      response = requests.post(
          "https://payment-api.com/charge",  # Encrypted
          json={"amount": amount, "card": card}
      )
  ```
</Card>

<Card title="Missing Idempotency" icon="shield-halved">
  ```python theme={null}
  # ❌ Would be flagged
  def charge_customer(customer_id, amount):
      return payment_gateway.charge(customer_id, amount)

  # ✅ Zenable ensures
  def charge_customer(customer_id, amount, idempotency_key=None):
      if not idempotency_key:
          idempotency_key = generate_idempotency_key()
      return payment_gateway.charge(
          customer_id, amount,
          idempotency_key=idempotency_key
      )
  ```
</Card>

## Policy Definition

### Creating Custom Policies

Simply upload your policy documents to Zenable, and we automatically convert them into enforceable rules applied through CLI and IDE integrations.

#### Example: Security Policy

```yaml expandable theme={null}
# security-policy.yaml (conceptual - configured in Zenable platform)
rules:
  - id: hardcoded-api-key
    patterns:
      - pattern-either:
          - pattern: $KEY = "..."
          - pattern: $KEY = '...'
      - metavariable-regex:
          metavariable: $KEY
          regex: (?i).*(api_key|apikey|api-key|secret_key|secret-key)
    message: |
      Hardcoded API key detected. This is a security risk.
      Store API keys in environment variables or secure key management systems.
    languages: [python, javascript, java]
    severity: ERROR
    metadata:
      category: security
      cwe: CWE-798
      owasp: A3

  - id: sql-injection-string-concat
    patterns:
      - pattern-either:
          - pattern: |
              $QUERY = "..." + $INPUT + "..."
              ...
              $CURSOR.execute($QUERY, ...)
          - pattern: |
              $QUERY = f"... {$INPUT} ..."
              ...
              $CURSOR.execute($QUERY, ...)
          - pattern: |
              $QUERY = "...".format($INPUT)
              ...
              $CURSOR.execute($QUERY, ...)
    message: |
      SQL query constructed using string concatenation with user input.
      This can lead to SQL injection vulnerabilities.
      Use parameterized queries instead.
    languages: [python]
    severity: ERROR
    metadata:
      category: security
      cwe: CWE-89
      owasp: A1

  - id: missing-authentication-decorator
    patterns:
      - pattern: |
          @app.route(...)
          def $FUNC(...):
            ...
      - pattern-not: |
          @app.route(...)
          @require_auth
          def $FUNC(...):
            ...
      - metavariable-regex:
          metavariable: $FUNC
          regex: .*(admin|user|account|profile|settings).*
    message: |
      Sensitive endpoint detected without authentication decorator.
      Add @require_auth to protect this endpoint.
    languages: [python]
    severity: WARNING
    metadata:
      category: security
      cwe: CWE-306
```

#### Example: Code Quality Policy

```yaml expandable theme={null}
# quality-policy.yaml (conceptual - configured in Zenable platform)
rules:
  - id: no-empty-exception-handlers
    patterns:
      - pattern: |
          try:
            ...
          except $EXCEPTION:
            pass
    message: |
      Empty exception handler detected. This can hide errors and make debugging difficult.
      At minimum, log the exception or add a comment explaining why it's being ignored.
    languages: [python]
    severity: WARNING
    metadata:
      category: best-practice

  - id: no-console-log-production
    patterns:
      - pattern-either:
          - pattern: console.log(...)
          - pattern: console.debug(...)
          - pattern: console.info(...)
    message: |
      Console logging detected. Remove or replace with proper logging before production.
    languages: [javascript, typescript]
    severity: INFO
    metadata:
      category: best-practice

  - id: missing-error-handling
    patterns:
      - pattern: |
          $PROMISE = $ASYNC_FUNC(...)
      - pattern-not: |
          $PROMISE = $ASYNC_FUNC(...).catch(...)
      - pattern-not: |
          try {
            ...
            $PROMISE = await $ASYNC_FUNC(...)
            ...
          } catch (...) {
            ...
          }
    message: |
      Async operation without error handling. Add .catch() or try/catch block.
    languages: [javascript, typescript]
    severity: WARNING
    metadata:
      category: error-handling
```

## Policy Enforcement Strategies

### Development-Time Enforcement

<Steps>
  <Step title="IDE Integration">
    With Zenable MCP installed, policies are enforced as developers write code:

    ```bash theme={null}
    zenable install
    ```

    The AI assistant will automatically:

    * Check code against policies
    * Suggest corrections
    * Apply fixes
  </Step>

  <Step title="Pre-commit Hooks">
    Enforce policies before code is committed:

    ```yaml theme={null}
    # .pre-commit-config.yaml
    ---
    repos:
     - repo: https://github.com/Zenable-io/ai-native-python
       rev: v0.2.0 # Use `pre-commit autoupdate --freeze` to safely maintain this
       hooks:
         - id: zenable-check
    ```
  </Step>

  <Step title="GitHub Integration">
    Install the [GitHub App](https://zenable.io/github?utm_source=docs\&utm_medium=policy-as-code\&utm_content=github-install) for automatic PR reviews. Once installed, every pull request is automatically reviewed against your policies.
  </Step>
</Steps>

## Next Steps

* Review our [Deployment & Rollout Guide](/deployment/rollout-guide) for best practices
* Set up [Supply Chain Security](/use-cases/supply-chain-security) policies
* Configure [AI Tools Integration](/use-cases/ai-tools-new-features) with policies
* Implement [Compliance Assessment](/use-cases/compliance-pre-audit) based on policies
