feat(artifacts): inspect Maven POM and Gradle module metadata

Inspect local Maven/Gradle metadata as Evidence with bounded report/XML admission, preserved caller choices and owned cleanup.

Refs #8828; broader comparison and resolution work remains outside this change.

Assisted-by: Suika (gensokyo-skills:suika-scatter-gather-planning)
Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
This commit is contained in:
Matt Van Hornandgensokyo-dev authored and GitHub committed 2026-11-17 14:40:38 +00:00
1 parent 5ccb7c59c8
commit 05be423acb
50 files changed
+3872 -24

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
import { decodeLimit } from "../domain/parseFailure.js";
/** The ParseFailure format of a Maven POM or Gradle module metadata file. */
export const MAVEN_GRADLE_METADATA_FORMAT = "maven-gradle-metadata";
/** Fixed report allowances; each names the representation it bounds. */
export type MavenGradleReportAllowance =
| "repeated_variant_name_chars"
| "dependency_rows"
| "variants"
| "exclusions"
| "unresolved_records"
| "xml_nodes";
const REPORT_REFUSALS: Readonly<
Record<
MavenGradleReportAllowance,
(required: number, limit: number) => string
>
> = {
repeated_variant_name_chars: (required, limit) =>
`Gradle module metadata would repeat ${String(required)} characters of variant names across its dependency rows, above the ${String(limit)}-character report allowance.`,
dependency_rows: (required, limit) =>
`Metadata declares ${String(required)} dependency and constraint rows, above the ${String(limit)}-row report allowance.`,
variants: (required, limit) =>
`Gradle module metadata declares ${String(required)} variants, above the ${String(limit)}-variant report allowance.`,
exclusions: (required, limit) =>
`Metadata declares ${String(required)} dependency exclusions, above the ${String(limit)}-exclusion report allowance.`,
unresolved_records: (required, limit) =>
`Metadata needs at least ${String(required)} unresolved reference and coordinate records, above the ${String(limit)}-record report allowance.`,
xml_nodes: (required, limit) =>
`Maven POM holds more than ${String(limit)} XML nodes (at least ${String(required)} counted), above the ${String(limit)}-node allowance for its document tree.`,
};
/**
* Refuse a report that would grow far past the input bytes. Each dependency
* row (with its unresolved-coordinate records), variant, exclusion and
* repeated variant name expands a few input bytes into a much larger report.
*/
export const metadataReportLimit = (
allowance: MavenGradleReportAllowance,
maximum: number,
required: number,
) =>
decodeLimit(
MAVEN_GRADLE_METADATA_FORMAT,
REPORT_REFUSALS[allowance](required, maximum),
{ name: allowance, maximum, required },
);
+120
View File
@@ -0,0 +1,120 @@
/** Tiny well-formed Maven POM with parent, properties, BOM import, and ranges. */
export const mavenPomFixture = `<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>demo-parent</artifactId>
<version>9.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>demo</artifactId>
<version>\${revision}</version>
<packaging>jar</packaging>
<properties>
<revision>1.2.3</revision>
<jackson.version>2.17.2</jackson.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>3.3.4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>\${jackson.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<scope>compile</scope>
<optional>false</optional>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>[5.10,6.0)</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
`;
/** Tiny Gradle Module Metadata 1.1 document with library and platform variants. */
export const gradleModuleFixture = `{
"formatVersion": "1.1",
"component": {
"group": "com.example",
"module": "demo",
"version": "1.2.3"
},
"createdBy": {
"gradle": {
"version": "8.10.2"
}
},
"variants": [
{
"name": "apiElements",
"attributes": {
"org.gradle.usage": "java-api",
"org.gradle.category": "library"
},
"dependencies": [
{
"group": "com.fasterxml.jackson.core",
"module": "jackson-databind",
"version": { "requires": "2.17.2" },
"excludes": [
{
"group": "com.fasterxml.jackson.core",
"module": "jackson-annotations"
}
]
}
]
},
{
"name": "runtimeElements",
"attributes": {
"org.gradle.usage": "java-runtime",
"org.gradle.category": "library"
},
"dependencyConstraints": [
{
"group": "org.slf4j",
"module": "slf4j-api",
"version": { "requires": "2.0.16" }
}
]
},
{
"name": "demoPlatform",
"attributes": {
"org.gradle.category": "platform"
},
"dependencyConstraints": [
{
"group": "com.fasterxml.jackson.core",
"module": "jackson-databind",
"version": { "strictly": "[2.17,2.18)" }
}
]
}
]
}
`;
File diff suppressed because it is too large. Load diff
+661
View File
@@ -0,0 +1,661 @@
import { MavenGradleUnresolvedCollector } from "./MavenGradleUnresolvedCollector.js";
import { Budget } from "../domain/budget.js";
import { decodeStrictUtf8 } from "../domain/strictUtf8.js";
import { parseJsonWithDuplicatePolicy } from "../domain/jsonDuplicateMember.js";
import { isRecord } from "../kernel/isRecord.js";
import { malformedInput, unsupportedInput } from "../domain/parseFailure.js";
import type { Element, Node } from "@xmldom/xmldom";
import {
countXmlNodes,
parseXmlDocument,
opensLikeXml,
} from "../domain/xmlDocument.js";
import {
MAVEN_GRADLE_METADATA_DEPENDENCY_ROWS,
MAVEN_GRADLE_METADATA_EXCLUSIONS,
MAVEN_GRADLE_METADATA_REPEATED_VARIANT_NAME_CHARS,
MAVEN_GRADLE_METADATA_VARIANTS,
MAVEN_GRADLE_METADATA_XML_NODES,
requestedVersionKind,
type MavenGradleDependency,
type MavenGradleMetadata,
} from "../domain/java/mavenGradleMetadata.js";
import { redactRecordedTransportUrl } from "../domain/recordedTransportUrl.js";
import {
MAVEN_GRADLE_METADATA_FORMAT,
metadataReportLimit,
type MavenGradleReportAllowance,
} from "./MavenGradleMetadata.errors.js";
const BASE_LIMITATIONS = [
"This workflow reads a Maven POM or Gradle module-metadata document without running Maven or Gradle, resolving a dependency tree, or contacting a repository.",
"Requested versions, ranges, and property spellings are recorded as written; interpolation and parent/BOM inheritance are not performed.",
] as const;
const isElement = (node: Node | null): node is Element =>
node !== null && node.nodeType === 1;
const childElements = (element: Element): Element[] => {
const children: Element[] = [];
for (
let child = element.firstChild;
child !== null;
child = child.nextSibling
)
if (isElement(child)) children.push(child);
return children;
};
const childrenNamed = (element: Element, local: string): Element[] =>
childElements(element).filter((child) => child.localName === local);
const soleNamed = (element: Element, local: string): Element | undefined => {
const matches = childrenNamed(element, local);
if (matches.length <= 1) return matches[0];
throw malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
`Maven POM declares <${local}> more than once in one <${element.localName}>.`,
);
};
const MAVEN_POM_NAMESPACE = "http://maven.apache.org/POM/4.0.0";
/**
* A Maven POM root: `project` in the POM namespace, or a namespace-free
* `project` that declares `modelVersion` or `artifactId`. Ant and other
* `project` vocabularies declare neither and are not POMs.
*/
const isMavenProjectRoot = (root: Node | null): root is Element => {
if (!isElement(root) || root.localName !== "project") return false;
if (root.namespaceURI === MAVEN_POM_NAMESPACE) return true;
return (
(root.namespaceURI === null || root.namespaceURI === "") &&
childElements(root).some(
(child) =>
child.localName === "modelVersion" || child.localName === "artifactId",
)
);
};
/** Refuse a report whose expanded collection would outgrow its fixed allowance. */
const admit = (
allowance: MavenGradleReportAllowance,
limit: number,
required: number,
): void => {
if (required > limit) throw metadataReportLimit(allowance, limit, required);
};
const nonempty = (value: string | null | undefined): string | null => {
if (value === null || value === undefined) return null;
const trimmed = value.trim();
return trimmed === "" ? null : trimmed;
};
const elementText = (element: Element | undefined): string | null => {
if (element === undefined) return null;
const parts: string[] = [];
for (
let child = element.firstChild;
child !== null;
child = child.nextSibling
)
// Text (3) and CDATA section (4) nodes both carry character data.
if (child.nodeType === 3 || child.nodeType === 4)
parts.push(child.nodeValue ?? "");
return nonempty(parts.join(""));
};
const childText = (element: Element, local: string): string | null =>
elementText(soleNamed(element, local));
const textOf = (value: unknown): string | null =>
typeof value === "string" ? nonempty(value) : null;
const boolOf = (value: string | null): boolean | null => {
if (value === null) return null;
const folded = value.toLowerCase();
if (folded === "true") return true;
if (folded === "false") return false;
return null;
};
const emptyGradleVersion = {
requires: null,
prefers: null,
strictly: null,
rejects: [] as string[],
};
/** An absent collection is empty; a present one must be a JSON array. */
const gradleArray = (value: unknown, field: string): readonly unknown[] => {
if (value === undefined) return [];
if (Array.isArray(value)) return value;
throw malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
`Gradle module metadata ${field} is present but is not a JSON array.`,
);
};
const gradleObjects = (
value: unknown,
field: string,
): readonly Record<string, unknown>[] =>
gradleArray(value, field).map((entry, index) => {
if (isRecord(entry)) return entry;
throw malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
`Gradle module metadata ${field}[${String(index)}] is not a JSON object.`,
);
});
const gradleVersionOf = (
value: unknown,
): MavenGradleDependency["gradle_version"] => {
if (typeof value === "string") {
const requires = nonempty(value);
return requires === null
? { ...emptyGradleVersion }
: { ...emptyGradleVersion, requires };
}
if (value === undefined) return { ...emptyGradleVersion };
if (!isRecord(value))
throw malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
"Gradle module metadata version is present but is neither a string nor a JSON object.",
);
const versionText = (field: "requires" | "prefers" | "strictly") => {
const entry = value[field];
if (entry === undefined || typeof entry === "string") return textOf(entry);
throw malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
`Gradle module metadata version.${field} is present but is not a string.`,
);
};
const rejects = gradleArray(value.rejects, "version.rejects").map(
(entry, index) => {
const text = textOf(entry);
if (text !== null) return text;
throw malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
`Gradle module metadata version.rejects[${String(index)}] is not a non-empty string.`,
);
},
);
return {
requires: versionText("requires"),
prefers: versionText("prefers"),
strictly: versionText("strictly"),
rejects,
};
};
const requestedFromGradle = (
version: MavenGradleDependency["gradle_version"],
): string | null => {
if (version === null) return null;
return version.requires ?? version.strictly ?? version.prefers;
};
/** The `<exclusion>` elements of one POM dependency row. */
const mavenExclusionElements = (element: Element): Element[] => {
const container = soleNamed(element, "exclusions");
return container === undefined ? [] : childrenNamed(container, "exclusion");
};
const parseMavenDependency = (
element: Element,
origin: "dependencies" | "dependencyManagement",
index: number,
unresolved: MavenGradleUnresolvedCollector,
): MavenGradleDependency => {
const group_id = childText(element, "groupId");
const artifact_id = childText(element, "artifactId");
const version = childText(element, "version");
const type = childText(element, "type");
const scope = childText(element, "scope");
const bom_import = type === "pom" && scope === "import";
const exclusions = mavenExclusionElements(element).map((exclusion) => ({
group_id: childText(exclusion, "groupId"),
artifact_id: childText(exclusion, "artifactId"),
}));
const owner =
origin === "dependencies" ? "dependency" : "dependency_management";
unresolved.coordinates(
{ group_id, artifact_id, version },
owner,
index,
false,
);
const optional_spelling = childText(element, "optional");
const classifier = childText(element, "classifier");
unresolved.properties(
[
["scope", scope],
["type", type],
["classifier", classifier],
["optional", optional_spelling],
],
owner,
index,
);
return {
group_id,
artifact_id,
version,
version_kind: requestedVersionKind(version, "maven-pom"),
gradle_version: null,
scope,
type,
optional: boolOf(optional_spelling),
optional_spelling,
classifier,
exclusions,
origin,
variant: null,
bom_import,
platform: false,
};
};
const parsePom = (
xml: string,
artifact: { path: string; sha256: string; bytes: number },
): MavenGradleMetadata => {
const limitations: string[] = [...BASE_LIMITATIONS];
// Count nodes as a stream first, so the tree is never built past its allowance.
const nodes = countXmlNodes(xml, MAVEN_GRADLE_METADATA_XML_NODES);
if (nodes > MAVEN_GRADLE_METADATA_XML_NODES)
throw metadataReportLimit(
"xml_nodes",
MAVEN_GRADLE_METADATA_XML_NODES,
nodes,
);
const parsed = parseXmlDocument(xml, {
doctype: "reject",
lineEndings: "preserve",
});
if (!parsed.ok)
throw parsed.error.kind === "unsupported"
? unsupportedInput(
MAVEN_GRADLE_METADATA_FORMAT,
"Maven POM declares a document type, which is unsupported.",
)
: malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
"Maven POM is not well-formed XML.",
);
const root = parsed.value.documentElement;
if (!isMavenProjectRoot(root))
throw unsupportedInput(
MAVEN_GRADLE_METADATA_FORMAT,
"Selected XML document is not a Maven project POM.",
);
const unresolved = new MavenGradleUnresolvedCollector();
const parentElement = soleNamed(root, "parent");
const parent =
parentElement === undefined
? null
: {
group_id: childText(parentElement, "groupId"),
artifact_id: childText(parentElement, "artifactId"),
version: childText(parentElement, "version"),
packaging: null,
relative_path: childText(parentElement, "relativePath"),
relative_path_declared:
soleNamed(parentElement, "relativePath") !== undefined,
};
if (parent !== null) unresolved.coordinates(parent, "parent", null, false);
const coordinates = {
group_id: childText(root, "groupId"),
artifact_id: childText(root, "artifactId"),
version: childText(root, "version"),
packaging: childText(root, "packaging"),
};
unresolved.coordinates(coordinates, "project", null, parent !== null);
unresolved.properties(
[["packaging", coordinates.packaging]],
"project",
null,
);
const propertiesElement = soleNamed(root, "properties");
const properties =
propertiesElement === undefined
? []
: childElements(propertiesElement).flatMap((property) => {
const name = nonempty(property.localName);
if (name === null) return [];
// A property may hold a repository URL; its userinfo never leaves the parser.
const {
url: value,
url_credentials_redacted: value_credentials_redacted,
} = redactRecordedTransportUrl(elementText(property));
return [{ name, value, value_credentials_redacted }];
});
const dependencyManagementElement = soleNamed(root, "dependencyManagement");
const managedContainer = dependencyManagementElement
? soleNamed(dependencyManagementElement, "dependencies")
: undefined;
const managedElements =
managedContainer === undefined
? []
: childrenNamed(managedContainer, "dependency");
const dependenciesContainer = soleNamed(root, "dependencies");
const dependencyElements =
dependenciesContainer === undefined
? []
: childrenNamed(dependenciesContainer, "dependency");
admit(
"dependency_rows",
MAVEN_GRADLE_METADATA_DEPENDENCY_ROWS,
managedElements.length + dependencyElements.length,
);
admit(
"exclusions",
MAVEN_GRADLE_METADATA_EXCLUSIONS,
[...managedElements, ...dependencyElements].reduce(
(count, element) => count + mavenExclusionElements(element).length,
0,
),
);
const dependency_management = managedElements.map((element, index) =>
parseMavenDependency(element, "dependencyManagement", index, unresolved),
);
const dependencies = dependencyElements.map((element, index) =>
parseMavenDependency(element, "dependencies", index, unresolved),
);
if (parent !== null)
limitations.push(
"Parent coordinates are recorded as spelled; the parent POM was not read and inheritance was not applied.",
);
if (soleNamed(root, "repositories") !== undefined)
limitations.push(
"Declared repositories are recorded as unread; they were not contacted.",
);
if (soleNamed(root, "profiles") !== undefined)
limitations.push(
"POM profiles are present and were not activated; profile-scoped declarations remain unread.",
);
if (coordinates.packaging === null)
limitations.push(
"Packaging was not declared; Maven would default to jar, but that default was not applied.",
);
return {
artifact: {
path: artifact.path,
sha256: artifact.sha256,
bytes: artifact.bytes,
},
format: "maven-pom",
coordinates,
parent,
properties,
dependencies,
dependency_management,
gradle: null,
unresolved: unresolved.finish(),
coverage: { status: "complete", examined_bytes: artifact.bytes },
limitations,
};
};
const parseGradleDependency = (
value: unknown,
origin: "variant-dependencies" | "variant-constraints",
variant: string | null,
platform: boolean,
index: number,
unresolved: MavenGradleUnresolvedCollector,
): MavenGradleDependency => {
if (!isRecord(value))
throw malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
`Gradle ${origin === "variant-dependencies" ? "dependency" : "dependency constraint"} ${String(index)} is not a JSON object.`,
);
const record = value;
const group_id = textOf(record.group);
const artifact_id = textOf(record.module);
const gradle_version = gradleVersionOf(record.version);
const version = requestedFromGradle(gradle_version);
unresolved.coordinates(
{ group_id, artifact_id, version },
"variant",
index,
false,
);
const excludes = gradleObjects(record.excludes, "excludes");
return {
group_id,
artifact_id,
version,
version_kind: requestedVersionKind(version, "gradle-module"),
gradle_version,
scope: null,
type: null,
optional: null,
optional_spelling: null,
classifier: null,
exclusions: excludes.map((entry) => ({
group_id: textOf(entry.group),
artifact_id: textOf(entry.module),
})),
origin,
variant,
bom_import: false,
platform,
};
};
const parseGradle = (
source: string,
artifact: { path: string; sha256: string; bytes: number },
): MavenGradleMetadata => {
const json = parseJsonWithDuplicatePolicy(source, "reject");
if (!json.ok) {
if (json.duplicate !== undefined)
throw malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
`Gradle module metadata declares a field more than once in one object (offset ${String(json.duplicate.offset)}).`,
);
// Engine diagnostics can quote credential-bearing source; keep the public reason generic.
throw malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
"Gradle module metadata is not well-formed JSON.",
{ cause: json.cause },
);
}
const parsed = json.value;
if (!isRecord(parsed))
throw unsupportedInput(
MAVEN_GRADLE_METADATA_FORMAT,
"Gradle module metadata root must be a JSON object.",
);
const format_version = textOf(parsed.formatVersion);
const component = isRecord(parsed.component) ? parsed.component : null;
const variantsValue = parsed.variants;
if (
format_version === null ||
(component === null && !Array.isArray(variantsValue))
)
throw unsupportedInput(
MAVEN_GRADLE_METADATA_FORMAT,
"Selected JSON document is not Gradle module metadata (missing formatVersion and component or variants).",
);
const limitations: string[] = [
...BASE_LIMITATIONS,
"Gradle variant attributes other than category and usage are not decoded.",
"available-at coordinates are recorded as spelled; the named module file was not fetched.",
];
const unresolved = new MavenGradleUnresolvedCollector();
const coordinates = {
group_id: component === null ? null : textOf(component.group),
artifact_id: component === null ? null : textOf(component.module),
version: component === null ? null : textOf(component.version),
packaging: null,
};
unresolved.coordinates(coordinates, "project", null, false);
const createdBy = isRecord(parsed.createdBy) ? parsed.createdBy : null;
const createdGradle =
createdBy !== null && isRecord(createdBy.gradle) ? createdBy.gradle : null;
// Count each expanded collection before any report record is built.
admit(
"variants",
MAVEN_GRADLE_METADATA_VARIANTS,
gradleArray(variantsValue, "variants").length,
);
const variants = gradleObjects(variantsValue, "variants");
const rowLists = variants.flatMap((variant) => [
gradleArray(variant.dependencies, "dependencies"),
gradleArray(variant.dependencyConstraints, "dependencyConstraints"),
]);
admit(
"dependency_rows",
MAVEN_GRADLE_METADATA_DEPENDENCY_ROWS,
rowLists.reduce((count, rows) => count + rows.length, 0),
);
let exclusions = 0;
for (const rows of rowLists)
for (const row of rows)
if (isRecord(row))
exclusions += gradleArray(row.excludes, "excludes").length;
admit("exclusions", MAVEN_GRADLE_METADATA_EXCLUSIONS, exclusions);
const dependencies: MavenGradleDependency[] = [];
const dependency_management: MavenGradleDependency[] = [];
const gradleVariants: NonNullable<MavenGradleMetadata["gradle"]>["variants"] =
[];
let nextIndex = 0;
const repeatedVariantNames = new Budget(
MAVEN_GRADLE_METADATA_REPEATED_VARIANT_NAME_CHARS,
);
for (const variant of variants) {
const name = textOf(variant.name);
const attributes = isRecord(variant.attributes) ? variant.attributes : {};
const category = textOf(attributes["org.gradle.category"]);
const usage = textOf(attributes["org.gradle.usage"]);
const platform =
category === "platform" || category === "enforced-platform";
const availableAt: unknown = variant["available-at"];
if (availableAt !== undefined && !isRecord(availableAt))
throw malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
"Gradle module metadata available-at is present but is not a JSON object.",
);
const available = availableAt === undefined ? null : availableAt;
const variantDependencies = gradleArray(
variant.dependencies,
"dependencies",
);
const constraints = gradleArray(
variant.dependencyConstraints,
"dependencyConstraints",
);
// Every row repeats its variant's name; admit that expansion before
// building rows, so a long name times many rows cannot outgrow the input.
const repeated =
(name?.length ?? 0) * (variantDependencies.length + constraints.length);
repeatedVariantNames.charge(repeated, () =>
metadataReportLimit(
"repeated_variant_name_chars",
repeatedVariantNames.maximum,
repeatedVariantNames.used + repeated,
),
);
for (const dependency of variantDependencies)
dependencies.push(
parseGradleDependency(
dependency,
"variant-dependencies",
name,
platform,
nextIndex++,
unresolved,
),
);
for (const constraint of constraints)
dependency_management.push(
parseGradleDependency(
constraint,
"variant-constraints",
name,
platform,
nextIndex++,
unresolved,
),
);
gradleVariants.push({
name,
category,
usage,
available_at:
available === null
? null
: {
group_id: textOf(available.group),
artifact_id: textOf(available.module),
version: textOf(available.version),
...redactRecordedTransportUrl(textOf(available.url)),
},
dependency_count: variantDependencies.length,
constraint_count: constraints.length,
});
}
return {
artifact: {
path: artifact.path,
sha256: artifact.sha256,
bytes: artifact.bytes,
},
format: "gradle-module",
coordinates,
parent: null,
properties: [],
dependencies,
dependency_management,
gradle: {
format_version,
created_by_gradle:
createdGradle === null ? null : textOf(createdGradle.version),
variants: gradleVariants,
},
unresolved: unresolved.finish(),
coverage: { status: "complete", examined_bytes: artifact.bytes },
limitations,
};
};
/** Decode one bounded Maven POM or Gradle module-metadata document without resolution. */
export const parseMavenGradleMetadata = (
bytes: Uint8Array,
artifact: { path: string; sha256: string; bytes: number },
): MavenGradleMetadata => {
if (bytes.length !== artifact.bytes)
throw malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
"Selected artifact length disagrees with the retained bytes.",
);
if (bytes.length === 0)
throw malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
"Selected file is empty.",
);
let source: string;
try {
// ignoreBOM: true kept a leading U+FEFF; "preserve" is that same policy.
source = decodeStrictUtf8(bytes, "preserve");
} catch {
throw malformedInput(
MAVEN_GRADLE_METADATA_FORMAT,
"Selected file is not valid UTF-8.",
);
}
const trimmed = source.trimStart();
if (trimmed.startsWith("{") || trimmed.startsWith("["))
return parseGradle(source, artifact);
if (opensLikeXml(trimmed) || trimmed.startsWith("<"))
return parsePom(source, artifact);
throw unsupportedInput(
MAVEN_GRADLE_METADATA_FORMAT,
"Selected file is not a Maven POM or Gradle module-metadata document.",
);
};
+213
View File
@@ -0,0 +1,213 @@
import {
ArtifactReaderFailure,
ArtifactResourceScope,
artifactFilePrimaryFacts,
type ArtifactFilePrimaryFacts,
projectArtifactCloseFailure,
projectOwnedArtifactIdentityFailure,
projectSelectedArtifactFileFailure,
projectStableArtifactFailure,
readStableArtifact,
projectOwnedArtifactInputFailure,
translateArtifactFailure,
type StableArtifactSnapshot,
} from "../resources/index.js";
import {
isParseLimit,
parseLimitConstraint,
parseFailureAnalysisError,
} from "../domain/parseFailureAnalysisError.js";
import { decodeLimit } from "../domain/parseFailure.js";
import { errorMessage } from "../kernel/errorMessage.js";
import { ArtifactOperationError } from "../domain/artifactOperationError.js";
import {
MAX_INSPECT_MAVEN_GRADLE_METADATA_FILE_BYTES,
type InspectMavenGradleMetadataInput,
} from "../domain/java/mavenGradleMetadata.js";
import { err, ok } from "../domain/result.js";
import {
MAVEN_GRADLE_METADATA_FORMAT,
type MavenGradleReportAllowance,
} from "./MavenGradleMetadata.errors.js";
import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js";
import { MAVEN_GRADLE_METADATA_PROVIDER_IDENTITY } from "./MavenGradleMetadataProviderIdentity.js";
import { parseMavenGradleMetadata } from "./MavenGradleMetadataParser.js";
const OPERATION = "inspect_maven_gradle_metadata";
/** Portable parser over one bounded, identity-checked POM or module-metadata file. */
/**
* Satisfies the application's MavenGradleMetadataPort structurally;
* composition checks the fit, so this provider does not import the
* application layer.
*/
export class MavenGradleMetadataProvider {
readonly identity = MAVEN_GRADLE_METADATA_PROVIDER_IDENTITY;
readonly #resources = new ArtifactResourceScope();
async close(): Promise<void> {
try {
await this.#resources.close();
} catch (cause: unknown) {
throw projectArtifactCloseFailure(
cause,
MAVEN_GRADLE_METADATA_PROVIDER_IDENTITY.id,
OPERATION,
);
}
}
async inspect(
input: InspectMavenGradleMetadataInput,
options?: { readonly signal?: AbortSignal },
) {
let snapshot: StableArtifactSnapshot | undefined;
try {
return await this.#resources.run(async () => {
snapshot = await readStableArtifact(
input.path,
input.max_file_bytes,
options?.signal,
undefined,
this.#resources,
);
return ok(
parseMavenGradleMetadata(snapshot.bytes, {
path: input.path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
}),
);
});
} catch (cause) {
return err(mavenGradleMetadataFailure(cause, input, snapshot));
}
}
}
const inputBudgetRemediation = (
input: InspectMavenGradleMetadataInput,
): string =>
input.max_file_bytes >= MAX_INSPECT_MAVEN_GRADLE_METADATA_FILE_BYTES
? `The file exceeds the ${String(MAX_INSPECT_MAVEN_GRADLE_METADATA_FILE_BYTES)}-byte input ceiling this operation accepts; select a smaller artifact.`
: `Raise max_file_bytes above ${String(input.max_file_bytes)} bytes, up to ${String(MAX_INSPECT_MAVEN_GRADLE_METADATA_FILE_BYTES)}, or select a smaller artifact; this is the caller-selected input read budget.`;
/** The subject a fixed-allowance remediation names for each report allowance. */
const REPORT_ALLOWANCE_SUBJECTS: Readonly<
Record<MavenGradleReportAllowance, (limit: number) => string>
> = {
dependency_rows: (limit) =>
`The ${String(limit)}-row allowance for dependency and constraint rows`,
variants: (limit) =>
`The ${String(limit)}-variant allowance for Gradle module variants`,
exclusions: (limit) =>
`The ${String(limit)}-exclusion allowance for dependency exclusions`,
unresolved_records: (limit) =>
`The ${String(limit)}-record allowance for unresolved references and coordinates`,
xml_nodes: (limit) =>
`The ${String(limit)}-node allowance for a Maven POM document tree`,
repeated_variant_name_chars: (limit) =>
`The ${String(limit)}-character allowance for variant names repeated across Gradle dependency rows`,
};
const mavenGradleMetadataFailurePrimary = (
facts: ArtifactFilePrimaryFacts,
input: InspectMavenGradleMetadataInput,
) => {
const { cause, origin } = facts;
if (isParseLimit(cause, MAVEN_GRADLE_METADATA_FORMAT)) {
const { name, maximum } = cause.failure.limit;
return parseLimitConstraint(OPERATION, "memory", cause, {
path: input.path,
...fixedAllowanceOptions(
Object.entries(REPORT_ALLOWANCE_SUBJECTS).find(
([key]) => key === name,
)?.[1](maximum) ?? name,
name === "xml_nodes" ? "parser" : "report",
{
limit: maximum,
unit:
name === "repeated_variant_name_chars"
? "UTF-16 code units"
: name === "unresolved_records"
? "records"
: name === "dependency_rows"
? "rows"
: name === "xml_nodes"
? "nodes"
: name,
},
),
});
}
const identityFailure = projectOwnedArtifactIdentityFailure(
facts,
OPERATION,
input.path,
);
if (identityFailure !== undefined) return identityFailure;
const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause);
if (formatFailure !== undefined) return formatFailure;
const inputFailure = projectOwnedArtifactInputFailure(
facts,
OPERATION,
input.path,
);
if (inputFailure !== undefined) return inputFailure;
if (
origin === "owned-or-classified" &&
cause instanceof ArtifactReaderFailure
) {
if (cause.reason === "limit" && cause.boundary === "file-size")
return parseLimitConstraint(
OPERATION,
"file-size",
decodeLimit(
MAVEN_GRADLE_METADATA_FORMAT,
cause.message,
{ name: "max_file_bytes", maximum: input.max_file_bytes },
{ cause },
),
{
retryable: false,
remediationAction: inputBudgetRemediation(input),
},
);
return translateArtifactFailure(OPERATION, cause);
}
const fileFailure = projectSelectedArtifactFileFailure(
cause,
OPERATION,
input.path,
"Maven POM or Gradle module metadata",
);
if (fileFailure !== undefined) return fileFailure;
return new ArtifactOperationError(
OPERATION,
origin === "owned-or-classified" && cause instanceof ArtifactReaderFailure
? cause.reason
: "io",
undefined,
errorMessage(cause),
{ cause },
);
};
const mavenGradleMetadataFailure = (
cause: unknown,
input: InspectMavenGradleMetadataInput,
snapshot?: StableArtifactSnapshot,
) => {
const primary = mavenGradleMetadataFailurePrimary(
artifactFilePrimaryFacts(cause),
input,
);
return projectStableArtifactFailure(
cause,
primary,
input.path,
MAVEN_GRADLE_METADATA_PROVIDER_IDENTITY.id,
OPERATION,
snapshot,
);
};
@@ -0,0 +1,6 @@
/** Bundled reader identity; coordinates and requested versions are separate observed facts. */
export const MAVEN_GRADLE_METADATA_PROVIDER_IDENTITY = {
id: "rea-maven-gradle-metadata",
name: "REA Maven POM and Gradle module metadata reader",
version: "1",
} as const;
@@ -0,0 +1,81 @@
import { expect, it } from "vitest";
import { ParseFailureError } from "../domain/parseFailure.js";
import { MavenGradleUnresolvedCollector } from "./MavenGradleUnresolvedCollector.js";
it("admits distinct references before retaining them and stops at a small shared quota", () => {
const collector = new MavenGradleUnresolvedCollector(2);
let failure: unknown;
try {
collector.properties(
[["version", "${first}${first}${second}${third}${fourth}"]],
"project",
null,
);
} catch (cause) {
failure = cause;
}
expect(failure).toBeInstanceOf(ParseFailureError);
expect(failure).toMatchObject({
failure: {
kind: "limit",
limit: { name: "unresolved_records", maximum: 2, required: 3 },
},
});
expect(collector.finish()).toEqual([
{
kind: "property",
reference: "${first}",
field: "version",
owner: "project",
index: null,
},
{
kind: "property",
reference: "${second}",
field: "version",
owner: "project",
index: null,
},
]);
});
it("deduplicates within each field while preserving separate field and row facts", () => {
const collector = new MavenGradleUnresolvedCollector(3);
collector.properties(
[
["version", "${same}${same}"],
["scope", "${same}"],
],
"dependency",
0,
);
collector.properties([["version", "${same}"]], "dependency", 1);
expect(
collector
.finish()
.map(({ field, index, reference }) => ({ field, index, reference })),
).toEqual([
{ field: "version", index: 0, reference: "${same}" },
{ field: "scope", index: 0, reference: "${same}" },
{ field: "version", index: 1, reference: "${same}" },
]);
});
it("shares admission between coordinate gaps and references across calls", () => {
const collector = new MavenGradleUnresolvedCollector(2);
collector.coordinates(
{ group_id: null, artifact_id: null, version: "1" },
"project",
null,
false,
);
expect(() =>
collector.properties([["scope", "${scope}"]], "dependency", 0),
).toThrow(ParseFailureError);
expect(
collector.finish().map(({ kind, reference }) => ({ kind, reference })),
).toEqual([
{ kind: "missing-coordinate", reference: "project.group_id" },
{ kind: "missing-coordinate", reference: "project.artifact_id" },
]);
});
@@ -0,0 +1,91 @@
import { Budget } from "../domain/budget.js";
import {
MAVEN_GRADLE_METADATA_UNRESOLVED_RECORDS,
mavenPropertyOccurrences,
type MavenGradleUnresolved,
} from "../domain/java/mavenGradleMetadata.js";
import { metadataReportLimit } from "./MavenGradleMetadata.errors.js";
type FieldValue = readonly [MavenGradleUnresolved["field"], string | null];
/** One report-wide admission owner for references and missing-coordinate facts. */
export class MavenGradleUnresolvedCollector {
readonly #records: MavenGradleUnresolved[] = [];
readonly #budget: Budget;
constructor(maximum = MAVEN_GRADLE_METADATA_UNRESOLVED_RECORDS) {
this.#budget = new Budget(maximum);
}
#reserve(): void {
this.#budget.charge(1, () =>
metadataReportLimit(
"unresolved_records",
this.#budget.maximum,
this.#budget.used + 1,
),
);
}
properties(
fields: readonly FieldValue[],
owner: MavenGradleUnresolved["owner"],
index: number | null,
): void {
for (const [field, value] of fields) {
const seen = new Set<string>();
for (const reference of mavenPropertyOccurrences(value)) {
if (seen.has(reference)) continue;
// Admit before retaining either the distinct reference or its record.
this.#reserve();
seen.add(reference);
this.#records.push({
kind: "property",
reference,
field,
owner,
index,
});
}
}
}
coordinates(
coordinates: {
readonly group_id: string | null;
readonly artifact_id: string | null;
readonly version: string | null;
},
owner: MavenGradleUnresolved["owner"],
index: number | null,
parentPresent: boolean,
): void {
const fields = [
["group_id", coordinates.group_id],
["artifact_id", coordinates.artifact_id],
["version", coordinates.version],
] as const;
for (const [field, value] of fields) {
if (value !== null) {
this.properties([[field, value]], owner, index);
continue;
}
// Maven's parent may supply group/version, but never the child's artifactId.
const inherited =
parentPresent && owner === "project" && field !== "artifact_id";
this.#reserve();
this.#records.push({
kind: inherited ? "parent-coordinate" : "missing-coordinate",
reference: inherited ? `parent.${field}` : `${owner}.${field}`,
field,
owner,
index,
});
}
}
/** Transfer the bounded records into the completed report. */
finish(): MavenGradleUnresolved[] {
return this.#records;
}
}