-
Notifications
You must be signed in to change notification settings - Fork 0
API Overview
This page provides a high-level overview of TMI's API design philosophy, authentication methods, rate limiting, and versioning strategy.
TMI follows RESTful API principles with a focus on:
1. Resource-Oriented Design:
- Resources are nouns (threat_models, threats, diagrams)
- Standard HTTP methods (GET, POST, PUT, PATCH, DELETE)
- Hierarchical resource relationships
2. Consistency:
- Uniform response formats across endpoints
- Consistent error handling
- Standard HTTP status codes
3. Developer Experience:
- Comprehensive OpenAPI specification
- Auto-generated client SDKs
- Clear error messages
- Pagination for large datasets
4. Security First:
- OAuth 2.0 authentication
- Role-based access control
- HMAC signature verification for webhooks
- HTTPS in production
TMI provides two primary API types:
Synchronous HTTP API for CRUD operations on resources.
Base URL:
- Development:
http://localhost:8080 - Production:
https://api.tmi.dev
Specification: OpenAPI 3.0.3
Key Features:
- Full CRUD operations on all resources
- Advanced filtering and pagination
- JSON Patch support for partial updates
- Webhook subscriptions
- Addon invocations
See: REST-API-Reference for detailed endpoint documentation.
Real-time bidirectional communication for collaborative editing.
WebSocket URL:
- Development:
ws://localhost:8080/ws - Production:
wss://api.tmi.dev/ws
Specification: AsyncAPI 2.6.0
Key Features:
- Real-time diagram collaboration
- Presence detection
- Live cursor tracking
- Conflict resolution
- Edit locking
See: WebSocket-API-Reference for detailed protocol documentation.
TMI uses OAuth 2.0 authorization code flow with JWT tokens.
Supported Providers:
- GitHub
- Microsoft (Azure AD)
- SAML
- Custom OAuth providers
Authentication Flow:
1. Client → /auth/{provider}/login
↓
2. Redirect to OAuth provider
↓
3. User authenticates with provider
↓
4. Provider → /auth/{provider}/callback
↓
5. TMI validates and creates session
↓
6. Return JWT token to client
Example:
# 1. Initiate OAuth flow
curl http://localhost:8080/auth/github/login
# Returns redirect URL to GitHub
# 2. User authorizes on GitHub
# GitHub redirects to: /auth/github/callback?code=...
# 3. TMI exchanges code for token
# Returns JWT tokenToken Structure:
{
"sub": "user-uuid",
"email": "[email protected]",
"name": "User Name",
"groups": ["team-security", "team-engineering"],
"exp": 1642185600,
"iat": 1642099200
}Token Claims:
-
sub: User ID (UUID) -
email: User email address -
name: User display name -
groups: User group memberships -
exp: Expiration timestamp -
iat: Issued at timestamp
Token Lifetime: 24 hours (configurable)
Include JWT token in Authorization header:
GET /api/v1/threat-models
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...Token Refresh:
- Tokens expire after 24 hours
- Re-authenticate when token expires
- No refresh token flow (stateless design)
Not Currently Supported
TMI uses OAuth/JWT for all authentication. Long-lived API keys may be added in a future release.
Workaround: Use service accounts with long-lived JWT tokens for automation.
TMI implements a comprehensive tiered rate limiting strategy to protect the API and ensure fair resource allocation.
TMI uses a four-tier rate limiting approach:
- Public Discovery (IP-based, 10 req/min) - Unauthenticated metadata endpoints
- Auth Flows (Multi-scope) - OAuth/SAML with session, IP, and user identifier tracking
- Resource Operations (User-based, 100 req/min, configurable) - Authenticated API endpoints
- Webhooks (User-based, multiple limits, configurable) - Webhook subscriptions and events
- Multi-scope limiting prevents credential stuffing and DoS attacks on auth endpoints
- Per-user configurable quotas support VIP users and integrations
- Database-backed quota storage for webhook and resource operation limits
-
Standard rate limit headers (
X-RateLimit-Limit,X-RateLimit-Remaining,Retry-After) - Graceful degradation when Redis is unavailable
When rate limited, the API returns 429 with retry information:
{
"code": "rate_limit_exceeded",
"message": "Rate limit exceeded: 100 requests per minute. Retry after 45 seconds.",
"details": {
"limit": 100,
"window": "minute",
"retry_after": 45
}
}- ✅ Webhook rate limiting fully implemented (not yet integrated)
- ❌ General API rate limiting specified but not implemented
- ❌ Admin API for quota management planned
See: API-Rate-Limiting for comprehensive rate limiting documentation including client integration examples, multi-scope enforcement details, and database schema.
API Version: 1.0.0
Status: Stable
URL-Based Versioning: Versions included in URL path
Format: /api/v{major}
Examples:
/api/v1/threat-models-
/api/v2/threat-models(future)
Version Support:
- Major versions supported for minimum 12 months after next major release
- Breaking changes require major version increment
- Deprecation warnings provided in advance
Non-Breaking Changes (no version increment):
- Adding new endpoints
- Adding optional request parameters
- Adding response fields
- Adding new event types
- Documentation improvements
Breaking Changes (major version increment):
- Removing endpoints
- Removing request/response fields
- Changing field types
- Changing authentication methods
- Modifying error response formats
When deprecating features:
- Announcement: Minimum 3 months notice
- Documentation: Clear migration path provided
-
Headers:
DeprecationandSunsetheaders on responses - Support: Old version supported during transition
Example Deprecation Header:
HTTP/1.1 200 OK
Deprecation: true
Sunset: Wed, 15 Jun 2025 00:00:00 GMT
Link: <https://api.tmi.dev/docs/migration-v2>; rel="deprecation"Single Resource:
{
"id": "uuid",
"name": "Resource Name",
"created_at": "2025-01-15T10:00:00Z"
}Resource List:
{
"items": [
{"id": "uuid-1", "name": "Item 1"},
{"id": "uuid-2", "name": "Item 2"}
],
"total": 50,
"limit": 20,
"offset": 0
}Empty List:
{
"items": [],
"total": 0,
"limit": 20,
"offset": 0
}Standard Error Format:
{
"error": "error_code",
"message": "Human-readable error message",
"details": {
"field": "Additional context"
}
}Common Error Codes:
4xx Client Errors:
-
400 Bad Request: Invalid request format or parameters -
401 Unauthorized: Missing or invalid authentication token -
403 Forbidden: Insufficient permissions -
404 Not Found: Resource does not exist -
409 Conflict: Resource conflict (e.g., duplicate) -
422 Unprocessable Entity: Validation failed -
429 Too Many Requests: Rate limit exceeded
5xx Server Errors:
-
500 Internal Server Error: Unexpected server error -
503 Service Unavailable: Service temporarily unavailable
Example Validation Error:
{
"error": "validation_failed",
"message": "Request validation failed",
"details": {
"name": "Name is required",
"description": "Description must be at least 10 characters"
}
}Standard Parameters:
-
limit: Number of items to return (default: 50, max: 500) -
offset: Number of items to skip (default: 0)
Example:
GET /api/v1/threat-models?limit=20&offset=40Response:
{
"items": [...],
"total": 150,
"limit": 20,
"offset": 40
}- Use reasonable page sizes: 20-50 items per page
- Cache responses: Reduce API calls
-
Handle empty results: Check
totalbefore iterating - Implement cursor-based pagination: For real-time data (future feature)
Query Parameters: Filter results by field values
Example:
# Filter by owner
GET /api/v1/threat-models?[email protected]
# Filter by date range
GET /api/v1/threat-models?created_after=2025-01-01
# Multiple filters
GET /api/v1/threat-models?[email protected]&created_after=2025-01-01Query Parameter: sort
Format: field or -field (descending)
Example:
# Sort by name ascending
GET /api/v1/threat-models?sort=name
# Sort by created date descending
GET /api/v1/threat-models?sort=-created_at
# Multiple sort fields
GET /api/v1/threat-models?sort=-created_at,nameContent-Type: application/json (required for POST/PUT/PATCH)
Accept: application/json (default)
Accept-Encoding: gzip, deflate (compression supported)
Content-Type: application/json (all responses)
Content-Encoding: gzip (if compression enabled)
ETag: Entity tag for caching
Cache-Control: Cache directives
Status: CORS enabled for browser-based clients
Allowed Origins: Configurable via CORS_ORIGINS environment variable
Allowed Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Allowed Headers: Authorization, Content-Type, X-Request-ID
Credentials: Supported (cookies, authorization headers)
Example Configuration:
export CORS_ORIGINS="https://app.example.com,https://dashboard.example.com"Auto-generated from OpenAPI specification:
Languages:
- Go: go-client-generated
- Java: java-client-generated
- JavaScript: javascript-client-generated
- Python: python-client-generated
Features:
- Type-safe models
- Authentication helpers
- Error handling
- Async/await support (where applicable)
Python:
from tmi_client import TMIClient
# Initialize client
client = TMIClient(
base_url='https://api.tmi.dev',
token='your-jwt-token'
)
# Get threat models
threat_models = client.threat_models.list(limit=10)
# Create threat model
new_tm = client.threat_models.create({
'name': 'My Threat Model',
'description': 'Security analysis'
})Recommended:
- Postman: Import OpenAPI spec
- Insomnia: REST client with GraphQL support
- curl: Command-line testing
- HTTPie: User-friendly curl alternative
X-Request-ID: Trace requests through system
Example:
curl -H "X-Request-ID: custom-trace-123" \
-H "Authorization: Bearer $TOKEN" \
https://api.tmi.dev/api/v1/threat-modelsCheck server logs for request_id=custom-trace-123
Health Check:
GET /healthResponse:
{
"status": "healthy",
"version": "1.0.0",
"timestamp": "2025-01-15T10:00:00Z"
}Readiness Check:
GET /readyChecks database and Redis connectivity.
- Use SDKs: Prefer generated clients over raw HTTP
- Handle Errors: Implement proper error handling
- Cache Responses: Reduce API calls with caching
- Implement Retries: Retry on transient errors (5xx)
- Monitor Usage: Track API usage and errors
- Version Pinning: Pin to specific API version
- Store Tokens Securely: Never commit tokens to source control
- Use HTTPS: Always use HTTPS in production
- Validate Inputs: Sanitize all user inputs
- Least Privilege: Use minimal required permissions
- Rotate Credentials: Regularly rotate secrets and tokens
- Pagination: Use pagination for large datasets
- Filtering: Filter on server side, not client side
- Compression: Enable gzip compression
- Parallel Requests: Make independent requests in parallel
- Connection Pooling: Reuse HTTP connections
- REST-API-Reference - Detailed endpoint documentation
- WebSocket-API-Reference - WebSocket protocol details
- API-Workflows - Common API usage patterns
- API-Integration - Integration guide
- API-Specifications - OpenAPI and AsyncAPI specs
- Setting-Up-Authentication - OAuth configuration
- Using TMI for Threat Modeling
- Accessing TMI
- Creating Your First Threat Model
- Understanding the User Interface
- Working with Data Flow Diagrams
- Managing Threats
- Collaborative Threat Modeling
- Using Notes and Documentation
- Metadata and Extensions
- Planning Your Deployment
- Deploying TMI Server
- Deploying TMI Web Application
- Setting Up Authentication
- Database Setup
- Component Integration
- Post-Deployment
- Monitoring and Health
- Database Operations
- Security Operations
- Performance and Scaling
- Maintenance Tasks