Skip to content

Learning Mode

import { Aside, Steps, Tabs, TabItem } from ‘@astrojs/starlight/components’;

Learning Mode

Pro Feature - Requires a ContractShield Pro license.

Learning Mode observes your API traffic in real-time, analyzes patterns, and suggests security rules. It’s the fastest way to bootstrap ContractShield protection for existing APIs.

How It Works

┌─────────────────────────────────────────────────────────────┐
│ Your Application │
│ │
│ Request ──▶ [ContractShield] ──▶ [Your Handler] ──▶ Response │
│ │ │
│ ▼ │
│ [Learning Mode] │
│ │ │
│ Samples (10% default) │
│ │ │
│ ▼ │
│ [Analysis] │
│ │ │
│ ▼ │
│ Suggested Security Rules │
└─────────────────────────────────────────────────────────────┘

Learning Mode:

  1. Collects a sample of API requests (configurable rate)
  2. Analyzes patterns: schemas, value ranges, invariants
  3. Detects potential vulnerabilities in observed traffic
  4. Suggests security rules in YAML/JSON format

Quick Start

  1. Enable Learning Mode

    import { contractshield, enableLearning } from '@cshield/pro';
    const shield = contractshield({
    policy: './policy.yaml',
    license: process.env.CONTRACTSHIELD_LICENSE_KEY,
    });
    // Enable learning with default settings
    enableLearning(shield, {
    sampling: { rate: 0.1 }, // 10% of requests
    storage: { path: './.contractshield/learning' },
    });
    app.use(shield);
  2. Let it observe traffic

    Run your application normally. Learning Mode collects samples in the background without impacting performance.

  3. Generate suggestions

    Terminal window
    npx contractshield learn analyze --output suggestions.yaml
  4. Review and apply

    Review the suggestions, adjust as needed, and add to your policy.

Configuration

enableLearning(shield, {
// Sampling
sampling: {
rate: 0.1, // 0.0 - 1.0 (default: 0.1 = 10%)
},
// Storage
storage: {
path: './.contractshield/learning', // Where to store samples
maxSize: '500MB', // Auto-purge when exceeded
ttl: 7 * 24 * 60 * 60 * 1000, // 7 days retention
encryption: false, // Optional AES-256 encryption
},
// Redaction (automatic)
redaction: {
// These are ALWAYS redacted (built-in, not configurable)
// password, token, secret, apikey, authorization, creditcard, ssn, etc.
// Add custom patterns
customPatterns: ['my_secret_field', /custom_\w+_token/],
},
});

CLI Commands

Start/Stop Collection

Terminal window
# Start learning (if not enabled in code)
npx contractshield learn start
# Stop learning
npx contractshield learn stop
# Check status
npx contractshield learn status

Analyze Collected Data

Terminal window
# Analyze and output suggestions
npx contractshield learn analyze
# Output to file
npx contractshield learn analyze --output suggestions.yaml
# JSON format
npx contractshield learn analyze --format json --output suggestions.json
# Analyze specific routes only
npx contractshield learn analyze --routes "POST /api/orders" "PUT /api/orders/*"

Manage Storage

Terminal window
# View storage stats
npx contractshield learn stats
# Purge old samples
npx contractshield learn purge --older-than 7d
# Clear all samples
npx contractshield learn purge --all

What Learning Mode Detects

Schema Inference

Analyzes request bodies to infer JSON Schema:

# Suggested schema for POST /api/orders
schemas:
POST /api/orders:
type: object
required: [customerId, items]
properties:
customerId:
type: string
pattern: "^cust_[a-z0-9]{8}$"
items:
type: array
minItems: 1
items:
type: object
properties:
productId: { type: string }
quantity: { type: integer, minimum: 1 }

Value Ranges

Detects typical ranges for numeric fields:

# Observed ranges
ranges:
POST /api/orders:
items.quantity:
observed: { min: 1, max: 100, avg: 3.2 }
suggested: { minimum: 1, maximum: 100 }
items.price:
observed: { min: 0.99, max: 9999.99 }
suggested: { minimum: 0, maximum: 10000 }

