Merge the forum (community module) into main
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -11,6 +11,7 @@ db.workspace = true
|
||||
analysis-prompt.workspace = true
|
||||
email-templates.workspace = true
|
||||
gift-card.workspace = true
|
||||
object-storage.workspace = true
|
||||
hmac.workspace = true
|
||||
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
|
||||
rand.workspace = true
|
||||
|
||||
@@ -179,6 +179,15 @@ pub async fn export(State(state): St, auth: AuthUser) -> ApiResult<impl IntoResp
|
||||
"questions": rows("SELECT json_build_object('id', q.id, 'analysis_id', q.analysis_id, 'question', q.question, 'status', q.status, 'answer', q.answer, 'created_at', q.created_at) FROM questions q WHERE q.asked_by = $1").await?,
|
||||
"credit_ledger": rows("SELECT json_build_object('unit', unit, 'delta', delta, 'reason', reason, 'note', note, 'created_at', created_at) FROM credit_ledger WHERE user_id = $1 ORDER BY created_at").await?,
|
||||
"shares": rows("SELECT json_build_object('slug', slug, 'kind', kind, 'title', title, 'show_birth_data', show_birth_data, 'view_count', view_count, 'created_at', created_at, 'revoked_at', revoked_at) FROM shares WHERE owner_id = $1").await?,
|
||||
// The forum (services/forum): what the user wrote and set there.
|
||||
"forum_profile": rows("SELECT json_build_object('nickname', nickname, 'avatar', avatar, 'bio', bio, 'chart_share', chart_share, 'invisible', invisible, 'points', points, 'post_count', post_count, 'created_at', created_at, 'email_replies', email_replies, 'email_followed', email_followed, 'email_messages', email_messages, 'email_mentions', email_mentions, 'email_listener', email_listener, 'email_weekly', email_weekly, 'listener', listener, 'supporter_badge', supporter_badge, 'banned_until', banned_until, 'ban_reason', ban_reason) FROM forum.members WHERE user_id = $1").await?,
|
||||
"forum_topic_memberships": rows("SELECT json_build_object('topic', tp.name, 'status', tm.status, 'note', tm.note, 'requested_at', tm.requested_at) FROM forum.topic_members tm JOIN forum.topics tp ON tp.id = tm.topic_id WHERE tm.user_id = $1").await?,
|
||||
"forum_posts": rows("SELECT json_build_object('id', p.id, 'thread_id', p.thread_id, 'thread_title', th.title, 'opening', p.is_opening, 'body', p.body, 'created_at', p.created_at, 'edited_at', p.edited_at, 'removed_at', p.deleted_at, 'removal_reason', p.delete_reason) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id WHERE p.author_id = $1 ORDER BY p.id").await?,
|
||||
"forum_reactions": rows("SELECT json_build_object('post_id', post_id, 'kind', kind, 'created_at', created_at) FROM forum.reactions WHERE user_id = $1 ORDER BY created_at").await?,
|
||||
"forum_followed_threads": rows("SELECT json_build_object('thread_id', thread_id, 'since', created_at) FROM forum.follows WHERE user_id = $1").await?,
|
||||
"forum_conversations": rows("SELECT json_build_object('id', c.id, 'with', m.nickname, 'requested_by_me', c.requested_by = $1, 'intro', c.intro, 'status', c.status, 'created_at', c.created_at) FROM forum.conversations c LEFT JOIN forum.members m ON m.user_id = CASE WHEN c.user_a = $1 THEN c.user_b ELSE c.user_a END WHERE $1 IN (c.user_a, c.user_b)").await?,
|
||||
"forum_messages_sent": rows("SELECT json_build_object('conversation_id', conversation_id, 'body', body, 'created_at', created_at) FROM forum.messages WHERE sender_id = $1 ORDER BY id").await?,
|
||||
"forum_reports_sent": rows("SELECT json_build_object('post_id', post_id, 'message_id', message_id, 'kind', kind, 'note', note, 'status', status, 'created_at', created_at) FROM forum.reports WHERE reporter_id = $1").await?,
|
||||
});
|
||||
Ok(([("content-disposition", "attachment; filename=\"sorsfonalak-export.json\"")], Json(document)))
|
||||
}
|
||||
@@ -249,8 +258,18 @@ pub async fn delete_me(
|
||||
.bind(auth.id())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
// The forum's own avatar picture (in the object storage) goes too.
|
||||
let avatar: Option<String> = sqlx::query_scalar("SELECT avatar FROM forum.members WHERE user_id = $1")
|
||||
.bind(auth.id())
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM users WHERE id = $1").bind(auth.id()).execute(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
if let (Some(file), Some(storage)) = (avatar.as_deref().and_then(|a| a.strip_prefix("upload:")), &state.storage)
|
||||
&& let Err(e) = storage.delete(&format!("forum-avatars/{file}")).await
|
||||
{
|
||||
tracing::warn!(error = %e, "removing a deleted account's forum avatar");
|
||||
}
|
||||
tracing::info!(user = %auth.id(), "account deleted");
|
||||
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ pub fn method(config: &crate::config::Config) -> Option<&'static str> {
|
||||
}
|
||||
|
||||
/// The terms (ÁSZF) version a purchase accepts; the frontend's `TERMS_UPDATED`.
|
||||
pub const TERMS_VERSION: &str = "2026-11-23";
|
||||
pub const TERMS_VERSION: &str = "2026-11-26";
|
||||
|
||||
/// Only admins can buy through Stripe: until purchases open, and always with a
|
||||
/// test key (nobody gets packages with Stripe's test cards, nobody types a
|
||||
|
||||
@@ -13,6 +13,12 @@
|
||||
//! per user: a click proves little. A natal analysis is earned by bringing a
|
||||
//! new user (`REFERRAL_REWARDS`): someone who signs up from a shared link and
|
||||
//! makes their own chart, at most [`REFERRAL_LIMIT`] times.
|
||||
//!
|
||||
//! A share made for the forum (`for_forum`, a question about one's chart,
|
||||
//! forecast or synastry) never shows birth data, and its public view leaves
|
||||
//! out the chart names: they may be real names next to a nickname. A yearly
|
||||
//! forecast can be shared too: its calculation and its detailed text, without
|
||||
//! the place of the birthday.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
@@ -27,6 +33,7 @@ use uuid::Uuid;
|
||||
|
||||
use super::analyses::{can_see, find_analysis};
|
||||
use super::charts::{ChartRow, find_chart, owned_chart};
|
||||
use super::forecasts::{ForecastRow, find_forecast, owned_forecast};
|
||||
use super::synastries::{VisibleSynastry, load_synastry, visible_synastry};
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::auth::{AuthUser, user_agent};
|
||||
@@ -39,6 +46,7 @@ pub enum ShareKind {
|
||||
Chart,
|
||||
Synastry,
|
||||
Analysis,
|
||||
Forecast,
|
||||
}
|
||||
|
||||
#[derive(Debug, sqlx::FromRow)]
|
||||
@@ -50,16 +58,18 @@ struct ShareRow {
|
||||
chart_id: Option<Uuid>,
|
||||
synastry_id: Option<Uuid>,
|
||||
analysis_id: Option<Uuid>,
|
||||
forecast_id: Option<Uuid>,
|
||||
title: Option<String>,
|
||||
show_birth_data: bool,
|
||||
for_forum: bool,
|
||||
view_count: i64,
|
||||
created_at: OffsetDateTime,
|
||||
revoked_at: Option<OffsetDateTime>,
|
||||
owner_ip_hash: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \
|
||||
view_count, created_at, revoked_at, owner_ip_hash";
|
||||
const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, forecast_id, title, \
|
||||
show_birth_data, for_forum, view_count, created_at, revoked_at, owner_ip_hash";
|
||||
|
||||
use super::client_ip;
|
||||
|
||||
@@ -113,8 +123,10 @@ impl ShareRow {
|
||||
"chart_id": self.chart_id,
|
||||
"synastry_id": self.synastry_id,
|
||||
"analysis_id": self.analysis_id,
|
||||
"forecast_id": self.forecast_id,
|
||||
"title": self.title,
|
||||
"show_birth_data": self.show_birth_data,
|
||||
"for_forum": self.for_forum,
|
||||
"view_count": self.view_count,
|
||||
"created_at": rfc3339(self.created_at),
|
||||
"revoked_at": rfc3339_opt(self.revoked_at),
|
||||
@@ -132,6 +144,9 @@ pub struct CreateShare {
|
||||
/// Show birth date, time and place (only ever of the sharer's own charts).
|
||||
#[serde(default)]
|
||||
show_birth_data: bool,
|
||||
/// For a forum post: no birth data, no names, no title.
|
||||
#[serde(default)]
|
||||
for_forum: bool,
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
@@ -140,14 +155,22 @@ pub async fn create(
|
||||
headers: HeaderMap,
|
||||
WithRejection(Json(req), _): Body<CreateShare>,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let (chart_id, synastry_id, analysis_id, kind) = match req.kind {
|
||||
let (mut chart_id, mut synastry_id, mut analysis_id, mut forecast_id) = (None, None, None, None);
|
||||
let kind = match req.kind {
|
||||
ShareKind::Chart => {
|
||||
owned_chart(&state.db, req.target_id, auth.id()).await?;
|
||||
(Some(req.target_id), None, None, "chart")
|
||||
chart_id = Some(req.target_id);
|
||||
"chart"
|
||||
}
|
||||
ShareKind::Synastry => {
|
||||
visible_synastry(&state.db, req.target_id, auth.id()).await?;
|
||||
(None, Some(req.target_id), None, "synastry")
|
||||
synastry_id = Some(req.target_id);
|
||||
"synastry"
|
||||
}
|
||||
ShareKind::Forecast => {
|
||||
owned_forecast(&state.db, req.target_id, auth.id()).await?;
|
||||
forecast_id = Some(req.target_id);
|
||||
"forecast"
|
||||
}
|
||||
ShareKind::Analysis => {
|
||||
let analysis = find_analysis(&state.db, req.target_id).await?.ok_or(ApiError::NotFound("analysis"))?;
|
||||
@@ -157,14 +180,18 @@ pub async fn create(
|
||||
if analysis.status != "done" {
|
||||
return Err(ApiError::conflict("analysis_not_ready", "Csak elkészült elemzést lehet megosztani."));
|
||||
}
|
||||
(None, None, Some(req.target_id), "analysis")
|
||||
analysis_id = Some(req.target_id);
|
||||
"analysis"
|
||||
}
|
||||
};
|
||||
let title = req.title.map(|t| t.trim().chars().take(120).collect::<String>()).filter(|t| !t.is_empty());
|
||||
// A forum share: never birth data, and no title of the sharer's own.
|
||||
let (title, show_birth_data) = if req.for_forum { (None, false) } else { (title, req.show_birth_data) };
|
||||
let open: Option<ShareRow> = sqlx::query_as(&format!(
|
||||
"SELECT {SHARE_COLUMNS} FROM shares WHERE owner_id = $1 AND kind = $2 AND revoked_at IS NULL \
|
||||
AND chart_id IS NOT DISTINCT FROM $3 AND synastry_id IS NOT DISTINCT FROM $4 \
|
||||
AND analysis_id IS NOT DISTINCT FROM $5 AND title IS NOT DISTINCT FROM $6 AND show_birth_data = $7 \
|
||||
AND forecast_id IS NOT DISTINCT FROM $8 AND for_forum = $9 \
|
||||
ORDER BY created_at DESC LIMIT 1"
|
||||
))
|
||||
.bind(auth.id())
|
||||
@@ -173,7 +200,9 @@ pub async fn create(
|
||||
.bind(synastry_id)
|
||||
.bind(analysis_id)
|
||||
.bind(&title)
|
||||
.bind(req.show_birth_data)
|
||||
.bind(show_birth_data)
|
||||
.bind(forecast_id)
|
||||
.bind(req.for_forum)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
if let Some(row) = open {
|
||||
@@ -182,8 +211,8 @@ pub async fn create(
|
||||
let slug = new_slug();
|
||||
let row: ShareRow = sqlx::query_as(&format!(
|
||||
"INSERT INTO shares (id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \
|
||||
owner_ip_hash) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING {SHARE_COLUMNS}"
|
||||
owner_ip_hash, forecast_id, for_forum) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING {SHARE_COLUMNS}"
|
||||
))
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(auth.id())
|
||||
@@ -193,8 +222,10 @@ pub async fn create(
|
||||
.bind(synastry_id)
|
||||
.bind(analysis_id)
|
||||
.bind(title)
|
||||
.bind(req.show_birth_data)
|
||||
.bind(show_birth_data)
|
||||
.bind(client_ip(&headers).map(|ip| ip_hash(&slug, &ip)))
|
||||
.bind(forecast_id)
|
||||
.bind(req.for_forum)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
Ok((StatusCode::CREATED, Json(row.view(&state.config.public_base_url))))
|
||||
@@ -229,7 +260,27 @@ fn public_chart_block(chart: &ChartRow, share: &ShareRow) -> Value {
|
||||
// Birth data only of the sharer's own chart, never of a partner's or of a
|
||||
// person they added (that is someone else's data).
|
||||
let show = share.show_birth_data && chart.owner_id == share.owner_id && chart.kind == "own";
|
||||
json!({ "label": chart.label, "chart": public_chart(&chart.result, show) })
|
||||
// A forum share leaves out the names (they may be real names next to a nickname).
|
||||
let label = if share.for_forum { Value::Null } else { Value::from(chart.label.clone()) };
|
||||
json!({ "label": label, "chart": public_chart(&chart.result, show) })
|
||||
}
|
||||
|
||||
/// A yearly forecast without where it was reckoned: the solar return chart
|
||||
/// without its place and time zone, and the year's calculation.
|
||||
fn public_forecast_block(forecast: &ForecastRow) -> Value {
|
||||
let sr = &forecast.result["solar_return"];
|
||||
let solar_return = if sr.is_object() {
|
||||
let mut chart = public_chart(sr, false);
|
||||
if let Some(obj) = chart.as_object_mut() {
|
||||
for key in ["local_time", "timezone", "utc_offset", "moment_utc", "location"] {
|
||||
obj.remove(key);
|
||||
}
|
||||
}
|
||||
chart
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
json!({ "year": forecast.year, "forecast": forecast.result["forecast"], "solar_return": solar_return })
|
||||
}
|
||||
|
||||
fn public_synastry_block(s: &VisibleSynastry, share: &ShareRow) -> Value {
|
||||
@@ -269,6 +320,26 @@ async fn public_body(db: &PgPool, share: &ShareRow) -> Result<Value, ApiError> {
|
||||
let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?;
|
||||
body["synastry"] = public_synastry_block(&s, share);
|
||||
}
|
||||
} else if let Some(forecast_id) = share.forecast_id {
|
||||
let forecast = find_forecast(db, forecast_id).await?.ok_or(ApiError::NotFound("share"))?;
|
||||
body["forecast"] = public_forecast_block(&forecast);
|
||||
// The detailed text of the year, if it was written.
|
||||
let analysis: Option<(String, Option<Value>, Option<OffsetDateTime>)> = sqlx::query_as(
|
||||
"SELECT language, content, completed_at FROM analyses \
|
||||
WHERE forecast_id = $1 AND kind = 'forecast' AND status = 'done' ORDER BY completed_at DESC LIMIT 1",
|
||||
)
|
||||
.bind(forecast_id)
|
||||
.fetch_optional(db)
|
||||
.await?;
|
||||
body["analysis"] = match analysis {
|
||||
Some((language, content, completed_at)) => json!({
|
||||
"kind": "forecast",
|
||||
"language": language,
|
||||
"content": content,
|
||||
"completed_at": rfc3339_opt(completed_at),
|
||||
}),
|
||||
None => Value::Null,
|
||||
};
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
@@ -1,276 +1,3 @@
|
||||
//! Object storage for uploaded photos: any S3-compatible service, addressed
|
||||
//! path-style (`{endpoint}/{bucket}/{key}`). In production DigitalOcean
|
||||
//! Spaces, in development a RustFS container.
|
||||
//!
|
||||
//! The bucket stays private: the backend reads the objects itself and serves
|
||||
//! them under `/v1/public/photos/...`, from where the frontend's image
|
||||
//! optimizer makes the sized versions (and Cloudflare caches those).
|
||||
//!
|
||||
//! Requests are signed with AWS Signature Version 4.
|
||||
//! Object storage for uploaded photos: the shared `object-storage` crate.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
/// `S3_ENDPOINT` (e.g. `https://fra1.digitaloceanspaces.com`), `S3_BUCKET`,
|
||||
/// `S3_REGION` (default `us-east-1`; Spaces accepts it too),
|
||||
/// `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` (in `.env.secrets`).
|
||||
#[derive(Clone)]
|
||||
pub struct StorageConfig {
|
||||
pub endpoint: String,
|
||||
pub bucket: String,
|
||||
pub region: String,
|
||||
pub access_key: String,
|
||||
pub secret_key: String,
|
||||
}
|
||||
|
||||
// The secret stays out of logs.
|
||||
impl std::fmt::Debug for StorageConfig {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("StorageConfig")
|
||||
.field("endpoint", &self.endpoint)
|
||||
.field("bucket", &self.bucket)
|
||||
.field("region", &self.region)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum StorageError {
|
||||
#[error("object storage request failed: {0}")]
|
||||
Http(#[from] reqwest::Error),
|
||||
#[error("object storage answered {status}: {body}")]
|
||||
Status { status: u16, body: String },
|
||||
}
|
||||
|
||||
pub struct Storage {
|
||||
config: StorageConfig,
|
||||
http: reqwest::Client,
|
||||
}
|
||||
|
||||
/// An object read back: its bytes and content type.
|
||||
pub struct Object {
|
||||
pub bytes: axum::body::Bytes,
|
||||
pub content_type: Option<String>,
|
||||
}
|
||||
|
||||
impl Storage {
|
||||
pub fn new(config: StorageConfig) -> Self {
|
||||
let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).build().expect("static configuration");
|
||||
Self { config, http }
|
||||
}
|
||||
|
||||
fn url(&self, key: &str) -> String {
|
||||
let path = if key.is_empty() { String::new() } else { format!("/{}", encode_path(key)) };
|
||||
format!("{}/{}{path}", self.config.endpoint, encode_segment(&self.config.bucket))
|
||||
}
|
||||
|
||||
async fn send(
|
||||
&self,
|
||||
method: reqwest::Method,
|
||||
key: &str,
|
||||
body: Vec<u8>,
|
||||
content_type: Option<&str>,
|
||||
) -> Result<reqwest::Response, StorageError> {
|
||||
let url = self.url(key);
|
||||
let parsed = reqwest::Url::parse(&url).map_err(|e| StorageError::Status { status: 0, body: e.to_string() })?;
|
||||
let host = match parsed.port() {
|
||||
Some(port) => format!("{}:{port}", parsed.host_str().unwrap_or_default()),
|
||||
None => parsed.host_str().unwrap_or_default().to_string(),
|
||||
};
|
||||
let payload_hash = hex(&Sha256::digest(&body));
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let auth = authorization(&self.config, method.as_str(), parsed.path(), &host, &payload_hash, now);
|
||||
let mut request = self
|
||||
.http
|
||||
.request(method, url)
|
||||
.header("x-amz-date", amz_date(now))
|
||||
.header("x-amz-content-sha256", &payload_hash)
|
||||
.header("authorization", auth);
|
||||
if let Some(ct) = content_type {
|
||||
request = request.header("content-type", ct);
|
||||
}
|
||||
let response = request.body(body).send().await?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn checked(response: reqwest::Response) -> Result<reqwest::Response, StorageError> {
|
||||
if response.status().is_success() {
|
||||
return Ok(response);
|
||||
}
|
||||
let status = response.status().as_u16();
|
||||
let body = response.text().await.unwrap_or_default().chars().take(500).collect();
|
||||
Err(StorageError::Status { status, body })
|
||||
}
|
||||
|
||||
pub async fn put(&self, key: &str, body: Vec<u8>, content_type: &str) -> Result<(), StorageError> {
|
||||
Self::checked(self.send(reqwest::Method::PUT, key, body, Some(content_type)).await?).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The object, or `None` if there is no such key.
|
||||
pub async fn get(&self, key: &str) -> Result<Option<Object>, StorageError> {
|
||||
let response = self.send(reqwest::Method::GET, key, Vec::new(), None).await?;
|
||||
if response.status() == reqwest::StatusCode::NOT_FOUND {
|
||||
return Ok(None);
|
||||
}
|
||||
let response = Self::checked(response).await?;
|
||||
let content_type = response.headers().get("content-type").and_then(|v| v.to_str().ok()).map(str::to_owned);
|
||||
Ok(Some(Object { bytes: response.bytes().await?, content_type }))
|
||||
}
|
||||
|
||||
/// Deletes the object; a missing one is not an error.
|
||||
pub async fn delete(&self, key: &str) -> Result<(), StorageError> {
|
||||
let response = self.send(reqwest::Method::DELETE, key, Vec::new(), None).await?;
|
||||
if response.status() == reqwest::StatusCode::NOT_FOUND {
|
||||
return Ok(());
|
||||
}
|
||||
Self::checked(response).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates the bucket if it does not exist yet (development: a fresh
|
||||
/// RustFS container has none; in production it is made in the console).
|
||||
pub async fn ensure_bucket(&self) -> Result<(), StorageError> {
|
||||
let head = self.send(reqwest::Method::HEAD, "", Vec::new(), None).await?;
|
||||
if head.status().is_success() {
|
||||
return Ok(());
|
||||
}
|
||||
Self::checked(self.send(reqwest::Method::PUT, "", Vec::new(), None).await?).await?;
|
||||
tracing::info!(bucket = %self.config.bucket, "object storage bucket created");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
fn hmac(key: &[u8], data: &str) -> Vec<u8> {
|
||||
let mut mac = HmacSha256::new_from_slice(key).expect("HMAC takes any key length");
|
||||
mac.update(data.as_bytes());
|
||||
mac.finalize().into_bytes().to_vec()
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
fn amz_date(t: OffsetDateTime) -> String {
|
||||
format!(
|
||||
"{:04}{:02}{:02}T{:02}{:02}{:02}Z",
|
||||
t.year(),
|
||||
u8::from(t.month()),
|
||||
t.day(),
|
||||
t.hour(),
|
||||
t.minute(),
|
||||
t.second()
|
||||
)
|
||||
}
|
||||
|
||||
/// URI-encodes one path segment as SigV4 wants it (unreserved characters stay).
|
||||
fn encode_segment(s: &str) -> String {
|
||||
s.bytes()
|
||||
.map(|b| match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
|
||||
_ => format!("%{b:02X}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn encode_path(key: &str) -> String {
|
||||
key.split('/').map(encode_segment).collect::<Vec<_>>().join("/")
|
||||
}
|
||||
|
||||
fn signing_key(secret: &str, date: &str, region: &str, service: &str) -> Vec<u8> {
|
||||
[date, region, service, "aws4_request"]
|
||||
.iter()
|
||||
.fold(format!("AWS4{secret}").into_bytes(), |key, part| hmac(&key, part))
|
||||
}
|
||||
|
||||
/// The `Authorization` header of a request (no query string; the path is
|
||||
/// already encoded, as in the URL).
|
||||
fn authorization(
|
||||
config: &StorageConfig,
|
||||
method: &str,
|
||||
path: &str,
|
||||
host: &str,
|
||||
payload_hash: &str,
|
||||
now: OffsetDateTime,
|
||||
) -> String {
|
||||
let date_time = amz_date(now);
|
||||
let date = &date_time[..8];
|
||||
let signed_headers = "host;x-amz-content-sha256;x-amz-date";
|
||||
let canonical = format!(
|
||||
"{method}\n{path}\n\nhost:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{date_time}\n\n\
|
||||
{signed_headers}\n{payload_hash}"
|
||||
);
|
||||
let scope = format!("{date}/{}/s3/aws4_request", config.region);
|
||||
let to_sign = format!("AWS4-HMAC-SHA256\n{date_time}\n{scope}\n{}", hex(&Sha256::digest(canonical.as_bytes())));
|
||||
let signature = hex(&hmac(&signing_key(&config.secret_key, date, &config.region, "s3"), &to_sign));
|
||||
format!(
|
||||
"AWS4-HMAC-SHA256 Credential={}/{scope}, SignedHeaders={signed_headers}, Signature={signature}",
|
||||
config.access_key
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The signing key example of the AWS documentation ("Examples of how to
|
||||
/// derive a signing key for Signature Version 4").
|
||||
#[test]
|
||||
fn derives_the_signing_key_like_aws() {
|
||||
let key = signing_key("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", "20150830", "us-east-1", "iam");
|
||||
assert_eq!(hex(&key), "c4afb1cc5771d871763a393e44b703571b55cc28424d1a5e86da6ed3c154a4b9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_the_authorization_header() {
|
||||
let config = StorageConfig {
|
||||
endpoint: "http://rustfs:9000".into(),
|
||||
bucket: "photos".into(),
|
||||
region: "us-east-1".into(),
|
||||
access_key: "AKIAIOSFODNN7EXAMPLE".into(),
|
||||
secret_key: "secret".into(),
|
||||
};
|
||||
let now = OffsetDateTime::from_unix_timestamp(1_369_353_600).unwrap();
|
||||
assert_eq!(amz_date(now), "20130524T000000Z");
|
||||
let empty = hex(&Sha256::digest(b""));
|
||||
assert_eq!(empty, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
|
||||
let auth = authorization(&config, "GET", "/photos/a.jpg", "rustfs:9000", &empty, now);
|
||||
assert!(auth.starts_with(
|
||||
"AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, \
|
||||
SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature="
|
||||
));
|
||||
let storage = Storage::new(config);
|
||||
assert_eq!(storage.url("celebrities/a b/ő.jpg"), "http://rustfs:9000/photos/celebrities/a%20b/%C5%91.jpg");
|
||||
assert_eq!(storage.url(""), "http://rustfs:9000/photos");
|
||||
}
|
||||
|
||||
/// Against a real S3 service (e.g. the RustFS container of development):
|
||||
/// `S3_TEST_ENDPOINT=http://127.0.0.1:9000 S3_TEST_KEY=… S3_TEST_SECRET=…
|
||||
/// cargo test -p backend live_round_trip -- --ignored`
|
||||
#[tokio::test]
|
||||
#[ignore]
|
||||
async fn live_round_trip() {
|
||||
let env = |name: &str| std::env::var(name).unwrap_or_else(|_| panic!("{name} is not set"));
|
||||
let storage = Storage::new(StorageConfig {
|
||||
endpoint: env("S3_TEST_ENDPOINT"),
|
||||
bucket: "storage-test".into(),
|
||||
region: "us-east-1".into(),
|
||||
access_key: env("S3_TEST_KEY"),
|
||||
secret_key: env("S3_TEST_SECRET"),
|
||||
});
|
||||
storage.ensure_bucket().await.unwrap();
|
||||
storage.ensure_bucket().await.unwrap();
|
||||
let key = "dir/próba kép.jpg";
|
||||
storage.put(key, b"hello".to_vec(), "image/jpeg").await.unwrap();
|
||||
let object = storage.get(key).await.unwrap().unwrap();
|
||||
assert_eq!((&object.bytes[..], object.content_type.as_deref()), (&b"hello"[..], Some("image/jpeg")));
|
||||
storage.delete(key).await.unwrap();
|
||||
assert!(storage.get(key).await.unwrap().is_none());
|
||||
storage.delete(key).await.unwrap();
|
||||
}
|
||||
}
|
||||
pub use object_storage::*;
|
||||
|
||||
@@ -1019,6 +1019,21 @@ async fn public_shares(pool: PgPool) {
|
||||
);
|
||||
assert_eq!(app.get(&format!("/v1/public/shares/{slug}"), None).await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.get("/v1/public/shares/nincs-ilyen", None).await.status, StatusCode::NOT_FOUND);
|
||||
|
||||
// A share for the forum: its own link, never birth data, no names, no title.
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/shares",
|
||||
Some(&anna),
|
||||
json!({"kind": "chart", "target_id": chart_id, "for_forum": true, "show_birth_data": true, "title": "Én"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
assert_eq!((r.body["for_forum"].as_bool(), r.body["show_birth_data"].as_bool()), (Some(true), Some(false)));
|
||||
let r = app.get(&format!("/v1/public/shares/{}", r.body["slug"].as_str().unwrap()), None).await;
|
||||
assert!(r.body["chart"]["label"].is_null(), "{}", r.body);
|
||||
assert!(r.body["chart"]["chart"].get("birth").is_none());
|
||||
assert!(r.body["title"].is_null());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
@@ -1032,12 +1047,39 @@ async fn export_and_delete_account(pool: PgPool) {
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let r = app.post("/v1/synastries", Some(&anna), json!({"chart1_id": b["id"], "chart2_id": a["id"]})).await;
|
||||
assert_eq!(r.status, StatusCode::OK); // already exists
|
||||
// Anna also wrote in the forum (services/forum keeps it in the same database).
|
||||
let (anna_id,): (uuid::Uuid,) =
|
||||
sqlx::query_as("SELECT id FROM users WHERE email = 'anna@example.com'").fetch_one(&app.pool).await.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.members (user_id, nickname, nickname_key, avatar) \
|
||||
VALUES ($1, 'Holdfény', 'holdfeny', 'hold-ejkek')",
|
||||
)
|
||||
.bind(anna_id)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let thread: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO forum.threads (topic_id, author_id, title) VALUES (4, $1, 'Téli levesek') RETURNING id",
|
||||
)
|
||||
.bind(anna_id)
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO forum.posts (thread_id, author_id, is_opening, body) VALUES ($1, $2, true, 'Sütőtök')")
|
||||
.bind(thread)
|
||||
.bind(anna_id)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let r = app.get("/v1/me/export", Some(&anna)).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert_eq!(r.body["charts"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(r.body["synastries"].as_array().unwrap().len(), 1);
|
||||
assert!(r.body["login_methods"][0].get("password_hash").is_none());
|
||||
assert_eq!(r.body["forum_profile"][0]["nickname"], "Holdfény");
|
||||
assert_eq!(r.body["forum_posts"][0]["body"], "Sütőtök");
|
||||
assert_eq!(r.body["forum_posts"][0]["thread_title"], "Téli levesek");
|
||||
|
||||
let r = app.call("DELETE", "/v1/me", Some(&anna), Some(json!({"confirm": "yes"}))).await;
|
||||
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||
@@ -1049,6 +1091,15 @@ async fn export_and_delete_account(pool: PgPool) {
|
||||
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
|
||||
let (left,): (i64,) = sqlx::query_as("SELECT count(*) FROM charts").fetch_one(&app.pool).await.unwrap();
|
||||
assert_eq!(left, 0);
|
||||
// Her forum profile is gone; her thread stays, by "Törölt tag" (no author).
|
||||
let (members, author): (i64, Option<uuid::Uuid>) = sqlx::query_as(
|
||||
"SELECT (SELECT count(*) FROM forum.members), (SELECT author_id FROM forum.threads WHERE id = $1)",
|
||||
)
|
||||
.bind(thread)
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((members, author), (0, None));
|
||||
assert_eq!(app.get("/v1/me", Some(&bela)).await.status, StatusCode::OK);
|
||||
}
|
||||
|
||||
@@ -1940,6 +1991,19 @@ async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) {
|
||||
assert_eq!(app.get(&uri, Some(&bob)).await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.get(&format!("/v1/forecasts/{id}"), Some(&anna)).await.body["year"], json!(year));
|
||||
|
||||
// A forecast can be shared (not by others), without where it was reckoned.
|
||||
let r = app.post("/v1/shares", Some(&bob), json!({"kind": "forecast", "target_id": away.body["id"]})).await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
let r = app
|
||||
.post("/v1/shares", Some(&anna), json!({"kind": "forecast", "target_id": away.body["id"], "for_forum": true}))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let shared = app.get(&format!("/v1/public/shares/{}", r.body["slug"].as_str().unwrap()), None).await.body;
|
||||
assert_eq!(shared["kind"], "forecast");
|
||||
assert_eq!(shared["forecast"]["forecast"]["start"], format!("{year}-03-15"));
|
||||
assert!(!shared.to_string().contains("Tokió"), "the place stays private: {shared}");
|
||||
assert!(shared["analysis"].is_null(), "no detailed text yet");
|
||||
|
||||
// the detailed text uses a forecast unit, not a natal one
|
||||
let analyses = format!("/v1/forecasts/{id}/analyses");
|
||||
grant_units(&app, &anna, "natal", 1).await;
|
||||
|
||||
Reference in New Issue
Block a user