oxidize-pdf 2.5.0

A pure Rust PDF generation and manipulation library with zero external dependencies
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
//! Runtime permissions enforcement for PDF operations
//!
//! This module implements runtime validation of PDF permissions with
//! callbacks and logging according to ISO 32000-1:2008 ยง7.6.3.3.

use crate::encryption::Permissions;
use crate::error::{PdfError, Result};
use std::sync::Mutex;

/// Permission operation type
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PermissionOperation {
    /// Print operation
    Print,
    /// Print in high quality
    PrintHighQuality,
    /// Modify document contents
    ModifyContents,
    /// Copy text and graphics
    Copy,
    /// Modify annotations
    ModifyAnnotations,
    /// Fill in form fields
    FillForms,
    /// Extract text and graphics for accessibility
    Accessibility,
    /// Assemble document (insert, rotate, delete pages)
    Assemble,
}

impl PermissionOperation {
    /// Get human-readable name
    pub fn name(&self) -> &'static str {
        match self {
            PermissionOperation::Print => "Print",
            PermissionOperation::PrintHighQuality => "Print High Quality",
            PermissionOperation::ModifyContents => "Modify Contents",
            PermissionOperation::Copy => "Copy",
            PermissionOperation::ModifyAnnotations => "Modify Annotations",
            PermissionOperation::FillForms => "Fill Forms",
            PermissionOperation::Accessibility => "Accessibility",
            PermissionOperation::Assemble => "Assemble",
        }
    }
}

/// Permission check result
#[derive(Debug, Clone)]
pub struct PermissionCheckResult {
    /// Operation that was checked
    pub operation: PermissionOperation,
    /// Whether permission was granted
    pub allowed: bool,
    /// Timestamp of check
    pub timestamp: std::time::SystemTime,
    /// Additional context
    pub context: Option<String>,
}

/// Callback for permission checks
pub type PermissionCallback = Box<dyn Fn(&PermissionCheckResult) + Send + Sync>;

/// Log level for permission events
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub enum LogLevel {
    /// Debug level - all events
    Debug,
    /// Info level - allowed operations
    Info,
    /// Warning level - denied operations
    Warn,
    /// Error level - security violations
    Error,
}

/// Permission event for logging
#[derive(Debug, Clone)]
pub struct PermissionEvent {
    /// Log level
    pub level: LogLevel,
    /// Operation
    pub operation: PermissionOperation,
    /// Whether allowed
    pub allowed: bool,
    /// Timestamp
    pub timestamp: std::time::SystemTime,
    /// Message
    pub message: String,
}

/// Permissions validator trait
pub trait PermissionsValidator: Send + Sync {
    /// Validate a permission operation
    fn validate(&self, operation: PermissionOperation) -> Result<bool>;

    /// Get current permissions
    fn permissions(&self) -> Permissions;
}

/// Runtime permissions enforcer
pub struct RuntimePermissions {
    /// Base permissions
    permissions: Permissions,
    /// Callbacks for permission checks
    callbacks: Vec<PermissionCallback>,
    /// Log level
    log_level: LogLevel,
    /// Event log
    event_log: Mutex<Vec<PermissionEvent>>,
    /// Whether to enforce permissions (false = allow all)
    enforce: bool,
}

impl RuntimePermissions {
    /// Create new runtime permissions
    pub fn new(permissions: Permissions) -> Self {
        Self {
            permissions,
            callbacks: Vec::new(),
            log_level: LogLevel::Info,
            event_log: Mutex::new(Vec::new()),
            enforce: true,
        }
    }

    /// Add a callback for permission checks
    pub fn add_callback<F>(&mut self, callback: F)
    where
        F: Fn(&PermissionCheckResult) + Send + Sync + 'static,
    {
        self.callbacks.push(Box::new(callback));
    }

    /// Set log level
    pub fn set_log_level(&mut self, level: LogLevel) {
        self.log_level = level;
    }

    /// Set enforcement (false = allow all operations)
    pub fn set_enforce(&mut self, enforce: bool) {
        self.enforce = enforce;
    }

    /// Get event log
    pub fn get_events(&self) -> Vec<PermissionEvent> {
        self.event_log
            .lock()
            .map(|log| log.clone())
            .unwrap_or_else(|_| Vec::new())
    }

