Skip to content

Context Patterns

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

Context Patterns

The request context is the data available to your CEL expressions. Learning to use it effectively is key to powerful business logic validation.

Context Structure

interface RequestContext {
version: "0.1";
id?: string;
timestamp?: string;
request: {
method: string;
path: string;
routeId?: string;
headers?: Record<string, string>;
query?: Record<string, unknown>;
contentType?: string;
body?: any;
};
identity?: {
authenticated?: boolean;
subject?: string; // User ID
tenant?: string; // Organization/tenant ID
scopes?: string[]; // Permissions
claims?: Record<string, unknown>; // Custom claims
};
client?: {
ip?: string;
userAgent?: string;
};
runtime?: {
language?: string;
service?: string;
env?: string;
};
webhook?: {
provider?: string;
signatureValid?: boolean;
replayed?: boolean;
};
}

Pattern 1: E-commerce Order Validation

A complete example for an e-commerce platform.

Identity Extractor

app.use(contractshield({
policy: './policy.yaml',
identityExtractor: (req) => ({
authenticated: !!req.user,
subject: req.user?.id,
tenant: req.user?.organizationId,
scopes: req.user?.permissions || [],
claims: {
tier: req.user?.subscriptionTier, // "free", "pro", "enterprise"
dailyOrderCount: req.user?.dailyOrders, // For rate limiting
creditLimit: req.user?.creditLimit
}
})
}));

Policy

routes:
- id: orders.create
match:
method: POST
path: /api/orders
contract:
requestSchema:
type: object
properties:
items:
type: array
minItems: 1
items:
type: object
properties:
sku: { type: string }
quantity: { type: integer, minimum: 1 }
unitPrice: { type: number, minimum: 0 }
required: [sku, quantity, unitPrice]
total: { type: number, minimum: 0 }
couponCode: { type: string }
required: [items, total]
rules:
# Authentication required
- id: auth.required
type: cel
action: block
severity: critical
config:
expr: "identity.authenticated == true"
message: "Authentication required"
# Total must match items
- id: order.total.valid
type: cel
action: block
severity: high
config:
expr: |
request.body.total == sum(request.body.items.map(i, i.unitPrice * i.quantity))
message: "Order total does not match sum of items"
# All quantities must be positive
- id: order.quantities.positive
type: cel
action: block
config:
expr: "request.body.items.all(i, i.quantity > 0)"
message: "All quantities must be positive"
# Max items based on subscription tier
- id: order.items.limit
type: cel
action: block
config:
expr: |
identity.claims.tier == "enterprise" ? size(request.body.items) <= 500 :
identity.claims.tier == "pro" ? size(request.body.items) <= 100 :
size(request.body.items) <= 20
message: "Order exceeds item limit for your subscription tier"
# Credit limit check
- id: order.credit.limit
type: cel
action: block
config:
expr: |
!has(identity.claims.creditLimit) ||
request.body.total <= identity.claims.creditLimit
message: "Order exceeds your credit limit"
# Daily order limit (anti-abuse)
- id: order.daily.limit
type: cel
action: block
config:
expr: "identity.claims.dailyOrderCount < 100"
message: "Daily order limit exceeded"

Pattern 2: Multi-Tenant SaaS

Strict tenant isolation for a B2B SaaS application.

Identity Extractor

app.use(contractshield({
policy: './policy.yaml',
identityExtractor: (req) => ({
authenticated: !!req.auth,
subject: req.auth?.userId,
tenant: req.auth?.tenantId,
scopes: req.auth?.scopes || [],
claims: {
role: req.auth?.role, // "owner", "admin", "member", "viewer"
teamId: req.auth?.teamId,
planLimits: req.auth?.planLimits // { maxUsers: 10, maxProjects: 5 }
}
})
}));

Policy

routes:
# Create project - must be in same tenant
- id: projects.create
match:
method: POST
path: /api/projects
contract:
requestSchema:
type: object
properties:
name: { type: string, minLength: 1, maxLength: 100 }
tenantId: { type: string }
required: [name, tenantId]
rules:
# Tenant isolation - CRITICAL
- id: tenant.isolation
type: cel
action: block
severity: critical
config:
expr: "identity.tenant == request.body.tenantId"
message: "Cannot create project in another tenant"
# Role check - must be admin or owner
- id: role.admin.required
type: cel
action: block
config:
expr: |
identity.claims.role == "owner" || identity.claims.role == "admin"
message: "Admin or owner role required"
# Update project - must be in same tenant AND have access
- id: projects.update
match:
method: PUT
path: /api/projects/{projectId}
rules:
- id: tenant.isolation
type: cel
action: block
severity: critical
config:
expr: "identity.tenant == request.body.tenantId"
message: "Cannot modify project in another tenant"
- id: role.write.required
type: cel
action: block
config:
expr: |
identity.claims.role in ["owner", "admin", "member"]
message: "Write access required"
# Invite user - check plan limits
- id: users.invite
match:
method: POST
path: /api/users/invite
rules:
- id: tenant.isolation
type: cel
action: block
severity: critical
config:
expr: "identity.tenant == request.body.tenantId"
- id: plan.user.limit
type: cel
action: block
config:
expr: |
request.body.currentUserCount < identity.claims.planLimits.maxUsers
message: "User limit reached for your plan. Please upgrade."

