fix(config): validate types and label errors

Refs #3750
This commit is contained in:
Gergo Magyar 2026-11-01 18:05:59 +00:00
parent 6beba7aee7
commit 75cacf4aaa
3 changed files with 84 additions and 21 deletions

View file

@ -188,8 +188,13 @@ export function validateBranchName(value: string, source: string): string {
}
}
const normalizeValue = (kind: ValueKind, value: unknown, key: string): unknown => {
const source = `${GITNEXUS_RC_FILENAME} "${key}"`;
const normalizeValue = (
kind: ValueKind,
value: unknown,
key: string,
configSource: string,
): unknown => {
const source = `${configSource} "${key}"`;
switch (kind) {
case 'boolean':
if (typeof value !== 'boolean') {
@ -330,7 +335,7 @@ const normalizeValue = (kind: ValueKind, value: unknown, key: string): unknown =
*/
const normalizeLevel = (
obj: Record<string, unknown>,
{ allowNestedKey }: { allowNestedKey: boolean },
{ allowNestedKey, source }: { allowNestedKey: boolean; source: string },
): Partial<AnalyzeOptions> => {
const out: Partial<AnalyzeOptions> = {};
const setBy = new Map<keyof AnalyzeOptions, string>();
@ -342,19 +347,17 @@ const normalizeLevel = (
// truthy) and would slip past `if (!spec)`, hitting the wrong error branch
// instead of the documented "Unknown key" message (#1996 tri-review P3).
if (!Object.hasOwn(KEY_SPECS, key)) {
throw new GitNexusRcError(
`Unknown key "${key}" in ${GITNEXUS_RC_FILENAME}. ${ALLOWED_KEYS_HINT}`,
);
throw new GitNexusRcError(`Unknown key "${key}" in ${source}. ${ALLOWED_KEYS_HINT}`);
}
const spec = KEY_SPECS[key];
const prev = setBy.get(spec.target);
if (prev && prev !== key) {
throw new GitNexusRcError(
`${GITNEXUS_RC_FILENAME}: "${prev}" and "${key}" both configure the same option; set only one.`,
`${source}: "${prev}" and "${key}" both configure the same option; set only one.`,
);
}
setBy.set(spec.target, key);
(out as Record<string, unknown>)[spec.target] = normalizeValue(spec.kind, value, key);
(out as Record<string, unknown>)[spec.target] = normalizeValue(spec.kind, value, key, source);
}
return out;
@ -447,13 +450,7 @@ function withEnvConfig(
} catch (err) {
throw new GitNexusRcError(`Could not read ${label}: ${(err as Error).message}`);
}
let envConfig: Partial<AnalyzeOptions>;
try {
envConfig = parseAnalyzeConfig(raw);
} catch (err) {
if (err instanceof GitNexusRcError) throw new GitNexusRcError(`${label}: ${err.message}`);
throw err;
}
const envConfig = parseAnalyzeConfig(raw, label);
logger.debug(
{ file: envPath, keys: Object.keys(envConfig), repoKeys: Object.keys(repoConfig ?? {}) },
'analyze config: applied GITNEXUS_RC over .gitnexusrc',
@ -461,7 +458,10 @@ function withEnvConfig(
return { ...repoConfig, ...envConfig };
}
function parseAnalyzeConfig(rawInput: string): Partial<AnalyzeOptions> {
function parseAnalyzeConfig(
rawInput: string,
source = GITNEXUS_RC_FILENAME,
): Partial<AnalyzeOptions> {
let raw = rawInput;
// Strip a leading UTF-8 BOM: Node's 'utf-8' decode keeps it, and JSON.parse
@ -475,25 +475,28 @@ function parseAnalyzeConfig(rawInput: string): Partial<AnalyzeOptions> {
parsed = JSON.parse(raw);
} catch (err) {
throw new GitNexusRcError(
`${GITNEXUS_RC_FILENAME} is not valid JSON: ${(err as Error).message}. ` +
`${source} is not valid JSON: ${(err as Error).message}. ` +
`Expected a JSON object such as {"defaultBranch": "develop", "skipContextFiles": true}.`,
);
}
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new GitNexusRcError(`${GITNEXUS_RC_FILENAME} must contain a JSON object.`);
throw new GitNexusRcError(`${source} must contain a JSON object.`);
}
const obj = parsed as Record<string, unknown>;
const flat = normalizeLevel(obj, { allowNestedKey: true });
const flat = normalizeLevel(obj, { allowNestedKey: true, source });
let nested: Partial<AnalyzeOptions> = {};
if (Object.prototype.hasOwnProperty.call(obj, NESTED_KEY)) {
const nestedRaw = obj[NESTED_KEY];
if (nestedRaw === null || typeof nestedRaw !== 'object' || Array.isArray(nestedRaw)) {
throw new GitNexusRcError(`${GITNEXUS_RC_FILENAME} "${NESTED_KEY}" must be a JSON object.`);
throw new GitNexusRcError(`${source} "${NESTED_KEY}" must be a JSON object.`);
}
nested = normalizeLevel(nestedRaw as Record<string, unknown>, { allowNestedKey: false });
nested = normalizeLevel(nestedRaw as Record<string, unknown>, {
allowNestedKey: false,
source,
});
}
// Nested `analyze` block overrides flat top-level keys for the same option.

View file

@ -2,6 +2,34 @@ import type { RouteFrameworkAlias } from '../../language-provider.js';
import { goRouteFramework } from '../../route-extractors/go-gin-echo.js';
const FIELDS = new Set(['importPath', 'type', 'framework']);
// https://go.dev/ref/spec#Keywords — these cannot name a type declaration.
const GO_KEYWORDS = new Set([
'break',
'case',
'chan',
'const',
'continue',
'default',
'defer',
'else',
'fallthrough',
'for',
'func',
'go',
'goto',
'if',
'import',
'interface',
'map',
'package',
'range',
'return',
'select',
'struct',
'switch',
'type',
'var',
]);
/** Upper bound on declared aliases; a longer list is rejected, never truncated. */
export const MAX_ROUTER_ALIASES = 100;
@ -42,6 +70,11 @@ export function normalizeRouterAliases(value: unknown, source: string): RouteFra
'must be a Go import path (e.g. "example.com/org/pkg")',
);
const type = field('type', /^[A-Za-z_][A-Za-z0-9_]*$/, 'must be a Go type name');
if (type === '_' || GO_KEYWORDS.has(type)) {
throw new Error(
`${source} entry field "type" must be a Go type name, not a keyword or blank identifier.`,
);
}
const framework = field('framework', /^[a-z]+$/, 'must be "gin" or "echo"');
if (!goRouteFramework(framework)) {
throw new Error(`${source} entry field "framework" must be "gin" or "echo".`);

View file

@ -329,6 +329,13 @@ describe('analyze-config (.gitnexusrc support, #243)', () => {
expect(() => loadAnalyzeConfig(dir)).toThrow(message);
});
it.each(['func', 'type', 'return', '_'])('rejects unusable Go alias type %s', async (type) => {
await writeRc(
JSON.stringify({ goRouterAliases: [{ importPath: CORE, type, framework: 'gin' }] }),
);
expect(() => loadAnalyzeConfig(dir)).toThrow(/must be a Go type name/);
});
it('rejects more router aliases than the cap instead of truncating', async () => {
const alias = (i: number) => ({ importPath: `${CORE}${i}`, type: 'Engine', framework: 'gin' });
await writeRc(
@ -389,6 +396,26 @@ describe('analyze-config (.gitnexusrc support, #243)', () => {
expect(() => loadAnalyzeConfig(dir)).toThrow(/GITNEXUS_RC file .*non-empty array/);
});
it.each([
['invalid JSON', '{'],
['non-object', '[]'],
['unknown key', '{"unknownOption": true}'],
['conflicting keys', '{"skipSkills": true, "skip-skills": false}'],
['invalid value', '{"skipSkills": "yes"}'],
['invalid nested block', '{"analyze": []}'],
['invalid nested value', '{"analyze": {"goRouterAliases": "gin"}}'],
])('names only the external file for %s errors', async (_name, raw) => {
const file = await writeEnvRc({});
await fs.writeFile(file, raw);
const expected = expect.objectContaining({
message: expect.stringContaining(`GITNEXUS_RC file "${file}"`),
});
expect(() => loadAnalyzeConfig(dir)).toThrow(expected);
expect(() => loadAnalyzeConfig(dir)).not.toThrow(/\.gitnexusrc/);
await expect(loadAnalyzeConfigStrict(dir)).rejects.toThrow(expected);
await expect(loadAnalyzeConfigStrict(dir)).rejects.not.toThrow(/\.gitnexusrc/);
});
it('rejects a directory and an oversized file', async () => {
process.env.GITNEXUS_RC = outside;
expect(() => loadAnalyzeConfig(dir)).toThrow(/not a regular file/);