Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@ Watari is a Rust/Axum web GUI that sits in front of [rustypaste](https://github.
- `config.rs` — `AppConfig::from_env()`; fails fast with a clear error if a required var is missing/invalid.
- `state.rs` — `AppState` (the Axum `State`), plus `FromRef` impls so `axum_extra`'s cookie `Key` and `axum_csrf`'s `CsrfConfig` can be extracted from it.
- `db.rs` — `sqlx` SQLite pool + typed query functions for `sessions`/`upload_log`. Uses the runtime query API (`sqlx::query`/`query_as`), not the `query!` macro, so there's no compile-time `DATABASE_URL` requirement.
- `session.rs` — the `UserSession` extractor (`FromRequestParts`): reads the `session_id` cookie, loads the session row, does best-effort silent OIDC token refresh, redirects to `/auth/login` on any failure. Also owns the `__oidc_state` cookie helpers (PKCE verifier/state/nonce, private/encrypted via `axum_extra::PrivateCookieJar`).
- `session.rs` — the `UserSession` extractor (`FromRequestParts`): reads the `session_id` cookie, loads the session row, does best-effort silent OIDC token refresh, redirects to `/auth/login` on any failure. `Option<UserSession>` (via `OptionalFromRequestParts`) never redirects, for public pages that still want the signed-in sidebar. Also owns the `__oidc_state` cookie helpers (PKCE verifier/state/nonce, private/encrypted via `axum_extra::PrivateCookieJar`).
- `oidc.rs` — OIDC discovery + the `/auth/login`, `/auth/callback`, `/auth/logout` handlers. Deliberately does **not** store the built `openidconnect::CoreClient` anywhere — oauth2 5.x's typestate-encoded endpoint generics make that type impractical to name in a struct field, so it's cheaply rebuilt from plain fields (`ClientId`, discovered `ProviderMetadata`, etc.) wherever needed.
- `token_map.rs` — loads `token-bindings.yaml`, resolves each `env_var`, and resolves a user's OIDC groups to a `TokenBinding` (first matching rule wins). `TokenBinding::is_admin()` is defined as "has the `delete` permission".
- `rustypaste.rs` — the rustypaste HTTP client. Field names/headers here were confirmed against rustypaste's actual source, not guessed — see the "rustypaste's real API" doc comment at the top of the file before changing it.
- `csrf.rs` / `csp.rs` / `ratelimit.rs` — `axum_csrf` verification helper, static CSP header middleware, and `tower_governor` layer factories.
- `templates.rs` — `Tpl<T>`, a tiny `IntoResponse` wrapper around `askama::Template::render()` (replaces the `askama_axum` crate, which no longer exists as of askama ≥0.13), and `Layout`, the struct every page template embeds as a `layout: Layout` field for the data `base.html` needs (csrf token, pbkdf2 iterations, user email, admin flag).
- `routes/` — `pages.rs` (home overview at `/home`, dashboard, upload/paste/shorten form pages; the Home diagram in `templates/home.html` is hand-aligned box-drawing text, so keep columns intact when editing it), `api.rs` (the mutating `/api/*` proxy endpoints + pagination), `decrypt.rs` (public, SSRF-guarded), `admin.rs` (token bindings viewer).
- `routes/` — `pages.rs` (home overview at `/home`, dashboard, upload/paste/shorten form pages; the Home diagram in `templates/home.html` is hand-aligned box-drawing text, so keep columns intact when editing it), `api.rs` (the mutating `/api/*` proxy endpoints + pagination), `decrypt.rs` (public, SSRF-guarded; `/decrypt` is also the "Decrypt" sidebar tab, and `share_link` builds the `/decrypt?url=…` link shown after encrypted uploads), `admin.rs` (token bindings viewer).

## Known deviations from `watari.md`

Expand Down
32 changes: 27 additions & 5 deletions src/routes/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,29 @@ struct FlashTemplate {
ok: bool,
message: String,
url: Option<String>,
/// Adds the "how to open password-protected content" explanation.
protected: bool,
}

fn flash_ok(message: impl Into<String>, url: String) -> Response {
/// Success flash after an upload/paste/shorten. For encrypted content the link
/// shown is Watari's decrypt page (what recipients should open), not the raw
/// rustypaste URL, which only serves ciphertext.
fn flash_ok(
state: &AppState,
message: impl Into<String>,
url: String,
encrypted: bool,
) -> Response {
let url = if encrypted {
super::decrypt::share_link(&state.config.app_base_url, &url)
} else {
url
};
Tpl(FlashTemplate {
ok: true,
message: message.into(),
url: Some(url),
protected: encrypted,
})
.into_response()
}
Expand All @@ -44,6 +60,7 @@ fn flash_err_status(status: StatusCode, message: impl Into<String>) -> Response
ok: false,
message: message.into(),
url: None,
protected: false,
}),
)
.into_response()
Expand Down Expand Up @@ -257,7 +274,12 @@ pub async fn upload(
&parsed.expire,
)
.await;
flash_ok(format!("Uploaded successfully ({size})."), url)
flash_ok(
&state,
format!("Uploaded successfully ({size})."),
url,
encrypted,
)
}
Err(e) => flash_err(upstream_message(e)),
}
Expand Down Expand Up @@ -331,7 +353,7 @@ pub async fn paste(
&parsed.expire,
)
.await;
flash_ok("Pasted successfully.", url)
flash_ok(&state, "Pasted successfully.", url, encrypted)
}
Err(e) => flash_err(upstream_message(e)),
}
Expand Down Expand Up @@ -386,7 +408,7 @@ pub async fn shorten(
&parsed.expire,
)
.await;
flash_ok("Shortened successfully.", short_url)
flash_ok(&state, "Shortened successfully.", short_url, false)
}
Err(e) => flash_err(upstream_message(e)),
};
Expand Down Expand Up @@ -424,7 +446,7 @@ pub async fn shorten(
&parsed.expire,
)
.await;
flash_ok("Shortened successfully.", url)
flash_ok(&state, "Shortened successfully.", url, encrypted)
}
Err(e) => flash_err(upstream_message(e)),
}
Expand Down
67 changes: 57 additions & 10 deletions src/routes/decrypt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,25 @@ use axum_csrf::CsrfToken;
use serde::Deserialize;

