Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fallback to 24h time format when MSI authentication fails due to date format mismatch #1177

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 47 additions & 35 deletions src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import java.sql.Statement;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
Expand Down Expand Up @@ -422,7 +423,8 @@ class ActiveDirectoryAuthentication {
static final String ACCESS_TOKEN_IDENTIFIER = "\"access_token\":\"";
static final String ACCESS_TOKEN_EXPIRES_IN_IDENTIFIER = "\"expires_in\":\"";
static final String ACCESS_TOKEN_EXPIRES_ON_IDENTIFIER = "\"expires_on\":\"";
static final String ACCESS_TOKEN_EXPIRES_ON_DATE_FORMAT = "M/d/yyyy h:mm:ss a X";
static final String ACCESS_TOKEN_EXPIRES_ON_AMPM_DATE_FORMAT = "M/d/yyyy h:mm:ss a X";
static final String ACCESS_TOKEN_EXPIRES_ON_24H_DATE_FORMAT = "M/d/yyyy H:mm:ss X";
static final int GET_ACCESS_TOKEN_SUCCESS = 0;
static final int GET_ACCESS_TOKEN_INVALID_GRANT = 1;
static final int GET_ACCESS_TOKEN_TANSISENT_ERROR = 2;
Expand Down Expand Up @@ -4428,40 +4430,8 @@ private SqlFedAuthToken getMSIAuthToken(String resource, String msiClientId) thr
try (InputStream stream = connection.getInputStream()) {

BufferedReader reader = new BufferedReader(new InputStreamReader(stream, UTF_8), 100);
String result = reader.readLine();

int startIndex_AT = result.indexOf(ActiveDirectoryAuthentication.ACCESS_TOKEN_IDENTIFIER)
+ ActiveDirectoryAuthentication.ACCESS_TOKEN_IDENTIFIER.length();

String accessToken = result.substring(startIndex_AT, result.indexOf("\"", startIndex_AT + 1));

Calendar cal = new Calendar.Builder().setInstant(new Date()).build();

if (isAzureFunction) {
// Fetch expires_on
int startIndex_ATX = result
.indexOf(ActiveDirectoryAuthentication.ACCESS_TOKEN_EXPIRES_ON_IDENTIFIER)
+ ActiveDirectoryAuthentication.ACCESS_TOKEN_EXPIRES_ON_IDENTIFIER.length();
String accessTokenExpiry = result.substring(startIndex_ATX,
result.indexOf("\"", startIndex_ATX + 1));
if (connectionlogger.isLoggable(Level.FINER)) {
connectionlogger.finer(toString() + " MSI auth token expires on: " + accessTokenExpiry);
}

DateFormat df = new SimpleDateFormat(
ActiveDirectoryAuthentication.ACCESS_TOKEN_EXPIRES_ON_DATE_FORMAT);
cal = new Calendar.Builder().setInstant(df.parse(accessTokenExpiry)).build();
} else {
// Fetch expires_in
int startIndex_ATX = result
.indexOf(ActiveDirectoryAuthentication.ACCESS_TOKEN_EXPIRES_IN_IDENTIFIER)
+ ActiveDirectoryAuthentication.ACCESS_TOKEN_EXPIRES_IN_IDENTIFIER.length();
String accessTokenExpiry = result.substring(startIndex_ATX,
result.indexOf("\"", startIndex_ATX + 1));
cal.add(Calendar.SECOND, Integer.parseInt(accessTokenExpiry));
}

return new SqlFedAuthToken(accessToken, cal.getTime());
String responseStr = reader.readLine();
return parseSqlFedAuthTokenResponse(isAzureFunction, responseStr);
}
} catch (Exception e) {
retry++;
Expand Down Expand Up @@ -4548,6 +4518,48 @@ private void sendFedAuthToken(FedAuthTokenCommand fedAuthCommand, SqlFedAuthToke
TDSParser.parse(tdsReader, tdsTokenHandler);
}

final SqlFedAuthToken parseSqlFedAuthTokenResponse(boolean isAzureFunction, String responseStr) throws ParseException {
int startIndex_AT = responseStr.indexOf(ActiveDirectoryAuthentication.ACCESS_TOKEN_IDENTIFIER)
+ ActiveDirectoryAuthentication.ACCESS_TOKEN_IDENTIFIER.length();

String accessToken = responseStr.substring(startIndex_AT, responseStr.indexOf("\"", startIndex_AT + 1));

Calendar cal = new Calendar.Builder().setInstant(new Date()).build();

if (isAzureFunction) {
// Fetch expires_on
int startIndex_ATX = responseStr
.indexOf(ActiveDirectoryAuthentication.ACCESS_TOKEN_EXPIRES_ON_IDENTIFIER)
+ ActiveDirectoryAuthentication.ACCESS_TOKEN_EXPIRES_ON_IDENTIFIER.length();
String accessTokenExpiry = responseStr.substring(startIndex_ATX,
responseStr.indexOf("\"", startIndex_ATX + 1));
if (connectionlogger.isLoggable(Level.FINER)) {
connectionlogger.finer(toString() + " MSI auth token expires on: " + accessTokenExpiry);
}

DateFormat df;
try {
df = new SimpleDateFormat(
ActiveDirectoryAuthentication.ACCESS_TOKEN_EXPIRES_ON_AMPM_DATE_FORMAT);
cal = new Calendar.Builder().setInstant(df.parse(accessTokenExpiry)).build();
} catch (ParseException ignore) {
df = new SimpleDateFormat(
ActiveDirectoryAuthentication.ACCESS_TOKEN_EXPIRES_ON_24H_DATE_FORMAT);
cal = new Calendar.Builder().setInstant(df.parse(accessTokenExpiry)).build();
}
} else {
// Fetch expires_in
int startIndex_ATX = responseStr
.indexOf(ActiveDirectoryAuthentication.ACCESS_TOKEN_EXPIRES_IN_IDENTIFIER)
+ ActiveDirectoryAuthentication.ACCESS_TOKEN_EXPIRES_IN_IDENTIFIER.length();
String accessTokenExpiry = responseStr.substring(startIndex_ATX,
responseStr.indexOf("\"", startIndex_ATX + 1));
cal.add(Calendar.SECOND, Integer.parseInt(accessTokenExpiry));
}

return new SqlFedAuthToken(accessToken, cal.getTime());
}

final void processFeatureExtAck(TDSReader tdsReader) throws SQLServerException {
tdsReader.readUnsignedByte(); // Reading FEATUREEXTACK_TOKEN 0xAE

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package com.microsoft.sqlserver.jdbc;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

Expand All @@ -14,6 +15,9 @@
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
Expand Down Expand Up @@ -599,4 +603,31 @@ public void run() {

assertTrue(isInterrupted, TestResource.getResource("R_threadInterruptNotSet"));
}

@Test
public void testCanParseAMPMDateExpInMSIToken() throws SQLServerException, ParseException {
final String windowsMachineResponse = "{\"access_token\":\"random-token-content\",\"expires_on\":\"11/1/2019 4:40:21 PM +00:00\"," +
"\"resource\":\"https://database.windows.net\",\"token_type\":\"Bearer\"}";
Calendar cal = new Calendar.Builder().setTimeZone(TimeZone.getTimeZone("UTC"))
.setDate(2019, 10, 1)
.setTimeOfDay(16, 40, 21, 0)
.build();
SQLServerConnection connection = new SQLServerConnection("someConnectionProperty");
SqlFedAuthToken token = connection.parseSqlFedAuthTokenResponse(true, windowsMachineResponse);
assertNotNull(token);
assertEquals(token.expiresOn.compareTo(cal.getTime()), 0);
}

@Test
public void testCanParse24hDateExpInMSIToken() throws SQLServerException, ParseException {
final String linuxMachineResponse = "{\"access_token\":\"mock-token-content\", \"expires_on\":\"10/31/2019 16:10:13 +00:00\", \"resource\":\"https://database.windows.net\", \"token_type\":\"Bearer\"}";
Calendar cal = new Calendar.Builder().setTimeZone(TimeZone.getTimeZone("UTC"))
.setDate(2019, 9, 31)
.setTimeOfDay(16, 10, 13, 0)
.build();
SQLServerConnection connection = new SQLServerConnection("someConnectionProperty");
SqlFedAuthToken token = connection.parseSqlFedAuthTokenResponse(true, linuxMachineResponse);
assertNotNull(token);
assertEquals(token.expiresOn.compareTo(cal.getTime()), 0);
}
}