interprex-github 7.0.0

GitHub provider for all Interprex development-platform domains
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use std::{collections::BTreeMap, fmt, io, path::Path, sync::Arc};

use interprex::{ConfigurationSource, ProviderError, Result};
use jsonwebtoken::EncodingKey;
use octocrab::{
    DefaultOctocrabBuilderConfig, NoAuth, NoSvc, NotLayerReady, Octocrab, OctocrabBuilder,
    service::middleware::retry::{NoOpRateLimitMetrics, RetryConfig},
};
use secrecy::ExposeSecret;

use crate::config::{GithubConfig, parse_project_config};

#[derive(Clone)]
pub struct GithubProvider {
    pub(crate) user: Option<Arc<Octocrab>>,
    pub(crate) streaming_user: Option<Arc<Octocrab>>,
    pub(crate) apps: BTreeMap<String, ConfiguredApp>,
    /// Where the credentials came from. A credential that is present records
    /// this on its own [`ConfiguredApp`]; the provider keeps it as well so
    /// that an *absent* credential can still name the file to edit.
    pub(crate) source: ConfigurationSource,
}

#[derive(Clone)]
pub(crate) struct ConfiguredApp {
    pub(crate) app_id: u64,
    pub(crate) read: Arc<Octocrab>,
    pub(crate) write: Arc<Octocrab>,
    pub(crate) source: ConfigurationSource,
}

impl fmt::Debug for GithubProvider {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("GithubProvider")
            .field("user", &self.user.as_ref().map(|_| "configured"))
            .field("apps", &self.apps.keys().collect::<Vec<_>>())
            .finish()
    }
}

impl GithubProvider {
    pub(crate) fn user(&self) -> Result<&Octocrab> {
        self.user.as_deref().ok_or_else(|| self.missing_user())
    }

    pub(crate) fn app(&self, name: &str) -> Result<&Octocrab> {
        self.configured_app(name).map(|app| app.read.as_ref())
    }

    pub(crate) fn configured_app(&self, name: &str) -> Result<&ConfiguredApp> {
        self.apps
            .get(name)
            .ok_or_else(|| ProviderError::MissingCredential {
                identity: name.to_owned(),
                kind: "named app",
                entry: format!("[provider.github.apps.{name}]"),
                origin: self.source.clone(),
            })
    }

    pub(crate) fn streaming_user(&self) -> Result<&Octocrab> {
        self.streaming_user
            .as_deref()
            .ok_or_else(|| self.missing_user())
    }

    fn missing_user(&self) -> ProviderError {
        ProviderError::MissingCredential {
            identity: "user".to_owned(),
            kind: "GH_TOKEN",
            entry: "GH_TOKEN in [provider.github]".to_owned(),
            origin: self.source.clone(),
        }
    }
}

pub fn from_config(config: GithubConfig) -> Result<GithubProvider> {
    from_config_with_source(config, ConfigurationSource::Direct)
}

fn from_config_with_source(
    config: GithubConfig,
    source: ConfigurationSource,
) -> Result<GithubProvider> {
    let user = config
        .gh_token
        .as_ref()
        .map(|token| build_user(token, &config))
        .transpose()?
        .map(Arc::new);
    let streaming_user = config
        .gh_token
        .as_ref()
        .map(|token| build_streaming_user(token, &config))
        .transpose()?
        .map(Arc::new);

    let mut apps = BTreeMap::new();
    for (name, credentials) in &config.apps {
        let key = || {
            EncodingKey::from_rsa_pem(credentials.private_key.expose_secret().as_bytes()).map_err(
                |_| ProviderError::Configuration {
                    origin: source.clone(),
                    reason: format!("invalid RSA private key for app {name}"),
                },
            )
        };
        let read = configured_builder(&config)?
            .app(credentials.app_id.into(), key()?)
            .build()
            .map_err(|error| external("construct app client", error))?
            .installation(credentials.installation_id.into())
            .map_err(|error| external("scope app installation", error))?;
        let write = base_builder(&config)?
            .add_retry_config(RetryConfig::None)
            .app(credentials.app_id.into(), key()?)
            .build()
            .map_err(|error| external("construct app write client", error))?
            .installation(credentials.installation_id.into())
            .map_err(|error| external("scope app write installation", error))?;
        apps.insert(
            name.clone(),
            ConfiguredApp {
                app_id: credentials.app_id,
                read: Arc::new(read),
                write: Arc::new(write),
                source: source.clone(),
            },
        );
    }
    Ok(GithubProvider {
        user,
        streaming_user,
        apps,
        source,
    })
}

