forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload.service.spec.ts
More file actions
275 lines (227 loc) · 9.5 KB
/
Copy pathupload.service.spec.ts
File metadata and controls
275 lines (227 loc) · 9.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import { Test, TestingModule } from '@nestjs/testing';
import { ConfigService } from '@nestjs/config';
import { UploadService } from './upload.service';
import { BadRequestException } from '@nestjs/common';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { DEFAULT_UPLOAD_POLICY } from './upload-policy';
jest.mock('@aws-sdk/s3-request-presigner', () => ({
getSignedUrl: jest.fn(),
}));
// Mock the S3 client so command dispatch (e.g. deleteFile -> send) does not
// attempt a real AWS network call during tests, which would otherwise reject
// and surface as an unhandled promise rejection that crashes the test process.
const mockS3Send = jest.fn().mockResolvedValue({});
jest.mock('@aws-sdk/client-s3', () => {
const actual = jest.requireActual('@aws-sdk/client-s3');
return {
...actual,
S3Client: jest.fn().mockImplementation(() => ({
send: mockS3Send,
})),
};
});
describe('UploadService', () => {
let service: UploadService;
let configService: ConfigService;
const mockGetSignedUrl = getSignedUrl as jest.MockedFunction<typeof getSignedUrl>;
const mockConfigService = {
get: jest.fn((key: string) => {
const config: Record<string, string> = {
AWS_REGION: 'us-east-1',
AWS_ACCESS_KEY_ID: 'test-key',
AWS_SECRET_ACCESS_KEY: 'test-secret',
S3_BUCKET_NAME: 'test-bucket',
S3_ENDPOINT: 'http://localhost:4566',
};
return config[key];
}),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
UploadService,
{
provide: ConfigService,
useValue: mockConfigService,
},
],
}).compile();
service = module.get<UploadService>(UploadService);
configService = module.get<ConfigService>(ConfigService);
mockGetSignedUrl.mockReset();
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('constructor', () => {
it('should throw error when S3 configuration is missing', () => {
const incompleteConfig = {
get: jest.fn((key: string) => {
const config: Record<string, string> = {
AWS_REGION: 'us-east-1',
// Missing other required S3 config
};
return config[key];
}),
};
expect(() => new UploadService(incompleteConfig as unknown as ConfigService)).toThrow(
'Missing required S3 configuration'
);
});
it('should initialize with custom upload policy from environment', () => {
const customConfig = {
get: jest.fn((key: string) => {
const config: Record<string, string> = {
AWS_REGION: 'us-east-1',
AWS_ACCESS_KEY_ID: 'test-key',
AWS_SECRET_ACCESS_KEY: 'test-secret',
S3_BUCKET_NAME: 'test-bucket',
UPLOAD_MAX_FILE_SIZE: '5MB',
UPLOAD_ALLOWED_MIME_TYPES: 'image/jpeg,image/png',
UPLOAD_KEY_PREFIX: 'custom-uploads',
};
return config[key];
}),
};
const customService = new UploadService(customConfig as unknown as ConfigService);
expect(customService).toBeDefined();
});
});
describe('getPresignedUploadUrl', () => {
it('should throw error for invalid filename', async () => {
await expect(service.getPresignedUploadUrl('', 'image/jpeg'))
.rejects.toThrow(BadRequestException);
await expect(service.getPresignedUploadUrl(null as any, 'image/jpeg'))
.rejects.toThrow(BadRequestException);
});
it('should throw error for invalid content type', async () => {
await expect(service.getPresignedUploadUrl('test.jpg', ''))
.rejects.toThrow(BadRequestException);
await expect(service.getPresignedUploadUrl('test.jpg', null as any))
.rejects.toThrow(BadRequestException);
});
it('should validate allowed mime types', async () => {
await expect(
service.getPresignedUploadUrl('test.jpg', 'image/invalid'),
).rejects.toThrow(BadRequestException);
});
it('should throw error for disallowed file extension', async () => {
await expect(service.getPresignedUploadUrl('test.exe', 'application/octet-stream'))
.rejects.toThrow(BadRequestException);
});
it('should validate file size', async () => {
const largeSize = DEFAULT_UPLOAD_POLICY.maxFileSize + 1;
await expect(
service.getPresignedUploadUrl('test.jpg', 'image/jpeg', largeSize),
).rejects.toThrow(BadRequestException);
});
it('should throw error for invalid file size', async () => {
await expect(service.getPresignedUploadUrl('test.jpg', 'image/jpeg', -1))
.rejects.toThrow(BadRequestException);
await expect(service.getPresignedUploadUrl('test.jpg', 'image/jpeg', 'invalid' as any))
.rejects.toThrow(BadRequestException);
});
it('should generate presigned URL for valid file', async () => {
mockGetSignedUrl.mockResolvedValue('http://presigned-url');
const result = await service.getPresignedUploadUrl('test.jpg', 'image/jpeg', 1000000);
expect(result).toHaveProperty('url');
expect(result).toHaveProperty('key');
expect(result.key).toMatch(/^receipts\/[a-f0-9-]+-test\.jpg$/);
expect(result.url).toBe('http://presigned-url');
});
it('should sanitize filename properly', async () => {
mockGetSignedUrl.mockResolvedValue('http://presigned-url');
const result = await service.getPresignedUploadUrl('../../../etc/passwd.jpg', 'image/jpeg');
// Path-traversal sequences must be neutralized: separators and "../"
// tokens collapse to the replacement char and no ".." survives into the
// object key (matching the security-sound sanitizer in upload-policy).
expect(result.key).toMatch(/^receipts\/[a-f0-9-]+-___etc_passwd\.jpg$/);
expect(result.key).not.toContain('..');
});
it('should handle very long filenames', async () => {
mockGetSignedUrl.mockResolvedValue('http://presigned-url');
const longFilename = 'a'.repeat(300) + '.jpg';
const result = await service.getPresignedUploadUrl(longFilename, 'image/jpeg');
expect(result.key.length).toBeLessThan(500); // Should be truncated
});
it('should include metadata in upload command', async () => {
mockGetSignedUrl.mockResolvedValue('http://presigned-url');
await service.getPresignedUploadUrl('test.jpg', 'image/jpeg', 1000000);
expect(mockGetSignedUrl).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
input: expect.objectContaining({
Metadata: expect.objectContaining({
originalFilename: 'test.jpg',
uploadId: expect.any(String),
uploadedAt: expect.any(String),
}),
}),
}),
expect.any(Object)
);
});
});
describe('getPresignedDownloadUrl', () => {
it('should throw error for invalid key', async () => {
await expect(service.getPresignedDownloadUrl(''))
.rejects.toThrow(BadRequestException);
await expect(service.getPresignedDownloadUrl(null as any))
.rejects.toThrow(BadRequestException);
});
it('should throw error for path traversal attempts', async () => {
await expect(service.getPresignedDownloadUrl('../secret'))
.rejects.toThrow(BadRequestException);
await expect(service.getPresignedDownloadUrl('/etc/passwd'))
.rejects.toThrow(BadRequestException);
await expect(service.getPresignedDownloadUrl('..\\secret'))
.rejects.toThrow(BadRequestException);
});
it('should generate download URL for valid key', async () => {
const key = 'receipts/test-file.jpg';
mockGetSignedUrl.mockResolvedValue('http://download-url');
const result = await service.getPresignedDownloadUrl(key);
expect(result).toBe('http://download-url');
});
it('should include download headers in request', async () => {
mockGetSignedUrl.mockResolvedValue('http://download-url');
await service.getPresignedDownloadUrl('receipts/test-file.jpg');
expect(mockGetSignedUrl).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
input: expect.objectContaining({
ResponseCacheControl: expect.any(String),
ResponseContentDisposition: expect.any(String),
}),
}),
expect.any(Object)
);
});
});
describe('deleteFile', () => {
it('should throw error for invalid key', async () => {
await expect(service.deleteFile(''))
.rejects.toThrow(BadRequestException);
await expect(service.deleteFile(null as any))
.rejects.toThrow(BadRequestException);
});
it('should throw error for path traversal attempts', async () => {
await expect(service.deleteFile('../secret'))
.rejects.toThrow(BadRequestException);
});
it('should handle successful deletion', async () => {
// This test would require mocking S3Client.send
// For now, we'll test the validation logic
await expect(service.deleteFile('receipts/test-file.jpg')).toBeDefined();
});
});
describe('getPolicy', () => {
it('should return current upload policy', () => {
const policy = service.getPolicy();
expect(policy).toHaveProperty('allowedMimeTypes');
expect(policy).toHaveProperty('maxFileSize');
expect(policy).toHaveProperty('keyPrefix');
expect(policy).toHaveProperty('allowedExtensions');
});
});
});