1use std::{collections::BTreeMap, fmt, io, path::Path, sync::Arc};
2
3use interprex::{ConfigurationSource, ProviderError, Result};
4use jsonwebtoken::EncodingKey;
5use octocrab::{
6 DefaultOctocrabBuilderConfig, NoAuth, NoSvc, NotLayerReady, Octocrab, OctocrabBuilder,
7 service::middleware::retry::{NoOpRateLimitMetrics, RetryConfig},
8};
9use secrecy::ExposeSecret;
10
11use crate::config::{GithubConfig, parse_project_config};
12
13#[derive(Clone)]
14pub struct GithubProvider {
15 pub(crate) user: Option<Arc<Octocrab>>,
16 pub(crate) streaming_user: Option<Arc<Octocrab>>,
17 pub(crate) apps: BTreeMap<String, ConfiguredApp>,
18}
19
20#[derive(Clone)]
21pub(crate) struct ConfiguredApp {
22 pub(crate) app_id: u64,
23 pub(crate) read: Arc<Octocrab>,
24 pub(crate) write: Arc<Octocrab>,
25 pub(crate) source: ConfigurationSource,
26}
27
28impl fmt::Debug for GithubProvider {
29 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
30 formatter
31 .debug_struct("GithubProvider")
32 .field("user", &self.user.as_ref().map(|_| "configured"))
33 .field("apps", &self.apps.keys().collect::<Vec<_>>())
34 .finish()
35 }
36}
37
38impl GithubProvider {
39 pub(crate) fn user(&self) -> Result<&Octocrab> {
40 self.user
41 .as_deref()
42 .ok_or(ProviderError::MissingCredential {
43 identity: "user".to_owned(),
44 kind: "GH_TOKEN",
45 })
46 }
47
48 pub(crate) fn app(&self, name: &str) -> Result<&Octocrab> {
49 self.configured_app(name).map(|app| app.read.as_ref())
50 }
51
52 pub(crate) fn configured_app(&self, name: &str) -> Result<&ConfiguredApp> {
53 self.apps
54 .get(name)
55 .ok_or_else(|| ProviderError::MissingCredential {
56 identity: name.to_owned(),
57 kind: "named app",
58 })
59 }
60
61 pub(crate) fn streaming_user(&self) -> Result<&Octocrab> {
62 self.streaming_user
63 .as_deref()
64 .ok_or(ProviderError::MissingCredential {
65 identity: "user".to_owned(),
66 kind: "GH_TOKEN",
67 })
68 }
69}
70
71pub fn from_config(config: GithubConfig) -> Result<GithubProvider> {
72 from_config_with_source(config, ConfigurationSource::Direct)
73}
74
75fn from_config_with_source(
76 config: GithubConfig,
77 source: ConfigurationSource,
78) -> Result<GithubProvider> {
79 let user = config
80 .gh_token
81 .as_ref()
82 .map(|token| build_user(token, &config))
83 .transpose()?
84 .map(Arc::new);
85 let streaming_user = config
86 .gh_token
87 .as_ref()
88 .map(|token| build_streaming_user(token, &config))
89 .transpose()?
90 .map(Arc::new);
91
92 let mut apps = BTreeMap::new();
93 for (name, credentials) in &config.apps {
94 let key = || {
95 EncodingKey::from_rsa_pem(credentials.private_key.expose_secret().as_bytes()).map_err(
96 |_| ProviderError::Configuration {
97 origin: source.clone(),
98 reason: format!("invalid RSA private key for app {name}"),
99 },
100 )
101 };
102 let read = configured_builder(&config)?
103 .app(credentials.app_id.into(), key()?)
104 .build()
105 .map_err(|error| external("construct app client", error))?
106 .installation(credentials.installation_id.into())
107 .map_err(|error| external("scope app installation", error))?;
108 let write = base_builder(&config)?
109 .add_retry_config(RetryConfig::None)
110 .app(credentials.app_id.into(), key()?)
111 .build()
112 .map_err(|error| external("construct app write client", error))?
113 .installation(credentials.installation_id.into())
114 .map_err(|error| external("scope app write installation", error))?;
115 apps.insert(
116 name.clone(),
117 ConfiguredApp {
118 app_id: credentials.app_id,
119 read: Arc::new(read),
120 write: Arc::new(write),
121 source: source.clone(),
122 },
123 );
124 }
125 Ok(GithubProvider {
126 user,
127 streaming_user,
128 apps,
129 })
130}
131
132pub async fn from_project(project_root: &Path) -> Result<GithubProvider> {
133 let path = project_root.join(".interprex.toml");
134 from_project_read(project_root, tokio::fs::read_to_string(path).await)
135}
136
137fn from_project_read(project_root: &Path, contents: io::Result<String>) -> Result<GithubProvider> {
138 let path = project_root.join(".interprex.toml");
139 let source = ConfigurationSource::File(path.display().to_string());
140 let contents = contents.map_err(|error| ProviderError::Configuration {
141 origin: source.clone(),
142 reason: error.kind().to_string(),
143 })?;
144 let config = parse_project_config(&contents, &source)?;
145 from_config_with_source(config, source)
146}
147
148fn build_user(token: &secrecy::SecretString, config: &GithubConfig) -> Result<Octocrab> {
149 configured_builder(config)?
150 .personal_token(token.clone())
151 .build()
152 .map_err(|error| external("construct user client", error))
153}
154
155fn build_streaming_user(token: &secrecy::SecretString, config: &GithubConfig) -> Result<Octocrab> {
156 base_builder(config)?
157 .personal_token(token.clone())
158 .build()
159 .map_err(|error| external("construct streaming user client", error))
160}
161
162fn configured_builder(
163 config: &GithubConfig,
164) -> Result<OctocrabBuilder<NoSvc, DefaultOctocrabBuilderConfig, NoAuth, NotLayerReady>> {
165 Ok(
166 base_builder(config)?.add_retry_config(RetryConfig::HandleRateLimits {
167 metrics: Arc::new(NoOpRateLimitMetrics),
168 max_retries: 3,
169 min_wait_seconds: 1,
170 }),
171 )
172}
173
174fn base_builder(
175 config: &GithubConfig,
176) -> Result<OctocrabBuilder<NoSvc, DefaultOctocrabBuilderConfig, NoAuth, NotLayerReady>> {
177 let mut builder = Octocrab::builder();
178 if let Some(uri) = &config.base_uri {
179 builder = builder
180 .base_uri(uri)
181 .map_err(|error| external("configure base URI", error))?;
182 }
183 if let Some(uri) = &config.upload_uri {
184 builder = builder
185 .upload_uri(uri)
186 .map_err(|error| external("configure upload URI", error))?;
187 }
188 Ok(builder)
189}
190
191pub(crate) fn external(operation: &'static str, error: impl fmt::Display) -> ProviderError {
192 ProviderError::External {
193 provider: "github",
194 operation,
195 message: error.to_string(),
196 }
197}
198
199pub(crate) fn authenticated_external(
200 operation: &'static str,
201 error: &octocrab::Error,
202) -> ProviderError {
203 let message = match error {
204 octocrab::Error::GitHub { source, .. } => {
205 format!("GitHub returned HTTP {}", source.status_code.as_u16())
206 }
207 _ => "request failed before a valid GitHub response".to_owned(),
208 };
209 ProviderError::External {
210 provider: "github",
211 operation,
212 message,
213 }
214}
215
216pub(crate) fn read_error(
217 operation: &'static str,
218 entity: impl Into<String>,
219 error: octocrab::Error,
220) -> ProviderError {
221 if is_not_found(&error) {
222 ProviderError::NotFound {
223 entity: entity.into(),
224 }
225 } else {
226 external(operation, error)
227 }
228}
229
230pub(crate) fn is_not_found(error: &octocrab::Error) -> bool {
231 matches!(
232 error,
233 octocrab::Error::GitHub { source, .. } if source.status_code.as_u16() == 404
234 )
235}
236
237#[cfg(test)]
238mod tests {
239 use std::{
240 collections::BTreeMap,
241 path::{Path, PathBuf},
242 sync::{
243 Arc,
244 atomic::{AtomicU64, Ordering},
245 },
246 };
247
248 use interprex::{ConfigurationSource, ProviderError};
249 use secrecy::SecretString;
250
251 use super::{ConfiguredApp, GithubProvider, from_config, from_project, from_project_read};
252 use crate::{AppCredentials, GithubConfig};
253
254 struct TempProject(PathBuf);
255
256 impl TempProject {
257 fn new(contents: Option<&str>) -> Self {
258 static NEXT: AtomicU64 = AtomicU64::new(0);
259 let path = std::env::temp_dir().join(format!(
260 "interprex-github-test-{}-{}",
261 std::process::id(),
262 NEXT.fetch_add(1, Ordering::Relaxed)
263 ));
264 std::fs::create_dir(&path).expect("create temporary project");
265 if let Some(contents) = contents {
266 std::fs::write(path.join(".interprex.toml"), contents)
267 .expect("write temporary project config");
268 }
269 Self(path)
270 }
271
272 fn path(&self) -> &Path {
273 &self.0
274 }
275 }
276
277 impl Drop for TempProject {
278 fn drop(&mut self) {
279 std::fs::remove_dir_all(&self.0).expect("remove temporary project");
280 }
281 }
282
283 #[test]
284 fn invalid_direct_app_key_reports_direct_construction() {
285 let error = from_config(GithubConfig {
286 apps: BTreeMap::from([(
287 "automation".to_owned(),
288 AppCredentials {
289 app_id: 12,
290 installation_id: 34,
291 private_key: SecretString::from("not-an-rsa-key"),
292 },
293 )]),
294 ..GithubConfig::default()
295 })
296 .expect_err("invalid key");
297 assert!(error.to_string().contains("direct"));
298 }
299
300 #[tokio::test]
301 async fn project_file_constructs_the_same_identity_as_direct_input() {
302 let project = TempProject::new(Some(
303 r#"
304 [provider.github]
305 GH_TOKEN = "user-secret"
306 "#,
307 ));
308 let from_project = from_project(project.path())
309 .await
310 .expect("project provider");
311 let direct = from_config(GithubConfig {
312 gh_token: Some(SecretString::from("user-secret")),
313 ..GithubConfig::default()
314 })
315 .expect("direct provider");
316
317 assert_eq!(format!("{from_project:?}"), format!("{direct:?}"));
318 assert!(from_project.user().is_ok());
319 assert!(from_project.streaming_user().is_ok());
320 }
321
322 #[tokio::test]
323 async fn project_app_error_reports_the_file_that_supplied_it() {
324 let project = TempProject::new(Some(
325 r#"
326 [provider.github]
327
328 [provider.github.apps.automation]
329 APP_ID = 12
330 INSTALLATION_ID = 34
331 PRIVATE_KEY = "not-an-rsa-key"
332 "#,
333 ));
334 let error = from_project(project.path()).await.expect_err("invalid key");
335 assert!(error.to_string().contains(&format!(
336 "file {}",
337 project.path().join(".interprex.toml").display()
338 )));
339 }
340
341 #[tokio::test]
342 async fn missing_project_file_returns_a_structured_configuration_error() {
343 let project = TempProject::new(None);
344 let error = from_project(project.path())
345 .await
346 .expect_err("missing file");
347 assert_eq!(
348 error,
349 ProviderError::Configuration {
350 origin: ConfigurationSource::File(
351 project.path().join(".interprex.toml").display().to_string()
352 ),
353 reason: std::io::ErrorKind::NotFound.to_string(),
354 }
355 );
356 }
357
358 #[test]
359 fn unreadable_project_file_returns_a_structured_configuration_error() {
360 let project_root = Path::new("/workspace/project");
361 let error = from_project_read(
362 project_root,
363 Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)),
364 )
365 .expect_err("unreadable file");
366 assert_eq!(
367 error,
368 ProviderError::Configuration {
369 origin: ConfigurationSource::File(
370 project_root.join(".interprex.toml").display().to_string()
371 ),
372 reason: std::io::ErrorKind::PermissionDenied.to_string(),
373 }
374 );
375 }
376
377 #[tokio::test]
378 async fn user_and_app_identities_remain_distinct() {
379 let app_only = GithubProvider {
380 user: None,
381 streaming_user: None,
382 apps: BTreeMap::from([(
383 "automation".to_owned(),
384 ConfiguredApp {
385 app_id: 12,
386 read: Arc::new(octocrab::Octocrab::default()),
387 write: Arc::new(octocrab::Octocrab::default()),
388 source: ConfigurationSource::Direct,
389 },
390 )]),
391 };
392 assert_eq!(
393 app_only.user().expect_err("user is absent"),
394 ProviderError::MissingCredential {
395 identity: "user".to_owned(),
396 kind: "GH_TOKEN"
397 }
398 );
399
400 let user = Arc::new(octocrab::Octocrab::default());
401 let user_only = GithubProvider {
402 user: Some(Arc::clone(&user)),
403 streaming_user: Some(user),
404 apps: BTreeMap::new(),
405 };
406 assert_eq!(
407 user_only
408 .app("automation")
409 .expect_err("named app is absent"),
410 ProviderError::MissingCredential {
411 identity: "automation".to_owned(),
412 kind: "named app"
413 }
414 );
415 }
416}