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/.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..6d8d333f32 --- /dev/null +++ b/.limetech/ai-review-markers/fix-api-client-identity-ws-policy-73041c5cc2c5.json @@ -0,0 +1,8 @@ +{ + "disposition": "PATCH", + "forecast_commit": "ee919505185a59be4ac687f6452d0db18520be50", + "reviewed_sha": "d7f2783a69c21fa3ccab91a6dc78f73d5823381a", + "schema": "limetech.ai-review-marker.v2", + "stage": "final", + "unresolved_proportionality_findings": [] +} 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..819d4e92e9 --- /dev/null +++ b/api/src/unraid-api/auth/fastify-throttler.guard.spec.ts @@ -0,0 +1,115 @@ +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 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(); + 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(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 48de4509cf..3d142e7901 100644 --- a/api/src/unraid-api/auth/fastify-throttler.guard.ts +++ b/api/src/unraid-api/auth/fastify-throttler.guard.ts @@ -9,6 +9,7 @@ import { ThrottlerStorage, ThrottlerStorageService, } from '@nestjs/throttler'; +import { isIP } from 'node:net'; import { type FastifyRequest } from 'fastify'; @@ -26,9 +27,18 @@ 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; + + // 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; + } + + // 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/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..0d22cbb61f 100644 --- a/api/src/unraid-api/rest/rest.controller.ts +++ b/api/src/unraid-api/rest/rest.controller.ts @@ -74,22 +74,14 @@ 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 ) { 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); @@ -153,8 +145,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 ) { 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; 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) {