splinter 0.6.14

Splinter is a privacy-focused platform for distributed applications that provides a blockchain-inspired networking environment for communication and transactions between organizations.
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
// Copyright 2018-2022 Cargill Incorporated
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A file-backed authorization handler for defining admin keys

use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::SystemTime;

use crate::error::InternalError;
use crate::rest_api::auth::identity::Identity;

use super::{AuthorizationHandler, AuthorizationHandlerResult};

/// A file-backed authorization handler that permits admin keys
///
/// The authorization handler only accepts [`Identity::Key`] identities; if a different type of
/// identity is provided, the handler will return [`AuthorizationHandlerResult::Continue`]. If a key
/// is provided, the handler will check if the key is present in the backing file. If the key is in
/// the backing file, the handler will return [`AuthorizationHandlerResult::Allow`]; if not, it will
/// return [`AuthorizationHandlerResult::Continue`]. The `permission_id` argument for
/// [`AuthorizationHandler::has_permission`] is ignored because this authorization handler provides
/// admin privileges (all permissions).
///
/// The authorization handler's backing file must be a list of keys separated by newlines.
///
/// The list of keys in the file are cached in-memory by the authorization handler; this means that
/// the handler will not have to read from the file every time permissions are checked. Instead,
/// each time the handler checks for permissions, it will check the backing file for any changes
/// since the last read, refreshing the internal cache if necessary. If the backing file does not
/// exist, is removed, or becomes unavailable, the authorization handler will treat the list of keys
/// as empty (all permission checks will receive a [`AuthorizationHandlerResult::Continue`] result).
#[derive(Clone)]
pub struct AllowKeysAuthorizationHandler {
    internal: Arc<Mutex<Internal>>,
}

impl AllowKeysAuthorizationHandler {
    /// Constructs a new `AllowKeysAuthorizationHandler`.
    ///
    /// # Arguments
    ///
    /// * `file_path` - The path of the backing allow keys file.
    pub fn new(file_path: &str) -> Result<Self, InternalError> {
        Ok(Self {
            internal: Arc::new(Mutex::new(Internal::new(file_path)?)),
        })
    }
}

impl AuthorizationHandler for AllowKeysAuthorizationHandler {
    fn has_permission(
        &self,
        identity: &Identity,
        _permission_id: &str,
    ) -> Result<AuthorizationHandlerResult, InternalError> {
        match identity {
            Identity::Key(key)
                if self
                    .internal
                    .lock()
                    .map_err(|_| {
                        InternalError::with_message(
                            "allow keys authorization handler internal lock poisoned".into(),
                        )
                    })?
                    .get_keys()
                    .contains(key) =>
            {
                Ok(AuthorizationHandlerResult::Allow)
            }
            _ => Ok(AuthorizationHandlerResult::Continue),
        }
    }

    fn clone_box(&self) -> Box<dyn AuthorizationHandler> {
        Box::new(self.clone())
    }
}

/// Internal state of the authorization handler
struct Internal {
    file_path: String,
    cached_keys: Vec<String>,
    last_read: SystemTime,
}

impl Internal {
    fn new(file_path: &str) -> Result<Self, InternalError> {
        let mut internal = Self {
            file_path: file_path.into(),
            cached_keys: vec![],
            last_read: SystemTime::UNIX_EPOCH,
        };

        // Read the file if it exists; otherwise just set the read the time.
        if PathBuf::from(file_path).is_file() {
            internal.read_keys()?;
        } else {
            internal.last_read = SystemTime::now();
        }

        Ok(internal)
    }

    /// Gets the internal list of keys. If the backing file has been modified since the last read,
    /// attempts to refresh the cache. If the file is unavailable, clears the cache.
    fn get_keys(&mut self) -> &[String] {
        let file_read_result = std::fs::metadata(&self.file_path)
            .and_then(|metadata| metadata.modified())
            .map_err(|err| {
                InternalError::from_source_with_message(
                    Box::new(err),
                    "failed to read allow keys file's last modification time".into(),
                )
            })
            .and_then(|last_modified| {
                if last_modified > self.last_read {
                    self.read_keys()
                } else {
                    Ok(())
                }
            });

        // If an error occurred with checking or reading the backing file, treat the file as empty
        // (clear the cache)
        if let Err(err) = file_read_result {
            warn!("Failed to read from allow keys file: {}", err);
            self.cached_keys.clear();
        }

        &self.cached_keys
    }

