Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
121 changes: 103 additions & 18 deletions src/graphql/auth.rs
Comment thread
shree-iyengar-dls marked this conversation as resolved.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

use std::str::FromStr;

use async_graphql::{Error, ErrorExtensions};
use axum_extra::headers::authorization::Bearer;
use axum_extra::headers::Authorization;
use derive_more::{Display, Error, From};
Expand Down Expand Up @@ -186,15 +187,27 @@ pub enum AuthError {
Missing,
}

impl ErrorExtensions for AuthError {
fn extend(&self) -> Error {
self.extend_with(|err, e| match err {
AuthError::ServerError(_) => e.set("code", "AUTH_SERVER_ERROR"),
AuthError::Failed => e.set("code", "AUTH_FAILED"),
AuthError::Missing => e.set("code", "AUTH_MISSING"),
})
}
}

#[cfg(test)]
mod tests {
use std::str::FromStr as _;

use assert_matches::assert_matches;
use async_graphql::{ErrorExtensions, Value};
use axum::http::HeaderValue;
use axum_extra::headers::authorization::{Bearer, Credentials};
use axum_extra::headers::Authorization;
use httpmock::MockServer;
use reqwest::Client;
use rstest::rstest;
use serde_json::json;

Expand Down Expand Up @@ -346,6 +359,22 @@ mod tests {
mock.assert();
}

fn check_auth_error_and_exts(
result: Result<(), AuthError>,
expected_auth_err_type: fn(&AuthError) -> bool,
expected_error_extension: String,
) {
let err = result.expect_err("Expected error");
assert!(expected_auth_err_type(&err), "Unexpected error type");

let extensions = err
.extend()
.extensions
.expect("Error should contain extensions");
let code = extensions.get("code").unwrap();
assert_eq!(code, &Value::String(expected_error_extension))
}

#[tokio::test]
async fn denied_check_instrument_admin() {
let server = MockServer::start();
Expand All @@ -371,9 +400,16 @@ mod tests {
let result = check
.check_instrument_admin(token("token").as_ref(), "i22")
.await;
let Err(AuthError::Failed) = result else {
panic!("Unexpected result from unauthorised check: {result:?}");
};

check_auth_error_and_exts(
result,
|e| matches!(e, AuthError::Failed),
"AUTH_FAILED".to_string(),
);

//let Err(AuthError::Failed) = result else {
// panic!("Unexpected result from unauthorised check: {result:?}");
//};
mock.assert();
}

Expand All @@ -399,9 +435,16 @@ mod tests {
admin_query: "demo/admin".into(),
});
let result = check.check_admin(token("token").as_ref()).await;
let Err(AuthError::Failed) = result else {
panic!("Unexpected result from unauthorised check: {result:?}");
};

check_auth_error_and_exts(
result,
|e| matches!(e, AuthError::Failed),
"AUTH_FAILED".to_string(),
);

//let Err(AuthError::Failed) = result else {
// panic!("Unexpected result from unauthorised check: {result:?}");
//};
mock.assert();
}

Expand All @@ -419,9 +462,16 @@ mod tests {
admin_query: "demo/admin".into(),
});
let result = check.check_access(None, "i22", "cm1234-4").await;
let Err(AuthError::Missing) = result else {
panic!("Unexpected result from unauthorised check: {result:?}");
};

check_auth_error_and_exts(
result,
|e| matches!(e, AuthError::Missing),
"AUTH_MISSING".to_string(),
);

//let Err(AuthError::Missing) = result else {
// panic!("Unexpected result from unauthorised check: {result:?}");
//};
mock.assert_calls(0);
}

Expand All @@ -439,9 +489,16 @@ mod tests {
admin_query: "demo/admin".into(),
});
let result = check.check_instrument_admin(None, "i22").await;
let Err(AuthError::Missing) = result else {
panic!("Unexpected result from unauthorised check: {result:?}");
};

