Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions saas-builder/POWER.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name: "saas-builder"
displayName: "SaaS Builder"
description: "Build production-ready multi-tenant SaaS applications with serverless architecture, integrated billing, and enterprise-grade security"
keywords: ["saas", "multi-tenant", "serverless", "aws", "lambda", "dynamodb", "stripe", "billing", "react", "typescript"]
keywords: ["saas", "multi-tenant", "serverless", "aws", "lambda", "dynamodb", "route53", "cloudfront", "waf", "acm", "stripe", "billing", "react", "typescript"]
author: "Allen Helton"
---

Expand All @@ -18,6 +18,8 @@ The SaaS Builder power provides tools and patterns for building scalable, cost-e

- **Multi-tenant architecture** with tenant isolation at the data layer
- **Serverless-first** infrastructure (Lambda, API Gateway, DynamoDB)
- **CDN, Certificate and domain management** with CloudFront SaaS Manager, ACM, and Route53
- **Caching and DDoS protection** with Amazon CloudFront and AWS WAF
- **Integrated billing** with Stripe and usage metering
- **Authentication & authorization** with JWT and RBAC
- **Cost-per-tenant economics** with zero idle costs
Expand Down Expand Up @@ -45,12 +47,17 @@ The SaaS Builder power provides tools and patterns for building scalable, cost-e
- DynamoDB on-demand pricing
- Zero cost when idle
- Linear scaling economics
- CloudFront pay as you go, 1TB free every month
- ACM Generated Certificates are free with CloudFront

### Security
- Managed authentication (Cognito/Auth0)
- JWT tokens with tenant claims
- Role-based access control (RBAC)
- Encryption at rest and in transit
- AWS WAF for request inspection, DDoS mitigation, application layer protection, bot management and fraud control
- Amazon CloudFront for GEO controls, caching and availability
- Rate limiting AWS WAF, API Gateway, Application layers

## Repository Structure

Expand All @@ -64,10 +71,28 @@ The SaaS Builder power provides tools and patterns for building scalable, cost-e
│ │ └── billing/
│ ├── lib/ # Business logic
│ └── infrastructure/ # IaC (CDK/SAM)
│ ├── cloudfront/ # Multi-tenant distributions
│ ├── certificates/ # ACM certificate management
│ ├── dns/ # Route53 hosted zones
│ ├── waf/ # Web ACL and security rules
│ └── api.yaml # API Gateway definition
├── schema/ # API contracts (OpenAPI)
└── .kiro/ # Kiro configuration
```

## Custom Domain Management

- **CloudFront SaaS Manager**: Multi-tenant distributions with per-tenant customization
- **ACM Certificates**: HTTPS and DNS validation for auto-renewal (us-east-1 region required)
- **DNS Options**: Platform-managed (Route53), tenant-managed, or hybrid approach
- **Tiered Strategy**: Basic (subdomains), Premium (vanity domains), Enterprise

## Security & Protection

- **AWS WAF**: AntiDDoS rule group, managed rules, rate limiting, IP reputation, geo-blocking, ATP for logins, bot control
- **Rate Limiting**: Multi-layer (WAF, API Gateway per tier, application quotas)
- **DDoS Protection**: AWS WAF AntiDDoS AMR, Shield Standard, CloudFront, Route53 DNS protection

## Billing & Payments

### Money Handling
Expand Down Expand Up @@ -140,9 +165,12 @@ Edit `saas-builder/mcp.json` to:
- Always validate tenant context
- Check user roles before operations
- Prefix all keys with tenant ID
- Use ACM HTTP validation (never email), fall back to DNS validation for wildcard domain
- Protect all public endpoints (AWS WAF with Amazon CloudFront)
- Implement rate limiting at multiple layers (service availability, tenant rate control)
- Use OpenAPI v3 specification as the source of truth for APIs, informing WAF rules, CloudFront configurations
- Use idempotency keys for payments
- Verify webhook signatures
- Implement rate limiting per tenant
- Monitor cost per tenant
- Test cross-tenant isolation
- Design for 10x growth
Expand Down
42 changes: 42 additions & 0 deletions saas-builder/steering/architecture-principles.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,48 @@ inclusion: always
- Load test with realistic multi-tenant traffic patterns
- Frontend: Manual testing preferred, focus on tenant-specific UI variations

## Ingress Patterns and Edge Security

**Multi-Tenant Distribution Strategy**:
- Share configuration across tenants for operational efficiency
- Allow tenant-specific customization (domains, certificates, security overrides)
- Use connection groups for DNS routing

**Tiered Service Model for CDN**:
- Basic: Single multi-tenant distribution, platform subdomains, wildcard certificate, pooled origin
- Premium: Same multi-tenant distribution, custom vanity domains, tenant certificates, dedicated origins, Origin Shield, enhanced WAF WebACL protections
- Enterprise: custom vanity domains, tenant certificates, dedicated origins, Origin Shield, custom WAF WebACL

**Certificate Strategy**:
- Use HTTP ACM validation for automatic renewal (Route53 and ACM)
- Wildcard certificates for platform subdomains (cost-effective)
- Tenant-specific certificates for custom domains (optional)

**DNS Ownership Models**:
- Platform-managed: Full control, automated validation, operational overhead
- Tenant-managed: Tenant controls DNS, zero platform cost, manual coordination
- Hybrid: Platform subdomains + optional custom domains

## Security & DDoS Protection

**Defense in Depth**:
- Use AWS WAF with CloudFront to provide for application layer protections
- AWS Shield Standard for network/transport layer DDoS
- Rate limiting at multiple layers (WAF, API Gateway, application)
- Geo-blocking and IP reputation filtering
- API Gateway (request, input validation, access control, usage plans)

**Positive Security Model WAF**:
- Default deny for APIs (explicit allow for known good patterns)
- Default allow for websites (explicit block for known bad patterns)
- Use managed rule groups for OWASP Top 10 protection
- Layer rules: non-terminating (count/challenge) before terminating (block/allow)

**Tenant-Specific Security**:
- Shared Web ACL for Basic tier (cost-effective)
- Enhanced rules for Premium tier (higher rate limits)
- Dedicated Web ACL for Enterprise tier (custom policies)

## Dependency Management
- Minimize third-party libraries - prefer AWS SDKs and built-in language features
- Pin versions to avoid breakages
Expand Down
111 changes: 111 additions & 0 deletions saas-builder/steering/implementation-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ inclusion: always
### Request/Response Models
- Define schemas in `schema/` (language-agnostic format preferred)
- Validate at API boundary with appropriate validation library
- API request validation with format and type checking
- Success: Return JSON object or array
- Error: `{ "error": { "code": "...", "message": "..." } }`
- Never expose internal database fields directly
Expand Down Expand Up @@ -105,6 +106,116 @@ handler(event) {
return 200 OK
}
```
### CloudFront and Custom Domains

