DanielMarquard reported a bug where Discourse webhooks fail to parse JSON payloads in PHP due to a missing closing brace. While the payload appeared valid in Discourse logs, the data received by PHP was truncated. DanielMarquard confirmed the discrepancy by comparing the well-formed JSON from Discourse against the truncated output from their PHP script.
codinghorror asked for insights. fantasticfears identified the root cause: PHP respects the Content-Length header, but Discourse was calculating this value incorrectly because the payload size was not being counted in octets. This caused PHP to truncate the string prematurely. fantasticfears submitted a pull request (https://github.com/discourse/discourse/pull/4451) to fix the issue.
tgxworld asked if the Excon library sets the header correctly. fantasticfears confirmed that Excon does set Content-Length if not provided, showing the relevant code in connection.rb which uses detect_content_length for various body types. fantasticfears suggested creating a dedicated module for this logic to improve code reuse and make it easier to replace Excon in the future.
I set up a webhook in Discourse today for the first time. I’ve got a great use case for it and can’t wait to finish the code.
But the post and topic event JSON sent by Discourse is not playing well with my receiving PHP script. PHP fails to parse it. Through json_last_error_msg, I saw that there is a syntax error somewhere in the payload, which is why json_decode is failing.
From the webhook’s log panel in Discourse, the request JSON validated when I tested it, so I set up a simple script to verify that PHP is receiving the same data that Discourse is reporting, but that doesn’t seem to be the case.
Yes, it does if the field is not provided. In connection.rb:
body = datum[:body].is_a?(String) ? StringIO.new(datum[:body]) : datum[:body]
# The HTTP spec isn't clear on it, but specifically, GET requests don't usually send bodies;
# if they don't, sending Content-Length:0 can cause issues.
unless datum[:method].to_s.casecmp('GET') == 0 && body.nil?
unless datum[:headers].has_key?('Content-Length')
datum[:headers]['Content-Length'] = detect_content_length(body)
end
end
def detect_content_length(body)
if body.respond_to?(:size)
# IO object: File, Tempfile, StringIO, etc.
body.size
elsif body.respond_to?(:stat)
# for 1.8.7 where file does not have size
body.stat.size
else
0
end
end
Since we need to record that field in the log, it doesn’t matter.
But it’s worthwhile to build a module for the job and redeliver action. 1) Reuse the code. 2) Easier to replace Excon.
erlend_sh
(Erlend Sogge Heggen)
Разделил(а) эту тему
6