vgi-bridge 0.18.1

The per-community VGI bridge: holds the community's forge credentials, takes git-ns/bridge jobs from its VTC over TSP or DIDComm, runs the forge adapters, reports results, events and drift, and posts the commit-trust check where no forge feature can be trusted to.
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
//! The adapter registry: one [`Forge`] per Forgejo host, and one per GitHub
//! App โ€” `(host, owner)`, since a private App serves only the account that
//! owns it.
//!
//! The core dispatches on a resource's host (and, on GitHub, its owner:
//! [`Adapters::for_resource`]) and talks to every adapter
//! through the forge-neutral [`Forge`] and [`ForgeHooks`] traits. The few
//! adapter-specific calls โ€” GitHub's managed set, pins and check runs,
//! Forgejo's token rotation โ€” go through [`Adapter`], so they stay in one
//! place.
//!
//! Adapters are built from the config plus the sealed store, and a GitHub
//! adapter can appear at run time (the App is registered through the
//! manifest flow while the bridge is up).

use std::collections::BTreeMap;
use std::path::Path;
use std::sync::{Arc, RwLock};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use vgi_forge::{Forge, ForgeHooks, Resource, VgiConfig};
use zeroize::Zeroizing;

use crate::config::BridgeConfig;
#[cfg(feature = "forge-forgejo")]
use crate::config::ForgejoForgeConfig;
#[cfg(feature = "forge-github")]
use crate::config::GitHubForgeConfig;
use crate::store::{NamespaceRecord, NamespaceState, Store};

/// One adapter, with its concrete type kept for the calls the trait does
/// not have.
#[derive(Clone)]
#[non_exhaustive]
pub enum Adapter {
    /// GitHub (github.com or GHES) as the community's App.
    #[cfg(feature = "forge-github")]
    GitHub(Arc<vgi_forge_github::GitHubForge>),
    /// A Forgejo instance as the community's bot.
    #[cfg(feature = "forge-forgejo")]
    Forgejo(Arc<vgi_forge_forgejo::ForgejoForge>),
}

impl std::fmt::Debug for Adapter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Adapter({})", self.forge().host())
    }
}

impl Adapter {
    /// The forge-neutral view.
    pub fn forge(&self) -> &dyn Forge {
        match self {
            #[cfg(feature = "forge-github")]
            Adapter::GitHub(g) => g.as_ref(),
            #[cfg(feature = "forge-forgejo")]
            Adapter::Forgejo(f) => f.as_ref(),
        }
    }

    /// The adapter's lifecycle hooks.
    pub fn hooks(&self) -> &dyn ForgeHooks {
        match self {
            #[cfg(feature = "forge-github")]
            Adapter::GitHub(g) => g.as_ref(),
            #[cfg(feature = "forge-forgejo")]
            Adapter::Forgejo(f) => f.as_ref(),
        }
    }

    /// The GitHub adapter, if this is one.
    #[cfg(feature = "forge-github")]
    pub fn github(&self) -> Option<&Arc<vgi_forge_github::GitHubForge>> {
        match self {
            Adapter::GitHub(g) => Some(g),
            #[allow(unreachable_patterns)]
            _ => None,
        }
    }

    /// The Forgejo adapter, if this is one.
    #[cfg(feature = "forge-forgejo")]
    pub fn forgejo(&self) -> Option<&Arc<vgi_forge_forgejo::ForgejoForge>> {
        match self {
            Adapter::Forgejo(f) => Some(f),
            #[allow(unreachable_patterns)]
            _ => None,
        }
    }

