Skip to content

A Maven settings.xml or NuGet.Config that is not UTF-8 is read as absent: a hosted Maven scan pins behind a catch-all mirror and every build fails, and agent mode scans a folder the build does not use #2375

Backlog

Description

[agent] Found by the architecture refactor routine on main at cfc870f. No PR yet: the routine already has three open.

Problem

socket-patch reads three machine settings files as strict UTF-8 and takes a file that is there but is not UTF-8 for no file at all. Maven and NuGet read those files in other encodings. So socket-patch and the build tool disagree about the machine, and the run says nothing.

  1. Hosted Maven, the default mode. ~/.m2/settings.xml declares a mirror that takes every repository (<mirrorOf>*</mirrorOf>, a company's repository manager). The scan is meant to write no pin there and warn redirect_maven_mirror_captures_repository, because the mirror does not hold the patched version (Do not wire a hosted Maven pin behind a mirror that would take its repository #2135). When the settings file holds one byte that is not UTF-8, the scan sees no mirror, pins the patch, prints "Switched 1 package to hosted patches … Nothing left to patch" and exits 0. Every Maven build then fails: Could not find artifact …:3.3.7-socket.07ea3d34 in corp.
  2. Agent mode, Maven. The same file names the local repository (<localRepository>). The crawler ignores it and reads ~/.m2/repository, which Maven does not use on that machine.
  3. Agent mode, NuGet. A user NuGet.Config in ISO-8859-1 or UTF-16 names globalPackagesFolder. The crawler ignores it and reads ~/.nuget/packages.

In 2 and 3 the run reads a folder the build does not use: it finds nothing where the default folder is empty, and where that folder holds a copy of the package a wet run would patch that copy while the build loads another. I ran the dry runs only (see "Not run").

Who it hurts. A machine whose Maven settings are not pure UTF-8: a settings.xml saved as ISO-8859-1 or windows-1252 with one accented letter in a comment, a password or a path, or one written by a Windows PowerShell 5.1 redirect (… > settings.xml writes UTF-16 LE with a byte-order mark), as a CI step that writes the file from a secret may do. A settings file with a catch-all mirror is a company's file. The scan's own refusal for project files names the PowerShell case (candidate_file_unreadable: "for example UTF-16, which Windows PowerShell 5.1 writes").

The contract already states the rule, for the files a rewriter edits: "A candidate file that exists but is not UTF-8 … is never read as absent" (CLI_CONTRACT.md, line 467, #721), and for a pom of a reactor, "its content is unknown" (lines 3659 to 3660). docs/ecosystems.md (lines 1974 to 1979) says the local repository is "found the way Maven finds it". These three readers were not brought under either.

Evidence on main (cfc870f)

The binary built from main. The Maven and NuGet projects are the bench's (socket-patch-bench serve maven/hosted and nuget/hosted), with its patch API on loopback. Real Maven 3.9.11 on Java 21, and the real .NET SDK 8.0.428 in mcr.microsoft.com/dotnet/sdk:8.0-noble.

1. Hosted Maven behind a mirror

One settings file, written in eight encodings. Its text is the same in each but for the declaration and one comment:

<?xml version="1.0" encoding="ISO-8859-1"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0">
  <!-- Configuración corporativa -->
  <mirrors>
    <mirror>
      <id>corp</id>
      <mirrorOf>*</mirrorOf>
      <url>http://127.0.0.1:18999/repository/maven-public/</url>
    </mirror>
  </mirrors>
</settings>

socket-patch scan --yes --json with that file as ~/.m2/settings.xml:

settings.xml file -b says scan Maven reads the mirror
UTF-8, ASCII only ASCII text skipped, redirect_maven_mirror_captures_repository, no file changed yes
UTF-8, the accented comment UTF-8 text the same (not run)
UTF-8 with a BOM UTF-8 (with BOM) text the same (not run)
ISO-8859-1, declared ISO-8859 text applied, no warning, 3 files changed yes
windows-1252, declared Non-ISO extended-ASCII text applied, no warning, 3 files changed yes
UTF-16 LE with a BOM UTF-16, little-endian text applied, no warning, 3 files changed yes
declared UTF-8, the comment saved as ISO-8859-1 ISO-8859 text applied, no warning, 3 files changed yes
no declaration, the comment saved as ISO-8859-1 ISO-8859 text applied, no warning, 3 files changed yes

Every row exits 0 with status: success. "Maven reads the mirror" is a real mvn -B -s <file> dependency:resolve. For the first row and the last three it is the unpinned project resolved into an empty local repository: BUILD SUCCESS, with about 600 requests arriving at the mirror stand-in on port 18999. For the ISO-8859-1 and UTF-16 rows it is the failure below, which names the mirror corp and its address.

The same project end to end, under the ISO-8859-1 file (the UTF-16 file gives the same result and the same error):

$ file -b ~/.m2/settings.xml
XML 1.0 document, ISO-8859 text

$ mvn -B -s ~/.m2/settings.xml -Dmaven.repo.local=<repo> dependency:resolve
[INFO] BUILD SUCCESS

$ socket-patch scan --yes; echo "exit $?"
Found 20 packages (20 maven)
Switched 1 package to hosted patches; rewrote 3 files.
  HIGH  io.midadi2/bech2-client@3.3.7  CVE-2024-10000
Next steps:
  1. Commit .mvn/checksums/checksums.sha256, .mvn/maven.config, and pom.xml to keep the hosted patches.
  2. Reinstall from the updated lockfile, then run `socket-patch vex` to verify the installed patches.

Patched 1 package, fixing 1 vulnerability (1 high).
Saved about 2 hours of engineering time (1 package upgrade at ~2 hours).
Nothing left to patch.
exit 0

$ mvn -B -s ~/.m2/settings.xml -Dmaven.repo.local=<repo> dependency:resolve
[INFO] BUILD FAILURE
[ERROR] Failed to execute goal on project bench-app: Could not resolve dependencies for project dev.socket.bench:bench-app:jar:1.0.0
[ERROR] dependency: io.midadi2:bech2-client:jar:3.3.7-socket.07ea3d34 (compile)
[ERROR] 	Could not find artifact io.midadi2:bech2-client:jar:3.3.7-socket.07ea3d34 in corp (http://127.0.0.1:18999/repository/maven-public/)

The mirror's log holds the two requests Maven made for the pin:

404 local GET io/midadi2/bech2-client/3.3.7-socket.07ea3d34/bech2-client-3.3.7-socket.07ea3d34.pom
404 local GET io/midadi2/bech2-client/3.3.7-socket.07ea3d34/bech2-client-3.3.7-socket.07ea3d34.jar

The control is the UTF-8 file with the same mirror. The scan says what it should, and the build stays green before and after:

$ socket-patch scan --yes; echo "exit $?"
Switched 0 packages to hosted patches; rewrote 0 files.
No patches could be switched to hosted:
  pkg:maven/io.midadi2/bech2-client@3.3.7: no lockfile entry pinning it could be rewritten (see the warning below)
Warning: io.midadi2:bech2-client: on this machine Maven's settings send the socket-patch-07ea3d34-… repository to the
mirror `corp` (<mirrorOf>*</mirrorOf> in ~/.m2/settings.xml), which does not serve the patched artifact, so the build
could not resolve it; this run wrote nothing for it … Either exclude the repository from that mirror … or patch with
`scan --mode vendored` …
exit 0

2. The Maven local repository, agent mode

~/.m2/settings.xml names an empty directory as <localRepository>; ~/.m2/repository holds the bench's 20 packages. socket-patch scan --mode agent -e maven --dry-run --json:

settings.xml scannedPackages the repository read
none 20 ~/.m2/repository
UTF-8 0 the one the file names
ISO-8859-1, declared 20 ~/.m2/repository
UTF-16 LE with a BOM 20 ~/.m2/repository

3. NuGet's packages folder, agent mode

A user ~/.nuget/NuGet/NuGet.Config that sets globalPackagesFolder to an empty directory. The real SDK, asked what it reads (dotnet nuget locals global-packages --list), beside socket-patch scan --mode agent -e nuget --dry-run --json:

NuGet.Config .NET SDK 8.0.428 scannedPackages
none /root/.nuget/packages/ 18
UTF-8, with or without a BOM the configured folder 0
ISO-8859-1, declared the configured folder 18 (~/.nuget/packages)
UTF-16 LE with a BOM the configured folder 18 (~/.nuget/packages)

NuGet is stricter than Maven: this SDK refuses a file declared UTF-8 that holds an ISO-8859-1 byte ("NuGet.Config is not valid XML") and one declared windows-1252 ("not a supported encoding name"), so those two are not cases for it.

The hosted NuGet scan reads the same user file for its sources and mappings, and its write differs with the encoding too. With a user config that maps * to a company source, the UTF-8 run adds one packageSourceMapping entry for the Socket source; the UTF-16 run also adds nuget.org → *, as for a machine with no mapping. I did not run a restore over that difference.

4. As unit tests

Two throwaway tests, one beside each Maven reader, each writing the same settings in three encodings. Both fail on main:

$ cargo test -p socket-patch-core --lib -- probe_settings
test crawlers::maven_crawler::settings_mirrors::tests::probe_settings_in_another_encoding_still_declare_their_mirror ... FAILED
test crawlers::maven_crawler::local_repo_tests::probe_settings_local_repository_in_another_encoding_is_honoured ... FAILED

assertion `left == right` failed
  left: [("UTF-8", Some("corp")), ("ISO-8859-1", None), ("UTF-16", None)]
 right: [("UTF-8", Some("corp")), ("ISO-8859-1", Some("corp")), ("UTF-16", Some("corp"))]

assertion `left == right` failed
  left: [("UTF-8", true), ("ISO-8859-1", false), ("UTF-16", false)]
 right: [("UTF-8", true), ("ISO-8859-1", true), ("UTF-16", true)]
The two tests

In the tests module of crates/socket-patch-core/src/crawlers/maven_crawler/settings_mirrors.rs:

#[test]
fn probe_settings_in_another_encoding_still_declare_their_mirror() {
    let body = settings(&[("corp", "*")]);
    let latin1: Vec<u8> = format!(
        "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<!-- Configuraci\u{f3}n -->\n{body}"
    )
    .chars()
    .map(|c| c as u8)
    .collect();
    let utf16: Vec<u8> = [0xFF, 0xFE]
        .into_iter()
        .chain(
            format!("<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n{body}")
                .encode_utf16()
                .flat_map(u16::to_le_bytes),
        )
        .collect();
    let utf8 = format!("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- Configuraci\u{f3}n -->\n{body}")
        .into_bytes();
    let mut seen = Vec::new();
    for (name, bytes) in [("UTF-8", utf8), ("ISO-8859-1", latin1), ("UTF-16", utf16)] {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("home");
        let root = tmp.path().join("proj");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::create_dir_all(home.join(".m2")).unwrap();
        std::fs::write(home.join(".m2/settings.xml"), bytes).unwrap();
        let sets = settings_mirror_sets(&env(&[("HOME", &home)]), Os::current(), None, &root, None);
        seen.push((name, captured(&sets).map(str::to_string)));
    }
    let corp = Some("corp".to_string());
    assert_eq!(
        seen,
        [("UTF-8", corp.clone()), ("ISO-8859-1", corp.clone()), ("UTF-16", corp)]
    );
}

In crates/socket-patch-core/src/crawlers/maven_crawler/local_repo_tests.rs:

#[test]
fn probe_settings_local_repository_in_another_encoding_is_honoured() {
    let data = tempfile::tempdir().unwrap();
    let body = format!(
        "<settings>\n  <!-- Configuraci\u{f3}n -->\n  <localRepository>{}</localRepository>\n</settings>\n",
        data.path().display()
    );
    let latin1: Vec<u8> = format!("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n{body}")
        .chars()
        .map(|c| c as u8)
        .collect();
    let utf16: Vec<u8> = [0xFF, 0xFE]
        .into_iter()
        .chain(
            format!("<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n{body}")
                .encode_utf16()
                .flat_map(u16::to_le_bytes),
        )
        .collect();
    let utf8 = format!("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n{body}").into_bytes();
    let mut seen = Vec::new();
    for (name, bytes) in [("UTF-8", utf8), ("ISO-8859-1", latin1), ("UTF-16", utf16)] {
        let home = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(home.path().join(".m2")).unwrap();
        std::fs::write(home.path().join(".m2").join("settings.xml"), bytes).unwrap();
        let e = env(&[("HOME", home.path())]);
        seen.push((name, m2_repo(&e, Os::Unix) == Some(data.path().to_path_buf())));
    }
    assert_eq!(seen, [("UTF-8", true), ("ISO-8859-1", true), ("UTF-16", true)]);
}
The mirror stand-in

A repository manager on loopback: it serves the bench's 20 packages (a copy of the bench's ~/.m2/repository without the _remote.repositories files) and takes everything else from Maven Central, as a company's group repository does. It logs each request. The patched version exists in neither, so it answers 404.

#!/usr/bin/env python3
"""mirror.py <static-dir> <port> <log> <cache-dir>"""
import os, sys, urllib.request, urllib.error
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
root, port, log, cache = sys.argv[1], int(sys.argv[2]), sys.argv[3], sys.argv[4]
PREFIX = "/repository/maven-public/"
CENTRALS = ["https://repo.maven.apache.org/maven2/", "https://repo1.maven.org/maven2/"]
class H(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"
    def log_message(self, *a): pass
    def note(self, status, src, path):
        with open(log, "a") as f: f.write(f"{status} {src} {self.command} {path}\n")
    def reply(self, status, body, head):
        self.send_response(status); self.send_header("Content-Length", str(len(body))); self.end_headers()
        if not head: self.wfile.write(body)
    def serve(self, head):
        if not self.path.startswith(PREFIX) or ".." in self.path:
            self.note(404, "-", self.path); return self.reply(404, b"", head)
        rel = self.path[len(PREFIX):]
        local = os.path.join(root, rel)
        if os.path.isfile(local):
            self.note(200, "local", rel); return self.reply(200, open(local, "rb").read(), head)
        cached = os.path.join(cache, rel)
        if os.path.isfile(cached):
            self.note(200, "central", rel); return self.reply(200, open(cached, "rb").read(), head)
        if os.path.isdir(os.path.join(root, *rel.split("/")[:2])):      # the stand-in's own groups
            self.note(404, "local", rel); return self.reply(404, b"", head)
        code = 502
        for attempt in range(30):                                       # see the note below
            try:
                body = urllib.request.urlopen(CENTRALS[attempt % 2] + rel, timeout=60).read()
                os.makedirs(os.path.dirname(cached), exist_ok=True); open(cached, "wb").write(body)
                self.note(200, "central", rel); return self.reply(200, body, head)
            except urllib.error.HTTPError as e: code = e.code
            except Exception: code = 502
        self.note(code, "central", rel); return self.reply(code, b"", head)
    def do_GET(self): self.serve(False)
    def do_HEAD(self): self.serve(True)
ThreadingHTTPServer(("127.0.0.1", port), H).serve_forever()

The retry is for the machine these runs were made on, where Maven Central answered 404 for about half of all requests at random. It plays no part in the finding: the two requests for the pin are answered from the stand-in's own groups.

Where

  • The mirror gate's reader: crates/socket-patch-core/src/crawlers/maven_crawler/settings_mirrors.rs, lines 192 to 198. read_regular_to_string_sync(path) and Err(_) => Vec::new(): any failure to read is "this file declares no mirror". It reads the user settings, the global settings and a project's .mvn/settings.xml.
  • The local repository's reader: crates/socket-patch-core/src/crawlers/maven_crawler.rs, settings_local_repository, lines 945 to 952: the same read with .ok()?.
  • NuGet's readers: crates/socket-patch-core/src/vendor/nuget_config.rs, settings_chain (lines 216 to 220) and inherited_source_keys_traced (lines 147 to 150 and 182 to 185): read_regular_to_string(…).await.ok(). The doc comment of settings_chain says a file that cannot be read or parsed "is skipped".

The earlier fixes of this class

The mirror gate arrived later (40ac5a7, #2135, 2026-11-19) with the plain strict read.

Planned fix

One reader for an XML settings file, beside utils::requirements::decode and sharing its code page tables: a byte-order mark (UTF-8, UTF-16 LE and BE) decides, else the encoding of the XML declaration, else UTF-8. It models UTF-8, US-ASCII, ISO-8859-1, windows-1252 and UTF-16. The three sites above read through it and their own strict reads go.

Two differences between the tools need a parameter, and the tables above give both: Maven 3.9.11 reads a file with a malformed byte under UTF-8, where the .NET SDK refuses it; and the .NET SDK 8 here has no windows-1252.

A file that is there and still cannot be read (an encoding the reader does not model, a read error) is not "no settings":

  • the mirror gate writes no Maven pin and warns, naming the file, since it cannot tell whether a mirror takes the repository;
  • the local repository lookup answers through the channel it already has for "cannot tell which repository" (maven_local_repository_undetermined: neither is scanned or patched);
  • the NuGet chain reports the same way for its folder.

Tests: the two above, a NuGet one of the same shape, and a row in e2e_redirect_maven_build.rs (the suite #2135 extended) with an ISO-8859-1 settings file under the real Maven.

One point for a maintainer. The second half adds a warning where a run is silent today, for a settings file socket-patch cannot read. I would add it: the contract's rule for project files is that such a file "is never read as absent", and a pin behind an unseen mirror breaks every build. If you would rather keep those runs as they are, the decoder alone still fixes every case in the tables.

Not run

  • Windows, where the PowerShell case comes from. The files here were written by a script in the encodings PowerShell 5.1 and an ISO-8859-1 editor produce.
  • A wet agent-mode run over a default folder that holds an older copy (the bench's installed copies are synthetic).
  • Maven 3.6, 3.8 and 4; only 3.9.11 ran. mvnd and the Maven Wrapper did not run.
  • A NuGet restore after the hosted scan's differing write.
  • Gradle's and sbt's machine files. Core reads gradle.properties as bytes in ISO-8859-1 (crawlers/gradle_cache.rs), so it is not this defect; I did not look at the others.

Generated by Claude Code

Activity

  1. added
    bug
    arch-audit
    on Nov 30, 2026
  2. mikolalysenko commented on Nov 30, 2026

    @mikolalysenko
    CollaboratorAuthor

    [agent] Two more sites of the same read, found right after filing. Both are settings files outside the project that a Node tool reads whatever their bytes.

    Yarn classic's offline mirror

    Hosted mode leaves yarn.lock alone when yarn 1 has an offline mirror (redirect_yarn_classic_offline_mirror): "yarn looks mirror tarballs up by file name, and the hosted tarball has the same name as the upstream one, so installs would get the unpatched bytes and fail the integrity check". The layers outside the project (~/.yarnrc, ~/.npmrc, the prefix's, every ancestor's) are read at crates/socket-patch-core/src/patch/redirect/yarnrc.rs, line 716, with read_regular_to_string_sync(path).ok().

    On main (cfc870f), the bench's yarn-classic/hosted project, real yarn 1.22.22, and a ~/.yarnrc of two lines:

    # Configuración
    yarn-offline-mirror "<dir>"
    
    ~/.yarnrc yarn config get yarn-offline-mirror socket-patch scan --yes --json
    none undefined applied, yarn.lock rewritten
    saved as UTF-8 <dir> skipped, redirect_yarn_classic_offline_mirror, nothing written
    saved as ISO-8859-1 <dir> applied, no warning, yarn.lock rewritten

    Every row exits 0 with status: success.

    The project's own .yarnrc is not a case: with the same ISO-8859-1 bytes there the scan refuses by name (candidate_file_unreadable, exit 1, nothing written), which is the rule the issue quotes. A UTF-16 .yarnrc is not a case either: yarn itself refuses it (SyntaxError: Unknown token).

    Not run: a yarn install from a mirror that holds the upstream tarball, after the pin. The consequence above is the one the refusal's own message gives.

    npm's allow-remote in the user config

    The contract says an explicit allow-remote other than all "is RESPECTED and never rewritten … in the project .npmrc AND in every other npm config layer npm would consult". The layers outside the project are read at crates/socket-patch-cli/src/commands/scan/hosted.rs, lines 2019 to 2022, with the same .ok().

    The bench's npm/hosted project, real npm 12.2.3, and a ~/.npmrc of two lines (; Configuración and allow-remote=root):

    ~/.npmrc npm config get allow-remote before scan project .npmrc after npm config get allow-remote after
    none none applied created, allow-remote=all all
    saved as UTF-8 root applied not written root
    saved as ISO-8859-1 root applied created, allow-remote=all all

    So the user's setting is overridden by a line the scan asks to commit. The same closure serves replace-registry-host and omit-lockfile-registry-resolved, whose warnings would go missing the same way; I read that and did not run it.

    For the fix

    The reader wants a third way to decode, beside Maven's and NuGet's: as Node reads a text file (UTF-8, with a replacement character for a malformed byte), for the files yarn 1 and npm read.


    Generated by Claude Code

  3. added 2 commits that reference this issue on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent:triagedarch-auditbugpriority:p3

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions