Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(storage): add support for content disposition and content type in getUrl #13615

Merged
merged 16 commits into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/aws-amplify/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@
"name": "[Storage] getUrl (S3)",
"path": "./dist/esm/storage/index.mjs",
"import": "{ getUrl }",
"limit": "15.51 kB"
"limit": "15.61 kB"
},
{
"name": "[Storage] list (S3)",
Expand All @@ -497,7 +497,7 @@
"name": "[Storage] uploadData (S3)",
"path": "./dist/esm/storage/index.mjs",
"import": "{ uploadData }",
"limit": "19.64 kB"
"limit": "19.66 kB"
}
]
}
129 changes: 129 additions & 0 deletions packages/storage/__tests__/providers/s3/apis/getUrl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,135 @@ describe('getUrl test with path', () => {
},
);
});
describe('Happy cases: With path and Content Disposition, Content Type', () => {
yuhengshs marked this conversation as resolved.
Show resolved Hide resolved
const config = {
credentials,
region,
userAgentValue: expect.any(String),
};
beforeEach(() => {
jest.mocked(headObject).mockResolvedValue({
ContentLength: 100,
ContentType: 'text/plain',
ETag: 'etag',
LastModified: new Date('01-01-1980'),
Metadata: { meta: 'value' },
$metadata: {} as any,
});
jest.mocked(getPresignedGetObjectUrl).mockResolvedValue(mockURL);
});
afterEach(() => {
jest.clearAllMocks();
});

test.each([
{
path: 'path',
expectedKey: 'path',
contentDisposition: 'inline; filename="example.txt"',
contentType: 'text/plain',
},
{
path: () => 'path',
expectedKey: 'path',
contentDisposition: {
type: 'attachment' as const,
yuhengshs marked this conversation as resolved.
Show resolved Hide resolved
filename: 'example.pdf',
},
contentType: 'application/pdf',
},
])(
'should getUrl with path $path and expectedKey $expectedKey and content disposition and content type',
async ({ path, expectedKey, contentDisposition, contentType }) => {
const headObjectOptions = {
Bucket: bucket,
Key: expectedKey,
};
const { url, expiresAt } = await getUrlWrapper({
path,
options: {
validateObjectExistence: true,
contentDisposition,
contentType,
},
});
expect(getPresignedGetObjectUrl).toHaveBeenCalledTimes(1);
expect(headObject).toHaveBeenCalledTimes(1);
await expect(headObject).toBeLastCalledWithConfigAndInput(
config,
headObjectOptions,
);
expect({ url, expiresAt }).toEqual({
url: mockURL,
expiresAt: expect.any(Date),
});
},
);
});
describe('Error cases: With invalid Content Disposition', () => {
const config = {
credentials,
region,
userAgentValue: expect.any(String),
};
beforeEach(() => {
jest.mocked(headObject).mockResolvedValue({
ContentLength: 100,
ContentType: 'text/plain',
ETag: 'etag',
LastModified: new Date('01-01-1980'),
Metadata: { meta: 'value' },
$metadata: {} as any,
});
jest.mocked(getPresignedGetObjectUrl).mockResolvedValue(mockURL);
});

afterEach(() => {
jest.clearAllMocks();
});

test.each([
{
path: 'path',
expectedKey: 'path',
contentDisposition: {
type: 'invalid' as const,
filename: '"example.txt',
},
},
{
path: 'path',
expectedKey: 'path',
contentDisposition: {
type: 'invalid' as const,
},
},
])(
'should ignore for invalid content disposition: $contentDisposition',
async ({ path, expectedKey }) => {
const headObjectOptions = {
Bucket: bucket,
Key: expectedKey,
};
const { url, expiresAt } = await getUrlWrapper({
path,
options: {
validateObjectExistence: true,
yuhengshs marked this conversation as resolved.
Show resolved Hide resolved
},
});
expect(getPresignedGetObjectUrl).toHaveBeenCalledTimes(1);
expect(headObject).toHaveBeenCalledTimes(1);
await expect(headObject).toBeLastCalledWithConfigAndInput(
config,
headObjectOptions,
);
expect({ url, expiresAt }).toEqual({
url: mockURL,
expiresAt: expect.any(Date),
});
},
);
});
describe('Error cases : With path', () => {
afterAll(() => {
jest.clearAllMocks();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,44 @@ describe('serializeGetObjectRequest', () => {
}),
);
});

it('should return get object API request with disposition and content type', async () => {
const actual = await getPresignedGetObjectUrl(
{
...defaultConfigWithStaticCredentials,
signingRegion: defaultConfigWithStaticCredentials.region,
signingService: 's3',
expiration: 900,
userAgentValue: 'UA',
},
{
Bucket: 'bucket',
Key: 'key',
ResponseContentDisposition: 'attachment; filename="filename.jpg"',
ResponseContentType: 'application/pdf',
},
);

expect(actual).toEqual(
expect.objectContaining({
hostname: `bucket.s3.${defaultConfigWithStaticCredentials.region}.amazonaws.com`,
pathname: '/key',
searchParams: expect.objectContaining({
get: expect.any(Function),
}),
}),
);

expect(actual.searchParams.get('X-Amz-Expires')).toBe('900');
expect(actual.searchParams.get('x-amz-content-sha256')).toEqual(
expect.any(String),
);
expect(actual.searchParams.get('response-content-disposition')).toBe(
'attachment; filename="filename.jpg"',
);
expect(actual.searchParams.get('response-content-type')).toBe(
'application/pdf',
);
expect(actual.searchParams.get('x-amz-user-agent')).toBe('UA');
});
});
9 changes: 9 additions & 0 deletions packages/storage/src/providers/s3/apis/internal/getUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
MAX_URL_EXPIRATION,
STORAGE_INPUT_KEY,
} from '../../utils/constants';
import { constructContentDisposition } from '../../utils/constructContentDisposition';