Pattern 3: Banking / Fintech

High-security patterns for financial operations.

Identity Extractor

app.use(contractshield({
policy: './policy.yaml',
identityExtractor: (req) => ({
authenticated: !!req.user,
subject: req.user?.customerId,
tenant: req.user?.bankId,
scopes: req.user?.permissions || [],
claims: {
accountIds: req.user?.accountIds, // Accounts user can access
dailyTransferLimit: req.user?.limits?.dailyTransfer,
remainingDailyLimit: req.user?.limits?.remainingToday,
mfaVerified: req.session?.mfaVerified,
lastMfaAt: req.session?.lastMfaTimestamp
}
})
}));

Policy

defaults:
vulnerabilityChecks:
prototypePollution: true
pathTraversal: true
ssrfInternal:
fields: [webhookUrl, callbackUrl]
routes:
# View account - must own the account
- id: accounts.get
match:
method: GET
path: /api/accounts/{accountId}
rules:
- id: account.ownership
type: cel
action: block
severity: critical
config:
expr: |
request.path.split("/")[3] in identity.claims.accountIds
message: "Access denied to this account"
# Transfer money - strict validation
- id: transfers.create
match:
method: POST
path: /api/transfers
contract:
requestSchema:
type: object
properties:
fromAccountId: { type: string }
toAccountId: { type: string }
amount: { type: number, minimum: 0.01 }
currency: { type: string, enum: [USD, EUR, GBP, CHF] }
description: { type: string, maxLength: 140 }
required: [fromAccountId, toAccountId, amount, currency]
rules:
# Must own source account
- id: transfer.source.ownership
type: cel
action: block
severity: critical
config:
expr: "request.body.fromAccountId in identity.claims.accountIds"
message: "You don't own the source account"
# Cannot transfer to same account
- id: transfer.different.accounts
type: cel
action: block
config:
expr: "request.body.fromAccountId != request.body.toAccountId"
message: "Cannot transfer to the same account"
# Amount must be positive
- id: transfer.amount.positive
type: cel
action: block
config:
expr: "request.body.amount > 0"
message: "Transfer amount must be positive"
# Check daily limit
- id: transfer.daily.limit
type: cel
action: block
config:
expr: "request.body.amount <= identity.claims.remainingDailyLimit"
message: "Transfer exceeds your daily limit"
# MFA required for large transfers
- id: transfer.mfa.required
type: cel
action: challenge
config:
expr: |
request.body.amount <= 1000 || identity.claims.mfaVerified == true
message: "MFA verification required for transfers over $1,000"
# MFA must be recent (15 minutes)
- id: transfer.mfa.recent
type: cel
action: challenge
config:
expr: |
request.body.amount <= 1000 ||
(now - timestamp(identity.claims.lastMfaAt)).getMinutes() < 15
message: "Please re-verify MFA for this transfer"

Pattern 4: API with External Context

Sometimes you need data not in the request. Use the claims to inject it.

Enriching Context with Database Lookups

app.use(async (req, res, next) => {
if (req.user) {
// Fetch additional data needed for validation
const [subscription, usage] = await Promise.all([
db.subscriptions.findByUser(req.user.id),
db.usage.getTodayStats(req.user.id)
]);
req.enrichedContext = {
subscriptionTier: subscription.tier,
apiCallsToday: usage.apiCalls,
storageUsedMb: usage.storageMb,
teamSize: subscription.teamSize
};
}
next();
});
app.use(contractshield({
policy: './policy.yaml',
identityExtractor: (req) => ({
authenticated: !!req.user,
subject: req.user?.id,
claims: {
...req.enrichedContext // Injected data available in CEL
}
})
}));

Using Enriched Context in CEL

rules:
- id: api.rate.limit
type: cel
action: block
config:
expr: "identity.claims.apiCallsToday < 10000"
message: "API rate limit exceeded"
- id: storage.limit
type: cel
action: block
config:
expr: |
identity.claims.subscriptionTier == "enterprise" ? true :
identity.claims.subscriptionTier == "pro" ? identity.claims.storageUsedMb < 10000 :
identity.claims.storageUsedMb < 1000
message: "Storage limit exceeded for your plan"

Best Practices

Do’s

  • ✅ Extract identity from verified JWT claims
  • ✅ Use severity: critical for security rules
  • ✅ Combine multiple rules for defense in depth
  • ✅ Log all blocked requests for audit

Don’ts

  • ❌ Trust unverified request body for authorization
  • ❌ Put secrets in CEL expressions
  • ❌ Make database calls in CEL (use claims instead)
  • ❌ Skip tenant isolation checks

Next Steps