1use std::collections::HashMap;
4use std::rc::Rc;
5
6use super::crypto::{sign_token, verify_token};
7use super::document::{Document, Field, OperationKind, Selection};
8use super::json::Json;
9use super::store::{DeepStore, ValueKind};
10
11#[derive(Debug, Clone)]
13pub struct GqlError {
14 pub message: String,
15 pub code: &'static str,
16 pub path: String,
17}
18
19impl GqlError {
20 pub fn validation(message: impl Into<String>, path: impl Into<String>) -> Self {
21 Self {
22 message: message.into(),
23 code: "validation-failed",
24 path: path.into(),
25 }
26 }
27
28 pub fn write(message: impl std::fmt::Display) -> Self {
29 let message = message.to_string();
30 let code = if message.contains("Forbidden") {
31 "permission-error"
32 } else if message.contains("violation") {
33 "constraint-violation"
34 } else {
35 "unexpected"
36 };
37 Self {
38 message,
39 code,
40 path: "$".to_string(),
41 }
42 }
43
44 pub fn to_json(&self) -> Json {
45 Json::object(vec![(
46 "errors",
47 Json::Array(vec![Json::object(vec![
48 ("message", Json::str(&*self.message)),
49 (
50 "extensions",
51 Json::object(vec![
52 ("path", Json::str(&*self.path)),
53 ("code", Json::str(self.code)),
54 ]),
55 ),
56 ])]),
57 )])
58 }
59}
60
61pub type GqlResult<T> = Result<T, GqlError>;
62
63#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
65pub struct Auth {
66 pub user: Option<i64>,
68 pub admin: bool,
69}
70
71pub struct Settings {
73 pub secret: Vec<u8>,
74 pub admin_secret: Option<String>,
75 introspection: Json,
76}
77
78impl Settings {
79 pub fn new(secret: Vec<u8>, admin_secret: Option<String>) -> Self {
80 let introspection = Json::parse(include_str!("introspection.json"))
81 .ok()
82 .and_then(|json| json.get("data").cloned())
83 .unwrap_or(Json::Null);
84 Self {
85 secret,
86 admin_secret,
87 introspection,
88 }
89 }
90
91 pub fn random_secret() -> Vec<u8> {
93 use std::io::Read;
94 let mut bytes = vec![0; 32];
95 std::fs::File::open("/dev/urandom")
96 .and_then(|mut random| random.read_exact(&mut bytes))
97 .map(|()| bytes)
98 .unwrap_or_else(|_| {
99 use std::hash::{BuildHasher, Hasher};
100 (0..4)
101 .flat_map(|_| {
102 let hasher = std::collections::hash_map::RandomState::new().build_hasher();
103 hasher.finish().to_le_bytes()
104 })
105 .collect()
106 })
107 }
108
109 pub fn authorize(
111 &self,
112 authorization: Option<&str>,
113 admin_secret: Option<&str>,
114 ) -> Result<Auth, String> {
115 let admin = match (&self.admin_secret, admin_secret) {
116 (Some(expected), Some(given)) if expected == given => true,
117 (_, Some(_)) => return Err("invalid x-hasura-admin-secret".to_string()),
118 _ => false,
119 };
120 let token = authorization
121 .map(|value| value.strip_prefix("Bearer ").unwrap_or(value).trim())
122 .filter(|token| !token.is_empty());
123 let user = match token {
124 None => None,
125 Some(token) => Some(
126 verify_token(&self.secret, token, now())
127 .map(|id| id as i64)
128 .map_err(|error| format!("Could not verify JWT: {error}"))?,
129 ),
130 };
131 Ok(Auth { user, admin })
132 }
133}
134
135fn now() -> u64 {
136 std::time::SystemTime::now()
137 .duration_since(std::time::UNIX_EPOCH)
138 .map_or(0, |elapsed| elapsed.as_secs())
139}
140
141pub struct Exec<'a, 's> {
143 pub store: &'a mut DeepStore<'s>,
144 pub settings: &'a Settings,
145 pub document: &'a Document,
146 pub variables: &'a Json,
147 pub auth: Auth,
148 pub subject: u32,
150 pub memo: HashMap<String, Rc<std::collections::HashSet<String>>>,
152}
153
154pub fn execute(
156 store: &mut DeepStore,
157 settings: &Settings,
158 query: &str,
159 operation: Option<&str>,
160 variables: &Json,
161 auth: Auth,
162) -> (Json, bool) {
163 let document = match Document::parse(query) {
164 Ok(document) => document,
165 Err(error) => {
166 return (
167 GqlError::validation(error.to_string(), "$.query").to_json(),
168 false,
169 );
170 }
171 };
172 let selected = match document.operation(operation) {
173 Ok(selected) => selected,
174 Err(error) => {
175 return (
176 GqlError::validation(error.to_string(), "$.query").to_json(),
177 false,
178 );
179 }
180 };
181 let mut defaults: Vec<(String, Json)> = match variables {
183 Json::Object(pairs) => pairs.clone(),
184 _ => Vec::new(),
185 };
186 for (name, default) in &selected.variables {
187 if let (Some(default), None) = (default, variables.get(name)) {
188 defaults.push((name.clone(), default.resolve(&Json::Null)));
189 }
190 }
191 let variables = Json::Object(defaults);
192 store.admin = auth.admin;
193 let subject = auth.user.and_then(|id| store.triplet_of(id)).unwrap_or(0);
194 let mut exec = Exec {
195 store,
196 settings,
197 document: &document,
198 variables: &variables,
199 auth,
200 subject,
201 memo: HashMap::new(),
202 };
203 let mutation = selected.kind == OperationKind::Mutation;
204 if mutation {
205 exec.store.begin();
206 }
207 let result = exec.root(&selected.selections, mutation);
208 let response = match result {
209 Ok(data) => {
210 if mutation {
211 if let Err(error) = exec.store.commit() {
212 return (GqlError::write(error).to_json(), false);
213 }
214 }
215 (Json::object(vec![("data", data)]), mutation)
216 }
217 Err(error) => {
218 if mutation {
219 if let Err(undo) = exec.store.rollback() {
220 return (GqlError::write(undo).to_json(), false);
221 }
222 }
223 (error.to_json(), false)
224 }
225 };
226 exec.store.admin = false;
227 response
228}
229
230impl<'a> Exec<'a, '_> {
231 pub fn flatten(
233 &self,
234 selections: &'a [Selection],
235 typename: &str,
236 ) -> GqlResult<Vec<&'a Field>> {
237 let mut fields = Vec::new();
238 self.collect(selections, typename, &mut fields, 0)?;
239 Ok(fields)
240 }
241
242 fn included(&self, directives: &[super::document::Directive]) -> bool {
243 directives.iter().all(|directive| {
244 let condition = directive
245 .arguments
246 .iter()
247 .find(|(name, _)| name == "if")
248 .map(|(_, value)| value.resolve(self.variables));
249 !matches!(
250 (directive.name.as_str(), condition),
251 ("skip", Some(Json::Bool(true))) | ("include", Some(Json::Bool(false)))
252 )
253 })
254 }
255
256 fn collect(
257 &self,
258 selections: &'a [Selection],
259 typename: &str,
260 out: &mut Vec<&'a Field>,
261 depth: usize,
262 ) -> GqlResult<()> {
263 if depth > 64 {
264 return Err(GqlError::validation(
265 "fragments are nested too deeply",
266 "$.query",
267 ));
268 }
269 for selection in selections {
270 match selection {
271 Selection::Field(field) => {
272 if self.included(&field.directives)
273 && !out
274 .iter()
275 .any(|seen| seen.response_key() == field.response_key())
276 {
277 out.push(field);
278 }
279 }
280 Selection::Spread(name, directives) => {
281 if self.included(directives) {
282 let Some(fragment) = self.document.fragments.get(name) else {
283 return Err(GqlError::validation(
284 format!("fragment '{name}' is undefined"),
285 "$.query",
286 ));
287 };
288 self.collect(fragment, typename, out, depth + 1)?;
289 }
290 }
291 Selection::Inline(on, directives, inner) => {
292 let applies = on.as_deref().is_none_or(|on| on == typename);
293 if applies && self.included(directives) {
294 self.collect(inner, typename, out, depth + 1)?;
295 }
296 }
297 }
298 }
299 Ok(())
300 }
301
302 fn root(&mut self, selections: &'a [Selection], mutation: bool) -> GqlResult<Json> {
303 let typename = if mutation {
304 "mutation_root"
305 } else {
306 "query_root"
307 };
308 let mut data = Vec::new();
309 for field in self.flatten(selections, typename)? {
310 self.memo.clear();
311 let value = self.root_field(field, typename, mutation)?;
312 data.push((field.response_key().to_string(), value));
313 }
314 Ok(Json::Object(data))
315 }
316
317 fn root_field(&mut self, field: &'a Field, root: &str, mutation: bool) -> GqlResult<Json> {
318 let name = field.name.as_str();
319 if name == "__typename" {
320 return Ok(Json::str(root));
321 }
322 if mutation {
323 if let Some(found) = self.mutation_field(field)? {
324 return Ok(found);
325 }
326 } else {
327 match name {
328 "__schema" => {
329 let schema = self
330 .settings
331 .introspection
332 .get("__schema")
333 .cloned()
334 .unwrap_or(Json::Null);
335 return self.project_schema(&schema, &field.selections, "__Schema");
336 }
337 "__type" => {
338 let wanted = field.argument("name", self.variables);
339 let found = self
340 .settings
341 .introspection
342 .get("__schema")
343 .and_then(|schema| schema.get("types"))
344 .map(Json::as_list)
345 .unwrap_or_default()
346 .into_iter()
347 .find(|item| {
348 item.get("name").and_then(Json::as_str)
349 == wanted.as_ref().and_then(Json::as_str)
350 })
351 .cloned()
352 .unwrap_or(Json::Null);
353 return self.project_schema(&found, &field.selections, "__Type");
354 }
355 "guest" => return self.guest(field),
356 "jwt" => return self.jwt(field),
357 _ => {}
358 }
359 if let Some(found) = self.select_field(field)? {
360 return Ok(found);
361 }
362 }
363 Err(GqlError::validation(
364 format!("field '{name}' not found in type: '{root}'"),
365 format!("$.selectionSet.{name}"),
366 ))
367 }
368
369 fn project_schema(
371 &self,
372 value: &Json,
373 selections: &'a [Selection],
374 typename: &str,
375 ) -> GqlResult<Json> {
376 match value {
377 Json::Array(items) => Ok(Json::Array(
378 items
379 .iter()
380 .map(|item| self.project_schema(item, selections, typename))
381 .collect::<GqlResult<_>>()?,
382 )),
383 Json::Object(_) => {
384 let mut out = Vec::new();
385 for field in self.flatten(selections, typename)? {
386 let name = field.name.as_str();
387 let found = if name == "__typename" {
388 Json::str(typename)
389 } else {
390 let inner = value.get(name).cloned().unwrap_or(Json::Null);
391 let next = match name {
392 "queryType" | "mutationType" | "subscriptionType" | "types"
393 | "type" | "ofType" | "interfaces" | "possibleTypes" => "__Type",
394 "fields" => "__Field",
395 "args" | "inputFields" => "__InputValue",
396 "enumValues" => "__EnumValue",
397 "directives" => "__Directive",
398 _ => typename,
399 };
400 if field.selections.is_empty() {
401 inner
402 } else {
403 self.project_schema(&inner, &field.selections, next)?
404 }
405 };
406 out.push((field.response_key().to_string(), found));
407 }
408 Ok(Json::Object(out))
409 }
410 other => Ok(other.clone()),
411 }
412 }
413
414 fn token_response(
415 &mut self,
416 field: &'a Field,
417 typename: &str,
418 id: Option<i64>,
419 error: Option<String>,
420 ) -> GqlResult<Json> {
421 let token = id.map(|id| sign_token(&self.settings.secret, id as u64, now()));
422 let mut out = Vec::new();
423 for item in self.flatten(&field.selections, typename)? {
424 let value = match item.name.as_str() {
425 "__typename" => Json::str(typename),
426 "token" => token.clone().map_or(Json::Null, Json::String),
427 "linkId" => id.map_or(Json::Null, Json::Int),
428 "error" => error.clone().map_or(Json::Null, Json::String),
429 other => {
430 return Err(GqlError::validation(
431 format!("field '{other}' not found in type: '{typename}'"),
432 format!("$.selectionSet.{}.{other}", field.name),
433 ))
434 }
435 };
436 out.push((item.response_key().to_string(), value));
437 }
438 Ok(Json::Object(out))
439 }
440
441 fn guest(&mut self, field: &'a Field) -> GqlResult<Json> {
444 self.store.begin();
445 let admin = std::mem::replace(&mut self.store.admin, true);
446 let created = self.create_guest();
447 self.store.admin = admin;
448 match created {
449 Ok(id) => {
450 self.store.commit().map_err(GqlError::write)?;
451 self.token_response(field, "GuestOutput", Some(id), None)
452 }
453 Err(error) => {
454 self.store.rollback().map_err(GqlError::write)?;
455 Err(GqlError::write(error))
456 }
457 }
458 }
459
460 fn create_guest(&mut self) -> anyhow::Result<i64> {
461 let user = self.core_id("User");
462 let id = self.store.reserve(1)[0];
463 self.store
464 .create_link(0, Some(id), user.unwrap_or(id), 0, 0)?;
465 if let (Some(join), Some(users)) =
467 (self.core_id("Join"), self.contained_in("deep", "users"))
468 {
469 self.store.create_link(0, None, join, users, id)?;
470 }
471 Ok(id)
472 }
473
474 fn jwt(&mut self, field: &'a Field) -> GqlResult<Json> {
477 let target = field
478 .argument("input", self.variables)
479 .and_then(|input| input.get("linkId").and_then(Json::as_i64));
480 let asker = self.auth.user;
481 let Some(target) = target.or(asker) else {
482 return self.token_response(
483 field,
484 "JWTOutput",
485 None,
486 Some("No link and no subject.".to_string()),
487 );
488 };
489 let permitted = self.auth.admin || !self.store.has_policy() || asker == Some(target);
490 if !permitted {
491 return self.token_response(field, "JWTOutput", None, Some("Forbidden.".to_string()));
492 }
493 if self.store.triplet_of(target).is_none() {
494 return self.token_response(
495 field,
496 "JWTOutput",
497 None,
498 Some(format!("No link {target}.")),
499 );
500 }
501 self.token_response(field, "JWTOutput", Some(target), None)
502 }
503
504 pub fn contained_in(&mut self, package: &str, name: &str) -> Option<i64> {
506 let contains: Vec<i64> = self
507 .store
508 .values()
509 .filter(|(_, row)| row.kind == ValueKind::String && row.value.as_str() == Some(name))
510 .map(|(_, row)| row.owner)
511 .collect();
512 contains.into_iter().find_map(|contain| {
513 let triplet = self.store.triplet_of(contain)?;
514 let row = self.raw_row(triplet)?;
515 let (_, parent) = self.store.value_of_owner(ValueKind::String, row.from_id)?;
516 (parent.value.as_str() == Some(package)).then_some(row.to_id)
517 })
518 }
519
520 pub fn core_id(&mut self, name: &str) -> Option<i64> {
522 self.contained_in("@deep-foundation/core", name)
523 }
524}