-
Notifications
You must be signed in to change notification settings - Fork 5
/
entity_provider.rs
563 lines (502 loc) · 18.9 KB
/
entity_provider.rs
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
//! Provides a simple `SimpleEntityProvider` and an implementation using a local file system,
//! in the form a `EntityProvider`.
//!
//! # Examples
//!
//! ```
//! use cedar_local_agent::public::file::entity_provider::{ConfigBuilder, EntityProvider};
//!
//! let entity_provider = EntityProvider::new(
//! ConfigBuilder::default()
//! .schema_path("schema_path")
//! .entities_path("entities_path")
//! .build()
//! .unwrap()
//! );
//! ```
use std::fmt::Debug;
use std::fs::File;
use std::io::Error;
use std::sync::Arc;
use async_trait::async_trait;
use cedar_policy::{entities_errors::EntitiesError, Entities, Request, Schema};
use derive_builder::Builder;
use thiserror::Error;
use tokio::sync::RwLock;
use tracing::{debug, info, instrument};
use crate::public::{
EntityProviderError, SimpleEntityProvider, UpdateProviderData, UpdateProviderDataError,
};
/// `ConfigBuilder` provides the data required to build the
/// `EntityProvider`. Favor the builder to use this object, see example.
///
/// # Examples
/// ```
/// use cedar_local_agent::public::file::entity_provider::ConfigBuilder;
///
/// let config = ConfigBuilder::default()
/// .entities_path("entities_path".to_string())
/// .schema_path("schema_path".to_string())
/// .build()
/// .unwrap();
/// ```
#[derive(Default, Builder, Debug)]
#[builder(setter(into))]
pub struct Config {
/// File path to the entities file
#[builder(setter(into, strip_option), default)]
pub entities_path: Option<String>,
/// File path to the schema file
#[builder(setter(into, strip_option), default)]
pub schema_path: Option<String>,
}
/// `EntityProvider` structure implements the `SimpleEntityProvider` trait.
#[derive(Debug)]
pub struct EntityProvider {
/// Entities path, stored to allow refreshing from disk.
entities_path: Option<String>,
/// Schema path, stored to allow refreshing from disk.
schema_path: Option<String>,
/// Entities can be updated through a back ground thread.
entities: RwLock<Arc<Entities>>,
}
/// `ProviderError` thrown by the constructor of the `EntityProvider`.
#[derive(Error, Debug)]
pub enum ProviderError {
/// Can't read from disk or find the file
#[error("IO Error: {0}")]
IOError(#[source] std::io::Error),
/// Schema file is malformed in some way
#[error("The Schema file failed to be parsed at path: {0}")]
SchemaParseError(String),
/// Entities file is malformed in some way
#[error("{0}")]
EntitiesError(String),
}
/// A wrapper that wraps `EntitiesError` to map the error message
struct EntitiesErrorWrapper {
// This is the path to the file to load entities
entity_file_path: String,
cause: EntitiesError,
}
/// A wrapper that wraps `SchemaParseError` to map the error message
struct SchemaParseErrorWrapper {
// This is the path to the file to load schema
schema_file_path: String,
}
/// Implements the constructor for the `EntitiesErrorWrapper`.
impl EntitiesErrorWrapper {
/// Creates a new wrapper of the `EntitiesError`
fn new(entity_file_path: String, cause: EntitiesError) -> Self {
Self {
// This is the path to the file to load entities.
entity_file_path,
cause,
}
}
}
/// Implements the constructor for the `SchemaParseErrorWrapper`.
impl SchemaParseErrorWrapper {
/// Creates a new wrapper of the `SchemaParseError`
fn new(schema_file_path: String) -> Self {
Self {
// This is the path to the file to load schema.
schema_file_path,
}
}
}
/// Map the `IOError` to the `ProvideError::IOError`
impl From<Error> for ProviderError {
fn from(value: Error) -> Self {
Self::IOError(value)
}
}
/// Map the `SchemaParseErrorWrapper` to the `ProvideError::SchemaParseError` with the file path
impl From<SchemaParseErrorWrapper> for ProviderError {
fn from(value: SchemaParseErrorWrapper) -> Self {
Self::SchemaParseError(value.schema_file_path)
}
}
fn create_entity_error_message(value: &EntitiesErrorWrapper) -> String {
format!(
"The Entities failed to be parsed at path: {}. Cause: {}",
value.entity_file_path, value.cause
)
}
/// Map the `EntitiesErrorWrapper` to the `ProvideError::EntitiesError` with the file path
impl From<EntitiesErrorWrapper> for ProviderError {
fn from(value: EntitiesErrorWrapper) -> Self {
Self::EntitiesError(create_entity_error_message(&value))
}
}
/// Implements the `EntityProvider`.
impl EntityProvider {
/// Builds a new `EntityProvider`.
///
/// # Examples
///
/// ```
/// use cedar_local_agent::public::file::entity_provider::{EntityProvider, ConfigBuilder};
///
/// let entity_provider = EntityProvider::new(
/// ConfigBuilder::default()
/// .schema_path("schema_path")
/// .entities_path("entities_path")
/// .build()
/// .unwrap()
/// );
/// ```
///
/// # Errors
///
/// This constructor will return a `EntityProvider` error if the applicable
/// entity or schema data is not a valid path or improperly formatted.
#[instrument(skip(configuration), err(Debug))]
pub fn new(configuration: Config) -> Result<Self, ProviderError> {
let entities = if let Some(entities_path) = configuration.entities_path.as_ref() {
let entities_file = File::open(entities_path)?;
let entities = if let Some(schema_path) = configuration.schema_path.as_ref() {
let schema_file = File::open(schema_path)?;
let schema = Schema::from_json_file(schema_file)
.map_err(|_schema_error| SchemaParseErrorWrapper::new(schema_path.clone()))?;
let res = Entities::from_json_file(entities_file, Some(&schema)).map_err(
|entities_error| {
EntitiesErrorWrapper::new(entities_path.clone(), entities_error)
},
)?;
debug!("Fetched Entities from file with Schema: entities_file_path={entities_path:?}: schema_file_path={schema_path:?}");
res
} else {
let res =
Entities::from_json_file(entities_file, None).map_err(|entities_error| {
EntitiesErrorWrapper::new(entities_path.clone(), entities_error)
})?;
debug!("Fetched Entities from file: entities_file_path={entities_path:?}");
res
};
entities
} else {
debug!("No Entity defined at local file system");
Entities::empty()
};
Ok(Self {
entities_path: configuration.entities_path,
schema_path: configuration.schema_path,
entities: RwLock::new(Arc::new(entities)),
})
}
}
/// Default Entity Provider that has no entities
impl Default for EntityProvider {
fn default() -> Self {
Self {
entities_path: None,
schema_path: None,
entities: RwLock::new(Arc::new(Entities::empty())),
}
}
}
/// Implements the update provider data trait
#[async_trait]
impl UpdateProviderData for EntityProvider {
#[instrument(skip(self), err(Debug))]
async fn update_provider_data(&self) -> Result<(), UpdateProviderDataError> {
let entities = if let Some(entities_path) = self.entities_path.as_ref() {
let entities_file = File::open(entities_path).map_err(|e| {
UpdateProviderDataError::General(Box::new(ProviderError::IOError(e)))
})?;
let entities = if let Some(schema_path) = self.schema_path.as_ref() {
let schema_file = File::open(schema_path).map_err(|e| {
UpdateProviderDataError::General(Box::new(ProviderError::IOError(e)))
})?;
let schema = Schema::from_json_file(schema_file).map_err(|_| {
UpdateProviderDataError::General(Box::new(ProviderError::SchemaParseError(
schema_path.to_string(),
)))
})?;
let res = Entities::from_json_file(entities_file, Some(&schema)).map_err(
|entities_error| {
UpdateProviderDataError::General(Box::new(ProviderError::from(
EntitiesErrorWrapper::new(entities_path.clone(), entities_error),
)))
},
)?;
debug!("Updated Entities from file with Schema: entities_file_path={entities_path:?}: schema_file_path={schema_path:?}");
res
} else {
let res =
Entities::from_json_file(entities_file, None).map_err(|entities_error| {
UpdateProviderDataError::General(Box::new(ProviderError::from(
EntitiesErrorWrapper::new(entities_path.clone(), entities_error),
)))
})?;
debug!("Updated Entities from file: entities_file_path={entities_path:?}");
res
};
entities
} else {
debug!("No Entity defined at local file system");
Entities::empty()
};
{
let mut entities_data = self.entities.write().await;
*entities_data = Arc::new(entities);
}
info!("Updated Entity Provider");
Ok(())
}
}
/// The `EntityProvider` returns all the `Entities` read from disk. The
/// cedar `Request` is unused for this use case.
#[async_trait]
impl SimpleEntityProvider for EntityProvider {
/// Get Entities.
#[instrument(skip_all, err(Debug))]
async fn get_entities(&self, _: &Request) -> Result<Arc<Entities>, EntityProviderError> {
Ok(self.entities.read().await.clone())
}
}
#[cfg(test)]
mod test {
use cedar_policy::{Context, Entities, Request};
use std::fs::File;
use std::io::ErrorKind;
use std::{fs, io};
use tempfile::NamedTempFile;
use crate::public::file::entity_provider::{
create_entity_error_message, ConfigBuilder, EntitiesErrorWrapper, EntityProvider,
ProviderError,
};
use crate::public::{SimpleEntityProvider, UpdateProviderData, UpdateProviderDataError};
#[test]
fn entity_provider_default_is_ok() {
assert!(EntityProvider::default().entities_path.is_none());
assert!(EntityProvider::default().schema_path.is_none());
}
#[test]
fn entity_provider_is_ok() {
assert!(EntityProvider::new(
ConfigBuilder::default()
.entities_path("tests/data/sweets.entities.json")
.schema_path("tests/data/sweets.schema.cedar.json")
.build()
.unwrap(),
)
.is_ok());
}
#[test]
fn entity_provider_is_ok_no_schema() {
assert!(EntityProvider::new(
ConfigBuilder::default()
.entities_path("tests/data/sweets.entities.json")
.build()
.unwrap(),
)
.is_ok());
}
#[test]
fn entity_provider_is_ok_no_input() {
assert!(EntityProvider::new(ConfigBuilder::default().build().unwrap(),).is_ok());
}
#[tokio::test]
async fn entity_provider_get_entities_ok_no_input() {
let provider = EntityProvider::new(ConfigBuilder::default().build().unwrap());
assert!(provider.is_ok());
assert!(provider
.unwrap()
.get_entities(
&Request::new(
r#"User::"Eric""#.parse().unwrap(),
r#"Action::"View""#.parse().unwrap(),
r#"Box::"10""#.parse().unwrap(),
Context::empty(),
None,
)
.unwrap()
)
.await
.is_ok());
}
#[test]
fn entity_provider_is_io_error_no_entities() {
let error = EntityProvider::new(
ConfigBuilder::default()
.entities_path("not_a_file")
.build()
.unwrap(),
);
assert!(error.is_err());
assert_eq!(
error.err().unwrap().to_string(),
"IO Error: No such file or directory (os error 2)"
);
}
#[test]
fn entity_provider_is_io_error_no_schema() {
let error = EntityProvider::new(
ConfigBuilder::default()
.entities_path("tests/data/sweets.entities.json")
.schema_path("not_a_file")
.build()
.unwrap(),
);
assert!(error.is_err());
assert_eq!(
error.err().unwrap().to_string(),
"IO Error: No such file or directory (os error 2)"
);
}
#[test]
fn entity_provider_malformed_schema() {
let error = EntityProvider::new(
ConfigBuilder::default()
.entities_path("tests/data/sweets.entities.json")
.schema_path("tests/data/schema_bad.cedarschema.json")
.build()
.unwrap(),
);
assert!(error.is_err());
assert_eq!(
error.err().unwrap().to_string(),
"The Schema file failed to be parsed at path: tests/data/schema_bad.cedarschema.json"
);
}
#[test]
fn entity_provider_malformed_entities() {
let entities_path = "tests/data/malformed_entities.json";
let entities_file = File::open(entities_path).unwrap();
let error = EntityProvider::new(
ConfigBuilder::default()
.entities_path(entities_path)
.build()
.unwrap(),
);
let cedar_error = Entities::from_json_file(entities_file, None);
assert!(error.is_err());
assert!(cedar_error.is_err());
assert_eq!(
error.err().unwrap().to_string(),
create_entity_error_message(&EntitiesErrorWrapper::new(
entities_path.into(),
cedar_error.unwrap_err()
))
);
}
#[tokio::test]
async fn entity_provider_update_is_ok() {
let provider = EntityProvider::new(
ConfigBuilder::default()
.entities_path("tests/data/sweets.entities.json")
.schema_path("tests/data/sweets.schema.cedar.json")
.build()
.unwrap(),
);
assert!(provider.is_ok());
assert!(provider.unwrap().update_provider_data().await.is_ok());
}
#[tokio::test]
async fn entity_provider_update_is_ok_no_schema() {
let provider = EntityProvider::new(
ConfigBuilder::default()
.entities_path("tests/data/sweets.entities.json")
.build()
.unwrap(),
);
assert!(provider.is_ok());
assert!(provider.unwrap().update_provider_data().await.is_ok());
}
#[tokio::test]
async fn entity_provider_update_is_ok_no_input() {
let provider = EntityProvider::new(ConfigBuilder::default().build().unwrap());
assert!(provider.is_ok());
assert!(provider.unwrap().update_provider_data().await.is_ok());
}
#[tokio::test]
async fn entity_provider_update_is_io_error() {
let temp_file = NamedTempFile::new().unwrap();
let temp_file_path = temp_file.path().to_str().unwrap().to_string();
fs::copy("tests/data/sweets.entities.json", temp_file_path.clone()).unwrap();
let provider = EntityProvider::new(
ConfigBuilder::default()
.entities_path(temp_file_path)
.build()
.unwrap(),
);
assert!(provider.is_ok());
let entity_provider = provider.unwrap();
temp_file.close().unwrap();
let actual = entity_provider.update_provider_data().await.unwrap_err();
let expect =
UpdateProviderDataError::General(Box::new(ProviderError::IOError(io::Error::new(
ErrorKind::NotFound,
"No such file or directory (os error 2)",
))));
assert_eq!(actual.to_string(), expect.to_string());
}
#[tokio::test]
async fn entity_provider_update_is_entity_error() {
let temp_entity = NamedTempFile::new().unwrap();
let temp_entity_path = temp_entity.path().to_str().unwrap().to_string();
fs::copy("tests/data/sweets.entities.json", temp_entity_path.clone()).unwrap();
let temp_schema = NamedTempFile::new().unwrap();
let temp_schema_path = temp_schema.path().to_str().unwrap().to_string();
fs::copy(
"tests/data/sweets.schema.cedar.json",
temp_schema_path.clone(),
)
.unwrap();
let provider = EntityProvider::new(
ConfigBuilder::default()
.entities_path(temp_entity_path.clone())
.schema_path(temp_schema_path.clone())
.build()
.unwrap(),
);
assert!(provider.is_ok());
let entity_provider = provider.unwrap();
fs::copy(
"tests/data/malformed_entities.json",
temp_entity_path.clone(),
)
.unwrap();
let update_result = entity_provider.update_provider_data().await;
assert!(update_result.is_err());
let update_provider_error = update_result.unwrap_err();
let UpdateProviderDataError::General(inner_error) = update_provider_error;
let inner_type = inner_error.downcast_ref::<ProviderError>().unwrap();
assert!(matches!(inner_type, ProviderError::EntitiesError(_)));
}
#[tokio::test]
async fn entity_provider_update_is_schema_error() {
let temp_entity = NamedTempFile::new().unwrap();
let temp_entity_path = temp_entity.path().to_str().unwrap().to_string();
fs::copy("tests/data/sweets.entities.json", temp_entity_path.clone()).unwrap();
let temp_schema = NamedTempFile::new().unwrap();
let temp_schema_path = temp_schema.path().to_str().unwrap().to_string();
fs::copy(
"tests/data/sweets.schema.cedar.json",
temp_schema_path.clone(),
)
.unwrap();
let provider = EntityProvider::new(
ConfigBuilder::default()
.entities_path(temp_entity_path.clone())
.schema_path(temp_schema_path.clone())
.build()
.unwrap(),
);
assert!(provider.is_ok());
let entity_provider = provider.unwrap();
fs::copy(
"tests/data/schema_bad.cedarschema.json",
temp_schema_path.clone(),
)
.unwrap();
let update_result = entity_provider.update_provider_data().await;
assert!(update_result.is_err());
let update_provider_error = update_result.unwrap_err();
let UpdateProviderDataError::General(inner_error) = update_provider_error;
let inner_type = inner_error.downcast_ref::<ProviderError>().unwrap();
assert!(matches!(inner_type, ProviderError::SchemaParseError(_)));
}
}