Skip to content
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
899be42
init
christiangoerdes May 28, 2026
9a15d18
Implement JSON-RPC request validation with rules and batch support
christiangoerdes May 28, 2026
69d37c7
Add unit tests for JsonRPCProtectionInterceptor
christiangoerdes May 28, 2026
9b7da29
Refactor JSON-RPC validation logic into JsonRPCValidator for improved…
christiangoerdes May 28, 2026
9222fc2
Add JSON-RPC parameter schema validation with unit tests
christiangoerdes May 28, 2026
89e6590
Support JSON-RPC parameter schema validation with regex-based method …
christiangoerdes May 28, 2026
8a57b48
Merge branch 'master' into json-rpc-protection
christiangoerdes May 28, 2026
5a225af
Make `fromNode` method public in JSONRPCRequest, add logging to JsonR…
christiangoerdes May 28, 2026
329ee81
Merge remote-tracking branch 'origin/json-rpc-protection' into json-r…
christiangoerdes May 28, 2026
5bd32da
Add Javadoc comments for JSON-RPC protection classes with detailed de…
christiangoerdes May 28, 2026
4fd835a
Support XML-style parameter mappings for JSON-RPC schema validation a…
christiangoerdes May 28, 2026
de22caa
Refactor JSON-RPC validation: rename `rules` to `methods` and improve…
predic8 May 28, 2026
c4b7d4d
Merge remote-tracking branch 'origin/json-rpc-protection' into json-r…
predic8 May 28, 2026
6825c32
Fix test failures: set batch rules before interceptor init
christiangoerdes Jun 1, 2026
7d431c3
Filter child elements excluded from JSON schema in `JsonSchemaGenerat…
christiangoerdes Jun 1, 2026
c25259c
Refactor Allow/Deny rule hierarchy: move to util.allowdeny, rename me…
christiangoerdes Jun 1, 2026
fd8d1f7
Reject non-JSON content types in `JsonRPCProtectionInterceptor` with …
christiangoerdes Jun 1, 2026
7ce7007
Merge branch 'master' into json-rpc-protection
christiangoerdes Jun 1, 2026
c1bab2b
Move Allow/Deny rules to `util.config.allowdeny` package and update a…
christiangoerdes Jun 1, 2026
f52a9a6
Add JSON-RPC protection tutorial with method filtering, parameter val…
christiangoerdes Jun 1, 2026
cd0bd99
Add tests for JSON-RPC protection tutorial covering method filtering,…
christiangoerdes Jun 1, 2026
fe0833b
Switch JSON-RPC `params` method matching from regex to exact names an…
christiangoerdes Jun 1, 2026
f7d963f
Add result schema validation to JSON-RPC protection and refactor sche…
christiangoerdes Jun 1, 2026
f223210
Add JSON-RPC result schema validation for `rpc.echo` with test update…
christiangoerdes Jun 1, 2026
92bb547
disable response handling when result mappings are empty
christiangoerdes Jun 1, 2026
0b4ed0c
Update JSON-RPC protection tutorial and tests to use consistent `id` …
christiangoerdes Jun 1, 2026
2519939
Add schema validation support for JSON-RPC `params`, `response`, and …
christiangoerdes Jun 5, 2026
79f985a
Remove deprecated JSON-RPC `params` and `result` schema handling, rep…
christiangoerdes Jun 5, 2026
f957fdf
Remove redundant body empty check in `JsonRPCProtectionInterceptor` s…
christiangoerdes Jun 5, 2026
24db336
Add copyright headers to JSON-RPC interceptor classes
christiangoerdes Jun 5, 2026
666c123
Merge branch 'master' into json-rpc-protection
christiangoerdes Jun 5, 2026
7ba583f
Add inline schema support for JSON-RPC `error` validation, enhance do…
christiangoerdes Jun 5, 2026
63ec1ea
Merge remote-tracking branch 'origin/json-rpc-protection' into json-r…
christiangoerdes Jun 5, 2026
f7d5cbd
Use inline schema in tutorial
christiangoerdes Jun 5, 2026
7a1e798
Add response schema validation for JSON-RPC methods, update tests wit…
christiangoerdes Jun 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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());
}
}
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;
}
}
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());
}
}
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);
}
Comment thread
christiangoerdes marked this conversation as resolved.
Outdated

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) {
}
}
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();
}
}
Loading
Loading