cedarling 0.0.65

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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
// 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.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid7::Uuid;

use super::errors::{BatchValidationError, MultiIssuerValidationError, TokenInputError};

/// Authorization request data with an optional principal.
///
/// When `principal` is `None`, the request is evaluated using Cedar's
/// partial-evaluation mode: policies whose principal scope would be unknown
/// can still produce a concrete decision provided they do not depend on the
/// principal's attributes.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RequestUnsigned {
    /// Optional principal entity for the authorization request.
    pub principal: Option<EntityData>,
    /// `cedar_policy` action
    pub action: String,
    /// `cedar_policy` resource data
    pub resource: EntityData,
    /// context to be used in `cedar_policy`
    pub context: Value,
}

/// Cedar policy entity data
/// fields represent `EntityUid`
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct EntityData {
    /// Cedar entity mapping info
    #[serde(rename = "cedar_entity_mapping")]
    pub cedar_mapping: CedarEntityMapping,
    /// entity attributes
    #[serde(flatten)]
    pub attributes: HashMap<String, Value>,
}

/// Cedar entity mapping information
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct CedarEntityMapping {
    /// entity type name
    #[serde(rename = "entity_type")]
    pub entity_type: String,
    /// entity id
    pub id: String,
}

impl EntityData {
    /// Deserializes a JSON string into [`EntityData`]
    pub fn from_json(entity_data: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str::<Self>(entity_data)
    }
}

/// Token input for multi-issuer authorization
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TokenInput {
    /// Token mapping type (e.g., "`Jans::Access_Token`", "`Acme::DolphinToken`")
    pub mapping: String,
    /// JWT token string
    pub payload: String,
}

impl TokenInput {
    /// Create a new [`TokenInput`]
    #[must_use]
    pub fn new(mapping: String, payload: String) -> Self {
        Self { mapping, payload }
    }

    /// Validate the token input format (mapping and payload presence)
    pub fn validate(&self) -> Result<(), TokenInputError> {
        // Validate mapping format
        if self.mapping.trim().is_empty() {
            return Err(TokenInputError::EmptyMapping);
        }

        // Validate payload format
        if self.payload.trim().is_empty() {
            return Err(TokenInputError::EmptyPayload);
        }

        Ok(())
    }
}

/// Multi-issuer authorization request
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AuthorizeMultiIssuerRequest {
    /// Array of JWT tokens with explicit type mappings
    pub tokens: Vec<TokenInput>,
    /// Resource being accessed (required for Cedar policy evaluation)
    pub resource: EntityData,
    /// Action being performed (required for Cedar policy evaluation)
    pub action: String,
    /// Optional additional context for policy evaluation (JSON format)
    pub context: Option<Value>,
}

impl AuthorizeMultiIssuerRequest {
    /// Create a new [`AuthorizeMultiIssuerRequest`]
    #[must_use]
    pub fn new(tokens: Vec<TokenInput>, resource: EntityData, action: String) -> Self {
        Self {
            tokens,
            resource,
            action,
            context: None,
        }
    }

    /// Create a new [`AuthorizeMultiIssuerRequest`] with all fields
    #[must_use]
    pub fn new_with_fields(
        tokens: Vec<TokenInput>,
        resource: EntityData,
        action: String,
        context: Option<Value>,
    ) -> Self {
        Self {
            tokens,
            resource,
            action,
            context,
        }
    }

    /// Basic validation of JSON fields
    pub fn validate(&self) -> Result<(), MultiIssuerValidationError> {
        // Basic validation
        if self.tokens.is_empty() {
            return Err(MultiIssuerValidationError::EmptyTokenArray);
        }

        if let Some(ref context) = self.context
            && !context.is_object()
        {
            return Err(MultiIssuerValidationError::InvalidContextJson);
        }

        Ok(())
    }
}

