# ActivityPub Security PoC - Architecture ## Project Structure ``` activitypub-security-poc/ ├── src/ │ ├── cli.js # Command-line interface │ ├── activitypub-client.js # ActivityPub HTTP client │ ├── security-tester.js # Security testing module │ └── mock-server.js # Mock ActivityPub server ├── examples/ │ ├── create-note.json # Sample Create activity │ ├── follow.json # Sample Follow activity │ ├── xss-payload.json # XSS test payload │ ├── ssrf-payload.json # SSRF test payload │ └── USAGE.md # Usage examples ├── docs/ │ ├── ARCHITECTURE.md # This file │ └── SECURITY_TESTING.md # Security testing guide ├── package.json ├── README.md └── test.sh # Quick test script ``` ## Core Components ### 1. ActivityPub Client (`activitypub-client.js`) **Purpose**: Low-level HTTP client for ActivityPub interactions. **Key Features**: - Send activities to inbox endpoints - Fetch from outbox endpoints - Fetch actor profiles - HTTP signature generation (for authenticated requests) - JSON-LD context handling - Activity creation helpers **Main Methods**: ```javascript class ActivityPubClient { sendToInbox(inboxUrl, activity, options) fetchOutbox(outboxUrl, options) fetchActor(actorUrl, options) signRequest(method, url, body) createActivity(type, object, additionalProps) createNote(content, additionalProps) } ``` ### 2. Security Tester (`security-tester.js`) **Purpose**: Automated security testing framework. **Key Features**: - XSS vulnerability testing - SSRF vulnerability testing - Object injection testing - Signature bypass testing - Authorization testing - SQL/Command injection testing **Main Methods**: ```javascript class SecurityTester { testXSS(inboxUrl) testSSRF(inboxUrl) testObjectInjection(inboxUrl) testSignatureBypass(inboxUrl) testAuthorization(actorUrl, inboxUrl) testInjection(inboxUrl) runAllTests(targetUrl, options) generateReport(results) } ``` ### 3. CLI (`cli.js`) **Purpose**: User-friendly command-line interface. **Commands**: - `test-inbox` - Send activities to inbox - `test-outbox` - Fetch from outbox - `fetch-actor` - Get actor profile - `security-scan` - Run security tests - `craft` - Create custom activities - `mock-server` - Start mock server ### 4. Mock Server (`mock-server.js`) **Purpose**: Simulated ActivityPub server for testing. **Key Features**: - Full ActivityPub endpoint simulation - WebFinger support - Activity validation - Security issue detection and logging - Multiple mock users (alice, bob) **Endpoints**: - `/.well-known/webfinger` - WebFinger - `/users/:username` - Actor profiles - `/users/:username/inbox` - User inbox - `/users/:username/outbox` - User outbox - `/users/:username/followers` - Followers collection - `/users/:username/following` - Following collection - `/inbox` - Shared inbox ## Data Flow ### Sending an Activity ``` User Command ↓ CLI (cli.js) ↓ ActivityPubClient.sendToInbox() ↓ HTTP POST with JSON-LD payload ↓ Target Server (or Mock Server) ↓ Response (status, headers, body) ↓ Display to User ``` ### Security Scan ``` User Command ↓ CLI (cli.js) ↓ SecurityTester.runAllTests() ↓ Multiple Test Methods (XSS, SSRF, etc.) ↓ ActivityPubClient.sendToInbox() for each payload ↓ Collect responses ↓ Analyze for vulnerabilities ↓ Generate Report ↓ Display to User ``` ### Mock Server Request Handling ``` HTTP Request ↓ MockActivityPubServer.handleRequest() ↓ Route to appropriate handler ↓ Validate activity (if POST) ↓ Perform security checks ↓ Log detected issues ↓ Store activity (if valid) ↓ Return response ``` ## Security Testing Methodology ### 1. Test Case Design Each security test: 1. Creates a malicious payload 2. Sends it to the target endpoint 3. Analyzes the response 4. Determines if vulnerability exists based on: - Response status (200/202 = potential issue) - Error messages - Behavior changes ### 2. Payload Categories **XSS Payloads**: - Script tags - Event handlers - JavaScript protocols - SVG-based vectors - Encoded payloads **SSRF Payloads**: - Internal IPs (localhost, 127.0.0.1) - Cloud metadata endpoints - File protocol URLs - IPv6 localhost - DNS rebinding targets **Injection Payloads**: - SQL injection patterns - Command injection sequences - Prototype pollution attempts - Path traversal strings ### 3. Validation Logic The mock server demonstrates proper validation: ```javascript // Activity validation validateActivity(activity) { - Check for required fields - Validate @context - Verify actor field - Return validation result } // Security checks performSecurityChecks(activity) { - Scan for XSS patterns - Check for SSRF attempts - Detect prototype pollution - Identify SQL injection patterns - Return list of issues } ``` ## HTTP Signatures (Planned) Future versions will implement full HTTP signature support: ``` 1. Generate RSA key pair 2. Include public key in actor profile 3. Sign requests with private key 4. Verify signatures on mock server 5. Test signature bypass scenarios ``` ## Extension Points ### Adding New Security Tests 1. Add test method to `SecurityTester`: ```javascript async testNewVulnerability(inboxUrl) { const payloads = [...]; const results = []; for (const payload of payloads) { // Create activity with payload // Send to inbox // Analyze response results.push({...}); } return results; } ``` 2. Integrate into `runAllTests()`: ```javascript if (!options.tests || options.tests.includes('newvuln')) { allResults.tests.newVuln = await this.testNewVulnerability(targetUrl); } ``` ### Adding New CLI Commands 1. Add command to `cli.js`: ```javascript program .command('new-command') .description('Description') .option('-f, --flag ', 'Option') .action(async (options) => { // Implementation }); ``` ### Extending Mock Server 1. Add new endpoint handler: ```javascript async handleNewEndpoint(req, res, path) { // Handle request this.sendJSON(res, data); } ``` 2. Add route in `handleRequest()`: ```javascript if (path.match(/^\/new-endpoint$/)) { await this.handleNewEndpoint(req, res, path); } ``` ## Best Practices ### Code Organization - **Separation of Concerns**: Client, tester, CLI, and server are separate modules - **Reusability**: Core client can be used independently - **Extensibility**: Easy to add new tests or commands - **Clean Code**: Well-commented, readable, maintainable ### Error Handling - Graceful error handling in all HTTP requests - Informative error messages - Non-blocking errors (continue testing on failure) ### Logging - Clear console output with color coding - Structured JSON output for results - Detailed mock server logs for debugging ### Testing Philosophy - **Defense in Depth**: Test multiple vulnerability types - **Real-world Scenarios**: Payloads based on actual attacks - **Responsible Testing**: Tools designed for authorized testing only - **Educational**: Code demonstrates both vulnerabilities and mitigations ## Future Enhancements ### Planned Features 1. **Full HTTP Signature Support** - RSA key generation - Signature creation and verification - Key rotation testing 2. **WebFinger Testing** - Account discovery - Resource validation - SSRF via WebFinger 3. **Media Upload Testing** - File upload vulnerabilities - Content-Type confusion - Malicious file detection bypass 4. **Rate Limiting Tests** - Concurrent request flooding - Activity spam detection - Resource exhaustion 5. **Interactive Mode** - Step-by-step testing wizard - Real-time response analysis - Guided security audits 6. **CI/CD Integration** - GitHub Actions workflow - Automated regression testing - Security benchmarking 7. **Reporting** - HTML report generation - PDF export - Vulnerability database integration ## Performance Considerations - **Async Operations**: All HTTP requests are asynchronous - **Timeout Handling**: Configurable timeouts prevent hanging - **Resource Management**: Proper cleanup of connections - **Scalability**: Can test multiple endpoints in parallel ## Security Considerations ### Tool Security - No sensitive data storage - No persistent state by default - Safe defaults (localhost, low timeout) - Clear warnings about authorized testing ### Mock Server Security - Intentionally logs security issues (for demonstration) - Does not execute malicious payloads - Sandboxed environment - No real persistence ## Dependencies - **commander**: CLI argument parsing - **node-fetch**: HTTP client - **chalk**: Terminal colors - **jsonld**: JSON-LD processing - **http-signature**: HTTP signature support (planned) All dependencies are well-maintained and security-audited. ## Contribution Guidelines When extending this project: 1. **Follow the architecture**: Keep separation of concerns 2. **Add tests**: Include example payloads 3. **Document**: Update this file and other docs 4. **Clean code**: Follow existing style 5. **Security first**: Consider implications of new features