    /// Clear event log
    pub fn clear_events(&self) {
        if let Ok(mut log) = self.event_log.lock() {
            log.clear();
        }
        // Silently ignore if lock is poisoned
    }

    /// Check if operation is allowed
    fn check_permission(&self, operation: PermissionOperation) -> bool {
        if !self.enforce {
            return true;
        }

        match operation {
            PermissionOperation::Print => self.permissions.can_print(),
            PermissionOperation::PrintHighQuality => self.permissions.can_print_high_quality(),
            PermissionOperation::ModifyContents => self.permissions.can_modify_contents(),
            PermissionOperation::Copy => self.permissions.can_copy(),
            PermissionOperation::ModifyAnnotations => self.permissions.can_modify_annotations(),
            PermissionOperation::FillForms => self.permissions.can_fill_forms(),
            PermissionOperation::Accessibility => self.permissions.can_access_for_accessibility(),
            PermissionOperation::Assemble => self.permissions.can_assemble(),
        }
    }

    /// Log an event
    fn log_event(&self, operation: PermissionOperation, allowed: bool, message: String) {
        let level = if allowed {
            if self.log_level <= LogLevel::Debug {
                LogLevel::Debug
            } else {
                LogLevel::Info
            }
        } else {
            LogLevel::Warn
        };

        let event = PermissionEvent {
            level,
            operation,
            allowed,
            timestamp: std::time::SystemTime::now(),
            message,
        };

        if level >= self.log_level {
            if let Ok(mut log) = self.event_log.lock() {
                log.push(event);
            }
            // Silently ignore if lock is poisoned
        }
    }

    /// Execute callbacks
    fn execute_callbacks(&self, result: &PermissionCheckResult) {
        for callback in &self.callbacks {
            callback(result);
        }
    }

    /// Validate operation with logging and callbacks
    fn validate_operation(
        &self,
        operation: PermissionOperation,
        context: Option<String>,
    ) -> Result<()> {
        let allowed = self.check_permission(operation);

        let result = PermissionCheckResult {
            operation,
            allowed,
            timestamp: std::time::SystemTime::now(),
            context: context.clone(),
        };

        // Execute callbacks
        self.execute_callbacks(&result);

        // Log event
        let message = if let Some(ctx) = context {
            format!(
                "{} operation {} ({})",
                operation.name(),
                if allowed { "allowed" } else { "denied" },
                ctx
            )
        } else {
            format!(
                "{} operation {}",
                operation.name(),
                if allowed { "allowed" } else { "denied" }
            )
        };
        self.log_event(operation, allowed, message);

        if allowed {
            Ok(())
        } else {
            Err(PdfError::PermissionDenied(format!(
                "Permission denied for {} operation",
                operation.name()
            )))
        }
    }

    // Public operation methods

    /// Validate print operation
    pub fn on_print(&self, context: Option<String>) -> Result<()> {
        self.validate_operation(PermissionOperation::Print, context)
    }

    /// Validate high-quality print operation
    pub fn on_print_high_quality(&self, context: Option<String>) -> Result<()> {
        self.validate_operation(PermissionOperation::PrintHighQuality, context)
    }

    /// Validate modify operation
    pub fn on_modify(&self, context: Option<String>) -> Result<()> {
        self.validate_operation(PermissionOperation::ModifyContents, context)
    }

    /// Validate copy operation
    pub fn on_copy(&self, context: Option<String>) -> Result<()> {
        self.validate_operation(PermissionOperation::Copy, context)
    }

    /// Validate annotation modification
    pub fn on_modify_annotations(&self, context: Option<String>) -> Result<()> {
        self.validate_operation(PermissionOperation::ModifyAnnotations, context)
    }

    /// Validate form filling
    pub fn on_form_fill(&self, context: Option<String>) -> Result<()> {
        self.validate_operation(PermissionOperation::FillForms, context)
    }

    /// Validate accessibility access
    pub fn on_accessibility(&self, context: Option<String>) -> Result<()> {
        self.validate_operation(PermissionOperation::Accessibility, context)
    }

    /// Validate document assembly
    pub fn on_assemble(&self, context: Option<String>) -> Result<()> {
        self.validate_operation(PermissionOperation::Assemble, context)
    }
}

