summaryrefslogtreecommitdiff
path: root/src/Agent.Windows/Recovery/TransactionalFileEditor.cs
blob: ff4ac5a73dc75dfe54e9b00aa9c1f7473131cc7f (plain)
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
using System.Security.Cryptography;
using System.Text;
using Agent.Core.Tools;
using Agent.Windows.Security;

namespace Agent.Windows.Recovery;

public sealed class TransactionalFileEditor(TaskResourceJournal journal, string backupRoot, long memoryBackupLimitBytes = 16 * 1024 * 1024)
{
    public FileEditTransaction Replace(string path, string content, string? expectedSha256 = null) => Replace(path, Encoding.UTF8.GetBytes(content), expectedSha256);

    public FileEditTransaction Replace(string path, ReadOnlySpan<byte> content, string? expectedSha256 = null)
    {
        string canonical = ResolvedPath.Resolve(path, requireExisting: false);
        bool existed = File.Exists(canonical);
        byte[]? original = existed ? File.ReadAllBytes(canonical) : null;
        string originalHash = original is null ? string.Empty : Convert.ToHexString(SHA256.HashData(original));
        if (expectedSha256 is not null && !originalHash.Equals(NormalizeHash(expectedSha256), StringComparison.Ordinal))
            throw new SandboxPolicyException("file.concurrent_change", "File hash does not match expected_sha256.");

        string backupPath = string.Empty;
        string inline = string.Empty;
        if (original is not null && original.LongLength > memoryBackupLimitBytes)
        {
            string directory = System.IO.Path.Combine(backupRoot, journal.TaskId.ToString("N"));
            Directory.CreateDirectory(directory);
            backupPath = System.IO.Path.Combine(directory, Guid.NewGuid().ToString("N") + ".backup");
            File.WriteAllBytes(backupPath, original);
        }
        else if (original is not null) inline = Convert.ToBase64String(original);

        string temporary = canonical + ".agent-mcp-" + Guid.NewGuid().ToString("N") + ".tmp";
        var data = new Dictionary<string, string>
        {
            ["existed"] = existed.ToString(), ["original_sha256"] = originalHash, ["original_base64"] = inline,
            ["backup_path"] = backupPath, ["temporary_path"] = temporary
        };
        Guid entryId = journal.Prepare("file.replace", canonical, data);
        File.WriteAllBytes(temporary, content);
        string replacementHash = Convert.ToHexString(SHA256.HashData(content));
        File.Move(temporary, canonical, overwrite: true);
        journal.MarkApplied(entryId, new Dictionary<string, string> { ["replacement_sha256"] = replacementHash });
        return new(journal, entryId, canonical, originalHash, replacementHash, backupPath, inline, existed);
    }

    public FileDeleteTransaction Delete(string path, string? expectedSha256 = null)
    {
        string canonical = ResolvedPath.Resolve(path);
        byte[] original = File.ReadAllBytes(canonical);
        string originalHash = Convert.ToHexString(SHA256.HashData(original));
        if (expectedSha256 is not null && !originalHash.Equals(NormalizeHash(expectedSha256), StringComparison.Ordinal))
            throw new SandboxPolicyException("file.concurrent_change", "File hash does not match expected_sha256.");
        string backupPath = string.Empty;
        string inline = string.Empty;
        if (original.LongLength > memoryBackupLimitBytes)
        {
            string directory = System.IO.Path.Combine(backupRoot, journal.TaskId.ToString("N"));
            Directory.CreateDirectory(directory);
            backupPath = System.IO.Path.Combine(directory, Guid.NewGuid().ToString("N") + ".backup");
            File.WriteAllBytes(backupPath, original);
        }
        else inline = Convert.ToBase64String(original);
        Guid entryId = journal.Prepare("file.delete", canonical, new Dictionary<string, string>
        {
            ["original_sha256"] = originalHash, ["original_base64"] = inline, ["backup_path"] = backupPath
        });
        File.Delete(canonical);
        journal.MarkApplied(entryId);
        return new(journal, entryId, canonical, originalHash, backupPath, inline);
    }

    public DirectoryMkdirTransaction Mkdir(string path)
    {
        string canonical = ResolvedPath.Resolve(path, requireExisting: false);
        bool existed = Directory.Exists(canonical);
        if (existed) throw new InvalidOperationException($"Directory already exists: '{canonical}'.");
        if (File.Exists(canonical)) throw new InvalidOperationException($"A file exists at the target path: '{canonical}'.");
        Guid entryId = journal.Prepare("dir.mkdir", canonical, new Dictionary<string, string> { ["existed"] = existed.ToString() });
        Directory.CreateDirectory(canonical);
        journal.MarkApplied(entryId);
        return new(journal, entryId, canonical);
    }

    public DirectoryRmdirTransaction Rmdir(string path)
    {
        string canonical = ResolvedPath.Resolve(path);
        if (!Directory.Exists(canonical)) throw new DirectoryNotFoundException($"Directory does not exist: '{canonical}'.");
        if (Directory.EnumerateFileSystemEntries(canonical, "*", SearchOption.TopDirectoryOnly).Any())
            throw new ToolValidationException("Directory is not empty. Remove contents first before removing the directory.");
        Guid entryId = journal.Prepare("dir.rmdir", canonical, new Dictionary<string, string>());
        Directory.Delete(canonical, recursive: false);
        journal.MarkApplied(entryId);
        return new(journal, entryId, canonical);
    }

