Skip to content
Merged
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
22 changes: 6 additions & 16 deletions src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,13 @@ function isPublicApiRoute(pathname: string): boolean {
return PUBLIC_API_ROUTES.some((route) => pathname.startsWith(route));
}

/**
* Extract API key from request headers
*/
function extractApiKey(request: NextRequest): string | null {
const authHeader = request.headers.get('authorization');

if (!authHeader) {
return null;
}

// Check for Bearer token format
const bearerMatch = authHeader.match(/^Bearer\s+(.+)$/i);
if (bearerMatch) {
return bearerMatch[1];
Expand All @@ -60,30 +56,24 @@ function extractApiKey(request: NextRequest): string | null {
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;

// Only process API routes
if (!pathname.startsWith('/api/')) {
return NextResponse.next();
}

// Allow public API routes without authentication
if (isPublicApiRoute(pathname)) {
return NextResponse.next();
}

// do some basic API key validation
// Api key format validation before we send request to api
const apiKey = extractApiKey(request);

if (!apiKey) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

const match = apiKey.match(API_KEY_REGEX);

if (!match) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
if (apiKey) {
const match = apiKey.match(API_KEY_REGEX);
if (!match) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
}

Comment thread
vigneshrajsb marked this conversation as resolved.
// Pass the request through - API routes will handle full validation
return NextResponse.next();
}

Expand Down
25 changes: 15 additions & 10 deletions src/pages/api/v1/admin/api-keys/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,18 +264,23 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)

// Bootstrap mode: Allow first API key creation with bootstrap token
if (req.method === 'POST') {
const hasKeys = await authService.hasApiKeys();
const config = await authService.getApiConfig();

if (!hasKeys) {
const providedToken = req.headers['x-bootstrap-token'] as string;
const bootstrapToken = process.env.APP_BOOTSTRAP_TOKEN;
// Skip bootstrap check if auth is disabled globally
if (config.requireAuth) {
const hasKeys = await authService.hasApiKeys();

if (bootstrapToken && providedToken === bootstrapToken) {
logger.info('Bootstrap mode: Creating first API key with bootstrap token');
return await handleCreateApiKey(req, res, authService);
} else {
logger.warn('Bootstrap mode: Invalid or missing bootstrap token');
return res.status(401).json({ error: 'Unauthorized' });
if (!hasKeys) {
const providedToken = req.headers['x-bootstrap-token'] as string;
const bootstrapToken = process.env.APP_BOOTSTRAP_TOKEN;

if (bootstrapToken && providedToken === bootstrapToken) {
logger.info('Bootstrap mode: Creating first API key with bootstrap token');
return await handleCreateApiKey(req, res, authService);
} else {
logger.warn('Bootstrap mode: Invalid or missing bootstrap token');
return res.status(401).json({ error: 'Unauthorized' });
}
}
}
}
Comment thread
vigneshrajsb marked this conversation as resolved.
Expand Down
12 changes: 8 additions & 4 deletions src/server/lib/auth/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ export async function validateAuth(
res: NextApiResponse
): Promise<{ valid: boolean; apiKey?: ApiKey }> {
try {
const authService = new AuthService();
const config = await authService.getApiConfig();

// Skip all authentication and rate limiting if requireAuth is false
if (!config.requireAuth) {
return { valid: true };
}

const authHeader = req.headers.authorization as string;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
logger.error('Missing or invalid Authorization header');
Expand All @@ -43,10 +51,6 @@ export async function validateAuth(

const apiKeyString = authHeader.substring(7); // Remove 'Bearer ' prefix

const authService = new AuthService();

const config = await authService.getApiConfig();

const apiKey = await authService.validateApiKey(apiKeyString);

if (!apiKey) {
Expand Down
1 change: 1 addition & 0 deletions src/server/services/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const DEFAULT_API_CONFIG: ApiConfig = {
rate_limit: 1000,
rate_limit_window: 600,
bcrypt_rounds: 12,
requireAuth: true,
};

export interface CreateApiKeyOptions {
Expand Down
1 change: 1 addition & 0 deletions src/server/services/types/globalConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,5 @@ export type ApiConfig = {
rate_limit: number;
rate_limit_window: number;
bcrypt_rounds: number;
requireAuth: boolean;
};