Files
k-mood/crates/adapters/http-axum/src/handlers/tokens.rs
Gabriel Kaszewski bf148902ab spa hardening, offline logging, rate limit fixes
server:
- backup exporter, auth extractors, error shapes, CONTEXT (prior work)
- spa assets served outside the rate limit via route_layer
- requests_per_second went to per_second(), which takes an interval not a
  rate: 50 meant one request per 50s once burst was spent. now converted
  properly. 15/s, burst 60

spa fixes:
- account delete cleared snake_case token keys that were never written
- refresh interceptor could retry forever
- date ranges used local day boundaries stamped +00:00
- "all" period trend plotted one page; calendar days fabricated mood 3
- chart grid invisible: hsl(var(--border)) against rgba tokens
- blob url leak, orphaned media on failed save, devtools in prod bundle
- pt-safe/safe-area-pb classes never existed

spa features:
- offline outbox: entries queue to IndexedDB, replay with backoff, only
  server refusals count against an entry
- drafts persist, quick-log sheet, diary infinite scroll + filters
- route error boundary, stale-chunk recovery, no service worker in dev

a11y + perf:
- mood picker is a radiogroup, activity picker keyboard-operable,
  text alternatives for colour/emoji, locale week start
- dark glass over the bright photo: worst case 1.4:1 -> 4.9-9.6:1
- initial payload 1095->769kB raw, 306->230kB gzip; 38 unused components
  and 5 deps dropped; fonts 218->133kB

53 tests added (43 spa, 10 server)
2026-08-28 15:00:30 +02:00

97 lines
4.4 KiB
Rust

use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use api_types::requests::MintApiTokenRequest;
use api_types::responses::{ApiTokenResponse, ErrorResponse, MintedApiTokenResponse};
use application::api_token::commands::MintApiTokenCommand;
use application::api_token::use_cases::{list_api_tokens, mint_api_token, revoke_api_token};
use domain::api_token::{ApiTokenId, TokenScopes};
use domain::provider::ProviderName;
use crate::errors::ApiError;
use crate::extractors::{Body, PathId, SessionUser};
use crate::state::AppState;
#[utoipa::path(get, path = "/api/v1/tokens", tag = "tokens", security(("bearer" = [])),
description = "Lists this account's api tokens. Values are never returned; only the name, \
when it was minted, and when it was last used.",
responses((status = 200, body = Vec<ApiTokenResponse>),
(status = 401, description = "No credential, or one this endpoint does not accept", body = ErrorResponse),
(status = 403, description = "A token that does not grant what this endpoint needs", body = ErrorResponse),
(status = 400, description = "Malformed request", body = ErrorResponse),
(status = 422, description = "Understood but refused", body = ErrorResponse))
)]
pub async fn handle_list(
State(state): State<AppState>,
SessionUser(user_id): SessionUser,
) -> Result<Json<Vec<ApiTokenResponse>>, ApiError> {
let deps = list_api_tokens::Deps {
query: state.api_token_query,
};
let tokens = list_api_tokens::execute(user_id, &deps).await?;
Ok(Json(tokens.into_iter().map(Into::into).collect()))
}
#[utoipa::path(post, path = "/api/v1/tokens", tag = "tokens", security(("bearer" = [])),
description = "Mints a token granting the scopes named in the request, and nothing else. \
The value comes back once and is never retrievable again. The name becomes \
the Provider that the token's metric writes are attributed to, so it must be \
lowercase letters, digits and hyphens. Account operations — minting tokens, \
changing the password, backup and restore — always need a signed-in session \
and are never reachable with a token.",
request_body = MintApiTokenRequest,
responses((status = 201, body = MintedApiTokenResponse),
(status = 401, description = "No credential, or one this endpoint does not accept", body = ErrorResponse),
(status = 403, description = "A token that does not grant what this endpoint needs", body = ErrorResponse),
(status = 400, description = "Malformed request", body = ErrorResponse),
(status = 422, description = "Understood but refused", body = ErrorResponse))
)]
pub async fn handle_mint(
State(state): State<AppState>,
SessionUser(user_id): SessionUser,
Body(body): Body<MintApiTokenRequest>,
) -> Result<(StatusCode, Json<MintedApiTokenResponse>), ApiError> {
let deps = mint_api_token::Deps {
command: state.api_token_command,
secrets: state.api_token_secrets,
};
let minted = mint_api_token::execute(
MintApiTokenCommand {
user_id,
name: ProviderName::new(body.name)?,
scopes: TokenScopes::from_names(body.scopes.iter().map(String::as_str))?,
},
&deps,
)
.await?;
Ok((StatusCode::CREATED, Json(minted.into())))
}
#[utoipa::path(delete, path = "/api/v1/tokens/{id}", tag = "tokens", security(("bearer" = [])),
description = "Revokes a token. It stops working at once.",
params(("id" = String, Path, description = "Token ID")),
responses((status = 204),
(status = 401, description = "No credential, or one this endpoint does not accept", body = ErrorResponse),
(status = 403, description = "A token that does not grant what this endpoint needs", body = ErrorResponse),
(status = 400, description = "Malformed request", body = ErrorResponse),
(status = 422, description = "Understood but refused", body = ErrorResponse))
)]
pub async fn handle_revoke(
State(state): State<AppState>,
SessionUser(user_id): SessionUser,
PathId(token_id): PathId<ApiTokenId>,
) -> Result<StatusCode, ApiError> {
let deps = revoke_api_token::Deps {
command: state.api_token_command,
};
revoke_api_token::execute(user_id, token_id, &deps).await?;
Ok(StatusCode::NO_CONTENT)
}