001/*
002 * Copyright 2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.revetsec.scim;
018
019import com.google.errorprone.annotations.CheckReturnValue;
020import com.revetsec.internal.HostClassifier;
021import com.revetsec.internal.Limits;
022import com.revetsec.internal.json.AsciiCase;
023import org.jspecify.annotations.NonNull;
024import org.jspecify.annotations.Nullable;
025
026import javax.annotation.concurrent.Immutable;
027import java.util.Objects;
028import java.util.Optional;
029
030/**
031 * Immutable SCIM attribute-path syntax with an optional absolute schema URI and one optional
032 * subattribute. Equality folds ASCII letters throughout the structural path. Syntax success does
033 * not establish a registered schema or grant filtering permission. URI text is never fetched.
034 *
035 * @since 1.0.0
036 */
037@Immutable
038@CheckReturnValue
039public final class ScimAttributePath {
040    private final @Nullable String schemaId;
041    private final @NonNull String attributeName;
042    private final @Nullable String subAttributeName;
043    private final @Nullable String foldedSchemaId;
044    private final @NonNull String foldedAttributeName;
045    private final @Nullable String foldedSubAttributeName;
046
047    private ScimAttributePath(@Nullable String schemaId, @NonNull String attributeName,
048            @Nullable String subAttributeName) {
049        this.schemaId = schemaId;
050        this.attributeName = attributeName;
051        this.subAttributeName = subAttributeName;
052        foldedSchemaId = schemaId == null ? null : AsciiCase.fold(schemaId);
053        foldedAttributeName = AsciiCase.fold(attributeName);
054        foldedSubAttributeName = subAttributeName == null ? null : AsciiCase.fold(subAttributeName);
055    }
056
057    /**
058     * Parses a complete bounded attribute path without surrounding whitespace. Names start with an
059     * ASCII letter and then contain ASCII letters, digits, underscore or hyphen. The narrowly
060     * supported {@code $ref} name can also represent a relative subattribute inside a ValuePath;
061     * declaring it as a top-level resource attribute still requires later schema binding. Schema
062     * IDs use bounded absolute URI syntax.
063     *
064     * @param expression the complete path expression
065     * @return syntactic success or a fixed invalidPath error
066     * @since 1.0.0
067     */
068    public static @NonNull ScimAttributePathParseResult fromExpressionResult(@NonNull String expression) {
069        Objects.requireNonNull(expression);
070        return parseRange(expression, 0, expression.length());
071    }
072
073    /**
074     * Returns the original schema ID spelling, when qualified.
075     *
076     * @return the original schema ID spelling, when qualified
077     * @since 1.0.0
078     */
079    public @NonNull Optional<@NonNull String> getSchemaId() { return Optional.ofNullable(schemaId); }
080    /**
081     * Returns the original attribute-name spelling.
082     *
083     * @return the original attribute-name spelling
084     * @since 1.0.0
085     */
086    public @NonNull String getAttributeName() { return attributeName; }
087    /**
088     * Returns the original subattribute-name spelling, when supplied.
089     *
090     * @return the original subattribute-name spelling, when supplied
091     * @since 1.0.0
092     */
093    public @NonNull Optional<@NonNull String> getSubAttributeName() { return Optional.ofNullable(subAttributeName); }
094
095    /**
096     * Explicitly emits this path as SCIM data, preserving the component spellings supplied during
097     * parsing. This operation can disclose application attribute and schema names.
098     * @return the SCIM attribute-path expression
099     * @since 1.0.0
100     */
101    public @NonNull String toScimString() {
102        return (schemaId == null ? "" : schemaId + ":") + attributeName
103                + (subAttributeName == null ? "" : "." + subAttributeName);
104    }
105
106    /**
107     * Returns whether the structural paths have equal ASCII-folded components.
108     *
109     * @return whether the structural paths have equal ASCII-folded components
110     * @since 1.0.0
111     */
112    @Override public boolean equals(@Nullable Object other) {
113        return this == other || (other instanceof ScimAttributePath path
114                && Objects.equals(foldedSchemaId, path.foldedSchemaId)
115                && foldedAttributeName.equals(path.foldedAttributeName)
116                && Objects.equals(foldedSubAttributeName, path.foldedSubAttributeName));
117    }
118
119    /**
120     * Returns a hash of the same ASCII-folded components used by equality.
121     *
122     * @return a hash of the same ASCII-folded components used by equality
123     * @since 1.0.0
124     */
125    @Override public int hashCode() {
126        int hash = Objects.hashCode(foldedSchemaId);
127        hash = 31 * hash + foldedAttributeName.hashCode();
128        return 31 * hash + Objects.hashCode(foldedSubAttributeName);
129    }
130
131    /**
132     * Returns a fixed redacted description.
133     *
134     * @return a fixed redacted description
135     * @since 1.0.0
136     */
137    @Override public @NonNull String toString() { return "ScimAttributePath{<redacted>}"; }
138
139    // Syntax-only engine helper. Its offsets remain relative to the complete supplied expression.
140    static @NonNull ScimAttributePathParseResult parseRange(@NonNull String expression, int start, int end) {
141        Objects.requireNonNull(expression);
142        if (start < 0 || end < start || end > expression.length())
143            throw new IllegalArgumentException("Invalid SCIM attribute-path input range.");
144        int maximumName = Limits.SCIM_ATTRIBUTE_NAME_LENGTH.getDefaultIntValue();
145        int maximumSchema = Limits.SCIM_SCHEMA_ID_LENGTH.getDefaultIntValue();
146        int maximumPath = maximumSchema + 2 * maximumName + 2;
147        if (end - start > maximumPath || end > Limits.SCIM_FILTER_LENGTH.getCap())
148            return rejected(0);
149        if (start == end) return rejected(start);
150
151        int separator = -1;
152        for (int index = end - 1; index >= start; --index) {
153            if (expression.charAt(index) == ':') { separator = index; break; }
154        }
155        int nameStart = separator < 0 ? start : separator + 1;
156        @Nullable String schema = null;
157        if (separator >= 0) {
158            if (separator - start > maximumSchema) return rejected(start + maximumSchema);
159            int failure = uriFailure(expression, start, separator);
160            if (failure >= 0) return rejected(failure);
161            schema = expression.substring(start, separator);
162        }
163
164        int dot = -1;
165        for (int index = nameStart; index < end; ++index) {
166            if (expression.charAt(index) == '.') { dot = index; break; }
167        }
168        int nameEnd = dot < 0 ? end : dot;
169        int failure = nameFailure(expression, nameStart, nameEnd, maximumName);
170        if (failure >= 0) return rejected(failure);
171        @Nullable String subAttribute = null;
172        if (dot >= 0) {
173            failure = nameFailure(expression, dot + 1, end, maximumName);
174            if (failure >= 0) return rejected(failure);
175            subAttribute = expression.substring(dot + 1, end);
176        }
177        return new ScimAttributePathParseResult.Succeeded(
178                new ScimAttributePath(schema, expression.substring(nameStart, nameEnd), subAttribute));
179    }
180
181    private static @NonNull ScimAttributePathParseResult rejected(int offset) {
182        return new ScimAttributePathParseResult.Rejected(ScimError.invalidPathAt(offset));
183    }
184
185    private static int nameFailure(@NonNull String text, int start, int end, int maximum) {
186        if (start == end) return start;
187        if (end - start > maximum) return start + maximum;
188        if (end - start == 4 && text.charAt(start) == '$'
189                && AsciiCase.fold(text.charAt(start + 1)) == 'r'
190                && AsciiCase.fold(text.charAt(start + 2)) == 'e'
191                && AsciiCase.fold(text.charAt(start + 3)) == 'f') return -1;
192        if (!alpha(text.charAt(start))) return start;
193        for (int index = start + 1; index < end; ++index) {
194            char character = text.charAt(index);
195            if (!alpha(character) && !digit(character) && character != '_' && character != '-') return index;
196        }
197        return -1;
198    }
199
200    static boolean isAbsoluteUriSyntax(@NonNull String value) {
201        return uriFailure(value, 0, value.length()) < 0;
202    }
203
204    // Bounded RFC 3986 URI syntax recognition, without exception-driven input rejection. Scheme-
205    // specific semantics and registered-prefix resolution belong to later schema binding.
206    private static int uriFailure(@NonNull String text, int start, int end) {
207        if (start == end || !alpha(text.charAt(start))) return start;
208        int schemeEnd = start + 1;
209        while (schemeEnd < end && text.charAt(schemeEnd) != ':') {
210            char character = text.charAt(schemeEnd);
211            if (!alpha(character) && !digit(character) && character != '+' && character != '-' && character != '.')
212                return schemeEnd;
213            ++schemeEnd;
214        }
215        if (schemeEnd == end) return schemeEnd;
216        int contentStart = schemeEnd + 1;
217        int fragment = end;
218        int query = end;
219        for (int index = contentStart; index < end; ++index) {
220            char character = text.charAt(index);
221            if (character == '#') { fragment = index; break; }
222            if (character == '?' && query == end) query = index;
223        }
224        int hierarchyEnd = Math.min(query, fragment);
225        int pathStart = contentStart;
226        if (contentStart + 1 < hierarchyEnd && text.charAt(contentStart) == '/'
227                && text.charAt(contentStart + 1) == '/') {
228            int authorityStart = contentStart + 2;
229            int authorityEnd = authorityStart;
230            while (authorityEnd < hierarchyEnd && text.charAt(authorityEnd) != '/') ++authorityEnd;
231            int failure = authorityFailure(text, authorityStart, authorityEnd);
232            if (failure >= 0) return failure;
233            pathStart = authorityEnd;
234        }
235        int failure = componentFailure(text, pathStart, hierarchyEnd, true, false, false);
236        if (failure >= 0) return failure;
237        if (query < fragment) {
238            failure = componentFailure(text, query + 1, fragment, true, true, false);
239            if (failure >= 0) return failure;
240        }
241        return fragment < end ? componentFailure(text, fragment + 1, end, true, true, false) : -1;
242    }
243
244    private static int authorityFailure(@NonNull String text, int start, int end) {
245        int hostStart = start;
246        for (int index = start; index < end; ++index) {
247            if (text.charAt(index) == '@') {
248                if (hostStart != start) return index;
249                int failure = componentFailure(text, start, index, false, false, true);
250                if (failure >= 0) return failure;
251                hostStart = index + 1;
252            }
253        }
254        if (hostStart < end && text.charAt(hostStart) == '[') {
255            int close = hostStart + 1;
256            while (close < end && text.charAt(close) != ']') ++close;
257            if (close == end) return hostStart;
258            if (!validIpLiteral(text, hostStart, close + 1)) return hostStart;
259            if (close + 1 == end) return -1;
260            if (text.charAt(close + 1) != ':') return close + 1;
261            return portFailure(text, close + 2, end);
262        }
263        int hostEnd = hostStart;
264        while (hostEnd < end && text.charAt(hostEnd) != ':') ++hostEnd;
265        int failure = registeredNameFailure(text, hostStart, hostEnd);
266        if (failure >= 0) return failure;
267        return hostEnd < end ? portFailure(text, hostEnd + 1, end) : -1;
268    }
269
270    private static boolean validIpLiteral(@NonNull String text, int start, int end) {
271        if (end - start < 3) return false;
272        char first = text.charAt(start + 1);
273        if (first != 'v' && first != 'V')
274            return HostClassifier.parseLiteral(text.substring(start, end)) != null;
275        int index = start + 2;
276        int versionStart = index;
277        while (index < end - 1 && hex(text.charAt(index))) ++index;
278        if (index == versionStart || index >= end - 2 || text.charAt(index++) != '.') return false;
279        while (index < end - 1) {
280            char character = text.charAt(index++);
281            if (!unreserved(character) && !subDelimiter(character) && character != ':') return false;
282        }
283        return true;
284    }
285
286    private static int portFailure(@NonNull String text, int start, int end) {
287        for (int index = start; index < end; ++index) if (!digit(text.charAt(index))) return index;
288        return -1;
289    }
290
291    private static int registeredNameFailure(@NonNull String text, int start, int end) {
292        for (int index = start; index < end; ++index) {
293            char character = text.charAt(index);
294            if (character == '%') {
295                if (index + 2 >= end || !hex(text.charAt(index + 1)) || !hex(text.charAt(index + 2))) return index;
296                index += 2;
297            } else if (!unreserved(character) && !subDelimiter(character)) return index;
298        }
299        return -1;
300    }
301
302    private static int componentFailure(@NonNull String text, int start, int end,
303            boolean slash, boolean question, boolean userInfo) {
304        for (int index = start; index < end; ++index) {
305            char character = text.charAt(index);
306            if (character == '%') {
307                if (index + 2 >= end || !hex(text.charAt(index + 1)) || !hex(text.charAt(index + 2))) return index;
308                index += 2;
309            } else if (!unreserved(character) && !subDelimiter(character) && character != ':'
310                    && !(character == '@' && !userInfo) && !(character == '/' && slash)
311                    && !(character == '?' && question)) return index;
312        }
313        return -1;
314    }
315
316    private static boolean alpha(char character) {
317        return (character >= 'A' && character <= 'Z') || (character >= 'a' && character <= 'z');
318    }
319
320    private static boolean digit(char character) { return character >= '0' && character <= '9'; }
321
322    private static boolean hex(char character) {
323        return digit(character) || (character >= 'A' && character <= 'F') || (character >= 'a' && character <= 'f');
324    }
325
326    private static boolean unreserved(char character) {
327        return alpha(character) || digit(character) || character == '-' || character == '.'
328                || character == '_' || character == '~';
329    }
330
331    private static boolean subDelimiter(char character) {
332        return character == '!' || character == '$' || character == '&' || character == '\''
333                || character == '(' || character == ')' || character == '*' || character == '+'
334                || character == ',' || character == ';' || character == '=';
335    }
336}