Invariants

Discovers relationships between fields:

# Suggested CEL invariants
invariants:
POST /api/orders:
- expr: "size(body.items) <= 50"
reason: "No order observed with more than 50 items"
- expr: "body.shipping.country in ['US', 'CA', 'MX']"
reason: "Only these countries observed in 10,000 samples"

Vulnerability Patterns

Flags suspicious patterns in observed traffic:

# Potential vulnerabilities detected
vulnerabilities:
- route: "GET /api/files"
type: "path_traversal_attempt"
samples: 23
example: "?path=../../etc/passwd"
recommendation: "Add path validation"
- route: "POST /api/search"
type: "nosql_injection_attempt"
samples: 5
example: '{"query": {"$where": "..."}}'
recommendation: "Enable NoSQL injection protection"

Security & Privacy

Automatic Redaction

These fields are always redacted (not configurable):

  • password, passwd, pwd
  • token, apikey, api_key, secret
  • authorization, bearer, jwt
  • creditcard, credit_card, cvv, ssn
  • cookie, session

Headers that are never stored:

  • Authorization
  • Cookie
  • X-API-Key
  • X-Auth-Token

Storage Security

  • Files are stored with 0600 permissions (owner read/write only)
  • Storage directory has 0700 permissions
  • Optional AES-256-GCM encryption for high-security environments
  • Automatic TTL-based purging

Sampling

Only a percentage of requests are sampled (default 10%). This:

  • Reduces storage requirements
  • Provides statistical significance
  • Minimizes performance impact

Performance Impact

AspectImpact
Request latency< 0.1ms (async, non-blocking)
Memory usage~10MB buffer
CPUNegligible (sampling + async write)
Disk I/OAsync, batched writes

Learning Mode is designed for production use. The collection is fire-and-forget and never blocks your request handlers.

Best Practices

1. Run During Representative Traffic

Enable Learning Mode when your API receives typical traffic patterns. Avoid:

  • Load testing periods (skews data)
  • Maintenance windows (low traffic)
  • Attack simulations (unless intentional)

2. Review Before Applying

Learning Mode suggests rules, it doesn’t apply them automatically. Always review:

  • Are the inferred schemas too strict?
  • Do invariants match your business logic?
  • Are there false positives in vulnerability detection?

3. Iterate

Terminal window
# Week 1: Collect
npx contractshield learn start
# Week 2: Analyze
npx contractshield learn analyze --output v1-suggestions.yaml
# Review, adjust, apply partial rules
# Week 3: Collect more
npx contractshield learn purge --all
npx contractshield learn start
# Week 4: Refine
npx contractshield learn analyze --output v2-suggestions.yaml

4. Use for New Endpoints

When adding new API endpoints:

  1. Deploy without strict contracts
  2. Enable Learning Mode for the new routes
  3. Analyze after sufficient traffic
  4. Apply generated contracts

Troubleshooting

”No samples collected”

  • Check that Learning Mode is enabled
  • Verify the sampling rate isn’t too low
  • Ensure the storage path is writable

”Storage full"

Terminal window
# Check usage
npx contractshield learn stats
# Purge old data
npx contractshield learn purge --older-than 3d

"Suggestions seem wrong”

  • Ensure you have enough samples (1000+ per route recommended)
  • Check for unusual traffic patterns in the collection period
  • Use --routes flag to focus on specific endpoints

API Reference

enableLearning(shield, options)

interface LearningOptions {
sampling: {
rate: number; // 0.0-1.0, default 0.1
};
storage: {
path: string; // Storage directory
maxSize?: string; // e.g., '500MB', '1GB'
ttl?: number; // Milliseconds, default 7 days
encryption?: boolean; // AES-256-GCM, default false
encryptionKey?: string; // Required if encryption: true
};
redaction?: {
customPatterns?: (string | RegExp)[];
};
}

disableLearning(shield)

Stops collection and flushes pending samples.

import { disableLearning } from '@cshield/pro';
// Graceful shutdown
process.on('SIGTERM', async () => {
await disableLearning(shield);
process.exit(0);
});