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, 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 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 #[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 pub fn login(&self) -> &str {
196 &self.owner.login
197 }
198
199 pub fn account_id(&self) -> &str {
203 &self.owner.account_id
204 }
205
206 pub(crate) fn account(&self) -> String {
208 transport::account_label(&self.credential, Some(&self.owner.login))
209 }
210
211 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 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 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 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}