1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Replacing a file without a window in which it is half-written.
//!
//! Two files in this tool decide whether encryption happens at all: the managed
//! section of `.gitattributes`, which carries `* filter=git-xcrypt`, and
//! `.git/config`, which carries the driver registration. `fs::write` truncates
//! first and writes second, so a failure between the two — a full disk, a
//! crash, a power loss — leaves whichever file it hit short or empty. Git then
//! sees no filter at all and treats every path as plain: `git add` on a secret
//! succeeds with exit code 0 and stores the plaintext, with no signal to the
//! user. Truncating `.gitattributes` also loses whatever the user wrote outside
//! our markers, which the section-editing code promises to preserve.
//!
//! Writing a sibling file and renaming it over the target closes that window:
//! `rename` replaces the entry in one step on every platform this tool targets
//! (`MoveFileEx` with `MOVEFILE_REPLACE_EXISTING` on Windows), so a reader sees
//! either the old file or the new one.
//!
//! The key file goes through [`write_owner_only`] rather than [`write`]: it has
//! the same half-written failure — a truncated key file is a repository nobody
//! can decrypt again — but the opposite permission rule, since inheriting a
//! loose mode from whatever was there before is exactly what a key must not do.
//!
//! The temporary file is created with `O_EXCL` and an unguessable name, which is
//! not tidiness. Without `O_EXCL` the name is merely a name: anyone able to
//! write the destination directory could pre-create it as a symlink, and
//! `File::create` would follow the link, write the master key wherever it points
//! and then rename the link over the destination. `export-key ~/keys/repo.key`
//! is a private directory, but `export-key /tmp/repo.key` is not, and the
//! command whose whole job is to hand over a key is the wrong place to rely on
//! the user picking a safe directory.
use OsString;
use fs;
use Write as _;
use ;
use crate::;
/// How the replacement file's permissions are decided.
/// Writes `contents` to `path`, replacing it in one step.
///
/// The temporary file lives beside the target, because `rename` across
/// filesystems is not a rename at all and would fall back to a copy.
///
/// Three limits worth knowing rather than discovering.
///
/// A target that is a symlink is replaced by a regular file, where `fs::write`
/// would have followed the link — `.gitattributes` under a dotfile manager is
/// the case where that shows. A target that is one of several hard links to the
/// same inode loses the link for the same reason. And the temporary file is only
/// cleaned up on a returned error, so a process killed outright can leave one
/// behind.
///
/// That last one is not always harmless. `unlock` replaces working-tree files
/// through here, so on that path the leftover holds a **decrypted secret** under
/// a name no `.git-xcrypt` pattern was written for — `secrets/` still covers it,
/// `*.env` does not. It inherits the target's permissions, which for a file git
/// checked out means it is no more readable than the file it replaces, but a
/// later `git add -A` could store it in the clear. There is no portable way to
/// clean up after `SIGKILL`; the residue is recorded here rather than hidden.
/// Every such file is recognised by [`is_temporary_name`], which is what the
/// user documentation has to tell people to look for after a killed `unlock` —
/// and what `lock` sweeps before it encrypts, since a plaintext leftover would
/// otherwise survive the one command whose job is to leave none.
///
/// # Errors
///
/// [`Error::Io`] when the temporary file cannot be created, written, flushed or
/// renamed. On failure the target is left exactly as it was.
/// Writes `contents` to `path` with owner-only permissions, in one step.
///
/// The same replacement as [`write`], with two differences that matter only for
/// key material: the file is created `0600` before a single byte reaches it, and
/// the target's permissions are **not** inherited — a key file that was somehow
/// left world readable must not stay that way.
///
/// **On Windows there is no mode to set, so nothing here narrows anything**: the
/// file inherits the ACL of the directory it is created in. For the repository's
/// own key that is the protection git gives `.git/config`, which is the same
/// protection as the rest of the checkout. For `export-key` the user picks the
/// directory, so the directory *is* the protection. Weaker than `0600` either
/// way, and recorded as a limitation in `README.md` §Known limitations and in
/// `context/foundation/zalozenia.md` — the founding document claimed owner-only
/// ACLs here until 2026-08-05, which was never true of any build.
///
/// # Errors
///
/// As [`write`].
/// Flushes the directory entry the rename just created.
///
/// Without it the promise above holds only where the target already existed: a
/// crash right after `init` could otherwise leave a repository with a key, a
/// filter registration and no `.gitattributes` at all — which is the state where
/// git stores plaintext and reports success. Best effort, and a no-op on
/// platforms that do not allow opening a directory.
/// Creates a fresh file next to `path`, and only ever a fresh one.
///
/// `create_new` is `O_EXCL`: it fails rather than opening anything that is
/// already there, symlink included, which is what keeps a pre-created link from
/// redirecting the write. The name is random rather than derived from the
/// process id, so it cannot be predicted and pre-created in the first place;
/// `O_EXCL` alone would then turn the attack into a denial of service, hence the
/// retries.
///
/// A key file is created at `0600` from the outset, so its content is never on
/// disk under a wider mode even for an instant.
/// What every temporary name carries between the target's name and `.tmp`.
const MARKER: & = b".git-xcrypt-";
/// How many random bytes go into a temporary name.
const RANDOM_LEN: usize = 8;
/// The longest single name a filesystem will normally take, in bytes.
///
/// `NAME_MAX` is 255 on ext4, APFS, HFS+, XFS and NTFS alike. Nothing here reads
/// the real limit — there is no portable way to — so this is the floor every
/// target platform meets.
const MAX_NAME: usize = 255;
/// A sibling name no one can guess and therefore no one can pre-create.
///
/// The target's own name is **shortened when the suffix would not fit**. Git
/// puts no such ceiling on a path: a file whose name is 224 bytes or longer
/// commits and checks out perfectly, and before this the sibling name came to
/// 256 bytes and `create_temporary` failed with `ENAMETOOLONG`. Measured, on a
/// repository holding one such file: `lock` exited 1 saying "running lock again
/// finishes the job", which was false — it failed identically for ever, so the
/// repository could never be closed and the secret stayed in the clear.
///
/// The cost of shortening is that [`strip_temporary_suffix`] then reconstructs a
/// *truncated* target, so residue left by a killed run on such a file may not be
/// recognised as belonging to a declared path and may go unswept. That is the
/// same outcome residue under an undeclared path already has, and it replaces a
/// command that could not run at all.
/// `name`, cut down to at most `limit` bytes.
///
/// A file name is an arbitrary byte string on Unix, so the cut is by bytes and
/// may land inside a multi-byte character — which is fine for a name nothing
/// ever decodes. On other platforms the name goes through its lossy text form,
/// which is what every other path in this crate does with a Windows name.
/// The target a temporary file was named after, if `name` is one of ours.
///
/// A process killed outright cannot clean up after itself, and on the `unlock`
/// and `lock` paths the residue holds a **decrypted secret**. `lock` promises
/// that no plaintext of a selected path survives it, so it has to recognise
/// residue — and, because it deletes what it recognises, it has to recognise it
/// *narrowly*. Returning the target rather than a yes/no is what lets the caller
/// add the second condition that makes deletion safe: only sweep residue whose
/// target the declaration actually selects.
///
/// Deliberately exact. The marker must be followed by exactly [`RANDOM_LEN`]
/// bytes of **lowercase** hex — the only kind [`temporary_name`] emits — then
/// `.tmp`, and something must precede the marker, because these names are always
/// built from a target's own name. A file a user happens to have called
/// `notes.git-xcrypt-draft.tmp` is not matched, and neither is
/// `notes.git-xcrypt-DEADBEEFDEADBEEF.tmp`.
/// Whether the target [`strip_temporary_suffix`] reconstructed may be **cut**.
///
/// [`temporary_name`] shortens the target when the suffix would not otherwise
/// fit, so above a certain length the name in a temporary file no longer
/// identifies its target — and a caller deciding what to do with residue is then
/// deciding about a file it cannot name. `lock` is that caller, and the answer
/// has to be "refuse", not "guess": measured on this build, a repository
/// declaring `*.env` with a 230-byte file name, and residue placed exactly as a
/// killed run leaves it, printed `nothing declares its target, so it was left
/// alone`, deleted the key and **exited 0** over `AWS_SECRET=hunter2` sitting in
/// the working tree in the clear — untracked, and not matching `*.env`, so the
/// next `git add -A` would have committed it that way.
///
/// Answered from the temporary name's own length rather than the target's,
/// because that is the side a caller holds, and with **three bytes of slack**:
/// the Unix arm of [`shorten`] cuts on a byte boundary and lands exactly on the
/// limit, but the other arm backs off to a character boundary and can stop a
/// little short. Being wrong in this direction costs a refusal on a residue file
/// whose name is within three bytes of the ceiling and whose target is genuinely
/// undeclared — which is a file a user made themselves, since every temporary
/// file this crate writes sits beside a declared path or a bootstrap file. Being
/// wrong in the other direction costs a secret.