fix(security): protect first-run notifications and server errors (#3126)

* fix(security): close anonymous notification setup and mask server errors

* fix: hide internal errors in default deployment

* fix: route HTTP errors through application logger

* test: mock logger in API fallback regression

* fix: avoid sensitive SQL details in HTTP error logs
This commit is contained in:
whyour authored and GitHub committed 2026-11-10 01:11:54 +08:00
1 parent cae580e02f
commit 1cfc0c8e2e
11 files changed
+104 -146

No files matched your search

+1
View File
@@ -13,6 +13,7 @@ test('unknown API requests return JSON 404 while env.js and SPA deep links work'
const app = express();
load('back/loaders/express.ts', {
'../api': () => express.Router(),
'./logger': { error() {} },
'../config': {
rootPath: dir,
uploadPath: dir,
+52
View File
@@ -3,6 +3,7 @@ const test = require('node:test');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const util = require('node:util');
const express = require('express');
const jwt = require('jsonwebtoken');
const load = require('../helpers/load-security-module.cjs');
@@ -105,6 +106,8 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
let envWriteCalls = 0;
let scopedMutationCalls = 0;
let initialized = 0;
let notificationCalls = 0;
const loggedErrors = [];
const User = class {};
const Script = class {
getFile(folder, filename) {
@@ -121,6 +124,10 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
return { code: 200 };
},
getAuthInfo: async () => auth,
updateNotificationMode: async () => {
notificationCalls++;
return { code: 200 };
},
};
const mocks = {
'../config': config,
@@ -136,6 +143,7 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
shareStore: { getAuthInfo: async () => auth, getApps: async () => apps },
},
'../config/serverEnv': { serveEnv: (_req, res) => res.end() },
'./logger': { error: (...args) => loggedErrors.push(util.format(...args)) },
'../services/user': User,
'../services/script': Script,
'../data/open': {},
@@ -209,6 +217,17 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
commandCalls++;
res.json({ code: 200 });
});
router.get('/security-test/error', (_req, _res, next) =>
next(new Error('sensitive server detail')),
);
router.get('/security-test/db-error', (_req, _res, next) => {
const error = new Error('sensitive database detail');
error.name = 'SequelizeDatabaseError';
error.errors = [{ message: 'sensitive row value' }];
error.sql = "SELECT * FROM users WHERE password = 'sensitive password'";
error.parameters = ['sensitive parameter'];
next(error);
});
return router;
};
const app = express();
@@ -238,6 +257,39 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
);
return { status: response.status, body: await response.json() };
};
auth.username = 'admin';
auth.password = 'admin';
for (const prefix of ['/api', '/open', '/panel/api', '/panel/open']) {
const response = await request(
`${prefix}/user/notification/init`,
undefined,
'PUT',
{ type: 'webhook', webhookUrl: 'http://127.0.0.1/?title=$title' },
);
assert.equal(response.status, 401, prefix);
}
assert.equal(notificationCalls, 0);
auth.username = 'owner';
auth.password = 'configured';
assert.equal(
(await request('/api/user/notification', valid, 'PUT', {})).body.code,
200,
);
assert.equal(notificationCalls, 1);
for (const route of ['/security-test/error', '/security-test/db-error']) {
const response = await request(`/api${route}`, valid);
assert.equal(response.status, 500);
assert.deepEqual(response.body, { code: 500, message: '未知错误' });
}
assert.equal(loggedErrors.length, 2);
assert.match(loggedErrors[1], /type=SequelizeDatabaseError/);
assert.ok(loggedErrors.every((line) => !line.includes('sensitive')));
const malformedToken = await request('/api/envs', 'not-a-jwt');
assert.equal(malformedToken.status, 401);
assert.deepEqual(malformedToken.body, {
code: 401,
message: 'Token 已失效',
});
for (const url of [
'/api/user/init',
'/open/user/init',
+13
View File
@@ -52,6 +52,19 @@ test('health uses actual readiness and returns HTTP 503 until recovery',async(t)
assert.equal(r.status,expected);assert.equal(b.code,expected);assert.equal(b.data.services.grpc,ready);
}
});
test('health failure does not reveal internal error details',async(t)=>{
const express=require('express');
const HealthService=class{};
const app=express();load('back/api/health.ts',{
typedi:{get:()=>({check:async()=>{throw Error('sensitive health detail');}})},
'../services/health':{HealthService},'../loaders/logger':{error(){}},
}).default(app);
const server=app.listen(0,'127.0.0.1');await new Promise(r=>server.once('listening',r));
t.after(()=>new Promise(r=>{server.close(r);server.closeAllConnections();}));
const response=await fetch(`http://127.0.0.1:${server.address().port}/health`);
assert.equal(response.status,500);
assert.deepEqual(await response.json(),{code:500,message:'Health check failed'});
});
test('recovery registration errors propagate while ordinary autosave retains file synchronization',async()=>{
const source=fs.readFileSync('back/services/cron.ts','utf8');const a=source.indexOf(' public async autosave_crontab('),z=source.indexOf(' public async bootTask',a);
const js=ts.transpileModule('class Fixture {\n'+source.slice(a,z)+'}\nmodule.exports=Fixture;', {compilerOptions:{target:ts.ScriptTarget.ES2020}}).outputText;