Skip to content

Chapter 22: Security and Compliance

Security breaches end startups. Compliance gaps block enterprise deals. Neither is optional -- both must be designed in from day one, not bolted on later.

Why This Matters

  • Owner: A single data breach can destroy your brand, trigger lawsuits, and kill customer trust permanently. SOC 2 and GDPR compliance unlock the enterprise market segment where deal sizes are 10-100x larger.
  • Dev : Security vulnerabilities are bugs with catastrophic consequences. Understanding auth, data isolation, and secure coding practices is non-negotiable.
  • PM : Compliance requirements generate real feature work (consent flows, data export, audit logs). They must be planned into the roadmap, not treated as afterthoughts.
  • Designer : Permission models, consent banners, data privacy UX, and access control interfaces are design problems that affect every user-facing screen.

The Concept (Simple)

Think of security and compliance like building a bank:

  • Authentication (AuthN) = Checking someone's ID at the door. "Who are you?"
  • Authorization (AuthZ) = Deciding which rooms they can enter. "What can you do?"
  • Data isolation = Ensuring one customer's safety deposit box cannot be opened by another customer
  • SOC 2 = An official audit that says "yes, this bank follows proper security procedures"
  • GDPR = Rules about what personal data you can collect, how you store it, and when you must delete it

Security is not a feature. It is a property of every feature.


How It Works (Detailed)

Authentication and Authorization

Authentication Flow (OAuth 2.0 / OpenID Connect)

┌─────────────────────────────────────────────────────────────────┐
│                  OAuth 2.0 + OIDC AUTH FLOW                     │
│                                                                 │
│  ┌──────────┐                              ┌──────────────────┐ │
│  │  User's  │  1. Click "Login"            │  Your SaaS App   │ │
│  │  Browser │─────────────────────────────▶│  (Client)        │ │
│  │          │                              └────────┬─────────┘ │
│  │          │                                       │           │
│  │          │  2. Redirect to Identity Provider     │           │
│  │          │◀──────────────────────────────────────┘           │
│  │          │                                                   │
│  │          │  3. User enters credentials                       │
│  │          │─────────────────────────────▶┌──────────────────┐ │
│  │          │                              │ Identity Provider│ │
│  │          │  4. Auth code returned        │ (Auth0, Clerk,   │ │
│  │          │◀─────────────────────────────│  Okta, Google)   │ │
│  │          │                              └────────┬─────────┘ │
│  │          │  5. Redirect back to app with code     │          │
│  │          │─────────────────────────────▶┌─────────┴────────┐ │
│  └──────────┘                              │  Your SaaS App   │ │
│                                            │                  │ │
│                 6. Exchange code for tokens │                  │ │
│               ┌──────────────────────────▶│                  │ │
│               │  ┌──────────────────┐      │                  │ │
│               │  │ Identity Provider│◀─────│                  │ │
│               │  │                  │      │                  │ │
│               │  │ Returns:         │      │                  │ │
│               │  │ - Access Token   │─────▶│  7. Create       │ │
│               │  │ - Refresh Token  │      │     session      │ │
│               │  │ - ID Token (OIDC)│      │     Store user   │ │
│               │  └──────────────────┘      └──────────────────┘ │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Authorization Models: RBAC vs ABAC

RBAC (Role-Based Access Control):
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│  User ──has──▶ Role ──has──▶ Permissions                   │
│                                                             │
│  Example:                                                   │
│  ┌─────────┐    ┌─────────┐    ┌──────────────────────┐    │
│  │  Alice   │──▶│  Admin   │──▶│ create, read, update,│    │
│  └─────────┘    └─────────┘    │ delete, manage_users │    │
│                                └──────────────────────┘    │
│  ┌─────────┐    ┌─────────┐    ┌──────────────────────┐    │
│  │   Bob    │──▶│  Editor  │──▶│ create, read, update │    │
│  └─────────┘    └─────────┘    └──────────────────────┘    │
│                                                             │
│  ┌─────────┐    ┌─────────┐    ┌──────────────────────┐    │
│  │  Carol   │──▶│  Viewer  │──▶│ read                 │    │
│  └─────────┘    └─────────┘    └──────────────────────┘    │
│                                                             │
│  Simple. Predictable. Works for 90% of SaaS products.      │
└─────────────────────────────────────────────────────────────┘

ABAC (Attribute-Based Access Control):
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│  Access = f(User attributes, Resource attributes,           │
│             Action, Environment)                            │
│                                                             │
│  Example policy:                                            │
│  "Allow if user.department == resource.department           │
│   AND user.clearance >= resource.sensitivity                │
│   AND time.current is within business_hours"                │
│                                                             │
│  More flexible. More complex. Use when RBAC is not enough.  │
└─────────────────────────────────────────────────────────────┘

