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.google.errorprone.annotations.CanIgnoreReturnValue;
021import com.revetsec.json.*;
022import com.revetsec.internal.json.AsciiCase;
023import org.jspecify.annotations.NonNull;
024import org.jspecify.annotations.Nullable;
025import javax.annotation.concurrent.Immutable;
026import javax.annotation.concurrent.NotThreadSafe;
027import java.net.URI;
028import java.time.Instant;
029import java.util.ArrayList;
030import java.util.List;
031import java.util.Optional;
032import static java.util.Objects.requireNonNull;
033
034/** Immutable schema-normalized application data. Intentional getters expose provisioning data;
035 * diagnostics never expose it. Trusted construction is not request provenance or authorization.
036 *
037     * @since 1.0.0
038 */
039@Immutable
040public final class ScimResource {
041    private final @NonNull ScimResourceType resourceType;
042    private final @NonNull JsonObject document;
043    private final @Nullable Object semanticContext;
044    private final long constructionWorkUnits;
045    private ScimResource(@NonNull ScimResourceType type, @NonNull JsonObject document,
046            @Nullable Object context, long constructionWorkUnits) {
047        this.resourceType = type; this.document = document; this.semanticContext = context;
048        this.constructionWorkUnits = constructionWorkUnits;
049    }
050    static @NonNull ScimResource parsed(@NonNull ScimResourceType type, @NonNull JsonObject document, @NonNull Object context) {
051        return parsed(type, document, context, ScimLimits.fromDefaults().getMaximumWorkUnits());
052    }
053    static @NonNull ScimResource parsed(@NonNull ScimResourceType type, @NonNull JsonObject document,
054            @NonNull Object context, long workUnits) {
055        return new ScimResource(type, document, context, workUnits);
056    }
057    @Nullable Object getSemanticContext() { return semanticContext; }
058    /** Starts trusted data construction.
059     * @param resourceType the schema registration
060     * @return a builder
061     * @since 1.0.0 */
062    @CheckReturnValue public static @NonNull Builder withResourceType(@NonNull ScimResourceType resourceType) { return new Builder(requireNonNull(resourceType)); }
063    /** Starts trusted data copying.
064     * @return a copier
065     * @since 1.0.0 */
066    @CheckReturnValue public @NonNull Copier copy() { return new Copier(this); }
067    /** Returns the resource type.
068     * @return the resource type
069     * @since 1.0.0 */
070    public @NonNull ScimResourceType getResourceType() { return resourceType; }
071    /** Intentionally exposes the immutable normalized document, including transient write-only data.
072     *
073     * @return the document
074     * @since 1.0.0 */
075    public @NonNull JsonObject getDocument() { return document; }
076    /** Finds a registered attribute or subattribute. Multi-valued subattributes return an array.
077     *
078     * @param path the path
079     * @return the assigned value, when present
080     * @since 1.0.0 */
081    public @NonNull Optional<@NonNull JsonValue> find(@NonNull ScimAttributePath path) {
082        requireNonNull(path);
083        Optional<ScimAttributePath> bound = ScimSchemas.canonicalPath(resourceType, path);
084        if (bound.isEmpty()) return Optional.empty();
085        ScimAttributePath canonical = bound.orElseThrow();
086        JsonObject container = document;
087        if (canonical.getSchemaId().isPresent() && !AsciiCase.fold(canonical.getSchemaId().orElseThrow()).equals(AsciiCase.fold(resourceType.getSchema().getId()))) {
088            Optional<JsonObject> extension = getExtension(canonical.getSchemaId().orElseThrow());
089            if (extension.isEmpty()) return Optional.empty();
090            container = extension.orElseThrow();
091        }
092        Optional<JsonValue> value = container.find(canonical.getAttributeName());
093        if (canonical.getSubAttributeName().isEmpty() || value.isEmpty()) return value;
094        String sub = canonical.getSubAttributeName().orElseThrow();
095        JsonValue assigned = value.orElseThrow();
096        if (assigned instanceof JsonObject object) return object.find(sub);
097        if (assigned instanceof JsonArray array) {
098            List<JsonValue> found = new ArrayList<>();
099            for (JsonValue element : array.getElements()) if (element instanceof JsonObject object) object.find(sub).ifPresent(found::add);
100            return found.isEmpty() ? Optional.empty() : Optional.of(JsonArray.fromElements(found));
101        }
102        return Optional.empty();
103    }
104    /** Finds a registered extension without fetching its identifier.
105     * @param schemaId the schema identifier
106     * @return the extension
107     * @since 1.0.0 */
108    public @NonNull Optional<@NonNull JsonObject> getExtension(@NonNull String schemaId) {
109        requireNonNull(schemaId);
110        for (ScimSchemaExtension extension : resourceType.getSchemaExtensions()) if (AsciiCase.fold(extension.getSchema().getId()).equals(AsciiCase.fold(schemaId))) {
111            JsonValue value = document.getMembers().get(extension.getSchema().getId());
112            return value instanceof JsonObject object ? Optional.of(object) : Optional.empty();
113        }
114        return Optional.empty();
115    }
116    /** Returns the server-assigned identifier.
117     * @return the identifier
118     * @since 1.0.0 */
119    public @NonNull Optional<@NonNull String> getId() { return document.find("id").filter(JsonString.class::isInstance).map(JsonString.class::cast).map(JsonString::getValue); }
120    /** Returns the client identifier.
121     * @return the identifier
122     * @since 1.0.0 */
123    public @NonNull Optional<@NonNull String> getExternalId() { return document.find("externalId").filter(JsonString.class::isInstance).map(JsonString.class::cast).map(JsonString::getValue); }
124    /** Returns the version entity tag.
125     * @return the version
126     * @since 1.0.0 */
127    public @NonNull Optional<@NonNull String> getVersion() { return metaString("version"); }
128    /** Returns the server-assigned location without fetching it.
129     * @return the location
130     * @since 1.0.0 */
131    public @NonNull Optional<@NonNull URI> getLocation() { return metaString("location").map(URI::create); }
132    /** Returns the creation instant; fractional seconds beyond nanosecond precision are truncated.
133     * @return the instant
134     * @since 1.0.0 */
135    public @NonNull Optional<@NonNull Instant> getCreated() { return metaString("created").map(ScimResourceValidation::instant); }
136    /** Returns the last modification instant; fractional seconds beyond nanosecond precision are truncated.
137     * @return the instant
138     * @since 1.0.0 */
139    public @NonNull Optional<@NonNull Instant> getLastModified() { return metaString("lastModified").map(ScimResourceValidation::instant); }
140    private @NonNull Optional<@NonNull String> metaString(@NonNull String name) {
141        JsonValue meta = document.getMembers().get("meta");
142        return meta instanceof JsonObject object ? object.find(name).filter(JsonString.class::isInstance).map(JsonString.class::cast).map(JsonString::getValue) : Optional.empty();
143    }
144    /** Returns a fixed redacted description.
145     * @return the description
146     * @since 1.0.0 */
147    @Override public @NonNull String toString() { return "ScimResource{document=<redacted>}"; }
148    /** Trusted document construction; invalid data is a programming error.
149     * @since 1.0.0 */
150    @NotThreadSafe @CheckReturnValue public static final class Builder {
151        private final @NonNull ScimResourceType type;
152        private @Nullable JsonObject document;
153        private @Nullable ScimLimits limits;
154        private Builder(@NonNull ScimResourceType type) { this.type = type; }
155        /** Replaces the entire document; null restores unset.
156     * @param value the document
157     * @return this builder
158     * @since 1.0.0 */
159        @CanIgnoreReturnValue public @NonNull Builder document(@Nullable JsonObject value) { document = value; return this; }
160        /** Uses the provider's configured processing limits for trusted construction.
161         * @param value processing limits; null restores defaults
162         * @return this builder
163         * @since 1.0.0 */
164        @CanIgnoreReturnValue public @NonNull Builder limits(@Nullable ScimLimits value) { limits = value; return this; }
165        /** Validates and normalizes trusted data.
166     * @return the immutable resource
167     * @since 1.0.0 */
168        public @NonNull ScimResource build() {
169            if (document == null) throw new IllegalStateException("A resource document is required.");
170            return trusted(type, document, null, budget(limits));
171        }
172        /** Returns a fixed redacted description.
173     * @return the description
174     * @since 1.0.0 */
175        @Override public @NonNull String toString() { return "ScimResource.Builder{document=<redacted>}"; }
176    }
177    /** Trusted copying; null restores the source document.
178     * @since 1.0.0 */
179    @NotThreadSafe @CheckReturnValue public static final class Copier {
180        private final @NonNull ScimResource source;
181        private @Nullable JsonObject document;
182        private @Nullable ScimLimits limits;
183        private Copier(@NonNull ScimResource source) { this.source = source; }
184        /** Replaces the entire document; null restores the source.
185     * @param value the document
186     * @return this copier
187     * @since 1.0.0 */
188        @CanIgnoreReturnValue public @NonNull Copier document(@Nullable JsonObject value) { document = value; return this; }
189        /** Overrides the source resource's processing limit for this copy.
190         * @param value processing limits; null uses the source limit
191         * @return this copier
192         * @since 1.0.0 */
193        @CanIgnoreReturnValue public @NonNull Copier limits(@Nullable ScimLimits value) { limits = value; return this; }
194        /** Validates the replacement trusted data.
195     * @return the immutable resource
196     * @since 1.0.0 */
197        public @NonNull ScimResource finish() { return trusted(source.resourceType,
198                document == null ? source.document : document, source.semanticContext,
199                limits == null ? source.constructionWorkUnits : budget(limits)); }
200        /** Returns a fixed redacted description.
201     * @return the description
202     * @since 1.0.0 */
203        @Override public @NonNull String toString() { return "ScimResource.Copier{document=<redacted>}"; }
204    }
205    private static long budget(@Nullable ScimLimits limits) {
206        return (limits == null ? ScimLimits.fromDefaults() : limits).getMaximumWorkUnits();
207    }
208    private static @NonNull ScimResource trusted(@NonNull ScimResourceType type,
209            @NonNull JsonObject document, @Nullable Object context, long workUnits) {
210        ScimResourceValidation validation = new ScimResourceValidation(type, null,
211                ScimCompatibility.strictInstance(), new ScimWork(workUnits), false);
212        JsonObject normalized = validation.normalize(document);
213        if (normalized == null) {
214            if (validation.error() == ScimError.requestTooLargeInstance())
215                throw new ScimResourceWorkLimitException();
216            throw new IllegalArgumentException("The resource document violates its registered schema.");
217        }
218        return new ScimResource(type, normalized, context, workUnits);
219    }
220}