Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions backend/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ bunt = "0.2.7"
bytes = "1"
chrono = { version = "0.4", default-features = false, features = ["serde", "std"] }
clap = { version = "4.2.2", features = ["derive", "string"] }
confique = { version = "0.4", features = ["toml"] }
confique = { version = "0.4.1", features = ["toml"] }
cookie = "0.18.0"
deadpool = { version = "0.13.1", default-features = false, features = ["managed", "rt_tokio_1"] }
deadpool-postgres = { version = "0.14.2", default-features = false, features = ["rt_tokio_1"] }
Expand Down Expand Up @@ -91,6 +91,9 @@ procfs = "0.18.0"
[target.'cfg(not(target_env = "msvc"))'.dependencies]
tikv-jemallocator = "0.7"

[dev-dependencies]
assert-json-diff = "2.0.2"

[build-dependencies]
built = { version = "0.8", features = ["chrono", "git2"] }

Expand Down
142 changes: 142 additions & 0 deletions backend/src/api/execute.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
use juniper::{graphql_value, http::{GraphQLRequest, GraphQLResponse}, GraphQLError};
use std::fmt;

use crate::prelude::*;
use super::{Context, RootNode};


/// The result of successfully executing a GraphQL request, with some metadata.
pub(crate) struct ExecuteOutput {
/// The response to send to the client. Might still contain GraphQL errors.
pub(crate) response: GraphQLResponse,

/// Number of SQL queries executed while resolving the request.
pub(crate) num_queries: u32,
}

/// Errors of `execute` that cannot be expressed as `GraphQLResponse`.
#[derive(Debug)]
pub(crate) enum ExecuteError {
/// The request could not be executed at all, e.g. because the query is
/// invalid.
InvalidRequest(GraphQLError),

/// Committing the DB transaction failed after successful execution. The
/// DB error was already logged.
Commit,
}

/// Executes the given GraphQL request. The DB transaction in `context` is
/// committed if there were no errors, and rolled back otherwise.
pub(crate) async fn execute(
root: &RootNode,
context: Context,
req: &GraphQLRequest,
) -> Result<ExecuteOutput, ExecuteError> {
struct GqlReqPrinter<'a>(&'a GraphQLRequest);
impl fmt::Display for GqlReqPrinter<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "Query:\n{}", self.0.query)?;
writeln!(f, "Operation name: {:?}", self.0.operation_name)?;
writeln!(f, "Variables: {}", serde_json::to_string_pretty(&self.0.variables).unwrap())?;
Ok(())
}
}


let gql_result = juniper::execute(
&req.query,
req.operation_name.as_deref(),
root,
&req.variables(),
&context,
).await;

// Get some values out of the context before dropping it
let num_queries = context.db.num_queries();
let tx = context.db;


// Check if any errors occured.
macro_rules! log_and_rollback {
() => {
debug!("Failed request:\n{}", GqlReqPrinter(req));
debug!("Rolling back DB transaction...");
if let Err(e) = tx.rollback().await {
error!("Failed to rollback transaction: {e}\nWill give up now. Transaction \
should be rolled back automatically since it won't be committed.");
}
};
}

let response = match gql_result {
Err(e) => {
// This kind of error only seems to happen when there is something
// wrong with the request. It's unlikely that any SQL queries have
// been executed, but we roll back the transaction anyway.
warn!("GraphQL request error: {e}");
log_and_rollback!();
return Err(ExecuteError::InvalidRequest(e));
}

Ok((value, errors)) if !errors.is_empty() => {
let error_to_msg = |e: &juniper::ExecutionError<juniper::DefaultScalarValue>| {
format!("{} (at `{}`)", e.error().message(), e.path().join("."))
};

warn!(
"Error{} during GraphQL execution: {}",
if errors.len() > 1 { "s" } else { "" },
if errors.len() > 1 {
errors.iter().map(|e| format!("\n- {}", error_to_msg(e))).collect::<String>()
} else {
error_to_msg(&errors[0])
},
);
log_and_rollback!();

// We just return all errors as normal GraphQL errors, BUT we return
// no regular data as that might contain data from the DB
// transaction that was rolled back. That is, with the exception of
// `currentUser` which contains no data from the DB at all. That's
// what the following code does: inspect the prepared value and
// extract only what we can give out.
let mut data = juniper::Value::Null;
let user = value.as_object_value()
.and_then(|o| o.get_field_value("currentUser"))
.and_then(|v| v.as_object_value());
if let Some(user) = user {
// Not even all fields are allowed. `myVideos` for example
// contains DB data.
let allowed_fields = [
"username", "displayName", "roles", "email",
"canUpload", "canUseStudio", "canUseEditor",
];
let filtered = user.clone().into_iter()
.filter(|(k, _)| allowed_fields.contains(&k.as_str()))
.collect::<juniper::Object<juniper::DefaultScalarValue>>();
data = graphql_value!({ "currentUser": filtered });
}

GraphQLResponse::from_result(Ok((data, errors)))
}

Ok((value, _)) => {
// There was no error dealing with this request so we can commit the DB
// transaction now.
if let Err(e) = tx.commit().await {
// If commiting failed, we would like to retry a couple times, but for
// now we just immediately reply 5xx.
//
// TODO: put all of this code in a loop and retry a couple times.
error!("Failed to commit transaction for API request: {}", e);
debug!("Request:\n{}", GqlReqPrinter(req));
return Err(ExecuteError::Commit);
};

GraphQLResponse::from_result(Ok((value, vec![])))
}
};

