@nathapp/nestjs-storage 2.1.5 → 3.0.0-rc.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +129 -9
- package/dist/module/storage.module.js.map +1 -1
- package/dist/providers/azure-blob-storage.d.ts +22 -0
- package/dist/providers/azure-blob-storage.js +169 -0
- package/dist/providers/azure-blob-storage.js.map +1 -0
- package/dist/providers/base-storage.d.ts +3 -5
- package/dist/providers/base-storage.js +4 -1
- package/dist/providers/base-storage.js.map +1 -1
- package/dist/providers/dropbox-storage.d.ts +3 -5
- package/dist/providers/dropbox-storage.js +84 -151
- package/dist/providers/dropbox-storage.js.map +1 -1
- package/dist/providers/gcs-storage.d.ts +22 -0
- package/dist/providers/gcs-storage.js +132 -0
- package/dist/providers/gcs-storage.js.map +1 -0
- package/dist/providers/gdrive-storage.d.ts +3 -5
- package/dist/providers/gdrive-storage.js +109 -192
- package/dist/providers/gdrive-storage.js.map +1 -1
- package/dist/providers/index.d.ts +2 -0
- package/dist/providers/index.js +2 -0
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/local-storage.d.ts +5 -6
- package/dist/providers/local-storage.js +68 -128
- package/dist/providers/local-storage.js.map +1 -1
- package/dist/providers/oss-storage.d.ts +1 -1
- package/dist/providers/oss-storage.js +10 -4
- package/dist/providers/oss-storage.js.map +1 -1
- package/dist/providers/provider-factory.js +8 -0
- package/dist/providers/provider-factory.js.map +1 -1
- package/dist/providers/s3-base-storage.d.ts +7 -10
- package/dist/providers/s3-base-storage.js +50 -95
- package/dist/providers/s3-base-storage.js.map +1 -1
- package/dist/service/storage-service.d.ts +3 -0
- package/dist/service/storage-service.js +25 -4
- package/dist/service/storage-service.js.map +1 -1
- package/dist/types/capabilities.d.ts +15 -0
- package/dist/types/capabilities.js +3 -0
- package/dist/types/capabilities.js.map +1 -0
- package/dist/types/clients.d.ts +216 -0
- package/dist/types/clients.js +3 -0
- package/dist/types/clients.js.map +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js +1 -0
- package/dist/types/index.js.map +1 -1
- package/dist/types/options.d.ts +28 -2
- package/dist/types/options.js +2 -0
- package/dist/types/options.js.map +1 -1
- package/dist/types/storage.d.ts +7 -2
- package/dist/util/imageUtils.js +9 -3
- package/dist/util/imageUtils.js.map +1 -1
- package/docs/20260215-fix-plan-storage.md +66 -0
- package/docs/20260215-implementation-report.md +33 -0
- package/docs/20260215-plan-storage-providers.md +207 -0
- package/docs/20260215-review-storage-postfix.md +278 -0
- package/docs/20260215-review-storage.md +284 -0
- package/docs/20260216-plan-storage-a-minus.md +41 -0
- package/docs/20260216-review-storage-postfix2.md +102 -0
- package/docs/gdrive-security.md +222 -0
- package/docs/provider-capabilities.md +448 -0
- package/package.json +8 -3
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
# Deep Code Review: @nathapp/nestjs-storage
|
|
2
|
+
|
|
3
|
+
**Date:** 2026-02-15
|
|
4
|
+
**Reviewer:** Subrina (AI)
|
|
5
|
+
**Version:** 2.1.5
|
|
6
|
+
**Files:** 21 (lib: ~1800 LOC, test: ~300 LOC)
|
|
7
|
+
**Baseline:** 4 test suites, most tests commented out/skipped
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Overall Grade: C (65/100)
|
|
12
|
+
|
|
13
|
+
The package provides a useful abstraction over multiple cloud storage providers (S3, Azure Blob, Alibaba OSS, Google Drive, Local, NFS, Dropbox). However, it suffers from significant security vulnerabilities, anti-patterns, and incomplete implementation. The codebase uses outdated callback-style patterns wrapped in unnecessary `new Promise` constructors, has no path traversal protection in LocalStorage, includes unused imports that could expose credentials, and has minimal functional test coverage.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Findings
|
|
18
|
+
|
|
19
|
+
### 🔴 CRITICAL
|
|
20
|
+
|
|
21
|
+
#### SEC-1: Path Traversal Vulnerability in LocalStorage
|
|
22
|
+
**Severity:** CRITICAL | **Category:** Security
|
|
23
|
+
```typescript
|
|
24
|
+
// lib/providers/local-storage.ts:72
|
|
25
|
+
putFile(path: string, data: Buffer) {
|
|
26
|
+
return new Promise<IFile>((resolve, reject) => {
|
|
27
|
+
fs.writeFile(path, data, (err) => { // No validation of 'path'
|
|
28
|
+
```
|
|
29
|
+
**Risk:** An attacker can provide paths like `../../../../etc/passwd` or `../../.ssh/id_rsa` to read/write files outside the intended storage root. The `root` property is stored but never used for validation.
|
|
30
|
+
**Fix:**
|
|
31
|
+
```typescript
|
|
32
|
+
private validatePath(userPath: string): string {
|
|
33
|
+
const resolved = path.resolve(this.root, userPath);
|
|
34
|
+
if (!resolved.startsWith(this.root)) {
|
|
35
|
+
throw new Error('Path traversal detected');
|
|
36
|
+
}
|
|
37
|
+
return resolved;
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
#### SEC-2: Unused AWS Import Exposes Credentials
|
|
42
|
+
**Severity:** CRITICAL | **Category:** Security
|
|
43
|
+
```typescript
|
|
44
|
+
// lib/types/storage.ts:1
|
|
45
|
+
import { bool } from "aws-sdk/clients/signer";
|
|
46
|
+
```
|
|
47
|
+
**Risk:** This unused import forces the `aws-sdk` package to be loaded, which searches for AWS credentials in environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`). If these are set globally (common in CI/CD), they could leak to error logs or be accessed by other code.
|
|
48
|
+
**Fix:** Remove the unused import entirely.
|
|
49
|
+
|
|
50
|
+
#### BUG-1: S3 readFile Returns Wrong Type
|
|
51
|
+
**Severity:** CRITICAL | **Category:** Bug
|
|
52
|
+
```typescript
|
|
53
|
+
// lib/providers/s3-base-storage.ts:94
|
|
54
|
+
readFile(fileId: string) {
|
|
55
|
+
return new Promise<NodeJS.ReadableStream>((resolve, reject) => {
|
|
56
|
+
this.storage.getObject({ /* ... */ })
|
|
57
|
+
.promise()
|
|
58
|
+
.then((data) => {
|
|
59
|
+
resolve(data.Body as NodeJS.ReadableStream); // WRONG: Body is Buffer | Uint8Array | Blob | string | Readable
|
|
60
|
+
```
|
|
61
|
+
**Risk:** S3's `GetObjectOutput.Body` is not always a `ReadableStream`. It can be a `Buffer`, `Blob`, `string`, or `Readable` depending on the environment and SDK version. Consumers expecting a stream will crash when they try to `.pipe()` or listen to events on a Buffer.
|
|
62
|
+
**Fix:** Use `createReadStream()` or ensure Body is converted to a proper stream:
|
|
63
|
+
```typescript
|
|
64
|
+
const readable = new Readable();
|
|
65
|
+
readable.push(data.Body);
|
|
66
|
+
readable.push(null);
|
|
67
|
+
resolve(readable);
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
#### MEM-1: No Resource Cleanup in LocalStorage Streams
|
|
71
|
+
**Severity:** CRITICAL | **Category:** Memory Leak
|
|
72
|
+
```typescript
|
|
73
|
+
// lib/providers/local-storage.ts:86
|
|
74
|
+
readFile(fileId: string) {
|
|
75
|
+
return new Promise<NodeJS.ReadableStream>((resolve, reject) => {
|
|
76
|
+
this.getFileOrFolder(fileId).then((file) => {
|
|
77
|
+
const stream = fs.createReadStream(fileId);
|
|
78
|
+
resolve(stream); // No error listener attached
|
|
79
|
+
```
|
|
80
|
+
**Risk:** If the stream encounters an error (e.g., file deleted mid-read, permissions changed), the error is unhandled and the file descriptor leaks. In long-running services, this leads to "too many open files" crashes.
|
|
81
|
+
**Fix:** Attach an error listener before resolving:
|
|
82
|
+
```typescript
|
|
83
|
+
const stream = fs.createReadStream(fileId);
|
|
84
|
+
stream.on('error', reject);
|
|
85
|
+
resolve(stream);
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
### 🟡 MEDIUM
|
|
91
|
+
|
|
92
|
+
#### PERF-1: Anti-Pattern: Unnecessary Promise Wrappers
|
|
93
|
+
**Severity:** MEDIUM | **Category:** Performance/Code Quality
|
|
94
|
+
**Locations:** LocalStorage (all methods), S3BaseStorage (5 methods), OssStorage (3 methods), GDriveStorage (all methods)
|
|
95
|
+
```typescript
|
|
96
|
+
// Example from lib/providers/local-storage.ts:28
|
|
97
|
+
createFolder(filePath: string) {
|
|
98
|
+
return new Promise<IFile>((resolve, reject) => {
|
|
99
|
+
fs.mkdir(filePath, (err) => { // Should use fs.promises.mkdir
|
|
100
|
+
if (err) { reject(err); } else { /* ... */ }
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
**Risk:**
|
|
106
|
+
- Creates unnecessary promise overhead (double wrapping)
|
|
107
|
+
- Uses outdated callback-style fs APIs when `fs.promises` exists since Node 10
|
|
108
|
+
- Harder to maintain and test
|
|
109
|
+
- More error-prone (forgetting to reject/resolve)
|
|
110
|
+
|
|
111
|
+
**Fix:** Use `fs.promises` or `util.promisify`:
|
|
112
|
+
```typescript
|
|
113
|
+
async createFolder(filePath: string): Promise<IFile> {
|
|
114
|
+
await fs.promises.mkdir(filePath);
|
|
115
|
+
return this.getFileOrFolder(filePath);
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
#### TYPE-1: Excessive use of `any` Types
|
|
120
|
+
**Severity:** MEDIUM | **Category:** Type Safety
|
|
121
|
+
**Locations:**
|
|
122
|
+
- `s3-base-storage.ts:12` - `private readonly storage: any`
|
|
123
|
+
- `oss-storage.ts:13` - `private readonly storage: any`
|
|
124
|
+
- `gdrive-storage.ts:9` - `private readonly drive: any`
|
|
125
|
+
- Multiple method signatures use `any` for provider-specific types
|
|
126
|
+
|
|
127
|
+
**Risk:** No compile-time type checking for storage provider operations. Typos and incorrect method calls only discovered at runtime.
|
|
128
|
+
**Fix:** Define minimal interfaces for the expected provider API or use proper SDK types with `loadPackage` type assertions.
|
|
129
|
+
|
|
130
|
+
#### BUG-2: compressImageBuffer Unsafe Format Handling
|
|
131
|
+
**Severity:** MEDIUM | **Category:** Bug
|
|
132
|
+
```typescript
|
|
133
|
+
// lib/util/imageUtils.ts:36
|
|
134
|
+
const { format } = meta
|
|
135
|
+
// ...
|
|
136
|
+
return image.toFormat(format, config[format]).toBuffer();
|
|
137
|
+
```
|
|
138
|
+
**Risk:** If the image has an unsupported or malicious format (e.g., `svg`, `pdf`), `config[format]` is `undefined`, causing `toFormat` to fail silently or use unexpected defaults. This could be exploited to bypass image validation.
|
|
139
|
+
**Fix:** Validate format before using:
|
|
140
|
+
```typescript
|
|
141
|
+
const allowedFormats = ['jpeg', 'png', 'webp'] as const;
|
|
142
|
+
if (!allowedFormats.includes(format)) {
|
|
143
|
+
throw new Error(`Unsupported format: ${format}`);
|
|
144
|
+
}
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
#### ENH-1: Methods Throwing "Not Implemented" Without Documentation
|
|
148
|
+
**Severity:** MEDIUM | **Category:** API Design
|
|
149
|
+
**Locations:**
|
|
150
|
+
- `S3BaseStorage`: `getClientUploadCredential`, `resolveClientUploadCallback`, `preprocessImage`
|
|
151
|
+
- `LocalStorage`: `getObjectUrl`, `getSignedUrl`, `getClientUploadCredential`, `resolveClientUploadCallback`, `preprocessImage`
|
|
152
|
+
|
|
153
|
+
**Risk:** Consumers have no way to know which methods are supported by which providers without reading the source code or triggering runtime errors.
|
|
154
|
+
**Fix:**
|
|
155
|
+
1. Make these methods optional in `BaseStorage` interface
|
|
156
|
+
2. Add JSDoc `@throws {Error}` annotations
|
|
157
|
+
3. Create a provider capability matrix in README
|
|
158
|
+
|
|
159
|
+
#### SEC-3: OSS Callback Validation Timing Attack
|
|
160
|
+
**Severity:** MEDIUM | **Category:** Security
|
|
161
|
+
```typescript
|
|
162
|
+
// lib/providers/oss-storage.ts:291
|
|
163
|
+
private validateSignature(pubKey: string, signature: Buffer, toSignByte: string): boolean {
|
|
164
|
+
const verify = crypto.createVerify("RSA-MD5");
|
|
165
|
+
verify.update(toSignByte);
|
|
166
|
+
return verify.verify(pubKey, signature); // Direct comparison - timing attack possible
|
|
167
|
+
}
|
|
168
|
+
```
|
|
169
|
+
**Risk:** The signature verification uses direct comparison which could be vulnerable to timing attacks where an attacker measures response times to guess the correct signature.
|
|
170
|
+
**Fix:** While `crypto.verify` itself is constant-time at the cryptographic level, add an additional timing-safe comparison wrapper for the boolean result if security is critical.
|
|
171
|
+
|
|
172
|
+
#### BUG-3: Image Resize Logic Bug
|
|
173
|
+
**Severity:** MEDIUM | **Category:** Bug
|
|
174
|
+
```typescript
|
|
175
|
+
// lib/util/imageUtils.ts:37
|
|
176
|
+
if ((width && meta.width && meta.width > width) || (height && meta.height && meta.height > height)) {
|
|
177
|
+
image.resize(width, height, resizeOptions);
|
|
178
|
+
}
|
|
179
|
+
```
|
|
180
|
+
**Risk:** This condition is incorrect. If you pass `width: 100, height: null`, and the image is 200x50, it will resize because `meta.width > width` is true, but it will call `resize(100, null)` which may not behave as expected (sharp could throw or use default aspect ratio).
|
|
181
|
+
**Fix:** Separate width and height logic or validate both are set before checking.
|
|
182
|
+
|
|
183
|
+
---
|
|
184
|
+
|
|
185
|
+
### 🟢 LOW
|
|
186
|
+
|
|
187
|
+
#### STYLE-1: Inconsistent Error Handling
|
|
188
|
+
**Severity:** LOW | **Category:** Code Quality
|
|
189
|
+
Some providers use `.catch(reject)` chains, others use `if (err) reject(err)` in callbacks. This makes the codebase harder to maintain.
|
|
190
|
+
|
|
191
|
+
#### STYLE-2: Commented-Out Test Code
|
|
192
|
+
**Severity:** LOW | **Category:** Testing
|
|
193
|
+
```typescript
|
|
194
|
+
// test/util/imageUtils.spec.ts
|
|
195
|
+
it('test compressImageBuffer', async () => {
|
|
196
|
+
console.log('Skip Test, apline image not support');
|
|
197
|
+
})
|
|
198
|
+
// All real tests are commented out
|
|
199
|
+
```
|
|
200
|
+
**Risk:** Zero confidence that image compression actually works. Tests exist but are disabled.
|
|
201
|
+
**Fix:** Either fix the Alpine compatibility issue or use a different base image for tests.
|
|
202
|
+
|
|
203
|
+
#### ENH-2: No TypeScript Strict Mode
|
|
204
|
+
**Severity:** LOW | **Category:** Type Safety
|
|
205
|
+
The `tsconfig.json` likely doesn't enable `strict: true`, allowing many type issues to slip through.
|
|
206
|
+
|
|
207
|
+
#### ENH-3: Missing JSDoc on Public APIs
|
|
208
|
+
**Severity:** LOW | **Category:** Documentation
|
|
209
|
+
Public methods in `BaseStorage`, `StorageService`, and utility functions lack JSDoc comments explaining parameters, return values, and error conditions.
|
|
210
|
+
|
|
211
|
+
#### ENH-4: No Stream Backpressure Handling
|
|
212
|
+
**Severity:** LOW | **Category:** Performance
|
|
213
|
+
When streaming files, there's no consideration of backpressure. If the consumer is slow, the stream could buffer indefinitely in memory.
|
|
214
|
+
|
|
215
|
+
#### BUG-4: GDrive refreshToken Stored in Constructor
|
|
216
|
+
**Severity:** MEDIUM | **Category:** Security
|
|
217
|
+
```typescript
|
|
218
|
+
// lib/providers/gdrive-storage.ts:14
|
|
219
|
+
auth.setCredentials({
|
|
220
|
+
refresh_token: options.options.refreshToken,
|
|
221
|
+
});
|
|
222
|
+
```
|
|
223
|
+
**Risk:** The refresh token is passed via constructor options which may be logged or exposed in error messages. OAuth refresh tokens are sensitive credentials.
|
|
224
|
+
**Fix:** Document that this should be stored in secure environment variables and not logged.
|
|
225
|
+
|
|
226
|
+
---
|
|
227
|
+
|
|
228
|
+
## Grading Rubric
|
|
229
|
+
|
|
230
|
+
| Dimension | Score | Rationale |
|
|
231
|
+
|:---|:---|:---|
|
|
232
|
+
| **Security** | 10/20 | Path traversal vulnerability, credential exposure risk, unused sensitive import |
|
|
233
|
+
| **Reliability** | 11/20 | Wrong return types, no error handlers on streams, incomplete method implementations |
|
|
234
|
+
| **API Design** | 14/20 | Good abstraction across providers, but methods throw "not implemented" without doc |
|
|
235
|
+
| **Code Quality** | 12/20 | Anti-patterns (promise wrappers), excessive `any`, commented-out tests |
|
|
236
|
+
| **Best Practices** | 18/20 | Uses `loadPackage` correctly for optional deps, proper peer dependencies config |
|
|
237
|
+
|
|
238
|
+
**Total Score: 65/100 (C)**
|
|
239
|
+
|
|
240
|
+
---
|
|
241
|
+
|
|
242
|
+
## Priority Fix Order
|
|
243
|
+
|
|
244
|
+
| Priority | ID | Effort | Description |
|
|
245
|
+
|:---|:---|:---|:---|
|
|
246
|
+
| P0 | SEC-1 | M | Add path traversal protection to LocalStorage |
|
|
247
|
+
| P0 | SEC-2 | S | Remove unused AWS import from storage.ts |
|
|
248
|
+
| P0 | BUG-1 | M | Fix S3 readFile return type (Buffer vs Stream) |
|
|
249
|
+
| P0 | MEM-1 | S | Add error listeners to file streams |
|
|
250
|
+
| P1 | PERF-1 | L | Replace callback-style fs with fs.promises across LocalStorage |
|
|
251
|
+
| P1 | TYPE-1 | M | Define interfaces for storage provider SDKs |
|
|
252
|
+
| P1 | BUG-2 | S | Validate image format before compression |
|
|
253
|
+
| P1 | ENH-1 | M | Document unsupported methods per provider |
|
|
254
|
+
| P2 | BUG-3 | S | Fix image resize condition logic |
|
|
255
|
+
| P2 | BUG-4 | S | Document refresh token security |
|
|
256
|
+
| P2 | STYLE-2 | M | Fix or remove commented test code |
|
|
257
|
+
| P3 | ENH-2 | S | Enable TypeScript strict mode |
|
|
258
|
+
| P3 | ENH-3 | L | Add JSDoc to all public APIs |
|
|
259
|
+
|
|
260
|
+
---
|
|
261
|
+
|
|
262
|
+
## Recommendations
|
|
263
|
+
|
|
264
|
+
1. **Immediate (P0):** Fix SEC-1 and SEC-2 before production use. The path traversal is a **critical CVE-level vulnerability**.
|
|
265
|
+
2. **Before 3.0.0:** Fix all P0 and P1 items. The stream/buffer type mismatch (BUG-1) will cause runtime crashes.
|
|
266
|
+
3. **Test Coverage:** Currently < 10% functional coverage. Target 70%+ for 3.0.0.
|
|
267
|
+
4. **Consider:** Breaking the `BaseStorage` abstract class into multiple optional interfaces (e.g., `SupportsClientUpload`, `SupportsImageProcessing`) to avoid "not implemented" throws.
|
|
268
|
+
5. **Security Audit:** Have a security team review the OAuth credential handling and OSS signature validation before production use.
|
|
269
|
+
|
|
270
|
+
---
|
|
271
|
+
|
|
272
|
+
## Test Status
|
|
273
|
+
|
|
274
|
+
Current: 4 test suites (imageUtils, module tests)
|
|
275
|
+
- `imageUtils.spec.ts`: 1 skipped test, 3 commented out
|
|
276
|
+
- `oss.spec.ts`: Not executed (requires live OSS credentials)
|
|
277
|
+
- Module tests: Basic DI registration only
|
|
278
|
+
|
|
279
|
+
**Blockers:**
|
|
280
|
+
- Alpine Linux image incompatibility with sharp
|
|
281
|
+
- No mock implementations for testing provider operations
|
|
282
|
+
- Missing integration test suite
|
|
283
|
+
|
|
284
|
+
**Recommendation:** Add unit tests with mocked SDK clients before fixing providers.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Plan: nestjs-storage B+ → A-
|
|
2
|
+
|
|
3
|
+
## Goal
|
|
4
|
+
Push grade from B+ (84) to A- (87+) by addressing remaining P2/P3 items.
|
|
5
|
+
|
|
6
|
+
## Phase 1: Documentation & Cleanup
|
|
7
|
+
|
|
8
|
+
### ENH-1: Provider Capability Matrix in README
|
|
9
|
+
Add a capability matrix table to `README.md` showing which provider supports which methods:
|
|
10
|
+
|
|
11
|
+
| Capability | Local | S3 | OSS | GDrive | Azure | GCS |
|
|
12
|
+
|---|---|---|---|---|---|---|
|
|
13
|
+
| readFile | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
|
14
|
+
| writeFile | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
|
15
|
+
| deleteFile | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
|
16
|
+
| getSignedUrl | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ |
|
|
17
|
+
| clientUpload | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
|
|
18
|
+
| preprocessImage | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
|
|
19
|
+
|
|
20
|
+
Also add `@throws` JSDoc annotations on methods that throw "Not Implemented".
|
|
21
|
+
|
|
22
|
+
### STYLE-2: Clean Commented Test Code
|
|
23
|
+
In `test/imageUtils.spec.ts`, remove or uncomment any commented-out test blocks.
|
|
24
|
+
|
|
25
|
+
### ENH-3: JSDoc on Public APIs
|
|
26
|
+
Add JSDoc to:
|
|
27
|
+
- `BaseStorage` public/protected methods
|
|
28
|
+
- Capability interfaces (`ISignedUrlCapable`, `IClientUploadCapable`, etc.)
|
|
29
|
+
- `StorageModule.forRoot()` / `forRootAsync()`
|
|
30
|
+
|
|
31
|
+
## Test Command
|
|
32
|
+
```bash
|
|
33
|
+
npx jest --config packages/nestjs-storage/test/jest-test.json --no-coverage --forceExit
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Commit
|
|
37
|
+
```
|
|
38
|
+
docs(nestjs-storage): add provider capability matrix, JSDoc, and test cleanup
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Do NOT push to remote.
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# Post-Fix Review #2: @nathapp/nestjs-storage
|
|
2
|
+
|
|
3
|
+
**Date:** 2026-02-16
|
|
4
|
+
**Reviewer:** Subrina (AI)
|
|
5
|
+
**Version:** 2.1.5
|
|
6
|
+
**Previous Reviews:** 20260215-review-storage.md (C, 65/100), 20260215-review-storage-postfix.md (B, 78/100)
|
|
7
|
+
**Tests:** 7 suites, 18 tests passing
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Overall Grade: B+ (84/100)
|
|
12
|
+
|
|
13
|
+
**Previous:** B (78/100)
|
|
14
|
+
**Change:** +6 points
|
|
15
|
+
|
|
16
|
+
All P0 and most P1 items now resolved. The package has proper path traversal protection, typed storage SDK interfaces, validated image processing, and two new cloud providers (Azure Blob, GCS). Remaining items are P2/P3 (documentation, commented tests, OSS timing attack).
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## P1 Items: Status
|
|
21
|
+
|
|
22
|
+
### ✅ TYPE-1: Excessive `any` Types — FIXED
|
|
23
|
+
**Fix Applied:** Created `lib/types/clients.ts` with typed interfaces:
|
|
24
|
+
- `IS3Client` — replaces `any` in S3BaseStorage
|
|
25
|
+
- `IOssClient` — replaces `any` in OssStorage
|
|
26
|
+
- `IGDriveClient` — replaces `any` in GDriveStorage
|
|
27
|
+
|
|
28
|
+
All three providers now use typed `private readonly storage: I*Client` instead of `any`.
|
|
29
|
+
|
|
30
|
+
**Remaining:** One `any` in `getClientUploadCredential` return type (OSS-specific, acceptable).
|
|
31
|
+
|
|
32
|
+
**Status:** ✅ RESOLVED
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
### ✅ BUG-2: compressImageBuffer Unsafe Format — FIXED
|
|
37
|
+
**Fix Applied:**
|
|
38
|
+
```typescript
|
|
39
|
+
const allowedFormats = ['jpeg', 'png', 'webp'];
|
|
40
|
+
if (!format || !allowedFormats.includes(format)) {
|
|
41
|
+
throw new Error(`Unsupported image format: ${format}. Allowed formats: ${allowedFormats.join(', ')}`);
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
Prevents undefined `config[format]` and blocks unsupported formats (svg, pdf, heic).
|
|
45
|
+
|
|
46
|
+
**Status:** ✅ RESOLVED
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
### ✅ BUG-3: Image Resize Logic — FIXED
|
|
51
|
+
**Fix Applied:**
|
|
52
|
+
```typescript
|
|
53
|
+
const shouldResizeWidth = width && meta.width && meta.width > width;
|
|
54
|
+
const shouldResizeHeight = height && meta.height && meta.height > height;
|
|
55
|
+
if (shouldResizeWidth || shouldResizeHeight) {
|
|
56
|
+
image.resize(width || undefined, height || undefined, resizeOptions);
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
Properly handles width-only and height-only cases by converting `null` to `undefined` for sharp compatibility.
|
|
60
|
+
|
|
61
|
+
**Status:** ✅ RESOLVED
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
### ❌ ENH-1: Unsupported Methods Documentation — NOT FIXED
|
|
66
|
+
Methods throwing "Not Implemented" still lack JSDoc `@throws` annotations or README capability matrix per provider.
|
|
67
|
+
|
|
68
|
+
**Status:** NOT ADDRESSED (P2, documentation only)
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Updated Grading Rubric
|
|
73
|
+
|
|
74
|
+
| Dimension | Before | After | Change | Rationale |
|
|
75
|
+
|:---|:---|:---|:---|:---|
|
|
76
|
+
| **Security** | 17/20 | 17/20 | 0 | No security changes this round |
|
|
77
|
+
| **Reliability** | 17/20 | 19/20 | +2 | Image format validation, resize logic fixed |
|
|
78
|
+
| **API Design** | 14/20 | 15/20 | +1 | Typed SDK interfaces improve API contracts |
|
|
79
|
+
| **Code Quality** | 12/20 | 15/20 | +3 | Major `any` elimination, 269-line types file |
|
|
80
|
+
| **Best Practices** | 18/20 | 18/20 | 0 | No change |
|
|
81
|
+
|
|
82
|
+
**Total Score: 84/100 (B+)**
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## Remaining Items (P2/P3)
|
|
87
|
+
|
|
88
|
+
| Priority | ID | Status | Description |
|
|
89
|
+
|:---|:---|:---|:---|
|
|
90
|
+
| P2 | ENH-1 | ❌ | Document unsupported methods per provider |
|
|
91
|
+
| P2 | SEC-3 | ❌ | OSS signature timing attack (low risk) |
|
|
92
|
+
| P2 | BUG-4 | ❌ | GDrive refreshToken security docs |
|
|
93
|
+
| P2 | STYLE-2 | ❌ | Commented test code in imageUtils.spec.ts |
|
|
94
|
+
| P3 | ENH-3 | ❌ | Missing JSDoc on public APIs |
|
|
95
|
+
|
|
96
|
+
None of these are blocking for 3.0.0 release.
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## Summary
|
|
101
|
+
|
|
102
|
+
**9/13 original findings resolved.** Package upgraded from C (65) → B+ (84) across two fix rounds. All critical security, reliability, and type safety issues addressed. New Azure Blob and GCS providers added. Remaining items are documentation and low-risk concerns suitable for post-release polish.
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
# Google Drive Security Best Practices
|
|
2
|
+
|
|
3
|
+
This document outlines security best practices for using the Google Drive storage provider in the @nathapp/nestjs-storage package.
|
|
4
|
+
|
|
5
|
+
## OAuth 2.0 Refresh Token Security
|
|
6
|
+
|
|
7
|
+
The GDrive storage provider uses OAuth 2.0 refresh tokens for authentication. Refresh tokens are long-lived credentials that allow the application to obtain new access tokens without user interaction.
|
|
8
|
+
|
|
9
|
+
### Security Implications
|
|
10
|
+
|
|
11
|
+
**Critical Security Risks:**
|
|
12
|
+
1. **Long-lived credentials** - Refresh tokens can be valid indefinitely until revoked
|
|
13
|
+
2. **Full account access** - Compromised refresh tokens grant the same permissions as the original OAuth grant
|
|
14
|
+
3. **No automatic expiration** - Unlike access tokens (which expire in ~1 hour), refresh tokens persist
|
|
15
|
+
4. **Credential theft** - If stored insecurely, refresh tokens are high-value targets for attackers
|
|
16
|
+
|
|
17
|
+
### Storage Best Practices
|
|
18
|
+
|
|
19
|
+
#### 1. Encryption at Rest (REQUIRED)
|
|
20
|
+
|
|
21
|
+
**NEVER store refresh tokens in plain text.** Always encrypt refresh tokens before storage:
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
// BAD - Plain text storage
|
|
25
|
+
const config = {
|
|
26
|
+
provider: Provider.GDRIVE,
|
|
27
|
+
options: {
|
|
28
|
+
clientId: process.env.GDRIVE_CLIENT_ID,
|
|
29
|
+
clientSecret: process.env.GDRIVE_CLIENT_SECRET,
|
|
30
|
+
refreshToken: 'ya29.a0AfH6SMBx...', // NEVER DO THIS
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
// GOOD - Encrypted storage
|
|
35
|
+
import { encrypt, decrypt } from './crypto-utils';
|
|
36
|
+
|
|
37
|
+
const encryptedToken = encrypt(refreshToken, encryptionKey);
|
|
38
|
+
// Store encryptedToken in database/config
|
|
39
|
+
|
|
40
|
+
// When initializing storage
|
|
41
|
+
const config = {
|
|
42
|
+
provider: Provider.GDRIVE,
|
|
43
|
+
options: {
|
|
44
|
+
clientId: process.env.GDRIVE_CLIENT_ID,
|
|
45
|
+
clientSecret: process.env.GDRIVE_CLIENT_SECRET,
|
|
46
|
+
refreshToken: decrypt(encryptedToken, encryptionKey),
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
**Encryption recommendations:**
|
|
52
|
+
- Use AES-256-GCM or ChaCha20-Poly1305
|
|
53
|
+
- Store encryption keys in a secrets manager (AWS Secrets Manager, HashiCorp Vault, etc.)
|
|
54
|
+
- NEVER hardcode encryption keys in source code
|
|
55
|
+
- Rotate encryption keys periodically
|
|
56
|
+
|
|
57
|
+
#### 2. Secrets Management
|
|
58
|
+
|
|
59
|
+
Use a dedicated secrets manager for storing encrypted refresh tokens:
|
|
60
|
+
|
|
61
|
+
**AWS Secrets Manager:**
|
|
62
|
+
```typescript
|
|
63
|
+
import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';
|
|
64
|
+
|
|
65
|
+
async function getGDriveRefreshToken(): Promise<string> {
|
|
66
|
+
const client = new SecretsManagerClient({ region: 'us-east-1' });
|
|
67
|
+
const response = await client.send(
|
|
68
|
+
new GetSecretValueCommand({ SecretId: 'gdrive/refresh-token' })
|
|
69
|
+
);
|
|
70
|
+
return JSON.parse(response.SecretString!).refreshToken;
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
**HashiCorp Vault:**
|
|
75
|
+
```typescript
|
|
76
|
+
import vault from 'node-vault';
|
|
77
|
+
|
|
78
|
+
async function getGDriveRefreshToken(): Promise<string> {
|
|
79
|
+
const client = vault({
|
|
80
|
+
endpoint: process.env.VAULT_ADDR,
|
|
81
|
+
token: process.env.VAULT_TOKEN,
|
|
82
|
+
});
|
|
83
|
+
const { data } = await client.read('secret/data/gdrive');
|
|
84
|
+
return data.data.refreshToken;
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
#### 3. Environment-Specific Configuration
|
|
89
|
+
|
|
90
|
+
**NEVER commit refresh tokens to version control:**
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
# .env (NEVER commit this file)
|
|
94
|
+
GDRIVE_CLIENT_ID=your-client-id.apps.googleusercontent.com
|
|
95
|
+
GDRIVE_CLIENT_SECRET=your-client-secret
|
|
96
|
+
GDRIVE_REFRESH_TOKEN_ENCRYPTED=encrypted-value-here
|
|
97
|
+
|
|
98
|
+
# .gitignore (ALWAYS commit this file)
|
|
99
|
+
.env
|
|
100
|
+
.env.local
|
|
101
|
+
.env.*.local
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
#### 4. Access Control
|
|
105
|
+
|
|
106
|
+
Limit access to refresh tokens:
|
|
107
|
+
- Use IAM roles/policies to restrict who can read secrets
|
|
108
|
+
- Enable audit logging for secret access
|
|
109
|
+
- Implement least-privilege access (only services that need GDrive access should have the token)
|
|
110
|
+
- Use separate refresh tokens for dev/staging/production environments
|
|
111
|
+
|
|
112
|
+
### OAuth Scope Minimization
|
|
113
|
+
|
|
114
|
+
Request only the minimum required scopes when obtaining refresh tokens:
|
|
115
|
+
|
|
116
|
+
**Minimal scopes for file operations:**
|
|
117
|
+
```
|
|
118
|
+
https://www.googleapis.com/auth/drive.file
|
|
119
|
+
```
|
|
120
|
+
This scope limits access to only files created by the application.
|
|
121
|
+
|
|
122
|
+
**Avoid broad scopes unless necessary:**
|
|
123
|
+
```
|
|
124
|
+
https://www.googleapis.com/auth/drive # Full drive access - use only if required
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
**Recommended scopes by use case:**
|
|
128
|
+
- File upload/download only: `drive.file`
|
|
129
|
+
- Read-only access: `drive.readonly`
|
|
130
|
+
- Metadata only: `drive.metadata.readonly`
|
|
131
|
+
- Full drive access: `drive` (use sparingly)
|
|
132
|
+
|
|
133
|
+
### Token Rotation
|
|
134
|
+
|
|
135
|
+
Implement refresh token rotation to limit the blast radius of compromised tokens:
|
|
136
|
+
|
|
137
|
+
1. **Periodic rotation** - Rotate refresh tokens every 90 days
|
|
138
|
+
2. **Proactive revocation** - Revoke tokens when:
|
|
139
|
+
- Employees leave the organization
|
|
140
|
+
- Service is decommissioned
|
|
141
|
+
- Security incident is detected
|
|
142
|
+
3. **Automated rotation** - Use Google's token rotation API:
|
|
143
|
+
|
|
144
|
+
```typescript
|
|
145
|
+
import { OAuth2Client } from 'google-auth-library';
|
|
146
|
+
|
|
147
|
+
async function rotateRefreshToken(currentRefreshToken: string): Promise<string> {
|
|
148
|
+
const oauth2Client = new OAuth2Client(
|
|
149
|
+
process.env.GDRIVE_CLIENT_ID,
|
|
150
|
+
process.env.GDRIVE_CLIENT_SECRET
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
oauth2Client.setCredentials({
|
|
154
|
+
refresh_token: currentRefreshToken,
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
// Getting a new access token triggers rotation if enabled in GCP Console
|
|
158
|
+
const { credentials } = await oauth2Client.refreshAccessToken();
|
|
159
|
+
|
|
160
|
+
if (credentials.refresh_token) {
|
|
161
|
+
// New refresh token issued - update storage
|
|
162
|
+
await updateStoredRefreshToken(credentials.refresh_token);
|
|
163
|
+
return credentials.refresh_token;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return currentRefreshToken;
|
|
167
|
+
}
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### Monitoring and Alerting
|
|
171
|
+
|
|
172
|
+
Implement monitoring for refresh token usage:
|
|
173
|
+
|
|
174
|
+
1. **Audit logging** - Log all OAuth token usage
|
|
175
|
+
2. **Anomaly detection** - Alert on:
|
|
176
|
+
- Token usage from unexpected IP addresses
|
|
177
|
+
- Unusual access patterns (time of day, volume)
|
|
178
|
+
- Multiple failed authentication attempts
|
|
179
|
+
3. **Compliance tracking** - Track token age and rotation status
|
|
180
|
+
|
|
181
|
+
### Token Revocation
|
|
182
|
+
|
|
183
|
+
Revoke refresh tokens immediately when:
|
|
184
|
+
- Security incident is detected
|
|
185
|
+
- Token is no longer needed
|
|
186
|
+
- Employee with token access leaves
|
|
187
|
+
- Compliance requirement mandates it
|
|
188
|
+
|
|
189
|
+
**Revocation example:**
|
|
190
|
+
```typescript
|
|
191
|
+
import { OAuth2Client } from 'google-auth-library';
|
|
192
|
+
|
|
193
|
+
async function revokeRefreshToken(refreshToken: string): Promise<void> {
|
|
194
|
+
const oauth2Client = new OAuth2Client();
|
|
195
|
+
await oauth2Client.revokeToken(refreshToken);
|
|
196
|
+
|
|
197
|
+
// Remove from storage
|
|
198
|
+
await deleteStoredRefreshToken();
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
## Production Checklist
|
|
203
|
+
|
|
204
|
+
Before deploying to production:
|
|
205
|
+
|
|
206
|
+
- [ ] Refresh tokens are encrypted at rest
|
|
207
|
+
- [ ] Encryption keys are stored in a secrets manager (not in code)
|
|
208
|
+
- [ ] OAuth scopes are minimized to required permissions only
|
|
209
|
+
- [ ] Refresh token rotation is enabled and automated
|
|
210
|
+
- [ ] Access to refresh tokens is restricted via IAM policies
|
|
211
|
+
- [ ] Audit logging is enabled for all token access
|
|
212
|
+
- [ ] Monitoring and alerting is configured for anomalous usage
|
|
213
|
+
- [ ] Token revocation procedure is documented and tested
|
|
214
|
+
- [ ] Separate refresh tokens are used for dev/staging/production
|
|
215
|
+
- [ ] `.env` files are in `.gitignore` and never committed
|
|
216
|
+
|
|
217
|
+
## References
|
|
218
|
+
|
|
219
|
+
- [Google OAuth 2.0 Best Practices](https://developers.google.com/identity/protocols/oauth2/production-readiness)
|
|
220
|
+
- [OWASP OAuth 2.0 Security Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/OAuth2_Cheat_Sheet.html)
|
|
221
|
+
- [Google Drive API Scopes](https://developers.google.com/drive/api/guides/api-specific-auth)
|
|
222
|
+
- [Google Cloud Security Best Practices](https://cloud.google.com/security/best-practices)
|