AccountRateLimitProperties.java

/*
 * Copyright (C) 2026 Alberto Irurueta Carro (alberto@irurueta.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.irurueta.authserver.authorization.api.web.account;

import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.DefaultValue;

/**
 * Configuration of the rate limiting of the unauthenticated account endpoints
 * ({@code authserver.account.rate-limit.*}).
 *
 * @param enabled        whether requests are limited at all (default {@code true}).
 * @param window         length of the fixed window the requests are counted in (default 15 minutes).
 * @param perClient      requests one client address may make in a window (default 20).
 * @param perEmail       requests that may name one e-mail address in a window (default 5).
 * @param maxTrackedKeys addresses tracked at most per kind of key; the oldest is forgotten first, so the memory
 *                       used stays bounded (default 10 000).
 */
@ConfigurationProperties(prefix = "authserver.account.rate-limit")
public record AccountRateLimitProperties(
        @DefaultValue("true") boolean enabled,
        @DefaultValue("PT15M") Duration window,
        @DefaultValue("20") int perClient,
        @DefaultValue("5") int perEmail,
        @DefaultValue("10000") int maxTrackedKeys) {

    /**
     * Validates the configuration.
     *
     * @throws IllegalArgumentException if the window is not positive, or a limit or the number of tracked keys is
     *                                  not positive.
     */
    public AccountRateLimitProperties {
        if (window == null || window.isZero() || window.isNegative()) {
            throw new IllegalArgumentException("window must be positive");
        }
        if (perClient < 1 || perEmail < 1 || maxTrackedKeys < 1) {
            throw new IllegalArgumentException("limits and maxTrackedKeys must be positive");
        }
    }
}