OXYGENHUB

Coverage / crates/hub/src/web/security_txt.rs 98.1%

101 of 103 lines run, 26 of 44 functions · run #471 on main · run missed

1
//! `security.txt` (RFC 9116, oxygenhub#224): where to report a
2
//! vulnerability in this hub. A site administrator sets the contact and,
3
//! if there is one, a policy page under Administration; until a contact is
4
//! set there is no file (404). `Expires` is always just under a year ahead,
5
//! as the RFC asks, so the file never goes stale.
6
7
use super::settings::csrf;
8
use super::{Error, Page, Shell};
9
use crate::auth::Viewer;
10
use crate::db::{self, accounts};
11
use crate::Shared;
12
use axum::extract::{Form, State};
13
use axum::http::{header, StatusCode};
14
use axum::response::{IntoResponse, Response};
15
use serde::Deserialize;
16
17
const CONTACT: &str = "security_contact";
18
const POLICY: &str = "security_policy";
19
const EMAIL: &str = "security_email";
20
const PAGE: &str = "security_page";
21
/// The longest page text kept.
22
const MAX_PAGE: usize = 20_000;
23
24
/// What `/security-contact` says until an administrator writes their own
25
/// (oxygenhub#230). It makes no promises on the site's behalf.
26
pub const DEFAULT_PAGE: &str = "If you think you have found a security problem in this hub, please tell us privately rather than in a public issue, proposal or comment.\n\n\
27
Please include:\n\n\
28
- what you found, and where (the page, the API call, the repository if one is involved);\n\
29
- how to reproduce it, step by step;\n\
30
- what you think someone could do with it.\n\n\
31
While you look, please do not read or change other people's data beyond what you need to show the problem, do not run tests that slow the service down for others, and give us a fair chance to fix it before you tell anyone else.\n";
32
/// How far ahead `Expires` is: under a year (RFC 9116 §2.5.5).
33
const EXPIRES_MS: i64 = 360 * 24 * 60 * 60_000;
34
35
/// The reporting address and the page text (empty when unset).
3698×
pub async fn page_settings(app: &Shared) -> (String, String) {
37392×
    let get = |k| async move { accounts::setting(&app.db, k).await.ok().flatten().unwrap_or_default() };
3898×
    (get(EMAIL).await, get(PAGE).await)
3998×
}
40
41
#[derive(askama::Template)]
42
#[template(path = "security_contact.html")]
43
pub struct ContactPage {
44
    shell: Shell,
45
    email: String,
46
    /// The page text as HTML, sanitised by the Markdown renderer.
47
    body_html: String,
48
}
49
50
/// `GET /security-contact`: how to report a security problem (oxygenhub#230).
512×
pub async fn contact_page(State(app): State<Shared>, viewer: Viewer) -> Page<ContactPage> {
522×
    let shell = Shell::new(&app, "/security-contact", &viewer);
532×
    let (mut email, text) = page_settings(&app).await;
54
    // No address of its own: security.txt's, when that is an email.
552×
    if email.is_empty() {
561×
        let (contact, _) = settings(&app).await;
571×
        email = contact_uri(&contact).and_then(|u| u.strip_prefix("mailto:").map(String::from)).unwrap_or_default();
581×
    }
592×
    let text = if text.trim().is_empty() { DEFAULT_PAGE.to_string() } else { text };
602×
    Page(ContactPage { shell, email, body_html: crate::render::markdown::render(&text, "", "") })
612×
}
62
63
/// The saved contact and policy (empty when unset).
64101×
pub async fn settings(app: &Shared) -> (String, String) {
65404×
    let get = |k| async move { accounts::setting(&app.db, k).await.ok().flatten().unwrap_or_default() };
66101×
    (get(CONTACT).await, get(POLICY).await)
67101×
}
68
69
/// A contact as the file gives it: an email address becomes a `mailto:`
70
/// URI; an https or mailto URI is kept. `None` for anything else.
7126×
pub fn contact_uri(contact: &str) -> Option<String> {
7226×
    let c = contact.trim();
73350×
    if c.is_empty() || c.chars().any(|ch| ch.is_whitespace() || ch.is_control()) {
746×
        return None;
7520×
    }
7620×
    if c.starts_with("https://") || c.starts_with("mailto:") {
773×
        return Some(c.to_string());
7817×
    }
7917×
    let (user, domain) = c.split_once('@')?;
8012×
    (!user.is_empty() && domain.contains('.') && !domain.contains('@') && !c.contains(':')).then(|| format!("mailto:{c}"))
8126×
}
82
83
/// The file's text, for a contact and policy, at `now_ms`.
847×
pub fn text(base_url: &str, contact: &str, policy: &str, now_ms: i64) -> Option<String> {
857×
    let contact = contact_uri(contact)?;
864×
    let expires = crate::render::time::rfc3339((now_ms + EXPIRES_MS) as u64);
874×
    let base = base_url.trim_end_matches('/');
884×
    let mut out = format!("Contact: {contact}\nExpires: {expires}\n");
894×
    if !policy.trim().is_empty() {
903×
        out.push_str(&format!("Policy: {}\n", policy.trim()));
913×
    }
924×
    out.push_str(&format!("Preferred-Languages: en\nCanonical: {base}/.well-known/security.txt\n"));
934×
    Some(out)
947×
}
95
96
/// `GET /.well-known/security.txt` and `/security.txt`.
974×
pub async fn serve(State(app): State<Shared>) -> Response {
984×
    let (contact, policy) = settings(&app).await;
994×
    match text(app.config.base_url(), &contact, &policy, db::now_ms()) {
1002×
        Some(t) => ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], t).into_response(),
