Skip to content

Commit 4e5c68b

Browse files
committed
Bind mutation reviews to HEAD targets and locked branch tips
1 parent 66d5b35 commit 4e5c68b

8 files changed

Lines changed: 359 additions & 7 deletions

File tree

‎README.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,19 @@ checks remain enabled. Authorized operations honor Git hooks, filters, signing,
3737
credential helpers and SSH configuration. Prompt replies use private,
3838
operation-bound sockets and are excluded from diagnostics.
3939

40-
Mutation requests bind reviewed HEAD/index/content identities. Granular staging
40+
Mutation requests bind reviewed HEAD/index/content identities. Index review
41+
tokens also bind the current symbolic HEAD target, so an external switch or
42+
rename to a branch at the same commit invalidates the old review. Granular staging
4143
uses an ephemeral alternate index while holding the actual Git index lock, then
4244
atomically installs that index; it never rewrites working files to stage them.
4345
Repository/common-directory advisory locks coordinate BusyStack processes. Git's
4446
locks and sequencer remain authoritative for other clients. Open-worktree leases
4547
protect worktrees used by BusyStack views. A cancelled process is reconciled;
4648
cancellation is separate from aborting a continuing operation. Push leases retain
4749
the exact remote tips reviewed, including across a background fetch.
50+
Branch deletion checks its reviewed tip inside Git's locked reference
51+
transaction with an operation-local native guard; it retains Git's own merged
52+
and worktree-occupancy checks and configured hooks.
4853
Worktree changes bind the reviewed checkout identity and status. Submodule
4954
updates bind the checked-out gitlink, coordinate initialized child repositories
5055
with their discovered superproject, and require separate execution grants for

