committed by
GitHub
15 changed files with 858 additions and 60 deletions
@ -0,0 +1,66 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2026 The Thingsboard Authors |
||||
|
* |
||||
|
* 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 org.thingsboard.server.service.security.auth.oauth2; |
||||
|
|
||||
|
import lombok.extern.slf4j.Slf4j; |
||||
|
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; |
||||
|
import org.thingsboard.server.common.data.StringUtils; |
||||
|
|
||||
|
import java.util.Locale; |
||||
|
import java.util.Set; |
||||
|
import java.util.regex.Pattern; |
||||
|
|
||||
|
@Slf4j |
||||
|
public class CallbackUrlSchemeValidator { |
||||
|
|
||||
|
// RFC 3986 scheme grammar, plus '_': mobile apps derive the scheme from their package name, which may contain one
|
||||
|
private static final Pattern SCHEME_PATTERN = Pattern.compile("[a-zA-Z][a-zA-Z0-9+.\\-_]*"); |
||||
|
private static final Set<String> FORBIDDEN_SCHEMES = Set.of("http", "https", "javascript", "data", "file", "vbscript"); |
||||
|
private static final int MAX_LOGGED_LENGTH = 128; |
||||
|
|
||||
|
/** |
||||
|
* The redirect carrying the access token is built as callbackUrlScheme + ':', so only a mobile app scheme may |
||||
|
* pass: a web scheme would send the token to whatever host follows it. |
||||
|
*/ |
||||
|
public static boolean isValid(String callbackUrlScheme) { |
||||
|
return !StringUtils.isEmpty(callbackUrlScheme) |
||||
|
&& SCHEME_PATTERN.matcher(callbackUrlScheme).matches() |
||||
|
&& !FORBIDDEN_SCHEMES.contains(callbackUrlScheme.toLowerCase(Locale.ROOT)); |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* The attribute is restored from the oauth2_auth_request cookie, which the client can replace, so the scheme is |
||||
|
* checked again on read and not only when the authorization request is built. |
||||
|
*/ |
||||
|
public static String getCallbackUrlScheme(OAuth2AuthorizationRequest authorizationRequest) { |
||||
|
String callbackUrlScheme = authorizationRequest != null ? |
||||
|
authorizationRequest.getAttribute(TbOAuth2ParameterNames.CALLBACK_URL_SCHEME) : null; |
||||
|
if (StringUtils.isEmpty(callbackUrlScheme)) { |
||||
|
return null; |
||||
|
} |
||||
|
if (!isValid(callbackUrlScheme)) { |
||||
|
log.warn("Ignoring invalid callback url scheme: [{}]", forLog(callbackUrlScheme)); |
||||
|
return null; |
||||
|
} |
||||
|
return callbackUrlScheme; |
||||
|
} |
||||
|
|
||||
|
// a rejected value is attacker-controlled: it must not be able to forge log lines
|
||||
|
private static String forLog(String value) { |
||||
|
return value.substring(0, Math.min(value.length(), MAX_LOGGED_LENGTH)).replaceAll("[^\\x20-\\x7E]", "?"); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,66 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2026 The Thingsboard Authors |
||||
|
* |
||||
|
* 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 org.thingsboard.server.service.security.auth.oauth2; |
||||
|
|
||||
|
import lombok.extern.slf4j.Slf4j; |
||||
|
import org.thingsboard.server.common.data.StringUtils; |
||||
|
|
||||
|
import java.util.Locale; |
||||
|
|
||||
|
@Slf4j |
||||
|
public class PrevUriValidator { |
||||
|
|
||||
|
private static final int MAX_LENGTH = 2048; |
||||
|
private static final int MAX_LOGGED_LENGTH = 128; |
||||
|
|
||||
|
public static boolean isValid(String prevUri) { |
||||
|
if (StringUtils.isEmpty(prevUri)) { |
||||
|
return false; |
||||
|
} |
||||
|
if (!isInAppPath(prevUri)) { |
||||
|
log.debug("Ignoring prevUri that is not an in-app path: [{}]", forLog(prevUri)); |
||||
|
return false; |
||||
|
} |
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* prevUri is appended to the platform base URL, which ends right after the authority, so the single leading '/' |
||||
|
* is what keeps the redirect on this host - it closes the authority before any of the value is read. The rest |
||||
|
* keeps an accepted value usable: it has to survive the cookie round trip (RFC 6265 allows neither control |
||||
|
* characters nor '"', ',', ';', '\' or non-ASCII) and to pass StrictHttpFirewall, which rejects '//', '%2f'
|
||||
|
* and '%5c' in the path; a fragment would swallow the access token. |
||||
|
*/ |
||||
|
private static boolean isInAppPath(String prevUri) { |
||||
|
if (prevUri.length() > MAX_LENGTH || prevUri.charAt(0) != '/') { |
||||
|
return false; |
||||
|
} |
||||
|
for (int i = 0; i < prevUri.length(); i++) { |
||||
|
char c = prevUri.charAt(i); |
||||
|
if (c <= ' ' || c >= 127 || c == '"' || c == ',' || c == ';' || c == '\\' || c == '#') { |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
String path = StringUtils.substringBefore(prevUri, "?").toLowerCase(Locale.ROOT); |
||||
|
return !path.contains("//") && !path.contains("%2f") && !path.contains("%5c"); |
||||
|
} |
||||
|
|
||||
|
// a rejected value is attacker-controlled: it must not be able to forge log lines
|
||||
|
private static String forLog(String prevUri) { |
||||
|
return prevUri.substring(0, Math.min(prevUri.length(), MAX_LOGGED_LENGTH)).replaceAll("[^\\x20-\\x7E]", "?"); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,81 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2026 The Thingsboard Authors |
||||
|
* |
||||
|
* 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 org.thingsboard.server.controller; |
||||
|
|
||||
|
import jakarta.servlet.http.Cookie; |
||||
|
import jakarta.servlet.http.HttpServletRequest; |
||||
|
import org.junit.jupiter.api.BeforeEach; |
||||
|
import org.junit.jupiter.api.Test; |
||||
|
import org.junit.jupiter.api.extension.ExtendWith; |
||||
|
import org.junit.jupiter.params.ParameterizedTest; |
||||
|
import org.junit.jupiter.params.provider.ValueSource; |
||||
|
import org.mockito.InjectMocks; |
||||
|
import org.mockito.Mock; |
||||
|
import org.mockito.junit.jupiter.MockitoExtension; |
||||
|
import org.thingsboard.server.common.data.id.CustomerId; |
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
import org.thingsboard.server.service.security.system.SystemSecurityService; |
||||
|
|
||||
|
import static org.assertj.core.api.Assertions.assertThat; |
||||
|
import static org.mockito.ArgumentMatchers.any; |
||||
|
import static org.mockito.Mockito.mock; |
||||
|
import static org.mockito.Mockito.when; |
||||
|
import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.PREV_URI_COOKIE_NAME; |
||||
|
|
||||
|
@ExtendWith(MockitoExtension.class) |
||||
|
public class AdminControllerMailOAuth2Test { |
||||
|
|
||||
|
private static final String BASE_URL = "https://thingsboard.example.com"; |
||||
|
private static final String DEFAULT_PREV_URI = "/settings/outgoing-mail"; |
||||
|
|
||||
|
@Mock |
||||
|
private SystemSecurityService systemSecurityService; |
||||
|
|
||||
|
@InjectMocks |
||||
|
private AdminController adminController; |
||||
|
|
||||
|
private HttpServletRequest request; |
||||
|
|
||||
|
@BeforeEach |
||||
|
public void before() { |
||||
|
request = mock(HttpServletRequest.class); |
||||
|
when(systemSecurityService.getBaseUrl(any(TenantId.class), any(CustomerId.class), any(HttpServletRequest.class))).thenReturn(BASE_URL); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testInAppPathIsTakenFromPrevUriCookie() { |
||||
|
givenPrevUriCookie("/settings/notifications?tab=1"); |
||||
|
assertThat(adminController.getMailOAuth2RedirectUrl(request)).isEqualTo(BASE_URL + "/settings/notifications?tab=1"); |
||||
|
} |
||||
|
|
||||
|
@ParameterizedTest |
||||
|
@ValueSource(strings = {"@evil.com/", "//evil.com", "https://evil.com", "/\\evil.com", "/settings#fragment"}) |
||||
|
public void testForgedPrevUriCookieIsIgnored(String prevUri) { |
||||
|
givenPrevUriCookie(prevUri); |
||||
|
assertThat(adminController.getMailOAuth2RedirectUrl(request)).isEqualTo(BASE_URL + DEFAULT_PREV_URI); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testRedirectUrlWithoutPrevUriCookie() { |
||||
|
when(request.getCookies()).thenReturn(null); |
||||
|
assertThat(adminController.getMailOAuth2RedirectUrl(request)).isEqualTo(BASE_URL + DEFAULT_PREV_URI); |
||||
|
} |
||||
|
|
||||
|
private void givenPrevUriCookie(String prevUri) { |
||||
|
when(request.getCookies()).thenReturn(new Cookie[]{new Cookie(PREV_URI_COOKIE_NAME, prevUri)}); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,81 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2026 The Thingsboard Authors |
||||
|
* |
||||
|
* 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 org.thingsboard.server.service.security.auth.oauth2; |
||||
|
|
||||
|
import org.junit.jupiter.api.Test; |
||||
|
import org.junit.jupiter.params.ParameterizedTest; |
||||
|
import org.junit.jupiter.params.provider.NullAndEmptySource; |
||||
|
import org.junit.jupiter.params.provider.ValueSource; |
||||
|
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; |
||||
|
|
||||
|
import static org.assertj.core.api.Assertions.assertThat; |
||||
|
|
||||
|
public class CallbackUrlSchemeValidatorTest { |
||||
|
|
||||
|
@ParameterizedTest |
||||
|
@ValueSource(strings = {"tbmobile", "tb-mobile.app1", "TbMobile+1", "org.mycompany.myapp.auth", "com.my_company.app.auth"}) |
||||
|
public void testMobileAppSchemeIsValid(String callbackUrlScheme) { |
||||
|
assertThat(CallbackUrlSchemeValidator.isValid(callbackUrlScheme)).isTrue(); |
||||
|
} |
||||
|
|
||||
|
@ParameterizedTest |
||||
|
@NullAndEmptySource |
||||
|
@ValueSource(strings = { |
||||
|
"https://evil.com", |
||||
|
"http://evil.com", |
||||
|
"https", |
||||
|
"HTTPS", |
||||
|
"javascript", |
||||
|
"data", |
||||
|
"file", |
||||
|
"vbscript", |
||||
|
"//evil.com", |
||||
|
"tbmobile/evil.com", |
||||
|
"tbmobile:evil.com", |
||||
|
"tbmobile evil", |
||||
|
"1tbmobile", |
||||
|
"tbmobile@evil.com" |
||||
|
}) |
||||
|
public void testInvalidSchemeIsRejected(String callbackUrlScheme) { |
||||
|
assertThat(CallbackUrlSchemeValidator.isValid(callbackUrlScheme)).isFalse(); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testValidSchemeIsTakenFromAuthorizationRequest() { |
||||
|
assertThat(CallbackUrlSchemeValidator.getCallbackUrlScheme(givenAuthorizationRequest("tbmobile"))).isEqualTo("tbmobile"); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testForgedSchemeFromAuthorizationRequestIsIgnored() { |
||||
|
assertThat(CallbackUrlSchemeValidator.getCallbackUrlScheme(givenAuthorizationRequest("https://evil.com"))).isNull(); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testAuthorizationRequestWithoutScheme() { |
||||
|
assertThat(CallbackUrlSchemeValidator.getCallbackUrlScheme(givenAuthorizationRequest(null))).isNull(); |
||||
|
assertThat(CallbackUrlSchemeValidator.getCallbackUrlScheme(null)).isNull(); |
||||
|
} |
||||
|
|
||||
|
private OAuth2AuthorizationRequest givenAuthorizationRequest(String callbackUrlScheme) { |
||||
|
OAuth2AuthorizationRequest.Builder builder = OAuth2AuthorizationRequest.authorizationCode() |
||||
|
.authorizationUri("testUri").clientId("testId"); |
||||
|
if (callbackUrlScheme != null) { |
||||
|
builder.attributes(attributes -> attributes.put(TbOAuth2ParameterNames.CALLBACK_URL_SCHEME, callbackUrlScheme)); |
||||
|
} |
||||
|
return builder.build(); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,69 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2026 The Thingsboard Authors |
||||
|
* |
||||
|
* 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 org.thingsboard.server.service.security.auth.oauth2; |
||||
|
|
||||
|
import jakarta.servlet.http.Cookie; |
||||
|
import jakarta.servlet.http.HttpServletRequest; |
||||
|
import jakarta.servlet.http.HttpServletResponse; |
||||
|
import org.junit.jupiter.api.Test; |
||||
|
import org.junit.jupiter.params.ParameterizedTest; |
||||
|
import org.junit.jupiter.params.provider.NullAndEmptySource; |
||||
|
import org.junit.jupiter.params.provider.ValueSource; |
||||
|
import org.mockito.ArgumentCaptor; |
||||
|
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; |
||||
|
|
||||
|
import static org.assertj.core.api.Assertions.assertThat; |
||||
|
import static org.mockito.Mockito.atLeastOnce; |
||||
|
import static org.mockito.Mockito.mock; |
||||
|
import static org.mockito.Mockito.verify; |
||||
|
import static org.mockito.Mockito.when; |
||||
|
import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.PREV_URI_COOKIE_NAME; |
||||
|
import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.PREV_URI_PARAMETER; |
||||
|
|
||||
|
public class HttpCookieOAuth2AuthorizationRequestRepositoryTest { |
||||
|
|
||||
|
private final HttpCookieOAuth2AuthorizationRequestRepository repository = new HttpCookieOAuth2AuthorizationRequestRepository(); |
||||
|
|
||||
|
@Test |
||||
|
public void testPrevUriSavedForInAppPath() { |
||||
|
assertThat(savePrevUri("/dashboards/3fa13530-6597-11ed-bd76-8bd591f0ec3e?state=someState")) |
||||
|
.isEqualTo("/dashboards/3fa13530-6597-11ed-bd76-8bd591f0ec3e?state=someState"); |
||||
|
} |
||||
|
|
||||
|
@ParameterizedTest |
||||
|
@NullAndEmptySource |
||||
|
@ValueSource(strings = {"@evil.com/"}) |
||||
|
public void testPrevUriNotSavedForInvalidValue(String prevUri) { |
||||
|
assertThat(savePrevUri(prevUri)).isNull(); |
||||
|
} |
||||
|
|
||||
|
private String savePrevUri(String prevUri) { |
||||
|
HttpServletRequest request = mock(HttpServletRequest.class); |
||||
|
HttpServletResponse response = mock(HttpServletResponse.class); |
||||
|
when(request.getParameter(PREV_URI_PARAMETER)).thenReturn(prevUri); |
||||
|
|
||||
|
repository.saveAuthorizationRequest(OAuth2AuthorizationRequest.authorizationCode() |
||||
|
.authorizationUri("testUri").clientId("testId").build(), request, response); |
||||
|
|
||||
|
ArgumentCaptor<Cookie> cookieCaptor = ArgumentCaptor.forClass(Cookie.class); |
||||
|
verify(response, atLeastOnce()).addCookie(cookieCaptor.capture()); |
||||
|
return cookieCaptor.getAllValues().stream() |
||||
|
.filter(cookie -> PREV_URI_COOKIE_NAME.equals(cookie.getName())) |
||||
|
.map(Cookie::getValue) |
||||
|
.findAny().orElse(null); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,103 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2026 The Thingsboard Authors |
||||
|
* |
||||
|
* 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 org.thingsboard.server.service.security.auth.oauth2; |
||||
|
|
||||
|
import jakarta.servlet.http.HttpServletRequest; |
||||
|
import jakarta.servlet.http.HttpServletResponse; |
||||
|
import org.junit.jupiter.api.BeforeEach; |
||||
|
import org.junit.jupiter.api.Test; |
||||
|
import org.junit.jupiter.params.ParameterizedTest; |
||||
|
import org.junit.jupiter.params.provider.ValueSource; |
||||
|
import org.mockito.ArgumentCaptor; |
||||
|
import org.springframework.security.authentication.AuthenticationServiceException; |
||||
|
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; |
||||
|
import org.thingsboard.server.common.data.id.CustomerId; |
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
import org.thingsboard.server.service.security.system.SystemSecurityService; |
||||
|
|
||||
|
import static org.assertj.core.api.Assertions.assertThat; |
||||
|
import static org.mockito.ArgumentMatchers.any; |
||||
|
import static org.mockito.ArgumentMatchers.anyString; |
||||
|
import static org.mockito.Mockito.mock; |
||||
|
import static org.mockito.Mockito.verify; |
||||
|
import static org.mockito.Mockito.when; |
||||
|
|
||||
|
public class Oauth2AuthenticationFailureHandlerTest { |
||||
|
|
||||
|
private static final String BASE_URL = "https://thingsboard.example.com"; |
||||
|
|
||||
|
private final HttpCookieOAuth2AuthorizationRequestRepository authorizationRequestRepository = |
||||
|
mock(HttpCookieOAuth2AuthorizationRequestRepository.class); |
||||
|
private final SystemSecurityService systemSecurityService = mock(SystemSecurityService.class); |
||||
|
private final Oauth2AuthenticationFailureHandler failureHandler = |
||||
|
new Oauth2AuthenticationFailureHandler(authorizationRequestRepository, systemSecurityService); |
||||
|
|
||||
|
private HttpServletRequest request; |
||||
|
private HttpServletResponse response; |
||||
|
|
||||
|
@BeforeEach |
||||
|
public void before() { |
||||
|
request = mock(HttpServletRequest.class); |
||||
|
response = mock(HttpServletResponse.class); |
||||
|
when(request.getContextPath()).thenReturn(""); |
||||
|
when(response.encodeRedirectURL(anyString())).thenAnswer(invocation -> invocation.getArgument(0)); |
||||
|
when(systemSecurityService.getBaseUrl(any(TenantId.class), any(CustomerId.class), any(HttpServletRequest.class))).thenReturn(BASE_URL); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testErrorIsSentToMobileAppScheme() throws Exception { |
||||
|
givenCallbackUrlScheme("tbmobile"); |
||||
|
assertThat(sendFailure()).isEqualTo("tbmobile:/?error=someError"); |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* The scheme is restored from the oauth2_auth_request cookie, so a forged one must not turn the error redirect |
||||
|
* into a link to another host. |
||||
|
*/ |
||||
|
@ParameterizedTest |
||||
|
@ValueSource(strings = {"https://evil.com", "javascript"}) |
||||
|
public void testForgedCallbackUrlSchemeFallsBackToLoginPage(String callbackUrlScheme) throws Exception { |
||||
|
givenCallbackUrlScheme(callbackUrlScheme); |
||||
|
assertThat(sendFailure()).isEqualTo(BASE_URL + "/login?loginError=someError"); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testErrorIsSentToLoginPageWithoutCallbackUrlScheme() throws Exception { |
||||
|
givenCallbackUrlScheme(null); |
||||
|
assertThat(sendFailure()).isEqualTo(BASE_URL + "/login?loginError=someError"); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testErrorIsSentToLoginPageWithoutAuthorizationRequest() throws Exception { |
||||
|
assertThat(sendFailure()).isEqualTo(BASE_URL + "/login?loginError=someError"); |
||||
|
} |
||||
|
|
||||
|
private void givenCallbackUrlScheme(String callbackUrlScheme) { |
||||
|
when(authorizationRequestRepository.loadAuthorizationRequest(request)).thenReturn( |
||||
|
OAuth2AuthorizationRequest.authorizationCode().authorizationUri("testUri").clientId("testId") |
||||
|
.attributes(attributes -> attributes.put(TbOAuth2ParameterNames.CALLBACK_URL_SCHEME, callbackUrlScheme)) |
||||
|
.build()); |
||||
|
} |
||||
|
|
||||
|
private String sendFailure() throws Exception { |
||||
|
failureHandler.onAuthenticationFailure(request, response, new AuthenticationServiceException("someError")); |
||||
|
|
||||
|
ArgumentCaptor<String> redirectCaptor = ArgumentCaptor.forClass(String.class); |
||||
|
verify(response).sendRedirect(redirectCaptor.capture()); |
||||
|
return redirectCaptor.getValue(); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,74 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2026 The Thingsboard Authors |
||||
|
* |
||||
|
* 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 org.thingsboard.server.service.security.auth.oauth2; |
||||
|
|
||||
|
import org.junit.jupiter.api.Test; |
||||
|
import org.junit.jupiter.params.ParameterizedTest; |
||||
|
import org.junit.jupiter.params.provider.NullAndEmptySource; |
||||
|
import org.junit.jupiter.params.provider.ValueSource; |
||||
|
|
||||
|
import static org.assertj.core.api.Assertions.assertThat; |
||||
|
|
||||
|
public class PrevUriValidatorTest { |
||||
|
|
||||
|
@ParameterizedTest |
||||
|
@ValueSource(strings = { |
||||
|
"/", |
||||
|
"/login", |
||||
|
"/dashboards/3fa13530-6597-11ed-bd76-8bd591f0ec3e", |
||||
|
"/dashboards/3fa13530-6597-11ed-bd76-8bd591f0ec3e?state=someState&page=1", |
||||
|
"/settings/outgoing-mail", |
||||
|
"/some%20path?q=a+b", |
||||
|
"/dashboards/3fa13530-6597-11ed-bd76-8bd591f0ec3e?state=W3siaWQiOiJhL2IifV0%3D" |
||||
|
}) |
||||
|
public void testValidPrevUri(String prevUri) { |
||||
|
assertThat(PrevUriValidator.isValid(prevUri)).isTrue(); |
||||
|
} |
||||
|
|
||||
|
@ParameterizedTest |
||||
|
@NullAndEmptySource |
||||
|
@ValueSource(strings = { |
||||
|
"@evil.com/", |
||||
|
"evil.com", |
||||
|
"https://evil.com", |
||||
|
"//evil.com", |
||||
|
"/\\evil.com", |
||||
|
"/\tevil.com", |
||||
|
"/ evil.com", |
||||
|
"/dashboards\\..\\evil.com", |
||||
|
"/login\nLocation: https://evil.com", |
||||
|
"/login\r\nSet-Cookie: a=b", |
||||
|
"/dashboards//evil.com", |
||||
|
"/dashboards%2Fevil.com", |
||||
|
"/dashboards%5cevil.com", |
||||
|
"/dashboards;jsessionid=1", |
||||
|
"/dashboards?title=a,b", |
||||
|
"/dashboards,list", |
||||
|
"/dashboards\"list", |
||||
|
"/dashboards/3fa13530-6597-11ed-bd76-8bd591f0ec3e#fragment", |
||||
|
"/панель" |
||||
|
}) |
||||
|
public void testInvalidPrevUri(String prevUri) { |
||||
|
assertThat(PrevUriValidator.isValid(prevUri)).isFalse(); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testPrevUriLengthLimit() { |
||||
|
assertThat(PrevUriValidator.isValid("/" + "a".repeat(2047))).isTrue(); |
||||
|
assertThat(PrevUriValidator.isValid("/" + "a".repeat(2048))).isFalse(); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,72 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2026 The Thingsboard Authors |
||||
|
* |
||||
|
* 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 org.thingsboard.server.service.security.model.token; |
||||
|
|
||||
|
import io.jsonwebtoken.JwtBuilder; |
||||
|
import io.jsonwebtoken.Jwts; |
||||
|
import io.jsonwebtoken.security.Keys; |
||||
|
import org.junit.jupiter.api.Test; |
||||
|
|
||||
|
import javax.crypto.SecretKey; |
||||
|
import java.util.Base64; |
||||
|
import java.util.Date; |
||||
|
import java.util.concurrent.TimeUnit; |
||||
|
|
||||
|
import static org.assertj.core.api.Assertions.assertThat; |
||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy; |
||||
|
|
||||
|
public class OAuth2AppTokenFactoryTest { |
||||
|
|
||||
|
private static final String APP_PACKAGE = "org.thingsboard.demo.app"; |
||||
|
private static final byte[] KEY_BYTES = "yjNyylzT1TmiVE2jV3YTnUpZzwLLLdPDJKmhLNyXDPnLtVCLcJIjIGmDPKHNoDMK".getBytes(); |
||||
|
|
||||
|
private final OAuth2AppTokenFactory tokenFactory = new OAuth2AppTokenFactory(); |
||||
|
|
||||
|
@Test |
||||
|
public void testMobileAppSchemeIsAccepted() { |
||||
|
assertThat(validate(appToken("tb-mobile.app1", APP_PACKAGE))).isEqualTo("tb-mobile.app1"); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testInvalidCallbackUrlSchemeIsRejected() { |
||||
|
assertThatThrownBy(() -> validate(appToken("https://evil.com", APP_PACKAGE))) |
||||
|
.isInstanceOf(IllegalArgumentException.class) |
||||
|
.hasMessageContaining("callbackUrlScheme"); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
public void testTokenWithoutIssuerIsRejected() { |
||||
|
assertThatThrownBy(() -> validate(appToken("tbmobile", null))) |
||||
|
.isInstanceOf(IllegalArgumentException.class) |
||||
|
.hasMessageContaining("issuer"); |
||||
|
} |
||||
|
|
||||
|
private String appToken(String callbackUrlScheme, String issuer) { |
||||
|
JwtBuilder builder = Jwts.builder() |
||||
|
.expiration(new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(1))) |
||||
|
.claim("callbackUrlScheme", callbackUrlScheme); |
||||
|
if (issuer != null) { |
||||
|
builder.issuer(issuer); |
||||
|
} |
||||
|
SecretKey key = Keys.hmacShaKeyFor(KEY_BYTES); |
||||
|
return builder.signWith(key).compact(); |
||||
|
} |
||||
|
|
||||
|
private String validate(String appToken) { |
||||
|
return tokenFactory.validateTokenAndGetCallbackUrlScheme(APP_PACKAGE, appToken, Base64.getEncoder().encodeToString(KEY_BYTES)); |
||||
|
} |
||||
|
|
||||
|
} |
||||
Loading…
Reference in new issue