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 matches!(
176        &error,
177        octocrab::Error::GitHub { source, .. } if source.status_code.as_u16() == 404
178    ) {
179        ProviderError::NotFound {
180            entity: entity.into(),
181        }
182    } else {
183        external(operation, error)
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use std::{
190        collections::BTreeMap,
191        path::{Path, PathBuf},
192        sync::{
193            Arc,
194            atomic::{AtomicU64, Ordering},
195        },
196    };
197
198    use interprex::{ConfigurationSource, ProviderError};
199    use secrecy::SecretString;
200
201    use super::{GithubProvider, from_config, from_project, from_project_read};
202    use crate::{AppCredentials, GithubConfig};
203
204    struct TempProject(PathBuf);
205
206    impl TempProject {
207        fn new(contents: Option<&str>) -> Self {
208            static NEXT: AtomicU64 = AtomicU64::new(0);
209            let path = std::env::temp_dir().join(format!(
210                "interprex-github-test-{}-{}",
211                std::process::id(),
212                NEXT.fetch_add(1, Ordering::Relaxed)
213            ));
214            std::fs::create_dir(&path).expect("create temporary project");
215            if let Some(contents) = contents {
216                std::fs::write(path.join(".interprex.toml"), contents)
217                    .expect("write temporary project config");
218            }
219            Self(path)
220        }
221
222        fn path(&self) -> &Path {
223            &self.0
224        }
225    }
226
227    impl Drop for TempProject {
228        fn drop(&mut self) {
229            std::fs::remove_dir_all(&self.0).expect("remove temporary project");
230        }
231    }
232
233    #[test]
234    fn invalid_direct_app_key_reports_direct_construction() {
235        let error = from_config(GithubConfig {
236            apps: BTreeMap::from([(
237                "automation".to_owned(),
238                AppCredentials {
239                    app_id: 12,
240                    installation_id: 34,
241                    private_key: SecretString::from("not-an-rsa-key"),
242                },
243            )]),
244            ..GithubConfig::default()
245        })
246        .expect_err("invalid key");
247        assert!(error.to_string().contains("direct"));
248    }
249
250    #[tokio::test]
251    async fn project_file_constructs_the_same_identity_as_direct_input() {
252        let project = TempProject::new(Some(
253            r#"
254                [provider.github]
255                GH_TOKEN = "user-secret"
256            "#,
257        ));
258        let from_project = from_project(project.path())
259            .await
260            .expect("project provider");
261        let direct = from_config(GithubConfig {
262            gh_token: Some(SecretString::from("user-secret")),
263            ..GithubConfig::default()
264        })
265        .expect("direct provider");
266
267        assert_eq!(format!("{from_project:?}"), format!("{direct:?}"));
268        assert!(from_project.user().is_ok());
269        assert!(from_project.streaming_user().is_ok());
270    }
271
272    #[tokio::test]
273    async fn project_app_error_reports_the_file_that_supplied_it() {
274        let project = TempProject::new(Some(
275            r#"
276                [provider.github]
277
278                [provider.github.apps.automation]
279                APP_ID = 12
280                INSTALLATION_ID = 34
281                PRIVATE_KEY = "not-an-rsa-key"
282            "#,
283        ));
284        let error = from_project(project.path()).await.expect_err("invalid key");
285        assert!(error.to_string().contains(&format!(
286            "file {}",
287            project.path().join(".interprex.toml").display()
288        )));
289    }
290
291    #[tokio::test]
292    async fn missing_project_file_returns_a_structured_configuration_error() {
293        let project = TempProject::new(None);
294        let error = from_project(project.path())
295            .await
296            .expect_err("missing file");
297        assert_eq!(
298            error,
299            ProviderError::Configuration {
300                origin: ConfigurationSource::File(
301                    project.path().join(".interprex.toml").display().to_string()
302                ),
303                reason: std::io::ErrorKind::NotFound.to_string(),
304            }
305        );
306    }
307
308    #[test]
309    fn unreadable_project_file_returns_a_structured_configuration_error() {
310        let project_root = Path::new("/workspace/project");
311        let error = from_project_read(
312            project_root,
313            Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)),
314        )
315        .expect_err("unreadable file");
316        assert_eq!(
317            error,
318            ProviderError::Configuration {
319                origin: ConfigurationSource::File(
320                    project_root.join(".interprex.toml").display().to_string()
321                ),
322                reason: std::io::ErrorKind::PermissionDenied.to_string(),
323            }
324        );
325    }
326
327    #[tokio::test]
328    async fn user_and_app_identities_remain_distinct() {
329        let app_only = GithubProvider {
330            user: None,
331            streaming_user: None,
332            apps: BTreeMap::from([(
333                "automation".to_owned(),
334                Arc::new(octocrab::Octocrab::default()),
335            )]),
336        };
337        assert_eq!(
338            app_only.user().expect_err("user is absent"),
339            ProviderError::MissingCredential {
340                identity: "user".to_owned(),
341                kind: "GH_TOKEN"
342            }
343        );
344
345        let user = Arc::new(octocrab::Octocrab::default());
346        let user_only = GithubProvider {
347            user: Some(Arc::clone(&user)),
348            streaming_user: Some(user),
349            apps: BTreeMap::new(),
350        };
351        assert_eq!(
352            user_only
353                .app("automation")
354                .expect_err("named app is absent"),
355            ProviderError::MissingCredential {
356                identity: "automation".to_owned(),
357                kind: "named app"
358            }
359        );
360    }
361}