    /// Hand a stored namespace back to the adapter after a restart: the
    /// binding, and on GitHub the required-workflow availability, managed
    /// set and pin โ€” without which its org-mode steps refuse to run.
    pub fn restore(&self, record: &NamespaceRecord) -> Result<()> {
        if record.state != NamespaceState::Bound {
            return Ok(());
        }
        let Some(binding) = &record.binding else {
            return Ok(());
        };
        match self {
            #[cfg(feature = "forge-github")]
            Adapter::GitHub(g) => {
                g.register_namespace(binding.namespace.clone())?;
                let rw = record
                    .required_workflow
                    .or(record.capabilities.as_ref().map(|c| c.required_workflow));
                if let Some(rw) = rw {
                    g.set_required_workflow(&record.resource, rw);
                }
                g.set_managed_repositories(&record.resource, record.managed.iter().copied());
                if let Some(ready) = record.bridge_checks {
                    g.set_bridge_checks_ready(&record.resource, ready);
                }
                if let Some(pin) = &record.pin {
                    g.set_required_workflow_pin(
                        &record.resource,
                        vgi_forge_github::RequiredWorkflowPin::new(
                            pin.repository_id,
                            pin.sha.clone(),
                            pin.check.clone(),
                        ),
                    );
                }
            }
            #[cfg(feature = "forge-forgejo")]
            Adapter::Forgejo(f) => {
                f.register_namespace(binding.namespace.clone())?;
            }
        }
        Ok(())
    }
}

/// What the manifest exchange produced, as sealed at
/// `github/<host>/<owner>/app`.
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StoredApp {
    /// Numeric App id.
    pub app_id: u64,
    /// The account that owns the App (lowercase), as GitHub reported it at
    /// registration.
    pub owner: String,
    /// URL slug.
    pub slug: String,
    /// OAuth client id.
    pub client_id: String,
    /// OAuth client secret.
    pub client_secret: String,
    /// Webhook HMAC secret.
    pub webhook_secret: String,
    /// The App private key, PEM.
    pub pem: String,
}

impl Drop for StoredApp {
    fn drop(&mut self) {
        use zeroize::Zeroize;
        self.client_secret.zeroize();
        self.webhook_secret.zeroize();
        self.pem.zeroize();
    }
}

/// The sealed-secret name of the GitHub App `owner` owns on `host`.
pub fn github_app_secret(host: &str, owner: &str) -> String {
    format!("github/{host}/{}/app", owner.to_ascii_lowercase())
}

/// Where a single-App release kept its App: `github/<host>/app`. Read only
/// to refuse it ([`refuse_single_app_layout`]).
pub fn legacy_github_app_secret(host: &str) -> String {
    format!("github/{host}/app")
}

/// Refuse a store holding a GitHub App in the single-App layout
/// (`github/<host>/app`, with no owner): this release keys every App by its
/// owner and does not read or move that record. Deployments are recreated,
/// not migrated.
pub fn refuse_single_app_layout(cfg: &BridgeConfig, store: &Store) -> Result<()> {
    let hosts: std::collections::BTreeSet<&str> =
        cfg.github.iter().map(|g| g.host.as_str()).collect();
    for host in hosts {
        if store.get_secret(&legacy_github_app_secret(host))?.is_some() {
            anyhow::bail!(
                "the store holds a GitHub App for `{host}` in the single-App layout \
                 (`github/{host}/app`), which this release does not use: every App is now one \
                 organisation's, with its own routes. Re-register the App: delete it on GitHub, \
                 start the bridge on a fresh store (an empty `data_dir`, or in VTA mode a fresh \
                 context), and register one App per organisation from the links it logs"
            );
        }
    }
    Ok(())
}

/// The sealed-secret names of a Forgejo bot's credentials.
pub fn forgejo_secret(host: &str, what: &str) -> String {
    format!("forgejo/{host}/{what}")
}

/// What an adapter is filed under: its host, and for a GitHub App the owner
/// (lowercase).
type Key = (String, Option<String>);

/// Every adapter the bridge has โ€” one per Forgejo host, one per GitHub App โ€”
/// with each one's bootstrap inputs.
#[derive(Default)]
pub struct Adapters {
    map: RwLock<BTreeMap<Key, Adapter>>,
    vgi: RwLock<BTreeMap<Key, VgiConfig>>,
}

impl std::fmt::Debug for Adapters {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let keys: Vec<String> = self
            .map
            .read()
            .expect("lock")
            .keys()
            .map(|(h, o)| match o {
                Some(o) => format!("{h}/{o}"),
                None => h.clone(),
            })
            .collect();
        f.debug_struct("Adapters").field("adapters", &keys).finish()
    }
}

