-
Notifications
You must be signed in to change notification settings - Fork 530
Expand file tree
/
Copy pathWebSession.java
More file actions
1082 lines (950 loc) · 37.3 KB
/
WebSession.java
File metadata and controls
1082 lines (950 loc) · 37.3 KB
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2026 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.cloudbeaver.model.session;
import io.cloudbeaver.*;
import io.cloudbeaver.model.*;
import io.cloudbeaver.model.app.ServletApplication;
import io.cloudbeaver.model.app.ServletAuthApplication;
import io.cloudbeaver.model.session.monitor.TaskProgressMonitor;
import io.cloudbeaver.model.user.WebUser;
import io.cloudbeaver.service.DBWSessionHandler;
import io.cloudbeaver.service.sql.WebSQLConstants;
import io.cloudbeaver.utils.CBModelConstants;
import io.cloudbeaver.utils.WebDataSourceUtils;
import io.cloudbeaver.utils.WebEventUtils;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBFileController;
import org.jkiss.dbeaver.model.DBPAdaptable;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.DBPEventListener;
import org.jkiss.dbeaver.model.access.DBAAuthCredentials;
import org.jkiss.dbeaver.model.access.DBACredentialsProvider;
import org.jkiss.dbeaver.model.auth.*;
import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration;
import org.jkiss.dbeaver.model.exec.DBCException;
import org.jkiss.dbeaver.model.meta.Association;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.navigator.DBNModel;
import org.jkiss.dbeaver.model.rm.*;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.BaseProgressMonitor;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.security.SMAdminController;
import org.jkiss.dbeaver.model.security.SMConstants;
import org.jkiss.dbeaver.model.security.SMController;
import org.jkiss.dbeaver.model.sql.DBQuotaException;
import org.jkiss.dbeaver.model.websocket.event.MessageType;
import org.jkiss.dbeaver.model.websocket.event.WSSessionLogUpdatedEvent;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.utils.CommonUtils;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;
/**
* Web session.
* Is the main source of data in web application
*/
//TODO: split to authenticated and non authenticated context
public class WebSession extends BaseWebSession
implements SMSessionWithAuth, SMCredentialsProvider, DBACredentialsProvider, DBPAdaptable {
private static final Log log = Log.getLog(WebSession.class);
public static final SMSessionType CB_SESSION_TYPE = new SMSessionType("CloudBeaver");
private static final String WEB_SESSION_AUTH_CONTEXT_TYPE = "web-session";
private static final AtomicInteger TASK_ID = new AtomicInteger();
public static String RUNTIME_PARAM_AUTH_INFOS = "auth-infos";
public static String RUNTIME_PARAM_CLIENT_ORIGIN = "client-origin";
private final AtomicInteger taskCount = new AtomicInteger();
private final String lastRemoteAddr;
private String lastRemoteUserAgent;
private String locale;
private boolean cacheExpired;
private String clientOrigin;
protected WebSessionGlobalProjectImpl globalProject;
private final List<WebServerMessage> sessionMessages = new ArrayList<>();
private final Map<String, WebAsyncTaskInfo> asyncTasks = new HashMap<>();
// Map of auth tokens. Key is authentication provider
private final List<WebAuthInfo> authTokens = new ArrayList<>();
private DBNModel navigatorModel;
private final ReadWriteLock navigatorModelLock = new ReentrantReadWriteLock(true);
private final DBRProgressMonitor progressMonitor = new SessionProgressMonitor();
private final Map<String, DBWSessionHandler<WebSession>> sessionHandlers;
private final WebDataSourceConnectEventListener connectListener = new WebDataSourceConnectEventListener(this);
public WebSession(
@NotNull WebHttpRequestInfo requestInfo,
@NotNull ServletAuthApplication application,
@NotNull Map<String, DBWSessionHandler<WebSession>> sessionHandlers
) throws DBException {
this(
Objects.requireNonNull(requestInfo.getId()),
CommonUtils.toString(requestInfo.getLocale()),
application,
sessionHandlers,
requestInfo.getLastRemoteAddress()
);
updateSessionParameters(requestInfo);
}
protected WebSession(
@NotNull String id,
@Nullable String locale,
@NotNull ServletApplication application,
@NotNull Map<String, DBWSessionHandler<WebSession>> sessionHandlers,
@Nullable String remoteAddr
) throws DBException {
super(id, application);
if (CommonUtils.isEmpty(remoteAddr)) {
throw new DBException("Remote address cannot be empty");
}
this.lastRemoteAddr = remoteAddr;
this.lastAccessTime = this.createTime;
this.sessionHandlers = sessionHandlers;
setLocale(CommonUtils.toString(locale, this.locale));
//force authorization of anonymous session to avoid access error,
//because before authorization could be called by any request,
//but now 'updateInfo' is called only in special requests,
//and the order of requests is not guaranteed.
//look at CB-4747
refreshSessionAuth();
}
@Nullable
@Override
public SMSessionPrincipal getSessionPrincipal() {
synchronized (authTokens) {
if (authTokens.isEmpty()) {
return null;
}
return authTokens.getFirst();
}
}
@Nullable
public WebSessionProjectImpl getSingletonProject() {
return getWorkspace().getActiveProject();
}
@Property
public String getCreateTime() {
return CBModelConstants.ISO_DATE_FORMAT.format(Instant.ofEpochMilli(createTime));
}
@Property
public synchronized String getLastAccessTime() {
return CBModelConstants.ISO_DATE_FORMAT.format(Instant.ofEpochMilli(lastAccessTime));
}
public String getLastRemoteAddr() {
return lastRemoteAddr;
}
public String getLastRemoteUserAgent() {
return lastRemoteUserAgent;
}
// Clear cache when
@Property
public boolean isCacheExpired() {
return cacheExpired;
}
public void setCacheExpired(boolean cacheExpired) {
this.cacheExpired = cacheExpired;
}
public WebUser getUser() {
return this.userContext.getUser();
}
@NotNull
public Map<String, String> getUserMetaParameters() {
var user = getUser();
if (user == null) {
return Map.of();
}
var allMetaParams = new HashMap<>(user.getMetaParameters());
getAllAuthInfo().forEach(authInfo -> allMetaParams.putAll(authInfo.getUserIdentity().getMetaParameters()));
return allMetaParams;
}
public String getUserId() {
return userContext.getUserId();
}
public synchronized boolean hasPermission(String perm) {
Set<String> sessionPermissions = getSessionPermissions();
return sessionPermissions.contains(DBWConstants.PERMISSION_ADMIN) || sessionPermissions.contains(perm);
}
public boolean isAuthorizedInSecurityManager() {
return userContext.isAuthorizedInSecurityManager();
}
public Set<String> getSessionPermissions() {
if (userContext.getUserPermissions() == null) {
refreshSessionAuth();
}
return userContext.getUserPermissions();
}
@NotNull
public SMController getSecurityController() {
return userContext.getSecurityController();
}
@NotNull
public SMAdminController getAdminSecurityController() throws DBException {
if (!hasPermission(DBWConstants.PERMISSION_ADMIN)) {
throw new DBException("Admin permissions required");
}
return userContext.getAdminSecurityController();
}
@NotNull
public RMController getRmController() {
return userContext.getRmController();
}
@NotNull
public DBFileController getFileController() {
return userContext.getFileController();
}
@Override
public void refreshUserData() {
super.refreshUserData();
refreshSessionAuth();
initNavigatorModel();
}
// Note: for admin use only
public void resetUserState(boolean needResetUserCache) throws DBException {
clearAuthTokens();
if (needResetUserCache) {
try {
resetSessionCache();
} catch (DBCException e) {
addSessionError(e);
log.error(e);
}
}
refreshUserData();
clearSessionContext();
}
public void resetUserState() throws DBException {
resetUserState(true);
}
@NotNull
public DBPEventListener getDataSourceConnectListener() {
return connectListener;
}
@NotNull
public String getClientOrigin() {
return clientOrigin;
}
public void updateClientOrigin(@NotNull String originFromRequest) {
this.clientOrigin = originFromRequest;
}
private void initNavigatorModel() {
navigatorModelLock.writeLock().lock();
try {
// Cleanup current data
if (this.navigatorModel != null) {
this.navigatorModel.dispose();
this.navigatorModel = null;
}
this.globalProject = null;
loadProjects();
this.navigatorModel = new DBNModel(DBWorkbench.getPlatform(), getWorkspace().getProjects());
this.navigatorModel.setModelAuthContext(getWorkspace().getAuthContext());
this.navigatorModel.initialize();
this.locale = Locale.getDefault().getLanguage();
} finally {
navigatorModelLock.writeLock().unlock();
}
}
private void loadProjects() {
WebSessionWorkspace workspace = getWorkspace();
workspace.clearProjects();
WebUser user = userContext.getUser();
if (user == null && DBWorkbench.isDistributed()) {
// No anonymous mode in distributed apps
return;
}
try {
RMController controller = getRmController();
RMProject[] rmProjects = controller.listAccessibleProjects();
for (RMProject project : rmProjects) {
createWebProject(project);
}
if (user == null && application.isAnonymousAccessEnabled()) {
WebProjectImpl anonymousProject = createWebProject(RMUtils.createAnonymousProject());
anonymousProject.setInMemory(true);
}
if (workspace.getActiveProject() == null && !workspace.getProjects().isEmpty()) {
workspace.setActiveProject(workspace.getProjects().getFirst());
}
} catch (DBException e) {
addSessionError(e);
log.error("Error getting accessible projects list", e);
}
}
@NotNull
private WebSessionProjectImpl createWebProject(@NotNull RMProject project) throws DBException {
WebSessionProjectImpl sessionProject;
if (project.isGlobal()) {
sessionProject = createGlobalProject(project);
} else {
sessionProject = createSessionProject(project);
}
// do not load data sources for anonymous project
if (project.getType() == RMProjectType.USER && userContext.getUser() == null) {
sessionProject.setInMemory(true);
}
addSessionProject(sessionProject);
if (!project.isShared() || application.isConfigurationMode()) {
getWorkspace().setActiveProject(sessionProject);
}
return sessionProject;
}
@NotNull
protected WebSessionProjectImpl createSessionProject(@NotNull RMProject project) throws DBException {
return new WebSessionProjectImpl(this, project, getProjectPath(project));
}
@NotNull
protected Path getProjectPath(@NotNull RMProject project) throws DBException {
return RMUtils.getProjectPath(project);
}
@NotNull
protected WebSessionProjectImpl createGlobalProject(RMProject project) {
globalProject = new WebSessionGlobalProjectImpl(this, project);
globalProject.refreshAccessibleConnectionIds();
return globalProject;
}
private void resetNavigationModel() {
navigatorModelLock.writeLock().lock();
try {
getWorkspace().getProjects().forEach(WebSessionProjectImpl::dispose);
if (this.navigatorModel != null) {
this.navigatorModel.dispose();
this.navigatorModel = null;
}
} finally {
navigatorModelLock.writeLock().unlock();
}
}
private synchronized void refreshSessionAuth() {
try {
if (!isAuthorizedInSecurityManager()) {
authAsAnonymousUser();
} else if (getUserId() != null) {
userContext.refreshPermissions();
if (globalProject != null) {
globalProject.refreshAccessibleConnectionIds();
}
}
} catch (Exception e) {
addSessionError(e);
log.error("Error reading session permissions", e);
}
}
private synchronized void authAsAnonymousUser() throws DBException {
if (!application.isAnonymousAccessEnabled()) {
return;
}
SMAuthInfo authInfo = getSecurityController().authenticateAnonymousUser(this.id, getSessionParameters(), CB_SESSION_TYPE);
updateSMSession(authInfo);
notifySessionAuthChange();
}
@NotNull
public String getLocale() {
return locale;
}
public void setLocale(@Nullable String locale) {
this.locale = locale != null ? locale : Locale.getDefault().getLanguage();
}
@Nullable
public DBNModel getNavigatorModel() {
navigatorModelLock.readLock().lock();
try {
return navigatorModel;
} finally {
navigatorModelLock.readLock().unlock();
}
}
@NotNull
public DBNModel getNavigatorModelOrThrow() throws DBWebException {
navigatorModelLock.readLock().lock();
try {
if (navigatorModel != null) {
return navigatorModel;
}
throw new DBWebException("Navigator model is not found in session");
} finally {
navigatorModelLock.readLock().unlock();
}
}
/**
* Returns and clears progress messages
*/
@Association
public List<WebServerMessage> getSessionMessages() {
synchronized (sessionMessages) {
List<WebServerMessage> copy = new ArrayList<>(sessionMessages);
sessionMessages.clear();
return copy;
}
}
public void updateInfo(boolean isOldHttpSessionUsed) {
log.trace("Update session lifetime " + getSessionId() + " for user " + getUserId());
touchSession();
if (isOldHttpSessionUsed) {
try {
// Persist session
if (!isAuthorizedInSecurityManager()) {
// Create new record
authAsAnonymousUser();
} else {
if (!application.isConfigurationMode()) {
// Update record
//TODO use generate id from SMController
getSecurityController().updateSession(this.userContext.getSmSessionId(), getSessionParameters());
}
}
} catch (Exception e) {
addSessionError(e);
log.error("Error persisting web session", e);
}
}
}
public synchronized void updateSessionParameters(WebHttpRequestInfo requestInfo) {
this.lastRemoteUserAgent = requestInfo.getLastRemoteUserAgent();
this.cacheExpired = false;
}
@Override
public void close() {
try {
resetNavigationModel();
} catch (Throwable e) {
log.error(e);
}
try {
clearAuthTokens();
} catch (Exception e) {
log.error("Error closing web session tokens");
}
this.userContext.setUser(null);
super.close();
}
@Override
public void close(boolean clearTokens, boolean sendSessionExpiredEvent) {
try {
resetNavigationModel();
} catch (Throwable e) {
log.error(e);
}
if (clearTokens) {
try {
clearAuthTokens();
} catch (Exception e) {
log.error("Error closing web session tokens");
}
}
this.userContext.setUser(null);
super.close(clearTokens, sendSessionExpiredEvent);
}
@NotNull
private List<WebAuthInfo> clearAuthTokens() throws DBException {
ArrayList<WebAuthInfo> tokensCopy;
synchronized (authTokens) {
tokensCopy = new ArrayList<>(this.authTokens);
}
for (WebAuthInfo ai : tokensCopy) {
removeAuthInfo(ai);
}
resetAuthToken();
return tokensCopy;
}
public DBRProgressMonitor getProgressMonitor() {
return progressMonitor;
}
///////////////////////////////////////////////////////
// Async model
public WebAsyncTaskInfo getAsyncTask(@NotNull String taskId, @NotNull String taskName, boolean create) {
synchronized (asyncTasks) {
WebAsyncTaskInfo taskInfo = asyncTasks.get(taskId);
if (taskInfo == null && create) {
taskInfo = new WebAsyncTaskInfo(taskId, taskName);
asyncTasks.put(taskId, taskInfo);
}
return taskInfo;
}
}
@NotNull
public WebAsyncTaskInfo asyncTaskStatus(String taskId, boolean removeOnFinish) throws DBWebException {
synchronized (asyncTasks) {
WebAsyncTaskInfo taskInfo = asyncTasks.get(taskId);
if (taskInfo == null) {
throw new DBWebException("Task '" + taskId + "' not found");
}
if (removeOnFinish && !taskInfo.isRunning()) {
asyncTasks.remove(taskId);
}
return taskInfo;
}
}
public boolean asyncTaskCancel(String taskId) throws DBWebException {
WebAsyncTaskInfo taskInfo;
synchronized (asyncTasks) {
taskInfo = asyncTasks.get(taskId);
if (taskInfo == null) {
throw new DBWebException("Task '" + taskId + "' not found");
}
}
AbstractJob job = taskInfo.getJob();
if (job instanceof CustomCancelableJob cancelableJob) {
cancelableJob.cancelJob(this, taskInfo);
}
CompletableFuture<?> future = getAttribute(getTaskConfirmationAttributeName(taskId));
if (future != null) {
future.cancel(false);
}
if (job != null) {
job.cancel();
}
return true;
}
public WebAsyncTaskInfo createAsyncTask(@NotNull String taskName) {
int taskId = TASK_ID.incrementAndGet();
return getAsyncTask(String.valueOf(taskId), taskName, true);
}
public List<WebAsyncTaskInfo> findTasksByJob(@NotNull Class<? extends AbstractJob> jobClass) {
synchronized (asyncTasks) {
List<WebAsyncTaskInfo> result = new ArrayList<>();
for (WebAsyncTaskInfo task : asyncTasks.values()) {
if (task.getJob() != null && jobClass.isAssignableFrom(task.getJob().getClass())) {
result.add(task);
}
}
return result;
}
}
@NotNull
public WebAsyncTaskInfo createAndRunAsyncTask(@NotNull String taskName, @NotNull WebAsyncTaskProcessor<?> runnable) {
WebAsyncTaskInfo asyncTask = createAsyncTask(taskName);
return runAsyncTask(asyncTask, runnable);
}
@NotNull
public WebAsyncTaskInfo runAsyncTask(@NotNull WebAsyncTaskInfo asyncTask, @NotNull WebAsyncTaskProcessor<?> runnable) {
AbstractJob job = new AbstractCancelableJob(asyncTask.getName()) {
@NotNull
@Override
protected IStatus run(@NotNull DBRProgressMonitor monitor) {
int curTaskCount = taskCount.incrementAndGet();
DBRProgressMonitor taskMonitor = new TaskProgressMonitor(monitor, WebSession.this, asyncTask);
try {
Number queryLimit = application.getAppConfiguration().getResourceQuota(WebSQLConstants.QUOTA_PROP_QUERY_LIMIT);
if (queryLimit != null && curTaskCount > queryLimit.intValue()) {
throw new DBQuotaException(
"Maximum simultaneous queries quota exceeded", WebSQLConstants.QUOTA_PROP_QUERY_LIMIT, queryLimit.intValue(), curTaskCount);
}
runnable.run(taskMonitor);
asyncTask.setResult(runnable.getResult());
asyncTask.setExtendedResult(runnable.getExtendedResults());
asyncTask.setStatus(DBWConstants.TASK_STATUS_FINISHED);
} catch (InvocationTargetException e) {
addSessionError(e.getTargetException());
asyncTask.setJobError(e.getTargetException());
} catch (Exception e) {
asyncTask.setJobError(e);
} finally {
taskCount.decrementAndGet();
asyncTask.setRunning(false);
WebEventUtils.sendAsyncTaskEvent(WebSession.this, asyncTask);
}
return Status.OK_STATUS;
}
};
asyncTask.setJob(job);
asyncTask.setRunning(true);
job.schedule();
return asyncTask;
}
public void addSessionError(@NotNull Throwable exception) {
addSessionMessage(new WebServerMessage(exception));
}
public void addSessionMessage(@NotNull WebServerMessage message) {
synchronized (sessionMessages) {
sessionMessages.add(message);
}
addSessionEvent(new WSSessionLogUpdatedEvent(
this.userContext.getSmSessionId(),
this.userContext.getUserId(),
message.getType(),
message.getMessage()));
}
public void addInfoMessage(@NotNull String message) {
addSessionMessage(new WebServerMessage(MessageType.INFO, message));
}
public void addWarningMessage(@NotNull String message) {
addSessionMessage(new WebServerMessage(MessageType.WARNING, message));
}
@NotNull
public List<WebServerMessage> readLog(Integer maxEntries, Boolean clearLog) {
synchronized (sessionMessages) {
List<WebServerMessage> messages = new ArrayList<>();
int entryCount = CommonUtils.toInt(maxEntries);
if (entryCount == 0 || entryCount >= sessionMessages.size()) {
messages.addAll(sessionMessages);
if (CommonUtils.toBoolean(clearLog)) {
sessionMessages.clear();
}
} else {
messages.addAll(sessionMessages.subList(0, maxEntries));
if (CommonUtils.toBoolean(clearLog)) {
sessionMessages.removeAll(messages);
}
}
return messages;
}
}
@Property
public Map<String, Object> getActionParameters() {
WebActionParameters action = WebActionParameters.fromSession(this, true);
return action == null ? null : action.getParameters();
}
public WebAuthInfo getAuthInfo(@Nullable String providerID) {
synchronized (authTokens) {
if (providerID != null) {
for (WebAuthInfo ai : authTokens) {
if (ai.getAuthProvider().equals(providerID)) {
return ai;
}
}
return null;
}
return authTokens.isEmpty() ? null : authTokens.getFirst();
}
}
@Override
public List<SMAuthInfo> getAuthInfos() {
synchronized (authTokens) {
return authTokens.stream().map(WebAuthInfo::getAuthInfo).toList();
}
}
@NotNull
public List<WebAuthInfo> getAllAuthInfo() {
synchronized (authTokens) {
return new ArrayList<>(authTokens);
}
}
public void addAuthInfo(@NotNull WebAuthInfo authInfo) throws DBException {
addAuthTokens(authInfo);
}
public void addAuthTokens(@NotNull WebAuthInfo... tokens) throws DBException {
WebUser newUser = null;
for (WebAuthInfo authInfo : tokens) {
if (newUser != null && newUser != authInfo.getUser()) {
throw new DBException("Different users specified in auth tokens: " + Arrays.toString(tokens));
}
newUser = authInfo.getUser();
}
if (application.isConfigurationMode() && this.userContext.getUser() == null && newUser != null) {
//FIXME hotfix to avoid exception after external auth provider login in easy config
userContext.setUser(newUser);
refreshUserData();
} else if (!CommonUtils.equalObjects(this.userContext.getUser(), newUser)) {
throw new DBException("Can't authorize different users in the single session");
}
for (WebAuthInfo authInfo : tokens) {
WebAuthInfo oldAuthInfo = getAuthInfo(authInfo.getAuthProviderDescriptor().getId());
if (oldAuthInfo != null) {
removeAuthInfo(oldAuthInfo);
}
getSessionContext().addSession(authInfo.getAuthSession());
}
synchronized (authTokens) {
Collections.addAll(authTokens, tokens);
}
notifySessionAuthChange();
}
public void notifySessionAuthChange() {
// Notify handlers about auth change
sessionHandlers.forEach((id, handler) -> {
try {
handler.handleSessionAuth(this);
} catch (Exception e) {
log.error("Error calling session handler '" + id + "'", e);
}
});
}
private void removeAuthInfo(@NotNull WebAuthInfo oldAuthInfo) {
oldAuthInfo.closeAuth();
synchronized (authTokens) {
authTokens.remove(oldAuthInfo);
}
}
public List<WebAuthInfo> removeAuthInfo(String providerId) throws DBException {
List<WebAuthInfo> oldInfo;
if (providerId == null) {
oldInfo = clearAuthTokens();
} else {
WebAuthInfo authInfo = getAuthInfo(providerId);
if (authInfo != null) {
removeAuthInfo(authInfo);
oldInfo = List.of(authInfo);
} else {
oldInfo = List.of();
}
}
if (authTokens.isEmpty()) {
resetUserState();
}
return oldInfo;
}
@Nullable
public List<DBACredentialsProvider> getContextCredentialsProviders() {
return getAdapters(DBACredentialsProvider.class);
}
// Auth credentials provider
// Adds auth properties passed from web (by user)
@Override
public boolean provideAuthParameters(
@NotNull DBRProgressMonitor monitor,
@NotNull DBPDataSourceContainer dataSourceContainer,
@NotNull DBPConnectionConfiguration configuration
) {
try {
// Properties from nested auth sessions
for (DBACredentialsProvider contextCredentialsProvider : getContextCredentialsProviders()) {
contextCredentialsProvider.provideAuthParameters(monitor, dataSourceContainer, configuration);
}
configuration.setRuntimeAttribute(RUNTIME_PARAM_AUTH_INFOS, getAllAuthInfo());
configuration.setRuntimeAttribute(RUNTIME_PARAM_CLIENT_ORIGIN, this.clientOrigin);
WebSessionProjectImpl project = getProjectById(dataSourceContainer.getProject().getId());
if (project != null) {
WebConnectionInfo webConnectionInfo = project.findWebConnectionInfo(dataSourceContainer.getId());
if (webConnectionInfo != null) {
WebDataSourceUtils.saveCredentialsInDataSource(webConnectionInfo, dataSourceContainer, configuration);
}
}
// uncommented because we had the problem with non-native auth models
// (for example, can't connect to DynamoDB if credentials are not saved)
DBAAuthCredentials credentials = configuration.getAuthModel().loadCredentials(dataSourceContainer, configuration);
WebDataSourceUtils.updateCredentialsFromProperties(this.progressMonitor, credentials, configuration.getAuthProperties());
configuration.getAuthModel().provideCredentials(dataSourceContainer, configuration, credentials);
} catch (DBException e) {
addSessionError(e);
log.error(e);
}
return true;
}
@NotNull
@Override
public String getAuthContextType() {
return WEB_SESSION_AUTH_CONTEXT_TYPE;
}
// May be called to extract auth information from session
@Override
public <T> T getAdapter(@NotNull Class<T> adapter) {
synchronized (authTokens) {
for (WebAuthInfo authInfo : authTokens) {
if (isAuthInfoInstanceOf(authInfo, adapter)) {
return adapter.cast(authInfo.getAuthSession());
}
}
}
return null;
}
@NotNull
public <T> List<T> getAdapters(Class<T> adapter) {
synchronized (authTokens) {
return authTokens.stream()
.filter(token -> isAuthInfoInstanceOf(token, adapter))
.map(token -> adapter.cast(token.getAuthSession()))
.collect(Collectors.toList());
}
}
private <T> boolean isAuthInfoInstanceOf(WebAuthInfo authInfo, Class<T> adapter) {
if (authInfo != null) {
return adapter.isInstance(authInfo.getAuthSession());
}
return false;
}
///////////////////////////////////////////////////////
// Utils
public Map<String, Object> getSessionParameters() {
var parameters = new HashMap<String, Object>();
parameters.put(SMConstants.SESSION_PARAM_LAST_REMOTE_ADDRESS, getLastRemoteAddr());
parameters.put(SMConstants.SESSION_PARAM_LAST_REMOTE_USER_AGENT, getLastRemoteUserAgent());
return parameters;
}
public void resetAuthToken() throws DBException {
this.userContext.reset();
}
public boolean updateSMSession(SMAuthInfo smAuthInfo) throws DBException {
boolean contextChanged = super.updateSMSession(smAuthInfo);
if (contextChanged) {
refreshUserData();
}
return contextChanged;
}
@Override
public SMCredentials getActiveUserCredentials() {
return userContext.getActiveUserCredentials();
}
@Override
public void refreshSMSession() throws DBException {
userContext.refreshSMSession();
}
@Nullable
public WebSessionProjectImpl getProjectById(@NotNull String projectId) {
return getWorkspace().getProjectById(projectId);
}
/**
* Returns project info from session cache.
*
* @throws DBWebException if project with provided id is not found.
*/
@NotNull
public WebSessionProjectImpl getAccessibleProjectById(@Nullable String projectId) throws DBWebException {
WebSessionProjectImpl project = null;
if (projectId != null) {
project = getWorkspace().getProjectById(projectId);
}
if (project == null) {
throw new DBWebException("Project not found: " + projectId);
}
return project;
}
@NotNull
public List<WebSessionProjectImpl> getAccessibleProjects() {
return getWorkspace().getProjects();
}
/**
* Adds project to session cache and navigator tree.
*/
public void addSessionProject(@NotNull WebSessionProjectImpl project) {
getWorkspace().addProject(project);
navigatorModelLock.readLock().lock();
try {
if (navigatorModel != null) {
navigatorModel.getRoot().addProject(project, false);
}
} finally {
navigatorModelLock.readLock().unlock();
}
}
/**
* Removes project from session cache and navigator tree.
*/
public void deleteSessionProject(@NotNull WebSessionProjectImpl project) {
RMProject rmProject = project.getRMProject();
log.info(String.format(
"Project deleted: [ID=%s, Name=%s, Type=%s, Creator=%s]",
rmProject.getId(), rmProject.getName(), rmProject.getType(), rmProject.getCreator()
));
project.dispose();
getWorkspace().removeProject(project);
navigatorModelLock.readLock().lock();
try {
if (navigatorModel != null) {
navigatorModel.getRoot().removeProject(project);
}
} finally {
navigatorModelLock.readLock().unlock();
}
}
@Override
public void addSessionProject(@NotNull String projectId) throws DBException {
super.addSessionProject(projectId);
var rmProject = getRmController().getProject(projectId, false, false);
if (rmProject == null) {
log.error("RM project '" + projectId + "' not found");
return;
}
createWebProject(rmProject);
}
@Override
public void updateSessionProject(@NotNull String projectId, @NotNull RMProjectInfo rmProjectInfo) throws DBException {
super.updateSessionProject(projectId, rmProjectInfo);
var project = getProjectById(projectId);
if (project == null) {
return;
}
project.updateProjectInfo(rmProjectInfo.getName(), rmProjectInfo.getDescription());
}