feat(storage): storage key validation, driver contract suite, LocalDriver

This commit is contained in:
jubnl
2026-08-15 23:54:43 +02:00
parent b1e4c830b2
commit 19f18a2b3a
7 changed files with 721 additions and 0 deletions
@@ -0,0 +1,198 @@
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { pipeline } from 'node:stream/promises';
import type { Readable } from 'node:stream';
import { assertValidKey, assertValidPrefix } from '../storage-keys';
import {
isLocalTempFile,
StorageBackendError,
StorageInvalidKeyError,
StorageNotFoundError,
type ByteRange,
type LocalTempFile,
type ObjectStat,
type StorageDriver,
} from '../storage.types';
const SPOOL_DIR_NAME = '.tmp';
function errnoCode(err: unknown): string | undefined {
return (err as NodeJS.ErrnoException).code;
}
/** ENOENT on the path or any parent segment being a file — both are a miss. */
function isMissing(err: unknown): boolean {
const code = errnoCode(err);
return code === 'ENOENT' || code === 'ENOTDIR';
}
/**
* The only real driver type in v1: plain files under a root directory.
*
* `put` is atomic — stream sources spool into the hidden `<root>/.tmp` and
* commit with a single same-volume `rename()`; caller-owned temp files rename
* directly with an EXDEV copy-fallback for the cross-volume edge case. The
* root is realpath'd at `init()` because in Docker both storage anchors are
* symlinks (Dockerfile: `/app/server/uploads → /app/uploads`,
* `/app/server/data → /app/data`) and a naive `startsWith` containment check
* misbehaves on symlinked roots — the trap backup.impl.ts:423 and
* nest/plugins/paths.ts already work around with `realpathSync`.
*/
export class LocalDriver implements StorageDriver {
readonly id: string;
private readonly configuredRoot: string;
private realRoot: string | null = null;
constructor(opts: { id: string; root: string }) {
this.id = opts.id;
this.configuredRoot = opts.root;
}
/**
* Ensure root + spool + category prefix dirs exist and resolve the real
* root. Runs on every registry load (boot and reload()) so a newly
* configured backend is usable immediately; `cleanSpool` is passed at boot
* only — on a reload it could delete an in-flight upload's spool file.
*/
init(opts: { ensurePrefixes?: string[]; cleanSpool?: boolean } = {}): void {
fs.mkdirSync(this.configuredRoot, { recursive: true });
this.realRoot = fs.realpathSync(this.configuredRoot);
fs.mkdirSync(this.spoolDir(), { recursive: true });
for (const prefix of opts.ensurePrefixes ?? []) {
assertValidPrefix(prefix);
if (prefix) fs.mkdirSync(path.join(this.realRoot, prefix), { recursive: true });
}
if (opts.cleanSpool) {
for (const entry of fs.readdirSync(this.spoolDir())) {
fs.rmSync(path.join(this.spoolDir(), entry), { recursive: true, force: true });
}
}
}
private root(): string {
if (!this.realRoot) {
throw new StorageBackendError(`LocalDriver '${this.id}' used before init()`);
}
return this.realRoot;
}
private spoolDir(): string {
return path.join(this.root(), SPOOL_DIR_NAME);
}
getSpoolDir(): string {
return this.spoolDir();
}
/**
* Central key validation plus defense-in-depth containment: even a key that
* somehow passed validation must resolve inside the real root.
*/
private resolvePath(key: string): string {
assertValidKey(key);
const resolved = path.resolve(this.root(), key);
if (!resolved.startsWith(this.root() + path.sep)) {
throw new StorageInvalidKeyError(key);
}
return resolved;
}
getLocalPath(key: string): string {
return this.resolvePath(key);
}
async put(key: string, source: Readable | LocalTempFile): Promise<void> {
const dest = this.resolvePath(key);
await fs.promises.mkdir(path.dirname(dest), { recursive: true });
if (isLocalTempFile(source)) {
try {
await fs.promises.rename(source.tmpPath, dest);
} catch (err) {
if (errnoCode(err) !== 'EXDEV') {
throw new StorageBackendError(`put failed for '${key}' on '${this.id}'`, err);
}
await fs.promises.copyFile(source.tmpPath, dest);
await fs.promises.unlink(source.tmpPath);
}
return;
}
const spool = path.join(this.spoolDir(), randomUUID());
try {
await pipeline(source, fs.createWriteStream(spool));
await fs.promises.rename(spool, dest);
} catch (err) {
await fs.promises.rm(spool, { force: true });
throw err instanceof Error && !errnoCode(err)
? err // source-stream failure: surface the caller's own error untouched
: new StorageBackendError(`put failed for '${key}' on '${this.id}'`, err);
}
}
async getStream(key: string, range?: ByteRange): Promise<{ stream: Readable; stat: ObjectStat }> {
const resolved = this.resolvePath(key);
const stat = await this.stat(key);
if (!stat) throw new StorageNotFoundError(key);
const stream = fs.createReadStream(
resolved,
range ? { start: range.start, end: range.end } : undefined,
);
return { stream, stat };
}
async stat(key: string): Promise<ObjectStat | null> {
const resolved = this.resolvePath(key);
try {
const st = await fs.promises.stat(resolved);
if (!st.isFile()) return null;
return { key, size: st.size, mtimeMs: st.mtimeMs };
} catch (err) {
if (isMissing(err)) return null;
throw new StorageBackendError(`stat failed for '${key}' on '${this.id}'`, err);
}
}
async delete(key: string): Promise<void> {
const resolved = this.resolvePath(key);
try {
await fs.promises.unlink(resolved);
} catch (err) {
if (isMissing(err)) return; // idempotent
throw new StorageBackendError(`delete failed for '${key}' on '${this.id}'`, err);
}
}
async *list(prefix: string): AsyncIterable<ObjectStat> {
assertValidPrefix(prefix);
const root = this.root();
yield* this.walk(prefix ? path.resolve(root, prefix) : root, root);
}
private async *walk(dir: string, root: string): AsyncIterable<ObjectStat> {
let entries: fs.Dirent[];
try {
entries = await fs.promises.readdir(dir, { withFileTypes: true });
} catch (err) {
if (isMissing(err)) return; // unpopulated prefix — empty, not an error
throw new StorageBackendError(`list failed under '${dir}' on '${this.id}'`, err);
}
for (const entry of entries) {
// Skips the .tmp spool (and any dotfile) defensively — key validation
// already makes dot segments unreachable, but list walks the real disk.
if (entry.name.startsWith('.')) continue;
const entryPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
yield* this.walk(entryPath, root);
} else if (entry.isFile()) {
const st = await fs.promises.stat(entryPath);
yield {
key: path.relative(root, entryPath).split(path.sep).join('/'),
size: st.size,
mtimeMs: st.mtimeMs,
};
}
}
}
}
+48
View File
@@ -0,0 +1,48 @@
import { StorageInvalidKeyError } from './storage.types';
/**
* Central key validation — the ONE place storage keys are checked, replacing
* the scattered per-route guards (`path.basename` + `startsWith` shapes in
* files.service.ts / platform.routes.ts / journey-public.controller.ts) as
* call sites migrate. Drivers still confine resolved paths to their root as
* defense in depth, but no driver or route re-implements these rules.
*
* Rejected: `..` segments, absolute paths, backslashes, empty segments,
* leading-dot segments (matches `express.static`'s default
* `dotfiles: 'ignore'` and keeps the `.tmp` spool unreachable), and control
* characters. Spaces are valid — legacy `photos/<filename>` keys are
* user-named flat files.
*/
const MAX_KEY_LENGTH = 1024;
function hasControlChars(value: string): boolean {
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
if (code < 0x20 || code === 0x7f) return true;
}
return false;
}
export function isValidKey(key: string): boolean {
if (!key || key.length > MAX_KEY_LENGTH) return false;
if (key.includes('\\') || hasControlChars(key)) return false;
for (const segment of key.split('/')) {
if (segment === '' || segment.startsWith('.')) return false;
}
return true;
}
export function assertValidKey(key: string): void {
if (!isValidKey(key)) throw new StorageInvalidKeyError(key);
}
/** Prefixes additionally allow `''` (list everything) and a trailing `/`. */
export function isValidPrefix(prefix: string): boolean {
if (prefix === '') return true;
return isValidKey(prefix.endsWith('/') ? prefix.slice(0, -1) : prefix);
}
export function assertValidPrefix(prefix: string): void {
if (!isValidPrefix(prefix)) throw new StorageInvalidKeyError(prefix);
}
+20
View File
@@ -0,0 +1,20 @@
import path from 'node:path';
/**
* The storage domain's one `__dirname` anchor (the uploads-root.ts idiom, and
* eventually its replacement: the registry's defaults make this the single
* source of truth the other 16 copies collapse onto in later slices).
*
* `__dirname` moves with the file — `server/{src,dist}/nest/storage` sits
* three levels under `server/`, so three `..` hops resolve to `<server>/`
* under both the src (vitest) and dist (runtime) layouts. The depth is stated
* rather than counted by hand and pinned by storage-keys.test.ts, exactly
* like uploads-root.test.ts pins UPLOADS_ROOT. In Docker both anchors are
* symlinks (`/app/server/uploads → /app/uploads`, `/app/server/data →
* /app/data`), which is why LocalDriver realpaths its root at init.
*/
export const DEFAULT_UPLOADS_ROOT = path.resolve(__dirname, '..', '..', '..', 'uploads');
export const DATA_ROOT = path.resolve(__dirname, '..', '..', '..', 'data');
export const DEFAULT_BACKUPS_ROOT = path.join(DATA_ROOT, 'backups');
/** Driver-agnostic global scratch space (`data/tmp`) — see StorageService.tempDir(). */
export const GLOBAL_TEMP_DIR = path.join(DATA_ROOT, 'tmp');
+100
View File
@@ -0,0 +1,100 @@
import type { Readable } from 'node:stream';
/**
* The storage abstraction's contract surface (spec:
* docs/superpowers/specs/2026-07-20-storage-backend-abstraction-design.md).
*
* S3 constraints are baked into the driver contract, not the implementation:
* keys are opaque POSIX-style strings, no rename/append/partial writes, no
* directory semantics. Adding a backend later means one driver file that
* passes the contract suite (tests/unit/nest/storage/storage-driver.contract.ts)
* — zero changes to controllers or services.
*/
export const STORAGE_CATEGORIES = [
'files',
'journey',
'covers',
'avatars',
'places',
'photos',
'photos-google',
'photos-trek',
'backups',
] as const;
export type StorageCategory = (typeof STORAGE_CATEGORIES)[number];
export interface ObjectStat {
key: string;
size: number;
mtimeMs: number;
}
/** Inclusive byte range, `fs.createReadStream` semantics; `end` omitted = to EOF. */
export interface ByteRange {
start: number;
end?: number;
}
/** Ignored by local drivers; a future S3 driver needs it for the PUT. */
export interface PutOptions {
contentType?: string;
}
/**
* A temp file whose OWNERSHIP transfers to `put()`: the driver moves or
* consumes it (rename into place locally; upload-then-delete remotely).
* Callers must not touch the path afterwards.
*/
export interface LocalTempFile {
tmpPath: string;
}
export function isLocalTempFile(source: Readable | LocalTempFile): source is LocalTempFile {
return typeof (source as LocalTempFile).tmpPath === 'string';
}
export interface StorageDriver {
/** Backend instance name, e.g. 'uploads-local'. */
readonly id: string;
/** Atomic: spool + single rename locally; single/multipart PUT remotely. */
put(key: string, source: Readable | LocalTempFile, opts?: PutOptions): Promise<void>;
getStream(key: string, range?: ByteRange): Promise<{ stream: Readable; stat: ObjectStat }>;
stat(key: string): Promise<ObjectStat | null>;
/** Idempotent; resolving on a missing key is success. */
delete(key: string): Promise<void>;
list(prefix: string): AsyncIterable<ObjectStat>;
/** Fast-path for local drivers; `null`/absent is exactly the remote-driver branch every caller must handle. */
getLocalPath?(key: string): string | null;
/** Same-filesystem spool dir (LocalDriver: `<root>/.tmp`), or null for drivers with no local filesystem. */
getSpoolDir?(): string | null;
}
/**
* Typed error set so route handlers map storage failures to their existing
* bespoke envelopes without string-matching driver internals.
*/
export class StorageBackendError extends Error {
constructor(
message: string,
readonly cause?: unknown,
) {
super(message);
this.name = 'StorageBackendError';
}
}
export class StorageNotFoundError extends Error {
constructor(readonly key: string) {
super(`storage object not found: ${key}`);
this.name = 'StorageNotFoundError';
}
}
/** Serving slices map this to a miss (404/next()), never a 500. */
export class StorageInvalidKeyError extends Error {
constructor(readonly key: string) {
super(`invalid storage key: ${key}`);
this.name = 'StorageInvalidKeyError';
}
}