-
Notifications
You must be signed in to change notification settings - Fork 37
Surface structured parse diagnostics from PolicySet.parsePolicies #367
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
muditchaudhary
merged 5 commits into
cedar-policy:main
from
jamesmulcahy:surface-parse-diagnostics
Sep 23, 2026
+355
−7
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
5276059
Surface structured parse diagnostics from PolicySet.parsePolicies
jamesmulcahy 20cc7c3
Preserve InternalException.getMessage() for parse failures
jamesmulcahy c1eb82d
Document how to index a DetailedError source span
jamesmulcahy 8632241
Satisfy SpotBugs in PolicyParseException
jamesmulcahy 7bdffd7
Guard throw_internal against a pending Java exception
jamesmulcahy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
92 changes: 92 additions & 0 deletions
92
CedarJava/src/main/java/com/cedarpolicy/model/exception/PolicyParseException.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| /* | ||
| * Copyright Cedar Contributors | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package com.cedarpolicy.model.exception; | ||
|
|
||
| import com.cedarpolicy.CedarJson; | ||
| import com.cedarpolicy.model.DetailedError; | ||
| import com.fasterxml.jackson.core.JsonProcessingException; | ||
| import com.fasterxml.jackson.core.type.TypeReference; | ||
| import java.util.Arrays; | ||
| import java.util.Collections; | ||
| import java.util.List; | ||
|
|
||
| /** | ||
| * Thrown when Cedar policy text fails to parse, carrying the structured diagnostics Cedar | ||
| * produced for each error. | ||
| * | ||
| * <p>Cedar reports a parse failure as one or more {@code miette} diagnostics: a message, the | ||
| * source span of the offending token, the tokens the parser expected there, and often help | ||
| * text. A single document may fail in several places, and every failure is reported. | ||
| * | ||
| * <p>Three accessors describe the same failure at increasing fidelity: | ||
| * | ||
| * <ul> | ||
| * <li>{@link #getMessage()} - one human-readable line, describing the first error only. Its | ||
| * wording is treated as part of this class's compatibility surface, so it is the least | ||
| * informative of the three and the safest to match on. | ||
| * <li>{@link #getErrors()} - one message per parse error, in the order Cedar reported them. | ||
| * These are Cedar's messages alone, without the prefix {@link #getMessage()} carries. | ||
| * <li>{@link #getDetailedErrors()} - the full diagnostic for each error, and the only | ||
| * accessor that reports where in the source the error occurred. See {@link DetailedError}. | ||
| * </ul> | ||
| * | ||
| * <p>Extends {@link InternalException}, so callers that catch the general parse-or-evaluate | ||
| * failure are unaffected and need not know this type exists. | ||
| */ | ||
| public final class PolicyParseException extends InternalException { | ||
|
|
||
| private static final TypeReference<List<DetailedError>> ERROR_LIST = | ||
| new TypeReference<List<DetailedError>>() { }; | ||
|
|
||
| private final transient List<DetailedError> detailedErrors; | ||
|
|
||
| /** | ||
| * Construct from the JSON array of {@code DetailedError} the native layer serialises. | ||
| * | ||
| * @param message the value {@link #getMessage()} reports | ||
| * @param messages one message per parse error, for {@link #getErrors()} | ||
| * @param detailedErrorsJson JSON array of {@code DetailedError}; if it cannot be read, | ||
| * the exception still carries {@code message} and {@code messages}, and | ||
| * {@link #getDetailedErrors()} returns empty, so a serialisation change can never | ||
| * turn a parse error into a different failure | ||
| */ | ||
| public PolicyParseException(String message, String[] messages, String detailedErrorsJson) { | ||
| super(message, Arrays.asList(messages)); | ||
| this.detailedErrors = readDetailedErrors(detailedErrorsJson); | ||
| } | ||
|
|
||
| private static List<DetailedError> readDetailedErrors(String json) { | ||
| if (json == null || json.isEmpty()) { | ||
| return List.of(); | ||
| } | ||
| try { | ||
| List<DetailedError> parsed = CedarJson.objectReader().forType(ERROR_LIST).readValue(json); | ||
| return parsed == null ? List.of() : List.copyOf(parsed); | ||
| } catch (JsonProcessingException | RuntimeException e) { | ||
| return List.of(); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * The structured diagnostics for each parse error, including source spans and help text. | ||
| * | ||
| * @return the diagnostics, or an empty list if none could be recovered | ||
| */ | ||
| public List<DetailedError> getDetailedErrors() { | ||
| return Collections.unmodifiableList(detailedErrors); | ||
| } | ||
| } |
108 changes: 108 additions & 0 deletions
108
CedarJava/src/test/java/com/cedarpolicy/PolicyParseDiagnosticsTests.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| /* | ||
| * Copyright Cedar Contributors | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package com.cedarpolicy; | ||
|
|
||
| import com.cedarpolicy.model.DetailedError; | ||
| import com.cedarpolicy.model.exception.InternalException; | ||
| import com.cedarpolicy.model.exception.PolicyParseException; | ||
| import com.cedarpolicy.model.policy.PolicySet; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; | ||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertFalse; | ||
| import static org.junit.jupiter.api.Assertions.assertThrows; | ||
| import static org.junit.jupiter.api.Assertions.assertTrue; | ||
|
|
||
| /** Parse failures carry Cedar's structured diagnostics, not just a flattened string. */ | ||
| public class PolicyParseDiagnosticsTests { | ||
|
|
||
| @Test | ||
| public void parseFailureCarriesSourceSpanAndExpectedTokens() { | ||
| // An entity literal in the action slot: the scope needs `action == ...`. | ||
| String src = "forbid(principal, Foo::Action::\"Read\", resource);"; | ||
| PolicyParseException e = | ||
| assertThrows(PolicyParseException.class, () -> PolicySet.parsePolicies(src)); | ||
|
|
||
| List<DetailedError> details = e.getDetailedErrors(); | ||
| assertEquals(1, details.size()); | ||
| DetailedError error = details.get(0); | ||
| assertTrue(error.message.contains("unexpected token `::`"), error.message); | ||
|
|
||
| assertEquals(1, error.sourceLocations.size()); | ||
| DetailedError.SourceLabel span = error.sourceLocations.get(0); | ||
| // The span must cover the offending `::`, so callers can underline it. | ||
| assertEquals(src.indexOf("::"), span.start); | ||
| assertEquals(src.indexOf("::") + 2, span.end); | ||
| assertTrue(span.label.orElse("").contains("expected"), span.label.toString()); | ||
| } | ||
|
|
||
| @Test | ||
| public void everyParseErrorIsReportedNotJustTheFirst() { | ||
| // ParseErrors' Display prints only the first error, so the flattened path reported | ||
| // one string for the whole document. Both accessors now carry all of them. | ||
| String src = "forbid(principal, Foo::Action::\"A\", resource);\n" | ||
| + "permit(principal, action, resource) when { 1 + };"; | ||
| PolicyParseException e = | ||
| assertThrows(PolicyParseException.class, () -> PolicySet.parsePolicies(src)); | ||
|
|
||
| assertEquals(2, e.getDetailedErrors().size()); | ||
| assertEquals(2, e.getErrors().size()); | ||
| // The message stays what Display gave it - the first error alone - so populating the | ||
| // list cannot widen the string that existing callers match on. | ||
| assertEquals("Internal error: Internal JNI Error: " + e.getErrors().get(0), e.getMessage()); | ||
| } | ||
|
|
||
| @Test | ||
| public void messageIsUnchangedForBackCompat() { | ||
| // Callers branch on getMessage() and match it with anchored regexes, so the string | ||
| // stays exactly as the generic error path wrote it, "Internal JNI Error: " and all. | ||
| // The added detail is reached through the accessors instead. | ||
| PolicyParseException e = assertThrows(PolicyParseException.class, | ||
| () -> PolicySet.parsePolicies("forbid(principal, Foo::Action::\"Read\", resource);")); | ||
|
|
||
| assertEquals("Internal error: Internal JNI Error: unexpected token `::`", e.getMessage()); | ||
| // getErrors() entries are the bare Cedar messages: the prefix described the binding | ||
| // rather than any one error, and is meaningless once the list is per-error. | ||
| assertEquals(List.of("unexpected token `::`"), e.getErrors()); | ||
| } | ||
|
|
||
| @Test | ||
| public void helpTextSurvivesWhenCedarSuppliesIt() { | ||
| PolicyParseException e = assertThrows(PolicyParseException.class, | ||
| () -> PolicySet.parsePolicies("permit(principle, action, resource);")); | ||
|
|
||
| DetailedError error = e.getDetailedErrors().get(0); | ||
| assertTrue(error.help.isPresent(), "expected help text for an invalid scope variable"); | ||
| assertTrue(error.help.get().contains("principal"), error.help.get()); | ||
| } | ||
|
|
||
| @Test | ||
| public void remainsCatchableAsInternalException() { | ||
| // PolicyParseException extends InternalException so existing callers keep working. | ||
| InternalException e = assertThrows(InternalException.class, | ||
| () -> PolicySet.parsePolicies("permit(principal, action, resource)")); | ||
| assertFalse(e.getErrors().isEmpty()); | ||
| } | ||
|
|
||
| @Test | ||
| public void validPolicySetStillParses() { | ||
| assertDoesNotThrow(() -> PolicySet.parsePolicies("permit(principal, action, resource);")); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note to myself: CHANGELOG.md in
mainis stale. The features under "Unreleased" are now released in CedarJava 4.8. I will update it and also place this change under the correct section.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Regarding removing the prefix in
getErrors, it seems fine to me. @mark-creamer-amazon what do you think? IIRC Cedar does not treat mutating error messages as a breaking change.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah I think removing the prefix in each of
getErrorsshould be fine.