Skip to content
Merged
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
5 changes: 2 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ jobs:

steps:
- uses: actions/checkout@v7
with:
submodules: true

- name: Reuse ccache directory
uses: actions/cache@v6
Expand All @@ -44,7 +42,7 @@ jobs:

- name: Install packages
run: |
(cd third_party && git clone -b develop --single-branch --depth 1 https://github.com/userver-framework/userver.git)
git clone -b develop --single-branch --depth 1 https://github.com/userver-framework/userver.git third_party/userver
sudo apt update
sudo apt install --allow-downgrades -y pycodestyle postgresql $(cat third_party/userver/scripts/docs/en/deps/${{matrix.os}}.md | tr '\n' ' ')

Expand Down Expand Up @@ -83,6 +81,7 @@ jobs:
- name: Test run after install
if: matrix.make == 'test-release'
run: |
export REALMEDIUM_JWT_SECRET="$(openssl rand -hex 32)"
./local_installation/bin/realmedium_sample \
--config=./local_installation/etc/realmedium_sample/config.yaml \
--config_vars=./local_installation/etc/realmedium_sample/config_vars.yaml \
Expand Down
2 changes: 0 additions & 2 deletions .github/workflows/docker.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
submodules: true

- name: Reuse ccache directory
uses: actions/cache@v6
Expand Down
3 changes: 0 additions & 3 deletions .gitmodules

This file was deleted.

7 changes: 0 additions & 7 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,6 @@ endif()

userver_setup_environment()


set(CPP_JWT_BUILD_TESTS OFF)
set(CPP_JWT_BUILD_EXAMPLES OFF)
add_subdirectory(third_party/cpp-jwt)

# Common sources
file(GLOB_RECURSE SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/*.[hc]pp)
file(GLOB_RECURSE UNIT_TEST_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/*_test.cpp)
Expand Down Expand Up @@ -56,8 +51,6 @@ userver_add_sql_library(
)
target_link_libraries(${PROJECT_NAME}_objs PUBLIC ${PROJECT_NAME}_sql)

target_link_libraries(${PROJECT_NAME}_objs PUBLIC cpp-jwt)

find_package(ICU COMPONENTS uc i18n REQUIRED)
target_link_libraries(${PROJECT_NAME}_objs PUBLIC ICU::uc ICU::i18n)

Expand Down
25 changes: 17 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,26 @@ This codebase was created to demonstrate a fully fledged backend application bui

### Prerequisites

[Install the userver](https://userver.tech/de/dab/md_en_2userver_2build_2build.html#ways_to_get_userver) into the system
or
* check it out `git clone --depth 1 https://github.com/userver-framework/userver.git /path/to/userver`
* install all of its dependencies
* `ln -s /path/to/userver /path/to/realmedioum_sample/third_party/userver`
Use a version of userver that provides `<userver/crypto/jwt.hpp>`.
[Install userver](https://userver.tech/de/dab/md_en_2userver_2build_2build.html#ways_to_get_userver) into the system
or clone it from the repository root and install its dependencies:

### Docker-compose
```
# Clone submodules
git submodule update --init
git clone --branch develop --depth 1 https://github.com/userver-framework/userver.git third_party/userver
```

The `jwt` component reads its HS256 secret from `REALMEDIUM_JWT_SECRET` at
startup. It requires at least 32 bytes. Generate a key once for local use:

```sh
export REALMEDIUM_JWT_SECRET="$(openssl rand -hex 32)"
```

Keep the same secret across restarts and replicas. Users with tokens signed
with the previous sample key must log in again.

### Docker-compose
```
# Run service
make docker-start-service-release
```
Expand Down
3 changes: 3 additions & 0 deletions configs/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ components_manager:
throttling_enabled: false
url_trailing_slash: strict-match

jwt:
secret#env: REALMEDIUM_JWT_SECRET

realmedium-database:
dbconnection: $dbconnection
dbconnection#env: DB_CONNECTION
Expand Down
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ services:
- POSTGRES_DB=realmedium_db-1
- POSTGRES_USER=user
- POSTGRES_PASSWORD=password
- REALMEDIUM_JWT_SECRET
- PREFIX=${PREFIX:-~/.local}
- CC
- CCACHE_DIR=/realmedium/.ccache
Expand Down
57 changes: 57 additions & 0 deletions src/auth/jwt.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#include "jwt.hpp"

#include <stdexcept>
#include <utility>

#include <userver/components/component_config.hpp>
#include <userver/crypto/jwt.hpp>
#include <userver/formats/json/inline.hpp>
#include <userver/yaml_config/merge_schemas.hpp>

namespace real_medium::auth {

Jwt::Jwt(const userver::components::ComponentConfig& config, const userver::components::ComponentContext& context)
: ComponentBase(config, context), keys_(ReadKeys(config)) {}

Jwt::Keys Jwt::ReadKeys(const userver::components::ComponentConfig& config) {
auto secret = config["secret"].As<std::string>();
if (secret.size() < 32) {
throw std::runtime_error("jwt.secret must contain at least 32 bytes for HS256");
}
return {userver::crypto::SignerHs256{secret}, userver::crypto::VerifierHs256{std::move(secret)}};
}

std::string Jwt::MakeToken(std::string_view user_id) const {
return userver::crypto::jwt::MakeToken(userver::formats::json::MakeObject("id", user_id), keys_.signer);
}

std::optional<std::string> Jwt::VerifyUserId(std::string_view token) const {
userver::formats::json::Value payload;
try {
payload = userver::crypto::jwt::Verify(
token, keys_.verifier, {.expiration = userver::crypto::jwt::ExpirationPolicy::kOptional}
).payload;
} catch (const userver::crypto::VerificationError&) {
return std::nullopt;
}
const auto id = payload["id"];
if (!id.IsString()) {
return std::nullopt;
}
return id.As<std::string>();
}

userver::yaml_config::Schema Jwt::GetStaticConfigSchema() {
return userver::yaml_config::MergeSchemas<userver::components::ComponentBase>(R"(
type: object
description: Issues and verifies user tokens with HS256
additionalProperties: false
required: [secret]
properties:
secret:
type: string
description: Shared HS256 secret of at least 32 bytes
)");
}

} // namespace real_medium::auth
38 changes: 38 additions & 0 deletions src/auth/jwt.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#pragma once

#include <optional>
#include <string>
#include <string_view>

#include <userver/components/component_base.hpp>
#include <userver/crypto/signers.hpp>
#include <userver/crypto/verifiers.hpp>

namespace real_medium::auth {

class Jwt final : public userver::components::ComponentBase {
public:
static constexpr std::string_view kName = "jwt";

Jwt(const userver::components::ComponentConfig& config, const userver::components::ComponentContext& context);

/// Issue a token with the user id in the "id" claim.
std::string MakeToken(std::string_view user_id) const;

/// Return the verified user id, or nullopt for an invalid token. A missing expiration claim is allowed.
std::optional<std::string> VerifyUserId(std::string_view token) const;

static userver::yaml_config::Schema GetStaticConfigSchema();

private:
struct Keys {
userver::crypto::SignerHs256 signer;
userver::crypto::VerifierHs256 verifier;
};

static Keys ReadKeys(const userver::components::ComponentConfig& config);

const Keys keys_;
};

} // namespace real_medium::auth
33 changes: 18 additions & 15 deletions src/handlers/auth/auth_bearer.cpp
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
#include "auth_bearer.hpp"
#include "auth/jwt.hpp"
#include "db/sql.hpp"
#include "utils/jwt.hpp"

#include <algorithm>
#include <optional>
#include <string>
#include <string_view>
#include <utility>

#include <userver/components/component_context.hpp>
#include <userver/http/common_headers.hpp>
#include <userver/storages/postgres/cluster.hpp>
#include <userver/storages/postgres/component.hpp>
Expand All @@ -14,8 +18,8 @@ class AuthCheckerBearer final : public userver::server::handlers::auth::AuthChec
public:
using AuthCheckResult = userver::server::handlers::auth::AuthCheckResult;

AuthCheckerBearer(userver::storages::postgres::ClusterPtr pg_cluster, bool is_required)
: pg_cluster_(std::move(pg_cluster)), is_required_(is_required) {}
AuthCheckerBearer(userver::storages::postgres::ClusterPtr pg_cluster, const Jwt& jwt, bool is_required)
: pg_cluster_(std::move(pg_cluster)), jwt_(jwt), is_required_(is_required) {}

[[nodiscard]] AuthCheckResult CheckAuth(
const userver::server::http::HttpRequest& request,
Expand All @@ -26,6 +30,7 @@ class AuthCheckerBearer final : public userver::server::handlers::auth::AuthChec

private:
userver::storages::postgres::ClusterPtr pg_cluster_;
const Jwt& jwt_;
const bool is_required_;
};

Expand All @@ -52,25 +57,22 @@ AuthCheckerBearer::AuthCheckResult AuthCheckerBearer::CheckAuth(
return AuthCheckResult{
AuthCheckResult::Status::kTokenNotFound,
{},
"'Authorization' header should have 'Bearer some-token' format",
"'Authorization' header should have 'Token some-token' format",
userver::server::handlers::HandlerErrorCode::kUnauthorized
};
}
std::string_view token{auth_value.c_str() + bearer_sep_pos + 1};
jwt::jwt_payload payload;
try {
payload = utils::jwt::DecodeJWT(token);
} catch (...) {
const auto token = std::string_view{auth_value}.substr(bearer_sep_pos + 1);
auto id = jwt_.VerifyUserId(token);
if (!id) {
return AuthCheckResult{
AuthCheckResult::Status::kTokenNotFound,
{},
"Token verification error",
userver::server::handlers::HandlerErrorCode::kUnauthorized
};
}
auto id = payload.get_claim_value<std::string>("id");

const auto res = pg_cluster_->Execute(userver::storages::postgres::ClusterHostType::kSlave, sql::kFindUserById, id);
const auto res = pg_cluster_->Execute(userver::storages::postgres::ClusterHostType::kSlave, sql::kFindUserById, *id);
if (res.IsEmpty()) {
return AuthCheckResult{
AuthCheckResult::Status::kTokenNotFound,
Expand All @@ -80,18 +82,19 @@ AuthCheckerBearer::AuthCheckResult AuthCheckerBearer::CheckAuth(
};
}

request_context.SetData("id", std::optional<std::string>(id));
request_context.SetData("id", std::move(id));
return {};
}

CheckerFactory::CheckerFactory(const userver::components::ComponentContext& context)
: pg_cluster_(context.FindComponent<userver::components::Postgres>("realmedium-database").GetCluster()) {}
: pg_cluster_(context.FindComponent<userver::components::Postgres>("realmedium-database").GetCluster()),
jwt_(context.FindComponent<Jwt>()) {}

userver::server::handlers::auth::AuthCheckerBasePtr CheckerFactory::MakeAuthChecker(
const userver::server::handlers::auth::HandlerAuthConfig& auth_config
) const {
auto is_required = auth_config["required"].As<bool>(false);
return std::make_shared<AuthCheckerBearer>(pg_cluster_, is_required);
return std::make_shared<AuthCheckerBearer>(pg_cluster_, jwt_, is_required);
}

} // namespace real_medium::auth
3 changes: 3 additions & 0 deletions src/handlers/auth/auth_bearer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

namespace real_medium::auth {

class Jwt;

class CheckerFactory final : public userver::server::handlers::auth::AuthCheckerFactoryBase {
public:
static constexpr std::string_view kAuthType = "bearer";
Expand All @@ -16,6 +18,7 @@ class CheckerFactory final : public userver::server::handlers::auth::AuthChecker

private:
userver::storages::postgres::ClusterPtr pg_cluster_;
const Jwt& jwt_;
};

} // namespace real_medium::auth
5 changes: 1 addition & 4 deletions src/handlers/users/user_get.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@ userver::formats::json::Value Handler::HandleRequestJsonThrow(

auto user = result.AsSingleRow<real_medium::models::User>(userver::storages::postgres::kRowTag);

userver::formats::json::ValueBuilder builder;
builder["user"] = user;

return builder.ExtractValue();
return MakeUserResponseWithToken(user);
}

} // namespace real_medium::handlers::users::get
6 changes: 3 additions & 3 deletions src/handlers/users/user_get.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

#include <userver/storages/postgres/cluster.hpp>

#include "handlers/common.hpp"
#include "handlers/users/user_handler_base.hpp"

namespace real_medium::handlers::users::get {

class Handler final : public Common {
class Handler final : public UserHandlerBase {
public:
static constexpr std::string_view kName = "handler-user-get";

using Common::Common;
using UserHandlerBase::UserHandlerBase;

userver::formats::json::Value HandleRequestJsonThrow(
const userver::server::http::HttpRequest& request,
Expand Down
24 changes: 24 additions & 0 deletions src/handlers/users/user_handler_base.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#include "user_handler_base.hpp"

#include <userver/components/component_context.hpp>
#include <userver/formats/json/value_builder.hpp>

#include "auth/jwt.hpp"
#include "models/user.hpp"

namespace real_medium::handlers {

UserHandlerBase::UserHandlerBase(
const userver::components::ComponentConfig& config,
const userver::components::ComponentContext& context
)
: Common(config, context), jwt_(context.FindComponent<auth::Jwt>()) {}

userver::formats::json::Value UserHandlerBase::MakeUserResponseWithToken(const models::User& user) const {
userver::formats::json::ValueBuilder response;
response["user"] = user;
response["user"]["token"] = jwt_.MakeToken(user.id);
return response.ExtractValue();
}

} // namespace real_medium::handlers
Loading