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

chore: authenticate default development user #1312

Closed
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
4 changes: 4 additions & 0 deletions Cargo.lock

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

7 changes: 6 additions & 1 deletion docker/dev-full/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ services:
command: /usr/bin/rivet-server start
environment:
- RUST_BACKTRACE=1
- RUST_LOG=debug,hyper=info
- RUST_LOG_TARGET=1
- RUST_LOG_SPAN_PATH=1
- RUST_LOG_ANSI_COLOR=1
stop_grace_period: 0s
ports:
# API
Expand Down Expand Up @@ -164,7 +168,8 @@ services:
test: ["CMD", "bash", "-c", ">/dev/tcp/127.0.0.1/8000"]
interval: 2s
timeout: 10s
retries: 10
# SeaweedFS takes a long time to start
retries: 30

vector:
image: timberio/vector:0.42.0-distroless-static
Expand Down
6 changes: 4 additions & 2 deletions packages/api/actor/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl Auth {

// Lookup project name ID
let project = if is_development {
query.project().unwrap_or("default")
query.project().unwrap_or(util::dev_defaults::PROJECT_SLUG)
} else {
unwrap_with!(query.project(), GAME_NOT_FOUND)
};
Expand All @@ -86,7 +86,9 @@ impl Auth {

// Lookup environment name ID
let environment = if is_development {
query.environment().unwrap_or("default")
query
.environment()
.unwrap_or(util::dev_defaults::ENVIRONMENT_SLUG)
} else {
unwrap_with!(query.project(), GAME_NOT_FOUND)
};
Expand Down
2 changes: 2 additions & 0 deletions packages/api/auth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ user-identity-create = { path = "../../services/user-identity/ops/create" }
token-create = { path = "../../services/token/ops/create" }
rivet-config = { version = "0.1.0", path = "../../common/config" }
rivet-env = { version = "0.1.0", path = "../../common/env" }
user = { version = "0.1.0", path = "../../services/user" }
chirp-workflow = { version = "0.1.0", path = "../../common/chirp-workflow/core" }

[dev-dependencies]
rivet-auth = { path = "../../common/smithy-output/api-auth/rust" }
Expand Down
2 changes: 0 additions & 2 deletions packages/api/auth/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use rivet_operation::prelude::*;

/// Information derived from the authentication middleware.
pub struct Auth {
config: rivet_config::Config,
claims: Option<Claims>,
}

Expand All @@ -22,7 +21,6 @@ impl ApiAuth for Auth {
Self::rate_limit(&config, rate_limit_ctx).await?;

Ok(Auth {
config: config.clone(),
claims: if let Some(api_token) = api_token {
Some(as_auth_expired(rivet_claims::decode(
&config.server()?.jwt.public,
Expand Down
47 changes: 37 additions & 10 deletions packages/api/auth/src/route/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ use http::response::Builder;
use proto::backend::{self, pkg::*};
use rivet_auth_server::models;
use rivet_claims::ClaimsDecode;
use rivet_config::config::rivet::AccessKind;
use rivet_operation::prelude::*;

use crate::{
auth::Auth,
utils::{self, delete_refresh_token_header, refresh_token_header},
utils::{delete_refresh_token_header, refresh_token_header},
};

// Also see user-token-create/src/main.rs
Expand Down Expand Up @@ -115,7 +116,7 @@ pub async fn identity(
}
}
} else {
register_user(ctx.client_info(), ctx.op_ctx()).await?
fallback_user(ctx.client_info(), ctx.op_ctx()).await?
};

// Validate response
Expand Down Expand Up @@ -165,17 +166,43 @@ pub async fn identity(
})
}

async fn register_user(
/// This will return the user authentication data if no refresh token is provided or if the refresh
/// token is expired.
///
/// With AccessKind::Development, this will return the default user.
///
/// Otherwise, this will return a new guest user.
async fn fallback_user(
client_info: backend::net::ClientInfo,
ctx: &OperationContext<()>,
) -> GlobalResult<(String, String)> {
// Register user
let user_id = Uuid::new_v4();
msg!([ctx] user::msg::create(user_id) -> user::msg::create_complete {
user_id: Some(user_id.into()),
namespace_id: None,
})
.await?;
let user_id = match ctx.config().server()?.rivet.auth.access_kind {
AccessKind::Public | AccessKind::Private => {
// Register new user
let user_id = Uuid::new_v4();
msg!([ctx] user::msg::create(user_id) -> user::msg::create_complete {
user_id: Some(user_id.into()),
namespace_id: None,
display_name: None,
})
.await?;

user_id
}
AccessKind::Development => {
// Lookup default user
let user_resolve_res = chirp_workflow::compat::op(
ctx,
::user::ops::resolve_display_name::Input {
display_name: util::dev_defaults::USER_NAME.into(),
},
)
.await?;
let user_id = unwrap!(user_resolve_res.user_id, "default user not found");

user_id
}
};

// Generate token
let token_res = op!([ctx] user_token_create {
Expand Down
8 changes: 4 additions & 4 deletions packages/api/cloud/src/route/games/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,9 +344,8 @@ pub async fn get(
};
let update_ts = update_ts.unwrap_or_else(util::timestamp::now);

let ((games, dev_teams), states, ns_list_res, version_list_res) = tokio::try_join!(
let ((games, dev_teams), ns_list_res, version_list_res) = tokio::try_join!(
fetch::game::games_and_dev_teams(ctx.op_ctx(), vec![game_id.into()]),
fetch::game::state(ctx.op_ctx(), vec![game_id.into()]),
op!([ctx] game_namespace_list {
game_ids: vec![game_id.into()],
}),
Expand All @@ -355,7 +354,6 @@ pub async fn get(
}),
)?;
let game = unwrap!(games.games.first());
let state = unwrap!(states.get(&game_id));
let dev_team = unwrap!(dev_teams.get(&game_id));
let ns_list = unwrap!(ns_list_res.games.first());
let version_list = unwrap!(version_list_res.games.first());
Expand Down Expand Up @@ -425,13 +423,15 @@ pub async fn get(
name_id: game.name_id.to_owned(),
display_name: game.display_name.to_owned(),
developer_group_id: unwrap_ref!(dev_team.team_id).as_uuid(),
total_player_count: state.total_player_count.api_try_into()?,
logo_url: util::route::game_logo(ctx.config(), game),
banner_url: util::route::game_banner(ctx.config(), game),

namespaces,
versions,
available_regions: regions,

// Deprecated
total_player_count: 0,
}),
watch: WatchResponse::new_as_model(update_ts),
})
Expand Down
2 changes: 1 addition & 1 deletion packages/common/cache/build/src/req_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ impl RequestConfig {
"cache returned wrong number of values"
);

tracing::info!(
tracing::debug!(
cached_len = cached_values.iter().filter(|x| x.is_some()).count(),
total_len = cached_values.len(),
"read from cache"
Expand Down
2 changes: 1 addition & 1 deletion packages/common/config/src/paths.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::path::PathBuf;

/// Name of the config directory holding the rivet config.
const CONFIG_DIR_NAME: &str = "rivet";
const CONFIG_DIR_NAME: &str = "rivet-server";

#[cfg(target_os = "linux")]
pub fn system_config_dir() -> PathBuf {
Expand Down
13 changes: 3 additions & 10 deletions packages/common/convert/src/convert/game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,25 +20,18 @@ pub fn handle(
pub fn summary(
config: &rivet_config::Config,
game: &backend::game::Game,
state: &fetch::game::GameState,
dev_team: &backend::team::Team,
) -> GlobalResult<models::GameSummary> {
let game_url = state
.prod_config
.domains
.first()
.map(|d| d.domain.clone())
.unwrap_or_else(|| game.url.clone());

Ok(models::GameSummary {
game_id: unwrap_ref!(game.game_id).as_uuid(),
name_id: game.name_id.to_owned(),
display_name: game.display_name.to_owned(),
logo_url: util::route::game_logo(config, &game),
banner_url: util::route::game_banner(config, &game),
url: game_url,
developer: Box::new(convert::group::handle(config, dev_team)?),
total_player_count: ApiTryInto::api_try_into(state.total_player_count)?,
// Deprecated
total_player_count: 0,
url: game.url.clone(),
})
}

Expand Down
5 changes: 1 addition & 4 deletions packages/common/convert/src/convert/identity.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
use rivet_api::models;
use rivet_operation::prelude::*;
use types_proto::rivet::{
backend::{self, pkg::*},
common,
};
use types_proto::rivet::backend::{self, pkg::*};

use crate::{convert, fetch, ApiTryInto};

Expand Down
98 changes: 2 additions & 96 deletions packages/common/convert/src/fetch/game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,6 @@ use types_proto::rivet::{

use crate::convert;

pub struct GameState {
pub prod_config: backend::cdn::NamespaceConfig,
pub total_player_count: u32,
}

pub async fn summaries(
ctx: &OperationContext<()>,
game_ids: Vec<Uuid>,
Expand All @@ -28,21 +23,17 @@ pub async fn summaries(
.map(Into::into)
.collect::<Vec<_>>();

let ((games, dev_teams), states) = tokio::try_join!(
games_and_dev_teams(ctx, proto_game_ids.clone()),
state(ctx, proto_game_ids.clone()),
)?;
let (games, dev_teams) = games_and_dev_teams(ctx, proto_game_ids.clone()).await?;

// Convert all data
games
.games
.iter()
.map(|game| {
let game_id = unwrap_ref!(game.game_id).as_uuid();
let state = unwrap!(states.get(&game_id));
let dev_team = unwrap!(dev_teams.get(&game_id));

convert::game::summary(ctx.config(), game, state, dev_team)
convert::game::summary(ctx.config(), game, dev_team)
})
.collect::<GlobalResult<Vec<_>>>()
}
Expand Down Expand Up @@ -82,91 +73,6 @@ pub async fn games_and_dev_teams(
Ok((games_res, dev_teams))
}

pub async fn state(
ctx: &OperationContext<()>,
game_ids: Vec<common::Uuid>,
) -> GlobalResult<HashMap<Uuid, GameState>> {
let namespaces_res = op!([ctx] game_namespace_list {
game_ids: game_ids,
})
.await?;
let all_namespace_ids = namespaces_res
.games
.iter()
.flat_map(|game| game.namespace_ids.iter().cloned())
.collect::<Vec<_>>();

let (game_namespaces_res, player_count_res) = tokio::try_join!(
op!([ctx] game_namespace_get {
namespace_ids: all_namespace_ids.clone(),
}),
op!([ctx] mm_player_count_for_namespace {
namespace_ids: all_namespace_ids,
}),
)?;

let mut prod_namespaces = HashMap::new();
for namespace in &game_namespaces_res.namespaces {
if &namespace.name_id == "prod" {
let game_id = unwrap_ref!(namespace.game_id).as_uuid();
let namespace_id = unwrap!(namespace.namespace_id).as_uuid();

prod_namespaces.insert(namespace_id, game_id);
}
}

let cdn_namespaces_res = op!([ctx] cdn_namespace_get {
namespace_ids: prod_namespaces
.keys()
.cloned()
.map(Into::into)
.collect::<Vec<_>>(),
})
.await?;

let cdn_configs = cdn_namespaces_res
.namespaces
.iter()
.map(|ns| {
let namespace_id = unwrap_ref!(ns.namespace_id).as_uuid();
let game_id = unwrap!(prod_namespaces.get(&namespace_id));
let config = unwrap_ref!(ns.config).clone();

// Fetch all namespace ids for game
let game_id_proto = Some(Into::<common::Uuid>::into(*game_id));
let all_namespace_ids = &unwrap!(namespaces_res
.games
.iter()
.find(|game| game.game_id == game_id_proto))
.namespace_ids;

let total_player_count = player_count_res
.namespaces
.iter()
.filter(|ns1| {
// Make sure this namespace belongs to this game
all_namespace_ids.iter().any(|ns2_id| {
ns1.namespace_id
.as_ref()
.map_or(false, |ns1_id| ns1_id == ns2_id)
})
})
// Aggregate the player count
.fold(0u32, |acc, x| acc + x.player_count);

Ok((
*game_id,
GameState {
prod_config: config,
total_player_count,
},
))
})
.collect::<GlobalResult<HashMap<_, _>>>()?;

Ok(cdn_configs)
}

pub async fn region_summaries(
ctx: &OperationContext<()>,
game_id: Uuid,
Expand Down
Loading
Loading