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