feather_reader/feed.rs
1//! Feed fetch → parse → sanitize → store pipeline.
2//!
3//! This is the module that turns a feed URL into rows in the [`store`]. It is
4//! deliberately conservative on three axes, because a feed reader ingests
5//! **hostile, arbitrary web input**:
6//!
7//! 1. **Politeness** — fetches use a **conditional GET** (`If-None-Match` /
8//! `If-Modified-Since` from the stored `ETag` / `Last-Modified`), an
9//! identifiable [`crate::USER_AGENT`], a request timeout, and a simple
10//! exponential backoff hint on error. A `304 Not Modified` is a no-op:
11//! the feed is untouched apart from bumping its next-poll time.
12//! 2. **Safety** — every entry's HTML is run through `ammonia` before it is
13//! ever stored (and therefore before it is ever rendered). Scripts, event
14//! handlers, `javascript:` URLs, tracking pixels' dangerous attributes, and
15//! other XSS vectors are stripped. Feeds carrying `<script>` is not
16//! hypothetical; treat all feed HTML as untrusted.
17//! 3. **Robustness** — a malformed feed is **logged and skipped**, never a
18//! panic. One bad publisher must not take down the poller. All non-test
19//! paths use `Result`/`anyhow`; there are no `unwrap`/`expect`s.
20//!
21//! The normalized shape written to the store is the store's own
22//! [`store::NewFeed`] / [`store::NewEntry`]; dedup is by feed-native GUID via
23//! [`store::insert_entries`]'s `ON CONFLICT (feed_id, guid)` upsert.
24
25use std::time::Duration;
26
27use anyhow::{Context, Result};
28use chrono::{DateTime, SecondsFormat, Utc};
29use feed_rs::model::{Entry as RawEntry, Feed as RawFeed, Text};
30use reqwest::header::{ETAG, IF_MODIFIED_SINCE, IF_NONE_MATCH, LAST_MODIFIED};
31use reqwest::{Client, StatusCode};
32use sqlx::SqlitePool;
33use url::Url;
34
35use crate::store::{self, Feed, NewEntry, NewFeed};
36
37/// The privacy classification of a feed URL — the output of
38/// [`classify_feed_privacy`].
39///
40/// A **private** feed carries a secret (a token / key / auth credential) *in the
41/// URL itself* — a Substack `…/feed/private/<token>`, a Patreon `?auth=…` feed,
42/// a Ghost members `?uuid=` feed, a private-podcast token feed (Supercast,
43/// Supporting Cast, tokened Megaphone/Acast+), and so on. FeatherReader stores a
44/// user's subscriptions as records in their **public PDS** (unauthenticated
45/// `getRecord` / `listRecords` + the firehose, retained even after delete), so
46/// writing such a URL anywhere — the PDS *or* the server's own store — would risk
47/// leaking paid / members-only access.
48///
49/// **Decision (stopgap until atproto permissioned data ships): FeatherReader
50/// supports PUBLIC feeds only.** A feed classified [`FeedPrivacy::Private`] is
51/// *refused* at the add / import boundary — never fetched, never stored, never
52/// written to the PDS. There is no local-secret fallback and no override: the
53/// server holds NO private secret, ever, which keeps "your data lives in your
54/// public PDS" 100% honest.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum FeedPrivacy {
57 /// No secret detected in the URL; safe to add as a public feed.
58 Public,
59 /// A secret was detected in the URL. The `String` is a short, human-readable
60 /// reason (for logging / the skip report), e.g. `"substack private feed
61 /// path"`. The feed is refused — not fetched, stored, or written anywhere.
62 Private(String),
63}
64
65impl FeedPrivacy {
66 /// Whether this classification is [`FeedPrivacy::Private`].
67 pub fn is_private(&self) -> bool {
68 matches!(self, FeedPrivacy::Private(_))
69 }
70}
71
72/// Query-parameter *keys* that, when present with a long/opaque value, mark a URL
73/// as carrying a secret. Conservative and lowercase-compared; matched as a whole
74/// key (case-insensitive) so a benign `keyword=` does NOT trip `key`. This is the
75/// generic, provider-agnostic credential-in-query defence — it catches paid
76/// feeds from providers we've never heard of. Covers Patreon (`auth`), Ghost
77/// members (`uuid`), token-in-query feeds (`token`/`key`/`k`/`sig`/`hash`), and
78/// the long tail (`access`/`apikey`/`private`/`password`/`u`/`s`/`p`/…).
79const SECRET_QUERY_KEYS: &[&str] = &[
80 "token", "key", "auth", "secret", "k", "sig", "hash", "access", "apikey", "api_key", "uuid",
81 "id", "u", "s", "p", "private", "password", "pw",
82];
83
84/// Path *segments* / fragments that mark a private-feed URL shape. Matched as a
85/// case-insensitive substring of the (lowercased) path so `/feed/private/<tok>`,
86/// `/members/…`, `/subscriber/…` etc. all trip regardless of the token that
87/// follows. Provider-agnostic: many paid providers expose members-only feeds
88/// under one of these path conventions.
89const PRIVATE_PATH_MARKERS: &[&str] = &[
90 "/private/",
91 "/feed/private/",
92 "/rss/private/",
93 "/private-feed/",
94 "/members/",
95 "/member/",
96 "/subscriber/",
97];
98
99/// A KNOWN paid/private feed provider, matched by host substring + (optionally) a
100/// path/query marker specific to that provider. This is the **secondary**,
101/// precision layer on top of the generic heuristic — it names providers so the
102/// skip report can say *why* and so we catch provider-specific shapes that the
103/// generic pass might rate as borderline. Data-driven and easy to extend: add a
104/// row, don't touch the matcher.
105struct KnownProvider {
106 /// Substring that must appear in the URL host (lowercased), e.g.
107 /// `substack.com`.
108 host_contains: &'static str,
109 /// Optional lowercased substring that must appear in the path-or-query for a
110 /// match (a provider's private-feed marker). `None` = the host alone is
111 /// enough (used for hosts that ONLY serve private/tokened feeds).
112 marker: Option<&'static str>,
113 /// Human-readable reason for the skip report.
114 reason: &'static str,
115}
116
117/// The known-provider table. Covers paid NEWSLETTERS and private PODCASTS — an
118/// RSS reader ingests both. Kept intentionally verbose/commented so it's obvious
119/// what each row targets and safe to extend.
120const KNOWN_PROVIDERS: &[KnownProvider] = &[
121 // --- Paid newsletters -------------------------------------------------
122 // Substack private feed: author.substack.com/feed/private/<token>.
123 KnownProvider {
124 host_contains: "substack.com",
125 marker: Some("/feed/private/"),
126 reason: "Substack private feed",
127 },
128 // Patreon RSS carries the member token as ?auth=.
129 KnownProvider {
130 host_contains: "patreon.com",
131 marker: Some("auth="),
132 reason: "Patreon member feed",
133 },
134 // Ghost members feed: ?uuid=<member-uuid> (or a members token path).
135 KnownProvider {
136 host_contains: "ghost.io",
137 marker: Some("uuid="),
138 reason: "Ghost members feed",
139 },
140 // Buttondown paid RSS uses a per-subscriber token in the path/query.
141 KnownProvider {
142 host_contains: "buttondown.email",
143 marker: Some("token"),
144 reason: "Buttondown premium feed",
145 },
146 KnownProvider {
147 host_contains: "buttondown.com",
148 marker: Some("token"),
149 reason: "Buttondown premium feed",
150 },
151 // Beehiiv premium RSS carries a subscriber token.
152 KnownProvider {
153 host_contains: "beehiiv.com",
154 marker: Some("token"),
155 reason: "Beehiiv premium feed",
156 },
157 // Memberful-gated feeds (host or ?auth token).
158 KnownProvider {
159 host_contains: "memberful.com",
160 marker: None,
161 reason: "Memberful members feed",
162 },
163 // Pico / Steady member feeds.
164 KnownProvider {
165 host_contains: "pico.link",
166 marker: None,
167 reason: "Pico member feed",
168 },
169 KnownProvider {
170 host_contains: "steadyhq.com",
171 marker: None,
172 reason: "Steady member feed",
173 },
174 // --- Private podcasts -------------------------------------------------
175 // Supercast private podcast feeds (host serves tokened member feeds only).
176 KnownProvider {
177 host_contains: "supercast.com",
178 marker: None,
179 reason: "Supercast private podcast",
180 },
181 KnownProvider {
182 host_contains: "supercast.tech",
183 marker: None,
184 reason: "Supercast private podcast",
185 },
186 // Supporting Cast private podcast feeds (supportingcast.fm).
187 KnownProvider {
188 host_contains: "supportingcast.fm",
189 marker: None,
190 reason: "Supporting Cast private podcast",
191 },
192 // RedCircle private/exclusive feeds.
193 KnownProvider {
194 host_contains: "redcircle.com",
195 marker: Some("private"),
196 reason: "RedCircle private podcast",
197 },
198 // Private/tokened Megaphone, Acast+, and Omny feeds carry an access token.
199 KnownProvider {
200 host_contains: "megaphone.fm",
201 marker: Some("token"),
202 reason: "Megaphone private podcast",
203 },
204 KnownProvider {
205 host_contains: "acast.com",
206 marker: Some("token"),
207 reason: "Acast+ private podcast",
208 },
209 KnownProvider {
210 host_contains: "omny.fm",
211 marker: Some("token"),
212 reason: "Omny private podcast",
213 },
214 // Apple / Spotify subscriber podcast feeds carry a per-listener token.
215 KnownProvider {
216 host_contains: "podcasts.apple.com",
217 marker: Some("token"),
218 reason: "Apple subscriber podcast",
219 },
220 KnownProvider {
221 host_contains: "spotify.com",
222 marker: Some("token"),
223 reason: "Spotify subscriber podcast",
224 },
225];
226
227/// Whether a URL may be **stored or published** as a feed URL at all.
228///
229/// This is the storage-side twin of the scheme check `net::check_scheme` applies
230/// before fetching. The fetch side has always been safe, because nothing can
231/// reach the network except through `net.rs` — but "safe to fetch" and "safe to
232/// write down" are different questions, and only the first had an answer.
233///
234/// Two paths took a URL from outside and stored it with no validation at all:
235/// `resolve_subscriptions` (any atproto client can write a subscription record
236/// into a user's repo) and the OPML import (`xmlUrl` is whatever the file says).
237/// `classify_feed_privacy` does not cover this — it deliberately returns
238/// `Public` for an unparseable URL, on the stated assumption that "the add path
239/// will reject it as malformed regardless", and those two paths are the ones
240/// that never had an add path to do the rejecting.
241///
242/// Note that `javascript:alert(1)` and `file:///etc/passwd` both *parse* cleanly
243/// as URLs, so parsing is not the check — the scheme is.
244pub fn is_storable_feed_url(url: &str, allow_at_uri: bool) -> bool {
245 // **`at://` is checked BEFORE `Url::parse`, because `Url::parse` cannot read
246 // the form that matters.** `at://did:plc:…/…` fails to parse with *invalid
247 // port number* — the colons in the DID are taken as a port separator — while
248 // the handle form `at://alice.example.com/…` parses fine. So adding `"at"`
249 // to the `matches!` below would appear to work and silently reject every
250 // DID-based at-URI, which is all of them in practice.
251 if let Some(rest) = crate::atproto::strip_at_prefix(url) {
252 // **Recognised case-insensitively, stored canonically.** Schemes are
253 // case-insensitive, so `At://` names the same publication — but
254 // `feeds.url` is UNIQUE, so accepting both spellings is two rows for
255 // one publication, the hazard the canonical-handle rule exists for.
256 // Recognising it here rather than letting it fall through to the
257 // generic checks is what keeps it out of the poller: nothing can fetch
258 // it under any spelling.
259 if !url.starts_with(crate::atproto::AT_URI_PREFIX) {
260 return false;
261 }
262 // **This gates STORING only — polling is handled by exclusion**, by
263 // kind rather than by any re-description of the URL, and
264 // `FeedKind::POLLABLE` is the one place the why is written down.
265 return allow_at_uri && is_storable_publication_uri(rest);
266 }
267 match Url::parse(url) {
268 Ok(u) => {
269 // No host check: for http(s) the `url` crate refuses every hostless
270 // spelling at parse (`http://`, `https://?q`, `http:///` are all
271 // "empty host") and turns `https:///x` into host `x`. A conjunct
272 // requiring a non-empty host was unreachable — a test hunt listed
273 // it as untested, and the honest answer was that no input reaches
274 // it. The `Err` arm below is what refuses a hostless URL.
275 matches!(u.scheme(), "http" | "https")
276 }
277 Err(_) => false,
278 }
279}
280
281/// The body of an `at://` URI — `<did-or-handle>/<collection>/<rkey>` — judged
282/// as a **storable feed**.
283///
284/// An allowlist entry, not a loosening: exactly one foreign collection is
285/// accepted, `site.standard.publication`. The two paths this guard exists for
286/// (`resolve_subscriptions`, the OPML import) take records written by any
287/// atproto client, so "it is an at-URI" is not a reason to store it — only "it
288/// is a publication this reader knows how to poll" is.
289fn is_storable_publication_uri(rest: &str) -> bool {
290 let mut parts = rest.split('/');
291 let (Some(authority), Some(collection), Some(rkey)) =
292 (parts.next(), parts.next(), parts.next())
293 else {
294 return false;
295 };
296 parts.next().is_none()
297 && collection == crate::lexicon::nsid::STANDARD_PUBLICATION
298 // **The rkey is validated against atproto's rules, not a blacklist.**
299 //
300 // A blacklist was the first attempt and it leaked twice: `is_control()`
301 // is Unicode category Cc only, so a bidi override (Cf) passed — and it
302 // reordered both the manage page and `scheduler.rs`'s `%feed.url` log
303 // line. Worse, nothing stopped a query string or fragment living inside
304 // the rkey, which satisfies the three-segment check and is exactly what
305 // `classify_feed_privacy`'s `at://` exemption keys off: a token
306 // smuggled there would have been declared public.
307 //
308 // An allowlist cannot leak the next character class someone finds.
309 // The charset alone still admitted `.`, `..` and a 10 000-byte key;
310 // `is_valid_rkey` carries the length and reserved-name rules too.
311 && crate::atproto::is_valid_rkey(rkey)
312 && is_storable_at_authority(authority)
313}
314
315/// The DID form only. `did:plc:` identifiers are validated by
316/// [`crate::oauth::identity::is_atproto_did`] rather than a `did:` prefix check,
317/// which would accept `did:plc:TOOSHORT`.
318///
319/// **The handle form is not storable, for the reason the canonical-handle rule
320/// already gave:** `feeds.url` is UNIQUE, so `at://alice.example.com/…` beside
321/// `at://did:plc:…/…` is two rows — two sidebar entries, and two polled copies
322/// once the reader is wired — for one publication. A handle is a mutable name
323/// for a DID; the row is keyed on the identity. Resolving a pasted or imported
324/// handle to its DID is the reader's job (#165 already resolves DIDs to their
325/// PDS), and belongs at input, not in storage.
326fn is_storable_at_authority(authority: &str) -> bool {
327 crate::oauth::identity::is_atproto_did(authority)
328}
329
330/// Classify whether a feed URL carries a secret credential in the URL itself.
331///
332/// Returns [`FeedPrivacy::Private`] (with a reason) when the URL looks like it
333/// embeds a token / key / auth credential, else [`FeedPrivacy::Public`].
334///
335/// **Design — provider-agnostic first.** The primary defence is a generic
336/// credential-in-URL heuristic that catches paid feeds from *any* provider, not
337/// just the ones we've named; a secondary known-provider table adds precision
338/// (and a nicer reason) for the common paid newsletters and private podcasts. We
339/// deliberately **bias toward flagging**: a false-positive block of a public feed
340/// is low-harm (the user just can't add that one feed yet), whereas a false
341/// negative would leak a paid secret onto the public network — high-harm.
342///
343/// Detection (any one is sufficient):
344/// 1. **Userinfo** — `https://user:pass@host/…` embeds credentials directly.
345/// 2. **Known private-feed path markers** — `PRIVATE_PATH_MARKERS`
346/// (`/feed/private/`, `/members/`, `/subscriber/`, …).
347/// 3. **Credential query parameters** — a query key in `SECRET_QUERY_KEYS` with
348/// a long/opaque value (Patreon `?auth=`, Ghost `?uuid=`, `?token=`, …).
349/// 4. **High-entropy opaque token segments** — a long opaque blob (hex ≥ 16,
350/// base64url ≥ 16, or a UUID) anywhere in the path or a query value, even
351/// without a telltale name.
352/// 5. **Known providers** — `KNOWN_PROVIDERS` host (+ optional marker) match.
353///
354/// An unparseable URL is treated as [`FeedPrivacy::Public`]: the add path rejects
355/// a malformed URL downstream anyway, and we don't want a parse quirk to
356/// misclassify.
357pub fn classify_feed_privacy(url: &str) -> FeedPrivacy {
358 // **`at://` is classified deliberately, and NOT doing so refused real
359 // subscriptions.** An atproto rkey is a TID — 13 base32-sortable characters
360 // — which is exactly what the generic "high-entropy token in path"
361 // heuristic below is looking for. Measured: without this arm,
362 // `at://did:plc:…/site.standard.publication/3lab2c4d5e6f7g8h` is
363 // classified PRIVATE and the subscription refused, while the DID form slips
364 // through only because it fails to parse as a `Url` at all.
365 //
366 // `Public` is the right answer: a publication is a public record in a
367 // public repo and the rkey is a handle, not a secret, so there is no
368 // private/paid shape for this scheme to carry.
369 if let Some(rest) = crate::atproto::strip_at_prefix(url) {
370 // A non-canonical scheme spelling is an at-URI this reader will not
371 // store, not an unparseable string for the `Err(_) => Public` arm below
372 // to wave through. Fail closed.
373 if !url.starts_with(crate::atproto::AT_URI_PREFIX) {
374 return FeedPrivacy::Private("non-canonical at:// scheme spelling".to_string());
375 }
376 // **Only a WELL-FORMED publication URI is exempt.** The first version
377 // of this was a bare prefix match, which declared any attacker-chosen
378 // string starting `at://` safe to publish — skipping the userinfo
379 // check, the known-provider table, the private-path markers, the
380 // secret-query keys and the entropy heuristics all at once. That is a
381 // regression against every one of them, on a path
382 // (`rename_subscription`) where this function is the only gate and the
383 // value is written to the user's PUBLIC repo.
384 //
385 // Anything else falls through to the generic checks below, which is
386 // where a credential-bearing string belongs.
387 if is_storable_publication_uri(rest) {
388 return FeedPrivacy::Public;
389 }
390 // **Malformed `at://` is REFUSED, not passed through.** Falling through
391 // reaches `Url::parse`, which fails on the DID form and lands on the
392 // `Err(_) => Public` arm below — whose justification is "the add path
393 // will reject it as a malformed URL regardless".
394 //
395 // **Defence in depth, not a live gate.** This comment used to say the
396 // justification is false on the `rename_subscription` path, "where this
397 // function is the only gate". That stopped being true when storability
398 // moved ahead of privacy on the repoint: a review then found no
399 // production caller can reach this arm at all — add pre-checks the
400 // `at://` prefix, rename and OPML and `resolve_subscriptions` all
401 // refuse a non-storable URL first. It stays because a fail-closed
402 // branch is worth its keep for the next caller that arrives without
403 // one, and because deleting a guard on the grounds that nothing
404 // currently reaches it is how the next one gets it wrong. It is not
405 // load-bearing today, and saying so is the honest version.
406 return FeedPrivacy::Private("not a well-formed at:// publication URI".to_string());
407 }
408 let parsed = match Url::parse(url) {
409 Ok(u) => u,
410 // Can't parse => the add path will reject it as a malformed URL regardless.
411 Err(_) => return FeedPrivacy::Public,
412 };
413
414 // (1) Userinfo (`https://user:pass@host/…`) — credentials in the authority.
415 if !parsed.username().is_empty() || parsed.password().is_some() {
416 return FeedPrivacy::Private("credentials in URL userinfo".to_string());
417 }
418
419 let path_lower = parsed.path().to_ascii_lowercase();
420 let query_lower = parsed.query().unwrap_or("").to_ascii_lowercase();
421 let host_lower = parsed.host_str().unwrap_or("").to_ascii_lowercase();
422
423 // (0) Public-feed allowlist. A handful of large, fully-public feed shapes
424 // carry a high-entropy-looking id in the query that would otherwise trip the
425 // generic entropy heuristic. YouTube channel/playlist RSS
426 // (`youtube.com/feeds/videos.xml?channel_id=UC…` / `?playlist_id=PL…`) is the
427 // canonical way any reader subscribes to a channel — the id is a PUBLIC
428 // handle, not a secret. Allowlist it before the generic checks so we don't
429 // false-block it. (Userinfo / known-provider markers are checked below and
430 // still apply, so this can't be used to smuggle a credential.)
431 if is_public_youtube_feed(&host_lower, &path_lower, &parsed) {
432 return FeedPrivacy::Public;
433 }
434
435 // (5) Known-provider precision layer (checked early so its specific reason
436 // wins over a generic one). Host substring + optional path/query marker.
437 for kp in KNOWN_PROVIDERS {
438 if host_lower.contains(kp.host_contains) {
439 let marker_ok = match kp.marker {
440 None => true,
441 Some(m) => {
442 let m = m.to_ascii_lowercase();
443 path_lower.contains(&m) || query_lower.contains(&m)
444 }
445 };
446 if marker_ok {
447 return FeedPrivacy::Private(kp.reason.to_string());
448 }
449 }
450 }
451
452 // (2) Known private-feed path markers.
453 for marker in PRIVATE_PATH_MARKERS {
454 if path_lower.contains(marker) {
455 return FeedPrivacy::Private(format!("private feed path `{marker}`"));
456 }
457 }
458
459 // (3) Credential query parameters with a long/opaque value.
460 for (k, v) in parsed.query_pairs() {
461 let key = k.as_ref().to_ascii_lowercase();
462 if SECRET_QUERY_KEYS.iter().any(|sk| *sk == key) && value_is_opaque(v.as_ref()) {
463 return FeedPrivacy::Private(format!("credential query parameter `{key}`"));
464 }
465 }
466
467 // (4) High-entropy opaque token segments (an embedded key/token with no
468 // telltale name): hex ≥ 16, base64url ≥ 16, or a UUID, in path or query.
469 // The dominant real-world private-podcast shape delivers the token as a
470 // *filename* (`<token>.rss` / `<token>.xml`) or affixed inside a larger
471 // segment (`feed-<uuid>`), so [`segment_hides_secret`] strips a trailing feed
472 // extension AND scans dot/underscore/hyphen-delimited sub-parts, not just the
473 // whole segment.
474 for seg in parsed.path().split('/').filter(|s| !s.is_empty()) {
475 if segment_hides_secret(seg) {
476 return FeedPrivacy::Private("high-entropy token in path".to_string());
477 }
478 }
479 for (_, v) in parsed.query_pairs() {
480 if looks_like_embedded_secret(v.as_ref()) {
481 return FeedPrivacy::Private("high-entropy token in query".to_string());
482 }
483 }
484
485 FeedPrivacy::Public
486}
487
488/// Whether a *named* credential query value (`?token=<v>`) is long/opaque enough
489/// to count as a secret. A short value (e.g. an enum like `?token=none`) is not.
490/// We treat a UUID, or anything ≥ 8 chars that isn't an obvious plain word, as
491/// opaque — named credential keys already signal intent, so the length bar is
492/// low.
493fn value_is_opaque(v: &str) -> bool {
494 if v.is_empty() {
495 return false;
496 }
497 if is_uuid(v) {
498 return true;
499 }
500 v.len() >= 8
501}
502
503/// Heuristic: does `s` look like an embedded secret (an opaque high-entropy
504/// token), as opposed to an ordinary slug or word? Matches a UUID, a hex string
505/// ≥ 16 chars, or a base64url-ish blob ≥ 16 chars that mixes letters and digits
506/// and isn't a hyphen/dot slug. Deliberately strict so it only fires on things
507/// that really look like keys — the named-marker and known-provider checks cover
508/// the rest.
509fn looks_like_embedded_secret(s: &str) -> bool {
510 if is_uuid(s) {
511 return true;
512 }
513 // Hex string ≥ 16 chars (e.g. a 32-char MD5-ish token).
514 if s.len() >= 16 && s.chars().all(|c| c.is_ascii_hexdigit()) {
515 return true;
516 }
517 // base64url-ish opaque blob ≥ 16 chars.
518 if s.len() < 16 {
519 return false;
520 }
521 // Hyphen/dot-heavy slugs (`this-is-a-normal-post-title`) are not secrets.
522 let separators = s
523 .bytes()
524 .filter(|b| *b == b'-' || *b == b'.' || *b == b' ')
525 .count();
526 if separators >= 3 {
527 return false;
528 }
529 // Must be plausibly token-charset: base64url alphabet only. `=` is accepted
530 // as base64 padding (it only ever appears trailing on a real blob, so a
531 // padded base64url token like `…dnc=` still counts).
532 let token_chars = s
533 .chars()
534 .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '='))
535 .count();
536 if token_chars < s.chars().count() {
537 return false;
538 }
539 let has_alpha = s.chars().any(|c| c.is_ascii_alphabetic());
540 let has_digit = s.chars().any(|c| c.is_ascii_digit());
541 if !(has_alpha && has_digit) {
542 // A token almost always mixes letters and digits; a pure-alpha long
543 // segment is far more likely to be a normal (if long) slug/word.
544 return false;
545 }
546 // Distinct-character ratio: real tokens use most of the alphabet, words
547 // repeat a small set. Require >= 10 distinct chars for a 16+ char blob.
548 let mut seen = std::collections::HashSet::new();
549 for c in s.chars() {
550 seen.insert(c.to_ascii_lowercase());
551 }
552 seen.len() >= 10
553}
554
555/// Known feed/file extensions a token filename may wear (`<token>.rss`,
556/// `<token>.xml`, …). Stripped before the whole-segment secret test so a
557/// tokened *filename* — the dominant private-podcast URL shape — is still caught.
558const FEED_EXTENSIONS: &[&str] = &["rss", "xml", "atom", "json", "rss20"];
559
560/// Whether a single path segment hides an embedded secret. Beyond the plain
561/// whole-segment [`looks_like_embedded_secret`] test, this also catches the two
562/// real-world shapes that wrap a token so the whole segment is no longer a clean
563/// blob:
564///
565/// 1. **Token-as-filename** — `<token>.rss` / `<token>.xml`: strip a trailing
566/// feed extension and re-test the stem.
567/// 2. **Token affixed inside a larger segment** — `feed-<uuid>`, `<token>.xml`,
568/// `pod_<hex32>`: split on `.`/`_`/`-` and test each sub-part, so a
569/// high-entropy blob delimited by an affix is still found.
570fn segment_hides_secret(seg: &str) -> bool {
571 if looks_like_embedded_secret(seg) {
572 return true;
573 }
574 // (1) Strip a trailing known feed extension and re-test the stem.
575 if let Some((stem, ext)) = seg.rsplit_once('.') {
576 if FEED_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str())
577 && looks_like_embedded_secret(stem)
578 {
579 return true;
580 }
581 }
582 // (2) A UUID embedded with an affix (`feed-<uuid>`, `<uuid>-audio`) — the
583 // `-` delimiters inside the UUID mean a naive split can't see it, so scan for
584 // a canonical UUID substring directly.
585 if contains_uuid(seg) {
586 return true;
587 }
588 // (3) Scan `.`/`_`/`-`-delimited sub-parts for a high-entropy blob affixed to
589 // an ordinary word (`pod_<hex32>`, `<hex32>.mp3`). Only fires on multi-part
590 // segments (a single-part segment was already covered by the whole-segment
591 // test above), so a plain `my-normal-post-slug` — whose parts are short
592 // dictionary words — can't trip it.
593 if seg.contains(['.', '_', '-']) {
594 for part in seg.split(['.', '_', '-']).filter(|p| !p.is_empty()) {
595 if looks_like_embedded_secret(part) {
596 return true;
597 }
598 }
599 }
600 false
601}
602
603/// Whether `s` contains a canonical 8-4-4-4-12 UUID as a substring (allowing an
604/// affix on either side, e.g. `feed-<uuid>` or `<uuid>-audio`). Slides a 36-char
605/// window over the string and tests each with [`is_uuid`].
606fn contains_uuid(s: &str) -> bool {
607 const UUID_LEN: usize = 36; // 8+4+4+4+12 + 4 hyphens.
608 let bytes = s.as_bytes();
609 if bytes.len() < UUID_LEN {
610 return false;
611 }
612 // ASCII-only window: a UUID is pure ASCII hex/hyphen, so byte indexing is
613 // safe here (a multi-byte char in the window just fails is_uuid).
614 (0..=bytes.len() - UUID_LEN).any(|i| s.get(i..i + UUID_LEN).map(is_uuid).unwrap_or(false))
615}
616
617/// Whether this is a PUBLIC YouTube channel/playlist RSS feed
618/// (`www.youtube.com/feeds/videos.xml?channel_id=UC…` or `?playlist_id=PL…`).
619/// The channel/playlist id is a public handle, not a credential, so these feeds
620/// must NOT be flagged by the generic entropy heuristic. We require the exact
621/// public host + feeds path + one of the two public id keys, so this narrow
622/// allowlist can't be abused to smuggle a `?token=` past classification.
623fn is_public_youtube_feed(host_lower: &str, path_lower: &str, parsed: &Url) -> bool {
624 let host_ok = host_lower == "youtube.com"
625 || host_lower == "www.youtube.com"
626 || host_lower.ends_with(".youtube.com");
627 if !host_ok || !path_lower.starts_with("/feeds/videos.xml") {
628 return false;
629 }
630 // Only the public id keys may appear; a `token`/`auth`/… key means treat it
631 // as a normal (potentially private) URL and let the checks below run.
632 parsed.query_pairs().all(|(k, _)| {
633 let k = k.as_ref().to_ascii_lowercase();
634 k == "channel_id" || k == "playlist_id" || k == "user"
635 })
636}
637
638/// Whether `s` is a canonical 8-4-4-4-12 hyphenated UUID (any hex case).
639fn is_uuid(s: &str) -> bool {
640 let groups = [8usize, 4, 4, 4, 12];
641 let parts: Vec<&str> = s.split('-').collect();
642 if parts.len() != groups.len() {
643 return false;
644 }
645 parts
646 .iter()
647 .zip(groups.iter())
648 .all(|(p, &n)| p.len() == n && p.chars().all(|c| c.is_ascii_hexdigit()))
649}
650
651/// How long a single feed fetch may take before we give up.
652const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
653
654/// Per-read idle timeout: cap the wait for the *next* body chunk, so a server
655/// that trickles bytes forever can't tie up a fetch under the total timeout.
656const READ_TIMEOUT: Duration = Duration::from_secs(15);
657
658/// Base backoff applied after a failed poll; the caller multiplies this by the
659/// feed's consecutive-error count (with a ceiling) to space out retries.
660const BACKOFF_BASE: Duration = Duration::from_secs(300);
661
662/// Ceiling on backoff so a persistently broken feed still gets retried daily.
663const BACKOFF_MAX: Duration = Duration::from_secs(24 * 3600);
664
665/// The outcome of polling a single feed. Lets the scheduler decide how to
666/// reschedule (and lets tests assert what happened) without inspecting the DB.
667#[derive(Debug, Clone, PartialEq, Eq)]
668pub enum PollOutcome {
669 /// The feed was fetched, parsed, and stored. `new_entries` is the number of
670 /// entries inserted or updated by this poll.
671 Updated { new_entries: u64 },
672 /// The server returned `304 Not Modified` — nothing changed, nothing stored.
673 NotModified,
674 /// The fetch or parse failed; the feed was left intact and skipped. Carries
675 /// the suggested backoff before the next attempt. Never a panic.
676 ///
677 /// **`kind` and `detail` are the reason, and they exist because their
678 /// absence cost a production investigation.** Until #159 the error was
679 /// logged here and discarded, so `feeds` recorded that a feed was failing
680 /// and never why — which is how sixty feeds broken by our own 304 handling
681 /// looked exactly like sixty dead blogs. `kind` is a small closed
682 /// vocabulary so failures can be counted by cause; `detail` is the message
683 /// for a human reading one row.
684 Failed {
685 backoff: Duration,
686 kind: FailureKind,
687 detail: String,
688 },
689}
690
691/// Why a poll failed, as a closed set.
692///
693/// Closed on purpose: the point is to *count* failures by cause, and a free-text
694/// kind cannot be counted. The detail string carries whatever else matters.
695#[derive(Debug, Clone, Copy, PartialEq, Eq)]
696pub enum FailureKind {
697 /// The request never produced a response — DNS, TLS, timeout, connection
698 /// refused, or a refusal by the SSRF guard.
699 Fetch,
700 /// A response arrived with a non-success status.
701 Status,
702 /// The body was too large, or reading it failed part-way.
703 Body,
704 /// The body arrived and is not a feed this parser can read.
705 Parse,
706}
707
708/// What the poller does with a feed row.
709///
710/// **A column, not a predicate.** "Can this be fetched?" used to be
711/// `substr(url, 1, 5) = 'at://'` spliced into four statements, with a fifth
712/// reader that had already drifted from them. Deciding it once, in Rust, at
713/// insert — and storing the answer — means SQL cannot disagree with the
714/// fetcher, and wiring the standard.site reader becomes a change to this
715/// function plus a dispatch, rather than an edit to every statement that
716/// mentions a URL.
717#[derive(Debug, Clone, Copy, PartialEq, Eq)]
718pub enum FeedKind {
719 /// An RSS/Atom/JSON feed document fetched over http(s).
720 Rss,
721 /// An `at://…/site.standard.publication/…` record pair in somebody's PDS,
722 /// read by `standard_site` and pollable since 0.4.0.
723 Publication,
724 /// Any other `at://` row: another collection, or a spelling the storage
725 /// guard would refuse. Rows like this predate that guard. **Never
726 /// pollable** — handing one to the standard.site reader would fail its
727 /// collection check every tick and publish it as an unreachable publisher —
728 /// and counted as unpollable so the capacity it holds stays visible.
729 Unsupported,
730}
731
732impl FeedKind {
733 /// The kinds the scheduler may select: RSS, and since 0.4.0 standard.site
734 /// publications. [`FeedKind::Unsupported`] is the kind it never selects.
735 ///
736 /// **This is the canonical home of the exclusion; the other sites point
737 /// here.** It used to be a SQL string predicate in `store`, carrying
738 /// its own copy of the rule — which is how one reader (`count_feeds`) came
739 /// to drift from it unnoticed.
740 ///
741 /// Why an unpollable kind is skipped rather than failed: an `Unsupported`
742 /// row names nothing either reader can fetch — another collection, a handle,
743 /// a non-canonical spelling — so polling it could only fail.
744 /// Handing such a row to the poller does not leave the feature dormant — it
745 /// manufactures one permanent failure per row, which the public cause
746 /// histogram then reports as an unreachable publisher. Unsupported is not
747 /// broken, and telling those apart is the entire reason a failure cause is
748 /// recorded. (Rows like this exist: subscriptions written by other clients
749 /// before this reader refused the scheme.)
750 ///
751 /// **`store::count_feeds` is deliberately NOT filtered by this.** The
752 /// global ceiling bounds storage on a small box, and an unpollable row
753 /// occupies a row, so it counts against the cap. An earlier version of this
754 /// note listed the readers without naming the exception, which read as
755 /// completeness it did not have: a review found the ceiling consuming
756 /// capacity that appeared on no surface, since `/stats` measures the poller
757 /// and excludes these rows. `/admin/metrics` renders
758 /// `store::unpollable_feeds` for exactly that reason.
759 /// **Adding a kind here makes a population of rows due all at once.**
760 /// `store::due_feeds` orders `next_poll IS NOT NULL, next_poll ASC`, so a
761 /// row with no scheduled poll sorts ahead of every dated one. Rows that
762 /// were never pollable have no schedule, so the boot that reclassifies
763 /// them hands the poller a block of N rows that outrank every regular
764 /// feed until they drain — `ceil(N / batch)` ticks, measured, during which
765 /// `/stats` shows a climbing backlog and nothing logs why. Bounded and
766 /// harmless at ninety feeds; not at ten thousand. Whoever wires the next
767 /// kind should seed or stagger `next_poll` for the rows it admits.
768 pub const POLLABLE: &'static [FeedKind] = &[FeedKind::Rss, FeedKind::Publication];
769
770 /// The kinds whose entries the retention **window** applies to.
771 ///
772 /// **Age is the wrong retention policy for an archive, and that is a
773 /// measurement, not a preference.** Three real publications, read through
774 /// `standard_site::fetch` on 2026-09-27: Standard.site's newest document was
775 /// **131 days** old, Annotated's **109** (with its oldest at 373), and minus
776 /// listens' **241**. Against the instance default window of 14 days, every
777 /// one of them stored **zero** rows — a green poll, an empty feed, and an
778 /// info log as the only trace. Long-form publishing is not news-paced.
779 ///
780 /// So a publication is bounded by COUNT instead: `max_entries_per_feed` in
781 /// `insert_entries`, which caps a feed at the newest N plus up to N starred.
782 /// That is a real bound — it is what keeps this from being "retention off" —
783 /// and it is the one that suits a source whose value is its archive.
784 ///
785 /// A generous absolute ceiling still applies (`publication_retention_days`),
786 /// because "not aged out" must not mean "immortal": rows belonging to a feed
787 /// nobody polls any more would otherwise never be reaped at all, and the
788 /// per-feed trim only runs when a poll stores something.
789 pub const AGED: &'static [FeedKind] = &[FeedKind::Rss];
790
791 /// The column value. Stable — it is persisted.
792 pub fn as_str(self) -> &'static str {
793 match self {
794 FeedKind::Rss => "rss",
795 FeedKind::Publication => "publication",
796 FeedKind::Unsupported => "unsupported",
797 }
798 }
799
800 /// A closed vocabulary on the way back in: a kind written by a newer build
801 /// is not silently read as one this build knows.
802 pub fn parse(raw: &str) -> Option<Self> {
803 match raw {
804 "rss" => Some(FeedKind::Rss),
805 "publication" => Some(FeedKind::Publication),
806 "unsupported" => Some(FeedKind::Unsupported),
807 _ => None,
808 }
809 }
810
811 /// What a URL will be stored as. The only place the question is asked.
812 ///
813 /// `store::feeds.kind` is a cache of this function, re-derived from the URL
814 /// on every start and on every upsert, so a change here needs no migration
815 /// and SQL cannot hold an opinion of its own about what a row is.
816 ///
817 /// **Case-insensitive on purpose.** An earlier version was case-sensitive,
818 /// with a test pinning that a mixed-case `At://` row IS handed to the
819 /// poller — reasoning that if Rust does not call it an at-URI, neither
820 /// should anything else. That was wrong in the direction that matters: URL
821 /// schemes are case-insensitive, so `Url::parse` folds `At://` to scheme
822 /// `at` and `net::check_scheme` refuses it (the DID form does not parse at
823 /// all). The row could only fail, every tick, forever, and be published in
824 /// the `fetch` bucket as an unreachable publisher. Storing a non-canonical
825 /// spelling is separately refused, because `feeds.url` is UNIQUE.
826 pub fn of(url: &str) -> Self {
827 match crate::atproto::strip_at_prefix(url) {
828 // **Only a URI the storage guard would accept is a publication.**
829 // Since publications became pollable, "it is an at-URI" is no longer
830 // a safe enough reason: another collection would be polled, fail,
831 // and back off forever while reading as an unreachable publisher.
832 // The canonical lowercase scheme too, for the same reason: storage
833 // refuses `At://` (#183), and a legacy row spelled that way would
834 // otherwise be polled and fail its parse every tick.
835 Some(rest) if url.starts_with("at://") && is_storable_publication_uri(rest) => {
836 FeedKind::Publication
837 }
838 Some(_) => FeedKind::Unsupported,
839 None => FeedKind::Rss,
840 }
841 }
842}
843
844/// Apply a [`PollOutcome`] to the feed's row: settle the error columns AND
845/// reschedule it. **Both halves, always, from one place.**
846///
847/// The scheduler did this inline. `web::add_subscription` then copied only the
848/// first half, so a poll taken off the scheduler could clear a stale failure's
849/// COUNT while leaving the feed parked on its stale backoff HORIZON — reported
850/// healthy, not polled for up to 24h. And its failures fed `consecutive_errors`
851/// with no reschedule, so repeated Subscribe clicks drove a shared feed to the
852/// 24h ceiling for every subscriber. Two copies of a sequence drift; this is
853/// the one copy.
854///
855/// `cadence` is the interval to use on success; the scheduler derives it from
856/// the feed's hint, a direct caller passes the configured default. A store
857/// failure is logged and the reschedule still attempted, so a hiccup writing
858/// the count cannot strand the feed at a NULL `next_poll` that `due_feeds`
859/// would then re-poll every tick.
860pub async fn settle_poll(
861 pool: &sqlx::SqlitePool,
862 url: &str,
863 outcome: &PollOutcome,
864 cadence: Duration,
865) {
866 let delay = match outcome {
867 // A 304 is a healthy poll: it proves the fetch worked and nothing changed.
868 PollOutcome::Updated { .. } | PollOutcome::NotModified => {
869 if let Err(err) = crate::store::reset_feed_errors(pool, url).await {
870 tracing::warn!(feed = %url, %err, "failed to reset feed error count");
871 }
872 cadence
873 }
874 PollOutcome::Failed {
875 backoff,
876 kind,
877 detail,
878 } => {
879 // Recompute from the feed's REAL consecutive-error count so a
880 // persistently-broken feed climbs toward the ceiling instead of
881 // retrying at the floor forever; fall back to the outcome's floor.
882 match crate::store::bump_feed_errors(pool, url, *kind, detail).await {
883 Ok(count) => backoff_for(count.max(1) as u32),
884 Err(err) => {
885 tracing::warn!(feed = %url, %err, "failed to bump feed error count; using floor backoff");
886 *backoff
887 }
888 }
889 }
890 };
891 if let Err(err) = crate::store::set_next_poll(pool, url, delay).await {
892 tracing::error!(feed = %url, %err, "failed to persist next_poll");
893 }
894}
895
896/// Cap on a failure detail, applied where the string is BUILT.
897///
898/// It was originally applied only inside `store::bump_feed_errors`, which
899/// bounded the database row and nothing else — and widening
900/// [`PollOutcome::Failed`] with this field had quietly opened a second sink:
901/// `web::add_subscription` logs `?outcome` at INFO on a user-facing request
902/// path. Bounding at construction bounds every sink, including ones added
903/// later by someone who never reads this comment.
904pub const MAX_FAILURE_DETAIL_CHARS: usize = 300;
905
906/// Render an error chain into a bounded [`PollOutcome::Failed`] detail.
907///
908/// `{e:#}` — the anyhow CHAIN, not just the outermost context. "fetching
909/// https://…" alone says nothing; the cause is the part that would have named
910/// the 304 bug in #159.
911pub fn failure_detail(err: impl std::fmt::Display) -> String {
912 let s = err.to_string();
913 if s.chars().count() <= MAX_FAILURE_DETAIL_CHARS {
914 return s;
915 }
916 s.chars().take(MAX_FAILURE_DETAIL_CHARS).collect()
917}
918
919impl FailureKind {
920 /// The stable string stored in `feeds.last_error_kind` and aggregated on
921 /// `/stats`. Changing one of these silently rewrites history in the
922 /// aggregate, so they are spelled out rather than derived from the variant.
923 pub fn as_str(self) -> &'static str {
924 match self {
925 Self::Fetch => "fetch",
926 Self::Status => "status",
927 Self::Body => "body",
928 Self::Parse => "parse",
929 }
930 }
931
932 /// Read back a persisted `last_error_kind`. `None` for anything this
933 /// version does not know, so a row written by a newer build is not
934 /// silently attributed to a cause this one recognises — the same contract
935 /// [`crate::metrics::Backend::parse`] keeps for the same reason.
936 pub fn parse(raw: &str) -> Option<Self> {
937 match raw {
938 "fetch" => Some(Self::Fetch),
939 "status" => Some(Self::Status),
940 "body" => Some(Self::Body),
941 "parse" => Some(Self::Parse),
942 _ => None,
943 }
944 }
945
946 /// Every variant, so a test can assert over the whole set rather than a
947 /// list that drifts when a variant is added.
948 pub const ALL: [Self; 4] = [Self::Fetch, Self::Status, Self::Body, Self::Parse];
949}
950
951/// Build a `reqwest::Client` configured for polite **and safe** feed fetching.
952///
953/// Callers should build this **once** and share it (connection pooling), then
954/// hand a reference to [`poll_feed`]. Kept here so the fetch policy (UA,
955/// timeout, redirect behaviour) lives with the code that depends on it.
956///
957/// Auto-redirect is **disabled** on purpose: feed URLs are untrusted, so
958/// redirects are followed manually by [`crate::net::guarded_get`], which
959/// re-validates the scheme + resolved IP of every hop (SSRF defence). A client
960/// that silently followed redirects could be bounced onto `169.254.169.254` or
961/// `127.0.0.1` between the guard's check and the connect.
962pub fn build_client() -> Result<Client> {
963 Client::builder()
964 .user_agent(crate::USER_AGENT)
965 .timeout(FETCH_TIMEOUT)
966 .read_timeout(READ_TIMEOUT)
967 // Ignore ambient proxy configuration, for the same reason the pinned
968 // client does: a proxied request hands the hostname to the proxy to
969 // resolve, so `net`'s IP checks never see the address they are meant to
970 // vet. See `net::build_pinned_client`.
971 .no_proxy()
972 // No auto-redirect: net::guarded_get follows + re-validates each hop.
973 .redirect(reqwest::redirect::Policy::none())
974 .build()
975 .context("failed to build feed HTTP client")
976}
977
978/// Compute the backoff for the `n`th consecutive failure (1-based), clamped to
979/// `BACKOFF_MAX`. Exponential in the error count so transient blips retry soon
980/// while a durably-broken feed backs off toward daily.
981///
982/// The scheduler passes the feed's persisted `consecutive_errors` count (see
983/// [`crate::store::bump_feed_errors`]) so a feed that keeps failing actually
984/// climbs toward `BACKOFF_MAX` instead of retrying at the floor forever.
985pub fn backoff_for(consecutive_errors: u32) -> Duration {
986 let n = consecutive_errors.max(1);
987 // Saturating shift: base * 2^(n-1), capped. Avoids overflow for large n.
988 let factor = 1u64.checked_shl(n.saturating_sub(1)).unwrap_or(u64::MAX);
989 let secs = BACKOFF_BASE
990 .as_secs()
991 .saturating_mul(factor)
992 .min(BACKOFF_MAX.as_secs());
993 Duration::from_secs(secs)
994}
995
996/// Poll one feed by **what it is**: an RSS/Atom/JSON document over HTTP, or a
997/// standard.site publication read from its author's PDS.
998///
999/// The single entry point the scheduler calls, so the choice of reader lives
1000/// with [`FeedKind`] and not in the poll loop. Same contract as [`poll_feed`]:
1001/// `Err` is a broken local store, never a misbehaving source.
1002pub async fn poll_feed_by_kind(
1003 pool: &SqlitePool,
1004 client: &Client,
1005 config: &crate::config::Config,
1006 feed: &Feed,
1007) -> Result<PollOutcome> {
1008 match FeedKind::of(&feed.url) {
1009 FeedKind::Rss => poll_feed(pool, client, feed, config.max_entries_per_feed).await,
1010 FeedKind::Publication => poll_publication(pool, client, config, feed).await,
1011 // Never selected: `due_feeds` reads only POLLABLE kinds. A defensive
1012 // failure rather than a panic if a caller hands one in anyway.
1013 FeedKind::Unsupported => Ok(PollOutcome::Failed {
1014 backoff: backoff_for(1),
1015 kind: FailureKind::Parse,
1016 detail: failure_detail(format!("{} is not a feed this reader can poll", feed.url)),
1017 }),
1018 }
1019}
1020
1021/// What a failed publication read is filed under in the cause histogram.
1022///
1023/// **`Fetch` means the request never produced a response**, so it is the
1024/// fallback, not the default answer: a PLC directory or PDS that answered —
1025/// with a 404 for a tombstoned DID, `RepoNotFound`, `RepoDeactivated` — is
1026/// `Status`, and an answer that was not what it claimed to be is `Parse`. Filed
1027/// as `Fetch`, a deleted account read as its server being down (found in
1028/// review).
1029fn publication_failure_kind(err: &anyhow::Error) -> FailureKind {
1030 use crate::atproto::{AtProtoError, DidResolutionCause};
1031 for cause in err.chain() {
1032 if cause.is::<crate::standard_site::NotAPublication>() || cause.is::<serde_json::Error>() {
1033 return FailureKind::Parse;
1034 }
1035 match cause.downcast_ref::<AtProtoError>() {
1036 Some(AtProtoError::Xrpc { .. }) => return FailureKind::Status,
1037 Some(AtProtoError::DidResolution { cause, .. }) => {
1038 return match cause {
1039 DidResolutionCause::Status => FailureKind::Status,
1040 DidResolutionCause::UnsupportedMethod | DidResolutionCause::NoPdsEndpoint => {
1041 FailureKind::Parse
1042 }
1043 DidResolutionCause::NotAPublicTarget => FailureKind::Fetch,
1044 }
1045 }
1046 _ => {}
1047 }
1048 }
1049 FailureKind::Fetch
1050}
1051
1052/// Read a standard.site publication from its author's PDS and store it.
1053///
1054/// A source failure — an unparseable URI, an unreachable PLC directory or
1055/// PDS, a walk that failed — is a [`PollOutcome::Failed`] with backoff, like an
1056/// RSS fetch failure, so `settle_poll` and `/stats` treat both kinds alike.
1057/// Only a broken local store is an `Err`, which `store_publication` decides.
1058async fn poll_publication(
1059 pool: &SqlitePool,
1060 client: &Client,
1061 config: &crate::config::Config,
1062 feed: &Feed,
1063) -> Result<PollOutcome> {
1064 poll_publication_group(pool, client, config, std::slice::from_ref(feed))
1065 .await
1066 .pop()
1067 .unwrap_or_else(|| Err(anyhow::anyhow!("no outcome for {}", feed.url)))
1068}
1069
1070/// Read several publications **from one repo** with one walk of its documents
1071/// (`standard_site::fetch_repo`), and store each. One outcome per feed, in
1072/// order. The caller groups by repo; a feed from another repo, or one whose
1073/// URL is not a publication URI, gets its own failure and does not affect the
1074/// rest.
1075///
1076/// **Why one walk:** cost scales with the repo, not the publication. Nine
1077/// publications in one repo were nine full walks of its documents.
1078pub async fn poll_publication_group(
1079 pool: &SqlitePool,
1080 client: &Client,
1081 config: &crate::config::Config,
1082 feeds: &[Feed],
1083) -> Vec<Result<PollOutcome>> {
1084 let failed = |kind: FailureKind, detail: String| -> Result<PollOutcome> {
1085 Ok(PollOutcome::Failed {
1086 backoff: backoff_for(1),
1087 kind,
1088 detail: failure_detail(detail),
1089 })
1090 };
1091 let uris: Vec<Option<crate::standard_site::AtUri>> = feeds
1092 .iter()
1093 .map(|f| crate::standard_site::AtUri::parse(&f.url))
1094 .collect();
1095 let Some(did) = uris.iter().flatten().next().map(|u| u.authority.clone()) else {
1096 return feeds
1097 .iter()
1098 .map(|f| {
1099 failed(
1100 FailureKind::Parse,
1101 format!("{} is not a readable at:// URI", f.url),
1102 )
1103 })
1104 .collect();
1105 };
1106 // Only the feeds of that repo with a publication URI are read together.
1107 let readable: Vec<usize> = (0..feeds.len())
1108 .filter(|&i| {
1109 uris[i].as_ref().is_some_and(|u| {
1110 u.authority == did && u.collection == crate::lexicon::nsid::STANDARD_PUBLICATION
1111 })
1112 })
1113 .collect();
1114 let rkeys: Vec<String> = readable
1115 .iter()
1116 .map(|&i| uris[i].as_ref().unwrap().rkey.clone())
1117 .collect();
1118
1119 // **One deadline for the whole read.** It is otherwise bounded only per
1120 // request (FETCH_TIMEOUT x MAX_LIST_PAGES): hours, against a repo that
1121 // pages slowly, all of it holding up the publication loop.
1122 let fetched = tokio::time::timeout(
1123 config.publication_read_deadline,
1124 crate::standard_site::fetch_repo(client, &config.oauth.plc_directory, &did, &rkeys),
1125 )
1126 .await;
1127 let mut reads: Vec<Option<anyhow::Result<crate::standard_site::PublicationRead>>> =
1128 feeds.iter().map(|_| None).collect();
1129 let repo_failure = match fetched {
1130 Ok(Ok(per)) => {
1131 for (slot, read) in readable.iter().zip(per) {
1132 reads[*slot] = Some(read);
1133 }
1134 None
1135 }
1136 Ok(Err(err)) => Some((publication_failure_kind(&err), format!("{err:#}"))),
1137 Err(_) => Some((
1138 FailureKind::Fetch,
1139 format!(
1140 "the read did not finish within {:?}",
1141 config.publication_read_deadline
1142 ),
1143 )),
1144 };
1145
1146 let (retention_days, retention_hard_days) = config.retention_for(FeedKind::Publication);
1147 let mut out = Vec::with_capacity(feeds.len());
1148 for (i, feed) in feeds.iter().enumerate() {
1149 let outcome = match (reads[i].take(), &repo_failure) {
1150 (Some(Ok(read)), _) => {
1151 crate::standard_site::store_publication(
1152 pool,
1153 &feed.url,
1154 read,
1155 config.max_entries_per_feed,
1156 retention_days,
1157 retention_hard_days,
1158 )
1159 .await
1160 }
1161 (Some(Err(err)), _) => failed(publication_failure_kind(&err), format!("{err:#}")),
1162 (None, Some((kind, detail))) if readable.contains(&i) => failed(*kind, detail.clone()),
1163 (None, _) => failed(
1164 FailureKind::Parse,
1165 format!("{} is not a publication in {did}", feed.url),
1166 ),
1167 };
1168 out.push(outcome);
1169 }
1170 out
1171}
1172
1173/// Fetch, parse, sanitize, normalize, and store a single feed.
1174///
1175/// Performs a conditional GET using the feed's stored `ETag` / `Last-Modified`.
1176/// On `304` it returns [`PollOutcome::NotModified`] without touching entries. On
1177/// `200` it parses with `feed-rs`, sanitizes every entry's HTML with `ammonia`,
1178/// upserts the feed row (carrying the fresh validators) and inserts new entries
1179/// (deduped by GUID). Any fetch/parse error is logged and returned as
1180/// [`PollOutcome::Failed`] — it never panics and never propagates as `Err` for
1181/// a merely-broken feed, so one bad publisher can't stall the scheduler.
1182///
1183/// `Err` is reserved for *store* failures (a broken local DB is a real error the
1184/// caller should see), not for feed misbehaviour.
1185///
1186/// `max_entries_per_feed` caps how many entries this feed retains after insert
1187/// (newest N by published date); `<= 0` disables the per-feed trim.
1188pub async fn poll_feed(
1189 pool: &SqlitePool,
1190 client: &Client,
1191 feed: &Feed,
1192 max_entries_per_feed: i64,
1193) -> Result<PollOutcome> {
1194 // --- conditional GET (through the SSRF guard) ----------------------------
1195 // The guard re-validates the scheme + resolved IP of the target and of every
1196 // redirect hop, so a subscribed feed can't bounce the poller onto an
1197 // internal address (cloud metadata / loopback). Conditional-GET validators
1198 // ride along as extra headers.
1199 let mut extra: Vec<(reqwest::header::HeaderName, reqwest::header::HeaderValue)> = Vec::new();
1200 if let Some(etag) = feed.etag.as_deref() {
1201 if let Ok(v) = reqwest::header::HeaderValue::from_str(etag) {
1202 extra.push((IF_NONE_MATCH, v));
1203 }
1204 }
1205 if let Some(lm) = feed.last_modified.as_deref() {
1206 if let Ok(v) = reqwest::header::HeaderValue::from_str(lm) {
1207 extra.push((IF_MODIFIED_SINCE, v));
1208 }
1209 }
1210
1211 let resp = match crate::net::guarded_get(client, &feed.url, &extra).await {
1212 Ok(r) => r,
1213 Err(e) => {
1214 tracing::warn!(feed = %feed.url, error = %e, "feed fetch failed (or blocked by SSRF guard)");
1215 return Ok(PollOutcome::Failed {
1216 backoff: backoff_for(1),
1217 kind: FailureKind::Fetch,
1218 detail: failure_detail(format!("{e:#}")),
1219 });
1220 }
1221 };
1222
1223 let status = resp.status();
1224 if status == StatusCode::NOT_MODIFIED {
1225 tracing::debug!(feed = %feed.url, "feed not modified (304)");
1226 // Bump last_polled/next_poll only; leave validators + entries untouched.
1227 touch_polled(pool, &feed.url, None, None)
1228 .await
1229 .with_context(|| format!("touch_polled after 304 for {}", feed.url))?;
1230 return Ok(PollOutcome::NotModified);
1231 }
1232 if !status.is_success() {
1233 tracing::warn!(feed = %feed.url, %status, "feed returned non-success status");
1234 return Ok(PollOutcome::Failed {
1235 backoff: backoff_for(1),
1236 kind: FailureKind::Status,
1237 detail: failure_detail(status),
1238 });
1239 }
1240
1241 // Capture validators for the *next* conditional GET before consuming body.
1242 let new_etag = header_str(resp.headers().get(ETAG));
1243 let new_last_modified = header_str(resp.headers().get(LAST_MODIFIED));
1244
1245 // Stream the body with a hard byte cap, aborting mid-stream if it exceeds
1246 // it. We never trust Content-Length: reqwest's gzip layer strips it, so a
1247 // small gzip bomb could otherwise inflate to GBs before any size check.
1248 let body = match crate::net::read_capped(resp).await {
1249 Ok(b) => b,
1250 Err(e) => {
1251 tracing::warn!(feed = %feed.url, error = %e, "feed body rejected (too large / read error)");
1252 return Ok(PollOutcome::Failed {
1253 backoff: backoff_for(1),
1254 kind: FailureKind::Body,
1255 detail: failure_detail(format!("{e:#}")),
1256 });
1257 }
1258 };
1259
1260 // --- parse (malformed feed => log + skip, never panic) -------------------
1261 let parsed = match feed_rs::parser::parse(&body[..]) {
1262 Ok(f) => f,
1263 Err(e) => {
1264 tracing::warn!(feed = %feed.url, error = %e, "malformed feed; skipping");
1265 return Ok(PollOutcome::Failed {
1266 backoff: backoff_for(1),
1267 kind: FailureKind::Parse,
1268 detail: failure_detail(format!("{e:#}")),
1269 });
1270 }
1271 };
1272
1273 // --- normalize + sanitize ------------------------------------------------
1274 let (title, site_url) = feed_metadata(&parsed);
1275 let new_feed = NewFeed {
1276 url: feed.url.clone(),
1277 title,
1278 site_url,
1279 etag: new_etag,
1280 last_modified: new_last_modified,
1281 last_polled: Some(now_rfc3339()),
1282 next_poll: None, // the scheduler owns cadence; leave it to set next_poll.
1283 };
1284
1285 let entries: Vec<NewEntry> = parsed.entries.iter().map(normalize_entry).collect();
1286
1287 // --- store (a store failure IS a real error) -----------------------------
1288 let feed_id = store::upsert_feed(pool, &new_feed)
1289 .await
1290 .with_context(|| format!("upsert_feed for {}", feed.url))?;
1291 let n = store::insert_entries(pool, feed_id, &entries, max_entries_per_feed)
1292 .await
1293 .with_context(|| format!("insert_entries for {}", feed.url))?;
1294
1295 tracing::info!(feed = %feed.url, entries = n, "feed polled");
1296 Ok(PollOutcome::Updated { new_entries: n })
1297}
1298
1299/// Bump `last_polled` (and optionally validators) without changing entries —
1300/// used on the `304 Not Modified` path.
1301async fn touch_polled(
1302 pool: &SqlitePool,
1303 url: &str,
1304 etag: Option<String>,
1305 last_modified: Option<String>,
1306) -> Result<()> {
1307 // `None` means "keep current" — upsert_feed COALESCEs the validators, so a
1308 // 304 that repeats no headers leaves the stored ones untouched. This used to
1309 // re-read the row and re-supply them by hand because the upsert clobbered
1310 // unconditionally; the read-modify-write is gone now that the upsert is
1311 // honest, and with it a race where a concurrent poll's validators could be
1312 // read here and written back stale.
1313 let nf = NewFeed {
1314 url: url.to_string(),
1315 etag,
1316 last_modified,
1317 last_polled: Some(now_rfc3339()),
1318 ..Default::default()
1319 };
1320 store::upsert_feed(pool, &nf).await?;
1321 Ok(())
1322}
1323
1324/// Extract `(title, site_url)` from a parsed feed. `site_url` prefers an
1325/// `alternate`/no-rel HTML link over the feed's self link.
1326fn feed_metadata(parsed: &RawFeed) -> (Option<String>, Option<String>) {
1327 let title = parsed
1328 .title
1329 .as_ref()
1330 .map(|t| bound_text(text_plain(t), MAX_TITLE_BYTES));
1331 let site_url = parsed
1332 .links
1333 .iter()
1334 // Prefer an explicit human-facing page: rel="alternate" or no rel at all.
1335 .find(|l| {
1336 l.rel.as_deref() == Some("alternate")
1337 || (l.rel.is_none()
1338 && l.media_type.as_deref() != Some("application/rss+xml")
1339 && l.media_type.as_deref() != Some("application/atom+xml"))
1340 })
1341 .or_else(|| {
1342 parsed
1343 .links
1344 .iter()
1345 .find(|l| l.rel.as_deref() != Some("self"))
1346 })
1347 .or_else(|| parsed.links.first())
1348 .map(|l| bound_text(l.href.clone(), MAX_URL_BYTES));
1349 (title, site_url)
1350}
1351
1352/// Turn a parsed [`RawEntry`] into the store's [`NewEntry`], sanitizing HTML.
1353///
1354/// Content preference: full `content` body, else `summary`. Whichever is chosen
1355/// is **always** passed through [`sanitize_html`] before storage. GUID falls
1356/// back to the entry link, then to a stable hash of title+link, so an entry
1357/// missing an `id` still deduplicates instead of being re-inserted forever.
1358fn normalize_entry(e: &RawEntry) -> NewEntry {
1359 let url = entry_link(e);
1360 let content_html = e
1361 .content
1362 .as_ref()
1363 .and_then(|c| c.body.as_deref())
1364 .or_else(|| e.summary.as_ref().map(|t| t.content.as_str()))
1365 .map(|raw| sanitize_html_bounded(raw, MAX_CONTENT_HTML_BYTES));
1366
1367 // GUID may use the raw link (dedup key only, never rendered), so prefer the
1368 // entry's first raw link for identity even when it's not a safe href.
1369 let guid = if !e.id.trim().is_empty() {
1370 e.id.trim().to_string()
1371 } else if let Some(link) = raw_entry_link(e) {
1372 link
1373 } else {
1374 // Last resort: derive a stable id so re-fetches dedup rather than dupe.
1375 stable_guid(e)
1376 };
1377
1378 NewEntry {
1379 guid: bound_guid(guid),
1380 url: url.map(|u| bound_text(u, MAX_URL_BYTES)),
1381 title: e
1382 .title
1383 .as_ref()
1384 .map(|t| bound_text(text_plain(t), MAX_TITLE_BYTES)),
1385 author: entry_author(e).map(|a| bound_text(a, MAX_AUTHOR_BYTES)),
1386 published: entry_time(e),
1387 content_html,
1388 fetched_at: None, // store defaults to "now".
1389 }
1390}
1391
1392/// The raw best-permalink URL for an entry (no scheme filtering) — used only as
1393/// a dedup GUID, never rendered as an href.
1394fn raw_entry_link(e: &RawEntry) -> Option<String> {
1395 e.links
1396 .iter()
1397 .find(|l| l.rel.as_deref() == Some("alternate") || l.rel.is_none())
1398 .or_else(|| e.links.first())
1399 .map(|l| l.href.clone())
1400}
1401
1402/// The best display/permalink URL for an entry, **scheme-allow-listed** so it is
1403/// safe to render as an `href`: prefer `rel="alternate"` or a no-rel link, else
1404/// the first link — but only if it is an `http`/`https` URL. A `javascript:` or
1405/// `data:` permalink (a stored-XSS vector that survives HTML escaping, since it
1406/// carries no HTML-special characters) is dropped here at ingest, before it can
1407/// ever reach the store or a template.
1408fn entry_link(e: &RawEntry) -> Option<String> {
1409 raw_entry_link(e).and_then(|href| crate::net::safe_link(&href))
1410}
1411
1412/// First author name, if any.
1413fn entry_author(e: &RawEntry) -> Option<String> {
1414 e.authors.first().map(|p| p.name.clone())
1415}
1416
1417/// Best CREDIBLE publication time (published, else updated) as an RFC3339
1418/// string, or `None` when neither is credible.
1419///
1420/// **A date in the future is discarded, not clamped, and not stored.** There was
1421/// no upper bound here, so an item dated in the year 2999 was stored verbatim
1422/// and became permanent: both retention sweeps test
1423/// `COALESCE(published, fetched_at) < cutoff` and a future date is never less
1424/// than either, the per-feed keep-set orders on the same expression `DESC` where
1425/// it is rank one forever, and every list view puts it at the top. A publisher
1426/// with a broken clock does that by accident; anyone wanting a permanent slot at
1427/// the top of a reader's list does it on purpose.
1428///
1429/// Discarded rather than clamped to now because the entry upsert refreshes
1430/// `published` on every poll while stamping `fetched_at` once — so a value
1431/// derived from the current clock is rewritten every cycle and the row can never
1432/// age at all. Clamping relocates the defect. Undated is the honest answer, and
1433/// `fetched_at` then dates the row and holds still. That is the rule the
1434/// publication path already follows; see `standard_site::entries_from_records`.
1435///
1436/// **Each candidate is judged separately**, so a bogus `<published>` beside a
1437/// credible `<updated>` keeps the good date. That helps Atom and only Atom: for
1438/// RSS 2 `feed-rs` copies `published` into `updated` when `updated` is absent
1439/// (`parser/rss2/mod.rs`), so the second candidate holds the same value and the
1440/// fall-through is a no-op. Worth keeping for the format where two independent
1441/// dates exist; worth not overstating for the one where they do not.
1442///
1443/// **The ceiling is [`MAX_FUTURE_PUBLISHED_DAYS`], NOT the publication path's
1444/// clock-skew grace, and the asymmetry is deliberate.** There, a refused
1445/// `publishedAt` falls back to the record key's TID — the real write time, a
1446/// credible date — so a five-minute bound costs almost nothing. Here there is no
1447/// such fallback: refusing leaves the entry undated and the reader sees no date
1448/// at all. Five minutes is sized for skew between two clocks, while the ordinary
1449/// cause of a future `pubDate` is a local time stamped `+0000` (up to 14 hours
1450/// out, the widest real UTC offset) or a post scheduled a little ahead. Those are
1451/// dates worth keeping, and they stop being future on their own.
1452///
1453/// What the bound must prevent is a date that can never become past, because that
1454/// is what makes a row permanently unsweepable, un-evictable and first in the
1455/// list.
1456fn entry_time(e: &RawEntry) -> Option<String> {
1457 let ceiling = Utc::now() + chrono::Duration::days(MAX_FUTURE_PUBLISHED_DAYS);
1458 e.published
1459 .filter(|d| *d <= ceiling)
1460 .or_else(|| e.updated.filter(|d| *d <= ceiling))
1461 .map(fmt_time)
1462}
1463
1464/// How far ahead of now a feed may date an entry before [`entry_time`] refuses
1465/// the date and lets `fetched_at` stand in.
1466///
1467/// Two days: the widest real UTC offset is +14:00, so a local time mislabelled as
1468/// UTC lands inside this, as does a post scheduled slightly ahead. Both are dates
1469/// worth keeping, and both stop being future without help. Anything further is
1470/// refused, because a date that never becomes past is what makes a row
1471/// permanently unsweepable and permanently first in the reading list.
1472pub(crate) const MAX_FUTURE_PUBLISHED_DAYS: i64 = 2;
1473
1474/// Extract the plain string content of a feed [`Text`] node.
1475fn text_plain(t: &Text) -> String {
1476 t.content.trim().to_string()
1477}
1478
1479/// Sanitize hostile feed **HTML** with ammonia's whitelist cleaner. Applied to
1480/// every RSS/Atom entry body unconditionally, because every one of them is
1481/// markup.
1482///
1483/// **Not for plain text.** An earlier version of this comment claimed it was
1484/// "safe on plain text too (it will simply escape/strip as needed)". It is
1485/// not: `clean` PARSES its input, so a bare `<` in prose swallows the rest —
1486/// `"if x<y then z"` comes back as `"if x"`. That sentence is how a
1487/// plain-text field got run through here once already. Use
1488/// [`plain_text_to_html`].
1489pub(crate) fn sanitize_html(raw: &str) -> String {
1490 ammonia::clean(raw)
1491}
1492
1493/// Render **plain text** into the HTML the `content_html` column holds.
1494///
1495/// **Not [`sanitize_html`].** `ammonia::clean` parses its input as markup, so a
1496/// bare `<` in prose swallows the rest: measured here, `"if x<y then z"` comes
1497/// back as `"if x"`. That is correct for an RSS body, which IS markup, and
1498/// silent data loss for a field a lexicon defines as text. Escape first, then
1499/// add the only markup this needs — line breaks, which the column's consumer
1500/// renders as HTML and would otherwise collapse.
1501pub(crate) fn plain_text_to_html(raw: &str) -> String {
1502 let escaped = raw
1503 .replace('&', "&")
1504 .replace('<', "<")
1505 .replace('>', ">");
1506 // Safe by order: every `<` from the input is already `<` before this
1507 // adds a real tag.
1508 escaped.replace('\n', "<br>")
1509}
1510
1511/// **What one entry, or one feed row, may store per field (#205).**
1512///
1513/// Every field below arrives from someone else's server — an RSS document or a
1514/// publisher's `site.standard.document` record — and nothing between the wire
1515/// and SQLite used to shorten it. A title could be megabytes, then indexed, read
1516/// back and rendered into every list view of that feed.
1517///
1518/// Chosen from measurement, not guessed. Production's 4,389 entries on
1519/// 2026-10-03: title max 253 bytes (p99 148), url max 235 (p99 178), author max
1520/// 26, content_html max 86,969 (p99 17,535). Each bound is at least 8x the
1521/// largest real value, so no ordinary article is touched; `MAX_TITLE_BYTES` is
1522/// `site.standard.document`'s own `title.maxLength`.
1523///
1524/// **Truncated, never refused.** Dropping an article because one field is long
1525/// is the failure mode the retention work was careful to avoid.
1526pub(crate) const MAX_TITLE_BYTES: usize = 5_000;
1527/// See [`MAX_TITLE_BYTES`].
1528pub(crate) const MAX_AUTHOR_BYTES: usize = 1_000;
1529/// See [`MAX_TITLE_BYTES`]. A truncated URL is a broken link, which was judged
1530/// better than no link; at 35x the longest real one it should never happen.
1531pub(crate) const MAX_URL_BYTES: usize = 8_192;
1532/// See [`MAX_TITLE_BYTES`]. Applies to the STORED HTML, after sanitizing or
1533/// escaping — see [`sanitize_html_bounded`] for why that is the bound that matters.
1534pub(crate) const MAX_CONTENT_HTML_BYTES: usize = 2 * 1024 * 1024;
1535/// An entry id longer than this is replaced by a stable hash of the whole id
1536/// (see [`bound_guid`]): it is the dedup key, under a UNIQUE index.
1537pub(crate) const MAX_GUID_BYTES: usize = 2_048;
1538
1539/// The largest index `<= at` that is a character boundary of `s`.
1540fn floor_char_boundary(s: &str, at: usize) -> usize {
1541 if at >= s.len() {
1542 return s.len();
1543 }
1544 (0..=at).rev().find(|&i| s.is_char_boundary(i)).unwrap_or(0)
1545}
1546
1547/// `s` cut to at most `max` bytes, on a character boundary. Plain-text fields
1548/// only: cutting markup or an escaped string here could split a tag or an
1549/// entity, which is what [`sanitize_html_bounded`] and [`plain_text_to_html_bounded`] exist for.
1550pub(crate) fn bound_text(mut s: String, max: usize) -> String {
1551 let cut = floor_char_boundary(&s, max);
1552 s.truncate(cut);
1553 s
1554}
1555
1556/// Plain text escaped into `content_html`, cut so the **output** fits `max`.
1557///
1558/// **Exact, in one pass.** Escaping is a fixed size per character (`&` is
1559/// five bytes, `<` and `>` four, a newline `<br>` four, anything else its UTF-8
1560/// length), so the longest prefix whose escaped form fits is found by adding
1561/// those up — no rendering, no search. Three rounds of review found bugs in a
1562/// generic re-render search that this replaces (#224).
1563pub(crate) fn plain_text_to_html_bounded(raw: &str, max: usize) -> String {
1564 let mut size = 0usize;
1565 let mut cut = raw.len();
1566 for (i, c) in raw.char_indices() {
1567 let escaped = match c {
1568 '&' => 5,
1569 '<' | '>' | '\n' => 4,
1570 c => c.len_utf8(),
1571 };
1572 if size + escaped > max {
1573 cut = i;
1574 break;
1575 }
1576 size += escaped;
1577 }
1578 plain_text_to_html(&raw[..cut])
1579}
1580
1581/// Feed HTML sanitized into `content_html`, cut so the **output** fits `max`.
1582///
1583/// **Sanitize once, then cut the sanitized output, not the input.** Cutting
1584/// the input made the result depend on how much of it the sanitizer would
1585/// strip — a large `data:` image, `<style>` or unterminated comment — and the
1586/// searches that tried to account for that kept nothing, or ran for hours, in
1587/// review (#224). Sanitized HTML is already clean: cutting it on a character
1588/// boundary and sanitizing that prefix again only closes the tags the cut left
1589/// open, so the second pass usually grows it by little. The first cut leaves a
1590/// margin for that growth; deeply nested markup, whose closers can outgrow any
1591/// margin, falls through to a bounded bisection.
1592///
1593/// Cost: the first sanitize is the one every body always had; the bounded
1594/// passes — one, or at most 1 + [`SANITIZE_BOUND_ATTEMPTS`] — run on at most
1595/// `max` bytes of already-clean HTML, and only for a body over the bound.
1596pub(crate) fn sanitize_html_bounded(raw: &str, max: usize) -> String {
1597 let clean = sanitize_html(raw);
1598 if clean.len() <= max {
1599 return clean;
1600 }
1601 // First, the cut that almost always works: just under the bound, with a
1602 // margin for the closers the cut leaves open. When it fits, that is the
1603 // answer — within 1/64 of the bound, in one extra pass.
1604 let margin = (max / 64).max(64);
1605 let first = floor_char_boundary(&clean, max.saturating_sub(margin));
1606 let again = sanitize_html(&clean[..first]);
1607 if again.len() <= max {
1608 return again;
1609 }
1610 // **Then a bounded bisection, not a widening margin.** A closing tag is
1611 // longer than the tag it opens, so a cut through deeply nested markup can
1612 // grow past the bound by more than any fixed margin; widening the margin
1613 // 4x a round reached a cut of 0 and stored nothing where nearly all of it
1614 // fit (found in review). `lo` always fits (the empty prefix does), `hi`
1615 // never does, and the next probe is taken AFTER they move.
1616 let (mut lo, mut hi) = (0usize, first);
1617 let mut best = String::new();
1618 let resolution = (max / 1024).max(1);
1619 for _ in 0..SANITIZE_BOUND_ATTEMPTS {
1620 if hi - lo <= resolution {
1621 break;
1622 }
1623 let mut cut = floor_char_boundary(&clean, lo + (hi - lo) / 2);
1624 if cut <= lo {
1625 // A multi-byte character straddles the midpoint: step past it
1626 // rather than give up.
1627 cut = ceil_char_boundary(&clean, lo + 1);
1628 if cut >= hi {
1629 break;
1630 }
1631 }
1632 let out = sanitize_html(&clean[..cut]);
1633 if out.len() <= max {
1634 lo = cut;
1635 best = out;
1636 } else {
1637 hi = cut;
1638 }
1639 }
1640 best
1641}
1642
1643/// The smallest index `>= at` that is a character boundary of `s`.
1644fn ceil_char_boundary(s: &str, at: usize) -> usize {
1645 (at..=s.len())
1646 .find(|&i| s.is_char_boundary(i))
1647 .unwrap_or(s.len())
1648}
1649
1650/// The most bisection passes [`sanitize_html_bounded`] spends after its first
1651/// cut: enough to resolve a 2 MiB bound to about 1/1024 of it.
1652const SANITIZE_BOUND_ATTEMPTS: usize = 14;
1653
1654/// An entry id, or a stable stand-in for one too long to index.
1655///
1656/// The id is the dedup key under `UNIQUE (feed_id, guid)`, so truncating it
1657/// would merge distinct entries that share a long prefix. A hash of the WHOLE
1658/// id keeps them apart and keeps the same entry deduplicating across polls —
1659/// the same construction as [`stable_guid`].
1660pub(crate) fn bound_guid(guid: String) -> String {
1661 if guid.len() <= MAX_GUID_BYTES {
1662 return guid;
1663 }
1664 use std::hash::{Hash, Hasher};
1665 let mut h = std::collections::hash_map::DefaultHasher::new();
1666 guid.hash(&mut h);
1667 format!("featherreader:long-guid:{:016x}", h.finish())
1668}
1669
1670/// Format a chrono timestamp as RFC3339 (UTC, seconds precision) to match the
1671/// store's string columns.
1672pub(crate) fn fmt_time(dt: DateTime<Utc>) -> String {
1673 dt.to_rfc3339_opts(SecondsFormat::Secs, true)
1674}
1675
1676/// "Now" in the store's RFC3339 shape.
1677fn now_rfc3339() -> String {
1678 Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true)
1679}
1680
1681/// A stable GUID derived from an entry's title + first link, for feeds that
1682/// supply neither an id nor a usable link id. Deterministic so re-fetches dedup.
1683fn stable_guid(e: &RawEntry) -> String {
1684 use std::hash::{Hash, Hasher};
1685 let mut h = std::collections::hash_map::DefaultHasher::new();
1686 e.title.as_ref().map(|t| t.content.as_str()).hash(&mut h);
1687 e.links.first().map(|l| l.href.as_str()).hash(&mut h);
1688 e.summary.as_ref().map(|s| s.content.as_str()).hash(&mut h);
1689 format!("featherreader:synthetic:{:016x}", h.finish())
1690}
1691
1692/// Decode an HTTP header value to an owned `String`, dropping non-UTF-8 values.
1693fn header_str(v: Option<&reqwest::header::HeaderValue>) -> Option<String> {
1694 v.and_then(|h| h.to_str().ok()).map(str::to_string)
1695}
1696
1697/// Discover a feed URL from a site's HTML via
1698/// `<link rel="alternate" type="application/rss+xml|atom+xml" href="…">`.
1699///
1700/// Returns the first RSS/Atom autodiscovery link found, resolved against the
1701/// page URL if the `href` is relative. This is what lets a user paste a *site*
1702/// URL and have FeatherReader find the actual feed ("subscribe by URL").
1703/// Returns `None` if the HTML carries no autodiscovery link.
1704///
1705/// The `base` is the URL the HTML was fetched from, used to resolve relative
1706/// `href`s. Pass `None` to only accept absolute hrefs.
1707pub fn discover_feed(site_html: &str, base: Option<&Url>) -> Option<Url> {
1708 // Parse the HTML with html5ever (via ammonia's dependency graph is separate;
1709 // use a light hand-rolled scan over <link> tags to avoid a new dependency).
1710 // We look for <link ...> elements whose rel contains "alternate" and whose
1711 // type is an RSS/Atom feed media type, and take the href.
1712 for tag in link_tags(site_html) {
1713 let rel = attr(&tag, "rel").unwrap_or_default().to_ascii_lowercase();
1714 let typ = attr(&tag, "type").unwrap_or_default().to_ascii_lowercase();
1715 let is_feed_type = typ.contains("application/rss+xml")
1716 || typ.contains("application/atom+xml")
1717 || typ.contains("application/feed+json")
1718 || typ.contains("application/json");
1719 // rel="alternate" is the standard; be lenient and also accept a bare
1720 // feed type with any rel, but require the feed media type either way.
1721 let rel_ok = rel.split_whitespace().any(|r| r == "alternate") || rel.is_empty();
1722 if is_feed_type && rel_ok {
1723 if let Some(href) = attr(&tag, "href") {
1724 let href = href.trim();
1725 if href.is_empty() {
1726 continue;
1727 }
1728 // Absolute URL wins directly; otherwise resolve against `base`.
1729 // Either way, only http(s): the href is publisher-controlled and
1730 // `Url::parse` accepts any scheme, so this is where an `at://`
1731 // (or `file:`, `javascript:`) alternate would otherwise become
1732 // the URL the add path stores — after its input gate has run.
1733 // Skip, don't stop: a later real feed link still wins.
1734 let resolved = match Url::parse(href) {
1735 Ok(u) => Some(u),
1736 Err(_) => base.and_then(|b| b.join(href).ok()),
1737 };
1738 match resolved {
1739 Some(u) if matches!(u.scheme(), "http" | "https") => return Some(u),
1740 _ => continue,
1741 }
1742 }
1743 }
1744 }
1745 None
1746}
1747
1748/// Extract the raw text of every `<link ...>` tag (self-closing or not) from an
1749/// HTML string. A deliberately small, allocation-light scan — feed
1750/// autodiscovery does not need a full DOM, and avoiding one keeps the dependency
1751/// surface minimal (design bias: boring, small-dependency).
1752fn link_tags(html: &str) -> Vec<String> {
1753 let mut out = Vec::new();
1754 let bytes = html.as_bytes();
1755 let lower = html.to_ascii_lowercase();
1756 let mut search_from = 0usize;
1757 while let Some(rel_idx) = lower[search_from..].find("<link") {
1758 let start = search_from + rel_idx;
1759 // Ensure it's a tag boundary ("<link" followed by whitespace, '>' or '/').
1760 let after = bytes.get(start + 5).copied();
1761 let boundary = matches!(after, Some(b) if b == b' ' || b == b'\t' || b == b'\n' || b == b'\r' || b == b'>' || b == b'/');
1762 if !boundary {
1763 search_from = start + 5;
1764 continue;
1765 }
1766 // Find the closing '>' for this tag.
1767 if let Some(end_rel) = html[start..].find('>') {
1768 let end = start + end_rel;
1769 out.push(html[start..=end].to_string());
1770 search_from = end + 1;
1771 } else {
1772 break;
1773 }
1774 }
1775 out
1776}
1777
1778/// Read an attribute value from a single tag string, handling both single- and
1779/// double-quoted values. Case-insensitive attribute name match.
1780fn attr(tag: &str, name: &str) -> Option<String> {
1781 let lower = tag.to_ascii_lowercase();
1782 let needle = format!("{name}=");
1783 let mut from = 0usize;
1784 while let Some(rel) = lower[from..].find(&needle) {
1785 let name_start = from + rel;
1786 // Guard against matching a suffix of a longer attribute name
1787 // (e.g. matching "type=" inside "mytype="): the char before must be a
1788 // tag/whitespace boundary.
1789 let ok_prefix = name_start == 0
1790 || matches!(
1791 tag.as_bytes().get(name_start - 1),
1792 Some(b' ') | Some(b'\t') | Some(b'\n') | Some(b'\r') | Some(b'<')
1793 );
1794 let val_start = name_start + needle.len();
1795 if !ok_prefix {
1796 from = val_start;
1797 continue;
1798 }
1799 let rest = &tag[val_start..];
1800 let quote = rest.chars().next();
1801 let value = match quote {
1802 Some('"') => rest[1..].split('"').next(),
1803 Some('\'') => rest[1..].split('\'').next(),
1804 // Unquoted: read up to whitespace, '>' or '/'.
1805 _ => rest
1806 .split(|c: char| c.is_whitespace() || c == '>' || c == '/')
1807 .next(),
1808 };
1809 return value.map(str::to_string);
1810 }
1811 None
1812}
1813
1814#[cfg(test)]
1815mod tests {
1816 use super::*;
1817
1818 const RSS_SAMPLE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
1819<rss version="2.0">
1820 <channel>
1821 <title>Example RSS Feed</title>
1822 <link>https://example.com/</link>
1823 <description>An example feed for tests</description>
1824 <item>
1825 <title>First post</title>
1826 <link>https://example.com/first</link>
1827 <guid>https://example.com/first</guid>
1828 <author>alice@example.com (Alice)</author>
1829 <pubDate>Fri, 10 Jul 2026 08:00:00 GMT</pubDate>
1830 <description><![CDATA[<p>Hello <b>world</b>.</p><script>alert('xss')</script><img src="x" onerror="alert(1)">]]></description>
1831 </item>
1832 <item>
1833 <title>Second post</title>
1834 <link>https://example.com/second</link>
1835 <guid>guid-second</guid>
1836 <pubDate>Sat, 11 Jul 2026 08:00:00 GMT</pubDate>
1837 <description><![CDATA[<a href="javascript:alert(1)">click</a><a href="https://ok.example/">ok</a>]]></description>
1838 </item>
1839 </channel>
1840</rss>"#;
1841
1842 const ATOM_SAMPLE: &str = r#"<?xml version="1.0" encoding="utf-8"?>
1843<feed xmlns="http://www.w3.org/2005/Atom">
1844 <title>Example Atom Feed</title>
1845 <link rel="alternate" href="https://atom.example.com/"/>
1846 <link rel="self" href="https://atom.example.com/feed.xml"/>
1847 <id>urn:uuid:feed-1</id>
1848 <updated>2026-07-11T08:00:00Z</updated>
1849 <entry>
1850 <title>Atom entry</title>
1851 <id>urn:uuid:entry-1</id>
1852 <link rel="alternate" href="https://atom.example.com/a"/>
1853 <author><name>Bob</name></author>
1854 <updated>2026-07-11T08:00:00Z</updated>
1855 <content type="html"><![CDATA[<p>Safe <em>text</em>.</p><script>steal()</script><iframe src="evil"></iframe>]]></content>
1856 </entry>
1857</feed>"#;
1858
1859 /// [`ATOM_SAMPLE`] with the `self` link before the `alternate` one.
1860 const ATOM_SELF_FIRST: &str = r#"<?xml version="1.0" encoding="utf-8"?>
1861<feed xmlns="http://www.w3.org/2005/Atom">
1862 <title>Example Atom Feed</title>
1863 <link rel="self" href="https://atom.example.com/feed.xml"/>
1864 <link rel="alternate" href="https://atom.example.com/"/>
1865 <id>urn:uuid:feed-1</id>
1866 <updated>2026-07-11T08:00:00Z</updated>
1867 <entry>
1868 <title>Atom entry</title>
1869 <id>urn:uuid:entry-1</id>
1870 <link rel="alternate" href="https://atom.example.com/a"/>
1871 <author><name>Bob</name></author>
1872 <updated>2026-07-11T08:00:00Z</updated>
1873 <content type="html"><![CDATA[<p>Safe <em>text</em>.</p><script>steal()</script><iframe src="evil"></iframe>]]></content>
1874 </entry>
1875</feed>"#;
1876
1877 // ---- #205: what one entry may store, per field ----------------------
1878
1879 /// An RSS document carrying one item with exactly these fields.
1880 fn rss_with_fields(title: &str, link: &str, author: &str, body: &str, guid: &str) -> String {
1881 format!(
1882 r#"<?xml version="1.0"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel>
1883<title>{title}</title><link>https://example.com/{link}</link>
1884<item><title>{title}</title><link>https://example.com/{link}</link><guid>{guid}</guid>
1885<dc:creator>{author}</dc:creator><description><![CDATA[{body}]]></description></item>
1886</channel></rss>"#
1887 )
1888 }
1889
1890 #[test]
1891 fn bound_text_cuts_on_a_character_boundary() {
1892 // 'é' is two bytes, so an odd limit lands mid-character.
1893 let cut = bound_text("é".repeat(100), 51);
1894 assert!(cut.len() <= 51, "not bounded: {} bytes", cut.len());
1895 assert_eq!(cut, "é".repeat(25), "cut too short or mid-character");
1896 assert_eq!(
1897 bound_text("short".into(), 51),
1898 "short",
1899 "a short value changed"
1900 );
1901 }
1902
1903 #[test]
1904 fn rendered_content_fits_even_when_rendering_grows_it() {
1905 // Escaping turns each `&` into `&` — five bytes from one.
1906 let out = plain_text_to_html_bounded(&"&".repeat(1_000), 100);
1907 assert!(
1908 out.len() <= 100,
1909 "escaped output not bounded: {} bytes",
1910 out.len()
1911 );
1912 assert!(!out.is_empty(), "bounded to nothing");
1913 assert_eq!(
1914 out.matches("&").count() * 5,
1915 out.len(),
1916 "cut mid-entity: {out}"
1917 );
1918 }
1919
1920 #[test]
1921 fn an_rss_items_text_fields_are_bounded() {
1922 let big = "x".repeat(100_000);
1923 let xml = rss_with_fields(&big, &big, &big, "body", "id-1");
1924 let parsed = feed_rs::parser::parse(xml.as_bytes()).unwrap();
1925 let e = normalize_entry(&parsed.entries[0]);
1926 assert!(e.title.as_ref().unwrap().len() <= MAX_TITLE_BYTES, "title");
1927 assert!(e.url.as_ref().unwrap().len() <= MAX_URL_BYTES, "url");
1928 assert!(
1929 e.author.as_ref().unwrap().len() <= MAX_AUTHOR_BYTES,
1930 "author"
1931 );
1932 let (title, site) = feed_metadata(&parsed);
1933 assert!(title.unwrap().len() <= MAX_TITLE_BYTES, "feed title");
1934 assert!(site.unwrap().len() <= MAX_URL_BYTES, "feed site url");
1935 }
1936
1937 #[test]
1938 fn an_rss_body_is_bounded_and_still_well_formed() {
1939 // Long enough to need cutting, with markup straddling the cut.
1940 let body = format!("<p>{}<b>tail</b></p>", "a".repeat(MAX_CONTENT_HTML_BYTES));
1941 let xml = rss_with_fields("t", "l", "a", &body, "id-2");
1942 let parsed = feed_rs::parser::parse(xml.as_bytes()).unwrap();
1943 let html = normalize_entry(&parsed.entries[0]).content_html.unwrap();
1944 assert!(
1945 html.len() <= MAX_CONTENT_HTML_BYTES,
1946 "body not bounded: {}",
1947 html.len()
1948 );
1949 assert_eq!(
1950 sanitize_html(&html),
1951 html,
1952 "the stored body is not well-formed sanitized HTML"
1953 );
1954 }
1955
1956 /// Review of #224: cutting the INPUT first threw away content that would
1957 /// have fit. A large inline `data:` image, which ammonia strips anyway,
1958 /// ahead of the article left the cut ending inside the image tag, and the
1959 /// article was stored as an empty body.
1960 #[test]
1961 fn content_the_sanitizer_strips_does_not_count_against_the_bound() {
1962 const MAX: usize = 64 * 1024;
1963 let body = format!(
1964 r#"<p><img src="data:image/png;base64,{}"></p><p>the article</p>"#,
1965 "A".repeat(MAX + 16 * 1024)
1966 );
1967 let html = sanitize_html_bounded(&body, MAX);
1968 assert!(
1969 html.contains("the article"),
1970 "the article was cut away: {} bytes kept",
1971 html.len()
1972 );
1973 assert!(html.len() <= MAX);
1974 }
1975
1976 /// Review of #224 (second round): the re-cut loop shrank its input by a
1977 /// few bytes a round when the bytes beyond the cut were ones the sanitizer
1978 /// strips anyway — measured at ~32 bytes/round, hours for one entry, on the
1979 /// poller's async task. The number of renders must be bounded.
1980 /// Review of #224: a cut into bytes the sanitizer strips anyway (here an
1981 /// unterminated comment) crept a few bytes a round, for hours. Bounding
1982 /// works on the SANITIZED output now, so stripped input costs nothing.
1983 #[test]
1984 fn content_cut_beside_stripped_bytes_still_keeps_what_fits() {
1985 const MAX: usize = 64 * 1024;
1986 let body = format!("<p>{}</p><!--{}", "a".repeat(MAX + 8), "x".repeat(16 * MAX));
1987 let html = sanitize_html_bounded(&body, MAX);
1988 assert!(html.len() <= MAX);
1989 assert!(
1990 html.len() > MAX - MAX / 16,
1991 "kept far less than fits: {}",
1992 html.len()
1993 );
1994 }
1995
1996 /// Also from that review: a cut landing inside a stripped prefix stored an
1997 /// empty body when an article that fits followed it.
1998 /// Also from review: a cut landing inside a stripped prefix stored an
1999 /// empty body when an article that fits followed it.
2000 #[test]
2001 fn a_stripped_prefix_does_not_leave_an_empty_body() {
2002 const MAX: usize = 64 * 1024;
2003 let body = format!(
2004 r#"<p><img src="data:image/png;base64,{}"></p><p>{}</p>"#,
2005 "A".repeat(3 * MAX),
2006 "&".repeat(MAX)
2007 );
2008 let html = sanitize_html_bounded(&body, MAX);
2009 assert!(html.len() <= MAX);
2010 assert!(
2011 html.len() > MAX - MAX / 16,
2012 "nothing like what fits was kept: {} bytes",
2013 html.len()
2014 );
2015 }
2016
2017 /// Third review: a multi-byte character where the search's stale probe
2018 /// landed ended it early, keeping 0 bytes where ~2 MiB fit.
2019 #[test]
2020 fn a_stripped_multibyte_prefix_does_not_leave_an_empty_body() {
2021 const MAX: usize = 64 * 1024;
2022 let body = format!(
2023 "<!--{}--><p>{}</p>",
2024 "漢".repeat(MAX),
2025 "&".repeat(MAX * 3 / 10)
2026 );
2027 let html = sanitize_html_bounded(&body, MAX);
2028 assert!(html.len() <= MAX);
2029 assert!(
2030 html.len() > MAX - MAX / 16,
2031 "kept {} of ~{MAX} that fits",
2032 html.len()
2033 );
2034 }
2035
2036 /// Fourth review of #224: a closing tag is longer than the tag it closes,
2037 /// so a cut through nested markup grew past the bound on re-sanitizing,
2038 /// and the widening margin jumped straight to a cut of 0 — an empty body
2039 /// where nearly all of it fit.
2040 #[test]
2041 fn nested_markup_is_cut_not_emptied() {
2042 const MAX: usize = 64 * 1024;
2043 let html = sanitize_html_bounded(&"<span>".repeat(16_384), MAX);
2044 assert!(html.len() <= MAX);
2045 assert!(
2046 html.len() > MAX / 3,
2047 "kept {} of ~{MAX} that fits",
2048 html.len()
2049 );
2050
2051 let mixed = format!("{}{}", "t".repeat(MAX * 3 / 4), "<span>".repeat(MAX / 8));
2052 let html = sanitize_html_bounded(&mixed, MAX);
2053 assert!(html.len() <= MAX);
2054 assert!(
2055 html.len() > MAX - MAX / 16,
2056 "kept {} of ~{MAX} that fits",
2057 html.len()
2058 );
2059 }
2060
2061 /// The plain-text bound is exact: escaping is linear, so the longest
2062 /// fitting prefix is found in one pass, never by search.
2063 #[test]
2064 fn the_plain_text_bound_is_exact() {
2065 const MAX: usize = 64 * 1024;
2066 let raw = format!("{}{}", "漢".repeat(MAX / 4), "&".repeat(MAX / 10));
2067 let out = plain_text_to_html_bounded(&raw, MAX);
2068 assert!(out.len() <= MAX);
2069 // The next character would not have fitted: '&' escapes to 5 bytes.
2070 assert!(out.len() > MAX - 5, "kept {} of {MAX}", out.len());
2071 assert!(
2072 raw.starts_with(&out.replace("&", "&")),
2073 "not a prefix of the input"
2074 );
2075 }
2076
2077 #[test]
2078 fn an_overlong_rss_guid_becomes_a_stable_short_one() {
2079 let long = "g".repeat(10_000);
2080 let xml = rss_with_fields("t", "l", "a", "b", &long);
2081 let parsed = feed_rs::parser::parse(xml.as_bytes()).unwrap();
2082 let a = normalize_entry(&parsed.entries[0]).guid;
2083 let b = normalize_entry(&parsed.entries[0]).guid;
2084 assert!(a.len() <= MAX_GUID_BYTES, "guid not bounded: {}", a.len());
2085 assert_eq!(
2086 a, b,
2087 "the stand-in is not stable, so the entry would duplicate"
2088 );
2089 let other = rss_with_fields("t", "l", "a", "b", &format!("{long}h"));
2090 let other = feed_rs::parser::parse(other.as_bytes()).unwrap();
2091 assert_ne!(
2092 a,
2093 normalize_entry(&other.entries[0]).guid,
2094 "two ids collapsed into one"
2095 );
2096 }
2097
2098 #[test]
2099 fn an_ordinary_long_article_is_untouched() {
2100 // The largest body production held on 2026-10-03 was 86,969 bytes.
2101 let body = format!("<p>{}</p>", "word ".repeat(18_000));
2102 let xml = rss_with_fields(
2103 "A normal title",
2104 "post",
2105 "Author",
2106 &body,
2107 "https://example.com/post",
2108 );
2109 let parsed = feed_rs::parser::parse(xml.as_bytes()).unwrap();
2110 let e = normalize_entry(&parsed.entries[0]);
2111 assert_eq!(e.content_html.unwrap(), sanitize_html(&body));
2112 assert_eq!(e.title.as_deref(), Some("A normal title"));
2113 assert_eq!(e.guid, "https://example.com/post");
2114 }
2115
2116 /// **A stated date in the future is discarded, not stored and not clamped.**
2117 ///
2118 /// `entry_time` was `e.published.or(e.updated)` with no ceiling, so an item
2119 /// dated in the year 2999 was stored verbatim and then became permanent:
2120 /// both retention sweeps test `COALESCE(published, fetched_at) < cutoff` and
2121 /// a future date is never less than either; the per-feed keep-set orders on
2122 /// the same expression `DESC`, where it is rank one forever; and every list
2123 /// view orders on `published DESC`, where it sits at the top. One item in one
2124 /// feed, there for good. A publisher with a broken clock does this by
2125 /// accident.
2126 ///
2127 /// Discarded rather than clamped to now, which is the rule `#186`
2128 /// established on the atproto side and the reasoning transfers exactly: the
2129 /// entry upsert refreshes `published` on every poll but stamps `fetched_at`
2130 /// once, so a value derived from the current clock is rewritten every cycle
2131 /// and the row can never age at all. Clamping moves the defect. Falling back
2132 /// to undated lets `fetched_at` date it, and that holds still.
2133 ///
2134 /// The ceiling is [`MAX_FUTURE_PUBLISHED_DAYS`] (two days), deliberately
2135 /// looser than the publication path's five-minute grace: a publication can
2136 /// fall back to its record key's TID, and a feed has no such fallback.
2137 #[test]
2138 fn a_future_dated_rss_item_is_stored_undated_rather_than_dated_in_2999() {
2139 let future = r#"<?xml version="1.0"?>
2140<rss version="2.0"><channel><title>Clock</title><link>https://clock.example/</link>
2141<item><title>From the future</title><link>https://clock.example/1</link>
2142<guid>https://clock.example/1</guid>
2143<pubDate>Sat, 01 Jan 2999 00:00:00 GMT</pubDate></item>
2144</channel></rss>"#;
2145 let parsed = feed_rs::parser::parse(future.as_bytes()).expect("should parse");
2146 // The fixture is only meaningful if feed-rs actually read the date.
2147 assert!(
2148 parsed.entries[0].published.is_some(),
2149 "the fixture's pubDate did not parse, so this test proves nothing",
2150 );
2151
2152 let e = normalize_entry(&parsed.entries[0]);
2153 assert_eq!(
2154 e.published, None,
2155 "a year-2999 date was stored, which makes the row unsweepable, \
2156 un-evictable and permanently first in the reading list",
2157 );
2158
2159 // And the other direction: an ordinary past date must survive, or this
2160 // would be satisfied by discarding every date.
2161 let past = future.replace("01 Jan 2999", "01 Jan 2020");
2162 let parsed = feed_rs::parser::parse(past.as_bytes()).expect("should parse");
2163 let e = normalize_entry(&parsed.entries[0]);
2164 assert!(
2165 e.published
2166 .as_deref()
2167 .is_some_and(|p| p.starts_with("2020")),
2168 "an ordinary past date was discarded: {:?}",
2169 e.published,
2170 );
2171
2172 // **A merely MISLABELLED date must survive.** The ordinary cause of a
2173 // future `pubDate` is a local time stamped `+0000` — up to 14 hours out,
2174 // not a clock a few minutes fast. Refusing those would leave real
2175 // articles undated and dateless on screen, which is why the bound is two
2176 // days rather than the publication path's five-minute skew grace.
2177 let soon = (Utc::now() + chrono::Duration::hours(14)).to_rfc2822();
2178 let near = future.replace("Sat, 01 Jan 2999 00:00:00 GMT", &soon);
2179 let parsed = feed_rs::parser::parse(near.as_bytes()).expect("should parse");
2180 assert!(
2181 parsed.entries[0].published.is_some(),
2182 "the mislabelled-date fixture did not parse",
2183 );
2184 let e = normalize_entry(&parsed.entries[0]);
2185 assert!(
2186 e.published.is_some(),
2187 "a date 14 hours ahead — the widest real UTC offset — was refused, \
2188 so a timezone-mislabelled article loses its date entirely",
2189 );
2190
2191 // And the bound still bounds: a month out is refused.
2192 let far = (Utc::now() + chrono::Duration::days(30)).to_rfc2822();
2193 let month = future.replace("Sat, 01 Jan 2999 00:00:00 GMT", &far);
2194 let parsed = feed_rs::parser::parse(month.as_bytes()).expect("should parse");
2195 let e = normalize_entry(&parsed.entries[0]);
2196 assert_eq!(
2197 e.published, None,
2198 "a date a month ahead was kept, so the row leads the list for a month",
2199 );
2200
2201 // **Each candidate is judged separately, not the winner of `or`.**
2202 //
2203 // Atom specifically: for RSS 2 `feed-rs` copies `published` into
2204 // `updated` when `updated` is absent, so the second candidate holds the
2205 // same bogus value and the fall-through cannot help. Only a format
2206 // carrying two independent dates exercises this.
2207 let both = r#"<?xml version="1.0"?>
2208<feed xmlns="http://www.w3.org/2005/Atom"><title>Clock</title>
2209<entry><title>Mixed</title><id>https://clock.example/2</id>
2210<link href="https://clock.example/2"/>
2211<published>2999-01-01T00:00:00Z</published>
2212<updated>2020-06-01T00:00:00Z</updated></entry></feed>"#;
2213 let parsed = feed_rs::parser::parse(both.as_bytes()).expect("should parse");
2214 assert!(
2215 parsed.entries[0].published.is_some() && parsed.entries[0].updated.is_some(),
2216 "the fixture needs BOTH dates parsed for this case to mean anything",
2217 );
2218 let e = normalize_entry(&parsed.entries[0]);
2219 assert!(
2220 e.published
2221 .as_deref()
2222 .is_some_and(|p| p.starts_with("2020")),
2223 "a credible `updated` was discarded along with a bogus `published`, \
2224 leaving the entry undated: {:?}",
2225 e.published,
2226 );
2227 }
2228
2229 /// Parse a static RSS sample through feed-rs + our normalize/sanitize path
2230 /// (no network) and assert the entries come out sanitized and well-shaped.
2231 #[test]
2232 fn rss_parses_and_sanitizes() {
2233 let parsed = feed_rs::parser::parse(RSS_SAMPLE.as_bytes()).expect("RSS should parse");
2234 assert_eq!(
2235 parsed.title.as_ref().map(text_plain).as_deref(),
2236 Some("Example RSS Feed")
2237 );
2238 assert_eq!(parsed.entries.len(), 2);
2239
2240 let (title, site) = feed_metadata(&parsed);
2241 assert_eq!(title.as_deref(), Some("Example RSS Feed"));
2242 assert_eq!(site.as_deref(), Some("https://example.com/"));
2243
2244 let e0 = normalize_entry(&parsed.entries[0]);
2245 assert_eq!(e0.guid, "https://example.com/first");
2246 assert_eq!(e0.title.as_deref(), Some("First post"));
2247 assert_eq!(e0.url.as_deref(), Some("https://example.com/first"));
2248 assert!(e0.published.is_some());
2249 let html0 = e0.content_html.expect("content present");
2250 // Sanitized: benign markup kept, script + onerror stripped.
2251 assert!(html0.contains("Hello"));
2252 assert!(html0.contains("<b>world</b>") || html0.contains("<b>"));
2253 assert!(!html0.to_ascii_lowercase().contains("<script"));
2254 assert!(!html0.to_ascii_lowercase().contains("onerror"));
2255 assert!(!html0.to_ascii_lowercase().contains("alert"));
2256
2257 // Second entry: javascript: URL scrubbed, safe link kept.
2258 let e1 = normalize_entry(&parsed.entries[1]);
2259 assert_eq!(e1.guid, "guid-second");
2260 let html1 = e1.content_html.expect("content present");
2261 assert!(!html1.to_ascii_lowercase().contains("javascript:"));
2262 assert!(html1.contains("https://ok.example/"));
2263 }
2264
2265 /// Same, for an Atom sample: alternate link is the site URL, dangerous
2266 /// elements are stripped from entry content.
2267 /// **`rel="alternate"` is preferred over a `rel="self"` listed FIRST.** In
2268 /// `ATOM_SAMPLE` the alternate link is already first, so "prefer alternate"
2269 /// and "take the first link" were indistinguishable; the selection could
2270 /// be replaced by `links.first()` with the suite green. A feed listing
2271 /// `self` first — very common in Atom — would store the feed XML URL as
2272 /// the subscription's `siteUrl`, published to the reader's PDS.
2273 #[test]
2274 fn atom_prefers_alternate_over_a_self_link_listed_first() {
2275 let parsed = feed_rs::parser::parse(ATOM_SELF_FIRST.as_bytes()).expect("Atom should parse");
2276 let (title, site) = feed_metadata(&parsed);
2277 assert_eq!(title.as_deref(), Some("Example Atom Feed"));
2278 // alternate link preferred over rel="self".
2279 assert_eq!(site.as_deref(), Some("https://atom.example.com/"));
2280 }
2281
2282 #[test]
2283 fn atom_parses_and_sanitizes() {
2284 let parsed = feed_rs::parser::parse(ATOM_SAMPLE.as_bytes()).expect("Atom should parse");
2285 let (title, site) = feed_metadata(&parsed);
2286 assert_eq!(title.as_deref(), Some("Example Atom Feed"));
2287 // alternate link preferred over rel="self".
2288 assert_eq!(site.as_deref(), Some("https://atom.example.com/"));
2289
2290 assert_eq!(parsed.entries.len(), 1);
2291 let e = normalize_entry(&parsed.entries[0]);
2292 assert_eq!(e.guid, "urn:uuid:entry-1");
2293 assert_eq!(e.title.as_deref(), Some("Atom entry"));
2294 assert_eq!(e.author.as_deref(), Some("Bob"));
2295 assert_eq!(e.url.as_deref(), Some("https://atom.example.com/a"));
2296 let html = e.content_html.expect("content present");
2297 assert!(html.contains("Safe"));
2298 assert!(!html.to_ascii_lowercase().contains("<script"));
2299 assert!(!html.to_ascii_lowercase().contains("<iframe"));
2300 }
2301
2302 /// **The rkey obeys all of atproto's record-key rules, not just the
2303 /// charset.** `.` and `..` are reserved and the length is 1..=512; the
2304 /// charset alone admitted both and a 10 000-character key, into a UNIQUE
2305 /// column and the user's public PDS. The rule is the one the repo's own
2306 /// TID tests already state.
2307 #[test]
2308 fn an_rkey_must_obey_atprotos_length_and_dot_rules() {
2309 let uri = |rkey: &str| {
2310 format!("at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/{rkey}")
2311 };
2312 assert!(
2313 !is_storable_feed_url(&uri("."), true),
2314 "`.` is a reserved rkey"
2315 );
2316 assert!(
2317 !is_storable_feed_url(&uri(".."), true),
2318 "`..` is a reserved rkey"
2319 );
2320 assert!(
2321 !is_storable_feed_url(&uri(&"a".repeat(513)), true),
2322 "an rkey over 512 bytes was accepted"
2323 );
2324 assert!(
2325 is_storable_feed_url(&uri(&"a".repeat(512)), true),
2326 "an rkey of exactly 512 bytes is valid"
2327 );
2328 assert!(is_storable_feed_url(&uri("3lab2c4d5e6f7g8h"), true));
2329 }
2330
2331 /// **Every `KNOWN_PROVIDERS` row is pinned by its own reason.**
2332 ///
2333 /// The provider test used URLs that the generic heuristics catch on their
2334 /// own — Substack's `/feed/private/` is also a path marker, Patreon's
2335 /// `?auth=…` an opaque secret key — and never asserted the reason. With
2336 /// 17 of 18 rows deleted, the suite stayed green. The provider layer runs
2337 /// FIRST so its specific reason wins; asserting the reason pins each row
2338 /// even where a generic rule would still refuse the URL. Values are kept
2339 /// short and plain so the generic query rule (`value_is_opaque`) does not
2340 /// fire — most of these are refused by the provider row alone.
2341 #[test]
2342 fn each_known_provider_is_caught_by_its_own_row() {
2343 for (url, reason) in [
2344 (
2345 "https://author.substack.com/feed/private/x",
2346 "Substack private feed",
2347 ),
2348 (
2349 "https://www.patreon.com/rss/creator?auth=ab",
2350 "Patreon member feed",
2351 ),
2352 ("https://blog.ghost.io/rss/?uuid=x", "Ghost members feed"),
2353 (
2354 "https://buttondown.email/me/rss?token=x",
2355 "Buttondown premium feed",
2356 ),
2357 (
2358 "https://buttondown.com/me/rss?token=x",
2359 "Buttondown premium feed",
2360 ),
2361 (
2362 "https://rss.beehiiv.com/feeds/x.xml?token=x",
2363 "Beehiiv premium feed",
2364 ),
2365 (
2366 "https://example.memberful.com/feed",
2367 "Memberful members feed",
2368 ),
2369 ("https://example.pico.link/feed", "Pico member feed"),
2370 ("https://steadyhq.com/rss/example", "Steady member feed"),
2371 (
2372 "https://example.supercast.com/feed",
2373 "Supercast private podcast",
2374 ),
2375 (
2376 "https://example.supercast.tech/feed",
2377 "Supercast private podcast",
2378 ),
2379 (
2380 "https://example.supportingcast.fm/feed",
2381 "Supporting Cast private podcast",
2382 ),
2383 (
2384 "https://feeds.redcircle.com/x?private=1",
2385 "RedCircle private podcast",
2386 ),
2387 (
2388 "https://feeds.megaphone.fm/x?token=x",
2389 "Megaphone private podcast",
2390 ),
2391 (
2392 "https://feeds.acast.com/public/shows/x?token=x",
2393 "Acast+ private podcast",
2394 ),
2395 (
2396 "https://omny.fm/shows/x/playlists/podcast.rss?token=x",
2397 "Omny private podcast",
2398 ),
2399 (
2400 "https://podcasts.apple.com/feed/x?token=x",
2401 "Apple subscriber podcast",
2402 ),
2403 (
2404 "https://anchor.spotify.com/s/x/podcast/rss?token=x",
2405 "Spotify subscriber podcast",
2406 ),
2407 ] {
2408 match classify_feed_privacy(url) {
2409 FeedPrivacy::Private(r) => {
2410 assert_eq!(r, reason, "{url} was refused by another rule")
2411 }
2412 FeedPrivacy::Public => panic!("{url} was not refused at all"),
2413 }
2414 }
2415 }
2416
2417 /// **Plain text is escaped, not sanitised.** `ammonia::clean` parses its
2418 /// input as markup, so a `<` in prose swallows everything after it:
2419 /// measured in this tree, `"if x<y then z"` becomes `"if x"`. That is the
2420 /// right function for an RSS body (which IS markup) and exactly the wrong
2421 /// one for a field the lexicon defines as plain text — it silently deletes
2422 /// the reader's content.
2423 #[test]
2424 fn plain_text_is_escaped_rather_than_swallowed() {
2425 assert_eq!(
2426 plain_text_to_html("Vec<String> is a type"),
2427 "Vec<String> is a type"
2428 );
2429 assert_eq!(plain_text_to_html("if x<y then z"), "if x<y then z");
2430 assert_eq!(plain_text_to_html("a & b"), "a & b");
2431 // Line structure survives into a field rendered as HTML.
2432 assert_eq!(plain_text_to_html("one\ntwo"), "one<br>two");
2433 // And it is still safe: the escaping happens before any markup is added.
2434 let hostile = plain_text_to_html("<script>alert(1)</script>");
2435 assert!(!hostile.contains("<script"), "{hostile}");
2436 }
2437
2438 #[test]
2439 fn discover_finds_rss_link() {
2440 let html = r#"<!doctype html><html><head>
2441 <title>Blog</title>
2442 <link rel="stylesheet" href="/style.css">
2443 <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">
2444 </head><body>hi</body></html>"#;
2445 let base = Url::parse("https://blog.example.com/").unwrap();
2446 let found = discover_feed(html, Some(&base)).expect("should discover feed");
2447 assert_eq!(found.as_str(), "https://blog.example.com/feed.xml");
2448 }
2449
2450 #[test]
2451 fn discover_finds_atom_absolute_link() {
2452 let html = r#"<head><link rel="alternate" type="application/atom+xml" href="https://x.example/atom"></head>"#;
2453 let found = discover_feed(html, None).expect("should discover absolute feed");
2454 assert_eq!(found.as_str(), "https://x.example/atom");
2455 }
2456
2457 /// **Autodiscovery only ever yields an http(s) URL.**
2458 ///
2459 /// The href is publisher-controlled and `Url::parse` accepts any scheme, so
2460 /// a page could hand the add path an `at://` publication URI (or anything
2461 /// else) that the user never typed — and the add path's input gate has
2462 /// already run by then. A non-http(s) alternate is skipped, not returned,
2463 /// so a later real feed link still wins.
2464 #[test]
2465 fn discover_skips_a_non_http_alternate() {
2466 let at_link = r#"<link rel="alternate" type="application/rss+xml" href="at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab2c4d5e6f7g8h">"#;
2467 assert!(
2468 discover_feed(&format!("<head>{at_link}</head>"), None).is_none(),
2469 "an at:// alternate was handed back as a feed URL"
2470 );
2471 let ftp_link =
2472 r#"<link rel="alternate" type="application/atom+xml" href="ftp://x.example/atom">"#;
2473 assert!(discover_feed(&format!("<head>{ftp_link}</head>"), None).is_none());
2474
2475 let real =
2476 r#"<link rel="alternate" type="application/atom+xml" href="https://x.example/atom">"#;
2477 let found = discover_feed(&format!("<head>{at_link}{real}</head>"), None)
2478 .expect("the http(s) link after a skipped one must still be found");
2479 assert_eq!(found.as_str(), "https://x.example/atom");
2480 }
2481
2482 #[test]
2483 fn discover_returns_none_without_feed_link() {
2484 let html =
2485 r#"<head><link rel="stylesheet" href="/s.css"><link rel="icon" href="/f.ico"></head>"#;
2486 assert!(discover_feed(html, None).is_none());
2487 }
2488
2489 #[test]
2490 fn synthetic_guid_is_stable_and_dedups() {
2491 // An item with neither guid nor link: feed-rs will hash the link (absent)
2492 // to a UUID id, but to exercise *our* synthetic fallback we clear the id
2493 // on the parsed entry and confirm normalize yields a deterministic guid.
2494 let xml = r#"<?xml version="1.0"?><rss version="2.0"><channel>
2495 <title>t</title>
2496 <item><title>only a title</title><description>body</description></item>
2497 </channel></rss>"#;
2498 let mut parsed = feed_rs::parser::parse(xml.as_bytes()).expect("parse");
2499 parsed.entries[0].id.clear();
2500 parsed.entries[0].links.clear();
2501 let g1 = normalize_entry(&parsed.entries[0]).guid;
2502 let g2 = normalize_entry(&parsed.entries[0]).guid;
2503 assert_eq!(g1, g2);
2504 assert!(g1.starts_with("featherreader:synthetic:"));
2505 }
2506
2507 #[test]
2508 fn entry_link_scheme_allowlist_neutralizes_javascript() {
2509 // An entry whose only link is a javascript: URL must yield no href.
2510 let xml = r#"<?xml version="1.0"?><rss version="2.0"><channel>
2511 <title>t</title>
2512 <item>
2513 <title>evil</title>
2514 <link>javascript:alert(document.domain)</link>
2515 <guid>evil-1</guid>
2516 </item>
2517 </channel></rss>"#;
2518 let parsed = feed_rs::parser::parse(xml.as_bytes()).expect("parse");
2519 let e = normalize_entry(&parsed.entries[0]);
2520 // url is dropped (not a safe http(s) link)…
2521 assert_eq!(e.url, None);
2522 // …but the entry still dedups (guid preserved from <guid>).
2523 assert_eq!(e.guid, "evil-1");
2524
2525 // A data: URL is likewise dropped.
2526 let xml2 = r#"<?xml version="1.0"?><rss version="2.0"><channel>
2527 <title>t</title>
2528 <item><title>d</title><link>data:text/html,<script>1</script></link><guid>d1</guid></item>
2529 </channel></rss>"#;
2530 let parsed2 = feed_rs::parser::parse(xml2.as_bytes()).expect("parse");
2531 let e2 = normalize_entry(&parsed2.entries[0]);
2532 assert_eq!(e2.url, None);
2533
2534 // A normal https link survives.
2535 let xml3 = r#"<?xml version="1.0"?><rss version="2.0"><channel>
2536 <title>t</title>
2537 <item><title>ok</title><link>https://ok.example/post</link><guid>ok1</guid></item>
2538 </channel></rss>"#;
2539 let parsed3 = feed_rs::parser::parse(xml3.as_bytes()).expect("parse");
2540 let e3 = normalize_entry(&parsed3.entries[0]);
2541 assert_eq!(e3.url.as_deref(), Some("https://ok.example/post"));
2542 }
2543
2544 #[test]
2545 fn classify_privacy_flags_secret_urls_across_providers() {
2546 // --- Known providers: newsletters ---
2547 // Substack private feed path.
2548 assert!(
2549 classify_feed_privacy("https://author.substack.com/feed/private/deadbeefcafe1234")
2550 .is_private()
2551 );
2552 // Patreon ?auth= member feed.
2553 assert!(classify_feed_privacy(
2554 "https://www.patreon.com/rss/author?auth=Zm9vYmFyc2VjcmV0dG9rZW4"
2555 )
2556 .is_private());
2557 // Ghost members feed via ?uuid=.
2558 assert!(classify_feed_privacy(
2559 "https://blog.ghost.io/rss/?uuid=1f2e3d4c-5b6a-7089-90ab-cdef01234567"
2560 )
2561 .is_private());
2562
2563 // --- Known providers: private podcasts ---
2564 // Supporting Cast tokened podcast feed.
2565 assert!(classify_feed_privacy(
2566 "https://feeds.supportingcast.fm/show/abcdef0123456789abcdef01"
2567 )
2568 .is_private());
2569 // Supercast private podcast (host alone is enough).
2570 assert!(classify_feed_privacy("https://feeds.supercast.com/12345/rss").is_private());
2571
2572 // --- Generic, provider-agnostic heuristic ---
2573 // Named credential query params with an opaque value.
2574 assert!(
2575 classify_feed_privacy("https://example.com/feed?token=Zm9vYmFyc2VjcmV0").is_private()
2576 );
2577 assert!(
2578 classify_feed_privacy("https://example.com/feed?key=Zm9vYmFyc2VjcmV0").is_private()
2579 );
2580 assert!(
2581 classify_feed_privacy("https://example.com/feed?secret=Zm9vYmFyc2VjcmV0").is_private()
2582 );
2583 // Userinfo credentials in the authority.
2584 assert!(classify_feed_privacy("https://user:pass@example.com/feed").is_private());
2585 // A `/private/` path segment on an unknown host.
2586 assert!(classify_feed_privacy("https://blog.example.com/private/rss").is_private());
2587 // `/members/` path convention.
2588 assert!(classify_feed_privacy("https://news.example.com/members/feed.xml").is_private());
2589 // A high-entropy opaque token embedded in the path with no telltale name.
2590 assert!(
2591 classify_feed_privacy("https://feeds.example.com/aB3xK9zQ7mP2rT5wL8nD4vF6")
2592 .is_private()
2593 );
2594 // A bare UUID path segment (many tokened feeds).
2595 assert!(classify_feed_privacy(
2596 "https://feeds.example.com/1f2e3d4c-5b6a-7089-90ab-cdef01234567"
2597 )
2598 .is_private());
2599 }
2600
2601 /// The dominant real-world private-podcast shape delivers the token as a
2602 /// FILENAME (`<token>.rss` / `<token>.xml`) or affixed inside a larger
2603 /// segment (`feed-<uuid>`). Named providers are caught by their host rule;
2604 /// these are UNKNOWN-provider CDNs that must still be caught by the generic
2605 /// backstop, so the secret is never fetched or stored.
2606 #[test]
2607 fn classify_privacy_catches_tokened_filenames_on_unknown_hosts() {
2608 // **A stem only the extension-strip branch can see.** Every other case
2609 // here is also caught by the sub-part scan (branch 3) or the UUID scan,
2610 // so deleting the strip left the suite green — `FEED_EXTENSIONS` was
2611 // effectively dead. This stem's `-`-separated parts are each too short
2612 // to look like a secret on their own, and the whole segment fails on
2613 // the `.` — only stripping `.rss` and re-testing the 26-char stem sees
2614 // it. That is exactly the shape a hyphen-bearing base64url token
2615 // filename takes.
2616 assert!(
2617 classify_feed_privacy("https://cdn.example/feeds/aB3xK9pQ-7mZ2vN8w-Qr5tYuW.rss")
2618 .is_private(),
2619 "a token stem visible only after stripping the extension was not caught"
2620 );
2621 // hex-32 token as an .xml filename.
2622 assert!(classify_feed_privacy(
2623 "https://cdn.somepod.io/f/a1b2c3d4e5f60718293a4b5c6d7e8f90.xml"
2624 )
2625 .is_private());
2626 // hex-32 token as a .rss filename on an unknown CDN.
2627 assert!(classify_feed_privacy(
2628 "https://dcs.megaphone.example/network/a1b2c3d4e5f60718293a4b5c6d7e8f90.rss"
2629 )
2630 .is_private());
2631 // UUID + .xml filename.
2632 assert!(classify_feed_privacy(
2633 "https://brandnew.example/feed/1f2e3d4c-5b6a-7089-90ab-cdef01234567.xml"
2634 )
2635 .is_private());
2636 // UUID affixed with a prefix (`feed-<uuid>`) — split can't see it, the
2637 // UUID-substring scan must.
2638 assert!(classify_feed_privacy(
2639 "https://x.example/feed-1f2e3d4c-5b6a-7089-90ab-cdef01234567"
2640 )
2641 .is_private());
2642 // UUID + .rss suffix.
2643 assert!(classify_feed_privacy(
2644 "https://x.example/1f2e3d4c-5b6a-7089-90ab-cdef01234567.rss"
2645 )
2646 .is_private());
2647 // hex-16 token as an .xml filename.
2648 assert!(classify_feed_privacy("https://x.example/feed/9f8e7d6c5b4a3928.xml").is_private());
2649 // A base64url token with `=` padding as a clean path segment.
2650 assert!(
2651 classify_feed_privacy("https://cdn.pod.io/f/YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnc=")
2652 .is_private()
2653 );
2654 }
2655
2656 /// YouTube channel/playlist RSS feeds are FULLY PUBLIC (the id is a public
2657 /// handle, not a secret) and are the standard way to subscribe to a channel —
2658 /// they must NOT be false-blocked by the generic entropy heuristic.
2659 #[test]
2660 fn classify_privacy_allows_public_youtube_feeds() {
2661 assert_eq!(
2662 classify_feed_privacy(
2663 "https://www.youtube.com/feeds/videos.xml?channel_id=UC-lHJZR3Gqxm24_Vd_AJ5Yw"
2664 ),
2665 FeedPrivacy::Public
2666 );
2667 assert_eq!(
2668 classify_feed_privacy(
2669 "https://www.youtube.com/feeds/videos.xml?playlist_id=PLFgquLnL59alCl_2TQvOiD5Vgm1hCaGSI"
2670 ),
2671 FeedPrivacy::Public
2672 );
2673 // Bare host form too.
2674 assert_eq!(
2675 classify_feed_privacy(
2676 "https://youtube.com/feeds/videos.xml?channel_id=UC-lHJZR3Gqxm24_Vd_AJ5Yw"
2677 ),
2678 FeedPrivacy::Public
2679 );
2680 // The allowlist is narrow: a `token=` on the YouTube feeds path still
2681 // classifies private (can't smuggle a credential through the allowlist).
2682 assert!(classify_feed_privacy(
2683 "https://www.youtube.com/feeds/videos.xml?token=Zm9vYmFyc2VjcmV0dG9rZW4"
2684 )
2685 .is_private());
2686 }
2687
2688 #[test]
2689 fn classify_privacy_leaves_normal_public_feeds_public() {
2690 // Plain feed documents.
2691 assert_eq!(
2692 classify_feed_privacy("https://example.com/feed.xml"),
2693 FeedPrivacy::Public
2694 );
2695 assert_eq!(
2696 classify_feed_privacy("https://blog.example.com/rss"),
2697 FeedPrivacy::Public
2698 );
2699 assert_eq!(
2700 classify_feed_privacy("https://blog.example.com/rss.xml"),
2701 FeedPrivacy::Public
2702 );
2703 // A Substack PUBLIC feed (`/feed`, not `/feed/private/`) stays public.
2704 assert_eq!(
2705 classify_feed_privacy("https://author.substack.com/feed"),
2706 FeedPrivacy::Public
2707 );
2708 // A WordPress `/feed` endpoint.
2709 assert_eq!(
2710 classify_feed_privacy("https://wordpress.example.com/feed/"),
2711 FeedPrivacy::Public
2712 );
2713 // A plain Atom feed.
2714 assert_eq!(
2715 classify_feed_privacy("https://example.org/atom.xml"),
2716 FeedPrivacy::Public
2717 );
2718 // A long, hyphenated slug must NOT be mistaken for an embedded secret.
2719 assert_eq!(
2720 classify_feed_privacy("https://example.com/2026/07/my-first-long-blog-post-title/feed"),
2721 FeedPrivacy::Public
2722 );
2723 // A benign query key that merely contains "key" as a substring is fine.
2724 assert_eq!(
2725 classify_feed_privacy("https://example.com/feed?keyword=rust"),
2726 FeedPrivacy::Public
2727 );
2728 // A short, non-opaque value on a named key (e.g. an enum) is not a secret.
2729 assert_eq!(
2730 classify_feed_privacy("https://example.com/feed?p=2"),
2731 FeedPrivacy::Public
2732 );
2733 // An empty credential value is not a secret.
2734 assert_eq!(
2735 classify_feed_privacy("https://example.com/feed?token="),
2736 FeedPrivacy::Public
2737 );
2738 // A hyphenated slug ending in a feed extension must NOT be seen as a
2739 // tokened filename (the stem is short dictionary words, not a blob).
2740 assert_eq!(
2741 classify_feed_privacy("https://example.com/my-first-long-blog-post.xml"),
2742 FeedPrivacy::Public
2743 );
2744 // A short hex episode id in an .xml filename (< 16 chars) is not a secret.
2745 assert_eq!(
2746 classify_feed_privacy("https://example.com/episodes/ab12cd.xml"),
2747 FeedPrivacy::Public
2748 );
2749 // A dotted host-style filename slug stays public.
2750 assert_eq!(
2751 classify_feed_privacy("https://example.com/category/tech-news/feed.xml"),
2752 FeedPrivacy::Public
2753 );
2754 // Unparseable URL: treated as Public (add path rejects it downstream).
2755 assert_eq!(classify_feed_privacy("not a url"), FeedPrivacy::Public);
2756 }
2757
2758 /// **The detail is bounded where it is CONSTRUCTED, not only where it is
2759 /// stored.**
2760 ///
2761 /// Review found that widening `PollOutcome::Failed` with this field opened a
2762 /// second sink nobody looked at: `web.rs`'s `add_subscription` logs
2763 /// `?outcome` at INFO on a user-facing request path, so the whole
2764 /// untruncated anyhow chain — redirect-hop URLs, the SSRF guard's refusal
2765 /// text naming a resolved internal address — went to the access log.
2766 ///
2767 /// Bounding inside `bump_feed_errors` protected the database and nothing
2768 /// else. Bounding at construction protects every sink, including the ones
2769 /// added later.
2770 #[test]
2771 fn a_failure_detail_is_bounded_at_construction() {
2772 let huge = "x".repeat(10_000);
2773 let outcome = PollOutcome::Failed {
2774 backoff: BACKOFF_BASE,
2775 kind: FailureKind::Fetch,
2776 detail: failure_detail(&huge),
2777 };
2778 let PollOutcome::Failed { detail, .. } = &outcome else {
2779 panic!("wrong variant");
2780 };
2781 assert!(
2782 detail.chars().count() <= MAX_FAILURE_DETAIL_CHARS,
2783 "detail was {} chars",
2784 detail.chars().count(),
2785 );
2786 // And the Debug rendering — which is what actually reached the log — is
2787 // bounded with it.
2788 assert!(format!("{outcome:?}").len() < 1_000);
2789 }
2790
2791 /// **Every failure kind has its own label, and they round-trip.**
2792 ///
2793 /// Review found that collapsing all four `as_str` arms to `"fetch"` left
2794 /// the whole suite green: every test of these columns passed string
2795 /// literals, so nothing tied a variant to its label. A histogram whose
2796 /// buckets all say the same thing is worse than no histogram — it reports a
2797 /// single confident cause for four different failures.
2798 ///
2799 /// Asserted over `ALL` rather than a hand-written list, so adding a variant
2800 /// without a label fails here instead of silently sharing one.
2801 #[test]
2802 fn every_failure_kind_has_a_distinct_round_tripping_label() {
2803 let mut seen = std::collections::BTreeSet::new();
2804 for kind in FailureKind::ALL {
2805 let label = kind.as_str();
2806 assert!(
2807 seen.insert(label),
2808 "{label:?} is used by more than one FailureKind",
2809 );
2810 assert_eq!(
2811 FailureKind::parse(label),
2812 Some(kind),
2813 "{label:?} does not read back as the kind that wrote it",
2814 );
2815 }
2816 assert_eq!(seen.len(), FailureKind::ALL.len());
2817 // A label from a newer build is not attributed to a cause this one
2818 // knows — the `metrics::Backend::parse` contract.
2819 assert_eq!(FailureKind::parse("quota"), None);
2820 }
2821
2822 /// **Escalation reaches `settle_poll`.** `backoff_for` grows with the
2823 /// count and is tested alone; nothing asserted that the poll path passes
2824 /// the COUNT in. `backoff_for(1)` in its place left the whole suite green
2825 /// — a permanently dead feed retrying forever at the first-failure floor,
2826 /// which the comment on that line says must not happen.
2827 #[tokio::test]
2828 async fn backoff_escalates_with_consecutive_failures() -> anyhow::Result<()> {
2829 let pool = crate::store::init_url("sqlite::memory:").await?;
2830 let url = "https://dead.example/feed.xml";
2831 crate::store::upsert_feed(
2832 &pool,
2833 &crate::store::NewFeed {
2834 url: url.to_string(),
2835 ..Default::default()
2836 },
2837 )
2838 .await?;
2839 for _ in 0..5 {
2840 crate::store::bump_feed_errors(&pool, url, FailureKind::Fetch, "down").await?;
2841 }
2842 let before = chrono::Utc::now();
2843 settle_poll(
2844 &pool,
2845 url,
2846 &PollOutcome::Failed {
2847 backoff: Duration::from_secs(300),
2848 kind: FailureKind::Fetch,
2849 detail: "still down".to_string(),
2850 },
2851 Duration::from_secs(3600),
2852 )
2853 .await;
2854 let next: String = sqlx::query_scalar("SELECT next_poll FROM feeds WHERE url = ?1")
2855 .bind(url)
2856 .fetch_one(&pool)
2857 .await?;
2858 let next = chrono::DateTime::parse_from_rfc3339(&next)?.with_timezone(&chrono::Utc);
2859 let delay = (next - before).num_seconds();
2860 let expected = backoff_for(6).as_secs() as i64;
2861 assert!(
2862 (delay - expected).abs() <= 60,
2863 "sixth failure scheduled {delay}s out; escalation says {expected}s"
2864 );
2865 assert!(
2866 delay > backoff_for(1).as_secs() as i64 + 60,
2867 "the sixth failure landed on the first-failure floor"
2868 );
2869 Ok(())
2870 }
2871
2872 #[test]
2873 fn backoff_grows_and_is_capped() {
2874 assert_eq!(backoff_for(1), BACKOFF_BASE);
2875 assert!(backoff_for(2) > backoff_for(1));
2876 assert_eq!(backoff_for(100), BACKOFF_MAX);
2877 }
2878
2879 /// **Storable and pollable are ONE decision.**
2880 ///
2881 /// Review found the sequencing error this closes: making `at://` storable
2882 /// while nothing can poll it does not leave the feature dormant, it creates
2883 /// permanent failures that the cause histogram then publishes as
2884 /// unreachable publishers — the exact conflation it exists to end.
2885 #[test]
2886 fn an_at_uri_is_not_storable_while_standard_site_is_off() {
2887 let uri = "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab";
2888 assert!(
2889 !is_storable_feed_url(uri, false),
2890 "stored a feed nothing can poll"
2891 );
2892 assert!(is_storable_feed_url(uri, true));
2893 assert!(is_storable_feed_url("https://example.com/feed.xml", false));
2894 assert!(is_storable_feed_url("https://example.com/feed.xml", true));
2895 }
2896
2897 /// **A non-canonical scheme spelling is recognised and refused.** URL
2898 /// schemes are case-insensitive, so `At://` names the same thing as
2899 /// `at://` — but `feeds.url` is UNIQUE, so accepting both is two rows for
2900 /// one publication. Recognised (not passed through to the generic checks
2901 /// as if it were an ordinary URL), then refused for the spelling.
2902 /// Since publications are polled, only a URI the storage guard accepts is
2903 /// a publication. Any other at-URI is Unsupported, which no poller reads.
2904 #[test]
2905 fn only_a_storable_publication_uri_is_a_publication() {
2906 let did = "did:plc:ohutz6x5acjmpuulp3x7wxxc";
2907 let pubn = crate::lexicon::nsid::STANDARD_PUBLICATION;
2908 assert_eq!(
2909 FeedKind::of(&format!("at://{did}/{pubn}/3lab")),
2910 FeedKind::Publication
2911 );
2912 for unsupported in [
2913 format!("at://{did}/app.bsky.feed.post/3lab"),
2914 format!("At://{did}/{pubn}/3lab"),
2915 format!("at://alice.example.com/{pubn}/3lab"),
2916 format!("at://did:plc:short/{pubn}/3lab"),
2917 ] {
2918 assert_eq!(
2919 FeedKind::of(&unsupported),
2920 FeedKind::Unsupported,
2921 "{unsupported}"
2922 );
2923 }
2924 assert_eq!(FeedKind::of("https://example.com/feed.xml"), FeedKind::Rss);
2925 assert!(!FeedKind::POLLABLE.contains(&FeedKind::Unsupported));
2926 assert_eq!(FeedKind::parse("unsupported"), Some(FeedKind::Unsupported));
2927 }
2928
2929 #[test]
2930 fn a_non_canonical_at_uri_spelling_is_recognised_and_refused() {
2931 for odd in [
2932 "At://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab",
2933 "AT://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab",
2934 ] {
2935 assert!(!is_storable_feed_url(odd, true), "stored {odd:?}");
2936 // Fails CLOSED: it is an at-URI this reader will not store, not an
2937 // unparseable string that the `Err(_) => Public` arm waves through.
2938 assert!(
2939 classify_feed_privacy(odd).is_private(),
2940 "{odd:?} was declared publishable"
2941 );
2942 }
2943 }
2944
2945 /// **The handle form is not storable — the DID form is the identity.**
2946 ///
2947 /// `feeds.url` is UNIQUE; a handle and its DID would be two rows for one
2948 /// publication, and a handle can change hands. Every spelling is refused,
2949 /// canonical or not; resolving one to a DID is the input path's job.
2950 #[test]
2951 fn a_handle_form_publication_uri_is_not_storable() {
2952 for authority in [
2953 "alice.example.com",
2954 "EXAMPLE.COM",
2955 "169.254.169.254",
2956 "pds.internal",
2957 "printer.local",
2958 "host:8080",
2959 "-.-",
2960 "a b.c",
2961 ] {
2962 let uri = format!("at://{authority}/site.standard.publication/3lab");
2963 assert!(
2964 !is_storable_feed_url(&uri, true),
2965 "accepted authority {authority:?}"
2966 );
2967 }
2968 }
2969
2970 /// A control character or space in the at-URI is refused: `scheduler.rs`
2971 /// logs `%feed.url` with Display, and `feeds.url` is UNIQUE.
2972 #[test]
2973 fn an_at_uri_with_control_characters_is_not_storable() {
2974 for bad in [
2975 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab\n",
2976 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab ",
2977 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3l\tab",
2978 ] {
2979 assert!(!is_storable_feed_url(bad, true), "accepted {bad:?}");
2980 }
2981 }
2982
2983 /// **The `at://` exemption is a REGRESSION unless it is narrow.**
2984 ///
2985 /// Fan-out review found the arm I added was a bare prefix match, so *any*
2986 /// attacker-chosen string starting `at://` was declared safe to publish —
2987 /// skipping the userinfo check, the known-provider table, the private-path
2988 /// markers, the secret-query keys and the entropy heuristics. Measured
2989 /// against `main`, these three went from `Private` to `Public`.
2990 ///
2991 /// That matters because `rename_subscription` caches the URL AND rewrites
2992 /// the user's PUBLIC PDS record, with `classify_feed_privacy` as its only
2993 /// gate.
2994 #[test]
2995 fn a_credential_bearing_at_uri_is_still_private() {
2996 for hostile in [
2997 "at://user:pass@private.example.com/feed/private/TOKEN?apikey=deadbeefdeadbeef",
2998 "at://patreon.com/rss/12345?auth=deadbeefdeadbeefdeadbeef",
2999 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab?apikey=sekrit",
3000 ] {
3001 assert!(
3002 matches!(classify_feed_privacy(hostile), FeedPrivacy::Private(_)),
3003 "declared public: {hostile}"
3004 );
3005 }
3006 }
3007
3008 /// An rkey is `[A-Za-z0-9._:~-]` per atproto. Without that, a query string
3009 /// or path fragment smuggled into the rkey satisfies the three-segment
3010 /// check — which is what the exemption above keys off.
3011 #[test]
3012 fn an_rkey_outside_the_atproto_charset_is_not_storable() {
3013 for bad in [
3014 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab?apikey=sekrit",
3015 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab#frag",
3016 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab%2Fevil",
3017 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/caf\u{e9}",
3018 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab\u{202e}x",
3019 ] {
3020 assert!(!is_storable_feed_url(bad, true), "accepted rkey in {bad:?}");
3021 }
3022 // The legitimate charset still passes.
3023 for good in [
3024 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab2c4d5e6f7g8h",
3025 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/a.b_c~d-e",
3026 ] {
3027 assert!(is_storable_feed_url(good, true), "refused {good:?}");
3028 }
3029 }
3030
3031 /// **A real rkey is a TID, and a TID looks exactly like a secret.**
3032 ///
3033 /// Without an explicit `at://` arm, `classify_feed_privacy` runs the generic
3034 /// "high-entropy token in path" heuristic over the rkey. Measured: a
3035 /// realistic 16-char rkey on a handle-form at-URI is classified PRIVATE and
3036 /// the subscription REFUSED. The DID form escaped only because it fails to
3037 /// parse as a `Url` at all — so the bug was invisible from that side.
3038 ///
3039 /// The first version of this test used the rkey `3lab`, which is too short
3040 /// to trip the heuristic, so it passed with and without the fix.
3041 #[test]
3042 fn a_realistic_at_uri_rkey_is_not_mistaken_for_a_secret() {
3043 for uri in [
3044 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab2c4d5e6f7g8h",
3045 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/aB3xK9pQ7mZ2vN8w",
3046 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab2c4d5e6f7g8h",
3047 ] {
3048 assert_eq!(
3049 classify_feed_privacy(uri),
3050 FeedPrivacy::Public,
3051 "a publication rkey was mistaken for a credential: {uri}"
3052 );
3053 }
3054 }
3055
3056 /// **The DID form is the one that matters, and the one `Url::parse` cannot
3057 /// read.**
3058 ///
3059 /// `Url::parse("at://did:plc:…/…")` fails with *invalid port number* — the
3060 /// colons in the DID are taken as a port separator. So the obvious
3061 /// implementation, adding `"at"` to the `matches!` on `u.scheme()`, silently
3062 /// rejects every DID-based at-URI while appearing to work: the handle form
3063 /// (`at://alice.example.com/…`) parses fine and would pass such a test.
3064 ///
3065 /// All 19 at-URI rows in production are the DID form. A test written with a
3066 /// handle would have passed against an implementation that cannot store a
3067 /// single one of them.
3068 #[test]
3069 fn a_did_form_publication_uri_is_storable() {
3070 assert!(is_storable_feed_url(
3071 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab",
3072 true
3073 ));
3074 }
3075
3076 /// **An allowlist entry, not a loosening.** `at://` is accepted for exactly
3077 /// one foreign collection. Any other collection is somebody else's lexicon
3078 /// arriving through a path (`resolve_subscriptions`, OPML import) that takes
3079 /// records from outside with no add-path to reject them.
3080 #[test]
3081 fn an_at_uri_for_another_collection_is_not_storable() {
3082 assert!(!is_storable_feed_url(
3083 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/community.lexicon.rss.subscription/3lab",
3084 true
3085 ));
3086 assert!(!is_storable_feed_url(
3087 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/app.bsky.feed.post/3lab",
3088 true
3089 ));
3090 }
3091
3092 /// The malformed shapes, each of which a naive `split('/')` would accept.
3093 #[test]
3094 fn a_malformed_at_uri_is_not_storable() {
3095 for bad in [
3096 "at://",
3097 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc",
3098 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication",
3099 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/",
3100 "at:///site.standard.publication/3lab",
3101 "at://did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab/extra",
3102 "at://not-a-did-or-handle/site.standard.publication/3lab",
3103 "at://did:plc:TOOSHORT/site.standard.publication/3lab",
3104 ] {
3105 assert!(!is_storable_feed_url(bad, true), "accepted {bad:?}");
3106 }
3107 }
3108
3109 /// **The reason the function exists, unchanged.** Mutating the new branch to
3110 /// accept any scheme makes this fail while the at-URI tests keep passing —
3111 /// that asymmetry is what says the change was an allowlist entry.
3112 #[test]
3113 fn the_refused_schemes_are_still_refused() {
3114 for bad in [
3115 "javascript:alert(1)",
3116 "file:///etc/passwd",
3117 "data:text/html,<script>",
3118 "ftp://example.com/feed.xml",
3119 "at:did:plc:ohutz6x5acjmpuulp3x7wxxc/site.standard.publication/3lab",
3120 ] {
3121 assert!(!is_storable_feed_url(bad, true), "accepted {bad:?}");
3122 }
3123 // A hostless http(s) URL is a PARSE error, not a parsed URL with no
3124 // host — `https:///feed.xml` even parses as host `feed.xml`. What
3125 // refuses these is the `Err` arm, so that is what this pins.
3126 for hostless in ["http://", "https://?q=1", "http:///"] {
3127 assert!(
3128 !is_storable_feed_url(hostless, true),
3129 "a hostless URL {hostless:?} was storable"
3130 );
3131 }
3132 assert!(is_storable_feed_url("https://example.com/feed.xml", true));
3133 assert!(is_storable_feed_url("http://example.com/feed.xml", true));
3134 }
3135}