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:
- Collects a sample of API requests (configurable rate)
- Analyzes patterns: schemas, value ranges, invariants
- Detects potential vulnerabilities in observed traffic
- Suggests security rules in YAML/JSON format
Quick Start
-
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 settingsenableLearning(shield, {sampling: { rate: 0.1 }, // 10% of requestsstorage: { path: './.contractshield/learning' },});app.use(shield); -
Let it observe traffic
Run your application normally. Learning Mode collects samples in the background without impacting performance.
-
Generate suggestions
Terminal window npx contractshield learn analyze --output suggestions.yaml -
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
# Start learning (if not enabled in code)npx contractshield learn start
# Stop learningnpx contractshield learn stop
# Check statusnpx contractshield learn statusAnalyze Collected Data
# Analyze and output suggestionsnpx contractshield learn analyze
# Output to filenpx contractshield learn analyze --output suggestions.yaml
# JSON formatnpx contractshield learn analyze --format json --output suggestions.json
# Analyze specific routes onlynpx contractshield learn analyze --routes "POST /api/orders" "PUT /api/orders/*"Manage Storage
# View storage statsnpx contractshield learn stats
# Purge old samplesnpx contractshield learn purge --older-than 7d
# Clear all samplesnpx contractshield learn purge --allWhat Learning Mode Detects
Schema Inference
Analyzes request bodies to infer JSON Schema:
# Suggested schema for POST /api/ordersschemas: 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 rangesranges: 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 invariantsinvariants: 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 detectedvulnerabilities: - 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,pwdtoken,apikey,api_key,secretauthorization,bearer,jwtcreditcard,credit_card,cvv,ssncookie,session
Headers that are never stored:
AuthorizationCookieX-API-KeyX-Auth-Token
Storage Security
- Files are stored with
0600permissions (owner read/write only) - Storage directory has
0700permissions - 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
| Aspect | Impact |
|---|---|
| Request latency | < 0.1ms (async, non-blocking) |
| Memory usage | ~10MB buffer |
| CPU | Negligible (sampling + async write) |
| Disk I/O | Async, 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
# Week 1: Collectnpx contractshield learn start
# Week 2: Analyzenpx contractshield learn analyze --output v1-suggestions.yaml
# Review, adjust, apply partial rules
# Week 3: Collect morenpx contractshield learn purge --allnpx contractshield learn start
# Week 4: Refinenpx contractshield learn analyze --output v2-suggestions.yaml4. Use for New Endpoints
When adding new API endpoints:
- Deploy without strict contracts
- Enable Learning Mode for the new routes
- Analyze after sufficient traffic
- 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"
# Check usagenpx contractshield learn stats
# Purge old datanpx 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
--routesflag 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 shutdownprocess.on('SIGTERM', async () => { await disableLearning(shield); process.exit(0);});