Famous people: admin page, own prompt, one photo, public pages
- Admin "Híres emberek": birth data, one photo (S3: DigitalOcean Spaces in production, RustFS in development), a face point that every crop keeps in view, publishing, and a detailed portrait written with its own `celebrity` prompt (third person, by name, from the chart alone). - The photo is stored once (upright JPEG, at most 2000 px, no metadata); next/image makes the sizes from it, so Cloudflare can cache those. - Public list and pages (/hires-emberek), in the sitemap, with a share image showing the face and the chart. - Share images: the wheel's glyphs and numbers are drawn with the card's fonts (inside the SVG image they came out as boxes, on every card). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -168,8 +168,44 @@ async fn fake_billingo_pdf(
|
||||
([("content-type", "application/pdf")], "%PDF-1.4 fake").into_response()
|
||||
}
|
||||
|
||||
async fn fake_services() -> String {
|
||||
/// A tiny S3: objects of the `photos` bucket in memory; signed requests only.
|
||||
type FakeS3 = Arc<std::sync::Mutex<std::collections::HashMap<String, (String, Vec<u8>)>>>;
|
||||
|
||||
async fn fake_s3(
|
||||
axum::extract::State(store): axum::extract::State<FakeS3>,
|
||||
method: axum::http::Method,
|
||||
headers: HeaderMap,
|
||||
axum::extract::Path(key): axum::extract::Path<String>,
|
||||
body: axum::body::Bytes,
|
||||
) -> axum::response::Response {
|
||||
use axum::response::IntoResponse;
|
||||
let auth = headers.get("authorization").and_then(|v| v.to_str().ok()).unwrap_or_default();
|
||||
if !auth.starts_with("AWS4-HMAC-SHA256 Credential=test-key/") || headers.get("x-amz-content-sha256").is_none() {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let mut store = store.lock().unwrap();
|
||||
match method.as_str() {
|
||||
"PUT" => {
|
||||
let ct = headers.get("content-type").and_then(|v| v.to_str().ok()).unwrap_or_default().to_string();
|
||||
store.insert(key, (ct, body.to_vec()));
|
||||
StatusCode::OK.into_response()
|
||||
}
|
||||
"GET" => match store.get(&key) {
|
||||
Some((ct, bytes)) => ([("content-type", ct.clone())], bytes.clone()).into_response(),
|
||||
None => StatusCode::NOT_FOUND.into_response(),
|
||||
},
|
||||
"DELETE" => {
|
||||
store.remove(&key);
|
||||
StatusCode::NO_CONTENT.into_response()
|
||||
}
|
||||
_ => StatusCode::METHOD_NOT_ALLOWED.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn fake_services_with(s3: FakeS3) -> String {
|
||||
let objects = Router::new().route("/s3/photos/{*key}", get(fake_s3).put(fake_s3).delete(fake_s3)).with_state(s3);
|
||||
let app = Router::new()
|
||||
.merge(objects)
|
||||
.route("/billingo/documents/{id}/download", get(fake_billingo_pdf))
|
||||
.route("/openrouter/models", get(fake_openrouter_models))
|
||||
.route("/v1/checkout/sessions", post(fake_stripe_create))
|
||||
@@ -221,6 +257,8 @@ struct TestApp {
|
||||
router: Router,
|
||||
pool: PgPool,
|
||||
state: Arc<AppState>,
|
||||
/// The objects in the fake object storage.
|
||||
s3: FakeS3,
|
||||
}
|
||||
|
||||
struct Response {
|
||||
@@ -235,11 +273,29 @@ impl TestApp {
|
||||
}
|
||||
|
||||
async fn with_config(pool: PgPool, change: impl FnOnce(&mut Config)) -> Self {
|
||||
let fake = fake_services().await;
|
||||
let s3 = FakeS3::default();
|
||||
let fake = fake_services_with(s3.clone()).await;
|
||||
let mut config = Config::for_tests(String::new(), fake.clone(), format!("{fake}/jwks"));
|
||||
change(&mut config);
|
||||
let state = Arc::new(AppState::new(pool.clone(), config));
|
||||
Self { router: routes::router(state.clone()), pool, state }
|
||||
Self { router: routes::router(state.clone()), pool, state, s3 }
|
||||
}
|
||||
|
||||
/// A request with a raw body (an uploaded file); the response body as bytes.
|
||||
async fn call_raw(
|
||||
&self,
|
||||
method: &str,
|
||||
uri: &str,
|
||||
token: Option<&str>,
|
||||
body: Vec<u8>,
|
||||
) -> (StatusCode, HeaderMap, Vec<u8>) {
|
||||
let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/octet-stream");
|
||||
if let Some(t) = token {
|
||||
req = req.header("authorization", format!("Bearer {t}"));
|
||||
}
|
||||
let resp = self.router.clone().oneshot(req.body(Body::from(body)).unwrap()).await.unwrap();
|
||||
let (status, headers) = (resp.status(), resp.headers().clone());
|
||||
(status, headers, resp.into_body().collect().await.unwrap().to_bytes().to_vec())
|
||||
}
|
||||
|
||||
async fn call(&self, method: &str, uri: &str, token: Option<&str>, body: Option<Value>) -> Response {
|
||||
@@ -941,7 +997,7 @@ async fn export_and_delete_account(pool: PgPool) {
|
||||
/// config and catalog, shared links, invitation pages, the waitlist and
|
||||
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
|
||||
/// logged-in user, so other apps cannot use them.
|
||||
const PUBLIC_ROUTES: [&str; 19] = [
|
||||
const PUBLIC_ROUTES: [&str; 22] = [
|
||||
"/healthz",
|
||||
// Stripe calls it; the signature proves it.
|
||||
"/v1/payments/stripe/webhook",
|
||||
@@ -963,6 +1019,10 @@ const PUBLIC_ROUTES: [&str; 19] = [
|
||||
"/v1/public/chart",
|
||||
"/v1/public/geo/countries",
|
||||
"/v1/public/geo/places",
|
||||
// Famous people's pages (drafts only for admins) and their photos.
|
||||
"/v1/public/celebrities",
|
||||
"/v1/public/celebrities/{slug}",
|
||||
"/v1/public/photos/{*key}",
|
||||
];
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
@@ -1075,7 +1135,10 @@ async fn everything_else_needs_login(pool: PgPool) {
|
||||
let source = include_str!("routes/mod.rs");
|
||||
let id = uuid::Uuid::now_v7().to_string();
|
||||
let mut checked = 0;
|
||||
for line in source.lines().map(str::trim).filter(|l| l.starts_with(".route(\"")) {
|
||||
// One route per item, also when rustfmt broke it into several lines.
|
||||
let flat = source.split_whitespace().collect::<Vec<_>>().join(" ").replace(".route( \"", ".route(\"");
|
||||
for line in flat.split(".route(\"").skip(1).map(|r| format!(".route(\"{}", r.split(".layer(cors").next().unwrap()))
|
||||
{
|
||||
let path = line.split('"').nth(1).unwrap();
|
||||
if PUBLIC_ROUTES.contains(&path) {
|
||||
continue;
|
||||
@@ -1334,8 +1397,8 @@ async fn admins_edit_analysis_prompts(pool: PgPool) {
|
||||
let prompts = r.body["prompts"].as_array().unwrap();
|
||||
let keys: Vec<String> =
|
||||
prompts.iter().map(|p| format!("{}/{}", p["kind"], p["language"]).replace('"', "")).collect();
|
||||
let expected =
|
||||
["summary", "natal", "synastry", "forecast", "question"].map(|k| [format!("{k}/hu"), format!("{k}/en")]);
|
||||
let expected = ["summary", "natal", "synastry", "forecast", "question", "celebrity"]
|
||||
.map(|k| [format!("{k}/hu"), format!("{k}/en")]);
|
||||
assert_eq!(keys, expected.concat());
|
||||
let natal = &prompts[2];
|
||||
assert_eq!((&natal["custom"], &natal["system"]), (&json!(false), &natal["default"]));
|
||||
@@ -2899,3 +2962,140 @@ async fn a_paid_forecast_fixes_the_person(pool: PgPool) {
|
||||
let r = app.call("PATCH", &format!("/v1/charts/{bela_id}"), Some(&anna), Some(corrected)).await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("person_analysed")));
|
||||
}
|
||||
|
||||
fn test_png(width: u32, height: u32) -> Vec<u8> {
|
||||
let img = image::RgbImage::from_pixel(width, height, image::Rgb([180, 140, 90]));
|
||||
let mut out = Vec::new();
|
||||
img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn admins_publish_famous_people_with_a_photo(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let birth = json!({"date": "1926-06-01", "time": "09:30", "country": "HU", "place": "Szeged"});
|
||||
let new = json!({"name": " Teszt Elek ", "subtitle": "színész", "birth": birth});
|
||||
assert_eq!(app.post("/v1/admin/celebrities", Some(&anna), new.clone()).await.status, StatusCode::FORBIDDEN);
|
||||
|
||||
// added: the chart is calculated and the analysis queued, free of charge
|
||||
let r = app.post("/v1/admin/celebrities", Some(&admin), new.clone()).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let c = r.body;
|
||||
let id = c["id"].as_str().unwrap().to_string();
|
||||
assert_eq!((c["name"].as_str(), c["slug"].as_str()), (Some("Teszt Elek"), Some("teszt-elek")));
|
||||
assert_eq!((&c["published"], &c["photo"]), (&json!(false), &Value::Null));
|
||||
assert_eq!((c["birth"]["date"].as_str(), c["birth"]["time"].as_str()), (Some("1926-06-01"), Some("09:30")));
|
||||
let analysis = &c["analysis"];
|
||||
assert_eq!((analysis["kind"].as_str(), analysis["status"].as_str()), (Some("celebrity"), Some("pending")));
|
||||
assert_eq!((analysis["credits_charged"].as_i64(), analysis["language"].as_str()), (Some(0), Some("hu")));
|
||||
let analysis_id = analysis["id"].as_str().unwrap().to_string();
|
||||
// the same name again gets its own address
|
||||
let r = app.post("/v1/admin/celebrities", Some(&admin), new.clone()).await;
|
||||
assert_eq!(r.body["slug"].as_str(), Some("teszt-elek-2"));
|
||||
let second = r.body["id"].as_str().unwrap().to_string();
|
||||
|
||||
// not among the admin's own charts, and the chart routes do not reach it
|
||||
let charts = app.get("/v1/charts", Some(&admin)).await.body;
|
||||
assert_eq!(charts["charts"].as_array().unwrap().len(), 0, "{charts}");
|
||||
let (chart_id,): (uuid::Uuid,) = sqlx::query_as("SELECT chart_id FROM celebrities WHERE id = $1::uuid")
|
||||
.bind(&id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(app.get(&format!("/v1/charts/{chart_id}"), Some(&admin)).await.status, StatusCode::NOT_FOUND);
|
||||
let r = app.call("DELETE", &format!("/v1/charts/{chart_id}"), Some(&admin), None).await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
|
||||
// a draft: only admins see the page
|
||||
assert_eq!(app.get("/v1/public/celebrities/teszt-elek", None).await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.get("/v1/public/celebrities/teszt-elek", Some(&anna)).await.status, StatusCode::NOT_FOUND);
|
||||
let r = app.get("/v1/public/celebrities/teszt-elek", Some(&admin)).await;
|
||||
assert_eq!((r.status, &r.body["analysis"]), (StatusCode::OK, &Value::Null));
|
||||
assert_eq!(app.get("/v1/public/celebrities", None).await.body["celebrities"], json!([]));
|
||||
|
||||
// the photo: stored once as JPEG under a new key, the old one deleted
|
||||
let uri = format!("/v1/admin/celebrities/{id}/photo");
|
||||
let (status, _, body) = app.call_raw("PUT", &uri, Some(&admin), b"not an image".to_vec()).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{}", String::from_utf8_lossy(&body));
|
||||
let (status, _, body) = app.call_raw("PUT", &uri, Some(&admin), test_png(3000, 4000)).await;
|
||||
assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body));
|
||||
let photo = serde_json::from_slice::<Value>(&body).unwrap()["photo"].clone();
|
||||
assert_eq!((photo["width"].as_i64(), photo["height"].as_i64()), (Some(1500), Some(2000)));
|
||||
let first_key = photo["key"].as_str().unwrap().to_string();
|
||||
assert!(first_key.starts_with(&format!("celebrities/{id}/")) && first_key.ends_with(".jpg"));
|
||||
let (status, _, body) = app.call_raw("PUT", &uri, Some(&admin), test_png(800, 800)).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let key = serde_json::from_slice::<Value>(&body).unwrap()["photo"]["key"].as_str().unwrap().to_string();
|
||||
assert_ne!(key, first_key);
|
||||
{
|
||||
let s3 = app.s3.lock().unwrap();
|
||||
assert!(!s3.contains_key(&first_key) && s3.contains_key(&key));
|
||||
assert_eq!(s3[&key].0, "image/jpeg");
|
||||
}
|
||||
// served while in use, cacheable for good; the replaced one is gone
|
||||
let (status, headers, bytes) = app.call_raw("GET", &format!("/v1/public/photos/{key}"), None, vec![]).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(headers["cache-control"], "public, max-age=31536000, immutable");
|
||||
assert_eq!(&bytes[..3], &[0xFF, 0xD8, 0xFF]);
|
||||
let (status, ..) = app.call_raw("GET", &format!("/v1/public/photos/{first_key}"), None, vec![]).await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
|
||||
// edits: face point, address, publishing
|
||||
let item = format!("/v1/admin/celebrities/{id}");
|
||||
let patch = |body: Value| app.call("PATCH", &item, Some(&admin), Some(body));
|
||||
let r = patch(json!({"slug": "Rossz Cím"})).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
let r = patch(json!({"slug": "teszt-elek-2"})).await;
|
||||
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("slug_taken")));
|
||||
let r = patch(json!({"focus_x": 0.25, "focus_y": 7.0, "published": true, "subtitle": null})).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!((&r.body["photo"]["focus_x"], &r.body["photo"]["focus_y"]), (&json!(0.25), &json!(1.0)));
|
||||
assert_eq!((&r.body["published"], &r.body["subtitle"]), (&json!(true), &Value::Null));
|
||||
|
||||
// published: the list and the page, with the birth data, the chart and the finished analysis
|
||||
sqlx::query("UPDATE analyses SET status = 'done', content = '{\"title\": \"Portré\"}', completed_at = now() WHERE id = $1::uuid")
|
||||
.bind(&analysis_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
// someone else with the very same chart gets their own portrait (the text has the name in it)
|
||||
let twin = json!({"name": "Teszt Ikertestvér", "birth": birth});
|
||||
let r = app.post("/v1/admin/celebrities", Some(&admin), twin).await;
|
||||
assert_eq!(r.body["analysis"]["status"].as_str(), Some("pending"), "{}", r.body);
|
||||
let twin_id = r.body["id"].as_str().unwrap().to_string();
|
||||
let r = app.call("DELETE", &format!("/v1/admin/celebrities/{twin_id}"), Some(&admin), None).await;
|
||||
assert_eq!(r.status, StatusCode::NO_CONTENT);
|
||||
|
||||
let list = app.get("/v1/public/celebrities", None).await.body;
|
||||
assert_eq!(list["celebrities"].as_array().unwrap().len(), 1, "{list}");
|
||||
assert_eq!(list["celebrities"][0]["highlights"]["sun"], "cancer");
|
||||
let page = app.get("/v1/public/celebrities/teszt-elek", None).await;
|
||||
assert_eq!(page.status, StatusCode::OK);
|
||||
assert_eq!(page.body["analysis"]["content"]["title"], "Portré");
|
||||
assert_eq!(page.body["chart"]["birth"]["place"], "Szeged");
|
||||
assert_eq!(page.body["photo"]["key"].as_str(), Some(key.as_str()));
|
||||
|
||||
// corrected birth data: a new chart and a new analysis
|
||||
let r = patch(json!({"birth": {"date": "1926-06-02", "time": "09:30", "country": "HU", "place": "Szeged"}})).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!(r.body["birth"]["date"].as_str(), Some("1926-06-02"));
|
||||
assert_ne!(r.body["analysis"]["id"].as_str(), Some(analysis_id.as_str()));
|
||||
assert_eq!(r.body["analysis"]["status"].as_str(), Some("pending"));
|
||||
|
||||
// the prompt can be tried on a famous person's chart
|
||||
let r = app
|
||||
.post("/v1/admin/prompts/celebrity/hu/preview", Some(&admin), json!({"system": "Próba.", "chart_id": chart_id}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
|
||||
|
||||
// deleted with the photo; the other one stays
|
||||
let r = app.call("DELETE", &format!("/v1/admin/celebrities/{id}"), Some(&admin), None).await;
|
||||
assert_eq!(r.status, StatusCode::NO_CONTENT);
|
||||
assert!(app.s3.lock().unwrap().is_empty());
|
||||
assert_eq!(app.get("/v1/public/celebrities/teszt-elek", None).await.status, StatusCode::NOT_FOUND);
|
||||
let left = app.get("/v1/admin/celebrities", Some(&admin)).await.body;
|
||||
assert_eq!(left["celebrities"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(left["celebrities"][0]["id"].as_str(), Some(second.as_str()));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user