subspace_github_auth/
token.rs1use serde::Deserialize;
5use subspace_core::Secret;
6
7use crate::AuthError;
8
9pub const TOKEN_PATH: &str = "/login/oauth/access_token";
11pub(crate) const REPLY_LIMIT: u64 = 64 * 1024;
13const REQUIRED_SCOPES: [&str; 2] = ["repo", "read:org"];
14const ORG_SCOPES: [&str; 3] = ["read:org", "write:org", "admin:org"];
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Granted {
20 pub token: Secret,
21 pub scopes: Vec<String>,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum Reply {
27 Token(Granted),
28 Pending,
30 SlowDown(Option<u64>),
32 Failed(AuthError),
33}
34
35#[derive(Deserialize)]
36struct Raw {
37 access_token: Option<String>,
38 scope: Option<String>,
39 error: Option<String>,
40 error_description: Option<String>,
41 interval: Option<u64>,
42}
43
44pub fn parse_reply(body: &[u8]) -> Reply {
46 let Ok(raw) = serde_json::from_slice::<Raw>(body) else {
47 return Reply::Failed(AuthError::Service(
48 "GitHub's answer was not understood.".into(),
49 ));
50 };
51 match (raw.access_token, raw.error.as_deref()) {
52 (Some(token), None) if !token.is_empty() => Reply::Token(Granted {
53 token: Secret::new(token),
54 scopes: scopes(raw.scope.as_deref().unwrap_or_default()),
55 }),
56 (_, Some("authorization_pending")) => Reply::Pending,
57 (_, Some("slow_down")) => Reply::SlowDown(raw.interval),
58 (_, error) => Reply::Failed(failure(error, raw.error_description)),
59 }
60}
61
62pub fn failure(error: Option<&str>, description: Option<String>) -> AuthError {
64 match error {
65 Some("access_denied") => AuthError::Denied,
66 Some("expired_token") => AuthError::Expired,
67 Some("device_flow_disabled") => AuthError::DeviceFlowDisabled,
68 Some(code) => AuthError::Service(description.unwrap_or_else(|| code.to_owned())),
69 None => AuthError::Service("GitHub returned no token.".into()),
70 }
71}
72
73pub fn scopes(value: &str) -> Vec<String> {
75 value
76 .split([',', ' '])
77 .map(str::trim)
78 .filter(|scope| !scope.is_empty())
79 .map(str::to_owned)
80 .collect()
81}
82
83pub fn missing_scopes(granted: &[String]) -> Vec<&'static str> {
85 let has = |wanted: &str| granted.iter().any(|scope| scope == wanted);
86 REQUIRED_SCOPES
87 .into_iter()
88 .filter(|&required| match required {
89 "read:org" => !ORG_SCOPES.iter().any(|scope| has(scope)),
90 other => !has(other),
91 })
92 .collect()
93}
94
95pub fn check_scopes(granted: &[String]) -> Result<(), AuthError> {
97 let missing = missing_scopes(granted);
98 if missing.is_empty() {
99 return Ok(());
100 }
101 Err(AuthError::MissingScopes(missing.join(" and ")))
102}
103
104pub(crate) fn request(oauth: &str, form: &[(&str, &str)]) -> Result<Reply, AuthError> {
106 let url = format!("{oauth}{TOKEN_PATH}");
107 let mut response = subspace_core::http::agent()
108 .post(&url)
109 .header("Accept", "application/json")
110 .send_form(form.iter().copied())
111 .map_err(|error| AuthError::Network(error.to_string()))?;
112 let body = response
113 .body_mut()
114 .with_config()
115 .limit(REPLY_LIMIT)
116 .read_to_vec()
117 .map_err(|error| AuthError::Network(error.to_string()))?;
118 Ok(parse_reply(&body))
119}
120
121#[cfg(test)]
122mod tests {
123 use super::{Granted, Reply, check_scopes, missing_scopes, parse_reply, scopes};
124 use crate::AuthError;
125 use subspace_core::Secret;
126
127 #[test]
128 fn a_token_answer_gives_the_token_and_its_scopes() {
129 let reply = parse_reply(
130 br#"{"access_token":"fixture-octo","token_type":"bearer","scope":"read:org,repo"}"#,
131 );
132 assert_eq!(
133 reply,
134 Reply::Token(Granted {
135 token: Secret::new("fixture-octo"),
136 scopes: vec!["read:org".into(), "repo".into()],
137 })
138 );
139 assert!(!format!("{reply:?}").contains("fixture-octo"));
140 }
141
142 #[test]
143 fn error_answers_become_plain_failures_or_polling_steps() {
144 let reply = |body: &str| parse_reply(body.as_bytes());
145 assert_eq!(
146 reply(r#"{"error":"authorization_pending"}"#),
147 Reply::Pending
148 );
149 assert_eq!(
150 reply(r#"{"error":"slow_down","interval":10}"#),
151 Reply::SlowDown(Some(10))
152 );
153 assert_eq!(
154 reply(r#"{"error":"access_denied"}"#),
155 Reply::Failed(AuthError::Denied)
156 );
157 assert_eq!(
158 reply(r#"{"error":"expired_token"}"#),
159 Reply::Failed(AuthError::Expired)
160 );
161 assert_eq!(
162 reply(
163 r#"{"error":"device_flow_disabled","error_description":"Device Flow must be explicitly enabled for this App"}"#
164 ),
165 Reply::Failed(AuthError::DeviceFlowDisabled)
166 );
167 assert_eq!(
168 reply(
169 r#"{"error":"bad_verification_code","error_description":"The code passed is incorrect or expired."}"#
170 ),
171 Reply::Failed(AuthError::Service(
172 "The code passed is incorrect or expired.".into()
173 ))
174 );
175 assert!(matches!(
176 reply("<html>"),
177 Reply::Failed(AuthError::Service(_))
178 ));
179 assert!(matches!(
180 reply(r#"{"access_token":""}"#),
181 Reply::Failed(AuthError::Service(_))
182 ));
183 }
184
185 #[test]
186 fn both_scopes_are_required_and_broader_org_scopes_count() {
187 assert_eq!(scopes("repo, read:org"), ["repo", "read:org"]);
188 assert!(check_scopes(&scopes("repo,read:org")).is_ok());
189 assert!(check_scopes(&scopes("repo,admin:org,gist")).is_ok());
190 assert_eq!(missing_scopes(&scopes("read:org")), ["repo"]);
191 assert_eq!(missing_scopes(&scopes("")), ["repo", "read:org"]);
192 let error = check_scopes(&scopes("public_repo")).unwrap_err();
193 assert_eq!(
194 error.to_string(),
195 "GitHub did not grant repo and read:org. Sign in again and approve every permission."
196 );
197 }
198}