impl Adapters {
    /// No adapters.
    pub fn new() -> Self {
        Adapters::default()
    }

    /// Put `adapter` in service, with the bootstrap inputs `vgi`: a GitHub
    /// App under `owner` (the account that owns it), a Forgejo bot under its
    /// host (`owner` is `None`).
    pub fn insert(&self, adapter: Adapter, owner: Option<&str>, vgi: VgiConfig) {
        let key = (
            adapter.forge().host().to_string(),
            owner.map(str::to_ascii_lowercase),
        );
        self.vgi.write().expect("lock").insert(key.clone(), vgi);
        self.map.write().expect("lock").insert(key, adapter);
    }

    /// The Forgejo adapter for `host`.
    pub fn get(&self, host: &str) -> Option<Adapter> {
        self.map
            .read()
            .expect("lock")
            .get(&(host.to_string(), None))
            .cloned()
    }

    /// The GitHub App `owner` owns on `host` โ€” that App and no other.
    pub fn get_github(&self, host: &str, owner: &str) -> Option<Adapter> {
        self.map
            .read()
            .expect("lock")
            .get(&(host.to_string(), Some(owner.to_ascii_lowercase())))
            .cloned()
    }

    /// How many adapters serve `host`.
    pub fn count_on(&self, host: &str) -> usize {
        self.map
            .read()
            .expect("lock")
            .keys()
            .filter(|(h, _)| h == host)
            .count()
    }

    /// The key of the adapter serving `r`: its Forgejo host, or the GitHub
    /// App its owner owns.
    fn key_of(&self, r: &Resource) -> Option<Key> {
        let map = self.map.read().expect("lock");
        [
            (r.host().to_string(), None),
            (r.host().to_string(), Some(r.owner().to_ascii_lowercase())),
        ]
        .into_iter()
        .find(|k| map.contains_key(k))
    }

    /// The adapter for a resource: its Forgejo host's, or the GitHub App its
    /// owner owns (and no other).
    pub fn for_resource(&self, r: &Resource) -> Option<Adapter> {
        let k = self.key_of(r)?;
        self.map.read().expect("lock").get(&k).cloned()
    }

    /// The bootstrap inputs of the adapter serving `r`.
    pub fn vgi_for(&self, r: &Resource) -> Option<VgiConfig> {
        let k = self.key_of(r)?;
        self.vgi.read().expect("lock").get(&k).cloned()
    }

    /// Every adapter.
    pub fn all(&self) -> Vec<Adapter> {
        self.map.read().expect("lock").values().cloned().collect()
    }
}

/// The forge-neutral bootstrap inputs from the config, plus a platform
/// keyring when the forge needs one.
pub fn vgi_config(cfg: &BridgeConfig, keyring: Option<Vec<u8>>) -> VgiConfig {
    let v = &cfg.verify_trust;
    let mut out = VgiConfig::new(
        cfg.trust_registry_did.clone(),
        cfg.vtc_did.clone(),
        v.action.clone(),
        v.version.clone(),
    );
    out.required_check = v.required_check.clone();
    out = out
        .with_verify_trust_transport(v.transport)
        .with_required_approvals(cfg.required_approvals);
    if let Some(sha) = &v.sha256 {
        out = out.with_verify_trust_sha256(sha.clone());
    }
    if let Some(k) = keyring {
        out = out.with_platform_keyring(k);
    }
    out
}

/// Read an armored keyring file.
pub fn read_keyring(path: &Path) -> Result<Vec<u8>> {
    std::fs::read(path).with_context(|| format!("reading the platform keyring {}", path.display()))
}

