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 static java.util.Objects.requireNonNull;
020
021import com.google.errorprone.annotations.CheckReturnValue;
022import com.revetsec.internal.Limits;
023import com.revetsec.internal.ObserverDispatch;
024import com.revetsec.internal.json.AsciiCase;
025import com.revetsec.internal.json.JsonCodec;
026import com.revetsec.internal.json.JsonDocument;
027import com.revetsec.internal.json.JsonLimits;
028import com.revetsec.internal.json.JsonParseException;
029import com.revetsec.internal.json.JsonParseResult;
030import com.revetsec.json.JsonArray;
031import com.revetsec.json.JsonNumber;
032import com.revetsec.json.JsonObject;
033import com.revetsec.json.JsonString;
034import com.revetsec.json.JsonValue;
035
036import org.jspecify.annotations.NonNull;
037import org.jspecify.annotations.Nullable;
038
039import java.net.URI;
040import java.nio.charset.StandardCharsets;
041import java.util.ArrayList;
042import java.util.Collections;
043import java.util.EnumSet;
044import java.util.IdentityHashMap;
045import java.util.LinkedHashMap;
046import java.util.LinkedHashSet;
047import java.util.List;
048import java.util.Map;
049import java.util.Optional;
050import java.util.Set;
051import java.util.function.Supplier;
052
053import javax.annotation.concurrent.Immutable;
054import javax.annotation.concurrent.NotThreadSafe;
055
056/**
057 * Immutable framework-neutral SCIM schema, request and response primitives. Applications authenticate,
058 * authorize, execute queries and persist candidates atomically; this facade performs no I/O.
059 * Each direct-result operation has one bounded work budget and redacted observer lifecycle.
060 * Parsed carriers are tied to this registration and compatibility snapshot. Base-URI-only copies
061 * share that semantic registration; changed compatibility requires fresh parsing.
062 * Resource-type arguments must be the exact immutable objects registered with this provider,
063 * rather than separately constructed equal definitions. Passing a foreign trusted type is a
064 * programming error; expected untrusted-input failures return checked fixed rejections.
065 * Original query/header occurrences must reach these operations before framework normalization.
066 * A prepared response proves bounded output only. Applications prepare the final authorized
067 * candidate before commit where preparation can fail, then emit it only after confirmed persistence.
068 * @since 1.0.0
069 */
070@Immutable
071@CheckReturnValue
072public final class ScimServiceProvider {
073    private final @NonNull URI baseUri;
074    private final @NonNull List<@NonNull ScimResourceType> resourceTypes;
075    private final @NonNull ScimServiceProviderConfig serviceProviderConfig;
076    private final @NonNull ScimLimits limits;
077    private final @NonNull ScimCompatibility compatibility;
078
079    @SuppressWarnings("Immutable") // Application SPI contract explicitly requires thread safety.
080    private final @Nullable ScimStringMatching stringMatching;
081
082    @SuppressWarnings("Immutable") // Application SPI contract explicitly requires thread safety.
083    private final @NonNull ScimObserver observer;
084
085    private final @NonNull Map<@NonNull ScimResourceType, @NonNull ScimFilterPolicy> filterPolicies;
086    private final @NonNull Map<@NonNull ScimResourceType, @NonNull ScimFilterBinding> bindings;
087    private final @NonNull List<@NonNull ScimSchema> schemas;
088    private final @NonNull Object semanticContext;
089
090    private ScimServiceProvider(@NonNull Builder builder, @Nullable Object context) {
091        baseUri = base(requireNonNull(builder.baseUri, "SCIM base URI is required."));
092        resourceTypes = builder.resourceTypes;
093        if (resourceTypes.isEmpty())
094            throw new IllegalStateException("SCIM requires at least one resource type.");
095        serviceProviderConfig =
096                builder.serviceProviderConfig == null
097                        ? ScimServiceProviderConfig.builder().build()
098                        : builder.serviceProviderConfig;
099        compatibility =
100                builder.compatibility == null
101                        ? ScimCompatibility.strictInstance()
102                        : builder.compatibility;
103        limits = builder.limits == null ? ScimLimits.fromDefaults() : builder.limits;
104        observer = builder.observer == null ? ScimObserver.disabledInstance() : builder.observer;
105        stringMatching = builder.stringMatching;
106        if (serviceProviderConfig.isPatchSupported() && stringMatching == null)
107            throw new IllegalStateException(
108                    "Advertised SCIM PATCH requires an application matching strategy.");
109        if (serviceProviderConfig.getPagination().getMaximumPageSize() > limits.getMaximumPageSize()
110                || serviceProviderConfig.getFilterMaximumResults() > limits.getMaximumPageSize())
111            throw new IllegalArgumentException(
112                    "SCIM advertised maxima exceed configured processing limits.");
113        schemas = registrations(resourceTypes);
114        Map<ScimResourceType, ScimFilterPolicy> policies = new LinkedHashMap<>();
115        for (Map.Entry<ScimResourceType, ScimFilterPolicy> entry :
116                builder.filterPolicies.entrySet()) {
117            registered(entry.getKey());
118            policies.put(entry.getKey(), entry.getValue());
119        }
120        IdentityHashMap<ScimResourceType, ScimFilterBinding> bound = new IdentityHashMap<>();
121        for (ScimResourceType type : resourceTypes) {
122            ScimFilterPolicy policy = identityPolicy(policies, type);
123            if (policy == null && serviceProviderConfig.isFilterSupported())
124                throw new IllegalStateException(
125                        "Advertised SCIM filtering requires an explicit policy for every type.");
126            bound.put(
127                    type,
128                    new ScimFilterBinding(
129                            type,
130                            limits.getFilterLimits(),
131                            compatibility,
132                            policy == null ? ScimFilterPolicy.rejectAllInstance() : policy,
133                            serviceProviderConfig.isFilterSupported()));
134        }
135        filterPolicies = Collections.unmodifiableMap(policies);
136        bindings = Collections.unmodifiableMap(bound);
137        semanticContext = context == null ? new Object() : context;
138    }
139
140    /** Starts configuration with no resource registrations; PATCH, filter, sort and password-change
141     * advertisement are disabled, and ETags are enabled. The application still owns password
142     * authorization and handling for a supplied write-only {@code password} value.
143     * @return a new builder
144     * @since 1.0.0
145     */
146    public static @NonNull Builder builder() {
147        return new Builder();
148    }
149
150    /** Starts a copy retaining the current semantic registration unless compatibility changes.
151     * @return a new copier
152     * @since 1.0.0
153     */
154    public @NonNull Copier copy() {
155        return new Copier(this);
156    }
157
158    /** Returns the trusted canonical trailing-slash base URI.
159     * @return the trusted canonical trailing-slash base URI
160     * @since 1.0.0
161     */
162    public @NonNull URI getBaseUri() {
163        return baseUri;
164    }
165
166    /** Returns the immutable registered resource types.
167     * @return the immutable registered resource types
168     * @since 1.0.0
169     */
170    public @NonNull List<@NonNull ScimResourceType> getResourceTypes() {
171        return resourceTypes;
172    }
173
174    /** Returns the advertised capabilities.
175     * @return the advertised capabilities
176     * @since 1.0.0
177     */
178    public @NonNull ScimServiceProviderConfig getServiceProviderConfig() {
179        return serviceProviderConfig;
180    }
181
182    /** Returns the processing limits.
183     * @return the processing limits
184     * @since 1.0.0
185     */
186    public @NonNull ScimLimits getLimits() {
187        return limits;
188    }
189
190    /** Returns the explicit compatibility features.
191     * @return the explicit compatibility features
192     * @since 1.0.0
193     */
194    public @NonNull ScimCompatibility getCompatibility() {
195        return compatibility;
196    }
197
198    /** Returns the optional application matching strategy.
199     * @return the optional application matching strategy
200     * @since 1.0.0
201     */
202    public @NonNull Optional<@NonNull ScimStringMatching> getStringMatching() {
203        return Optional.ofNullable(stringMatching);
204    }
205
206    /** Returns the immutable configured filter policies.
207     * @return the immutable configured filter policies
208     * @since 1.0.0
209     */
210    public @NonNull Map<@NonNull ScimResourceType, @NonNull ScimFilterPolicy> getFilterPolicies() {
211        return filterPolicies;
212    }
213
214    /** Validates exactly one original physical media-type header occurrence.
215     * Accepts application/scim+json or application/json with the selected syntactically valid charset
216     * accommodation. Bodies remain strictly UTF-8 regardless of a charset label. Missing, duplicate,
217     * malformed or unsupported values reject; do not join physical occurrences before validation.
218     * @param rawHeaderValues original physical Content-Type values, including an empty list when absent
219     * @return the checked direct result
220     * @since 1.0.0
221     */
222    public @NonNull ScimContentTypeResult validateContentTypeResult(
223            @NonNull List<@NonNull String> rawHeaderValues) {
224        requireNonNull(rawHeaderValues);
225        ScimWork work = work();
226        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
227        return process(
228                ScimObserver.Operation.CONTENT_TYPE,
229                used,
230                () -> media(rawHeaderValues, work),
231                () -> new ScimContentTypeResult.Rejected(ScimError.internalErrorInstance()));
232    }
233
234    /** Parses, binds and approves the complete normalized filter under the configured policy.
235     * Syntax alone grants no query permission. Applications execute the returned tree and separately
236     * authorize the caller and tenant; this operation executes no storage query.
237     * @param resourceType the exact registered resource-type object
238     * @param expression the complete untrusted filter expression
239     * @return the checked direct result
240     * @since 1.0.0
241     */
242    public @NonNull ScimFilterParseResult parseFilterResult(
243            @NonNull ScimResourceType resourceType, @NonNull String expression) {
244        registered(resourceType);
245        requireNonNull(expression);
246        ScimWork work = work();
247        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
248        return process(
249                ScimObserver.Operation.FILTER,
250                used,
251                () -> binding(resourceType).bind(expression, used, work),
252                () -> new ScimFilterParseResult.Rejected(ScimError.internalErrorInstance()));
253    }
254
255    @NonNull ScimFilterEvaluationResult evaluateFilterResult(
256            @NonNull ScimResource resource, @NonNull ScimFilter filter) {
257        ScimWork work = work();
258        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
259        return process(
260                ScimObserver.Operation.FILTER_EVALUATE,
261                used,
262                () -> {
263                    if (!associated(resource))
264                        return new ScimFilterEvaluationResult.Rejected(ScimError.invalidValueInstance());
265                    String expression = ScimFilterEvaluation.expression(filter, limits.getFilterLimits(), work);
266                    if (expression == null)
267                        return new ScimFilterEvaluationResult.Rejected(work.wasExceeded()
268                                ? ScimError.requestTooLargeInstance() : ScimError.invalidFilterInstance());
269                    ScimFilterParseResult rebound = binding(resource.getResourceType()).bind(expression, used, work);
270                    if (rebound instanceof ScimFilterParseResult.Rejected rejected)
271                        return new ScimFilterEvaluationResult.Rejected(work.wasExceeded()
272                                ? ScimError.requestTooLargeInstance() : rejected.getError());
273                    return ScimFilterEvaluation.evaluate(resource,
274                            ((ScimFilterParseResult.Succeeded) rebound).getFilter(),
275                            requireNonNull(stringMatching), work);
276                },
277                () -> new ScimFilterEvaluationResult.Rejected(ScimError.internalErrorInstance()));
278    }
279
280    /** Parses a raw GET collection query with strict bounded decoding and complete filter approval.
281     * Preserve physical repeated fields; do not first pass through a framework parameter map.
282     * Raw plus means space and percent escapes are decoded strictly. Applications own execution,
283     * authorization and cursor authenticity/context binding.
284     * @param resourceType the exact registered resource-type object
285     * @param rawQuery the original undecoded query without a leading question mark, or empty when absent
286     * @return the checked direct result
287     * @since 1.0.0
288     */
289    public @NonNull ScimQueryParseResult parseQueryResult(
290            @NonNull ScimResourceType resourceType, @NonNull String rawQuery) {
291        registered(resourceType);
292        requireNonNull(rawQuery);
293        ScimWork work = work();
294        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
295        return process(
296                ScimObserver.Operation.QUERY,
297                used,
298                () ->
299                        ScimQueries.query(
300                                resourceType,
301                                rawQuery,
302                                serviceProviderConfig,
303                                limits,
304                                compatibility,
305                                semanticContext,
306                                binding(resourceType),
307                                used,
308                                work),
309                () -> new ScimQueryParseResult.Rejected(ScimError.internalErrorInstance()));
310    }
311
312    /** Parses a bound projection from the original raw query, separately from caller authorization.
313     * Preserve physical repeated fields and undecoded text before framework parameter normalization.
314     * The returned selection retains this provider's semantic registration.
315     * @param resourceType the exact registered resource-type object
316     * @param rawQuery the original undecoded query without a leading question mark, or empty when absent
317     * @return the checked direct result
318     * @since 1.0.0
319     */
320    public @NonNull ScimAttributeSelectionResult parseAttributeSelectionResult(
321            @NonNull ScimResourceType resourceType, @NonNull String rawQuery) {
322        registered(resourceType);
323        requireNonNull(rawQuery);
324        ScimWork work = work();
325        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
326        return process(
327                ScimObserver.Operation.ATTRIBUTE_SELECTION,
328                used,
329                () -> ScimQueries.selection(resourceType, rawQuery, limits, semanticContext, work),
330                () -> new ScimAttributeSelectionResult.Rejected(ScimError.internalErrorInstance()));
331    }
332
333    /** Checks weak opaque-version If-Match against the existing resource, deliberately differing
334     * from general HTTP strong comparison. Absence succeeds; an isolated wildcard tests existence.
335     * Applications check this exact authoritative resource under the write's lock/version predicate.
336     * @param rawHeaderValues original physical If-Match values, or an empty list when absent
337     * @param current the authoritative existing resource from that transaction
338     * @return the checked direct result
339     * @since 1.0.0
340     */
341    public @NonNull ScimIfMatchResult checkIfMatchResult(
342            @NonNull List<@NonNull String> rawHeaderValues, @NonNull ScimResource current) {
343        requireNonNull(rawHeaderValues);
344        registered(requireNonNull(current).getResourceType());
345        ScimWork work = work();
346        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
347        return process(
348                ScimObserver.Operation.IF_MATCH,
349                used,
350                () ->
351                        !headerWork(rawHeaderValues, limits.getMaximumConditionalTags(), work)
352                                ? new ScimIfMatchResult.Rejected(
353                                        ScimError.requestTooLargeInstance())
354                                : associated(current)
355                                        ? ScimHeaders.ifMatch(rawHeaderValues, current, limits)
356                                        : new ScimIfMatchResult.Rejected(
357                                                ScimError.invalidValueInstance()),
358                () -> new ScimIfMatchResult.Rejected(ScimError.internalErrorInstance()));
359    }
360
361    /** Checks original conditional-read tags against the authoritative existing resource using weak
362     * opaque-version comparison. Absence proceeds; an isolated wildcard can report NotModified
363     * without a version. Applications own the corresponding GET/HEAD route and read consistency.
364     * @param rawHeaderValues original physical If-None-Match values, or an empty list when absent
365     * @param current the authoritative existing resource
366     * @return the checked direct result
367     * @since 1.0.0
368     */
369    public @NonNull ScimIfNoneMatchResult checkIfNoneMatchResult(
370            @NonNull List<@NonNull String> rawHeaderValues, @NonNull ScimResource current) {
371        requireNonNull(rawHeaderValues);
372        registered(requireNonNull(current).getResourceType());
373        ScimWork work = work();
374        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
375        return process(
376                ScimObserver.Operation.IF_NONE_MATCH,
377                used,
378                () ->
379                        !headerWork(rawHeaderValues, limits.getMaximumConditionalTags(), work)
380                                ? new ScimIfNoneMatchResult.Rejected(
381                                        ScimError.requestTooLargeInstance())
382                                : associated(current)
383                                        ? ScimHeaders.ifNoneMatch(rawHeaderValues, current, limits)
384                                        : new ScimIfNoneMatchResult.Rejected(
385                                                ScimError.invalidValueInstance()),
386                () -> new ScimIfNoneMatchResult.Rejected(ScimError.internalErrorInstance()));
387    }
388
389    /** Parses a search body after validating original media-type fields.
390     * @param resourceType the exact registered resource-type object
391     * @param contentTypeHeaderValues original physical media-type occurrences
392     * @param body untrusted UTF-8 JSON; empty bytes reject
393     * @return a checked candidate or fixed error
394     * @since 1.0.0
395     */
396    public @NonNull ScimQueryParseResult parseSearchRequestResult(
397            @NonNull ScimResourceType resourceType,
398            @NonNull List<@NonNull String> contentTypeHeaderValues,
399            byte @NonNull [] body) {
400        registered(resourceType);
401        requireNonNull(body);
402        requireNonNull(contentTypeHeaderValues);
403        ScimWork work = work();
404        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
405        return process(
406                ScimObserver.Operation.SEARCH,
407                used,
408                () -> {
409                    ScimContentTypeResult media = media(contentTypeHeaderValues, work);
410                    if (media instanceof ScimContentTypeResult.Rejected rejected)
411                        return new ScimQueryParseResult.Rejected(rejected.getError());
412                    Body parsed = parse(body, work);
413                    if (parsed.error != null)
414                        return new ScimQueryParseResult.Rejected(parsed.error);
415                    JsonDocument document = requireNonNull(parsed.document);
416                    return ScimQueries.search(
417                            resourceType,
418                            document,
419                            serviceProviderConfig,
420                            limits,
421                            compatibility,
422                            semanticContext,
423                            binding(resourceType),
424                            used,
425                            work);
426                },
427                () -> new ScimQueryParseResult.Rejected(ScimError.internalErrorInstance()));
428    }
429
430    /** Parses a search body whose HTTP framing and media type were already validated.
431     * @param resourceType the exact registered resource-type object
432     * @param body untrusted UTF-8 JSON; empty bytes reject
433     * @return a checked candidate or fixed error
434     * @since 1.0.0
435     */
436    public @NonNull ScimQueryParseResult parseSearchRequestResult(
437            @NonNull ScimResourceType resourceType, byte @NonNull [] body) {
438        registered(resourceType);
439        requireNonNull(body);
440        ScimWork work = work();
441        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
442        return process(
443                ScimObserver.Operation.SEARCH,
444                used,
445                () -> {
446                    Body parsed = parse(body, work);
447                    if (parsed.error != null)
448                        return new ScimQueryParseResult.Rejected(parsed.error);
449                    JsonDocument document = requireNonNull(parsed.document);
450                    return ScimQueries.search(
451                            resourceType,
452                            document,
453                            serviceProviderConfig,
454                            limits,
455                            compatibility,
456                            semanticContext,
457                            binding(resourceType),
458                            used,
459                            work);
460                },
461                () -> new ScimQueryParseResult.Rejected(ScimError.internalErrorInstance()));
462    }
463
464    /** Parses a create body after validating original media-type fields.
465     * @param resourceType the exact registered resource-type object
466     * @param contentTypeHeaderValues original physical media-type occurrences
467     * @param body untrusted UTF-8 JSON; empty bytes reject
468     * @return a checked candidate or fixed error
469     * @since 1.0.0
470     */
471    public @NonNull ScimResourceParseResult parseResourceResult(
472            @NonNull ScimResourceType resourceType,
473            @NonNull List<@NonNull String> contentTypeHeaderValues,
474            byte @NonNull [] body) {
475        registered(resourceType);
476        requireNonNull(body);
477        requireNonNull(contentTypeHeaderValues);
478        ScimWork work = work();
479        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
480        return process(
481                ScimObserver.Operation.RESOURCE_CREATE,
482                used,
483                () -> {
484                    ScimContentTypeResult media = media(contentTypeHeaderValues, work);
485                    if (media instanceof ScimContentTypeResult.Rejected rejected)
486                        return new ScimResourceParseResult.Rejected(rejected.getError());
487                    Body parsed = parse(body, work);
488                    if (parsed.error != null)
489                        return new ScimResourceParseResult.Rejected(parsed.error);
490                    JsonDocument document = requireNonNull(parsed.document);
491                    return ScimResources.create(
492                            resourceType, document, compatibility, work, semanticContext, used);
493                },
494                () -> new ScimResourceParseResult.Rejected(ScimError.internalErrorInstance()));
495    }
496
497    /** Parses a create body whose HTTP framing and media type were already validated.
498     * @param resourceType the exact registered resource-type object
499     * @param body untrusted UTF-8 JSON; empty bytes reject
500     * @return a checked candidate or fixed error
501     * @since 1.0.0
502     */
503    public @NonNull ScimResourceParseResult parseResourceResult(
504            @NonNull ScimResourceType resourceType, byte @NonNull [] body) {
505        registered(resourceType);
506        requireNonNull(body);
507        ScimWork work = work();
508        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
509        return process(
510                ScimObserver.Operation.RESOURCE_CREATE,
511                used,
512                () -> {
513                    Body parsed = parse(body, work);
514                    if (parsed.error != null)
515                        return new ScimResourceParseResult.Rejected(parsed.error);
516                    JsonDocument document = requireNonNull(parsed.document);
517                    return ScimResources.create(
518                            resourceType, document, compatibility, work, semanticContext, used);
519                },
520                () -> new ScimResourceParseResult.Rejected(ScimError.internalErrorInstance()));
521    }
522
523    /** Parses a replace body after validating original media-type fields.
524     * @param resourceType the exact registered resource-type object
525     * @param current the immutable authoritative current resource
526     * @param contentTypeHeaderValues original physical media-type occurrences
527     * @param body untrusted UTF-8 JSON; empty bytes reject
528     * @return a checked candidate or fixed error
529     * @since 1.0.0
530     */
531    public @NonNull ScimResourceParseResult parseReplacementResult(
532            @NonNull ScimResourceType resourceType,
533            @NonNull ScimResource current,
534            @NonNull List<@NonNull String> contentTypeHeaderValues,
535            byte @NonNull [] body) {
536        registered(resourceType);
537        requireNonNull(body);
538        requireNonNull(current);
539        if (!same(current.getResourceType(), resourceType))
540            throw new IllegalArgumentException("SCIM replacement type mismatch.");
541        requireNonNull(contentTypeHeaderValues);
542        ScimWork work = work();
543        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
544        return process(
545                ScimObserver.Operation.RESOURCE_REPLACE,
546                used,
547                () -> {
548                    if (!associated(current))
549                        return new ScimResourceParseResult.Rejected(
550                                ScimError.invalidValueInstance());
551                    ScimContentTypeResult media = media(contentTypeHeaderValues, work);
552                    if (media instanceof ScimContentTypeResult.Rejected rejected)
553                        return new ScimResourceParseResult.Rejected(rejected.getError());
554                    Body parsed = parse(body, work);
555                    if (parsed.error != null)
556                        return new ScimResourceParseResult.Rejected(parsed.error);
557                    JsonDocument document = requireNonNull(parsed.document);
558                    return ScimResources.replace(
559                            resourceType,
560                            current,
561                            document,
562                            compatibility,
563                            work,
564                            semanticContext,
565                            used);
566                },
567                () -> new ScimResourceParseResult.Rejected(ScimError.internalErrorInstance()));
568    }
569
570    /** Parses a replace body whose HTTP framing and media type were already validated.
571     * @param resourceType the exact registered resource-type object
572     * @param current the immutable authoritative current resource
573     * @param body untrusted UTF-8 JSON; empty bytes reject
574     * @return a checked candidate or fixed error
575     * @since 1.0.0
576     */
577    public @NonNull ScimResourceParseResult parseReplacementResult(
578            @NonNull ScimResourceType resourceType,
579            @NonNull ScimResource current,
580            byte @NonNull [] body) {
581        registered(resourceType);
582        requireNonNull(body);
583        requireNonNull(current);
584        if (!same(current.getResourceType(), resourceType))
585            throw new IllegalArgumentException("SCIM replacement type mismatch.");
586        ScimWork work = work();
587        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
588        return process(
589                ScimObserver.Operation.RESOURCE_REPLACE,
590                used,
591                () -> {
592                    if (!associated(current))
593                        return new ScimResourceParseResult.Rejected(
594                                ScimError.invalidValueInstance());
595                    Body parsed = parse(body, work);
596                    if (parsed.error != null)
597                        return new ScimResourceParseResult.Rejected(parsed.error);
598                    JsonDocument document = requireNonNull(parsed.document);
599                    return ScimResources.replace(
600                            resourceType,
601                            current,
602                            document,
603                            compatibility,
604                            work,
605                            semanticContext,
606                            used);
607                },
608                () -> new ScimResourceParseResult.Rejected(ScimError.internalErrorInstance()));
609    }
610
611    /** Parses ordered PATCH operations after validating original media-type fields.
612     * @param resourceType the exact registered resource-type object
613     * @param contentTypeHeaderValues original physical media-type occurrences
614     * @param body untrusted UTF-8 PatchOp JSON; empty bytes reject
615     * @return a schema-bound request or fixed error
616     * @since 1.0.0
617     */
618    public @NonNull ScimPatchParseResult parsePatchRequestResult(
619            @NonNull ScimResourceType resourceType,
620            @NonNull List<@NonNull String> contentTypeHeaderValues,
621            byte @NonNull [] body) {
622        registered(resourceType);
623        requireNonNull(contentTypeHeaderValues);
624        requireNonNull(body);
625        ScimWork work = work();
626        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
627        return process(
628                ScimObserver.Operation.PATCH_PARSE,
629                used,
630                () -> {
631                    if (!serviceProviderConfig.isPatchSupported())
632                        return new ScimPatchParseResult.Rejected(ScimError.forbiddenInstance());
633                    ScimContentTypeResult media = media(contentTypeHeaderValues, work);
634                    if (media instanceof ScimContentTypeResult.Rejected rejected)
635                        return new ScimPatchParseResult.Rejected(rejected.getError());
636                    Body parsed = parse(body, work);
637                    if (parsed.error != null)
638                        return new ScimPatchParseResult.Rejected(parsed.error);
639                    return ScimPatchParsing.parse(resourceType, requireNonNull(parsed.document),
640                            compatibility, limits, work, semanticContext, used);
641                },
642                () -> new ScimPatchParseResult.Rejected(ScimError.internalErrorInstance()));
643    }
644
645    /** Parses PATCH bytes whose transport framing and media type were already validated.
646     * @param resourceType the exact registered resource-type object
647     * @param body untrusted UTF-8 PatchOp JSON; empty bytes reject
648     * @return a schema-bound request or fixed error
649     * @since 1.0.0
650     */
651    public @NonNull ScimPatchParseResult parsePatchRequestResult(
652            @NonNull ScimResourceType resourceType, byte @NonNull [] body) {
653        registered(resourceType);
654        requireNonNull(body);
655        ScimWork work = work();
656        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
657        return process(
658                ScimObserver.Operation.PATCH_PARSE,
659                used,
660                () -> {
661                    if (!serviceProviderConfig.isPatchSupported())
662                        return new ScimPatchParseResult.Rejected(ScimError.forbiddenInstance());
663                    Body parsed = parse(body, work);
664                    if (parsed.error != null)
665                        return new ScimPatchParseResult.Rejected(parsed.error);
666                    return ScimPatchParsing.parse(resourceType, requireNonNull(parsed.document),
667                            compatibility, limits, work, semanticContext, used);
668                },
669                () -> new ScimPatchParseResult.Rejected(ScimError.internalErrorInstance()));
670    }
671
672    /** Applies every ordered operation to an immutable candidate, publishing only after final validation.
673     * Applications authorize attempted and effective paths and persist the candidate atomically.
674     * @param current authoritative resource from the application's transaction
675     * @param patch schema-bound request from this semantic registration
676     * @return a complete candidate with change/provenance paths or fixed error
677     * @since 1.0.0
678     */
679    public @NonNull ScimPatchApplicationResult applyPatchResult(
680            @NonNull ScimResource current, @NonNull ScimPatchRequest patch) {
681        requireNonNull(current);
682        requireNonNull(patch);
683        registered(current.getResourceType());
684        ScimWork work = work();
685        Set<ScimCompatibilityFeature> used = EnumSet.noneOf(ScimCompatibilityFeature.class);
686        return process(
687                ScimObserver.Operation.PATCH_APPLY,
688                used,
689                () -> {
690                    ScimStringMatching matching = stringMatching;
691                    if (!serviceProviderConfig.isPatchSupported() || matching == null)
692                        return new ScimPatchApplicationResult.Rejected(ScimError.forbiddenInstance());
693                    if (!associated(current) || !associated(patch)
694                            || !same(current.getResourceType(), patch.getResourceType()))
695                        return new ScimPatchApplicationResult.Rejected(ScimError.invalidValueInstance());
696                    return ScimPatchEngine.apply(current, patch, compatibility, matching, work,
697                            semanticContext, used);
698                },
699                () -> new ScimPatchApplicationResult.Rejected(ScimError.internalErrorInstance()));
700    }
701
702    /** Reduces supported standard Group membership operations into ordered ID steps without reading storage.
703     * Metadata-dependent operations require full evaluation. The application executes all steps and the
704     * remainder under one authorization decision and transaction/version predicate.
705     * @param patch schema-bound request from this semantic registration
706     * @return ordered steps, full-evaluation requirement or fixed error
707     * @since 1.0.0
708     */
709    public @NonNull ScimMembershipPatchResult reduceMembershipPatchResult(@NonNull ScimPatchRequest patch) {
710        requireNonNull(patch);
711        ScimWork work = work();
712        return process(
713                ScimObserver.Operation.MEMBERSHIP_REDUCE,
714                Set.of(),
715                () -> {
716                    if (!serviceProviderConfig.isPatchSupported())
717                        return new ScimMembershipPatchResult.Rejected(ScimError.forbiddenInstance());
718                    if (!associated(patch))
719                        return new ScimMembershipPatchResult.Rejected(ScimError.invalidValueInstance());
720                    return ScimMembershipReduction.reduce(patch, work);
721                },
722                () -> new ScimMembershipPatchResult.Rejected(ScimError.internalErrorInstance()));
723    }
724
725    /** Encodes an authoritative ID as one path segment beneath the trusted type endpoint.
726     * ASCII letters, digits and {@code -._~} remain literal; other UTF-8 bytes use uppercase
727     * percent escapes. Standalone {@code .} and {@code ..} identifiers are rejected before encoding.
728     * Existing percent escapes in the opaque ID are data, not instructions to decode.
729     * @param resourceType the exact registered resource-type object
730     * @param authoritativeId application-assigned identifier
731     * @return an absolute resource location
732     * @since 1.0.0
733     */
734    public @NonNull URI resourceLocationFor(
735            @NonNull ScimResourceType resourceType, @NonNull String authoritativeId) {
736        registered(resourceType);
737        ScimSchemas.requireText(requireNonNull(authoritativeId), false);
738        if (!ScimResourceValidation.validResourceId(authoritativeId))
739            throw new IllegalArgumentException("Invalid SCIM resource identifier.");
740        StringBuilder segment = new StringBuilder();
741        for (byte octet : authoritativeId.getBytes(StandardCharsets.UTF_8)) {
742            int value = octet & 255;
743            if ((value >= 'a' && value <= 'z')
744                    || (value >= 'A' && value <= 'Z')
745                    || (value >= '0' && value <= '9')
746                    || value == '-'
747                    || value == '.'
748                    || value == '_'
749                    || value == '~') segment.append((char) value);
750            else {
751                segment.append('%');
752                segment.append("0123456789ABCDEF".charAt(value >>> 4));
753                segment.append("0123456789ABCDEF".charAt(value & 15));
754            }
755        }
756        return URI.create(
757                baseUri.toASCIIString() + resourceType.getEndpoint().substring(1) + "/" + segment);
758    }
759
760    /** Prepares a GET resource response without write provenance.
761     * @param resource resource to render
762     * @param selection bound projection
763     * @return a bounded prepared response or fixed error
764     * @since 1.0.0
765     */
766    public @NonNull ScimResponseResult resourceResponseResult(
767            @NonNull ScimResource resource, @NonNull ScimAttributeSelection selection) {
768        return response(resource, Set.of(), selection, false, 200);
769    }
770
771    /** Prepares a replacement response from the final authorized candidate with authoritative metadata.
772     * Prepare before commit where preparation can fail, and emit only after confirmed persistence.
773     * Supplied paths are trusted application provenance from parsing, separately from attempted or
774     * modified authorization targets. The bare set has no private parser/configuration proof; its
775     * paths are validated against the target schema. Preparation proves neither authorization nor persistence.
776     * @param replaced the final application-assigned replacement candidate
777     * @param suppliedPaths canonical paths actually supplied, from the resource parse result
778     * @param selection the bound projection from this semantic registration
779     * @return a bounded prepared response or fixed error
780     * @since 1.0.0
781     */
782    public @NonNull ScimResponseResult replacementResponseResult(
783            @NonNull ScimResource replaced,
784            @NonNull Set<@NonNull ScimAttributePath> suppliedPaths,
785            @NonNull ScimAttributeSelection selection) {
786        return response(replaced, suppliedPaths, selection, true, 200);
787    }
788
789    /** Prepares creation from the final authorized candidate with authoritative ID and metadata.
790     * Location comes from the trusted base/type endpoint, and any existing meta.location must agree.
791     * Prepare before commit where preparation can fail, and emit only after confirmed persistence.
792     * Supplied paths are trusted application provenance from parsing, not attempted/modified targets.
793     * The bare set has no private parser/configuration proof; its paths are checked against the target
794     * schema. Preparation proves neither authorization nor persistence.
795     * @param created the final application-assigned creation candidate with an assigned ID
796     * @param suppliedPaths canonical paths actually supplied, from the resource parse result
797     * @param selection the bound projection from this semantic registration
798     * @return a bounded prepared response or fixed error
799     * @since 1.0.0
800     */
801    public @NonNull ScimResponseResult createdResponseResult(
802            @NonNull ScimResource created,
803            @NonNull Set<@NonNull ScimAttributePath> suppliedPaths,
804            @NonNull ScimAttributeSelection selection) {
805        return response(created, suppliedPaths, selection, true, 201);
806    }
807
808    /** Prepares the final authorized PATCH candidate after application-assigned authoritative metadata.
809     * Prepare before commit where preparation can fail, and emit only after confirmed persistence.
810     * The resource type's default is used unless either projection parameter was supplied, which
811     * forces status 200. Bodyless responses retain authoritative ETag and bounded headers.
812     * Supplied paths are trusted application provenance from PATCH application, not attempted/modified
813     * authorization targets. The bare set has no private parser/configuration proof; its paths are
814     * checked against the target schema. Preparation proves neither authorization nor persistence.
815     * @param persistedCandidate the final application-assigned candidate; persistence need not precede preparation
816     * @param suppliedPaths canonical paths actually supplied, from the PATCH application result
817     * @param selection the bound response projection from this semantic registration
818     * @return a bounded prepared response or fixed error
819     * @since 1.0.0
820     */
821    public @NonNull ScimResponseResult patchResponseResult(
822            @NonNull ScimResource persistedCandidate,
823            @NonNull Set<@NonNull ScimAttributePath> suppliedPaths,
824            @NonNull ScimAttributeSelection selection) {
825        requireNonNull(persistedCandidate);
826        requireNonNull(selection);
827        int status = persistedCandidate.getResourceType().isPatchResponseNoContent()
828                && !selection.isExplicit() ? 204 : 200;
829        return response(persistedCandidate, suppliedPaths, selection, true, status);
830    }
831
832    private @NonNull ScimResponseResult response(
833            @NonNull ScimResource resource,
834            @NonNull Set<@NonNull ScimAttributePath> supplied,
835            @NonNull ScimAttributeSelection selection,
836            boolean write,
837            int status) {
838        requireNonNull(resource);
839        requireNonNull(selection);
840        requireNonNull(supplied);
841        registered(resource.getResourceType());
842        ScimWork work = work();
843        return process(
844                ScimObserver.Operation.RESPONSE_PREPARE,
845                Set.of(),
846                () -> {
847                    if (!associated(resource)
848                            || resource.getId().isEmpty()
849                            || !associated(selection)
850                            || !same(resource.getResourceType(), selection.getResourceType())
851                            || !supplied(resource.getResourceType(), supplied, work))
852                        return responseError(ScimError.invalidValueInstance());
853                    if (status == 204)
854                        return ScimResponses.prepare(limits, 204, null, etag(resource), work);
855                    JsonObject body =
856                            ScimResources.project(resource, selection, supplied, write, work);
857                    if (body == null) return responseError(ScimError.responseTooLargeInstance());
858                    Map<String, List<String>> headers = etag(resource);
859                    if (status == 201) {
860                        if (resource.getId().isEmpty())
861                            return responseError(ScimError.invalidValueInstance());
862                        URI location =
863                                resourceLocationFor(
864                                        resource.getResourceType(), resource.getId().get());
865                        if (resource.getLocation().isPresent()
866                                && !resource.getLocation().get().equals(location))
867                            return responseError(ScimError.invalidValueInstance());
868                        LinkedHashMap<String, JsonValue> members =
869                                new LinkedHashMap<>(body.getMembers());
870                        JsonValue original = members.get("meta");
871                        LinkedHashMap<String, JsonValue> meta =
872                                new LinkedHashMap<>(
873                                        original instanceof JsonObject object
874                                                ? object.getMembers()
875                                                : Map.of());
876                        meta.put("location", JsonString.fromValue(location.toASCIIString()));
877                        members.put("meta", JsonObject.fromMembers(meta));
878                        body = JsonObject.fromMembers(members);
879                        headers = new LinkedHashMap<>(headers);
880                        headers.put("Location", List.of(location.toASCIIString()));
881                    }
882                    return ScimResponses.prepare(limits, status, body, headers, work);
883                },
884                () -> responseError(ScimError.internalErrorInstance()));
885    }
886
887    /** Prepares a truthful index or cursor ListResponse from an application-produced page.
888     * @param page checked page and its originating query
889     * @return a bounded prepared response or fixed error
890     * @since 1.0.0
891     */
892    public @NonNull ScimResponseResult listResponseResult(@NonNull ScimListPage page) {
893        requireNonNull(page);
894        ScimWork work = work();
895        return process(
896                ScimObserver.Operation.RESPONSE_PREPARE,
897                Set.of(),
898                () -> {
899                    ScimQuery query = page.getQuery();
900                    if (!same(query.getSemanticContext(), semanticContext)
901                            || !registeredIdentity(query.getResourceType()))
902                        return responseError(ScimError.invalidValueInstance());
903                    List<JsonValue> values = new ArrayList<>();
904                    for (ScimResource resource : page.getResources()) {
905                        if (!work.take(1))
906                            return responseError(ScimError.responseTooLargeInstance());
907                        if (!associated(resource) || resource.getId().isEmpty())
908                            return responseError(ScimError.invalidValueInstance());
909                        JsonObject body =
910                                ScimResources.project(
911                                        resource,
912                                        query.getAttributeSelection(),
913                                        Set.of(),
914                                        false,
915                                        work);
916                        if (body == null)
917                            return responseError(ScimError.responseTooLargeInstance());
918                        values.add(body);
919                    }
920                    Map<String, JsonValue> body = list(values);
921                    page.getTotalResults()
922                            .ifPresent(
923                                    value -> body.put("totalResults", JsonNumber.fromValue(value)));
924                    query.getStartIndex()
925                            .ifPresent(
926                                    value -> body.put("startIndex", JsonNumber.fromValue(value)));
927                    page.getNextCursor()
928                            .ifPresent(
929                                    value -> body.put("nextCursor", JsonString.fromValue(value)));
930                    page.getPreviousCursor()
931                            .ifPresent(
932                                    value ->
933                                            body.put(
934                                                    "previousCursor", JsonString.fromValue(value)));
935                    return ScimResponses.prepare(
936                            limits, 200, JsonObject.fromMembers(body), Map.of(), work);
937                },
938                () -> responseError(ScimError.internalErrorInstance()));
939    }
940
941    /** Prepares bounded discovery with projection; discovery filters reject.
942     * @param rawQuery the original undecoded query without a leading question mark, or empty when absent
943     * @return discovery or a fixed error
944     * @since 1.0.0
945     */
946    public @NonNull ScimResponseResult serviceProviderConfigResponseResult(
947            @NonNull String rawQuery) {
948        return discovery("config", null, requireNonNull(rawQuery));
949    }
950
951    /** Prepares bounded discovery with projection; discovery filters reject.
952     * @param rawQuery the original undecoded query without a leading question mark, or empty when absent
953     * @return discovery or a fixed error
954     * @since 1.0.0
955     */
956    public @NonNull ScimResponseResult resourceTypesResponseResult(@NonNull String rawQuery) {
957        return discovery("types", null, requireNonNull(rawQuery));
958    }
959
960    /** Prepares bounded discovery with projection; discovery filters reject.
961     * @param resourceTypeName registered case-exact type name
962     * @param rawQuery the original undecoded query without a leading question mark, or empty when absent
963     * @return discovery or a fixed error
964     * @since 1.0.0
965     */
966    public @NonNull ScimResponseResult resourceTypeResponseResult(
967            @NonNull String resourceTypeName, @NonNull String rawQuery) {
968        requireNonNull(resourceTypeName);
969        return discovery("type", resourceTypeName, requireNonNull(rawQuery));
970    }
971
972    /** Prepares bounded discovery with projection; discovery filters reject.
973     * @param rawQuery the original undecoded query without a leading question mark, or empty when absent
974     * @return discovery or a fixed error
975     * @since 1.0.0
976     */
977    public @NonNull ScimResponseResult schemasResponseResult(@NonNull String rawQuery) {
978        return discovery("schemas", null, requireNonNull(rawQuery));
979    }
980
981    /** Prepares bounded discovery with projection; discovery filters reject.
982     * @param schemaId registered schema identifier
983     * @param rawQuery the original undecoded query without a leading question mark, or empty when absent
984     * @return discovery or a fixed error
985     * @since 1.0.0
986     */
987    public @NonNull ScimResponseResult schemaResponseResult(
988            @NonNull String schemaId, @NonNull String rawQuery) {
989        requireNonNull(schemaId);
990        return discovery("schema", schemaId, requireNonNull(rawQuery));
991    }
992
993    private @NonNull ScimResponseResult discovery(
994            @NonNull String kind, @Nullable String selector, @NonNull String raw) {
995        ScimWork work = work();
996        return process(
997                ScimObserver.Operation.RESPONSE_PREPARE,
998                Set.of(),
999                () -> {
1000                    ScimResourceType descriptor =
1001                            kind.equals("config")
1002                                    ? DiscoveryTypes.CONFIG
1003                                    : kind.equals("type") || kind.equals("types")
1004                                            ? DiscoveryTypes.TYPE
1005                                            : DiscoveryTypes.SCHEMA;
1006                    ScimAttributeSelectionResult selected =
1007                            ScimQueries.discoverySelection(
1008                                    descriptor, raw, limits, semanticContext, work);
1009                    if (selected instanceof ScimAttributeSelectionResult.Rejected rejected)
1010                        return responseError(rejected.getError());
1011                    ScimAttributeSelection selection =
1012                            ((ScimAttributeSelectionResult.Succeeded) selected)
1013                                    .getAttributeSelection();
1014                    if (selector != null) {
1015                        long cap =
1016                                kind.equals("schema")
1017                                        ? Limits.SCIM_SCHEMA_ID_LENGTH.getCap()
1018                                        : Limits.SCIM_ATTRIBUTE_NAME_LENGTH.getCap();
1019                        if (selector.length() > cap)
1020                            return responseError(ScimError.requestTooLargeInstance());
1021                        if (!work.spend(selector.length()))
1022                            return responseError(ScimError.responseTooLargeInstance());
1023                    }
1024                    List<JsonObject> candidates = new ArrayList<>();
1025                    if (kind.equals("config")) {
1026                        if (!configurationWork(work))
1027                            return responseError(ScimError.responseTooLargeInstance());
1028                        candidates.add(ScimDiscovery.configuration(serviceProviderConfig));
1029                    } else if (kind.equals("type") || kind.equals("types")) {
1030                        for (ScimResourceType type : resourceTypes)
1031                            if (selector == null || type.getName().equals(selector)) {
1032                                if (!typeWork(type, work))
1033                                    return responseError(ScimError.responseTooLargeInstance());
1034                                candidates.add(ScimDiscovery.resourceType(type));
1035                            }
1036                    } else
1037                        for (ScimSchema schema : schemas)
1038                            if (selector == null
1039                                    || AsciiCase.fold(schema.getId())
1040                                            .equals(AsciiCase.fold(selector))) {
1041                                if (!schemaWork(schema, work))
1042                                    return responseError(ScimError.responseTooLargeInstance());
1043                                candidates.add(ScimDiscovery.schema(schema));
1044                            }
1045                    if (candidates.isEmpty() && selector != null)
1046                        return responseError(ScimError.notFoundInstance());
1047                    List<JsonValue> values = new ArrayList<>();
1048                    for (JsonObject body : candidates) {
1049                        JsonObject projected =
1050                                ScimResources.project(
1051                                        ScimResource.parsed(descriptor, body, semanticContext),
1052                                        selection,
1053                                        Set.of(),
1054                                        false,
1055                                        work);
1056                        if (projected == null)
1057                            return responseError(ScimError.responseTooLargeInstance());
1058                        values.add(projected);
1059                    }
1060                    JsonObject output;
1061                    if (kind.equals("types") || kind.equals("schemas")) {
1062                        Map<String, JsonValue> members = list(values);
1063                        members.put("totalResults", JsonNumber.fromValue((long) values.size()));
1064                        members.put("startIndex", JsonNumber.fromValue(1L));
1065                        output = JsonObject.fromMembers(members);
1066                    } else output = (JsonObject) values.get(0);
1067                    return ScimResponses.prepare(limits, 200, output, Map.of(), work);
1068                },
1069                () -> responseError(ScimError.internalErrorInstance()));
1070    }
1071
1072    // Reserve all descriptor visits and text before allocating their JSON representations.
1073    private static boolean schemaWork(@NonNull ScimSchema schema, @NonNull ScimWork work) {
1074        if (!work.spend(
1075                (long) schema.getId().length()
1076                        + schema.getName().length()
1077                        + schema.getDescription().orElse("").length())) return false;
1078        for (ScimAttributeDefinition definition : schema.getAttributes())
1079            if (!definitionWork(definition, work)) return false;
1080        return true;
1081    }
1082
1083    private static boolean definitionWork(
1084            @NonNull ScimAttributeDefinition definition, @NonNull ScimWork work) {
1085        // Covers emitted facet nodes as well as the subsequent immutable-model scans.
1086        if (!work.spend(
1087                16L
1088                        + definition.getName().length()
1089                        + definition.getDescription().orElse("").length())) return false;
1090        for (String value : definition.getCanonicalValues())
1091            if (!work.spend(2L + value.length())) return false;
1092        for (String value : definition.getReferenceTypes())
1093            if (!work.spend(2L + value.length())) return false;
1094        for (ScimAttributeDefinition child : definition.getSubAttributes())
1095            if (!definitionWork(child, work)) return false;
1096        return true;
1097    }
1098
1099    private static boolean typeWork(@NonNull ScimResourceType type, @NonNull ScimWork work) {
1100        if (!work.spend(
1101                16L
1102                        + type.getName().length()
1103                        + type.getEndpoint().length()
1104                        + type.getSchema().getId().length()
1105                        + type.getId().orElse("").length()
1106                        + type.getDescription().orElse("").length())) return false;
1107        for (ScimSchemaExtension extension : type.getSchemaExtensions())
1108            if (!work.spend(4L + extension.getSchema().getId().length())) return false;
1109        return true;
1110    }
1111
1112    private boolean configurationWork(@NonNull ScimWork work) {
1113        if (!work.spend(
1114                32L
1115                        + serviceProviderConfig
1116                                .getDocumentationUri()
1117                                .map(URI::toString)
1118                                .orElse("")
1119                                .length())) return false;
1120        for (ScimAuthenticationScheme scheme : serviceProviderConfig.getAuthenticationSchemes())
1121            if (!work.spend(
1122                    8L
1123                            + scheme.getType().length()
1124                            + scheme.getName().length()
1125                            + scheme.getDescription().length()
1126                            + scheme.getSpecUri().map(URI::toString).orElse("").length()
1127                            + scheme.getDocumentationUri().map(URI::toString).orElse("").length()))
1128                return false;
1129        return true;
1130    }
1131
1132    /** Returns the fixed bounded no-content response.
1133     * @return a bodyless 204 response
1134     * @since 1.0.0
1135     */
1136    public @NonNull ScimResponse noContentResponse() {
1137        return process(
1138                ScimObserver.Operation.RESPONSE_PREPARE,
1139                Set.of(),
1140                ScimResponses::noContent,
1141                () -> ScimResponses.error(ScimError.internalErrorInstance()));
1142    }
1143
1144    /** Prepares a bounded bodyless conditional read response with current ETag when enabled.
1145     * @param current authoritative existing resource
1146     * @return a bounded 304 response or fixed error
1147     * @since 1.0.0
1148     */
1149    public @NonNull ScimResponseResult notModifiedResponseResult(@NonNull ScimResource current) {
1150        requireNonNull(current);
1151        registered(current.getResourceType());
1152        ScimWork work = work();
1153        return process(
1154                ScimObserver.Operation.RESPONSE_PREPARE,
1155                Set.of(),
1156                () ->
1157                        associated(current)
1158                                ? ScimResponses.prepare(limits, 304, null, etag(current), work)
1159                                : responseError(ScimError.invalidValueInstance()),
1160                () -> responseError(ScimError.internalErrorInstance()));
1161    }
1162
1163    /** Returns a fixed bounded error without including request data or causes.
1164     * @param error fixed core error
1165     * @return an error response
1166     * @since 1.0.0
1167     */
1168    public @NonNull ScimResponse errorResponse(@NonNull ScimError error) {
1169        requireNonNull(error);
1170        return process(
1171                ScimObserver.Operation.RESPONSE_PREPARE,
1172                Set.of(),
1173                () -> ScimResponses.error(error),
1174                () -> ScimResponses.error(ScimError.internalErrorInstance()));
1175    }
1176
1177    /** Returns a fixed redacted description.
1178     * @return a redacted description
1179     * @since 1.0.0
1180     */
1181    @Override
1182    public @NonNull String toString() {
1183        return "ScimServiceProvider{<redacted>}";
1184    }
1185
1186    private @NonNull Body parse(byte @NonNull [] body, @NonNull ScimWork work) {
1187        if (!work.spend(ScimWork.byteUnits(body.length))) return new Body(null, ScimError.requestTooLargeInstance());
1188        JsonParseResult result =
1189                JsonCodec.parseResult(
1190                        body,
1191                        JsonLimits.scim(
1192                                limits.getMaximumBodyBytes(), limits.getMaximumJsonNodes()));
1193        return result instanceof JsonParseResult.Succeeded success
1194                ? new Body(success.getDocument(), null)
1195                : new Body(null, jsonError((JsonParseResult.Rejected) result));
1196    }
1197
1198    private static final class Body {
1199        final @Nullable JsonDocument document;
1200        final @Nullable ScimError error;
1201
1202        Body(@Nullable JsonDocument document, @Nullable ScimError error) {
1203            this.document = document;
1204            this.error = error;
1205        }
1206    }
1207
1208    private static @NonNull ScimError jsonError(JsonParseResult.@NonNull Rejected rejected) {
1209        return rejected.getKind() == JsonParseException.Kind.INPUT_SIZE
1210                        || rejected.getKind() == JsonParseException.Kind.NODES
1211                        || rejected.getKind() == JsonParseException.Kind.DEPTH
1212                        || rejected.getKind() == JsonParseException.Kind.STRING_LENGTH
1213                        || rejected.getKind() == JsonParseException.Kind.NUMBER_LENGTH
1214                        || rejected.getKind() == JsonParseException.Kind.EXPONENT
1215                ? ScimError.requestTooLargeInstance()
1216                : ScimError.invalidSyntaxInstance();
1217    }
1218
1219    @SuppressWarnings(
1220            "ReferenceEquality") // Identity is the private registration/provenance capability.
1221    private static boolean same(@NonNull Object first, @NonNull Object second) {
1222        return first == second;
1223    }
1224
1225    private static boolean headerWork(
1226            @NonNull List<@NonNull String> values, int maximum, @NonNull ScimWork work) {
1227        if (values.size() > maximum) return false;
1228        for (String value : values)
1229            if (!work.spend(1L + 2L * requireNonNull(value).length())) return false;
1230        return true;
1231    }
1232
1233    private static @NonNull ScimContentTypeResult media(
1234            @NonNull List<@NonNull String> values, @NonNull ScimWork work) {
1235        if (values.size() != 1) return ScimHeaders.contentType(values);
1236        return headerWork(values, 1, work)
1237                ? ScimHeaders.contentType(values)
1238                : new ScimContentTypeResult.Rejected(ScimError.requestTooLargeInstance());
1239    }
1240
1241    private @NonNull ScimWork work() {
1242        return new ScimWork(limits.getMaximumWorkUnits());
1243    }
1244
1245    private @NonNull ScimFilterBinding binding(@NonNull ScimResourceType type) {
1246        return requireNonNull(bindings.get(type));
1247    }
1248
1249    private boolean registeredIdentity(@NonNull ScimResourceType type) {
1250        for (ScimResourceType registered : resourceTypes) if (same(type, registered)) return true;
1251        return false;
1252    }
1253
1254    private void registered(@NonNull ScimResourceType type) {
1255        if (!registeredIdentity(requireNonNull(type)))
1256            throw new IllegalArgumentException(
1257                    "SCIM resource type is not registered with this provider.");
1258    }
1259
1260    private boolean associated(@NonNull ScimResource resource) {
1261        Object context = resource.getSemanticContext();
1262        return registeredIdentity(resource.getResourceType())
1263                && (context == null || same(context, semanticContext));
1264    }
1265
1266    private boolean associated(@NonNull ScimAttributeSelection selection) {
1267        return registeredIdentity(selection.getResourceType())
1268                && same(selection.getSemanticContext(), semanticContext);
1269    }
1270
1271    private boolean associated(@NonNull ScimPatchRequest patch) {
1272        return registeredIdentity(patch.getResourceType())
1273                && same(patch.getSemanticContext(), semanticContext);
1274    }
1275
1276    private boolean supplied(
1277            @NonNull ScimResourceType type,
1278            @NonNull Set<@NonNull ScimAttributePath> paths,
1279            @NonNull ScimWork work) {
1280        if (paths.size() > Limits.SCIM_ATTRIBUTE_DEFINITIONS.getCap()) return false;
1281        for (ScimAttributePath path : paths) {
1282            if (!work.take(1)) return false;
1283            ScimAttributePath canonical =
1284                    ScimSchemas.canonicalPath(type, requireNonNull(path)).orElse(null);
1285            if (canonical == null || !canonical.equals(path)) return false;
1286        }
1287        return true;
1288    }
1289
1290    private @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> etag(
1291            @NonNull ScimResource resource) {
1292        return serviceProviderConfig.isEtagSupported() && resource.getVersion().isPresent()
1293                ? Map.of("ETag", List.of(resource.getVersion().get()))
1294                : Map.of();
1295    }
1296
1297    private static @NonNull Map<@NonNull String, @NonNull JsonValue> list(
1298            @NonNull List<@NonNull JsonValue> resources) {
1299        LinkedHashMap<String, JsonValue> body = new LinkedHashMap<>();
1300        body.put(
1301                "schemas",
1302                JsonArray.fromElements(
1303                        List.of(
1304                                JsonString.fromValue(
1305                                        "urn:ietf:params:scim:api:messages:2.0:ListResponse"))));
1306        body.put("Resources", JsonArray.fromElements(resources));
1307        body.put("itemsPerPage", JsonNumber.fromValue((long) resources.size()));
1308        return body;
1309    }
1310
1311    private static @NonNull ScimResponseResult responseError(@NonNull ScimError error) {
1312        return new ScimResponseResult.Rejected(error);
1313    }
1314
1315    private <R extends @NonNull Object> @NonNull R process(
1316            ScimObserver.@NonNull Operation operation,
1317            @NonNull Set<@NonNull ScimCompatibilityFeature> used,
1318            @NonNull Supplier<@NonNull R> action,
1319            @NonNull Supplier<@NonNull R> failure) {
1320        ObserverDispatch.dispatch(observer, value -> value.willProcess(operation));
1321        R result;
1322        try {
1323            result = requireNonNull(action.get());
1324        } catch (Throwable unexpected) {
1325            if (unexpected instanceof VirtualMachineError fatal) throw fatal;
1326            if (unexpected instanceof InterruptedException) Thread.currentThread().interrupt();
1327            for (ScimCompatibilityFeature feature : used)
1328                ObserverDispatch.dispatch(
1329                        observer, value -> value.didUseCompatibilityFeature(feature));
1330            ObserverDispatch.dispatch(observer, value -> value.didFailToProcess(operation));
1331            return requireNonNull(failure.get());
1332        }
1333        for (ScimCompatibilityFeature feature : used)
1334            ObserverDispatch.dispatch(observer, value -> value.didUseCompatibilityFeature(feature));
1335        ScimObserver.Outcome outcome = outcome(result);
1336        ObserverDispatch.dispatch(observer, value -> value.didProcess(operation, outcome));
1337        return result;
1338    }
1339
1340    private static ScimObserver.@NonNull Outcome outcome(@NonNull Object result) {
1341        if (result instanceof ScimResponse || result instanceof ScimResponseResult.Prepared)
1342            return ScimObserver.Outcome.PREPARED;
1343        if (result instanceof ScimIfMatchResult.Satisfied) return ScimObserver.Outcome.SATISFIED;
1344        if (result instanceof ScimIfNoneMatchResult.Proceed) return ScimObserver.Outcome.PROCEED;
1345        if (result instanceof ScimIfNoneMatchResult.NotModified)
1346            return ScimObserver.Outcome.NOT_MODIFIED;
1347        if (result instanceof ScimMembershipPatchResult.RequiresFullEvaluation)
1348            return ScimObserver.Outcome.REQUIRES_FULL_EVALUATION;
1349        if (result instanceof ScimContentTypeResult.Accepted
1350                || result instanceof ScimFilterParseResult.Succeeded
1351                || result instanceof ScimQueryParseResult.Succeeded
1352                || result instanceof ScimAttributeSelectionResult.Succeeded
1353                || result instanceof ScimResourceParseResult.Succeeded
1354                || result instanceof ScimPatchParseResult.Succeeded
1355                || result instanceof ScimPatchApplicationResult.Succeeded
1356                || result instanceof ScimFilterEvaluationResult.Succeeded
1357                || result instanceof ScimMembershipPatchResult.Reduced)
1358            return ScimObserver.Outcome.SUCCEEDED;
1359        return ScimObserver.Outcome.REJECTED;
1360    }
1361
1362    private static @Nullable ScimFilterPolicy identityPolicy(
1363            @NonNull Map<@NonNull ScimResourceType, @NonNull ScimFilterPolicy> policies,
1364            @NonNull ScimResourceType type) {
1365        for (Map.Entry<ScimResourceType, ScimFilterPolicy> entry : policies.entrySet())
1366            if (same(entry.getKey(), type)) return entry.getValue();
1367        return null;
1368    }
1369
1370    private static @NonNull URI base(@NonNull URI uri) {
1371        if (uri.toString().length() > Limits.SCIM_BASE_URI_LENGTH.getCap()
1372                || uri.toASCIIString().length() > Limits.SCIM_BASE_URI_LENGTH.getCap()
1373                || uri.getHost() == null
1374                || uri.getRawUserInfo() != null
1375                || uri.getRawQuery() != null
1376                || uri.getRawFragment() != null
1377                || !uri.isAbsolute()
1378                || !("http".equals(AsciiCase.fold(uri.getScheme()))
1379                        || "https".equals(AsciiCase.fold(uri.getScheme()))))
1380            throw new IllegalArgumentException(
1381                    "SCIM base URI requires bounded absolute HTTP(S) without credentials, query or fragment.");
1382        String path = uri.getRawPath();
1383        if (path == null) throw new IllegalArgumentException("SCIM base URI requires a path.");
1384        if (!path.isEmpty() && !path.equals("/"))
1385            ScimSchemas.requireEndpoint(
1386                    path.endsWith("/") ? path.substring(0, path.length() - 1) : path);
1387        String text = uri.toASCIIString();
1388        if (!text.endsWith("/")) text += "/";
1389        if (text.length() > Limits.SCIM_BASE_URI_LENGTH.getCap())
1390            throw new IllegalArgumentException("SCIM canonical base URI exceeds its bound.");
1391        return URI.create(text);
1392    }
1393
1394    private static @NonNull List<@NonNull ScimSchema> registrations(
1395            @NonNull List<@NonNull ScimResourceType> types) {
1396        Set<String> names = new LinkedHashSet<>(),
1397                endpoints = new LinkedHashSet<>(),
1398                ids = new LinkedHashSet<>();
1399        LinkedHashMap<String, ScimSchema> all = new LinkedHashMap<>();
1400        List<ScimSchema> reserved =
1401                List.of(
1402                        ScimSchema.userInstance(),
1403                        ScimSchema.groupInstance(),
1404                        ScimSchema.enterpriseUserInstance(),
1405                        ScimSchema.serviceProviderConfigInstance(),
1406                        ScimSchema.resourceTypeInstance(),
1407                        ScimSchema.schemaInstance());
1408        for (ScimResourceType type : types) {
1409            if (type.getName().equals("Schema")
1410                    || type.getName().equals("ResourceType")
1411                    || type.getName().equals("ServiceProviderConfig"))
1412                throw new IllegalArgumentException(
1413                        "SCIM application type collides with a discovery type.");
1414            for (String discovery : List.of("/Schemas", "/ResourceTypes", "/ServiceProviderConfig"))
1415                if (type.getEndpoint().equals(discovery)
1416                        || type.getEndpoint().startsWith(discovery + "/"))
1417                    throw new IllegalArgumentException(
1418                            "SCIM application endpoint collides with discovery.");
1419            if (!names.add(type.getName())
1420                    || !endpoints.add(type.getEndpoint())
1421                    || (type.getId().isPresent() && !ids.add(type.getId().get())))
1422                throw new IllegalArgumentException("Duplicate SCIM resource registration.");
1423            for (ScimSchema schema : ScimSchemas.allSchemas(type)) {
1424                for (ScimSchema builtin : reserved)
1425                    if (AsciiCase.fold(schema.getId()).equals(AsciiCase.fold(builtin.getId()))
1426                            && !schema.equals(builtin))
1427                        throw new IllegalArgumentException(
1428                                "Reserved SCIM schema identifier has contradictory characteristics.");
1429                String key = AsciiCase.fold(schema.getId());
1430                ScimSchema previous = all.putIfAbsent(key, schema);
1431                if (previous != null && !previous.equals(schema))
1432                    throw new IllegalArgumentException(
1433                            "SCIM schema identifier has conflicting definitions.");
1434                if (previous == null) {
1435                    if (all.size() > Limits.SCIM_SCHEMAS.getCap())
1436                        throw new IllegalArgumentException(
1437                                "SCIM registration exceeds its schema bound.");
1438                }
1439            }
1440        }
1441        return List.copyOf(all.values());
1442    }
1443
1444    private static final class DiscoveryTypes {
1445        static final @NonNull ScimResourceType CONFIG =
1446                ScimResourceType.discovery(
1447                        ScimSchema.serviceProviderConfigInstance(),
1448                        "ServiceProviderConfig",
1449                        "/ServiceProviderConfig");
1450        static final @NonNull ScimResourceType TYPE =
1451                ScimResourceType.discovery(
1452                        ScimSchema.resourceTypeInstance(), "ResourceType", "/ResourceTypes");
1453        static final @NonNull ScimResourceType SCHEMA =
1454                ScimResourceType.discovery(ScimSchema.schemaInstance(), "Schema", "/Schemas");
1455    }
1456
1457    /** Mutable complete provider configuration; null restores each documented default.
1458     * @since 1.0.0
1459     */
1460    @NotThreadSafe
1461    @CheckReturnValue
1462    public static final class Builder {
1463        private @Nullable URI baseUri;
1464        private @NonNull List<@NonNull ScimResourceType> resourceTypes = List.of();
1465        private @Nullable ScimServiceProviderConfig serviceProviderConfig;
1466        private @NonNull Map<@NonNull ScimResourceType, @NonNull ScimFilterPolicy> filterPolicies =
1467                Map.of();
1468        private @Nullable ScimCompatibility compatibility;
1469        private @Nullable ScimStringMatching stringMatching;
1470        private @Nullable ScimLimits limits;
1471        private @Nullable ScimObserver observer;
1472
1473        private Builder() {}
1474
1475        /** Replaces the value; null restores required base URI to unset.
1476         * @param value complete replacement, or null for the stated default
1477         * @return this builder
1478         * @since 1.0.0
1479         */
1480        public @NonNull Builder baseUri(@Nullable URI value) {
1481            baseUri = value;
1482            return this;
1483        }
1484
1485        /** Replaces the value; null restores complete registrations to empty.
1486         * @param value complete replacement, or null for the stated default
1487         * @return this builder
1488         * @since 1.0.0
1489         */
1490        public @NonNull Builder resourceTypes(@Nullable List<@NonNull ScimResourceType> value) {
1491            if (value != null && value.size() > Limits.SCIM_RESOURCE_TYPES.getCap())
1492                throw new IllegalArgumentException("SCIM resource type count exceeds its bound.");
1493            resourceTypes = value == null ? List.of() : List.copyOf(value);
1494            return this;
1495        }
1496
1497        /** Replaces the value; null restores capabilities to fresh defaults.
1498         * @param value complete replacement, or null for the stated default
1499         * @return this builder
1500         * @since 1.0.0
1501         */
1502        public @NonNull Builder serviceProviderConfig(@Nullable ScimServiceProviderConfig value) {
1503            serviceProviderConfig = value;
1504            return this;
1505        }
1506
1507        /** Replaces the value; null restores complete policies to empty.
1508         * @param value complete replacement, or null for the stated default
1509         * @return this builder
1510         * @since 1.0.0
1511         */
1512        public @NonNull Builder filterPolicies(
1513                @Nullable Map<@NonNull ScimResourceType, @NonNull ScimFilterPolicy> value) {
1514            if (value != null && value.size() > Limits.SCIM_RESOURCE_TYPES.getCap())
1515                throw new IllegalArgumentException(
1516                        "SCIM policy registration count exceeds its bound.");
1517            filterPolicies = value == null ? Map.of() : Map.copyOf(value);
1518            return this;
1519        }
1520
1521        /** Replaces the value; null restores features to strict.
1522         * @param value complete replacement, or null for the stated default
1523         * @return this builder
1524         * @since 1.0.0
1525         */
1526        public @NonNull Builder compatibility(@Nullable ScimCompatibility value) {
1527            compatibility = value;
1528            return this;
1529        }
1530
1531        /** Replaces the value; null restores strategy to absent.
1532         * @param value complete replacement, or null for the stated default
1533         * @return this builder
1534         * @since 1.0.0
1535         */
1536        public @NonNull Builder stringMatching(@Nullable ScimStringMatching value) {
1537            stringMatching = value;
1538            return this;
1539        }
1540
1541        /** Replaces the value; null restores processing limits to fresh defaults.
1542         * @param value complete replacement, or null for the stated default
1543         * @return this builder
1544         * @since 1.0.0
1545         */
1546        public @NonNull Builder limits(@Nullable ScimLimits value) {
1547            limits = value;
1548            return this;
1549        }
1550
1551        /** Replaces the value; null restores observer to disabled.
1552         * @param value complete replacement, or null for the stated default
1553         * @return this builder
1554         * @since 1.0.0
1555         */
1556        public @NonNull Builder observer(@Nullable ScimObserver value) {
1557            observer = value;
1558            return this;
1559        }
1560
1561        /** Snapshots and validates registration, capabilities and all bound policies without callbacks.
1562         * @return an immutable provider
1563         * @since 1.0.0
1564         */
1565        public @NonNull ScimServiceProvider build() {
1566            return new ScimServiceProvider(this, null);
1567        }
1568    }
1569
1570    /** Mutable provider copy. Null restores the corresponding source value.
1571     * @since 1.0.0
1572     */
1573    @NotThreadSafe
1574    @CheckReturnValue
1575    public static final class Copier {
1576        private final @NonNull ScimServiceProvider source;
1577        private @Nullable URI baseUri;
1578        private @Nullable ScimCompatibility compatibility;
1579
1580        private Copier(@NonNull ScimServiceProvider source) {
1581            this.source = source;
1582        }
1583
1584        /** Replaces trusted base URI; null restores the source.
1585         * @param value new trusted base URI, or null
1586         * @return this copier
1587         * @since 1.0.0
1588         */
1589        public @NonNull Copier baseUri(@Nullable URI value) {
1590            baseUri = value;
1591            return this;
1592        }
1593
1594        /** Replaces explicit features; null restores the source.
1595         * @param value new compatibility, or null
1596         * @return this copier
1597         * @since 1.0.0
1598         */
1599        public @NonNull Copier compatibility(@Nullable ScimCompatibility value) {
1600            compatibility = value;
1601            return this;
1602        }
1603
1604        /** Validates a new snapshot without callbacks, retaining semantic context only for unchanged features.
1605         * @return the copied provider
1606         * @since 1.0.0
1607         */
1608        public @NonNull ScimServiceProvider finish() {
1609            ScimCompatibility selected =
1610                    compatibility == null ? source.compatibility : compatibility;
1611            Builder builder =
1612                    builder()
1613                            .baseUri(baseUri == null ? source.baseUri : baseUri)
1614                            .resourceTypes(source.resourceTypes)
1615                            .serviceProviderConfig(source.serviceProviderConfig)
1616                            .filterPolicies(source.filterPolicies)
1617                            .compatibility(selected)
1618                            .stringMatching(source.stringMatching)
1619                            .limits(source.limits)
1620                            .observer(source.observer);
1621            return new ScimServiceProvider(
1622                    builder, selected.equals(source.compatibility) ? source.semanticContext : null);
1623        }
1624    }
1625}