Skip to main content

cedarling_uniffi/
lib.rs

1// This software is available under the Apache-2.0 license.
2// See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
3//
4// Copyright (c) 2024, Gluu, Inc.
5#![cfg(not(target_arch = "wasm32"))]
6
7use cedarling::{
8    self as core, BootstrapConfig, BootstrapConfigRaw, DataApi, DataEntry as CoreDataEntry,
9    DataStoreStats as CoreDataStoreStats, LogStorage, MetricsError as CoreMetricsError,
10    MetricsSnapshot as CoreMetricsSnapshot, PolicyStoreSource, TrustedIssuerLoadingInfo,
11};
12use std::sync::Arc;
13/// Result types returned by authorization calls.
14pub mod result;
15use result::{
16    AuthorizeResult, BatchAuthorizeMultiIssuerResponse, BatchAuthorizeUnsignedResponse,
17    MultiIssuerAuthorizeResult,
18};
19use serde_json::Value;
20use std::collections::HashMap;
21use std::time::Duration;
22#[cfg(test)]
23mod tests;
24
25#[cfg(target_os = "android")]
26mod android;
27
28uniffi::setup_scaffolding!();
29
30// Enum representing initialization errors
31#[derive(Debug, thiserror::Error, uniffi::Enum)]
32pub enum CedarlingError {
33    #[error("Initialization Error: {error_msg}")]
34    InitializationFailed { error_msg: String },
35}
36
37// Enum representing authorization errors
38#[derive(Debug, thiserror::Error, uniffi::Enum)]
39pub enum AuthorizeError {
40    #[error("Authorization Error: {error_msg}")]
41    AuthorizationFailed { error_msg: String },
42    #[error("Invalid context json data provided")]
43    InvalidContext,
44    #[error("Invalid input: {error_msg}")]
45    InvalidInput { error_msg: String },
46}
47
48// Enum representing logging errors
49#[derive(Debug, thiserror::Error, uniffi::Enum)]
50pub enum LogError {
51    #[error("Logging Error: {error_msg}")]
52    LoggingFailed { error_msg: String },
53}
54
55// Enum representing data store errors
56// Mirrors the core DataError variants to allow programmatic error matching
57#[derive(Debug, thiserror::Error, uniffi::Enum)]
58pub enum DataError {
59    /// Invalid key provided (key is empty)
60    #[error("invalid key: key cannot be empty")]
61    InvalidKey,
62
63    /// Key not found in store
64    #[error("key not found: {key}")]
65    KeyNotFound {
66        /// The key that was not found
67        key: String,
68    },
69
70    /// Storage limit exceeded
71    #[error("storage limit exceeded: max {max} entries")]
72    StorageLimitExceeded {
73        /// Maximum allowed entries
74        max: u64,
75    },
76
77    /// TTL exceeds maximum allowed
78    #[error("TTL exceeds max allowed")]
79    TTLExceeded {
80        /// The requested TTL in seconds
81        requested: u64,
82        /// The maximum allowed TTL in seconds
83        max: u64,
84    },
85
86    /// Value too large
87    #[error("value size {size} bytes exceeds max {max} bytes")]
88    ValueTooLarge {
89        /// Actual size in bytes
90        size: u64,
91        /// Maximum allowed size in bytes
92        max: u64,
93    },
94
95    /// Serialization error
96    #[error("serialization error: {0}")]
97    SerializationError(String),
98}
99
100/// Error returned by [`Cedarling::drain_metrics`](crate::Cedarling::drain_metrics)
101/// when a local metrics snapshot is not available.
102#[derive(Debug, thiserror::Error, uniffi::Error)]
103pub enum MetricsError {
104    /// Local metrics collection is disabled. Enable it by setting
105    /// `CEDARLING_METRICS_COLLECTION=enabled`.
106    #[error("metrics collection is disabled")]
107    NotEnabled,
108    /// The metrics collector is owned by the Lock telemetry ticker; enabling
109    /// `CEDARLING_METRICS_COLLECTION` will not help. Returned whenever
110    /// `CEDARLING_LOCK_TELEMETRY_INTERVAL` is set, even if the Lock server
111    /// has no telemetry endpoint and metrics are not shipped anywhere.
112    #[error("metrics collection is owned by the lock telemetry ticker")]
113    LockTelemetry,
114}
115
116impl From<CoreMetricsError> for MetricsError {
117    fn from(err: CoreMetricsError) -> Self {
118        match err {
119            CoreMetricsError::Disabled => MetricsError::NotEnabled,
120            CoreMetricsError::LockTelemetry => MetricsError::LockTelemetry,
121        }
122    }
123}
124
125#[derive(Debug, Clone, uniffi::Object)]
126pub struct EntityData {
127    inner: core::EntityData,
128}
129
130#[derive(Debug, thiserror::Error, uniffi::Error)]
131pub enum EntityError {
132    #[error("JSON conversion failed: {0}")]
133    JsonConversion(String),
134    #[error("JSON conversion failed for payload key: {0}, value: {1}")]
135    JsonConversionPayload(String, String),
136}
137
138/// TokenInput for multi-issuer authorization
139#[derive(Debug, Clone, uniffi::Record)]
140pub struct TokenInput {
141    /// Token mapping type (e.g., "Jans::Access_Token", "Acme::DolphinToken")
142    pub mapping: String,
143    /// JWT token string
144    pub payload: String,
145}
146
147/// TRACE execution context, already normalized by the host. Cedarling never
148/// generates `execution_id`: the execution initiator (gateway, PEP, host) owns
149/// it together with `execution_authority`.
150#[derive(Debug, Clone, uniffi::Record)]
151pub struct TraceContext {
152    /// `trace_execution_id` issued by the execution initiator
153    pub execution_id: String,
154    /// Authority that issued `execution_id`
155    pub execution_authority: String,
156    /// Stable id of the workload the decision is made for
157    pub workload_id: String,
158    /// Instance of the workload, when the host distinguishes instances
159    #[uniffi(default)]
160    pub workload_instance_id: Option<String>,
161}
162
163/// Per-call metadata of an authorization request. None of it takes part in
164/// policy evaluation: the decision is the same with or without options.
165#[derive(Debug, Clone, uniffi::Record)]
166pub struct AuthorizeOptions {
167    /// `None` means the host has no execution context, so no TRACE record can
168    /// be emitted for the decision.
169    #[uniffi(default)]
170    pub trace: Option<TraceContext>,
171}
172
173impl From<TraceContext> for core::TraceContext {
174    fn from(value: TraceContext) -> Self {
175        core::TraceContext {
176            execution_id: value.execution_id,
177            execution_authority: value.execution_authority,
178            workload_id: value.workload_id,
179            workload_instance_id: value.workload_instance_id,
180        }
181    }
182}
183
184impl From<AuthorizeOptions> for core::AuthorizeOptions {
185    fn from(value: AuthorizeOptions) -> Self {
186        core::AuthorizeOptions {
187            trace: value.trace.map(Into::into),
188        }
189    }
190}
191
192/// `None` options are the same as default options.
193fn options_to_core(options: Option<AuthorizeOptions>) -> core::AuthorizeOptions {
194    options.map(Into::into).unwrap_or_default()
195}
196
197/// One `{resource, action, context}` triple in a batch authorization request.
198///
199/// `context` is optional; `None` defaults to `{}` at conversion time.
200#[derive(Debug, Clone, uniffi::Record)]
201pub struct BatchItem {
202    pub resource: Arc<EntityData>,
203    pub action: String,
204    #[uniffi(default)]
205    pub context: Option<JsonValue>,
206}
207
208/// Data entry with value and metadata
209#[derive(Debug, Clone, uniffi::Record)]
210pub struct DataEntry {
211    /// The key for this entry
212    pub key: String,
213    /// The actual value stored (as JSON string)
214    pub value: JsonValue,
215    /// The inferred Cedar type of the value
216    pub data_type: String,
217    /// Timestamp when this entry was created (RFC 3339 format)
218    pub created_at: String,
219    /// Timestamp when this entry expires (RFC 3339 format), or empty string if no TTL
220    pub expires_at: String,
221    /// Number of times this entry has been accessed
222    pub access_count: u64,
223}
224
225/// Statistics about the DataStore
226#[derive(Debug, Clone, uniffi::Record)]
227pub struct DataStoreStats {
228    /// Number of entries currently stored
229    pub entry_count: u64,
230    /// Maximum number of entries allowed (0 = unlimited)
231    pub max_entries: u64,
232    /// Maximum size per entry in bytes (0 = unlimited)
233    pub max_entry_size: u64,
234    /// Whether metrics tracking is enabled
235    pub metrics_enabled: bool,
236    /// Total size of all entries in bytes (approximate, based on JSON serialization)
237    pub total_size_bytes: u64,
238    /// Average size per entry in bytes (0 if no entries)
239    pub avg_entry_size_bytes: u64,
240    /// Percentage of capacity used (0.0-100.0, based on entry count)
241    pub capacity_usage_percent: f64,
242    /// Memory usage threshold percentage (from config)
243    pub memory_alert_threshold: f64,
244    /// Whether memory usage exceeds the alert threshold
245    pub memory_alert_triggered: bool,
246}
247
248/// Telemetry metrics snapshot for the current interval.
249#[derive(Debug, Clone, uniffi::Record)]
250pub struct MetricsSnapshot {
251    /// Per-policy evaluation counts (`policy_id`, `policy_id.allow`, `policy_id.deny`).
252    pub policy_stats: HashMap<String, i64>,
253    /// Classified error counters keyed by error metric key.
254    pub error_counters: HashMap<String, i64>,
255    /// Operational counters and gauges (authorization, cache, JWT, data, lock).
256    pub operational_stats: HashMap<String, i64>,
257    /// Duration of the snapshot interval with sub-second precision.
258    pub interval: Duration,
259}
260
261impl From<CoreMetricsSnapshot> for MetricsSnapshot {
262    fn from(snap: CoreMetricsSnapshot) -> Self {
263        Self {
264            policy_stats: snap.policy_stats,
265            error_counters: snap.error_counters,
266            operational_stats: snap.operational_stats,
267            interval: snap.interval,
268        }
269    }
270}
271
272impl TryFrom<CoreDataEntry> for DataEntry {
273    type Error = DataError;
274
275    fn try_from(entry: CoreDataEntry) -> Result<Self, Self::Error> {
276        // Use serde_json::to_string for stable serialization of CedarType
277        let data_type = serde_json::to_string(&entry.data_type).map_err(|e| {
278            DataError::SerializationError(format!("Failed to serialize data_type: {}", e))
279        })?;
280        // Remove quotes from the serialized string (serde_json adds quotes for enum strings)
281        let data_type = data_type.trim_matches('"').to_string();
282
283        Ok(Self {
284            key: entry.key,
285            value: JsonValue {
286                value: serde_json::to_string(&entry.value).map_err(|e| {
287                    DataError::SerializationError(format!("Failed to serialize value: {}", e))
288                })?,
289            },
290            data_type,
291            created_at: entry.created_at.to_rfc3339(),
292            expires_at: entry
293                .expires_at
294                .map(|dt| dt.to_rfc3339())
295                .unwrap_or_default(),
296            access_count: entry.access_count,
297        })
298    }
299}
300
301// Helper function to convert core DataError to uniffi DataError
302impl From<core::DataError> for DataError {
303    fn from(err: core::DataError) -> Self {
304        match err {
305            core::DataError::InvalidKey => DataError::InvalidKey,
306            core::DataError::KeyNotFound { key } => DataError::KeyNotFound { key },
307            core::DataError::StorageLimitExceeded { max } => {
308                DataError::StorageLimitExceeded { max: max as u64 }
309            },
310            core::DataError::TTLExceeded { requested, max } => DataError::TTLExceeded {
311                requested: requested.as_secs(),
312                max: max.as_secs(),
313            },
314            core::DataError::ValueTooLarge { size, max } => DataError::ValueTooLarge {
315                size: size as u64,
316                max: max as u64,
317            },
318            core::DataError::SerializationError(e) => DataError::SerializationError(e.to_string()),
319        }
320    }
321}
322
323impl From<CoreDataStoreStats> for DataStoreStats {
324    fn from(stats: CoreDataStoreStats) -> Self {
325        Self {
326            entry_count: stats.entry_count as u64,
327            max_entries: stats.max_entries as u64,
328            max_entry_size: stats.max_entry_size as u64,
329            metrics_enabled: stats.metrics_enabled,
330            total_size_bytes: stats.total_size_bytes as u64,
331            avg_entry_size_bytes: stats.avg_entry_size_bytes as u64,
332            capacity_usage_percent: stats.capacity_usage_percent,
333            memory_alert_threshold: stats.memory_alert_threshold,
334            memory_alert_triggered: stats.memory_alert_triggered,
335        }
336    }
337}
338
339#[uniffi::export]
340impl EntityData {
341    // A custom method that returns a Result for cases where you want to handle errors.
342    #[uniffi::constructor]
343    pub fn new(
344        entity_type: String,
345        id: String,
346        payload: HashMap<String, JsonValue>,
347    ) -> Result<Self, EntityError> {
348        let mut converted_payload = HashMap::new();
349        for (k, v) in payload {
350            let json_value = Value::try_from(v)
351                .map_err(|err| EntityError::JsonConversionPayload(k.clone(), err.to_string()))?;
352
353            converted_payload.insert(k, json_value);
354        }
355        let inner = core::EntityData {
356            cedar_mapping: core::CedarEntityMapping { entity_type, id },
357            attributes: converted_payload,
358        };
359        Ok(Self { inner })
360    }
361
362    #[uniffi::constructor]
363    pub fn from_json(json_string: String) -> Result<Self, EntityError> {
364        let parsed: core::EntityData = serde_json::from_str(&json_string)
365            .map_err(|err| EntityError::JsonConversion(err.to_string()))?;
366
367        Ok(Self { inner: parsed })
368    }
369}
370
371/// A wrapper struct for JSON values passed across the FFI boundary.
372///
373/// This struct allows language bindings (like Kotlin or Swift) to pass valid JSON
374/// data to the Cedarling engine as a string, which is then parsed internally.
375#[derive(Debug, Clone, uniffi::Record)]
376pub struct JsonValue {
377    /// String representation of the JSON value
378    pub value: String,
379}
380
381impl TryFrom<JsonValue> for Value {
382    type Error = serde_json::Error;
383    fn try_from(val: JsonValue) -> Result<Self, Self::Error> {
384        // Hot-path: callers commonly pass the exact literal `"{}"` for an empty
385        // context.
386        if val.value == "{}" {
387            return Ok(Value::Object(serde_json::Map::new()));
388        }
389        serde_json::from_str(&val.value)
390    }
391}
392
393// Wrapper struct for core Cedarling instance
394#[derive(uniffi::Object)]
395pub struct Cedarling {
396    inner: cedarling::blocking::Cedarling,
397}
398
399#[uniffi::export]
400impl Cedarling {
401    // Loads Cedarling instance from a JSON configuration string
402    #[uniffi::constructor]
403    pub fn load_from_json(config: String) -> Result<Self, CedarlingError> {
404        // Parse the JSON string into `BootstrapConfigRaw`
405        let config: BootstrapConfigRaw =
406            serde_json::from_str(&config).map_err(|e| CedarlingError::InitializationFailed {
407                error_msg: e.to_string(),
408            })?;
409
410        // Convert to `BootstrapConfig`
411        let config = BootstrapConfig::from_raw_config(&config).map_err(|e| {
412            CedarlingError::InitializationFailed {
413                error_msg: e.to_string(),
414            }
415        })?;
416
417        // Create a new `Cedarling` instance
418        let cedarling = core::blocking::Cedarling::new(&config).map_err(|e| {
419            CedarlingError::InitializationFailed {
420                error_msg: e.to_string(),
421            }
422        })?;
423
424        Ok(Self { inner: cedarling })
425    }
426
427    /// Loads Cedarling from bootstrap JSON plus a Cedar archive (`.cjar`) as raw bytes.
428    ///
429    /// host cannot pass a filesystem path—for example Android assets loaded via `AssetManager`.
430    #[uniffi::constructor]
431    pub fn load_from_json_with_archive_bytes(
432        config: String,
433        archive_bytes: &[u8],
434    ) -> Result<Self, CedarlingError> {
435        let mut raw_config: BootstrapConfigRaw =
436            serde_json::from_str(&config).map_err(|e| CedarlingError::InitializationFailed {
437                error_msg: e.to_string(),
438            })?;
439
440        raw_config.local_policy_store = None;
441        raw_config.policy_store_uri = None;
442        raw_config.policy_store_cjar_url = None;
443        // Set a dummy .cjar file path to satisfy validation (will be overridden below)
444        raw_config.policy_store_local_fn = Some("dummy.cjar".to_string());
445
446        let mut bootstrap_config = BootstrapConfig::from_raw_config(&raw_config).map_err(|e| {
447            CedarlingError::InitializationFailed {
448                error_msg: e.to_string(),
449            }
450        })?;
451
452        // Override the policy store source with the archive bytes
453        bootstrap_config.policy_store_config.source =
454            PolicyStoreSource::ArchiveBytes(archive_bytes.to_vec());
455
456        let cedarling = core::blocking::Cedarling::new(&bootstrap_config).map_err(|e| {
457            CedarlingError::InitializationFailed {
458                error_msg: e.to_string(),
459            }
460        })?;
461
462        Ok(Self { inner: cedarling })
463    }
464
465    // Loads Cedarling instance from a configuration file
466    #[uniffi::constructor]
467    pub fn load_from_file(path: String) -> Result<Self, CedarlingError> {
468        let config: BootstrapConfig =
469            cedarling::BootstrapConfig::load_from_file(&path).map_err(|e| {
470                CedarlingError::InitializationFailed {
471                    error_msg: format!("Failed to read the file: {}", e),
472                }
473            })?;
474
475        let cedarling = core::blocking::Cedarling::new(&config).map_err(|e| {
476            CedarlingError::InitializationFailed {
477                error_msg: e.to_string(),
478            }
479        })?;
480
481        Ok(Self { inner: cedarling })
482    }
483
484    // Handles authorization for unsigned requests
485    #[uniffi::method(default(options = None))]
486    pub fn authorize_unsigned(
487        &self,
488        principal: Option<Arc<EntityData>>,
489        action: String,
490        resource: Arc<EntityData>,
491        context: JsonValue,
492        options: Option<AuthorizeOptions>,
493    ) -> Result<AuthorizeResult, AuthorizeError> {
494        let core_principal: Option<core::EntityData> = principal.map(|p| p.inner.clone());
495
496        let core_resource = resource.inner.clone();
497
498        let core_request = core::RequestUnsigned {
499            principal: core_principal,
500            action,
501            resource: core_resource,
502            context: context
503                .try_into()
504                .map_err(|_| AuthorizeError::InvalidContext)?,
505            options: options_to_core(options),
506        };
507
508        let result = self.inner.authorize_unsigned(core_request).map_err(|e| {
509            AuthorizeError::AuthorizationFailed {
510                error_msg: e.to_string(),
511            }
512        })?;
513        Ok(result.into())
514    }
515
516    // Handles multi-issuer authorization request
517    #[uniffi::method(default(options = None))]
518    pub fn authorize_multi_issuer(
519        &self,
520        tokens: Vec<TokenInput>,
521        action: String,
522        resource: Arc<EntityData>,
523        context: Option<JsonValue>,
524        options: Option<AuthorizeOptions>,
525    ) -> Result<MultiIssuerAuthorizeResult, AuthorizeError> {
526        let core_tokens: Vec<core::TokenInput> = tokens
527            .into_iter()
528            .map(|t| core::TokenInput {
529                mapping: t.mapping,
530                payload: t.payload,
531            })
532            .collect();
533
534        let core_resource = resource.inner.clone();
535
536        let core_context = if let Some(ctx) = context {
537            Some(ctx.try_into().map_err(|_| AuthorizeError::InvalidContext)?)
538        } else {
539            None
540        };
541
542        let core_request = core::AuthorizeMultiIssuerRequest {
543            tokens: core_tokens,
544            resource: core_resource,
545            action,
546            context: core_context,
547            options: options_to_core(options),
548        };
549
550        let result = self
551            .inner
552            .authorize_multi_issuer(core_request)
553            .map_err(|e| AuthorizeError::AuthorizationFailed {
554                error_msg: e.to_string(),
555            })?;
556        Ok(result.into())
557    }
558
559    /// Authorize a batch of unsigned requests against one shared principal.
560    ///
561    /// Setup work (principal build + pushed-data snapshot) runs once and each
562    /// item is evaluated in input order. Returns a
563    /// [`BatchAuthorizeUnsignedResponse`] with `batch_id` and per-item results.
564    /// Batch-level failures reject the whole call; per-item failures are returned
565    /// as `BatchItemError` entries that callers must inspect without affecting other items.
566    #[uniffi::method(default(options = None))]
567    pub fn authorize_unsigned_batch(
568        &self,
569        principal: Option<Arc<EntityData>>,
570        items: Vec<BatchItem>,
571        options: Option<AuthorizeOptions>,
572    ) -> Result<BatchAuthorizeUnsignedResponse, AuthorizeError> {
573        let core_items = items
574            .into_iter()
575            .map(batch_item_to_core)
576            .collect::<Result<Vec<_>, _>>()?;
577        let core_request = core::BatchAuthorizeUnsignedRequest {
578            principal: principal.map(|p| p.inner.clone()),
579            items: core_items,
580            options: options_to_core(options),
581        };
582        let response = self
583            .inner
584            .authorize_unsigned_batch(core_request)
585            .map_err(|e| AuthorizeError::AuthorizationFailed {
586                error_msg: e.to_string(),
587            })?;
588        Ok(response.into())
589    }
590
591    /// Authorize a batch of multi-issuer requests against one shared token set.
592    ///
593    /// Tokens are validated and token/issuer entities built once, then each
594    /// item is evaluated in input order. Batch-level failures (validation,
595    /// JWT verification, status-list refresh) reject the whole call; per-item
596    /// failures are returned as `BatchItemError` entries that callers must inspect.
597    #[uniffi::method(default(options = None))]
598    pub fn authorize_multi_issuer_batch(
599        &self,
600        tokens: Vec<TokenInput>,
601        items: Vec<BatchItem>,
602        options: Option<AuthorizeOptions>,
603    ) -> Result<BatchAuthorizeMultiIssuerResponse, AuthorizeError> {
604        let core_tokens: Vec<core::TokenInput> = tokens
605            .into_iter()
606            .map(|t| core::TokenInput {
607                mapping: t.mapping,
608                payload: t.payload,
609            })
610            .collect();
611        let core_items = items
612            .into_iter()
613            .map(batch_item_to_core)
614            .collect::<Result<Vec<_>, _>>()?;
615        let core_request = core::BatchAuthorizeMultiIssuerRequest {
616            tokens: core_tokens,
617            items: core_items,
618            options: options_to_core(options),
619        };
620        let response = self
621            .inner
622            .authorize_multi_issuer_batch(core_request)
623            .map_err(|e| AuthorizeError::AuthorizationFailed {
624                error_msg: e.to_string(),
625            })?;
626        Ok(response.into())
627    }
628
629    // Retrieves logs and serializes them as JSON strings
630    #[uniffi::method]
631    pub fn pop_logs(&self) -> Result<Vec<String>, LogError> {
632        let mut result = Vec::new();
633
634        for log in self.inner.pop_logs() {
635            let log_str = serde_json::to_string(&log).map_err(|e| LogError::LoggingFailed {
636                error_msg: e.to_string(),
637            })?;
638            result.push(log_str);
639        }
640        Ok(result)
641    }
642    //Get log by id
643    #[uniffi::method]
644    pub fn get_log_by_id(&self, id: &str) -> Result<String, LogError> {
645        if let Some(log_json_value) = self.inner.get_log_by_id(id) {
646            serde_json::to_string(&log_json_value).map_err(|e| LogError::LoggingFailed {
647                error_msg: e.to_string(),
648            })
649        } else {
650            Err(LogError::LoggingFailed {
651                error_msg: "Log not found".to_string(),
652            })
653        }
654    }
655    //Get all log ids
656    #[uniffi::method]
657    pub fn get_log_ids(&self) -> Vec<String> {
658        let log_ids = self.inner.get_log_ids();
659        let mut result = Vec::with_capacity(log_ids.len());
660
661        for log_id in log_ids {
662            result.push(log_id.clone());
663        }
664
665        result
666    }
667
668    /// Get logs by tag, like `log_kind` or `log level`.
669    /// Tag can be `log_kind`, `log_level`.
670    #[uniffi::method]
671    pub fn get_logs_by_tag(&self, tag: &str) -> Result<Vec<String>, LogError> {
672        let logs = self.inner.get_logs_by_tag(tag);
673        let mut result = Vec::with_capacity(logs.len());
674
675        for log in logs {
676            let log_str = serde_json::to_string(&log).map_err(|e| LogError::LoggingFailed {
677                error_msg: e.to_string(),
678            })?;
679            result.push(log_str);
680        }
681
682        Ok(result)
683    }
684
685    /// Get logs by request_id.
686    /// Return log entries that match the given request_id.
687    #[uniffi::method]
688    pub fn get_logs_by_request_id(&self, request_id: &str) -> Result<Vec<String>, LogError> {
689        let logs = self.inner.get_logs_by_request_id(request_id);
690        let mut result = Vec::with_capacity(logs.len());
691
692        for log in logs {
693            let log_str = serde_json::to_string(&log).map_err(|e| LogError::LoggingFailed {
694                error_msg: e.to_string(),
695            })?;
696            result.push(log_str);
697        }
698        Ok(result)
699    }
700
701    /// Get log by request_id and tag, like composite key `request_id` + `log_kind`.
702    /// Tag can be `log_kind`, `log_level`.
703    /// Return log entries that match the given request_id and tag.
704    #[uniffi::method]
705    pub fn get_logs_by_request_id_and_tag(
706        &self,
707        request_id: &str,
708        tag: &str,
709    ) -> Result<Vec<String>, LogError> {
710        let logs = self.inner.get_logs_by_request_id_and_tag(request_id, tag);
711        let mut result = Vec::with_capacity(logs.len());
712
713        for log in logs {
714            let log_str = serde_json::to_string(&log).map_err(|e| LogError::LoggingFailed {
715                error_msg: e.to_string(),
716            })?;
717            result.push(log_str);
718        }
719
720        Ok(result)
721    }
722
723    /// Closes the connections to the Lock Server and pushes all available logs.
724    #[uniffi::method]
725    pub fn shut_down(&self) {
726        self.inner.shut_down();
727    }
728
729    /// Push a value into the data store with an optional TTL.
730    /// If the key already exists, the value will be replaced.
731    /// If TTL is not provided, the default TTL from configuration is used.
732    #[uniffi::method]
733    pub fn push_data_ctx(
734        &self,
735        key: String,
736        value: JsonValue,
737        ttl_secs: Option<i64>,
738    ) -> Result<(), DataError> {
739        let json_value: Value = value.try_into().map_err(|e| {
740            DataError::SerializationError(format!("Failed to parse JSON value: {}", e))
741        })?;
742
743        let ttl = ttl_secs
744            .map(|secs| {
745                u64::try_from(secs).map(Duration::from_secs).map_err(|_| {
746                    DataError::SerializationError("TTL must be a non-negative integer".to_string())
747                })
748            })
749            .transpose()?;
750        self.inner
751            .push_data_ctx(&key, json_value, ttl)
752            .map_err(|e: core::DataError| DataError::from(e))
753    }
754
755    /// Get a value from the data store by key.
756    /// Returns None if the key doesn't exist or the entry has expired.
757    #[uniffi::method]
758    pub fn get_data_ctx(&self, key: String) -> Result<Option<JsonValue>, DataError> {
759        let result: Result<_, core::DataError> = self.inner.get_data_ctx(&key);
760        match result.map_err(DataError::from)? {
761            Some(value) => Ok(Some(JsonValue {
762                value: serde_json::to_string(&value).map_err(|e| {
763                    DataError::SerializationError(format!("Failed to serialize value: {}", e))
764                })?,
765            })),
766            None => Ok(None),
767        }
768    }
769
770    /// Get a data entry with full metadata by key.
771    /// Returns None if the key doesn't exist or the entry has expired.
772    #[uniffi::method]
773    pub fn get_data_entry_ctx(&self, key: String) -> Result<Option<DataEntry>, DataError> {
774        let result: Result<_, core::DataError> = self.inner.get_data_entry_ctx(&key);
775        match result.map_err(DataError::from)? {
776            Some(entry) => Ok(Some(entry.try_into()?)),
777            None => Ok(None),
778        }
779    }
780
781    /// Remove a value from the data store by key.
782    /// Returns true if the key existed and was removed, false otherwise.
783    #[uniffi::method]
784    pub fn remove_data_ctx(&self, key: String) -> Result<bool, DataError> {
785        self.inner
786            .remove_data_ctx(&key)
787            .map_err(|e: core::DataError| DataError::from(e))
788    }
789
790    /// Clear all entries from the data store.
791    #[uniffi::method]
792    pub fn clear_data_ctx(&self) -> Result<(), DataError> {
793        self.inner
794            .clear_data_ctx()
795            .map_err(|e: core::DataError| DataError::from(e))
796    }
797
798    /// List all entries with their metadata.
799    /// Returns a list of DataEntry objects.
800    #[uniffi::method]
801    pub fn list_data_ctx(&self) -> Result<Vec<DataEntry>, DataError> {
802        let result: Result<_, core::DataError> = self.inner.list_data_ctx();
803        result
804            .map_err(DataError::from)?
805            .into_iter()
806            .map(TryInto::try_into)
807            .collect()
808    }
809
810    /// Get statistics about the data store.
811    #[uniffi::method]
812    pub fn get_stats_ctx(&self) -> Result<DataStoreStats, DataError> {
813        self.inner
814            .get_stats_ctx()
815            .map(Into::into)
816            .map_err(|e: core::DataError| DataError::from(e))
817    }
818
819    /// Destructive read: returns the telemetry metrics snapshot and resets
820    /// the counters for the next interval. `interval` is a Duration with
821    /// sub-second precision (Python `timedelta`, Kotlin `java.time.Duration`,
822    /// Swift `TimeInterval` seconds).
823    #[uniffi::method]
824    pub fn drain_metrics(&self) -> Result<MetricsSnapshot, MetricsError> {
825        self.inner
826            .drain_metrics()
827            .map(Into::into)
828            .map_err(|e: CoreMetricsError| MetricsError::from(e))
829    }
830
831    /// Returns the ID of the currently published policy store, if it carries one.
832    ///
833    /// `None` when the store carries no ID. The value is an opaque,
834    /// source-dependent string; it may change after a background refresh.
835    #[uniffi::method]
836    pub fn policy_store_id(&self) -> Option<String> {
837        self.inner.policy_store_id()
838    }
839
840    #[uniffi::method]
841    pub fn is_trusted_issuer_loaded_by_name(&self, issuer_name: &str) -> bool {
842        self.inner.is_trusted_issuer_loaded_by_name(issuer_name)
843    }
844
845    #[uniffi::method]
846    pub fn is_trusted_issuer_loaded_by_iss(&self, iss_claim: &str) -> bool {
847        self.inner.is_trusted_issuer_loaded_by_iss(iss_claim)
848    }
849
850    #[uniffi::method]
851    pub fn total_issuers(&self) -> i64 {
852        i64::try_from(self.inner.total_issuers()).unwrap_or(i64::MAX)
853    }
854
855    #[uniffi::method]
856    pub fn loaded_trusted_issuers_count(&self) -> i64 {
857        i64::try_from(self.inner.loaded_trusted_issuers_count()).unwrap_or(i64::MAX)
858    }
859
860    #[uniffi::method]
861    pub fn loaded_trusted_issuer_ids(&self) -> Vec<String> {
862        self.inner.loaded_trusted_issuer_ids().into_iter().collect()
863    }
864
865    #[uniffi::method]
866    pub fn failed_trusted_issuer_ids(&self) -> Vec<String> {
867        self.inner.failed_trusted_issuer_ids().into_iter().collect()
868    }
869}
870
871/// Convert a UniFFI-facing [`BatchItem`] into the core `cedarling::BatchItem`.
872/// `context: None` defaults to `{}`, matching the batch API's serde default.
873fn batch_item_to_core(item: BatchItem) -> Result<core::BatchItem, AuthorizeError> {
874    let context = match item.context {
875        Some(ctx) => ctx.try_into().map_err(|_| AuthorizeError::InvalidContext)?,
876        None => Value::Object(serde_json::Map::new()),
877    };
878    Ok(core::BatchItem {
879        resource: item.resource.inner.clone(),
880        action: item.action,
881        context,
882    })
883}