Skip to main content

subspace_client_github/
bound.rs

1//! Credential-bound reads, independent of subsequent account/environment changes.
2
3use crate::{Client, detail_from_data, model::GhItemDetail, queries, transport, validate};
4use serde_json::{Value, json};
5use std::sync::Arc;
6use subspace_core::{
7    credentials::{Credential, Credentials},
8    http::{Error, status},
9};
10
11const BOUND_VIEWER_QUERY: &str = "query ViewerBound { viewer { id login } }";
12const MAX_ACCOUNT_ID_BYTES: usize = 256;
13
14mod packages;
15pub use packages::{
16    Organization, PackageRelease, PackageRepository, ReleaseAsset, RepositoryRef,
17    ResolvedRepository, newest_package_release,
18};
19
20/// A verified principal and one in-memory credential. Never serialized or Debug.
21pub struct BoundRead {
22    pub(super) credential: Credential,
23    credentials: Arc<Credentials>,
24    endpoint: String,
25    account: String,
26    account_id: String,
27}
28
29impl BoundRead {
30    /// Verify the requested login using exactly the credential retained for reads.
31    pub(crate) fn bind(client: &Client, login: &str) -> Result<Self, Error> {
32        validate::check_login(login)?;
33        let mut bound = BoundRead {
34            credential: client.credential(Some(login))?,
35            credentials: client.credentials.clone(),
36            endpoint: client.api_url.clone(),
37            account: login.to_owned(),
38            account_id: String::new(),
39        };
40        let data = bound.graphql(BOUND_VIEWER_QUERY, json!({}))?;
41        let actual = data["viewer"]["login"]
42            .as_str()
43            .ok_or_else(|| transport::unexpected("viewer"))?;
44        validate::check_login(actual)?;
45        if !actual.eq_ignore_ascii_case(login) {
46            return Err(transport::status(
47                status::UNAUTHORIZED,
48                "The GitHub credential belongs to another account.",
49            ));
50        }
51        bound.account = actual.to_ascii_lowercase();
52        bound.account_id = verified_account_id(&data)?.to_owned();
53        Ok(bound)
54    }
55}
56
57impl BoundRead {
58    // qual:allow(dry, boilerplate) reason: "Verified binding metadata must not be mutable independently of its credential."
59    pub fn account(&self) -> &str {
60        &self.account
61    }
62
63    /// The immutable viewer node ID verified with this binding's credential.
64    // qual:api
65    // qual:allow(dry, boilerplate) reason: "Verified binding metadata must not be mutable independently of its credential."
66    pub fn account_id(&self) -> &str {
67        &self.account_id
68    }
69
70    // qual:allow(dry, boilerplate) reason: "Verified binding metadata must not be mutable independently of its credential."
71    pub fn endpoint(&self) -> &str {
72        &self.endpoint
73    }
74
75    /// Reuses the existing bounded detail query, including comments and reviews.
76    pub fn item(&self, key: &str) -> Result<GhItemDetail, Error> {
77        let item = validate::check_key(key)?;
78        let variables = json!({"owner":item.owner,"name":item.name,"number":item.number});
79        let data = self.graphql(&queries::detail_query(), variables)?;
80        let data = serde_json::from_value(data).map_err(|_| transport::unexpected("response"))?;
81        detail_from_data(data, &self.account)
82    }
83
84    pub(super) fn graphql(&self, query: &str, variables: Value) -> Result<Value, Error> {
85        let body = json!({"query":query,"variables":variables}).to_string();
86        let response = transport::post_bound_graphql(
87            &format!("{}/graphql", self.endpoint),
88            &self.credential,
89            &self.account,
90            &body,
91        );
92        if matches!(
93            &response,
94            Err(Error::Status {
95                status: status::UNAUTHORIZED,
96                ..
97            })
98        ) {
99            self.credentials.invalidate(&self.credential);
100        }
101        transport::graphql_data(&self.account, response?, false).map_err(safe_error)
102    }
103}
104
105pub(crate) fn verified_account_id(data: &Value) -> Result<&str, Error> {
106    data["viewer"]["id"]
107        .as_str()
108        .filter(|id| {
109            !id.trim().is_empty()
110                && id.len() <= MAX_ACCOUNT_ID_BYTES
111                && !id.chars().any(char::is_control)
112        })
113        .ok_or_else(|| transport::unexpected("viewer identity"))
114}
115
116fn safe_error(error: Error) -> Error {
117    match error {
118        Error::Status { status, .. } => {
119            transport::status(status, "GitHub rejected the bound read.")
120        }
121        _ => Error::Network("GitHub bound read failed.".into()),
122    }
123}