Skip to main content

subspace_client_github/
work.rs

1//! The work credential pinned for one operation.
2//!
3//! [`Client::pin_work`] resolves the work account's credential once and
4//! verifies, with that very credential, whose it is. Every request the
5//! operation then makes goes out with that credential and nothing else: no
6//! request looks the credential up again, and a rejected one is not retried
7//! with whichever credential the account holds by then. So an answer is
8//! always the answer for the account the operation names, even when the
9//! credential changes while the operation runs.
10
11use std::sync::PoisonError;
12
13use serde::de::DeserializeOwned;
14use serde_json::{Value, json};
15use sha2::{Digest, Sha256};
16use subspace_core::credentials::Credential;
17use subspace_core::http::Error;
18use subspace_core::http::status as http_status;
19use ureq::Body;
20use ureq::http::Response;
21
22use crate::transport::{self, JSON, unexpected};
23use crate::{Client, MAX_BODY_BYTES, pick_work_login, validate, verified_work_login};
24
25/// The viewer read that verifies a work credential: its login and its
26/// immutable node ID.
27const WORK_VIEWER_QUERY: &str = "query WorkViewer { viewer { id login } }";
28
29/// The account GitHub verified a credential belongs to.
30#[derive(Clone)]
31pub(crate) struct Owner {
32    login: String,
33    account_id: String,
34}
35
36/// The work account's credential and the account GitHub verified it belongs
37/// to, for one operation. It borrows the client and is never stored,
38/// serialized or printed.
39pub struct PinnedWork<'a> {
40    pub(crate) client: &'a Client,
41    pub(crate) credential: Credential,
42    owner: Owner,
43}
44
45/// Whose a credential is, remembered by its fingerprint. A token's owner
46/// never changes, so a credential verified once this run need not be
47/// verified again; a new token, for another account or the same one, is a
48/// new fingerprint and is verified afresh.
49pub(crate) struct Verified {
50    fingerprint: Vec<u8>,
51    owner: Owner,
52}
53
54fn fingerprint(credential: &Credential) -> Vec<u8> {
55    Sha256::digest(credential.value.expose().as_bytes()).to_vec()
56}
57
58fn no_work_account(message: &str) -> Error {
59    Error::Status {
60        status: http_status::BAD_GATEWAY,
61        message: message.into(),
62    }
63}
64
65fn is_rejected<T>(result: &Result<T, Error>) -> bool {
66    matches!(
67        result,
68        Err(Error::Status {
69            status: http_status::UNAUTHORIZED,
70            ..
71        })
72    )
73}
74
75/// The account `credential` belongs to, from the viewer read made with
76/// exactly that credential, or from an earlier such read of the same
77/// credential this run.
78fn credential_owner(client: &Client, credential: &Credential, login: &str) -> Result<Owner, Error> {
79    let fingerprint = fingerprint(credential);
80    if let Some(known) = client
81        .verified
82        .lock()
83        .unwrap_or_else(PoisonError::into_inner)
84        .as_ref()
85        .filter(|known| known.fingerprint == fingerprint)
86    {
87        return Ok(known.owner.clone());
88    }
89    let account = transport::account_label(credential, Some(login));
90    let body = json!({ "query": WORK_VIEWER_QUERY, "variables": {} }).to_string();
91    let response = transport::post_graphql(
92        &format!("{}/graphql", client.api_url),
93        credential,
94        &account,
95        &body,
96    )?;
97    let data = transport::graphql_data(&account, response, false)?;
98    let actual = data["viewer"]["login"]
99        .as_str()
100        .ok_or_else(|| unexpected("viewer"))?;
101    validate::check_login(actual)?;
102    let owner = Owner {
103        login: actual.to_owned(),
104        account_id: crate::bound::verified_account_id(&data)?.to_owned(),
105    };
106    *client
107        .verified
108        .lock()
109        .unwrap_or_else(PoisonError::into_inner) = Some(Verified {
110        fingerprint,
111        owner: owner.clone(),
112    });
113    Ok(owner)
114}
115
116/// Forgets whose `credential` is, once GitHub rejected it.
117fn forget_verified(client: &Client, credential: &Credential) {
118    let fingerprint = fingerprint(credential);
119    let mut verified = client
120        .verified
121        .lock()
122        .unwrap_or_else(PoisonError::into_inner);
123    if verified
124        .as_ref()
125        .is_some_and(|known| known.fingerprint == fingerprint)
126    {
127        *verified = None;
128    }
129}
130
131impl<'a> PinnedWork<'a> {
132    /// Resolves the work account's credential once and verifies whose it is
133    /// with that same credential ([`Client::pin_work`]).
134    pub(crate) fn pin(client: &'a Client, chosen: Option<&str>) -> Result<Self, Error> {
135        let accounts = client.credentials.github_accounts().map_err(|_| {
136            no_work_account("No GitHub accounts are configured for the work account.")
137        })?;
138        let login = pick_work_login(&accounts.logins, chosen).ok_or_else(|| {
139            no_work_account("No work (EMU) or chosen GitHub account is configured.")
140        })?;
141        Self::for_login(client, login)
142    }
143
144    pub(crate) fn for_login(client: &'a Client, login: &str) -> Result<Self, Error> {
145        validate::check_login(login)?;
146        let resolve = || {
147            client
148                .credentials
149                .github(Some(login))
150                .map_err(|error| no_work_account(&error.to_string()))
151        };
152        // A credential GitHub rejects is dropped and resolved once more
153        // before anything is pinned; once pinned, nothing is resolved again.
154        let mut credential = resolve()?;
155        let mut owner = credential_owner(client, &credential, login);
156        if is_rejected(&owner) {
157            client.credentials.invalidate(&credential);
158            credential = resolve()?;
159            owner = credential_owner(client, &credential, login);
160            if is_rejected(&owner) {
161                client.credentials.invalidate(&credential);
162            }
163        }
164        let mut owner = owner?;
165        owner.login = verified_work_login(login, &owner.login)?;
166        Ok(Self {
167            client,
168            credential,
169            owner,
170        })
171    }
172
173    /// The credential of `login`, pinned without a viewer read, for tests
174    /// of what a pinned operation sends.
175    #[cfg(test)]
176    pub(crate) fn for_tests(
177        client: &'a Client,
178        login: &str,
179        account_id: &str,
180    ) -> Result<Self, Error> {
181        Ok(Self {
182            client,
183            credential: client.credentials.github(Some(login))?,
184            owner: Owner {
185                login: login.to_owned(),
186                account_id: account_id.to_owned(),
187            },
188        })
189    }
190}
191
192impl PinnedWork<'_> {
193    /// The work login, as gh spells it, that GitHub verified the credential
194    /// belongs to.
195    pub fn login(&self) -> &str {
196        &self.owner.login
197    }
198
199    /// The immutable node ID of the account the credential belongs to. Key
200    /// anything kept per account by it: a login can be renamed and reused.
201    // qual:api - Consumed by app crates through the Framework facade.
202    pub fn account_id(&self) -> &str {
203        &self.owner.account_id
204    }
205
206    /// The account messages name.
207    pub(crate) fn account(&self) -> String {
208        transport::account_label(&self.credential, Some(&self.owner.login))
209    }
210
211    /// Passes `result` through. A 401 drops the pinned credential from the
212    /// cache, so the next operation resolves and verifies one afresh; this
213    /// one is not retried with another.
214    pub(crate) fn checked<T>(&self, result: Result<T, Error>) -> Result<T, Error> {
215        if is_rejected(&result) {
216            self.client.credentials.invalidate(&self.credential);
217            forget_verified(self.client, &self.credential);
218        }
219        result
220    }
221
222    /// One GraphQL read with the pinned credential.
223    pub(crate) fn graphql<T: DeserializeOwned>(
224        &self,
225        query: &str,
226        variables: Value,
227    ) -> Result<T, Error> {
228        let account = self.account();
229        let body = json!({ "query": query, "variables": variables }).to_string();
230        let response = self.checked(transport::post_graphql(
231            &format!("{}/graphql", self.client.api_url),
232            &self.credential,
233            &account,
234            &body,
235        ))?;
236        let data = transport::graphql_data(&account, response, false)?;
237        serde_json::from_value(data).map_err(|_| unexpected("response"))
238    }
239
240    /// One REST GET with the pinned credential, at `version` of the API.
241    pub(crate) fn get(&self, url: &str, version: Option<&str>) -> Result<Response<Body>, Error> {
242        let account = self.account();
243        self.checked(match version {
244            Some(version) => {
245                transport::get_rest_version(url, &self.credential, &account, JSON, version)
246            }
247            None => transport::get_rest(url, &self.credential, &account, JSON),
248        })
249    }
250
251    /// One REST JSON read with the pinned credential.
252    pub(crate) fn rest_json<T: DeserializeOwned>(&self, url: &str) -> Result<T, Error> {
253        let bytes = transport::read_limited(self.get(url, None)?, MAX_BODY_BYTES)?;
254        serde_json::from_slice(&bytes).map_err(|_| unexpected("response"))
255    }
256}