From 24164d90f35bd691696e09ac7826f8959fa434c9 Mon Sep 17 00:00:00 2001 From: moonrailgun Date: Wed, 25 Nov 2026 23:24:54 +0800 Subject: [PATCH] fix(admin): require configured credentials and harden JWT verification --- server/admin-next/src/server/index.ts | 13 + .../src/server/middleware/auth.test.ts | 320 ++++++++++++++++-- .../admin-next/src/server/middleware/auth.ts | 82 ++++- server/admin-next/src/server/router/api.ts | 19 +- server/admin/package.json | 1 + server/admin/src/server/index.ts | 13 + .../admin/src/server/middleware/auth.test.ts | 286 ++++++++++++++++ server/admin/src/server/middleware/auth.ts | 82 ++++- server/admin/src/server/router/api.ts | 19 +- 9 files changed, 767 insertions(+), 68 deletions(-) create mode 100644 server/admin/src/server/middleware/auth.test.ts diff --git a/server/admin-next/src/server/index.ts b/server/admin-next/src/server/index.ts index 573b674ee06..34259d98a28 100644 --- a/server/admin-next/src/server/index.ts +++ b/server/admin-next/src/server/index.ts @@ -7,6 +7,7 @@ import path from 'path'; import dotenv from 'dotenv'; dotenv.config({ path: path.resolve(__dirname, '../../../.env') }); import { apiRouter } from './router/api'; +import { getAdminAuth } from './middleware/auth'; const app = express(); @@ -17,6 +18,18 @@ if (!process.env.MONGO_URL) { process.exit(1); } +if (!getAdminAuth()) { + console.warn( + '[Tailchat Admin Next] ADMIN_USER or ADMIN_PASS is not set. Admin login and protected APIs are disabled until both are configured.' + ); +} + +if (!process.env.SECRET?.trim() && process.env.NODE_ENV === 'production') { + console.warn( + '[Tailchat Admin Next] SECRET is not set, falling back to a publicly known default. Please set a strong random SECRET.' + ); +} + // 链接数据库 mongoose.connect(process.env.MONGO_URL, (error: any) => { if (!error) { diff --git a/server/admin-next/src/server/middleware/auth.test.ts b/server/admin-next/src/server/middleware/auth.test.ts index 6701242ed6c..984b0321c1b 100644 --- a/server/admin-next/src/server/middleware/auth.test.ts +++ b/server/admin-next/src/server/middleware/auth.test.ts @@ -1,59 +1,307 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { EventEmitter } from 'node:events'; +import type { Request, Response } from 'express'; import jwt from 'jsonwebtoken'; +import md5 from 'md5'; import auditLogModel from '../../../../models/auditLog'; -import { auth, authSecret } from './auth'; +import { + auth, + getAdminAuth, + getAuthSecret, + verifyAdminCredentials, +} from './auth'; -function request(method: string, statusCode = 200) { - const entries: any[] = []; - (auditLogModel as any).record = async (entry: any) => { - entries.push(entry); +interface AuditEntry { + source: string; + action: string; + operator: string; + success: boolean; + detail: unknown; + ip: string; + userAgent?: string; +} + +function withAdminEnv( + env: { ADMIN_USER?: string; ADMIN_PASS?: string; SECRET?: string }, + fn: () => void +) { + const prev = { + ADMIN_USER: process.env.ADMIN_USER, + ADMIN_PASS: process.env.ADMIN_PASS, + SECRET: process.env.SECRET, }; - const token = jwt.sign( - { username: 'root', platform: 'admin-next' }, - authSecret - ); - const req: any = { - method, + for (const key of ['ADMIN_USER', 'ADMIN_PASS', 'SECRET'] as const) { + if (env[key] === undefined) { + delete process.env[key]; + } else { + process.env[key] = env[key]; + } + } + + try { + fn(); + } finally { + for (const key of ['ADMIN_USER', 'ADMIN_PASS', 'SECRET'] as const) { + if (prev[key] === undefined) { + delete process.env[key]; + } else { + process.env[key] = prev[key]; + } + } + } +} + +function runAuthMiddleware(options: { + method?: string; + authorization?: string; + statusCode?: number; +}) { + const entries: AuditEntry[] = []; + const originalRecord = auditLogModel.record; + auditLogModel.record = (async (entry: AuditEntry) => { + entries.push(entry); + }) as typeof auditLogModel.record; + + const req = { + method: options.method ?? 'GET', originalUrl: '/admin-next/api/users/1?_sort=id', body: { nickname: 'foo' }, - headers: { authorization: `Bearer ${token}`, 'user-agent': 'node-test' }, + headers: { + ...(options.authorization !== undefined + ? { authorization: options.authorization } + : {}), + 'user-agent': 'node-test', + }, socket: { remoteAddress: '10.0.0.1' }, - }; - const res: any = Object.assign(new EventEmitter(), { statusCode }); - let passed = false; + } as unknown as Request; - auth()(req, res, () => { - passed = true; + let responseStatus = options.statusCode ?? 200; + let responseBody = ''; + const resEmitter = Object.assign(new EventEmitter(), { + get statusCode() { + return responseStatus; + }, + set statusCode(code: number) { + responseStatus = code; + }, + status(code: number) { + responseStatus = code; + return this; + }, + end(body?: string) { + if (body !== undefined) { + responseBody = body; + } + return this; + }, }); - res.emit('finish'); + const res = resEmitter as unknown as Response; + + let passed = false; + try { + auth()(req, res, () => { + passed = true; + }); + resEmitter.emit('finish'); + } finally { + auditLogModel.record = originalRecord; + } - return { entries, passed }; + return { entries, passed, statusCode: responseStatus, body: responseBody }; } -test('audits authenticated write requests with operator and result', () => { - const { entries, passed } = request('PUT'); +test('rejects forged JWT when ADMIN_PASS is empty with default docker-compose env', () => { + withAdminEnv({ ADMIN_USER: 'tailchat', ADMIN_PASS: '', SECRET: '' }, () => { + assert.equal(getAdminAuth(), null); + assert.equal(getAuthSecret(), null); + assert.equal(verifyAdminCredentials('tailchat', ''), false); + + const forgedSecret = + 'tailchat' + md5(JSON.stringify({ username: 'tailchat', password: '' })); + const forgedWithoutUser = jwt.sign( + { platform: 'admin-next' }, + forgedSecret + ); + const forgedWithUser = jwt.sign( + { username: 'tailchat', platform: 'admin-next' }, + forgedSecret + ); - assert.equal(passed, true); - assert.deepEqual(entries, [ + for (const token of [forgedWithoutUser, forgedWithUser]) { + const result = runAuthMiddleware({ + method: 'POST', + authorization: `Bearer ${token}`, + }); + assert.equal(result.passed, false); + assert.equal(result.statusCode, 401); + assert.equal(result.body, 'Server not set env: ADMIN_USER, ADMIN_PASS'); + assert.deepEqual(result.entries, []); + } + }); +}); + +test('rejects requests when credentials are unset or whitespace-only even if SECRET is set', () => { + const cases = [ + { ADMIN_USER: undefined, ADMIN_PASS: undefined, SECRET: undefined }, + { ADMIN_USER: 'tailchat', ADMIN_PASS: ' ', SECRET: 'custom-secret' }, { - source: 'admin', - action: 'PUT /admin-next/api/users/1', - operator: 'root', - success: true, - detail: { nickname: 'foo' }, - ip: '10.0.0.1', - userAgent: 'node-test', + ADMIN_USER: ' ', + ADMIN_PASS: 'configured-value', + SECRET: 'custom-secret', }, - ]); - assert.equal(request('DELETE', 500).entries[0].success, false); + ]; + + for (const env of cases) { + withAdminEnv(env, () => { + assert.equal(getAdminAuth(), null); + assert.equal(getAuthSecret(), null); + + const forgedSecret = + (env.SECRET || 'tailchat') + + md5( + JSON.stringify({ + username: env.ADMIN_USER, + password: env.ADMIN_PASS, + }) + ); + const token = jwt.sign( + { username: env.ADMIN_USER || 'tailchat', platform: 'admin-next' }, + forgedSecret + ); + const result = runAuthMiddleware({ + method: 'GET', + authorization: `Bearer ${token}`, + }); + assert.equal(result.passed, false); + assert.equal(result.statusCode, 401); + }); + } +}); + +test('audits authenticated write requests with operator and result', () => { + withAdminEnv( + { ADMIN_USER: 'root', ADMIN_PASS: 'configured-pass', SECRET: 'test-key' }, + () => { + const secret = getAuthSecret(); + assert.ok(secret); + const token = jwt.sign( + { username: 'root', platform: 'admin-next' }, + secret + ); + + const putResult = runAuthMiddleware({ + method: 'PUT', + authorization: `Bearer ${token}`, + }); + assert.equal(putResult.passed, true); + assert.deepEqual(putResult.entries, [ + { + source: 'admin', + action: 'PUT /admin-next/api/users/1', + operator: 'root', + success: true, + detail: { nickname: 'foo' }, + ip: '10.0.0.1', + userAgent: 'node-test', + }, + ]); + + const deleteResult = runAuthMiddleware({ + method: 'DELETE', + authorization: `Bearer ${token}`, + statusCode: 500, + }); + assert.equal(deleteResult.passed, true); + assert.equal(deleteResult.entries[0].success, false); + } + ); +}); + +test('does not audit read requests and accepts case-insensitive Bearer scheme', () => { + withAdminEnv( + { ADMIN_USER: 'root', ADMIN_PASS: 'configured-pass', SECRET: 'test-key' }, + () => { + const secret = getAuthSecret(); + assert.ok(secret); + const token = jwt.sign( + { username: 'root', platform: 'admin-next' }, + secret + ); + + const result = runAuthMiddleware({ + method: 'GET', + authorization: `bearer ${token}`, + }); + assert.equal(result.passed, true); + assert.deepEqual(result.entries, []); + } + ); }); -test('does not audit read requests', () => { - const { entries, passed } = request('GET'); +test('rejects invalid authorization headers, forged keys, wrong platform, wrong username, and unsigned tokens', () => { + withAdminEnv( + { ADMIN_USER: 'root', ADMIN_PASS: 'configured-pass', SECRET: 'test-key' }, + () => { + const secret = getAuthSecret(); + assert.ok(secret); - assert.equal(passed, true); - assert.deepEqual(entries, []); + assert.equal(verifyAdminCredentials('root', 'configured-pass'), true); + assert.equal(verifyAdminCredentials('root', 'wrong-pass'), false); + assert.equal(verifyAdminCredentials('other', 'configured-pass'), false); + assert.equal(verifyAdminCredentials(null, 'configured-pass'), false); + + const missingHeader = runAuthMiddleware({ method: 'GET' }); + assert.equal(missingHeader.passed, false); + assert.equal(missingHeader.statusCode, 401); + + const validToken = jwt.sign( + { username: 'root', platform: 'admin-next' }, + secret + ); + const nonBearer = runAuthMiddleware({ + method: 'GET', + authorization: `Basic ${validToken}`, + }); + assert.equal(nonBearer.passed, false); + assert.equal(nonBearer.statusCode, 401); + + const defaultEmptyKey = + 'tailchat' + + md5(JSON.stringify({ username: 'tailchat', password: '' })); + const forgedWithDefaultKey = jwt.sign( + { username: 'root', platform: 'admin-next' }, + defaultEmptyKey + ); + const wrongPlatform = jwt.sign( + { username: 'root', platform: 'admin' }, + secret + ); + const wrongUsername = jwt.sign( + { username: 'other', platform: 'admin-next' }, + secret + ); + const missingUsername = jwt.sign({ platform: 'admin-next' }, secret); + const noneAlgToken = `${Buffer.from( + JSON.stringify({ alg: 'none', typ: 'JWT' }) + ).toString('base64url')}.${Buffer.from( + JSON.stringify({ username: 'root', platform: 'admin-next' }) + ).toString('base64url')}.`; + + for (const token of [ + forgedWithDefaultKey, + wrongPlatform, + wrongUsername, + missingUsername, + noneAlgToken, + ]) { + const result = runAuthMiddleware({ + authorization: `Bearer ${token}`, + }); + assert.equal(result.passed, false); + assert.equal(result.statusCode, 401); + } + } + ); }); diff --git a/server/admin-next/src/server/middleware/auth.ts b/server/admin-next/src/server/middleware/auth.ts index 0650e41992e..fcd0cb05ddc 100644 --- a/server/admin-next/src/server/middleware/auth.ts +++ b/server/admin-next/src/server/middleware/auth.ts @@ -1,16 +1,65 @@ +import crypto from 'crypto'; import type { NextFunction, Request, Response } from 'express'; import jwt from 'jsonwebtoken'; import md5 from 'md5'; import auditLogModel from '../../../../models/auditLog'; import { getRequestIp } from '../../../../lib/requestIp'; -export const adminAuth = { - username: process.env.ADMIN_USER, - password: process.env.ADMIN_PASS, -}; +export interface AdminAuthConfig { + username: string; + password: string; +} + +export function getAdminAuth(): AdminAuthConfig | null { + const username = process.env.ADMIN_USER; + const password = process.env.ADMIN_PASS; + + if (!username?.trim() || !password?.trim()) { + return null; + } + + return { + username, + password, + }; +} + +export function getAuthSecret( + adminAuth: AdminAuthConfig | null = getAdminAuth() +): string | null { + if (!adminAuth) { + return null; + } + + // 增加一个md5的盐值确保SECRET没有设置的情况下只修改了用户名密码也不会被人伪造token秘钥 + return (process.env.SECRET || 'tailchat') + md5(JSON.stringify(adminAuth)); +} + +function timingSafeEqualStr(a: string, b: string): boolean { + return crypto.timingSafeEqual( + crypto.createHash('sha256').update(a).digest(), + crypto.createHash('sha256').update(b).digest() + ); +} + +export function verifyAdminCredentials( + username: unknown, + password: unknown, + adminAuth: AdminAuthConfig | null = getAdminAuth() +): boolean { + if ( + !adminAuth || + typeof username !== 'string' || + typeof password !== 'string' + ) { + return false; + } -export const authSecret = - (process.env.SECRET || 'tailchat') + md5(JSON.stringify(adminAuth)); // 增加一个md5的盐值确保SECRET没有设置的情况下只修改了用户名密码也不会被人伪造token秘钥 + const usernameMatched = timingSafeEqualStr(username, adminAuth.username); + const passwordMatched = timingSafeEqualStr(password, adminAuth.password); + + return usernameMatched && passwordMatched; +} /** * 记录管理后台操作的审计日志 @@ -37,20 +86,37 @@ export function recordAdminAudit( export function auth() { return (req: Request, res: Response, next: NextFunction) => { try { + const adminAuth = getAdminAuth(); + const authSecret = getAuthSecret(adminAuth); + if (!adminAuth || !authSecret) { + res.status(401).end('Server not set env: ADMIN_USER, ADMIN_PASS'); + return; + } + const authorization = req.headers.authorization; if (!authorization) { res.status(401).end('not found authorization in headers'); return; } + if (!/^Bearer /i.test(authorization)) { + res.status(401).end('Invalid authorization header'); + return; + } + const token = authorization.slice('Bearer '.length); - const payload = jwt.verify(token, authSecret); + const payload = jwt.verify(token, authSecret, { + algorithms: ['HS256'], + }); if (typeof payload === 'string') { res.status(401).end('payload type error'); return; } - if (payload.platform !== 'admin-next') { + if ( + payload.platform !== 'admin-next' || + payload.username !== adminAuth.username + ) { res.status(401).end('Payload invalid'); return; } diff --git a/server/admin-next/src/server/router/api.ts b/server/admin-next/src/server/router/api.ts index 884fe53d712..a81f21b1326 100644 --- a/server/admin-next/src/server/router/api.ts +++ b/server/admin-next/src/server/router/api.ts @@ -2,10 +2,11 @@ import { Router } from 'express'; import jwt from 'jsonwebtoken'; import { broker, callBrokerAction } from '../broker'; import { - adminAuth, auth, - authSecret, + getAdminAuth, + getAuthSecret, recordAdminAudit, + verifyAdminCredentials, } from '../middleware/auth'; import { configRouter } from './config'; import { networkRouter } from './network'; @@ -29,18 +30,20 @@ import _ from 'lodash'; const router = Router(); router.post('/login', (req, res) => { - if (!adminAuth.username || !adminAuth.password) { + const adminAuth = getAdminAuth(); + const authSecret = getAuthSecret(adminAuth); + if (!adminAuth || !authSecret) { res.status(401).end('Server not set env: ADMIN_USER, ADMIN_PASS'); return; } - const { username, password } = req.body; + const { username, password } = req.body ?? {}; - if (username === adminAuth.username && password === adminAuth.password) { + if (verifyAdminCredentials(username, password, adminAuth)) { // 用户名和密码都正确,返回token const token = jwt.sign( { - username, + username: adminAuth.username, platform: 'admin-next', }, authSecret, @@ -50,11 +53,11 @@ router.post('/login', (req, res) => { ); res.status(200).json({ - username, + username: adminAuth.username, token: token, expiredAt: new Date().valueOf() + 2 * 60 * 60 * 1000, }); - recordAdminAudit(req, username, true); + recordAdminAudit(req, adminAuth.username, true); } else { res.status(401).end('username or password incorrect'); recordAdminAudit(req, username, false); diff --git a/server/admin/package.json b/server/admin/package.json index 4267f06702e..ddab7ac06bf 100644 --- a/server/admin/package.json +++ b/server/admin/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "nodemon", "start": "cross-env NODE_ENV=production node dist/admin/src/server/index.js", + "test": "node --test -r ts-node/register src/server/middleware/*.test.ts", "build": "pnpm build:client && pnpm build:server", "build:client": "vite build", "build:server": "tsc -p tsconfig.server.json" diff --git a/server/admin/src/server/index.ts b/server/admin/src/server/index.ts index 87eb17222c9..dc381d38493 100644 --- a/server/admin/src/server/index.ts +++ b/server/admin/src/server/index.ts @@ -7,6 +7,7 @@ import path from 'path'; import dotenv from 'dotenv'; dotenv.config({ path: path.resolve(__dirname, '../../../.env') }); import { apiRouter } from './router/api'; +import { getAdminAuth } from './middleware/auth'; const app = express(); @@ -17,6 +18,18 @@ if (!process.env.MONGO_URL) { process.exit(1); } +if (!getAdminAuth()) { + console.warn( + '[Tailchat Admin] ADMIN_USER or ADMIN_PASS is not set. Admin login and protected APIs are disabled until both are configured.' + ); +} + +if (!process.env.SECRET?.trim() && process.env.NODE_ENV === 'production') { + console.warn( + '[Tailchat Admin] SECRET is not set, falling back to a publicly known default. Please set a strong random SECRET.' + ); +} + // 链接数据库 mongoose.connect(process.env.MONGO_URL, (error: any) => { if (!error) { diff --git a/server/admin/src/server/middleware/auth.test.ts b/server/admin/src/server/middleware/auth.test.ts new file mode 100644 index 00000000000..bb92c445e3f --- /dev/null +++ b/server/admin/src/server/middleware/auth.test.ts @@ -0,0 +1,286 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import type { Request, Response } from 'express'; +import jwt from 'jsonwebtoken'; +import md5 from 'md5'; +import auditLogModel from '../../../../models/auditLog'; +import { + auth, + getAdminAuth, + getAuthSecret, + verifyAdminCredentials, +} from './auth'; + +interface AuditEntry { + source: string; + action: string; + operator: string; + success: boolean; + detail: unknown; + ip: string; + userAgent?: string; +} + +function withAdminEnv( + env: { ADMIN_USER?: string; ADMIN_PASS?: string; SECRET?: string }, + fn: () => void +) { + const prev = { + ADMIN_USER: process.env.ADMIN_USER, + ADMIN_PASS: process.env.ADMIN_PASS, + SECRET: process.env.SECRET, + }; + + for (const key of ['ADMIN_USER', 'ADMIN_PASS', 'SECRET'] as const) { + if (env[key] === undefined) { + delete process.env[key]; + } else { + process.env[key] = env[key]; + } + } + + try { + fn(); + } finally { + for (const key of ['ADMIN_USER', 'ADMIN_PASS', 'SECRET'] as const) { + if (prev[key] === undefined) { + delete process.env[key]; + } else { + process.env[key] = prev[key]; + } + } + } +} + +function runAuthMiddleware(options: { + method?: string; + authorization?: string; + statusCode?: number; +}) { + const entries: AuditEntry[] = []; + const originalRecord = auditLogModel.record; + auditLogModel.record = (async (entry: AuditEntry) => { + entries.push(entry); + }) as typeof auditLogModel.record; + + const req = { + method: options.method ?? 'GET', + originalUrl: '/admin/api/user/count/summary', + body: { nickname: 'foo' }, + headers: { + ...(options.authorization !== undefined + ? { authorization: options.authorization } + : {}), + 'user-agent': 'node-test', + }, + socket: { remoteAddress: '10.0.0.1' }, + } as unknown as Request; + + let responseStatus = options.statusCode ?? 200; + let responseBody = ''; + const resEmitter = Object.assign(new EventEmitter(), { + get statusCode() { + return responseStatus; + }, + set statusCode(code: number) { + responseStatus = code; + }, + status(code: number) { + responseStatus = code; + return this; + }, + end(body?: string) { + if (body !== undefined) { + responseBody = body; + } + return this; + }, + }); + const res = resEmitter as unknown as Response; + + let passed = false; + try { + auth()(req, res, () => { + passed = true; + }); + resEmitter.emit('finish'); + } finally { + auditLogModel.record = originalRecord; + } + + return { entries, passed, statusCode: responseStatus, body: responseBody }; +} + +test('rejects forged JWT when ADMIN_PASS is empty with default docker-compose env', () => { + withAdminEnv({ ADMIN_USER: 'tailchat', ADMIN_PASS: '', SECRET: '' }, () => { + assert.equal(getAdminAuth(), null); + assert.equal(getAuthSecret(), null); + assert.equal(verifyAdminCredentials('tailchat', ''), false); + + const forgedSecret = + 'tailchat' + md5(JSON.stringify({ username: 'tailchat', password: '' })); + const forgedWithoutUser = jwt.sign({ platform: 'admin' }, forgedSecret); + const forgedWithUser = jwt.sign( + { username: 'tailchat', platform: 'admin' }, + forgedSecret + ); + + for (const token of [forgedWithoutUser, forgedWithUser]) { + const result = runAuthMiddleware({ + method: 'GET', + authorization: `Bearer ${token}`, + }); + assert.equal(result.passed, false); + assert.equal(result.statusCode, 401); + assert.equal(result.body, 'Server not set env: ADMIN_USER, ADMIN_PASS'); + assert.deepEqual(result.entries, []); + } + }); +}); + +test('rejects requests when credentials are unset or whitespace-only even if SECRET is set', () => { + const cases = [ + { ADMIN_USER: undefined, ADMIN_PASS: undefined, SECRET: undefined }, + { ADMIN_USER: 'tailchat', ADMIN_PASS: ' ', SECRET: 'custom-secret' }, + { + ADMIN_USER: ' ', + ADMIN_PASS: 'configured-value', + SECRET: 'custom-secret', + }, + ]; + + for (const env of cases) { + withAdminEnv(env, () => { + assert.equal(getAdminAuth(), null); + assert.equal(getAuthSecret(), null); + + const forgedSecret = + (env.SECRET || 'tailchat') + + md5( + JSON.stringify({ + username: env.ADMIN_USER, + password: env.ADMIN_PASS, + }) + ); + const token = jwt.sign( + { username: env.ADMIN_USER || 'tailchat', platform: 'admin' }, + forgedSecret + ); + const result = runAuthMiddleware({ + method: 'GET', + authorization: `Bearer ${token}`, + }); + assert.equal(result.passed, false); + assert.equal(result.statusCode, 401); + }); + } +}); + +test('allows valid admin JWT (case-insensitive Bearer) and audits write requests', () => { + withAdminEnv( + { ADMIN_USER: 'root', ADMIN_PASS: 'configured-pass', SECRET: 'test-key' }, + () => { + const secret = getAuthSecret(); + assert.ok(secret); + const token = jwt.sign({ username: 'root', platform: 'admin' }, secret); + + const getResult = runAuthMiddleware({ + method: 'GET', + authorization: `bearer ${token}`, + }); + assert.equal(getResult.passed, true); + assert.deepEqual(getResult.entries, []); + + const postResult = runAuthMiddleware({ + method: 'POST', + authorization: `Bearer ${token}`, + }); + assert.equal(postResult.passed, true); + assert.deepEqual(postResult.entries, [ + { + source: 'admin', + action: 'POST /admin/api/user/count/summary', + operator: 'root', + success: true, + detail: { nickname: 'foo' }, + ip: '10.0.0.1', + userAgent: 'node-test', + }, + ]); + + const deleteResult = runAuthMiddleware({ + method: 'DELETE', + authorization: `Bearer ${token}`, + statusCode: 500, + }); + assert.equal(deleteResult.passed, true); + assert.equal(deleteResult.entries[0].success, false); + } + ); +}); + +test('rejects invalid authorization headers, forged keys, wrong platform, wrong username, and unsigned tokens', () => { + withAdminEnv( + { ADMIN_USER: 'root', ADMIN_PASS: 'configured-pass', SECRET: 'test-key' }, + () => { + const secret = getAuthSecret(); + assert.ok(secret); + + assert.equal(verifyAdminCredentials('root', 'configured-pass'), true); + assert.equal(verifyAdminCredentials('root', 'wrong-pass'), false); + assert.equal(verifyAdminCredentials('other', 'configured-pass'), false); + assert.equal(verifyAdminCredentials(null, 'configured-pass'), false); + + const missingHeader = runAuthMiddleware({ method: 'GET' }); + assert.equal(missingHeader.passed, false); + assert.equal(missingHeader.statusCode, 401); + + const validToken = jwt.sign( + { username: 'root', platform: 'admin' }, + secret + ); + const nonBearer = runAuthMiddleware({ + authorization: `Basic ${validToken}`, + }); + assert.equal(nonBearer.passed, false); + assert.equal(nonBearer.statusCode, 401); + + const defaultEmptyKey = + 'tailchat' + + md5(JSON.stringify({ username: 'tailchat', password: '' })); + const forgedWithDefaultKey = jwt.sign( + { username: 'root', platform: 'admin' }, + defaultEmptyKey + ); + const wrongPlatform = jwt.sign( + { username: 'root', platform: 'admin-next' }, + secret + ); + const wrongUsername = jwt.sign( + { username: 'other', platform: 'admin' }, + secret + ); + const missingUsername = jwt.sign({ platform: 'admin' }, secret); + const noneAlgToken = `${Buffer.from( + JSON.stringify({ alg: 'none', typ: 'JWT' }) + ).toString('base64url')}.${Buffer.from( + JSON.stringify({ username: 'root', platform: 'admin' }) + ).toString('base64url')}.`; + + for (const token of [ + forgedWithDefaultKey, + wrongPlatform, + wrongUsername, + missingUsername, + noneAlgToken, + ]) { + const result = runAuthMiddleware({ + authorization: `Bearer ${token}`, + }); + assert.equal(result.passed, false); + assert.equal(result.statusCode, 401); + } + } + ); +}); diff --git a/server/admin/src/server/middleware/auth.ts b/server/admin/src/server/middleware/auth.ts index 37b674948f9..f531862346a 100644 --- a/server/admin/src/server/middleware/auth.ts +++ b/server/admin/src/server/middleware/auth.ts @@ -1,16 +1,65 @@ +import crypto from 'crypto'; import type { NextFunction, Request, Response } from 'express'; import jwt from 'jsonwebtoken'; import md5 from 'md5'; import auditLogModel from '../../../../models/auditLog'; import { getRequestIp } from '../../../../lib/requestIp'; -export const adminAuth = { - username: process.env.ADMIN_USER, - password: process.env.ADMIN_PASS, -}; +export interface AdminAuthConfig { + username: string; + password: string; +} + +export function getAdminAuth(): AdminAuthConfig | null { + const username = process.env.ADMIN_USER; + const password = process.env.ADMIN_PASS; + + if (!username?.trim() || !password?.trim()) { + return null; + } + + return { + username, + password, + }; +} + +export function getAuthSecret( + adminAuth: AdminAuthConfig | null = getAdminAuth() +): string | null { + if (!adminAuth) { + return null; + } + + // 增加一个md5的盐值确保SECRET没有设置的情况下只修改了用户名密码也不会被人伪造token秘钥 + return (process.env.SECRET || 'tailchat') + md5(JSON.stringify(adminAuth)); +} + +function timingSafeEqualStr(a: string, b: string): boolean { + return crypto.timingSafeEqual( + crypto.createHash('sha256').update(a).digest(), + crypto.createHash('sha256').update(b).digest() + ); +} + +export function verifyAdminCredentials( + username: unknown, + password: unknown, + adminAuth: AdminAuthConfig | null = getAdminAuth() +): boolean { + if ( + !adminAuth || + typeof username !== 'string' || + typeof password !== 'string' + ) { + return false; + } -export const authSecret = - (process.env.SECRET || 'tailchat') + md5(JSON.stringify(adminAuth)); // 增加一个md5的盐值确保SECRET没有设置的情况下只修改了用户名密码也不会被人伪造token秘钥 + const usernameMatched = timingSafeEqualStr(username, adminAuth.username); + const passwordMatched = timingSafeEqualStr(password, adminAuth.password); + + return usernameMatched && passwordMatched; +} /** * 记录管理后台操作的审计日志 @@ -37,20 +86,37 @@ export function recordAdminAudit( export function auth() { return (req: Request, res: Response, next: NextFunction) => { try { + const adminAuth = getAdminAuth(); + const authSecret = getAuthSecret(adminAuth); + if (!adminAuth || !authSecret) { + res.status(401).end('Server not set env: ADMIN_USER, ADMIN_PASS'); + return; + } + const authorization = req.headers.authorization; if (!authorization) { res.status(401).end('not found authorization in headers'); return; } + if (!/^Bearer /i.test(authorization)) { + res.status(401).end('Invalid authorization header'); + return; + } + const token = authorization.slice('Bearer '.length); - const payload = jwt.verify(token, authSecret); + const payload = jwt.verify(token, authSecret, { + algorithms: ['HS256'], + }); if (typeof payload === 'string') { res.status(401).end('payload type error'); return; } - if (payload.platform !== 'admin') { + if ( + payload.platform !== 'admin' || + payload.username !== adminAuth.username + ) { res.status(401).end('Payload invalid'); return; } diff --git a/server/admin/src/server/router/api.ts b/server/admin/src/server/router/api.ts index addd791788d..719d02740c7 100644 --- a/server/admin/src/server/router/api.ts +++ b/server/admin/src/server/router/api.ts @@ -2,10 +2,11 @@ import { Router } from 'express'; import jwt from 'jsonwebtoken'; import { broker, callBrokerAction } from '../broker'; import { - adminAuth, auth, - authSecret, + getAdminAuth, + getAuthSecret, recordAdminAudit, + verifyAdminCredentials, } from '../middleware/auth'; import { configRouter } from './config'; import { networkRouter } from './network'; @@ -29,18 +30,20 @@ import _ from 'lodash'; const router = Router(); router.post('/login', (req, res) => { - if (!adminAuth.username || !adminAuth.password) { + const adminAuth = getAdminAuth(); + const authSecret = getAuthSecret(adminAuth); + if (!adminAuth || !authSecret) { res.status(401).end('Server not set env: ADMIN_USER, ADMIN_PASS'); return; } - const { username, password } = req.body; + const { username, password } = req.body ?? {}; - if (username === adminAuth.username && password === adminAuth.password) { + if (verifyAdminCredentials(username, password, adminAuth)) { // 用户名和密码都正确,返回token const token = jwt.sign( { - username, + username: adminAuth.username, platform: 'admin', }, authSecret, @@ -50,11 +53,11 @@ router.post('/login', (req, res) => { ); res.status(200).json({ - username, + username: adminAuth.username, token: token, expiredAt: new Date().valueOf() + 2 * 60 * 60 * 1000, }); - recordAdminAudit(req, username, true); + recordAdminAudit(req, adminAuth.username, true); } else { res.status(401).end('username or password incorrect'); recordAdminAudit(req, username, false);