feat(hub): add central service foundation and transactional mail
This commit is contained in:
parent
b14f036bdb
commit
a811de590a
25 changed files with 1521 additions and 4 deletions
29
hub/Cargo.toml
Normal file
29
hub/Cargo.toml
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
[package]
|
||||
name = "vnox-hub"
|
||||
description = "Vnox central service foundation — identity, readiness and transactional mail"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
axum = "0.8"
|
||||
ed25519-dalek.workspace = true
|
||||
hex.workspace = true
|
||||
rand.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio = { workspace = true, features = ["signal"] }
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
uuid = { workspace = true, features = ["serde"] }
|
||||
sqlx = { version = "0.9", default-features = false, features = ["sqlite", "runtime-tokio", "migrate", "macros"] }
|
||||
lettre = { version = "0.11.23", default-features = false, features = ["builder", "smtp-transport", "tokio1-rustls", "aws-lc-rs", "webpki-roots"] }
|
||||
url = "2"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
79
hub/README.md
Normal file
79
hub/README.md
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
# Vnox Hub foundation
|
||||
|
||||
`vnox-hub` is the central service foundation. It starts as one HTTP service behind
|
||||
an HTTPS reverse proxy and stores its issuer identity and SQLite database locally.
|
||||
Community messages and voice never pass through this process.
|
||||
|
||||
## Implemented
|
||||
|
||||
- `/health`: process liveness.
|
||||
- `/ready`: database readiness after successful migrations and issuer validation.
|
||||
- `/version`: binary version and explicit `foundation` stage.
|
||||
- `/v1/info`: public issuer ID/key and honest feature availability.
|
||||
- `/`: deployment status page; `/assets/vnox-mark.svg`: approved V connection mark.
|
||||
- Durable SQLite schema and issuer identity with a private `0600` key file.
|
||||
- TLS-only SMTP transport and HTML/plain-text transactional email templates.
|
||||
|
||||
Email authentication, GitHub OAuth, server registration/discovery, friends, DM
|
||||
storage and marketplace API are **not enabled**. There is no public endpoint for
|
||||
sending mail. Existing schema tables are foundations, not working authentication.
|
||||
Template links are previews of future routes; they do not create working tokens.
|
||||
|
||||
## Configuration
|
||||
|
||||
Set these in a protected systemd `EnvironmentFile` outside Git. Use a dedicated
|
||||
service user, a private `0700` data directory, restrictive umask and loopback-only HTTP.
|
||||
|
||||
```ini
|
||||
HUB_BIND=127.0.0.1:17843
|
||||
HUB_DATA_DIR=/var/lib/vnox-hub
|
||||
PUBLIC_BASE_URL=https://central.loki-code.dev
|
||||
SMTP_HOST=smtp.provider.example
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=provider-user
|
||||
SMTP_PASSWORD=replace-outside-git
|
||||
MAIL_FROM="Vnox <noreply@loki-code.dev>"
|
||||
RUST_LOG=vnox_hub=info
|
||||
```
|
||||
|
||||
`SMTP_HOST` may be omitted to disable the transport. Partially configured
|
||||
credentials cause startup validation errors instead of silent fallback. Port465
|
||||
uses implicit TLS; all other ports require STARTTLS with certificate validation.
|
||||
No plaintext downgrade is supported. SMTP construction validates configuration;
|
||||
readiness does not claim SMTP delivery was tested. Configure an external monitor
|
||||
for `/ready` and perform SMTP connectivity checks separately.
|
||||
|
||||
`PUBLIC_BASE_URL` must be an HTTPS origin with no path, query, credentials or
|
||||
fragment. It is the only source for email links; request Host headers are ignored.
|
||||
Do not configure an untrusted hostname as the public origin.
|
||||
|
||||
## Run and verify
|
||||
|
||||
Run commands from `VNOX-Server/`:
|
||||
|
||||
```sh
|
||||
cargo run -p vnox-hub
|
||||
cargo run -p vnox-hub -- --check-smtp
|
||||
cargo run -p vnox-hub -- --render-email-preview /tmp/vnox-mail-preview
|
||||
cargo test -p vnox-hub
|
||||
cargo clippy -p vnox-hub --all-targets -- -D warnings
|
||||
```
|
||||
|
||||
`--check-smtp` connects, validates TLS/authentication and issues an SMTP NOOP. It
|
||||
never sends mail. `--render-email-preview` writes three HTML/plain-text pairs with
|
||||
dummy token/code values and never contacts SMTP. Do not use example values as
|
||||
real verification credentials. Secrets must not be passed as command arguments.
|
||||
|
||||
## Deployment and backup
|
||||
|
||||
Terminate HTTPS at Nginx, keep the random Hub listener on loopback, and expose only
|
||||
443/80 as required for HTTPS/ACME. Check configuration before reloading Nginx.
|
||||
Use the supplied parent deployment configuration once reviewed. The process
|
||||
handles SIGTERM/Ctrl-C with graceful HTTP shutdown and closes its SQLite pool.
|
||||
|
||||
Keep `issuer.json` and `hub.sqlite3` together in backup/restore. If their identities
|
||||
differ, startup fails; it must never silently replace the issuer of an existing
|
||||
Hub. An invalid/malformed issuer file likewise fails closed. Protect the entire
|
||||
data directory, not only the JSON file. Additional account/device revocation,
|
||||
registry authorization, mailbox lifecycle and storage policies require their own
|
||||
implementation and security review before those capabilities are enabled.
|
||||
4
hub/assets/index.html
Normal file
4
hub/assets/index.html
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
<!doctype html>
|
||||
<html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Vnox Central</title>
|
||||
<style>html{color-scheme:dark}*{box-sizing:border-box}body{margin:0;background:#151516;color:#e9e7e4;font:16px/1.6 system-ui,sans-serif;min-height:100vh;display:grid;place-items:center;padding:24px}main{max-width:660px;width:100%;border:1px solid #403a33;border-radius:18px;overflow:hidden;background:#202022}header{padding:32px;background:linear-gradient(125deg,#45382d,#292829);display:flex;gap:15px;align-items:center}img{width:50px;height:50px}header strong{font-size:24px;letter-spacing:-.5px}section{padding:30px 32px}h1{font-size:23px;line-height:1.3;margin:0 0 16px}p{color:#bab3aa;margin:0 0 20px}.status{display:inline-block;color:#bbcfad;font-size:13px;background:#30362e;padding:4px 10px;border-radius:6px}ul{padding-left:20px;color:#c7bfb4}footer{padding:18px 32px;border-top:1px solid #393531;color:#a49a90;font-size:13px}a{color:#d5b58a;text-underline-offset:3px}nav{display:flex;flex-wrap:wrap;gap:22px;margin-top:27px}</style></head>
|
||||
<body><main><header><img src="/assets/vnox-mark.svg" alt=""><strong>Vnox Central</strong></header><section><span class="status">Сервис развёрнут · базовый этап</span><h1 style="margin-top:22px">Центр сети Vnox</h1><p>Здесь появятся общий профиль, друзья и поиск серверов. Сейчас подготовлены служба, постоянная identity, база данных и почтовый транспорт.</p><ul><li>Регистрация и вход пока не включены.</li><li>Каталог серверов, личные сообщения и маркетплейс ещё разрабатываются.</li><li>Сообщества обслуживают свои чаты и голос самостоятельно.</li></ul><nav><a href="/ready">Готовность службы</a><a href="/v1/info">Возможности API</a><a href="/version">Версия</a></nav></section><footer>Vnox · собственные сообщества, общее пространство для общения.</footer></main></body></html>
|
||||
BIN
hub/assets/vnox-mark.png
Normal file
BIN
hub/assets/vnox-mark.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3 KiB |
1
hub/assets/vnox-mark.svg
Normal file
1
hub/assets/vnox-mark.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Vnox"><rect width="64" height="64" rx="17" fill="#202022"/><g fill="none" stroke="#dac5a6" stroke-width="5" stroke-linejoin="round" stroke-linecap="round"><path d="M16 20 32 46 48 20"/><path d="M16 20H26M38 20H48"/></g></svg>
|
||||
|
After Width: | Height: | Size: 308 B |
26
hub/migrations/0001_foundation.sql
Normal file
26
hub/migrations/0001_foundation.sql
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
-- No authentication/registry endpoints use these tables yet. Defining durable
|
||||
-- IDs now does not imply that account/device authorization is implemented.
|
||||
CREATE TABLE hub_metadata (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE accounts (
|
||||
user_id TEXT PRIMARY KEY,
|
||||
handle TEXT UNIQUE NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE devices (
|
||||
device_id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES accounts(user_id) ON DELETE CASCADE,
|
||||
public_key BLOB NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
revoked_at INTEGER
|
||||
);
|
||||
CREATE TABLE servers (
|
||||
server_id TEXT PRIMARY KEY,
|
||||
owner_user_id TEXT NOT NULL REFERENCES accounts(user_id),
|
||||
public_key BLOB UNIQUE NOT NULL,
|
||||
address TEXT NOT NULL,
|
||||
visibility TEXT NOT NULL CHECK (visibility IN ('private', 'unlisted', 'public')),
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
99
hub/src/config.rs
Normal file
99
hub/src/config.rs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
use std::{net::SocketAddr, path::PathBuf};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use url::Url;
|
||||
|
||||
/// Public deployment configuration. Secret-bearing SMTP fields are intentionally not Debug.
|
||||
pub struct Config {
|
||||
pub bind: SocketAddr,
|
||||
pub data_dir: PathBuf,
|
||||
pub origin: Url,
|
||||
pub smtp: Option<SmtpConfig>,
|
||||
}
|
||||
|
||||
/// SMTP credentials are only read from the service environment, never command arguments.
|
||||
pub struct SmtpConfig {
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
pub user: String,
|
||||
pub password: String,
|
||||
pub from: String,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn from_env() -> Result<Self> {
|
||||
Self::from_lookup(|name| std::env::var(name).ok())
|
||||
}
|
||||
|
||||
pub fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Result<Self> {
|
||||
let bind = get("HUB_BIND")
|
||||
.unwrap_or_else(|| "127.0.0.1:17843".into())
|
||||
.parse::<SocketAddr>()
|
||||
.context("HUB_BIND must be an IP address and port")?;
|
||||
if !bind.ip().is_loopback() {
|
||||
bail!("HUB_BIND must be loopback; terminate HTTPS at the reverse proxy");
|
||||
}
|
||||
let origin = parse_origin(
|
||||
&get("PUBLIC_BASE_URL").unwrap_or_else(|| "https://central.loki-code.dev".into()),
|
||||
)?;
|
||||
let smtp_host = get("SMTP_HOST").unwrap_or_default();
|
||||
let smtp = if smtp_host.trim().is_empty() {
|
||||
if ["SMTP_USER", "SMTP_PASSWORD", "SMTP_PORT"]
|
||||
.iter()
|
||||
.any(|name| get(name).is_some_and(|value| !value.trim().is_empty()))
|
||||
{
|
||||
bail!("SMTP credentials/port require SMTP_HOST");
|
||||
}
|
||||
None
|
||||
} else {
|
||||
let port = get("SMTP_PORT")
|
||||
.unwrap_or_else(|| "587".into())
|
||||
.parse::<u16>()
|
||||
.context("SMTP_PORT must be a number")?;
|
||||
let user = get("SMTP_USER").unwrap_or_default();
|
||||
let password = get("SMTP_PASSWORD").unwrap_or_default();
|
||||
if user.is_empty() != password.is_empty() {
|
||||
bail!("SMTP_USER and SMTP_PASSWORD must be configured together");
|
||||
}
|
||||
if smtp_host.chars().any(char::is_whitespace)
|
||||
|| smtp_host.contains('/')
|
||||
|| smtp_host.contains('@')
|
||||
{
|
||||
bail!("SMTP_HOST must be a hostname, not a URL");
|
||||
}
|
||||
if port == 0 {
|
||||
bail!("SMTP_PORT cannot be zero");
|
||||
}
|
||||
Some(SmtpConfig {
|
||||
host: smtp_host,
|
||||
port,
|
||||
user,
|
||||
password,
|
||||
from: get("MAIL_FROM").unwrap_or_else(|| "Vnox <noreply@loki-code.dev>".into()),
|
||||
})
|
||||
};
|
||||
Ok(Self {
|
||||
bind,
|
||||
origin,
|
||||
smtp,
|
||||
data_dir: get("HUB_DATA_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("./dev/hub-data")),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_origin(value: &str) -> Result<Url> {
|
||||
let url = Url::parse(value).context("PUBLIC_BASE_URL must be an HTTPS origin")?;
|
||||
if url.scheme() != "https"
|
||||
|| url.host_str().is_none()
|
||||
|| !url.username().is_empty()
|
||||
|| url.password().is_some()
|
||||
|| url.query().is_some()
|
||||
|| url.fragment().is_some()
|
||||
|| url.path() != "/"
|
||||
{
|
||||
bail!("PUBLIC_BASE_URL must be an HTTPS origin without credentials, path or query");
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
44
hub/src/database.rs
Normal file
44
hub/src/database.rs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
use std::{path::Path, time::Duration};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use sqlx::{SqlitePool, sqlite::SqliteConnectOptions};
|
||||
|
||||
use crate::identity::Issuer;
|
||||
|
||||
pub async fn open(directory: &Path, issuer: &Issuer) -> Result<SqlitePool> {
|
||||
let options = SqliteConnectOptions::new()
|
||||
.filename(directory.join("hub.sqlite3"))
|
||||
.create_if_missing(true)
|
||||
.foreign_keys(true)
|
||||
.busy_timeout(Duration::from_secs(5));
|
||||
let pool = sqlx::sqlite::SqlitePoolOptions::new()
|
||||
.max_connections(4)
|
||||
.acquire_timeout(Duration::from_secs(5))
|
||||
.connect_with(options)
|
||||
.await
|
||||
.context("opening Hub database")?;
|
||||
sqlx::migrate!("./migrations")
|
||||
.run(&pool)
|
||||
.await
|
||||
.context("migrating Hub database")?;
|
||||
let mut transaction = pool.begin().await?;
|
||||
for (name, value) in [
|
||||
("issuer_id", issuer.id.to_string()),
|
||||
("issuer_public_key", issuer.public_key.clone()),
|
||||
] {
|
||||
sqlx::query("INSERT OR IGNORE INTO hub_metadata(key,value) VALUES (?,?)")
|
||||
.bind(name)
|
||||
.bind(&value)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
let existing: String = sqlx::query_scalar("SELECT value FROM hub_metadata WHERE key=?")
|
||||
.bind(name)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await?;
|
||||
if existing != value {
|
||||
bail!("Hub database and issuer identity do not match; restore them together");
|
||||
}
|
||||
}
|
||||
transaction.commit().await?;
|
||||
Ok(pool)
|
||||
}
|
||||
148
hub/src/identity.rs
Normal file
148
hub/src/identity.rs
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
use std::{fs::OpenOptions, io::Write, path::Path};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use ed25519_dalek::SigningKey;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct StoredIdentity {
|
||||
version: u32,
|
||||
issuer_id: Uuid,
|
||||
secret_key: String,
|
||||
public_key: String,
|
||||
}
|
||||
|
||||
/// Stable issuer identity. Only its public projection is exposed through HTTP.
|
||||
pub struct Issuer {
|
||||
pub id: Uuid,
|
||||
pub public_key: String,
|
||||
}
|
||||
|
||||
impl Issuer {
|
||||
pub fn load_or_create(directory: &Path) -> Result<Self> {
|
||||
let mut builder = std::fs::DirBuilder::new();
|
||||
builder.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
builder.mode(0o700);
|
||||
}
|
||||
builder
|
||||
.create(directory)
|
||||
.context("creating Hub data directory")?;
|
||||
check_private_directory(directory)?;
|
||||
let path = directory.join("issuer.json");
|
||||
let stored = match OpenOptions::new().read(true).open(&path) {
|
||||
Ok(file) => {
|
||||
check_private_permissions(&file)?;
|
||||
if file.metadata()?.len() > 4096 {
|
||||
bail!("Hub issuer identity exceeds the expected size");
|
||||
}
|
||||
let value: StoredIdentity =
|
||||
serde_json::from_reader(file).context("reading Hub issuer identity")?;
|
||||
value
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
let key = SigningKey::generate(&mut rand::rng());
|
||||
let value = StoredIdentity {
|
||||
version: 1,
|
||||
issuer_id: Uuid::new_v4(),
|
||||
secret_key: hex::encode(key.to_bytes()),
|
||||
public_key: hex::encode(key.verifying_key().to_bytes()),
|
||||
};
|
||||
persist_new_identity(&path, &value)?;
|
||||
value
|
||||
}
|
||||
Err(error) => return Err(error).context("opening Hub issuer identity"),
|
||||
};
|
||||
let secret = hex::decode(&stored.secret_key)
|
||||
.ok()
|
||||
.and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
|
||||
.context("Hub issuer private key has invalid encoding or length")?;
|
||||
let key = SigningKey::from_bytes(&secret);
|
||||
if stored.version != 1 || hex::encode(key.verifying_key().to_bytes()) != stored.public_key {
|
||||
bail!("Hub issuer identity failed integrity validation");
|
||||
}
|
||||
Ok(Self {
|
||||
id: stored.issuer_id,
|
||||
public_key: stored.public_key,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn check_private_permissions(file: &std::fs::File) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if file.metadata()?.permissions().mode() & 0o077 != 0 {
|
||||
bail!("Hub issuer identity must not be accessible to group/other users (use 0600)");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_private_directory(directory: &Path) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if std::fs::metadata(directory)?.permissions().mode() & 0o077 != 0 {
|
||||
bail!("Hub data directory must be private (use 0700)");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Publish a fully synced key file without replacing any concurrent issuer.
|
||||
// A failed first write must never leave a truncated final identity behind.
|
||||
fn persist_new_identity(path: &Path, identity: &StoredIdentity) -> Result<()> {
|
||||
let temporary = path.with_extension(format!("{}.tmp", Uuid::new_v4()));
|
||||
let result = (|| -> Result<()> {
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
{
|
||||
let mut file = options
|
||||
.open(&temporary)
|
||||
.context("preparing Hub issuer identity")?;
|
||||
file.write_all(&serde_json::to_vec_pretty(identity)?)
|
||||
.context("writing Hub issuer identity")?;
|
||||
file.sync_all().context("syncing Hub issuer identity")?;
|
||||
}
|
||||
std::fs::hard_link(&temporary, path).context("publishing new Hub issuer identity")?;
|
||||
#[cfg(unix)]
|
||||
std::fs::File::open(path.parent().context("issuer directory is missing")?)?
|
||||
.sync_all()
|
||||
.context("syncing Hub issuer directory")?;
|
||||
Ok(())
|
||||
})();
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn publishing_never_overwrites_an_existing_identity_or_leaves_temp_files() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("issuer.json");
|
||||
std::fs::write(&path, b"existing issuer").unwrap();
|
||||
let key = SigningKey::generate(&mut rand::rng());
|
||||
let candidate = StoredIdentity {
|
||||
version: 1,
|
||||
issuer_id: Uuid::new_v4(),
|
||||
secret_key: hex::encode(key.to_bytes()),
|
||||
public_key: hex::encode(key.verifying_key().to_bytes()),
|
||||
};
|
||||
assert!(persist_new_identity(&path, &candidate).is_err());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"existing issuer");
|
||||
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
|
||||
}
|
||||
}
|
||||
5
hub/src/lib.rs
Normal file
5
hub/src/lib.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
pub mod config;
|
||||
pub mod database;
|
||||
pub mod identity;
|
||||
pub mod mail;
|
||||
pub mod web;
|
||||
59
hub/src/mail/layout.rs
Normal file
59
hub/src/mail/layout.rs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
/// Escape all dynamic HTML, including attribute values.
|
||||
pub fn escape(value: &str) -> String {
|
||||
value
|
||||
.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
.replace('\'', "'")
|
||||
}
|
||||
|
||||
pub struct Content<'a> {
|
||||
pub title: &'a str,
|
||||
pub preheader: &'a str,
|
||||
pub paragraphs: &'a [&'a str],
|
||||
pub code: Option<&'a str>,
|
||||
pub button: &'a str,
|
||||
pub url: &'a str,
|
||||
pub expiry: &'a str,
|
||||
pub origin: &'a str,
|
||||
}
|
||||
|
||||
/// Table-based inline HTML with a solid-color fallback for gradient support.
|
||||
pub fn render(content: &Content<'_>) -> String {
|
||||
let paragraphs = content
|
||||
.paragraphs
|
||||
.iter()
|
||||
.map(|value| {
|
||||
format!(
|
||||
"<p style=\"margin:0 0 16px;font-size:16px;line-height:26px;color:#eae6df\">{}</p>",
|
||||
escape(value)
|
||||
)
|
||||
})
|
||||
.collect::<String>();
|
||||
let code = content.code.map(|value| format!("<p style=\"margin:22px 0;padding:18px;background:#111112;border:1px solid #494238;border-radius:10px;font-family:Consolas,monospace;font-size:30px;font-weight:700;letter-spacing:6px;text-align:center;color:#f0d7ae\">{}</p>", escape(value))).unwrap_or_default();
|
||||
let title = escape(content.title);
|
||||
let url = escape(content.url);
|
||||
let origin = escape(content.origin);
|
||||
format!(
|
||||
r##"<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark light"><title>{title}</title></head>
|
||||
<body style="margin:0;padding:0;background:#101011" bgcolor="#101011">
|
||||
<div style="display:none;max-height:0;overflow:hidden;opacity:0">{preheader}</div>
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#101011"><tr><td align="center" style="padding:32px 12px">
|
||||
<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" bgcolor="#1c1c1e" style="width:100%;max-width:600px;border:1px solid #383634;border-radius:18px;overflow:hidden;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif">
|
||||
<tr><td bgcolor="#38312a" style="background:#38312a;background-image:linear-gradient(125deg,#514033 0%,#39312c 55%,#242426 100%);padding:30px 32px 32px">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr><td width="42" height="42" align="center" bgcolor="#151516" style="border-radius:11px;color:#e8d5b8;font-size:19px;font-weight:800"><img src="{origin}/assets/vnox-mark.png" width="42" height="42" alt="V" style="display:block;border:0;border-radius:11px"></td><td style="padding-left:12px;color:#f6f0e7;font-size:23px;font-weight:700">Vnox</td></tr></table>
|
||||
<p style="margin:25px 0 10px;color:#d1b998;font-size:12px">Личное пространство для общения</p>
|
||||
<h1 style="margin:0;color:#fff9ef;font-size:28px;line-height:35px;font-weight:700">{title}</h1>
|
||||
</td></tr><tr><td style="padding:32px 32px 12px">{paragraphs}{code}
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:23px 0 17px"><tr><td bgcolor="#d5b58a" style="border-radius:9px"><a href="{url}" style="display:inline-block;padding:14px 26px;color:#231d16;text-decoration:none;font-size:15px;font-weight:700;border-radius:9px">{button}</a></td></tr></table>
|
||||
<p style="margin:0 0 24px;font-size:13px;line-height:21px;color:#aca49a">{expiry}</p>
|
||||
<p style="margin:0 0 9px;font-size:12px;color:#aca49a">Если кнопка не открывается, скопируй ссылку:</p>
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td bgcolor="#171718" style="padding:13px;border:1px solid #3c3732;border-radius:9px;word-break:break-all;font-size:12px;line-height:20px"><a href="{url}" style="color:#d8bd98;text-decoration:none">{url}</a></td></tr></table>
|
||||
<p style="margin:26px 0 18px;font-size:13px;line-height:21px;color:#aca49a">Не запрашивал это действие? Не передавай код или ссылку другим людям. Если это письмо о новом устройстве, проверь активные сеансы.</p>
|
||||
</td></tr><tr><td bgcolor="#171718" style="border-top:1px solid #383634;padding:21px 32px;color:#9e978d;font-size:12px;line-height:20px">Автоматическое письмо Vnox. Отвечать на него не нужно.<br><a href="{origin}" style="color:#d8bd98;text-decoration:none">{origin}</a></td></tr></table></td></tr></table></body></html>"##,
|
||||
preheader = escape(content.preheader),
|
||||
button = escape(content.button),
|
||||
expiry = escape(content.expiry),
|
||||
)
|
||||
}
|
||||
65
hub/src/mail/mod.rs
Normal file
65
hub/src/mail/mod.rs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
pub mod layout;
|
||||
pub mod templates;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use lettre::{
|
||||
AsyncSmtpTransport, AsyncTransport, Tokio1Executor,
|
||||
message::{Mailbox, Message, MultiPart},
|
||||
transport::smtp::authentication::Credentials,
|
||||
};
|
||||
|
||||
use crate::config::SmtpConfig;
|
||||
|
||||
/// TLS-only SMTP transport, deliberately without Debug or credential logging.
|
||||
pub struct Mailer {
|
||||
transport: AsyncSmtpTransport<Tokio1Executor>,
|
||||
from: Mailbox,
|
||||
}
|
||||
|
||||
impl Mailer {
|
||||
pub fn new(config: &SmtpConfig) -> Result<Self> {
|
||||
let builder = if config.port == 465 {
|
||||
AsyncSmtpTransport::<Tokio1Executor>::relay(&config.host)
|
||||
} else {
|
||||
AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&config.host)
|
||||
}
|
||||
.context("invalid SMTP TLS hostname")?;
|
||||
let mut builder = builder
|
||||
.port(config.port)
|
||||
.timeout(Some(Duration::from_secs(15)));
|
||||
if !config.user.is_empty() {
|
||||
builder = builder.credentials(Credentials::new(
|
||||
config.user.clone(),
|
||||
config.password.clone(),
|
||||
));
|
||||
}
|
||||
Ok(Self {
|
||||
transport: builder.build(),
|
||||
from: config.from.parse().context("MAIL_FROM must be a mailbox")?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Connect, negotiate TLS, authenticate and issue NOOP; never sends a message.
|
||||
pub async fn check_connection(&self) -> Result<()> {
|
||||
match self.transport.test_connection().await {
|
||||
Ok(true) => Ok(()),
|
||||
Ok(false) | Err(_) => bail!("SMTP TLS/authentication check failed"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal transport only. There is intentionally no public send-email HTTP endpoint.
|
||||
pub async fn deliver(&self, recipient: &str, email: templates::Email) -> Result<()> {
|
||||
let message = Message::builder()
|
||||
.from(self.from.clone())
|
||||
.to(recipient.parse().context("invalid recipient mailbox")?)
|
||||
.subject(email.subject)
|
||||
.multipart(MultiPart::alternative_plain_html(email.text, email.html))?;
|
||||
self.transport
|
||||
.send(message)
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("SMTP delivery failed"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
118
hub/src/mail/templates.rs
Normal file
118
hub/src/mail/templates.rs
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
use anyhow::{Result, bail};
|
||||
use url::Url;
|
||||
|
||||
use super::layout::{self, Content};
|
||||
use crate::config::parse_origin;
|
||||
|
||||
/// A rendered transactional message; no recipient or delivery happens here.
|
||||
pub struct Email {
|
||||
pub subject: String,
|
||||
pub text: String,
|
||||
pub html: String,
|
||||
}
|
||||
|
||||
pub enum Kind<'a> {
|
||||
Verify { token: &'a str },
|
||||
Login { code: &'a str },
|
||||
NewDevice { device: &'a str },
|
||||
}
|
||||
|
||||
pub fn render(origin: &Url, kind: Kind<'_>) -> Result<Email> {
|
||||
parse_origin(origin.as_str())?;
|
||||
let (title, paragraphs, code, button, path, expiry) = match kind {
|
||||
Kind::Verify { token } => {
|
||||
if token.is_empty() || token.len() > 512 {
|
||||
bail!("invalid verification token length");
|
||||
}
|
||||
(
|
||||
"Подтверди свою почту",
|
||||
vec!["Добро пожаловать в Vnox!".to_owned(), "Подтверди адрес, чтобы завершить настройку профиля и пользоваться глобальными функциями.".to_owned()],
|
||||
None,
|
||||
"Подтвердить почту",
|
||||
("verify-email", Some(("token", token))),
|
||||
"Ссылка действует 24 часа и может быть использована только один раз.",
|
||||
)
|
||||
}
|
||||
Kind::Login { code } => {
|
||||
if code.len() != 8 || !code.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
bail!("login code must contain exactly eight ASCII digits");
|
||||
}
|
||||
(
|
||||
"Твой код входа",
|
||||
vec![
|
||||
"Используй этот одноразовый код, чтобы войти в Vnox. Никому его не сообщай."
|
||||
.to_owned(),
|
||||
],
|
||||
Some(code),
|
||||
"Открыть Vnox",
|
||||
("login", None),
|
||||
"Код действует 10 минут. Он не продлевается при повторном открытии письма.",
|
||||
)
|
||||
}
|
||||
Kind::NewDevice { device } => {
|
||||
if device.is_empty() || device.len() > 200 || device.chars().any(char::is_control) {
|
||||
bail!("invalid device description");
|
||||
}
|
||||
(
|
||||
"Новое устройство в аккаунте",
|
||||
vec![format!("К твоему аккаунту подключено устройство: {device}."), "Если это был не ты, проверь список устройств и отзови доступ незнакомого сеанса.".to_owned()],
|
||||
None,
|
||||
"Проверить устройства",
|
||||
("account/devices", None),
|
||||
"Уведомление не содержит ключей или токенов доступа.",
|
||||
)
|
||||
}
|
||||
};
|
||||
let mut url = origin.join(path.0)?;
|
||||
if let Some((name, value)) = path.1 {
|
||||
url.query_pairs_mut().append_pair(name, value);
|
||||
}
|
||||
let paragraph_refs = paragraphs.iter().map(String::as_str).collect::<Vec<_>>();
|
||||
let origin_text = origin.as_str().trim_end_matches('/');
|
||||
let content = Content {
|
||||
title,
|
||||
preheader: title,
|
||||
paragraphs: ¶graph_refs,
|
||||
code,
|
||||
button,
|
||||
url: url.as_str(),
|
||||
expiry,
|
||||
origin: origin_text,
|
||||
};
|
||||
let text = format!(
|
||||
"Vnox\n\n{title}\n\n{}\n\n{}\n{button}: {}\n\n{expiry}\n\nНе передавай код или ссылку другим людям.\n\n{origin_text}\n",
|
||||
paragraphs.join("\n\n"),
|
||||
code.map(|value| format!("Код: {value}\n"))
|
||||
.unwrap_or_default(),
|
||||
url.as_str(),
|
||||
);
|
||||
Ok(Email {
|
||||
subject: format!("Vnox — {title}"),
|
||||
text,
|
||||
html: layout::render(&content),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn write_previews(directory: &std::path::Path, origin: &Url) -> Result<()> {
|
||||
std::fs::create_dir_all(directory)?;
|
||||
for (name, kind) in [
|
||||
(
|
||||
"verify",
|
||||
Kind::Verify {
|
||||
token: "DUMMY_PREVIEW_NOT_A_REAL_TOKEN",
|
||||
},
|
||||
),
|
||||
("login", Kind::Login { code: "12345678" }),
|
||||
(
|
||||
"new-device",
|
||||
Kind::NewDevice {
|
||||
device: "Linux Desktop · пример",
|
||||
},
|
||||
),
|
||||
] {
|
||||
let email = render(origin, kind)?;
|
||||
std::fs::write(directory.join(format!("{name}.html")), email.html)?;
|
||||
std::fs::write(directory.join(format!("{name}.txt")), email.text)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
80
hub/src/main.rs
Normal file
80
hub/src/main.rs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
use std::{path::PathBuf, sync::Arc, time::Instant};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use vnox_hub::{config::Config, database, identity::Issuer, mail, web};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| "vnox_hub=info".into()),
|
||||
)
|
||||
.init();
|
||||
let args = std::env::args().skip(1).collect::<Vec<_>>();
|
||||
if args == ["--help"] {
|
||||
println!(
|
||||
"vnox-hub [--check-smtp | --render-email-preview DIRECTORY]\nConfiguration is read from the protected service environment. No send-email CLI is exposed."
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let config = Config::from_env()?;
|
||||
if args == ["--check-smtp"] {
|
||||
let smtp = config.smtp.as_ref().context("SMTP is not configured")?;
|
||||
mail::Mailer::new(smtp)?.check_connection().await?;
|
||||
println!("SMTP TLS and authentication verified; no email was sent.");
|
||||
return Ok(());
|
||||
}
|
||||
if args
|
||||
.first()
|
||||
.is_some_and(|arg| arg == "--render-email-preview")
|
||||
&& args.len() == 2
|
||||
{
|
||||
mail::templates::write_previews(&PathBuf::from(&args[1]), &config.origin)?;
|
||||
println!(
|
||||
"Generated three HTML/plain-text previews with dummy credentials; no email was sent."
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if !args.is_empty() {
|
||||
bail!("unknown arguments; use --help");
|
||||
}
|
||||
let issuer = Issuer::load_or_create(&config.data_dir)?;
|
||||
let database = database::open(&config.data_dir, &issuer).await?;
|
||||
// Validate configured SMTP eagerly without making startup depend on the
|
||||
// availability of an external provider. There is no public mail endpoint.
|
||||
if let Some(smtp) = &config.smtp {
|
||||
mail::Mailer::new(smtp)?;
|
||||
}
|
||||
let state = Arc::new(web::HubState {
|
||||
database,
|
||||
issuer,
|
||||
smtp_configured: config.smtp.is_some(),
|
||||
started: Instant::now(),
|
||||
});
|
||||
let listener = tokio::net::TcpListener::bind(config.bind)
|
||||
.await
|
||||
.context("binding Hub listener")?;
|
||||
tracing::info!(address = %listener.local_addr()?, "Vnox Hub foundation listening");
|
||||
axum::serve(listener, web::router(state.clone()))
|
||||
.with_graceful_shutdown(shutdown())
|
||||
.await
|
||||
.context("serving Hub HTTP")?;
|
||||
state.database.close().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn shutdown() {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
if let Ok(mut terminate) = signal(SignalKind::terminate()) {
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => {},
|
||||
_ = terminate.recv() => {},
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
}
|
||||
121
hub/src/web.rs
Normal file
121
hub/src/web.rs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
use axum::{
|
||||
Json, Router,
|
||||
body::Body,
|
||||
extract::State,
|
||||
http::{HeaderValue, Request, StatusCode},
|
||||
middleware::{self, Next},
|
||||
response::{Html, Response},
|
||||
routing::get,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::identity::Issuer;
|
||||
|
||||
pub struct HubState {
|
||||
pub database: SqlitePool,
|
||||
pub issuer: Issuer,
|
||||
pub smtp_configured: bool,
|
||||
pub started: Instant,
|
||||
}
|
||||
|
||||
pub fn router(state: Arc<HubState>) -> Router {
|
||||
Router::new()
|
||||
.route("/", get(index))
|
||||
.route("/health", get(health))
|
||||
.route("/ready", get(ready))
|
||||
.route("/version", get(version))
|
||||
.route("/v1/info", get(info))
|
||||
.route("/assets/vnox-mark.svg", get(logo))
|
||||
.route("/assets/vnox-mark.png", get(logo_png))
|
||||
.fallback(|| async { (StatusCode::NOT_FOUND, Json(json!({"error": "not_found"}))) })
|
||||
.layer(middleware::from_fn(headers))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
async fn health() -> Json<Value> {
|
||||
Json(json!({"status": "ok", "service": "vnox-hub"}))
|
||||
}
|
||||
|
||||
async fn ready(State(state): State<Arc<HubState>>) -> (StatusCode, Json<Value>) {
|
||||
match sqlx::query_scalar::<_, i64>("SELECT 1")
|
||||
.fetch_one(&state.database)
|
||||
.await
|
||||
{
|
||||
Ok(1) => (
|
||||
StatusCode::OK,
|
||||
Json(json!({"status": "ready", "database": "ready", "issuer": "loaded"})),
|
||||
),
|
||||
_ => (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
Json(json!({"status": "not_ready"})),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
async fn version() -> Json<Value> {
|
||||
Json(json!({
|
||||
"service": "vnox-hub",
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"api_version": 1,
|
||||
"stage": "foundation"
|
||||
}))
|
||||
}
|
||||
|
||||
async fn info(State(state): State<Arc<HubState>>) -> Json<Value> {
|
||||
Json(json!({
|
||||
"service": "vnox-hub",
|
||||
"stage": "foundation",
|
||||
"issuer_id": state.issuer.id,
|
||||
"issuer_public_key": state.issuer.public_key,
|
||||
"uptime_seconds": state.started.elapsed().as_secs(),
|
||||
"smtp": {"configured": state.smtp_configured, "public_send_endpoint": false},
|
||||
"capabilities": {
|
||||
"email_auth": "not_enabled",
|
||||
"github_auth": "not_enabled",
|
||||
"server_registry": "not_enabled",
|
||||
"friends": "not_enabled",
|
||||
"direct_messages": "not_enabled",
|
||||
"marketplace": "not_enabled"
|
||||
},
|
||||
"retention_plan": {"dm_days": 7, "attachment_days": 4, "attachment_max_bytes": 20000000}
|
||||
}))
|
||||
}
|
||||
|
||||
async fn logo() -> ([(&'static str, &'static str); 1], &'static str) {
|
||||
(
|
||||
[("content-type", "image/svg+xml; charset=utf-8")],
|
||||
include_str!("../assets/vnox-mark.svg"),
|
||||
)
|
||||
}
|
||||
|
||||
async fn logo_png() -> ([(&'static str, &'static str); 1], &'static [u8]) {
|
||||
(
|
||||
[("content-type", "image/png")],
|
||||
include_bytes!("../assets/vnox-mark.png"),
|
||||
)
|
||||
}
|
||||
|
||||
async fn index() -> Html<&'static str> {
|
||||
Html(include_str!("../assets/index.html"))
|
||||
}
|
||||
|
||||
async fn headers(request: Request<Body>, next: Next) -> Response {
|
||||
let mut response = next.run(request).await;
|
||||
for (name, value) in [
|
||||
("cache-control", "no-store"),
|
||||
("x-content-type-options", "nosniff"),
|
||||
("referrer-policy", "no-referrer"),
|
||||
(
|
||||
"content-security-policy",
|
||||
"default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; frame-ancestors 'none'",
|
||||
),
|
||||
] {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(name, HeaderValue::from_static(value));
|
||||
}
|
||||
response
|
||||
}
|
||||
210
hub/tests/foundation.rs
Normal file
210
hub/tests/foundation.rs
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
use std::{collections::HashMap, sync::Arc, time::Instant};
|
||||
|
||||
use axum::{
|
||||
body::Body,
|
||||
http::{Request, StatusCode},
|
||||
};
|
||||
use tempfile::TempDir;
|
||||
use tower::ServiceExt;
|
||||
use vnox_hub::{
|
||||
config::Config,
|
||||
database,
|
||||
identity::Issuer,
|
||||
web::{self, HubState},
|
||||
};
|
||||
|
||||
fn private_directory() -> TempDir {
|
||||
let directory = TempDir::new().unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
}
|
||||
directory
|
||||
}
|
||||
|
||||
fn config(values: &[(&str, &str)]) -> anyhow::Result<Config> {
|
||||
let values = values
|
||||
.iter()
|
||||
.map(|(key, value)| (*key, *value))
|
||||
.collect::<HashMap<_, _>>();
|
||||
Config::from_lookup(|key| values.get(key).map(|value| (*value).to_owned()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_public_binding_and_untrusted_origins() {
|
||||
assert!(config(&[("HUB_BIND", "0.0.0.0:18000")]).is_err());
|
||||
for origin in [
|
||||
"http://central.example",
|
||||
"https://a.example/path",
|
||||
"https://a.example?token=x",
|
||||
"https://user:secret@a.example",
|
||||
"https://a.example/#fragment",
|
||||
] {
|
||||
assert!(config(&[("PUBLIC_BASE_URL", origin)]).is_err(), "{origin}");
|
||||
}
|
||||
assert!(config(&[("PUBLIC_BASE_URL", "https://central.example")]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_incomplete_smtp_config_instead_of_silently_disabling_mail() {
|
||||
assert!(config(&[("SMTP_PASSWORD", "not-a-real-secret")]).is_err());
|
||||
assert!(config(&[("SMTP_HOST", "smtp.example"), ("SMTP_USER", "test")]).is_err());
|
||||
assert!(config(&[("SMTP_HOST", "smtp.example"), ("SMTP_PORT", "0")]).is_err());
|
||||
assert!(config(&[("SMTP_HOST", "smtp://smtp.example")]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issuer_identity_is_stable_and_private() {
|
||||
let directory = private_directory();
|
||||
let first = Issuer::load_or_create(directory.path()).unwrap();
|
||||
let second = Issuer::load_or_create(directory.path()).unwrap();
|
||||
assert_eq!(first.id, second.id);
|
||||
assert_eq!(first.public_key, second.public_key);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let path = directory.path().join("issuer.json");
|
||||
assert_eq!(
|
||||
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
|
||||
0o600
|
||||
);
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
assert!(Issuer::load_or_create(directory.path()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_identity_does_not_get_replaced_with_a_new_issuer() {
|
||||
let directory = private_directory();
|
||||
let issuer = Issuer::load_or_create(directory.path()).unwrap();
|
||||
let path = directory.path().join("issuer.json");
|
||||
let original = std::fs::read_to_string(&path).unwrap();
|
||||
std::fs::write(&path, original.replace(&issuer.public_key, &"0".repeat(64))).unwrap();
|
||||
assert!(Issuer::load_or_create(directory.path()).is_err());
|
||||
assert!(
|
||||
std::fs::read_to_string(path)
|
||||
.unwrap()
|
||||
.contains(&"0".repeat(64))
|
||||
);
|
||||
}
|
||||
|
||||
async fn state() -> (TempDir, Arc<HubState>) {
|
||||
let directory = private_directory();
|
||||
let issuer = Issuer::load_or_create(directory.path()).unwrap();
|
||||
let pool = database::open(directory.path(), &issuer).await.unwrap();
|
||||
(
|
||||
directory,
|
||||
Arc::new(HubState {
|
||||
database: pool,
|
||||
issuer,
|
||||
smtp_configured: true,
|
||||
started: Instant::now(),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn database_migrations_persist_and_refuse_a_different_issuer() {
|
||||
let (directory, state) = state().await;
|
||||
let tables: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN ('accounts','devices','servers')")
|
||||
.fetch_one(&state.database).await.unwrap();
|
||||
assert_eq!(tables, 3);
|
||||
state.database.close().await;
|
||||
let pool = database::open(directory.path(), &state.issuer)
|
||||
.await
|
||||
.unwrap();
|
||||
pool.close().await;
|
||||
let other_dir = private_directory();
|
||||
let other = Issuer::load_or_create(other_dir.path()).unwrap();
|
||||
assert!(database::open(directory.path(), &other).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn readiness_reflects_database_failure() {
|
||||
let (_directory, state) = state().await;
|
||||
let app = web::router(state.clone());
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/ready")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
state.database.close().await;
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/ready")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn capabilities_and_routes_do_not_pretend_authentication_is_ready() {
|
||||
let (_directory, state) = state().await;
|
||||
let app = web::router(state);
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/v1/info")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.headers()["cache-control"], "no-store");
|
||||
let body = axum::body::to_bytes(response.into_body(), 8192)
|
||||
.await
|
||||
.unwrap();
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
for capability in [
|
||||
"email_auth",
|
||||
"github_auth",
|
||||
"server_registry",
|
||||
"friends",
|
||||
"direct_messages",
|
||||
"marketplace",
|
||||
] {
|
||||
assert_eq!(value["capabilities"][capability], "not_enabled");
|
||||
}
|
||||
assert_eq!(value["smtp"]["public_send_endpoint"], false);
|
||||
assert!(value.get("secret_key").is_none());
|
||||
for path in [
|
||||
"/v1/auth/email/start",
|
||||
"/v1/servers/register",
|
||||
"/v1/mail/send",
|
||||
] {
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri(path)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn refuses_a_world_readable_data_directory() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let directory = private_directory();
|
||||
std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert!(Issuer::load_or_create(directory.path()).is_err());
|
||||
assert!(!directory.path().join("issuer.json").exists());
|
||||
}
|
||||
109
hub/tests/mail.rs
Normal file
109
hub/tests/mail.rs
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
use vnox_hub::{
|
||||
config::{SmtpConfig, parse_origin},
|
||||
mail::{
|
||||
Mailer,
|
||||
templates::{self, Kind},
|
||||
},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn mail_links_stay_on_configured_origin_and_escape_dynamic_content() {
|
||||
let origin = parse_origin("https://central.loki-code.dev").unwrap();
|
||||
let email = templates::render(
|
||||
&origin,
|
||||
Kind::Verify {
|
||||
token: "abc\"&<https://evil.example>",
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
email
|
||||
.html
|
||||
.contains("https://central.loki-code.dev/verify-email?token=")
|
||||
);
|
||||
assert!(!email.html.contains("href=\"https://evil.example"));
|
||||
assert!(!email.html.contains("token=abc\""));
|
||||
let email = templates::render(
|
||||
&origin,
|
||||
Kind::NewDevice {
|
||||
device: "<img src=x onerror=evil()>",
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(email.html.contains("<img src=x onerror=evil()>"));
|
||||
assert!(!email.html.contains("<img src=x"));
|
||||
assert!(email.text.contains("<img src=x onerror=evil()>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_codes_are_validated_and_rendered_in_both_message_parts() {
|
||||
let origin = parse_origin("https://central.loki-code.dev").unwrap();
|
||||
for code in ["123", "1234567x", "123456789", "12345678"] {
|
||||
assert!(templates::render(&origin, Kind::Login { code }).is_err());
|
||||
}
|
||||
let email = templates::render(&origin, Kind::Login { code: "12345678" }).unwrap();
|
||||
assert!(email.html.contains("12345678"));
|
||||
assert!(email.text.contains("12345678"));
|
||||
assert!(email.html.contains("10 минут"));
|
||||
assert!(email.subject.starts_with("Vnox"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previews_are_three_safe_html_and_text_pairs() {
|
||||
let directory = tempfile::TempDir::new().unwrap();
|
||||
let origin = parse_origin("https://central.loki-code.dev").unwrap();
|
||||
templates::write_previews(directory.path(), &origin).unwrap();
|
||||
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 6);
|
||||
let verify = std::fs::read_to_string(directory.path().join("verify.html")).unwrap();
|
||||
assert!(verify.contains("DUMMY_PREVIEW_NOT_A_REAL_TOKEN"));
|
||||
assert!(!verify.contains("LoVisual"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smtp_setup_rejects_invalid_mailbox_and_tls_hostname() {
|
||||
let config = SmtpConfig {
|
||||
host: "smtp.example".into(),
|
||||
port: 587,
|
||||
user: "".into(),
|
||||
password: "".into(),
|
||||
from: "bad\r\nInjected: x".into(),
|
||||
};
|
||||
assert!(Mailer::new(&config).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn smtp_probe_requires_tls_and_never_falls_back_to_cleartext_authentication() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
socket
|
||||
.write_all(b"220 localhost ESMTP test\r\n")
|
||||
.await
|
||||
.unwrap();
|
||||
let mut buffer = [0; 2048];
|
||||
let len = socket.read(&mut buffer).await.unwrap();
|
||||
let first = String::from_utf8_lossy(&buffer[..len]).to_string();
|
||||
socket
|
||||
.write_all(b"250-localhost\r\n250 AUTH PLAIN LOGIN\r\n")
|
||||
.await
|
||||
.unwrap();
|
||||
let second = socket.read(&mut buffer).await.unwrap_or(0);
|
||||
(first, buffer[..second].to_vec())
|
||||
});
|
||||
let mailer = Mailer::new(&SmtpConfig {
|
||||
host: "localhost".into(),
|
||||
port,
|
||||
user: "user".into(),
|
||||
password: "test-password".into(),
|
||||
from: "Vnox <noreply@example.com>".into(),
|
||||
})
|
||||
.unwrap();
|
||||
assert!(mailer.check_connection().await.is_err());
|
||||
let (first, second) = server.await.unwrap();
|
||||
assert!(first.to_uppercase().starts_with("EHLO"));
|
||||
let commands = String::from_utf8_lossy(&second).to_uppercase();
|
||||
assert!(!commands.contains("AUTH"));
|
||||
assert!(!commands.contains("MAIL FROM"));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue