From c50fc7e1e6bec6cdab02ae1cc4a2544fb783bdff Mon Sep 17 00:00:00 2001 From: Spence Pope Date: Thu, 15 Oct 2026 16:39:09 -0400 Subject: [PATCH] [APP-3405] Match Safelink domain rules on subdomains (#12001) --- bskylink/package.json | 1 + bskylink/src/cache/safelinkClient.ts | 81 ++++++++++----- bskylink/src/safelinkSubdomains.test.ts | 132 ++++++++++++++++++++++++ bskylink/yarn.lock | 12 +++ 4 files changed, 203 insertions(+), 23 deletions(-) create mode 100644 bskylink/src/safelinkSubdomains.test.ts diff --git a/bskylink/package.json b/bskylink/package.json index 32271b340..9b7b8b605 100644 --- a/bskylink/package.json +++ b/bskylink/package.json @@ -24,6 +24,7 @@ "pg": "^8.12.0", "pino": "^9.2.0", "prom-client": "^15.1.3", + "tldts": "^6.1.86", "uint8arrays": "^5.1.0" }, "devDependencies": { diff --git a/bskylink/src/cache/safelinkClient.ts b/bskylink/src/cache/safelinkClient.ts index 6e8d3f54a..79dd314e0 100644 --- a/bskylink/src/cache/safelinkClient.ts +++ b/bskylink/src/cache/safelinkClient.ts @@ -5,6 +5,7 @@ import { type ToolsOzoneSafelinkQueryEvents, } from '@atproto/api' import {LRUCache} from 'lru-cache' +import {parse as parseDomain} from 'tldts' import {type ServiceConfig} from '../config.js' import type Database from '../db/index.js' @@ -15,6 +16,34 @@ const SAFELINK_MIN_FETCH_INTERVAL = 1_000 const SAFELINK_MAX_FETCH_INTERVAL = 10_000 const SCHEME_REGEX = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\// +/** + * The domains whose rules apply to `host`, most specific first: the host + * itself, then each parent domain up to its registrable domain. Uses the + * Public Suffix List, including private suffixes like `github.io`, so it never + * reaches a shared suffix: a rule on `scam.com` covers `pay.scam.com`, but + * nothing walks up to `co.uk` or `github.io`. + */ +export function domainLookupOrder(host: string): string[] { + const order = [host] + let hostname: string + try { + hostname = new URL(`https://${host}`).hostname + } catch { + return order + } + const {domain, isIp} = parseDomain(hostname, {allowPrivateDomains: true}) + if (isIp || !domain || !hostname.endsWith(domain)) { + return order + } + let current = hostname + while (true) { + if (!order.includes(current)) order.push(current) + if (current === domain) break + current = current.slice(current.indexOf('.') + 1) + } + return order +} + export class SafelinkClient { private domainCache: LRUCache private urlCache: LRUCache @@ -61,37 +90,43 @@ export class SafelinkClient { return 'ok' } - // First, check if there is an existing URL rule. Note that even if the rule is 'ok', we still - // want to check for a blocking domain rule, so we will only return here if the url rule exists - // _and_ it is not 'ok'. - const urlRule = this.urlCache.get(url) - if (urlRule && urlRule !== 'ok') { + const urlRule = await this.lookupRule(this.urlCache, url, 'url') + if (urlRule !== 'ok') { return urlRule } - // If we find a domain rule of _any_ kind, including 'ok', we can now return that rule. - const domainRule = this.domainCache.get(domain) - if (domainRule) { - return domainRule + // domain rules cover subdomains too, and the most specific rule wins + for (const candidate of domainLookupOrder(domain)) { + const rule = await this.lookupRule(this.domainCache, candidate, 'domain') + if (rule !== 'ok') { + return rule + } } - try { - const maybeUrlRule = await this.getRule(this.db, url, 'url') - this.urlCache.set(url, maybeUrlRule) - return maybeUrlRule - } catch (e) { - this.urlCache.set(url, 'ok') - } + return 'ok' + } + /** + * The rule for `key` from the cache, or from the database on a miss. A miss + * is cached as 'ok' so repeat lookups skip the database. + */ + private async lookupRule( + cache: LRUCache, + key: string, + pattern: ToolsOzoneSafelinkDefs.PatternType, + ): Promise { + const cached = cache.get(key) + if (cached) { + return cached + } + let rule: SafelinkRule | 'ok' try { - const maybeDomainRule = await this.getRule(this.db, domain, 'domain') - this.domainCache.set(domain, maybeDomainRule) - return maybeDomainRule - } catch (e) { - this.domainCache.set(domain, 'ok') + rule = await this.getRule(this.db, key, pattern) + } catch { + rule = 'ok' } - - return 'ok' + cache.set(key, rule) + return rule } private async getRule( diff --git a/bskylink/src/safelinkSubdomains.test.ts b/bskylink/src/safelinkSubdomains.test.ts new file mode 100644 index 000000000..727ca6774 --- /dev/null +++ b/bskylink/src/safelinkSubdomains.test.ts @@ -0,0 +1,132 @@ +import assert from 'node:assert' +import {describe, it} from 'node:test' + +import {LRUCache} from 'lru-cache' + +import {domainLookupOrder, SafelinkClient} from './cache/safelinkClient.js' +import {type SafelinkRule} from './db/schema.js' + +const rule = ( + pattern: SafelinkRule['pattern'], + url: string, + action: SafelinkRule['action'], +): SafelinkRule => ({ + id: 1, + eventType: 'addRule', + url, + pattern, + action, + createdAt: new Date().toISOString(), +}) + +/** A client whose database holds `rules`, recording each database lookup. */ +const createClient = (rules: SafelinkRule[]) => { + const client: SafelinkClient = Object.create(SafelinkClient.prototype) + const lookups: string[] = [] + const domainCache = new LRUCache({max: 100}) + Reflect.set(client, 'domainCache', domainCache) + Reflect.set(client, 'urlCache', new LRUCache({max: 100})) + Reflect.set( + client, + 'getRule', + (_db: unknown, key: string, pattern: SafelinkRule['pattern']) => { + lookups.push(`${pattern}:${key}`) + const found = rules.find(r => r.pattern === pattern && r.url === key) + return found ? Promise.resolve(found) : Promise.reject(new Error('none')) + }, + ) + return {client, lookups, domainCache} +} + +void describe('domainLookupOrder', () => { + void it('walks up to the registrable domain', () => { + assert.deepStrictEqual(domainLookupOrder('a.pay.scam.com'), [ + 'a.pay.scam.com', + 'pay.scam.com', + 'scam.com', + ]) + }) + + void it('stops at multi-part public suffixes', () => { + assert.deepStrictEqual(domainLookupOrder('pay.scam.co.uk'), [ + 'pay.scam.co.uk', + 'scam.co.uk', + ]) + }) + + void it('stops at private suffixes', () => { + assert.deepStrictEqual(domainLookupOrder('someone.github.io'), [ + 'someone.github.io', + ]) + }) + + void it('only checks the host itself for suffixes, IPs and single labels', () => { + assert.deepStrictEqual(domainLookupOrder('co.uk'), ['co.uk']) + assert.deepStrictEqual(domainLookupOrder('10.0.0.1'), ['10.0.0.1']) + assert.deepStrictEqual(domainLookupOrder('localhost'), ['localhost']) + }) + + void it('keeps the port on the host, then checks domains without it', () => { + assert.deepStrictEqual(domainLookupOrder('pay.scam.com:8443'), [ + 'pay.scam.com:8443', + 'pay.scam.com', + 'scam.com', + ]) + }) +}) + +void describe('Safelink subdomain matching', () => { + void it('applies a domain rule to its subdomains', async () => { + const block = rule('domain', 'scam.com', 'block') + const {client} = createClient([block]) + assert.strictEqual( + await client.tryFindRule('https://pay.scam.com/login'), + block, + ) + }) + + void it('prefers the most specific domain rule', async () => { + const allow = rule('domain', 'safe.scam.com', 'whitelist') + const {client} = createClient([rule('domain', 'scam.com', 'block'), allow]) + assert.strictEqual(await client.tryFindRule('https://safe.scam.com'), allow) + }) + + void it('never applies a rule on a public suffix', async () => { + const {client} = createClient([rule('domain', 'github.io', 'block')]) + assert.strictEqual( + await client.tryFindRule('https://someone.github.io'), + 'ok', + ) + }) + + void it('checks parents even after a subdomain was cached as clean', async () => { + const block = rule('domain', 'scam.com', 'block') + const rules: SafelinkRule[] = [] + const {client, domainCache} = createClient(rules) + assert.strictEqual(await client.tryFindRule('https://pay.scam.com'), 'ok') + // a later rule on the parent, whose cache entry the sync clears + rules.push(block) + domainCache.delete('scam.com') + assert.strictEqual(await client.tryFindRule('https://pay.scam.com'), block) + }) + + void it('checks URL rules before domain rules', async () => { + const urlBlock = rule('url', 'example.com/bad', 'block') + const {client} = createClient([ + rule('domain', 'example.com', 'whitelist'), + urlBlock, + ]) + assert.strictEqual( + await client.tryFindRule('https://example.com/bad'), + urlBlock, + ) + }) + + void it('caches misses so repeat lookups skip the database', async () => { + const {client, lookups} = createClient([]) + await client.tryFindRule('https://pay.scam.com') + const first = lookups.length + await client.tryFindRule('https://pay.scam.com') + assert.strictEqual(lookups.length, first) + }) +}) diff --git a/bskylink/yarn.lock b/bskylink/yarn.lock index 017ef2984..015f338c0 100644 --- a/bskylink/yarn.lock +++ b/bskylink/yarn.lock @@ -1276,6 +1276,18 @@ tlds@^1.234.0: resolved "https://registry.yarnpkg.com/tlds/-/tlds-1.260.0.tgz#666c2584cf627b4296e888b799ec341be42821ac" integrity sha512-78+28EWBhCEE7qlyaHA9OR3IPvbCLiDh3Ckla593TksfFc9vfTsgvH7eS+dr3o9qr31gwGbogcI16yN91PoRjQ== +tldts-core@^6.1.86: + version "6.1.86" + resolved "https://registry.yarnpkg.com/tldts-core/-/tldts-core-6.1.86.tgz#a93e6ed9d505cb54c542ce43feb14c73913265d8" + integrity sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA== + +tldts@^6.1.86: + version "6.1.86" + resolved "https://registry.yarnpkg.com/tldts/-/tldts-6.1.86.tgz#087e0555b31b9725ee48ca7e77edc56115cd82f7" + integrity sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ== + dependencies: + tldts-core "^6.1.86" + toidentifier@1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.1.tgz#3be34321a88a820ed1bd80dfaa33e479fbb8dd35" -- knotmirror 0.0.1