From 3125fe3db4ad42eefaf4d842d5b5e5d811da56a9 Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Tue, 20 Oct 2026 10:50:50 +0200 Subject: [PATCH] feat(filter): filter by time span and date ranges --- CHANGELOG.md | 3 + README.md | 2 +- src/http.rs | 68 +++++++++++++++++++++ src/http/dmarc_reports.rs | 9 +++ src/http/mails.rs | 6 ++ src/http/summary.rs | 29 ++++----- src/http/tls_reports.rs | 12 ++++ ui/components/dashboard.js | 25 +------- ui/components/dmarc-reports.js | 16 +++-- ui/components/mails.js | 20 +++--- ui/components/tls-reports.js | 14 +++-- ui/style.js | 25 ++++++++ ui/utils.js | 108 +++++++++++++++++++++++++++++++++ 13 files changed, 278 insertions(+), 59 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1fa75af..e84f9ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ All notable changes to this project will be documented in this file. +## [Unreleased] +* Feature: Filter mails and reports by time span or custom date range (issues #82 and #32 by @FrauJulian). + ## [2.6.1] - 2026-10-18 * Fix: Flag DKIM auth only when no signature passes (fix for issue #85 by @FrauJulian). * Removed XML and JSON count from dashboard and added next update time. diff --git a/README.md b/README.md index 32dbb1a..9d27b2e 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ You can find more screenshots [here](screenshots/screenshots.md). - [x] Summary with charts for domains, organizations and passed/failed checks - [x] Filter charts summary by domain or time span - [x] Viewing of ranked sources/IPs by domain and report type -- [x] Viewing filtered lists of reports +- [x] Viewing filtered lists of reports (incl. time span or date range) - [x] Viewing of individual reports - [x] Export reports as XML or JSON documents - [x] List all mails in the IMAP inbox diff --git a/src/http.rs b/src/http.rs index ecdcfc2..0099f01 100644 --- a/src/http.rs +++ b/src/http.rs @@ -23,6 +23,7 @@ use axum::{Router, extract::State}; use axum_server::Handle; use base64::Engine; use base64::engine::general_purpose::STANDARD; +use chrono::{TimeDelta, Utc}; use futures::StreamExt; use rustls_acme::AcmeConfig; use rustls_acme::caches::DirCache; @@ -258,3 +259,70 @@ async fn health() -> HeaderMap { headers.insert(CACHE_CONTROL, HeaderValue::from_static("no-cache")); headers } + +/// UNIX seconds, missing bounds are unlimited. +#[derive(Clone, Copy, Default)] +struct TimeRange { + from: Option, + to: Option, +} + +impl TimeRange { + /// Invalid time spans are ignored, the stricter lower bound wins. + fn new(time_span: Option, from: Option, to: Option) -> Self { + let threshold = time_span + .and_then(|hours| i64::try_from(hours).ok()) + .filter(|hours| *hours > 0) + .and_then(TimeDelta::try_hours) + .and_then(|delta| Utc::now().checked_sub_signed(delta)) + .map(|t| t.timestamp()); + Self { + from: threshold.max(from), + to, + } + } + + fn overlaps(&self, begin: i64, end: i64) -> bool { + self.from.is_none_or(|from| end >= from) && self.to.is_none_or(|to| begin <= to) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn time_range_time_span() { + assert!(TimeRange::new(None, None, None).from.is_none()); + assert!(TimeRange::new(Some(0), None, None).from.is_none()); + assert!(TimeRange::new(Some(u64::MAX), None, None).from.is_none()); + assert!( + TimeRange::new(Some(i64::MAX as u64), None, None) + .from + .is_none() + ); + let from = TimeRange::new(Some(24), None, None).from.unwrap(); + let expected = (Utc::now() - TimeDelta::hours(24)).timestamp(); + assert!((expected - from).abs() < 5); + } + + #[test] + fn time_range_from_to() { + assert_eq!( + TimeRange::new(Some(24), Some(0), None).from, + TimeRange::new(Some(24), None, None).from + ); + assert_eq!( + TimeRange::new(Some(24), Some(i64::MAX), None).from, + Some(i64::MAX) + ); + let range = TimeRange::new(None, Some(100), Some(200)); + assert!(range.overlaps(150, 150)); + assert!(range.overlaps(50, 100)); + assert!(range.overlaps(200, 300)); + assert!(range.overlaps(50, 300)); + assert!(!range.overlaps(50, 99)); + assert!(!range.overlaps(201, 300)); + assert!(TimeRange::default().overlaps(i64::MIN, i64::MIN)); + } +} diff --git a/src/http/dmarc_reports.rs b/src/http/dmarc_reports.rs index 0b503ae..20b6c66 100644 --- a/src/http/dmarc_reports.rs +++ b/src/http/dmarc_reports.rs @@ -106,6 +106,9 @@ pub struct ReportFilters { domain: Option, org: Option, ip: Option, + time_span: Option, + from: Option, + to: Option, } impl ReportFilters { @@ -138,11 +141,17 @@ pub async fn list_handler( // Parse IP once to speed up filters let ip_filter = filters.ip.as_deref().and_then(|s| IpAddr::from_str(s).ok()); + let range = super::TimeRange::new(filters.time_span, filters.from, filters.to); + let reports: Vec = state .lock() .await .dmarc_reports .iter() + .filter(|(_, rwi)| { + let date_range = &rwi.report.report_metadata.date_range; + range.overlaps(date_range.begin as i64, date_range.end as i64) + }) .filter(|(_, rwi)| { if let Some(id) = &filters.id { rwi.mail_id == *id diff --git a/src/http/mails.rs b/src/http/mails.rs index 05dec48..fe7fc41 100644 --- a/src/http/mails.rs +++ b/src/http/mails.rs @@ -67,6 +67,9 @@ pub struct MailFilters { oversized: Option, errors: Option, duplicates: Option, + time_span: Option, + from: Option, + to: Option, } impl MailFilters { @@ -86,10 +89,13 @@ pub async fn list_handler( // Remove URL encoding from strings in filters filters.url_decode(); + let range = super::TimeRange::new(filters.time_span, filters.from, filters.to); + let lock = state.lock().await; let mails: Vec<&Mail> = lock .mails .values() + .filter(|m| range.overlaps(m.date, m.date)) .filter(|m| { if let Some(queried_sender) = &filters.sender { m.sender.to_lowercase() == *queried_sender diff --git a/src/http/summary.rs b/src/http/summary.rs index 91dec73..a2a11de 100644 --- a/src/http/summary.rs +++ b/src/http/summary.rs @@ -4,7 +4,6 @@ use crate::tls::{FailureResultType, PolicyType, TlsResultType}; use axum::Json; use axum::extract::{Query, State}; use axum::response::IntoResponse; -use chrono::{Duration, Utc}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; @@ -17,6 +16,10 @@ pub struct SummaryFilters { /// None or a value of zero means the filter is disabled! time_span: Option, + /// Inclusive UNIX seconds, overlapping reports are included. + from: Option, + to: Option, + /// Domain to be filtered. Other domains will be ignored. /// None means the filter is disabled! domain: Option, @@ -38,12 +41,6 @@ pub async fn handler( ) -> impl IntoResponse { filters.url_decode(); let guard = state.lock().await; - let mut time_span = None; - if let Some(hours) = filters.time_span - && hours > 0 - { - time_span = Some(Duration::hours(hours as i64)); - } let summary = Summary::new( guard.mails.len(), Reports { @@ -52,7 +49,7 @@ pub async fn handler( }, guard.last_update, guard.next_update, - time_span, + super::TimeRange::new(filters.time_span, filters.from, filters.to), filters.domain.clone(), ); Json(summary) @@ -141,7 +138,7 @@ impl Summary { reports: Reports, last_update: Option, next_update: Option, - time_span: Option, + range: super::TimeRange, domain_filter: Option, ) -> Self { let mut dmarc = DmarcSummary { @@ -154,13 +151,10 @@ impl Summary { ..Default::default() }; - let threshold = time_span.map(|d| (Utc::now() - d).timestamp() as u64); - let threshold_datetime = time_span.map(|d| Utc::now() - d); let domain_filter = domain_filter.map(|d| d.to_lowercase()); for DmarcReportWithMailId { report, .. } in reports.dmarc.values() { - if let Some(threshold) = threshold - && report.report_metadata.date_range.end < threshold - { + let date_range = &report.report_metadata.date_range; + if !range.overlaps(date_range.begin as i64, date_range.end as i64) { continue; } if let Some(df) = &domain_filter @@ -194,9 +188,10 @@ impl Summary { } } for TlsReportWithMailId { report, .. } in reports.tls.values() { - if let Some(threshold_datetime) = threshold_datetime - && report.date_range.end_datetime < threshold_datetime - { + if !range.overlaps( + report.date_range.start_datetime.timestamp(), + report.date_range.end_datetime.timestamp(), + ) { continue; } if let Some(df) = &domain_filter diff --git a/src/http/tls_reports.rs b/src/http/tls_reports.rs index eb04e91..f6cde5d 100644 --- a/src/http/tls_reports.rs +++ b/src/http/tls_reports.rs @@ -83,6 +83,9 @@ pub struct ReportFilters { domain: Option, org: Option, ip: Option, + time_span: Option, + from: Option, + to: Option, } impl ReportFilters { @@ -115,11 +118,20 @@ pub async fn list_handler( // Parse IP once to speed up filters let ip_filter = filters.ip.as_deref().and_then(|s| IpAddr::from_str(s).ok()); + let range = super::TimeRange::new(filters.time_span, filters.from, filters.to); + let reports: Vec = state .lock() .await .tls_reports .iter() + .filter(|(_, rwi)| { + let date_range = &rwi.report.date_range; + range.overlaps( + date_range.start_datetime.timestamp(), + date_range.end_datetime.timestamp(), + ) + }) .filter(|(_, rwi)| { if let Some(id) = &filters.id { rwi.mail_id == *id diff --git a/ui/components/dashboard.js b/ui/components/dashboard.js index 9ca6ff4..5778751 100644 --- a/ui/components/dashboard.js +++ b/ui/components/dashboard.js @@ -1,5 +1,6 @@ import { LitElement, html, css } from "lit"; import { globalStyle } from "../style.js"; +import { timeQuery, timeSpanSelect } from "../utils.js"; export class Dashboard extends LitElement { static styles = [globalStyle, css` @@ -79,16 +80,6 @@ export class Dashboard extends LitElement { } } - onTimeSpanChange(event) { - const value = event.target.value; - if (value && value !== "0") { - this.params.ts = value; - } else { - delete this.params.ts; - } - this.updateByParams(); - } - onDomainChange(event) { const value = event.target.value; if (value && value !== "all") { @@ -138,9 +129,7 @@ export class Dashboard extends LitElement { async updateCharts() { const queryParams = []; - if (this.params.ts && this.params.ts !== "0") { - queryParams.push("time_span=" + this.params.ts); - } + queryParams.push(...timeQuery(this.params)); if (this.params.domain && this.params.domain !== "all") { queryParams.push("domain=" + this.params.domain); } @@ -365,15 +354,7 @@ export class Dashboard extends LitElement {
- Time Span for Summary Charts: - + ${timeSpanSelect(this.params, "dashboard", "Time Span for Summary Charts")} diff --git a/ui/components/dmarc-reports.js b/ui/components/dmarc-reports.js index c815f76..b2d1268 100644 --- a/ui/components/dmarc-reports.js +++ b/ui/components/dmarc-reports.js @@ -1,5 +1,6 @@ import { LitElement, html } from "lit"; import { globalStyle } from "../style.js"; +import { timeParams, timeQuery, timeSpanSelect } from "../utils.js"; export class DmarcReports extends LitElement { static styles = [globalStyle]; @@ -45,6 +46,8 @@ export class DmarcReports extends LitElement { if (this.params.ip) { urlParams.push("ip=" + encodeURIComponent(this.params.ip)); } + this.filtered = urlParams.length > 0; + urlParams.push(...timeQuery(this.params)); let url = "dmarc-reports"; if (urlParams.length > 0) { url += "?" + urlParams.join("&"); @@ -52,22 +55,23 @@ export class DmarcReports extends LitElement { const response = await fetch(url); this.reports = await response.json(); this.reports.sort((a, b) => b.date_begin - a.date_begin); - this.filtered = this.filtered = urlParams.length > 0; } render() { + const time = timeParams(this.params); return html`

DMARC Reports

${this.filtered ? - html`Filter active! Show all Reports` : + html`Filter active! Show all Reports` : html`Filters: - Reports with Problems - Reports with DKIM Problems - Reports with SPF Problems - Reports with DMARC Problems + Reports with Problems + Reports with DKIM Problems + Reports with SPF Problems + Reports with DMARC Problems ` } + ${timeSpanSelect(this.params, "dmarc-reports")}
`; diff --git a/ui/components/mails.js b/ui/components/mails.js index 5350d3d..b9a280c 100644 --- a/ui/components/mails.js +++ b/ui/components/mails.js @@ -1,5 +1,6 @@ import { LitElement, html } from "lit"; import { globalStyle } from "../style.js"; +import { timeParams, timeQuery, timeSpanSelect } from "../utils.js"; export class Mails extends LitElement { static styles = [globalStyle]; @@ -39,6 +40,8 @@ export class Mails extends LitElement { if (this.params.duplicates === "true" || this.params.duplicates === "false") { queryParams.push("duplicates=" + this.params.duplicates); } + this.filtered = queryParams.length > 0; + queryParams.push(...timeQuery(this.params)); let url = "mails"; if (queryParams.length > 0) { url += "?" + queryParams.join("&"); @@ -46,22 +49,23 @@ export class Mails extends LitElement { const mailsResponse = await fetch(url); this.mails = await mailsResponse.json(); this.mails.sort((a, b) => b.date - a.date); - this.filtered = queryParams.length > 0; } render() { + const time = timeParams(this.params); return html`

Mails

${this.filtered ? - html`Filter active! Show all Mails` : - html`Filters: Oversized Mails - With DMARC - With TLS - Without Files - With Duplicates - Parsing Errors` + html`Filter active! Show all Mails` : + html`Filters: Oversized Mails + With DMARC + With TLS + Without Files + With Duplicates + Parsing Errors` } + ${timeSpanSelect(this.params, "mails")}
`; diff --git a/ui/components/tls-reports.js b/ui/components/tls-reports.js index 8627fe3..eb607fa 100644 --- a/ui/components/tls-reports.js +++ b/ui/components/tls-reports.js @@ -1,5 +1,6 @@ import { LitElement, html } from "lit"; import { globalStyle } from "../style.js"; +import { timeParams, timeQuery, timeSpanSelect } from "../utils.js"; export class TlsReports extends LitElement { static styles = [globalStyle]; @@ -42,6 +43,8 @@ export class TlsReports extends LitElement { if (this.params.ip) { urlParams.push("ip=" + encodeURIComponent(this.params.ip)); } + this.filtered = urlParams.length > 0; + urlParams.push(...timeQuery(this.params)); let url = "tls-reports"; if (urlParams.length > 0) { url += "?" + urlParams.join("&"); @@ -49,21 +52,22 @@ export class TlsReports extends LitElement { const response = await fetch(url); this.reports = await response.json(); this.reports.sort((a, b) => new Date(b.date_begin) - new Date(a.date_begin)); - this.filtered = this.filtered = urlParams.length > 0; } render() { + const time = timeParams(this.params); return html`

SMTP TLS Reports

${this.filtered ? - html`Filter active! Show all Reports` : + html`Filter active! Show all Reports` : html`Filters: - Reports with Problems - Reports with MTA-STS Problems - Reports with TLSA Problems + Reports with Problems + Reports with MTA-STS Problems + Reports with TLSA Problems ` } + ${timeSpanSelect(this.params, "tls-reports")}
`; diff --git a/ui/style.js b/ui/style.js index dd0c326..e1e0452 100644 --- a/ui/style.js +++ b/ui/style.js @@ -108,6 +108,31 @@ export const globalStyle = css` background-color: rgb(90, 98, 104); } + .time-range { + border: 1px solid rgb(206, 212, 218); + border-radius: 3px; + padding: 15px; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); + } + + .time-range label { + margin-right: 10px; + } + + .time-range .button { + margin-top: 10px; + } + + .time-range .error { + margin-top: 10px; + color: rgb(220, 53, 69); + } + + .button:disabled { + cursor: not-allowed; + opacity: 0.5; + } + .button.sm { padding: 1px; padding-left: 4px; diff --git a/ui/utils.js b/ui/utils.js index 9d658b5..d1d37c1 100644 --- a/ui/utils.js +++ b/ui/utils.js @@ -1,3 +1,111 @@ +import { html } from "lit"; + export function join(elements, joiner) { return elements.flatMap(x => [joiner, x]).slice(1); } + +const timeSpans = [ + ["0", "Everything"], + ["24", "Last Day"], + ["72", "Last Three Days"], + ["168", "Last Week"], + ["744", "Last Month"], + ["4464", "Last Six Months"], + ["8760", "Last Year"], +]; + +const datePattern = /^\d{4}-\d{2}-\d{2}$/; + +function validDate(value) { + return datePattern.test(value ?? "") ? value : ""; +} + +function isoDate(date) { + return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; +} + +// Dates are whole days in local time +export function timeQuery(params) { + const query = []; + if (/^\d+$/.test(params.ts ?? "") && params.ts !== "0") { + query.push("time_span=" + params.ts); + } + if (validDate(params.from)) { + query.push("from=" + Math.floor(new Date(params.from + "T00:00:00").getTime() / 1000)); + } + if (validDate(params.to)) { + query.push("to=" + Math.floor(new Date(params.to + "T23:59:59").getTime() / 1000)); + } + return query; +} + +export function timeParams(params) { + return ["ts", "from", "to"].filter(k => params[k]).map(k => k + "=" + params[k]).join("&"); +} + +function localDate(value) { + return new Date(value + "T00:00:00").toLocaleDateString(); +} + +function rangeText(from, to) { + if (from && to) { + return localDate(from) + " – " + localDate(to); + } + return from ? "Since " + localDate(from) : "Until " + localDate(to); +} + +export function timeSpanSelect(params, route, label) { + const navigate = (changes) => { + const newParams = { ...params, ...changes }; + Object.keys(newParams).filter(k => !newParams[k]).forEach(k => delete newParams[k]); + const query = Object.keys(newParams).map(k => k + "=" + newParams[k]).join("&"); + document.location.href = "#/" + route + (query.length > 0 ? "?" + query : ""); + }; + const from = validDate(params.from); + const to = validDate(params.to); + const custom = from || to; + const selected = custom ? "range" : (params.ts ?? "0"); + const popover = (event) => event.target.getRootNode().querySelector(".time-range"); + const onSelect = (event) => { + const value = event.target.value; + if (value === "custom") { + event.target.value = selected; + popover(event).showPopover(); + } else { + navigate({ ts: value === "0" ? "" : value, from: "", to: "" }); + } + }; + const invalidRange = (fromValue, toValue) => Boolean(fromValue && toValue && toValue < fromValue); + const onInput = (event) => { + const box = popover(event); + const [fromInput, toInput] = box.querySelectorAll("input"); + const invalid = invalidRange(fromInput.value, toInput.value); + box.querySelector(".apply").disabled = invalid; + box.querySelector(".error").hidden = !invalid; + }; + const onApply = (event) => { + const [fromInput, toInput] = popover(event).querySelectorAll("input"); + navigate({ ts: "", from: fromInput.value, to: toInput.value }); + popover(event).hidePopover(); + }; + const weekAgo = new Date(); + weekAgo.setDate(weekAgo.getDate() - 7); + const fromValue = custom ? from : isoDate(weekAgo); + const toValue = custom ? to : isoDate(new Date()); + const invalid = invalidRange(fromValue, toValue); + const css = label ? "" : "button"; + return html`${label ? label + ": " : ""} +
+ + + + + +
`; +}