From 75cacf4aaade1e2fdf99e121d03c58541a8aaeda Mon Sep 17 00:00:00 2001 From: Gergo Magyar Date: Sun, 1 Nov 2026 18:05:59 +0000 Subject: [PATCH] fix(config): validate types and label errors Refs #3750 --- gitnexus/src/cli/analyze-config.ts | 45 ++++++++++--------- .../ingestion/languages/go/route-config.ts | 33 ++++++++++++++ gitnexus/test/unit/analyze-config.test.ts | 27 +++++++++++ 3 files changed, 84 insertions(+), 21 deletions(-) diff --git a/gitnexus/src/cli/analyze-config.ts b/gitnexus/src/cli/analyze-config.ts index 7bef7fa6d..45c4b2a2a 100644 --- a/gitnexus/src/cli/analyze-config.ts +++ b/gitnexus/src/cli/analyze-config.ts @@ -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, - { allowNestedKey }: { allowNestedKey: boolean }, + { allowNestedKey, source }: { allowNestedKey: boolean; source: string }, ): Partial => { const out: Partial = {}; const setBy = new Map(); @@ -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)[spec.target] = normalizeValue(spec.kind, value, key); + (out as Record)[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; - 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 { +function parseAnalyzeConfig( + rawInput: string, + source = GITNEXUS_RC_FILENAME, +): Partial { 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 { 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; - const flat = normalizeLevel(obj, { allowNestedKey: true }); + const flat = normalizeLevel(obj, { allowNestedKey: true, source }); let nested: Partial = {}; 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, { allowNestedKey: false }); + nested = normalizeLevel(nestedRaw as Record, { + allowNestedKey: false, + source, + }); } // Nested `analyze` block overrides flat top-level keys for the same option. diff --git a/gitnexus/src/core/ingestion/languages/go/route-config.ts b/gitnexus/src/core/ingestion/languages/go/route-config.ts index bbca2ea9c..e2b5c77b4 100644 --- a/gitnexus/src/core/ingestion/languages/go/route-config.ts +++ b/gitnexus/src/core/ingestion/languages/go/route-config.ts @@ -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".`); diff --git a/gitnexus/test/unit/analyze-config.test.ts b/gitnexus/test/unit/analyze-config.test.ts index 7ddad8266..240e18f70 100644 --- a/gitnexus/test/unit/analyze-config.test.ts +++ b/gitnexus/test/unit/analyze-config.test.ts @@ -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/);