Skip to main content

Current Authentication Status

The HeartMAP REST API does not currently implement authentication or authorization. The API is designed for local development and trusted network environments.

Security Considerations

Current Implementation

The API server is built with FastAPI but does not include:
  • API key authentication
  • OAuth2 or JWT tokens
  • User authentication
  • Role-based access control (RBAC)
  • Rate limiting
  • Request signing
If you need to deploy the HeartMAP API in a production or shared environment, consider implementing the following security measures:
Deploy the API behind a firewall or within a private network:
  • Use VPN access for remote users
  • Restrict IP addresses using firewall rules
  • Deploy in a private subnet with no direct internet access
  • Use a bastion host or jump server for access
# Run server on localhost only
uvicorn api_server:app --host 127.0.0.1 --port 8000
Use a reverse proxy like Nginx or Apache with authentication:Example Nginx Configuration:
server {
    listen 443 ssl;
    server_name heartmap-api.example.com;
    
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    
    auth_basic "HeartMAP API";
    auth_basic_user_file /etc/nginx/.htpasswd;
    
    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
Create password file:
htpasswd -c /etc/nginx/.htpasswd username
Access with basic auth:
curl -u username:password https://heartmap-api.example.com/health
Deploy behind an API gateway that handles authentication:
  • AWS API Gateway: Supports IAM, Cognito, Lambda authorizers
  • Kong: Open-source API gateway with authentication plugins
  • Traefik: Modern reverse proxy with middleware support
  • Azure API Management: Enterprise API management service
For development access to remote servers:
# Create SSH tunnel
ssh -L 8000:localhost:8000 user@remote-server

# Access API through tunnel
curl http://localhost:8000/health

Future Authentication Plans

Future versions of HeartMAP may include built-in authentication options:

API Keys

Simple API key-based authentication for service-to-service communication

JWT Tokens

JSON Web Token support for stateless authentication

OAuth2

OAuth2 integration for third-party authentication providers

RBAC

Role-based access control for multi-user environments

Implementing Custom Authentication

If you need to add authentication to your HeartMAP deployment, you can extend the API with FastAPI’s security utilities:

Example: API Key Authentication

from fastapi import Security, HTTPException, status
from fastapi.security import APIKeyHeader

API_KEY = "your-secret-api-key-here"
api_key_header = APIKeyHeader(name="X-API-Key")

async def verify_api_key(api_key: str = Security(api_key_header)):
    if api_key != API_KEY:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid API key"
        )
    return api_key

# Apply to endpoints
@app.post("/analyze", dependencies=[Security(verify_api_key)])
async def analyze_data(...):
    # Your endpoint code
    pass
Usage:
curl -X POST http://localhost:8000/analyze \
  -H "X-API-Key: your-secret-api-key-here" \
  -F "file=@heart_data.h5ad"

Example: JWT Bearer Token

from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import jwt

SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"

security = HTTPBearer()

async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    try:
        payload = jwt.decode(
            credentials.credentials,
            SECRET_KEY,
            algorithms=[ALGORITHM]
        )
        return payload
    except jwt.InvalidTokenError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication token"
        )

# Apply to endpoints
@app.post("/analyze", dependencies=[Depends(verify_token)])
async def analyze_data(...):
    # Your endpoint code
    pass
Usage:
# Get token (implement your own token generation)
TOKEN="your.jwt.token"

curl -X POST http://localhost:8000/analyze \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@heart_data.h5ad"

HTTPS/TLS

Development

For local development, HTTP is sufficient:
uvicorn api_server:app --host 127.0.0.1 --port 8000

Production

For production deployments, always use HTTPS. You can configure Uvicorn with SSL certificates:
uvicorn api_server:app \
  --host 0.0.0.0 \
  --port 443 \
  --ssl-keyfile=/path/to/key.pem \
  --ssl-certfile=/path/to/cert.pem
Or use a reverse proxy (recommended) to handle TLS termination.

Data Security

File Upload Security

The API accepts uploaded .h5ad files. Consider:
1

File Type Validation

Validate that uploaded files are valid AnnData/H5AD format
import scanpy as sc

try:
    adata = sc.read_h5ad(file_path)
except Exception as e:
    raise HTTPException(400, "Invalid H5AD file")
2

File Size Limits

Implement maximum file size limits to prevent DoS attacks
from fastapi import UploadFile, File

MAX_FILE_SIZE = 100 * 1024 * 1024  # 100 MB

@app.post("/analyze")
async def analyze_data(file: UploadFile = File(...)):
    content = await file.read(MAX_FILE_SIZE + 1)
    if len(content) > MAX_FILE_SIZE:
        raise HTTPException(413, "File too large")
3

Temporary File Cleanup

The API already implements temporary file cleanup, but ensure it happens even on errors
try:
    # Process file
    pass
finally:
    Path(tmp_file_path).unlink(missing_ok=True)

Configuration Security

The /config endpoints allow runtime configuration changes. Consider:
  • Restricting which parameters can be modified
  • Validating parameter values and ranges
  • Requiring authentication for configuration changes
  • Logging all configuration modifications

Security Checklist

Before deploying HeartMAP API to production:
  • Deploy behind firewall or in private network
  • Implement authentication (API key, JWT, OAuth2)
  • Enable HTTPS/TLS
  • Configure reverse proxy with security headers
  • Set up rate limiting
  • Implement request size limits
  • Validate all file uploads
  • Enable audit logging
  • Restrict /config endpoint access
  • Use environment variables for secrets
  • Regular security updates for dependencies
  • Monitor for suspicious activity

FastAPI Security

Official FastAPI security documentation

API Endpoints

View all available API endpoints

Build docs developers (and LLMs) love