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
Expand Up @@ -96,6 +96,8 @@ public interface CacheProvider {

<V> Cache<V> createApiKeyCache();

<V> Cache<V> createUserDetailsAuthzCache();

<V> Cache<V> createTeAttributesCache();

<V> Cache<V> createProgramTeAttributesCache();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,5 +68,6 @@ public enum Region {
dataIntegrityDetailsCache,
queryAliasCache,
corsWhitelistCache,
notificationTemplateCache
notificationTemplateCache,
userDetailsAuthzCache
}
17 changes: 17 additions & 0 deletions dhis-2/dhis-api/src/main/java/org/hisp/dhis/user/UserDetails.java
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,23 @@ static UserDetails createUserDetails(
@Nonnull
Set<String> getUserRoleIds();

/**
* Soft-refresh stamp: global authz epoch read before this snapshot was built. 0 = unknown; the
* next soft-refresh check verifies the generation and re-stamps or rebuilds. Only {@link
* UserDetailsImpl} carries real stamps.
*/
default long getAuthzCheckedEpoch() {
return 0L;
}

/**
* Soft-refresh stamp: effective authz generation (max of user and role gens) this snapshot
* reflects. 0 = unknown, which fails safe (extra refresh, never stale).
*/
default long getAuthzGen() {
return 0L;
}

boolean canModifyUser(User userToModify);

boolean isExternalAuth();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,20 @@
import org.springframework.security.core.GrantedAuthority;

@Getter
@Builder
@Builder(toBuilder = true)
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Slf4j
public class UserDetailsImpl implements UserDetails {

/**
* Pinned to the pre-stamp shape of this class (release that introduced soft-refresh). Sessions
* serialized by earlier code then deserialize cleanly with {@code authzCheckedEpoch} and {@code
* authzGen} defaulting to 0, which the soft-refresh check treats as "unknown": one refresh on the
* next request instead of a failed deserialization and a forced re-login. Do NOT let this value
* drift; guarded by {@code UserDetailsImplSerializationTest}.
*/
private static final long serialVersionUID = -6804263748578733471L;

private final String uid;
@Setter private Long id;
private final String code;
Expand Down Expand Up @@ -78,6 +87,18 @@ public class UserDetailsImpl implements UserDetails {
@Nonnull private final Set<Long> managedGroupLongIds;
@Nonnull private final Set<Long> userRoleLongIds;

/**
* Soft-refresh stamp: global authz epoch read BEFORE this snapshot was built. 0 = unknown (e.g.
* login-built or deserialized from a pre-stamp release); the next check verifies the gen.
*/
private final long authzCheckedEpoch;

/**
* Soft-refresh stamp: effective authz generation (max of user and role gens) this snapshot
* reflects. 0 = unknown, which fails SAFE (one extra refresh, never stale).
*/
private final long authzGen;

@Override
public boolean canModifyUser(User other) {
if (other == null) {
Expand Down Expand Up @@ -125,4 +146,9 @@ public boolean isAuthorized(String auth) {
public boolean isAuthorized(@Nonnull Authorities auth) {
return isAuthorized(auth.toString());
}

/** Copy with new soft-refresh stamps; all data fields unchanged. */
public UserDetailsImpl withAuthzStamp(long checkedEpoch, long gen) {
return toBuilder().authzCheckedEpoch(checkedEpoch).authzGen(gen).build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* 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;

/**
* Soft-refresh facade over authz generation stamps and cached UserDetails snapshots.
*
* @author Morten Svanæs
*/
public interface AuthzService {

/**
* Epoch-validated, cached, immutable snapshot for username, stamped with the authz epoch read
* before the snapshot was built and the effective generation it reflects (see {@link
* UserDetails#getAuthzCheckedEpoch()}). Returns a snapshot that reflects every authz change
* committed up to the epoch value read at call entry. Null if user unknown.
*/
@CheckForNull
UserDetails getFreshUserDetails(@Nonnull String username);

/**
* Three-way freshness check against the principal's own authz stamp. Returns:
*
* <ul>
* <li>the same instance: stamp is current (or the user is unknown) — nothing to do;
* <li>a re-stamped copy: the epoch moved but this principal's generations did not — persist the
* copy so the next check takes the epoch fast path;
* <li>a rebuilt snapshot: this principal's generations moved — persist and use it.
* </ul>
*
* <p>Identity comparison with the argument tells the caller whether anything must be persisted.
*/
@Nonnull
UserDetails refreshIfStale(@Nonnull UserDetails principal);

void bumpUserAuthz(@Nonnull String userUid);

void bumpRoleAuthz(@Nonnull String roleUid);

void bumpUsers(@Nonnull Collection<String> userUids);
}
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;

/**
* Generation stamps that drive UserDetails soft-refresh.
*
* <p>Every bump advances the global epoch. Bumps participate in the caller's ambient transaction
* (JdbcTemplate joins it), so a reader can never observe a gen/epoch value without also seeing the
* committed data that caused it.
*
* @author Morten Svanæs
*/
public interface AuthzVersionStore {
/** Global epoch; advanced by every bump. Missing row = 0. */
long getEpoch();

/** max(user gen for userUid, role gens for roleUids); missing keys count as 0. */
long getMaxGen(@Nonnull String userUid, @Nonnull Collection<String> roleUids);

void bumpUserGen(@Nonnull String userUid);

void bumpRoleGen(@Nonnull String roleUid);

/** Bumps each distinct uid once and the epoch once. */
void bumpUserGens(@Nonnull Collection<String> userUids);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* 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;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;

import java.io.ObjectStreamClass;
import java.util.Set;
import org.junit.jupiter.api.Test;

/**
* Guards the session-compatibility contract of {@link UserDetailsImpl}: the serialVersionUID is
* pinned to the pre-authz-stamp shape of the class, so HTTP sessions serialized by earlier releases
* (Redis / persisted container sessions) deserialize cleanly with stamps defaulting to 0 — one soft
* refresh on the next request instead of a forced re-login. If this test fails you changed the
* serialized shape; do NOT re-pin without deciding the upgrade story.
*
* @author Morten Svanæs
*/
class UserDetailsImplSerializationTest {

@Test
void serialVersionUidIsPinnedToPreStampShape() {
assertEquals(
-6804263748578733471L,
ObjectStreamClass.lookup(UserDetailsImpl.class).getSerialVersionUID());
}

@Test
void withAuthzStampCopiesDataAndReplacesStamps() {
UserDetails original =
UserDetails.empty()
.username("alice")
.uid("u1")
.userRoleIds(Set.of("r1"))
.authzCheckedEpoch(3L)
.authzGen(2L)
.build();

UserDetailsImpl stamped = ((UserDetailsImpl) original).withAuthzStamp(7L, 5L);

assertNotSame(original, stamped);
assertEquals("alice", stamped.getUsername());
assertEquals("u1", stamped.getUid());
assertEquals(Set.of("r1"), stamped.getUserRoleIds());
assertEquals(7L, stamped.getAuthzCheckedEpoch());
assertEquals(5L, stamped.getAuthzGen());
}

@Test
void defaultStampsAreZeroMeaningUnknown() {
UserDetails details = UserDetails.empty().username("bob").uid("u2").build();

assertEquals(0L, details.getAuthzCheckedEpoch());
assertEquals(0L, details.getAuthzGen());
}
}
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,7 @@ private Converter<Jwt, DhisJwtAuthenticationToken> getTokenConverter(
String mappingValue = jwt.getClaim(mappingClaimKey);
UserDetails currentUserDetails =
switch (mappingClaimKey) {
case "username" -> userService.createUserDetailsByUsername(mappingValue);
case "username" -> authzService.getFreshUserDetails(mappingValue);
case "email" -> userService.createUserDetailsByOpenId(mappingValue);
default -> throw new InvalidBearerTokenException("Invalid mapping claim");
};
Expand Down
Loading
Loading