Skip to main content

interprex_github/
client.rs

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