mirror of
https://github.com/whyour/qinglong.git
synced 2026-10-02 06:31:40 +08:00
fix: report resource conflicts and accurate CLI API errors
This commit is contained in:
@@ -14,6 +14,7 @@ import { AuthInfo } from '../data/system';
|
|||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { t } from '../shared/i18n';
|
import { t } from '../shared/i18n';
|
||||||
import { AppScope } from '../data/open';
|
import { AppScope } from '../data/open';
|
||||||
|
import uniqueConstraintError from '../middlewares/uniqueConstraintError';
|
||||||
import protectedPathCase from '../middlewares/protectedPathCase';
|
import protectedPathCase from '../middlewares/protectedPathCase';
|
||||||
|
|
||||||
function resolveTrustProxy(value = process.env.QL_TRUST_PROXY) {
|
function resolveTrustProxy(value = process.env.QL_TRUST_PROXY) {
|
||||||
@@ -190,6 +191,7 @@ export default ({ app }: { app: Application }) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.use(errors());
|
app.use(errors());
|
||||||
|
app.use(uniqueConstraintError);
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
(
|
(
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { ErrorRequestHandler } from 'express';
|
||||||
|
import { UniqueConstraintError } from 'sequelize';
|
||||||
|
import { t } from '../shared/i18n';
|
||||||
|
|
||||||
|
// Handle the database constraint itself so concurrent writes are covered too.
|
||||||
|
const uniqueConstraintError: ErrorRequestHandler = (err, req, res, next) => {
|
||||||
|
if (!(err instanceof UniqueConstraintError)) return next(err);
|
||||||
|
// Constraint details can contain environment values or application credentials.
|
||||||
|
res
|
||||||
|
.status(409)
|
||||||
|
.json({ code: 409, message: t('资源已存在,请检查重复的名称或值') });
|
||||||
|
};
|
||||||
|
|
||||||
|
export default uniqueConstraintError;
|
||||||
@@ -3,6 +3,7 @@ import { shareStore } from './store';
|
|||||||
const messages: Record<string, Record<string, string>> = {
|
const messages: Record<string, Record<string, string>> = {
|
||||||
zh: {},
|
zh: {},
|
||||||
en: {
|
en: {
|
||||||
|
'资源已存在,请检查重复的名称或值': 'Resource already exists; check for duplicate names or values',
|
||||||
'暂无权限': 'Access denied',
|
'暂无权限': 'Access denied',
|
||||||
'参数错误': 'Invalid parameter',
|
'参数错误': 'Invalid parameter',
|
||||||
'参数不正确': 'Invalid parameter',
|
'参数不正确': 'Invalid parameter',
|
||||||
|
|||||||
@@ -53,23 +53,12 @@ export async function request(
|
|||||||
// Check HTTP status before decoding (proxies may return HTML on denial).
|
// Check HTTP status before decoding (proxies may return HTML on denial).
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
await response.body?.cancel();
|
await response.body?.cancel();
|
||||||
const suffix =
|
rejectResponse(
|
||||||
method !== 'GET' && response.status >= 500
|
response.status,
|
||||||
? translate(
|
'HTTP',
|
||||||
process.env,
|
method,
|
||||||
' 执行结果可能未知,请先检查%s状态再考虑重试。',
|
resource,
|
||||||
resource,
|
credentialsHint,
|
||||||
)
|
|
||||||
: '';
|
|
||||||
fail(
|
|
||||||
translate(
|
|
||||||
process.env,
|
|
||||||
'API 请求被拒绝(HTTP %s),请检查%s。%s',
|
|
||||||
response.status,
|
|
||||||
credentialsHint,
|
|
||||||
suffix,
|
|
||||||
),
|
|
||||||
[401, 403].includes(response.status) ? 3 : 1,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
@@ -100,28 +89,63 @@ export async function request(
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (endpoint.split('?')[0] === 'user/login' && isRecord(result) && result.code === 420)
|
if (
|
||||||
fail(translate(process.env, '需要双因素验证,请调用 user two-factor-login。'), 3);
|
endpoint.split('?')[0] === 'user/login' &&
|
||||||
|
isRecord(result) &&
|
||||||
|
result.code === 420
|
||||||
|
)
|
||||||
|
fail(
|
||||||
|
translate(process.env, '需要双因素验证,请调用 user two-factor-login。'),
|
||||||
|
3,
|
||||||
|
);
|
||||||
if (!isRecord(result) || result.code !== 200) {
|
if (!isRecord(result) || result.code !== 200) {
|
||||||
const status =
|
const status =
|
||||||
isRecord(result) && typeof result.code === 'number'
|
isRecord(result) && typeof result.code === 'number'
|
||||||
? result.code
|
? result.code
|
||||||
: undefined;
|
: undefined;
|
||||||
fail(
|
rejectResponse(status, 'code', method, resource, credentialsHint);
|
||||||
translate(
|
|
||||||
process.env,
|
|
||||||
'API 请求被拒绝(code %s),请检查%s。',
|
|
||||||
status ?? translate(process.env, '未知'),
|
|
||||||
credentialsHint,
|
|
||||||
),
|
|
||||||
status === 401 || status === 403 ? 3 : 1,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (options.output)
|
if (options.output)
|
||||||
fail(translate(process.env, '接口返回 JSON,未保存下载文件。'));
|
fail(translate(process.env, '接口返回 JSON,未保存下载文件。'));
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function rejectResponse(
|
||||||
|
status: number | undefined,
|
||||||
|
kind: 'HTTP' | 'code',
|
||||||
|
method: string,
|
||||||
|
resource: string,
|
||||||
|
credentialsHint: string,
|
||||||
|
): never {
|
||||||
|
const denied = status === 401 || status === 403;
|
||||||
|
const reason = denied
|
||||||
|
? translate(process.env, '请检查%s。', credentialsHint)
|
||||||
|
: status === 409
|
||||||
|
? translate(process.env, '资源冲突,请检查重复的名称或值。')
|
||||||
|
: status !== undefined && status >= 500
|
||||||
|
? translate(process.env, '服务端错误,请检查服务状态和日志。')
|
||||||
|
: translate(process.env, '请求未成功,请检查请求参数和服务日志。');
|
||||||
|
const suffix =
|
||||||
|
method !== 'GET' && (status === undefined || status >= 500)
|
||||||
|
? translate(
|
||||||
|
process.env,
|
||||||
|
' 执行结果可能未知,请先检查%s状态再考虑重试。',
|
||||||
|
resource,
|
||||||
|
)
|
||||||
|
: '';
|
||||||
|
fail(
|
||||||
|
translate(
|
||||||
|
process.env,
|
||||||
|
'API 请求失败(%s %s)。%s%s',
|
||||||
|
kind,
|
||||||
|
status ?? translate(process.env, '未知'),
|
||||||
|
reason,
|
||||||
|
suffix,
|
||||||
|
),
|
||||||
|
denied ? 3 : 1,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export async function authenticate(config: Credentials): Promise<Session> {
|
export async function authenticate(config: Credentials): Promise<Session> {
|
||||||
const query = new URLSearchParams({
|
const query = new URLSearchParams({
|
||||||
client_id: config.clientId,
|
client_id: config.clientId,
|
||||||
|
|||||||
@@ -151,6 +151,12 @@ export const english: Record<string, string> = {
|
|||||||
应用凭据: 'application credentials',
|
应用凭据: 'application credentials',
|
||||||
'应用凭据和 %s 权限': 'application credentials and %s permission',
|
'应用凭据和 %s 权限': 'application credentials and %s permission',
|
||||||
未知: 'unknown',
|
未知: 'unknown',
|
||||||
|
'请检查%s。': 'Check %s.',
|
||||||
|
'资源冲突,请检查重复的名称或值。': 'Resource conflict; check for duplicate names or values.',
|
||||||
|
'服务端错误,请检查服务状态和日志。': 'Server error; check service status and logs.',
|
||||||
|
'请求未成功,请检查请求参数和服务日志。': 'Request unsuccessful; check request parameters and service logs.',
|
||||||
|
'API 请求失败(%s %s)。%s%s': 'API request failed (%s %s). %s%s',
|
||||||
|
|
||||||
' 执行结果可能未知,请先检查%s状态再考虑重试。':
|
' 执行结果可能未知,请先检查%s状态再考虑重试。':
|
||||||
' Execution outcome may be unknown; check %s status before retrying.',
|
' Execution outcome may be unknown; check %s status before retrying.',
|
||||||
'API 请求被拒绝(HTTP %s),请检查%s。%s':
|
'API 请求被拒绝(HTTP %s),请检查%s。%s':
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ test('API diagnostics preserve resource scope, uncertainty, codes and secret sup
|
|||||||
language === 'en' ? /outcome.*unknown/ : /结果.*未知/,
|
language === 'en' ? /outcome.*unknown/ : /结果.*未知/,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (failure !== 'network') {
|
if (failure === 'permission' || failure === 'api') {
|
||||||
assert.ok(
|
assert.ok(
|
||||||
error.message.includes(
|
error.message.includes(
|
||||||
endpoint.startsWith('subscriptions')
|
endpoint.startsWith('subscriptions')
|
||||||
@@ -89,3 +89,54 @@ test('API diagnostics preserve resource scope, uncertainty, codes and secret sup
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('HTTP and body errors distinguish conflicts, authentication and server failures without leaking bodies', async (t) => {
|
||||||
|
const previous = process.env.QL_LANG;
|
||||||
|
t.after(() => {
|
||||||
|
if (previous === undefined) delete process.env.QL_LANG;
|
||||||
|
else process.env.QL_LANG = previous;
|
||||||
|
});
|
||||||
|
for (const language of ['en', 'zh']) {
|
||||||
|
process.env.QL_LANG = language;
|
||||||
|
for (const kind of ['HTTP', 'code'])
|
||||||
|
for (const status of [400, 401, 403, 409, 500, 503])
|
||||||
|
for (const method of ['GET', 'PUT']) {
|
||||||
|
t.mock.method(
|
||||||
|
global,
|
||||||
|
'fetch',
|
||||||
|
async () =>
|
||||||
|
new Response(
|
||||||
|
JSON.stringify({ code: status, message: 'secret-value' }),
|
||||||
|
{ status: kind === 'HTTP' ? status : 200 },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await assert.rejects(
|
||||||
|
request(
|
||||||
|
{ url: 'https://fixture.invalid', token: 'secret-token' },
|
||||||
|
'envs',
|
||||||
|
{ method },
|
||||||
|
),
|
||||||
|
(error) => {
|
||||||
|
assert.equal(error.exitCode, [401, 403].includes(status) ? 3 : 1);
|
||||||
|
assert.match(error.message, new RegExp(`${kind} ${status}`));
|
||||||
|
assert.doesNotMatch(error.message, /secret-|fixture/);
|
||||||
|
if ([401, 403].includes(status))
|
||||||
|
assert.match(error.message, /credentials|凭据/);
|
||||||
|
else
|
||||||
|
assert.doesNotMatch(
|
||||||
|
error.message,
|
||||||
|
/credentials|permission|凭据|权限/,
|
||||||
|
);
|
||||||
|
if (status === 409) assert.match(error.message, /conflict|冲突/);
|
||||||
|
if (status >= 500)
|
||||||
|
assert.match(error.message, /Server error|服务端错误/);
|
||||||
|
if (status >= 500 && method === 'PUT')
|
||||||
|
assert.match(error.message, /unknown|未知/);
|
||||||
|
else assert.doesNotMatch(error.message, /unknown|未知/);
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
t.mock.restoreAll();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { Sequelize, DataTypes } = require('sequelize');
|
||||||
|
const i18n = require.resolve('../../back/shared/i18n');
|
||||||
|
require.cache[i18n] = {
|
||||||
|
id: i18n,
|
||||||
|
filename: i18n,
|
||||||
|
loaded: true,
|
||||||
|
exports: { t: (x) => x },
|
||||||
|
};
|
||||||
|
const handler = require('../../back/middlewares/uniqueConstraintError').default;
|
||||||
|
|
||||||
|
test('database uniqueness conflicts return 409 without values and preserve existing rows', async () => {
|
||||||
|
const db = new Sequelize('sqlite::memory:', { logging: false });
|
||||||
|
try {
|
||||||
|
const App = db.define('App', {
|
||||||
|
name: { type: DataTypes.STRING, unique: true },
|
||||||
|
});
|
||||||
|
const Env = db.define('Env', {
|
||||||
|
name: { type: DataTypes.STRING, unique: 'pair' },
|
||||||
|
value: { type: DataTypes.STRING, unique: 'pair' },
|
||||||
|
});
|
||||||
|
await db.sync();
|
||||||
|
const first = await App.create({ name: 'private-app' });
|
||||||
|
const second = await App.create({ name: 'other' });
|
||||||
|
await Env.create({ name: 'TOKEN', value: 'private-value' });
|
||||||
|
const env = await Env.create({ name: 'TOKEN', value: 'other-value' });
|
||||||
|
for (const write of [
|
||||||
|
() => App.create({ name: first.name }),
|
||||||
|
() => second.update({ name: first.name }),
|
||||||
|
() => env.update({ value: 'private-value' }),
|
||||||
|
]) {
|
||||||
|
await assert.rejects(write, (err) => {
|
||||||
|
let status, body;
|
||||||
|
handler(
|
||||||
|
err,
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
status: (x) => {
|
||||||
|
status = x;
|
||||||
|
return {
|
||||||
|
json: (x) => {
|
||||||
|
body = x;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
() => assert.fail('constraint passed through'),
|
||||||
|
);
|
||||||
|
assert.equal(status, 409);
|
||||||
|
assert.equal(body.code, 409);
|
||||||
|
assert.doesNotMatch(
|
||||||
|
JSON.stringify(body),
|
||||||
|
/private-|TOKEN|INSERT|UPDATE/,
|
||||||
|
);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
assert.equal((await second.reload()).name, 'other');
|
||||||
|
assert.equal((await env.reload()).value, 'other-value');
|
||||||
|
const writes = await Promise.allSettled([
|
||||||
|
App.create({ name: 'race' }),
|
||||||
|
App.create({ name: 'race' }),
|
||||||
|
]);
|
||||||
|
assert.equal(writes.filter((x) => x.status === 'fulfilled').length, 1);
|
||||||
|
assert.equal(await App.count({ where: { name: 'race' } }), 1);
|
||||||
|
const unrelated = new Error('unrelated');
|
||||||
|
handler(unrelated, {}, {}, (err) => assert.equal(err, unrelated));
|
||||||
|
} finally {
|
||||||
|
await db.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user