Security Patterns Cookbook¶
This document provides a practical implementation cookbook for recurring security patterns used across ConnectSoft's ecosystem. It is written for developers, architects, and platform engineers who need to implement security patterns in services, platforms, and SaaS products.
These patterns are battle-tested approaches to common security challenges in multi-tenant, AI-heavy SaaS applications. Each pattern includes implementation guidance, trade-offs, and when to use which approach.
Important
Secure-by-Default: These patterns should be implemented by default in all ConnectSoft services. Factory-generated services inherit these patterns through templates, but developers extending services must ensure these patterns are maintained.
Tenant Isolation Patterns¶
Pattern 1: Per-Tenant Database¶
Description:
Each tenant has a dedicated database instance or schema.
Implementation:
- Separate database per tenant (physical isolation)
- Or separate schema per tenant within shared database (logical isolation)
- Connection string per tenant stored in Key Vault
- Tenant context resolved before database access
Pros:
- Strong Isolation - Complete data separation, no cross-tenant access possible
- Simpler Queries - No tenant filtering needed in queries
- Independent Scaling - Scale databases per tenant needs
- Easier Compliance - Per-tenant data residency and compliance
Cons:
- Infrastructure Overhead - Higher cost for many tenants
- Operational Complexity - More databases to manage, backup, monitor
- Schema Evolution - Schema changes must be applied to all tenant databases
When to Use:
- High-value enterprise tenants with strict compliance requirements
- Tenants requiring independent scaling or data residency
- Vertical suites (Insurance, Healthcare) with regulatory requirements
- Tenants with high data volumes or specialized needs
See: Threat Models for tenant isolation threat analysis.
Pattern 2: Shared Database + Tenant Key + Row-Level Security¶
Description:
All tenants share a database, with tenant ID as a key column and row-level security (RLS) policies enforcing isolation.
Implementation:
TenantIdcolumn in all tables- RLS policies enforce tenant-scoped access
- All queries automatically filtered by tenant context
- Database-level RLS prevents bypassing application-level checks
Pros:
- Cost Efficient - Single database infrastructure for many tenants
- Simpler Operations - One database to manage, backup, monitor
- Easier Schema Evolution - Schema changes applied once
- Good Performance - Efficient queries with proper indexing
Cons:
- Requires Care - Must ensure tenant context is always set
- Potential for Mistakes - Bugs can lead to cross-tenant data access
- Less Isolation - Logical separation, not physical
- Complex RLS Policies - RLS policies must be carefully designed and tested
When to Use:
- Long-tail tenants (many small tenants)
- Cost-sensitive scenarios
- Standard SaaS products with similar data structures
- When strong isolation is not required
Implementation Checklist:
- All tables include
TenantIdcolumn (NOT NULL, indexed) - RLS policies enabled on all tenant-scoped tables
- Tenant context validated and set before any database access
- Application-level tenant filtering in addition to RLS (defense in depth)
- Regular audits to verify RLS policies are working
- Integration tests for cross-tenant access prevention
See: Microservice Template for template implementation.
Pattern 3: Hybrid Approach¶
Description:
High-value tenants use per-tenant databases; long-tail tenants share a database with RLS.
Implementation:
- Tenant classification (enterprise vs. standard)
- Enterprise tenants: per-tenant database
- Standard tenants: shared database with RLS
- Routing logic selects appropriate database based on tenant
Pros:
- Balanced - Strong isolation where needed, cost efficiency for long tail
- Flexible - Can migrate tenants between models as needs change
- Scalable - Can scale enterprise tenants independently
Cons:
- Complexity - Two different patterns to maintain
- Routing Logic - Must correctly route to appropriate database
- Migration Challenges - Moving tenants between models requires data migration
When to Use:
- Mixed tenant base (enterprise + long tail)
- Cost optimization while maintaining compliance
- Gradual migration from shared to per-tenant for specific tenants
See: Threat Models for tenant isolation considerations.
Mapping to ConnectSoft Architecture¶
These patterns align with ConnectSoft's architectural principles:
Domain-Driven Design (DDD):
- Tenant isolation is a domain concept, not just infrastructure
- Bounded contexts can define tenant boundaries
- Aggregate roots enforce tenant-scoped invariants
Clean Architecture:
- Tenant isolation implemented at infrastructure layer
- Domain layer is tenant-agnostic (tenant context injected)
- Application layer enforces tenant-scoped business rules
Microservice Templates:
- Templates support all three patterns through configuration
- Factory-generated services inherit tenant isolation patterns
- Developers can choose pattern based on requirements
See: Clean Architecture & DDD for architectural principles.
Secrets Management¶
Key Vault Usage¶
Description:
All secrets stored in Azure Key Vault (or equivalent secure secret store), never in code or configuration files.
Implementation:
- Secrets loaded from Key Vault at runtime
- Managed identity or service principal for Key Vault access
- Secrets cached in memory (never logged or exposed)
- Secret rotation supported without code changes
Pattern:
// Conceptual pattern - not actual code
var secretClient = new SecretClient(vaultUri, new DefaultAzureCredential());
var connectionString = await secretClient.GetSecretAsync("db-connection-string");
Rules:
- No secrets in source code or configuration files
- Secrets loaded from Key Vault at runtime
- Managed identity used for Key Vault access (no client secrets)
- Secrets never logged or included in error messages
- Secret access logged to Audit Platform
See: Security & Compliance Policy for secrets management policy.
Per-Environment Vaults¶
Description:
Separate Key Vault per environment (dev, test, staging, prod).
Implementation:
- Environment-specific vault URIs in configuration
- Different secrets per environment
- Environment isolation prevents cross-environment secret access
- Production vault has stricter access controls
Benefits:
- Environment isolation
- Different secrets per environment
- Stricter controls for production
- Easier secret rotation per environment
Per-Tenant Connector Credentials¶
Description:
Each tenant's connector credentials (for external systems) stored separately in Key Vault.
Implementation:
- Secret naming:
tenant-{tenantId}-connector-{connectorId}-{credentialType} - Credentials scoped to tenant and specific connector
- Credential rotation per tenant without affecting others
- Audit logging of credential access and usage
Creation:
- Credentials created when tenant configures connector
- OAuth flow or API key generation per tenant
- Credentials stored in tenant-scoped Key Vault location
Rotation:
- Credentials rotated on schedule or on-demand
- Old credentials invalidated before new credentials activated
- Zero-downtime rotation (grace period for old credentials)
Revocation:
- Credentials revoked immediately on tenant request or security incident
- Revocation logged to Audit Platform
- Connector operations fail gracefully with clear error messages
See: Threat Models for connector security threats.
Zero-Trust Between Services¶
Service Identities¶
Description:
Each service authenticates using managed identity, service principal, or mTLS certificate.
Implementation:
- Azure Managed Identity - Services use managed identity for Azure resources
- Service Principals - Services authenticate using service principal credentials
- mTLS Certificates - Services use mutual TLS certificates for authentication
- No Shared Secrets - Services never share passwords or API keys
Pattern:
// Conceptual pattern - not actual code
var credential = new DefaultAzureCredential(); // Uses managed identity
var token = await credential.GetTokenAsync(new TokenRequestContext(scopes));
Benefits:
- No shared secrets to manage
- Automatic credential rotation
- Audit trail of service identity usage
- Principle of least privilege (scoped permissions)
Short-Lived Service-to-Service Tokens¶
Description:
Services obtain short-lived tokens (15-60 minutes) for service-to-service communication.
Implementation:
- Services request tokens from Identity Platform using client credentials flow
- Tokens scoped to specific audience and resources
- Tokens cached and refreshed before expiration
- Token validation on every service-to-service call
Token Scopes:
- Audience - Specific service or API
- Resources - Specific resources or operations
- Tenant Context - Tenant-scoped tokens for multi-tenant services
Benefits:
- Limited exposure window if token compromised
- Automatic expiration and refresh
- Scope-based access control
- Audit trail of token usage
Private Networks and API Gateway¶
Description:
Services communicate over private networks, with API Gateway as the public entry point.
Implementation:
- Private Networks - Services in private VNet or network segment
- No Direct Public Access - Services not directly accessible from internet
- API Gateway - Public traffic enters through API Gateway
- Service Mesh - Optional service mesh for service-to-service communication
Network Architecture:
Benefits:
- Reduced attack surface (services not publicly accessible)
- Network-level isolation
- Centralized authentication and authorization at gateway
- DDoS protection and rate limiting at gateway
See: Threat Models for zero-trust threat analysis.
Input Validation & Output Encoding¶
API Input Validation¶
Description:
All API inputs validated at the boundary before processing.
Implementation:
- FluentValidation - Use FluentValidation for request validation
- Data Annotations - Use data annotations for model validation
- Model Binding Validation - ASP.NET Core model binding validation
- Custom Validators - Custom validators for business rules
Validation Rules:
- All inputs validated (no trust of client data)
- Type validation (strings, numbers, dates, etc.)
- Length and format validation
- Business rule validation
- Tenant context validation (tenant ID matches authenticated user)
See: Microservice Template for validation implementation.
Form & Document Sanitization¶
Description:
Form inputs and document content sanitized to prevent injection attacks.
Implementation:
- HTML Sanitization - Strip or escape HTML tags in form inputs
- Markdown Sanitization - Sanitize markdown content
- File Type Validation - Validate file types and scan for malicious content
- Content Scanning - Scan uploaded files for malware
Sanitization Rules:
- HTML tags stripped or escaped
- Script tags and event handlers removed
- File types restricted to allowed list
- File size limits enforced
- Content scanning for malicious patterns
Safe Logging¶
Description:
Logs never contain secrets, PII, or sensitive data.
Implementation:
- Automatic Redaction - PII and secrets automatically redacted from logs
- Structured Logging - Structured logging with redaction hooks
- Custom Redactors - Custom redactors for domain-specific sensitive data
- Log Classification - Logs classified by sensitivity level
Redaction Rules:
- Secrets never logged (tokens, passwords, API keys)
- PII redacted (email, phone, SSN, etc.)
- PHI redacted (medical records, health data)
- Financial data redacted (credit cards, account numbers)
- Document content not logged (only metadata)
See: Security & Compliance Policy for logging requirements.
AI Prompt Preparation¶
Description:
AI prompts prepared safely to prevent injection attacks.
Implementation:
- Input Sanitization - User input sanitized before inclusion in prompts
- System Prompt Protection - System prompts cannot be overridden by user input
- Instruction Hierarchy - System instructions take precedence over user input
- Content Filtering - Prompts filtered for malicious patterns
Prompt Security Rules:
- User input sanitized and validated
- System prompts protected from user override
- Prompt injection detection and prevention
- Sensitive data redacted from prompts
- Tenant context strictly enforced in prompts
See: Threat Models for AI-specific threats.
Secure-by-Default Templates¶
Microservice Template¶
Default Security Building Blocks:
- Authentication Middleware - OAuth2/OIDC token validation
- Authorization Middleware - Role and scope-based authorization
- Rate Limiting - Global and endpoint-specific rate limits
- CORS Configuration - Origin whitelisting and method restrictions
- mTLS Support - Service-to-service mutual TLS
- Audit Logging Hooks - Audit event emission for security events
- Input Validation - FluentValidation and data annotations
- Output Encoding - Safe response encoding
- Secrets Management - Key Vault integration
- Health Checks - Security-aware health checks
Developer Checklist:
- All endpoints require authentication (unless explicitly public)
- Authorization checks implemented for all protected operations
- Rate limiting configured appropriately
- CORS configured for allowed origins only
- Input validation implemented for all inputs
- Audit events emitted for security-sensitive operations
- Secrets loaded from Key Vault (never hardcoded)
- Tenant isolation enforced (tenant context validated)
See: Microservice Template for template details.
Identity Backend Template¶
Default Security Building Blocks:
- OAuth2/OIDC Server - Standards-based authentication
- Token Management - Access and refresh token handling
- MFA Support - Multi-factor authentication
- Password Policies - Strong password requirements
- Account Lockout - Brute force protection
- Audit Logging - All authentication events logged
- Rate Limiting - Authentication endpoint rate limits
- External IdP Integration - Secure federation
Developer Checklist:
- Token lifetimes configured appropriately
- Refresh token rotation implemented
- MFA enforced for admin accounts
- Password policies enforced
- Account lockout configured
- All auth events logged to Audit Platform
- Rate limiting prevents brute force attacks
See: Identity Platform for platform details.
Auth Server Template¶
Default Security Building Blocks:
- Token Validation - JWT signature validation
- Token Introspection - Token validation via introspection endpoint
- Scope Validation - Scope-based authorization
- Audience Validation - Audience claim validation
- Caching - Token validation result caching
- Rate Limiting - Validation endpoint rate limits
Developer Checklist:
- Token signatures validated on every request
- Scopes checked for all protected operations
- Audience validated to prevent token reuse
- Token validation cached appropriately
- Rate limiting prevents abuse
Agent Service Template¶
Default Security Building Blocks:
- Agent Authentication - Agent identity and authentication
- Tool Authorization - Tool access control per agent
- Tenant Isolation - Strict tenant context enforcement
- Prompt Security - Input sanitization and injection prevention
- Content Filtering - Output content filtering
- Audit Logging - Agent execution and tool usage logged
- Human-in-the-Loop - Critical operations require approval
Developer Checklist:
- Agent identity authenticated
- Tool access scoped to agent and tenant
- Tenant context validated before any data access
- Prompts sanitized and validated
- Content filters applied to responses
- All agent actions logged to Audit Platform
- Critical operations require human approval
See: Factory Overview for Factory architecture.
Related Documents¶
Security Documentation¶
- Security Overview - Security vision and principles
- Threat Models - Threat analysis and mitigations
- Compliance Blueprints - Compliance-by-design architecture
Architecture & Templates¶
- Clean Architecture & DDD - Architectural principles
- Microservice Template - Microservice template
- Event-Driven Mindset - Event-driven patterns
Platform Documentation¶
- Identity Platform - Identity & Access Platform
- Audit Platform - Audit Platform
Governance¶
- Security & Compliance Policy - Security policy