I have two endpoints and I want one of them to be accessible by requests from the localhost only. The other one should receive requests from anywhere. In the Security section of the documentation I found the next configuration:
"extra_config": {
"github_com/devopsfaith/krakend-httpsecure": {
"allowed_hosts": [
"host.known.com:443"
]
}
}
But this is at the root level only. Also, this includes the port, I need to filter for the criteria: "Comes from the localhost?"
Is there a way in which I can meet this requirement? Whether using KrakenD, IPTables, etc...
KrakenD Enterprise solves that for you. But if you are with the Community version, then you can use the Common Expression Language (CEL) component.
Although it's much more limited than IP filtering (Enterprise) itself, CEL allows you to write pre-conditions before your backends are actually hit.
An example that checks that a request is coming from localhost (IPv6):
{
"endpoint": "/localhost-ipv6",
"extra_config": {
"validation/cel": [
{
"check_expr": "'127.0.0.1' in req_headers['X-Forwarded-For']"
}
]
}
}
You can adjust the above snippet with the exact value of the X-Forwarded-For
you are receiving in your environment. To make sure you are testing the right thing, create a test endpoint like the following:
{
"endpoint": "/test-headers",
"backend": [
{
"host": ["http://localhost:8080"],
"url_pattern": "/__debug/"
}
]
}
Start krakend with krakend run -d -c krakend.json
and then fire a request from inside and outside. You will see in the KrakenD logs the headers. Like:
2022/03/15 10:38:26 KRAKEND DEBUG: [ENDPOINT: /__debug/*] Headers: map[Accept-Encoding:[gzip] User-Agent:[KrakenD Version 2.0.0] X-Forwarded-For:[127.0.0.1] X-Forwarded-Host:[localhost:8080]]
Finally, there are other ways to solve this with the CEL component. You can even create a pseudo authentication with CEL with something like:
{
"validation/cel": [
{
"check_expr": "'acbdefghijklmnopqrstuvwxyz1234567890' in req_headers['X-KEY']"
}
]
}
There are more examples in the documentation https://www.krakend.io/docs/endpoints/common-expression-language-cel/