1012×
        None => (StatusCode::NOT_FOUND, "This hub has no security contact set.\n").into_response(),
102
    }
1034×
}
104
105
#[derive(Deserialize)]
106
pub struct SecurityForm {
107
    #[serde(rename = "_csrf")]
108
    csrf_token: String,
109
    #[serde(default)]
110
    contact: String,
111
    #[serde(default)]
112
    policy: String,
113
    /// Where reports go, shown on /security-contact.
114
    #[serde(default)]
115
    email: String,
116
    /// The page's text, Markdown; empty for the default.
117
    #[serde(default)]
118
    page: String,
119
}
120
121
/// `POST /admin/security`: the contact (an email address or https page)
122
/// and an optional https policy page; an empty contact takes the file down.
1238×
pub async fn save(State(app): State<Shared>, viewer: Viewer, Form(f): Form<SecurityForm>) -> Result<Page<super::admin::AdminPage>, Error> {
1248×
    let shell = Shell::new(&app, "/admin", &viewer);
1258×
    let me = super::admin::require_admin(&viewer, &shell)?;
1267×
    csrf(&viewer, &f.csrf_token, &shell)?;
1277×
    let (contact, policy) = (f.contact.trim(), f.policy.trim());
1287×
    if !contact.is_empty() && contact_uri(contact).is_none() {
1291×
        return Err(Error::bad(shell, "The contact is an email address or an https:// page."));
1306×
    }
1316×
    if !policy.is_empty() && (!policy.starts_with("https://") || policy.chars().any(char::is_whitespace)) {
1321×
        return Err(Error::bad(shell, "The policy is an https:// page, or empty."));
1335×
    }
1345×
    let (email, page) = (f.email.trim(), f.page.trim());
1355×
    if !email.is_empty() && contact_uri(email).is_none_or(|u| !u.starts_with("mailto:")) {
1361×
        return Err(Error::bad(shell, "The reporting address is an email address, or empty."));
1374×
    }
1384×
    if page.chars().count() > MAX_PAGE {
1390×
        return Err(Error::bad(shell, format!("The page text is at most {MAX_PAGE} characters.")));
1404×
    }
1414×
    let e = |e| Error::from_db(shell.clone(), e);
1424×
    accounts::set_setting(&app.db, CONTACT, contact).await.map_err(e)?;
1434×
    accounts::set_setting(&app.db, POLICY, policy).await.map_err(e)?;
1444×
    accounts::set_setting(&app.db, EMAIL, email).await.map_err(e)?;
1454×
    accounts::set_setting(&app.db, PAGE, page).await.map_err(e)?;
1464×
    accounts::audit(&app.db, Some(&me), "admin.security_contact", contact, policy).await.ok();
1474×
    let notice = if contact.is_empty() {
1481×
        "No security contact: /.well-known/security.txt is gone.".to_string()
149
    } else {
1503×
        "Security contact saved: /.well-known/security.txt names it.".to_string()
151
    };
1524×
    super::admin::admin_page(&app, shell, super::admin::AdminSection::SecurityContact, Some(notice)).await
1538×
}
154
155
#[cfg(test)]
156
mod tests {
157
    use super::*;
158
159
    #[test]
1601×
    fn contacts_become_uris_or_are_refused() {
1611×
        assert_eq!(contact_uri("[email protected]").as_deref(), Some("mailto:[email protected]"));
1621×
        assert_eq!(contact_uri(" https://example.org/report ").as_deref(), Some("https://example.org/report"));
1631×
        assert_eq!(contact_uri("mailto:[email protected]").as_deref(), Some("mailto:[email protected]"));
1647×
        for bad in ["", "http://example.org", "nobody", "a@b", "a [email protected]", "javascript:alert(1)", "[email protected]\nContact: evil"] {
1657×
            assert_eq!(contact_uri(bad), None, "{bad:?}");
166
        }
1671×
    }
168
169
    #[test]
1701×
    fn the_file_expires_under_a_year_ahead_and_is_canonical() {
1711×
        let now = 1_800_000_000_000; // 2027-01-15
1721×
        let t = text("https://hub.example/", "[email protected]", "https://hub.example/policy", now).unwrap();
1731×
        assert_eq!(
174
            t,
175
            "Contact: mailto:[email protected]\nExpires: 2028-01-10T08:00:00Z\nPolicy: https://hub.example/policy\n\
176
             Preferred-Languages: en\nCanonical: https://hub.example/.well-known/security.txt\n"
177
        );
1781×
        assert!(!text("https://hub.example", "[email protected]", "", now).unwrap().contains("Policy"));
1791×
        assert!(text("https://hub.example", "", "", now).is_none());
1801×
    }
181
}