When to use which:

ScenarioRBACABAC
Standard SaaS with owner/admin/memberYesNo
Healthcare with department-level accessNoYes
Multi-tenant with per-tenant rolesYesMaybe
Document sharing with fine-grained permsNoYes
Startup MVPYesNo
Enterprise with complex org structuresBothYes

Recommended RBAC roles for most SaaS:

┌──────────────────────────────────────────────────────────┐
│  STANDARD SAAS ROLE HIERARCHY                            │
│                                                          │
│  Super Admin (platform-level, your internal team)        │
│       │                                                  │
│       ▼                                                  │
│  Organization Owner (billing, member management)         │
│       │                                                  │
│       ▼                                                  │
│  Admin (settings, integrations, all content)             │
│       │                                                  │
│       ▼                                                  │
│  Member (create, read, update own content)               │
│       │                                                  │
│       ▼                                                  │
│  Viewer (read-only access)                               │
│       │                                                  │
│       ▼                                                  │
│  Guest (limited access, external collaborators)          │
└──────────────────────────────────────────────────────────┘

Data Isolation in Multi-Tenant Systems

Data isolation ensures one tenant can never see, modify, or infer another tenant's data. This is the most critical security property of any SaaS application.

DATA ISOLATION LAYERS:

┌─────────────────────────────────────────────────────────┐
│  LAYER 1: Application Layer                             │
│  ┌───────────────────────────────────────────────────┐  │
│  │  Every query includes: WHERE tenant_id = ?        │  │
│  │  Middleware validates tenant context on every req  │  │
│  │  API keys are scoped to a single tenant           │  │
│  └───────────────────────────────────────────────────┘  │
│                                                         │
│  LAYER 2: Database Layer                                │
│  ┌───────────────────────────────────────────────────┐  │
│  │  Row-Level Security (RLS) policies in PostgreSQL  │  │
│  │  OR schema-per-tenant isolation                   │  │
│  │  OR database-per-tenant (maximum isolation)       │  │
│  └───────────────────────────────────────────────────┘  │
│                                                         │
│  LAYER 3: Infrastructure Layer                          │
│  ┌───────────────────────────────────────────────────┐  │
│  │  Separate encryption keys per tenant (optional)   │  │
│  │  Network isolation for high-security tenants      │  │
│  │  Separate storage buckets per tenant (if needed)  │  │
│  └───────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘

PostgreSQL Row-Level Security example:

sql
-- Enable RLS on a table
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;

-- Create policy: users can only see their tenant's rows
CREATE POLICY tenant_isolation ON projects
  USING (tenant_id = current_setting('app.current_tenant')::uuid);

-- Set tenant context at the start of each request
SET app.current_tenant = 'tenant-uuid-here';

-- Now all queries are automatically filtered
SELECT * FROM projects;  -- Only returns current tenant's projects

Data Handling Matrix

Data TypeStorageEncryptionRetentionAccess Control
User credentialsAuth providerHashed (bcrypt)Account lifetimeAuth service
Personal info (PII)Primary DBAt rest + transitPolicy-definedRBAC + tenant
Payment dataStripe/processorNever storedN/AN/A
Session tokensRedis/memorySigned (JWT)24h-30dBearer only
Audit logsAppend-only DBAt rest1-7 yearsAdmin + compliance
File uploadsObject storageAt rest + transitUser-controlledSigned URLs
Analytics eventsAnalytics DBAt rest2-5 yearsInternal only
API keysPrimary DBHashedUntil revokedOwner only
BackupsObject storageAt rest30-90 daysOps team only

SOC 2 Basics and Preparation

SOC 2 (System and Organization Controls 2) is the most common security audit framework for SaaS companies. Enterprise customers require it.

SOC 2 Trust Service Criteria:

PrincipleWhat It CoversPriority
SecurityProtection against unauthorized accessRequired
AvailabilitySystem uptime and performance commitmentsCommon
ConfidentialityProtection of confidential informationCommon
Processing IntegrityData processing is complete, accurate, timelySometimes
PrivacyPersonal data collection, use, retention, disclosureSometimes

Start with Security + Availability. Add others as customers demand them.

SOC 2 preparation timeline:

Month 1-2: Foundation
┌──────────────────────────────────────────┐
│ - Adopt a compliance platform            │
│   (Vanta, Drata, Secureframe)            │
│ - Write security policies                │
│ - Enable SSO for all internal tools      │
│ - Set up endpoint management (MDM)       │
│ - Enable MFA for all team members        │
└──────────────────────────────────────────┘


