-
Notifications
You must be signed in to change notification settings - Fork 14
/
CurrentDetails.java
636 lines (555 loc) · 21.5 KB
/
CurrentDetails.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/*
* Copyright 2006-2017 University of Dundee. All rights reserved.
* Use is subject to license terms supplied in LICENSE.txt
*/
package ome.security.basic;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ome.system.EventContext;
import ome.system.Principal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import ome.api.local.LocalAdmin;
import ome.conditions.ApiUsageException;
import ome.conditions.InternalException;
import ome.conditions.SecurityViolation;
import ome.model.IObject;
import ome.model.core.OriginalFile;
import ome.model.enums.AdminPrivilege;
import ome.model.enums.EventType;
import ome.model.internal.Details;
import ome.model.internal.Permissions;
import ome.model.internal.Permissions.Right;
import ome.model.internal.Permissions.Role;
import ome.model.meta.Event;
import ome.model.meta.EventLog;
import ome.model.meta.Experimenter;
import ome.model.meta.ExperimenterGroup;
import ome.model.meta.GroupExperimenterMap;
import ome.model.meta.Session;
import ome.security.SystemTypes;
import ome.services.messages.RegisterServiceCleanupMessage;
import ome.services.sessions.SessionContext;
import ome.services.sessions.state.SessionCache;
import ome.services.sessions.stats.SessionStats;
import ome.services.sharing.ShareStore;
import ome.services.util.ServiceHandler;
import ome.system.Roles;
import ome.tools.hibernate.HibernateUtils;
/**
* Stores information related to the security context of the current thread.
* Code calling into the server must setup CurrentDetails properly. An existing
* user must be set (the creation of a new user is only allowed if the current
* user is set to root; root always exists. QED.) The event must also be set.
* Umask is optional.
*
* This information is stored in a Details object, but unlike Details which
* assumes that an empty value signifies increased security levels, empty values
* here signify reduced security levels. E.g.,
*
* Details: user == null implies that the object belongs to root
* CurrentDetails: user == null implies that the current user is "nobody" (anonymous)
*/
public class CurrentDetails implements PrincipalHolder {
private static Logger log = LoggerFactory.getLogger(CurrentDetails.class);
private final SessionCache cache;
private final Roles roles;
private final SystemTypes sysTypes;
private final LightAdminPrivileges adminPrivileges;
private final ThreadLocal<LinkedList<BasicEventContext>> contexts = new ThreadLocal<LinkedList<BasicEventContext>>();
private final Set<String> managedRepoUuids;
private final Set<String> scriptRepoUuids;
/**
* Call context set on the current details before login occurred. If this
* is the case, then it will get consumed and
*/
private final ThreadLocal<Map<String, String>> delayedCallContext
= new ThreadLocal<Map<String, String>>();
/**
* Default constructor. Should only be used for testing, since the stats
* used will not be correct.
*/
public CurrentDetails() {
this(null);
}
public CurrentDetails(SessionCache cache) {
this.cache = cache;
this.roles = new Roles();
this.sysTypes = new SystemTypes(roles);
this.adminPrivileges = new LightAdminPrivileges(roles);
this.managedRepoUuids = Collections.emptySet();
this.scriptRepoUuids = Collections.emptySet();
}
public CurrentDetails(SessionCache cache, Roles roles, SystemTypes sysTypes, LightAdminPrivileges adminPrivileges,
Set<String> managedRepoUuids, Set<String> scriptRepoUuids) {
this.cache = cache;
this.roles = roles;
this.sysTypes = sysTypes;
this.adminPrivileges = adminPrivileges;
this.managedRepoUuids = managedRepoUuids;
this.scriptRepoUuids = scriptRepoUuids;
}
private LinkedList<BasicEventContext> list() {
LinkedList<BasicEventContext> list = contexts.get();
if (list == null) {
list = new LinkedList<BasicEventContext>();
contexts.set(list);
}
return list;
}
// Method call context methods
// =================================================================
public Map<String, String> setContext(Map<String, String> ctx) {
LinkedList<BasicEventContext> list = list();
if (list.size() == 0) {
delayedCallContext.set(ctx);
return null;
} else {
return list.getLast().setCallContext(ctx);
}
}
public Map<String, String> getContext() {
return list().getLast().getCallContext();
}
protected void checkDelayedCallContext(BasicEventContext bec) {
Map<String, String> ctx = delayedCallContext.get();
delayedCallContext.set(null);
bec.setCallContext(ctx);
}
// PrincipalHolder methods
// =================================================================
public int size() {
return list().size();
}
public Principal getLast() {
return list().getLast().getPrincipal();
}
public void login(Principal principal) {
// Can't use the method in SessionManager since that leads to a
// circular reference in Spring.
final String uuid = principal.getName();
final SessionContext ctx = cache.getSessionContext(uuid);
final SessionStats stats = ctx.stats();
final BasicEventContext c = new BasicEventContext(principal, stats);
login(c);
}
/**
* Login method which can be used by the security system to replace the
* existing {@link BasicEventContext}.
*/
public void login(BasicEventContext bec) {
if (log.isDebugEnabled()) {
log.debug("Logging in :" + bec);
}
checkDelayedCallContext(bec);
list().add(bec);
bec.getStats().methodIn();
}
public int logout() {
LinkedList<BasicEventContext> list = list();
BasicEventContext bec = list.removeLast();
bec.getStats().methodOut();
if (log.isDebugEnabled()) {
log.debug("Logged out: " + bec);
}
return list.size();
}
// High-level methods used to fulfill {@link SecuritySystem}
// =================================================================
/**
* Checks if the current {@link Thread} has non-null {@link Experimenter},
* {@link Event}, and {@link ExperimenterGroup}, required for proper
* functioning of the security system.
*/
public boolean isReady() {
BasicEventContext c = current();
if (c.getEvent() != null && c.getGroup() != null
&& c.getOwner() != null) {
return true;
}
return false;
}
public boolean isGraphCritical(Details details) {
EventContext ec = getCurrentEventContext();
long gid = ec.getCurrentGroupId();
Permissions perms = ec.getCurrentGroupPermissions();
if (gid < 0) {
try {
ExperimenterGroup g = details.getGroup();
gid = g.getId();
perms = g.getDetails().getPermissions();
} catch (NullPointerException npe) {
throw new SecurityViolation("isGraphCriticalCheck: not enough context");
}
if (gid == roles.getUserGroupId()) {
throw new SecurityViolation(
"isGraphCriticalCheck: Current group < 0 while accessing 'user' group!");
}
}
boolean admin = ec.isCurrentUserAdmin();
boolean pi = ec.getLeaderOfGroupsList().contains(gid);
if (perms.isGranted(Role.WORLD, Right.READ)) {
// Public groups (rwrwrw) are always non-critical
return false;
} else if (perms.isGranted(Role.GROUP, Right.READ)) {
// Since the object will be contained in the group,
// then it will be readable regardless.
return false;
} else {
// This is a private group. Any form of admin modification is
// critical.
return admin || pi;
}
}
public boolean isOwnerOrSupervisor(IObject object) {
if (object == null) {
throw new ApiUsageException("Object can't be null");
}
final Long o = HibernateUtils.nullSafeOwnerId(object);
final Long g; // see 2874 and chmod
if (object instanceof ExperimenterGroup) {
g = object.getId();
} else {
g = HibernateUtils.nullSafeGroupId(object);
}
final EventContext ec = getCurrentEventContext();
if (ec.getLeaderOfGroupsList().contains(g)) {
/* is group leader */
return true;
}
if (ec.getCurrentUserId().equals(o)) {
/* is owner */
return true;
}
if (!ec.isCurrentUserAdmin()) {
/* neither data owner nor group leader nor administrator */
return false;
}
final boolean isSysType = sysTypes.isSystemType(object.getClass());
final Set<AdminPrivilege> privileges = ec.getCurrentAdminPrivileges();
if (isSysType) {
if (object instanceof Experimenter) {
return privileges.contains(adminPrivileges.getPrivilege(AdminPrivilege.VALUE_MODIFY_USER));
} else if (object instanceof ExperimenterGroup) {
return privileges.contains(adminPrivileges.getPrivilege(AdminPrivilege.VALUE_MODIFY_GROUP));
} else if (object instanceof GroupExperimenterMap) {
return privileges.contains(adminPrivileges.getPrivilege(AdminPrivilege.VALUE_MODIFY_GROUP_MEMBERSHIP));
} else {
return true;
}
} else {
if (object instanceof OriginalFile) {
final String repo = ((OriginalFile) object).getRepo();
if (repo != null) {
if (managedRepoUuids.contains(repo)) {
return privileges.contains(adminPrivileges.getPrivilege(AdminPrivilege.VALUE_WRITE_MANAGED_REPO));
} else if (scriptRepoUuids.contains(repo)) {
return privileges.contains(adminPrivileges.getPrivilege(AdminPrivilege.VALUE_WRITE_SCRIPT_REPO));
} else {
/* other repository */
return privileges.contains(adminPrivileges.getPrivilege(AdminPrivilege.VALUE_WRITE_FILE));
}
} else {
/* not in repository */
return privileges.contains(adminPrivileges.getPrivilege(AdminPrivilege.VALUE_WRITE_FILE));
}
} else {
return privileges.contains(adminPrivileges.getPrivilege(AdminPrivilege.VALUE_WRITE_OWNED));
}
}
}
// State management
// =================================================================
/**
* Replaces all the simple-valued fields in the {@link BasicEventContext}.
* This method
*/
void checkAndInitialize(EventContext ec, LocalAdmin admin, ShareStore store) {
current().checkAndInitialize(ec, admin, store);
}
/**
* Returns the current {@link BasicEventContext instance} throwing an
* exception if there isn't one.
*/
BasicEventContext current() {
BasicEventContext c = list().getLast();
return c;
}
/**
* @return the current event context
*/
public EventContext getCurrentEventContext() {
return current();
}
/**
* It suffices to set the {@link Details} to a new instance to make this
* context unusable. {@link #isReady()} will return false.
*/
public void invalidateCurrentEventContext() {
BasicEventContext c = current();
c.invalidate();
if (log.isDebugEnabled()) {
log.debug("Invalidated login: " + c);
}
}
// ~ Events and Details
// =================================================================
public Event newEvent(Session session, EventType type,
TokenHolder tokenHolder) {
BasicEventContext c = current();
Event e = new Event();
e.setType(type);
e.setTime(new Timestamp(System.currentTimeMillis()));
tokenHolder.setToken(e.getGraphHolder());
e.getDetails().setPermissions(Permissions.READ_ONLY);
// Proxied if necessary
e.setExperimenter(c.getOwner());
e.setExperimenterGroup(c.getGroup());
e.setSession(session);
c.setEvent(e);
return e;
}
public void addLog(String action, Class klass, Long id) {
Assert.notNull(action);
Assert.notNull(klass);
Assert.notNull(id);
if (Event.class.isAssignableFrom(klass)
|| EventLog.class.isAssignableFrom(klass)) {
if (log.isDebugEnabled()) {
log.debug("Not logging creation of logging type:" + klass);
}
return; // EARLY EXIT
} else {
if (!isReady()) {
throw new InternalException("Not ready to add EventLog");
}
}
if (log.isInfoEnabled()) {
log.info("Adding log:" + action + "," + klass + "," + id);
}
BasicEventContext c = current();
List<EventLog> list = current().getLogs();
if (list == null) {
list = new ArrayList<EventLog>();
c.setLogs(list);
}
EventLog l = new EventLog();
l.setAction(action);
l.setEntityType(klass.getName()); // TODO could be id to Type entity
l.setEntityId(id);
l.setEvent(c.getEvent());
Details d = Details.create();
d.setPermissions(Permissions.WORLD_IMMUTABLE);
l.getDetails().copy(d);
list.add(l);
}
public SessionStats getStats() {
return current().getStats();
}
public List<EventLog> getLogs() { // TODO defensive copy
List<EventLog> logs = current().getLogs();
return logs == null ? new ArrayList<EventLog>() : logs;
}
public void clearLogs() {
current().setLogs(null);
}
/**
* Creates a {@link Details} object for the current security context.
*
* The {@link Permissions} on the instance are calculated from the current
* group as well as the user's umask.
*
* @return details for the current security context
* @see <a href="https://trac.openmicroscopy.org/ome/ticket/1434">ticket:1434</a>
*/
public Details createDetails() {
final BasicEventContext c = current();
final Details d = Details.create(new Object[]{c, c.getCallContext()});
d.setCreationEvent(c.getEvent());
d.setUpdateEvent(c.getEvent());
d.setOwner(c.getOwner());
d.setGroup(c.getGroup());
// ticket:1434
final Permissions groupPerms = c.getCurrentGroupPermissions();
final Permissions p = new Permissions(groupPerms);
d.setPermissions(p);
return d;
}
public void applyContext(Details details, boolean changePerms) {
final BasicEventContext c = current();
details.setContexts(new Object[]{c, c.getCallContext()});
if (changePerms) {
// Make the permissions match (#8277)
final Permissions groupPerms = c.getCurrentGroupPermissions();
if (groupPerms != Permissions.DUMMY) {
details.setPermissions(new Permissions(groupPerms));
} else {
// In the case of the dummy, we will be required to have
// the group id already set in the context.
ExperimenterGroup group = details.getGroup();
if (group != null) {
// Systypes still will have DUMMY values.
Long gid = details.getGroup().getId();
Permissions p = c.getPermissionsForGroup(gid);
if (p != null) {
// Ticket:9505. This must be a new copy of the permissions
// in order to prevent the restrictions being modified by
// later objects!
details.setPermissions(new Permissions(p));
} else if (gid.equals(Long.valueOf(roles.getUserGroupId()))) {
details.setPermissions(new Permissions(Permissions.EMPTY));
} else {
throw new InternalException("No permissions: " + details);
}
}
}
}
}
/**
* Checks the "groupPermissions" map in {@link BasicEventContext} which has
* been filled up by calls to {@link BasicEventContext#setPermissionsForGroup(Long, Permissions)}
* during {@link BasicACLVoter#allowLoad(org.hibernate.Session, Class, Details, long)}.
* @param session the Hibernate session
*/
public void loadPermissions(org.hibernate.Session session) {
current().loadPermissions(session);
}
public Experimenter getOwner() {
return current().getOwner();
}
public Experimenter getSudoer() {
return current().getSudoer();
}
public ExperimenterGroup getGroup() {
return current().getGroup();
}
public Set<AdminPrivilege> getAdminPrivileges() {
return current().getAdminPrivileges();
}
public Event getEvent() {
return current().getEvent();
}
/**
* Take all values during loadEventContext() in one shot. Event is set
* during {@link #newEvent(long, EventType, TokenHolder)} and possibly
* updated via {@link #updateEvent(Event)}.
*/
void setValues(Experimenter owner, Experimenter sudoer, ExperimenterGroup group,
Permissions perms,
boolean isAdmin, Set<AdminPrivilege> adminPrivileges, boolean isReadOnly, Long shareId) {
BasicEventContext c = current();
c.setOwner(owner);
c.setSudoer(sudoer);
c.setGroup(group, perms);
c.setAdmin(isAdmin);
c.setAdminPrivileges(adminPrivileges);
c.setReadOnly(isReadOnly);
c.setShareId(shareId);
}
/**
* Allows for updating the {@link Event} if the session is not readOnly.
*/
void updateEvent(Event event) {
current().setEvent(event);
}
/**
* @return if the current user is the system's <q>guest</q> user
*/
public boolean isCurrentUserGuest() {
return current().getCurrentUserId() == roles.getGuestId();
}
// ~ Cleanups
// =========================================================================
/**
* Add a {@link RegisterServiceCleanupMessage} to the current thread for
* cleanup by the {@link ServiceHandler} on exit.
*/
public void addCleanup(RegisterServiceCleanupMessage cleanup) {
Set<RegisterServiceCleanupMessage> cleanups = current()
.getServiceCleanups();
if (cleanups == null) {
cleanups = new HashSet<RegisterServiceCleanupMessage>();
current().setServiceCleanups(cleanups);
}
cleanups.add(cleanup);
}
/**
* Returns the current cleanups and resets the {@link Set}. Instances can
* most likely only be closed once, so it doesn't make sense to keep them
* around. The first caller of this method is responsible for closing all of
* them.
* @return a new copy of the current cleanups
*/
public Set<RegisterServiceCleanupMessage> emptyCleanups() {
Set<RegisterServiceCleanupMessage> set = current().getServiceCleanups();
if (current().getServiceCleanups() == null) {
return Collections.emptySet();
} else {
Set<RegisterServiceCleanupMessage> copy = new HashSet<RegisterServiceCleanupMessage>(
set);
set.clear();
return copy;
}
}
// ~ Subsystems
// =========================================================================
public boolean addDisabled(String id) {
Set<String> s = current().getDisabledSubsystems();
if (s == null) {
s = new HashSet<String>();
current().setDisabledSubsystems(s);
}
return s.add(id);
}
public boolean addAllDisabled(String... ids) {
Set<String> s = current().getDisabledSubsystems();
if (s == null) {
s = new HashSet<String>();
current().setDisabledSubsystems(s);
}
if (ids != null) {
return Collections.addAll(s, ids);
}
return false;
}
public boolean removeDisabled(String id) {
Set<String> s = current().getDisabledSubsystems();
if (s != null && id != null) {
return s.remove(id);
}
return false;
}
public boolean removeAllDisabled(String... ids) {
Set<String> s = current().getDisabledSubsystems();
if (s != null && ids != null) {
boolean changed = false;
for (String string : ids) {
changed |= s.remove(string);
}
}
return false;
}
public void clearDisabled() {
current().setDisabledSubsystems(null);
}
public boolean isDisabled(String id) {
if (size() == 0) {
// The security system is not active, so nothing can have
// been "disabled"
return false;
} else {
Set<String> s = current().getDisabledSubsystems();
if (s == null || id == null || !s.contains(id)) {
return false;
}
return true;
}
}
}