check_auth_error_and_exts(
result,
|e| matches!(e, AuthError::Missing),
"AUTH_MISSING".to_string(),
);

//let Err(AuthError::Missing) = result else {
// panic!("Unexpected result from unauthorised check: {result:?}");
//};
mock.assert_calls(0);
}

Expand All @@ -459,9 +516,16 @@ mod tests {
admin_query: "demo/admin".into(),
});
let result = check.check_admin(None).await;
let Err(AuthError::Missing) = result else {
panic!("Unexpected result from unauthorised check: {result:?}");
};

check_auth_error_and_exts(
result,
|e| matches!(e, AuthError::Missing),
"AUTH_MISSING".to_string(),
);

//let Err(AuthError::Missing) = result else {
// panic!("Unexpected result from unauthorised check: {result:?}");
//};
mock.assert_calls(0);
}

Expand All @@ -482,9 +546,30 @@ mod tests {
let result = check
.check_instrument_admin(token("token").as_ref(), "i22")
.await;
let Err(AuthError::ServerError(_)) = result else {
panic!("Unexpected result from unauthorised check: {result:?}");
};

check_auth_error_and_exts(
result,
|e| matches!(e, AuthError::ServerError(_)),
"AUTH_SERVER_ERROR".to_string(),
);

//let Err(AuthError::ServerError(_)) = result else {
// panic!("Unexpected result from unauthorised check: {result:?}");
//};
mock.assert();
}

#[rstest]
#[case::server_error(AuthError::ServerError(Client::new().get("invalid").build().unwrap_err()), "AUTH_SERVER_ERROR")]
#[case::failed(AuthError::Failed, "AUTH_FAILED")]
#[case::missing(AuthError::Missing, "AUTH_MISSING")]
#[tokio::test]
Comment thread
tpoliaw marked this conversation as resolved.

async fn auth_error_extensions(#[case] input: AuthError, #[case] expected: String) {
let e = input.extend();
let extensions = e.extensions.expect("Error should have extensions");
let code = extensions.get("code").unwrap();

assert_eq!(code, &Value::String(expected))
}
}
25 changes: 22 additions & 3 deletions src/graphql/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ use std::path::{Component, PathBuf};
use async_graphql::extensions::Tracing;
use async_graphql::http::GraphiQLSource;
use async_graphql::{
Context, Description, EmptySubscription, InputObject, InputValueError, InputValueResult,
Object, Scalar, ScalarType, Schema, SimpleObject, TypeName, Value,
Context, Description, EmptySubscription, ErrorExtensions, InputObject, InputValueError,
InputValueResult, Object, Scalar, ScalarType, Schema, SimpleObject, TypeName, Value,
};
use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
use auth::{AuthError, PolicyCheck};
Expand Down Expand Up @@ -479,7 +479,7 @@ where
check(policy, token.as_ref())
.await
.inspect_err(|e| info!("Authorization failed: {e:?}"))
.map_err(async_graphql::Error::from)
.map_err(|e| e.extend())
} else {
trace!("No authorization configured");
Ok(())
Expand Down Expand Up @@ -1037,6 +1037,16 @@ mod tests {
result.errors[0].message,
"No authentication token was provided"
);
assert_eq!(
result.errors[0]
.extensions
.as_ref()
.unwrap()
.get("code")
.unwrap(),
&Value::from("AUTH_MISSING")
);

Comment thread
shree-iyengar-dls marked this conversation as resolved.
Outdated
assert_eq!(result.data, Value::Null);
}

Expand All @@ -1063,6 +1073,15 @@ mod tests {

println!("{result:#?}");
assert_eq!(result.errors[0].message, "Authentication failed");
assert_eq!(
result.errors[0]
.extensions
.as_ref()
.unwrap()
.get("code")
.unwrap(),
&Value::from("AUTH_FAILED")
);
assert_eq!(result.data, Value::Null);

// Ensure that the number wasn't incremented
Expand Down
Loading