/// A single item in a batch authorization request.
///
/// Each item carries the resource, action, and context that vary per item;
/// the shared principal (unsigned) or token set (multi-issuer) lives on the
/// enclosing batch request.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct BatchItem {
    /// Resource being accessed for this item.
    pub resource: EntityData,
    /// Action being performed on this item.
    pub action: String,
    /// Per-item context. Omitting the field defaults to `{}`; explicit
    /// non-object values are rejected via [`BatchValidationError::InvalidItemContext`].
    #[serde(default = "empty_object")]
    pub context: Value,
}

fn empty_object() -> Value {
    Value::Object(serde_json::Map::new())
}

/// Batch unsigned authorization request.
///
/// One optional principal is evaluated against N `{resource, action, context}`
/// items. All items share the same principal snapshot and pushed-data snapshot.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BatchAuthorizeUnsignedRequest {
    /// Principal entity for the batch. When `None`, per-item evaluation runs
    /// via Cedar partial evaluation with the same fail-closed contract as
    /// `authorize_unsigned`.
    pub principal: Option<EntityData>,
    /// Items to authorize. Results are returned in the same order.
    pub items: Vec<BatchItem>,
}

impl BatchAuthorizeUnsignedRequest {
    /// Construct a new batch unsigned request.
    #[must_use]
    pub fn new(principal: Option<EntityData>, items: Vec<BatchItem>) -> Self {
        Self { principal, items }
    }

    /// Validate the batch request structure. See [`BatchValidationError`] for
    /// the possible failure modes.
    pub fn validate(&self) -> Result<(), BatchValidationError> {
        if self.items.is_empty() {
            return Err(BatchValidationError::EmptyItems);
        }
        for (index, item) in self.items.iter().enumerate() {
            if !item.context.is_object() {
                return Err(BatchValidationError::InvalidItemContext { index });
            }
        }
        Ok(())
    }
}

/// Batch multi-issuer authorization request.
///
/// One token set is validated once and evaluated against N
/// `{resource, action, context}` items. All items share the same validated-token
/// snapshot, token/issuer entity snapshot, and pushed-data snapshot.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BatchAuthorizeMultiIssuerRequest {
    /// JWT tokens with explicit type mappings; validated once for the whole batch.
    pub tokens: Vec<TokenInput>,
    /// Items to authorize. Results are returned in the same order.
    pub items: Vec<BatchItem>,
}

impl BatchAuthorizeMultiIssuerRequest {
    /// Construct a new batch multi-issuer request.
    #[must_use]
    pub fn new(tokens: Vec<TokenInput>, items: Vec<BatchItem>) -> Self {
        Self { tokens, items }
    }

    /// Validate the batch request structure. See [`BatchValidationError`] for
    /// the possible failure modes.
    pub fn validate(&self) -> Result<(), BatchValidationError> {
        if self.tokens.is_empty() {
            return Err(BatchValidationError::EmptyTokens);
        }
        if self.items.is_empty() {
            return Err(BatchValidationError::EmptyItems);
        }
        for (index, item) in self.items.iter().enumerate() {
            if !item.context.is_object() {
                return Err(BatchValidationError::InvalidItemContext { index });
            }
        }
        Ok(())
    }
}

/// Response wrapper for batch authorization calls.
///
/// Carries a shared `batch_id` (`UUIDv7`) alongside per-item results. `results[i]`
/// corresponds to `items[i]` in the request. The `batch_id` matches the
/// `batch_id` field stamped on the per-item decision-log entries emitted
/// during evaluation, so callers can correlate their client-side logs with
/// the server-side audit trail.
///
/// The `batch_id` is also indexed in the in-memory decision-log store — use
/// [`LogStorage::get_logs_by_request_id`](crate::log::interface::LogStorage::get_logs_by_request_id)
/// with `batch_id.to_string()` to retrieve all decision entries for this batch.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BatchAuthorizeResponse<R> {
    /// Shared correlation ID for every decision-log entry emitted by this batch.
    pub batch_id: Uuid,
    /// Per-item results, in input order.
    pub results: Vec<R>,
}

