diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b77189..7723960 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,8 @@ backward compatible. ### Fixed +- **`vg scan` reports the installed version of a Terraform registry module.** `terraform init` and `tofu init` record each module they install in `.terraform/modules/modules.json`. When that file sits next to the configuration that calls a registry module, its `Version` is the row's `resolvedVersion`, and drift is computed from it rather than from the lowest version the constraint allows. Each root reads its own file, so `envs/staging` and `envs/prod` can resolve differently. Modules called from inside other modules are not matched, and a source installed at two versions in one root stays unresolved. A missing or malformed file leaves the row unchanged (#621). + - **`vg scan` reports a .NET runtime inherited from `Directory.Build.props`.** A project that sets neither `TargetFramework` nor `TargetFrameworks` takes them from the nearest `Directory.Build.props` between that project and the scanned directory. A value in the project file wins. A value that contains `$(`, such as `$(DefaultTfm)`, is not reported as a runtime (#627). - **`vg scan` reads OpenTofu `.tofu` files for provider and module drift.** `required_providers`, `required_version`, and registry `module` blocks in a `.tofu` file are scored, including a tree that has no `.tf` file. When `x.tf` and `x.tofu` are in the same directory, only `x.tofu` is read. A `.tf` file with no `.tofu` sibling is unchanged. The file list used when there is no file index also includes `terraform.tf` and the `.tofu` names of the usual root files (#622). diff --git a/DOCS.md b/DOCS.md index 78f54dc..de3739f 100644 --- a/DOCS.md +++ b/DOCS.md @@ -277,6 +277,8 @@ vg drift Reads each project's lockfile and reports which dependencies have drifted behind their latest known version. Offline by default (uses the last-known catalog); add `--online` to check live registries for current latest versions. +For Terraform, a provider's exact version comes from `.terraform.lock.hcl`, and a registry module's installed version comes from `.terraform/modules/modules.json`, which `terraform init` or `tofu init` writes next to the files that call the module. A missing or unreadable file leaves the declared constraint in place. + | Flag | Description | |------|-------------| | `--online` | Check live registries for the latest versions instead of the offline catalog | diff --git a/src/core-open/scanners/terraform-scanner.ts b/src/core-open/scanners/terraform-scanner.ts index 5525d95..a2fecf1 100644 --- a/src/core-open/scanners/terraform-scanner.ts +++ b/src/core-open/scanners/terraform-scanner.ts @@ -17,6 +17,8 @@ interface TerraformProvider { interface TerraformModule { source: string; // e.g., "terraform-aws-modules/vpc/aws" version?: string; + /** Directory of the file that declares the module block. */ + dir?: string; } /** @@ -339,6 +341,46 @@ async function parseTerraformLock(filePath: string, cache?: FileCache): Promise< return resolved; } +/** + * Installed registry module versions from `.terraform/modules/modules.json`, + * which `terraform init` / `tofu init` writes in the root it ran in. Keyed by + * the normalised registry address. Only the root's own module calls count + * (a `Key` with no `.`): nested calls such as `vpc.endpoints` belong to other + * modules. An address installed at two different versions in one root is left + * out, since the source alone can't say which call is which. + */ +async function parseTerraformModules(filePath: string, cache?: FileCache): Promise> { + const versions = new Map>(); + + try { + const content = cache + ? await cache.readTextFile(filePath) + : await readTextFile(filePath); + const parsed = JSON.parse(content) as { Modules?: unknown } | null; + const modules = Array.isArray(parsed?.Modules) ? parsed.Modules : []; + + for (const entry of modules) { + if (!entry || typeof entry !== 'object') continue; + const { Key, Source, Version } = entry as { Key?: unknown; Source?: unknown; Version?: unknown }; + if (typeof Key !== 'string' || Key === '' || Key.includes('.')) continue; + if (typeof Source !== 'string' || typeof Version !== 'string' || Version.length === 0) continue; + const address = publicRegistryModuleAddress(Source); + if (!address) continue; + const seen = versions.get(address) ?? new Set(); + seen.add(Version); + versions.set(address, seen); + } + } catch { + return new Map(); + } + + const resolved = new Map(); + for (const [address, seen] of versions) { + if (seen.size === 1) resolved.set(address, [...seen][0]); + } + return resolved; +} + /** * Calculate version drift. */ @@ -467,7 +509,8 @@ export async function scanTerraform( } allProviders.push(...providers); - allModules.push(...modules); + const dir = path.dirname(tfFile); + allModules.push(...modules.map((m) => ({ ...m, dir }))); } // A provider requirement is one constraint per source. Terraform rejects @@ -490,7 +533,7 @@ export async function scanTerraform( for (const m of allModules) { const key = `${m.source}\0${m.version ?? ''}`; if (!uniqueModules.has(key)) { - uniqueModules.set(key, { source: m.source, version: m.version }); + uniqueModules.set(key, { source: m.source, version: m.version, dir: m.dir }); } } const modulePins = [...uniqueModules.values()].sort((a, b) => { @@ -506,6 +549,15 @@ export async function scanTerraform( // Read lock file for exact versions const lockPath = `${projectPath}/.terraform.lock.hcl`; const resolvedVersions = await parseTerraformLock(lockPath, cache); + // Each root keeps its own modules.json, next to the files that call the + // modules (envs/staging and envs/prod install separately). + const installedModules = new Map>(); + for (const dir of new Set(modulePins.map((pin) => pin.dir ?? projectPath))) { + installedModules.set( + dir, + await parseTerraformModules(path.join(dir, '.terraform', 'modules', 'modules.json'), cache), + ); + } // Prepare items to fetch const itemsToFetch: Array<{ type: 'provider' | 'module'; namespace: string; name: string; provider?: string }> = []; @@ -569,12 +621,15 @@ export async function scanTerraform( else buckets.unknown++; } - for (const { source, version: constraintVersion } of modulePins) { - const currentVersion = constraintVersion || 'unknown'; + for (const { source, version: constraintVersion, dir } of modulePins) { // The version map is keyed by `namespace/name/system`. The row name stays // the raw source, so a subdir and a public-registry prefix still show up // as distinct pins while sharing the fetched latest version. const address = publicRegistryModuleAddress(source); + const resolvedVersion = address + ? installedModules.get(dir ?? projectPath)?.get(address) + : undefined; + const currentVersion = resolvedVersion || constraintVersion || 'unknown'; const latestVersion = address ? latestVersions.get(address) : undefined; const drift = (latestVersion && currentVersion !== 'unknown') ? calculateDrift(currentVersion, latestVersion) : 'unknown'; @@ -594,7 +649,7 @@ export async function scanTerraform( package: `module:${source}`, section: 'dependencies', currentSpec: constraintVersion || 'unknown', - resolvedVersion: null, + resolvedVersion: resolvedVersion || null, latestStable: latestVersion || null, majorsBehind, drift, diff --git a/test/terraform-scanner.test.ts b/test/terraform-scanner.test.ts index 41d34e4..4fae2d4 100644 --- a/test/terraform-scanner.test.ts +++ b/test/terraform-scanner.test.ts @@ -115,6 +115,171 @@ describe('scanTerraform module pins', () => { }); }); +function modulesJson(entries: Array<{ Key?: string; Source: string; Version: string }>): string { + return JSON.stringify({ + Modules: [ + { Key: '', Source: '', Dir: '.' }, + ...entries.map((entry, index) => ({ + Key: entry.Key ?? `m${index}`, + Source: entry.Source, + Version: entry.Version, + Dir: `.terraform/modules/${entry.Key ?? `m${index}`}`, + })), + ], + }); +} + +describe('scanTerraform module resolved versions', () => { + const modulesPath = '.terraform/modules/modules.json'; + + it('reports the installed version from modules.json for a matching registry module', async () => { + const dir = await writeTree({ + 'main.tf': moduleBlock('vpc', 'terraform-aws-modules/vpc/aws', '~> 5.0'), + [modulesPath]: modulesJson([ + { Source: 'registry.terraform.io/terraform-aws-modules/vpc/aws', Version: '5.8.1' }, + ]), + }); + + const scan = await scanTerraform(dir, new FileCache(), manifest, true); + const modules = scan!.dependencies.filter((row) => row.package.startsWith('module:')); + expect(modules).toEqual([ + expect.objectContaining({ + package: 'module:terraform-aws-modules/vpc/aws', + currentSpec: '~> 5.0', + resolvedVersion: '5.8.1', + latestStable: '5.8.1', + drift: 'current', + majorsBehind: 0, + }), + ]); + }); + + it('leaves module rows unchanged when modules.json is absent', async () => { + const dir = await writeTree({ + 'main.tf': moduleBlock('vpc', 'terraform-aws-modules/vpc/aws', '~> 5.0'), + }); + + const scan = await scanTerraform(dir, new FileCache(), manifest, true); + const modules = scan!.dependencies.filter((row) => row.package.startsWith('module:')); + expect(modules).toEqual([ + expect.objectContaining({ + package: 'module:terraform-aws-modules/vpc/aws', + currentSpec: '~> 5.0', + resolvedVersion: null, + latestStable: '5.8.1', + drift: 'minor-behind', + majorsBehind: 0, + }), + ]); + }); + + it('falls back without throwing when modules.json is malformed', async () => { + const dir = await writeTree({ + 'main.tf': moduleBlock('vpc', 'terraform-aws-modules/vpc/aws', '~> 5.0'), + [modulesPath]: '{ "Modules": [', + }); + + for (const cache of [new FileCache(), undefined]) { + const scan = await scanTerraform(dir, cache, manifest, true); + const modules = scan!.dependencies.filter((row) => row.package.startsWith('module:')); + expect(modules).toEqual([ + expect.objectContaining({ + package: 'module:terraform-aws-modules/vpc/aws', + currentSpec: '~> 5.0', + resolvedVersion: null, + drift: 'minor-behind', + }), + ]); + } + }); + + it('does not use a modules.json version recorded for a different module', async () => { + const dir = await writeTree({ + 'main.tf': moduleBlock('vpc', 'terraform-aws-modules/vpc/aws', '~> 5.0'), + [modulesPath]: modulesJson([ + { Source: 'registry.terraform.io/terraform-aws-modules/eks/aws', Version: '20.0.0' }, + ]), + }); + + const scan = await scanTerraform(dir, new FileCache(), manifest, true); + const modules = scan!.dependencies.filter((row) => row.package.startsWith('module:')); + expect(modules).toEqual([ + expect.objectContaining({ + package: 'module:terraform-aws-modules/vpc/aws', + currentSpec: '~> 5.0', + resolvedVersion: null, + drift: 'minor-behind', + }), + ]); + }); + + it('reads the modules.json in each root', async () => { + const dir = await writeTree({ + 'envs/staging/main.tf': moduleBlock('vpc', 'terraform-aws-modules/vpc/aws', '~> 4.0'), + [`envs/staging/${modulesPath}`]: modulesJson([ + { Source: 'registry.terraform.io/terraform-aws-modules/vpc/aws', Version: '4.0.2' }, + ]), + 'envs/prod/main.tf': moduleBlock('vpc', 'terraform-aws-modules/vpc/aws', '~> 5.0'), + [`envs/prod/${modulesPath}`]: modulesJson([ + { Source: 'registry.terraform.io/terraform-aws-modules/vpc/aws', Version: '5.8.1' }, + ]), + }); + + const scan = await scanTerraform(dir, new FileCache(), manifest, true); + const modules = scan!.dependencies.filter((row) => row.package.startsWith('module:')); + expect(modules.map((row) => [row.currentSpec, row.resolvedVersion])).toEqual([ + ['~> 4.0', '4.0.2'], + ['~> 5.0', '5.8.1'], + ]); + }); + + it('does not apply a modules.json from another root', async () => { + const dir = await writeTree({ + 'main.tf': moduleBlock('vpc', 'terraform-aws-modules/vpc/aws', '~> 5.0'), + [modulesPath]: modulesJson([ + { Source: 'registry.terraform.io/terraform-aws-modules/vpc/aws', Version: '5.8.1' }, + ]), + 'envs/staging/main.tf': moduleBlock('vpc', 'terraform-aws-modules/vpc/aws', '~> 4.0'), + }); + + const scan = await scanTerraform(dir, new FileCache(), manifest, true); + const modules = scan!.dependencies.filter((row) => row.package.startsWith('module:')); + expect(modules.map((row) => [row.currentSpec, row.resolvedVersion])).toEqual([ + ['~> 4.0', null], + ['~> 5.0', '5.8.1'], + ]); + }); + + it('ignores modules.json entries for calls nested inside other modules', async () => { + const dir = await writeTree({ + 'main.tf': moduleBlock('vpc', 'terraform-aws-modules/vpc/aws', '~> 5.0'), + [modulesPath]: modulesJson([ + { Key: 'network.vpc', Source: 'registry.terraform.io/terraform-aws-modules/vpc/aws', Version: '5.1.0' }, + ]), + }); + + const scan = await scanTerraform(dir, new FileCache(), manifest, true); + const row = scan!.dependencies.find((r) => r.package === 'module:terraform-aws-modules/vpc/aws'); + expect(row?.resolvedVersion).toBeNull(); + }); + + it('leaves a source installed at two versions in one root unresolved', async () => { + const dir = await writeTree({ + 'main.tf': + moduleBlock('vpc_a', 'terraform-aws-modules/vpc/aws', '~> 5.0') + + moduleBlock('vpc_b', 'terraform-aws-modules/vpc/aws', '~> 4.0'), + [modulesPath]: modulesJson([ + { Key: 'vpc_a', Source: 'registry.terraform.io/terraform-aws-modules/vpc/aws', Version: '5.8.1' }, + { Key: 'vpc_b', Source: 'registry.terraform.io/terraform-aws-modules/vpc/aws', Version: '4.0.2' }, + ]), + }); + + const scan = await scanTerraform(dir, new FileCache(), manifest, true); + const modules = scan!.dependencies.filter((row) => row.package.startsWith('module:')); + expect(modules.map((row) => row.resolvedVersion)).toEqual([null, null]); + }); +}); + function terraformBlock(body: string): string { return `terraform {\n${body}\n}\n`; }