Skip to content

Commit

Permalink
fix(s3-request-presigner): add port to host name if missed (#3897)
Browse files Browse the repository at this point in the history
  • Loading branch information
AllanZhengYP authored Sep 15, 2022
1 parent b439cea commit 37f574f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
30 changes: 30 additions & 0 deletions packages/s3-request-presigner/src/presigner.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,34 @@ describe("s3 presigner", () => {
host: `${minimalRequest.hostname}:${port}`,
});
});

it("should inject host header with port if current host header missing port", async () => {
const signer = new S3RequestPresigner(s3ResolvedConfig);
const port = 12345;
const signed = await signer.presign({
...minimalRequest,
headers: {
host: minimalRequest.hostname,
},
port,
});
expect(signed.headers).toMatchObject({
host: `${minimalRequest.hostname}:${port}`,
});
});

it("should NOT overwrite host header if different host header is already set", async () => {
const signer = new S3RequestPresigner(s3ResolvedConfig);
const port = 12345;
const signed = await signer.presign({
...minimalRequest,
headers: {
host: "proxy." + minimalRequest.hostname,
},
port,
});
expect(signed.headers).toMatchObject({
host: "proxy." + minimalRequest.hostname,
});
});
});
13 changes: 7 additions & 6 deletions packages/s3-request-presigner/src/presigner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export class S3RequestPresigner implements RequestPresigner {
this.signer = new SignatureV4MultiRegion(resolvedOptions);
}

public async presign(
public presign(
requestToSign: IHttpRequest,
{ unsignableHeaders = new Set(), unhoistableHeaders = new Set(), ...options }: RequestPresigningArguments = {}
): Promise<IHttpRequest> {
Expand All @@ -38,11 +38,12 @@ export class S3RequestPresigner implements RequestPresigner {
unhoistableHeaders.add(header);
});
requestToSign.headers[SHA256_HEADER] = UNSIGNED_PAYLOAD;
if (!requestToSign.headers["host"]) {
requestToSign.headers.host = requestToSign.hostname;
if (requestToSign.port) {
requestToSign.headers.host = `${requestToSign.headers.host}:${requestToSign.port}`;
}

const currentHostHeader = requestToSign.headers.host;
const port = requestToSign.port;
const expectedHostHeader = `${requestToSign.hostname}${requestToSign.port != null ? ":" + port : ""}`;
if (!currentHostHeader || (currentHostHeader === requestToSign.hostname && requestToSign.port != null)) {
requestToSign.headers.host = expectedHostHeader;
}
return this.signer.presign(requestToSign, {
expiresIn: 900,
Expand Down

0 comments on commit 37f574f

Please sign in to comment.