Python client SDK for AI Fabrix authentication, authorization, and logging
pip install miso-client==5.2.3 Copy PIP instructions
The AI Fabrix Miso Client SDK provides authentication, authorization, and logging for Python applications integrated with the AI Fabrix platform.
await init_secrets() provides one server-side startup API for local credentials and opt-in client-credential bootstrap. Unset or local mode works with existing controllers. See Secret initialization for configuration, rotation and controller requirements.
pip install miso-client Step 2: Create .env MISO_CLIENTID=ctrl-dev-my-app MISO_CLIENTSECRET=your-secret MISO_CONTROLLER_URL=http://localhost:3000 REDIS_HOST=localhost Step 3: Use It from miso_client import MisoClient, load_config client = MisoClient(load_config()) await client.initialize() is_valid = await client.validate_token(token) That's it! You now have authentication, roles, and logging.
First time? You'll need Keycloak and Miso Controller running.
# Start infrastructure (Postgres, Redis) aifabrix up # Install Keycloak for authentication aifabrix create keycloak --port 8082 --database --template platform aifabrix build keycloak aifabrix run keycloak # Install Miso Controller aifabrix create miso-controller --port 3000 --database --redis --template platform aifabrix build miso-controller aifabrix run miso-controller → Infrastructure Guide
Already have Keycloak and Controller? Use the Quick Start above.
What happens: Your app validates user tokens from Keycloak.
from miso_client import MisoClient, load_config # Create client (loads from .env automatically) client = MisoClient(load_config()) await client.initialize() # Get token from request (helper method) token = client.get_token(req) if token: is_valid = await client.validate_token(token) if is_valid: user = await client.get_user(token) print('User:', user) Where to get tokens? Users authenticate via Keycloak, then your app receives JWTs in the Authorization header.
Two-token model: The SDK uses a client token (obtained once from the controller with client id/secret, sent as x-client-token on all API requests) and a user token (sent as Authorization: Bearer for user-scoped operations). Only the client token endpoint receives client id/secret; all other APIs use the client token.
User token lifecycle contract (hard cutover): The SDK exposes helpers for token-expiration normalization and adaptive refresh scheduling. Legacy token storage helper API has been removed.
from miso_client import ( normalize_expires_at, get_jwt_expires_at, get_effective_user_token_refresh_buffer, get_user_token_refresh_due_at, is_user_token_refresh_due, is_user_token_expired, ) Refresh endpoint boundary: Token-based refresh in Python SDK flows uses POST /api/v1/auth/login/device/refresh with body refreshToken (via AuthApi.refresh_device_code_token(...)). Browser session refresh remains POST /api/v1/auth/refresh with no refreshToken body (via AuthApi.refresh_session_token()). Hard-cut contract uses explicit methods only (no ambiguous generic refresh entrypoint and no strict-path response fallback parsing).
Browser-only activity controls (N/A for Python SDK runtime): Activity-driven session refresh listener controls are part of browser DataClient behavior (TypeScript SDK / frontend runtime) and are not implemented by miso-client-python. Python SDK parity work focuses on shared request-driven auth/session contract semantics.
Session-cookie refresh for server-side consumers: When a browser opens your API directly, it sends only the miso_access_token cookie, whose access token lives a few minutes. validate_or_refresh_session_cookie(token) validates that cookie token and, only when it has expired, renews the browser session through Miso POST /api/v1/auth/refresh (once per expired token). Add the returned set_cookie to your response so the browser keeps the renewed cookie. Bearer-header tokens are never refreshed this way.
from miso_client import apply_session_cookie token = client.get_session_cookie_token(request) result = await client.validate_or_refresh_session_cookie(token) if not result.valid: raise HTTPException(status_code=401) apply_session_cookie(response, result) # no-op unless the session was renewed → Browser-session cookie refresh
Request-driven migration and rollback (Python runtime):
Token exchange (delegated tokens): If your app has an external token (from an external identity provider), call exchange_token(delegated_token) to get a Keycloak token for use with the SDK: result = await client.exchange_token(delegated_token) then use result.accessToken for validate_token, get_roles, etc.
Validate application token (client token): To verify a controller-issued application token (e.g. x-client-token from your backend or dataplane), use validate_client_token(token). Results are cached to avoid extra controller calls. Use for dataplane or services that need to check an app token: result = await client.validate_client_token(app_token) then check result.data.authenticated and result.data.application, result.data.expiresAt, etc.
What happens: Check user roles to control access. Roles are cached in Redis for performance.
→ Complete RBAC example → AI Fabrix Builder Quick Start
What happens: Application logs are sent to the Miso Controller with client token authentication. All HTTP requests are automatically audited with ISO 27001 compliant data masking.
ISO 27001 Compliance: All HTTP requests are automatically audited with sensitive data masked. Configure audit logging behavior using AuditConfig:
→ Complete logging example → Logging Reference
What happens: The SDK provides a unified logging interface with minimal API (1-3 parameters maximum) and automatic context extraction. This eliminates the need to manually pass Request objects or context dictionaries.
from fastapi import FastAPI from miso_client import get_logger from miso_client.utils.fastapi_logger_middleware import logger_context_middleware app = FastAPI() # Add middleware early in middleware chain (after auth middleware) app.middleware("http")(logger_context_middleware) @app.get("/api/users") async def get_users(): logger = get_logger() # Auto-detects context from contextvars await logger.info("Users list accessed") # Auto-extracts request context users = await fetch_users() return users Flask Setup from flask import Flask from miso_client import get_logger from miso_client.utils.flask_logger_middleware import register_logger_context_middleware app = Flask(__name__) # Register middleware register_logger_context_middleware(app) @app.route("/api/users") async def get_users(): logger = get_logger() # Auto-detects context from contextvars await logger.info("Users list accessed") # Auto-extracts request context users = await fetch_users() return users Service Layer Usage from miso_client import get_logger class UserService: async def get_user(self, user_id: str): logger = get_logger() # Uses contextvars context if available await logger.info("Fetching user") # Auto-extracts context if available try: user = await db.user.find_unique({"id": user_id}) await logger.audit("ACCESS", "User", user_id) # Read access audit return user except Exception as error: await logger.error("Failed to fetch user", error) # Auto-extracts error details raise Background Job Usage from miso_client import get_logger, set_logger_context async def background_job(): # Set context for this async execution context set_logger_context({ "jobId": "job-123", "jobType": "sync", }) logger = get_logger() await logger.info("Background job started") # All logs in this async context will use the set context await process_data() UnifiedLogger Methods:
What happens: Create audit trails for compliance and security monitoring.
What happens: Use encryption for sensitive data and generic caching for improved performance.
# Add to .env ENCRYPTION_KEY=your-32-byte-encryption-key → API Reference → Cache Methods
What happens: When API_KEY is set in your .env file, you can authenticate requests using the API key as a bearer token, bypassing OAuth2 authentication. This is useful for testing without setting up Keycloak.
# Add to .env for testing API_KEY=your-test-api-key-here Important:
Sensitive fields are configured via miso_client/utils/sensitive_fields_config.json. You can customize this by:
The default configuration includes ISO 27001 compliant sensitive fields:
Field-name matching is case-insensitive and ignores _ and -. The sensitive token value matches only a complete normalized field name, so VALUE and v_a_l_u_e are masked while ordinary composite names such as totalValue and defaultValue remain visible unless they match another sensitive token. Add a genuinely sensitive composite name explicitly under fields in custom configuration. Python DataMasker does not currently consume fieldPatterns.
Masking JSON documents (for other projects): Use DataMasker to mask sensitive fields in any JSON structure before logging or sending to external systems:
from miso_client import DataMasker doc = {"user": "john", "password": "secret123", "email": "john@example.com"} masked = DataMasker.mask_sensitive_data(doc) # {"user": "john", "password": "***MASKED***", "email": "john@example.com"} Audit Logging Configuration:
Configure audit logging behavior using AuditConfig (see Configuration section above):
The SDK uses a two-layer HTTP client architecture for ISO 27001 compliance:
aifabrix create myapp --port 3000 --database --language python Login to controller:
aifabrix app register myapp --environment dev Start development and then deploy to your chosen runtime.
What happens: The SDK automatically parses structured error responses from the API (RFC 7807-style format) and makes them available through the MisoClientError and ApiErrorException exceptions.
The ErrorResponse model follows RFC 7807-style format:
{ "errors": [ "The user has provided input that the browser is unable to convert.", "There are multiple rows in the database for the same value" ], "type": "/Errors/Bad Input", "title": "Bad Request", "statusCode": 400, "instance": "/OpenApi/rest/Xzy" } Features:
from miso_client import ErrorResponse # Create ErrorResponse from dict error_data = { "errors": ["Validation failed"], "type": "/Errors/Validation", "title": "Validation Error", "statusCode": 422, "instance": "/api/endpoint" } error_response = ErrorResponse(**error_data) # Access fields print(error_response.errors) # ["Validation failed"] print(error_response.type) # "/Errors/Validation" print(error_response.title) # "Validation Error" print(error_response.statusCode) # 422 print(error_response.instance) # "/api/endpoint" Pagination, Filtering, and Sorting Utilities What happens: The SDK provides reusable utilities for pagination, filtering, sorting, and error handling that work with any API endpoint.
from miso_client import ( parsePaginationParams, parse_pagination_params, createPaginatedListResponse, PaginatedListResponse, ) # Parse pagination from query parameters (returns dict with currentPage/pageSize keys) params = {"page": "1", "pageSize": "20"} pagination = parsePaginationParams(params) # Returns: {"currentPage": 1, "pageSize": 20} # Parse pagination from query parameters (returns tuple with page/page_size) page, page_size = parse_pagination_params({"page": "1", "page_size": "20"}) # Returns: (1, 20) # Create paginated response items = [{"id": 1}, {"id": 2}] response = createPaginatedListResponse( items, totalItems=120, currentPage=1, pageSize=20, type="item" ) # Response structure: # { # "meta": { # "totalItems": 120, # "currentPage": 1, # "pageSize": 20, # "type": "item" # }, # "data": [{"id": 1}, {"id": 2}] # } Filtering Filter Operators: eq, neq, in, nin, gt, lt, gte, lte, contains, like
Filter Format: field:op:value (e.g., status:eq:active)
from miso_client import FilterBuilder, parse_filter_params, build_query_string # Dynamic filter building with FilterBuilder filter_builder = FilterBuilder() \ .add('status', 'eq', 'active') \ .add('region', 'in', ['eu', 'us']) \ .add('created_at', 'gte', '2024-01-01') # Get query string query_string = filter_builder.to_query_string() # Returns: "filter=status:eq:active&filter=region:in:eu,us&filter=created_at:gte:2024-01-01" # Parse existing filter parameters params = {'filter': ['status:eq:active', 'region:in:eu,us']} filters = parse_filter_params(params) # Returns: [FilterOption(field='status', op='eq', value='active'), ...] # Use with HTTP client response = await client.http_client.get_with_filters( '/api/items', filter_builder=filter_builder ) Building Complete Filter Queries:
from miso_client import FilterQuery, FilterOption, build_query_string # Create filter query with filters, sort, pagination, and fields filter_query = FilterQuery( filters=[ FilterOption(field='status', op='eq', value='active'), FilterOption(field='region', op='in', value=['eu', 'us']) ], sort=['-updated_at', 'created_at'], page=1, pageSize=20, # Note: camelCase for API compatibility fields=['id', 'name', 'status'] ) # Build query string query_string = build_query_string(filter_query) Sorting Sort Format: -field for descending, field for ascending (e.g., -updated_at, created_at)
from miso_client import parse_sort_params, build_sort_string, SortOption # Parse sort parameters params = {'sort': '-updated_at'} sort_options = parse_sort_params(params) # Returns: [SortOption(field='updated_at', order='desc')] # Parse multiple sorts params = {'sort': ['-updated_at', 'created_at']} sort_options = parse_sort_params(params) # Returns: [ # SortOption(field='updated_at', order='desc'), # SortOption(field='created_at', order='asc') # ] # Build sort string sort_options = [ SortOption(field='updated_at', order='desc'), SortOption(field='created_at', order='asc') ] sort_string = build_sort_string(sort_options) # Returns: "-updated_at,created_at" Combined Usage Pagination + Filter + Sort:
# Get paginated response response = await client.http_client.get_paginated( '/api/items', page=1, page_size=20 ) # Response is automatically parsed as PaginatedListResponse print(response.meta.totalItems) # 120 print(response.meta.currentPage) # 1 print(len(response.data)) # 25 Metadata Filter Integration Working with /metadata/filter endpoint:
# Get metadata filters from endpoint metadata_response = await client.http_client.post( "/api/v1/metadata/filter", {"documentStorageKey": "my-doc-storage"} ) # Convert AccessFieldFilter to FilterBuilder filter_builder = FilterBuilder() for access_filter in metadata_response.mandatoryFilters: filter_builder.add(access_filter.field, 'in', access_filter.values) # Use with query utilities query_string = filter_builder.to_query_string() # Apply to API requests response = await client.http_client.get_with_filters( '/api/items', filter_builder=filter_builder ) Features:
from fastapi import Depends, HTTPException, Security from fastapi.security import HTTPBearer from miso_client import MisoClient security = HTTPBearer() client = MisoClient(load_config()) async def get_current_user(credentials = Security(security)): token = credentials.credentials is_valid = await client.validate_token(token) if not is_valid: raise HTTPException(status_code=401, detail="Invalid token") return await client.get_user(token) Protect routes by role (FastAPI):
@app.get('/admin') async def admin_panel(user = Depends(get_current_user), credentials = Security(security)): token = credentials.credentials is_admin = await client.has_role(token, 'admin') if not is_admin: raise HTTPException(status_code=403, detail="Forbidden") # Admin only code return {"message": "Admin panel"} Use environment variables:
MISO_CLIENTID=ctrl-dev-my-app MISO_CLIENTSECRET=your-secret MISO_CONTROLLER_URL=http://localhost:3000 REDIS_HOST=localhost REDIS_PORT=6379 MISO_LOG_LEVEL=info API_KEY=your-test-api-key # Optional: For testing (bypasses OAuth2) 🐛 Troubleshooting "Cannot connect to controller" → Verify controllerUrl is correct and accessible → Check network connectivity
"Redis connection failed" → SDK falls back to controller-only mode (slower but works) → Fix: aifabrix up to start Redis
"Client token fetch failed" → Check MISO_CLIENTID and MISO_CLIENTSECRET are correct → Verify credentials are configured in controller → Ensure ENCRYPTION_KEY environment variable is set (required for encryption service)
"Token validation fails" → Ensure Keycloak is running and configured correctly → Verify token is from correct Keycloak instance → Check that python-dotenv is installed if using .env files
# pip pip install miso-client # Repository development (Python 3.11–3.14) make PYTHON=python3 VENV=venv install-dev make NODE=node PNPM=pnpm install-node-tools make PYTHON=python3 VENV=venv validate-silent Development and build dependencies come from the committed, hash-checked files in requirements/; make lock regenerates them with the pinned build toolchain. The .python-version file selects Python 3.14 for compatible version managers, while an explicit PYTHON value continues to select supported matrix interpreters. Node 24 and pnpm are development-only baseline-checker tools and are not required to install or use the Python package. make platform-baseline-check and pnpm platform-baseline-check invoke the same accepted canonical checker; direct validation fails with an actionable message when its frozen Node tools are absent.
This project is licensed under the MIT License - see the LICENSE file for details.
authentication authorization rbac jwt redis logging aifabrix miso
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
None of the files in this release were uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




