-
Notifications
You must be signed in to change notification settings - Fork 166
add JsonRPCProtection plugin #2963
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
christiangoerdes
wants to merge
35
commits into
master
Choose a base branch
from
json-rpc-protection
base: master
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.
Open
Changes from 9 commits
Commits
Show all changes
35 commits
Select commit
Hold shift + click to select a range
899be42
init
christiangoerdes 9a15d18
Implement JSON-RPC request validation with rules and batch support
christiangoerdes 69d37c7
Add unit tests for JsonRPCProtectionInterceptor
christiangoerdes 9b7da29
Refactor JSON-RPC validation logic into JsonRPCValidator for improved…
christiangoerdes 9222fc2
Add JSON-RPC parameter schema validation with unit tests
christiangoerdes 89e6590
Support JSON-RPC parameter schema validation with regex-based method …
christiangoerdes 8a57b48
Merge branch 'master' into json-rpc-protection
christiangoerdes 5a225af
Make `fromNode` method public in JSONRPCRequest, add logging to JsonR…
christiangoerdes 329ee81
Merge remote-tracking branch 'origin/json-rpc-protection' into json-r…
christiangoerdes 5bd32da
Add Javadoc comments for JSON-RPC protection classes with detailed de…
christiangoerdes 4fd835a
Support XML-style parameter mappings for JSON-RPC schema validation a…
christiangoerdes de22caa
Refactor JSON-RPC validation: rename `rules` to `methods` and improve…
predic8 c4b7d4d
Merge remote-tracking branch 'origin/json-rpc-protection' into json-r…
predic8 6825c32
Fix test failures: set batch rules before interceptor init
christiangoerdes 7d431c3
Filter child elements excluded from JSON schema in `JsonSchemaGenerat…
christiangoerdes c25259c
Refactor Allow/Deny rule hierarchy: move to util.allowdeny, rename me…
christiangoerdes fd8d1f7
Reject non-JSON content types in `JsonRPCProtectionInterceptor` with …
christiangoerdes 7ce7007
Merge branch 'master' into json-rpc-protection
christiangoerdes c1bab2b
Move Allow/Deny rules to `util.config.allowdeny` package and update a…
christiangoerdes f52a9a6
Add JSON-RPC protection tutorial with method filtering, parameter val…
christiangoerdes cd0bd99
Add tests for JSON-RPC protection tutorial covering method filtering,…
christiangoerdes fe0833b
Switch JSON-RPC `params` method matching from regex to exact names an…
christiangoerdes f7d963f
Add result schema validation to JSON-RPC protection and refactor sche…
christiangoerdes f223210
Add JSON-RPC result schema validation for `rpc.echo` with test update…
christiangoerdes 92bb547
disable response handling when result mappings are empty
christiangoerdes 0b4ed0c
Update JSON-RPC protection tutorial and tests to use consistent `id` …
christiangoerdes 2519939
Add schema validation support for JSON-RPC `params`, `response`, and …
christiangoerdes 79f985a
Remove deprecated JSON-RPC `params` and `result` schema handling, rep…
christiangoerdes f957fdf
Remove redundant body empty check in `JsonRPCProtectionInterceptor` s…
christiangoerdes 24db336
Add copyright headers to JSON-RPC interceptor classes
christiangoerdes 666c123
Merge branch 'master' into json-rpc-protection
christiangoerdes 7ba583f
Add inline schema support for JSON-RPC `error` validation, enhance do…
christiangoerdes 63ec1ea
Merge remote-tracking branch 'origin/json-rpc-protection' into json-r…
christiangoerdes f7d5cbd
Use inline schema in tutorial
christiangoerdes 7a1e798
Add response schema validation for JSON-RPC methods, update tests wit…
christiangoerdes 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
17 changes: 17 additions & 0 deletions
17
core/src/main/java/com/predic8/membrane/core/interceptor/json/rpc/Allow.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,17 @@ | ||
| package com.predic8.membrane.core.interceptor.json.rpc; | ||
|
|
||
| import com.predic8.membrane.annot.MCElement; | ||
|
|
||
| @MCElement(name = "allow", collapsed = true, component = false, id = "rpc-allow") | ||
| public class Allow extends Rule { | ||
|
|
||
| @Override | ||
| boolean permits() { | ||
| return true; | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "Allow{method=%s}".formatted(getMethod()); | ||
| } | ||
| } |
34 changes: 34 additions & 0 deletions
34
core/src/main/java/com/predic8/membrane/core/interceptor/json/rpc/BatchRule.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,34 @@ | ||
| package com.predic8.membrane.core.interceptor.json.rpc; | ||
|
|
||
| import com.predic8.membrane.annot.MCAttribute; | ||
| import com.predic8.membrane.annot.MCElement; | ||
| import com.predic8.membrane.core.util.ConfigurationException; | ||
|
|
||
| @MCElement(name = "batch", component = false) | ||
| public class BatchRule { | ||
|
|
||
| private boolean enabled = true; | ||
|
|
||
| private Integer maxSize = 100; | ||
|
|
||
| @MCAttribute | ||
| public void setEnabled(boolean enabled) { | ||
| this.enabled = enabled; | ||
| } | ||
|
|
||
| @MCAttribute | ||
| public void setMaxSize(Integer maxSize) { | ||
| if (maxSize == null || maxSize < 1) { | ||
| throw new ConfigurationException("batch maxSize must be greater than 0"); | ||
| } | ||
| this.maxSize = maxSize; | ||
| } | ||
|
|
||
| public Integer getMaxSize() { | ||
| return maxSize; | ||
| } | ||
|
|
||
| public boolean isEnabled() { | ||
| return enabled; | ||
| } | ||
| } |
17 changes: 17 additions & 0 deletions
17
core/src/main/java/com/predic8/membrane/core/interceptor/json/rpc/Deny.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,17 @@ | ||
| package com.predic8.membrane.core.interceptor.json.rpc; | ||
|
|
||
| import com.predic8.membrane.annot.MCElement; | ||
|
|
||
| @MCElement(name = "deny", collapsed = true, component = false, id = "rpc-deny") | ||
| public class Deny extends Rule { | ||
|
|
||
| @Override | ||
| boolean permits() { | ||
| return false; | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "Deny{method=%s}".formatted(getMethod()); | ||
| } | ||
| } |
136 changes: 136 additions & 0 deletions
136
core/src/main/java/com/predic8/membrane/core/interceptor/json/rpc/JsonRPCParams.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,136 @@ | ||
| /* Copyright 2026 predic8 GmbH, www.predic8.com | ||
|
|
||
| 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 | ||
|
|
||
| http://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.predic8.membrane.core.interceptor.json.rpc; | ||
|
|
||
| import com.networknt.schema.InputFormat; | ||
| import com.networknt.schema.Schema; | ||
| import com.networknt.schema.SchemaLocation; | ||
| import com.networknt.schema.SchemaRegistry; | ||
| import com.networknt.schema.resource.SchemaLoader; | ||
| import com.predic8.membrane.annot.MCElement; | ||
| import com.predic8.membrane.annot.MCOtherAttributes; | ||
| import com.predic8.membrane.core.interceptor.schemavalidation.json.MembraneSchemaLoader; | ||
| import com.predic8.membrane.core.resolver.Resolver; | ||
| import com.predic8.membrane.core.util.ConfigurationException; | ||
| import com.predic8.membrane.core.util.URIFactory; | ||
|
|
||
| import java.io.IOException; | ||
| import java.io.InputStream; | ||
| import java.util.LinkedHashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.regex.Pattern; | ||
| import java.util.regex.PatternSyntaxException; | ||
|
|
||
| import static com.networknt.schema.InputFormat.JSON; | ||
| import static com.networknt.schema.InputFormat.YAML; | ||
| import static com.networknt.schema.SchemaRegistry.withDefaultDialect; | ||
| import static com.networknt.schema.SpecificationVersion.DRAFT_2020_12; | ||
| import static com.predic8.membrane.core.resolver.ResolverMap.combine; | ||
|
|
||
| @MCElement(name = "params", component = false) | ||
| public class JsonRPCParams { | ||
|
|
||
| private Map<String, String> params = new LinkedHashMap<>(); | ||
| private List<CompiledSchema> schemas = List.of(); | ||
|
|
||
| @MCOtherAttributes | ||
| public void setParams(Map<String, String> params) { | ||
| this.params = params == null ? new LinkedHashMap<>() : new LinkedHashMap<>(params); | ||
| } | ||
|
|
||
| public Map<String, String> getParams() { | ||
| return params; | ||
| } | ||
|
|
||
| public void init(Resolver resolver, URIFactory uriFactory, String beanBaseLocation) { | ||
| if (params.isEmpty()) { | ||
| schemas = List.of(); | ||
| return; | ||
| } | ||
| if (resolver == null || uriFactory == null) { | ||
| throw new ConfigurationException("Cannot initialize JSON-RPC param schemas without resolver context."); | ||
| } | ||
|
|
||
| schemas = params.entrySet().stream() | ||
| .map(entry -> new CompiledSchema( | ||
| entry.getKey(), | ||
| compilePattern(entry.getKey()), | ||
| loadSchema(entry.getKey(), entry.getValue(), resolver, uriFactory, beanBaseLocation) | ||
| )) | ||
| .toList(); | ||
| } | ||
|
|
||
| public Schema getSchema(String method) { | ||
| if (method == null) { | ||
| return null; | ||
| } | ||
|
|
||
| for (CompiledSchema schema : schemas) { | ||
| if (schema.pattern().matcher(method).matches()) { | ||
| return schema.schema(); | ||
| } | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| private static Schema loadSchema(String methodPattern, String schemaPath, Resolver resolver, URIFactory uriFactory, String beanBaseLocation) { | ||
| if (schemaPath == null || schemaPath.trim().isEmpty()) { | ||
| throw new ConfigurationException("JSON-RPC param schema path for method pattern '%s' must not be empty.".formatted(methodPattern)); | ||
| } | ||
|
|
||
| String resolvedLocation = combine(uriFactory, beanBaseLocation, schemaPath.trim()); | ||
| try (InputStream in = resolver.resolve(resolvedLocation)) { | ||
| Schema schema = createSchemaRegistry(resolver).getSchema( | ||
| SchemaLocation.of(resolvedLocation), | ||
| in, | ||
| getSchemaFormat(resolvedLocation) | ||
| ); | ||
| schema.initializeValidators(); | ||
| return schema; | ||
| } catch (IOException e) { | ||
| throw new ConfigurationException("Cannot read JSON-RPC param schema for method pattern '%s' from '%s'.".formatted(methodPattern, schemaPath), e); | ||
| } catch (RuntimeException e) { | ||
| throw new ConfigurationException("Cannot create JSON-RPC param schema for method pattern '%s' from '%s'.".formatted(methodPattern, schemaPath), e); | ||
| } | ||
| } | ||
|
|
||
| private static SchemaRegistry createSchemaRegistry(Resolver resolver) { | ||
| return withDefaultDialect( | ||
| DRAFT_2020_12, | ||
| builder -> builder.schemaLoader(SchemaLoader.builder() | ||
| .resourceLoaders(loaders -> loaders.values(list -> list.addFirst(new MembraneSchemaLoader(resolver)))) | ||
| .build()) | ||
| ); | ||
| } | ||
|
|
||
| private static InputFormat getSchemaFormat(String schemaLocation) { | ||
| return schemaLocation.toLowerCase().endsWith(".yaml") || schemaLocation.toLowerCase().endsWith(".yml") ? YAML : JSON; | ||
| } | ||
|
|
||
| private static Pattern compilePattern(String methodPattern) { | ||
| if (methodPattern == null || methodPattern.trim().isEmpty()) { | ||
| throw new ConfigurationException("JSON-RPC param method pattern must not be empty."); | ||
| } | ||
| try { | ||
| return Pattern.compile(methodPattern.trim()); | ||
| } catch (PatternSyntaxException e) { | ||
| throw new ConfigurationException("Invalid JSON-RPC param method regex: " + methodPattern, e); | ||
| } | ||
| } | ||
|
|
||
| private record CompiledSchema(String methodPattern, Pattern pattern, Schema schema) { | ||
| } | ||
| } | ||
140 changes: 140 additions & 0 deletions
140
...ain/java/com/predic8/membrane/core/interceptor/json/rpc/JsonRPCProtectionInterceptor.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,140 @@ | ||
| package com.predic8.membrane.core.interceptor.json.rpc; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.predic8.membrane.annot.MCChildElement; | ||
| import com.predic8.membrane.annot.MCElement; | ||
| import com.predic8.membrane.core.exchange.Exchange; | ||
| import com.predic8.membrane.core.http.Response; | ||
| import com.predic8.membrane.core.interceptor.AbstractInterceptor; | ||
| import com.predic8.membrane.core.interceptor.Outcome; | ||
| import com.predic8.membrane.core.interceptor.json.rpc.JsonRPCValidator.ValidationError; | ||
| import com.predic8.membrane.core.jsonrpc.JSONRPCRequest; | ||
| import com.predic8.membrane.core.jsonrpc.JSONRPCResponse; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import java.io.IOException; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
|
|
||
| import static com.predic8.membrane.core.http.MimeType.APPLICATION_JSON; | ||
| import static com.predic8.membrane.core.http.Response.statusCode; | ||
| import static com.predic8.membrane.core.interceptor.Interceptor.Flow.REQUEST; | ||
| import static com.predic8.membrane.core.interceptor.Outcome.CONTINUE; | ||
| import static com.predic8.membrane.core.interceptor.Outcome.RETURN; | ||
| import static com.predic8.membrane.core.interceptor.json.rpc.JsonRPCValidator.PayloadType.BATCH; | ||
| import static java.util.EnumSet.of; | ||
|
|
||
| @MCElement(name = "jsonRPCProtection") | ||
| public class JsonRPCProtectionInterceptor extends AbstractInterceptor { | ||
|
|
||
| private static final Logger log = LoggerFactory.getLogger(JsonRPCProtectionInterceptor.class); | ||
| private static final ObjectMapper OM = new ObjectMapper(); | ||
|
|
||
| private BatchRule batchRule = new BatchRule(); | ||
| private List<Rule> rules = List.of(); | ||
| private JsonRPCParams params = new JsonRPCParams(); | ||
| private JsonRPCValidator validator; | ||
|
|
||
| public JsonRPCProtectionInterceptor() { | ||
| name = "json rpc protection"; | ||
| setAppliedFlow(of(REQUEST)); | ||
| } | ||
|
|
||
| @Override | ||
| public void init() { | ||
| super.init(); | ||
| params.init(router.getResolverMap(), router.getConfiguration().getUriFactory(), getBeanBaseLocation()); | ||
| validator = createValidator(); | ||
| } | ||
|
|
||
| @Override | ||
| public Outcome handleRequest(Exchange exc) { | ||
| if (!"POST".equals(exc.getRequest().getMethod())) { | ||
| return CONTINUE; | ||
| } | ||
|
|
||
| String body = exc.getRequest().getBodyAsStringDecoded(); | ||
| if (body == null || body.isBlank()) { | ||
| return CONTINUE; | ||
| } | ||
|
|
||
| return reject(exc, getValidator().validate(body)); | ||
| } | ||
|
|
||
| private Outcome reject(Exchange exc, ValidationError error) { | ||
| if (error == null) { | ||
| return CONTINUE; | ||
| } | ||
| log.info("Rejected JSON-RPC request: {}", error.message()); | ||
| exc.setResponse(createErrorResponse(error)); | ||
| return RETURN; | ||
| } | ||
|
|
||
| @MCChildElement(order = 0) | ||
| public void setBatch(BatchRule batchRule) { | ||
| this.batchRule = batchRule; | ||
| validator = null; | ||
| } | ||
|
|
||
| @MCChildElement(order = 1) | ||
| public void setRules(List<Rule> rules) { | ||
| this.rules = rules == null ? List.of() : new ArrayList<>(rules); | ||
| validator = null; | ||
| } | ||
|
|
||
| @MCChildElement(order = 2) | ||
| public void setParams(JsonRPCParams params) { | ||
| this.params = params == null ? new JsonRPCParams() : params; | ||
| validator = null; | ||
| } | ||
|
|
||
| public BatchRule getBatch() { | ||
| return batchRule; | ||
| } | ||
|
|
||
| public List<Rule> getRules() { | ||
| return rules; | ||
| } | ||
|
|
||
| public JsonRPCParams getParams() { | ||
| return params; | ||
| } | ||
|
|
||
| private JsonRPCValidator getValidator() { | ||
| if (validator == null) { | ||
| validator = createValidator(); | ||
| } | ||
| return validator; | ||
| } | ||
|
|
||
| private JsonRPCValidator createValidator() { | ||
| params.init(router.getResolverMap(), router.getConfiguration().getUriFactory(), getBeanBaseLocation()); | ||
| return new JsonRPCValidator(batchRule, rules, params); | ||
| } | ||
|
|
||
| private Response createErrorResponse(ValidationError error) { | ||
| try { | ||
| if (error.payloadType() == BATCH) { | ||
| return statusCode(error.httpStatus()) | ||
| .contentType(APPLICATION_JSON) | ||
| .body(OM.writeValueAsString(List.of(JSONRPCResponse.error(responseId(error.request()), error.code(), error.message())))) | ||
| .build(); | ||
| } | ||
|
|
||
| return statusCode(error.httpStatus()) | ||
| .contentType(APPLICATION_JSON) | ||
| .body(JSONRPCResponse.error(responseId(error.request()), error.code(), error.message()).toJson()) | ||
| .build(); | ||
| } catch (IOException e) { | ||
| throw new RuntimeException("Could not create JSON-RPC error response", e); | ||
| } | ||
| } | ||
|
|
||
| private Object responseId(JSONRPCRequest request) { | ||
| if (request == null || request.isNotification()) { | ||
| return null; | ||
| } | ||
| return request.getId(); | ||
| } | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.