mikyll commented on issue #11964:
URL: https://github.com/apache/apisix/issues/11964#issuecomment-2650183515

   That's because `2607:fea8:bba0:7c00:cd88:f5a6:5fb0:2a56:51108` is not a 
valid IPv6 address 👀 
   
   According to standard [RFC 4291 - IP Version 6 Addressing 
Architecture](https://www.rfc-editor.org/rfc/rfc4291.html#section-2.2), the 
IPv6 address consists of 128 bits, typically represented as **eight groups of 
16-bit pieces in hexadecimal, separated by colons** (`:`): 
`xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx`.
   
   Since your address presents 9 of these, and the last one has 5 digits, the 
plugin throws an error, because it doesn't expect to find the port. Moreover, 
according to the standard, typically you would write the `IPv6` + `port` like 
this: `[IPv6]:port`, but real-ip doesn't expect to find the port anyways, so it 
doesn't matter in this case.
   
   In fact, 
[real-ip](https://github.com/apache/apisix/blob/a747b06988bba80a3f4287452d17418b950ced93/apisix/plugins/real-ip.lua#L154C68-L154C78)
 uses 
[`resty.ipmatcher.parse_ipv6()`](https://github.com/api7/lua-resty-ipmatcher/blob/3e93c53eb8c9884efe939ef070486a0e507cc5be/resty/ipmatcher.lua#L78-L104)
 to match the IPv6, which doesn't handle ports.
   
   To solve this issue, you can pre-process the header to remove the port, for 
example by using 
[serverless-pre-function](https://apisix.apache.org/docs/apisix/plugins/serverless/)
 (**NB**: you have to change its priority to `>23000` for it to run before 
real-ip plugin):
   
   ```json
   ...
   "plugins": {
     "real-ip": {
       ...
     },
     "serverless-pre-function": {
       "_meta": 23001,
       "phase": "rewrite",
       "functions": [
         "return function(); local my_header = 
ngx.req.get_headers()['X-Forwarded-For']; if my_header then; 
ngx.req.set_header('X-Forwarded-For', [value](my_header:gsub(":[^:]+$", ""))); 
end; end"
       ]
     }
   },
   ```
   
   Full Lua function:
   
   ```lua
   function()
     local my_header = ngx.req.get_headers()['X-Forwarded-For']
     if my_header then
       ngx.req.set_header('X-Forwarded-For', [value](my_header:gsub(":[^:]+$", 
"")))
     end
   end
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to