Repository navigation
Expand file tree
/
Copy pathAuthorizationPolicy.cs
More file actions
209 lines (194 loc) · 8.44 KB
/
Copy pathAuthorizationPolicy.cs
File metadata and controls
209 lines (194 loc) · 8.44 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
using System.Text.Json.Nodes;
using KeyLoad.Core;
using KeyLoad.Security.Features.Authorization;
namespace KeyLoad.Security;
/// <summary>Enforces persisted resource, row, and sensitive-field access policy.</summary>
public sealed class AuthorizationPolicy : IAuthorizationPolicy
{
private const string AuthorizationWildcard = "*";
private const string ScopeDeniedMessage = "The principal cannot perform this operation in this scope.";
private const string RowWriteDeniedMessage = "The principal cannot write this row scope.";
private const string FieldUseDeniedMessage = "The query requires a protected field-use grant.";
private const string FieldWriteDeniedMessage = "The mutation requires a protected field-write grant.";
private const string SensitiveReplacementGrant = "document.replaceSensitive";
private const string ReplacementDeniedMessage = "Replacing a redacted document requires an explicit replacement grant. Use a field patch.";
private const string WorkerInputDeniedMessage = "Required worker input is protected by a missing raw-read grant.";
private const string EmptyObjectJson = "{}";
private const string NullValueJson = "null";
private const int EmptySequenceLength = 0;
private const int FirstElementIndex = 0;
private const int PathSegmentWidth = 1;
internal static bool Grant(PrincipalRecord principal, string grant) => principal.ClusterAdministrator
|| principal.FieldGrants.Contains(grant, StringComparer.Ordinal) || principal.FieldGrants.Contains(AuthorizationWildcard, StringComparer.Ordinal);
/// <inheritdoc />
public void Require(PrincipalRecord principal, PartitionRef partition, string resource, Capability capability)
{
ArgumentNullException.ThrowIfNull(principal);
ArgumentNullException.ThrowIfNull(partition);
if (principal.ClusterAdministrator)
{
return;
}
if (principal.TenantId != partition.TenantId || !principal.Grants.Any(g => (g.Database == AuthorizationWildcard || g.Database == partition.DatabaseId)
&& (g.Resource == AuthorizationWildcard || g.Resource == resource) && (g.Capabilities & capability) == capability))
{
throw Errors.Fail(ErrorCode.PermissionDenied, ScopeDeniedMessage);
}
}
/// <inheritdoc />
public bool CanReadRow(PrincipalRecord principal, RowAccess access)
{
ArgumentNullException.ThrowIfNull(principal);
ArgumentNullException.ThrowIfNull(access);
return principal.ClusterAdministrator || !principal.RestrictRows
|| access.OwnerId is not null && access.OwnerId == principal.OwnerId
|| access.ProjectId is not null && principal.Projects.Contains(access.ProjectId, StringComparer.Ordinal);
}
/// <inheritdoc />
public void RequireWriteRow(PrincipalRecord principal, RowAccess access)
{
if (!CanReadRow(principal, access))
{
throw Errors.Fail(ErrorCode.PermissionDenied, RowWriteDeniedMessage);
}
}
/// <inheritdoc />
public void RequireFieldUse(PrincipalRecord principal, ResourceDefinition resource, string path)
{
ArgumentNullException.ThrowIfNull(principal);
ArgumentNullException.ThrowIfNull(resource);
foreach (var policy in resource.FieldPolicies)
{
if (Overlaps(policy.Path, path) && !Grant(principal, policy.RawUseGrant))
{
throw Errors.Fail(ErrorCode.PermissionDenied, FieldUseDeniedMessage);
}
}
}
/// <inheritdoc />
public void RequireFieldWrite(PrincipalRecord principal, ResourceDefinition resource, string path)
{
ArgumentNullException.ThrowIfNull(principal);
ArgumentNullException.ThrowIfNull(resource);
foreach (var policy in resource.FieldPolicies)
{
if (Overlaps(policy.Path, path) && !Grant(principal, policy.WriteGrant))
{
throw Errors.Fail(ErrorCode.PermissionDenied, FieldWriteDeniedMessage);
}
}
}
/// <inheritdoc />
public IEnumerable<SensitiveFieldPolicy> GetEffectiveFieldPolicies(ResourceDefinition resource, string path)
{
ArgumentNullException.ThrowIfNull(resource);
ArgumentNullException.ThrowIfNull(path);
return resource.FieldPolicies.Where(policy => Overlaps(policy.Path, path));
}
/// <inheritdoc />
public void RequireReplacement(PrincipalRecord principal, ResourceDefinition resource, bool explicitReplacement)
{
ArgumentNullException.ThrowIfNull(principal);
ArgumentNullException.ThrowIfNull(resource);
if (resource.FieldPolicies.Any(p => !Grant(principal, p.RawReadGrant))
&& (!explicitReplacement || !Grant(principal, SensitiveReplacementGrant)))
{
throw Errors.Fail(ErrorCode.PermissionDenied, ReplacementDeniedMessage);
}
}
/// <inheritdoc />
public void RequireWorkerInput(PrincipalRecord principal, ResourceDefinition resource)
{
ArgumentNullException.ThrowIfNull(principal);
ArgumentNullException.ThrowIfNull(resource);
if (resource.FieldPolicies.Concat(resource.HeaderPolicies).Any(p => p.RequiredForProcessing && !Grant(principal, p.RawReadGrant)))
{
throw Errors.Fail(ErrorCode.PermissionDenied, WorkerInputDeniedMessage);
}
}
/// <inheritdoc />
public void RequireReplayInput(PrincipalRecord principal, ResourceDefinition resource)
=> ReplayInputPolicy.Require(principal, resource);
/// <inheritdoc />
public string Project(PrincipalRecord principal, IReadOnlyList<SensitiveFieldPolicy> policies, string json, out string[] omitted)
{
var hidden = policies.Where(p => !Grant(principal, p.RawReadGrant)).ToArray();
omitted = hidden.Select(p => p.Path).ToArray();
if (hidden.Length == EmptySequenceLength)
{
return json;
}
if (hidden.Any(p => p.Path.Length == EmptySequenceLength))
{
return EmptyObjectJson;
}
var root = JsonNode.Parse(json);
foreach (var policy in hidden)
{
Remove(root, JsonData.PathSegments(policy.Path), FirstElementIndex);
}
return root?.ToJsonString() ?? NullValueJson;
}
private static void Remove(JsonNode? node, string[] path, int position)
{
if (node is null || position >= path.Length)
{
return;
}
if (node is JsonObject obj)
{
foreach (var key in (path[position] == AuthorizationWildcard ? obj.Select(p => p.Key).ToArray() : [path[position]]))
{
if (position == path.Length - PathSegmentWidth)
{
obj.Remove(key);
continue;
}
Remove(obj[key], path, position + PathSegmentWidth);
}
return;
}
if (node is not JsonArray array)
{
return;
}
if (path[position] != AuthorizationWildcard)
{
if (int.TryParse(path[position], out var index) && index >= FirstElementIndex && index < array.Count)
{
RemoveArrayEntry(array, index, path, position);
}
return;
}
for (var index = FirstElementIndex; index < array.Count; index++)
{
RemoveArrayEntry(array, index, path, position);
}
}
private static void RemoveArrayEntry(JsonArray array, int index, string[] path, int position)
{
if (position == path.Length - PathSegmentWidth)
{
array[index] = null;
return;
}
Remove(array[index], path, position + PathSegmentWidth);
}
/// <summary>Reports whether two JSON field paths cover any of the same fields.</summary>
/// <param name="protectedPath">Persisted sensitive-field path.</param>
/// <param name="path">Requested field path.</param>
/// <returns>Whether the paths overlap.</returns>
public static bool Overlaps(string protectedPath, string path)
{
var left = JsonData.PathSegments(protectedPath);
var right = JsonData.PathSegments(path);
for (var i = FirstElementIndex; i < Math.Min(left.Length, right.Length); i++)
{
if (left[i] != AuthorizationWildcard && right[i] != AuthorizationWildcard && left[i] != right[i])
{
return false;
}
}
return true;
}
}