001/*
002 * Copyright 2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.revetsec.scim;
018
019import com.google.errorprone.annotations.CheckReturnValue;
020import com.revetsec.internal.Limits;
021import org.jspecify.annotations.NonNull;
022import org.jspecify.annotations.Nullable;
023
024import javax.annotation.concurrent.Immutable;
025import javax.annotation.concurrent.NotThreadSafe;
026import java.util.Collections;
027import java.util.EnumSet;
028import java.util.HashSet;
029import java.util.IdentityHashMap;
030import java.util.LinkedHashMap;
031import java.util.LinkedHashSet;
032import java.util.Map;
033import java.util.Objects;
034import java.util.Set;
035
036/**
037 * An immutable declaration of supported filter shapes. Defaults deny every shape. Syntax is checked
038 * at construction; registering a policy with a service provider later binds its paths to a schema
039 * and checks complete normalized filters. Possessing this configuration does not approve a filter.
040 *
041 * @since 1.0.0
042 */
043@Immutable
044@CheckReturnValue
045public final class ScimFilterPolicy {
046    private static final @NonNull ScimFilterPolicy REJECT_ALL = new Builder().build();
047
048    private final @NonNull Map<@NonNull String, @NonNull Set<@NonNull ScimComparisonOperator>> allowedComparisons;
049    private final @NonNull Set<@NonNull String> allowedPresence;
050    private final @NonNull Map<@NonNull String, @NonNull ScimFilterPolicy> allowedValuePaths;
051    private final @NonNull Set<@NonNull ScimLogicalOperator> allowedLogicalOperators;
052    private final int maximumComparisons;
053
054    private ScimFilterPolicy(@NonNull Builder builder) {
055        validatePaths(builder.allowedComparisons.keySet(), false);
056        validatePaths(builder.allowedPresence, false);
057        validatePaths(builder.allowedValuePaths.keySet(), true);
058        validateGraph(builder.allowedComparisons.size(), builder.allowedPresence.size(), builder.allowedValuePaths);
059        maximumComparisons = Limits.SCIM_FILTER_COMPARISONS.require(builder.maximumComparisons == null
060                ? Limits.SCIM_FILTER_COMPARISONS.getDefaultIntValue() : builder.maximumComparisons);
061        allowedComparisons = builder.allowedComparisons;
062        allowedPresence = builder.allowedPresence;
063        allowedValuePaths = builder.allowedValuePaths;
064        allowedLogicalOperators = builder.allowedLogicalOperators;
065    }
066
067    /**
068     * Starts complete policy configuration with every filter shape denied.
069     * @return a new builder
070     * @since 1.0.0
071     */
072    public static @NonNull Builder builder() { return new Builder(); }
073
074    /**
075     * Returns the fixed policy that explicitly denies filtering.
076     * @return the rejection policy
077     * @since 1.0.0
078     */
079    public static @NonNull ScimFilterPolicy rejectAllInstance() { return REJECT_ALL; }
080
081    /**
082     * Returns the immutable configured path-to-comparison-operator snapshot.
083     * @return configured comparison shapes
084     * @since 1.0.0
085     */
086    public @NonNull Map<@NonNull String, @NonNull Set<@NonNull ScimComparisonOperator>> getAllowedComparisons() {
087        return allowedComparisons;
088    }
089
090    /**
091     * Returns immutable configured presence paths.
092     *
093     * @return immutable configured presence paths
094     * @since 1.0.0
095     */
096    public @NonNull Set<@NonNull String> getAllowedPresence() { return allowedPresence; }
097    /**
098     * Returns immutable configured ValuePath policies.
099     *
100     * @return immutable configured ValuePath policies
101     * @since 1.0.0
102     */
103    public @NonNull Map<@NonNull String, @NonNull ScimFilterPolicy> getAllowedValuePaths() { return allowedValuePaths; }
104    /**
105     * Returns immutable configured logical operators.
106     *
107     * @return immutable configured logical operators
108     * @since 1.0.0
109     */
110    public @NonNull Set<@NonNull ScimLogicalOperator> getAllowedLogicalOperators() { return allowedLogicalOperators; }
111    /**
112     * Returns maximum comparisons across a complete filter.
113     *
114     * @return maximum comparisons across a complete filter
115     * @since 1.0.0
116     */
117    public @NonNull Integer getMaximumComparisons() { return maximumComparisons; }
118
119    /**
120     * Returns a fixed redacted description.
121     *
122     * @return a fixed redacted description
123     * @since 1.0.0
124     */
125    @Override public @NonNull String toString() { return "ScimFilterPolicy{<redacted>}"; }
126
127    private static void requireEntryBound(int size) {
128        if (size > Limits.SCIM_FILTER_NODES.getCap())
129            throw new IllegalArgumentException("SCIM filter policy exceeds its entry bound.");
130    }
131
132    private static void validatePaths(@NonNull Set<@NonNull String> paths, boolean valuePath) {
133        Set<ScimAttributePath> unique = new HashSet<>();
134        for (String expression : paths) {
135            ScimAttributePathParseResult result = ScimAttributePath.fromExpressionResult(expression);
136            if (!(result instanceof ScimAttributePathParseResult.Succeeded succeeded))
137                throw new IllegalArgumentException("SCIM filter policy contains an invalid attribute path.");
138            ScimAttributePath path = succeeded.getAttributePath();
139            if (!unique.add(path))
140                throw new IllegalArgumentException("SCIM filter policy contains equivalent attribute paths.");
141            if (valuePath && path.getSubAttributeName().isPresent())
142                throw new IllegalArgumentException("SCIM ValuePath policy requires a top-level attribute path.");
143        }
144    }
145
146    private static void validateGraph(int comparisonPaths, int presencePaths,
147            @NonNull Map<@NonNull String, @NonNull ScimFilterPolicy> children) {
148        requireEntryBound(children.size());
149        IdentityHashMap<ScimFilterPolicy, Boolean> active = new IdentityHashMap<>();
150        // Count repeated DAG occurrences as work: sharing a child cannot evade aggregate bounds.
151        int[] counts = {1, comparisonPaths + presencePaths + children.size()};
152        requireEntryBound(counts[1]);
153        for (ScimFilterPolicy child : children.values())
154            visitPolicy(Objects.requireNonNull(child), 2, active, counts);
155    }
156
157    private static void visitPolicy(@NonNull ScimFilterPolicy policy, int depth,
158            @NonNull IdentityHashMap<@NonNull ScimFilterPolicy, @NonNull Boolean> active, int @NonNull [] counts) {
159        if (depth > Limits.SCIM_FILTER_DEPTH.getCap() || ++counts[0] > Limits.SCIM_FILTER_NODES.getCap())
160            throw new IllegalArgumentException("SCIM filter policy graph exceeds its structural bounds.");
161        counts[1] += policy.allowedComparisons.size() + policy.allowedPresence.size() + policy.allowedValuePaths.size();
162        requireEntryBound(counts[1]);
163        if (active.put(policy, Boolean.TRUE) != null)
164            throw new IllegalArgumentException("SCIM filter policy graph contains a cycle.");
165        for (ScimFilterPolicy child : policy.allowedValuePaths.values())
166            visitPolicy(child, depth + 1, active, counts);
167        active.remove(policy);
168    }
169
170    /**
171     * Mutable, non-thread-safe policy configuration. Setters replace complete snapshots. Null
172     * clears collections and restores the registered comparison-count default.
173     *
174     * @since 1.0.0
175     */
176    @NotThreadSafe
177    @CheckReturnValue
178    public static final class Builder {
179        private @NonNull Map<@NonNull String, @NonNull Set<@NonNull ScimComparisonOperator>> allowedComparisons = Map.of();
180        private @NonNull Set<@NonNull String> allowedPresence = Set.of();
181        private @NonNull Map<@NonNull String, @NonNull ScimFilterPolicy> allowedValuePaths = Map.of();
182        private @NonNull Set<@NonNull ScimLogicalOperator> allowedLogicalOperators = Set.of();
183        private @Nullable Integer maximumComparisons;
184
185        private Builder() { }
186
187        /**
188         * Replaces supported comparison shapes with a deep immutable collection snapshot.
189         * @param value complete comparison map, or null to deny comparisons
190         * @return this builder
191         * @since 1.0.0
192         */
193        public @NonNull Builder allowedComparisons(
194                @Nullable Map<@NonNull String, @NonNull Set<@NonNull ScimComparisonOperator>> value) {
195            if (value == null) { allowedComparisons = Map.of(); return this; }
196            requireEntryBound(value.size());
197            Map<String, Set<ScimComparisonOperator>> copy = new LinkedHashMap<>();
198            for (Map.Entry<String, Set<ScimComparisonOperator>> entry : value.entrySet()) {
199                String path = Objects.requireNonNull(entry.getKey());
200                Set<ScimComparisonOperator> operators = Objects.requireNonNull(entry.getValue());
201                requireEntryBound(operators.size());
202                EnumSet<ScimComparisonOperator> operatorCopy = EnumSet.noneOf(ScimComparisonOperator.class);
203                for (ScimComparisonOperator operator : operators)
204                    operatorCopy.add(Objects.requireNonNull(operator));
205                copy.put(path, Collections.unmodifiableSet(operatorCopy));
206            }
207            allowedComparisons = Collections.unmodifiableMap(copy);
208            return this;
209        }
210
211        /**
212         * Replaces supported presence paths with an immutable snapshot.
213         * @param value complete path set, or null to deny presence
214         * @return this builder
215         * @since 1.0.0
216         */
217        public @NonNull Builder allowedPresence(@Nullable Set<@NonNull String> value) {
218            if (value == null) { allowedPresence = Set.of(); return this; }
219            requireEntryBound(value.size());
220            Set<String> copy = new LinkedHashSet<>();
221            for (String path : value) copy.add(Objects.requireNonNull(path));
222            allowedPresence = Collections.unmodifiableSet(copy);
223            return this;
224        }
225
226        /**
227         * Replaces supported ValuePath policies after checking finite acyclic graph bounds.
228         * @param value complete path-to-policy map, or null to deny ValuePath
229         * @return this builder
230         * @since 1.0.0
231         */
232        public @NonNull Builder allowedValuePaths(
233                @Nullable Map<@NonNull String, @NonNull ScimFilterPolicy> value) {
234            if (value == null) { allowedValuePaths = Map.of(); return this; }
235            validateGraph(0, 0, value);
236            Map<String, ScimFilterPolicy> copy = new LinkedHashMap<>();
237            for (Map.Entry<String, ScimFilterPolicy> entry : value.entrySet())
238                copy.put(Objects.requireNonNull(entry.getKey()), Objects.requireNonNull(entry.getValue()));
239            allowedValuePaths = Collections.unmodifiableMap(copy);
240            return this;
241        }
242
243        /**
244         * Replaces supported logical operators with an immutable snapshot.
245         * @param value complete operator set, or null to deny logical operators
246         * @return this builder
247         * @since 1.0.0
248         */
249        public @NonNull Builder allowedLogicalOperators(@Nullable Set<@NonNull ScimLogicalOperator> value) {
250            if (value == null) { allowedLogicalOperators = Set.of(); return this; }
251            requireEntryBound(value.size());
252            EnumSet<ScimLogicalOperator> copy = EnumSet.noneOf(ScimLogicalOperator.class);
253            for (ScimLogicalOperator operator : value) copy.add(Objects.requireNonNull(operator));
254            allowedLogicalOperators = Collections.unmodifiableSet(copy);
255            return this;
256        }
257
258        /**
259         * Sets the comparison-count limit: default 32, inclusive range 1–128. The filter's node
260         * limit provides an additional bound when a complete filter is checked.
261         * @param value the limit, or null to restore its default
262         * @return this builder
263         * @since 1.0.0
264         */
265        public @NonNull Builder maximumComparisons(@Nullable Integer value) {
266            maximumComparisons = value; return this;
267        }
268
269        /**
270         * Checks path syntax and graph bounds and creates a complete immutable snapshot. Schema
271         * registration and normalized-filter approval are later service-provider operations.
272         * @return filter policy
273         * @since 1.0.0
274         */
275        public @NonNull ScimFilterPolicy build() { return new ScimFilterPolicy(this); }
276    }
277}