Repository navigation
Expand file tree
/
Copy pathProtectedFiles.cs
More file actions
467 lines (414 loc) · 15.7 KB
/
Copy pathProtectedFiles.cs
File metadata and controls
467 lines (414 loc) · 15.7 KB
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
using System.Collections.Concurrent;
using GeFeSLE;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using SQLitePCL;
using Newtonsoft.Json; // Add this import statement
public static class ProtectedFiles
{
private sealed class ListAccessSnapshot
{
public GeListVisibility Visibility { get; set; }
public string? CreatorId { get; set; }
public HashSet<string> OwnerIds { get; set; } = new HashSet<string>(StringComparer.Ordinal);
public HashSet<string> ContributorIds { get; set; } = new HashSet<string>(StringComparer.Ordinal);
public bool HydratedFromDb { get; set; }
}
// define a bunch of defaults: List<string>
private static readonly Dictionary<string, string> internalFiles = new Dictionary<string, string> {
// { "/_edit.item.html", "contributor" },
// { "/_edit.item.js", "contributor" }, REMOVED (for suggestions)
{ "/_edit.list.js", "listowner" },
{ "/_edit.list.html", "listowner" },
{ "/_edituser.html", "SuperUser" },
{ "/_edituser.js", "SuperUser" },
{ "/_mastobookmark.html", "listowner" },
{ "/_mastobookmark.js", "listowner" }
};
// "D:\repos\GeFeSLE-server\wwwroot\_modal.google.js"
// "D:\repos\GeFeSLE-server\wwwroot\_modal.mastodon.js"
// "D:\repos\GeFeSLE-server\wwwroot\_password.change.html"
// "D:\repos\GeFeSLE-server\wwwroot\_password.change.js"
private static ConcurrentDictionary<string, string> Files = new ConcurrentDictionary<string, string>();
// first string is the FILE name, the second is the list name, which is the KEY to the next dictionary
// basically: check Files above for the filename. If its an "internal protected file" OR
// its associated with a List that is not public, it will be in here. The VALUE is the NAME of the LIST
// which you use to look up the List object in the next dictionary (saves a DB query)
private static ConcurrentDictionary<string, GeList> Lists = new ConcurrentDictionary<string, GeList>();
private static ConcurrentDictionary<string, ListAccessSnapshot> ListAccess = new ConcurrentDictionary<string, ListAccessSnapshot>();
// add a file to the list
public static void AddFile(string path, string listName)
{
Files.TryAdd(path, listName);
DBg.d(LogLevel.Trace, $"ProtectedFiles.AddFile: {path} - list name: {listName}");
}
// remove a file from the list
public static void RemoveFile(string path)
{
var removed = "";
Files.TryRemove(path, out removed);
DBg.d(LogLevel.Trace, $"ProtectedFiles.RemoveFile: {path} - list name: {removed}");
}
// check if a file is in the list
public static bool ContainsFile(string path)
{
return Files.ContainsKey(path);
}
public static bool TryGetProtectionScope(string path, out string? scope)
{
var found = Files.TryGetValue(path, out var mapped);
scope = mapped;
return found;
}
// call this on:
// 1. startup
// 2. when a list is created
// 3. when a list is deleted
// 4. when a list's visibility is changed
// 5. when a list's name is changed
// 6. when a list's contributors are changed
// 7. when a list's owners are changed
// 8. when a list's creator is changed
public static void ReLoadFiles(GeFeSLEDb db)
{
// get a list of all GeList in the database that have .Visibility > GeListVisibility.Public
var lists = db.Lists
.Include(list => list.Creator)
.Include(list => list.ListOwners)
.Include(list => list.Contributors)
.Where(list => list.Visibility > GeListVisibility.Public)
.ToList();
foreach (var list in lists)
{
AddList(list);
}
foreach ((string file, string minrole) in internalFiles)
{
AddFile(file, minrole);
}
}
public static void AddList(GeList list)
{
string fn = "ProtectedFiles.AddList";
DBg.d(LogLevel.Trace, $"{fn} -- {list.Name}");
if (list.Name != null && list.Visibility > GeListVisibility.Public)
{
AddFile($"/rss-{list.Name}.xml", list.Name);
AddFile($"/{list.Name}.json", list.Name);
AddFile($"/{list.Name}.html", list.Name);
Lists.AddOrUpdate(list.Name!, list, (_, _) => list);
ListAccess.AddOrUpdate(list.Name!, BuildSnapshot(list), (_, _) => BuildSnapshot(list));
}
else {
DBg.d(LogLevel.Information, $"{fn} skipping name: {list.Name} or visibility: {list.Visibility}");
}
}
public static void RemoveProtectedListByName(string? listName)
{
if (string.IsNullOrWhiteSpace(listName))
{
return;
}
RemoveFile($"/rss-{listName}.xml");
RemoveFile($"/{listName}.json");
RemoveFile($"/{listName}.html");
Lists.TryRemove(listName, out _);
ListAccess.TryRemove(listName, out _);
}
public static async Task RefreshListCacheAsync(GeFeSLEDb db, int listId, string? oldName = null)
{
GeList? list = await db.Lists
.Include(l => l.Creator)
.Include(l => l.ListOwners)
.Include(l => l.Contributors)
.FirstOrDefaultAsync(l => l.Id == listId);
if (!string.IsNullOrWhiteSpace(oldName)
&& (list is null || !string.Equals(oldName, list.Name, StringComparison.Ordinal)))
{
RemoveProtectedListByName(oldName);
}
if (list is null)
{
return;
}
if (list.Visibility > GeListVisibility.Public)
{
AddList(list);
}
else
{
RemoveProtectedListByName(list.Name);
}
}
public static bool RemoveList(GeList list)
{
string fn = "ProtectedFiles.RemoveList";
DBg.d(LogLevel.Trace, $"{fn} -- {list.Name}");
if (list.Name != null && list.Visibility == GeListVisibility.Public)
{
RemoveFile($"/rss-{list.Name}.xml");
RemoveFile($"/{list.Name}.json");
RemoveFile($"/{list.Name}.html");
ListAccess.TryRemove(list.Name!, out _);
return Lists.TryRemove(list.Name!, out _);
}
else {
DBg.d(LogLevel.Information, $"{fn} NOT REMOVING name: {list.Name}, visibility: {list.Visibility}");
return false;
}
}
public static async Task<(bool, string?)> IsFileVisibleToUser(string path,
string? userId,
string? realizedRole,
GeFeSLEDb db)
{
var fn = "IsFileVisibleToUser"; DBg.d(LogLevel.Trace, fn);
string? ynot;
Files.TryGetValue(path, out var listName);
// Build an effective role set from the already-realized session role.
// This avoids a role DB lookup on every protected resource request.
IList<string> roles = BuildEffectiveRoles(realizedRole);
if (IsInternalProtected(listName))
{
if (IsInternalProtectedVisibleToUser(listName, roles, out ynot))
{
ynot = $"{fn} file {path} is internal protected file: {ynot}";
return (true, ynot);
}
else
{
ynot = $"{fn} file {path} is internal protected file: {ynot}";
return (false, ynot);
}
}
DBg.d(LogLevel.Trace, $"{fn} file {path} is not an interal protected file.");
ListAccessSnapshot? access = null;
if (!string.IsNullOrWhiteSpace(listName))
{
if (!ListAccess.TryGetValue(listName, out var cachedAccess) || cachedAccess is null || !cachedAccess.HydratedFromDb)
{
access = await HydrateSnapshotForListName(db, listName);
}
else
{
access = cachedAccess;
}
}
// did we get a list?
if (access == null)
{
DBg.d(LogLevel.Critical, $"{fn}: {path} - user {userId ?? "(no-id)"} - NO LIST ASSOCIATED - WHY AM I HERE?");
ynot = "No list associated with this file! Why am I here?";
return (false, ynot);
}
(bool isVis, ynot) = IsSnapshotVisibleToUser(access, userId, roles);
if (isVis)
{
ynot = $"Path {path} is visible: {ynot}";
return (isVis, ynot);
}
else
{
ynot = $"Path {path} is NOT visible: {ynot}";
return (isVis, ynot);
};
}
private static ListAccessSnapshot BuildSnapshot(GeList list)
{
return new ListAccessSnapshot
{
Visibility = list.Visibility,
CreatorId = list.CreatorId,
OwnerIds = list.ListOwners
.Where(u => !string.IsNullOrWhiteSpace(u.Id))
.Select(u => u.Id)
.ToHashSet(StringComparer.Ordinal),
ContributorIds = list.Contributors
.Where(u => !string.IsNullOrWhiteSpace(u.Id))
.Select(u => u.Id)
.ToHashSet(StringComparer.Ordinal),
HydratedFromDb = list.Creator is not null
|| list.ListOwners.Count > 0
|| list.Contributors.Count > 0
};
}
private static async Task<ListAccessSnapshot?> HydrateSnapshotForListName(GeFeSLEDb db, string listName)
{
GeList? hydrated = await db.Lists
.Include(l => l.Creator)
.Include(l => l.ListOwners)
.Include(l => l.Contributors)
.FirstOrDefaultAsync(l => l.Name == listName);
if (hydrated is null)
{
return null;
}
var snapshot = BuildSnapshot(hydrated);
snapshot.HydratedFromDb = true;
ListAccess.AddOrUpdate(listName, snapshot, (_, _) => snapshot);
Lists.AddOrUpdate(listName, hydrated, (_, _) => hydrated);
return snapshot;
}
private static IList<string> BuildEffectiveRoles(string? realizedRole)
{
var roles = new List<string>();
if (string.IsNullOrWhiteSpace(realizedRole))
{
return roles;
}
if (string.Equals(realizedRole, "SuperUser", StringComparison.Ordinal))
{
roles.Add("SuperUser");
roles.Add("listowner");
roles.Add("contributor");
return roles;
}
if (string.Equals(realizedRole, "listowner", StringComparison.Ordinal))
{
roles.Add("listowner");
roles.Add("contributor");
return roles;
}
if (string.Equals(realizedRole, "contributor", StringComparison.Ordinal))
{
roles.Add("contributor");
return roles;
}
return roles;
}
public static bool IsInternalProtected(string listName)
{
string fn = "IsInternalProtected"; DBg.d(LogLevel.Trace, fn);
if (listName == "SuperUser" || listName == "listowner" || listName == "contributor")
{
return true;
}
else return false;
}
public static bool IsInternalPathVisibleToRole(string listName, string? realizedRole, out string ynot)
{
IList<string> roles = BuildEffectiveRoles(realizedRole);
return IsInternalProtectedVisibleToUser(listName, roles, out ynot);
}
private static (bool, string?) IsSnapshotVisibleToUser(
ListAccessSnapshot access,
string? userId,
IList<string> roles)
{
if (access.Visibility == GeListVisibility.Public)
{
return (true, "List is public");
}
if (roles.Contains("SuperUser"))
{
return (true, "User is a super user");
}
if (string.IsNullOrWhiteSpace(userId))
{
return (false, "User is not identified");
}
bool isCreator = string.Equals(access.CreatorId, userId, StringComparison.Ordinal);
bool isOwner = access.OwnerIds.Contains(userId);
bool isContributor = access.ContributorIds.Contains(userId);
switch (access.Visibility)
{
case GeListVisibility.Contributors:
if (isContributor || isOwner || isCreator)
{
return (true, "User is contributor/owner/creator");
}
return (false, "User is not a contributor/list owner/creator");
case GeListVisibility.ListOwners:
if (isOwner || isCreator)
{
return (true, "User is list owner/creator");
}
return (false, "User is not a list owner/creator");
case GeListVisibility.Private:
if (isCreator)
{
return (true, "User is the creator");
}
return (false, "User is not the creator");
default:
return (false, "Visibility rule denied");
}
}
// For "protected" files like the edit and modify pages, internal .js files
// we protect them with listnames==role_required_to_view
// if a file's "listname" is one of these, compare with user's role
public static bool IsInternalProtectedVisibleToUser(string listName, IList<string> roles, out string ynot)
{
string fn = "IsInternalProtectedVisibleToUser"; DBg.d(LogLevel.Trace, fn);
bool isVis = false;
switch (listName)
{
case "SuperUser":
if (roles.Contains("SuperUser"))
{
isVis = true;
ynot = "User is a super user";
}
else ynot = "User is not a super user";
break;
case "listowner":
if (roles.Contains("SuperUser") || roles.Contains("listowner"))
{
isVis = true;
ynot = "User is a super user or list owner";
}
else ynot = "User is not a super user or list owner";
break;
case "contributor":
if (roles.Contains("SuperUser") || roles.Contains("listowner") || roles.Contains("contributor"))
{
isVis = true;
ynot = "User is a super user, list owner, or contributor";
}
else
{
ynot = "User is not a super user, list owner, or contributor";
}
break;
default:
ynot = "File is not internal protected file";
break;
}
return isVis;
}
public static (bool, string?) IsListVisibleToUser(
GeList list,
GeFeSLEUser user,
IList<string> roles)
{
string fn = "IsListVisibleToUser"; DBg.d(LogLevel.Trace, fn);
string? ynot;
bool isVis = false;
if (list.Visibility == GeListVisibility.Public)
{
DBg.d(LogLevel.Critical, $"{fn}: - {user.UserName} - LIST IS PUBLIC - WHY AM I HERE? ");
ynot = "List is public";
isVis = true;
}
else if (roles.Contains("SuperUser"))
{
DBg.d(LogLevel.Trace, $"{fn}: - {user.UserName} - USER IS SUPERUSER");
ynot = "User is a super user";
isVis = true;
}
else
{
(bool allowed, ynot) = list.IsUserAllowedToView(user);
if (allowed)
{
DBg.d(LogLevel.Trace, $"{fn}: - {user.UserName} - USER IS EXPLICITLY ALLOWED TO VIEW LIST");
isVis = true;
}
else
{
DBg.d(LogLevel.Critical, $"ProtectedFiles.IsFileVisibleToUser: - HOW WE GET HERE? {user.UserName} {list.Name}");
}
}
return (isVis, ynot);
}
}