cedarling 0.0.64

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

//! Test utilities for policy store testing.
//!
//! This module provides utilities for creating test policy stores programmatically,
//! including:
//! - `PolicyStoreTestBuilder` - Fluent builder for creating policy stores
//! - Test fixtures for valid and invalid policy stores
//! - Archive creation utilities for .cjar testing
//! - Performance testing utilities

use super::errors::PolicyStoreError;
use std::collections::HashMap;
use std::io::{Cursor, Write};
use zip::write::{ExtendedFileOptions, FileOptions};
use zip::{CompressionMethod, ZipWriter};

/// Builder for creating test policy stores programmatically.
pub(crate) struct PolicyStoreTestBuilder {
    /// Store ID (hex string)
    pub id: String,
    /// Store name
    pub name: String,
    /// Store version
    pub version: String,
    /// Cedar version
    pub cedar_version: String,
    /// Description
    pub description: Option<String>,
    /// Schema content (Cedar schema format)
    pub schema: String,
    /// Policies: filename -> content
    pub policies: HashMap<String, String>,
    /// Templates: filename -> content
    pub templates: HashMap<String, String>,
    /// Entities: filename -> content
    pub entities: HashMap<String, String>,
    /// Trusted issuers: filename -> content
    pub trusted_issuers: HashMap<String, String>,
    /// Additional files to include
    pub extra_files: HashMap<String, String>,
}

impl Default for PolicyStoreTestBuilder {
    fn default() -> Self {
        Self::new("test123456789")
    }
}

