Validate protocol v2 ref prefixes and want-refs

Protocol v2 ls-refs accepts a client-supplied ref-prefix, and fetch
accepts a client-supplied want-ref; both reach the ref database. For
file-backed repositories, RefDirectory maps the name to a loose-ref file
path, so path-traversal components (for example
refs/heads/../../../victim.git/refs/private/) let a client read loose
refs outside the served repository.

Validate both in the protocol parser, before they reach RefDirectory:

- ref-prefix: complete each prefix to a synthetic full ref name and
  validate it with Repository.isValidRefName(). Legal partial prefixes
  pass; traversal is rejected.
- want-ref: it is a complete ref name, so validate it directly with
  Repository.isValidRefName(). HEAD is also allowed, since it is a valid
  want-ref that isValidRefName() rejects as a one-level name.

For want-ref this mirrors native git's check_refname_format() gate
before the files backend builds a path. For ref-prefix JGit applies the
same validation because its file-backed ls-refs fast path scans loose
refs by prefix; native git uses ref-prefix only as a string filter.

Add a file-backed UploadPack regression test that creates sibling
repositories and verifies a traversal ref-prefix is rejected, plus
ProtocolV2Parser tests for valid partial prefixes, traversal and invalid
prefixes, want-ref HEAD, and a traversal want-ref.

Bug: https://gitlab.eclipse.org/security/vulnerability-reports/-/work_items/794
Change-Id: I9afcca950cfa12d904036da438fe3549fdb0d46a
diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ProtocolV2ParserTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ProtocolV2ParserTest.java
index bab4a36..cce8ec7 100644
--- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ProtocolV2ParserTest.java
+++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ProtocolV2ParserTest.java
@@ -348,6 +348,70 @@ public void testLsRefsPeel() throws IOException {
 	}
 
 	@Test