/// Build the GitHub adapter for `g` from its sealed App credentials, or
/// `None` if the App has not been registered yet. An App recorded as owned
/// by another account than `g.app_owner` is refused.
#[cfg(feature = "forge-github")]
pub fn build_github(
    store: &Store,
    g: &GitHubForgeConfig,
) -> Result<Option<Arc<vgi_forge_github::GitHubForge>>> {
    use vgi_forge_github::{GitHubConfig, GitHubForge, InProcessKey, Secret};
    let Some(bytes) = store.get_secret(&github_app_secret(&g.host, &g.app_owner))? else {
        return Ok(None);
    };
    let app: StoredApp = serde_json::from_slice(&bytes).context("decoding the sealed App")?;
    let owner = &app.owner;
    if !owner.eq_ignore_ascii_case(&g.app_owner) {
        anyhow::bail!(
            "the App stored for `{}` on `{}` is owned by `{owner}`: refusing it",
            g.app_owner,
            g.host
        );
    }
    let mut cfg = if g.host == "github.com" {
        GitHubConfig::github_com(app.app_id, app.client_id.clone(), app.slug.clone())
    } else {
        GitHubConfig::enterprise(&g.host, app.app_id, app.client_id.clone(), app.slug.clone())?
    };
    if let (Some(api), Some(web)) = (&g.api_base, &g.web_base) {
        cfg = cfg.with_endpoints(api.clone(), web.clone());
    }
    if g.bridge_checks {
        cfg = cfg.with_bridge_checks();
    }
    // The key stays in process memory from here on (the enclave signer of
    // ยง5.7 is the `AppKeySigner` seam when a deployment has one).
    let pem = Zeroizing::new(app.pem.clone());
    let signer = Arc::new(InProcessKey::from_pem(&pem)?);
    let forge = GitHubForge::new(cfg, signer, Secret::new(app.webhook_secret.clone()))?
        .with_client_secret(Secret::new(app.client_secret.clone()));
    Ok(Some(Arc::new(forge)))
}

/// The startup log line for a `[[github]]` entry whose App's credentials
/// loaded.
#[cfg(feature = "forge-github")]
pub(crate) fn app_in_service_line(slug: &str, owner: &str, host: &str) -> String {
    format!("the GitHub App `{slug}` for `{owner}` on {host} is in service")
}

/// Connect the Forgejo adapter for `f` with its sealed bot credentials.
/// `None` if the bot token is not stored yet.
#[cfg(feature = "forge-forgejo")]
pub async fn build_forgejo(
    cfg: &BridgeConfig,
    store: &Store,
    f: &ForgejoForgeConfig,
) -> Result<Option<Arc<vgi_forge_forgejo::ForgejoForge>>> {
    use vgi_forge_forgejo::{Credentials, ForgejoConfig, ForgejoForge, MergeFallback, Secret};
    let host = f.host()?;
    let secret = |what: &str| -> Result<Option<Secret>> {
        Ok(store
            .get_secret_string(&forgejo_secret(&host, what))?
            .map(|s| Secret::new(s.as_str())))
    };
    let Some(token) = secret("bot-token")? else {
        return Ok(None);
    };
    let oauth = secret("oauth-client-secret")?
        .context("the Forgejo OAuth client secret is not stored (`vgi-bridge secret set`)")?;
    let webhook = secret("webhook-secret")?
        .context("the Forgejo webhook secret is not stored (`vgi-bridge secret set`)")?;
    let mut fc = ForgejoConfig::new(
        f.base_url.clone(),
        f.bot_login.clone(),
        f.oauth_client_id.clone(),
        cfg.url(&format!("forgejo/{host}/bind")),
        cfg.url(&format!("forgejo/{host}/link")),
    )?
    .with_webhook_url(cfg.url(&format!("forgejo/{host}/webhook")));
    if f.instance_signing_key_fallback {
        fc = fc.with_merge_fallback(MergeFallback::InstanceSigningKey);
    }
    if let Some(ctx) = &f.status_check_context {
        fc = fc.with_status_check_context(ctx.clone());
    }
    if let Some(label) = &f.runs_on {
        fc = fc.with_runs_on(label.clone())?;
    }
    let mut creds = Credentials::new(token, oauth, webhook);
    if let Some(pw) = secret("bot-password")? {
        creds = creds.with_bot_password(pw);
    }
    Ok(Some(Arc::new(ForgejoForge::connect(fc, creds).await?)))
}