1use rusqlite::params;
11
12use crate::backend::storage::error::StoreError;
13use crate::backend::storage::store::Store;
14
15const OWNER: &str = "owner";
16const GRANTED: &str = "granted";
17
18#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
20#[ts(export, export_to = "../../../frontend/types/rpc/")]
21pub struct DroneAccess {
22 pub owner: String,
24 pub agents: Vec<String>,
26}
27
28impl DroneAccess {
29 pub fn allows(&self, agent: &str) -> bool {
31 let agent = key(agent);
32 !agent.is_empty() && (self.owner == agent || self.agents.iter().any(|a| *a == agent))
33 }
34}
35
36pub fn key(agent: &str) -> String {
38 agent.trim().to_ascii_lowercase()
39}
40
41pub trait DroneAccessStore {
42 fn access_get(&self, drone_id: &str) -> Result<DroneAccess, StoreError>;
44 fn access_set_owner(&self, drone_id: &str, agent: &str, now_ms: i64) -> Result<(), StoreError>;
46 fn access_set_agents(&self, drone_id: &str, agents: &[String], by: &str, now_ms: i64) -> Result<(), StoreError>;
48 fn access_delete_for(&self, drone_id: &str) -> Result<usize, StoreError>;
50}
51
52impl DroneAccessStore for Store {
53 fn access_get(&self, drone_id: &str) -> Result<DroneAccess, StoreError> {
54 let conn = self.conn().lock().unwrap();
55 let mut stmt = conn.prepare("SELECT agent, kind FROM db_drone_access WHERE drone_id = ?1 ORDER BY agent")?;
56 let mut rows = stmt.query(params![drone_id])?;
57 let mut access = DroneAccess::default();
58 while let Some(row) = rows.next()? {
59 let (agent, kind): (String, String) = (row.get(0)?, row.get(1)?);
60 match kind.as_str() {
61 OWNER => access.owner = agent,
62 GRANTED => access.agents.push(agent),
63 _ => {}
64 }
65 }
66 Ok(access)
67 }
68
69 fn access_set_owner(&self, drone_id: &str, agent: &str, now_ms: i64) -> Result<(), StoreError> {
70 let agent = key(agent);
71 if agent.is_empty() {
72 return Ok(());
73 }
74 let conn = self.conn().lock().unwrap();
75 conn.execute(
76 "INSERT INTO db_drone_access (drone_id, agent, kind, set_at, set_by)
77 SELECT ?1, ?2, ?3, ?4, ?2
78 WHERE NOT EXISTS (SELECT 1 FROM db_drone_access WHERE drone_id = ?1 AND kind = ?3)",
79 params![drone_id, agent, OWNER, now_ms],
80 )?;
81 Ok(())
82 }
83
84 fn access_set_agents(&self, drone_id: &str, agents: &[String], by: &str, now_ms: i64) -> Result<(), StoreError> {
85 let mut conn = self.conn().lock().unwrap();
86 let tx = conn.transaction()?;
87 tx.execute("DELETE FROM db_drone_access WHERE drone_id = ?1 AND kind = ?2", params![drone_id, GRANTED])?;
88 for agent in agents.iter().map(|a| key(a)).filter(|a| !a.is_empty()) {
89 tx.execute(
90 "INSERT OR IGNORE INTO db_drone_access (drone_id, agent, kind, set_at, set_by) VALUES (?1, ?2, ?3, ?4, ?5)",
91 params![drone_id, agent, GRANTED, now_ms, by],
92 )?;
93 }
94 tx.commit()?;
95 Ok(())
96 }
97
98 fn access_delete_for(&self, drone_id: &str) -> Result<usize, StoreError> {
99 let conn = self.conn().lock().unwrap();
100 Ok(conn.execute("DELETE FROM db_drone_access WHERE drone_id = ?1", params![drone_id])?)
101 }
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107
108 fn store() -> std::sync::Arc<Store> {
109 crate::server::tests::test_state().id_store.clone()
110 }
111
112 #[tokio::test]
113 async fn a_drone_nobody_made_has_no_owner_and_allows_no_agent() {
114 let access = store().access_get("d-none").unwrap();
115 assert_eq!(access, DroneAccess::default());
116 assert!(!access.allows("opaz"));
117 assert!(!access.allows(""), "an empty name is no one");
118 }
119
120 #[tokio::test]
121 async fn the_first_owner_stays_and_a_name_is_one_whatever_its_case() {
122 let s = store();
123 s.access_set_owner("d1", "Opaz", 1).unwrap();
124 s.access_set_owner("d1", "korp", 2).unwrap();
125 let access = s.access_get("d1").unwrap();
126 assert_eq!(access.owner, "opaz", "the owner is the first one and is kept in lower case");
127 assert!(access.allows("OPAZ"));
128 assert!(!access.allows("korp"));
129 }
130
131 #[tokio::test]
132 async fn given_agents_are_replaced_whole_and_do_not_touch_the_owner() {
133 let s = store();
134 s.access_set_owner("d2", "opaz", 1).unwrap();
135 s.access_set_agents("d2", &["Korp".to_string(), "korp".to_string(), " ".to_string()], "operator", 2).unwrap();
136 assert_eq!(s.access_get("d2").unwrap().agents, ["korp"]);
137 s.access_set_agents("d2", &["clamk".to_string()], "agent:opaz", 3).unwrap();
138 let access = s.access_get("d2").unwrap();
139 assert_eq!((access.owner.as_str(), access.agents), ("opaz", vec!["clamk".to_string()]));
140 }
141
142 #[tokio::test]
143 async fn deleting_a_drone_forgets_who_had_it() {
144 let s = store();
145 s.access_set_owner("d3", "opaz", 1).unwrap();
146 s.access_set_agents("d3", &["korp".to_string()], "operator", 2).unwrap();
147 assert_eq!(s.access_delete_for("d3").unwrap(), 2);
148 assert_eq!(s.access_get("d3").unwrap(), DroneAccess::default());
149 }
150}