-
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
Open
jamesmulcahy
wants to merge
1
commit into
cedar-policy:main
Choose a base branch
from
jamesmulcahy:surface-parse-diagnostics
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+267
−4
Open
Changes from all commits
Commits
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
84 changes: 84 additions & 0 deletions
84
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,84 @@ | ||
| /* | ||
| * 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.type.TypeReference; | ||
| 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 parse failures as {@code miette} diagnostics: a message, the source span | ||
| * of the offending token, the tokens the parser expected there, and often help text. Prior | ||
| * to this type those were flattened to a single {@code Display} string, so callers saw | ||
| * "unexpected token `::`" with no indication of where in the policy it occurred, and every | ||
| * error after the first was discarded. {@link #getDetailedErrors()} returns the full set, | ||
| * one {@link DetailedError} per parse error, in the order Cedar reported them. | ||
| * | ||
| * <p>Extends {@link InternalException} so existing {@code catch} blocks are unaffected. | ||
| * Two message details differ from the generic error path, deliberately: the | ||
| * {@code "Internal JNI Error: "} prefix is dropped, because it describes the binding rather | ||
| * than the policy and reads as a library fault rather than a typo in the caller's input; | ||
| * and {@link #getErrors()} carries one entry per parse error rather than a single entry for | ||
| * the whole document, which is what its plural contract always implied. | ||
| */ | ||
| public 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 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 messages} and {@link #getDetailedErrors()} | ||
| * returns empty, so a serialisation change can never turn a parse error into a | ||
| * different failure | ||
| */ | ||
| public PolicyParseException(String[] messages, String detailedErrorsJson) { | ||
| super(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 (Exception 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); | ||
| } | ||
| } |
102 changes: 102 additions & 0 deletions
102
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,102 @@ | ||
| /* | ||
| * 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.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()); | ||
| } | ||
|
|
||
| @Test | ||
| public void messagesDropTheInternalJniErrorPrefix() { | ||
| // That prefix describes the binding, not the policy: reading "Internal JNI Error" | ||
| // for an ordinary typo suggests a library fault rather than a fixable mistake. | ||
| PolicyParseException e = assertThrows(PolicyParseException.class, | ||
| () -> PolicySet.parsePolicies("forbid(principal, Foo::Action::\"Read\", resource);")); | ||
|
|
||
| assertEquals("Internal error: unexpected token `::`", e.getMessage()); | ||
| 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() { | ||
| org.junit.jupiter.api.Assertions.assertDoesNotThrow( | ||
| () -> PolicySet.parsePolicies("permit(principal, action, resource);")); | ||
| } | ||
| } | ||
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
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.
Nit: we should import
assertDoesNotThrowaboveThere 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.
Ack; fixed this in my local branch