-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathUserResource.java
More file actions
2033 lines (1834 loc) · 76.1 KB
/
Copy pathUserResource.java
File metadata and controls
2033 lines (1834 loc) · 76.1 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
/*******************************************************************************
* Copyright 2015 Defense Health Agency (DHA)
*
* If your use of this software does not include any GPLv2 components:
* 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.
* ----------------------------------------------------------------------------
* If your use of this software includes any GPLv2 components:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* 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.
*******************************************************************************/
package prerna.semoss.web.services.local;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import org.apache.http.client.ClientProtocolException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.javatuples.Pair;
import org.json.JSONArray;
import org.owasp.encoder.Encode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.NewCookie;
import jakarta.ws.rs.core.Response;
import prerna.auth.AccessToken;
import prerna.auth.AuthProvider;
import prerna.auth.SyncUserAssetsThread;
import prerna.auth.User;
import prerna.auth.external.ExternalAuthorizationHelper;
import prerna.auth.utils.AbstractSecurityUtils;
import prerna.auth.utils.SecurityAPIUserUtils;
import prerna.auth.utils.SecurityAdminUtils;
import prerna.auth.utils.SecurityExternalConnectorsUtils;
import prerna.auth.utils.SecurityNativeUserUtils;
import prerna.auth.utils.SecurityUpdateUtils;
import prerna.auth.utils.SecurityUserUtils;
import prerna.cluster.util.ClusterUtil;
import prerna.io.connector.IAccessTokenFiller;
import prerna.io.connector.jira.JiraTokenFiller;
import prerna.io.connector.salesforce.SalesforceTokenFiller;
import prerna.io.connector.servicenow.ServiceNowTokenFiller;
import prerna.security.HttpHelperUtility;
import prerna.security.PKCEUtil;
import prerna.usertracking.UserTrackingUtils;
import prerna.util.Constants;
import prerna.util.SocialPropertiesUtil;
import prerna.util.Utility;
import prerna.util.ldap.ILdapAuthenticator;
import prerna.util.ldap.LDAPPasswordChangeRequiredException;
import prerna.util.linotp.LinOTPResponse;
import prerna.util.linotp.LinOTPUtil;
import prerna.web.conf.DBLoader;
import prerna.web.conf.UserSessionLoader;
import prerna.web.services.util.WebUtility;
import waffle.servlet.WindowsPrincipal;
@Path("/auth")
@PermitAll
public class UserResource {
private static final Logger classLogger = LogManager.getLogger(UserResource.class);
private static final String CUSTOM_REDIRECT_SESSION_KEY = "custom_redirect";
private static final String OAUTH_DISABLE_REDIRECT_SESSION_KEY = "oauth_disable_redirect";
private static final SecureRandom NONCE_RANDOM = new SecureRandom();
/**
* What a login started with {@code disableRedirect=true} ends on instead of a
* redirect: the window the sign in ran in closes itself. The FE that opened it
* also closes it once it sees the login, so the page works without its script.
*/
private static final String LOGIN_COMPLETE_PAGE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Signed in</title>
</head>
<body>
<p>You are signed in. You can close this window.</p>
<script nonce="%s">window.close();</script>
</body>
</html>
""";
private static SocialPropertiesUtil socialData = null;
static {
socialData = SocialPropertiesUtil.getInstance();
}
/**
* Session attribute holding the PKCE code verifier between authorize and
* callback.
*/
private static final String PKCE_VERIFIER_ATTR = "pkce_code_verifier";
/**
* Returns the active login providers for the current session user.
*
* @param request inbound HTTP request
* @return provider-name map response
*/
@GET
@Path("/logins")
public Response getAllLogins(@Context HttpServletRequest request) {
List<NewCookie> newCookies = new ArrayList<>();
HttpSession session = request.getSession(false);
User semossUser = null;
if (session != null) {
semossUser = (User) session.getAttribute(Constants.SESSION_USER);
}
if (semossUser == null) {
// not authenticated
// remove any cookies we shouldn't have
WebUtility.expireSessionCookies(request, newCookies);
if (session != null && (session.isNew() || request.isRequestedSessionIdValid())) {
session.invalidate();
}
}
Map<String, String> retMap = User.getLoginNames(semossUser);
return WebUtility.getResponse(retMap, 200, newCookies.toArray(new NewCookie[] {}));
}
/**
* Logs a user out of one provider or all providers in the current session.
*
* @param provider provider name or {@code ALL}
* @param disableRedirect when true, do not send a redirect response
* @param request inbound HTTP request
* @param response outbound HTTP response
* @return logout result payload
* @throws IOException when redirect writing fails
*/
@GET
@Produces("application/json")
@Path("/logout/{provider}")
public Response logout(@PathParam("provider") String provider,
@QueryParam("disableRedirect") boolean disableRedirect, @Context HttpServletRequest request,
@Context HttpServletResponse response) throws IOException {
boolean noUser = false;
boolean removed = false;
provider = WebUtility.inputSanitizer(provider);
HttpSession session = request.getSession();
User thisUser = (User) session.getAttribute(Constants.SESSION_USER);
if (thisUser == null) {
Map<String, Object> ret = new HashMap<>();
ret.put("success", false);
ret.put(Constants.ERROR_MESSAGE, "No user is currently logged in the session");
return WebUtility.getResponse(ret, 400);
}
// log the user logout
classLogger.info("User is logging out of provider {}", provider);
provider = WebUtility.inputSanitizer(provider);
if (provider.equalsIgnoreCase("ALL")) {
removed = true;
noUser = true;
} else {
AuthProvider token = AuthProvider.valueOf(provider.toUpperCase());
String assetEngineId = null;
// TODO: what does this part do?
// TODO: feel like when logout need to adjust the asset id
if (thisUser.getLogins().size() == 1) {
thisUser.getAssetProjectId(token);
}
removed = thisUser.dropAccessToken(token);
if (thisUser.getLogins().isEmpty()) {
noUser = true;
} else {
request.getSession().setAttribute(Constants.SESSION_USER, thisUser);
Thread.ofVirtual().start(new SyncUserAssetsThread(assetEngineId));
// put the new map for the user space
session.setAttribute(Constants.USER_ASSET_IDS, thisUser.getAssetEngineMap());
}
}
List<NewCookie> nullCookies = null;
if (noUser) {
// when we call session.invalidate() the UserSessionLoader will properly log is
// user logout or tomcat ending
session.setAttribute(UserSessionLoader.IS_USER_LOGOUT, true);
classLogger.info("User has logged out from all providers in the session");
// well, you have logged out and we always require a login
// so i will redirect you by default unless you specifically say not to
if (!disableRedirect) {
response.setStatus(302);
String customUrl = DBLoader.getCustomLogoutUrl();
if (customUrl != null && !customUrl.isEmpty()) {
response.setHeader("redirect", customUrl);
response.sendError(302, "Need to redirect to " + customUrl);
} else {
String redirectUrl = WebUtility.inputSanitizer(request.getHeader("referer"));
if (DBLoader.useLogoutPage()) {
String scheme = WebUtility.inputSanitizer(request.getScheme());
if (!scheme.trim().equalsIgnoreCase("https") && !scheme.trim().equalsIgnoreCase("http")) {
throw new IllegalArgumentException("scheme is invalid, please input proper scheme");
}
String serverName = WebUtility.inputSanitizer(request.getServerName()); // hostname.com
int serverPort = request.getServerPort(); // 8080
String contextPath = WebUtility.inputSanitizer(request.getContextPath()); // /Monolith
redirectUrl = "";
redirectUrl += scheme + "://" + serverName;
if (serverPort != 80 && serverPort != 443) {
redirectUrl += ":" + serverPort;
}
redirectUrl += contextPath + "/logout/";
response.setHeader("redirect", redirectUrl);
response.sendError(302, "Need to redirect to " + redirectUrl);
} else {
redirectUrl = redirectUrl + WebUtility.determineLoginExtension(request);
String encodedRedirectUrl = Encode.forHtml(redirectUrl);
response.setHeader("redirect", encodedRedirectUrl);
response.sendError(302, "Need to redirect to " + encodedRedirectUrl);
}
}
}
// remove the cookie from the browser
// for the session id
classLogger.info("Removing session token");
nullCookies = new ArrayList<>();
WebUtility.expireSessionCookies(request, nullCookies);
// invalidate the session
session.invalidate();
}
Map<String, Boolean> ret = new HashMap<>();
ret.put("success", removed);
if (nullCookies == null) {
return WebUtility.getResponse(ret, 200);
}
return WebUtility.getResponseNoCache(ret, 200, nullCookies.toArray(new NewCookie[] {}));
}
/**
* Adds or updates an authenticated access token in the current user session.
*
* @param token normalized access token
* @param request inbound HTTP request
* @param autoAdd when true, create/update the user record automatically
*/
public static void addAccessToken(AccessToken token, HttpServletRequest request, boolean autoAdd) {
HttpSession session = request.getSession(true);
User semossUser = (User) session.getAttribute(Constants.SESSION_USER);
// all of this is now in the user
boolean firstLogin = semossUser == null;
if (firstLogin) {
semossUser = new User();
session.setAttribute(Constants.SESSION_USER_ID_LOG, token.getId());
// to prevent session fixation attacks
if (!session.isNew()) {
request.changeSessionId();
}
}
// add new users into the database
if (autoAdd) {
SecurityUpdateUtils.addOAuthUser(token);
}
// validate the user's login
// that they are not locked
// and to update the last login date
try {
SecurityUpdateUtils.validateUserLogin(token);
} catch (Exception e) {
classLogger.error("Unexpected error in addAccessToken", e);
}
// also set the user metadata
SecurityUserUtils.loadUserMetadata(token);
semossUser.setAccessToken(token);
semossUser.setAnonymous(false);
session.setAttribute(Constants.SESSION_USER, semossUser);
WebUtility.loggingContextLoginEvent(session);
UserResource.userTrackingLogin(request, semossUser, token.getProvider());
// log the user login
classLogger.info("User is logging in with provider {}", token.getProvider());
// only for first login
// lets see if there is an external auth
// that we should be loading
if (firstLogin && Boolean
.parseBoolean(Utility.getDIHelperProperty(Constants.EXTERNAL_PERMISSION_MANAGEMENT_ENABLED) + "")) {
try {
ExternalAuthorizationHelper.updateEnginePermissionsBasedOnApiCall(semossUser);
} catch (Exception e) {
classLogger.error("Unexpected error in addAccessToken", e);
}
}
}
/**
* Records a user login event in the tracking system.
*
* @param request inbound HTTP request
* @param semossUser authenticated user
* @param ap authentication provider used for login
*/
public static void userTrackingLogin(HttpServletRequest request, User semossUser, AuthProvider ap) {
String ip = WebUtility.getClientIp(request);
if (request.getSession() != null && request.getSession().getId() != null) {
UserTrackingUtils.registerLogin(request.getSession().getId(), ip, semossUser, ap);
} else {
UserTrackingUtils.registerLogin("NO_SESSION_ID", ip, semossUser, ap);
}
}
/**
* User info method calls
*/
/**
* Gets user profile information for any OAuth provider.
* <p>
* Resolves the provider (handling aliases such as
* {@code microsoft}/{@code ms}), then refreshes the logged-in user's profile
* from that provider using its {@link IAccessTokenFiller} strategy - the same
* fetch/parse logic used at login, so no per-provider code is duplicated here.
*
* @param provider the provider path segment
* @param request inbound HTTP request
* @return the user's display name, or a prompt to log in
*/
@GET
@Produces("application/json")
@Path("/userinfo/{provider}")
public Response userinfoGeneric(@PathParam("provider") String provider, @Context HttpServletRequest request) {
provider = WebUtility.inputSanitizer(provider);
AuthProvider providerEnum = AuthProvider.getSocialPropKeysToEnum().getOrDefault(provider.toLowerCase(),
AuthProvider.GENERIC);
String prefix = AuthProvider.getSocialPrefixForPath(provider) + "_";
Map<String, Object> ret = new HashMap<>();
HttpSession session = request.getSession(false);
User semossUser = (session != null) ? (User) session.getAttribute(Constants.SESSION_USER) : null;
if (semossUser == null) {
List<NewCookie> newCookies = new ArrayList<>();
// not authenticated - remove any cookies we shouldn't have
WebUtility.expireSessionCookies(request, newCookies);
if (session != null && (session.isNew() || request.isRequestedSessionIdValid())) {
session.invalidate();
}
ret.put(Constants.ERROR_MESSAGE, "Log into your " + providerEnum.getDisplayName() + " account");
return WebUtility.getResponseNoCache(ret, 200, newCookies.toArray(new NewCookie[] {}));
}
try {
AccessToken loggedInToken = semossUser.getAccessToken(providerEnum);
if (loggedInToken == null) {
throw new IllegalStateException(
"No access token for provider " + providerEnum.name() + " - user needs to login");
}
// refresh the profile from the provider using its filler strategy (userinfo
// GET/POST, id_token decode, etc. are all encapsulated in the filler)
AccessToken newToken = new AccessToken();
newToken.setAccess_token(loggedInToken.getAccess_token());
providerEnum.newTokenFiller().fillAccessToken(newToken, prefix);
ret.putAll(newToken.toProviderMap(false, null, false));
return WebUtility.getResponse(ret, 200);
} catch (Exception e) {
classLogger.error("Failed to fetch user info for provider " + providerEnum.name(), e);
ret.put(Constants.ERROR_MESSAGE, "Log into your " + providerEnum.getDisplayName() + " account");
return WebUtility.getResponse(ret, 200);
}
}
/**
* Initializes an OAuth login flow session and stores a custom redirect value
* when present, and whether the login should end without a redirect
* ({@code disableRedirect=true}).
*
* @param request inbound HTTP request
* @return existing or newly-created session
*/
private HttpSession initializeOAuthLoginSession(HttpServletRequest request) {
HttpSession session = request.getSession(false);
String customRedirect = WebUtility.cleanHttpResponse(request.getParameter("redirect"));
if (customRedirect != null && !customRedirect.isEmpty()) {
if (session == null) {
session = request.getSession();
}
session.setAttribute(CUSTOM_REDIRECT_SESSION_KEY, customRedirect);
}
// the provider's callback does not carry the parameters the login started
// with, so disableRedirect is kept in the session until the login ends. A
// login that starts without it drops one an abandoned login left behind.
if (!isOAuthCallback(request)) {
if (Boolean.parseBoolean(request.getParameter("disableRedirect"))) {
if (session == null) {
session = request.getSession();
}
session.setAttribute(OAUTH_DISABLE_REDIRECT_SESSION_KEY, Boolean.TRUE);
} else if (session != null) {
session.removeAttribute(OAUTH_DISABLE_REDIRECT_SESSION_KEY);
}
}
return session;
}
/**
* Whether a request to an OAuth login endpoint is the provider sending the user
* back, rather than the FE starting a login.
*
* @param request inbound HTTP request
* @return true for a provider callback
*/
private boolean isOAuthCallback(HttpServletRequest request) {
return request.getParameter("code") != null || request.getParameter("state") != null
|| request.getParameter("error") != null;
}
/**
* Ends a successful OAuth login. A login started with
* {@code disableRedirect=true}, such as one the FE opened in a popup, ends on a
* page that closes its window; every other login is redirected to the main page
* or its custom redirect.
*
* @param request inbound HTTP request
* @param response outbound HTTP response
* @throws IOException when the response cannot be written
*/
private void finishOAuthLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession();
if (!Boolean.TRUE.equals(session.getAttribute(OAUTH_DISABLE_REDIRECT_SESSION_KEY))) {
setMainPageRedirect(request, response);
return;
}
session.removeAttribute(OAUTH_DISABLE_REDIRECT_SESSION_KEY);
session.removeAttribute(CUSTOM_REDIRECT_SESSION_KEY);
addSessionCookieHeader(request, response, session);
byte[] nonceBytes = new byte[16];
NONCE_RANDOM.nextBytes(nonceBytes);
String nonce = Base64.getEncoder().encodeToString(nonceBytes);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache-Control", "no-store");
// its own policy: only this page's one script may run
response.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'nonce-" + nonce
+ "'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'");
response.getWriter().write(LOGIN_COMPLETE_PAGE.formatted(nonce));
// commit it here, since the resource method returns null
response.flushBuffer();
}
/**
* Resolves the authenticated user from a session.
*
* @param session HTTP session
* @return session user or {@code null}
*/
private User getSessionUser(HttpSession session) {
if (session == null) {
return null;
}
return (User) session.getAttribute(Constants.SESSION_USER);
}
/**
* Reloads the session user after an OAuth callback updates session state.
*
* @param request inbound HTTP request
* @param session current session reference
* @return session user or {@code null}
*/
private User refreshSessionUser(HttpServletRequest request, HttpSession session) {
if (session != null || (session = request.getSession(false)) != null) {
return (User) session.getAttribute(Constants.SESSION_USER);
}
return null;
}
/**
* Checks whether a user has an access token for the requested provider.
*
* @param user user to inspect
* @param provider authentication provider
* @return {@code true} when a token exists
*/
private boolean hasAccessToken(User user, AuthProvider provider) {
return user != null && user.getAccessToken(provider) != null;
}
/**
* Encodes the request query string for safe OAuth parsing.
*
* @param request inbound HTTP request
* @return encoded query string
*/
private String getEncodedQueryString(HttpServletRequest request) {
return WebUtility.encodeHTTPUri(request.getQueryString());
}
/**
* Checks whether the callback query contains an OAuth authorization code.
*
* @param queryString encoded callback query string
* @return {@code true} when a code parameter is present
*/
private boolean hasOAuthCode(String queryString) {
return queryString != null && queryString.contains("code");
}
/**
* Handles ADFS OAuth login callback flow.
*/
@GET
@Produces("application/json")
@Path("/login/adfs")
public Response loginADFS(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
// unified OAuth2/OIDC flow - see loginGeneric + AdfsTokenFiller (id_token mode)
return loginGeneric("adfs", request, response);
}
/**
* Handles Dropbox OAuth login callback flow.
*/
@GET
@Produces("application/json")
@Path("/login/dropbox")
public Response loginDropBox(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
// unified OAuth2 flow - see loginGeneric + DropboxTokenFiller
return loginGeneric("dropbox", request, response);
}
/**
* Handles GitHub OAuth login callback flow.
* https://developer.github.com/apps/building-oauth-apps/authorization-options-for-oauth-apps/
*/
@GET
@Produces("application/json")
@Path("/login/github")
public Response loginGithub(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
// unified OAuth2 flow - see loginGeneric + GithubTokenFiller
// (form-encoded token exchange + git cert install live in the filler)
return loginGeneric("github", request, response);
}
/**
* Handles GitLab OAuth login callback flow.
* https://docs.gitlab.com/13.12/ee/integration/oauth_provider.html
* https://docs.gitlab.com/13.12/ee/api/oauth2.html
*/
@GET
@Produces("application/json")
@Path("/login/gitlab")
public Response loginGitlab(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
// unified OAuth2 flow - see loginGeneric + GitLabTokenFiller
return loginGeneric("gitlab", request, response);
}
/**
* Handles Google OAuth login callback flow.
* https://developers.google.com/api-client-library/java/google-api-java-client/oauth2
*/
@GET
@Produces("application/json")
@Path("/login/google")
public Response loginGoogle(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
// unified OAuth2 flow - see loginGeneric + GoogleTokenFiller
return loginGeneric("google", request, response);
}
/**
* Handles Jira OAuth login callback and exchanges the authorization code for a
* token.
*
* @param request inbound HTTP request
* @param response outbound HTTP response
* @return redirect response
* @throws IOException when redirect writing fails
*/
@GET
@Produces("application/json")
@Path("/login2/jira")
public Response loginJiraDynamic(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
HttpSession session = initializeOAuthLoginSession(request);
User userObj = getSessionUser(session);
String queryString = getEncodedQueryString(request);
if (hasOAuthCode(queryString)) {
if (!hasAccessToken(userObj, AuthProvider.JIRA)) {
String[] outputs = HttpHelperUtility.getCodes(queryString);
String code = URLDecoder.decode(outputs[0], StandardCharsets.UTF_8);
if (code.matches("[ -~]+")) {
String state = URLDecoder.decode(outputs[1], StandardCharsets.UTF_8);
String connectionId = session == null ? null : (String) session.getAttribute("sf_state_" + state);
if (connectionId == null) {
// invalid or tampered state
response.setStatus(400);
return null;
}
session.removeAttribute("sf_state_" + state);
String redirectUri = WebUtility.getCurrentCallbackUrl(request);
boolean autoAdd = true;
Map<String, Object> details = SecurityExternalConnectorsUtils
.getJiraConnectionDetails(connectionId);
String clientId = (String) details.get("clientId");
String clientSecret = (String) details.get("clientSecret");
String userInfoUrl = (String) details.get("userInfoUrl");
if (clientId == null || clientSecret == null || redirectUri == null) {
classLogger.warn(
"Jira credentials unavailable for connectionId='{}'; missing clientId={}, clientSecret={}, redirectUri={}",
Utility.cleanLogString(connectionId), clientId == null, clientSecret == null,
redirectUri == null);
response.setContentType("text/plain; charset=UTF-8");
response.setHeader("X-Content-Type-Options", "nosniff");
response.setStatus(400);
response.getWriter().write("Jira credentials not found for the requested connection");
return null;
}
classLogger.debug(">> {}", Utility.cleanLogString(request.getQueryString()));
Map<String, String> params = new HashMap<>();
params.put("client_id", clientId);
params.put("client_secret", clientSecret);
params.put("redirect_uri", redirectUri);
params.put("code", code);
params.put("grant_type", "authorization_code");
String url = "https://auth.atlassian.com/oauth/token";
AccessToken accessToken = HttpHelperUtility.getAccessToken(url, params, true, true);
if (accessToken == null) {
// not authenticated
response.setStatus(302);
response.sendRedirect(getJiraRedirectDynamic(request, response, connectionId));
return null;
}
accessToken.setProvider(AuthProvider.JIRA);
// fill the access token with the other properties so we can properly create the
// user
JiraTokenFiller profiler = new JiraTokenFiller();
profiler.fillAccessToken(accessToken, userInfoUrl, null, null, null);
String cloudId = fetchJiraCloudId(accessToken.getAccess_token());
if (cloudId != null) {
accessToken.setId(cloudId);
}
addAccessToken(accessToken, request, autoAdd);
classLogger.debug("Successfully processed Jira OAuth callback. Access Token is.. {}",
accessToken.getAccess_token());
}
}
}
userObj = refreshSessionUser(request, session);
if (!hasAccessToken(userObj, AuthProvider.JIRA)) {
// not authenticated
response.setStatus(302);
response.sendRedirect(getJiraRedirectDynamic(request, response, null));
return null;
}
finishOAuthLogin(request, response);
return null;
}
/**
* Builds the Jira dynamic-credential authorization redirect URL.
*
* @param request inbound HTTP request
* @param response outbound HTTP response
* @param connectionId external-connector id
* @return Jira authorize URL or {@code null} when validation fails
* @throws UnsupportedEncodingException when redirect parameters cannot be URL
* encoded
* @throws IOException when response writing fails
*/
private String getJiraRedirectDynamic(HttpServletRequest request, HttpServletResponse response, String connectionId)
throws UnsupportedEncodingException, IOException {
String redirectUri = WebUtility.getCurrentCallbackUrl(request);
if (connectionId == null) {
connectionId = request.getParameter("connectionId");
}
if (connectionId == null || connectionId.isEmpty()) {
response.setStatus(400);
response.getWriter().write("Missing required parameter: connectionId");
return null;
}
String state = UUID.randomUUID().toString();
request.getSession().setAttribute("sf_state_" + state, connectionId);
Map<String, Object> details = SecurityExternalConnectorsUtils.getJiraConnectionDetails(connectionId);
String clientId = (String) details.get("clientId");
String scope = (String) details.get("scope");
if (clientId == null || scope == null || redirectUri == null) {
classLogger.warn(
"Jira credentials unavailable for connectionId='{}'; missing clientId={}, scope={}, redirectUri={}",
Utility.cleanLogString(connectionId), clientId == null, scope == null, redirectUri == null);
response.setContentType("text/plain; charset=UTF-8");
response.setHeader("X-Content-Type-Options", "nosniff");
response.setStatus(400);
response.getWriter().write("Jira credentials not found for the requested connection");
return null;
}
String redirectUrl = "https://auth.atlassian.com/authorize" + "?audience=api.atlassian.com" + "&client_id="
+ URLEncoder.encode(clientId, "UTF-8") + "&scope=" + URLEncoder.encode(scope, "UTF-8")
+ "&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8") + "&state="
+ URLEncoder.encode(state, "UTF-8") + "&response_type=code" + "&prompt=consent";
classLogger.debug("Sending Jira redirect.. {}", Utility.cleanLogString(redirectUrl));
return redirectUrl;
}
/**
* Fetches the first accessible Jira cloud resource id for a bearer token.
*
* @param bearerToken Jira bearer token
* @return cloud id when available; otherwise {@code null}
*/
private String fetchJiraCloudId(String bearerToken) {
try {
String url = "https://api.atlassian.com/oauth/token/accessible-resources";
Map<String, Object> params = new HashMap<>();
String output = HttpHelperUtility.makeGetCall(url, bearerToken, params, true);
JSONArray resources = new JSONArray(output);
if (resources.length() > 0) {
return resources.getJSONObject(0).getString("id");
}
} catch (Exception e) {
classLogger.error("Failed to fetch Jira accessible resources (cloudId)", e);
}
return null;
}
/**
* Handles LinkedIn OAuth login callback flow.
*/
@GET
@Produces("application/json")
@Path("/login/linkedin")
public Response loginLinkedin(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
// unified OAuth2 flow - see loginGeneric + LinkedInTokenFiller
return loginGeneric("linkedin", request, response);
}
/**
* Deprecated alias for the Microsoft OAuth login endpoint.
*/
@GET
@Produces("application/json")
@Path("/login/ms")
@Deprecated
public Response loginMS(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
return loginMicrosoft(request, response);
}
/**
* Handles Microsoft OAuth login callback flow.
*
* @param request inbound HTTP request
* @param response outbound HTTP response
* @return redirect response
* @throws IOException when redirect writing fails
*/
@GET
@Produces("application/json")
@Path("/login/microsoft")
public Response loginMicrosoft(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
// unified OAuth2 flow - see loginGeneric + MicrosoftTokenFiller
// (tenant-templated endpoints + login_external enforcement live in the filler)
return loginGeneric("ms", request, response);
}
/**
* Handles Okta OAuth login callback flow.
*/
@GET
@Produces("application/json")
@Path("/login/okta")
public Response loginOkta(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
// unified OAuth2 flow - see loginGeneric + OktaTokenFiller
return loginGeneric("okta", request, response);
}
@Path("/login/producthunt")
/**
* Handles Product Hunt OAuth login callback flow.
*
* @param request inbound HTTP request
* @param response outbound HTTP response
* @return redirect response
* @throws IOException when redirect writing fails
*/
public Response loginProducthunt(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
// unified OAuth2 flow - see loginGeneric + ProductHuntTokenFiller
return loginGeneric("producthunt", request, response);
}
/**
* Handles Salesforce OAuth login callback flow.
*/
@GET
@Produces("application/json")
@Path("/login/salesforce")
public Response loginSalesforce(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
// unified OAuth2 flow - see loginGeneric + SalesforceTokenFiller
return loginGeneric("salesforce", request, response);
}
/**
* Handles Salesforce OAuth callback flow using dynamic connector credentials.
*/
@GET
@Produces("application/json")
@Path("/login2/salesforce")
public Response loginSalesforceDynamic(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException {
HttpSession session = initializeOAuthLoginSession(request);
User userObj = getSessionUser(session);
String queryString = getEncodedQueryString(request);
if (hasOAuthCode(queryString)) {
if (!hasAccessToken(userObj, AuthProvider.SALESFORCE)) {
String[] outputs = HttpHelperUtility.getCodes(queryString);
// oauth code should match [ -~]+ (1 or more ascii)
// https://www.rfc-editor.org/rfc/rfc6749#appendix-A.11
String code = URLDecoder.decode(outputs[0], StandardCharsets.UTF_8);
if (code.matches("[ -~]+")) {
String state = outputs[1];
String connectionId = session == null ? null : (String) session.getAttribute("sf_state_" + state);
if (connectionId == null) {
// invalid or tampered state
response.setStatus(400);
return null;
}
session.removeAttribute("sf_state_" + state);
// get credentials by UUID (ID) from SALESFORCE_CREDENTIALS table
String redirectUri = WebUtility.getCurrentCallbackUrl(request);
boolean autoAdd = true;
Pair<String, String> details = SecurityExternalConnectorsUtils
.getSalesforceConnectionDetails(connectionId);
String clientId = details.getValue0();
String clientSecret = details.getValue1();
if (clientId == null || clientSecret == null || redirectUri == null) {
classLogger.warn(
"Salesforce credentials unavailable for connectionId='{}'; missing clientId={}, clientSecret={}, redirectUri={}",
Utility.cleanLogString(connectionId), clientId == null, clientSecret == null,
redirectUri == null);
response.setContentType("text/plain; charset=UTF-8");
response.setHeader("X-Content-Type-Options", "nosniff");
response.setStatus(400);
response.getWriter().write("Salesforce credentials not found for the requested connection");
return null;
}
classLogger.debug(">> {}", Utility.cleanLogString(request.getQueryString()));
Map<String, String> params = new HashMap<>();
params.put("client_id", clientId);
params.put("grant_type", "authorization_code");
params.put("redirect_uri", redirectUri);
params.put("code", code);
params.put("client_secret", clientSecret);
String url = "https://login.salesforce.com/services/oauth2/token";
AccessToken accessToken = HttpHelperUtility.getAccessToken(url, params, true, true);
if (accessToken == null) {
// not authenticated
response.setStatus(302);
response.sendRedirect(getSalesforceRedirectDynamic(request, response, connectionId));
return null;
}
accessToken.setProvider(AuthProvider.SALESFORCE);
// fill the access token with the other properties so we can properly create the
// user
SalesforceTokenFiller profiler = new SalesforceTokenFiller();
profiler.fillAccessToken(accessToken, null, null, null, null);
addAccessToken(accessToken, request, autoAdd);
classLogger.debug("Access Token is.. {}", accessToken.getAccess_token());
}
}
}
userObj = refreshSessionUser(request, session);
if (!hasAccessToken(userObj, AuthProvider.SALESFORCE)) {
// not authenticated
response.setStatus(302);
response.sendRedirect(getSalesforceRedirectDynamic(request, response, null));
return null;
}
finishOAuthLogin(request, response);
return null;
}
/**
* Builds the Salesforce dynamic-credential authorization redirect URL.
*
* @param request inbound HTTP request
* @param response outbound HTTP response
* @param connectionId external-connector id
* @return Salesforce authorize URL or {@code null} when validation fails
* @throws UnsupportedEncodingException when redirect parameters cannot be URL
* encoded
* @throws IOException when response writing fails
*/
private String getSalesforceRedirectDynamic(HttpServletRequest request, @Context HttpServletResponse response,
String connectionId) throws UnsupportedEncodingException, IOException {
String redirectUri = WebUtility.getCurrentCallbackUrl(request);
if (connectionId == null) {
connectionId = request.getParameter("connectionId");
}
if (connectionId == null || connectionId.isEmpty()) {
response.setStatus(400);
response.getWriter().write("Missing required parameter: connectionId");
return null;
}
String state = UUID.randomUUID().toString();
// store the connection id in session
request.getSession().setAttribute("sf_state_" + state, connectionId);