1use std::borrow::Cow;
9use std::fmt;
10use std::sync::Arc;
11
12use coqui_access::guatiao::library::ProviderError;
13use coqui_access::guatiao::{FromValue, Schema, ToValue};
14use coqui_access::{Claims, Person};
15
16use crate::table::{Keyed, Reloading, SourceError, Table};
17
18pub mod authorized;
19pub use authorized::{
20 AuthorizedFile, DirectReader, FileRead, PinFileReader, ReadFailure, TemplateError,
21};
22
23#[derive(Debug, Clone, Default, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct PinSet {
28 pub fingerprint: Option<String>,
30 pub key: Option<String>,
32}
33
34impl PinSet {
35 pub fn from_claims(claims: &Claims) -> Self {
37 let pick = |name: &str| {
38 claims
39 .get(name)
40 .first()
41 .map(|value| value.to_ascii_lowercase())
42 };
43 Self {
44 fingerprint: pick("fingerprint"),
45 key: pick("spki"),
46 }
47 }
48
49 pub fn is_empty(&self) -> bool {
51 self.fingerprint.is_none() && self.key.is_none()
52 }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57#[non_exhaustive]
58pub enum PinCheck {
59 Holds,
61 Absent,
63 Refused(String),
67}
68
69pub trait PinSource: Send + Sync {
76 fn check(&self, person: &Person, pins: &PinSet) -> Result<PinCheck, ProviderError>;
78}
79
80pub fn pin_matches(text: &str, wanted: &PinSet) -> Option<bool> {
85 let valid = |hex: &str| hex.len() == 64 && hex.bytes().all(|byte| byte.is_ascii_hexdigit());
86 if let Some(hex) = text.strip_prefix("sha256:") {
87 return valid(hex).then(|| {
88 wanted.fingerprint.as_deref() == Some(&format!("sha256:{}", hex.to_ascii_lowercase()))
89 });
90 }
91 let hex = text.strip_prefix("spki-sha256:")?;
92 valid(hex)
93 .then(|| wanted.key.as_deref() == Some(&format!("sha256:{}", hex.to_ascii_lowercase())))
94}
95
96#[derive(Clone, PartialEq, Eq, FromValue, Schema, ToValue)]
98#[map(crate = ::coqui_access::guatiao, deny_unknown_fields)]
99#[non_exhaustive]
100pub struct AccountPin {
101 pub name: String,
103 pub pin: String,
105}
106
107impl AccountPin {
108 pub fn new(name: impl Into<String>, pin: impl Into<String>) -> Self {
110 Self {
111 name: name.into(),
112 pin: pin.into(),
113 }
114 }
115}
116
117impl Keyed for AccountPin {
118 fn key(&self) -> Cow<'_, str> {
119 Cow::Owned(format!(
120 "{}
121{}",
122 self.name,
123 self.pin.to_ascii_lowercase()
124 ))
125 }
126}
127
128impl fmt::Debug for AccountPin {
129 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
130 formatter
131 .debug_struct("AccountPin")
132 .field("name", &"[REDACTED]")
133 .field("pin", &"[REDACTED]")
134 .finish()
135 }
136}
137
138pub struct TablePins {
141 pins: Reloading<AccountPin>,
142}
143
144impl fmt::Debug for TablePins {
145 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
146 formatter.debug_struct("TablePins").finish_non_exhaustive()
147 }
148}
149
150impl TablePins {
151 pub fn new(table: Arc<dyn Table<AccountPin>>) -> Result<Self, SourceError> {
157 let wanted = PinSet::default();
158 Ok(Self {
159 pins: Reloading::new(table, move |records| {
160 if records
161 .iter()
162 .any(|record| pin_matches(&record.pin, &wanted).is_none())
163 {
164 return Err(SourceError::invalid("a pin in the table is not a pin"));
165 }
166 Ok(())
167 })?,
168 })
169 }
170}
171
172impl PinSource for TablePins {
173 fn check(&self, person: &Person, pins: &PinSet) -> Result<PinCheck, ProviderError> {
174 let held = self
175 .pins
176 .read(|records| {
177 records.iter().any(|record| {
178 record.name == person.name && pin_matches(&record.pin, pins) == Some(true)
179 })
180 })
181 .map_err(|reason| reason.reading("pin table"))?;
182 Ok(if held {
183 PinCheck::Holds
184 } else {
185 PinCheck::Absent
186 })
187 }
188}