cedarling_python.cedarling_python
BootstrapConfig
A Python wrapper for the Rust cedarling::BootstrapConfig struct.
Configures the Cedarling application, including authorization, logging, and policy store settings.
Methods
.. method:: __init__(self, options)
Initializes the Cedarling instance with the provided configuration.
:param options: A `dict` with startup settings.
.. method:: load_from_file(str) -> BootstrapConfig
Loads the bootstrap config from a file.
:returns: A BootstrapConfig instance
:raises ValueError: If a provided value is invalid or decoding fails.
:raises OSError: If there is an error reading while the file.
.. method:: load_from_json(str) -> BootstrapConfig
Loads the bootstrap config from a JSON string.
:returns: A BootstrapConfig instance
:raises ValueError: If a provided value is invalid or decoding fails.
.. method:: from_env(config=None) -> BootstrapConfig
Loads the bootstrap config from environment variables, optionally merging with provided config.
:param config: Optional dictionary with additional configuration to merge with environment variables.
:returns: A BootstrapConfig instance
:raises ValueError: If a provided value is invalid or decoding fails.
PolicyEvaluationError
Represents an error that occurred when evaluating a Cedar policy.
Attributes
id : str The ID of the policy that caused the error. error : str The error message describing the evaluation failure.
Diagnostics
Provides detailed information about how a policy decision was made, including policies that contributed to the decision and any errors encountered during evaluation.
Attributes
reason : set of str
A set of PolicyIds for the policies that contributed to the decision. If no policies applied, this set is empty.
errors : list of PolicyEvaluationError
A list of errors that occurred during the authorization process. These are unordered as policies may be evaluated in any order.
Decision
Represents the decision result of a Cedar policy authorization.
Methods
value() -> str
Returns the string value of the decision.
__str__() -> str
Returns the string representation of the decision.
__repr__() -> str
Returns the detailed type representation of the decision.
__eq__(other: Decision) -> bool
Compares two Decision objects for equality.
EntityData
A Python wrapper for the Rust cedarling::EntityData struct. This class represents
a resource entity with Cedar mapping information and attributes. Attributes are stored as a payload
in a dictionary format.
Attributes
:param cedar_entity_mapping: Cedar entity mapping information containing entity_type and id. :param payload: Optional dictionary of attributes.
Methods
.. method:: __init__(self, entity_type: str, id: str, **kwargs: dict) Initialize a new EntityData. In kwargs the payload is a dictionary of entity attributes.
.. method:: from_dict(cls, value: dict) -> EntityData
Initialize a new EntityData from a dictionary.
The dictionary should contain a cedar_entity_mapping field with entity_type and id subfields.
Cedar entity mapping information
RequestUnsigned
A Python wrapper for the Rust cedarling::RequestUnsigned struct. Represents
authorization data for an unsigned authorization request for an optional single
principal.
Attributes
:param principal: Optional EntityData representing the principal. When None,
the core performs partial evaluation of the policies.
:param action: The action to be authorized.
:param resource: Resource data (wrapped ResourceData object).
:param context: Python dictionary with additional context.
:param options: Optional AuthorizeOptions, e.g. a TRACE context.
Example
# Create a request for authorization
request = RequestUnsigned(principal=principal, action="read", resource=resource, context={})
TokenInput
A Python wrapper for the Rust cedarling::TokenInput struct.
Represents a JWT token with explicit type mapping for multi-issuer authorization.
Attributes
:param mapping: Token mapping type (e.g., "Jans::Access_Token", "Acme::DolphinToken") :param payload: JWT token string
Example
# Create a token input for multi-issuer authorization
token = TokenInput(mapping="Jans::Access_Token", payload="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
AuthorizeMultiIssuerRequest
A Python wrapper for the Rust cedarling::AuthorizeMultiIssuerRequest struct.
Represents a multi-issuer authorization request with multiple JWT tokens from different issuers.
Attributes
:param tokens: List of TokenInput objects containing JWT tokens with explicit type mappings
:param resource: Resource data (wrapped EntityData object)
:param action: The action to be authorized
:param context: Optional Python dictionary with additional context
:param options: Optional AuthorizeOptions, e.g. a TRACE context.
Example
# Create a multi-issuer authorization request
tokens = [
TokenInput(mapping="Jans::Access_Token", payload="eyJhbGc..."),
TokenInput(mapping="Acme::DolphinToken", payload="eyJhbGc...")
]
request = AuthorizeMultiIssuerRequest(
tokens=tokens,
resource=resource,
action="Read",
context={"location": "miami"}
)
Per-call options; never change the decision. The getter returns a copy,
so mutating req.options.trace is discarded; assign new options instead.
BatchItem
A Python wrapper for the Rust cedarling::BatchItem struct. Represents one
{resource, action, context} triple inside a batch authorization request.
Attributes
:param resource: EntityData describing the resource for this item.
:param action: The action string for this item (e.g., 'Jans::Action::"Read"').
:param context: Optional Python dict of per-item context. None defaults to {}.
Example
item = BatchItem(resource=resource, action="Jans::Action::\"Read\"", context={})
BatchItemError
Per-item preparation/validation failure surfaced inside a batch response at
results[i].error.
Attributes
:param category: Stable variant slug (action_parse, resource_build,
context_build, principal_build, schema_validation,
multi_issuer_entity, request_validation).
:type category: str
:param item_index: Position of the failing item in the original items list.
:type item_index: int
:param message: Human-readable diagnostic. Safe to log.
:type message: str
BatchItemUnsignedResult
One slot in a batch unsigned response's results list. Callers switch on
is_ok() — on True, call unwrap() for the AuthorizeResult; on False,
read .error for the BatchItemError.
BatchItemMultiIssuerResult
A Python wrapper for a single result slot in a multi-issuer batch response.
Use is_ok() to check success, unwrap() to retrieve the
MultiIssuerAuthorizeResult when True, and the error property
to retrieve the BatchItemError when False.
BatchAuthorizeUnsignedRequest
A Python wrapper for the Rust cedarling::BatchAuthorizeUnsignedRequest.
Bundles one optional principal with N BatchItems; every item is evaluated
against the same principal snapshot and pushed-data snapshot.
Attributes
:param principal: Optional EntityData shared across every item.
:param items: List of BatchItem objects, evaluated in input order.
:param options: Optional AuthorizeOptions, e.g. a TRACE context.
Example
req = BatchAuthorizeUnsignedRequest(
principal=principal,
items=[BatchItem(resource=res1, action="Read", context={}), ...],
)
BatchAuthorizeMultiIssuerRequest
A Python wrapper for the Rust cedarling::BatchAuthorizeMultiIssuerRequest.
Bundles one token set with N BatchItems; tokens are validated and token
entities built once for the whole batch.
Attributes
:param tokens: List of TokenInput shared across every item.
:param items: List of BatchItem objects, evaluated in input order.
:param options: Optional AuthorizeOptions, e.g. a TRACE context.
Example
req = BatchAuthorizeMultiIssuerRequest(
tokens=[TokenInput(mapping="Jans::Access_Token", payload="eyJ...")],
items=[BatchItem(resource=res1, action="Read", context={}), ...],
)
Getter materializes a fresh Python list, so req.tokens.append(t) is
silently discarded — reassign to mutate.
A Python wrapper for cedarling::BatchAuthorizeResponse<Result<AuthorizeResult, BatchItemError>>.
Carries a shared batch_id (UUIDv7) alongside per-item results. Each entry
in results is a BatchItemUnsignedResult — an AuthorizeResult when
Cedar reached a decision, or a BatchItemError when the item failed during
per-item preparation or request validation. results[i] corresponds to the
items[i] supplied to the request.
Attributes: batch_id (str): The shared UUIDv7 identifier for this batch evaluation. results (List[BatchItemUnsignedResult]): The evaluation results, in input order.
Multi-issuer analog of BatchAuthorizeUnsignedResponse.
Attributes: batch_id (str): The shared UUIDv7 identifier for this batch evaluation. results (List[BatchItemMultiIssuerResult]): The evaluation results, in input order.
AuthorizeResultResponse
A Python wrapper for the Rust cedar_policy::Response struct.
Represents the result of an authorization request.
Attributes
:param decision: The authorization decision (wrapped Decision object).
:param diagnostics: Additional information on the decision (wrapped Diagnostics object).
AuthorizeResult
A Python wrapper for the Rust cedarling::AuthorizeResult struct.
Represents the result of an authorization request.
Methods
.. method:: is_allowed(self) -> bool Returns whether the request is allowed.
MultiIssuerAuthorizeResult
A Python wrapper for the Rust cedarling::MultiIssuerAuthorizeResult struct.
Represents the result of a multi-issuer authorization request.
Methods
.. method:: is_allowed(self) -> bool Returns whether the request is allowed.
.. method:: response(self) -> AuthorizeResultResponse Returns the detailed Cedar policy response.
.. method:: request_id(self) -> str Returns the unique request ID for this authorization.
.. method:: dropped_tokens(self) -> list[DroppedToken] Returns the tokens the caller supplied that were not used in this decision (empty when every token contributed).
DroppedToken
A token the caller supplied that multi-issuer authorization did not use.
Identifies the entry by its input mapping and zero-based index, with a
claim-free reason.
Attributes
.. attribute:: mapping
str: the Cedar entity-type mapping of the dropped input.
.. attribute:: index
int: zero-based position in the request's tokens list.
.. attribute:: reason
DropReason: why the token was dropped.
DropReason
Why a token was dropped from a multi-issuer authorization. Same shape as
the reason object in the core JSON.
Attributes
.. attribute:: kind
str: stable snake-case slug (e.g. "jwt_validation_failed").
.. attribute:: detail
str | None: stable detail slug for invalid_input
("empty_mapping" / "empty_payload"); None otherwise.
.. attribute:: message
str: claim-free human-readable message; non-empty for every reason.
PolicyEffect
Represents the effect of a Cedar policy.
Values
- Permit: The policy permits the request.
- Forbid: The policy forbids the request.
PolicyMetadata
Metadata about a Cedar policy, including its ID, effect, annotations, and source code.
Attributes
:param id: The policy ID string. :param effect: The policy effect as a PolicyEffect enum value. :param annotations: Dictionary of policy annotations. :param source: The Cedar policy source code.
TraceContext
A Python wrapper for the Rust cedarling::TraceContext struct.
TRACE execution context, already normalized by the host. Cedarling does not
parse headers, tokens or baggage and never generates execution_id: the
execution initiator (gateway, PEP, host) owns the execution_id +
execution_authority pair.
Attributes
:param execution_id: trace_execution_id issued by the execution initiator.
:param execution_authority: Authority that issued execution_id.
:param workload_id: Stable id of the workload the decision is made for.
:param workload_instance_id: Optional instance of that workload.
Example
trace = TraceContext(
execution_id="exec-01JABC",
execution_authority="https://gateway.example.com",
workload_id="spiffe://example.org/agent/planner",
)
AuthorizeOptions
A Python wrapper for the Rust cedarling::AuthorizeOptions struct.
Per-call metadata that travels with an authorization request. None of it
takes part in policy evaluation: the decision is the same with or without
options.
Attributes
:param trace: Optional TraceContext. None means the host has no
execution context, so no TRACE record can be emitted for the decision.
The getter returns a copy, so opts.trace.workload_id = ... is
discarded; assign a new TraceContext instead.
Example
options = AuthorizeOptions(trace=TraceContext("exec-1", "https://gw.example.com", "workload-1"))
request = RequestUnsigned(action=action, resource=resource, context={}, options=options)
CedarType
Represents the type of a Cedar value based on JSON structure.
Values
- String: String type
- Long: Long (integer) type
- Bool: Boolean type
- Set: Set (array) type
- Record: Record (object) type
- Entity: Entity reference type
- Ip: IP address extension type (ipaddr)
- Decimal: Decimal extension type
- DateTime: DateTime extension type
- Duration: Duration extension type
DataEntry
A data entry in the DataStore with value and metadata.
Attributes
key : str The key for this entry value : dict | list | str | int | float | bool | None The actual value stored, deserialized from JSON — may be any JSON-compatible Python shape data_type : CedarType The inferred Cedar type of the value created_at : str Timestamp when this entry was created (RFC 3339 format) expires_at : str | None Timestamp when this entry expires (RFC 3339 format), or None if no TTL access_count : int Number of times this entry has been accessed
DataStoreStats
Statistics about the DataStore.
Attributes
entry_count : int Number of entries currently stored max_entries : int Maximum number of entries allowed (0 = unlimited) max_entry_size : int Maximum size per entry in bytes (0 = unlimited) metrics_enabled : bool Whether metrics tracking is enabled total_size_bytes : int Total size of all entries in bytes (approximate, based on JSON serialization) avg_entry_size_bytes : int Average size per entry in bytes (0 if no entries) capacity_usage_percent : float Percentage of capacity used (0.0-100.0, based on entry count) memory_alert_threshold : float Memory usage threshold percentage (from config) memory_alert_triggered : bool Whether memory usage exceeds the alert threshold
Cedarling
A Python wrapper for the Rust cedarling::Cedarling struct.
Represents an instance of the Cedarling application, a local authorization service
that answers authorization questions based on JWT tokens.
Attributes
:param config: A BootstrapConfig object for initializing the Cedarling instance.
Methods
.. method:: __init__(self, config)
Initializes the Cedarling instance with the provided configuration.
:param config: A `BootstrapConfig` object with startup settings.
.. method:: authorize_unsigned(self, request: RequestUnsigned) -> AuthorizeResult
Authorize request with unsigned data.
:param request: RequestUnsigned struct for authorize.
.. method:: authorize_multi_issuer(self, request: AuthorizeMultiIssuerRequest) -> MultiIssuerAuthorizeResult
Authorize multi-issuer request.
Makes authorization decision based on multiple JWT tokens from different issuers.
:param request: AuthorizeMultiIssuerRequest struct for authorize.
.. method:: pop_logs(self) -> List[dict]
Retrieves and removes all logs from storage.
:returns: A list of log entries as Python objects.
.. method:: get_log_by_id(self, id: str) -> dict|None
Gets a log entry by its ID.
:param id: The log entry ID.
.. method:: get_log_ids(self) -> List[str]
Retrieves all stored log IDs.
.. method:: get_logs_by_tag(self, tag: str) -> List[dict]
Retrieves all logs matching a specific tag. Tags can be 'log_kind', 'log_level' params from log entries.
:param tag: A string specifying the tag type.
:returns: A list of log entries filtered by the tag, each converted to a Python dictionary.
.. method:: get_logs_by_request_id(self, id: str) -> List[dict]
Retrieves log entries associated with a specific request ID. Each log entry is converted to a Python dictionary containing fields like 'id', 'timestamp', and 'message'.
:param id: The unique identifier for the request.
:returns: A list of dictionaries, each representing a log entry related to the specified request ID.
.. method:: get_logs_by_request_id_and_tag(self, id: str, tag: str) -> List[dict]
Retrieves all logs associated with a specific request ID and tag. The tag can be 'log_kind', 'log_level' params from log entries.
:param id: The request ID as a string.
:param tag: The tag type as a string.
:returns: A list of log entries matching both the request ID and tag, each converted to a Python dictionary.
.. method:: shut_down(self)
Closes the connections to the Lock Server and pushes all available logs.
.. method:: push_data_ctx(self, key: str, value: Any, ttl_secs: int | None = None)
Push a value into the data store with an optional TTL.
If the key already exists, the value will be replaced.
If TTL is not provided, the default TTL from configuration is used.
:param key: The key for the data entry
:param value: The value to store (dict, list, str, int, float, bool)
:param ttl_secs: Optional TTL in seconds (None uses default from config)
:raises DataErrorCtx: If the operation fails
.. method:: get_data_ctx(self, key: str) -> Any | None
Get a value from the data store by key.
Returns None if the key doesn't exist or the entry has expired.
:param key: The key to retrieve
:returns: The value as a Python object, or None if not found
:raises DataErrorCtx: If the operation fails
.. method:: get_data_entry_ctx(self, key: str) -> DataEntry | None
Get a data entry with full metadata by key.
Returns None if the key doesn't exist or the entry has expired.
:param key: The key to retrieve
:returns: A DataEntry object with metadata, or None if not found
:raises DataErrorCtx: If the operation fails
.. method:: remove_data_ctx(self, key: str) -> bool
Remove a value from the data store by key.
:param key: The key to remove
:returns: True if the key existed and was removed, False otherwise
:raises DataErrorCtx: If the operation fails
.. method:: clear_data_ctx(self)
Clear all entries from the data store.
:raises DataErrorCtx: If the operation fails
.. method:: list_data_ctx(self) -> List[DataEntry]
List all entries with their metadata.
Returns a list of DataEntry objects containing key, value, type, and timing metadata.
:returns: A list of DataEntry objects
:raises DataErrorCtx: If the operation fails
.. method:: get_stats_ctx(self) -> DataStoreStats
Get statistics about the data store.
Returns current entry count, capacity limits, and configuration state.
:returns: A DataStoreStats object
:raises DataErrorCtx: If the operation fails
.. method:: drain_metrics(self) -> MetricsSnapshot
Destructive read: returns the telemetry metrics snapshot and resets
the counters for the next interval.
Only available when `CEDARLING_METRICS_COLLECTION` is enabled and no
Lock telemetry ticker owns the collector. Raises `ValueError` when
Lock telemetry owns the collector, i.e. whenever
`CEDARLING_LOCK_TELEMETRY_INTERVAL` is set, even if the Lock
server has no telemetry endpoint. `interval` is a
`datetime.timedelta` with sub-second precision.
:returns: A MetricsSnapshot object
:raises ValueError: If metrics collection is disabled or owned by lock telemetry.
.. method:: policy_store_id(self) -> str | None
Returns the ID of the currently published policy store, if it carries one.
:returns: The store ID, or None when the store carries no ID.
Returns metadata for all policies whose scope constraints are compatible with the given principal, actions, and resources.
This performs scope-level filtering only (principal/action/resource constraints).
Policies with when/unless conditions may still not apply at evaluation time.
:param principal: Optional EntityData representing the principal entity. When
None, policies are filtered assuming an unknown principal.
:param actions: List of action strings (e.g., 'Jans::Action::"Read"').
:param resources: List of EntityData representing resource entities.
:returns: A list of PolicyMetadata objects for matching policies.
:raises AuthorizeError: If policy matching fails.
Returns metadata for all policies whose scope constraints are compatible with the given token-derived principals, actions, and resources.
Tokens are validated and their mapping types used as principal entity types.
:param tokens: List of TokenInput representing JWT tokens with mapping types. :param actions: List of action strings (e.g., 'Jans::Action::"Read"'). :param resources: List of EntityData representing resource entities. :returns: A list of PolicyMetadata objects for matching policies. :raises AuthorizeError: If token validation or policy matching fails.
Merge the annotations (@key("value")) of the given policies into a single dict.
Intended for resolving the determining policies of an authorization decision:
pass list(result.response.diagnostics.reason).
Lossy: if the same annotation key appears on several policies, one value wins
arbitrarily. Use annotation_values / annotations_by_policy when duplicates
matter. Unknown policy IDs are silently skipped.
:param policy_ids: List of policy ID strings. :returns: A dict mapping annotation keys to values.
Collect every value of the annotation key across the given policies,
preserving duplicates. Unknown policy IDs are silently skipped.
:param policy_ids: List of policy ID strings. :param key: The annotation key to look up. :returns: A list of annotation values.
Return the annotations of each given policy, grouped by policy ID
the loss-free companion to annotations_map. Unknown policy IDs are
silently skipped.
:param policy_ids: List of policy ID strings. :returns: A dict mapping policy IDs to their annotation dicts.
Returns a list of log entries by tag.
Tag can be log_kind, log_level.
Returns a list of all log entries by request id and tag.
Tag can be log_kind, log_level.
Push a value into the data store with an optional TTL.
If the key already exists, the value will be replaced. If TTL is not provided, the default TTL from configuration is used.
:param key: The key for the data entry :param value: The value to store (dict, list, str, int, float, bool) :param ttl_secs: Optional TTL in seconds (None uses default from config) :raises DataErrorCtx: If the operation fails
Get a value from the data store by key.
Returns None if the key doesn't exist or the entry has expired. If metrics are enabled, increments the access count for the entry.
:param key: The key to retrieve :returns: The value as a Python object, or None if not found :raises DataErrorCtx: If the operation fails
Get a data entry with full metadata by key.
Returns None if the key doesn't exist or the entry has expired. Includes metadata like creation time, expiration, access count, and type.
:param key: The key to retrieve :returns: A DataEntry object with metadata, or None if not found :raises DataErrorCtx: If the operation fails
Remove a value from the data store by key.
:param key: The key to remove :returns: True if the key existed and was removed, False otherwise :raises DataErrorCtx: If the operation fails
Clear all entries from the data store.
:raises DataErrorCtx: If the operation fails
List all entries with their metadata.
Returns a list of DataEntry objects containing key, value, type, and timing metadata.
:returns: A list of DataEntry objects :raises DataErrorCtx: If the operation fails
Get statistics about the data store.
Returns current entry count, capacity limits, and configuration state.
:returns: A DataStoreStats object :raises DataErrorCtx: If the operation fails
Destructive read: returns the telemetry metrics snapshot and resets the counters for the next interval.
Only available when CEDARLING_METRICS_COLLECTION is enabled and no
Lock telemetry ticker owns the collector (raises ValueError when
Lock telemetry owns the collector, i.e. whenever
CEDARLING_LOCK_TELEMETRY_INTERVAL is set, even if the Lock
server has no telemetry endpoint). interval is a
datetime.timedelta with sub-second precision.
Returns the ID of the currently published policy store, if it carries one.
Returns true if the trusted issuer with the given name (its issuer) is loaded.
MetricsSnapshot
Destructive read: telemetry metrics snapshot with per-policy stats, error counters, and operational counters for the current interval. Draining resets the counters, so use a single consumer.
Attributes
policy_stats : dict
Per-policy evaluation counts (policy_id, policy_id.allow,
policy_id.deny)
error_counters : dict
Classified error counters keyed by error metric key
operational_stats : dict
Operational counters and gauges (authorization, cache, JWT, data, lock)
interval : datetime.timedelta
Duration of the snapshot interval with sub-second precision.