Issue Creating Signed Request in JavaScript to AWS for AWS managed Prometheus

I’m working on creating a lambda to query and dynamically stand up AWS managed Prometheus alarms. To do so, I need to make a signed http request and I’m getting this error:

“”statusCode”: 403, “headers”: “{n “date”: “Mon, 24 Jun 2024 12:00:23 GMT”,n “content-type”: “application/json”,n “content-length”: “1867”,n “connection”: “keep-alive”,n “x-amzn-requestid”: “7a6bc218-9f69-42ac-b2f9-cfb0b0832acf, 7a6bc218-9f69-42ac-b2f9-cfb0b0832acf”,n “server”: “amazon”,n “x-amzn-errortype”: “InvalidSignatureException”n}”, “body”: “{“message”:”The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.nnThe Canonical String for this request should have been”

The logging is very verbose and I’ll remove the sensitive logging once I move outside my test env.I’m also using a custom logging lib so you can ignore that part. I thought I had this configured correctly but now I’m getting stuck.

That being said, am I formatting this request wrong? Any ideas?

Here my code:

import {SignatureV4} from '@smithy/signature-v4';
import {defaultProvider} from '@aws-sdk/credential-provider-node';
import {HttpRequest} from '@smithy/protocol-http';
import {Sha256} from '@aws-crypto/sha256-browser';


const makeSignedRequest = async (
  path: string,
  region: string
): Promise<any> => {
  const hostname = `aps-workspaces.${region}.amazonaws.com`;
  const request = new HttpRequest({
    method: 'GET',
    protocol: 'https:',
    hostname,
    path,
    headers: {
      'Content-Type': 'application/json',
      Host: hostname, // Explicitly adding the Host header
    },
  });
  
  request.headers.Host = hostname; // Explicitly adding the Host header
  log
    .info()
    .str('initialRequest', JSON.stringify(request, null, 2))
    .msg('Initial request object');
  const signer = new SignatureV4({
    credentials: defaultProvider(),
    region,
    service: 'aps',
    sha256: Sha256,
  });
  const signedRequest = await signer.sign(request);
  log
    .info()
    .str(
      'signedRequest',
      JSON.stringify(
        {
          method: signedRequest.method,
          protocol: signedRequest.protocol,
          hostname: signedRequest.hostname,
          path: signedRequest.path,
          headers: signedRequest.headers,
        },
        null,
        2
      )
    )
    .msg('Signed request object');
  return new Promise((resolve, reject) => {
    const req = https.request(
      {
        hostname: signedRequest.hostname,
        path: signedRequest.path,
        method: signedRequest.method,
        headers: signedRequest.headers,
      },
      res => {
        let data = '';
        res.on('data', chunk => {
          data += chunk;
        });
        res.on('end', () => {
          log
            .info()
            .num('statusCode', res.statusCode || 0)
            .str('headers', JSON.stringify(res.headers, null, 2))
            .str('body', data)
            .msg('Response received');
          try {
            const parsedData = JSON.parse(data);
            resolve(parsedData);
          } catch (error) {
            log
              .error()
              .err(error)
              .str('rawData', data)
              .msg('Failed to parse response data');
            reject(error);
          }
        });
      }
    );
    req.on('error', error => {
      log.error().err(error).msg('Request error');
      reject(error);
    });
    req.end();
  });
};const makeSignedRequest = async (
  path: string,
  region: string
): Promise<any> => {
  const hostname = `aps-workspaces.${region}.amazonaws.com`;
  const request = new HttpRequest({
    method: 'GET',
    protocol: 'https:',
    hostname,
    path,
    headers: {
      'Content-Type': 'application/json',
      Host: hostname, 
    },
  });

 
  request.headers.Host = hostname; 

  log
    .info()
    .str('initialRequest', JSON.stringify(request, null, 2))
    .msg('Initial request object');

  const signer = new SignatureV4({
    credentials: defaultProvider(),
    region,
    service: 'aps',
    sha256: Sha256,
  });

  const signedRequest = await signer.sign(request);

  log
    .info()
    .str(
      'signedRequest',
      JSON.stringify(
        {
          method: signedRequest.method,
          protocol: signedRequest.protocol,
          hostname: signedRequest.hostname,
          path: signedRequest.path,
          headers: signedRequest.headers,
        },
        null,
        2
      )
    )
    .msg('Signed request object');

  return new Promise((resolve, reject) => {
    const req = https.request(
      {
        hostname: signedRequest.hostname,
        path: signedRequest.path,
        method: signedRequest.method,
        headers: signedRequest.headers,
      },
      res => {
        let data = '';
        res.on('data', chunk => {
          data += chunk;
        });
        res.on('end', () => {
          log
            .info()
            .num('statusCode', res.statusCode || 0)
            .str('headers', JSON.stringify(res.headers, null, 2))
            .str('body', data)
            .msg('Response received');

          try {
            const parsedData = JSON.parse(data);
            resolve(parsedData);
          } catch (error) {
            log
              .error()
              .err(error)
              .str('rawData', data)
              .msg('Failed to parse response data');
            reject(error);
          }
        });
      }
    );

    req.on('error', error => {
      log.error().err(error).msg('Request error');
      reject(error);
    });

    req.end();
  });
};

The signed request should be pulling the correct creds and signing the req but for the life of me I can’t see where I’m going wrong.

New contributor

William Rose is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật