Skip to content

Commit 8eb85f4

Browse files
committed
feat: add readme
1 parent 8a06178 commit 8eb85f4

File tree

1 file changed

+295
-0
lines changed

1 file changed

+295
-0
lines changed
Lines changed: 295 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,295 @@
1+
# GraphScope Sandbox API Key Authentication
2+
3+
## Overview
4+
5+
A simple and secure API Key authentication system for GraphScope Sandbox service, protecting both REST API endpoints and MCP (Model Context Protocol) server.
6+
7+
## Features
8+
9+
- βœ… **API Key Authentication**: Bearer token-based authentication
10+
- βœ… **Express & MCP Support**: Protects both HTTP API and MCP protocol
11+
- βœ… **Multiple Key Support**: Single or multiple API keys configuration
12+
- βœ… **Path Filtering**: Health checks and specific paths can skip authentication
13+
- βœ… **Security Logging**: Detailed authentication logs with key masking
14+
- βœ… **Key Generation Tool**: Built-in CLI tool for generating secure API keys
15+
16+
## Quick Setup
17+
18+
### 1. Generate API Key
19+
20+
```bash
21+
# Generate a single API key
22+
npm run generate-api-key
23+
24+
# Generate multiple API keys
25+
npm run generate-api-key -- --count 3
26+
27+
# Generate with custom prefix
28+
npm run generate-api-key -- --prefix my_app
29+
```
30+
31+
### 2. Configure Environment
32+
33+
```bash
34+
# Single API key
35+
export SANDBOX_API_KEY="ai-spider_your_generated_key_here"
36+
37+
# Multiple API keys (comma separated)
38+
export SANDBOX_API_KEYS="key1,key2,key3"
39+
40+
# Or create .env file
41+
echo 'SANDBOX_API_KEY=ai-spider_your_generated_key_here' > .env
42+
```
43+
44+
### 3. Start Services
45+
46+
```bash
47+
# Start Express API server (port 3000)
48+
npm run dev
49+
50+
# Start MCP server (port 3001)
51+
npm run dev:mcp
52+
```
53+
54+
## Usage Examples
55+
56+
### REST API Calls
57+
58+
```bash
59+
# Health check (no auth required)
60+
curl http://localhost:3000/health
61+
62+
# Create sandbox (auth required)
63+
curl -X POST http://localhost:3000/api/sandbox \
64+
-H "Authorization: Bearer ai-spider_your_api_key_here" \
65+
-H "Content-Type: application/json" \
66+
-d '{"image": "node:18"}'
67+
```
68+
69+
### MCP Client Configuration
70+
71+
```json
72+
{
73+
"mcpServers": {
74+
"graphscope-sandbox": {
75+
"url": "http://localhost:3001/mcp",
76+
"headers": {
77+
"Authorization": "Bearer ai-spider_your_api_key_here"
78+
}
79+
}
80+
}
81+
}
82+
```
83+
84+
### JavaScript/Node.js
85+
86+
```javascript
87+
const API_KEY = "ai-spider_your_api_key_here";
88+
const API_BASE = "http://localhost:3000/api";
89+
90+
const response = await fetch(`${API_BASE}/sandbox`, {
91+
method: "POST",
92+
headers: {
93+
Authorization: `Bearer ${API_KEY}`,
94+
"Content-Type": "application/json"
95+
},
96+
body: JSON.stringify({ image: "node:18" })
97+
});
98+
```
99+
100+
## Architecture
101+
102+
### Components
103+
104+
```
105+
πŸ“ src/middleware/
106+
β”œβ”€β”€ simple-auth.ts # Authentication middleware
107+
πŸ“ src/
108+
β”œβ”€β”€ server.ts # Express server with auth
109+
β”œβ”€β”€ mcp/transport.ts # MCP server with auth
110+
πŸ“ scripts/
111+
β”œβ”€β”€ generate-api-key.cjs # API key generation tool
112+
```
113+
114+
### Authentication Flow
115+
116+
```mermaid
117+
graph TD
118+
A[Client Request] --> B{Has Authorization Header?}
119+
B -->|No| C[401 Unauthorized]
120+
B -->|Yes| D{Format: Bearer <key>?}
121+
D -->|No| C
122+
D -->|Yes| E{Valid API Key?}
123+
E -->|No| C
124+
E -->|Yes| F[Request Allowed]
125+
```
126+
127+
### Protected Endpoints
128+
129+
| Endpoint Pattern | Protection | Description |
130+
| ---------------- | ---------- | ---------------------- |
131+
| `/health` | ❌ None | Health check |
132+
| `/api/*` | βœ… API Key | All API endpoints |
133+
| MCP Server | βœ… API Key | Model Context Protocol |
134+
135+
## Configuration Options
136+
137+
### Environment Variables
138+
139+
| Variable | Type | Description | Example |
140+
| ------------------ | ------ | ------------------------------- | --------------------- |
141+
| `SANDBOX_API_KEY` | String | Single API key | `ai-spider_abc123...` |
142+
| `SANDBOX_API_KEYS` | String | Multiple keys (comma-separated) | `key1,key2,key3` |
143+
144+
### API Key Format
145+
146+
```
147+
<prefix>_<32_random_chars>
148+
```
149+
150+
- **Prefix**: `ai-spider` (configurable)
151+
- **Length**: 32 alphanumeric characters
152+
- **Example**: `ai-spider_K8jHn2mP9xQvR7sT3wY6zA1bC4dF5gE0`
153+
154+
## Security Features
155+
156+
### πŸ”’ Authentication Protection
157+
158+
- **Bearer Token**: Standard `Authorization: Bearer <token>` format
159+
- **Key Validation**: Exact match validation against configured keys
160+
- **Request Logging**: All authentication attempts are logged
161+
- **Key Masking**: Only first 8 characters logged for security
162+
163+
### πŸ›‘οΈ Error Handling
164+
165+
| Error | Status | Description |
166+
| --------------------- | ------ | ---------------------------- |
167+
| Missing Authorization | 401 | No `Authorization` header |
168+
| Invalid Format | 401 | Wrong header format |
169+
| Invalid Key | 401 | API key not recognized |
170+
| Server Error | 500 | Authentication service error |
171+
172+
### πŸ“Š Logging Examples
173+
174+
```
175+
# Successful authentication
176+
[INFO] API key authentication successful { ip: '127.0.0.1', path: '/api/sandbox', keyPrefix: 'ai-spide...' }
177+
178+
# Failed authentication
179+
[WARN] Invalid API key attempt { ip: '127.0.0.1', path: '/api/sandbox', keyPrefix: 'invalid...' }
180+
```
181+
182+
## Testing
183+
184+
### Verify Setup
185+
186+
```bash
187+
# Test health endpoint (should work)
188+
curl -I http://localhost:3000/health
189+
190+
# Test API without auth (should fail with 401)
191+
curl -I http://localhost:3000/api/sandbox
192+
193+
# Test API with auth (should work with POST data)
194+
curl -I -H "Authorization: Bearer $SANDBOX_API_KEY" \
195+
http://localhost:3000/api/sandbox
196+
```
197+
198+
### Expected Responses
199+
200+
```bash
201+
# No auth - 401 Unauthorized
202+
{
203+
"error": {
204+
"code": "MISSING_AUTH",
205+
"message": "Authorization header is required. Use: Authorization: Bearer <your-api-key>"
206+
}
207+
}
208+
209+
# Invalid key - 401 Unauthorized
210+
{
211+
"error": {
212+
"code": "INVALID_API_KEY",
213+
"message": "Invalid API key"
214+
}
215+
}
216+
```
217+
218+
## Implementation Details
219+
220+
### Middleware Structure
221+
222+
```typescript
223+
// Authentication middleware
224+
export const simpleApiKeyAuth = (req, res, next) => {
225+
// 1. Check Authorization header
226+
// 2. Validate Bearer format
227+
// 3. Verify API key
228+
// 4. Log attempt
229+
// 5. Allow/deny request
230+
};
231+
232+
// Conditional authentication
233+
export const conditionalAuth = (req, res, next) => {
234+
// Skip auth for health checks
235+
// Apply auth for API routes
236+
};
237+
```
238+
239+
### Key Features
240+
241+
- **Path Filtering**: `/health` endpoint bypasses authentication
242+
- **Multiple Keys**: Support both single and multiple API key configurations
243+
- **Secure Logging**: API keys are masked in logs (only show first 8 chars)
244+
- **Error Messages**: Clear, actionable error messages for debugging
245+
- **Environment Config**: Flexible configuration via environment variables
246+
247+
## Migration from Unauthenticated
248+
249+
### Before (Insecure)
250+
251+
```bash
252+
curl http://localhost:3000/api/sandbox # ❌ Works without auth
253+
```
254+
255+
### After (Secure)
256+
257+
```bash
258+
curl http://localhost:3000/api/sandbox # ❌ 401 Unauthorized
259+
curl -H "Authorization: Bearer <key>" http://localhost:3000/api/sandbox # βœ… Works
260+
```
261+
262+
## Security Best Practices
263+
264+
1. **πŸ” Keep Keys Secret**: Never commit API keys to version control
265+
2. **πŸ”„ Rotate Regularly**: Change API keys periodically
266+
3. **🌍 Environment Separation**: Use different keys for dev/staging/prod
267+
4. **πŸ“ Monitor Usage**: Check logs for suspicious authentication attempts
268+
5. **🚫 No Hardcoding**: Always use environment variables for keys
269+
270+
## Troubleshooting
271+
272+
### Common Issues
273+
274+
| Problem | Solution |
275+
| --------------------------- | ---------------------------------------------------------------- |
276+
| "No API keys configured" | Set `SANDBOX_API_KEY` or `SANDBOX_API_KEYS` environment variable |
277+
| Authentication always fails | Check API key format and environment variable name |
278+
| MCP client can't connect | Ensure client config includes `Authorization` header |
279+
280+
### Debug Commands
281+
282+
```bash
283+
# Check if API key is set
284+
echo ${SANDBOX_API_KEY:0:8}...
285+
286+
# View authentication logs
287+
tail -f logs/sandbox.log | grep -E "(authentication|API key)"
288+
289+
# Test key generation
290+
npm run generate-api-key
291+
```
292+
293+
---
294+
295+
**πŸš€ Ready to deploy!** Your GraphScope Sandbox is now secured with API Key authentication.

0 commit comments

Comments
Β (0)