    /// Reads the backing file and caches its contents, logging an error for any key that can't be
    /// read
    fn read_keys(&mut self) -> Result<(), InternalError> {
        let file = File::open(&self.file_path).map_err(|err| {
            InternalError::from_source_with_message(
                Box::new(err),
                "failed to open allow keys file".into(),
            )
        })?;
        let keys = BufReader::new(file)
            .lines()
            .enumerate()
            .filter_map(|(idx, res)| {
                match res {
                    Ok(line) => Some(line),
                    Err(err) => {
                        error!(
                            "Failed to read key from line {} of allow keys file: {}",
                            idx + 1, // Lines are 1-indexed, iterators are 0-indexed
                            err
                        );
                        None
                    }
                }
            })
            .collect();

        self.cached_keys = keys;
        self.last_read = SystemTime::now();

        Ok(())
    }
}

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

    use std::fs::remove_file;
    use std::io::Write;
    use std::thread::sleep;
    use std::time::Duration;

    use tempdir::TempDir;

    const KEY1: &str = "012345";
    const KEY2: &str = "abcdef";

    /// Verifies that the `AllowKeysAuthorizationHandler` returns `AuthorizationResult::Continue`
    /// when an unexpected identity (not a key) is passed in.
    ///
    /// 1. Create a new allow keys file in a temp directory
    /// 2. Create a new `AllowKeysAuthorizationHandler` backed by the file
    /// 3. Call `has_permission` with identities that aren't keys and verify the correct result is
    ///    returned
    #[test]
    fn auth_handler_unexpected_identity() {
        let temp_dir =
            TempDir::new("auth_handler_unexpected_identity").expect("Failed to create temp dir");
        let path = temp_dir
            .path()
            .join("allow_keys")
            .to_str()
            .expect("Failed to get path")
            .to_string();
        write_to_file(&[KEY1], &path);

        let handler = AllowKeysAuthorizationHandler::new(&path).expect("Failed to create handler");

        assert!(matches!(
            handler.has_permission(&Identity::Custom("identity".into()), "permission"),
            Ok(AuthorizationHandlerResult::Continue),
        ));
        #[cfg(any(feature = "biome-credentials", feature = "oauth"))]
        assert!(matches!(
            handler.has_permission(&Identity::User("user_id".into()), "permission"),
            Ok(AuthorizationHandlerResult::Continue),
        ));
    }

    /// Verifies that the `AllowKeysAuthorizationHandler` returns `AuthorizationResult::Continue`
    /// when an unknown key is passed in.
    ///
    /// 1. Create a new allow keys file in a temp directory
    /// 2. Create a new `AllowKeysAuthorizationHandler` backed by the file
    /// 3. Call `has_permission` with a key that isn't in the file and verify the correct result is
    ///    returned
    #[test]
    fn auth_handler_unknown_key() {
        let temp_dir = TempDir::new("auth_handler_unknown_key").expect("Failed to create temp dir");
        let path = temp_dir
            .path()
            .join("allow_keys")
            .to_str()
            .expect("Failed to get path")
            .to_string();
        write_to_file(&[KEY1], &path);

        let handler = AllowKeysAuthorizationHandler::new(&path).expect("Failed to create handler");

        assert!(matches!(
            handler.has_permission(&Identity::Key(KEY2.into()), "permission"),
            Ok(AuthorizationHandlerResult::Continue),
        ));
    }

    /// Verifies that the `AllowKeysAuthorizationHandler` returns `AuthorizationResult::Allow` when
    /// when a known key is passed in.
    ///
    /// 1. Create a new allow keys file in a temp directory
    /// 2. Create a new `AllowKeysAuthorizationHandler` backed by the file
    /// 3. Call `has_permission` with keys that are in the file and verify the correct results are
    ///    returned
    #[test]
    fn auth_handler_allow() {
        let temp_dir = TempDir::new("auth_handler_allow").expect("Failed to create temp dir");
        let path = temp_dir
            .path()
            .join("allow_keys")
            .to_str()
            .expect("Failed to get path")
            .to_string();
        write_to_file(&[KEY1, KEY2], &path);

        let handler = AllowKeysAuthorizationHandler::new(&path).expect("Failed to create handler");

        assert!(matches!(
            handler.has_permission(&Identity::Key(KEY1.into()), "permission"),
            Ok(AuthorizationHandlerResult::Allow),
        ));
        assert!(matches!(
            handler.has_permission(&Identity::Key(KEY2.into()), "permission"),
            Ok(AuthorizationHandlerResult::Allow),
        ));
    }

    /// Verifies that the `AllowKeysAuthorizationHandler` reloads the keys from the backing file if
    /// it was modified since the last read.
    ///
    /// 1. Create a new, empty allow keys file in a temp directory
    /// 2. Create a new `AllowKeysAuthorizationHandler` backed by the file
    /// 3. Write some keys to the file
    /// 4. Call `has_permission` with the keys that were written to the file and verify the correct
    ///    results are returned
    /// 5. Remove a key from the file (overwrite the file without the key)
    /// 6. Call `has_permission` with the key that was removed and verify the correct result is
    ///    returned
    #[test]
    fn reload_modified_file() {
        let temp_dir = TempDir::new("reload_modified_file").expect("Failed to create temp dir");
        let path = temp_dir
            .path()
            .join("allow_keys")
            .to_str()
            .expect("Failed to get path")
            .to_string();
        write_to_file(&[], &path);

        let handler = AllowKeysAuthorizationHandler::new(&path).expect("Failed to create handler");

        // Allow some time before writing the file to make sure the read time is earlier than the
        // write time; the sytem clock may not be very precise.
        sleep(Duration::from_secs(1));

        write_to_file(&[KEY1, KEY2], &path);

        assert!(matches!(
            handler.has_permission(&Identity::Key(KEY1.into()), "permission"),
            Ok(AuthorizationHandlerResult::Allow),
        ));
        assert!(matches!(
            handler.has_permission(&Identity::Key(KEY2.into()), "permission"),
            Ok(AuthorizationHandlerResult::Allow),
        ));

        // Allow some time before writing the file to make sure the read time is earlier than the
        // write time; the sytem clock may not be very precise.
        sleep(Duration::from_secs(1));

        write_to_file(&[KEY1], &path);

        assert!(matches!(
            handler.has_permission(&Identity::Key(KEY2.into()), "permission"),
            Ok(AuthorizationHandlerResult::Continue),
        ));
    }

    /// Verifies that the `AllowKeysAuthorizationHandler` treats the list of keys as empty if the
    /// backing file is removed.
    ///
    /// 1. Create a new allow keys file in a temp directory
    /// 2. Create a new `AllowKeysAuthorizationHandler` backed by the file
    /// 3. Remove the backing file
    /// 4. Call `has_permission` with a key that was in the file and verify that `Continue` is
    ///    returned
    #[test]
    fn file_removed() {
        let temp_dir = TempDir::new("file_removed").expect("Failed to create temp dir");
        let path = temp_dir
            .path()
            .join("allow_keys")
            .to_str()
            .expect("Failed to get path")
            .to_string();
        write_to_file(&[KEY1], &path);

        let handler = AllowKeysAuthorizationHandler::new(&path).expect("Failed to create handler");

        remove_file(&path).expect("Failed to remove file");
        assert!(!PathBuf::from(&path).exists());

        assert!(matches!(
            handler.has_permission(&Identity::Key(KEY1.into()), "permission"),
            Ok(AuthorizationHandlerResult::Continue),
        ));
    }

    fn write_to_file(keys: &[&str], file_path: &str) {
        let mut file = File::create(file_path).expect("Failed to create allow keys file");
        for key in keys {
            writeln!(file, "{}", key).expect("Failed to write key to file");
        }
    }

    /// Verifies that the `AllowKeysAuthorizationHandler` is able to start without an existing file
    /// and load the file once it's created.
    ///
    /// 1. Create a new temp directory
    /// 2. Create a new `AllowKeysAuthorizationHandler` backed by a non-existent file in the temp
    ///    directory
    /// 3. Verify that `has_permission` returns `Continue`
    /// 3. Create the backing file with a key
    /// 4. Call `has_permission` with the key in the file and verify that `Allow` is returned
    #[test]
    fn load_after_file_created() {
        let temp_dir = TempDir::new("load_after_file_created").expect("Failed to create temp dir");
        let path = temp_dir
            .path()
            .join("allow_keys")
            .to_str()
            .expect("Failed to get path")
            .to_string();

        let handler = AllowKeysAuthorizationHandler::new(&path).expect("Failed to create handler");

        assert!(matches!(
            handler.has_permission(&Identity::Key(KEY1.into()), "permission"),
            Ok(AuthorizationHandlerResult::Continue),
        ));

        // Allow some time before writing the file to make sure the last read time is earlier than
        // the write time; the sytem clock may not be very precise.
        sleep(Duration::from_secs(1));

        write_to_file(&[KEY1], &path);

        assert!(matches!(
            handler.has_permission(&Identity::Key(KEY1.into()), "permission"),
            Ok(AuthorizationHandlerResult::Allow),
        ));
    }
}