-
Notifications
You must be signed in to change notification settings - Fork 460
/
ReadAttributeHandler.java
351 lines (311 loc) · 18.6 KB
/
ReadAttributeHandler.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
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
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.controller.operations.global;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.operations.global.EnhancedSyntaxSupport.containsEnhancedSyntax;
import static org.jboss.as.controller.operations.global.EnhancedSyntaxSupport.extractAttributeName;
import java.util.logging.Level;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ExpressionResolver;
import org.jboss.as.controller.ObjectListAttributeDefinition;
import org.jboss.as.controller.ObjectMapAttributeDefinition;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationDefinition;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.UnauthorizedException;
import org.jboss.as.controller.access.AuthorizationResult;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.common.ControllerResolver;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.operations.validation.ModelTypeValidator;
import org.jboss.as.controller.operations.validation.ParametersValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* {@link org.jboss.as.controller.OperationStepHandler} reading a single attribute at the given operation address.
* The required request parameter "name" represents the attribute name.
*
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
*/
public class ReadAttributeHandler extends GlobalOperationHandlers.AbstractMultiTargetHandler {
public static final OperationDefinition DEFINITION = new SimpleOperationDefinitionBuilder(READ_ATTRIBUTE_OPERATION, ControllerResolver.getResolver("global"))
.setParameters(GlobalOperationAttributes.NAME, GlobalOperationAttributes.INCLUDE_DEFAULTS, GlobalOperationAttributes.INCLUDE_UNDEFINED_METRIC_VALUES)
.setReadOnly()
.setReplyType(ModelType.OBJECT)
.build();
public static final OperationStepHandler INSTANCE = new ReadAttributeHandler();
private static final SimpleAttributeDefinition RESOLVE = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.RESOLVE_EXPRESSIONS, ModelType.BOOLEAN)
.setRequired(false)
.setDefaultValue(ModelNode.FALSE)
.build();
public static final OperationDefinition RESOLVE_DEFINITION = new SimpleOperationDefinitionBuilder(READ_ATTRIBUTE_OPERATION, ControllerResolver.getResolver("global"))
.setParameters(RESOLVE, GlobalOperationAttributes.NAME, GlobalOperationAttributes.INCLUDE_DEFAULTS)
.setReadOnly()
.setReplyType(ModelType.OBJECT)
.build();
public static final OperationStepHandler RESOLVE_INSTANCE = new ReadAttributeHandler(true);
private final ParametersValidator validator = new ParametersValidator() {
@Override
public void validate(ModelNode operation) throws OperationFailedException {
super.validate(operation);
if( operation.hasDefined(ModelDescriptionConstants.RESOLVE_EXPRESSIONS)){
if(operation.get(ModelDescriptionConstants.RESOLVE_EXPRESSIONS).asBoolean(false) && !resolvable){
throw ControllerLogger.ROOT_LOGGER.unableToResolveExpressions();
}
}
}
};
private final OperationStepHandler overrideHandler;
private final boolean resolvable;
public ReadAttributeHandler() {
this(null, null, false);
}
public ReadAttributeHandler(boolean resolve){
this(null, null, resolve);
}
ReadAttributeHandler(FilteredData filteredData, OperationStepHandler overrideHandler, boolean resolvable) {
super(filteredData);
if( resolvable){
validator.registerValidator(RESOLVE.getName(), new ModelTypeValidator(ModelType.BOOLEAN, true));
}
validator.registerValidator(GlobalOperationAttributes.NAME.getName(), new StringLengthValidator(1));
validator.registerValidator(GlobalOperationAttributes.INCLUDE_DEFAULTS.getName(), new ModelTypeValidator(ModelType.BOOLEAN, true));
validator.registerValidator(GlobalOperationAttributes.INCLUDE_UNDEFINED_METRIC_VALUES.getName(), new ModelTypeValidator(ModelType.BOOLEAN, true));
assert overrideHandler == null || filteredData != null : "overrideHandler only supported with filteredData";
this.overrideHandler = overrideHandler;
this.resolvable = resolvable;
}
@Override
void doExecute(OperationContext context, ModelNode operation, FilteredData filteredData, boolean ignoreMissingResource) throws OperationFailedException {
// Add a step to authorize the attribute read once we determine the value below
context.addStep(operation, new AuthorizeAttributeReadHandler(filteredData), OperationContext.Stage.MODEL, true);
final boolean resolve = RESOLVE.resolveModelAttribute(context, operation).asBoolean();
if( resolve && resolvable ){
context.addStep(operation, ResolveAttributeHandler.getInstance(), OperationContext.Stage.MODEL, true);
}
if (filteredData == null) {
doExecuteInternal(context, operation);
} else {
try {
if (overrideHandler == null) {
doExecuteInternal(context, operation);
} else {
overrideHandler.execute(context, operation);
}
} catch (UnauthorizedException ue) {
// Just report the failure to the filter and complete normally
PathAddress pa = context.getCurrentAddress();
filteredData.addReadRestrictedAttribute(pa, operation.get(NAME).asString());
context.getResult().set(new ModelNode());
}
}
}
private void doExecuteInternal(OperationContext context, ModelNode operation) throws OperationFailedException {
validator.validate(operation);
String attributeName = GlobalOperationAttributes.NAME.resolveModelAttribute(context, operation).asString();
final boolean defaults = GlobalOperationAttributes.INCLUDE_DEFAULTS.resolveModelAttribute(context,operation).asBoolean();
final boolean includeUndefinedMetricValue = GlobalOperationAttributes.INCLUDE_UNDEFINED_METRIC_VALUES.resolveModelAttribute(context, operation).asBoolean();
final ImmutableManagementResourceRegistration registry = context.getResourceRegistration();
final boolean useEnhancedSyntax = containsEnhancedSyntax(attributeName, registry);
String attributeExpression = attributeName;
if (useEnhancedSyntax){
attributeName = extractAttributeName(attributeName);
}
final AttributeAccess attributeAccess = registry.getAttributeAccess(PathAddress.EMPTY_ADDRESS, attributeName);
if (attributeAccess == null) {
throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.unknownAttribute(attributeName));
}
assert attributeAccess.getAttributeDefinition() != null;
if (attributeAccess.getReadHandler() == null) {
resolveAttribute(context, attributeAccess.getAttributeDefinition(), attributeExpression, defaults, useEnhancedSyntax);
} else {
OperationStepHandler handler = attributeAccess.getReadHandler();
ClassLoader oldTccl = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(handler.getClass());
try {
handler.execute(context, operation);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
}
if (attributeAccess.getAccessType() == AttributeAccess.AccessType.METRIC) {
if (!context.getResult().isDefined() && !includeUndefinedMetricValue) {
// Use the undefined metric value for the attribute definition instead.
ModelNode undefinedMetricValue = attributeAccess.getAttributeDefinition().getUndefinedMetricValue();
if (undefinedMetricValue != null) {
context.getResult().set(undefinedMetricValue);
}
}
}
if (useEnhancedSyntax) {
// remove attribute name from expression string ("attribute-name.rest" => "rest")
int prefixLength = attributeName.length();
if (attributeExpression.charAt(prefixLength) == '.') {
prefixLength++; // remove also '.' character if present
}
String remainingExpression = attributeExpression.substring(prefixLength);
if (AttributeAccess.Storage.CONFIGURATION == attributeAccess.getStorageType()) {
ModelNode resolved = EnhancedSyntaxSupport.resolveEnhancedSyntax(remainingExpression, context.getResult(),
attributeAccess.getAttributeDefinition());
context.getResult().set(resolved);
} else {
assert AttributeAccess.Storage.RUNTIME == attributeAccess.getStorageType();
// Resolution must be postponed to RUNTIME stage for Storage.RUNTIME attributes.
context.addStep((context1, operation1) -> {
ModelNode resolved = EnhancedSyntaxSupport.resolveEnhancedSyntax(remainingExpression, context.getResult(),
attributeAccess.getAttributeDefinition());
context.getResult().set(resolved);
}, OperationContext.Stage.RUNTIME);
}
}
}
}
private static class AuthorizeAttributeReadHandler implements OperationStepHandler {
private final FilteredData filteredData;
private AuthorizeAttributeReadHandler(FilteredData filteredData) {
this.filteredData = filteredData;
}
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
if (filteredData == null) {
doExecuteInternal(context, operation);
} else {
try {
doExecuteInternal(context, operation);
} catch (UnauthorizedException ue) {
if (context.hasResult()) {
context.getResult().set(new ModelNode());
}
// Report the failure to the filter and complete normally
PathAddress pa = context.getCurrentAddress();
filteredData.addReadRestrictedAttribute(pa, operation.get(NAME).asString());
context.getResult().set(new ModelNode());
}
}
}
private void doExecuteInternal(OperationContext context, ModelNode operation) throws OperationFailedException {
ModelNode value = context.hasResult() ? context.getResult().clone() : new ModelNode();
AuthorizationResult authorizationResult = context.authorize(operation, operation.require(NAME).asString(), value);
if (authorizationResult.getDecision() == AuthorizationResult.Decision.DENY) {
context.getResult().clear();
throw ControllerLogger.ROOT_LOGGER.unauthorized(operation.require(OP).asString(), context.getCurrentAddress(), authorizationResult.getExplanation());
}
}
}
private static class ResolveAttributeHandler implements OperationStepHandler {
private ResolveAttributeHandler(){}
private static class ResolveAttributeHandlerHolder {
private static final ResolveAttributeHandler INSTANCE = new ResolveAttributeHandler();
}
public static ResolveAttributeHandler getInstance(){
return ResolveAttributeHandlerHolder.INSTANCE;
}
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
ModelNode unresolvedResult = context.hasResult() ? context.getResult().clone() : new ModelNode();
// For now, don't use the context to resolve, as we don't want to support vault resolution
// from a remote management client. The purpose of the vault is to require someone to have
// access to both the config (i.e. the expression) and to the vault itself in order to read, and
// allowing a remote user to use the management API to read defeats the purpose.
//ModelNode resolved = context.resolveExpressions(result);
// Instead we use a resolver that will not complain about unresolvable stuff (i.e. vault expressions),
// simply returning them unresolved.
ModelNode answer = ExpressionResolver.SIMPLE_LENIENT.resolveExpressions(unresolvedResult);
if (!answer.equals(unresolvedResult)) {
// SIMPLE_LENIENT will not resolve everything the context can, e.g. vault or credential store expressions.
// And we don't want to provide such resolution, as that kind of security-sensitive resolution should
// not escape the server process by being sent in a management op response. But if the true
// resolution differs from what SIMPLE_LENIENT did, we should just not resolve in our response and
// include a warning to that effect.
ModelNode fullyResolved = context.resolveExpressions(unresolvedResult);
if (!answer.equals(fullyResolved)) {
answer = unresolvedResult;
context.addResponseWarning(Level.WARNING,
ControllerLogger.MGMT_OP_LOGGER.attributeUnresolvableUsingSimpleResolution(
operation.get(NAME).asString(),
context.getCurrentAddress().toCLIStyleString(),
unresolvedResult));
}
}
context.getResult().set(answer);
}
}
static void resolveAttribute(OperationContext context, AttributeDefinition attribute, String attributeSyntax, boolean defaults, boolean enhancedSyntax) throws OperationFailedException {
final Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS, false);
final ModelNode subModel = resource.getModel();
if (enhancedSyntax) {
context.getResult().set(EnhancedSyntaxSupport.resolveEnhancedSyntax(attributeSyntax, subModel, attribute));
} else if (subModel.hasDefined(attribute.getName())) {
final ModelNode result = subModel.get(attribute.getName());
context.getResult().set(result);
if (defaults) {
handleObjectAttributes(context.getResult(), attribute);
}
} else if (defaults && attribute.getDefaultValue() != null) {
// No defined value in the model. See if we should reply with a default from the metadata,
// reply with undefined, or fail because it's a non-existent attribute name
context.getResult().set(attribute.getDefaultValue());
} else {
// model had no defined value, but we treat its existence in the model or the metadata
// as proof that it's a legit attribute name
context.getResult(); // this initializes the "result" to ModelType.UNDEFINED
}
}
private static void handleObjectAttributes(ModelNode model, AttributeDefinition attribute) {
if (attribute instanceof ObjectTypeAttributeDefinition) {
readNestedDefaults(model, (ObjectTypeAttributeDefinition) attribute);
} else if (attribute instanceof ObjectListAttributeDefinition) {
ObjectTypeAttributeDefinition valueType = ((ObjectListAttributeDefinition) attribute).getValueType();
for (int i = 0; i < model.asInt(); i++) {
readNestedDefaults(model.get(i), valueType);
}
} else if (attribute instanceof ObjectMapAttributeDefinition) {
ObjectTypeAttributeDefinition valueType = ((ObjectMapAttributeDefinition) attribute).getValueType();
for (String key : model.keys()) {
readNestedDefaults(model.get(key), valueType);
}
}
}
private static void readNestedDefaults(ModelNode model, ObjectTypeAttributeDefinition attribute) {
for (AttributeDefinition subAttribute : attribute.getValueTypes()) {
ModelNode defaultValue = subAttribute.getDefaultValue();
String subAttrName = subAttribute.getName();
if (defaultValue != null && !model.hasDefined(subAttrName)) {
model.get(subAttrName).set(defaultValue);
}
if (model.hasDefined(subAttrName)) {
handleObjectAttributes(model.get(subAttrName), subAttribute);
}
}
}
}