Ok(ExecuteOutput { response, num_queries })
}
25 changes: 24 additions & 1 deletion backend/src/api/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub type IdKind = [u8; 2];
///
/// Each key is encoded as 12 byte ASCII string.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, GraphQLScalar)]
#[serde(try_from = "String", into = "String")]
#[graphql(
name = "ID",
description = "An opaque, globally-unique identifier",
Expand Down Expand Up @@ -51,7 +52,7 @@ macro_rules! define_kinds {
$(
pub(crate) const [<$name:upper _KIND>]: IdKind = *$val;

pub(crate) fn $name(key: Key) -> Self {
pub(crate) const fn $name(key: Key) -> Self {
Self {
kind: Self:: [<$name:upper _KIND>],
key,
Expand Down Expand Up @@ -169,6 +170,20 @@ impl fmt::Display for Id {
}
}

impl TryFrom<String> for Id {
type Error = &'static str;

fn try_from(s: String) -> Result<Self, Self::Error> {
s.parse()
}
}

impl From<Id> for String {
fn from(id: Id) -> Self {
id.to_string()
}
}

#[cfg(test)]
mod tests {
use std::str::FromStr;
Expand All @@ -194,6 +209,14 @@ mod tests {
check(Id::SERIES_KIND, u64::MAX, "srP__________");
}

#[test]
fn serde() {
let id = Id::realm(Key(1));
let json = serde_json::to_value(id).unwrap();
assert_eq!(json, serde_json::json!("reAAAAAAAAAAB"));
assert_eq!(serde_json::from_value::<Id>(json).unwrap(), id);
}

#[test]
fn invalid_decode() {
// Wrong length
Expand Down
5 changes: 5 additions & 0 deletions backend/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use self::{
mod common;
mod context;
mod err;
mod execute;
mod id;
mod jwt;
mod model;
Expand All @@ -18,10 +19,14 @@ mod query;
mod subscription;
mod util;

#[cfg(test)]
mod tests;

pub(crate) use self::{
id::Id,
context::Context,
common::{Node, NodeValue},
execute::{execute, ExecuteError},
};


Expand Down
51 changes: 51 additions & 0 deletions backend/src/api/tests/event.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use serde_json::json;

use crate::prelude::*;
use super::util::{TestApi, ADMIN, JOSE_STUDENT, SABINE_INSTRUCTOR};


#[tokio::test]
async fn event_read_access() -> Result<()> {
let api = TestApi::new().await?;
let event = api.db.add_event("Secret", 60, "secret-event", None).await?;
api.db.execute("update events set read_roles = '{ROLE_STAFF}' where id = $1", &[&event]).await?;

let query = r#"query ($id: String!) {
currentUser { username }
eventByOpencastId(id: $id) {
__typename
... on AuthorizedEvent { title }
}
}"#;
let vars = json!({ "id": "secret-event" });

api.query(query).vars(&vars)
.run().await?
.assert_ok(json!({
"currentUser": null,
"eventByOpencastId": { "__typename": "NotAllowed" },
}));

api.query(query).vars(&vars).as_user(&JOSE_STUDENT)
.run().await?
.assert_ok(json!({
"currentUser": { "username": "jose" },
"eventByOpencastId": { "__typename": "NotAllowed" },
}));

api.query(query).vars(&vars).as_user(&SABINE_INSTRUCTOR)
.run().await?
.assert_ok(json!({
"currentUser": { "username": "sabine" },
"eventByOpencastId": { "__typename": "AuthorizedEvent", "title": "Secret" },
}));

api.query(query).vars(&vars).as_user(&ADMIN)
.run().await?
.assert_ok(json!({
"currentUser": { "username": "admin" },
"eventByOpencastId": { "__typename": "AuthorizedEvent", "title": "Secret" },
}));

Ok(())
}
8 changes: 8 additions & 0 deletions backend/src/api/tests/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
//! Tests for the GraphQL API, grouped by topic. Helpers for writing tests are
//! in `util`.

mod util;

mod event;
mod realm;
mod user;
Loading