impl PolicyStoreTestBuilder {
    /// Create a new builder with the given store ID.
    pub(crate) fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: "Test Policy Store".to_string(),
            version: "1.0.0".to_string(),
            cedar_version: "4.4.0".to_string(),
            description: None,
            schema: Self::default_schema(),
            policies: HashMap::new(),
            templates: HashMap::new(),
            entities: HashMap::new(),
            trusted_issuers: HashMap::new(),
            extra_files: HashMap::new(),
        }
    }

    /// Default minimal Cedar schema for testing.
    pub(crate) fn default_schema() -> String {
        r#"namespace TestApp {
    entity User;
    entity Resource;
    entity Role;
    
    action "read" appliesTo {
        principal: [User],
        resource: [Resource]
    };
    
    action "write" appliesTo {
        principal: [User],
        resource: [Resource]
    };
}
"#
        .to_string()
    }

    /// Set the store name.
    pub(crate) fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// Set the store version.
    pub(crate) fn with_version(mut self, version: impl Into<String>) -> Self {
        self.version = version.into();
        self
    }

    /// Set the description.
    pub(crate) fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Set a custom Cedar schema.
    ///
    /// If not called, a default minimal schema is used.
    pub(crate) fn with_schema(mut self, schema: impl Into<String>) -> Self {
        self.schema = schema.into();
        self
    }

    /// Add a policy file.
    ///
    /// # Arguments
    /// * `name` - Filename without .cedar extension (e.g., "policy1" or "auth/admin")
    /// * `content` - Cedar policy content with @id annotation
    pub(crate) fn with_policy(
        mut self,
        name: impl Into<String>,
        content: impl Into<String>,
    ) -> Self {
        self.policies.insert(name.into(), content.into());
        self
    }

    /// Add a template file.
    ///
    /// # Arguments
    /// * `name` - Filename without .cedar extension
    /// * `content` - Cedar template content with @id annotation and slot(s)
    pub(crate) fn with_template(
        mut self,
        name: impl Into<String>,
        content: impl Into<String>,
    ) -> Self {
        self.templates.insert(name.into(), content.into());
        self
    }

    /// Add an entity file.
    ///
    /// # Arguments
    /// * `name` - Filename without .json extension (e.g., "users" or "roles/admin")
    /// * `content` - JSON entity content
    pub(crate) fn with_entity(
        mut self,
        name: impl Into<String>,
        content: impl Into<String>,
    ) -> Self {
        self.entities.insert(name.into(), content.into());
        self
    }

    /// Add a trusted issuer file.
    pub(crate) fn with_trusted_issuer(
        mut self,
        name: impl Into<String>,
        content: impl Into<String>,
    ) -> Self {
        self.trusted_issuers.insert(name.into(), content.into());
        self
    }

    /// Generate metadata.json content.
    pub(crate) fn build_metadata_json(&self) -> String {
        let mut metadata = serde_json::json!({
            "cedar_version": self.cedar_version,
            "policy_store": {
                "id": self.id,
                "name": self.name,
                "version": self.version
            }
        });

        if let Some(desc) = &self.description {
            metadata["policy_store"]["description"] = serde_json::Value::String(desc.clone());
        }

        serde_json::to_string_pretty(&metadata).unwrap()
    }

    /// Build all files as a `HashMap` (path -> content bytes).
    fn build_files(&self) -> HashMap<String, Vec<u8>> {
        let mut files: HashMap<String, Vec<u8>> = HashMap::new();

        // Add metadata.json
        files.insert(
            "metadata.json".to_string(),
            self.build_metadata_json().into_bytes(),
        );

        // Add schema.cedarschema
        files.insert(
            "schema.cedarschema".to_string(),
            self.schema.as_bytes().to_vec(),
        );

        // Add policies
        for (name, content) in &self.policies {
            let path = format!("policies/{name}.cedar");
            files.insert(path, content.as_bytes().to_vec());
        }

        // Add templates
        for (name, content) in &self.templates {
            let path = format!("templates/{name}.cedar");
            files.insert(path, content.as_bytes().to_vec());
        }

        // Add entities
        for (name, content) in &self.entities {
            let path = format!("entities/{name}.json");
            files.insert(path, content.as_bytes().to_vec());
        }

        // Add trusted issuers
        for (name, content) in &self.trusted_issuers {
            let path = format!("trusted-issuers/{name}.json");
            files.insert(path, content.as_bytes().to_vec());
        }

        // Add extra files last, overwriting any generated files with the same path
        for (path, content) in &self.extra_files {
            files.insert(path.clone(), content.as_bytes().to_vec());
        }

        files
    }

    /// Build policy store as .cjar archive bytes.
    ///
    /// Returns the archive as a byte vector suitable for `ArchiveVfs::from_buffer()`.
    pub(crate) fn build_archive(&self) -> Result<Vec<u8>, PolicyStoreError> {
        let files = self.build_files();
        let buffer = Vec::new();
        let cursor = Cursor::new(buffer);
        let mut zip = ZipWriter::new(cursor);

        for (path, content) in files {
            let options = FileOptions::<ExtendedFileOptions>::default()
                .compression_method(CompressionMethod::Deflated);
            zip.start_file(&path, options)
                .map_err(|e| PolicyStoreError::Io(std::io::Error::other(e)))?;
            zip.write_all(&content).map_err(PolicyStoreError::Io)?;
        }

        let cursor = zip
            .finish()
            .map_err(|e| PolicyStoreError::Io(std::io::Error::other(e)))?;
        Ok(cursor.into_inner())
    }
}

// ============================================================================
// Test Fixtures
// ============================================================================

/// Pre-built test fixtures for common scenarios.
pub(crate) mod fixtures {
    use super::*;

    /// Creates a minimal valid policy store.
    pub(crate) fn minimal_valid() -> PolicyStoreTestBuilder {
        PolicyStoreTestBuilder::new("abc123def456").with_policy(
            "allow-all",
            r#"@id("allow-all")
permit(principal, action, resource);"#,
        )
    }

    /// Creates a policy store with multiple policies.
    pub(crate) fn with_multiple_policies(count: usize) -> PolicyStoreTestBuilder {
        let mut builder = PolicyStoreTestBuilder::new("multipolicy123");

        for i in 0..count {
            builder = builder.with_policy(
                format!("policy{i}"),
                format!(
                    r#"@id("policy{i}")
permit(
    principal == TestApp::User::"user{i}",
    action == TestApp::Action::"read",
    resource == TestApp::Resource::"res{i}"
);"#
                ),
            );
        }

        builder
    }

