Skip to content

API Overview

Eric Fitzgerald edited this page Nov 21, 2025 · 2 revisions

API Overview

This page provides a high-level overview of TMI's API design philosophy, authentication methods, rate limiting, and versioning strategy.

API Design Philosophy

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

API Types

TMI provides two primary API types:

REST API

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.

WebSocket API

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.

Authentication

OAuth 2.0 Flow

TMI uses OAuth 2.0 authorization code flow with JWT tokens.

Supported Providers:

  • GitHub
  • Google
  • 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 token

JWT Tokens

Token Structure:

{
  "sub": "user-uuid",
  "email": "user@example.com",
  "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)

Using Tokens

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)

API Key Authentication

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.

Rate Limiting

TMI implements a comprehensive tiered rate limiting strategy to protect the API and ensure fair resource allocation.

Rate Limiting Strategy

TMI uses a four-tier rate limiting approach:

  1. Public Discovery (IP-based, 10 req/min) - Unauthenticated metadata endpoints
  2. Auth Flows (Multi-scope) - OAuth/SAML with session, IP, and user identifier tracking
  3. Resource Operations (User-based, 100 req/min, configurable) - Authenticated API endpoints
  4. Webhooks (User-based, multiple limits, configurable) - Webhook subscriptions and events

Key Features

  • 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

Rate Limit Response

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
  }
}

Implementation Status

  • ✅ 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.

Versioning

Current Version

API Version: 1.0.0

Status: Stable

Versioning Strategy

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

Breaking vs Non-Breaking Changes

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

Deprecation Policy

When deprecating features:

  1. Announcement: Minimum 3 months notice
  2. Documentation: Clear migration path provided
  3. Headers: Deprecation and Sunset headers on responses
  4. 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"

Response Formats

Success Responses

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
}

Error Responses

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"
  }
}

Pagination

Query Parameters

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=40

Response:

{
  "items": [...],
  "total": 150,
  "limit": 20,
  "offset": 40
}

Pagination Best Practices

  1. Use reasonable page sizes: 20-50 items per page
  2. Cache responses: Reduce API calls
  3. Handle empty results: Check total before iterating
  4. Implement cursor-based pagination: For real-time data (future feature)

Filtering and Sorting

Filtering

Query Parameters: Filter results by field values

Example:

# Filter by owner
GET /api/v1/threat-models?owner=user@example.com

# Filter by date range
GET /api/v1/threat-models?created_after=2025-01-01

# Multiple filters
GET /api/v1/threat-models?owner=user@example.com&created_after=2025-01-01

Sorting

Query 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,name

Content Negotiation

Request Headers

Content-Type: application/json (required for POST/PUT/PATCH)

Accept: application/json (default)

Accept-Encoding: gzip, deflate (compression supported)

Response Headers

Content-Type: application/json (all responses)

Content-Encoding: gzip (if compression enabled)

ETag: Entity tag for caching

Cache-Control: Cache directives

CORS

Cross-Origin Requests

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"

SDKs and Client Libraries

Generated SDKs

Auto-generated from OpenAPI specification:

Languages:

Features:

  • Type-safe models
  • Authentication helpers
  • Error handling
  • Async/await support (where applicable)

SDK Example

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'
})

Testing and Debugging

API Testing Tools

Recommended:

  • Postman: Import OpenAPI spec
  • Insomnia: REST client with GraphQL support
  • curl: Command-line testing
  • HTTPie: User-friendly curl alternative

Debug Headers

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-models

Check server logs for request_id=custom-trace-123

Health Endpoints

Health Check:

GET /health

Response:

{
  "status": "healthy",
  "version": "1.0.0",
  "timestamp": "2025-01-15T10:00:00Z"
}

Readiness Check:

GET /ready

Checks database and Redis connectivity.

Best Practices

API Integration

  1. Use SDKs: Prefer generated clients over raw HTTP
  2. Handle Errors: Implement proper error handling
  3. Cache Responses: Reduce API calls with caching
  4. Implement Retries: Retry on transient errors (5xx)
  5. Monitor Usage: Track API usage and errors
  6. Version Pinning: Pin to specific API version

Security

  1. Store Tokens Securely: Never commit tokens to source control
  2. Use HTTPS: Always use HTTPS in production
  3. Validate Inputs: Sanitize all user inputs
  4. Least Privilege: Use minimal required permissions
  5. Rotate Credentials: Regularly rotate secrets and tokens

Performance

  1. Pagination: Use pagination for large datasets
  2. Filtering: Filter on server side, not client side
  3. Compression: Enable gzip compression
  4. Parallel Requests: Make independent requests in parallel
  5. Connection Pooling: Reuse HTTP connections

Related Documentation

Clone this wiki locally