Surface structured parse diagnostics from PolicySet.parsePolicies - #367
jamesmulcahy wants to merge 4 commits into
Conversation
Parse failures are reduced to format!("Internal JNI Error: {e}") in
jni_failed, discarding the miette diagnostic cedar produced: the source
span, the tokens the parser expected, and the help text. ParseErrors'
Display also prints only its first error, so subsequent errors are lost.
Add PolicyParseException, a subclass of InternalException carrying
List<DetailedError> - the same representation the validation path already
returns. parsePoliciesJni downcasts ParseErrors and converts each
ParseError via the existing From<&E: miette::Diagnostic> impl. If building
the richer exception fails for any reason the generic path is used, so a
parse error can never become a different kind of failure.
Existing catch (InternalException) blocks are unaffected. Two message
details change deliberately: the "Internal JNI Error: " prefix is dropped,
since it describes the binding rather than the policy and reads as a
library fault rather than a typo the caller can fix; and getErrors()
carries one entry per parse error rather than a single entry for the whole
document, which is what its plural contract always implied.
Signed-off-by: James Mulcahy <jmulcahy@netflix.com>
8d0587c to
5276059
Compare
|
Full disclosure -- I've not written any rust before myself, and Claude helped with this change. Background/motivation is well summarized by Claude above. The TL;DR is that the |
|
Hi @lianah @mark-creamer-amazon @muditchaudhary -- James from Netflix here, we met a few weeks ago! Our Cedar usage is going well, but we've run into some UX friction with policy validation that should be improved by this PR. Would appreciate your time in reviewing! Thank you! |
|
Hey James, I'll take a look today. Thanks for the PR! |
|
|
||
| @Test | ||
| public void validPolicySetStillParses() { | ||
| org.junit.jupiter.api.Assertions.assertDoesNotThrow( |
There was a problem hiding this comment.
Nit: we should import assertDoesNotThrow above
There was a problem hiding this comment.
Ack; fixed this in my local branch
|
I agree with the direction of this PR, but I do worry about breaking existing consumers here.
I think I'm hesitant towards the |
[...]
Understood, I think that's a reasonable take. I'll update the PR to conform with your guidance. Thanks for the review! |
Review feedback on cedar-policy#367: dropping the "Internal JNI Error: " prefix from getMessage() is a breaking change. Consumers branch on that string and at least one matches it with an anchored regex, so it is effectively part of the API even though the prefix describes the binding rather than the policy. PolicyParseException now takes the message the generic path would have produced and passes it through, so getMessage() is byte-for-byte unchanged: "Internal error: Internal JNI Error: " followed by ParseErrors' Display, which prints the first error alone. internal_error_message is the single definition of that string, shared with the throw_internal fallback, so the two paths cannot drift. The added detail is reached through the accessors instead. getErrors() still carries one entry per parse error - the plurality its List contract always implied - each the bare Cedar message, and getDetailedErrors() carries the miette diagnostics. InternalException gains a protected constructor setting message and error list independently; the existing ones derive the message from the list, which would have widened it as the list was populated. messagesDropTheInternalJniErrorPrefix becomes messageIsUnchangedForBackCompat and now guards against the regression it previously asserted, and the multiple-error test pins the message to the first error alone. Also imports assertDoesNotThrow, and adds the CHANGELOG entry the PR was missing. Signed-off-by: James Mulcahy <jmulcahy@netflix.com> Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
|
@mark-creamer-amazon — Claude Code here, posting as James's agent; he's asked me to follow up on your review and has reviewed this reply before it went out. Two commits pushed, branch now at
|
The spans Cedar reports are UTF-8 byte offsets, but nothing said so
beyond "in bytes" on the two fields, and the obvious way to use them --
source.substring(start, end) -- is wrong the moment the policy text
contains a non-ASCII character. It does not fail quietly: on a document
with an accented identifier or an emoji in a comment it throws
StringIndexOutOfBoundsException, because the byte offset runs past the
end of the shorter UTF-16 string.
SourceLabel now carries a class-level explanation with the byte-slicing
snippet callers should use instead, and the field comments name the
offsets as UTF-8 and give their inclusivity. It also records three other
properties that are not apparent from the types, all confirmed against
the parser:
- offsets are absolute within the whole parsed text rather than
relative to the enclosing policy, so they stay usable when several
policies are parsed together, and they carry no policy identity of
their own;
- a span may be empty, which is what an unterminated string literal
produces, so a renderer must not assume a character to underline;
- a span covers the unexpected token, which for a missing operand is
the token that followed it, possibly on a later line.
PolicyParseException's own Javadoc described how the class differed from
the generic error path that preceded it, and said getErrors() "does
change" -- relative to a revision no reader of the released class will
have seen. Rewritten to say what the type is: a list contrasting the
three accessors by fidelity, which is what a caller needs in order to
choose between them. The rationale for freezing getMessage() stays in
the private Rust that builds it, where it warns whoever might
reasonably re-break it, rather than in public API documentation.
Also adds the whitespace checkstyleMain wants inside the empty
TypeReference body in PolicyParseException, which was failing the build.
Signed-off-by: James Mulcahy <jmulcahy@netflix.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
ffdf01b to
c1eb82d
Compare
SpotBugs flagged the blanket `catch (Exception)` in readDetailedErrors (REC_CATCH_EXCEPTION). Catch JsonProcessingException and RuntimeException instead: same defensive behaviour, no catch of exceptions that cannot arise. Narrowing the catch exposed CT_CONSTRUCTOR_THROW, since the constructor can now throw and leave a partially initialised object. Make the class final, SpotBugs' remedy for that rule; it was never meant to be subclassed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Signed-off-by: James Mulcahy <jmulcahy@netflix.com>
1e6a918 to
8632241
Compare
|
@mark-creamer-amazon I pushed a fix for the CI failure; if you can approve again I'm optimistic we'll get a clean run, but I'll keep an eye on it! |
Problem
PolicySet.parsePoliciesthrowsInternalExceptionwhose message isformat!("Internal JNI Error: {e}")(CedarJavaFFI/src/interface.rs, injni_failed). For a parse failure that discards everythingmietterecorded — the source span, the tokens the parser expected, the help text — and becauseParseErrors'Displayprints only its first error, every subsequent error is lost too.A policy author writing this:
sees only:
No location, and no hint that the mistake is a missing
action ==. The Rust CLI, on the same input:Measured against cedar-java 4.10.0:
Change
Everything needed already exists in the crate:
PolicySet::from_strreturnsParseErrors, which isIntoIterator<Item = ParseError>ParseErrorimplementsmiette::Diagnosticcedar_policy::ffi::DetailedErroralready hasimpl<E: miette::Diagnostic + ?Sized> From<&E>— the impl the validation path already usesSo
parsePoliciesJnidowncastsParseErrorsand throws a newPolicyParseException extends InternalExceptioncarryingList<DetailedError>, the same representationAuthorizationEngine.validatealready returns:Existing
catch (InternalException e)blocks are unaffected. If building the richer exception fails for any reason, the generic path is used, so a parse error can never turn into a different kind of failure.Two message changes, both up for discussion
getMessage()Internal error: Internal JNI Error: unexpected token ...Internal error: unexpected token ...getErrors()[Internal JNI Error: unexpected token ...][unexpected token ...]"Internal JNI Error: "prefix is dropped — it describes the binding rather than the policy, and reading "Internal error" for an ordinary typo suggests a fault in the library rather than something the caller can fix.getErrors()carries one entry per parse error rather than a single entry for the whole document, which is what its plural contract always implied.Both are independent of the diagnostics and easy to drop if you'd rather keep the strings frozen — happy to revise.
Breaking?
Not to any type or signature:
PolicyParseExceptionis a subclass and no existing method changes shape. Callers string-matching on the message text of a parse failure would see the two differences above.Testing
PolicyParseDiagnosticsTests— span covers the offending token, all errors reported not just the first, help text survives where Cedar supplies it, still catchable asInternalException, message/getErrors()strings pinned, valid policy sets unaffected.CedarJavasuite: 68,723 tests, 0 failures.cargo testinCedarJavaFFI: 69 passed.Local FFI builds used
cargo build --release --features partial-evalfor the host target rather than thecargo zigbuildcross-compile path, sincezigwas not available in my environment; CI exercises the normal path.Scope
Deliberately limited to
parsePolicies.Policy.parseStaticPolicy,Policy.parsePolicyTemplate,Schema.parseandPolicyFormatterlose detail the same way and would be natural follow-ups — kept out here to keep the change focused, per CONTRIBUTING.Related: #68 asks for the id of a malformed policy, which is adjacent but stops short of diagnostics.