Month 3-4: Implementation
┌──────────────────────────────────────────┐
│ - Implement access controls and logging  │
│ - Set up vulnerability scanning          │
│ - Configure backup and recovery          │
│ - Establish incident response plan       │
│ - Background checks for employees        │
└──────────────────────────────────────────┘


Month 5-6: Observation + Audit
┌──────────────────────────────────────────┐
│ - SOC 2 Type I audit (point-in-time)     │
│ - Fix any findings                       │
│ - Begin SOC 2 Type II observation period │
│   (3-12 months of evidence)              │
└──────────────────────────────────────────┘


Month 9-18: Type II Report
┌──────────────────────────────────────────┐
│ - Complete Type II audit                 │
│ - Receive report                         │
│ - Share with customers under NDA         │
└──────────────────────────────────────────┘

GDPR Compliance Essentials

GDPR applies if you have any users in the EU/EEA, regardless of where your company is based.

Compliance Framework Comparison

RequirementGDPR (EU)SOC 2HIPAA (US Healthcare)CCPA (California)
Applies toAny company with EU usersAny SaaS (voluntary)Healthcare data handlersCompanies with CA consumers
Data subject rightsAccess, delete, port, rectifyN/AAccess, accountingAccess, delete, opt-out
Consent requiredYes, explicitN/AAuthorization requiredOpt-out model
Breach notification72 hours to authorityPer incident response plan60 days to individuals"Without unreasonable delay"
PenaltiesUp to 4% global revenueLoss of enterprise dealsUp to $1.5M per violation$7,500 per violation
Audit/certificationDPA + documentationExternal auditor reportExternal auditSelf-assessment
Time to comply2-4 months6-18 months6-12 months1-3 months

GDPR requirements checklist for SaaS:

  • [ ] Privacy policy -- clear, plain-language explanation of data practices
  • [ ] Cookie consent -- opt-in banner for non-essential cookies (not just a notice)
  • [ ] Data Processing Agreement (DPA) -- contract with enterprise customers
  • [ ] Right to access -- users can export all their data
  • [ ] Right to deletion -- users can request complete data removal
  • [ ] Right to portability -- data export in machine-readable format (JSON, CSV)
  • [ ] Data minimization -- collect only what you need
  • [ ] Breach notification -- process to notify authorities within 72 hours
  • [ ] Records of processing -- document what data you collect and why
  • [ ] Sub-processor list -- publish which third parties process your users' data
  • [ ] Data retention policy -- define how long you keep each data type

Security Checklist

A practical security checklist for SaaS applications, ordered by priority:

Critical (Do immediately):

  • [ ] Use a managed auth provider -- never store passwords yourself
  • [ ] Enforce HTTPS everywhere (TLS 1.2+)
  • [ ] Enable MFA for all admin and internal accounts
  • [ ] Parameterize all database queries (prevent SQL injection)
  • [ ] Validate and sanitize all user input on the server side
  • [ ] Set secure HTTP headers (CSP, HSTS, X-Frame-Options)
  • [ ] Implement tenant isolation at both application and database layers
  • [ ] Store secrets in a vault (AWS Secrets Manager, HashiCorp Vault), never in code

High (Do within first month):

  • [ ] Set up automated dependency vulnerability scanning (Dependabot, Snyk)
  • [ ] Implement rate limiting on all API endpoints
  • [ ] Add audit logging for all sensitive operations (login, data access, settings changes)
  • [ ] Configure CORS properly -- do not use wildcard in production
  • [ ] Implement session management with secure, HttpOnly, SameSite cookies
  • [ ] Set up error monitoring that does not leak sensitive data in stack traces
  • [ ] Enable database encryption at rest
  • [ ] Implement API key rotation mechanism

Medium (Do within first quarter):

  • [ ] Conduct a basic penetration test (or use automated tools like OWASP ZAP)
  • [ ] Implement IP allowlisting for admin APIs
  • [ ] Set up intrusion detection / anomaly alerting
  • [ ] Create an incident response plan and runbook
  • [ ] Implement data backup encryption and test restore procedures
  • [ ] Add CSRF protection on all state-changing endpoints
  • [ ] Review and tighten IAM policies on cloud provider

Ongoing:

  • [ ] Quarterly dependency updates and vulnerability reviews
  • [ ] Annual penetration test by a third party
  • [ ] Regular access reviews -- remove departed employees immediately
  • [ ] Security training for all team members (at least annually)
  • [ ] Review and update security policies as the product evolves

