chore(history): squash 67 commit(s) from 2026-09-25
- feat(accounts): persist device links with opaque hashed tokens, list and revoke endpoints - feat(frontend): app shell, routing and landing page with the chat-command hero - feat(frontend): Cyrillic-first fonts (Unbounded, Onest, JetBrains Mono); add i18next and motion - docs: free mod, bilingual site, one-click download, theme editor, public profiles, rich landing in plans - feat(accounts): internal gRPC AuthenticateDevice guarded by internal key - feat(frontend): ru/en i18n with typed per-feature dictionaries and language switch - feat(accounts): GET /me profile endpoint - feat(gateway): scaffold crate with config validation and health check - feat(gateway): reverse proxy to accounts and configs services - feat(gateway): resolve identity once from access JWT or device token via gRPC - feat(gateway): per-route and global rate limits with Retry-After - feat(gateway): CORS for the site origin; docs for gateway and internal contract - feat(configs): scaffold service with schema, config validation and health check - feat(configs): four config slots per account with list, get and save - feat(configs): permanent share codes with regenerate and public load-by-code - feat(accounts): GetPublicProfiles gRPC for showcase author info - style(accounts,common): apply rustfmt to existing sources - feat(configs): public showcase with publish, browse, detail and copy-to-slot - feat(backend): public profile endpoint and showcase author filter - fix(gateway): silence clippy collapsible-if and needless-ref warnings - docs(backend): configs-service implemented; Подсистема 1 backend complete - feat(mod): add Optimize module skeleton with OptimizeState holder - feat(mod): gate glass blur behind Optimize no_glass knob - feat(mod): cut MotionBlur and DoF sample counts behind lite_post knob - feat(mod): trim procedural sky noise behind lite_sky knob - feat(mod): drop fade gradients and digit rolls behind lean_hud knob - docs(todo): mark Optimize module phase 9.2 complete - refactor(mod): drop dead Renderer2D compatibility shims - refactor(mod): prune unreachable Renderer2D overload towers - refactor(mod): remove unused Renderer2D overloads and imports - docs(todo): mark Renderer2D giant-splitting done (2179 to 1597) - refactor(mod): extract shader id constants from LoVisualRenderPipelines - docs(todo): record registry wave 2026-09-25 (Renderer2D, pipelines) - refactor(mod): move Renderer2D instance state into base class - refactor(mod): extract Renderer2DRounded drawing family - refactor(mod): extract Renderer2DPath connector and chamfer family - refactor(mod): extract Renderer2DShapes circle line and texture primitives - refactor(mod): extract Renderer2DGlass and Renderer2DItem families - refactor(mod): prune Renderer2D imports after facade split - docs(todo): record Renderer2D facade inheritance split (1597 to 475) - docs: easter eggs — .env honeypot, konami troll mode, devtools banner, IDDQD config, breakable 404 block, 418 teapot - feat(mod): introduce surface style system core (SurfaceStyle, StyleSpec, StyleConfig, SurfaceRenderer) - refactor(mod): delegate HudRenderUtil liquid glass draws to SurfaceRenderer (dedupe glass constants) - refactor(mod): route bespoke glass call sites through SurfaceRenderer.plateSpec - feat(mod): add Auto option to HUD bg effects via shared HudBgStyles resolution - feat(mod): flat fallback for no-glass optimize mode and persist global HUD config - feat(mod): default HUD bg effects to Auto so the global surface style drives widgets - feat(mod): add global cycle-style hotkey with surface style notification - feat(mod): add surface style swatch strip under the global style picker - feat(gateway): reject ambiguous paths and answer .env probes with a honeypot - fix(gateway): charge failed credentials against the rate limit, allow stale ones on /auth - feat(frontend): ClickGui theme pipeline generated from the mod, live site theming - feat(frontend): landing v2 hero — voxel/particle backdrop, live ClickGui, theme strip - docs(todo): drop the FPS A/B measurement from phase 9.3, close phase 9 - feat(gateway): answer /coffee with a 418 teapot - feat(frontend): land the rest of landing v2 — HUD, module wall, showcase, FAQ, footer - feat(frontend): one-click download from GitHub releases, changelog page, release CI - feat(frontend): theme editor with live ClickGui preview, mod-compatible export and share links - fix(frontend): landing HUD playground now shows real mod widgets (fps, coordinates, module list, keybinds, ping) - style(frontend): apply ClickGui glass effect to landing HUD playground widgets - fix(frontend): prevent color field row overflow in theme editor grid - fix(frontend): never attach stale bearer token to /auth/* requests - fix(configs): unpublish/publish can no longer bypass moderation - refactor(accounts): shrink auth/handlers.rs under the 250-line cap - fix(accounts): tolerate concurrent refresh without killing every session - fix(gateway): minor hardening from the backend review - feat(configs): IDDQD easter egg config
This commit is contained in:
parent
72bc4c7148
commit
7f4b532f99
257 changed files with 13085 additions and 6582 deletions
27
backend/configs-service/Cargo.toml
Normal file
27
backend/configs-service/Cargo.toml
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
[package]
|
||||
name = "configs-service"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
name = "configs_service"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
common = { path = "../common" }
|
||||
axum = { version = "0.8", features = ["macros"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = "0.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "tls-rustls", "postgres", "uuid", "chrono", "json", "macros", "migrate"] }
|
||||
uuid = { version = "1", features = ["v4", "serde"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
rand = "0.10"
|
||||
tonic = "0.14"
|
||||
anyhow = "1"
|
||||
dotenvy = "0.15"
|
||||
|
||||
[dev-dependencies]
|
||||
axum-test = "21"
|
||||
|
|
@ -1357,6 +1357,20 @@ git commit -m "feat(configs): public showcase with publish, browse, detail and c
|
|||
|
||||
---
|
||||
|
||||
### Task 5b: Public profile data (for the site's `/u/:id`)
|
||||
|
||||
**Files:** accounts-service `src/accounts/handlers.rs` (+ `public_profile`), `src/accounts/repo.rs` (+ `account_rank`), `tests/auth_flow.rs`; configs-service `src/showcase/{repo,handlers}.rs` (`author` filter), `tests/showcase.rs`.
|
||||
|
||||
**Interfaces:**
|
||||
- accounts-service `GET /users/{id}` — public, no identity needed (still behind the internal key): `200 { id, display_nick, avatar_url: string|null, created_at, badges: string[] }`, 404 for unknown/invalid ids. Never returns email or role. `badges`: `"early"` when the account is among the first 1000 by `created_at` (`SELECT count(*) FROM accounts WHERE created_at < $1` < 1000). Gateway routes `users` → accounts (already in the gateway plan's table).
|
||||
- configs-service `GET /showcase?author={uuid}` — same page shape, filtered to that account's non-hidden listings; invalid uuid → 400.
|
||||
|
||||
- [ ] **Step 1: Failing tests** — `/users/{id}` returns nick without email and includes `early`; unknown id 404; `/showcase?author=` returns only that author's listings.
|
||||
- [ ] **Step 2: Implement** (`repo::page` gains `author: Option<Uuid>` → `AND l.account_id = $3` when set).
|
||||
- [ ] **Step 3: Commit** — `feat(backend): public profile endpoint and showcase author filter`
|
||||
|
||||
---
|
||||
|
||||
### Task 6: End-to-end through the gateway + docs
|
||||
|
||||
**Files:**
|
||||
|
|
@ -1387,3 +1401,11 @@ Expected: each call succeeds and the showcase item carries the real nick.
|
|||
git add -A backend/STRUCTURE.md TODO.md backend/.env.example
|
||||
git commit -m "docs(backend): configs-service implemented; Подсистема 1 backend complete"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: `IDDQD` easter egg — done
|
||||
|
||||
`GET /configs/shared/{code}`: when `normalize(code) == "IDDQD"` return `200 { name: "God mode", data: <joke config>, updated_at: "1993-12-10T00:00:00Z" }` without touching the DB (DOOM's release date). The joke config data: every module disabled except `ChinaHat` (exact JSON shape = the mod's config format; until the mod-integration plan defines it, use `{ "modules": { "ChinaHat": { "enabled": true } }, "note": "god mode: только шляпа" }`). Real codes can never be `IDDQD` (no `I` in the alphabet, length 5). Test + commit `feat(configs): IDDQD easter egg config`.
|
||||
|
||||
Implemented in `src/sharing/handlers.rs::load_shared` (checked before hitting `repo::by_share_code`); test in `tests/sharing.rs::iddqd_is_a_god_mode_easter_egg_without_touching_the_db`.
|
||||
|
|
|
|||
31
backend/configs-service/migrations/0001_init.sql
Normal file
31
backend/configs-service/migrations/0001_init.sql
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||
REVOKE ALL ON SCHEMA public FROM PUBLIC;
|
||||
|
||||
-- account_id has no FK: accounts live in accounts_db (separate database).
|
||||
CREATE TABLE config_slots (
|
||||
account_id UUID NOT NULL,
|
||||
slot_index SMALLINT NOT NULL CHECK (slot_index BETWEEN 1 AND 4),
|
||||
name TEXT NOT NULL,
|
||||
data JSONB NOT NULL,
|
||||
share_code TEXT NOT NULL UNIQUE,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (account_id, slot_index)
|
||||
);
|
||||
|
||||
CREATE TABLE showcase_listings (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
account_id UUID NOT NULL,
|
||||
slot_index SMALLINT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
copies_count INTEGER NOT NULL DEFAULT 0,
|
||||
-- set by admin moderation (Подсистема 3); public queries always filter it
|
||||
hidden BOOLEAN NOT NULL DEFAULT false,
|
||||
published_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (account_id, slot_index),
|
||||
FOREIGN KEY (account_id, slot_index)
|
||||
REFERENCES config_slots (account_id, slot_index) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX idx_showcase_new ON showcase_listings (published_at DESC) WHERE NOT hidden;
|
||||
CREATE INDEX idx_showcase_popular ON showcase_listings (copies_count DESC, published_at DESC) WHERE NOT hidden;
|
||||
56
backend/configs-service/src/config.rs
Normal file
56
backend/configs-service/src/config.rs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
use anyhow::{Context, Result};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Config {
|
||||
pub database_url: String,
|
||||
pub port: u16,
|
||||
pub internal_key: String,
|
||||
pub accounts_grpc_url: String,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn from_env() -> Result<Config> {
|
||||
Ok(Config {
|
||||
database_url: std::env::var("CONFIGS_DATABASE_URL")
|
||||
.context("CONFIGS_DATABASE_URL not set")?,
|
||||
port: std::env::var("CONFIGS_PORT")
|
||||
.unwrap_or_else(|_| "8082".into())
|
||||
.parse()
|
||||
.context("CONFIGS_PORT")?,
|
||||
internal_key: std::env::var("INTERNAL_KEY").context("INTERNAL_KEY not set")?,
|
||||
accounts_grpc_url: std::env::var("ACCOUNTS_GRPC_URL")
|
||||
.context("ACCOUNTS_GRPC_URL not set")?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if self.internal_key.len() < 32 {
|
||||
anyhow::bail!("INTERNAL_KEY must be at least 32 bytes");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample(key: &str) -> Config {
|
||||
Config {
|
||||
database_url: String::new(),
|
||||
port: 0,
|
||||
internal_key: key.into(),
|
||||
accounts_grpc_url: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strong_key_passes() {
|
||||
assert!(sample(&"k".repeat(32)).validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_key_is_rejected() {
|
||||
assert!(sample("short").validate().is_err());
|
||||
}
|
||||
}
|
||||
83
backend/configs-service/src/error.rs
Normal file
83
backend/configs-service/src/error.rs
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
use axum::{
|
||||
Json,
|
||||
extract::{
|
||||
FromRequest, FromRequestParts,
|
||||
rejection::{JsonRejection, PathRejection, QueryRejection},
|
||||
},
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AppError {
|
||||
Validation(String),
|
||||
NotFound(String),
|
||||
Conflict(String),
|
||||
Forbidden(String),
|
||||
Internal(anyhow::Error),
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
fn into_response(self) -> Response {
|
||||
let (status, message) = match self {
|
||||
AppError::Validation(m) => (StatusCode::BAD_REQUEST, m),
|
||||
AppError::NotFound(m) => (StatusCode::NOT_FOUND, m),
|
||||
AppError::Conflict(m) => (StatusCode::CONFLICT, m),
|
||||
AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m),
|
||||
AppError::Internal(err) => {
|
||||
tracing::error!("internal error: {err:?}");
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, "internal error".into())
|
||||
}
|
||||
};
|
||||
(status, Json(json!({ "error": message }))).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<JsonRejection> for AppError {
|
||||
fn from(rejection: JsonRejection) -> Self {
|
||||
AppError::Validation(rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<QueryRejection> for AppError {
|
||||
fn from(rejection: QueryRejection) -> Self {
|
||||
AppError::Validation(rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PathRejection> for AppError {
|
||||
fn from(rejection: PathRejection) -> Self {
|
||||
AppError::Validation(rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop-in replacements for `axum::{Json, Query, Path}` that report rejections
|
||||
/// (malformed body/query/path) as our `{"error": ...}` shape instead of
|
||||
/// axum's plain-text default.
|
||||
#[derive(FromRequest)]
|
||||
#[from_request(via(axum::Json), rejection(AppError))]
|
||||
pub struct AppJson<T>(pub T);
|
||||
|
||||
impl<T> IntoResponse for AppJson<T>
|
||||
where
|
||||
Json<T>: IntoResponse,
|
||||
{
|
||||
fn into_response(self) -> Response {
|
||||
Json(self.0).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(FromRequestParts)]
|
||||
#[from_request(via(axum::extract::Query), rejection(AppError))]
|
||||
pub struct AppQuery<T>(pub T);
|
||||
|
||||
#[derive(FromRequestParts)]
|
||||
#[from_request(via(axum::extract::Path), rejection(AppError))]
|
||||
pub struct AppPath<T>(pub T);
|
||||
|
||||
impl From<sqlx::Error> for AppError {
|
||||
fn from(err: sqlx::Error) -> Self {
|
||||
AppError::Internal(err.into())
|
||||
}
|
||||
}
|
||||
55
backend/configs-service/src/lib.rs
Normal file
55
backend/configs-service/src/lib.rs
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
pub mod config;
|
||||
pub mod error;
|
||||
pub mod sharing;
|
||||
pub mod showcase;
|
||||
pub mod slots;
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
extract::DefaultBodyLimit,
|
||||
routing::{get, post},
|
||||
};
|
||||
use common::internal::{InternalKey, require_internal_key};
|
||||
use config::Config;
|
||||
use showcase::profiles::ProfileSource;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn build_app(pool: sqlx::PgPool, cfg: &Config, profiles: Arc<dyn ProfileSource>) -> Router {
|
||||
let slots_state = slots::handlers::SlotsState { pool: pool.clone() };
|
||||
let showcase_state = showcase::handlers::ShowcaseState { pool, profiles };
|
||||
let showcase_routes = Router::new()
|
||||
.route(
|
||||
"/configs/{slot}/publish",
|
||||
post(showcase::handlers::publish).delete(showcase::handlers::unpublish),
|
||||
)
|
||||
.route("/showcase", get(showcase::handlers::browse))
|
||||
.route("/showcase/{id}", get(showcase::handlers::detail))
|
||||
.route("/showcase/{id}/copy", post(showcase::handlers::copy))
|
||||
.with_state(showcase_state);
|
||||
let api = Router::new()
|
||||
.route("/configs", get(slots::handlers::list))
|
||||
.route(
|
||||
"/configs/{slot}",
|
||||
get(slots::handlers::get).put(slots::handlers::save),
|
||||
)
|
||||
.route(
|
||||
"/configs/shared/{code}",
|
||||
get(sharing::handlers::load_shared),
|
||||
)
|
||||
.route(
|
||||
"/configs/{slot}/regenerate-code",
|
||||
post(sharing::handlers::regenerate),
|
||||
)
|
||||
.with_state(slots_state)
|
||||
.merge(showcase_routes)
|
||||
.layer(DefaultBodyLimit::max(
|
||||
slots::handlers::MAX_DATA_BYTES + 16 * 1024,
|
||||
))
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
InternalKey::new(cfg.internal_key.clone()),
|
||||
require_internal_key,
|
||||
));
|
||||
Router::new()
|
||||
.route("/health", get(|| async { "ok" }))
|
||||
.merge(api)
|
||||
}
|
||||
20
backend/configs-service/src/main.rs
Normal file
20
backend/configs-service/src/main.rs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
dotenvy::dotenv().ok();
|
||||
tracing_subscriber::fmt::init();
|
||||
let cfg = configs_service::config::Config::from_env()?;
|
||||
cfg.validate()?;
|
||||
let pool = sqlx::PgPool::connect(&cfg.database_url).await?;
|
||||
sqlx::migrate!("./migrations").run(&pool).await?;
|
||||
let profiles = std::sync::Arc::new(
|
||||
configs_service::showcase::profiles::GrpcProfiles::connect_lazy(
|
||||
&cfg.accounts_grpc_url,
|
||||
&cfg.internal_key,
|
||||
)?,
|
||||
);
|
||||
let app = configs_service::build_app(pool, &cfg, profiles);
|
||||
let listener = tokio::net::TcpListener::bind(("0.0.0.0", cfg.port)).await?;
|
||||
tracing::info!("configs-service listening on {}", cfg.port);
|
||||
axum::serve(listener, app).await?;
|
||||
Ok(())
|
||||
}
|
||||
35
backend/configs-service/src/sharing/codes.rs
Normal file
35
backend/configs-service/src/sharing/codes.rs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
use rand::RngExt;
|
||||
|
||||
/// No 0/O, 1/I/L — players type these by hand in chat.
|
||||
pub const ALPHABET: &[u8] = b"23456789ABCDEFGHJKMNPQRSTUVWXYZ";
|
||||
pub const CODE_LEN: usize = 8;
|
||||
|
||||
pub fn new_code() -> String {
|
||||
let mut rng = rand::rng();
|
||||
(0..CODE_LEN)
|
||||
.map(|_| ALPHABET[rng.random_range(0..ALPHABET.len())] as char)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn normalize(code: &str) -> String {
|
||||
code.trim().to_uppercase()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn codes_use_only_the_unambiguous_alphabet() {
|
||||
for _ in 0..200 {
|
||||
let c = new_code();
|
||||
assert_eq!(c.len(), CODE_LEN);
|
||||
assert!(c.bytes().all(|b| ALPHABET.contains(&b)), "{c}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_trims_and_uppercases() {
|
||||
assert_eq!(normalize(" ab3k9mzq \n"), "AB3K9MZQ");
|
||||
}
|
||||
}
|
||||
52
backend/configs-service/src/sharing/handlers.rs
Normal file
52
backend/configs-service/src/sharing/handlers.rs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
use super::codes::normalize;
|
||||
use crate::error::{AppError, AppPath};
|
||||
use crate::slots::handlers::{SlotsState, validate_slot};
|
||||
use crate::slots::repo::{self, SharedConfig};
|
||||
use axum::{Json, extract::State};
|
||||
use common::internal::GatewayIdentity;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ShareCodeResponse {
|
||||
pub share_code: String,
|
||||
}
|
||||
|
||||
/// Easter egg: `IDDQD` (DOOM's god-mode cheat) never touches the DB — real
|
||||
/// share codes are drawn from an alphabet without `I` and can never equal it.
|
||||
fn god_mode() -> SharedConfig {
|
||||
SharedConfig {
|
||||
name: "God mode".into(),
|
||||
data: serde_json::json!({
|
||||
"modules": { "ChinaHat": { "enabled": true } },
|
||||
"note": "god mode: только шляпа"
|
||||
}),
|
||||
// DOOM's release date.
|
||||
updated_at: "1993-12-10T00:00:00Z".parse().expect("valid RFC3339 literal"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn load_shared(
|
||||
State(state): State<SlotsState>,
|
||||
AppPath(code): AppPath<String>,
|
||||
) -> Result<Json<SharedConfig>, AppError> {
|
||||
let code = normalize(&code);
|
||||
if code == "IDDQD" {
|
||||
return Ok(Json(god_mode()));
|
||||
}
|
||||
repo::by_share_code(&state.pool, &code)
|
||||
.await?
|
||||
.map(Json)
|
||||
.ok_or_else(|| AppError::NotFound("unknown share code".into()))
|
||||
}
|
||||
|
||||
pub async fn regenerate(
|
||||
State(state): State<SlotsState>,
|
||||
id: GatewayIdentity,
|
||||
AppPath(slot): AppPath<i16>,
|
||||
) -> Result<Json<ShareCodeResponse>, AppError> {
|
||||
let slot = validate_slot(slot)?;
|
||||
repo::regenerate_code(&state.pool, id.account_id, slot)
|
||||
.await?
|
||||
.map(|share_code| Json(ShareCodeResponse { share_code }))
|
||||
.ok_or_else(|| AppError::NotFound("slot is empty".into()))
|
||||
}
|
||||
2
backend/configs-service/src/sharing/mod.rs
Normal file
2
backend/configs-service/src/sharing/mod.rs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
pub mod codes;
|
||||
pub mod handlers;
|
||||
174
backend/configs-service/src/showcase/handlers.rs
Normal file
174
backend/configs-service/src/showcase/handlers.rs
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
use super::profiles::{Author, ProfileSource};
|
||||
use super::repo::{self, CopyOutcome, ListingRow, PAGE_SIZE, PublishOutcome, Sort};
|
||||
use crate::error::{AppError, AppJson, AppPath, AppQuery};
|
||||
use crate::slots::handlers::{has_control_chars, validate_slot};
|
||||
use axum::{Json, extract::State, http::StatusCode};
|
||||
use chrono::{DateTime, Utc};
|
||||
use common::internal::GatewayIdentity;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ShowcaseState {
|
||||
pub pool: sqlx::PgPool,
|
||||
pub profiles: Arc<dyn ProfileSource>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Listing {
|
||||
pub id: Uuid,
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub config_name: String,
|
||||
pub copies_count: i32,
|
||||
pub published_at: DateTime<Utc>,
|
||||
pub author: Option<Author>,
|
||||
}
|
||||
|
||||
fn to_listing(row: ListingRow, author: Option<Author>) -> Listing {
|
||||
Listing {
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
description: row.description,
|
||||
config_name: row.name,
|
||||
copies_count: row.copies_count,
|
||||
published_at: row.published_at,
|
||||
author,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PublishRequest {
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
pub async fn publish(
|
||||
State(state): State<ShowcaseState>,
|
||||
id: GatewayIdentity,
|
||||
AppPath(slot): AppPath<i16>,
|
||||
AppJson(req): AppJson<PublishRequest>,
|
||||
) -> Result<Json<serde_json::Value>, AppError> {
|
||||
let slot = validate_slot(slot)?;
|
||||
let title = req.title.trim();
|
||||
if title.is_empty() || title.chars().count() > 64 || has_control_chars(title) {
|
||||
return Err(AppError::Validation(
|
||||
"title must be 1..64 characters, no control characters".into(),
|
||||
));
|
||||
}
|
||||
let description = req.description.trim().to_owned();
|
||||
if description.chars().count() > 500 || has_control_chars(&description) {
|
||||
return Err(AppError::Validation(
|
||||
"description must be at most 500 characters, no control characters".into(),
|
||||
));
|
||||
}
|
||||
match repo::publish(&state.pool, id.account_id, slot, title, &description).await? {
|
||||
PublishOutcome::Published(listing) => {
|
||||
Ok(Json(serde_json::json!({ "listing_id": listing })))
|
||||
}
|
||||
PublishOutcome::SlotEmpty => Err(AppError::NotFound("slot is empty".into())),
|
||||
PublishOutcome::Hidden => Err(AppError::Forbidden(
|
||||
"listing is hidden by moderation".into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn unpublish(
|
||||
State(state): State<ShowcaseState>,
|
||||
id: GatewayIdentity,
|
||||
AppPath(slot): AppPath<i16>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
let slot = validate_slot(slot)?;
|
||||
if repo::unpublish(&state.pool, id.account_id, slot).await? {
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
} else {
|
||||
Err(AppError::NotFound("slot is not published".into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PageQuery {
|
||||
pub sort: Option<String>,
|
||||
pub page: Option<i64>,
|
||||
pub author: Option<Uuid>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct PageResponse {
|
||||
pub items: Vec<Listing>,
|
||||
pub page: i64,
|
||||
pub has_more: bool,
|
||||
}
|
||||
|
||||
pub async fn browse(
|
||||
State(state): State<ShowcaseState>,
|
||||
AppQuery(q): AppQuery<PageQuery>,
|
||||
) -> Result<Json<PageResponse>, AppError> {
|
||||
let sort = match q.sort.as_deref() {
|
||||
None | Some("new") => Sort::New,
|
||||
Some("popular") => Sort::Popular,
|
||||
Some(_) => return Err(AppError::Validation("sort must be new or popular".into())),
|
||||
};
|
||||
let page = q.page.unwrap_or(0).clamp(0, 10_000);
|
||||
let mut rows = repo::page(&state.pool, sort, page, q.author).await?;
|
||||
let has_more = rows.len() as i64 > PAGE_SIZE;
|
||||
rows.truncate(PAGE_SIZE as usize);
|
||||
let ids: Vec<Uuid> = rows.iter().map(|r| r.account_id).collect();
|
||||
let authors = state.profiles.profiles(&ids).await;
|
||||
let items = rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let author = authors.get(&r.account_id).cloned();
|
||||
to_listing(r, author)
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(PageResponse {
|
||||
items,
|
||||
page,
|
||||
has_more,
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn detail(
|
||||
State(state): State<ShowcaseState>,
|
||||
AppPath(id): AppPath<Uuid>,
|
||||
) -> Result<Json<serde_json::Value>, AppError> {
|
||||
let (row, data) = repo::detail(&state.pool, id)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound("no such listing".into()))?;
|
||||
let author = state
|
||||
.profiles
|
||||
.profiles(&[row.account_id])
|
||||
.await
|
||||
.remove(&row.account_id);
|
||||
let mut body =
|
||||
serde_json::to_value(to_listing(row, author)).map_err(|e| AppError::Internal(e.into()))?;
|
||||
body["data"] = data;
|
||||
Ok(Json(body))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CopyRequest {
|
||||
pub slot: i16,
|
||||
}
|
||||
|
||||
pub async fn copy(
|
||||
State(state): State<ShowcaseState>,
|
||||
id: GatewayIdentity,
|
||||
AppPath(listing): AppPath<Uuid>,
|
||||
AppJson(req): AppJson<CopyRequest>,
|
||||
) -> Result<(StatusCode, Json<crate::slots::repo::Slot>), AppError> {
|
||||
let slot = validate_slot(req.slot)?;
|
||||
match repo::copy_into(&state.pool, listing, id.account_id, slot).await? {
|
||||
CopyOutcome::ListingMissing => Err(AppError::NotFound("no such listing".into())),
|
||||
CopyOutcome::SlotOccupied => Err(AppError::Conflict("target slot is not empty".into())),
|
||||
CopyOutcome::Copied => {
|
||||
let saved = crate::slots::repo::get(&state.pool, id.account_id, slot)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::Internal(anyhow::anyhow!("copied slot vanished")))?;
|
||||
Ok((StatusCode::CREATED, Json(saved)))
|
||||
}
|
||||
}
|
||||
}
|
||||
3
backend/configs-service/src/showcase/mod.rs
Normal file
3
backend/configs-service/src/showcase/mod.rs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
pub mod handlers;
|
||||
pub mod profiles;
|
||||
pub mod repo;
|
||||
74
backend/configs-service/src/showcase/profiles.rs
Normal file
74
backend/configs-service/src/showcase/profiles.rs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
use common::internal::GrpcKeyAttach;
|
||||
use common::pb::accounts::{
|
||||
GetPublicProfilesRequest, accounts_internal_client::AccountsInternalClient,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use std::{collections::HashMap, future::Future, pin::Pin};
|
||||
use tonic::{
|
||||
service::interceptor::InterceptedService,
|
||||
transport::{Channel, Endpoint},
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Author {
|
||||
pub nick: String,
|
||||
pub avatar_url: Option<String>,
|
||||
}
|
||||
|
||||
pub type ProfilesFuture<'a> = Pin<Box<dyn Future<Output = HashMap<Uuid, Author>> + Send + 'a>>;
|
||||
|
||||
pub trait ProfileSource: Send + Sync + 'static {
|
||||
fn profiles<'a>(&'a self, ids: &'a [Uuid]) -> ProfilesFuture<'a>;
|
||||
}
|
||||
|
||||
pub struct GrpcProfiles {
|
||||
client: AccountsInternalClient<InterceptedService<Channel, GrpcKeyAttach>>,
|
||||
}
|
||||
|
||||
impl GrpcProfiles {
|
||||
pub fn connect_lazy(url: &str, internal_key: &str) -> anyhow::Result<Self> {
|
||||
let channel = Endpoint::from_shared(url.to_owned())?
|
||||
.timeout(std::time::Duration::from_secs(3))
|
||||
.connect_lazy();
|
||||
Ok(GrpcProfiles {
|
||||
client: AccountsInternalClient::with_interceptor(
|
||||
channel,
|
||||
GrpcKeyAttach::new(internal_key)?,
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ProfileSource for GrpcProfiles {
|
||||
fn profiles<'a>(&'a self, ids: &'a [Uuid]) -> ProfilesFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let request = GetPublicProfilesRequest {
|
||||
account_ids: ids.iter().map(Uuid::to_string).collect(),
|
||||
};
|
||||
match self.client.clone().get_public_profiles(request).await {
|
||||
Ok(reply) => reply
|
||||
.into_inner()
|
||||
.profiles
|
||||
.into_iter()
|
||||
.filter_map(|p| {
|
||||
let id = Uuid::parse_str(&p.account_id).ok()?;
|
||||
let avatar_url = (!p.avatar_url.is_empty()).then_some(p.avatar_url);
|
||||
Some((
|
||||
id,
|
||||
Author {
|
||||
nick: p.display_nick,
|
||||
avatar_url,
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect(),
|
||||
Err(status) => {
|
||||
// Showcase must stay browsable when accounts-service is down.
|
||||
tracing::warn!("GetPublicProfiles failed: {status}");
|
||||
HashMap::new()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
213
backend/configs-service/src/showcase/repo.rs
Normal file
213
backend/configs-service/src/showcase/repo.rs
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
use chrono::{DateTime, Utc};
|
||||
use sqlx::{PgPool, Postgres, query::QueryAs, query_as};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const PAGE_SIZE: i64 = 20;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Sort {
|
||||
New,
|
||||
Popular,
|
||||
}
|
||||
|
||||
#[derive(Debug, sqlx::FromRow)]
|
||||
pub struct ListingRow {
|
||||
pub id: Uuid,
|
||||
pub account_id: Uuid,
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub copies_count: i32,
|
||||
pub published_at: DateTime<Utc>,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
const LISTING_FROM: &str = " FROM showcase_listings l
|
||||
JOIN config_slots s ON s.account_id = l.account_id AND s.slot_index = l.slot_index";
|
||||
const LISTING_COLS: &str =
|
||||
"l.id, l.account_id, l.title, l.description, l.copies_count, l.published_at, s.name";
|
||||
|
||||
pub enum PublishOutcome {
|
||||
Published(Uuid),
|
||||
SlotEmpty,
|
||||
Hidden,
|
||||
}
|
||||
|
||||
pub async fn publish(
|
||||
pool: &PgPool,
|
||||
account_id: Uuid,
|
||||
slot: i16,
|
||||
title: &str,
|
||||
description: &str,
|
||||
) -> Result<PublishOutcome, sqlx::Error> {
|
||||
// The FK to config_slots makes this fail for an empty slot; check first for a clean 404.
|
||||
let exists: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM config_slots WHERE account_id = $1 AND slot_index = $2)",
|
||||
)
|
||||
.bind(account_id)
|
||||
.bind(slot)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
if !exists {
|
||||
return Ok(PublishOutcome::SlotEmpty);
|
||||
}
|
||||
let hidden: Option<bool> = sqlx::query_scalar(
|
||||
"SELECT hidden FROM showcase_listings WHERE account_id = $1 AND slot_index = $2",
|
||||
)
|
||||
.bind(account_id)
|
||||
.bind(slot)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
if hidden == Some(true) {
|
||||
return Ok(PublishOutcome::Hidden);
|
||||
}
|
||||
let id = sqlx::query_scalar(
|
||||
"INSERT INTO showcase_listings (account_id, slot_index, title, description)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (account_id, slot_index)
|
||||
DO UPDATE SET title = EXCLUDED.title, description = EXCLUDED.description
|
||||
RETURNING id",
|
||||
)
|
||||
.bind(account_id)
|
||||
.bind(slot)
|
||||
.bind(title)
|
||||
.bind(description)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(PublishOutcome::Published(id))
|
||||
}
|
||||
|
||||
pub async fn unpublish(pool: &PgPool, account_id: Uuid, slot: i16) -> Result<bool, sqlx::Error> {
|
||||
let r = sqlx::query(
|
||||
"DELETE FROM showcase_listings WHERE account_id = $1 AND slot_index = $2 AND NOT hidden",
|
||||
)
|
||||
.bind(account_id)
|
||||
.bind(slot)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(r.rows_affected() == 1)
|
||||
}
|
||||
|
||||
/// Returns up to PAGE_SIZE + 1 rows; the caller uses the extra one for `has_more`.
|
||||
pub async fn page(
|
||||
pool: &PgPool,
|
||||
sort: Sort,
|
||||
page: i64,
|
||||
author: Option<Uuid>,
|
||||
) -> Result<Vec<ListingRow>, sqlx::Error> {
|
||||
// The dynamic parts are an enum-derived ORDER BY and a fixed author filter
|
||||
// constant; all values stay bound parameters, so AssertSqlSafe is honest.
|
||||
let order = match sort {
|
||||
Sort::New => "l.published_at DESC",
|
||||
Sort::Popular => "l.copies_count DESC, l.published_at DESC",
|
||||
};
|
||||
let author_filter = if author.is_some() {
|
||||
"AND l.account_id = $3"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let sql = format!(
|
||||
"SELECT {LISTING_COLS}{LISTING_FROM} WHERE NOT l.hidden {author_filter} ORDER BY {order}, l.id \
|
||||
LIMIT $1 OFFSET $2"
|
||||
);
|
||||
let mut query: QueryAs<'_, Postgres, ListingRow, _> =
|
||||
query_as::<Postgres, ListingRow>(sqlx::AssertSqlSafe(sql))
|
||||
.bind(PAGE_SIZE + 1)
|
||||
.bind(page * PAGE_SIZE);
|
||||
if let Some(id) = author {
|
||||
query = query.bind(id);
|
||||
}
|
||||
query.fetch_all(pool).await
|
||||
}
|
||||
|
||||
pub async fn detail(
|
||||
pool: &PgPool,
|
||||
id: Uuid,
|
||||
) -> Result<Option<(ListingRow, serde_json::Value)>, sqlx::Error> {
|
||||
let Some((row, data)) = sqlx::query_as::<_, (Uuid, Uuid, String, String, i32, DateTime<Utc>, String, serde_json::Value)>(
|
||||
"SELECT l.id, l.account_id, l.title, l.description, l.copies_count, l.published_at, s.name, s.data
|
||||
FROM showcase_listings l
|
||||
JOIN config_slots s ON s.account_id = l.account_id AND s.slot_index = l.slot_index
|
||||
WHERE l.id = $1 AND NOT l.hidden",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
.map(|(id, account_id, title, description, copies_count, published_at, name, data)| {
|
||||
(
|
||||
ListingRow {
|
||||
id,
|
||||
account_id,
|
||||
title,
|
||||
description,
|
||||
copies_count,
|
||||
published_at,
|
||||
name,
|
||||
},
|
||||
data,
|
||||
)
|
||||
})
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some((row, data)))
|
||||
}
|
||||
|
||||
pub enum CopyOutcome {
|
||||
Copied,
|
||||
ListingMissing,
|
||||
SlotOccupied,
|
||||
}
|
||||
|
||||
pub async fn copy_into(
|
||||
pool: &PgPool,
|
||||
listing: Uuid,
|
||||
account_id: Uuid,
|
||||
slot: i16,
|
||||
) -> Result<CopyOutcome, sqlx::Error> {
|
||||
let mut tx = pool.begin().await?;
|
||||
let Some((owner, name, data)): Option<(Uuid, String, serde_json::Value)> = sqlx::query_as(
|
||||
"SELECT l.account_id, s.name, s.data FROM showcase_listings l JOIN config_slots s
|
||||
ON s.account_id = l.account_id AND s.slot_index = l.slot_index
|
||||
WHERE l.id = $1 AND NOT l.hidden",
|
||||
)
|
||||
.bind(listing)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
else {
|
||||
return Ok(CopyOutcome::ListingMissing);
|
||||
};
|
||||
// Share codes are globally unique; retry a handful of times on collision
|
||||
// like `save` does, rather than failing the whole copy.
|
||||
let mut attempts = 0;
|
||||
let inserted_rows = loop {
|
||||
let result = sqlx::query(
|
||||
"INSERT INTO config_slots (account_id, slot_index, name, data, share_code)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (account_id, slot_index) DO NOTHING",
|
||||
)
|
||||
.bind(account_id)
|
||||
.bind(slot)
|
||||
.bind(&name)
|
||||
.bind(&data)
|
||||
.bind(crate::sharing::codes::new_code())
|
||||
.execute(&mut *tx)
|
||||
.await;
|
||||
match result {
|
||||
Err(err) if crate::slots::repo::is_share_code_collision(&err) && attempts < 3 => {
|
||||
attempts += 1;
|
||||
}
|
||||
other => break other?.rows_affected(),
|
||||
}
|
||||
};
|
||||
if inserted_rows == 0 {
|
||||
return Ok(CopyOutcome::SlotOccupied);
|
||||
}
|
||||
if owner != account_id {
|
||||
sqlx::query("UPDATE showcase_listings SET copies_count = copies_count + 1 WHERE id = $1")
|
||||
.bind(listing)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(CopyOutcome::Copied)
|
||||
}
|
||||
89
backend/configs-service/src/slots/handlers.rs
Normal file
89
backend/configs-service/src/slots/handlers.rs
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
use super::repo::{self, Slot, SlotSummary};
|
||||
use crate::error::{AppError, AppJson, AppPath};
|
||||
use axum::{Json, extract::State};
|
||||
use common::internal::GatewayIdentity;
|
||||
use serde::Deserialize;
|
||||
|
||||
pub const MAX_DATA_BYTES: usize = 256 * 1024;
|
||||
const MAX_NAME_CHARS: usize = 32;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SlotsState {
|
||||
pub pool: sqlx::PgPool,
|
||||
}
|
||||
|
||||
pub fn validate_slot(slot: i16) -> Result<i16, AppError> {
|
||||
if (1..=4).contains(&slot) {
|
||||
Ok(slot)
|
||||
} else {
|
||||
Err(AppError::Validation("slot must be 1..4".into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Rejects any ASCII/Unicode control character (including a bare CR/LF), which
|
||||
/// would otherwise corrupt log lines or list rendering downstream.
|
||||
pub fn has_control_chars(s: &str) -> bool {
|
||||
s.chars().any(|c| c.is_control())
|
||||
}
|
||||
|
||||
pub fn validate_name(name: &str) -> Result<String, AppError> {
|
||||
let name = name.trim();
|
||||
let len = name.chars().count();
|
||||
if len == 0 || len > MAX_NAME_CHARS {
|
||||
return Err(AppError::Validation(format!(
|
||||
"name must be 1..{MAX_NAME_CHARS} characters"
|
||||
)));
|
||||
}
|
||||
if has_control_chars(name) {
|
||||
return Err(AppError::Validation(
|
||||
"name must not contain control characters".into(),
|
||||
));
|
||||
}
|
||||
Ok(name.to_owned())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SaveRequest {
|
||||
pub name: String,
|
||||
pub data: serde_json::Value,
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
State(state): State<SlotsState>,
|
||||
id: GatewayIdentity,
|
||||
) -> Result<Json<Vec<SlotSummary>>, AppError> {
|
||||
Ok(Json(repo::list(&state.pool, id.account_id).await?))
|
||||
}
|
||||
|
||||
pub async fn get(
|
||||
State(state): State<SlotsState>,
|
||||
id: GatewayIdentity,
|
||||
AppPath(slot): AppPath<i16>,
|
||||
) -> Result<Json<Slot>, AppError> {
|
||||
let slot = validate_slot(slot)?;
|
||||
repo::get(&state.pool, id.account_id, slot)
|
||||
.await?
|
||||
.map(Json)
|
||||
.ok_or_else(|| AppError::NotFound("slot is empty".into()))
|
||||
}
|
||||
|
||||
pub async fn save(
|
||||
State(state): State<SlotsState>,
|
||||
id: GatewayIdentity,
|
||||
AppPath(slot): AppPath<i16>,
|
||||
AppJson(req): AppJson<SaveRequest>,
|
||||
) -> Result<Json<Slot>, AppError> {
|
||||
let slot = validate_slot(slot)?;
|
||||
let name = validate_name(&req.name)?;
|
||||
let size = serde_json::to_vec(&req.data)
|
||||
.map_err(|e| AppError::Internal(e.into()))?
|
||||
.len();
|
||||
if size > MAX_DATA_BYTES {
|
||||
return Err(AppError::Validation(format!(
|
||||
"config data must be at most {MAX_DATA_BYTES} bytes"
|
||||
)));
|
||||
}
|
||||
Ok(Json(
|
||||
repo::save(&state.pool, id.account_id, slot, &name, &req.data).await?,
|
||||
))
|
||||
}
|
||||
2
backend/configs-service/src/slots/mod.rs
Normal file
2
backend/configs-service/src/slots/mod.rs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
pub mod handlers;
|
||||
pub mod repo;
|
||||
119
backend/configs-service/src/slots/repo.rs
Normal file
119
backend/configs-service/src/slots/repo.rs
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
use crate::sharing::codes::new_code;
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Serialize;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Serialize, sqlx::FromRow)]
|
||||
pub struct SlotSummary {
|
||||
pub slot: i16,
|
||||
pub name: String,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
pub share_code: String,
|
||||
pub published: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, sqlx::FromRow)]
|
||||
pub struct Slot {
|
||||
pub slot: i16,
|
||||
pub name: String,
|
||||
pub data: serde_json::Value,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
pub share_code: String,
|
||||
}
|
||||
|
||||
pub async fn list(pool: &PgPool, account_id: Uuid) -> Result<Vec<SlotSummary>, sqlx::Error> {
|
||||
sqlx::query_as(
|
||||
"SELECT s.slot_index AS slot, s.name, s.updated_at, s.share_code, (l.id IS NOT NULL) AS published
|
||||
FROM config_slots s
|
||||
LEFT JOIN showcase_listings l ON l.account_id = s.account_id AND l.slot_index = s.slot_index
|
||||
WHERE s.account_id = $1 ORDER BY s.slot_index",
|
||||
)
|
||||
.bind(account_id)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get(pool: &PgPool, account_id: Uuid, slot: i16) -> Result<Option<Slot>, sqlx::Error> {
|
||||
sqlx::query_as(
|
||||
"SELECT slot_index AS slot, name, data, updated_at, share_code
|
||||
FROM config_slots WHERE account_id = $1 AND slot_index = $2",
|
||||
)
|
||||
.bind(account_id)
|
||||
.bind(slot)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) fn is_share_code_collision(err: &sqlx::Error) -> bool {
|
||||
matches!(err, sqlx::Error::Database(db) if db.constraint() == Some("config_slots_share_code_key"))
|
||||
}
|
||||
|
||||
pub async fn save(
|
||||
pool: &PgPool,
|
||||
account_id: Uuid,
|
||||
slot: i16,
|
||||
name: &str,
|
||||
data: &serde_json::Value,
|
||||
) -> Result<Slot, sqlx::Error> {
|
||||
// share_code is only used on INSERT; an update keeps the existing one.
|
||||
// 31^8 codes make collisions vanishingly rare, but never fatal.
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
let result = sqlx::query_as(
|
||||
"INSERT INTO config_slots (account_id, slot_index, name, data, share_code)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (account_id, slot_index)
|
||||
DO UPDATE SET name = EXCLUDED.name, data = EXCLUDED.data, updated_at = now()
|
||||
RETURNING slot_index AS slot, name, data, updated_at, share_code",
|
||||
)
|
||||
.bind(account_id)
|
||||
.bind(slot)
|
||||
.bind(name)
|
||||
.bind(data)
|
||||
.bind(new_code())
|
||||
.fetch_one(pool)
|
||||
.await;
|
||||
match result {
|
||||
Err(err) if is_share_code_collision(&err) && attempts < 3 => attempts += 1,
|
||||
other => return other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, sqlx::FromRow)]
|
||||
pub struct SharedConfig {
|
||||
pub name: String,
|
||||
pub data: serde_json::Value,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
pub async fn by_share_code(pool: &PgPool, code: &str) -> Result<Option<SharedConfig>, sqlx::Error> {
|
||||
sqlx::query_as("SELECT name, data, updated_at FROM config_slots WHERE share_code = $1")
|
||||
.bind(code)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn regenerate_code(
|
||||
pool: &PgPool,
|
||||
account_id: Uuid,
|
||||
slot: i16,
|
||||
) -> Result<Option<String>, sqlx::Error> {
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
let result = sqlx::query_scalar(
|
||||
"UPDATE config_slots SET share_code = $3
|
||||
WHERE account_id = $1 AND slot_index = $2 RETURNING share_code",
|
||||
)
|
||||
.bind(account_id)
|
||||
.bind(slot)
|
||||
.bind(new_code())
|
||||
.fetch_optional(pool)
|
||||
.await;
|
||||
match result {
|
||||
Err(err) if is_share_code_collision(&err) && attempts < 3 => attempts += 1,
|
||||
other => return other,
|
||||
}
|
||||
}
|
||||
}
|
||||
72
backend/configs-service/tests/common/mod.rs
Normal file
72
backend/configs-service/tests/common/mod.rs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
#![allow(dead_code)]
|
||||
|
||||
use axum_test::TestServer;
|
||||
use configs_service::config::Config;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[allow(unused_imports)] // used by slots/showcase tests from Task 2 on
|
||||
pub use ::common::internal::ACCOUNT_ID_HEADER;
|
||||
|
||||
pub const TEST_INTERNAL_KEY: &str = "internal-key-internal-key-internal!!";
|
||||
|
||||
pub async fn test_pool() -> sqlx::PgPool {
|
||||
let url = std::env::var("CONFIGS_DATABASE_URL")
|
||||
.unwrap_or_else(|_| "postgres://lovisual:lovisual@localhost:5432/configs_db".into());
|
||||
let pool = sqlx::PgPool::connect(&url)
|
||||
.await
|
||||
.expect("connect to configs_db");
|
||||
sqlx::migrate!("./migrations")
|
||||
.run(&pool)
|
||||
.await
|
||||
.expect("run migrations");
|
||||
pool
|
||||
}
|
||||
|
||||
pub fn test_config() -> Config {
|
||||
Config {
|
||||
database_url: String::new(),
|
||||
port: 0,
|
||||
internal_key: TEST_INTERNAL_KEY.into(),
|
||||
accounts_grpc_url: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn test_server(app: axum::Router) -> TestServer {
|
||||
let mut server = TestServer::new(app);
|
||||
server.add_header(::common::internal::INTERNAL_KEY_HEADER, TEST_INTERNAL_KEY);
|
||||
server
|
||||
}
|
||||
|
||||
/// Accounts live in another service; here an account is just a fresh UUID.
|
||||
pub fn new_account() -> Uuid {
|
||||
Uuid::new_v4()
|
||||
}
|
||||
|
||||
use configs_service::showcase::profiles::{Author, ProfileSource, ProfilesFuture};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Every account is "Author-<first 4 chars of id>".
|
||||
pub struct FakeProfiles;
|
||||
|
||||
impl ProfileSource for FakeProfiles {
|
||||
fn profiles<'a>(&'a self, ids: &'a [Uuid]) -> ProfilesFuture<'a> {
|
||||
Box::pin(async move {
|
||||
ids.iter()
|
||||
.map(|id| {
|
||||
(
|
||||
*id,
|
||||
Author {
|
||||
nick: format!("Author-{}", &id.to_string()[..4]),
|
||||
avatar_url: None,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect::<HashMap<_, _>>()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn no_profiles() -> Arc<dyn ProfileSource> {
|
||||
Arc::new(FakeProfiles)
|
||||
}
|
||||
93
backend/configs-service/tests/sharing.rs
Normal file
93
backend/configs-service/tests/sharing.rs
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
mod common;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::json;
|
||||
|
||||
async fn server() -> axum_test::TestServer {
|
||||
common::test_server(configs_service::build_app(
|
||||
common::test_pool().await,
|
||||
&common::test_config(),
|
||||
common::no_profiles(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn save(s: &axum_test::TestServer, owner: &str) -> String {
|
||||
let r: serde_json::Value = s
|
||||
.put("/configs/1")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, owner)
|
||||
.json(&json!({ "name": "legit", "data": { "k": 1 } }))
|
||||
.await
|
||||
.json();
|
||||
r["share_code"].as_str().unwrap().to_owned()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn iddqd_is_a_god_mode_easter_egg_without_touching_the_db() {
|
||||
let s = server().await;
|
||||
for code in ["IDDQD", "iddqd", "%20%20IdDqD%20%20"] {
|
||||
let r = s.get(&format!("/configs/shared/{code}")).await;
|
||||
r.assert_status_ok();
|
||||
let body: serde_json::Value = r.json();
|
||||
assert_eq!(body["name"], "God mode");
|
||||
assert_eq!(body["data"]["modules"]["ChinaHat"]["enabled"], true);
|
||||
assert_eq!(body["updated_at"], "1993-12-10T00:00:00Z");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn anyone_can_load_by_code_case_insensitively_without_owner_leak() {
|
||||
let s = server().await;
|
||||
let code = save(&s, &common::new_account().to_string()).await;
|
||||
let res = s
|
||||
.get(&format!("/configs/shared/{}", code.to_lowercase()))
|
||||
.await;
|
||||
res.assert_status_ok();
|
||||
let body: serde_json::Value = res.json();
|
||||
assert_eq!(body["name"], "legit");
|
||||
assert_eq!(body["data"], json!({ "k": 1 }));
|
||||
assert!(body.get("account_id").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn regenerate_invalidates_the_old_code() {
|
||||
let s = server().await;
|
||||
let owner = common::new_account().to_string();
|
||||
let old = save(&s, &owner).await;
|
||||
let res = s
|
||||
.post("/configs/1/regenerate-code")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &owner)
|
||||
.await;
|
||||
res.assert_status_ok();
|
||||
let new = res.json::<serde_json::Value>()["share_code"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert_ne!(old, new);
|
||||
s.get(&format!("/configs/shared/{old}"))
|
||||
.await
|
||||
.assert_status(StatusCode::NOT_FOUND);
|
||||
s.get(&format!("/configs/shared/{new}"))
|
||||
.await
|
||||
.assert_status_ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn regenerate_on_empty_slot_is_404_and_needs_identity() {
|
||||
let s = server().await;
|
||||
s.post("/configs/4/regenerate-code")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, common::new_account().to_string())
|
||||
.await
|
||||
.assert_status(StatusCode::NOT_FOUND);
|
||||
s.post("/configs/4/regenerate-code")
|
||||
.await
|
||||
.assert_status_unauthorized();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_code_is_404() {
|
||||
server()
|
||||
.await
|
||||
.get("/configs/shared/ZZZZZZZZ")
|
||||
.await
|
||||
.assert_status(StatusCode::NOT_FOUND);
|
||||
}
|
||||
261
backend/configs-service/tests/showcase.rs
Normal file
261
backend/configs-service/tests/showcase.rs
Normal file
|
|
@ -0,0 +1,261 @@
|
|||
mod common;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::json;
|
||||
|
||||
async fn server() -> axum_test::TestServer {
|
||||
common::test_server(configs_service::build_app(
|
||||
common::test_pool().await,
|
||||
&common::test_config(),
|
||||
common::no_profiles(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn publish(s: &axum_test::TestServer, owner: &str, title: &str) -> String {
|
||||
s.put("/configs/1")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, owner)
|
||||
.json(&json!({ "name": "cfg", "data": { "t": title } }))
|
||||
.await
|
||||
.assert_status_ok();
|
||||
let r = s
|
||||
.post("/configs/1/publish")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, owner)
|
||||
.json(&json!({ "title": title, "description": "desc" }))
|
||||
.await;
|
||||
r.assert_status_ok();
|
||||
r.json::<serde_json::Value>()["listing_id"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn published_listing_shows_up_publicly_with_author() {
|
||||
let s = server().await;
|
||||
let owner = common::new_account();
|
||||
let id = publish(&s, &owner.to_string(), "Best PvP").await;
|
||||
|
||||
let page: serde_json::Value = s.get("/showcase?sort=new&page=0").await.json();
|
||||
let item = page["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|i| i["id"] == id)
|
||||
.expect("listed");
|
||||
assert_eq!(item["title"], "Best PvP");
|
||||
assert_eq!(item["config_name"], "cfg");
|
||||
assert_eq!(
|
||||
item["author"]["nick"],
|
||||
format!("Author-{}", &owner.to_string()[..4])
|
||||
);
|
||||
assert!(item.get("account_id").is_none());
|
||||
|
||||
let detail: serde_json::Value = s.get(&format!("/showcase/{id}")).await.json();
|
||||
assert_eq!(detail["data"], json!({ "t": "Best PvP" }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unpublish_removes_listing() {
|
||||
let s = server().await;
|
||||
let owner = common::new_account().to_string();
|
||||
let id = publish(&s, &owner, "gone").await;
|
||||
s.delete("/configs/1/publish")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &owner)
|
||||
.await
|
||||
.assert_status(StatusCode::NO_CONTENT);
|
||||
s.get(&format!("/showcase/{id}"))
|
||||
.await
|
||||
.assert_status(StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn copy_goes_into_a_free_slot_and_counts() {
|
||||
let s = server().await;
|
||||
let id = publish(&s, &common::new_account().to_string(), "copy me").await;
|
||||
let me = common::new_account().to_string();
|
||||
|
||||
let r = s
|
||||
.post(&format!("/showcase/{id}/copy"))
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &me)
|
||||
.json(&json!({ "slot": 3 }))
|
||||
.await;
|
||||
r.assert_status(StatusCode::CREATED);
|
||||
assert_eq!(
|
||||
r.json::<serde_json::Value>()["data"],
|
||||
json!({ "t": "copy me" })
|
||||
);
|
||||
|
||||
s.post(&format!("/showcase/{id}/copy"))
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &me)
|
||||
.json(&json!({ "slot": 3 }))
|
||||
.await
|
||||
.assert_status(StatusCode::CONFLICT);
|
||||
|
||||
let detail: serde_json::Value = s.get(&format!("/showcase/{id}")).await.json();
|
||||
assert_eq!(detail["copies_count"], 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn publish_validation_and_auth() {
|
||||
let s = server().await;
|
||||
let owner = common::new_account().to_string();
|
||||
s.post("/configs/2/publish")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &owner)
|
||||
.json(&json!({ "title": "x" }))
|
||||
.await
|
||||
.assert_status(StatusCode::NOT_FOUND);
|
||||
s.put("/configs/2")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &owner)
|
||||
.json(&json!({ "name": "n", "data": {} }))
|
||||
.await;
|
||||
s.post("/configs/2/publish")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &owner)
|
||||
.json(&json!({ "title": " " }))
|
||||
.await
|
||||
.assert_status(StatusCode::BAD_REQUEST);
|
||||
s.post("/configs/2/publish")
|
||||
.json(&json!({ "title": "x" }))
|
||||
.await
|
||||
.assert_status_unauthorized();
|
||||
s.get("/showcase?sort=bogus")
|
||||
.await
|
||||
.assert_status(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn popular_sort_orders_by_copies() {
|
||||
let s = server().await;
|
||||
let low = publish(&s, &common::new_account().to_string(), "low").await;
|
||||
let high = publish(&s, &common::new_account().to_string(), "high").await;
|
||||
for _ in 0..2 {
|
||||
s.post(&format!("/showcase/{high}/copy"))
|
||||
.add_header(
|
||||
common::ACCOUNT_ID_HEADER,
|
||||
&common::new_account().to_string(),
|
||||
)
|
||||
.json(&json!({ "slot": 1 }))
|
||||
.await
|
||||
.assert_status(StatusCode::CREATED);
|
||||
}
|
||||
let page: serde_json::Value = s.get("/showcase?sort=popular").await.json();
|
||||
let ids: Vec<&str> = page["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|i| i["id"].as_str().unwrap())
|
||||
.collect();
|
||||
let hi = ids.iter().position(|i| *i == high);
|
||||
let lo = ids.iter().position(|i| *i == low);
|
||||
assert!(
|
||||
hi.is_some() && lo.is_none_or(|lo| hi.unwrap() < lo),
|
||||
"high-copy listing must come first"
|
||||
);
|
||||
}
|
||||
|
||||
async fn hide(pool: &sqlx::PgPool, id: &str) {
|
||||
sqlx::query("UPDATE showcase_listings SET hidden = true WHERE id = $1")
|
||||
.bind(uuid::Uuid::parse_str(id).unwrap())
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hidden_listing_is_invisible_everywhere_and_moderation_wins() {
|
||||
let pool = common::test_pool().await;
|
||||
let s = common::test_server(configs_service::build_app(
|
||||
pool.clone(),
|
||||
&common::test_config(),
|
||||
common::no_profiles(),
|
||||
));
|
||||
let owner = common::new_account().to_string();
|
||||
let id = publish(&s, &owner, "moderate me").await;
|
||||
hide(&pool, &id).await;
|
||||
|
||||
// Invisible in browse.
|
||||
let page: serde_json::Value = s.get("/showcase?sort=new&page=0").await.json();
|
||||
assert!(
|
||||
page["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|i| i["id"] != id),
|
||||
"hidden listing must not appear in browse"
|
||||
);
|
||||
|
||||
// Invisible in the author filter.
|
||||
let page: serde_json::Value = s.get(&format!("/showcase?author={owner}")).await.json();
|
||||
assert!(
|
||||
page["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|i| i["id"] != id),
|
||||
"hidden listing must not appear in the author filter"
|
||||
);
|
||||
|
||||
// 404 on detail.
|
||||
s.get(&format!("/showcase/{id}"))
|
||||
.await
|
||||
.assert_status(StatusCode::NOT_FOUND);
|
||||
|
||||
// 404 on copy.
|
||||
s.post(&format!("/showcase/{id}/copy"))
|
||||
.add_header(
|
||||
common::ACCOUNT_ID_HEADER,
|
||||
&common::new_account().to_string(),
|
||||
)
|
||||
.json(&json!({ "slot": 3 }))
|
||||
.await
|
||||
.assert_status(StatusCode::NOT_FOUND);
|
||||
|
||||
// Unpublishing a hidden listing is a 404, and it stays in the DB.
|
||||
s.delete("/configs/1/publish")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &owner)
|
||||
.await
|
||||
.assert_status(StatusCode::NOT_FOUND);
|
||||
let still_there: i64 = sqlx::query_scalar("SELECT count(*) FROM showcase_listings WHERE id = $1")
|
||||
.bind(uuid::Uuid::parse_str(&id).unwrap())
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(still_there, 1, "unpublish must not delete a hidden listing");
|
||||
|
||||
// Republishing a hidden slot never unhides it: 403, and it's still hidden.
|
||||
s.post("/configs/1/publish")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &owner)
|
||||
.json(&json!({ "title": "sneaky", "description": "" }))
|
||||
.await
|
||||
.assert_status(StatusCode::FORBIDDEN);
|
||||
let hidden: bool = sqlx::query_scalar("SELECT hidden FROM showcase_listings WHERE id = $1")
|
||||
.bind(uuid::Uuid::parse_str(&id).unwrap())
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(hidden, "publish must never clear the hidden flag");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn showcase_can_be_filtered_by_author() {
|
||||
let s = server().await;
|
||||
let owner = common::new_account().to_string();
|
||||
let mine = publish(&s, &owner, "mine one").await;
|
||||
let theirs = publish(&s, &common::new_account().to_string(), "someone else").await;
|
||||
|
||||
let page: serde_json::Value = s.get(&format!("/showcase?author={owner}")).await.json();
|
||||
let ids: Vec<&str> = page["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|i| i["id"].as_str().unwrap())
|
||||
.collect();
|
||||
assert!(ids.contains(&mine.as_str()), "own listing must be listed");
|
||||
assert!(
|
||||
!ids.contains(&theirs.as_str()),
|
||||
"other authors filtered out"
|
||||
);
|
||||
|
||||
s.get("/showcase?author=not-a-uuid")
|
||||
.await
|
||||
.assert_status(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
128
backend/configs-service/tests/slots.rs
Normal file
128
backend/configs-service/tests/slots.rs
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
mod common;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::json;
|
||||
|
||||
async fn server() -> axum_test::TestServer {
|
||||
common::test_server(configs_service::build_app(
|
||||
common::test_pool().await,
|
||||
&common::test_config(),
|
||||
common::no_profiles(),
|
||||
))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn health_ok_and_api_requires_internal_key() {
|
||||
let pool = common::test_pool().await;
|
||||
let raw = axum_test::TestServer::new(configs_service::build_app(
|
||||
pool,
|
||||
&common::test_config(),
|
||||
common::no_profiles(),
|
||||
));
|
||||
raw.get("/health").await.assert_status_ok();
|
||||
raw.get("/configs")
|
||||
.await
|
||||
.assert_status(StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn save_then_get_then_list() {
|
||||
let s = server().await;
|
||||
let me = common::new_account();
|
||||
let data = json!({ "modules": { "Hud": { "enabled": true } } });
|
||||
|
||||
let saved = s
|
||||
.put("/configs/2")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, me.to_string())
|
||||
.json(&json!({ "name": " pvp ", "data": data }))
|
||||
.await;
|
||||
saved.assert_status_ok();
|
||||
let saved: serde_json::Value = saved.json();
|
||||
assert_eq!(saved["name"], "pvp");
|
||||
assert_eq!(saved["share_code"].as_str().unwrap().len(), 8);
|
||||
|
||||
let got: serde_json::Value = s
|
||||
.get("/configs/2")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, me.to_string())
|
||||
.await
|
||||
.json();
|
||||
assert_eq!(got["data"], data);
|
||||
|
||||
let list: Vec<serde_json::Value> = s
|
||||
.get("/configs")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, me.to_string())
|
||||
.await
|
||||
.json();
|
||||
assert_eq!(list.len(), 1);
|
||||
assert_eq!(list[0]["slot"], 2);
|
||||
assert_eq!(list[0]["published"], false);
|
||||
assert!(
|
||||
list[0].get("data").is_none(),
|
||||
"list must not ship full configs"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resave_keeps_share_code_and_overwrites_data() {
|
||||
let s = server().await;
|
||||
let me = common::new_account().to_string();
|
||||
let first: serde_json::Value = s
|
||||
.put("/configs/1")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &me)
|
||||
.json(&json!({ "name": "a", "data": 1 }))
|
||||
.await
|
||||
.json();
|
||||
let second: serde_json::Value = s
|
||||
.put("/configs/1")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &me)
|
||||
.json(&json!({ "name": "b", "data": 2 }))
|
||||
.await
|
||||
.json();
|
||||
assert_eq!(first["share_code"], second["share_code"]);
|
||||
assert_eq!(second["data"], 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validation_errors() {
|
||||
let s = server().await;
|
||||
let me = common::new_account().to_string();
|
||||
for slot in ["0", "5"] {
|
||||
s.put(&format!("/configs/{slot}"))
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &me)
|
||||
.json(&json!({ "name": "x", "data": {} }))
|
||||
.await
|
||||
.assert_status(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
s.put("/configs/1")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &me)
|
||||
.json(&json!({ "name": " ", "data": {} }))
|
||||
.await
|
||||
.assert_status(StatusCode::BAD_REQUEST);
|
||||
s.put("/configs/1")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &me)
|
||||
.json(&json!({ "name": "x".repeat(33), "data": {} }))
|
||||
.await
|
||||
.assert_status(StatusCode::BAD_REQUEST);
|
||||
let huge = "x".repeat(256 * 1024 + 1);
|
||||
s.put("/configs/1")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &me)
|
||||
.json(&json!({ "name": "x", "data": huge }))
|
||||
.await
|
||||
.assert_status(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slots_are_private_and_need_identity() {
|
||||
let s = server().await;
|
||||
let owner = common::new_account().to_string();
|
||||
s.put("/configs/3")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, &owner)
|
||||
.json(&json!({ "name": "x", "data": {} }))
|
||||
.await
|
||||
.assert_status_ok();
|
||||
s.get("/configs/3")
|
||||
.add_header(common::ACCOUNT_ID_HEADER, common::new_account().to_string())
|
||||
.await
|
||||
.assert_status(StatusCode::NOT_FOUND);
|
||||
s.get("/configs").await.assert_status_unauthorized();
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue