Skip to content

Commit

Permalink
feat(auth): improve authentication flow logging (datahub-project#10428)
Browse files Browse the repository at this point in the history
  • Loading branch information
darnaut authored and sleeperdeep committed Jun 25, 2024
1 parent 42e4501 commit bb4be6b
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 33 deletions.
2 changes: 2 additions & 0 deletions datahub-frontend/app/auth/sso/oidc/OidcCallbackLogic.java
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,8 @@ private Result handleOidcCallback(
"Failed to perform post authentication steps. Error message: %s", e.getMessage()));
}

log.info("OIDC callback authentication successful for user: {}", userName);

// Successfully logged in - Generate GMS login token
final String accessToken = authClient.generateSessionTokenForUser(corpUserUrn.getId());
return result
Expand Down
6 changes: 4 additions & 2 deletions datahub-frontend/app/client/AuthServiceClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@ public String generateSessionTokenForUser(@Nonnull final String userId) {
CloseableHttpResponse response = null;

try {

final String protocol = this.metadataServiceUseSsl ? "https" : "http";
final HttpPost request =
new HttpPost(
Expand All @@ -86,6 +85,8 @@ public String generateSessionTokenForUser(@Nonnull final String userId) {
this.metadataServicePort,
GENERATE_SESSION_TOKEN_ENDPOINT));

log.info("Requesting session token for user: {}", userId);

// Build JSON request to generate a token on behalf of a user.
final ObjectMapper objectMapper = new ObjectMapper();
final ObjectNode objectNode = objectMapper.createObjectNode();
Expand All @@ -100,7 +101,7 @@ public String generateSessionTokenForUser(@Nonnull final String userId) {
response = httpClient.execute(request);
final HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK && entity != null) {
// Successfully generated a token for the User
log.info("Successfully received session token for user: {}", userId);
final String jsonStr = EntityUtils.toString(entity);
return getAccessTokenFromJson(jsonStr);
} else {
Expand All @@ -110,6 +111,7 @@ public String generateSessionTokenForUser(@Nonnull final String userId) {
response.getStatusLine().toString(), response.getEntity().toString()));
}
} catch (Exception e) {
log.error("Failed to generate session token for user: {}", userId, e);
throw new RuntimeException("Failed to generate session token for user", e);
} finally {
try {
Expand Down
12 changes: 7 additions & 5 deletions datahub-frontend/app/controllers/AuthenticationController.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
import play.mvc.Results;
import security.AuthenticationManager;

// TODO add logging.
public class AuthenticationController extends Controller {
public static final String AUTH_VERBOSE_LOGGING = "auth.verbose.logging";
private static final String AUTH_REDIRECT_URI_PARAM = "redirect_uri";
Expand Down Expand Up @@ -183,10 +182,12 @@ public Result logIn(Http.Request request) {
boolean loginSucceeded = tryLogin(username, password);

if (!loginSucceeded) {
_logger.info("Login failed for user: {}", username);
return Results.badRequest(invalidCredsJson);
}

final Urn actorUrn = new CorpuserUrn(username);
_logger.info("Login successful for user: {}, urn: {}", username, actorUrn);
final String accessToken = _authClient.generateSessionTokenForUser(actorUrn.getId());
return createSession(actorUrn.toString(), accessToken);
}
Expand Down Expand Up @@ -250,6 +251,7 @@ public Result signUp(Http.Request request) {
final Urn userUrn = new CorpuserUrn(email);
final String userUrnString = userUrn.toString();
_authClient.signUp(userUrnString, fullName, email, title, password, inviteToken);
_logger.info("Signed up user {} using invite tokens", userUrnString);
final String accessToken = _authClient.generateSessionTokenForUser(userUrn.getId());
return createSession(userUrnString, accessToken);
}
Expand Down Expand Up @@ -351,15 +353,15 @@ private boolean tryLogin(String username, String password) {
// First try jaas login, if enabled
if (_jaasConfigs.isJAASEnabled()) {
try {
_logger.debug("Attempting jaas authentication");
_logger.debug("Attempting JAAS authentication for user: {}", username);
AuthenticationManager.authenticateJaasUser(username, password);
_logger.debug("Jaas authentication successful. Login succeeded");
_logger.debug("JAAS authentication successful. Login succeeded");
loginSucceeded = true;
} catch (Exception e) {
if (_verbose) {
_logger.debug("Jaas authentication error. Login failed", e);
_logger.debug("JAAS authentication error. Login failed", e);
} else {
_logger.debug("Jaas authentication error. Login failed");
_logger.debug("JAAS authentication error. Login failed");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,7 @@ CompletableFuture<ResponseEntity<String>> generateSessionTokenForUser(
try {
bodyJson = mapper.readTree(jsonStr);
} catch (JsonProcessingException e) {
log.error(
String.format(
"Failed to parse json while attempting to generate session token %s", jsonStr));
log.error("Failed to parse json while attempting to generate session token {}", jsonStr, e);
return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
}
if (bodyJson == null) {
Expand All @@ -139,22 +137,28 @@ CompletableFuture<ResponseEntity<String>> generateSessionTokenForUser(
return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
}

log.debug(String.format("Attempting to generate session token for user %s", userId.asText()));
log.info("Attempting to generate session token for user {}", userId.asText());
final String actorId = AuthenticationContext.getAuthentication().getActor().getId();
return CompletableFuture.supplyAsync(
() -> {
// 1. Verify that only those authorized to generate a token (datahub system) are able to.
if (isAuthorizedToGenerateSessionToken(actorId)) {
try {
// 2. Generate a new DataHub JWT
final long sessionTokenDurationMs =
_configProvider.getAuthentication().getSessionTokenDurationMs();
final String token =
_statelessTokenService.generateAccessToken(
TokenType.SESSION,
new Actor(ActorType.USER, userId.asText()),
_configProvider.getAuthentication().getSessionTokenDurationMs());
sessionTokenDurationMs);
log.info(
"Successfully generated session token for user: {}, duration: {} ms",
userId.asText(),
sessionTokenDurationMs);
return new ResponseEntity<>(buildTokenResponse(token), HttpStatus.OK);
} catch (Exception e) {
log.error("Failed to generate session token for user", e);
log.error("Failed to generate session token for user: {}", userId.asText(), e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Expand Down Expand Up @@ -189,8 +193,7 @@ CompletableFuture<ResponseEntity<String>> signUp(final HttpEntity<String> httpEn
try {
bodyJson = mapper.readTree(jsonStr);
} catch (JsonProcessingException e) {
log.error(
String.format("Failed to parse json while attempting to create native user %s", jsonStr));
log.debug("Failed to parse json while attempting to create native user", e);
return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
}
if (bodyJson == null) {
Expand Down Expand Up @@ -229,13 +232,13 @@ CompletableFuture<ResponseEntity<String>> signUp(final HttpEntity<String> httpEn
String passwordString = password.asText();
String inviteTokenString = inviteToken.asText();
Authentication auth = AuthenticationContext.getAuthentication();
log.debug(String.format("Attempting to create native user %s", userUrnString));
log.info("Attempting to create native user {}", userUrnString);
return CompletableFuture.supplyAsync(
() -> {
try {
Urn inviteTokenUrn = _inviteTokenService.getInviteTokenUrn(inviteTokenString);
if (!_inviteTokenService.isInviteTokenValid(systemOperationContext, inviteTokenUrn)) {
log.error(String.format("Invalid invite token %s", inviteTokenString));
log.error("Invalid invite token {}", inviteTokenString);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}

Expand All @@ -247,10 +250,10 @@ CompletableFuture<ResponseEntity<String>> signUp(final HttpEntity<String> httpEn
titleString,
passwordString);
String response = buildSignUpResponse();
log.info("Created native user {}", userUrnString);
return new ResponseEntity<>(response, HttpStatus.OK);
} catch (Exception e) {
log.error(
String.format("Failed to create credentials for native user %s", userUrnString), e);
log.error("Failed to create credentials for native user {}", userUrnString, e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
});
Expand Down Expand Up @@ -279,8 +282,7 @@ CompletableFuture<ResponseEntity<String>> resetNativeUserCredentials(
try {
bodyJson = mapper.readTree(jsonStr);
} catch (JsonProcessingException e) {
log.error(
String.format("Failed to parse json while attempting to create native user %s", jsonStr));
log.debug("Failed to parse json while attempting to create native user", e);
return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
}
if (bodyJson == null) {
Expand All @@ -300,17 +302,17 @@ CompletableFuture<ResponseEntity<String>> resetNativeUserCredentials(
String passwordString = password.asText();
String resetTokenString = resetToken.asText();
Authentication auth = AuthenticationContext.getAuthentication();
log.debug(String.format("Attempting to reset credentials for native user %s", userUrnString));
log.info("Attempting to reset credentials for native user {}", userUrnString);
return CompletableFuture.supplyAsync(
() -> {
try {
_nativeUserService.resetCorpUserCredentials(
systemOperationContext, userUrnString, passwordString, resetTokenString);
String response = buildResetNativeUserCredentialsResponse();
log.info("Reset credentials for native user {}", userUrnString);
return new ResponseEntity<>(response, HttpStatus.OK);
} catch (Exception e) {
log.error(
String.format("Failed to reset credentials for native user %s", userUrnString), e);
log.error("Failed to reset credentials for native user {}", userUrnString, e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
});
Expand Down Expand Up @@ -338,9 +340,7 @@ CompletableFuture<ResponseEntity<String>> verifyNativeUserCredentials(
try {
bodyJson = mapper.readTree(jsonStr);
} catch (JsonProcessingException e) {
log.error(
String.format(
"Failed to parse json while attempting to verify native user password %s", jsonStr));
log.debug("Failed to parse json while attempting to verify native user password", e);
return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
}
if (bodyJson == null) {
Expand All @@ -357,18 +357,21 @@ CompletableFuture<ResponseEntity<String>> verifyNativeUserCredentials(

String userUrnString = userUrn.asText();
String passwordString = password.asText();
log.debug(String.format("Attempting to verify credentials for native user %s", userUrnString));
log.info("Attempting to verify credentials for native user {}", userUrnString);
return CompletableFuture.supplyAsync(
() -> {
try {
boolean doesPasswordMatch =
_nativeUserService.doesPasswordMatch(
systemOperationContext, userUrnString, passwordString);
String response = buildVerifyNativeUserPasswordResponse(doesPasswordMatch);
log.info(
"Verified credentials for native user: {}, result: {}",
userUrnString,
doesPasswordMatch);
return new ResponseEntity<>(response, HttpStatus.OK);
} catch (Exception e) {
log.error(
String.format("Failed to verify credentials for native user %s", userUrnString), e);
log.error("Failed to verify credentials for native user {}", userUrnString, e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
});
Expand All @@ -383,9 +386,7 @@ CompletableFuture<ResponseEntity<String>> track(final HttpEntity<String> httpEnt
try {
bodyJson = mapper.readTree(jsonStr);
} catch (JsonProcessingException e) {
log.error(
String.format(
"Failed to parse json while attempting to track analytics event %s", jsonStr));
log.error("Failed to parse json while attempting to track analytics event {}", jsonStr);
return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
}
if (bodyJson == null) {
Expand Down

0 comments on commit bb4be6b

Please sign in to comment.