In Practice

Real-World Example: Preparing for Your First Enterprise Customer

Situation: Your SaaS has 200 SMB customers. A Fortune 500 company wants to buy, but their security questionnaire has 300 questions and they require SOC 2.

Month 1: Sign up for Vanta (compliance automation). Costs ~$10K/year but saves 100+ hours. Auto-connects to AWS, GitHub, Google Workspace to collect evidence.

Month 2: Write security policies (Vanta provides templates). Enable SSO across all internal tools. Set up endpoint management. Implement audit logging in the product.

Month 3: Engage a SOC 2 auditor. Complete Type I audit (point-in-time snapshot). This is enough for many enterprise customers to move forward.

Month 4-6: Fill out the security questionnaire (Vanta helps auto-populate). Sign the customer's DPA. Offer them the option of dedicated infrastructure (DB-per-tenant from Chapter 19).

Month 6-12: Complete SOC 2 Type II observation period. Get the report. Use it to close 5 more enterprise deals.

Cost: ~$30-50K total (tooling + auditor). Revenue unlocked: $500K+ ARR from enterprise segment.

Common Mistakes

  1. Storing passwords in your own database -- use Auth0, Clerk, or Supabase Auth. There is no good reason to handle credentials yourself.
  2. Treating tenant isolation as an afterthought -- a single data leak between tenants can end your company. Use PostgreSQL RLS from day one.
  3. Ignoring GDPR because "we are a US company" -- if a single EU resident uses your product, GDPR applies. Fines are real.
  4. Over-engineering security early -- you do not need a WAF, SIEM, and zero-trust network on day one. Focus on the Critical checklist items first.
  5. Not having an incident response plan -- when a breach happens (not if), you need to know exactly who does what in the first 60 minutes.
  6. Putting secrets in environment variables in CI/CD configs -- use a proper secrets manager and never log environment variables.

Key Takeaways

  • Use a managed auth provider for authentication; implement RBAC for authorization. Never roll your own password storage.
  • Tenant data isolation must be enforced at both the application layer (middleware) and database layer (RLS or schema separation).
  • Start SOC 2 preparation 6 months before you need the report. Use a compliance automation platform to reduce the burden by 80%.
  • GDPR compliance requires real product features: data export, deletion, consent management. Plan them into your roadmap.
  • Security is a spectrum, not a checkbox. Start with the Critical items and work down the priority list.
  • Every "security later" decision becomes 10x more expensive to fix as your user base grows.

Action Items

Owner

  • [ ] Budget $30-50K for SOC 2 readiness if you are targeting enterprise customers
  • [ ] Sign up for a compliance automation platform (Vanta, Drata, or Secureframe) as soon as you have your first enterprise lead
  • [ ] Require MFA for all team members on all internal tools -- today
  • [ ] Purchase cyber liability insurance before your first enterprise contract
  • [ ] Publish a security page on your website (build trust, reduce inbound security questions)

Dev

  • [ ] Integrate a managed auth provider and implement RBAC in the first sprint
  • [ ] Enable PostgreSQL Row-Level Security for tenant isolation (see Chapter 19: SaaS Architecture 101)
  • [ ] Set up automated dependency scanning in CI/CD (see Chapter 21: Shipping and Deployment)
  • [ ] Implement audit logging for all create, update, and delete operations
  • [ ] Add rate limiting to all public API endpoints
  • [ ] Create a GET /api/v1/user/data-export endpoint for GDPR data portability
  • [ ] Create a DELETE /api/v1/user/account endpoint for GDPR right to deletion
  • [ ] Store all secrets in a vault, not in code or environment files

PM

  • [ ] Add GDPR compliance features to the roadmap: consent management, data export, account deletion
  • [ ] Include security review as a gate in the feature development process
  • [ ] Maintain a sub-processor list and update it when new third-party integrations are added
  • [ ] Plan for SOC 2 prep work in quarterly planning -- it takes real engineering time
  • [ ] Create a security questionnaire response template for sales enablement

Designer

  • [ ] Design a clear, non-annoying cookie consent banner that meets GDPR opt-in requirements
  • [ ] Design the account deletion flow -- it should be accessible but include appropriate confirmation steps
  • [ ] Design the data export experience -- users should be able to request and download their data easily
  • [ ] Design role and permission management UIs that are intuitive for organization admins
  • [ ] Plan the RBAC UI: role assignment, permission visibility, access request flows (see Chapter 20: Tech Stack Decisions for component library options)

The Product Builder's Playbook