pub async fn from_project(project_root: &Path) -> Result<GithubProvider> {
    let path = project_root.join(".interprex.toml");
    from_project_read(project_root, tokio::fs::read_to_string(path).await)
}

fn from_project_read(project_root: &Path, contents: io::Result<String>) -> Result<GithubProvider> {
    let path = project_root.join(".interprex.toml");
    let source = ConfigurationSource::File(path.display().to_string());
    let contents = contents.map_err(|error| ProviderError::Configuration {
        origin: source.clone(),
        reason: error.kind().to_string(),
    })?;
    let config = parse_project_config(&contents, &source)?;
    from_config_with_source(config, source)
}

fn build_user(token: &secrecy::SecretString, config: &GithubConfig) -> Result<Octocrab> {
    configured_builder(config)?
        .personal_token(token.clone())
        .build()
        .map_err(|error| external("construct user client", error))
}

fn build_streaming_user(token: &secrecy::SecretString, config: &GithubConfig) -> Result<Octocrab> {
    base_builder(config)?
        .personal_token(token.clone())
        .build()
        .map_err(|error| external("construct streaming user client", error))
}

fn configured_builder(
    config: &GithubConfig,
) -> Result<OctocrabBuilder<NoSvc, DefaultOctocrabBuilderConfig, NoAuth, NotLayerReady>> {
    Ok(
        base_builder(config)?.add_retry_config(RetryConfig::HandleRateLimits {
            metrics: Arc::new(NoOpRateLimitMetrics),
            max_retries: 3,
            min_wait_seconds: 1,
        }),
    )
}

fn base_builder(
    config: &GithubConfig,
) -> Result<OctocrabBuilder<NoSvc, DefaultOctocrabBuilderConfig, NoAuth, NotLayerReady>> {
    let mut builder = Octocrab::builder();
    if let Some(uri) = &config.base_uri {
        builder = builder
            .base_uri(uri)
            .map_err(|error| external("configure base URI", error))?;
    }
    if let Some(uri) = &config.upload_uri {
        builder = builder
            .upload_uri(uri)
            .map_err(|error| external("configure upload URI", error))?;
    }
    Ok(builder)
}

pub(crate) fn external(operation: &'static str, error: impl fmt::Display) -> ProviderError {
    ProviderError::External {
        provider: "github",
        operation,
        message: error.to_string(),
    }
}

pub(crate) fn authenticated_external(
    operation: &'static str,
    error: &octocrab::Error,
) -> ProviderError {
    let message = match error {
        octocrab::Error::GitHub { source, .. } => {
            format!("GitHub returned HTTP {}", source.status_code.as_u16())
        }
        _ => "request failed before a valid GitHub response".to_owned(),
    };
    ProviderError::External {
        provider: "github",
        operation,
        message,
    }
}

pub(crate) fn read_error(
    operation: &'static str,
    entity: impl Into<String>,
    error: octocrab::Error,
) -> ProviderError {
    if is_not_found(&error) {
        ProviderError::NotFound {
            entity: entity.into(),
        }
    } else {
        external(operation, error)
    }
}

pub(crate) fn is_not_found(error: &octocrab::Error) -> bool {
    matches!(
        error,
        octocrab::Error::GitHub { source, .. } if source.status_code.as_u16() == 404
    )
}

#[cfg(test)]
mod tests {
    use std::{
        collections::BTreeMap,
        path::{Path, PathBuf},
        sync::{
            Arc,
            atomic::{AtomicU64, Ordering},
        },
    };

    use interprex::{ConfigurationSource, ProviderError};
    use secrecy::SecretString;

    use super::{ConfiguredApp, GithubProvider, from_config, from_project, from_project_read};
    use crate::{AppCredentials, GithubConfig};

    struct TempProject(PathBuf);

    impl TempProject {
        fn new(contents: Option<&str>) -> Self {
            static NEXT: AtomicU64 = AtomicU64::new(0);
            let path = std::env::temp_dir().join(format!(
                "interprex-github-test-{}-{}",
                std::process::id(),
                NEXT.fetch_add(1, Ordering::Relaxed)
            ));
            std::fs::create_dir(&path).expect("create temporary project");
            if let Some(contents) = contents {
                std::fs::write(path.join(".interprex.toml"), contents)
                    .expect("write temporary project config");
            }
            Self(path)
        }

        fn path(&self) -> &Path {
            &self.0
        }
    }

    impl Drop for TempProject {
        fn drop(&mut self) {
            std::fs::remove_dir_all(&self.0).expect("remove temporary project");
        }
    }

