mod backend;
pub(crate) mod fake;
#[cfg(feature = "steam")]
pub(crate) mod real;
#[cfg(test)]
mod tests;
pub use backend::{AuthBackend, WebApiTicket};
pub use fake::FakeAuthFailure;
use std::collections::HashMap;
use std::time::Duration;
use bevy_app::{App, AppExit, First, Last, Update};
use bevy_ecs::message::{MessageCursor, Messages};
use bevy_ecs::prelude::*;
use bevy_ecs::system::SystemParam;
use bevy_time::{Real, Time};
use tracing::{info, warn};
use crate::{BackendEvent, PumpedEvents, SteamBackendRes, SteamKitSystems};
#[derive(Resource, Clone, Debug)]
pub struct AuthSettings {
pub timeout: Duration,
pub cancel_on_exit: bool,
}
impl Default for AuthSettings {
fn default() -> Self {
Self { timeout: Duration::from_secs(30), cancel_on_exit: true }
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct AuthRequestId(pub u64);
impl AuthRequestId {
pub const FIRST_MANUAL: u64 = 1 << 63;
}
#[derive(Debug)]
struct Pending {
op: u64,
identity: String,
started: Option<Duration>,
}
#[derive(Resource, Debug, Default)]
pub struct SteamAuth {
next_op: u64,
pending: HashMap<AuthRequestId, Pending>,
live: HashMap<AuthRequestId, u64>,
last_issued: u64,
cursor: MessageCursor<AuthRequest>,
}
impl SteamAuth {
pub fn is_pending(&self, id: AuthRequestId) -> bool {
self.pending.contains_key(&id)
}
pub fn is_live(&self, id: AuthRequestId) -> bool {
self.live.contains_key(&id)
}
pub fn live_tickets(&self) -> usize {
self.live.len()
}
pub fn next_id(&mut self) -> AuthRequestId {
loop {
self.last_issued = if self.last_issued + 1 >= AuthRequestId::FIRST_MANUAL { 1 } else { self.last_issued + 1 };
let id = AuthRequestId(self.last_issued);
if !self.in_use(id) {
return id;
}
}
}
fn in_use(&self, id: AuthRequestId) -> bool {
self.pending.contains_key(&id) || self.live.contains_key(&id)
}
fn op(&mut self) -> u64 {
self.next_op = self.next_op.wrapping_add(1).max(1);
self.next_op
}
}
#[derive(Message, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthRequest {
WebApiTicket {
id: AuthRequestId,
identity: String,
},
Cancel {
id: AuthRequestId,
},
}
impl AuthRequest {
pub fn web_api_ticket(id: AuthRequestId, identity: impl Into<String>) -> Self {
Self::WebApiTicket { id, identity: identity.into() }
}
pub fn cancel(id: AuthRequestId) -> Self {
Self::Cancel { id }
}
pub fn id(&self) -> AuthRequestId {
match self {
Self::WebApiTicket { id, .. } | Self::Cancel { id } => *id,
}
}
}
#[derive(Message, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct WebApiTicketReady {
pub id: AuthRequestId,
pub identity: String,
pub ticket: WebApiTicket,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AuthErrorKind {
NoBackend,
InvalidIdentity,
DuplicateId,
Failed,
TimedOut,
Cancelled,
Exiting,
}
#[derive(Message, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AuthError {
pub id: AuthRequestId,
pub kind: AuthErrorKind,
pub message: String,
}
pub(crate) fn build(app: &mut App, settings: &AuthSettings) {
app.insert_resource(settings.clone())
.init_resource::<SteamAuth>()
.add_message::<AuthRequest>()
.add_message::<WebApiTicketReady>()
.add_message::<AuthError>()
.add_systems(First, apply_auth_events.in_set(SteamKitSystems::Callbacks))
.add_systems(Update, handle_auth_requests.in_set(SteamKitSystems::Requests))
.add_systems(Last, auth_on_exit.in_set(SteamKitSystems::Requests));
}
#[derive(SystemParam)]
struct AuthOut<'w> {
ready: MessageWriter<'w, WebApiTicketReady>,
error: MessageWriter<'w, AuthError>,
}
impl AuthOut<'_> {
fn fail(&mut self, id: AuthRequestId, kind: AuthErrorKind, message: impl Into<String>) {
let message = message.into();
warn!(">>> STEAM: web API ticket request {}: {kind:?} ({message})", id.0);
self.error.write(AuthError { id, kind, message });
}
}
fn auth_api<'a>(backend: &'a Option<Res<'_, SteamBackendRes>>) -> Option<&'a dyn AuthBackend> {
backend.as_ref().and_then(|b| b.0.auth())
}
fn apply_auth_events(backend: Option<Res<SteamBackendRes>>, pumped: Res<PumpedEvents>, mut state: ResMut<SteamAuth>, mut out: AuthOut) {
let Some(api) = auth_api(&backend) else {
let lost = pumped.0.iter().filter(|e| matches!(e, BackendEvent::WebApiTicket { .. })).count();
if lost > 0 && backend.is_none() {
warn!(">>> STEAM: backend removed before {lost} web API ticket(s) were applied - dropped");
}
return;
};
for ev in &pumped.0 {
#[allow(irrefutable_let_patterns)]
let BackendEvent::WebApiTicket { op, result } = ev
else {
continue;
};
let Some(id) = state.pending.iter().find(|(_, p)| p.op == *op).map(|(id, _)| *id) else {
info!(">>> STEAM: late web API ticket for a given-up request - dropped");
continue;
};
let Some(p) = state.pending.remove(&id) else { continue };
match result {
Ok(ticket) => {
info!(">>> STEAM: web API ticket for identity {:?} ready ({} bytes)", p.identity, ticket.len());
state.live.insert(id, p.op);
out.ready.write(WebApiTicketReady { id, identity: p.identity, ticket: ticket.clone() });
}
Err(message) => {
api.cancel_auth_ticket(p.op);
out.fail(id, AuthErrorKind::Failed, format!("Steam: {message}"));
}
}
}
}
fn handle_auth_requests(
backend: Option<Res<SteamBackendRes>>,
time: Option<Res<Time<Real>>>,
settings: Res<AuthSettings>,
messages: Res<Messages<AuthRequest>>,
mut state: ResMut<SteamAuth>,
mut out: AuthOut,
) {
let requests: Vec<AuthRequest> = state.cursor.read(&messages).cloned().collect();
let Some(api) = auth_api(&backend) else {
let mut gone: Vec<AuthRequestId> = state.pending.drain().map(|(id, _)| id).collect();
gone.sort();
for id in gone {
out.fail(id, AuthErrorKind::NoBackend, "Steam backend removed while this request waited");
}
state.live.clear();
for req in requests {
if let AuthRequest::WebApiTicket { id, .. } = req {
out.fail(id, AuthErrorKind::NoBackend, "auth: Steam is not available");
}
}
return;
};
let now = time.as_ref().map(|t| t.elapsed());
if let Some(now) = now {
for p in state.pending.values_mut() {
p.started.get_or_insert(now);
}
let mut expired: Vec<AuthRequestId> =
state.pending.iter().filter(|(_, p)| p.started.is_some_and(|t| now.saturating_sub(t) >= settings.timeout)).map(|(id, _)| *id).collect();
expired.sort();
for id in expired {
if let Some(p) = state.pending.remove(&id) {
api.cancel_auth_ticket(p.op);
out.fail(id, AuthErrorKind::TimedOut, "no ticket from Steam in time (cancelled)");
}
}
}
for req in requests {
apply_request(api, now, &mut state, &mut out, req);
}
}
fn apply_request(api: &dyn AuthBackend, now: Option<Duration>, state: &mut SteamAuth, out: &mut AuthOut, req: AuthRequest) {
match req {
AuthRequest::WebApiTicket { id, identity } => {
if state.in_use(id) {
out.fail(id, AuthErrorKind::DuplicateId, "rejected: this id is still pending or its ticket is live (that one keeps its own answer)");
return;
}
if identity.contains('\0') {
out.fail(id, AuthErrorKind::InvalidIdentity, "the identity contains a NUL byte");
return;
}
let op = state.op();
if api.request_web_api_ticket(op, &identity) {
info!(">>> STEAM: web API ticket requested for identity {identity:?}");
state.pending.insert(id, Pending { op, identity, started: now });
} else {
out.fail(id, AuthErrorKind::Failed, "the backend refused the ticket request");
}
}
AuthRequest::Cancel { id } => {
if let Some(op) = state.live.remove(&id) {
api.cancel_auth_ticket(op);
info!(">>> STEAM: web API ticket {} cancelled", id.0);
} else if let Some(p) = state.pending.remove(&id) {
api.cancel_auth_ticket(p.op);
out.fail(id, AuthErrorKind::Cancelled, "cancelled before the ticket arrived");
}
}
}
}
fn auth_on_exit(
mut exit: MessageReader<AppExit>,
backend: Option<Res<SteamBackendRes>>,
settings: Res<AuthSettings>,
messages: Res<Messages<AuthRequest>>,
mut state: ResMut<SteamAuth>,
mut out: AuthOut,
) {
if exit.read().count() == 0 {
return;
}
let late: Vec<AuthRequest> = state.cursor.read(&messages).cloned().collect();
let api = auth_api(&backend);
for req in late {
match req {
AuthRequest::WebApiTicket { id, .. } => {
let kind = if api.is_some() { AuthErrorKind::Exiting } else { AuthErrorKind::NoBackend };
out.fail(id, kind, "the app exited before this request was sent");
}
AuthRequest::Cancel { id } => {
if let Some(api) = api {
apply_request(api, None, &mut state, &mut out, AuthRequest::Cancel { id });
}
}
}
}
let mut pending: Vec<(AuthRequestId, u64)> = state.pending.drain().map(|(id, p)| (id, p.op)).collect();
pending.sort();
for (id, op) in pending {
if let Some(api) = api {
api.cancel_auth_ticket(op);
}
out.fail(id, AuthErrorKind::Exiting, "the app exited before Steam answered");
}
if settings.cancel_on_exit {
let live: Vec<u64> = state.live.drain().map(|(_, op)| op).collect();
if let Some(api) = api {
for op in &live {
api.cancel_auth_ticket(*op);
}
}
if !live.is_empty() {
info!(">>> STEAM: {} web API ticket(s) cancelled on exit", live.len());
}
}
}