-
Notifications
You must be signed in to change notification settings - Fork 215
/
PolicyCommandEnforcement.java
256 lines (228 loc) · 12.2 KB
/
PolicyCommandEnforcement.java
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
/*
* Copyright (c) 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.policies.service.enforcement;
import java.util.List;
import java.util.Optional;
import org.eclipse.ditto.base.model.auth.AuthorizationContext;
import org.eclipse.ditto.base.model.exceptions.DittoRuntimeException;
import org.eclipse.ditto.base.model.signals.commands.CommandToExceptionRegistry;
import org.eclipse.ditto.internal.utils.cacheloaders.PolicyEnforcer;
import org.eclipse.ditto.json.JsonFactory;
import org.eclipse.ditto.json.JsonFieldSelector;
import org.eclipse.ditto.json.JsonKey;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.json.JsonValue;
import org.eclipse.ditto.policies.api.Permission;
import org.eclipse.ditto.policies.enforcement.AbstractEnforcementReloaded;
import org.eclipse.ditto.policies.enforcement.CreationRestrictionEnforcer;
import org.eclipse.ditto.policies.model.Label;
import org.eclipse.ditto.policies.model.Permissions;
import org.eclipse.ditto.policies.model.PoliciesResourceType;
import org.eclipse.ditto.policies.model.Policy;
import org.eclipse.ditto.policies.model.PolicyEntry;
import org.eclipse.ditto.policies.model.ResourceKey;
import org.eclipse.ditto.policies.model.enforcers.Enforcer;
import org.eclipse.ditto.policies.model.enforcers.PolicyEnforcers;
import org.eclipse.ditto.policies.model.signals.commands.PolicyCommand;
import org.eclipse.ditto.policies.model.signals.commands.PolicyCommandResponse;
import org.eclipse.ditto.policies.model.signals.commands.actions.PolicyActionCommand;
import org.eclipse.ditto.policies.model.signals.commands.actions.TopLevelPolicyActionCommand;
import org.eclipse.ditto.policies.model.signals.commands.exceptions.PolicyCommandToAccessExceptionRegistry;
import org.eclipse.ditto.policies.model.signals.commands.exceptions.PolicyCommandToActionsExceptionRegistry;
import org.eclipse.ditto.policies.model.signals.commands.exceptions.PolicyCommandToModifyExceptionRegistry;
import org.eclipse.ditto.policies.model.signals.commands.exceptions.PolicyNotAccessibleException;
import org.eclipse.ditto.policies.model.signals.commands.modify.CreatePolicy;
import org.eclipse.ditto.policies.model.signals.commands.modify.ModifyPolicy;
import org.eclipse.ditto.policies.model.signals.commands.modify.PolicyModifyCommand;
import org.eclipse.ditto.policies.model.signals.commands.query.PolicyQueryCommandResponse;
/**
* Authorizes {@link PolicyCommand}s and filters {@link PolicyCommandResponse}s.
*/
public final class PolicyCommandEnforcement
extends AbstractEnforcementReloaded<PolicyCommand<?>, PolicyCommandResponse<?>> {
/**
* Json fields that are always shown regardless of authorization.
*/
private static final JsonFieldSelector POLICY_QUERY_COMMAND_RESPONSE_ALLOWLIST =
JsonFactory.newFieldSelector(Policy.JsonFields.ID);
private final CreationRestrictionEnforcer creationRestrictionEnforcer;
public PolicyCommandEnforcement(final CreationRestrictionEnforcer creationRestrictionEnforcer) {
this.creationRestrictionEnforcer = creationRestrictionEnforcer;
}
@Override
public PolicyCommand<?> authorizeSignal(final PolicyCommand<?> command, final PolicyEnforcer policyEnforcer) {
final Enforcer enforcer = policyEnforcer.getEnforcer();
final var policyResourceKey = PoliciesResourceType.policyResource(command.getResourcePath());
final var authorizationContext = command.getDittoHeaders().getAuthorizationContext();
final PolicyCommand<?> authorizedCommand;
if (command instanceof CreatePolicy) {
final var enforcerContext = new CreationRestrictionEnforcer.Context(command.getResourceType(),
command.getEntityId().getNamespace(),
command.getDittoHeaders()
);
if (creationRestrictionEnforcer.canCreate(enforcerContext)
&& (
command.getDittoHeaders().isAllowPolicyLockout()
|| hasUnrestrictedWritePermission(enforcer, policyResourceKey, authorizationContext)
)
) {
authorizedCommand = command;
} else {
throw errorForPolicyCommand(command);
}
} else if (command instanceof PolicyActionCommand) {
authorizedCommand =
authorizeActionCommand(policyEnforcer, command, policyResourceKey, authorizationContext)
.orElseThrow(() -> errorForPolicyCommand(command));
} else if (command instanceof PolicyModifyCommand) {
if (hasUnrestrictedWritePermission(enforcer, policyResourceKey, authorizationContext)) {
authorizedCommand = command;
} else {
throw errorForPolicyCommand(command);
}
} else {
final String permission = Permission.READ;
if (enforcer.hasPartialPermissions(policyResourceKey, authorizationContext, permission)) {
authorizedCommand = command;
} else {
throw errorForPolicyCommand(command);
}
}
return authorizedCommand;
}
@Override
public PolicyCommand<?> authorizeSignalWithMissingEnforcer(final PolicyCommand<?> command) {
final PolicyCommand<?> policyCommand = transformModifyPolicyToCreatePolicy(command);
if (policyCommand instanceof CreatePolicy createPolicy) {
final var enforcer = PolicyEnforcers.defaultEvaluator(createPolicy.getPolicy());
return authorizeSignal(createPolicy, PolicyEnforcer.of(enforcer));
} else {
throw PolicyNotAccessibleException.newBuilder(policyCommand.getEntityId())
.dittoHeaders(policyCommand.getDittoHeaders())
.build();
}
}
@Override
public PolicyCommandResponse<?> filterResponse(final PolicyCommandResponse<?> commandResponse,
final PolicyEnforcer policyEnforcer) {
if (commandResponse instanceof PolicyQueryCommandResponse<?> policyQueryCommandResponse) {
try {
return buildJsonViewForPolicyQueryCommandResponse(policyQueryCommandResponse,
policyEnforcer.getEnforcer());
} catch (final RuntimeException e) {
throw reportError("Error after building JsonView", e, commandResponse.getDittoHeaders());
}
} else {
// no filtering required for non PolicyQueryCommandResponses:
return commandResponse;
}
}
@SuppressWarnings("unchecked")
private static <T extends PolicyCommand<?>> Optional<T> authorizeActionCommand(final PolicyEnforcer enforcer,
final T command, final ResourceKey resourceKey, final AuthorizationContext authorizationContext) {
if (command instanceof TopLevelPolicyActionCommand topLevelPolicyActionCommand) {
return (Optional<T>) authorizeTopLevelAction(enforcer, topLevelPolicyActionCommand, authorizationContext);
} else {
return authorizeEntryLevelAction(enforcer.getEnforcer(), command, resourceKey, authorizationContext);
}
}
private static <T extends PolicyCommand<?>> Optional<T> authorizeEntryLevelAction(final Enforcer enforcer,
final T command, final ResourceKey resourceKey, final AuthorizationContext authorizationContext) {
return enforcer.hasUnrestrictedPermissions(resourceKey, authorizationContext, Permission.EXECUTE)
? Optional.of(command)
: Optional.empty();
}
private static Optional<TopLevelPolicyActionCommand> authorizeTopLevelAction(final PolicyEnforcer policyEnforcer,
final TopLevelPolicyActionCommand command, final AuthorizationContext authorizationContext) {
final var enforcer = policyEnforcer.getEnforcer();
final List<Label> authorizedLabels = policyEnforcer.getPolicy()
.map(policy -> policy.getEntriesSet().stream()
.map(PolicyEntry::getLabel)
.filter(label -> enforcer.hasUnrestrictedPermissions(asResourceKey(label, command),
authorizationContext, Permission.EXECUTE))
.toList())
.orElse(List.of());
if (authorizedLabels.isEmpty()) {
return Optional.empty();
} else {
final var adjustedCommand = TopLevelPolicyActionCommand.of(command.getPolicyActionCommand(), authorizedLabels);
return Optional.of(adjustedCommand);
}
}
private static boolean hasUnrestrictedWritePermission(final Enforcer enforcer, final ResourceKey policyResourceKey,
final AuthorizationContext authorizationContext) {
return enforcer.hasUnrestrictedPermissions(policyResourceKey, authorizationContext, Permission.WRITE);
}
/**
* Limit view on entity of {@code PolicyQueryCommandResponse} by enforcer.
*
* @param response the response.
* @param enforcer the enforcer.
* @return response with view on entity restricted by enforcer.
*/
public static <T extends PolicyQueryCommandResponse<T>> T buildJsonViewForPolicyQueryCommandResponse(
final PolicyQueryCommandResponse<T> response,
final Enforcer enforcer) {
final JsonValue entity = response.getEntity();
if (entity.isObject()) {
final JsonObject filteredView =
getJsonViewForPolicyQueryCommandResponse(entity.asObject(), response, enforcer);
return response.setEntity(filteredView);
} else {
return response.setEntity(entity);
}
}
private static JsonObject getJsonViewForPolicyQueryCommandResponse(final JsonObject responseEntity,
final PolicyQueryCommandResponse<?> response,
final Enforcer enforcer) {
final var resourceKey = ResourceKey.newInstance(PolicyCommand.RESOURCE_TYPE, response.getResourcePath());
final var authorizationContext = response.getDittoHeaders().getAuthorizationContext();
return enforcer.buildJsonView(resourceKey, responseEntity, authorizationContext,
POLICY_QUERY_COMMAND_RESPONSE_ALLOWLIST, Permissions.newInstance(Permission.READ));
}
private static PolicyCommand<?> transformModifyPolicyToCreatePolicy(final PolicyCommand<?> receivedCommand) {
if (receivedCommand instanceof ModifyPolicy modifyPolicy) {
return CreatePolicy.of(modifyPolicy.getPolicy(), modifyPolicy.getDittoHeaders());
} else {
return receivedCommand;
}
}
/**
* Create error due to failing to execute a policy-command in the expected way.
*
* @param policyCommand the command.
* @return the error.
*/
private static DittoRuntimeException errorForPolicyCommand(final PolicyCommand<?> policyCommand) {
final CommandToExceptionRegistry<PolicyCommand<?>, DittoRuntimeException> registry;
if (policyCommand instanceof PolicyActionCommand) {
registry = PolicyCommandToActionsExceptionRegistry.getInstance();
} else if (policyCommand instanceof PolicyModifyCommand) {
registry = PolicyCommandToModifyExceptionRegistry.getInstance();
} else {
registry = PolicyCommandToAccessExceptionRegistry.getInstance();
}
return registry.exceptionFrom(policyCommand);
}
/**
* Convert a policy entry label for a top-level policy action into a resource path for authorization check.
*
* @param label the policy entry label.
* @param command the top-level policy action command.
* @return the resource key.
*/
private static ResourceKey asResourceKey(final Label label, final PolicyCommand<?> command) {
return ResourceKey.newInstance(PoliciesResourceType.POLICY,
Policy.JsonFields.ENTRIES.getPointer().addLeaf(JsonKey.of(label)).append(command.getResourcePath()));
}
}