use crate::error::AppError;
use crate::session::UserSession;
use crate::state::AppState;
use crate::templates::{Layout, Tpl};

/// The link to share for password-protected content: Watari's decrypt page
/// with the rustypaste URL prefilled, so recipients only type the password.
pub fn share_link(app_base_url: &str, paste_url: &str) -> String {
let encoded: String = url::form_urlencoded::byte_serialize(paste_url.as_bytes()).collect();
format!(
"{}/decrypt?url={encoded}",
app_base_url.trim_end_matches('/')
)
}

#[derive(Deserialize)]
pub struct DecryptPageQuery {
url: Option<String>,
}

#[derive(Deserialize)]
pub struct DecryptQuery {
url: String,
Expand All @@ -18,29 +34,37 @@ pub struct DecryptQuery {
#[template(path = "decrypt.html")]
struct DecryptTemplate {
layout: Layout,
/// Prefills the link field; empty when opened from the sidebar tab.
url: String,
}

/// `GET /decrypt?url=...` — intentionally unauthenticated (watari.md §9.3) so
/// `GET /decrypt[?url=...]` — intentionally unauthenticated (watari.md §9.3) so
/// recipients without an SSO account can decrypt shared content. Renders the
/// password prompt; actual bytes are fetched client-side from `/decrypt/fetch`.
/// link + password form; actual bytes are fetched client-side from
/// `/decrypt/fetch`. Signed-in users (it's also a sidebar tab) keep their
/// normal sidebar.
pub async fn page(
State(state): State<AppState>,
session: Option<UserSession>,
csrf_token: CsrfToken,
Query(query): Query<DecryptQuery>,
Query(query): Query<DecryptPageQuery>,
) -> Response {
let csrf = match csrf_token.authenticity_token() {
Ok(t) => t,
Err(e) => {
return AppError::Internal(anyhow::anyhow!("csrf token error: {e}")).into_response();
}
let layout = match &session {
Some(session) => super::pages::layout_for(&state, &csrf_token, session),
None => csrf_token
.authenticity_token()
.map(|csrf| Layout::anonymous(csrf, state.config.pbkdf2_iterations))
.map_err(|e| anyhow::anyhow!("csrf token error: {e}")),
};
let layout = match layout {
Ok(l) => l,
Err(e) => return AppError::Internal(e).into_response(),
};
let layout = Layout::anonymous(csrf, state.config.pbkdf2_iterations);
(
csrf_token,
Tpl(DecryptTemplate {
layout,
url: query.url,
url: query.url.unwrap_or_default(),
}),
)
.into_response()
Expand Down Expand Up @@ -90,3 +114,26 @@ pub async fn fetch(State(state): State<AppState>, Query(query): Query<DecryptQue

([(header::CONTENT_TYPE, "application/octet-stream")], bytes).into_response()
}

#[cfg(test)]
mod tests {
use super::share_link;

#[test]
fn share_link_encodes_the_paste_url() {
assert_eq!(
share_link(
"https://watari.example.com/",
"https://paste.example.com/safe-toad.txt?x=1&y=2"
),
"https://watari.example.com/decrypt?url=https%3A%2F%2Fpaste.example.com%2Fsafe-toad.txt%3Fx%3D1%26y%3D2"
);
assert_eq!(
share_link(
"https://watari.example.com",
"https://paste.example.com/a.txt"
),
"https://watari.example.com/decrypt?url=https%3A%2F%2Fpaste.example.com%2Fa.txt"
);
}
}
20 changes: 16 additions & 4 deletions src/routes/pages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ pub struct UploadRowView {
pub id: String,
pub display_name: String,
pub paste_url: String,
/// What to share/open: the Watari decrypt page for encrypted items (the
/// raw rustypaste URL only serves ciphertext), `paste_url` otherwise.
pub share_url: String,
pub encrypted: bool,
/// RFC 3339 (UTC); `static/app.js` turns it into "14:05" / "3 days ago" in
/// the viewer's timezone.
Expand Down Expand Up @@ -94,20 +97,29 @@ pub async fn load_section_page(
SectionPage {
has_more: db_rows.len() as i64 == PAGE_SIZE,
next_cursor: db_rows.last().map(|r| r.created_at),
rows: db_rows.iter().map(UploadRowView::from).collect(),
rows: db_rows
.iter()
.map(|row| UploadRowView::new(row, &state.config.app_base_url))
.collect(),
}
}

impl From<&db::UploadLogRow> for UploadRowView {
fn from(row: &db::UploadLogRow) -> Self {
impl UploadRowView {
fn new(row: &db::UploadLogRow, app_base_url: &str) -> Self {
let created_at_iso = OffsetDateTime::from_unix_timestamp(row.created_at)
.ok()
.and_then(|t| t.format(&Rfc3339).ok())
.unwrap_or_default();
let share_url = if row.encrypted {
super::decrypt::share_link(app_base_url, &row.paste_url)
} else {
row.paste_url.clone()
};
Self {
id: row.id.clone(),
display_name: row.display_name.clone(),
paste_url: row.paste_url.clone(),
share_url,
encrypted: row.encrypted,
created_at_iso,
}
Expand Down Expand Up @@ -146,7 +158,7 @@ fn can_delete(state: &AppState, token_id: &str) -> bool {
.unwrap_or(false)
}

fn layout_for(
pub(crate) fn layout_for(
state: &AppState,
token: &CsrfToken,
session: &UserSession,
Expand Down
20 changes: 19 additions & 1 deletion src/session.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use axum::extract::FromRequestParts;
use axum::extract::{FromRequestParts, OptionalFromRequestParts};
use axum::http::request::Parts;
use axum::response::{IntoResponse, Redirect, Response};
use axum_extra::extract::cookie::{Cookie, CookieJar, PrivateCookieJar, SameSite};
Expand Down Expand Up @@ -153,3 +153,21 @@ impl FromRequestParts<AppState> for UserSession {
})
}
}

/// `Option<UserSession>`: for public pages (e.g. `/decrypt`) that show the
/// signed-in sidebar when a valid session exists but must not redirect
/// anonymous visitors to login.
impl OptionalFromRequestParts<AppState> for UserSession {
type Rejection = std::convert::Infallible;

async fn from_request_parts(
parts: &mut Parts,
state: &AppState,
) -> Result<Option<Self>, Self::Rejection> {
Ok(
<UserSession as FromRequestParts<AppState>>::from_request_parts(parts, state)
.await
.ok(),
)
}
}
5 changes: 5 additions & 0 deletions static/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,11 @@ button.copy-btn {
}

.flash-ok { border-color: var(--ok); }
.flash-hint { font-size: 0.9rem; opacity: 0.85; line-height: 1.5; }

.page-intro { max-width: 42rem; line-height: 1.55; opacity: 0.85; }
#decrypt-result { margin-top: 1rem; }
#decrypt-result pre { white-space: pre-wrap; word-break: break-word; }
.flash-error { border-color: var(--danger); }

.flash-url {
Expand Down
Loading
Loading