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68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# Password Reset Testing Guide

Complete guide for testing the password reset functionality with audit logging.

## Overview

The password reset system provides secure token-based password recovery with:
- Secure token generation (32+ characters)
- Time-limited tokens (1 hour expiry)
- Email delivery via Resend
- Comprehensive audit logging
- Protection against email enumeration attacks
- Single-use tokens

## Prerequisites

1. **Environment Variables** (see `.env.example`):
   ```bash
   RESEND_API_KEY=re_xxxxx
   RESEND_FROM_EMAIL=swiftops@atomio.tech
   APP_DOMAIN=swiftops.atomio.tech
   APP_PROTOCOL=https
   PASSWORD_RESET_TOKEN_EXPIRY_HOURS=1
   ```

2. **Database Migrations**:
   ```bash
   # Ensure user_invitations table exists
   # (Created in migration 11_user_invitations.sql)
   ```

3. **Test User**:
   ```bash
   # Register a test user first
   curl -X POST http://localhost:8000/api/v1/auth/register \
     -H "Content-Type: application/json" \
     -d '{
       "email": "test@example.com",
       "password": "TestPass123!",
       "first_name": "Test",
       "last_name": "User"
     }'
   ```

## Test Scenarios

### 1. Request Password Reset

**Endpoint**: `POST /api/v1/auth/forgot-password`

**Request**:
```bash
curl -X POST http://localhost:8000/api/v1/auth/forgot-password \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com"
  }'
```

**Expected Response** (200 OK):
```json
{
  "message": "If an account exists with this email, you will receive a password reset link."
}
```

**Verification**:
1. Check database for reset token:
   ```sql
   SELECT token, expires_at, status 
   FROM user_invitations 
   WHERE email = 'test@example.com' 
     AND invitation_metadata->>'type' = 'password_reset'
   ORDER BY created_at DESC 
   LIMIT 1;
   ```

2. Check audit log:
   ```sql
   SELECT action, description, created_at 
   FROM audit_logs 
   WHERE action = 'password_reset_request'
   ORDER BY created_at DESC 
   LIMIT 1;
   ```

3. Check email (if Resend configured):
   - Subject: "Reset Your SwiftOps Password"
   - Contains reset link with token
   - Mentions 1 hour expiry

### 2. Reset Password with Valid Token

**Endpoint**: `POST /api/v1/auth/reset-password`

**Request**:
```bash
# Get token from database first
TOKEN="<token_from_database>"

curl -X POST http://localhost:8000/api/v1/auth/reset-password \
  -H "Content-Type: application/json" \
  -d '{
    "token": "'$TOKEN'",
    "new_password": "NewTestPass456!"
  }'
```

**Expected Response** (200 OK):
```json
{
  "message": "Password reset successful. You can now login with your new password."
}
```

**Verification**:
1. Check token status updated:
   ```sql
   SELECT status, accepted_at 
   FROM user_invitations 
   WHERE token = '<token>';
   ```
   - Status should be 'accepted'
   - accepted_at should be set

2. Check audit log:
   ```sql
   SELECT action, description 
   FROM audit_logs 
   WHERE action = 'password_reset'
   ORDER BY created_at DESC 
   LIMIT 1;
   ```

3. Login with new password:
   ```bash
   curl -X POST http://localhost:8000/api/v1/auth/login \
     -H "Content-Type: application/json" \
     -d '{
       "email": "test@example.com",
       "password": "NewTestPass456!"
     }'
   ```

4. Verify old password fails:
   ```bash
   curl -X POST http://localhost:8000/api/v1/auth/login \
     -H "Content-Type: application/json" \
     -d '{
       "email": "test@example.com",
       "password": "TestPass123!"
     }'
   ```
   - Should return 401 Unauthorized

### 3. Invalid Token

**Request**:
```bash
curl -X POST http://localhost:8000/api/v1/auth/reset-password \
  -H "Content-Type: application/json" \
  -d '{
    "token": "invalid-token-12345678901234567890",
    "new_password": "NewTestPass456!"
  }'
```

**Expected Response** (400 Bad Request):
```json
{
  "detail": "Invalid or expired reset token"
}
```

**Verification**:
- Check audit log for failed attempt:
  ```sql
  SELECT action, description, additional_metadata 
  FROM audit_logs 
  WHERE action = 'password_reset_failed'
  ORDER BY created_at DESC 
  LIMIT 1;
  ```

### 4. Expired Token

**Setup**:
```sql
-- Manually expire a token for testing
UPDATE user_invitations 
SET expires_at = NOW() - INTERVAL '1 hour'
WHERE email = 'test@example.com' 
  AND status = 'pending'
  AND invitation_metadata->>'type' = 'password_reset';
```

**Request**:
```bash
curl -X POST http://localhost:8000/api/v1/auth/reset-password \
  -H "Content-Type: application/json" \
  -d '{
    "token": "<expired_token>",
    "new_password": "NewTestPass456!"
  }'
```

**Expected Response** (400 Bad Request):
```json
{
  "detail": "Reset token has expired. Please request a new one."
}
```

