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) -> 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, client.work_account.as_ref())
139            .ok_or_else(|| {
140                no_work_account("No work (EMU) or chosen GitHub account is configured.")
141            })?
142            .clone();
143        let resolve = || {
144            client
145                .credentials
146                .github(Some(&login))
147                .map_err(|error| no_work_account(&error.to_string()))
148        };
149        // A credential GitHub rejects is dropped and resolved once more
150        // before anything is pinned; once pinned, nothing is resolved again.
151        let mut credential = resolve()?;
152        let mut owner = credential_owner(client, &credential, &login);
153        if is_rejected(&owner) {
154            client.credentials.invalidate(&credential);
155            credential = resolve()?;
156            owner = credential_owner(client, &credential, &login);
157            if is_rejected(&owner) {
158                client.credentials.invalidate(&credential);
159            }
160        }
161        let mut owner = owner?;
162        owner.login = verified_work_login(&login, &owner.login)?;
163        Ok(Self {
164            client,
165            credential,
166            owner,
167        })
168    }
169
170    /// The credential of `login`, pinned without a viewer read, for tests
171    /// of what a pinned operation sends.
172    #[cfg(test)]
173    pub(crate) fn for_tests(
174        client: &'a Client,
175        login: &str,
176        account_id: &str,
177    ) -> Result<Self, Error> {
178        Ok(Self {
179            client,
180            credential: client.credentials.github(Some(login))?,
181            owner: Owner {
182                login: login.to_owned(),
183                account_id: account_id.to_owned(),
184            },
185        })
186    }
187}
188
189impl PinnedWork<'_> {
190    /// The work login, as gh spells it, that GitHub verified the credential
191    /// belongs to.
192    pub fn login(&self) -> &str {
193        &self.owner.login
194    }
195
196    /// The immutable node ID of the account the credential belongs to. Key
197    /// anything kept per account by it: a login can be renamed and reused.
198    // qual:api - Consumed by app crates through the Framework facade.
199    pub fn account_id(&self) -> &str {
200        &self.owner.account_id
201    }
202
203    /// The account messages name.
204    pub(crate) fn account(&self) -> String {
205        transport::account_label(&self.credential, Some(&self.owner.login))
206    }
207
208    /// Passes `result` through. A 401 drops the pinned credential from the
209    /// cache, so the next operation resolves and verifies one afresh; this
210    /// one is not retried with another.
211    pub(crate) fn checked<T>(&self, result: Result<T, Error>) -> Result<T, Error> {
212        if is_rejected(&result) {
213            self.client.credentials.invalidate(&self.credential);
214            forget_verified(self.client, &self.credential);
215        }
216        result
217    }
218
219    /// One GraphQL read with the pinned credential.
220    pub(crate) fn graphql<T: DeserializeOwned>(
221        &self,
222        query: &str,
223        variables: Value,
224    ) -> Result<T, Error> {
225        let account = self.account();
226        let body = json!({ "query": query, "variables": variables }).to_string();
227        let response = self.checked(transport::post_graphql(
228            &format!("{}/graphql", self.client.api_url),
229            &self.credential,
230            &account,
231            &body,
232        ))?;
233        let data = transport::graphql_data(&account, response, false)?;
234        serde_json::from_value(data).map_err(|_| unexpected("response"))
235    }
236
237    /// One REST GET with the pinned credential, at `version` of the API.
238    pub(crate) fn get(&self, url: &str, version: Option<&str>) -> Result<Response<Body>, Error> {
239        let account = self.account();
240        self.checked(match version {
241            Some(version) => {
242                transport::get_rest_version(url, &self.credential, &account, JSON, version)
243            }
244            None => transport::get_rest(url, &self.credential, &account, JSON),
245        })
246    }
247
248    /// One REST JSON read with the pinned credential.
249    pub(crate) fn rest_json<T: DeserializeOwned>(&self, url: &str) -> Result<T, Error> {
250        let bytes = transport::read_limited(self.get(url, None)?, MAX_BODY_BYTES)?;
251        serde_json::from_slice(&bytes).map_err(|_| unexpected("response"))
252    }
253}