cedarling_python.cedarling_python

class BootstrapConfig:

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.
def from_env(config=None):
def load_from_file(path):
def load_from_json(config_json):
class PolicyEvaluationError:

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.

error

Underlying evaluation error string representation

id

Id of the policy with an error

class Diagnostics:

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.

errors

Errors that occurred during authorization. The errors should be treated as unordered, since policies may be evaluated in any order.

reason

PolicyIds of the policies that contributed to the decision. If no policies applied to the request, this set will be empty.

class Decision:

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.

value

get the value of the decision

class EntityData:

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.

def from_dict(cls, /, value):

method to build a resource data object from a python dictionary

cedar_mapping

Cedar entity mapping info

payload

setter for payload attribute

class CedarEntityMapping:

Cedar entity mapping information

id

entity id

entity_type

entity type name

class RequestUnsigned:

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={})
principal
options

Per-call options; never change the decision. The getter returns a copy, so mutating req.options.trace is discarded; assign new options instead.

action

cedar_policy action

resource

cedar_policy resource data

context

context to be used in cedar_policy; deserialized on every to_cedarling() call so mutations to the source dict (or nested values) are always picked up.

class TokenInput:

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...")
mapping

Token mapping type

payload

JWT token string

class AuthorizeMultiIssuerRequest:

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"}
)
resource

cedar_policy resource data

action

cedar_policy action

options

Per-call options; never change the decision. The getter returns a copy, so mutating req.options.trace is discarded; assign new options instead.

tokens

List of TokenInput objects. Getter materializes a fresh Python list, so req.tokens.append(t) is silently discarded — reassign to mutate.

context

Optional context dict; deserialized on every to_cedarling() call so mutations to the source dict (or nested values) are always picked up.

class BatchItem:

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={})
resource
action
context

Per-item context dict; deserialized on every to_cedarling() call so mutations to the source dict (or nested values) are always picked up.

class BatchItemError:

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

message
category
item_index
class BatchItemUnsignedResult:

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.

def is_ok(self, /):

True when Cedar evaluated this item (Allow or Deny); False when the item failed to build.

def unwrap(self, /):

The AuthorizeResult if is_ok(); raises ValueError otherwise.

error

The per-item BatchItemError if !is_ok(); None otherwise.

class BatchItemMultiIssuerResult:

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.

def is_ok(self, /):
def unwrap(self, /):
error
class BatchAuthorizeUnsignedRequest:

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={}), ...],
)
principal
items

Getter materializes a fresh Python list, so req.items.append(i) is silently discarded — reassign to mutate.

options

Per-call options; never change the decision. The getter returns a copy, so mutating req.options.trace is discarded; assign new options instead.

class BatchAuthorizeMultiIssuerRequest:

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={}), ...],
)
tokens

Getter materializes a fresh Python list, so req.tokens.append(t) is silently discarded — reassign to mutate.

items

Getter materializes a fresh Python list, so req.items.append(i) is silently discarded — reassign to mutate.

options

Per-call options; never change the decision. The getter returns a copy, so mutating req.options.trace is discarded; assign new options instead.

class BatchAuthorizeUnsignedResponse:

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.

results
batch_id
class BatchAuthorizeMultiIssuerResponse:

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.

batch_id
results
class AuthorizeResultResponse:

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).

decision

Authorization decision

diagnostics

Diagnostics providing more information on how this decision was reached

class AuthorizeResult:

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.

def is_allowed(self, /):

Returns true if request is allowed

def request_id(self, /):

Get the request ID associated with this result

response

Returns the underlying cedar_policy Response for this request.

class MultiIssuerAuthorizeResult:

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).

def is_allowed(self, /):

Returns true if request is allowed

def response(self, /):

Get the Cedar policy response

def request_id(self, /):

Get the request ID associated with this result

def dropped_tokens(self, /):

Tokens dropped from this decision (empty when every token was used).

class DroppedToken:

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.

index
mapping
reason
class DropReason:

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.

message
detail
kind
class PolicyEffect:

PolicyEffect

Represents the effect of a Cedar policy.

Values

  • Permit: The policy permits the request.
  • Forbid: The policy forbids the request.
class PolicyMetadata:

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.

annotations

Key-value pairs from Cedar policy annotations.

effect

The policy effect as a PolicyEffect enum.

source

The Cedar policy source code.

id

The policy ID.

