Forum: daily sky thread, listeners, mentions, own avatars, restricted topics
- The worker opens a "Mai égbolt" thread every morning from the day's sky (no AI), pinned for the day. - Volunteer listeners (from the Kereső rank) get a badge, a count of the threads asking to be heard that still wait for a reply, and, if they ask, an e-mail after two hours of waiting. - "@Holdfény" names a member (nicknames with spaces too): they follow the thread, hear of it live and, if they asked, by e-mail; a search helps typing it. - From the Kereső rank a member may upload an own avatar: a small square JPEG without metadata in the object storage (now a shared crate with the backend), served by the forum; moderators can put the starter back. - The "Támogató" badge for buyers who switch it on. - The admin creates and edits topics; restricted ones are read by their approved members, who ask to join and moderators decide. - "Most itt vannak" on the front page; the weekly summary e-mail on Sunday evening for those who ask (off by default). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
-- The forum, more (docs/kozosseg.md): the daily sky thread, volunteer
|
||||
-- listeners, mentions, the weekly summary, the supporter badge, and
|
||||
-- restricted topics with approval. (Own avatars need no column: the avatar
|
||||
-- holds `upload:<file>` then.)
|
||||
|
||||
-- The site's own threads and posts (the daily "Mai égbolt"): no member author.
|
||||
ALTER TABLE forum.threads ADD COLUMN system boolean NOT NULL DEFAULT false;
|
||||
-- The daily sky thread of that day (one a day).
|
||||
ALTER TABLE forum.threads ADD COLUMN daily_date date UNIQUE;
|
||||
ALTER TABLE forum.posts ADD COLUMN system boolean NOT NULL DEFAULT false;
|
||||
|
||||
-- Volunteer listeners: told when a thread asking to be heard waits for a reply.
|
||||
ALTER TABLE forum.members ADD COLUMN listener boolean NOT NULL DEFAULT false;
|
||||
ALTER TABLE forum.members ADD COLUMN email_listener text NOT NULL DEFAULT 'off'
|
||||
CHECK (email_listener IN ('off', 'instant'));
|
||||
-- The listeners were told about this thread (once).
|
||||
ALTER TABLE forum.threads ADD COLUMN listeners_notified_at timestamptz;
|
||||
|
||||
-- "@Holdfény" in a post: whom it names.
|
||||
CREATE TABLE forum.mentions (
|
||||
post_id bigint NOT NULL REFERENCES forum.posts ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (post_id, user_id)
|
||||
);
|
||||
CREATE INDEX mentions_user_idx ON forum.mentions (user_id, created_at DESC);
|
||||
ALTER TABLE forum.members ADD COLUMN email_mentions text NOT NULL DEFAULT 'instant'
|
||||
CHECK (email_mentions IN ('off', 'instant'));
|
||||
|
||||
-- The weekly summary e-mail: off until the member asks for it.
|
||||
ALTER TABLE forum.members ADD COLUMN email_weekly boolean NOT NULL DEFAULT false;
|
||||
ALTER TABLE forum.members ADD COLUMN weekly_sent_at timestamptz;
|
||||
|
||||
-- The "Támogató" badge: only for buyers, and only when they switch it on.
|
||||
ALTER TABLE forum.members ADD COLUMN supporter_badge boolean NOT NULL DEFAULT false;
|
||||
|
||||
-- Members of a restricted topic: they ask, a moderator approves.
|
||||
CREATE TABLE forum.topic_members (
|
||||
topic_id smallint NOT NULL REFERENCES forum.topics ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
|
||||
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved')),
|
||||
-- A few words from the member asking to join.
|
||||
note text NOT NULL DEFAULT '',
|
||||
requested_at timestamptz NOT NULL DEFAULT now(),
|
||||
decided_at timestamptz,
|
||||
decided_by uuid REFERENCES users ON DELETE SET NULL,
|
||||
PRIMARY KEY (topic_id, user_id)
|
||||
);
|
||||
CREATE INDEX topic_members_user_idx ON forum.topic_members (user_id) WHERE status = 'approved';
|
||||
|
||||
ALTER TABLE forum.mod_log DROP CONSTRAINT mod_log_action_check;
|
||||
ALTER TABLE forum.mod_log ADD CONSTRAINT mod_log_action_check
|
||||
CHECK (action IN ('delete_post', 'restore_post', 'delete_thread', 'restore_thread', 'ban', 'unban',
|
||||
'lock', 'unlock', 'pin', 'unpin', 'resolve_report', 'dismiss_report',
|
||||
'approve_member', 'reject_member', 'remove_member', 'reset_avatar', 'topic'));
|
||||
@@ -187,6 +187,9 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result<Rendered,
|
||||
("forum_digest", _) => forum_digest(payload, url)?,
|
||||
("forum_message", _) => forum_message(payload, url)?,
|
||||
("forum_moderation", _) => forum_moderation(payload, url)?,
|
||||
("forum_mention", _) => forum_mention(payload, url)?,
|
||||
("forum_listener", _) => forum_listener(payload, url)?,
|
||||
("forum_weekly", _) => forum_weekly(payload, url)?,
|
||||
("forum_report_result", _) => forum_report_result(payload, url)?,
|
||||
_ => return Err(TemplateError::UnknownTemplate(template.to_owned())),
|
||||
};
|
||||
@@ -361,6 +364,90 @@ fn forum_reply(payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||
forum_footer(payload, content, "a fórumon azonnali értesítést kértél a válaszokról")
|
||||
}
|
||||
|
||||
/// Someone named the member ("@Holdfény") in a post.
|
||||
fn forum_mention(payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||
let author = name(payload, "author").unwrap_or_else(|| "Valaki".into());
|
||||
let title = name(payload, "thread_title").ok_or(TemplateError::MissingField("thread_title"))?;
|
||||
let content = Content {
|
||||
subject: format!("{author} megemlített: „{title}”"),
|
||||
preheader: excerpt(payload, "excerpt", 90),
|
||||
greeting: hello(payload),
|
||||
intro: format!("{author} megemlített a Sorsfonalak fórumán, a(z) „{title}” szálban:"),
|
||||
quote: excerpt(payload, "excerpt", 300),
|
||||
points: None,
|
||||
code: None,
|
||||
button: "Megnézem",
|
||||
url,
|
||||
note: "Az említésekről szóló leveleket a fórumprofilodnál kapcsolhatod ki.".into(),
|
||||
reason: None,
|
||||
unsubscribe: None,
|
||||
unsubscribe_post_url: None,
|
||||
};
|
||||
forum_footer(payload, content, "a fórumon értesítést kértél, ha megemlítenek")
|
||||
}
|
||||
|
||||
/// For a volunteer listener: a thread asking to be heard waits for a reply.
|
||||
fn forum_listener(payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||
let title = name(payload, "thread_title").ok_or(TemplateError::MissingField("thread_title"))?;
|
||||
let content = Content {
|
||||
subject: format!("Válaszra vár: „{title}”"),
|
||||
preheader: Some("Valaki meghallgatást kért, és még senki nem válaszolt.".into()),
|
||||
greeting: hello(payload),
|
||||
intro: format!(
|
||||
"A(z) „{title}” szálban valaki meghallgatást kért, és még senki nem válaszolt neki. Ha van rá időd, egy pár soros válasz is sokat jelenthet."
|
||||
),
|
||||
quote: None,
|
||||
points: None,
|
||||
code: None,
|
||||
button: "Elolvasom",
|
||||
url,
|
||||
note: "Tanács helyett elég, ha leírod, hogy itt vagy, vagy hogy veled is történt hasonló.".into(),
|
||||
reason: None,
|
||||
unsubscribe: None,
|
||||
unsubscribe_post_url: None,
|
||||
};
|
||||
forum_footer(payload, content, "önkéntes meghallgatóként értesítést kértél a válasz nélküli szálakról")
|
||||
}
|
||||
|
||||
/// The weekly summary: the busiest threads, and those still waiting.
|
||||
fn forum_weekly(payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||
let lines = |key: &'static str| -> Vec<String> {
|
||||
payload[key]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|l| l.as_str())
|
||||
.map(|l| l.chars().filter(|c| !c.is_control()).take(160).collect())
|
||||
.collect()
|
||||
};
|
||||
let busy = lines("busy");
|
||||
let waiting = lines("waiting");
|
||||
if busy.is_empty() && waiting.is_empty() {
|
||||
return Err(TemplateError::MissingField("busy"));
|
||||
}
|
||||
let mut items = busy;
|
||||
if !waiting.is_empty() {
|
||||
items.push("Még válaszra vár:".into());
|
||||
items.extend(waiting.into_iter().map(|w| format!(" {w}")));
|
||||
}
|
||||
let content = Content {
|
||||
subject: "A hét a fórumon".into(),
|
||||
preheader: items.first().cloned(),
|
||||
greeting: hello(payload),
|
||||
intro: "Ezekről beszélgettünk a héten a Sorsfonalak fórumán:".into(),
|
||||
quote: None,
|
||||
points: Some(("A hét szálai:", items)),
|
||||
code: None,
|
||||
button: "Benézek a fórumra",
|
||||
url,
|
||||
note: "Hetente egyszer, vasárnap este küldjük, ha kérted.".into(),
|
||||
reason: None,
|
||||
unsubscribe: None,
|
||||
unsubscribe_post_url: None,
|
||||
};
|
||||
forum_footer(payload, content, "a fórumon heti összefoglalót kértél")
|
||||
}
|
||||
|
||||
/// The daily digest: the threads with new posts for the member.
|
||||
fn forum_digest(payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||
let lines: Vec<String> = payload["lines"]
|
||||
@@ -1367,5 +1454,18 @@ mod tests {
|
||||
let m = render("forum_report_result", "hu", &json!({"url": "u", "outcome": "no_violation"})).unwrap();
|
||||
assert!(m.text.starts_with("Szia!") && m.text.contains("a tartalom marad"));
|
||||
assert!(render("forum_report_result", "hu", &json!({"url": "u"})).is_err());
|
||||
|
||||
let mut p = forum_links();
|
||||
p["author"] = json!("Zöldág");
|
||||
p["thread_title"] = json!("Téli levesek");
|
||||
p["excerpt"] = json!("@Csendesvíz szerinted?");
|
||||
assert_eq!(render("forum_mention", "hu", &p).unwrap().subject, "Zöldág megemlített: „Téli levesek”");
|
||||
let m = render("forum_listener", "hu", &p).unwrap();
|
||||
assert_eq!(m.subject, "Válaszra vár: „Téli levesek”");
|
||||
let mut p = forum_links();
|
||||
p["busy"] = json!(["„Téli levesek” – 12 hozzászólás"]);
|
||||
p["waiting"] = json!(["„Nehéz napok”"]);
|
||||
let m = render("forum_weekly", "hu", &p).unwrap();
|
||||
assert!(m.text.contains("Még válaszra vár") && m.unsubscribe_post_url.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "object-storage"
|
||||
description = "S3-compatible object storage (DigitalOcean Spaces, RustFS) for the Sorsfonalak services"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
bytes = "1"
|
||||
hmac.workspace = true
|
||||
reqwest.workspace = true
|
||||
sha2.workspace = true
|
||||
thiserror.workspace = true
|
||||
time.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio.workspace = true
|
||||
@@ -0,0 +1,294 @@
|
||||
//! Object storage for uploaded pictures (the backend's photos, the forum's
|
||||
//! avatars): any S3-compatible service, addressed path-style
|
||||
//! (`{endpoint}/{bucket}/{key}`). In production DigitalOcean Spaces, in
|
||||
//! development a RustFS container.
|
||||
//!
|
||||
//! The bucket stays private: the services read the objects themselves and
|
||||
//! serve them (the backend under `/v1/public/photos/...`, the forum under
|
||||
//! `/v1/forum/avatars/...`).
|
||||
//!
|
||||
//! Requests are signed with AWS Signature Version 4.
|
||||
|
||||
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: bytes::Bytes,
|
||||
pub content_type: Option<String>,
|
||||
}
|
||||
|
||||
impl StorageConfig {
|
||||
/// From `S3_ENDPOINT`, `S3_BUCKET`, `S3_REGION` (default `us-east-1`),
|
||||
/// `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`; `None` without an endpoint.
|
||||
pub fn from_env() -> Result<Option<Self>, String> {
|
||||
let var = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty());
|
||||
let Some(endpoint) = var("S3_ENDPOINT") else { return Ok(None) };
|
||||
let required = |name: &str| var(name).ok_or_else(|| format!("{name} is required with S3_ENDPOINT"));
|
||||
Ok(Some(Self {
|
||||
endpoint: endpoint.trim_end_matches('/').to_string(),
|
||||
bucket: required("S3_BUCKET")?,
|
||||
region: var("S3_REGION").unwrap_or_else(|| "us-east-1".into()),
|
||||
access_key: required("S3_ACCESS_KEY_ID")?,
|
||||
secret_key: required("S3_SECRET_ACCESS_KEY")?,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
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 object-storage 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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user