> For the complete documentation index, see [llms.txt](https://docs.soniclabs.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.soniclabs.com/sonic/node-deployment/node-hardening/appendix-d-filtering-proxy-nginx.md).

# Appendix D: Filtering Proxy (nginx)

An nginx example that meets the Tier 4 proxy requirements.

This example meets the [Tier 4.2](https://docs.soniclabs.com/sonic/node-deployment/node-hardening/tier-4-control-access.md) requirements using nginx with its JavaScript module (`njs`). Test it on a staging node before production, and run **all** the tests at the end, including the ones that try to sneak past the filter.

**Install.** The `nginx-module-njs` package comes from nginx's own repository, not from Ubuntu or Debian. Add it first by following the instructions at <https://nginx.org/en/linux_packages.html>, then:

```bash
sudo apt install nginx nginx-module-njs
```

**TLS certificate.** The proxy serves HTTPS, so it needs a certificate and key for its host name (e.g. `rpc.example.com`). Get one from Let's Encrypt (`certbot`) or your provider, and put the files where `ssl_certificate` and `ssl_certificate_key` point below.

**`/etc/nginx/njs/rpc_filter.js`**

```js
// Methods every authenticated client may call
var BASIC = [
  "eth_chainId", "eth_blockNumber", "eth_getBalance", "eth_getCode",
  "eth_getStorageAt", "eth_getTransactionCount", "eth_call", "eth_estimateGas",
  "eth_gasPrice", "eth_maxPriorityFeePerGas", "eth_feeHistory",
  "eth_getBlockByNumber", "eth_getBlockByHash", "eth_getLogs",
  "eth_getTransactionByHash", "eth_getTransactionReceipt",
  "eth_sendRawTransaction", "net_version", "web3_clientVersion"
];

// Extra methods for clients that need tracing
var TRACING = [
  "debug_traceCall", "debug_traceTransaction",
  "debug_traceBlockByNumber", "debug_traceBlockByHash"
];

// Which client (from the API key map in nginx.conf) may call what
var ACCESS = {
  "wallet-backend": BASIC,
  "indexer": BASIC.concat(TRACING)
};

// Only built-in tracers that can't run code from the request.
// Never add "muxTracer": it accepts other tracer names inside its settings,
// and the node treats any name it doesn't recognize as JavaScript code.
var SAFE_TRACERS = ["callTracer", "prestateTracer", "4byteTracer", "flatCallTracer"];

var MAX_BATCH = 50;
var MAX_DEPTH = 32;

// The node ignores upper/lower case in field names ("Tracer" is the same as
// "tracer"). This filter does not, so anything ambiguous is rejected below.
var TOP_FIELDS = ["jsonrpc", "id", "method", "params"];
var SENSITIVE = ["tracer", "tracerConfig"];

// True if every field name, at every level, means the same to the node as to us.
function unambiguous(v, depth) {
  if (depth > MAX_DEPTH) return false;
  if (Array.isArray(v)) {
    for (var i = 0; i < v.length; i++) {
      if (!unambiguous(v[i], depth + 1)) return false;
    }
    return true;
  }
  if (v === null || typeof v !== "object") return true;
  var seen = Object.create(null);
  var keys = Object.keys(v);
  for (var j = 0; j < keys.length; j++) {
    var k = keys[j];
    if (!/^[\x20-\x7e]*$/.test(k)) return false;       // unusual characters
    var lower = k.toLowerCase();
    if (seen[lower]) return false;                     // e.g. "tracer" and "Tracer"
    seen[lower] = true;
    for (var s = 0; s < SENSITIVE.length; s++) {       // e.g. "TRACER" on its own
      if (lower === SENSITIVE[s].toLowerCase() && k !== SENSITIVE[s]) return false;
    }
    if (!unambiguous(v[k], depth + 1)) return false;
  }
  return true;
}

function tracerAllowed(params) {
  if (!Array.isArray(params)) return true;
  for (var i = 0; i < params.length; i++) {
    var p = params[i];
    if (p && typeof p === "object" && p.tracer !== undefined) {
      if (typeof p.tracer !== "string" || SAFE_TRACERS.indexOf(p.tracer) === -1) return false;
    }
  }
  return true;
}

function allowed(client, req) {
  if (!req || typeof req !== "object" || Array.isArray(req)) return false;
  var fields = Object.keys(req);
  for (var i = 0; i < fields.length; i++) {
    if (TOP_FIELDS.indexOf(fields[i]) === -1) return false;   // e.g. "Method"
  }
  if (!unambiguous(req, 0)) return false;
  if (typeof req.method !== "string") return false;
  var list = ACCESS[client];
  if (!list || list.indexOf(req.method) === -1) return false;
  if (!tracerAllowed(req.params)) return false;
  return true;
}

function deny(r, status, why) {
  // JSON.stringify keeps request text on one log line, so it can't fake log entries
  r.error("rpc-filter: rejected client=" + r.variables.rpc_client +
          " ip=" + r.remoteAddress + " reason=" + JSON.stringify(why) +
          " body=" + JSON.stringify((r.requestText || "").slice(0, 2000)));
  r.headersOut["Content-Type"] = "application/json";
  r.return(status, '{"jsonrpc":"2.0","id":null,"error":{"code":-32601,"message":"request not allowed"}}');
}

function filter(r) {
  var client = r.variables.rpc_client;
  if (!client) return deny(r, 401, "no-or-bad-api-key");

  var body;
  try { body = JSON.parse(r.requestText); } catch (e) { return deny(r, 400, "bad-json"); }

  var items = Array.isArray(body) ? body : [body];
  if (items.length === 0 || items.length > MAX_BATCH) return deny(r, 403, "batch-size");

  for (var i = 0; i < items.length; i++) {
    if (!allowed(client, items[i])) return deny(r, 403, "method-or-tracer:" + (items[i] && items[i].method));
  }
  r.internalRedirect("@sonic");
}

export default { filter };
```

**`/etc/nginx/nginx.conf`** (relevant parts)

```nginx
load_module modules/ngx_http_js_module.so;   # at the very top, outside http {}

http {
    js_path   /etc/nginx/njs/;
    js_import rpc from rpc_filter.js;

    # One long random key per client. Generate with: openssl rand -hex 32
    map $http_x_api_key $rpc_client {
        default "";
        "REPLACE-WITH-RANDOM-KEY-1" "wallet-backend";
        "REPLACE-WITH-RANDOM-KEY-2" "indexer";
    }

    limit_req_zone  $rpc_client zone=rpc_rate:10m rate=50r/s;

    # Requests without a valid key don't count against rpc_rate (empty key),
    # so limit those per source IP instead
    map $rpc_client $rpc_anon_ip {
        ""      $binary_remote_addr;
        default "";
    }
    limit_req_zone  $rpc_anon_ip zone=rpc_anon:10m rate=5r/s;
    limit_conn_zone $rpc_client zone=rpc_conn:10m;

    upstream sonic_node {
        server 127.0.0.1:18545;      # the node, listening on localhost only
        keepalive 32;
    }

    server {
        listen 8443 ssl;
        ssl_certificate     /etc/nginx/tls/rpc.crt;
        ssl_certificate_key /etc/nginx/tls/rpc.key;

        client_max_body_size    1m;
        client_body_buffer_size 1m;   # keeps the body in memory so the filter can read it

        location = / {
            limit_req  zone=rpc_rate burst=100 nodelay;
            limit_req  zone=rpc_anon burst=10 nodelay;
            limit_conn rpc_conn 20;
            js_content rpc.filter;
        }

        location @sonic {
            proxy_pass http://sonic_node;
            # The node only accepts host names listed in --http.vhosts (Tier 1.4).
            # Without this line nginx would send "sonic_node", and the node would refuse it.
            proxy_set_header Host localhost;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_read_timeout 60s;
        }

        location / { return 404; }
    }
}
```

**Test it:**

```bash
sudo nginx -t && sudo systemctl reload nginx

URL=https://rpc.example.com:8443/
KEY1=REPLACE-WITH-RANDOM-KEY-1     # wallet-backend
KEY2=REPLACE-WITH-RANDOM-KEY-2     # indexer
# Prints only the HTTP status code of a request: status <key> '<request>'
status() { curl -s -o /dev/null -w '%{http_code}\n' "$URL" -H "x-api-key: $1" -H 'content-type: application/json' -d "$2"; }

# Allowed: should return a block number
curl -s "$URL" -H "x-api-key: $KEY1" -H 'content-type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}'

# Built-in tracer for the indexer: should be allowed (200)
status "$KEY2" '{"jsonrpc":"2.0","id":1,"method":"debug_traceCall","params":[{"to":"0x0000000000000000000000000000000000000000"},"latest",{"tracer":"callTracer"}]}'

# No key: should be rejected (401)
status "" '{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}'

# Tracing with the wallet-backend key: should be rejected (403)
status "$KEY1" '{"jsonrpc":"2.0","id":1,"method":"debug_traceCall","params":[{},"latest",{"tracer":"callTracer"}]}'

# Custom JavaScript tracer: should be rejected (403), even for the indexer key
status "$KEY2" '{"jsonrpc":"2.0","id":1,"method":"debug_traceCall","params":[{},"latest",{"tracer":"{result:function(){return 1},fault:function(){}}"}]}'
```

The next three requests try to slip past the filter. **Every one must be rejected (403).** If any of them returns 200, don't use the filter until you've found out why.

```bash
# "Tracer" with a capital T: the node treats it as "tracer"
status "$KEY2" '{"jsonrpc":"2.0","id":1,"method":"debug_traceCall","params":[{},"latest",{"Tracer":"{result:function(){return 1},fault:function(){}}"}]}'

# A second, capitalized "Method": the node would run debug_traceCall
status "$KEY1" '{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","Method":"debug_traceCall","params":[{},"latest"]}'

# muxTracer carrying JavaScript inside its settings
status "$KEY2" '{"jsonrpc":"2.0","id":1,"method":"debug_traceCall","params":[{},"latest",{"tracer":"muxTracer","tracerConfig":{"{result:function(){return 1},fault:function(){}}":{}}}]}'

# Rejections are logged here:
sudo grep rpc-filter /var/log/nginx/error.log
```
