API Layer¶
Litestar REST + WebSocket API -- controllers, authentication, guards, and channels.
App¶
app
¶
Litestar application factory.
Creates and configures the Litestar application with all controllers, middleware, exception handlers, plugins, and lifecycle hooks (startup/shutdown).
create_app
¶
create_app(
*,
config=None,
persistence=None,
message_bus=None,
cost_tracker=None,
approval_store=None,
auth_service=None,
task_engine=None,
coordinator=None,
agent_registry=None,
meeting_orchestrator=None,
meeting_scheduler=None,
performance_tracker=None,
settings_service=None,
provider_registry=None,
provider_health_tracker=None,
tool_invocation_tracker=None,
delegation_record_store=None,
artifact_storage=None,
)
Create and configure the Litestar application.
All parameters are optional for testing -- provide fakes via keyword arguments. Services not explicitly provided are auto-wired from config and environment variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
RootConfig | None
|
Root company configuration. |
None
|
persistence
|
PersistenceBackend | None
|
Persistence backend. |
None
|
message_bus
|
MessageBus | None
|
Internal message bus. |
None
|
cost_tracker
|
CostTracker | None
|
Cost tracking service. |
None
|
approval_store
|
ApprovalStore | None
|
Approval queue store. |
None
|
auth_service
|
AuthService | None
|
Pre-built auth service (for testing). |
None
|
task_engine
|
TaskEngine | None
|
Centralized task state engine. |
None
|
coordinator
|
MultiAgentCoordinator | None
|
Multi-agent coordinator. |
None
|
agent_registry
|
AgentRegistryService | None
|
Agent registry service. |
None
|
meeting_orchestrator
|
MeetingOrchestrator | None
|
Meeting orchestrator. |
None
|
meeting_scheduler
|
MeetingScheduler | None
|
Meeting scheduler. |
None
|
performance_tracker
|
PerformanceTracker | None
|
Performance tracking service. |
None
|
settings_service
|
SettingsService | None
|
Settings service for runtime config. |
None
|
provider_registry
|
ProviderRegistry | None
|
Provider registry. |
None
|
provider_health_tracker
|
ProviderHealthTracker | None
|
Provider health tracking service. |
None
|
tool_invocation_tracker
|
ToolInvocationTracker | None
|
Tool invocation tracking service. |
None
|
delegation_record_store
|
DelegationRecordStore | None
|
Delegation record store. |
None
|
artifact_storage
|
ArtifactStorageBackend | None
|
Artifact storage backend. |
None
|
Returns:
| Type | Description |
|---|---|
Litestar
|
Configured Litestar application. |
Source code in src/synthorg/api/app.py
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 | |
Config¶
config
¶
API configuration models.
Frozen Pydantic models for CORS, rate limiting, server,
authentication, and the top-level ApiConfig that aggregates
them all.
CorsConfig
pydantic-model
¶
Bases: BaseModel
CORS configuration for the API.
Attributes:
| Name | Type | Description |
|---|---|---|
allowed_origins |
tuple[str, ...]
|
Origins permitted to make cross-origin requests. |
allow_methods |
tuple[str, ...]
|
HTTP methods permitted in cross-origin requests. |
allow_headers |
tuple[str, ...]
|
Headers permitted in cross-origin requests. |
allow_credentials |
bool
|
Whether credentials (cookies, auth) are allowed in cross-origin requests. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
allowed_origins(tuple[str, ...]) -
allow_methods(tuple[str, ...]) -
allow_headers(tuple[str, ...]) -
allow_credentials(bool)
Validators:
-
_validate_wildcard_credentials
RateLimitTimeUnit
¶
Bases: StrEnum
Valid time windows for rate limiting.
RateLimitConfig
pydantic-model
¶
Bases: BaseModel
API rate limiting configuration.
Maps to Litestar's built-in RateLimitConfig middleware.
Attributes:
| Name | Type | Description |
|---|---|---|
max_requests |
int
|
Maximum requests per time window. |
time_unit |
RateLimitTimeUnit
|
Time window ( |
exclude_paths |
tuple[str, ...]
|
Paths excluded from rate limiting. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
max_requests(int) -
time_unit(RateLimitTimeUnit) -
exclude_paths(tuple[str, ...])
ServerConfig
pydantic-model
¶
Bases: BaseModel
Uvicorn server configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
host |
str
|
Bind address. |
port |
int
|
Bind port. |
reload |
bool
|
Enable auto-reload for development. |
workers |
int
|
Number of worker processes. |
ws_ping_interval |
float
|
WebSocket ping interval in seconds (0 to disable). |
ws_ping_timeout |
float
|
WebSocket pong timeout in seconds. |
ssl_certfile |
str | None
|
Path to SSL certificate file (PEM format). |
ssl_keyfile |
str | None
|
Path to SSL private key file (PEM format). |
ssl_ca_certs |
str | None
|
Path to CA bundle for client cert verification. |
trusted_proxies |
tuple[str, ...]
|
IP addresses/CIDRs trusted as reverse
proxies for |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
host(str) -
port(int) -
reload(bool) -
workers(int) -
ws_ping_interval(float) -
ws_ping_timeout(float) -
ssl_certfile(str | None) -
ssl_keyfile(str | None) -
ssl_ca_certs(str | None) -
trusted_proxies(tuple[str, ...])
Validators:
-
_normalize_empty_tls -
_validate_tls_pair
ApiConfig
pydantic-model
¶
Bases: BaseModel
Top-level API configuration aggregating all sub-configs.
Attributes:
| Name | Type | Description |
|---|---|---|
cors |
CorsConfig
|
CORS configuration. |
rate_limit |
RateLimitConfig
|
Rate limiting configuration. |
server |
ServerConfig
|
Uvicorn server configuration. |
auth |
AuthConfig
|
Authentication configuration. |
api_prefix |
NotBlankStr
|
URL prefix for all API routes. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
cors(CorsConfig) -
rate_limit(RateLimitConfig) -
server(ServerConfig) -
auth(AuthConfig) -
api_prefix(NotBlankStr)
DTOs¶
dto
¶
Request/response DTOs and envelope models.
Response envelopes wrap all API responses in a consistent structure. Request DTOs define write-operation payloads (separate from domain models because they omit server-generated fields).
ErrorDetail
pydantic-model
¶
Bases: BaseModel
Structured error metadata (RFC 9457).
Self-contained so agents can parse it without referencing the parent envelope.
Attributes:
| Name | Type | Description |
|---|---|---|
detail |
NotBlankStr
|
Human-readable occurrence-specific explanation. |
error_code |
ErrorCode
|
Machine-readable error code (by convention, 4-digit
category-grouped; see |
error_category |
ErrorCategory
|
High-level error category. |
retryable |
bool
|
Whether the client should retry the request. |
retry_after |
int | None
|
Seconds to wait before retrying ( |
instance |
NotBlankStr
|
Request correlation ID for log tracing. |
title |
NotBlankStr
|
Static per-category title (e.g. "Authentication Error"). |
type |
NotBlankStr
|
Documentation URI for the error category. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
detail(NotBlankStr) -
error_code(ErrorCode) -
error_category(ErrorCategory) -
retryable(bool) -
retry_after(int | None) -
instance(NotBlankStr) -
title(NotBlankStr) -
type(NotBlankStr)
Validators:
-
_validate_retry_after_consistency
ProblemDetail
pydantic-model
¶
Bases: BaseModel
Bare RFC 9457 application/problem+json response body.
Returned when the client sends Accept: application/problem+json.
Attributes:
| Name | Type | Description |
|---|---|---|
type |
NotBlankStr
|
Documentation URI for the error category. |
title |
NotBlankStr
|
Static per-category title. |
status |
int
|
HTTP status code. |
detail |
NotBlankStr
|
Human-readable occurrence-specific explanation. |
instance |
NotBlankStr
|
Request correlation ID for log tracing. |
error_code |
ErrorCode
|
Machine-readable 4-digit error code. |
error_category |
ErrorCategory
|
High-level error category. |
retryable |
bool
|
Whether the client should retry the request. |
retry_after |
int | None
|
Seconds to wait before retrying ( |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
type(NotBlankStr) -
title(NotBlankStr) -
status(int) -
detail(NotBlankStr) -
instance(NotBlankStr) -
error_code(ErrorCode) -
error_category(ErrorCategory) -
retryable(bool) -
retry_after(int | None)
Validators:
-
_validate_retry_after_consistency
ApiResponse
pydantic-model
¶
Bases: BaseModel
Standard API response envelope.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
T | None
|
Response payload ( |
error |
str | None
|
Error message ( |
error_detail |
ErrorDetail | None
|
Structured error metadata ( |
success |
bool
|
Whether the request succeeded (computed from |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
data(T | None) -
error(str | None) -
error_detail(ErrorDetail | None)
Validators:
-
_validate_error_detail_consistency
PaginationMeta
pydantic-model
¶
PaginatedResponse
pydantic-model
¶
Bases: BaseModel
Paginated API response envelope.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
tuple[T, ...]
|
Page of items. |
error |
str | None
|
Error message ( |
error_detail |
ErrorDetail | None
|
Structured error metadata ( |
pagination |
PaginationMeta
|
Pagination metadata. |
degraded_sources |
tuple[NotBlankStr, ...]
|
Data sources that failed gracefully, resulting in partial data. Empty when all sources responded normally. |
success |
bool
|
Whether the request succeeded (computed from |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
data(tuple[T, ...]) -
error(str | None) -
error_detail(ErrorDetail | None) -
pagination(PaginationMeta) -
degraded_sources(tuple[NotBlankStr, ...])
Validators:
-
_validate_error_detail_consistency
CreateArtifactRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a new artifact.
Attributes:
| Name | Type | Description |
|---|---|---|
type |
ArtifactType
|
Artifact type (code, tests, documentation). |
path |
NotBlankStr
|
Logical file/directory path of the artifact. |
task_id |
NotBlankStr
|
ID of the originating task. |
created_by |
NotBlankStr
|
Agent ID of the creator. |
description |
str
|
Human-readable description. |
content_type |
str
|
MIME content type (empty if no content stored). |
project_id |
NotBlankStr | None
|
Optional project ID to link the artifact to. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
type(ArtifactType) -
path(NotBlankStr) -
task_id(NotBlankStr) -
created_by(NotBlankStr) -
description(str) -
content_type(str) -
project_id(NotBlankStr | None)
CreateProjectRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a new project.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
NotBlankStr
|
Project display name. |
description |
str
|
Detailed project description. |
team |
tuple[NotBlankStr, ...]
|
Agent IDs assigned to the project. |
lead |
NotBlankStr | None
|
Agent ID of the project lead. |
deadline |
str | None
|
Optional deadline (ISO 8601 string). |
budget |
float
|
Total budget in base currency. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
name(NotBlankStr) -
description(str) -
team(tuple[NotBlankStr, ...]) -
lead(NotBlankStr | None) -
deadline(str | None) -
budget(float)
Validators:
-
_validate_request
CreateTaskRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a new task.
Attributes:
| Name | Type | Description |
|---|---|---|
title |
NotBlankStr
|
Short task title. |
description |
NotBlankStr
|
Detailed task description. |
type |
TaskType
|
Task work type. |
priority |
Priority
|
Task priority level. |
project |
NotBlankStr
|
Project ID. |
created_by |
NotBlankStr
|
Agent name of the creator. |
assigned_to |
NotBlankStr | None
|
Optional assignee agent ID. |
estimated_complexity |
Complexity
|
Complexity estimate. |
budget_limit |
float
|
Maximum spend in base currency. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
title(NotBlankStr) -
description(NotBlankStr) -
type(TaskType) -
priority(Priority) -
project(NotBlankStr) -
created_by(NotBlankStr) -
assigned_to(NotBlankStr | None) -
estimated_complexity(Complexity) -
budget_limit(float)
UpdateTaskRequest
pydantic-model
¶
Bases: BaseModel
Payload for updating task fields.
All fields are optional -- only provided fields are updated.
Attributes:
| Name | Type | Description |
|---|---|---|
title |
NotBlankStr | None
|
New title. |
description |
NotBlankStr | None
|
New description. |
priority |
Priority | None
|
New priority. |
assigned_to |
NotBlankStr | None
|
New assignee. |
budget_limit |
float | None
|
New budget limit. |
expected_version |
int | None
|
Optimistic concurrency guard. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
title(NotBlankStr | None) -
description(NotBlankStr | None) -
priority(Priority | None) -
assigned_to(NotBlankStr | None) -
budget_limit(float | None) -
expected_version(int | None)
TransitionTaskRequest
pydantic-model
¶
Bases: BaseModel
Payload for a task status transition.
Attributes:
| Name | Type | Description |
|---|---|---|
target_status |
TaskStatus
|
The desired target status. |
assigned_to |
NotBlankStr | None
|
Optional assignee override for the transition. |
expected_version |
int | None
|
Optimistic concurrency guard. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
target_status(TaskStatus) -
assigned_to(NotBlankStr | None) -
expected_version(int | None)
CancelTaskRequest
pydantic-model
¶
Bases: BaseModel
Payload for cancelling a task.
Attributes:
| Name | Type | Description |
|---|---|---|
reason |
NotBlankStr
|
Reason for cancellation. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
CreateApprovalRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a new approval item.
Attributes:
| Name | Type | Description |
|---|---|---|
action_type |
NotBlankStr
|
Kind of action requiring approval
( |
title |
NotBlankStr
|
Short summary. |
description |
NotBlankStr
|
Detailed explanation. |
risk_level |
ApprovalRiskLevel
|
Assessed risk level. |
ttl_seconds |
int | None
|
Optional time-to-live in seconds (min 60, max 604 800 = 7 days). |
task_id |
NotBlankStr | None
|
Optional associated task. |
metadata |
dict[str, str]
|
Additional key-value pairs. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
action_type(NotBlankStr) -
title(NotBlankStr) -
description(NotBlankStr) -
risk_level(ApprovalRiskLevel) -
ttl_seconds(int | None) -
task_id(NotBlankStr | None) -
metadata(dict[str, str])
Validators:
-
_validate_action_type_format→action_type -
_validate_metadata_bounds
ApproveRequest
pydantic-model
¶
Bases: BaseModel
Payload for approving an approval item.
Attributes:
| Name | Type | Description |
|---|---|---|
comment |
NotBlankStr | None
|
Optional comment explaining the approval. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
comment(NotBlankStr | None)
RejectRequest
pydantic-model
¶
Bases: BaseModel
Payload for rejecting an approval item.
Attributes:
| Name | Type | Description |
|---|---|---|
reason |
NotBlankStr
|
Mandatory reason for rejection. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
reason(NotBlankStr)
CoordinateTaskRequest
pydantic-model
¶
Bases: BaseModel
Payload for triggering multi-agent coordination on a task.
Attributes:
| Name | Type | Description |
|---|---|---|
agent_names |
tuple[NotBlankStr, ...] | None
|
Agent names to coordinate with ( |
max_subtasks |
int
|
Maximum subtasks for decomposition. |
max_concurrency_per_wave |
int | None
|
Override for max concurrency per wave. |
fail_fast |
bool | None
|
Override for fail-fast behaviour ( |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
agent_names(tuple[NotBlankStr, ...] | None) -
max_subtasks(int) -
max_concurrency_per_wave(int | None) -
fail_fast(bool | None)
Validators:
-
_validate_unique_agent_names
CoordinationPhaseResponse
pydantic-model
¶
Bases: BaseModel
Response model for a single coordination phase.
Attributes:
| Name | Type | Description |
|---|---|---|
phase |
NotBlankStr
|
Phase name. |
success |
bool
|
Whether the phase completed successfully. |
duration_seconds |
float
|
Wall-clock duration of the phase. |
error |
NotBlankStr | None
|
Error description if the phase failed. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
phase(NotBlankStr) -
success(bool) -
duration_seconds(float) -
error(NotBlankStr | None)
Validators:
-
_validate_success_error_consistency
CoordinationResultResponse
pydantic-model
¶
Bases: BaseModel
Response model for a complete coordination run.
Attributes:
| Name | Type | Description |
|---|---|---|
parent_task_id |
NotBlankStr
|
ID of the parent task. |
topology |
NotBlankStr
|
Resolved coordination topology. |
total_duration_seconds |
float
|
Total wall-clock duration. |
total_cost_usd |
float
|
Total cost across all waves. |
phases |
tuple[CoordinationPhaseResponse, ...]
|
Phase results in execution order. |
wave_count |
int
|
Number of execution waves. |
is_success |
bool
|
Whether all phases succeeded (computed). |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
parent_task_id(NotBlankStr) -
topology(NotBlankStr) -
total_duration_seconds(float) -
total_cost_usd(float) -
currency(str) -
phases(tuple[CoordinationPhaseResponse, ...]) -
wave_count(int)
CreateFromPresetRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a provider from a preset.
Attributes:
| Name | Type | Description |
|---|---|---|
preset_name |
NotBlankStr
|
Name of the preset to create from. |
name |
NotBlankStr
|
Unique provider name (2-64 chars, lowercase + hyphens). |
auth_type |
AuthType | None
|
Override the preset's default auth type (optional). |
subscription_token |
NotBlankStr | None
|
Bearer token for subscription-based auth. |
tos_accepted |
bool
|
Whether the user accepted the subscription ToS. |
base_url |
NotBlankStr | None
|
Override the preset's default base URL (optional). |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
preset_name(NotBlankStr) -
name(NotBlankStr) -
auth_type(AuthType | None) -
api_key(NotBlankStr | None) -
subscription_token(NotBlankStr | None) -
tos_accepted(bool) -
base_url(NotBlankStr | None) -
models(tuple[ProviderModelConfig, ...] | None)
Validators:
-
_validate_name→name -
_validate_base_url→base_url
CreateProviderRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a new provider.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
NotBlankStr
|
Unique provider name (2-64 chars, lowercase + hyphens). |
driver |
NotBlankStr
|
Driver backend name (default |
litellm_provider |
NotBlankStr | None
|
LiteLLM routing identifier override. |
auth_type |
AuthType
|
Authentication mechanism for this provider. |
api_key |
NotBlankStr | None
|
API key credential (optional, depends on auth_type). |
subscription_token |
NotBlankStr | None
|
Bearer token for subscription-based auth. |
tos_accepted |
bool
|
Whether the user accepted the subscription ToS. |
base_url |
NotBlankStr | None
|
Provider API base URL. |
models |
tuple[ProviderModelConfig, ...]
|
Pre-configured model definitions. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
name(NotBlankStr) -
driver(NotBlankStr) -
litellm_provider(NotBlankStr | None) -
auth_type(AuthType) -
api_key(NotBlankStr | None) -
subscription_token(NotBlankStr | None) -
tos_accepted(bool) -
base_url(NotBlankStr | None) -
oauth_token_url(NotBlankStr | None) -
oauth_client_id(NotBlankStr | None) -
oauth_client_secret(NotBlankStr | None) -
oauth_scope(NotBlankStr | None) -
custom_header_name(NotBlankStr | None) -
custom_header_value(NotBlankStr | None) -
models(tuple[ProviderModelConfig, ...]) -
preset_name(NotBlankStr | None)
Validators:
-
_validate_name→name -
_validate_base_url→base_url
DiscoverModelsResponse
pydantic-model
¶
Bases: BaseModel
Result of provider model auto-discovery.
Attributes:
| Name | Type | Description |
|---|---|---|
discovered_models |
tuple[ProviderModelConfig, ...]
|
Models found on the provider endpoint. |
provider_name |
NotBlankStr
|
Name of the provider that was queried. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
discovered_models(tuple[ProviderModelConfig, ...]) -
provider_name(NotBlankStr)
ProbePresetRequest
pydantic-model
¶
Bases: BaseModel
Request to probe a preset's candidate URLs for reachability.
Attributes:
| Name | Type | Description |
|---|---|---|
preset_name |
NotBlankStr
|
Preset identifier to probe. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
preset_name(NotBlankStr)
ProbePresetResponse
pydantic-model
¶
Bases: BaseModel
Result of probing a preset's candidate URLs.
Attributes:
| Name | Type | Description |
|---|---|---|
url |
NotBlankStr | None
|
The first reachable base URL, or |
model_count |
int
|
Number of models discovered at the URL. |
candidates_tried |
int
|
Number of candidate URLs attempted. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
url(NotBlankStr | None) -
model_count(int) -
candidates_tried(int)
ProviderResponse
pydantic-model
¶
Bases: BaseModel
Safe provider config for API responses -- secrets stripped.
Non-secret auth fields are included for frontend edit form UX.
Boolean has_* indicators signal credential presence without
exposing values.
Attributes:
| Name | Type | Description |
|---|---|---|
driver |
NotBlankStr
|
Driver backend name. |
litellm_provider |
NotBlankStr | None
|
LiteLLM routing identifier override. |
auth_type |
AuthType
|
Authentication mechanism. |
base_url |
NotBlankStr | None
|
Provider API base URL. |
models |
tuple[ProviderModelConfig, ...]
|
Configured model definitions. |
has_api_key |
bool
|
Whether an API key is set. |
has_oauth_credentials |
bool
|
Whether OAuth credentials are configured. |
has_custom_header |
bool
|
Whether a custom auth header is configured. |
has_subscription_token |
bool
|
Whether a subscription token is set. |
tos_accepted_at |
str | None
|
ISO timestamp of ToS acceptance (or |
preset_name |
NotBlankStr | None
|
Preset used to create this provider (if any). |
supports_model_pull |
bool
|
Whether pulling models is supported. |
supports_model_delete |
bool
|
Whether deleting models is supported. |
supports_model_config |
bool
|
Whether per-model config is supported. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
driver(NotBlankStr) -
litellm_provider(NotBlankStr | None) -
auth_type(AuthType) -
base_url(NotBlankStr | None) -
models(tuple[ProviderModelConfig, ...]) -
has_api_key(bool) -
has_oauth_credentials(bool) -
has_custom_header(bool) -
has_subscription_token(bool) -
tos_accepted_at(str | None) -
oauth_token_url(NotBlankStr | None) -
oauth_client_id(NotBlankStr | None) -
oauth_scope(NotBlankStr | None) -
custom_header_name(NotBlankStr | None) -
preset_name(NotBlankStr | None) -
supports_model_pull(bool) -
supports_model_delete(bool) -
supports_model_config(bool)
TestConnectionRequest
pydantic-model
¶
Bases: BaseModel
Payload for testing a provider connection.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
NotBlankStr | None
|
Model to test (defaults to first model in config). |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
model(NotBlankStr | None)
TestConnectionResponse
pydantic-model
¶
Bases: BaseModel
Result of a provider connection test.
Attributes:
| Name | Type | Description |
|---|---|---|
success |
bool
|
Whether the connection test succeeded. |
latency_ms |
float | None
|
Round-trip latency in milliseconds. |
error |
NotBlankStr | None
|
Error message on failure. |
model_tested |
NotBlankStr | None
|
Model ID that was tested. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
success(bool) -
latency_ms(float | None) -
error(NotBlankStr | None) -
model_tested(NotBlankStr | None)
Validators:
-
_validate_success_error_consistency
UpdateProviderRequest
pydantic-model
¶
Bases: BaseModel
Payload for updating a provider (partial update).
All fields are optional -- only provided fields are updated.
tos_accepted: only True re-stamps the timestamp;
False and None are no-ops (cannot be retracted).
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
driver(NotBlankStr | None) -
litellm_provider(NotBlankStr | None) -
auth_type(AuthType | None) -
api_key(NotBlankStr | None) -
clear_api_key(bool) -
subscription_token(NotBlankStr | None) -
clear_subscription_token(bool) -
tos_accepted(bool | None) -
base_url(NotBlankStr | None) -
oauth_token_url(NotBlankStr | None) -
oauth_client_id(NotBlankStr | None) -
oauth_client_secret(NotBlankStr | None) -
oauth_scope(NotBlankStr | None) -
custom_header_name(NotBlankStr | None) -
custom_header_value(NotBlankStr | None) -
models(tuple[ProviderModelConfig, ...] | None)
Validators:
-
_validate_base_url→base_url -
_validate_credential_clear_consistency
CreateWorkflowDefinitionRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a new workflow definition.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
NotBlankStr
|
Workflow name. |
description |
str
|
Optional description. |
workflow_type |
WorkflowType
|
Target execution topology. |
nodes |
tuple[dict[str, object], ...]
|
Nodes in the workflow graph (serialized as dicts). |
edges |
tuple[dict[str, object], ...]
|
Edges connecting nodes (serialized as dicts). |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
name(NotBlankStr) -
description(str) -
workflow_type(WorkflowType) -
nodes(tuple[dict[str, object], ...]) -
edges(tuple[dict[str, object], ...])
UpdateWorkflowDefinitionRequest
pydantic-model
¶
Bases: BaseModel
Payload for updating an existing workflow definition.
All fields are optional -- only provided fields are updated.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
NotBlankStr | None
|
New name. |
description |
str | None
|
New description. |
workflow_type |
WorkflowType | None
|
New workflow type. |
nodes |
tuple[dict[str, object], ...] | None
|
New nodes. |
edges |
tuple[dict[str, object], ...] | None
|
New edges. |
expected_version |
int | None
|
Optimistic concurrency guard. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
name(NotBlankStr | None) -
description(str | None) -
workflow_type(WorkflowType | None) -
nodes(tuple[dict[str, object], ...] | None) -
edges(tuple[dict[str, object], ...] | None) -
expected_version(int | None)
ActivateWorkflowRequest
pydantic-model
¶
Bases: BaseModel
Request body for activating a workflow definition.
Attributes:
| Name | Type | Description |
|---|---|---|
project |
NotBlankStr
|
Project ID for all created tasks. |
context |
dict[str, str | int | float | bool | None]
|
Runtime context for condition expression evaluation. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
project(NotBlankStr) -
context(dict[str, str | int | float | bool | None])
to_provider_response
¶
Convert a ProviderConfig to a safe ProviderResponse.
Strips all secrets and provides boolean credential indicators.
Resolves local model management capabilities from the preset
when preset_name is set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ProviderConfig
|
Provider configuration (may contain secrets). |
required |
Returns:
| Type | Description |
|---|---|
ProviderResponse
|
Safe response DTO with secrets stripped. |
Source code in src/synthorg/api/dto_providers.py
Errors¶
errors
¶
API error hierarchy and RFC 9457 error taxonomy.
All API-specific errors inherit from ApiError so callers
can catch the entire family with a single except clause.
ErrorCategory and ErrorCode provide machine-readable error
metadata for structured error responses (RFC 9457).
ErrorCategory
¶
Bases: StrEnum
High-level error category for structured error responses.
Values are lowercase strings suitable for JSON serialization.
ErrorCode
¶
Bases: IntEnum
Machine-readable error codes (4-digit, category-grouped).
First digit encodes the category: 1xxx = auth, 2xxx = validation, 3xxx = not_found, 4xxx = conflict, 5xxx = rate_limit, 6xxx = budget_exhausted, 7xxx = provider_error, 8xxx = internal.
ApiError
¶
Bases: Exception
Base exception for API-layer errors.
Class Attributes
default_message: Fallback error message used when none is provided and for 5xx response scrubbing. error_category: RFC 9457 error category. error_code: RFC 9457 machine-readable error code. retryable: Whether the client should retry the request.
Instance Attributes
status_code: HTTP status code (set via __init__, fixed per
subclass).
Source code in src/synthorg/api/errors.py
__init_subclass__
¶
Validate error_code/error_category consistency at class creation.
Source code in src/synthorg/api/errors.py
NotFoundError
¶
ApiValidationError
¶
ConflictError
¶
VersionConflictError
¶
Bases: ApiError
Raised when an ETag/If-Match version check fails (409).
Used for ETag/If-Match optimistic concurrency checks -- currently on settings endpoints.
Source code in src/synthorg/api/errors.py
ForbiddenError
¶
SessionRevokedError
¶
Bases: ApiError
Raised when a revoked session token is used (401).
Gives clients a distinct error code (SESSION_REVOKED) so
they can show a "you were logged out" message instead of a
generic auth failure.
Source code in src/synthorg/api/errors.py
UnauthorizedError
¶
ServiceUnavailableError
¶
category_title
¶
Return the RFC 9457 title for a category.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cat
|
ErrorCategory
|
Error category. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Human-readable title string. |
category_type_uri
¶
Return the RFC 9457 type URI for a category.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cat
|
ErrorCategory
|
Error category. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Documentation URI with fragment anchor for the error category. |
Source code in src/synthorg/api/errors.py
Guards¶
guards
¶
Route guards for access control.
Guards read the authenticated user identity from connection.user
(populated by the auth middleware) and check role-based permissions.
The require_roles factory creates guards for arbitrary role sets.
Pre-built constants cover common patterns::
require_ceo -- CEO only
require_ceo_or_manager -- CEO or Manager
require_approval_roles -- CEO, Manager, or Board Member
require_ceo_or_manager
module-attribute
¶
require_ceo_or_manager = require_roles(CEO, MANAGER)
Guard allowing CEO or Manager roles.
require_approval_roles
module-attribute
¶
require_approval_roles = require_roles(CEO, MANAGER, BOARD_MEMBER)
Guard allowing roles that can approve or reject actions.
HumanRole
¶
Bases: StrEnum
Recognised human roles for access control.
has_write_role
¶
Return True if the role grants write access.
Use this for inline role checks instead of importing _WRITE_ROLES
directly. The write set includes CEO, Manager, and Pair Programmer.
Source code in src/synthorg/api/guards.py
require_write_access
¶
Guard that allows only write-capable human roles.
Checks connection.user.role for ceo, manager,
or pair_programmer. Board members are excluded (they
may only observe and approve). The system role is
intentionally excluded -- use require_roles() with the
desired roles for endpoints the CLI needs to reach.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
ASGIConnection
|
The incoming connection. |
required |
_
|
object
|
Route handler (unused). |
required |
Raises:
| Type | Description |
|---|---|
PermissionDeniedException
|
If the role is not permitted. |
Source code in src/synthorg/api/guards.py
require_read_access
¶
Guard that allows all human roles (excludes SYSTEM).
Checks connection.user.role for any human role
including observer and board_member. The internal
system role is excluded -- use require_roles() for
endpoints the CLI needs to reach.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
ASGIConnection
|
The incoming connection. |
required |
_
|
object
|
Route handler (unused). |
required |
Raises:
| Type | Description |
|---|---|
PermissionDeniedException
|
If the role is not permitted. |
Source code in src/synthorg/api/guards.py
require_roles
¶
Create a guard that allows only the specified roles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*roles
|
HumanRole
|
One or more |
()
|
Returns:
| Type | Description |
|---|---|
Callable[[ASGIConnection, object], None]
|
A guard function compatible with Litestar's guard protocol. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no roles are provided. |
Source code in src/synthorg/api/guards.py
Middleware¶
middleware
¶
Request middleware and before-send hooks.
Provides ASGI middleware for request logging, and a before_send
hook that injects security headers (CSP, CORP, HSTS, Cache-Control,
etc.) into every HTTP response -- including exception-handler and
unmatched-route (404/405) responses.
Why before_send instead of ASGI middleware?
Litestar's before_send hook wraps the ASGI send callback at
the outermost layer (before the middleware stack), so it fires for
all responses. By contrast, user-defined ASGI middleware only runs
for matched routes -- 404 and 405 responses from the router bypass it.
RequestLoggingMiddleware
¶
ASGI middleware that logs request start and completion.
Uses time.perf_counter() for high-resolution duration
measurement. Only logs HTTP requests (non-HTTP scopes like
WebSocket and lifespan are passed through without logging).
Source code in src/synthorg/api/middleware.py
__call__
async
¶
Process an ASGI request, logging start and completion.
Source code in src/synthorg/api/middleware.py
security_headers_hook
async
¶
Inject security headers into every HTTP response.
Registered as a Litestar before_send hook so it fires for
all HTTP responses -- successful, exception-handler, and
router-level 404/405.
Adds static security headers (CORP, HSTS, X-Content-Type-Options,
etc.) and path-aware Content-Security-Policy (strict for API,
relaxed for /docs/ to allow Scalar UI resources) and
Cache-Control (no-store for API, public, max-age=300
for /docs/ since it serves public, non-user-specific content).
Uses __setitem__ (not add) so that if any handler or
middleware already set a header, the known-good value overwrites
it rather than creating a duplicate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Message
|
ASGI message dict (only |
required |
scope
|
Scope
|
ASGI connection scope. |
required |
Source code in src/synthorg/api/middleware.py
Pagination¶
pagination
¶
In-memory pagination helper.
Applies offset/limit slicing to tuples and produces
PaginationMeta for the response envelope.
PaginationOffset
module-attribute
¶
Query parameter type for pagination offset (>= 0).
PaginationLimit
module-attribute
¶
Query parameter type for pagination limit (1-200).
paginate
¶
Slice a tuple and produce pagination metadata.
Clamps offset to [0, len(items)] and limit to
[1, MAX_LIMIT] as a safety net.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
tuple[T, ...]
|
Full collection to paginate. |
required |
offset
|
int
|
Zero-based starting index. |
required |
limit
|
int
|
Maximum items to return. |
required |
total
|
int | None
|
True total count when items has been truncated
upstream (e.g. by a safety cap). Defaults to
|
None
|
Returns:
| Type | Description |
|---|---|
tuple[tuple[T, ...], PaginationMeta]
|
A tuple of (page_items, pagination_meta). |
Source code in src/synthorg/api/pagination.py
WebSocket Models¶
ws_models
¶
WebSocket event models for real-time feeds.
Defines event types and the WsEvent payload that is
serialised to JSON and pushed to WebSocket subscribers.
WsEventType
¶
Bases: StrEnum
Types of real-time WebSocket events.
WsEvent
pydantic-model
¶
Bases: BaseModel
A real-time event pushed over WebSocket.
Callers must not mutate the payload dict after construction
-- the dict is a mutable reference inside a frozen model.
Attributes:
| Name | Type | Description |
|---|---|---|
event_type |
WsEventType
|
Classification of the event. |
channel |
NotBlankStr
|
Target channel name. |
timestamp |
AwareDatetime
|
When the event occurred. |
payload |
dict[str, object]
|
Event-specific data. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
event_type(WsEventType) -
channel(NotBlankStr) -
timestamp(AwareDatetime) -
payload(dict[str, object])
Auth¶
config
¶
Authentication configuration.
AuthConfig
pydantic-model
¶
Bases: BaseModel
JWT and authentication configuration.
The jwt_secret is resolved at application startup via a
priority chain:
SYNTHORG_JWT_SECRETenvironment variable (for multi-instance deployments sharing a common secret).- Previously persisted secret in the
settingstable. - Auto-generate a new secret and persist it for future runs.
At construction time the secret may be empty -- it is populated before the first request is served.
Attributes:
| Name | Type | Description |
|---|---|---|
jwt_secret |
str
|
HMAC signing key for JWT tokens and API key hashing (resolved at startup, repr-hidden). Rotating this invalidates all stored API key hashes. |
jwt_algorithm |
Literal['HS256', 'HS384', 'HS512']
|
JWT signing algorithm (HMAC family only). |
jwt_expiry_minutes |
int
|
Token lifetime in minutes. |
min_password_length |
int
|
Minimum password length for setup/change. |
exclude_paths |
tuple[str, ...] | None
|
URL paths excluded from auth middleware. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
jwt_secret(str) -
jwt_algorithm(Literal['HS256', 'HS384', 'HS512']) -
jwt_expiry_minutes(int) -
min_password_length(int) -
exclude_paths(tuple[str, ...] | None)
Validators:
-
_validate_secret_length
jwt_secret
pydantic-field
¶
JWT signing secret (resolved at startup). Also used as the HMAC key for API key hash computation -- rotating this secret invalidates all stored API key hashes.
jwt_expiry_minutes
pydantic-field
¶
Token lifetime in minutes (default 24h)
min_password_length
pydantic-field
¶
Minimum password length for setup and password change
exclude_paths
pydantic-field
¶
Regex patterns for paths excluded from authentication. When None (default), paths are auto-derived from the API prefix (health, auth/setup, auth/login, docs, scalar UI). Use ^ to anchor at the start of the path and add $ when an exact match (rather than a prefix match) is required.
with_secret
¶
Return a copy with the JWT secret set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret
|
str
|
Resolved JWT signing secret. |
required |
Returns:
| Type | Description |
|---|---|
AuthConfig
|
New |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the secret is too short. |
Source code in src/synthorg/api/auth/config.py
models
¶
Authentication domain models.
AuthMethod
¶
Bases: StrEnum
Authentication method used for a request.
User
pydantic-model
¶
Bases: BaseModel
Persisted user account.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
NotBlankStr
|
Unique user identifier. |
username |
NotBlankStr
|
Login username. |
password_hash |
str
|
Argon2id hash (excluded from repr). |
role |
HumanRole
|
Access control role. |
must_change_password |
bool
|
Whether the user must change password. |
created_at |
AwareDatetime
|
Account creation timestamp. |
updated_at |
AwareDatetime
|
Last modification timestamp. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
id(NotBlankStr) -
username(NotBlankStr) -
password_hash(str) -
role(HumanRole) -
must_change_password(bool) -
created_at(AwareDatetime) -
updated_at(AwareDatetime)
ApiKey
pydantic-model
¶
Bases: BaseModel
Persisted API key (hash-only storage).
Attributes:
| Name | Type | Description |
|---|---|---|
id |
NotBlankStr
|
Unique key identifier (UUID). |
key_hash |
NotBlankStr
|
HMAC-SHA256 hex digest of the raw key. |
name |
NotBlankStr
|
Human-readable label. |
role |
HumanRole
|
Access control role. |
user_id |
NotBlankStr
|
Owner user ID. |
created_at |
AwareDatetime
|
Key creation timestamp (timezone-aware). |
expires_at |
AwareDatetime | None
|
Optional expiry timestamp (timezone-aware). |
revoked |
bool
|
Whether the key has been revoked. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
id(NotBlankStr) -
key_hash(NotBlankStr) -
name(NotBlankStr) -
role(HumanRole) -
user_id(NotBlankStr) -
created_at(AwareDatetime) -
expires_at(AwareDatetime | None) -
revoked(bool)
AuthenticatedUser
pydantic-model
¶
Bases: BaseModel
Lightweight identity attached to connection.user.
Populated by the auth middleware after successful authentication.
Attributes:
| Name | Type | Description |
|---|---|---|
user_id |
NotBlankStr
|
User's unique identifier. |
username |
NotBlankStr
|
User's login name. |
role |
HumanRole
|
Access control role. |
auth_method |
AuthMethod
|
How the user authenticated. |
must_change_password |
bool
|
Whether forced password change is pending. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
user_id(NotBlankStr) -
username(NotBlankStr) -
role(HumanRole) -
auth_method(AuthMethod) -
must_change_password(bool)
service
¶
Authentication service -- password hashing, JWT ops, API key hashing.
SecretNotConfiguredError
¶
Bases: RuntimeError
Raised when the JWT secret is required but not configured.
AuthService
¶
Immutable authentication operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
AuthConfig
|
Authentication configuration (carries JWT secret). |
required |
Source code in src/synthorg/api/auth/service.py
hash_password
¶
Hash a password with Argon2id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
password
|
str
|
Plaintext password. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Argon2id hash string. |
verify_password
¶
Verify a password against an Argon2id hash.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
password
|
str
|
Plaintext password to check. |
required |
password_hash
|
str
|
Stored Argon2id hash. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Raises:
| Type | Description |
|---|---|
VerificationError
|
On non-mismatch verification failures (e.g. unsupported parameters). |
InvalidHashError
|
If the stored hash is corrupted or malformed (data integrity issue). |
Source code in src/synthorg/api/auth/service.py
hash_password_async
async
¶
Hash a password with Argon2id in a thread executor.
Offloads the CPU-intensive hashing to avoid blocking the event loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
password
|
str
|
Plaintext password. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Argon2id hash string. |
Source code in src/synthorg/api/auth/service.py
verify_password_async
async
¶
Verify a password against an Argon2id hash in a thread executor.
Offloads the CPU-intensive verification to avoid blocking the event loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
password
|
str
|
Plaintext password to check. |
required |
password_hash
|
str
|
Stored Argon2id hash. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in src/synthorg/api/auth/service.py
create_token
¶
Create a JWT for the given user.
The token includes a pwd_sig claim -- a 16-character
truncated SHA-256 of the stored password hash. This is
plain SHA-256, not HMAC -- the password hash is already a
high-entropy Argon2id output, and the claim is protected
by the JWT signature. The auth middleware validates this
claim on every request so that tokens issued before a
password change are automatically rejected.
A jti (JWT ID) claim is included for per-token session
tracking and revocation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
User
|
Authenticated user. |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, int, str]
|
Tuple of (encoded JWT, expiry seconds, session ID). |
Raises:
| Type | Description |
|---|---|
SecretNotConfiguredError
|
If the JWT secret is empty. |
Source code in src/synthorg/api/auth/service.py
decode_token
¶
Decode and validate a JWT.
Audience (aud) verification is intentionally disabled
here (verify_aud=False) because audience validation is
performed per-role in the auth middleware's
_resolve_jwt_user. System-user tokens require
aud=synthorg-backend; regular user tokens omit aud.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
Encoded JWT string. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Decoded claims dictionary. |
Raises:
| Type | Description |
|---|---|
SecretNotConfiguredError
|
If the JWT secret is empty. |
InvalidTokenError
|
If the token is invalid or expired. |
Source code in src/synthorg/api/auth/service.py
hash_api_key
¶
Compute HMAC-SHA256 hex digest of a raw API key.
Uses the server-side JWT secret as the HMAC key so that an attacker with read access to stored hashes cannot brute-force API keys offline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_key
|
str
|
The plaintext API key. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Lowercase hex digest. |
Raises:
| Type | Description |
|---|---|
SecretNotConfiguredError
|
If the JWT secret is empty. |
Source code in src/synthorg/api/auth/service.py
generate_api_key
staticmethod
¶
Generate a cryptographically secure API key.
Returns:
| Type | Description |
|---|---|
str
|
URL-safe base64 string (43 chars). |
middleware
¶
JWT + API key authentication middleware.
ApiAuthMiddleware
¶
Bases: AbstractAuthenticationMiddleware
Authenticate requests via JWT or API key.
Reads Authorization: Bearer <token> from the request.
Tokens containing . are treated exclusively as JWTs.
Tokens without dots are tried as API keys via HMAC-SHA256
hash lookup.
Requires auth_service, persistence backend on
app.state["app_state"].
authenticate_request
async
¶
Validate the Authorization header.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
ASGIConnection[Any, Any, Any, Any]
|
Incoming ASGI connection. |
required |
Returns:
| Type | Description |
|---|---|
AuthenticationResult
|
AuthenticationResult with AuthenticatedUser. |
Raises:
| Type | Description |
|---|---|
NotAuthorizedException
|
If authentication fails. |
Source code in src/synthorg/api/auth/middleware.py
create_auth_middleware_class
¶
Create a middleware class with excluded paths baked in.
Litestar's AbstractAuthenticationMiddleware.__init__ takes
exclude as a parameter (default None). We create a
subclass whose __init__ forwards the configured exclude
list to super().__init__.
The middleware is restricted to ScopeType.HTTP only --
WebSocket connections use ticket-based auth handled entirely
inside the WS handler (see controllers/ws.py).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth_config
|
AuthConfig
|
Auth configuration with exclude_paths. |
required |
Returns:
| Type | Description |
|---|---|
type[ApiAuthMiddleware]
|
Middleware class ready for use in the Litestar middleware stack. |