+	public void testLsRefsAcceptsValidPartialRefPrefixes() throws IOException {
+		PacketLineIn pckIn = formatAsPacketLine(PacketLineIn.delimiter(),
+				"ref-prefix r", "ref-prefix refs/heads/maste",
+				"ref-prefix refs/heads/", "ref-prefix refs/heads/v1.0",
+				PacketLineIn.end());
+
+		ProtocolV2Parser parser = new ProtocolV2Parser(
+				ConfigBuilder.getDefault());
+		LsRefsV2Request req = parser.parseLsRefsRequest(pckIn);
+		assertThat(req.getRefPrefixes(), hasItems("r", "refs/heads/maste",
+				"refs/heads/", "refs/heads/v1.0"));
+	}
+
+	@Test
+	public void testLsRefsRejectsTraversalRefPrefix() throws IOException {
+		PacketLineIn pckIn = formatAsPacketLine(PacketLineIn.delimiter(),
+				"ref-prefix refs/heads/../../../victim/refs/private/",
+				PacketLineIn.end());
+
+		ProtocolV2Parser parser = new ProtocolV2Parser(
+				ConfigBuilder.getDefault());
+		assertThrows(PackProtocolException.class,
+				() -> parser.parseLsRefsRequest(pckIn));
+	}
+
+	@Test
+	public void testLsRefsRejectsInvalidRefPrefixes() throws IOException {
+		for (String bad : new String[] { "refs/heads/./x", "refs/heads\\x",
+				"refs/heads/x:y", "/refs/heads/x", "refs//heads/x" }) {
+			PacketLineIn pckIn = formatAsPacketLine(PacketLineIn.delimiter(),
+					"ref-prefix " + bad, PacketLineIn.end());
+			ProtocolV2Parser parser = new ProtocolV2Parser(
+					ConfigBuilder.getDefault());
+			assertThrows(PackProtocolException.class,
+					() -> parser.parseLsRefsRequest(pckIn));
+		}
+	}
+
+	@Test
+	public void testFetchAllowsHeadWantRef() throws IOException {
+		PacketLineIn pckIn = formatAsPacketLine(PacketLineIn.delimiter(),
+				"want e4980cdc48cfa1301493ca94eb70523f6788b819",
+				"want-ref HEAD", PacketLineIn.end());
+
+		ProtocolV2Parser parser = new ProtocolV2Parser(
+				ConfigBuilder.start().allowRefInWant().done());
+		FetchV2Request request = parser.parseFetchRequest(pckIn);
+		assertThat(request.getWantedRefs(), hasItems("HEAD"));
+	}
+
+	@Test
+	public void testFetchRejectsTraversalWantRef() throws IOException {
+		PacketLineIn pckIn = formatAsPacketLine(PacketLineIn.delimiter(),
+				"want e4980cdc48cfa1301493ca94eb70523f6788b819",
+				"want-ref refs/heads/../../../victim/refs/private/admin",
+				PacketLineIn.end());
+
+		ProtocolV2Parser parser = new ProtocolV2Parser(
+				ConfigBuilder.start().allowRefInWant().done());
+		assertThrows(PackProtocolException.class,
+				() -> parser.parseFetchRequest(pckIn));
+	}
+
+	@Test
 	public void testLsRefsRefPrefixes() throws IOException {
 		PacketLineIn pckIn = formatAsPacketLine(PacketLineIn.delimiter(),
 				"ref-prefix refs/for", "ref-prefix refs/heads",
diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/UploadPackLsRefsFileRepositoryTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/UploadPackLsRefsFileRepositoryTest.java
index 7d5fc61..3159723 100644
--- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/UploadPackLsRefsFileRepositoryTest.java
+++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/UploadPackLsRefsFileRepositoryTest.java
@@ -10,18 +10,25 @@
 package org.eclipse.jgit.transport;
 
 import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
 import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.assertTrue;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import java.nio.charset.StandardCharsets;
 import java.util.Objects;
-import java.util.function.Consumer;
 
 import org.eclipse.jgit.internal.storage.file.FileRepository;
 import org.eclipse.jgit.junit.LocalDiskRepositoryTestCase;
 import org.eclipse.jgit.junit.TestRepository;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectInserter;
+import org.eclipse.jgit.lib.RefUpdate;
 import org.eclipse.jgit.lib.Sets;
 import org.eclipse.jgit.revwalk.RevCommit;
 import org.eclipse.jgit.revwalk.RevTag;
@@ -65,16 +72,43 @@ public void testV2LsRefsPeel() throws Exception {
 		assertTrue(PacketLineIn.isEnd(pckIn.readString()));
 	}
 
-	private ByteArrayInputStream uploadPackV2(String... inputLines)
+	@Test
+	public void testV2LsRefsRejectsPathTraversalRefPrefix()
 			throws Exception {
-		return uploadPackV2(null, inputLines);
+		try (FileRepository source = createBareRepository();
+				FileRepository victim = createBareRepository()) {
+			ObjectId admin = writeLooseRef(victim, "refs/private/admin",
+					"private object in victim repository");
+			ObjectId deploy = writeLooseRef(victim, "refs/private/deploy",
+					"second private object in victim repository");
+
+			assertNull(source.exactRef("refs/private/admin"));
+			assertNull(source.exactRef("refs/private/deploy"));
+			assertTrue(!source.getObjectDatabase().has(admin));
+			assertTrue(!source.getObjectDatabase().has(deploy));
+
+			String prefix = "refs/heads/../../../"
+					+ victim.getDirectory().getName() + "/refs/private/";
+			UploadPackInternalServerErrorException e = assertThrows(
+					UploadPackInternalServerErrorException.class,
+					() -> uploadPackV2(source, "command=ls-refs\n",
+							PacketLineIn.delimiter(), "ref-prefix " + prefix,
+							PacketLineIn.end()));
+
+			assertThat(e.getCause().getMessage(),
+					containsString("Invalid ref name: " + prefix));
+		}
 	}
 
-	private ByteArrayInputStream uploadPackV2(
-			Consumer<UploadPack> postConstructionSetup, String... inputLines)
+	private ByteArrayInputStream uploadPackV2(String... inputLines)
 			throws Exception {
-		ByteArrayInputStream recvStream = uploadPackV2Setup(
-				postConstructionSetup, inputLines);
+		return uploadPackV2(server, inputLines);
+	}
+
+	private ByteArrayInputStream uploadPackV2(FileRepository repository,
+			String... inputLines) throws Exception {
+		ByteArrayInputStream recvStream = uploadPackV2Setup(repository,
+				inputLines);
 		PacketLineIn pckIn = new PacketLineIn(recvStream);
 
 		// drain capabilities
@@ -85,16 +119,13 @@ private ByteArrayInputStream uploadPackV2(
 	}
 
 	private ByteArrayInputStream uploadPackV2Setup(
-			Consumer<UploadPack> postConstructionSetup, String... inputLines)
+			FileRepository repository, String... inputLines)
 			throws Exception {
 
 		ByteArrayInputStream send = linesAsInputStream(inputLines);
 
-		server.getConfig().setString("protocol", null, "version", "2");
-		UploadPack up = new UploadPack(server);
-		if (postConstructionSetup != null) {
-			postConstructionSetup.accept(up);
-		}
+		repository.getConfig().setString("protocol", null, "version", "2");
+		UploadPack up = new UploadPack(repository);
 		up.setExtraParameters(Sets.of("version=2"));
 
 		ByteArrayOutputStream recv = new ByteArrayOutputStream();
@@ -103,6 +134,25 @@ private ByteArrayInputStream uploadPackV2Setup(
 		return new ByteArrayInputStream(recv.toByteArray());
 	}
 
+	private static ObjectId writeLooseRef(FileRepository repository,
+			String name, String contents) throws IOException {
+		ObjectId oid;
+		try (ObjectInserter inserter = repository.newObjectInserter()) {
+			oid = inserter.insert(Constants.OBJ_BLOB,
+					contents.getBytes(StandardCharsets.UTF_8));
+			inserter.flush();
+		}
+
+		RefUpdate update = repository.updateRef(name);
+		update.setNewObjectId(oid);
+		update.setForceUpdate(true);
+		RefUpdate.Result result = update.update();
+		assertTrue(result == RefUpdate.Result.NEW
+				|| result == RefUpdate.Result.FORCED
+				|| result == RefUpdate.Result.NO_CHANGE);
+		return oid;
+	}
+
 	private static ByteArrayInputStream linesAsInputStream(String... inputLines)
 			throws IOException {
 		try (ByteArrayOutputStream send = new ByteArrayOutputStream()) {
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/transport/ProtocolV2Parser.java b/org.eclipse.jgit/src/org/eclipse/jgit/transport/ProtocolV2Parser.java
index e437f22..eedcc49 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/transport/ProtocolV2Parser.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/transport/ProtocolV2Parser.java
@@ -39,7 +39,9 @@
 import org.eclipse.jgit.errors.InvalidObjectIdException;
 import org.eclipse.jgit.errors.PackProtocolException;
 import org.eclipse.jgit.internal.JGitText;
+import org.eclipse.jgit.lib.Constants;
 import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
 
 /**
  * Parse the incoming git protocol lines from the wire and translate them into a
@@ -134,8 +136,12 @@ FetchV2Request parseFetchRequest(PacketLineIn pckIn)
 						.fromString(line2.substring(PACKET_WANT.length())));
 			} else if (transferConfig.isAllowRefInWant()
 					&& line2.startsWith(PACKET_WANT_REF)) {
-				reqBuilder.addWantedRef(
-						line2.substring(PACKET_WANT_REF.length()));
+				String refName = line2.substring(PACKET_WANT_REF.length());
+				if (!isValidRefName(refName)) {
+					throw new PackProtocolException(MessageFormat
+							.format(JGitText.get().invalidRefName, refName));
+				}
+				reqBuilder.addWantedRef(refName);
 			} else if (line2.startsWith(PACKET_HAVE)) {
 				reqBuilder.addPeerHas(ObjectId
 						.fromString(line2.substring(PACKET_HAVE.length())));
@@ -260,7 +266,12 @@ LsRefsV2Request parseLsRefsRequest(PacketLineIn pckIn)
 			} else if (line2.equals("symrefs")) { //$NON-NLS-1$
 				builder.setSymrefs(true);
 			} else if (line2.startsWith("ref-prefix ")) { //$NON-NLS-1$
-				prefixes.add(line2.substring("ref-prefix ".length())); //$NON-NLS-1$
+				String prefix = line2.substring("ref-prefix ".length()); //$NON-NLS-1$
+				if (!isValidRefPrefix(prefix)) {
+					throw new PackProtocolException(MessageFormat
+							.format(JGitText.get().invalidRefName, prefix));
+				}
+				prefixes.add(prefix);
 			} else {
 				throw new PackProtocolException(MessageFormat
 						.format(JGitText.get().unexpectedPacketLine, line2));
@@ -270,6 +281,20 @@ LsRefsV2Request parseLsRefsRequest(PacketLineIn pckIn)
 		return builder.setRefPrefixes(prefixes).build();
 	}
 
+	private static boolean isValidRefPrefix(String prefix) {
+		if (prefix.isEmpty()) {
+			return true;
+		}
+		String refName = prefix.endsWith("/") //$NON-NLS-1$
+				? prefix + "x" //$NON-NLS-1$
+				: prefix + "/x"; //$NON-NLS-1$
+		return Repository.isValidRefName(refName);
+	}
+
+	private static boolean isValidRefName(String name) {
+		return Constants.HEAD.equals(name) || Repository.isValidRefName(name);
+	}
+
 	ObjectInfoRequest parseObjectInfoRequest(PacketLineIn pckIn)
 			throws PackProtocolException, IOException {
 		ObjectInfoRequest.Builder builder = ObjectInfoRequest.builder();