    #[test]
    fn invalid_direct_app_key_reports_direct_construction() {
        let error = from_config(GithubConfig {
            apps: BTreeMap::from([(
                "automation".to_owned(),
                AppCredentials {
                    app_id: 12,
                    installation_id: 34,
                    private_key: SecretString::from("not-an-rsa-key"),
                },
            )]),
            ..GithubConfig::default()
        })
        .expect_err("invalid key");
        assert!(error.to_string().contains("direct"));
    }

    #[tokio::test]
    async fn project_file_constructs_the_same_identity_as_direct_input() {
        let project = TempProject::new(Some(
            r#"
                [provider.github]
                GH_TOKEN = "user-secret"
            "#,
        ));
        let from_project = from_project(project.path())
            .await
            .expect("project provider");
        let direct = from_config(GithubConfig {
            gh_token: Some(SecretString::from("user-secret")),
            ..GithubConfig::default()
        })
        .expect("direct provider");

        assert_eq!(format!("{from_project:?}"), format!("{direct:?}"));
        assert!(from_project.user().is_ok());
        assert!(from_project.streaming_user().is_ok());
    }

    #[tokio::test]
    async fn project_app_error_reports_the_file_that_supplied_it() {
        let project = TempProject::new(Some(
            r#"
                [provider.github]

                [provider.github.apps.automation]
                APP_ID = 12
                INSTALLATION_ID = 34
                PRIVATE_KEY = "not-an-rsa-key"
            "#,
        ));
        let error = from_project(project.path()).await.expect_err("invalid key");
        assert!(error.to_string().contains(&format!(
            "file {}",
            project.path().join(".interprex.toml").display()
        )));
    }

    #[tokio::test]
    async fn missing_project_file_returns_a_structured_configuration_error() {
        let project = TempProject::new(None);
        let error = from_project(project.path())
            .await
            .expect_err("missing file");
        assert_eq!(
            error,
            ProviderError::Configuration {
                origin: ConfigurationSource::File(
                    project.path().join(".interprex.toml").display().to_string()
                ),
                reason: std::io::ErrorKind::NotFound.to_string(),
            }
        );
    }

    #[test]
    fn unreadable_project_file_returns_a_structured_configuration_error() {
        let project_root = Path::new("/workspace/project");
        let error = from_project_read(
            project_root,
            Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)),
        )
        .expect_err("unreadable file");
        assert_eq!(
            error,
            ProviderError::Configuration {
                origin: ConfigurationSource::File(
                    project_root.join(".interprex.toml").display().to_string()
                ),
                reason: std::io::ErrorKind::PermissionDenied.to_string(),
            }
        );
    }

    #[tokio::test]
    async fn user_and_app_identities_remain_distinct() {
        let source = ConfigurationSource::File("/workspace/project/.interprex.toml".to_owned());
        let app_only = GithubProvider {
            user: None,
            streaming_user: None,
            apps: BTreeMap::from([(
                "automation".to_owned(),
                ConfiguredApp {
                    app_id: 12,
                    read: Arc::new(octocrab::Octocrab::default()),
                    write: Arc::new(octocrab::Octocrab::default()),
                    source: source.clone(),
                },
            )]),
            source: source.clone(),
        };
        assert_eq!(
            app_only.user().expect_err("user is absent"),
            ProviderError::MissingCredential {
                identity: "user".to_owned(),
                kind: "GH_TOKEN",
                entry: "GH_TOKEN in [provider.github]".to_owned(),
                origin: source.clone(),
            }
        );

        let user = Arc::new(octocrab::Octocrab::default());
        let user_only = GithubProvider {
            user: Some(Arc::clone(&user)),
            streaming_user: Some(user),
            apps: BTreeMap::new(),
            source: source.clone(),
        };
        assert_eq!(
            user_only
                .app("automation")
                .expect_err("named app is absent"),
            ProviderError::MissingCredential {
                identity: "automation".to_owned(),
                kind: "named app",
                entry: "[provider.github.apps.automation]".to_owned(),
                origin: source,
            }
        );
    }

    #[tokio::test]
    async fn absent_named_app_names_the_project_file_and_the_table_it_wants() {
        let project = TempProject::new(Some(
            r#"
                [provider.github]
                GH_TOKEN = "user-secret"
            "#,
        ));
        let provider = from_project(project.path())
            .await
            .expect("project provider");

        let message = provider
            .app("adr-codex-review")
            .expect_err("named app is absent")
            .to_string();
        assert!(
            message.contains("[provider.github.apps.adr-codex-review]"),
            "{message}"
        );
        assert!(
            message.contains(&project.path().join(".interprex.toml").display().to_string()),
            "{message}"
        );
    }
}