impl<R> BatchAuthorizeResponse<R> {
    /// Construct a new batch response.
    #[must_use]
    pub fn new(batch_id: Uuid, results: Vec<R>) -> Self {
        Self { batch_id, results }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use test_utils::token_claims::generate_token_using_claims;

    // Helper function to create test tokens with proper claims
    fn create_test_token(mapping: &str, issuer: &str, sub: &str) -> TokenInput {
        let claims = json!({
            "sub": sub,
            "iat": 1_516_239_022,
            "iss": issuer
        });
        let token_string = generate_token_using_claims(&claims);
        TokenInput::new(mapping.to_string(), token_string)
    }

    #[test]
    fn test_token_input_creation() {
        let token = create_test_token("Jans::Access_Token", "https://example.com", "1234567890");

        assert_eq!(token.mapping, "Jans::Access_Token");
        assert!(token.payload.contains('.')); // JWT format check
    }

    #[test]
    fn test_token_input_validate_success() {
        let token = create_test_token("Jans::Access_Token", "https://example.com", "1234567890");

        let result = token.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_token_input_validate_empty_mapping() {
        let token = TokenInput::new(String::new(), "valid.jwt.token".to_string());

        let result = token.validate();
        assert!(matches!(result, Err(TokenInputError::EmptyMapping)));
    }

    #[test]
    fn test_token_input_validate_empty_payload() {
        let token = TokenInput::new("Jans::Access_Token".to_string(), String::new());

        let result = token.validate();
        assert!(matches!(result, Err(TokenInputError::EmptyPayload)));
    }

    #[test]
    fn test_authorize_multi_issuer_request_creation() {
        let tokens = vec![
            create_test_token("Jans::Access_Token", "https://example.com", "1234567890"),
            create_test_token("Jans::Id_Token", "https://example.com", "1234567890"),
        ];

        let resource = EntityData {
            cedar_mapping: CedarEntityMapping {
                entity_type: "Document".to_string(),
                id: "doc123".to_string(),
            },
            attributes: HashMap::new(),
        };

        let request =
            AuthorizeMultiIssuerRequest::new(tokens.clone(), resource.clone(), "Read".to_string());

        assert_eq!(request.tokens.len(), 2);
        assert_eq!(request.resource, resource);
        assert_eq!(request.action, "Read");
        assert!(request.context.is_none());
    }

    #[test]
    fn test_authorize_multi_issuer_request_with_fields() {
        let tokens = vec![create_test_token(
            "Jans::Access_Token",
            "https://example.com",
            "1234567890",
        )];

        let resource = EntityData {
            cedar_mapping: CedarEntityMapping {
                entity_type: "Document".to_string(),
                id: "doc123".to_string(),
            },
            attributes: HashMap::new(),
        };
        let action = "Read".to_string();
        let context = Some(json!({"location": "miami"}));

        let request = AuthorizeMultiIssuerRequest::new_with_fields(
            tokens,
            resource.clone(),
            action.clone(),
            context.clone(),
        );

        assert_eq!(request.tokens.len(), 1);
        assert_eq!(request.resource, resource);
        assert_eq!(request.action, action);
        assert_eq!(request.context, context);
    }

    #[test]
    fn test_authorize_multi_issuer_request_validation_success() {
        let tokens = vec![
            create_test_token("Jans::Access_Token", "https://example.com", "1234567890"),
            create_test_token("Jans::Id_Token", "https://example.com", "1234567890"),
        ];

        let resource = EntityData {
            cedar_mapping: CedarEntityMapping {
                entity_type: "Document".to_string(),
                id: "doc123".to_string(),
            },
            attributes: HashMap::new(),
        };

        let request = AuthorizeMultiIssuerRequest::new(tokens, resource, "Read".to_string());

        assert!(request.validate().is_ok());
    }

    #[test]
    fn test_authorize_multi_issuer_request_validation_empty_tokens() {
        let resource = EntityData {
            cedar_mapping: CedarEntityMapping {
                entity_type: "Document".to_string(),
                id: "doc123".to_string(),
            },
            attributes: HashMap::new(),
        };

        let request = AuthorizeMultiIssuerRequest::new(vec![], resource, "Read".to_string());

        let result = request.validate();
        assert!(matches!(
            result,
            Err(MultiIssuerValidationError::EmptyTokenArray)
        ));
    }

    #[test]
    fn test_authorize_multi_issuer_request_validation_invalid_token() {
        let tokens = vec![TokenInput::new(
            "valid-mapping".to_string(), // Valid mapping since we removed token validation
            "some-payload".to_string(),
        )];

        let resource = EntityData {
            cedar_mapping: CedarEntityMapping {
                entity_type: "Document".to_string(),
                id: "doc123".to_string(),
            },
            attributes: HashMap::new(),
        };

        let request = AuthorizeMultiIssuerRequest::new(tokens, resource, "Read".to_string());

        let result = request.validate();
        // The new validation logic only checks JSON fields
        // Valid mapping should pass validation
        assert!(result.is_ok());
    }

    #[test]
    fn test_authorize_multi_issuer_request_validation_invalid_json_fields() {
        let tokens = vec![create_test_token(
            "Jans::Access_Token",
            "https://example.com",
            "1234567890",
        )];

        let resource = EntityData {
            cedar_mapping: CedarEntityMapping {
                entity_type: "Document".to_string(),
                id: "doc123".to_string(),
            },
            attributes: HashMap::new(),
        };

        let request = AuthorizeMultiIssuerRequest::new_with_fields(
            tokens,
            resource,           // Valid resource
            "Read".to_string(), // Valid action
            Some(json!(123)),   // Invalid context (should be object)
        );

        let result = request.validate();
        assert!(matches!(
            result,
            Err(MultiIssuerValidationError::InvalidContextJson)
        ));
    }

    #[test]
    fn test_serialization_deserialization() {
        let tokens = vec![create_test_token(
            "Jans::Access_Token",
            "https://example.com",
            "1234567890",
        )];

        let resource = EntityData {
            cedar_mapping: CedarEntityMapping {
                entity_type: "Document".to_string(),
                id: "doc123".to_string(),
            },
            attributes: HashMap::new(),
        };
        let request = AuthorizeMultiIssuerRequest::new_with_fields(
            tokens,
            resource,
            "Read".to_string(),
            Some(json!({"location": "miami"})),
        );

        // Test serialization
        let json = serde_json::to_string(&request).expect("Should serialize");

        // Test deserialization
        let deserialized: AuthorizeMultiIssuerRequest =
            serde_json::from_str(&json).expect("Should deserialize");

        assert_eq!(request, deserialized);
    }

    fn make_resource(id: &str) -> EntityData {
        EntityData {
            cedar_mapping: CedarEntityMapping {
                entity_type: "Document".to_string(),
                id: id.to_string(),
            },
            attributes: HashMap::new(),
        }
    }

    fn make_item(id: &str) -> BatchItem {
        BatchItem {
            resource: make_resource(id),
            action: "Read".to_string(),
            context: json!({}),
        }
    }

    #[test]
    fn batch_unsigned_validates_valid_request() {
        let req = BatchAuthorizeUnsignedRequest::new(None, vec![make_item("a"), make_item("b")]);
        req.validate()
            .expect("well-formed unsigned request should validate");
    }

    #[test]
    fn batch_unsigned_rejects_empty_items() {
        let req = BatchAuthorizeUnsignedRequest::new(None, vec![]);
        assert_eq!(
            req.validate(),
            Err(BatchValidationError::EmptyItems),
            "validation should reject empty items list"
        );
    }

    #[test]
    fn batch_unsigned_rejects_non_object_context() {
        let bad_item = BatchItem {
            resource: make_resource("bad"),
            action: "Read".to_string(),
            context: json!(42),
        };
        let req = BatchAuthorizeUnsignedRequest::new(None, vec![make_item("a"), bad_item]);
        assert_eq!(
            req.validate(),
            Err(BatchValidationError::InvalidItemContext { index: 1 }),
            "validation should reject non-object context at index 1"
        );
    }

    #[test]
    fn batch_multi_issuer_validates_valid_request() {
        let tokens = vec![create_test_token(
            "Jans::Access_Token",
            "https://example.com",
            "sub",
        )];
        let req = BatchAuthorizeMultiIssuerRequest::new(tokens, vec![make_item("a")]);
        req.validate()
            .expect("well-formed multi-issuer request should validate");
    }

    #[test]
    fn batch_multi_issuer_rejects_empty_tokens() {
        let req = BatchAuthorizeMultiIssuerRequest::new(vec![], vec![make_item("a")]);
        assert_eq!(
            req.validate(),
            Err(BatchValidationError::EmptyTokens),
            "validation should reject empty tokens list"
        );
    }

    #[test]
    fn batch_multi_issuer_rejects_empty_items() {
        let tokens = vec![create_test_token(
            "Jans::Access_Token",
            "https://example.com",
            "sub",
        )];
        let req = BatchAuthorizeMultiIssuerRequest::new(tokens, vec![]);
        assert_eq!(
            req.validate(),
            Err(BatchValidationError::EmptyItems),
            "validation should reject empty items list"
        );
    }

    #[test]
    fn batch_multi_issuer_rejects_non_object_context() {
        let tokens = vec![create_test_token(
            "Jans::Access_Token",
            "https://example.com",
            "sub",
        )];
        let bad_item = BatchItem {
            resource: make_resource("bad"),
            action: "Read".to_string(),
            context: json!("string-not-object"),
        };
        let req = BatchAuthorizeMultiIssuerRequest::new(tokens, vec![bad_item]);
        assert_eq!(
            req.validate(),
            Err(BatchValidationError::InvalidItemContext { index: 0 }),
            "validation should reject non-object context at index 0"
        );
    }

    #[test]
    fn batch_unsigned_round_trips_json() {
        let req = BatchAuthorizeUnsignedRequest::new(
            Some(make_resource("me")),
            vec![
                BatchItem {
                    resource: make_resource("a"),
                    action: "Read".to_string(),
                    context: json!({"ip": "10.0.0.1"}),
                },
                BatchItem {
                    resource: make_resource("b"),
                    action: "Write".to_string(),
                    context: json!({}),
                },
            ],
        );
        let s = serde_json::to_string(&req).expect("serialize");
        let round: BatchAuthorizeUnsignedRequest = serde_json::from_str(&s).expect("deserialize");
        assert_eq!(
            round.items.len(),
            2,
            "round-trip should preserve items length"
        );
        assert_eq!(
            round.items[0].action, "Read",
            "round-trip should preserve item 0 action"
        );
        assert_eq!(
            round.items[1].action, "Write",
            "round-trip should preserve item 1 action"
        );
        assert!(
            round.principal.is_some(),
            "round-trip should preserve principal presence"
        );
    }

    #[test]
    fn batch_multi_issuer_round_trips_json() {
        let tokens = vec![
            create_test_token("Jans::Access_Token", "https://example.com", "sub-a"),
            create_test_token("Jans::Id_Token", "https://example.com", "sub-b"),
        ];
        let req = BatchAuthorizeMultiIssuerRequest::new(
            tokens,
            vec![make_item("a"), make_item("b"), make_item("c")],
        );
        let s = serde_json::to_string(&req).expect("serialize");
        let round: BatchAuthorizeMultiIssuerRequest =
            serde_json::from_str(&s).expect("deserialize");
        assert_eq!(
            round.tokens.len(),
            2,
            "round-trip should preserve tokens length"
        );
        assert_eq!(
            round.items.len(),
            3,
            "round-trip should preserve items length"
        );
    }

    #[test]
    fn batch_response_round_trips_json() {
        use crate::log::gen_uuid7;
        let response: BatchAuthorizeResponse<String> =
            BatchAuthorizeResponse::new(gen_uuid7(), vec!["allow".to_string(), "deny".to_string()]);
        let s = serde_json::to_string(&response).expect("serialize");
        let round: BatchAuthorizeResponse<String> = serde_json::from_str(&s).expect("deserialize");
        assert_eq!(
            round.batch_id, response.batch_id,
            "round-trip should preserve batch_id"
        );
        assert_eq!(
            round.results, response.results,
            "round-trip should preserve results list"
        );
    }
}