‎lib/src/context.dart‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -163,8 +163,29 @@ final class GitContext {
163163
RepositoryId repo, {
164164
GitCancellation? cancellation,
165165
}) async {
166+
// Equal commit IDs do not identify the destination branch. In particular,
167+
// symbolic-ref or branch -m can retarget a reviewed commit without touching
168+
// the index. Bind its opaque review token to the resolved HEAD target too.
169+
Future<String> headTarget() async {
170+
final result = await runRepository(
171+
repo,
172+
['symbolic-ref', '--quiet', 'HEAD'],
173+
cancellation: cancellation,
174+
allowFailure: true,
175+
);
176+
if (result.success) return 'symbolic:${fingerprint(result.stdout)}';
177+
if (result.exitCode == 1) return 'detached';
178+
throw classifyGitFailure(result.diagnostic, exitCode: result.exitCode);
179+
}
180+
181+
final binding = await headTarget();
166182
final path = utf8.encode(await gitMetadataPath(this, repo, 'index'));
167-
if (!LinuxPaths.stat(path).exists) return 'absent';
183+
if (!LinuxPaths.stat(path).exists) {
184+
if (await headTarget() != binding) {
185+
throw const GitException(GitErrorCode.staleReview);
186+
}
187+
return fingerprint(utf8.encode('$binding:absent'));
188+
}
168189
final fd = LinuxPaths.secureOpen(path, readOnly: true);
169190
try {
170191
final before = LinuxPaths.descriptorStat(fd);
@@ -179,10 +200,11 @@ final class GitContext {
179200
)
180201
.first;
181202
if (before.stamp != LinuxPaths.descriptorStat(fd).stamp ||
182-
before.identity != LinuxPaths.stat(path).identity) {
203+
before.identity != LinuxPaths.stat(path).identity ||
204+
await headTarget() != binding) {
183205
throw const GitException(GitErrorCode.staleReview);
184206
}
185-
return digest.toString();
207+
return fingerprint([...utf8.encode(binding), 0, ...digest.bytes]);
186208
} finally {
187209
LinuxPaths.close(fd);
188210
}

‎lib/src/engine.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ final class GitEngine implements GitClient, GitWorkflowClient, GitPatchClient {
3737
_repositories = RepositoryQueries(_ctx);
3838
_contents = ContentQueries(_ctx);
3939
_index = IndexMutations(_ctx, _contents);
40-
_references = ReferenceWorkflows(_ctx);
40+
_references = ReferenceWorkflows(_ctx, helperPath: helperPath);
4141
_network = NetworkWorkflows(_ctx, _references);
4242
_history = HistoryWorkflows(_ctx, _contents);
4343
_creation = CreationWorkflows(_ctx, _repositories);

‎lib/src/reference_workflows.dart‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
import 'dart:convert';
22
import 'dart:io';
3+
import 'dart:math';
34
import 'client.dart';
45
import 'context.dart';
56
import 'byte_text.dart';
67
import 'models.dart';
78
import 'parsers.dart';
89
import 'runner.dart';
10+
import 'native_helper.dart';
911

1012
final class ReferenceWorkflows {
11-
const ReferenceWorkflows(this.ctx);
13+
const ReferenceWorkflows(this.ctx, {this.helperPath});
1214
final GitContext ctx;
15+
final String? helperPath;
1316
Future<void> branchName(RepositoryId repo, String name) async {
1417
if (name.isEmpty || name.startsWith('-') || name.contains('\u0000'))
1518
throw const GitException(GitErrorCode.invalidRequest);
@@ -102,6 +105,7 @@ final class ReferenceWorkflows {
102105
Map<String, String> operationEnvironment = const {},
103106
}) async {
104107
final List<String> args;
108+
var safetyArguments = <String>[];
105109
List<int>? input;
106110
switch (request) {
107111
case BranchMutation():
@@ -153,6 +157,48 @@ final class ReferenceWorkflows {
153157
case BranchAction.delete:
154158
// Safe delete has no automatic force fallback. An explicit second
155159
// review may choose forceDeleteReviewed for an unmerged branch.
160+
final tip = request.expectedTip;
161+
if (tip == null)
162+
throw const GitException(GitErrorCode.invalidRequest);
163+
final enabled = await ctx.runRepository(
164+
repo,
165+
[
166+
'config',
167+
'--type=bool',
168+
'--get',
169+
'hook.reference-transaction.enabled',
170+
],
171+
passive: false,
172+
allowFailure: true,
173+
);
174+
if (enabled.success && oneLine(enabled.text) == 'false') {
175+
throw const GitException(
176+
GitErrorCode.invalidRequest,
177+
diagnostic:
178+
'Branch deletion needs its reference-transaction safety guard. Enable hook.reference-transaction.enabled, then review again.',
179+
);
180+
}
181+
if (!enabled.success && enabled.exitCode != 1)
182+
throw enabled.failure;
183+
final helper = installedGitHelper(preferred: helperPath);
184+
if (helper == null)
185+
throw const GitException(
186+
GitErrorCode.unavailable,
187+
diagnostic: 'Repair the installed native Git safety helper.',
188+
);
189+
String quote(String s) => "'${s.replaceAll("'", "'\\''")}'";
190+
final hook =
191+
'busystack-review-${List.generate(16, (_) => Random.secure().nextInt(256).toRadixString(16).padLeft(2, '0')).join()}';
192+
safetyArguments = [
193+
'-c',
194+
'hook.reference-transaction.enabled=true',
195+
'-c',
196+
'hook.$hook.event=reference-transaction',
197+
'-c',
198+
'hook.$hook.enabled=true',
199+
'-c',
200+
'hook.$hook.command=${quote(helper)} --reference-guard ${quote('refs/heads/${request.name}')} ${quote(tip.value)}',
201+
];
156202
args = [
157203
'branch',
158204
request.forceDeleteReviewed ? '-D' : '--delete',
@@ -264,7 +310,7 @@ final class ReferenceWorkflows {
264310
}
265311
return ctx.runRepository(
266312
repo,
267-
args,
313+
[...safetyArguments, ...args],
268314
passive: false,
269315
input: input,
270316
cancellation: cancellation,

‎lib/src/runner.dart‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,9 @@ final class ProcessGitRunner implements GitRunner {
203203
'LC_ALL': 'C.UTF-8',
204204
'GIT_LITERAL_PATHSPECS': '1',
205205
...environment,
206+
// Only the selected runner may name the executable used by the
207+
// operation-local reference guard. Never trust an inherited value.
208+
'BUSYSTACK_GIT_RUNTIME': executable,
206209
},
207210
);
208211
} on ProcessException {
@@ -370,6 +373,8 @@ GitException classifyGitFailure(
370373
}) {
371374
final text = diagnostic.toLowerCase();
372375
final code = switch (text) {
376+
_ when text.contains('busystack reviewed reference changed') =>
377+
GitErrorCode.staleReview,
373378
_ when text.contains('dubious ownership') => GitErrorCode.ownership,
374379
_
375380
when text.contains('author identity unknown') ||

‎native/git_helper.c‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#define _GNU_SOURCE
22
#include <arpa/inet.h>
33
#include <errno.h>
4+
#include <fcntl.h>
45
#include <signal.h>
56
#include <stdint.h>
67
#include <stdio.h>
@@ -96,11 +97,73 @@ static int git_argv(int argc, char **argv) {
9697
return 1;
9798
}
9899

100+
/* Git invokes this extra, operation-local hook with the ref locks held. The
101+
* transaction's old-value can be all zeroes even when deleting an existing
102+
* branch, so read the actual ref through the same trusted Git executable.
103+
* User hooks remain Git's responsibility; no repository metadata is written. */
104+
static int reference_guard(int argc, char **argv) {
105+
if (argc != 5) return 1;
106+
if (strcmp(argv[4], "prepared") != 0) return 0;
107+
const char *git = getenv("BUSYSTACK_GIT_RUNTIME"), *ref = argv[2], *expected = argv[3];
108+
size_t oid_length = strlen(expected);
109+
if (!git || git[0] != '/' || strncmp(ref, "refs/heads/", 11) != 0 ||
110+
strlen(ref) > 262144 || (oid_length != 40 && oid_length != 64)) return 1;
111+
for (size_t i = 0; i < oid_length; ++i) if (hex_digit(expected[i]) < 0) return 1;
112+
alarm(10);
113+
char *line = malloc(262146);
114+
if (!line) return 1;
115+
size_t total = 0;
116+
int matched = 0;
117+
while (fgets(line, 262146, stdin)) {
118+
size_t length = strlen(line);
119+
total += length;
120+
if (!length || line[length - 1] != '\n' || total > 8388608) { free(line); return 1; }
121+
line[length - 1] = 0;
122+
char *first = strchr(line, ' '), *second = first ? strchr(first + 1, ' ') : NULL;
123+
if (!second) { free(line); return 1; }
124+
if (strcmp(second + 1, ref) == 0) matched = 1;
125+
}
126+
free(line);
127+
if (ferror(stdin)) return 1;
128+
if (!matched) return 0;
129+
int descriptors[2];
130+
if (pipe2(descriptors, O_CLOEXEC) < 0) return 1;
131+
pid_t owner = getpid(), child = fork();
132+
if (child < 0) { close(descriptors[0]); close(descriptors[1]); return 1; }
133+
if (child == 0) {
134+
close(descriptors[0]);
135+
if (prctl(PR_SET_PDEATHSIG, SIGKILL) < 0 || getppid() != owner ||
136+
dup2(descriptors[1], STDOUT_FILENO) < 0) _exit(1);
137+
close(descriptors[1]);
138+
char *arguments[] = {(char *) git, "--no-pager", "-c", "core.fsmonitor=false",
139+
"rev-parse", "--verify", "--quiet", "--end-of-options", (char *) ref, NULL};
140+
execv(git, arguments); _exit(127);
141+
}
142+
close(descriptors[1]);
143+
char actual[67]; size_t count = 0;
144+
while (count < sizeof(actual)) {
145+
ssize_t received = read(descriptors[0], actual + count, sizeof(actual) - count);
146+
if (received < 0 && errno == EINTR) continue;
147+
if (received <= 0) break;
148+
count += (size_t) received;
149+
}
150+
close(descriptors[0]);
151+
int status;
152+
while (waitpid(child, &status, 0) < 0) { if (errno != EINTR) return 1; }
153+
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0 || count != oid_length + 1 ||
154+
actual[oid_length] != '\n' || memcmp(actual, expected, oid_length) != 0) {
155+
fputs("BusyStack reviewed reference changed; refresh and review again.\n", stderr);
156+
return 1;
157+
}
158+
return 0;
159+
}
160+
99161
/* Installed prompt helper: no SDK or repository-owned helper scripts.
100162
* Socket requests are authenticated and operation scoped. */
101163
int main(int argc, char **argv) {
102164
if (argc >= 3 && strcmp(argv[1], "--supervise") == 0) return supervise(argc, argv);
103165
if (argc >= 3 && strcmp(argv[1], "--git-argv") == 0) return git_argv(argc, argv);
166+
if (argc >= 2 && strcmp(argv[1], "--reference-guard") == 0) return reference_guard(argc, argv);
104167
const char *socket_path = getenv("BUSYSTACK_GIT_PROMPT_SOCKET");
105168
const char *token = getenv("BUSYSTACK_GIT_PROMPT_TOKEN");
106169
const char *operation = getenv("BUSYSTACK_GIT_OPERATION");

0 commit comments

Comments
 (0)