Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- **BREAKING**: An empty or whitespace-only answer to `git rev-parse --show-object-format` is no longer read as a SHA-1 repository. No git prints nothing: git 2.29 and later print `sha1` or `sha256`, and older git prints the option back, which is still read as `sha1`. An empty answer comes from a custom runner or `plumbing` object that returns `''` for calls it does not handle, and reading it as `sha1` and remembering it let a 40-digit id through to git in a SHA-256 repository, where git expands it as an abbreviation. `updateRef()`, and `writeTree()` and `writeCommit()` given object ids, now refuse it with an `UnsupportedCapabilityError`, run no write, and read the format again on the next call. A custom runner that relied on `''` meaning SHA-1 must answer the repository's format, `sha1` or `sha256`, or let git answer (git-stunts/plumbing#47).

### Fixed

- **Gitlink entries in written trees**: `GitTree.toMktreeFormat()` takes each entry's type from its mode, so a mode-`160000` gitlink (a submodule commit) is written as `160000 commit <id>\t<path>`, not `blob`. `GitPersistenceService.writeTree()` can now write a tree that holds a gitlink entry, in SHA-1 and SHA-256 repositories; before, `git mktree` refused it with `object type (blob) doesn't match mode type (commit)`. This writes the tree entry only: plumbing does not write `.gitmodules`, and it does not clone, fetch or update submodules. Every other tree is written as before (git-stunts/plumbing#46).

### Security

- **Tree entry paths can no longer add, cut or unquote `git mktree` entries**: `git mktree` reads one entry per line, so a newline in a caller-supplied path such as `"a\n160000 commit <id>\tsmuggled"` ended its line early and wrote an entry the caller never supplied, and a NUL byte cut the name git kept. A tree entry path holding a newline or a NUL byte is now a `ValidationError`, from `GitTreeEntry`, `GitTree`, `GitTreeBuilder` and `createCommitFromFiles()`, before any git runs. `writeTree()` reads and checks every path once more as it serializes the tree and writes the value it checked, so a path changed in an entry after it was built is refused too, and `createCommitFromFiles()` checks every file path before it writes any blob. git also C-unquoted a path that starts with `"` and dropped anything after the closing quote, so `"x"` was stored as `x`, `"\056git"` as `.git`, `"same"` beside `same` as a duplicate entry, and a lone `"` was refused; such a path is now written C-quoted, so git stores it byte for byte. Every path that was accepted before and holds neither byte is still accepted. A path holding an unpaired UTF-16 surrogate is still written as U+FFFD, as before. Releases v2.7.0 through 4.0.0-rc.1 are affected; to check trees already written from untrusted names, compare `git ls-tree -z` with the names supplied, or run `git fsck --strict`, which reports `.git` entries and duplicate entries (git-stunts/plumbing#84).
Expand Down
6 changes: 4 additions & 2 deletions src/domain/entities/GitTree.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ export default class GitTree {
/**
* Serializes the tree entries into the format expected by `git mktree`.
* Format: <mode> <type> <sha>\t<path>
*
* The type is the one the mode names (`tree`, `commit` for a gitlink, or
* `blob`), since `git mktree` refuses a line whose type and mode disagree.
* @returns {string}
* @throws {ValidationError} For an entry whose path holds a newline or a NUL
* byte, even one written into the entry after it was built, since git would
Expand All @@ -115,8 +118,7 @@ export default class GitTree {
.map((entry, index) => {
const path = entry.path;
GitTreeEntry.assertPath(path, 'GitTree.toMktreeFormat', index);
const type = entry.isTree() ? 'tree' : 'blob';
return `${entry.mode} ${type} ${entry.sha}\t${MktreePathEncoder.encode(path)}`;
return `${entry.mode} ${entry.type()} ${entry.sha}\t${MktreePathEncoder.encode(path)}`;
})
.join('\n') + '\n';
}
Expand Down
92 changes: 92 additions & 0 deletions test/GitlinkTreeEntries.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import GitPlumbing, { GitBlob, GitPersistenceService, GitTree } from '../index.js';
import GitTreeEntry from '../src/domain/entities/GitTreeEntry.js';

// Medium: real git on a fresh bare repository per test (git-stunts/plumbing#46).
//
// Oracle: git itself. `git mktree` refuses a line whose type does not match
// its mode, so writeTree() of a tree holding a gitlink (mode 160000) succeeds
// only if the gitlink is labelled `commit`. The written tree is read back with
// `git ls-tree`, run outside plumbing through node:child_process. The gitlink
// names a commit that is not in the object database: git does not require a
// submodule's commit to exist, and writeTree() does not pass `--missing`.
//
// The whole file runs with GIT_CONFIG_GLOBAL=/dev/null, GIT_CONFIG_NOSYSTEM=1
// and HOME in a temporary directory, so the host's configuration reaches
// neither plumbing nor the oracle.
const GITLINK = { sha1: '1'.repeat(40), sha256: '2'.repeat(64) };
const PINNED = { GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_ATTR_NOSYSTEM: '1' };

let home;

/** Runs real git outside plumbing, with none of the host's configuration. */
function gitOutside(cwd, args) {
const result = spawnSync('git', args, {
cwd,
env: { PATH: process.env.PATH, HOME: home, ...PINNED },
});
return { code: result.status, stdout: String(result.stdout ?? ''), stderr: String(result.stderr ?? '') };
}

// One enclosing suite, so the environment hooks below are suite hooks: Deno's
// BDD runner refuses a global hook once a test is registered.
describe('writeTree with a gitlink entry', () => {
let savedEnvironment;
let repositories;

beforeAll(() => {
home = fs.mkdtempSync(path.join(os.tmpdir(), 'git-plumbing-home-'));
savedEnvironment = Object.fromEntries(
['HOME', 'XDG_CONFIG_HOME', ...Object.keys(PINNED)].map((key) => [key, process.env[key]])
);
Object.assign(process.env, PINNED, { HOME: home });
delete process.env.XDG_CONFIG_HOME;
});

afterAll(() => {
for (const [key, value] of Object.entries(savedEnvironment)) {
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
fs.rmSync(home, { recursive: true, force: true });
});

beforeEach(() => {
repositories = [];
});

afterEach(() => {
for (const repoPath of repositories) {
fs.rmSync(repoPath, { recursive: true, force: true });
}
});

for (const format of ['sha1', 'sha256']) {
it(`writes a gitlink as a commit entry in a ${format} repository`, async () => {
const repoPath = fs.mkdtempSync(path.join(os.tmpdir(), `git-plumbing-gitlink-${format}-`));
repositories.push(repoPath);
expect(gitOutside(repoPath, ['init', '--bare', `--object-format=${format}`]).code).toBe(0);
const git = await GitPlumbing.createDefault({ cwd: repoPath });
const persistence = new GitPersistenceService({ plumbing: git });

const blob = await persistence.writeBlob(GitBlob.fromContent('file content'));
const tree = new GitTree(null, [
new GitTreeEntry({ path: 'f.txt', sha: blob, mode: '100644' }),
new GitTreeEntry({ path: 'sub', sha: GITLINK[format], mode: '160000' }),
]);

const treeId = await persistence.writeTree(tree);

expect(gitOutside(repoPath, ['cat-file', '-t', treeId.toString()]).stdout).toBe('tree\n');
const listing = gitOutside(repoPath, ['ls-tree', treeId.toString()]);
expect(listing.code).toBe(0);
expect(listing.stdout).toBe(`100644 blob ${blob}\tf.txt\n160000 commit ${GITLINK[format]}\tsub\n`);
});
}
});
1 change: 1 addition & 0 deletions test/deno_entry.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import './RepositoryFormatting.test.js';
import './ShellRunner.test.js';
import './ChangedFiles.test.js';
import './Sha256Repositories.test.js';
import './GitlinkTreeEntries.test.js';
import './TreeEntryPathInjection.test.js';
import './ObjectFormatServices.test.js';
import './ObjectFormatReads.test.js';
Expand Down
23 changes: 23 additions & 0 deletions test/domain/entities/GitTree.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,29 @@ describe('GitTree', () => {
expect(format).toBe(`100644 blob ${VALID_SHA}\tfile.txt\n040000 tree ${EMPTY_TREE_SHA}\tsubdir\n`);
});

// git-stunts/plumbing#46: git mktree refuses a line whose type does not match
// its mode, so a gitlink (mode 160000) must be labelled commit.
it('labels a gitlink entry commit in mktree format', () => {
const gitlink = new GitTreeEntry({ path: 'sub', sha: GitSha.from(VALID_SHA), mode: '160000' });
const tree = new GitTree(null, [gitlink]);

expect(tree.toMktreeFormat()).toBe(`160000 commit ${VALID_SHA}\tsub\n`);
});

it('labels every tree mode with the type that mode names', () => {
const modes = ['040000', '100644', '100755', '120000', '160000'];
const entries = modes.map((mode, i) => new GitTreeEntry({ path: `p${i}`, sha: GitSha.from(VALID_SHA), mode }));
const tree = new GitTree(null, entries);

expect(tree.toMktreeFormat()).toBe(
`040000 tree ${VALID_SHA}\tp0\n` +
`100644 blob ${VALID_SHA}\tp1\n` +
`100755 blob ${VALID_SHA}\tp2\n` +
`120000 blob ${VALID_SHA}\tp3\n` +
`160000 commit ${VALID_SHA}\tp4\n`
);
});

it('returns single newline for empty tree mktree format', () => {
const tree = new GitTree(null, []);
expect(tree.toMktreeFormat()).toBe('\n');
Expand Down
Loading