1#![doc = include_str!("../examples/file-provider.rs")]
41#![allow(clippy::print_stderr)]
44#![allow(clippy::print_stdout)]
45
46use jiff::Timestamp;
47use serde::{Deserialize, Serialize};
48use std::{fmt::Display, io};
49
50mod error;
51mod secret;
52mod stdio;
53
54pub use error::Error;
55pub use secret::Secret;
56use stdio::stdin_stdout_to_console;
57
58#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
60pub struct CredentialHello {
61 pub v: Vec<u32>,
63}
64
65pub struct UnsupportedCredential;
67impl Credential for UnsupportedCredential {
68 fn perform(
69 &self,
70 _registry: &RegistryInfo<'_>,
71 _action: &Action<'_>,
72 _args: &[&str],
73 ) -> Result<CredentialResponse, Error> {
74 Err(Error::UrlNotSupported)
75 }
76}
77
78#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
80#[serde(rename_all = "kebab-case")]
81pub struct CredentialRequest<'a> {
82 pub v: u32,
84 #[serde(borrow)]
85 pub registry: RegistryInfo<'a>,
86 #[serde(borrow, flatten)]
87 pub action: Action<'a>,
88 #[serde(skip_serializing_if = "Vec::is_empty", default)]
90 pub args: Vec<&'a str>,
91}
92
93#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
94#[serde(rename_all = "kebab-case")]
95pub struct RegistryInfo<'a> {
96 pub index_url: &'a str,
98 #[serde(skip_serializing_if = "Option::is_none")]
101 pub name: Option<&'a str>,
102 #[serde(skip_serializing_if = "Vec::is_empty", default)]
104 pub headers: Vec<String>,
105}
106
107#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
108#[non_exhaustive]
109#[serde(tag = "kind", rename_all = "kebab-case")]
110pub enum Action<'a> {
111 #[serde(borrow)]
112 Get(Operation<'a>),
113 Login(LoginOptions<'a>),
114 Logout,
115 #[serde(other)]
116 Unknown,
117}
118
119impl<'a> Display for Action<'a> {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 match self {
122 Action::Get(_) => f.write_str("get"),
123 Action::Login(_) => f.write_str("login"),
124 Action::Logout => f.write_str("logout"),
125 Action::Unknown => f.write_str("<unknown>"),
126 }
127 }
128}
129
130#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
131#[serde(rename_all = "kebab-case")]
132pub struct LoginOptions<'a> {
133 #[serde(skip_serializing_if = "Option::is_none")]
135 pub token: Option<Secret<&'a str>>,
136 #[serde(skip_serializing_if = "Option::is_none")]
138 pub login_url: Option<&'a str>,
139}
140
141#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
143#[non_exhaustive]
144#[serde(tag = "operation", rename_all = "kebab-case")]
145pub enum Operation<'a> {
146 Read,
148 Publish {
150 name: &'a str,
152 vers: &'a str,
154 cksum: &'a str,
156 },
157 Yank {
159 name: &'a str,
161 vers: &'a str,
163 },
164 Unyank {
166 name: &'a str,
168 vers: &'a str,
170 },
171 Owners {
173 name: &'a str,
175 },
176 #[serde(other)]
177 Unknown,
178}
179
180#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
182#[serde(tag = "kind", rename_all = "kebab-case")]
183#[non_exhaustive]
184pub enum CredentialResponse {
185 Get {
186 token: Secret<String>,
187 #[serde(flatten)]
188 cache: CacheControl,
189 operation_independent: bool,
190 },
191 Login,
192 Logout,
193 #[serde(other)]
194 Unknown,
195}
196
197#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
198#[serde(tag = "cache", rename_all = "kebab-case")]
199#[non_exhaustive]
200pub enum CacheControl {
201 Never,
203 Expires {
205 #[serde(with = "jiff::fmt::serde::timestamp::second::required")]
207 expiration: Timestamp,
208 },
209 Session,
211 #[serde(other)]
212 Unknown,
213}
214
215pub const PROTOCOL_VERSION_1: u32 = 1;
223pub trait Credential {
224 fn perform(
226 &self,
227 registry: &RegistryInfo<'_>,
228 action: &Action<'_>,
229 args: &[&str],
230 ) -> Result<CredentialResponse, Error>;
231}
232
233pub fn main(credential: impl Credential) {
235 let result = doit(credential).map_err(|e| Error::Other(e));
236 if result.is_err() {
237 serde_json::to_writer(std::io::stdout(), &result)
238 .expect("failed to serialize credential provider error");
239 println!();
240 }
241}
242
243fn doit(
244 credential: impl Credential,
245) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
246 let hello = CredentialHello {
247 v: vec![PROTOCOL_VERSION_1],
248 };
249 serde_json::to_writer(std::io::stdout(), &hello)?;
250 println!();
251
252 loop {
253 let mut buffer = String::new();
254 let len = std::io::stdin().read_line(&mut buffer)?;
255 if len == 0 {
256 return Ok(());
257 }
258 let request = deserialize_request(&buffer)?;
259 let response = stdin_stdout_to_console(|| {
260 credential.perform(&request.registry, &request.action, &request.args)
261 })?;
262
263 serde_json::to_writer(std::io::stdout(), &response)?;
264 println!();
265 }
266}
267
268fn deserialize_request(
270 value: &str,
271) -> Result<CredentialRequest<'_>, Box<dyn std::error::Error + Send + Sync>> {
272 let request: CredentialRequest<'_> = serde_json::from_str(&value)?;
273 if request.v != PROTOCOL_VERSION_1 {
274 return Err(format!("unsupported protocol version {}", request.v).into());
275 }
276 Ok(request)
277}
278
279pub fn read_line() -> Result<String, io::Error> {
281 let mut buf = String::new();
282 io::stdin().read_line(&mut buf)?;
283 Ok(buf.trim().to_string())
284}
285
286pub fn read_token(
288 login_options: &LoginOptions<'_>,
289 registry: &RegistryInfo<'_>,
290) -> Result<Secret<String>, Error> {
291 if let Some(token) = &login_options.token {
292 return Ok(token.to_owned());
293 }
294
295 if let Some(url) = login_options.login_url {
296 eprintln!("please paste the token found on {url} below");
297 } else if let Some(name) = registry.name {
298 eprintln!("please paste the token for {name} below");
299 } else {
300 eprintln!("please paste the token for {} below", registry.index_url);
301 }
302
303 Ok(Secret::from(read_line().map_err(Box::new)?))
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309
310 #[test]
311 fn unsupported_version() {
312 let msg = r#"{"v":999, "registry": {"index-url":""}, "args":[], "kind": "unexpected"}"#;
315 assert_eq!(
316 "unsupported protocol version 999",
317 deserialize_request(msg).unwrap_err().to_string()
318 );
319 }
320
321 #[test]
322 fn cache_control() {
323 let cc = CacheControl::Expires {
324 expiration: Timestamp::from_second(1693928537).unwrap(),
325 };
326 let json = serde_json::to_string(&cc).unwrap();
327 assert_eq!(json, r#"{"cache":"expires","expiration":1693928537}"#);
328
329 let cc = CacheControl::Session;
330 let json = serde_json::to_string(&cc).unwrap();
331 assert_eq!(json, r#"{"cache":"session"}"#);
332
333 let cc: CacheControl = serde_json::from_str(r#"{"cache":"unknown-kind"}"#).unwrap();
334 assert_eq!(cc, CacheControl::Unknown);
335
336 assert_eq!(
337 "missing field `expiration`",
338 serde_json::from_str::<CacheControl>(r#"{"cache":"expires"}"#)
339 .unwrap_err()
340 .to_string()
341 );
342 }
343
344 #[test]
345 fn credential_response() {
346 let cr = CredentialResponse::Get {
347 cache: CacheControl::Never,
348 operation_independent: true,
349 token: Secret::from("value".to_string()),
350 };
351 let json = serde_json::to_string(&cr).unwrap();
352 assert_eq!(
353 json,
354 r#"{"kind":"get","token":"value","cache":"never","operation_independent":true}"#
355 );
356
357 let cr = CredentialResponse::Login;
358 let json = serde_json::to_string(&cr).unwrap();
359 assert_eq!(json, r#"{"kind":"login"}"#);
360
361 let cr: CredentialResponse =
362 serde_json::from_str(r#"{"kind":"unknown-kind","extra-data":true}"#).unwrap();
363 assert_eq!(cr, CredentialResponse::Unknown);
364
365 let cr: CredentialResponse =
366 serde_json::from_str(r#"{"kind":"login","extra-data":true}"#).unwrap();
367 assert_eq!(cr, CredentialResponse::Login);
368
369 let cr: CredentialResponse = serde_json::from_str(r#"{"kind":"get","token":"value","cache":"never","operation_independent":true,"extra-field-ignored":123}"#).unwrap();
370 assert_eq!(
371 cr,
372 CredentialResponse::Get {
373 cache: CacheControl::Never,
374 operation_independent: true,
375 token: Secret::from("value".to_string())
376 }
377 );
378 }
379
380 #[test]
381 fn credential_request() {
382 let get_oweners = CredentialRequest {
383 v: PROTOCOL_VERSION_1,
384 args: vec![],
385 registry: RegistryInfo {
386 index_url: "url",
387 name: None,
388 headers: vec![],
389 },
390 action: Action::Get(Operation::Owners { name: "pkg" }),
391 };
392
393 let json = serde_json::to_string(&get_oweners).unwrap();
394 assert_eq!(
395 json,
396 r#"{"v":1,"registry":{"index-url":"url"},"kind":"get","operation":"owners","name":"pkg"}"#
397 );
398
399 let cr: CredentialRequest<'_> =
400 serde_json::from_str(r#"{"extra-1":true,"v":1,"registry":{"index-url":"url","extra-2":true},"kind":"get","operation":"owners","name":"pkg","args":[]}"#).unwrap();
401 assert_eq!(cr, get_oweners);
402 }
403
404 #[test]
405 fn credential_request_logout() {
406 let unknown = CredentialRequest {
407 v: PROTOCOL_VERSION_1,
408 args: vec![],
409 registry: RegistryInfo {
410 index_url: "url",
411 name: None,
412 headers: vec![],
413 },
414 action: Action::Logout,
415 };
416
417 let cr: CredentialRequest<'_> = serde_json::from_str(
418 r#"{"v":1,"registry":{"index-url":"url"},"kind":"logout","extra-1":true,"args":[]}"#,
419 )
420 .unwrap();
421 assert_eq!(cr, unknown);
422 }
423
424 #[test]
425 fn credential_request_unknown() {
426 let unknown = CredentialRequest {
427 v: PROTOCOL_VERSION_1,
428 args: vec![],
429 registry: RegistryInfo {
430 index_url: "",
431 name: None,
432 headers: vec![],
433 },
434 action: Action::Unknown,
435 };
436
437 let cr: CredentialRequest<'_> = serde_json::from_str(
438 r#"{"v":1,"registry":{"index-url":""},"kind":"unexpected-1","extra-1":true,"args":[]}"#,
439 )
440 .unwrap();
441 assert_eq!(cr, unknown);
442 }
443}