class TraceContext:

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",
)
execution_authority
workload_instance_id
execution_id
workload_id
class AuthorizeOptions:

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)
trace
class CedarType:

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
String = CedarType.String
Record = CedarType.Record
Entity = CedarType.Entity
Decimal = CedarType.Decimal
DateTime = CedarType.DateTime
Duration = CedarType.Duration
class DataEntry:

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

value

Get the value stored in this entry

expires_at

Get the expiration timestamp (RFC 3339 format), or None if no TTL

key

Get the key for this entry

data_type

Get the Cedar type of this entry

created_at

Get the creation timestamp (RFC 3339 format)

access_count

Get the access count

class DataStoreStats:

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

max_entry_size

Maximum size per entry in bytes (0 = unlimited)

max_entries

Maximum number of entries allowed (0 = unlimited)

memory_alert_triggered

Whether memory usage exceeds the alert threshold

capacity_usage_percent

Percentage of capacity used (0.0-100.0, based on entry count)

avg_entry_size_bytes

Average size per entry in bytes (0 if no entries)

entry_count

Number of entries currently stored

metrics_enabled

Whether metrics tracking is enabled

total_size_bytes

Total size of all entries in bytes (approximate, based on JSON serialization)

memory_alert_threshold

Memory usage threshold percentage (from config)

class Cedarling:

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.
def authorize_unsigned(self, /, request):

Authorize request with unsigned data.

def authorize_multi_issuer(self, /, request):

Authorize multi-issuer request. Makes authorization decision based on multiple JWT tokens from different issuers.

def authorize_unsigned_batch(self, /, request):

Authorize a batch of unsigned requests against one shared principal.

Setup work (principal build + pushed-data snapshot) runs once and each item is evaluated in input order. Returns a BatchAuthorizeUnsignedResponse with batch_id and per-item results.

Batch-level failures (validation, principal parse) raise; per-item failures are returned as BatchItemError entries that callers must inspect.

def authorize_multi_issuer_batch(self, /, request):

Authorize a batch of multi-issuer requests against one shared token set.

Tokens are validated and token/issuer entities built once, then each item is evaluated in input order. Returns a BatchAuthorizeMultiIssuerResponse with batch_id and per-item results.

Batch-level failures (validation, JWT verification, status-list refresh) raise; per-item failures are returned as BatchItemError entries that callers must inspect.

def get_matching_policies_unsigned(self, /, principal, actions, resources):

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.

def get_matching_policies_multi_issuer(self, /, tokens, actions, resources):

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.

def annotations_map(self, /, policy_ids):

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.

def annotation_values(self, /, policy_ids, key):

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.

def annotations_by_policy(self, /, policy_ids):

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.

def pop_logs(self, /):

Return logs and remove them from the storage

def get_log_by_id(self, /, id):

Get specific log entry

def get_log_ids(self, /):

Returns a list of all log ids

def get_logs_by_tag(self, /, tag):

Returns a list of log entries by tag. Tag can be log_kind, log_level.

def get_logs_by_request_id(self, /, request_id):

Returns a list of log entries by request id.

def get_logs_by_request_id_and_tag(self, /, id, tag):

Returns a list of all log entries by request id and tag. Tag can be log_kind, log_level.

def shut_down(self, /):

Closes the connections to the Lock Server and pushes all available logs.

def push_data_ctx(self, /, key, value, ttl_secs=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

def get_data_ctx(self, /, key):

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

def get_data_entry_ctx(self, /, key):

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

def remove_data_ctx(self, /, key):

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

def clear_data_ctx(self, /):

Clear all entries from the data store.

:raises DataErrorCtx: If the operation fails

def list_data_ctx(self, /):

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

def get_stats_ctx(self, /):

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

def drain_metrics(self, /):

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.

def policy_store_id(self, /):

Returns the ID of the currently published policy store, if it carries one.

def is_trusted_issuer_loaded_by_name(self, /, issuer_name):

Returns true if the trusted issuer with the given name (its issuer) is loaded.

def is_trusted_issuer_loaded_by_iss(self, /, iss_claim):

Returns true if trusted issuer with the given iss claim is loaded.

def total_issuers(self, /):

Returns total number of configured trusted issuers.

def loaded_trusted_issuers_count(self, /):

Returns number of successfully loaded trusted issuers.

def loaded_trusted_issuer_ids(self, /):

Returns ids of successfully loaded trusted issuers.

def failed_trusted_issuer_ids(self, /):

Returns ids of trusted issuers that failed to load.

class MetricsSnapshot:

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.

policy_stats

Per-policy evaluation counts.

interval

Duration of the snapshot interval with sub-second precision.

error_counters

Classified error counters.

operational_stats

Operational counters and gauges.