YAML Contract Definitions: A Complete Guide for ContractShield
Learn how to define API security contracts using YAML in ContractShield. Human-readable, version-control friendly, and powerful.
ContractShield supports both JSON and YAML for defining API contracts. While both formats work identically, YAML has become the preferred choice for many teams. In this guide, we'll explore why YAML works so well for security contracts and walk through practical examples.
Why YAML for Security Contracts?
YAML offers several advantages over JSON when defining contracts:
- → Comments: Document the "why" behind each rule directly in the file
- → Readability: Less visual noise without quotes and braces everywhere
- → Multi-line strings: Write complex CEL expressions cleanly
- → Git-friendly: Cleaner diffs when contracts evolve
Anatomy of a YAML Contract
A ContractShield contract has three main sections: endpoint matching, schema validation, and business logic invariants.
# contracts/users-create.yaml
# Security contract for user registration
endpoint: /api/users
method: POST
# JSON Schema for request structure
schema:
type: object
required:
- email
- password
- role
properties:
email:
type: string
format: email
password:
type: string
minLength: 12
role:
type: string
enum: [user, admin, moderator]
additionalProperties: false
# CEL invariants for business logic
invariants:
- expr: 'request.body.role != "admin" || context.user.isAdmin'
message: Only admins can create admin accounts
- expr: |
request.body.email.endsWith("@company.com") ||
request.body.role == "user"
message: External emails can only have user role Schema vs Invariants: When to Use Each
Understanding the difference between schema validation and CEL invariants is key to writing effective contracts.
| Aspect | Schema (YAML) | Invariants (CEL) |
|---|---|---|
| Purpose | Structure & types | Business logic |
| Example | type: integer | qty > 0 && qty <= stock |
| Context | Request body only | Body + headers + user context |
| Cross-field | Limited | Full support |
Real-World Examples
E-commerce: Order Creation
# contracts/orders-create.yaml
endpoint: /api/orders
method: POST
schema:
type: object
required: [items, shippingAddress]
properties:
items:
type: array
minItems: 1
maxItems: 50
items:
type: object
required: [productId, quantity, unitPrice]
properties:
productId:
type: string
pattern: "^SKU-[A-Z0-9]+$"
quantity:
type: integer
minimum: 1
unitPrice:
type: number
minimum: 0
couponCode:
type: string
maxLength: 20
shippingAddress:
type: object
required: [country, postalCode]
invariants:
# Prevent negative total exploits
- expr: |
request.body.items.all(item,
item.quantity > 0 && item.unitPrice >= 0
)
message: Invalid item quantity or price
# Verify total matches line items
- expr: |
!has(request.body.total) ||
request.body.total == request.body.items
.map(i, i.quantity * i.unitPrice)
.sum()
message: Total does not match item prices
# Daily order limit for fraud prevention
- expr: context.user.dailyOrderCount < 10
message: Daily order limit exceeded SaaS: API Key Management
# contracts/api-keys-create.yaml
endpoint: /api/keys
method: POST
schema:
type: object
required: [name, scopes]
properties:
name:
type: string
minLength: 3
maxLength: 50
scopes:
type: array
items:
type: string
enum: [read, write, delete, admin]
expiresIn:
type: integer
minimum: 3600 # 1 hour minimum
maximum: 31536000 # 1 year maximum
invariants:
# Only admins can create admin-scoped keys
- expr: |
!("admin" in request.body.scopes) ||
context.user.role == "admin"
message: Admin scope requires admin role
# Enforce key limits by plan
- expr: context.user.apiKeyCount < context.tenant.maxApiKeys
message: API key limit reached for your plan IDE Support with Schema Validation
Get autocomplete and validation in your editor by adding the schema directive:
# yaml-language-server: $schema=https://contractshield.dev/schemas/policy.v0.1.json
endpoint: /api/users
method: POST
# Your editor now provides autocomplete and validation! Loading YAML Contracts
ContractShield automatically loads both .json and .yaml files from your contracts directory:
import express from 'express';
import { contractshield } from '@cshield/pep-express';
const app = express();
app.use(express.json());
// Load all contracts from directory
app.use(contractshield({
contractsDir: './contracts', // Loads *.yaml and *.json
strict: true,
}));
app.listen(3000); Best Practices
- 1. One file per endpoint-method pair
Use naming like
users-post.yaml,users-id-put.yaml - 2. Comment the business reason
Future you will thank present you for explaining why that limit is 10000
- 3. Version contracts with your API
Contracts should evolve alongside your code in the same PR
- 4. Use strict mode in production
Reject requests to endpoints without contracts
Migrating from JSON
Already have JSON contracts? The conversion is straightforward since YAML is a superset of JSON:
# JSON
{
"endpoint": "/api/users",
"method": "POST",
"schema": {
"type": "object",
"properties": {
"email": { "type": "string", "format": "email" }
}
}
}
# Equivalent YAML
endpoint: /api/users
method: POST
schema:
type: object
properties:
email:
type: string
format: email Pro tip: Many online converters can do this automatically. Just clean up the output to use YAML's cleaner syntax.
Ready to define your contracts?
Check out the full documentation for schema reference, CEL expression guide, and more examples.