impl PermissionsValidator for RuntimePermissions {
    fn validate(&self, operation: PermissionOperation) -> Result<bool> {
        Ok(self.check_permission(operation))
    }

    fn permissions(&self) -> Permissions {
        self.permissions
    }
}

/// Builder for RuntimePermissions
pub struct RuntimePermissionsBuilder {
    permissions: Permissions,
    callbacks: Vec<PermissionCallback>,
    log_level: LogLevel,
    enforce: bool,
}

impl RuntimePermissionsBuilder {
    /// Create new builder
    pub fn new(permissions: Permissions) -> Self {
        Self {
            permissions,
            callbacks: Vec::new(),
            log_level: LogLevel::Info,
            enforce: true,
        }
    }

    /// Add callback
    pub fn with_callback<F>(mut self, callback: F) -> Self
    where
        F: Fn(&PermissionCheckResult) + Send + Sync + 'static,
    {
        self.callbacks.push(Box::new(callback));
        self
    }

    /// Set log level
    pub fn with_log_level(mut self, level: LogLevel) -> Self {
        self.log_level = level;
        self
    }

    /// Set enforcement
    pub fn with_enforcement(mut self, enforce: bool) -> Self {
        self.enforce = enforce;
        self
    }

    /// Build RuntimePermissions
    pub fn build(self) -> RuntimePermissions {
        let mut runtime = RuntimePermissions::new(self.permissions);
        runtime.callbacks = self.callbacks;
        runtime.log_level = self.log_level;
        runtime.enforce = self.enforce;
        runtime
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    #[test]
    fn test_permission_operation_names() {
        assert_eq!(PermissionOperation::Print.name(), "Print");
        assert_eq!(
            PermissionOperation::ModifyContents.name(),
            "Modify Contents"
        );
        assert_eq!(PermissionOperation::Accessibility.name(), "Accessibility");
    }

    #[test]
    fn test_runtime_permissions_allow() {
        let perms = Permissions::all();
        let runtime = RuntimePermissions::new(perms);

        assert!(runtime.on_print(None).is_ok());
        assert!(runtime.on_modify(None).is_ok());
        assert!(runtime.on_copy(None).is_ok());
    }

    #[test]
    fn test_runtime_permissions_deny() {
        let perms = Permissions::new(); // No permissions
        let runtime = RuntimePermissions::new(perms);

        assert!(runtime.on_print(None).is_err());
        assert!(runtime.on_modify(None).is_err());
        assert!(runtime.on_copy(None).is_err());
    }

    #[test]
    fn test_runtime_permissions_selective() {
        let perms = *Permissions::new().set_print(true).set_copy(true);
        let runtime = RuntimePermissions::new(perms);

        assert!(runtime.on_print(None).is_ok());
        assert!(runtime.on_copy(None).is_ok());
        assert!(runtime.on_modify(None).is_err());
    }

    #[test]
    fn test_enforcement_disabled() {
        let perms = Permissions::new(); // No permissions
        let mut runtime = RuntimePermissions::new(perms);
        runtime.set_enforce(false);

        // All operations should be allowed
        assert!(runtime.on_print(None).is_ok());
        assert!(runtime.on_modify(None).is_ok());
        assert!(runtime.on_copy(None).is_ok());
    }

    #[test]
    fn test_callbacks() {
        let perms = *Permissions::new().set_print(true);
        let mut runtime = RuntimePermissions::new(perms);

        let callback_called = Arc::new(Mutex::new(false));
        let callback_called_clone = callback_called.clone();

        runtime.add_callback(move |result| {
            assert_eq!(result.operation, PermissionOperation::Print);
            assert!(result.allowed);
            *callback_called_clone.lock().unwrap() = true;
        });

        runtime.on_print(None).unwrap();
        assert!(*callback_called.lock().unwrap());
    }

    #[test]
    fn test_multiple_callbacks() {
        let perms = *Permissions::new().set_print(true);
        let mut runtime = RuntimePermissions::new(perms);

        let counter = Arc::new(Mutex::new(0));

        for _ in 0..3 {
            let counter_clone = counter.clone();
            runtime.add_callback(move |_| {
                *counter_clone.lock().unwrap() += 1;
            });
        }

        runtime.on_print(None).unwrap();
        assert_eq!(*counter.lock().unwrap(), 3);
    }

    #[test]
    fn test_context_in_callback() {
        let perms = *Permissions::new().set_copy(true);
        let mut runtime = RuntimePermissions::new(perms);

        let context_received = Arc::new(Mutex::new(String::new()));
        let context_clone = context_received.clone();

        runtime.add_callback(move |result| {
            if let Some(ctx) = &result.context {
                *context_clone.lock().unwrap() = ctx.clone();
            }
        });

        runtime.on_copy(Some("Copying page 5".to_string())).unwrap();
        assert_eq!(*context_received.lock().unwrap(), "Copying page 5");
    }

    #[test]
    fn test_event_logging() {
        let perms = *Permissions::new().set_print(true);
        let mut runtime = RuntimePermissions::new(perms);
        runtime.set_log_level(LogLevel::Debug);

        runtime.on_print(Some("Test print".to_string())).unwrap();
        let _ = runtime.on_modify(None); // This will fail

        let events = runtime.get_events();
        assert_eq!(events.len(), 2);

        assert_eq!(events[0].operation, PermissionOperation::Print);
        assert!(events[0].allowed);

        assert_eq!(events[1].operation, PermissionOperation::ModifyContents);
        assert!(!events[1].allowed);
    }

    #[test]
    fn test_log_levels() {
        let perms = Permissions::all();
        let mut runtime = RuntimePermissions::new(perms);

        // Set to Warn - should only log denied operations
        runtime.set_log_level(LogLevel::Warn);

        runtime.on_print(None).unwrap(); // Allowed - not logged

        let mut runtime2 = RuntimePermissions::new(Permissions::new());
        runtime2.set_log_level(LogLevel::Warn);
        let _ = runtime2.on_print(None); // Denied - logged

        assert_eq!(runtime.get_events().len(), 0);
        assert_eq!(runtime2.get_events().len(), 1);
    }

    #[test]
    fn test_clear_events() {
        let perms = Permissions::all();
        let runtime = RuntimePermissions::new(perms);

        runtime.on_print(None).unwrap();
        runtime.on_copy(None).unwrap();

        assert!(runtime.get_events().len() >= 2);

        runtime.clear_events();
        assert_eq!(runtime.get_events().len(), 0);
    }

    #[test]
    fn test_permissions_validator_trait() {
        let perms = *Permissions::new().set_accessibility(true);
        let runtime = RuntimePermissions::new(perms);

        // Test trait methods
        assert!(runtime
            .validate(PermissionOperation::Accessibility)
            .unwrap());
        assert!(!runtime.validate(PermissionOperation::Print).unwrap());

        let retrieved_perms = runtime.permissions();
        assert!(retrieved_perms.can_access_for_accessibility());
        assert!(!retrieved_perms.can_print());
    }

    #[test]
    fn test_builder() {
        let counter = Arc::new(Mutex::new(0));
        let counter_clone = counter.clone();

        let runtime = RuntimePermissionsBuilder::new(Permissions::all())
            .with_callback(move |_| {
                *counter_clone.lock().unwrap() += 1;
            })
            .with_log_level(LogLevel::Debug)
            .with_enforcement(true)
            .build();

        runtime.on_print(None).unwrap();
        assert_eq!(*counter.lock().unwrap(), 1);
        assert_eq!(runtime.log_level, LogLevel::Debug);
    }

    #[test]
    fn test_all_operations() {
        let perms = Permissions::all();
        let runtime = RuntimePermissions::new(perms);

        // Test all operations
        assert!(runtime.on_print(None).is_ok());
        assert!(runtime.on_print_high_quality(None).is_ok());
        assert!(runtime.on_modify(None).is_ok());
        assert!(runtime.on_copy(None).is_ok());
        assert!(runtime.on_modify_annotations(None).is_ok());
        assert!(runtime.on_form_fill(None).is_ok());
        assert!(runtime.on_accessibility(None).is_ok());
        assert!(runtime.on_assemble(None).is_ok());
    }

    #[test]
    fn test_error_messages() {
        let perms = Permissions::new();
        let runtime = RuntimePermissions::new(perms);

        let err = runtime.on_print(None).unwrap_err();
        match err {
            PdfError::PermissionDenied(msg) => {
                assert!(msg.contains("Print"));
            }
            _ => panic!("Expected PermissionDenied error"),
        }
    }
}