Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"disposition": "PATCH",
"forecast_commit": "ee919505185a59be4ac687f6452d0db18520be50",
"reviewed_sha": "d7f2783a69c21fa3ccab91a6dc78f73d5823381a",
"schema": "limetech.ai-review-marker.v2",
"stage": "final",
"unresolved_proportionality_findings": []
}
115 changes: 115 additions & 0 deletions api/src/unraid-api/auth/fastify-throttler.guard.spec.ts
Original file line number Diff line number Diff line change
@@ -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> | 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<number | undefined>((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);
});
});
16 changes: 13 additions & 3 deletions api/src/unraid-api/auth/fastify-throttler.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
ThrottlerStorage,
ThrottlerStorageService,
} from '@nestjs/throttler';
import { isIP } from 'node:net';

import { type FastifyRequest } from 'fastify';

Expand All @@ -26,9 +27,18 @@ export class FastifyThrottlerGuard extends ThrottlerGuard {
);
}

protected async getTracker(req: Record<string, any>): Promise<string> {
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<string> {
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) {
Expand Down
79 changes: 77 additions & 2 deletions api/src/unraid-api/rest/rest.controller.oidc.integration.test.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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<typeof vi.fn>;
getProvider: ReturnType<typeof vi.fn>;
Expand Down Expand Up @@ -141,9 +146,23 @@ describe('RestController OIDC authorize integration', () => {
},
},
],
}).compile();
})
.overrideGuard(FastifyThrottlerGuard)
.useValue({ canActivate: () => true })
.compile();

controller = module.get<RestController>(RestController);
app = module.createNestApplication<NestFastifyApplication>(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();
Expand All @@ -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,
Expand Down
16 changes: 4 additions & 12 deletions api/src/unraid-api/rest/rest.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -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
) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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<string> {
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[] = [
{
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down
Loading