From ee919505185a59be4ac687f6452d0db18520be50 Mon Sep 17 00:00:00 2001 From: Eli Bosley Date: Tue, 27 Oct 2026 21:30:41 -0400 Subject: [PATCH 01/10] chore(ai-review): record transport fix design forecast --- ...lient-identity-ws-policy-73041c5cc2c5.json | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 .limetech/ai-review-markers/fix-api-client-identity-ws-policy-73041c5cc2c5.json diff --git a/.limetech/ai-review-markers/fix-api-client-identity-ws-policy-73041c5cc2c5.json b/.limetech/ai-review-markers/fix-api-client-identity-ws-policy-73041c5cc2c5.json new file mode 100644 index 0000000000..24cff5f635 --- /dev/null +++ b/.limetech/ai-review-markers/fix-api-client-identity-ws-policy-73041c5cc2c5.json @@ -0,0 +1,25 @@ +{ + "disposition": "PATCH", + "expected_structural_delta": "Five existing production TypeScript modules plus nginx patch asset; zero new runtime owners, dependencies or state stores. About 80-160 added production lines, 10-35 removed; 1-2 new test files and 2-4 extended files with 180-320 test lines.", + "minimum_design": "Extend the existing nginx script modification and throttler guard to preserve trusted client identity; reuse the selected-operation introspection check in graphql-ws before execution.", + "outcome": "Independent OIDC client limits through the supported nginx socket path and consistent disabled-sandbox introspection policy on HTTP and WebSocket.", + "reuse_decisions": [ + { + "decision": "extend", + "name": "RcNginxModification", + "rationale": "Existing owner for rc.nginx patching and reload lifecycle; update static and generated patch on current OS versions." + }, + { + "decision": "extend", + "name": "FastifyThrottlerGuard", + "rationale": "Select raw TCP peer or one validated nginx-provided Unix socket client address." + }, + { + "decision": "reuse", + "name": "Introspection AST policy and graphqlWsOptions", + "rationale": "Apply one selected-operation predicate with dynamic sandbox policy before both transports execute." + } + ], + "schema": "limetech.ai-review-marker.v2", + "stage": "forecast" +} From 6f876da36b277df5390a869aec418e8032883a85 Mon Sep 17 00:00:00 2001 From: Eli Bosley Date: Tue, 27 Oct 2026 21:43:41 -0400 Subject: [PATCH 02/10] fix(auth): preserve client identity through the nginx socket proxy --- .../auth/fastify-throttler.guard.spec.ts | 113 ++++++++++++++++++ .../auth/fastify-throttler.guard.ts | 17 ++- .../__test__/rc-nginx.modification.spec.ts | 95 +++++++++++++++ .../snapshots/rc.nginx.modified.snapshot | 1 + .../modifications/patches/rc-nginx.patch | 16 ++- .../modifications/rc-nginx.modification.ts | 96 ++++++++------- 6 files changed, 288 insertions(+), 50 deletions(-) create mode 100644 api/src/unraid-api/auth/fastify-throttler.guard.spec.ts create mode 100644 api/src/unraid-api/unraid-file-modifier/modifications/__test__/rc-nginx.modification.spec.ts diff --git a/api/src/unraid-api/auth/fastify-throttler.guard.spec.ts b/api/src/unraid-api/auth/fastify-throttler.guard.spec.ts new file mode 100644 index 0000000000..882bd9ea50 --- /dev/null +++ b/api/src/unraid-api/auth/fastify-throttler.guard.spec.ts @@ -0,0 +1,113 @@ +import { Reflector } from '@nestjs/core'; +import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host.js'; +import { ThrottlerStorageService } from '@nestjs/throttler'; +import { mkdtemp, rm } from 'node:fs/promises'; +import http from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import Fastify from 'fastify'; +import { afterEach, describe, expect, it } from 'vitest'; + +import { FastifyThrottlerGuard } from '@app/unraid-api/auth/fastify-throttler.guard.js'; + +describe('FastifyThrottlerGuard client identity', () => { + const cleanups: Array<() => Promise | void> = []; + afterEach(async () => { + for (const cleanup of cleanups.reverse()) await cleanup(); + cleanups.length = 0; + }); + + const createServer = async () => { + const storage = new ThrottlerStorageService(); + cleanups.push(() => storage.onApplicationShutdown()); + const guard = new FastifyThrottlerGuard([{ ttl: 60_000, limit: 2 }], storage, new Reflector()); + await guard.onModuleInit(); + const server = Fastify({ trustProxy: 'loopback' }); + cleanups.push(() => server.close()); + class Controller { + authorize() {} + callback() {} + } + for (const path of ['/authorize', '/callback']) { + const handler = + path === '/authorize' ? Controller.prototype.authorize : Controller.prototype.callback; + server.get(path, async (req, res) => { + const context = new ExecutionContextHost([req, res], Controller, handler); + try { + await guard.canActivate(context); + return res.code(204).send(); + } catch (error) { + const status = + error instanceof Error && + 'getStatus' in error && + typeof error.getStatus === 'function' + ? error.getStatus() + : 500; + return res.code(status).send(); + } + }); + } + return server; + }; + + it('uses the actual TCP peer even when loopback clients forge forwarded headers', async () => { + const server = await createServer(); + for (const forwarded of ['192.0.2.1', '192.0.2.2']) { + expect( + ( + await server.inject({ + url: '/authorize', + remoteAddress: '127.0.0.2', + headers: { 'x-forwarded-for': forwarded }, + }) + ).statusCode + ).toBe(204); + } + expect( + ( + await server.inject({ + url: '/authorize', + remoteAddress: '127.0.0.2', + headers: { 'x-forwarded-for': '192.0.2.3' }, + }) + ).statusCode + ).toBe(429); + expect((await server.inject({ url: '/authorize', remoteAddress: '127.0.0.3' })).statusCode).toBe( + 204 + ); + expect((await server.inject({ url: '/callback', remoteAddress: '127.0.0.2' })).statusCode).toBe( + 204 + ); + }); + + it('keeps Unix socket clients independent and rejects missing or ambiguous identity', async () => { + const directory = await mkdtemp(join(tmpdir(), 'api-ip-')); + cleanups.push(() => rm(directory, { recursive: true, force: true })); + const server = await createServer(); + const socketPath = join(directory, 'api.sock'); + await server.listen({ path: socketPath }); + const send = (address?: string) => + new Promise((resolve, reject) => { + const request = http.get( + { + socketPath, + path: '/authorize', + headers: address ? { 'x-forwarded-for': address } : {}, + }, + (response) => { + response.resume(); + response.on('end', () => resolve(response.statusCode)); + } + ); + request.on('error', reject); + }); + expect(await send('192.0.2.1')).toBe(204); + expect(await send('192.0.2.1')).toBe(204); + expect(await send('192.0.2.1')).toBe(429); + expect(await send('192.0.2.2')).toBe(204); + expect(await send()).toBe(400); + expect(await send('192.0.2.1, 192.0.2.2')).toBe(400); + expect(await send('invalid')).toBe(400); + }); +}); diff --git a/api/src/unraid-api/auth/fastify-throttler.guard.ts b/api/src/unraid-api/auth/fastify-throttler.guard.ts index 48de4509cf..f951be04a5 100644 --- a/api/src/unraid-api/auth/fastify-throttler.guard.ts +++ b/api/src/unraid-api/auth/fastify-throttler.guard.ts @@ -1,4 +1,4 @@ -import { ExecutionContext, Inject, Injectable, Optional } from '@nestjs/common'; +import { BadRequestException, ExecutionContext, Inject, Injectable, Optional } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { GqlExecutionContext } from '@nestjs/graphql'; import { @@ -9,6 +9,7 @@ import { ThrottlerStorage, ThrottlerStorageService, } from '@nestjs/throttler'; +import { isIP } from 'node:net'; import { type FastifyRequest } from 'fastify'; @@ -26,9 +27,17 @@ export class FastifyThrottlerGuard extends ThrottlerGuard { ); } - protected async getTracker(req: Record): Promise { - const request = req as unknown as FastifyRequest; - return request.ip ?? request.ips?.[0] ?? request.headers?.['x-forwarded-for'] ?? '0.0.0.0'; + protected async getTracker(request: FastifyRequest): Promise { + const peerAddress = request.raw.socket.remoteAddress; + if (peerAddress) return peerAddress; + + // Unix sockets have no peer IP. nginx overwrites this header with its TCP client address. + const forwardedAddress = request.headers['x-forwarded-for']; + if (typeof forwardedAddress === 'string' && isIP(forwardedAddress)) { + return forwardedAddress; + } + + throw new BadRequestException('Client IP address is unavailable'); } getRequestResponse(context: ExecutionContext) { diff --git a/api/src/unraid-api/unraid-file-modifier/modifications/__test__/rc-nginx.modification.spec.ts b/api/src/unraid-api/unraid-file-modifier/modifications/__test__/rc-nginx.modification.spec.ts new file mode 100644 index 0000000000..59346caec6 --- /dev/null +++ b/api/src/unraid-api/unraid-file-modifier/modifications/__test__/rc-nginx.modification.spec.ts @@ -0,0 +1,95 @@ +import { Logger } from '@nestjs/common'; +import { execFile } from 'node:child_process'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { promisify } from 'node:util'; + +import { createPatch } from 'diff'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import RcNginxModification from '@app/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.js'; + +describe('rc.nginx client identity lifecycle', () => { + let directory: string; + beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), 'api-nginx-')); + }); + afterEach(async () => { + await rm(directory, { recursive: true, force: true }); + }); + + it('patches integrated API versions, survives reapply, and rolls back cleanly', async () => { + const original = `CONNECT_CONFIG="existing" +build_locations(){ + cat <<- 'EOF' +\tlocation /graphql { +\t proxy_set_header X-Forwarded-For \\$http_x_forwarded_for; +\t proxy_pass http://unix:/var/run/unraid-api.sock:/graphql; +\t proxy_set_header Host \\$host; +\t} +\tEOF +} +`; + const file = join(directory, 'rc.nginx'); + const previous = original.replace('CONNECT_CONFIG="existing"', 'CONNECT_CONFIG="previous"'); + await writeFile(file, previous); + await writeFile(`${file}.patch`, createPatch(file, original, previous)); + const modification = new RcNginxModification(new Logger()); + modification.filePath = file; + expect((await modification.shouldApply()).shouldApply).toBe(true); + await modification.apply(); + const patched = await readFile(file, 'utf8'); + expect(patched).toContain('proxy_set_header X-Forwarded-For $remote_addr;'); + expect(patched).not.toContain('$http_x_forwarded_for'); + expect(patched.match(/proxy_set_header X-Forwarded-For/g)).toHaveLength(1); + const { stdout } = await promisify(execFile)('/bin/bash', [ + '-c', + 'source "$1"; build_locations', + 'nginx-test', + file, + ]); + expect(stdout).toContain('proxy_set_header X-Forwarded-For $remote_addr;'); + await modification.apply(); + expect(await readFile(file, 'utf8')).toBe(patched); + await modification.rollback(); + expect(await readFile(file, 'utf8')).toBe(original); + }); + it('emits a valid client address variable from the bundled nginx generator', async () => { + const original = await readFile( + new URL('./__fixtures__/downloaded/rc.nginx', import.meta.url), + 'utf8' + ); + const file = join(directory, 'rc.nginx'); + await writeFile(file, original); + const modification = new RcNginxModification(new Logger()); + modification.filePath = file; + await modification.apply(); + const patched = await readFile(file, 'utf8'); + const start = patched.indexOf('build_locations(){'); + const end = patched.indexOf('\n}\n', start); + expect(start).toBeGreaterThan(-1); + expect(end).toBeGreaterThan(start); + const generator = join(directory, 'locations.sh'); + const locations = join(directory, 'locations.conf'); + await writeFile(generator, patched.slice(start, end + 3)); + await promisify(execFile)('/bin/bash', [ + '-c', + 'source "$1"; LOCATIONS="$2"; build_locations', + 'nginx-test', + generator, + locations, + ]); + const generated = await readFile(locations, 'utf8'); + const header = generated + .split('\n') + .filter((line) => line.includes('proxy_set_header X-Forwarded-For')); + expect(header.map((line) => line.trim())).toEqual([ + 'proxy_set_header X-Forwarded-For $remote_addr;', + ]); + await modification.apply(); + expect(await readFile(file, 'utf8')).toBe(patched); + await modification.rollback(); + expect(await readFile(file, 'utf8')).toBe(original); + }); +}); diff --git a/api/src/unraid-api/unraid-file-modifier/modifications/__test__/snapshots/rc.nginx.modified.snapshot b/api/src/unraid-api/unraid-file-modifier/modifications/__test__/snapshots/rc.nginx.modified.snapshot index 7c555fda54..6547894484 100644 --- a/api/src/unraid-api/unraid-file-modifier/modifications/__test__/snapshots/rc.nginx.modified.snapshot +++ b/api/src/unraid-api/unraid-file-modifier/modifications/__test__/snapshots/rc.nginx.modified.snapshot @@ -421,6 +421,7 @@ build_locations(){ allow all; error_log /dev/null crit; proxy_pass http://unix:/var/run/unraid-api.sock:/graphql; + proxy_set_header X-Forwarded-For $remote_addr; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header Upgrade $http_upgrade; diff --git a/api/src/unraid-api/unraid-file-modifier/modifications/patches/rc-nginx.patch b/api/src/unraid-api/unraid-file-modifier/modifications/patches/rc-nginx.patch index fbac95e0bc..2fa9b0725e 100644 --- a/api/src/unraid-api/unraid-file-modifier/modifications/patches/rc-nginx.patch +++ b/api/src/unraid-api/unraid-file-modifier/modifications/patches/rc-nginx.patch @@ -44,7 +44,19 @@ Index: /etc/rc.d/rc.nginx T=' ' if check && [[ $1 == lo ]]; then if [[ $IPV4 == yes ]]; then -@@ -566,11 +584,11 @@ +@@ -401,10 +419,11 @@ + # + location /graphql { + allow all; + error_log /dev/null crit; + proxy_pass http://unix:/var/run/unraid-api.sock:/graphql; ++ proxy_set_header X-Forwarded-For $remote_addr; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_cache_bypass $http_upgrade; +@@ -566,11 +585,11 @@ # extract common name from cert CERTNAME=$(openssl x509 -noout -subject -nameopt multiline -in $CERTPATH | sed -n 's/ *commonName *= //p') # define CSP frame-ancestors for cert @@ -57,7 +69,7 @@ Index: /etc/rc.d/rc.nginx WANIP6=$(curl https://wanip6.unraid.net/ 2>/dev/null) fi if [[ $CERTNAME == *\.myunraid\.net ]]; then -@@ -660,14 +678,14 @@ +@@ -660,14 +679,14 @@ echo "NGINX_WANFQDN=\"$WANFQDN\"" >>$INI echo "NGINX_WANFQDN6=\"$WANFQDN6\"" >>$INI # defined if ts_bundle.pem present: diff --git a/api/src/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.ts b/api/src/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.ts index 6b1c717a3a..f05d8a6c19 100644 --- a/api/src/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.ts +++ b/api/src/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.ts @@ -7,7 +7,7 @@ import { } from '@app/unraid-api/unraid-file-modifier/file-modification.js'; /** - * Patch rc.nginx on < Unraid 7.2.0 to read the updated connect & api config files + * Preserve client identity for the API proxy and backport legacy Connect configuration. * * Backport of https://github.com/unraid/webgui/pull/2269 */ @@ -15,34 +15,23 @@ export default class RcNginxModification extends FileModification { public filePath: string = '/etc/rc.d/rc.nginx' as const; id: string = 'rc-nginx'; - /** - * Generate a patch for the rc.nginx file - * - * Should result in the same patch as - * https://patch-diff.githubusercontent.com/raw/unraid/webgui/pull/2269.patch - * - * @param overridePath - The path to override the default file path - * @returns The patch for the rc.nginx file - */ protected async generatePatch(overridePath?: string): Promise { if (!(await fileExists(this.filePath))) { throw new Error(`File ${this.filePath} not found.`); } const fileContent = await readFile(this.filePath, 'utf8'); - if (!fileContent.includes('MYSERVERS=')) { - throw new Error(`MYSERVERS not found in the file; incorrect target?`); - } - - let newContent = fileContent.replace( - 'MYSERVERS="/boot/config/plugins/dynamix.my.servers/myservers.cfg"', - `CONNECT_CONFIG="/boot/config/plugins/dynamix.my.servers/configs/connect.json" + let newContent = fileContent; + if (fileContent.includes('MYSERVERS=')) { + newContent = newContent.replace( + 'MYSERVERS="/boot/config/plugins/dynamix.my.servers/myservers.cfg"', + `CONNECT_CONFIG="/boot/config/plugins/dynamix.my.servers/configs/connect.json" API_UTILS="/usr/local/share/dynamix.unraid.net/scripts/api_utils.sh"` - ); + ); - if (!newContent.includes('check_remote_access()')) { - newContent = newContent.replace( - '# create listening ports', - `# check if remote access should be enabled + if (!newContent.includes('check_remote_access()')) { + newContent = newContent.replace( + '# create listening ports', + `# check if remote access should be enabled check_remote_access(){ # Check if connect plugin is enabled using api_utils.sh if [[ -f $API_UTILS ]] && $API_UTILS is_api_plugin_enabled "unraid-api-plugin-connect"; then @@ -60,38 +49,57 @@ check_remote_access(){ } # create listening ports` - ); - } - - newContent = newContent.replace( - `if [[ -L /usr/local/sbin/unraid-api ]] && grep -qs 'wanaccess="yes"' $MYSERVERS && ! grep -qs 'username=""' $MYSERVERS; then`, - `if [[ -L /usr/local/sbin/unraid-api ]] && check_remote_access; then` - ); + ); + } - newContent = newContent.replace( - 'for NET in ${!NET_FQDN6[@]}; do', - 'for NET in "${!NET_FQDN6[@]}"; do' - ); - newContent = newContent.replace( - 'for NET in ${!NET_FQDN[@]}; do', - 'for NET in "${!NET_FQDN[@]}"; do' - ); + newContent = newContent.replace( + `if [[ -L /usr/local/sbin/unraid-api ]] && grep -qs 'wanaccess="yes"' $MYSERVERS && ! grep -qs 'username=""' $MYSERVERS; then`, + `if [[ -L /usr/local/sbin/unraid-api ]] && check_remote_access; then` + ); - // Add robots.txt Access-Control-Allow-Origin header if not already present - if (!newContent.includes('#robots.txt any origin')) { newContent = newContent.replace( - 'location = /robots.txt {', - // prettier-ignore - `location = /robots.txt { -\t add_header Access-Control-Allow-Origin *; #robots.txt any origin` + 'for NET in ${!NET_FQDN6[@]}; do', + 'for NET in "${!NET_FQDN6[@]}"; do' + ); + newContent = newContent.replace( + 'for NET in ${!NET_FQDN[@]}; do', + 'for NET in "${!NET_FQDN[@]}"; do' ); + + // Add robots.txt Access-Control-Allow-Origin header if not already present + if (!newContent.includes('#robots.txt any origin')) { + newContent = newContent.replace( + 'location = /robots.txt {', + // prettier-ignore + `location = /robots.txt { +\t add_header Access-Control-Allow-Origin *; #robots.txt any origin` + ); + } } + newContent = newContent.replace( + /(^[\t ]*location \/graphql \{\n)([\s\S]*?)(^[\t ]*\})/gm, + (match: string, opening: string, directives: string, closing: string) => { + const proxyLine = + /^[\t ]*proxy_pass http:\/\/unix:\/var\/run\/unraid-api\.sock:\/graphql;[^\n]*\n/m; + if (!proxyLine.test(directives)) return match; + const withoutForwardedFor = directives.replace( + /^[\t ]*proxy_set_header X-Forwarded-For[^\n]*\n/gm, + '' + ); + const updated = withoutForwardedFor.replace(proxyLine, (line) => { + const indent = line.match(/^[\t ]*/)?.[0] ?? ''; + return `${line}${indent}proxy_set_header X-Forwarded-For $remote_addr;\n`; + }); + return `${opening}${updated}${closing}`; + } + ); + return this.createPatchWithDiff(overridePath ?? this.filePath, fileContent, newContent); } async shouldApply(): Promise { - const { shouldApply, reason } = await super.shouldApply(); + const { shouldApply, reason } = await super.shouldApply({ checkOsVersion: false }); return { shouldApply, reason, From d7f2783a69c21fa3ccab91a6dc78f73d5823381a Mon Sep 17 00:00:00 2001 From: Eli Bosley Date: Tue, 27 Oct 2026 21:43:50 -0400 Subject: [PATCH 03/10] fix(graphql): enforce introspection policy on websocket operations --- api/src/unraid-api/graph/graph.module.ts | 4 +- .../unraid-api/graph/introspection-plugin.ts | 2 +- .../graph/request-protection.spec.ts | 81 ++++++++++++++++++- .../unraid-api/graph/request-protection.ts | 21 ++++- 4 files changed, 101 insertions(+), 7 deletions(-) diff --git a/api/src/unraid-api/graph/graph.module.ts b/api/src/unraid-api/graph/graph.module.ts index 902505a3a0..8a947b942f 100644 --- a/api/src/unraid-api/graph/graph.module.ts +++ b/api/src/unraid-api/graph/graph.module.ts @@ -19,7 +19,7 @@ import '@app/unraid-api/graph/auth/auth-action.enum.js'; import { createDynamicIntrospectionPlugin } from '@app/unraid-api/graph/introspection-plugin.js'; import { - graphqlWsOptions, + createGraphqlWsOptions, maxGraphqlTokens, requestProtection, } from '@app/unraid-api/graph/request-protection.js'; @@ -61,7 +61,7 @@ import { PluginModule } from '@app/unraid-api/plugin/plugin.module.js'; createDynamicIntrospectionPlugin(isSandboxEnabled), createSandboxPlugin(), ] as any[], - subscriptions: { 'graphql-ws': graphqlWsOptions }, + subscriptions: { 'graphql-ws': createGraphqlWsOptions(isSandboxEnabled) }, buildSchemaOptions: { dateScalarMode: 'isoDate', // Only add directive when not in test environment to avoid GraphQL version conflicts diff --git a/api/src/unraid-api/graph/introspection-plugin.ts b/api/src/unraid-api/graph/introspection-plugin.ts index d3c62bfb0a..1a9372cc26 100644 --- a/api/src/unraid-api/graph/introspection-plugin.ts +++ b/api/src/unraid-api/graph/introspection-plugin.ts @@ -64,7 +64,7 @@ const hasBlockedIntrospectionField = ( return blocked; }); -const isBlockedIntrospectionOperation = ( +export const isBlockedIntrospectionOperation = ( operation: OperationDefinitionNode, document: DocumentNode ): boolean => { diff --git a/api/src/unraid-api/graph/request-protection.spec.ts b/api/src/unraid-api/graph/request-protection.spec.ts index a034f6b4a0..d8520b60fa 100644 --- a/api/src/unraid-api/graph/request-protection.spec.ts +++ b/api/src/unraid-api/graph/request-protection.spec.ts @@ -1,7 +1,13 @@ +import { createServer } from 'node:http'; +import { createRequire } from 'node:module'; + import { buildSchema, parse, validate } from 'graphql'; +import { createClient } from 'graphql-ws'; +import { useServer } from 'graphql-ws/use/ws'; import { describe, expect, it } from 'vitest'; +import WebSocket, { WebSocketServer } from 'ws'; -import { requestProtection } from '@app/unraid-api/graph/request-protection.js'; +import { createGraphqlWsOptions, requestProtection } from '@app/unraid-api/graph/request-protection.js'; const schema = buildSchema('type Query { value: String, child: Query }'); @@ -60,3 +66,76 @@ describe('requestProtection', () => { expect(validateRequest('query First { value } query Second { value }')).toHaveLength(0); }); }); + +describe('WebSocket introspection policy', () => { + it('checks the selected operation before execution and reads sandbox changes on the same connection', async () => { + const graphql: typeof import('graphql') = createRequire(import.meta.url)('graphql'); + const socketSchema = graphql.buildSchema('type Query { value: String }'); + let resolverCalls = 0; + let sandboxEnabled = false; + socketSchema.getQueryType()!.getFields().value.resolve = () => { + resolverCalls++; + return 'ok'; + }; + const server = createServer(); + const sockets = new WebSocketServer({ server, path: '/graphql' }); + const disposable = useServer( + { + schema: socketSchema, + ...createGraphqlWsOptions(() => sandboxEnabled), + }, + sockets + ); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('Expected TCP listener'); + const client = createClient({ + url: `ws://127.0.0.1:${address.port}/graphql`, + webSocketImpl: WebSocket, + lazy: false, + retryAttempts: 0, + }); + const run = async (query: string, operationName?: string) => { + const iterator = client.iterate({ query, operationName }); + try { + return (await iterator.next()).value; + } finally { + await iterator.return?.(); + } + }; + try { + for (const query of [ + '{ __schema { queryType { name } } value }', + '{ metadata: __type(name: "Query") { name } value }', + 'query { ...Metadata value } fragment Metadata on Query { __schema { queryType { name } } }', + '{ ... on Query { __schema @include(if: true) { queryType { name } } } value }', + ]) { + await expect(run(query)).rejects.toEqual([ + expect.objectContaining({ extensions: { code: 'INTROSPECTION_DISABLED' } }), + ]); + } + expect(resolverCalls).toBe(0); + const operations = + 'query Normal { value __typename } query Metadata { __schema { queryType { name } } }'; + expect((await run(operations, 'Normal'))?.data).toEqual({ + value: 'ok', + __typename: 'Query', + }); + await expect(run(operations, 'Metadata')).rejects.toBeDefined(); + sandboxEnabled = true; + expect((await run(operations, 'Metadata'))?.data).toEqual({ + __schema: { queryType: { name: 'Query' } }, + }); + sandboxEnabled = false; + await expect(run(operations, 'Metadata')).rejects.toBeDefined(); + const aliases = Array.from({ length: 101 }, (_, index) => `a${index}: value`).join(' '); + await expect(run(`{ ${aliases} }`)).rejects.toBeDefined(); + } finally { + await client.dispose(); + await disposable.dispose(); + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())) + ); + } + }); +}); diff --git a/api/src/unraid-api/graph/request-protection.ts b/api/src/unraid-api/graph/request-protection.ts index e1194028fc..1f3239b403 100644 --- a/api/src/unraid-api/graph/request-protection.ts +++ b/api/src/unraid-api/graph/request-protection.ts @@ -4,6 +4,8 @@ import type { DocumentNode, GraphQLSchema } from 'graphql'; import type { SubscribePayload } from 'graphql-ws'; import { ApolloArmor } from '@escape.tech/graphql-armor'; +import { isBlockedIntrospectionOperation } from '@app/unraid-api/graph/introspection-plugin.js'; + export const maxGraphqlTokens = 5_000; const graphqlForWs: typeof import('graphql') = createRequire(import.meta.url)('graphql'); @@ -26,11 +28,24 @@ export const requestProtection = new ApolloArmor({ const websocketValidationRules = [...graphqlForWs.specifiedRules, ...requestProtection.validationRules]; -export const graphqlWsOptions = { +export const createGraphqlWsOptions = (isSandboxEnabled: () => boolean) => ({ path: '/graphql', onSubscribe: (_context: unknown, _id: string, payload: SubscribePayload) => { try { - graphqlForWs.parse(payload.query, { maxTokens: maxGraphqlTokens }); + const document = graphqlForWs.parse(payload.query, { maxTokens: maxGraphqlTokens }); + const operation = graphqlForWs.getOperationAST(document, payload.operationName); + if ( + !isSandboxEnabled() && + operation && + isBlockedIntrospectionOperation(operation, document) + ) { + return [ + new graphqlForWs.GraphQLError( + 'GraphQL introspection is not allowed, but the current request is for introspection.', + { extensions: { code: 'INTROSPECTION_DISABLED' } } + ), + ]; + } } catch (error) { if (error instanceof graphqlForWs.GraphQLError) return [error]; throw error; @@ -40,4 +55,4 @@ export const graphqlWsOptions = { // Nest passes this option to graphql-ws, although its subscription config omits the type. validate: (schema: GraphQLSchema, document: DocumentNode) => graphqlForWs.validate(schema, document, websocketValidationRules), -}; +}); From 6d51064ae9d2adc2ee2c9892f0d4752c47236f07 Mon Sep 17 00:00:00 2001 From: Eli Bosley Date: Tue, 27 Oct 2026 21:43:58 -0400 Subject: [PATCH 04/10] chore(ai-review): record transport fix review receipt --- ...lient-identity-ws-policy-73041c5cc2c5.json | 25 +++---------------- 1 file changed, 4 insertions(+), 21 deletions(-) diff --git a/.limetech/ai-review-markers/fix-api-client-identity-ws-policy-73041c5cc2c5.json b/.limetech/ai-review-markers/fix-api-client-identity-ws-policy-73041c5cc2c5.json index 24cff5f635..6d8d333f32 100644 --- a/.limetech/ai-review-markers/fix-api-client-identity-ws-policy-73041c5cc2c5.json +++ b/.limetech/ai-review-markers/fix-api-client-identity-ws-policy-73041c5cc2c5.json @@ -1,25 +1,8 @@ { "disposition": "PATCH", - "expected_structural_delta": "Five existing production TypeScript modules plus nginx patch asset; zero new runtime owners, dependencies or state stores. About 80-160 added production lines, 10-35 removed; 1-2 new test files and 2-4 extended files with 180-320 test lines.", - "minimum_design": "Extend the existing nginx script modification and throttler guard to preserve trusted client identity; reuse the selected-operation introspection check in graphql-ws before execution.", - "outcome": "Independent OIDC client limits through the supported nginx socket path and consistent disabled-sandbox introspection policy on HTTP and WebSocket.", - "reuse_decisions": [ - { - "decision": "extend", - "name": "RcNginxModification", - "rationale": "Existing owner for rc.nginx patching and reload lifecycle; update static and generated patch on current OS versions." - }, - { - "decision": "extend", - "name": "FastifyThrottlerGuard", - "rationale": "Select raw TCP peer or one validated nginx-provided Unix socket client address." - }, - { - "decision": "reuse", - "name": "Introspection AST policy and graphqlWsOptions", - "rationale": "Apply one selected-operation predicate with dynamic sandbox policy before both transports execute." - } - ], + "forecast_commit": "ee919505185a59be4ac687f6452d0db18520be50", + "reviewed_sha": "d7f2783a69c21fa3ccab91a6dc78f73d5823381a", "schema": "limetech.ai-review-marker.v2", - "stage": "forecast" + "stage": "final", + "unresolved_proportionality_findings": [] } From 3408c9c1853b10c25e4e6e11b6302c2f0f2f1197 Mon Sep 17 00:00:00 2001 From: SimonFair <39065407+SimonFair@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:21:30 +0000 Subject: [PATCH 05/10] fix(api): normalize client IP headers across nginx patch paths --- .../__test__/rc-nginx.modification.spec.ts | 84 +++++++++++++------ .../modifications/rc-nginx.modification.ts | 7 +- 2 files changed, 63 insertions(+), 28 deletions(-) diff --git a/api/src/unraid-api/unraid-file-modifier/modifications/__test__/rc-nginx.modification.spec.ts b/api/src/unraid-api/unraid-file-modifier/modifications/__test__/rc-nginx.modification.spec.ts index 59346caec6..94985d25f0 100644 --- a/api/src/unraid-api/unraid-file-modifier/modifications/__test__/rc-nginx.modification.spec.ts +++ b/api/src/unraid-api/unraid-file-modifier/modifications/__test__/rc-nginx.modification.spec.ts @@ -19,42 +19,45 @@ describe('rc.nginx client identity lifecycle', () => { await rm(directory, { recursive: true, force: true }); }); - it('patches integrated API versions, survives reapply, and rolls back cleanly', async () => { - const original = `CONNECT_CONFIG="existing" + it.each(['X-Forwarded-For', 'x-forwarded-for', 'x-FoRwArDeD-fOr'])( + 'normalizes %s and survives reapply and rollback', + async (headerName) => { + const original = `CONNECT_CONFIG="existing" build_locations(){ cat <<- 'EOF' \tlocation /graphql { -\t proxy_set_header X-Forwarded-For \\$http_x_forwarded_for; +\t proxy_set_header ${headerName} \\$http_x_forwarded_for; \t proxy_pass http://unix:/var/run/unraid-api.sock:/graphql; \t proxy_set_header Host \\$host; \t} \tEOF } `; - const file = join(directory, 'rc.nginx'); - const previous = original.replace('CONNECT_CONFIG="existing"', 'CONNECT_CONFIG="previous"'); - await writeFile(file, previous); - await writeFile(`${file}.patch`, createPatch(file, original, previous)); - const modification = new RcNginxModification(new Logger()); - modification.filePath = file; - expect((await modification.shouldApply()).shouldApply).toBe(true); - await modification.apply(); - const patched = await readFile(file, 'utf8'); - expect(patched).toContain('proxy_set_header X-Forwarded-For $remote_addr;'); - expect(patched).not.toContain('$http_x_forwarded_for'); - expect(patched.match(/proxy_set_header X-Forwarded-For/g)).toHaveLength(1); - const { stdout } = await promisify(execFile)('/bin/bash', [ - '-c', - 'source "$1"; build_locations', - 'nginx-test', - file, - ]); - expect(stdout).toContain('proxy_set_header X-Forwarded-For $remote_addr;'); - await modification.apply(); - expect(await readFile(file, 'utf8')).toBe(patched); - await modification.rollback(); - expect(await readFile(file, 'utf8')).toBe(original); - }); + const file = join(directory, 'rc.nginx'); + const previous = original.replace('CONNECT_CONFIG="existing"', 'CONNECT_CONFIG="previous"'); + await writeFile(file, previous); + await writeFile(`${file}.patch`, createPatch(file, original, previous)); + const modification = new RcNginxModification(new Logger()); + modification.filePath = file; + expect((await modification.shouldApply()).shouldApply).toBe(true); + await modification.apply(); + const patched = await readFile(file, 'utf8'); + expect(patched).toContain('proxy_set_header X-Forwarded-For $remote_addr;'); + expect(patched).not.toContain('$http_x_forwarded_for'); + expect(patched.match(/proxy_set_header X-Forwarded-For/g)).toHaveLength(1); + const { stdout } = await promisify(execFile)('/bin/bash', [ + '-c', + 'source "$1"; build_locations', + 'nginx-test', + file, + ]); + expect(stdout).toContain('proxy_set_header X-Forwarded-For $remote_addr;'); + await modification.apply(); + expect(await readFile(file, 'utf8')).toBe(patched); + await modification.rollback(); + expect(await readFile(file, 'utf8')).toBe(original); + } + ); it('emits a valid client address variable from the bundled nginx generator', async () => { const original = await readFile( new URL('./__fixtures__/downloaded/rc.nginx', import.meta.url), @@ -92,4 +95,31 @@ build_locations(){ await modification.rollback(); expect(await readFile(file, 'utf8')).toBe(original); }); + + it('normalizes existing headers outside the bundled patch context', async () => { + const fixture = await readFile( + new URL('./__fixtures__/downloaded/rc.nginx', import.meta.url), + 'utf8' + ); + const original = fixture.replace( + 'proxy_intercept_errors on;', + 'proxy_intercept_errors on;\n\t proxy_set_header x-forwarded-for $http_x_forwarded_for;' + ); + expect(original).not.toBe(fixture); + const file = join(directory, 'rc.nginx'); + await writeFile(file, original); + const modification = new RcNginxModification(new Logger()); + modification.filePath = file; + + await modification.apply(); + + const patched = await readFile(file, 'utf8'); + expect(patched.match(/proxy_set_header x-forwarded-for\s/gi)).toHaveLength(1); + expect(patched).toContain('proxy_set_header X-Forwarded-For $remote_addr;'); + expect(patched).not.toContain('$http_x_forwarded_for'); + await modification.apply(); + expect(await readFile(file, 'utf8')).toBe(patched); + await modification.rollback(); + expect(await readFile(file, 'utf8')).toBe(original); + }); }); diff --git a/api/src/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.ts b/api/src/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.ts index f05d8a6c19..35cd9678d4 100644 --- a/api/src/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.ts +++ b/api/src/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.ts @@ -15,6 +15,11 @@ export default class RcNginxModification extends FileModification { public filePath: string = '/etc/rc.d/rc.nginx' as const; id: string = 'rc-nginx'; + protected async getPregeneratedPatch(): Promise { + // Existing forwarding headers can occur outside the bundled patch's context. + return null; + } + protected async generatePatch(overridePath?: string): Promise { if (!(await fileExists(this.filePath))) { throw new Error(`File ${this.filePath} not found.`); @@ -84,7 +89,7 @@ check_remote_access(){ /^[\t ]*proxy_pass http:\/\/unix:\/var\/run\/unraid-api\.sock:\/graphql;[^\n]*\n/m; if (!proxyLine.test(directives)) return match; const withoutForwardedFor = directives.replace( - /^[\t ]*proxy_set_header X-Forwarded-For[^\n]*\n/gm, + /^[\t ]*proxy_set_header[\t ]+X-Forwarded-For[\t ]+[^\n]*\n/gim, '' ); const updated = withoutForwardedFor.replace(proxyLine, (line) => { From d3b5a2016593eebbb9ffb30a43b68f5e4fd71b03 Mon Sep 17 00:00:00 2001 From: SimonFair <39065407+SimonFair@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:09:44 +0000 Subject: [PATCH 06/10] fix(auth): reject repeated OIDC query parameters before coercion Preserve array query values through the production ValidationPipe so existing OIDC validation rejects them before allocating state or dispatching callbacks. Add real HTTP regressions for all four query bindings. Work Intent: https://linear.app/lime-technology/issue/OS-982 --- .../rest.controller.oidc.integration.test.ts | 79 ++++++++++++++++++- api/src/unraid-api/rest/rest.controller.ts | 8 +- 2 files changed, 81 insertions(+), 6 deletions(-) diff --git a/api/src/unraid-api/rest/rest.controller.oidc.integration.test.ts b/api/src/unraid-api/rest/rest.controller.oidc.integration.test.ts index b602736756..73b4fdfb1e 100644 --- a/api/src/unraid-api/rest/rest.controller.oidc.integration.test.ts +++ b/api/src/unraid-api/rest/rest.controller.oidc.integration.test.ts @@ -1,8 +1,11 @@ +import { ValidationPipe } from '@nestjs/common'; +import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'; import { Test, TestingModule } from '@nestjs/testing'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { FastifyReply, FastifyRequest } from '@app/unraid-api/types/fastify.js'; +import { FastifyThrottlerGuard } from '@app/unraid-api/auth/fastify-throttler.guard.js'; import { OidcAuthorizationService } from '@app/unraid-api/graph/resolvers/sso/auth/oidc-authorization.service.js'; import { OidcClaimsService } from '@app/unraid-api/graph/resolvers/sso/auth/oidc-claims.service.js'; import { OidcTokenExchangeService } from '@app/unraid-api/graph/resolvers/sso/auth/oidc-token-exchange.service.js'; @@ -17,11 +20,13 @@ import { } from '@app/unraid-api/graph/resolvers/sso/models/oidc-provider.model.js'; import { OidcSessionService } from '@app/unraid-api/graph/resolvers/sso/session/oidc-session.service.js'; import { OidcStateService } from '@app/unraid-api/graph/resolvers/sso/session/oidc-state.service.js'; +import { OidcRequestHandler } from '@app/unraid-api/graph/resolvers/sso/utils/oidc-request-handler.util.js'; import { RestController } from '@app/unraid-api/rest/rest.controller.js'; import { RestService } from '@app/unraid-api/rest/rest.service.js'; describe('RestController OIDC authorize integration', () => { let controller: RestController; + let app: NestFastifyApplication; let oidcConfig: { getConfig: ReturnType; getProvider: ReturnType; @@ -141,9 +146,23 @@ describe('RestController OIDC authorize integration', () => { }, }, ], - }).compile(); + }) + .overrideGuard(FastifyThrottlerGuard) + .useValue({ canActivate: () => true }) + .compile(); controller = module.get(RestController); + app = module.createNestApplication(new FastifyAdapter()); + app.useGlobalPipes( + new ValidationPipe({ + transform: true, + whitelist: true, + forbidNonWhitelisted: true, + transformOptions: { enableImplicitConversion: true }, + }) + ); + await app.init(); + await app.getHttpAdapter().getInstance().ready(); statusSpy = vi.fn(); headerSpy = vi.fn(); @@ -167,6 +186,62 @@ describe('RestController OIDC authorize integration', () => { mockReply = reply; }); + afterEach(async () => { + await app?.close(); + }); + + it('preserves ordinary authorization parameters through the production HTTP validation pipeline', async () => { + const query = new URLSearchParams({ + state: 'client-state-123', + redirect_uri: 'http://localhost/graphql/api/auth/oidc/callback', + }); + const response = await app.inject({ + method: 'GET', + url: `/graphql/api/auth/oidc/authorize/${provider.id}?${query}`, + }); + expect(response.statusCode).toBe(302); + expect(oidcStateService.generateSecureState).toHaveBeenCalledWith( + provider.id, + 'client-state-123', + 'http://localhost/graphql/api/auth/oidc/callback' + ); + }); + + it.each([ + ['repeated state', 'state=one&state=two&redirect_uri=http://localhost'], + [ + 'repeated redirect URI', + 'state=one&redirect_uri=http://localhost/graphql/api/auth/oidc/callback&redirect_uri=http://localhost/graphql/api/auth/oidc/callback', + ], + ['missing state', 'redirect_uri=http://localhost'], + ['missing redirect URI', 'state=one'], + ['overlong state', `state=${'x'.repeat(257)}&redirect_uri=http://localhost`], + ['overlong redirect URI', `state=one&redirect_uri=http://localhost/${'x'.repeat(2048)}`], + ])('rejects %s before allocating authorization state', async (_name, query) => { + const response = await app.inject({ + method: 'GET', + url: `/graphql/api/auth/oidc/authorize/${provider.id}?${query}`, + }); + expect(response.statusCode).toBe(400); + expect(oidcStateService.generateSecureState).not.toHaveBeenCalled(); + }); + + it.each([ + ['repeated code', 'code=one&code=two&state=state'], + ['repeated state', 'code=code&state=one&state=two'], + ['missing code', 'state=state'], + ['missing state', 'code=code'], + ])('rejects callback %s before routing the callback', async (_name, query) => { + const callback = vi.spyOn(OidcRequestHandler, 'handleCallback'); + const response = await app.inject({ + method: 'GET', + url: `/graphql/api/auth/oidc/callback?${query}`, + }); + expect(response.statusCode).toBe(302); + expect(response.headers.location).toBe('/login#error=Authentication%20failed'); + expect(callback).not.toHaveBeenCalled(); + }); + it('authorizes successfully through both redirect validation layers for proxied domains', async () => { const mockRequest = createMockRequest( undefined, diff --git a/api/src/unraid-api/rest/rest.controller.ts b/api/src/unraid-api/rest/rest.controller.ts index a22e6b2d7a..2b91abba19 100644 --- a/api/src/unraid-api/rest/rest.controller.ts +++ b/api/src/unraid-api/rest/rest.controller.ts @@ -74,8 +74,8 @@ export class RestController { @Throttle({ default: { limit: 10, ttl: 60_000 } }) async oidcAuthorize( @Param('providerId') providerId: string, - @Query('state') state: string, - @Query('redirect_uri') redirectUri: string, + @Query('state') state: string | string[] | undefined, + @Query('redirect_uri') redirectUri: string | string[] | undefined, @Req() req: FastifyRequest, @Res() res: FastifyReply ) { @@ -153,8 +153,8 @@ export class RestController { @UseGuards(FastifyThrottlerGuard) @Throttle({ default: { limit: 10, ttl: 60_000 } }) async oidcCallback( - @Query('code') code: string, - @Query('state') state: string, + @Query('code') code: string | string[] | undefined, + @Query('state') state: string | string[] | undefined, @Req() req: FastifyRequest, @Res() res: FastifyReply ) { From 00d17867d4d06b553e63e01753720dc28ee54b06 Mon Sep 17 00:00:00 2001 From: SimonFair <39065407+SimonFair@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:14:08 +0000 Subject: [PATCH 07/10] Isolate file modification test fixtures --- .../__test__/generic-modification.spec.ts | 26 ++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/api/src/unraid-api/unraid-file-modifier/modifications/__test__/generic-modification.spec.ts b/api/src/unraid-api/unraid-file-modifier/modifications/__test__/generic-modification.spec.ts index 3ec9404800..3f55a8a8fa 100644 --- a/api/src/unraid-api/unraid-file-modifier/modifications/__test__/generic-modification.spec.ts +++ b/api/src/unraid-api/unraid-file-modifier/modifications/__test__/generic-modification.spec.ts @@ -1,9 +1,10 @@ import { Logger } from '@nestjs/common'; -import { readFile, writeFile } from 'fs/promises'; -import { basename, dirname, resolve } from 'path'; -import { fileURLToPath } from 'url'; +import { copyFile, mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { basename, dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; -import { describe, expect, test, vi } from 'vitest'; +import { describe, expect, onTestFinished, test, vi } from 'vitest'; import { FileModification } from '@app/unraid-api/unraid-file-modifier/file-modification.js'; import AuthRequestModification from '@app/unraid-api/unraid-file-modifier/modifications/auth-request.modification.js'; @@ -22,6 +23,19 @@ interface ModificationTestCase { const getPathToFixture = (fileName: string) => resolve(dirname(fileURLToPath(import.meta.url)), `__fixtures__/downloaded/${fileName}`); +async function copyFixture(fileName: string): Promise { + const directory = await mkdtemp(join(tmpdir(), 'api-file-modification-')); + onTestFinished(() => rm(directory, { recursive: true, force: true })); + const path = join(directory, fileName); + try { + await copyFile(getPathToFixture(fileName), path); + } catch (error) { + // Add-file modifiers start with no fixture. + if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error; + } + return path; +} + /** Modifications that patch the content of an existing file in one or more places. */ const patchTestCases: ModificationTestCase[] = [ { @@ -66,7 +80,7 @@ const simpleTestCases: ModificationTestCase[] = []; async function testModification(testCase: ModificationTestCase) { const fileName = basename(testCase.fileUrl); - const filePath = getPathToFixture(fileName); + const filePath = await copyFixture(fileName); const originalContent = await readFile(filePath, 'utf-8').catch(() => ''); const logger = new Logger(); const patcher = await new testCase.ModificationClass(logger); @@ -108,7 +122,7 @@ async function testInvalidModification(testCase: ModificationTestCase) { // @ts-expect-error - Testing invalid pregenerated patches patcher.getPregeneratedPatch = vi.fn().mockResolvedValue('I AM NOT A VALID PATCH'); - const filePath = getPathToFixture(testCase.fileName); + const filePath = await copyFixture(testCase.fileName); // @ts-expect-error - Testing invalid pregenerated patches patcher.filePath = filePath; From d84e401bf83b85b1882e5b7c4b199bde30fd00ee Mon Sep 17 00:00:00 2001 From: SimonFair <39065407+SimonFair@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:35:26 +0000 Subject: [PATCH 08/10] Rely on the OIDC redirect parameter validator --- api/src/unraid-api/rest/rest.controller.ts | 8 -------- 1 file changed, 8 deletions(-) diff --git a/api/src/unraid-api/rest/rest.controller.ts b/api/src/unraid-api/rest/rest.controller.ts index 2b91abba19..0d22cbb61f 100644 --- a/api/src/unraid-api/rest/rest.controller.ts +++ b/api/src/unraid-api/rest/rest.controller.ts @@ -80,16 +80,8 @@ export class RestController { @Res() res: FastifyReply ) { try { - // Validate required parameters const params = OidcRequestHandler.validateAuthorizeParams(providerId, state, redirectUri); - // IMPORTANT: Use the redirect_uri from query params directly - // Do NOT parse headers or try to build/validate against headers - // The frontend provides the complete redirect_uri - if (!params.redirectUri) { - return res.status(400).send('redirect_uri parameter is required'); - } - // Security validation: validate redirect_uri with support for allowed origins const requestInfo = OidcRequestHandler.extractRequestInfo(req); From 145c91387467a0315eb52716091e80875bb2b4cf Mon Sep 17 00:00:00 2001 From: SimonFair <39065407+SimonFair@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:04:59 +0000 Subject: [PATCH 09/10] fix(ci): report advisory audit findings without failing the check --- .github/workflows/main.yml | 4 ++-- scripts/pnpm-audit.mjs | 19 +++++++++++++++---- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index be32bac749..f5b94740f8 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -160,7 +160,7 @@ jobs: uses: codecov/codecov-action@v6 with: token: ${{ secrets.CODECOV_TOKEN }} - files: ./coverage/coverage-final.json,../web/coverage/coverage-final.json,../unraid-ui/coverage/coverage-final.json,../packages/unraid-api-plugin-connect/coverage/coverage-final.json,../packages/unraid-shared/coverage/coverage-final.json + files: api/coverage/coverage-final.json,web/coverage/coverage-final.json,unraid-ui/coverage/coverage-final.json,packages/unraid-api-plugin-connect/coverage/coverage-final.json,packages/unraid-shared/coverage/coverage-final.json fail_ci_if_error: false audit: @@ -186,7 +186,7 @@ jobs: node-version-file: ".nvmrc" - name: Audit production dependencies - run: pnpm run audit --prod + run: pnpm run audit --prod --advisory build-artifacts: name: Build All Artifacts diff --git a/scripts/pnpm-audit.mjs b/scripts/pnpm-audit.mjs index 5712549e7d..72bbe64ea1 100644 --- a/scripts/pnpm-audit.mjs +++ b/scripts/pnpm-audit.mjs @@ -5,7 +5,8 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs'; import { join, relative } from 'node:path'; const cwd = process.cwd(); -const args = process.argv.slice(2).filter((arg) => arg !== '--json'); +const advisoryOnly = process.argv.includes('--advisory'); +const args = process.argv.slice(2).filter((arg) => arg !== '--json' && arg !== '--advisory'); const audit = spawnSync('pnpm', ['audit', '--json', ...args], { cwd, encoding: 'utf8', @@ -25,7 +26,7 @@ try { if (audit.stdout) { process.stdout.write(audit.stdout); } - process.exitCode = audit.status ?? 1; + process.exitCode = audit.status || 1; } if (report && report.error) { @@ -34,7 +35,7 @@ if (report && report.error) { report = undefined; } -if (report && !isRecognizedAuditReport(report)) { +if (report !== undefined && !isRecognizedAuditReport(report)) { process.stderr.write('pnpm audit returned an unrecognized report shape; failing closed.\n'); process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); process.exitCode = audit.status || 1; @@ -54,7 +55,17 @@ if (report) { updateVulnerabilityMetadata(report); process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); - process.exitCode = Object.keys(report.advisories ?? {}).length === 0 ? 0 : (audit.status ?? 1); + const advisoryCount = Object.keys(report.advisories).length; + if (audit.error || audit.signal !== null || (audit.status !== 0 && audit.status !== 1)) { + process.exitCode = audit.status || 1; + } else if (advisoryOnly && audit.status === 1 && advisoryCount > 0) { + process.stderr.write( + `::warning title=Dependency audit::Found ${advisoryCount} advisories. See the audit report in this job.\n`, + ); + process.exitCode = 0; + } else { + process.exitCode = advisoryCount === 0 ? 0 : (audit.status ?? 1); + } } function isRecognizedAuditReport(report) { From 520a8051243c7999aedd19617c33f0526322fe9e Mon Sep 17 00:00:00 2001 From: SimonFair <39065407+SimonFair@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:52:44 +0000 Subject: [PATCH 10/10] fix(api): retain OIDC access when WebGUI omits the client IP --- .../auth/fastify-throttler.guard.spec.ts | 10 +- .../auth/fastify-throttler.guard.ts | 7 +- .../__test__/rc-nginx.modification.spec.ts | 125 ------------------ .../snapshots/rc.nginx.modified.snapshot | 1 - .../modifications/patches/rc-nginx.patch | 16 +-- .../modifications/rc-nginx.modification.ts | 101 ++++++-------- 6 files changed, 56 insertions(+), 204 deletions(-) delete mode 100644 api/src/unraid-api/unraid-file-modifier/modifications/__test__/rc-nginx.modification.spec.ts diff --git a/api/src/unraid-api/auth/fastify-throttler.guard.spec.ts b/api/src/unraid-api/auth/fastify-throttler.guard.spec.ts index 882bd9ea50..819d4e92e9 100644 --- a/api/src/unraid-api/auth/fastify-throttler.guard.spec.ts +++ b/api/src/unraid-api/auth/fastify-throttler.guard.spec.ts @@ -81,7 +81,7 @@ describe('FastifyThrottlerGuard client identity', () => { ); }); - it('keeps Unix socket clients independent and rejects missing or ambiguous identity', async () => { + it('keeps known Unix socket clients independent and shares one limit for unknown clients', async () => { const directory = await mkdtemp(join(tmpdir(), 'api-ip-')); cleanups.push(() => rm(directory, { recursive: true, force: true })); const server = await createServer(); @@ -106,8 +106,10 @@ describe('FastifyThrottlerGuard client identity', () => { expect(await send('192.0.2.1')).toBe(204); expect(await send('192.0.2.1')).toBe(429); expect(await send('192.0.2.2')).toBe(204); - expect(await send()).toBe(400); - expect(await send('192.0.2.1, 192.0.2.2')).toBe(400); - expect(await send('invalid')).toBe(400); + expect(await send()).toBe(204); + expect(await send('192.0.2.1, 192.0.2.2')).toBe(204); + expect(await send('invalid')).toBe(429); + expect(await send()).toBe(429); + expect(await send('192.0.2.3')).toBe(204); }); }); diff --git a/api/src/unraid-api/auth/fastify-throttler.guard.ts b/api/src/unraid-api/auth/fastify-throttler.guard.ts index f951be04a5..3d142e7901 100644 --- a/api/src/unraid-api/auth/fastify-throttler.guard.ts +++ b/api/src/unraid-api/auth/fastify-throttler.guard.ts @@ -1,4 +1,4 @@ -import { BadRequestException, ExecutionContext, Inject, Injectable, Optional } from '@nestjs/common'; +import { ExecutionContext, Inject, Injectable, Optional } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { GqlExecutionContext } from '@nestjs/graphql'; import { @@ -31,13 +31,14 @@ export class FastifyThrottlerGuard extends ThrottlerGuard { const peerAddress = request.raw.socket.remoteAddress; if (peerAddress) return peerAddress; - // Unix sockets have no peer IP. nginx overwrites this header with its TCP client address. + // WebGUI forwards its client IP over the Unix socket when available. const forwardedAddress = request.headers['x-forwarded-for']; if (typeof forwardedAddress === 'string' && isIP(forwardedAddress)) { return forwardedAddress; } - throw new BadRequestException('Client IP address is unavailable'); + // Older WebGUI releases share one rate limit when the client IP is unavailable. + return 'unknown-client'; } getRequestResponse(context: ExecutionContext) { diff --git a/api/src/unraid-api/unraid-file-modifier/modifications/__test__/rc-nginx.modification.spec.ts b/api/src/unraid-api/unraid-file-modifier/modifications/__test__/rc-nginx.modification.spec.ts deleted file mode 100644 index 94985d25f0..0000000000 --- a/api/src/unraid-api/unraid-file-modifier/modifications/__test__/rc-nginx.modification.spec.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { Logger } from '@nestjs/common'; -import { execFile } from 'node:child_process'; -import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { promisify } from 'node:util'; - -import { createPatch } from 'diff'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; - -import RcNginxModification from '@app/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.js'; - -describe('rc.nginx client identity lifecycle', () => { - let directory: string; - beforeEach(async () => { - directory = await mkdtemp(join(tmpdir(), 'api-nginx-')); - }); - afterEach(async () => { - await rm(directory, { recursive: true, force: true }); - }); - - it.each(['X-Forwarded-For', 'x-forwarded-for', 'x-FoRwArDeD-fOr'])( - 'normalizes %s and survives reapply and rollback', - async (headerName) => { - const original = `CONNECT_CONFIG="existing" -build_locations(){ - cat <<- 'EOF' -\tlocation /graphql { -\t proxy_set_header ${headerName} \\$http_x_forwarded_for; -\t proxy_pass http://unix:/var/run/unraid-api.sock:/graphql; -\t proxy_set_header Host \\$host; -\t} -\tEOF -} -`; - const file = join(directory, 'rc.nginx'); - const previous = original.replace('CONNECT_CONFIG="existing"', 'CONNECT_CONFIG="previous"'); - await writeFile(file, previous); - await writeFile(`${file}.patch`, createPatch(file, original, previous)); - const modification = new RcNginxModification(new Logger()); - modification.filePath = file; - expect((await modification.shouldApply()).shouldApply).toBe(true); - await modification.apply(); - const patched = await readFile(file, 'utf8'); - expect(patched).toContain('proxy_set_header X-Forwarded-For $remote_addr;'); - expect(patched).not.toContain('$http_x_forwarded_for'); - expect(patched.match(/proxy_set_header X-Forwarded-For/g)).toHaveLength(1); - const { stdout } = await promisify(execFile)('/bin/bash', [ - '-c', - 'source "$1"; build_locations', - 'nginx-test', - file, - ]); - expect(stdout).toContain('proxy_set_header X-Forwarded-For $remote_addr;'); - await modification.apply(); - expect(await readFile(file, 'utf8')).toBe(patched); - await modification.rollback(); - expect(await readFile(file, 'utf8')).toBe(original); - } - ); - it('emits a valid client address variable from the bundled nginx generator', async () => { - const original = await readFile( - new URL('./__fixtures__/downloaded/rc.nginx', import.meta.url), - 'utf8' - ); - const file = join(directory, 'rc.nginx'); - await writeFile(file, original); - const modification = new RcNginxModification(new Logger()); - modification.filePath = file; - await modification.apply(); - const patched = await readFile(file, 'utf8'); - const start = patched.indexOf('build_locations(){'); - const end = patched.indexOf('\n}\n', start); - expect(start).toBeGreaterThan(-1); - expect(end).toBeGreaterThan(start); - const generator = join(directory, 'locations.sh'); - const locations = join(directory, 'locations.conf'); - await writeFile(generator, patched.slice(start, end + 3)); - await promisify(execFile)('/bin/bash', [ - '-c', - 'source "$1"; LOCATIONS="$2"; build_locations', - 'nginx-test', - generator, - locations, - ]); - const generated = await readFile(locations, 'utf8'); - const header = generated - .split('\n') - .filter((line) => line.includes('proxy_set_header X-Forwarded-For')); - expect(header.map((line) => line.trim())).toEqual([ - 'proxy_set_header X-Forwarded-For $remote_addr;', - ]); - await modification.apply(); - expect(await readFile(file, 'utf8')).toBe(patched); - await modification.rollback(); - expect(await readFile(file, 'utf8')).toBe(original); - }); - - it('normalizes existing headers outside the bundled patch context', async () => { - const fixture = await readFile( - new URL('./__fixtures__/downloaded/rc.nginx', import.meta.url), - 'utf8' - ); - const original = fixture.replace( - 'proxy_intercept_errors on;', - 'proxy_intercept_errors on;\n\t proxy_set_header x-forwarded-for $http_x_forwarded_for;' - ); - expect(original).not.toBe(fixture); - const file = join(directory, 'rc.nginx'); - await writeFile(file, original); - const modification = new RcNginxModification(new Logger()); - modification.filePath = file; - - await modification.apply(); - - const patched = await readFile(file, 'utf8'); - expect(patched.match(/proxy_set_header x-forwarded-for\s/gi)).toHaveLength(1); - expect(patched).toContain('proxy_set_header X-Forwarded-For $remote_addr;'); - expect(patched).not.toContain('$http_x_forwarded_for'); - await modification.apply(); - expect(await readFile(file, 'utf8')).toBe(patched); - await modification.rollback(); - expect(await readFile(file, 'utf8')).toBe(original); - }); -}); diff --git a/api/src/unraid-api/unraid-file-modifier/modifications/__test__/snapshots/rc.nginx.modified.snapshot b/api/src/unraid-api/unraid-file-modifier/modifications/__test__/snapshots/rc.nginx.modified.snapshot index 6547894484..7c555fda54 100644 --- a/api/src/unraid-api/unraid-file-modifier/modifications/__test__/snapshots/rc.nginx.modified.snapshot +++ b/api/src/unraid-api/unraid-file-modifier/modifications/__test__/snapshots/rc.nginx.modified.snapshot @@ -421,7 +421,6 @@ build_locations(){ allow all; error_log /dev/null crit; proxy_pass http://unix:/var/run/unraid-api.sock:/graphql; - proxy_set_header X-Forwarded-For $remote_addr; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header Upgrade $http_upgrade; diff --git a/api/src/unraid-api/unraid-file-modifier/modifications/patches/rc-nginx.patch b/api/src/unraid-api/unraid-file-modifier/modifications/patches/rc-nginx.patch index 2fa9b0725e..fbac95e0bc 100644 --- a/api/src/unraid-api/unraid-file-modifier/modifications/patches/rc-nginx.patch +++ b/api/src/unraid-api/unraid-file-modifier/modifications/patches/rc-nginx.patch @@ -44,19 +44,7 @@ Index: /etc/rc.d/rc.nginx T=' ' if check && [[ $1 == lo ]]; then if [[ $IPV4 == yes ]]; then -@@ -401,10 +419,11 @@ - # - location /graphql { - allow all; - error_log /dev/null crit; - proxy_pass http://unix:/var/run/unraid-api.sock:/graphql; -+ proxy_set_header X-Forwarded-For $remote_addr; - proxy_http_version 1.1; - proxy_set_header Host $host; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection $connection_upgrade; - proxy_cache_bypass $http_upgrade; -@@ -566,11 +585,11 @@ +@@ -566,11 +584,11 @@ # extract common name from cert CERTNAME=$(openssl x509 -noout -subject -nameopt multiline -in $CERTPATH | sed -n 's/ *commonName *= //p') # define CSP frame-ancestors for cert @@ -69,7 +57,7 @@ Index: /etc/rc.d/rc.nginx WANIP6=$(curl https://wanip6.unraid.net/ 2>/dev/null) fi if [[ $CERTNAME == *\.myunraid\.net ]]; then -@@ -660,14 +679,14 @@ +@@ -660,14 +678,14 @@ echo "NGINX_WANFQDN=\"$WANFQDN\"" >>$INI echo "NGINX_WANFQDN6=\"$WANFQDN6\"" >>$INI # defined if ts_bundle.pem present: diff --git a/api/src/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.ts b/api/src/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.ts index 35cd9678d4..6b1c717a3a 100644 --- a/api/src/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.ts +++ b/api/src/unraid-api/unraid-file-modifier/modifications/rc-nginx.modification.ts @@ -7,7 +7,7 @@ import { } from '@app/unraid-api/unraid-file-modifier/file-modification.js'; /** - * Preserve client identity for the API proxy and backport legacy Connect configuration. + * Patch rc.nginx on < Unraid 7.2.0 to read the updated connect & api config files * * Backport of https://github.com/unraid/webgui/pull/2269 */ @@ -15,28 +15,34 @@ export default class RcNginxModification extends FileModification { public filePath: string = '/etc/rc.d/rc.nginx' as const; id: string = 'rc-nginx'; - protected async getPregeneratedPatch(): Promise { - // Existing forwarding headers can occur outside the bundled patch's context. - return null; - } - + /** + * Generate a patch for the rc.nginx file + * + * Should result in the same patch as + * https://patch-diff.githubusercontent.com/raw/unraid/webgui/pull/2269.patch + * + * @param overridePath - The path to override the default file path + * @returns The patch for the rc.nginx file + */ protected async generatePatch(overridePath?: string): Promise { if (!(await fileExists(this.filePath))) { throw new Error(`File ${this.filePath} not found.`); } const fileContent = await readFile(this.filePath, 'utf8'); - let newContent = fileContent; - if (fileContent.includes('MYSERVERS=')) { - newContent = newContent.replace( - 'MYSERVERS="/boot/config/plugins/dynamix.my.servers/myservers.cfg"', - `CONNECT_CONFIG="/boot/config/plugins/dynamix.my.servers/configs/connect.json" + if (!fileContent.includes('MYSERVERS=')) { + throw new Error(`MYSERVERS not found in the file; incorrect target?`); + } + + let newContent = fileContent.replace( + 'MYSERVERS="/boot/config/plugins/dynamix.my.servers/myservers.cfg"', + `CONNECT_CONFIG="/boot/config/plugins/dynamix.my.servers/configs/connect.json" API_UTILS="/usr/local/share/dynamix.unraid.net/scripts/api_utils.sh"` - ); + ); - if (!newContent.includes('check_remote_access()')) { - newContent = newContent.replace( - '# create listening ports', - `# check if remote access should be enabled + if (!newContent.includes('check_remote_access()')) { + newContent = newContent.replace( + '# create listening ports', + `# check if remote access should be enabled check_remote_access(){ # Check if connect plugin is enabled using api_utils.sh if [[ -f $API_UTILS ]] && $API_UTILS is_api_plugin_enabled "unraid-api-plugin-connect"; then @@ -54,57 +60,38 @@ check_remote_access(){ } # create listening ports` - ); - } - - newContent = newContent.replace( - `if [[ -L /usr/local/sbin/unraid-api ]] && grep -qs 'wanaccess="yes"' $MYSERVERS && ! grep -qs 'username=""' $MYSERVERS; then`, - `if [[ -L /usr/local/sbin/unraid-api ]] && check_remote_access; then` ); - - newContent = newContent.replace( - 'for NET in ${!NET_FQDN6[@]}; do', - 'for NET in "${!NET_FQDN6[@]}"; do' - ); - newContent = newContent.replace( - 'for NET in ${!NET_FQDN[@]}; do', - 'for NET in "${!NET_FQDN[@]}"; do' - ); - - // Add robots.txt Access-Control-Allow-Origin header if not already present - if (!newContent.includes('#robots.txt any origin')) { - newContent = newContent.replace( - 'location = /robots.txt {', - // prettier-ignore - `location = /robots.txt { -\t add_header Access-Control-Allow-Origin *; #robots.txt any origin` - ); - } } newContent = newContent.replace( - /(^[\t ]*location \/graphql \{\n)([\s\S]*?)(^[\t ]*\})/gm, - (match: string, opening: string, directives: string, closing: string) => { - const proxyLine = - /^[\t ]*proxy_pass http:\/\/unix:\/var\/run\/unraid-api\.sock:\/graphql;[^\n]*\n/m; - if (!proxyLine.test(directives)) return match; - const withoutForwardedFor = directives.replace( - /^[\t ]*proxy_set_header[\t ]+X-Forwarded-For[\t ]+[^\n]*\n/gim, - '' - ); - const updated = withoutForwardedFor.replace(proxyLine, (line) => { - const indent = line.match(/^[\t ]*/)?.[0] ?? ''; - return `${line}${indent}proxy_set_header X-Forwarded-For $remote_addr;\n`; - }); - return `${opening}${updated}${closing}`; - } + `if [[ -L /usr/local/sbin/unraid-api ]] && grep -qs 'wanaccess="yes"' $MYSERVERS && ! grep -qs 'username=""' $MYSERVERS; then`, + `if [[ -L /usr/local/sbin/unraid-api ]] && check_remote_access; then` ); + newContent = newContent.replace( + 'for NET in ${!NET_FQDN6[@]}; do', + 'for NET in "${!NET_FQDN6[@]}"; do' + ); + newContent = newContent.replace( + 'for NET in ${!NET_FQDN[@]}; do', + 'for NET in "${!NET_FQDN[@]}"; do' + ); + + // Add robots.txt Access-Control-Allow-Origin header if not already present + if (!newContent.includes('#robots.txt any origin')) { + newContent = newContent.replace( + 'location = /robots.txt {', + // prettier-ignore + `location = /robots.txt { +\t add_header Access-Control-Allow-Origin *; #robots.txt any origin` + ); + } + return this.createPatchWithDiff(overridePath ?? this.filePath, fileContent, newContent); } async shouldApply(): Promise { - const { shouldApply, reason } = await super.shouldApply({ checkOsVersion: false }); + const { shouldApply, reason } = await super.shouldApply(); return { shouldApply, reason,