cedarling 0.0.44

The Cedarling: a high-performance local authorization service powered by the Rust Cedar Engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
// This software is available under the Apache-2.0 license.
// See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
//
// Copyright (c) 2024, Gluu, Inc.

//! Cross-flow contract tests for the batch authorize APIs: result equivalence
//! vs sequence-of-single, shuffle-preserves-order, and `batch_id` `UUIDv7` +
//! log correlation. Per-flow tests live alongside each flow's implementation.

use super::utils::cedarling_util::get_cedarling_with_callback;
use super::utils::*;
use crate::authz::request::{
    AuthorizeMultiIssuerRequest, BatchAuthorizeMultiIssuerRequest, BatchAuthorizeUnsignedRequest,
    BatchItem, EntityData, RequestUnsigned, TokenInput,
};
use crate::tests::utils::test_helpers::create_test_principal;
use crate::{
    AuthorizeResult, BatchItemError, Cedarling, LogStorage, MultiIssuerAuthorizeResult,
};

fn expect_ok_unsigned(
    r: &Result<AuthorizeResult, BatchItemError>,
    idx: usize,
) -> &AuthorizeResult {
    r.as_ref()
        .unwrap_or_else(|e| panic!("item {idx} expected Ok, got Err: {e:?}"))
}

fn expect_ok_multi(
    r: &Result<MultiIssuerAuthorizeResult, BatchItemError>,
    idx: usize,
) -> &MultiIssuerAuthorizeResult {
    r.as_ref()
        .unwrap_or_else(|e| panic!("item {idx} expected Ok, got Err: {e:?}"))
}

static UNSIGNED_POLICY_STORE: &str =
    include_str!("../../../test_files/policy-store_no_trusted_issuers.yaml");
static MULTI_ISSUER_POLICY_STORE: &str =
    include_str!("../../../test_files/policy-store-multi-issuer-basic.yaml");

async fn unsigned_cedarling() -> Cedarling {
    get_cedarling_with_callback(
        PolicyStoreSource::Yaml(UNSIGNED_POLICY_STORE.to_string()),
        |_| {},
    )
    .await
}

async fn multi_issuer_cedarling() -> Cedarling {
    get_cedarling_with_callback(
        PolicyStoreSource::Yaml(MULTI_ISSUER_POLICY_STORE.to_string()),
        |_| {},
    )
    .await
}

fn make_issue(id: &str, org_id: &str) -> EntityData {
    create_test_principal(
        "Jans::Issue",
        id,
        json!({"org_id": org_id, "country": "US"}),
    )
    .expect("resource should build")
}

fn unsigned_item(action: &str, resource: EntityData) -> BatchItem {
    BatchItem {
        resource,
        action: action.to_string(),
        context: json!({}),
    }
}

fn dolphin_userinfo_token() -> TokenInput {
    TokenInput::new(
        "Dolphin::Userinfo_token".to_string(),
        generate_token_using_claims(json!({
            "iss": "https://idp.dolphin.sea",
            "sub": "dolphin_user_123",
            "jti": "dolphin_user_123",
            "client_id": "dolphin_client_123",
            "aud": "dolphin_audience",
            "exp": 2_000_000_000,
            "iat": 1_516_239_022,
            "role": ["admin", "user"],
        })),
    )
}

fn approved_resource(id: &str) -> EntityData {
    EntityData::from_json(
        &json!({
            "cedar_entity_mapping": { "entity_type": "Acme::Resource", "id": id },
            "name": "Approved Dolphin Foods",
        })
        .to_string(),
    )
    .expect("resource should build")
}

fn multi_issuer_allow_item() -> BatchItem {
    BatchItem {
        resource: approved_resource("ApprovedDolphinFoods"),
        action: "Acme::Action::\"CheckRoleFoodApprover\"".to_string(),
        context: json!({}),
    }
}

fn multi_issuer_deny_item(resource_id: &str) -> BatchItem {
    BatchItem {
        resource: approved_resource(resource_id),
        action: "Acme::Action::\"CheckRoleFoodApprover\"".to_string(),
        context: json!({}),
    }
}

fn diagnostic_reasons(result_response: &cedar_policy::Response) -> Vec<String> {
    let mut r: Vec<String> = result_response
        .diagnostics()
        .reason()
        .map(ToString::to_string)
        .collect();
    r.sort();
    r
}

// ── Result equivalence ──────────────────────────────────────────────

