/
AuthorizationValidationVisitor.java
387 lines (341 loc) · 15.9 KB
/
AuthorizationValidationVisitor.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
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
385
386
387
/*
* JBoss, Home of Professional Open Source.
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
*
* This library 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 library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
package org.teiid.dqp.internal.process;
import java.util.*;
import org.teiid.CommandContext;
import org.teiid.PolicyDecider;
import org.teiid.adminapi.DataPolicy;
import org.teiid.adminapi.DataPolicy.Context;
import org.teiid.adminapi.DataPolicy.PermissionType;
import org.teiid.api.exception.query.QueryMetadataException;
import org.teiid.core.CoreConstants;
import org.teiid.core.TeiidComponentException;
import org.teiid.core.TeiidProcessingException;
import org.teiid.dqp.internal.process.multisource.MultiSourceElement;
import org.teiid.logging.AuditMessage;
import org.teiid.logging.LogConstants;
import org.teiid.logging.LogManager;
import org.teiid.logging.MessageLevel;
import org.teiid.metadata.AbstractMetadataRecord;
import org.teiid.query.QueryPlugin;
import org.teiid.query.function.FunctionLibrary;
import org.teiid.query.metadata.QueryMetadataInterface;
import org.teiid.query.metadata.TempMetadataID;
import org.teiid.query.resolver.util.ResolverUtil;
import org.teiid.query.sql.LanguageObject;
import org.teiid.query.sql.lang.*;
import org.teiid.query.sql.symbol.ElementSymbol;
import org.teiid.query.sql.symbol.Function;
import org.teiid.query.sql.symbol.GroupSymbol;
import org.teiid.query.sql.symbol.Symbol;
import org.teiid.query.sql.visitor.ElementCollectorVisitor;
import org.teiid.query.sql.visitor.GroupCollectorVisitor;
import org.teiid.query.validator.AbstractValidationVisitor;
public class AuthorizationValidationVisitor extends AbstractValidationVisitor {
private CommandContext commandContext;
private PolicyDecider decider;
public AuthorizationValidationVisitor(PolicyDecider decider, CommandContext commandContext) {
this.decider = decider;
this.commandContext = commandContext;
}
// ############### Visitor methods for language objects ##################
@Override
public void visit(Create obj) {
validateTemp(PermissionType.CREATE, obj.getTable().getNonCorrelationName(), false, obj.getTable(), Context.CREATE);
}
@Override
public void visit(AlterProcedure obj) {
validateEntitlements(Arrays.asList(obj.getTarget()), DataPolicy.PermissionType.ALTER, Context.ALTER);
}
@Override
public void visit(AlterTrigger obj) {
validateEntitlements(Arrays.asList(obj.getTarget()), DataPolicy.PermissionType.ALTER, obj.isCreate()?Context.CREATE:Context.ALTER);
}
@Override
public void visit(AlterView obj) {
validateEntitlements(Arrays.asList(obj.getTarget()), DataPolicy.PermissionType.ALTER, Context.ALTER);
}
@Override
public void visit(ObjectTable objectTable) {
String language = ObjectTable.DEFAULT_LANGUAGE;
if (objectTable.getScriptingLanguage() != null) {
language = objectTable.getScriptingLanguage();
}
Map<String, LanguageObject> map = new HashMap<String, LanguageObject>();
map.put(language, objectTable);
validateEntitlements(PermissionType.LANGUAGE, Context.QUERY, map);
}
private void validateTemp(DataPolicy.PermissionType action, String resource, boolean schema, LanguageObject object, Context context) {
Set<String> resources = Collections.singleton(resource);
logRequest(resources, context);
boolean allowed = decider.isTempAccessable(action, schema?resource:null, context, commandContext);
logResult(resources, context, allowed);
if (!allowed) {
handleValidationError(
QueryPlugin.Util.getString("ERR.018.005.0095", commandContext.getUserName(), "CREATE_TEMPORARY_TABLES"), //$NON-NLS-1$ //$NON-NLS-2$
Arrays.asList(object));
}
}
private void logRequest(Set<String> resources, Context context) {
if (LogManager.isMessageToBeRecorded(LogConstants.CTX_AUDITLOGGING, MessageLevel.DETAIL)) {
// Audit - request
AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-request", resources.toArray(new String[resources.size()]), commandContext); //$NON-NLS-1$
LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
}
}
@Override
public void visit(Drop obj) {
validateTemp(PermissionType.DROP, obj.getTable().getNonCorrelationName(), false, obj.getTable(), Context.DROP);
}
public void visit(Delete obj) {
validateEntitlements(obj);
}
public void visit(Insert obj) {
validateEntitlements(obj);
}
public void visit(Query obj) {
validateEntitlements(obj);
}
public void visit(Update obj) {
validateEntitlements(obj);
}
public void visit(StoredProcedure obj) {
validateEntitlements(obj);
}
public void visit(Function obj) {
if (FunctionLibrary.LOOKUP.equalsIgnoreCase(obj.getName())) {
try {
ResolverUtil.ResolvedLookup lookup = ResolverUtil.resolveLookup(obj, this.getMetadata());
List<Symbol> symbols = new LinkedList<Symbol>();
symbols.add(lookup.getGroup());
symbols.add(lookup.getKeyElement());
symbols.add(lookup.getReturnElement());
validateEntitlements(symbols, DataPolicy.PermissionType.READ, Context.QUERY);
} catch (TeiidComponentException e) {
handleException(e, obj);
} catch (TeiidProcessingException e) {
handleException(e, obj);
}
} else {
String schema = obj.getFunctionDescriptor().getSchema();
if (schema != null && !isSystemSchema(schema)) {
Map<String, Function> map = new HashMap<String, Function>();
map.put(obj.getFunctionDescriptor().getFullName(), obj);
validateEntitlements(PermissionType.EXECUTE, Context.FUNCTION, map);
}
}
}
// ######################### Validation methods #########################
/**
* Validate insert/merge entitlements
*/
protected void validateEntitlements(Insert obj) {
List<LanguageObject> insert = new LinkedList<LanguageObject>();
insert.add(obj.getGroup());
insert.addAll(obj.getVariables());
validateEntitlements(
insert,
DataPolicy.PermissionType.CREATE,
Context.INSERT);
if (obj.isMerge()) {
validateEntitlements(
insert,
DataPolicy.PermissionType.UPDATE,
Context.MERGE);
}
}
/**
* Validate update entitlements
*/
protected void validateEntitlements(Update obj) {
// Check that all elements used in criteria have read permission
HashSet<ElementSymbol> elements = new HashSet<ElementSymbol>();
ElementCollectorVisitor.getElements(obj.getChangeList().getClauseMap().values(), elements);
if (obj.getCriteria() != null) {
ElementCollectorVisitor.getElements(obj.getCriteria(), elements);
}
validateEntitlements(
elements,
DataPolicy.PermissionType.READ,
Context.UPDATE);
// The variables from the changes must be checked for UPDATE entitlement
// validateEntitlements on all the variables used in the update.
List<LanguageObject> updated = new LinkedList<LanguageObject>();
updated.add(obj.getGroup());
updated.addAll(obj.getChangeList().getClauseMap().keySet());
validateEntitlements(updated, DataPolicy.PermissionType.UPDATE, Context.UPDATE);
}
/**
* Validate delete entitlements
*/
protected void validateEntitlements(Delete obj) {
// Check that all elements used in criteria have read permission
if (obj.getCriteria() != null) {
validateEntitlements(
ElementCollectorVisitor.getElements(obj.getCriteria(), true),
DataPolicy.PermissionType.READ,
Context.DELETE);
}
// Check that all elements of group being deleted have delete permission
validateEntitlements(Arrays.asList(obj.getGroup()), DataPolicy.PermissionType.DELETE, Context.DELETE);
}
/**
* Validate query entitlements
*/
protected void validateEntitlements(Query obj) {
// If query contains SELECT INTO, validate INTO portion
Into intoObj = obj.getInto();
if ( intoObj != null ) {
GroupSymbol intoGroup = intoObj.getGroup();
Collection<LanguageObject> intoElements = new LinkedList<LanguageObject>();
intoElements.add(intoGroup);
try {
intoElements.addAll(ResolverUtil.resolveElementsInGroup(intoGroup, getMetadata()));
} catch (QueryMetadataException err) {
handleException(err, intoGroup);
} catch (TeiidComponentException err) {
handleException(err, intoGroup);
}
validateEntitlements(intoElements,
DataPolicy.PermissionType.CREATE,
Context.INSERT);
}
// Validate this query's entitlements
Collection<LanguageObject> entitledObjects = new ArrayList<LanguageObject>(GroupCollectorVisitor.getGroupsIgnoreInlineViews(obj, true));
if (!isXMLCommand(obj)) {
entitledObjects.addAll(ElementCollectorVisitor.getElements(obj, true));
}
if(entitledObjects.size() == 0) {
return;
}
validateEntitlements(entitledObjects, DataPolicy.PermissionType.READ, Context.QUERY);
}
/**
* Validate query entitlements
*/
protected void validateEntitlements(StoredProcedure obj) {
validateEntitlements(Arrays.asList(obj.getGroup()), DataPolicy.PermissionType.EXECUTE, Context.STORED_PROCEDURE);
}
/**
* Check that the user is entitled to access all data elements in the command.
*
* @param symbols The collection of <code>Symbol</code>s affected by these actions.
* @param actionCode The actions to validate for
* @param auditContext The {@link AuthorizationService} to use when resource auditing is done.
*/
protected void validateEntitlements(Collection<? extends LanguageObject> symbols, DataPolicy.PermissionType actionCode, Context auditContext) {
Map<String, LanguageObject> nameToSymbolMap = new LinkedHashMap<String, LanguageObject>();
for (LanguageObject symbol : symbols) {
try {
Object metadataID = null;
if(symbol instanceof ElementSymbol) {
metadataID = ((ElementSymbol)symbol).getMetadataID();
if (metadataID instanceof MultiSourceElement || metadataID instanceof TempMetadataID) {
continue;
}
} else if(symbol instanceof GroupSymbol) {
GroupSymbol group = (GroupSymbol)symbol;
metadataID = group.getMetadataID();
if (metadataID instanceof TempMetadataID) {
if (group.isProcedure()) {
Map<String, LanguageObject> procMap = new LinkedHashMap<String, LanguageObject>();
addToNameMap(((TempMetadataID)metadataID).getOriginalMetadataID(), symbol, procMap, getMetadata());
validateEntitlements(PermissionType.EXECUTE, auditContext, procMap);
} else if (group.isTempTable() && group.isImplicitTempGroupSymbol()) {
validateTemp(actionCode, group.getNonCorrelationName(), false, group, auditContext);
}
continue;
}
}
addToNameMap(metadataID, symbol, nameToSymbolMap, getMetadata());
} catch(QueryMetadataException e) {
handleException(e);
} catch(TeiidComponentException e) {
handleException(e);
}
}
validateEntitlements(actionCode, auditContext, nameToSymbolMap);
}
static void addToNameMap(Object metadataID, LanguageObject symbol, Map<String, LanguageObject> nameToSymbolMap, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
String fullName = metadata.getFullName(metadataID);
Object modelId = metadata.getModelID(metadataID);
String modelName = metadata.getFullName(modelId);
if (!isSystemSchema(modelName)) {
//foreign temp table full names are not schema qualified by default
if (!metadata.isVirtualModel(modelId)) {
GroupSymbol group = null;
if (symbol instanceof ElementSymbol) {
group = ((ElementSymbol)symbol).getGroupSymbol();
} else if (symbol instanceof GroupSymbol) {
group = (GroupSymbol)symbol;
}
if (group != null && group.isTempGroupSymbol() && !group.isGlobalTable()) {
fullName = modelName + AbstractMetadataRecord.NAME_DELIM_CHAR + modelId;
}
}
nameToSymbolMap.put(fullName, symbol);
}
}
static private boolean isSystemSchema(String modelName) {
return CoreConstants.SYSTEM_MODEL.equalsIgnoreCase(modelName) || CoreConstants.ODBC_MODEL.equalsIgnoreCase(modelName);
}
private void validateEntitlements(DataPolicy.PermissionType actionCode,
Context auditContext, Map<String, ? extends LanguageObject> nameToSymbolMap) {
if (nameToSymbolMap.isEmpty()) {
return;
}
Collection<String> inaccessibleResources = getInaccessibleResources(actionCode, nameToSymbolMap.keySet(), auditContext);
if(inaccessibleResources.isEmpty()) {
return;
}
List<LanguageObject> inaccessibleSymbols = new ArrayList<LanguageObject>(inaccessibleResources.size());
for (String name : inaccessibleResources) {
inaccessibleSymbols.add(nameToSymbolMap.get(name));
}
// CASE 2362 - do not include the names of the elements for which the user
// is not authorized in the exception message
handleValidationError(
QueryPlugin.Util.getString("ERR.018.005.0095", commandContext.getUserName(), actionCode), //$NON-NLS-1$
inaccessibleSymbols);
}
/**
* Out of the resources specified, return the subset for which the specified not have authorization to access.
*/
public Set<String> getInaccessibleResources(DataPolicy.PermissionType action, Set<String> resources, Context context) {
logRequest(resources, context);
Set<String> results = decider.getInaccessibleResources(action, resources, context, commandContext);
logResult(resources, context, results.isEmpty());
return results;
}
private void logResult(Set<String> resources, Context context,
boolean granted) {
if (LogManager.isMessageToBeRecorded(LogConstants.CTX_AUDITLOGGING, MessageLevel.DETAIL)) {
if (granted) {
AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-granted all", resources.toArray(new String[resources.size()]), commandContext); //$NON-NLS-1$
LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
} else {
AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-denied", resources.toArray(new String[resources.size()]), commandContext); //$NON-NLS-1$
LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
}
}
}
}