From c2df1fb3c618caca8a991a37994c92a5b1b825ce Mon Sep 17 00:00:00 2001 From: Zhongwei Li Date: Sat, 29 Nov 2025 18:52:40 +0800 Subject: [PATCH] Initial commit --- .claude-plugin/plugin.json | 15 + README.md | 3 + commands/scan-api-security.md | 848 ++++++++++++++++++ plugin.lock.json | 97 ++ skills/skill-adapter/assets/README.md | 7 + .../skill-adapter/assets/config-template.json | 32 + .../assets/example_api_response.json | 75 ++ skills/skill-adapter/assets/owasp_logo.png | 10 + .../skill-adapter/assets/report_template.md | 99 ++ skills/skill-adapter/assets/skill-schema.json | 28 + skills/skill-adapter/assets/test-data.json | 27 + skills/skill-adapter/references/README.md | 8 + .../references/best-practices.md | 69 ++ skills/skill-adapter/references/examples.md | 70 ++ skills/skill-adapter/scripts/README.md | 7 + .../skill-adapter/scripts/helper-template.sh | 42 + skills/skill-adapter/scripts/validation.sh | 32 + 17 files changed, 1469 insertions(+) create mode 100644 .claude-plugin/plugin.json create mode 100644 README.md create mode 100644 commands/scan-api-security.md create mode 100644 plugin.lock.json create mode 100644 skills/skill-adapter/assets/README.md create mode 100644 skills/skill-adapter/assets/config-template.json create mode 100644 skills/skill-adapter/assets/example_api_response.json create mode 100644 skills/skill-adapter/assets/owasp_logo.png create mode 100644 skills/skill-adapter/assets/report_template.md create mode 100644 skills/skill-adapter/assets/skill-schema.json create mode 100644 skills/skill-adapter/assets/test-data.json create mode 100644 skills/skill-adapter/references/README.md create mode 100644 skills/skill-adapter/references/best-practices.md create mode 100644 skills/skill-adapter/references/examples.md create mode 100644 skills/skill-adapter/scripts/README.md create mode 100755 skills/skill-adapter/scripts/helper-template.sh create mode 100755 skills/skill-adapter/scripts/validation.sh diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..0ce9b65 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,15 @@ +{ + "name": "api-security-scanner", + "description": "Scan APIs for security vulnerabilities and OWASP API Top 10", + "version": "1.0.0", + "author": { + "name": "Jeremy Longshore", + "email": "[email protected]" + }, + "skills": [ + "./skills" + ], + "commands": [ + "./commands" + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..2fb6cd7 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# api-security-scanner + +Scan APIs for security vulnerabilities and OWASP API Top 10 diff --git a/commands/scan-api-security.md b/commands/scan-api-security.md new file mode 100644 index 0000000..732c40b --- /dev/null +++ b/commands/scan-api-security.md @@ -0,0 +1,848 @@ +--- +description: Scan API for security vulnerabilities +shortcut: apiscan +--- + +# Scan API Security + +Perform comprehensive automated security scanning to identify OWASP API Security Top 10 vulnerabilities, misconfigurations, and potential attack vectors with detailed remediation guidance. + +## When to Use This Command + +Use `/scan-api-security` when you need to: +- Audit API security before production deployment +- Perform regular security assessments +- Validate security fixes and patches +- Comply with security standards (OWASP, PCI DSS) +- Identify authentication and authorization flaws +- Detect data exposure and injection vulnerabilities + +DON'T use this when: +- Scanning third-party APIs without permission (illegal) +- As a replacement for manual security review (use both) +- Performance testing is the primary goal (use load testing instead) + +## Design Decisions + +This command implements **OWASP ZAP + Custom Scanners** as the primary approach because: +- Industry-standard security testing framework +- Comprehensive vulnerability coverage +- Active and passive scanning modes +- API-specific security checks +- Detailed reporting and remediation guidance +- Integration with CI/CD pipelines + +**Alternative considered: Burp Suite** +- More features for manual testing +- Better for complex authentication flows +- Commercial license required +- Recommended for enterprise environments + +**Alternative considered: Manual testing only** +- More thorough for business logic flaws +- Time-consuming and expensive +- Inconsistent coverage +- Recommended as complement to automated scanning + +## Prerequisites + +Before running this command: +1. API documentation (OpenAPI/Swagger preferred) +2. Test environment with realistic data +3. Authentication credentials for all roles +4. Permission to perform security testing +5. Baseline security requirements defined + +## Implementation Process + +### Step 1: Configure Security Scanner +Set up OWASP ZAP or similar tools with API-specific rules and authentication. + +### Step 2: Perform Automated Scanning +Run comprehensive automated scans for known vulnerability patterns. + +### Step 3: Execute Manual Verification +Verify critical findings and test business logic vulnerabilities. + +### Step 4: Analyze Results +Review findings, eliminate false positives, and prioritize by severity. + +### Step 5: Generate Security Report +Create detailed report with findings, evidence, and remediation steps. + +## Output Format + +The command generates: +- `security-report.html` - Executive summary with charts +- `vulnerabilities.json` - Machine-readable findings +- `evidence/` - Screenshots and request/response logs +- `remediation-guide.md` - Fix recommendations by priority +- `security-tests.py` - Regression tests for found issues +- `compliance-checklist.md` - Standards compliance status + +## Code Examples + +### Example 1: Comprehensive API Security Scanner + +```javascript +// security-scanner.js +const ZAPClient = require('zaproxy'); +const axios = require('axios'); +const jwt = require('jsonwebtoken'); +const { createHash } = require('crypto'); + +class APISecurityScanner { + constructor(apiUrl, options = {}) { + this.apiUrl = apiUrl; + this.zapOptions = { + proxy: options.zapProxy || 'http://localhost:8080', + apiKey: options.zapApiKey || 'your-zap-api-key' + }; + this.zap = new ZAPClient(this.zapOptions); + this.findings = []; + this.credentials = options.credentials || {}; + } + + async runComprehensiveScan() { + console.log('Starting comprehensive API security scan...'); + + try { + // Phase 1: Authentication Testing + await this.testAuthentication(); + + // Phase 2: Authorization Testing + await this.testAuthorization(); + + // Phase 3: Input Validation + await this.testInputValidation(); + + // Phase 4: Data Exposure + await this.testDataExposure(); + + // Phase 5: Rate Limiting + await this.testRateLimiting(); + + // Phase 6: Security Headers + await this.testSecurityHeaders(); + + // Phase 7: OWASP Top 10 API + await this.testOWASPTop10(); + + // Generate report + return this.generateReport(); + } catch (error) { + console.error('Security scan failed:', error); + throw error; + } + } + + async testAuthentication() { + console.log('Testing authentication mechanisms...'); + + const tests = [ + // Test 1: Broken Authentication + { + name: 'JWT Algorithm Confusion', + test: async () => { + const token = jwt.sign({ user: 'admin' }, 'secret', { algorithm: 'HS256' }); + const modifiedToken = token.replace('HS256', 'none'); + + try { + const response = await axios.get(`${this.apiUrl}/protected`, { + headers: { Authorization: `Bearer ${modifiedToken}` } + }); + + if (response.status === 200) { + this.addFinding({ + severity: 'CRITICAL', + category: 'Authentication', + title: 'JWT Algorithm Confusion Vulnerability', + description: 'API accepts JWT tokens with "none" algorithm', + evidence: { token: modifiedToken, response: response.data }, + remediation: 'Explicitly verify JWT algorithm, reject "none"' + }); + } + } catch (error) { + // Expected behavior - authentication should fail + } + } + }, + + // Test 2: Weak Password Policy + { + name: 'Weak Password Policy', + test: async () => { + const weakPasswords = ['123456', 'password', 'admin']; + + for (const password of weakPasswords) { + try { + const response = await axios.post(`${this.apiUrl}/register`, { + username: 'testuser', + password: password + }); + + if (response.status === 201) { + this.addFinding({ + severity: 'HIGH', + category: 'Authentication', + title: 'Weak Password Policy', + description: `API accepts weak password: "${password}"`, + evidence: { password, response: response.status }, + remediation: 'Implement strong password requirements' + }); + } + } catch (error) { + // Good - weak password rejected + } + } + } + }, + + // Test 3: Session Fixation + { + name: 'Session Fixation', + test: async () => { + const fixedSession = 'fixed-session-id-12345'; + + try { + // Try to set a fixed session ID + const response = await axios.post(`${this.apiUrl}/login`, + { username: 'user', password: 'pass' }, + { headers: { 'Cookie': `sessionId=${fixedSession}` } } + ); + + const setCookie = response.headers['set-cookie']; + if (setCookie && setCookie.includes(fixedSession)) { + this.addFinding({ + severity: 'HIGH', + category: 'Authentication', + title: 'Session Fixation Vulnerability', + description: 'API accepts client-provided session IDs', + evidence: { providedSession: fixedSession, setCookie }, + remediation: 'Always generate new session IDs on login' + }); + } + } catch (error) { + // Expected - login might fail + } + } + } + ]; + + for (const test of tests) { + try { + await test.test(); + } catch (error) { + console.error(`Test "${test.name}" failed:`, error.message); + } + } + } + + async testAuthorization() { + console.log('Testing authorization controls...'); + + // Test IDOR vulnerabilities + const userTokens = { + user1: await this.getAuthToken('user1', 'password1'), + user2: await this.getAuthToken('user2', 'password2') + }; + + // Try to access user2's data with user1's token + try { + const response = await axios.get(`${this.apiUrl}/users/user2/profile`, { + headers: { Authorization: `Bearer ${userTokens.user1}` } + }); + + if (response.status === 200) { + this.addFinding({ + severity: 'CRITICAL', + category: 'Authorization', + title: 'Insecure Direct Object Reference (IDOR)', + description: 'User can access other users\' private data', + evidence: { + authenticatedAs: 'user1', + accessedData: 'user2/profile', + response: response.data + }, + remediation: 'Implement proper authorization checks for all resources' + }); + } + } catch (error) { + // Good - access denied + } + + // Test privilege escalation + try { + const response = await axios.post(`${this.apiUrl}/admin/users`, + { role: 'admin' }, + { headers: { Authorization: `Bearer ${userTokens.user1}` } } + ); + + if (response.status === 200) { + this.addFinding({ + severity: 'CRITICAL', + category: 'Authorization', + title: 'Privilege Escalation', + description: 'Regular user can perform admin actions', + evidence: { endpoint: '/admin/users', response: response.status }, + remediation: 'Implement role-based access control (RBAC)' + }); + } + } catch (error) { + // Expected - should be forbidden + } + } + + async testInputValidation() { + console.log('Testing input validation...'); + + const injectionPayloads = { + sql: ["' OR '1'='1", "admin'--", "1; DROP TABLE users--"], + nosql: ['{"$gt": ""}', '{"$ne": null}', '{"$regex": ".*"}'], + command: ['| ls -la', '; cat /etc/passwd', '`whoami`'], + xxe: [']>'], + xss: ['', 'javascript:alert(1)', ''] + }; + + for (const [type, payloads] of Object.entries(injectionPayloads)) { + for (const payload of payloads) { + try { + const response = await axios.post(`${this.apiUrl}/search`, { + query: payload + }); + + // Check if payload appears unescaped in response + if (response.data && JSON.stringify(response.data).includes(payload)) { + this.addFinding({ + severity: 'CRITICAL', + category: 'Injection', + title: `${type.toUpperCase()} Injection Vulnerability`, + description: `API vulnerable to ${type} injection`, + evidence: { payload, response: response.data }, + remediation: `Implement proper input validation and parameterized queries` + }); + } + } catch (error) { + // Error might indicate successful injection prevention + } + } + } + } + + async testDataExposure() { + console.log('Testing for excessive data exposure...'); + + try { + const response = await axios.get(`${this.apiUrl}/users`); + + if (response.data && Array.isArray(response.data)) { + const sensitiveFields = ['password', 'ssn', 'creditCard', 'apiKey', 'secret']; + const exposedFields = []; + + response.data.forEach(user => { + sensitiveFields.forEach(field => { + if (user[field] !== undefined) { + exposedFields.push(field); + } + }); + }); + + if (exposedFields.length > 0) { + this.addFinding({ + severity: 'HIGH', + category: 'Data Exposure', + title: 'Sensitive Data Exposure', + description: 'API returns sensitive fields in responses', + evidence: { exposedFields: [...new Set(exposedFields)] }, + remediation: 'Filter sensitive fields from API responses' + }); + } + } + } catch (error) { + console.error('Data exposure test failed:', error.message); + } + } + + async testRateLimiting() { + console.log('Testing rate limiting...'); + + const endpoint = `${this.apiUrl}/login`; + const requests = []; + const requestCount = 100; + + // Send rapid requests + for (let i = 0; i < requestCount; i++) { + requests.push( + axios.post(endpoint, { + username: 'test', + password: `attempt${i}` + }).catch(err => ({ status: err.response?.status })) + ); + } + + const responses = await Promise.all(requests); + const successfulRequests = responses.filter(r => r.status !== 429).length; + + if (successfulRequests === requestCount) { + this.addFinding({ + severity: 'HIGH', + category: 'Rate Limiting', + title: 'Missing Rate Limiting', + description: 'API endpoints lack rate limiting protection', + evidence: { + endpoint, + requestsSent: requestCount, + successfulRequests + }, + remediation: 'Implement rate limiting on all endpoints' + }); + } + } + + async testSecurityHeaders() { + console.log('Testing security headers...'); + + try { + const response = await axios.get(this.apiUrl); + const headers = response.headers; + + const requiredHeaders = { + 'x-content-type-options': 'nosniff', + 'x-frame-options': 'DENY', + 'x-xss-protection': '1; mode=block', + 'strict-transport-security': 'max-age=31536000', + 'content-security-policy': null // Just check existence + }; + + const missingHeaders = []; + + for (const [header, expectedValue] of Object.entries(requiredHeaders)) { + if (!headers[header]) { + missingHeaders.push(header); + } else if (expectedValue && headers[header] !== expectedValue) { + missingHeaders.push(`${header} (incorrect value)`); + } + } + + if (missingHeaders.length > 0) { + this.addFinding({ + severity: 'MEDIUM', + category: 'Security Headers', + title: 'Missing Security Headers', + description: 'Important security headers are missing', + evidence: { missingHeaders }, + remediation: 'Add all recommended security headers' + }); + } + } catch (error) { + console.error('Security headers test failed:', error.message); + } + } + + async testOWASPTop10() { + console.log('Running OWASP API Security Top 10 tests...'); + + // Use ZAP for comprehensive scanning + await this.zap.core.newSession('api-security-scan', true); + await this.zap.core.setMode('attack'); + + // Configure context + const contextId = await this.zap.context.newContext('API Context'); + await this.zap.context.includeInContext(contextId, `${this.apiUrl}.*`); + + // Run active scan + const scanId = await this.zap.ascan.scan(this.apiUrl, true, true); + + // Wait for scan completion + let progress = 0; + while (progress < 100) { + progress = await this.zap.ascan.status(scanId); + await this.delay(5000); + console.log(`Scan progress: ${progress}%`); + } + + // Get results + const alerts = await this.zap.core.alerts(this.apiUrl); + + alerts.forEach(alert => { + this.addFinding({ + severity: this.mapZAPSeverity(alert.risk), + category: 'OWASP Scan', + title: alert.name, + description: alert.description, + evidence: { + url: alert.url, + param: alert.param, + attack: alert.attack, + evidence: alert.evidence + }, + remediation: alert.solution + }); + }); + } + + addFinding(finding) { + this.findings.push({ + ...finding, + timestamp: new Date().toISOString(), + id: createHash('md5').update(JSON.stringify(finding)).digest('hex') + }); + } + + mapZAPSeverity(risk) { + const mapping = { + 'High': 'CRITICAL', + 'Medium': 'HIGH', + 'Low': 'MEDIUM', + 'Informational': 'LOW' + }; + return mapping[risk] || 'MEDIUM'; + } + + async getAuthToken(username, password) { + try { + const response = await axios.post(`${this.apiUrl}/login`, { + username, + password + }); + return response.data.token; + } catch (error) { + console.error(`Failed to authenticate ${username}`); + return null; + } + } + + delay(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); + } + + generateReport() { + const report = { + scanDate: new Date().toISOString(), + targetAPI: this.apiUrl, + summary: { + total: this.findings.length, + critical: this.findings.filter(f => f.severity === 'CRITICAL').length, + high: this.findings.filter(f => f.severity === 'HIGH').length, + medium: this.findings.filter(f => f.severity === 'MEDIUM').length, + low: this.findings.filter(f => f.severity === 'LOW').length + }, + findings: this.findings, + recommendations: this.generateRecommendations() + }; + + // Save report + require('fs').writeFileSync( + 'security-report.json', + JSON.stringify(report, null, 2) + ); + + console.log('\nSecurity Scan Complete!'); + console.log(`Total findings: ${report.summary.total}`); + console.log(`Critical: ${report.summary.critical}`); + console.log(`High: ${report.summary.high}`); + + return report; + } + + generateRecommendations() { + const recommendations = []; + + if (this.findings.some(f => f.category === 'Authentication')) { + recommendations.push({ + priority: 1, + title: 'Strengthen Authentication', + actions: [ + 'Implement MFA for sensitive operations', + 'Use secure session management', + 'Enforce strong password policies' + ] + }); + } + + if (this.findings.some(f => f.category === 'Authorization')) { + recommendations.push({ + priority: 1, + title: 'Implement Proper Authorization', + actions: [ + 'Use role-based access control (RBAC)', + 'Validate user permissions for each request', + 'Implement resource-level authorization' + ] + }); + } + + return recommendations; + } +} + +// Usage +const scanner = new APISecurityScanner('https://api.example.com', { + credentials: { + admin: { username: 'admin', password: 'admin123' }, + user: { username: 'user', password: 'user123' } + }, + zapProxy: 'http://localhost:8080', + zapApiKey: 'your-zap-api-key' +}); + +scanner.runComprehensiveScan() + .then(report => { + console.log('Security scan completed successfully'); + // Send report via email or integrate with issue tracker + }) + .catch(error => { + console.error('Security scan failed:', error); + process.exit(1); + }); +``` + +### Example 2: Python Security Testing Framework + +```python +# api_security_scanner.py +import requests +import json +import hashlib +import time +from typing import Dict, List, Any +from dataclasses import dataclass, asdict +from enum import Enum +import jwt +import base64 +from urllib.parse import urlparse + +class Severity(Enum): + CRITICAL = "CRITICAL" + HIGH = "HIGH" + MEDIUM = "MEDIUM" + LOW = "LOW" + INFO = "INFO" + +@dataclass +class SecurityFinding: + severity: Severity + category: str + title: str + description: str + evidence: Dict[str, Any] + remediation: str + cwe_id: str = None + owasp_category: str = None + +class APISecurityTester: + def __init__(self, base_url: str, auth_token: str = None): + self.base_url = base_url + self.session = requests.Session() + if auth_token: + self.session.headers['Authorization'] = f'Bearer {auth_token}' + self.findings: List[SecurityFinding] = [] + + def run_security_tests(self): + """Run comprehensive security test suite.""" + print("Starting API Security Testing...") + + test_suites = [ + self.test_broken_authentication, + self.test_broken_authorization, + self.test_excessive_data_exposure, + self.test_lack_of_resources_rate_limiting, + self.test_security_misconfiguration, + self.test_injection_vulnerabilities, + self.test_improper_assets_management, + self.test_insufficient_logging + ] + + for test_suite in test_suites: + try: + test_suite() + except Exception as e: + print(f"Test suite failed: {e}") + + return self.generate_report() + + def test_injection_vulnerabilities(self): + """Test for various injection vulnerabilities.""" + print("Testing for injection vulnerabilities...") + + # SQL Injection payloads + sql_payloads = [ + "' OR '1'='1", + "admin'--", + "' UNION SELECT * FROM users--", + "1' AND '1' = '1" + ] + + # Test each endpoint with injection payloads + endpoints = ['/search', '/users', '/products'] + + for endpoint in endpoints: + for payload in sql_payloads: + try: + response = self.session.get( + f"{self.base_url}{endpoint}", + params={'q': payload} + ) + + # Check for SQL error messages in response + error_indicators = [ + 'SQL syntax', + 'mysql_fetch', + 'ORA-01', + 'PostgreSQL', + 'SQLite' + ] + + response_text = response.text.lower() + for indicator in error_indicators: + if indicator.lower() in response_text: + self.add_finding( + severity=Severity.CRITICAL, + category="Injection", + title="SQL Injection Vulnerability", + description=f"Endpoint {endpoint} vulnerable to SQL injection", + evidence={ + "endpoint": endpoint, + "payload": payload, + "indicator": indicator + }, + remediation="Use parameterized queries", + cwe_id="CWE-89" + ) + break + + except Exception as e: + pass + + def test_broken_authentication(self): + """Test for authentication vulnerabilities.""" + print("Testing authentication mechanisms...") + + # Test JWT vulnerabilities + test_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" + + # Try token with 'none' algorithm + header = base64.urlsafe_b64encode( + json.dumps({"alg": "none", "typ": "JWT"}).encode() + ).decode().rstrip('=') + + payload = test_token.split('.')[1] + none_token = f"{header}.{payload}." + + response = self.session.get( + f"{self.base_url}/profile", + headers={'Authorization': f'Bearer {none_token}'} + ) + + if response.status_code == 200: + self.add_finding( + severity=Severity.CRITICAL, + category="Authentication", + title="JWT None Algorithm Vulnerability", + description="API accepts JWT tokens with 'none' algorithm", + evidence={"token": none_token[:50] + "..."}, + remediation="Explicitly verify JWT algorithm", + cwe_id="CWE-347" + ) + + def add_finding(self, **kwargs): + """Add a security finding to the results.""" + finding = SecurityFinding(**kwargs) + self.findings.append(finding) + print(f" Found: {finding.title} ({finding.severity.value})") + + def generate_report(self) -> Dict[str, Any]: + """Generate comprehensive security report.""" + report = { + "scan_date": time.strftime("%Y-%m-%d %H:%M:%S"), + "target_api": self.base_url, + "total_findings": len(self.findings), + "severity_breakdown": { + "CRITICAL": len([f for f in self.findings if f.severity == Severity.CRITICAL]), + "HIGH": len([f for f in self.findings if f.severity == Severity.HIGH]), + "MEDIUM": len([f for f in self.findings if f.severity == Severity.MEDIUM]), + "LOW": len([f for f in self.findings if f.severity == Severity.LOW]) + }, + "findings": [asdict(f) for f in self.findings] + } + + # Save report + with open("security_report.json", "w") as f: + json.dump(report, f, indent=2) + + print(f"\nSecurity scan complete. Found {len(self.findings)} issues.") + return report + +# Usage example +if __name__ == "__main__": + scanner = APISecurityTester("https://api.example.com") + report = scanner.run_security_tests() + print(f"Report saved to security_report.json") +``` + +## Error Handling + +| Error | Cause | Solution | +|-------|-------|----------| +| "Connection refused to ZAP" | ZAP proxy not running | Start ZAP daemon on configured port | +| "Permission denied" | No authorization for security testing | Obtain written permission before scanning | +| "Rate limited during scan" | Too many requests | Reduce scan speed, add delays | +| "False positive findings" | Overly aggressive rules | Manually verify and tune scanner rules | +| "Incomplete scan results" | Scan timeout | Increase timeout, scan in phases | + +## Configuration Options + +**Scan Modes** +- `passive`: Non-intrusive scanning only +- `active`: Full vulnerability testing +- `targeted`: Focus on specific vulnerabilities +- `compliance`: Check against standards + +**Authentication Types** +- `bearer`: JWT/OAuth tokens +- `basic`: Username/password +- `apikey`: API key authentication +- `certificate`: Client certificates + +## Best Practices + +DO: +- Always get written permission before scanning +- Test in non-production environments first +- Verify findings manually to eliminate false positives +- Document all security tests performed +- Prioritize fixes based on severity and exploitability +- Retest after implementing fixes + +DON'T: +- Scan production APIs during peak hours +- Ignore low-severity findings (defense in depth) +- Share vulnerability details publicly +- Rely solely on automated scanning +- Skip retesting after remediation + +## Security Standards Compliance + +**OWASP API Security Top 10 (2023)** +1. Broken Object Level Authorization +2. Broken Authentication +3. Broken Object Property Level Authorization +4. Unrestricted Resource Consumption +5. Broken Function Level Authorization +6. Unrestricted Access to Sensitive Business Flows +7. Server Side Request Forgery +8. Security Misconfiguration +9. Improper Inventory Management +10. Unsafe Consumption of APIs + +## Related Commands + +- `/api-authentication-builder` - Implement secure authentication +- `/api-rate-limiter` - Add rate limiting protection +- `/api-monitoring-dashboard` - Monitor security events +- `/api-response-validator` - Validate API responses + +## Version History + +- v1.0.0 (2024-10): Initial implementation with OWASP API Top 10 coverage +- Planned v1.1.0: Add GraphQL and gRPC security testing \ No newline at end of file diff --git a/plugin.lock.json b/plugin.lock.json new file mode 100644 index 0000000..3a87c84 --- /dev/null +++ b/plugin.lock.json @@ -0,0 +1,97 @@ +{ + "$schema": "internal://schemas/plugin.lock.v1.json", + "pluginId": "gh:jeremylongshore/claude-code-plugins-plus:plugins/api-development/api-security-scanner", + "normalized": { + "repo": null, + "ref": "refs/tags/v20251128.0", + "commit": "30fc4cd4a937d5a996650fbbcca81c1d019e20b7", + "treeHash": "33acc0d74439f698d79167eadf392772554741e8c54f034d1439e739642d6540", + "generatedAt": "2025-11-28T10:18:08.842124Z", + "toolVersion": "publish_plugins.py@0.2.0" + }, + "origin": { + "remote": "git@github.com:zhongweili/42plugin-data.git", + "branch": "master", + "commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390", + "repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data" + }, + "manifest": { + "name": "api-security-scanner", + "description": "Scan APIs for security vulnerabilities and OWASP API Top 10", + "version": "1.0.0" + }, + "content": { + "files": [ + { + "path": "README.md", + "sha256": "7e415dbbab9f5532e0b9bfb6c35b0393e9f7d30c62197b48c83d6777e47e2e3c" + }, + { + "path": ".claude-plugin/plugin.json", + "sha256": "90998c7b79da2adec697714364621d2287138290f5913fb4f336a882ff843e40" + }, + { + "path": "commands/scan-api-security.md", + "sha256": "0ac77d782b14f255f2e0801fb02d25f118115280722343f1075184a9a771e5be" + }, + { + "path": "skills/skill-adapter/references/examples.md", + "sha256": "922bbc3c4ebf38b76f515b5c1998ebde6bf902233e00e2c5a0e9176f975a7572" + }, + { + "path": "skills/skill-adapter/references/best-practices.md", + "sha256": "c8f32b3566252f50daacd346d7045a1060c718ef5cfb07c55a0f2dec5f1fb39e" + }, + { + "path": "skills/skill-adapter/references/README.md", + "sha256": "14a0e4c7da8db0b91b4531d305ba012cc378545c65a67e71e578f92cb4c072a3" + }, + { + "path": "skills/skill-adapter/scripts/helper-template.sh", + "sha256": "0881d5660a8a7045550d09ae0acc15642c24b70de6f08808120f47f86ccdf077" + }, + { + "path": "skills/skill-adapter/scripts/validation.sh", + "sha256": "92551a29a7f512d2036e4f1fb46c2a3dc6bff0f7dde4a9f699533e446db48502" + }, + { + "path": "skills/skill-adapter/scripts/README.md", + "sha256": "5c3e56f1be69677ceec2977e2c1543ededffcadb4a5e2fec1dc53ac534f6e68a" + }, + { + "path": "skills/skill-adapter/assets/test-data.json", + "sha256": "ac17dca3d6e253a5f39f2a2f1b388e5146043756b05d9ce7ac53a0042eee139d" + }, + { + "path": "skills/skill-adapter/assets/owasp_logo.png", + "sha256": "ba3b97f76a81ac510a917c5c82f5882e69da3fb8cda9e775314f0f2262d615ed" + }, + { + "path": "skills/skill-adapter/assets/report_template.md", + "sha256": "117d1bad24ab396604afb2e0cb20b7bfef3fe0557dd0b6c3d8165da16367f8dc" + }, + { + "path": "skills/skill-adapter/assets/README.md", + "sha256": "d0747d6b7b8b17b59a5b9d92b53206f420db2249e40b7911b9c5ac607c198973" + }, + { + "path": "skills/skill-adapter/assets/skill-schema.json", + "sha256": "f5639ba823a24c9ac4fb21444c0717b7aefde1a4993682897f5bf544f863c2cd" + }, + { + "path": "skills/skill-adapter/assets/example_api_response.json", + "sha256": "8499f096b427d91e4f2505fdaf0508c44341a28635b3d803a79673105c98b268" + }, + { + "path": "skills/skill-adapter/assets/config-template.json", + "sha256": "0c2ba33d2d3c5ccb266c0848fc43caa68a2aa6a80ff315d4b378352711f83e1c" + } + ], + "dirSha256": "33acc0d74439f698d79167eadf392772554741e8c54f034d1439e739642d6540" + }, + "security": { + "scannedAt": null, + "scannerVersion": null, + "flags": [] + } +} \ No newline at end of file diff --git a/skills/skill-adapter/assets/README.md b/skills/skill-adapter/assets/README.md new file mode 100644 index 0000000..702a61a --- /dev/null +++ b/skills/skill-adapter/assets/README.md @@ -0,0 +1,7 @@ +# Assets + +Bundled resources for api-security-scanner skill + +- [ ] report_template.md: Markdown template for generating the API security scan report. +- [ ] example_api_response.json: Example API response to demonstrate the structure and format of API data. +- [ ] owasp_logo.png: OWASP logo for inclusion in the report. diff --git a/skills/skill-adapter/assets/config-template.json b/skills/skill-adapter/assets/config-template.json new file mode 100644 index 0000000..16f1712 --- /dev/null +++ b/skills/skill-adapter/assets/config-template.json @@ -0,0 +1,32 @@ +{ + "skill": { + "name": "skill-name", + "version": "1.0.0", + "enabled": true, + "settings": { + "verbose": false, + "autoActivate": true, + "toolRestrictions": true + } + }, + "triggers": { + "keywords": [ + "example-trigger-1", + "example-trigger-2" + ], + "patterns": [] + }, + "tools": { + "allowed": [ + "Read", + "Grep", + "Bash" + ], + "restricted": [] + }, + "metadata": { + "author": "Plugin Author", + "category": "general", + "tags": [] + } +} diff --git a/skills/skill-adapter/assets/example_api_response.json b/skills/skill-adapter/assets/example_api_response.json new file mode 100644 index 0000000..dbb6c88 --- /dev/null +++ b/skills/skill-adapter/assets/example_api_response.json @@ -0,0 +1,75 @@ +{ + "_comment": "Example API response from a security scan", + "scan_id": "api-scan-2024-10-27-123456", + "target_url": "https://example.com/api/v1", + "scan_start_time": "2024-10-27T14:00:00Z", + "scan_end_time": "2024-10-27T14:15:00Z", + "scan_status": "completed", + "vulnerabilities": [ + { + "vulnerability_id": "API1:2023 Broken Object Level Authorization", + "name": "Broken Object Level Authorization", + "severity": "High", + "description": "API endpoints are vulnerable to broken object level authorization. Attackers can access objects belonging to other users by manipulating object IDs.", + "owasp_category": "OWASP API Security Top 10", + "cwe_id": "CWE-285", + "affected_endpoint": "/users/{user_id}", + "http_method": "GET", + "parameter": "user_id", + "payload": "12345", + "evidence": "Returned user data for user_id 98765 when authenticated as user_id 12345.", + "remediation": "Implement proper authorization checks to ensure users can only access objects they own or have permission to access. Use parameterized queries and avoid direct object references. Consider using a Role-Based Access Control (RBAC) system.", + "references": [ + "https://owasp.org/API-Security/editions/2023/en/0xa1-broken-object-level-authorization/", + "https://cwe.mitre.org/data/definitions/285.html" + ], + "status": "open" + }, + { + "vulnerability_id": "API4:2023 Unrestricted Resource Consumption", + "name": "Unrestricted Resource Consumption", + "severity": "Medium", + "description": "API is vulnerable to unrestricted resource consumption. Attackers can exhaust server resources by sending a large number of requests or large payloads.", + "owasp_category": "OWASP API Security Top 10", + "cwe_id": "CWE-400", + "affected_endpoint": "/search", + "http_method": "POST", + "parameter": "query", + "payload": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "evidence": "Server response time increased significantly after sending a large number of requests with large payloads.", + "remediation": "Implement rate limiting, pagination, and input validation to prevent resource exhaustion. Consider using a Content Delivery Network (CDN) to cache static content.", + "references": [ + "https://owasp.org/API-Security/editions/2023/en/0xa4-unrestricted-access-to-sensitive-business-flows/", + "https://cwe.mitre.org/data/definitions/400.html" + ], + "status": "open" + }, + { + "_comment": "Example of a low severity issue", + "vulnerability_id": "API9:2023 Improper Assets Management", + "name": "Improper Assets Management", + "severity": "Low", + "description": "API lacks proper assets management. Debug endpoints are exposed in production.", + "owasp_category": "OWASP API Security Top 10", + "cwe_id": "CWE-1173", + "affected_endpoint": "/debug/healthcheck", + "http_method": "GET", + "parameter": null, + "payload": null, + "evidence": "Debug endpoint /debug/healthcheck is accessible without authentication in production.", + "remediation": "Disable or remove debug endpoints from production environment. Implement proper authentication and authorization for sensitive endpoints.", + "references": [ + "https://owasp.org/API-Security/editions/2023/en/0xa9-improper-assets-management/", + "https://cwe.mitre.org/data/definitions/1173.html" + ], + "status": "open" + } + ], + "scan_summary": { + "total_vulnerabilities": 3, + "high_severity": 1, + "medium_severity": 1, + "low_severity": 1, + "info_severity": 0 + } +} \ No newline at end of file diff --git a/skills/skill-adapter/assets/owasp_logo.png b/skills/skill-adapter/assets/owasp_logo.png new file mode 100644 index 0000000..ea7c929 --- /dev/null +++ b/skills/skill-adapter/assets/owasp_logo.png @@ -0,0 +1,10 @@ +// This is a placeholder for the OWASP logo. +// To replace this placeholder with the actual OWASP logo: +// 1. Download the OWASP logo in PNG format from the official OWASP website (https://owasp.org/www-project-top-ten/). +// 2. Open this file (owasp_logo.png) in an image editor (e.g., GIMP, Photoshop, Paint.NET). +// 3. Replace the placeholder content with the downloaded OWASP logo. +// 4. Ensure the file is saved as a PNG with the same name (owasp_logo.png). +// +// This logo will be used in the API Security Scanner report to visually represent the OWASP API Top 10 vulnerabilities. + +iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQMAAACQp+OdAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwKANUAAAASUVORK5CYII= \ No newline at end of file diff --git a/skills/skill-adapter/assets/report_template.md b/skills/skill-adapter/assets/report_template.md new file mode 100644 index 0000000..036d9f3 --- /dev/null +++ b/skills/skill-adapter/assets/report_template.md @@ -0,0 +1,99 @@ +# API Security Scan Report + +**API Endpoint:** [Insert API Endpoint Here, e.g., `https://api.example.com/v1/users`] + +**Scan Date:** [Insert Date Here, e.g., `2024-10-27`] + +**Report Generated By:** api-security-scanner@claude-code-plugins-plus + +**Report ID:** [Insert a unique Report ID here for tracking, e.g., `API-SCAN-20241027-001`] + +## Executive Summary + +[Provide a brief overview of the scan results. Highlight the most critical vulnerabilities and their potential impact. For example: `This scan identified several high-severity vulnerabilities, including Broken Authentication and Injection flaws. Immediate remediation is recommended to prevent unauthorized access and data breaches.`] + +## Vulnerability Details + +This section provides detailed information about each vulnerability identified during the scan, including its severity, description, and recommended remediation steps. + +### 1. [Vulnerability Title, e.g., Broken Authentication] + +* **OWASP API Security Top 10 Category:** [e.g., API1:2023 Broken Object Level Authorization] +* **Severity:** [e.g., High, Medium, Low, Informational] +* **Description:** [Provide a detailed explanation of the vulnerability. For example: `The API endpoint is vulnerable to Broken Authentication due to weak password policies and the absence of multi-factor authentication. Attackers can potentially gain unauthorized access to user accounts by brute-forcing passwords.`] +* **Affected Endpoint(s):** [List the specific API endpoints affected by the vulnerability. For example: `/api/login`, `/api/reset-password`] +* **Request Example:** + + ``` + POST /api/login + Content-Type: application/json + + { + "username": "testuser", + "password": "weakpassword" + } + ``` +* **Response Example:** + + ``` + { + "status": "success", + "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." + } + ``` +* **Impact:** [Describe the potential impact of the vulnerability. For example: `Successful exploitation could allow attackers to access sensitive user data, perform actions on behalf of users, and potentially compromise the entire system.`] +* **Recommendation:** [Provide specific and actionable remediation steps. For example: `Implement strong password policies, enforce multi-factor authentication, and implement rate limiting to prevent brute-force attacks.`] +* **Evidence:** [Provide evidence or proof of concept that demonstrates the vulnerability. This could include screenshots, logs, or code snippets. Be mindful of sensitive information.] + +### 2. [Vulnerability Title, e.g., Injection Vulnerability] + +* **OWASP API Security Top 10 Category:** [e.g., API2:2023 Broken User Authentication] +* **Severity:** [e.g., High, Medium, Low, Informational] +* **Description:** [Provide a detailed explanation of the vulnerability. For example: `The API endpoint is vulnerable to SQL injection due to insufficient input validation. Attackers can potentially execute arbitrary SQL queries by injecting malicious code into input fields.`] +* **Affected Endpoint(s):** [List the specific API endpoints affected by the vulnerability. For example: `/api/users/{id}`] +* **Request Example:** + + ``` + GET /api/users/1' OR '1'='1 + ``` +* **Response Example:** [Show the unexpected response indicating injection success, or an error message revealing the backend technology.] +* **Impact:** [Describe the potential impact of the vulnerability. For example: `Successful exploitation could allow attackers to access, modify, or delete sensitive data from the database, potentially leading to data breaches and system compromise.`] +* **Recommendation:** [Provide specific and actionable remediation steps. For example: `Implement proper input validation, use parameterized queries or prepared statements, and apply the principle of least privilege to database access.`] +* **Evidence:** [Provide evidence or proof of concept that demonstrates the vulnerability. This could include screenshots, logs, or code snippets. Be mindful of sensitive information.] + +### 3. [Vulnerability Title, e.g., Excessive Data Exposure] + +* **OWASP API Security Top 10 Category:** [e.g., API3:2023 Excessive Data Exposure] +* **Severity:** [e.g., High, Medium, Low, Informational] +* **Description:** [Provide a detailed explanation of the vulnerability. For example: `The API endpoint returns more data than necessary, potentially exposing sensitive user information to unauthorized parties.`] +* **Affected Endpoint(s):** [List the specific API endpoints affected by the vulnerability. For example: `/api/profile`] +* **Request Example:** + + ``` + GET /api/profile + ``` +* **Response Example:** + + ```json + { + "id": 123, + "username": "testuser", + "email": "testuser@example.com", + "phone_number": "555-123-4567", + "address": "123 Main St", + "credit_card_number": "XXXXXXXXXXXXXXXX" + } + ``` +* **Impact:** [Describe the potential impact of the vulnerability. For example: `Exposure of sensitive data could lead to identity theft, financial fraud, and privacy violations.`] +* **Recommendation:** [Provide specific and actionable remediation steps. For example: `Implement data filtering and masking to return only the necessary data to the client. Avoid exposing sensitive information such as credit card numbers and social security numbers.`] +* **Evidence:** [Provide evidence or proof of concept that demonstrates the vulnerability. This could include screenshots, logs, or code snippets. Be mindful of sensitive information.] + +**(Repeat the above section for each identified vulnerability)** + +## Conclusion + +[Summarize the overall security posture of the API based on the scan results. Emphasize the importance of addressing the identified vulnerabilities and provide recommendations for ongoing security testing and monitoring. For example: `The API has several critical vulnerabilities that require immediate attention. Addressing these vulnerabilities is crucial to protect sensitive data and prevent potential security breaches. Regular security scans and penetration testing are recommended to maintain a strong security posture.`] + +## Disclaimer + +This report is based on the results of an automated security scan and should be used as a starting point for further investigation and remediation. It is important to manually verify the findings and implement appropriate security measures to mitigate the identified vulnerabilities. The effectiveness of the remediation steps depends on the specific implementation and configuration of the API. \ No newline at end of file diff --git a/skills/skill-adapter/assets/skill-schema.json b/skills/skill-adapter/assets/skill-schema.json new file mode 100644 index 0000000..8dc154c --- /dev/null +++ b/skills/skill-adapter/assets/skill-schema.json @@ -0,0 +1,28 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Claude Skill Configuration", + "type": "object", + "required": ["name", "description"], + "properties": { + "name": { + "type": "string", + "pattern": "^[a-z0-9-]+$", + "maxLength": 64, + "description": "Skill identifier (lowercase, hyphens only)" + }, + "description": { + "type": "string", + "maxLength": 1024, + "description": "What the skill does and when to use it" + }, + "allowed-tools": { + "type": "string", + "description": "Comma-separated list of allowed tools" + }, + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+$", + "description": "Semantic version (x.y.z)" + } + } +} diff --git a/skills/skill-adapter/assets/test-data.json b/skills/skill-adapter/assets/test-data.json new file mode 100644 index 0000000..f0cd871 --- /dev/null +++ b/skills/skill-adapter/assets/test-data.json @@ -0,0 +1,27 @@ +{ + "testCases": [ + { + "name": "Basic activation test", + "input": "trigger phrase example", + "expected": { + "activated": true, + "toolsUsed": ["Read", "Grep"], + "success": true + } + }, + { + "name": "Complex workflow test", + "input": "multi-step trigger example", + "expected": { + "activated": true, + "steps": 3, + "toolsUsed": ["Read", "Write", "Bash"], + "success": true + } + } + ], + "fixtures": { + "sampleInput": "example data", + "expectedOutput": "processed result" + } +} diff --git a/skills/skill-adapter/references/README.md b/skills/skill-adapter/references/README.md new file mode 100644 index 0000000..dbf419d --- /dev/null +++ b/skills/skill-adapter/references/README.md @@ -0,0 +1,8 @@ +# References + +Bundled resources for api-security-scanner skill + +- [ ] owasp_api_top_10.md: Detailed documentation of each OWASP API Security Top 10 vulnerability, including examples and attack vectors. +- [ ] api_security_best_practices.md: A guide to API security best practices, covering topics such as authentication, authorization, input validation, and error handling. +- [ ] api_schema_example.json: Example API schema to demonstrate how to define and validate API endpoints. +- [ ] api_scan_configuration.md: Documentation on how to configure the API security scanner, including setting scan parameters, defining target APIs, and specifying authentication methods. diff --git a/skills/skill-adapter/references/best-practices.md b/skills/skill-adapter/references/best-practices.md new file mode 100644 index 0000000..3505048 --- /dev/null +++ b/skills/skill-adapter/references/best-practices.md @@ -0,0 +1,69 @@ +# Skill Best Practices + +Guidelines for optimal skill usage and development. + +## For Users + +### Activation Best Practices + +1. **Use Clear Trigger Phrases** + - Match phrases from skill description + - Be specific about intent + - Provide necessary context + +2. **Provide Sufficient Context** + - Include relevant file paths + - Specify scope of analysis + - Mention any constraints + +3. **Understand Tool Permissions** + - Check allowed-tools in frontmatter + - Know what the skill can/cannot do + - Request appropriate actions + +### Workflow Optimization + +- Start with simple requests +- Build up to complex workflows +- Verify each step before proceeding +- Use skill consistently for related tasks + +## For Developers + +### Skill Development Guidelines + +1. **Clear Descriptions** + - Include explicit trigger phrases + - Document all capabilities + - Specify limitations + +2. **Proper Tool Permissions** + - Use minimal necessary tools + - Document security implications + - Test with restricted tools + +3. **Comprehensive Documentation** + - Provide usage examples + - Document common pitfalls + - Include troubleshooting guide + +### Maintenance + +- Keep version updated +- Test after tool updates +- Monitor user feedback +- Iterate on descriptions + +## Performance Tips + +- Scope skills to specific domains +- Avoid overlapping trigger phrases +- Keep descriptions under 1024 chars +- Test activation reliability + +## Security Considerations + +- Never include secrets in skill files +- Validate all inputs +- Use read-only tools when possible +- Document security requirements diff --git a/skills/skill-adapter/references/examples.md b/skills/skill-adapter/references/examples.md new file mode 100644 index 0000000..b1d8bd2 --- /dev/null +++ b/skills/skill-adapter/references/examples.md @@ -0,0 +1,70 @@ +# Skill Usage Examples + +This document provides practical examples of how to use this skill effectively. + +## Basic Usage + +### Example 1: Simple Activation + +**User Request:** +``` +[Describe trigger phrase here] +``` + +**Skill Response:** +1. Analyzes the request +2. Performs the required action +3. Returns results + +### Example 2: Complex Workflow + +**User Request:** +``` +[Describe complex scenario] +``` + +**Workflow:** +1. Step 1: Initial analysis +2. Step 2: Data processing +3. Step 3: Result generation +4. Step 4: Validation + +## Advanced Patterns + +### Pattern 1: Chaining Operations + +Combine this skill with other tools: +``` +Step 1: Use this skill for [purpose] +Step 2: Chain with [other tool] +Step 3: Finalize with [action] +``` + +### Pattern 2: Error Handling + +If issues occur: +- Check trigger phrase matches +- Verify context is available +- Review allowed-tools permissions + +## Tips & Best Practices + +- ✅ Be specific with trigger phrases +- ✅ Provide necessary context +- ✅ Check tool permissions match needs +- ❌ Avoid vague requests +- ❌ Don't mix unrelated tasks + +## Common Issues + +**Issue:** Skill doesn't activate +**Solution:** Use exact trigger phrases from description + +**Issue:** Unexpected results +**Solution:** Check input format and context + +## See Also + +- Main SKILL.md for full documentation +- scripts/ for automation helpers +- assets/ for configuration examples diff --git a/skills/skill-adapter/scripts/README.md b/skills/skill-adapter/scripts/README.md new file mode 100644 index 0000000..3b1944a --- /dev/null +++ b/skills/skill-adapter/scripts/README.md @@ -0,0 +1,7 @@ +# Scripts + +Bundled resources for api-security-scanner skill + +- [ ] api_scan.py: Script to perform the API security scan, handling authentication, request building, and response parsing. +- [ ] report_generator.py: Script to generate a formatted report (e.g., Markdown, JSON) of the scan results. +- [ ] remediation_guidance.py: Script to provide specific remediation steps based on the identified vulnerabilities. diff --git a/skills/skill-adapter/scripts/helper-template.sh b/skills/skill-adapter/scripts/helper-template.sh new file mode 100755 index 0000000..c4aae90 --- /dev/null +++ b/skills/skill-adapter/scripts/helper-template.sh @@ -0,0 +1,42 @@ +#!/bin/bash +# Helper script template for skill automation +# Customize this for your skill's specific needs + +set -e + +function show_usage() { + echo "Usage: $0 [options]" + echo "" + echo "Options:" + echo " -h, --help Show this help message" + echo " -v, --verbose Enable verbose output" + echo "" +} + +# Parse arguments +VERBOSE=false + +while [[ $# -gt 0 ]]; do + case $1 in + -h|--help) + show_usage + exit 0 + ;; + -v|--verbose) + VERBOSE=true + shift + ;; + *) + echo "Unknown option: $1" + show_usage + exit 1 + ;; + esac +done + +# Your skill logic here +if [ "$VERBOSE" = true ]; then + echo "Running skill automation..." +fi + +echo "✅ Complete" diff --git a/skills/skill-adapter/scripts/validation.sh b/skills/skill-adapter/scripts/validation.sh new file mode 100755 index 0000000..590af58 --- /dev/null +++ b/skills/skill-adapter/scripts/validation.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# Skill validation helper +# Validates skill activation and functionality + +set -e + +echo "🔍 Validating skill..." + +# Check if SKILL.md exists +if [ ! -f "../SKILL.md" ]; then + echo "❌ Error: SKILL.md not found" + exit 1 +fi + +# Validate frontmatter +if ! grep -q "^---$" "../SKILL.md"; then + echo "❌ Error: No frontmatter found" + exit 1 +fi + +# Check required fields +if ! grep -q "^name:" "../SKILL.md"; then + echo "❌ Error: Missing 'name' field" + exit 1 +fi + +if ! grep -q "^description:" "../SKILL.md"; then + echo "❌ Error: Missing 'description' field" + exit 1 +fi + +echo "✅ Skill validation passed"