Skip to content
Closed
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
68 changes: 68 additions & 0 deletions src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<i64>,
to: Option<i64>,
}

impl TimeRange {
/// Invalid time spans are ignored, the stricter lower bound wins.
fn new(time_span: Option<u64>, from: Option<i64>, to: Option<i64>) -> 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));
}
}
9 changes: 9 additions & 0 deletions src/http/dmarc_reports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ pub struct ReportFilters {
domain: Option<String>,
org: Option<String>,
ip: Option<String>,
time_span: Option<u64>,
from: Option<i64>,
to: Option<i64>,
}

impl ReportFilters {
Expand Down Expand Up @@ -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<ReportHeader> = 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
Expand Down
6 changes: 6 additions & 0 deletions src/http/mails.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ pub struct MailFilters {
oversized: Option<bool>,
errors: Option<bool>,
duplicates: Option<bool>,
time_span: Option<u64>,
from: Option<i64>,
to: Option<i64>,
}

impl MailFilters {
Expand All @@ -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
Expand Down
29 changes: 12 additions & 17 deletions src/http/summary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -17,6 +16,10 @@ pub struct SummaryFilters {
/// None or a value of zero means the filter is disabled!
time_span: Option<u64>,

/// Inclusive UNIX seconds, overlapping reports are included.
from: Option<i64>,
to: Option<i64>,

/// Domain to be filtered. Other domains will be ignored.
/// None means the filter is disabled!
domain: Option<String>,
Expand All @@ -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 {
Expand All @@ -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)
Expand Down Expand Up @@ -141,7 +138,7 @@ impl Summary {
reports: Reports,
last_update: Option<u64>,
next_update: Option<u64>,
time_span: Option<Duration>,
range: super::TimeRange,
domain_filter: Option<String>,
) -> Self {
let mut dmarc = DmarcSummary {
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions src/http/tls_reports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ pub struct ReportFilters {
domain: Option<String>,
org: Option<String>,
ip: Option<String>,
time_span: Option<u64>,
from: Option<i64>,
to: Option<i64>,
}

impl ReportFilters {
Expand Down Expand Up @@ -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<ReportHeader> = 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
Expand Down
25 changes: 3 additions & 22 deletions ui/components/dashboard.js
Original file line number Diff line number Diff line change
@@ -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`
Expand Down Expand Up @@ -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") {
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -365,15 +354,7 @@ export class Dashboard extends LitElement {

<div class="module stats">
<span>
Time Span for Summary Charts:
<select @change="${this.onTimeSpanChange}">
<option value="0">Everything</option>
<option ?selected=${this.params.ts === "72"} value="72">Last Three Days</option>
<option ?selected=${this.params.ts === "168"} value="168">Last Week</option>
<option ?selected=${this.params.ts === "744"} value="744">Last Month</option>
<option ?selected=${this.params.ts === "4464"} value="4464">Last Six Months</option>
<option ?selected=${this.params.ts === "8760"} value="8760">Last Year</option>
</select>
${timeSpanSelect(this.params, "dashboard", "Time Span for Summary Charts")}
</span>

<span>
Expand Down
16 changes: 10 additions & 6 deletions ui/components/dmarc-reports.js
Original file line number Diff line number Diff line change
@@ -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];
Expand Down Expand Up @@ -45,29 +46,32 @@ 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("&");
}
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`
<h1>DMARC Reports</h1>
<div>
${this.filtered ?
html`Filter active! <a class="ml button" href="#/dmarc-reports">Show all Reports</a>` :
html`Filter active! <a class="ml button" href="#/dmarc-reports${time ? "?" + time : ""}">Show all Reports</a>` :
html`Filters:
<a class="ml button mr-5" href="#/dmarc-reports?flagged=true">Reports with Problems</a>
<a class="button mr-5" href="#/dmarc-reports?flagged_dkim=true">Reports with DKIM Problems</a>
<a class="button mr-5" href="#/dmarc-reports?flagged_spf=true">Reports with SPF Problems</a>
<a class="button" href="#/dmarc-reports?flagged_dmarc=true">Reports with DMARC Problems</a>
<a class="ml button mr-5" href="#/dmarc-reports?flagged=true${time ? "&" + time : ""}">Reports with Problems</a>
<a class="button mr-5" href="#/dmarc-reports?flagged_dkim=true${time ? "&" + time : ""}">Reports with DKIM Problems</a>
<a class="button mr-5" href="#/dmarc-reports?flagged_spf=true${time ? "&" + time : ""}">Reports with SPF Problems</a>
<a class="button" href="#/dmarc-reports?flagged_dmarc=true${time ? "&" + time : ""}">Reports with DMARC Problems</a>
`
}
${timeSpanSelect(this.params, "dmarc-reports")}
</div>
<drv-dmarc-report-table .reports="${this.reports}"></drv-dmarc-report-table>
`;
Expand Down
Loading
Loading