    /// Creates a policy store with multiple entities.
    pub(crate) fn with_multiple_entities(count: usize) -> PolicyStoreTestBuilder {
        let mut builder = PolicyStoreTestBuilder::new("multientity123").with_policy(
            "allow-all",
            r#"@id("allow-all") permit(principal, action, resource);"#,
        );

        // Create users
        let mut users = Vec::new();
        for i in 0..count {
            users.push(serde_json::json!({
                "uid": {"type": "TestApp::User", "id": format!("user{}", i)},
                "attrs": {
                    "name": format!("User {}", i),
                    "email": format!("user{}@example.com", i)
                },
                "parents": []
            }));
        }

        builder = builder.with_entity("users", serde_json::to_string_pretty(&users).unwrap());

        builder
    }

    // ========================================================================
    // Invalid Fixtures
    // ========================================================================

    /// Creates a policy store with invalid metadata JSON.
    pub(crate) fn invalid_metadata_json() -> PolicyStoreTestBuilder {
        let mut builder = minimal_valid();
        builder
            .extra_files
            .insert("metadata.json".to_string(), "{ invalid json }".to_string());
        builder
    }

    /// Creates a policy store with invalid policy syntax.
    pub(crate) fn invalid_policy_syntax() -> PolicyStoreTestBuilder {
        PolicyStoreTestBuilder::new("invalidpolicy")
            .with_policy("bad-policy", "permit ( principal action resource );")
    }

    /// Creates a policy store with duplicate entity UIDs.
    pub(crate) fn duplicate_entity_uids() -> PolicyStoreTestBuilder {
        let users1 = serde_json::json!([{
            "uid": {"type": "TestApp::User", "id": "alice"},
            "attrs": {},
            "parents": []
        }]);

        let users2 = serde_json::json!([{
            "uid": {"type": "TestApp::User", "id": "alice"},
            "attrs": {},
            "parents": []
        }]);

        minimal_valid()
            .with_entity("users1", users1.to_string())
            .with_entity("users2", users2.to_string())
    }

    /// Creates a policy store with invalid trusted issuer config.
    pub(crate) fn invalid_trusted_issuer() -> PolicyStoreTestBuilder {
        let issuer = serde_json::json!({
            "bad-issuer": {
                "name": "Missing OIDC endpoint"
                // Missing required oidc_endpoint field
            }
        });

        minimal_valid().with_trusted_issuer("bad-issuer", issuer.to_string())
    }
}

// ============================================================================
// Archive Test Utilities
// ============================================================================

/// Creates a test archive with path traversal attempt.
pub(super) fn create_path_traversal_archive() -> Vec<u8> {
    let buffer = Vec::new();
    let cursor = Cursor::new(buffer);
    let mut zip = ZipWriter::new(cursor);

    let options = FileOptions::<ExtendedFileOptions>::default()
        .compression_method(CompressionMethod::Deflated);
    zip.start_file("../../../etc/passwd", options).unwrap();
    zip.write_all(b"malicious content").unwrap();

    zip.finish().unwrap().into_inner()
}

/// Creates a corrupted archive (invalid ZIP structure).
pub(super) fn create_corrupted_archive() -> Vec<u8> {
    // Start with valid ZIP header but corrupt it
    let mut bytes = vec![0x50, 0x4B, 0x03, 0x04]; // ZIP local file header
    bytes.extend_from_slice(&[0xFF; 100]); // Corrupted data
    bytes
}

/// Creates a deeply nested archive for path length testing.
pub(super) fn create_deep_nested_archive(depth: usize) -> Vec<u8> {
    let buffer = Vec::new();
    let cursor = Cursor::new(buffer);
    let mut zip = ZipWriter::new(cursor);

    let path = (0..depth).map(|_| "dir").collect::<Vec<_>>().join("/") + "/file.txt";

    let options = FileOptions::<ExtendedFileOptions>::default()
        .compression_method(CompressionMethod::Deflated);
    zip.start_file(&path, options).unwrap();
    zip.write_all(b"deep content").unwrap();

    zip.finish().unwrap().into_inner()
}

// ============================================================================
// Performance Testing Utilities
// ============================================================================