import { getProperties } from './getProperties';

Expand Down Expand Up @@ -74,6 +75,14 @@ export const getUrl = async (
{
Bucket: bucket,
Key: finalKey,
...(getUrlOptions?.contentDisposition && {
ResponseContentDisposition: constructContentDisposition(
getUrlOptions.contentDisposition,
),
}),
...(getUrlOptions?.contentType && {
ResponseContentType: getUrlOptions.contentType,
}),
},
),
expiresAt: new Date(Date.now() + urlExpirationInSec * 1000),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ResolvedS3Config } from '../../../types/options';
import { StorageUploadDataPayload } from '../../../../../types';
import { Part, createMultipartUpload } from '../../../utils/client';
import { logger } from '../../../../../utils';
import { constructContentDisposition } from '../../../utils/constructContentDisposition';

import {
cacheMultipartUpload,
Expand All @@ -22,7 +23,9 @@ interface LoadOrCreateMultipartUploadOptions {
keyPrefix?: string;
key: string;
contentType?: string;
contentDisposition?: string;
contentDisposition?:
| string
| { type: 'attachment' | 'inline'; filename?: string };
yuhengshs marked this conversation as resolved.
Show resolved Hide resolved
contentEncoding?: string;
metadata?: Record<string, string>;
size?: number;
Expand Down Expand Up @@ -102,7 +105,7 @@ export const loadOrCreateMultipartUpload = async ({
Bucket: bucket,
Key: finalKey,
ContentType: contentType,
ContentDisposition: contentDisposition,
ContentDisposition: constructContentDisposition(contentDisposition),
ContentEncoding: contentEncoding,
Metadata: metadata,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { ItemWithKey, ItemWithPath } from '../../types/outputs';
import { putObject } from '../../utils/client';
import { getStorageUserAgentValue } from '../../utils/userAgent';
import { STORAGE_INPUT_KEY } from '../../utils/constants';
import { constructContentDisposition } from '../../utils/constructContentDisposition';

/**
* Get a function the returns a promise to call putObject API to S3.
Expand Down Expand Up @@ -57,7 +58,7 @@ export const putObjectJob =
Key: finalKey,
Body: data,
ContentType: contentType,
ContentDisposition: contentDisposition,
ContentDisposition: constructContentDisposition(contentDisposition),
ContentEncoding: contentEncoding,
Metadata: metadata,
ContentMD5: isObjectLockEnabled
Expand Down
27 changes: 26 additions & 1 deletion packages/storage/src/providers/s3/types/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ interface CommonOptions {
useAccelerateEndpoint?: boolean;
}

/**
* Represents the content disposition of a file.
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
*/
export interface ContentDisposition {
type: 'attachment' | 'inline';
filename?: string;
}

/** @deprecated This may be removed in the next major version. */
type ReadOptions =
| {
Expand Down Expand Up @@ -114,6 +123,19 @@ export type GetUrlOptions = CommonOptions & {
* @default 900 (15 minutes)
*/
expiresIn?: number;
/**
* The default content-disposition header value of the file when downloading it.
* If a string is provided, it will be used as-is.
* If an object is provided, it will be used to construct the header value
* based on the ContentDisposition type definition.
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
*/
contentDisposition?: ContentDisposition | string;
/**
* The content-type header value of the file when downloading it.
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
*/
contentType?: string;
};

/** @deprecated Use {@link GetUrlOptionsWithPath} instead. */
Expand All @@ -135,9 +157,12 @@ export type UploadDataOptions = CommonOptions &
TransferOptions & {
/**
* The default content-disposition header value of the file when downloading it.
* If a string is provided, it will be used as-is.
* If an object is provided, it will be used to construct the header value
* based on the ContentDisposition type definition.
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
*/
contentDisposition?: string;
contentDisposition?: ContentDisposition | string;
/**
* The default content-encoding header value of the file when downloading it.
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
Expand Down
15 changes: 14 additions & 1 deletion packages/storage/src/providers/s3/utils/client/getObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ const USER_AGENT_HEADER = 'x-amz-user-agent';

export type GetObjectInput = Pick<
GetObjectCommandInput,
'Bucket' | 'Key' | 'Range'
| 'Bucket'
| 'Key'
| 'Range'
| 'ResponseContentDisposition'
| 'ResponseContentType'
>;

export type GetObjectOutput = GetObjectCommandOutput;
Expand Down Expand Up @@ -156,6 +160,15 @@ export const getPresignedGetObjectUrl = async (
config.userAgentValue,
);
}
if (input.ResponseContentType) {
url.searchParams.append('response-content-type', input.ResponseContentType);
}
if (input.ResponseContentDisposition) {
url.searchParams.append(
'response-content-disposition',
input.ResponseContentDisposition,
);
}

for (const [headerName, value] of Object.entries(headers).sort(
([key1], [key2]) => key1.localeCompare(key2),
Expand Down
yuhengshs marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { ContentDisposition } from '../types/options';

export const constructContentDisposition = (
contentDisposition?: string | ContentDisposition,
): string | undefined => {
if (typeof contentDisposition === 'object') {
const { type, filename } = contentDisposition;

return filename ? `${type}; filename="${filename}"` : type;
}

return contentDisposition;
};
Loading