From fc295f189eb762e56f81ec021fca79355958a54d Mon Sep 17 00:00:00 2001 From: "Martyn \"makit\" Kilbryde" <info@makit.net> Date: Thu, 12 Jan 2023 15:08:20 +0000 Subject: [PATCH] Fix Serverless JavaScript example (#86) * Update JavaScript example so it works OpenSearch Service ignores the body and doesn't want it signed - need to sign without the body before adding the body back into the request * Change signedRequest to request Co-authored-by: Liz Snyder <31932630+lizsnyder@users.noreply.github.com> --- doc_source/serverless-clients.md | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/doc_source/serverless-clients.md b/doc_source/serverless-clients.md index 9db58f9..24b9871 100644 --- a/doc_source/serverless-clients.md +++ b/doc_source/serverless-clients.md @@ -221,15 +221,20 @@ var client = new Client({ request.service = 'aoss'; request.region = ''; // e.g. us-east-1 - var contentLength = '0'; - - if (request.headers['content-length']) { - contentLength = request.headers['content-length']; - request.headers['content-length'] = '0'; - } + // You can't include Content-Length as a signed header, otherwise you'll get an invalid signature error. + // The body and content-length should be removed before signing to avoid the header being included + // and the signature being incorrectly calculated including the body. + var body = request.body; + request.body = undefined; + delete request.headers['content-length']; + + // Serverless collections expect this header in all requests with an HTTP body. The payload doesn't need to be signed; any value is fine. request.headers['x-amz-content-sha256'] = 'UNSIGNED-PAYLOAD'; + request = aws4.sign(request, AWS.config.credentials); - request.headers['content-length'] = contentLength; + + // Add the body back into the request now the signature has been calculated without it + request.body = body; return request } @@ -378,4 +383,4 @@ func main() { fmt.Print(resp.Status + "\n") } -``` \ No newline at end of file +```