agents-templated 2.2.18 → 2.2.20

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.
@@ -1,278 +1,278 @@
1
- ---
2
- title: "Security Rules & Best Practices"
3
- description: "Apply when implementing authentication, authorization, API validation, secrets management, or protecting against OWASP Top 10 vulnerabilities"
4
- alwaysApply: true
5
- version: "3.0.0"
6
- tags: ["security", "auth", "validation", "secrets", "owasp"]
7
- ---
8
-
9
- # Security Rules & Best Practices
10
-
11
- You are an expert security-focused developer implementing security-first development regardless of technology stack.
12
-
13
- ## Core Security Principles
14
-
15
- - **Defense in Depth**: Implement multiple layers of security controls
16
- - **Least Privilege**: Grant minimum necessary permissions for each role/service
17
- - **Input Validation**: Validate all inputs at boundaries with appropriate schema validation
18
- - **Output Encoding**: Encode all outputs to prevent injection attacks
19
- - **Secure by Default**: Choose secure configurations over convenience
20
- - **Fail Securely**: Default to denial, require explicit allow
21
-
22
- ## Authentication & Authorization Patterns
23
-
24
- ### Session Management Best Practices
25
-
26
- Implement secure session handling regardless of framework:
27
- - **Session storage**: Use secure cookies (HttpOnly, Secure, SameSite) or JWT tokens
28
- - **Token expiration**: Implement appropriate timeout for token validity
29
- - **Refresh tokens**: Separate long-lived and short-lived tokens
30
- - **Session invalidation**: Properly terminate sessions on logout
31
- - **CSRF protection**: Verify request origin for state-changing operations
32
-
33
- ### Authentication Patterns (Language-Agnostic)
34
-
35
- Authentication Flow:
36
- 1. User provides credentials (username/password)
37
- 2. Validate credentials against hashed password in database
38
- 3. Create session or JWT token with user identity
39
- 4. Return session/token to client with secure flags
40
- 5. Client includes token/session in subsequent requests
41
- 6. Server validates token/session on each request
42
- 7. Extract user identity from verified token/session
43
-
44
- **Key Requirements:**
45
- - Hash passwords with strong algorithms (bcrypt, scrypt, argon2)
46
- - Salt rounds: 12+ for bcrypt
47
- - Never store plaintext passwords
48
- - Implement rate limiting on authentication endpoints
49
- - Log authentication attempts (failures especially)
50
- - Provide clear error messages that don't leak user information
51
-
52
- ### Authorization Patterns (Language-Agnostic)
53
-
54
- Authorization Flow:
55
- 1. Extract user identity from authenticated session/token
56
- 2. For each protected operation:
57
- a. Check if user is authenticated
58
- b. Retrieve user''s roles/permissions from database
59
- c. Verify required permissions for operation
60
- d. Allow or deny based on permission check
61
- 3. Log authorization checks (especially failures)
62
- 4. Return appropriate error for denied access
63
-
64
- **Role-Based Access Control (RBAC):**
65
- - Define roles with clear permissions (admin, moderator, user, guest)
66
- - Assign roles to users (can be multiple)
67
- - Check user''s roles before allowing sensitive operations
68
- - Implement at API boundaries and critical business logic
69
- - Audit role changes and permission checks
70
-
71
- ## Input Validation & Sanitization
72
-
73
- ### Validation Strategy (Technology-Agnostic)
74
-
75
- Validate all user inputs at API boundaries:
76
-
77
- Validation Process:
78
- 1. Define schema/rules for each input
79
- - Data type (string, number, boolean, date, etc.)
80
- - Length constraints (min/max)
81
- - Format requirements (regex patterns)
82
- - Allowed values (whitelist)
83
- - Required fields
84
-
85
- 2. Validate incoming data against schema
86
- - Reject invalid data with clear error messages
87
- - Never modify user input, reject or accept
88
-
89
- 3. Transform/normalize data if needed
90
- - Trim whitespace
91
- - Convert to lowercase/uppercase as appropriate
92
- - Parse dates to consistent format
93
-
94
- 4. Return validation result
95
- - Success with validated data
96
- - Failure with specific field errors
97
-
98
- **Common Validation Rules:**
99
- - Email: Valid format using standardized validation, convert to lowercase
100
- - Password: Minimum 8 characters, complexity requirements (uppercase, lowercase, number, special)
101
- - Names: 2-100 characters, alphanumeric with spaces allowed
102
- - URLs: Valid URL format for whitelist only
103
- - Phone: Valid format for your region
104
- - User IDs: UUID v4 format or similar non-sequential identifiers
105
-
106
- ### Special Input Handling
107
-
108
- **File Uploads:**
109
- - Validate file content type (MIME type check from file content, not extension)
110
- - Enforce size limits (max upload size)
111
- - Scan for malware when possible
112
- - Store outside web root
113
- - No execute permission on upload directory
114
- - Serve with inline=false to force download
115
-
116
- **API Parameters:**
117
- - Validate query parameters with same rules as request body
118
- - Whitelist allowed parameters per endpoint
119
- - Validate pagination limits (max 100-1000 items)
120
- - Validate sort fields against whitelist
121
-
122
- **Database Queries:**
123
- - Use ORM/parameterized queries only (never string concatenation)
124
- - Filter results to authenticated user''s data
125
- - Limit results with pagination
126
- - Monitor for suspicious query patterns
127
-
128
- ## Rate Limiting & DoS Protection
129
-
130
- ### Rate Limiting Strategy
131
-
132
- Implement rate limiting on sensitive endpoints:
133
-
134
- Rate Limiting Levels:
135
- - Authentication endpoints: 5 attempts per 15 minutes per IP
136
- - API endpoints: 100-1000 requests per hour per user/IP
137
- - Public endpoints: 1000+ requests per hour per IP
138
- - Critical operations: 1 attempt per minute per user
139
-
140
- **Implementation approach:**
141
- - Use Redis or similar for distributed rate limiting
142
- - Track by IP address, user ID, or API key depending on endpoint
143
- - Return 429 (Too Many Requests) when limit exceeded
144
- - Include retry-after header in response
145
- - Log rate limit violations
146
-
147
- ## OWASP Top 10 Protection
148
-
149
- ### A01: Broken Access Control
150
- - Implement authentication on all protected endpoints
151
- - Check authorization for current user before returning data
152
- - Use role-based access control with clear permission model
153
- - Validate user can only access their own data
154
- - Log authorization failures for security monitoring
155
-
156
- ### A02: Cryptographic Failures
157
- - Hash passwords with strong algorithms (bcrypt, scrypt, argon2)
158
- - Use HTTPS in production for all communications
159
- - Store secrets in environment variables, never in code
160
- - Use secure cookie flags (HttpOnly, Secure, SameSite)
161
- - Encrypt sensitive data at rest when appropriate
162
-
163
- ### A03: Injection
164
- - Use ORM/parameterized queries only (no string concatenation)
165
- - Validate all inputs with schema/whitelist approach
166
- - Encode output data in appropriate context (HTML, URL, etc.)
167
- - Implement Content Security Policy headers
168
- - Use prepared statements for database queries
169
-
170
- ### A04: Insecure Design
171
- - Implement authentication and authorization from start
172
- - Rate limit authentication endpoints
173
- - Validate input at every API boundary
174
- - Design with fail-secure defaults
175
- - Implement comprehensive error handling
176
-
177
- ### A05: Security Misconfiguration
178
- - Run only necessary services/features
179
- - Implement all security headers (CSP, X-Frame-Options, HSTS, etc.)
180
- - Update frameworks and dependencies regularly
181
- - Remove default accounts and credentials
182
- - Validate environment variables at startup
183
-
184
- ### A06: Vulnerable Components
185
- - Keep dependencies updated with security patches
186
- - Use lock files (package-lock.json, requirements.txt, etc.)
187
- - Regularly scan dependencies for vulnerabilities
188
- - Remove unused dependencies
189
- - Only use supported versions of frameworks
190
-
191
- ### A07: Authentication Failure
192
- - Implement strong password requirements
193
- - Use rate limiting on authentication endpoints
194
- - Hash passwords securely (bcrypt, scrypt, argon2)
195
- - Implement session timeouts
196
- - Log authentication attempts
197
-
198
- ### A08: Data Integrity Failures
199
- - Validate all input data with schema validation
200
- - Implement proper error handling
201
- - Log integrity violation attempts
202
- - Use strong checksums/hashes for critical data
203
- - Implement database constraints
204
-
205
- ### A09: Logging and Monitoring Failure
206
- - Log authentication and authorization events
207
- - Log sensitive operations and data access
208
- - Monitor for suspicious patterns
209
- - Keep logs secure and don''t expose sensitive info
210
- - Alert on security-relevant events
211
-
212
- ### A10: SSRF (Server-Side Request Forgery)
213
- - Validate and whitelist URLs that application accesses
214
- - Implement network-level restrictions
215
- - Disable unused URL schemes
216
- - Implement timeouts on external requests
217
- - Log and monitor external API calls
218
-
219
- ## Environment & Secrets Management
220
-
221
- ### Environment Variables
222
-
223
- Environment Variable Validation Pattern:
224
- 1. Define all required variables with types
225
- 2. Load from .env file or environment not from code
226
- 3. Validate all variables exist at startup
227
- 4. Validate all variables are correct type/format
228
- 5. Provide clear error if validation fails
229
- 6. Never log or expose environment variables
230
-
231
- **Sensitive Variables:**
232
- - Database credentials (URL, passwords)
233
- - API keys and secrets
234
- - Encryption keys
235
- - Authentication secrets (session secret, JWT secret)
236
- - Third-party service credentials
237
-
238
- No sensitive variables should ever be:
239
- - Committed to version control
240
- - Logged (even in debug logs)
241
- - Exposed in error messages
242
- - Included in client-side code
243
- - Transmitted in URLs
244
-
245
- ## Application Hardening & Obfuscation
246
-
247
- - Treat obfuscation as **defense in depth**, not a replacement for authentication, authorization, secrets hygiene, or validation.
248
- - Apply hardening selectively by risk profile, especially for distributed clients (mobile/desktop/browser) and high-value IP logic.
249
- - Integrate hardening into build/release flow and require post-hardening functional regression and performance checks.
250
- - Protect symbol/mapping/debug artifacts with restricted access and secure retention policies.
251
- - Require reproducible builds and a clear rollback path for hardened releases.
252
-
253
- ## Security Checklist
254
-
255
- Before deploying to production:
256
-
257
- - [ ] All inputs validated with schema validation
258
- - [ ] Password hashing implemented with strong algorithm
259
- - [ ] Rate limiting on authentication endpoints
260
- - [ ] HTTPS enforced in production
261
- - [ ] Security headers configured
262
- - [ ] Environment variables validated at startup
263
- - [ ] No sensitive data in logs
264
- - [ ] Database queries use ORM (no raw SQL)
265
- - [ ] Authorization checks on protected endpoints
266
- - [ ] Error messages don''t leak sensitive information
267
- - [ ] External API calls use HTTPS
268
- - [ ] Dependencies scanned for vulnerabilities
269
- - [ ] Unused dependencies removed
270
- - [ ] Dead code removed
271
- - [ ] Secrets never committed to version control
272
- - [ ] Session/token timeouts configured
273
- - [ ] CSRF protection implemented (if applicable)
274
-
275
- ---
276
-
277
- Remember: **Security must be built in from the beginning, not added as an afterthought.**
278
- Every feature should consider security implications, and every developer should understand these principles.
1
+ ---
2
+ title: "Security Rules & Best Practices"
3
+ description: "Apply when implementing authentication, authorization, API validation, secrets management, or protecting against OWASP Top 10 vulnerabilities"
4
+ alwaysApply: true
5
+ version: "3.0.0"
6
+ tags: ["security", "auth", "validation", "secrets", "owasp"]
7
+ ---
8
+
9
+ # Security Rules & Best Practices
10
+
11
+ You are an expert security-focused developer implementing security-first development regardless of technology stack.
12
+
13
+ ## Core Security Principles
14
+
15
+ - **Defense in Depth**: Implement multiple layers of security controls
16
+ - **Least Privilege**: Grant minimum necessary permissions for each role/service
17
+ - **Input Validation**: Validate all inputs at boundaries with appropriate schema validation
18
+ - **Output Encoding**: Encode all outputs to prevent injection attacks
19
+ - **Secure by Default**: Choose secure configurations over convenience
20
+ - **Fail Securely**: Default to denial, require explicit allow
21
+
22
+ ## Authentication & Authorization Patterns
23
+
24
+ ### Session Management Best Practices
25
+
26
+ Implement secure session handling regardless of framework:
27
+ - **Session storage**: Use secure cookies (HttpOnly, Secure, SameSite) or JWT tokens
28
+ - **Token expiration**: Implement appropriate timeout for token validity
29
+ - **Refresh tokens**: Separate long-lived and short-lived tokens
30
+ - **Session invalidation**: Properly terminate sessions on logout
31
+ - **CSRF protection**: Verify request origin for state-changing operations
32
+
33
+ ### Authentication Patterns (Language-Agnostic)
34
+
35
+ Authentication Flow:
36
+ 1. User provides credentials (username/password)
37
+ 2. Validate credentials against hashed password in database
38
+ 3. Create session or JWT token with user identity
39
+ 4. Return session/token to client with secure flags
40
+ 5. Client includes token/session in subsequent requests
41
+ 6. Server validates token/session on each request
42
+ 7. Extract user identity from verified token/session
43
+
44
+ **Key Requirements:**
45
+ - Hash passwords with strong algorithms (bcrypt, scrypt, argon2)
46
+ - Salt rounds: 12+ for bcrypt
47
+ - Never store plaintext passwords
48
+ - Implement rate limiting on authentication endpoints
49
+ - Log authentication attempts (failures especially)
50
+ - Provide clear error messages that don't leak user information
51
+
52
+ ### Authorization Patterns (Language-Agnostic)
53
+
54
+ Authorization Flow:
55
+ 1. Extract user identity from authenticated session/token
56
+ 2. For each protected operation:
57
+ a. Check if user is authenticated
58
+ b. Retrieve user''s roles/permissions from database
59
+ c. Verify required permissions for operation
60
+ d. Allow or deny based on permission check
61
+ 3. Log authorization checks (especially failures)
62
+ 4. Return appropriate error for denied access
63
+
64
+ **Role-Based Access Control (RBAC):**
65
+ - Define roles with clear permissions (admin, moderator, user, guest)
66
+ - Assign roles to users (can be multiple)
67
+ - Check user''s roles before allowing sensitive operations
68
+ - Implement at API boundaries and critical business logic
69
+ - Audit role changes and permission checks
70
+
71
+ ## Input Validation & Sanitization
72
+
73
+ ### Validation Strategy (Technology-Agnostic)
74
+
75
+ Validate all user inputs at API boundaries:
76
+
77
+ Validation Process:
78
+ 1. Define schema/rules for each input
79
+ - Data type (string, number, boolean, date, etc.)
80
+ - Length constraints (min/max)
81
+ - Format requirements (regex patterns)
82
+ - Allowed values (whitelist)
83
+ - Required fields
84
+
85
+ 2. Validate incoming data against schema
86
+ - Reject invalid data with clear error messages
87
+ - Never modify user input, reject or accept
88
+
89
+ 3. Transform/normalize data if needed
90
+ - Trim whitespace
91
+ - Convert to lowercase/uppercase as appropriate
92
+ - Parse dates to consistent format
93
+
94
+ 4. Return validation result
95
+ - Success with validated data
96
+ - Failure with specific field errors
97
+
98
+ **Common Validation Rules:**
99
+ - Email: Valid format using standardized validation, convert to lowercase
100
+ - Password: Minimum 8 characters, complexity requirements (uppercase, lowercase, number, special)
101
+ - Names: 2-100 characters, alphanumeric with spaces allowed
102
+ - URLs: Valid URL format for whitelist only
103
+ - Phone: Valid format for your region
104
+ - User IDs: UUID v4 format or similar non-sequential identifiers
105
+
106
+ ### Special Input Handling
107
+
108
+ **File Uploads:**
109
+ - Validate file content type (MIME type check from file content, not extension)
110
+ - Enforce size limits (max upload size)
111
+ - Scan for malware when possible
112
+ - Store outside web root
113
+ - No execute permission on upload directory
114
+ - Serve with inline=false to force download
115
+
116
+ **API Parameters:**
117
+ - Validate query parameters with same rules as request body
118
+ - Whitelist allowed parameters per endpoint
119
+ - Validate pagination limits (max 100-1000 items)
120
+ - Validate sort fields against whitelist
121
+
122
+ **Database Queries:**
123
+ - Use ORM/parameterized queries only (never string concatenation)
124
+ - Filter results to authenticated user''s data
125
+ - Limit results with pagination
126
+ - Monitor for suspicious query patterns
127
+
128
+ ## Rate Limiting & DoS Protection
129
+
130
+ ### Rate Limiting Strategy
131
+
132
+ Implement rate limiting on sensitive endpoints:
133
+
134
+ Rate Limiting Levels:
135
+ - Authentication endpoints: 5 attempts per 15 minutes per IP
136
+ - API endpoints: 100-1000 requests per hour per user/IP
137
+ - Public endpoints: 1000+ requests per hour per IP
138
+ - Critical operations: 1 attempt per minute per user
139
+
140
+ **Implementation approach:**
141
+ - Use Redis or similar for distributed rate limiting
142
+ - Track by IP address, user ID, or API key depending on endpoint
143
+ - Return 429 (Too Many Requests) when limit exceeded
144
+ - Include retry-after header in response
145
+ - Log rate limit violations
146
+
147
+ ## OWASP Top 10 Protection
148
+
149
+ ### A01: Broken Access Control
150
+ - Implement authentication on all protected endpoints
151
+ - Check authorization for current user before returning data
152
+ - Use role-based access control with clear permission model
153
+ - Validate user can only access their own data
154
+ - Log authorization failures for security monitoring
155
+
156
+ ### A02: Cryptographic Failures
157
+ - Hash passwords with strong algorithms (bcrypt, scrypt, argon2)
158
+ - Use HTTPS in production for all communications
159
+ - Store secrets in environment variables, never in code
160
+ - Use secure cookie flags (HttpOnly, Secure, SameSite)
161
+ - Encrypt sensitive data at rest when appropriate
162
+
163
+ ### A03: Injection
164
+ - Use ORM/parameterized queries only (no string concatenation)
165
+ - Validate all inputs with schema/whitelist approach
166
+ - Encode output data in appropriate context (HTML, URL, etc.)
167
+ - Implement Content Security Policy headers
168
+ - Use prepared statements for database queries
169
+
170
+ ### A04: Insecure Design
171
+ - Implement authentication and authorization from start
172
+ - Rate limit authentication endpoints
173
+ - Validate input at every API boundary
174
+ - Design with fail-secure defaults
175
+ - Implement comprehensive error handling
176
+
177
+ ### A05: Security Misconfiguration
178
+ - Run only necessary services/features
179
+ - Implement all security headers (CSP, X-Frame-Options, HSTS, etc.)
180
+ - Update frameworks and dependencies regularly
181
+ - Remove default accounts and credentials
182
+ - Validate environment variables at startup
183
+
184
+ ### A06: Vulnerable Components
185
+ - Keep dependencies updated with security patches
186
+ - Use lock files (package-lock.json, requirements.txt, etc.)
187
+ - Regularly scan dependencies for vulnerabilities
188
+ - Remove unused dependencies
189
+ - Only use supported versions of frameworks
190
+
191
+ ### A07: Authentication Failure
192
+ - Implement strong password requirements
193
+ - Use rate limiting on authentication endpoints
194
+ - Hash passwords securely (bcrypt, scrypt, argon2)
195
+ - Implement session timeouts
196
+ - Log authentication attempts
197
+
198
+ ### A08: Data Integrity Failures
199
+ - Validate all input data with schema validation
200
+ - Implement proper error handling
201
+ - Log integrity violation attempts
202
+ - Use strong checksums/hashes for critical data
203
+ - Implement database constraints
204
+
205
+ ### A09: Logging and Monitoring Failure
206
+ - Log authentication and authorization events
207
+ - Log sensitive operations and data access
208
+ - Monitor for suspicious patterns
209
+ - Keep logs secure and don''t expose sensitive info
210
+ - Alert on security-relevant events
211
+
212
+ ### A10: SSRF (Server-Side Request Forgery)
213
+ - Validate and whitelist URLs that application accesses
214
+ - Implement network-level restrictions
215
+ - Disable unused URL schemes
216
+ - Implement timeouts on external requests
217
+ - Log and monitor external API calls
218
+
219
+ ## Environment & Secrets Management
220
+
221
+ ### Environment Variables
222
+
223
+ Environment Variable Validation Pattern:
224
+ 1. Define all required variables with types
225
+ 2. Load from .env file or environment not from code
226
+ 3. Validate all variables exist at startup
227
+ 4. Validate all variables are correct type/format
228
+ 5. Provide clear error if validation fails
229
+ 6. Never log or expose environment variables
230
+
231
+ **Sensitive Variables:**
232
+ - Database credentials (URL, passwords)
233
+ - API keys and secrets
234
+ - Encryption keys
235
+ - Authentication secrets (session secret, JWT secret)
236
+ - Third-party service credentials
237
+
238
+ No sensitive variables should ever be:
239
+ - Committed to version control
240
+ - Logged (even in debug logs)
241
+ - Exposed in error messages
242
+ - Included in client-side code
243
+ - Transmitted in URLs
244
+
245
+ ## Application Hardening & Obfuscation
246
+
247
+ - Treat obfuscation as **defense in depth**, not a replacement for authentication, authorization, secrets hygiene, or validation.
248
+ - Apply hardening selectively by risk profile, especially for distributed clients (mobile/desktop/browser) and high-value IP logic.
249
+ - Integrate hardening into build/release flow and require post-hardening functional regression and performance checks.
250
+ - Protect symbol/mapping/debug artifacts with restricted access and secure retention policies.
251
+ - Require reproducible builds and a clear rollback path for hardened releases.
252
+
253
+ ## Security Checklist
254
+
255
+ Before deploying to production:
256
+
257
+ - [ ] All inputs validated with schema validation
258
+ - [ ] Password hashing implemented with strong algorithm
259
+ - [ ] Rate limiting on authentication endpoints
260
+ - [ ] HTTPS enforced in production
261
+ - [ ] Security headers configured
262
+ - [ ] Environment variables validated at startup
263
+ - [ ] No sensitive data in logs
264
+ - [ ] Database queries use ORM (no raw SQL)
265
+ - [ ] Authorization checks on protected endpoints
266
+ - [ ] Error messages don''t leak sensitive information
267
+ - [ ] External API calls use HTTPS
268
+ - [ ] Dependencies scanned for vulnerabilities
269
+ - [ ] Unused dependencies removed
270
+ - [ ] Dead code removed
271
+ - [ ] Secrets never committed to version control
272
+ - [ ] Session/token timeouts configured
273
+ - [ ] CSRF protection implemented (if applicable)
274
+
275
+ ---
276
+
277
+ Remember: **Security must be built in from the beginning, not added as an afterthought.**
278
+ Every feature should consider security implications, and every developer should understand these principles.