Skip to content
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Copyright (c) 2004-2026, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.user.authz;

/**
* Shared constants for UserDetails soft-refresh.
*
* @author Morten Svanæs
*/
public final class AuthzConstants {

/** HttpSession attribute holding the effective authz generation of the session principal. */
public static final String SESSION_AUTHZ_GEN_ATTR = "DHIS2_AUTHZ_GEN";

private AuthzConstants() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright (c) 2004-2026, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.user.authz;

import java.util.Collection;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.hisp.dhis.user.UserDetails;

/**
* Shared authz freshness service for form/OIDC sessions, JWT, and PAT.
*
* <p>Keeps {@link UserDetails} immutable: callers rebuild snapshots when generation stamps change.
*
* @author Morten Svanæs
*/
public interface AuthzService {

long currentUserGen(@Nonnull String username);

long currentRoleGen(@Nonnull String roleUid);

/**
* Effective generation for a principal:
* {@code max(userGen, max(roleGen for each role id on the principal))}.
*/
long effectiveGen(@Nonnull UserDetails principal);

long bumpUserAuthz(@Nonnull String username);

long bumpRoleAuthz(@Nonnull String roleUid);

void bumpUsers(@Nonnull Collection<String> usernames);

@CheckForNull
UserDetails loadFreshUserDetails(@Nonnull String username);

/**
* Returns {@code current} if still fresh, otherwise a newly built immutable {@link UserDetails}.
*/
@Nonnull
UserDetails ensureFresh(@Nonnull UserDetails current);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright (c) 2004-2026, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.user.authz;

import java.util.Collection;
import javax.annotation.Nonnull;

/**
* Stores dual generation stamps used for soft-refresh of immutable {@code UserDetails}.
*
* <p>Missing keys are treated as generation {@code 0}. Implementations must be safe for concurrent
* bumps.
*
* @author Morten Svanæs
*/
public interface AuthzVersionStore {

long getUserGen(@Nonnull String username);

long getRoleGen(@Nonnull String roleUid);

/** Atomically increments and returns the new user generation. */
long bumpUserGen(@Nonnull String username);

/** Atomically increments and returns the new role generation. */
long bumpRoleGen(@Nonnull String roleUid);

/** Bumps each username once. Order is not significant. */
void bumpUserGens(@Nonnull Collection<String> usernames);
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import org.hisp.dhis.security.oidc.DhisOidcProviderRepository;
import org.hisp.dhis.user.UserDetails;
import org.hisp.dhis.user.UserService;
import org.hisp.dhis.user.authz.AuthzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AuthenticationManager;
Expand Down Expand Up @@ -109,6 +110,7 @@ public class Dhis2JwtAuthenticationManagerResolver
@Autowired private DhisOidcProviderRepository clientRegistrationRepository;
@Autowired private Dhis2OAuth2ClientService oAuth2ClientService;
@Autowired private UserService userService;
@Autowired private AuthzService authzService;

private final Map<String, AuthenticationManager> authenticationManagers =
new ConcurrentHashMap<>();
Expand Down Expand Up @@ -218,7 +220,10 @@ private Converter<Jwt, DhisJwtAuthenticationToken> getTokenConverter(
String mappingValue = jwt.getClaim(mappingClaimKey);
UserDetails currentUserDetails =
switch (mappingClaimKey) {
case "username" -> userService.createUserDetailsByUsername(mappingValue);
case "username" -> {
UserDetails loaded = authzService.loadFreshUserDetails(mappingValue);
yield loaded != null ? loaded : userService.createUserDetailsByUsername(mappingValue);
}
case "email" -> userService.createUserDetailsByOpenId(mappingValue);
default -> throw new InvalidBearerTokenException("Invalid mapping claim");
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import org.hisp.dhis.common.UID;
import org.hisp.dhis.security.Authorities;
import org.hisp.dhis.security.acl.AclService;
import org.hisp.dhis.user.authz.AuthzService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -53,19 +54,23 @@ public class DefaultUserGroupService implements UserGroupService {
private final AclService aclService;
private final HibernateCacheManager cacheManager;
private final Cache<String> userGroupNameCache;
private final AuthzService authzService;

public DefaultUserGroupService(
UserGroupStore userGroupStore,
AclService aclService,
HibernateCacheManager cacheManager,
CacheProvider cacheProvider) {
CacheProvider cacheProvider,
AuthzService authzService) {
checkNotNull(userGroupStore);
checkNotNull(aclService);
checkNotNull(cacheManager);
checkNotNull(authzService);

this.userGroupStore = userGroupStore;
this.aclService = aclService;
this.cacheManager = cacheManager;
this.authzService = authzService;

userGroupNameCache = cacheProvider.createUserGroupNameCache();
}
Expand Down Expand Up @@ -98,6 +103,12 @@ public void updateUserGroup(UserGroup userGroup) {

cacheManager.clearQueryCache();
aclService.invalidateCurrentUserGroupInfoCache();
// Soft-refresh members when group metadata/membership changes.
if (userGroup.getMembers() != null) {
userGroup.getMembers().stream()
.filter(u -> u != null && u.getUsername() != null)
.forEach(u -> authzService.bumpUserAuthz(u.getUsername()));
}
}

@Override
Expand Down Expand Up @@ -157,6 +168,9 @@ public void addUserToGroups(User user, Collection<String> uids, UserDetails curr
}
}
aclService.invalidateCurrentUserGroupInfoCache();
if (user.getUsername() != null) {
authzService.bumpUserAuthz(user.getUsername());
}
}

@Override
Expand Down Expand Up @@ -184,6 +198,9 @@ && canAddOrRemoveMember(userGroup, currentUser)
}

aclService.invalidateCurrentUserGroupInfoCache();
if (user.getUsername() != null) {
authzService.bumpUserAuthz(user.getUsername());
}
}

private Collection<UserGroup> getUserGroupsByUid(@Nonnull Collection<UID> uids) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* Copyright (c) 2004-2026, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.user.authz;

import lombok.extern.slf4j.Slf4j;
import org.hisp.dhis.condition.RedisDisabledCondition;
import org.hisp.dhis.condition.RedisEnabledCondition;
import org.hisp.dhis.external.conf.ConfigurationKey;
import org.hisp.dhis.external.conf.DhisConfigurationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;

/**
* Wires {@link AuthzVersionStore}: Redis when Redis is enabled (required for multi-node session
* deployments), JDBC otherwise.
*
* @author Morten Svanæs
*/
@Slf4j
@Configuration
public class AuthzVersionStoreConfig {

@Bean
@Conditional(RedisEnabledCondition.class)
public AuthzVersionStore redisAuthzVersionStore(
@Autowired(required = false) @Qualifier("stringRedisTemplate")
StringRedisTemplate stringRedisTemplate,
DhisConfigurationProvider config) {
if (stringRedisTemplate == null) {
// Fail closed: Redis sessions without a usable template must not silently go local-only.
throw new IllegalStateException(
"redis.enabled=true but stringRedisTemplate is unavailable; cannot start AuthzVersionStore");
}
if (!config.isEnabled(ConfigurationKey.REDIS_ENABLED)) {
throw new IllegalStateException("Redis AuthzVersionStore requires redis.enabled=true");
}
log.info("Using Redis AuthzVersionStore for UserDetails soft-refresh");
return new RedisAuthzVersionStore(stringRedisTemplate);
}

@Bean
@Conditional(RedisDisabledCondition.class)
public AuthzVersionStore jdbcAuthzVersionStore(JdbcTemplate jdbcTemplate) {
log.info("Using JDBC AuthzVersionStore for UserDetails soft-refresh (Redis disabled)");
return new JdbcAuthzVersionStore(jdbcTemplate);
}
}
Loading
Loading