chore(oidc): backfill + add mobile redirect URI whitelist setting to the backend (#1268)
This commit is contained in:
@@ -26,6 +26,8 @@ import jakarta.servlet.http.HttpServletRequest;
|
|||||||
|
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.text.ParseException;
|
import java.text.ParseException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.ConcurrentMap;
|
import java.util.concurrent.ConcurrentMap;
|
||||||
@@ -37,7 +39,10 @@ import java.util.regex.Pattern;
|
|||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public class OidcAuthService {
|
public class OidcAuthService {
|
||||||
|
|
||||||
private static final String MOBILE_SCHEME = "booklore://";
|
private static final String DEFAULT_MOBILE_REDIRECT_URI = "grimmory://oauth2-callback";
|
||||||
|
// TODO(grimmory-cleanup): Remove after the Booklore to Grimmory migration window closes.
|
||||||
|
private static final String LEGACY_MOBILE_REDIRECT_URI = "booklore://oauth2-callback";
|
||||||
|
private static final String WILDCARD_REDIRECT_URI = "*";
|
||||||
private static final String OAUTH2_CALLBACK_PATH = "/oauth2-callback";
|
private static final String OAUTH2_CALLBACK_PATH = "/oauth2-callback";
|
||||||
private static final Pattern TRAILING_SLASH_PATTERN = Pattern.compile("/+$");
|
private static final Pattern TRAILING_SLASH_PATTERN = Pattern.compile("/+$");
|
||||||
|
|
||||||
@@ -123,8 +128,8 @@ public class OidcAuthService {
|
|||||||
throw ApiError.OIDC_INVALID_REDIRECT_URI.createException();
|
throw ApiError.OIDC_INVALID_REDIRECT_URI.createException();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (redirectUri.startsWith(MOBILE_SCHEME)) {
|
if (isMobileRedirectUri(redirectUri)) {
|
||||||
if (!redirectUri.equals(MOBILE_SCHEME + "oauth2-callback")) {
|
if (!isAllowedMobileRedirectUri(redirectUri)) {
|
||||||
throw ApiError.OIDC_INVALID_REDIRECT_URI.createException();
|
throw ApiError.OIDC_INVALID_REDIRECT_URI.createException();
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
@@ -168,11 +173,48 @@ public class OidcAuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void validateAppRedirectUri(String appRedirectUri) {
|
public void validateAppRedirectUri(String appRedirectUri) {
|
||||||
if (appRedirectUri == null || !appRedirectUri.startsWith(MOBILE_SCHEME)) {
|
if (!isMobileRedirectUri(appRedirectUri) || !isAllowedMobileRedirectUri(appRedirectUri)) {
|
||||||
throw ApiError.OIDC_INVALID_REDIRECT_URI.createException();
|
throw ApiError.OIDC_INVALID_REDIRECT_URI.createException();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean isAllowedMobileRedirectUri(String redirectUri) {
|
||||||
|
List<String> effectiveRedirectUris = getEffectiveMobileRedirectUris();
|
||||||
|
return effectiveRedirectUris.contains(WILDCARD_REDIRECT_URI) || effectiveRedirectUris.contains(redirectUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> getEffectiveMobileRedirectUris() {
|
||||||
|
List<String> configuredRedirectUris = appSettingService.getAppSettings().getOidcRedirectUris();
|
||||||
|
List<String> effectiveRedirectUris = configuredRedirectUris == null || configuredRedirectUris.isEmpty()
|
||||||
|
? new ArrayList<>(List.of(DEFAULT_MOBILE_REDIRECT_URI))
|
||||||
|
: new ArrayList<>(configuredRedirectUris);
|
||||||
|
|
||||||
|
if (effectiveRedirectUris.contains(DEFAULT_MOBILE_REDIRECT_URI)
|
||||||
|
&& !effectiveRedirectUris.contains(LEGACY_MOBILE_REDIRECT_URI)) {
|
||||||
|
effectiveRedirectUris.add(LEGACY_MOBILE_REDIRECT_URI);
|
||||||
|
}
|
||||||
|
|
||||||
|
return effectiveRedirectUris;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isMobileRedirectUri(String redirectUri) {
|
||||||
|
if (redirectUri == null || redirectUri.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
URI uri = URI.create(redirectUri);
|
||||||
|
String scheme = uri.getScheme();
|
||||||
|
return scheme != null
|
||||||
|
&& !scheme.isBlank()
|
||||||
|
&& !"http".equalsIgnoreCase(scheme)
|
||||||
|
&& !"https".equalsIgnoreCase(scheme)
|
||||||
|
&& uri.getFragment() == null;
|
||||||
|
} catch (IllegalArgumentException _) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void persistOidcSession(BookLoreUserEntity user, String subject, String issuer,
|
private void persistOidcSession(BookLoreUserEntity user, String subject, String issuer,
|
||||||
OidcTokenClient.TokenResponse tokenResponse, String rawIdToken,
|
OidcTokenClient.TokenResponse tokenResponse, String rawIdToken,
|
||||||
JWTClaimsSet claims) {
|
JWTClaimsSet claims) {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ public enum AppSettingKey {
|
|||||||
// @formatter:off
|
// @formatter:off
|
||||||
// ADMIN only (public settings)
|
// ADMIN only (public settings)
|
||||||
OIDC_PROVIDER_DETAILS ("oidc_provider_details", true, true, List.of(PermissionType.ADMIN)),
|
OIDC_PROVIDER_DETAILS ("oidc_provider_details", true, true, List.of(PermissionType.ADMIN)),
|
||||||
|
OIDC_REDIRECT_URIS ("oidc_redirect_uris", true, false, List.of(PermissionType.ADMIN)),
|
||||||
OIDC_ENABLED ("oidc_enabled", false, true, List.of(PermissionType.ADMIN)),
|
OIDC_ENABLED ("oidc_enabled", false, true, List.of(PermissionType.ADMIN)),
|
||||||
OIDC_AUTO_PROVISION_DETAILS ("oidc_auto_provision_details", true, false, List.of(PermissionType.ADMIN)),
|
OIDC_AUTO_PROVISION_DETAILS ("oidc_auto_provision_details", true, false, List.of(PermissionType.ADMIN)),
|
||||||
OIDC_SESSION_DURATION_HOURS ("oidc_session_duration_hours", false, false, List.of(PermissionType.ADMIN)),
|
OIDC_SESSION_DURATION_HOURS ("oidc_session_duration_hours", false, false, List.of(PermissionType.ADMIN)),
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ public class AppSettings {
|
|||||||
private boolean metadataDownloadOnBookdrop;
|
private boolean metadataDownloadOnBookdrop;
|
||||||
private boolean oidcEnabled;
|
private boolean oidcEnabled;
|
||||||
private OidcProviderDetails oidcProviderDetails;
|
private OidcProviderDetails oidcProviderDetails;
|
||||||
|
private List<String> oidcRedirectUris;
|
||||||
private OidcAutoProvisionDetails oidcAutoProvisionDetails;
|
private OidcAutoProvisionDetails oidcAutoProvisionDetails;
|
||||||
private MetadataProviderSettings metadataProviderSettings;
|
private MetadataProviderSettings metadataProviderSettings;
|
||||||
private MetadataMatchWeights metadataMatchWeights;
|
private MetadataMatchWeights metadataMatchWeights;
|
||||||
|
|||||||
@@ -22,13 +22,18 @@ import org.springframework.stereotype.Service;
|
|||||||
import tools.jackson.core.JacksonException;
|
import tools.jackson.core.JacksonException;
|
||||||
import tools.jackson.core.type.TypeReference;
|
import tools.jackson.core.type.TypeReference;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@DependsOnDatabaseInitialization
|
@DependsOnDatabaseInitialization
|
||||||
public class AppSettingService {
|
public class AppSettingService {
|
||||||
|
private static final String DEFAULT_MOBILE_REDIRECT_URI = "grimmory://oauth2-callback";
|
||||||
|
private static final String WILDCARD_REDIRECT_URI = "*";
|
||||||
|
|
||||||
private final AppProperties appProperties;
|
private final AppProperties appProperties;
|
||||||
private final SettingPersistenceHelper settingPersistenceHelper;
|
private final SettingPersistenceHelper settingPersistenceHelper;
|
||||||
@@ -57,6 +62,10 @@ public class AppSettingService {
|
|||||||
|
|
||||||
validatePermission(key, user);
|
validatePermission(key, user);
|
||||||
|
|
||||||
|
if (key == AppSettingKey.OIDC_REDIRECT_URIS) {
|
||||||
|
val = validateAndNormalizeOidcRedirectUris(val);
|
||||||
|
}
|
||||||
|
|
||||||
if (key == AppSettingKey.OIDC_FORCE_ONLY_MODE) {
|
if (key == AppSettingKey.OIDC_FORCE_ONLY_MODE) {
|
||||||
validateOidcForceOnlyMode(val);
|
validateOidcForceOnlyMode(val);
|
||||||
}
|
}
|
||||||
@@ -107,6 +116,64 @@ public class AppSettingService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private List<String> validateAndNormalizeOidcRedirectUris(Object val) {
|
||||||
|
if (val == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
if (!(val instanceof List<?> rawValues)) {
|
||||||
|
throw ApiError.GENERIC_BAD_REQUEST.createException("OIDC redirect URIs must be an array");
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> redirectUris = rawValues.stream()
|
||||||
|
.map(value -> {
|
||||||
|
if (value == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!(value instanceof String stringValue)) {
|
||||||
|
throw ApiError.GENERIC_BAD_REQUEST.createException("OIDC redirect URIs must be an array of strings");
|
||||||
|
}
|
||||||
|
return stringValue.trim();
|
||||||
|
})
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
if (redirectUris.contains(WILDCARD_REDIRECT_URI) && redirectUris.size() > 1) {
|
||||||
|
throw ApiError.GENERIC_BAD_REQUEST.createException("Wildcard redirect URI must be the only value");
|
||||||
|
}
|
||||||
|
|
||||||
|
Set<String> uniqueUris = new LinkedHashSet<>();
|
||||||
|
for (String redirectUri : redirectUris) {
|
||||||
|
if (redirectUri == null || redirectUri.isBlank()) {
|
||||||
|
throw ApiError.GENERIC_BAD_REQUEST.createException("Redirect URI cannot be blank");
|
||||||
|
}
|
||||||
|
if (!WILDCARD_REDIRECT_URI.equals(redirectUri)) {
|
||||||
|
validateMobileRedirectUriShape(redirectUri);
|
||||||
|
}
|
||||||
|
if (!uniqueUris.add(redirectUri)) {
|
||||||
|
throw ApiError.GENERIC_BAD_REQUEST.createException("Duplicate redirect URI: " + redirectUri);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return List.copyOf(uniqueUris);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateMobileRedirectUriShape(String redirectUri) {
|
||||||
|
try {
|
||||||
|
URI uri = URI.create(redirectUri);
|
||||||
|
String scheme = uri.getScheme();
|
||||||
|
if (scheme == null || scheme.isBlank()) {
|
||||||
|
throw ApiError.GENERIC_BAD_REQUEST.createException("Redirect URI must include a scheme");
|
||||||
|
}
|
||||||
|
if ("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme)) {
|
||||||
|
throw ApiError.GENERIC_BAD_REQUEST.createException("Redirect URI must use a custom mobile scheme");
|
||||||
|
}
|
||||||
|
if (uri.getFragment() != null) {
|
||||||
|
throw ApiError.GENERIC_BAD_REQUEST.createException("Redirect URI must not contain a fragment");
|
||||||
|
}
|
||||||
|
} catch (IllegalArgumentException _) {
|
||||||
|
throw ApiError.GENERIC_BAD_REQUEST.createException("Redirect URI is not a valid URI: " + redirectUri);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Cacheable("publicSettings")
|
@Cacheable("publicSettings")
|
||||||
public PublicAppSetting getPublicSettings() {
|
public PublicAppSetting getPublicSettings() {
|
||||||
return buildPublicSetting();
|
return buildPublicSetting();
|
||||||
@@ -144,6 +211,8 @@ public class AppSettingService {
|
|||||||
builder.libraryMetadataRefreshOptions(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.LIBRARY_METADATA_REFRESH_OPTIONS, new TypeReference<>() {
|
builder.libraryMetadataRefreshOptions(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.LIBRARY_METADATA_REFRESH_OPTIONS, new TypeReference<>() {
|
||||||
}, List.of(), true));
|
}, List.of(), true));
|
||||||
builder.oidcProviderDetails(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.OIDC_PROVIDER_DETAILS, OidcProviderDetails.class, null, false));
|
builder.oidcProviderDetails(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.OIDC_PROVIDER_DETAILS, OidcProviderDetails.class, null, false));
|
||||||
|
builder.oidcRedirectUris(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.OIDC_REDIRECT_URIS, new TypeReference<>() {
|
||||||
|
}, List.of(DEFAULT_MOBILE_REDIRECT_URI), true));
|
||||||
builder.oidcAutoProvisionDetails(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.OIDC_AUTO_PROVISION_DETAILS, OidcAutoProvisionDetails.class, new OidcAutoProvisionDetails(), true));
|
builder.oidcAutoProvisionDetails(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.OIDC_AUTO_PROVISION_DETAILS, OidcAutoProvisionDetails.class, new OidcAutoProvisionDetails(), true));
|
||||||
builder.metadataProviderSettings(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_PROVIDER_SETTINGS, MetadataProviderSettings.class, settingPersistenceHelper.getDefaultMetadataProviderSettings(), true));
|
builder.metadataProviderSettings(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_PROVIDER_SETTINGS, MetadataProviderSettings.class, settingPersistenceHelper.getDefaultMetadataProviderSettings(), true));
|
||||||
builder.metadataMatchWeights(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_MATCH_WEIGHTS, MetadataMatchWeights.class, settingPersistenceHelper.getDefaultMetadataMatchWeights(), true));
|
builder.metadataMatchWeights(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_MATCH_WEIGHTS, MetadataMatchWeights.class, settingPersistenceHelper.getDefaultMetadataMatchWeights(), true));
|
||||||
|
|||||||
@@ -245,8 +245,21 @@ class OidcAuthServiceTest {
|
|||||||
// --- validateAppRedirectUri ---
|
// --- validateAppRedirectUri ---
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void validateAppRedirectUri_validMobileRedirect() {
|
void validateAppRedirectUri_allowsConfiguredMobileRedirect() {
|
||||||
oidcAuthService.validateAppRedirectUri("booklore://some-path");
|
var settings = enabledSettings();
|
||||||
|
settings.setOidcRedirectUris(List.of("grimmory://auth/return"));
|
||||||
|
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||||
|
|
||||||
|
oidcAuthService.validateAppRedirectUri("grimmory://auth/return");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateAppRedirectUri_allowsDerivedLegacyCallbackWhenDefaultGrimmoryCallbackIsConfigured() {
|
||||||
|
var settings = enabledSettings();
|
||||||
|
settings.setOidcRedirectUris(List.of("grimmory://oauth2-callback"));
|
||||||
|
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||||
|
|
||||||
|
oidcAuthService.validateAppRedirectUri("booklore://oauth2-callback");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -261,6 +274,16 @@ class OidcAuthServiceTest {
|
|||||||
.isInstanceOf(APIException.class);
|
.isInstanceOf(APIException.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateAppRedirectUri_unlistedCustomSchemeThrows() {
|
||||||
|
var settings = enabledSettings();
|
||||||
|
settings.setOidcRedirectUris(List.of("grimmory://oauth2-callback"));
|
||||||
|
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> oidcAuthService.validateAppRedirectUri("evil://oauth2-callback"))
|
||||||
|
.isInstanceOf(APIException.class);
|
||||||
|
}
|
||||||
|
|
||||||
// --- findOrProvisionUser (indirect) ---
|
// --- findOrProvisionUser (indirect) ---
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -539,6 +562,64 @@ class OidcAuthServiceTest {
|
|||||||
assertThat(result.getStatusCode().value()).isEqualTo(200);
|
assertThat(result.getStatusCode().value()).isEqualTo(200);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateRedirectUri_allowsDerivedBookloreCallbackWhenGrimmoryCallbackIsConfigured() {
|
||||||
|
var settings = enabledSettings();
|
||||||
|
settings.setOidcRedirectUris(List.of("grimmory://oauth2-callback"));
|
||||||
|
var tokenResponse = tokenResponse(null, "id-token");
|
||||||
|
var claims = new JWTClaimsSet.Builder().subject("sub-123").build();
|
||||||
|
var userClaims = userClaims("jdoe", "sub-123");
|
||||||
|
var user = existingOidcUser("jdoe", "sub-123");
|
||||||
|
|
||||||
|
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||||
|
when(oidcTokenClient.exchangeAuthorizationCode(eq(CODE), eq(CODE_VERIFIER), eq("booklore://oauth2-callback"), any()))
|
||||||
|
.thenReturn(tokenResponse);
|
||||||
|
when(oidcTokenValidator.validateIdToken("id-token", ISSUER_URI, CLIENT_ID, NONCE, null))
|
||||||
|
.thenReturn(claims);
|
||||||
|
when(oidcClaimExtractor.extractClaims(eq(claims), any(), eq(Map.of()))).thenReturn(userClaims);
|
||||||
|
when(userRepository.findByOidcIssuerAndOidcSubject(ISSUER_URI, "sub-123")).thenReturn(Optional.of(user));
|
||||||
|
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn(null);
|
||||||
|
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
|
||||||
|
|
||||||
|
var result = oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, "booklore://oauth2-callback", NONCE, mockRequest());
|
||||||
|
|
||||||
|
assertThat(result.getStatusCode().value()).isEqualTo(200);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateRedirectUri_rejectsUnlistedCustomMobileRedirect() {
|
||||||
|
var settings = enabledSettings();
|
||||||
|
settings.setOidcRedirectUris(List.of("grimmory://oauth2-callback"));
|
||||||
|
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, "grimmory://some-other-path", NONCE, mockRequest()))
|
||||||
|
.isInstanceOf(APIException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateRedirectUri_allowsAnyConfiguredWildcardMobileRedirect() {
|
||||||
|
var settings = enabledSettings();
|
||||||
|
settings.setOidcRedirectUris(List.of("*"));
|
||||||
|
var tokenResponse = tokenResponse(null, "id-token");
|
||||||
|
var claims = new JWTClaimsSet.Builder().subject("sub-123").build();
|
||||||
|
var userClaims = userClaims("jdoe", "sub-123");
|
||||||
|
var user = existingOidcUser("jdoe", "sub-123");
|
||||||
|
|
||||||
|
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||||
|
when(oidcTokenClient.exchangeAuthorizationCode(eq(CODE), eq(CODE_VERIFIER), eq("grimmory://some-other-path"), any()))
|
||||||
|
.thenReturn(tokenResponse);
|
||||||
|
when(oidcTokenValidator.validateIdToken("id-token", ISSUER_URI, CLIENT_ID, NONCE, null))
|
||||||
|
.thenReturn(claims);
|
||||||
|
when(oidcClaimExtractor.extractClaims(eq(claims), any(), eq(Map.of()))).thenReturn(userClaims);
|
||||||
|
when(userRepository.findByOidcIssuerAndOidcSubject(ISSUER_URI, "sub-123")).thenReturn(Optional.of(user));
|
||||||
|
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn(null);
|
||||||
|
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
|
||||||
|
|
||||||
|
var result = oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, "grimmory://some-other-path", NONCE, mockRequest());
|
||||||
|
|
||||||
|
assertThat(result.getStatusCode().value()).isEqualTo(200);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void validateRedirectUri_invalidMobileRedirectThrows() {
|
void validateRedirectUri_invalidMobileRedirectThrows() {
|
||||||
var settings = enabledSettings();
|
var settings = enabledSettings();
|
||||||
|
|||||||
@@ -0,0 +1,168 @@
|
|||||||
|
package org.booklore.service.appsettings;
|
||||||
|
|
||||||
|
import org.booklore.config.AppProperties;
|
||||||
|
import org.booklore.config.security.service.AuthenticationService;
|
||||||
|
import org.booklore.model.dto.BookLoreUser;
|
||||||
|
import org.booklore.model.dto.settings.AppSettingKey;
|
||||||
|
import org.booklore.model.entity.AppSettingEntity;
|
||||||
|
import org.booklore.model.enums.AuditAction;
|
||||||
|
import org.booklore.repository.AppSettingsRepository;
|
||||||
|
import org.booklore.service.audit.AuditService;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import tools.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class AppSettingServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private AppProperties appProperties;
|
||||||
|
@Mock
|
||||||
|
private AuthenticationService authenticationService;
|
||||||
|
@Mock
|
||||||
|
private AuditService auditService;
|
||||||
|
@Mock
|
||||||
|
private AppSettingsRepository appSettingsRepository;
|
||||||
|
|
||||||
|
private SettingPersistenceHelper settingPersistenceHelper;
|
||||||
|
|
||||||
|
private AppSettingService appSettingService;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
settingPersistenceHelper = new SettingPersistenceHelper(appSettingsRepository, new ObjectMapper());
|
||||||
|
appSettingService = new AppSettingService(appProperties, settingPersistenceHelper, authenticationService, auditService);
|
||||||
|
|
||||||
|
var permissions = new BookLoreUser.UserPermissions();
|
||||||
|
permissions.setAdmin(true);
|
||||||
|
BookLoreUser user = BookLoreUser.builder()
|
||||||
|
.id(1L)
|
||||||
|
.username("admin")
|
||||||
|
.permissions(permissions)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateSetting_acceptsValidOidcRedirectUris() throws Exception {
|
||||||
|
appSettingService.updateSetting(
|
||||||
|
AppSettingKey.OIDC_REDIRECT_URIS,
|
||||||
|
List.of("grimmory://oauth2-callback", "grimmory://auth/return")
|
||||||
|
);
|
||||||
|
|
||||||
|
ArgumentCaptor<AppSettingEntity> settingCaptor = ArgumentCaptor.forClass(AppSettingEntity.class);
|
||||||
|
verify(appSettingsRepository).save(settingCaptor.capture());
|
||||||
|
|
||||||
|
AppSettingEntity savedSetting = settingCaptor.getValue();
|
||||||
|
assertThat(savedSetting.getName()).isEqualTo(AppSettingKey.OIDC_REDIRECT_URIS.toString());
|
||||||
|
assertThat(savedSetting.getVal()).isEqualTo("[\"grimmory://oauth2-callback\",\"grimmory://auth/return\"]");
|
||||||
|
verify(auditService).log(AuditAction.OIDC_CONFIG_CHANGED, "Updated setting: " + AppSettingKey.OIDC_REDIRECT_URIS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateSetting_acceptsWildcardOidcRedirectUri() throws Exception {
|
||||||
|
appSettingService.updateSetting(
|
||||||
|
AppSettingKey.OIDC_REDIRECT_URIS,
|
||||||
|
List.of("*")
|
||||||
|
);
|
||||||
|
|
||||||
|
ArgumentCaptor<AppSettingEntity> settingCaptor = ArgumentCaptor.forClass(AppSettingEntity.class);
|
||||||
|
verify(appSettingsRepository).save(settingCaptor.capture());
|
||||||
|
|
||||||
|
AppSettingEntity savedSetting = settingCaptor.getValue();
|
||||||
|
assertThat(savedSetting.getName()).isEqualTo(AppSettingKey.OIDC_REDIRECT_URIS.toString());
|
||||||
|
assertThat(savedSetting.getVal()).isEqualTo("[\"*\"]");
|
||||||
|
verify(auditService).log(AuditAction.OIDC_CONFIG_CHANGED, "Updated setting: " + AppSettingKey.OIDC_REDIRECT_URIS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateSetting_rejectsWildcardCombinedWithOtherUris() {
|
||||||
|
assertThatThrownBy(() -> appSettingService.updateSetting(
|
||||||
|
AppSettingKey.OIDC_REDIRECT_URIS,
|
||||||
|
List.of("*", "grimmory://oauth2-callback")
|
||||||
|
))
|
||||||
|
.hasMessageContaining("Wildcard redirect URI must be the only value");
|
||||||
|
|
||||||
|
verify(appSettingsRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateSetting_rejectsBlankOidcMobileRedirectUri() {
|
||||||
|
assertThatThrownBy(() -> appSettingService.updateSetting(
|
||||||
|
AppSettingKey.OIDC_REDIRECT_URIS,
|
||||||
|
List.of(" ")
|
||||||
|
))
|
||||||
|
.hasMessageContaining("Redirect URI cannot be blank");
|
||||||
|
|
||||||
|
verify(appSettingsRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateSetting_rejectsNonStringOidcMobileRedirectUriEntries() {
|
||||||
|
assertThatThrownBy(() -> appSettingService.updateSetting(
|
||||||
|
AppSettingKey.OIDC_REDIRECT_URIS,
|
||||||
|
List.of(42)
|
||||||
|
))
|
||||||
|
.hasMessageContaining("OIDC redirect URIs must be an array of strings");
|
||||||
|
|
||||||
|
verify(appSettingsRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateSetting_rejectsDuplicateOidcMobileRedirectUris() {
|
||||||
|
assertThatThrownBy(() -> appSettingService.updateSetting(
|
||||||
|
AppSettingKey.OIDC_REDIRECT_URIS,
|
||||||
|
List.of("grimmory://oauth2-callback", "grimmory://oauth2-callback")
|
||||||
|
))
|
||||||
|
.hasMessageContaining("Duplicate redirect URI");
|
||||||
|
|
||||||
|
verify(appSettingsRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateSetting_rejectsHttpRedirectUri() {
|
||||||
|
assertThatThrownBy(() -> appSettingService.updateSetting(
|
||||||
|
AppSettingKey.OIDC_REDIRECT_URIS,
|
||||||
|
List.of("https://example.com/oauth2-callback")
|
||||||
|
))
|
||||||
|
.hasMessageContaining("Redirect URI must use a custom mobile scheme");
|
||||||
|
|
||||||
|
verify(appSettingsRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateSetting_rejectsRedirectUriWithFragment() {
|
||||||
|
assertThatThrownBy(() -> appSettingService.updateSetting(
|
||||||
|
AppSettingKey.OIDC_REDIRECT_URIS,
|
||||||
|
List.of("grimmory://oauth2-callback#done")
|
||||||
|
))
|
||||||
|
.hasMessageContaining("Redirect URI must not contain a fragment");
|
||||||
|
|
||||||
|
verify(appSettingsRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateSetting_rejectsRedirectUriWithoutScheme() {
|
||||||
|
assertThatThrownBy(() -> appSettingService.updateSetting(
|
||||||
|
AppSettingKey.OIDC_REDIRECT_URIS,
|
||||||
|
List.of("oauth2-callback")
|
||||||
|
))
|
||||||
|
.hasMessageContaining("Redirect URI must include a scheme");
|
||||||
|
|
||||||
|
verify(appSettingsRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user