@mytechtoday/augment-extensions 1.2.2 → 1.3.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.
- package/LICENSE +22 -22
- package/augment-extensions/domain-rules/software-architecture/README.md +143 -143
- package/augment-extensions/domain-rules/software-architecture/examples/banking-layered.md +961 -961
- package/augment-extensions/domain-rules/software-architecture/examples/ecommerce-microservices.md +990 -990
- package/augment-extensions/domain-rules/software-architecture/examples/iot-eventdriven.md +882 -882
- package/augment-extensions/domain-rules/software-architecture/examples/monolith-to-microservices-migration.md +703 -703
- package/augment-extensions/domain-rules/software-architecture/examples/serverless-imageprocessing.md +957 -957
- package/augment-extensions/domain-rules/software-architecture/examples/trading-eventdriven.md +747 -747
- package/augment-extensions/domain-rules/software-architecture/module.json +119 -119
- package/augment-extensions/domain-rules/software-architecture/rules/challenges-solutions.md +763 -763
- package/augment-extensions/domain-rules/software-architecture/rules/definitions-terminology.md +409 -409
- package/augment-extensions/domain-rules/software-architecture/rules/design-principles.md +684 -684
- package/augment-extensions/domain-rules/software-architecture/rules/evaluation-testing.md +1381 -1381
- package/augment-extensions/domain-rules/software-architecture/rules/event-driven-architecture.md +616 -616
- package/augment-extensions/domain-rules/software-architecture/rules/fundamentals.md +306 -306
- package/augment-extensions/domain-rules/software-architecture/rules/industry-architectures.md +554 -554
- package/augment-extensions/domain-rules/software-architecture/rules/layered-architecture.md +776 -776
- package/augment-extensions/domain-rules/software-architecture/rules/microservices-architecture.md +503 -503
- package/augment-extensions/domain-rules/software-architecture/rules/modeling-documentation.md +1199 -1199
- package/augment-extensions/domain-rules/software-architecture/rules/monolithic-architecture.md +351 -351
- package/augment-extensions/domain-rules/software-architecture/rules/principles.md +556 -556
- package/augment-extensions/domain-rules/software-architecture/rules/quality-attributes.md +797 -797
- package/augment-extensions/domain-rules/software-architecture/rules/scalability-performance.md +1345 -1345
- package/augment-extensions/domain-rules/software-architecture/rules/security-architecture.md +1039 -1039
- package/augment-extensions/domain-rules/software-architecture/rules/serverless-architecture.md +711 -711
- package/augment-extensions/domain-rules/software-architecture/rules/skills-development.md +568 -568
- package/augment-extensions/domain-rules/software-architecture/rules/tools-methodologies.md +961 -961
- package/augment-extensions/visual-design/CHANGELOG.md +132 -0
- package/augment-extensions/visual-design/README.md +255 -0
- package/augment-extensions/visual-design/__tests__/README.md +119 -0
- package/augment-extensions/visual-design/__tests__/style-selector.test.ts +172 -0
- package/augment-extensions/visual-design/__tests__/vendor-styles.test.ts +214 -0
- package/augment-extensions/visual-design/domains/other/ai-prompt-helper.ts +157 -0
- package/augment-extensions/visual-design/domains/other/dotnet-application.ts +156 -0
- package/augment-extensions/visual-design/domains/other/linux-platform.ts +156 -0
- package/augment-extensions/visual-design/domains/other/mobile-application.ts +157 -0
- package/augment-extensions/visual-design/domains/other/motion-picture.ts +156 -0
- package/augment-extensions/visual-design/domains/other/os-application.ts +156 -0
- package/augment-extensions/visual-design/domains/other/print-campaigns.ts +158 -0
- package/augment-extensions/visual-design/domains/other/web-app.ts +157 -0
- package/augment-extensions/visual-design/domains/other/website.ts +161 -0
- package/augment-extensions/visual-design/domains/other/windows-platform.ts +156 -0
- package/augment-extensions/visual-design/domains/web-page-styles/amazon-cloudscape.ts +506 -0
- package/augment-extensions/visual-design/domains/web-page-styles/google-modern.ts +615 -0
- package/augment-extensions/visual-design/domains/web-page-styles/microsoft-fluent.ts +531 -0
- package/augment-extensions/visual-design/examples/README.md +97 -0
- package/augment-extensions/visual-design/examples/ai-prompt-generation.md +233 -0
- package/augment-extensions/visual-design/examples/basic-usage.md +216 -0
- package/augment-extensions/visual-design/examples/domain-workflows.md +257 -0
- package/augment-extensions/visual-design/examples/vendor-comparison.md +247 -0
- package/augment-extensions/visual-design/module.json +78 -0
- package/augment-extensions/visual-design/style-selector.ts +177 -0
- package/augment-extensions/visual-design/types.ts +302 -0
- package/augment-extensions/visual-design/visual-design-core.ts +469 -0
- package/augment-extensions/workflows/adr-support/README.md +227 -0
- package/augment-extensions/workflows/adr-support/__tests__/adr-validator.test.ts +203 -0
- package/augment-extensions/workflows/adr-support/adr-validator.ts +162 -0
- package/augment-extensions/workflows/adr-support/examples/complete-lifecycle-example.md +449 -0
- package/augment-extensions/workflows/adr-support/examples/integration-example.md +580 -0
- package/augment-extensions/workflows/adr-support/examples/superseding-example.md +436 -0
- package/augment-extensions/workflows/adr-support/module.json +112 -0
- package/augment-extensions/workflows/adr-support/rules/adr-creation.md +372 -0
- package/augment-extensions/workflows/adr-support/rules/beads-integration.md +443 -0
- package/augment-extensions/workflows/adr-support/rules/conflict-detection.md +486 -0
- package/augment-extensions/workflows/adr-support/rules/decision-detection.md +362 -0
- package/augment-extensions/workflows/adr-support/rules/lifecycle-management.md +427 -0
- package/augment-extensions/workflows/adr-support/rules/openspec-integration.md +465 -0
- package/augment-extensions/workflows/adr-support/rules/template-selection.md +405 -0
- package/augment-extensions/workflows/adr-support/rules/validation-rules.md +543 -0
- package/augment-extensions/workflows/adr-support/schemas/adr-config.json +191 -0
- package/augment-extensions/workflows/adr-support/schemas/adr-metadata.json +172 -0
- package/augment-extensions/workflows/adr-support/templates/business-case.md +235 -0
- package/augment-extensions/workflows/adr-support/templates/madr-elaborate.md +197 -0
- package/augment-extensions/workflows/adr-support/templates/madr-simple.md +68 -0
- package/augment-extensions/workflows/adr-support/templates/nygard.md +84 -0
- package/augment-extensions/writing-standards/screenplay/rules/file-organization.md +213 -213
- package/augment-extensions/writing-standards/screenplay/utils/__tests__/file-organization.test.ts +169 -169
- package/augment-extensions/writing-standards/screenplay/utils/file-organization.ts +165 -165
- package/cli/dist/utils/auto-sync.js +19 -19
- package/package.json +5 -3
- package/augment-extensions/workflows/openspec/README.md +0 -96
- package/augment-extensions/workflows/openspec/examples/complete-change-example.md +0 -244
- package/augment-extensions/workflows/openspec/module.json +0 -54
- package/augment-extensions/workflows/openspec/rules/best-practices.md +0 -272
- package/augment-extensions/workflows/openspec/rules/manual-setup.md +0 -231
- package/augment-extensions/workflows/openspec/rules/spec-format.md +0 -236
- package/augment-extensions/workflows/openspec/rules/workflow.md +0 -214
package/augment-extensions/domain-rules/software-architecture/rules/security-architecture.md
CHANGED
|
@@ -1,1039 +1,1039 @@
|
|
|
1
|
-
# Security Architecture
|
|
2
|
-
|
|
3
|
-
## Overview
|
|
4
|
-
|
|
5
|
-
This document covers security architecture principles, patterns, and practices for building secure systems. Security must be designed into the architecture from the beginning, not added as an afterthought.
|
|
6
|
-
|
|
7
|
-
**References**: OWASP (Open Web Application Security Project), NIST Cybersecurity Framework, Zero Trust Architecture
|
|
8
|
-
|
|
9
|
-
---
|
|
10
|
-
|
|
11
|
-
## Knowledge
|
|
12
|
-
|
|
13
|
-
### Security Principles
|
|
14
|
-
|
|
15
|
-
#### Defense in Depth
|
|
16
|
-
|
|
17
|
-
**Definition**
|
|
18
|
-
- Multiple layers of security controls
|
|
19
|
-
- If one layer fails, others provide protection
|
|
20
|
-
- No single point of failure
|
|
21
|
-
- Comprehensive security strategy
|
|
22
|
-
|
|
23
|
-
**Layers**
|
|
24
|
-
1. **Physical Security**: Data center access, hardware security
|
|
25
|
-
2. **Network Security**: Firewalls, VPNs, network segmentation
|
|
26
|
-
3. **Host Security**: OS hardening, antivirus, host firewalls
|
|
27
|
-
4. **Application Security**: Input validation, authentication, authorization
|
|
28
|
-
5. **Data Security**: Encryption, access controls, data masking
|
|
29
|
-
|
|
30
|
-
**Benefits**
|
|
31
|
-
- Reduces risk of complete compromise
|
|
32
|
-
- Provides multiple opportunities to detect attacks
|
|
33
|
-
- Limits blast radius of security incidents
|
|
34
|
-
- Supports compliance requirements
|
|
35
|
-
|
|
36
|
-
#### Least Privilege
|
|
37
|
-
|
|
38
|
-
**Definition**
|
|
39
|
-
- Grant minimum permissions necessary to perform a task
|
|
40
|
-
- Users and services should have only required access
|
|
41
|
-
- Reduces attack surface and blast radius
|
|
42
|
-
- Principle of minimal authority
|
|
43
|
-
|
|
44
|
-
**Application**
|
|
45
|
-
- User permissions (RBAC, ABAC)
|
|
46
|
-
- Service accounts (minimal IAM roles)
|
|
47
|
-
- Database access (read-only where possible)
|
|
48
|
-
- API access (scoped tokens)
|
|
49
|
-
- File system permissions
|
|
50
|
-
|
|
51
|
-
**Benefits**
|
|
52
|
-
- Limits damage from compromised accounts
|
|
53
|
-
- Reduces insider threat risk
|
|
54
|
-
- Simplifies access auditing
|
|
55
|
-
- Supports compliance (SOC 2, ISO 27001)
|
|
56
|
-
|
|
57
|
-
#### Fail Securely
|
|
58
|
-
|
|
59
|
-
**Definition**
|
|
60
|
-
- System should fail in a secure state
|
|
61
|
-
- Errors should not expose sensitive information
|
|
62
|
-
- Default to deny access on failure
|
|
63
|
-
- Graceful degradation without security compromise
|
|
64
|
-
|
|
65
|
-
**Practices**
|
|
66
|
-
- Default deny (whitelist, not blacklist)
|
|
67
|
-
- Generic error messages (no sensitive details)
|
|
68
|
-
- Secure defaults (opt-in for risky features)
|
|
69
|
-
- Fail closed (deny access on auth failure)
|
|
70
|
-
|
|
71
|
-
#### Zero Trust Architecture
|
|
72
|
-
|
|
73
|
-
**Definition**
|
|
74
|
-
- Never trust, always verify
|
|
75
|
-
- No implicit trust based on network location
|
|
76
|
-
- Verify every request, every time
|
|
77
|
-
- Assume breach mentality
|
|
78
|
-
|
|
79
|
-
**Principles**
|
|
80
|
-
1. **Verify explicitly**: Always authenticate and authorize
|
|
81
|
-
2. **Use least privilege access**: Just-in-time and just-enough-access
|
|
82
|
-
3. **Assume breach**: Minimize blast radius, segment access
|
|
83
|
-
|
|
84
|
-
**Components**
|
|
85
|
-
- Identity and access management (IAM)
|
|
86
|
-
- Multi-factor authentication (MFA)
|
|
87
|
-
- Micro-segmentation
|
|
88
|
-
- Continuous monitoring and validation
|
|
89
|
-
- Encryption everywhere
|
|
90
|
-
|
|
91
|
-
### Threat Modeling
|
|
92
|
-
|
|
93
|
-
**Definition**
|
|
94
|
-
- Systematic approach to identifying security threats
|
|
95
|
-
- Analyze system to find vulnerabilities
|
|
96
|
-
- Prioritize threats by risk
|
|
97
|
-
- Design mitigations
|
|
98
|
-
|
|
99
|
-
**STRIDE Model**
|
|
100
|
-
|
|
101
|
-
- **S**poofing: Impersonating user or system
|
|
102
|
-
- **T**ampering: Modifying data or code
|
|
103
|
-
- **R**epudiation: Denying actions
|
|
104
|
-
- **I**nformation Disclosure: Exposing sensitive data
|
|
105
|
-
- **D**enial of Service: Making system unavailable
|
|
106
|
-
- **E**levation of Privilege: Gaining unauthorized access
|
|
107
|
-
|
|
108
|
-
**Threat Modeling Process**
|
|
109
|
-
|
|
110
|
-
1. **Identify Assets**: What needs protection?
|
|
111
|
-
2. **Create Architecture Overview**: Data flow diagrams
|
|
112
|
-
3. **Identify Threats**: Use STRIDE or other framework
|
|
113
|
-
4. **Mitigate Threats**: Design security controls
|
|
114
|
-
5. **Validate**: Review and test mitigations
|
|
115
|
-
|
|
116
|
-
**Tools**
|
|
117
|
-
- Microsoft Threat Modeling Tool
|
|
118
|
-
- OWASP Threat Dragon
|
|
119
|
-
- IriusRisk
|
|
120
|
-
- ThreatModeler
|
|
121
|
-
|
|
122
|
-
### Authentication
|
|
123
|
-
|
|
124
|
-
**Definition**
|
|
125
|
-
- Verifying identity of user or system
|
|
126
|
-
- "Who are you?"
|
|
127
|
-
- Foundation of access control
|
|
128
|
-
- Multiple factors increase security
|
|
129
|
-
|
|
130
|
-
**Authentication Factors**
|
|
131
|
-
|
|
132
|
-
1. **Something You Know**: Password, PIN, security question
|
|
133
|
-
2. **Something You Have**: Phone, hardware token, smart card
|
|
134
|
-
3. **Something You Are**: Biometrics (fingerprint, face, iris)
|
|
135
|
-
|
|
136
|
-
**Multi-Factor Authentication (MFA)**
|
|
137
|
-
- Combines two or more factors
|
|
138
|
-
- Significantly increases security
|
|
139
|
-
- Protects against password compromise
|
|
140
|
-
- Industry best practice
|
|
141
|
-
|
|
142
|
-
**Authentication Protocols**
|
|
143
|
-
|
|
144
|
-
- **OAuth 2.0**: Authorization framework for delegated access
|
|
145
|
-
- **OpenID Connect**: Identity layer on top of OAuth 2.0
|
|
146
|
-
- **SAML**: XML-based authentication and authorization
|
|
147
|
-
- **JWT**: JSON Web Tokens for stateless authentication
|
|
148
|
-
|
|
149
|
-
**Best Practices**
|
|
150
|
-
- Enforce strong password policies
|
|
151
|
-
- Implement MFA for sensitive operations
|
|
152
|
-
- Use secure password storage (bcrypt, Argon2)
|
|
153
|
-
- Implement account lockout after failed attempts
|
|
154
|
-
- Use HTTPS for credential transmission
|
|
155
|
-
- Implement session timeout
|
|
156
|
-
|
|
157
|
-
### Authorization
|
|
158
|
-
|
|
159
|
-
**Definition**
|
|
160
|
-
- Determining what authenticated user can do
|
|
161
|
-
- "What are you allowed to do?"
|
|
162
|
-
- Access control and permissions
|
|
163
|
-
- Enforces security policies
|
|
164
|
-
|
|
165
|
-
**Authorization Models**
|
|
166
|
-
|
|
167
|
-
#### Role-Based Access Control (RBAC)
|
|
168
|
-
|
|
169
|
-
**Definition**
|
|
170
|
-
- Permissions assigned to roles
|
|
171
|
-
- Users assigned to roles
|
|
172
|
-
- Simplifies permission management
|
|
173
|
-
- Common in enterprise systems
|
|
174
|
-
|
|
175
|
-
**Example**
|
|
176
|
-
```
|
|
177
|
-
Roles: Admin, Manager, User
|
|
178
|
-
Admin: All permissions
|
|
179
|
-
Manager: Read, Write, Delete (own resources)
|
|
180
|
-
User: Read, Write (own resources)
|
|
181
|
-
```
|
|
182
|
-
|
|
183
|
-
**Benefits**
|
|
184
|
-
- Easy to understand and manage
|
|
185
|
-
- Scales well for large organizations
|
|
186
|
-
- Supports separation of duties
|
|
187
|
-
- Simplifies auditing
|
|
188
|
-
|
|
189
|
-
#### Attribute-Based Access Control (ABAC)
|
|
190
|
-
|
|
191
|
-
**Definition**
|
|
192
|
-
- Permissions based on attributes
|
|
193
|
-
- User attributes, resource attributes, environment attributes
|
|
194
|
-
- Fine-grained, dynamic access control
|
|
195
|
-
- Flexible and expressive
|
|
196
|
-
|
|
197
|
-
**Example**
|
|
198
|
-
```
|
|
199
|
-
Allow if:
|
|
200
|
-
user.department == resource.department AND
|
|
201
|
-
user.clearance >= resource.classification AND
|
|
202
|
-
time.hour >= 9 AND time.hour <= 17
|
|
203
|
-
```
|
|
204
|
-
|
|
205
|
-
**Benefits**
|
|
206
|
-
- Fine-grained control
|
|
207
|
-
- Dynamic policies
|
|
208
|
-
- Context-aware decisions
|
|
209
|
-
- Reduces role explosion
|
|
210
|
-
|
|
211
|
-
#### Policy-Based Access Control
|
|
212
|
-
|
|
213
|
-
**Definition**
|
|
214
|
-
- Centralized policy engine
|
|
215
|
-
- Policies written in declarative language
|
|
216
|
-
- Separates policy from code
|
|
217
|
-
- Examples: OPA (Open Policy Agent), AWS IAM Policies
|
|
218
|
-
|
|
219
|
-
**Benefits**
|
|
220
|
-
- Centralized policy management
|
|
221
|
-
- Auditable policies
|
|
222
|
-
- Testable policies
|
|
223
|
-
- Reusable across services
|
|
224
|
-
|
|
225
|
-
### Encryption
|
|
226
|
-
|
|
227
|
-
**Definition**
|
|
228
|
-
- Converting data to unreadable format
|
|
229
|
-
- Protects confidentiality
|
|
230
|
-
- Two main types: symmetric and asymmetric
|
|
231
|
-
- Essential for data protection
|
|
232
|
-
|
|
233
|
-
**Encryption at Rest**
|
|
234
|
-
- Protects stored data
|
|
235
|
-
- Database encryption (TDE)
|
|
236
|
-
- File system encryption
|
|
237
|
-
- Disk encryption
|
|
238
|
-
- Key management critical
|
|
239
|
-
|
|
240
|
-
**Encryption in Transit**
|
|
241
|
-
- Protects data during transmission
|
|
242
|
-
- TLS/SSL for HTTPS
|
|
243
|
-
- VPNs for network traffic
|
|
244
|
-
- Encrypted messaging protocols
|
|
245
|
-
- Certificate management
|
|
246
|
-
|
|
247
|
-
**Key Management**
|
|
248
|
-
- Secure key generation
|
|
249
|
-
- Key rotation policies
|
|
250
|
-
- Key storage (HSM, KMS)
|
|
251
|
-
- Key access controls
|
|
252
|
-
- Key backup and recovery
|
|
253
|
-
|
|
254
|
-
**Best Practices**
|
|
255
|
-
- Use strong algorithms (AES-256, RSA-2048+)
|
|
256
|
-
- Never roll your own crypto
|
|
257
|
-
- Use TLS 1.2 or higher
|
|
258
|
-
- Implement perfect forward secrecy
|
|
259
|
-
- Rotate keys regularly
|
|
260
|
-
- Use hardware security modules (HSM) for key storage
|
|
261
|
-
|
|
262
|
-
### Secure Communication
|
|
263
|
-
|
|
264
|
-
**TLS/SSL**
|
|
265
|
-
- Transport Layer Security
|
|
266
|
-
- Encrypts data in transit
|
|
267
|
-
- Provides authentication and integrity
|
|
268
|
-
- Essential for web applications
|
|
269
|
-
|
|
270
|
-
**Certificate Management**
|
|
271
|
-
- Use trusted Certificate Authorities (CA)
|
|
272
|
-
- Implement certificate pinning for mobile apps
|
|
273
|
-
- Monitor certificate expiration
|
|
274
|
-
- Use automated certificate renewal (Let's Encrypt)
|
|
275
|
-
|
|
276
|
-
**API Security**
|
|
277
|
-
- API keys for identification
|
|
278
|
-
- OAuth 2.0 for authorization
|
|
279
|
-
- Rate limiting and throttling
|
|
280
|
-
- Input validation and sanitization
|
|
281
|
-
- CORS policies
|
|
282
|
-
|
|
283
|
-
### Input Validation and Sanitization
|
|
284
|
-
|
|
285
|
-
**Definition**
|
|
286
|
-
- Validate all input from untrusted sources
|
|
287
|
-
- Sanitize data before use
|
|
288
|
-
- Prevent injection attacks
|
|
289
|
-
- Defense against OWASP Top 10 vulnerabilities
|
|
290
|
-
|
|
291
|
-
**Validation Strategies**
|
|
292
|
-
- Whitelist (allow known good)
|
|
293
|
-
- Blacklist (deny known bad) - less secure
|
|
294
|
-
- Type checking and constraints
|
|
295
|
-
- Length and format validation
|
|
296
|
-
- Business logic validation
|
|
297
|
-
|
|
298
|
-
**Common Injection Attacks**
|
|
299
|
-
|
|
300
|
-
**SQL Injection**
|
|
301
|
-
- Malicious SQL in user input
|
|
302
|
-
- Can read, modify, or delete data
|
|
303
|
-
- Prevention: Parameterized queries, ORMs
|
|
304
|
-
|
|
305
|
-
**Cross-Site Scripting (XSS)**
|
|
306
|
-
- Malicious scripts in web pages
|
|
307
|
-
- Can steal cookies, session tokens
|
|
308
|
-
- Prevention: Output encoding, CSP headers
|
|
309
|
-
|
|
310
|
-
**Command Injection**
|
|
311
|
-
- Malicious commands in system calls
|
|
312
|
-
- Can execute arbitrary code
|
|
313
|
-
- Prevention: Avoid system calls, input validation
|
|
314
|
-
|
|
315
|
-
**LDAP Injection**
|
|
316
|
-
- Malicious LDAP queries
|
|
317
|
-
- Can bypass authentication
|
|
318
|
-
- Prevention: Input validation, parameterized queries
|
|
319
|
-
|
|
320
|
-
### Audit Logging
|
|
321
|
-
|
|
322
|
-
**Definition**
|
|
323
|
-
- Record security-relevant events
|
|
324
|
-
- Support forensics and compliance
|
|
325
|
-
- Detect and investigate incidents
|
|
326
|
-
- Non-repudiation
|
|
327
|
-
|
|
328
|
-
**What to Log**
|
|
329
|
-
- Authentication events (success, failure)
|
|
330
|
-
- Authorization failures
|
|
331
|
-
- Data access (especially sensitive data)
|
|
332
|
-
- Configuration changes
|
|
333
|
-
- Administrative actions
|
|
334
|
-
- Security events (attacks, anomalies)
|
|
335
|
-
|
|
336
|
-
**Log Content**
|
|
337
|
-
- Timestamp (UTC)
|
|
338
|
-
- User/service identity
|
|
339
|
-
- Action performed
|
|
340
|
-
- Resource accessed
|
|
341
|
-
- Result (success/failure)
|
|
342
|
-
- Source IP address
|
|
343
|
-
- Session ID
|
|
344
|
-
|
|
345
|
-
**Best Practices**
|
|
346
|
-
- Log to centralized system (SIEM)
|
|
347
|
-
- Protect logs from tampering
|
|
348
|
-
- Retain logs per compliance requirements
|
|
349
|
-
- Monitor logs for anomalies
|
|
350
|
-
- Never log sensitive data (passwords, credit cards)
|
|
351
|
-
- Use structured logging (JSON)
|
|
352
|
-
|
|
353
|
-
---
|
|
354
|
-
|
|
355
|
-
## Skills
|
|
356
|
-
|
|
357
|
-
### Implementing Authentication
|
|
358
|
-
|
|
359
|
-
**JWT-Based Authentication**
|
|
360
|
-
|
|
361
|
-
**Token Structure**
|
|
362
|
-
- Header: Algorithm and token type
|
|
363
|
-
- Payload: Claims (user ID, roles, expiration)
|
|
364
|
-
- Signature: Verify token integrity
|
|
365
|
-
|
|
366
|
-
**Best Practices**
|
|
367
|
-
- Use short expiration times (15 minutes)
|
|
368
|
-
- Implement refresh tokens
|
|
369
|
-
- Store tokens securely (httpOnly cookies)
|
|
370
|
-
- Validate signature on every request
|
|
371
|
-
- Include audience and issuer claims
|
|
372
|
-
- Use strong signing algorithms (RS256, ES256)
|
|
373
|
-
|
|
374
|
-
**Session Management**
|
|
375
|
-
- Generate cryptographically random session IDs
|
|
376
|
-
- Set secure and httpOnly flags on cookies
|
|
377
|
-
- Implement session timeout
|
|
378
|
-
- Invalidate sessions on logout
|
|
379
|
-
- Regenerate session ID after authentication
|
|
380
|
-
|
|
381
|
-
### Implementing Authorization
|
|
382
|
-
|
|
383
|
-
**RBAC Implementation**
|
|
384
|
-
|
|
385
|
-
**Database Schema**
|
|
386
|
-
```sql
|
|
387
|
-
CREATE TABLE users (
|
|
388
|
-
id UUID PRIMARY KEY,
|
|
389
|
-
email VARCHAR(255) UNIQUE NOT NULL,
|
|
390
|
-
password_hash VARCHAR(255) NOT NULL
|
|
391
|
-
);
|
|
392
|
-
|
|
393
|
-
CREATE TABLE roles (
|
|
394
|
-
id UUID PRIMARY KEY,
|
|
395
|
-
name VARCHAR(50) UNIQUE NOT NULL
|
|
396
|
-
);
|
|
397
|
-
|
|
398
|
-
CREATE TABLE permissions (
|
|
399
|
-
id UUID PRIMARY KEY,
|
|
400
|
-
name VARCHAR(100) UNIQUE NOT NULL,
|
|
401
|
-
resource VARCHAR(50) NOT NULL,
|
|
402
|
-
action VARCHAR(50) NOT NULL
|
|
403
|
-
);
|
|
404
|
-
|
|
405
|
-
CREATE TABLE user_roles (
|
|
406
|
-
user_id UUID REFERENCES users(id),
|
|
407
|
-
role_id UUID REFERENCES roles(id),
|
|
408
|
-
PRIMARY KEY (user_id, role_id)
|
|
409
|
-
);
|
|
410
|
-
|
|
411
|
-
CREATE TABLE role_permissions (
|
|
412
|
-
role_id UUID REFERENCES roles(id),
|
|
413
|
-
permission_id UUID REFERENCES permissions(id),
|
|
414
|
-
PRIMARY KEY (role_id, permission_id)
|
|
415
|
-
);
|
|
416
|
-
```
|
|
417
|
-
|
|
418
|
-
**Authorization Check**
|
|
419
|
-
```typescript
|
|
420
|
-
async function checkPermission(
|
|
421
|
-
userId: string,
|
|
422
|
-
resource: string,
|
|
423
|
-
action: string
|
|
424
|
-
): Promise<boolean> {
|
|
425
|
-
const result = await db.query(`
|
|
426
|
-
SELECT COUNT(*) as count
|
|
427
|
-
FROM users u
|
|
428
|
-
JOIN user_roles ur ON u.id = ur.user_id
|
|
429
|
-
JOIN role_permissions rp ON ur.role_id = rp.role_id
|
|
430
|
-
JOIN permissions p ON rp.permission_id = p.id
|
|
431
|
-
WHERE u.id = $1
|
|
432
|
-
AND p.resource = $2
|
|
433
|
-
AND p.action = $3
|
|
434
|
-
`, [userId, resource, action]);
|
|
435
|
-
|
|
436
|
-
return result.rows[0].count > 0;
|
|
437
|
-
}
|
|
438
|
-
```
|
|
439
|
-
|
|
440
|
-
### Implementing Secure Password Storage
|
|
441
|
-
|
|
442
|
-
**Password Hashing**
|
|
443
|
-
```typescript
|
|
444
|
-
import bcrypt from 'bcrypt';
|
|
445
|
-
|
|
446
|
-
// Hash password during registration
|
|
447
|
-
async function hashPassword(password: string): Promise<string> {
|
|
448
|
-
const saltRounds = 10; // Cost factor
|
|
449
|
-
return bcrypt.hash(password, saltRounds);
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
// Verify password during login
|
|
453
|
-
async function verifyPassword(
|
|
454
|
-
password: string,
|
|
455
|
-
hash: string
|
|
456
|
-
): Promise<boolean> {
|
|
457
|
-
return bcrypt.compare(password, hash);
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
// Example usage
|
|
461
|
-
class AuthService {
|
|
462
|
-
async register(email: string, password: string): Promise<User> {
|
|
463
|
-
// Validate password strength
|
|
464
|
-
if (password.length < 8) {
|
|
465
|
-
throw new Error('Password must be at least 8 characters');
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
const passwordHash = await hashPassword(password);
|
|
469
|
-
|
|
470
|
-
return this.userRepository.create({
|
|
471
|
-
email,
|
|
472
|
-
passwordHash
|
|
473
|
-
});
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
async login(email: string, password: string): Promise<string> {
|
|
477
|
-
const user = await this.userRepository.findByEmail(email);
|
|
478
|
-
|
|
479
|
-
if (!user) {
|
|
480
|
-
throw new Error('Invalid credentials');
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
const isValid = await verifyPassword(password, user.passwordHash);
|
|
484
|
-
|
|
485
|
-
if (!isValid) {
|
|
486
|
-
throw new Error('Invalid credentials');
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
// Generate JWT token
|
|
490
|
-
return this.generateToken(user);
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
```
|
|
494
|
-
|
|
495
|
-
### Implementing Rate Limiting
|
|
496
|
-
|
|
497
|
-
**Token Bucket Algorithm**
|
|
498
|
-
```typescript
|
|
499
|
-
interface RateLimitConfig {
|
|
500
|
-
maxTokens: number; // Bucket capacity
|
|
501
|
-
refillRate: number; // Tokens per second
|
|
502
|
-
windowMs: number; // Time window
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
class RateLimiter {
|
|
506
|
-
private buckets = new Map<string, TokenBucket>();
|
|
507
|
-
|
|
508
|
-
constructor(private config: RateLimitConfig) {}
|
|
509
|
-
|
|
510
|
-
async checkLimit(key: string): Promise<boolean> {
|
|
511
|
-
let bucket = this.buckets.get(key);
|
|
512
|
-
|
|
513
|
-
if (!bucket) {
|
|
514
|
-
bucket = new TokenBucket(
|
|
515
|
-
this.config.maxTokens,
|
|
516
|
-
this.config.refillRate
|
|
517
|
-
);
|
|
518
|
-
this.buckets.set(key, bucket);
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
return bucket.consume();
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
class TokenBucket {
|
|
526
|
-
private tokens: number;
|
|
527
|
-
private lastRefill: number;
|
|
528
|
-
|
|
529
|
-
constructor(
|
|
530
|
-
private capacity: number,
|
|
531
|
-
private refillRate: number
|
|
532
|
-
) {
|
|
533
|
-
this.tokens = capacity;
|
|
534
|
-
this.lastRefill = Date.now();
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
consume(): boolean {
|
|
538
|
-
this.refill();
|
|
539
|
-
|
|
540
|
-
if (this.tokens >= 1) {
|
|
541
|
-
this.tokens -= 1;
|
|
542
|
-
return true;
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
return false;
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
private refill(): void {
|
|
549
|
-
const now = Date.now();
|
|
550
|
-
const timePassed = (now - this.lastRefill) / 1000;
|
|
551
|
-
const tokensToAdd = timePassed * this.refillRate;
|
|
552
|
-
|
|
553
|
-
this.tokens = Math.min(
|
|
554
|
-
this.capacity,
|
|
555
|
-
this.tokens + tokensToAdd
|
|
556
|
-
);
|
|
557
|
-
this.lastRefill = now;
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
// Express middleware
|
|
562
|
-
function rateLimitMiddleware(limiter: RateLimiter) {
|
|
563
|
-
return async (req: Request, res: Response, next: NextFunction) => {
|
|
564
|
-
const key = req.ip || req.socket.remoteAddress || 'unknown';
|
|
565
|
-
|
|
566
|
-
const allowed = await limiter.checkLimit(key);
|
|
567
|
-
|
|
568
|
-
if (!allowed) {
|
|
569
|
-
res.status(429).json({
|
|
570
|
-
error: 'Too many requests'
|
|
571
|
-
});
|
|
572
|
-
return;
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
next();
|
|
576
|
-
};
|
|
577
|
-
}
|
|
578
|
-
```
|
|
579
|
-
|
|
580
|
-
---
|
|
581
|
-
|
|
582
|
-
## Examples
|
|
583
|
-
|
|
584
|
-
### Zero Trust Architecture Implementation
|
|
585
|
-
|
|
586
|
-
**Service-to-Service Authentication**
|
|
587
|
-
```typescript
|
|
588
|
-
// Service A calling Service B
|
|
589
|
-
class ServiceClient {
|
|
590
|
-
constructor(
|
|
591
|
-
private serviceUrl: string,
|
|
592
|
-
private clientId: string,
|
|
593
|
-
private clientSecret: string
|
|
594
|
-
) {}
|
|
595
|
-
|
|
596
|
-
async callService(endpoint: string, data: any): Promise<any> {
|
|
597
|
-
// Get access token
|
|
598
|
-
const token = await this.getAccessToken();
|
|
599
|
-
|
|
600
|
-
// Make authenticated request
|
|
601
|
-
const response = await fetch(`${this.serviceUrl}${endpoint}`, {
|
|
602
|
-
method: 'POST',
|
|
603
|
-
headers: {
|
|
604
|
-
'Authorization': `Bearer ${token}`,
|
|
605
|
-
'Content-Type': 'application/json'
|
|
606
|
-
},
|
|
607
|
-
body: JSON.stringify(data)
|
|
608
|
-
});
|
|
609
|
-
|
|
610
|
-
if (!response.ok) {
|
|
611
|
-
throw new Error(`Service call failed: ${response.statusText}`);
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
return response.json();
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
private async getAccessToken(): Promise<string> {
|
|
618
|
-
// OAuth 2.0 Client Credentials flow
|
|
619
|
-
const response = await fetch('https://auth.example.com/token', {
|
|
620
|
-
method: 'POST',
|
|
621
|
-
headers: {
|
|
622
|
-
'Content-Type': 'application/x-www-form-urlencoded'
|
|
623
|
-
},
|
|
624
|
-
body: new URLSearchParams({
|
|
625
|
-
grant_type: 'client_credentials',
|
|
626
|
-
client_id: this.clientId,
|
|
627
|
-
client_secret: this.clientSecret,
|
|
628
|
-
scope: 'service-b:read service-b:write'
|
|
629
|
-
})
|
|
630
|
-
});
|
|
631
|
-
|
|
632
|
-
const data = await response.json();
|
|
633
|
-
return data.access_token;
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
// Service B validating requests
|
|
638
|
-
class AuthMiddleware {
|
|
639
|
-
async validateToken(req: Request, res: Response, next: NextFunction) {
|
|
640
|
-
const authHeader = req.headers.authorization;
|
|
641
|
-
|
|
642
|
-
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
643
|
-
res.status(401).json({ error: 'Missing or invalid authorization header' });
|
|
644
|
-
return;
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
const token = authHeader.substring(7);
|
|
648
|
-
|
|
649
|
-
try {
|
|
650
|
-
// Validate token with auth service
|
|
651
|
-
const tokenInfo = await this.validateWithAuthService(token);
|
|
652
|
-
|
|
653
|
-
// Check required scopes
|
|
654
|
-
if (!this.hasRequiredScopes(tokenInfo.scopes, req.path, req.method)) {
|
|
655
|
-
res.status(403).json({ error: 'Insufficient permissions' });
|
|
656
|
-
return;
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
// Attach token info to request
|
|
660
|
-
(req as any).auth = tokenInfo;
|
|
661
|
-
next();
|
|
662
|
-
} catch (error) {
|
|
663
|
-
res.status(401).json({ error: 'Invalid token' });
|
|
664
|
-
}
|
|
665
|
-
}
|
|
666
|
-
|
|
667
|
-
private async validateWithAuthService(token: string): Promise<TokenInfo> {
|
|
668
|
-
const response = await fetch('https://auth.example.com/validate', {
|
|
669
|
-
headers: {
|
|
670
|
-
'Authorization': `Bearer ${token}`
|
|
671
|
-
}
|
|
672
|
-
});
|
|
673
|
-
|
|
674
|
-
if (!response.ok) {
|
|
675
|
-
throw new Error('Token validation failed');
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
return response.json();
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
private hasRequiredScopes(
|
|
682
|
-
scopes: string[],
|
|
683
|
-
path: string,
|
|
684
|
-
method: string
|
|
685
|
-
): boolean {
|
|
686
|
-
// Check if token has required scopes for this endpoint
|
|
687
|
-
const requiredScope = `service-b:${method.toLowerCase()}`;
|
|
688
|
-
return scopes.includes(requiredScope);
|
|
689
|
-
}
|
|
690
|
-
}
|
|
691
|
-
```
|
|
692
|
-
|
|
693
|
-
### OWASP Top 10 Mitigations
|
|
694
|
-
|
|
695
|
-
**1. Broken Access Control**
|
|
696
|
-
```typescript
|
|
697
|
-
// Bad: No authorization check
|
|
698
|
-
app.delete('/api/users/:id', async (req, res) => {
|
|
699
|
-
await userRepository.delete(req.params.id);
|
|
700
|
-
res.json({ success: true });
|
|
701
|
-
});
|
|
702
|
-
|
|
703
|
-
// Good: Check authorization
|
|
704
|
-
app.delete('/api/users/:id', authenticate, async (req, res) => {
|
|
705
|
-
const currentUser = (req as any).user;
|
|
706
|
-
const targetUserId = req.params.id;
|
|
707
|
-
|
|
708
|
-
// Users can only delete their own account, or admin can delete any
|
|
709
|
-
if (currentUser.id !== targetUserId && !currentUser.roles.includes('admin')) {
|
|
710
|
-
res.status(403).json({ error: 'Forbidden' });
|
|
711
|
-
return;
|
|
712
|
-
}
|
|
713
|
-
|
|
714
|
-
await userRepository.delete(targetUserId);
|
|
715
|
-
res.json({ success: true });
|
|
716
|
-
});
|
|
717
|
-
```
|
|
718
|
-
|
|
719
|
-
**2. Cryptographic Failures**
|
|
720
|
-
```typescript
|
|
721
|
-
// Bad: Storing sensitive data in plain text
|
|
722
|
-
await db.query(
|
|
723
|
-
'INSERT INTO users (email, password, ssn) VALUES ($1, $2, $3)',
|
|
724
|
-
[email, password, ssn]
|
|
725
|
-
);
|
|
726
|
-
|
|
727
|
-
// Good: Hash passwords, encrypt sensitive data
|
|
728
|
-
import bcrypt from 'bcrypt';
|
|
729
|
-
import crypto from 'crypto';
|
|
730
|
-
|
|
731
|
-
const passwordHash = await bcrypt.hash(password, 10);
|
|
732
|
-
const ssnEncrypted = encrypt(ssn, process.env.ENCRYPTION_KEY!);
|
|
733
|
-
|
|
734
|
-
await db.query(
|
|
735
|
-
'INSERT INTO users (email, password_hash, ssn_encrypted) VALUES ($1, $2, $3)',
|
|
736
|
-
[email, passwordHash, ssnEncrypted]
|
|
737
|
-
);
|
|
738
|
-
|
|
739
|
-
function encrypt(text: string, key: string): string {
|
|
740
|
-
const iv = crypto.randomBytes(16);
|
|
741
|
-
const cipher = crypto.createCipheriv('aes-256-gcm', Buffer.from(key, 'hex'), iv);
|
|
742
|
-
|
|
743
|
-
let encrypted = cipher.update(text, 'utf8', 'hex');
|
|
744
|
-
encrypted += cipher.final('hex');
|
|
745
|
-
|
|
746
|
-
const authTag = cipher.getAuthTag();
|
|
747
|
-
|
|
748
|
-
return iv.toString('hex') + ':' + authTag.toString('hex') + ':' + encrypted;
|
|
749
|
-
}
|
|
750
|
-
```
|
|
751
|
-
|
|
752
|
-
**3. Injection**
|
|
753
|
-
```typescript
|
|
754
|
-
// Bad: SQL injection vulnerability
|
|
755
|
-
app.get('/api/users', async (req, res) => {
|
|
756
|
-
const name = req.query.name;
|
|
757
|
-
const users = await db.query(`SELECT * FROM users WHERE name = '${name}'`);
|
|
758
|
-
res.json(users);
|
|
759
|
-
});
|
|
760
|
-
|
|
761
|
-
// Good: Parameterized query
|
|
762
|
-
app.get('/api/users', async (req, res) => {
|
|
763
|
-
const name = req.query.name;
|
|
764
|
-
const users = await db.query(
|
|
765
|
-
'SELECT * FROM users WHERE name = $1',
|
|
766
|
-
[name]
|
|
767
|
-
);
|
|
768
|
-
res.json(users);
|
|
769
|
-
});
|
|
770
|
-
|
|
771
|
-
// Better: Use ORM with built-in protection
|
|
772
|
-
app.get('/api/users', async (req, res) => {
|
|
773
|
-
const name = req.query.name;
|
|
774
|
-
const users = await User.findAll({
|
|
775
|
-
where: { name }
|
|
776
|
-
});
|
|
777
|
-
res.json(users);
|
|
778
|
-
});
|
|
779
|
-
```
|
|
780
|
-
|
|
781
|
-
**4. Insecure Design**
|
|
782
|
-
```typescript
|
|
783
|
-
// Bad: Password reset without verification
|
|
784
|
-
app.post('/api/reset-password', async (req, res) => {
|
|
785
|
-
const { email, newPassword } = req.body;
|
|
786
|
-
|
|
787
|
-
const user = await userRepository.findByEmail(email);
|
|
788
|
-
if (user) {
|
|
789
|
-
await userRepository.updatePassword(user.id, newPassword);
|
|
790
|
-
}
|
|
791
|
-
|
|
792
|
-
res.json({ success: true });
|
|
793
|
-
});
|
|
794
|
-
|
|
795
|
-
// Good: Secure password reset flow
|
|
796
|
-
app.post('/api/request-password-reset', async (req, res) => {
|
|
797
|
-
const { email } = req.body;
|
|
798
|
-
|
|
799
|
-
const user = await userRepository.findByEmail(email);
|
|
800
|
-
if (user) {
|
|
801
|
-
// Generate secure token
|
|
802
|
-
const token = crypto.randomBytes(32).toString('hex');
|
|
803
|
-
const expires = new Date(Date.now() + 3600000); // 1 hour
|
|
804
|
-
|
|
805
|
-
await passwordResetRepository.create({
|
|
806
|
-
userId: user.id,
|
|
807
|
-
token: await bcrypt.hash(token, 10),
|
|
808
|
-
expires
|
|
809
|
-
});
|
|
810
|
-
|
|
811
|
-
// Send email with reset link
|
|
812
|
-
await emailService.sendPasswordResetEmail(user.email, token);
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
// Always return success to prevent email enumeration
|
|
816
|
-
res.json({ success: true });
|
|
817
|
-
});
|
|
818
|
-
|
|
819
|
-
app.post('/api/reset-password', async (req, res) => {
|
|
820
|
-
const { token, newPassword } = req.body;
|
|
821
|
-
|
|
822
|
-
const resetRequest = await passwordResetRepository.findByToken(token);
|
|
823
|
-
|
|
824
|
-
if (!resetRequest || resetRequest.expires < new Date()) {
|
|
825
|
-
res.status(400).json({ error: 'Invalid or expired token' });
|
|
826
|
-
return;
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
const isValid = await bcrypt.compare(token, resetRequest.token);
|
|
830
|
-
if (!isValid) {
|
|
831
|
-
res.status(400).json({ error: 'Invalid token' });
|
|
832
|
-
return;
|
|
833
|
-
}
|
|
834
|
-
|
|
835
|
-
await userRepository.updatePassword(resetRequest.userId, newPassword);
|
|
836
|
-
await passwordResetRepository.delete(resetRequest.id);
|
|
837
|
-
|
|
838
|
-
res.json({ success: true });
|
|
839
|
-
});
|
|
840
|
-
```
|
|
841
|
-
|
|
842
|
-
**5. Security Misconfiguration**
|
|
843
|
-
```typescript
|
|
844
|
-
// Bad: Exposing stack traces in production
|
|
845
|
-
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
|
|
846
|
-
res.status(500).json({
|
|
847
|
-
error: err.message,
|
|
848
|
-
stack: err.stack // Exposes internal details
|
|
849
|
-
});
|
|
850
|
-
});
|
|
851
|
-
|
|
852
|
-
// Good: Generic error messages in production
|
|
853
|
-
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
|
|
854
|
-
// Log full error for debugging
|
|
855
|
-
logger.error('Unhandled error', {
|
|
856
|
-
error: err.message,
|
|
857
|
-
stack: err.stack,
|
|
858
|
-
path: req.path,
|
|
859
|
-
method: req.method
|
|
860
|
-
});
|
|
861
|
-
|
|
862
|
-
// Return generic message to client
|
|
863
|
-
res.status(500).json({
|
|
864
|
-
error: process.env.NODE_ENV === 'production'
|
|
865
|
-
? 'Internal server error'
|
|
866
|
-
: err.message
|
|
867
|
-
});
|
|
868
|
-
});
|
|
869
|
-
|
|
870
|
-
// Security headers
|
|
871
|
-
import helmet from 'helmet';
|
|
872
|
-
|
|
873
|
-
app.use(helmet({
|
|
874
|
-
contentSecurityPolicy: {
|
|
875
|
-
directives: {
|
|
876
|
-
defaultSrc: ["'self'"],
|
|
877
|
-
styleSrc: ["'self'", "'unsafe-inline'"],
|
|
878
|
-
scriptSrc: ["'self'"],
|
|
879
|
-
imgSrc: ["'self'", 'data:', 'https:']
|
|
880
|
-
}
|
|
881
|
-
},
|
|
882
|
-
hsts: {
|
|
883
|
-
maxAge: 31536000,
|
|
884
|
-
includeSubDomains: true,
|
|
885
|
-
preload: true
|
|
886
|
-
}
|
|
887
|
-
}));
|
|
888
|
-
```
|
|
889
|
-
|
|
890
|
-
---
|
|
891
|
-
|
|
892
|
-
## Understanding
|
|
893
|
-
|
|
894
|
-
### Security Architecture Patterns
|
|
895
|
-
|
|
896
|
-
**API Gateway Pattern**
|
|
897
|
-
- Single entry point for all API requests
|
|
898
|
-
- Centralized authentication and authorization
|
|
899
|
-
- Rate limiting and throttling
|
|
900
|
-
- Request/response transformation
|
|
901
|
-
- Logging and monitoring
|
|
902
|
-
|
|
903
|
-
**Backend for Frontend (BFF) Pattern**
|
|
904
|
-
- Separate backend for each client type
|
|
905
|
-
- Tailored security policies per client
|
|
906
|
-
- Reduces over-fetching and under-fetching
|
|
907
|
-
- Client-specific authentication flows
|
|
908
|
-
|
|
909
|
-
**Sidecar Pattern**
|
|
910
|
-
- Security proxy alongside each service
|
|
911
|
-
- Handles authentication, encryption, logging
|
|
912
|
-
- Decouples security from business logic
|
|
913
|
-
- Common in service mesh architectures
|
|
914
|
-
|
|
915
|
-
### Security Testing
|
|
916
|
-
|
|
917
|
-
**Static Application Security Testing (SAST)**
|
|
918
|
-
- Analyze source code for vulnerabilities
|
|
919
|
-
- Find issues early in development
|
|
920
|
-
- Tools: SonarQube, Checkmarx, Fortify
|
|
921
|
-
|
|
922
|
-
**Dynamic Application Security Testing (DAST)**
|
|
923
|
-
- Test running application
|
|
924
|
-
- Find runtime vulnerabilities
|
|
925
|
-
- Tools: OWASP ZAP, Burp Suite, Acunetix
|
|
926
|
-
|
|
927
|
-
**Interactive Application Security Testing (IAST)**
|
|
928
|
-
- Combines SAST and DAST
|
|
929
|
-
- Real-time vulnerability detection
|
|
930
|
-
- Tools: Contrast Security, Seeker
|
|
931
|
-
|
|
932
|
-
**Penetration Testing**
|
|
933
|
-
- Simulated attacks by security experts
|
|
934
|
-
- Find vulnerabilities before attackers do
|
|
935
|
-
- Regular testing (quarterly, annually)
|
|
936
|
-
|
|
937
|
-
**Dependency Scanning**
|
|
938
|
-
- Check for vulnerable dependencies
|
|
939
|
-
- Automated scanning in CI/CD
|
|
940
|
-
- Tools: Snyk, Dependabot, npm audit
|
|
941
|
-
|
|
942
|
-
### Compliance and Standards
|
|
943
|
-
|
|
944
|
-
**Common Standards**
|
|
945
|
-
- **PCI DSS**: Payment Card Industry Data Security Standard
|
|
946
|
-
- **HIPAA**: Health Insurance Portability and Accountability Act
|
|
947
|
-
- **GDPR**: General Data Protection Regulation
|
|
948
|
-
- **SOC 2**: Service Organization Control 2
|
|
949
|
-
- **ISO 27001**: Information Security Management
|
|
950
|
-
|
|
951
|
-
**Compliance Requirements**
|
|
952
|
-
- Data encryption (at rest and in transit)
|
|
953
|
-
- Access controls and audit logging
|
|
954
|
-
- Incident response procedures
|
|
955
|
-
- Regular security assessments
|
|
956
|
-
- Data retention and deletion policies
|
|
957
|
-
|
|
958
|
-
### Best Practices
|
|
959
|
-
|
|
960
|
-
1. **Security by Design**
|
|
961
|
-
- Include security from the start
|
|
962
|
-
- Threat modeling in design phase
|
|
963
|
-
- Security requirements alongside functional requirements
|
|
964
|
-
|
|
965
|
-
2. **Principle of Least Privilege**
|
|
966
|
-
- Grant minimum necessary permissions
|
|
967
|
-
- Regular access reviews
|
|
968
|
-
- Just-in-time access for sensitive operations
|
|
969
|
-
|
|
970
|
-
3. **Defense in Depth**
|
|
971
|
-
- Multiple layers of security
|
|
972
|
-
- No single point of failure
|
|
973
|
-
- Assume each layer can be breached
|
|
974
|
-
|
|
975
|
-
4. **Secure Defaults**
|
|
976
|
-
- Deny by default, allow by exception
|
|
977
|
-
- Secure configuration out of the box
|
|
978
|
-
- Opt-in for risky features
|
|
979
|
-
|
|
980
|
-
5. **Keep Security Simple**
|
|
981
|
-
- Complex security is hard to maintain
|
|
982
|
-
- Prefer standard solutions over custom
|
|
983
|
-
- Document security decisions
|
|
984
|
-
|
|
985
|
-
6. **Continuous Monitoring**
|
|
986
|
-
- Real-time security monitoring
|
|
987
|
-
- Automated alerts for anomalies
|
|
988
|
-
- Regular security audits
|
|
989
|
-
|
|
990
|
-
7. **Incident Response Plan**
|
|
991
|
-
- Documented procedures
|
|
992
|
-
- Regular drills and updates
|
|
993
|
-
- Clear roles and responsibilities
|
|
994
|
-
|
|
995
|
-
### Common Pitfalls
|
|
996
|
-
|
|
997
|
-
1. **Security as an Afterthought**
|
|
998
|
-
- Adding security late is expensive
|
|
999
|
-
- Retrofitting is harder than building in
|
|
1000
|
-
- Security should be in initial requirements
|
|
1001
|
-
|
|
1002
|
-
2. **Trusting User Input**
|
|
1003
|
-
- All input is potentially malicious
|
|
1004
|
-
- Validate and sanitize everything
|
|
1005
|
-
- Never trust client-side validation alone
|
|
1006
|
-
|
|
1007
|
-
3. **Hardcoded Secrets**
|
|
1008
|
-
- Passwords, API keys in source code
|
|
1009
|
-
- Use environment variables or secret managers
|
|
1010
|
-
- Never commit secrets to version control
|
|
1011
|
-
|
|
1012
|
-
4. **Insufficient Logging**
|
|
1013
|
-
- Can't investigate what you don't log
|
|
1014
|
-
- Log security events comprehensively
|
|
1015
|
-
- Protect logs from tampering
|
|
1016
|
-
|
|
1017
|
-
5. **Ignoring Updates**
|
|
1018
|
-
- Unpatched vulnerabilities are common attack vector
|
|
1019
|
-
- Regular dependency updates
|
|
1020
|
-
- Automated vulnerability scanning
|
|
1021
|
-
|
|
1022
|
-
6. **Over-reliance on Obscurity**
|
|
1023
|
-
- Security through obscurity is not security
|
|
1024
|
-
- Assume attackers know your system
|
|
1025
|
-
- Use proven security mechanisms
|
|
1026
|
-
|
|
1027
|
-
---
|
|
1028
|
-
|
|
1029
|
-
## References
|
|
1030
|
-
|
|
1031
|
-
- **OWASP Top 10**: https://owasp.org/www-project-top-ten/
|
|
1032
|
-
- **OWASP ASVS**: Application Security Verification Standard
|
|
1033
|
-
- **NIST Cybersecurity Framework**: https://www.nist.gov/cyberframework
|
|
1034
|
-
- **Zero Trust Architecture**: NIST SP 800-207
|
|
1035
|
-
- **CWE Top 25**: Common Weakness Enumeration
|
|
1036
|
-
- **SANS Top 25**: Most Dangerous Software Errors
|
|
1037
|
-
- **ISO/IEC 27001**: Information Security Management
|
|
1038
|
-
- **PCI DSS**: Payment Card Industry Data Security Standard
|
|
1039
|
-
|
|
1
|
+
# Security Architecture
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
This document covers security architecture principles, patterns, and practices for building secure systems. Security must be designed into the architecture from the beginning, not added as an afterthought.
|
|
6
|
+
|
|
7
|
+
**References**: OWASP (Open Web Application Security Project), NIST Cybersecurity Framework, Zero Trust Architecture
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Knowledge
|
|
12
|
+
|
|
13
|
+
### Security Principles
|
|
14
|
+
|
|
15
|
+
#### Defense in Depth
|
|
16
|
+
|
|
17
|
+
**Definition**
|
|
18
|
+
- Multiple layers of security controls
|
|
19
|
+
- If one layer fails, others provide protection
|
|
20
|
+
- No single point of failure
|
|
21
|
+
- Comprehensive security strategy
|
|
22
|
+
|
|
23
|
+
**Layers**
|
|
24
|
+
1. **Physical Security**: Data center access, hardware security
|
|
25
|
+
2. **Network Security**: Firewalls, VPNs, network segmentation
|
|
26
|
+
3. **Host Security**: OS hardening, antivirus, host firewalls
|
|
27
|
+
4. **Application Security**: Input validation, authentication, authorization
|
|
28
|
+
5. **Data Security**: Encryption, access controls, data masking
|
|
29
|
+
|
|
30
|
+
**Benefits**
|
|
31
|
+
- Reduces risk of complete compromise
|
|
32
|
+
- Provides multiple opportunities to detect attacks
|
|
33
|
+
- Limits blast radius of security incidents
|
|
34
|
+
- Supports compliance requirements
|
|
35
|
+
|
|
36
|
+
#### Least Privilege
|
|
37
|
+
|
|
38
|
+
**Definition**
|
|
39
|
+
- Grant minimum permissions necessary to perform a task
|
|
40
|
+
- Users and services should have only required access
|
|
41
|
+
- Reduces attack surface and blast radius
|
|
42
|
+
- Principle of minimal authority
|
|
43
|
+
|
|
44
|
+
**Application**
|
|
45
|
+
- User permissions (RBAC, ABAC)
|
|
46
|
+
- Service accounts (minimal IAM roles)
|
|
47
|
+
- Database access (read-only where possible)
|
|
48
|
+
- API access (scoped tokens)
|
|
49
|
+
- File system permissions
|
|
50
|
+
|
|
51
|
+
**Benefits**
|
|
52
|
+
- Limits damage from compromised accounts
|
|
53
|
+
- Reduces insider threat risk
|
|
54
|
+
- Simplifies access auditing
|
|
55
|
+
- Supports compliance (SOC 2, ISO 27001)
|
|
56
|
+
|
|
57
|
+
#### Fail Securely
|
|
58
|
+
|
|
59
|
+
**Definition**
|
|
60
|
+
- System should fail in a secure state
|
|
61
|
+
- Errors should not expose sensitive information
|
|
62
|
+
- Default to deny access on failure
|
|
63
|
+
- Graceful degradation without security compromise
|
|
64
|
+
|
|
65
|
+
**Practices**
|
|
66
|
+
- Default deny (whitelist, not blacklist)
|
|
67
|
+
- Generic error messages (no sensitive details)
|
|
68
|
+
- Secure defaults (opt-in for risky features)
|
|
69
|
+
- Fail closed (deny access on auth failure)
|
|
70
|
+
|
|
71
|
+
#### Zero Trust Architecture
|
|
72
|
+
|
|
73
|
+
**Definition**
|
|
74
|
+
- Never trust, always verify
|
|
75
|
+
- No implicit trust based on network location
|
|
76
|
+
- Verify every request, every time
|
|
77
|
+
- Assume breach mentality
|
|
78
|
+
|
|
79
|
+
**Principles**
|
|
80
|
+
1. **Verify explicitly**: Always authenticate and authorize
|
|
81
|
+
2. **Use least privilege access**: Just-in-time and just-enough-access
|
|
82
|
+
3. **Assume breach**: Minimize blast radius, segment access
|
|
83
|
+
|
|
84
|
+
**Components**
|
|
85
|
+
- Identity and access management (IAM)
|
|
86
|
+
- Multi-factor authentication (MFA)
|
|
87
|
+
- Micro-segmentation
|
|
88
|
+
- Continuous monitoring and validation
|
|
89
|
+
- Encryption everywhere
|
|
90
|
+
|
|
91
|
+
### Threat Modeling
|
|
92
|
+
|
|
93
|
+
**Definition**
|
|
94
|
+
- Systematic approach to identifying security threats
|
|
95
|
+
- Analyze system to find vulnerabilities
|
|
96
|
+
- Prioritize threats by risk
|
|
97
|
+
- Design mitigations
|
|
98
|
+
|
|
99
|
+
**STRIDE Model**
|
|
100
|
+
|
|
101
|
+
- **S**poofing: Impersonating user or system
|
|
102
|
+
- **T**ampering: Modifying data or code
|
|
103
|
+
- **R**epudiation: Denying actions
|
|
104
|
+
- **I**nformation Disclosure: Exposing sensitive data
|
|
105
|
+
- **D**enial of Service: Making system unavailable
|
|
106
|
+
- **E**levation of Privilege: Gaining unauthorized access
|
|
107
|
+
|
|
108
|
+
**Threat Modeling Process**
|
|
109
|
+
|
|
110
|
+
1. **Identify Assets**: What needs protection?
|
|
111
|
+
2. **Create Architecture Overview**: Data flow diagrams
|
|
112
|
+
3. **Identify Threats**: Use STRIDE or other framework
|
|
113
|
+
4. **Mitigate Threats**: Design security controls
|
|
114
|
+
5. **Validate**: Review and test mitigations
|
|
115
|
+
|
|
116
|
+
**Tools**
|
|
117
|
+
- Microsoft Threat Modeling Tool
|
|
118
|
+
- OWASP Threat Dragon
|
|
119
|
+
- IriusRisk
|
|
120
|
+
- ThreatModeler
|
|
121
|
+
|
|
122
|
+
### Authentication
|
|
123
|
+
|
|
124
|
+
**Definition**
|
|
125
|
+
- Verifying identity of user or system
|
|
126
|
+
- "Who are you?"
|
|
127
|
+
- Foundation of access control
|
|
128
|
+
- Multiple factors increase security
|
|
129
|
+
|
|
130
|
+
**Authentication Factors**
|
|
131
|
+
|
|
132
|
+
1. **Something You Know**: Password, PIN, security question
|
|
133
|
+
2. **Something You Have**: Phone, hardware token, smart card
|
|
134
|
+
3. **Something You Are**: Biometrics (fingerprint, face, iris)
|
|
135
|
+
|
|
136
|
+
**Multi-Factor Authentication (MFA)**
|
|
137
|
+
- Combines two or more factors
|
|
138
|
+
- Significantly increases security
|
|
139
|
+
- Protects against password compromise
|
|
140
|
+
- Industry best practice
|
|
141
|
+
|
|
142
|
+
**Authentication Protocols**
|
|
143
|
+
|
|
144
|
+
- **OAuth 2.0**: Authorization framework for delegated access
|
|
145
|
+
- **OpenID Connect**: Identity layer on top of OAuth 2.0
|
|
146
|
+
- **SAML**: XML-based authentication and authorization
|
|
147
|
+
- **JWT**: JSON Web Tokens for stateless authentication
|
|
148
|
+
|
|
149
|
+
**Best Practices**
|
|
150
|
+
- Enforce strong password policies
|
|
151
|
+
- Implement MFA for sensitive operations
|
|
152
|
+
- Use secure password storage (bcrypt, Argon2)
|
|
153
|
+
- Implement account lockout after failed attempts
|
|
154
|
+
- Use HTTPS for credential transmission
|
|
155
|
+
- Implement session timeout
|
|
156
|
+
|
|
157
|
+
### Authorization
|
|
158
|
+
|
|
159
|
+
**Definition**
|
|
160
|
+
- Determining what authenticated user can do
|
|
161
|
+
- "What are you allowed to do?"
|
|
162
|
+
- Access control and permissions
|
|
163
|
+
- Enforces security policies
|
|
164
|
+
|
|
165
|
+
**Authorization Models**
|
|
166
|
+
|
|
167
|
+
#### Role-Based Access Control (RBAC)
|
|
168
|
+
|
|
169
|
+
**Definition**
|
|
170
|
+
- Permissions assigned to roles
|
|
171
|
+
- Users assigned to roles
|
|
172
|
+
- Simplifies permission management
|
|
173
|
+
- Common in enterprise systems
|
|
174
|
+
|
|
175
|
+
**Example**
|
|
176
|
+
```
|
|
177
|
+
Roles: Admin, Manager, User
|
|
178
|
+
Admin: All permissions
|
|
179
|
+
Manager: Read, Write, Delete (own resources)
|
|
180
|
+
User: Read, Write (own resources)
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
**Benefits**
|
|
184
|
+
- Easy to understand and manage
|
|
185
|
+
- Scales well for large organizations
|
|
186
|
+
- Supports separation of duties
|
|
187
|
+
- Simplifies auditing
|
|
188
|
+
|
|
189
|
+
#### Attribute-Based Access Control (ABAC)
|
|
190
|
+
|
|
191
|
+
**Definition**
|
|
192
|
+
- Permissions based on attributes
|
|
193
|
+
- User attributes, resource attributes, environment attributes
|
|
194
|
+
- Fine-grained, dynamic access control
|
|
195
|
+
- Flexible and expressive
|
|
196
|
+
|
|
197
|
+
**Example**
|
|
198
|
+
```
|
|
199
|
+
Allow if:
|
|
200
|
+
user.department == resource.department AND
|
|
201
|
+
user.clearance >= resource.classification AND
|
|
202
|
+
time.hour >= 9 AND time.hour <= 17
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
**Benefits**
|
|
206
|
+
- Fine-grained control
|
|
207
|
+
- Dynamic policies
|
|
208
|
+
- Context-aware decisions
|
|
209
|
+
- Reduces role explosion
|
|
210
|
+
|
|
211
|
+
#### Policy-Based Access Control
|
|
212
|
+
|
|
213
|
+
**Definition**
|
|
214
|
+
- Centralized policy engine
|
|
215
|
+
- Policies written in declarative language
|
|
216
|
+
- Separates policy from code
|
|
217
|
+
- Examples: OPA (Open Policy Agent), AWS IAM Policies
|
|
218
|
+
|
|
219
|
+
**Benefits**
|
|
220
|
+
- Centralized policy management
|
|
221
|
+
- Auditable policies
|
|
222
|
+
- Testable policies
|
|
223
|
+
- Reusable across services
|
|
224
|
+
|
|
225
|
+
### Encryption
|
|
226
|
+
|
|
227
|
+
**Definition**
|
|
228
|
+
- Converting data to unreadable format
|
|
229
|
+
- Protects confidentiality
|
|
230
|
+
- Two main types: symmetric and asymmetric
|
|
231
|
+
- Essential for data protection
|
|
232
|
+
|
|
233
|
+
**Encryption at Rest**
|
|
234
|
+
- Protects stored data
|
|
235
|
+
- Database encryption (TDE)
|
|
236
|
+
- File system encryption
|
|
237
|
+
- Disk encryption
|
|
238
|
+
- Key management critical
|
|
239
|
+
|
|
240
|
+
**Encryption in Transit**
|
|
241
|
+
- Protects data during transmission
|
|
242
|
+
- TLS/SSL for HTTPS
|
|
243
|
+
- VPNs for network traffic
|
|
244
|
+
- Encrypted messaging protocols
|
|
245
|
+
- Certificate management
|
|
246
|
+
|
|
247
|
+
**Key Management**
|
|
248
|
+
- Secure key generation
|
|
249
|
+
- Key rotation policies
|
|
250
|
+
- Key storage (HSM, KMS)
|
|
251
|
+
- Key access controls
|
|
252
|
+
- Key backup and recovery
|
|
253
|
+
|
|
254
|
+
**Best Practices**
|
|
255
|
+
- Use strong algorithms (AES-256, RSA-2048+)
|
|
256
|
+
- Never roll your own crypto
|
|
257
|
+
- Use TLS 1.2 or higher
|
|
258
|
+
- Implement perfect forward secrecy
|
|
259
|
+
- Rotate keys regularly
|
|
260
|
+
- Use hardware security modules (HSM) for key storage
|
|
261
|
+
|
|
262
|
+
### Secure Communication
|
|
263
|
+
|
|
264
|
+
**TLS/SSL**
|
|
265
|
+
- Transport Layer Security
|
|
266
|
+
- Encrypts data in transit
|
|
267
|
+
- Provides authentication and integrity
|
|
268
|
+
- Essential for web applications
|
|
269
|
+
|
|
270
|
+
**Certificate Management**
|
|
271
|
+
- Use trusted Certificate Authorities (CA)
|
|
272
|
+
- Implement certificate pinning for mobile apps
|
|
273
|
+
- Monitor certificate expiration
|
|
274
|
+
- Use automated certificate renewal (Let's Encrypt)
|
|
275
|
+
|
|
276
|
+
**API Security**
|
|
277
|
+
- API keys for identification
|
|
278
|
+
- OAuth 2.0 for authorization
|
|
279
|
+
- Rate limiting and throttling
|
|
280
|
+
- Input validation and sanitization
|
|
281
|
+
- CORS policies
|
|
282
|
+
|
|
283
|
+
### Input Validation and Sanitization
|
|
284
|
+
|
|
285
|
+
**Definition**
|
|
286
|
+
- Validate all input from untrusted sources
|
|
287
|
+
- Sanitize data before use
|
|
288
|
+
- Prevent injection attacks
|
|
289
|
+
- Defense against OWASP Top 10 vulnerabilities
|
|
290
|
+
|
|
291
|
+
**Validation Strategies**
|
|
292
|
+
- Whitelist (allow known good)
|
|
293
|
+
- Blacklist (deny known bad) - less secure
|
|
294
|
+
- Type checking and constraints
|
|
295
|
+
- Length and format validation
|
|
296
|
+
- Business logic validation
|
|
297
|
+
|
|
298
|
+
**Common Injection Attacks**
|
|
299
|
+
|
|
300
|
+
**SQL Injection**
|
|
301
|
+
- Malicious SQL in user input
|
|
302
|
+
- Can read, modify, or delete data
|
|
303
|
+
- Prevention: Parameterized queries, ORMs
|
|
304
|
+
|
|
305
|
+
**Cross-Site Scripting (XSS)**
|
|
306
|
+
- Malicious scripts in web pages
|
|
307
|
+
- Can steal cookies, session tokens
|
|
308
|
+
- Prevention: Output encoding, CSP headers
|
|
309
|
+
|
|
310
|
+
**Command Injection**
|
|
311
|
+
- Malicious commands in system calls
|
|
312
|
+
- Can execute arbitrary code
|
|
313
|
+
- Prevention: Avoid system calls, input validation
|
|
314
|
+
|
|
315
|
+
**LDAP Injection**
|
|
316
|
+
- Malicious LDAP queries
|
|
317
|
+
- Can bypass authentication
|
|
318
|
+
- Prevention: Input validation, parameterized queries
|
|
319
|
+
|
|
320
|
+
### Audit Logging
|
|
321
|
+
|
|
322
|
+
**Definition**
|
|
323
|
+
- Record security-relevant events
|
|
324
|
+
- Support forensics and compliance
|
|
325
|
+
- Detect and investigate incidents
|
|
326
|
+
- Non-repudiation
|
|
327
|
+
|
|
328
|
+
**What to Log**
|
|
329
|
+
- Authentication events (success, failure)
|
|
330
|
+
- Authorization failures
|
|
331
|
+
- Data access (especially sensitive data)
|
|
332
|
+
- Configuration changes
|
|
333
|
+
- Administrative actions
|
|
334
|
+
- Security events (attacks, anomalies)
|
|
335
|
+
|
|
336
|
+
**Log Content**
|
|
337
|
+
- Timestamp (UTC)
|
|
338
|
+
- User/service identity
|
|
339
|
+
- Action performed
|
|
340
|
+
- Resource accessed
|
|
341
|
+
- Result (success/failure)
|
|
342
|
+
- Source IP address
|
|
343
|
+
- Session ID
|
|
344
|
+
|
|
345
|
+
**Best Practices**
|
|
346
|
+
- Log to centralized system (SIEM)
|
|
347
|
+
- Protect logs from tampering
|
|
348
|
+
- Retain logs per compliance requirements
|
|
349
|
+
- Monitor logs for anomalies
|
|
350
|
+
- Never log sensitive data (passwords, credit cards)
|
|
351
|
+
- Use structured logging (JSON)
|
|
352
|
+
|
|
353
|
+
---
|
|
354
|
+
|
|
355
|
+
## Skills
|
|
356
|
+
|
|
357
|
+
### Implementing Authentication
|
|
358
|
+
|
|
359
|
+
**JWT-Based Authentication**
|
|
360
|
+
|
|
361
|
+
**Token Structure**
|
|
362
|
+
- Header: Algorithm and token type
|
|
363
|
+
- Payload: Claims (user ID, roles, expiration)
|
|
364
|
+
- Signature: Verify token integrity
|
|
365
|
+
|
|
366
|
+
**Best Practices**
|
|
367
|
+
- Use short expiration times (15 minutes)
|
|
368
|
+
- Implement refresh tokens
|
|
369
|
+
- Store tokens securely (httpOnly cookies)
|
|
370
|
+
- Validate signature on every request
|
|
371
|
+
- Include audience and issuer claims
|
|
372
|
+
- Use strong signing algorithms (RS256, ES256)
|
|
373
|
+
|
|
374
|
+
**Session Management**
|
|
375
|
+
- Generate cryptographically random session IDs
|
|
376
|
+
- Set secure and httpOnly flags on cookies
|
|
377
|
+
- Implement session timeout
|
|
378
|
+
- Invalidate sessions on logout
|
|
379
|
+
- Regenerate session ID after authentication
|
|
380
|
+
|
|
381
|
+
### Implementing Authorization
|
|
382
|
+
|
|
383
|
+
**RBAC Implementation**
|
|
384
|
+
|
|
385
|
+
**Database Schema**
|
|
386
|
+
```sql
|
|
387
|
+
CREATE TABLE users (
|
|
388
|
+
id UUID PRIMARY KEY,
|
|
389
|
+
email VARCHAR(255) UNIQUE NOT NULL,
|
|
390
|
+
password_hash VARCHAR(255) NOT NULL
|
|
391
|
+
);
|
|
392
|
+
|
|
393
|
+
CREATE TABLE roles (
|
|
394
|
+
id UUID PRIMARY KEY,
|
|
395
|
+
name VARCHAR(50) UNIQUE NOT NULL
|
|
396
|
+
);
|
|
397
|
+
|
|
398
|
+
CREATE TABLE permissions (
|
|
399
|
+
id UUID PRIMARY KEY,
|
|
400
|
+
name VARCHAR(100) UNIQUE NOT NULL,
|
|
401
|
+
resource VARCHAR(50) NOT NULL,
|
|
402
|
+
action VARCHAR(50) NOT NULL
|
|
403
|
+
);
|
|
404
|
+
|
|
405
|
+
CREATE TABLE user_roles (
|
|
406
|
+
user_id UUID REFERENCES users(id),
|
|
407
|
+
role_id UUID REFERENCES roles(id),
|
|
408
|
+
PRIMARY KEY (user_id, role_id)
|
|
409
|
+
);
|
|
410
|
+
|
|
411
|
+
CREATE TABLE role_permissions (
|
|
412
|
+
role_id UUID REFERENCES roles(id),
|
|
413
|
+
permission_id UUID REFERENCES permissions(id),
|
|
414
|
+
PRIMARY KEY (role_id, permission_id)
|
|
415
|
+
);
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
**Authorization Check**
|
|
419
|
+
```typescript
|
|
420
|
+
async function checkPermission(
|
|
421
|
+
userId: string,
|
|
422
|
+
resource: string,
|
|
423
|
+
action: string
|
|
424
|
+
): Promise<boolean> {
|
|
425
|
+
const result = await db.query(`
|
|
426
|
+
SELECT COUNT(*) as count
|
|
427
|
+
FROM users u
|
|
428
|
+
JOIN user_roles ur ON u.id = ur.user_id
|
|
429
|
+
JOIN role_permissions rp ON ur.role_id = rp.role_id
|
|
430
|
+
JOIN permissions p ON rp.permission_id = p.id
|
|
431
|
+
WHERE u.id = $1
|
|
432
|
+
AND p.resource = $2
|
|
433
|
+
AND p.action = $3
|
|
434
|
+
`, [userId, resource, action]);
|
|
435
|
+
|
|
436
|
+
return result.rows[0].count > 0;
|
|
437
|
+
}
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
### Implementing Secure Password Storage
|
|
441
|
+
|
|
442
|
+
**Password Hashing**
|
|
443
|
+
```typescript
|
|
444
|
+
import bcrypt from 'bcrypt';
|
|
445
|
+
|
|
446
|
+
// Hash password during registration
|
|
447
|
+
async function hashPassword(password: string): Promise<string> {
|
|
448
|
+
const saltRounds = 10; // Cost factor
|
|
449
|
+
return bcrypt.hash(password, saltRounds);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// Verify password during login
|
|
453
|
+
async function verifyPassword(
|
|
454
|
+
password: string,
|
|
455
|
+
hash: string
|
|
456
|
+
): Promise<boolean> {
|
|
457
|
+
return bcrypt.compare(password, hash);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// Example usage
|
|
461
|
+
class AuthService {
|
|
462
|
+
async register(email: string, password: string): Promise<User> {
|
|
463
|
+
// Validate password strength
|
|
464
|
+
if (password.length < 8) {
|
|
465
|
+
throw new Error('Password must be at least 8 characters');
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const passwordHash = await hashPassword(password);
|
|
469
|
+
|
|
470
|
+
return this.userRepository.create({
|
|
471
|
+
email,
|
|
472
|
+
passwordHash
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
async login(email: string, password: string): Promise<string> {
|
|
477
|
+
const user = await this.userRepository.findByEmail(email);
|
|
478
|
+
|
|
479
|
+
if (!user) {
|
|
480
|
+
throw new Error('Invalid credentials');
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
const isValid = await verifyPassword(password, user.passwordHash);
|
|
484
|
+
|
|
485
|
+
if (!isValid) {
|
|
486
|
+
throw new Error('Invalid credentials');
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// Generate JWT token
|
|
490
|
+
return this.generateToken(user);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
```
|
|
494
|
+
|
|
495
|
+
### Implementing Rate Limiting
|
|
496
|
+
|
|
497
|
+
**Token Bucket Algorithm**
|
|
498
|
+
```typescript
|
|
499
|
+
interface RateLimitConfig {
|
|
500
|
+
maxTokens: number; // Bucket capacity
|
|
501
|
+
refillRate: number; // Tokens per second
|
|
502
|
+
windowMs: number; // Time window
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
class RateLimiter {
|
|
506
|
+
private buckets = new Map<string, TokenBucket>();
|
|
507
|
+
|
|
508
|
+
constructor(private config: RateLimitConfig) {}
|
|
509
|
+
|
|
510
|
+
async checkLimit(key: string): Promise<boolean> {
|
|
511
|
+
let bucket = this.buckets.get(key);
|
|
512
|
+
|
|
513
|
+
if (!bucket) {
|
|
514
|
+
bucket = new TokenBucket(
|
|
515
|
+
this.config.maxTokens,
|
|
516
|
+
this.config.refillRate
|
|
517
|
+
);
|
|
518
|
+
this.buckets.set(key, bucket);
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
return bucket.consume();
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
class TokenBucket {
|
|
526
|
+
private tokens: number;
|
|
527
|
+
private lastRefill: number;
|
|
528
|
+
|
|
529
|
+
constructor(
|
|
530
|
+
private capacity: number,
|
|
531
|
+
private refillRate: number
|
|
532
|
+
) {
|
|
533
|
+
this.tokens = capacity;
|
|
534
|
+
this.lastRefill = Date.now();
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
consume(): boolean {
|
|
538
|
+
this.refill();
|
|
539
|
+
|
|
540
|
+
if (this.tokens >= 1) {
|
|
541
|
+
this.tokens -= 1;
|
|
542
|
+
return true;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
return false;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
private refill(): void {
|
|
549
|
+
const now = Date.now();
|
|
550
|
+
const timePassed = (now - this.lastRefill) / 1000;
|
|
551
|
+
const tokensToAdd = timePassed * this.refillRate;
|
|
552
|
+
|
|
553
|
+
this.tokens = Math.min(
|
|
554
|
+
this.capacity,
|
|
555
|
+
this.tokens + tokensToAdd
|
|
556
|
+
);
|
|
557
|
+
this.lastRefill = now;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// Express middleware
|
|
562
|
+
function rateLimitMiddleware(limiter: RateLimiter) {
|
|
563
|
+
return async (req: Request, res: Response, next: NextFunction) => {
|
|
564
|
+
const key = req.ip || req.socket.remoteAddress || 'unknown';
|
|
565
|
+
|
|
566
|
+
const allowed = await limiter.checkLimit(key);
|
|
567
|
+
|
|
568
|
+
if (!allowed) {
|
|
569
|
+
res.status(429).json({
|
|
570
|
+
error: 'Too many requests'
|
|
571
|
+
});
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
next();
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
```
|
|
579
|
+
|
|
580
|
+
---
|
|
581
|
+
|
|
582
|
+
## Examples
|
|
583
|
+
|
|
584
|
+
### Zero Trust Architecture Implementation
|
|
585
|
+
|
|
586
|
+
**Service-to-Service Authentication**
|
|
587
|
+
```typescript
|
|
588
|
+
// Service A calling Service B
|
|
589
|
+
class ServiceClient {
|
|
590
|
+
constructor(
|
|
591
|
+
private serviceUrl: string,
|
|
592
|
+
private clientId: string,
|
|
593
|
+
private clientSecret: string
|
|
594
|
+
) {}
|
|
595
|
+
|
|
596
|
+
async callService(endpoint: string, data: any): Promise<any> {
|
|
597
|
+
// Get access token
|
|
598
|
+
const token = await this.getAccessToken();
|
|
599
|
+
|
|
600
|
+
// Make authenticated request
|
|
601
|
+
const response = await fetch(`${this.serviceUrl}${endpoint}`, {
|
|
602
|
+
method: 'POST',
|
|
603
|
+
headers: {
|
|
604
|
+
'Authorization': `Bearer ${token}`,
|
|
605
|
+
'Content-Type': 'application/json'
|
|
606
|
+
},
|
|
607
|
+
body: JSON.stringify(data)
|
|
608
|
+
});
|
|
609
|
+
|
|
610
|
+
if (!response.ok) {
|
|
611
|
+
throw new Error(`Service call failed: ${response.statusText}`);
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
return response.json();
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
private async getAccessToken(): Promise<string> {
|
|
618
|
+
// OAuth 2.0 Client Credentials flow
|
|
619
|
+
const response = await fetch('https://auth.example.com/token', {
|
|
620
|
+
method: 'POST',
|
|
621
|
+
headers: {
|
|
622
|
+
'Content-Type': 'application/x-www-form-urlencoded'
|
|
623
|
+
},
|
|
624
|
+
body: new URLSearchParams({
|
|
625
|
+
grant_type: 'client_credentials',
|
|
626
|
+
client_id: this.clientId,
|
|
627
|
+
client_secret: this.clientSecret,
|
|
628
|
+
scope: 'service-b:read service-b:write'
|
|
629
|
+
})
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
const data = await response.json();
|
|
633
|
+
return data.access_token;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// Service B validating requests
|
|
638
|
+
class AuthMiddleware {
|
|
639
|
+
async validateToken(req: Request, res: Response, next: NextFunction) {
|
|
640
|
+
const authHeader = req.headers.authorization;
|
|
641
|
+
|
|
642
|
+
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
643
|
+
res.status(401).json({ error: 'Missing or invalid authorization header' });
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
const token = authHeader.substring(7);
|
|
648
|
+
|
|
649
|
+
try {
|
|
650
|
+
// Validate token with auth service
|
|
651
|
+
const tokenInfo = await this.validateWithAuthService(token);
|
|
652
|
+
|
|
653
|
+
// Check required scopes
|
|
654
|
+
if (!this.hasRequiredScopes(tokenInfo.scopes, req.path, req.method)) {
|
|
655
|
+
res.status(403).json({ error: 'Insufficient permissions' });
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// Attach token info to request
|
|
660
|
+
(req as any).auth = tokenInfo;
|
|
661
|
+
next();
|
|
662
|
+
} catch (error) {
|
|
663
|
+
res.status(401).json({ error: 'Invalid token' });
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
private async validateWithAuthService(token: string): Promise<TokenInfo> {
|
|
668
|
+
const response = await fetch('https://auth.example.com/validate', {
|
|
669
|
+
headers: {
|
|
670
|
+
'Authorization': `Bearer ${token}`
|
|
671
|
+
}
|
|
672
|
+
});
|
|
673
|
+
|
|
674
|
+
if (!response.ok) {
|
|
675
|
+
throw new Error('Token validation failed');
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
return response.json();
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
private hasRequiredScopes(
|
|
682
|
+
scopes: string[],
|
|
683
|
+
path: string,
|
|
684
|
+
method: string
|
|
685
|
+
): boolean {
|
|
686
|
+
// Check if token has required scopes for this endpoint
|
|
687
|
+
const requiredScope = `service-b:${method.toLowerCase()}`;
|
|
688
|
+
return scopes.includes(requiredScope);
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
```
|
|
692
|
+
|
|
693
|
+
### OWASP Top 10 Mitigations
|
|
694
|
+
|
|
695
|
+
**1. Broken Access Control**
|
|
696
|
+
```typescript
|
|
697
|
+
// Bad: No authorization check
|
|
698
|
+
app.delete('/api/users/:id', async (req, res) => {
|
|
699
|
+
await userRepository.delete(req.params.id);
|
|
700
|
+
res.json({ success: true });
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
// Good: Check authorization
|
|
704
|
+
app.delete('/api/users/:id', authenticate, async (req, res) => {
|
|
705
|
+
const currentUser = (req as any).user;
|
|
706
|
+
const targetUserId = req.params.id;
|
|
707
|
+
|
|
708
|
+
// Users can only delete their own account, or admin can delete any
|
|
709
|
+
if (currentUser.id !== targetUserId && !currentUser.roles.includes('admin')) {
|
|
710
|
+
res.status(403).json({ error: 'Forbidden' });
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
await userRepository.delete(targetUserId);
|
|
715
|
+
res.json({ success: true });
|
|
716
|
+
});
|
|
717
|
+
```
|
|
718
|
+
|
|
719
|
+
**2. Cryptographic Failures**
|
|
720
|
+
```typescript
|
|
721
|
+
// Bad: Storing sensitive data in plain text
|
|
722
|
+
await db.query(
|
|
723
|
+
'INSERT INTO users (email, password, ssn) VALUES ($1, $2, $3)',
|
|
724
|
+
[email, password, ssn]
|
|
725
|
+
);
|
|
726
|
+
|
|
727
|
+
// Good: Hash passwords, encrypt sensitive data
|
|
728
|
+
import bcrypt from 'bcrypt';
|
|
729
|
+
import crypto from 'crypto';
|
|
730
|
+
|
|
731
|
+
const passwordHash = await bcrypt.hash(password, 10);
|
|
732
|
+
const ssnEncrypted = encrypt(ssn, process.env.ENCRYPTION_KEY!);
|
|
733
|
+
|
|
734
|
+
await db.query(
|
|
735
|
+
'INSERT INTO users (email, password_hash, ssn_encrypted) VALUES ($1, $2, $3)',
|
|
736
|
+
[email, passwordHash, ssnEncrypted]
|
|
737
|
+
);
|
|
738
|
+
|
|
739
|
+
function encrypt(text: string, key: string): string {
|
|
740
|
+
const iv = crypto.randomBytes(16);
|
|
741
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', Buffer.from(key, 'hex'), iv);
|
|
742
|
+
|
|
743
|
+
let encrypted = cipher.update(text, 'utf8', 'hex');
|
|
744
|
+
encrypted += cipher.final('hex');
|
|
745
|
+
|
|
746
|
+
const authTag = cipher.getAuthTag();
|
|
747
|
+
|
|
748
|
+
return iv.toString('hex') + ':' + authTag.toString('hex') + ':' + encrypted;
|
|
749
|
+
}
|
|
750
|
+
```
|
|
751
|
+
|
|
752
|
+
**3. Injection**
|
|
753
|
+
```typescript
|
|
754
|
+
// Bad: SQL injection vulnerability
|
|
755
|
+
app.get('/api/users', async (req, res) => {
|
|
756
|
+
const name = req.query.name;
|
|
757
|
+
const users = await db.query(`SELECT * FROM users WHERE name = '${name}'`);
|
|
758
|
+
res.json(users);
|
|
759
|
+
});
|
|
760
|
+
|
|
761
|
+
// Good: Parameterized query
|
|
762
|
+
app.get('/api/users', async (req, res) => {
|
|
763
|
+
const name = req.query.name;
|
|
764
|
+
const users = await db.query(
|
|
765
|
+
'SELECT * FROM users WHERE name = $1',
|
|
766
|
+
[name]
|
|
767
|
+
);
|
|
768
|
+
res.json(users);
|
|
769
|
+
});
|
|
770
|
+
|
|
771
|
+
// Better: Use ORM with built-in protection
|
|
772
|
+
app.get('/api/users', async (req, res) => {
|
|
773
|
+
const name = req.query.name;
|
|
774
|
+
const users = await User.findAll({
|
|
775
|
+
where: { name }
|
|
776
|
+
});
|
|
777
|
+
res.json(users);
|
|
778
|
+
});
|
|
779
|
+
```
|
|
780
|
+
|
|
781
|
+
**4. Insecure Design**
|
|
782
|
+
```typescript
|
|
783
|
+
// Bad: Password reset without verification
|
|
784
|
+
app.post('/api/reset-password', async (req, res) => {
|
|
785
|
+
const { email, newPassword } = req.body;
|
|
786
|
+
|
|
787
|
+
const user = await userRepository.findByEmail(email);
|
|
788
|
+
if (user) {
|
|
789
|
+
await userRepository.updatePassword(user.id, newPassword);
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
res.json({ success: true });
|
|
793
|
+
});
|
|
794
|
+
|
|
795
|
+
// Good: Secure password reset flow
|
|
796
|
+
app.post('/api/request-password-reset', async (req, res) => {
|
|
797
|
+
const { email } = req.body;
|
|
798
|
+
|
|
799
|
+
const user = await userRepository.findByEmail(email);
|
|
800
|
+
if (user) {
|
|
801
|
+
// Generate secure token
|
|
802
|
+
const token = crypto.randomBytes(32).toString('hex');
|
|
803
|
+
const expires = new Date(Date.now() + 3600000); // 1 hour
|
|
804
|
+
|
|
805
|
+
await passwordResetRepository.create({
|
|
806
|
+
userId: user.id,
|
|
807
|
+
token: await bcrypt.hash(token, 10),
|
|
808
|
+
expires
|
|
809
|
+
});
|
|
810
|
+
|
|
811
|
+
// Send email with reset link
|
|
812
|
+
await emailService.sendPasswordResetEmail(user.email, token);
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
// Always return success to prevent email enumeration
|
|
816
|
+
res.json({ success: true });
|
|
817
|
+
});
|
|
818
|
+
|
|
819
|
+
app.post('/api/reset-password', async (req, res) => {
|
|
820
|
+
const { token, newPassword } = req.body;
|
|
821
|
+
|
|
822
|
+
const resetRequest = await passwordResetRepository.findByToken(token);
|
|
823
|
+
|
|
824
|
+
if (!resetRequest || resetRequest.expires < new Date()) {
|
|
825
|
+
res.status(400).json({ error: 'Invalid or expired token' });
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
const isValid = await bcrypt.compare(token, resetRequest.token);
|
|
830
|
+
if (!isValid) {
|
|
831
|
+
res.status(400).json({ error: 'Invalid token' });
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
await userRepository.updatePassword(resetRequest.userId, newPassword);
|
|
836
|
+
await passwordResetRepository.delete(resetRequest.id);
|
|
837
|
+
|
|
838
|
+
res.json({ success: true });
|
|
839
|
+
});
|
|
840
|
+
```
|
|
841
|
+
|
|
842
|
+
**5. Security Misconfiguration**
|
|
843
|
+
```typescript
|
|
844
|
+
// Bad: Exposing stack traces in production
|
|
845
|
+
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
|
|
846
|
+
res.status(500).json({
|
|
847
|
+
error: err.message,
|
|
848
|
+
stack: err.stack // Exposes internal details
|
|
849
|
+
});
|
|
850
|
+
});
|
|
851
|
+
|
|
852
|
+
// Good: Generic error messages in production
|
|
853
|
+
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
|
|
854
|
+
// Log full error for debugging
|
|
855
|
+
logger.error('Unhandled error', {
|
|
856
|
+
error: err.message,
|
|
857
|
+
stack: err.stack,
|
|
858
|
+
path: req.path,
|
|
859
|
+
method: req.method
|
|
860
|
+
});
|
|
861
|
+
|
|
862
|
+
// Return generic message to client
|
|
863
|
+
res.status(500).json({
|
|
864
|
+
error: process.env.NODE_ENV === 'production'
|
|
865
|
+
? 'Internal server error'
|
|
866
|
+
: err.message
|
|
867
|
+
});
|
|
868
|
+
});
|
|
869
|
+
|
|
870
|
+
// Security headers
|
|
871
|
+
import helmet from 'helmet';
|
|
872
|
+
|
|
873
|
+
app.use(helmet({
|
|
874
|
+
contentSecurityPolicy: {
|
|
875
|
+
directives: {
|
|
876
|
+
defaultSrc: ["'self'"],
|
|
877
|
+
styleSrc: ["'self'", "'unsafe-inline'"],
|
|
878
|
+
scriptSrc: ["'self'"],
|
|
879
|
+
imgSrc: ["'self'", 'data:', 'https:']
|
|
880
|
+
}
|
|
881
|
+
},
|
|
882
|
+
hsts: {
|
|
883
|
+
maxAge: 31536000,
|
|
884
|
+
includeSubDomains: true,
|
|
885
|
+
preload: true
|
|
886
|
+
}
|
|
887
|
+
}));
|
|
888
|
+
```
|
|
889
|
+
|
|
890
|
+
---
|
|
891
|
+
|
|
892
|
+
## Understanding
|
|
893
|
+
|
|
894
|
+
### Security Architecture Patterns
|
|
895
|
+
|
|
896
|
+
**API Gateway Pattern**
|
|
897
|
+
- Single entry point for all API requests
|
|
898
|
+
- Centralized authentication and authorization
|
|
899
|
+
- Rate limiting and throttling
|
|
900
|
+
- Request/response transformation
|
|
901
|
+
- Logging and monitoring
|
|
902
|
+
|
|
903
|
+
**Backend for Frontend (BFF) Pattern**
|
|
904
|
+
- Separate backend for each client type
|
|
905
|
+
- Tailored security policies per client
|
|
906
|
+
- Reduces over-fetching and under-fetching
|
|
907
|
+
- Client-specific authentication flows
|
|
908
|
+
|
|
909
|
+
**Sidecar Pattern**
|
|
910
|
+
- Security proxy alongside each service
|
|
911
|
+
- Handles authentication, encryption, logging
|
|
912
|
+
- Decouples security from business logic
|
|
913
|
+
- Common in service mesh architectures
|
|
914
|
+
|
|
915
|
+
### Security Testing
|
|
916
|
+
|
|
917
|
+
**Static Application Security Testing (SAST)**
|
|
918
|
+
- Analyze source code for vulnerabilities
|
|
919
|
+
- Find issues early in development
|
|
920
|
+
- Tools: SonarQube, Checkmarx, Fortify
|
|
921
|
+
|
|
922
|
+
**Dynamic Application Security Testing (DAST)**
|
|
923
|
+
- Test running application
|
|
924
|
+
- Find runtime vulnerabilities
|
|
925
|
+
- Tools: OWASP ZAP, Burp Suite, Acunetix
|
|
926
|
+
|
|
927
|
+
**Interactive Application Security Testing (IAST)**
|
|
928
|
+
- Combines SAST and DAST
|
|
929
|
+
- Real-time vulnerability detection
|
|
930
|
+
- Tools: Contrast Security, Seeker
|
|
931
|
+
|
|
932
|
+
**Penetration Testing**
|
|
933
|
+
- Simulated attacks by security experts
|
|
934
|
+
- Find vulnerabilities before attackers do
|
|
935
|
+
- Regular testing (quarterly, annually)
|
|
936
|
+
|
|
937
|
+
**Dependency Scanning**
|
|
938
|
+
- Check for vulnerable dependencies
|
|
939
|
+
- Automated scanning in CI/CD
|
|
940
|
+
- Tools: Snyk, Dependabot, npm audit
|
|
941
|
+
|
|
942
|
+
### Compliance and Standards
|
|
943
|
+
|
|
944
|
+
**Common Standards**
|
|
945
|
+
- **PCI DSS**: Payment Card Industry Data Security Standard
|
|
946
|
+
- **HIPAA**: Health Insurance Portability and Accountability Act
|
|
947
|
+
- **GDPR**: General Data Protection Regulation
|
|
948
|
+
- **SOC 2**: Service Organization Control 2
|
|
949
|
+
- **ISO 27001**: Information Security Management
|
|
950
|
+
|
|
951
|
+
**Compliance Requirements**
|
|
952
|
+
- Data encryption (at rest and in transit)
|
|
953
|
+
- Access controls and audit logging
|
|
954
|
+
- Incident response procedures
|
|
955
|
+
- Regular security assessments
|
|
956
|
+
- Data retention and deletion policies
|
|
957
|
+
|
|
958
|
+
### Best Practices
|
|
959
|
+
|
|
960
|
+
1. **Security by Design**
|
|
961
|
+
- Include security from the start
|
|
962
|
+
- Threat modeling in design phase
|
|
963
|
+
- Security requirements alongside functional requirements
|
|
964
|
+
|
|
965
|
+
2. **Principle of Least Privilege**
|
|
966
|
+
- Grant minimum necessary permissions
|
|
967
|
+
- Regular access reviews
|
|
968
|
+
- Just-in-time access for sensitive operations
|
|
969
|
+
|
|
970
|
+
3. **Defense in Depth**
|
|
971
|
+
- Multiple layers of security
|
|
972
|
+
- No single point of failure
|
|
973
|
+
- Assume each layer can be breached
|
|
974
|
+
|
|
975
|
+
4. **Secure Defaults**
|
|
976
|
+
- Deny by default, allow by exception
|
|
977
|
+
- Secure configuration out of the box
|
|
978
|
+
- Opt-in for risky features
|
|
979
|
+
|
|
980
|
+
5. **Keep Security Simple**
|
|
981
|
+
- Complex security is hard to maintain
|
|
982
|
+
- Prefer standard solutions over custom
|
|
983
|
+
- Document security decisions
|
|
984
|
+
|
|
985
|
+
6. **Continuous Monitoring**
|
|
986
|
+
- Real-time security monitoring
|
|
987
|
+
- Automated alerts for anomalies
|
|
988
|
+
- Regular security audits
|
|
989
|
+
|
|
990
|
+
7. **Incident Response Plan**
|
|
991
|
+
- Documented procedures
|
|
992
|
+
- Regular drills and updates
|
|
993
|
+
- Clear roles and responsibilities
|
|
994
|
+
|
|
995
|
+
### Common Pitfalls
|
|
996
|
+
|
|
997
|
+
1. **Security as an Afterthought**
|
|
998
|
+
- Adding security late is expensive
|
|
999
|
+
- Retrofitting is harder than building in
|
|
1000
|
+
- Security should be in initial requirements
|
|
1001
|
+
|
|
1002
|
+
2. **Trusting User Input**
|
|
1003
|
+
- All input is potentially malicious
|
|
1004
|
+
- Validate and sanitize everything
|
|
1005
|
+
- Never trust client-side validation alone
|
|
1006
|
+
|
|
1007
|
+
3. **Hardcoded Secrets**
|
|
1008
|
+
- Passwords, API keys in source code
|
|
1009
|
+
- Use environment variables or secret managers
|
|
1010
|
+
- Never commit secrets to version control
|
|
1011
|
+
|
|
1012
|
+
4. **Insufficient Logging**
|
|
1013
|
+
- Can't investigate what you don't log
|
|
1014
|
+
- Log security events comprehensively
|
|
1015
|
+
- Protect logs from tampering
|
|
1016
|
+
|
|
1017
|
+
5. **Ignoring Updates**
|
|
1018
|
+
- Unpatched vulnerabilities are common attack vector
|
|
1019
|
+
- Regular dependency updates
|
|
1020
|
+
- Automated vulnerability scanning
|
|
1021
|
+
|
|
1022
|
+
6. **Over-reliance on Obscurity**
|
|
1023
|
+
- Security through obscurity is not security
|
|
1024
|
+
- Assume attackers know your system
|
|
1025
|
+
- Use proven security mechanisms
|
|
1026
|
+
|
|
1027
|
+
---
|
|
1028
|
+
|
|
1029
|
+
## References
|
|
1030
|
+
|
|
1031
|
+
- **OWASP Top 10**: https://owasp.org/www-project-top-ten/
|
|
1032
|
+
- **OWASP ASVS**: Application Security Verification Standard
|
|
1033
|
+
- **NIST Cybersecurity Framework**: https://www.nist.gov/cyberframework
|
|
1034
|
+
- **Zero Trust Architecture**: NIST SP 800-207
|
|
1035
|
+
- **CWE Top 25**: Common Weakness Enumeration
|
|
1036
|
+
- **SANS Top 25**: Most Dangerous Software Errors
|
|
1037
|
+
- **ISO/IEC 27001**: Information Security Management
|
|
1038
|
+
- **PCI DSS**: Payment Card Industry Data Security Standard
|
|
1039
|
+
|