Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Also support Authorization:Bearer header to specify access token #1720

Merged
merged 21 commits into from
Jan 31, 2025
Merged
Show file tree
Hide file tree
Changes from 9 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
54 changes: 47 additions & 7 deletions src/engine/Server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,37 @@
httpServer.run();
}

std::optional<std::string> Server::extractAccessToken(
const ad_utility::httpUtils::HttpRequest auto& request,
const ad_utility::url_parser::ParamValueMap& params) {
std::optional<std::string> tokenFromAuthorizationHeader;
std::optional<std::string> tokenFromParameter;
if (request.find(http::field::authorization) != request.end()) {
string_view authorization = request[http::field::authorization];
const std::string prefix = "Bearer ";
if (!authorization.starts_with(prefix)) {
throw std::runtime_error(
absl::StrCat("Authorization header doesn't start with \"Bearer \"."));
}
authorization.remove_prefix(prefix.length());
tokenFromAuthorizationHeader = std::string(authorization);
}
if (params.contains("access-token")) {
tokenFromParameter = ad_utility::url_parser::getParameterCheckAtMostOnce(
params, "access-token");
}
// If both are specified, they must be equal. This way there is no hidden
// precedence.
if (tokenFromAuthorizationHeader && tokenFromParameter &&
tokenFromAuthorizationHeader != tokenFromParameter) {
throw std::runtime_error(
"Access token is specified both in the `Authorization` Header and the "
"`access-token` parameter, but they aren't the same.");
}
return tokenFromAuthorizationHeader ? std::move(tokenFromAuthorizationHeader)
: std::move(tokenFromParameter);
}

// _____________________________________________________________________________
ad_utility::url_parser::ParsedRequest Server::parseHttpRequest(
const ad_utility::httpUtils::HttpRequest auto& request) {
Expand All @@ -174,7 +205,8 @@
using namespace ad_utility::url_parser::sparqlOperation;
auto parsedUrl = ad_utility::url_parser::parseRequestTarget(request.target());
ad_utility::url_parser::ParsedRequest parsedRequest{
std::move(parsedUrl.path_), std::move(parsedUrl.parameters_), None{}};
std::move(parsedUrl.path_), std::nullopt,
std::move(parsedUrl.parameters_), None{}};

// Some valid requests (e.g. QLever's custom commands like retrieving index
// statistics) don't have a query. So an empty operation is not necessarily an
Expand All @@ -188,9 +220,14 @@
parsedRequest.parameters_.erase(paramName);
}
};
auto extractAccessTokenFromRequest = [&parsedRequest, &request]() {
parsedRequest.accessToken_ =
extractAccessToken(request, parsedRequest.parameters_);
};

if (request.method() == http::verb::get) {
setOperationIfSpecifiedInParams.template operator()<Query>("query");
extractAccessTokenFromRequest();
if (parsedRequest.parameters_.contains("update")) {
throw std::runtime_error("SPARQL Update is not allowed as GET request.");
}
Expand Down Expand Up @@ -260,15 +297,20 @@
}
setOperationIfSpecifiedInParams.template operator()<Query>("query");
setOperationIfSpecifiedInParams.template operator()<Update>("update");
// We parse the access token from the url-encoded parameters in the body.
// The URL parameters must be empty for URL-encoded POST (see above).
extractAccessTokenFromRequest();

return parsedRequest;
}
if (contentType.starts_with(contentTypeSparqlQuery)) {
parsedRequest.operation_ = Query{request.body()};
extractAccessTokenFromRequest();
return parsedRequest;
}
if (contentType.starts_with(contentTypeSparqlUpdate)) {
parsedRequest.operation_ = Update{request.body()};
extractAccessTokenFromRequest();
return parsedRequest;
}
throw std::runtime_error(absl::StrCat(
Expand Down Expand Up @@ -355,8 +397,7 @@
// Check the access token. If an access token is provided and the check fails,
// throw an exception and do not process any part of the query (even if the
// processing had been allowed without access token).
bool accessTokenOk =
checkAccessToken(checkParameter("access-token", std::nullopt));
bool accessTokenOk = checkAccessToken(parsedHttpRequest.accessToken_);

Check warning on line 400 in src/engine/Server.cpp

View check run for this annotation

Codecov / codecov/patch

src/engine/Server.cpp#L400

Added line #L400 was not covered by tests
Qup42 marked this conversation as resolved.
Show resolved Hide resolved
auto requireValidAccessToken = [&accessTokenOk](
const std::string& actionName) {
if (!accessTokenOk) {
Expand Down Expand Up @@ -1160,17 +1201,16 @@
if (!accessToken) {
return false;
}
auto accessTokenProvidedMsg = absl::StrCat(
"Access token \"access-token=", accessToken.value(), "\" provided");
auto requestIgnoredMsg = ", request is ignored";
const auto accessTokenProvidedMsg = "Access token was provided";
const auto requestIgnoredMsg = ", request is ignored";

Check warning on line 1205 in src/engine/Server.cpp

View check run for this annotation

Codecov / codecov/patch

src/engine/Server.cpp#L1204-L1205

Added lines #L1204 - L1205 were not covered by tests
if (accessToken_.empty()) {
throw std::runtime_error(absl::StrCat(
accessTokenProvidedMsg,
" but server was started without --access-token", requestIgnoredMsg));
} else if (!ad_utility::constantTimeEquals(accessToken.value(),
accessToken_)) {
throw std::runtime_error(absl::StrCat(
accessTokenProvidedMsg, " but not correct", requestIgnoredMsg));
accessTokenProvidedMsg, " but it was invalid", requestIgnoredMsg));

Check warning on line 1213 in src/engine/Server.cpp

View check run for this annotation

Codecov / codecov/patch

src/engine/Server.cpp#L1213

Added line #L1213 was not covered by tests
} else {
LOG(DEBUG) << accessTokenProvidedMsg << " and correct" << std::endl;
return true;
Expand Down
7 changes: 7 additions & 0 deletions src/engine/Server.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class Server {
FRIEND_TEST(ServerTest, parseHttpRequest);
FRIEND_TEST(ServerTest, getQueryId);
FRIEND_TEST(ServerTest, createMessageSender);
FRIEND_TEST(ServerTest, extractAccessToken);

public:
explicit Server(unsigned short port, size_t numThreads,
Expand Down Expand Up @@ -115,6 +116,12 @@ class Server {
static ad_utility::url_parser::ParsedRequest parseHttpRequest(
const ad_utility::httpUtils::HttpRequest auto& request);

/// Extract the Access token for that request from the `Authorization` header
/// or the URL query parameters.
static std::optional<std::string> extractAccessToken(
const ad_utility::httpUtils::HttpRequest auto& request,
const ad_utility::url_parser::ParamValueMap& params);

/// Handle a single HTTP request. Check whether a file request or a query was
/// sent, and dispatch to functions handling these cases. This function
/// requires the constraints for the `HttpHandler` in `HttpServer.h`.
Expand Down
2 changes: 2 additions & 0 deletions src/util/http/UrlParser.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,12 @@ struct None {

// Representation of parsed HTTP request.
// - `path_` is the URL path
// - `accessToken_` is the access token for that request
// - `parameters_` is a hashmap of the parameters
// - `operation_` the operation that should be performed
struct ParsedRequest {
std::string path_;
std::optional<std::string> accessToken_;
ParamValueMap parameters_;
std::variant<sparqlOperation::Query, sparqlOperation::Update,
sparqlOperation::None>
Expand Down
Loading
Loading