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