Authentication and Security

Guide to authentication and secure connection setup for the User API.

Authentication Overview

The Manta platform uses JWT (JSON Web Token) authentication for API access. Each API call requires a valid token that identifies the user and their permissions.

Obtaining Tokens

From Dashboard

  1. Log into the Manta dashboard

  2. Navigate to Profile → API Tokens

  3. Click “Generate New Token”

  4. Copy the token (it won’t be shown again)

From Administrator

Your organization’s Manta administrator can provide tokens with specific permissions.

Initializing the API

Basic Authentication

from manta import UserAPI

# Initialize with token
api = UserAPI(
    token="your_jwt_token",
    host="platform.manta.io",
    port=50052
)

Secure Connection (mTLS)

from manta import UserAPI

# Initialize with certificates
api = UserAPI(
    token="your_jwt_token",
    host="platform.manta.io",
    port=50052,
    cert_folder="/path/to/certificates"
)

Token Management

Token Validation

# Check if token is valid
try:
    api = UserAPI(token=token, host=host, port=port)
    if api.is_available():
        user = api.get_user()
        print(f"Token valid for user: {user['username']}")
except AuthenticationError:
    print("Invalid token")

Token Expiration

import jwt
from datetime import datetime

def check_token_expiry(token):
    """Check when token expires"""
    try:
        # Decode without verification (just to read exp)
        decoded = jwt.decode(token, options={"verify_signature": False})
        exp_timestamp = decoded.get('exp')

        if exp_timestamp:
            expiry = datetime.fromtimestamp(exp_timestamp)
            remaining = expiry - datetime.now()
            print(f"Token expires in: {remaining}")
            return remaining.total_seconds() > 0
    except Exception as e:
        print(f"Error checking token: {e}")
        return False

Token Refresh

def refresh_token(api, refresh_token):
    """Refresh expired token"""
    try:
        # Request new token
        new_token = api.refresh_token(refresh_token)

        # Reinitialize API with new token
        api = UserAPI(
            token=new_token,
            host=api.host,
            port=api.port
        )
        return api
    except Exception as e:
        print(f"Failed to refresh token: {e}")
        return None

Secure Storage

Environment Variables

import os
from manta import UserAPI

# Store token in environment
os.environ["MANTA_TOKEN"] = "your_jwt_token"

# Read from environment
token = os.environ.get("MANTA_TOKEN")
if not token:
    raise ValueError("MANTA_TOKEN not set")

api = UserAPI(token=token, host="localhost", port=50052)

Configuration File

import configparser
from pathlib import Path

# Save token to config
config = configparser.ConfigParser()
config['auth'] = {'token': 'your_jwt_token'}

config_path = Path.home() / '.manta' / 'credentials.ini'
config_path.parent.mkdir(exist_ok=True)

with open(config_path, 'w') as f:
    config.write(f)

# Set file permissions (Unix/Linux)
import os
os.chmod(config_path, 0o600)  # Read/write for owner only

Keyring Storage

import keyring

# Store token in system keyring
keyring.set_password("manta", "api_token", "your_jwt_token")

# Retrieve token
token = keyring.get_password("manta", "api_token")

api = UserAPI(token=token, host="localhost", port=50052)

Certificate Management

For enhanced security, use mTLS (mutual TLS) authentication:

Certificate Structure

/path/to/certificates/
├── ca.crt          # Certificate Authority
├── client.crt      # Client certificate
└── client.key      # Client private key

Using Certificates

from manta import UserAPI

api = UserAPI(
    token="your_jwt_token",
    host="secure.manta.io",
    port=50052,
    cert_folder="/path/to/certificates"
)

# The API will automatically use:
# - ca.crt for server verification
# - client.crt and client.key for client authentication

Permission Scopes

Tokens can have different permission scopes:

# Check user permissions
user = api.get_user()
permissions = user.get('permissions', [])

if 'cluster:create' in permissions:
    # User can create clusters
    pass

if 'swarm:deploy' in permissions:
    # User can deploy swarms
    pass

Common Permission Scopes

  • cluster:read - View cluster information

  • cluster:write - Modify clusters

  • swarm:deploy - Deploy swarms

  • swarm:stop - Stop running swarms

  • module:upload - Upload new modules

  • results:read - Access results

  • admin:* - Full administrative access

Security Best Practices

1. Token Security

# DON'T hardcode tokens
# BAD
api = UserAPI(token="eyJhbGciOiJIUzI1NiIs...")

# GOOD - Use environment variables or secure storage
token = os.environ.get("MANTA_TOKEN")
api = UserAPI(token=token, host=host, port=port)

2. Secure Transmission

# Always use HTTPS/TLS in production
api = UserAPI(
    token=token,
    host="platform.manta.io",  # Uses HTTPS
    port=443,
    verify_ssl=True  # Verify server certificate
)

3. Token Rotation

import schedule

def rotate_token():
    """Rotate token periodically"""
    global api
    new_token = request_new_token()  # Your token refresh logic
    api = UserAPI(token=new_token, host=host, port=port)

# Schedule token rotation
schedule.every(7).days.do(rotate_token)

4. Audit Logging

import logging

# Enable audit logging
logging.basicConfig(
    filename='manta_api_audit.log',
    level=logging.INFO,
    format='%(asctime)s - %(message)s'
)

def audit_api_call(operation, **kwargs):
    """Log API operations for audit"""
    logging.info(f"API Operation: {operation}, Args: {kwargs}")

# Wrap API calls
def deploy_swarm_with_audit(api, cluster_id, swarm):
    audit_api_call("deploy_swarm", cluster_id=cluster_id)
    return api.deploy_swarm(cluster_id, swarm)

Error Handling

from manta.errors import AuthenticationError, TokenExpiredError

try:
    api = UserAPI(token=token, host=host, port=port)
    result = api.get_user()

except AuthenticationError as e:
    print(f"Authentication failed: {e}")
    # Invalid token - request new one

except TokenExpiredError as e:
    print(f"Token expired: {e}")
    # Refresh token

except Exception as e:
    print(f"Unexpected error: {e}")

Multi-Environment Setup

class MantaEnvironment:
    """Manage multiple environment configurations"""

    ENVIRONMENTS = {
        "dev": {
            "host": "dev.manta.io",
            "port": 50052,
            "token_env": "MANTA_DEV_TOKEN"
        },
        "staging": {
            "host": "staging.manta.io",
            "port": 50052,
            "token_env": "MANTA_STAGING_TOKEN"
        },
        "prod": {
            "host": "platform.manta.io",
            "port": 443,
            "token_env": "MANTA_PROD_TOKEN",
            "cert_folder": "/etc/manta/certs"
        }
    }

    @classmethod
    def get_api(cls, environment="dev"):
        """Get API for specific environment"""
        config = cls.ENVIRONMENTS[environment]
        token = os.environ.get(config["token_env"])

        if not token:
            raise ValueError(f"Token not found for {environment}")

        return UserAPI(
            token=token,
            host=config["host"],
            port=config["port"],
            cert_folder=config.get("cert_folder")
        )

# Usage
api_dev = MantaEnvironment.get_api("dev")
api_prod = MantaEnvironment.get_api("prod")

Next Steps