| name | securability-code-patterns |
| description | Practical FIASSE/SSEM code patterns and templates for trust boundaries, canonical input handling, Derived Integrity Principle, structured logging, and SSEM-compliant implementations. Use when: implementing canonical input handling at trust boundaries, enforcing Derived Integrity (server-side business value derivation), writing audit-logging code, creating error handling patterns, refactoring for SSEM attributes (Analyzability, Modifiability, Testability, Confidentiality, Accountability, Authenticity, Availability, Integrity, Resilience). |
| user-invocable | true |
| license | CC-BY-4.0 |
Securability Code Patterns
Practical, battle-tested code patterns that implement FIASSE/SSEM principles at the implementation level.
Core Patterns
1. Canonical Input Handling at Trust Boundaries
When to use: Every HTTP handler, message consumer, file parser, or service-to-service call.
Pattern: Canonicalize → Sanitize → Validate
TypeScript/Node.js Example
interface UserCreateRequest {
username: string;
email: string;
age: number;
}
interface ValidatedUserInput {
---
## References (Consolidated)
- ../shared-references/ssem-model.md
- ../shared-references/trust-boundaries.md
- ../shared-references/anti-patterns.md
- ../shared-references/canonical-input-handling.md
age: number;
}
function validateUserInput(request: any): ValidatedUserInput | null {
const rawUsername = String(request.username ?? "").trim().toLowerCase();
const rawEmail = String(request.email ?? "").trim().toLowerCase();
const rawAge = parseInt(request.age, 10);
if (rawUsername.length === 0 || rawUsername.length > 128) {
logSecurityEvent({
type: "INPUT_VALIDATION_FAILURE",
field: "username",
reason: "invalid_length",
suppressed_value: `length=${rawUsername.length}`,
});
return null;
}
const usernamePattern = /^[a-z0-9_-]{3,128}$/;
if (!usernamePattern.test(rawUsername)) {
logSecurityEvent({
type: "INPUT_VALIDATION_FAILURE",
field: "username",
reason: "invalid_format",
});
return null;
}
if (!isValidEmail(rawEmail)) {
logSecurityEvent({
type: "INPUT_VALIDATION_FAILURE",
field: "email",
reason: "invalid_email",
});
return null;
}
if (isNaN(rawAge) || rawAge < 0 || rawAge > 150) {
logSecurityEvent({
type: "INPUT_VALIDATION_FAILURE",
field: "age",
reason: "out_of_range",
suppressed_value: `attempted=${request.age}`,
});
return null;
}
return {
username: rawUsername,
email: rawEmail,
age: rawAge,
};
}
async function handleCreateUser(req: Request): Promise<Response> {
const validated = validateUserInput(req.body);
if (!validated) {
return new Response("Invalid input", { status: 400 });
}
const user = await db.users.create(validated);
return new Response(JSON.stringify(user));
}
Python Example
from dataclasses import dataclass
from typing import Optional
import re
import logging
security_logger = logging.getLogger("security")
@dataclass
class ValidatedUserInput:
"""Marker type: input has passed canonical handling."""
username: str
email: str
age: int
def validate_user_input(request_data: dict) -> Optional[ValidatedUserInput]:
"""Applies canonical input handling: canonicalize → sanitize → validate."""
raw_username = str(request_data.get("username", "")).strip().lower()
raw_email = str(request_data.get("email", "")).strip().lower()
raw_age_str = request_data.get("age", "")
if not raw_username or len(raw_username) > 128:
security_logger.warning(
"input_validation_failure",
extra={
"field": "username",
"reason": "invalid_length",
"attempted_length": len(raw_username),
}
)
return None
if not re.match(r"^[a-z0-9_-]{3,128}$", raw_username):
security_logger.warning(
"input_validation_failure",
extra={"field": "username", "reason": "invalid_format"}
)
return None
if not is_valid_email(raw_email):
security_logger.warning(
"input_validation_failure",
extra={"field": "email", "reason": "invalid_email"}
)
return None
try:
raw_age = int(raw_age_str)
if raw_age < 0 or raw_age > 150:
raise ValueError("out of range")
except (ValueError, TypeError):
security_logger.warning(
"input_validation_failure",
extra={
"field": "age",
"reason": "invalid_type_or_range",
"attempted_value": str(raw_age_str)[:20],
}
)
return None
return ValidatedUserInput(
username=raw_username,
email=raw_email,
age=raw_age
)
2. The Derived Integrity Principle
Core Rule: Never accept a business-critical value from the client. Derive it server-side.
Pattern: Client expresses intent, server derives the facts.
E-Commerce Checkout Example
async function checkoutBad(req: Request) {
const { itemIds, quantities, totalPrice } = req.body;
await recordPurchase({ itemIds, quantities, totalPrice });
}
async function checkoutGood(req: Request) {
const validated = validateCheckoutIntent({
itemIds: req.body.itemIds,
quantities: req.body.quantities,
});
if (!validated) {
return new Response("Invalid items or quantities", { status: 400 });
}
const items = await db.products.findByIds(validated.itemIds);
if (!items || items.length !== validated.itemIds.length) {
logSecurityEvent({
type: "INTEGRITY_VIOLATION",
reason: "item_not_found",
attempted_ids: validated.itemIds,
});
return new Response("Item not found", { status: 404 });
}
const total = items.reduce((sum, item, idx) => {
return sum + item.price * validated.quantities[idx];
}, 0);
if ("totalPrice" in req.body) {
logSecurityEvent({
type: "INTEGRITY_VIOLATION",
reason: "client_supplied_price",
suppressed_client_price: req.body.totalPrice,
server_derived_price: total,
});
}
const purchase = await db.purchases.create({
itemIds: validated.itemIds,
quantities: validated.quantities,
totalPrice: total,
userId: req.user.id,
timestamp: new Date(),
});
return new Response(JSON.stringify(purchase));
}
Permission/Role Example
async function updateUserRoleBad(req: Request) {
const { userId, newRole } = req.body;
await db.users.update(userId, { role: newRole });
}
async function updateUserRoleGood(req: Request) {
const { userId, newRole } = req.body;
const requester = req.user;
const grantableRoles = await getGrantableRoles(requester);
if (!grantableRoles.includes(newRole)) {
logSecurityEvent({
type: "AUTHORIZATION_FAILURE",
requester: requester.id,
attempted_role: newRole,
grantable_roles: grantableRoles,
});
return new Response("Forbidden", { status: 403 });
}
const effectiveRole = deriveEffectiveRole(newRole, requester);
await db.users.update(userId, { role: effectiveRole });
await logAudit({
action: "role_changed",
adminId: requester.id,
targetUserId: userId,
newRole: effectiveRole,
});
return new Response({ success: true });
}
3. Structured Audit Logging (Accountability)
Pattern: Log security-relevant events as structured data with rich context.
TypeScript Example
interface SecurityEvent {
timestamp: string;
type: string;
severity: "INFO" | "WARNING" | "ERROR" | "CRITICAL";
actor?: string;
resource?: string;
action: string;
outcome: "success" | "failure";
reason?: string;
context?: Record<string, any>;
suppressed_values?: Record<string, string>;
}
const auditLogger = new Logger("audit");
function logSecurityEvent(event: SecurityEvent) {
const logged = {
...event,
timestamp: event.timestamp || new Date().toISOString(),
};
auditLogger.info(logged.type, {
event: logged,
});
}
function exampleAuthFailure() {
logSecurityEvent({
type: "AUTH_FAILURE",
severity: "WARNING",
actor: "user_123",
action: "login_attempt",
outcome: "failure",
reason: "invalid_password",
context: {
clientIp: "192.0.2.1",
userAgent: "Mozilla/5.0...",
},
});
}
function examplePrivilegeChange() {
logSecurityEvent({
type: "PRIVILEGE_CHANGE",
severity: "WARNING",
actor: "admin_456",
resource: "user_789",
action: "role_upgraded",
outcome: "success",
context: {
oldRole: "viewer",
newRole: "editor",
reason: "team_lead_request",
},
});
}
function exampleSensitiveDataAccess() {
logSecurityEvent({
type: "DATA_ACCESS",
severity: "INFO",
actor: "service_api_key_001",
resource: "customer_pii_database",
action: "query_executed",
outcome: "success",
context: {
recordsReturned: 42,
query: "SELECT * FROM users WHERE region='us-west'",
},
});
}
Audit Trail Example (Immutable)
interface AuditTrailEntry {
id: string;
timestamp: string;
actor: string;
action: string;
targetResource: string;
oldValue?: any;
newValue?: any;
reason?: string;
}
async function recordAuditTrail(entry: Omit<AuditTrailEntry, "id" | "timestamp">) {
const trailEntry: AuditTrailEntry = {
id: generateUUID(),
timestamp: new Date().toISOString(),
...entry,
};
await db.auditTrail.insert(trailEntry);
await externalAuditService.log(trailEntry);
}
await recordAuditTrail({
actor: "admin_user_456",
action: "permission_grant",
targetResource: "user_789",
oldValue: { permissions: ["read"] },
newValue: { permissions: ["read", "write", "admin"] },
reason: "Approved by security review",
});
4. Error Handling (Resilience + Confidentiality)
Pattern: Handle errors gracefully; never expose internal details to clients.
TypeScript Example
async function getUserBad(userId: string) {
try {
return await db.users.findById(userId);
} catch (err) {
return new Response(err.message, { status: 500 });
}
}
class AppError extends Error {
constructor(
public userMessage: string,
public logMessage: string,
public statusCode: number = 500,
public internalCode: string = "INTERNAL_ERROR"
) {
super(userMessage);
}
}
async function getUserGood(userId: string) {
try {
const user = await db.users.findById(userId);
if (!user) {
throw new AppError(
"User not found",
`User ${userId} not found in database`,
404,
"USER_NOT_FOUND"
);
}
return user;
} catch (err) {
if (err instanceof AppError) {
logSecurityEvent({
type: "APP_ERROR",
severity: "WARNING",
action: "get_user",
outcome: "failure",
reason: err.internalCode,
context: { userId },
});
return new Response(err.userMessage, { status: err.statusCode });
}
logSecurityEvent({
type: "UNEXPECTED_ERROR",
severity: "ERROR",
action: "get_user",
outcome: "failure",
reason: "internal_server_error",
context: { userId, error: err.message },
});
return new Response("Internal server error", { status: 500 });
}
}
5. Strong Typing for Integrity (Testability + Analyzability)
Pattern: Use type markers to signal validation state.
declare const Validated: unique symbol;
interface ValidatedEmail {
[Validated]: "email";
value: string;
}
interface ValidatedPhoneNumber {
[Validated]: "phone";
value: string;
}
function validateEmail(raw: string): ValidatedEmail | null {
if (!raw.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
return null;
}
return { [Validated]: "email", value: raw };
}
function validatePhone(raw: string): ValidatedPhoneNumber | null {
if (!raw.match(/^\+?[\d\s\-()]{10,}$/)) {
return null;
}
return { [Validated]: "phone", value: raw };
}
async function sendConfirmationEmail(email: ValidatedEmail) {
await emailService.send({
to: email.value,
});
}
sendConfirmationEmail("user@example.com");
sendConfirmationEmail(validateEmail("user@example.com")!);
Resource Files
Quick Checklist
Before submitting code review:
- Analyzability: Clear function names, <200 lines per function, low cyclomatic complexity
- Modifiability: Minimal coupling, no duplication, interfaces are stable
- Testability: Functions have clear inputs/outputs, minimal side effects, can be mocked
- Confidentiality: No secrets in logs, sensitive data encrypted, principle of least privilege
- Accountability: Security events logged with who/what/when, immutable audit trail
- Authenticity: Identity verified server-side, never trust client claims
- Availability: Proper rate limiting, circuit breakers, graceful degradation
- Integrity: Derived Integrity Principle applied (server-side business value derivation)
- Resilience: Input validation at trust boundaries, comprehensive error handling, immutable data for concurrency
References
- FIASSE Framework
- SSEM Attributes: Maintainability (Analyzability, Modifiability, Testability) | Trustworthiness (Confidentiality, Accountability, Authenticity) | Reliability (Availability, Integrity, Resilience)