From 982223ad38e428ca4e2269fff56bccd332ca0222 Mon Sep 17 00:00:00 2001 From: Hazelnoot Date: Fri, 4 Jul 2025 12:16:18 -0400 Subject: validate all URLs before fetch --- .../test/unit/core/activitypub/ApUtilityService.ts | 30 ++++++++++++++-------- 1 file changed, 20 insertions(+), 10 deletions(-) (limited to 'packages/backend/test/unit') diff --git a/packages/backend/test/unit/core/activitypub/ApUtilityService.ts b/packages/backend/test/unit/core/activitypub/ApUtilityService.ts index 325a94dc5a..a49ba35112 100644 --- a/packages/backend/test/unit/core/activitypub/ApUtilityService.ts +++ b/packages/backend/test/unit/core/activitypub/ApUtilityService.ts @@ -3,30 +3,40 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import type { UtilityService } from '@/core/UtilityService.js'; import type { IObject } from '@/core/activitypub/type.js'; import type { EnvService } from '@/core/EnvService.js'; +import type { MiMeta } from '@/models/Meta.js'; +import type { Config } from '@/config.js'; import { ApUtilityService } from '@/core/activitypub/ApUtilityService.js'; +import { UtilityService } from '@/core/UtilityService.js'; describe(ApUtilityService, () => { let serviceUnderTest: ApUtilityService; let env: Record; beforeEach(() => { - const utilityService = { - punyHostPSLDomain(input: string) { - const host = new URL(input).host; - const parts = host.split('.'); - return `${parts[parts.length - 2]}.${parts[parts.length - 1]}`; - }, - } as unknown as UtilityService; - env = {}; const envService = { env, } as unknown as EnvService; - serviceUnderTest = new ApUtilityService(utilityService, envService); + const config = { + host: 'example.com', + blockedHosts: [], + silencedHosts: [], + mediaSilencedHosts: [], + federationHosts: [], + bubbleInstances: [], + deliverSuspendedSoftware: [], + federation: 'all', + } as unknown as Config; + const meta = { + + } as MiMeta; + + const utilityService = new UtilityService(config, meta, envService); + + serviceUnderTest = new ApUtilityService(utilityService); }); describe('assertIdMatchesUrlAuthority', () => { -- cgit v1.2.3-freya From af967fe6bee8e06470f10bc1a0e274fc0db9d66c Mon Sep 17 00:00:00 2001 From: Hazelnoot Date: Tue, 8 Jul 2025 11:01:56 -0400 Subject: refactor actor validation to reduce code duplication --- packages/backend/src/core/UtilityService.ts | 4 +- .../src/core/activitypub/ApUtilityService.ts | 86 ++++++++++++- .../src/core/activitypub/models/ApPersonService.ts | 141 ++++++--------------- packages/backend/src/core/activitypub/type.ts | 6 +- .../test/unit/FetchInstanceMetadataService.ts | 2 + .../test/unit/core/activitypub/ApUtilityService.ts | 112 +++++++++++++++- 6 files changed, 242 insertions(+), 109 deletions(-) (limited to 'packages/backend/test/unit') diff --git a/packages/backend/src/core/UtilityService.ts b/packages/backend/src/core/UtilityService.ts index 281edccca3..27d3cb7776 100644 --- a/packages/backend/src/core/UtilityService.ts +++ b/packages/backend/src/core/UtilityService.ts @@ -10,8 +10,8 @@ import psl from 'psl'; import { DI } from '@/di-symbols.js'; import type { Config } from '@/config.js'; import { bindThis } from '@/decorators.js'; -import { MiMeta, SoftwareSuspension } from '@/models/Meta.js'; -import { MiInstance } from '@/models/Instance.js'; +import type { MiMeta } from '@/models/Meta.js'; +import type { MiInstance } from '@/models/Instance.js'; import { IdentifiableError } from '@/misc/identifiable-error.js'; import { EnvService } from '@/core/EnvService.js'; diff --git a/packages/backend/src/core/activitypub/ApUtilityService.ts b/packages/backend/src/core/activitypub/ApUtilityService.ts index eede48f0c6..26ea0cd632 100644 --- a/packages/backend/src/core/activitypub/ApUtilityService.ts +++ b/packages/backend/src/core/activitypub/ApUtilityService.ts @@ -7,18 +7,29 @@ import { Injectable } from '@nestjs/common'; import { UtilityService } from '@/core/UtilityService.js'; import { IdentifiableError } from '@/misc/identifiable-error.js'; import { toArray } from '@/misc/prelude/array.js'; -import { getApId, getOneApHrefNullable, IObject } from '@/core/activitypub/type.js'; +import { getApId, getNullableApId, getOneApHrefNullable } from '@/core/activitypub/type.js'; +import type { IObject, IObjectWithId } from '@/core/activitypub/type.js'; +import { bindThis } from '@/decorators.js'; +import { renderInlineError } from '@/misc/render-inline-error.js'; +import { LoggerService } from '@/core/LoggerService.js'; +import type Logger from '@/logger.js'; @Injectable() export class ApUtilityService { + private readonly logger: Logger; + constructor( private readonly utilityService: UtilityService, - ) {} + loggerService: LoggerService, + ) { + this.logger = loggerService.getLogger('ap-utility'); + } /** * Verifies that the object's ID has the same authority as the provided URL. * Returns on success, throws on any validation error. */ + @bindThis public assertIdMatchesUrlAuthority(object: IObject, url: string): void { // This throws if the ID is missing or invalid, but that's ok. // Anonymous objects are impossible to verify, so we don't allow fetching them. @@ -34,6 +45,7 @@ export class ApUtilityService { /** * Checks if two URLs have the same host authority */ + @bindThis public haveSameAuthority(url1: string, url2: string): boolean { if (url1 === url2) return true; @@ -51,6 +63,7 @@ export class ApUtilityService { * @throws {IdentifiableError} if object does not have an ID * @returns the best URL, or null if none were found */ + @bindThis public findBestObjectUrl(object: IObject): string | null { const targetUrl = getApId(object); const targetAuthority = this.utilityService.punyHostPSLDomain(targetUrl); @@ -81,6 +94,75 @@ export class ApUtilityService { return acceptableUrls[0]?.url ?? null; } + + /** + * Sanitizes an inline / nested Object property within an AP object. + * + * Returns true if the property contains a valid string URL, object w/ valid ID, or an array containing one of those. + * Returns false and erases the property if it doesn't contain a valid value. + * + * Arrays are automatically flattened. + * Falsy values (including null) are collapsed to undefined. + * @param obj Object containing the property to validate + * @param key Key of the property in obj + * @param parentUri URI of the object that contains this inline object. + * @param parentHost PSL host of parentUri + * @param keyPath If obj is *itself* a nested object, set this to the property path from root to obj (including the trailing '.'). This does not affect the logic, but improves the clarity of logs. + */ + @bindThis + public sanitizeInlineObject(obj: Partial>, key: Key, parentUri: string | URL, parentHost: string, keyPath = ''): obj is Partial> { + let value: unknown = obj[key]; + + // Unpack arrays + if (Array.isArray(value)) { + value = value[0]; + } + + // Clear the value - we'll add it back once we have a confirmed ID + obj[key] = undefined; + + // Collapse falsy values to undefined + if (!value) { + return false; + } + + // Exclude nested arrays + if (Array.isArray(value)) { + this.logger.warn(`Excluding ${keyPath}${key} from object ${parentUri}: nested arrays are prohibited`); + return false; + } + + // Exclude incorrect types + if (typeof(value) !== 'string' && typeof(value) !== 'object') { + this.logger.warn(`Excluding ${keyPath}${key} from object ${parentUri}: incorrect type ${typeof(value)}`); + return false; + } + + const valueId = getNullableApId(value); + if (!valueId) { + // Exclude missing ID + this.logger.warn(`Excluding ${keyPath}${key} from object ${parentUri}: missing or invalid ID`); + return false; + } + + try { + const parsed = this.utilityService.assertUrl(valueId); + const parsedHost = this.utilityService.punyHostPSLDomain(parsed); + if (parsedHost !== parentHost) { + // Exclude wrong host + this.logger.warn(`Excluding ${keyPath}${key} from object ${parentUri}: wrong host in ${valueId} (got ${parsedHost}, expected ${parentHost})`); + return false; + } + } catch (err) { + // Exclude invalid URLs + this.logger.warn(`Excluding ${keyPath}${key} from object ${parentUri}: invalid URL ${valueId}: ${renderInlineError(err)}`); + return false; + } + + // Success - store the sanitized value and return + obj[key] = value as string | IObjectWithId; + return true; + } } function isAcceptableUrlType(type: string | undefined): boolean { diff --git a/packages/backend/src/core/activitypub/models/ApPersonService.ts b/packages/backend/src/core/activitypub/models/ApPersonService.ts index 05bd97a3e3..b3fd17e7a0 100644 --- a/packages/backend/src/core/activitypub/models/ApPersonService.ts +++ b/packages/backend/src/core/activitypub/models/ApPersonService.ts @@ -46,7 +46,7 @@ import { verifyFieldLinks } from '@/misc/verify-field-link.js'; import { isRetryableError } from '@/misc/is-retryable-error.js'; import { renderInlineError } from '@/misc/render-inline-error.js'; import { IdentifiableError } from '@/misc/identifiable-error.js'; -import { getApId, getApType, getNullableApId, isActor, isCollection, isCollectionOrOrderedCollection, isPropertyValue } from '../type.js'; +import { getApId, getApType, isActor, isCollection, isCollectionOrOrderedCollection, isPropertyValue } from '../type.js'; import { extractApHashtags } from './tag.js'; import type { OnModuleInit } from '@nestjs/common'; import type { ApNoteService } from './ApNoteService.js'; @@ -159,46 +159,32 @@ export class ApPersonService implements OnModuleInit, OnApplicationShutdown { const parsedUri = this.utilityService.assertUrl(uri); const expectHost = this.utilityService.punyHostPSLDomain(parsedUri); + // Validate type if (!isActor(x)) { throw new UnrecoverableError(`invalid Actor ${uri}: unknown type '${x.type}'`); } - if (!(typeof x.id === 'string' && x.id.length > 0)) { - throw new UnrecoverableError(`invalid Actor ${uri}: wrong id type`); + // Validate id + if (!x.id) { + throw new UnrecoverableError(`invalid Actor ${uri}: missing id`); } - - if (!(typeof x.inbox === 'string' && x.inbox.length > 0)) { - throw new UnrecoverableError(`invalid Actor ${uri}: wrong inbox type`); + if (typeof(x.id) !== 'string') { + throw new UnrecoverableError(`invalid Actor ${uri}: wrong id type ${typeof(x.id)}`); + } + const parsedId = this.utilityService.assertUrl(x.id); + const idHost = this.utilityService.punyHostPSLDomain(parsedId); + if (idHost !== expectHost) { + throw new UnrecoverableError(`invalid Actor ${uri}: wrong host in id ${x.id} (got ${parsedId}, expected ${expectHost})`); } - this.utilityService.assertUrl(x.inbox); - const inboxHost = this.utilityService.punyHostPSLDomain(x.inbox); - if (inboxHost !== expectHost) { - throw new UnrecoverableError(`invalid Actor ${uri}: wrong inbox host ${inboxHost}`); + // Validate inbox + this.apUtilityService.sanitizeInlineObject(x, 'inbox', parsedUri, expectHost); + if (!x.inbox || typeof(x.inbox) !== 'string') { + throw new UnrecoverableError(`invalid Actor ${uri}: missing or invalid inbox ${x.inbox}`); } // Sanitize sharedInbox - try { - if (x.sharedInbox) { - const sharedInbox = getNullableApId(x.sharedInbox); - if (sharedInbox) { - const parsed = this.utilityService.assertUrl(sharedInbox); - if (this.utilityService.punyHostPSLDomain(parsed) !== expectHost) { - this.logger.warn(`Excluding sharedInbox for actor ${uri}: wrong host in ${sharedInbox}`); - x.sharedInbox = undefined; - } - } else { - this.logger.warn(`Excluding sharedInbox for actor ${uri}: missing ID`); - x.sharedInbox = undefined; - } - } else { - // Collapse all falsy values to undefined - x.sharedInbox = undefined; - } - } catch { - // Shared inbox is unparseable - strip out - x.sharedInbox = undefined; - } + this.apUtilityService.sanitizeInlineObject(x, 'sharedInbox', parsedUri, expectHost); // Sanitize endpoints object if (typeof(x.endpoints) === 'object') { @@ -211,94 +197,47 @@ export class ApPersonService implements OnModuleInit, OnApplicationShutdown { // Sanitize endpoints.sharedInbox if (x.endpoints) { - try { - if (x.endpoints.sharedInbox) { - const sharedInbox = getNullableApId(x.endpoints.sharedInbox); - if (sharedInbox) { - const parsed = this.utilityService.assertUrl(sharedInbox); - if (this.utilityService.punyHostPSLDomain(parsed) !== expectHost) { - this.logger.warn(`Excluding endpoints.sharedInbox for actor ${uri}: wrong host in ${sharedInbox}`); - x.endpoints.sharedInbox = undefined; - } - } else { - this.logger.warn(`Excluding endpoints.sharedInbox for actor ${uri}: missing ID`); - x.endpoints.sharedInbox = undefined; - } - } else { - // Collapse all falsy values to undefined - x.endpoints.sharedInbox = undefined; - } - } catch { - // Shared inbox is unparseable - strip out - x.endpoints.sharedInbox = undefined; + this.apUtilityService.sanitizeInlineObject(x.endpoints, 'sharedInbox', parsedUri, expectHost, 'endpoints.'); + + if (!x.endpoints.sharedInbox) { + x.endpoints = undefined; } } // Sanitize collections - for (const collection of ['outbox', 'followers', 'following', 'featured'] as (keyof IActor)[]) { - try { - if (x[collection]) { - const collectionUri = getNullableApId(x[collection]); - if (collectionUri) { - const parsed = this.utilityService.assertUrl(collectionUri); - if (this.utilityService.punyHostPSLDomain(parsed) !== expectHost) { - this.logger.warn(`Excluding ${collection} for actor ${uri}: wrong host in ${collectionUri}`); - x[collection] = undefined; - } - } else { - this.logger.warn(`Excluding ${collection} for actor ${uri}: missing ID`); - x[collection] = undefined; - } - } else { - // Collapse all falsy values to undefined - x[collection] = undefined; - } - } catch { - // Collection is unparseable - strip out - x[collection] = undefined; - } + for (const collection of ['outbox', 'followers', 'following', 'featured'] as const) { + this.apUtilityService.sanitizeInlineObject(x, collection, parsedUri, expectHost); } + // Validate username if (!(typeof x.preferredUsername === 'string' && x.preferredUsername.length > 0 && x.preferredUsername.length <= 128 && /^\w([\w-.]*\w)?$/.test(x.preferredUsername))) { throw new UnrecoverableError(`invalid Actor ${uri}: wrong username`); } + // Sanitize name // These fields are only informational, and some AP software allows these // fields to be very long. If they are too long, we cut them off. This way // we can at least see these users and their activities. - if (x.name) { - if (!(typeof x.name === 'string' && x.name.length > 0)) { - throw new UnrecoverableError(`invalid Actor ${uri}: wrong name`); - } - x.name = truncate(x.name, nameLength); - } else if (x.name === '') { - // Mastodon emits empty string when the name is not set. + if (!x.name) { x.name = undefined; - } - if (x.summary) { - if (!(typeof x.summary === 'string' && x.summary.length > 0)) { - throw new UnrecoverableError(`invalid Actor ${uri}: wrong summary`); - } - x.summary = truncate(x.summary, summaryLength); + } else if (typeof(x.name) !== 'string') { + this.logger.warn(`Excluding name from object ${uri}: incorrect type ${typeof(x)}`); + x.name = undefined; + } else { + x.name = truncate(x.name, nameLength); } - const parsedId = this.utilityService.assertUrl(x.id); - const idHost = this.utilityService.punyHostPSLDomain(parsedId); - if (idHost !== expectHost) { - throw new UnrecoverableError(`invalid Actor ${uri}: wrong id ${x.id}`); + // Sanitize summary + if (!x.summary) { + x.summary = undefined; + } else if (typeof(x.summary) !== 'string') { + this.logger.warn(`Excluding summary from object ${uri}: incorrect type ${typeof(x)}`); + } else { + x.summary = truncate(x.summary, summaryLength); } - if (x.publicKey) { - if (typeof x.publicKey.id !== 'string') { - throw new UnrecoverableError(`invalid Actor ${uri}: wrong publicKey.id type`); - } - - const parsed = this.utilityService.assertUrl(x.publicKey.id); - const publicKeyIdHost = this.utilityService.punyHostPSLDomain(parsed); - if (publicKeyIdHost !== expectHost) { - throw new UnrecoverableError(`invalid Actor ${uri}: wrong publicKey.id ${x.publicKey.id}`); - } - } + // Sanitize publicKey + this.apUtilityService.sanitizeInlineObject(x, 'publicKey', parsedUri, expectHost); return x; } diff --git a/packages/backend/src/core/activitypub/type.ts b/packages/backend/src/core/activitypub/type.ts index 554420d670..ebe29a4fe6 100644 --- a/packages/backend/src/core/activitypub/type.ts +++ b/packages/backend/src/core/activitypub/type.ts @@ -86,7 +86,7 @@ export function getOneApId(value: ApObject): string { /** * Get ActivityStreams Object id */ -export function getApId(value: string | IObject | [string | IObject], sourceForLogs?: string): string { +export function getApId(value: unknown | [unknown] | unknown[], sourceForLogs?: string): string { const id = getNullableApId(value); if (id == null) { @@ -102,7 +102,7 @@ export function getApId(value: string | IObject | [string | IObject], sourceForL /** * Get ActivityStreams Object id, or null if not present */ -export function getNullableApId(source: string | IObject | [string | IObject]): string | null { +export function getNullableApId(source: unknown | [unknown] | unknown[]): string | null { const value: unknown = fromTuple(source); if (value != null) { @@ -276,7 +276,7 @@ export interface IActor extends IObject { followers?: string | ICollection | IOrderedCollection; following?: string | ICollection | IOrderedCollection; featured?: string | IOrderedCollection; - outbox: string | IOrderedCollection; + outbox?: string | IOrderedCollection; endpoints?: { sharedInbox?: string; }; diff --git a/packages/backend/test/unit/FetchInstanceMetadataService.ts b/packages/backend/test/unit/FetchInstanceMetadataService.ts index 1e3605aafc..812ee38703 100644 --- a/packages/backend/test/unit/FetchInstanceMetadataService.ts +++ b/packages/backend/test/unit/FetchInstanceMetadataService.ts @@ -16,6 +16,7 @@ import { HttpRequestService } from '@/core/HttpRequestService.js'; import { LoggerService } from '@/core/LoggerService.js'; import { UtilityService } from '@/core/UtilityService.js'; import { IdService } from '@/core/IdService.js'; +import { EnvService } from '@/core/EnvService.js'; import { DI } from '@/di-symbols.js'; function mockRedis() { @@ -46,6 +47,7 @@ describe('FetchInstanceMetadataService', () => { LoggerService, UtilityService, IdService, + EnvService, ], }) .useMocker((token) => { diff --git a/packages/backend/test/unit/core/activitypub/ApUtilityService.ts b/packages/backend/test/unit/core/activitypub/ApUtilityService.ts index a49ba35112..7b564b1fdd 100644 --- a/packages/backend/test/unit/core/activitypub/ApUtilityService.ts +++ b/packages/backend/test/unit/core/activitypub/ApUtilityService.ts @@ -7,6 +7,8 @@ import type { IObject } from '@/core/activitypub/type.js'; import type { EnvService } from '@/core/EnvService.js'; import type { MiMeta } from '@/models/Meta.js'; import type { Config } from '@/config.js'; +import type { LoggerService } from '@/core/LoggerService.js'; +import Logger from '@/logger.js'; import { ApUtilityService } from '@/core/activitypub/ApUtilityService.js'; import { UtilityService } from '@/core/UtilityService.js'; @@ -36,7 +38,17 @@ describe(ApUtilityService, () => { const utilityService = new UtilityService(config, meta, envService); - serviceUnderTest = new ApUtilityService(utilityService); + const loggerService = { + getLogger(domain: string) { + const logger = new Logger(domain); + Object.defineProperty(logger, 'log', { + value: () => {}, + }); + return logger; + }, + } as unknown as LoggerService; + + serviceUnderTest = new ApUtilityService(utilityService, loggerService); }); describe('assertIdMatchesUrlAuthority', () => { @@ -361,4 +373,102 @@ describe(ApUtilityService, () => { expect(result).toBe('http://example.com/1'); }); }); + + describe('sanitizeInlineObject', () => { + it('should exclude nested arrays', () => { + const input = { + test: [[]] as unknown as string[], + }; + + const result = serviceUnderTest.sanitizeInlineObject(input, 'test', 'https://example.com/actor', 'example.com'); + + expect(result).toBe(false); + }); + + it('should exclude incorrect type', () => { + const input = { + test: 0 as unknown as string, + }; + + const result = serviceUnderTest.sanitizeInlineObject(input, 'test', 'https://example.com/actor', 'example.com'); + + expect(result).toBe(false); + }); + + it('should exclude missing ID', () => { + const input = { + test: { + id: undefined, + }, + }; + + const result = serviceUnderTest.sanitizeInlineObject(input, 'test', 'https://example.com/actor', 'example.com'); + + expect(result).toBe(false); + }); + + it('should exclude wrong host', () => { + const input = { + test: 'https://wrong.com/object', + }; + + const result = serviceUnderTest.sanitizeInlineObject(input, 'test', 'https://example.com/actor', 'example.com'); + + expect(result).toBe(false); + }); + + it('should exclude invalid URLs', () => { + const input = { + test: 'https://user@example.com/object', + }; + + const result = serviceUnderTest.sanitizeInlineObject(input, 'test', 'https://example.com/actor', 'example.com'); + + expect(result).toBe(false); + }); + + it('should accept string', () => { + const input = { + test: 'https://example.com/object', + }; + + const result = serviceUnderTest.sanitizeInlineObject(input, 'test', 'https://example.com/actor', 'example.com'); + + expect(result).toBe(true); + }); + + it('should accept array of string', () => { + const input = { + test: ['https://example.com/object'], + }; + + const result = serviceUnderTest.sanitizeInlineObject(input, 'test', 'https://example.com/actor', 'example.com'); + + expect(result).toBe(true); + }); + + it('should accept object', () => { + const input = { + test: { + id: 'https://example.com/object', + }, + }; + + const result = serviceUnderTest.sanitizeInlineObject(input, 'test', 'https://example.com/actor', 'example.com'); + + expect(result).toBe(true); + }); + + it('should accept array of object', () => { + const input = { + test: [{ + id: 'https://example.com/object', + }], + }; + + const result = serviceUnderTest.sanitizeInlineObject(input, 'test', 'https://example.com/actor', 'example.com'); + + expect(result).toBe(true); + }); + }); }); -- cgit v1.2.3-freya From 3c59a7ae01f7ea7094178cf961c3f4a668672f08 Mon Sep 17 00:00:00 2001 From: Hazelnoot Date: Tue, 8 Jul 2025 11:27:31 -0400 Subject: allow HTTP connections to private IPs --- packages/backend/src/core/HttpRequestService.ts | 17 +++++++++++--- packages/backend/src/core/UtilityService.ts | 8 +++---- .../backend/test/unit/core/HttpRequestService.ts | 26 ++++++++++++++++++++-- 3 files changed, 42 insertions(+), 9 deletions(-) (limited to 'packages/backend/test/unit') diff --git a/packages/backend/src/core/HttpRequestService.ts b/packages/backend/src/core/HttpRequestService.ts index 046b0dc244..bbc127fa86 100644 --- a/packages/backend/src/core/HttpRequestService.ts +++ b/packages/backend/src/core/HttpRequestService.ts @@ -20,7 +20,6 @@ import type { IObject, IObjectWithId } from '@/core/activitypub/type.js'; import { UtilityService } from '@/core/UtilityService.js'; import { ApUtilityService } from '@/core/activitypub/ApUtilityService.js'; import type { Response } from 'node-fetch'; -import type { URL } from 'node:url'; import type { Socket } from 'node:net'; export type HttpRequestSendOptions = { @@ -28,6 +27,15 @@ export type HttpRequestSendOptions = { validators?: ((res: Response) => void)[]; }; +export function isPrivateUrl(url: URL): boolean { + if (!ipaddr.isValid(url.hostname)) { + return false; + } + + const ip = ipaddr.parse(url.hostname); + return ip.range() !== 'unicast'; +} + export function isPrivateIp(allowedPrivateNetworks: PrivateNetwork[] | undefined, ip: string, port?: number): boolean { const parsedIp = ipaddr.parse(ip); @@ -303,6 +311,7 @@ export class HttpRequestService { timeout?: number, size?: number, isLocalAddressAllowed?: boolean, + allowHttp?: boolean, } = {}, extra: HttpRequestSendOptions = { throwErrorWhenResponseNotOk: true, @@ -311,7 +320,9 @@ export class HttpRequestService { ): Promise { const timeout = args.timeout ?? 5000; - this.utilityService.assertUrl(url); + const parsedUrl = new URL(url); + const allowHttp = args.allowHttp || isPrivateUrl(parsedUrl); + this.utilityService.assertUrl(parsedUrl, allowHttp); const controller = new AbortController(); setTimeout(() => { @@ -320,7 +331,7 @@ export class HttpRequestService { const isLocalAddressAllowed = args.isLocalAddressAllowed ?? false; - const res = await fetch(url, { + const res = await fetch(parsedUrl, { method: args.method ?? 'GET', headers: { 'User-Agent': this.config.userAgent, diff --git a/packages/backend/src/core/UtilityService.ts b/packages/backend/src/core/UtilityService.ts index 27d3cb7776..a90774cf59 100644 --- a/packages/backend/src/core/UtilityService.ts +++ b/packages/backend/src/core/UtilityService.ts @@ -226,7 +226,7 @@ export class UtilityService { * @throws {IdentifiableError} If URL contains credentials */ @bindThis - public assertUrl(url: string | URL): URL | never { + public assertUrl(url: string | URL, allowHttp?: boolean): URL | never { // If string, parse and validate if (typeof(url) === 'string') { try { @@ -237,7 +237,7 @@ export class UtilityService { } // Must be HTTPS - if (!this.checkHttps(url)) { + if (!this.checkHttps(url, allowHttp)) { throw new IdentifiableError('0bedd29b-e3bf-4604-af51-d3352e2518af', `invalid url ${url}: unsupported protocol ${url.protocol}`); } @@ -255,12 +255,12 @@ export class UtilityService { * Based on check-https.ts. */ @bindThis - public checkHttps(url: string | URL): boolean { + public checkHttps(url: string | URL, allowHttp = false): boolean { const isNonProd = this.envService.env.NODE_ENV !== 'production'; try { const proto = new URL(url).protocol; - return proto === 'https:' || (proto === 'http:' && isNonProd); + return proto === 'https:' || (proto === 'http:' && (isNonProd || allowHttp)); } catch { // Invalid URLs don't "count" as HTTPS return false; diff --git a/packages/backend/test/unit/core/HttpRequestService.ts b/packages/backend/test/unit/core/HttpRequestService.ts index a2f4604e7b..5aeeb1e26f 100644 --- a/packages/backend/test/unit/core/HttpRequestService.ts +++ b/packages/backend/test/unit/core/HttpRequestService.ts @@ -3,11 +3,11 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -import { jest } from '@jest/globals'; +import { describe, jest } from '@jest/globals'; import type { Mock } from 'jest-mock'; import type { PrivateNetwork } from '@/config.js'; import type { Socket } from 'net'; -import { HttpRequestService, isPrivateIp, validateSocketConnect } from '@/core/HttpRequestService.js'; +import { HttpRequestService, isPrivateIp, isPrivateUrl, validateSocketConnect } from '@/core/HttpRequestService.js'; import { parsePrivateNetworks } from '@/config.js'; describe(HttpRequestService, () => { @@ -53,6 +53,28 @@ describe(HttpRequestService, () => { }); }); + describe('isPrivateUrl', () => { + it('should return false when URL is not an IP', () => { + const result = isPrivateUrl(new URL('https://example.com')); + expect(result).toBe(false); + }); + + it('should return false when IP is public', () => { + const result = isPrivateUrl(new URL('https://23.192.228.80')); + expect(result).toBe(false); + }); + + it('should return true when IP is private', () => { + const result = isPrivateUrl(new URL('https://127.0.0.1')); + expect(result).toBe(true); + }); + + it('should return true when IP is private with port and path', () => { + const result = isPrivateUrl(new URL('https://127.0.0.1:443/some/path')); + expect(result).toBe(true); + }); + }); + describe('validateSocketConnect', () => { let fakeSocket: Socket; let fakeSocketMutable: { -- cgit v1.2.3-freya From 25622b536c982f717c72b0cf039322d45c36a55b Mon Sep 17 00:00:00 2001 From: Hazelnoot Date: Fri, 25 Jul 2025 16:28:53 -0400 Subject: resolve domain names when checking for private URLs --- packages/backend/src/core/HttpRequestService.ts | 30 ++++++++--- .../src/core/activitypub/models/ApPersonService.ts | 1 - .../backend/test/unit/core/HttpRequestService.ts | 60 ++++++++++++++++------ 3 files changed, 65 insertions(+), 26 deletions(-) (limited to 'packages/backend/test/unit') diff --git a/packages/backend/src/core/HttpRequestService.ts b/packages/backend/src/core/HttpRequestService.ts index bbc127fa86..34aaada9f2 100644 --- a/packages/backend/src/core/HttpRequestService.ts +++ b/packages/backend/src/core/HttpRequestService.ts @@ -27,16 +27,27 @@ export type HttpRequestSendOptions = { validators?: ((res: Response) => void)[]; }; -export function isPrivateUrl(url: URL): boolean { - if (!ipaddr.isValid(url.hostname)) { - return false; +export async function isPrivateUrl(url: URL, lookup: net.LookupFunction): Promise { + const ip = await resolveIp(url, lookup); + return ip.range() !== 'unicast'; +} + +export async function resolveIp(url: URL, lookup: net.LookupFunction) { + if (ipaddr.isValid(url.hostname)) { + return ipaddr.parse(url.hostname); } - const ip = ipaddr.parse(url.hostname); - return ip.range() !== 'unicast'; + const resolvedIp = await new Promise((resolve, reject) => { + lookup(url.hostname, {}, (err, address) => { + if (err) reject(err); + else resolve(address as string); + }); + }); + + return ipaddr.parse(resolvedIp); } -export function isPrivateIp(allowedPrivateNetworks: PrivateNetwork[] | undefined, ip: string, port?: number): boolean { +export function isAllowedPrivateIp(allowedPrivateNetworks: PrivateNetwork[] | undefined, ip: string, port?: number): boolean { const parsedIp = ipaddr.parse(ip); for (const { cidr, ports } of allowedPrivateNetworks ?? []) { @@ -53,7 +64,7 @@ export function isPrivateIp(allowedPrivateNetworks: PrivateNetwork[] | undefined export function validateSocketConnect(allowedPrivateNetworks: PrivateNetwork[] | undefined, socket: Socket): void { const address = socket.remoteAddress; if (address && ipaddr.isValid(address)) { - if (isPrivateIp(allowedPrivateNetworks, address, socket.remotePort)) { + if (isAllowedPrivateIp(allowedPrivateNetworks, address, socket.remotePort)) { socket.destroy(new Error(`Blocked address: ${address}`)); } } @@ -142,6 +153,7 @@ export class HttpRequestService { private config: Config, private readonly apUtilityService: ApUtilityService, private readonly utilityService: UtilityService, + private readonly lookup: net.LookupFunction, ) { const cache = new CacheableLookup({ maxTtl: 3600, // 1hours @@ -149,6 +161,8 @@ export class HttpRequestService { lookup: false, // nativeのdns.lookupにfallbackしない }); + this.lookup = cache.lookup as unknown as net.LookupFunction; + const agentOption = { keepAlive: true, keepAliveMsecs: 30 * 1000, @@ -321,7 +335,7 @@ export class HttpRequestService { const timeout = args.timeout ?? 5000; const parsedUrl = new URL(url); - const allowHttp = args.allowHttp || isPrivateUrl(parsedUrl); + const allowHttp = args.allowHttp || await isPrivateUrl(parsedUrl, this.lookup); this.utilityService.assertUrl(parsedUrl, allowHttp); const controller = new AbortController(); diff --git a/packages/backend/src/core/activitypub/models/ApPersonService.ts b/packages/backend/src/core/activitypub/models/ApPersonService.ts index b3fd17e7a0..30124949bb 100644 --- a/packages/backend/src/core/activitypub/models/ApPersonService.ts +++ b/packages/backend/src/core/activitypub/models/ApPersonService.ts @@ -56,7 +56,6 @@ import type { ApLoggerService } from '../ApLoggerService.js'; import type { ApImageService } from './ApImageService.js'; import type { IActor, ICollection, IObject, IOrderedCollection } from '../type.js'; -import { IdentifiableError } from '@/misc/identifiable-error.js'; const nameLength = 128; const summaryLength = 2048; diff --git a/packages/backend/test/unit/core/HttpRequestService.ts b/packages/backend/test/unit/core/HttpRequestService.ts index 5aeeb1e26f..0759306666 100644 --- a/packages/backend/test/unit/core/HttpRequestService.ts +++ b/packages/backend/test/unit/core/HttpRequestService.ts @@ -7,8 +7,9 @@ import { describe, jest } from '@jest/globals'; import type { Mock } from 'jest-mock'; import type { PrivateNetwork } from '@/config.js'; import type { Socket } from 'net'; -import { HttpRequestService, isPrivateIp, isPrivateUrl, validateSocketConnect } from '@/core/HttpRequestService.js'; +import { HttpRequestService, isAllowedPrivateIp, isPrivateUrl, resolveIp, validateSocketConnect } from '@/core/HttpRequestService.js'; import { parsePrivateNetworks } from '@/config.js'; +import { IPv4 } from 'ipaddr.js'; describe(HttpRequestService, () => { let allowedPrivateNetworks: PrivateNetwork[] | undefined; @@ -21,56 +22,81 @@ describe(HttpRequestService, () => { ]); }); - describe('isPrivateIp', () => { + describe(isAllowedPrivateIp, () => { it('should return false when ip public', () => { - const result = isPrivateIp(allowedPrivateNetworks, '74.125.127.100', 80); + const result = isAllowedPrivateIp(allowedPrivateNetworks, '74.125.127.100', 80); expect(result).toBeFalsy(); }); it('should return false when ip private and port matches', () => { - const result = isPrivateIp(allowedPrivateNetworks, '127.0.0.1', 1); + const result = isAllowedPrivateIp(allowedPrivateNetworks, '127.0.0.1', 1); expect(result).toBeFalsy(); }); it('should return false when ip private and all ports undefined', () => { - const result = isPrivateIp(allowedPrivateNetworks, '10.0.0.1', undefined); + const result = isAllowedPrivateIp(allowedPrivateNetworks, '10.0.0.1', undefined); expect(result).toBeFalsy(); }); it('should return true when ip private and no ports specified', () => { - const result = isPrivateIp(allowedPrivateNetworks, '10.0.0.2', 80); + const result = isAllowedPrivateIp(allowedPrivateNetworks, '10.0.0.2', 80); expect(result).toBeTruthy(); }); it('should return true when ip private and port does not match', () => { - const result = isPrivateIp(allowedPrivateNetworks, '127.0.0.1', 80); + const result = isAllowedPrivateIp(allowedPrivateNetworks, '127.0.0.1', 80); expect(result).toBeTruthy(); }); it('should return true when ip private and port is null but ports are specified', () => { - const result = isPrivateIp(allowedPrivateNetworks, '127.0.0.1', undefined); + const result = isAllowedPrivateIp(allowedPrivateNetworks, '127.0.0.1', undefined); expect(result).toBeTruthy(); }); }); - describe('isPrivateUrl', () => { - it('should return false when URL is not an IP', () => { - const result = isPrivateUrl(new URL('https://example.com')); + const fakeLookup = (host: string, _: unknown, callback: (err: Error | null, ip: string) => void) => { + if (host === 'localhost') { + callback(null, '127.0.0.1'); + } else { + callback(null, '23.192.228.80'); + } + }; + + describe(resolveIp, () => { + it('should parse inline IPs', async () => { + const result = await resolveIp(new URL('https://10.0.0.1'), fakeLookup); + expect(result.toString()).toEqual('10.0.0.1'); + }); + + it('should resolve domain names', async () => { + const result = await resolveIp(new URL('https://localhost'), fakeLookup); + expect(result.toString()).toEqual('127.0.0.1'); + }); + }); + + describe(isPrivateUrl, () => { + it('should return false when URL is public host', async () => { + const result = await isPrivateUrl(new URL('https://example.com'), fakeLookup); expect(result).toBe(false); }); - it('should return false when IP is public', () => { - const result = isPrivateUrl(new URL('https://23.192.228.80')); + it('should return true when URL is private host', async () => { + const result = await isPrivateUrl(new URL('https://localhost'), fakeLookup); + expect(result).toBe(true); + }); + + it('should return false when IP is public', async () => { + const result = await isPrivateUrl(new URL('https://23.192.228.80'), fakeLookup); expect(result).toBe(false); }); - it('should return true when IP is private', () => { - const result = isPrivateUrl(new URL('https://127.0.0.1')); + it('should return true when IP is private', async () => { + const result = await isPrivateUrl(new URL('https://127.0.0.1'), fakeLookup); expect(result).toBe(true); }); - it('should return true when IP is private with port and path', () => { - const result = isPrivateUrl(new URL('https://127.0.0.1:443/some/path')); + it('should return true when IP is private with port and path', async () => { + const result = await isPrivateUrl(new URL('https://127.0.0.1:443/some/path'), fakeLookup); expect(result).toBe(true); }); }); -- cgit v1.2.3-freya From db15ac0fbb8bb4474f365a42a1df9056828d26b3 Mon Sep 17 00:00:00 2001 From: Hazelnoot Date: Fri, 25 Jul 2025 16:32:54 -0400 Subject: fix DI error in HttpRequestService.ts --- packages/backend/src/core/HttpRequestService.ts | 6 +++++- packages/backend/test/unit/core/HttpRequestService.ts | 1 - 2 files changed, 5 insertions(+), 2 deletions(-) (limited to 'packages/backend/test/unit') diff --git a/packages/backend/src/core/HttpRequestService.ts b/packages/backend/src/core/HttpRequestService.ts index 34aaada9f2..bd72fefe4f 100644 --- a/packages/backend/src/core/HttpRequestService.ts +++ b/packages/backend/src/core/HttpRequestService.ts @@ -148,12 +148,16 @@ export class HttpRequestService { */ public readonly httpsAgent: https.Agent; + /** + * Get shared DNS resolver + */ + public readonly lookup: net.LookupFunction; + constructor( @Inject(DI.config) private config: Config, private readonly apUtilityService: ApUtilityService, private readonly utilityService: UtilityService, - private readonly lookup: net.LookupFunction, ) { const cache = new CacheableLookup({ maxTtl: 3600, // 1hours diff --git a/packages/backend/test/unit/core/HttpRequestService.ts b/packages/backend/test/unit/core/HttpRequestService.ts index 0759306666..ccce32ffee 100644 --- a/packages/backend/test/unit/core/HttpRequestService.ts +++ b/packages/backend/test/unit/core/HttpRequestService.ts @@ -9,7 +9,6 @@ import type { PrivateNetwork } from '@/config.js'; import type { Socket } from 'net'; import { HttpRequestService, isAllowedPrivateIp, isPrivateUrl, resolveIp, validateSocketConnect } from '@/core/HttpRequestService.js'; import { parsePrivateNetworks } from '@/config.js'; -import { IPv4 } from 'ipaddr.js'; describe(HttpRequestService, () => { let allowedPrivateNetworks: PrivateNetwork[] | undefined; -- cgit v1.2.3-freya