From 3944d3564eca3dc132fe0caee62b4a1087a5b9ec Mon Sep 17 00:00:00 2001
From: Dominik George <dominik.george@teckids.org>
Date: Sun, 9 May 2021 01:10:18 +0200
Subject: [PATCH] [Cache] Fix access to static global CACHE

---
 src/cache.rs | 15 ++++++++++-----
 src/pam.rs   |  4 ++--
 2 files changed, 12 insertions(+), 7 deletions(-)

diff --git a/src/cache.rs b/src/cache.rs
index 752fc45..b12bc6c 100644
--- a/src/cache.rs
+++ b/src/cache.rs
@@ -17,6 +17,7 @@ use crate::BASE_NAME;
 
 use lazy_static::lazy_static;
 use std::collections::HashMap;
+use std::sync::{Mutex, MutexGuard};
 
 use libc::{geteuid, seteuid, getpwnam, uid_t};
 use std::ffi::CString;
@@ -33,10 +34,9 @@ use serde::Serialize;
 use serde::de::DeserializeOwned;
 use serde_json;
 
-const TOKEN_DEFAULT_EXPIRES: u64 = 24 * 60 * 60;
 const USER_TOKEN_FILENAME: &str = "user_token.json";
 
-struct Cache {
+pub struct Cache {
     user_tokens: HashMap<String, BasicTokenResponse>,
     original_euid: uid_t,
 }
@@ -194,9 +194,10 @@ impl Cache {
         match self.place_user_cache_file(owner, USER_TOKEN_FILENAME.to_string()) {
             Ok(path) => {
                 debug!("Deleting cache file for {}", owner);
-                fs::remove_file(path)
+                fs::remove_file(path).ok();
+                ()
             },
-            Err(e) => Err(e)
+            Err(e) => ()
         };
         self.restore_privileges();
     }
@@ -221,5 +222,9 @@ fn save_json<O: Serialize>(path: PathBuf, obj: O) -> Result<(), io::Error> {
 }
 
 lazy_static! {
-    pub static ref CACHE: Cache = Cache::new();
+    static ref CACHE: Mutex<Cache> = Mutex::new(Cache::new());
+}
+
+pub fn get_cache() -> MutexGuard<'static, Cache> {
+    CACHE.lock().unwrap()
 }
diff --git a/src/pam.rs b/src/pam.rs
index 32e44e5..461d71c 100644
--- a/src/pam.rs
+++ b/src/pam.rs
@@ -24,7 +24,7 @@ use crate::oauth::get_access_token_password;
 
 use crate::logging::setup_log;
 
-use crate::cache::CACHE;
+use crate::cache::get_cache;
 
 use pamsm::{PamServiceModule, Pam, PamFlag, PamError, PamLibExt};
 
@@ -90,7 +90,7 @@ impl PamServiceModule for PamOidc {
             match get_access_token_password(conf, "pam", username.to_string(), password.to_string(), PamError::SERVICE_ERR, PamError::AUTH_ERR) {
                 Ok(t) => {
                     info!("Authenticated {} using Resource Owner Password Grant", username);
-                    CACHE.save_user_token(&username.to_string(), t.into());
+                    get_cache().save_user_token(&username.to_string(), t.into());
                     return PamError::SUCCESS;
                 },
                 Err(e) => {
-- 
GitLab