**Multi-Tenant Distribution Setup**:
- Create one distribution per tier (for example; Basic, Premium, Enterprise)
- Use parameters for tenant-specific values:
- S3 origin: `${tenantId}.s3.${region}.amazonaws.com`, `/tenants/${tenantId}`
- API Gateway origin: `${apiId}.execute-api.${region}.amazonaws.com`, `/${stage}/tenants/${tenantId}`
- Attach shared Web ACL ARN to distribution
- Create distribution tenant per tenant with domain names and certificate ARN
- Pass parameter values (tenantId, apiId, stage, region) to distribution tenant

**ACM Certificate Implementation**:
- Wildcard for Basic tier: `*.yourplatform.com` with DNS validation (auto-validates via Route53)
- Tenant-specific for Premium/Enterprise: DNS validation (tenant adds CNAME records)
- Poll certificate status: `PENDING_VALIDATION` → `ISSUED`
- Associate certificate ARN with CloudFront distribution tenant once issued
- All CloudFront certificates must be in us-east-1 region
- Never use email validation (manual renewal, not scalable)

**DNS Configuration**:

Platform subdomain (instant onboarding):
- Create CNAME in platform hosted zone: `${tenantId}.yourplatform.com` → CloudFront endpoint
- TTL: Low value for flexibility during onboarding (e.g., 5 minutes)
- Uses wildcard certificate

Platform-managed tenant domain (automated validation):
- Create Route53 hosted zone for tenant domain
- Request ACM certificate with HTTP(1st choice) or DNS(2nd choice) validation (auto-creates validation CNAME in zone)
- Create CNAME for traffic: `${tenantDomain}` → CloudFront endpoint
- Provide Route53 name servers to tenant for domain delegation

Tenant-managed DNS (manual coordination):
- Request ACM certificate for tenant domain
- Provide DNS validation CNAME records to tenant
- Tenant adds CNAME to their DNS provider
- Poll ACM status until validated
- Provide CloudFront endpoint CNAME to tenant
- Tenant adds traffic CNAME to their DNS

**Tenant Onboarding Workflows**:
- Platform subdomain: Create CNAME → instant access
- Tenant vanity (manual): Request cert → provide validation records → tenant adds → poll status → associate cert → provide endpoint
- Platform-managed: Create zone → request cert → auto-validate → add CNAME → provide name servers → tenant delegates

