Kong / kong-python-pdk

Write Kong plugins in Python (Experimental)
Apache License 2.0
40 stars 14 forks source link

kong.request.get_header() is returning list instead of string #139

Open vitorluis opened 5 months ago

vitorluis commented 5 months ago

Hello folks,

I've being playing around with custom plugins for Kong using Python and I have the following plugin running on my data plane nodes:

#!/usr/bin/env python3
import os
import kong_pdk.pdk.kong as kong

Schema = (
    {"message": {"type": "string"}},
)

version = '0.1.0'
priority = 0

# This is an example plugin that add a header to the response

class Plugin(object):
    def __init__(self, config):
        self.config = config

    def access(self, kong: kong.kong):
        host, err = kong.request.get_header("host")
        if err:
            pass  # error handling
        # if run with --no-lua-style
        # try:
        #     host = kong.request.get_header("host")
        # except Exception as ex:
        #     pass  # error handling
        message = "hello"
        if 'message' in self.config:
            message = self.config['message']
        kong.service.request.set_header("x-hello-from-python", "Python says %s to %s" % (message, host))
        kong.service.request.set_header("x-python-pid", str(os.getpid()))

        kong.log.info("Client headers", kong.request.get_headers())
        kong.service.request.set_header("X-Client-Header", kong.request.get_header("X-Client-Header"))

# add below section to allow this plugin optionally be running in a dedicated process
if __name__ == "__main__":
    from kong_pdk.cli import start_dedicated_server

    start_dedicated_server("test-plugin", Plugin, version, priority, Schema)

The problem happens on kong.service.request.set_header("X-Client-Header", kong.request.get_header("X-Client-Header")), when calling this kong.request.get_header("X-Client-Header") I get an error. Sorry I don't have the complete log line but it was stating str_find expecting string, got table.

In order to make it work I had to do the following:

kong.service.request.set_header("X-Client-Header", kong.request.get_header("X-Client-Header")[0])

I also logged the headers that came in the request and got the following:

Client headers ({'postman-token': ['18dce4fb-c9b8-463a-8309-651285c5657e'], 'accept-encoding': ['gzip, deflate, br'], 'x-hello-from-python': ['Python says Iron Maiden to apigtwyapps-int-stg.netapp.com'], 'host': ['apigtwyapps-int-stg.netapp.com'], 'user-agent': ['PostmanRuntime/7.36.1'], 'x-python-pid': ['7939'], 'x-forwarded-for': ['10.249.71.53'], 'accept': ['*/*'], 'x-forwarded-proto': ['https'], 'x-client-header': ['Metallica']}, None)

Any idea why is this happening?

Kong Gateway version: 3.5.0.2 PDK: 0.36

Thanks.