/// Batch must produce the same per-item decisions and diagnostic reasons as
/// the sequence of single-item calls with the same inputs.
#[tokio::test]
async fn batch_unsigned_matches_sequence_of_single() {
    let cedarling = unsigned_cedarling().await;
    let principal_ok = create_test_principal("Jans::TestPrincipal1", "p1", json!({"is_ok": true}))
        .expect("principal should build");
    let principal_bad =
        create_test_principal("Jans::TestPrincipal1", "p1", json!({"is_ok": false}))
            .expect("principal should build");

    // Two same-shaped items — the allow/deny split comes from swapping
    // principal_ok vs. principal_bad on the two batches below.
    let items = vec![
        unsigned_item(
            "Jans::Action::\"UpdateForTestPrincipals\"",
            make_issue("issue-0", "acme"),
        ),
        unsigned_item(
            "Jans::Action::\"UpdateForTestPrincipals\"",
            make_issue("issue-1", "acme"),
        ),
    ];

    // Sequence-of-single with the allowing principal.
    let mut seq_ok = Vec::with_capacity(items.len());
    for item in &items {
        let r = cedarling
            .authorize_unsigned(RequestUnsigned {
                principal: Some(principal_ok.clone()),
                action: item.action.clone(),
                resource: item.resource.clone(),
                context: item.context.clone(),
            })
            .await
            .expect("single call should succeed");
        seq_ok.push(r);
    }

    // Same inputs via the batch call.
    let batch_ok = cedarling
        .authorize_unsigned_batch(BatchAuthorizeUnsignedRequest::new(
            Some(principal_ok.clone()),
            items.clone(),
        ))
        .await
        .expect("batch should succeed");

    assert_eq!(
        seq_ok.len(),
        batch_ok.results.len(),
        "batch must return same number of results as sequence"
    );
    assert!(
        batch_ok
            .results
            .iter()
            .enumerate()
            .all(|(i, r)| expect_ok_unsigned(r, i).decision),
        "is_ok=true principal must Allow every item — check fixture drift"
    );
    for (i, (s, b)) in seq_ok.iter().zip(batch_ok.results.iter()).enumerate() {
        let bo = expect_ok_unsigned(b, i);
        assert_eq!(s.decision, bo.decision, "decision mismatch at item {i}");
        test_utils::assert_eq!(
            diagnostic_reasons(&s.response),
            diagnostic_reasons(&bo.response),
            "diagnostic reasons mismatch at item {i}"
        );
    }

    // Same equivalence must hold on Deny outcomes, not only Allow.
    let mut seq_bad = Vec::with_capacity(items.len());
    for item in &items {
        let r = cedarling
            .authorize_unsigned(RequestUnsigned {
                principal: Some(principal_bad.clone()),
                action: item.action.clone(),
                resource: item.resource.clone(),
                context: item.context.clone(),
            })
            .await
            .expect("single call should succeed");
        seq_bad.push(r);
    }
    let batch_bad = cedarling
        .authorize_unsigned_batch(BatchAuthorizeUnsignedRequest::new(
            Some(principal_bad),
            items,
        ))
        .await
        .expect("batch should succeed");

    assert!(
        batch_bad
            .results
            .iter()
            .enumerate()
            .all(|(i, r)| !expect_ok_unsigned(r, i).decision),
        "is_ok=false principal must Deny every item — check fixture drift"
    );
    for (i, (s, b)) in seq_bad.iter().zip(batch_bad.results.iter()).enumerate() {
        let bo = expect_ok_unsigned(b, i);
        assert_eq!(s.decision, bo.decision, "deny decision mismatch at item {i}");
        test_utils::assert_eq!(
            diagnostic_reasons(&s.response),
            diagnostic_reasons(&bo.response),
            "deny diagnostic reasons mismatch at item {i}"
        );
    }
}

/// Same equivalence for multi-issuer: token validation once vs. per call must
/// not change per-item outcomes.
#[tokio::test]
async fn batch_multi_issuer_matches_sequence_of_single() {
    let cedarling = multi_issuer_cedarling().await;
    let tokens = vec![dolphin_userinfo_token()];

    // Mix of allow (right resource id) and deny (wrong resource id).
    let items = vec![
        multi_issuer_allow_item(),
        multi_issuer_deny_item("wrong-id-1"),
        multi_issuer_allow_item(),
        multi_issuer_deny_item("wrong-id-2"),
    ];

    let mut sequence = Vec::with_capacity(items.len());
    for item in &items {
        let r = cedarling
            .authorize_multi_issuer(AuthorizeMultiIssuerRequest::new_with_fields(
                tokens.clone(),
                item.resource.clone(),
                item.action.clone(),
                Some(item.context.clone()),
            ))
            .await
            .expect("single multi-issuer call should succeed");
        sequence.push(r);
    }

    let batch = cedarling
        .authorize_multi_issuer_batch(BatchAuthorizeMultiIssuerRequest::new(tokens, items.clone()))
        .await
        .expect("multi-issuer batch should succeed");

    assert_eq!(
        sequence.len(),
        batch.results.len(),
        "multi-issuer batch must return same number of results as sequence"
    );
    // Positive/negative anchors — allow items at 0/2, deny items at 1/3.
    // Guards against a fixture drift where both sides silently all-Deny.
    let decisions: Vec<bool> = batch
        .results
        .iter()
        .enumerate()
        .map(|(i, r)| expect_ok_multi(r, i).decision)
        .collect();
    assert_eq!(
        decisions,
        vec![true, false, true, false],
        "batch decisions must match the allow/deny/allow/deny item pattern"
    );
    for (i, (s, b)) in sequence.iter().zip(batch.results.iter()).enumerate() {
        let bo = expect_ok_multi(b, i);
        assert_eq!(s.decision, bo.decision, "decision mismatch at item {i}");
        test_utils::assert_eq!(
            diagnostic_reasons(&s.response),
            diagnostic_reasons(&bo.response),
            "diagnostic reasons mismatch at item {i}"
        );
    }
}

