Skip to content

Commit 254e011

Browse files
jfblaaclaude
andauthored
feat(manifest): generate Socket facts for .NET solutions and projects (#1678)
* feat(manifest): generate Socket facts for .NET solutions and projects `socket manifest dotnet` writes `<entry>.socket.facts.json` per solution, plus one per project no solution builds, from the user's own `dotnet restore`: a bundled C# tool evaluates projects in-process on the selected SDK (MSBuildLocator) and reads project.assets.json with NuGet's own API. PackageReference (central package management, lock files, multi-targeting, runtime targets) and packages.config are supported, for C#, F# and VB. --auto-manifest, `socket manifest auto`, dynamic SBOM inference and the setup wizards detect .NET builds and skip them with a warning where no .NET SDK runs. --reach sidecars carry each project's compiler inputs per target framework from a design-time build, and scan and fix pass Coana --use-only-socket-facts-artifacts when NuGet facts are present. Resolution, restore and design-time build failures fail closed. * fix(manifest): address .NET facts review feedback - Honour --include-configs/--exclude-configs in the per-framework build context the sidecar carries, for single- and multi-targeting projects. - After a failed restore, treat a project.nuget.cache older than the restore as not restored: NuGet leaves an up-to-date project's cache untouched, so it cannot tell such a project from one the restore never reached. - Keep the coverage rule in one isRootCovered, cache solution member listings, and probe the SDK once per global.json. - Build every script's options from one list, type the per-build projectInfo records, and drop dead fields and parameters. - Classify NuGet failures by error code only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(manifest): pin patched System.Text.Json and System.Formats.Asn1 The .NET tool's compile-time closure resolved System.Text.Json 6.0.0 (CVE-2024-43485) and System.Formats.Asn1 5.0.0 (CVE-2024-38095). Neither ships, since the shared framework supplies both at run time, but the lock file still carried them. Reference the patched versions compile-only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(manifest): simplify .NET facts generation - Share the per-root build step (coverage check, run, covered files) between the recursive generator and `manifest dotnet`, which now takes the ecosystem config whole and starts from resolveEcosystemConfig. - Keep covered build files per tool, so JVM coverage no longer makes every solution list its members. - Keep only Coana's flags and the sidecar path for `socket fix`, not the parsed sidecar. - Carry a root's target framework as one optional field; reuse the build and root nodes when assembling per-framework sidecar data. - Add getOrInsert, ManifestDefaults and wizard answer helpers. - C# tool: nullable restore exit code, Failure's default project key, one unscannable exit in ReadAssets, ShortFrameworkName(ProjectInstance). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 319db5e commit 254e011

44 files changed

Lines changed: 3761 additions & 382 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.config/rollup.dist.config.mjs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,20 @@ async function copyManifestScripts() {
131131
path.join(destDir, 'socket-workspaces.plugin.scala'),
132132
),
133133
])
134+
// The dotnet tool's publish output (scripts/dotnet-tool/build-tool.sh),
135+
// like the Maven jar absent from a fresh checkout.
136+
const dotnetToolDir = path.join(srcDir, 'dotnet-tool', 'publish')
137+
if (existsSync(path.join(dotnetToolDir, 'socket-facts-dotnet.dll'))) {
138+
await fs.cp(dotnetToolDir, path.join(destDir, 'dotnet-tool'), {
139+
recursive: true,
140+
})
141+
} else if (constants.ENV[INLINED_SOCKET_CLI_PUBLISHED_BUILD]) {
142+
throw new Error(
143+
'dotnet manifest tool not found at ' +
144+
dotnetToolDir +
145+
' for a published build. Build it first: pnpm run build:dotnet-tool',
146+
)
147+
}
134148
const jarPath = path.join(
135149
srcDir,
136150
'maven-extension',

‎.github/workflows/publish-npm.yml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,12 @@ jobs:
386386
fi
387387
bash src/commands/manifest/scripts/maven-extension/build-jar.sh
388388
389+
# Same for the dotnet manifest tool: built here, bundled into
390+
# dist/manifest-scripts, never committed. The runner image's preinstalled
391+
# .NET SDK builds it (actions/setup-dotnet is not on the org allowlist).
392+
- name: Build dotnet manifest tool
393+
run: bash src/commands/manifest/scripts/dotnet-tool/build-tool.sh
394+
389395
# PACK ONCE, PUBLISH THOSE BYTES. Each variant is built, packed to a
390396
# tarball, and smoke-tested from that tarball; the three tarballs are
391397
# uploaded as an artifact and the publish job stages those exact files.

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
66

77
## [Unreleased]
88

9+
### Added
10+
- `socket manifest dotnet` [beta] generates Socket facts files for .NET solutions and projects from your own `dotnet restore`, covering PackageReference (central package management and lock files included) and packages.config projects.
11+
- `socket manifest auto`, `socket manifest setup` and `--auto-manifest` now detect .NET solutions and projects, and skip them with a warning where no .NET SDK is installed.
12+
913
### Changed
1014
- Modules outside the scan root can no longer be excluded with `--exclude-paths`; `**/x` used to match a `../x` module by accident. Single-root runs whose Maven or Gradle options relocate the build root (`-f`, `-p`) now match patterns relative to the current directory, as documented.
1115

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
"build:dist": "pnpm build:dist:src && pnpm build:dist:types",
4040
"build:dist:src": "run-p -c clean:dist clean:external && dotenvx -q run -f .env.local -- rollup -c .config/rollup.dist.config.mjs",
4141
"build:dist:types": "pnpm clean:dist:types && tsgo --project tsconfig.dts.json",
42+
"build:dotnet-tool": "bash src/commands/manifest/scripts/dotnet-tool/build-tool.sh",
4243
"build:maven-extension": "bash src/commands/manifest/scripts/maven-extension/build-jar.sh",
4344
"build:sea": "node src/sea/build-sea.mts",
4445
"build:sea:internal:bootstrap": "rollup -c .config/rollup.sea.config.mjs",

‎src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ describe('socket fix --dynamic-sbom-inference', () => {
123123
}
124124
const uploadManifestFiles = vi.fn()
125125
const generated = {
126+
artifactsFlags: ['--maven-use-only-socket-facts'],
126127
paths: [FACTS],
127128
sidecarFile: '/tmp/socket-fix-facts/sidecar.json',
128129
remove: vi.fn(),

‎src/commands/fix/coana-fix.mts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,7 @@ async function coanaFixWithFacts(
392392
if (!silence) {
393393
spinner?.stop()
394394
logger.info(
395-
'Generating Socket facts for Gradle, sbt and Maven builds ...',
395+
'Generating Socket facts for .NET, Gradle, sbt and Maven builds ...',
396396
)
397397
}
398398
factsSlot.generated = await generateSocketFactsForFix({
@@ -412,7 +412,7 @@ async function coanaFixWithFacts(
412412
// Discovery only needs which artifacts the facts files resolve. Applying
413413
// fixes reads each project's tree; a Coana predating facts trees can only
414414
// tell from the sidecar's classpaths which projects resolve an artifact.
415-
const discoveryFlags = factsSlot ? ['--maven-use-only-socket-facts'] : []
415+
const discoveryFlags = factsSlot?.generated?.artifactsFlags ?? []
416416
const factsFlags = [
417417
...discoveryFlags,
418418
...(sidecarFile ? ['--compute-artifacts-sidecar', sidecarFile] : []),

‎src/commands/fix/generated-socket-facts.mts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import { copyFile, mkdir, rm, writeFile } from 'node:fs/promises'
22
import path from 'node:path'
33

4+
import { useOnlySocketFactsArtifactsFlags } from '../manifest/scripts/sidecar.mts'
45
import { runDynamicSbomInference } from '../scan/run-dynamic-sbom-inference.mts'
56

67
export type GeneratedSocketFacts = {
8+
// Coana's flags selecting what the facts files resolve.
9+
artifactsFlags: string[]
710
paths: string[]
8-
// The facts files' per-project classpaths, outside the repository.
11+
// The facts files' per-project classpaths, written outside the repository.
912
sidecarFile: string | undefined
1013
remove: () => Promise<void>
1114
restore: () => Promise<void>
@@ -52,6 +55,7 @@ export async function generateSocketFactsForFix({
5255
)
5356
await restoreAll(originals)
5457
}
58+
let artifactsFlags: string[]
5559
let paths: string[]
5660
let sidecarFile: string | undefined
5761
try {
@@ -62,6 +66,7 @@ export async function generateSocketFactsForFix({
6266
sidecar: true,
6367
withFiles: false,
6468
})
69+
artifactsFlags = useOnlySocketFactsArtifactsFlags(resolvedPathsSidecar)
6570
paths = factsPaths.map(p => path.resolve(cwd, p))
6671
if (resolvedPathsSidecar) {
6772
sidecarFile = path.join(tmpDir, 'sidecar.json')
@@ -78,6 +83,7 @@ export async function generateSocketFactsForFix({
7883
...(await backUp(paths, path.join(tmpDir, 'generated'))),
7984
]
8085
return {
86+
artifactsFlags,
8187
paths,
8288
sidecarFile,
8389
remove: () => reset(paths),

‎src/commands/fix/generated-socket-facts.test.mts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,17 +65,21 @@ describe('generateSocketFactsForFix', () => {
6565
it('writes the sidecar outside the repository', async () => {
6666
mockRunDynamicSbomInference.mockImplementation(async () => {
6767
await fs.writeFile(fresh, 'generated')
68-
return { factsPaths: [fresh], resolvedPathsSidecar: { [fresh]: {} } }
68+
return {
69+
factsPaths: [fresh],
70+
resolvedPathsSidecar: { [fresh]: { components: [], projects: [] } },
71+
}
6972
})
7073

71-
const { sidecarFile } = await generate()
74+
const { artifactsFlags, sidecarFile } = await generate()
7275

7376
expect(mockRunDynamicSbomInference).toHaveBeenCalledWith(
7477
expect.objectContaining({ sidecar: true }),
7578
)
79+
expect(artifactsFlags).toEqual(['--maven-use-only-socket-facts'])
7680
expect(path.dirname(sidecarFile!)).toBe(tmpDir)
7781
expect(JSON.parse(await fs.readFile(sidecarFile!, 'utf8'))).toEqual({
78-
[fresh]: {},
82+
[fresh]: { components: [], projects: [] },
7983
})
8084
})
8185

Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
1+
import path from 'node:path'
2+
3+
import { debugFn } from '@socketsecurity/registry/lib/debug'
4+
import { safeStatsSync } from '@socketsecurity/registry/lib/fs'
5+
import { logger } from '@socketsecurity/registry/lib/logger'
6+
7+
import { convertDotnetToFacts } from './convert-dotnet-to-facts.mts'
8+
import { resolveEcosystemConfig } from './generate-recursive-manifests.mts'
9+
import { excludePathsFlag } from './manifest-flags.mts'
10+
import { parseBuildToolOpts } from './parse-build-tool-opts.mts'
11+
import constants, { SOCKET_JSON } from '../../constants.mts'
12+
import { commonFlags } from '../../flags.mts'
13+
import { checkCommandInput } from '../../utils/check-input.mts'
14+
import { cmdFlagValueToArray } from '../../utils/cmd.mts'
15+
import { getOutputKind } from '../../utils/get-output-kind.mts'
16+
import { meowOrExit } from '../../utils/meow-with-subcommands.mts'
17+
import { getFlagListOutput } from '../../utils/output-formatting.mts'
18+
import { readOrDefaultSocketJson } from '../../utils/socket-json.mts'
19+
import { camelToKebab } from '../../utils/strings.mts'
20+
import { assertValidExcludePaths } from '../scan/exclude-paths.mts'
21+
22+
import type {
23+
CliCommandConfig,
24+
CliCommandContext,
25+
} from '../../utils/meow-with-subcommands.mts'
26+
27+
const config: CliCommandConfig = {
28+
commandName: 'dotnet',
29+
description:
30+
'[beta] Generate Socket facts files from .NET solutions and projects',
31+
hidden: false,
32+
flags: {
33+
...commonFlags,
34+
bin: {
35+
type: 'string',
36+
description:
37+
'Location of the dotnet binary to use, default: dotnet on PATH',
38+
},
39+
dotnetOpts: {
40+
type: 'string',
41+
description:
42+
'Additional options to pass on to `dotnet restore`, e.g. `-p:Configuration=Release --configfile nuget.config`. MSBuild properties among them also apply to project evaluation',
43+
},
44+
includeConfigs: {
45+
type: 'string',
46+
description:
47+
'Comma-separated glob patterns matched against target frameworks (case-sensitive; `*`, `?`, and `[...]` wildcards). Only target frameworks matching at least one pattern are read, e.g. `net8.0`. A runtime-specific target (`net8.0/win-x64`) also matches its framework. Default: every target framework',
48+
},
49+
excludeConfigs: {
50+
type: 'string',
51+
description:
52+
'Comma-separated glob patterns; target frameworks matching any pattern are skipped (applied after --include-configs)',
53+
},
54+
...excludePathsFlag,
55+
ignoreUnresolved: {
56+
type: 'boolean',
57+
description:
58+
'Warn on unresolved dependencies instead of failing the run (unresolved deps are not emitted to the facts file)',
59+
},
60+
verbose: {
61+
type: 'boolean',
62+
description: 'Print debug messages',
63+
},
64+
},
65+
help: (command, config) => `
66+
Usage
67+
$ ${command} [options] [CWD=.|FILE]
68+
69+
Options
70+
${getFlagListOutput(config.flags)}
71+
72+
Emits a \`<file>.socket.facts.json\` per solution or project describing its
73+
resolved NuGet dependency graph. Given a directory, it builds every
74+
solution (.sln, .slnx) and project (.csproj, .fsproj, .vbproj) at its top
75+
level, solutions first, skipping projects a solution already covers; given
76+
a file, just that one (a .slnf solution filter too).
77+
78+
Dependencies come from your own \`dotnet restore\` (same SDK, global.json,
79+
nuget.config and credential providers), so a build that restores for you
80+
restores here. PackageReference projects (central package management and
81+
lock files included) and packages.config projects are supported. An
82+
unresolved dependency is a fatal error unless --ignore-unresolved.
83+
84+
Support is beta. Please report issues or give us feedback on what's missing.
85+
86+
Examples
87+
88+
$ ${command} .
89+
$ ${command} ./App.sln
90+
$ ${command} --dotnet-opts="-p:Configuration=Release" .
91+
`,
92+
}
93+
94+
export const cmdManifestDotnet = {
95+
description: config.description,
96+
hidden: config.hidden,
97+
run,
98+
}
99+
100+
async function run(
101+
argv: string[] | readonly string[],
102+
importMeta: ImportMeta,
103+
{ parentName }: CliCommandContext,
104+
): Promise<void> {
105+
const cli = meowOrExit({
106+
argv,
107+
config,
108+
importMeta,
109+
parentName,
110+
})
111+
112+
const { json = false, markdown = false } = cli.flags
113+
114+
const dryRun = !!cli.flags['dryRun']
115+
116+
const outputKind = getOutputKind(json, markdown)
117+
118+
const wasValidInput = checkCommandInput(outputKind, {
119+
nook: true,
120+
test: cli.input.length <= 1,
121+
message: 'Can only accept one DIR or FILE (make sure to escape spaces!)',
122+
fail: 'received ' + cli.input.length,
123+
})
124+
if (!wasValidInput) {
125+
return
126+
}
127+
128+
const target = path.resolve(process.cwd(), cli.input[0] ?? '.')
129+
const isFile = !!safeStatsSync(target)?.isFile()
130+
const cwd = isFile ? path.dirname(target) : target
131+
const entryFile = isFile ? path.basename(target) : undefined
132+
133+
const sockJson = readOrDefaultSocketJson(cwd)
134+
const defaults = sockJson.defaults?.manifest?.dotnet
135+
136+
debugFn('inspect', `override: ${SOCKET_JSON} dotnet`, defaults)
137+
138+
const dotnetConfig = resolveEcosystemConfig('dotnet', cwd, sockJson)
139+
const given = cli.flags as {
140+
bin?: string | undefined
141+
dotnetOpts?: string | undefined
142+
excludeConfigs?: string | undefined
143+
ignoreUnresolved?: boolean | undefined
144+
includeConfigs?: string | undefined
145+
verbose?: boolean | undefined
146+
}
147+
// An empty --bin or --dotnet-opts leaves the default in place.
148+
const flags = {
149+
...given,
150+
bin: given.bin || undefined,
151+
dotnetOpts: given.dotnetOpts || undefined,
152+
}
153+
for (const key of [
154+
'bin',
155+
'dotnetOpts',
156+
'excludeConfigs',
157+
'ignoreUnresolved',
158+
'includeConfigs',
159+
'verbose',
160+
] as const) {
161+
const configured = defaults?.[key]
162+
if (
163+
flags[key] === undefined &&
164+
configured !== undefined &&
165+
configured !== null &&
166+
configured !== ''
167+
) {
168+
logger.info(
169+
`Using default --${camelToKebab(key)} from ${SOCKET_JSON}:`,
170+
configured,
171+
)
172+
}
173+
}
174+
dotnetConfig.bin = flags.bin ?? dotnetConfig.bin
175+
if (flags.dotnetOpts) {
176+
dotnetConfig.buildOpts = parseBuildToolOpts(flags.dotnetOpts)
177+
}
178+
dotnetConfig.excludeConfigs =
179+
flags.excludeConfigs ?? dotnetConfig.excludeConfigs
180+
dotnetConfig.ignoreUnresolved =
181+
flags.ignoreUnresolved ?? dotnetConfig.ignoreUnresolved
182+
dotnetConfig.includeConfigs =
183+
flags.includeConfigs ?? dotnetConfig.includeConfigs
184+
dotnetConfig.verbose = flags.verbose ?? dotnetConfig.verbose
185+
const { bin, verbose } = dotnetConfig
186+
187+
if (verbose) {
188+
logger.group('- ', parentName, config.commandName, ':')
189+
logger.group('- flags:', cli.flags)
190+
logger.groupEnd()
191+
logger.log('- input:', cli.input)
192+
logger.groupEnd()
193+
logger.group()
194+
logger.info('- cwd:', cwd)
195+
logger.info('- entry:', entryFile ?? '(every solution and project)')
196+
logger.info('- dotnet bin:', bin)
197+
logger.groupEnd()
198+
}
199+
200+
if (dryRun) {
201+
logger.log(constants.DRY_RUN_BAILING_NOW)
202+
return
203+
}
204+
205+
const excludePaths = cmdFlagValueToArray(cli.flags['excludePaths'])
206+
assertValidExcludePaths(excludePaths)
207+
208+
await convertDotnetToFacts({
209+
config: dotnetConfig,
210+
cwd,
211+
entryFile,
212+
excludePaths,
213+
})
214+
}

‎src/commands/manifest/cmd-manifest.mts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { cmdManifestBazel } from './bazel/cmd-manifest-bazel.mts'
22
import { cmdManifestAuto } from './cmd-manifest-auto.mts'
33
import { cmdManifestCdxgen } from './cmd-manifest-cdxgen.mts'
44
import { cmdManifestConda } from './cmd-manifest-conda.mts'
5+
import { cmdManifestDotnet } from './cmd-manifest-dotnet.mts'
56
import { cmdManifestDynamicSbomInference } from './cmd-manifest-dynamic-sbom-inference.mts'
67
import { cmdManifestGradle } from './cmd-manifest-gradle.mts'
78
import { cmdManifestKotlin } from './cmd-manifest-kotlin.mts'
@@ -74,6 +75,7 @@ async function run(
7475
bazel: cmdManifestBazel,
7576
cdxgen: cmdManifestCdxgen,
7677
conda: cmdManifestConda,
78+
dotnet: cmdManifestDotnet,
7779
'dynamic-sbom-inference': cmdManifestDynamicSbomInference,
7880
gradle: cmdManifestGradle,
7981
kotlin: cmdManifestKotlin,

0 commit comments

Comments
 (0)