# Security Testing Guide
This guide provides comprehensive testing procedures for all security aspects of the Impersonator Smart Wallet system.
## Pre-Testing Setup
1. Install testing dependencies:
```bash
npm install --save-dev @testing-library/react @testing-library/jest-dom jest jest-environment-jsdom
```
2. Set up test environment variables
3. Configure test database/storage mocks
---
## Test Categories
### 1. Input Validation Tests
#### Address Validation
```typescript
describe("Address Validation", () => {
test("rejects malicious addresses", () => {
const malicious = [
"",
"javascript:alert('xss')",
"../../etc/passwd",
"0x" + "a".repeat(1000), // Too long
"0xGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG", // Invalid hex
];
malicious.forEach(addr => {
expect(validateAddress(addr).valid).toBe(false);
});
});
test("detects contract addresses", async () => {
const contractAddr = "0x..."; // Known contract
const isContract = await isContractAddress(contractAddr, provider);
expect(isContract).toBe(true);
});
});
```
#### Transaction Data Validation
```typescript
describe("Transaction Data Validation", () => {
test("rejects malicious bytecode", () => {
const malicious = [
"0x" + "00".repeat(50000), // Too large
"0xdeadbeef";
const address = maliciousScript + "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb";
// Should sanitize and extract valid address
const result = validateAddress(address);
expect(result.valid).toBe(false);
});
test("prevents transaction manipulation", async () => {
const originalTx = createTestTransaction();
// Try to modify transaction
const modifiedTx = {
...originalTx,
to: "0xAttacker",
value: "1000000000000000000000", // 1000 ETH
};
// Should reject or require re-approval
await expect(
updateTransaction(originalTx.id, modifiedTx)
).rejects.toThrow("Cannot modify approved transaction");
});
});
```
---
## Penetration Testing Scenarios
### Scenario 1: XSS Attack
1. Inject `` in address field
2. Verify it's sanitized/blocked
3. Check localStorage is not accessible
### Scenario 2: CSRF Attack
1. Create malicious site that sends transaction requests
2. Verify origin validation prevents execution
3. Check CSRF tokens are required
### Scenario 3: Replay Attack
1. Capture transaction request
2. Replay same transaction
3. Verify nonce prevents duplicate execution
### Scenario 4: Race Condition Attack
1. Send 100 concurrent approval requests
2. Verify all are processed correctly
3. Check threshold is not bypassed
### Scenario 5: Integer Overflow
1. Send transaction with value > max uint256
2. Verify BigNumber handles correctly
3. Check no precision loss
---
## Automated Security Scanning
### 1. Dependency Scanning
```bash
npm audit
npm audit fix
```
### 2. Code Scanning
```bash
# Use ESLint security plugin
npm install --save-dev eslint-plugin-security
# Run security linting
npm run lint:security
```
### 3. Static Analysis
```bash
# Use SonarQube or similar
sonar-scanner
```
---
## Manual Testing Checklist
### Input Validation
- [ ] All address inputs validated
- [ ] Contract addresses rejected as owners
- [ ] Transaction data sanitized
- [ ] Value inputs use BigNumber
- [ ] Network IDs validated
### Access Control
- [ ] Only owners can modify wallet
- [ ] Threshold changes verified
- [ ] Owner additions require authorization
- [ ] Transaction approvals tracked correctly
### Message Security
- [ ] postMessage uses specific origins
- [ ] Message validation prevents injection
- [ ] Replay protection works
- [ ] Timestamp validation active
### Storage Security
- [ ] Sensitive data encrypted
- [ ] Keys not stored in localStorage
- [ ] Data can be decrypted correctly
- [ ] Tampered data rejected
### Transaction Security
- [ ] Nonces managed correctly
- [ ] Duplicate transactions prevented
- [ ] Gas limits enforced
- [ ] Amount limits enforced
- [ ] Expiration checked
### Provider Security
- [ ] Providers verified
- [ ] Accounts match wallets
- [ ] No fake providers accepted
- [ ] Signer validation works
---
## Performance Under Attack
### Load Testing
```typescript
describe("Performance Under Attack", () => {
test("handles spam transactions", async () => {
// Create 1000 transactions rapidly
const promises = Array(1000).fill(0).map((_, i) =>
createTransaction({
from: "0xFrom",
to: "0xTo",
value: "0",
data: "0x",
})
);
const start = Date.now();
await Promise.all(promises);
const duration = Date.now() - start;
// Should complete in reasonable time
expect(duration).toBeLessThan(10000); // 10 seconds
});
test("rate limiting prevents DoS", async () => {
const limiter = new RateLimiter(10, 60000);
const key = "test-key";
// First 10 should succeed
for (let i = 0; i < 10; i++) {
expect(limiter.checkLimit(key)).toBe(true);
}
// 11th should fail
expect(limiter.checkLimit(key)).toBe(false);
});
});
```
---
## Reporting Security Issues
If you find security vulnerabilities:
1. **DO NOT** create public issues
2. Email security team directly
3. Include:
- Description of vulnerability
- Steps to reproduce
- Potential impact
- Suggested fix
---
## Continuous Security Monitoring
### Daily Checks
- [ ] Review error logs for suspicious activity
- [ ] Check for failed validations
- [ ] Monitor transaction patterns
### Weekly Checks
- [ ] Review dependency updates
- [ ] Check for new CVEs
- [ ] Review access logs
### Monthly Checks
- [ ] Full security audit
- [ ] Penetration testing
- [ ] Code review
---
## Security Metrics to Track
1. **Failed Validations**: Count of rejected inputs
2. **Rate Limit Hits**: Number of rate-limited requests
3. **Suspicious Transactions**: Transactions flagged for review
4. **Provider Verification Failures**: Failed provider checks
5. **Encryption Failures**: Failed encryption/decryption attempts
6. **Message Replay Attempts**: Blocked replay attacks
---
## Conclusion
Regular security testing is essential. Run these tests:
- Before every release
- After major changes
- Monthly as part of security review
- After security incidents
Keep this guide updated as new threats emerge.