// ── Shuffle ordering ───────────────────────────────────────────────

/// Reversing input order reverses result order — proves the positional
/// mapping isn't accidentally driven by item content.
#[tokio::test]
async fn batch_unsigned_reverse_order_preserves_positional_mapping() {
    let cedarling = unsigned_cedarling().await;
    let principal = create_test_principal("Jans::TestPrincipal1", "p1", json!({"is_ok": true}))
        .expect("principal");

    // Even index → good action (Allow); odd → bad action (Err/ActionParse).
    let items: Vec<BatchItem> = (0..8)
        .map(|i| {
            let action = if i % 2 == 0 {
                "Jans::Action::\"UpdateForTestPrincipals\""
            } else {
                "this is not a valid uid"
            };
            unsigned_item(action, make_issue(&format!("res-{i}"), "acme"))
        })
        .collect();

    let baseline = cedarling
        .authorize_unsigned_batch(BatchAuthorizeUnsignedRequest::new(
            Some(principal.clone()),
            items.clone(),
        ))
        .await
        .expect("baseline batch should succeed");

    let mut reversed = items;
    reversed.reverse();
    let shuffled = cedarling
        .authorize_unsigned_batch(BatchAuthorizeUnsignedRequest::new(
            Some(principal),
            reversed,
        ))
        .await
        .expect("reversed batch should succeed");

    // Map each per-item Result to a Some(bool) / None slot so an Err from a
    // bad-action item is a distinguishable position (not silently folded into
    // the same "false" as a Cedar-Deny).
    let baseline_slots: Vec<Option<bool>> = baseline
        .results
        .iter()
        .map(|r| r.as_ref().ok().map(|ok| ok.decision))
        .collect();
    let shuffled_slots: Vec<Option<bool>> = shuffled
        .results
        .iter()
        .map(|r| r.as_ref().ok().map(|ok| ok.decision))
        .collect();

    let mut expected = baseline_slots.clone();
    expected.reverse();
    test_utils::assert_eq!(
        shuffled_slots, expected,
        "reversing items must reverse the result positions exactly"
    );
    assert_eq!(
        baseline_slots,
        vec![
            Some(true),
            None,
            Some(true),
            None,
            Some(true),
            None,
            Some(true),
            None
        ],
        "sanity: even indices Ok(true), odd indices Err(ActionParse)"
    );
}

// ── batch_id + log correlation ─────────────────────────────────────

/// `batch_id` is a `UUIDv7` and every per-item decision-log entry emitted for
/// the batch is retrievable via `get_logs_by_request_id(batch_id)`.
#[tokio::test]
async fn batch_unsigned_batch_id_is_uuidv7_and_indexes_per_item_logs() {
    let cedarling = unsigned_cedarling().await;
    let principal = create_test_principal("Jans::TestPrincipal1", "p1", json!({"is_ok": true}))
        .expect("principal");

    let items: Vec<BatchItem> = (0..3)
        .map(|i| {
            unsigned_item(
                "Jans::Action::\"UpdateForTestPrincipals\"",
                make_issue(&format!("issue-{i}"), "acme"),
            )
        })
        .collect();

    let response = cedarling
        .authorize_unsigned_batch(BatchAuthorizeUnsignedRequest::new(Some(principal), items))
        .await
        .expect("batch should succeed");

    assert_eq!(
        response.batch_id.version(),
        Some(7),
        "batch_id must be a UUIDv7"
    );

    let batch_id_str = response.batch_id.to_string();
    let logs = cedarling.get_logs_by_request_id(&batch_id_str);
    assert!(
        !logs.is_empty(),
        "logs indexed by batch_id must not be empty"
    );

    for entry in &logs {
        let entry_batch_id = entry
            .get("batch_id")
            .and_then(|v| v.as_str())
            .expect("every batch log entry has a batch_id field");
        assert_eq!(entry_batch_id, batch_id_str);
    }
}