/// Creates a large policy store for load testing.
///
/// # Arguments
/// * `policy_count` - Number of policies to generate
/// * `entity_count` - Number of entities to generate
/// * `issuer_count` - Number of trusted issuers to generate
pub(super) fn create_large_policy_store(
    policy_count: usize,
    entity_count: usize,
    issuer_count: usize,
) -> PolicyStoreTestBuilder {
    let mut builder = PolicyStoreTestBuilder::new("loadtest123456");

    // Generate policies
    for i in 0..policy_count {
        builder = builder.with_policy(
            format!("policy{i:06}"),
            format!(
                r#"@id("policy{:06}")
permit(
    principal == TestApp::User::"user{:06}",
    action == TestApp::Action::"read",
    resource == TestApp::Resource::"resource{:06}"
) when {{
    principal has email && principal.email like "*@example.com"
}};"#,
                i,
                i % entity_count,
                i % 100
            ),
        );
    }

    // Generate entities in batches
    let batch_size = 1000;
    let entity_batches = entity_count.div_ceil(batch_size);

    for batch in 0..entity_batches {
        let start = batch * batch_size;
        let end = ((batch + 1) * batch_size).min(entity_count);

        let entities: Vec<_> = (start..end)
            .map(|i| {
                serde_json::json!({
                    "uid": {"type": "TestApp::User", "id": format!("user{:06}", i)},
                    "attrs": {
                        "name": format!("User {}", i),
                        "email": format!("user{}@example.com", i),
                        "department": format!("dept{}", i % 10)
                    },
                    "parents": []
                })
            })
            .collect();

        builder = builder.with_entity(
            format!("users_batch{batch:04}"),
            serde_json::to_string(&entities).unwrap(),
        );
    }

    // Generate trusted issuers
    for i in 0..issuer_count {
        let issuer = serde_json::json!({
            format!("issuer{}", i): {
                "name": format!("Issuer {}", i),
                "openid_configuration_endpoint": format!("https://issuer{}.example.com/.well-known/openid-configuration", i),
                "token_metadata": {
                    "access_token": {
                        "entity_type_name": "issuer",
                        "user_id": "sub",
                        "required_claims": ["sub"]
                    }
                }
            }
        });
        builder = builder.with_trusted_issuer(format!("issuer{i}"), issuer.to_string());
    }

    builder
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder_creates_valid_metadata() {
        let builder = PolicyStoreTestBuilder::new("test123abc456")
            .with_name("My Test Store")
            .with_version("2.0.0")
            .with_description("A test store");

        let metadata_json = builder.build_metadata_json();
        let metadata: serde_json::Value = serde_json::from_str(&metadata_json).unwrap();

        assert_eq!(metadata["cedar_version"], "4.4.0");
        assert_eq!(metadata["policy_store"]["id"], "test123abc456");
        assert_eq!(metadata["policy_store"]["name"], "My Test Store");
        assert_eq!(metadata["policy_store"]["version"], "2.0.0");
        assert_eq!(metadata["policy_store"]["description"], "A test store");
    }

    #[test]
    fn test_builder_creates_archive() {
        let builder = fixtures::minimal_valid();
        let archive = builder.build_archive().unwrap();

        // Verify it's a valid ZIP
        assert!(!archive.is_empty());
        assert_eq!(&archive[0..2], &[0x50, 0x4B]); // ZIP magic number
    }

    #[test]
    fn test_fixture_with_multiple_policies() {
        let builder = fixtures::with_multiple_policies(10);
        assert_eq!(builder.policies.len(), 10);
    }

    #[test]
    fn test_fixture_with_multiple_entities() {
        let builder = fixtures::with_multiple_entities(100);
        assert_eq!(builder.entities.len(), 1); // All in one file
    }

    #[test]
    fn test_large_policy_store_creation() {
        let builder = create_large_policy_store(100, 1000, 5);
        assert_eq!(builder.policies.len(), 100);
        assert_eq!(builder.trusted_issuers.len(), 5);
    }

    #[test]
    fn test_path_traversal_archive() {
        let archive = create_path_traversal_archive();
        assert!(!archive.is_empty());
    }

    #[test]
    fn test_corrupted_archive() {
        let archive = create_corrupted_archive();
        assert!(!archive.is_empty());
    }

    #[test]
    fn test_deep_nested_archive() {
        let archive = create_deep_nested_archive(50);
        assert!(!archive.is_empty());
    }
}