Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
18b4d56
Add CzertainlyAuthenticationCache with caching for authentication met…
LukasNajman Apr 29, 2026
90bfb9f
Compare UUIDs not strings
LukasNajman May 5, 2026
1d5bf6c
Add SessionTableHelper to create session tables in the database
LukasNajman May 5, 2026
50a6748
Handle malformed certificate headers in CzertainlyAuthenticationFilte…
LukasNajman May 5, 2026
3647d22
Replace null checks with `Objects.requireNonNull` in CzertainlyAuthen…
LukasNajman May 5, 2026
cd3ef37
Extract `TokenJtiIndex` for user-to-JTI mapping and integrate it into…
LukasNajman May 5, 2026
a56422e
Validate `userUuid` is non-blank in `TokenJtiIndex.add` to ensure dat…
LukasNajman May 5, 2026
52630ee
Fix failing tests
LukasNajman May 5, 2026
1d06752
Handle `IllegalStateException` in `CzertainlyAuthenticationClient` to…
LukasNajman May 5, 2026
9383a94
Address code review notes
LukasNajman May 6, 2026
985efbc
Refactor `AuthenticationCache` to remove certificate fingerprint depe…
LukasNajman May 6, 2026
f575127
Introduce configurable authentication cache properties with TTL and m…
LukasNajman May 6, 2026
d5bf756
Enable cache statistics tracking for enhanced monitoring
LukasNajman May 6, 2026
8a549c3
Add integration tests for `AuthenticationCache` eviction logic
LukasNajman May 6, 2026
d908ec1
Update `revokeCertificate` test to correct cache eviction assertions
LukasNajman May 6, 2026
28ff286
Refactor to use `UUID` objects instead of `String`
LukasNajman May 6, 2026
eee94d9
Merge branch 'main' into Authn-Cache
LukasNajman May 7, 2026
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
8 changes: 8 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,14 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>

<!-- OpenTelemetry -->
<dependency>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.czertainly.core.auth.oauth2;

import com.czertainly.api.model.core.logging.enums.AuthMethod;
import com.czertainly.api.model.core.logging.enums.Operation;
import com.czertainly.api.model.core.logging.enums.OperationResult;
import com.czertainly.api.model.core.settings.SettingsSection;
Expand Down Expand Up @@ -62,7 +61,7 @@ public AbstractAuthenticationToken convert(@Nullable Jwt source) {
throw e;
}