    public FileRenameTransaction Rename(string sourcePath, string destinationPath)
    {
        string source = ResolvedPath.Resolve(sourcePath);
        string destination = ResolvedPath.Resolve(destinationPath, requireExisting: false);
        if (!File.Exists(source)) throw new FileNotFoundException($"Source file does not exist: '{source}'.");
        if (File.Exists(destination)) throw new ToolValidationException($"Destination already exists: '{destination}'. Rename overwrite is not allowed.");
        if (!source.StartsWith(System.IO.Path.GetPathRoot(source)!, StringComparison.OrdinalIgnoreCase) ||
            !destination.StartsWith(System.IO.Path.GetPathRoot(source)!, StringComparison.OrdinalIgnoreCase))
            throw new ToolValidationException("Cross-volume rename is not supported.");
        byte[] content = File.ReadAllBytes(source);
        string sourceHash = Convert.ToHexString(SHA256.HashData(content));
        Guid entryId = journal.Prepare("file.rename", source, new Dictionary<string, string>
        {
            ["destination_path"] = destination, ["source_sha256"] = sourceHash
        });
        File.Move(source, destination);
        journal.MarkApplied(entryId);
        return new(journal, entryId, source, destination, sourceHash);
    }

    private static string NormalizeHash(string hash) => hash.Replace("-", string.Empty, StringComparison.Ordinal).Trim().ToUpperInvariant();
}

public sealed class FileDeleteTransaction(TaskResourceJournal journal, Guid entryId, string path, string originalHash, string backupPath, string originalBase64)
{
    private bool _finished;
    public void Commit() { if (_finished) return; Cleanup(); journal.MarkCleaned(entryId); _finished = true; }
    public void Rollback()
    {
        if (_finished) return;
        if (File.Exists(path)) throw new InvalidOperationException("Rollback refused because the deleted path was recreated.");
        byte[] original = backupPath.Length > 0 ? File.ReadAllBytes(backupPath) : Convert.FromBase64String(originalBase64);
        if (!Convert.ToHexString(SHA256.HashData(original)).Equals(originalHash, StringComparison.Ordinal)) throw new InvalidDataException("Delete backup hash verification failed.");
        File.WriteAllBytes(path, original);
        Cleanup(); journal.MarkCleaned(entryId); _finished = true;
    }
    private void Cleanup()
    {
        if (backupPath.Length == 0) return;
        File.Delete(backupPath);
        string? parent = System.IO.Path.GetDirectoryName(backupPath);
        if (parent is not null && Directory.Exists(parent) && !Directory.EnumerateFileSystemEntries(parent).Any()) Directory.Delete(parent);
    }
}

public sealed class DirectoryMkdirTransaction(TaskResourceJournal journal, Guid entryId, string path)
{
    private bool _finished;
    public void Commit() { if (_finished) return; journal.MarkCleaned(entryId); _finished = true; }
    public void Rollback()
    {
        if (_finished) return;
        if (Directory.Exists(path)) Directory.Delete(path, recursive: false);
        journal.MarkCleaned(entryId);
        _finished = true;
    }
}

public sealed class DirectoryRmdirTransaction(TaskResourceJournal journal, Guid entryId, string path)
{
    private bool _finished;
    public void Commit() { if (_finished) return; journal.MarkCleaned(entryId); _finished = true; }
    public void Rollback()
    {
        if (_finished) return;
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        journal.MarkCleaned(entryId);
        _finished = true;
    }
}

public sealed class FileRenameTransaction(TaskResourceJournal journal, Guid entryId, string sourcePath, string destinationPath, string sourceHash)
{
    private bool _finished;
    public void Commit() { if (_finished) return; journal.MarkCleaned(entryId); _finished = true; }
    public void Rollback()
    {
        if (_finished) return;
        if (!File.Exists(destinationPath)) throw new InvalidOperationException("Rollback refused because the destination file is missing.");
        if (!Hash(destinationPath).Equals(sourceHash, StringComparison.Ordinal))
            throw new InvalidDataException("Rollback refused because the destination file hash does not match the original source hash.");
        File.Move(destinationPath, sourcePath);
        journal.MarkCleaned(entryId);
        _finished = true;
    }
    private static string Hash(string target)
    {
        using FileStream stream = File.OpenRead(target);
        return Convert.ToHexString(SHA256.HashData(stream));
    }
}

public sealed class FileEditTransaction(
    TaskResourceJournal journal, Guid entryId, string path, string originalHash, string replacementHash,
    string backupPath, string originalBase64, bool originallyExisted)
{
    private bool _finished;

    public void Commit()
    {
        if (_finished) return;
        DeleteBackup();
        journal.MarkCleaned(entryId);
        _finished = true;
    }

    public void Rollback()
    {
        if (_finished) return;
        if (!File.Exists(path) || !Hash(path).Equals(replacementHash, StringComparison.Ordinal))
            throw new InvalidOperationException("Rollback refused because the replacement file changed after the transaction.");
        if (originallyExisted)
        {
            byte[] original = backupPath.Length > 0 ? File.ReadAllBytes(backupPath) : Convert.FromBase64String(originalBase64);
            if (!Convert.ToHexString(SHA256.HashData(original)).Equals(originalHash, StringComparison.Ordinal)) throw new InvalidDataException("Backup hash verification failed.");
            string temporary = path + ".rollback-" + Guid.NewGuid().ToString("N") + ".tmp";
            File.WriteAllBytes(temporary, original);
            File.Move(temporary, path, overwrite: true);
        }
        else File.Delete(path);
        DeleteBackup();
        journal.MarkCleaned(entryId);
        _finished = true;
    }

    private void DeleteBackup()
    {
        if (backupPath.Length == 0) return;
        File.Delete(backupPath);
        string? parent = System.IO.Path.GetDirectoryName(backupPath);
        if (parent is not null && Directory.Exists(parent) && !Directory.EnumerateFileSystemEntries(parent).Any()) Directory.Delete(parent);
    }
    private static string Hash(string target)
    {
        using FileStream stream = File.OpenRead(target);
        return Convert.ToHexString(SHA256.HashData(stream));
    }
}