| | | 1 | | namespace Elsa.Authorization; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Decides whether a held permission satisfies a required one. One matching rule shape on both axes: |
| | | 5 | | /// exact match, or a wildcard. |
| | | 6 | | /// </summary> |
| | | 7 | | public static class PermissionMatcher |
| | | 8 | | { |
| | | 9 | | /// <summary>Whether <paramref name="granted"/> satisfies <paramref name="required"/>.</summary> |
| | | 10 | | public static bool Satisfies(Permission granted, Permission required) => |
| | 77 | 11 | | ResourceMatches(granted.Resource, required.Resource) && VerbMatches(granted.Verb, required.Verb); |
| | | 12 | | |
| | | 13 | | /// <summary>Whether any of <paramref name="granted"/> satisfies <paramref name="required"/>.</summary> |
| | | 14 | | public static bool Satisfies(IEnumerable<Permission> granted, Permission required) => |
| | 24 | 15 | | granted.Any(x => Satisfies(x, required)); |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Whether a granted resource pattern covers a required resource. A trailing <c>/*</c> matches the |
| | | 19 | | /// named node and every descendant at any depth; a bare <c>*</c> matches everything. |
| | | 20 | | /// </summary> |
| | | 21 | | public static bool ResourceMatches(string granted, string required) |
| | | 22 | | { |
| | 90 | 23 | | if (granted == Permission.Wildcard) |
| | 39 | 24 | | return true; |
| | | 25 | | |
| | 51 | 26 | | if (string.Equals(granted, required, StringComparison.Ordinal)) |
| | 17 | 27 | | return true; |
| | | 28 | | |
| | 34 | 29 | | if (!granted.EndsWith($"{Permission.PathSeparator}{Permission.Wildcard}", StringComparison.Ordinal)) |
| | 10 | 30 | | return false; |
| | | 31 | | |
| | | 32 | | // 'workflows/*' covers 'workflows' itself as well as everything beneath it. |
| | 24 | 33 | | var prefix = granted[..^2]; |
| | | 34 | | |
| | 24 | 35 | | if (string.Equals(prefix, required, StringComparison.Ordinal)) |
| | 2 | 36 | | return true; |
| | | 37 | | |
| | 22 | 38 | | return required.Length > prefix.Length |
| | 22 | 39 | | && required.StartsWith(prefix, StringComparison.Ordinal) |
| | 22 | 40 | | && required[prefix.Length] == Permission.PathSeparator; |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | /// <summary>Whether a granted verb covers a required verb.</summary> |
| | | 44 | | public static bool VerbMatches(string granted, string required) => |
| | 61 | 45 | | granted == Permission.Wildcard || string.Equals(granted, required, StringComparison.Ordinal); |
| | | 46 | | } |