Skip to main content

cedarling_uniffi/
result.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
6use cedarling::{self as core, bindings::cedar_policy};
7
8/// Result of an authorization request.
9#[derive(Debug, uniffi::Record)]
10pub struct AuthorizeResult {
11    pub response: Response,
12    /// `true` if the request is allowed.
13    pub decision: bool,
14    /// Identifier of this request, also used in its logs.
15    pub request_id: String,
16}
17
18/// Cedar decision together with its diagnostics.
19#[derive(Debug, uniffi::Record)]
20pub struct Response {
21    pub decision: Decision,
22    pub diagnostics: Diagnostics,
23}
24
25/// Cedar authorization decision.
26#[derive(Debug, uniffi::Enum)]
27pub enum Decision {
28    Allow,
29    Deny,
30}
31
32/// Policies that determined the decision and errors raised during evaluation.
33#[derive(Debug, uniffi::Record)]
34pub struct Diagnostics {
35    /// IDs of the policies that contributed to the decision.
36    pub reasons: Vec<String>,
37    /// Errors raised while evaluating policies.
38    pub errors: Vec<String>,
39}
40
41// Conversion implementations
42impl From<cedar_policy::Decision> for Decision {
43    fn from(decision: cedar_policy::Decision) -> Self {
44        match decision {
45            cedar_policy::Decision::Allow => Decision::Allow,
46            cedar_policy::Decision::Deny => Decision::Deny,
47        }
48    }
49}
50
51impl From<&cedar_policy::Diagnostics> for Diagnostics {
52    fn from(diag: &cedar_policy::Diagnostics) -> Self {
53        Diagnostics {
54            reasons: diag.reason().map(|id| id.to_string()).collect(),
55            errors: diag.errors().map(|e| e.to_string()).collect(),
56        }
57    }
58}
59
60impl From<cedar_policy::Response> for Response {
61    fn from(response: cedar_policy::Response) -> Self {
62        Response {
63            decision: response.decision().into(),
64            diagnostics: response.diagnostics().into(),
65        }
66    }
67}
68
69impl From<core::AuthorizeResult> for AuthorizeResult {
70    fn from(result: core::AuthorizeResult) -> Self {
71        AuthorizeResult {
72            response: result.response.into(),
73            decision: result.decision,
74            request_id: result.request_id,
75        }
76    }
77}
78
79/// Result of multi-issuer authorization
80#[derive(Debug, uniffi::Record)]
81pub struct MultiIssuerAuthorizeResult {
82    pub response: Response,
83    pub decision: bool,
84    pub request_id: String,
85    pub dropped_tokens: Vec<DroppedToken>,
86}
87
88use cedarling::{DropReason, TokenInputError};
89
90// UniFFI exports the core enums directly; a mismatch with the core definition
91// fails to compile, so there is no hand-written mapping to drift.
92#[uniffi::remote(Enum)]
93pub enum TokenInputError {
94    EmptyMapping,
95    EmptyPayload,
96}
97
98#[uniffi::remote(Enum)]
99pub enum DropReason {
100    InvalidInput(TokenInputError),
101    JwtValidationFailed,
102    DuplicateToken,
103    DuplicateMapping,
104    NoProcessorRegistered,
105    CustomProcessingFailed,
106    CustomProcessingTimedOut,
107    EntityBuildFailed,
108}
109
110/// Why a token was dropped. `kind()`, `detail()` and `message()` return the
111/// same values as the core JSON `reason` object; `variant` is the typed reason.
112#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
113pub struct DropReasonInfo {
114    pub variant: DropReason,
115}
116
117#[uniffi::export]
118impl DropReasonInfo {
119    /// Stable snake-case slug, e.g. `"jwt_validation_failed"`.
120    pub fn kind(&self) -> String {
121        self.variant.slug().to_string()
122    }
123
124    /// Stable detail slug for `invalid_input` (`"empty_mapping"` /
125    /// `"empty_payload"`); `None` otherwise.
126    pub fn detail(&self) -> Option<String> {
127        self.variant.detail().map(str::to_string)
128    }
129
130    /// Claim-free human-readable message; non-empty for every reason.
131    pub fn message(&self) -> String {
132        self.variant.message()
133    }
134}
135
136/// A token dropped during multi-issuer authorization, identified by its input
137/// `mapping` and zero-based `index`, with the claim-free `reason`.
138#[derive(Debug, uniffi::Record)]
139pub struct DroppedToken {
140    pub mapping: String,
141    // i64 (not u64) so the Kotlin/Java binding exposes a signed Long rather
142    // than a JVM-hostile ULong; usize casts fit trivially.
143    pub index: i64,
144    pub reason: DropReasonInfo,
145}
146
147impl From<core::DroppedToken> for DroppedToken {
148    fn from(d: core::DroppedToken) -> Self {
149        Self {
150            reason: DropReasonInfo { variant: d.reason },
151            mapping: d.mapping,
152            index: d.index as i64,
153        }
154    }
155}
156
157impl From<core::MultiIssuerAuthorizeResult> for MultiIssuerAuthorizeResult {
158    fn from(result: core::MultiIssuerAuthorizeResult) -> Self {
159        MultiIssuerAuthorizeResult {
160            response: result.response.into(),
161            decision: result.decision,
162            request_id: result.request_id,
163            dropped_tokens: result.dropped_tokens.into_iter().map(Into::into).collect(),
164        }
165    }
166}
167
168/// Per-item build failure surfaced inside a batch response when Cedar
169/// couldn't be reached for that item. `category` is the stable variant slug
170/// (`action_parse`, `resource_build`, …), `item_index` is the position of
171/// the failing item in the original `items` list.
172#[derive(Debug, uniffi::Record)]
173pub struct BatchItemError {
174    pub category: String,
175    // i64 (not u64) so the Kotlin/Java binding exposes it as a signed Long
176    // rather than a JVM-hostile ULong. usize casts fit trivially.
177    pub item_index: i64,
178    pub message: String,
179}
180
181impl From<core::BatchItemError> for BatchItemError {
182    fn from(e: core::BatchItemError) -> Self {
183        let message = e.to_string();
184        Self {
185            category: e.category().to_string(),
186            item_index: e.item_index() as i64,
187            message,
188        }
189    }
190}
191
192/// One slot in `BatchAuthorizeUnsignedResponse.results`. Pattern-match on
193/// `Success(_)` to read the Cedar decision, or `Failed(_)` to read the
194/// per-item build failure.
195#[derive(Debug, uniffi::Enum)]
196pub enum BatchItemUnsignedOutcome {
197    Success { result: AuthorizeResult },
198    Failed { error: BatchItemError },
199}
200
201impl From<Result<core::AuthorizeResult, core::BatchItemError>> for BatchItemUnsignedOutcome {
202    fn from(r: Result<core::AuthorizeResult, core::BatchItemError>) -> Self {
203        match r {
204            Ok(ok) => Self::Success { result: ok.into() },
205            Err(err) => Self::Failed { error: err.into() },
206        }
207    }
208}
209
210/// Multi-issuer analog of [`BatchItemUnsignedOutcome`].
211#[derive(Debug, uniffi::Enum)]
212pub enum BatchItemMultiIssuerOutcome {
213    Success { result: MultiIssuerAuthorizeResult },
214    Failed { error: BatchItemError },
215}
216
217impl From<Result<core::MultiIssuerAuthorizeResult, core::BatchItemError>>
218    for BatchItemMultiIssuerOutcome
219{
220    fn from(r: Result<core::MultiIssuerAuthorizeResult, core::BatchItemError>) -> Self {
221        match r {
222            Ok(ok) => Self::Success { result: ok.into() },
223            Err(err) => Self::Failed { error: err.into() },
224        }
225    }
226}
227
228/// Result of `Cedarling.authorize_unsigned_batch`. Carries a shared `batch_id`
229/// (UUIDv7) alongside per-item outcomes. `results[i]` corresponds to the
230/// `items[i]` supplied in the request.
231#[derive(Debug, uniffi::Record)]
232pub struct BatchAuthorizeUnsignedResponse {
233    pub batch_id: String,
234    pub results: Vec<BatchItemUnsignedOutcome>,
235}
236
237impl From<core::BatchAuthorizeResponse<Result<core::AuthorizeResult, core::BatchItemError>>>
238    for BatchAuthorizeUnsignedResponse
239{
240    fn from(
241        value: core::BatchAuthorizeResponse<Result<core::AuthorizeResult, core::BatchItemError>>,
242    ) -> Self {
243        Self {
244            batch_id: value.batch_id.to_string(),
245            results: value.results.into_iter().map(Into::into).collect(),
246        }
247    }
248}
249
250/// Result of `Cedarling.authorize_multi_issuer_batch`. Same shape as
251/// [`BatchAuthorizeUnsignedResponse`] with multi-issuer results.
252#[derive(Debug, uniffi::Record)]
253pub struct BatchAuthorizeMultiIssuerResponse {
254    pub batch_id: String,
255    pub results: Vec<BatchItemMultiIssuerOutcome>,
256}
257
258impl
259    From<
260        core::BatchAuthorizeResponse<
261            Result<core::MultiIssuerAuthorizeResult, core::BatchItemError>,
262        >,
263    > for BatchAuthorizeMultiIssuerResponse
264{
265    fn from(
266        value: core::BatchAuthorizeResponse<
267            Result<core::MultiIssuerAuthorizeResult, core::BatchItemError>,
268        >,
269    ) -> Self {
270        Self {
271            batch_id: value.batch_id.to_string(),
272            results: value.results.into_iter().map(Into::into).collect(),
273        }
274    }
275}