You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The Platform Module provides the foundational authentication, API client management, and core service infrastructure for the Aignostics Python SDK. It enables secure communication with the Aignostics Platform API and serves as the primary entry point for all biomedical data analysis workflows. This module handles OAuth 2.0 authentication flows, token management, API client configuration, and provides the base infrastructure for higher-level application modules.
1.2 Functional Requirements
The Platform Module shall:
[FR-01] Provide secure OAuth 2.0 authentication with support for both Authorization Code with PKCE and Device Authorization flows
[FR-02] Manage JWT token lifecycle including acquisition, caching, validation, and refresh operations
[FR-03] Configure and provide authenticated API clients for interaction with Aignostics Platform services
[FR-04] Support multiple deployment environments (production, staging, development, test) with automatic endpoint configuration
[FR-05] Provide CLI commands for user authentication operations (login, logout, whoami)
[FR-06] Handle authentication errors with retry mechanisms and fallback flows
[FR-07] Support proxy configurations and SSL certificate handling for enterprise environments
[FR-08] Provide health monitoring for both public and authenticated API endpoints
[FR-09] Manage application and application version resources with listing and filtering capabilities
[FR-10] Create and manage application runs with status monitoring and result retrieval
[FR-11] Download and verify file integrity using CRC32C checksums for run artifacts
[FR-12] Generate signed URLs for secure Google Cloud Storage access
[FR-13] Provide user and organization information retrieval with sensitive data masking options
[FR-14] Support external token providers to bypass internal OAuth 2.0 flows for machine-to-machine, service account, or custom token lifecycle scenarios.
1.3 Non-Functional Requirements
Performance: 30s API timeout, 3s retry backoff, file-based token caching, 10-retry port availability checking
Security: HTTPS-only communication, JWT validation (signature/audience/expiration), SecretStr protection, data masking, proxy/SSL support
Reliability: Auto token refresh, browser-to-device flow fallback, re-authentication on failures, port conflict handling, socket reuse
Factory Pattern: Client.get_api_client() creates configured API clients based on environment settings
Service Layer Pattern: Business logic encapsulated in service classes with clean separation from API details
Strategy Pattern: Multiple authentication flows (Authorization Code vs Device Flow) selected based on environment capabilities; external token provider as a fully independent alternative strategy
Template Method Pattern: Base authentication flow with specific implementations for different OAuth grant types
3. Inputs and Outputs
3.1 Inputs
Input Type
Source
Format/Type
Validation Rules
Code Location
Environment Variables
OS Environment
String/SecretStr
Must match expected format for URLs and client IDs
graph TD
A[User Request] --> X{External Token Provider?}
X -->|Yes| I[Create API Client with External Provider]
X -->|No| B{Token Cached?}
B -->|Yes| C[Use Cached Token]
B -->|No| D[OAuth Authentication]
D --> E{Browser Available?}
E -->|Yes| F[Browser Login]
E -->|No| G[Device Code Login]
F --> H[Get JWT Token]
G --> H
C --> H
H --> I[Create API Client]
I --> J[Make API Request]
J --> K[Return Results]
L[Health Check] --> M[Check API Status]
Loading
4. Interface Definitions
4.1 Public API
Core Client Interface
classClient:
"""Main client for interacting with the Aignostics Platform API."""def__init__(
self,
cache_token: bool=True,
token_provider: Callable[[], str] |None=None,
) ->None:
"""Initializes authenticated API client with resource accessors."""defme(self) ->Me:
"""Retrieves current user and organization information."""defapplication(self, application_id: str) ->Application:
"""Finds specific application by ID."""defrun(self, application_run_id: str) ->ApplicationRun:
"""Creates ApplicationRun instance for existing run."""@staticmethoddefget_api_client(
cache_token: bool=True,
token_provider: Callable[[], str] |None=None,
) ->_AuthenticatedApi: # internal subclass of PublicApi; exposes token_provider attribute"""Creates authenticated API client with proper configuration."""
Service Interface
classService(BaseService):
"""Core service for authentication and system operations."""deflogin(self, relogin: bool=False) ->bool:
"""Authenticates user and caches token."""deflogout(self) ->bool:
"""Removes cached authentication token."""defget_user_info(self, relogin: bool=False) ->UserInfo:
"""Retrieves authenticated user information."""defhealth(self) ->Health:
"""Determines service and API health status."""definfo(self, mask_secrets: bool=True) ->dict[str, Any]:
"""Returns service information including settings and user info."""
classApplications(_AuthenticatedResource):
"""Resource class for managing applications."""def__init__(self, api: _AuthenticatedApi) ->None:
"""Initializes the Applications resource with the API client."""deflist(self) ->Iterator[Application]:
"""Find all available applications."""@propertydefversions(self) ->Versions:
"""Access to application versions management."""
classVersions(_AuthenticatedResource):
"""Resource class for managing application versions."""# Constructor inherited from _AuthenticatedResource# def __init__(self, api: _AuthenticatedApi) -> None:deflist(self, application: Application|str) ->Iterator[ApplicationVersion]:
"""Find all versions for a specific application."""deflist_sorted(self, application: Application|str) ->list[ApplicationVersion]:
"""Get application versions sorted by semver, descending."""deflatest(self, application: Application|str) ->ApplicationVersion|None:
"""Get latest version."""defdetails(self, application_version: ApplicationVersion|str) ->ApplicationVersion:
"""Retrieves details for a specific application version."""
classRuns(_AuthenticatedResource):
"""Resource class for managing application runs."""# Constructor inherited from _AuthenticatedResource# def __init__(self, api: _AuthenticatedApi) -> None:defcreate(self, application_version: str, items: list[ItemCreationRequest]) ->ApplicationRun:
"""Creates a new application run."""deflist(self, for_application_version: str|None=None) ->Generator[ApplicationRun, Any, None]:
"""Find application runs, optionally filtered by application version."""deflist_data(self, for_application_version: str|None=None, sort: str|None=None, page_size: int=100) ->Iterator[ApplicationRunData]:
"""Fetch application runs data with optional filtering and sorting."""def__call__(self, application_run_id: str) ->ApplicationRun:
"""Retrieves an ApplicationRun instance for an existing run."""
classApplicationRun(_AuthenticatedResource):
"""Represents a single application run."""def__init__(self, api: _AuthenticatedApi, application_run_id: str) ->None:
"""Initializes an ApplicationRun instance."""@classmethoddeffor_application_run_id(cls, application_run_id: str) ->"ApplicationRun":
"""Creates an ApplicationRun instance for an existing run."""defdetails(self) ->ApplicationRunData:
"""Retrieves the current status of the application run."""defcancel(self) ->None:
"""Cancels the application run."""defresults(
self,
nocache: bool=False,
item_ids: list[str] |None=None,
external_ids: list[str] |None=None,
) ->Iterator[ItemResultData]:
"""Retrieves the results of items in the run, optionally filtered by item or external IDs."""defitem_status(self) ->dict[str, ItemStatus]:
"""Retrieves the status of all items in the run."""defdownload_to_folder(self, download_base: Path|str, checksum_attribute_key: str="checksum_base64_crc32c") ->None:
"""Downloads all result artifacts to a folder."""
classSettings(OpaqueSettings):
"""Configuration settings for the Aignostics SDK."""# Core API settingsapi_root: straudience: strauthorization_base_url: strtoken_url: strdevice_url: strjws_json_url: strclient_id_interactive: str# Optional settingsclient_id_device: SecretStr|Nonerefresh_token: SecretStr|Nonecache_dir: strrequest_timeout_seconds: intauthorization_backoff_seconds: int
4.2 CLI Interface
Command Structure:
uvx aignostics platform [subcommand] [options]
Available Commands:
login [--relogin]: Authenticate user with platform
logout: Remove authentication and clear cached tokens
whoami [--mask-secrets] [--relogin]: Display current user information
4.3 GUI Interface
The Platform module provides foundational services but does not directly expose GUI components. It supports GUI applications by providing:
Authentication State: Token validation and user information for GUI session management
API Client Factory: Configured clients for GUI data operations
Health Monitoring: Service status for GUI health indicators
5. Dependencies and Integration
5.1 Internal Dependencies
Dependency Module
Usage Purpose
Interface Used
Utils Module
Logging, configuration loading, base service classes
get_logger(), BaseService, OpaqueSettings
5.2 External Dependencies
Dependency
Version
Purpose
Optional/Required
aignx.codegen
^X.X.X
Auto-generated API client and models
Required
requests
^2.31.0
HTTP client for authentication flows
Required
requests-oauthlib
^1.3.0
OAuth 2.0 flow implementation
Required
PyJWT
^2.8.0
JWT token validation and decoding
Required
crc32c
^2.7.0
File integrity verification
Required
pydantic
^2.5.0
Settings validation and data models
Required
pydantic-settings
^2.1.0
Environment-based configuration
Required
google-cloud-storage
^2.10.0
Signed URL generation for downloads
Optional
typer
^0.9.0
CLI framework
Required
appdirs
^1.4.4
Platform-appropriate cache directory
Required
5.3 Integration Points
Aignostics Platform API: Primary integration via authenticated HTTP requests to platform endpoints
Auth0 Identity Service: OAuth 2.0 flows for user authentication and token management
Google Cloud Storage: Signed URL generation and secure file download capabilities
System Proxy Services: Automatic proxy detection and configuration for enterprise environments
6. Configuration and Settings
6.1 Configuration Parameters
Parameter
Type
Default
Description
Required
api_root
str
https://platform.aignostics.com
Base URL of Aignostics API
Yes
audience
str
Environment-specific
OAuth audience claim
Yes
scope
str
offline_access
OAuth scopes required
Yes
cache_dir
str
User cache directory
Directory for token storage
No
request_timeout_seconds
int
30
API request timeout
No
authorization_backoff_seconds
int
3
Retry backoff time
No
6.2 Environment Variables
Variable
Purpose
Example Value
AIGNOSTICS_API_ROOT
Override default API endpoint
https://platform-dev.aignostics.com
AIGNOSTICS_CLIENT_ID_DEVICE
Device flow client ID
device_client_123
AIGNOSTICS_SCOPE
OAuth scopes required
offline_access,read:data
AIGNOSTICS_AUDIENCE
OAuth audience claim
https://custom-audience
AIGNOSTICS_AUTHORIZATION_BASE_URL
Custom authorization endpoint
https://custom.auth0.com/authorize
AIGNOSTICS_TOKEN_URL
Custom token endpoint
https://custom.auth0.com/oauth/token
AIGNOSTICS_REDIRECT_URI
Custom redirect URI
http://localhost:9000/
AIGNOSTICS_DEVICE_URL
Custom device authorization URL
https://custom.auth0.com/oauth/device/code
AIGNOSTICS_JWS_JSON_URL
Custom JWS key set URL
https://custom.auth0.com/.well-known/jwks.json
AIGNOSTICS_CLIENT_ID_INTERACTIVE
Interactive flow client ID
interactive_client_123
AIGNOSTICS_REFRESH_TOKEN
Long-lived refresh token
refresh_token_value
AIGNOSTICS_CACHE_DIR
Custom cache directory
/custom/cache/path
AIGNOSTICS_REQUEST_TIMEOUT_SECONDS
API request timeout
60
AIGNOSTICS_AUTHORIZATION_BACKOFF_SECONDS
Authorization retry backoff time
5
AIGNOSTICS_ENV_FILE
Custom .env file location
/path/to/custom/.env
REQUESTS_CA_BUNDLE
SSL certificate bundle
/path/to/ca-bundle.crt
7. Error Handling and Validation
7.1 Error Categories
Error Type
Cause
Handling Strategy
User Impact
AuthenticationError
Invalid credentials or network issues
Retry with exponential backoff; clear cached tokens