-
Notifications
You must be signed in to change notification settings - Fork 687
Expand file tree
/
Copy pathACLParser.cs
More file actions
384 lines (351 loc) · 15.8 KB
/
Copy pathACLParser.cs
File metadata and controls
384 lines (351 loc) · 15.8 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Garnet.server.ACL
{
class ACLParser
{
private static readonly char[] WhitespaceChars = [' ', '\t', '\r', '\n'];
private static readonly Dictionary<string, RespAclCategories> categoryNames = new Dictionary<string, RespAclCategories>(StringComparer.OrdinalIgnoreCase)
{
["admin"] = RespAclCategories.Admin,
["bitmap"] = RespAclCategories.Bitmap,
["blocking"] = RespAclCategories.Blocking,
["connection"] = RespAclCategories.Connection,
["dangerous"] = RespAclCategories.Dangerous,
["geo"] = RespAclCategories.Geo,
["hash"] = RespAclCategories.Hash,
["hyperloglog"] = RespAclCategories.HyperLogLog,
["fast"] = RespAclCategories.Fast,
["keyspace"] = RespAclCategories.KeySpace,
["list"] = RespAclCategories.List,
["pubsub"] = RespAclCategories.PubSub,
["read"] = RespAclCategories.Read,
["scripting"] = RespAclCategories.Scripting,
["set"] = RespAclCategories.Set,
["sortedset"] = RespAclCategories.SortedSet,
["slow"] = RespAclCategories.Slow,
["stream"] = RespAclCategories.Stream,
["string"] = RespAclCategories.String,
["transaction"] = RespAclCategories.Transaction,
["vector"] = RespAclCategories.Vector,
["write"] = RespAclCategories.Write,
["garnet"] = RespAclCategories.Garnet,
["custom"] = RespAclCategories.Custom,
["all"] = RespAclCategories.All,
};
private static readonly Dictionary<RespAclCategories, string> categoryNamesReversed = categoryNames.ToDictionary(static kv => kv.Value, static kv => kv.Key);
/// <summary>
/// Parses a single-line ACL rule and returns a new user according to that rule.
///
/// ACL rules follow a subset of the Redis ACL rule syntax, with each rule
/// being formatted as follows:
///
/// ACL_RULE := user <username> (<ACL_OPERATION>)+
/// ACL_OPERATION := on | off | +@<category> | -@<category>
///
/// To manage user account:
/// on/off: enable/disable the user account
///
/// To configure user passwords:
/// ><password>: Add the password to the list of valid passwords for the user
/// <<password>: Remove the password from the list of valid password for the user
/// #<hash>: Add the password hash to the list of valid passwords for the user
/// !<hash>: Remove the password hash from the list of valid passwords for the user
/// nopass: Specify this user can login without a password.
/// resetpass: Reset all passwords defined for the user so far and disable passwordless login.
/// </summary>
/// <param name="input">A single line Redis-style ACL rule.</param>
/// <param name="acl">An optional access control list to modify.</param>
/// <returns>A user object representing the modified user.</returns>
/// <exception cref="ACLParsingException">Thrown if the ACL rule cannot be parsed.</exception>
/// <exception cref="ACLCategoryDoesNotExistException">Thrown if the ACL command category used by the operation does not exist.</exception>
/// <exception cref="ACLUnknownOperationException">Thrown if the given operation does not exist.</exception>
public static User ParseACLRule(string input, AccessControlList acl = null)
{
// Tokenize input string
string[] tokens = input.Trim().Split(WhitespaceChars, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
// Sanity check for correctness
if (tokens.Length < 3)
{
throw new ACLParsingException("Malformed ACL rule");
}
// Expect keyword USER
if (!tokens[0].Equals("user", StringComparison.OrdinalIgnoreCase))
{
throw new ACLParsingException("ACL rules need to start with the USER keyword");
}
// Expect username
string username = tokens[1];
// Retrieve/add the user with the username to the access control list, if provided
User user;
if (acl != null)
{
user = acl.GetUserHandle(username)?.User;
if (user == null)
{
user = new User(username);
acl.AddUserHandle(new UserHandle(user));
}
}
else
{
user = new User(username);
}
// Parse remaining tokens as ACL operations
for (int i = 2; i < tokens.Length; i++)
{
ApplyACLOpToUser(ref user, tokens[i]);
}
return user;
}
/// <summary>
/// Parses the given ACL operation string and applies it to the given user.
/// </summary>
/// <param name="user">User to apply the operation to.</param>
/// <param name="op">ACL operation as string.</param>
/// <exception cref="ACLCategoryDoesNotExistException">Thrown if the ACL command category used by the operation does not exist.</exception>
/// <exception cref="ACLUnknownOperationException">Thrown if the given operation does not exist.</exception>
public static void ApplyACLOpToUser(ref User user, string op)
{
// Bail early for empty op
if (op.Length == 0)
{
return;
}
if (op.Equals("ON", StringComparison.OrdinalIgnoreCase))
{
// Enable user
user.IsEnabled = true;
}
else if (op.Equals("OFF", StringComparison.OrdinalIgnoreCase))
{
// Disable user
user.IsEnabled = false;
}
else if (op.Equals("NOPASS", StringComparison.OrdinalIgnoreCase))
{
// Make account passwordless
user.ClearPasswords();
user.IsPasswordless = true;
}
else if (op.Equals("RESET", StringComparison.OrdinalIgnoreCase))
{
// Remove all passwords and access rights from the user
user.Reset();
}
else if (op.Equals("RESETPASS", StringComparison.OrdinalIgnoreCase))
{
// Remove all passwords from the user
user.ClearPasswords();
user.IsPasswordless = false;
}
else if (op[0] == '>')
{
// Add password from cleartext
user.AddPasswordHash(ACLPassword.ACLPasswordFromString(op.Substring(1)));
}
else if (op[0] == '<')
{
// Remove password from cleartext
user.RemovePasswordHash(ACLPassword.ACLPasswordFromString(op.Substring(1)));
}
else if ((op[0] == '#') || (op[0] == '!'))
{
try
{
if (op[0] == '#')
{
// Add password from hash
user.AddPasswordHash(ACLPassword.ACLPasswordFromHash(op.Substring(1)));
}
else
{
// Remove password from hash
user.RemovePasswordHash(ACLPassword.ACLPasswordFromHash(op.Substring(1)));
}
}
catch (ACLPasswordException exception)
{
throw new ACLParsingException($"{exception.Message}");
}
}
else if (op.StartsWith("-@", StringComparison.Ordinal) || op.StartsWith("+@", StringComparison.Ordinal))
{
// Parse category name
string categoryName = op.Substring(2);
RespAclCategories category;
try
{
category = ACLParser.GetACLCategoryByName(categoryName);
}
catch (KeyNotFoundException)
{
throw new ACLCategoryDoesNotExistException(categoryName);
}
// Add or remove the category
if (op[0] == '-')
{
user.RemoveCategory(category);
}
else
{
user.AddCategory(category);
}
}
else if (op.StartsWith('-') || op.StartsWith('+'))
{
// Individual commands or command|subcommand pairs
string commandName = op.Substring(1);
if (TryParseCommandForAcl(commandName, out RespCommand command))
{
if (op[0] == '-')
{
user.RemoveCommand(command);
}
else
{
user.AddCommand(command);
}
}
else if (IsValidCustomCommandName(commandName))
{
// Modules may not be loaded yet (ACL file is parsed before LoadModules), so we
// store the name on the user and resolve it later (startup pass, SETUSER, dispatch).
if (op[0] == '-')
{
user.RemoveCustomCommand(commandName);
}
else
{
user.AddCustomCommand(commandName);
}
}
else
{
throw new AclCommandDoesNotExistException(commandName);
}
}
else if (op.Equals("~*", StringComparison.Ordinal) || op.Equals("ALLKEYS", StringComparison.OrdinalIgnoreCase))
{
// NOTE: No-op, because only wildcard key patterns are currently supported
}
else if (op.Equals("RESETKEYS", StringComparison.OrdinalIgnoreCase))
{
// NOTE: No-op, because only wildcard key patterns are currently supported
}
else
{
throw new ACLUnknownOperationException(op);
}
// There's some fixup that has to be done when parsing a command
static bool TryParseCommandForAcl(string commandName, out RespCommand command)
{
int subCommandSepIx = commandName.IndexOf('|');
bool isSubCommand = subCommandSepIx != -1;
string effectiveName = isSubCommand ? commandName[..subCommandSepIx] + "_" + commandName[(subCommandSepIx + 1)..] : commandName;
if (!Enum.TryParse(effectiveName, ignoreCase: true, out command) || !IsValidParse(command, effectiveName))
{
// Try replacing dots with empty strings for commands like RI.CREATE -> RICREATE
string dotlessName = effectiveName.Replace(".", "");
if (dotlessName != effectiveName && Enum.TryParse(dotlessName, ignoreCase: true, out command) && IsValidParse(command, dotlessName))
{
// Successfully parsed after removing dots — fall through to validation below
}
else if (commandName.Equals("SLAVEOF", StringComparison.OrdinalIgnoreCase))
{
command = RespCommand.SECONDARYOF;
}
else if (commandName.Equals("CLUSTER|SET-CONFIG-EPOCH", StringComparison.OrdinalIgnoreCase))
{
command = RespCommand.CLUSTER_SETCONFIGEPOCH;
}
else
{
return false;
}
}
// Validate parse results matches the original input expectations
if (isSubCommand)
{
if (!RespCommandsInfo.TryGetRespCommandInfo(command, out RespCommandsInfo info))
{
throw new ACLException($"Couldn't load information for {command}, shouldn't be possible");
}
if (info.Command != command)
{
return false;
}
}
return !IsInvalidCommandToAcl(command);
}
// Returns true if the parsed value could possibly result in this command
//
// Used to handle the weirdness in Enum.TryParse - long term we probably
// shift to something like IUtf8SpanParsable.
static bool IsValidParse(RespCommand command, ReadOnlySpan<char> fromStr)
{
return command != RespCommand.NONE && command != RespCommand.INVALID && !fromStr.ContainsAnyInRange('0', '9');
}
// Some commands aren't really commands, so ACLs shouldn't accept their names
static bool IsInvalidCommandToAcl(RespCommand command)
=> command == RespCommand.INVALID || command == RespCommand.NONE || command.NormalizeForACLs() != command;
}
/// <summary>
/// Maximum length (in chars) of a custom command name accepted in an ACL rule.
/// </summary>
internal const int MaxCustomCommandNameLength = 64;
/// <summary>
/// Returns true if <paramref name="name"/> is a syntactically valid custom command name.
/// Strict validation prevents the unknown-name fallback from accepting RESP-meta bytes
/// or whitespace-bearing junk. Allowed: ASCII letters/digits and '.', '_', '-', '|';
/// first character must be alphanumeric.
/// </summary>
internal static bool IsValidCustomCommandName(string name)
{
if (string.IsNullOrEmpty(name) || name.Length > MaxCustomCommandNameLength)
{
return false;
}
char first = name[0];
bool firstOk = (first >= 'A' && first <= 'Z')
|| (first >= 'a' && first <= 'z')
|| (first >= '0' && first <= '9');
if (!firstOk)
{
return false;
}
foreach (char c in name)
{
bool ok = (c >= 'A' && c <= 'Z')
|| (c >= 'a' && c <= 'z')
|| (c >= '0' && c <= '9')
// '|' is permitted so custom names can mirror built-in subcommand notation (e.g. CLIENT|GETNAME).
|| c == '.' || c == '_' || c == '-' || c == '|';
if (!ok)
{
return false;
}
}
return true;
}
/// <summary>
/// Lookup the <see cref="RespAclCategories"/> by equivalent string.
/// </summary>
public static RespAclCategories GetACLCategoryByName(string categoryName)
=> ACLParser.categoryNames[categoryName];
/// <summary>
/// Lookup the string equivalent to <paramref name="category"/>.
/// </summary>
public static string GetNameByACLCategory(RespAclCategories category)
=> ACLParser.categoryNamesReversed[category];
/// <summary>
/// Returns a collection of all valid category names.
/// </summary>
/// <returns>Collection of valid category names.</returns>
public static IReadOnlyCollection<string> ListCategories()
=> ACLParser.categoryNames.Keys;
}
}