@martinffx/atelier 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,236 @@
1
+ # Security Design Patterns
2
+
3
+ Catalog of architectural patterns for building secure systems.
4
+
5
+ ## Input Validation Patterns
6
+
7
+ ### Whitelist Validation
8
+ Define what's allowed, reject everything else. More secure than blacklist (define what's blocked, allow everything else).
9
+
10
+ - Specify allowed types, formats, lengths, ranges
11
+ - Reject input that doesn't match exactly
12
+ - Don't try to "fix" invalid input — reject it
13
+
14
+ ### Schema Validation
15
+ Define expected structure and enforce it at the boundary.
16
+
17
+ - Types, required fields, field constraints
18
+ - Nested object validation
19
+ - Array item validation
20
+
21
+ ### Sanitization vs. Validation
22
+
23
+ | Approach | When to Use | Risk |
24
+ |----------|-------------|------|
25
+ | **Validation** | Reject invalid input entirely | Low — no invalid data enters system |
26
+ | **Sanitization** | Clean input for safe use | Medium — subtle bugs in sanitization logic |
27
+ | **Encoding** | Escape for specific context | Context-dependent — wrong encoding for wrong context |
28
+
29
+ **Rule**: Validate first. Only sanitize if you understand exactly what the destination context requires.
30
+
31
+ ## Authentication Patterns
32
+
33
+ ### Session-Based Authentication
34
+ - Server-side session storage
35
+ - Session ID in httpOnly, secure, sameSite cookie
36
+ - Server validates session on every request
37
+
38
+ ### Token-Based Authentication
39
+ - Signed token (JWT, Paseto) containing claims
40
+ - Token sent in Authorization header
41
+ - Server validates signature and expiry
42
+
43
+ ### Multi-Factor Authentication
44
+ - Something you know (password)
45
+ - Something you have (device, token)
46
+ - Something you are (biometric)
47
+
48
+ **Key Decision**: Session vs. Token depends on state requirements, scale, and revocation needs.
49
+
50
+ ## Authorization Patterns
51
+
52
+ ### Role-Based Access Control (RBAC)
53
+ - Users assigned to roles
54
+ - Roles granted permissions
55
+ - Simple to understand and audit
56
+
57
+ ### Attribute-Based Access Control (ABAC)
58
+ - Policies based on user attributes, resource attributes, environment
59
+ - More flexible but more complex
60
+ - Better for fine-grained, dynamic access control
61
+
62
+ ### Resource-Level Authorization
63
+ Every operation checks: "Does this user have permission to perform this action on this specific resource?"
64
+
65
+ - Don't check once at login and assume it's valid for all subsequent actions
66
+ - Re-verify on every request that touches a resource
67
+ - Consider resource ownership, sharing, delegation
68
+
69
+ ## Output Protection Patterns
70
+
71
+ ### Response Filtering
72
+ Remove sensitive fields from API responses based on caller's authorization level.
73
+
74
+ - Never return internal IDs, passwords, tokens, or secrets
75
+ - Filter differently for different user types
76
+ - Consider field-level access control
77
+
78
+ ### Error Message Safety
79
+ - Return generic errors to users
80
+ - Log detailed errors internally
81
+ - Never expose: stack traces, database schemas, file paths, internal IPs, system versions
82
+
83
+ ## Audit and Logging Patterns
84
+
85
+ ### Security Event Logging
86
+ Log events that matter for security investigations:
87
+
88
+ - Authentication attempts (success and failure)
89
+ - Authorization failures
90
+ - Sensitive data access
91
+ - Configuration changes
92
+ - Privilege escalations
93
+
94
+ ### Audit Trail Requirements
95
+ - **Who**: Which user or service performed the action
96
+ - **What**: What action was performed
97
+ - **When**: Timestamp (UTC)
98
+ - **Where**: Source IP, endpoint, service
99
+ - **Result**: Success or failure
100
+ - **Context**: Relevant IDs, parameters (sanitized)
101
+
102
+ ### Log Protection
103
+ - Logs should be tamper-evident (append-only, signed)
104
+ - Separate log access from application access
105
+ - Retain according to compliance requirements
106
+ - Don't log secrets, tokens, or sensitive personal data
107
+
108
+ ## Secrets Management Patterns
109
+
110
+ ### Environment-Based Configuration
111
+ - Secrets in environment variables, never in code
112
+ - Separate config per environment (dev, staging, prod)
113
+ - Use secret management services in production (Vault, AWS Secrets Manager, etc.)
114
+
115
+ ### Secret Rotation
116
+ - Rotate credentials regularly
117
+ - Support emergency rotation
118
+ - Don't hardcode secret references
119
+
120
+ ### Least-Exposure Principle
121
+ - Services should only know the secrets they absolutely need
122
+ - Don't use one API key for everything
123
+ - Separate credentials by function and scope
124
+
125
+ ## Resilience Patterns
126
+
127
+ ### Circuit Breaker
128
+ When a dependency fails repeatedly, stop calling it temporarily to prevent cascading failures.
129
+
130
+ - Detect failure threshold
131
+ - Open circuit (fail fast) for a period
132
+ - Half-open (test with limited traffic) before fully closing
133
+
134
+ ### Rate Limiting
135
+ Prevent abuse by limiting requests per time window per client.
136
+
137
+ - Different limits for different endpoints (auth vs. data)
138
+ - Different limits for different user types (anonymous vs. authenticated)
139
+ - Consider burst allowances and graceful degradation
140
+
141
+ ### Timeout and Backoff
142
+ - All external calls should have timeouts
143
+ - Retry with exponential backoff for transient failures
144
+ - Don't retry authentication failures (could be brute force)
145
+
146
+ ## Data Protection Patterns
147
+
148
+ ### Encryption at Rest
149
+ - Sensitive data encrypted in database
150
+ - Key management separate from data access
151
+ - Consider performance impact on queries
152
+
153
+ ### Encryption in Transit
154
+ - TLS for all external communication
155
+ - Consider mTLS for service-to-service
156
+ - Don't disable certificate verification
157
+
158
+ ### Tokenization
159
+ Replace sensitive data with non-sensitive equivalents.
160
+
161
+ - Actual data stored in secure vault
162
+ - Token used in application logic
163
+ - Reduces exposure surface
164
+
165
+ ## Secure Defaults Patterns
166
+
167
+ ### Deny by Default
168
+ - All access denied unless explicitly granted
169
+ - All features disabled unless explicitly enabled
170
+ - All connections rejected unless explicitly allowed
171
+
172
+ ### Minimal Surface Area
173
+ - Don't expose features you don't need
174
+ - Disable unused endpoints, services, protocols
175
+ - Remove default accounts and sample data
176
+
177
+ ### Secure Configuration
178
+ - Framework defaults should be hardened
179
+ - Don't rely on "out of the box" security
180
+ - Explicitly configure security settings
181
+
182
+ ## Defense in Depth Patterns
183
+
184
+ ### Layered Controls
185
+ Multiple independent controls for the same threat:
186
+
187
+ ```
188
+ Threat: SQL Injection
189
+ ├── Layer 1: Input validation (reject non-matching input)
190
+ ├── Layer 2: Parameterized queries (prevent interpretation as SQL)
191
+ ├── Layer 3: Least privilege database user (limit damage if bypassed)
192
+ └── Layer 4: Monitoring (detect and alert on suspicious patterns)
193
+ ```
194
+
195
+ ### Compartmentalization
196
+ - Separate sensitive operations from general operations
197
+ - Isolate user data by tenant or scope
198
+ - Use different credentials for different functions
199
+
200
+ ### Fail-Safe States
201
+ - When validation fails: reject
202
+ - When auth fails: deny
203
+ - When encryption fails: don't send
204
+ - When logging fails: fail closed (don't proceed silently)
205
+
206
+ ## Anti-Patterns to Avoid
207
+
208
+ ### God Object Security
209
+ Putting all security logic in one place (e.g., a single middleware) instead of at each layer.
210
+
211
+ **Problem**: Bypass the middleware, bypass all security.
212
+ **Fix**: Security at every relevant layer.
213
+
214
+ ### Client-Side Security
215
+ Relying on browser validation, hidden fields, or client logic for security.
216
+
217
+ **Problem**: Clients are completely under attacker control.
218
+ **Fix**: Server-side validation is the only validation that matters.
219
+
220
+ ### Security Through Obscurity
221
+ Relying on secrecy of design or implementation for security.
222
+
223
+ **Problem**: Once discovered (and it will be), there's no protection.
224
+ **Fix**: Assume attackers know your design. Security should work even when public.
225
+
226
+ ### Trusting the Network
227
+ Assuming internal network traffic is safe.
228
+
229
+ **Problem**: Lateral movement after initial compromise is common.
230
+ **Fix**: Authenticate and validate internal traffic too.
231
+
232
+ ### Hardcoded Secrets
233
+ Embedding credentials, keys, or tokens in source code.
234
+
235
+ **Problem**: Committed to version control, visible to anyone with code access.
236
+ **Fix**: Environment variables, secret managers, runtime injection.
@@ -0,0 +1,137 @@
1
+ # Threat Modeling Guide
2
+
3
+ Extended approaches for analyzing security threats during system design.
4
+
5
+ ## Data Flow Analysis
6
+
7
+ Map how data moves through your system to identify trust boundaries:
8
+
9
+ ```
10
+ External Request → [Trust Boundary] → API Gateway → [Trust Boundary] → Service → [Trust Boundary] → Database
11
+ ↑ ↑
12
+ Authenticate Authorize
13
+ Validate input Validate output
14
+ Rate limit Audit log
15
+ ```
16
+
17
+ **Process**:
18
+ 1. Draw the data flow for a specific use case
19
+ 2. Identify every trust boundary crossing
20
+ 3. Ask: "What's the worst thing that could enter here?"
21
+ 4. Ask: "What validation or enforcement should happen at this boundary?"
22
+ 5. Look for paths that bypass expected controls
23
+
24
+ ## STRIDE in Depth
25
+
26
+ ### Spoofing
27
+ - **Threat**: Attacker pretends to be a legitimate user or system
28
+ - **Questions**: How are identities verified? Can tokens be stolen or forged? Can sessions be hijacked?
29
+ - **Controls**: Strong authentication, token binding, session validation, mutual TLS
30
+
31
+ ### Tampering
32
+ - **Threat**: Data is modified in transit or at rest
33
+ - **Questions**: Is integrity checked? Can parameters be altered? Can files be modified?
34
+ - **Controls**: Input validation, checksums, signatures, immutable audit logs
35
+
36
+ ### Repudiation
37
+ - **Threat**: Actions can't be traced back to an actor
38
+ - **Questions**: Are all sensitive operations logged? Are logs tamper-evident? Can users deny their actions?
39
+ - **Controls**: Comprehensive audit logging, signed logs, non-repudiation mechanisms
40
+
41
+ ### Information Disclosure
42
+ - **Threat**: Sensitive data leaks to unauthorized parties
43
+ - **Questions**: What data is exposed in errors? In logs? In API responses? Can users access other users' data?
44
+ - **Controls**: Output filtering, log redaction, access controls, encryption at rest/transit
45
+
46
+ ### Denial of Service
47
+ - **Threat**: System becomes unavailable or unusable
48
+ - **Questions**: Can endpoints be overwhelmed? Are there expensive operations? Can resources be exhausted?
49
+ - **Controls**: Rate limiting, resource quotas, circuit breakers, caching, input size limits
50
+
51
+ ### Elevation of Privilege
52
+ - **Threat**: User gains more access than authorized
53
+ - **Questions**: Is authorization checked on every operation? Can parameters be manipulated to access other resources? Are roles properly enforced?
54
+ - **Controls**: Resource-level authorization, parameter validation, role enforcement, privilege separation
55
+
56
+ ## Attack Trees
57
+
58
+ ### Building an Attack Tree
59
+
60
+ ```
61
+ Goal: Access User Data
62
+ ├── Path A: Steal Session Token
63
+ │ ├── Phishing (requires social engineering)
64
+ │ ├── XSS (requires input injection) ← Mitigated by output encoding
65
+ │ └── Network interception (requires unencrypted traffic) ← Mitigated by HTTPS
66
+ ├── Path B: Direct Database Access
67
+ │ ├── SQL Injection (requires unparameterized query) ← Mitigated by parameterized queries
68
+ │ └── Direct connection (requires network access) ← Mitigated by network segmentation
69
+ └── Path C: Abuse API
70
+ ├── IDOR (requires missing authorization) ← Mitigated by resource checks
71
+ └── Parameter tampering (requires missing validation) ← Mitigated by input validation
72
+ ```
73
+
74
+ **Usage**: Focus on the unmitigated paths. If you find a path with no controls, that's your priority.
75
+
76
+ ### Risk Scoring
77
+
78
+ For each identified threat, assess:
79
+
80
+ - **Impact** (1-5): How bad would exploitation be?
81
+ - **Likelihood** (1-5): How easy is it to exploit?
82
+ - **Risk** = Impact × Likelihood
83
+
84
+ | Score | Action |
85
+ |-------|--------|
86
+ | 20-25 | Must mitigate before release |
87
+ | 12-16 | Should mitigate in next release cycle |
88
+ | 6-10 | Track and mitigate when convenient |
89
+ | 1-5 | Accept risk, document reasoning |
90
+
91
+ ## Trust Boundary Patterns
92
+
93
+ ### External → Internal
94
+ - Every external request is hostile until authenticated and validated
95
+ - Validation must happen before any processing
96
+ - Never use external data to make internal decisions without verification
97
+
98
+ ### Internal → External
99
+ - Assume external systems are compromised or malicious
100
+ - Validate all responses from third parties
101
+ - Don't expose internal state or identifiers
102
+
103
+ ### User → User
104
+ - Users should never directly access each other's data
105
+ - All cross-user access must go through authorization checks
106
+ - Consider temporal access (can user A access user B's data at time T?)
107
+
108
+ ### Process → Process
109
+ - Inter-service communication should be authenticated
110
+ - Don't trust internal network traffic by default
111
+ - Validate messages between components as if they came from outside
112
+
113
+ ## Threat Modeling Checklist
114
+
115
+ For each feature or component:
116
+
117
+ - [ ] All entry points identified
118
+ - [ ] All trust boundaries mapped
119
+ - [ ] STRIDE threats considered
120
+ - [ ] Attack paths identified for high-value targets
121
+ - [ ] Existing controls mapped
122
+ - [ ] Gaps identified and prioritized
123
+ - [ ] Risk scores assigned
124
+ - [ ] Mitigations planned and scheduled
125
+ - [ ] Assumptions documented (what are we trusting?)
126
+
127
+ ## Lightweight Threat Modeling
128
+
129
+ When you don't have time for full analysis:
130
+
131
+ 1. **Write the user story**: "As an attacker, I want to..."
132
+ 2. **Identify one critical asset**: What would hurt most to lose?
133
+ 3. **Find the shortest path**: What's the easiest way to access it?
134
+ 4. **Add one control**: What's the simplest mitigation?
135
+ 5. **Repeat**: Do this for 3-5 attack stories
136
+
137
+ This takes 15 minutes and catches the most obvious issues.