1use std::fmt;
4use zeroize::Zeroize;
5
6const SERVICE: &str = "Toolblox";
8
9pub(crate) const SESSION_COOKIE_MARKER: &str = "_|warning:";
11
12pub(crate) fn contains_session_cookie(text: &str) -> bool {
14 text.to_ascii_lowercase().contains(SESSION_COOKIE_MARKER)
15}
16
17pub struct Secret(String);
19
20impl Secret {
21 pub(crate) fn new(value: String) -> Self {
23 Self(value)
24 }
25
26 pub(crate) fn expose(&self) -> &str {
28 &self.0
29 }
30}
31
32impl fmt::Debug for Secret {
33 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
34 formatter.write_str("Secret([redacted])")
35 }
36}
37
38impl Drop for Secret {
39 fn drop(&mut self) {
40 self.0.zeroize();
41 }
42}
43
44#[derive(Debug)]
46pub enum CredentialError {
47 Missing,
49 #[cfg(not(any(windows, target_os = "macos")))]
51 Unsupported,
52 Platform,
54}
55
56impl fmt::Display for CredentialError {
57 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
58 match self {
59 Self::Missing => write!(
60 formatter,
61 "The saved session wasn't found. Can you sign in again?"
62 ),
63 #[cfg(not(any(windows, target_os = "macos")))]
64 Self::Unsupported => write!(
65 formatter,
66 "Secure session storage isn't supported on this platform. Is this device running Windows or macOS?"
67 ),
68 Self::Platform => write!(
69 formatter,
70 "Toolblox couldn't access secure session storage. Is the credential store unlocked?"
71 ),
72 }
73 }
74}
75
76impl std::error::Error for CredentialError {}
77
78pub trait CredentialStore: Send + Sync {
80 fn get(&self, account_id: u64) -> Result<Secret, CredentialError>;
82 fn set(&self, account_id: u64, secret: &str) -> Result<(), CredentialError>;
84 fn delete(&self, account_id: u64) -> Result<(), CredentialError>;
86}
87
88#[derive(Debug, Default)]
90pub struct OsCredentialStore;
91
92impl OsCredentialStore {
93 #[cfg(any(windows, target_os = "macos"))]
95 fn entry(account_id: u64) -> Result<keyring::Entry, CredentialError> {
96 keyring::Entry::new(SERVICE, &format!("account-{account_id}"))
97 .map_err(|_| CredentialError::Platform)
98 }
99}
100
101#[cfg(any(windows, target_os = "macos"))]
102impl CredentialStore for OsCredentialStore {
103 fn get(&self, account_id: u64) -> Result<Secret, CredentialError> {
104 Self::entry(account_id)?
105 .get_password()
106 .map(Secret)
107 .map_err(|error| match error {
108 keyring::Error::NoEntry => CredentialError::Missing,
109 _ => CredentialError::Platform,
110 })
111 }
112
113 fn set(&self, account_id: u64, secret: &str) -> Result<(), CredentialError> {
114 if secret.is_empty() {
115 return Err(CredentialError::Missing);
116 }
117 Self::entry(account_id)?
118 .set_password(secret)
119 .map_err(|_| CredentialError::Platform)
120 }
121
122 fn delete(&self, account_id: u64) -> Result<(), CredentialError> {
123 match Self::entry(account_id)?.delete_credential() {
124 Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
125 Err(_) => Err(CredentialError::Platform),
126 }
127 }
128}
129
130#[cfg(not(any(windows, target_os = "macos")))]
131impl CredentialStore for OsCredentialStore {
132 fn get(&self, _account_id: u64) -> Result<Secret, CredentialError> {
133 Err(CredentialError::Unsupported)
134 }
135
136 fn set(&self, _account_id: u64, _secret: &str) -> Result<(), CredentialError> {
137 Err(CredentialError::Unsupported)
138 }
139
140 fn delete(&self, _account_id: u64) -> Result<(), CredentialError> {
141 Err(CredentialError::Unsupported)
142 }
143}
144
145#[cfg(test)]
147macro_rules! assert_not_impl {
148 ($type:ty: $($trait:path),+ $(,)?) => {$(
149 const _: fn() = || {
150 trait AmbiguousIfImplemented<Marker> {
151 fn check() {}
152 }
153 impl<T: ?Sized> AmbiguousIfImplemented<()> for T {}
154 struct Implemented;
155 impl<T: ?Sized + $trait> AmbiguousIfImplemented<Implemented> for T {}
156 let _ = <$type as AmbiguousIfImplemented<_>>::check;
157 };
158 )+};
159}
160#[cfg(test)]
161pub(crate) use assert_not_impl;
162
163#[cfg(test)]
164pub(crate) mod tests {
165 use std::path::Path;
166
167 use super::*;
168
169 assert_not_impl!(Secret: Clone, std::fmt::Display, serde::Serialize);
170
171 const SECRET_ACCESS: &[(&str, &[(&str, usize)])] = &[
175 (
176 ".expose()",
177 &[("app_commands.rs", 1), ("login.rs", 1), ("roblox.rs", 1)],
178 ),
179 (".set_cookie(", &[("login.rs", 1)]),
180 (".expose_secret()", &[("app_commands.rs", 2)]),
181 ("cookie_header(", &[("roblox.rs", 5)]),
182 ("keyring::", &[("credentials.rs", 4)]),
183 ("get_password", &[("credentials.rs", 1)]),
184 (".cookies()", &[("login.rs", 1)]),
185 ("find-generic-password", &[]),
186 ("CryptUnprotectData", &[]),
187 ];
188
189 pub(crate) fn production_source(source: &str) -> String {
191 let source = source.replace("\r\n", "\n");
192 let end = ["#[cfg(test)]\nmod ", "#[cfg(test)]\npub(crate) mod "]
193 .iter()
194 .filter_map(|marker| source.find(marker))
195 .min()
196 .unwrap_or(source.len());
197 source[..end]
198 .lines()
199 .filter(|line| !line.trim_start().starts_with("//"))
200 .collect::<Vec<_>>()
201 .join("\n")
202 }
203
204 #[test]
205 fn production_source_excludes_tests_with_either_line_ending() {
206 for visibility in ["", "pub(crate) "] {
207 let source = format!(
208 "// Comment\nfn production() {{}}\n#[cfg(test)]\n{visibility}mod tests {{}}\n"
209 );
210 let expected = "fn production() {}";
211 assert_eq!(production_source(&source), expected);
212 assert_eq!(production_source(&source.replace('\n', "\r\n")), expected);
213 }
214 }
215
216 #[test]
217 fn secret_access_points_match_the_reviewed_list() {
218 let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
219 let mut files: Vec<_> = std::fs::read_dir(&directory)
220 .unwrap()
221 .map(|entry| entry.unwrap().path())
222 .filter(|path| path.extension().is_some_and(|extension| extension == "rs"))
223 .collect();
224 files.sort();
225 assert!(!files.is_empty());
226 let mut problems = Vec::new();
227 for (pattern, allowed) in SECRET_ACCESS {
228 for path in &files {
229 let name = path.file_name().unwrap().to_str().unwrap();
230 let source = std::fs::read_to_string(path).unwrap();
231 let found = production_source(&source).matches(pattern).count();
232 let expected = allowed
233 .iter()
234 .find(|(file, _)| *file == name)
235 .map_or(0, |(_, count)| *count);
236 if found != expected {
237 problems.push(format!(
238 "{name} uses `{pattern}` {found} times; the reviewed count is {expected}"
239 ));
240 }
241 }
242 }
243 assert!(
244 problems.is_empty(),
245 "Session secret access changed. Review that the secret can't reach JavaScript, a \
246 widget, a log, or a non-Roblox host, then update SECRET_ACCESS.\n{}",
247 problems.join("\n")
248 );
249 }
250
251 #[test]
252 fn session_cookies_are_detected_in_any_case() {
253 assert!(contains_session_cookie(
254 r#"{"value":"_|WARNING:-DO-NOT-SHARE-THIS.--Sharing|_ABC"}"#
255 ));
256 assert!(contains_session_cookie("_|warning:-do-not-share-this"));
257 assert!(!contains_session_cookie(
258 r#"{"name":".ROBLOSECURITY docs"}"#
259 ));
260 }
261}