**Verification**:
- Token status updated to 'expired':
  ```sql
  SELECT status FROM user_invitations WHERE token = '<expired_token>';
  ```

### 5. Token Reuse Prevention

**Request**:
```bash
# Use the same token twice
TOKEN="<already_used_token>"

# First use (should succeed)
curl -X POST http://localhost:8000/api/v1/auth/reset-password \
  -H "Content-Type: application/json" \
  -d '{
    "token": "'$TOKEN'",
    "new_password": "NewTestPass456!"
  }'

# Second use (should fail)
curl -X POST http://localhost:8000/api/v1/auth/reset-password \
  -H "Content-Type: application/json" \
  -d '{
    "token": "'$TOKEN'",
    "new_password": "AnotherPass789!"
  }'
```

**Expected**:
- First request: 200 OK
- Second request: 400 Bad Request

### 6. Non-Existent Email (No Enumeration)

**Request**:
```bash
curl -X POST http://localhost:8000/api/v1/auth/forgot-password \
  -H "Content-Type: application/json" \
  -d '{
    "email": "nonexistent@example.com"
  }'
```

**Expected Response** (200 OK):
```json
{
  "message": "If an account exists with this email, you will receive a password reset link."
}
```

**Verification**:
- Same response as valid email (prevents enumeration)
- No token created in database
- Audit log still created

### 7. Password Validation

**Weak Passwords to Test**:
```bash
# Too short
curl -X POST http://localhost:8000/api/v1/auth/reset-password \
  -H "Content-Type: application/json" \
  -d '{"token": "test", "new_password": "short"}'

# No uppercase
curl -X POST http://localhost:8000/api/v1/auth/reset-password \
  -H "Content-Type: application/json" \
  -d '{"token": "test", "new_password": "nouppercase123"}'

# No digits
curl -X POST http://localhost:8000/api/v1/auth/reset-password \
  -H "Content-Type: application/json" \
  -d '{"token": "test", "new_password": "NoDigitsHere"}'
```

**Expected**: All should return 422 Validation Error

## Automated Tests

### Python Tests

Run pytest tests:
```bash
# All password reset tests
pytest tests/integration/test_password_reset.py -v

# Specific test
pytest tests/integration/test_password_reset.py::TestPasswordReset::test_reset_password_with_valid_token -v

# All auth audit log tests
pytest tests/integration/test_auth_audit_logs.py -v
```

### JavaScript Tests

Run Node.js tests:
```bash
cd tests/integration
npm install axios  # If not already installed
node test_password_reset.js
```

## Audit Log Verification

Check all audit logs for password reset flow:

```sql
-- All password reset related logs
SELECT 
  action,
  description,
  user_email,
  ip_address,
  created_at
FROM audit_logs
WHERE action IN (
  'password_reset_request',
  'password_reset',
  'password_reset_failed'
)
ORDER BY created_at DESC
LIMIT 20;

-- Detailed view with metadata
SELECT 
  action,
  description,
  additional_metadata,
  created_at
FROM audit_logs
WHERE entity_type = 'auth'
  AND action LIKE '%password%'
ORDER BY created_at DESC;
```

## Email Template Testing

If Resend is configured, verify email appearance:

1. **Subject**: "Reset Your SwiftOps Password"
2. **Content**:
   - Personalized greeting with user's name
   - Clear call-to-action button
   - Plain text link as fallback
   - Security notice about 1-hour expiry
   - Warning if user didn't request reset
3. **Styling**:
   - Responsive design
   - Professional appearance
   - SwiftOps branding

## Security Checklist

- [ ] Tokens are cryptographically secure (32+ characters)
- [ ] Tokens expire after 1 hour
- [ ] Tokens are single-use only
- [ ] No email enumeration (same response for valid/invalid emails)
- [ ] Password strength requirements enforced
- [ ] All actions logged in audit trail
- [ ] IP addresses captured in audit logs
- [ ] User agents captured in audit logs
- [ ] Email delivery failures handled gracefully
- [ ] Database errors don't expose sensitive info

## Troubleshooting

### Email Not Received

1. Check Resend API key:
   ```bash
   echo $RESEND_API_KEY
   ```

2. Check application logs:
   ```bash
   grep "Password reset" logs/app.log
   grep "Email send error" logs/app.log
   ```

3. Verify Resend domain configuration

### Token Not Working

1. Check token exists and is valid:
   ```sql
   SELECT * FROM user_invitations 
   WHERE token = '<token>';
   ```

2. Check expiry time:
   ```sql
   SELECT 
     token,
     expires_at,
     expires_at > NOW() as is_valid,
     status
   FROM user_invitations 
   WHERE token = '<token>';
   ```

### Audit Logs Not Created

1. Check database connection
2. Verify audit_logs table exists
3. Check application logs for errors
4. Ensure AuditService is imported correctly

## Performance Considerations

- Token generation: < 10ms
- Database query: < 50ms
- Email sending: < 2s (async)
- Total request time: < 100ms (excluding email)

## Next Steps

After testing password reset:
1. Test all auth endpoints with audit logging
2. Verify audit log retention policies
3. Set up monitoring for failed reset attempts
4. Configure email rate limiting
5. Review security policies with team