-
-
Notifications
You must be signed in to change notification settings - Fork 170
/
MongoPermissionsUtils.java
351 lines (310 loc) · 14.1 KB
/
MongoPermissionsUtils.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
/*-
* ========================LICENSE_START=================================
* restheart-security
* %%
* Copyright (C) 2018 - 2020 SoftInstigate
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* =========================LICENSE_END==================================
*/
package org.restheart.security.interceptors.mongo;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.google.gson.JsonElement;
import com.jayway.jsonpath.JsonPath;
import org.bson.BsonArray;
import org.bson.BsonDateTime;
import org.bson.BsonDocument;
import org.bson.BsonDouble;
import org.bson.BsonInt32;
import org.bson.BsonInt64;
import org.bson.BsonNull;
import org.bson.BsonString;
import org.bson.BsonValue;
import org.restheart.exchange.MongoRequest;
import org.restheart.idm.FileRealmAccount;
import org.restheart.idm.MongoRealmAccount;
import org.restheart.security.authorizers.AclPermission;
import org.restheart.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.undertow.attribute.ExchangeAttributes;
public class MongoPermissionsUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(MongoPermissionsUtils.class);
/**
* Interpolate values in doc like '@user', '@user.property', @now
*
* Supports accounts handled by MongoRealAuthenticator and
* FileRealmAuthenticator
*
* Legacy variable names %USER, %ROLES and %NOW are supported as well
*
* @param request
* @param bson
* @return bson with interpolated variables
*/
public static BsonValue interpolateBson(MongoRequest request, BsonValue bson) {
if (bson.isDocument()) {
var ret = new BsonDocument();
var doc = bson.asDocument();
doc.keySet().stream().forEach(k -> {
var value = doc.get(k);
if (value.isString()) {
ret.put(k, interpolatePropValue(request, k, doc.get(k).asString().getValue()));
} else if (value.isDocument()) {
ret.put(k, interpolateBson(request, value));
} else if (value.isArray()) {
value.asArray().stream().forEachOrdered(e -> ret.put(k, interpolateBson(request, e)));
} else {
ret.put(k, value);
}
});
return ret;
} else if (bson.isArray()) {
var ret = new BsonArray();
bson.asArray().stream().forEachOrdered(ae -> ret.add(interpolateBson(request, ae)));
return ret;
} else if (bson.isString()) {
return interpolatePropValue(request, null, bson.asString().getValue());
} else {
return bson;
}
}
/**
* If value is a '@user', '@user.property', '@request',
* '@request.remoteIp', '@mongoPermissions', '@mongoPermissions.readFilter',
* '@now', returns the interpolated value.
*
* For '@user' and '@mongoPermissions' supports accounts handled by
* MongoRealAuthenticator and FileRealmAuthenticator
*
* Legacy variable names %USER, %ROLES and %NOW are supported as well
*
* @param request
* @param key
* @param value
* @return
*/
public static BsonValue interpolatePropValue(MongoRequest request, String key, String value) {
if (value == null) {
return BsonNull.VALUE;
} else if ("%USER".equals(value)) {
return new BsonString(ExchangeAttributes.remoteUser().readAttribute(request.getExchange()));
} else if ("%ROLES".equals(value)) {
if (Objects.nonNull(request.getAuthenticatedAccount())
&& Objects.nonNull(request.getAuthenticatedAccount().getRoles())) {
var ret = new BsonArray();
request.getAuthenticatedAccount().getRoles().stream().map(s -> new BsonString(s))
.forEachOrdered(ret::add);
return ret;
} else {
return new BsonArray();
}
} else if ("%NOW".equals(value) || "@now".equals(value)) {
return new BsonDateTime(Instant.now().getEpochSecond() * 1000);
} else if (value.equals("@user")) {
if (request.getAuthenticatedAccount() instanceof MongoRealmAccount) {
var maccount = (MongoRealmAccount) request.getAuthenticatedAccount();
return maccount.getAccountDocument();
} else if (request.getAuthenticatedAccount() instanceof FileRealmAccount) {
var faccount = (FileRealmAccount) request.getAuthenticatedAccount();
return toBson(faccount.getAccountProperties());
} else {
return BsonNull.VALUE;
}
} else if (value.equals("@request")) {
return getRequestObject(request);
} else if (value.startsWith("@request.") && value.length() > 8) {
var requestObject = getRequestObject(request);
var prop = value.substring(9);
LOGGER.debug("request doc: {}", requestObject.toJson());
if (prop.contains(".")) {
try {
JsonElement v = JsonPath.read(requestObject.toJson(), "$.".concat(prop));
return JsonUtils.parse(v.toString());
} catch (Throwable pnfe) {
return BsonNull.VALUE;
}
} else {
if (requestObject.containsKey(prop)) {
return requestObject.get(prop);
} else {
return BsonNull.VALUE;
}
}
} else if (value.equals("@mongoPermissions")) {
var permission = AclPermission.from(request.getExchange());
if (permission != null && permission.getMongoPermissions() != null) {
return permission.getMongoPermissions().asBson();
} else {
return BsonNull.VALUE;
}
} else if (value.startsWith("@mongoPermissions.") && value.length() > 17) {
var permission = AclPermission.from(request.getExchange());
if (permission != null && permission.getMongoPermissions() != null) {
var doc = permission.getMongoPermissions().asBson();
var prop = value.substring(18);
LOGGER.debug("permission doc: {}", permission);
if (prop.contains(".")) {
try {
JsonElement v = JsonPath.read(doc.toJson(), "$.".concat(prop));
return JsonUtils.parse(v.toString());
} catch (Throwable pnfe) {
return BsonNull.VALUE;
}
} else {
if (doc.containsKey(prop)) {
return doc.get(prop);
} else {
return BsonNull.VALUE;
}
}
} else {
return BsonNull.VALUE;
}
} else if (value.startsWith("@user.") && value.length() > 5) {
if (request.getAuthenticatedAccount() instanceof MongoRealmAccount) {
var maccount = (MongoRealmAccount) request.getAuthenticatedAccount();
var accountDoc = maccount.getAccountDocument();
var prop = value.substring(6);
LOGGER.debug("account doc: {}", accountDoc.toJson());
if (prop.contains(".")) {
try {
JsonElement v = JsonPath.read(accountDoc.toJson(), "$.".concat(prop));
return JsonUtils.parse(v.toString());
} catch (Throwable pnfe) {
return BsonNull.VALUE;
}
} else {
if (accountDoc.containsKey(prop)) {
return accountDoc.get(prop);
} else {
return BsonNull.VALUE;
}
}
} else if (request.getAuthenticatedAccount() instanceof FileRealmAccount) {
var faccount = (FileRealmAccount) request.getAuthenticatedAccount();
return fromProperties(faccount.getAccountProperties(), value.substring(6));
} else {
return BsonNull.VALUE;
}
} else {
return new BsonString(value);
}
}
@SuppressWarnings("unchecked")
private static BsonValue fromProperties(Map<String, Object> properties, String key) {
if (key.contains(".")) {
var first = key.substring(0, key.indexOf("."));
var last = key.substring(key.indexOf(".") + 1);
var subProperties = properties.get(first);
if (subProperties != null && subProperties instanceof Map<?, ?>) {
return fromProperties((Map<String, Object>) subProperties, last);
} else if (subProperties != null && subProperties instanceof List<?>) {
List<Object> list = (List<Object>) subProperties;
// we have a list, the next subkey must be a number as in first.0 or first.0.b
if (last.contains(".")) {
var next = last.substring(0, last.indexOf("."));
try {
var idx = Integer.parseInt(next);
var elementAtIdx = list.get(idx);
var afterNext = last.substring(last.indexOf(".") + 1);
if (elementAtIdx instanceof Map<?, ?>) {
return fromProperties((Map<String, Object>) elementAtIdx, afterNext);
} else {
LOGGER.warn("Key {} at {} matches an array but selected element is not an object", key,
first);
return BsonNull.VALUE;
}
} catch (Throwable t) {
LOGGER.warn("Key {} at {} matches an array but following part is not a number", key, first);
return BsonNull.VALUE;
}
} else {
try {
var idx = Integer.parseInt(last);
return toBson(list.get(idx));
} catch (Throwable t) {
LOGGER.error("Key {} at {} matches an array but following part is not a number", key, first);
return BsonNull.VALUE;
}
}
} else {
return BsonNull.VALUE;
}
} else {
if (properties.containsKey(key)) {
return toBson(properties.get(key));
} else {
return BsonNull.VALUE;
}
}
}
@SuppressWarnings("unchecked")
private static BsonValue toBson(Object obj) {
if (obj instanceof String) {
return new BsonString((String) obj);
} else if (obj instanceof Map<?, ?>) {
var map = (Map<String, Object>) obj;
var ret = new BsonDocument();
map.entrySet().stream().forEachOrdered(e -> ret.put(e.getKey(), toBson(e.getValue())));
return ret;
} else if (obj instanceof List<?>) {
var list = (List<Object>) obj;
var ret = new BsonArray();
list.stream().forEachOrdered(e -> ret.add(toBson(e)));
return ret;
} else if (obj instanceof Integer) {
return new BsonInt32((Integer) obj);
} else if (obj instanceof Long) {
return new BsonInt64((Long) obj);
} else if (obj instanceof Double) {
return new BsonDouble((Double) obj);
} else {
LOGGER.warn("ovverridendProp value not suppored {}", obj);
return BsonNull.VALUE;
}
}
private static BsonDocument getRequestObject(final MongoRequest request) {
var exchange = request.getExchange();
var properties = new BsonDocument();
var _userName = ExchangeAttributes.remoteUser().readAttribute(exchange);
var userName = _userName != null ? new BsonString(_userName) : BsonNull.VALUE;
// remote user
properties.put("userName", userName);
// dateTime
properties.put("epochTimeStamp", new BsonDateTime(Instant.now().getEpochSecond() * 1000));
// dateTime
properties.put("dateTime", new BsonString(ExchangeAttributes.dateTime().readAttribute(exchange)));
// local ip
properties.put("localIp", new BsonString(ExchangeAttributes.localIp().readAttribute(exchange)));
// local port
properties.put("localPort", new BsonString(ExchangeAttributes.localPort().readAttribute(exchange)));
// local server name
properties.put("localServerName", new BsonString(ExchangeAttributes.localServerName().readAttribute(exchange)));
// request query string
properties.put("queryString", new BsonString(ExchangeAttributes.queryString().readAttribute(exchange)));
// request relative path
properties.put("relativePath", new BsonString(ExchangeAttributes.relativePath().readAttribute(exchange)));
// remote ip
properties.put("remoteIp", new BsonString(ExchangeAttributes.remoteIp().readAttribute(exchange)));
// request method
properties.put("requestMethod", new BsonString(ExchangeAttributes.requestMethod().readAttribute(exchange)));
// request protocol
properties.put("requestProtocol", new BsonString(ExchangeAttributes.requestProtocol().readAttribute(exchange)));
return properties;
}
}