1use 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
25const WORK_VIEWER_QUERY: &str = "query WorkViewer { viewer { id login } }";
28
29#[derive(Clone)]
31pub(crate) struct Owner {
32 login: String,
33 account_id: String,
34}
35
36pub struct PinnedWork<'a> {
40 pub(crate) client: &'a Client,
41 pub(crate) credential: Credential,
42 owner: Owner,
43}
44
45pub(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
75fn 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
116fn 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 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 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 #[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 pub fn login(&self) -> &str {
193 &self.owner.login
194 }
195
196 pub fn account_id(&self) -> &str {
200 &self.owner.account_id
201 }
202
203 pub(crate) fn account(&self) -> String {
205 transport::account_label(&self.credential, Some(&self.owner.login))
206 }
207
208 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 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 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 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}