AuthenticationInfo authInfo = authenticationClient.authenticate(AuthMethod.TOKEN, claims, false);
AuthenticationInfo authInfo = authenticationClient.authenticateByToken(claims);
CzertainlyUserDetails userDetails = new CzertainlyUserDetails(authInfo);
// Provider settings will not be null, otherwise converter would not have been reached from decoder
logger.debug("User '{}' has been authenticated using JWT from OAuth2 Provider '{}'.", userDetails.getUsername(), providerSettings == null ? " " : providerSettings.getName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull Ht
private void authenticate(HttpServletRequest request, Map<String, Object> claims, ClientRegistration clientRegistration) {
AuthenticationInfo authInfo;
try {
authInfo = authenticationClient.authenticate(AuthMethod.TOKEN, claims, false);
authInfo = authenticationClient.authenticateByToken(claims);
CzertainlyAuthenticationToken authenticationToken = new CzertainlyAuthenticationToken(new CzertainlyUserDetails(authInfo));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
LOGGER.debug("Session of user '{}' logged using OAuth2 Provider '{}' has been successfully validated.", authenticationToken.getPrincipal().getUsername(), clientRegistration.getRegistrationId());
Expand Down
15 changes: 15 additions & 0 deletions src/main/java/com/czertainly/core/config/AuthCacheProperties.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.czertainly.core.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "caching.authentication")
public record AuthCacheProperties(
int ttlMinutes,
int maxSize
) {

public AuthCacheProperties {
if (ttlMinutes <= 0) ttlMinutes = 5;
if (maxSize <= 0) maxSize = 500;
}
}
52 changes: 52 additions & 0 deletions src/main/java/com/czertainly/core/config/CacheConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.czertainly.core.config;

import com.czertainly.core.security.authn.client.TokenJtiIndex;
import com.czertainly.core.security.authn.client.UserCertificateIndex;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching(order = Ordered.HIGHEST_PRECEDENCE)
@EnableConfigurationProperties(AuthCacheProperties.class)
public class CacheConfig {

public static final String SIGNING_PROFILES_CACHE = "signingProfiles";
public static final String TSP_PROFILES_CACHE = "tspProfiles";
public static final String CERTIFICATE_CHAIN_CACHE = "certificateChain";
public static final String SYSTEM_USER_AUTH_CACHE = "systemUserAuth";
public static final String USER_UUID_AUTH_CACHE = "userUuidAuth";
public static final String CERTIFICATE_AUTH_CACHE = "certificateAuth";
public static final String TOKEN_AUTH_CACHE = "tokenAuth";
public static final String FORMATTER_CONNECTOR_CACHE = "formatterConnector";
public static final String CRYPTOGRAPHIC_KEY_ITEM_CACHE = "cryptographicKeyItem";

@Bean
public CacheManager cacheManager(AuthCacheProperties cacheProperties, TokenJtiIndex tokenJtiIndex, UserCertificateIndex userCertificateIndex) {
CaffeineCacheManager mgr = new CaffeineCacheManager(SIGNING_PROFILES_CACHE, TSP_PROFILES_CACHE, CERTIFICATE_CHAIN_CACHE, SYSTEM_USER_AUTH_CACHE, USER_UUID_AUTH_CACHE, FORMATTER_CONNECTOR_CACHE, CRYPTOGRAPHIC_KEY_ITEM_CACHE);
mgr.setCaffeine(Caffeine.newBuilder()
.expireAfterWrite(cacheProperties.ttlMinutes(), TimeUnit.MINUTES)
.maximumSize(cacheProperties.maxSize())
.recordStats());
mgr.registerCustomCache(CERTIFICATE_AUTH_CACHE, Caffeine.newBuilder()
.expireAfterWrite(cacheProperties.ttlMinutes(), TimeUnit.MINUTES)
.maximumSize(cacheProperties.maxSize())
.recordStats()
.removalListener(userCertificateIndex)
.build());
mgr.registerCustomCache(TOKEN_AUTH_CACHE, Caffeine.newBuilder()
.expireAfterWrite(cacheProperties.ttlMinutes(), TimeUnit.MINUTES)
.maximumSize(cacheProperties.maxSize())
.recordStats()
.removalListener(tokenJtiIndex)
.build());
return mgr;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.czertainly.core.security.authn.client.AuthenticationInfo;
import com.czertainly.core.security.authn.client.CzertainlyAuthenticationClient;
import com.czertainly.core.util.AuthHelper;
import com.czertainly.core.util.CertificateUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
Expand All @@ -19,7 +20,11 @@

import java.io.IOException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.UUID;

public class CzertainlyAuthenticationFilter extends OncePerRequestFilter {
Expand All @@ -44,33 +49,22 @@ protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull Ht
log.trace("Going to authenticate the '{}' request on '{}'.", request.getMethod(), request.getRequestURI());

try {

AuthMethod authMethod = AuthMethod.NONE;
Object authData = null;

if (request.getHeader(certificateHeaderName) != null) {
authMethod = AuthMethod.CERTIFICATE;
authData = request.getHeader(certificateHeaderName);
AuthenticationInfo authInfo;
String rawCertHeader = request.getHeader(certificateHeaderName);
if (rawCertHeader != null) {
authInfo = authenticateByCertificate(rawCertHeader);
} else {
authInfo = authClient.authenticate(AuthMethod.NONE, null, isLocalhostAddress(request));
}
Comment thread
LukasNajman marked this conversation as resolved.

AuthenticationInfo authInfo = authClient.authenticate(authMethod, authData, isLocalhostAddress(request));

Authentication authentication;
if (authInfo.isAnonymous()) {
authentication = new CzertainlyAnonymousToken(UUID.randomUUID().toString(), new CzertainlyUserDetails(authInfo), authInfo.getAuthorities());
} else {
authentication = new CzertainlyAuthenticationToken(new CzertainlyUserDetails(authInfo));
}

SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(authentication);
SecurityContextHolder.setContext(securityContext);
CzertainlyUserDetails userDetails = (CzertainlyUserDetails) authentication.getPrincipal();
if (userDetails.getAuthMethod() == AuthMethod.CERTIFICATE) {
log.debug("User with username '{}' has been successfully authenticated with certificate.", userDetails.getUsername());
} else {
log.debug("User has not been identified, using anonymous user.");
}
updateSecurityContext(authentication);

} catch (AuthenticationException e) {
SecurityContextHolder.clearContext();
Expand All @@ -84,6 +78,33 @@ protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull Ht
filterChain.doFilter(request, response);
}

private static void updateSecurityContext(Authentication authentication) {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(authentication);
SecurityContextHolder.setContext(securityContext);
CzertainlyUserDetails userDetails = (CzertainlyUserDetails) authentication.getPrincipal();
if (userDetails.getAuthMethod() == AuthMethod.CERTIFICATE) {
log.debug("User with username '{}' has been successfully authenticated with certificate.", userDetails.getUsername());
} else {
log.debug("User has not been identified, using anonymous user.");
}
}

private AuthenticationInfo authenticateByCertificate(String rawCertHeader) {
AuthenticationInfo authInfo;
try {
String decoded = URLDecoder.decode(rawCertHeader, StandardCharsets.UTF_8);
byte[] derBytes = Base64.getDecoder().decode(CertificateUtil.normalizeCertificateContent(decoded));
String thumbprint = CertificateUtil.getThumbprint(derBytes);
authInfo = authClient.authenticateByCertificate(rawCertHeader, thumbprint);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 algorithm not available", e);
} catch (IllegalArgumentException e) {
throw new CzertainlyAuthenticationException("Invalid certificate header: " + e.getMessage(), e);
}
return authInfo;
}

private boolean isAuthenticationNeeded(final HttpServletRequest request) {
SecurityContext securityContext = SecurityContextHolder.getContext();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package com.czertainly.core.security.authn.client;

import java.util.UUID;
import java.util.function.Supplier;

public interface AuthenticationCache {

/**
* Returns cached authentication for a system user, or invokes {@code loader} and caches the result.
* Cached by username. System usernames (superadmin, acme, scep, …) are stable identifiers
* that never change, so the cache entry remains valid for its full TTL.
*
* @param username system username used as the cache key
* @param loader called on a cache miss to produce the {@link AuthenticationInfo}
* @return the cached or freshly loaded {@link AuthenticationInfo}
*/
AuthenticationInfo getOrAuthenticateSystemUser(String username, Supplier<AuthenticationInfo> loader);
Comment thread
LukasNajman marked this conversation as resolved.
Dismissed

/**
* Returns cached authentication for a user identified by UUID, or invokes {@code loader} and caches the result.
* Effective for repeated internal impersonation calls within the TTL window.
*
* @param userUuid UUID of the user, used as the cache key
* @param loader called on a cache miss to produce the {@link AuthenticationInfo}
* @return the cached or freshly loaded {@link AuthenticationInfo}
*/
AuthenticationInfo getOrAuthenticateByUserUuid(UUID userUuid, Supplier<AuthenticationInfo> loader);
Comment thread
LukasNajman marked this conversation as resolved.
Dismissed

/**
* Returns cached authentication for a client-certificate request, or invokes {@code loader} and caches the result.
* Cached by SHA-256 of the DER-encoded certificate bytes (computed in CzertainlyAuthenticationFilter),
* matching the DB {@code certificate.fingerprint} field. All requests carrying the same client certificate
* share one cache entry. The entry is evicted immediately on revocation via CertificateServiceImpl.
*
* @param thumbprint SHA-256 fingerprint of the client certificate, used as the cache key
* @param loader called on a cache miss to produce the {@link AuthenticationInfo}
* @return the cached or freshly loaded {@link AuthenticationInfo}
*/
AuthenticationInfo getOrAuthenticateByCertificate(String thumbprint, Supplier<AuthenticationInfo> loader);
Comment thread
github-code-quality[bot] marked this conversation as resolved.
Fixed

/**
* Returns cached authentication for a bearer-token request, or invokes {@code loader} and caches the result.
* Cached by the {@code jti} claim, which is unique per token issuance. All requests that carry the same
* access token share one cache entry for its lifetime. When the token is refreshed, a new {@code jti}
* causes a cache miss, triggering a fresh auth-service call. Tokens without a {@code jti} are never cached.
*
* @param jti the {@code jti} claim of the access token, used as the cache key; {@code null} skips caching
* @param loader called on a cache miss to produce the {@link AuthenticationInfo}
* @return the cached or freshly loaded {@link AuthenticationInfo}
*/
AuthenticationInfo getOrAuthenticateByToken(String jti, Supplier<AuthenticationInfo> loader);

/**
* Evicts all auth cache entries for a single user: their UUID entry, all token entries tracked
* in the jti index, and their certificate entry tracked in the certificate index.
* Use this for user-scoped changes (role assignment, disable, delete, certificate revocation)
* where only one user is affected and the system-user cache can be left untouched.
*
* @param userUuid UUID of the user whose cache entries should be evicted
*/
void evictByUserUuid(UUID userUuid);

/**
* Evicts only the certificate-based auth cache entry for the given fingerprint.
* Use this when a certificate is disassociated from a user but the user's identity and
* roles are unchanged — their UUID and token cache entries remain valid.
*
* @param certFingerprint SHA-256 fingerprint of the certificate to evict
*/
void evictByCertificateFingerprint(String certFingerprint);

/**
* Clears all four auth caches and the jti index (the per-user map of {@code jti} claims used to
* find and evict token cache entries when a user is modified). Use this for role-level mutations
* (permission changes, role deletion) that may affect any user, including system accounts.
*/
void evictAll();
}
Loading
Loading