**Critical Implementation Rules**:
- All CloudFront certificates must be in us-east-1 region
- Use DNS validation (never email - requires manual renewal)
- Keep validation CNAMEs in DNS permanently (enables auto-renewal)
- Use Alias records for apex domains (no query charges)
- Set TTL low during onboarding for flexibility, increase after stable
- Monitor certificate validation status and alert tenant if stuck
- Test DNS propagation (can take minutes to days depending on DNS provider)

### AWS WAF and Security

**Web ACL Configuration**:
Key settings for CloudFront WAF integration:

- **Scope**: `CLOUDFRONT` (required for CloudFront distributions)
- **Associate with CloudFront**: Attach Web ACL ARN to multi-tenant distribution

**Positive Security Model** (if using default deny):
If changing default action to `Block`, add terminating allow rule lower in the rule order:
- Allow `/api/v1/*` with valid JWT token label, count/label match, with a rate limit
- Allow static assets: `\.(css|js|png|jpg|gif|ico|woff2?)$`, with a rate limit
- Allow health check: `/health`, with a rate limit

**API use-case: Positive Security Model Pattern**:
- Reference WAF Rule Priority Order table above for complete configuration
- Default action: Allow (with comprehensive rule-based blocking)
- Alternative: Default Block with explicit allow rules for known good patterns
- Use labels from managed rules to identify and allow authenticated requests

**DDoS Protection**:
- AWS Shield Standard: Automatic with CloudFront (no config needed)
- CloudFront absorbs layer 3/4 attacks at edge locations
- Route53 provides DNS query flood protection
- WAF rate limiting prevents application layer attacks

**AWS WAF Rule Priority Order**:
Configure based on your security requirements. Default action depends on use case:
- **Websites**: Default Allow with rule-based blocking
- **APIs**: Default Block (positive security model) with explicit allow rules

**Rule Priority Guidelines** (adjust priorities in increments of 10 for flexibility):

| Priority Range | Rule Type | Action | Purpose |
|----------------|-----------|--------|---------|
| 0-10 | AntiDDoS (AMR) | Count/Challenge | DDoS protection (exclude API endpoints from challenge using regex) |
| 10-20 | IP Allowlist | Allow | Trusted IPs bypass all rules (if applicable) |
| 30-40 | IP Blocklist | Block | Known malicious IPs, headers, user-agents |
| 50-60 | Geo-Blocking | Block | High-risk countries based on your requirements |
| 60-90 | Rate Limiting | Count | Global, per-method (GET, POST/PUT/DELETE) |
| 90-100 | Body Size Restriction | Count | Tune based on your API requirements (default: 16KB, max: 64KB with additional cost) |
| 100-110 | IP Reputation (AMR) | None/Challenge | Block/challenge known DDoS IPs, count reconnaissance |
| 110-120 | DDoS IP Rate Limit | Count | Rate limit for labeled DDoS IPs |
| 120-130 | Anonymous IP (AMR) | None | Block VPNs, proxies, Tor (if required) |
| 130-140 | Core Rule Set (AMR) | None | OWASP Top 10 protection |
| 140-150 | Known Bad Inputs (AMR) | None | Malicious patterns, directory traversal |
| 150-160 | Language-Specific (AMR) | None | PHP, Linux, etc. (based on your stack) |
| 160-170 | SQL Injection (AMR) | None | SQLi attack prevention |
| 170-180 | Admin Protection (AMR) | None | Protect admin paths |
| 180-190 | Bot Control (AMR) | Count | Common bot detection (optional: upgrade to Targeted for enterprise) |

**Important Configurations**:
- **Body Inspection**: Default 16KB, up to 64KB available (additional cost)
- **Token Domains**: Configure for your application domains for use with WAF tokens
- **CSP Headers**: Set appropriate Content Security Policy headers (if AWS WAF Bot Control required)
- **Regex Handling**: Exclude static assets and API endpoints from challenges where appropriate (use AWS WAF regex)

### Environment Configuration
- Use environment variables for runtime config
Expand Down
4 changes: 4 additions & 0 deletions saas-builder/steering/repository-structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ backend/
│ └── usage/ # Usage metering utilities
├── db/ # Data access layer (tenant-aware queries)
└── infrastructure/ # IaC (CDK, SAM, Terraform)
├── cloudfront/ # Multi-tenant distributions, distribution tenants
├── certificates/ # ACM certificate management and validation
├── dns/ # Route53 hosted zones and records
├── waf/ # Web ACL, managed rules, rate limiting
├── api.yaml # API Gateway definition
├── database.yaml # DynamoDB tables
└── auth.yaml # Cognito/Auth0 config
Expand Down