// AtomicFile.readText over a real in-memory volume: the text keeps a leading // byte order mark, so a read, edit and AtomicFile.write round trip is // byte-identical, where core readFileString drops the mark. import { assert, describe, it } from "@effect/vitest"; import type { MemoryFileSystemFaultsFactory, MemoryFileSystemSeed } from "@effected/memfs"; import { MemoryFileSystem } from "@effected/memfs"; import type { PlatformError } from "effect"; import { Effect, Exit, FileSystem } from "effect"; import { AtomicFile } from "../src/index.js"; const TARGET = "/work/notes.md"; const BOM = [0xef, 0xbb, 0xbf]; const bytes = (...values: ReadonlyArray) => new Uint8Array(values); const utf8 = (text: string) => [...new TextEncoder().encode(text)]; /** Read `TARGET`, write the text straight back, and return the read and the bytes on disk after. */ const roundTrip = Effect.gen(function* () { const read = yield* AtomicFile.readText(TARGET); yield* AtomicFile.write(TARGET, read.text); const volume = yield* MemoryFileSystem.Volume; return { read, after: volume.bytes(TARGET) }; }); const seeded = (content: Uint8Array) => MemoryFileSystem.layerWithPath({ [TARGET]: content }); /** Runs `swap` against the unfaulted filesystem just before `read` is read: after the check or resolve before it. */ const swapBeforeRead = ( read: string, swap: (fs: FileSystem.FileSystem) => Effect.Effect, ): MemoryFileSystemFaultsFactory => (base) => ({ readFile: (path) => (path === read ? Effect.andThen(swap(base), base.readFile(path)) : undefined), }); describe("AtomicFile.readText", () => { it.effect("keeps a leading BOM in the text and a rewrite is byte-identical", () => { const original = bytes(...BOM, ...utf8("# Title\n")); return Effect.gen(function* () { const { read, after } = yield* roundTrip; assert.isTrue(read.bom); assert.strictEqual(read.text, "\uFEFF# Title\n"); assert.deepStrictEqual(after, original); }).pipe(Effect.provide(seeded(original))); }); it.effect("core readFileString drops the BOM the same volume holds", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; assert.strictEqual(yield* fs.readFileString(TARGET), "a"); assert.strictEqual((yield* AtomicFile.readText(TARGET)).text, "\uFEFFa"); }).pipe(Effect.provide(seeded(bytes(...BOM, 0x61)))), ); it.effect("an edit after the BOM keeps the BOM on write", () => Effect.gen(function* () { const read = yield* AtomicFile.readText(TARGET); yield* AtomicFile.write(TARGET, read.text.replace("old", "new")); const volume = yield* MemoryFileSystem.Volume; assert.deepStrictEqual(volume.bytes(TARGET), bytes(...BOM, ...utf8("new\n"))); }).pipe(Effect.provide(seeded(bytes(...BOM, ...utf8("old\n"))))), ); it.effect("a file without a BOM reads unchanged and round-trips byte-identical", () => { const original = bytes(...utf8("plain é text\r\n")); return Effect.gen(function* () { const { read, after } = yield* roundTrip; assert.isFalse(read.bom); assert.strictEqual(read.text, "plain é text\r\n"); assert.deepStrictEqual(after, original); }).pipe(Effect.provide(seeded(original))); }); it.effect("a file that is only a BOM reads as one U+FEFF and round-trips", () => { const original = bytes(...BOM); return Effect.gen(function* () { const { read, after } = yield* roundTrip; assert.isTrue(read.bom); assert.strictEqual(read.text, "\uFEFF"); assert.deepStrictEqual(after, original); }).pipe(Effect.provide(seeded(original))); }); it.effect("a U+FEFF after the first character is content, not a BOM", () => { const original = bytes(0x61, ...BOM, 0x62); return Effect.gen(function* () { const { read, after } = yield* roundTrip; assert.isFalse(read.bom); assert.strictEqual(read.text, "a\uFEFFb"); assert.deepStrictEqual(after, original); }).pipe(Effect.provide(seeded(original))); }); it.effect("two leading BOMs: the first is the mark, the second is content, both kept", () => { const original = bytes(...BOM, ...BOM, 0x61); return Effect.gen(function* () { const { read, after } = yield* roundTrip; assert.isTrue(read.bom); assert.strictEqual(read.text, "\uFEFF\uFEFFa"); assert.deepStrictEqual(after, original); }).pipe(Effect.provide(seeded(original))); }); it.effect("an empty file reads as empty text without a BOM", () => { const original = bytes(); return Effect.gen(function* () { const { read, after } = yield* roundTrip; assert.deepStrictEqual(read, { text: "", bom: false }); assert.deepStrictEqual(after, original); }).pipe(Effect.provide(seeded(original))); }); it.effect("a truncated BOM is invalid UTF-8 and fails InvalidData", () => Effect.gen(function* () { const error = yield* Effect.flip(AtomicFile.readText(TARGET)); assert.strictEqual(error.reason._tag, "InvalidData"); }).pipe(Effect.provide(seeded(bytes(0xef, 0xbb)))), ); it.effect("invalid UTF-8 fails InvalidData from AtomicFile and leaves the file untouched", () => { const original = bytes(0x61, 0xff, 0x62); return Effect.gen(function* () { const error = yield* Effect.flip(AtomicFile.readText(TARGET)); assert.strictEqual(error.reason._tag, "InvalidData"); assert.strictEqual(error.reason.module, "AtomicFile"); assert.strictEqual(error.reason.method, "readText"); assert.strictEqual(error.reason._tag === "InvalidData" ? error.reason.pathOrDescriptor : undefined, TARGET); const volume = yield* MemoryFileSystem.Volume; assert.deepStrictEqual(volume.bytes(TARGET), original); }).pipe(Effect.provide(seeded(original))); }); it.effect("a UTF-16 LE file with its BOM is not UTF-8 and fails InvalidData", () => Effect.gen(function* () { const error = yield* Effect.flip(AtomicFile.readText(TARGET)); assert.strictEqual(error.reason._tag, "InvalidData"); }).pipe(Effect.provide(seeded(bytes(0xff, 0xfe, 0x61, 0x00)))), ); it.effect("an absent target fails NotFound", () => Effect.gen(function* () { const error = yield* Effect.flip(AtomicFile.readText(TARGET)); assert.strictEqual(error.reason._tag, "NotFound"); }).pipe(Effect.provide(MemoryFileSystem.layerWithPath({ "/work": MemoryFileSystem.directory() }))), ); }); describe("AtomicFile.readText with confineTo", () => { const ROOT = "/root"; const NESTED = "/root/sub/config.json"; const ESCAPE = "/outside/secret.json"; const seed: MemoryFileSystemSeed = { [ESCAPE]: "secret", [ROOT]: MemoryFileSystem.directory(), "/rootling/secret.json": "sibling", [NESTED]: "inside", "/root/linked.json": MemoryFileSystem.symlink(ESCAPE), "/root/inner/real.json": "inner", "/root/alias": MemoryFileSystem.symlink("/root/inner"), "/root/escape": MemoryFileSystem.symlink("/outside"), "/root/moved/config.json": "moved", }; /** `/root/moved`'s realPath answers a directory outside the root, as a link swapped in above it would. */ const layer = MemoryFileSystem.layerWithPath(seed, { faults: () => ({ realPath: (path) => (path === "/root/moved" ? Effect.succeed("/outside") : undefined), }), }); const assertRefused = (error: PlatformError.PlatformError, description?: string) => { if (error.reason._tag === "BadArgument") return assert.fail("expected a SystemError"); assert.strictEqual(error.reason._tag, "PermissionDenied"); assert.strictEqual(error.reason.module, "AtomicFile"); assert.strictEqual(error.reason.method, "readText"); if (description !== undefined) assert.strictEqual(error.reason.description, description); }; // Every refusal checkConfined reports, run through the read: same rule, same description. for (const [label, target, reason] of [ ["a .. escape", "/root/../outside/secret.json", "outside"], ["an absolute path outside", ESCAPE, "outside"], ["a sibling sharing the root's prefix", "/rootling/secret.json", "outside"], ["the root itself", ROOT, "outside"], ["a link at the target", "/root/linked.json", "linked-target"], ["a link below the root that stays inside it", "/root/alias/real.json", "linked-directory"], ["a link below the root that leaves it", "/root/escape/secret.json", "linked-directory"], ["a directory resolving elsewhere", "/root/moved/config.json", "resolved-elsewhere"], ] as const) { it.effect(`${label}: the read refuses as checkConfined does`, () => Effect.gen(function* () { const verdict = yield* AtomicFile.checkConfined(target, { confineTo: ROOT }); if (verdict._tag !== "Refused") return assert.fail(`expected a refusal, got ${verdict._tag}`); assert.strictEqual(verdict.reason, reason); assertRefused(yield* Effect.flip(AtomicFile.readText(target, { confineTo: ROOT })), verdict.description); }).pipe(Effect.provide(layer)), ); } it.effect("reads a file inside the root, a BOM kept", () => Effect.gen(function* () { assert.deepStrictEqual(yield* AtomicFile.readText(NESTED, { confineTo: ROOT }), { text: "inside", bom: false }); assert.deepStrictEqual(yield* AtomicFile.readText("/root/bom.md", { confineTo: ROOT }), { text: "\uFEFFx", bom: true, }); }).pipe(Effect.provide(MemoryFileSystem.layerWithPath({ ...seed, "/root/bom.md": bytes(...BOM, 0x78) }))), ); it.effect("an unnormalised target and root are judged after resolving", () => Effect.gen(function* () { assert.strictEqual( (yield* AtomicFile.readText("/root/./sub/config.json", { confineTo: "/root/" })).text, "inside", ); }).pipe(Effect.provide(layer)), ); it.effect("an absent target inside the root fails NotFound, not a refusal", () => Effect.gen(function* () { const error = yield* Effect.flip(AtomicFile.readText("/root/sub/absent.json", { confineTo: ROOT })); assert.strictEqual(error.reason._tag, "NotFound"); }).pipe(Effect.provide(layer)), ); it.effect("an absent root fails NotFound", () => Effect.gen(function* () { const error = yield* Effect.flip(AtomicFile.readText("/nowhere/a.json", { confineTo: "/nowhere" })); assert.strictEqual(error.reason._tag, "NotFound"); }).pipe(Effect.provide(layer)), ); it.effect( "a parent swapped for a link after the first check is refused by the re-check, its content not returned", () => Effect.gen(function* () { // The read itself went through the new link and got the outside file; the re-check refuses it. const error = yield* Effect.flip(AtomicFile.readText(NESTED, { confineTo: ROOT })); assertRefused(error, "a directory below confineTo is a symbolic link (/root/sub)"); const volume = yield* MemoryFileSystem.Volume; assert.strictEqual(volume.readLink("/root/sub"), "/outside"); }).pipe( Effect.provide( MemoryFileSystem.layerWithPath( { [NESTED]: "inside", "/outside/config.json": "secret" }, { faults: swapBeforeRead(NESTED, (fs) => Effect.andThen(fs.rename("/root/sub", "/root/moved"), fs.symlink("/outside", "/root/sub")), ), }, ), ), ), ); it.effect("a link swapped in at the target after the first check is refused by the re-check", () => Effect.gen(function* () { assertRefused( yield* Effect.flip(AtomicFile.readText(NESTED, { confineTo: ROOT })), "the target is a symbolic link", ); }).pipe( Effect.provide( MemoryFileSystem.layerWithPath( { ...seed, "/outside/config.json": "secret" }, { faults: swapBeforeRead(NESTED, (fs) => Effect.andThen(fs.remove(NESTED), fs.symlink(ESCAPE, NESTED))), }, ), ), ), ); it.effect("a non-string confineTo is a defect", () => Effect.gen(function* () { const exit = yield* Effect.exit(AtomicFile.readText(NESTED, { confineTo: 1 } as never)); assert.isTrue(Exit.isFailure(exit) && Exit.hasDies(exit) && !Exit.hasFails(exit)); }).pipe(Effect.provide(layer)), ); }); describe('AtomicFile.readText with links: "resolve"', () => { const ROOT = "/root"; const NESTED = "/root/sub/config.json"; const ESCAPE = "/outside/secret.json"; const seed: MemoryFileSystemSeed = { [ESCAPE]: "secret", "/outside/config.json": "outside config", "/rootling/secret.json": "sibling", [NESTED]: "inside", "/root/a/one.md": "one", "/root/c/alias.md": MemoryFileSystem.symlink("/root/a/one.md"), "/root/inner/real.json": "inner", "/root/alias": MemoryFileSystem.symlink("/root/inner"), "/root/linked.json": MemoryFileSystem.symlink(ESCAPE), "/root/escape": MemoryFileSystem.symlink("/outside"), "/root/dangling.json": MemoryFileSystem.symlink("/nowhere.json"), "/in-from-outside.json": MemoryFileSystem.symlink("/root/a/one.md"), "/bundle": MemoryFileSystem.symlink(ROOT), }; const layer = MemoryFileSystem.layerWithPath(seed); const resolve = (target: string, confineTo = ROOT) => AtomicFile.readText(target, { confineTo, links: "resolve" }); const assertRefused = (error: PlatformError.PlatformError, description: string) => { if (error.reason._tag === "BadArgument") return assert.fail("expected a SystemError"); assert.strictEqual(error.reason._tag, "PermissionDenied"); assert.strictEqual(error.reason.module, "AtomicFile"); assert.strictEqual(error.reason.method, "readText"); assert.strictEqual(error.reason.description, description); }; for (const [label, target, text] of [ ["a file link staying inside the root", "/root/c/alias.md", "one"], ["a directory link staying inside the root", "/root/alias/real.json", "inner"], ["a plain file", NESTED, "inside"], ["a link outside the root leading into it", "/in-from-outside.json", "one"], ] as const) { it.effect(`${label}: reads through the link`, () => Effect.gen(function* () { assert.deepStrictEqual(yield* resolve(target), { text, bom: false }); }).pipe(Effect.provide(layer)), ); } it.effect("the default mode refuses the same in-root link", () => Effect.gen(function* () { const error = yield* Effect.flip(AtomicFile.readText("/root/c/alias.md", { confineTo: ROOT })); assert.strictEqual(error.reason._tag, "PermissionDenied"); }).pipe(Effect.provide(layer)), ); it.effect("a symlinked root is judged by its real path", () => Effect.gen(function* () { assert.strictEqual((yield* resolve("/bundle/c/alias.md", "/bundle")).text, "one"); }).pipe(Effect.provide(layer)), ); for (const [label, target, real] of [ ["a file link leaving the root", "/root/linked.json", ESCAPE], ["a directory link leaving the root", "/root/escape/secret.json", ESCAPE], ["a .. escape", "/root/../outside/secret.json", ESCAPE], ["a sibling sharing the root's prefix", "/rootling/secret.json", "/rootling/secret.json"], ["the root itself", ROOT, ROOT], ] as const) { it.effect(`${label}: refused, naming where it resolves`, () => Effect.gen(function* () { assertRefused( yield* Effect.flip(resolve(target)), `the target resolves to ${real}, outside confineTo (${ROOT})`, ); }).pipe(Effect.provide(layer)), ); } it.effect("a dangling link fails NotFound, not a refusal", () => Effect.gen(function* () { const error = yield* Effect.flip(resolve("/root/dangling.json")); assert.strictEqual(error.reason._tag, "NotFound"); }).pipe(Effect.provide(layer)), ); it.effect("a parent swapped for a link leaving the root before the read is refused, its content not returned", () => Effect.gen(function* () { // The read went through the new link and got the outside file; the second resolve refuses it. assertRefused( yield* Effect.flip(resolve(NESTED)), `the target resolved to ${NESTED} for the read and to /outside/config.json after it`, ); }).pipe( Effect.provide( MemoryFileSystem.layerWithPath(seed, { faults: swapBeforeRead(NESTED, (fs) => Effect.andThen(fs.rename("/root/sub", "/root/moved"), fs.symlink("/outside", "/root/sub")), ), }), ), ), ); it.effect("a link retargeted between the resolve and the read is refused", () => Effect.gen(function* () { assertRefused( yield* Effect.flip(resolve("/root/c/alias.md")), `the target resolved to /root/a/one.md for the read and to ${ESCAPE} after it`, ); }).pipe( Effect.provide( MemoryFileSystem.layerWithPath(seed, { faults: swapBeforeRead("/root/a/one.md", (fs) => Effect.andThen(fs.remove("/root/c/alias.md"), fs.symlink(ESCAPE, "/root/c/alias.md")), ), }), ), ), ); for (const [label, options] of [ ['"resolve" without confineTo', { links: "resolve" }], ["an unknown links value", { confineTo: ROOT, links: "nope" }], ['links: "follow"', { confineTo: ROOT, links: "follow" }], ['links: "replace"', { confineTo: ROOT, links: "replace" }], ["a non-string confineTo", { confineTo: 1, links: "resolve" }], ] as const) { it.effect(`${label} is a defect`, () => Effect.gen(function* () { const exit = yield* Effect.exit(AtomicFile.readText(NESTED, options as never)); assert.isTrue(Exit.isFailure(exit) && Exit.hasDies(exit) && !Exit.hasFails(exit)); }).pipe(Effect.provide(layer)), ); } }); describe("AtomicFile.checkReadable", () => { const ROOT = "/root"; const NESTED = "/root/sub/config.json"; const ESCAPE = "/outside/secret.json"; const seed: MemoryFileSystemSeed = { [ESCAPE]: "secret", "/outside/config.json": "outside config", "/rootling/secret.json": "sibling", [NESTED]: "inside", "/root/a/one.md": "one", "/root/c/alias.md": MemoryFileSystem.symlink("/root/a/one.md"), "/root/inner/real.json": "inner", "/root/alias": MemoryFileSystem.symlink("/root/inner"), "/root/linked.json": MemoryFileSystem.symlink(ESCAPE), "/root/escape": MemoryFileSystem.symlink("/outside"), "/root/dangling.json": MemoryFileSystem.symlink("/nowhere.json"), "/root/X/sub": MemoryFileSystem.symlink("/outside"), "/root/d1": MemoryFileSystem.symlink("/root/X"), "/bundle": MemoryFileSystem.symlink(ROOT), }; const layer = MemoryFileSystem.layerWithPath(seed); /** The description of readText's refusal, or a failure when it read. */ const readRefusal = (target: string, options: { readonly confineTo: string; readonly links?: "resolve" }) => Effect.flip(AtomicFile.readText(target, options)).pipe( Effect.map((error) => (error.reason._tag === "BadArgument" ? undefined : error.reason.description)), ); // Unset links: checkConfined's answer exactly, and readText refuses with the same description. for (const target of [ ESCAPE, "/root/linked.json", "/root/alias/real.json", "/root/escape/secret.json", "/root/d1/sub/config.json", NESTED, ]) { it.effect(`unset links: ${target} answers as checkConfined does, and the read agrees`, () => Effect.gen(function* () { const verdict = yield* AtomicFile.checkReadable(target, { confineTo: ROOT }); assert.deepStrictEqual(verdict, yield* AtomicFile.checkConfined(target, { confineTo: ROOT })); if (verdict._tag === "Confined") { assert.strictEqual(verdict.path, target); assert.strictEqual((yield* AtomicFile.readText(target, { confineTo: ROOT })).text, "inside"); } else { assert.strictEqual(yield* readRefusal(target, { confineTo: ROOT }), verdict.description); } }).pipe(Effect.provide(layer)), ); } for (const [label, target, real] of [ ["a file link staying inside the root", "/root/c/alias.md", "/root/a/one.md"], ["a directory link staying inside the root", "/root/alias/real.json", "/root/inner/real.json"], ["a plain file", NESTED, NESTED], ] as const) { it.effect(`links: "resolve", ${label}: Confined at the real path the read reads`, () => Effect.gen(function* () { const verdict = yield* AtomicFile.checkReadable(target, { confineTo: ROOT, links: "resolve" }); assert.deepStrictEqual(verdict, { _tag: "Confined", path: real }); }).pipe(Effect.provide(layer)), ); } for (const [label, target, real] of [ ["a file link leaving the root", "/root/linked.json", ESCAPE], ["a directory link leaving the root", "/root/escape/secret.json", ESCAPE], ["a link under an in-root link leaving the root", "/root/d1/sub/config.json", "/outside/config.json"], ["a .. escape", "/root/../outside/secret.json", ESCAPE], ["a sibling sharing the root's prefix", "/rootling/secret.json", "/rootling/secret.json"], ["the root itself", ROOT, ROOT], ] as const) { it.effect(`links: "resolve", ${label}: resolves-outside, as the read refuses`, () => Effect.gen(function* () { const options = { confineTo: ROOT, links: "resolve" } as const; const description = `the target resolves to ${real}, outside confineTo (${ROOT})`; assert.deepStrictEqual(yield* AtomicFile.checkReadable(target, options), { _tag: "Refused", reason: "resolves-outside", description, path: target, root: ROOT, target: real, resolved: real, }); assert.strictEqual(yield* readRefusal(target, options), description); }).pipe(Effect.provide(layer)), ); } it.effect('links: "resolve" through a symlinked root reports the root\'s real path', () => Effect.gen(function* () { const verdict = yield* AtomicFile.checkReadable("/bundle/linked.json", { confineTo: "/bundle", links: "resolve", }); if (verdict._tag !== "Refused") return assert.fail(`expected a refusal, got ${verdict._tag}`); assert.strictEqual(verdict.root, ROOT); assert.strictEqual(verdict.resolved, ESCAPE); }).pipe(Effect.provide(layer)), ); it.effect('links: "resolve", a dangling link fails NotFound as the read does, not a refusal', () => Effect.gen(function* () { const error = yield* Effect.flip( AtomicFile.checkReadable("/root/dangling.json", { confineTo: ROOT, links: "resolve" }), ); assert.strictEqual(error.reason._tag, "NotFound"); }).pipe(Effect.provide(layer)), ); // The one refusal no check ahead of the read can answer: the target resolving differently after the read. it.effect('links: "resolve", a link retargeted during the read: the check said Confined, the read refuses', () => Effect.gen(function* () { const options = { confineTo: ROOT, links: "resolve" } as const; const verdict = yield* AtomicFile.checkReadable("/root/c/alias.md", options); assert.deepStrictEqual(verdict, { _tag: "Confined", path: "/root/a/one.md" }); assert.strictEqual( yield* readRefusal("/root/c/alias.md", options), `the target resolved to /root/a/one.md for the read and to ${ESCAPE} after it`, ); }).pipe( Effect.provide( MemoryFileSystem.layerWithPath(seed, { faults: swapBeforeRead("/root/a/one.md", (fs) => Effect.andThen(fs.remove("/root/c/alias.md"), fs.symlink(ESCAPE, "/root/c/alias.md")), ), }), ), ), ); it.effect("reads and writes nothing", () => Effect.gen(function* () { const volume = yield* MemoryFileSystem.Volume; const before = volume.snapshot(); yield* AtomicFile.checkReadable(NESTED, { confineTo: ROOT }); yield* AtomicFile.checkReadable("/root/linked.json", { confineTo: ROOT, links: "resolve" }); assert.deepStrictEqual(volume.snapshot(), before); }).pipe(Effect.provide(layer)), ); for (const [label, options] of [ ["a missing confineTo", {}], ['"resolve" without confineTo', { links: "resolve" }], ["an unknown links value", { confineTo: ROOT, links: "nope" }], ['links: "follow"', { confineTo: ROOT, links: "follow" }], ['links: "replace"', { confineTo: ROOT, links: "replace" }], ["a non-string confineTo", { confineTo: 1 }], ] as const) { it.effect(`${label} is a defect`, () => Effect.gen(function* () { const exit = yield* Effect.exit(AtomicFile.checkReadable(NESTED, options as never)); assert.isTrue(Exit.isFailure(exit) && Exit.hasDies(exit) && !Exit.hasFails(exit)); }).pipe(Effect.provide(layer)), ); } });