Skip to content

Add caching for token validation results #41

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
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
25 changes: 25 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "java",
"name": "Debug Spring Test (Gradle Paths)",
"request": "launch",
"mainClass": "${file}",
"projectName": "SpringCFTurnstile",
"classPaths": [
"${workspaceFolder}/build/classes/java/main",
"${workspaceFolder}/build/classes/java/test",
"${workspaceFolder}/build/resources/main",
"${workspaceFolder}/build/resources/test"
],
"vmArgs": [
"-ea",
"-Dspring.profiles.active=test"
]
}
]
}
7 changes: 7 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ repositories {
dependencies {
// Spring Boot dependencies
compileOnly "org.springframework.boot:spring-boot-starter-web:$springBootVersion"
compileOnly "org.springframework.boot:spring-boot-starter-cache:$springBootVersion"

// Caffeine cache - efficient in-memory caching
compileOnly "com.github.ben-manes.caffeine:caffeine:3.1.8"

// Lombok dependencies
compileOnly "org.projectlombok:lombok:$lombokVersion"
Expand All @@ -46,8 +50,11 @@ dependencies {

// Testing dependencies
testImplementation "org.springframework.boot:spring-boot-starter-web:$springBootVersion"
testImplementation "org.springframework.boot:spring-boot-starter-cache:$springBootVersion"
testImplementation "com.github.ben-manes.caffeine:caffeine:3.1.8"
testImplementation "org.springframework.boot:spring-boot-starter-test:$springBootVersion"
testImplementation "org.springframework.boot:spring-boot-starter-actuator:$springBootVersion"
testImplementation 'org.junit.platform:junit-platform-console:1.9.3'
}

test {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import com.digitalsanctuary.cf.turnstile.config.TurnstileCacheConfig;
import com.digitalsanctuary.cf.turnstile.config.TurnstileCacheProperties;
import com.digitalsanctuary.cf.turnstile.config.TurnstileConfigProperties;
import com.digitalsanctuary.cf.turnstile.config.TurnstileServiceConfig;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;

Expand All @@ -26,6 +30,11 @@
* sitekey: your-turnstile-site-key
* secret: your-turnstile-secret-key
* url: https://challenges.cloudflare.com/turnstile/v0/siteverify
* cache:
* enabled: true
* ttlSeconds: 300
* maxSize: 1000
* cacheSuccessOnly: true
* </pre>
* <p>
* The {@link #onStartup()} method is annotated with {@link jakarta.annotation.PostConstruct} and is executed
Expand All @@ -34,12 +43,19 @@
*
* @see com.digitalsanctuary.cf.turnstile.config.TurnstileConfigProperties
* @see com.digitalsanctuary.cf.turnstile.config.TurnstileServiceConfig
* @see com.digitalsanctuary.cf.turnstile.config.TurnstileCacheProperties
* @see com.digitalsanctuary.cf.turnstile.config.TurnstileCacheConfig
* @see com.digitalsanctuary.cf.turnstile.service.TurnstileValidationService
*/
@Slf4j
@Configuration
@AutoConfiguration
@Import({TurnstileServiceConfig.class, TurnstileConfigProperties.class})
@Import({
TurnstileServiceConfig.class,
TurnstileConfigProperties.class,
TurnstileCacheProperties.class,
TurnstileCacheConfig.class
})
public class TurnstileConfiguration {

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.digitalsanctuary.cf.turnstile.config;

import java.util.concurrent.TimeUnit;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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 com.github.benmanes.caffeine.cache.Caffeine;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
* Configuration class for Turnstile caching.
* <p>
* This class configures the cache manager and related components for the Turnstile validation service.
* It is conditionally enabled based on the {@code ds.cf.turnstile.cache.enabled} property.
* </p>
*/
@Slf4j
@Configuration
@EnableCaching
@RequiredArgsConstructor
@ConditionalOnProperty(name = "ds.cf.turnstile.cache.enabled", havingValue = "true", matchIfMissing = true)
public class TurnstileCacheConfig {

/**
* The name of the cache used for Turnstile validation results.
*/
public static final String TURNSTILE_VALIDATION_CACHE = "turnstileValidationCache";

private final TurnstileCacheProperties cacheProperties;

/**
* Logs the cache configuration on startup.
*/
@PostConstruct
public void onStartup() {
log.info("Turnstile caching is enabled");
log.info("Cache TTL: {} seconds", cacheProperties.getTtlSeconds());
log.info("Cache max size: {} entries", cacheProperties.getMaxSize());
log.info("Cache successful validations only: {}", cacheProperties.isCacheSuccessOnly());
}

/**
* Creates and configures the cache manager.
*
* @return the configured cache manager
*/
@Bean
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager(TURNSTILE_VALIDATION_CACHE);

Caffeine<Object, Object> caffeine = Caffeine.newBuilder()
.expireAfterWrite(cacheProperties.getTtlSeconds(), TimeUnit.SECONDS)
.maximumSize(cacheProperties.getMaxSize())
.recordStats();

cacheManager.setCaffeine(caffeine);
return cacheManager;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.digitalsanctuary.cf.turnstile.config;

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

import lombok.Data;

/**
* Configuration properties for Turnstile caching.
* <p>
* This class defines the configuration properties for the caching functionality of the Turnstile validation service.
* </p>
* <p>
* By default, these properties are expected to be defined with the prefix {@code ds.cf.turnstile.cache}:
* </p>
*
* <pre>
* ds:
* cf:
* turnstile:
* cache:
* enabled: true
* ttlSeconds: 300
* maxSize: 1000
* </pre>
*/
@Data
@Component("turnstileCacheProperties")
@ConfigurationProperties(prefix = "ds.cf.turnstile.cache")
public class TurnstileCacheProperties {

/**
* Whether caching is enabled for Turnstile validation responses. Default is true.
*/
private boolean enabled = true;

/**
* Time-to-live for cache entries in seconds. Default is 300 seconds (5 minutes).
*/
private int ttlSeconds = 300;

/**
* Maximum number of entries in the cache. Default is 1000.
*/
private int maxSize = 1000;

/**
* Whether to cache successful validations only. If true, only successful validations will be cached, which prevents cache poisoning. Default is
* true.
*/
private boolean cacheSuccessOnly = true;
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
public class TurnstileServiceConfig {

private final TurnstileConfigProperties properties;
private final TurnstileCacheProperties cacheProperties;

/**
* Creates a RestTemplate bean for Turnstile API interactions.
Expand All @@ -40,7 +41,7 @@ public RestTemplate turnstileRestTemplate(RestTemplateBuilder builder) {
*/
@Bean
public TurnstileValidationService turnstileValidationService() {
return new TurnstileValidationService(turnstileRestClient(), properties);
return new TurnstileValidationService(turnstileRestClient(), properties, cacheProperties);
}

/**
Expand Down
Loading